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
import Call main = runSystemDefault $ do linkPicture $ const $ return $ color blue $ circleOutline 240 stand
fumieval/call
examples/circle.hs
bsd-3-clause
113
0
11
23
41
19
22
4
1
{-# LANGUAGE ExistentialQuantification, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, TypeSynonymInstances, CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Core -- Copyright : (c) Spencer Janssen 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : not portable, uses cunning newtype deriving -- -- The 'X' monad, a state monad transformer over 'IO', for the window -- manager state, and support routines. -- ----------------------------------------------------------------------------- module XMonad.Core ( X, WindowSet, WindowSpace, WorkspaceId, ScreenId(..), ScreenDetail(..), XState(..), XConf(..), XConfig(..), LayoutClass(..), Layout(..), readsLayout, Typeable, Message, SomeMessage(..), fromMessage, LayoutMessages(..), StateExtension(..), ExtensionClass(..), runX, catchX, userCode, userCodeDef, io, catchIO, installSignalHandlers, uninstallSignalHandlers, withDisplay, withWindowSet, isRoot, runOnWorkspaces, getAtom, spawn, spawnPID, xfork, getXMonadDir, recompile, trace, whenJust, whenX, atom_WM_STATE, atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, atom_WM_TAKE_FOCUS, ManageHook, Query(..), runQuery ) where import XMonad.StackSet hiding (modify) import Prelude hiding ( catch ) import Codec.Binary.UTF8.String (encodeString) import Control.Exception.Extensible (catch, fromException, try, bracket, throw, finally, SomeException(..)) import Control.Applicative import Control.Monad.State import Control.Monad.Reader import System.FilePath import System.IO import System.Info import System.Posix.Process (executeFile, forkProcess, getAnyProcessStatus, createSession) import System.Posix.Signals import System.Posix.IO import System.Posix.Types (ProcessID) import System.Process import System.Directory import System.Exit import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras (Event) import Data.Typeable import Data.List ((\\)) import Data.Maybe (isJust,fromMaybe) import Data.Monoid import qualified Data.Map as M import qualified Data.Set as S -- | XState, the (mutable) window manager state. data XState = XState { windowset :: !WindowSet -- ^ workspace list , mapped :: !(S.Set Window) -- ^ the Set of mapped windows , waitingUnmap :: !(M.Map Window Int) -- ^ the number of expected UnmapEvents , dragging :: !(Maybe (Position -> Position -> X (), X ())) , numberlockMask :: !KeyMask -- ^ The numlock modifier , extensibleState :: !(M.Map String (Either String StateExtension)) -- ^ stores custom state information. -- -- The module "XMonad.Utils.ExtensibleState" in xmonad-contrib -- provides additional information and a simple interface for using this. } -- | XConf, the (read-only) window manager configuration. data XConf = XConf { display :: Display -- ^ the X11 display , config :: !(XConfig Layout) -- ^ initial user configuration , theRoot :: !Window -- ^ the root window , normalBorder :: !Pixel -- ^ border color of unfocused windows , focusedBorder :: !Pixel -- ^ border color of the focused window , keyActions :: !(M.Map (KeyMask, KeySym) (X ())) -- ^ a mapping of key presses to actions , buttonActions :: !(M.Map (KeyMask, Button) (Window -> X ())) -- ^ a mapping of button presses to actions , mouseFocused :: !Bool -- ^ was refocus caused by mouse action? , mousePosition :: !(Maybe (Position, Position)) -- ^ position of the mouse according to -- the event currently being processed , currentEvent :: !(Maybe Event) -- ^ event currently being processed } -- todo, better name data XConfig l = XConfig { normalBorderColor :: !String -- ^ Non focused windows border color. Default: \"#dddddd\" , focusedBorderColor :: !String -- ^ Focused windows border color. Default: \"#ff0000\" , terminal :: !String -- ^ The preferred terminal application. Default: \"xterm\" , layoutHook :: !(l Window) -- ^ The available layouts , manageHook :: !ManageHook -- ^ The action to run when a new window is opened , handleEventHook :: !(Event -> X All) -- ^ Handle an X event, returns (All True) if the default handler -- should also be run afterwards. mappend should be used for combining -- event hooks in most cases. , workspaces :: ![String] -- ^ The list of workspaces' names , modMask :: !KeyMask -- ^ the mod modifier , keys :: !(XConfig Layout -> M.Map (ButtonMask,KeySym) (X ())) -- ^ The key binding: a map from key presses and actions , mouseBindings :: !(XConfig Layout -> M.Map (ButtonMask, Button) (Window -> X ())) -- ^ The mouse bindings , borderWidth :: !Dimension -- ^ The border width , logHook :: !(X ()) -- ^ The action to perform when the windows set is changed , startupHook :: !(X ()) -- ^ The action to perform on startup , focusFollowsMouse :: !Bool -- ^ Whether window entry events can change focus } type WindowSet = StackSet WorkspaceId (Layout Window) Window ScreenId ScreenDetail type WindowSpace = Workspace WorkspaceId (Layout Window) Window -- | Virtual workspace indices type WorkspaceId = String -- | Physical screen indices newtype ScreenId = S Int deriving (Eq,Ord,Show,Read,Enum,Num,Integral,Real) -- | The 'Rectangle' with screen dimensions data ScreenDetail = SD { screenRect :: !Rectangle } deriving (Eq,Show, Read) ------------------------------------------------------------------------ -- | The X monad, 'ReaderT' and 'StateT' transformers over 'IO' -- encapsulating the window manager configuration and state, -- respectively. -- -- Dynamic components may be retrieved with 'get', static components -- with 'ask'. With newtype deriving we get readers and state monads -- instantiated on 'XConf' and 'XState' automatically. -- newtype X a = X (ReaderT XConf (StateT XState IO) a) deriving (Functor, Monad, MonadIO, MonadState XState, MonadReader XConf, Typeable) instance Applicative X where pure = return (<*>) = ap instance (Monoid a) => Monoid (X a) where mempty = return mempty mappend = liftM2 mappend type ManageHook = Query (Endo WindowSet) newtype Query a = Query (ReaderT Window X a) deriving (Functor, Monad, MonadReader Window, MonadIO) runQuery :: Query a -> Window -> X a runQuery (Query m) w = runReaderT m w instance Monoid a => Monoid (Query a) where mempty = return mempty mappend = liftM2 mappend -- | Run the 'X' monad, given a chunk of 'X' monad code, and an initial state -- Return the result, and final state runX :: XConf -> XState -> X a -> IO (a, XState) runX c st (X a) = runStateT (runReaderT a c) st -- | Run in the 'X' monad, and in case of exception, and catch it and log it -- to stderr, and run the error case. catchX :: X a -> X a -> X a catchX job errcase = do st <- get c <- ask (a, s') <- io $ runX c st job `catch` \e -> case fromException e of Just x -> throw e `const` (x `asTypeOf` ExitSuccess) _ -> do hPrint stderr e; runX c st errcase put s' return a -- | Execute the argument, catching all exceptions. Either this function or -- 'catchX' should be used at all callsites of user customized code. userCode :: X a -> X (Maybe a) userCode a = catchX (Just `liftM` a) (return Nothing) -- | Same as userCode but with a default argument to return instead of using -- Maybe, provided for convenience. userCodeDef :: a -> X a -> X a userCodeDef def a = fromMaybe def `liftM` userCode a -- --------------------------------------------------------------------- -- Convenient wrappers to state -- | Run a monad action with the current display settings withDisplay :: (Display -> X a) -> X a withDisplay f = asks display >>= f -- | Run a monadic action with the current stack set withWindowSet :: (WindowSet -> X a) -> X a withWindowSet f = gets windowset >>= f -- | True if the given window is the root window isRoot :: Window -> X Bool isRoot w = (w==) <$> asks theRoot -- | Wrapper for the common case of atom internment getAtom :: String -> X Atom getAtom str = withDisplay $ \dpy -> io $ internAtom dpy str False -- | Common non-predefined atoms atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, atom_WM_STATE, atom_WM_TAKE_FOCUS :: X Atom atom_WM_PROTOCOLS = getAtom "WM_PROTOCOLS" atom_WM_DELETE_WINDOW = getAtom "WM_DELETE_WINDOW" atom_WM_STATE = getAtom "WM_STATE" atom_WM_TAKE_FOCUS = getAtom "WM_TAKE_FOCUS" ------------------------------------------------------------------------ -- LayoutClass handling. See particular instances in Operations.hs -- | An existential type that can hold any object that is in 'Read' -- and 'LayoutClass'. data Layout a = forall l. (LayoutClass l a, Read (l a)) => Layout (l a) -- | Using the 'Layout' as a witness, parse existentially wrapped windows -- from a 'String'. readsLayout :: Layout a -> String -> [(Layout a, String)] readsLayout (Layout l) s = [(Layout (asTypeOf x l), rs) | (x, rs) <- reads s] -- | Every layout must be an instance of 'LayoutClass', which defines -- the basic layout operations along with a sensible default for each. -- -- Minimal complete definition: -- -- * 'runLayout' || (('doLayout' || 'pureLayout') && 'emptyLayout'), and -- -- * 'handleMessage' || 'pureMessage' -- -- You should also strongly consider implementing 'description', -- although it is not required. -- -- Note that any code which /uses/ 'LayoutClass' methods should only -- ever call 'runLayout', 'handleMessage', and 'description'! In -- other words, the only calls to 'doLayout', 'pureMessage', and other -- such methods should be from the default implementations of -- 'runLayout', 'handleMessage', and so on. This ensures that the -- proper methods will be used, regardless of the particular methods -- that any 'LayoutClass' instance chooses to define. class Show (layout a) => LayoutClass layout a where -- | By default, 'runLayout' calls 'doLayout' if there are any -- windows to be laid out, and 'emptyLayout' otherwise. Most -- instances of 'LayoutClass' probably do not need to implement -- 'runLayout'; it is only useful for layouts which wish to make -- use of more of the 'Workspace' information (for example, -- "XMonad.Layout.PerWorkspace"). runLayout :: Workspace WorkspaceId (layout a) a -> Rectangle -> X ([(a, Rectangle)], Maybe (layout a)) runLayout (Workspace _ l ms) r = maybe (emptyLayout l r) (doLayout l r) ms -- | Given a 'Rectangle' in which to place the windows, and a 'Stack' -- of windows, return a list of windows and their corresponding -- Rectangles. If an element is not given a Rectangle by -- 'doLayout', then it is not shown on screen. The order of -- windows in this list should be the desired stacking order. -- -- Also possibly return a modified layout (by returning @Just -- newLayout@), if this layout needs to be modified (e.g. if it -- keeps track of some sort of state). Return @Nothing@ if the -- layout does not need to be modified. -- -- Layouts which do not need access to the 'X' monad ('IO', window -- manager state, or configuration) and do not keep track of their -- own state should implement 'pureLayout' instead of 'doLayout'. doLayout :: layout a -> Rectangle -> Stack a -> X ([(a, Rectangle)], Maybe (layout a)) doLayout l r s = return (pureLayout l r s, Nothing) -- | This is a pure version of 'doLayout', for cases where we -- don't need access to the 'X' monad to determine how to lay out -- the windows, and we don't need to modify the layout itself. pureLayout :: layout a -> Rectangle -> Stack a -> [(a, Rectangle)] pureLayout _ r s = [(focus s, r)] -- | 'emptyLayout' is called when there are no windows. emptyLayout :: layout a -> Rectangle -> X ([(a, Rectangle)], Maybe (layout a)) emptyLayout _ _ = return ([], Nothing) -- | 'handleMessage' performs message handling. If -- 'handleMessage' returns @Nothing@, then the layout did not -- respond to the message and the screen is not refreshed. -- Otherwise, 'handleMessage' returns an updated layout and the -- screen is refreshed. -- -- Layouts which do not need access to the 'X' monad to decide how -- to handle messages should implement 'pureMessage' instead of -- 'handleMessage' (this restricts the risk of error, and makes -- testing much easier). handleMessage :: layout a -> SomeMessage -> X (Maybe (layout a)) handleMessage l = return . pureMessage l -- | Respond to a message by (possibly) changing our layout, but -- taking no other action. If the layout changes, the screen will -- be refreshed. pureMessage :: layout a -> SomeMessage -> Maybe (layout a) pureMessage _ _ = Nothing -- | This should be a human-readable string that is used when -- selecting layouts by name. The default implementation is -- 'show', which is in some cases a poor default. description :: layout a -> String description = show instance LayoutClass Layout Window where runLayout (Workspace i (Layout l) ms) r = fmap (fmap Layout) `fmap` runLayout (Workspace i l ms) r doLayout (Layout l) r s = fmap (fmap Layout) `fmap` doLayout l r s emptyLayout (Layout l) r = fmap (fmap Layout) `fmap` emptyLayout l r handleMessage (Layout l) = fmap (fmap Layout) . handleMessage l description (Layout l) = description l instance Show (Layout a) where show (Layout l) = show l -- | Based on ideas in /An Extensible Dynamically-Typed Hierarchy of -- Exceptions/, Simon Marlow, 2006. Use extensible messages to the -- 'handleMessage' handler. -- -- User-extensible messages must be a member of this class. -- class Typeable a => Message a -- | -- A wrapped value of some type in the 'Message' class. -- data SomeMessage = forall a. Message a => SomeMessage a -- | -- And now, unwrap a given, unknown 'Message' type, performing a (dynamic) -- type check on the result. -- fromMessage :: Message m => SomeMessage -> Maybe m fromMessage (SomeMessage m) = cast m -- X Events are valid Messages. instance Message Event -- | 'LayoutMessages' are core messages that all layouts (especially stateful -- layouts) should consider handling. data LayoutMessages = Hide -- ^ sent when a layout becomes non-visible | ReleaseResources -- ^ sent when xmonad is exiting or restarting deriving (Typeable, Eq) instance Message LayoutMessages -- --------------------------------------------------------------------- -- Extensible state -- -- | Every module must make the data it wants to store -- an instance of this class. -- -- Minimal complete definition: initialValue class Typeable a => ExtensionClass a where -- | Defines an initial value for the state extension initialValue :: a -- | Specifies whether the state extension should be -- persistent. Setting this method to 'PersistentExtension' -- will make the stored data survive restarts, but -- requires a to be an instance of Read and Show. -- -- It defaults to 'StateExtension', i.e. no persistence. extensionType :: a -> StateExtension extensionType = StateExtension -- | Existential type to store a state extension. data StateExtension = forall a. ExtensionClass a => StateExtension a -- ^ Non-persistent state extension | forall a. (Read a, Show a, ExtensionClass a) => PersistentExtension a -- ^ Persistent extension -- --------------------------------------------------------------------- -- | General utilities -- -- Lift an 'IO' action into the 'X' monad io :: MonadIO m => IO a -> m a io = liftIO -- | Lift an 'IO' action into the 'X' monad. If the action results in an 'IO' -- exception, log the exception to stderr and continue normal execution. catchIO :: MonadIO m => IO () -> m () catchIO f = io (f `catch` \(SomeException e) -> hPrint stderr e >> hFlush stderr) -- | spawn. Launch an external application. Specifically, it double-forks and -- runs the 'String' you pass as a command to \/bin\/sh. -- -- Note this function assumes your locale uses utf8. spawn :: MonadIO m => String -> m () spawn x = spawnPID x >> return () -- | Like 'spawn', but returns the 'ProcessID' of the launched application spawnPID :: MonadIO m => String -> m ProcessID spawnPID x = xfork $ executeFile "/bin/sh" False ["-c", encodeString x] Nothing -- | A replacement for 'forkProcess' which resets default signal handlers. xfork :: MonadIO m => IO () -> m ProcessID xfork x = io . forkProcess . finally nullStdin $ do uninstallSignalHandlers createSession x where nullStdin = do fd <- openFd "/dev/null" ReadOnly Nothing defaultFileFlags dupTo fd stdInput closeFd fd -- | This is basically a map function, running a function in the 'X' monad on -- each workspace with the output of that function being the modified workspace. runOnWorkspaces :: (WindowSpace -> X WindowSpace) -> X () runOnWorkspaces job = do ws <- gets windowset h <- mapM job $ hidden ws c:v <- mapM (\s -> (\w -> s { workspace = w}) <$> job (workspace s)) $ current ws : visible ws modify $ \s -> s { windowset = ws { current = c, visible = v, hidden = h } } -- | Return the path to @~\/.xmonad@. getXMonadDir :: MonadIO m => m String getXMonadDir = io $ getAppUserDataDirectory "xmonad" -- | 'recompile force', recompile @~\/.xmonad\/xmonad.hs@ when any of the -- following apply: -- -- * force is 'True' -- -- * the xmonad executable does not exist -- -- * the xmonad executable is older than xmonad.hs or any file in -- ~\/.xmonad\/lib -- -- The -i flag is used to restrict recompilation to the xmonad.hs file only, -- and any files in the ~\/.xmonad\/lib directory. -- -- Compilation errors (if any) are logged to ~\/.xmonad\/xmonad.errors. If -- GHC indicates failure with a non-zero exit code, an xmessage displaying -- that file is spawned. -- -- 'False' is returned if there are compilation errors. -- recompile :: MonadIO m => Bool -> m Bool recompile force = io $ do dir <- getXMonadDir let binn = "xmonad-"++arch++"-"++os bin = dir </> binn base = dir </> "xmonad" err = base ++ ".errors" src = base ++ ".hs" lib = dir </> "lib" libTs <- mapM getModTime . Prelude.filter isSource =<< allFiles lib srcT <- getModTime src binT <- getModTime bin if force || any (binT <) (srcT : libTs) then do -- temporarily disable SIGCHLD ignoring: uninstallSignalHandlers status <- bracket (openFile err WriteMode) hClose $ \h -> waitForProcess =<< runProcess "ghc" ["--make", "xmonad.hs", "-i", "-ilib", "-fforce-recomp", "-v0", "-o",binn] (Just dir) Nothing Nothing Nothing (Just h) -- re-enable SIGCHLD: installSignalHandlers -- now, if it fails, run xmessage to let the user know: when (status /= ExitSuccess) $ do ghcErr <- readFile err let msg = unlines $ ["Error detected while loading xmonad configuration file: " ++ src] ++ lines (if null ghcErr then show status else ghcErr) ++ ["","Please check the file for errors."] -- nb, the ordering of printing, then forking, is crucial due to -- lazy evaluation hPutStrLn stderr msg forkProcess $ executeFile "xmessage" True ["-default", "okay", msg] Nothing return () return (status == ExitSuccess) else return True where getModTime f = catch (Just <$> getModificationTime f) (\(SomeException _) -> return Nothing) isSource = flip elem [".hs",".lhs",".hsc"] allFiles t = do let prep = map (t</>) . Prelude.filter (`notElem` [".",".."]) cs <- prep <$> catch (getDirectoryContents t) (\(SomeException _) -> return []) ds <- filterM doesDirectoryExist cs concat . ((cs \\ ds):) <$> mapM allFiles ds -- | Conditionally run an action, using a @Maybe a@ to decide. whenJust :: Monad m => Maybe a -> (a -> m ()) -> m () whenJust mg f = maybe (return ()) f mg -- | Conditionally run an action, using a 'X' event to decide whenX :: X Bool -> X () -> X () whenX a f = a >>= \b -> when b f -- | A 'trace' for the 'X' monad. Logs a string to stderr. The result may -- be found in your .xsession-errors file trace :: MonadIO m => String -> m () trace = io . hPutStrLn stderr -- | Ignore SIGPIPE to avoid termination when a pipe is full, and SIGCHLD to -- avoid zombie processes, and clean up any extant zombie processes. installSignalHandlers :: MonadIO m => m () installSignalHandlers = io $ do installHandler openEndedPipe Ignore Nothing installHandler sigCHLD Ignore Nothing (try :: IO a -> IO (Either SomeException a)) $ fix $ \more -> do x <- getAnyProcessStatus False False when (isJust x) more return () uninstallSignalHandlers :: MonadIO m => m () uninstallSignalHandlers = io $ do installHandler openEndedPipe Default Nothing installHandler sigCHLD Default Nothing return ()
csstaub/xmonad
XMonad/Core.hs
bsd-3-clause
22,214
0
22
5,439
4,331
2,371
1,960
-1
-1
module Main where newtype CmdLineP s a = CmdLineP { runCmdLine :: s -> (a, s) } instance Monad (CmdLineP s) where return a = CmdLineP $ \s -> (a, s) m >>= k = CmdLineP $ \s -> let (a, s') = runCmdLine m s in runCmdLine (k a) s' dynamic_flags :: [Flag (CmdLineP DynFlags)] dynamic_flags = [] data DynFlags = DynFlags { field1 :: String, field2 :: String, field3 :: Bool } data Flag m = Flag { flagName :: String, flagOptKind :: OptKind m } data OptKind m = NoArg (m ()) | HasArg (String -> m ())
dterei/Scraps
haskell/twoTypeArgs.hs
bsd-3-clause
575
0
12
181
231
130
101
19
1
import qualified Data.Map as M data StepState = StepState { minDigit :: Int, maxDigit :: Int, lastDigit :: Int } deriving (Show, Eq, Ord) up, down :: StepState -> StepState up (StepState a b c) = StepState a (max b $ c + 1) (c + 1) down (StepState a b c) = StepState (min a $ (c - 1)) b (c - 1) next :: M.Map StepState Integer -> M.Map StepState Integer next m = M.unionWith (+) (next' up m) (next' down m) where next' f = M.filterWithKey (\(StepState _ _ c) _ -> c >= 0 && c <= 9) . M.mapKeysWith (+) f count :: M.Map StepState Integer -> Integer count = M.fold (+) 0 . M.filterWithKey (\(StepState a b _) _ -> a == 0 && b == 9) solve :: Int -> Integer solve n = sum . map count . take n . iterate next . M.fromList $ [(StepState d d d, 1) | d <- [1..9]] main = do print $ solve 40
EdisonAlgorithms/ProjectEuler
vol4/178.hs
mit
880
0
13
267
438
229
209
18
1
import Control.Monad import Distribution.Simple import Distribution.Simple.BuildPaths (autogenModulesDir) import Distribution.Simple.InstallDirs as I import Distribution.Simple.LocalBuildInfo as L import qualified Distribution.Simple.Setup as S import qualified Distribution.Simple.Program as P import Distribution.Simple.Utils (createDirectoryIfMissingVerbose, rewriteFile) import Distribution.PackageDescription import Distribution.Text import Distribution.Verbosity import System.FilePath ((</>), isAbsolute) import System.Directory import qualified System.FilePath.Posix as Px make :: Verbosity -> [String] -> IO () make verbosity = P.runProgramInvocation verbosity . P.simpleProgramInvocation "make" -- ---------------------------------------------------------------------------- -- Main main :: IO () main = defaultMainWithHooks $ simpleUserHooks { postClean = piccoloClean , postBuild = piccoloBuild , postCopy = \_ flags pkg local -> piccoloInstall (S.fromFlag $ S.copyVerbosity flags) (S.fromFlag $ S.copyDest flags) pkg local , postInst = \_ flags pkg local -> piccoloInstall (S.fromFlag $ S.installVerbosity flags) NoCopyDest pkg local } -- ---------------------------------------------------------------------------- -- Clean piccoloClean :: Args -> S.CleanFlags -> PackageDescription -> () -> IO () piccoloClean _ flags _ _ = do let verbosity = S.fromFlag $ S.cleanVerbosity flags make verbosity [ "-C", "runtime", "clean" ] -- ---------------------------------------------------------------------------- -- Build piccoloBuild :: Args -> S.BuildFlags -> PackageDescription -> LocalBuildInfo -> IO () piccoloBuild _ flags _ local = do let verbosity = S.fromFlag $ S.buildVerbosity flags make verbosity [ "-C", "runtime", "build" ] -- ---------------------------------------------------------------------------- -- Copy/Install piccoloInstall :: Verbosity -> CopyDest -> PackageDescription -> LocalBuildInfo -> IO () piccoloInstall verbosity copy pkg local = do let target = datadir $ L.absoluteInstallDirs pkg local copy target' = target </> "runtime" putStrLn $ "Installing runtime in " ++ target' make verbosity [ "-C", "runtime", "install", "TARGET=" ++ target' ]
fredokun/piccolo
Setup.hs
gpl-3.0
2,498
0
13
567
558
306
252
53
1
main :: (Int,Int,Int,Int,Int,Int,Int,Char,String,Int,Maybe Char) main = undefined
roberth/uu-helium
test/staticerrors/TupleTooBig3.hs
gpl-3.0
84
0
6
9
47
29
18
2
1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} -- TODO: clean up name shadowing {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- @NOCOMMIT module Pontarius.E2E.SMP where import Control.Monad.Except import Control.Monad.Free import Control.Monad.Reader import Control.Monad.State import qualified Crypto.Hash.SHA256 as SHA256 import Crypto.Number.ModArithmetic as Mod import qualified Crypto.Random as CRandom import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.Serialize as Serialize import Data.Text (Text) import qualified Data.Text.Encoding as Text import Data.Word import Pontarius.E2E.Monad import Pontarius.E2E.Types import Pontarius.E2E.Helpers import Pontarius.E2E.Serialize smpHash :: Word8 -> Integer -> Maybe Integer -> Integer smpHash v b1 b2 = rollInteger . BS.unpack . SHA256.hash . Serialize.runPut $ do Serialize.putWord8 v putMPI b1 case b2 of Nothing -> return () Just b2' -> putMPI b2' mkSmpExponent :: (CRandom.CPRG g, MonadRandom g m, Functor m) => m Integer mkSmpExponent = randomIntegerBytes 192 mkSecret :: (MonadReader E2EGlobals m, MonadState E2EState m) => ((PubKey, PubKey) -> (PubKey, PubKey)) -> ByteString -> m Integer mkSecret perm uSecret = do ourKey <- asks pubKey Just theirKey <- gets theirPubKey Just s <- gets ssid let (iKey, rKey) = perm (ourKey, theirKey) sBytes = Serialize.runPut $ do Serialize.putWord8 0x01 Serialize.putByteString $ fingerPrint iKey Serialize.putByteString $ fingerPrint rKey Serialize.putByteString s Serialize.putByteString uSecret return . rollInteger . BS.unpack $ SHA256.hash sBytes where fingerPrint = SHA256.hash . encodePubkey getQ :: MonadReader E2EGlobals m => m Integer getQ = do p <- prime return $ (p - 1) `div` 2 sendSmpMessage :: SmpMessage -> SMP () sendSmpMessage msg = lift . lift . lift $ Free (SendSmpMessage msg (return ())) recvSmpMessage :: Int -> SMP SmpMessage recvSmpMessage tp = lift . lift . lift $ Free (RecvSmpMessage tp return) rangeGuard :: (MonadError E2EError m, MonadReader E2EGlobals m) => String -> Integer -> m () rangeGuard name x = do p <- prime protocolGuard ValueRange name $ 2 <= x && x <= (p - 2) hashGuard :: MonadError E2EError m => String -> Integer -> Word8 -> Integer -> Maybe Integer -> m () hashGuard name l b r1 r2 = protocolGuard HashMismatch name $ l == smpHash b r1 r2 -- smp1 :: CRandom.CPRG g => Integer -> Smp g Bool smp1 :: Maybe Text -> Text -> (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) -> SMP Bool smp1 mbQuestion x' (a2, a3, r2, r3, r4, r5, r6, r7) = do p <- prime q <- getQ x <- mkSecret id (Text.encodeUtf8 x') let infixr 8 ^. b ^. e = Mod.exponantiation_rtl_binary b e p infixr 7 *. l *. r = (l * r) `mod` p infixl 7 /. l /. r = case inverse r p of Nothing -> error $ "could not invert " ++ show r Just r' -> l *. r' -- [a2, a3, r2, r3] <- replicateM 4 mkSmpExponent let g2a = 2 ^. a2 g3a = 2 ^. a3 c2 = smpHash 1 (2 ^. r2) Nothing d2 = (r2 - a2*c2) `mod` q c3 = smpHash 2 (2 ^. r3) Nothing d3 = (r3 - a3*c3) `mod` q sendSmpMessage $ SmpMessage1 mbQuestion g2a c2 d2 g3a c3 d3 ---------------------------------------------------------------------------- SmpMessage2 g2b' c2' d2' g3b' c3' d3' pb' qb' cp' d5' d6' <- recvSmpMessage 2 rangeGuard "alice g2b" g2b' rangeGuard "alice g3b" g3b' rangeGuard "alice pb" pb' rangeGuard "alice qb" qb' let g2 = g2b' ^. a2 g3 = g3b' ^. a3 hashGuard "alice c2" c2' 3 (2 ^. d2' *. g2b' ^. c2') Nothing hashGuard "alice c3" c3' 4 (2 ^. d3' *. g3b' ^. c3') Nothing -- TODO: fix and reinstate hashGuard "alice cp" cp' 5 (g3 ^. d5' *. pb' ^. cp') (Just $ 2 ^. d5' *. g2 ^. d6' *. qb' ^. cp') -- [r4, r5, r6, r7] <- replicateM 4 mkSmpExponent let pa = g3 ^. r4 qa = 2 ^. r4 *. g2 ^. x cp = smpHash 6 (g3 ^. r5) $ Just (2 ^. r5 *. g2 ^. r6) d5 = (r5 - r4 * cp) `mod` q d6 = (r6 - x * cp) `mod` q ra = (qa /. qb') ^. a3 cr = smpHash 7 (2 ^. r7) (Just $ (qa /. qb') ^. r7) d7 = (r7 - a3 * cr) `mod` q sendSmpMessage $ SmpMessage3 pa qa cp d5 d6 ra cr d7 ------------------------------------------------- SmpMessage4 rb' cr' d7' <- recvSmpMessage 4 rangeGuard "alice rb" rb' -- TODO: fix and reinstate hashGuard "alice cr" cr' 8 (2 ^. d7' *. g3b' ^. cr') (Just $ (qa /. qb') ^. d7' *. rb' ^. cr') return $! (pa /. pb') == rb' ^. a3 smp2 :: Text -> (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) -> SmpMessage -> SMP Bool smp2 y' (b2, b3, r2, r3, r4, r5, r6, r7) msg1 = do p <- prime q <- getQ y <- mkSecret (\(x,y) -> (y,x)) (Text.encodeUtf8 y') let infixr 8 ^. b ^. e = Mod.exponantiation_rtl_binary b e p infixr 7 *. x *. y = mulmod x y p mulmod x' y' p = (x' * y') `mod` p infixl 7 /. x /. y = case inverse y p of Nothing -> error $ "could not invert " ++ show y Just y' -> x *. y' let SmpMessage1 _ g2a' c2' d2' g3a' c3' d3' = msg1 rangeGuard "bob g2a'" g2a' rangeGuard "bob gaa'" g3a' hashGuard "bob c2'" c2' 1 (2 ^. d2' *. g2a' ^. c2') Nothing hashGuard "bob c3'" c3' 2 (2 ^. d3' *. g3a' ^. c3') Nothing -- [b2, b3, r2, r3, r4, r5, r6] <- replicateM 7 mkSmpExponent let g2b = 2 ^. b2 g3b = 2 ^. b3 c2 = smpHash 3 (2 ^. r2) Nothing d2 = (r2 - b2 * c2) `mod` q c3 = smpHash 4 (2 ^. r3) Nothing d3 = (r3 - b3 * c3) `mod` q g2 = g2a' ^. b2 g3 = g3a' ^. b3 pb = g3 ^. r4 qb = 2 ^. r4 *. g2 ^. y cp = smpHash 5 (g3 ^. r5) (Just $ (2 ^. r5 *. g2 ^. r6)) d5 = (r5 - r4 * cp) `mod` q d6 = (r6 - y * cp) `mod` q sendSmpMessage $ SmpMessage2 g2b c2 d2 g3b c3 d3 pb qb cp d5 d6 --------------------------------------------------------------- SmpMessage3 pa' qa' cp' d5' d6' ra' cr' d7' <- recvSmpMessage 3 rangeGuard "bob pa'" pa' rangeGuard "bob qa'" qa' rangeGuard "bob ra'" ra' hashGuard "bob cp" cp' 6 (g3 ^. d5' *. pa' ^. cp') (Just $ 2 ^. d5' *. g2 ^. d6' *. qa' ^. cp') hashGuard "bob cr" cr' 7 (2 ^. d7' *. g3a' ^. cr' ) (Just $ (qa' /. qb) ^. d7' *. ra' ^. cr' ) -- r7 <- mkSmpExponent let rb = (qa' /. qb) ^. b3 cr = smpHash 8 (2 ^. r7) (Just $ (qa' /. qb) ^. r7) d7 = (r7 - b3 * cr) `mod` q hashGuard "bob cr" cr 8 (2 ^. d7 *. g3b ^. cr) (Just $ (qa' /. qb) ^. d7 *. rb ^. cr) sendSmpMessage $ SmpMessage4 rb cr d7 ------------------------ let rab = ra' ^. b3 return $! (pa' /. pb) == rab
Philonous/pontarius-xmpp-e2e
source/Pontarius/E2E/SMP.hs
apache-2.0
7,446
0
16
2,386
2,654
1,369
1,285
178
2
{-# LANGUAGE CPP, GADTs #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- ---------------------------------------------------------------------------- -- | Handle conversion of CmmProc to LLVM code. -- module LlvmCodeGen.CodeGen ( genLlvmProc ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import LlvmCodeGen.Regs import BlockId import CodeGen.Platform ( activeStgRegs, callerSaves ) import CLabel import Cmm import PprCmm import CmmUtils import CmmSwitch import Hoopl import DynFlags import FastString import ForeignCall import Outputable hiding (panic, pprPanic) import qualified Outputable import Platform import OrdList import UniqSupply import Unique import Util import Control.Monad.Trans.Class import Control.Monad.Trans.Writer #if __GLASGOW_HASKELL__ > 710 import Data.Semigroup ( Semigroup ) import qualified Data.Semigroup as Semigroup #endif import Data.List ( nub ) import Data.Maybe ( catMaybes ) type Atomic = Bool type LlvmStatements = OrdList LlvmStatement -- ----------------------------------------------------------------------------- -- | Top-level of the LLVM proc Code generator -- genLlvmProc :: RawCmmDecl -> LlvmM [LlvmCmmDecl] genLlvmProc (CmmProc infos lbl live graph) = do let blocks = toBlockListEntryFirstFalseFallthrough graph (lmblocks, lmdata) <- basicBlocksCodeGen live blocks let info = mapLookup (g_entry graph) infos proc = CmmProc info lbl live (ListGraph lmblocks) return (proc:lmdata) genLlvmProc _ = panic "genLlvmProc: case that shouldn't reach here!" -- ----------------------------------------------------------------------------- -- * Block code generation -- -- | Generate code for a list of blocks that make up a complete -- procedure. The first block in the list is exepected to be the entry -- point and will get the prologue. basicBlocksCodeGen :: LiveGlobalRegs -> [CmmBlock] -> LlvmM ([LlvmBasicBlock], [LlvmCmmDecl]) basicBlocksCodeGen _ [] = panic "no entry block!" basicBlocksCodeGen live (entryBlock:cmmBlocks) = do (prologue, prologueTops) <- funPrologue live (entryBlock:cmmBlocks) -- Generate code (BasicBlock bid entry, entryTops) <- basicBlockCodeGen entryBlock (blocks, topss) <- fmap unzip $ mapM basicBlockCodeGen cmmBlocks -- Compose let entryBlock = BasicBlock bid (fromOL prologue ++ entry) return (entryBlock : blocks, prologueTops ++ entryTops ++ concat topss) -- | Generate code for one block basicBlockCodeGen :: CmmBlock -> LlvmM ( LlvmBasicBlock, [LlvmCmmDecl] ) basicBlockCodeGen block = do let (_, nodes, tail) = blockSplit block id = entryLabel block (mid_instrs, top) <- stmtsToInstrs $ blockToList nodes (tail_instrs, top') <- stmtToInstrs tail let instrs = fromOL (mid_instrs `appOL` tail_instrs) return (BasicBlock id instrs, top' ++ top) -- ----------------------------------------------------------------------------- -- * CmmNode code generation -- -- A statement conversion return data. -- * LlvmStatements: The compiled LLVM statements. -- * LlvmCmmDecl: Any global data needed. type StmtData = (LlvmStatements, [LlvmCmmDecl]) -- | Convert a list of CmmNode's to LlvmStatement's stmtsToInstrs :: [CmmNode e x] -> LlvmM StmtData stmtsToInstrs stmts = do (instrss, topss) <- fmap unzip $ mapM stmtToInstrs stmts return (concatOL instrss, concat topss) -- | Convert a CmmStmt to a list of LlvmStatement's stmtToInstrs :: CmmNode e x -> LlvmM StmtData stmtToInstrs stmt = case stmt of CmmComment _ -> return (nilOL, []) -- nuke comments CmmTick _ -> return (nilOL, []) CmmUnwind {} -> return (nilOL, []) CmmAssign reg src -> genAssign reg src CmmStore addr src -> genStore addr src CmmBranch id -> genBranch id CmmCondBranch arg true false likely -> genCondBranch arg true false likely CmmSwitch arg ids -> genSwitch arg ids -- Foreign Call CmmUnsafeForeignCall target res args -> genCall target res args -- Tail call CmmCall { cml_target = arg, cml_args_regs = live } -> genJump arg live _ -> panic "Llvm.CodeGen.stmtToInstrs" -- | Wrapper function to declare an instrinct function by function type getInstrinct2 :: LMString -> LlvmType -> LlvmM ExprData getInstrinct2 fname fty@(LMFunction funSig) = do let fv = LMGlobalVar fname fty (funcLinkage funSig) Nothing Nothing Constant fn <- funLookup fname tops <- case fn of Just _ -> return [] Nothing -> do funInsert fname fty un <- getUniqueM let lbl = mkAsmTempLabel un return [CmmData (Section Data lbl) [([],[fty])]] return (fv, nilOL, tops) getInstrinct2 _ _ = error "getInstrinct2: Non-function type!" -- | Declares an instrinct function by return and parameter types getInstrinct :: LMString -> LlvmType -> [LlvmType] -> LlvmM ExprData getInstrinct fname retTy parTys = let funSig = LlvmFunctionDecl fname ExternallyVisible CC_Ccc retTy FixedArgs (tysToParams parTys) Nothing fty = LMFunction funSig in getInstrinct2 fname fty -- | Memory barrier instruction for LLVM >= 3.0 barrier :: LlvmM StmtData barrier = do let s = Fence False SyncSeqCst return (unitOL s, []) -- | Foreign Calls genCall :: ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData -- Write barrier needs to be handled specially as it is implemented as an LLVM -- intrinsic function. genCall (PrimTarget MO_WriteBarrier) _ _ = do platform <- getLlvmPlatform if platformArch platform `elem` [ArchX86, ArchX86_64, ArchSPARC] then return (nilOL, []) else barrier genCall (PrimTarget MO_Touch) _ _ = return (nilOL, []) genCall (PrimTarget (MO_UF_Conv w)) [dst] [e] = runStmtsDecls $ do dstV <- getCmmRegW (CmmLocal dst) let ty = cmmToLlvmType $ localRegType dst width = widthToLlvmFloat w castV <- lift $ mkLocalVar ty ve <- exprToVarW e statement $ Assignment castV $ Cast LM_Uitofp ve width statement $ Store castV dstV genCall (PrimTarget (MO_UF_Conv _)) [_] args = panic $ "genCall: Too many arguments to MO_UF_Conv. " ++ "Can only handle 1, given" ++ show (length args) ++ "." -- Handle prefetching data genCall t@(PrimTarget (MO_Prefetch_Data localityInt)) [] args | 0 <= localityInt && localityInt <= 3 = runStmtsDecls $ do let argTy = [i8Ptr, i32, i32, i32] funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints' = zip args arg_hints argVars <- arg_varsW args_hints' ([], nilOL, []) fptr <- liftExprData $ getFunPtr funTy t argVars' <- castVarsW $ zip argVars argTy doTrashStmts let argSuffix = [mkIntLit i32 0, mkIntLit i32 localityInt, mkIntLit i32 1] statement $ Expr $ Call StdCall fptr (argVars' ++ argSuffix) [] | otherwise = panic $ "prefetch locality level integer must be between 0 and 3, given: " ++ (show localityInt) -- Handle PopCnt, Clz, Ctz, and BSwap that need to only convert arg -- and return types genCall t@(PrimTarget (MO_PopCnt w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_Clz w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_Ctz w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_BSwap w)) dsts args = genCallSimpleCast w t dsts args genCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = runStmtsDecls $ do addrVar <- exprToVarW addr nVar <- exprToVarW n let targetTy = widthToLlvmInt width ptrExpr = Cast LM_Inttoptr addrVar (pLift targetTy) ptrVar <- doExprW (pLift targetTy) ptrExpr dstVar <- getCmmRegW (CmmLocal dst) let op = case amop of AMO_Add -> LAO_Add AMO_Sub -> LAO_Sub AMO_And -> LAO_And AMO_Nand -> LAO_Nand AMO_Or -> LAO_Or AMO_Xor -> LAO_Xor retVar <- doExprW targetTy $ AtomicRMW op ptrVar nVar SyncSeqCst statement $ Store retVar dstVar genCall (PrimTarget (MO_AtomicRead _)) [dst] [addr] = runStmtsDecls $ do dstV <- getCmmRegW (CmmLocal dst) v1 <- genLoadW True addr (localRegType dst) statement $ Store v1 dstV genCall (PrimTarget (MO_Cmpxchg _width)) [dst] [addr, old, new] = runStmtsDecls $ do addrVar <- exprToVarW addr oldVar <- exprToVarW old newVar <- exprToVarW new let targetTy = getVarType oldVar ptrExpr = Cast LM_Inttoptr addrVar (pLift targetTy) ptrVar <- doExprW (pLift targetTy) ptrExpr dstVar <- getCmmRegW (CmmLocal dst) retVar <- doExprW (LMStructU [targetTy,i1]) $ CmpXChg ptrVar oldVar newVar SyncSeqCst SyncSeqCst retVar' <- doExprW targetTy $ ExtractV retVar 0 statement $ Store retVar' dstVar genCall (PrimTarget (MO_AtomicWrite _width)) [] [addr, val] = runStmtsDecls $ do addrVar <- exprToVarW addr valVar <- exprToVarW val let ptrTy = pLift $ getVarType valVar ptrExpr = Cast LM_Inttoptr addrVar ptrTy ptrVar <- doExprW ptrTy ptrExpr statement $ Expr $ AtomicRMW LAO_Xchg ptrVar valVar SyncSeqCst -- Handle memcpy function specifically since llvm's intrinsic version takes -- some extra parameters. genCall t@(PrimTarget op) [] args | Just align <- machOpMemcpyishAlign op = runStmtsDecls $ do dflags <- getDynFlags let isVolTy = [i1] isVolVal = [mkIntLit i1 0] argTy | MO_Memset _ <- op = [i8Ptr, i8, llvmWord dflags, i32] ++ isVolTy | otherwise = [i8Ptr, i8Ptr, llvmWord dflags, i32] ++ isVolTy funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints argVars <- arg_varsW args_hints ([], nilOL, []) fptr <- getFunPtrW funTy t argVars' <- castVarsW $ zip argVars argTy doTrashStmts let alignVal = mkIntLit i32 align arguments = argVars' ++ (alignVal:isVolVal) statement $ Expr $ Call StdCall fptr arguments [] -- We handle MO_U_Mul2 by simply using a 'mul' instruction, but with operands -- twice the width (we first zero-extend them), e.g., on 64-bit arch we will -- generate 'mul' on 128-bit operands. Then we only need some plumbing to -- extract the two 64-bit values out of 128-bit result. genCall (PrimTarget (MO_U_Mul2 w)) [dstH, dstL] [lhs, rhs] = runStmtsDecls $ do let width = widthToLlvmInt w bitWidth = widthInBits w width2x = LMInt (bitWidth * 2) -- First zero-extend the operands ('mul' instruction requires the operands -- and the result to be of the same type). Note that we don't use 'castVars' -- because it tries to do LM_Sext. lhsVar <- exprToVarW lhs rhsVar <- exprToVarW rhs lhsExt <- doExprW width2x $ Cast LM_Zext lhsVar width2x rhsExt <- doExprW width2x $ Cast LM_Zext rhsVar width2x -- Do the actual multiplication (note that the result is also 2x width). retV <- doExprW width2x $ LlvmOp LM_MO_Mul lhsExt rhsExt -- Extract the lower bits of the result into retL. retL <- doExprW width $ Cast LM_Trunc retV width -- Now we right-shift the higher bits by width. let widthLlvmLit = LMLitVar $ LMIntLit (fromIntegral bitWidth) width retShifted <- doExprW width2x $ LlvmOp LM_MO_LShr retV widthLlvmLit -- And extract them into retH. retH <- doExprW width $ Cast LM_Trunc retShifted width dstRegL <- getCmmRegW (CmmLocal dstL) dstRegH <- getCmmRegW (CmmLocal dstH) statement $ Store retL dstRegL statement $ Store retH dstRegH -- MO_U_QuotRem2 is another case we handle by widening the registers to double -- the width and use normal LLVM instructions (similarly to the MO_U_Mul2). The -- main difference here is that we need to combine two words into one register -- and then use both 'udiv' and 'urem' instructions to compute the result. genCall (PrimTarget (MO_U_QuotRem2 w)) [dstQ, dstR] [lhsH, lhsL, rhs] = runStmtsDecls $ do let width = widthToLlvmInt w bitWidth = widthInBits w width2x = LMInt (bitWidth * 2) -- First zero-extend all parameters to double width. let zeroExtend expr = do var <- exprToVarW expr doExprW width2x $ Cast LM_Zext var width2x lhsExtH <- zeroExtend lhsH lhsExtL <- zeroExtend lhsL rhsExt <- zeroExtend rhs -- Now we combine the first two parameters (that represent the high and low -- bits of the value). So first left-shift the high bits to their position -- and then bit-or them with the low bits. let widthLlvmLit = LMLitVar $ LMIntLit (fromIntegral bitWidth) width lhsExtHShifted <- doExprW width2x $ LlvmOp LM_MO_Shl lhsExtH widthLlvmLit lhsExt <- doExprW width2x $ LlvmOp LM_MO_Or lhsExtHShifted lhsExtL -- Finally, we can call 'udiv' and 'urem' to compute the results. retExtDiv <- doExprW width2x $ LlvmOp LM_MO_UDiv lhsExt rhsExt retExtRem <- doExprW width2x $ LlvmOp LM_MO_URem lhsExt rhsExt -- And since everything is in 2x width, we need to truncate the results and -- then return them. let narrow var = doExprW width $ Cast LM_Trunc var width retDiv <- narrow retExtDiv retRem <- narrow retExtRem dstRegQ <- lift $ getCmmReg (CmmLocal dstQ) dstRegR <- lift $ getCmmReg (CmmLocal dstR) statement $ Store retDiv dstRegQ statement $ Store retRem dstRegR -- Handle the MO_{Add,Sub}IntC separately. LLVM versions return a record from -- which we need to extract the actual values. genCall t@(PrimTarget (MO_AddIntC w)) [dstV, dstO] [lhs, rhs] = genCallWithOverflow t w [dstV, dstO] [lhs, rhs] genCall t@(PrimTarget (MO_SubIntC w)) [dstV, dstO] [lhs, rhs] = genCallWithOverflow t w [dstV, dstO] [lhs, rhs] -- Similar to MO_{Add,Sub}IntC, but MO_Add2 expects the first element of the -- return tuple to be the overflow bit and the second element to contain the -- actual result of the addition. So we still use genCallWithOverflow but swap -- the return registers. genCall t@(PrimTarget (MO_Add2 w)) [dstO, dstV] [lhs, rhs] = genCallWithOverflow t w [dstV, dstO] [lhs, rhs] genCall t@(PrimTarget (MO_SubWordC w)) [dstV, dstO] [lhs, rhs] = genCallWithOverflow t w [dstV, dstO] [lhs, rhs] -- Handle all other foreign calls and prim ops. genCall target res args = runStmtsDecls $ do dflags <- getDynFlags -- parameter types let arg_type (_, AddrHint) = i8Ptr -- cast pointers to i8*. Llvm equivalent of void* arg_type (expr, _) = cmmToLlvmType $ cmmExprType dflags expr -- ret type let ret_type [] = LMVoid ret_type [(_, AddrHint)] = i8Ptr ret_type [(reg, _)] = cmmToLlvmType $ localRegType reg ret_type t = panic $ "genCall: Too many return values! Can only handle" ++ " 0 or 1, given " ++ show (length t) ++ "." -- extract Cmm call convention, and translate to LLVM call convention platform <- lift $ getLlvmPlatform let lmconv = case target of ForeignTarget _ (ForeignConvention conv _ _ _) -> case conv of StdCallConv -> case platformArch platform of ArchX86 -> CC_X86_Stdcc ArchX86_64 -> CC_X86_Stdcc _ -> CC_Ccc CCallConv -> CC_Ccc CApiConv -> CC_Ccc PrimCallConv -> panic "LlvmCodeGen.CodeGen.genCall: PrimCallConv" JavaScriptCallConv -> panic "LlvmCodeGen.CodeGen.genCall: JavaScriptCallConv" PrimTarget _ -> CC_Ccc {- CC_Ccc of the possibilities here are a worry with the use of a custom calling convention for passing STG args. In practice the more dangerous combinations (e.g StdCall + llvmGhcCC) don't occur. The native code generator only handles StdCall and CCallConv. -} -- call attributes let fnAttrs | never_returns = NoReturn : llvmStdFunAttrs | otherwise = llvmStdFunAttrs never_returns = case target of ForeignTarget _ (ForeignConvention _ _ _ CmmNeverReturns) -> True _ -> False -- fun type let (res_hints, arg_hints) = foreignTargetHints target let args_hints = zip args arg_hints let ress_hints = zip res res_hints let ccTy = StdCall -- tail calls should be done through CmmJump let retTy = ret_type ress_hints let argTy = tysToParams $ map arg_type args_hints let funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible lmconv retTy FixedArgs argTy (llvmFunAlign dflags) argVars <- arg_varsW args_hints ([], nilOL, []) fptr <- getFunPtrW funTy target let doReturn | ccTy == TailCall = statement $ Return Nothing | never_returns = statement $ Unreachable | otherwise = return () doTrashStmts -- make the actual call case retTy of LMVoid -> do statement $ Expr $ Call ccTy fptr argVars fnAttrs _ -> do v1 <- doExprW retTy $ Call ccTy fptr argVars fnAttrs -- get the return register let ret_reg [reg] = reg ret_reg t = panic $ "genCall: Bad number of registers! Can only handle" ++ " 1, given " ++ show (length t) ++ "." let creg = ret_reg res vreg <- getCmmRegW (CmmLocal creg) if retTy == pLower (getVarType vreg) then do statement $ Store v1 vreg doReturn else do let ty = pLower $ getVarType vreg let op = case ty of vt | isPointer vt -> LM_Bitcast | isInt vt -> LM_Ptrtoint | otherwise -> panic $ "genCall: CmmReg bad match for" ++ " returned type!" v2 <- doExprW ty $ Cast op v1 ty statement $ Store v2 vreg doReturn -- | Generate a call to an LLVM intrinsic that performs arithmetic operation -- with overflow bit (i.e., returns a struct containing the actual result of the -- operation and an overflow bit). This function will also extract the overflow -- bit and zero-extend it (all the corresponding Cmm PrimOps represent the -- overflow "bit" as a usual Int# or Word#). genCallWithOverflow :: ForeignTarget -> Width -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData genCallWithOverflow t@(PrimTarget op) w [dstV, dstO] [lhs, rhs] = do -- So far this was only tested for the following four CallishMachOps. let valid = op `elem` [ MO_Add2 w , MO_AddIntC w , MO_SubIntC w , MO_SubWordC w ] MASSERT(valid) let width = widthToLlvmInt w -- This will do most of the work of generating the call to the intrinsic and -- extracting the values from the struct. (value, overflowBit, (stmts, top)) <- genCallExtract t w (lhs, rhs) (width, i1) -- value is i<width>, but overflowBit is i1, so we need to cast (Cmm expects -- both to be i<width>) (overflow, zext) <- doExpr width $ Cast LM_Zext overflowBit width dstRegV <- getCmmReg (CmmLocal dstV) dstRegO <- getCmmReg (CmmLocal dstO) let storeV = Store value dstRegV storeO = Store overflow dstRegO return (stmts `snocOL` zext `snocOL` storeV `snocOL` storeO, top) genCallWithOverflow _ _ _ _ = panic "genCallExtract: wrong ForeignTarget or number of arguments" -- | A helper function for genCallWithOverflow that handles generating the call -- to the LLVM intrinsic and extracting the result from the struct to LlvmVars. genCallExtract :: ForeignTarget -- ^ PrimOp -> Width -- ^ Width of the operands. -> (CmmActual, CmmActual) -- ^ Actual arguments. -> (LlvmType, LlvmType) -- ^ LLLVM types of the returned sturct. -> LlvmM (LlvmVar, LlvmVar, StmtData) genCallExtract target@(PrimTarget op) w (argA, argB) (llvmTypeA, llvmTypeB) = do let width = widthToLlvmInt w argTy = [width, width] retTy = LMStructU [llvmTypeA, llvmTypeB] -- Process the arguments. let args_hints = zip [argA, argB] (snd $ foreignTargetHints target) (argsV1, args1, top1) <- arg_vars args_hints ([], nilOL, []) (argsV2, args2) <- castVars $ zip argsV1 argTy -- Get the function and make the call. fname <- cmmPrimOpFunctions op (fptr, _, top2) <- getInstrinct fname retTy argTy -- We use StdCall for primops. See also the last case of genCall. (retV, call) <- doExpr retTy $ Call StdCall fptr argsV2 [] -- This will result in a two element struct, we need to use "extractvalue" -- to get them out of it. (res1, ext1) <- doExpr llvmTypeA (ExtractV retV 0) (res2, ext2) <- doExpr llvmTypeB (ExtractV retV 1) let stmts = args1 `appOL` args2 `snocOL` call `snocOL` ext1 `snocOL` ext2 tops = top1 ++ top2 return (res1, res2, (stmts, tops)) genCallExtract _ _ _ _ = panic "genCallExtract: unsupported ForeignTarget" -- Handle simple function call that only need simple type casting, of the form: -- truncate arg >>= \a -> call(a) >>= zext -- -- since GHC only really has i32 and i64 types and things like Word8 are backed -- by an i32 and just present a logical i8 range. So we must handle conversions -- from i32 to i8 explicitly as LLVM is strict about types. genCallSimpleCast :: Width -> ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData genCallSimpleCast w t@(PrimTarget op) [dst] args = do let width = widthToLlvmInt w dstTy = cmmToLlvmType $ localRegType dst fname <- cmmPrimOpFunctions op (fptr, _, top3) <- getInstrinct fname width [width] dstV <- getCmmReg (CmmLocal dst) let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints (argsV, stmts2, top2) <- arg_vars args_hints ([], nilOL, []) (argsV', stmts4) <- castVars $ zip argsV [width] (retV, s1) <- doExpr width $ Call StdCall fptr argsV' [] ([retV'], stmts5) <- castVars [(retV,dstTy)] let s2 = Store retV' dstV let stmts = stmts2 `appOL` stmts4 `snocOL` s1 `appOL` stmts5 `snocOL` s2 return (stmts, top2 ++ top3) genCallSimpleCast _ _ dsts _ = panic ("genCallSimpleCast: " ++ show (length dsts) ++ " dsts") -- | Create a function pointer from a target. getFunPtrW :: (LMString -> LlvmType) -> ForeignTarget -> WriterT LlvmAccum LlvmM LlvmVar getFunPtrW funTy targ = liftExprData $ getFunPtr funTy targ -- | Create a function pointer from a target. getFunPtr :: (LMString -> LlvmType) -> ForeignTarget -> LlvmM ExprData getFunPtr funTy targ = case targ of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do name <- strCLabel_llvm lbl getHsFunc' name (funTy name) ForeignTarget expr _ -> do (v1, stmts, top) <- exprToVar expr dflags <- getDynFlags let fty = funTy $ fsLit "dynamic" cast = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genCall: Expr is of bad type for function" ++ " call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v2,s1) <- doExpr (pLift fty) $ Cast cast v1 (pLift fty) return (v2, stmts `snocOL` s1, top) PrimTarget mop -> do name <- cmmPrimOpFunctions mop let fty = funTy name getInstrinct2 name fty -- | Conversion of call arguments. arg_varsW :: [(CmmActual, ForeignHint)] -> ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) -> WriterT LlvmAccum LlvmM [LlvmVar] arg_varsW xs ys = do (vars, stmts, decls) <- lift $ arg_vars xs ys tell $ LlvmAccum stmts decls return vars -- | Conversion of call arguments. arg_vars :: [(CmmActual, ForeignHint)] -> ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) -> LlvmM ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) arg_vars [] (vars, stmts, tops) = return (vars, stmts, tops) arg_vars ((e, AddrHint):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e dflags <- getDynFlags let op = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr a -> panic $ "genCall: Can't cast llvmType to i8*! (" ++ showSDoc dflags (ppr a) ++ ")" (v2, s1) <- doExpr i8Ptr $ Cast op v1 i8Ptr arg_vars rest (vars ++ [v2], stmts `appOL` stmts' `snocOL` s1, tops ++ top') arg_vars ((e, _):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e arg_vars rest (vars ++ [v1], stmts `appOL` stmts', tops ++ top') -- | Cast a collection of LLVM variables to specific types. castVarsW :: [(LlvmVar, LlvmType)] -> WriterT LlvmAccum LlvmM [LlvmVar] castVarsW vars = do (vars, stmts) <- lift $ castVars vars tell $ LlvmAccum stmts mempty return vars -- | Cast a collection of LLVM variables to specific types. castVars :: [(LlvmVar, LlvmType)] -> LlvmM ([LlvmVar], LlvmStatements) castVars vars = do done <- mapM (uncurry castVar) vars let (vars', stmts) = unzip done return (vars', toOL stmts) -- | Cast an LLVM variable to a specific type, panicing if it can't be done. castVar :: LlvmVar -> LlvmType -> LlvmM (LlvmVar, LlvmStatement) castVar v t | getVarType v == t = return (v, Nop) | otherwise = do dflags <- getDynFlags let op = case (getVarType v, t) of (LMInt n, LMInt m) -> if n < m then LM_Sext else LM_Trunc (vt, _) | isFloat vt && isFloat t -> if llvmWidthInBits dflags vt < llvmWidthInBits dflags t then LM_Fpext else LM_Fptrunc (vt, _) | isInt vt && isFloat t -> LM_Sitofp (vt, _) | isFloat vt && isInt t -> LM_Fptosi (vt, _) | isInt vt && isPointer t -> LM_Inttoptr (vt, _) | isPointer vt && isInt t -> LM_Ptrtoint (vt, _) | isPointer vt && isPointer t -> LM_Bitcast (vt, _) | isVector vt && isVector t -> LM_Bitcast (vt, _) -> panic $ "castVars: Can't cast this type (" ++ showSDoc dflags (ppr vt) ++ ") to (" ++ showSDoc dflags (ppr t) ++ ")" doExpr t $ Cast op v t -- | Decide what C function to use to implement a CallishMachOp cmmPrimOpFunctions :: CallishMachOp -> LlvmM LMString cmmPrimOpFunctions mop = do dflags <- getDynFlags let intrinTy1 = "p0i8.p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags) intrinTy2 = "p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags) unsupported = panic ("cmmPrimOpFunctions: " ++ show mop ++ " not supported here") return $ case mop of MO_F32_Exp -> fsLit "expf" MO_F32_Log -> fsLit "logf" MO_F32_Sqrt -> fsLit "llvm.sqrt.f32" MO_F32_Pwr -> fsLit "llvm.pow.f32" MO_F32_Sin -> fsLit "llvm.sin.f32" MO_F32_Cos -> fsLit "llvm.cos.f32" MO_F32_Tan -> fsLit "tanf" MO_F32_Asin -> fsLit "asinf" MO_F32_Acos -> fsLit "acosf" MO_F32_Atan -> fsLit "atanf" MO_F32_Sinh -> fsLit "sinhf" MO_F32_Cosh -> fsLit "coshf" MO_F32_Tanh -> fsLit "tanhf" MO_F64_Exp -> fsLit "exp" MO_F64_Log -> fsLit "log" MO_F64_Sqrt -> fsLit "llvm.sqrt.f64" MO_F64_Pwr -> fsLit "llvm.pow.f64" MO_F64_Sin -> fsLit "llvm.sin.f64" MO_F64_Cos -> fsLit "llvm.cos.f64" MO_F64_Tan -> fsLit "tan" MO_F64_Asin -> fsLit "asin" MO_F64_Acos -> fsLit "acos" MO_F64_Atan -> fsLit "atan" MO_F64_Sinh -> fsLit "sinh" MO_F64_Cosh -> fsLit "cosh" MO_F64_Tanh -> fsLit "tanh" MO_Memcpy _ -> fsLit $ "llvm.memcpy." ++ intrinTy1 MO_Memmove _ -> fsLit $ "llvm.memmove." ++ intrinTy1 MO_Memset _ -> fsLit $ "llvm.memset." ++ intrinTy2 (MO_PopCnt w) -> fsLit $ "llvm.ctpop." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_BSwap w) -> fsLit $ "llvm.bswap." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Clz w) -> fsLit $ "llvm.ctlz." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Ctz w) -> fsLit $ "llvm.cttz." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Prefetch_Data _ )-> fsLit "llvm.prefetch" MO_AddIntC w -> fsLit $ "llvm.sadd.with.overflow." ++ showSDoc dflags (ppr $ widthToLlvmInt w) MO_SubIntC w -> fsLit $ "llvm.ssub.with.overflow." ++ showSDoc dflags (ppr $ widthToLlvmInt w) MO_Add2 w -> fsLit $ "llvm.uadd.with.overflow." ++ showSDoc dflags (ppr $ widthToLlvmInt w) MO_SubWordC w -> fsLit $ "llvm.usub.with.overflow." ++ showSDoc dflags (ppr $ widthToLlvmInt w) MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported -- We support MO_U_Mul2 through ordinary LLVM mul instruction, see the -- appropriate case of genCall. MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported MO_UF_Conv _ -> unsupported MO_AtomicRead _ -> unsupported MO_AtomicRMW _ _ -> unsupported MO_AtomicWrite _ -> unsupported MO_Cmpxchg _ -> unsupported -- | Tail function calls genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData -- Call to known function genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address genJump expr live = do fty <- llvmFunTy live (vf, stmts, top) <- exprToVar expr dflags <- getDynFlags let cast = case getVarType vf of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genJump: Expr is of bad type for function call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v1, s1) <- doExpr (pLift fty) $ Cast cast vf (pLift fty) (stgRegs, stgStmts) <- funEpilogue live let s2 = Expr $ Call TailCall v1 stgRegs llvmStdFunAttrs let s3 = Return Nothing return (stmts `snocOL` s1 `appOL` stgStmts `snocOL` s2 `snocOL` s3, top) -- | CmmAssign operation -- -- We use stack allocated variables for CmmReg. The optimiser will replace -- these with registers when possible. genAssign :: CmmReg -> CmmExpr -> LlvmM StmtData genAssign reg val = do vreg <- getCmmReg reg (vval, stmts2, top2) <- exprToVar val let stmts = stmts2 let ty = (pLower . getVarType) vreg dflags <- getDynFlags case ty of -- Some registers are pointer types, so need to cast value to pointer LMPointer _ | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) LMVector _ _ -> do (v, s1) <- doExpr ty $ Cast LM_Bitcast vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) _ -> do let s1 = Store vval vreg return (stmts `snocOL` s1, top2) -- | CmmStore operation genStore :: CmmExpr -> CmmExpr -> LlvmM StmtData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genStore addr@(CmmReg (CmmGlobal r)) val = genStore_fast addr r 0 val genStore addr@(CmmRegOff (CmmGlobal r) n) val = genStore_fast addr r n val genStore addr@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (fromInteger n) val genStore addr@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (negate $ fromInteger n) val -- generic case genStore addr val = getTBAAMeta topN >>= genStore_slow addr val -- | CmmStore operation -- This is a special case for storing to a global register pointer -- offset such as I32[Sp+8]. genStore_fast :: CmmExpr -> GlobalReg -> Int -> CmmExpr -> LlvmM StmtData genStore_fast addr r n val = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (vval, stmts, top) <- exprToVar val (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case pLower grt == getVarType vval of -- were fine True -> do let s3 = MetaStmt meta $ Store vval ptr return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3, top) -- cast to pointer type needed False -> do let ty = (pLift . getVarType) vval (ptr', s3) <- doExpr ty $ Cast LM_Bitcast ptr ty let s4 = MetaStmt meta $ Store vval ptr' return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, top) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genStore_slow addr val meta -- | CmmStore operation -- Generic case. Uses casts and pointer arithmetic if needed. genStore_slow :: CmmExpr -> CmmExpr -> [MetaAnnot] -> LlvmM StmtData genStore_slow addr val meta = do (vaddr, stmts1, top1) <- exprToVar addr (vval, stmts2, top2) <- exprToVar val let stmts = stmts1 `appOL` stmts2 dflags <- getDynFlags case getVarType vaddr of -- sometimes we need to cast an int to a pointer before storing LMPointer ty@(LMPointer _) | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = MetaStmt meta $ Store v vaddr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) LMPointer _ -> do let s1 = MetaStmt meta $ Store vval vaddr return (stmts `snocOL` s1, top1 ++ top2) i@(LMInt _) | i == llvmWord dflags -> do let vty = pLift $ getVarType vval (vptr, s1) <- doExpr vty $ Cast LM_Inttoptr vaddr vty let s2 = MetaStmt meta $ Store vval vptr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) other -> pprPanic "genStore: ptr not right type!" (PprCmm.pprExpr addr <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr vaddr))) -- | Unconditional branch genBranch :: BlockId -> LlvmM StmtData genBranch id = let label = blockIdToLlvm id in return (unitOL $ Branch label, []) -- | Conditional branch genCondBranch :: CmmExpr -> BlockId -> BlockId -> Maybe Bool -> LlvmM StmtData genCondBranch cond idT idF likely = do let labelT = blockIdToLlvm idT let labelF = blockIdToLlvm idF -- See Note [Literals and branch conditions]. (vc, stmts1, top1) <- exprToVarOpt i1Option cond if getVarType vc == i1 then do (vc', (stmts2, top2)) <- case likely of Just b -> genExpectLit (if b then 1 else 0) i1 vc _ -> pure (vc, (nilOL, [])) let s1 = BranchIf vc' labelT labelF return (stmts1 `appOL` stmts2 `snocOL` s1, top1 ++ top2) else do dflags <- getDynFlags panic $ "genCondBranch: Cond expr not bool! (" ++ showSDoc dflags (ppr vc) ++ ")" -- | Generate call to llvm.expect.x intrinsic. Assigning result to a new var. genExpectLit :: Integer -> LlvmType -> LlvmVar -> LlvmM (LlvmVar, StmtData) genExpectLit expLit expTy var = do dflags <- getDynFlags let lit = LMLitVar $ LMIntLit expLit expTy llvmExpectName | isInt expTy = fsLit $ "llvm.expect." ++ showSDoc dflags (ppr expTy) | otherwise = panic $ "genExpectedLit: Type not an int!" (llvmExpect, stmts, top) <- getInstrinct llvmExpectName expTy [expTy, expTy] (var', call) <- doExpr expTy $ Call StdCall llvmExpect [var, lit] [] return (var', (stmts `snocOL` call, top)) {- Note [Literals and branch conditions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is important that whenever we generate branch conditions for literals like '1', they are properly narrowed to an LLVM expression of type 'i1' (for bools.) Otherwise, nobody is happy. So when we convert a CmmExpr to an LLVM expression for a branch conditional, exprToVarOpt must be certain to return a properly narrowed type. genLit is responsible for this, in the case of literal integers. Often, we won't see direct statements like: if(1) { ... } else { ... } at this point in the pipeline, because the Glorious Code Generator will do trivial branch elimination in the sinking pass (among others,) which will eliminate the expression entirely. However, it's certainly possible and reasonable for this to occur in hand-written C-- code. Consider something like: #ifndef SOME_CONDITIONAL #define CHECK_THING(x) 1 #else #define CHECK_THING(x) some_operation((x)) #endif f() { if (CHECK_THING(xyz)) { ... } else { ... } } In such an instance, CHECK_THING might result in an *expression* in one case, and a *literal* in the other, depending on what in particular was #define'd. So we must be sure to properly narrow the literal in this case to i1 as it won't be eliminated beforehand. For a real example of this, see ./rts/StgStdThunks.cmm -} -- | Switch branch genSwitch :: CmmExpr -> SwitchTargets -> LlvmM StmtData genSwitch cond ids = do (vc, stmts, top) <- exprToVar cond let ty = getVarType vc let labels = [ (mkIntLit ty ix, blockIdToLlvm b) | (ix, b) <- switchTargetsCases ids ] -- out of range is undefined, so let's just branch to first label let defLbl | Just l <- switchTargetsDefault ids = blockIdToLlvm l | otherwise = snd (head labels) let s1 = Switch vc defLbl labels return $ (stmts `snocOL` s1, top) -- ----------------------------------------------------------------------------- -- * CmmExpr code generation -- -- | An expression conversion return data: -- * LlvmVar: The var holding the result of the expression -- * LlvmStatements: Any statements needed to evaluate the expression -- * LlvmCmmDecl: Any global data needed for this expression type ExprData = (LlvmVar, LlvmStatements, [LlvmCmmDecl]) -- | Values which can be passed to 'exprToVar' to configure its -- behaviour in certain circumstances. -- -- Currently just used for determining if a comparison should return -- a boolean (i1) or a word. See Note [Literals and branch conditions]. newtype EOption = EOption { i1Expected :: Bool } -- XXX: EOption is an ugly and inefficient solution to this problem. -- | i1 type expected (condition scrutinee). i1Option :: EOption i1Option = EOption True -- | Word type expected (usual). wordOption :: EOption wordOption = EOption False -- | Convert a CmmExpr to a list of LlvmStatements with the result of the -- expression being stored in the returned LlvmVar. exprToVar :: CmmExpr -> LlvmM ExprData exprToVar = exprToVarOpt wordOption exprToVarOpt :: EOption -> CmmExpr -> LlvmM ExprData exprToVarOpt opt e = case e of CmmLit lit -> genLit opt lit CmmLoad e' ty -> genLoad False e' ty -- Cmmreg in expression is the value, so must load. If you want actual -- reg pointer, call getCmmReg directly. CmmReg r -> do (v1, ty, s1) <- getCmmRegVal r case isPointer ty of True -> do -- Cmm wants the value, so pointer types must be cast to ints dflags <- getDynFlags (v2, s2) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint v1 (llvmWord dflags) return (v2, s1 `snocOL` s2, []) False -> return (v1, s1, []) CmmMachOp op exprs -> genMachOp opt op exprs CmmRegOff r i -> do dflags <- getDynFlags exprToVar $ expandCmmReg dflags (r, i) CmmStackSlot _ _ -> panic "exprToVar: CmmStackSlot not supported!" -- | Handle CmmMachOp expressions genMachOp :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Unary Machop genMachOp _ op [x] = case op of MO_Not w -> let all1 = mkIntLit (widthToLlvmInt w) (-1) in negate (widthToLlvmInt w) all1 LM_MO_Xor MO_S_Neg w -> let all0 = mkIntLit (widthToLlvmInt w) 0 in negate (widthToLlvmInt w) all0 LM_MO_Sub MO_F_Neg w -> let all0 = LMLitVar $ LMFloatLit (-0) (widthToLlvmFloat w) in negate (widthToLlvmFloat w) all0 LM_MO_FSub MO_SF_Conv _ w -> fiConv (widthToLlvmFloat w) LM_Sitofp MO_FS_Conv _ w -> fiConv (widthToLlvmInt w) LM_Fptosi MO_SS_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Sext MO_UU_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Zext MO_FF_Conv from to -> sameConv from (widthToLlvmFloat to) LM_Fptrunc LM_Fpext MO_VS_Neg len w -> let ty = widthToLlvmInt w vecty = LMVector len ty all0 = LMIntLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_Sub MO_VF_Neg len w -> let ty = widthToLlvmFloat w vecty = LMVector len ty all0 = LMFloatLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_FSub -- Handle unsupported cases explicitly so we get a warning -- of missing case when new MachOps added MO_Add _ -> panicOp MO_Mul _ -> panicOp MO_Sub _ -> panicOp MO_S_MulMayOflo _ -> panicOp MO_S_Quot _ -> panicOp MO_S_Rem _ -> panicOp MO_U_MulMayOflo _ -> panicOp MO_U_Quot _ -> panicOp MO_U_Rem _ -> panicOp MO_Eq _ -> panicOp MO_Ne _ -> panicOp MO_S_Ge _ -> panicOp MO_S_Gt _ -> panicOp MO_S_Le _ -> panicOp MO_S_Lt _ -> panicOp MO_U_Ge _ -> panicOp MO_U_Gt _ -> panicOp MO_U_Le _ -> panicOp MO_U_Lt _ -> panicOp MO_F_Add _ -> panicOp MO_F_Sub _ -> panicOp MO_F_Mul _ -> panicOp MO_F_Quot _ -> panicOp MO_F_Eq _ -> panicOp MO_F_Ne _ -> panicOp MO_F_Ge _ -> panicOp MO_F_Gt _ -> panicOp MO_F_Le _ -> panicOp MO_F_Lt _ -> panicOp MO_And _ -> panicOp MO_Or _ -> panicOp MO_Xor _ -> panicOp MO_Shl _ -> panicOp MO_U_Shr _ -> panicOp MO_S_Shr _ -> panicOp MO_V_Insert _ _ -> panicOp MO_V_Extract _ _ -> panicOp MO_V_Add _ _ -> panicOp MO_V_Sub _ _ -> panicOp MO_V_Mul _ _ -> panicOp MO_VS_Quot _ _ -> panicOp MO_VS_Rem _ _ -> panicOp MO_VU_Quot _ _ -> panicOp MO_VU_Rem _ _ -> panicOp MO_VF_Insert _ _ -> panicOp MO_VF_Extract _ _ -> panicOp MO_VF_Add _ _ -> panicOp MO_VF_Sub _ _ -> panicOp MO_VF_Mul _ _ -> panicOp MO_VF_Quot _ _ -> panicOp where negate ty v2 negOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx return (v1, stmts `snocOL` s1, top) negateVec ty v2 negOp = do (vx, stmts1, top) <- exprToVar x ([vx'], stmts2) <- castVars [(vx, ty)] (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx' return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top) fiConv ty convOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ Cast convOp vx ty return (v1, stmts `snocOL` s1, top) sameConv from ty reduce expand = do x'@(vx, stmts, top) <- exprToVar x let sameConv' op = do (v1, s1) <- doExpr ty $ Cast op vx ty return (v1, stmts `snocOL` s1, top) dflags <- getDynFlags let toWidth = llvmWidthInBits dflags ty -- LLVM doesn't like trying to convert to same width, so -- need to check for that as we do get Cmm code doing it. case widthInBits from of w | w < toWidth -> sameConv' expand w | w > toWidth -> sameConv' reduce _w -> return x' panicOp = panic $ "LLVM.CodeGen.genMachOp: non unary op encountered" ++ "with one argument! (" ++ show op ++ ")" -- Handle GlobalRegs pointers genMachOp opt o@(MO_Add _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (fromInteger n) e genMachOp opt o@(MO_Sub _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (negate . fromInteger $ n) e -- Generic case genMachOp opt op e = genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This is a specialised method that handles Global register manipulations like -- 'Sp - 16', using the getelementptr instruction. genMachOp_fast :: EOption -> MachOp -> GlobalReg -> Int -> [CmmExpr] -> LlvmM ExprData genMachOp_fast opt op r n e = do (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) dflags <- getDynFlags let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] (var, s3) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint ptr (llvmWord dflags) return (var, s1 `snocOL` s2 `snocOL` s3, []) False -> genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This handles all the cases not handle by the specialised genMachOp_fast. genMachOp_slow :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Element extraction genMachOp_slow _ (MO_V_Extract l w) [val, idx] = runExprData $ do vval <- exprToVarW val vidx <- exprToVarW idx [vval'] <- castVarsW [(vval, LMVector l ty)] doExprW ty $ Extract vval' vidx where ty = widthToLlvmInt w genMachOp_slow _ (MO_VF_Extract l w) [val, idx] = runExprData $ do vval <- exprToVarW val vidx <- exprToVarW idx [vval'] <- castVarsW [(vval, LMVector l ty)] doExprW ty $ Extract vval' vidx where ty = widthToLlvmFloat w -- Element insertion genMachOp_slow _ (MO_V_Insert l w) [val, elt, idx] = runExprData $ do vval <- exprToVarW val velt <- exprToVarW elt vidx <- exprToVarW idx [vval'] <- castVarsW [(vval, ty)] doExprW ty $ Insert vval' velt vidx where ty = LMVector l (widthToLlvmInt w) genMachOp_slow _ (MO_VF_Insert l w) [val, elt, idx] = runExprData $ do vval <- exprToVarW val velt <- exprToVarW elt vidx <- exprToVarW idx [vval'] <- castVarsW [(vval, ty)] doExprW ty $ Insert vval' velt vidx where ty = LMVector l (widthToLlvmFloat w) -- Binary MachOp genMachOp_slow opt op [x, y] = case op of MO_Eq _ -> genBinComp opt LM_CMP_Eq MO_Ne _ -> genBinComp opt LM_CMP_Ne MO_S_Gt _ -> genBinComp opt LM_CMP_Sgt MO_S_Ge _ -> genBinComp opt LM_CMP_Sge MO_S_Lt _ -> genBinComp opt LM_CMP_Slt MO_S_Le _ -> genBinComp opt LM_CMP_Sle MO_U_Gt _ -> genBinComp opt LM_CMP_Ugt MO_U_Ge _ -> genBinComp opt LM_CMP_Uge MO_U_Lt _ -> genBinComp opt LM_CMP_Ult MO_U_Le _ -> genBinComp opt LM_CMP_Ule MO_Add _ -> genBinMach LM_MO_Add MO_Sub _ -> genBinMach LM_MO_Sub MO_Mul _ -> genBinMach LM_MO_Mul MO_U_MulMayOflo _ -> panic "genMachOp: MO_U_MulMayOflo unsupported!" MO_S_MulMayOflo w -> isSMulOK w x y MO_S_Quot _ -> genBinMach LM_MO_SDiv MO_S_Rem _ -> genBinMach LM_MO_SRem MO_U_Quot _ -> genBinMach LM_MO_UDiv MO_U_Rem _ -> genBinMach LM_MO_URem MO_F_Eq _ -> genBinComp opt LM_CMP_Feq MO_F_Ne _ -> genBinComp opt LM_CMP_Fne MO_F_Gt _ -> genBinComp opt LM_CMP_Fgt MO_F_Ge _ -> genBinComp opt LM_CMP_Fge MO_F_Lt _ -> genBinComp opt LM_CMP_Flt MO_F_Le _ -> genBinComp opt LM_CMP_Fle MO_F_Add _ -> genBinMach LM_MO_FAdd MO_F_Sub _ -> genBinMach LM_MO_FSub MO_F_Mul _ -> genBinMach LM_MO_FMul MO_F_Quot _ -> genBinMach LM_MO_FDiv MO_And _ -> genBinMach LM_MO_And MO_Or _ -> genBinMach LM_MO_Or MO_Xor _ -> genBinMach LM_MO_Xor MO_Shl _ -> genBinMach LM_MO_Shl MO_U_Shr _ -> genBinMach LM_MO_LShr MO_S_Shr _ -> genBinMach LM_MO_AShr MO_V_Add l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Add MO_V_Sub l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Sub MO_V_Mul l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Mul MO_VS_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SDiv MO_VS_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SRem MO_VU_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_UDiv MO_VU_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_URem MO_VF_Add l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FAdd MO_VF_Sub l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FSub MO_VF_Mul l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FMul MO_VF_Quot l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FDiv MO_Not _ -> panicOp MO_S_Neg _ -> panicOp MO_F_Neg _ -> panicOp MO_SF_Conv _ _ -> panicOp MO_FS_Conv _ _ -> panicOp MO_SS_Conv _ _ -> panicOp MO_UU_Conv _ _ -> panicOp MO_FF_Conv _ _ -> panicOp MO_V_Insert {} -> panicOp MO_V_Extract {} -> panicOp MO_VS_Neg {} -> panicOp MO_VF_Insert {} -> panicOp MO_VF_Extract {} -> panicOp MO_VF_Neg {} -> panicOp where binLlvmOp ty binOp = runExprData $ do vx <- exprToVarW x vy <- exprToVarW y if getVarType vx == getVarType vy then do doExprW (ty vx) $ binOp vx vy else do -- Error. Continue anyway so we can debug the generated ll file. dflags <- getDynFlags let style = mkCodeStyle CStyle toString doc = renderWithStyle dflags doc style cmmToStr = (lines . toString . PprCmm.pprExpr) statement $ Comment $ map fsLit $ cmmToStr x statement $ Comment $ map fsLit $ cmmToStr y doExprW (ty vx) $ binOp vx vy binCastLlvmOp ty binOp = runExprData $ do vx <- exprToVarW x vy <- exprToVarW y [vx', vy'] <- castVarsW [(vx, ty), (vy, ty)] doExprW ty $ binOp vx' vy' -- | Need to use EOption here as Cmm expects word size results from -- comparisons while LLVM return i1. Need to extend to llvmWord type -- if expected. See Note [Literals and branch conditions]. genBinComp opt cmp = do ed@(v1, stmts, top) <- binLlvmOp (\_ -> i1) (Compare cmp) dflags <- getDynFlags if getVarType v1 == i1 then case i1Expected opt of True -> return ed False -> do let w_ = llvmWord dflags (v2, s1) <- doExpr w_ $ Cast LM_Zext v1 w_ return (v2, stmts `snocOL` s1, top) else panic $ "genBinComp: Compare returned type other then i1! " ++ (showSDoc dflags $ ppr $ getVarType v1) genBinMach op = binLlvmOp getVarType (LlvmOp op) genCastBinMach ty op = binCastLlvmOp ty (LlvmOp op) -- | Detect if overflow will occur in signed multiply of the two -- CmmExpr's. This is the LLVM assembly equivalent of the NCG -- implementation. Its much longer due to type information/safety. -- This should actually compile to only about 3 asm instructions. isSMulOK :: Width -> CmmExpr -> CmmExpr -> LlvmM ExprData isSMulOK _ x y = runExprData $ do vx <- exprToVarW x vy <- exprToVarW y dflags <- getDynFlags let word = getVarType vx let word2 = LMInt $ 2 * (llvmWidthInBits dflags $ getVarType vx) let shift = llvmWidthInBits dflags word let shift1 = toIWord dflags (shift - 1) let shift2 = toIWord dflags shift if isInt word then do x1 <- doExprW word2 $ Cast LM_Sext vx word2 y1 <- doExprW word2 $ Cast LM_Sext vy word2 r1 <- doExprW word2 $ LlvmOp LM_MO_Mul x1 y1 rlow1 <- doExprW word $ Cast LM_Trunc r1 word rlow2 <- doExprW word $ LlvmOp LM_MO_AShr rlow1 shift1 rhigh1 <- doExprW word2 $ LlvmOp LM_MO_AShr r1 shift2 rhigh2 <- doExprW word $ Cast LM_Trunc rhigh1 word doExprW word $ LlvmOp LM_MO_Sub rlow2 rhigh2 else panic $ "isSMulOK: Not bit type! (" ++ showSDoc dflags (ppr word) ++ ")" panicOp = panic $ "LLVM.CodeGen.genMachOp_slow: unary op encountered" ++ "with two arguments! (" ++ show op ++ ")" -- More then two expression, invalid! genMachOp_slow _ _ _ = panic "genMachOp: More then 2 expressions in MachOp!" -- | Handle CmmLoad expression. genLoad :: Atomic -> CmmExpr -> CmmType -> LlvmM ExprData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genLoad atomic e@(CmmReg (CmmGlobal r)) ty = genLoad_fast atomic e r 0 ty genLoad atomic e@(CmmRegOff (CmmGlobal r) n) ty = genLoad_fast atomic e r n ty genLoad atomic e@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast atomic e r (fromInteger n) ty genLoad atomic e@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast atomic e r (negate $ fromInteger n) ty -- generic case genLoad atomic e ty = getTBAAMeta topN >>= genLoad_slow atomic e ty -- | Handle CmmLoad expression. -- This is a special case for loading from a global register pointer -- offset such as I32[Sp+8]. genLoad_fast :: Atomic -> CmmExpr -> GlobalReg -> Int -> CmmType -> LlvmM ExprData genLoad_fast atomic e r n ty = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let ty' = cmmToLlvmType ty (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case grt == ty' of -- were fine True -> do (var, s3) <- doExpr ty' (MExpr meta $ loadInstr ptr) return (var, s1 `snocOL` s2 `snocOL` s3, []) -- cast to pointer type needed False -> do let pty = pLift ty' (ptr', s3) <- doExpr pty $ Cast LM_Bitcast ptr pty (var, s4) <- doExpr ty' (MExpr meta $ loadInstr ptr') return (var, s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, []) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genLoad_slow atomic e ty meta where loadInstr ptr | atomic = ALoad SyncSeqCst False ptr | otherwise = Load ptr -- | Handle Cmm load expression. -- Generic case. Uses casts and pointer arithmetic if needed. genLoad_slow :: Atomic -> CmmExpr -> CmmType -> [MetaAnnot] -> LlvmM ExprData genLoad_slow atomic e ty meta = runExprData $ do iptr <- exprToVarW e dflags <- getDynFlags case getVarType iptr of LMPointer _ -> do doExprW (cmmToLlvmType ty) (MExpr meta $ loadInstr iptr) i@(LMInt _) | i == llvmWord dflags -> do let pty = LMPointer $ cmmToLlvmType ty ptr <- doExprW pty $ Cast LM_Inttoptr iptr pty doExprW (cmmToLlvmType ty) (MExpr meta $ loadInstr ptr) other -> do pprPanic "exprToVar: CmmLoad expression is not right type!" (PprCmm.pprExpr e <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr iptr))) where loadInstr ptr | atomic = ALoad SyncSeqCst False ptr | otherwise = Load ptr -- | Handle CmmReg expression. This will return a pointer to the stack -- location of the register. Throws an error if it isn't allocated on -- the stack. getCmmReg :: CmmReg -> LlvmM LlvmVar getCmmReg (CmmLocal (LocalReg un _)) = do exists <- varLookup un dflags <- getDynFlags case exists of Just ety -> return (LMLocalVar un $ pLift ety) Nothing -> fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr un) ++ " was not allocated!" -- This should never happen, as every local variable should -- have been assigned a value at some point, triggering -- "funPrologue" to allocate it on the stack. getCmmReg (CmmGlobal g) = do onStack <- checkStackReg g dflags <- getDynFlags if onStack then return (lmGlobalRegVar dflags g) else fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr g) ++ " not stack-allocated!" -- | Return the value of a given register, as well as its type. Might -- need to be load from stack. getCmmRegVal :: CmmReg -> LlvmM (LlvmVar, LlvmType, LlvmStatements) getCmmRegVal reg = case reg of CmmGlobal g -> do onStack <- checkStackReg g dflags <- getDynFlags if onStack then loadFromStack else do let r = lmGlobalRegArg dflags g return (r, getVarType r, nilOL) _ -> loadFromStack where loadFromStack = do ptr <- getCmmReg reg let ty = pLower $ getVarType ptr (v, s) <- doExpr ty (Load ptr) return (v, ty, unitOL s) -- | Allocate a local CmmReg on the stack allocReg :: CmmReg -> (LlvmVar, LlvmStatements) allocReg (CmmLocal (LocalReg un ty)) = let ty' = cmmToLlvmType ty var = LMLocalVar un (LMPointer ty') alc = Alloca ty' 1 in (var, unitOL $ Assignment var alc) allocReg _ = panic $ "allocReg: Global reg encountered! Global registers should" ++ " have been handled elsewhere!" -- | Generate code for a literal genLit :: EOption -> CmmLit -> LlvmM ExprData genLit opt (CmmInt i w) -- See Note [Literals and branch conditions]. = let width | i1Expected opt = i1 | otherwise = LMInt (widthInBits w) -- comm = Comment [ fsLit $ "EOption: " ++ show opt -- , fsLit $ "Width : " ++ show w -- , fsLit $ "Width' : " ++ show (widthInBits w) -- ] in return (mkIntLit width i, nilOL, []) genLit _ (CmmFloat r w) = return (LMLitVar $ LMFloatLit (fromRational r) (widthToLlvmFloat w), nilOL, []) genLit opt (CmmVec ls) = do llvmLits <- mapM toLlvmLit ls return (LMLitVar $ LMVectorLit llvmLits, nilOL, []) where toLlvmLit :: CmmLit -> LlvmM LlvmLit toLlvmLit lit = do (llvmLitVar, _, _) <- genLit opt lit case llvmLitVar of LMLitVar llvmLit -> return llvmLit _ -> panic "genLit" genLit _ cmm@(CmmLabel l) = do var <- getGlobalPtr =<< strCLabel_llvm l dflags <- getDynFlags let lmty = cmmToLlvmType $ cmmLitType dflags cmm (v1, s1) <- doExpr lmty $ Cast LM_Ptrtoint var (llvmWord dflags) return (v1, unitOL s1, []) genLit opt (CmmLabelOff label off) = do dflags <- getDynFlags (vlbl, stmts, stat) <- genLit opt (CmmLabel label) let voff = toIWord dflags off (v1, s1) <- doExpr (getVarType vlbl) $ LlvmOp LM_MO_Add vlbl voff return (v1, stmts `snocOL` s1, stat) genLit opt (CmmLabelDiffOff l1 l2 off) = do dflags <- getDynFlags (vl1, stmts1, stat1) <- genLit opt (CmmLabel l1) (vl2, stmts2, stat2) <- genLit opt (CmmLabel l2) let voff = toIWord dflags off let ty1 = getVarType vl1 let ty2 = getVarType vl2 if (isInt ty1) && (isInt ty2) && (llvmWidthInBits dflags ty1 == llvmWidthInBits dflags ty2) then do (v1, s1) <- doExpr (getVarType vl1) $ LlvmOp LM_MO_Sub vl1 vl2 (v2, s2) <- doExpr (getVarType v1 ) $ LlvmOp LM_MO_Add v1 voff return (v2, stmts1 `appOL` stmts2 `snocOL` s1 `snocOL` s2, stat1 ++ stat2) else panic "genLit: CmmLabelDiffOff encountered with different label ty!" genLit opt (CmmBlock b) = genLit opt (CmmLabel $ infoTblLbl b) genLit _ CmmHighStackMark = panic "genStaticLit - CmmHighStackMark unsupported!" -- ----------------------------------------------------------------------------- -- * Misc -- -- | Find CmmRegs that get assigned and allocate them on the stack -- -- Any register that gets written needs to be allcoated on the -- stack. This avoids having to map a CmmReg to an equivalent SSA form -- and avoids having to deal with Phi node insertion. This is also -- the approach recommended by LLVM developers. -- -- On the other hand, this is unnecessarily verbose if the register in -- question is never written. Therefore we skip it where we can to -- save a few lines in the output and hopefully speed compilation up a -- bit. funPrologue :: LiveGlobalRegs -> [CmmBlock] -> LlvmM StmtData funPrologue live cmmBlocks = do trash <- getTrashRegs let getAssignedRegs :: CmmNode O O -> [CmmReg] getAssignedRegs (CmmAssign reg _) = [reg] -- Calls will trash all registers. Unfortunately, this needs them to -- be stack-allocated in the first place. getAssignedRegs (CmmUnsafeForeignCall _ rs _) = map CmmGlobal trash ++ map CmmLocal rs getAssignedRegs _ = [] getRegsBlock (_, body, _) = concatMap getAssignedRegs $ blockToList body assignedRegs = nub $ concatMap (getRegsBlock . blockSplit) cmmBlocks isLive r = r `elem` alwaysLive || r `elem` live dflags <- getDynFlags stmtss <- flip mapM assignedRegs $ \reg -> case reg of CmmLocal (LocalReg un _) -> do let (newv, stmts) = allocReg reg varInsert un (pLower $ getVarType newv) return stmts CmmGlobal r -> do let reg = lmGlobalRegVar dflags r arg = lmGlobalRegArg dflags r ty = (pLower . getVarType) reg trash = LMLitVar $ LMUndefLit ty rval = if isLive r then arg else trash alloc = Assignment reg $ Alloca (pLower $ getVarType reg) 1 markStackReg r return $ toOL [alloc, Store rval reg] return (concatOL stmtss, []) -- | Function epilogue. Load STG variables to use as argument for call. -- STG Liveness optimisation done here. funEpilogue :: LiveGlobalRegs -> LlvmM ([LlvmVar], LlvmStatements) funEpilogue live = do -- Have information and liveness optimisation is enabled? let liveRegs = alwaysLive ++ live isSSE (FloatReg _) = True isSSE (DoubleReg _) = True isSSE (XmmReg _) = True isSSE (YmmReg _) = True isSSE (ZmmReg _) = True isSSE _ = False -- Set to value or "undef" depending on whether the register is -- actually live dflags <- getDynFlags let loadExpr r = do (v, _, s) <- getCmmRegVal (CmmGlobal r) return (Just $ v, s) loadUndef r = do let ty = (pLower . getVarType $ lmGlobalRegVar dflags r) return (Just $ LMLitVar $ LMUndefLit ty, nilOL) platform <- getDynFlag targetPlatform loads <- flip mapM (activeStgRegs platform) $ \r -> case () of _ | r `elem` liveRegs -> loadExpr r | not (isSSE r) -> loadUndef r | otherwise -> return (Nothing, nilOL) let (vars, stmts) = unzip loads return (catMaybes vars, concatOL stmts) -- | A series of statements to trash all the STG registers. -- -- In LLVM we pass the STG registers around everywhere in function calls. -- So this means LLVM considers them live across the entire function, when -- in reality they usually aren't. For Caller save registers across C calls -- the saving and restoring of them is done by the Cmm code generator, -- using Cmm local vars. So to stop LLVM saving them as well (and saving -- all of them since it thinks they're always live, we trash them just -- before the call by assigning the 'undef' value to them. The ones we -- need are restored from the Cmm local var and the ones we don't need -- are fine to be trashed. getTrashStmts :: LlvmM LlvmStatements getTrashStmts = do regs <- getTrashRegs stmts <- flip mapM regs $ \ r -> do reg <- getCmmReg (CmmGlobal r) let ty = (pLower . getVarType) reg return $ Store (LMLitVar $ LMUndefLit ty) reg return $ toOL stmts getTrashRegs :: LlvmM [GlobalReg] getTrashRegs = do plat <- getLlvmPlatform return $ filter (callerSaves plat) (activeStgRegs plat) -- | Get a function pointer to the CLabel specified. -- -- This is for Haskell functions, function type is assumed, so doesn't work -- with foreign functions. getHsFunc :: LiveGlobalRegs -> CLabel -> LlvmM ExprData getHsFunc live lbl = do fty <- llvmFunTy live name <- strCLabel_llvm lbl getHsFunc' name fty getHsFunc' :: LMString -> LlvmType -> LlvmM ExprData getHsFunc' name fty = do fun <- getGlobalPtr name if getVarType fun == fty then return (fun, nilOL, []) else do (v1, s1) <- doExpr (pLift fty) $ Cast LM_Bitcast fun (pLift fty) return (v1, unitOL s1, []) -- | Create a new local var mkLocalVar :: LlvmType -> LlvmM LlvmVar mkLocalVar ty = do un <- getUniqueM return $ LMLocalVar un ty -- | Execute an expression, assigning result to a var doExpr :: LlvmType -> LlvmExpression -> LlvmM (LlvmVar, LlvmStatement) doExpr ty expr = do v <- mkLocalVar ty return (v, Assignment v expr) -- | Expand CmmRegOff expandCmmReg :: DynFlags -> (CmmReg, Int) -> CmmExpr expandCmmReg dflags (reg, off) = let width = typeWidth (cmmRegType dflags reg) voff = CmmLit $ CmmInt (fromIntegral off) width in CmmMachOp (MO_Add width) [CmmReg reg, voff] -- | Convert a block id into a appropriate Llvm label blockIdToLlvm :: BlockId -> LlvmVar blockIdToLlvm bid = LMLocalVar (getUnique bid) LMLabel -- | Create Llvm int Literal mkIntLit :: Integral a => LlvmType -> a -> LlvmVar mkIntLit ty i = LMLitVar $ LMIntLit (toInteger i) ty -- | Convert int type to a LLvmVar of word or i32 size toI32 :: Integral a => a -> LlvmVar toI32 = mkIntLit i32 toIWord :: Integral a => DynFlags -> a -> LlvmVar toIWord dflags = mkIntLit (llvmWord dflags) -- | Error functions panic :: String -> a panic s = Outputable.panic $ "LlvmCodeGen.CodeGen." ++ s pprPanic :: String -> SDoc -> a pprPanic s d = Outputable.pprPanic ("LlvmCodeGen.CodeGen." ++ s) d -- | Returns TBAA meta data by unique getTBAAMeta :: Unique -> LlvmM [MetaAnnot] getTBAAMeta u = do mi <- getUniqMeta u return [MetaAnnot tbaa (MetaNode i) | let Just i = mi] -- | Returns TBAA meta data for given register getTBAARegMeta :: GlobalReg -> LlvmM [MetaAnnot] getTBAARegMeta = getTBAAMeta . getTBAA -- | A more convenient way of accumulating LLVM statements and declarations. data LlvmAccum = LlvmAccum LlvmStatements [LlvmCmmDecl] #if __GLASGOW_HASKELL__ > 710 instance Semigroup LlvmAccum where LlvmAccum stmtsA declsA <> LlvmAccum stmtsB declsB = LlvmAccum (stmtsA Semigroup.<> stmtsB) (declsA Semigroup.<> declsB) #endif instance Monoid LlvmAccum where mempty = LlvmAccum nilOL [] LlvmAccum stmtsA declsA `mappend` LlvmAccum stmtsB declsB = LlvmAccum (stmtsA `mappend` stmtsB) (declsA `mappend` declsB) liftExprData :: LlvmM ExprData -> WriterT LlvmAccum LlvmM LlvmVar liftExprData action = do (var, stmts, decls) <- lift action tell $ LlvmAccum stmts decls return var statement :: LlvmStatement -> WriterT LlvmAccum LlvmM () statement stmt = tell $ LlvmAccum (unitOL stmt) [] doExprW :: LlvmType -> LlvmExpression -> WriterT LlvmAccum LlvmM LlvmVar doExprW a b = do (var, stmt) <- lift $ doExpr a b statement stmt return var exprToVarW :: CmmExpr -> WriterT LlvmAccum LlvmM LlvmVar exprToVarW = liftExprData . exprToVar runExprData :: WriterT LlvmAccum LlvmM LlvmVar -> LlvmM ExprData runExprData action = do (var, LlvmAccum stmts decls) <- runWriterT action return (var, stmts, decls) runStmtsDecls :: WriterT LlvmAccum LlvmM () -> LlvmM (LlvmStatements, [LlvmCmmDecl]) runStmtsDecls action = do LlvmAccum stmts decls <- execWriterT action return (stmts, decls) getCmmRegW :: CmmReg -> WriterT LlvmAccum LlvmM LlvmVar getCmmRegW = lift . getCmmReg genLoadW :: Atomic -> CmmExpr -> CmmType -> WriterT LlvmAccum LlvmM LlvmVar genLoadW atomic e ty = liftExprData $ genLoad atomic e ty doTrashStmts :: WriterT LlvmAccum LlvmM () doTrashStmts = do stmts <- lift getTrashStmts tell $ LlvmAccum stmts mempty
olsner/ghc
compiler/llvmGen/LlvmCodeGen/CodeGen.hs
bsd-3-clause
72,290
3
25
21,207
19,706
9,743
9,963
1,248
64
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-} {-| Description: Respond to various requests involving database course information. This module contains the functions that perform different database queries and serve the information back to the client. -} module Database.CourseQueries (retrieveCourse, returnCourse, allCourses, courseInfo, getDeptCourses, queryGraphs, deptList, returnTutorial, returnLecture) where import Happstack.Server.SimpleHTTP import Database.Persist import Database.Persist.Sqlite import Database.Tables as Tables import Control.Monad.IO.Class (liftIO, MonadIO) import Util.Happstack (createJSONResponse) import qualified Data.Text as T import WebParsing.ParsingHelp import Data.String.Utils import Data.List import Config (databasePath) import Control.Monad (liftM) -- ** Querying a single course -- | Takes a course code (e.g. \"CSC108H1\") and sends a JSON representation -- of the course as a response. retrieveCourse :: String -> ServerPart Response retrieveCourse = liftIO . queryCourse . T.pack -- | Queries the database for all information about @course@, constructs a JSON object -- representing the course and returns the appropriate JSON response. queryCourse :: T.Text -> IO Response queryCourse str = do courseJSON <- returnCourse str return $ createJSONResponse courseJSON -- | Queries the database for all information about @course@, -- constructs and returns a Course value. returnCourse :: T.Text -> IO Course returnCourse lowerStr = runSqlite databasePath $ do let courseStr = T.toUpper lowerStr sqlCourse :: [Entity Courses] <- selectList [CoursesCode ==. courseStr] [] -- TODO: Just make one query for all lectures, then partition later. -- Same for tutorials. sqlLecturesFall :: [Entity Lecture] <- selectList [LectureCode ==. courseStr, LectureSession ==. "F"] [] sqlLecturesSpring :: [Entity Lecture] <- selectList [LectureCode ==. courseStr, LectureSession ==. "S"] [] sqlLecturesYear :: [Entity Lecture] <- selectList [LectureCode ==. courseStr, LectureSession ==. "Y"] [] sqlTutorialsFall :: [Entity Tutorial] <- selectList [TutorialCode ==. courseStr, TutorialSession ==. "F"] [] sqlTutorialsSpring :: [Entity Tutorial] <- selectList [TutorialCode ==. courseStr, TutorialSession ==. "S"] [] sqlTutorialsYear :: [Entity Tutorial] <- selectList [TutorialCode ==. courseStr, TutorialSession ==. "Y"] [] let fallSession = buildSession sqlLecturesFall sqlTutorialsFall springSession = buildSession sqlLecturesSpring sqlTutorialsSpring yearSession = buildSession sqlLecturesYear sqlTutorialsYear if null sqlCourse then return emptyCourse else return (buildCourse fallSession springSession yearSession (entityVal $ head sqlCourse)) -- | Queries the database for all information regarding a specific tutorial for -- a @course@, returns a Tutorial. returnTutorial :: T.Text -> T.Text -> T.Text -> IO (Maybe Tutorial) returnTutorial lowerStr sect session = runSqlite databasePath $ do maybeEntityTutorials <- selectFirst [TutorialCode ==. T.toUpper lowerStr, TutorialSection ==. Just sect, TutorialSession ==. session] [] return $ fmap entityVal maybeEntityTutorials -- | Queries the database for all information regarding a specific lecture for -- a @course@, returns a Lecture. returnLecture :: T.Text -> T.Text -> T.Text -> IO (Maybe Lecture) returnLecture lowerStr sect session = runSqlite databasePath $ do maybeEntityLectures <- selectFirst [LectureCode ==. T.toUpper lowerStr, LectureSection ==. sect, LectureSession ==. session] [] return $ fmap entityVal maybeEntityLectures -- | Builds a Course structure from a tuple from the Courses table. -- Some fields still need to be added in. buildCourse :: Maybe Session -> Maybe Session -> Maybe Session -> Courses -> Course buildCourse fallSession springSession yearSession course = Course (coursesBreadth course) (coursesDescription course) (coursesTitle course) (coursesPrereqString course) fallSession springSession yearSession (coursesCode course) (coursesExclusions course) (coursesManualTutorialEnrolment course) (coursesManualPracticalEnrolment course) (coursesDistribution course) (coursesPrereqs course) (coursesCoreqs course) (coursesVideoUrls course) -- | Builds a Session structure from a list of tuples from the Lecture table, -- and a list of tuples from the Tutorial table. buildSession :: [Entity Lecture] -> [Entity Tutorial] -> Maybe Tables.Session buildSession lecs tuts = Just $ Tables.Session (map entityVal lecs) (map entityVal tuts) -- ** Other queries -- | Builds a list of all course codes in the database. allCourses :: IO Response allCourses = do response <- runSqlite databasePath $ do courses :: [Entity Courses] <- selectList [] [] let codes = map (coursesCode . entityVal) courses return $ T.unlines codes return $ toResponse response -- | Returns all course info for a given department. courseInfo :: String -> ServerPart Response courseInfo dept = liftM createJSONResponse (getDeptCourses dept) -- | Returns all course info for a given department. getDeptCourses :: MonadIO m => String -> m [Course] getDeptCourses dept = liftIO $ runSqlite databasePath $ do courses :: [Entity Courses] <- selectList [] [] lecs :: [Entity Lecture] <- selectList [] [] tuts :: [Entity Tutorial] <- selectList [] [] let c = filter (startswith dept . T.unpack . coursesCode) $ map entityVal courses return $ map (buildTimes (map entityVal lecs) (map entityVal tuts)) c where lecByCode course = filter (\lec -> lectureCode lec == coursesCode course) tutByCode course = filter (\tut -> tutorialCode tut == coursesCode course) buildTimes lecs tuts course = let fallLectures = filter (\lec -> lectureSession lec == "F") lecs springLectures = filter (\lec -> lectureSession lec == "S") lecs yearLectures = filter (\lec -> lectureSession lec == "Y") lecs fallTutorials = filter (\tut -> tutorialSession tut == "F") tuts springTutorials = filter (\tut -> tutorialSession tut == "S") tuts yearTutorials = filter (\tut -> tutorialSession tut == "Y") tuts fallSession = buildSession' (lecByCode course fallLectures) (tutByCode course fallTutorials) springSession = buildSession' (lecByCode course springLectures) (tutByCode course springTutorials) yearSession = buildSession' (lecByCode course yearLectures) (tutByCode course yearTutorials) in buildCourse fallSession springSession yearSession course buildSession' lecs tuts = Just $ Tables.Session lecs tuts -- | Return a list of all departments. deptList :: IO Response deptList = do depts <- runSqlite databasePath $ do courses :: [Entity Courses] <- selectList [] [] return $ sort . nub $ map g courses return $ createJSONResponse depts where g = take 3 . T.unpack . coursesCode . entityVal -- | Queries the graphs table and returns a JSON response of Graph JSON -- objects. queryGraphs :: IO Response queryGraphs = runSqlite databasePath $ do graphs :: [Entity Graph] <- selectList [] [] return $ createJSONResponse graphs
tamaralipowski/courseography
hs/Database/CourseQueries.hs
gpl-3.0
7,938
0
16
1,993
1,840
925
915
131
2
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[SimplUtils]{The simplifier utilities} -} {-# LANGUAGE CPP #-} module SimplUtils ( -- Rebuilding mkLam, mkCase, prepareAlts, tryEtaExpandRhs, -- Inlining, preInlineUnconditionally, postInlineUnconditionally, activeUnfolding, activeRule, getUnfoldingInRuleMatch, simplEnvForGHCi, updModeForStableUnfoldings, updModeForRules, -- The continuation type SimplCont(..), DupFlag(..), isSimplified, contIsDupable, contResultType, contHoleType, contIsTrivial, contArgs, countValArgs, countArgs, mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg, interestingCallContext, -- ArgInfo ArgInfo(..), ArgSpec(..), mkArgInfo, addValArgTo, addCastTo, addTyArgTo, argInfoExpr, argInfoAppArgs, pushSimplifiedArgs, abstractFloats ) where #include "HsVersions.h" import SimplEnv import CoreMonad ( SimplifierMode(..), Tick(..) ) import DynFlags import CoreSyn import qualified CoreSubst import PprCore import CoreFVs import CoreUtils import CoreArity import CoreUnfold import Name import Id import Var import Demand import SimplMonad import Type hiding( substTy ) import Coercion hiding( substCo ) import DataCon ( dataConWorkId ) import VarEnv import VarSet import BasicTypes import Util import MonadUtils import Outputable import Pair import Control.Monad ( when ) {- ************************************************************************ * * The SimplCont and DupFlag types * * ************************************************************************ A SimplCont allows the simplifier to traverse the expression in a zipper-like fashion. The SimplCont represents the rest of the expression, "above" the point of interest. You can also think of a SimplCont as an "evaluation context", using that term in the way it is used for operational semantics. This is the way I usually think of it, For example you'll often see a syntax for evaluation context looking like C ::= [] | C e | case C of alts | C `cast` co That's the kind of thing we are doing here, and I use that syntax in the comments. Key points: * A SimplCont describes a *strict* context (just like evaluation contexts do). E.g. Just [] is not a SimplCont * A SimplCont describes a context that *does not* bind any variables. E.g. \x. [] is not a SimplCont -} data SimplCont = Stop -- An empty context, or <hole> OutType -- Type of the <hole> CallCtxt -- Tells if there is something interesting about -- the context, and hence the inliner -- should be a bit keener (see interestingCallContext) -- Specifically: -- This is an argument of a function that has RULES -- Inlining the call might allow the rule to fire -- Never ValAppCxt (use ApplyToVal instead) -- or CaseCtxt (use Select instead) | CastIt -- <hole> `cast` co OutCoercion -- The coercion simplified -- Invariant: never an identity coercion SimplCont | ApplyToVal { -- <hole> arg sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_arg :: InExpr, -- The argument, sc_env :: StaticEnv, -- and its static env sc_cont :: SimplCont } | ApplyToTy { -- <hole> ty sc_arg_ty :: OutType, -- Argument type sc_hole_ty :: OutType, -- Type of the function, presumably (forall a. blah) -- See Note [The hole type in ApplyToTy] sc_cont :: SimplCont } | Select { -- case <hole> of alts sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_bndr :: InId, -- case binder sc_alts :: [InAlt], -- Alternatives sc_env :: StaticEnv, -- and their static environment sc_cont :: SimplCont } -- The two strict forms have no DupFlag, because we never duplicate them | StrictBind -- (\x* \xs. e) <hole> InId [InBndr] -- let x* = <hole> in e InExpr StaticEnv -- is a special case SimplCont | StrictArg -- f e1 ..en <hole> ArgInfo -- Specifies f, e1..en, Whether f has rules, etc -- plus strictness flags for *further* args CallCtxt -- Whether *this* argument position is interesting SimplCont | TickIt (Tickish Id) -- Tick tickish <hole> SimplCont data DupFlag = NoDup -- Unsimplified, might be big | Simplified -- Simplified | OkToDup -- Simplified and small isSimplified :: DupFlag -> Bool isSimplified NoDup = False isSimplified _ = True -- Invariant: the subst-env is empty perhapsSubstTy :: DupFlag -> StaticEnv -> Type -> Type perhapsSubstTy dup env ty | isSimplified dup = ty | otherwise = substTy env ty {- Note [DupFlag invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~ In both (ApplyToVal dup _ env k) and (Select dup _ _ env k) the following invariants hold (a) if dup = OkToDup, then continuation k is also ok-to-dup (b) if dup = OkToDup or Simplified, the subst-env is empty (and and hence no need to re-simplify) -} instance Outputable DupFlag where ppr OkToDup = text "ok" ppr NoDup = text "nodup" ppr Simplified = text "simpl" instance Outputable SimplCont where ppr (Stop ty interesting) = text "Stop" <> brackets (ppr interesting) <+> ppr ty ppr (CastIt co cont ) = (text "CastIt" <+> ppr co) $$ ppr cont ppr (TickIt t cont) = (text "TickIt" <+> ppr t) $$ ppr cont ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont }) = (text "ApplyToTy" <+> pprParendType ty) $$ ppr cont ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont }) = (text "ApplyToVal" <+> ppr dup <+> pprParendExpr arg) $$ ppr cont ppr (StrictBind b _ _ _ cont) = (text "StrictBind" <+> ppr b) $$ ppr cont ppr (StrictArg ai _ cont) = (text "StrictArg" <+> ppr (ai_fun ai)) $$ ppr cont ppr (Select { sc_dup = dup, sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont }) = (text "Select" <+> ppr dup <+> ppr bndr) $$ ifPprDebug (nest 2 $ vcat [ppr (seTvSubst se), ppr alts]) $$ ppr cont {- Note [The hole type in ApplyToTy] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sc_hole_ty field of ApplyToTy records the type of the "hole" in the continuation. It is absolutely necessary to compute contHoleType, but it is not used for anything else (and hence may not be evaluated). Why is it necessary for contHoleType? Consider the continuation ApplyToType Int (Stop Int) corresponding to (<hole> @Int) :: Int What is the type of <hole>? It could be (forall a. Int) or (forall a. a), and there is no way to know which, so we must record it. In a chain of applications (f @t1 @t2 @t3) we'll lazily compute exprType for (f @t1) and (f @t1 @t2), which is potentially non-linear; but it probably doesn't matter because we'll never compute them all. ************************************************************************ * * ArgInfo and ArgSpec * * ************************************************************************ -} data ArgInfo = ArgInfo { ai_fun :: OutId, -- The function ai_args :: [ArgSpec], -- ...applied to these args (which are in *reverse* order) ai_type :: OutType, -- Type of (f a1 ... an) ai_rules :: [CoreRule], -- Rules for this function ai_encl :: Bool, -- Flag saying whether this function -- or an enclosing one has rules (recursively) -- True => be keener to inline in all args ai_strs :: [Bool], -- Strictness of remaining arguments -- Usually infinite, but if it is finite it guarantees -- that the function diverges after being given -- that number of args ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline -- Always infinite } data ArgSpec = ValArg OutExpr -- Apply to this (coercion or value); c.f. ApplyToVal | TyArg { as_arg_ty :: OutType -- Apply to this type; c.f. ApplyToTy , as_hole_ty :: OutType } -- Type of the function (presumably forall a. blah) | CastBy OutCoercion -- Cast by this; c.f. CastIt instance Outputable ArgSpec where ppr (ValArg e) = text "ValArg" <+> ppr e ppr (TyArg { as_arg_ty = ty }) = text "TyArg" <+> ppr ty ppr (CastBy c) = text "CastBy" <+> ppr c addValArgTo :: ArgInfo -> OutExpr -> ArgInfo addValArgTo ai arg = ai { ai_args = ValArg arg : ai_args ai , ai_type = applyTypeToArg (ai_type ai) arg } addTyArgTo :: ArgInfo -> OutType -> ArgInfo addTyArgTo ai arg_ty = ai { ai_args = arg_spec : ai_args ai , ai_type = piResultTy poly_fun_ty arg_ty } where poly_fun_ty = ai_type ai arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = poly_fun_ty } addCastTo :: ArgInfo -> OutCoercion -> ArgInfo addCastTo ai co = ai { ai_args = CastBy co : ai_args ai , ai_type = pSnd (coercionKind co) } argInfoAppArgs :: [ArgSpec] -> [OutExpr] argInfoAppArgs [] = [] argInfoAppArgs (CastBy {} : _) = [] -- Stop at a cast argInfoAppArgs (ValArg e : as) = e : argInfoAppArgs as argInfoAppArgs (TyArg { as_arg_ty = ty } : as) = Type ty : argInfoAppArgs as pushSimplifiedArgs :: SimplEnv -> [ArgSpec] -> SimplCont -> SimplCont pushSimplifiedArgs _env [] k = k pushSimplifiedArgs env (arg : args) k = case arg of TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } -> ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = rest } ValArg e -> ApplyToVal { sc_arg = e, sc_env = env, sc_dup = Simplified, sc_cont = rest } CastBy c -> CastIt c rest where rest = pushSimplifiedArgs env args k -- The env has an empty SubstEnv argInfoExpr :: OutId -> [ArgSpec] -> OutExpr -- NB: the [ArgSpec] is reversed so that the first arg -- in the list is the last one in the application argInfoExpr fun rev_args = go rev_args where go [] = Var fun go (ValArg a : as) = go as `App` a go (TyArg { as_arg_ty = ty } : as) = go as `App` Type ty go (CastBy co : as) = mkCast (go as) co {- ************************************************************************ * * Functions on SimplCont * * ************************************************************************ -} mkBoringStop :: OutType -> SimplCont mkBoringStop ty = Stop ty BoringCtxt mkRhsStop :: OutType -> SimplCont -- See Note [RHS of lets] in CoreUnfold mkRhsStop ty = Stop ty RhsCtxt mkLazyArgStop :: OutType -> CallCtxt -> SimplCont mkLazyArgStop ty cci = Stop ty cci ------------------- contIsRhsOrArg :: SimplCont -> Bool contIsRhsOrArg (Stop {}) = True contIsRhsOrArg (StrictBind {}) = True contIsRhsOrArg (StrictArg {}) = True contIsRhsOrArg _ = False contIsRhs :: SimplCont -> Bool contIsRhs (Stop _ RhsCtxt) = True contIsRhs _ = False ------------------- contIsDupable :: SimplCont -> Bool contIsDupable (Stop {}) = True contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k contIsDupable (ApplyToVal { sc_dup = OkToDup }) = True -- See Note [DupFlag invariants] contIsDupable (Select { sc_dup = OkToDup }) = True -- ...ditto... contIsDupable (CastIt _ k) = contIsDupable k contIsDupable _ = False ------------------- contIsTrivial :: SimplCont -> Bool contIsTrivial (Stop {}) = True contIsTrivial (ApplyToTy { sc_cont = k }) = contIsTrivial k contIsTrivial (ApplyToVal { sc_arg = Coercion _, sc_cont = k }) = contIsTrivial k contIsTrivial (CastIt _ k) = contIsTrivial k contIsTrivial _ = False ------------------- contResultType :: SimplCont -> OutType contResultType (Stop ty _) = ty contResultType (CastIt _ k) = contResultType k contResultType (StrictBind _ _ _ _ k) = contResultType k contResultType (StrictArg _ _ k) = contResultType k contResultType (Select { sc_cont = k }) = contResultType k contResultType (ApplyToTy { sc_cont = k }) = contResultType k contResultType (ApplyToVal { sc_cont = k }) = contResultType k contResultType (TickIt _ k) = contResultType k contHoleType :: SimplCont -> OutType contHoleType (Stop ty _) = ty contHoleType (TickIt _ k) = contHoleType k contHoleType (CastIt co _) = pFst (coercionKind co) contHoleType (StrictBind b _ _ se _) = substTy se (idType b) contHoleType (StrictArg ai _ _) = funArgTy (ai_type ai) contHoleType (ApplyToTy { sc_hole_ty = ty }) = ty -- See Note [The hole type in ApplyToTy] contHoleType (ApplyToVal { sc_arg = e, sc_env = se, sc_dup = dup, sc_cont = k }) = mkFunTy (perhapsSubstTy dup se (exprType e)) (contHoleType k) contHoleType (Select { sc_dup = d, sc_bndr = b, sc_env = se }) = perhapsSubstTy d se (idType b) ------------------- countValArgs :: SimplCont -> Int -- Count value arguments excluding coercions countValArgs (ApplyToVal { sc_arg = arg, sc_cont = cont }) | Coercion {} <- arg = countValArgs cont | otherwise = 1 + countValArgs cont countValArgs _ = 0 countArgs :: SimplCont -> Int -- Count all arguments, including types, coercions, and other values countArgs (ApplyToTy { sc_cont = cont }) = 1 + countArgs cont countArgs (ApplyToVal { sc_cont = cont }) = 1 + countArgs cont countArgs _ = 0 contArgs :: SimplCont -> (Bool, [ArgSummary], SimplCont) -- Summarises value args, discards type args and coercions -- The returned continuation of the call is only used to -- answer questions like "are you interesting?" contArgs cont | lone cont = (True, [], cont) | otherwise = go [] cont where lone (ApplyToTy {}) = False -- See Note [Lone variables] in CoreUnfold lone (ApplyToVal {}) = False lone (CastIt {}) = False lone _ = True go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k }) = go (is_interesting arg se : args) k go args (ApplyToTy { sc_cont = k }) = go args k go args (CastIt _ k) = go args k go args k = (False, reverse args, k) is_interesting arg se = interestingArg se arg -- Do *not* use short-cutting substitution here -- because we want to get as much IdInfo as possible ------------------- mkArgInfo :: Id -> [CoreRule] -- Rules for function -> Int -- Number of value args -> SimplCont -- Context of the call -> ArgInfo mkArgInfo fun rules n_val_args call_cont | n_val_args < idArity fun -- Note [Unsaturated functions] = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules, ai_encl = False , ai_strs = vanilla_stricts , ai_discs = vanilla_discounts } | otherwise = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules , ai_encl = interestingArgContext rules call_cont , ai_strs = add_type_str fun_ty arg_stricts , ai_discs = arg_discounts } where fun_ty = idType fun vanilla_discounts, arg_discounts :: [Int] vanilla_discounts = repeat 0 arg_discounts = case idUnfolding fun of CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}} -> discounts ++ vanilla_discounts _ -> vanilla_discounts vanilla_stricts, arg_stricts :: [Bool] vanilla_stricts = repeat False arg_stricts = case splitStrictSig (idStrictness fun) of (demands, result_info) | not (demands `lengthExceeds` n_val_args) -> -- Enough args, use the strictness given. -- For bottoming functions we used to pretend that the arg -- is lazy, so that we don't treat the arg as an -- interesting context. This avoids substituting -- top-level bindings for (say) strings into -- calls to error. But now we are more careful about -- inlining lone variables, so its ok (see SimplUtils.analyseCont) if isBotRes result_info then map isStrictDmd demands -- Finite => result is bottom else map isStrictDmd demands ++ vanilla_stricts | otherwise -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) <+> ppr n_val_args <+> ppr demands ) vanilla_stricts -- Not enough args, or no strictness add_type_str :: Type -> [Bool] -> [Bool] -- If the function arg types are strict, record that in the 'strictness bits' -- No need to instantiate because unboxed types (which dominate the strict -- types) can't instantiate type variables. -- add_type_str is done repeatedly (for each call); might be better -- once-for-all in the function -- But beware primops/datacons with no strictness add_type_str _ [] = [] add_type_str fun_ty strs -- Look through foralls | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions = add_type_str fun_ty' strs add_type_str fun_ty (str:strs) -- Add strict-type info | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty = (str || isStrictType arg_ty) : add_type_str fun_ty' strs add_type_str _ strs = strs {- Note [Unsaturated functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (test eyeball/inline4) x = a:as y = f x where f has arity 2. Then we do not want to inline 'x', because it'll just be floated out again. Even if f has lots of discounts on its first argument -- it must be saturated for these to kick in -} {- ************************************************************************ * * Interesting arguments * * ************************************************************************ Note [Interesting call context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to avoid inlining an expression where there can't possibly be any gain, such as in an argument position. Hence, if the continuation is interesting (eg. a case scrutinee, application etc.) then we inline, otherwise we don't. Previously some_benefit used to return True only if the variable was applied to some value arguments. This didn't work: let x = _coerce_ (T Int) Int (I# 3) in case _coerce_ Int (T Int) x of I# y -> .... we want to inline x, but can't see that it's a constructor in a case scrutinee position, and some_benefit is False. Another example: dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t) .... case dMonadST _@_ x0 of (a,b,c) -> .... we'd really like to inline dMonadST here, but we *don't* want to inline if the case expression is just case x of y { DEFAULT -> ... } since we can just eliminate this case instead (x is in WHNF). Similar applies when x is bound to a lambda expression. Hence contIsInteresting looks for case expressions with just a single default case. -} interestingCallContext :: SimplCont -> CallCtxt -- See Note [Interesting call context] interestingCallContext cont = interesting cont where interesting (Select {}) = CaseCtxt interesting (ApplyToVal {}) = ValAppCtxt -- Can happen if we have (f Int |> co) y -- If f has an INLINE prag we need to give it some -- motivation to inline. See Note [Cast then apply] -- in CoreUnfold interesting (StrictArg _ cci _) = cci interesting (StrictBind {}) = BoringCtxt interesting (Stop _ cci) = cci interesting (TickIt _ k) = interesting k interesting (ApplyToTy { sc_cont = k }) = interesting k interesting (CastIt _ k) = interesting k -- If this call is the arg of a strict function, the context -- is a bit interesting. If we inline here, we may get useful -- evaluation information to avoid repeated evals: e.g. -- x + (y * z) -- Here the contIsInteresting makes the '*' keener to inline, -- which in turn exposes a constructor which makes the '+' inline. -- Assuming that +,* aren't small enough to inline regardless. -- -- It's also very important to inline in a strict context for things -- like -- foldr k z (f x) -- Here, the context of (f x) is strict, and if f's unfolding is -- a build it's *great* to inline it here. So we must ensure that -- the context for (f x) is not totally uninteresting. interestingArgContext :: [CoreRule] -> SimplCont -> Bool -- If the argument has form (f x y), where x,y are boring, -- and f is marked INLINE, then we don't want to inline f. -- But if the context of the argument is -- g (f x y) -- where g has rules, then we *do* want to inline f, in case it -- exposes a rule that might fire. Similarly, if the context is -- h (g (f x x)) -- where h has rules, then we do want to inline f; hence the -- call_cont argument to interestingArgContext -- -- The ai-rules flag makes this happen; if it's -- set, the inliner gets just enough keener to inline f -- regardless of how boring f's arguments are, if it's marked INLINE -- -- The alternative would be to *always* inline an INLINE function, -- regardless of how boring its context is; but that seems overkill -- For example, it'd mean that wrapper functions were always inlined -- -- The call_cont passed to interestingArgContext is the context of -- the call itself, e.g. g <hole> in the example above interestingArgContext rules call_cont = notNull rules || enclosing_fn_has_rules where enclosing_fn_has_rules = go call_cont go (Select {}) = False go (ApplyToVal {}) = False -- Shouldn't really happen go (ApplyToTy {}) = False -- Ditto go (StrictArg _ cci _) = interesting cci go (StrictBind {}) = False -- ?? go (CastIt _ c) = go c go (Stop _ cci) = interesting cci go (TickIt _ c) = go c interesting RuleArgCtxt = True interesting _ = False {- Note [Interesting arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An argument is interesting if it deserves a discount for unfoldings with a discount in that argument position. The idea is to avoid unfolding a function that is applied only to variables that have no unfolding (i.e. they are probably lambda bound): f x y z There is little point in inlining f here. Generally, *values* (like (C a b) and (\x.e)) deserve discounts. But we must look through lets, eg (let x = e in C a b), because the let will float, exposing the value, if we inline. That makes it different to exprIsHNF. Before 2009 we said it was interesting if the argument had *any* structure at all; i.e. (hasSomeUnfolding v). But does too much inlining; see Trac #3016. But we don't regard (f x y) as interesting, unless f is unsaturated. If it's saturated and f hasn't inlined, then it's probably not going to now! Note [Conlike is interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f d = ...((*) d x y)... ... f (df d')... where df is con-like. Then we'd really like to inline 'f' so that the rule for (*) (df d) can fire. To do this a) we give a discount for being an argument of a class-op (eg (*) d) b) we say that a con-like argument (eg (df d)) is interesting -} interestingArg :: SimplEnv -> CoreExpr -> ArgSummary -- See Note [Interesting arguments] interestingArg env e = go env 0 e where -- n is # value args to which the expression is applied go env n (Var v) | SimplEnv { seIdSubst = ids, seInScope = in_scope } <- env = case lookupVarEnv ids v of Nothing -> go_var n (refineFromInScope in_scope v) Just (DoneId v') -> go_var n (refineFromInScope in_scope v') Just (DoneEx e) -> go (zapSubstEnv env) n e Just (ContEx tvs cvs ids e) -> go (setSubstEnv env tvs cvs ids) n e go _ _ (Lit {}) = ValueArg go _ _ (Type _) = TrivArg go _ _ (Coercion _) = TrivArg go env n (App fn (Type _)) = go env n fn go env n (App fn _) = go env (n+1) fn go env n (Tick _ a) = go env n a go env n (Cast e _) = go env n e go env n (Lam v e) | isTyVar v = go env n e | n>0 = NonTrivArg -- (\x.b) e is NonTriv | otherwise = ValueArg go _ _ (Case {}) = NonTrivArg go env n (Let b e) = case go env' n e of ValueArg -> ValueArg _ -> NonTrivArg where env' = env `addNewInScopeIds` bindersOf b go_var n v | isConLikeId v = ValueArg -- Experimenting with 'conlike' rather that -- data constructors here | idArity v > n = ValueArg -- Catches (eg) primops with arity but no unfolding | n > 0 = NonTrivArg -- Saturated or unknown call | conlike_unfolding = ValueArg -- n==0; look for an interesting unfolding -- See Note [Conlike is interesting] | otherwise = TrivArg -- n==0, no useful unfolding where conlike_unfolding = isConLikeUnfolding (idUnfolding v) {- ************************************************************************ * * SimplifierMode * * ************************************************************************ The SimplifierMode controls several switches; see its definition in CoreMonad sm_rules :: Bool -- Whether RULES are enabled sm_inline :: Bool -- Whether inlining is enabled sm_case_case :: Bool -- Whether case-of-case is enabled sm_eta_expand :: Bool -- Whether eta-expansion is enabled -} simplEnvForGHCi :: DynFlags -> SimplEnv simplEnvForGHCi dflags = mkSimplEnv $ SimplMode { sm_names = ["GHCi"] , sm_phase = InitialPhase , sm_rules = rules_on , sm_inline = False , sm_eta_expand = eta_expand_on , sm_case_case = True } where rules_on = gopt Opt_EnableRewriteRules dflags eta_expand_on = gopt Opt_DoLambdaEtaExpansion dflags -- Do not do any inlining, in case we expose some unboxed -- tuple stuff that confuses the bytecode interpreter updModeForStableUnfoldings :: Activation -> SimplifierMode -> SimplifierMode -- See Note [Simplifying inside stable unfoldings] updModeForStableUnfoldings inline_rule_act current_mode = current_mode { sm_phase = phaseFromActivation inline_rule_act , sm_inline = True , sm_eta_expand = False } -- For sm_rules, just inherit; sm_rules might be "off" -- because of -fno-enable-rewrite-rules where phaseFromActivation (ActiveAfter _ n) = Phase n phaseFromActivation _ = InitialPhase updModeForRules :: SimplifierMode -> SimplifierMode -- See Note [Simplifying rules] updModeForRules current_mode = current_mode { sm_phase = InitialPhase , sm_inline = False , sm_rules = False , sm_eta_expand = False } {- Note [Simplifying rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When simplifying a rule, refrain from any inlining or applying of other RULES. Doing anything to the LHS is plain confusing, because it means that what the rule matches is not what the user wrote. c.f. Trac #10595, and #10528. Moreover, inlining (or applying rules) on rule LHSs risks introducing Ticks into the LHS, which makes matching trickier. Trac #10665, #10745. Doing this to either side confounds tools like HERMIT, which seek to reason about and apply the RULES as originally written. See Trac #10829. Note [Inlining in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Something is inlined if (i) the sm_inline flag is on, AND (ii) the thing has an INLINE pragma, AND (iii) the thing is inlinable in the earliest phase. Example of why (iii) is important: {-# INLINE [~1] g #-} g = ... {-# INLINE f #-} f x = g (g x) If we were to inline g into f's inlining, then an importing module would never be able to do f e --> g (g e) ---> RULE fires because the stable unfolding for f has had g inlined into it. On the other hand, it is bad not to do ANY inlining into an stable unfolding, because then recursive knots in instance declarations don't get unravelled. However, *sometimes* SimplGently must do no call-site inlining at all (hence sm_inline = False). Before full laziness we must be careful not to inline wrappers, because doing so inhibits floating e.g. ...(case f x of ...)... ==> ...(case (case x of I# x# -> fw x#) of ...)... ==> ...(case x of I# x# -> case fw x# of ...)... and now the redex (f x) isn't floatable any more. The no-inlining thing is also important for Template Haskell. You might be compiling in one-shot mode with -O2; but when TH compiles a splice before running it, we don't want to use -O2. Indeed, we don't want to inline anything, because the byte-code interpreter might get confused about unboxed tuples and suchlike. Note [Simplifying inside stable unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We must take care with simplification inside stable unfoldings (which come from INLINE pragmas). First, consider the following example let f = \pq -> BIG in let g = \y -> f y y {-# INLINE g #-} in ...g...g...g...g...g... Now, if that's the ONLY occurrence of f, it might be inlined inside g, and thence copied multiple times when g is inlined. HENCE we treat any occurrence in a stable unfolding as a multiple occurrence, not a single one; see OccurAnal.addRuleUsage. Second, we do want *do* to some modest rules/inlining stuff in stable unfoldings, partly to eliminate senseless crap, and partly to break the recursive knots generated by instance declarations. However, suppose we have {-# INLINE <act> f #-} f = <rhs> meaning "inline f in phases p where activation <act>(p) holds". Then what inlinings/rules can we apply to the copy of <rhs> captured in f's stable unfolding? Our model is that literally <rhs> is substituted for f when it is inlined. So our conservative plan (implemented by updModeForStableUnfoldings) is this: ------------------------------------------------------------- When simplifying the RHS of an stable unfolding, set the phase to the phase in which the stable unfolding first becomes active ------------------------------------------------------------- That ensures that a) Rules/inlinings that *cease* being active before p will not apply to the stable unfolding, consistent with it being inlined in its *original* form in phase p. b) Rules/inlinings that only become active *after* p will not apply to the stable unfolding, again to be consistent with inlining the *original* rhs in phase p. For example, {-# INLINE f #-} f x = ...g... {-# NOINLINE [1] g #-} g y = ... {-# RULE h g = ... #-} Here we must not inline g into f's RHS, even when we get to phase 0, because when f is later inlined into some other module we want the rule for h to fire. Similarly, consider {-# INLINE f #-} f x = ...g... g y = ... and suppose that there are auto-generated specialisations and a strictness wrapper for g. The specialisations get activation AlwaysActive, and the strictness wrapper get activation (ActiveAfter 0). So the strictness wrepper fails the test and won't be inlined into f's stable unfolding. That means f can inline, expose the specialised call to g, so the specialisation rules can fire. A note about wrappers ~~~~~~~~~~~~~~~~~~~~~ It's also important not to inline a worker back into a wrapper. A wrapper looks like wraper = inline_me (\x -> ...worker... ) Normally, the inline_me prevents the worker getting inlined into the wrapper (initially, the worker's only call site!). But, if the wrapper is sure to be called, the strictness analyser will mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf continuation. -} activeUnfolding :: SimplEnv -> Id -> Bool activeUnfolding env | not (sm_inline mode) = active_unfolding_minimal | otherwise = case sm_phase mode of InitialPhase -> active_unfolding_gentle Phase n -> active_unfolding n where mode = getMode env getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv -- When matching in RULE, we want to "look through" an unfolding -- (to see a constructor) if *rules* are on, even if *inlinings* -- are not. A notable example is DFuns, which really we want to -- match in rules like (op dfun) in gentle mode. Another example -- is 'otherwise' which we want exprIsConApp_maybe to be able to -- see very early on getUnfoldingInRuleMatch env = (in_scope, id_unf) where in_scope = seInScope env mode = getMode env id_unf id | unf_is_active id = idUnfolding id | otherwise = NoUnfolding unf_is_active id | not (sm_rules mode) = active_unfolding_minimal id | otherwise = isActive (sm_phase mode) (idInlineActivation id) active_unfolding_minimal :: Id -> Bool -- Compuslory unfoldings only -- Ignore SimplGently, because we want to inline regardless; -- the Id has no top-level binding at all -- -- NB: we used to have a second exception, for data con wrappers. -- On the grounds that we use gentle mode for rule LHSs, and -- they match better when data con wrappers are inlined. -- But that only really applies to the trivial wrappers (like (:)), -- and they are now constructed as Compulsory unfoldings (in MkId) -- so they'll happen anyway. active_unfolding_minimal id = isCompulsoryUnfolding (realIdUnfolding id) active_unfolding :: PhaseNum -> Id -> Bool active_unfolding n id = isActiveIn n (idInlineActivation id) active_unfolding_gentle :: Id -> Bool -- Anything that is early-active -- See Note [Gentle mode] active_unfolding_gentle id = isInlinePragma prag && isEarlyActive (inlinePragmaActivation prag) -- NB: wrappers are not early-active where prag = idInlinePragma id ---------------------- activeRule :: SimplEnv -> Activation -> Bool -- Nothing => No rules at all activeRule env | not (sm_rules mode) = \_ -> False -- Rewriting is off | otherwise = isActive (sm_phase mode) where mode = getMode env {- ************************************************************************ * * preInlineUnconditionally * * ************************************************************************ preInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~ @preInlineUnconditionally@ examines a bndr to see if it is used just once in a completely safe way, so that it is safe to discard the binding inline its RHS at the (unique) usage site, REGARDLESS of how big the RHS might be. If this is the case we don't simplify the RHS first, but just inline it un-simplified. This is much better than first simplifying a perhaps-huge RHS and then inlining and re-simplifying it. Indeed, it can be at least quadratically better. Consider x1 = e1 x2 = e2[x1] x3 = e3[x2] ...etc... xN = eN[xN-1] We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc. This can happen with cascades of functions too: f1 = \x1.e1 f2 = \xs.e2[f1] f3 = \xs.e3[f3] ...etc... THE MAIN INVARIANT is this: ---- preInlineUnconditionally invariant ----- IF preInlineUnconditionally chooses to inline x = <rhs> THEN doing the inlining should not change the occurrence info for the free vars of <rhs> ---------------------------------------------- For example, it's tempting to look at trivial binding like x = y and inline it unconditionally. But suppose x is used many times, but this is the unique occurrence of y. Then inlining x would change y's occurrence info, which breaks the invariant. It matters: y might have a BIG rhs, which will now be dup'd at every occurrenc of x. Even RHSs labelled InlineMe aren't caught here, because there might be no benefit from inlining at the call site. [Sept 01] Don't unconditionally inline a top-level thing, because that can simply make a static thing into something built dynamically. E.g. x = (a,b) main = \s -> h x [Remember that we treat \s as a one-shot lambda.] No point in inlining x unless there is something interesting about the call site. But watch out: if you aren't careful, some useful foldr/build fusion can be lost (most notably in spectral/hartel/parstof) because the foldr didn't see the build. Doing the dynamic allocation isn't a big deal, in fact, but losing the fusion can be. But the right thing here seems to be to do a callSiteInline based on the fact that there is something interesting about the call site (it's strict). Hmm. That seems a bit fragile. Conclusion: inline top level things gaily until Phase 0 (the last phase), at which point don't. Note [pre/postInlineUnconditionally in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even in gentle mode we want to do preInlineUnconditionally. The reason is that too little clean-up happens if you don't inline use-once things. Also a bit of inlining is *good* for full laziness; it can expose constant sub-expressions. Example in spectral/mandel/Mandel.hs, where the mandelset function gets a useful let-float if you inline windowToViewport However, as usual for Gentle mode, do not inline things that are inactive in the intial stages. See Note [Gentle mode]. Note [Stable unfoldings and preInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas! Example {-# INLINE f #-} f :: Eq a => a -> a f x = ... fInt :: Int -> Int fInt = f Int dEqInt ...fInt...fInt...fInt... Here f occurs just once, in the RHS of fInt. But if we inline it there we'll lose the opportunity to inline at each of fInt's call sites. The INLINE pragma will only inline when the application is saturated for exactly this reason; and we don't want PreInlineUnconditionally to second-guess it. A live example is Trac #3736. c.f. Note [Stable unfoldings and postInlineUnconditionally] Note [Top-level bottoming Ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Don't inline top-level Ids that are bottoming, even if they are used just once, because FloatOut has gone to some trouble to extract them out. Inlining them won't make the program run faster! Note [Do not inline CoVars unconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Coercion variables appear inside coercions, and the RHS of a let-binding is a term (not a coercion) so we can't necessarily inline the latter in the former. -} preInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-ful bindings preInlineUnconditionally dflags env top_lvl bndr rhs | not active = False | isStableUnfolding (idUnfolding bndr) = False -- Note [Stable unfoldings and preInlineUnconditionally] | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids] | not (gopt Opt_SimplPreInlining dflags) = False | isCoVar bndr = False -- Note [Do not inline CoVars unconditionally] | otherwise = case idOccInfo bndr of IAmDead -> True -- Happens in ((\x.1) v) OneOcc in_lam True int_cxt -> try_once in_lam int_cxt _ -> False where mode = getMode env active = isActive (sm_phase mode) act -- See Note [pre/postInlineUnconditionally in gentle mode] act = idInlineActivation bndr try_once in_lam int_cxt -- There's one textual occurrence | not in_lam = isNotTopLevel top_lvl || early_phase | otherwise = int_cxt && canInlineInLam rhs -- Be very careful before inlining inside a lambda, because (a) we must not -- invalidate occurrence information, and (b) we want to avoid pushing a -- single allocation (here) into multiple allocations (inside lambda). -- Inlining a *function* with a single *saturated* call would be ok, mind you. -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok) -- where -- is_cheap = exprIsCheap rhs -- ok = is_cheap && int_cxt -- int_cxt The context isn't totally boring -- E.g. let f = \ab.BIG in \y. map f xs -- Don't want to substitute for f, because then we allocate -- its closure every time the \y is called -- But: let f = \ab.BIG in \y. map (f y) xs -- Now we do want to substitute for f, even though it's not -- saturated, because we're going to allocate a closure for -- (f y) every time round the loop anyhow. -- canInlineInLam => free vars of rhs are (Once in_lam) or Many, -- so substituting rhs inside a lambda doesn't change the occ info. -- Sadly, not quite the same as exprIsHNF. canInlineInLam (Lit _) = True canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e canInlineInLam _ = False -- not ticks. Counting ticks cannot be duplicated, and non-counting -- ticks around a Lam will disappear anyway. early_phase = case sm_phase mode of Phase 0 -> False _ -> True -- If we don't have this early_phase test, consider -- x = length [1,2,3] -- The full laziness pass carefully floats all the cons cells to -- top level, and preInlineUnconditionally floats them all back in. -- Result is (a) static allocation replaced by dynamic allocation -- (b) many simplifier iterations because this tickles -- a related problem; only one inlining per pass -- -- On the other hand, I have seen cases where top-level fusion is -- lost if we don't inline top level thing (e.g. string constants) -- Hence the test for phase zero (which is the phase for all the final -- simplifications). Until phase zero we take no special notice of -- top level things, but then we become more leery about inlining -- them. {- ************************************************************************ * * postInlineUnconditionally * * ************************************************************************ postInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~~ @postInlineUnconditionally@ decides whether to unconditionally inline a thing based on the form of its RHS; in particular if it has a trivial RHS. If so, we can inline and discard the binding altogether. NB: a loop breaker has must_keep_binding = True and non-loop-breakers only have *forward* references. Hence, it's safe to discard the binding NOTE: This isn't our last opportunity to inline. We're at the binding site right now, and we'll get another opportunity when we get to the ocurrence(s) Note that we do this unconditional inlining only for trival RHSs. Don't inline even WHNFs inside lambdas; doing so may simply increase allocation when the function is called. This isn't the last chance; see NOTE above. NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why? Because we don't even want to inline them into the RHS of constructor arguments. See NOTE above NB: At one time even NOINLINE was ignored here: if the rhs is trivial it's best to inline it anyway. We often get a=E; b=a from desugaring, with both a and b marked NOINLINE. But that seems incompatible with our new view that inlining is like a RULE, so I'm sticking to the 'active' story for now. -} postInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> OutId -- The binder (an InId would be fine too) -- (*not* a CoVar) -> OccInfo -- From the InId -> OutExpr -> Unfolding -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-ful bindings postInlineUnconditionally dflags env top_lvl bndr occ_info rhs unfolding | not active = False | isWeakLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline -- because it might be referred to "earlier" | isExportedId bndr = False | isStableUnfolding unfolding = False -- Note [Stable unfoldings and postInlineUnconditionally] | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally] | exprIsTrivial rhs = True | otherwise = case occ_info of -- The point of examining occ_info here is that for *non-values* -- that occur outside a lambda, the call-site inliner won't have -- a chance (because it doesn't know that the thing -- only occurs once). The pre-inliner won't have gotten -- it either, if the thing occurs in more than one branch -- So the main target is things like -- let x = f y in -- case v of -- True -> case x of ... -- False -> case x of ... -- This is very important in practice; e.g. wheel-seive1 doubles -- in allocation if you miss this out OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue -> smallEnoughToInline dflags unfolding -- Small enough to dup -- ToDo: consider discount on smallEnoughToInline if int_cxt is true -- -- NB: Do NOT inline arbitrarily big things, even if one_br is True -- Reason: doing so risks exponential behaviour. We simplify a big -- expression, inline it, and simplify it again. But if the -- very same thing happens in the big expression, we get -- exponential cost! -- PRINCIPLE: when we've already simplified an expression once, -- make sure that we only inline it if it's reasonably small. && (not in_lam || -- Outside a lambda, we want to be reasonably aggressive -- about inlining into multiple branches of case -- e.g. let x = <non-value> -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } -- Inlining can be a big win if C3 is the hot-spot, even if -- the uses in C1, C2 are not 'interesting' -- An example that gets worse if you add int_cxt here is 'clausify' (isCheapUnfolding unfolding && int_cxt)) -- isCheap => acceptable work duplication; in_lam may be true -- int_cxt to prevent us inlining inside a lambda without some -- good reason. See the notes on int_cxt in preInlineUnconditionally IAmDead -> True -- This happens; for example, the case_bndr during case of -- known constructor: case (a,b) of x { (p,q) -> ... } -- Here x isn't mentioned in the RHS, so we don't want to -- create the (dead) let-binding let x = (a,b) in ... _ -> False -- Here's an example that we don't handle well: -- let f = if b then Left (\x.BIG) else Right (\y.BIG) -- in \y. ....case f of {...} .... -- Here f is used just once, and duplicating the case work is fine (exprIsCheap). -- But -- - We can't preInlineUnconditionally because that woud invalidate -- the occ info for b. -- - We can't postInlineUnconditionally because the RHS is big, and -- that risks exponential behaviour -- - We can't call-site inline, because the rhs is big -- Alas! where active = isActive (sm_phase (getMode env)) (idInlineActivation bndr) -- See Note [pre/postInlineUnconditionally in gentle mode] {- Note [Top level and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't do postInlineUnconditionally for top-level things (even for ones that are trivial): * Doing so will inline top-level error expressions that have been carefully floated out by FloatOut. More generally, it might replace static allocation with dynamic. * Even for trivial expressions there's a problem. Consider {-# RULE "foo" forall (xs::[T]). reverse xs = ruggle xs #-} blah xs = reverse xs ruggle = sort In one simplifier pass we might fire the rule, getting blah xs = ruggle xs but in *that* simplifier pass we must not do postInlineUnconditionally on 'ruggle' because then we'll have an unbound occurrence of 'ruggle' If the rhs is trivial it'll be inlined by callSiteInline, and then the binding will be dead and discarded by the next use of OccurAnal * There is less point, because the main goal is to get rid of local bindings used in multiple case branches. * The inliner should inline trivial things at call sites anyway. Note [Stable unfoldings and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do not do postInlineUnconditionally if the Id has an stable unfolding, otherwise we lose the unfolding. Example -- f has stable unfolding with rhs (e |> co) -- where 'e' is big f = e |> co Then there's a danger we'll optimise to f' = e f = f' |> co and now postInlineUnconditionally, losing the stable unfolding on f. Now f' won't inline because 'e' is too big. c.f. Note [Stable unfoldings and preInlineUnconditionally] ************************************************************************ * * Rebuilding a lambda * * ************************************************************************ -} mkLam :: [OutBndr] -> OutExpr -> SimplCont -> SimplM OutExpr -- mkLam tries three things -- a) eta reduction, if that gives a trivial expression -- b) eta expansion [only if there are some value lambdas] mkLam [] body _cont = return body mkLam bndrs body cont = do { dflags <- getDynFlags ; mkLam' dflags bndrs body } where mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr mkLam' dflags bndrs (Cast body co) | not (any bad bndrs) -- Note [Casts and lambdas] = do { lam <- mkLam' dflags bndrs body ; return (mkCast lam (mkPiCos Representational bndrs co)) } where co_vars = tyCoVarsOfCo co bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars mkLam' dflags bndrs body@(Lam {}) = mkLam' dflags (bndrs ++ bndrs1) body1 where (bndrs1, body1) = collectBinders body mkLam' dflags bndrs (Tick t expr) | tickishFloatable t = mkTick t <$> mkLam' dflags bndrs expr mkLam' dflags bndrs body | gopt Opt_DoEtaReduction dflags , Just etad_lam <- tryEtaReduce bndrs body = do { tick (EtaReduction (head bndrs)) ; return etad_lam } | not (contIsRhs cont) -- See Note [Eta-expanding lambdas] , gopt Opt_DoLambdaEtaExpansion dflags , any isRuntimeVar bndrs , let body_arity = exprEtaExpandArity dflags body , body_arity > 0 = do { tick (EtaExpansion (head bndrs)) ; let res = mkLams bndrs (etaExpand body_arity body) ; traceSmpl "eta expand" (vcat [text "before" <+> ppr (mkLams bndrs body) , text "after" <+> ppr res]) ; return res } | otherwise = return (mkLams bndrs body) {- Note [Eta expanding lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In general we *do* want to eta-expand lambdas. Consider f (\x -> case x of (a,b) -> \s -> blah) where 's' is a state token, and hence can be eta expanded. This showed up in the code for GHc.IO.Handle.Text.hPutChar, a rather important function! The eta-expansion will never happen unless we do it now. (Well, it's possible that CorePrep will do it, but CorePrep only has a half-baked eta-expander that can't deal with casts. So it's much better to do it here.) However, when the lambda is let-bound, as the RHS of a let, we have a better eta-expander (in the form of tryEtaExpandRhs), so we don't bother to try expansion in mkLam in that case; hence the contIsRhs guard. Note [Casts and lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider (\x. (\y. e) `cast` g1) `cast` g2 There is a danger here that the two lambdas look separated, and the full laziness pass might float an expression to between the two. So this equation in mkLam' floats the g1 out, thus: (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1) where x:tx. In general, this floats casts outside lambdas, where (I hope) they might meet and cancel with some other cast: \x. e `cast` co ===> (\x. e) `cast` (tx -> co) /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co) /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co) (if not (g `in` co)) Notice that it works regardless of 'e'. Originally it worked only if 'e' was itself a lambda, but in some cases that resulted in fruitless iteration in the simplifier. A good example was when compiling Text.ParserCombinators.ReadPrec, where we had a definition like (\x. Get `cast` g) where Get is a constructor with nonzero arity. Then mkLam eta-expanded the Get, and the next iteration eta-reduced it, and then eta-expanded it again. Note also the side condition for the case of coercion binders. It does not make sense to transform /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g) because the latter is not well-kinded. ************************************************************************ * * Eta expansion * * ************************************************************************ -} tryEtaExpandRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (Arity, OutExpr) -- See Note [Eta-expanding at let bindings] tryEtaExpandRhs env bndr rhs = do { dflags <- getDynFlags ; (new_arity, new_rhs) <- try_expand dflags ; WARN( new_arity < old_id_arity, (text "Arity decrease:" <+> (ppr bndr <+> ppr old_id_arity <+> ppr old_arity <+> ppr new_arity) $$ ppr new_rhs) ) -- Note [Arity decrease] in Simplify return (new_arity, new_rhs) } where try_expand dflags | exprIsTrivial rhs = return (exprArity rhs, rhs) | sm_eta_expand (getMode env) -- Provided eta-expansion is on , let new_arity1 = findRhsArity dflags bndr rhs old_arity new_arity2 = idCallArity bndr new_arity = max new_arity1 new_arity2 , new_arity > old_arity -- And the current manifest arity isn't enough = do { tick (EtaExpansion bndr) ; return (new_arity, etaExpand new_arity rhs) } | otherwise = return (old_arity, rhs) old_arity = exprArity rhs -- See Note [Do not expand eta-expand PAPs] old_id_arity = idArity bndr {- Note [Eta-expanding at let bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now eta expand at let-bindings, which is where the payoff comes. The most significant thing is that we can do a simple arity analysis (in CoreArity.findRhsArity), which we can't do for free-floating lambdas One useful consequence of not eta-expanding lambdas is this example: genMap :: C a => ... {-# INLINE genMap #-} genMap f xs = ... myMap :: D a => ... {-# INLINE myMap #-} myMap = genMap Notice that 'genMap' should only inline if applied to two arguments. In the stable unfolding for myMap we'll have the unfolding (\d -> genMap Int (..d..)) We do not want to eta-expand to (\d f xs -> genMap Int (..d..) f xs) because then 'genMap' will inline, and it really shouldn't: at least as far as the programmer is concerned, it's not applied to two arguments! Note [Do not eta-expand PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to have old_arity = manifestArity rhs, which meant that we would eta-expand even PAPs. But this gives no particular advantage, and can lead to a massive blow-up in code size, exhibited by Trac #9020. Suppose we have a PAP foo :: IO () foo = returnIO () Then we can eta-expand do foo = (\eta. (returnIO () |> sym g) eta) |> g where g :: IO () ~ State# RealWorld -> (# State# RealWorld, () #) But there is really no point in doing this, and it generates masses of coercions and whatnot that eventually disappear again. For T9020, GHC allocated 6.6G beore, and 0.8G afterwards; and residency dropped from 1.8G to 45M. But note that this won't eta-expand, say f = \g -> map g Does it matter not eta-expanding such functions? I'm not sure. Perhaps strictness analysis will have less to bite on? ************************************************************************ * * \subsection{Floating lets out of big lambdas} * * ************************************************************************ Note [Floating and type abstraction] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: x = /\a. C e1 e2 We'd like to float this to y1 = /\a. e1 y2 = /\a. e2 x = /\a. C (y1 a) (y2 a) for the usual reasons: we want to inline x rather vigorously. You may think that this kind of thing is rare. But in some programs it is common. For example, if you do closure conversion you might get: data a :-> b = forall e. (e -> a -> b) :$ e f_cc :: forall a. a :-> a f_cc = /\a. (\e. id a) :$ () Now we really want to inline that f_cc thing so that the construction of the closure goes away. So I have elaborated simplLazyBind to understand right-hand sides that look like /\ a1..an. body and treat them specially. The real work is done in SimplUtils.abstractFloats, but there is quite a bit of plumbing in simplLazyBind as well. The same transformation is good when there are lets in the body: /\abc -> let(rec) x = e in b ==> let(rec) x' = /\abc -> let x = x' a b c in e in /\abc -> let x = x' a b c in b This is good because it can turn things like: let f = /\a -> letrec g = ... g ... in g into letrec g' = /\a -> ... g' a ... in let f = /\ a -> g' a which is better. In effect, it means that big lambdas don't impede let-floating. This optimisation is CRUCIAL in eliminating the junk introduced by desugaring mutually recursive definitions. Don't eliminate it lightly! [May 1999] If we do this transformation *regardless* then we can end up with some pretty silly stuff. For example, let st = /\ s -> let { x1=r1 ; x2=r2 } in ... in .. becomes let y1 = /\s -> r1 y2 = /\s -> r2 st = /\s -> ...[y1 s/x1, y2 s/x2] in .. Unless the "..." is a WHNF there is really no point in doing this. Indeed it can make things worse. Suppose x1 is used strictly, and is of the form x1* = case f y of { (a,b) -> e } If we abstract this wrt the tyvar we then can't do the case inline as we would normally do. That's why the whole transformation is part of the same process that floats let-bindings and constructor arguments out of RHSs. In particular, it is guarded by the doFloatFromRhs call in simplLazyBind. Note [Which type variables to abstract over] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Abstract only over the type variables free in the rhs wrt which the new binding is abstracted. Note that * The naive approach of abstracting wrt the tyvars free in the Id's /type/ fails. Consider: /\ a b -> let t :: (a,b) = (e1, e2) x :: a = fst t in ... Here, b isn't free in x's type, but we must nevertheless abstract wrt b as well, because t's type mentions b. Since t is floated too, we'd end up with the bogus: poly_t = /\ a b -> (e1, e2) poly_x = /\ a -> fst (poly_t a *b*) * We must do closeOverKinds. Example (Trac #10934): f = /\k (f:k->*) (a:k). let t = AccFailure @ (f a) in ... Here we want to float 't', but we must remember to abstract over 'k' as well, even though it is not explicitly mentioned in the RHS, otherwise we get t = /\ (f:k->*) (a:k). AccFailure @ (f a) which is obviously bogus. -} abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr) abstractFloats main_tvs body_env body = ASSERT( notNull body_floats ) do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats ; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) } where main_tv_set = mkVarSet main_tvs body_floats = getFloatBinds body_env empty_subst = CoreSubst.mkEmptySubst (seInScope body_env) abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind) abstract subst (NonRec id rhs) = do { (poly_id, poly_app) <- mk_poly tvs_here id ; let poly_rhs = mkLams tvs_here rhs' subst' = CoreSubst.extendIdSubst subst id poly_app ; return (subst', (NonRec poly_id poly_rhs)) } where rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs -- tvs_here: see Note [Which type variables to abstract over] tvs_here = varSetElemsWellScoped $ intersectVarSet main_tv_set $ closeOverKinds $ exprSomeFreeVars isTyVar rhs' abstract subst (Rec prs) = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps) poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs) | rhs <- rhss] ; return (subst', Rec (poly_ids `zip` poly_rhss)) } where (ids,rhss) = unzip prs -- For a recursive group, it's a bit of a pain to work out the minimal -- set of tyvars over which to abstract: -- /\ a b c. let x = ...a... in -- letrec { p = ...x...q... -- q = .....p...b... } in -- ... -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'. -- Since it's a pain, we just use the whole set, which is always safe -- -- If you ever want to be more selective, remember this bizarre case too: -- x::a = x -- Here, we must abstract 'x' over 'a'. tvs_here = toposortTyVars main_tvs mk_poly tvs_here var = do { uniq <- getUniqueM ; let poly_name = setNameUnique (idName var) uniq -- Keep same name poly_ty = mkInvForAllTys tvs_here (idType var) -- But new type of course poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.hs mkLocalIdOrCoVar poly_name poly_ty ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) } -- In the olden days, it was crucial to copy the occInfo of the original var, -- because we were looking at occurrence-analysed but as yet unsimplified code! -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking -- at already simplified code, so it doesn't matter -- -- It's even right to retain single-occurrence or dead-var info: -- Suppose we started with /\a -> let x = E in B -- where x occurs once in B. Then we transform to: -- let x' = /\a -> E in /\a -> let x* = x' a in B -- where x* has an INLINE prag on it. Now, once x* is inlined, -- the occurrences of x' will be just the occurrences originally -- pinned on x. {- Note [Abstract over coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the type variable a. Rather than sort this mess out, we simply bale out and abstract wrt all the type variables if any of them are coercion variables. Historical note: if you use let-bindings instead of a substitution, beware of this: -- Suppose we start with: -- -- x = /\ a -> let g = G in E -- -- Then we'll float to get -- -- x = let poly_g = /\ a -> G -- in /\ a -> let g = poly_g a in E -- -- But now the occurrence analyser will see just one occurrence -- of poly_g, not inside a lambda, so the simplifier will -- PreInlineUnconditionally poly_g back into g! Badk to square 1! -- (I used to think that the "don't inline lone occurrences" stuff -- would stop this happening, but since it's the *only* occurrence, -- PreInlineUnconditionally kicks in first!) -- -- Solution: put an INLINE note on g's RHS, so that poly_g seems -- to appear many times. (NB: mkInlineMe eliminates -- such notes on trivial RHSs, so do it manually.) ************************************************************************ * * prepareAlts * * ************************************************************************ prepareAlts tries these things: 1. Eliminate alternatives that cannot match, including the DEFAULT alternative. 2. If the DEFAULT alternative can match only one possible constructor, then make that constructor explicit. e.g. case e of x { DEFAULT -> rhs } ===> case e of x { (a,b) -> rhs } where the type is a single constructor type. This gives better code when rhs also scrutinises x or e. 3. Returns a list of the constructors that cannot holds in the DEFAULT alternative (if there is one) Here "cannot match" includes knowledge from GADTs It's a good idea to do this stuff before simplifying the alternatives, to avoid simplifying alternatives we know can't happen, and to come up with the list of constructors that are handled, to put into the IdInfo of the case binder, for use when simplifying the alternatives. Eliminating the default alternative in (1) isn't so obvious, but it can happen: data Colour = Red | Green | Blue f x = case x of Red -> .. Green -> .. DEFAULT -> h x h y = case y of Blue -> .. DEFAULT -> [ case y of ... ] If we inline h into f, the default case of the inlined h can't happen. If we don't notice this, we may end up filtering out *all* the cases of the inner case y, which give us nowhere to go! -} prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt]) -- The returned alternatives can be empty, none are possible prepareAlts scrut case_bndr' alts | Just (tc, tys) <- splitTyConApp_maybe (varType case_bndr') -- Case binder is needed just for its type. Note that as an -- OutId, it has maximum information; this is important. -- Test simpl013 is an example = do { us <- getUniquesM ; let (idcs1, alts1) = filterAlts tc tys imposs_cons alts (yes2, alts2) = refineDefaultAlt us tc tys idcs1 alts1 (yes3, idcs3, alts3) = combineIdenticalAlts idcs1 alts2 -- "idcs" stands for "impossible default data constructors" -- i.e. the constructors that can't match the default case ; when yes2 $ tick (FillInCaseDefault case_bndr') ; when yes3 $ tick (AltMerge case_bndr') ; return (idcs3, alts3) } | otherwise -- Not a data type, so nothing interesting happens = return ([], alts) where imposs_cons = case scrut of Var v -> otherCons (idUnfolding v) _ -> [] {- ************************************************************************ * * mkCase * * ************************************************************************ mkCase tries these things 1. Merge Nested Cases case e of b { ==> case e of b { p1 -> rhs1 p1 -> rhs1 ... ... pm -> rhsm pm -> rhsm _ -> case b of b' { pn -> let b'=b in rhsn pn -> rhsn ... ... po -> let b'=b in rhso po -> rhso _ -> let b'=b in rhsd _ -> rhsd } which merges two cases in one case when -- the default alternative of the outer case scrutises the same variable as the outer case. This transformation is called Case Merging. It avoids that the same variable is scrutinised multiple times. 2. Eliminate Identity Case case e of ===> e True -> True; False -> False and similar friends. -} mkCase, mkCase1, mkCase2 :: DynFlags -> OutExpr -> OutId -> OutType -> [OutAlt] -- Alternatives in standard (increasing) order -> SimplM OutExpr -------------------------------------------------- -- 1. Merge Nested Cases -------------------------------------------------- mkCase dflags scrut outer_bndr alts_ty ((DEFAULT, _, deflt_rhs) : outer_alts) | gopt Opt_CaseMerge dflags , (ticks, Case (Var inner_scrut_var) inner_bndr _ inner_alts) <- stripTicksTop tickishFloatable deflt_rhs , inner_scrut_var == outer_bndr = do { tick (CaseMerge outer_bndr) ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args ) (con, args, wrap_rhs rhs) -- Simplifier's no-shadowing invariant should ensure -- that outer_bndr is not shadowed by the inner patterns wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs -- The let is OK even for unboxed binders, wrapped_alts | isDeadBinder inner_bndr = inner_alts | otherwise = map wrap_alt inner_alts merged_alts = mergeAlts outer_alts wrapped_alts -- NB: mergeAlts gives priority to the left -- case x of -- A -> e1 -- DEFAULT -> case x of -- A -> e2 -- B -> e3 -- When we merge, we must ensure that e1 takes -- precedence over e2 as the value for A! ; fmap (mkTicks ticks) $ mkCase1 dflags scrut outer_bndr alts_ty merged_alts } -- Warning: don't call mkCase recursively! -- Firstly, there's no point, because inner alts have already had -- mkCase applied to them, so they won't have a case in their default -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr -- in munge_rhs may put a case into the DEFAULT branch! mkCase dflags scrut bndr alts_ty alts = mkCase1 dflags scrut bndr alts_ty alts -------------------------------------------------- -- 2. Eliminate Identity Case -------------------------------------------------- mkCase1 _dflags scrut case_bndr _ alts@((_,_,rhs1) : _) -- Identity case | all identity_alt alts = do { tick (CaseIdentity case_bndr) ; return (mkTicks ticks $ re_cast scrut rhs1) } where ticks = concatMap (stripTicksT tickishFloatable . thdOf3) (tail alts) identity_alt (con, args, rhs) = check_eq rhs con args check_eq (Cast rhs co) con args = not (any (`elemVarSet` tyCoVarsOfCo co) args) && check_eq rhs con args -- See Note [RHS casts] check_eq (Lit lit) (LitAlt lit') _ = lit == lit' check_eq (Var v) _ _ | v == case_bndr = True check_eq (Var v) (DataAlt con) [] = v == dataConWorkId con -- Optimisation only check_eq (Tick t e) alt args = tickishFloatable t && check_eq e alt args check_eq rhs (DataAlt con) args = cheapEqExpr' tickishFloatable rhs $ mkConApp con (arg_tys ++ varsToCoreExprs args) check_eq _ _ _ = False arg_tys = map Type (tyConAppArgs (idType case_bndr)) -- Note [RHS casts] -- ~~~~~~~~~~~~~~~~ -- We've seen this: -- case e of x { _ -> x `cast` c } -- And we definitely want to eliminate this case, to give -- e `cast` c -- So we throw away the cast from the RHS, and reconstruct -- it at the other end. All the RHS casts must be the same -- if (all identity_alt alts) holds. -- -- Don't worry about nested casts, because the simplifier combines them re_cast scrut (Cast rhs co) = Cast (re_cast scrut rhs) co re_cast scrut _ = scrut mkCase1 dflags scrut bndr alts_ty alts = mkCase2 dflags scrut bndr alts_ty alts -------------------------------------------------- -- Catch-all -------------------------------------------------- mkCase2 _dflags scrut bndr alts_ty alts = return (Case scrut bndr alts_ty alts) {- Note [Dead binders] ~~~~~~~~~~~~~~~~~~~~ Note that dead-ness is maintained by the simplifier, so that it is accurate after simplification as well as before. Note [Cascading case merge] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Case merging should cascade in one sweep, because it happens bottom-up case e of a { DEFAULT -> case a of b DEFAULT -> case b of c { DEFAULT -> e A -> ea B -> eb C -> ec ==> case e of a { DEFAULT -> case a of b DEFAULT -> let c = b in e A -> let c = b in ea B -> eb C -> ec ==> case e of a { DEFAULT -> let b = a in let c = b in e A -> let b = a in let c = b in ea B -> let b = a in eb C -> ec However here's a tricky case that we still don't catch, and I don't see how to catch it in one pass: case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... After occurrence analysis (and its binder-swap) we get this case x of c1 { I# a1 -> let x = c1 in -- Binder-swap addition case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... When we simplify the inner case x, we'll see that x=c1=I# a1. So we'll bind a2 to a1, and get case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case a1 of ... This is corect, but we can't do a case merge in this sweep because c2 /= a1. Reason: the binding c1=I# a1 went inwards without getting changed to c1=I# c2. I don't think this is worth fixing, even if I knew how. It'll all come out in the next pass anyway. -}
mcschroeder/ghc
compiler/simplCore/SimplUtils.hs
bsd-3-clause
79,744
0
18
24,371
8,416
4,497
3,919
-1
-1
module Language.Haskell.Liquid.Simplify (simplifyBounds) where import Language.Haskell.Liquid.Types import Language.Fixpoint.Types import Language.Fixpoint.Visitor -- import Control.Applicative ((<$>)) import Data.Monoid simplifyBounds :: SpecType -> SpecType simplifyBounds = fmap go where go x = x { ur_reft = go' $ ur_reft x } -- OLD go' (Reft (v, rs)) = Reft(v, filter (not . isBoundLike) rs) go' (Reft (v, Refa p)) = Reft(v, Refa $ dropBoundLike p) dropBoundLike :: Pred -> Pred dropBoundLike p | isKvar p = p | isBoundLikePred p = mempty | otherwise = p where isKvar = not . null . kvars isBoundLikePred :: Pred -> Bool isBoundLikePred (PAnd ps) = simplifyLen <= length [p | p <- ps, isImp p ] isBoundLikePred _ = False isImp :: Pred -> Bool isImp (PImp _ _) = True isImp _ = False -- OLD isBoundLike (RConc pred) = isBoundLikePred pred -- OLD isBoundLike (RKvar _ _) = False -- OLD moreThan 0 _ = True -- OLD moreThan _ [] = False -- OLD moreThan i (True : xs) = moreThan (i-1) xs -- OLD moreThan i (False : xs) = moreThan i xs simplifyLen :: Int simplifyLen = 5
mightymoose/liquidhaskell
src/Language/Haskell/Liquid/Simplify.hs
bsd-3-clause
1,197
0
11
315
287
155
132
23
1
module C4 where import D4 instance SameOrNot Double where isSameOrNot a b = a == b isNotSame a b = a /= b myFringe :: (Tree a) -> [a] myFringe (Leaf x) = [x] myFringe (Branch left right) = myFringe left
SAdams601/HaRe
old/testing/renaming/C4_AstOut.hs
bsd-3-clause
222
0
7
60
97
51
46
8
1
{-# LANGUAGE DataKinds, ExistentialQuantification, MagicHash, RankNTypes, TypeApplications #-} import GHC.Records (HasField(..)) data T = MkT { foo :: forall a . a -> a } data U = forall b . MkU { bar :: b } -- This should fail because foo is higher-rank. x = getField @"foo" (MkT id) -- This should fail because bar is a naughty record selector (it -- involves an existential). y = getField @"bar" (MkU True) main = return ()
ezyang/ghc
testsuite/tests/overloadedrecflds/should_fail/hasfieldfail02.hs
bsd-3-clause
445
0
10
95
109
62
47
8
1
module E where import System.IO.Unsafe a :: Int a = 1
urbanslug/ghc
testsuite/tests/safeHaskell/ghci/E.hs
bsd-3-clause
57
0
4
14
20
13
7
4
1
import Data.List extractABAs s | length s < 3 = [] | otherwise = if x == z && x /= y then (x, y) : extractABAs (tail s) else extractABAs (tail s) where [x, y, z] = take 3 s separate supernet hypernet buffer [] = (buffer : supernet, hypernet) separate supernet hypernet buffer (c:cs) | c == '[' = separate (buffer : supernet) hypernet "" cs | c == ']' = separate supernet (buffer : hypernet) "" cs | otherwise = separate supernet hypernet (c : buffer) cs supportSSL s = not . null $ allABAs supernet `intersect` map flip (allABAs hypernet) where (supernet, hypernet) = separate [] [] "" s allABAs = concatMap extractABAs flip (x, y) = (y, x) main = do input <- getContents print . length . filter id . map supportSSL . lines $ input
lzlarryli/advent_of_code_2016
day7/part2.hs
mit
788
0
11
198
367
184
183
21
2
import Control.Arrow import Data.List import Data.List.Split (|>) :: a -> (a -> b) -> b (|>) x y = y x infixl 0 |> main :: IO () main = do _ <- getLine interact $ readInts >>> solve >>> map show >>> intercalate "\n" solve :: [Integer] -> [Int] solve = iterate step >>> map length >>> takeWhile (>0) step :: [Integer] -> [Integer] step xs = map (subtract (minimum xs)) xs |> filter (>0) readInts :: String -> [Integer] readInts = splitOn " " >>> map read
Dobiasd/HackerRank-solutions
Algorithms/Warmup/Cut_the_sticks/Main.hs
mit
466
0
10
101
225
119
106
16
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} module Parser (parseSheet, expr, nfunc) where import System.Environment import Text.ParserCombinators.Parsec -- hiding (string) import Control.Applicative ((<*), (<$>), (<*>)) import Control.Monad (liftM) import Data.Array import Data.Char import Data.Map as M hiding (map, foldl) import Data.Maybe import Data.Either (rights) import Data.Either.Utils (fromRight) import Data.List import Data.Monoid import Data.Function import Sheet import Expr import Cell import Ref import Cat -- | Parse the user input stings to the CellFns in each cell parseSheet :: Sheet String -> Sheet CellFn parseSheet = fmap ((either (const $ sval "Parse error") id).(parse expr "")) expr :: Parser CellFn expr = do (try fexpr) <|> pstring -- | This is the exported parser. It parses one of a numerical, string or boolean expression fexpr :: Parser CellFn fexpr = do char '=' (try bexpr) <|> (try sexpr) <|> (nexpr) -- | Parse a numerical expression in parentheses parenNexpr:: Parser CellFn parenNexpr = do char '(' whitespace e <- nexpr char ')' return e -- | Parse a string expression in parentheses parenSexpr:: Parser CellFn parenSexpr = do char '(' whitespace e <- sexpr char ')' whitespace return e -- | Parse a boolean expression in parentheses parenBexpr:: Parser CellFn parenBexpr = do char '(' whitespace e <- bexpr char ')' whitespace return e -- | Parse a numerical expression nexpr :: Parser CellFn nexpr = do first <- mulTerm ops <- addOps return $ foldl buildExpr first ops where buildExpr acc ('+', x) = eadd acc x buildExpr acc ('-', x) = esub acc x -- | Parse a string expression sexpr:: Parser CellFn sexpr = do first <- sterm ops <- concatOps return $ foldl buildExpr first ops where buildExpr acc ('&', x) = econcat acc x -- | Parse a boolean expression bexpr :: Parser CellFn bexpr = do first <- andTerm ops <- orOps return $ foldl buildExpr first ops where buildExpr acc ('|', x) = eor acc x -- | Second level of numerical terms - after addition, before powers mulTerm:: Parser CellFn mulTerm = do first <- powTerm ops <- mulOps return $ foldl buildExpr first ops where buildExpr acc ('*', x) = emul acc x buildExpr acc ('/', x) = ediv acc x -- | Third level of numerical terms - after multiplication powTerm:: Parser CellFn powTerm = do first <- nterm ops <- powOps return $ foldl buildExpr first ops where buildExpr acc ('^', x) = epow acc x -- | Parse a built in numerical function, or a numerical terminal nfuncTerm :: Parser CellFn nfuncTerm = (try nfunc) <|> nterm -- | Parse the boolean AND terms andTerm:: Parser CellFn andTerm = do first <- compTerm ops <- andOps return $ foldl buildExpr first ops where buildExpr acc ('&', x) = eand acc x -- This is a comparison term eg 1>3, True=False, "Nick">"Straw" compTerm :: Parser CellFn compTerm = do (try bcomp) <|> (try scomp) <|> (try ncomp) <|> (try bterm) -- A Helper function for making the comparison terms applyCompOp :: Char -> CellFn -> CellFn -> CellFn applyCompOp '>' x y = egt x y applyCompOp '<' x y = elt x y applyCompOp '=' x y = eeq x y -- Numerical comparisons ncomp :: Parser CellFn ncomp = do x <- nterm; op <- compOp; y <- nterm; return $ applyCompOp op x y -- Boolean comparisons bcomp :: Parser CellFn bcomp = do x <- bterm; op <- compOp; y <- bterm; return $ applyCompOp op x y -- String comparisons scomp :: Parser CellFn scomp = do x <- sterm; op <- compOp; y <- sterm; return $ applyCompOp op x y addOps :: Parser [(Char, CellFn)] addOps = many addOp mulOps :: Parser [(Char, CellFn)] mulOps = many mulOp powOps :: Parser [(Char, CellFn)] powOps = many powOp orOps :: Parser [(Char, CellFn)] orOps = many orOp andOps :: Parser [(Char, CellFn)] andOps = many andOp concatOps :: Parser [(Char, CellFn)] concatOps = many concatOp addOp :: Parser (Char, CellFn) addOp = do op <- oneOf "+-" whitespace t <- mulTerm whitespace return (op, t) compOp :: Parser Char compOp = do op <- oneOf ">=<"; whitespace return op mulOp :: Parser (Char, CellFn) mulOp = do op <- oneOf "*/" whitespace t <- powTerm whitespace return (op, t) powOp :: Parser (Char, CellFn) powOp = do op <- oneOf "^" whitespace t <- nterm whitespace return (op, t) concatOp :: Parser (Char, CellFn) concatOp = do op <- oneOf "&" whitespace t <- sterm whitespace return (op, t) andOp :: Parser (Char, CellFn) andOp = do op <- string "&&" whitespace t <- compTerm -- bterm whitespace return (head op, t) orOp :: Parser (Char, CellFn) orOp = do op <- string "||" whitespace t <- andTerm -- bterm whitespace return (head op, t) nterm :: Parser CellFn nterm = do t <- term' whitespace return t where term' = (try $ number) <|> (try parenNexpr) <|> (try $ nfunc) <|> (try nRef) sterm :: Parser CellFn sterm = do t <- sterm' whitespace return t where sterm' = (try $ qstring) <|> (try parenSexpr) <|> (try $ sfunc) <|> (try sRef) bterm :: Parser CellFn bterm = do t <- bterm' whitespace return t where bterm' = (try $ pbool) <|> (try parenBexpr) <|> (try $ bfunc) <|> (try bRef) -- Quoted string qstring :: Parser CellFn qstring = do char '"' s <- manyTill (noneOf ("\"")) (char '"') whitespace return $ sval s pstring :: Parser CellFn pstring = do char '"' s <- manyTill (noneOf ("\"")) (char '"') whitespace return $ sval s s2b::String->Bool s2b s = if (map toUpper s)=="TRUE" then True else False pbool :: Parser CellFn pbool = do whitespace s <- string "True" <|> string "False"; return $ bval $ s2b s pDigit:: Parser Char pDigit = oneOf ['0'..'9'] pSign:: Parser Char pSign = option '+' $ oneOf "-+" pDigits:: Parser [Char] pDigits = many1 pDigit pDecimalPoint :: Parser Char pDecimalPoint = char '.' pFracPart :: Parser [Char] pFracPart = option "0" (pDecimalPoint >> pDigits) number :: Parser CellFn number = do sign <- pSign integerPart <- pDigits fracPart <- pFracPart expPart <- pExp let i = read integerPart let f = read fracPart let e = expPart let value = (i + (f / 10^(length fracPart))) * 10 ^^ e return $ nval $ case sign of '+' -> value '-' -> negate value where pExp = option 0 $ do oneOf "eE" sign <- pSign num <- pDigits let n = read num return $ if sign == '-' then negate n else n whitespace = many $ oneOf "\n\t\r\v " nfunc :: Parser CellFn nfunc = do fname <- manyTill letter (char '(') ps <- nexpr `sepBy` (char ',') char ')' return $ enfunc fname ps sfunc :: Parser CellFn sfunc = do char '@' fname <- manyTill letter (char '(') ps <- sexpr `sepBy` (char ',') char ')' return $ esfunc fname ps bfunc :: Parser CellFn bfunc = do char '@' fname <- manyTill letter (char '(') ps <- bexpr `sepBy` (char ',') char ')' return $ ebfunc fname ps pAbs:: Parser Char pAbs = char '$' pAlpha :: Parser Char pAlpha = oneOf "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" nRef :: Parser CellFn nRef = fmap eref pRef bRef :: Parser CellFn bRef = fmap eref pRef sRef :: Parser CellFn sRef = fmap eref pRef pRef :: Parser Ref pRef = try pAbsAbs <|> try pAbsRel <|> try pRelAbs <|> pRelRel -- So, A goes to 1, column counting starts at 1 u2i :: Char -> Int u2i c = ord (toUpper c) - 64 pAbsAbs :: Parser Ref pAbsAbs = do ac <- pAbs c <- pAlpha rc <- pAbs r <- pDigits return $ Ref (CAbs $ u2i c) (RAbs (read r)) pAbsRel :: Parser Ref pAbsRel = do ac <- pAbs c <- pAlpha r <- pDigits return $ Ref (CAbs $ u2i c) (RRel (read r)) pRelAbs :: Parser Ref pRelAbs = do c <- pAlpha rc <- pAbs r <- pDigits return $ Ref (CRel $ u2i c) (RAbs (read r)) pRelRel :: Parser Ref pRelRel = do c <- pAlpha r <- pDigits return $ Ref (CRel $ u2i c) (RRel (read r))
b1g3ar5/Spreadsheet
Parser.hs
mit
9,128
21
17
2,816
3,075
1,526
1,549
286
3
{-# LANGUAGE OverloadedStrings #-} module Chat where import Data.Aeson hiding (Success) import Control.Applicative ((<$>), (<*>)) import qualified Data.Text as T import qualified Network.WebSockets as WS import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar) import Control.Monad (forM_) import Types data ChatEvent = Enter T.Text | Leave T.Text | Message T.Text T.Text deriving (Show) instance ToJSON ChatEvent where toJSON (Enter login) = object ["event" .= ("enter" :: T.Text), "user" .= login] toJSON (Leave login) = object ["event" .= ("leave" :: T.Text), "user" .= login] toJSON (Message login msg) = object ["event" .= ("message" :: T.Text), "user" .= login, "message" .= msg] data MessageReq = MessageReq { mrText :: T.Text } instance FromJSON MessageReq where parseJSON (Object v) = MessageReq <$> v .: "message" sendToAll :: TVar ServerState -> ChatEvent -> IO () sendToAll st ev = do let msg = encode ev S { connections = conns } <- atomically $ readTVar st forM_ conns $ flip WS.sendTextData msg . snd
SPY/scotty-chat-sandbox
src/Chat.hs
mit
1,142
0
10
228
398
221
177
27
1
{- acid-state is a log-based storage, therefor correct ordering of transactions is a - key point to guarantee consistency. - To test the correctness of ordering we use a simple non-commutative - operation, as lined out in the following. -} import Test.QuickCheck ncOp1 :: Int -> Int -> Int ncOp1 x v = (x + v) `mod` v ncOp2 :: Char -> String -> String ncOp2 x v = x : v ncOp3 :: Int -> [Int] -> [Int] ncOp3 x v = x : v ncOp4 :: Int -> [Int] -> [Int] ncOp4 x v | length v < 20 = x : v | otherwise = x : shorten where shorten = reverse $ (r !! 1 - r !! 2 + r !! 3):drop 3 r r = reverse v ncOp = ncOp4 main :: IO () main = do verbCheck (\(v,x,y) -> x == y || ncOp x (ncOp y v) /= ncOp y (ncOp x v)) deepCheck (\(v,x,y) -> x == y || ncOp x (ncOp y v) /= ncOp y (ncOp x v)) verbCheck = verboseCheckWith stdArgs { maxSuccess = 5 } deepCheck = quickCheckWith stdArgs { maxSuccess = 5000 }
sdx23/acid-state-dist
test/NonCommutative.hs
mit
928
0
14
243
387
202
185
20
1
---------------------------------------------------------------- -- -- | Ascetic -- -- @Text\/Ascetic\/HTML.hs@ -- -- Wrappers for building HTML file represented using the -- Ascetic data structure. ---------------------------------------------------------------- -- module Text.Ascetic.HTML where import Data.String.Utils (join) import qualified Text.Ascetic as A ---------------------------------------------------------------- -- | Data structures specific to HTML files. type Class = String type Selector = String type PseudoClass = Maybe String type Property = String type Value = String type DeclarationBlock = [(Property, Value)] data CSS = CSS [([Selector], PseudoClass, DeclarationBlock)] type HTML = A.Ascetic class ToHTML a where html :: a -> HTML ---------------------------------------------------------------- -- | Combinators for assembling HTML files. file :: HTML -> HTML -> HTML file head body = A.E "html" [head, body] head :: [HTML] -> HTML head hs = A.E "head" hs meta_ :: [(A.Attribute, A.Value)] -> HTML meta_ avs = A.A "meta" avs [] style :: CSS -> HTML style (CSS dbs) = A.E "style" $ [A.C $ "\n" ++ join "\n\n" [ (join ", " ss) ++ (maybe "" ((++) ":") pc) ++ " {\n " ++ join "\n " [p ++ ": " ++ v ++ ";" | (p,v) <- pvs] ++ "\n}" | (ss, pc, pvs) <- dbs] ++ "\n" ] script :: String -> HTML script src = A.E "script" [A.C src] script_ :: [(A.Attribute, A.Value)] -> String -> HTML script_ avs src = A.A "script" avs [A.C src] body :: [HTML] -> HTML body hs = A.E "body" hs div :: [HTML] -> HTML div hs = A.E "div" hs div_ :: [(A.Attribute, A.Value)] -> [HTML] -> HTML div_ avs hs = A.A "div" avs hs span :: [HTML] -> HTML span hs = A.E "span" hs span_ :: [(A.Attribute, A.Value)] -> [HTML] -> HTML span_ avs hs = A.A "span" avs hs content :: String -> HTML content s = A.C s td :: HTML -> HTML td h = A.E "td" [h] tr :: [HTML] -> HTML tr hs = A.E "tr" hs table :: [HTML] -> HTML table hs = A.E "table" hs conc :: [HTML] -> HTML conc hs = A.L hs bold :: HTML -> HTML bold h = A.E "b" [h] --eof
lapets/ascetic
Text/Ascetic/HTML.hs
mit
2,086
0
18
426
810
445
365
52
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TupleSections #-} module Text.Atomos.Atom.Export where import Data.DList (DList) import qualified Data.DList as D import qualified Data.List.NonEmpty as N import Data.Monoid import Text.Atomos.Types import Text.HTML.TagSoup import Data.Time import qualified Data.Foldable as F import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Base64 as Base64 import qualified Data.Text as T import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.Text.Encoding as T textElement :: S.ByteString -> TextElement -> DList (Tag S.ByteString) textElement n (PlainText t) = D.fromList [TagOpen n [("type", "text")], TagText $ T.encodeUtf8 t, TagClose n] textElement n (HtmlText t) = D.fromList [TagOpen n [("type", "html")], TagText $ T.encodeUtf8 t, TagClose n] textElement n (XHtmlText t) = D.singleton (TagOpen n [("type", "xhtml")]) <> D.fromList t <> D.singleton (TagClose n) person :: S.ByteString -> Person -> DList (Tag S.ByteString) person t (Person n mbu mbe) = D.singleton (TagOpen t []) <> D.fromList [TagOpen "name" [], TagText (T.encodeUtf8 n), TagClose "name"] <> maybe D.empty (\u -> D.fromList [TagOpen "uri" [], TagText u, TagClose "uri"]) mbu <> maybe D.empty (\e -> D.fromList [TagOpen "email" [], TagText e, TagClose "email"]) mbe <> D.singleton (TagClose t) category :: Category -> DList (Tag S.ByteString) category (Category t mbs mbl) = D.fromList [ TagOpen "category" attrs, TagClose "category" ] where attrs = (:) ("term", t) $ maybe id (\s -> (:) ("scheme", s)) mbs $ maybe id (\l -> (:) ("label", T.encodeUtf8 l)) mbl [] generator :: Generator -> DList (Tag S.ByteString) generator (Generator mbu mbv t) = D.fromList [ TagOpen "generator" attrs, TagText t, TagClose "generator"] where attrs = maybe id (\u -> (:) ("uri", u)) mbu $ maybe id (\v -> (:) ("version", v)) mbv [] link_ :: S.ByteString -> Link_ -> DList (Tag S.ByteString) link_ rel (Link_ h mby mbl mbt mbn) = D.fromList [TagOpen "link" attrs, TagClose "link"] where attrs = (:) ("href", h) $ (:) ("rel", rel) $ maybe id (\y -> (:) ("type", y)) mby $ maybe id (\l -> (:) ("hreflang", l)) mbl $ maybe id (\t -> (:) ("title", T.encodeUtf8 t)) mbt $ maybe id (\n -> (:) ("length", n)) mbn [] link :: Link -> DList (Tag S.ByteString) link (Link r l) = link_ r l inlinePlain :: Maybe S.ByteString -> T.Text -> DList (Tag S.ByteString) inlinePlain mby t = D.fromList [TagOpen "content" $ maybe [] ((:[]) . ("type",)) mby, TagText $ T.encodeUtf8 t, TagClose "content"] inlineXML :: Maybe S.ByteString -> [Tag S.ByteString] -> DList (Tag S.ByteString) inlineXML mby x = D.singleton (TagOpen "content" $ maybe [("type", "xhtml")] ((:[]) . ("type",)) mby) <> D.fromList x <> D.singleton (TagClose "content") inlineBASE64 :: Maybe S.ByteString -> S.ByteString -> DList (Tag S.ByteString) inlineBASE64 mby b = D.fromList [ TagOpen "content" $ maybe [("type", "application/octet-stream")] ((:[]) . ("type",)) mby , TagText $ Base64.encode b, TagClose "content"] outOfLine :: Maybe S.ByteString -> S.ByteString -> DList (Tag S.ByteString) outOfLine mby s = D.fromList [ TagOpen "content" . (:) ("src", s) $ maybe [] ((:[]) . ("type",)) mby, TagClose "content"] contentSummary :: Content -> (DList (Tag S.ByteString), DList (Tag S.ByteString)) contentSummary (ContentInlinePlain (InlinePlain mby t s)) = (inlinePlain mby t, maybe mempty (textElement "summary") s) contentSummary (ContentInlineXml (InlineXml mby x s)) = (inlineXML mby x, maybe mempty (textElement "summary") s) contentSummary (ContentInlineBase64 (InlineBase64 mby b s)) = (inlineBASE64 mby b, textElement "summary" s) contentSummary (ContentOutOfLine (OutOfLine mby r s)) = (outOfLine mby r, textElement "summary" s) noContSummary :: NoContent -> (DList (Tag S.ByteString), DList (Tag S.ByteString)) noContSummary (NoContent a s) = (mconcat . map (link_ "alternate") $ N.toList a, maybe mempty (textElement "summary") s) linkContSummary :: Either Content NoContent -> (DList (Tag S.ByteString), DList (Tag S.ByteString), DList (Tag S.ByteString)) linkContSummary = either ((\(c, s) -> (mempty, c, s)) . contentSummary) ((\(l, s) -> (l, mempty, s)) . noContSummary) simple :: S.ByteString -> S.ByteString -> DList (Tag S.ByteString) simple n i = D.fromList [TagOpen n [], TagText i, TagClose n] formatRfc3339Date :: ZonedTime -> S.ByteString formatRfc3339Date = S8.pack . formatTime defaultTimeLocale "%FT%T%Q%z" dateElem :: S.ByteString -> ZonedTime -> DList (Tag S8.ByteString) dateElem e z = D.fromList [TagOpen e [], TagText $ formatRfc3339Date z, TagClose e] entry :: F.Foldable f => Entry f -> DList (Tag S.ByteString) entry (Entry as cats cnt cbrs i ls pub rs src ttl upd) = let (alts, contents, summary) = linkContSummary cnt in D.singleton (TagOpen "entry" []) <> textElement "title" ttl <> mconcat (map category cats) <> contents <> summary <> maybe mempty feed src <> simple "id" i <> F.foldl' (\j a -> j <> person "author" a) mempty as <> mconcat (map (person "contributor") cbrs) <> maybe mempty (textElement "rights") rs <> mconcat (map link ls) <> alts <> maybe mempty (dateElem "published") pub <> dateElem "updated" upd <> D.singleton (TagClose "entry") authorEntries :: Either (N.NonEmpty Person, [Entry []]) ([Entry N.NonEmpty]) -> (DList (Tag S.ByteString), DList (Tag S.ByteString)) authorEntries = either (\(as, es) -> (mconcat . map (person "author") $ N.toList as, mconcat $ map entry es)) (\es -> (mempty, mconcat $ map entry es)) feed :: Feed -> DList (Tag S.ByteString) feed (Feed cats cbrs gen icon i self other logo rs sub ttl upd ae) = let (authors, entries) = authorEntries ae in D.singleton (TagOpen "?xml" [("version", "1.0"), ("encoding", "utf-8")]) <> D.singleton (TagOpen "feed" [("xmlns", "http://www.w3.org/2005/Atom")]) <> textElement "title" ttl <> maybe mempty (textElement "subtitle") sub <> mconcat (map category cats) <> maybe mempty (simple "icon") icon <> maybe mempty (simple "logo") logo <> authors <> mconcat (map (person "contributor") cbrs) <> maybe mempty (textElement "rights") rs <> simple "id" i <> maybe mempty generator gen <> maybe mempty (link_ "self") self <> mconcat (map link other) <> dateElem "updated" upd <> entries <> D.singleton (TagClose "feed") renderAtom :: Feed -> L.ByteString renderAtom f = renderTags (map (fmap L.fromStrict) $ D.toList $ feed f)
philopon/atomos
Text/Atomos/Atom/Export.hs
mit
6,875
0
27
1,425
2,923
1,518
1,405
124
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} module Rules where -- | IF 'condition' DO 'action' rule following Minsky's "Model Six" data IfDo c a = IfDo { condition :: c , action :: a } deriving (Eq,Show) -- | IF 'condition' DO 'action' THEN 'outcome' rule following Minsky's "Model Six" -- This form is used for deliberative thinking and above layers data IfDoThen c a = IfDoThen { rule :: IfDo c a , outcome :: c } deriving (Eq,Show) -- | The main common trait of the rules - they might match some situation class CanMatch a b where matches :: a -> b -> Bool -- | The second common trait of the rules - they prescribe some action class Actionable a b | a -> b where getAction :: a -> b instance Eq c => CanMatch (IfDo c a) c where matches (IfDo c1 _) c2 = c1 == c2 instance Eq c => CanMatch (IfDoThen c a) c where matches (IfDoThen (IfDo c1 _) _) c2 = c1 == c2 instance Actionable (IfDo c a) a where getAction (IfDo _ a) = a instance Actionable (IfDoThen c a) a where getAction (IfDoThen (IfDo _ a) _) = a
research-team/robot-dream
src/Rules.hs
mit
1,215
0
10
347
313
169
144
24
0
{-| Module: Itchy.Localization.RichText Description: RichText License: MIT -} {-# LANGUAGE GeneralizedNewtypeDeriving, LambdaCase, OverloadedStrings #-} module Itchy.Localization.RichText ( RichText(..) , RichChunk(..) ) where import Data.String import qualified Data.Text as T import qualified Text.Blaze as TB import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A newtype RichText = RichText [RichChunk] deriving (Eq, Ord, Semigroup, Monoid) instance IsString RichText where fromString s = RichText [fromString s] instance TB.ToMarkup RichText where toMarkup (RichText chunks) = mconcat $ map TB.toMarkup chunks data RichChunk = RichChunkText !T.Text | RichChunkLink !T.Text !T.Text | RichChunkCode !T.Text deriving (Eq, Ord) instance IsString RichChunk where fromString = RichChunkText . T.pack instance TB.ToMarkup RichChunk where toMarkup = \case RichChunkText t -> H.toHtml t RichChunkLink l t -> H.a H.! A.href (H.toValue l) H.! A.target "_blank" $ H.toHtml t RichChunkCode t -> H.code $ H.toHtml t
quyse/itchy
Itchy/Localization/RichText.hs
mit
1,067
8
15
161
329
178
151
34
0
{-# LANGUAGE RecordWildCards #-} module Main ( main ) where import Universum import Control.Exception.Safe (handle) import Data.Maybe (fromMaybe) import Formatting (sformat, shown, (%)) import qualified Network.Transport.TCP as TCP (TCPAddr (..)) import qualified System.IO.Temp as Temp import Ntp.Client (NtpConfiguration) import Pos.Chain.Genesis as Genesis (Config (..), ConfigurationError) import Pos.Chain.Txp (TxpConfiguration) import Pos.Chain.Update (updateConfiguration) import qualified Pos.Client.CLI as CLI import Pos.Context (NodeContext (..)) import Pos.DB.DB (initNodeDBs) import Pos.DB.Txp (txpGlobalSettings) import Pos.Infra.Diffusion.Types (Diffusion, hoistDiffusion) import Pos.Infra.Network.Types (NetworkConfig (..), Topology (..), topologyDequeuePolicy, topologyEnqueuePolicy, topologyFailurePolicy) import Pos.Launcher (HasConfigurations, NodeParams (..), NodeResources (..), WalletConfiguration, bracketNodeResources, loggerBracket, lpConsoleLog, runNode, runRealMode, withConfigurations) import Pos.Util (logException) import Pos.Util.CompileInfo (HasCompileInfo, withCompileInfo) import Pos.Util.Config (ConfigurationException (..)) import Pos.Util.Trace (fromTypeclassWlog, noTrace) import Pos.Util.UserSecret (usVss) import Pos.Util.Wlog (LoggerName, logInfo) import Pos.WorkMode (EmptyMempoolExt, RealMode) import AuxxOptions (AuxxAction (..), AuxxOptions (..), AuxxStartMode (..), getAuxxOptions) import Mode (AuxxContext (..), AuxxMode, realModeToAuxx) import Plugin (auxxPlugin, rawExec) import Repl (PrintAction, WithCommandAction (..), withAuxxRepl) loggerName :: LoggerName loggerName = "auxx" -- 'NodeParams' obtained using 'CLI.getNodeParams' are not perfect for -- Auxx, so we need to adapt them slightly. correctNodeParams :: AuxxOptions -> NodeParams -> IO (NodeParams, Bool) correctNodeParams AuxxOptions {..} np = do (dbPath, isTempDbUsed) <- case npDbPathM np of Nothing -> do tempDir <- Temp.getCanonicalTemporaryDirectory dbPath <- Temp.createTempDirectory tempDir "nodedb" logInfo $ sformat ("Temporary db created: "%shown) dbPath return (dbPath, True) Just dbPath -> do logInfo $ sformat ("Supplied db used: "%shown) dbPath return (dbPath, False) let np' = np { npNetworkConfig = networkConfig , npRebuildDb = npRebuildDb np || isTempDbUsed , npDbPathM = Just dbPath } return (np', isTempDbUsed) where topology = TopologyAuxx aoPeers networkConfig = NetworkConfig { ncDefaultPort = 3000 , ncSelfName = Nothing , ncEnqueuePolicy = topologyEnqueuePolicy topology , ncDequeuePolicy = topologyDequeuePolicy topology , ncFailurePolicy = topologyFailurePolicy topology , ncTopology = topology , ncTcpAddr = TCP.Unaddressable } runNodeWithSinglePlugin :: (HasConfigurations, HasCompileInfo) => Genesis.Config -> TxpConfiguration -> NodeResources EmptyMempoolExt -> (Diffusion AuxxMode -> AuxxMode ()) -> Diffusion AuxxMode -> AuxxMode () runNodeWithSinglePlugin genesisConfig txpConfig nr plugin = runNode genesisConfig txpConfig nr [ ("runNodeWithSinglePlugin", plugin) ] action :: HasCompileInfo => AuxxOptions -> Either WithCommandAction Text -> IO () action opts@AuxxOptions {..} command = do let pa = either printAction (const putText) command case aoStartMode of Automatic -> handle @_ @ConfigurationException (\_ -> runWithoutNode pa) . handle @_ @ConfigurationError (\_ -> runWithoutNode pa) $ withConfigurations noTrace Nothing cnaDumpGenesisDataPath cnaDumpConfiguration conf (runWithConfig pa) Light -> runWithoutNode pa _ -> withConfigurations noTrace Nothing cnaDumpGenesisDataPath cnaDumpConfiguration conf (runWithConfig pa) where runWithoutNode :: PrintAction IO -> IO () runWithoutNode printAction = printAction "Mode: light" >> rawExec Nothing Nothing Nothing opts Nothing command runWithConfig :: HasConfigurations => PrintAction IO -> Genesis.Config -> WalletConfiguration -> TxpConfiguration -> NtpConfiguration -> IO () runWithConfig printAction genesisConfig _walletConfig txpConfig _ntpConfig = do printAction "Mode: with-config" (nodeParams, tempDbUsed) <- (correctNodeParams opts . fst) =<< CLI.getNodeParams fromTypeclassWlog loggerName cArgs nArgs (configGeneratedSecrets genesisConfig) let toRealMode :: AuxxMode a -> RealMode EmptyMempoolExt a toRealMode auxxAction = do realModeContext <- ask let auxxContext = AuxxContext { acRealModeContext = realModeContext , acTempDbUsed = tempDbUsed } lift $ runReaderT auxxAction auxxContext vssSK = fromMaybe (error "no user secret given") (npUserSecret nodeParams ^. usVss) sscParams = CLI.gtSscParams cArgs vssSK (npBehaviorConfig nodeParams) bracketNodeResources genesisConfig nodeParams sscParams (txpGlobalSettings genesisConfig txpConfig) (initNodeDBs genesisConfig) $ \nr -> let NodeContext {..} = nrContext nr modifier = if aoStartMode == WithNode then runNodeWithSinglePlugin genesisConfig txpConfig nr else identity auxxModeAction = modifier (auxxPlugin genesisConfig txpConfig opts command) in runRealMode updateConfiguration genesisConfig txpConfig nr $ \diffusion -> toRealMode (auxxModeAction (hoistDiffusion realModeToAuxx toRealMode diffusion)) [email protected] {..} = aoCommonNodeArgs conf = CLI.configurationOptions (CLI.commonArgs cArgs) nArgs = CLI.NodeArgs { behaviorConfigPath = Nothing } main :: IO () main = withCompileInfo $ do opts <- getAuxxOptions let disableConsoleLog | Repl <- aoAction opts = -- Logging in the REPL disrupts the prompt, -- so we disable it. -- TODO: When LW-25 is resolved we also want -- to be able to enable logging in REPL using -- a Haskeline-compatible print action. \lp -> lp { lpConsoleLog = Just False } | otherwise = identity loggingParams = disableConsoleLog $ CLI.loggingParams loggerName (aoCommonNodeArgs opts) loggerBracket "auxx" loggingParams . logException "auxx" $ do let runAction a = action opts a case aoAction opts of Repl -> withAuxxRepl $ \c -> runAction (Left c) Cmd cmd -> runAction (Right cmd)
input-output-hk/pos-haskell-prototype
auxx/Main.hs
mit
7,841
0
19
2,649
1,656
895
761
-1
-1
module Movement where import Direction import Rooms import Data.List import Data.Map(Map,toList,lookup) import Data.Maybe type Transitions = Map (Room, Direction) Room move :: Transitions -> Room -> Direction -> Maybe Room move transitions current dir = Data.Map.lookup (current, dir) transitions doMove :: Transitions -> Room -> Direction -> (String, Transitions, Room, Bool) doMove transitions current dir = let dest = move transitions current dir in maybe ("You cannot move " ++ (show dir) ++ ".", transitions, current, False) (\newroom -> ("Moving " ++ (show dir) ++ ".", transitions, newroom, True)) dest getExits :: Transitions -> Room -> [Direction] getExits transitions current = foldr (\((r, d), _) b -> if r == current then d:b else b) [] (toList transitions)
disquieting-silence/adventure
src/Movement.hs
mit
797
0
14
145
304
170
134
19
2
module Orville.PostgreSQL.Internal.SyntheticField ( SyntheticField, syntheticFieldExpression, syntheticFieldAlias, syntheticFieldValueFromSqlValue, syntheticField, nullableSyntheticField, ) where import qualified Orville.PostgreSQL.Internal.Expr as Expr import Orville.PostgreSQL.Internal.FieldDefinition (FieldName, stringToFieldName) import qualified Orville.PostgreSQL.Internal.SqlValue as SqlValue {- | A 'SyntheticField' can be used to evaluate a SQL expression based on the columns of a table when records are selected from the database. Synthetic fields are inherently read-only. -} data SyntheticField a = SyntheticField { _syntheticFieldExpression :: Expr.ValueExpression , _syntheticFieldAlias :: FieldName , _syntheticFieldValueFromSqlValue :: SqlValue.SqlValue -> Either String a } {- | Returns the SQL expression that should be in with select statements to calculated the sythetic field. -} syntheticFieldExpression :: SyntheticField a -> Expr.ValueExpression syntheticFieldExpression = _syntheticFieldExpression {- | Returns the alias that should be used in select statements to name the the synthetic field. -} syntheticFieldAlias :: SyntheticField a -> FieldName syntheticFieldAlias = _syntheticFieldAlias {- | Decodes a calculated value selected from the database to its expected Haskell type. Returns a 'Left' with an error message if the decoding fails. -} syntheticFieldValueFromSqlValue :: SyntheticField a -> SqlValue.SqlValue -> Either String a syntheticFieldValueFromSqlValue = _syntheticFieldValueFromSqlValue {- | Constructs a 'SyntheticField' that will select a SQL expression using the given alias. -} syntheticField :: -- | The SQL expression to be selected Expr.ValueExpression -> -- | The alias to be used to name the calculation in SQL experios String -> -- | A function to decode the expression result from a 'SqlValue.SqlValue' (SqlValue.SqlValue -> Either String a) -> SyntheticField a syntheticField expression alias fromSqlValue = SyntheticField { _syntheticFieldExpression = expression , _syntheticFieldAlias = stringToFieldName alias , _syntheticFieldValueFromSqlValue = fromSqlValue } {- | Modifies a 'SyntheticField' to allow it to decode @NULL@ values. -} nullableSyntheticField :: SyntheticField a -> SyntheticField (Maybe a) nullableSyntheticField synthField = synthField { _syntheticFieldValueFromSqlValue = \sqlValue -> if SqlValue.isSqlNull sqlValue then Right Nothing else Just <$> syntheticFieldValueFromSqlValue synthField sqlValue }
flipstone/orville
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/SyntheticField.hs
mit
2,623
0
10
441
316
184
132
40
2
-- | failure semantics {-# language TemplateHaskell #-} {-# language DeriveDataTypeable #-} {-# language FlexibleInstances #-} {-# language MultiParamTypeClasses #-} module CSP.STS.Fail where import Challenger.Partial import Inter.Types import Inter.Quiz import CSP.STS.Type import CSP.STS.Dot import CSP.Fail.Compute import CSP.Fail.Quiz import Autolib.Dot.Dotty ( peng ) import Autolib.Set import qualified Data.Set as S import qualified Data.Map as M import Autolib.ToDoc import Autolib.Reader import Autolib.NFA.Shortest ( is_accepted ) import Autolib.Reader import Autolib.Reporter import Data.Typeable data STS_Fail = STS_Fail deriving ( Read, Show, Typeable ) instance OrderScore STS_Fail where scoringOrder _ = Increasing instance Partial STS_Fail ( STS Int Char, STS Int Char ) ( [ Char ], Set Char ) where report p ( a, b ) = do inform $ vcat [ text "Begründen Sie durch ein Beispiel," , text "daß die folgenden Zustandsübergangssysteme" , text "unterschiedliche Ablehnungssemantik besitzen:" ] inform $ text "A = " <+> toDoc a peng a inform $ text "B = " <+> toDoc b peng b initial p (a,b) = ( take 2 $ S.toList $ alphabet a , alphabet a ) total p (a,b) (w,r) = do pa <- compute ( text "A" ) a (w,r) pb <- compute ( text "B" ) b (w,r) {- let fa = failures a fb = failures b let u = map Right w ++ [ Left r ] let pa = is_accepted fa u pb = is_accepted fb u inform $ text "Gehört diese Ablehnung zur Semantik von A?" </> toDoc pa inform $ text "Gehört diese Ablehnung zur Semantik von B?" </> toDoc pb -} when ( pa == pb ) $ reject $ text "Die Antworten dürfen nicht übereinstimmen." compute name s (w,r) = nested 4 $ do inform $ text "Gehört diese Ablehnung zur Semantik von" <+> name <+> text "?" nested 4 $ case failure_trace s (w,r) of Left msg -> do inform msg ; return False Right msg -> do inform msg ; return True make_fixed :: Make make_fixed = direct STS_Fail (s1, s2) (s1, s2) = (STS { start = 3 :: Int , alphabet = mkSet [ 'a' , 'b' ] , visible = [ ( 2 , 'b' , 4 ) , ( 2 , 'a' , 4 ) , ( 4 , 'b' , 1 ) , ( 4 , 'a' , 2 ) , ( 1 , 'b' , 2 ) , ( 2 , 'a' , 2 ) ] , hidden = [ ( 1 , 1 ) , ( 3 , 1 ) , ( 3 , 2 ) ] },STS { start = 4 :: Int , alphabet = mkSet [ 'a' , 'b' ] , visible = [ ( 4 , 'a' , 4 ) , ( 3 , 'b' , 3 ) , ( 1 , 'a' , 2 ) , ( 2 , 'b' , 3 ) , ( 4 , 'b' , 3 ) , ( 3 , 'b' , 4 ) , ( 2 , 'a' , 2 ) ] , hidden = [ ( 3 , 4 ) , ( 1 , 2 ) , ( 4 , 2 ) , ( 3 , 3 ) ] }) data Config = Config { num_states :: Int , letters :: [Char] , num_visible :: Int , num_mutated :: Int , num_hidden :: Int , generator_repeat :: Int } deriving ( Typeable ) example_config :: Config example_config = Config { num_states = 4 , num_visible = 6 , num_mutated = 2 , num_hidden = 0 , letters = "ab" , generator_repeat = 1000 } $(derives [makeReader, makeToDoc] [''Config]) instance Show Config where show = render . toDoc instance Generator STS_Fail Config ( STS Int Char, STS Int Char , ( [[ Char]] , [[ Either ( Set Char) Char]] ) ) where generator _ conf key = roll ( letters conf ) ( num_states conf ) ( num_visible conf ) ( num_hidden conf ) ( num_mutated conf ) ( generator_repeat conf ) instance Project STS_Fail ( STS Int Char, STS Int Char , ( [[Char]], [[ Either ( Set Char) Char]] ) ) ( STS Int Char, STS Int Char ) where project _ (a,b,u) = (a,b) make_quiz :: Make make_quiz = quiz STS_Fail example_config
marcellussiegburg/autotool
collection/src/CSP/STS/Fail.hs
gpl-2.0
4,091
0
14
1,469
1,258
716
542
93
2
{-# LANGUAGE DatatypeContexts #-} {-# LANGUAGE DatatypeContexts #-} {-# language DatatypeContexts #-} {-# language TemplateHaskell #-} {-# language DeriveDataTypeable #-} {-# language FlexibleContexts #-} {-# language MultiParamTypeClasses #-} module Rewriting.Termination where import Rewriting.Termination.Semiring import Rewriting.Termination.Multilinear import qualified Rewriting.Termination.Polynomial as P import qualified Polynomial.Type as P import Rewriting.Termination.Interpretation import Rewriting.TRS import Polynomial.Class import qualified Prelude import Prelude hiding ( Num (..), sum, (^), (/), Integer, null, gcd, divMod, div, mod ) import Challenger.Partial import Inter.Types import Autolib.Symbol import Autolib.Size import Autolib.Reader import Autolib.ToDoc import Autolib.Reporter import Autolib.FiniteMap import qualified Data.Map as M import Data.Typeable import Control.Monad ( when, forM ) import Control.Applicative ( (<$>) ) import qualified Data.Set as S data Restriction = And [ Restriction ] | Or [ Restriction ] | Not Restriction | Lexicographic_with_children Restriction | Matrix_Natural | Matrix_Fuzzy | Matrix_Arctic | Matrix_Tropical | Matrix_dimension_at_most Int | Polynomial -- TODO: restrict degree deriving ( Eq, Ord, Typeable ) derives [makeReader, makeToDoc] [''Restriction] data Symbol c => Problem c = Problem { system :: TRS c c , restriction :: Restriction } deriving ( Eq, Typeable ) problem0 :: Problem Identifier problem0 = Problem { system = read "TRS { variables = [x] , rules = [ a(b(x)) -> b(a(x)) ] }" , restriction = Or [ Matrix_Natural, Lexicographic_with_children Matrix_Natural ] } problem1 :: Problem Identifier problem1 = Problem { system = read "TRS { variables = [x,y] , rules = [ f(x,a) -> b(a(x)) ] }" , restriction = Polynomial } derives [makeReader, makeToDoc] [''Problem] data Symbol c => Order c = Empty | Interpretation { dim :: Int, values :: Interpretation c } | Lexicographic [ Order c ] deriving ( Eq, Typeable ) instance Symbol c => Size (Order c) where size o = case o of Empty -> 0 Interpretation {} -> size $ values o Lexicographic ords -> Prelude.sum $ map size ords derives [makeReader, makeToDoc] [''Order] data Rewriting_Termination = Rewriting_Termination deriving Typeable derives [makeReader, makeToDoc] [''Rewriting_Termination] instance Show Rewriting_Termination where show = render . toDoc instance OrderScore Rewriting_Termination where scoringOrder _ = Increasing instance Symbol c => Partial Rewriting_Termination (Problem c) (Order c) where describe _ p = vcat [ text "give a rewrite order" , text "that is compatible with" <+> toDoc (system p) , text "and conforms to" <+> toDoc (restriction p) , text "--" , text "polynomial interpretation syntax: arguments are x1, x2, .." , text "size (for highscore): total number of monomials" , text "--" , text "matrix syntax: scalar 3, row [4,5,6], column [1,2,3], matrix [[1,2],[3,4]], unit 3, zero (2,1)" , text "semiring elements: -inf, 0, 1, .. , +inf" , text "domains: _Natural, _Arctic, _Tropical, _Fuzzy" , text "size (for highscore): total number of nonzero entries" ] initial _ p | restriction p == Polynomial = Interpretation 1 $ Polynomial_Interpretation $ M.fromList $ do (k,f) <- zip [1..] $ S.toList $ signature $ system p return ( f , if arity f > 0 then (fromInteger 1 + fromInteger 2 * (P.variable $ P.X (succ $ k `Prelude.mod` arity f))^2) else fromInteger 5 ) initial _ p = Interpretation 2 $ Matrix_Interpretation_Natural $ M.fromList $ do (k,f) <- zip [1..] $ S.toList $ signature $ system p return ( f, projection (arity f) (succ $ k `Prelude.mod` arity f) 2 ) partial _ p o = do check_dimensions (signature $ system p) o everything_monotone o ok <- compute_restriction (restriction p) o when (not ok) $ reject $ text "order does not conform to restriction" total _ p o = do compatible o $ system p make_fixed_matrix :: Make make_fixed_matrix = direct Rewriting_Termination problem0 make_fixed_poly :: Make make_fixed_poly = direct Rewriting_Termination problem1 compute_restriction r o = case r of And rs -> and <$> forM rs ( \ r -> compute_restriction r o ) Or rs -> or <$> forM rs ( \ r -> compute_restriction r o ) Not r -> not <$> compute_restriction r o _ -> case (r,o) of ( Lexicographic_with_children r, Lexicographic ords ) -> and <$> forM ords ( \ o -> compute_restriction r o ) ( Matrix_Natural, Interpretation {values = Matrix_Interpretation_Natural {}} ) -> return True ( Matrix_Arctic, Interpretation {values = Matrix_Interpretation_Arctic {}}) -> return True ( Matrix_Tropical, Interpretation { values = Matrix_Interpretation_Tropical {}} ) -> return True ( Matrix_Fuzzy, Interpretation { values = Matrix_Interpretation_Fuzzy {}} ) -> return True ( Matrix_dimension_at_most d, Interpretation { dim = dim} ) -> return $ d >= dim ( Polynomial, Interpretation { values = Polynomial_Interpretation {}} ) -> return True _ -> return False everything_monotone o = case o of Empty -> return () Interpretation {} -> check_monotone $ values o Lexicographic ords -> forM_ ords everything_monotone check_dimensions sig o = case o of Empty -> return () Lexicographic ords -> forM_ ords $ check_dimensions sig Interpretation {} -> check_dimension sig (dim o) (values o) signature sys = S.unions $ do u <- rules sys ; [ syms $ lhs u, syms $ rhs u ] compatible ord sys = forM_ (rules sys) $ \ u -> do o <- compute ord u when (o /= Greater) $ reject $ text "must be greater" compute ord u = case ord of Empty -> return Greater_Equal Interpretation {dim=d, values=int} -> compute_order int d u Lexicographic ords -> compute_lex ords u compute_lex [] u = return Greater_Equal compute_lex (ord:ords) u = do c <- compute ord u case c of Greater -> return Greater Greater_Equal -> compute_lex ords u Other -> return Other
marcellussiegburg/autotool
collection/src/Rewriting/Termination.hs
gpl-2.0
6,490
0
21
1,620
1,875
976
899
147
11
{-| This module is a collection of utility functions performed over the syntax of Pepa models. -} module Language.Pepa.PepaUtils ( TransitionAnalysis ( .. ) , modelTransitionAnalysis , isPepaActionEnabled , TransSuccessor , possibleTransSuccessors , possibleTransitions , allTransitionsOfModel , SuccessorTrans , SuccessorTransMap , allSuccessors , CanonicalSuccessor , CanonicalSuccessors , allSuccessorsCanonical , derivativesOfComponent , reachableProcessDefs , transitiveDerivatives , findProcessDefinition , makePepaChoice , addProcessDefinitions , ParOrSeq ( .. ) , isParOrSeqComponent , getRateSpec ) where {- External Library Modules Imported -} {- Standard Modules Imported -} import qualified Data.List as List import qualified Data.Maybe as Maybe import Data.Maybe ( mapMaybe ) {- Local Modules Imported -} import qualified Language.Pepa.QualifiedName as Qualified import qualified Language.Pepa.Syntax as Pepa import Language.Pepa.Syntax ( ParsedModel ( .. ) , ProcessDef , ParsedComponent ( .. ) , ParsedComponentId , Transition ( .. ) , ParsedTrans , ParsedAction ( .. ) ) {- End of Imports -} -- | A type containing all the transitions in a given model. data TransitionAnalysis = TransitionAnalysis { modelNamedTransitions :: CanonicalSuccessors , modelNoSourceTrans :: [ ( ParsedTrans , ParsedComponentId ) ] , modelNoTargetTrans :: [ ( ParsedComponentId , ParsedTrans ) ] , modelOrphanTrans :: [ ParsedTrans ] } modelTransitionAnalysis :: ParsedModel -> TransitionAnalysis modelTransitionAnalysis model = TransitionAnalysis { modelNamedTransitions = namedTrans , modelNoSourceTrans = noSourceTrans , modelNoTargetTrans = noTargetTrans , modelOrphanTrans = orphanTrans } where allTransitions = allSuccessors model namedTrans = [ (source, (trans, target)) | (Just source, (trans, Just target)) <- allTransitions ] noSourceTrans = [ (trans, target) | (Nothing, (trans, Just target)) <- allTransitions ] noTargetTrans = [ (source, trans) | (Just source, (trans, Nothing)) <- allTransitions ] orphanTrans = [ trans | (Nothing, (trans, Nothing)) <- allTransitions ] {-| Returns true if the pepa component given may perform the given action. -} isPepaActionEnabled :: ParsedAction -> ParsedComponentId -> ParsedModel -> Bool isPepaActionEnabled act ident model = any ((act ==) . pepaTransAction) $ possibleTransitions model ident -- | The type of transitions from components to components type TransSuccessor = (ParsedTrans, Maybe ParsedComponentId) -- | The type of /seen/ process identifiers type Seen = [ ParsedComponentId ] {-| Returns the list of possible transitions from a given starting point in a sequential component. This is not transitive, it only returns the transitions which can be made now. -} possibleTransSuccessors :: ParsedModel -> ParsedComponentId -> [ TransSuccessor ] possibleTransSuccessors model ident = snd $ possibleTrans [] ident where -- The first argument is a list of seen processes this stops us -- going into the inevitable infinite loop. possibleTrans :: Seen -> ParsedComponentId -> ( Seen , [ TransSuccessor ] ) possibleTrans seen ident2 | elem ident2 seen = (seen, []) | otherwise = case findProcessDefinition model ident2 of Nothing -> error $ notFound ident2 Just comp -> possibleTransComp (ident2 : seen) comp -- The same thing here, the first argument is the list of seen -- processes. possibleTransComp :: Seen -> ParsedComponent -> (Seen, [ TransSuccessor ]) possibleTransComp seen (StopProcess) = (seen, []) possibleTransComp seen (IdProcess ident2) = possibleTrans seen ident2 possibleTransComp seen (CondBehaviour _ right) = possibleTransComp seen right possibleTransComp seen (ComponentSum left right) = -- Note, that I think this actually messes up on: @P = Q + Q@ -- that is it will produce less transitions that it should. (rightSeen, leftTrans ++ rightTrans) where (leftSeen, leftTrans) = possibleTransComp seen left (rightSeen, rightTrans) = possibleTransComp leftSeen right possibleTransComp seen (PrefixComponent trans s) = -- Here we do not call 'ident2' recursively hence we are -- /not/ finding all the reachable transitions only the ones -- that are possible NOW. case s of IdProcess ident2 -> (seen, [ (trans, Just ident2) ]) _ -> (seen, [ (trans, Nothing ) ]) possibleTransComp _seen (Cooperation _ _ _ ) = error errorMessage possibleTransComp _seen (ProcessArray _ _ _ ) = error errorMessage possibleTransComp _seen (Hiding _ _ ) = error errorMessage errorMessage = "Attempt to obtain the sequetional transitions " ++ "of a parallel component" notFound name = unwords [ "component:" , Qualified.textual name , "not found when attempting to gather next" , "transitions" ] {-| The same as 'possibleTransSuccessors' except we remove the successors. -} possibleTransitions :: ParsedModel -> ParsedComponentId -> [ ParsedTrans ] possibleTransitions model = (map fst) . (possibleTransSuccessors model) {-| Finds all the derivatives of a given sequential component. This works whether the model is in normal form or not, but it will only return named derivatives. The behaviour is supposed to be somewhat undefined on ill-typed models, for example on in which a sequential component has a parallel or undefined derivative. -} derivativesOfComponent :: ParsedModel -> ParsedComponentId -> [ ParsedComponentId ] derivativesOfComponent model startId = mapMaybe snd tSuccs where tSuccs = possibleTransSuccessors model startId {-| Finds all the process definitions reachable (or related) to a given process name. So this in a sense finds the sub-model related to a given process name. This includes the definition for the given ParsedComponentId since this is reachable by virtue of doing nothing. Normally this doesn't make much difference since it is reachable since the process is cyclic. -} reachableProcessDefs :: ParsedModel -> ParsedComponentId -> [ ProcessDef ] reachableProcessDefs model startId = getDerivativesId [] startId where modelDefs = modelProcessDefs model getDef :: ParsedComponentId -> Maybe ParsedComponent getDef ident = lookup ident modelDefs getDerivativesId :: [ ProcessDef ] -> ParsedComponentId -> [ ProcessDef ] getDerivativesId seen currentId | any ((== currentId) . fst) seen = seen | Just comp <- getDef currentId = getDerivatives ((currentId, comp) : seen) comp | otherwise = error $ "Undefined component in reachable: " ++ (Qualified.textual currentId) getDerivatives :: [ ProcessDef ] -> ParsedComponent ->[ ProcessDef ] getDerivatives seen (IdProcess currentId) = getDerivativesId seen currentId getDerivatives seen (PrefixComponent _trans next) = getDerivatives seen next getDerivatives seen (ComponentSum left right) = getDerivatives (getDerivatives seen left) right getDerivatives seen (CondBehaviour _rate comp) = getDerivatives seen comp getDerivatives seen (StopProcess) = seen getDerivatives seen (Cooperation left _actions right) = getDerivatives (getDerivatives seen left) right getDerivatives seen (ProcessArray comp _size _coop) = getDerivatives seen comp getDerivatives seen (Hiding comp _coop) = getDerivatives seen comp {-| 'derivativesOfComponent' finds those derivatives which can be reached via a single transition. 'transitiveDerivatives' finds all reachable derivatives from the given starting point. Note that the given 'startId' is only returned if it is reachable from itself. -} transitiveDerivatives :: ParsedModel -- ^ The input model -> ParsedComponentId -- ^ The named starting point -> [ ParsedComponentId ] -- ^ Reachable derivatives transitiveDerivatives model startId = getDerives startId [] where getDerives :: ParsedComponentId -> [ ParsedComponentId ] -> [ ParsedComponentId ] getDerives ident seen | elem ident seen = seen | otherwise = foldr getDerives (ident : seen) $ derivativesOfComponent model ident {-| Finds all the transitions of a model, note that it is possible that some of these can never be performed, for example if they are defined within an unused process. -} allTransitionsOfModel :: ParsedModel -> [ ParsedTrans ] allTransitionsOfModel model = concatMap (getTransitions . snd) pDefs where pDefs = modelProcessDefs model getTransitions :: ParsedComponent -> [ ParsedTrans ] getTransitions (IdProcess _) = [] getTransitions (StopProcess) = [] getTransitions (PrefixComponent trans next) = trans : (getTransitions next) getTransitions (ComponentSum left right) = (getTransitions left) ++ (getTransitions right) getTransitions (CondBehaviour _cond comp) = getTransitions comp -- Shouldn't really get a transition in a parallel component but this won't hurt. getTransitions (Cooperation left _ right) = (getTransitions left) ++ (getTransitions right) getTransitions (ProcessArray _ _ _) = [] getTransitions (Hiding comp _) = getTransitions comp {- (map takeTrans) . allSuccessors where takeTrans :: SuccessorTrans -> ParsedTrans takeTrans = fst . snd -} {-| Yet another type of successor transition. This one includes the possibility of having the identifier of the component from which we are transisting. This is a good analysis to do when the model is in normal form such that every prefix component is a single prefix component within a process definition such as: @P = (a, r).Q@ That is, there is no chaining of prefix components and they are not a part of other components such as prefixes. [@todo@] all the other ones should just call this and then map the result. I still think this is not quite right, if we have @P = S@ then we should have all the successors of @S@ as being possible from @P@. So now this uses 'possibleTransSuccessors' This should be re-written to descend from the main composition. My worry here is that we might duplicate the transitions in the whole model due to aliases (of course we shouldn't call this if the model is not in normal form, but still). -} type SuccessorTrans = ( Maybe ParsedComponentId , (ParsedTrans, Maybe ParsedComponentId) ) type SuccessorTransMap = [ SuccessorTrans ] allSuccessors :: ParsedModel -> SuccessorTransMap allSuccessors model = concatMap succsOfDef pDefs where pDefs = modelProcessDefs model succsOfDef :: ProcessDef -> SuccessorTransMap succsOfDef (ident, _comp) = map addIdent transSuccs where transSuccs = possibleTransSuccessors model ident addIdent :: TransSuccessor -> SuccessorTrans addIdent t = (Just ident, t) {- The type of the less forgiving 'SuccessorTransMap' which is the result of 'allSuccessorsCanonical' which is only to be called on those models in canonical form. -} type CanonicalSuccessor = ( ParsedComponentId , (ParsedTrans, ParsedComponentId) ) type CanonicalSuccessors = [ CanonicalSuccessor ] {- 'allSucessorsCanonical' is just as the above 'allSuccessors' however it will return 'Nothing' in the case that any of the successors has no name for the source component or no name for the target component. This means it should only be called with a model in canonical form. -} allSuccessorsCanonical :: ParsedModel -> Maybe CanonicalSuccessors allSuccessorsCanonical model = if any (not . hasBothNames) successors then Nothing else Just okay where successors = allSuccessors model okay = [ (sou, (t, tar) ) | (Just sou, (t, Just tar)) <- successors ] hasBothNames :: SuccessorTrans -> Bool hasBothNames (Just _, (_, Just _)) = True hasBothNames _ = False {- succsOfDef :: ProcessDef -> SuccessorTransMap succsOfDef (ident, PrefixComponent t (IdProcess ident2)) = [ (Just ident, (t, Just ident2)) ] succsOfDef (ident, PrefixComponent t next) = ( Just ident, (t, Nothing) ) : (succsOfProcess next) succsOfDef (ident, ComponentSum left right) = (succsOfDef (ident, left)) ++ (succsOfDef (ident, right)) succsOfDef (_, component) = succsOfProcess component succsOfProcess :: ParsedComponent -> SuccessorTransMap succsOfProcess (IdProcess _) = [] -- So here the second maybe is a 'Just' because there is -- an ident, we assume that the definition is not directly -- above here since in that case it would have been caught -- by 'succsOfDef' succsOfProcess (PrefixComponent t (IdProcess ident)) = [ (Nothing, (t, Just ident)) ] -- Right, now we have no ident as the source or the target succsOfProcess (PrefixComponent t next) = (Nothing, (t, Nothing)) : (succsOfProcess next) succsOfProcess (ComponentSum left right) = (succsOfProcess left) ++ (succsOfProcess right) -- There shouldn't be any in the parallel ones, but oh well succsOfProcess (Cooperation left _ right) = (succsOfProcess left) ++ (succsOfProcess right) succsOfProcess (ProcessArray _ _ _) = [] succsOfProcess (Hiding left _) = succsOfProcess left -} -- | Finds a process definition in a pepa model findProcessDefinition :: ParsedModel -> ParsedComponentId -> Maybe ParsedComponent findProcessDefinition pModel ident = lookup ident $ modelProcessDefs pModel {-| makes a choice between a given number of components. Note that this currently just raises an error if passed the empty list, an alternative would be to go to the special @Stop@ process. -} makePepaChoice :: [ ParsedComponent ] -> ParsedComponent makePepaChoice [] = error "makePepaChoice called with an empty list" makePepaChoice ls = foldl1 ComponentSum ls addProcessDefinitions :: [ ProcessDef ] -> ParsedModel -> ParsedModel addProcessDefinitions defs model = model { modelProcessDefs = defs ++ (modelProcessDefs model) } {-| The type returned by 'isParOrSeqComponent' -} data ParOrSeq = IsPar | IsSeq | ParOrSeq deriving Eq {-| Returns whether or not a component is a parallel component. It relies on a function to tell whether a component identifier is parallel or sequential. This will depend on the state of the model at the time. If for example we have applied a tranformation to remove all parallel defs then all component identifiers can be assumed to be sequential. -} isParOrSeqComponent :: ParOrSeq -- What to return for an identifier -> ParsedComponent -> ParOrSeq isParOrSeqComponent idRes (IdProcess _) = idRes isParOrSeqComponent _ (StopProcess) = IsSeq isParOrSeqComponent _ (PrefixComponent _ _) = IsSeq isParOrSeqComponent _ (ComponentSum _ _) = IsSeq isParOrSeqComponent _ (CondBehaviour _ _) = IsSeq isParOrSeqComponent _ (Cooperation _ _ _) = IsPar isParOrSeqComponent _ (ProcessArray _ _ _) = IsPar isParOrSeqComponent _ (Hiding _ _) = IsPar {-| Get the rate specification of the given rate name if it occurs in the model. We only do a textual search for the name. -} getRateSpec :: ParsedModel -> String -> Maybe Pepa.RateSpec getRateSpec model name = List.find isRightRate $ Pepa.rateDefsOfModel model where isRightRate :: Pepa.RateSpec -> Bool isRightRate (q, _) = name == (Qualified.textual q)
allanderek/ipclib
Language/Pepa/PepaUtils.hs
gpl-2.0
17,214
0
13
4,867
2,491
1,359
1,132
217
10
-- xmonad: Personal module: Appearance -- Author: Simon L. J. Robin | https://sljrobin.org -------------------------------------------------------------------------------- module Appearance where -------------------------------------------------------------------------------- -- * `XMonad.Layout.Decoration` -> Enable the creation of decorated layouts -- * `XMonad` -> Main library -------------------------------------------------------------------------------- import XMonad import XMonad.Layout.Decoration -------------------------------------------------------------------------------- -- Colors -------------------------------------------------------------------------------- myClrBlue = "#7CAFC2" -- Blue myClrDGrey = "#585858" -- Dark Grey myClrLGrey = "#ABABAB" -- Light Grey myClrRed = "#AB4642" -- Red myClrWhite = "#F8F8F8" -- White -------------------------------------------------------------------------------- -- Borders -------------------------------------------------------------------------------- myBorderWidth :: Dimension -- Border width declaration myBorderWidth = 1 -- Border width myClrNormalBorder = myClrDGrey -- Normal border myClrFocusedBorder = myClrLGrey -- Focused border -------------------------------------------------------------------------------- -- Fonts -------------------------------------------------------------------------------- myFnt = "xft:DejaVu Sans Mono:pixelsize=12:Book" -- Main font myFntLayTab = myFnt -- Font for Tabbed myFntGrid = myFnt -- Font for Grid -------------------------------------------------------------------------------- -- Theme 'Tabbed' Layout -------------------------------------------------------------------------------- myThemeLayoutTabbed :: Theme myThemeLayoutTabbed = defaultTheme -- Active tab { activeColor = myClrLGrey -- Color , activeBorderColor = myClrWhite -- Border , activeTextColor = myClrWhite -- Text -- Inactive tab , inactiveColor = myClrDGrey -- Color , inactiveBorderColor = myClrWhite -- Border , inactiveTextColor = myClrWhite -- Text -- Urgent tab , urgentColor = myClrDGrey -- Color , urgentBorderColor = myClrRed -- Border , urgentTextColor = myClrRed -- Text -- Font , fontName = myFntLayTab }
sljrobin/dotfiles
xmonad/.xmonad/lib/Appearance.hs
gpl-2.0
2,458
0
6
467
189
136
53
27
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./OWL2/MS.hs Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Datatypes specific to the Manchester Syntax of OWL 2 References : <http://www.w3.org/TR/owl2-manchester-syntax/> -} module OWL2.MS where import Common.Id import OWL2.AS import Data.Data import qualified Data.Map as Map import qualified Data.Set as Set {- | annotions are annotedAnnotationList that must be preceded by the keyword @Annotations:@ if non-empty -} type Annotations = [Annotation] type AnnotatedList a = [(Annotations, a)] -- | this datatype extends the Manchester Syntax to also allow GCIs data Extended = Misc Annotations | ClassEntity ClassExpression | ObjectEntity ObjectPropertyExpression | SimpleEntity Entity deriving (Show, Eq, Ord, Typeable, Data) -- | frames with annotated lists data ListFrameBit = AnnotationBit (AnnotatedList AnnotationProperty) -- relation | ExpressionBit (AnnotatedList ClassExpression) -- relation | ObjectBit (AnnotatedList ObjectPropertyExpression) -- relation | DataBit (AnnotatedList DataPropertyExpression) -- relation | IndividualSameOrDifferent (AnnotatedList Individual) -- relation | ObjectCharacteristics (AnnotatedList Character) | DataPropRange (AnnotatedList DataRange) | IndividualFacts (AnnotatedList Fact) deriving (Show, Eq, Ord, Typeable, Data) data AnnoType = Declaration | Assertion | XmlError String deriving (Show, Eq, Ord, Typeable, Data) -- | frames which start with annotations data AnnFrameBit = AnnotationFrameBit AnnoType | DataFunctional | DatatypeBit DataRange | ClassDisjointUnion [ClassExpression] | ClassHasKey [ObjectPropertyExpression] [DataPropertyExpression] | ObjectSubPropertyChain [ObjectPropertyExpression] deriving (Show, Eq, Ord, Typeable, Data) data Fact = ObjectPropertyFact PositiveOrNegative ObjectPropertyExpression Individual | DataPropertyFact PositiveOrNegative DataPropertyExpression Literal deriving (Show, Eq, Ord, Typeable, Data) data FrameBit = ListFrameBit (Maybe Relation) ListFrameBit | AnnFrameBit Annotations AnnFrameBit deriving (Show, Eq, Ord, Typeable, Data) data Frame = Frame Extended [FrameBit] deriving (Show, Eq, Ord, Typeable, Data) data Axiom = PlainAxiom { axiomTopic :: Extended -- the Class or Individual , axiomBit :: FrameBit -- the property expressed by the sentence } deriving (Show, Eq, Ord, Typeable, Data) {- Individual: alex <------ axiomTopic Facts: hasParent john <------ axiomBit -} mkExtendedEntity :: Entity -> Extended mkExtendedEntity e@(Entity _ ty iri) = case ty of Class -> ClassEntity $ Expression iri ObjectProperty -> ObjectEntity $ ObjectProp iri _ -> SimpleEntity e getAxioms :: Frame -> [Axiom] getAxioms (Frame e fbl) = map (PlainAxiom e) fbl axToFrame :: Axiom -> Frame axToFrame (PlainAxiom e fb) = Frame e [fb] instance GetRange Axiom where getRange = Range . joinRanges . map rangeSpan . Set.toList . symsOfAxiom data Ontology = Ontology { name :: OntologyIRI , imports :: [ImportIRI] , ann :: [Annotations] , ontFrames :: [Frame] } deriving (Show, Eq, Ord, Typeable, Data) data OntologyDocument = OntologyDocument { prefixDeclaration :: PrefixMap , ontology :: Ontology } deriving (Show, Eq, Ord, Typeable, Data) instance GetRange OntologyDocument emptyOntology :: [Frame] -> Ontology emptyOntology = Ontology nullQName [] [] emptyOntologyDoc :: OntologyDocument emptyOntologyDoc = OntologyDocument Map.empty $ emptyOntology [] isEmptyOntology :: Ontology -> Bool isEmptyOntology (Ontology oiri annoList impList fs) = isNullQName oiri && null annoList && null impList && null fs isEmptyOntologyDoc :: OntologyDocument -> Bool isEmptyOntologyDoc (OntologyDocument ns onto) = Map.null ns && isEmptyOntology onto emptyAnnoList :: [a] -> AnnotatedList a emptyAnnoList = map $ \ x -> ([], x) symsOfAxiom :: Axiom -> Set.Set Entity symsOfAxiom (PlainAxiom e f) = Set.union (symsOfExtended e) $ symsOfFrameBit f symsOfExtended :: Extended -> Set.Set Entity symsOfExtended e = case e of Misc as -> symsOfAnnotations as SimpleEntity s -> Set.singleton s ObjectEntity o -> symsOfObjectPropertyExpression o ClassEntity c -> symsOfClassExpression c symsOfObjectPropertyExpression :: ObjectPropertyExpression -> Set.Set Entity symsOfObjectPropertyExpression o = case o of ObjectProp i -> Set.singleton $ mkEntity ObjectProperty i ObjectInverseOf i -> symsOfObjectPropertyExpression i symsOfClassExpression :: ClassExpression -> Set.Set Entity symsOfClassExpression ce = case ce of Expression c -> Set.singleton $ mkEntity Class c ObjectJunction _ cs -> Set.unions $ map symsOfClassExpression cs ObjectComplementOf c -> symsOfClassExpression c ObjectOneOf is -> Set.fromList $ map (mkEntity NamedIndividual) is ObjectValuesFrom _ oe c -> Set.union (symsOfObjectPropertyExpression oe) $ symsOfClassExpression c ObjectHasValue oe i -> Set.insert (mkEntity NamedIndividual i) $ symsOfObjectPropertyExpression oe ObjectHasSelf oe -> symsOfObjectPropertyExpression oe ObjectCardinality (Cardinality _ _ oe mc) -> Set.union (symsOfObjectPropertyExpression oe) $ maybe Set.empty symsOfClassExpression mc DataValuesFrom _ de dr -> Set.insert (mkEntity DataProperty de) $ symsOfDataRange dr DataHasValue de _ -> Set.singleton $ mkEntity DataProperty de DataCardinality (Cardinality _ _ d m) -> Set.insert (mkEntity DataProperty d) $ maybe Set.empty symsOfDataRange m symsOfDataRange :: DataRange -> Set.Set Entity symsOfDataRange dr = case dr of DataType t _ -> Set.singleton $ mkEntity Datatype t DataJunction _ ds -> Set.unions $ map symsOfDataRange ds DataComplementOf d -> symsOfDataRange d DataOneOf _ -> Set.empty symsOfAnnotation :: Annotation -> Set.Set Entity symsOfAnnotation (Annotation as p _) = Set.insert (mkEntity AnnotationProperty p) $ Set.unions (map symsOfAnnotation as) symsOfAnnotations :: Annotations -> Set.Set Entity symsOfAnnotations = Set.unions . map symsOfAnnotation symsOfFrameBit :: FrameBit -> Set.Set Entity symsOfFrameBit fb = case fb of ListFrameBit _ lb -> symsOfListFrameBit lb AnnFrameBit as af -> Set.union (symsOfAnnotations as) $ symsOfAnnFrameBit af symsOfAnnFrameBit :: AnnFrameBit -> Set.Set Entity symsOfAnnFrameBit af = case af of AnnotationFrameBit _ -> Set.empty DataFunctional -> Set.empty DatatypeBit dr -> symsOfDataRange dr ClassDisjointUnion cs -> Set.unions $ map symsOfClassExpression cs ClassHasKey os ds -> Set.union (Set.unions $ map symsOfObjectPropertyExpression os) . Set.fromList $ map (mkEntity DataProperty) ds ObjectSubPropertyChain os -> Set.unions $ map symsOfObjectPropertyExpression os symsOfListFrameBit :: ListFrameBit -> Set.Set Entity symsOfListFrameBit lb = case lb of AnnotationBit l -> annotedSyms (Set.singleton . mkEntity AnnotationProperty) l ExpressionBit l -> annotedSyms symsOfClassExpression l ObjectBit l -> annotedSyms symsOfObjectPropertyExpression l DataBit l -> annotedSyms (Set.singleton . mkEntity DataProperty) l IndividualSameOrDifferent l -> annotedSyms (Set.singleton . mkEntity NamedIndividual) l ObjectCharacteristics l -> annotedSyms (const Set.empty) l DataPropRange l -> annotedSyms symsOfDataRange l IndividualFacts l -> annotedSyms symsOfFact l symsOfFact :: Fact -> Set.Set Entity symsOfFact fact = case fact of ObjectPropertyFact _ oe i -> Set.insert (mkEntity NamedIndividual i) $ symsOfObjectPropertyExpression oe DataPropertyFact _ d _ -> Set.singleton $ mkEntity DataProperty d annotedSyms :: (a -> Set.Set Entity) -> AnnotatedList a -> Set.Set Entity annotedSyms f l = Set.union (Set.unions $ map (symsOfAnnotations . fst) l) . Set.unions $ map (f . snd) l
gnn/Hets
OWL2/MS.hs
gpl-2.0
7,970
0
13
1,348
2,253
1,134
1,119
160
11
{-# OPTIONS_GHC -Wall #-} -- rewrite of dwm-status.c in the one true programming language -- but first, install haskell-x11 import Graphics.X11.Xlib.Event (sync) import Graphics.X11.Xlib.Display (defaultRootWindow, openDisplay, closeDisplay) -- import Graphics.X11.Xlib.Display -- import Graphics.X11.Xlib.Types (Display) import Graphics.X11.Xlib.Types (Display) import Graphics.X11.Xlib.Window (storeName) import Control.Concurrent (threadDelay) import Control.Monad (forever) import Control.Applicative ((<$>)) import System.Locale (defaultTimeLocale) -- for time import System.Time -- import Data.Time.Clock -- import Data.Time.LocalTime -- import Data.Time.Format import Text.Printf -- see below for ansi codes help -- colours red, white, magenta, purple, yellow, blue, brightGreen, deepGreen :: String whitebg, magentabg, purplebg, bluebg, deepGreenbg :: String unknown :: String red = "\x1b[38;5;196m" white = "\x1b[38;5;255m" whitebg = "\x1b[48;5;255m" magenta = "\x1b[38;5;199m" magentabg = "\x1b[48;5;199m" yellow = "\x1b[38;5;190m" blue = "\x1b[38;5;21m" bluebg = "\x1b[48;5;21m" brightGreen = "\x1b[38;5;46m" -- 40 is less bright deepGreen = "\x1b[38;5;34m" deepGreenbg = "\x1b[48;5;34m" purple = "\x1b[38;5;57m" purplebg = "\x1b[48;5;57m" unknown = yellow resetAll :: String resetAll = "\x1b[0m" -- resets all attributes main :: IO () main = do dpy <- openDisplay "" mainLoop dpy closeDisplay dpy playWithDpy :: IO () playWithDpy = openDisplay "" >>= closeDisplay -- LOL mainLoop :: Display -> IO () mainLoop dpy = forever $ do time <- getDateTime "[%a %b %d] %H:%M:%S" (x,y,z) <- getLoadAvg let avgs = printf "[%.2f %.2f %.2f] " x y z batt <- getBattery temper <- getTemperature mail <- getMail setStatus dpy $ avgs ++ batt ++ temper ++ mail ++ time threadDelay 1000000 -- sleep one second -- threadDelay 6000000 -- sleep six seconds -- threadDelay 10000000 -- sleep ten seconds -- threadDelay 60000000 -- sleep sixty seconds getMail :: IO String -- this file should be populated by cron getMail = do mail <- getFileData "/tmp/dwm-status.mail" return $ "[mail " ++ show mail ++ "] " setStatus :: Display -> String -> IO () setStatus dpy str = do let window = defaultRootWindow dpy storeName dpy window str sync dpy False {- -- getDateTime could be implemented instead with Data.Time.Calendar getDateTime :: IO String getDateTime = do time <- getCurrentTime timezone <- getCurrentTimeZone let localTime = utcToLocalTime timezone time return $ formatTime defaultTimeLocale "[%a %b %d] %H:%M:%S" localTime -- return $ formatTime defaultTimeLocale "[%a %b %d] %H:%M" localTime -- or like this -- getDateTime = do -- localTime <- getClockTime >>= toCalendarTime -- return $ formatCalendarTime defaultTimeLocale "[%a %b %d] %H:%M:%S" localTime -- return $ formatCalendarTime defaultTimeLocale "[%a %b %d] %H:%M" localTime -- or like this: -- getDateTime = getClockTime >>= toCalendarTime >>= return . -- formatCalendarTime defaultTimeLocale "[%a %b %d] %H:%M:%S" -} -- or like this! -- give it the format you want getDateTime :: String -> IO String getDateTime str = getClockTime >>= toCalendarTime >>= return . formatCalendarTime defaultTimeLocale str type LoadAvgs = (Double, Double, Double) getLoadAvg :: IO LoadAvgs -- getLoadAvg :: IO (Double, Double, Double) getLoadAvg = parseLoadAvg <$> readFile "/proc/loadavg" where parseLoadAvg :: String -> LoadAvgs parseLoadAvg input = (x,y,z) where (x:y:z:_) = map read (words input) getFileData :: FilePath -> IO Int getFileData = fmap read . readFile getTemperature :: IO String getTemperature = do temper <- ((/1000) . fromIntegral) <$> getFileData "/sys/class/thermal/thermal_zone0/temp" let colour = f temper return $ printf "[%s%02.1f°C%s] " colour temper (getColour 0) where f :: Double -> String f temper | temper > 80 = getColour 1 -- red | temper > 75 = getColour 2 -- yellow | temper < 70 = getColour 6 -- blue | otherwise = getColour 0 -- no colour getBattery :: IO String getBattery = do capacity <- getFileData "/sys/class/power_supply/BAT0/capacity" status <- readFile "/sys/class/power_supply/BAT0/status" let chargin = status /= "Discharging\n" {- -- TODO: display warning on low battery, using zenity if capacity < 95 then do if not chargin then putStrLn "not plugged in! oh no :(" else putStrLn "plugged in" else putStrLn "lotsa battery left!" -} let colour :: String colour = if chargin then if capacity > 95 then getColour 3 -- deep green else getColour 4 -- magenta else if capacity > 70 then getColour 3 -- deep green else if capacity > 30 then getColour 6 -- blue else if capacity > 10 then getColour 2 -- yellow else getColour 1 -- red return $ printf "[%s%d%%%s] " colour capacity (getColour 0) -- return (colour ++ show capacity ++ getColour 0) -- positive codes return various colours -- code 0 returns a reset string -- code -1 returns empty string -- one way to display all available colours: weechat --colors getColour :: Int -> String getColour 0 = "\x1b[0m" -- reset getColour 1 = "\x1b[38;5;196m" -- red getColour 2 = "\x1b[38;5;190m" -- yellow getColour 3 = "\x1b[38;5;34m" -- deep green getColour 4 = "\x1b[38;5;199m" -- magenta getColour 5 = "\x1b[38;5;46m" -- bright green getColour 6 = "\x1b[38;5;45m" -- bright blue getColour 7 = "\x1b[38;5;21m" -- blue getColour _ = "" -- empty string {- an ansi escape sequence is in the form: \e[<code>m where: \e - escape - ascii 27 / hex 1b / octal 033 [ - literal bracket m - literal 'm' the code is one of the following: 0 - reset colors to default n;m n - o - normal color 1 - 'bright' color m - 30-37 - foreground 40-47 - background n;5;m n - 38 - foreground 48 - background 5 - literal '5' m - 0-15 - classic ansi color 16-231 - xterm 256-color rgb color 232-255 - grayscale see all of the colours with weechat --colors -}
ninedotnine/dwm-status-haskell
dwm-status.hs
gpl-3.0
6,548
16
14
1,686
1,143
596
547
107
6
{-# LANGUAGE UnicodeSyntax #-} module Util.Match ( match , matchBy , MatchResult , leftOnly , rightOnly , both ) where import BaseImport import Data.List data MatchResult ξ = MatchResult { leftOnly ∷ [ξ] , rightOnly ∷ [ξ] , both ∷ [(ξ, ξ)] } deriving Show addRight ∷ MatchResult ξ → [ξ] → MatchResult ξ addRight r zs = r { rightOnly = rightOnly r ++ zs } addLeft ∷ MatchResult ξ → [ξ] → MatchResult ξ addLeft r zs = r { leftOnly = leftOnly r ++ zs } addBoth ∷ MatchResult ξ → ξ → ξ → MatchResult ξ addBoth r x y = r { both = (x, y) : both r } match ∷ Ord ξ ⇒ [ξ] → [ξ] → MatchResult ξ match = matchBy compare -- -- match left to right items using the ordering enforced by cmp. -- return -- ⋅ leftOnly: x ∈ left s.t. x ∉ right -- ⋅ rightOnly: y ∈ right s.t. y ∉ left -- ⋅ both: (x, y) s.t. x ∈ right, y ∈ left, x ≡ y -- matchBy ∷ (ξ → ξ → Ordering) → [ξ] → [ξ] → MatchResult ξ matchBy cmp left right = φ (MatchResult [] [] []) (sortBy cmp left) (sortBy cmp right) where φ r [] [] = r φ r [] ys = addRight r ys φ r xs [] = addLeft r xs φ r lft@(x:xs) rgt@(y:ys) | cmp x y ≡ EQ = φ (addBoth r x y) xs ys | cmp x y ≡ LT = φ (addLeft r [x]) xs rgt | cmp x y ≡ GT = φ (addRight r [y]) lft ys φ r _ _ = r
c0c0n3/audidoza
app/Util/Match.hs
gpl-3.0
1,505
0
11
486
567
300
267
33
5
{-# LANGUAGE OverloadedStrings #-} module Main where import System.Environment import System.Exit import System.Remote.Monitoring import Brnfckr.Eval (runBrainFuck) main :: IO () main = do forkServer "localhost" 8000 fname <- fmap head getArgs source <- readFile fname stream <- getContents case runBrainFuck source stream of ((Left e, _), _) -> print e >> exitWith (ExitFailure 1) ((_, _), s) -> putStr s
johntyree/brnfckr
src/executables/Main.hs
gpl-3.0
428
0
13
82
153
79
74
15
2
-- Copyright (C) 2014 Boucher, Antoni <[email protected]> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 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/>. {-| Module : Cookbook Description : LaTeX Cookbook document class for HaTeX. Copyright : © Antoni Boucher, 2014 License : GPL-3 Maintener : [email protected] Stability : experimental Portability : POSIX This module provides functions for the commands and environments of the cookbook LaTeX document class. -} module Cookbook (cookingPart, cookingTime, ingredients, marinateTime, portions, preparationTime, recipe, steps, totalTime) where import Text.LaTeX.Base.Class (LaTeXC, comm0, comm1, liftL) import Text.LaTeX.Base.Syntax (LaTeX (TeXEnv)) import Utils.LaTeX (comm1Opt1, comm3) -- |Generate a 'cookingpart' command. cookingPart :: LaTeXC l => l -> l cookingPart = comm1 "cookingpart" -- |Generate a 'cookingtime' command. cookingTime :: LaTeXC l => Maybe l -> l -> l cookingTime = comm1Opt1 "cookingtime" -- |Generate an 'ingredients' environment. ingredients :: LaTeXC l => l -> l ingredients = liftL $ TeXEnv "ingredients" [] -- |Generate a 'marinatetime' command. marinateTime :: LaTeXC l => Maybe l -> l -> l marinateTime = comm1Opt1 "macerationtime" -- |Generate a 'portions' command. portions :: LaTeXC l => l -> l portions = comm1 "portions" -- |Generate a 'preparationtime' command. preparationTime :: LaTeXC l => Maybe l -> l -> l preparationTime = comm1Opt1 "preparationtime" -- |Generate a 'recipe' command. recipe :: LaTeXC l => l -> l -> l -> l recipe = comm3 "recipe" -- |Generate a 'steps' environment. steps :: LaTeXC l => l -> l steps = liftL $ TeXEnv "steps" [] -- |Generate a 'totaltime' command. totalTime :: LaTeXC l => l totalTime = comm0 "totaltime"
antoyo/recettesduquebec2tex
src/Cookbook.hs
gpl-3.0
2,317
0
8
396
364
206
158
22
1
import Control.Monad as M import Control.Monad as MP import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Resource import Data.Array.Repa as R import Data.Conduit import Data.Conduit.List as CL import Data.List as L import Data.Vector.Unboxed as VU import PetaVision.Image.ImageIO import PetaVision.Utility.HDF5 import System.Directory import System.Environment {-# INLINE plotLabel #-} plotLabel :: FilePath -> ImageRepa -> IO () plotLabel filePath = plotImageRepa filePath . normalizeImageRepa . fmap (computeS . R.map (\x -> if x == 255 then 0 else if x == 1 then 2 else 1)) {-# INLINE plotImage #-} plotImage :: FilePath -> R.Array U DIM3 Double -> IO () plotImage filePath arr = let (Z :. nf :. rows :. cols) = extent arr maxIndexArr = fromListUnboxed (Z :. (1 :: Int) :. rows :. cols) -- . -- L.map -- (\k -> -- if k == 1 -- then 1 -- else 0) $ [ fromIntegral . VU.maxIndex . toUnboxed . computeS . R.slice arr $ (Z :. All :. i :. j) | i <- [0 .. rows - 1] , j <- [0 .. cols - 1] ] range = ( VU.minimum . toUnboxed $ maxIndexArr , VU.maximum . toUnboxed $ maxIndexArr) in do -- M.mapM_ -- (\i -> -- plotImageRepa (filePath L.++ "_" L.++ show i L.++ ".png") . -- normalizeImageRepa . -- Image 8 . -- computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.slice arr $ -- (Z :. i :. All :. All)) -- [0 .. nf - 1] plotImageRepa (filePath L.++ ".png") . normalizeImageRepa . Image 8 $ maxIndexArr print range main = do (filePath:_) <- getArgs xs <- runResourceT . runConduit $ hdf5Source1 filePath "label" "data" .| CL.consume removePathForcibly "Recon" createDirectory "Recon" MP.zipWithM_ (\i (labelArr, imgArr) -> do plotLabel ("Recon/Label_" L.++ show i L.++ ".png") . Image 8 $ labelArr plotImage ("Recon/Recon_" L.++ show i) imgArr) [1 ..] xs
XinhuaZhang/PetaVisionHaskell
Application/Amoeba/Plot.hs
gpl-3.0
2,384
1
18
929
587
318
269
57
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CodeDeploy.UpdateDeploymentGroup -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Changes information about an existing deployment group. -- -- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_UpdateDeploymentGroup.html> module Network.AWS.CodeDeploy.UpdateDeploymentGroup ( -- * Request UpdateDeploymentGroup -- ** Request constructor , updateDeploymentGroup -- ** Request lenses , udgApplicationName , udgAutoScalingGroups , udgCurrentDeploymentGroupName , udgDeploymentConfigName , udgEc2TagFilters , udgNewDeploymentGroupName , udgServiceRoleArn -- * Response , UpdateDeploymentGroupResponse -- ** Response constructor , updateDeploymentGroupResponse -- ** Response lenses , udgrHooksNotCleanedUp ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CodeDeploy.Types import qualified GHC.Exts data UpdateDeploymentGroup = UpdateDeploymentGroup { _udgApplicationName :: Text , _udgAutoScalingGroups :: List "autoScalingGroups" Text , _udgCurrentDeploymentGroupName :: Text , _udgDeploymentConfigName :: Maybe Text , _udgEc2TagFilters :: List "ec2TagFilters" EC2TagFilter , _udgNewDeploymentGroupName :: Maybe Text , _udgServiceRoleArn :: Maybe Text } deriving (Eq, Read, Show) -- | 'UpdateDeploymentGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'udgApplicationName' @::@ 'Text' -- -- * 'udgAutoScalingGroups' @::@ ['Text'] -- -- * 'udgCurrentDeploymentGroupName' @::@ 'Text' -- -- * 'udgDeploymentConfigName' @::@ 'Maybe' 'Text' -- -- * 'udgEc2TagFilters' @::@ ['EC2TagFilter'] -- -- * 'udgNewDeploymentGroupName' @::@ 'Maybe' 'Text' -- -- * 'udgServiceRoleArn' @::@ 'Maybe' 'Text' -- updateDeploymentGroup :: Text -- ^ 'udgApplicationName' -> Text -- ^ 'udgCurrentDeploymentGroupName' -> UpdateDeploymentGroup updateDeploymentGroup p1 p2 = UpdateDeploymentGroup { _udgApplicationName = p1 , _udgCurrentDeploymentGroupName = p2 , _udgNewDeploymentGroupName = Nothing , _udgDeploymentConfigName = Nothing , _udgEc2TagFilters = mempty , _udgAutoScalingGroups = mempty , _udgServiceRoleArn = Nothing } -- | The application name corresponding to the deployment group to update. udgApplicationName :: Lens' UpdateDeploymentGroup Text udgApplicationName = lens _udgApplicationName (\s a -> s { _udgApplicationName = a }) -- | The replacement list of Auto Scaling groups to be included in the deployment -- group, if you want to change them. udgAutoScalingGroups :: Lens' UpdateDeploymentGroup [Text] udgAutoScalingGroups = lens _udgAutoScalingGroups (\s a -> s { _udgAutoScalingGroups = a }) . _List -- | The current name of the existing deployment group. udgCurrentDeploymentGroupName :: Lens' UpdateDeploymentGroup Text udgCurrentDeploymentGroupName = lens _udgCurrentDeploymentGroupName (\s a -> s { _udgCurrentDeploymentGroupName = a }) -- | The replacement deployment configuration name to use, if you want to change -- it. udgDeploymentConfigName :: Lens' UpdateDeploymentGroup (Maybe Text) udgDeploymentConfigName = lens _udgDeploymentConfigName (\s a -> s { _udgDeploymentConfigName = a }) -- | The replacement set of Amazon EC2 tags to filter on, if you want to change -- them. udgEc2TagFilters :: Lens' UpdateDeploymentGroup [EC2TagFilter] udgEc2TagFilters = lens _udgEc2TagFilters (\s a -> s { _udgEc2TagFilters = a }) . _List -- | The new name of the deployment group, if you want to change it. udgNewDeploymentGroupName :: Lens' UpdateDeploymentGroup (Maybe Text) udgNewDeploymentGroupName = lens _udgNewDeploymentGroupName (\s a -> s { _udgNewDeploymentGroupName = a }) -- | A replacement service role's ARN, if you want to change it. udgServiceRoleArn :: Lens' UpdateDeploymentGroup (Maybe Text) udgServiceRoleArn = lens _udgServiceRoleArn (\s a -> s { _udgServiceRoleArn = a }) newtype UpdateDeploymentGroupResponse = UpdateDeploymentGroupResponse { _udgrHooksNotCleanedUp :: List "hooksNotCleanedUp" AutoScalingGroup } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList UpdateDeploymentGroupResponse where type Item UpdateDeploymentGroupResponse = AutoScalingGroup fromList = UpdateDeploymentGroupResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _udgrHooksNotCleanedUp -- | 'UpdateDeploymentGroupResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'udgrHooksNotCleanedUp' @::@ ['AutoScalingGroup'] -- updateDeploymentGroupResponse :: UpdateDeploymentGroupResponse updateDeploymentGroupResponse = UpdateDeploymentGroupResponse { _udgrHooksNotCleanedUp = mempty } -- | If the output contains no data, and the corresponding deployment group -- contained at least one Auto Scaling group, AWS CodeDeploy successfully -- removed all corresponding Auto Scaling lifecycle event hooks from the AWS -- user account. If the output does contain data, AWS CodeDeploy could not -- remove some Auto Scaling lifecycle event hooks from the AWS user account. udgrHooksNotCleanedUp :: Lens' UpdateDeploymentGroupResponse [AutoScalingGroup] udgrHooksNotCleanedUp = lens _udgrHooksNotCleanedUp (\s a -> s { _udgrHooksNotCleanedUp = a }) . _List instance ToPath UpdateDeploymentGroup where toPath = const "/" instance ToQuery UpdateDeploymentGroup where toQuery = const mempty instance ToHeaders UpdateDeploymentGroup instance ToJSON UpdateDeploymentGroup where toJSON UpdateDeploymentGroup{..} = object [ "applicationName" .= _udgApplicationName , "currentDeploymentGroupName" .= _udgCurrentDeploymentGroupName , "newDeploymentGroupName" .= _udgNewDeploymentGroupName , "deploymentConfigName" .= _udgDeploymentConfigName , "ec2TagFilters" .= _udgEc2TagFilters , "autoScalingGroups" .= _udgAutoScalingGroups , "serviceRoleArn" .= _udgServiceRoleArn ] instance AWSRequest UpdateDeploymentGroup where type Sv UpdateDeploymentGroup = CodeDeploy type Rs UpdateDeploymentGroup = UpdateDeploymentGroupResponse request = post "UpdateDeploymentGroup" response = jsonResponse instance FromJSON UpdateDeploymentGroupResponse where parseJSON = withObject "UpdateDeploymentGroupResponse" $ \o -> UpdateDeploymentGroupResponse <$> o .:? "hooksNotCleanedUp" .!= mempty
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/UpdateDeploymentGroup.hs
mpl-2.0
7,646
0
10
1,565
930
556
374
107
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.StorageGateway.RemoveTagsFromResource -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation removes one or more tags from the specified resource. -- -- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RemoveTagsFromResource.html AWS API Reference> for RemoveTagsFromResource. module Network.AWS.StorageGateway.RemoveTagsFromResource ( -- * Creating a Request removeTagsFromResource , RemoveTagsFromResource -- * Request Lenses , rtfrTagKeys , rtfrResourceARN -- * Destructuring the Response , removeTagsFromResourceResponse , RemoveTagsFromResourceResponse -- * Response Lenses , rtfrrsResourceARN , rtfrrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.StorageGateway.Types import Network.AWS.StorageGateway.Types.Product -- | RemoveTagsFromResourceInput -- -- /See:/ 'removeTagsFromResource' smart constructor. data RemoveTagsFromResource = RemoveTagsFromResource' { _rtfrTagKeys :: !(Maybe [Text]) , _rtfrResourceARN :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RemoveTagsFromResource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rtfrTagKeys' -- -- * 'rtfrResourceARN' removeTagsFromResource :: RemoveTagsFromResource removeTagsFromResource = RemoveTagsFromResource' { _rtfrTagKeys = Nothing , _rtfrResourceARN = Nothing } -- | The keys of the tags you want to remove from the specified resource. A -- tag is composed of a key\/value pair. rtfrTagKeys :: Lens' RemoveTagsFromResource [Text] rtfrTagKeys = lens _rtfrTagKeys (\ s a -> s{_rtfrTagKeys = a}) . _Default . _Coerce; -- | The Amazon Resource Name (ARN) of the resource you want to remove the -- tags from. rtfrResourceARN :: Lens' RemoveTagsFromResource (Maybe Text) rtfrResourceARN = lens _rtfrResourceARN (\ s a -> s{_rtfrResourceARN = a}); instance AWSRequest RemoveTagsFromResource where type Rs RemoveTagsFromResource = RemoveTagsFromResourceResponse request = postJSON storageGateway response = receiveJSON (\ s h x -> RemoveTagsFromResourceResponse' <$> (x .?> "ResourceARN") <*> (pure (fromEnum s))) instance ToHeaders RemoveTagsFromResource where toHeaders = const (mconcat ["X-Amz-Target" =# ("StorageGateway_20130630.RemoveTagsFromResource" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON RemoveTagsFromResource where toJSON RemoveTagsFromResource'{..} = object (catMaybes [("TagKeys" .=) <$> _rtfrTagKeys, ("ResourceARN" .=) <$> _rtfrResourceARN]) instance ToPath RemoveTagsFromResource where toPath = const "/" instance ToQuery RemoveTagsFromResource where toQuery = const mempty -- | RemoveTagsFromResourceOutput -- -- /See:/ 'removeTagsFromResourceResponse' smart constructor. data RemoveTagsFromResourceResponse = RemoveTagsFromResourceResponse' { _rtfrrsResourceARN :: !(Maybe Text) , _rtfrrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RemoveTagsFromResourceResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rtfrrsResourceARN' -- -- * 'rtfrrsResponseStatus' removeTagsFromResourceResponse :: Int -- ^ 'rtfrrsResponseStatus' -> RemoveTagsFromResourceResponse removeTagsFromResourceResponse pResponseStatus_ = RemoveTagsFromResourceResponse' { _rtfrrsResourceARN = Nothing , _rtfrrsResponseStatus = pResponseStatus_ } -- | The Amazon Resource Name (ARN) of the resource that the tags were -- removed from. rtfrrsResourceARN :: Lens' RemoveTagsFromResourceResponse (Maybe Text) rtfrrsResourceARN = lens _rtfrrsResourceARN (\ s a -> s{_rtfrrsResourceARN = a}); -- | The response status code. rtfrrsResponseStatus :: Lens' RemoveTagsFromResourceResponse Int rtfrrsResponseStatus = lens _rtfrrsResponseStatus (\ s a -> s{_rtfrrsResponseStatus = a});
olorin/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/RemoveTagsFromResource.hs
mpl-2.0
5,076
0
13
1,070
679
406
273
88
1
{-# LANGUAGE OverloadedStrings #-} module Commands.Autokick ( autokick ) where import Data.ByteString (ByteString) import Control.Monad import Data.Maybe import Data.Response import Network.IRC autokick :: Monad m => ByteString -> ByteString -> Response m autokick msg usr = simpleCmd' msg $ \p chan -> pure $ do NickName n _ _ <- p guard $ n == usr return $ kick (fromMaybe "" chan) usr (Just msg)
tsahyt/lmrbot
src/Commands/Autokick.hs
agpl-3.0
455
0
13
121
146
75
71
16
1
module ObjD.Link.Inline ( maybeInlineCall, inlineCall )where import ObjD.Link.Struct import ObjD.Link.Env import ObjD.Link.DataType import qualified Data.Map as M import Control.Arrow import Data.Maybe maybeInlineCall :: Env -> Exp -> Exp maybeInlineCall env e = let callExpOpt = case e of Dot _ c@Call{} -> Just c Call{} -> Just e _ -> Nothing defOpt = case callExpOpt of Just (Call dd _ _ _) -> Just dd Nothing -> Nothing in if isJust defOpt && DefModInline `elem` defMods (fromJust defOpt) then inlineCall env{envVarSuffix = "__il_" ++ envVarSuffix env} e else e inlineCall :: Env -> Exp -> Exp inlineCall env e = let callExpOpt = case e of Dot _ c@Call{} -> Just c Call{} -> Just e _ -> Nothing (Call def _ pars callGens) = fromJust callExpOpt pars' = if DefModStatic `notElem` defMods def then selfPar : pars else pars selfExp = case e of Dot l _ -> l selfTp = exprDataType selfExp selfClass = dataTypeClass env selfTp selfPar = (localVal "self" selfTp, selfExp) needSelf = case selfExp of Self _ -> False Super _ -> False _ -> True declaredVals :: [Def] declaredVals = forExp findVal $ defBody def where findVal (Val _ d) = [d] findVal _ = [] defClass :: Class defClass = fromJust $ defClassRec selfClass where defClassRec cl | def `elem` classDefs cl = Just cl | otherwise = listToMaybe $ mapMaybe defClassRec $ map fst $ extendsRefs $ classExtends cl gens :: Generics gens = M.union classGensMap defGensMap where classGensMap = buildGenerics defClass $ fromJust $ upGenericsToClass defClass ((dataTypeClass env selfTp), (dataTypeGenerics selfTp)) defGensMap = M.fromList $ zip (maybe [] (map className . defGenericsClasses) $ defGenerics def) callGens mapDeclaredValsGenerics = map repGens declaredVals where repGens d = (d, d{defType = unwrapGeneric $ repgens $ defType d, defName = envVarSuffix env ++ defName d}) repgens = replaceGenerics False gens . unblockGenerics replacedExp = mapExp (rep True) $ defBody def rep :: Bool -> Exp -> Maybe Exp rep r (Dot (Call d tp [] _) (Call Def{defMods = mbLamdaMods} _ lambdaCallPars _)) | DefModApplyLambda `elem` mbLamdaMods = fmap (unwrapLambda (map (mapExp (rep r) . snd) lambdaCallPars)) $ findRef d tp rep _ (LambdaCall (Call d tp [] _)) = fmap (unwrapLambda []) $ findRef d tp rep True (Dot l r@(Call _ _ [] _)) = Just $ Dot (mapExp (rep True) l) (mapExp (rep False) r) rep True (Arrow l r@(Call _ _ [] _)) = Just $ Arrow (mapExp (rep True) l) (mapExp (rep False) r) rep True (Call d tp [] _) | DefModField `elem` defMods d || DefModLocal `elem` defMods d = findRef d tp rep r (Call d tp cpars cgens) = Just $ Call d (repgens tp) (map (second $ mapExp (rep r)) cpars) (map repgens cgens) rep r (Val b dd) = fmap (\d -> Val b $ d{defBody = mapExp (rep r) (defBody d)} ) $ lookup dd mapDeclaredValsGenerics rep _ (Self _) = if needSelf then lookup (fst selfPar) refs else Nothing rep _ (Is tp) = Just $ Is $ repgens tp rep _ (As tp) = Just $ As $ repgens tp rep _ (CastDot tp) = Just $ CastDot $ repgens tp rep r (Cast tp ee) = Just $ Cast (repgens tp) (mapExp (rep r) ee) rep _ _ = Nothing findRef :: Def -> DataType -> Maybe Exp findRef d tp = fmap checkOpt $ lookup d refs where checkOpt ee = case tp of TPOption True _ -> case ee of Call d' (TPOption False otp) [] [] -> Call d' (TPOption True otp) [] [] _ -> ee _ -> ee refs :: [(Def, Exp)] refs = (map (second callRef) vals) ++ pars' ++ map (second callRef) mapDeclaredValsGenerics vals = (map dec parsForDeclareVars) dec (d, pe) = (d, tmpVal env (defName d) (repgens $ defType d) pe) unwrapLambda :: [Exp] -> Exp -> Exp unwrapLambda [] (Lambda _ ee _) = ee unwrapLambda parExps (Lambda lpars ee _) = let nonelemPars = (map (\((nm, tp), lpe) -> Val False $ localValE nm tp lpe) $ filter (not . isElementaryExpression . snd ) (zip lpars parExps)) elemPars = map (first fst) $ filter (isElementaryExpression . snd ) (zip lpars parExps) ee' = case elemPars of [] -> ee _ -> mapExp replaceOnEP ee replaceOnEP (Dot l r@(Call _ _ [] [])) = Just $ Dot (mapExp replaceOnEP l) r replaceOnEP (Arrow l r@(Call _ _ [] [])) = Just $ Arrow (mapExp replaceOnEP l) r replaceOnEP (Call d _ [] _) = lookup (defName d) elemPars replaceOnEP _ = Nothing in case nonelemPars of [] -> ee' _ -> Braces $ nonelemPars ++ [ee'] unwrapLambda [] ee = LambdaCall ee unwrapLambda p ee = case unwrapGeneric $ exprDataType ee of tp@TPFun{} -> Dot ee $ call (applyLambdaDef tp) p _ -> ee parsForDeclareVars = filter (checkCountOfUsing . fst) unelementaryPars where unelementaryPars = filter (not . isElementaryExpression . snd) pars' checkCountOfUsing d = (length $ filter (d ==) usingDefs) > 1 usingDefs = forExp findUsage (defBody def) findUsage (Call d _ [] _) = [d] findUsage (Self _) = [fst selfPar | needSelf] findUsage _ = [] in if null parsForDeclareVars then replacedExp else Braces $ (map (Val False . snd) vals) ++ [replacedExp]
antonzherdev/objd
src/ObjD/Link/Inline.hs
lgpl-3.0
5,077
34
20
1,133
2,357
1,190
1,167
112
34
{-# LANGUAGE OverloadedStrings #-} module WaTor.Utils ( both , floatPair , entityKey , isFish , isShark , isEmpty ) where import Control.Applicative import Data.Bifunctor import qualified Data.Text as T import WaTor.Types both :: (a -> b) -> (a, a) -> (b, b) both f = f `bimap` f floatPair :: Coord -> (Float, Float) floatPair = both fromIntegral entityKey :: Entity -> T.Text entityKey Fish{} = "fish" entityKey Shark{} = "shark" entityKey Empty = "empty" isFish, isShark, isEmpty :: Entity -> Bool isFish Fish{} = True isFish _ = False isShark Shark{} = True isShark _ = False isEmpty Empty = True isEmpty _ = False
erochest/wa-tor
src/WaTor/Utils.hs
apache-2.0
725
0
7
213
231
132
99
27
1
module Lycopene.Option.Done (doneIssue) where import Options.Applicative import Lycopene.Option.Command import Lycopene.Option.Internal doneIssue :: ParserInfo Command doneIssue = let doneP = Done <$> argid in info doneP (progDesc "Close an issue and set it has been done")
utky/lycopene
backup/Option/Done.hs
apache-2.0
314
0
9
75
68
38
30
8
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-name-shadowing #-} module HTML.Base where import Control.Monad import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A htmlHeader :: Maybe String -- ^ HTML <title> value -> [FilePath] -- ^ CSS files -> [FilePath] -- ^ JS scripts -> Html htmlHeader title cssFiles scripts = H.head $ do H.title . toHtml $ maybe "bindrop" ("bindrop - " ++) title -- load javascript forM_ scripts $ \s -> H.script ! A.type_ "text/javascript" ! A.src (toValue $ "/static/js/" ++ s) $ return () -- load css forM_ cssFiles $ \c -> H.link ! A.type_ "text/css" ! A.href (toValue $ "/static/css/" ++ c) ! A.rel "stylesheet" --Ubuntu font H.link ! A.type_ "text/css" ! A.href ("http://fonts.googleapis.com/css?family=Ubuntu") ! A.rel "stylesheet" baseHtml :: Maybe String -> Html -> Html baseHtml title content = docTypeHtml $ do htmlHeader title ["base.css"] [] content
mcmaniac/bindrop
src/HTML/Base.hs
apache-2.0
1,026
0
15
251
297
154
143
28
1
{-| Generic data loader. This module holds the common code for parsing the input data after it has been loaded from external sources. -} {- Copyright (C) 2009, 2010, 2011, 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Loader ( mergeData , clearDynU , checkData , assignIndices , setMaster , lookupNode , lookupInstance , lookupGroup , eitherLive , commonSuffix , extractExTags , updateExclTags , RqType(..) , Request(..) , ClusterData(..) , emptyCluster ) where import Control.Monad import Data.List import qualified Data.Map as M import Data.Maybe import Text.Printf (printf) import System.Time (ClockTime(..)) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Cluster as Cluster import Ganeti.BasicTypes import qualified Ganeti.HTools.Tags as Tags import Ganeti.HTools.Types import Ganeti.Utils import Ganeti.Types (EvacMode) -- * Types {-| The iallocator request type. This type denotes what request we got from Ganeti and also holds request-specific fields. -} data RqType = Allocate Instance.Instance Cluster.AllocDetails -- ^ A new instance -- allocation | Relocate Idx Int [Ndx] -- ^ Choose a new -- secondary node | NodeEvacuate [Idx] EvacMode -- ^ node-evacuate mode | ChangeGroup [Gdx] [Idx] -- ^ Multi-relocate mode | MultiAllocate [(Instance.Instance, Cluster.AllocDetails)] -- ^ Multi-allocate mode deriving (Show) -- | A complete request, as received from Ganeti. data Request = Request RqType ClusterData deriving (Show) -- | The cluster state. data ClusterData = ClusterData { cdGroups :: Group.List -- ^ The node group list , cdNodes :: Node.List -- ^ The node list , cdInstances :: Instance.List -- ^ The instance list , cdTags :: [String] -- ^ The cluster tags , cdIPolicy :: IPolicy -- ^ The cluster instance policy } deriving (Show, Eq) -- | An empty cluster. emptyCluster :: ClusterData emptyCluster = ClusterData Container.empty Container.empty Container.empty [] defIPolicy -- * Functions -- | Lookups a node into an assoc list. lookupNode :: (Monad m) => NameAssoc -> String -> String -> m Ndx lookupNode ktn inst node = maybe (fail $ "Unknown node '" ++ node ++ "' for instance " ++ inst) return $ M.lookup node ktn -- | Lookups an instance into an assoc list. lookupInstance :: (Monad m) => NameAssoc -> String -> m Idx lookupInstance kti inst = maybe (fail $ "Unknown instance '" ++ inst ++ "'") return $ M.lookup inst kti -- | Lookups a group into an assoc list. lookupGroup :: (Monad m) => NameAssoc -> String -> String -> m Gdx lookupGroup ktg nname gname = maybe (fail $ "Unknown group '" ++ gname ++ "' for node " ++ nname) return $ M.lookup gname ktg -- | Given a list of elements (and their names), assign indices to them. assignIndices :: (Element a) => [(String, a)] -> (NameAssoc, Container.Container a) assignIndices name_element = let (name_idx, idx_element) = unzip . map (\ (idx, (k, v)) -> ((k, idx), (idx, setIdx v idx))) . zip [0..] $ name_element in (M.fromList name_idx, Container.fromList idx_element) -- | Given am indexed node list, and the name of the master, mark it as such. setMaster :: (Monad m) => NameAssoc -> Node.List -> String -> m Node.List setMaster node_names node_idx master = do kmaster <- maybe (fail $ "Master node " ++ master ++ " unknown") return $ M.lookup master node_names let mnode = Container.find kmaster node_idx return $ Container.add kmaster (Node.setMaster mnode True) node_idx -- | For each instance, add its index to its primary and secondary nodes. fixNodes :: Node.List -> Instance.Instance -> Node.List fixNodes accu inst = let pdx = Instance.pNode inst sdx = Instance.sNode inst pold = Container.find pdx accu pnew = Node.setPri pold inst ac2 = Container.add pdx pnew accu in if sdx /= Node.noSecondary then let sold = Container.find sdx accu snew = Node.setSec sold inst in Container.add sdx snew ac2 else ac2 -- | Set the node's policy to its group one. Note that this requires -- the group to exist (should have been checked before), otherwise it -- will abort with a runtime error. setNodePolicy :: Group.List -> Node.Node -> Node.Node setNodePolicy gl node = let grp = Container.find (Node.group node) gl gpol = Group.iPolicy grp in Node.setPolicy gpol node -- | Update instance with exclusion tags list. updateExclTags :: [String] -> Instance.Instance -> Instance.Instance updateExclTags tl inst = let allTags = Instance.allTags inst exclTags = filter (\tag -> any (`isPrefixOf` tag) tl) allTags in inst { Instance.exclTags = exclTags } -- | Update the movable attribute. updateMovable :: [String] -- ^ Selected instances (if not empty) -> [String] -- ^ Excluded instances -> Instance.Instance -- ^ Target Instance -> Instance.Instance -- ^ Target Instance with updated attribute updateMovable selinsts exinsts inst = if Instance.name inst `elem` exinsts || not (null selinsts || Instance.name inst `elem` selinsts) then Instance.setMovable inst False else inst -- | Disables moves for instances with a split group. disableSplitMoves :: Node.List -> Instance.Instance -> Instance.Instance disableSplitMoves nl inst = if not . isOk . Cluster.instanceGroup nl $ inst then Instance.setMovable inst False else inst -- | Set the auto-repair policy for an instance. setArPolicy :: [String] -- ^ Cluster tags -> Group.List -- ^ List of node groups -> Node.List -- ^ List of nodes -> Instance.List -- ^ List of instances -> ClockTime -- ^ Current timestamp, to evaluate ArSuspended -> Instance.List -- ^ Updated list of instances setArPolicy ctags gl nl il time = let getArPolicy' = flip getArPolicy time cpol = fromMaybe ArNotEnabled $ getArPolicy' ctags gpols = Container.map (fromMaybe cpol . getArPolicy' . Group.allTags) gl ipolfn = getArPolicy' . Instance.allTags nlookup = flip Container.find nl . Instance.pNode glookup = flip Container.find gpols . Node.group . nlookup updateInstance inst = inst { Instance.arPolicy = fromMaybe (glookup inst) $ ipolfn inst } in Container.map updateInstance il -- | Get the auto-repair policy from a list of tags. -- -- This examines the ganeti:watcher:autorepair and -- ganeti:watcher:autorepair:suspend tags to determine the policy. If none of -- these tags are present, Nothing (and not ArNotEnabled) is returned. getArPolicy :: [String] -> ClockTime -> Maybe AutoRepairPolicy getArPolicy tags time = let enabled = mapMaybe (autoRepairTypeFromRaw <=< chompPrefix Tags.autoRepairTagEnabled) tags suspended = mapMaybe (chompPrefix Tags.autoRepairTagSuspended) tags futureTs = filter (> time) . map (flip TOD 0) $ mapMaybe (tryRead "auto-repair suspend time") suspended in case () of -- Note how we must return ArSuspended even if "enabled" is empty, so that -- node groups or instances can suspend repairs that were enabled at an -- upper scope (cluster or node group). _ | "" `elem` suspended -> Just $ ArSuspended Forever | not $ null futureTs -> Just . ArSuspended . Until . maximum $ futureTs | not $ null enabled -> Just $ ArEnabled (minimum enabled) | otherwise -> Nothing -- | Compute the longest common suffix of a list of strings that -- starts with a dot. longestDomain :: [String] -> String longestDomain [] = "" longestDomain (x:xs) = foldr (\ suffix accu -> if all (isSuffixOf suffix) xs then suffix else accu) "" $ filter (isPrefixOf ".") (tails x) -- | Extracts the exclusion tags from the cluster configuration. extractExTags :: [String] -> [String] extractExTags = filter (not . null) . mapMaybe (chompPrefix Tags.exTagsPrefix) -- | Extracts the common suffix from node\/instance names. commonSuffix :: Node.List -> Instance.List -> String commonSuffix nl il = let node_names = map Node.name $ Container.elems nl inst_names = map Instance.name $ Container.elems il in longestDomain (node_names ++ inst_names) -- | Set the migration-related tags on a node given the cluster tags; -- this assumes that the node tags are already set on that node. addMigrationTags :: [String] -- ^ cluster tags -> Node.Node -> Node.Node addMigrationTags ctags node = let ntags = Node.nTags node migTags = Tags.getMigRestrictions ctags ntags rmigTags = Tags.getRecvMigRestrictions ctags ntags in Node.setRecvMigrationTags (Node.setMigrationTags node migTags) rmigTags -- | Initializer function that loads the data from a node and instance -- list and massages it into the correct format. mergeData :: [(String, DynUtil)] -- ^ Instance utilisation data -> [String] -- ^ Exclusion tags -> [String] -- ^ Selected instances (if not empty) -> [String] -- ^ Excluded instances -> ClockTime -- ^ The current timestamp -> ClusterData -- ^ Data from backends -> Result ClusterData -- ^ Fixed cluster data mergeData um extags selinsts exinsts time cdata@(ClusterData gl nl il ctags _) = let il2 = setArPolicy ctags gl nl il time il3 = foldl' (\im (name, n_util) -> case Container.findByName im name of Nothing -> im -- skipping unknown instance Just inst -> let new_i = inst { Instance.util = n_util } in Container.add (Instance.idx inst) new_i im ) il2 um allextags = extags ++ extractExTags ctags inst_names = map Instance.name $ Container.elems il3 selinst_lkp = map (lookupName inst_names) selinsts exinst_lkp = map (lookupName inst_names) exinsts lkp_unknown = filter (not . goodLookupResult) (selinst_lkp ++ exinst_lkp) selinst_names = map lrContent selinst_lkp exinst_names = map lrContent exinst_lkp node_names = map Node.name (Container.elems nl) common_suffix = longestDomain (node_names ++ inst_names) il4 = Container.map (computeAlias common_suffix . updateExclTags allextags . updateMovable selinst_names exinst_names) il3 nl2 = foldl' fixNodes nl (Container.elems il4) nl3 = Container.map (setNodePolicy gl . computeAlias common_suffix . (`Node.buildPeers` il4)) nl2 il5 = Container.map (disableSplitMoves nl3) il4 nl4 = Container.map (addMigrationTags ctags) nl3 in if' (null lkp_unknown) (Ok cdata { cdNodes = nl4, cdInstances = il5 }) (Bad $ "Unknown instance(s): " ++ show(map lrContent lkp_unknown)) -- | In a cluster description, clear dynamic utilisation information. clearDynU :: ClusterData -> Result ClusterData clearDynU cdata@(ClusterData _ _ il _ _) = let il2 = Container.map (\ inst -> inst {Instance.util = zeroUtil }) il in Ok cdata { cdInstances = il2 } -- | Checks the cluster data for consistency. checkData :: Node.List -> Instance.List -> ([String], Node.List) checkData nl il = Container.mapAccum (\ msgs node -> let nname = Node.name node nilst = map (`Container.find` il) (Node.pList node) dilst = filter Instance.instanceDown nilst adj_mem = sum . map Instance.mem $ dilst delta_mem = truncate (Node.tMem node) - Node.nMem node - Node.fMem node - nodeImem node il + adj_mem delta_dsk = truncate (Node.tDsk node) - Node.fDsk node - nodeIdsk node il newn = Node.setFmem (Node.setXmem node delta_mem) (Node.fMem node - adj_mem) umsg1 = if delta_mem > 512 || delta_dsk > 1024 then printf "node %s is missing %d MB ram \ \and %d GB disk" nname delta_mem (delta_dsk `div` 1024):msgs else msgs in (umsg1, newn) ) [] nl -- | Compute the amount of memory used by primary instances on a node. nodeImem :: Node.Node -> Instance.List -> Int nodeImem node il = let rfind = flip Container.find il il' = map rfind $ Node.pList node oil' = filter Instance.notOffline il' in sum . map Instance.mem $ oil' -- | Compute the amount of disk used by instances on a node (either primary -- or secondary). nodeIdsk :: Node.Node -> Instance.List -> Int nodeIdsk node il = let rfind = flip Container.find il in sum . map (Instance.dsk . rfind) $ Node.pList node ++ Node.sList node -- | Get live information or a default value eitherLive :: (Monad m) => Bool -> a -> m a -> m a eitherLive True _ live_data = live_data eitherLive False def_data _ = return def_data
ganeti-github-testing/ganeti-test-1
src/Ganeti/HTools/Loader.hs
bsd-2-clause
15,102
0
20
4,128
3,252
1,731
1,521
245
2
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, OverloadedStrings #-} module QC where import Data.Aeson as A import qualified Data.Vector as V import Control.Applicative import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import Data.Text (Text) import Data.Hashable (Hashable) import Control.Monad import Data.Text (Text) import Data.Scientific import Test.QuickCheck import Test.QuickCheck.Function instance Arbitrary Text where arbitrary = do i <- choose (1,10) Text.pack <$> vectorOf i (elements (['A'..'Z'] ++ ['a'..'z'])) newtype Label = Label Text deriving Show -- Label lbl is never "id" instance Arbitrary Label where arbitrary = do lab <- arbitrary if lab == "id" then arbitrary else return $ Label lab instance Arbitrary Object where arbitrary = do i <- choose (1,10) b <- arbitrary arbitraryHashMap b i -- The first argument is if we have an "id" or not, in this HashMap. arbitraryHashMap :: Bool -> Int -> Gen Object arbitraryHashMap b n = do i <- choose (1,10) v <- arbitraryValue (n-1) ixVals <- vectorOf i (liftM2 (,) arbitrary (arbitraryValue (n-1))) return $ (HashMap.fromList . map (\(Label lbl,e) -> (lbl,e))) ((if b then [(Label "id",v)] else []) ++ ixVals) instance Arbitrary A.Array where arbitrary = do i <- choose (1,10) arbitraryArray i arbitraryArray n = do i <- choose (0,10) V.fromList <$> vectorOf i (arbitraryValue (n-1) :: Gen A.Value) instance Arbitrary A.Value where arbitrary = do i <- choose (0,10) arbitraryValue i arbitraryValue :: Int -> Gen Value arbitraryValue n = frequency $ [ (10,A.String <$> (arbitrary :: Gen Text)) , (10,(Number . fromFloatDigits) <$> (arbitrary :: Gen Double)) , (2,A.Bool <$> (arbitrary :: Gen Bool)) , (1,return A.Null) , ( if n >= 1 then 10 else 0 , A.Object <$> (arbitraryHashMap False (n-1) :: Gen Object) ) , ( if n >= 1 then 5 else 0 , A.Array <$> (arbitraryArray (n-1) :: Gen Array) ) ]
andygill/scotty-crud
tests/QC.hs
bsd-2-clause
2,291
0
15
660
785
428
357
58
3
{-# LANGUAGE GADTs #-} module Language.Drasil.Space (Space(..), DomainDesc(..), RealInterval(..), RTopology(..), Inclusive(..), getActorName) where import Language.Drasil.Symbol (Symbol) -- FIXME: These need to be spaces and not just types. -- | Spaces data Space = Integer | Rational | Real | Natural | Boolean | Char | String | Radians | Vect Space | Array Space | Actor String | DiscreteI [Int] --ex. let A = {1, 2, 4, 7} | DiscreteD [Double] | DiscreteS [String] --ex. let Meal = {"breakfast", "lunch", "dinner"} | Void deriving (Eq, Show) -- The 'spaces' below are all good. -- | Topology of a subset of reals. data RTopology = Continuous | Discrete data DomainDesc a b where BoundedDD :: Symbol -> RTopology -> a -> b -> DomainDesc a b AllDD :: Symbol -> RTopology -> DomainDesc a b data Inclusive = Inc | Exc -- | RealInterval. A |RealInterval| is a subset of |Real| (as a |Space|). -- These come in different flavours. -- For now, embed |Expr| for the bounds, but that will change as well. data RealInterval a b where Bounded :: (Inclusive, a) -> (Inclusive, b) -> RealInterval a b -- (x .. y) UpTo :: (Inclusive, a) -> RealInterval a b -- (-infinity .. x) UpFrom :: (Inclusive, b) -> RealInterval a b -- (x .. infinity) getActorName :: Space -> String getActorName (Actor n) = n getActorName _ = error "getActorName called on non-actor space"
JacquesCarette/literate-scientific-software
code/drasil-lang/Language/Drasil/Space.hs
bsd-2-clause
1,409
0
10
293
332
203
129
34
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverlappingInstances, FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns, RecordWildCards, PatternGuards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} module Narradar.Interface.Cli (narradarMain, prologMain , Options(..), defOpts ) where import Control.Concurrent import Control.Exception (evaluate) import qualified Control.Exception as CE import Control.Monad.Free import Data.Foldable (Foldable) import Data.Maybe import Data.Monoid import Data.Traversable (Traversable) import System.Cmd import System.Directory import System.Environment import System.Exit import System.FilePath import System.IO import System.Posix.Process import System.Posix.Signals import System.Console.GetOpt import Text.ParserCombinators.Parsec (parse, runParser) import Text.Printf import Text.XHtml (toHtml) import qualified Language.Prolog.Syntax as Prolog import Prelude as P import Narradar import Narradar.Framework import Narradar.Framework.GraphViz (dotProof', DotProof(..)) import Narradar.Utils import MuTerm.Framework.Output #ifdef TESTING import Properties (properties) import Test.Framework.Runners.Console import Test.Framework.Options import Test.Framework.Runners.Options #endif narradarMain :: forall mp. (IsMZero mp, Traversable mp ,Dispatch (Problem Rewriting (NTRS Id)) ,Dispatch (Problem IRewriting (NTRS Id)) ,Dispatch (Problem (InitialGoal (TermF Id) Rewriting) (NTRS Id)) ,Dispatch (Problem (InitialGoal (TermF Id) IRewriting) (NTRS Id)) ,Dispatch (Problem (InitialGoal (TermF Id) Narrowing) (NTRS Id)) ,Dispatch (Problem (InitialGoal (TermF Id) INarrowing) (NTRS Id)) ,Dispatch (Problem (Relative (NTRS Id) (InitialGoal (TermF Id) Rewriting)) (NTRS Id)) ,Dispatch (Problem (Relative (NTRS Id) (InitialGoal (TermF Id) IRewriting)) (NTRS Id)) ,Dispatch (Problem (Relative (NTRS Id) Rewriting) (NTRS Id)) ,Dispatch (Problem (Relative (NTRS Id) IRewriting) (NTRS Id)) ,Dispatch (Problem Narrowing (NTRS Id)) ,Dispatch (Problem CNarrowing (NTRS Id)) ,Dispatch PrologProblem ) => (forall a. mp a -> Maybe a) -> IO () narradarMain run = catchTimeout $ do (flags@Options{..}, _, _errors) <- getOptions let echoV str = when (verbose>1) $ hPutStrLn stderr str tmp <- getTemporaryDirectory let printDiagram :: Proof PrettyDotF mp a -> IO () printDiagram proof | isNothing pdfFile = return () | Just the_pdf <- pdfFile = withTempFile tmp "narradar.dot" $ \fp h -> do let dotSrc = dotProof' DotProof{showFailedPaths = verbose > 1} proof hPutStrLn h dotSrc hClose h #ifdef DEBUG when (verbose > 1) $ writeFile (the_pdf ++ ".dot") dotSrc #endif let dotCmd = printf "dot -Tpdf %s -o%s" fp the_pdf echoV dotCmd dotOk <- system dotCmd echo ("PDF proof written to " ++ the_pdf) return (dotOk == ExitSuccess, ()) a_problem <- eitherM $ narradarParse problemFile input let proof = dispatchAProblem a_problem sol <- maybe (fmap Just) withTimeout timeout $ evaluate $ run (runProof proof) let diagrams = isJust pdfFile case join sol of Just sol -> do putStrLn "YES" when diagrams $ printDiagram sol when (verbose>0) $ print $ pPrint sol Nothing -> do putStrLn "MAYBE" let proof' = unsafeSliceProof proof when (verbose > 1) $ print $ pprProofFailures proof' when (verbose > 1 && diagrams) (printDiagram proof') `const` proof where catchTimeout = (`CE.catch` \TimeoutException -> putStrLn "MAYBE" >> exitSuccess) withTimeout t m = do res <- newEmptyMVar done <- newMVar () worker_id <- forkIO $ (`CE.catch` \TimeoutException -> return ()) $ do val <- m takeMVar done putMVar res (Just val) clocker_id <- forkIO $ do threadDelay (t * 1000000) takeMVar done throwTo worker_id TimeoutException putMVar res Nothing takeMVar res prologMain :: forall mp. (IsMZero mp, Traversable mp ,Dispatch PrologProblem ) => (forall a. mp a -> Maybe a) -> IO () prologMain run = catchTimeout $ do (flags@Options{..}, _, _errors) <- getOptions let echoV str = when (verbose>1) $ hPutStrLn stderr str tmp <- getTemporaryDirectory let printDiagram :: Proof PrettyDotF mp a -> IO () printDiagram proof | isNothing pdfFile = return () | Just the_pdf <- pdfFile = withTempFile tmp "narradar.dot" $ \fp h -> do let dotSrc = dotProof' DotProof{showFailedPaths = verbose > 1} proof hPutStrLn h dotSrc hClose h #ifdef DEBUG when (verbose > 1) $ writeFile (the_pdf ++ ".dot") dotSrc #endif let dotcmd = printf "dot -Tpdf %s -o%s" fp the_pdf echoV dotcmd dotok <- system dotcmd echo ("PDF proof written to " ++ the_pdf) return (dotok == ExitSuccess, ()) prologProblem <- eitherM $ parse prologParser problemFile input let proof = dispatch prologProblem sol = run (runProof proof) diagrams = isJust pdfFile case sol of Just sol -> do putStrLn "YES" when diagrams $ printDiagram sol when (verbose>0) $ print $ pPrint sol Nothing -> do putStrLn "MAYBE" when (verbose > 1) $ print $ pprProofFailures proof when (diagrams && verbose > 0) $ printDiagram (sliceProof proof) where catchTimeout = (`CE.catch` \TimeoutException -> putStrLn "MAYBE") -- ------------------------------ -- Command Line Options handling -- ------------------------------ usage = "Narradar - Automated Narrowing Termination Proofs\n" ++ "USAGE: narradar OPTIONS [FILENAME]" getOptions = do args <- getArgs let (actions, nonOptions, errors) = getOpt Permute opts args case errors of [] -> do let problemFile = fromMaybe "INPUT" (listToMaybe nonOptions) input <- maybe getContents readFile (listToMaybe nonOptions) opts <- foldl (P.>>=) (P.return defOpts{problemFile,input}) actions P.return (opts, nonOptions, errors) _ -> putStrLn ("Error: " ++ unwords errors) >> putStrLn (usageInfo usage opts) >> exitWith (ExitFailure (-1)) data Options = Options { problemFile :: FilePath , pdfFile :: Maybe FilePath , input :: String , verbose :: Int , timeout :: Maybe Int } defOpts = Options{ problemFile = "", pdfFile = Nothing, input = "", verbose = 0, timeout = Nothing} --opts :: [OptDescr (Flags f id -> Flags f id)] opts = [ Option "" ["pdf"] (OptArg setPdfPath "PATH") "Produce a pdf proof file (implied by -v2)" #ifndef GHCI , Option "t" ["timeout"] (ReqArg setTimeout "SECONDS") "Timeout in seconds (default:none)" #endif , Option "v" ["verbose"] (OptArg setVerbosity "LEVEL") "Verbosity level (0-2)" , Option "h?" ["help"] (NoArg (\ _ -> putStrLn(usageInfo usage opts) P.>> exitSuccess)) "Displays this help screen" #ifdef TESTING , Option "" ["verify"] (OptArg runTests "THREADS") "Run quickcheck properties and unit tests (# THREADS)" #endif ] #ifdef TESTING runTests mb_threads _ = do defaultMainWithOpts properties runnerOpts exitSuccess where runnerOpts = RunnerOptions (fmap read mb_threads) (Just to) Nothing to = TestOptions {topt_seed = Nothing ,topt_maximum_generated_tests = Just 5000 ,topt_maximum_unsuitable_generated_tests = Just 1000 ,topt_timeout = Just(Just (ms 3000)) } ms = (*1000000) #endif setTimeout arg opts = do let t = read arg {- scheduleAlarm t t_id <- myThreadId installHandler sigALRM (Catch $ do throwTo t_id TimeoutException debug "timeout" ) Nothing -} P.return opts{timeout= Just t} setVerbosity Nothing opts@Options{..} = P.return opts{verbose=1} setVerbosity (Just "2") opts@Options{..} = do {P.return opts{verbose=2, pdfFile = pdfFile `mplus` Just (problemFile <.> "pdf")}} `catch` (\e -> error "cannot parse the verbosity level") setVerbosity (Just i) opts@Options{..} = do {i <- readIO i; P.return opts{verbose=i}} `catch` (\e -> error "cannot parse the verbosity level") setPdfPath Nothing opts = P.return opts{ pdfFile = Just (problemFile opts <.> "pdf") } setPdfPath (Just f) opts = P.return opts{ pdfFile = Just f }
pepeiborra/narradar
src/Narradar/Interface/Cli.hs
bsd-3-clause
9,388
0
22
2,869
2,752
1,402
1,350
164
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Lib where import qualified Data.Text as T import qualified Data.Text.Format as TF import qualified Data.Text.Lazy as TL import qualified Database.RethinkDB as R disruptionUrl :: T.Text disruptionUrl = "https://citymapper.com/api/1/routestatus?weekend=0" summarizeWriteResponse :: [R.WriteResponse] -> Maybe TL.Text summarizeWriteResponse = let tplus (a, b) (a', b') = (a + a', b + b') extract R.WriteResponse {..} = (writeResponseInserted, writeResponseReplaced) format :: (Int, Int) -> Maybe TL.Text format (0, 0) = Nothing format a = Just $ TF.format "Inserted: {}, updated: {}" a in format . foldl (\b a -> b `tplus` extract a) (0, 0)
passy/disruption-tracker
src/Lib.hs
bsd-3-clause
753
0
12
140
227
133
94
18
2
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Yesod.Admin.Crud.Handlers where import Control.Monad (unless) import Data.Monoid (mempty) import Data.Text (Text) import qualified Data.Text as Text import Language.Haskell.TH.Syntax (Pred(ClassP), Type(VarT), mkName) import Database.Persist.Base (EntityDef(..), PersistField, PersistValue(PersistNull), SomePersistField, columnName, toPersistValue) import Text.Cassius (cassiusFile) import Text.Hamlet (shamletFile) import Yesod ( GHandler, GWidget, Html, RedirectType(RedirectTemporary), RenderRoute(..), RepHtml, Yesod, YesodDispatch(..), addCassius, defaultLayout, getRouteToMaster, mkYesodSub, permissionDenied, parseRoutes, redirect, toSinglePiece, whamletFile) import Yesod.Admin.Crud.Class (YesodAdmin(..)) import Yesod.Admin.Crud.TableFuncs (TableFuncs(..)) import Yesod.Admin.Crud.Type (Admin) import Yesod.Admin.User (isAdminUser) mkYesodSub "Admin" [ClassP ''YesodAdmin [VarT (mkName "master")]] [parseRoutes| / ShowR GET /add/#String AddR POST /edit/#String/#Text EditR GET POST /delete/#String/#Text DeleteR GET POST |] checkAdmin :: YesodAdmin master => GHandler Admin master () checkAdmin = do isAdmin <- isAdminUser unless isAdmin $ permissionDenied mempty getShowH :: YesodAdmin master => GHandler Admin master [(String, [String], [(PersistValue, [SomePersistField])])] getShowH = do checkAdmin getTableNames >>= mapM tableData where tableData table = do tableFuncs <- getTableFuncs table rows <- listRows tableFuncs let cols = map columnName . entityColumns $ tableDef tableFuncs return (table, cols, rows) tableHeader :: String -> [String] -> Int -> Html tableHeader title colNames numActions = $(shamletFile "hamlet/table-header.hamlet") where hasActions = numActions > 0 numCols = 1 + length colNames + numActions tableRowValues :: [SomePersistField] -> Html tableRowValues vals = $(shamletFile "hamlet/table-row-vals.hamlet") isEmptyCell :: PersistField a => a -> Bool isEmptyCell = (PersistNull ==) . toPersistValue stylesheet :: GWidget Admin master () stylesheet = addCassius $(cassiusFile "cassius/yesod-admin-crud.css") getShowR :: YesodAdmin master => GHandler Admin master RepHtml getShowR = do checkAdmin tables <- getShowH adminRoute <- getRouteToMaster defaultLayout $ do stylesheet mapM_ (showTable adminRoute) tables where showTable adminRoute (entity, colNames, items) = $(whamletFile "hamlet/listing.hamlet") where title = entity ++ " Table" getEditR :: YesodAdmin master => String -> Text -> GHandler Admin master RepHtml getEditR table key = do checkAdmin tableFuncs <- getTableFuncs table let cols = map columnName . entityColumns $ tableDef tableFuncs item <- getRow tableFuncs key adminRoute <- getRouteToMaster defaultLayout $ do stylesheet $(whamletFile "hamlet/edit-row.hamlet") where cellText (_, cell) = if isEmptyCell cell then mempty else toSinglePiece (toPersistValue cell) getDeleteR :: YesodAdmin master => String -> Text -> GHandler Admin master RepHtml getDeleteR table key = do checkAdmin tableFuncs <- getTableFuncs table let cols = map columnName . entityColumns $ tableDef tableFuncs item <- getRow tableFuncs key adminRoute <- getRouteToMaster defaultLayout $ do stylesheet $(whamletFile "hamlet/delete-row.hamlet") directHome :: YesodAdmin master => GHandler Admin master () directHome = do adminRoute <- getRouteToMaster redirect RedirectTemporary (adminRoute ShowR) postAddR :: YesodAdmin master => String -> GHandler Admin master () postAddR table = do checkAdmin tableFuncs <- getTableFuncs table addRow tableFuncs directHome postEditR :: YesodAdmin master => String -> Text -> GHandler Admin master () postEditR table key = do checkAdmin tableFuncs <- getTableFuncs table editRow tableFuncs key directHome postDeleteR :: YesodAdmin master => String -> Text -> GHandler Admin master () postDeleteR table key = do checkAdmin tableFuncs <- getTableFuncs table deleteRow tableFuncs key directHome
yairchu/yesod-admin-crud
Yesod/Admin/Crud/Handlers.hs
bsd-3-clause
4,363
0
14
840
1,208
621
587
97
2
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} module Trav where import Data.Monoid import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes newtype Identity a = Identity a deriving (Eq, Ord, Show, Functor) instance Arbitrary a => Arbitrary (Identity a) where arbitrary = Identity <$> arbitrary instance Eq a => EqProp (Identity a) where (=-=) = eq instance Foldable Identity where foldMap f (Identity a ) = f a instance Traversable Identity where traverse aToFb (Identity a) = Identity <$> (aToFb a) newtype Constant a b = Constant { getConstant :: a } deriving (Eq, Ord, Show, Functor) instance Foldable (Constant a) where foldMap _ c = mempty instance Traversable (Constant a) where traverse a1ToFb (Constant a) = pure (Constant a) instance Arbitrary a => Arbitrary (Constant a b) where arbitrary = Constant <$> arbitrary instance (Eq a, Eq b)=> EqProp (Constant a b) where (=-=) = eq data Optional a = Nada | Yep a deriving (Eq, Ord, Show, Functor) instance Foldable Optional where foldMap f op = case op of Nada -> mempty Yep a -> f a instance Traversable Optional where traverse aToFb op = case op of Nada -> pure Nada Yep a -> Yep <$> aToFb a instance Arbitrary a => Arbitrary (Optional a) where arbitrary = oneof [pure Nada, Yep <$> arbitrary] instance Eq a => EqProp (Optional a) where (=-=) = eq data List a = Nil | Cons a (List a) deriving (Eq, Ord, Show, Functor) instance Foldable List where foldMap _ Nil = mempty foldMap f (Cons x xs) = f x <> (foldMap f xs) instance Traversable List where traverse _ Nil = pure Nil traverse f (Cons x xs) = Cons <$> f x <*> (traverse f xs) instance Arbitrary a => Arbitrary (List a) where arbitrary = oneof [ pure Nil, Cons <$> arbitrary <*> arbitrary ] instance Eq a => EqProp (List a) where (=-=) = eq data Three a b c = Three a b c deriving (Eq, Show, Functor) instance Foldable (Three a b) where foldMap f (Three _ _ c) = f c instance Traversable (Three a b) where traverse f (Three a b c) = Three a b <$> f c instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where arbitrary = Three <$> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where (=-=) = eq data Three' a b = Three' a b b deriving (Eq, Show, Functor) instance Foldable (Three' a) where foldMap f (Three' _ b1 b2) = f b1 <> f b2 instance Traversable (Three' a) where traverse f (Three' a b1 b2) = Three' a <$> f b1 <*> f b2 instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where arbitrary = Three' <$> arbitrary <*> arbitrary <*> arbitrary instance (Eq a, Eq b) => EqProp (Three' a b) where (=-=) = eq data S n a = S (n a) a deriving (Eq, Show) instance Functor n => Functor (S n) where -- to transform the a inside the n a to a be, we need Functor n fmap f (S na a) = S (f <$> na) (f a) instance Foldable n => Foldable (S n) where foldMap f (S na a) = foldMap f na <> f a instance Traversable n => Traversable (S n) where -- now, to flip the containers around, we need Traversable n traverse f (S na a) = S <$> traverse f na <*> f a instance (Arbitrary a, Arbitrary (n a)) => Arbitrary (S n a) where arbitrary = S <$> arbitrary <*> arbitrary instance (Eq a, Eq (n a)) => EqProp (S n a) where (=-=) = eq data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show, Functor) instance Foldable Tree where foldMap _ Empty = mempty foldMap f (Leaf a) = f a foldMap f (Node l a r) = (foldMap f l) <> (f a) <> (foldMap f r) instance Traversable Tree where traverse _ Empty = pure Empty traverse f (Leaf a) = Leaf <$> f a traverse f (Node l a r) = Node <$> traverse f l <*> f a <*> traverse f r instance Arbitrary a => Arbitrary (Tree a) where arbitrary = oneof [ pure Empty , Leaf <$> arbitrary , Node <$> arbitrary <*> arbitrary <*> arbitrary ] instance Eq a => EqProp (Tree a) where (=-=) = eq main :: IO () main = do quickBatch (traversable (undefined :: Identity (Int, Int, String))) quickBatch (traversable (undefined :: Constant String (Int, Int, [Bool]))) quickBatch (traversable (undefined :: Optional (Int, Int, [String]))) quickBatch (traversable (undefined :: List (Int, Int, Maybe String))) quickBatch (traversable (undefined :: Three Bool String (Int, Int, Maybe String))) quickBatch (traversable (undefined :: Three' Float (Int, Int, Maybe String))) quickBatch (traversable (undefined :: S Maybe (Int, Int, Maybe String))) quickBatch (traversable (undefined :: Tree (Int, Int, [String])))
nicklawls/haskellbook
src/Trav.hs
bsd-3-clause
4,751
0
13
1,128
2,070
1,068
1,002
125
1
-- | This module contains orphan 'XMLGenT' instances for 'ServerMonad', 'FilterMonad', 'WebMonad', 'HasRqData', and 'Happstack'. It does not export any functions. {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeFamilies, UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Happstack.Server.XMLGenT where import Control.Applicative (Alternative(..)) import Control.Monad (MonadPlus(..)) import Control.Monad.Trans (MonadIO(..)) import Happstack.Server.SimpleHTTP (ServerMonad(..), FilterMonad(..), WebMonad(..), HasRqData(..), Happstack(..), Response) import HSP.XMLGenerator (XMLGenT(..)) import HSP.Monad (HSPT(..)) instance (ServerMonad m) => ServerMonad (XMLGenT m) where askRq = XMLGenT askRq localRq f (XMLGenT m) = XMLGenT (localRq f m) instance (FilterMonad a m) => FilterMonad a (XMLGenT m) where setFilter = XMLGenT . setFilter composeFilter f = XMLGenT (composeFilter f) getFilter (XMLGenT m) = XMLGenT (getFilter m) instance (WebMonad a m) => WebMonad a (XMLGenT m) where finishWith r = XMLGenT $ finishWith r instance (HasRqData m) => (HasRqData (XMLGenT m)) where askRqEnv = XMLGenT askRqEnv localRqEnv f (XMLGenT m) = XMLGenT (localRqEnv f m) rqDataError = XMLGenT . rqDataError instance (Alternative m, MonadPlus m, Functor m, MonadIO m, ServerMonad m, FilterMonad a m, WebMonad a m, HasRqData m, a ~ Response) => Happstack (XMLGenT m) instance (ServerMonad m) => ServerMonad (HSPT xml m) where askRq = HSPT askRq localRq f (HSPT m) = HSPT (localRq f m) instance (FilterMonad a m) => FilterMonad a (HSPT xml m) where setFilter = HSPT . setFilter composeFilter f = HSPT (composeFilter f) getFilter (HSPT m) = HSPT (getFilter m) instance (WebMonad a m) => WebMonad a (HSPT xml m) where finishWith r = HSPT $ finishWith r instance (HasRqData m) => (HasRqData (HSPT xml m)) where askRqEnv = HSPT askRqEnv localRqEnv f (HSPT m) = HSPT (localRqEnv f m) rqDataError = HSPT . rqDataError instance (Alternative m, MonadPlus m, Functor m, MonadIO m, ServerMonad m, FilterMonad a m, WebMonad a m, HasRqData m, a ~ Response) => Happstack (HSPT xml m)
Happstack/happstack-hsp
src/Happstack/Server/XMLGenT.hs
bsd-3-clause
2,279
6
10
495
757
405
352
37
0
{-# language CPP #-} -- No documentation found for Chapter "PipelineStageFlags2" module Vulkan.Core13.Enums.PipelineStageFlags2 ( pattern PIPELINE_STAGE_2_NONE_KHR , pattern PIPELINE_STAGE_2_TOP_OF_PIPE_BIT_KHR , pattern PIPELINE_STAGE_2_DRAW_INDIRECT_BIT_KHR , pattern PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR , pattern PIPELINE_STAGE_2_VERTEX_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR , pattern PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR , pattern PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR , pattern PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR , pattern PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR , pattern PIPELINE_STAGE_2_TRANSFER_BIT , pattern PIPELINE_STAGE_2_TRANSFER_BIT_KHR , pattern PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT_KHR , pattern PIPELINE_STAGE_2_HOST_BIT_KHR , pattern PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR , pattern PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR , pattern PIPELINE_STAGE_2_COPY_BIT_KHR , pattern PIPELINE_STAGE_2_RESOLVE_BIT_KHR , pattern PIPELINE_STAGE_2_BLIT_BIT_KHR , pattern PIPELINE_STAGE_2_CLEAR_BIT_KHR , pattern PIPELINE_STAGE_2_INDEX_INPUT_BIT_KHR , pattern PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT_KHR , pattern PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR , PipelineStageFlags2 , PipelineStageFlagBits2( PIPELINE_STAGE_2_NONE , PIPELINE_STAGE_2_TOP_OF_PIPE_BIT , PIPELINE_STAGE_2_DRAW_INDIRECT_BIT , PIPELINE_STAGE_2_VERTEX_INPUT_BIT , PIPELINE_STAGE_2_VERTEX_SHADER_BIT , PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT , PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT , PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT , PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT , PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT , PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT , PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT , PIPELINE_STAGE_2_COMPUTE_SHADER_BIT , PIPELINE_STAGE_2_ALL_TRANSFER_BIT , PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT , PIPELINE_STAGE_2_HOST_BIT , PIPELINE_STAGE_2_ALL_GRAPHICS_BIT , PIPELINE_STAGE_2_ALL_COMMANDS_BIT , PIPELINE_STAGE_2_COPY_BIT , PIPELINE_STAGE_2_RESOLVE_BIT , PIPELINE_STAGE_2_BLIT_BIT , PIPELINE_STAGE_2_CLEAR_BIT , PIPELINE_STAGE_2_INDEX_INPUT_BIT , PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT , PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT , PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI , PIPELINE_STAGE_2_SUBPASS_SHADING_BIT_HUAWEI , PIPELINE_STAGE_2_MESH_SHADER_BIT_NV , PIPELINE_STAGE_2_TASK_SHADER_BIT_NV , PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT , PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR , PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR , PIPELINE_STAGE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR , PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV , PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT , PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT , .. ) ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showString) import Numeric (showHex) import Vulkan.Zero (Zero) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Foreign.Storable (Storable) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import Vulkan.Core10.FundamentalTypes (Flags64) -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_NONE_KHR" pattern PIPELINE_STAGE_2_NONE_KHR = PIPELINE_STAGE_2_NONE -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT_KHR" pattern PIPELINE_STAGE_2_TOP_OF_PIPE_BIT_KHR = PIPELINE_STAGE_2_TOP_OF_PIPE_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT_KHR" pattern PIPELINE_STAGE_2_DRAW_INDIRECT_BIT_KHR = PIPELINE_STAGE_2_DRAW_INDIRECT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR" pattern PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR = PIPELINE_STAGE_2_VERTEX_INPUT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_VERTEX_SHADER_BIT_KHR = PIPELINE_STAGE_2_VERTEX_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT_KHR = PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT_KHR = PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT_KHR = PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR = PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR" pattern PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR = PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR" pattern PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR = PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR" pattern PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR = PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR" pattern PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR = PIPELINE_STAGE_2_COMPUTE_SHADER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR" pattern PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR = PIPELINE_STAGE_2_ALL_TRANSFER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_TRANSFER_BIT" pattern PIPELINE_STAGE_2_TRANSFER_BIT = PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_TRANSFER_BIT_KHR" pattern PIPELINE_STAGE_2_TRANSFER_BIT_KHR = PIPELINE_STAGE_2_TRANSFER_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT_KHR" pattern PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT_KHR = PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_HOST_BIT_KHR" pattern PIPELINE_STAGE_2_HOST_BIT_KHR = PIPELINE_STAGE_2_HOST_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR" pattern PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR = PIPELINE_STAGE_2_ALL_GRAPHICS_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR" pattern PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR = PIPELINE_STAGE_2_ALL_COMMANDS_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_COPY_BIT_KHR" pattern PIPELINE_STAGE_2_COPY_BIT_KHR = PIPELINE_STAGE_2_COPY_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_RESOLVE_BIT_KHR" pattern PIPELINE_STAGE_2_RESOLVE_BIT_KHR = PIPELINE_STAGE_2_RESOLVE_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_BLIT_BIT_KHR" pattern PIPELINE_STAGE_2_BLIT_BIT_KHR = PIPELINE_STAGE_2_BLIT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_CLEAR_BIT_KHR" pattern PIPELINE_STAGE_2_CLEAR_BIT_KHR = PIPELINE_STAGE_2_CLEAR_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT_KHR" pattern PIPELINE_STAGE_2_INDEX_INPUT_BIT_KHR = PIPELINE_STAGE_2_INDEX_INPUT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT_KHR" pattern PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT_KHR = PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT -- No documentation found for TopLevel "VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR" pattern PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR = PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT type PipelineStageFlags2 = PipelineStageFlagBits2 -- | VkPipelineStageFlagBits2 - Pipeline stage flags for -- VkPipelineStageFlags2 -- -- = Description -- -- Note -- -- The @TOP@ and @BOTTOM@ pipeline stages are deprecated, and applications -- should prefer 'PIPELINE_STAGE_2_ALL_COMMANDS_BIT' and -- 'PIPELINE_STAGE_2_NONE'. -- -- Note -- -- The 'PipelineStageFlags2' bitmask goes beyond the 31 individual bit -- flags allowable within a C99 enum, which is how -- 'Vulkan.Core10.Enums.PipelineStageFlagBits.PipelineStageFlagBits' is -- defined. The first 31 values are common to both, and are -- interchangeable. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_synchronization2 VK_KHR_synchronization2>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_3 VK_VERSION_1_3> newtype PipelineStageFlagBits2 = PipelineStageFlagBits2 Flags64 deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- | 'PIPELINE_STAGE_2_NONE' specifies no stages of execution. pattern PIPELINE_STAGE_2_NONE = PipelineStageFlagBits2 0x0000000000000000 -- | 'PIPELINE_STAGE_2_TOP_OF_PIPE_BIT' is equivalent to -- 'PIPELINE_STAGE_2_ALL_COMMANDS_BIT' with -- 'Vulkan.Core13.Enums.AccessFlags2.AccessFlags2' set to @0@ when -- specified in the second synchronization scope, but equivalent to -- 'PIPELINE_STAGE_2_NONE' in the first scope. pattern PIPELINE_STAGE_2_TOP_OF_PIPE_BIT = PipelineStageFlagBits2 0x0000000000000001 -- | 'PIPELINE_STAGE_2_DRAW_INDIRECT_BIT' specifies the stage of the pipeline -- where indirect command parameters are consumed. This stage also includes -- reading commands written by -- 'Vulkan.Extensions.VK_NV_device_generated_commands.cmdPreprocessGeneratedCommandsNV'. pattern PIPELINE_STAGE_2_DRAW_INDIRECT_BIT = PipelineStageFlagBits2 0x0000000000000002 -- | 'PIPELINE_STAGE_2_VERTEX_INPUT_BIT' is equivalent to the logical OR of: -- -- - 'PIPELINE_STAGE_2_INDEX_INPUT_BIT' -- -- - 'PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT' pattern PIPELINE_STAGE_2_VERTEX_INPUT_BIT = PipelineStageFlagBits2 0x0000000000000004 -- | 'PIPELINE_STAGE_2_VERTEX_SHADER_BIT' specifies the vertex shader stage. pattern PIPELINE_STAGE_2_VERTEX_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000008 -- | 'PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT' specifies the -- tessellation control shader stage. pattern PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000010 -- | 'PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT' specifies the -- tessellation evaluation shader stage. pattern PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000020 -- | 'PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT' specifies the geometry shader -- stage. pattern PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000040 -- | 'PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT' specifies the fragment shader -- stage. pattern PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000080 -- | 'PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT' specifies the stage of the -- pipeline where early fragment tests (depth and stencil tests before -- fragment shading) are performed. This stage also includes -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load operations> -- for framebuffer attachments with a depth\/stencil format. pattern PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT = PipelineStageFlagBits2 0x0000000000000100 -- | 'PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT' specifies the stage of the -- pipeline where late fragment tests (depth and stencil tests after -- fragment shading) are performed. This stage also includes -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass store operations> -- for framebuffer attachments with a depth\/stencil format. pattern PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT = PipelineStageFlagBits2 0x0000000000000200 -- | 'PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT' specifies the stage of -- the pipeline after blending where the final color values are output from -- the pipeline. This stage also includes -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#renderpass-load-store-ops subpass load and store operations> -- and multisample resolve operations for framebuffer attachments with a -- color or depth\/stencil format. pattern PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT = PipelineStageFlagBits2 0x0000000000000400 -- | 'PIPELINE_STAGE_2_COMPUTE_SHADER_BIT' specifies the compute shader -- stage. pattern PIPELINE_STAGE_2_COMPUTE_SHADER_BIT = PipelineStageFlagBits2 0x0000000000000800 -- | 'PIPELINE_STAGE_2_ALL_TRANSFER_BIT' is equivalent to specifying all of: -- -- - 'PIPELINE_STAGE_2_COPY_BIT' -- -- - 'PIPELINE_STAGE_2_BLIT_BIT' -- -- - 'PIPELINE_STAGE_2_RESOLVE_BIT' -- -- - 'PIPELINE_STAGE_2_CLEAR_BIT' pattern PIPELINE_STAGE_2_ALL_TRANSFER_BIT = PipelineStageFlagBits2 0x0000000000001000 -- | 'PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT' is equivalent to -- 'PIPELINE_STAGE_2_ALL_COMMANDS_BIT' with -- 'Vulkan.Core13.Enums.AccessFlags2.AccessFlags2' set to @0@ when -- specified in the first synchronization scope, but equivalent to -- 'PIPELINE_STAGE_2_NONE' in the second scope. pattern PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT = PipelineStageFlagBits2 0x0000000000002000 -- | 'PIPELINE_STAGE_2_HOST_BIT' specifies a pseudo-stage indicating -- execution on the host of reads\/writes of device memory. This stage is -- not invoked by any commands recorded in a command buffer. pattern PIPELINE_STAGE_2_HOST_BIT = PipelineStageFlagBits2 0x0000000000004000 -- | 'PIPELINE_STAGE_2_ALL_GRAPHICS_BIT' specifies the execution of all -- graphics pipeline stages, and is equivalent to the logical OR of: -- -- - 'PIPELINE_STAGE_2_DRAW_INDIRECT_BIT' -- -- - 'PIPELINE_STAGE_2_TASK_SHADER_BIT_NV' -- -- - 'PIPELINE_STAGE_2_MESH_SHADER_BIT_NV' -- -- - 'PIPELINE_STAGE_2_VERTEX_INPUT_BIT' -- -- - 'PIPELINE_STAGE_2_VERTEX_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT' -- -- - 'PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT' -- -- - 'PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT' -- -- - 'PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT' -- -- - 'PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT' -- -- - 'Vulkan.Extensions.VK_KHR_synchronization2.PIPELINE_STAGE_2_SHADING_RATE_IMAGE_BIT_NV' -- -- - 'PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT' -- -- - 'PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI' pattern PIPELINE_STAGE_2_ALL_GRAPHICS_BIT = PipelineStageFlagBits2 0x0000000000008000 -- | 'PIPELINE_STAGE_2_ALL_COMMANDS_BIT' specifies all operations performed -- by all commands supported on the queue it is used with. pattern PIPELINE_STAGE_2_ALL_COMMANDS_BIT = PipelineStageFlagBits2 0x0000000000010000 -- | 'PIPELINE_STAGE_2_COPY_BIT' specifies the execution of all -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#copies copy commands>, -- including 'Vulkan.Core10.CommandBufferBuilding.cmdCopyQueryPoolResults'. pattern PIPELINE_STAGE_2_COPY_BIT = PipelineStageFlagBits2 0x0000000100000000 -- | 'PIPELINE_STAGE_2_RESOLVE_BIT' specifies the execution of -- 'Vulkan.Core10.CommandBufferBuilding.cmdResolveImage'. pattern PIPELINE_STAGE_2_RESOLVE_BIT = PipelineStageFlagBits2 0x0000000200000000 -- | 'PIPELINE_STAGE_2_BLIT_BIT' specifies the execution of -- 'Vulkan.Core10.CommandBufferBuilding.cmdBlitImage'. pattern PIPELINE_STAGE_2_BLIT_BIT = PipelineStageFlagBits2 0x0000000400000000 -- | 'PIPELINE_STAGE_2_CLEAR_BIT' specifies the execution of -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#clears clear commands>, -- with the exception of -- 'Vulkan.Core10.CommandBufferBuilding.cmdClearAttachments'. pattern PIPELINE_STAGE_2_CLEAR_BIT = PipelineStageFlagBits2 0x0000000800000000 -- | 'PIPELINE_STAGE_2_INDEX_INPUT_BIT' specifies the stage of the pipeline -- where index buffers are consumed. pattern PIPELINE_STAGE_2_INDEX_INPUT_BIT = PipelineStageFlagBits2 0x0000001000000000 -- | 'PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT' specifies the stage of the -- pipeline where vertex buffers are consumed. pattern PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT = PipelineStageFlagBits2 0x0000002000000000 -- | 'PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT' is equivalent to -- specifying all supported -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipeline-graphics-subsets-pre-rasterization pre-rasterization shader stages>: -- -- - 'PIPELINE_STAGE_2_VERTEX_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT' -- -- - 'PIPELINE_STAGE_2_TASK_SHADER_BIT_NV' -- -- - 'PIPELINE_STAGE_2_MESH_SHADER_BIT_NV' pattern PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT = PipelineStageFlagBits2 0x0000004000000000 -- | 'PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI' specifies the stage of the -- pipeline where the invocation mask image is read by the implementation -- to optimize the ray dispatch. pattern PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI = PipelineStageFlagBits2 0x0000010000000000 -- | 'PIPELINE_STAGE_2_SUBPASS_SHADING_BIT_HUAWEI' specifies the subpass -- shading shader stage. pattern PIPELINE_STAGE_2_SUBPASS_SHADING_BIT_HUAWEI = PipelineStageFlagBits2 0x0000008000000000 -- | 'PIPELINE_STAGE_2_MESH_SHADER_BIT_NV' specifies the mesh shader stage. pattern PIPELINE_STAGE_2_MESH_SHADER_BIT_NV = PipelineStageFlagBits2 0x0000000000100000 -- | 'PIPELINE_STAGE_2_TASK_SHADER_BIT_NV' specifies the task shader stage. pattern PIPELINE_STAGE_2_TASK_SHADER_BIT_NV = PipelineStageFlagBits2 0x0000000000080000 -- | 'PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT' specifies the stage -- of the pipeline where the fragment density map is read to -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fragmentdensitymapops generate the fragment areas>. pattern PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT = PipelineStageFlagBits2 0x0000000000800000 -- | 'PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR' specifies the execution of -- the ray tracing shader stages. pattern PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR = PipelineStageFlagBits2 0x0000000000200000 -- | 'PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR' specifies the -- execution of -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#acceleration-structure acceleration structure commands>. pattern PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR = PipelineStageFlagBits2 0x0000000002000000 -- | 'PIPELINE_STAGE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' specifies -- the stage of the pipeline where the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-fragment-shading-rate-attachment fragment shading rate attachment> -- or -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-shading-rate-image shading rate image> -- is read to determine the fragment shading rate for portions of a -- rasterized primitive. pattern PIPELINE_STAGE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = PipelineStageFlagBits2 0x0000000000400000 -- | 'PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV' specifies the stage of the -- pipeline where device-side generation of commands via -- 'Vulkan.Extensions.VK_NV_device_generated_commands.cmdPreprocessGeneratedCommandsNV' -- is handled. pattern PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV = PipelineStageFlagBits2 0x0000000000020000 -- | 'PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT' specifies the stage of -- the pipeline where the predicate of conditional rendering is consumed. pattern PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT = PipelineStageFlagBits2 0x0000000000040000 -- | 'PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT' specifies the stage of the -- pipeline where vertex attribute output values are written to the -- transform feedback buffers. pattern PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT = PipelineStageFlagBits2 0x0000000001000000 conNamePipelineStageFlagBits2 :: String conNamePipelineStageFlagBits2 = "PipelineStageFlagBits2" enumPrefixPipelineStageFlagBits2 :: String enumPrefixPipelineStageFlagBits2 = "PIPELINE_STAGE_2_" showTablePipelineStageFlagBits2 :: [(PipelineStageFlagBits2, String)] showTablePipelineStageFlagBits2 = [ (PIPELINE_STAGE_2_NONE , "NONE") , (PIPELINE_STAGE_2_TOP_OF_PIPE_BIT , "TOP_OF_PIPE_BIT") , (PIPELINE_STAGE_2_DRAW_INDIRECT_BIT , "DRAW_INDIRECT_BIT") , (PIPELINE_STAGE_2_VERTEX_INPUT_BIT , "VERTEX_INPUT_BIT") , (PIPELINE_STAGE_2_VERTEX_SHADER_BIT , "VERTEX_SHADER_BIT") , (PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT , "TESSELLATION_CONTROL_SHADER_BIT") , (PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT, "TESSELLATION_EVALUATION_SHADER_BIT") , (PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT , "GEOMETRY_SHADER_BIT") , (PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT , "FRAGMENT_SHADER_BIT") , (PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT , "EARLY_FRAGMENT_TESTS_BIT") , (PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT , "LATE_FRAGMENT_TESTS_BIT") , (PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT , "COLOR_ATTACHMENT_OUTPUT_BIT") , (PIPELINE_STAGE_2_COMPUTE_SHADER_BIT , "COMPUTE_SHADER_BIT") , (PIPELINE_STAGE_2_ALL_TRANSFER_BIT , "ALL_TRANSFER_BIT") , (PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT , "BOTTOM_OF_PIPE_BIT") , (PIPELINE_STAGE_2_HOST_BIT , "HOST_BIT") , (PIPELINE_STAGE_2_ALL_GRAPHICS_BIT , "ALL_GRAPHICS_BIT") , (PIPELINE_STAGE_2_ALL_COMMANDS_BIT , "ALL_COMMANDS_BIT") , (PIPELINE_STAGE_2_COPY_BIT , "COPY_BIT") , (PIPELINE_STAGE_2_RESOLVE_BIT , "RESOLVE_BIT") , (PIPELINE_STAGE_2_BLIT_BIT , "BLIT_BIT") , (PIPELINE_STAGE_2_CLEAR_BIT , "CLEAR_BIT") , (PIPELINE_STAGE_2_INDEX_INPUT_BIT , "INDEX_INPUT_BIT") , (PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT , "VERTEX_ATTRIBUTE_INPUT_BIT") , (PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT , "PRE_RASTERIZATION_SHADERS_BIT") , (PIPELINE_STAGE_2_INVOCATION_MASK_BIT_HUAWEI , "INVOCATION_MASK_BIT_HUAWEI") , (PIPELINE_STAGE_2_SUBPASS_SHADING_BIT_HUAWEI , "SUBPASS_SHADING_BIT_HUAWEI") , (PIPELINE_STAGE_2_MESH_SHADER_BIT_NV , "MESH_SHADER_BIT_NV") , (PIPELINE_STAGE_2_TASK_SHADER_BIT_NV , "TASK_SHADER_BIT_NV") , (PIPELINE_STAGE_2_FRAGMENT_DENSITY_PROCESS_BIT_EXT , "FRAGMENT_DENSITY_PROCESS_BIT_EXT") , (PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR , "RAY_TRACING_SHADER_BIT_KHR") , (PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, "ACCELERATION_STRUCTURE_BUILD_BIT_KHR") , (PIPELINE_STAGE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR, "FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR") , (PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_NV , "COMMAND_PREPROCESS_BIT_NV") , (PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT , "CONDITIONAL_RENDERING_BIT_EXT") , (PIPELINE_STAGE_2_TRANSFORM_FEEDBACK_BIT_EXT , "TRANSFORM_FEEDBACK_BIT_EXT") ] instance Show PipelineStageFlagBits2 where showsPrec = enumShowsPrec enumPrefixPipelineStageFlagBits2 showTablePipelineStageFlagBits2 conNamePipelineStageFlagBits2 (\(PipelineStageFlagBits2 x) -> x) (\x -> showString "0x" . showHex x) instance Read PipelineStageFlagBits2 where readPrec = enumReadPrec enumPrefixPipelineStageFlagBits2 showTablePipelineStageFlagBits2 conNamePipelineStageFlagBits2 PipelineStageFlagBits2
expipiplus1/vulkan
src/Vulkan/Core13/Enums/PipelineStageFlags2.hs
bsd-3-clause
28,884
1
10
7,158
1,653
1,043
610
-1
-1
module Stylesheet ( style ) where import Stitch import Stitch.Combinators import Data.Text (Text) type Color = Text midnight :: Color midnight = "rgba(44, 62, 80, 1)" cloud :: Color cloud = "rgba(236, 240, 241, 1)" amethyst :: Color amethyst = "rgba(155, 89, 182, 1)" nephritis :: Color nephritis = "rgba(39, 174, 96, 1)" white :: Color white = "white" style :: CSS style = do cssImport "url(http://fonts.googleapis.com/css?family=Lato:400,700)" reset "html" ? "font-size" .= "62.5%" "body" ? do "h1" ? do "font" -: do "size" .= "1.5rem" "weight" .= "bold" "margin-bottom" .= "0.5rem" "padding" .= "0.5rem" "display" .= "inline-block" "background-color" .= amethyst "color" .= white "font-family" .= "Lato, Helvetica, sans" "background-color" .= cloud "color" .= midnight "a" ? do "color" .= midnight "text-decoration" .= "none" "&:hover" ? "text-decoration" .= "underline" "#main" ? do "max-width" .= "40rem" "margin" .= "0 auto" "padding" .= "1rem" "font" .= "inherit" "input" ? do "font" .= "inherit" "border" .= "none" "&[type=submit]" ? do "background-color" .= nephritis "cursor" .= "pointer" "color" .= white "margin" .= "0.25rem" "&[type=file]" ? "margin" .= "0.25rem" reset :: CSS reset = do "html, body, div, span, applet, object, iframe,\ \ h1, h2, h3, h4, h5, h6, p, blockquote, pre,\ \ a, abbr, acronym, address, big, cite, code,\ \ del, dfn, em, img, ins, kbd, q, s, samp,\ \ small, strike, strong, sub, sup, tt, var,\ \ b, u, i, center, dl, dt, dd, ol, ul, li,\ \ fieldset, form, label, legend,\ \ table, caption, tbody, tfoot, thead, tr, th, td,\ \ article, aside, canvas, details, embed,\ \ figure, figcaption, footer, header, hgroup,\ \ menu, nav, output, ruby, section, summary,\ \ time, mark, audio, video" ? do comment "http://meyerweb.com/eric/tools/css/reset/\n\ \ v2.0 | 20110126\n\ \ License: none (public domain)" "margin" .= "0" "padding" .= "0" "border" .= "none" "font" -: do "weight" .= "inherit" "size" .= "100%" "vertical-align" .= "baseline" "footer, header, hgroup, menu, nav, section" ? do comment "HTML5 display-role reset for older browsers" "display" .= "block" "body" ? "line-height" .= "1" "ol, ul" ? "list-style" .= "none" "blockquote, q" ? do "quotes" .= "none" "&:before, &:after" ? do "content" .= "\"\"" "content" .= "none" "table" ? "border" -: do "collapse" .= "collapse" "spacing" .= "0"
intolerable/crusher
src/Stylesheet.hs
bsd-3-clause
2,669
0
16
695
512
238
274
80
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.List -- Copyright : (c) David Himmelstrup 2005 -- Duncan Coutts 2008-2011 -- License : BSD-like -- -- Maintainer : [email protected] -- -- Search for and print information about packages ----------------------------------------------------------------------------- module Distribution.Client.List ( list, info ) where import Distribution.Package ( PackageName(..), Package(..), packageName, packageVersion , Dependency(..), thisPackageVersion, depends, simplifyDependency ) import Distribution.ModuleName (ModuleName) import Distribution.License (License) import qualified Distribution.InstalledPackageInfo as Installed import qualified Distribution.PackageDescription as Available import Distribution.PackageDescription ( Flag(..), FlagName(..) ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.Simple.Compiler ( Compiler, PackageDBStack ) import Distribution.Simple.Program (ProgramConfiguration) import Distribution.Simple.Utils ( equating, comparing, die, notice ) import Distribution.Simple.Setup (fromFlag) import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Version ( Version(..), VersionRange, withinRange, anyVersion , intersectVersionRanges, simplifyVersionRange ) import Distribution.Verbosity (Verbosity) import Distribution.Text ( Text(disp), display ) import Distribution.Client.Types ( AvailablePackage(..), Repo, AvailablePackageDb(..) , InstalledPackage(..) ) import Distribution.Client.Dependency.Types ( PackageConstraint(..) ) import Distribution.Client.Targets ( UserTarget, resolveUserTargets, PackageSpecifier(..) ) import Distribution.Client.Setup ( GlobalFlags(..), ListFlags(..), InfoFlags(..) ) import Distribution.Client.Utils ( mergeBy, MergeResult(..) ) import Distribution.Client.IndexUtils as IndexUtils ( getAvailablePackages, getInstalledPackages ) import Distribution.Client.FetchUtils ( isFetched ) import Data.List ( sortBy, groupBy, sort, nub, intersperse, maximumBy, partition ) import Data.Maybe ( listToMaybe, fromJust, fromMaybe, isJust ) import qualified Data.Map as Map import Data.Tree as Tree import Control.Monad ( MonadPlus(mplus), join ) import Control.Exception ( assert ) import Text.PrettyPrint.HughesPJ as Disp import System.Directory ( doesDirectoryExist ) -- |Show information about packages list :: Verbosity -> PackageDBStack -> [Repo] -> Compiler -> ProgramConfiguration -> ListFlags -> [String] -> IO () list verbosity packageDBs repos comp conf listFlags pats = do installed <- getInstalledPackages verbosity comp packageDBs conf availableDb <- getAvailablePackages verbosity repos let available = packageIndex availableDb prefs name = fromMaybe anyVersion (Map.lookup name (packagePreferences availableDb)) pkgsInfo :: [(PackageName, [InstalledPackage], [AvailablePackage])] pkgsInfo -- gather info for all packages | null pats = mergePackages (PackageIndex.allPackages installed) (PackageIndex.allPackages available) -- gather info for packages matching search term | otherwise = mergePackages (matchingPackages installed) (matchingPackages available) matches :: [PackageDisplayInfo] matches = [ mergePackageInfo pref installedPkgs availablePkgs selectedPkg False | (pkgname, installedPkgs, availablePkgs) <- pkgsInfo , not onlyInstalled || not (null installedPkgs) , let pref = prefs pkgname selectedPkg = latestWithPref pref availablePkgs ] if simpleOutput then putStr $ unlines [ display (pkgName pkg) ++ " " ++ display version | pkg <- matches , version <- if onlyInstalled then installedVersions pkg else nub . sort $ installedVersions pkg ++ availableVersions pkg ] -- Note: this only works because for 'list', one cannot currently -- specify any version constraints, so listing all installed -- and available ones works. else if null matches then notice verbosity "No matches found." else putStr $ unlines (map showPackageSummaryInfo matches) where onlyInstalled = fromFlag (listInstalled listFlags) simpleOutput = fromFlag (listSimpleOutput listFlags) matchingPackages index = [ pkg | pat <- pats , (_, pkgs) <- PackageIndex.searchByNameSubstring index pat , pkg <- pkgs ] info :: Verbosity -> PackageDBStack -> [Repo] -> Compiler -> ProgramConfiguration -> GlobalFlags -> InfoFlags -> [UserTarget] -> IO () info verbosity packageDBs repos comp conf globalFlags _listFlags userTargets = do installed <- getInstalledPackages verbosity comp packageDBs conf availableDb <- getAvailablePackages verbosity repos let available = packageIndex availableDb prefs name = fromMaybe anyVersion (Map.lookup name (packagePreferences availableDb)) -- Users may specify names of packages that are only installed, not -- just available source packages, so we must resolve targets using -- the combination of installed and available packages. let available' = PackageIndex.fromList $ map packageId (PackageIndex.allPackages installed) ++ map packageId (PackageIndex.allPackages available) pkgSpecifiers <- resolveUserTargets verbosity globalFlags available' userTargets pkgsinfo <- sequence [ do pkginfo <- either die return $ gatherPkgInfo prefs installed available pkgSpecifier updateFileSystemPackageDetails pkginfo | pkgSpecifier <- pkgSpecifiers ] putStr $ unlines (map showPackageDetailedInfo pkgsinfo) where gatherPkgInfo prefs installed available (NamedPackage name constraints) | null (selectedInstalledPkgs) && null (selectedAvailablePkgs) = Left $ "There is no available version of " ++ display name ++ " that satisfies " ++ display (simplifyVersionRange verConstraint) | otherwise = Right $ mergePackageInfo pref installedPkgs availablePkgs selectedAvailablePkg showPkgVersion where pref = prefs name installedPkgs = PackageIndex.lookupPackageName installed name availablePkgs = PackageIndex.lookupPackageName available name selectedInstalledPkgs = PackageIndex.lookupDependency installed (Dependency name verConstraint) selectedAvailablePkgs = PackageIndex.lookupDependency available (Dependency name verConstraint) selectedAvailablePkg = latestWithPref pref selectedAvailablePkgs -- display a specific package version if the user -- supplied a non-trivial version constraint showPkgVersion = not (null verConstraints) verConstraint = foldr intersectVersionRanges anyVersion verConstraints verConstraints = [ vr | PackageVersionConstraint _ vr <- constraints ] gatherPkgInfo prefs installed available (SpecificSourcePackage pkg) = Right $ mergePackageInfo pref installedPkgs availablePkgs selectedPkg True where name = packageName pkg pref = prefs name installedPkgs = PackageIndex.lookupPackageName installed name availablePkgs = PackageIndex.lookupPackageName available name selectedPkg = Just pkg -- | The info that we can display for each package. It is information per -- package name and covers all installed and avilable versions. -- data PackageDisplayInfo = PackageDisplayInfo { pkgName :: PackageName, selectedVersion :: Maybe Version, selectedAvailable :: Maybe AvailablePackage, installedVersions :: [Version], availableVersions :: [Version], preferredVersions :: VersionRange, homepage :: String, bugReports :: String, sourceRepo :: String, synopsis :: String, description :: String, category :: String, license :: License, author :: String, maintainer :: String, dependencies :: [Dependency], flags :: [Flag], hasLib :: Bool, hasExe :: Bool, executables :: [String], modules :: [ModuleName], haddockHtml :: FilePath, haveTarball :: Bool } showPackageSummaryInfo :: PackageDisplayInfo -> String showPackageSummaryInfo pkginfo = renderStyle (style {lineLength = 80, ribbonsPerLine = 1}) $ char '*' <+> disp (pkgName pkginfo) $+$ (nest 4 $ vcat [ maybeShow (synopsis pkginfo) "Synopsis:" reflowParagraphs , text "Default available version:" <+> case selectedAvailable pkginfo of Nothing -> text "[ Not available from any configured repository ]" Just pkg -> disp (packageVersion pkg) , text "Installed versions:" <+> case installedVersions pkginfo of [] | hasLib pkginfo -> text "[ Not installed ]" | otherwise -> text "[ Unknown ]" versions -> dispTopVersions 4 (preferredVersions pkginfo) versions , maybeShow (homepage pkginfo) "Homepage:" text , text "License: " <+> text (display (license pkginfo)) ]) $+$ text "" where maybeShow [] _ _ = empty maybeShow l s f = text s <+> (f l) showPackageDetailedInfo :: PackageDisplayInfo -> String showPackageDetailedInfo pkginfo = renderStyle (style {lineLength = 80, ribbonsPerLine = 1}) $ char '*' <+> disp (pkgName pkginfo) <> maybe empty (\v -> char '-' <> disp v) (selectedVersion pkginfo) <+> text (replicate (16 - length (display (pkgName pkginfo))) ' ') <> parens pkgkind $+$ (nest 4 $ vcat [ entry "Synopsis" synopsis hideIfNull reflowParagraphs , entry "Versions available" availableVersions (altText null "[ Not available from server ]") (dispTopVersions 9 (preferredVersions pkginfo)) , entry "Versions installed" installedVersions (altText null (if hasLib pkginfo then "[ Not installed ]" else "[ Unknown ]")) (dispTopVersions 4 (preferredVersions pkginfo)) , entry "Homepage" homepage orNotSpecified text , entry "Bug reports" bugReports orNotSpecified text , entry "Description" description hideIfNull reflowParagraphs , entry "Category" category hideIfNull text , entry "License" license alwaysShow disp , entry "Author" author hideIfNull reflowLines , entry "Maintainer" maintainer hideIfNull reflowLines , entry "Source repo" sourceRepo orNotSpecified text , entry "Executables" executables hideIfNull (commaSep text) , entry "Flags" flags hideIfNull (commaSep dispFlag) , entry "Dependencies" dependencies hideIfNull (commaSep disp) , entry "Documentation" haddockHtml showIfInstalled text , entry "Cached" haveTarball alwaysShow dispYesNo , if not (hasLib pkginfo) then empty else text "Modules:" $+$ nest 4 (vcat (map disp . sort . modules $ pkginfo)) ]) $+$ text "" where entry fname field cond format = case cond (field pkginfo) of Nothing -> label <+> format (field pkginfo) Just Nothing -> empty Just (Just other) -> label <+> text other where label = text fname <> char ':' <> padding padding = text (replicate (13 - length fname ) ' ') normal = Nothing hide = Just Nothing replace msg = Just (Just msg) alwaysShow = const normal hideIfNull v = if null v then hide else normal showIfInstalled v | not isInstalled = hide | null v = replace "[ Not installed ]" | otherwise = normal altText nul msg v = if nul v then replace msg else normal orNotSpecified = altText null "[ Not specified ]" commaSep f = Disp.fsep . Disp.punctuate (Disp.char ',') . map f dispFlag f = case flagName f of FlagName n -> text n dispYesNo True = text "Yes" dispYesNo False = text "No" isInstalled = not (null (installedVersions pkginfo)) hasExes = length (executables pkginfo) >= 2 --TODO: exclude non-buildable exes pkgkind | hasLib pkginfo && hasExes = text "programs and library" | hasLib pkginfo && hasExe pkginfo = text "program and library" | hasLib pkginfo = text "library" | hasExes = text "programs" | hasExe pkginfo = text "program" | otherwise = empty reflowParagraphs :: String -> Doc reflowParagraphs = vcat . intersperse (text "") -- re-insert blank lines . map (fsep . map text . concatMap words) -- reflow paragraphs . filter (/= [""]) . groupBy (\x y -> "" `notElem` [x,y]) -- break on blank lines . lines reflowLines :: String -> Doc reflowLines = vcat . map text . lines -- | We get the 'PackageDisplayInfo' by combining the info for the installed -- and available versions of a package. -- -- * We're building info about a various versions of a single named package so -- the input package info records are all supposed to refer to the same -- package name. -- mergePackageInfo :: VersionRange -> [InstalledPackage] -> [AvailablePackage] -> Maybe AvailablePackage -> Bool -> PackageDisplayInfo mergePackageInfo versionPref installedPkgs availablePkgs selectedPkg showVer = assert (length installedPkgs + length availablePkgs > 0) $ PackageDisplayInfo { pkgName = combine packageName available packageName installed, selectedVersion = if showVer then fmap packageVersion selectedPkg else Nothing, selectedAvailable = availableSelected, installedVersions = map packageVersion installedPkgs, availableVersions = map packageVersion availablePkgs, preferredVersions = versionPref, license = combine Available.license available Installed.license installed, maintainer = combine Available.maintainer available Installed.maintainer installed, author = combine Available.author available Installed.author installed, homepage = combine Available.homepage available Installed.homepage installed, bugReports = maybe "" Available.bugReports available, sourceRepo = fromMaybe "" . join . fmap (uncons Nothing Available.repoLocation . sortBy (comparing Available.repoKind) . Available.sourceRepos) $ available, --TODO: installed package info is missing synopsis synopsis = maybe "" Available.synopsis available, description = combine Available.description available Installed.description installed, category = combine Available.category available Installed.category installed, flags = maybe [] Available.genPackageFlags availableGeneric, hasLib = isJust installed || fromMaybe False (fmap (isJust . Available.condLibrary) availableGeneric), hasExe = fromMaybe False (fmap (not . null . Available.condExecutables) availableGeneric), executables = map fst (maybe [] Available.condExecutables availableGeneric), modules = combine Installed.exposedModules installed (maybe [] Available.exposedModules . Available.library) available, dependencies = map simplifyDependency $ combine Available.buildDepends available (map thisPackageVersion . depends) installed', haddockHtml = fromMaybe "" . join . fmap (listToMaybe . Installed.haddockHTMLs) $ installed, haveTarball = False } where combine f x g y = fromJust (fmap f x `mplus` fmap g y) installed' = latestWithPref versionPref installedPkgs installed = fmap (\(InstalledPackage p _) -> p) installed' availableSelected | isJust selectedPkg = selectedPkg | otherwise = latestWithPref versionPref availablePkgs availableGeneric = fmap packageDescription availableSelected available = fmap flattenPackageDescription availableGeneric uncons :: b -> (a -> b) -> [a] -> b uncons z _ [] = z uncons _ f (x:_) = f x -- | Not all the info is pure. We have to check if the docs really are -- installed, because the registered package info lies. Similarly we have to -- check if the tarball has indeed been fetched. -- updateFileSystemPackageDetails :: PackageDisplayInfo -> IO PackageDisplayInfo updateFileSystemPackageDetails pkginfo = do fetched <- maybe (return False) (isFetched . packageSource) (selectedAvailable pkginfo) docsExist <- doesDirectoryExist (haddockHtml pkginfo) return pkginfo { haveTarball = fetched, haddockHtml = if docsExist then haddockHtml pkginfo else "" } latestWithPref :: Package pkg => VersionRange -> [pkg] -> Maybe pkg latestWithPref _ [] = Nothing latestWithPref pref pkgs = Just (maximumBy (comparing prefThenVersion) pkgs) where prefThenVersion pkg = let ver = packageVersion pkg in (withinRange ver pref, ver) -- | Rearrange installed and available packages into groups referring to the -- same package by name. In the result pairs, the lists are guaranteed to not -- both be empty. -- mergePackages :: [InstalledPackage] -> [AvailablePackage] -> [( PackageName , [InstalledPackage] , [AvailablePackage] )] mergePackages installed available = map collect $ mergeBy (\i a -> fst i `compare` fst a) (groupOn packageName installed) (groupOn packageName available) where collect (OnlyInLeft (name,is) ) = (name, is, []) collect ( InBoth (_,is) (name,as)) = (name, is, as) collect (OnlyInRight (name,as)) = (name, [], as) groupOn :: Ord key => (a -> key) -> [a] -> [(key,[a])] groupOn key = map (\xs -> (key (head xs), xs)) . groupBy (equating key) . sortBy (comparing key) dispTopVersions :: Int -> VersionRange -> [Version] -> Doc dispTopVersions n pref vs = (Disp.fsep . Disp.punctuate (Disp.char ',') . map (\ver -> if ispref ver then disp ver else parens (disp ver)) . sort . take n . interestingVersions ispref $ vs) <+> trailingMessage where ispref ver = withinRange ver pref extra = length vs - n trailingMessage | extra <= 0 = Disp.empty | otherwise = Disp.parens $ Disp.text "and" <+> Disp.int (length vs - n) <+> if extra == 1 then Disp.text "other" else Disp.text "others" -- | Reorder a bunch of versions to put the most interesting / significant -- versions first. A preferred version range is taken into account. -- -- This may be used in a user interface to select a small number of versions -- to present to the user, e.g. -- -- > let selectVersions = sort . take 5 . interestingVersions pref -- interestingVersions :: (Version -> Bool) -> [Version] -> [Version] interestingVersions pref = map ((\ns -> Version ns []) . fst) . filter snd . concat . Tree.levels . swizzleTree . reorderTree (\(Node (v,_) _) -> pref (Version v [])) . reverseTree . mkTree . map versionBranch where swizzleTree = unfoldTree (spine []) where spine ts' (Node x []) = (x, ts') spine ts' (Node x (t:ts)) = spine (Node x ts:ts') t reorderTree _ (Node x []) = Node x [] reorderTree p (Node x ts) = Node x (ts' ++ ts'') where (ts',ts'') = partition p (map (reorderTree p) ts) reverseTree (Node x cs) = Node x (reverse (map reverseTree cs)) mkTree xs = unfoldTree step (False, [], xs) where step (node,ns,vs) = ( (reverse ns, node) , [ (any null vs', n:ns, filter (not . null) vs') | (n, vs') <- groups vs ] ) groups = map (\g -> (head (head g), map tail g)) . groupBy (equating head)
yihuang/cabal-install
Distribution/Client/List.hs
bsd-3-clause
21,877
0
20
6,686
5,158
2,715
2,443
405
8
take :: Int -> ([a] -> [a])
NeonGraal/rwh-stack
ch02/Take.hs
bsd-3-clause
27
0
8
6
23
13
10
1
0
-- | This module provides 'RequesterT', the standard implementation of -- 'Requester'. {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #ifdef USE_REFLEX_OPTIMIZER {-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-} #endif module Reflex.Requester.Base ( RequesterT (..) , runRequesterT , withRequesterT , runWithReplaceRequesterTWith , traverseIntMapWithKeyWithAdjustRequesterTWith , traverseDMapWithKeyWithAdjustRequesterTWith , RequesterData , RequesterDataKey , traverseRequesterData , forRequesterData , requesterDataToList , singletonRequesterData , matchResponsesWithRequests , multiEntry , unMultiEntry , requesting' ) where import Reflex.Class import Reflex.Adjustable.Class import Reflex.Dynamic import Reflex.Host.Class import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.Requester.Class import Reflex.TriggerEvent.Class import Control.Applicative (liftA2) import Control.Monad.Exception import Control.Monad.Identity import Control.Monad.Morph import Control.Monad.Primitive import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.State.Strict import Data.Bits import Data.Coerce import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap import Data.Dependent.Sum (DSum (..)) import Data.Functor.Compose import Data.Functor.Misc import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid ((<>)) import Data.Proxy import qualified Data.Semigroup as S import Data.Some (Some(Some)) import Data.Type.Equality import Data.Unique.Tag import GHC.Exts (Any) import Unsafe.Coerce --TODO: Make this module type-safe newtype TagMap (f :: * -> *) = TagMap (IntMap Any) newtype RequesterData f = RequesterData (TagMap (Entry f)) data RequesterDataKey a where RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a --TODO: Don't put a second Int here (or in the other Multis); use a single Int instead RequesterDataKey_Multi2 :: {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a singletonRequesterData :: RequesterDataKey a -> f a -> RequesterData f singletonRequesterData rdk v = case rdk of RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v requesterDataToList :: RequesterData f -> [DSum RequesterDataKey f] requesterDataToList (RequesterData m) = do k :=> Entry e <- tagMapToList m case myKeyType k of MyTagType_Single -> return $ RequesterDataKey_Single k :=> e MyTagType_Multi -> do (k', e') <- IntMap.toList e k'' :=> e'' <- requesterDataToList e' return $ RequesterDataKey_Multi k k' k'' :=> e'' MyTagType_Multi2 -> do (k', e') <- Map.toList e (k'', e'') <- IntMap.toList e' k''' :=> e''' <- requesterDataToList e'' return $ RequesterDataKey_Multi2 k k' k'' k''' :=> e''' MyTagType_Multi3 -> do (k', e') <- IntMap.toList e (k'', e'') <- IntMap.toList e' k''' :=> e''' <- requesterDataToList e'' return $ RequesterDataKey_Multi3 k k' k'' k''' :=> e''' singletonTagMap :: forall f a. MyTag a -> f a -> TagMap f singletonTagMap (MyTag k) v = TagMap $ IntMap.singleton k $ (unsafeCoerce :: f a -> Any) v tagMapToList :: forall f. TagMap f -> [DSum MyTag f] tagMapToList (TagMap m) = f <$> IntMap.toList m where f :: (Int, Any) -> DSum MyTag f f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g) traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m where g :: Int -> Any -> t Any g k v = (unsafeCoerce :: g a -> Any) <$> f (MyTag k) ((unsafeCoerce :: Any -> f a) v) -- | Runs in reverse to accommodate for the fact that we accumulate it in reverse traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response) traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order where go :: forall x. MyTag x -> Entry request x -> m (Entry response x) go k (Entry request) = Entry <$> case myKeyType k of MyTagType_Single -> f request MyTagType_Multi -> traverse (traverseRequesterData f) request MyTagType_Multi2 -> traverse (traverse (traverseRequesterData f)) request MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request -- | 'traverseRequesterData' with its arguments flipped forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response) forRequesterData r f = traverseRequesterData f r data MyTagType :: * -> * where MyTagType_Single :: MyTagType (Single a) MyTagType_Multi :: MyTagType Multi MyTagType_Multi2 :: MyTagType (Multi2 k) MyTagType_Multi3 :: MyTagType Multi3 myKeyType :: MyTag x -> MyTagType x myKeyType (MyTag k) = case k .&. 0x3 of 0x0 -> unsafeCoerce MyTagType_Single 0x1 -> unsafeCoerce MyTagType_Multi 0x2 -> unsafeCoerce MyTagType_Multi2 0x3 -> unsafeCoerce MyTagType_Multi3 t -> error $ "Reflex.Requester.Base.myKeyType: no such key type" <> show t data Single a data Multi data Multi2 (k :: * -> *) data Multi3 class MyTagTypeOffset x where myTagTypeOffset :: proxy x -> Int instance MyTagTypeOffset (Single a) where myTagTypeOffset _ = 0x0 instance MyTagTypeOffset Multi where myTagTypeOffset _ = 0x1 instance MyTagTypeOffset (Multi2 k) where myTagTypeOffset _ = 0x2 instance MyTagTypeOffset Multi3 where myTagTypeOffset _ = 0x3 type family EntryContents request a where EntryContents request (Single a) = request a EntryContents request Multi = IntMap (RequesterData request) EntryContents request (Multi2 k) = Map (Some k) (IntMap (RequesterData request)) EntryContents request Multi3 = IntMap (IntMap (RequesterData request)) newtype Entry request x = Entry { unEntry :: EntryContents request x } {-# INLINE singleEntry #-} singleEntry :: f a -> Entry f (Single a) singleEntry = Entry {-# INLINE multiEntry #-} multiEntry :: IntMap (RequesterData f) -> Entry f Multi multiEntry = Entry {-# INLINE unMultiEntry #-} unMultiEntry :: Entry f Multi -> IntMap (RequesterData f) unMultiEntry = unEntry -- | We use a hack here to pretend we have x ~ request a; we don't want to use a GADT, because GADTs (even with zero-size existential contexts) can't be newtypes -- WARNING: This type should never be exposed. In particular, this is extremely unsound if a MyTag from one run of runRequesterT is ever compared against a MyTag from another newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum) newtype MyTagWrap (f :: * -> *) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum) {-# INLINE castMyTagWrap #-} castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x) castMyTagWrap = coerce instance GEq MyTag where (MyTag a) `geq` (MyTag b) = if a == b then Just $ unsafeCoerce Refl else Nothing instance GCompare MyTag where (MyTag a) `gcompare` (MyTag b) = case a `compare` b of LT -> GLT EQ -> unsafeCoerce GEQ GT -> GGT instance GEq (MyTagWrap f) where (MyTagWrap a) `geq` (MyTagWrap b) = if a == b then Just $ unsafeCoerce Refl else Nothing instance GCompare (MyTagWrap f) where (MyTagWrap a) `gcompare` (MyTagWrap b) = case a `compare` b of LT -> GLT EQ -> unsafeCoerce GEQ GT -> GGT data RequesterState t (request :: * -> *) = RequesterState { _requesterState_nextMyTag :: {-# UNPACK #-} !Int -- Starts at -4 and goes down by 4 each time, to accommodate two 'type' bits at the bottom , _requesterState_requests :: ![(Int, Event t Any)] } -- | A basic implementation of 'Requester'. newtype RequesterT t request (response :: * -> *) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException -- MonadAsyncException can't be derived on ghc-8.0.1; we use base-4.9.1 as a proxy for ghc-8.0.2 #if MIN_VERSION_base(4,9,1) , MonadAsyncException #endif ) deriving instance MonadSample t m => MonadSample t (RequesterT t request response m) deriving instance MonadHold t m => MonadHold t (RequesterT t request response m) deriving instance PostBuild t m => PostBuild t (RequesterT t request response m) deriving instance TriggerEvent t m => TriggerEvent t (RequesterT t request response m) instance PrimMonad m => PrimMonad (RequesterT t request response m) where type PrimState (RequesterT t request response m) = PrimState m primitive = lift . primitive -- TODO: Monoid and Semigroup can likely be derived once StateT has them. instance (Monoid a, Monad m) => Monoid (RequesterT t request response m a) where mempty = pure mempty mappend = liftA2 mappend instance (S.Semigroup a, Monad m) => S.Semigroup (RequesterT t request response m a) where (<>) = liftA2 (S.<>) -- | Run a 'RequesterT' action. The resulting 'Event' will fire whenever -- requests are made, and responses should be provided in the input 'Event'. -- The 'Tag' keys will be used to return the responses to the same place the -- requests were issued. runRequesterT :: (Reflex t, Monad m) => RequesterT t request response m a -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild runRequesterT (RequesterT a) responses = do (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $ coerceEvent responses return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s) -- | Map a function over the request and response of a 'RequesterT' withRequesterT :: (Reflex t, MonadFix m) => (forall x. req x -> req' x) -- ^ The function to map over the request -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT' withRequesterT freq frsp child = do rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp' (a, req) <- lift $ runRequesterT child rsp rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $ fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req return a instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where type Request (RequesterT t request response m) = request type Response (RequesterT t request response m) = response requesting = fmap coerceEvent . responseFromTag . castMyTagWrap <=< tagRequest . (coerceEvent :: Event t (request a) -> Event t (Entry request (Single a))) requesting_ = void . tagRequest . fmapCheap singleEntry {-# INLINE tagRequest #-} tagRequest :: forall m x t request response. (Monad m, MyTagTypeOffset x) => Event t (Entry request x) -> RequesterT t request response m (MyTagWrap request (Entry request x)) tagRequest req = do old <- RequesterT get let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x) t = MyTagWrap n RequesterT $ put $ RequesterState { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4 , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old } return t {-# INLINE responseFromTag #-} responseFromTag :: Monad m => MyTagWrap response (Entry response x) -> RequesterT t request response m (Event t (Entry response x)) responseFromTag (MyTagWrap t) = do responses :: EventSelectorInt t Any <- RequesterT ask return $ (unsafeCoerce :: Event t Any -> Event t (Entry response x)) $ selectInt responses t instance MonadTrans (RequesterT t request response) where lift = RequesterT . lift . lift instance MFunctor (RequesterT t request response) where hoist f = RequesterT . hoist (hoist f) . unRequesterT instance PerformEvent t m => PerformEvent t (RequesterT t request response m) where type Performable (RequesterT t request response m) = Performable m performEvent_ = lift . performEvent_ performEvent = lift . performEvent instance MonadRef m => MonadRef (RequesterT t request response m) where type Ref (RequesterT t request response m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (RequesterT t request response m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance MonadReader r m => MonadReader r (RequesterT t request response m) where ask = lift ask local f (RequesterT a) = RequesterT $ mapStateT (mapReaderT $ local f) a reader = lift . reader instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm' traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental {-# INLINABLE traverseDMapWithKeyWithAdjust #-} traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x)) requesting' = responseFromTag . castMyTagWrap <=< tagRequest {-# INLINABLE runWithReplaceRequesterTWith #-} runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m , MonadFix m ) => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b')) -> RequesterT t request response m a -> Event t (RequesterT t request response m b) -> RequesterT t request response m (a, Event t b) runWithReplaceRequesterTWith f a0 a' = do rec na' <- numberOccurrencesFrom 1 a' responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here let responses' = fanInt responses ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na' requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v' return (result0, fmapCheap (fst . snd) v') {-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-} traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p. ( Reflex t , MonadHold t m , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request))) , Patch (p (Event t (IntMap (RequesterData request)))) , Functor p , MonadFix m ) => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v')) -> IntMap (IntMap.Key, v) -> Event t (p (IntMap.Key, v)) -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v'))) ) -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request)))) -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request)))) -> (IntMap.Key -> v -> RequesterT t request response m v') -> IntMap v -> Event t (p v) -> RequesterT t request response m (IntMap v', Event t (p v')) traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here let responses :: EventSelectorInt t (IntMap (RequesterData response)) responses = fanInt $ fmapCheap unpack response unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response)) unpack = unEntry pack :: IntMap (IntMap (RequesterData request)) -> Entry request Multi3 pack = Entry f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v') f' k (n, v) = do (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k --TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time? return (fmapCheap (IntMap.singleton n) myRequests, result) ndm' <- numberOccurrencesFrom 1 dm' (children0, children') <- base f' (fmap ((,) 0) dm0) $ fmap (\(n, dm) -> fmap ((,) n) dm) ndm' --TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable let result0 = fmap snd children0 result' = fforCheap children' $ fmap snd requests0 :: IntMap (Event t (IntMap (RequesterData request))) requests0 = fmap fst children0 requests' :: Event t (p (Event t (IntMap (RequesterData request)))) requests' = fforCheap children' $ fmap fst promptRequests :: Event t (IntMap (IntMap (RequesterData request))) promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence' requests <- holdIncremental requests0 requests' return (result0, result') {-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-} traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'. ( GCompare k , Reflex t , MonadHold t m , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request))) , Patch (p' (Some k) (Event t (IntMap (RequesterData request)))) , MonadFix m ) => (forall k' v1 v2. GCompare k' => (forall a. k' a -> v1 a -> m (v2 a)) -> DMap k' v1 -> Event t (p k' v1) -> RequesterT t request response m (DMap k' v2, Event t (p k' v2)) ) -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2) -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2) -> (forall v2. p' (Some k) v2 -> Map (Some k) v2) -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a)) -> (forall a. k a -> v a -> RequesterT t request response m (v' a)) -> DMap k v -> Event t (p k v) -> RequesterT t request response m (DMap k v', Event t (p k v')) traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response))) responses = fanMap $ fmapCheap unpack response unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response)) unpack = unEntry pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k) pack = Entry f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a) f' k (Compose (n, v)) = do (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k)) return $ Compose (fmapCheap (IntMap.singleton n) myRequests, result) ndm' <- numberOccurrencesFrom 1 dm' (children0, children') <- base f' (DMap.map (\v -> Compose (0, v)) dm0) $ fmap (\(n, dm) -> mapPatch (\v -> Compose (n, v)) dm) ndm' let result0 = DMap.map (snd . getCompose) children0 result' = fforCheap children' $ mapPatch $ snd . getCompose requests0 :: Map (Some k) (Event t (IntMap (RequesterData request))) requests0 = weakenDMapWith (fst . getCompose) children0 requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request)))) requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request))) promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence' requests <- holdIncremental requests0 requests' return (result0, result') data Decoder rawResponse response = forall a. Decoder (RequesterDataKey a) (rawResponse -> response a) -- | Matches incoming responses with previously-sent requests -- and uses the provided request "decoder" function to process -- incoming responses. matchResponsesWithRequests :: forall t rawRequest rawResponse request response m. ( MonadFix m , MonadHold t m , Reflex t ) => (forall a. request a -> (rawRequest, rawResponse -> response a)) -- ^ Given a request (from 'Requester'), produces the wire format of the -- request and a function used to process the associated response -> Event t (RequesterData request) -- ^ The outgoing requests -> Event t (Int, rawResponse) -- ^ The incoming responses, tagged by an identifying key -> m ( Event t (Map Int rawRequest) , Event t (RequesterData response) ) -- ^ A map of outgoing wire-format requests and an event of responses keyed -- by the 'RequesterData' key of the associated outgoing request matchResponsesWithRequests f send recv = do rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <- holdIncremental mempty $ leftmost [ fmap (\(_, outstanding, _) -> outstanding) outgoing , snd <$> incoming ] let outgoing = processOutgoing nextId send incoming = processIncoming waitingFor recv return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming) where -- Tags each outgoing request with an identifying integer key -- and returns the next available key, a map of response decoders -- for requests for which there are outstanding responses, and the -- raw requests to be sent out. processOutgoing :: Behavior t Int -- The next available key -> Event t (RequesterData request) -- The outgoing request -> Event t ( Int , PatchMap Int (Decoder rawResponse response) , Map Int rawRequest ) -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests processOutgoing nextId out = flip pushAlways out $ \dm -> do oldNextId <- sample nextId let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do n <- get put $ succ n let (rawReq, rspF) = f v return (n, rawReq, Decoder k rspF) patchWaitingFor = PatchMap $ Map.fromList $ (\(n, _, dec) -> (n, Just dec)) <$> result toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result return (newNextId, patchWaitingFor, toSend) -- Looks up the each incoming raw response in a map of response -- decoders and returns the decoded response and a patch that can -- be used to clear the ID of the consumed response out of the queue -- of expected responses. processIncoming :: Incremental t (PatchMap Int (Decoder rawResponse response)) -- A map of outstanding expected responses -> Event t (Int, rawResponse) -- A incoming response paired with its identifying key -> Event t (RequesterData response, PatchMap Int v) -- The decoded response and a patch that clears the outstanding responses queue processIncoming waitingFor inc = flip push inc $ \(n, rawRsp) -> do wf <- sample $ currentIncremental waitingFor case Map.lookup n wf of Nothing -> return Nothing -- TODO How should lookup failures be handled here? They shouldn't ever happen.. Just (Decoder k rspF) -> do let rsp = rspF rawRsp return $ Just ( singletonRequesterData k rsp , PatchMap $ Map.singleton n Nothing )
ryantrinkle/reflex
src/Reflex/Requester/Base.hs
bsd-3-clause
28,425
0
25
7,089
8,239
4,237
4,002
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Engine.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Test.Tasty.HUnit import Duckling.Engine import Duckling.Locale (Lang(..)) import Duckling.Types import Duckling.Regex.Types tests :: TestTree tests = testGroup "Engine Tests" [ emptyRegexTest , unicodeAndRegexTest ] emptyRegexTest :: TestTree emptyRegexTest = testCase "Empty Regex Test" $ case regex "()" of Regex regex -> assertEqual "empty result" [] $ runDuckling $ lookupRegexAnywhere "hey" EN regex _ -> assertFailure "expected a regex" unicodeAndRegexTest :: TestTree unicodeAndRegexTest = testCase "Unicode and Regex Test" $ case regex "\\$([0-9]*)" of Regex regex -> do -- assertEqual "" expected $ runDuckling $ lookupRegexAnywhere "\128526 $35" EN regex _ -> assertFailure "expected a regex" where expected = [ Node { nodeRange = Range 2 5 , token = Token RegexMatch (GroupMatch ["35"]) , children = [] , rule = Nothing } ]
facebookincubator/duckling
tests/Duckling/Engine/Tests.hs
bsd-3-clause
1,279
0
13
274
275
151
124
34
2
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.TextureBarrier -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.TextureBarrier ( -- * Extension Support glGetARBTextureBarrier, gl_ARB_texture_barrier, -- * Functions glTextureBarrier ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/TextureBarrier.hs
bsd-3-clause
617
0
4
86
44
34
10
6
0
{-# LANGUAGE NoImplicitPrelude, Trustworthy #-} {-# LANGUAGE PolyKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Proxy -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Definition of a Proxy type (poly-kinded in GHC) -- -- /Since: 4.7.0.0/ ----------------------------------------------------------------------------- module Data.Proxy ( Proxy(..), asProxyTypeOf , KProxy(..) ) where import GHC.Base import GHC.Show import GHC.Read import GHC.Enum import GHC.Arr -- | A concrete, poly-kinded proxy type data Proxy t = Proxy -- | A concrete, promotable proxy type, for use at the kind level -- There are no instances for this because it is intended at the kind level only data KProxy (t :: *) = KProxy -- It's common to use (undefined :: Proxy t) and (Proxy :: Proxy t) -- interchangeably, so all of these instances are hand-written to be -- lazy in Proxy arguments. instance Eq (Proxy s) where _ == _ = True instance Ord (Proxy s) where compare _ _ = EQ instance Show (Proxy s) where showsPrec _ _ = showString "Proxy" instance Read (Proxy s) where readsPrec d = readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ]) instance Enum (Proxy s) where succ _ = error "Proxy.succ" pred _ = error "Proxy.pred" fromEnum _ = 0 toEnum 0 = Proxy toEnum _ = error "Proxy.toEnum: 0 expected" enumFrom _ = [Proxy] enumFromThen _ _ = [Proxy] enumFromThenTo _ _ _ = [Proxy] enumFromTo _ _ = [Proxy] instance Ix (Proxy s) where range _ = [Proxy] index _ _ = 0 inRange _ _ = True rangeSize _ = 1 unsafeIndex _ _ = 0 unsafeRangeSize _ = 1 instance Bounded (Proxy s) where minBound = Proxy maxBound = Proxy instance Monoid (Proxy s) where mempty = Proxy mappend _ _ = Proxy mconcat _ = Proxy instance Functor Proxy where fmap _ _ = Proxy {-# INLINE fmap #-} instance Applicative Proxy where pure _ = Proxy {-# INLINE pure #-} _ <*> _ = Proxy {-# INLINE (<*>) #-} instance Monad Proxy where return _ = Proxy {-# INLINE return #-} _ >>= _ = Proxy {-# INLINE (>>=) #-} -- | 'asProxyTypeOf' is a type-restricted version of 'const'. -- It is usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the tag -- of the second. asProxyTypeOf :: a -> Proxy a -> a asProxyTypeOf = const {-# INLINE asProxyTypeOf #-}
jstolarek/ghc
libraries/base/Data/Proxy.hs
bsd-3-clause
2,747
0
12
722
587
323
264
61
1
{-# LANGUAGE BangPatterns, CPP, DefaultSignatures, FlexibleContexts, FlexibleInstances, KindSignatures, MultiParamTypeClasses, OverlappingInstances, OverloadedStrings, Rank2Types, ScopedTypeVariables, TypeOperators, UndecidableInstances #-} module Data.Csv.Conversion ( -- * Type conversion Only(..) , FromRecord(..) , FromNamedRecord(..) , ToNamedRecord(..) , DefaultOrdered(..) , FromField(..) , ToRecord(..) , ToField(..) -- * Parser , Parser , runParser -- * Accessors , index , (.!) , unsafeIndex , lookup , (.:) , namedField , (.=) , record , namedRecord , header ) where import Control.Applicative (Alternative, (<|>), empty) import Control.Monad (MonadPlus, mplus, mzero) import Data.Attoparsec.ByteString.Char8 (double) import qualified Data.Attoparsec.ByteString.Char8 as A8 import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import Data.Hashable (Hashable) import qualified Data.HashMap.Lazy as HM import Data.Int (Int8, Int16, Int32, Int64) import qualified Data.IntMap as IM import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LT import Data.Vector (Vector, (!)) import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import Data.Word (Word8, Word16, Word32, Word64) import GHC.Float (double2Float) import GHC.Generics import Prelude hiding (lookup, takeWhile) import Data.Csv.Conversion.Internal import Data.Csv.Types #if !MIN_VERSION_base(4,8,0) import Control.Applicative (Applicative, (<$>), (<*>), (<*), (*>), pure) import Data.Monoid (Monoid, mappend, mempty) import Data.Traversable (traverse) import Data.Word (Word) #endif ------------------------------------------------------------------------ -- bytestring compatibility toStrict :: L.ByteString -> B.ByteString fromStrict :: B.ByteString -> L.ByteString #if MIN_VERSION_bytestring(0,10,0) toStrict = L.toStrict fromStrict = L.fromStrict #else toStrict = B.concat . L.toChunks fromStrict = L.fromChunks . (:[]) #endif {-# INLINE toStrict #-} {-# INLINE fromStrict #-} ------------------------------------------------------------------------ -- Type conversion ------------------------------------------------------------------------ -- Index-based conversion -- | A type that can be converted from a single CSV record, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Record' has the wrong number of -- columns. -- -- Given this example data: -- -- > John,56 -- > Jane,55 -- -- here's an example type and instance: -- -- > data Person = Person { name :: !Text, age :: !Int } -- > -- > instance FromRecord Person where -- > parseRecord v -- > | length v == 2 = Person <$> -- > v .! 0 <*> -- > v .! 1 -- > | otherwise = mzero class FromRecord a where parseRecord :: Record -> Parser a default parseRecord :: (Generic a, GFromRecord (Rep a)) => Record -> Parser a parseRecord r = to <$> gparseRecord r -- | Haskell lacks a single-element tuple type, so if you CSV data -- with just one column you can use the 'Only' type to represent a -- single-column result. newtype Only a = Only { fromOnly :: a } deriving (Eq, Ord, Read, Show) -- | A type that can be converted to a single CSV record. -- -- An example type and instance: -- -- > data Person = Person { name :: !Text, age :: !Int } -- > -- > instance ToRecord Person where -- > toRecord (Person name age) = record [ -- > toField name, toField age] -- -- Outputs data on this form: -- -- > John,56 -- > Jane,55 class ToRecord a where -- | Convert a value to a record. toRecord :: a -> Record default toRecord :: (Generic a, GToRecord (Rep a) Field) => a -> Record toRecord = V.fromList . gtoRecord . from instance FromField a => FromRecord (Only a) where parseRecord v | n == 1 = Only <$> unsafeIndex v 0 | otherwise = lengthMismatch 1 v where n = V.length v -- TODO: Check if we want all toRecord conversions to be stricter. instance ToField a => ToRecord (Only a) where toRecord = V.singleton . toField . fromOnly instance (FromField a, FromField b) => FromRecord (a, b) where parseRecord v | n == 2 = (,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 | otherwise = lengthMismatch 2 v where n = V.length v instance (ToField a, ToField b) => ToRecord (a, b) where toRecord (a, b) = V.fromList [toField a, toField b] instance (FromField a, FromField b, FromField c) => FromRecord (a, b, c) where parseRecord v | n == 3 = (,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 | otherwise = lengthMismatch 3 v where n = V.length v instance (ToField a, ToField b, ToField c) => ToRecord (a, b, c) where toRecord (a, b, c) = V.fromList [toField a, toField b, toField c] instance (FromField a, FromField b, FromField c, FromField d) => FromRecord (a, b, c, d) where parseRecord v | n == 4 = (,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 | otherwise = lengthMismatch 4 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d) => ToRecord (a, b, c, d) where toRecord (a, b, c, d) = V.fromList [ toField a, toField b, toField c, toField d] instance (FromField a, FromField b, FromField c, FromField d, FromField e) => FromRecord (a, b, c, d, e) where parseRecord v | n == 5 = (,,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 <*> unsafeIndex v 4 | otherwise = lengthMismatch 5 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e) => ToRecord (a, b, c, d, e) where toRecord (a, b, c, d, e) = V.fromList [ toField a, toField b, toField c, toField d, toField e] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f) => FromRecord (a, b, c, d, e, f) where parseRecord v | n == 6 = (,,,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 <*> unsafeIndex v 4 <*> unsafeIndex v 5 | otherwise = lengthMismatch 6 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f) => ToRecord (a, b, c, d, e, f) where toRecord (a, b, c, d, e, f) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g) => FromRecord (a, b, c, d, e, f, g) where parseRecord v | n == 7 = (,,,,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 <*> unsafeIndex v 4 <*> unsafeIndex v 5 <*> unsafeIndex v 6 | otherwise = lengthMismatch 7 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g) => ToRecord (a, b, c, d, e, f, g) where toRecord (a, b, c, d, e, f, g) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f, toField g] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h) => FromRecord (a, b, c, d, e, f, g, h) where parseRecord v | n == 8 = (,,,,,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 <*> unsafeIndex v 4 <*> unsafeIndex v 5 <*> unsafeIndex v 6 <*> unsafeIndex v 7 | otherwise = lengthMismatch 8 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g, ToField h) => ToRecord (a, b, c, d, e, f, g, h) where toRecord (a, b, c, d, e, f, g, h) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f, toField g, toField h] instance (FromField a, FromField b, FromField c, FromField d, FromField e, FromField f, FromField g, FromField h, FromField i) => FromRecord (a, b, c, d, e, f, g, h, i) where parseRecord v | n == 9 = (,,,,,,,,) <$> unsafeIndex v 0 <*> unsafeIndex v 1 <*> unsafeIndex v 2 <*> unsafeIndex v 3 <*> unsafeIndex v 4 <*> unsafeIndex v 5 <*> unsafeIndex v 6 <*> unsafeIndex v 7 <*> unsafeIndex v 8 | otherwise = lengthMismatch 9 v where n = V.length v instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f, ToField g, ToField h, ToField i) => ToRecord (a, b, c, d, e, f, g, h, i) where toRecord (a, b, c, d, e, f, g, h, i) = V.fromList [ toField a, toField b, toField c, toField d, toField e, toField f, toField g, toField h, toField i] lengthMismatch :: Int -> Record -> Parser a lengthMismatch expected v = fail $ "cannot unpack array of length " ++ show n ++ " into a " ++ desired ++ ". Input record: " ++ show v where n = V.length v desired | expected == 1 = "Only" | expected == 2 = "pair" | otherwise = show expected ++ "-tuple" instance FromField a => FromRecord [a] where parseRecord = traverse parseField . V.toList instance ToField a => ToRecord [a] where toRecord = V.fromList . map toField instance FromField a => FromRecord (V.Vector a) where parseRecord = traverse parseField instance ToField a => ToRecord (Vector a) where toRecord = V.map toField instance (FromField a, U.Unbox a) => FromRecord (U.Vector a) where parseRecord = fmap U.convert . traverse parseField instance (ToField a, U.Unbox a) => ToRecord (U.Vector a) where toRecord = V.map toField . U.convert ------------------------------------------------------------------------ -- Name-based conversion -- | A type that can be converted from a single CSV record, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Record' has the wrong number of -- columns. -- -- Given this example data: -- -- > name,age -- > John,56 -- > Jane,55 -- -- here's an example type and instance: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > data Person = Person { name :: !Text, age :: !Int } -- > -- > instance FromNamedRecord Person where -- > parseNamedRecord m = Person <$> -- > m .: "name" <*> -- > m .: "age" -- -- Note the use of the @OverloadedStrings@ language extension which -- enables 'B8.ByteString' values to be written as string literals. class FromNamedRecord a where parseNamedRecord :: NamedRecord -> Parser a default parseNamedRecord :: (Generic a, GFromNamedRecord (Rep a)) => NamedRecord -> Parser a parseNamedRecord r = to <$> gparseNamedRecord r -- | A type that can be converted to a single CSV record. -- -- An example type and instance: -- -- > data Person = Person { name :: !Text, age :: !Int } -- > -- > instance ToNamedRecord Person where -- > toNamedRecord (Person name age) = namedRecord [ -- > "name" .= name, "age" .= age] class ToNamedRecord a where -- | Convert a value to a named record. toNamedRecord :: a -> NamedRecord default toNamedRecord :: (Generic a, GToRecord (Rep a) (B.ByteString, B.ByteString)) => a -> NamedRecord toNamedRecord = namedRecord . gtoRecord . from -- | A type that has a default field order when converted to CSV. This -- class lets you specify how to get the headers to use for a record -- type that's an instance of 'ToNamedRecord'. -- -- To derive an instance, the type is required to only have one -- constructor and that constructor must have named fields (also known -- as selectors) for all fields. -- -- Right: @data Foo = Foo { foo :: !Int }@ -- -- Wrong: @data Bar = Bar Int@ -- -- If you try to derive an instance using GHC generics and your type -- doesn't have named fields, you will get an error along the lines -- of: -- -- > <interactive>:9:10: -- > No instance for (DefaultOrdered (M1 S NoSelector (K1 R Char) ())) -- > arising from a use of ‘Data.Csv.Conversion.$gdmheader’ -- > In the expression: Data.Csv.Conversion.$gdmheader -- > In an equation for ‘header’: -- > header = Data.Csv.Conversion.$gdmheader -- > In the instance declaration for ‘DefaultOrdered Foo’ -- class DefaultOrdered a where -- | The header order for this record. Should include the names -- used in the 'NamedRecord' returned by 'toNamedRecord'. Pass -- 'undefined' as the argument, together with a type annotation -- e.g. @'headerOrder' ('undefined' :: MyRecord)@. headerOrder :: a -> Header -- TODO: Add Generic implementation default headerOrder :: (Generic a, GToNamedRecordHeader (Rep a)) => a -> Header headerOrder = V.fromList. gtoNamedRecordHeader . from instance (FromField a, FromField b, Ord a) => FromNamedRecord (M.Map a b) where parseNamedRecord m = M.fromList <$> (traverse parseBoth $ HM.toList m) instance (ToField a, ToField b, Ord a) => ToNamedRecord (M.Map a b) where toNamedRecord = HM.fromList . map (\ (k, v) -> (toField k, toField v)) . M.toList instance (Eq a, FromField a, FromField b, Hashable a) => FromNamedRecord (HM.HashMap a b) where parseNamedRecord m = HM.fromList <$> (traverse parseBoth $ HM.toList m) instance (Eq a, ToField a, ToField b, Hashable a) => ToNamedRecord (HM.HashMap a b) where toNamedRecord = HM.fromList . map (\ (k, v) -> (toField k, toField v)) . HM.toList parseBoth :: (FromField a, FromField b) => (Field, Field) -> Parser (a, b) parseBoth (k, v) = (,) <$> parseField k <*> parseField v ------------------------------------------------------------------------ -- Individual field conversion -- | A type that can be converted from a single CSV field, with the -- possibility of failure. -- -- When writing an instance, use 'empty', 'mzero', or 'fail' to make a -- conversion fail, e.g. if a 'Field' can't be converted to the given -- type. -- -- Example type and instance: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > data Color = Red | Green | Blue -- > -- > instance FromField Color where -- > parseField s -- > | s == "R" = pure Red -- > | s == "G" = pure Green -- > | s == "B" = pure Blue -- > | otherwise = mzero class FromField a where parseField :: Field -> Parser a -- | A type that can be converted to a single CSV field. -- -- Example type and instance: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > data Color = Red | Green | Blue -- > -- > instance ToField Color where -- > toField Red = "R" -- > toField Green = "G" -- > toField Blue = "B" class ToField a where toField :: a -> Field -- | 'Nothing' if the 'Field' is 'B.empty', 'Just' otherwise. instance FromField a => FromField (Maybe a) where parseField s | B.null s = pure Nothing | otherwise = Just <$> parseField s {-# INLINE parseField #-} -- | 'Nothing' is encoded as an 'B.empty' field. instance ToField a => ToField (Maybe a) where toField = maybe B.empty toField {-# INLINE toField #-} -- | @'Left' field@ if conversion failed, 'Right' otherwise. instance FromField a => FromField (Either Field a) where parseField s = case runParser (parseField s) of Left _ -> pure $ Left s Right a -> pure $ Right a {-# INLINE parseField #-} -- | Ignores the 'Field'. Always succeeds. instance FromField () where parseField _ = pure () {-# INLINE parseField #-} -- | Assumes UTF-8 encoding. instance FromField Char where parseField s = case T.decodeUtf8' s of Left e -> fail $ show e Right t | T.compareLength t 1 == EQ -> pure (T.head t) | otherwise -> typeError "Char" s Nothing {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField Char where toField = toField . T.encodeUtf8 . T.singleton {-# INLINE toField #-} -- | Accepts same syntax as 'rational'. Ignores whitespace. instance FromField Double where parseField = parseDouble {-# INLINE parseField #-} -- | Uses decimal notation or scientific notation, depending on the -- number. instance ToField Double where toField = realFloat {-# INLINE toField #-} -- | Accepts same syntax as 'rational'. Ignores whitespace. instance FromField Float where parseField s = double2Float <$> parseDouble s {-# INLINE parseField #-} -- | Uses decimal notation or scientific notation, depending on the -- number. instance ToField Float where toField = realFloat {-# INLINE toField #-} parseDouble :: B.ByteString -> Parser Double parseDouble s = case parseOnly (ws *> double <* ws) s of Left err -> typeError "Double" s (Just err) Right n -> pure n {-# INLINE parseDouble #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Int where parseField = parseSigned "Int" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Int where toField = decimal {-# INLINE toField #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Integer where parseField = parseSigned "Integer" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Integer where toField = decimal {-# INLINE toField #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Int8 where parseField = parseSigned "Int8" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Int8 where toField = decimal {-# INLINE toField #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Int16 where parseField = parseSigned "Int16" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Int16 where toField = decimal {-# INLINE toField #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Int32 where parseField = parseSigned "Int32" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Int32 where toField = decimal {-# INLINE toField #-} -- | Accepts a signed decimal number. Ignores whitespace. instance FromField Int64 where parseField = parseSigned "Int64" {-# INLINE parseField #-} -- | Uses decimal encoding with optional sign. instance ToField Int64 where toField = decimal {-# INLINE toField #-} -- | Accepts an unsigned decimal number. Ignores whitespace. instance FromField Word where parseField = parseUnsigned "Word" {-# INLINE parseField #-} -- | Uses decimal encoding. instance ToField Word where toField = decimal {-# INLINE toField #-} -- | Accepts an unsigned decimal number. Ignores whitespace. instance FromField Word8 where parseField = parseUnsigned "Word8" {-# INLINE parseField #-} -- | Uses decimal encoding. instance ToField Word8 where toField = decimal {-# INLINE toField #-} -- | Accepts an unsigned decimal number. Ignores whitespace. instance FromField Word16 where parseField = parseUnsigned "Word16" {-# INLINE parseField #-} -- | Uses decimal encoding. instance ToField Word16 where toField = decimal {-# INLINE toField #-} -- | Accepts an unsigned decimal number. Ignores whitespace. instance FromField Word32 where parseField = parseUnsigned "Word32" {-# INLINE parseField #-} -- | Uses decimal encoding. instance ToField Word32 where toField = decimal {-# INLINE toField #-} -- | Accepts an unsigned decimal number. Ignores whitespace. instance FromField Word64 where parseField = parseUnsigned "Word64" {-# INLINE parseField #-} -- | Uses decimal encoding. instance ToField Word64 where toField = decimal {-# INLINE toField #-} instance FromField B.ByteString where parseField = pure {-# INLINE parseField #-} instance ToField B.ByteString where toField = id {-# INLINE toField #-} instance FromField L.ByteString where parseField = pure . fromStrict {-# INLINE parseField #-} instance ToField L.ByteString where toField = toStrict {-# INLINE toField #-} -- | Assumes UTF-8 encoding. Fails on invalid byte sequences. instance FromField T.Text where parseField = either (fail . show) pure . T.decodeUtf8' {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField T.Text where toField = toField . T.encodeUtf8 {-# INLINE toField #-} -- | Assumes UTF-8 encoding. Fails on invalid byte sequences. instance FromField LT.Text where parseField = either (fail . show) (pure . LT.fromStrict) . T.decodeUtf8' {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField LT.Text where toField = toField . toStrict . LT.encodeUtf8 {-# INLINE toField #-} -- | Assumes UTF-8 encoding. Fails on invalid byte sequences. instance FromField [Char] where parseField = fmap T.unpack . parseField {-# INLINE parseField #-} -- | Uses UTF-8 encoding. instance ToField [Char] where toField = toField . T.pack {-# INLINE toField #-} parseSigned :: (Integral a, Num a) => String -> B.ByteString -> Parser a parseSigned typ s = case parseOnly (ws *> A8.signed A8.decimal <* ws) s of Left err -> typeError typ s (Just err) Right n -> pure n {-# INLINE parseSigned #-} parseUnsigned :: Integral a => String -> B.ByteString -> Parser a parseUnsigned typ s = case parseOnly (ws *> A8.decimal <* ws) s of Left err -> typeError typ s (Just err) Right n -> pure n {-# INLINE parseUnsigned #-} ws :: A8.Parser () ws = A8.skipWhile (\c -> c == ' ' || c == '\t') ------------------------------------------------------------------------ -- Custom version of attoparsec @parseOnly@ function which fails if -- there is leftover content after parsing a field. parseOnly :: A8.Parser a -> B.ByteString -> Either String a parseOnly parser input = go (A8.parse parser input) where go (A8.Fail _ _ err) = Left err go (A8.Partial f) = go2 (f B.empty) go (A8.Done leftover result) | B.null leftover = Right result | otherwise = Left ("incomplete field parse, leftover: " ++ show (B.unpack leftover)) go2 (A8.Fail _ _ err) = Left err go2 (A8.Partial _) = error "parseOnly: impossible error!" go2 (A8.Done leftover result) | B.null leftover = Right result | otherwise = Left ("incomplete field parse, leftover: " ++ show (B.unpack leftover)) {-# INLINE parseOnly #-} typeError :: String -> B.ByteString -> Maybe String -> Parser a typeError typ s mmsg = fail $ "expected " ++ typ ++ ", got " ++ show (B8.unpack s) ++ cause where cause = case mmsg of Just msg -> " (" ++ msg ++ ")" Nothing -> "" ------------------------------------------------------------------------ -- Constructors and accessors -- | Retrieve the /n/th field in the given record. The result is -- 'empty' if the value cannot be converted to the desired type. -- Raises an exception if the index is out of bounds. -- -- 'index' is a simple convenience function that is equivalent to -- @'parseField' (v '!' idx)@. If you're certain that the index is not -- out of bounds, using 'unsafeIndex' is somewhat faster. index :: FromField a => Record -> Int -> Parser a index v idx = parseField (v ! idx) {-# INLINE index #-} -- | Alias for 'index'. (.!) :: FromField a => Record -> Int -> Parser a (.!) = index {-# INLINE (.!) #-} infixl 9 .! -- | Like 'index' but without bounds checking. unsafeIndex :: FromField a => Record -> Int -> Parser a unsafeIndex v idx = parseField (V.unsafeIndex v idx) {-# INLINE unsafeIndex #-} -- | Retrieve a field in the given record by name. The result is -- 'empty' if the field is missing or if the value cannot be converted -- to the desired type. lookup :: FromField a => NamedRecord -> B.ByteString -> Parser a lookup m name = maybe (fail err) parseField $ HM.lookup name m where err = "no field named " ++ show (B8.unpack name) {-# INLINE lookup #-} -- | Alias for 'lookup'. (.:) :: FromField a => NamedRecord -> B.ByteString -> Parser a (.:) = lookup {-# INLINE (.:) #-} -- | Construct a pair from a name and a value. For use with -- 'namedRecord'. namedField :: ToField a => B.ByteString -> a -> (B.ByteString, B.ByteString) namedField name val = (name, toField val) {-# INLINE namedField #-} -- | Alias for 'namedField'. (.=) :: ToField a => B.ByteString -> a -> (B.ByteString, B.ByteString) (.=) = namedField {-# INLINE (.=) #-} -- | Construct a record from a list of 'B.ByteString's. Use 'toField' -- to convert values to 'B.ByteString's for use with 'record'. record :: [B.ByteString] -> Record record = V.fromList -- | Construct a named record from a list of name-value 'B.ByteString' -- pairs. Use '.=' to construct such a pair from a name and a value. namedRecord :: [(B.ByteString, B.ByteString)] -> NamedRecord namedRecord = HM.fromList -- | Construct a header from a list of 'B.ByteString's. header :: [B.ByteString] -> Header header = V.fromList ------------------------------------------------------------------------ -- Parser for converting records to data types -- | Failure continuation. type Failure f r = String -> f r -- | Success continuation. type Success a f r = a -> f r -- | Conversion of a field to a value might fail e.g. if the field is -- malformed. This possibility is captured by the 'Parser' type, which -- lets you compose several field conversions together in such a way -- that if any of them fail, the whole record conversion fails. newtype Parser a = Parser { unParser :: forall f r. Failure f r -> Success a f r -> f r } instance Monad Parser where m >>= g = Parser $ \kf ks -> let ks' a = unParser (g a) kf ks in unParser m kf ks' {-# INLINE (>>=) #-} return a = Parser $ \_kf ks -> ks a {-# INLINE return #-} fail msg = Parser $ \kf _ks -> kf msg {-# INLINE fail #-} instance Functor Parser where fmap f m = Parser $ \kf ks -> let ks' a = ks (f a) in unParser m kf ks' {-# INLINE fmap #-} instance Applicative Parser where pure = return {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} instance Alternative Parser where empty = fail "empty" {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance MonadPlus Parser where mzero = fail "mzero" {-# INLINE mzero #-} mplus a b = Parser $ \kf ks -> let kf' _ = unParser b kf ks in unParser a kf' ks {-# INLINE mplus #-} instance Monoid (Parser a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} apP :: Parser (a -> b) -> Parser a -> Parser b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} -- | Run a 'Parser', returning either @'Left' errMsg@ or @'Right' -- result@. Forces the value in the 'Left' or 'Right' constructors to -- weak head normal form. -- -- You most likely won't need to use this function directly, but it's -- included for completeness. runParser :: Parser a -> Either String a runParser p = unParser p left right where left !errMsg = Left errMsg right !x = Right x {-# INLINE runParser #-} ------------------------------------------------------------------------ -- Generics class GFromRecord f where gparseRecord :: Record -> Parser (f p) instance GFromRecordSum f Record => GFromRecord (M1 i n f) where gparseRecord v = case (IM.lookup n gparseRecordSum) of Nothing -> lengthMismatch n v Just p -> M1 <$> p v where n = V.length v class GFromNamedRecord f where gparseNamedRecord :: NamedRecord -> Parser (f p) instance GFromRecordSum f NamedRecord => GFromNamedRecord (M1 i n f) where gparseNamedRecord v = foldr (\f p -> p <|> M1 <$> f v) empty (IM.elems gparseRecordSum) class GFromRecordSum f r where gparseRecordSum :: IM.IntMap (r -> Parser (f p)) instance (GFromRecordSum a r, GFromRecordSum b r) => GFromRecordSum (a :+: b) r where gparseRecordSum = IM.unionWith (\a b r -> a r <|> b r) (fmap (L1 <$>) <$> gparseRecordSum) (fmap (R1 <$>) <$> gparseRecordSum) instance GFromRecordProd f r => GFromRecordSum (M1 i n f) r where gparseRecordSum = IM.singleton n (fmap (M1 <$>) f) where (n, f) = gparseRecordProd 0 class GFromRecordProd f r where gparseRecordProd :: Int -> (Int, r -> Parser (f p)) instance GFromRecordProd U1 r where gparseRecordProd n = (n, const (pure U1)) instance (GFromRecordProd a r, GFromRecordProd b r) => GFromRecordProd (a :*: b) r where gparseRecordProd n0 = (n2, f) where f r = (:*:) <$> fa r <*> fb r (n1, fa) = gparseRecordProd n0 (n2, fb) = gparseRecordProd n1 instance GFromRecordProd f Record => GFromRecordProd (M1 i n f) Record where gparseRecordProd n = fmap (M1 <$>) <$> gparseRecordProd n instance FromField a => GFromRecordProd (K1 i a) Record where gparseRecordProd n = (n + 1, \v -> K1 <$> parseField (V.unsafeIndex v n)) data Proxy s (f :: * -> *) a = Proxy instance (FromField a, Selector s) => GFromRecordProd (M1 S s (K1 i a)) NamedRecord where gparseRecordProd n = (n + 1, \v -> (M1 . K1) <$> v .: name) where name = T.encodeUtf8 (T.pack (selName (Proxy :: Proxy s f a))) class GToRecord a f where gtoRecord :: a p -> [f] instance GToRecord U1 f where gtoRecord U1 = [] instance (GToRecord a f, GToRecord b f) => GToRecord (a :*: b) f where gtoRecord (a :*: b) = gtoRecord a ++ gtoRecord b instance (GToRecord a f, GToRecord b f) => GToRecord (a :+: b) f where gtoRecord (L1 a) = gtoRecord a gtoRecord (R1 b) = gtoRecord b instance GToRecord a f => GToRecord (M1 D c a) f where gtoRecord (M1 a) = gtoRecord a instance GToRecord a f => GToRecord (M1 C c a) f where gtoRecord (M1 a) = gtoRecord a instance GToRecord a Field => GToRecord (M1 S c a) Field where gtoRecord (M1 a) = gtoRecord a instance ToField a => GToRecord (K1 i a) Field where gtoRecord (K1 a) = [toField a] instance (ToField a, Selector s) => GToRecord (M1 S s (K1 i a)) (B.ByteString, B.ByteString) where gtoRecord m@(M1 (K1 a)) = [T.encodeUtf8 (T.pack (selName m)) .= toField a] -- We statically fail on sum types and product types without selectors -- (field names). class GToNamedRecordHeader a where gtoNamedRecordHeader :: a p -> [Name] instance GToNamedRecordHeader U1 where gtoNamedRecordHeader _ = [] instance (GToNamedRecordHeader a, GToNamedRecordHeader b) => GToNamedRecordHeader (a :*: b) where gtoNamedRecordHeader _ = gtoNamedRecordHeader (undefined :: a p) ++ gtoNamedRecordHeader (undefined :: b p) instance GToNamedRecordHeader a => GToNamedRecordHeader (M1 D c a) where gtoNamedRecordHeader _ = gtoNamedRecordHeader (undefined :: a p) instance GToNamedRecordHeader a => GToNamedRecordHeader (M1 C c a) where gtoNamedRecordHeader _ = gtoNamedRecordHeader (undefined :: a p) -- | Instance to ensure that you cannot derive DefaultOrdered for -- constructors without selectors. instance DefaultOrdered (M1 S NoSelector a ()) => GToNamedRecordHeader (M1 S NoSelector a) where gtoNamedRecordHeader _ = error "You cannot derive DefaultOrdered for constructors without selectors." instance Selector s => GToNamedRecordHeader (M1 S s a) where gtoNamedRecordHeader m | null name = error "Cannot derive DefaultOrdered for constructors without selectors" | otherwise = [B8.pack (selName m)] where name = selName m
ahodgen/cassava
Data/Csv/Conversion.hs
bsd-3-clause
33,622
0
16
8,917
8,464
4,536
3,928
595
5
{------------------------------------------------------------------------------- Computes BOW similarity scores over a list of word pairs (c) 2013 Jan Snajder <[email protected]> -------------------------------------------------------------------------------} import qualified DSem.VectorSpace.Bow as Bow import qualified DSem.Vector as V import qualified Data.Text as T import Text.Printf import Control.Applicative import Control.Monad import Control.Monad.Trans import System.IO import System.Environment import System.Exit import Data.Maybe import Data.Word (Word64) -- retains only the POS (first character after '_') parseWord :: String -> String parseWord w = case break (=='_') w of (l,_:p:_) -> l ++ "_" ++ [p] (l,_) -> l similarity :: String -> String -> Bow.ModelM (Double,Double,Double,Word64) similarity w1 w2 = do v1 <- Bow.getVector $ T.pack w1 v2 <- Bow.getVector $ T.pack w2 return $ case (v1,v2) of (Just v1,Just v2) -> (max 0 . min 1 $ V.cosine v1 v2, V.norm2 v1, V.norm2 v2, V.dimShared v1 v2) _ -> (-1,-1,-1,-1) main = do args <- getArgs when (length args < 2) $ do putStrLn "Usage: bow-pairs-sim2 <bow matrix> <list of word pairs>" exitFailure m <- Bow.readMatrix (args!!0) ps <- map (parse . reverse . words) . lines <$> readFile (args!!1) putStrLn "w_1\tw_2\tcosine\tnorm(w_1)\tnorm(w_2)\tdim_shared" Bow.runModelIO m $ do -- Bow.setCacheSize 100 forM_ ps $ \(w1,w2) -> do (s,n1,n2,d) <- similarity w1 w2 liftIO . putStrLn $ printf "%s\t%s\t%.3f\t%.3f\t%.3f\t%d" w1 w2 s n1 n2 d where parse (w2:w1:_) = (parseWord w1,parseWord w2) parse _ = error "no parse"
jsnajder/dsem
src/bow-pairs-sim2.hs
bsd-3-clause
1,688
0
15
326
572
299
273
39
2
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS -fno-warn-orphans #-} -- | -- Module : Text.RegExp -- Copyright : Thomas Wilke, Frank Huch, and Sebastian Fischer -- License : BSD3 -- Maintainer : Sebastian Fischer <mailto:[email protected]> -- Stability : experimental -- -- This library provides a simple and fast regular expression matcher -- that is implemented in Haskell without binding to external -- libraries. -- -- There are different ways to implement regular expression -- matching. Backtracking algorithms are simple but need bookkeeping -- overhead for nondeterministic search. One can use deterministic -- finite automata (DFA, see -- <http://swtch.com/~rsc/regexp/regexp1.html>) to match regular -- expressions faster. But for certain regular expressions these DFA -- are exponentially large which sometimes leads to prohibitive memory -- requirements. -- -- We use a smart and simple algorithm to generate a DFA from a -- regular expression and do not generate the DFA completely but on -- the fly while parsing. This leads to a linear-time deterministic -- algorithm with constant space requirements. More specifically, the -- run time is limited by the product of the sizes of the regular -- expression and the string and the memory is limited by the size of -- the regular expression. -- module Text.RegExp ( module Data.Semiring, Weight(..), -- * Constructing regular expressions RegExp, fromString, eps, char, sym, psym, anySym, noMatch, alt, seq_, rep, rep1, opt, brep, perm, -- * Matching (=~), acceptFull, acceptPartial, matchingCount, fullMatch, partialMatch ) where import Data.Semiring import qualified Data.String import Text.RegExp.Data import Text.RegExp.Parser import Text.RegExp.Matching -- | -- Parses a regular expression from its string representation. If the -- 'OverloadedStrings' language extension is enabled, string literals -- can be used as regular expressions without using 'fromString' -- explicitly. Implicit conversion is especially useful in combination -- with functions like '=~' that take a value of type @RegExp Char@ as -- argument. -- -- Here are some examples of supported regular expressions along with -- an explanation what they mean: -- -- * @a@ matches the character @a@ -- -- * @[abc]@ matches any of the characters @a@, @b@, or @c@. It is -- equivalent to @(a|b|c)@, but @|@ can be used to specify -- alternatives between arbitrary regular expressions, not only -- characters. -- -- * @[^abc]@ matches anything but the characters @a@, @b@, or @c@. -- -- * @\\d@ matches a digit and is equivalent to @[0-9]@. Moreover, -- @\\D@ matches any non-digit character, @\\s@ and @\\S@ match -- space and non-space characters and @\\w@ and @\\W@ match word -- characters and non-word characters, that is, @\\w@ abbreviates -- @[a-zA-Z_]@. -- -- * @a?@ matches the empty word or the character @a@, @a*@ matches -- zero or more occurrences of @a@, and @a+@ matches one or more -- @a@'s. -- -- * @.@ (the dot) matches one arbitrary character. -- -- * @a{4,7}@ matches four to seven occurrences of @a@, @a{2}@ -- matches two. -- fromString :: String -> RegExp Char fromString = Data.String.fromString instance Data.String.IsString (RegExp Char) where fromString = parse -- | -- Matches a sequence of the given regular expressions in any -- order. For example, the regular expression -- -- @ -- perm (map char \"abc\") -- @ -- -- has the same meaning as -- -- @ -- abc|acb|bca|bac|cba|cab -- @ -- -- and is represented as -- -- @ -- a(bc|cb)|b(ca|ac)|c(ba|ab) -- @ -- perm :: [RegExp c] -> RegExp c perm [] = eps perm [r] = r perm rs = go rs [] where go [p] qs = p `seq_` perm qs go (p:ps) qs = (p `seq_` perm (ps ++ qs)) `alt` go ps (p:qs) -- | -- Alias for 'acceptFull' specialized for Strings. Useful in combination -- with the 'IsString' instance for 'RegExp' 'Char' -- (=~) :: RegExp Char -> String -> Bool (=~) = acceptFull
sebfisch/haskell-regexp
src/Text/RegExp.hs
bsd-3-clause
4,001
0
12
748
405
276
129
25
2
-- | PDF objects. module Graphics.PDF.Types ( -- * Object types ObjectID(..) , Number(..) , Array , Dict , Object(..) -- * Constructors , array , dict ) where import qualified Data.ByteString as B import Data.Fixed import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as H import Data.Vector (Vector) import qualified Data.Vector as V -- | A PDF object. data Object = Null | Bool !Bool | Number !Number | String !B.ByteString | Name !B.ByteString | Array !Array | Dict !Dict | Reference !ObjectID | Indirect !ObjectID !Object deriving (Eq, Show) -- | A PDF number object. data Number = I !Int | F !(Fixed E6) deriving (Eq, Show) -- | An object identifier, consisting of an object number and a generation -- number. data ObjectID = ObjectID !Int !Int deriving (Eq, Ord, Show) -- | A PDF array object. type Array = Vector Object -- | A PDF dictionary object. type Dict = HashMap B.ByteString Object -- | Construct an 'Object' from a list of values. array :: [Object] -> Object array = Array . V.fromList -- | Create an 'Object' from a list of name-value pairs. dict :: [(B.ByteString, Object)] -> Object dict = Dict . H.fromList
knrafto/pdfkit
Graphics/PDF/Types.hs
bsd-3-clause
1,302
0
9
351
314
186
128
63
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexProgram -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/vertex_program.txt ARB_vertex_program> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.VertexProgram ( -- * Enums gl_COLOR_SUM_ARB, gl_CURRENT_MATRIX_ARB, gl_CURRENT_MATRIX_STACK_DEPTH_ARB, gl_CURRENT_VERTEX_ATTRIB_ARB, gl_MATRIX0_ARB, gl_MATRIX10_ARB, gl_MATRIX11_ARB, gl_MATRIX12_ARB, gl_MATRIX13_ARB, gl_MATRIX14_ARB, gl_MATRIX15_ARB, gl_MATRIX16_ARB, gl_MATRIX17_ARB, gl_MATRIX18_ARB, gl_MATRIX19_ARB, gl_MATRIX1_ARB, gl_MATRIX20_ARB, gl_MATRIX21_ARB, gl_MATRIX22_ARB, gl_MATRIX23_ARB, gl_MATRIX24_ARB, gl_MATRIX25_ARB, gl_MATRIX26_ARB, gl_MATRIX27_ARB, gl_MATRIX28_ARB, gl_MATRIX29_ARB, gl_MATRIX2_ARB, gl_MATRIX30_ARB, gl_MATRIX31_ARB, gl_MATRIX3_ARB, gl_MATRIX4_ARB, gl_MATRIX5_ARB, gl_MATRIX6_ARB, gl_MATRIX7_ARB, gl_MATRIX8_ARB, gl_MATRIX9_ARB, gl_MAX_PROGRAM_ADDRESS_REGISTERS_ARB, gl_MAX_PROGRAM_ATTRIBS_ARB, gl_MAX_PROGRAM_ENV_PARAMETERS_ARB, gl_MAX_PROGRAM_INSTRUCTIONS_ARB, gl_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, gl_MAX_PROGRAM_MATRICES_ARB, gl_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB, gl_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB, gl_MAX_PROGRAM_NATIVE_ATTRIBS_ARB, gl_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, gl_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, gl_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, gl_MAX_PROGRAM_PARAMETERS_ARB, gl_MAX_PROGRAM_TEMPORARIES_ARB, gl_MAX_VERTEX_ATTRIBS_ARB, gl_PROGRAM_ADDRESS_REGISTERS_ARB, gl_PROGRAM_ATTRIBS_ARB, gl_PROGRAM_BINDING_ARB, gl_PROGRAM_ERROR_POSITION_ARB, gl_PROGRAM_ERROR_STRING_ARB, gl_PROGRAM_FORMAT_ARB, gl_PROGRAM_FORMAT_ASCII_ARB, gl_PROGRAM_INSTRUCTIONS_ARB, gl_PROGRAM_LENGTH_ARB, gl_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB, gl_PROGRAM_NATIVE_ATTRIBS_ARB, gl_PROGRAM_NATIVE_INSTRUCTIONS_ARB, gl_PROGRAM_NATIVE_PARAMETERS_ARB, gl_PROGRAM_NATIVE_TEMPORARIES_ARB, gl_PROGRAM_PARAMETERS_ARB, gl_PROGRAM_STRING_ARB, gl_PROGRAM_TEMPORARIES_ARB, gl_PROGRAM_UNDER_NATIVE_LIMITS_ARB, gl_TRANSPOSE_CURRENT_MATRIX_ARB, gl_VERTEX_ATTRIB_ARRAY_ENABLED_ARB, gl_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB, gl_VERTEX_ATTRIB_ARRAY_POINTER_ARB, gl_VERTEX_ATTRIB_ARRAY_SIZE_ARB, gl_VERTEX_ATTRIB_ARRAY_STRIDE_ARB, gl_VERTEX_ATTRIB_ARRAY_TYPE_ARB, gl_VERTEX_PROGRAM_ARB, gl_VERTEX_PROGRAM_POINT_SIZE_ARB, gl_VERTEX_PROGRAM_TWO_SIDE_ARB, -- * Functions glBindProgramARB, glDeleteProgramsARB, glDisableVertexAttribArrayARB, glEnableVertexAttribArrayARB, glGenProgramsARB, glGetProgramEnvParameterdvARB, glGetProgramEnvParameterfvARB, glGetProgramLocalParameterdvARB, glGetProgramLocalParameterfvARB, glGetProgramStringARB, glGetProgramivARB, glGetVertexAttribPointervARB, glGetVertexAttribdvARB, glGetVertexAttribfvARB, glGetVertexAttribivARB, glIsProgramARB, glProgramEnvParameter4dARB, glProgramEnvParameter4dvARB, glProgramEnvParameter4fARB, glProgramEnvParameter4fvARB, glProgramLocalParameter4dARB, glProgramLocalParameter4dvARB, glProgramLocalParameter4fARB, glProgramLocalParameter4fvARB, glProgramStringARB, glVertexAttrib1dARB, glVertexAttrib1dvARB, glVertexAttrib1fARB, glVertexAttrib1fvARB, glVertexAttrib1sARB, glVertexAttrib1svARB, glVertexAttrib2dARB, glVertexAttrib2dvARB, glVertexAttrib2fARB, glVertexAttrib2fvARB, glVertexAttrib2sARB, glVertexAttrib2svARB, glVertexAttrib3dARB, glVertexAttrib3dvARB, glVertexAttrib3fARB, glVertexAttrib3fvARB, glVertexAttrib3sARB, glVertexAttrib3svARB, glVertexAttrib4NbvARB, glVertexAttrib4NivARB, glVertexAttrib4NsvARB, glVertexAttrib4NubARB, glVertexAttrib4NubvARB, glVertexAttrib4NuivARB, glVertexAttrib4NusvARB, glVertexAttrib4bvARB, glVertexAttrib4dARB, glVertexAttrib4dvARB, glVertexAttrib4fARB, glVertexAttrib4fvARB, glVertexAttrib4ivARB, glVertexAttrib4sARB, glVertexAttrib4svARB, glVertexAttrib4ubvARB, glVertexAttrib4uivARB, glVertexAttrib4usvARB, glVertexAttribPointerARB ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/VertexProgram.hs
bsd-3-clause
4,493
0
4
505
466
318
148
144
0
{-# LANGUAGE TemplateHaskell #-} module ChanLib where import Data.Char (toLower) import System.IO import Data.Maybe import Network.HTTP import Network.URI import Data.Aeson import Data.Aeson.TH import qualified Data.ByteString.Lazy.Char8 as BS data Board = Board [Page] deriving Show data Page = Page { threads :: [Thread] } deriving Show data Thread = Thread { tNo :: Int , tSticky :: Maybe Int , tClosed :: Maybe Int , tNow :: String , tName :: String , tCom :: Maybe String , tFilename :: String , tExt :: String , tW :: Int , tH :: Int , tTim :: Int , tTime :: Int , tMD5 :: String , tLast_Replies :: Maybe [Post] } deriving Show data Post = Post { pNo :: Int , pNow :: String , pName :: Maybe String , pCom :: Maybe String , pFilename :: Maybe String , pExt :: Maybe String , pW :: Maybe Int , pH :: Maybe Int , pTime :: Int , pMD5 :: Maybe String } deriving Show -- Generate JSON instances for Board and Page. $(concat <$> mapM (deriveJSON defaultOptions) [''Board, ''Page]) -- Generate JSON instances for Thread and Post using more advanced parsing rules. $(concat <$> mapM (deriveJSON defaultOptions { fieldLabelModifier = map toLower . drop 1}) [''Thread, ''Post]) {-| The 'parseBoard' function packs a given JSON String as a lazy ByteString and attempts to decode it using Aeson. Just Board on success. Nothing on parse failure. -} parseBoard :: String -> Maybe Board parseBoard s = decode $ BS.pack s {-| The 'uriToRequest' function creates a simple GET request from a given URI. -} uriToRequest :: URI -> Request String uriToRequest s = Request { rqURI = s , rqMethod = GET , rqHeaders = [] , rqBody = "" } {-| The 'strToRequest' function attempts to create a request from a url as a String. Just (Request String) on success. Nothing on failure. -} strToRequest :: String -> Maybe (Request String) strToRequest url = uriToRequest <$> parseURI url {-| The 'downloadURL' function downloads a file from a URL. (Left errorMsg) if an error occurs, (Right doc) if success. It takes one argument, of type 'String' -} downloadURL :: String -> IO (Either String String) downloadURL s = do case (strToRequest s) of Nothing -> return $ Left "URL parse error." Just req -> do resp <- simpleHTTP req case resp of Left x -> return $ Left ("Error connecting: " ++ show x) Right r -> case rspCode r of (2,_,_) -> return $ Right (rspBody r) _ -> return $ Left (show r) {-| The 'getBoard' function downloads and parses a chan board given a URL as a String. IO (Left String) on failure. IO (Right Board) on sucess. -} getBoard :: String -> IO (Either String Board) getBoard url = do rsp <- downloadURL url case rsp of (Left err) -> return $ Left err (Right r) -> case (parseBoard r) of (Just b) -> return $ Right b _ -> return $ Left "JSON parse error." getAllThreads :: Board -> [Thread] getAllThreads (Board pages) = concatMap (threads) pages
spocot/haskell-chan
src/ChanLib.hs
bsd-3-clause
3,965
0
21
1,640
816
442
374
65
4
{-# LANGUAGE RecursiveDo, ScopedTypeVariables #-} import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.Tasty.HUnit as HU import Data.Char import Control.Applicative import Text.Earley import Text.Earley.Mixfix main :: IO () main = defaultMain tests -- -putStrLn . prettyExpr 0 $ Add (Add (Var "a") (Var "b")) (Add (Var "c") (Var "d")) -- defaultMain tests tests :: TestTree tests = testGroup "Tests" [qcProps, unitTests] qcProps :: TestTree qcProps = testGroup "QuickCheck Properties" [ QC.testProperty "Expr: parse . pretty = id" $ \e -> [e] === parseExpr (prettyExpr 0 e) , QC.testProperty "Ambiguous Expr: parse . pretty ≈ id" $ \e -> e `elem` parseAmbiguousExpr (prettyExpr 0 e) , QC.testProperty "The empty parser doesn't parse anything" $ \(input :: String) -> allParses (parser (return empty :: forall r. Grammar r () (Prod r () Char ())) input) == (,) [] Report { position = 0 , expected = [] , unconsumed = input } , QC.testProperty "Many empty parsers parse very little" $ \(input :: String) -> allParses (parser (return $ many empty <* pure "blah" :: forall r. Grammar r () (Prod r () Char [()])) input) == (,) [([], 0)] Report { position = 0 , expected = [] , unconsumed = input } ] unitTests :: TestTree unitTests = testGroup "Unit Tests" [ HU.testCase "VeryAmbiguous gives the right number of results" $ length (fst $ fullParses $ parser veryAmbiguous $ replicate 8 'b') @?= 2871 , HU.testCase "VeryAmbiguous gives the correct report" $ report (parser veryAmbiguous $ replicate 3 'b') @?= Report {position = 3, expected = "s", unconsumed = ""} , HU.testCase "Inline alternatives work" $ let input = "ababbbaaabaa" in allParses (parser inlineAlts input) @?= allParses (parser nonInlineAlts input) , HU.testCase "Some reversed words" $ let input = "wordwordstop" l = length input in allParses (parser someWords input) @?= (,) [(["stop", "drow", "drow"], l)] Report { position = l , expected = [] , unconsumed = [] } , HU.testCase "Optional Nothing" $ fullParses (parser (return optional_) "b") @?= (,) [(Nothing, 'b')] Report {position = 1, expected = "", unconsumed = ""} , HU.testCase "Optional Just" $ fullParses (parser (return optional_) "ab") @?= (,) [(Just 'a', 'b')] Report {position = 2, expected = "", unconsumed = ""} , HU.testCase "Optional using rules Nothing" $ fullParses (parser optionalRule "b") @?= (,) [(Nothing, 'b')] Report {position = 1, expected = "", unconsumed = ""} , HU.testCase "Optional using rules Just" $ fullParses (parser optionalRule "ab") @?= (,) [(Just 'a', 'b')] Report {position = 2, expected = "", unconsumed = ""} , HU.testCase "Optional without continuation Nothing" $ fullParses (parser (return $ optional $ namedSymbol 'a') "") @?= (,) [Nothing] Report {position = 0, expected = "a", unconsumed = ""} , HU.testCase "Optional without continuation Just" $ fullParses (parser (return $ optional $ namedSymbol 'a') "a") @?= (,) [Just 'a'] Report {position = 1, expected = "", unconsumed = ""} , HU.testCase "Optional using rules without continuation Nothing" $ fullParses (parser (rule $ optional $ namedSymbol 'a') "") @?= (,) [Nothing] Report {position = 0, expected = "a", unconsumed = ""} , HU.testCase "Optional using rules without continuation Just" $ fullParses (parser (rule $ optional $ namedSymbol 'a') "a") @?= (,) [Just 'a'] Report {position = 1, expected = "", unconsumed = ""} , HU.testCase "Mixfix 1" $ let x = Ident [Just "x"] in fullParses (parser mixfixGrammar $ words "if x then x else x") @?= (,) [App ifthenelse [x, x, x]] Report {position = 6, expected = [], unconsumed = []} , HU.testCase "Mixfix 2" $ let x = Ident [Just "x"] in fullParses (parser mixfixGrammar $ words "prefix x postfix") @?= (,) [App prefix [App postfix [x]]] Report {position = 3, expected = [], unconsumed = []} , HU.testCase "Mixfix 3" $ let x = Ident [Just "x"] in fullParses (parser mixfixGrammar $ words "x infix1 x infix2 x") @?= (,) [App infix1 [x, App infix2 [x, x]]] Report {position = 5, expected = [], unconsumed = []} , HU.testCase "Mixfix 4" $ let x = Ident [Just "x"] in fullParses (parser mixfixGrammar $ words "[ x ]") @?= (,) [App closed [x]] Report {position = 3, expected = [], unconsumed = []} ] optional_ :: Prod r Char Char (Maybe Char, Char) optional_ = (,) <$> optional (namedSymbol 'a') <*> namedSymbol 'b' optionalRule :: Grammar r Char (Prod r Char Char (Maybe Char, Char)) optionalRule = mdo test <- rule $ (,) <$> optional (namedSymbol 'a') <*> namedSymbol 'b' return test inlineAlts :: Grammar r Char (Prod r Char Char String) inlineAlts = mdo p <- rule $ pure [] <|> (:) <$> (namedSymbol 'a' <|> namedSymbol 'b') <*> p return p nonInlineAlts :: Grammar r Char (Prod r Char Char String) nonInlineAlts = mdo ab <- rule $ namedSymbol 'a' <|> namedSymbol 'b' p <- rule $ pure [] <|> (:) <$> ab <*> p return p someWords :: Grammar r () (Prod r () Char [String]) someWords = return $ flip (:) <$> (map reverse <$> some (word "word")) <*> word "stop" veryAmbiguous :: Grammar r Char (Prod r Char Char ()) veryAmbiguous = mdo s <- rule $ () <$ symbol 'b' <|> () <$ s <* s <|> () <$ s <* s <* s <?> 's' return s parseExpr :: String -> [Expr] parseExpr input = fst (fullParses (parser expr (lexExpr input))) -- We need to annotate types for point-free version parseAmbiguousExpr :: String -> [Expr] parseAmbiguousExpr input = fst (fullParses (parser ambiguousExpr (lexExpr input))) data Expr = Add Expr Expr | Mul Expr Expr | Var String deriving (Eq, Ord, Show) instance Arbitrary Expr where arbitrary = sized arbExpr where arbIdent = Var <$> elements ["a", "b", "c", "x", "y", "z"] arbExpr n | n > 0 = oneof [ arbIdent , Add <$> arbExpr1 <*> arbExpr1 , Mul <$> arbExpr1 <*> arbExpr1 ] where arbExpr1 = arbExpr (n `div` 2) arbExpr _ = arbIdent shrink (Var _) = [] shrink (Add a b) = a : b : [ Add a' b | a' <- shrink a ] ++ [ Add a b' | b' <- shrink b ] shrink (Mul a b) = a : b : [ Mul a' b | a' <- shrink a ] ++ [ Mul a b' | b' <- shrink b ] expr :: Grammar r String (Prod r String String Expr) expr = mdo x1 <- rule $ Add <$> x1 <* namedSymbol "+" <*> x2 <|> x2 <?> "sum" x2 <- rule $ Mul <$> x2 <* namedSymbol "*" <*> x3 <|> x3 <?> "product" x3 <- rule $ Var <$> (satisfy ident <?> "identifier") <|> namedSymbol "(" *> x1 <* namedSymbol ")" return x1 where ident (x:_) = isAlpha x ident _ = False ambiguousExpr :: Grammar r String (Prod r String String Expr) ambiguousExpr = mdo x1 <- rule $ Add <$> x1 <* namedSymbol "+" <*> x1 <|> x2 <?> "sum" x2 <- rule $ Mul <$> x2 <* namedSymbol "*" <*> x2 <|> x3 <?> "product" x3 <- rule $ Var <$> (satisfy ident <?> "identifier") <|> namedSymbol "(" *> x1 <* namedSymbol ")" return x1 where ident (x:_) = isAlpha x ident _ = False prettyParens :: Bool -> String -> String prettyParens True s = "(" ++ s ++ ")" prettyParens False s = s prettyExpr :: Int -> Expr -> String prettyExpr _ (Var s) = s prettyExpr d (Add a b) = prettyParens (d > 0) $ prettyExpr 0 a ++ " + " ++ prettyExpr 1 b prettyExpr d (Mul a b) = prettyParens (d > 1) $ prettyExpr 1 a ++ " * " ++ prettyExpr 2 b -- @words@ like lexer, but consider parentheses as separate tokens lexExpr :: String -> [String] lexExpr "" = [] lexExpr ('(' : s) = "(" : lexExpr s lexExpr (')' : s) = ")" : lexExpr s lexExpr (c : s) | isSpace c = lexExpr s | otherwise = let (tok, rest) = span p (c : s) in tok : lexExpr rest where p x = not (x == '(' || x == ')' || isSpace x) data MixfixExpr = Ident (Holey String) | App (Holey String) [MixfixExpr] deriving (Eq, Show) mixfixGrammar :: Grammar r String (Prod r String String MixfixExpr) mixfixGrammar = mixfixExpression table (Ident . pure . Just <$> namedSymbol "x") App where hident = map (fmap symbol) table = [ [(hident ifthenelse, RightAssoc)] , [(hident prefix, RightAssoc)] , [(hident postfix, LeftAssoc)] , [(hident infix1, LeftAssoc)] , [(hident infix2, RightAssoc)] , [(hident closed, NonAssoc)] ] ifthenelse, prefix, postfix, infix1, infix2, closed :: Holey String ifthenelse = [Just "if", Nothing, Just "then", Nothing, Just "else", Nothing] prefix = [Just "prefix", Nothing] postfix = [Nothing, Just "postfix"] infix1 = [Nothing, Just "infix1", Nothing] infix2 = [Nothing, Just "infix2", Nothing] closed = [Just "[", Nothing, Just "]"]
Axure/Earley
tests/Tests.hs
bsd-3-clause
9,453
0
19
2,756
3,530
1,840
1,690
195
2
module Baum.Leftist.Ops where import Baum.Leftist.Type import qualified Baum.Heap.Class as C import Baum.Heap.Op (Position) instance C.Heap LeftistTree where -- empty :: baum a empty = Leaf -- isEmpty :: baum a -> Bool isEmpty t = case t of Leaf -> True _ -> False -- insert :: Ord a => baum a -> a -> baum a insert t k = meld t (Branch Leaf k Leaf) -- deleteMin :: Ord a => baum a -> baum a deleteMin t = meld (left t) (right t) get t ps = case t of Leaf -> Nothing Branch {} -> case ps of [] -> return $ key t 0 : ps -> C.get ( left t ) ps 1 : ps -> C.get ( right t ) ps _ -> Nothing -- decreaseTo :: Ord a => baum a -> Position -> a -> baum a decreaseTo = decreaseTo -- equal :: Eq a => baum a -> baum a -> Bool equal t1 t2 = t1 == t2 toList = toList -- | fuegt zwei Baeume zusammen meld :: Ord a => LeftistTree a -> LeftistTree a -> LeftistTree a meld t Leaf = t meld Leaf t = t meld t1 t2 = if (key t1) < (key t2) then meld t2 t1 else swap (Branch (left t2) (key t2) (meld t1 (right t2))) -- | vertauscht rechten und linken Teilbaum, wenn rechter Baum hoeher swap :: Ord a => LeftistTree a -> LeftistTree a swap Leaf = Leaf swap (Branch l k r) = if (s l) >= (s r) then Branch l k r else Branch r k l -- | liefert den kuerzesten Weg bis zum ersten Blatt s :: LeftistTree a -> Int s t = case t of Leaf -> 0 _ -> s (right t) + 1 -- | Key in einem Branch verringern und evtl. Aufsteigen lassen decreaseTo :: Ord a => LeftistTree a -> Position -> a -> LeftistTree a decreaseTo t [] a = Branch {left = left t, key = a, right = right t} decreaseTo t (0:pt) a = let x = decreaseTo (left t) pt a in f x t 0 decreaseTo t (1:pt) a = let x = decreaseTo (right t) pt a in f x t 1 -- | Realisiert das Aufsteigen eines geaenderten Wertes f :: Ord a => LeftistTree a -> LeftistTree a -> Int -> LeftistTree a f t1 t2 0 = if (key t1) < (key t2) then Branch{ left = Branch{ left = left t1, key = key t2, right = right t1}, key = key t1, right = right t2} else Branch{ left = t1, key = key t2, right = right t2} f t1 t2 1 = if (key t1) < (key t2) then Branch{ left = left t2, key = key t1, right = Branch{ left = left t1, key = key t2, right = right t1}} else Branch{ left = left t2, key = key t2, right = t1} -- | Erzeugt Liste des Baums mit (Position,Key) toList :: LeftistTree a -> [(Position, a)] toList t = case t of Leaf -> [] _ -> toListCount t [] -- | Durch toList initiiert, erzeugt die Liste, bestimmt Positionen toListCount :: LeftistTree a -> Position -> [(Position, a)] toListCount t k = case t of Leaf -> [] _ -> [(k, key t)] ++ toListCount (left t) (k ++ [0]) ++ toListCount (right t) (k ++[1])
Erdwolf/autotool-bonn
src/Baum/Leftist/Ops.hs
gpl-2.0
2,979
42
15
964
1,170
608
562
69
3
{-# 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.OpsWorks.UnassignVolume -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Unassigns an assigned Amazon EBS volume. The volume remains registered -- with the stack. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_UnassignVolume.html AWS API Reference> for UnassignVolume. module Network.AWS.OpsWorks.UnassignVolume ( -- * Creating a Request unassignVolume , UnassignVolume -- * Request Lenses , uvVolumeId -- * Destructuring the Response , unassignVolumeResponse , UnassignVolumeResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'unassignVolume' smart constructor. newtype UnassignVolume = UnassignVolume' { _uvVolumeId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UnassignVolume' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uvVolumeId' unassignVolume :: Text -- ^ 'uvVolumeId' -> UnassignVolume unassignVolume pVolumeId_ = UnassignVolume' { _uvVolumeId = pVolumeId_ } -- | The volume ID. uvVolumeId :: Lens' UnassignVolume Text uvVolumeId = lens _uvVolumeId (\ s a -> s{_uvVolumeId = a}); instance AWSRequest UnassignVolume where type Rs UnassignVolume = UnassignVolumeResponse request = postJSON opsWorks response = receiveNull UnassignVolumeResponse' instance ToHeaders UnassignVolume where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.UnassignVolume" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON UnassignVolume where toJSON UnassignVolume'{..} = object (catMaybes [Just ("VolumeId" .= _uvVolumeId)]) instance ToPath UnassignVolume where toPath = const "/" instance ToQuery UnassignVolume where toQuery = const mempty -- | /See:/ 'unassignVolumeResponse' smart constructor. data UnassignVolumeResponse = UnassignVolumeResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UnassignVolumeResponse' with the minimum fields required to make a request. -- unassignVolumeResponse :: UnassignVolumeResponse unassignVolumeResponse = UnassignVolumeResponse'
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/UnassignVolume.hs
mpl-2.0
3,629
0
12
738
405
247
158
57
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching bindings (HsBinds and MonoBinds) Handles @HsBinds@; those at the top level require different handling, in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at lower levels it is preserved with @let@/@letrec@s). -} {-# LANGUAGE CPP #-} module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec, dsHsWrapper, dsTcEvBinds, dsTcEvBinds_s, dsEvBinds, dsMkUserRule ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr( dsLExpr ) import {-# SOURCE #-} Match( matchWrapper ) import DsMonad import DsGRHSs import DsUtils import HsSyn -- lots of things import CoreSyn -- lots of things import Literal ( Literal(MachStr) ) import CoreSubst import OccurAnal ( occurAnalyseExpr ) import MkCore import CoreUtils import CoreArity ( etaExpand ) import CoreUnfold import CoreFVs import UniqSupply import Digraph import PrelNames import TysPrim ( mkProxyPrimTy ) import TyCon import TcEvidence import TcType import Type import Kind( isKind ) import Coercion hiding (substCo) import TysWiredIn ( eqBoxDataCon, coercibleDataCon, mkListTy , mkBoxedTupleTy, charTy , typeNatKind, typeSymbolKind ) import Id import MkId(proxyHashId) import Class import DataCon ( dataConTyCon ) import Name import IdInfo ( IdDetails(..) ) import Var import VarSet import Rules import VarEnv import Outputable import Module import SrcLoc import Maybes import OrdList import Bag import BasicTypes hiding ( TopLevel ) import DynFlags import FastString import Util import MonadUtils import Control.Monad(liftM,when) {-********************************************************************** * * Desugaring a MonoBinds * * **********************************************************************-} dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) dsTopLHsBinds binds = ds_lhs_binds binds dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)] dsLHsBinds binds = do { binds' <- ds_lhs_binds binds ; return (fromOL binds') } ------------------------ ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds ; return (foldBag appOL id nilOL ds_bs) } dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr)) dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr)) dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless }) = do { dflags <- getDynFlags ; core_expr <- dsLExpr expr -- Dictionary bindings are always VarBinds, -- so we only need do this here ; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr | otherwise = var ; return (unitOL (makeCorePair dflags var' False 0 core_expr)) } dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches , fun_co_fn = co_fn, fun_tick = tick , fun_infix = inf }) = do { dflags <- getDynFlags ; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches ; let body' = mkOptTickBox tick body ; rhs <- dsHsWrapper co_fn (mkLams args body') ; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -} return (unitOL (makeCorePair dflags fun False 0 rhs)) } dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty , pat_ticks = (rhs_tick, var_ticks) }) = do { body_expr <- dsGuarded grhss ty ; let body' = mkOptTickBox rhs_tick body_expr ; sel_binds <- mkSelectorBinds var_ticks pat body' -- We silently ignore inline pragmas; no makeCorePair -- Not so cool, but really doesn't matter ; return (toOL sel_binds) } -- A common case: one exported variable -- Non-recursive bindings come through this way -- So do self-recursive bindings, and recursive bindings -- that have been chopped up with type signatures dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = [export] , abs_ev_binds = ev_binds, abs_binds = binds }) | ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = prags } <- export = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec (fromOL bind_prs) ; ds_binds <- dsTcEvBinds_s ev_binds ; rhs <- dsHsWrapper wrap $ -- Usually the identity mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ Var local ; (spec_binds, rules) <- dsSpecs rhs prags ; let global' = addIdSpecialisations global rules main_bind = makeCorePair dflags global' (isDefaultMethod prags) (dictArity dicts) rhs ; return (main_bind `consOL` spec_binds) } dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = exports, abs_ev_binds = ev_binds , abs_binds = binds }) -- See Note [Desugaring AbsBinds] = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs | (lcl_id, rhs) <- fromOL bind_prs ] -- Monomorphic recursion possible, hence Rec locals = map abe_mono exports tup_expr = mkBigCoreVarTup locals tup_ty = exprType tup_expr ; ds_binds <- dsTcEvBinds_s ev_binds ; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ tup_expr ; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs) ; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = spec_prags }) = do { tup_id <- newSysLocalDs tup_ty ; rhs <- dsHsWrapper wrap $ mkLams tyvars $ mkLams dicts $ mkTupleSelector locals local tup_id $ mkVarApps (Var poly_tup_id) (tyvars ++ dicts) ; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs ; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags ; let global' = (global `setInlinePragma` defaultInlinePragma) `addIdSpecialisations` rules -- Kill the INLINE pragma because it applies to -- the user written (local) function. The global -- Id is just the selector. Hmm. ; return ((global', rhs) `consOL` spec_binds) } ; export_binds_s <- mapM mk_bind exports ; return ((poly_tup_id, poly_tup_rhs) `consOL` concatOL export_binds_s) } where inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with -- the inline pragma from the source -- The type checker put the inline pragma -- on the *global* Id, so we need to transfer it inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag) | ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports , let prag = idInlinePragma gbl_id ] add_inline :: Id -> Id -- tran add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind" ------------------------ makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr) makeCorePair dflags gbl_id is_default_method dict_arity rhs | is_default_method -- Default methods are *always* inlined = (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs) | DFunId is_newtype <- idDetails gbl_id = (mk_dfun_w_stuff is_newtype, rhs) | otherwise = case inlinePragmaSpec inline_prag of EmptyInlineSpec -> (gbl_id, rhs) NoInline -> (gbl_id, rhs) Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs) Inline -> inline_pair where inline_prag = idInlinePragma gbl_id inlinable_unf = mkInlinableUnfolding dflags rhs inline_pair | Just arity <- inlinePragmaSat inline_prag -- Add an Unfolding for an INLINE (but not for NOINLINE) -- And eta-expand the RHS; see Note [Eta-expanding INLINE things] , let real_arity = dict_arity + arity -- NB: The arity in the InlineRule takes account of the dictionaries = ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs , etaExpand real_arity rhs) | otherwise = pprTrace "makeCorePair: arity missing" (ppr gbl_id) $ (gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs) -- See Note [ClassOp/DFun selection] in TcInstDcls -- See Note [Single-method classes] in TcInstDcls mk_dfun_w_stuff is_newtype | is_newtype = gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 } | otherwise = gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args `setInlinePragma` dfunInlinePragma (dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs) (dfun_con, dfun_args) = collectArgs dfun_body dfun_constr | Var id <- dfun_con , DataConWorkId con <- idDetails id = con | otherwise = pprPanic "makeCorePair: dfun" (ppr rhs) dictArity :: [Var] -> Arity -- Don't count coercion variables in arity dictArity dicts = count isId dicts {- [Desugaring AbsBinds] ~~~~~~~~~~~~~~~~~~~~~ In the general AbsBinds case we desugar the binding to this: tup a (d:Num a) = let fm = ...gm... gm = ...fm... in (fm,gm) f a d = case tup a d of { (fm,gm) -> fm } g a d = case tup a d of { (fm,gm) -> fm } Note [Rules and inlining] ~~~~~~~~~~~~~~~~~~~~~~~~~ Common special case: no type or dictionary abstraction This is a bit less trivial than you might suppose The naive way woudl be to desguar to something like f_lcl = ...f_lcl... -- The "binds" from AbsBinds M.f = f_lcl -- Generated from "exports" But we don't want that, because if M.f isn't exported, it'll be inlined unconditionally at every call site (its rhs is trivial). That would be ok unless it has RULES, which would thereby be completely lost. Bad, bad, bad. Instead we want to generate M.f = ...f_lcl... f_lcl = M.f Now all is cool. The RULES are attached to M.f (by SimplCore), and f_lcl is rapidly inlined away. This does not happen in the same way to polymorphic binds, because they desugar to M.f = /\a. let f_lcl = ...f_lcl... in f_lcl Although I'm a bit worried about whether full laziness might float the f_lcl binding out and then inline M.f at its call site Note [Specialising in no-dict case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if there are no tyvars or dicts, we may have specialisation pragmas. Class methods can generate AbsBinds [] [] [( ... spec-prag] { AbsBinds [tvs] [dicts] ...blah } So the overloading is in the nested AbsBinds. A good example is in GHC.Float: class (Real a, Fractional a) => RealFrac a where round :: (Integral b) => a -> b instance RealFrac Float where {-# SPECIALIZE round :: Float -> Int #-} The top-level AbsBinds for $cround has no tyvars or dicts (because the instance does not). But the method is locally overloaded! Note [Abstracting over tyvars only] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When abstracting over type variable only (not dictionaries), we don't really need to built a tuple and select from it, as we do in the general case. Instead we can take AbsBinds [a,b] [ ([a,b], fg, fl, _), ([b], gg, gl, _) ] { fl = e1 gl = e2 h = e3 } and desugar it to fg = /\ab. let B in e1 gg = /\b. let a = () in let B in S(e2) h = /\ab. let B in e3 where B is the *non-recursive* binding fl = fg a b gl = gg b h = h a b -- See (b); note shadowing! Notice (a) g has a different number of type variables to f, so we must use the mkArbitraryType thing to fill in the gaps. We use a type-let to do that. (b) The local variable h isn't in the exports, and rather than clone a fresh copy we simply replace h by (h a b), where the two h's have different types! Shadowing happens here, which looks confusing but works fine. (c) The result is *still* quadratic-sized if there are a lot of small bindings. So if there are more than some small number (10), we filter the binding set B by the free variables of the particular RHS. Tiresome. Why got to this trouble? It's a common case, and it removes the quadratic-sized tuple desugaring. Less clutter, hopefully faster compilation, especially in a case where there are a *lot* of bindings. Note [Eta-expanding INLINE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider foo :: Eq a => a -> a {-# INLINE foo #-} foo x = ... If (foo d) ever gets floated out as a common sub-expression (which can happen as a result of method sharing), there's a danger that we never get to do the inlining, which is a Terribly Bad thing given that the user said "inline"! To avoid this we pre-emptively eta-expand the definition, so that foo has the arity with which it is declared in the source code. In this example it has arity 2 (one for the Eq and one for x). Doing this should mean that (foo d) is a PAP and we don't share it. Note [Nested arities] ~~~~~~~~~~~~~~~~~~~~~ For reasons that are not entirely clear, method bindings come out looking like this: AbsBinds [] [] [$cfromT <= [] fromT] $cfromT [InlPrag=INLINE] :: T Bool -> Bool { AbsBinds [] [] [fromT <= [] fromT_1] fromT :: T Bool -> Bool { fromT_1 ((TBool b)) = not b } } } Note the nested AbsBind. The arity for the InlineRule on $cfromT should be gotten from the binding for fromT_1. It might be better to have just one level of AbsBinds, but that requires more thought! -} ------------------------ dsSpecs :: CoreExpr -- Its rhs -> TcSpecPrags -> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids , [CoreRule] ) -- Rules for the Global Ids -- See Note [Handling SPECIALISE pragmas] in TcBinds dsSpecs _ IsDefaultMethod = return (nilOL, []) dsSpecs poly_rhs (SpecPrags sps) = do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps ; let (spec_binds_s, rules) = unzip pairs ; return (concatOL spec_binds_s, rules) } dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding -- Nothing => RULE is for an imported Id -- rhs is in the Id's unfolding -> Located TcSpecPrag -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule)) dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector") <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:") <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialiation inherits that -- See Note [Activation pragmas for SPECIALISE] | otherwise = putSrcSpanDs loc $ do { uniq <- newUnique ; let poly_name = idName poly_id spec_occ = mkSpecOcc (getOccName poly_name) spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name) ; (bndrs, ds_lhs) <- liftM collectBinders (dsHsWrapper spec_co (Var poly_id)) ; let spec_ty = mkPiTypes bndrs (exprType ds_lhs) ; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id -- , ptext (sLit "spec_co:") <+> ppr spec_co -- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $ case decomposeRuleLhs bndrs ds_lhs of { Left msg -> do { warnDs msg; return Nothing } ; Right (rule_bndrs, _fn, args) -> do { dflags <- getDynFlags ; this_mod <- getModule ; let fn_unf = realIdUnfolding poly_id unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args) spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf spec_id = mkLocalId spec_name spec_ty `setInlinePragma` inl_prag `setIdUnfolding` spec_unf ; rule <- dsMkUserRule this_mod is_local_id (mkFastString ("SPEC " ++ showPpr dflags poly_name)) rule_act poly_name rule_bndrs args (mkVarApps (Var spec_id) bndrs) ; spec_rhs <- dsHsWrapper spec_co poly_rhs -- Commented out: see Note [SPECIALISE on INLINE functions] -- ; when (isInlinePragma id_inl) -- (warnDs $ ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:") -- <+> quotes (ppr poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule)) -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because -- makeCorePair overwrites the unfolding, which we have -- just created using specUnfolding } } } where is_local_id = isJust mb_poly_rhs poly_rhs | Just rhs <- mb_poly_rhs = rhs -- Local Id; this is its rhs | Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id) = unfolding -- Imported Id; this is its unfolding -- Use realIdUnfolding so we get the unfolding -- even when it is a loop breaker. -- We want to specialise recursive functions! | otherwise = pprPanic "dsImpSpecs" (ppr poly_id) -- The type checker has checked that it *has* an unfolding id_inl = idInlinePragma poly_id -- See Note [Activation pragmas for SPECIALISE] inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl | not is_local_id -- See Note [Specialising imported functions] -- in OccurAnal , isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma | otherwise = id_inl -- Get the INLINE pragma from SPECIALISE declaration, or, -- failing that, from the original Id spec_prag_act = inlinePragmaActivation spec_inl -- See Note [Activation pragmas for SPECIALISE] -- no_act_spec is True if the user didn't write an explicit -- phase specification in the SPECIALISE pragma no_act_spec = case inlinePragmaSpec spec_inl of NoInline -> isNeverActive spec_prag_act _ -> isAlwaysActive spec_prag_act rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit | otherwise = spec_prag_act -- Specified by user dsMkUserRule :: Module -> Bool -> RuleName -> Activation -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> DsM CoreRule dsMkUserRule this_mod is_local name act fn bndrs args rhs = do let rule = mkRule this_mod False is_local name act fn bndrs args rhs dflags <- getDynFlags when (isOrphan (ru_orphan rule) && wopt Opt_WarnOrphans dflags) $ warnDs (ruleOrphWarn rule) return rule ruleOrphWarn :: CoreRule -> SDoc ruleOrphWarn rule = ptext (sLit "Orphan rule:") <+> ppr rule {- Note [SPECIALISE on INLINE functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to warn that using SPECIALISE for a function marked INLINE would be a no-op; but it isn't! Especially with worker/wrapper split we might have {-# INLINE f #-} f :: Ord a => Int -> a -> ... f d x y = case x of I# x' -> $wf d x' y We might want to specialise 'f' so that we in turn specialise '$wf'. We can't even /name/ '$wf' in the source code, so we can't specialise it even if we wanted to. Trac #10721 is a case in point. Note [Activation pragmas for SPECIALISE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From a user SPECIALISE pragma for f, we generate a) A top-level binding spec_fn = rhs b) A RULE f dOrd = spec_fn We need two pragma-like things: * spec_fn's inline pragma: inherited from f's inline pragma (ignoring activation on SPEC), unless overriden by SPEC INLINE * Activation of RULE: from SPECIALISE pragma (if activation given) otherwise from f's inline pragma This is not obvious (see Trac #5237)! Examples Rule activation Inline prag on spec'd fn --------------------------------------------------------------------- SPEC [n] f :: ty [n] Always, or NOINLINE [n] copy f's prag NOINLINE f SPEC [n] f :: ty [n] NOINLINE copy f's prag NOINLINE [k] f SPEC [n] f :: ty [n] NOINLINE [k] copy f's prag INLINE [k] f SPEC [n] f :: ty [n] INLINE [k] copy f's prag SPEC INLINE [n] f :: ty [n] INLINE [n] (ignore INLINE prag on f, same activation for rule and spec'd fn) NOINLINE [k] f SPEC f :: ty [n] INLINE [k] ************************************************************************ * * \subsection{Adding inline pragmas} * * ************************************************************************ -} decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr]) -- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE, -- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs -- may add some extra dictionary binders (see Note [Free dictionaries]) -- -- Returns Nothing if the LHS isn't of the expected shape -- Note [Decomposing the left-hand side of a RULE] decomposeRuleLhs orig_bndrs orig_lhs | not (null unbound) -- Check for things unbound on LHS -- See Note [Unused spec binders] = Left (vcat (map dead_msg unbound)) | Just (fn_id, args) <- decompose fun2 args2 , let extra_dict_bndrs = mk_extra_dict_bndrs fn_id args = -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs -- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs -- , ptext (sLit "lhs1:") <+> ppr lhs1 -- , ptext (sLit "extra_dict_bndrs:") <+> ppr extra_dict_bndrs -- , ptext (sLit "fn_id:") <+> ppr fn_id -- , ptext (sLit "args:") <+> ppr args]) $ Right (orig_bndrs ++ extra_dict_bndrs, fn_id, args) | otherwise = Left bad_shape_msg where lhs1 = drop_dicts orig_lhs lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS] (fun2,args2) = collectArgs lhs2 lhs_fvs = exprFreeVars lhs2 unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs orig_bndr_set = mkVarSet orig_bndrs -- Add extra dict binders: Note [Free dictionaries] mk_extra_dict_bndrs fn_id args = [ mkLocalId (localiseName (idName d)) (idType d) | d <- varSetElems (exprsFreeVars args `delVarSetList` (fn_id : orig_bndrs)) -- fn_id: do not quantify over the function itself, which may -- itself be a dictionary (in pathological cases, Trac #10251) , isDictId d ] decompose (Var fn_id) args | not (fn_id `elemVarSet` orig_bndr_set) = Just (fn_id, args) decompose _ _ = Nothing bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar")) 2 (vcat [ text "Optimised lhs:" <+> ppr lhs2 , text "Orig lhs:" <+> ppr orig_lhs]) dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr , ptext (sLit "is not bound in RULE lhs")]) 2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs , text "Orig lhs:" <+> ppr orig_lhs , text "optimised lhs:" <+> ppr lhs2 ]) pp_bndr bndr | isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr) | Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred) | otherwise = ptext (sLit "variable") <+> quotes (ppr bndr) drop_dicts :: CoreExpr -> CoreExpr drop_dicts e = wrap_lets needed bnds body where needed = orig_bndr_set `minusVarSet` exprFreeVars body (bnds, body) = split_lets (occurAnalyseExpr e) -- The occurAnalyseExpr drops dead bindings which is -- crucial to ensure that every binding is used later; -- which in turn makes wrap_lets work right split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr) split_lets e | Let (NonRec d r) body <- e , isDictId d , (bs, body') <- split_lets body = ((d,r):bs, body') | otherwise = ([], e) wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr wrap_lets _ [] body = body wrap_lets needed ((d, r) : bs) body | rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body) | otherwise = wrap_lets needed bs body where rhs_fvs = exprFreeVars r needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d {- Note [Decomposing the left-hand side of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are several things going on here. * drop_dicts: see Note [Drop dictionary bindings on rule LHS] * simpleOptExpr: see Note [Simplify rule LHS] * extra_dict_bndrs: see Note [Free dictionaries] Note [Drop dictionary bindings on rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ drop_dicts drops dictionary bindings on the LHS where possible. E.g. let d:Eq [Int] = $fEqList $fEqInt in f d --> f d Reasoning here is that there is only one d:Eq [Int], and so we can quantify over it. That makes 'd' free in the LHS, but that is later picked up by extra_dict_bndrs (Note [Dead spec binders]). NB 1: We can only drop the binding if the RHS doesn't bind one of the orig_bndrs, which we assume occur on RHS. Example f :: (Eq a) => b -> a -> a {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-} Here we want to end up with RULE forall d:Eq a. f ($dfEqList d) = f_spec d Of course, the ($dfEqlist d) in the pattern makes it less likely to match, but there is no other way to get d:Eq a NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all the evidence bindings to be wrapped around the outside of the LHS. (After simplOptExpr they'll usually have been inlined.) dsHsWrapper does dependency analysis, so that civilised ones will be simple NonRec bindings. We don't handle recursive dictionaries! NB3: In the common case of a non-overloaded, but perhaps-polymorphic specialisation, we don't need to bind *any* dictionaries for use in the RHS. For example (Trac #8331) {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-} useAbstractMonad :: MonadAbstractIOST m => m Int Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code but the RHS uses no dictionaries, so we want to end up with RULE forall s (d :: MonadAbstractIOST (ReaderT s)). useAbstractMonad (ReaderT s) d = $suseAbstractMonad s Trac #8848 is a good example of where there are some intersting dictionary bindings to discard. The drop_dicts algorithm is based on these observations: * Given (let d = rhs in e) where d is a DictId, matching 'e' will bind e's free variables. * So we want to keep the binding if one of the needed variables (for which we need a binding) is in fv(rhs) but not already in fv(e). * The "needed variables" are simply the orig_bndrs. Consider f :: (Eq a, Show b) => a -> b -> String ... SPECIALISE f :: (Show b) => Int -> b -> String ... Then orig_bndrs includes the *quantified* dictionaries of the type namely (dsb::Show b), but not the one for Eq Int So we work inside out, applying the above criterion at each step. Note [Simplify rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~ simplOptExpr occurrence-analyses and simplifies the LHS: (a) Inline any remaining dictionary bindings (which hopefully occur just once) (b) Substitute trivial lets so that they don't get in the way Note that we substitute the function too; we might have this as a LHS: let f71 = M.f Int in f71 (c) Do eta reduction. To see why, consider the fold/build rule, which without simplification looked like: fold k z (build (/\a. g a)) ==> ... This doesn't match unless you do eta reduction on the build argument. Similarly for a LHS like augment g (build h) we do not want to get augment (\a. g a) (build h) otherwise we don't match when given an argument like augment (\a. h a a) (build h) Note [Matching seqId] ~~~~~~~~~~~~~~~~~~~ The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack and this code turns it back into an application of seq! See Note [Rules for seq] in MkId for the details. Note [Unused spec binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: a -> a ... SPECIALISE f :: Eq a => a -> a ... It's true that this *is* a more specialised type, but the rule we get is something like this: f_spec d = f RULE: f = f_spec d Note that the rule is bogus, because it mentions a 'd' that is not bound on the LHS! But it's a silly specialisation anyway, because the constraint is unused. We could bind 'd' to (error "unused") but it seems better to reject the program because it's almost certainly a mistake. That's what the isDeadBinder call detects. Note [Free dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~ When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, which is presumably in scope at the function definition site, we can quantify over it too. *Any* dict with that type will do. So for example when you have f :: Eq a => a -> a f = <rhs> ... SPECIALISE f :: Int -> Int ... Then we get the SpecPrag SpecPrag (f Int dInt) And from that we want the rule RULE forall dInt. f Int dInt = f_spec f_spec = let f = <rhs> in f Int dInt But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External Name, and you can't bind them in a lambda or forall without getting things confused. Likewise it might have an InlineRule or something, which would be utterly bogus. So we really make a fresh Id, with the same unique and type as the old one, but with an Internal name and no IdInfo. ************************************************************************ * * Desugaring evidence * * ************************************************************************ -} dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr dsHsWrapper WpHole e = return e dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty) dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds return (mkCoreLets bs e) dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e ; dsHsWrapper c1 e1 } dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1 ; e1 <- dsHsWrapper c1 (Var x) ; e2 <- dsHsWrapper c2 (mkCoreAppDs (text "dsHsWrapper") e e1) ; return (Lam x e2) } dsHsWrapper (WpCast co) e = ASSERT(tcCoercionRole co == Representational) dsTcCoercion co (mkCastDs e) dsHsWrapper (WpEvLam ev) e = return $ Lam ev e dsHsWrapper (WpTyLam tv) e = return $ Lam tv e dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm) -------------------------------------- dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind] dsTcEvBinds_s [] = return [] dsTcEvBinds_s (b:rest) = ASSERT( null rest ) -- Zonker ensures null dsTcEvBinds b dsTcEvBinds :: TcEvBinds -> DsM [CoreBind] dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this dsTcEvBinds (EvBinds bs) = dsEvBinds bs dsEvBinds :: Bag EvBind -> DsM [CoreBind] dsEvBinds bs = mapM ds_scc (sccEvBinds bs) where ds_scc (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = r })) = liftM (NonRec v) (dsEvTerm r) ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs) ds_pair (EvBind { eb_lhs = v, eb_rhs = r }) = liftM ((,) v) (dsEvTerm r) sccEvBinds :: Bag EvBind -> [SCC EvBind] sccEvBinds bs = stronglyConnCompFromEdgedVertices edges where edges :: [(EvBind, EvVar, [EvVar])] edges = foldrBag ((:) . mk_node) [] bs mk_node :: EvBind -> (EvBind, EvVar, [EvVar]) mk_node b@(EvBind { eb_lhs = var, eb_rhs = term }) = (b, var, varSetElems (evVarsOfTerm term)) {-********************************************************************** * * Desugaring EvTerms * * **********************************************************************-} dsEvTerm :: EvTerm -> DsM CoreExpr dsEvTerm (EvId v) = return (Var v) dsEvTerm (EvCallStack cs) = dsEvCallStack cs dsEvTerm (EvTypeable ty ev) = dsEvTypeable ty ev dsEvTerm (EvLit (EvNum n)) = mkIntegerExpr n dsEvTerm (EvLit (EvStr s)) = mkStringExprFS s dsEvTerm (EvCast tm co) = do { tm' <- dsEvTerm tm ; dsTcCoercion co $ mkCastDs tm' } -- 'v' is always a lifted evidence variable so it is -- unnecessary to call varToCoreExpr v here. dsEvTerm (EvDFunApp df tys tms) = return (Var df `mkTyApps` tys `mkApps` (map Var tms)) dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions] dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox dsEvTerm (EvSuperClass d n) = do { d' <- dsEvTerm d ; let (cls, tys) = getClassPredTys (exprType d') sc_sel_id = classSCSelId cls n -- Zero-indexed ; return $ Var sc_sel_id `mkTyApps` tys `App` d' } dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg] where errorId = tYPE_ERROR_ID litMsg = Lit (MachStr (fastStringToByteString msg)) {-********************************************************************** * * Desugaring Typeable dictionaries * * **********************************************************************-} dsEvTypeable :: Type -> EvTypeable -> DsM CoreExpr -- Return a CoreExpr :: Typeable ty -- This code is tightly coupled to the representation -- of TypeRep, in base library Data.Typeable.Internals dsEvTypeable ty ev = do { tyCl <- dsLookupTyCon typeableClassName -- Typeable ; let kind = typeKind ty Just typeable_data_con = tyConSingleDataCon_maybe tyCl -- "Data constructor" -- for Typeable ; rep_expr <- ds_ev_typeable ty ev -- Build Core for (let r::TypeRep = rep in \proxy. rep) -- See Note [Memoising typeOf] ; repName <- newSysLocalDs (exprType rep_expr) ; let proxyT = mkProxyPrimTy kind ty method = bindNonRec repName rep_expr $ mkLams [mkWildValBinder proxyT] (Var repName) -- Package up the method as `Typeable` dictionary ; return $ mkConApp typeable_data_con [Type kind, Type ty, method] } ds_ev_typeable :: Type -> EvTypeable -> DsM CoreExpr -- Returns a CoreExpr :: TypeRep ty ds_ev_typeable ty EvTypeableTyCon | Just (tc, ks) <- splitTyConApp_maybe ty = ASSERT( all isKind ks ) do { ctr <- dsLookupGlobalId mkPolyTyConAppName -- mkPolyTyConApp :: TyCon -> [KindRep] -> [TypeRep] -> TypeRep ; tyRepTc <- dsLookupTyCon typeRepTyConName -- TypeRep (the TyCon) ; let tyRepType = mkTyConApp tyRepTc [] -- TypeRep (the Type) mkRep cRep kReps tReps = mkApps (Var ctr) [ cRep , mkListExpr tyRepType kReps , mkListExpr tyRepType tReps ] kindRep k -- Returns CoreExpr :: TypeRep for that kind k = case splitTyConApp_maybe k of Nothing -> panic "dsEvTypeable: not a kind constructor" Just (kc,ks) -> do { kcRep <- tyConRep kc ; reps <- mapM kindRep ks ; return (mkRep kcRep [] reps) } ; tcRep <- tyConRep tc ; kReps <- mapM kindRep ks ; return (mkRep tcRep kReps []) } ds_ev_typeable ty (EvTypeableTyApp ev1 ev2) | Just (t1,t2) <- splitAppTy_maybe ty = do { e1 <- getRep ev1 t1 ; e2 <- getRep ev2 t2 ; ctr <- dsLookupGlobalId mkAppTyName ; return ( mkApps (Var ctr) [ e1, e2 ] ) } ds_ev_typeable ty (EvTypeableTyLit ev) = do { fun <- dsLookupGlobalId tr_fun ; dict <- dsEvTerm ev -- Of type KnownNat/KnownSym ; let proxy = mkTyApps (Var proxyHashId) [ty_kind, ty] ; return (mkApps (mkTyApps (Var fun) [ty]) [ dict, proxy ]) } where ty_kind = typeKind ty -- tr_fun is the Name of -- typeNatTypeRep :: KnownNat a => Proxy# a -> TypeRep -- of typeSymbolTypeRep :: KnownSymbol a => Proxy# a -> TypeRep tr_fun | ty_kind `eqType` typeNatKind = typeNatTypeRepName | ty_kind `eqType` typeSymbolKind = typeSymbolTypeRepName | otherwise = panic "dsEvTypeable: unknown type lit kind" ds_ev_typeable ty ev = pprPanic "dsEvTypeable" (ppr ty $$ ppr ev) getRep :: EvTerm -> Type -- EvTerm for Typeable ty, and ty -> DsM CoreExpr -- Return CoreExpr :: TypeRep (of ty) -- namely (typeRep# dict proxy) -- Remember that -- typeRep# :: forall k (a::k). Typeable k a -> Proxy k a -> TypeRep getRep ev ty = do { typeable_expr <- dsEvTerm ev ; typeRepId <- dsLookupGlobalId typeRepIdName ; let ty_args = [typeKind ty, ty] ; return (mkApps (mkTyApps (Var typeRepId) ty_args) [ typeable_expr , mkTyApps (Var proxyHashId) ty_args ]) } tyConRep :: TyCon -> DsM CoreExpr -- Returns CoreExpr :: TyCon tyConRep tc | Just tc_rep_nm <- tyConRepName_maybe tc = do { tc_rep_id <- dsLookupGlobalId tc_rep_nm ; return (Var tc_rep_id) } | otherwise = pprPanic "tyConRep" (ppr tc) {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} {-********************************************************************** * * Desugaring EvCallStack evidence * * **********************************************************************-} dsEvCallStack :: EvCallStack -> DsM CoreExpr -- See Note [Overview of implicit CallStacks] in TcEvidence.hs dsEvCallStack cs = do df <- getDynFlags m <- getModule srcLocDataCon <- dsLookupDataCon srcLocDataConName let srcLocTyCon = dataConTyCon srcLocDataCon let srcLocTy = mkTyConTy srcLocTyCon let mkSrcLoc l = liftM (mkCoreConApps srcLocDataCon) (sequence [ mkStringExprFS (unitIdFS $ moduleUnitId m) , mkStringExprFS (moduleNameFS $ moduleName m) , mkStringExprFS (srcSpanFile l) , return $ mkIntExprInt df (srcSpanStartLine l) , return $ mkIntExprInt df (srcSpanStartCol l) , return $ mkIntExprInt df (srcSpanEndLine l) , return $ mkIntExprInt df (srcSpanEndCol l) ]) -- Be careful to use [Char] instead of String here to avoid -- unnecessary dependencies on GHC.Base, particularly when -- building GHC.Err.absentError let callSiteTy = mkBoxedTupleTy [mkListTy charTy, srcLocTy] matchId <- newSysLocalDs $ mkListTy callSiteTy callStackDataCon <- dsLookupDataCon callStackDataConName let callStackTyCon = dataConTyCon callStackDataCon let callStackTy = mkTyConTy callStackTyCon let emptyCS = mkCoreConApps callStackDataCon [mkNilExpr callSiteTy] let pushCS name loc rest = mkWildCase rest callStackTy callStackTy [( DataAlt callStackDataCon , [matchId] , mkCoreConApps callStackDataCon [mkConsExpr callSiteTy (mkCoreTup [name, loc]) (Var matchId)] )] let mkPush name loc tm = do nameExpr <- mkStringExprFS name locExpr <- mkSrcLoc loc case tm of EvCallStack EvCsEmpty -> return (pushCS nameExpr locExpr emptyCS) _ -> do tmExpr <- dsEvTerm tm -- at this point tmExpr :: IP sym CallStack -- but we need the actual CallStack to pass to pushCS, -- so we use unwrapIP to strip the dictionary wrapper -- See Note [Overview of implicit CallStacks] let ip_co = unwrapIP (exprType tmExpr) return (pushCS nameExpr locExpr (mkCastDs tmExpr ip_co)) case cs of EvCsTop name loc tm -> mkPush name loc tm EvCsPushCall name loc tm -> mkPush (occNameFS $ getOccName name) loc tm EvCsEmpty -> panic "Cannot have an empty CallStack" {-********************************************************************** * * Desugaring Coercions * * **********************************************************************-} dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr -- This is the crucial function that moves -- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion -- e.g. dsTcCoercion (trans g1 g2) k -- = case g1 of EqBox g1# -> -- case g2 of EqBox g2# -> -- k (trans g1# g2#) -- thing_inside will get a coercion at the role requested dsTcCoercion co thing_inside = do { us <- newUniqueSupply ; let eqvs_covs :: [(EqVar,CoVar)] eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co)) (uniqsFromSupply us) subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs] result_expr = thing_inside (ds_tc_coercion subst co) result_ty = exprType result_expr ; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) } where mk_co_var :: Id -> Unique -> (Id, Id) mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc) where eq_nm = idName eqv occ = nameOccName eq_nm loc = nameSrcSpan eq_nm ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2 (ty1, ty2) = getEqPredTys (evVarPred eqv) wrap_in_case result_ty (eqv, cov) body = case getEqPredRole (evVarPred eqv) of Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)] Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)] Phantom -> panic "wrap_in_case/phantom" ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion -- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b) -- the result is of type (a ~# b) (reps. a ~# b) -- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on) -- No need for InScope set etc because the ds_tc_coercion subst tc_co = go tc_co where go (TcRefl r ty) = Refl r (Coercion.substTy subst ty) go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos) go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2) go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co) where (subst', tv') = Coercion.substTyVarBndr subst tv go (TcAxiomInstCo ax ind cos) = AxiomInstCo ax ind (map go cos) go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2 go (TcSymCo co) = mkSymCo (go co) go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2) go (TcNthCo n co) = mkNthCo n (go co) go (TcLRCo lr co) = mkLRCo lr (go co) go (TcSubCo co) = mkSubCo (go co) go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2) go (TcCoVarCo v) = ds_ev_id subst v go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs) go (TcCoercion co) = co ds_co_binds :: TcEvBinds -> CvSubst ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs) ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb) ds_scc :: CvSubst -> SCC EvBind -> CvSubst ds_scc subst (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = ev_term })) = extendCvSubstAndInScope subst v (ds_co_term subst ev_term) ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co) ds_co_term :: CvSubst -> EvTerm -> Coercion ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co ds_co_term subst (EvId v) = ds_ev_id subst v ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co) ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co) ds_ev_id :: CvSubst -> EqVar -> Coercion ds_ev_id subst v | Just co <- Coercion.lookupCoVar subst v = co | otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co) {- Note [Simple coercions] ~~~~~~~~~~~~~~~~~~~~~~~ We have a special case for coercions that are simple variables. Suppose cv :: a ~ b is in scope Lacking the special case, if we see f a b cv we'd desguar to f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#) which is a bit stupid. The special case does the obvious thing. This turns out to be important when desugaring the LHS of a RULE (see Trac #7837). Suppose we have normalise :: (a ~ Scalar a) => a -> a normalise_Double :: Double -> Double {-# RULES "normalise" normalise = normalise_Double #-} Then the RULE we want looks like forall a, (cv:a~Scalar a). normalise a cv = normalise_Double But without the special case we generate the redundant box/unbox, which simpleOpt (currently) doesn't remove. So the rule never matches. Maybe simpleOpt should be smarter. But it seems like a good plan to simply never generate the redundant box/unbox in the first place. -}
AlexanderPankiv/ghc
compiler/deSugar/DsBinds.hs
bsd-3-clause
49,879
0
22
15,585
8,310
4,271
4,039
-1
-1
module Optimization.TrustRegion.Newton ( -- * Newton's method newton -- * Matrix inversion methods , bicInv , bicInv' ) where import Control.Applicative import Data.Distributive (Distributive) import Data.Functor.Bind (Apply) import Data.Foldable (Foldable) import Linear -- | Newton's method newton :: (Num a, Ord a, Additive f, Metric f, Foldable f) => (f a -> f a) -- ^ gradient of function -> (f a -> f (f a)) -- ^ inverse Hessian -> f a -- ^ starting point -> [f a] -- ^ iterates newton df ddfInv x0 = iterate go x0 where go x = x ^-^ ddfInv x !* df x {-# INLINEABLE newton #-} -- | Inverse by iterative method of Ben-Israel and Cohen -- with given starting condition bicInv' :: (Functor m, Distributive m, Additive m, Applicative m, Apply m, Foldable m, Conjugate a) => m (m a) -> m (m a) -> [m (m a)] bicInv' a0 a = iterate go a0 where go ak = 2 *!! ak !-! ak !*! a !*! ak {-# INLINEABLE bicInv' #-} -- | Inverse by iterative method of Ben-Israel and Cohen -- starting from @alpha A^T@. Alpha should be set such that -- 0 < alpha < 2/sigma^2 where @sigma@ denotes the largest singular -- value of A bicInv :: (Functor m, Distributive m, Additive m, Applicative m, Apply m, Foldable m, Conjugate a) => a -> m (m a) -> [m (m a)] bicInv alpha a = bicInv' (alpha *!! adjoint a) a {-# INLINEABLE bicInv #-}
ocramz/optimization
src/Optimization/TrustRegion/Newton.hs
bsd-3-clause
1,456
0
12
397
438
232
206
26
1
-- #hide module Graphics.HGL.Win32.WND ( WND, mkWND, openWND, closeWND, redrawWND , handleEvents, closeAllHWNDs , beginGraphics, endGraphics , wndRect , getHWND , drawWND ) where import Graphics.HGL.Units (Point) import Graphics.HGL.Internals.Event( Event(..) ) import Graphics.HGL.Internals.Draw (Draw, unDraw) import Graphics.HGL.Internals.Events( Events, sendEvent, sendTick ) import Graphics.HGL.Internals.Utilities(safeTry, Exception) import Graphics.HGL.Win32.Draw( DrawFun, setDefaults, withDC ) import Graphics.HGL.Win32.Types( Key(MkKey), toPoint ) import Control.Concurrent( yield ) import Control.Monad(liftM2,when) import Data.Bits import Data.IORef import Data.Maybe(isJust) import System.IO.Unsafe(unsafePerformIO) import Graphics.Win32 import System.Win32 (getModuleHandle) ---------------------------------------------------------------- -- Once a window has been closed, we want to detect any further -- operations on the window - so all access is via a mutable Maybe ---------------------------------------------------------------- newtype WND = MkWND (IORef (Maybe HWND)) closeWND :: WND -> IO () closeWND wnd@(MkWND hwndref) = do mb_hwnd <- readIORef hwndref writeIORef hwndref Nothing -- mark it as closed case mb_hwnd of Just hwnd -> do removeHWND hwnd -- added by Ulf Norell <[email protected]> yield -- added by Ulf destroyWindow hwnd Nothing -> return () getHWND :: WND -> IO HWND getHWND (MkWND hwndref) = do mb_hwnd <- readIORef hwndref case mb_hwnd of Just hwnd -> return hwnd Nothing -> ioError (userError "Attempted to act on closed window") redrawWND :: WND -> IO () redrawWND wnd = do hwnd <- getHWND wnd invalidateRect (Just hwnd) Nothing False drawWND :: WND -> Draw () -> IO () drawWND wnd p = do hwnd <- getHWND wnd withDC (Just hwnd) (\ hdc -> setDefaults hdc >> unDraw p hdc) wndRect :: WND -> IO (Point, Point) wndRect wnd = do hwnd <- getHWND wnd (l,t,r,b) <- getClientRect hwnd return (toPoint (l,t), toPoint (r,b)) mkWND :: HWND -> IO WND mkWND hwnd = fmap MkWND (newIORef (Just hwnd)) openWND :: String -> Maybe POINT -> Maybe POINT -> Events -- where to send the events -> DrawFun -- how to redraw the picture -> Maybe MilliSeconds -- time between timer ticks -> IO WND openWND name pos size events draw tickRate = do checkInitialised clAss <- newClass hwnd <- createWND name wndProc pos size wS_OVERLAPPEDWINDOW Nothing show hwnd False updateWindow hwnd maybe (return ()) (\ rate -> setWinTimer hwnd 1 rate >> return ()) tickRate fmap MkWND (newIORef (Just hwnd)) where wndProc hwnd msg wParam lParam = do -- print msg rs <- safeTry $ do r <- windowProc (sendEvent events) draw (\ wParam -> sendTick events) hwnd msg wParam lParam r `seq` return r -- force it inside the try! case rs of Right a -> return a Left e -> uncaughtError e >> return 0 -- Let's hope this works ok show hwnd iconified = if iconified then do showWindow hwnd sW_SHOWNORMAL -- open "iconified" return () else do showWindow hwnd sW_RESTORE -- open "restored" (ie normal size) bringWindowToTop hwnd -- Note that this code uses a single (static) MSG throughout the whole -- system - let's hope this isn't a problem handleEvents :: IO Bool -> IO () handleEvents userQuit = do -- first wait for a window to be created or for the user prog to quit -- this avoids the race condition that we might quit (for lack of -- any windows) before the user's thread has even had a chance to run. safeTry $ while (fmap not (liftM2 (||) userQuit (fmap not noMoreWindows))) yield -- Ulf uses this instead of handleEvent -- then wait for all windows to be shut down or user to quit safeTry $ while (fmap not (liftM2 (||) userQuit systemQuit)) handleEvent return () where while p s = do { c <- p; if c then s >> while p s else return () } handleEvent :: IO () handleEvent = do yield -- always yield before any blocking operation nowin <- noMoreWindows when (not nowin) $ allocaMessage $ \ lpmsg -> do getMessage lpmsg Nothing translateMessage lpmsg dispatchMessage lpmsg return () ---------------------------------------------------------------- -- The grotty details - opening WNDs, creating classes, etc ---------------------------------------------------------------- className = mkClassName "Graphics.HGL.Win32.WND" newClass :: IO ATOM newClass = do icon <- loadIcon Nothing iDI_APPLICATION cursor <- loadCursor Nothing iDC_ARROW whiteBrush <- getStockBrush wHITE_BRUSH mainInstance <- getModuleHandle Nothing atom <- registerClass ( (cS_HREDRAW .|. cS_VREDRAW), -- redraw if window size Changes mainInstance, (Just icon), (Just cursor), (Just whiteBrush), Nothing, className) --return atom return (maybe undefined id atom) createWND :: String -> WindowClosure -> Maybe POINT -> Maybe POINT -> WindowStyle -> Maybe HMENU -> IO HWND createWND name wndProc posn size style menu = do mainInstance <- getModuleHandle Nothing mbSize <- calcSize size hwnd <- createWindowEx 0 -- Win32.wS_EX_TOPMOST className name style (fmap (fromIntegral.fst) posn) -- x (fmap (fromIntegral.snd) posn) -- y (fmap (fromIntegral.fst) mbSize) -- w (fmap (fromIntegral.snd) mbSize) -- h Nothing -- parent menu mainInstance wndProc addHWND hwnd return hwnd where calcSize :: Maybe POINT -> IO (Maybe POINT) calcSize = maybe (return Nothing) (\ (width, height) -> do (l,t,r,b) <- adjustWindowRect (0,0,width,height) style (isJust menu) return $ Just (r-l, b-t)) windowProc :: (Event -> IO ()) -> -- Event Handler DrawFun -> -- Picture redraw (WPARAM -> IO ()) -> -- tick (HWND -> WindowMessage -> WPARAM -> LPARAM -> IO LRESULT) windowProc send redraw tick hwnd msg wParam lParam | msg == wM_PAINT = paint | msg == wM_MOUSEMOVE = mouseMove lParam | msg == wM_LBUTTONDOWN || msg == wM_LBUTTONDBLCLK = button lParam True True | msg == wM_LBUTTONUP = button lParam True False | msg == wM_RBUTTONDOWN || msg == wM_RBUTTONDBLCLK = button lParam False True | msg == wM_RBUTTONUP = button lParam False False | msg == wM_KEYDOWN = key wParam True | msg == wM_KEYUP = key wParam False | msg == wM_CHAR = char wParam | msg == wM_TIMER = timer wParam | msg == wM_SIZE = resize {- | msg == wM_MOUSEACTIVATE = do hwnd' <- setFocus hwnd if hwnd `eqHWND` hwnd' then return mA_NOACTIVATE -- already had input focus else return mA_ACTIVATEANDEAT -} | msg == wM_DESTROY = destroy | otherwise = defWindowProc (Just hwnd) msg wParam lParam where paint :: IO LRESULT paint = paintWith hwnd (\hdc lpps -> do redraw hwnd hdc return 0 ) button :: LPARAM -> Bool -> Bool -> IO LRESULT button lParam isLeft isDown = do let (y,x) = lParam `divMod` 65536 send (Button {pt = toPoint (x,y), isLeft=isLeft, isDown=isDown}) return 0 key :: WPARAM -> Bool -> IO LRESULT key wParam isDown = do send (Key { keysym = MkKey wParam, isDown = isDown }) -- by returning 1 we let it get translated into a char too return 1 char :: WPARAM -> IO LRESULT char wParam = do send (Char { char = toEnum (fromIntegral wParam) }) return 0 mouseMove :: LPARAM -> IO LRESULT mouseMove lParam = do let (y,x) = lParam `divMod` 65536 send (MouseMove { pt = toPoint (x,y) }) return 0 timer :: WPARAM -> IO LRESULT timer wParam = do tick wParam return 0 resize :: IO LRESULT resize = do -- don't send new size, it may be out of date by the time we -- get round to reading the event send Resize return 0 destroy :: IO LRESULT destroy = do removeHWND hwnd send Closed return 0 paintWith :: HWND -> (HDC -> LPPAINTSTRUCT -> IO a) -> IO a paintWith hwnd p = allocaPAINTSTRUCT $ \ lpps -> do hdc <- beginPaint hwnd lpps a <- p hdc lpps endPaint hwnd lpps return a ---------------------------------------------------------------- -- The open window list ---------------------------------------------------------------- -- It's very important that we close any windows - even if the -- Haskell application fails to do so (or aborts for some reason). -- Therefore we keep a list of open windows and close them all at the -- end. -- persistent list of open windows windows :: IORef [HWND] windows = unsafePerformIO (newIORef []) initialised :: IORef Bool initialised = unsafePerformIO (newIORef False) noMoreWindows :: IO Bool noMoreWindows = fmap null (readIORef windows) -- It's also important that we abort cleanly if an uncaught IOError -- occurs - this flag keeps track of such things hadUncaughtError :: IORef Bool hadUncaughtError = unsafePerformIO (newIORef False) -- We call this if an uncaught error has occured uncaughtError :: Exception -> IO () uncaughtError e = do putStr "Uncaught Error: " print e writeIORef hadUncaughtError True systemQuit :: IO Bool systemQuit = liftM2 (||) (readIORef hadUncaughtError) noMoreWindows beginGraphics :: IO () beginGraphics = do closeAllHWNDs -- just in case any are already open! writeIORef initialised True checkInitialised :: IO () checkInitialised = do init <- readIORef initialised if init then return () else ioError (userError msg) where msg = "Graphics library uninitialised: perhaps you forgot to use runGraphics?" endGraphics :: IO () endGraphics = do closeAllHWNDs writeIORef initialised False closeAllHWNDs :: IO () closeAllHWNDs = do hwnds <- readIORef windows mapM_ destroyWindow hwnds writeIORef windows [] writeIORef hadUncaughtError False -- clear the system addHWND :: HWND -> IO () addHWND hwnd = do hwnds <- readIORef windows writeIORef windows (hwnd:hwnds) -- remove a HWND from windows list removeHWND :: HWND -> IO () removeHWND hwnd = do hwnds <- readIORef windows writeIORef windows (filter (/= hwnd) hwnds)
FranklinChen/hugs98-plus-Sep2006
packages/HGL/Graphics/HGL/Win32/WND.hs
bsd-3-clause
10,283
147
15
2,396
2,969
1,530
1,439
266
3
-- | -- Module : Codec.Binary.Base16 -- Copyright : (c) 2007 Magnus Therning -- License : BSD3 -- -- Implemented as specified in RFC 4648 (<http://tools.ietf.org/html/rfc4648>). -- -- Further documentation and information can be found at -- <http://www.haskell.org/haskellwiki/Library/Data_encoding>. module Codec.Binary.Base16 ( EncIncData(..) , EncIncRes(..) , encodeInc , encode , DecIncData(..) , DecIncRes(..) , decodeInc , decode , chop , unchop ) where import Codec.Binary.Util import Control.Monad import Data.Array import Data.Bits import Data.Maybe import Data.Word import qualified Data.Map as M -- {{{1 enc/dec map _encMap = [ (0, '0'), (1, '1'), (2, '2'), (3, '3'), (4, '4') , (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9') , (10, 'A'), (11, 'B'), (12, 'C'), (13, 'D'), (14, 'E') , (15, 'F') ] -- {{{1 encodeArray encodeArray :: Array Word8 Char encodeArray = array (0, 64) _encMap -- {{{1 decodeMap decodeMap :: M.Map Char Word8 decodeMap = M.fromList [(snd i, fst i) | i <- _encMap] -- {{{1 encode -- | Incremental encoder function. encodeInc :: EncIncData -> EncIncRes String encodeInc EDone = EFinal [] encodeInc (EChunk os) = EPart (concat $ map toHex os) encodeInc -- | Encode data. encode :: [Word8] -> String encode = encoder encodeInc -- {{{1 decode -- | Incremental decoder function. decodeInc :: DecIncData String -> DecIncRes String decodeInc d = dI [] d where dec2 cs = let ds = map (flip M.lookup decodeMap) cs es@[e1, e2] = map fromJust ds o = e1 `shiftL` 4 .|. e2 allJust = and . map isJust in if allJust ds then Just o else Nothing dI [] DDone = DFinal [] [] dI lo DDone = DFail [] lo dI lo (DChunk s) = doDec [] (lo ++ s) where doDec acc s'@(c1:c2:cs) = maybe (DFail acc s') (\ b -> doDec (acc ++ [b]) cs) (dec2 [c1, c2]) doDec acc s = DPart acc (dI s) -- | Decode data. decode :: String -> Maybe [Word8] decode = decoder decodeInc -- {{{1 chop -- | Chop up a string in parts. -- -- The length given is rounded down to the nearest multiple of 2. chop :: Int -- ^ length of individual lines -> String -> [String] chop n "" = [] chop n s = let enc_len | n < 2 = 2 | otherwise = n `div` 2 * 2 in take enc_len s : chop n (drop enc_len s) -- {{{1 unchop -- | Concatenate the strings into one long string. unchop :: [String] -> String unchop = foldr (++) ""
magthe/dataenc
src/Codec/Binary/Base16.hs
bsd-3-clause
2,657
0
15
792
854
485
369
63
5
module Language.Lua.Token where -- | Lua tokens data Token = TokPlus -- ^+ | TokMinus -- ^\- | TokStar -- ^\* | TokSlash -- ^/ | TokPercent -- ^% | TokExp -- ^^ | TokSh -- ^# | TokEqual -- ^== | TokNotequal -- ^~= | TokLEq -- ^<= | TokGEq -- ^\>= | TokLT -- ^< | TokGT -- ^\> | TokAssign -- ^= | TokLParen -- ^( | TokRParen -- ^) | TokLBrace -- ^{ | TokRBrace -- ^} | TokLBracket -- ^\[ | TokRBracket -- ^] | TokDColon -- ^:: | TokSemic -- ^; | TokColon -- ^: | TokComma -- ^, | TokDot -- ^. | TokDDot -- ^.. | TokEllipsis -- ^... | TokDLT -- ^<< | TokDGT -- ^\>\> | TokAmpersand -- ^& | TokPipe -- ^| | TokDSlash -- ^// | TokTilde -- ^~ | TokAnd -- ^and | TokBreak -- ^break | TokDo -- ^do | TokElse -- ^else | TokElseIf -- ^elseif | TokEnd -- ^end | TokFalse -- ^false | TokFor -- ^for | TokFunction -- ^function | TokGoto -- ^goto | TokIf -- ^if | TokIn -- ^in | TokLocal -- ^local | TokNil -- ^nil | TokNot -- ^not | TokOr -- ^or | TokRepeat -- ^repeat | TokReturn -- ^return | TokThen -- ^then | TokTrue -- ^true | TokUntil -- ^until | TokWhile -- ^while | TokFloat -- ^floating point number constant | TokInt -- ^integer number constant | TokSLit -- ^string constant | TokIdent -- ^identifier | TokWhiteSpace -- ^white space | TokComment -- ^comment | TokUntermString -- ^ unterminated string | TokUntermComment -- ^ unterminated comment | TokUnexpected -- ^ unexpected character deriving Eq instance Show Token where show TokPlus = "`+`" show TokMinus = "`-`" show TokStar = "`*`" show TokSlash = "`/`" show TokPercent = "`%`" show TokExp = "`^`" show TokSh = "`#`" show TokEqual = "`==`" show TokNotequal = "`~=`" show TokLEq = "`<=`" show TokGEq = "`>=`" show TokLT = "`<`" show TokGT = "`>`" show TokAssign = "`=`" show TokLParen = "`(`" show TokRParen = "`)`" show TokLBrace = "`{`" show TokRBrace = "`}`" show TokLBracket = "`[`" show TokRBracket = "`]`" show TokDColon = "`::`" show TokSemic = "`;`" show TokColon = "`:`" show TokComma = "`,`" show TokDot = "`.`" show TokDDot = "`..`" show TokEllipsis = "`...`" show TokDLT = "`<<`" show TokDGT = "`>>`" show TokAmpersand = "`&`" show TokPipe = "`|`" show TokDSlash = "`//`" show TokTilde = "`~`" show TokAnd = "`and`" show TokBreak = "`break`" show TokDo = "`do`" show TokElse = "`else`" show TokElseIf = "`elseif`" show TokEnd = "`end`" show TokFalse = "`false`" show TokFor = "`for`" show TokFunction = "`function`" show TokGoto = "`goto`" show TokIf = "`if`" show TokIn = "`in`" show TokLocal = "`local`" show TokNil = "`nil`" show TokNot = "`not`" show TokOr = "`or`" show TokRepeat = "`repeat`" show TokReturn = "`return`" show TokThen = "`then`" show TokTrue = "`true`" show TokUntil = "`until`" show TokWhile = "`while`" show TokWhiteSpace = "white_space" show TokComment = "comment" show TokFloat = "float" show TokInt = "int" show TokSLit = "string" show TokIdent = "identifier" show TokUntermString = "unterminated_string" show TokUntermComment = "unterminated_comment" show TokUnexpected = "unexpected_character"
yav/language-lua
src/Language/Lua/Token.hs
bsd-3-clause
4,723
0
6
2,274
791
462
329
132
0
module SAT.Beispiel where -- -- $Id$ import SAT.Types import Autolib.FiniteMap l1 = Pos (read "x") :: Literal v1 = read "x" :: Variable k1 = Or [Pos $ read "x", Neg $ read "y", Pos $ read "z"] :: Klausel k2 = Or [Neg $ read "x", Pos $ read "y", Pos $ read "z"] :: Klausel formel = And [ k1, k2 ] :: Formel b1 :: Belegung b1 = listToFM [ ( read "x", True), ( read "y", False) ] belegung :: Belegung belegung = listToFM [( read "x", False), ( read "y" , True), ( read "z" , False)]
Erdwolf/autotool-bonn
src/SAT/Beispiel.hs
gpl-2.0
497
2
8
119
232
128
104
13
1
-- | You don't normally need to use this Lex module directly - it is -- called automatically by the parser. (This interface is only exposed -- for debugging purposes.) -- -- This is a hand-written lexer for tokenising the text of an XML -- document so that it is ready for parsing. It attaches position -- information in (line,column) format to every token. The main -- entry point is 'xmlLex'. A secondary entry point, 'xmlReLex', is -- provided for when the parser needs to stuff a string back onto -- the front of the text and re-tokenise it (typically when expanding -- macros). -- -- As one would expect, the lexer is essentially a small finite -- state machine. module Text.XML.HaXml.Lex ( -- * Entry points to the lexer xmlLex -- :: String -> String -> [Token] , xmlReLex -- :: Posn -> String -> [Token] , reLexEntityValue -- :: (String->Maybe String) -> Posn -> String -> [Token] -- * Token types , Token , TokenT(..) , Special(..) , Section(..) ) where import Data.Char import Text.XML.HaXml.Posn data Where = InTag String | NotInTag deriving (Eq) -- | All tokens are paired up with a source position. -- Lexical errors are passed back as a special @TokenT@ value. type Token = (Posn, TokenT) -- | The basic token type. data TokenT = TokCommentOpen -- ^ \<!-- | TokCommentClose -- ^ --> | TokPIOpen -- ^ \<? | TokPIClose -- ^ ?> | TokSectionOpen -- ^ \<![ | TokSectionClose -- ^ ]]> | TokSection Section -- ^ CDATA INCLUDE IGNORE etc | TokSpecialOpen -- ^ \<! | TokSpecial Special -- ^ DOCTYPE ELEMENT ATTLIST etc | TokEndOpen -- ^ \<\/ | TokEndClose -- ^ \/> | TokAnyOpen -- ^ \< | TokAnyClose -- ^ > | TokSqOpen -- ^ \[ | TokSqClose -- ^ \] | TokEqual -- ^ = | TokQuery -- ^ ? | TokStar -- ^ \* | TokPlus -- ^ + | TokAmp -- ^ & | TokSemi -- ^ ; | TokHash -- ^ # | TokBraOpen -- ^ ( | TokBraClose -- ^ ) | TokPipe -- ^ | | TokPercent -- ^ % | TokComma -- ^ , | TokQuote -- ^ \'\' or \"\" | TokName String -- ^ begins with letter, no spaces | TokFreeText String -- ^ any character data | TokNull -- ^ fake token | TokError String -- ^ lexical error deriving (Eq) data Special = DOCTYPEx | ELEMENTx | ATTLISTx | ENTITYx | NOTATIONx deriving (Eq,Show) data Section = CDATAx | INCLUDEx | IGNOREx deriving (Eq,Show) instance Show TokenT where showsPrec _p TokCommentOpen = showString "<!--" showsPrec _p TokCommentClose = showString "-->" showsPrec _p TokPIOpen = showString "<?" showsPrec _p TokPIClose = showString "?>" showsPrec _p TokSectionOpen = showString "<![" showsPrec _p TokSectionClose = showString "]]>" showsPrec p (TokSection s) = showsPrec p s showsPrec _p TokSpecialOpen = showString "<!" showsPrec p (TokSpecial s) = showsPrec p s showsPrec _p TokEndOpen = showString "</" showsPrec _p TokEndClose = showString "/>" showsPrec _p TokAnyOpen = showString "<" showsPrec _p TokAnyClose = showString ">" showsPrec _p TokSqOpen = showString "[" showsPrec _p TokSqClose = showString "]" showsPrec _p TokEqual = showString "=" showsPrec _p TokQuery = showString "?" showsPrec _p TokStar = showString "*" showsPrec _p TokPlus = showString "+" showsPrec _p TokAmp = showString "&" showsPrec _p TokSemi = showString ";" showsPrec _p TokHash = showString "#" showsPrec _p TokBraOpen = showString "(" showsPrec _p TokBraClose = showString ")" showsPrec _p TokPipe = showString "|" showsPrec _p TokPercent = showString "%" showsPrec _p TokComma = showString "," showsPrec _p TokQuote = showString "' or \"" showsPrec _p (TokName s) = showString s showsPrec _p (TokFreeText s) = showString s showsPrec _p TokNull = showString "(null)" showsPrec _p (TokError s) = showString s --trim, revtrim :: String -> String --trim = f . f where f = reverse . dropWhile isSpace --revtrim = f.reverse.f where f = dropWhile isSpace --revtrim = reverse . dropWhile (=='\n') -- most recently used defn. emit :: TokenT -> Posn -> Token emit tok p = forcep p `seq` (p,tok) lexerror :: String -> Posn -> [Token] lexerror s p = [(p, TokError ("Lexical error:\n "++s))] skip :: Int -> Posn -> String -> (Posn->String->[Token]) -> [Token] skip n p s k = k (addcol n p) (drop n s) blank :: ([Where]->Posn->String->[Token]) -> [Where]-> Posn-> String-> [Token] blank _ (InTag t:_) p [] = lexerror ("unexpected EOF within "++t) p blank _ _ _ [] = [] blank k w p (' ': s) = blank k w (addcol 1 p) s blank k w p ('\t':s) = blank k w (tab p) s blank k w p ('\n':s) = blank k w (newline p) s blank k w p ('\r':s) = blank k w p s blank k w p ('\xa0': s) = blank k w (addcol 1 p) s blank k w p s = k w p s prefixes :: String -> String -> Bool [] `prefixes` _ = True (x:xs) `prefixes` (y:ys) = x==y && xs `prefixes` ys (_:_) `prefixes` [] = False --error "unexpected EOF in prefix" textUntil, textOrRefUntil :: [Char] -> TokenT -> [Char] -> Posn -> Posn -> [Char] -> (Posn->String->[Token]) -> [Token] textUntil close _tok _acc pos p [] _k = lexerror ("unexpected EOF while looking for closing token "++close ++"\n to match the opening token in "++show pos) p textUntil close tok acc pos p (s:ss) k | close `prefixes` (s:ss) = emit (TokFreeText (reverse acc)) pos: emit tok p: skip (length close-1) (addcol 1 p) ss k | tok==TokSemi && length acc >= 8 -- special case for repairing broken & = emit (TokFreeText "amp") pos: emit tok pos: k (addcol 1 pos) (reverse acc++s:ss) | isSpace s = textUntil close tok (s:acc) pos (white s p) ss k | otherwise = textUntil close tok (s:acc) pos (addcol 1 p) ss k textOrRefUntil close _tok _acc pos p [] _k = lexerror ("unexpected EOF while looking for closing token "++close ++"\n to match the opening token in "++show pos) p textOrRefUntil close tok acc pos p (s:ss) k | close `prefixes` (s:ss) = emit (TokFreeText (reverse acc)) pos: emit tok p: skip (length close-1) (addcol 1 p) ss k | s=='&' = (if not (null acc) then (emit (TokFreeText (reverse acc)) pos:) else id) (emit TokAmp p: textUntil ";" TokSemi "" p (addcol 1 p) ss (\p' i-> textOrRefUntil close tok "" p p' i k)) | isSpace s = textOrRefUntil close tok (s:acc) pos (white s p) ss k | otherwise = textOrRefUntil close tok (s:acc) pos (addcol 1 p) ss k ---- -- | The first argument to 'xmlLex' is the filename (used for source positions, -- especially in error messages), and the second is the string content of -- the XML file. xmlLex :: String -> String -> [Token] xmlLex filename = xmlAny [] (posInNewCxt filename Nothing) -- | 'xmlReLex' is used when the parser expands a macro (PE reference). -- The expansion of the macro must be re-lexed as if for the first time. xmlReLex :: Posn -> String -> [Token] xmlReLex p s | "INCLUDE" `prefixes` s = emit (TokSection INCLUDEx) p: k 7 | "IGNORE" `prefixes` s = emit (TokSection IGNOREx) p: k 6 | otherwise = blank xmlAny [] p s where k n = skip n p s (blank xmlAny []) -- | 'reLexEntityValue' is used solely within parsing an entityvalue. -- Normally, a PERef is logically separated from its surroundings by -- whitespace. But in an entityvalue, a PERef can be juxtaposed to -- an identifier, so the expansion forms a new identifier. -- Thus the need to rescan the whole text for possible PERefs. reLexEntityValue :: (String->Maybe String) -> Posn -> String -> [Token] reLexEntityValue lookup p s = textOrRefUntil "%" TokNull [] p p (expand s++"%") (xmlAny []) where expand [] = [] expand ('%':xs) = let (sym,rest) = break (==';') xs in case lookup sym of Just val -> expand val ++ expand (tail rest) Nothing -> "%"++sym++";"++ expand (tail rest) -- hmmm expand (x:xs) = x: expand xs --xmltop :: Posn -> String -> [Token] --xmltop p [] = [] --xmltop p s -- | "<?" `prefixes` s = emit TokPIOpen p: next 2 (xmlPI [InTag "<?...?>"]) -- | "<!--" `prefixes` s = emit TokCommentOpen p: next 4 (xmlComment []) -- | "<!" `prefixes` s = emit TokSpecialOpen p: next 2 (xmlSpecial [InTag "<!...>"]) -- | otherwise = lexerror "expected <?xml?> or <!DOCTYPE>" p -- where next n k = skip n p s k xmlPI, xmlPIEnd, xmlComment, xmlAny, xmlTag, xmlSection, xmlSpecial :: [Where] -> Posn -> String -> [Token] xmlPI w p s = xmlName p s "name of processor in <? ?>" (blank xmlPIEnd w) xmlPIEnd w p s = textUntil "?>" TokPIClose "" p p s (blank xmlAny (tail w)) xmlComment w p s = textUntil "-->" TokCommentClose "" p p s (blank xmlAny w) -- Note: the order of the clauses in xmlAny is very important. -- Some matches must precede the NotInTag test, the rest must follow it. xmlAny (InTag t:_) p [] = lexerror ("unexpected EOF within "++t) p xmlAny _ _ [] = [] xmlAny w p s@('<':ss) | "?" `prefixes` ss = emit TokPIOpen p: skip 2 p s (xmlPI (InTag "<?...?>":w)) | "!--" `prefixes` ss = emit TokCommentOpen p: skip 4 p s (xmlComment w) | "![" `prefixes` ss = emit TokSectionOpen p: skip 3 p s (xmlSection w) | "!" `prefixes` ss = emit TokSpecialOpen p: skip 2 p s (xmlSpecial (InTag "<!...>":w)) | "/" `prefixes` ss = emit TokEndOpen p: skip 2 p s (xmlTag (InTag "</...>":tail w)) | otherwise = emit TokAnyOpen p: skip 1 p s (xmlTag (InTag "<...>":NotInTag:w)) xmlAny (_:_:w) p s@('/':ss) | ">" `prefixes` ss = emit TokEndClose p: skip 2 p s (xmlAny w) xmlAny w p ('&':ss) = emit TokAmp p: textUntil ";" TokSemi "" p (addcol 1 p) ss (xmlAny w) xmlAny w@(NotInTag:_) p s = xmlContent "" w p p s -- everything below here is implicitly InTag. xmlAny w p ('>':ss) = emit TokAnyClose p: xmlAny (tail w) (addcol 1 p) ss xmlAny w p ('[':ss) = emit TokSqOpen p: blank xmlAny (InTag "[...]":w) (addcol 1 p) ss xmlAny w p (']':ss) | "]>" `prefixes` ss = emit TokSectionClose p: skip 3 p (']':ss) (xmlAny (tail w)) | otherwise = emit TokSqClose p: blank xmlAny (tail w) (addcol 1 p) ss xmlAny w p ('(':ss) = emit TokBraOpen p: blank xmlAny (InTag "(...)":w) (addcol 1 p) ss xmlAny w p (')':ss) = emit TokBraClose p: blank xmlAny (tail w) (addcol 1 p) ss xmlAny w p ('=':ss) = emit TokEqual p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('*':ss) = emit TokStar p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('+':ss) = emit TokPlus p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('?':ss) = emit TokQuery p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('|':ss) = emit TokPipe p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('%':ss) = emit TokPercent p: blank xmlAny w (addcol 1 p) ss xmlAny w p (';':ss) = emit TokSemi p: blank xmlAny w (addcol 1 p) ss xmlAny w p (',':ss) = emit TokComma p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('#':ss) = emit TokHash p: blank xmlAny w (addcol 1 p) ss xmlAny w p ('"':ss) = emit TokQuote p: textOrRefUntil "\"" TokQuote "" p1 p1 ss (xmlAny w) where p1 = addcol 1 p xmlAny w p ('\'':ss) = emit TokQuote p: textOrRefUntil "'" TokQuote "" p1 p1 ss (xmlAny w) where p1 = addcol 1 p xmlAny w p s | isSpace (head s) = blank xmlAny w p s | isAlphaNum (head s) || (head s)`elem`":_" = xmlName p s "some kind of name" (blank xmlAny w) | otherwise = lexerror ("unrecognised token: "++take 4 s) p xmlTag w p s = xmlName p s "tagname for element in < >" (blank xmlAny w) xmlSection = blank xmlSection0 where xmlSection0 w p s | "CDATA[" `prefixes` s = emit (TokSection CDATAx) p: accum w p s 6 | "INCLUDE" `prefixes` s = emit (TokSection INCLUDEx) p: k w p s 7 | "IGNORE" `prefixes` s = emit (TokSection IGNOREx) p: k w p s 6 | "%" `prefixes` s = emit TokPercent p: k w p s 1 | otherwise = lexerror ("expected CDATA, IGNORE, or INCLUDE, but got " ++take 7 s) p accum w p s n = let p0 = addcol n p in textUntil "]]>" TokSectionClose "" p0 p0 (drop n s) (blank xmlAny w) k w p s n = skip n p s (xmlAny ({-InTag "<![section[ ... ]]>": -}w)) xmlSpecial w p s | "DOCTYPE" `prefixes` s = emit (TokSpecial DOCTYPEx) p: k 7 | "ELEMENT" `prefixes` s = emit (TokSpecial ELEMENTx) p: k 7 | "ATTLIST" `prefixes` s = emit (TokSpecial ATTLISTx) p: k 7 | "ENTITY" `prefixes` s = emit (TokSpecial ENTITYx) p: k 6 | "NOTATION" `prefixes` s = emit (TokSpecial NOTATIONx) p: k 8 | otherwise = lexerror ("expected DOCTYPE, ELEMENT, ENTITY, ATTLIST, or NOTATION," ++" but got "++take 7 s) p where k n = skip n p s (blank xmlAny w) xmlName :: Posn -> [Char] -> [Char] -> (Posn->[Char]->[Token]) -> [Token] xmlName p (s:ss) cxt k | isAlphaNum s || s==':' || s=='_' = gatherName (s:[]) p (addcol 1 p) ss k | otherwise = lexerror ("expected a "++cxt++", but got char "++show s) p where gatherName acc pos p [] k = emit (TokName (reverse acc)) pos: k p [] -- lexerror ("unexpected EOF in name at "++show pos) p gatherName acc pos p (s:ss) k | isAlphaNum s || s `elem` ".-_:" = gatherName (s:acc) pos (addcol 1 p) ss k | otherwise = emit (TokName (reverse acc)) pos: k p (s:ss) xmlName p [] cxt _ = lexerror ("expected a "++cxt++", but got end of input") p xmlContent :: [Char] -> [Where] -> Posn -> Posn -> [Char] -> [Token] xmlContent acc _w _pos p [] = if all isSpace acc then [] else lexerror "unexpected EOF between tags" p xmlContent acc w pos p (s:ss) | elem s "<&" = {- if all isSpace acc then xmlAny w p (s:ss) else -} emit (TokFreeText (reverse acc)) pos: xmlAny w p (s:ss) | isSpace s = xmlContent (s:acc) w pos (white s p) ss | otherwise = xmlContent (s:acc) w pos (addcol 1 p) ss --ident :: (String->TokenT) -> -- Posn -> String -> [String] -> -- (Posn->String->[String]->[Token]) -> [Token] --ident tok p s ss k = -- let (name,s0) = span (\c-> isAlphaNum c || c `elem` "`-_#.'/\\") s -- in emit (tok name) p: skip (length name) p s ss k
ryanfan/courseography
dependencies/HaXml-1.25.3/src/Text/XML/HaXml/Lex.hs
gpl-3.0
15,483
64
15
4,840
5,235
2,670
2,565
256
4
{-# LANGUAGE PatternSynonyms, TypeOperators, TypeFamilies, MultiParamTypeClasses, GADTs #-} module ClassOperator where -- | Class with fixity, including associated types class a ><> b where type a <>< b :: * data a ><< b (>><), (<<>) :: a -> b -> () -- | Multiple fixities (**>), (**<), (>**), (<**) :: a -> a -> () infixr 1 ><> infixl 2 <>< infixl 3 ><< infixr 4 >>< infixl 5 <<> infixr 8 **>, >** infixl 8 **<, <**
ezyang/ghc
testsuite/tests/typecheck/should_fail/ClassOperator.hs
bsd-3-clause
432
0
9
94
124
82
42
14
0
{-# LANGUAGE DeriveDataTypeable #-} module T4003A where import T4003B import Data.Data data MyId = MyId deriving (Data, Typeable) data HsExpr id = HsOverLit (HsOverLit id) | HsBracketOut (HsExpr MyId) deriving (Data, Typeable)
siddhanathan/ghc
testsuite/tests/rename/should_compile/T4003A.hs
bsd-3-clause
242
0
8
47
69
40
29
10
0
module Main (main) where -- See Trac #149 -- Currently (with GHC 7.0) the CSE works, just, -- but it's delicate. import System.CPUTime main :: IO () main = print $ playerMostOccur2 [1..m] m :: Int m = 22 playerMostOccur2 :: [Int] -> Int playerMostOccur2 [a] = a playerMostOccur2 (x:xs) | numOccur x (x:xs) > numOccur pmo xs = x | otherwise = pmo where pmo = playerMostOccur2 xs numOccur :: Int -> [Int] -> Int numOccur i is = length is
ghc-android/ghc
testsuite/tests/perf/should_run/T149_B.hs
bsd-3-clause
451
0
11
97
167
89
78
14
1
{- This program crashed GHC 2.03 From: Marc van Dongen <[email protected]> Date: Sat, 31 May 1997 14:35:40 +0100 (BST) zonkIdOcc: g_aoQ panic! (the `impossible' happened): lookupBindC:no info! for: g_aoQ (probably: data dependencies broken by an optimisation pass) static binds for: Tmp.$d1{-rmM,x-} local binds for: -} module ShouldFail where data AB p q = A | B p q g :: (Ord p,Ord q) => (AB p q) -> Bool g (B _ _) = g A
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail072.hs
bsd-3-clause
471
0
8
125
72
40
32
5
1
module SpecHelper where import Control.Monad ((>=>)) import System.Directory (doesFileExist, doesDirectoryExist) import System.IO.Temp (withSystemTempDirectory) import Dotfiles import Dotfiles.Config import Dotfiles.Commands exists :: FilePath -> IO Bool exists path = or `fmap` sequence [doesFileExist path, doesDirectoryExist path] mockEnv :: FilePath -> IO Env mockEnv tmpDir = do env <- readEnv tmpDir runCommand env install [] return env withEnv :: (Env -> IO ()) -> IO () withEnv action = withSystemTempDirectory "hdotfiles_test" (mockEnv >=> action)
ilya-yurtaev/hdotfiles
tests/SpecHelper.hs
mit
631
0
9
146
188
99
89
16
1
module GridC.Util where eitherMap :: (a -> c) -> (b -> d) -> Either a b -> Either c d eitherMap a b c = case c of Left d -> Left (a d) Right e -> Right (b e) binOps :: [[(String, String)]] binOps = [ [("*", "mul"), ("/", "div"), ("%", "mod")], [("+", "add"), ("-", "sub")], [(">", "greater"), ("<", "less")], [("==", "equal"), ("!=", "nequal")], [("&", "band")], [("^", "bxor")], [("&&", "and")] ]
lessandro/gridc
src/GridC/Util.hs
mit
472
0
10
146
250
149
101
15
2
module Hircules.Config (configDir, logDir) where import System.Environment (getEnv) import System.FilePath ((</>)) import System.IO.Unsafe (unsafePerformIO) homeDir :: FilePath homeDir = unsafePerformIO $ getEnv "HOME" configDir :: FilePath configDir = homeDir </> configDirName configDirName :: FilePath configDirName = ".hircules" logDir :: FilePath logDir = configDir </> logDirName logDirName :: FilePath logDirName = "logs"
juhp/hircules
src/Hircules/Config.hs
mit
435
0
6
57
112
67
45
14
1
module TClasses where -- : set expandtab ts=2 ruler number spell -- daw -- : syntax enable --------------------------- -- Type Class Instances -- Instances -- Deriving -- Defining type classes -- Subclasses ---------------------------- -- Type Class Instances -- Instances where we can add on instances to extend Type Classes further -- with deriving we can add in these instances in obvious ways rather than by definition by definition -- el2m :: Eq a => a -> [a] -> Bool el2m _ [] = False el2m x (y:ys) | x==y = True | otherwise = el2m x ys -- Haskell doesn't have a built in equality test for functions it would have to be added. -- Functions don't have built in equality tests. -- but we can have a known answer test (KAT) -- to test for equality between colors -- we have to create an instance of equality for our RGB type. data RGB = RGB Int Int Int -- > :t RGB -- RGB :: Int -> Int -> Int -> RGB instance Eq RGB where (RGB r1 g1 b1) == (RGB r2 g2 b2) = (r1 == r2) && (g1 == g2) && (b1 == b2) instance Show RGB where show (RGB r g b) = "RGB " ++ (show r) ++ " " ++ (show g) ++ " " ++ (show b) colors = [RGB 255 0 0, RGB 0 255 0, RGB 0 0 255] green = RGB 0 255 0 greenInColors = elem green colors -- *TClasses> elem green colors -- True -- *TClasses> show (RGB 255 255 255) -- "RGB 255 255 255" data Mayb2 a = Nothing' | Just' a -- because Mayb2 a is defined with an Eq type no matter what a is; -- x == y have values of type a and will always be equal, whoops! -- => is the context of the type-class instance -- and parameterized Types might require additional constraints -- for simple things this is straight forward -- but more complex examples will require knowing about the "context instance". -- we've had to add an instance here instance (Eq a) => Eq (Mayb2 a) where Nothing' == Nothing' = True Nothing' == (Just' _) = False (Just' _) == Nothing' = False (Just' x) == (Just' y) = x == y data Person = Person String Int Int instance Eq Person where (Person name1 age1 height1) == (Person name2 age2 height2) = (name1 == name2) && (age1 == age2) && (height1 == height2) -- so that we don't have to do this for every Type constraint we can use the keyword deriving -- data RGB' = RGB Int Int Int -- deriving Eq --------------------------- ---- deriving ----------- --------------------------- -- only legal addtions are possible -- deriving adds on obvious type-classes like -- Eq where each component == component -- Ord where (<),(>),(<=),(>=) component to component -- Show gives us show "component" -- "[Constructor-name] {argument-1} {argument-2}..." -- Read which gives the read function -- Deriving-parse output of default show -- Minimum complete definitions -- must be satisfied {- class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool -- Defined in `GHC.Classes' -- Default definitions -- we create new type classes when to not have them would require excessive amounts of definitions -- to get polymorphic functionality on a given function. -- Subclasses work as refinements on the Superclass. Eq just allows for comparison where as Ord which inherits from Eq allows other comparisons (<),(>),(<=),(>=) which would not be possible to do with out first checking if two elements were the same or not. {- class Eq a => Ord a where compare :: a -> a -> Ordering (<) :: a -> a -> Bool (>=) :: a -> a -> Bool (>) :: a -> a -> Bool (<=) :: a -> a -> Bool max :: a -> a -> a min :: a -> a -> a -- Defined in `GHC.Classes' -} -- note that the Class definition class Eq a => Ord a where shows that Ord is a Subclass of Eq. -- compare :: a -> a -> Ordering -- note that ordering is defined thus... -- data Ordering = LT | EQ | GT -- Defined in `GHC.Types' {- class (Num a, Ord a) => Real a where toRational :: a -> Rational -- Defined in `GHC.Real' -}
HaskellForCats/HaskellForCats
MenaBeginning/Ch008/2014-0205CustTypeClass.hs
mit
4,016
9
13
982
574
321
253
-1
-1
module Gshell.Names ( gshellDirName , gshellDir , commitsDirName , commitsDir , commitFileName , commitFile , revDirName , revDir , mountDirName , mountDir , workDirName , workDir , workHelperFileName , workHelperFile , parentsFileName , parentsFile , masterFileName , masterFile , timeStampFileName , timeStampFile , unionfsLogFileName , unionfsLogFile , logFileName , logFile , generateHash , generateId , gshellInited , mergeOf ) where import Control.Applicative import Data.List import System.FilePath import System.Random gshellDirName = ".gshell" gshellDir path = path </> gshellDirName commitsDirName = "commits" commitsDir path = path </> gshellDirName </> commitsDirName commitFileName = "commit" commitFile path revName = path </> gshellDirName </> commitsDirName </> revName </> mountDirName revDirName = "rev" revDir path = path </> gshellDirName </> commitsDirName </> revDirName mountDirName = "to-mount" mountDir path revName = path </> gshellDirName </> commitsDirName </> revName </> mountDirName workDirName = "work-id" workDir path = path </> workDirName workHelperFileName = "work-information" workHelperFile path workId = path </> gshellDirName </> (workDirName ++ workId) </> workHelperFileName parentsFileName = "parents" parentsFile path revName = path </> gshellDirName </> commitsDirName </> revName </> parentsFileName masterFileName = "master" masterFile path = path </> gshellDirName </> masterFileName timeStampFileName = "time-stamp" timeStampFile path revName = path </> gshellDirName </> commitsDirName </> revName </> timeStampFileName unionfsLogFileName = "unionfs.log" unionfsLogFile path fullWorkDirName = path </> gshellDirName </> fullWorkDirName </> unionfsLogFileName logFileName = "read.log" logFile path revName = path </> gshellDirName </> commitsDirName </> revName </> logFileName generateHash :: IO FilePath generateHash = do g <- newStdGen let a = take 10 $ (randomRs ('a', 'z') g) let b = take 10 $ (randomRs ('0', '9') g) let hash = concat $ zipWith (\a b -> a:[b]) a b return $ "-" ++ hash generateId :: IO FilePath generateId = do g <- newStdGen let c = (randomRs ('0', '9') g) let a = take 2 $ c let b = take 2 $ drop 2 c return $ a ++ b gshellInited :: Bool -> String gshellInited a = "gshell is " ++ (if a then "already" else "not") ++ " inited" mergeOf :: [FilePath] -> String mergeOf revs = concat $ ["Merge of: "] ++ (intersperse ", " revs)
ctlab/gShell
src/Gshell/Names.hs
mit
3,057
4
17
1,013
726
384
342
74
2
module LLVM.Codegen.Constant ( ci1, ci8, ci16, ci32, ci64, cf32, cf64, cfloat, cdouble, cnull, cundef, cstruct, cstructpack, carray, cvector, cstring, cstringz, Constant(..) ) where import Data.Char import LLVM.General.AST import qualified LLVM.General.AST.Float as F import qualified LLVM.General.AST.Constant as C ci1, ci8, ci16, ci32, ci64 :: (Integral a) => a -> C.Constant ci1 = C.Int 1 . fromIntegral ci8 = C.Int 8 . fromIntegral ci16 = C.Int 16 . fromIntegral ci32 = C.Int 32 . fromIntegral ci64 = C.Int 64 . fromIntegral cf32, cfloat :: Float -> C.Constant cf32 = C.Float . F.Single cfloat = cf32 cf64, cdouble :: Double -> C.Constant cf64 = C.Float . F.Double cdouble = cf64 cnull :: Type -> C.Constant cnull ty = C.Null ty cundef :: Type -> C.Constant cundef = C.Undef cstruct :: [C.Constant] -> C.Constant cstruct values = C.Struct Nothing False values cstructpack :: [C.Constant] -> C.Constant cstructpack values = C.Struct Nothing False values carray :: Type -> [C.Constant] -> C.Constant carray ty values = C.Array ty values cvector :: [C.Constant] -> C.Constant cvector values = C.Vector values -- | Null terminated constant string cstringz :: String -> C.Constant cstringz s = carray (IntegerType 8) chars where chars = map (ci8 . ord) s ++ [ci8 (0 :: Int)] -- | Non-null terminated constant string cstring :: String -> C.Constant cstring s = carray (IntegerType 8) chars where chars = map (ci8 . ord) s -- | Conversion between Haskell numeric values and LLVM constants class Constant a where toConstant :: a -> C.Constant instance Constant Bool where toConstant False = ci1 (0 :: Int) toConstant True = ci1 (1 :: Int) instance Constant Int where toConstant = ci64 instance Constant Float where toConstant = cf32 instance Constant Double where {-toConstant = cf64-}
sdiehl/llvm-codegen
src/LLVM/Codegen/Constant.hs
mit
1,856
0
10
362
646
361
285
58
1
{-# LANGUAGE OverloadedStrings #-} import Web.Uploadcare main :: IO () main = do client <- newDemoClient efile <- getFile client "1d4d470b-8048-4c00-8ae6-9be332e7d2b1" putStrLn $ case efile of Right file -> originalFileUrl file Left err -> err
uploadcare/uploadcare-haskell
example/file.hs
mit
276
0
11
67
73
34
39
9
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} module Numeric.Sampling.Util where import Control.Lens import Control.Monad import Control.Monad.Random import Data.Traversable import Linear.Affine import Linear.Vector import Numeric.Sampling.Types unP :: Point f x -> f x unP (P x) = x {-# INLINE unP #-} (^+^~) :: (Num a, Additive f) => Setting (->) s t (f a) (f a) -> f a -> s -> t l ^+^~ a = over l (^+^ a) {-# INLINE (^+^~) #-} (.+^~) :: (Num a, Affine f) => Setting (->) s t (f a) (f a) -> Diff f a -> s -> t l .+^~ a = over l (.+^ a) {-# INLINE (.+^~) #-} -- | A Hamiltonian leapfrog integration step. leapfrog :: (Additive f, Fractional a) => Scalar f a -> Grad f a -> StateS f a -> StateS f a leapfrog eps field = leap . frog . leap where leap h = h & mom ^+^~ (eps/2 *^ field (h ^. pos)) frog h = h & pos .+^~ (eps/2 *^ (h ^. mom)) {-# INLINE leapfrog #-} flickStateS :: (Traversable f, MonadRandom m, Random a) => Flick m a -> Point f a -> m (StateS f a) flickStateS flick x = liftM (StateS x . unP) (flick x) -- | Not particularly great random momentum "flicking" uniformMomentumStateS :: (Traversable f, MonadRandom m, Random a) => Point f a -> m (StateS f a) uniformMomentumStateS x = liftM (StateS x . unP) (uniformFlick x) uniformFlick :: (MonadRandom m, Random a) => Flick m a uniformFlick = Data.Traversable.mapM (const getRandom)
tel/mcmc
src/Numeric/Sampling/Util.hs
mit
1,396
0
12
296
597
311
286
34
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} module Z80.Operations ( -- * Load Group Load , ld , Stack , push , pop -- * Exchange, Block Transfer, and Search Group , Exchange , ex , exx , ldi , ldir , ldd , lddr , cpi , cpir , cpd , cpdr -- * 8-Bit Arithmetic Group , Arithmetic8 , sub , and , or , xor , cp , Inc , inc , dec -- * General-Purpose Arithmetic and CPU Control Groups , Arithmetic , CarryArithmetic , daa , cpl , neg , ccf , scf , nop , halt , di , ei , im -- * 8-Bit / 16-Bit Arithmetic Group , add , adc , sbc -- * Rotate and Shift Group , RotateShift , rlca , rla , rrca , rra , rlc , rl , rrc , rr , sla , sra , srl , rld , rrd -- * Bit Set, Reset, and Test Group , Bitwise , bit , set , res -- * Jump Group , Jump , jp , JumpRelative , jr , djnz , ($-) , ($+) -- * Call and Return Group , Call , call , Return , ret , reti , retn , rst -- * Input and Output Group , InOut , in_ , ini , inir , ind , indr , out , outi , otir , outd , otdr ) where import Data.Bits hiding (xor, bit) import Data.Word import Z80.Assembler import Z80.Operands import Control.Applicative ((<$>)) import Control.Monad ((>=>)) import Prelude hiding (and, or) class Load tgt src where ld :: tgt -> src -> Z80ASM instance Load Reg8 Reg8 where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load Reg8 C where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load C Reg8 where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load A Reg8 where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load Reg8 A where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load A C where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance Load C A where ld r r' = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. encodeReg8 r'] instance (n ~ Word8) => Load Reg8 n where ld r n = code [encodeReg8 r .<. 3 .|. 6, fromIntegral n] instance (n ~ Word8) => Load A n where ld r n = code [encodeReg8 r .<. 3 .|. 6, fromIntegral n] instance (n ~ Word8) => Load C n where ld r n = code [encodeReg8 r .<. 3 .|. 6, fromIntegral n] instance Load Reg8 [HL] where ld r [HL] = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6] ld _ x = derefError x instance Load A [HL] where ld r [HL] = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6] ld _ x = derefError x instance Load C [HL] where ld r [HL] = code [1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6] ld _ x = derefError x instance Load [HL] Reg8 where ld [HL] r = code [1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r] ld x _ = derefError x instance Load [HL] A where ld [HL] r = code [1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r] ld x _ = derefError x instance Load [HL] C where ld [HL] r = code [1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r] ld x _ = derefError x instance (n ~ Word8) => Load [HL] n where ld [HL] n = code [0x36, n] ld x _ = derefError x instance Load Reg8 [RegIx] where ld r [i :+ ofst] = code [encodeOrError i, 1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6, ofst] ld r [i] = ld r [i+0] ld _ x = derefError x instance Load A [RegIx] where ld r [i :+ ofst] = code [encodeOrError i, 1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6, ofst] ld r [i] = ld r [i+0] ld _ x = derefError x instance Load C [RegIx] where ld r [i :+ ofst] = code [encodeOrError i, 1 .<. 6 .|. encodeReg8 r .<. 3 .|. 6, ofst] ld r [i] = ld r [i+0] ld _ x = derefError x instance Load [RegIx] Reg8 where ld [i :+ ofst] r = code [encodeOrError i, 1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r, ofst] ld [i] r = ld [i+0] r ld x _ = derefError x instance Load [RegIx] A where ld [i :+ ofst] r = code [encodeOrError i, 1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r, ofst] ld [i] r = ld [i+0] r ld x _ = derefError x instance Load [RegIx] C where ld [i :+ ofst] r = code [encodeOrError i, 1 .<. 6 .|. 6 .<. 3 .|. encodeReg8 r, ofst] ld [i] r = ld [i+0] r ld x _ = derefError x instance (n ~ Word8) => Load [RegIx] n where ld [i :+ ofst] n = code [encodeOrError i, 0x36, ofst, n] ld [i] n = ld [i+0] n ld x _ = derefError x instance Load A [BC] where ld A [BC] = code [0x0a] ld _ x = derefError x instance Load A [DE] where ld A [DE] = code [0x1a] ld _ x = derefError x instance Load [BC] A where ld [BC] A = code [0x02] ld x _ = derefError x instance Load [DE] A where ld [DE] A = code [0x12] ld x _ = derefError x instance (nn ~ Word16) => Load A [nn] where ld A [nn] = code [0x3a, lo nn, hi nn] ld _ x = derefError x instance (nn ~ Word16) => Load [nn] A where ld [nn] A = code [0x32, lo nn, hi nn] ld x _ = derefError x instance Load A I where ld A I = code [0xed, 0x57] instance Load I A where ld I A = code [0xed, 0x47] instance Load A R where ld A R = code [0xed, 0x5f] instance Load R A where ld R A = code [0xed, 0x4f] instance (Reg16 dd, nn ~ Word16) => Load dd nn where ld dd nn = code [encodeReg16 dd .<. 4 .|. 0x01, lo nn, hi nn] instance (nn ~ Word16) => Load HL nn where ld dd nn = code [encodeReg16 dd .<. 4 .|. 0x01, lo nn, hi nn] instance (nn ~ Word16) => Load SP nn where ld dd nn = code [encodeReg16 dd .<. 4 .|. 0x01, lo nn, hi nn] instance (nn ~ Word16) => Load RegIx nn where ld i nn = code [encodeReg16 i, 0x21, lo nn, hi nn] instance (nn ~ Word16) => Load HL [nn] where ld HL [nn] = code [0x2a, lo nn, hi nn] ld _ x = derefError x instance (nn ~ Word16) => Load [nn] HL where ld [nn] HL = code [0x22, lo nn, hi nn] ld x _ = derefError x -- NOTE Z80 documentation says you should be able to pass HL here, but that -- seems to clash with the previous instance, which is HL-specific? instance (Reg16 dd, nn ~ Word16) => Load dd [nn] where ld dd [nn] = code [0xed, 0x01 .<. 6 .|. encodeReg16 dd .<. 4 .|. 0xb, lo nn, hi nn] ld _ x = derefError x instance (nn ~ Word16) => Load SP [nn] where ld dd [nn] = code [0xed, 0x01 .<. 6 .|. encodeReg16 dd .<. 4 .|. 0xb, lo nn, hi nn] ld _ x = derefError x instance (Reg16 dd, nn ~ Word16) => Load [nn] dd where ld [nn] dd = code [0xed, 0x01 .<. 6 .|. encodeReg16 dd .<. 4 .|. 0x3, lo nn, hi nn] ld x _ = derefError x instance (nn ~ Word16) => Load [nn] SP where ld [nn] dd = code [0xed, 0x01 .<. 6 .|. encodeReg16 dd .<. 4 .|. 0x3, lo nn, hi nn] ld x _ = derefError x instance (nn ~ Word16) => Load RegIx [nn] where ld i [nn] = code [encodeReg16 i, 0x2a, lo nn, hi nn] ld _ x = derefError x instance (nn ~ Word16) => Load [nn] RegIx where ld [nn] i = code [encodeReg16 i, 0x22, lo $ fromIntegral nn, hi $ fromIntegral nn] ld x _ = derefError x instance Load SP HL where ld SP HL = code [0xf9] instance Load SP RegIx where ld SP i = code [encodeReg16 i, 0xf9] class Stack reg where push :: reg -> Z80ASM pop :: reg -> Z80ASM instance (Reg16 qq) => Stack qq where push qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x5] pop qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x1] instance Stack HL where push qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x5] pop qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x1] instance Stack AF where push qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x5] pop qq = code [0x3 .<. 6 .|. encodeReg16 qq .<. 4 .|. 0x1] instance Stack RegIx where push i = code [encodeReg16 i, 0xe5] pop i = code [encodeReg16 i, 0xe1] class Exchange reg reg' where ex :: reg -> reg' -> Z80ASM instance Exchange DE HL where ex DE HL = code [0xeb] instance Exchange AF AF' where ex AF AF' = code [0x08] instance Exchange [SP] HL where ex [SP] HL = code [0xe3] ex x _ = derefError x instance Exchange [SP] RegIx where ex [SP] i = code [encodeReg16 i, 0xe3] ex x _ = derefError x exx :: Z80ASM exx = code [0xd9] ldi :: Z80ASM ldi = code [0xed, 0xa0] ldir :: Z80ASM ldir = code [0xed, 0xb0] ldd :: Z80ASM ldd = code [0xed, 0xa8] lddr :: Z80ASM lddr = code [0xed, 0xb8] cpi :: Z80ASM cpi = code [0xed, 0xa1] cpir :: Z80ASM cpir = code [0xed, 0xb1] cpd :: Z80ASM cpd = code [0xed, 0xa9] cpdr :: Z80ASM cpdr = code [0xed, 0xb9] class Arithmetic8 operand where sub :: operand -> Z80ASM and :: operand -> Z80ASM or :: operand -> Z80ASM xor :: operand -> Z80ASM cp :: operand -> Z80ASM instance Arithmetic8 A where sub r = code [0x1 .<. 7 .|. 0x2 .<. 3 .|. encodeReg8 r] and r = code [0x1 .<. 7 .|. 0x4 .<. 3 .|. encodeReg8 r] or r = code [0x1 .<. 7 .|. 0x6 .<. 3 .|. encodeReg8 r] xor r = code [0x1 .<. 7 .|. 0x5 .<. 3 .|. encodeReg8 r] cp r = code [0x1 .<. 7 .|. 0x7 .<. 3 .|. encodeReg8 r] instance Arithmetic8 C where sub r = code [0x1 .<. 7 .|. 0x2 .<. 3 .|. encodeReg8 r] and r = code [0x1 .<. 7 .|. 0x4 .<. 3 .|. encodeReg8 r] or r = code [0x1 .<. 7 .|. 0x6 .<. 3 .|. encodeReg8 r] xor r = code [0x1 .<. 7 .|. 0x5 .<. 3 .|. encodeReg8 r] cp r = code [0x1 .<. 7 .|. 0x7 .<. 3 .|. encodeReg8 r] instance Arithmetic8 Reg8 where sub r = code [0x1 .<. 7 .|. 0x2 .<. 3 .|. encodeReg8 r] and r = code [0x1 .<. 7 .|. 0x4 .<. 3 .|. encodeReg8 r] or r = code [0x1 .<. 7 .|. 0x6 .<. 3 .|. encodeReg8 r] xor r = code [0x1 .<. 7 .|. 0x5 .<. 3 .|. encodeReg8 r] cp r = code [0x1 .<. 7 .|. 0x7 .<. 3 .|. encodeReg8 r] instance (n ~ Word8) => Arithmetic8 n where sub n = code [0xd6, n] and n = code [0xe6, n] or n = code [0xf6, n] xor n = code [0xee, n] cp n = code [0xfe, n] instance Arithmetic8 [HL] where sub [HL] = code [0x96] sub x = derefError x and [HL] = code [0xa6] and x = derefError x or [HL] = code [0xb6] or x = derefError x xor [HL] = code [0xae] xor x = derefError x cp [HL] = code [0xbe] cp x = derefError x instance Arithmetic8 [RegIx] where sub [i :+ d] = code [encodeOrError i, 0x96, d] sub [i] = sub [i+0] sub x = derefError x and [i :+ d] = code [encodeOrError i, 0xa6, d] and [i] = and [i+0] and x = derefError x or [i :+ d] = code [encodeOrError i, 0xb6, d] or [i] = or [i+0] or x = derefError x xor [i :+ d] = code [encodeOrError i, 0xae, d] xor [i] = xor [i+0] xor x = derefError x cp [i :+ d] = code [encodeOrError i, 0xbe, d] cp [i] = cp [i+0] cp x = derefError x class Inc operand where inc :: operand -> Z80ASM dec :: operand -> Z80ASM instance Inc A where inc r = code [encodeReg8 r .<. 3 .|. 0x4] dec r = code [encodeReg8 r .<. 3 .|. 0x5] instance Inc C where inc r = code [encodeReg8 r .<. 3 .|. 0x4] dec r = code [encodeReg8 r .<. 3 .|. 0x5] instance Inc Reg8 where inc r = code [encodeReg8 r .<. 3 .|. 0x4] dec r = code [encodeReg8 r .<. 3 .|. 0x5] instance Inc [HL] where inc [HL] = code [0x34] inc x = derefError x dec [HL] = code [0x35] dec x = derefError x instance Inc [RegIx] where inc [i :+ d] = code [encodeOrError i, 0x34, d] inc [i] = inc [i+0] inc x = derefError x dec [i :+ d] = code [encodeOrError i, 0x35, d] dec [i] = dec [i+0] dec x = derefError x daa :: Z80ASM daa = code [0x27] cpl :: Z80ASM cpl = code [0x2f] neg :: Z80ASM neg = code [0xed, 0x44] ccf :: Z80ASM ccf = code [0x3f] scf :: Z80ASM scf = code [0x37] nop :: Z80ASM nop = code [0x00] halt :: Z80ASM halt = code [0x76] di :: Z80ASM di = code [0xf3] ei :: Z80ASM ei = code [0xfb] im :: Word8 -> Z80ASM im 0 = code [0xed, 0x46] im 1 = code [0xed, 0x56] im 2 = code [0xed, 0x5e] im x = error $ "Invalid interrupt mode: " ++ show x class Arithmetic target operand where add :: target -> operand -> Z80ASM class CarryArithmetic target operand where adc :: target -> operand -> Z80ASM sbc :: target -> operand -> Z80ASM instance Arithmetic A A where add A r = code [0x1 .<. 7 .|. encodeReg8 r] instance CarryArithmetic A A where adc A r = code [0x1 .<. 7 .|. 0x1 .<. 3 .|. encodeReg8 r] sbc A r = code [0x1 .<. 7 .|. 0x3 .<. 3 .|. encodeReg8 r] instance Arithmetic A C where add A r = code [0x1 .<. 7 .|. encodeReg8 r] instance CarryArithmetic A C where adc A r = code [0x1 .<. 7 .|. 0x1 .<. 3 .|. encodeReg8 r] sbc A r = code [0x1 .<. 7 .|. 0x3 .<. 3 .|. encodeReg8 r] instance Arithmetic A Reg8 where add A r = code [0x1 .<. 7 .|. encodeReg8 r] instance CarryArithmetic A Reg8 where adc A r = code [0x1 .<. 7 .|. 0x1 .<. 3 .|. encodeReg8 r] sbc A r = code [0x1 .<. 7 .|. 0x3 .<. 3 .|. encodeReg8 r] instance (n ~ Word8) => Arithmetic A n where add A n = code [0xc6, n] instance (n ~ Word8) => CarryArithmetic A n where adc A n = code [0xce, n] sbc A n = code [0xde, n] instance Arithmetic A [HL] where add A [HL] = code [0x86] add A x = derefError x instance CarryArithmetic A [HL] where adc A [HL] = code [0x8e] adc A x = derefError x sbc A [HL] = code [0x9e] sbc A x = derefError x instance Arithmetic A [RegIx] where add A [i :+ d] = code [encodeOrError i, 0x86, d] add A [i] = add A [i+0] add A x = derefError x instance CarryArithmetic A [RegIx] where adc A [i :+ d] = code [encodeOrError i, 0x8e, d] adc A [i] = adc A [i+0] adc A x = derefError x sbc A [i :+ d] = code [encodeOrError i, 0x9e, d] sbc A [i] = sbc A [i+0] sbc A x = derefError x instance (Reg16 ss) => Arithmetic HL ss where add HL ss = code [encodeReg16 ss .<. 4 .|. 0x09] instance (Reg16 ss) => CarryArithmetic HL ss where adc HL ss = code [0xed, 0x40 .|. encodeReg16 ss .<. 4 .|. 0x0a] sbc HL ss = code [0xed, 0x40 .|. encodeReg16 ss .<. 4 .|. 0x2] instance (Reg16 ss, Show ss) => Arithmetic RegIx ss where add i pp = code [encodeReg16 i, encodeReg16 pp .<. 4 .|. 0x09] instance Arithmetic RegIx SP where add i pp = code [encodeReg16 i, encodeReg16 pp .<. 4 .|. 0x09] instance Arithmetic RegIx RegIx where add i i' | i == i' = code [encodeReg16 i, 0x2 .<. 4 .|. 0x09] add i i' = error $ "Invalid operation: add " ++ show i ++ " " ++ show i' instance (Reg16 ss) => Inc ss where inc r = code [encodeReg16 r .<. 4 .|. 0x3] dec r = code [encodeReg16 r .<. 4 .|. 0xb] instance Inc HL where inc r = code [encodeReg16 r .<. 4 .|. 0x3] dec r = code [encodeReg16 r .<. 4 .|. 0xb] instance Inc SP where inc r = code [encodeReg16 r .<. 4 .|. 0x3] dec r = code [encodeReg16 r .<. 4 .|. 0xb] instance Inc RegIx where inc i = code [encodeReg16 i, 0x23] dec i = code [encodeReg16 i, 0x2b] rlca, rla, rrca, rra :: Z80ASM rlca = code [0x07] rla = code [0x17] rrca = code [0x0f] rra = code [0x1f] class RotateShift r where rlc :: r -> Z80ASM rl :: r -> Z80ASM rrc :: r -> Z80ASM rr :: r -> Z80ASM sla :: r -> Z80ASM sra :: r -> Z80ASM srl :: r -> Z80ASM instance RotateShift Reg8 where rlc r = code [0xcb, encodeReg8 r] rl r = code [0xcb, 0x2 .<. 3 .|. encodeReg8 r] rrc r = code [0xcb, 0x1 .<. 3 .|. encodeReg8 r] rr r = code [0xcb, 0x3 .<. 3 .|. encodeReg8 r] sla r = code [0xcb, 0x4 .<. 3 .|. encodeReg8 r] sra r = code [0xcb, 0x5 .<. 3 .|. encodeReg8 r] srl r = code [0xcb, 0x7 .<. 3 .|. encodeReg8 r] instance RotateShift A where rlc r = code [0xcb, encodeReg8 r] rl r = code [0xcb, 0x2 .<. 3 .|. encodeReg8 r] rrc r = code [0xcb, 0x1 .<. 3 .|. encodeReg8 r] rr r = code [0xcb, 0x3 .<. 3 .|. encodeReg8 r] sla r = code [0xcb, 0x4 .<. 3 .|. encodeReg8 r] sra r = code [0xcb, 0x5 .<. 3 .|. encodeReg8 r] srl r = code [0xcb, 0x7 .<. 3 .|. encodeReg8 r] instance RotateShift C where rlc r = code [0xcb, encodeReg8 r] rl r = code [0xcb, 0x2 .<. 3 .|. encodeReg8 r] rrc r = code [0xcb, 0x1 .<. 3 .|. encodeReg8 r] rr r = code [0xcb, 0x3 .<. 3 .|. encodeReg8 r] sla r = code [0xcb, 0x4 .<. 3 .|. encodeReg8 r] sra r = code [0xcb, 0x5 .<. 3 .|. encodeReg8 r] srl r = code [0xcb, 0x7 .<. 3 .|. encodeReg8 r] instance RotateShift [HL] where rlc [HL] = code [0xcb, 0x06] rlc x = derefError x rl [HL] = code [0xcb, 0x16] rl x = derefError x rrc [HL] = code [0xcb, 0x0e] rrc x = derefError x rr [HL] = code [0xcb, 0x1e] rr x = derefError x sla [HL] = code [0xcb, 0x26] sla x = derefError x sra [HL] = code [0xcb, 0x2e] sra x = derefError x srl [HL] = code [0xcb, 0x3e] srl x = derefError x instance RotateShift [RegIx] where rlc [i:+d] = code [encodeOrError i, 0xcb, d, 0x06] rlc [i] = rlc [i+0] rlc x = derefError x rl [i:+d] = code [encodeOrError i, 0xcb, d, 0x16] rl [i] = rl [i+0] rl x = derefError x rrc [i:+d] = code [encodeOrError i, 0xcb, d, 0x0e] rrc [i] = rrc [i+0] rrc x = derefError x rr [i:+d] = code [encodeOrError i, 0xcb, d, 0x1e] rr [i] = rr [i+0] rr x = derefError x sla [i:+d] = code [encodeOrError i, 0xcb, d, 0x26] sla [i] = sla [i+0] sla x = derefError x sra [i:+d] = code [encodeOrError i, 0xcb, d, 0x2e] sra [i] = sra [i+0] sra x = derefError x srl [i:+d] = code [encodeOrError i, 0xcb, d, 0x3e] srl [i] = srl [i+0] srl x = derefError x rld, rrd :: Z80ASM rld = code [0xed, 0x6f] rrd = code [0xed, 0x67] class Bitwise r where bit :: Word8 -> r -> Z80ASM set :: Word8 -> r -> Z80ASM res :: Word8 -> r -> Z80ASM instance Bitwise Reg8 where bit b r = code [0xcb, 0x1 .<. 6 .|. b .<. 3 .|. encodeReg8 r] set b r = code [0xcb, 0x3 .<. 6 .|. b .<. 3 .|. encodeReg8 r] res b r = code [0xcb, 0x2 .<. 6 .|. b .<. 3 .|. encodeReg8 r] instance Bitwise A where bit b r = code [0xcb, 0x1 .<. 6 .|. b .<. 3 .|. encodeReg8 r] set b r = code [0xcb, 0x3 .<. 6 .|. b .<. 3 .|. encodeReg8 r] res b r = code [0xcb, 0x2 .<. 6 .|. b .<. 3 .|. encodeReg8 r] instance Bitwise C where bit b r = code [0xcb, 0x1 .<. 6 .|. b .<. 3 .|. encodeReg8 r] set b r = code [0xcb, 0x3 .<. 6 .|. b .<. 3 .|. encodeReg8 r] res b r = code [0xcb, 0x2 .<. 6 .|. b .<. 3 .|. encodeReg8 r] instance Bitwise [HL] where bit b [HL] = code [0xcb, 0x1 .<. 6 .|. b .<. 3 .|. 0x6] bit _ x = derefError x set b [HL] = code [0xcb, 0x3 .<. 6 .|. b .<. 3 .|. 0x6] set _ x = derefError x res b [HL] = code [0xcb, 0x2 .<. 6 .|. b .<. 3 .|. 0x6] res _ x = derefError x instance Bitwise [RegIx] where bit b [i :+ d] = code [encodeOrError i, 0xcb, d, 0x1 .<. 6 .|. b .<. 3 .|. 0x6] bit b [i] = bit b [i+0] bit _ x = derefError x set b [i :+ d] = code [encodeOrError i, 0xcb, d, 0x3 .<. 6 .|. b .<. 3 .|. 0x6] set b [i] = set b [i+0] set _ x = derefError x res b [i :+ d] = code [encodeOrError i, 0xcb, d, 0x2 .<. 6 .|. b .<. 3 .|. 0x6] res b [i] = res b [i+0] res _ x = derefError x class Jump p r where jp :: p -> r instance (nn ~ Word16) => Jump nn (Z80 a) where jp nn = meaningless "jp" $ code [0xc3, lo nn, hi nn] instance (Cond cc, nn ~ Word16) => Jump cc (nn -> Z80 a) where jp cc = \nn -> meaningless "jp" $ code [0x3 .<. 6 .|. encodeCondition cc .<. 3 .|. 0x2, lo nn, hi nn] instance Jump [HL] Z80ASM where jp [HL] = code [0xe9] jp x = derefError x instance Jump [RegIx] Z80ASM where jp [i] = code [encodeReg16 i, 0xe9] jp x = derefError x class JumpRelative p r where jr :: p -> r instance (a ~ Word16) => JumpRelative a (Z80 b) where jr = relative >=> \a -> meaningless "jr" $ code [0x18, a-2] instance (a ~ Word16) => JumpRelative C (a -> Z80 b) where jr C = relative >=> \a -> meaningless "jr" $ code [0x38, a-2] instance (a ~ Word16) => JumpRelative NC (a -> Z80 b) where jr NC = relative >=> \a -> meaningless "jr" $ code [0x30, a-2] instance (a ~ Word16) => JumpRelative Z (a -> Z80 b) where jr Z = relative >=> \a -> meaningless "jr" $ code [0x28, a-2] instance (a ~ Word16) => JumpRelative NZ (a -> Z80 b) where jr NZ = relative >=> \a -> meaningless "jr" $ code [0x20, a-2] djnz :: Word16 -> Z80ASM djnz = relative >=> \a -> code [0x10, a-2] ($-), ($+) :: (Word16 -> Z80ASM) -> Word16 -> Z80ASM op $- a = op . subtract a =<< label op $+ a = op . (+ a) =<< label class Call p r where call :: p -> r instance (nn ~ Word16) => Call nn (Z80 a) where call nn = meaningless "call" $ code [0xcd, lo nn, hi nn] instance (nn ~ Word16, Cond cc) => Call cc (nn -> Z80 a) where call cc = \nn -> meaningless "call" $ code [0x3 .<. 6 .|. encodeCondition cc .<. 3 .|. 0x4, lo nn, hi nn] class Return t where ret :: t instance Return (Z80 a) where ret = meaningless "call" $ code [0xc9] instance (Cond cc) => Return (cc -> Z80 a) where ret = \cc -> meaningless "call" $ code [0x3 .<. 6 .|. encodeCondition cc .<. 3] reti, retn :: Z80ASM reti = code [0xed, 0x4d] retn = code [0xed, 0x45] rst :: Word8 -> Z80ASM rst p = code [0x3 .<. 6 .|. encodeMemLoc p .<. 3 .|. 0x7] where encodeMemLoc 0x00 = 0x0 -- 000 encodeMemLoc 0x08 = 0x1 -- 001 encodeMemLoc 0x10 = 0x2 -- 010 encodeMemLoc 0x18 = 0x3 -- 011 encodeMemLoc 0x20 = 0x4 -- 100 encodeMemLoc 0x28 = 0x5 -- 101 encodeMemLoc 0x30 = 0x6 -- 110 encodeMemLoc 0x38 = 0x7 -- 111 encodeMemLoc x = error $ "Invalid parameter to rst: " ++ show x class InOut target source where in_ :: target -> source -> Z80ASM out :: source -> target -> Z80ASM instance (Word8 ~ n) => InOut A [n] where in_ A [n] = code [0xdb, n] in_ _ x = derefError x out [n] A = code [0xd3, n] out x _ = derefError x instance InOut Reg8 [C] where in_ r [C] = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3] in_ _ x = derefError x out [C] r = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3 .|. 0x1] out x _ = derefError x instance InOut A [C] where in_ r [C] = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3] in_ _ x = derefError x out [C] r = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3 .|. 0x1] out x _ = derefError x instance InOut C [C] where in_ r [C] = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3] in_ _ x = derefError x out [C] r = code [0xed, 0x1 .<. 6 .|. encodeReg8 r .<. 3 .|. 0x1] out x _ = derefError x ini, inir, ind, indr :: Z80ASM ini = code [0xed, 0xa2] inir = code [0xed, 0xb2] ind = code [0xed, 0xaa] indr = code [0xed, 0xba] outi, otir, outd, otdr :: Z80ASM outi = code [0xed, 0xa3] otir = code [0xed, 0xb3] outd = code [0xed, 0xab] otdr = code [0xed, 0xbb] {- -------- INTERNAL UTILITIES -------- -} (.<.) :: Bits a => a -> Int -> a (.<.) = shiftL hi, lo :: Word16 -> Word8 hi = fromIntegral . byteSwap16 lo = fromIntegral -- Get an address relative to the current address relative :: Word16 -> Z80 Word8 relative a = fromIntegral . validate . (`subtract` (fromIntegral a)) . asInt <$> label where asInt x = fromIntegral x :: Int validate x | x >= (-126) && x <= 129 = x | otherwise = error $ "Relative address out of range: " ++ show x derefError :: Show a => a -> b derefError x = error $ "Dereference syntax is a list with exactly one entry. Invalid: " ++ show x meaningless :: Monad m => String -> m a -> m b meaningless s a = a >> return (error $ "Return value from " ++ s ++ " is meaningless") class EncodeReg8 r where encodeReg8 :: r -> Word8 instance EncodeReg8 A where encodeReg8 A = 0x7 -- 111 instance EncodeReg8 C where encodeReg8 C = 0x1 -- 001 instance EncodeReg8 Reg8 where encodeReg8 B = 0x0 -- 000 encodeReg8 D = 0x2 -- 010 encodeReg8 E = 0x3 -- 011 encodeReg8 H = 0x4 -- 100 encodeReg8 L = 0x5 -- 101 class EncodeReg16 r where encodeReg16 :: r -> Word8 instance EncodeReg16 BC where encodeReg16 BC = 0x0 -- 00 instance EncodeReg16 DE where encodeReg16 DE = 0x1 -- 01 instance EncodeReg16 HL where encodeReg16 HL = 0x2 -- 10 -- SP and AF both encode to the same value. -- This will break if there is ever a situation in which either could be passed. instance EncodeReg16 SP where encodeReg16 SP = 0x3 -- 11 instance EncodeReg16 AF where encodeReg16 AF = 0x3 -- 11 class EncodeReg16 r => Reg16 r instance Reg16 BC instance Reg16 DE instance EncodeReg16 RegIx where encodeReg16 IX = 0xdd encodeReg16 IY = 0xfd encodeReg16 i = error $ "Cannot encode offset index: " ++ show i encodeOrError :: EncodeReg16 x => Maybe x -> Word8 encodeOrError (Just x) = encodeReg16 x encodeOrError Nothing = error $ "Cannot encode register: no value" class EncodeCondition r where encodeCondition :: r -> Word8 instance EncodeCondition Condition where encodeCondition PO = 0x4 encodeCondition PE = 0x5 encodeCondition P = 0x6 encodeCondition M = 0x7 instance EncodeCondition NZ where encodeCondition NZ = 0x0 instance EncodeCondition Z where encodeCondition Z = 0x1 instance EncodeCondition NC where encodeCondition NC = 0x2 instance EncodeCondition C where encodeCondition C = 0x3 class EncodeCondition c => Cond c instance Cond Condition instance Cond NZ instance Cond Z instance Cond NC instance Cond C
dpwright/z80
src/Z80/Operations.hs
mit
25,122
0
14
6,775
12,110
6,240
5,870
-1
-1
{-# LANGUAGE CPP, OverloadedStrings #-} module BasicTests (basicSpecs) where import Yesod.Test import Foundation redirectCode :: Int #if MIN_VERSION_yesod_test(1,4,0) redirectCode = 303 #else redirectCode = 302 #endif basicSpecs :: YesodSpec MyApp basicSpecs = ydescribe "Basic tests" $ do yit "checks the home page is not logged in" $ do get' "/" statusIs 200 bodyContains "Please visit the <a href=\"/auth/login\">Login page" yit "tests an invalid login" $ do get' "/auth/login" statusIs 200 post' "/auth/page/account/login" $ do byLabel "Username" "abc" byLabel "Password" "xxx" statusIs redirectCode get' "/auth/login" statusIs 200 bodyContains "Invalid username/password combination" yit "new account page looks ok" $ do get' "/auth/page/account/newaccount" statusIs 200 htmlAllContain "title" "Register a new account" bodyContains "Register" yit "reset password page looks ok" $ do get' "/auth/page/account/resetpassword" statusIs 200 bodyContains "Send password reset email" post' "/auth/page/account/resetpassword" $ do byLabel "Username" "abc" addToken statusIs redirectCode get' "/" statusIs 200 bodyContains "Invalid username" yit "verify page returns an error" $ do get' "/auth/page/account/verify/abc/xxxxxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "invalid verification key" yit "new password returns an error" $ do get' "/auth/page/account/newpassword/abc/xxxxxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "invalid verification key" yit "set password returns an error" $ do post' "/auth/page/account/setpassword" $ do addPostParam "f1" "xxx" addPostParam "f2" "xxx" addPostParam "f3" "xxx" addPostParam "f4" "xxx" addPostParam "f5" "xxx" statusIs redirectCode get' "/" statusIs 200 bodyContains "As a protection against cross-site" yit "resend verify email returns an error" $ do post' "/auth/page/account/resendverifyemail" $ do addPostParam "f1" "xxx" addPostParam "f2" "xxx" statusIs 400 bodyContains "As a protection against cross-site"
meteficha/yesod-auth-account-fork
tests/BasicTests.hs
mit
2,728
0
14
990
472
183
289
68
1
{-# LANGUAGE OverloadedStrings #-} import Data.Maybe import Network.URL import Pipes.Core ((+>>)) import Network.Discord.Types import Network.Discord.Gateway import Network.Discord.Rest data LogClient = LClient instance Client LogClient where getAuth _ = Bot "TOKEN" main :: IO () main = runWebsocket (fromJust $ importURL "wss://gateway.discord.gg") LClient $ do fetch' (CreateMessage 188134500411244545 "Hello, World!" Nothing) fetch' (CreateMessage 188134500411244545 "I'm running discord.hs!" Nothing)
jano017/Discord.hs
examples/hello_world.hs
mit
517
0
10
68
134
71
63
14
1
module MolSeq ( MolSeq, SeqType(DNA,Protein), string2seq, seqType, seqName, seqDistance, seqSequence, seqLength ) where import Hamming import Data.Function data SeqType = DNA | Protein deriving (Show, Eq) data MolSeq = MolSeq String String SeqType deriving (Show, Eq) dnaBlocks :: String dnaBlocks = "ACGT" isProtein :: String -> Bool isProtein s = not $ isDNA s isDNA :: String -> Bool isDNA = all (`elem` dnaBlocks) string2seq :: String -> String -> MolSeq string2seq name s | isDNA s = MolSeq name s DNA | isProtein s = MolSeq name s Protein seqName :: MolSeq -> String seqName (MolSeq name _ _) = name seqSequence :: MolSeq -> String seqSequence (MolSeq _ s _) = s seqLength :: MolSeq -> Int seqLength (MolSeq _ s _) = length s seqType :: MolSeq -> SeqType seqType (MolSeq _ _ typ) = typ {- Enligt en känd och enkel modell som kallas Jukes-Cantor låter man avståndet da, b mellan två DNA-sekvenser a och b vara da,b= -3/4ln(1-4α/3) där α är andelen positioner där sekvenserna skiljer sig åt. Formeln fungerar inte bra om sekvenserna skiljer sig åt mer än väntat, så om α>0.74 låter man ofta da, b = 3.3. -} divide :: Int -> Int -> Double divide = (/) `on` realToFrac seqDist :: String -> String -> Double seqDist a b = divide (hammingDist a b) (length a) seqDistance :: MolSeq -> MolSeq -> Double seqDistance (MolSeq _ a DNA) (MolSeq _ b DNA) | seqDist a b <= 0.74 = -3 / 4 * log(1 - 4/3 * seqDist a b) | otherwise = 3.3 seqDistance (MolSeq _ a Protein) (MolSeq _ b Protein) | seqDist a b <= 0.94 = -19 / 20 * log(1 - 20/19 * seqDist a b) | otherwise = 3.7 seqDistance _ _ = error "Incompatible Sequence types"
considerate/progp
Haskell/bio/molseq.hs
mit
1,734
17
11
405
601
312
289
43
1
module Main where import Graphics.Cogh import FRP.Gearh quitOutput :: Bool -> Output quitOutput True = quit quitOutput False = mempty renderOutput :: Window -> Element -> Output renderOutput window = output . renderRoot window createImageResource :: Window -> String -> IO (Resource Texture) createImageResource window imageLocation = createResource createImage deleteImage where createImage = newTextureFromImage window imageLocation deleteImage = deleteTexture eventInput :: Window -> Input Event eventInput = manytimes . getEvents data State = State { x :: Int , y :: Int , finish :: Bool } deriving (Show) updateEvent :: Event -> State -> State updateEvent Quit state = newState where newState = state { finish = True } updateEvent (MousePosition mx my) state = newState where newState = state { x = mx, y = my } updateEvent _ state = state renderScene :: State -> Maybe Texture -> Element renderScene state (Just texture) = move centerX centerY $ group [ move (-w2) (-h2) $ rectangle w2 h2 0xFF0000FF , rectangle w2 h2 0x00FF00FF , move (-110) 10 $ rectangle 100 100 0x0000FFFF , move (-w4) (-h4) $ image w2 h2 texture ] where (w, h) = (textureWidth texture, textureHeight texture) (w2, h2) = (div w 2, div h 2) (w4, h4) = (div w 4, div h 4) centerX = x state centerY = y state renderScene state Nothing = move centerX centerY $ group [ move (-w2) (-h2) $ rectangle w2 h2 0xFF0000FF , rectangle w2 h2 0x00FF00FF , move (-110) 10 $ rectangle 100 100 0x0000FFFF , move (-w4) (-h4) $ rectangle w2 h2 0xFFFFFF44 ] where (w, h) = (400, 400) (w2, h2) = (div w 2, div h 2) (w4, h4) = (div w 4, div h 4) centerX = x state centerY = y state initialState :: State initialState = State 0 0 False main :: IO () main = do (Just window) <- newWindow "Test" res <- createImageResource window "test.png" let i = mconcat [ fmap updateEvent (eventInput window) ] o = mconcat [ quitOutput . finish , withResource res (renderOutput window) . renderScene , resourceRequest res . const Load ] _ <- runGear i o initialState return ()
ivokosir/gearh
test/renderResources.hs
mit
2,180
0
15
522
857
443
414
68
1
module Main where import Data.BBS import System.Console.Haskeline import System.Environment import Text.Printf usage :: IO () usage = printf "usage: post [OPTION] [TEXT]" parse :: [String] -> IO () parse ["--help"] = usage parse ["-h"] = usage -- parse ("-i":id:"-p":text) = printf "Sending '%v' to %v.\n" (head text) (head id) parse _ = usage main :: IO () main = getArgs >>= parse
mebio-us/BBS
utilities/post.hs
mit
401
0
7
80
110
61
49
13
1
{- see Chapter 32 of the Haskell 2010 Language Report -} module Foreign.Marshal.Array where
evilcandybag/JSHC
hslib/Foreign/Marshal/Array.hs
mit
95
0
3
16
8
6
2
1
0
import Network import Control.Concurrent(forkIO) import System.IO import Control.Monad import System.Environment {- Реализуйте простой эхо-сервер. Это программа, которая слушает определенный порт, принимает соединения, и всё, что присылает клиент, отправляет ему обратно. (2 балла) -} main :: IO () main = do args <- getArgs case args of (portToListen:_) -> do socket <- listenOn (PortNumber (fromInteger (read portToListen))) forever $ do (handler, host, port) <- accept socket forkIO $ (forever (hGetLine handler >>= hPutStrLn handler)) otherwise -> putStrLn "Usage: echo_server {port number}"
SergeyKrivohatskiy/fp_haskell
hw09/echo_server.hs
mit
812
0
20
162
161
81
80
15
2
{-# LANGUAGE OverloadedStrings #-} module Main where import Test.Hspec import Text.Blaze.Html.Renderer.Text (renderHtml) import Yesod.Markdown import qualified Data.Text as T import qualified Data.Text.Lazy as TL main :: IO () main = hspec spec spec :: Spec spec = describe "Yesod.Markdown" $ do it "converts Markdown to sanitized HTML" $ do let markdown = Markdown $ T.unlines [ "# Title" , "" , "- one" , "- two" , "- three" , "" , "<script>" , " alert('xxs');" , "</script>" ] let Right html = markdownToHtml markdown renderHtml html `shouldBe` TL.concat [ "<h1 id=\"title\">Title</h1>" , "<ul>" , "<li>one</li>" , "<li>two</li>" , "<li>three</li>" , "</ul>" , "\n alert('xxs');\n" ] it "converts Markdown to unsanitized HTML" $ do let markdown = Markdown $ T.unlines [ "# Title" , "" , "- one" , "- two" , "- three" , "" , "<script>" , " alert('xxs');" , "</script>" ] let Right html = markdownToHtmlTrusted markdown renderHtml html `shouldBe` TL.concat [ "<h1 id=\"title\">Title</h1>" , "<ul>" , "<li>one</li>" , "<li>two</li>" , "<li>three</li>" , "</ul>" , "<script>\n" , " alert('xxs');\n" , "</script>" ]
robgssp/yesod-markdown
test/Spec.hs
gpl-2.0
1,719
0
16
780
304
170
134
53
1
{-| Utilities common to hledger journal readers. -} module Hledger.Read.Utils where import Control.Monad.Error import Data.List import System.Directory (getHomeDirectory) import System.FilePath(takeDirectory,combine) import System.Time (getClockTime) import Text.ParserCombinators.Parsec import Hledger.Data.Types (Journal, JournalContext(..), Commodity, JournalUpdate) import Hledger.Utils import Hledger.Data.Dates (getCurrentYear) import Hledger.Data.Journal (nullctx, nulljournal, journalFinalise) juSequence :: [JournalUpdate] -> JournalUpdate juSequence us = liftM (foldr (.) id) $ sequence us -- | Given a JournalUpdate-generating parsec parser, file path and data string, -- parse and post-process a Journal so that it's ready to use, or give an error. parseJournalWith :: (GenParser Char JournalContext (JournalUpdate,JournalContext)) -> FilePath -> String -> ErrorT String IO Journal parseJournalWith p f s = do tc <- liftIO getClockTime tl <- liftIO getCurrentLocalTime y <- liftIO getCurrentYear case runParser p nullctx{ctxYear=Just y} f s of Right (updates,ctx) -> do j <- updates `ap` return nulljournal case journalFinalise tc tl f s ctx j of Right j' -> return j' Left estr -> throwError estr Left e -> throwError $ show e setYear :: Integer -> GenParser tok JournalContext () setYear y = updateState (\ctx -> ctx{ctxYear=Just y}) getYear :: GenParser tok JournalContext (Maybe Integer) getYear = liftM ctxYear getState setCommodity :: Commodity -> GenParser tok JournalContext () setCommodity c = updateState (\ctx -> ctx{ctxCommodity=Just c}) getCommodity :: GenParser tok JournalContext (Maybe Commodity) getCommodity = liftM ctxCommodity getState pushParentAccount :: String -> GenParser tok JournalContext () pushParentAccount parent = updateState addParentAccount where addParentAccount ctx0 = ctx0 { ctxAccount = normalize parent : ctxAccount ctx0 } normalize = (++ ":") popParentAccount :: GenParser tok JournalContext () popParentAccount = do ctx0 <- getState case ctxAccount ctx0 of [] -> unexpected "End of account block with no beginning" (_:rest) -> setState $ ctx0 { ctxAccount = rest } getParentAccount :: GenParser tok JournalContext String getParentAccount = liftM (concat . reverse . ctxAccount) getState -- | Convert a possibly relative, possibly tilde-containing file path to an absolute one. -- using the current directory from a parsec source position. ~username is not supported. expandPath :: (MonadIO m) => SourcePos -> FilePath -> m FilePath expandPath pos fp = liftM mkAbsolute (expandHome fp) where mkAbsolute = combine (takeDirectory (sourceName pos)) expandHome inname | "~/" `isPrefixOf` inname = do homedir <- liftIO getHomeDirectory return $ homedir ++ drop 1 inname | otherwise = return inname fileSuffix :: FilePath -> String fileSuffix = reverse . takeWhile (/='.') . reverse . dropWhile (/='.')
trygvis/hledger
hledger-lib/Hledger/Read/Utils.hs
gpl-3.0
3,179
0
15
723
848
440
408
52
3
module StoreTest ( storeTests ) where import Data.ByteString as BS import System.IO.Temp import qualified Test.Framework as TF import Test.Framework.Providers.HUnit import Test.HUnit import Freenet.Store import Freenet.Types storeTests :: TF.Test storeTests = TF.testGroup "store" [ testCase "create store" testCreate ] testCreate :: Assertion testCreate = withSystemTempDirectory "ads-test" $ \tmpdir -> do sf <- mkStoreFile (tmpdir ++ "dummy-store") 1000 :: IO (StoreFile DummyStorable) return () dummySize :: Int dummySize = 12345 newtype DummyStorable = DS BS.ByteString instance DataBlock DummyStorable where instance StorePersistable DummyStorable where storeSize _ = dummySize
waldheinz/ads
src/tests/StoreTest.hs
gpl-3.0
778
0
12
179
184
103
81
21
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.ServiceManagement.Services.Configs.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a service configuration (version) for a managed service. -- -- /See:/ <https://cloud.google.com/service-management/ Google Service Management API Reference> for @servicemanagement.services.configs.get@. module Network.Google.Resource.ServiceManagement.Services.Configs.Get ( -- * REST Resource ServicesConfigsGetResource -- * Creating a Request , servicesConfigsGet , ServicesConfigsGet -- * Request Lenses , scgXgafv , scgUploadProtocol , scgPp , scgAccessToken , scgUploadType , scgBearerToken , scgConfigId , scgServiceName , scgCallback ) where import Network.Google.Prelude import Network.Google.ServiceManagement.Types -- | A resource alias for @servicemanagement.services.configs.get@ method which the -- 'ServicesConfigsGet' request conforms to. type ServicesConfigsGetResource = "v1" :> "services" :> Capture "serviceName" Text :> "configs" :> Capture "configId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Service -- | Gets a service configuration (version) for a managed service. -- -- /See:/ 'servicesConfigsGet' smart constructor. data ServicesConfigsGet = ServicesConfigsGet' { _scgXgafv :: !(Maybe Xgafv) , _scgUploadProtocol :: !(Maybe Text) , _scgPp :: !Bool , _scgAccessToken :: !(Maybe Text) , _scgUploadType :: !(Maybe Text) , _scgBearerToken :: !(Maybe Text) , _scgConfigId :: !Text , _scgServiceName :: !Text , _scgCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ServicesConfigsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scgXgafv' -- -- * 'scgUploadProtocol' -- -- * 'scgPp' -- -- * 'scgAccessToken' -- -- * 'scgUploadType' -- -- * 'scgBearerToken' -- -- * 'scgConfigId' -- -- * 'scgServiceName' -- -- * 'scgCallback' servicesConfigsGet :: Text -- ^ 'scgConfigId' -> Text -- ^ 'scgServiceName' -> ServicesConfigsGet servicesConfigsGet pScgConfigId_ pScgServiceName_ = ServicesConfigsGet' { _scgXgafv = Nothing , _scgUploadProtocol = Nothing , _scgPp = True , _scgAccessToken = Nothing , _scgUploadType = Nothing , _scgBearerToken = Nothing , _scgConfigId = pScgConfigId_ , _scgServiceName = pScgServiceName_ , _scgCallback = Nothing } -- | V1 error format. scgXgafv :: Lens' ServicesConfigsGet (Maybe Xgafv) scgXgafv = lens _scgXgafv (\ s a -> s{_scgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). scgUploadProtocol :: Lens' ServicesConfigsGet (Maybe Text) scgUploadProtocol = lens _scgUploadProtocol (\ s a -> s{_scgUploadProtocol = a}) -- | Pretty-print response. scgPp :: Lens' ServicesConfigsGet Bool scgPp = lens _scgPp (\ s a -> s{_scgPp = a}) -- | OAuth access token. scgAccessToken :: Lens' ServicesConfigsGet (Maybe Text) scgAccessToken = lens _scgAccessToken (\ s a -> s{_scgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). scgUploadType :: Lens' ServicesConfigsGet (Maybe Text) scgUploadType = lens _scgUploadType (\ s a -> s{_scgUploadType = a}) -- | OAuth bearer token. scgBearerToken :: Lens' ServicesConfigsGet (Maybe Text) scgBearerToken = lens _scgBearerToken (\ s a -> s{_scgBearerToken = a}) -- | The id of the service configuration resource. scgConfigId :: Lens' ServicesConfigsGet Text scgConfigId = lens _scgConfigId (\ s a -> s{_scgConfigId = a}) -- | The name of the service. See the -- [overview](\/service-management\/overview) for naming requirements. For -- example: \`example.googleapis.com\`. scgServiceName :: Lens' ServicesConfigsGet Text scgServiceName = lens _scgServiceName (\ s a -> s{_scgServiceName = a}) -- | JSONP scgCallback :: Lens' ServicesConfigsGet (Maybe Text) scgCallback = lens _scgCallback (\ s a -> s{_scgCallback = a}) instance GoogleRequest ServicesConfigsGet where type Rs ServicesConfigsGet = Service type Scopes ServicesConfigsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/service.management", "https://www.googleapis.com/auth/service.management.readonly"] requestClient ServicesConfigsGet'{..} = go _scgServiceName _scgConfigId _scgXgafv _scgUploadProtocol (Just _scgPp) _scgAccessToken _scgUploadType _scgBearerToken _scgCallback (Just AltJSON) serviceManagementService where go = buildClient (Proxy :: Proxy ServicesConfigsGetResource) mempty
rueshyna/gogol
gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Configs/Get.hs
mpl-2.0
6,142
0
20
1,511
943
548
395
137
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.YouTube.VideoCategories.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of categories that can be associated with YouTube videos. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.videoCategories.list@. module Network.Google.Resource.YouTube.VideoCategories.List ( -- * REST Resource VideoCategoriesListResource -- * Creating a Request , videoCategoriesList , VideoCategoriesList -- * Request Lenses , vclPart , vclRegionCode , vclHl , vclId ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.videoCategories.list@ method which the -- 'VideoCategoriesList' request conforms to. type VideoCategoriesListResource = "youtube" :> "v3" :> "videoCategories" :> QueryParam "part" Text :> QueryParam "regionCode" Text :> QueryParam "hl" Text :> QueryParam "id" Text :> QueryParam "alt" AltJSON :> Get '[JSON] VideoCategoryListResponse -- | Returns a list of categories that can be associated with YouTube videos. -- -- /See:/ 'videoCategoriesList' smart constructor. data VideoCategoriesList = VideoCategoriesList' { _vclPart :: !Text , _vclRegionCode :: !(Maybe Text) , _vclHl :: !Text , _vclId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'VideoCategoriesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vclPart' -- -- * 'vclRegionCode' -- -- * 'vclHl' -- -- * 'vclId' videoCategoriesList :: Text -- ^ 'vclPart' -> VideoCategoriesList videoCategoriesList pVclPart_ = VideoCategoriesList' { _vclPart = pVclPart_ , _vclRegionCode = Nothing , _vclHl = "en_US" , _vclId = Nothing } -- | The part parameter specifies the videoCategory resource properties that -- the API response will include. Set the parameter value to snippet. vclPart :: Lens' VideoCategoriesList Text vclPart = lens _vclPart (\ s a -> s{_vclPart = a}) -- | The regionCode parameter instructs the API to return the list of video -- categories available in the specified country. The parameter value is an -- ISO 3166-1 alpha-2 country code. vclRegionCode :: Lens' VideoCategoriesList (Maybe Text) vclRegionCode = lens _vclRegionCode (\ s a -> s{_vclRegionCode = a}) -- | The hl parameter specifies the language that should be used for text -- values in the API response. vclHl :: Lens' VideoCategoriesList Text vclHl = lens _vclHl (\ s a -> s{_vclHl = a}) -- | The id parameter specifies a comma-separated list of video category IDs -- for the resources that you are retrieving. vclId :: Lens' VideoCategoriesList (Maybe Text) vclId = lens _vclId (\ s a -> s{_vclId = a}) instance GoogleRequest VideoCategoriesList where type Rs VideoCategoriesList = VideoCategoryListResponse type Scopes VideoCategoriesList = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtubepartner"] requestClient VideoCategoriesList'{..} = go (Just _vclPart) _vclRegionCode (Just _vclHl) _vclId (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy VideoCategoriesListResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/VideoCategories/List.hs
mpl-2.0
4,424
0
15
1,066
556
330
226
83
1