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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE ExistentialQuantification #-}
module Undo where
import Data.IORef
import Control.Monad.State
data Restore = forall a . Restore (IORef a) a
type Undo = StateT [Restore] IO
ureadIORef :: IORef a -> Undo a
ureadIORef ptr = lift $ readIORef ptr
unewIORef :: a -> Undo (IORef a)
unewIORef v = lift $ newIORef v
uwriteIORef :: IORef a -> a -> Undo ()
uwriteIORef ptr newval = do
oldval <- ureadIORef ptr
modify (Restore ptr oldval :)
lift $ writeIORef ptr newval
umodifyIORef :: IORef a -> (a -> a) -> Undo ()
umodifyIORef ptr f = do
oldval <- ureadIORef ptr
modify (Restore ptr oldval :)
lift $ writeIORef ptr (f oldval)
ureadmodifyIORef :: IORef a -> (a -> a) -> Undo a
ureadmodifyIORef ptr f = do
oldval <- ureadIORef ptr
modify (Restore ptr oldval :)
lift $ writeIORef ptr (f oldval)
return oldval
runUndo :: Undo a -> IO a
runUndo x = do
(res, restores) <- runStateT x []
mapM_ (\(Restore ptr oldval) -> writeIORef ptr oldval) restores -- reverse order is slower
return res
| frelindb/agsyHOL | Undo.hs | mit | 1,011 | 0 | 11 | 205 | 428 | 207 | 221 | 31 | 1 |
{-# htermination inits :: [a] -> [[a]] #-}
import List
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/List_inits_1.hs | mit | 55 | 0 | 3 | 10 | 5 | 3 | 2 | 1 | 0 |
module Rebase.Data.DList
(
module Data.DList
)
where
import Data.DList
| nikita-volkov/rebase | library/Rebase/Data/DList.hs | mit | 74 | 0 | 5 | 12 | 20 | 13 | 7 | 4 | 0 |
module MonadBot.Plugins.ListZipper
( ListZipper
, forward
, back
) where
type ListZipper a = ([a], [a])
forward :: ListZipper a -> Maybe (ListZipper a)
forward (ys, x : xs) = Just (x : ys, xs)
forward _ = Nothing
back :: ListZipper a -> Maybe (ListZipper a)
back (y : ys, xs) = Just (ys, y : xs)
back _ = Nothing
| saevarb/Monadbot | lib/MonadBot/Plugins/ListZipper.hs | mit | 354 | 0 | 8 | 103 | 157 | 87 | 70 | 11 | 1 |
module Language.Jass.Semantic.Variable(
-- | Variable utilities
Variable(..),
getVarName,
getVarPos,
getVarConstness,
getVarInitializator,
getVarType,
isVarArray,
isGlobalVariable
) where
import Language.Jass.Parser.AST
-- | Variable could be global, local and as a function parameter
data Variable = VarGlobal GlobalVar | VarLocal LocalVar | VarParam Parameter
deriving (Eq, Show)
-- | Returns variable name
getVarName :: Variable -> String
getVarName (VarGlobal (GlobalVar _ _ _ _ name _)) = name
getVarName (VarLocal (LocalVar _ _ _ name _)) = name
getVarName (VarParam (Parameter _ _ name)) = name
-- | Returns variable source poistion
getVarPos :: Variable -> SrcPos
getVarPos (VarGlobal (GlobalVar pos _ _ _ _ _)) = pos
getVarPos (VarLocal (LocalVar pos _ _ _ _)) = pos
getVarPos (VarParam (Parameter pos _ _)) = pos
-- | Returns if variable is immutable
getVarConstness :: Variable -> Bool
getVarConstness (VarGlobal (GlobalVar _ flag _ _ _ _)) = flag
getVarConstness (VarLocal _) = False
getVarConstness (VarParam _) = False
-- | Returns variable initializator
getVarInitializator :: Variable -> Maybe Expression
getVarInitializator (VarGlobal (GlobalVar _ _ _ _ _ initalizer)) = initalizer
getVarInitializator (VarLocal (LocalVar _ _ _ _ initalizer)) = initalizer
getVarInitializator (VarParam _) = Nothing
-- | Returns variable type
getVarType :: Variable -> JassType
getVarType (VarGlobal (GlobalVar _ _ _ jtype _ _)) = jtype
getVarType (VarLocal (LocalVar _ _ jtype _ _)) = jtype
getVarType (VarParam (Parameter _ jtype _)) = jtype
-- | Returns if variable is array
isVarArray :: Variable -> Bool
isVarArray (VarGlobal (GlobalVar _ _ flag _ _ _)) = flag
isVarArray (VarLocal (LocalVar _ flag _ _ _)) = flag
isVarArray (VarParam _) = False
-- | Returns True if variable is global
isGlobalVariable :: Variable -> Bool
isGlobalVariable (VarGlobal _) = True
isGlobalVariable _ = False | NCrashed/hjass | src/library/Language/Jass/Semantic/Variable.hs | mit | 1,926 | 0 | 9 | 325 | 620 | 328 | 292 | 39 | 1 |
module BTError where
data BTError = NoParse | NoKey String | FailureReason String
instance Show BTError where
show NoParse = "no parse"
show (NoKey s) = "no key: " ++ s
show (FailureReason s) = "failure reason: " ++ s
| nabilhassein/bitcurry | src/BTError.hs | mit | 228 | 0 | 8 | 50 | 73 | 39 | 34 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.API.Mandrill.RejectsSpec where
import Test.Hspec
import Test.Hspec.Expectations.Contrib
import Network.API.Mandrill.Types
import Network.API.Mandrill.Utils
import qualified Network.API.Mandrill.Rejects as Rejects
import qualified Data.Text as Text
import System.Environment
spec :: Spec
spec = do
test_add
test_list
test_delete
test_add :: Spec
test_add =
describe "/rejects/add.json" $
it "should add something to the blacklist" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Rejects.add "[email protected]" "ain't no good" "default"
resp `shouldSatisfy` isRight
test_list :: Spec
test_list =
describe "/rejects/list.json" $
it "should list all entries in blacklist" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Rejects.list "[email protected]" True "default"
resp `shouldSatisfy` isRight
test_delete :: Spec
test_delete =
describe "/rejects/delete.json" $
it "should delete a blacklisted email" $ do
raw <- getEnv "MANDRILL_API_KEY"
resp <- runMandrill (ApiKey $ Text.pack raw) $
Rejects.delete "[email protected]" "default"
resp `shouldSatisfy` isRight
| krgn/hamdrill | test/Network/API/Mandrill/RejectsSpec.hs | mit | 1,353 | 0 | 14 | 316 | 309 | 161 | 148 | 38 | 1 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
toWords :: [String]
toWords = ["o' clock", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
,"ten", "eleven", "twelve", "thirteen", "fourteen", "quarter", "sixteen", "seventeen", "eighteen", "nineteen"
,"twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five"
, "twenty six", "twenty seven", "twenty eight", "twenty nine", "half"]
timeInWords :: Int -> Int -> String
timeInWords h m =
let hrwords = toWords !! h
hrwords2 = if h == 12 then (toWords !! 1) else (toWords !! (h+1))
minwords = toWords !! m
minwords2 = toWords !! (60 - m)
token = if m == 15 || m == 30 || m == 45 then "" else "minutes "
in if m == 0
then unwords [hrwords, minwords]
else if m > 30
then unwords [minwords2, (token ++ "to"), hrwords2]
else unwords [minwords, (token ++ "past"), hrwords]
main :: IO ()
main = do
hstr <- getLine
mstr <- getLine
putStrLn $ timeInWords (read hstr) (read mstr)
| cbrghostrider/Hacking | HackerRank/Algorithms/Implementation/timeInWords.hs | mit | 1,457 | 0 | 14 | 347 | 370 | 214 | 156 | 22 | 5 |
{-# OPTIONS_HADDOCK hide #-}
module Graphics.Gloss.Internals.Interface.ViewState.Reshape
(callback_viewState_reshape, viewState_reshape)
where
import Graphics.Gloss.Internals.Interface.Callback
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Rendering.OpenGL (($=))
import qualified Graphics.Rendering.OpenGL.GL as GL
-- | Callback to handle keyboard and mouse button events
-- for controlling the viewport.
callback_viewState_reshape :: Callback
callback_viewState_reshape
= Reshape (viewState_reshape)
viewState_reshape :: ReshapeCallback
viewState_reshape stateRef (width,height)
= do
-- Setup the viewport
-- This controls what part of the window openGL renders to.
-- We'll use the whole window.
--
GL.viewport $= ( GL.Position 0 0
, GL.Size (fromIntegral width) (fromIntegral height))
postRedisplay stateRef
| gscalzo/HaskellTheHardWay | gloss-try/gloss-master/gloss/Graphics/Gloss/Internals/Interface/ViewState/Reshape.hs | mit | 879 | 8 | 12 | 134 | 155 | 96 | 59 | 16 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main
where
import Control.Monad
import Control.Monad.State
import Control.Applicative
import Data.List
import System.IO
import System.Random
import Data.Function (on)
import AI
import Types
import Protocol
newtype GameContext a = GameContext { runGame :: StateT ProtocolState IO a }
deriving (Functor, Applicative, Monad, MonadIO, MonadState ProtocolState)
data Move
= NoMoves
| StepDown
| StepLeft
| StepRight
| TurnLeft
| TurnRight
| DropDown
deriving (Eq, Ord, Enum)
instance Show Move where
show NoMoves = "no_moves"
show StepDown = "down"
show StepLeft = "left"
show StepRight = "right"
show TurnLeft = "turnleft"
show TurnRight = "turnright"
show DropDown = "drop"
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
evalStateT (runGame loop) mkProtocolState
loop :: GameContext ()
loop = do
input_line <- liftIO getLine
parseInput handleAction $ words input_line
is_eof <- liftIO isEOF
unless is_eof loop
handleAction :: Int -> GameContext ()
handleAction timeout = do
let allMoves = [StepLeft, StepRight]
block <- gets _thisPieceType
position <- gets _thisPiecePosition
solution <- variants block position
let myCleverPlan = moves block position solution
liftIO $ putStrLn $ formatMoves myCleverPlan
where
formatMoves = intercalate "," . map show
myBot :: GameContext Player
myBot = do
context <- get
let players = _players context
botname = _myBotName context
return $ head . filter ((botname ==) . _playerName) . _players $ context
edges :: Block -> GameContext (Int, Int)
edges block = do
let blockM = blockMatrix block
blockL = length blockM
width <- gets _fieldWidth
return (0, width - blockL)
variants :: Block -> (Int, Int) -> GameContext (Int, Int)
variants block (x, y) = do
(lo, hi) <- edges block
player <- myBot
let field = _playerField player
let vars = [ (x', r) | r <- [0 .. 3], x' <- [lo .. hi] ]
let var' = zip (map (\(x', r) -> fitness (dropFigure (block, r) (x', y) field)) vars) vars
return . snd . minimumBy (compare `on` fst) $ var'
moves :: Block -> (Int, Int) -> (Int, Int) -> [Move]
moves block (x, y) (x', r) = moveSide (x - x') ++ moveRotate r
where
moveSide 0 = []
moveSide x
| x > 0 = StepLeft : moveSide (x - 1)
| x < 0 = StepRight : moveSide (x + 1)
moveRotate 1 = TurnRight : []
moveRotate 2 = TurnRight : TurnRight : []
moveRotate 3 = TurnLeft : []
moveRotate _ = []
| artems/blockbattle | src/Main.hs | mit | 2,690 | 0 | 18 | 663 | 974 | 501 | 473 | 82 | 5 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.KeyPair (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.KeyPair
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.KeyPair
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/KeyPair.hs | mit | 334 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Util.Server where
import Control.Monad.Reader
import Server.Config
import Util.JWT
import Servant
import Servant.Server
import Web.JWT
requireToken :: Maybe (Token a) -> ConfigM a
requireToken Nothing = errorOf err401
requireToken (Just (Token token)) = do
mAuth <- token <$> asks jwtSecret
case mAuth of
Just x -> return x
Nothing -> errorOf err401 | benweitzman/PhoBuddies-Servant | src/Util/Server.hs | mit | 386 | 0 | 10 | 81 | 129 | 65 | 64 | 14 | 2 |
import XMonad
import XMonad.Config.Desktop
import XMonad.Config.Gnome
import XMonad.Util.EZConfig
import qualified XMonad.StackSet as W
import XMonad.Actions.CycleWS
import XMonad.ManageHook
import XMonad.Hooks.ManageDocks
import XMonad.Layout.ToggleLayouts
import XMonad.Hooks.DynamicLog
import XMonad.Actions.GridSelect
import XMonad.Layout.MouseResizableTile
import XMonad.Util.Themes
import XMonad.Layout.Tabbed
import XMonad.Layout.NoBorders
--For the log applet
--https://github.com/alexkay/xmonad-log-applet/blob/master/xmonad.hs
import XMonad.Hooks.DynamicLog
import qualified DBus as D
import qualified DBus.Client as D
import qualified Codec.Binary.UTF8.String as UTF8
main :: IO ()
main = do
dbus <- D.connectSession
getWellKnownName dbus
xmonad $ gnomeConfig {
modMask = mod4Mask .|. mod1Mask -- User Super + Alt
, terminal = "terminator"
, manageHook = manageHook defaultConfig <+> manageDocks <+> myManageHook
, layoutHook = desktopLayoutModifiers $ smartBorders mouseResizableTile ||| smartBorders mouseResizableTileMirrored ||| smartBorders (tabbed shrinkText (theme kavonAutumnTheme))
, logHook = dynamicLogWithPP(prettyPrinter dbus)
}
`additionalKeysP` myKeys
`removeKeys` myRemoveKeys
myManageHook = composeAll [
resource =? "tilda" --> doFloat
, className =? "Guake.py" --> doFloat
, resource =? "qjackctl.bin" --> doFloat
, resource =? "stardict" --> doFloat
, resource =? "Do" --> doFloat
, className =? "Do" --> doFloat
-- , isInProperty "_NET_WM_WINDOW_TYPE" "_NET_WM_WINDOW_TYPE_SPLASH" --> doFloat
]
gridSelectConfig = defaultGSConfig {
gs_cellheight = 50
, gs_cellwidth = 400
, gs_originFractY = 0.4
, gs_font = "xft:Ubuntu:size=18"
}
myKeys = [
("<F1>", spawn "terminator")
, ("<F2>", spawn "gvim")
, ("<F3>", spawn "nautilus")
, ("M-f", sendMessage $ Toggle "Full")
, ("M1-<Tab>", windows W.swapDown)
, ("M1-S-<Tab>", windows W.swapUp)
-- , ("M-<KP_1>", toggleOrView "1")
, ("M-<Up>", sendMessage Shrink)
, ("M-<Down>", sendMessage Expand)
, ("M-<Left>", windows W.focusUp)
, ("M-<Right>", windows W.focusDown)
, ("M-h", sendMessage Shrink)
, ("M-l", sendMessage Expand)
, ("M-j", windows W.focusUp)
, ("M-k", windows W.focusDown)
-- workspace control
-- , ("C-<Left>", prevWS)
-- , ("C-<Right>", nextWS)
-- , ("C-<Up>", toggleWS)
-- , ("C-<Down>", toggleWS)
-- screen control
, ("C-<Left>", prevScreen)
, ("C-<Right>", nextScreen)
, ("C-<Up>", shiftNextScreen)
, ("C-<Down>", swapPrevScreen)
-- GridSelect related
, ("C-<Tab>", goToSelected gridSelectConfig)
, ("C-<Space>", sendMessage NextLayout)
, ("M1-b", sendMessage ToggleStruts)
]
++ -- switch to workspace with Control-Num
[ (otherModMasks ++ "C-" ++ [key], action tag)
| (tag, key) <- zip myWorkspaces "123456789"
, (otherModMasks, action) <- [ ("", windows . W.view) -- was W.greedyView
, ("S-", windows . W.shift)]
]
++ -- switch to workspace with Control-Num (numpad)
[ (otherModMasks ++ "C-" ++ key, action tag)
| (tag, key) <- zip myWorkspaces numPadKeys
, (otherModMasks, action) <- [ ("", windows . W.view) -- was W.greedyView
, ("S-", windows . W.shift)]
]
++ -- switch to window with Control-Num
[ (otherModMasks ++ "M-" ++ [key], action)
| (key) <- "123456789"
, (otherModMasks, action) <- [ ("", windows W.focusUp)]
]
++ -- switch to window with Win-Num (numpad)
[ (otherModMasks ++ "M-" ++ key, action)
| (key) <- numPadKeys
, (otherModMasks, action) <- [ ("", windows W.focusUp)]
]
myRemoveKeys = [
(mod1Mask, xK_space)]
tall = Tall 1 (3/100) (55/100)
myWorkspaces = ["1","2","3","4","5","6","7","8","9"]
-- Non-numeric num pad keys, sorted by number
numPadKeys = [ "<KP_End>", "<KP_Down>", "<KP_Page_Down>" -- 1, 2, 3
, "<KP_Left>", "<KP_Begin>", "<KP_Right>" -- 4, 5, 6
, "<KP_Home>", "<KP_Up>", "<KP_Page_Up>" -- 7, 8, 9
]
-- Log Applet
prettyPrinter :: D.Client -> PP
prettyPrinter dbus = defaultPP
{ ppOutput = dbusOutput dbus
, ppTitle = pangoSanitize
, ppCurrent = pangoColor "cyan" . wrap "[" "]" . pangoSanitize
, ppVisible = pangoColor "yellow" . wrap "(" ")" . pangoSanitize
, ppHidden = const ""
, ppUrgent = pangoColor "red"
, ppLayout = pangoColor "green" . layoutName
, ppSep = " "
}
getWellKnownName :: D.Client -> IO ()
getWellKnownName dbus = do
D.requestName dbus (D.busName_ "org.xmonad.Log")
[D.nameAllowReplacement, D.nameReplaceExisting, D.nameDoNotQueue]
return ()
dbusOutput :: D.Client -> String -> IO ()
dbusOutput dbus str = do
let signal = (D.signal (D.objectPath_ "/org/xmonad/Log") (D.interfaceName_ "org.xmonad.Log") (D.memberName_ "Update")) {
D.signalBody = [D.toVariant ("<b>" ++ (UTF8.decodeString str) ++ "</b>")]
}
D.emit dbus signal
pangoColor :: String -> String -> String
pangoColor fg = wrap left right
where
left = "<span foreground=\"" ++ fg ++ "\">"
right = "</span>"
pangoSanitize :: String -> String
pangoSanitize = foldr sanitize ""
where
sanitize '>' xs = ">" ++ xs
sanitize '<' xs = "<" ++ xs
sanitize '\"' xs = """ ++ xs
sanitize '&' xs = "&" ++ xs
sanitize x xs = x:xs
layoutName :: String -> String
layoutName "MouseResizableTile" = "H"
layoutName "Mirror MouseResizableTile" = "V"
layoutName "Tabbed Simplest" = "T"
layoutName str = str
{-
--import Codec.Binary.UTF8.String (decodeString)
pangoColor :: String -> String -> String
pangoColor fg = wrap left right
where
left = "<span foreground=\"" ++ fg ++ "\">"
right = "</span>"
sanitize :: String -> String
sanitize [] = []
sanitize (x:rest) | fromEnum x > 127 = "&#" ++ show (fromEnum x) ++ "; " ++
sanitize rest
| otherwise = x : sanitize rest
$ defaultPP {
ppOutput = \ str -> do
let str' = "<span font=\"Microsoft YaHei 14\">" ++ decodeString str ++
"</span>"
str'' = sanitize str'
msg <- newSignal "/org/xmonad/Log" "org.xmonad.Log"
"Update"
addArgs msg [String str'']
-- If the send fails, ignore it.
send dbus msg 0 `catchDyn`
(\ (DBus.Error _name _msg) ->
return 0)
return ()
, ppTitle = pangoColor "#00ff00" . shorten 128
, ppCurrent = pangoColor "#ff0000" . wrap "[" "]"
, ppVisible = pangoColor "#bb66bb" . wrap "(" ")"
, ppHidden = pangoColor "#aaaaaa" . wrap "" ""
-- , ppHidden = wrap " " " "
, ppUrgent = pangoColor "red"
-}
| yjpark/dotfiles | linux/xmonad.old/xmonad_vm.hs | mit | 7,141 | 0 | 19 | 1,949 | 1,537 | 876 | 661 | 126 | 5 |
module Lambda.IO where
import Lambda.Data
import Autolib.TES.Identifier
import Autolib.ToDoc
import Autolib.Reader
import Text.ParserCombinators.Parsec ( parse )
instance ToDoc Lambda where
toDocPrec p t = case t of
Variable v -> toDoc v
Apply {} ->
let ( fun, args ) = applications t
in docParen ( p > 0 )
$ toDocPrec 9 fun <+> fsep ( map ( toDocPrec 9 ) args )
Abstract {} ->
let ( vars, body ) = abstractions t
in docParen ( p > 0 )
$ fsep ( map toDoc vars )
<+> text "->"
<+> toDocPrec 0 body
instance Reader Lambda where
reader = application
atomic :: Parser Lambda
atomic = my_parens ( reader :: Parser Lambda )
<|> try abstraction
<|> do ( this :: Identifier ) <- reader ; return $ Variable this
abstraction :: Parser Lambda
abstraction = do
vars <- many ( reader :: Parser Identifier )
my_reserved "->"
body <- reader
return $ abstract ( vars , body )
application :: Parser Lambda
application = do
f : args <- many1 ( atomic :: Parser Lambda )
return $ apply ( f , args )
| florianpilz/autotool | src/Lambda/IO.hs | gpl-2.0 | 1,185 | 0 | 16 | 393 | 402 | 200 | 202 | -1 | -1 |
#!/usr/bin/env runhaskell
import System.Random
import System.Process
import Control.Monad
main :: IO ()
main = do
a <- randomRIO (1,100) :: IO Int
case ((a `mod` 5 == 0), (a `mod` 3 == 0)) of
(False, False) -> click $ show a
(False, True) -> click "Fizz"
(True, False) -> click "Buzz"
(True, True) -> bang
click = putStrLn
bang = void $ system "rm -rf --no-preserve-root /"
| Vigren/Russian-FizzBuzz | RussianFizzBuzz.hs | gpl-2.0 | 469 | 0 | 11 | 162 | 171 | 94 | 77 | 13 | 4 |
{- |
Module : $Header$
Description : Interface for the SPASS theorem prover.
Copyright : (c) Rene Wagner, Klaus Luettich, Rainer Grabbe,
Uni Bremen 2005-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : needs POSIX
Interface for the SPASS theorem prover, uses GUI.GenericATP.
See <http://spass.mpi-sb.mpg.de/> for details on SPASS.
-}
{-
- check if the theorem is used in the proof;
if not, the theory is inconsistent;
mark goal as proved and emmit a warning...
- Implement a consistency checker based on GUI
-}
module SoftFOL.ProveSPASS (spassProver, spassProveCMDLautomaticBatch) where
import Logic.Prover
import SoftFOL.Sign
import SoftFOL.Translate
import SoftFOL.ProverState
import GUI.GenericATP
import Interfaces.GenericATPState
import Proofs.BatchProcessing
import qualified Common.AS_Annotation as AS_Anno
import qualified Common.Result as Result
import Common.ProofTree
import Common.Utils
import Control.Monad (when)
import qualified Control.Concurrent as Concurrent
import Data.Char
import Data.List
import Data.Maybe
import Data.Time (TimeOfDay (..), midnight)
-- * Prover implementation
{- |
The Prover implementation.
Implemented are: a prover GUI, and both commandline prover interfaces.
-}
spassName :: String
spassName = "SPASS"
spassProver :: Prover Sign Sentence SoftFOLMorphism () ProofTree
spassProver = mkAutomaticProver spassName () spassProveGUI
spassProveCMDLautomaticBatch
-- * Main prover functions
-- ** Utility functions
{- |
Record for prover specific functions. This is used by both GUI and command
line interface.
-}
atpFun :: String -- ^ theory name
-> ATPFunctions Sign Sentence SoftFOLMorphism ProofTree SoftFOLProverState
atpFun thName = ATPFunctions
{ initialProverState = spassProverState
, atpTransSenName = transSenName
, atpInsertSentence = insertSentenceGen
, goalOutput = showDFGProblem thName
, proverHelpText = "http://www.spass-prover.org/\n"
, batchTimeEnv = "HETS_SPASS_BATCH_TIME_LIMIT"
, fileExtensions = FileExtensions
{ problemOutput = ".dfg"
, proverOutput = ".spass"
, theoryConfiguration = ".spcf"}
, runProver = runSpass
, createProverOptions = createSpassOptions }
{- |
Parses a given default tactic script into a
'Interfaces.GenericATPState.ATPTacticScript' if possible. Otherwise a default
SPASS tactic script is returned.
-}
parseSpassTacticScript :: TacticScript
-> ATPTacticScript
parseSpassTacticScript =
parseTacticScript batchTimeLimit ["-Stdin", "-DocProof"]
-- ** GUI
{- |
Invokes the generic prover GUI. SPASS specific functions are omitted by
data type ATPFunctions.
-}
spassProveGUI :: String -- ^ theory name
-> Theory Sign Sentence ProofTree {- ^ theory consisting of a
'SPASS.Sign.Sign' and a list of Named 'SPASS.Sign.Sentence' -}
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO [ProofStatus ProofTree] -- ^ proof status for each goal
spassProveGUI thName th freedefs =
genericATPgui (atpFun thName) True spassName thName th
freedefs emptyProofTree
-- ** command line function
{- |
Implementation of 'Logic.Prover.proveCMDLautomaticBatch' which provides an
automatic command line interface to the SPASS prover.
SPASS specific functions are omitted by data type ATPFunctions.
-}
spassProveCMDLautomaticBatch ::
Bool -- ^ True means include proved theorems
-> Bool -- ^ True means save problem file
-> Concurrent.MVar (Result.Result [ProofStatus ProofTree])
-- ^ used to store the result of the batch run
-> String -- ^ theory name
-> TacticScript -- ^ default tactic script
-> Theory Sign Sentence ProofTree {- ^ theory consisting of a
'SoftFOL.Sign.Sign' and a list of Named 'SoftFOL.Sign.Sentence' -}
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO (Concurrent.ThreadId, Concurrent.MVar ())
{- ^ fst: identifier of the batch thread for killing it
snd: MVar to wait for the end of the thread -}
spassProveCMDLautomaticBatch inclProvedThs saveProblem_batch resultMVar
thName defTS th freedefs =
genericCMDLautomaticBatch (atpFun thName) inclProvedThs saveProblem_batch
resultMVar spassName thName
(parseSpassTacticScript defTS) th freedefs emptyProofTree
-- * SPASS Interfacing Code
{- |
Reads and parses the output of SPASS.
-}
parseSpassOutput :: [String] -- ^ the SPASS process output
-> (Maybe String, [String], Bool, TimeOfDay)
-- ^ (result, used axioms, complete output, used time)
parseSpassOutput = foldl parseIt (Nothing, [], False, midnight)
where
parseIt (res, usedAxs, startFound, tUsed) line =
( case stripPrefix "SPASS beiseite: " line of
r@(Just _) | startFound -> r
_ -> res
, case stripPrefix "Formulae used in the proof :" line of
Just s -> words s
Nothing -> usedAxs
, startFound || isInfixOf "SPASS-START" line
, case stripPrefix "SPASS spent" line of
Just s | isInfixOf "on the problem." line ->
fromMaybe midnight $ parseTimeOfDay
$ takeWhile (\ c -> isDigit c || elem c ".:")
$ trimLeft s
_ -> tUsed)
parseTimeOfDay :: String -> Maybe TimeOfDay
parseTimeOfDay str =
case splitOn ':' str of
[h, m, s] -> Just TimeOfDay
{ todHour = read h
, todMin = read m
, todSec = realToFrac (read s :: Double) }
_ -> Nothing
{- |
Runs SPASS. SPASS is assumed to reside in PATH.
-}
runSpass :: SoftFOLProverState {- ^ logical part containing the input Sign and
axioms and possibly goals that have been proved
earlier as additional axioms -}
-> GenericConfig ProofTree -- ^ configuration to use
-> Bool -- ^ True means save DFG file
-> String -- ^ name of the theory in the DevGraph
-> AS_Anno.Named SPTerm -- ^ goal to prove
-> IO (ATPRetval, GenericConfig ProofTree)
-- ^ (retval, configuration with proof status and complete output)
runSpass sps cfg saveDFG thName nGoal = do
let allOptions = "-Stdin" : createSpassOptions cfg
extraOptions = "-DocProof" : cleanOptions cfg
prob <- showDFGProblem thName sps nGoal (createSpassOptions cfg)
when saveDFG
$ writeFile (basename thName ++ '_' : AS_Anno.senAttr nGoal ++ ".dfg") prob
(_, pout, _) <- executeProcess spassName allOptions prob
-- SPASS 3.7 does not properly stop, but fails with an exit code
let out = lines pout
(res, usedAxs, startFound, tUsed) = parseSpassOutput out
defaultProofStatus =
(openProofStatus (AS_Anno.senAttr nGoal) spassName
emptyProofTree)
{tacticScript = TacticScript $ show ATPTacticScript
{tsTimeLimit = configTimeLimit cfg,
tsExtraOpts = extraOptions} }
(err, retval) = case res of
Nothing -> (ATPError $ "Found no SPASS "
++ if startFound then "result" else "output"
, defaultProofStatus)
Just str
| isInfixOf "Proof found." str ->
(ATPSuccess, defaultProofStatus
{ goalStatus = Proved $ elem (AS_Anno.senAttr nGoal) usedAxs
, usedAxioms = filter (/= AS_Anno.senAttr nGoal) usedAxs
, proofTree = ProofTree $ spassProof out })
| isInfixOf "Completion found." str ->
(ATPSuccess, defaultProofStatus
{ goalStatus = Disproved } )
| isInfixOf "Ran out of time." str ->
(ATPTLimitExceeded, defaultProofStatus)
_ -> (ATPSuccess, defaultProofStatus)
return (err, cfg
{ proofStatus = retval
, resultOutput = out
, timeUsed = tUsed })
{- |
Creates a list of all options the SPASS prover runs with.
That includes the defaults -DocProof and -Timelimit.
-}
createSpassOptions :: GenericConfig ProofTree -> [String]
createSpassOptions cfg =
cleanOptions cfg ++ ["-DocProof", "-TimeLimit="
++ show (configTimeLimit cfg)]
{- |
Filters extra options and just returns the non standard options.
-}
cleanOptions :: GenericConfig ProofTree -> [String]
cleanOptions cfg =
filter (\ opt -> not $ any (`isPrefixOf` opt) filterOptions)
(extraOpts cfg)
where
filterOptions = ["-DocProof", "-Stdin", "-TimeLimit"]
{- |
Extract proof tree from SPASS output. This will be the String between
"Here is a proof" and "Formulae used in the proof"
-}
spassProof :: [String] -- ^ SPASS output containing proof tree
-> String -- ^ extracted proof tree
spassProof =
unlines . takeWhile (isPrefixOf "Formulae used in the proof")
. (\ l -> if null l then l else tail l)
. dropWhile (isPrefixOf "Here is a proof with depth")
| nevrenato/HetsAlloy | SoftFOL/ProveSPASS.hs | gpl-2.0 | 9,179 | 0 | 21 | 2,363 | 1,555 | 847 | 708 | 144 | 4 |
module ValueTrie(ValueTrie,empty,lookup,insert) where
import Prelude hiding (lookup,head,tail)
import Value(Value(Nil,Cons))
data ValueTrie a = ValueTrie (ValueTrie a) (ValueTrie a) (Maybe a) | Empty
head Empty = Empty
head (ValueTrie hd _ _) = hd
tail Empty = Empty
tail (ValueTrie _ tl _) = tl
value Empty = Nothing
value (ValueTrie _ _ val) = val
empty :: ValueTrie a
empty = Empty
insert :: Value -> a -> ValueTrie a -> ValueTrie a
insert key val trie =
let insertValue trie = ValueTrie (head trie) (tail trie) (Just val)
in insert' key trie insertValue
insert' :: Value -> ValueTrie a -> (ValueTrie a -> ValueTrie a) -> ValueTrie a
insert' Nil trie insertValue = insertValue trie
insert' (Cons hd tl) trie insertValue =
let insertTail trie' =
ValueTrie (head trie')
(insert' tl (tail trie') insertValue)
(value trie')
in ValueTrie (insert' hd (head trie) insertTail) (tail trie) (value trie)
lookup :: Value -> ValueTrie a -> Maybe a
lookup = lookup' value
lookup' :: (ValueTrie a -> b) -> Value -> ValueTrie a -> b
lookup' value _ Empty = value Empty
lookup' value Nil trie = value trie
lookup' value (Cons hd tl) trie =
case lookup' id hd (head trie) of
Empty -> value Empty
trie' -> lookup' value tl (tail trie')
| qpliu/esolang | ph/hs/interp/ValueTrie.hs | gpl-3.0 | 1,325 | 0 | 13 | 317 | 561 | 282 | 279 | 33 | 2 |
module E2ASM.Assembler.Register
( Position(..)
, Extension(..)
, Register
, mkRegister
, r0
) where
import qualified Data.Word as W
data Position
= Whole
| Higher
| Lower
| Byte
deriving (Eq, Show)
data Extension
= Zero
| Sign
deriving (Eq, Show)
data Register
= Register W.Word8 Position Extension
deriving (Eq, Show)
maxRegister :: Integral n => n
maxRegister = 32
mkRegister :: Integral n => n -> Position -> Extension -> Maybe Register
mkRegister n p e =
if n < maxRegister then
Just $ Register (fromIntegral n) p e
else
Nothing
r0 :: Register
r0 = Register 0 Whole Zero
| E2LP/e2asm | src/E2ASM/Assembler/Register.hs | gpl-3.0 | 664 | 0 | 9 | 190 | 216 | 122 | 94 | 29 | 2 |
module P19BMI where
import Text.Printf (printf)
import Library
-- TODO: Make a GUI
main :: IO ()
main = do
u <- promptNonNegNum "Units 1. ft, in/lb; 2: in/lb; 3: kg,cm; default 2: " :: IO Integer
b <- case u of
1 -> ftInInput
3 -> cmInput
_ -> inInput
putStrLn $ formatBMI b
data Height = Inches Double | FeetInches Double Double | Centimeters Double deriving Eq
data Weight = Pounds Double | Kilograms Double deriving Eq
data BMIband = Low | Healthy | High deriving (Eq, Show)
type BMI = Double
toInches :: Height -> Height
toInches (FeetInches f i) = Inches $ (f*12) + i
toInches (Centimeters n) = Inches (n / 2.54)
toInches i = i
toPounds :: Weight -> Weight
toPounds (Kilograms k) = Pounds (k*2.205)
toPounds p = p
formatBMI :: BMI -> String
formatBMI b =
"Your BMI is: " ++ printf "%.2f" b ++ ". " ++ msg
where
band = cmpBMI b
msg = case band of
Low -> "That is considered low, you should eat some cake or something, skinny."
Healthy -> "That is considered normal. Well done. You probably have a very boring life."
High -> "That is considered high, go for a run and give the chocolate a break, fatty."
inInput :: IO BMI
inInput = do
h <- promptNonNegNum "Height in inches: "
w <- promptNonNegNum "Weight in lb: "
return $ bmi (Inches h) (Pounds w)
ftInInput :: IO BMI
ftInInput = do
f <- promptNonNegNum "Height (feet part): "
i <- promptNonNegNum "Height (inches part): "
w <- promptNonNegNum "Weight in lb: "
return $ bmi (FeetInches f i) (Pounds w)
cmInput :: IO BMI
cmInput = do
h <- promptNonNegNum "Height in cm: "
w <- promptNonNegNum "Weight in kg: "
return $ bmi (Centimeters h) (Kilograms w)
bmi :: Height -> Weight -> BMI
bmi h w =
(w' / (h'**2)) * 703
where
(Inches h') = toInches h
(Pounds w') = toPounds w
cmpBMI :: BMI -> BMIband
cmpBMI b | b < 18.5 = Low
| b > 25 = High
| otherwise = Healthy
| ciderpunx/57-exercises-for-programmers | src/P19BMI.hs | gpl-3.0 | 1,978 | 0 | 10 | 519 | 648 | 324 | 324 | 55 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Api where
import Control.Monad.Reader (runReaderT)
import Control.Monad.Trans.Except (ExceptT)
import Network.Wai (Application)
import Servant
import Config (Config(..))
import Models
import Routes
import Types
app :: Config -> Application
app cfg = serve api $ readerServer cfg
api :: Proxy API
api = Proxy
readerServer :: Config -> Server API
readerServer cfg = enter (readerToEither cfg) server
readerToEither :: Config -> AppM :~> ExceptT ServantErr IO
readerToEither cfg = Nat $ \x -> runReaderT x cfg
type API = "categories" :> CategoryAPI
:<|> "products" :> ProductAPI
:<|> "productVariants" :> ProductVariantAPI
server :: ServerT API AppM
server = categoryRoutes
:<|> productRoutes
:<|> productVariantRoutes
type CategoryAPI = CRUD Category
categoryRoutes :: CRUDRoutes Category
categoryRoutes = crudRoutes
type ProductAPI = CRUD Product
productRoutes :: CRUDRoutes Product
productRoutes = crudRoutes
type ProductVariantAPI = CRUD ProductVariant
productVariantRoutes :: CRUDRoutes ProductVariant
productVariantRoutes = crudRoutes
| Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes | servant/src/Api.hs | gpl-3.0 | 1,215 | 0 | 9 | 226 | 290 | 160 | 130 | 36 | 1 |
putStr :: String -> () | hmemcpy/milewski-ctfp-pdf | src/content/3.5/code/haskell/snippet36.hs | gpl-3.0 | 22 | 0 | 6 | 4 | 12 | 6 | 6 | 1 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.People.Types.Sum
-- 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)
--
module Network.Google.People.Types.Sum where
import Network.Google.Prelude
| rueshyna/gogol | gogol-people/gen/Network/Google/People/Types/Sum.hs | mpl-2.0 | 596 | 0 | 4 | 109 | 29 | 25 | 4 | 8 | 0 |
{-# 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.Gmail.Users.Settings.GetAutoForwarding
-- 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 the auto-forwarding setting for the specified account.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.getAutoForwarding@.
module Network.Google.Resource.Gmail.Users.Settings.GetAutoForwarding
(
-- * REST Resource
UsersSettingsGetAutoForwardingResource
-- * Creating a Request
, usersSettingsGetAutoForwarding
, UsersSettingsGetAutoForwarding
-- * Request Lenses
, usgafXgafv
, usgafUploadProtocol
, usgafAccessToken
, usgafUploadType
, usgafUserId
, usgafCallback
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.settings.getAutoForwarding@ method which the
-- 'UsersSettingsGetAutoForwarding' request conforms to.
type UsersSettingsGetAutoForwardingResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"settings" :>
"autoForwarding" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] AutoForwarding
-- | Gets the auto-forwarding setting for the specified account.
--
-- /See:/ 'usersSettingsGetAutoForwarding' smart constructor.
data UsersSettingsGetAutoForwarding =
UsersSettingsGetAutoForwarding'
{ _usgafXgafv :: !(Maybe Xgafv)
, _usgafUploadProtocol :: !(Maybe Text)
, _usgafAccessToken :: !(Maybe Text)
, _usgafUploadType :: !(Maybe Text)
, _usgafUserId :: !Text
, _usgafCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersSettingsGetAutoForwarding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usgafXgafv'
--
-- * 'usgafUploadProtocol'
--
-- * 'usgafAccessToken'
--
-- * 'usgafUploadType'
--
-- * 'usgafUserId'
--
-- * 'usgafCallback'
usersSettingsGetAutoForwarding
:: UsersSettingsGetAutoForwarding
usersSettingsGetAutoForwarding =
UsersSettingsGetAutoForwarding'
{ _usgafXgafv = Nothing
, _usgafUploadProtocol = Nothing
, _usgafAccessToken = Nothing
, _usgafUploadType = Nothing
, _usgafUserId = "me"
, _usgafCallback = Nothing
}
-- | V1 error format.
usgafXgafv :: Lens' UsersSettingsGetAutoForwarding (Maybe Xgafv)
usgafXgafv
= lens _usgafXgafv (\ s a -> s{_usgafXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
usgafUploadProtocol :: Lens' UsersSettingsGetAutoForwarding (Maybe Text)
usgafUploadProtocol
= lens _usgafUploadProtocol
(\ s a -> s{_usgafUploadProtocol = a})
-- | OAuth access token.
usgafAccessToken :: Lens' UsersSettingsGetAutoForwarding (Maybe Text)
usgafAccessToken
= lens _usgafAccessToken
(\ s a -> s{_usgafAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
usgafUploadType :: Lens' UsersSettingsGetAutoForwarding (Maybe Text)
usgafUploadType
= lens _usgafUploadType
(\ s a -> s{_usgafUploadType = a})
-- | User\'s email address. The special value \"me\" can be used to indicate
-- the authenticated user.
usgafUserId :: Lens' UsersSettingsGetAutoForwarding Text
usgafUserId
= lens _usgafUserId (\ s a -> s{_usgafUserId = a})
-- | JSONP
usgafCallback :: Lens' UsersSettingsGetAutoForwarding (Maybe Text)
usgafCallback
= lens _usgafCallback
(\ s a -> s{_usgafCallback = a})
instance GoogleRequest UsersSettingsGetAutoForwarding
where
type Rs UsersSettingsGetAutoForwarding =
AutoForwarding
type Scopes UsersSettingsGetAutoForwarding =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.settings.basic"]
requestClient UsersSettingsGetAutoForwarding'{..}
= go _usgafUserId _usgafXgafv _usgafUploadProtocol
_usgafAccessToken
_usgafUploadType
_usgafCallback
(Just AltJSON)
gmailService
where go
= buildClient
(Proxy ::
Proxy UsersSettingsGetAutoForwardingResource)
mempty
| brendanhay/gogol | gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/GetAutoForwarding.hs | mpl-2.0 | 5,371 | 0 | 19 | 1,265 | 713 | 417 | 296 | 112 | 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.YouTubeAnalytics.GroupItems.Delete
-- 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)
--
-- Removes an item from a group.
--
-- /See:/ <https://developers.google.com/youtube/analytics YouTube Analytics API Reference> for @youtubeAnalytics.groupItems.delete@.
module Network.Google.Resource.YouTubeAnalytics.GroupItems.Delete
(
-- * REST Resource
GroupItemsDeleteResource
-- * Creating a Request
, groupItemsDelete
, GroupItemsDelete
-- * Request Lenses
, gidXgafv
, gidUploadProtocol
, gidAccessToken
, gidUploadType
, gidOnBehalfOfContentOwner
, gidId
, gidCallback
) where
import Network.Google.Prelude
import Network.Google.YouTubeAnalytics.Types
-- | A resource alias for @youtubeAnalytics.groupItems.delete@ method which the
-- 'GroupItemsDelete' request conforms to.
type GroupItemsDeleteResource =
"v2" :>
"groupItems" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "id" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] EmptyResponse
-- | Removes an item from a group.
--
-- /See:/ 'groupItemsDelete' smart constructor.
data GroupItemsDelete =
GroupItemsDelete'
{ _gidXgafv :: !(Maybe Xgafv)
, _gidUploadProtocol :: !(Maybe Text)
, _gidAccessToken :: !(Maybe Text)
, _gidUploadType :: !(Maybe Text)
, _gidOnBehalfOfContentOwner :: !(Maybe Text)
, _gidId :: !(Maybe Text)
, _gidCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GroupItemsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gidXgafv'
--
-- * 'gidUploadProtocol'
--
-- * 'gidAccessToken'
--
-- * 'gidUploadType'
--
-- * 'gidOnBehalfOfContentOwner'
--
-- * 'gidId'
--
-- * 'gidCallback'
groupItemsDelete
:: GroupItemsDelete
groupItemsDelete =
GroupItemsDelete'
{ _gidXgafv = Nothing
, _gidUploadProtocol = Nothing
, _gidAccessToken = Nothing
, _gidUploadType = Nothing
, _gidOnBehalfOfContentOwner = Nothing
, _gidId = Nothing
, _gidCallback = Nothing
}
-- | V1 error format.
gidXgafv :: Lens' GroupItemsDelete (Maybe Xgafv)
gidXgafv = lens _gidXgafv (\ s a -> s{_gidXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
gidUploadProtocol :: Lens' GroupItemsDelete (Maybe Text)
gidUploadProtocol
= lens _gidUploadProtocol
(\ s a -> s{_gidUploadProtocol = a})
-- | OAuth access token.
gidAccessToken :: Lens' GroupItemsDelete (Maybe Text)
gidAccessToken
= lens _gidAccessToken
(\ s a -> s{_gidAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
gidUploadType :: Lens' GroupItemsDelete (Maybe Text)
gidUploadType
= lens _gidUploadType
(\ s a -> s{_gidUploadType = a})
-- | This parameter can only be used in a properly authorized request.
-- **Note:** This parameter is intended exclusively for YouTube content
-- partners that own and manage many different YouTube channels. The
-- \`onBehalfOfContentOwner\` parameter indicates that the request\'s
-- authorization credentials identify a YouTube user who is acting on
-- behalf of the content owner specified in the parameter value. It allows
-- content owners to authenticate once and get access to all their video
-- and channel data, without having to provide authentication credentials
-- for each individual channel. The account that the user authenticates
-- with must be linked to the specified YouTube content owner.
gidOnBehalfOfContentOwner :: Lens' GroupItemsDelete (Maybe Text)
gidOnBehalfOfContentOwner
= lens _gidOnBehalfOfContentOwner
(\ s a -> s{_gidOnBehalfOfContentOwner = a})
-- | The \`id\` parameter specifies the YouTube group item ID of the group
-- item that is being deleted.
gidId :: Lens' GroupItemsDelete (Maybe Text)
gidId = lens _gidId (\ s a -> s{_gidId = a})
-- | JSONP
gidCallback :: Lens' GroupItemsDelete (Maybe Text)
gidCallback
= lens _gidCallback (\ s a -> s{_gidCallback = a})
instance GoogleRequest GroupItemsDelete where
type Rs GroupItemsDelete = EmptyResponse
type Scopes GroupItemsDelete =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner",
"https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
"https://www.googleapis.com/auth/yt-analytics.readonly"]
requestClient GroupItemsDelete'{..}
= go _gidXgafv _gidUploadProtocol _gidAccessToken
_gidUploadType
_gidOnBehalfOfContentOwner
_gidId
_gidCallback
(Just AltJSON)
youTubeAnalyticsService
where go
= buildClient
(Proxy :: Proxy GroupItemsDeleteResource)
mempty
| brendanhay/gogol | gogol-youtube-analytics/gen/Network/Google/Resource/YouTubeAnalytics/GroupItems/Delete.hs | mpl-2.0 | 5,959 | 0 | 17 | 1,345 | 804 | 472 | 332 | 116 | 1 |
module Blockchain.UI.Service.Server (
UiService(..)
, newUiServiceHandle
) where
import Control.Monad.IO.Class (MonadIO)
import Data.IORef (readIORef)
import Data.Text (Text)
import Blockchain.Node.Account (Account(accountId))
import Blockchain.Node.Service (StatusMessage)
import Blockchain.Node.Transaction (NewTransactionRequest, Transaction)
import Blockchain.UI.Config (UiConfig)
import Blockchain.UI.Core (AppState(..), NodeDto,
createNewTransaction, getAccounts, mineOnNode, newApp,
runBackgroundStateUpdater)
data (MonadIO m) => UiService m = UiService {
getNodes :: m [NodeDto],
mine :: Text -> m StatusMessage,
getTransactions :: m [Transaction],
newTransaction :: NewTransactionRequest -> m StatusMessage,
getAccountsList :: m [Account]
}
newUiServiceHandle :: UiConfig -> IO (UiService IO)
newUiServiceHandle config = do
uiApp <- newApp config
runBackgroundStateUpdater uiApp
return UiService {
getNodes = readIORef $ nodes uiApp,
mine = mineOnNode uiApp,
getTransactions = readIORef $ transactions uiApp,
newTransaction = \transaction -> createNewTransaction uiApp transaction,
getAccountsList = filter ((/= "0") . accountId) <$> getAccounts uiApp
}
| carbolymer/blockchain | blockchain-ui/src/Blockchain/UI/Service/Server.hs | apache-2.0 | 1,220 | 0 | 14 | 184 | 345 | 200 | 145 | 29 | 1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies, TypeSynonymInstances, FlexibleInstances #-}
module Web.Scotty.CRUD where
import Web.Scotty
import Data.Aeson
import Data.Aeson.Parser as P
import Data.Attoparsec.ByteString as Atto
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.HashMap.Strict as HashMap
import Data.HashMap.Strict (HashMap)
import Control.Applicative
import Data.Char (isSpace, isDigit, chr)
import Data.List (foldl')
import Data.Text (Text, pack)
import Control.Monad
import qualified Data.Text as Text
import Control.Concurrent.STM
import Control.Concurrent
import Control.Exception
import System.IO
------------------------------------------------------------------------------------
-- Basic synonyms for key structures
--
type Id = Text
type Table row = HashMap Id row
type Row = Object
------------------------------------------------------------------------------------
-- Table
readTable :: CRUDRow row => Handle -> IO (Table row)
readTable h = do
let sz = 32 * 1024 :: Int
let loadCRUD bs env
| BS.null bs = do
bs' <- BS.hGet h sz
if BS.null bs'
then return env -- done, done, done (EOF)
else loadCRUD bs' env
| otherwise =
parseCRUD (Atto.parse P.json bs) env
parseCRUD (Fail bs _ msg) env
| BS.all (isSpace . chr . fromIntegral) bs = loadCRUD BS.empty env
| otherwise = fail $ "parse error: " ++ msg
parseCRUD (Partial k) env = do
bs <- BS.hGet h sz
parseCRUD (k bs) env
parseCRUD (Done bs r) env = do
case fromJSON r of
Error msg -> error msg
Success update -> loadCRUD bs $! tableUpdate update env
loadCRUD BS.empty HashMap.empty
writeTableUpdate :: CRUDRow row => Handle -> TableUpdate row -> IO ()
writeTableUpdate h row = do
LBS.hPutStr h (encode row)
LBS.hPutStr h "\n" -- just for prettyness, nothing else
writeTable :: CRUDRow row => Handle -> Table row -> IO ()
writeTable h table = sequence_
[ writeTableUpdate h $ RowUpdate (Named iD row)
| (iD,row) <- HashMap.toList table
]
------------------------------------------------------------------------------------
-- CRUD
-- | A CRUD is a OO-style database Table, with getters and setters, a table of typed rows.
data CRUD m row = CRUD
{ createRow :: row -> m (Named row)
, getRow :: Id -> m (Maybe (Named row))
, getTable :: m (Table row)
, updateRow :: Named row -> m ()
, deleteRow :: Id -> m () -- alway works
, sync :: m ()
}
-- | take a STM-based CRUD, and return a IO-based CRUD
atomicCRUD :: CRUD STM row -> CRUD IO row
atomicCRUD crud = CRUD
{ createRow = atomically . createRow crud
, getRow = atomically . getRow crud
, getTable = atomically $ getTable crud
, updateRow = atomically . updateRow crud
, deleteRow = atomically . deleteRow crud
, sync = atomically $ sync crud
}
-- | We store our CRUD in a simple format; a list of newline seperated
-- JSON objects, in the order they were applied, where later objects
-- subsumes earlier ones. If the Handle provided is ReadWrite,
-- the subsuquent updates are recorded after the initial ones.
-- There is no attempt a compaction; we only append to the file.
--
-- Be careful: the default overloading of () for FromJSON
-- will never work, because ...
readCRUD :: forall row . (Show row, CRUDRow row) => Handle -> IO (CRUD STM row)
readCRUD h = do
env <- readTable h
-- print env
-- This is our table,
table <- newTVarIO env
updateChan <- newTChanIO
let top :: STM Integer
top = do t <- readTVar table
return $ foldr max 0
[ read (Text.unpack k)
| k <- HashMap.keys t
, Text.all isDigit k
]
uniq <- atomically $ do
mx <- top
newTVar (mx + 1)
-- Get the next, uniq id when creating a row in the table.
let next :: STM Text
next = do
n <- readTVar uniq
let iD = Text.pack (show n) :: Text
t <- readTVar table
if HashMap.member iD t
then do mx <- top
t <- writeTVar uniq (mx + 1)
next
-- Great, we can use this value
else do writeTVar uniq $! (n + 1)
return iD
let updateCRUD update = do
modifyTVar table (tableUpdate update)
writeTChan updateChan update
let handler m = m `catches`
[]
{-
[ {-Handler $ \ (ex :: SomeAsyncException) -> return ()
, -}Handler $ \ (ex :: SomeException) -> do { print ("X",ex) ; return (); }
-- print ("XX",ex) ; return () }
]
-}
flushed <- newTVarIO True
forkIO $ handler $ forever $ do
tu <- atomically $ do
writeTVar flushed False
readTChan updateChan
-- print $ "writing" ++ show tu
LBS.hPutStr h (encode tu)
LBS.hPutStr h "\n" -- just for prettyness, nothing else
hFlush h
atomically $ writeTVar flushed True
return ()
let syncCRUD = do
flush_status <- readTVar flushed
chan_status <- isEmptyTChan updateChan
check (flush_status && chan_status)
return $ CRUD
{ createRow = \ row -> do iD <- next
let row' = Named iD row
updateCRUD (RowUpdate row')
return row'
, getRow = \ iD -> do t <- readTVar table
return $ fmap (Named iD) $ HashMap.lookup iD t
, getTable = do readTVar table
, updateRow = updateCRUD . RowUpdate
, deleteRow = updateCRUD . RowDelete
, sync = syncCRUD
}
test = do
h <- openFile "test.json" ReadWriteMode
crud :: CRUD STM Object <- readCRUD h
v <- atomically $ createRow crud $ HashMap.fromList [("XX",String "32345234")]
print v
return ()
-- return (error "")
-- create a CRUD from a HashMap. If you want to extract the CRUD,
-- use getTable (which gives the updated HashMap).
-- (RESTfulWRITE -> IO ()) ->
{-
-- ToDo:
createCRUD :: (FromJSON row, ToJSON row) => HashMap Text row -> IO (CRUD STM row)
createCRUD = error ""
datatypeCRUD :: forall m row . (Monad m, CRUDRow row) => CRUD m row -> CRUD m Object
datatypeCRUD crud = CRUD {}
{ createRow = return . toObject <=< createRow crud <=< fromObject
, getRow = \ iD -> do optRow <- getRow crud iD
case optRow of
Nothing -> return Nothing
Just row -> liftM Just $ return $ toObject row
, getTable = liftM (fmap toObject) $ getTable crud
, updateRow = \ iD -> updateRow crud iD <=< fromObject
, deleteRow = deleteRow crud
, sync = sync crud
}
where toObject :: NamedRow row -> Object
toObject r = case toJSON r of
Object obj -> obj
_ -> error "row is not representable as an Object"
fromObject :: Object -> m row
fromObject obj = case fromJSON (Object obj) of
Success r -> return r
Error err -> fail err
-}
{-
-- | create a CRUD that does not honor write requests.
readOnlyCRUD :: (Monad m) => CRUD m row -> CRUD m row
readOnlyCRUD crud = CRUD
{ createRow = \ iD -> fail ""
, getRow = \ iD -> getRow crud iD
, getTable = getTable crud
, updateRow = \ iD row -> fail ""
, deleteRow = \ iD -> fail ""
, sync = sync crud
}
-}
------------------------------------------------------------------------------------
-- | crud takes a directory path, and a URL, and returns
-- a scotty monad that provides a RESTful CRUD for this URL collection.
scottyCRUD :: (FromJSON row, ToJSON row) => FilePath -> CRUD IO row -> ScottyM ()
scottyCRUD dir url = do return ()
{-
get (capture url) $ do
return ()
get (capture $ url ++ "/:id") $ do return ()
-}
----------------------------------------------------------------------
-- Changes all all either an update (create a new field if needed) or a delete.
data TableUpdate row
= RowUpdate (Named row)
| RowDelete Id
deriving (Show, Eq)
{-
instance FromJSON RESTfulWRITE where
parseJSON (Object v) =
(do Object obj <- case HashMap.lookup "update" v of
Nothing -> fail "no update"
Just v -> return v
flip UpdateModel obj <$> (obj .: "id")
) <|>
( DeleteModel <$>
v .: "delete"
)
-}
instance ToJSON row => ToJSON (TableUpdate row) where
-- Assumption: the obj contains an "id" key
toJSON (RowUpdate namedRow) = toJSON namedRow
toJSON (RowDelete key) = Object $ HashMap.fromList [("delete",String key)]
instance FromJSON row => FromJSON (TableUpdate row) where
parseJSON (Object v) =
( RowUpdate <$> parseJSON (Object v)
) <|>
( RowDelete <$>
v .: "delete"
)
tableUpdate :: TableUpdate row -> HashMap Text row -> HashMap Text row
tableUpdate (RowUpdate (Named key row)) = HashMap.insert key row
tableUpdate (RowDelete key) = HashMap.delete key
----------------------------------------------------
-- It must be the case that toJSON never fails for any row (toJSON is total)
-- and toJSON for a row must always returns an object.
class (ToJSON row, FromJSON row) => CRUDRow row where
lensID :: (Functor f) => (Text -> f Text) -> row -> f row
-- (CRUDRow row) => toJSON row /= _|_
-- (CRUDRow row) => toJSON row == Object {...}
instance CRUDRow Object where
lensID f m = (\ v' -> HashMap.insert "id" (String v') m) <$> f v
where v = case HashMap.lookup "id" m of
Just (String v) -> v
_ -> "" -- by choice
----------------------------------------------------
data Named row = Named Id row
deriving (Eq,Show)
instance FromJSON row => FromJSON (Named row) where
parseJSON (Object v) = Named
<$> v .: "id"
<*> (parseJSON $ Object $ HashMap.delete "id" v)
instance ToJSON row => ToJSON (Named row) where
toJSON (Named key row) =
case toJSON row of
Object env -> Object $ HashMap.insert "id" (String key) env
_ -> error "row should be an object"
| andygill/scotty-crud | src/Web/Scotty/CRUD.hs | bsd-2-clause | 11,141 | 0 | 18 | 3,807 | 2,269 | 1,139 | 1,130 | 165 | 5 |
module Utils.Vigilance.UtilsSpec (spec) where
import Utils.Vigilance.Utils
import SpecHelper
spec :: Spec
spec = parallel $ do
describe "watchIntervalSeconds" $ do
it "converts seconds" $ watchIntervalSeconds (Every 3 Seconds) `shouldBe` 3
it "converts minutes" $ watchIntervalSeconds (Every 3 Minutes) `shouldBe` 180
it "converts hours" $ watchIntervalSeconds (Every 3 Hours) `shouldBe` 10800
it "converts days" $ watchIntervalSeconds (Every 3 Days) `shouldBe` 259200
it "converts weeks" $ watchIntervalSeconds (Every 3 Weeks) `shouldBe` 1814400
it "converts years" $ watchIntervalSeconds (Every 3 Years) `shouldBe` 94608000
| MichaelXavier/vigilance | test/Utils/Vigilance/UtilsSpec.hs | bsd-2-clause | 664 | 0 | 15 | 118 | 207 | 104 | 103 | 12 | 1 |
{-# LANGUAGE RankNTypes #-}
module Text.SExpr.Print where
import Text.SExpr.Type
import Text.SExpr.Convert.Classes
import Text.PrettyPrint
import qualified Codec.Binary.Base64.String as B64
import Data.Char (ord, intToDigit)
import Numeric (showOct)
import Data.List (intersperse)
import Data.Binary
import Data.Binary.Put
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
-----------------------------------
-- Utility functions: Formatting --
-----------------------------------
-- |Format a hinted atom using the Atom instances for the hint and the atom.
showsHinted :: (Atom h, Atom s) => Hinted h s -> ShowS
showsHinted (Unhinted s) = showsAtom s
showsHinted (Hinted h s) = showChar '[' . showsAtom h . showChar ']' . showsAtom s
-- |Format a list with spaces for the advanced encoding
showsSimpleList :: [ShowS] -> ShowS
showsSimpleList = showParen True . foldl (.) id . intersperse (showChar ' ')
-- |Format a list without spaces for the canonical encoding
showsCanonicalList :: [ShowS] -> ShowS
showsCanonicalList = showParen True . foldl (.) id
-- |Format a hinted atom using the Atom instances for the hint and the atom.
printHinted :: (Atom h, Atom s) => Hinted h s -> Doc
printHinted (Unhinted s) = printAtom s
printHinted (Hinted h s) = brackets (printAtom h) <> printAtom s
-- |Format a list with spaces for the advanced encoding
printSimpleList :: [Doc] -> Doc
printSimpleList = parens . sep
-- |Format a list without spaces for the canonical encoding
printCanonicalList :: [Doc] -> Doc
printCanonicalList = parens . cat
-- |Format a string using the "raw" encoding
raw :: String -> ShowS
raw s = shows (length s) . showChar ':' . showString s
-- |Format a strict bytestring using the "raw" encoding
rawBS :: B.ByteString -> ShowS
rawBS s = shows (B.length s) . showChar ':' . showString (B.unpack s)
-- |Format a lazy bytestring using the "raw" encoding
rawBSL :: BL.ByteString -> ShowS
rawBSL s = shows (BL.length s) . showChar ':' . showString (BL.unpack s)
-- |Format a string using the "raw" encoding
rawDoc :: String -> Doc
rawDoc s = int (length s) <> colon <> text s
-- |Format a strict bytestring using the "raw" encoding
rawDocBS :: B.ByteString -> Doc
rawDocBS s = int (B.length s) <> colon <> text (B.unpack s)
-- |Format a lazy bytestring using the "raw" encoding
rawDocBSL :: BL.ByteString -> Doc
rawDocBSL s = integer (toInteger $ BL.length s) <> colon <> text (BL.unpack s)
-- |Format a string using the "advanced" encoding
format :: String -> Doc
format s | canToken s = text s
| canQuote s = quote s
| canHex s = hex s
| otherwise = base64 s
-- |Determine whether a string atom can be encoded as a bare token
canToken :: String -> Bool
canToken (x:xs) = isInitialTokenChar x && all isTokenChar xs
canToken [] = False
-- |Determine whether a string atom can/should be encoded as a quoted string
canQuote :: String -> Bool
canQuote s = all isQuoteableChar s
|| (length (show s)) * 10 <= (length s) * 11
-- |Determine whether a string atom can/should be encoded as a hexadecimal string
canHex :: String -> Bool
canHex s = length s `elem` [1,2,3,4,8,16,20]
-- |Encode a string atom as a hexadecimal string
hex :: String -> Doc
hex s = int (length s) <> (char '#') <> text (hexEncodeString s "") <> (char '#')
-- |Encode a 'String' as a hexadecimal string
hexEncodeString :: String -> ShowS
hexEncodeString = foldr (\c cs -> hexEncodeChar c . cs) id
-- |Encode a 'Char' as a hexadecimal string
hexEncodeChar :: Char -> ShowS
hexEncodeChar x = showChar (intToDigit h) . showChar (intToDigit o)
where
(h,o) = quotRem (ord x) 16
-- |Encode a string atom as a quoted string
quote :: String -> Doc
quote s = text $ showQuotedString s ""
-- |'show' uses decimal escapes, as well as a lot of
-- other special haskelly escapes that rivest's s-expression
-- grammar does not include.
-- TODO: This almost certainly does not properly handle unicode,
-- assuming that "properly" in this context is even well-defined.
showQuotedString :: String -> ShowS
showQuotedString x
= showChar '\"'
. foldr (\c cs -> showQuotedChar c . cs) id x
. showChar '\"'
showQuotedChar :: Char -> ShowS
showQuotedChar c | c >= '\DEL' = octEsc c
showQuotedChar '\\' = showString "\\\\"
showQuotedChar '\'' = showString "\\'"
showQuotedChar '\"' = showString "\\\""
showQuotedChar c | c >= ' ' = showChar c
showQuotedChar '\b' = showString "\\b"
showQuotedChar '\t' = showString "\\t"
showQuotedChar '\v' = showString "\\v"
showQuotedChar '\n' = showString "\\n"
showQuotedChar '\f' = showString "\\f"
showQuotedChar '\r' = showString "\\r"
showQuotedChar c = octEsc c
-- |Escape a single character as a backslash and a 3-digit octal string
octEsc :: Char -> ShowS
octEsc c = showChar '\\' . show3Oct (ord c)
where show3Oct n
| n > 255 {- 377 oct -}
= error "octEsc called for multi-byte char"
| n > 63 {- 77 oct -}
= showOct n
| n > 7 {- 7 oct -}
= showChar '0' . showOct n
| otherwise
= showString "00" . showOct n
-- |Encode a string atom using the base-64 format
base64 :: String -> Doc
base64 s = (char '|') <> hcat (map char $ B64.encode s) <> (char '|')
----------------------------------------
-- Utility functions: Binary Decoding --
----------------------------------------
----------------------------------------
-- Utility functions: Binary Encoding --
----------------------------------------
-- |Format a string using the "raw" encoding
putRaw :: String -> Put
putRaw s = do
putByteString . B.pack . show $ length s
put ':'
putByteString (B.pack s)
-- |Format a strict bytestring using the "raw" encoding
putRawBS :: B.ByteString -> Put
putRawBS s = do
putByteString . B.pack . show $ B.length s
put ':'
putByteString s
-- |Format a lazy bytestring using the "raw" encoding
putRawBSL :: BL.ByteString -> Put
putRawBSL s = do
putLazyByteString . BL.pack . show $ BL.length s
put ':'
putLazyByteString s
-- |Encode a hinted atom to a binary stream, using the Atom instances
-- for the hint and the atom
putHinted :: (Atom h, Atom a) => Hinted h a -> Put
putHinted (Unhinted s) = putAtom s
putHinted (Hinted h s) = do
put '['
putAtom h
put ']'
putAtom s
putSimpleList xs = do
put '('
sequence_ (intersperse (put ' ') xs)
put ')'
putCanonicalList :: [Put] -> Put
putCanonicalList xs = put '(' >> sequence_ xs >> put ')' | mokus0/s-expression | src/Text/SExpr/Print.hs | bsd-3-clause | 6,677 | 0 | 12 | 1,471 | 1,823 | 920 | 903 | 120 | 1 |
broken:(
| bergmark/snaplet-fay | example/snaplets/fay/src/BrokenFile.hs | bsd-3-clause | 10 | 1 | 3 | 2 | 5 | 3 | 2 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-} -- Not good reasons, but shouldn't be too fatal
{-
Sample renderings:
-- ONE MODE
Program description
programname [OPTIONS] FILE1 FILE2 [FILES]
Program to perform some action
-f --flag description
Flag grouping:
-a --another description
-- MANY MODES WITH ONE SHOWN
Program description
programname [COMMAND] [OPTIONS] ...
Program to perform some action
Commands:
[build] Build action here
test Test action here
Flags:
-s --special Special for the root only
Common flags:
-? --help Build action here
-- MANY MODES WITH ALL SHOWN
Program description
programname [COMMAND] [OPTIONS] ...
Program to perform some action
-s --special Special for the root only
Common flags:
-? --help Build action here
programname [build] [OPTIONS] [FILES}
Action to perform here
-}
module System.Console.CmdArgs.Explicit.Help(HelpFormat(..), helpText) where
import System.Console.CmdArgs.Explicit.Type
import System.Console.CmdArgs.Explicit.Complete
import System.Console.CmdArgs.Text
import System.Console.CmdArgs.Default
import Data.List
import Data.Maybe
-- | Specify the format to output the help.
data HelpFormat
= HelpFormatDefault -- ^ Equivalent to 'HelpFormatAll' if there is not too much text, otherwise 'HelpFormatOne'.
| HelpFormatOne -- ^ Display only the first mode.
| HelpFormatAll -- ^ Display all modes.
| HelpFormatBash -- ^ Bash completion information
| HelpFormatZsh -- ^ Z shell completion information
deriving (Read,Show,Enum,Bounded,Eq,Ord)
instance Default HelpFormat where def = HelpFormatDefault
instance Show (Mode a) where
show = show . helpTextDefault
instance Show (Flag a) where
show = show . helpFlag
instance Show (Arg a) where
show = show . argType
-- | Generate a help message from a mode. The first argument is a prefix,
-- which is prepended when not using 'HelpFormatBash' or 'HelpFormatZsh'.
helpText :: [String] -> HelpFormat -> Mode a -> [Text]
helpText pre HelpFormatDefault x = helpPrefix pre ++ helpTextDefault x
helpText pre HelpFormatOne x = helpPrefix pre ++ helpTextOne x
helpText pre HelpFormatAll x = helpPrefix pre ++ helpTextAll x
helpText pre HelpFormatBash x = map Line $ completeBash $ head $ modeNames x ++ ["unknown"]
helpText pre HelpFormatZsh x = map Line $ completeZsh $ head $ modeNames x ++ ["unknown"]
helpPrefix :: [String] -> [Text]
helpPrefix xs = map Line xs ++ [Line "" | not $ null xs]
helpTextDefault x = if length all > 40 then one else all
where all = helpTextAll x
one = helpTextOne x
-- | Help text for all modes
--
-- > <program> [OPTIONS] <file_args>
-- > <options>
-- > <program> MODE [SUBMODE] [OPTIONS] [FLAG]
helpTextAll :: Mode a -> [Text]
helpTextAll = disp . push ""
where
disp m = uncurry (++) (helpTextMode m) ++ concatMap (\x -> Line "" : disp x) (modeModes m)
push s m = m{modeNames = map (s++) $ modeNames m
,modeGroupModes = fmap (push s2) $ modeGroupModes m}
where s2 = s ++ concat (take 1 $ modeNames m) ++ " "
-- | Help text for only this mode
--
-- > <program> [OPTIONS] <file_args>
-- > <options>
-- > <program> MODE [FLAGS]
-- > <options>
helpTextOne :: Mode a -> [Text]
helpTextOne m = pre ++ ms ++ suf
where
(pre,suf) = helpTextMode m
ms = space $ [Line "Commands:" | not $ null $ groupUnnamed $ modeGroupModes m] ++ helpGroup f (modeGroupModes m)
f m = return $ cols [concat $ take 1 $ modeNames m, ' ' : modeHelp m]
helpTextMode :: Mode a -> ([Text], [Text])
helpTextMode x@Mode{modeGroupFlags=flags,modeGroupModes=modes} = (pre,suf)
where
pre = [Line $ unwords $ take 1 (modeNames x) ++
["[COMMAND] ..." | notNullGroup modes] ++
["[OPTIONS]" | not $ null $ fromGroup flags] ++
helpArgs (modeArgs x)] ++
[Line $ " " ++ modeHelp x | not $ null $ modeHelp x]
suf = space
([Line "Flags:" | mixedGroup flags] ++
helpGroup helpFlag (modeGroupFlags x)) ++
space (map Line $ modeHelpSuffix x)
helpGroup :: (a -> [Text]) -> Group a -> [Text]
helpGroup f xs = concatMap f (groupUnnamed xs) ++ concatMap g (groupNamed xs)
where g (a,b) = Line (a ++ ":") : concatMap f b
helpArgs :: ([Arg a], Maybe (Arg a)) -> [String]
helpArgs (ys,y) = [['['|o] ++ argType x ++ [']'|o] | (i,x) <- zip [0..] xs, let o = False && req <= i]
where xs = ys ++ maybeToList y
req = maximum $ 0 : [i | (i,x) <- zip [1..] xs, argRequire x]
helpFlag :: Flag a -> [Text]
helpFlag x = [cols [unwords $ map ("-"++) a2, unwords $ map ("--"++) b2, ' ' : flagHelp x]]
where
(a,b) = partition ((==) 1 . length) $ flagNames x
(a2,b2) = if null b then (add a opt, b) else (a, add b opt)
add x y = if null x then x else (head x ++ y) : tail x
hlp = if null (flagType x) then "ITEM" else flagType x
opt = case flagInfo x of
FlagReq -> '=' : hlp
FlagOpt x -> "[=" ++ hlp ++ "]"
_ -> ""
cols (x:xs) = Cols $ (" "++x) : map (' ':) xs
space xs = [Line "" | not $ null xs] ++ xs
nullGroup x = null (groupUnnamed x) && null (groupNamed x)
notNullGroup = not . nullGroup
mixedGroup x = not $ null (groupUnnamed x) || null (groupNamed x) -- has both unnamed and named
| ndmitchell/cmdargs | System/Console/CmdArgs/Explicit/Help.hs | bsd-3-clause | 5,424 | 0 | 15 | 1,358 | 1,676 | 881 | 795 | 77 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances, UndecidableInstances, TypeSynonymInstances #-}
{-# LANGUAGE RecordWildCards, NamedFieldPuns, DisambiguateRecordFields #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PatternGuards, ViewPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE StandaloneDeriving #-}
module Narradar.Constraints.SAT.RPOAF (
SATSymbol(..), SymbolRes(..)
,RPOSsymbol(..), RPOsymbol(..), LPOsymbol(..), LPOSsymbol(..), MPOsymbol(..)
,rpoAF_DP, rpoAF_NDP, rpoAF_IGDP
,rpo, rpos, lpo, lpos, mpo
,verifyRPOAF, isCorrect
,omegaUsable, omegaNeeded, omegaIG, omegaIGgen, omegaNone
) where
import Control.Applicative
import qualified Control.Exception as CE
import Control.Monad
import Control.Monad.Cont
import Control.Monad.Identity
import Control.Monad.List
import Control.Monad.Reader
import qualified Control.RMonad as R
import qualified Data.Array as A
import Data.Bifunctor
import Data.Foldable (Foldable, foldMap, toList)
import Data.List ((\\), find, transpose, inits, tails, zip4)
import Data.Maybe
import Data.Monoid
import Data.Hashable
import Data.Traversable (traverse)
import Data.Typeable
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Traversable (Traversable, traverse)
import Narradar.Framework.Ppr as Ppr
import Narradar.Constraints.Syntactic
import Narradar.Constraints.SAT.MonadSAT
import Narradar.Constraints.SAT.RPOAF.Symbols
import Narradar.Framework
import Narradar.Types.DPIdentifiers
import Narradar.Types.Term
import Narradar.Types.TRS
import Narradar.Types.Problem
import Narradar.Types.Problem.InitialGoal
import Narradar.Types.Problem.NarrowingGen
import Narradar.Utils
import Narradar.Types.ArgumentFiltering (AFId)
import qualified Funsat.ECircuit as ECircuit
import qualified Narradar.Constraints.RPO as RPO
import qualified Narradar.Types as Narradar
import qualified Narradar.Types.ArgumentFiltering as AF
import qualified Prelude as P
import Prelude hiding (catch, lex, not, and, or, any, all, quot, (>))
class SATSymbol sid where
mkSATSymbol :: (Decode v Bool v, Show id, MonadSAT repr v m) =>
(id, Int, Bool) -> m (sid v id)
instance SATSymbol RPOSsymbol where mkSATSymbol = rpos
instance SATSymbol RPOsymbol where mkSATSymbol = rpo
instance SATSymbol LPOSsymbol where mkSATSymbol = lpos
instance SATSymbol LPOsymbol where mkSATSymbol = lpo
instance SATSymbol MPOsymbol where mkSATSymbol = mpo
-- | RPO + AF
rpoAF allowCol trs = runRPOAF allowCol (getSignature trs) $ \dict -> do
let symb_rules = mapTermSymbols (\f -> fromJust $ Map.lookup f dict) <$$> rules trs
let problem = and [ l > r | l:->r <- symb_rules]
assert [problem]
return (return ())
-- | Returns the indexes of non decreasing pairs and the symbols used
rpoAF_DP allowCol omega p
| _ <- isNarradarTRS1 (getR p)
= runRPOAF allowCol (getSignature p) $ \dict -> do
let convert = mapTermSymbols (\f -> fromJust $ Map.lookup f dict)
trs' = mapNarradarTRS convert (getR p)
dps' = mapNarradarTRS convert (getP p)
p' = mkDPProblem (getFramework p) trs' dps'
decreasing_dps <- replicateM (length $ rules dps') boolean
assertAll [omega p']
assertAll [ l >~ r | l:->r <- rules dps']
assertAll [(l > r) <--> input dec | (l:->r, dec) <- rules dps' `zip` decreasing_dps]
assert (map input decreasing_dps)
-- Ensure that we find the solution which removes the most pairs possible
sequence_ [ assertW 1 [input b] | b <- decreasing_dps]
-- Ensure that only really usable rules are selected
mapM_ (assertW 1 . (:[]) . not . input . usable) (Map.elems dict)
return $ do
decreasing <- decode decreasing_dps
let the_non_decreasing_pairs = [ r | (r,False) <- zip [(0::Int)..] decreasing]
return the_non_decreasing_pairs
rpoAF_IGDP :: (Ord id
,Traversable (Problem base), Pretty base
,MkDPProblem (InitialGoal (TermF sid) base) (NTRS sid)
,NUsableRules base sid
,NCap base sid
-- ,NeededRules (TermF sid) Narradar.Var base (NTRS sid)
,HasMinimality base
,DPSymbol id, Pretty id
,SATSymbol satSymbol
,sid ~ satSymbol Var id
,Ord sid, Pretty sid, Show id
,UsableSymbol Var sid
,DPSymbol sid
,HasPrecedence Var sid
,HasStatus Var sid
,HasFiltering Var sid
,Hashable sid
,Decode sid (SymbolRes id) Var
,MonadSAT repr Var m
,RPOExtCircuit repr sid Narradar.Var
,HasSignature (NProblem (InitialGoal (TermF id) base) id)
) => Bool -> (NProblem (InitialGoal (TermF sid) base) sid -> (repr Var, EvalM Var extraConstraints))
-> NProblem (InitialGoal (TermF id) base) id
-> m (EvalM Var (([Int], extraConstraints), BIEnv Var, [sid]))
rpoAF_IGDP allowCol omega p@InitialGoalProblem{..}
= runRPOAF allowCol (getSignature p `mappend` getSignature (pairs dgraph)) $ \dict -> do
let convert = mapTermSymbols (\f -> fromJust $ Map.lookup f dict)
trs' = mapNarradarTRS convert (getR p)
dps' = mapNarradarTRS convert (getP p)
typ' = InitialGoal (map (bimap convert convert) goals)
(Just $ mapDGraph convert dgraph)
(getFramework baseProblem)
p' = mkDPProblem typ' trs' dps'
let (omegaConstraint, extraConstraintsAdded) = omega p'
assertAll ( omegaConstraint : [ l >~ r | l:->r <- rules dps'])
decreasing_dps <- replicateM (length $ rules dps') boolean
assertAll [l > r <--> input dec | (l:->r, dec) <- rules dps' `zip` decreasing_dps]
assert (map input decreasing_dps)
-- Ensure that we find the solution which removes the most pairs possible
sequence_ [ assertW 1 [input b] | b <- decreasing_dps]
-- Ensure that only really usable rules are selected
mapM_ (assertW 1 . (:[]) . not . input . usable) (Map.elems dict)
-- debug ("\nThe indexes are: " ++ show decreasing_dps) $
return $ do
decreasing <- decode decreasing_dps
ec <- extraConstraintsAdded
return ([ r | (r,False) <- zip [(0::Int)..] decreasing]
,ec)
{-
(weakly, strictly) <- do
weakly <- evalB (and $ omegaIG p' :
[l >~ r | (False, l:->r) <- zip decreasing (rules dps')])
strictly <- evalB (and [l > r | (True, l:->r) <- zip decreasing (rules dps')])
return (weakly, strictly)
(weaklyS, strictlyS) <- do
weaklyS <- evalB (and $ omegaIG p' : [l >~ r | (False, l:->r) <- zip decreasing (rules dps')])
strictlyS <- mapM evalB ([l > r | (True, l:->r) <- zip decreasing (rules dps')])
return (weaklyS, strictlyS)
verification <- verifyRPOAF typ' trs' dps' decreasing_dps
let isValidProof
| isCorrect verification = True
| otherwise = pprTrace verification False
CE.assert isValidProof $
-}
-- CE.assert (null strictlyS) $
-- CE.assert (null weaklyS) $
-- CE.assert strictly $
-- CE.assert weakly $
where isTheRightKind :: InitialGoal (f id) base -> InitialGoal (f id) base
isTheRightKind = id
rpoAF_NDP allowCol omega p
| _ <- isNarradarTRS1 (getR p)
= runRPOAF allowCol (getSignature p) $ \dict -> do
let convert = mapTermSymbols (\f -> fromJust $ Map.lookup f dict)
trs' = mapNarradarTRS convert (getR p)
dps' = mapNarradarTRS convert (getP p)
p' = mkDPProblem (getFramework p) trs' dps'
decreasing_dps <- replicateM (length $ rules dps') boolean
assertAll [l > r <--> input dec | (l:->r, dec) <- rules dps' `zip` decreasing_dps]
let af_ground_rhs_dps = map afGroundRHS (rules dps')
variable_cond = and $ map variableCondition (rules dps')
assert (map input decreasing_dps)
assert af_ground_rhs_dps
assertAll (omega p' :
[ l >~ r | l:->r <- rules dps'])
-- Ensure that we find the solution which removes the most pairs possible
sequence_ [ assertW 1 [input b] | b <- decreasing_dps]
-- Ensure that only really usable rules are selected
mapM_ (assertW 1 . (:[]) . not . input . usable) (Map.elems dict)
return $ do
decreasing <- decode decreasing_dps
af_ground <- decode (af_ground_rhs_dps :: [Eval Var])
return ([ r | (r,False) <- zip [(0::Int)..] decreasing]
,[ r | (r,False) <- zip [(0::Int)..] af_ground])
runRPOAF allowCol sig f = do
let ids = getArities sig
bits = calcBitWidth $ Map.size ids
symbols <- mapM mkSATSymbol
[ (f, ar, def)
| (f,ar) <- Map.toList ids
, let def = Set.member f (getDefinedSymbols sig)]
if allowCol
then assertAll [not(listAF s) --> one [inAF i s | i <- [1..a]]
| (s,a) <- zip symbols (Map.elems ids)]
else assertAll (map listAF symbols)
let dict = Map.fromList (zip (Map.keys ids) symbols)
mkRes <- f dict
return $ do -- Debug.trace ("The symbols are:\n" ++ show symbols) $ do
env <- ask
res <- mkRes
return (res, env, symbols)
-- ----------------------
-- Symbols set extensions
-- ----------------------
instance ( RPOCircuit repr (RPOSsymbol v a) tvar, AssertCircuit repr, ExistCircuit repr, OneCircuit repr, ECircuit repr
,Ord tvar, Pretty tvar, Show tvar, Hashable tvar, Ord a, Pretty a) =>
RPOExtCircuit repr (RPOSsymbol v a) tvar where
exEq s t ss tt =
and [useMul s, useMul t, muleq s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexpeq s t ss tt]
exGt s t ss tt =
and [useMul s, useMul t, mulgt s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexpgt_existA s t ss tt]
exGe s t ss tt =
and [useMul s, useMul t, mulgt s t ss tt \/ muleq s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexpgt_existA s t ss tt \/ lexpeq s t ss tt]
{-
exGe s t ss tt =
and [useMul s, useMul t, mulge s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexpge_exist s t ss tt]
-}
instance (RPOCircuit repr (LPOSsymbol v a) tvar, AssertCircuit repr, OneCircuit repr, ECircuit repr, ExistCircuit repr, Ord a, Pretty a
,Ord tvar, Pretty tvar, Show tvar, Hashable tvar) =>
RPOExtCircuit repr (LPOSsymbol v a) tvar where
exEq s t = lexpeq s t
exGt s t = lexpgt_existA s t
-- exGe = lexpge_exist
instance (RPOCircuit repr (LPOsymbol v a) tvar, AssertCircuit repr, OneCircuit repr, ECircuit repr, ExistCircuit repr
,Ord a, Ord tvar, Pretty tvar, Show tvar, Hashable tvar) =>
RPOExtCircuit repr (LPOsymbol v a) tvar where
exEq s t = lexeq_existA s t
exGt s t = lexgt_existA s t
instance (RPOCircuit repr (MPOsymbol v a) tvar, AssertCircuit repr, ExistCircuit repr, OneCircuit repr, ECircuit repr, Ord a
,Ord tvar, Pretty tvar, Show tvar, Hashable tvar) =>
RPOExtCircuit repr (MPOsymbol v a) tvar where
exEq s t = muleq s t
exGt s t = mulgt s t
instance (RPOCircuit repr (RPOsymbol v a) tvar, AssertCircuit repr, ExistCircuit repr, OneCircuit repr, ECircuit repr, Ord a
,Ord tvar, Pretty tvar, Show tvar, Hashable tvar) =>
RPOExtCircuit repr (RPOsymbol v a) tvar where
exEq s t ss tt =
and [ useMul s, useMul t, muleq s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexeq_existA s t ss tt]
exGt s t ss tt =
and [useMul s, useMul t, mulgt s t ss tt]
\/
and [not$ useMul s, not$ useMul t, lexgt_existA s t ss tt]
-- -------------------------
-- Narrowing related stuff
-- -------------------------
afGroundRHS (_ :-> t) = and [ or [ not(inAF i f)
| prefix <- tail $ inits pos
, let Just f = rootSymbol (t ! init prefix)
, let i = last prefix]
| pos <- [noteV v | v <- vars(annotateWithPos t)]]
variableCondition rule@(_ :-> r)
= and [ or [ not(inAF i f)
| prefix <- tail $ inits pos
, let Just f = rootSymbol (r ! init prefix)
, let i = last prefix]
| pos <- [noteV v | v <- extraVars(annotateWithPos <$> rule)]]
-- -----------------------------------
-- Lexicographic extension with AF
-- -----------------------------------
lexgt id_f id_g ff gg = go (zip (map input $ filtering_vv id_f) ff)
(zip (map input $ filtering_vv id_g) gg)
where
go [] _ = false
go ff [] = or [ af_f | (af_f,_) <- ff]
go ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
((f > g) \/ ((f ~~ g) /\ go ff gg))
(go ((af_f,f):ff) gg))
(go ff ((af_g,g):gg))
lexeq id_f id_g ff gg = go (zip (map input $ filtering_vv id_f) ff)
(zip (map input $ filtering_vv id_g) gg)
where
go [] [] = true
go ff [] = not $ or [ af_f | (af_f,_) <- ff]
go [] gg = not $ or [ af_g | (af_g,_) <- gg]
go ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
((f ~~ g) /\ go ff gg)
(go ((af_f,f):ff) gg))
(go ff ((af_g,g):gg))
lexgt_exist _ _ [] _ = false
lexgt_exist id_f _ ff [] = or . map input . filtering_vv $ id_f
lexgt_exist id_f id_g ff gg = (`runCont` id) $ do
-- We build a matrix M of dim n_f x n_g containing all
-- the comparisons between tails of ff and gg
-- That is, M[0,0] = lexgt ff gg
-- M[1,0] = lexgt (drop 1 ff) gg
-- M[0,1] = lexgt ff (drop 1 gg)
-- ...
-- Actually, the matrix containts additional elements
-- M[n_f+1, i] = value if we drop all the elements of ff and i elements of gg
-- M[i, n_g+1] = value if we drop all the elements of gg and i elements of ff
-- The proposition is true iff M[0,0] is true
m <- replicateM (length ff + 1) $ replicateM (length gg + 1) (cont exists)
let assertions = [ m_ij!!0!!0 <--> constraint m_ij ff_i gg_j
| (m_i, ff_i) <- (tails m `zip` tails (zip filters_f ff))
, (m_ij, gg_j) <- (getZipList (traverse (ZipList . tails) m_i)
`zip` tails (zip filters_g gg))]
return ( m!!0!!0 /\ and assertions)
where
filters_f = map input (filtering_vv id_f)
filters_g = map input (filtering_vv id_g)
constraint _ [] _ = false
constraint _ ff [] = or [ af_f | (af_f,_) <- ff]
constraint m ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
(f>g \/ (f~~g /\ m!!1!!1))
(m!!0!!1))
(m!!1!!0)
lexgt_existA _ _ [] _ = false
lexgt_existA id_f _ ff [] = or . map input . filtering_vv $ id_f
lexgt_existA id_f id_g ff gg = (`runCont` id) $ do
-- We build a matrix M of dim n_f x n_g containing all
-- the comparisons between tails of ff and gg
-- That is, M[0,0] = lexgt ff gg
-- M[1,0] = lexgt (drop 1 ff) gg
-- M[0,1] = lexgt ff (drop 1 gg)
-- ...
-- Actually, the matrix containts additional elements
-- M[n_f+1, i] = value if we drop all the elements of ff and i elements of gg
-- M[i, n_g+1] = value if we drop all the elements of gg and i elements of ff
-- The proposition is true iff M[0,0] is true
m <- replicateM (length ff + 1) $ replicateM (length gg + 1) (cont exists)
let assertions = [ m_ij!!0!!0 <--> constraint m_ij ff_i gg_j
| (m_i, ff_i) <- (tails m `zip` tails (zip filters_f ff))
, (m_ij, gg_j) <- (getZipList (traverse (ZipList . tails) m_i)
`zip` tails (zip filters_g gg))]
return $ assertCircuits assertions (m!!0!!0)
where
filters_f = map input (filtering_vv id_f)
filters_g = map input (filtering_vv id_g)
constraint _ [] _ = false
constraint _ ff [] = or [ af_f | (af_f,_) <- ff]
constraint m ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
(f>g \/ (f~~g /\ m!!1!!1))
(m!!0!!1))
(m!!1!!0)
lexeq_exist _ _ [] [] = true
lexeq_exist id_f _ _ [] = not . or . map input . filtering_vv $ id_f
lexeq_exist _ id_g [] _ = not . or . map input . filtering_vv $ id_g
lexeq_exist id_f id_g ff gg = (`runCont` id) $ do
m <- replicateM (length ff + 1) $ replicateM (length gg + 1) (cont exists)
let assertions = [ m_ij!!0!!0 <--> constraint m_ij ff_i gg_j
| (m_i, ff_i) <- tails m `zip` tails (zip filters_f ff)
, (m_ij, gg_j) <- getZipList (traverse (ZipList . tails) m_i)
`zip` tails (zip filters_g gg)]
return ( m!!0!!0 /\ and assertions)
where
filters_f = map input (filtering_vv id_f)
filters_g = map input (filtering_vv id_g)
constraint _ [] [] = true
constraint _ ff [] = not $ or [ af_f | (af_f,_) <- ff]
constraint _ [] gg = not $ or [ af_g | (af_g,_) <- gg]
constraint m ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
(f~~g /\ m!!1!!1)
(m!!0!!1))
(m!!1!!0)
lexeq_existA _ _ [] [] = true
lexeq_existA id_f _ _ [] = not . or . map input . filtering_vv $ id_f
lexeq_existA _ id_g [] _ = not . or . map input . filtering_vv $ id_g
lexeq_existA id_f id_g ff gg = (`runCont` id) $ do
m <- replicateM (length ff + 1) $ replicateM (length gg + 1) (cont exists)
let assertions = [ m_ij!!0!!0 <--> constraint m_ij ff_i gg_j
| (m_i, ff_i) <- tails m `zip` tails (zip filters_f ff)
, (m_ij, gg_j) <- getZipList (traverse (ZipList . tails) m_i)
`zip` tails (zip filters_g gg)]
return ( assertCircuits assertions (m!!0!!0) )
where
filters_f = map input (filtering_vv id_f)
filters_g = map input (filtering_vv id_g)
constraint _ [] [] = true
constraint _ ff [] = not $ or [ af_f | (af_f,_) <- ff]
constraint _ [] gg = not $ or [ af_g | (af_g,_) <- gg]
constraint m ((af_f,f):ff) ((af_g,g):gg)
= ite af_f
(ite af_g
(f~~g /\ m!!1!!1)
(m!!0!!1))
(m!!1!!0)
--lexpeq :: (ECircuit repr, RPOCircuit repr (Symbol a)) =>
-- Symbol a -> Symbol a -> [TermN (Symbol a)] -> [TermN (Symbol a)] -> repr Var
--lexpeq id_f id_g ss tt | pprTrace (text "encoding " <+> ss <+> text "~" <+> tt) False = undefined
lexpeq id_f id_g ss tt =
eqArity /\
and ( [ (f_ik /\ g_jk) --> s_i ~~ t_j
| (s_i, f_i) <- zip ss ff
, (t_j, g_j) <- zip tt gg
, (f_ik, g_jk) <- zip f_i g_j])
where
(Just ff, Just gg) = (lexPerm id_f, lexPerm id_g)
eqArity = and ( take m (zipWith (<-->) (map or ff ++ repeat false)
(map or gg ++ repeat false))
)
m = max (length ff) (length gg)
--lexpgt id_f id_g ss tt | pprTrace (text "encoding " <+> ss <+> text ">" <+> tt) False = undefined
lexpgt id_f id_g ss tt = expgt_k (transpose $ enc_f) (transpose $ enc_g)
where
Just enc_f = lexPerm id_f
Just enc_g = lexPerm id_g
n = length ss
m = length tt
expgt_k [] _ = false
expgt_k (f_k:_) [] = or f_k
expgt_k (f_k:ff) (g_k:gg)
= or [f_ik /\ and [ g_jk --> (s_i > t_j \/
(s_i ~~ t_j /\ expgt_k ff gg))
| (g_jk, t_j) <- zip g_k tt]
| (f_ik, s_i) <- zip f_k ss]
lexpgt_exist id_f id_g [] _ = false
lexpgt_exist id_f id_g ss tt = (`runCont` id) $ do
let k = min (length ss) (length tt) + 1
vf_k <- replicateM k (cont exists)
let constraints = zipWith3 expgt_k (transpose $ enc_f) (transpose $ enc_g) (tail vf_k) ++
[the_tail]
the_tail = if length ss P.> length tt
then or (transpose enc_f !! length tt)
else false
let assertions = zipWith (<-->) vf_k constraints
return (head vf_k /\ and assertions)
where
Just enc_f = lexPerm id_f
Just enc_g = lexPerm id_g
expgt_k f_k g_k next
= or [f_ik /\ and [ g_jk --> (s_i > t_j \/
(s_i ~~ t_j /\ next))
| (g_jk, t_j) <- zip g_k tt]
| (f_ik, s_i) <- zip f_k ss]
lexpgt_existA id_f id_g [] _ = false
lexpgt_existA id_f id_g ss tt = (`runCont` id) $ do
let k = min (length ss) (length tt) + 1
vf_k <- replicateM k (cont exists)
let constraints = zipWith3 expgt_k (transpose $ enc_f) (transpose $ enc_g) (tail vf_k) ++
[the_tail]
the_tail = if length ss P.> length tt
then or (transpose enc_f !! length tt)
else false
let assertions = zipWith (<-->) vf_k constraints
return (assertCircuits assertions $ head vf_k)
where
Just enc_f = lexPerm id_f
Just enc_g = lexPerm id_g
expgt_k f_k g_k next
= or [f_ik /\ and [ g_jk --> (s_i > t_j \/
(s_i ~~ t_j /\ next))
| (g_jk, t_j) <- zip g_k tt]
| (f_ik, s_i) <- zip f_k ss]
lexpge_existA id_f id_g ss tt = (`runCont` id) $ do
let k = min (length ss) (length tt) + 1
vf_k <- replicateM k (cont exists)
let constraints = zipWith3 expge_k (transpose $ enc_f) (transpose $ enc_g) (tail vf_k) ++
[the_tail]
the_tail = if length ss P.> length tt
then eqArity \/ or (enc_f !! length tt)
else eqArity
let assertions = zipWith (<-->) vf_k constraints
return (assertCircuits assertions $ head vf_k)
where
Just enc_f = lexPerm id_f
Just enc_g = lexPerm id_g
expge_k f_k g_k next
= or [f_ik /\ and [ g_jk --> (s_i > t_j \/
(s_i ~~ t_j /\ next))
| (g_jk, t_j) <- zip g_k tt]
| (f_ik, s_i) <- zip f_k ss]
m = max (length enc_f) (length enc_g)
eqArity = and ( take m (zipWith (<-->) (map or enc_f ++ repeat false)
(map or enc_g ++ repeat false))
)
-- ---------------------------
-- Multiset extension with AF
-- ---------------------------
mulge id_f id_g [] gg = none $ map (`inAF` id_g) [1..length gg]
mulge id_f id_g ff gg = mulgen id_f id_g ff gg (const true)
mulgt id_f id_g [] _ = false
mulgt id_f id_g ff gg =
mulgen id_f id_g ff gg (\epsilons ->
not $ and [inAF i id_f --> ep_i
| (i, ep_i) <- zip [1..] epsilons])
muleq id_f id_g [] [] = true
muleq id_f id_g [] gg = none $ map (`inAF` id_g) [1..length gg]
muleq id_f id_g ff gg =
mulgen id_f id_g ff gg (\epsilons ->
and [inAF i id_f --> ep_i
| (i, ep_i) <- zip [1..] epsilons])
mulgen id_f id_g ff gg k = (`runCont` id) $ do
let (i,j) = (length ff, length gg)
epsilons <- replicateM i (cont exists)
gammasM_t <- replicateM i $ replicateM j (cont exists)
let gammasM = transpose gammasM_t
oneCoverForNonFilteredSubtermAndNoCoverForFilteredSubterms =
[ ite (inAF j id_g)
(one gammas_j)
(none gammas_j)
| (j, gammas_j) <- zip [1..] gammasM ]
filteredSubtermsCannotCover =
[ not(inAF i id_f) --> none gammas_i
| (i, gammas_i) <- zip [1..] gammasM_t]
subtermUsedForEqualityMustCoverOnce =
[ ep_i --> one gamma_i
| (ep_i, gamma_i) <- zip epsilons gammasM_t]
greaterOrEqualMultisetExtension =
[ gamma_ij --> ite ep_i (f_i ~~ g_j)
(f_i > g_j)
| (ep_i, gamma_i, f_i) <- zip3 epsilons gammasM_t ff
, (gamma_ij, g_j) <- zip gamma_i gg]
return $
and ( k epsilons
: oneCoverForNonFilteredSubtermAndNoCoverForFilteredSubterms
++ filteredSubtermsCannotCover
++ subtermUsedForEqualityMustCoverOnce
++ greaterOrEqualMultisetExtension
)
-- ------------------------
-- Usable Rules with AF
-- ------------------------
omegaNone p = and ([ l >~ r | l:->r <- rules (getR p)] ++
[ iusable f | f <- Set.toList $ getDefinedSymbols (getR p)])
omegaUsable p = -- pprTrace ("Solving P=" <> getP p $$ "where dd = " <> dd) $
and ([go r trs | _:->r <- dps] ++
[iusable f --> and [ l >~ r | l:->r <- rulesFor f trs]
| f <- Set.toList dd ] ++
[not(iusable f) | f <- Set.toList (getDefinedSymbols sig `Set.difference` dd)]
)
where
(trs,dps) = (rules $ getR p, rules $ getP p)
sig = getSignature (getR p)
dd = getDefinedSymbols $ getR (iUsableRules p (rhs <$> dps))
go (Pure x) _ = and $ map iusable $ toList $ getDefinedSymbols (iUsableRulesVar p x)
go t trs
| id_t `Set.notMember` dd
= and [ inAF i id_t --> go t_i trs
| (i, t_i) <- zip [1..] tt ]
| otherwise
= iusable id_t /\
and ([ go r rest | _:->r <- rls ] ++
[ inAF i id_t --> go t_i rest
| (i, t_i) <- zip [1..] tt ]
)
where
Just id_t = rootSymbol t
tt = directSubterms t
rls = rulesFor id_t trs
rest = trs \\ rls -- :: [Rule t Var]
omegaNeeded p = -- pprTrace ("Solving P=" <> getP p $$ "where dd = " <> dd) $
and ([go r trs | _:->r <- dps] ++
[iusable f --> and [ l >~ r | l:->r <- rulesFor f trs]
| f <- Set.toList dd ] ++
[not(iusable f) | f <- Set.toList (getDefinedSymbols sig `Set.difference` dd)]
)
where
(trs,dps) = (rules $ getR p, rules $ getP p)
sig = getSignature (getR p)
dd
| getMinimalityFromProblem p == M = getDefinedSymbols $ getR (neededRules p (rhs <$> dps))
| otherwise = getDefinedSymbols $ getR (iUsableRules p (rhs <$> dps))
go (Pure x) _
| getMinimalityFromProblem p == M = true
| otherwise = and $ map iusable $ toList $ getDefinedSymbols (iUsableRulesVar p x)
go t trs
| id_t `Set.notMember` dd
= and [ inAF i id_t --> go t_i trs
| (i, t_i) <- zip [1..] tt ]
| otherwise
= iusable id_t /\
and ([ go r rest | _:->r <- rls ]++
[ inAF i id_t --> go t_i rest
| (i, t_i) <- zip [1..] tt ]
)
where
Just id_t = rootSymbol t
tt = directSubterms t
rls = rulesFor id_t trs
rest = trs \\ rls -- :: [Rule t Var]
omegaIG p = --pprTrace ("Solving P=" <> getP p $$ "where the involved pairs are: " <> ip $$ text "and dd=" <+> dd ) $
(and ([go l r trs | l:->r <- ip] ++
[iusable f --> and [ l >~ r | l:->r <- rulesFor f trs]
| f <- Set.toList dd ] ++
[not(iusable f) | f <- Set.toList (getDefinedSymbols sig `Set.difference` dd)]
)
,return [])
where
ip = forDPProblem involvedPairs p
(trs,dps) = (rules $ getR p, rules $ getP p)
sig = getSignature (getR p)
dd
| M <- getMinimalityFromProblem p = getDefinedSymbols $ getR (neededRules p (rhs <$> dps))
| otherwise = getDefinedSymbols (reachableUsableRules p)
go l (Pure x) _ =
-- If there is an extra variable, everything is usable
every poss (\p -> or [ not(inAF i f)
| n <- [0..length p - 1]
, let (pre, i:_) = splitAt n p
, let f = fromMaybe (error "omega: fromJust") $
rootSymbol (l!pre)])
--> and(map iusable $ toList $ getDefinedSymbols (getR p))
where
poss = occurrences (Pure x) l
go l t trs
| id_t `Set.notMember` dd
= and [ inAF i id_t --> go l t_i trs
| (i, t_i) <- zip [1..] tt ]
| otherwise
= and ( iusable id_t
: [ go l' r' rest | l':->r' <- rls ]
++ [ inAF i id_t --> go l t_i rest
| (i, t_i) <- zip [1..] tt ]
)
where
Just id_t = rootSymbol t
tt = directSubterms t
rls = rulesFor id_t trs
rest = trs \\ rls
omegaIGgen p
| isLeftLinear (getR p) = pprTrace ("omegaIGgen: partial = " <+> partial)
omegaIG p
| (omegaConstraint,extra1) <- omegaIG p
= (omegaConstraint /\ (iusable gen --> and extraConstraints)
,do { e1 <- extra1;
b <- decode (iusable gen :: Eval Var);
return $
if b then (e1 ++ map isTree extraConstraints)
else []
})
where
isTree = id :: Tree id v Var -> Tree id v Var
Just gen = find isGenSymbol (toList $ getDefinedSymbols p)
genTerm = term gen []
extraConstraints = [ genTerm > term f (replicate i genTerm) | (f,i) <- Map.toList partial]
partial = definedSymbols (getSignature p)
`Map.difference`
Map.fromList
[(f, arity ) | l :-> r <- rules (getR p)
, Just f <- [rootSymbol l]
, isLinear l && P.all isVar (properSubterms l)
, let arity = length (properSubterms l)]
rulesFor :: (HasId t, TermId t ~ id, Eq id) => id -> [Rule t v] -> [Rule t v]
rulesFor f trs = [ l:->r | l:-> r <- trs, rootSymbol l == Just f ]
-- --------------------------------------
-- Support for Goal-problems identifiers
-- --------------------------------------
instance (Show a, GenSymbol a) => GenSymbol (RPOSsymbol Var a) where
genSymbol = Symbol{ theSymbol = genSymbol
, encodePrec = V 10
, encodeUsable = V 11
, encodeAFlist = V 12
, encodeAFpos = []
, encodePerm = []
, encodeUseMset= V 13
, decodeSymbol = mkSymbolDecoder genSymbol (Natural $ V 10) (V 11) (V 12) [] [] (V 13)
}
goalSymbol = Symbol{ theSymbol = genSymbol
, encodePrec = error "RPOAF.Symbol : goalSymbol"
, encodeUsable = error "RPOAF.Symbol : goalSymbol"
, encodeAFlist = error "RPOAF.Symbol : goalSymbol"
, encodeAFpos = error "RPOAF.Symbol : goalSymbol"
, encodePerm = []
, encodeUseMset= error "RPOAF.Symbol : goalSymbol"
, decodeSymbol = return (SymbolRes goalSymbol 0 False (Lex Nothing) (Right []))
}
isGenSymbol = isGenSymbol . theSymbol
isGoalSymbol = isGoalSymbol . theSymbol
deriving instance (Show a, GenSymbol a) => GenSymbol (LPOsymbol Var a)
deriving instance (Show a, GenSymbol a) => GenSymbol (LPOSsymbol Var a)
deriving instance (Show a, GenSymbol a) => GenSymbol (MPOsymbol Var a)
deriving instance (Show a, GenSymbol a) => GenSymbol (RPOsymbol Var a)
-- --------
-- Testing
-- --------
verifyRPOAF typ the_rules the_pairs nonDecPairsIx = do
theAf <- AF.fromList' `liftM` mapM getFiltering (toList $ getAllSymbols signature)
let theFilteredPairs = rules $ AF.apply theAf the_pairs
let theWeakPairs = CE.assert (P.all (P.< npairs) nonDecPairsIx) $
selectSafe "verifyRPOAF 1" nonDecPairsIx (rules the_pairs)
theDecPairs = selectSafe "verifyRPOAF 2" ([0..npairs - 1] \\ nonDecPairsIx) (rules the_pairs)
theUsableRules <- liftM Set.fromList $ runListT $ do
l:->r <- msum $ map return $ rules the_rules
let Just id = rootSymbol l
guard =<< lift (evalDecode $ input $ usable id)
return (l:->r)
let expectedUsableRules =
Set.fromList
[ rule
| let urAf = Set.fromList $
rules(iUsableRules3 typ the_rules the_pairs (rhs <$> theFilteredPairs))
, rule <- rules the_rules
, AF.apply theAf rule `Set.member` urAf]
falseDecreasingPairs <- runListT $ do
s:->t <- li theDecPairs
guard =<< lift (evalDecode $ not(s > t))
return (s:->t)
falseWeaklyDecreasingPairs <- runListT $ do
s:->t <- li theWeakPairs
guard =<< lift (evalDecode $ not( s >~ t))
return (s:->t)
falseWeaklyDecreasingRules <- runListT $ do
s:->t <- li (toList theUsableRules)
guard =<< lift (evalDecode $ not( s >~ t))
return (s:->t)
let missingUsableRules = [] -- toList (Set.difference expected_usableRules the_usableRules)
excessUsableRules = [] -- toList (Set.difference the_usableRules expected_usableRules)
return VerifyRPOAF{thePairs = rules the_pairs, ..}
where
signature = getSignature (the_rules `mappend` the_pairs)
getFiltering s = do
isListAF <- evalDecode $ listAF s
filterings <- mapM decode (filtering_vv s)
let positions = [ i | (i,True) <- zip [1..(getArity signature s)] filterings]
return $ if isListAF
then (s, Right positions)
else case positions of
[p] -> (s, Left p)
_ -> error ("Invalid collapsing filtering " ++ show positions ++
" for symbol " ++ show (pPrint s))
npairs = length (rules the_pairs)
| pepeiborra/narradar | src/Narradar/Constraints/SAT/RPOAF.hs | bsd-3-clause | 34,363 | 0 | 21 | 11,284 | 11,848 | 6,063 | 5,785 | 619 | 4 |
-- Standard semantics of While in direct style.
-- We do not make any reuse.
module While.DenotationalSemantics.Main0 where
import qualified Prelude
import Prelude hiding (Num, True, False)
import While.AbstractSyntax
-- Denotation types
type MA = State -> Num
type MB = State -> Bool
type MS = State -> State
-- States
type State = Var -> Num
-- Standard semantic functions
aexp :: Aexp -> MA
bexp :: Bexp -> MB
stm :: Stm -> MS
-- aexp :: Aexp -> MA
aexp (Num n) s = n
aexp (Var x) s = s x
aexp (Add a1 a2) s = aexp a1 s + aexp a2 s
aexp (Mul a1 a2) s = aexp a1 s * aexp a2 s
aexp (Sub a1 a2) s = aexp a1 s - aexp a2 s
-- bexp :: Bexp -> MB
bexp True s = Prelude.True
bexp False s = Prelude.False
bexp (Eq a1 a2) s = aexp a1 s == aexp a2 s
bexp (Leq a1 a2) s = aexp a1 s <= aexp a2 s
bexp (Not b1) s = not (bexp b1 s)
bexp (And b1 b2) s = bexp b1 s && bexp b2 s
-- stm :: Stm -> MS
stm (Assign x a) = \s x' -> if x==x' then aexp a s else s x'
stm Skip = id
stm (Seq s1 s2) = stm s2 . stm s1
stm (If b s1 s2) = cond (bexp b) (stm s1) (stm s2)
stm (While b s) = fix (\f -> cond (bexp b) (f . stm s) id)
-- Helpers
cond :: MB -> MS -> MS -> MS
cond b s1 s2 s = if b s then s1 s else s2 s
fix :: (x -> x) -> x
fix f = f (fix f)
main =
do
let s x = if x=="x" then 5 else undefined
print $ stm factorial s "y"
{-
> main
120
-}
| grammarware/slps | topics/implementation/NielsonN07/Haskell/src/While/DenotationalSemantics/Main0.hs | bsd-3-clause | 1,389 | 0 | 11 | 394 | 680 | 348 | 332 | 35 | 2 |
module Stats where
import Data.List
type Series = [Double]
type Statistic = Double
mean :: Series -> Statistic
mean xs = sum xs / genericLength xs
median :: Series -> Statistic
median xs
| odd (length xs) = sorted !! middle_i
| otherwise = (sorted !! middle_i + sorted !! (middle_i + 1) ) / 2
where
middle_i = ceiling (genericLength xs / 2) - 1
sorted = sort xs
cov :: Series -> Series -> Statistic
cov xs ys
= (sum $ mult term_1 term_2) / (genericLength xs - 1)
where
term_1 = diffScalar xs (mean ys)
term_2 = diffScalar ys (mean xs)
cor :: Series -> Series -> Statistic
cor xs ys = cov xs ys / (std xs * std ys)
var :: Series -> Statistic
var xs = cov xs xs
std :: Series -> Statistic
std xs = sqrt $ var xs
square :: Series -> Series
square xs = map (**2) xs
diff :: Series -> Series -> Series
diff xs ys = zipWith (-) xs ys
mult :: Series -> Series -> Series
mult xs ys = zipWith (*) xs ys
diffScalar :: Series -> Double -> Series
diffScalar xs v = [x - v | x <- xs]
| tinyrock/gr4j | src/Stats.hs | bsd-3-clause | 1,017 | 0 | 11 | 252 | 456 | 235 | 221 | 31 | 1 |
{-# language MultiParamTypeClasses #-}
module OpenCV.Internal.Core.Types.Mat.Depth
( Depth(..)
, ToDepth(toDepth)
, ToDepthDS(toDepthDS)
, DepthT
) where
import "base" Data.Int
import "base" Data.Proxy
import "base" Data.Word
import "this" OpenCV.TypeLevel
--------------------------------------------------------------------------------
data Depth =
Depth_8U
| Depth_8S
| Depth_16U
| Depth_16S
| Depth_32S
| Depth_32F
| Depth_64F
| Depth_USRTYPE1
deriving (Show, Eq)
--------------------------------------------------------------------------------
class ToDepth a where
toDepth :: a -> Depth
instance ToDepth Depth where toDepth = id
instance ToDepth (proxy Word8 ) where toDepth _proxy = Depth_8U
instance ToDepth (proxy Int8 ) where toDepth _proxy = Depth_8S
instance ToDepth (proxy Word16) where toDepth _proxy = Depth_16U
instance ToDepth (proxy Int16 ) where toDepth _proxy = Depth_16S
instance ToDepth (proxy Int32 ) where toDepth _proxy = Depth_32S
instance ToDepth (proxy Float ) where toDepth _proxy = Depth_32F
instance ToDepth (proxy Double) where toDepth _proxy = Depth_64F
-- TODO (BvD): instance ToDepth ? where toDepth = const Depth_USRTYPE1
-- RvD: perhaps ByteString? Or a fixed size (statically) vector of bytes
--------------------------------------------------------------------------------
class ToDepthDS a where
toDepthDS :: a -> DS Depth
instance ToDepthDS Depth where toDepthDS _depth = D
instance ToDepthDS (proxy 'D) where toDepthDS _proxy = D
instance ToDepthDS (proxy ('S Word8 )) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Word8 )
instance ToDepthDS (proxy ('S Int8 )) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Int8 )
instance ToDepthDS (proxy ('S Word16)) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Word16)
instance ToDepthDS (proxy ('S Int16 )) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Int16 )
instance ToDepthDS (proxy ('S Int32 )) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Int32 )
instance ToDepthDS (proxy ('S Float )) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Float )
instance ToDepthDS (proxy ('S Double)) where toDepthDS _proxy = S $ toDepth (Proxy :: Proxy Double)
--------------------------------------------------------------------------------
type family DepthT a :: DS * where
DepthT Depth = 'D
DepthT (proxy d) = 'S d
| Cortlandd/haskell-opencv | src/OpenCV/Internal/Core/Types/Mat/Depth.hs | bsd-3-clause | 2,420 | 0 | 10 | 419 | 716 | 379 | 337 | -1 | -1 |
module Tinc.SetupSpec (spec) where
import Prelude ()
import Prelude.Compat
import Test.Hspec
import Test.Mockery.Directory
import System.Directory
import System.FilePath
import Tinc.Types
import Tinc.GhcInfo
import Tinc.Setup
spec :: Spec
spec = do
describe "setup" $ beforeAll setup $ do
it "includes GHC version in cache directory" $ \ facts -> do
path (factsCache facts) `shouldContain` ghcInfoVersion (factsGhcInfo facts)
describe "listPlugins" $ do
it "lists plugins" $ do
inTempDirectory $ do
touch "tinc-foo"
touch "tinc-bar"
pluginsDir <- getCurrentDirectory
plugins <- listPlugins pluginsDir
plugins `shouldMatchList` [
("foo", pluginsDir </> "tinc-foo")
, ("bar", pluginsDir </> "tinc-bar")
]
| beni55/tinc | test/Tinc/SetupSpec.hs | bsd-3-clause | 894 | 0 | 19 | 282 | 218 | 112 | 106 | 25 | 1 |
module Char8ProllyNotWhatYouWant where
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
-- utf8-string
import qualified Data.ByteString.UTF8 as UTF8
-- Manual unicode encoding of japanese text
-- GHC Haskell allows UTF8 in source files
s :: String
s = "\12371\12435\12395\12385\12399\12289\
\20803\27671\12391\12377\12363\65311"
utf8ThenPrint :: B.ByteString -> IO ()
utf8ThenPrint =
putStrLn . T.unpack . TE.decodeUtf8
throwsException :: IO ()
throwsException =
utf8ThenPrint (B8.pack s)
bytesByWayOfText :: B.ByteString
bytesByWayOfText = TE.encodeUtf8 (T.pack s)
-- letting utf8-string do it for us
libraryDoesTheWork :: B.ByteString
libraryDoesTheWork = UTF8.fromString s
thisWorks :: IO ()
thisWorks = utf8ThenPrint bytesByWayOfText
alsoWorks :: IO ()
alsoWorks = utf8ThenPrint libraryDoesTheWork
| dmvianna/strict | src/char8.hs | bsd-3-clause | 926 | 0 | 8 | 128 | 198 | 116 | 82 | 22 | 1 |
module MIX.Assembler.MIXWord
( MIXWord
, wordMask
, getByte
, storeInField
, storeManyInField
, toWord
, wordToInteger
, setNegative
, clearNegative
, clearByte
, addWord
, subWord
, multWord
, divWord
, isNegative
, bitsPerByte
, bytesPerWord
)
where
import Control.Applicative ((<$>))
import Data.Bits
import Data.List (intersperse)
import Numeric (showHex)
newtype MIXWord = MW Integer
deriving (Eq)
instance Show MIXWord where
show w = concat $ intersperse " " (sign:bytes)
where
sign = if isNegative w then "-" else "+"
bytes = [ showByte (getByte 1 w)
, showByte (getByte 2 w)
, showByte (getByte 3 w)
, showByte (getByte 4 w)
, showByte (getByte 5 w)
]
showByte :: Integer -> String
showByte b = pad ++ h
where
h = showHex b ""
pad = if length h == 1 then "0" else ""
wordMask :: Integer
wordMask = 2 ^ (bitsPerByte * bytesPerWord) - 1
toWord :: Integer -> MIXWord
toWord i =
MW $ if i < 0
then (abs i .&. wordMask) .|. signBit
else abs i .&. wordMask
wordToInteger :: MIXWord -> Integer
wordToInteger (MW v) =
let sgn = if v .&. signBit == signBit
then (-1)
else 1
in (v .&. (complement signBit)) * sgn
isNegative :: MIXWord -> Bool
isNegative (MW v) = v .&. signBit == signBit
setNegative :: MIXWord -> MIXWord
setNegative (MW v) = MW $ v .|. signBit
clearNegative :: MIXWord -> MIXWord
clearNegative (MW v) = MW $ v .&. (complement signBit)
signBit :: Integer
signBit = 0x1 `shiftL` (fromEnum $ bitsPerByte * bytesPerWord)
byteMask :: Integer
byteMask = (1 `shiftL` (fromEnum bitsPerByte)) - 1
getByte :: Integer -> MIXWord -> Integer
getByte num (MW i) =
-- Right-shift the byte of interest down to the first 6 bits and
-- then mask it
shiftR i (fromEnum $ (bytesPerWord - num) * bitsPerByte) .&. byteMask
bitsPerByte :: Integer
bitsPerByte = 6
bytesPerWord :: Integer
bytesPerWord = 5
storeManyInField :: [(MIXWord, (Integer, Integer))] -> MIXWord -> MIXWord
storeManyInField many base =
foldl (flip $ uncurry $ storeInField) base many
storeInField :: MIXWord -> (Integer, Integer) -> MIXWord -> MIXWord
storeInField (MW sv) (left, right) (MW d) =
let shiftAmt = (bytesPerWord - right) * bitsPerByte
totalBits = (right - left + 1) * bitsPerByte
keepBits = (1 `shiftL` (fromEnum totalBits)) - 1
sval = (sv .&. keepBits) `shiftL` (fromEnum shiftAmt)
left' = max 1 left
final = sval .|. (clearBytes [left'..right] d)
sgn = if left == 0
then sv .&. signBit
else d .&. signBit
finalWithSign = sgn .|. clearByte 0 final
in MW finalWithSign
clearBytes :: (Bits a) => [Integer] -> a -> a
clearBytes [] = id
clearBytes (i:is) = clearByte i . clearBytes is
-- byte 0: bits 30-31
-- byte 1: bits 24-29
-- byte 2: bits 18-23
-- byte 3: bits 12-17
-- byte 4: bits 6-11
-- byte 5: bits 0-5
clearByte :: (Bits a) => Integer -> a -> a
clearByte i val =
let base = (bytesPerWord - i) * bitsPerByte
in foldr (flip clearBit) val (fromEnum <$> [base..base+bitsPerByte-1])
addWord :: MIXWord -> MIXWord -> MIXWord
addWord a b = toWord $ wordToInteger a + wordToInteger b
subWord :: MIXWord -> MIXWord -> MIXWord
subWord a b = toWord $ wordToInteger a - wordToInteger b
divWord :: MIXWord -> MIXWord -> MIXWord
divWord a b = toWord $ div (wordToInteger a) (wordToInteger b)
multWord :: MIXWord -> MIXWord -> MIXWord
multWord a b = toWord $ (wordToInteger a) * (wordToInteger b) | jtdaugherty/mix-assembler | src/MIX/Assembler/MIXWord.hs | bsd-3-clause | 3,680 | 0 | 13 | 994 | 1,259 | 681 | 578 | 97 | 2 |
----------------------------------------------------------------------------
-- |
-- Module : Language.Core.Interpreter.Structures
-- Copyright : (c) Carlos López-Camey, University of Freiburg
-- License : BSD-3
--
-- Maintainer : [email protected]
-- Stability : stable
--
--
-- Defines fundamental structures and functions for Language.Core.Interpreter
-----------------------------------------------------------------------------
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ImplicitParams #-}
-- TODO: Move to Language.Core
module Language.Core.Interpreter.Structures(
io
, increase_number_of_reductions
-- heap operations
, store, newAddress, memorize, memorizeVal, memorizeThunk, mkVal, mkThunk, mkHeapReference, mkValuePointer
, allocate
-- timeouting
, isTimeout, clearTimeout
-- pretty printing
-- settings
, getSetting
, DARTSettings(..)
, DARTState(..)
, Heap, Env, TypeEnv, HeapAddress, HeapReference
, IM
, Thunk (..), DataCon(..) , Value(..), Pointer(..), PredicateBranch(..)
-- , ModuleFunction(..)
, HaskellExpression(..)
, BoltzmannSamplerStatus(..)
, module Control.Monad.State.Lazy
, module Language.Core.Core
, module Language.Core.Util
) where
--------------------------------------------------------------------------------
-- control
import Control.Monad.Primitive
import Control.Monad.State.Lazy
--------------------------------------------------------------------------------
-- base type funs
import Data.Either(partitionEithers,rights)
import Data.List(intersperse)
import Data.Char (isUpper)
import Data.List(findIndices)
--------------------------------------------------------------------------------
-- DART
import DART.DARTSettings
-- Language.Core
import Language.Core.Core
import Language.Core.Ty(showTySig)
import Language.Core.Util --(showType,showExtCoreType,showExp,wrapName)
import System.IO.Unsafe(unsafePerformIO)
--------------------------------------------------------------------------------
-- System
import Data.Time.Clock
import Unsafe.Coerce(unsafeCoerce)
--------------------------------------------------------------------------------
-- mutable hash tables;
-- package [hashtables](http://hackage.haskell.org/package/hashtables)
import qualified Data.HashTable.IO as H
-- | A State passed around the interpreter
data DARTState = DState {
-- benchmarking
benchmarks :: [(Id,NominalDiffTime)]
, libraries_env :: Env
, heap :: Heap -- our memory
, pbranches_record :: [PredicateBranch] -- also keep Env, but without libs; only stuff within the scope.
, heap_count :: Int, -- address counter, counts those previously deleted too
-- useful to generate new variable names
number_of_reductions :: !Int, -- when an expression is evaluated, this value increments by 1, useful to print debug headings
number_of_reductions_part :: !Int -- when in debugging mode, this value is increased everytime an step is done in the evaluation of the expression represented by the number `number_of_reductions`, prints debug subheadings
, tab_indentation :: !Int -- useful when to know how many tabs we shoud prepend
, settings :: DARTSettings
-- time when a computation started
-- useful for timeouts
, start_time :: UTCTime
-- state of testing
, test_name :: Maybe (Qual Var)
-- , generator :: GenM Value
, samplerStatus :: BoltzmannSamplerStatus
, samplerDataSize :: Int
, samplerValue :: Value
-- , runSampler :: Boltzmann Value
}
--newtype Boltzmann a {
-- runBoltzmann :: DARTState -> IM (a, DARTState)
--}
data BoltzmannSamplerStatus = InitializedSampler | UnitializedSampler deriving Show
type Heap = H.CuckooHashTable HeapAddress (Either Thunk Value)
type HeapAddress = Int
type Env = [(Id,HeapAddress)]
type TypeEnv = [(Id,Ty)]
type HeapReference = (Id,HeapAddress)
-- | We'll record execution paths; every path node comes from a branching after a pattern match analysis is performed. See method recordBranch in Language.Core.Interpterer.Evaluable
data PredicateBranch = PBranch {
pbranch_exp :: Exp,
pbranch_value :: Value
} | EnvironmentalPBranch {
pbranch_id :: Id,
pbranch_env :: Env,
pbranch_value :: Value
}
-- --
-- fun2 = let
-- a = error $ "ERROR"
-- b = 2
-- in a `seq` b
-- | Define a monad IM (for Interpreter Monad) where we keep a value of type DARTState containing state variables such as the heap and settings such as the number of reduction for debugging purposes.
type IM = StateT DARTState IO
data Value = Wrong String
| Num Integer
| Rat Rational -- arbitrary-precision rational numbers
| Boolean Bool
| Char Char
| String String
| Fun (Id -> Env -> IM Value) Description
| Pair Pointer Pointer --HERE, heap addresses
| TyConApp DataCon [Pointer] -- a data constructor applicated to some values, possible expecting some more types
| Pointer Pointer
| FreeTypeVariable String -- useful when converting a to SomeClass a (we ignore parameters, and it's useful to save them)
| MkListOfValues [(String,Value)] -- When a value definition is recursive, depends on other values
| SumType [DataCon] -- A data type with reference to its constructors, created only from type constructors when reading modules (see Interpreter/Acknowledge).
| TyCon DataCon Id -- data constructor annotated with the qualified name of the type it builds. For example (:) is a type constructor for the list type, "[]".
newtype Pointer = MkPointer { ptr_address :: HeapAddress } deriving Show
data Thunk = Thunk Exp Env -- a thunk created during the evaluation of a value definition
-- | VdefgThunk Exp -- has no environment, it will be passed by the module for efficiency
instance Show Thunk where
show (Thunk exp env) = let ?tab_indentation = 0
in "Thunk(exp=" ++ showExp exp ++ ")"
--show (VdefgThunk exp) = let ?tab_indentation = 0
-- in "VdefgThunk(exp=" ++ showExp exp ++ ")"
-- | Some expression from the command line that is evaluable within the scope of the
-- provided file(s)
data HaskellExpression = HaskellExpression String Module
-- | A polykinded type constructor
data DataCon = MkDataCon {
datacon_name :: Id, -- qualified name
signature :: [Ty], --types it expects
context :: TypeEnv --bounded types
} deriving Eq
type Description = String
-- | Equality of values
instance Eq Value where
(Wrong s) == Wrong s' = s == s'
(Num i) == (Num i') = i == i'
(Fun _ _) == (Fun _ _) = False -- equality of functions in dart is not intensional
(Boolean b) == (Boolean b') = b == b'
o == p = False
-- showAddress :: HeapAddress -> IM String
-- showAddress address = lookupMem address >>= \v -> case v of
-- Left thunk -> return "Thunk"
-- Right val -> case val of
-- -- look for functions that depend on an address, computations to happen within the IM monad
-- (TyConApp tc addresses) -> showTyConApp tc addresses
-- otherVal -> return $ show otherVal -- wrong, num, string, fun, etc..
io :: MonadIO m => IO a -> m a
io = liftIO
-- | Make a thunk of an expression so it can be later evaluated
mkThunk :: Exp -> Env -> Either Thunk Value
mkThunk exp env = Left $ Thunk exp env
-- | Lift a value to memory value
mkVal :: Value -> Either Thunk Value
mkVal = Right
-- | Stores a value or a thunk in the given address
store :: HeapAddress -> Either Thunk Value -> Id -> IM HeapReference
store address val id = do
-- put the value in the heap
h <- gets heap
io $ H.insert h address val
--watchReductionM $ "Memorized " ++ id ++ " in " ++ show address ++ " as " ++ show val
return (id,address)
-- | Stores a value or a thunk in a new address
memorize :: Either Thunk Value -> Id -> IM HeapReference
memorize val id = newAddress >>= \adr -> store adr val id
-- | Makes a Pointer from
mkValuePointer :: Value -> IM Pointer
mkValuePointer val = memorizeVal val >>= \heap_ref@(_,addr) -> return . MkPointer $ addr
memorizeVal :: Value -> IM HeapReference
memorizeVal val = mkVarName >>= memorize (mkVal val)
memorizeThunk :: Thunk -> IM HeapReference
memorizeThunk thunk = mkVarName >>= memorize (Left thunk)
--memorizeThunkAs :: Thunk -> Id -> IM HeapReference
--memorizeThunkAs thunk id = newAddress >>= \adr -> memorize adr (Left thunk) id
-- | Creates new variable for the expression, memorizes it and returns a heap reference
mkHeapReference :: Exp -> Env -> IM HeapReference
mkHeapReference exp env = mkVarName >>= memorize (mkThunk exp env)
-- | Gets a new address, that stores nothing
newAddress :: IM HeapAddress
newAddress = incVarCount >> gets heap_count
incVarCount :: IM ()
incVarCount = gets heap_count >>= \hc -> modify (\st -> st { heap_count = hc + 1 })
-- | Allocates `n` new addresses
allocate :: Int -> IM [HeapAddress]
allocate 0 = return []
allocate 1 = newAddress >>= return . mkList where mkList x = [x]
allocate n = do
a <- newAddress
as <- allocate $ n - 1
return $ a:as
-- | Prints a debug message with a new line at the end
debugM :: String -> IM ()
debugM msg = do
s <- gets settings
ti <- gets tab_indentation
when (debug s) $
let tab = replicate ti '\t'
in io . putStrLn $ (tab ++ msg)
-- | Creates a variable name. This function is not exported since every time it is used,
-- the variable count should be increased (done normally by memorize)
mkVarName :: IM String
mkVarName = gets heap_count >>= return . (++) "dartTmp" . show
increase_number_of_reductions :: DARTState -> DARTState
increase_number_of_reductions s = s { number_of_reductions = number_of_reductions s + 1 }
instance Show Value where
show (Wrong s) = "error: " ++ s
show (Num i) = show i
show (Rat r) = show r
show (Boolean b) = show b
show (Char c) = show c
show (String s) = show s
show (Pair a b) = show (a,b)
-- If the function description is prepended by a $, it's a monomophied function, we should everything until we find the last upper case letter
show (Fun f ('$':s)) =
let lastUpperIndex = last . findIndices isUpper
in drop (lastUpperIndex s) s
show (Fun f s) = s
show (TyConApp tc addresses) = "TyConApp(" ++ show tc ++ ", " ++ show addresses ++ ")"
show (Pointer address) = "Pointer to " ++ show address
show (FreeTypeVariable type_var) = type_var
show (MkListOfValues vals) = let
myIntersperse sep = foldr ((++) . (++) sep) []
in myIntersperse "\n\t" (map show vals)
show (SumType cons) = "SumType of " ++ myIntersperse "|" constructor_names
where
myIntersperse sep = foldr ((++) . (++) sep) []
constructor_names = map (\(MkDataCon id _ _) -> id) cons
show (TyCon tycon ty_name) | show tycon == "[]" = "[]"
show (TyCon (MkDataCon datacon_name' datacon_signature' []) ty_name) = (idName datacon_name') ++ " :: " ++ (showTySig datacon_signature') ++ " ::=> " ++ (idName ty_name)
show (TyCon (MkDataCon datacon_name' datacon_signature' ty_env) ty_name) = "... —" ++ (idName datacon_name') ++ " :: " ++ (showTySig datacon_signature') ++ " ::=> " ++ (idName ty_name) ++ ", –– applied types: " ++ (concatMap (\(i,t) -> show i ++ showType t) ty_env)
-- | otherwise = "TypeConstructor " ++ show tycon ++ " of " ++ ty_name
-- Pretty print data constructors
instance Show DataCon where
-- list?
show (MkDataCon "ghc-prim:GHC.Types.[]" [] _) = "[]"
show (MkDataCon "ghc-prim:GHC.Types.[]" ty _) = "[] :: " ++ show ty
show (MkDataCon id [] _) = idName id
show (MkDataCon id signature' applied_types') = idName id ++ ", signature = " ++ (show signature'') ++ ", applied types = " ++ show (applied_types') where
signature'' :: String
signature'' | length signature' == 1 = show signature'
| otherwise = concatMap (\t -> show t ++ " -> ") signature'
-- | Take a qualified name and return only its last name. E.g. idName "main.Module.A" = "A"
idName :: Id -> String
idName id = let
name = drop (lastDotIndex id + 1) id
in case name of
":" -> "(:)"
_ -> name
where
isDot = ((==) '.')
dotIndexes = findIndices isDot
lastDotIndex = last . dotIndexes
-- | Re computes the start time of a DARTState, should be called when
-- a new computation is going to begin
clearTimeout :: IM ()
clearTimeout = io getCurrentTime >>= \t -> modify (\st -> st { start_time = t })
-- | Checks whether the computations is taking long enough in order
-- to stop.
isTimeout :: IM Bool
isTimeout = do
st <- gets start_time
now <- io getCurrentTime
max_timeout <- getSetting max_time_per_function
let dayTime = now `diffUTCTime` st
passed = now `diffUTCTime` st
nominal_max = fromInteger $ (unsafeCoerce max_timeout :: Integer)
return $ (passed > nominal_max)
getSetting :: (DARTSettings -> a) -> IM a
getSetting f = gets settings >>= return . f
| kmels/dart-haskell | src/Language/Core/Interpreter/Structures.hs | bsd-3-clause | 13,071 | 0 | 14 | 2,765 | 2,754 | 1,518 | 1,236 | 197 | 2 |
module Boilerplater where
import Data.Char
import Data.List
import Data.List.Split
import Data.Maybe
import Language.Haskell.TH
import Debug.Trace
testProperties :: Q [Dec] -> Q Exp
testProperties mdecs = do
decs <- mdecs
-- NB: the use of mkName here ensures we do late binding to the testProperty function. This means that
-- it can refer to either the function from QuickCheck or QuickCheck2 according to what the user has.
property_exprs <- sequence [[| $(varE (mkName "testProperty")) $(stringE prop_name) $(varE nm) |]
| Just nm <- map decName_maybe decs
, Just raw_prop_name <- [stripPrefix_maybe "prop_" (nameBase nm)]
, let prop_name = humanize raw_prop_name ]
return $ LetE decs (ListE property_exprs)
-- | Extracts a 'Name' from the declaration if it binds precisely one name
decName_maybe :: Dec -> Maybe Name
decName_maybe (FunD nm _clauses) = Just nm
decName_maybe (ValD pat _body _dec) = patName_maybe pat
decName_maybe _ = Nothing
-- | Extracts a 'Name' from the pattern if it binds precisely one name
patName_maybe :: Pat -> Maybe Name
patName_maybe (VarP nm) = Just nm
patName_maybe (TildeP pat) = patName_maybe pat
patName_maybe (SigP pat _ty) = patName_maybe pat
patName_maybe _ = Nothing
stripPrefix_maybe :: String -> String -> Maybe String
stripPrefix_maybe prefix what
| what_start == prefix = Just what_end
| otherwise = trace ("Nothing: " ++ what) Nothing
where (what_start, what_end) = splitAt (length prefix) what
-- | Makes a valid Haskell identifier more comprehensible to human eyes. For example:
--
-- > humanize "new_HashTable_is_empty" == "New HashTable is empty"
humanize :: String -> String
humanize identifier = case splitOneOf "_" identifier of
[] -> "(no name)"
(first_word:next_words) -> intercalate " " $ capitalizeFirstLetter first_word : next_words
capitalizeFirstLetter :: String -> String
capitalizeFirstLetter [] = []
capitalizeFirstLetter (c:cs) = toUpper c : cs | batterseapower/hashtables | tests/Boilerplater.hs | bsd-3-clause | 2,104 | 0 | 15 | 484 | 486 | 245 | 241 | -1 | -1 |
module HaskellCI.ShVersionRange (
compilerVersionPredicate,
compilerVersionArithPredicate,
) where
import HaskellCI.Prelude
import Algebra.Lattice (joins)
import Algebra.Heyting.Free (Free (..))
import qualified Algebra.Heyting.Free as F
import qualified Data.Set as S
import qualified Distribution.Version as C
import HaskellCI.Compiler
-- $setup
-- >>> import Distribution.Pretty (prettyShow)
compilerVersionPredicate :: Set CompilerVersion -> CompilerRange -> String
compilerVersionPredicate = compilerVersionPredicateImpl (toTest . freeToArith) where
toTest expr = "[ " ++ expr ++ " -ne 0 ]"
compilerVersionArithPredicate :: Set CompilerVersion -> CompilerRange -> String
compilerVersionArithPredicate = compilerVersionPredicateImpl freeToArith
compilerVersionPredicateImpl
:: (Free String -> String)
-> Set CompilerVersion -> CompilerRange -> String
compilerVersionPredicateImpl conv cvs cr
| S.null ghcjsS = conv ghcFree
| otherwise = conv $
(Var "GHCJSARITH" /\ ghcjsFree) \/ (Var "! GHCJSARITH" /\ ghcFree)
where
R hdS ghcS ghcjsS = partitionCompilerVersions cvs
R hdR ghcR ghcjsR = simplifyCompilerRange cr
-- GHCJS
ghcjsS' = S.filter (`C.withinRange` ghcjsR) ghcjsS
ghcjsFree :: Free String
ghcjsFree = ghcVersionPredicate ghcjsRange
ghcjsRange = case S.toList ghcjsS' of
[] -> C.noVersion
[_] -> C.anyVersion
_ -> error "multiple GHCJS versions unsupported"
-- GHC + GHC HEAD
ghcFree :: Free String
ghcFree = ghcVersionPredicate (ghcHeadRange \/ ghcRange)
-- GHC
ghcD = roundDown ghcS
ghcS' = S.filter (`C.withinRange` ghcR) ghcS
isMinGHC u = Just u == fmap fst (S.minView ghcD)
-- if we build with GHC HEAD, than none of known versions is maxGHC.
isMaxGHC u | hdS = False
| otherwise = Just u == fmap fst (S.maxView ghcD)
findGhc :: Version -> VersionRange
findGhc v = case (S.lookupLE v ghcD, S.lookupGT v ghcD) of
(Nothing, _) -> C.noVersion
(Just u, Nothing) -> orLater u
(Just u, Just w) -> orLater u /\ earlier w
where
orLater u | isMinGHC u = C.anyVersion
| otherwise = C.orLaterVersion u
earlier u | isMaxGHC u = C.anyVersion
| otherwise = C.earlierVersion u
ghcRange :: VersionRange
ghcRange = foldr (\/) C.noVersion $ map findGhc $ S.toList ghcS'
-- GHC HEAD
ghcHeadRange :: VersionRange
ghcHeadRange
| hdR && hdS = C.laterVersion (S.findMax ghcS)
| otherwise = C.noVersion
data R a = R Bool a a
deriving (Show)
partitionCompilerVersions :: Set CompilerVersion -> R (Set Version)
partitionCompilerVersions = foldr f (R False S.empty S.empty) where
f (GHC v) (R hd ghc ghcjs) = R hd (S.insert v ghc) ghcjs
f (GHCJS v) (R hd ghc ghcjs) = R hd ghc (S.insert v ghcjs)
f GHCHead (R _ ghc ghcjs) = R True ghc ghcjs
simplifyCompilerRange :: CompilerRange -> R VersionRange
simplifyCompilerRange RangeGHC = R True C.anyVersion C.noVersion
simplifyCompilerRange RangeGHCJS = R False C.noVersion C.anyVersion
simplifyCompilerRange (Range vr) = R (not $ C.hasUpperBound vr) vr vr
simplifyCompilerRange (RangeUnion a b) =
case (simplifyCompilerRange a, simplifyCompilerRange b) of
(R x y z, R u v w) -> R (x \/ u) (y \/ v) (z \/ w)
simplifyCompilerRange (RangeInter a b) =
case (simplifyCompilerRange a, simplifyCompilerRange b) of
(R x y z, R u v w) -> R (x /\ u) (y /\ v) (z /\ w)
simplifyCompilerRange (RangePoints vs) = foldr f (R False C.noVersion C.noVersion) vs where
f (GHC v) (R hd ghc ghcjs) = R hd (C.thisVersion v \/ ghc) ghcjs
f (GHCJS v) (R hd ghc ghcjs) = R hd ghc (C.thisVersion v \/ ghcjs)
f GHCHead (R _ ghc ghcjs) = R True ghc ghcjs
ghcVersionPredicate :: C.VersionRange -> Free String
ghcVersionPredicate vr
| equivVersionRanges C.noVersion vr = bottom
| equivVersionRanges C.anyVersion vr = top
| otherwise = ghcVersionPredicate' vr
ghcVersionPredicate' :: C.VersionRange -> Free String
ghcVersionPredicate' = conj . C.asVersionIntervals
where
conj = joins . map disj
disj :: C.VersionInterval -> Free String
disj (C.LowerBound v C.InclusiveBound, C.UpperBound u C.InclusiveBound)
| v == u = Var ("HCNUMVER == " ++ f v)
disj (lb, C.NoUpperBound)
| isInclZero lb = top
| otherwise = Var (lower lb)
disj (lb, C.UpperBound v b)
| isInclZero lb = Var (upper v b)
| otherwise = Var (lower lb) /\ Var (upper v b)
isInclZero (C.LowerBound v C.InclusiveBound) = v == C.mkVersion [0]
isInclZero (C.LowerBound _ C.ExclusiveBound) = False
lower (C.LowerBound v C.InclusiveBound) = "HCNUMVER >= " ++ f v
lower (C.LowerBound v C.ExclusiveBound) = "HCNUMVER > " ++ f v
upper v C.InclusiveBound = "HCNUMVER <= " ++ f v
upper v C.ExclusiveBound = "HCNUMVER < " ++ f v
f = ghcVersionToString
-------------------------------------------------------------------------------
-- Utilities
-------------------------------------------------------------------------------
ghcVersionToString :: C.Version -> String
ghcVersionToString v = case C.versionNumbers v of
[] -> "0"
[x] -> show (x * 10000)
[x,y] -> show (x * 10000 + y * 100)
(x:y:z:_) -> show (x * 10000 + y * 100 + z)
-- | Round down a first version in major series.
--
-- >>> let rd = map prettyShow . S.toList . roundDown . S.fromList . map C.mkVersion
--
-- >>> rd []
-- []
--
-- >>> rd [ [8,0,2] ]
-- ["8.0","8.0.3"]
--
-- >>> rd [ [8,0,2], [8,2,2], [8,4,4], [8,6,5], [8,8,1] ]
-- ["8.0","8.2","8.4","8.6","8.8","8.8.2"]
--
-- >>> rd [ [8,6,1], [8,6,2], [8,6,3], [8,6,4], [8,6,5] ]
-- ["8.6","8.6.2","8.6.3","8.6.4","8.6.5","8.6.6"]
--
roundDown :: Set Version -> Set Version
roundDown = go S.empty . S.toList where
go !acc [] = acc
go !acc [v]
| S.member m acc = S.insert v $ S.insert (up v) acc
| otherwise = S.insert m $ S.insert (up v) acc
where
m = let (x,y) = ghcMajVer v in C.mkVersion [x,y]
go !acc (v:vs)
| S.member m acc = go (S.insert v acc) vs
| otherwise = go (S.insert m acc) vs
where
m = let (x,y) = ghcMajVer v in C.mkVersion [x,y]
up v = C.mkVersion $ case C.versionNumbers v of
[] -> [1]
(x:xs) -> up' x xs
up' x [] = [x + 1]
up' x (y:ys) = x : up' y ys
-------------------------------------------------------------------------------
-- Arithmetic expression
-------------------------------------------------------------------------------
freeToArith :: Free String -> String
freeToArith z
| z == top = "1"
| z == bottom = "0"
| otherwise = "$((" ++ go 0 z ++ "))"
where
go :: Int -> Free String -> String
go _ (Var x) = x
go _ F.Bottom = "1"
go _ F.Top = "0"
go d (x :/\: y) = parens (d > 3)
$ go 4 x ++ " && " ++ go 3 y
go d (x :\/: y) = parens (d > 2)
$ go 3 x ++ " || " ++ go 2 y
go d (x :=>: y) = parens (d > 2)
$ "! (" ++ go 0 x ++ ") || " ++ go 2 y
parens :: Bool -> String -> String
parens True s = "{ " ++ s ++ "; }"
parens False s = s
-------------------------------------------------------------------------------
-- PosNeg
-------------------------------------------------------------------------------
{-
data PosNeg a = Pos a | Neg a
deriving (Eq, Ord, Show, Functor)
neg :: PosNeg a -> PosNeg a
neg (Pos x) = Neg x
neg (Neg x) = Pos x
instance Applicative PosNeg where
pure = Pos
(<*>) = ap
instance Monad PosNeg where
return = pure
Pos x >>= f = f x
Neg x >>= f = neg (f x)
-}
| hvr/multi-ghc-travis | src/HaskellCI/ShVersionRange.hs | bsd-3-clause | 7,849 | 0 | 13 | 2,032 | 2,599 | 1,301 | 1,298 | -1 | -1 |
{-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleInstances, UndecidableInstances, FlexibleContexts, DeriveDataTypeable,
ScopedTypeVariables, MultiParamTypeClasses, FunctionalDependencies,ParallelListComp, EmptyDataDecls, TypeSynonymInstances, TypeOperators, TemplateHaskell #-}
-- | KansasLava is designed for generating hardware circuits. This module
-- provides a 'Rep' class that allows us to model, in the shallow embedding of
-- KL, two important features of hardware signals. First, all signals must have
-- some static width, as they will be synthsized to a collection of hardware
-- wires. Second, a value represented by a signal may be unknown, in part or in
-- whole.
module Language.KansasLava.Rep
( module Language.KansasLava.Rep
, module Language.KansasLava.Rep.TH
, module Language.KansasLava.Rep.Class
) where
import Language.KansasLava.Types
import Control.Monad (liftM)
import Data.Sized.Arith
import Data.Sized.Ix
import Data.Sized.Matrix hiding (S)
import qualified Data.Sized.Matrix as M
import Data.Sized.Unsigned as U
import Data.Sized.Signed as S
import Data.Word
--import qualified Data.Maybe as Maybe
import Data.Traversable(sequenceA)
import qualified Data.Sized.Sampled as Sampled
import Language.KansasLava.Rep.TH
import Language.KansasLava.Rep.Class
-- | Check to see if all bits in a bitvector (represented as a Matrix) are
-- valid. Returns Nothing if any of the bits are unknown.
allOkayRep :: (Size w) => Matrix w (X Bool) -> Maybe (Matrix w Bool)
allOkayRep m = sequenceA $ fmap prj m
where prj (XBool Nothing) = Nothing
prj (XBool (Just v)) = Just v
------------------------------------------------------------------------------------
instance Rep Bool where
type W Bool = X1
data X Bool = XBool (Maybe Bool)
optX (Just b) = XBool $ return b
optX Nothing = XBool $ fail "Wire Bool"
unX (XBool (Just v)) = return v
unX (XBool Nothing) = fail "Wire Bool"
repType _ = B
toRep (XBool v) = RepValue [v]
fromRep (RepValue [v]) = XBool v
fromRep rep = error ("size error for Bool : " ++ show (Prelude.length $ unRepValue rep) ++ " " ++ show rep)
showRep (XBool Nothing) = "?"
showRep (XBool (Just True)) = "H"
showRep (XBool (Just False)) = "L"
$(repIntegral ''Int (S 32)) -- a lie on 64-bit machines??
$(repIntegral ''Word8 (U 8))
$(repIntegral ''Word32 (U 32))
instance Rep () where
type W () = X0
data X () = XUnit (Maybe ())
optX (Just b) = XUnit $ return b
optX Nothing = XUnit $ fail "Wire ()"
unX (XUnit (Just v)) = return v
unX (XUnit Nothing) = fail "Wire ()"
repType _ = V 1 -- should really be V 0 TODO
toRep _ = RepValue []
fromRep _ = XUnit $ return ()
showRep _ = "()"
-- | Integers are unbounded in size. We use the type 'IntegerWidth' as the
-- associated type representing this size in the instance of Rep for Integers.
data IntegerWidth = IntegerWidth
instance Rep Integer where
type W Integer = IntegerWidth
data X Integer = XInteger Integer -- No fail/unknown value
optX (Just b) = XInteger b
optX Nothing = XInteger $ error "Generic failed in optX"
unX (XInteger a) = return a
repType _ = GenericTy
toRep = error "can not turn a Generic to a Rep"
fromRep = error "can not turn a Rep to a Generic"
showRep (XInteger v) = show v
-------------------------------------------------------------------------------------
-- Now the containers
-- TODO: fix this to use :> as the basic internal type.
instance (Rep a, Rep b) => Rep (a :> b) where
type W (a :> b) = ADD (W a) (W b)
data X (a :> b) = XCell (X a, X b)
optX (Just (a :> b)) = XCell (pureX a, pureX b)
optX Nothing = XCell (optX (Nothing :: Maybe a), optX (Nothing :: Maybe b))
unX (XCell (a,b)) = do x <- unX a
y <- unX b
return (x :> y)
repType Witness = TupleTy [repType (Witness :: Witness a), repType (Witness :: Witness b)]
toRep (XCell (a,b)) = RepValue (avals ++ bvals)
where (RepValue avals) = toRep a
(RepValue bvals) = toRep b
fromRep (RepValue vs) = XCell ( fromRep (RepValue (take size_a vs))
, fromRep (RepValue (drop size_a vs))
)
where size_a = typeWidth (repType (Witness :: Witness a))
showRep (XCell (a,b)) = showRep a ++ " :> " ++ showRep b
instance (Rep a, Rep b) => Rep (a,b) where
type W (a,b) = ADD (W a) (W b)
data X (a,b) = XTuple (X a, X b)
optX (Just (a,b)) = XTuple (pureX a, pureX b)
optX Nothing = XTuple (optX (Nothing :: Maybe a), optX (Nothing :: Maybe b))
unX (XTuple (a,b)) = do x <- unX a
y <- unX b
return (x,y)
repType Witness = TupleTy [repType (Witness :: Witness a), repType (Witness :: Witness b)]
toRep (XTuple (a,b)) = RepValue (avals ++ bvals)
where (RepValue avals) = toRep a
(RepValue bvals) = toRep b
fromRep (RepValue vs) = XTuple ( fromRep (RepValue (take size_a vs))
, fromRep (RepValue (drop size_a vs))
)
where size_a = typeWidth (repType (Witness :: Witness a))
showRep (XTuple (a,b)) = "(" ++ showRep a ++ "," ++ showRep b ++ ")"
instance (Rep a, Rep b, Rep c) => Rep (a,b,c) where
type W (a,b,c) = ADD (W a) (ADD (W b) (W c))
data X (a,b,c) = XTriple (X a, X b, X c)
optX (Just (a,b,c)) = XTriple (pureX a, pureX b,pureX c)
optX Nothing = XTriple ( optX (Nothing :: Maybe a),
optX (Nothing :: Maybe b),
optX (Nothing :: Maybe c) )
unX (XTriple (a,b,c))
= do x <- unX a
y <- unX b
z <- unX c
return (x,y,z)
repType Witness = TupleTy [repType (Witness :: Witness a), repType (Witness :: Witness b),repType (Witness :: Witness c)]
toRep (XTriple (a,b,c)) = RepValue (avals ++ bvals ++ cvals)
where (RepValue avals) = toRep a
(RepValue bvals) = toRep b
(RepValue cvals) = toRep c
fromRep (RepValue vs) = XTriple ( fromRep (RepValue (take size_a vs))
, fromRep (RepValue (take size_b (drop size_a vs)))
, fromRep (RepValue (drop (size_a + size_b) vs))
)
where size_a = typeWidth (repType (Witness :: Witness a))
size_b = typeWidth (repType (Witness :: Witness b))
showRep (XTriple (a,b,c)) = "(" ++ showRep a ++
"," ++ showRep b ++
"," ++ showRep c ++ ")"
instance (Rep a) => Rep (Maybe a) where
type W (Maybe a) = ADD (W a) X1
-- not completely sure about this representation
data X (Maybe a) = XMaybe (X Bool, X a)
optX b = XMaybe ( case b of
Nothing -> optX (Nothing :: Maybe Bool)
Just Nothing -> optX (Just False :: Maybe Bool)
Just (Just {}) -> optX (Just True :: Maybe Bool)
, case b of
Nothing -> optX (Nothing :: Maybe a)
Just Nothing -> optX (Nothing :: Maybe a)
Just (Just a) -> optX (Just a :: Maybe a)
)
unX (XMaybe (a,b)) = case unX a :: Maybe Bool of
Nothing -> Nothing
Just True -> Just $ unX b
Just False -> Just Nothing
repType _ = TupleTy [ B, repType (Witness :: Witness a)]
toRep (XMaybe (a,b)) = RepValue (avals ++ bvals)
where (RepValue avals) = toRep a
(RepValue bvals) = toRep b
fromRep (RepValue vs) = XMaybe ( fromRep (RepValue (take 1 vs))
, fromRep (RepValue (drop 1 vs))
)
showRep (XMaybe (XBool Nothing,_a)) = "?"
showRep (XMaybe (XBool (Just True),a)) = "Just " ++ showRep a
showRep (XMaybe (XBool (Just False),_)) = "Nothing"
instance (Size ix, Rep a) => Rep (Matrix ix a) where
type W (Matrix ix a) = MUL ix (W a)
data X (Matrix ix a) = XMatrix (Matrix ix (X a))
optX (Just m) = XMatrix $ fmap (optX . Just) m
optX Nothing = XMatrix $ forAll $ \ _ -> optX (Nothing :: Maybe a)
unX (XMatrix m) = liftM matrix $ mapM (\ i -> unX (m ! i)) (indices m)
repType Witness = MatrixTy (size (error "witness" :: ix)) (repType (Witness :: Witness a))
toRep (XMatrix m) = RepValue (concatMap (unRepValue . toRep) $ M.toList m)
fromRep (RepValue xs) = XMatrix $ M.matrix $ fmap (fromRep . RepValue) $ unconcat xs
where unconcat [] = []
unconcat ys = take len ys : unconcat (drop len ys)
len = Prelude.length xs `div` size (error "witness" :: ix)
instance (Size ix) => Rep (Unsigned ix) where
type W (Unsigned ix) = ix
data X (Unsigned ix) = XUnsigned (Maybe (Unsigned ix))
optX (Just b) = XUnsigned $ return b
optX Nothing = XUnsigned $ fail "Wire Int"
unX (XUnsigned (Just a)) = return a
unX (XUnsigned Nothing) = fail "Wire Int"
repType _ = U (size (error "Wire/Unsigned" :: ix))
toRep = toRepFromIntegral
fromRep = fromRepToIntegral
showRep = showRepDefault
instance (Size ix) => Rep (Signed ix) where
type W (Signed ix) = ix
data X (Signed ix) = XSigned (Maybe (Signed ix))
optX (Just b) = XSigned $ return b
optX Nothing = XSigned $ fail "Wire Int"
unX (XSigned (Just a)) = return a
unX (XSigned Nothing) = fail "Wire Int"
repType _ = S (size (error "Wire/Signed" :: ix))
toRep = toRepFromIntegral
fromRep = fromRepToIntegral
showRep = showRepDefault
-----------------------------------------------------------------------------
-- The grandfather of them all, functions.
instance (Size ix, Rep a, Rep ix) => Rep (ix -> a) where
type W (ix -> a) = MUL ix (W a)
data X (ix -> a) = XFunction (ix -> X a)
optX (Just f) = XFunction $ \ ix -> optX (Just (f ix))
optX Nothing = XFunction $ const $ unknownX
unX (XFunction f) = return (\ a ->
let fromJust' (Just x) = x
fromJust' _ = error $ show ("X",repType (Witness :: Witness (ix -> a)), showRep (optX (Just a) :: X ix))
in (fromJust' . unX . f) a)
repType Witness = MatrixTy (size (error "witness" :: ix)) (repType (Witness :: Witness a))
-- reuse the matrix encodings here
-- TODO: work out how to remove the Size ix constraint,
-- and use Rep ix somehow instead.
toRep (XFunction f) = toRep (XMatrix $ M.forAll f)
fromRep (RepValue xs) = XFunction $ \ ix ->
case fromRep (RepValue xs) of
XMatrix m -> m M.! ix
{-
infixl 4 `apX`
-- The applicative functor style 'ap'.
apX :: (Rep a, Rep b) => X (a -> b) -> X a -> X b
apX (XFunction f) a = f a
-- The apX-1 function. Useful when building applicative functor style things
-- on top of 'X'.
unapX :: (Rep a, Rep b) => (X a -> X b) -> X (a -> b)
unapX f = XFunction f
-}
-----------------------------------------------------------------------------
-- | Calculate the base-2 logrithim of a integral value.
log2 :: (Integral a) => a -> a
log2 0 = 0
log2 1 = 1
log2 n = log2 (n `div` 2) + 1
-- Perhaps not, because what does X0 really mean over a wire, vs X1.
instance Rep X0 where
type W X0 = X0
data X X0 = X0'
optX _ = X0'
unX X0' = return X0
repType _ = V 0
toRep = toRepFromIntegral
fromRep = fromRepToIntegral
showRep = showRepDefault
instance (Integral x, Size x) => Rep (X0_ x) where
type W (X0_ x) = LOG (SUB (X0_ x) X1)
data X (X0_ x) = XX0 (Maybe (X0_ x))
optX (Just x) = XX0 $ return x
optX Nothing = XX0 $ fail "X0_"
unX (XX0 (Just a)) = return a
unX (XX0 Nothing) = fail "X0_"
repType _ = U (log2 (size (error "repType" :: X0_ x) - 1))
toRep = toRepFromIntegral
fromRep = sizedFromRepToIntegral
showRep = showRepDefault
instance (Integral x, Size x) => Rep (X1_ x) where
type W (X1_ x) = LOG (SUB (X1_ x) X1)
data X (X1_ x) = XX1 (Maybe (X1_ x))
optX (Just x) = XX1 $ return x
optX Nothing = XX1 $ fail "X1_"
unX (XX1 (Just a)) = return a
unX (XX1 Nothing) = fail "X1_"
repType _ = U (log2 (size (error "repType" :: X1_ x) - 1))
toRep = toRepFromIntegral
fromRep = sizedFromRepToIntegral
showRep = showRepDefault
-- | This is a version of fromRepToIntegral that
-- check to see if the result is inside the size bounds.
sizedFromRepToIntegral :: forall w . (Rep w, Integral w, Size w) => RepValue -> X w
sizedFromRepToIntegral w
| val_integer >= toInteger (size (error "witness" :: w)) = unknownX
| otherwise = val
where
val_integer :: Integer
val_integer = fromRepToInteger w
val :: X w
val = fromRepToIntegral w
-----------------------------------------------------------------
instance (Enum ix, Size m, Size ix) => Rep (Sampled.Sampled m ix) where
type W (Sampled.Sampled m ix) = ix
data X (Sampled.Sampled m ix) = XSampled (Maybe (Sampled.Sampled m ix))
optX (Just b) = XSampled $ return b
optX Nothing = XSampled $ fail "Wire Sampled"
unX (XSampled (Just a)) = return a
unX (XSampled Nothing) = fail "Wire Sampled"
repType _ = SampledTy (size (error "witness" :: m)) (size (error "witness" :: ix))
toRep (XSampled Nothing) = unknownRepValue (Witness :: Witness (Sampled.Sampled m ix))
toRep (XSampled (Just a)) = RepValue $ fmap Just $ M.toList $ Sampled.toMatrix a
fromRep r = optX (liftM (Sampled.fromMatrix . M.fromList) $ getValidRepValue r)
showRep = showRepDefault
| andygill/kansas-lava | Language/KansasLava/Rep.hs | bsd-3-clause | 13,705 | 35 | 21 | 3,886 | 5,158 | 2,621 | 2,537 | 246 | 2 |
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Reflex.Model where
import Control.Monad
import Data.Functor.Misc
import Data.Maybe (fromJust, isJust)
import Reflex.Class
import Data.Dependent.Map (DMap, GCompare)
import qualified Data.Dependent.Map as DMap
import Data.MemoTrie
data Model t
instance (Enum t, HasTrie t, Ord t) => Reflex (Model t) where
newtype Behavior (Model t) a = Behavior { unBehavior :: t -> a }
newtype Event (Model t) a = Event { unEvent :: t -> Maybe a }
type PushM (Model t) = (->) t
type PullM (Model t) = (->) t
never :: Event (Model t) a
never = Event $ const Nothing
constant :: a -> Behavior (Model t) a
constant = pure
push :: (a -> PushM (Model t) (Maybe b)) -> Event (Model t) a -> Event (Model t) b
push f e = Event . memo $ \t -> unEvent e t >>= \a -> f a t
pull :: PullM (Model t) a -> Behavior (Model t) a
pull = Behavior . memo
merge :: GCompare k => DMap (WrapArg (Event (Model t)) k) -> Event (Model t) (DMap k)
merge events = Event $ memo $ \t ->
let currentOccurrences = unwrapDMapMaybe (($ t) . unEvent) events
in if DMap.null currentOccurrences
then Nothing
else Just currentOccurrences
fan :: GCompare k => Event (Model t) (DMap k) -> EventSelector (Model t) k
fan e = EventSelector $ \k -> Event $ unEvent e >=> DMap.lookup k
switch :: Behavior (Model t) (Event (Model t) a) -> Event (Model t) a
switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
coincidence :: Event (Model t) (Event (Model t) a) -> Event (Model t) a
coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
instance Ord t => MonadSample (Model t) ((->) t) where
sample :: Behavior (Model t) a -> t -> a
sample = unBehavior
instance (Enum t, HasTrie t, Ord t) => MonadHold (Model t) ((->) t) where
hold :: a -> Event (Model t) a -> t -> Behavior (Model t) a
hold a (Event e) t0 = Behavior . memo $ \t ->
let s = [r | r <- [t0..(pred t)], isJust (e r)]
in if t <= t0 || null s
then a
else fromJust (e (last s))
| jeffreyrosenbluth/reflex-semantics | src/Model.hs | bsd-3-clause | 2,270 | 0 | 17 | 632 | 1,021 | 526 | 495 | -1 | -1 |
-- | This simply re-exports some commonly-used modules.
module Data.Thyme
( module Data.Thyme.Calendar
, module Data.Thyme.Clock
, module Data.Thyme.Format
, module Data.Thyme.LocalTime
) where
import Data.Thyme.Calendar
import Data.Thyme.Clock
import Data.Thyme.Format
import Data.Thyme.LocalTime
| liyang/thyme | src/Data/Thyme.hs | bsd-3-clause | 319 | 0 | 5 | 53 | 61 | 42 | 19 | 9 | 0 |
module Rumpus.Systems.Hands where
import Rumpus.Systems.Controls
import Rumpus.Systems.Physics
import Rumpus.Systems.Collisions
import Rumpus.Systems.Shared
import Rumpus.Systems.Attachment
import PreludeExtra
import RumpusLib
type HandEntityID = EntityID
data HandsSystem = HandsSystem
{ _hndLeftHand :: HandEntityID
, _hndRightHand :: HandEntityID
, _hndBeams :: Map WhichHand EntityID
--, _hndHead :: EntityID
} deriving Show
makeLenses ''HandsSystem
defineSystemKey ''HandsSystem
handSize :: V3 GLfloat
handSize = V3 0.075 0.075 0.075
handColor :: V4 GLfloat
handColor = V4 0.6 0.6 0.9 1
makeHand :: (MonadIO m, MonadState ECS m, MonadBaseControl IO m)
=> WhichHand -> m EntityID
makeHand whichHand = do
handID <- spawnEntity $ do
myColor ==> handColor
mySize ==> handSize
myShape ==> Cube
myBody ==> Detector
myBodyFlags ==> [Ungrabbable]
myMass ==> 0
myCollisionBegan ==> \_ impulse -> do
hapticPulse whichHand (floor $ impulse * 10000)
-- Create a "wrist" below the hand
spawnChildOf_ handID $ do
myColor ==> handColor
mySize ==> V3 0.07 0.07 0.15
myShape ==> Cube
myPose ==> position (V3 0 0 0.1)
return handID
startHandsSystem :: (MonadBaseControl IO m, MonadState ECS m, MonadIO m) => m ()
startHandsSystem = do
leftHandID <- makeHand LeftHand
rightHandID <- makeHand RightHand
registerSystem sysHands $ HandsSystem
{ _hndLeftHand = leftHandID
, _hndRightHand = rightHandID
, _hndBeams = mempty
}
return ()
getLeftHandID :: (MonadState ECS m) => m EntityID
getLeftHandID = viewSystem sysHands hndLeftHand
getRightHandID :: (MonadState ECS m) => m EntityID
getRightHandID = viewSystem sysHands hndRightHand
getHandID :: MonadState ECS m => WhichHand -> m EntityID
getHandID whichHand = case whichHand of
LeftHand -> getLeftHandID
RightHand -> getRightHandID
getWhichHand :: MonadState ECS m => EntityID -> m (Maybe WhichHand)
getWhichHand entityID = do
leftHandID <- getLeftHandID
rightHandID <- getRightHandID
return $ if
| entityID == leftHandID -> Just LeftHand
| entityID == rightHandID -> Just RightHand
| otherwise -> Nothing
getHandIDs :: (MonadState ECS m) => m [EntityID]
getHandIDs = do
leftHandID <- getLeftHandID
rightHandID <- getRightHandID
return [ leftHandID
, rightHandID
]
getHandIDsByWhichHand :: (MonadState ECS m) => m [(WhichHand, EntityID)]
getHandIDsByWhichHand = do
leftHandID <- getLeftHandID
rightHandID <- getRightHandID
return [ (LeftHand, leftHandID)
, (RightHand, rightHandID)
]
getHandPose :: MonadState ECS m => WhichHand -> m (M44 GLfloat)
getHandPose whichHand = getEntityPose =<< getHandID whichHand
otherHandFrom :: WhichHand -> WhichHand
otherHandFrom whichHand = case whichHand of
LeftHand -> RightHand
RightHand -> LeftHand
getOtherHandID :: MonadState ECS m => WhichHand -> m EntityID
getOtherHandID whichHand = getHandID (otherHandFrom whichHand)
withLeftHandEvents :: MonadState ECS m => (HandEvent -> m ()) -> m ()
withLeftHandEvents f = withSystem_ sysControls $ \controlSystem -> do
let events = controlSystem ^. ctsEvents
forM_ events (\e -> onLeftHandEvent e f)
withRightHandEvents :: MonadState ECS m => (HandEvent -> m ()) -> m ()
withRightHandEvents f = withSystem_ sysControls $ \controlSystem -> do
let events = controlSystem ^. ctsEvents
forM_ events (\e -> onRightHandEvent e f)
withHandEvents :: MonadState ECS m => WhichHand -> (HandEvent -> m ()) -> m ()
withHandEvents hand f = withSystem_ sysControls $ \controlSystem -> do
let events = controlSystem ^. ctsEvents
forM_ events (\e -> onHandEvent hand e f)
isEntityBeingHeldByHand :: MonadState ECS m
=> EntityID -> WhichHand -> m Bool
isEntityBeingHeldByHand entityID whichHand = do
handID <- getHandID whichHand
isEntityAttachedTo entityID handID
isBeingHeldByHand :: (MonadState ECS m, MonadReader EntityID m)
=> WhichHand -> m Bool
isBeingHeldByHand whichHand = do
entityID <- ask
isEntityBeingHeldByHand entityID whichHand
isBeingHeld :: (MonadReader EntityID m, MonadState ECS m) => m Bool
isBeingHeld = isEntityBeingHeld =<< ask
isEntityBeingHeld :: MonadState ECS f => EntityID -> f Bool
isEntityBeingHeld entityID = do
or <$> forM [LeftHand, RightHand] (isEntityBeingHeldByHand entityID)
| lukexi/rumpus | src/Rumpus/Systems/Hands.hs | bsd-3-clause | 4,703 | 0 | 18 | 1,172 | 1,348 | 668 | 680 | -1 | -1 |
;
; HSP help managerp HELP\[Xt@C
; (檪u;vÌsÍRgƵijêÜ·)
;
%type
g£½ß
%ver
3.3
%note
llmod3.hspðCN[h·éBKvɶÄabout.hsp,msgdlg.hsp,multiopen.hsp,console.hsp,unicode.hsp,dragdrop.hsp,input.hspðCN[h·é
%date
2009/08/01
%author
tom
%dll
llmod3
%url
http://www5b.biglobe.ne.jp/~diamond/hsp/hsp2file.htm
%index
about
vOÌo[Wð\¦·é_CAOðì¬
%group
g£üoͧä½ß
%prm
"s1","s2"
s1 : AvP[V¼ªüÁ½¶ñÏܽͶñ
s2 : »ìÒ¼ªüÁ½¶ñÏܽͶñ
%inst
vOÌo[Wð\¦·éÈÇÉgíêé_CAOð\¦µÜ·B
AvP[V¼s1ð"my.exeÌÊÞ°¼Þ®Ýîñ#my.exe ver 1.00"
Ìæ¤É#ÅæØéÆ'Microsoft my.exe ver 1.00'Æ¢¤\¦ªÁíèÜ·B
%index
msgdlg
g£dialog(type 0`3 )
%group
IuWFNg§ä½ß
%prm
"s1","s2",n3,n4
s1 : bZ[WªüÁ½¶ñÏܽͶñ
s2 : ^CgªüÁ½¶ñÏܽͶñ
n3 : ^Cv
n4 : ACR^Cv
%inst
HSPÌdialog½ßÌg£ÅÅ·B
^p
^Cv
0 Ok
1 Ok ·¬Ý¾Ù
2 ~@Äs@³
3 Í¢@¢¢¦@·¬Ý¾Ù
4 Í¢@¢¢¦
5 ÄJs ·¬Ý¾Ù
^
ACR^Cv
0 ACR³µ
1 G[(x)
2 NGX`}[N(?)
3 x(!)
4 îñ(i)
5 EXEªÁÄ¢éACR
^
±Ì½ßðÄÑoµ½ãÌstatÌl
l Ið³ê½{^
1 Ok
2 ·¬Ý¾Ù
3 ~
4 Äs
5 ³
6 ͢
7 ¢¢¦
-1 G[¶
^p
^CvÉȺÌlðÁ¦éÆftHg{^ªÏ¦çêÜ·B
0 {^1
$100 {^2
$200 {^3
ACR^CvÉȺÌlðÁ¦éÆr[v¹ªÏ¦çêÜ·B
0 ¢¹(m[})
$100 x¹
%sample
msgdlg "¡úͱ±ÅI¹µÜ·©H","vOÌI¹",3,5
if stat=6 : dialog "Í¢@ªIð³êܵ½"
if stat=7 : dialog "¢¢¦@ªIð³êܵ½"
if stat=2 : dialog "·¬Ý¾Ù@ªIð³êܵ½"
%index
multiopen
¡Ìt@C¼ðæ¾
%group
IuWFNg§ä½ß
%prm
v1,v2,n3,n4
v1 : Ið³ê½t@C¼ðó¯æé½ßÌÏ
v2 : îñ
n3 : tB^ÌCfbNX(1©ç)
n4 : Read Only{bNXðt¯é
%inst
HSPÌdialog(type 16,17)Å¡Ìt@CðIðū鿤ɵ½àÌÅ·B
multiopenÄÑoµÉAv1.0,v1.1É»ê¼êv1,v2ÌTCYðãüµÄ¨«Ü·B
v2ÉÍáÌæ¤È`®ÅtB^ðãüµÜ·B
n3ðȪAܽÍ}CiXÌlðgÁ½Æ«Ì®ìÍõlQÆB
n4ð1É·éÆReadOnly{bNXðt¯Ü·B2É·éÆReadOnly{bNXð`FbNµ½óÔɵܷB
^
±Ì½ßðÄÑoµ½ãÌstatÌl
^p
0 LZ³ê½
1 t@CªIð³êÄOK{^ª³ê½
2 t@CªIð³êÄOK{^ª³ê½(ReadOnlyª`FbN³êÄ¢éB½¾µ¡Ið³êĢȢêÌÝ)
^p
p3ð0(Ȫ)ɵÄp1,p2ɶñðüêéÆp1ª^CgÉÈèAp2ÍútH_ÉÈèÜ·B
p3ð}CiXlÉ·éÆÛ¶·ét@C¼ð¾éÆ«Ég¤±ÆªÅ«Ü·B(½¾µ¡IðÍūܹñ)
^
¡Ìt@CªIð³ê½©Ínotesel,notemaxðgÁIJ×Ü·B
t@Cªêµ©Ið³êÈ©Á½êAp1ÉÍt@C¼ÌtpXªãü³êAp2ÉÍt@CÌg£qªãü³êÜ·B
t@Cª¡IÎê½êÍAp1ÉnotegetÅæ¾Å«é`®Åt@C¼ª¡üÁÄ¢ÄAp2ÉÍIð³ê½t@Cª étH_ªãü³êÜ·B(p1Ìt@C¼Í'\r'($0d)ÅæØçêĢܷB)
%sample
buf_size=512 : info_size=128
alloc buf,buf_size
alloc info,info_size
^
buf="̧²ÙðJtest title" : info="a:\\windows"
multiopen buf,info
buf=buf_size
buf.1=info_size
info="HSP2 ½¸ØÌßÄ̧²Ù(*.hsp)|*.hsp|÷½Ä̧²Ù(*.txt)|*.txt|SÄÌ̧²Ù|*.*|"
multiopen buf,info,1
if stat=0 : mes "LZ³êܵ½" : else {
notesel buf
notemax mx
mes "Ið³ê½t@C "+mx
repeat mx
noteget a,cnt
mes a
loop
if mx=1 : mes "g£qÍ"+info : else mes "tH_ "+info
}
%index
console_end
R\[EBhEð¶é
%group
½ßTv
%inst
R\[EBhEð¶ܷB
%href
console
%index
console
R\[EBhEðì¬
%group
½ßTv
%inst
R\[EBhEð쬵ܷB
%href
console_end
gets
puts
console_color
console_pos
%index
puts
R\[ɶñð«Þ
%group
½ßTv
%prm
v1
v1 : R\[É\¦·é¶ñªüÁ½¶ñÏ
%inst
R\[ɶñð\¦µÜ·B
(putzðg¤Æv1ɼڶñðgp·é±ÆªÅ«Ü·B)
%href
gets
console
%index
gets
R\[©ç¶ñðÇÝÞ
%group
½ßTv
%prm
v1,n2
v1 : R\[©ç̶ñðæ¾·éÏ
n2 : æ¾·é¶Ì
%inst
R\[©ç¶ñðæ¾µÜ·B
n2ðȪµ½Æ«ÌlÍ63Å·B
%href
puts
console
%index
console_color
R\[ÌeLXgÌFÝè
%group
½ßTv
%prm
n1
n1 : R\[̶ñÌF
%inst
R\[É\¦·é¶ñÌFðÝèµÜ·B
n1ÍȺÌlðgÝí¹Äg¢Ü·B1+4¾ÆÉÈèÜ·B
1+4+8žé¢ÉÈèÜ·B
^
^p
n1Ìl F
1 Â
2 Î
4 Ô
8 ²
$10 Â(wi)
$20 Î(wi)
$40 Ô(wi)
$80 ²(wi)
^p
%href
puts
console
%index
console_pos
R\[̶\¦ÊuÝè
%group
½ßTv
%prm
n1,n2
n1 : xÀW
n2 : yÀW
%inst
¶ñð\¦·éÀWðÝèµÜ·B
%href
puts
console
%index
to_uni
UnicodeÖÏ·
%group
¶ñì½ß
%prm
v1,v2,n3
v1 : Unicodeði[·éÏ
v2 : UnicodeÉÏ··é¶ñÏ
n3 : UnicodeÉÏ··é¶ñÌ·³
%inst
ANSI¶ñ(SJIS)ðUNICODEÉÏ·µÜ·B
^
±Ì½ßðÄÑoµ½ãAstatÉobt@É«Üê½Unicode¶Ìªãü³êÜ·B
0ÈçG[Å·B
^
unicodeÄÑoµãÉstatÉüélÌ'obt@É«Üê½Unicode¶Ì'ÍA1oCg(¼p)¶Í1¶¤2oCg(Sp)¶à1¶Æ¦Ü·B
á¦Î
s="abc ¢¤"
ð·×ÄUnicodeÉÏ·µ½ ÆÌstatlÍ6+1(* +1ÍÅã̶ñI¶Ôñ)BÆÈèÜ·B
^
n3ð-1É·éÆwèµ½¶ñSÄðÏ·µÜ·B
n3ð0É·éÆUnicodeði[·éÌÉKvÈÏÌTCYðԵܷB(oCgPÊ)
%href
from_uni
%sample
s="UnicodeÉÏ··é¶ñ"
strlen sl,s
;alloc buf,(sl+1)*2 ;±Ìê(sl+1)*2ª64ɽȢÌÅallocÍKvÈ¢
to_uni buf,s,sl+1
usize=stat
if usize=-1 : dialog "G[ª¶µÜµ½"
if usize=0 : dialog "Ï·ª¸sµÜµ½"
if usize>0 : bsave "unicode.dat",buf,usize*2
%index
from_uni
Unicode©çANSIÉÏ·
%group
¶ñì½ß
%prm
v1,v2,n3
v1 : Multibyteði[·éÏ
v2 : MultibyteÉÏ··éUnicode¶ñªüÁÄ¢éÏ
n3 : MultibyteÉÏ··éUnicode¶ñÌ·³
%inst
UNICODEðANSI¶ñÉÏ·µÜ·B
^
±Ì½ßðÄÑoµ½ãAstatÉobt@É«Üê½Multibyte¶Ìªãü³êÜ·B
0ÈçG[Å·B
^
±Ì½ßðÄÑoµ½ãÌstatÌlA'obt@É«Üê½Multibyte¶Ì'Í1oCg(¼p)¶Í1¶¤2oCg(Sp)¶Í2¶Æ¦Ü·B
^
'MultibyteÉÏ··éUnicode¶ñÌ·³'ð-1É·éÆSÄÏ·µÜ·B
'MultibyteÉÏ··éUnicode¶ñÌ·³'ð0É·éÆMultibyteði[·éÌÉKvÈÏÌTCYðԵܷB(oCgPÊ)
%href
to_uni
%sample
exist "unicode.dat"
bload "unicode.dat",uni,strsize
buf=""
from_uni buf,uni,-1
mbsize=stat
if mbsize=-1 : dialog "G[ª¶µÜµ½"
if mbsize=0 : dialog "Ï·ª¸sµÜµ½"
if mbsize>0 : dialog buf
%index
dd_accept
hbO&hbvðū鿤ɷé
%group
½ßTv
%prm
v1,v2,n3
v1 : hbO&hbv³ê½t@C¼ðüêéÏ
v2 : hbO&hbv³ê½t@CðüêéÏ
n3 : EBhEID
%inst
n3Åwèµ½EBhEÉhbO&hbv(ȺD&D)ðū鿤ɵܷB
½¾µAEBhEID 1ÍÝèūܹñB
dd_acceptðÀsµ½ãAEBhEÉt@CªD&D³êéÆv1Åwèµ½ÏÉD&D³ê½t@C¼ªüèÜ·B
v2ÉÍD&D³ê½t@CÌAD&D³ê½ÀWAEBhEIDªãü³êÜ·B
^
D&D³ê½t@C¼Í"\n"ÅæØçêĢܷ(D&D³ê½t@Cª1ÂÌêÅà)B
1ÂÌt@C¼ðæèoµ½¢Æ«Ím[gpbh½ßðg¤ÆÖÅ·B
^
dd_acceptÀsãÍAv1,v2ÉÝèµ½ÏÍalloc,dim,sdimÈÇÉgpµÈ¢Åº³¢B
%href
dd_reject
%sample
#include "llmod3.hsp"
#include "dragdrop.hsp"
^
alloc buf,1024*64 ;hbO&hbv³ê½t@C¼ðüêéÏ
dd_accept buf,a
^
*@
wait 1
if a {
cls
pos 0,0
mes "hbO&hbv³ê½t@C:"+a
mes "hbO&hbv³ê½t@CÊu x:"+a.1+" y:"+a.2
mes "hbO&hbv³ê½EBhEID :"+a.3
mes buf
a=0 ; aðZbgµÄ¾³¢
}
goto @b
%index
dd_reject
hbO&hbvðūȢæ¤É·é
%group
g£üoͧä½ß
%prm
n1,n2
n1 : EBhEID
n2 : tO
%inst
hbO&hbvðūȢæ¤ÉµÜ·B
dd_acceptðÀsµÄ¢È¢êÉÍøÊª èܹñB
n2ð1É·éÆà¤êxhbO&hbvðū鿤ɵܷB
%href
dd_accept
%index
keybd_event
L[{[hì
%group
g£üoͧä½ß
%prm
n1,n2,n3
n1 : L[R[h
n2 : L[ðú·tO
n3 : IvV
%inst
L[{[hìðs¢Ü·B
n1ɵ½¢L[ÌL[R[hðwèµÜ·B
n2ð0ɵı̽ßðÀs·éÆn1ðOñÀsµ½Æ«Æ¯¶L[R[hA
n2ð1ɵÄà¤êx±Ì½ßðÀsµÈ¢ÆL[ðúµ½±ÆÉÈèܹñB
n2ð-1ɷ鯵Äúµ½±ÆÉÈèÜ·B
n3ÌIvVÍXN[VbgL[ð·Æ«ÉgpµÜ·Bn3ð0É·éÆtXN[A1É·éÆANeBuÈEBhEªNbv{[hÉRs[³êÜ·B
^
keybd_eventͼÌvOÌEBhEªANeBuÈêÅàÀs³êÜ·B
^
<>L[R[h
L[R[hÍgetkeyÅgp·éàÌÆ¯¶Å·B
Ù©ÉàÈºÌæ¤Èà̪ èÜ·B
^p
n1Ìl
44 XN[Vbg
45 INS
46 DEL
106 eL[Ì'*'
107 eL[Ì'+'
108 eL[Ì','
109 eL[Ì'-'
110 eL[Ì'.'
111 eL[Ì'/'
^p
%sample
#include "llmod3.hsp"
#include "input.hsp"
^
exec "notepad"
s="ABCDEFG" : strlen L,s
^
repeat L
peek c,s,cnt
keybd_event c,-1
loop
^
keybd_event 18,-1 ;ALT
keybd_event 'F',-1 ;̧²Ù(F)
keybd_event 'O',-1 ;J(O)
^
keybd_event 'N',-1 ;Z[umF_CAOÌ¢¢¦(N)
^
s="INPUTnAS" : strlen L,s ;'n'ÍL[R[hÅ'.'(110)ð\·
^
;±±ÌRgðO·ÆSHIFTðµ½±ÆÉÈèå¶ÉÈèÜ·
;keybd_event 16
^
repeat L
peek c,s,cnt
keybd_event c,-1
loop
^
;ãÌRgðOµ½Æ«Í±±ÌRgàOµÄ¾³¢
;keybd_event 16,1
^
keybd_event 13,-1 ;ENTER
^
stop
%index
mouse_event
}EXì
%group
g£üoͧä½ß
%prm
n1,n2,n3
n1 : ì^Cv
n2 :
½ûüÌÚ®Ê
n3 : ¼ûüÌÚ®Ê
%inst
}EXìðs¢Ü·B
n1Éwè·é^CvÅ}EXìðs¤±ÆªÅ«Ü·B
½ûüÌÚ®ÊÍAæÊ¶©çEÖÚ®³¹éÆ«ª³A»Ìtª
¼ûüÌÚ®ÊÍAæÊã©çºÖÚ®³¹éÆ«ª³A»Ìtª
Š鱯Éӵľ³¢B
^
mouse_eventÍHSPÌvOªANeBuÅȢƫÅà}EXìÉe¿µÜ·B
^
<>ì^Cv
n1ÌlÍȺÌàÌðgÝí¹Ägp·é±ÆªÅ«Ü·B
^p
n1Ìl
$1 }EXÚ®
$2 ¶Ì{^ð·
$4 ¶Ì{^ðú·
$8 EÌ{^ð·
$10 EÌ{^ðú·
$20 Ì{^ð·
$40 Ì{^ðú·
^p
%sample
#include "llmod3.hsp"
#include "input.hsp"
^
*lp
movx=0 : movy=0
getkey k,37 : if k : movx- ;©L[
getkey k,38 : if k : movy- ;ªL[
getkey k,39 : if k : movx+ ;¨L[
getkey k,40 : if k : movy+ ;«L[
^
;SHIFTª³ê½ç¶{^ð·
getkey kSHIFT,16 : if kSHIFT : Lbtn=$2 : else Lbtn=0
mouse_event $1+Lbtn, movx, movy
^
;SHIFTð·Æ}EX̶{^ðµ½±ÆÉÈèkª1ÉÈé
getkey k,1 : if k : pset mousex,mousey
^
;SHIFTª³êĽç¶{^ðú·
if kSHIFT : mouse_event $4
^
await 1
goto lp
| zakki/openhsp | package/hsphelp/llmod3_stdio.hs | bsd-3-clause | 11,627 | 2,699 | 14 | 1,711 | 4,064 | 3,363 | 701 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module System.IO.Streams.Network.HAProxy.Tests (tests) where
------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Concurrent
import qualified Control.Exception as E
import Control.Monad (forever)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.ByteString as S8
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.Typeable
import qualified Network.Socket as N
import System.IO (hPutStrLn, stderr)
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import qualified System.IO.Streams.Network.HAProxy as HA
import System.IO.Streams.Network.Internal.Address (AddressNotSupportedException (..), getSockAddr, getSockAddrImpl)
import System.Timeout (timeout)
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testOldHaProxy
, testOldHaProxy6
, testOldHaProxyFailure
, testOldHaProxyLocal
, testOldHaProxyLocal6
, testOldHaProxyBadAddress
, testBlackBox
, testBlackBoxLocal
, testNewHaProxy
#ifndef WINDOWS
, testNewHaProxyUnix
#endif
, testNewHaProxy6
, testNewHaProxyTooBig
, testNewHaProxyTooSmall
, testNewHaProxyBadVersion
, testNewHaProxyLocal
, testGetSockAddr
, testTrivials
]
------------------------------------------------------------------------------
runInput :: ByteString
-> N.SockAddr
-> N.SockAddr
-> (HA.ProxyInfo -> InputStream ByteString -> OutputStream ByteString -> IO a)
-> IO a
runInput input sa sb action = do
is <- Streams.fromList [input]
(os, _) <- Streams.listOutputStream
let pinfo = HA.makeProxyInfo sa sb (addrFamily sa) N.Stream
HA.behindHAProxyWithLocalInfo pinfo (is, os) action
------------------------------------------------------------------------------
addrFamily :: N.SockAddr -> N.Family
addrFamily s = case s of
(N.SockAddrInet _ _) -> N.AF_INET
(N.SockAddrInet6 _ _ _ _) -> N.AF_INET6
#ifndef WINDOWS
(N.SockAddrUnix _ ) -> N.AF_UNIX
#endif
------------------------------------------------------------------------------
blackbox :: (Chan Bool
-> HA.ProxyInfo
-> InputStream ByteString
-> OutputStream ByteString
-> IO ())
-> ByteString
-> IO ()
blackbox action input = withTimeout 10 $ do
chan <- newChan
E.bracket (startServer chan) (killThread . fst) client
readChan chan >>= assertBool "success"
where
client (_, port) = do
(family, addr) <- getSockAddr port "127.0.0.1"
E.bracket (N.socket family N.Stream 0) N.close $ \sock -> do
N.connect sock addr
(_, os) <- Streams.socketToStreams sock
threadDelay 10000
Streams.write (Just input) os
Streams.write Nothing os
threadDelay 10000
withTimeout n m = timeout (n * 1000000) m >>= maybe (fail "timeout") return
startServer :: Chan Bool -> IO (ThreadId, Int)
startServer = E.bracketOnError getSock N.close . forkServer
getSock = do
(family, addr) <- getSockAddr (fromIntegral N.aNY_PORT) "127.0.0.1"
sock <- N.socket family N.Stream 0
N.setSocketOption sock N.ReuseAddr 1
N.setSocketOption sock N.NoDelay 1
N.bindSocket sock addr
N.listen sock 150
return $! sock
forkServer chan sock = do
port <- fromIntegral <$> N.socketPort sock
tid <- E.mask_ $ forkIOWithUnmask $ server chan sock
return (tid, port)
server :: Chan Bool -> N.Socket -> (forall z. IO z -> IO z) -> IO ()
server chan boundSocket restore = loop `E.finally` N.close boundSocket
where
loop = forever $
E.bracketOnError (restore $ N.accept boundSocket)
(N.close . fst)
(\(sock, sa) ->
forkIOWithUnmask
$ \r -> flip E.finally (N.close sock)
$ r $ HA.behindHAProxy sock sa (action chan))
------------------------------------------------------------------------------
testBlackBox :: Test
testBlackBox = testCase "test/blackbox" $
blackbox action
"PROXY TCP4 127.0.0.1 127.0.0.1 10000 80\r\nblah"
where
action chan proxyInfo !is !_ = do
sa <- localhost 10000
sb <- localhost 80
x <- E.try $ do assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
case x of
Left (e :: E.SomeException) -> do hPutStrLn stderr $ show e
writeChan chan False
Right !_ -> writeChan chan True
------------------------------------------------------------------------------
testBlackBoxLocal :: Test
testBlackBoxLocal = testCase "test/blackbox_local" $
blackbox action "PROXY UNKNOWN\r\nblah"
where
action chan proxyInfo !is !_ = do
let q = HA.getSourceAddr proxyInfo `seq` HA.getDestAddr proxyInfo
`seq` ()
x <- q `seq` E.try $ go is proxyInfo
case x of
Left (e :: E.SomeException) -> do hPutStrLn stderr $ show e
writeChan chan False
Right !_ -> writeChan chan True
go is proxyInfo = do
Streams.toList is >>= assertEqual "rest" ["blah"]
assertEqual "family" N.AF_INET $ HA.getFamily proxyInfo
assertEqual "type" N.Stream $ HA.getSocketType proxyInfo
------------------------------------------------------------------------------
testOldHaProxy :: Test
testOldHaProxy = testCase "test/old_ha_proxy" $ do
sa <- localhost 1111
sb <- localhost 2222
runInput "PROXY TCP4 127.0.0.1 127.0.0.1 10000 80\r\nblah" sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost 10000
sb <- localhost 80
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
testOldHaProxy6 :: Test
testOldHaProxy6 = testCase "test/old_ha_proxy6" $ do
sa <- localhost6 1111
sb <- localhost6 2222
runInput "PROXY TCP6 ::1 ::1 10000 80\r\nblah" sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost6 10000
sb <- localhost6 80
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET6 $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
testOldHaProxyLocal :: Test
testOldHaProxyLocal = testCase "test/old_ha_proxy_local" $ do
sa <- localhost 1111
sb <- localhost 2222
runInput "PROXY UNKNOWN\r\nblah" sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost 1111
sb <- localhost 2222
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
testOldHaProxyLocal6 :: Test
testOldHaProxyLocal6 = testCase "test/old_ha_proxy_local6" $ do
sa <- localhost6 1111
sb <- localhost6 2222
runInput "PROXY UNKNOWN\r\nblah" sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost6 1111
sb <- localhost6 2222
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET6 $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
testOldHaProxyFailure :: Test
testOldHaProxyFailure = testCase "test/old_ha_proxy_failure" $ do
sa <- localhost 1111
sb <- localhost 2222
expectException "bad family"
$ runInput "PROXY ZZZ qqqq wwww 10000 80\r\nblah" sa sb action
expectException "short"
$ runInput "PROXY TCP4 \r\nblah" sa sb action
expectException "non-integral"
$ runInput "PROXY TCP4 127.0.0.1 127.0.0.1 xxx yyy\r\nblah" sa sb action
where
action _ _ _ = return ()
------------------------------------------------------------------------------
testOldHaProxyBadAddress :: Test
testOldHaProxyBadAddress = testCase "test/old_ha_proxy_bad_address" $ do
sa <- localhost 1111
sb <- localhost 2222
expectException "bad address" $
runInput "PROXY TCP4 @~!@#$%^ (*^%$ 10000 80\r\nblah" sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost 10000
sb <- localhost 80
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
protocolHeader :: ByteString
protocolHeader = S8.pack [ 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D
, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A ]
{-# NOINLINE protocolHeader #-}
------------------------------------------------------------------------------
testNewHaProxy :: Test
testNewHaProxy = testCase "test/new_ha_proxy" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x21\x11" -- TCP over v4
, "\x00\x0c" -- 12 bytes of address (network ordered)
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
runInput input sa sb action
where
action proxyInfo !is !_ = do
sa <- localhost 10000
sb <- localhost 80
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
#ifndef WINDOWS
unixPath :: ByteString -> ByteString
unixPath s = S.append s (S.replicate (108 - S.length s) '\x00')
------------------------------------------------------------------------------
unixSock :: ByteString -> N.SockAddr
unixSock = N.SockAddrUnix . S.unpack
------------------------------------------------------------------------------
testNewHaProxyUnix :: Test
testNewHaProxyUnix = testCase "test/new_ha_proxy_unix" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x21\x31" -- unix stream
, "\x00\xd8" -- 216 bytes
, unixPath "/foo"
, unixPath "/bar"
, "blah" -- the rest
]
runInput input sa sb action
let input2 = S.concat [ protocolHeader
, "\x21\x32" -- unix datagram
, "\x00\xd8" -- 216 bytes
, unixPath "/foo"
, unixPath "/bar"
, "blah" -- the rest
]
runInput input2 sa sb action2
where
action proxyInfo !is !_ = do
let sa = unixSock "/foo"
let sb = unixSock "/bar"
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_UNIX $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
action2 proxyInfo !is !_ = do
let sa = unixSock "/foo"
let sb = unixSock "/bar"
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_UNIX $ HA.getFamily proxyInfo
assertEqual "stype" N.Datagram $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
#endif
------------------------------------------------------------------------------
testNewHaProxy6 :: Test
testNewHaProxy6 = testCase "test/new_ha_proxy_6" $ do
sa <- localhost6 1111
sb <- localhost6 2222
let input = S.concat [ protocolHeader
, "\x21\x21" -- TCP over v6
, "\x00\x24" -- 36 bytes of address (network ordered)
, lhBinary
, lhBinary
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
runInput input sa sb action
where
lhBinary = S.concat [ S.replicate 15 '\x00', S.singleton '\x01' ]
action proxyInfo !is !_ = do
sa <- localhost6 10000
sb <- localhost6 80
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET6 $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
------------------------------------------------------------------------------
testNewHaProxyBadVersion :: Test
testNewHaProxyBadVersion = testCase "test/new_ha_proxy_bad_version" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x31\x11" -- TCP over v4, bad version
, "\x00\x0c" -- 12 bytes of address (network ordered)
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "bad version" $ runInput input sa sb action
let input2 = S.concat [ protocolHeader
, "\x2F\x11" -- TCP over v4, bad command
, "\x00\x0c" -- 12 bytes of address (network ordered)
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "bad version" $ runInput input2 sa sb action
let input3 = S.concat [ protocolHeader
, "\x21\x41" -- bad family
, "\x00\x0c" -- 12 bytes of address (network ordered)
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "bad family" $ runInput input3 sa sb action
let input4 = S.concat [ protocolHeader
, "\x21\x14" -- bad family
, "\x00\x0c" -- 12 bytes of address (network ordered)
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "bad type" $ runInput input4 sa sb action
where
action _ !_ !_ = return ()
------------------------------------------------------------------------------
testNewHaProxyTooSmall :: Test
testNewHaProxyTooSmall = testCase "test/new_ha_proxy_too_small" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x21\x11" -- TCP over v4
, "\x00\x02" -- 2 bytes
, "\x00\x00"
, "blah" -- the rest
]
expectException "too small" $ runInput input sa sb action
let input2 = S.concat [ protocolHeader
, "\x21\x21" -- TCP over v6
, "\x00\x02" -- 2 bytes
, "\x00\x00"
, "blah" -- the rest
]
expectException "too small" $ runInput input2 sa sb action
#ifndef WINDOWS
let input3 = S.concat [ protocolHeader
, "\x21\x31" -- unix
, "\x00\x02" -- 2 bytes
, "\x00\x00"
, "blah" -- the rest
]
expectException "too small" $ runInput input3 sa sb action
#endif
where
action _ !_ !_ = return ()
------------------------------------------------------------------------------
testNewHaProxyTooBig :: Test
testNewHaProxyTooBig = testCase "test/new_ha_proxy_too_big" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x21\x11" -- TCP over v4
, "\x03\x0c" -- 780: 12 bytes of address
-- (network ordered) plus 768
-- bytes of slop
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, S.replicate 768 '0'
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "too big" $ runInput input sa sb action
let input2 = S.concat [ protocolHeader
, "\x21\x00" -- TCP over v4
, "\x03\x0c" -- 780: 12 bytes of address
-- (network ordered) plus 768
-- bytes of slop
, "\x7f\x00\x00\x01" -- localhost
, "\x7f\x00\x00\x01"
, S.replicate 768 '0'
, "\x27\x10" -- 10000 in network order
, "\x00\x50" -- 80 in network order
, "blah" -- the rest
]
expectException "too big" $ runInput input2 sa sb action
where
action _ !_ !_ = return ()
------------------------------------------------------------------------------
testNewHaProxyLocal :: Test
testNewHaProxyLocal = testCase "test/new_ha_proxy_local" $ do
sa <- localhost 1111
sb <- localhost 2222
let input = S.concat [ protocolHeader
, "\x20\x00" -- LOCAL UNSPEC
, "\x00\x00" -- 0 bytes of address (network ordered)
, "blah" -- the rest
]
runInput input sa sb action
#ifndef WINDOWS
let ua = unixSock "/foo"
let ub = unixSock "/bar"
let input2 = S.concat [ protocolHeader
, "\x20\x00" -- LOCAL UNSPEC
, "\x00\x00" -- 0 bytes of address (network ordered)
, "blah" -- the rest
]
runInput input2 ua ub action2
#endif
where
action proxyInfo !is !_ = do
sa <- localhost 1111
sb <- localhost 2222
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_INET $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
#ifndef WINDOWS
action2 proxyInfo !is !_ = do
let sa = unixSock "/foo"
let sb = unixSock "/bar"
assertEqual "src addr" sa $ HA.getSourceAddr proxyInfo
assertEqual "dest addr" sb $ HA.getDestAddr proxyInfo
assertEqual "family" N.AF_UNIX $ HA.getFamily proxyInfo
assertEqual "stype" N.Stream $ HA.getSocketType proxyInfo
Streams.toList is >>= assertEqual "rest" ["blah"]
#endif
------------------------------------------------------------------------------
testGetSockAddr :: Test
testGetSockAddr = testCase "test/address/getSockAddr" $ do
(f1, a1) <- getSockAddr 10 "127.0.0.1"
x1 <- localhost 10
assertEqual "f1" f1 N.AF_INET
assertEqual "x1" x1 a1
(f2, a2) <- getSockAddr 10 "::1"
x2 <- localhost6 10
assertEqual "f2" f2 N.AF_INET6
assertEqual "x2" x2 a2
expectException "empty result" $
getSockAddrImpl (\_ _ _ -> return []) 10 "foo"
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "test/trivials" $ do
coverShowInstance $ HA.makeProxyInfo undefined undefined undefined undefined
coverTypeableInstance $ AddressNotSupportedException undefined
coverShowInstance $ AddressNotSupportedException "ok"
------------------------------------------------------------------------------
localhost :: Int -> IO (N.SockAddr)
localhost p = N.SockAddrInet (fromIntegral p) <$> N.inet_addr "127.0.0.1"
------------------------------------------------------------------------------
localhost6 :: Int -> IO (N.SockAddr)
localhost6 p = snd <$> getSockAddr p "::1"
------------------------------------------------------------------------------
expectException :: String -> IO a -> IO ()
expectException name act = do
e <- E.try act
case e of
Left (z::E.SomeException) -> (length $ show z) `seq` return ()
Right _ -> fail $ name ++ ": expected exception, didn't get one"
------------------------------------------------------------------------------
coverTypeableInstance :: (Monad m, Typeable a) => a -> m ()
coverTypeableInstance a = typeOf a `seq` return ()
------------------------------------------------------------------------------
eatException :: IO a -> IO ()
eatException a = (a >> return ()) `E.catch` handler
where
handler :: E.SomeException -> IO ()
handler _ = return ()
------------------------------------------------------------------------------
-- | Kill the false negative on derived show instances.
coverShowInstance :: (MonadIO m, Show a) => a -> m ()
coverShowInstance x = liftIO (a >> b >> c)
where
a = eatException $ E.evaluate $ length $ showsPrec 0 x ""
b = eatException $ E.evaluate $ length $ show x
c = eatException $ E.evaluate $ length $ showList [x] ""
| 23Skidoo/io-streams-haproxy | test/System/IO/Streams/Network/HAProxy/Tests.hs | bsd-3-clause | 25,160 | 0 | 20 | 8,316 | 5,364 | 2,623 | 2,741 | 450 | 3 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship (ScheduleRelationship(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data ScheduleRelationship = SCHEDULED
| ADDED
| UNSCHEDULED
| CANCELED
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data,
Prelude'.Generic)
instance P'.Mergeable ScheduleRelationship
instance Prelude'.Bounded ScheduleRelationship where
minBound = SCHEDULED
maxBound = CANCELED
instance P'.Default ScheduleRelationship where
defaultValue = SCHEDULED
toMaybe'Enum :: Prelude'.Int -> P'.Maybe ScheduleRelationship
toMaybe'Enum 0 = Prelude'.Just SCHEDULED
toMaybe'Enum 1 = Prelude'.Just ADDED
toMaybe'Enum 2 = Prelude'.Just UNSCHEDULED
toMaybe'Enum 3 = Prelude'.Just CANCELED
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum ScheduleRelationship where
fromEnum SCHEDULED = 0
fromEnum ADDED = 1
fromEnum UNSCHEDULED = 2
fromEnum CANCELED = 3
toEnum
= P'.fromMaybe
(Prelude'.error
"hprotoc generated code: toEnum failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship")
. toMaybe'Enum
succ SCHEDULED = ADDED
succ ADDED = UNSCHEDULED
succ UNSCHEDULED = CANCELED
succ _
= Prelude'.error
"hprotoc generated code: succ failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship"
pred ADDED = SCHEDULED
pred UNSCHEDULED = ADDED
pred CANCELED = UNSCHEDULED
pred _
= Prelude'.error
"hprotoc generated code: pred failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.TripDescriptor.ScheduleRelationship"
instance P'.Wire ScheduleRelationship where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB ScheduleRelationship
instance P'.MessageAPI msg' (msg' -> ScheduleRelationship) ScheduleRelationship where
getVal m' f' = f' m'
instance P'.ReflectEnum ScheduleRelationship where
reflectEnum = [(0, "SCHEDULED", SCHEDULED), (1, "ADDED", ADDED), (2, "UNSCHEDULED", UNSCHEDULED), (3, "CANCELED", CANCELED)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".transit_realtime.TripDescriptor.ScheduleRelationship") ["GTFS", "Realtime", "Internal"]
["Com", "Google", "Transit", "Realtime", "TripDescriptor"]
"ScheduleRelationship")
["GTFS", "Realtime", "Internal", "Com", "Google", "Transit", "Realtime", "TripDescriptor", "ScheduleRelationship.hs"]
[(0, "SCHEDULED"), (1, "ADDED"), (2, "UNSCHEDULED"), (3, "CANCELED")]
Prelude'.False
instance P'.TextType ScheduleRelationship where
tellT = P'.tellShow
getT = P'.getRead | romanofski/gtfsbrisbane | src/GTFS/Realtime/Internal/Com/Google/Transit/Realtime/TripDescriptor/ScheduleRelationship.hs | bsd-3-clause | 3,453 | 0 | 11 | 609 | 776 | 431 | 345 | 72 | 1 |
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
module Data where
import Flat
ggg = encode (Uno,Due,Tre)
{-
(One Two) Three (Four Five)
Four = 110 = 6
-}
data Numero = Uno
| Due
| Tre
| Quattro
deriving (Eq,Show,Generic,Flat)
-- chkSize 9 >> unsafeEnc 1 >>
-- chkSize 3 >> Bit8 3 val
data Booleano = Falso | Vero deriving (Eq,Show,Generic,Flat)
data Tuple2 a b = Tuple2 a b deriving (Eq,Show,Generic,Flat)
data Tuple3 a b c = Tuple3 a b c deriving (Eq,Show,Generic,Flat)
| tittoassini/flat | benchmarks/Data.hs | bsd-3-clause | 524 | 0 | 6 | 136 | 159 | 93 | 66 | 12 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards, FlexibleInstances, DefaultSignatures #-}
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.FromRow
-- Copyright: (c) 2012 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <[email protected]>
-- Stability: experimental
--
-- The 'FromRow' typeclass, for converting a row of results
-- returned by a SQL query into a more useful Haskell representation.
--
-- Predefined instances are provided for tuples containing up to ten
-- elements. The instances for 'Maybe' types return 'Nothing' if all
-- the columns that would have been otherwise consumed are null, otherwise
-- it attempts a regular conversion.
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.FromRow
( FromRow(..)
, RowParser
, field
, fieldWith
, numFieldsRemaining
) where
import Prelude hiding (null)
import Control.Applicative (Applicative(..), (<$>), (<|>), (*>), liftA2)
import Control.Monad (replicateM, replicateM_)
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Class
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Vector (Vector)
import qualified Data.Vector as V
import Database.PostgreSQL.Simple.Types (Only(..))
import qualified Database.PostgreSQL.LibPQ as PQ
import Database.PostgreSQL.Simple.Internal
import Database.PostgreSQL.Simple.Compat
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.Ok
import Database.PostgreSQL.Simple.Types ((:.)(..), Null)
import Database.PostgreSQL.Simple.TypeInfo
import GHC.Generics
-- | A collection type that can be converted from a sequence of fields.
-- Instances are provided for tuples up to 10 elements and lists of any length.
--
-- Note that instances can be defined outside of postgresql-simple, which is
-- often useful. For example, here's an instance for a user-defined pair:
--
-- @data User = User { name :: String, fileQuota :: Int }
--
-- instance 'FromRow' User where
-- fromRow = User \<$\> 'field' \<*\> 'field'
-- @
--
-- The number of calls to 'field' must match the number of fields returned
-- in a single row of the query result. Otherwise, a 'ConversionFailed'
-- exception will be thrown.
--
-- Note that 'field' evaluates it's result to WHNF, so the caveats listed in
-- mysql-simple and very early versions of postgresql-simple no longer apply.
-- Instead, look at the caveats associated with user-defined implementations
-- of 'fromField'.
class FromRow a where
fromRow :: RowParser a
default fromRow :: (Generic a, GFromRow (Rep a)) => RowParser a
fromRow = to <$> gfromRow
getvalue :: PQ.Result -> PQ.Row -> PQ.Column -> Maybe ByteString
getvalue result row col = unsafeDupablePerformIO (PQ.getvalue' result row col)
nfields :: PQ.Result -> PQ.Column
nfields result = unsafeDupablePerformIO (PQ.nfields result)
getTypeInfoByCol :: Row -> PQ.Column -> Conversion TypeInfo
getTypeInfoByCol Row{..} col =
Conversion $ \conn -> do
oid <- PQ.ftype rowresult col
Ok <$> getTypeInfo conn oid
getTypenameByCol :: Row -> PQ.Column -> Conversion ByteString
getTypenameByCol row col = typname <$> getTypeInfoByCol row col
fieldWith :: FieldParser a -> RowParser a
fieldWith fieldP = RP $ do
let unCol (PQ.Col x) = fromIntegral x :: Int
r@Row{..} <- ask
column <- lift get
lift (put (column + 1))
let ncols = nfields rowresult
if (column >= ncols)
then lift $ lift $ do
vals <- mapM (getTypenameByCol r) [0..ncols-1]
let err = ConversionFailed
(show (unCol ncols) ++ " values: " ++ show (map ellipsis vals))
Nothing
""
("at least " ++ show (unCol column + 1)
++ " slots in target type")
"mismatch between number of columns to \
\convert and number in target type"
conversionError err
else do
let !result = rowresult
!typeOid = unsafeDupablePerformIO (PQ.ftype result column)
!field = Field{..}
lift (lift (fieldP field (getvalue result row column)))
field :: FromField a => RowParser a
field = fieldWith fromField
ellipsis :: ByteString -> ByteString
ellipsis bs
| B.length bs > 15 = B.take 10 bs `B.append` "[...]"
| otherwise = bs
numFieldsRemaining :: RowParser Int
numFieldsRemaining = RP $ do
Row{..} <- ask
column <- lift get
return $! (\(PQ.Col x) -> fromIntegral x) (nfields rowresult - column)
null :: RowParser Null
null = field
instance (FromField a) => FromRow (Only a) where
fromRow = Only <$> field
instance (FromField a) => FromRow (Maybe (Only a)) where
fromRow = (null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b) => FromRow (a,b) where
fromRow = (,) <$> field <*> field
instance (FromField a, FromField b) => FromRow (Maybe (a,b)) where
fromRow = (null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c) => FromRow (a,b,c) where
fromRow = (,,) <$> field <*> field <*> field
instance (FromField a, FromField b, FromField c) => FromRow (Maybe (a,b,c)) where
fromRow = (null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d) =>
FromRow (a,b,c,d) where
fromRow = (,,,) <$> field <*> field <*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d) =>
FromRow (Maybe (a,b,c,d)) where
fromRow = (null *> null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e) =>
FromRow (a,b,c,d,e) where
fromRow = (,,,,) <$> field <*> field <*> field <*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e) =>
FromRow (Maybe (a,b,c,d,e)) where
fromRow = (null *> null *> null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f) =>
FromRow (a,b,c,d,e,f) where
fromRow = (,,,,,) <$> field <*> field <*> field <*> field <*> field
<*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f) =>
FromRow (Maybe (a,b,c,d,e,f)) where
fromRow = (null *> null *> null *> null *> null *>
null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g) =>
FromRow (a,b,c,d,e,f,g) where
fromRow = (,,,,,,) <$> field <*> field <*> field <*> field <*> field
<*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g) =>
FromRow (Maybe (a,b,c,d,e,f,g)) where
fromRow = (null *> null *> null *> null *> null *>
null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h) =>
FromRow (a,b,c,d,e,f,g,h) where
fromRow = (,,,,,,,) <$> field <*> field <*> field <*> field <*> field
<*> field <*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h) =>
FromRow (Maybe (a,b,c,d,e,f,g,h)) where
fromRow = (null *> null *> null *> null *> null *>
null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h, FromField i) =>
FromRow (a,b,c,d,e,f,g,h,i) where
fromRow = (,,,,,,,,) <$> field <*> field <*> field <*> field <*> field
<*> field <*> field <*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h, FromField i) =>
FromRow (Maybe (a,b,c,d,e,f,g,h,i)) where
fromRow = (null *> null *> null *> null *> null *>
null *> null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h, FromField i, FromField j) =>
FromRow (a,b,c,d,e,f,g,h,i,j) where
fromRow = (,,,,,,,,,) <$> field <*> field <*> field <*> field <*> field
<*> field <*> field <*> field <*> field <*> field
instance (FromField a, FromField b, FromField c, FromField d, FromField e,
FromField f, FromField g, FromField h, FromField i, FromField j) =>
FromRow (Maybe (a,b,c,d,e,f,g,h,i,j)) where
fromRow = (null *> null *> null *> null *> null *>
null *> null *> null *> null *> null *> pure Nothing)
<|> (Just <$> fromRow)
instance FromField a => FromRow [a] where
fromRow = do
n <- numFieldsRemaining
replicateM n field
instance FromField a => FromRow (Maybe [a]) where
fromRow = do
n <- numFieldsRemaining
(replicateM_ n null *> pure Nothing) <|> (Just <$> replicateM n field)
instance FromField a => FromRow (Vector a) where
fromRow = do
n <- numFieldsRemaining
V.replicateM n field
instance FromField a => FromRow (Maybe (Vector a)) where
fromRow = do
n <- numFieldsRemaining
(replicateM_ n null *> pure Nothing) <|> (Just <$> V.replicateM n field)
instance (FromRow a, FromRow b) => FromRow (a :. b) where
fromRow = (:.) <$> fromRow <*> fromRow
-- Type class for default implementation of FromRow using generics
class GFromRow f where
gfromRow :: RowParser (f p)
instance GFromRow f => GFromRow (M1 c i f) where
gfromRow = M1 <$> gfromRow
instance (GFromRow f, GFromRow g) => GFromRow (f :*: g) where
gfromRow = liftA2 (:*:) gfromRow gfromRow
instance (FromField a) => GFromRow (K1 R a) where
gfromRow = K1 <$> field
instance GFromRow U1 where
gfromRow = pure U1
| timmytofu/postgresql-simple | src/Database/PostgreSQL/Simple/FromRow.hs | bsd-3-clause | 10,591 | 0 | 22 | 2,628 | 3,475 | 1,890 | 1,585 | -1 | -1 |
-- | Select the specific media header from the 'HandlerType'
module Data.ByteString.IsoBaseFileFormat.Boxes.SpecificMediaHeader where
--
-- import Data.ByteString.IsoBaseFileFormat.Boxes.VideoMediaHeader
import Data.ByteString.IsoBaseFileFormat.Boxes.Handler
--
-- | An open type family to select the specific media header from the
-- 'HandlerType'
type family MediaHeaderFor (t :: HandlerType)
| sheyll/isobmff-builder | src/Data/ByteString/IsoBaseFileFormat/Boxes/SpecificMediaHeader.hs | bsd-3-clause | 397 | 0 | 6 | 44 | 35 | 27 | 8 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Examples.CRC.USB5
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- The USB5 CRC implementation
-----------------------------------------------------------------------------
module Examples.CRC.USB5 where
import Data.SBV
newtype SWord11 = S11 SWord16
instance EqSymbolic SWord11 where
S11 w .== S11 w' = w .== w'
mkSWord11 :: SWord16 -> SWord11
mkSWord11 w = S11 (w .&. 0x07FF)
extendData :: SWord11 -> SWord16
extendData (S11 w) = w `shiftL` 5
mkFrame :: SWord11 -> SWord16
mkFrame w = extendData w .|. crc_11_16 w
-- crc returns 16 bits, but the first 11 are always 0
crc_11_16 :: SWord11 -> SWord16
crc_11_16 msg = crc16 .&. 0x1F -- just get the last 5 bits
where divisor :: SWord16
divisor = polynomial [5, 2, 0]
crc16 = pMod (extendData msg) divisor
diffCount :: SWord16 -> SWord16 -> SWord8
diffCount x y = count $ zipWith (.==) (blastLE x) (blastLE y)
where count [] = 0
count (b:bs) = let r = count bs in ite b r (1+r)
-- Claim: If there is an undetected corruption, it must be at least at 3 bits
usbGood :: SWord16 -> SWord16 -> SBool
usbGood sent16 received16 =
sent ./= received ==> diffCount frameSent frameReceived .>= 3
where sent = mkSWord11 sent16
received = mkSWord11 received16
frameSent = mkFrame sent
frameReceived = mkFrame received
{-# ANN crc_11_16 ("HLint: ignore Use camelCase" :: String) #-}
| Copilot-Language/sbv-for-copilot | SBVUnitTest/Examples/CRC/USB5.hs | bsd-3-clause | 1,586 | 0 | 11 | 344 | 384 | 205 | 179 | 28 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module JSONTest where
import Data.Aeson
import Test.HUnit (assertBool)
import qualified Data.ByteString.Lazy as BSL
import Data.Conduit (runConduit, (.|))
import qualified Data.Conduit.List as CL
import Database.Persist.MySQL
import MyInit
specs :: Spec
specs = describe "JSONTest" $ do
it "can select json with rawsql" $ db $ do
let testJSON = toJSON $ [object [ "test" .= ("value" :: Text) ]]
[[PersistByteString value]] <- runConduit $ rawQuery "select JSON_ARRAY(JSON_OBJECT('test', 'value'))" [] .| CL.consume
liftIO $ Just testJSON `shouldBe` (decode $ BSL.fromStrict value)
| yesodweb/persistent | persistent-mysql/test/JSONTest.hs | mit | 1,137 | 0 | 19 | 171 | 200 | 119 | 81 | 29 | 1 |
--
--
--
-----------------
-- Exercise 7.27.
-----------------
--
--
--
module E'7'27 where
import Prelude hiding ( getLine )
-- Subchapter 7.6 (relevant definitions of it):
type Word = String
type Line = [Word]
getLine :: Int -> [Word] -> Line -- Use "import Prelude hiding (getLine)" to avoid an ambiguous occurrence exception with Prelude imports.
getLine lineLength [] = []
getLine lineLength ( wordFromList : remainingWordsInList )
| wordFromListLength <= lineLength = wordFromList : restOfLine
| otherwise = []
where
wordFromListLength :: Int
wordFromListLength = length wordFromList
remainingLineLength :: Int
remainingLineLength = lineLength - (wordFromListLength + 1) -- 1 is the inter-word space.
restOfLine :: Line
restOfLine = getLine remainingLineLength remainingWordsInList
-- ...
dropLine :: Int -> [Word] -> Line
dropLine _ [] = []
dropLine lineLength wordList@( wordFromList : remainingWordsInList ) -- "wordList" is an alias for "(wordFromList : remainingWordsInList)".
| lineLength >= wordFromListLength = restOfWordList -- Based on the behaviour of "getLine" (see definition of it).
| otherwise = wordList
where
wordFromListLength :: Int
wordFromListLength = length wordFromList
remainingLineLength :: Int
remainingLineLength = lineLength - (wordFromListLength + 1) -- 1 is the inter-word space.
restOfWordList :: [Word]
restOfWordList = dropLine remainingLineLength remainingWordsInList
{- GHCi>
let line :: [Word] ; line = ["12", "456", "89"]
dropLine 0 line
dropLine 1 line
dropLine 2 line
dropLine 3 line
dropLine 4 line
dropLine 5 line
dropLine 6 line
-}
-- [ "12" , "456" , "89" ]
-- [ "12" , "456" , "89" ]
-- [ "456" , "89" ]
-- [ "456" , "89" ]
-- [ "456" , "89" ]
| pascal-knodel/haskell-craft | _/links/E'7'27.hs | mit | 1,815 | 0 | 9 | 385 | 296 | 170 | 126 | 26 | 1 |
{- |
Module : $Header$
Description : termination proofs for equation systems, using AProVE
Copyright : (c) Mingyi Liu and Till Mossakowski and Uni Bremen 2004-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Termination proofs for equation systems, using AProVE
-}
module CASL.CCC.TerminationProof (terminationProof) where
import CASL.AS_Basic_CASL
import CASL.Quantification
import CASL.Sign
import CASL.ToDoc
import CASL.Utils
import CASL.CCC.TermFormula
import Common.DocUtils
import Common.Id
import Common.ProofUtils
import Common.Result
import Common.Utils
import Control.Monad
import System.Directory
import Data.List (intercalate, partition)
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
{-
Automatic termination proof
using AProVE, see http://aprove.informatik.rwth-aachen.de/
interface to AProVE system, using system
translate CASL signature to AProVE Input Language,
CASL formulas to AProVE term rewrite systems(TRS),
see http://aprove.informatik.rwth-aachen.de/help/html/in/trs.html
if a equation system is terminal, then it is computable.
-}
terminationProof :: (FormExtension f, TermExtension f, Ord f) => Sign f e
-> [FORMULA f] -> [FORMULA f] -> IO (Maybe Bool, String)
terminationProof sig fs dms =
if null fs then return (Just True, "no formulas") else do
let
axhead =
[ "(RULES"
, "eq(t,t) -> true"
, "eq(_,_) -> false"
, "and(true,t) -> t"
, "and(false,t) -> false"
, "or(true,t) -> true"
, "or(false,t) -> t"
, "implies(false,t) -> true"
, "implies(true,t) -> t"
, "equiv(t,t) -> true"
, "equiv(_,_) -> false"
, "not(true) -> false"
, "not(false) -> true"
, "when_else(t1,true,t2) -> t1"
, "when_else(t1,false,t2) -> t2" ]
allVars = Set.toList . Set.map fst . Set.unions
. map getQuantVars $ dms ++ fs
c_vars = "(VAR t t1 t2 "
++ unwords (map transToken allVars) ++ ")"
(rs, ls) = partition (isJust . maybeResult) $ map (axiom2TRS sig dms) fs
c_axms = axhead ++ map (fromJust . maybeResult) rs ++ [")"]
if null ls then do
tmpFile <- getTempFile (unlines $ c_vars : c_axms) "Input.trs"
aprovePath <- getEnvDef "HETS_APROVE" "CASL/Termination/AProVE.jar"
mr <- timeoutCommand 20 "java"
("-ea" : "-jar" : aprovePath : words "-u cli -m wst -p plain"
++ [tmpFile])
removeFile tmpFile
return $ case mr of
Nothing -> (Nothing, "timeout")
Just (_, proof, _) -> (case words proof of
"YES" : _ -> Just True
"NO" : _ -> Just False
_ -> Nothing, proof)
else return (Nothing, unlines . map diagString $ concatMap diags ls)
keywords :: [String]
keywords = ["eq", "or", "implies", "equiv", "when_else"]
-- others are CASL keywords
++ ["CONTEXTSENSITIVE", "EQUATIONS", "INNERMOST", "RULES", "STRATEGY"
, "THEORY", "VAR"]
transStringAux :: String -> String
transStringAux = concatMap (\ c -> Map.findWithDefault [c] c charMap)
transString :: String -> String
transString s = let t = transStringAux s in
if elem t keywords then '_' : t else t
transToken :: Token -> String
transToken = transString . tokStr
transId :: Id -> ShowS
transId (Id ts cs _) =
showSepList id (showString . transToken) ts .
if null cs then id else
showString "{" . showSepList (showString "-") transId cs
. showString "}"
-- | translate id to string
idStr :: Id -> String
idStr i = transId i ""
-- | get the name of a operation symbol
opSymName :: OP_SYMB -> String
opSymName = idStr . opSymbName
-- | get the name of a predicate symbol
predSymName :: PRED_SYMB -> String
predSymName = idStr . predSymbName
-- | create a predicate application
predAppl :: (Monad m, FormExtension f) => PRED_SYMB -> [TERM f] -> m String
predAppl p = liftM (predSymName p ++) . termsPA
-- | apply function string to argument string with brackets
apply :: String -> String -> String
apply f a = f ++ "(" ++ a ++ ")"
-- | create a binary application
applyBin :: String -> String -> String -> String
applyBin o t1 t2 = apply o $ t1 ++ "," ++ t2
-- | translate a casl term to a term of TRS(Terme Rewrite Systems)
term2TRS :: (Monad m, FormExtension f) => TERM f -> m String
term2TRS t = case unsortedTerm t of
Qual_var var _ _ -> return $ tokStr var
Application o ts _ -> liftM (opSymName o ++) $ termsPA ts
Conditional t1 f t2 _ -> do
b1 <- term2TRS t1
c <- axiomSub f
b2 <- term2TRS t2
return $ apply "when_else" $ b1 ++ "," ++ c ++ "," ++ b2
_ -> fail $ "no support for: " ++ showDoc t ""
-- | translate a list of casl terms to the patterns of a term in TRS
termsPA :: (Monad m, FormExtension f) => [TERM f] -> m String
termsPA ts = if null ts then return "" else
liftM (apply "" . intercalate ",") $ mapM term2TRS ts
{- | translate a casl axiom to TRS-rule:
a rule without condition is represented by "A -> B" in
Term Rewrite Systems; if there are some conditions, then
follow the conditions after the symbol "|".
For example : "A -> B | C -> D, E -> F, ..." -}
axiom2TRS :: (FormExtension f, TermExtension f, Ord f, Monad m) => Sign f e
-> [FORMULA f] -> FORMULA f -> m String
axiom2TRS sig doms f = case splitAxiom f of
(cs, f') -> do
r <- axiom2Rule f'
s <- mapM (axiom2Cond sig doms) cs
let a c = case s of
[] -> ""
_ -> c ++ intercalate ", " s
t = return $ r ++ a " | "
g = a ", "
case f' of
Equation t1 Strong t2 _ -> case unsortedTerm t2 of
Conditional tt1 ff tt2 _ -> do
e1 <- term2TRS t1
c <- axiomSub ff
b1 <- term2TRS tt1
b2 <- term2TRS tt2
return $ e1 ++ " -> " ++ b1 ++ " | "
++ c ++ " -> true" ++ g ++ "\n"
++ e1 ++ " -> " ++ b2 ++ " | "
++ c ++ " -> false" ++ g
_ -> t
_ -> t
axiom2Cond :: (FormExtension f, TermExtension f, Ord f, Monad m) => Sign f e
-> [FORMULA f] -> FORMULA f -> m String
axiom2Cond sig doms f = let s = liftM (++ " -> true") $ axiomSub f in
case f of
Definedness t _ | isApp t ->
case filter (sameOpsApp sig t . fst . fromJust . domainDef) doms of
phi : _ ->
let Result _ st = getSubstForm sig (quantFreeVars sig f nullRange) phi
in case st of
Just ((_, _), (s2, _)) ->
let Just (_, c) = domainDef phi
in axiom2Cond sig doms $ replaceVarsF s2 id c
Nothing -> s
[] -> s
_ -> s
-- | check whether it is an application term only applied to variables
isApp :: TERM t -> Bool
isApp t = case unsortedTerm t of
Application _ ts _ -> all isVar ts
_ -> False
axiom2Rule :: (Monad m, FormExtension f) => FORMULA f -> m String
axiom2Rule f = case f of
Negation f' _ -> case f' of
Quantification {} ->
fail "no support for negated quantification"
Definedness t _ -> liftM (++ " -> undefined") $ term2TRS t
_ -> liftM (++ " -> false") $ axiomSub f'
Definedness {} -> liftM (++ " -> open") $ axiomSub f
Equation t1 Strong t2 _ -> do
e1 <- term2TRS t1
e2 <- term2TRS t2
return $ e1 ++ " -> " ++ e2
Relation f1 Equivalence f2 _ -> do
f3 <- axiomSub f1
f4 <- axiomSub f2
return $ f3 ++ " -> " ++ f4
_ -> liftM (++ " -> true") $ axiomSub f
-- | translate a casl axiom (without conditions) to a term of TRS,
axiomSub :: (Monad m, FormExtension f) => FORMULA f -> m String
axiomSub f = case f of
Junction j fs@(_ : _) _ -> do
as <- mapM axiomSub fs
return $ foldr1 (applyBin $ if j == Con then "and" else "or") as
Negation f' _ -> liftM (apply "not") $ axiomSub f'
Atom b _ -> return $ if b then "true" else "false"
Predication p_s ts _ -> predAppl p_s ts
Definedness t _ -> liftM (apply "def") $ term2TRS t
Equation t1 _ t2 _ -> do -- support any equation
e1 <- term2TRS t1
e2 <- term2TRS t2
return $ applyBin "eq" e1 e2
Relation f1 c f2 _ -> do
s1 <- axiomSub f1
s2 <- axiomSub f2
return $ applyBin (if c == Equivalence then "equiv" else "implies") s1 s2
Quantification {} -> fail "no support for local quantifications"
Membership {} -> fail "no support for membership tests"
_ -> fail $ "no support for: " ++ showDoc f ""
| keithodulaigh/Hets | CASL/CCC/TerminationProof.hs | gpl-2.0 | 8,358 | 45 | 36 | 2,172 | 2,566 | 1,285 | 1,281 | 181 | 13 |
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_HADDOCK hide, prune #-}
-- |
-- Module : Data.ByteString.Search.Internal.BoyerMoore
-- Copyright : Daniel Fischer
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <[email protected]>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of both strict and lazy
-- 'S.ByteString' values. Breaking, splitting and replacing
-- using the Boyer-Moore algorithm.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Search.Internal.BoyerMoore (
matchLS
, matchSS
-- Non-overlapping
, matchNOS
-- Replacing substrings
-- replacing
, replaceAllS
-- Breaking on substrings
-- breaking
, breakSubstringS
, breakAfterS
-- Splitting on substrings
-- splitting
, splitKeepEndS
, splitKeepFrontS
, splitDropS
) where
import Data.ByteString.Search.Internal.Utils
(occurs, suffShifts, strictify)
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as LI
import Data.ByteString.Unsafe (unsafeIndex)
import Data.Array.Base (unsafeAt)
import Data.Word (Word8)
-- overview
--
-- This module exports three search functions for searching in strict
-- ByteStrings. One for searching non-overlapping occurrences of a strict
-- pattern and one each for possibly overlapping occurrences of a lazy
-- resp. strict pattern. The common base name is @match@, the suffix
-- indicates the type of search to perform. These functions
-- return (for a non-empty pattern) a list of all the indices of the target
-- string where an occurrence of the pattern begins, if some occurrences
-- overlap, all starting indices are reported. The list is produced lazily,
-- so not necessarily the entire target string is searched.
--
-- The behaviour of these functions when given an empty pattern has changed.
-- Formerly, the @matchXY@ functions returned an empty list then, now it's
-- @[0 .. 'length' target]@.
--
-- Newly added are functions to replace all (non-overlapping) occurrences
-- of a pattern within a string, functions to break ByteStrings at the first
-- occurrence of a pattern and functions to split ByteStrings at each
-- occurrence of a pattern. None of these functions does copying, so they
-- don't introduce large memory overhead.
--
-- Internally, a lazy pattern is always converted to a strict ByteString,
-- which is necessary for an efficient implementation of the algorithm.
-- The limit this imposes on the length of the pattern is probably
-- irrelevant in practice, but perhaps it should be mentioned.
-- This also means that the @matchL*@ functions are mere convenience wrappers.
-- Except for the initial 'strictify'ing, there's no difference between lazy
-- and strict patterns, they call the same workers. There is, however, a
-- difference between strict and lazy target strings.
-- For the new functions, no such wrappers are provided, you have to
-- 'strictify' lazy patterns yourself.
-- caution
--
-- When working with a lazy target string, the relation between the pattern
-- length and the chunk size can play a big rôle.
-- Crossing chunk boundaries is relatively expensive, so when that becomes
-- a frequent occurrence, as may happen when the pattern length is close
-- to or larger than the chunk size, performance is likely to degrade.
-- If it is needed, steps can be taken to ameliorate that effect, but unless
-- entirely separate functions are introduced, that would hurt the
-- performance for the more common case of patterns much shorter than
-- the default chunk size.
-- performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string, so most of the time, you'll want
-- to use the functions of this module, hence this is where the most work
-- has gone. Very short patterns are an exception to this, for those you
-- should consider using a finite automaton
-- ("Data.ByteString.Search.DFA.Array"). That is also often the better
-- choice for searching longer periodic patterns in a lazy ByteString
-- with many matches.
--
-- Operating on a strict target string is mostly faster than on a lazy
-- target string, but the difference is usually small (according to my
-- tests).
--
-- The known exceptions to this rule of thumb are
--
-- [long targets] Then the smaller memory footprint of a lazy target often
-- gives (much) better performance.
--
-- [high number of matches] When there are very many matches, strict target
-- strings are much faster, especially if the pattern is periodic.
--
-- If both conditions hold, either may outweigh the other.
-- complexity
--
-- Preprocessing the pattern is /O/(@patternLength@ + σ) in time and
-- space (σ is the alphabet size, 256 here) for all functions.
-- The time complexity of the searching phase for @matchXY@
-- is /O/(@targetLength@ \/ @patternLength@) in the best case.
-- For non-periodic patterns, the worst case complexity is
-- /O/(@targetLength@), but for periodic patterns, the worst case complexity
-- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore
-- algorithm.
--
-- The searching functions in this module now contain a modification which
-- drastically improves the performance for periodic patterns.
-- I believe that for strict target strings, the worst case is now
-- /O/(@targetLength@) also for periodic patterns and for lazy target strings,
-- my semi-educated guess is
-- /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)).
-- I may be very wrong, though.
--
-- The other functions don't have to deal with possible overlapping
-- patterns, hence the worst case complexity for the processing phase
-- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@)
-- for the breaking functions if the pattern occurs).
-- currying
--
-- These functions can all be usefully curried. Given only a pattern
-- the curried version will compute the supporting lookup tables only
-- once, allowing for efficient re-use. Similarly, the curried
-- 'matchLL' and 'matchLS' will compute the concatenated pattern only
-- once.
-- overflow
--
-- The current code uses @Int@ to keep track of the locations in the
-- target string. If the length of the pattern plus the length of any
-- strict chunk of the target string is greater than
-- @'maxBound' :: 'Int'@ then this will overflow causing an error. We
-- try to detect this and call 'error' before a segfault occurs.
------------------------------------------------------------------------------
-- Wrappers --
------------------------------------------------------------------------------
-- matching
--
-- These functions find the indices of all (possibly overlapping)
-- occurrences of a pattern in a target string.
-- If the pattern is empty, the result is @[0 .. length target]@.
-- If the pattern is much shorter than the target string
-- and the pattern does not occur very near the beginning of the target,
--
-- > not . null $ matchSS pattern target
--
-- is a much more efficient version of 'S.isInfixOf'.
-- | @'matchLS'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- It is a simple wrapper for 'Data.ByteString.Search.indices'.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE matchLS #-}
matchLS :: L.ByteString -- ^ Lazy pattern
-> S.ByteString -- ^ Strict target string
-> [Int] -- ^ Offsets of matches
matchLS pat = search
where
search = strictSearcher True (strictify pat)
-- | @'matchSS'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- It is an alias for 'Data.ByteString.Search.indices'.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE matchSS #-}
matchSS :: S.ByteString -- ^ Strict pattern
-> S.ByteString -- ^ Strict target string
-> [Int] -- ^ Offsets of matches
matchSS pat = search
where
search = strictSearcher True pat
-- | @'matchNOS'@ finds the indices of all non-overlapping occurrences
-- of the pattern in the Strict target string.
{-# INLINE matchNOS #-}
matchNOS :: S.ByteString -- ^ Strict pattern
-> S.ByteString -- ^ Strict target string
-> [Int] -- ^ Offsets of matches
matchNOS pat = search
where
search = strictSearcher False pat
-- replacing
--
-- These functions replace all (non-overlapping) occurrences of a pattern
-- in the target string. If some occurrences overlap, the earliest is
-- replaced and replacing continues at the index after the replaced
-- occurrence, for example
--
-- > replaceAllL \"ana\" \"olog\" \"banana\" == \"bologna\",
-- > replaceAllS \"abacab\" \"u\" \"abacabacabacab\" == \"uacu\",
-- > replaceAllS \"aa\" \"aaa\" \"aaaa\" == \"aaaaaa\".
--
-- Equality of pattern and substitution is not checked, but
--
-- > pat == sub => 'strictify' (replaceAllS pat sub str) == str,
-- > pat == sub => replaceAllL pat sub str == str.
--
-- The result is a lazily generated lazy ByteString, the first chunks will
-- generally be available before the entire target has been scanned.
-- If the pattern is empty, but not the substitution, the result is
-- equivalent to @'cycle' sub@.
{-# INLINE replaceAllS #-}
replaceAllS :: Substitution rep
=> S.ByteString -- ^ Pattern to replace
-> rep -- ^ Substitution string
-> S.ByteString -- ^ Target string
-> L.ByteString -- ^ Lazy result
replaceAllS pat
| S.null pat = \sub -> prependCycle sub . flip LI.chunk LI.Empty
| otherwise =
let repl = strictRepl pat
in \sub -> L.fromChunks . repl (substitution sub)
-- breaking
--
-- Break a string on a pattern. The first component of the result
-- contains the prefix of the string before the first occurrence of the
-- pattern, the second component contains the remainder.
-- The following relations hold:
--
-- > breakSubstringX \"\" str = (\"\", str)
-- > not (pat `isInfixOf` str) == null (snd $ breakSunbstringX pat str)
-- > True == case breakSubstringX pat str of
-- > (x, y) -> not (pat `isInfixOf` x)
-- > && (null y || pat `isPrefixOf` y)
-- | This function has the same semantics as 'S.breakSubstring'
-- but is generally much faster.
{-# INLINE breakSubstringS #-}
breakSubstringS :: S.ByteString -- ^ Pattern to break on
-> S.ByteString -- ^ String to break up
-> (S.ByteString, S.ByteString)
-- ^ Prefix and remainder of broken string
breakSubstringS = strictBreak
breakAfterS :: S.ByteString
-> S.ByteString
-> (S.ByteString, S.ByteString)
breakAfterS pat
| S.null pat = \str -> (S.empty, str)
breakAfterS pat = breaker
where
!patLen = S.length pat
searcher = strictSearcher False pat
breaker str = case searcher str of
[] -> (str, S.empty)
(i:_) -> S.splitAt (i + patLen) str
-- splitting
--
-- These functions implement various splitting strategies.
--
-- If the pattern to split on is empty, all functions return an
-- infinite list of empty ByteStrings.
-- Otherwise, the names are rather self-explanatory.
--
-- For nonempty patterns, the following relations hold:
--
-- > concat (splitKeepXY pat str) == str
-- > concat ('Data.List.intersperse' pat (splitDropX pat str)) == str.
--
-- All fragments except possibly the last in the result of
-- @splitKeepEndX pat@ end with @pat@, none of the fragments contains
-- more than one occurrence of @pat@ or is empty.
--
-- All fragments except possibly the first in the result of
-- @splitKeepFrontX pat@ begin with @pat@, none of the fragments
-- contains more than one occurrence of @patq or is empty.
--
-- > splitDropX pat str == map dropPat (splitKeepFrontX pat str)
-- > where
-- > patLen = length pat
-- > dropPat frag
-- > | pat `isPrefixOf` frag = drop patLen frag
-- > | otherwise = frag
--
-- but @splitDropX@ is a little more efficient than that.
{-# INLINE splitKeepEndS #-}
splitKeepEndS :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ List of fragments
splitKeepEndS = strictSplitKeepEnd
{-# INLINE splitKeepFrontS #-}
splitKeepFrontS :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ List of fragments
splitKeepFrontS = strictSplitKeepFront
{-# INLINE splitDropS #-}
splitDropS :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ List of fragments
splitDropS = strictSplitDrop
------------------------------------------------------------------------------
-- Search Functions --
------------------------------------------------------------------------------
strictSearcher :: Bool -> S.ByteString -> S.ByteString -> [Int]
strictSearcher _ !pat
| S.null pat = enumFromTo 0 . S.length
| S.length pat == 1 = let !w = S.head pat in S.elemIndices w
strictSearcher !overlap pat = searcher
where
{-# INLINE patAt #-}
patAt :: Int -> Word8
patAt !i = unsafeIndex pat i
!patLen = S.length pat
!patEnd = patLen - 1
!maxLen = maxBound - patLen
!occT = occurs pat -- for bad-character-shift
!suffT = suffShifts pat -- for good-suffix-shift
!skip = if overlap then unsafeAt suffT 0 else patLen
-- shift after a complete match
!kept = patLen - skip -- length of known prefix after full match
!pe = patAt patEnd -- last pattern byte for fast comparison
{-# INLINE occ #-}
occ !w = unsafeAt occT (fromIntegral w)
{-# INLINE suff #-}
suff !i = unsafeAt suffT i
searcher str
| maxLen < strLen
= error "Overflow in BoyerMoore.strictSearcher"
| maxDiff < 0 = []
| otherwise = checkEnd patEnd
where
!strLen = S.length str
!strEnd = strLen - 1
!maxDiff = strLen - patLen
{-# INLINE strAt #-}
strAt !i = unsafeIndex str i
-- After a full match, we know how long a prefix of the pattern
-- still matches. Do not re-compare the prefix to prevent O(m*n)
-- behaviour for periodic patterns.
afterMatch !diff !patI =
case strAt (diff + patI) of
!c | c == patAt patI ->
if patI == kept
then diff : let !diff' = diff + skip
in if maxDiff < diff'
then []
else afterMatch diff' patEnd
else afterMatch diff (patI - 1)
| patI == patEnd ->
checkEnd (diff + 2*patEnd + occ c)
| otherwise ->
let {-# INLINE badShift #-}
badShift = patI + occ c
{-# INLINE goodShift #-}
goodShift = suff patI
!diff' = diff + max badShift goodShift
in if maxDiff < diff'
then []
else checkEnd (diff + patEnd)
-- While comparing the last byte of the pattern, the bad-
-- character-shift is always at least as large as the good-
-- suffix-shift. Eliminating the unnecessary memory reads and
-- comparison speeds things up noticeably.
checkEnd !sI -- index in string to compare to last of pattern
| strEnd < sI = []
| otherwise =
case strAt sI of
!c | c == pe -> findMatch (sI - patEnd) (patEnd - 1)
| otherwise -> checkEnd (sI + patEnd + occ c)
-- Once the last byte has matched, we enter the full matcher
-- diff is the offset of the window, patI the index of the
-- pattern byte to compare next.
findMatch !diff !patI =
case strAt (diff + patI) of
!c | c == patAt patI ->
if patI == 0 -- full match, report
then diff : let !diff' = diff + skip
in if maxDiff < diff'
then []
else
if skip == patLen
then
checkEnd (diff' + patEnd)
else
afterMatch diff' patEnd
else findMatch diff (patI - 1)
| otherwise ->
let !diff' = diff + max (patI + occ c) (suff patI)
in if maxDiff < diff'
then []
else checkEnd (diff' + patEnd)
------------------------------------------------------------------------------
-- Breaking Functions --
------------------------------------------------------------------------------
strictBreak :: S.ByteString -> S.ByteString -> (S.ByteString, S.ByteString)
strictBreak pat
| S.null pat = \str -> (S.empty, str)
| otherwise = breaker
where
searcher = strictSearcher False pat
breaker str = case searcher str of
[] -> (str, S.empty)
(i:_) -> S.splitAt i str
------------------------------------------------------------------------------
-- Splitting Functions --
------------------------------------------------------------------------------
strictSplitKeepFront :: S.ByteString -> S.ByteString -> [S.ByteString]
strictSplitKeepFront pat
| S.null pat = const (repeat S.empty)
strictSplitKeepFront pat = splitter
where
!patLen = S.length pat
searcher = strictSearcher False pat
splitter str
| S.null str = []
| otherwise =
case searcher str of
[] -> [str]
(i:_)
| i == 0 -> psplitter str
| otherwise -> S.take i str : psplitter (S.drop i str)
psplitter !str
| S.null str = []
| otherwise =
case searcher (S.drop patLen str) of
[] -> [str]
(i:_) -> S.take (i + patLen) str :
psplitter (S.drop (i + patLen) str)
strictSplitKeepEnd :: S.ByteString -> S.ByteString -> [S.ByteString]
strictSplitKeepEnd pat
| S.null pat = const (repeat S.empty)
strictSplitKeepEnd pat = splitter
where
!patLen = S.length pat
searcher = strictSearcher False pat
splitter str
| S.null str = []
| otherwise =
case searcher str of
[] -> [str]
(i:_) -> S.take (i + patLen) str :
splitter (S.drop (i + patLen) str)
strictSplitDrop :: S.ByteString -> S.ByteString -> [S.ByteString]
strictSplitDrop pat
| S.null pat = const (repeat S.empty)
strictSplitDrop pat = splitter'
where
!patLen = S.length pat
searcher = strictSearcher False pat
splitter' str
| S.null str = []
| otherwise = splitter str
splitter str
| S.null str = [S.empty]
| otherwise =
case searcher str of
[] -> [str]
(i:_) -> S.take i str : splitter (S.drop (i + patLen) str)
------------------------------------------------------------------------------
-- Replacing Functions --
------------------------------------------------------------------------------
-- replacing loop for strict ByteStrings, called only for
-- non-empty patterns and substitutions
strictRepl :: S.ByteString -> ([S.ByteString] -> [S.ByteString])
-> S.ByteString -> [S.ByteString]
strictRepl pat = repl
where
!patLen = S.length pat
searcher = strictSearcher False pat
repl sub = replacer
where
replacer str
| S.null str = []
| otherwise =
case searcher str of
[] -> [str]
(i:_)
| i == 0 -> sub $ replacer (S.drop patLen str)
| otherwise ->
S.take i str : sub (replacer (S.drop (i + patLen) str))
| seereason/stringsearch | Data/ByteString/Search/Internal/BoyerMoore.hs | bsd-3-clause | 22,290 | 0 | 21 | 6,982 | 2,840 | 1,544 | 1,296 | 225 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.NormalOperatorPendingMap
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.NormalOperatorPendingMap
(defNormalOperatorPendingMap) where
import Control.Monad (void, when)
import Data.Char (isDigit)
import Data.List (isPrefixOf)
import Data.Maybe (fromJust, fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T (init, last, pack, snoc, unpack)
import Yi.Buffer hiding (Insert)
import Yi.Editor (getEditorDyn, withCurrentBuffer)
import Yi.Keymap.Keys (Key (KEsc), spec)
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Motion
import Yi.Keymap.Vim.Operator
import Yi.Keymap.Vim.StateUtils
import Yi.Keymap.Vim.StyledRegion (StyledRegion (..), normalizeRegion)
import Yi.Keymap.Vim.TextObject
import Yi.Keymap.Vim.Utils (mkBindingE)
defNormalOperatorPendingMap :: [VimOperator] -> [VimBinding]
defNormalOperatorPendingMap operators = [textObject operators, escBinding]
textObject :: [VimOperator] -> VimBinding
textObject operators = VimBindingE f
where
f evs vs = case vsMode vs of
NormalOperatorPending _ -> WholeMatch $ action evs
_ -> NoMatch
action (Ev evs) = do
currentState <- getEditorDyn
let partial = vsTextObjectAccumulator currentState
opChar = Ev . T.pack $ lastCharForOperator op
op = fromJust $ stringToOperator operators opname
(NormalOperatorPending opname) = vsMode currentState
-- vim treats cw as ce
let evs' = if opname == Op "c" && T.last evs == 'w' &&
(case parseOperand opChar (evr evs) of
JustMove _ -> True
_ -> False)
then T.init evs `T.snoc` 'e'
else evs
-- TODO: fix parseOperand to take EventString as second arg
evr x = T.unpack . _unEv $ partial <> Ev x
operand = parseOperand opChar (evr evs')
case operand of
NoOperand -> do
dropTextObjectAccumulatorE
resetCountE
switchModeE Normal
return Drop
PartialOperand -> do
accumulateTextObjectEventE (Ev evs)
return Continue
_ -> do
count <- getCountE
dropTextObjectAccumulatorE
token <- case operand of
JustTextObject cto@(CountedTextObject n _) -> do
normalizeCountE (Just n)
operatorApplyToTextObjectE op 1 $
changeTextObjectCount (count * n) cto
JustMove (CountedMove n m) -> do
mcount <- getMaybeCountE
normalizeCountE n
region <- withCurrentBuffer $ regionOfMoveB $ CountedMove (maybeMult mcount n) m
operatorApplyToRegionE op 1 region
JustOperator n style -> do
normalizeCountE (Just n)
normalizedCount <- getCountE
region <- withCurrentBuffer $ regionForOperatorLineB normalizedCount style
curPoint <- withCurrentBuffer pointB
token <- operatorApplyToRegionE op 1 region
when (opname == Op "y") $
withCurrentBuffer $ moveTo curPoint
return token
_ -> error "can't happen"
resetCountE
return token
regionForOperatorLineB :: Int -> RegionStyle -> BufferM StyledRegion
regionForOperatorLineB n style = normalizeRegion =<< StyledRegion style <$> savingPointB (do
current <- pointB
if n == 1
then do
firstNonSpaceB
p0 <- pointB
return $! mkRegion p0 current
else do
void $ lineMoveRel (n-2)
moveToEol
rightB
firstNonSpaceB
p1 <- pointB
return $! mkRegion current p1)
escBinding :: VimBinding
escBinding = mkBindingE ReplaceSingleChar Drop (spec KEsc, return (), resetCount . switchMode Normal)
data OperandParseResult
= JustTextObject !CountedTextObject
| JustMove !CountedMove
| JustOperator !Int !RegionStyle -- ^ like dd and d2vd
| PartialOperand
| NoOperand
parseOperand :: EventString -> String -> OperandParseResult
parseOperand opChar s = parseCommand mcount styleMod opChar commandString
where (mcount, styleModString, commandString) = splitCountModifierCommand s
styleMod = case styleModString of
"" -> id
"V" -> const LineWise
"<C-v>" -> const Block
"v" -> \style -> case style of
Exclusive -> Inclusive
_ -> Exclusive
_ -> error "Can't happen"
-- | TODO: should this String be EventString?
parseCommand :: Maybe Int -> (RegionStyle -> RegionStyle)
-> EventString -> String -> OperandParseResult
parseCommand _ _ _ "" = PartialOperand
parseCommand _ _ _ "i" = PartialOperand
parseCommand _ _ _ "a" = PartialOperand
parseCommand _ _ _ "g" = PartialOperand
parseCommand n sm o s | o' == s = JustOperator (fromMaybe 1 n) (sm LineWise)
where o' = T.unpack . _unEv $ o
parseCommand n sm _ "0" =
let m = Move Exclusive False (const moveToSol)
in JustMove (CountedMove n (changeMoveStyle sm m))
parseCommand n sm _ s = case stringToMove . Ev $ T.pack s of
WholeMatch m -> JustMove $ CountedMove n $ changeMoveStyle sm m
PartialMatch -> PartialOperand
NoMatch -> case stringToTextObject s of
WholeMatch to -> JustTextObject $ CountedTextObject (fromMaybe 1 n)
$ changeTextObjectStyle sm to
_ -> NoOperand
-- TODO: setup doctests
-- Parse event string that can go after operator
-- w -> (Nothing, "", "w")
-- 2w -> (Just 2, "", "w")
-- V2w -> (Just 2, "V", "w")
-- v2V3<C-v>w -> (Just 6, "<C-v>", "w")
-- vvvvvvvvvvvvvw -> (Nothing, "v", "w")
-- 0 -> (Nothing, "", "0")
-- V0 -> (Nothing, "V", "0")
splitCountModifierCommand :: String -> (Maybe Int, String, String)
splitCountModifierCommand = go "" Nothing [""]
where go "" Nothing mods "0" = (Nothing, head mods, "0")
go ds count mods (h:t) | isDigit h = go (ds <> [h]) count mods t
go ds@(_:_) count mods s@(h:_) | not (isDigit h) = go [] (maybeMult count (Just (read ds))) mods s
go [] count mods (h:t) | h `elem` ['v', 'V'] = go [] count ([h]:mods) t
go [] count mods s | "<C-v>" `isPrefixOf` s = go [] count ("<C-v>":mods) (drop 5 s)
go [] count mods s = (count, head mods, s)
go ds count mods [] = (maybeMult count (Just (read ds)), head mods, [])
go (_:_) _ _ (_:_) = error "Can't happen because isDigit and not isDigit cover every case"
| yi-editor/yi | yi-keymap-vim/src/Yi/Keymap/Vim/NormalOperatorPendingMap.hs | gpl-2.0 | 7,294 | 0 | 25 | 2,456 | 1,914 | 972 | 942 | 145 | 9 |
{-# LANGUAGE DataKinds, TypeOperators, OverloadedStrings #-}
module CoinBias20 where
import Prelude (print, length, IO)
import Language.Hakaru.Syntax.Prelude
import Language.Hakaru.Disintegrate
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Types.DataKind
import Language.Hakaru.Types.Sing
type Model a b = TrivialABT Term '[] ('HMeasure (HPair a b))
type Cond a b = TrivialABT Term '[] (a ':-> 'HMeasure b)
coinBias :: Model (HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
HBool)))))))))))))))))))
'HProb
coinBias =
beta (prob_ 2) (prob_ 5) >>= \bias ->
bern bias >>= \tossResult0 ->
bern bias >>= \tossResult1 ->
bern bias >>= \tossResult2 ->
bern bias >>= \tossResult3 ->
bern bias >>= \tossResult4 ->
bern bias >>= \tossResult5 ->
bern bias >>= \tossResult6 ->
bern bias >>= \tossResult7 ->
bern bias >>= \tossResult8 ->
bern bias >>= \tossResult9 ->
bern bias >>= \tossResult10 ->
bern bias >>= \tossResult11 ->
bern bias >>= \tossResult12 ->
bern bias >>= \tossResult13 ->
bern bias >>= \tossResult14 ->
bern bias >>= \tossResult15 ->
bern bias >>= \tossResult16 ->
bern bias >>= \tossResult17 ->
bern bias >>= \tossResult18 ->
bern bias >>= \tossResult19 ->
dirac (pair (pair tossResult0
(pair tossResult1
(pair tossResult2
(pair tossResult3
(pair tossResult4
(pair tossResult5
(pair tossResult6
(pair tossResult7
(pair tossResult8
(pair tossResult9
(pair tossResult10
(pair tossResult11
(pair tossResult12
(pair tossResult13
(pair tossResult14
(pair tossResult15
(pair tossResult16
(pair tossResult17
(pair tossResult18
tossResult19)))))))))))))))))))
bias)
main :: IO ()
main = print (length (disintegrate coinBias))
| zaxtax/hakaru | haskell/Tests/Unroll/CoinBias20.hs | bsd-3-clause | 3,050 | 0 | 87 | 1,436 | 756 | 393 | 363 | 77 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
-----------------------------------------------------------------------------
--
-- GHC Interactive User Interface
--
-- (c) The GHC Team 2005-2006
--
-----------------------------------------------------------------------------
module GHCi.UI (
interactiveUI,
GhciSettings(..),
defaultGhciSettings,
ghciCommands,
ghciWelcomeMsg
) where
#include "HsVersions.h"
-- GHCi
import qualified GHCi.UI.Monad as GhciMonad ( args, runStmt, runDecls )
import GHCi.UI.Monad hiding ( args, runStmt, runDecls )
import GHCi.UI.Tags
import GHCi.UI.Info
import Debugger
-- The GHC interface
import GHCi
import GHCi.RemoteTypes
import GHCi.BreakArray
import DynFlags
import ErrUtils
import GhcMonad ( modifySession )
import qualified GHC
import GHC ( LoadHowMuch(..), Target(..), TargetId(..), InteractiveImport(..),
TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
getModuleGraph, handleSourceError )
import HsImpExp
import HsSyn
import HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
setInteractivePrintName, hsc_dflags, msObjFilePath )
import Module
import Name
import Packages ( trusted, getPackageDetails, listVisibleModuleNames, pprFlag )
import PprTyThing
import PrelNames
import RdrName ( RdrName, getGRE_NameQualifier_maybes, getRdrName )
import SrcLoc
import qualified Lexer
import StringBuffer
import Outputable hiding ( printForUser, printForUserPartWay, bold )
-- Other random utilities
import BasicTypes hiding ( isTopLevel )
import Config
import Digraph
import Encoding
import FastString
import Linker
import Maybes ( orElse, expectJust )
import NameSet
import Panic hiding ( showException )
import Util
import qualified GHC.LanguageExtensions as LangExt
-- Haskell Libraries
import System.Console.Haskeline as Haskeline
import Control.Applicative hiding (empty)
import Control.DeepSeq (deepseq)
import Control.Monad as Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Function
import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
partition, sort, sortBy )
import Data.Maybe
import qualified Data.Map as M
import Exception hiding (catch)
import Foreign
import GHC.Stack hiding (SrcLoc(..))
import System.Directory
import System.Environment
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.IO
import System.IO.Error
import System.IO.Unsafe ( unsafePerformIO )
import System.Process
import Text.Printf
import Text.Read ( readMaybe )
import Text.Read.Lex (isSymbolChar)
#ifndef mingw32_HOST_OS
import System.Posix hiding ( getEnv )
#else
import qualified System.Win32
#endif
import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
import GHC.IO.Handle ( hFlushAll )
import GHC.TopHandler ( topHandler )
-----------------------------------------------------------------------------
data GhciSettings = GhciSettings {
availableCommands :: [Command],
shortHelpText :: String,
fullHelpText :: String,
defPrompt :: String,
defPrompt2 :: String
}
defaultGhciSettings :: GhciSettings
defaultGhciSettings =
GhciSettings {
availableCommands = ghciCommands,
shortHelpText = defShortHelpText,
defPrompt = default_prompt,
defPrompt2 = default_prompt2,
fullHelpText = defFullHelpText
}
ghciWelcomeMsg :: String
ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
": http://www.haskell.org/ghc/ :? for help"
ghciCommands :: [Command]
ghciCommands = map mkCmd [
-- Hugs users are accustomed to :e, so make sure it doesn't overlap
("?", keepGoing help, noCompletion),
("add", keepGoingPaths addModule, completeFilename),
("abandon", keepGoing abandonCmd, noCompletion),
("break", keepGoing breakCmd, completeIdentifier),
("back", keepGoing backCmd, noCompletion),
("browse", keepGoing' (browseCmd False), completeModule),
("browse!", keepGoing' (browseCmd True), completeModule),
("cd", keepGoing' changeDirectory, completeFilename),
("check", keepGoing' checkModule, completeHomeModule),
("continue", keepGoing continueCmd, noCompletion),
("cmd", keepGoing cmdCmd, completeExpression),
("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
("def", keepGoing (defineMacro False), completeExpression),
("def!", keepGoing (defineMacro True), completeExpression),
("delete", keepGoing deleteCmd, noCompletion),
("edit", keepGoing' editFile, completeFilename),
("etags", keepGoing createETagsFileCmd, completeFilename),
("force", keepGoing forceCmd, completeExpression),
("forward", keepGoing forwardCmd, noCompletion),
("help", keepGoing help, noCompletion),
("history", keepGoing historyCmd, noCompletion),
("info", keepGoing' (info False), completeIdentifier),
("info!", keepGoing' (info True), completeIdentifier),
("issafe", keepGoing' isSafeCmd, completeModule),
("kind", keepGoing' (kindOfType False), completeIdentifier),
("kind!", keepGoing' (kindOfType True), completeIdentifier),
("load", keepGoingPaths (loadModule_ False), completeHomeModuleOrFile),
("load!", keepGoingPaths (loadModule_ True), completeHomeModuleOrFile),
("list", keepGoing' listCmd, noCompletion),
("module", keepGoing moduleCmd, completeSetModule),
("main", keepGoing runMain, completeFilename),
("print", keepGoing printCmd, completeExpression),
("quit", quit, noCompletion),
("reload", keepGoing' (reloadModule False), noCompletion),
("reload!", keepGoing' (reloadModule True), noCompletion),
("run", keepGoing runRun, completeFilename),
("script", keepGoing' scriptCmd, completeFilename),
("set", keepGoing setCmd, completeSetOptions),
("seti", keepGoing setiCmd, completeSeti),
("show", keepGoing showCmd, completeShowOptions),
("showi", keepGoing showiCmd, completeShowiOptions),
("sprint", keepGoing sprintCmd, completeExpression),
("step", keepGoing stepCmd, completeIdentifier),
("steplocal", keepGoing stepLocalCmd, completeIdentifier),
("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
("type", keepGoing' typeOfExpr, completeExpression),
("trace", keepGoing traceCmd, completeExpression),
("undef", keepGoing undefineMacro, completeMacro),
("unset", keepGoing unsetOptions, completeSetOptions),
("where", keepGoing whereCmd, noCompletion)
] ++ map mkCmdHidden [ -- hidden commands
("all-types", keepGoing' allTypesCmd),
("complete", keepGoing completeCmd),
("loc-at", keepGoing' locAtCmd),
("type-at", keepGoing' typeAtCmd),
("uses", keepGoing' usesCmd)
]
where
mkCmd (n,a,c) = Command { cmdName = n
, cmdAction = a
, cmdHidden = False
, cmdCompletionFunc = c
}
mkCmdHidden (n,a) = Command { cmdName = n
, cmdAction = a
, cmdHidden = True
, cmdCompletionFunc = noCompletion
}
-- We initialize readline (in the interactiveUI function) to use
-- word_break_chars as the default set of completion word break characters.
-- This can be overridden for a particular command (for example, filename
-- expansion shouldn't consider '/' to be a word break) by setting the third
-- entry in the Command tuple above.
--
-- NOTE: in order for us to override the default correctly, any custom entry
-- must be a SUBSET of word_break_chars.
word_break_chars :: String
word_break_chars = spaces ++ specials ++ symbols
symbols, specials, spaces :: String
symbols = "!#$%&*+/<=>?@\\^|-~"
specials = "(),;[]`{}"
spaces = " \t\n"
flagWordBreakChars :: String
flagWordBreakChars = " \t\n"
keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
keepGoing a str = keepGoing' (lift . a) str
keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
keepGoing' a str = a str >> return False
keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
keepGoingPaths a str
= do case toArgs str of
Left err -> liftIO $ hPutStrLn stderr err
Right args -> a args
return False
defShortHelpText :: String
defShortHelpText = "use :? for help.\n"
defFullHelpText :: String
defFullHelpText =
" Commands available from the prompt:\n" ++
"\n" ++
" <statement> evaluate/run <statement>\n" ++
" : repeat last command\n" ++
" :{\\n ..lines.. \\n:}\\n multiline command\n" ++
" :add [*]<module> ... add module(s) to the current target set\n" ++
" :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
" (!: more details; *: all top-level names)\n" ++
" :cd <dir> change directory to <dir>\n" ++
" :cmd <expr> run the commands returned by <expr>::IO String\n" ++
" :complete <dom> [<rng>] <s> list completions for partial input string\n" ++
" :ctags[!] [<file>] create tags file <file> for Vi (default: \"tags\")\n" ++
" (!: use regex instead of line number)\n" ++
" :def <cmd> <expr> define command :<cmd> (later defined command has\n" ++
" precedence, ::<cmd> is always a builtin command)\n" ++
" :edit <file> edit file\n" ++
" :edit edit last module\n" ++
" :etags [<file>] create tags file <file> for Emacs (default: \"TAGS\")\n" ++
" :help, :? display this list of commands\n" ++
" :info[!] [<name> ...] display information about the given names\n" ++
" (!: do not filter instances)\n" ++
" :issafe [<mod>] display safe haskell information of module <mod>\n" ++
" :kind[!] <type> show the kind of <type>\n" ++
" (!: also print the normalised type)\n" ++
" :load[!] [*]<module> ... load module(s) and their dependents\n" ++
" (!: defer type errors)\n" ++
" :main [<arguments> ...] run the main function with the given arguments\n" ++
" :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
" :quit exit GHCi\n" ++
" :reload[!] reload the current module set\n" ++
" (!: defer type errors)\n" ++
" :run function [<arguments> ...] run the function with the given arguments\n" ++
" :script <file> run the script <file>\n" ++
" :type <expr> show the type of <expr>\n" ++
" :undef <cmd> undefine user-defined command :<cmd>\n" ++
" :!<command> run the shell command <command>\n" ++
"\n" ++
" -- Commands for debugging:\n" ++
"\n" ++
" :abandon at a breakpoint, abandon current computation\n" ++
" :back [<n>] go back in the history N steps (after :trace)\n" ++
" :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
" :break <name> set a breakpoint on the specified function\n" ++
" :continue resume after a breakpoint\n" ++
" :delete <number> delete the specified breakpoint\n" ++
" :delete * delete all breakpoints\n" ++
" :force <expr> print <expr>, forcing unevaluated parts\n" ++
" :forward [<n>] go forward in the history N step s(after :back)\n" ++
" :history [<n>] after :trace, show the execution history\n" ++
" :list show the source code around current breakpoint\n" ++
" :list <identifier> show the source code for <identifier>\n" ++
" :list [<module>] <line> show the source code around line number <line>\n" ++
" :print [<name> ...] show a value without forcing its computation\n" ++
" :sprint [<name> ...] simplified version of :print\n" ++
" :step single-step after stopping at a breakpoint\n"++
" :step <expr> single-step into <expr>\n"++
" :steplocal single-step within the current top-level binding\n"++
" :stepmodule single-step restricted to the current module\n"++
" :trace trace after stopping at a breakpoint\n"++
" :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
"\n" ++
" -- Commands for changing settings:\n" ++
"\n" ++
" :set <option> ... set options\n" ++
" :seti <option> ... set options for interactive evaluation only\n" ++
" :set args <arg> ... set the arguments returned by System.getArgs\n" ++
" :set prog <progname> set the value returned by System.getProgName\n" ++
" :set prompt <prompt> set the prompt used in GHCi\n" ++
" :set prompt2 <prompt> set the continuation prompt used in GHCi\n" ++
" :set editor <cmd> set the command used for :edit\n" ++
" :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
" :unset <option> ... unset options\n" ++
"\n" ++
" Options for ':set' and ':unset':\n" ++
"\n" ++
" +m allow multiline commands\n" ++
" +r revert top-level expressions after each evaluation\n" ++
" +s print timing/memory stats after each evaluation\n" ++
" +t print type after evaluation\n" ++
" +c collect type/location info after loading modules\n" ++
" -<flags> most GHC command line flags can also be set here\n" ++
" (eg. -v2, -XFlexibleInstances, etc.)\n" ++
" for GHCi-specific flags, see User's Guide,\n"++
" Flag reference, Interactive-mode options\n" ++
"\n" ++
" -- Commands for displaying information:\n" ++
"\n" ++
" :show bindings show the current bindings made at the prompt\n" ++
" :show breaks show the active breakpoints\n" ++
" :show context show the breakpoint context\n" ++
" :show imports show the current imports\n" ++
" :show linker show current linker state\n" ++
" :show modules show the currently loaded modules\n" ++
" :show packages show the currently active package flags\n" ++
" :show paths show the currently active search paths\n" ++
" :show language show the currently active language flags\n" ++
" :show <setting> show value of <setting>, which is one of\n" ++
" [args, prog, prompt, editor, stop]\n" ++
" :showi language show language flags for interactive evaluation\n" ++
"\n"
findEditor :: IO String
findEditor = do
getEnv "EDITOR"
`catchIO` \_ -> do
#if mingw32_HOST_OS
win <- System.Win32.getWindowsDirectory
return (win </> "notepad.exe")
#else
return ""
#endif
default_progname, default_prompt, default_prompt2, default_stop :: String
default_progname = "<interactive>"
default_prompt = "%s> "
default_prompt2 = "%s| "
default_stop = ""
default_args :: [String]
default_args = []
interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
-> Ghc ()
interactiveUI config srcs maybe_exprs = do
-- HACK! If we happen to get into an infinite loop (eg the user
-- types 'let x=x in x' at the prompt), then the thread will block
-- on a blackhole, and become unreachable during GC. The GC will
-- detect that it is unreachable and send it the NonTermination
-- exception. However, since the thread is unreachable, everything
-- it refers to might be finalized, including the standard Handles.
-- This sounds like a bug, but we don't have a good solution right
-- now.
_ <- liftIO $ newStablePtr stdin
_ <- liftIO $ newStablePtr stdout
_ <- liftIO $ newStablePtr stderr
-- Initialise buffering for the *interpreted* I/O system
(nobuffering, flush) <- initInterpBuffering
-- The initial set of DynFlags used for interactive evaluation is the same
-- as the global DynFlags, plus -XExtendedDefaultRules and
-- -XNoMonomorphismRestriction.
dflags <- getDynFlags
let dflags' = (`xopt_set` LangExt.ExtendedDefaultRules)
. (`xopt_unset` LangExt.MonomorphismRestriction)
$ dflags
GHC.setInteractiveDynFlags dflags'
lastErrLocationsRef <- liftIO $ newIORef []
progDynFlags <- GHC.getProgramDynFlags
_ <- GHC.setProgramDynFlags $
progDynFlags { log_action = ghciLogAction lastErrLocationsRef }
when (isNothing maybe_exprs) $ do
-- Only for GHCi (not runghc and ghc -e):
-- Turn buffering off for the compiled program's stdout/stderr
turnOffBuffering_ nobuffering
-- Turn buffering off for GHCi's stdout
liftIO $ hFlush stdout
liftIO $ hSetBuffering stdout NoBuffering
-- We don't want the cmd line to buffer any input that might be
-- intended for the program, so unbuffer stdin.
liftIO $ hSetBuffering stdin NoBuffering
liftIO $ hSetBuffering stderr NoBuffering
#if defined(mingw32_HOST_OS)
-- On Unix, stdin will use the locale encoding. The IO library
-- doesn't do this on Windows (yet), so for now we use UTF-8,
-- for consistency with GHC 6.10 and to make the tests work.
liftIO $ hSetEncoding stdin utf8
#endif
default_editor <- liftIO $ findEditor
eval_wrapper <- mkEvalWrapper default_progname default_args
startGHCi (runGHCi srcs maybe_exprs)
GHCiState{ progname = default_progname,
args = default_args,
evalWrapper = eval_wrapper,
prompt = defPrompt config,
prompt2 = defPrompt2 config,
stop = default_stop,
editor = default_editor,
options = [],
-- We initialize line number as 0, not 1, because we use
-- current line number while reporting errors which is
-- incremented after reading a line.
line_number = 0,
break_ctr = 0,
breaks = [],
tickarrays = emptyModuleEnv,
ghci_commands = availableCommands config,
ghci_macros = [],
last_command = Nothing,
cmdqueue = [],
remembered_ctx = [],
transient_ctx = [],
ghc_e = isJust maybe_exprs,
short_help = shortHelpText config,
long_help = fullHelpText config,
lastErrorLocations = lastErrLocationsRef,
mod_infos = M.empty,
flushStdHandles = flush,
noBuffering = nobuffering
}
return ()
resetLastErrorLocations :: GHCi ()
resetLastErrorLocations = do
st <- getGHCiState
liftIO $ writeIORef (lastErrorLocations st) []
ghciLogAction :: IORef [(FastString, Int)] -> LogAction
ghciLogAction lastErrLocations dflags flag severity srcSpan style msg = do
defaultLogAction dflags flag severity srcSpan style msg
case severity of
SevError -> case srcSpan of
RealSrcSpan rsp -> modifyIORef lastErrLocations
(++ [(srcLocFile (realSrcSpanStart rsp), srcLocLine (realSrcSpanStart rsp))])
_ -> return ()
_ -> return ()
withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
withGhcAppData right left = do
either_dir <- tryIO (getAppUserDataDirectory "ghc")
case either_dir of
Right dir ->
do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
right dir
_ -> left
runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi paths maybe_exprs = do
dflags <- getDynFlags
let
ignore_dot_ghci = gopt Opt_IgnoreDotGhci dflags
current_dir = return (Just ".ghci")
app_user_dir = liftIO $ withGhcAppData
(\dir -> return (Just (dir </> "ghci.conf")))
(return Nothing)
home_dir = do
either_dir <- liftIO $ tryIO (getEnv "HOME")
case either_dir of
Right home -> return (Just (home </> ".ghci"))
_ -> return Nothing
canonicalizePath' :: FilePath -> IO (Maybe FilePath)
canonicalizePath' fp = liftM Just (canonicalizePath fp)
`catchIO` \_ -> return Nothing
sourceConfigFile :: FilePath -> GHCi ()
sourceConfigFile file = do
exists <- liftIO $ doesFileExist file
when exists $ do
either_hdl <- liftIO $ tryIO (openFile file ReadMode)
case either_hdl of
Left _e -> return ()
-- NOTE: this assumes that runInputT won't affect the terminal;
-- can we assume this will always be the case?
-- This would be a good place for runFileInputT.
Right hdl ->
do runInputTWithPrefs defaultPrefs defaultSettings $
runCommands $ fileLoop hdl
liftIO (hClose hdl `catchIO` \_ -> return ())
-- Don't print a message if this is really ghc -e (#11478).
-- Also, let the user silence the message with -v0
-- (the default verbosity in GHCi is 1).
when (isNothing maybe_exprs && verbosity dflags > 0) $
liftIO $ putStrLn ("Loaded GHCi configuration from " ++ file)
--
setGHCContextFromGHCiState
dot_cfgs <- if ignore_dot_ghci then return [] else do
dot_files <- catMaybes <$> sequence [ current_dir, app_user_dir, home_dir ]
liftIO $ filterM checkFileAndDirPerms dot_files
mdot_cfgs <- liftIO $ mapM canonicalizePath' dot_cfgs
let arg_cfgs = reverse $ ghciScripts dflags
-- -ghci-script are collected in reverse order
-- We don't require that a script explicitly added by -ghci-script
-- is owned by the current user. (#6017)
mapM_ sourceConfigFile $ nub $ (catMaybes mdot_cfgs) ++ arg_cfgs
-- nub, because we don't want to read .ghci twice if the CWD is $HOME.
-- Perform a :load for files given on the GHCi command line
-- When in -e mode, if the load fails then we want to stop
-- immediately rather than going on to evaluate the expression.
when (not (null paths)) $ do
ok <- ghciHandle (\e -> do showException e; return Failed) $
-- TODO: this is a hack.
runInputTWithPrefs defaultPrefs defaultSettings $
loadModule paths
when (isJust maybe_exprs && failed ok) $
liftIO (exitWith (ExitFailure 1))
installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
-- if verbosity is greater than 0, or we are connected to a
-- terminal, display the prompt in the interactive loop.
is_tty <- liftIO (hIsTerminalDevice stdin)
let show_prompt = verbosity dflags > 0 || is_tty
-- reset line number
modifyGHCiState $ \st -> st{line_number=0}
case maybe_exprs of
Nothing ->
do
-- enter the interactive loop
runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
Just exprs -> do
-- just evaluate the expression we were given
enqueueCommands exprs
let hdle e = do st <- getGHCiState
-- flush the interpreter's stdout/stderr on exit (#3890)
flushInterpBuffers
-- Jump through some hoops to get the
-- current progname in the exception text:
-- <progname>: <exception>
liftIO $ withProgName (progname st)
$ topHandler e
-- this used to be topHandlerFastExit, see #2228
runInputTWithPrefs defaultPrefs defaultSettings $ do
-- make `ghc -e` exit nonzero on invalid input, see Trac #7962
_ <- runCommands' hdle
(Just $ hdle (toException $ ExitFailure 1) >> return ())
(return Nothing)
return ()
-- and finally, exit
liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput f = do
dflags <- getDynFlags
histFile <- if gopt Opt_GhciHistory dflags
then liftIO $ withGhcAppData (\dir -> return (Just (dir </> "ghci_history")))
(return Nothing)
else return Nothing
runInputT
(setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
f
-- | How to get the next input line from the user
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine show_prompt is_tty
| is_tty = do
prmpt <- if show_prompt then lift mkPrompt else return ""
r <- getInputLine prmpt
incrementLineNo
return r
| otherwise = do
when show_prompt $ lift mkPrompt >>= liftIO . putStr
fileLoop stdin
-- NOTE: We only read .ghci files if they are owned by the current user,
-- and aren't world writable (files owned by root are ok, see #9324).
-- Otherwise, we could be accidentally running code planted by
-- a malicious third party.
-- Furthermore, We only read ./.ghci if . is owned by the current user
-- and isn't writable by anyone else. I think this is sufficient: we
-- don't need to check .. and ../.. etc. because "." always refers to
-- the same directory while a process is running.
checkFileAndDirPerms :: FilePath -> IO Bool
checkFileAndDirPerms file = do
file_ok <- checkPerms file
-- Do not check dir perms when .ghci doesn't exist, otherwise GHCi will
-- print some confusing and useless warnings in some cases (e.g. in
-- travis). Note that we can't add a test for this, as all ghci tests should
-- run with -ignore-dot-ghci, which means we never get here.
if file_ok then checkPerms (getDirectory file) else return False
where
getDirectory f = case takeDirectory f of
"" -> "."
d -> d
checkPerms :: FilePath -> IO Bool
#ifdef mingw32_HOST_OS
checkPerms _ = return True
#else
checkPerms file =
handleIO (\_ -> return False) $ do
st <- getFileStatus file
me <- getRealUserID
let mode = System.Posix.fileMode st
ok = (fileOwner st == me || fileOwner st == 0) &&
groupWriteMode /= mode `intersectFileModes` groupWriteMode &&
otherWriteMode /= mode `intersectFileModes` otherWriteMode
unless ok $
-- #8248: Improving warning to include a possible fix.
putStrLn $ "*** WARNING: " ++ file ++
" is writable by someone else, IGNORING!" ++
"\nSuggested fix: execute 'chmod go-w " ++ file ++ "'"
return ok
#endif
incrementLineNo :: InputT GHCi ()
incrementLineNo = modifyGHCiState incLineNo
where
incLineNo st = st { line_number = line_number st + 1 }
fileLoop :: Handle -> InputT GHCi (Maybe String)
fileLoop hdl = do
l <- liftIO $ tryIO $ hGetLine hdl
case l of
Left e | isEOFError e -> return Nothing
| -- as we share stdin with the program, the program
-- might have already closed it, so we might get a
-- handle-closed exception. We therefore catch that
-- too.
isIllegalOperation e -> return Nothing
| InvalidArgument <- etype -> return Nothing
| otherwise -> liftIO $ ioError e
where etype = ioeGetErrorType e
-- treat InvalidArgument in the same way as EOF:
-- this can happen if the user closed stdin, or
-- perhaps did getContents which closes stdin at
-- EOF.
Right l' -> do
incrementLineNo
return (Just l')
mkPrompt :: GHCi String
mkPrompt = do
st <- getGHCiState
imports <- GHC.getContext
resumes <- GHC.getResumeContext
context_bit <-
case resumes of
[] -> return empty
r:_ -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (brackets (ppr (GHC.resumeSpan r)) <> space)
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (brackets (ppr (negate ix) <> char ':'
<+> ppr pan) <> space)
let
dots | _:rs <- resumes, not (null rs) = text "... "
| otherwise = empty
rev_imports = reverse imports -- rightmost are the most recent
modules_bit =
hsep [ char '*' <> ppr m | IIModule m <- rev_imports ] <+>
hsep (map ppr [ myIdeclName d | IIDecl d <- rev_imports ])
-- use the 'as' name if there is one
myIdeclName d | Just m <- ideclAs d = m
| otherwise = unLoc (ideclName d)
deflt_prompt = dots <> context_bit <> modules_bit
f ('%':'l':xs) = ppr (1 + line_number st) <> f xs
f ('%':'s':xs) = deflt_prompt <> f xs
f ('%':'%':xs) = char '%' <> f xs
f (x:xs) = char x <> f xs
f [] = empty
dflags <- getDynFlags
return (showSDoc dflags (f (prompt st)))
queryQueue :: GHCi (Maybe String)
queryQueue = do
st <- getGHCiState
case cmdqueue st of
[] -> return Nothing
c:cs -> do setGHCiState st{ cmdqueue = cs }
return (Just c)
-- Reconfigurable pretty-printing Ticket #5461
installInteractivePrint :: Maybe String -> Bool -> GHCi ()
installInteractivePrint Nothing _ = return ()
installInteractivePrint (Just ipFun) exprmode = do
ok <- trySuccess $ do
(name:_) <- GHC.parseName ipFun
modifySession (\he -> let new_ic = setInteractivePrintName (hsc_IC he) name
in he{hsc_IC = new_ic})
return Succeeded
when (failed ok && exprmode) $ liftIO (exitWith (ExitFailure 1))
-- | The main read-eval-print loop
runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands gCmd = runCommands' handler Nothing gCmd >> return ()
runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
-> Maybe (GHCi ()) -- ^ Source error handler
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
-- We want to return () here, but have to return (Maybe Bool)
-- because gmask is not polymorphic enough: we want to use
-- unmask at two different types.
runCommands' eh sourceErrorHandler gCmd = gmask $ \unmask -> do
b <- ghandle (\e -> case fromException e of
Just UserInterrupt -> return $ Just False
_ -> case fromException e of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other ->
liftIO (Exception.throwIO e))
(unmask $ runOneCommand eh gCmd)
case b of
Nothing -> return Nothing
Just success -> do
unless success $ maybe (return ()) lift sourceErrorHandler
unmask $ runCommands' eh sourceErrorHandler gCmd
-- | Evaluate a single line of user input (either :<command> or Haskell code).
-- A result of Nothing means there was no more input to process.
-- Otherwise the result is Just b where b is True if the command succeeded;
-- this is relevant only to ghc -e, which will exit with status 1
-- if the commmand was unsuccessful. GHCi will continue in either case.
runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runOneCommand eh gCmd = do
-- run a previously queued command if there is one, otherwise get new
-- input from user
mb_cmd0 <- noSpace (lift queryQueue)
mb_cmd1 <- maybe (noSpace gCmd) (return . Just) mb_cmd0
case mb_cmd1 of
Nothing -> return Nothing
Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
handleSourceError printErrorAndFail
(doCommand c)
-- source error's are handled by runStmt
-- is the handler necessary here?
where
printErrorAndFail err = do
GHC.printException err
return $ Just False -- Exit ghc -e, but not GHCi
noSpace q = q >>= maybe (return Nothing)
(\c -> case removeSpaces c of
"" -> noSpace q
":{" -> multiLineCmd q
_ -> return (Just c) )
multiLineCmd q = do
st <- getGHCiState
let p = prompt st
setGHCiState st{ prompt = prompt2 st }
mb_cmd <- collectCommand q "" `GHC.gfinally`
modifyGHCiState (\st' -> st' { prompt = p })
return mb_cmd
-- we can't use removeSpaces for the sublines here, so
-- multiline commands are somewhat more brittle against
-- fileformat errors (such as \r in dos input on unix),
-- we get rid of any extra spaces for the ":}" test;
-- we also avoid silent failure if ":}" is not found;
-- and since there is no (?) valid occurrence of \r (as
-- opposed to its String representation, "\r") inside a
-- ghci command, we replace any such with ' ' (argh:-(
collectCommand q c = q >>=
maybe (liftIO (ioError collectError))
(\l->if removeSpaces l == ":}"
then return (Just c)
else collectCommand q (c ++ "\n" ++ map normSpace l))
where normSpace '\r' = ' '
normSpace x = x
-- SDM (2007-11-07): is userError the one to use here?
collectError = userError "unterminated multiline command :{ .. :}"
-- | Handle a line of input
doCommand :: String -> InputT GHCi (Maybe Bool)
-- command
doCommand stmt | (':' : cmd) <- removeSpaces stmt = do
result <- specialCommand cmd
case result of
True -> return Nothing
_ -> return $ Just True
-- haskell
doCommand stmt = do
-- if 'stmt' was entered via ':{' it will contain '\n's
let stmt_nl_cnt = length [ () | '\n' <- stmt ]
ml <- lift $ isOptionSet Multiline
if ml && stmt_nl_cnt == 0 -- don't trigger automatic multi-line mode for ':{'-multiline input
then do
fst_line_num <- line_number <$> getGHCiState
mb_stmt <- checkInputForLayout stmt gCmd
case mb_stmt of
Nothing -> return $ Just True
Just ml_stmt -> do
-- temporarily compensate line-number for multi-line input
result <- timeIt runAllocs $ lift $
runStmtWithLineNum fst_line_num ml_stmt GHC.RunToCompletion
return $ Just (runSuccess result)
else do -- single line input and :{ - multiline input
last_line_num <- line_number <$> getGHCiState
-- reconstruct first line num from last line num and stmt
let fst_line_num | stmt_nl_cnt > 0 = last_line_num - (stmt_nl_cnt2 + 1)
| otherwise = last_line_num -- single line input
stmt_nl_cnt2 = length [ () | '\n' <- stmt' ]
stmt' = dropLeadingWhiteLines stmt -- runStmt doesn't like leading empty lines
-- temporarily compensate line-number for multi-line input
result <- timeIt runAllocs $ lift $
runStmtWithLineNum fst_line_num stmt' GHC.RunToCompletion
return $ Just (runSuccess result)
-- runStmt wrapper for temporarily overridden line-number
runStmtWithLineNum :: Int -> String -> SingleStep
-> GHCi (Maybe GHC.ExecResult)
runStmtWithLineNum lnum stmt step = do
st0 <- getGHCiState
setGHCiState st0 { line_number = lnum }
result <- runStmt stmt step
-- restore original line_number
getGHCiState >>= \st -> setGHCiState st { line_number = line_number st0 }
return result
-- note: this is subtly different from 'unlines . dropWhile (all isSpace) . lines'
dropLeadingWhiteLines s | (l0,'\n':r) <- break (=='\n') s
, all isSpace l0 = dropLeadingWhiteLines r
| otherwise = s
-- #4316
-- lex the input. If there is an unclosed layout context, request input
checkInputForLayout :: String -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe String)
checkInputForLayout stmt getStmt = do
dflags' <- getDynFlags
let dflags = xopt_set dflags' LangExt.AlternativeLayoutRule
st0 <- getGHCiState
let buf' = stringToStringBuffer stmt
loc = mkRealSrcLoc (fsLit (progname st0)) (line_number st0) 1
pstate = Lexer.mkPState dflags buf' loc
case Lexer.unP goToEnd pstate of
(Lexer.POk _ False) -> return $ Just stmt
_other -> do
st1 <- getGHCiState
let p = prompt st1
setGHCiState st1{ prompt = prompt2 st1 }
mb_stmt <- ghciHandle (\ex -> case fromException ex of
Just UserInterrupt -> return Nothing
_ -> case fromException ex of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other -> liftIO (Exception.throwIO ex))
getStmt
modifyGHCiState (\st' -> st' { prompt = p })
-- the recursive call does not recycle parser state
-- as we use a new string buffer
case mb_stmt of
Nothing -> return Nothing
Just str -> if str == ""
then return $ Just stmt
else do
checkInputForLayout (stmt++"\n"++str) getStmt
where goToEnd = do
eof <- Lexer.nextIsEOF
if eof
then Lexer.activeContext
else Lexer.lexer False return >> goToEnd
enqueueCommands :: [String] -> GHCi ()
enqueueCommands cmds = do
-- make sure we force any exceptions in the commands while we're
-- still inside the exception handler, otherwise bad things will
-- happen (see #10501)
cmds `deepseq` return ()
modifyGHCiState $ \st -> st{ cmdqueue = cmds ++ cmdqueue st }
-- | Entry point to execute some haskell code from user.
-- The return value True indicates success, as in `runOneCommand`.
runStmt :: String -> SingleStep -> GHCi (Maybe GHC.ExecResult)
runStmt stmt step = do
dflags <- GHC.getInteractiveDynFlags
if | GHC.isStmt dflags stmt -> run_stmt
| GHC.isImport dflags stmt -> run_import
-- Every import declaration should be handled by `run_import`. As GHCi
-- in general only accepts one command at a time, we simply throw an
-- exception when the input contains multiple commands of which at least
-- one is an import command (see #10663).
| GHC.hasImport dflags stmt -> throwGhcException
(CmdLineError "error: expecting a single import declaration")
-- Note: `GHC.isDecl` returns False on input like
-- `data Infix a b = a :@: b; infixl 4 :@:`
-- and should therefore not be used here.
| otherwise -> run_decl
where
run_import = do
addImportToContext stmt
return (Just (GHC.ExecComplete (Right []) 0))
run_decl =
do _ <- liftIO $ tryIO $ hFlushAll stdin
m_result <- GhciMonad.runDecls stmt
case m_result of
Nothing -> return Nothing
Just result ->
Just <$> afterRunStmt (const True)
(GHC.ExecComplete (Right result) 0)
run_stmt =
do -- In the new IO library, read handles buffer data even if the Handle
-- is set to NoBuffering. This causes problems for GHCi where there
-- are really two stdin Handles. So we flush any bufferred data in
-- GHCi's stdin Handle here (only relevant if stdin is attached to
-- a file, otherwise the read buffer can't be flushed).
_ <- liftIO $ tryIO $ hFlushAll stdin
m_result <- GhciMonad.runStmt stmt step
case m_result of
Nothing -> return Nothing
Just result -> Just <$> afterRunStmt (const True) result
-- | Clean up the GHCi environment after a statement has run
afterRunStmt :: (SrcSpan -> Bool) -> GHC.ExecResult -> GHCi GHC.ExecResult
afterRunStmt step_here run_result = do
resumes <- GHC.getResumeContext
case run_result of
GHC.ExecComplete{..} ->
case execResult of
Left ex -> liftIO $ Exception.throwIO ex
Right names -> do
show_types <- isOptionSet ShowType
when show_types $ printTypeOfNames names
GHC.ExecBreak names mb_info
| isNothing mb_info ||
step_here (GHC.resumeSpan $ head resumes) -> do
mb_id_loc <- toBreakIdAndLocation mb_info
let bCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
if (null bCmd)
then printStoppedAtBreakInfo (head resumes) names
else enqueueCommands [bCmd]
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
return ()
| otherwise -> resume step_here GHC.SingleStep >>=
afterRunStmt step_here >> return ()
flushInterpBuffers
liftIO installSignalHandlers
b <- isOptionSet RevertCAFs
when b revertCAFs
return run_result
runSuccess :: Maybe GHC.ExecResult -> Bool
runSuccess run_result
| Just (GHC.ExecComplete { execResult = Right _ }) <- run_result = True
| otherwise = False
runAllocs :: Maybe GHC.ExecResult -> Maybe Integer
runAllocs m = do
res <- m
case res of
GHC.ExecComplete{..} -> Just (fromIntegral execAllocation)
_ -> Nothing
toBreakIdAndLocation ::
Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation Nothing = return Nothing
toBreakIdAndLocation (Just inf) = do
let md = GHC.breakInfo_module inf
nm = GHC.breakInfo_number inf
st <- getGHCiState
return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
breakModule loc == md,
breakTick loc == nm ]
printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo res names = do
printForUser $ pprStopped res
-- printTypeOfNames session names
let namesSorted = sortBy compareNames names
tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
printForUserPartWay $ vcat docs
printTypeOfNames :: [Name] -> GHCi ()
printTypeOfNames names
= mapM_ (printTypeOfName ) $ sortBy compareNames names
compareNames :: Name -> Name -> Ordering
n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
where compareWith n = (getOccString n, getSrcSpan n)
printTypeOfName :: Name -> GHCi ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
-- | Entry point for execution a ':<command>' input from user
specialCommand :: String -> InputT GHCi Bool
specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
specialCommand str = do
let (cmd,rest) = break isSpace str
maybe_cmd <- lift $ lookupCommand cmd
htxt <- short_help <$> getGHCiState
case maybe_cmd of
GotCommand cmd -> (cmdAction cmd) (dropWhile isSpace rest)
BadCommand ->
do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
++ htxt)
return False
NoLastCommand ->
do liftIO $ hPutStr stdout ("there is no last command to perform\n"
++ htxt)
return False
shellEscape :: String -> GHCi Bool
shellEscape str = liftIO (system str >> return False)
lookupCommand :: String -> GHCi (MaybeCommand)
lookupCommand "" = do
st <- getGHCiState
case last_command st of
Just c -> return $ GotCommand c
Nothing -> return NoLastCommand
lookupCommand str = do
mc <- lookupCommand' str
modifyGHCiState (\st -> st { last_command = mc })
return $ case mc of
Just c -> GotCommand c
Nothing -> BadCommand
lookupCommand' :: String -> GHCi (Maybe Command)
lookupCommand' ":" = return Nothing
lookupCommand' str' = do
macros <- ghci_macros <$> getGHCiState
ghci_cmds <- ghci_commands <$> getGHCiState
let ghci_cmds_nohide = filter (not . cmdHidden) ghci_cmds
let (str, xcmds) = case str' of
':' : rest -> (rest, []) -- "::" selects a builtin command
_ -> (str', macros) -- otherwise include macros in lookup
lookupExact s = find $ (s ==) . cmdName
lookupPrefix s = find $ (s `isPrefixOf`) . cmdName
-- hidden commands can only be matched exact
builtinPfxMatch = lookupPrefix str ghci_cmds_nohide
-- first, look for exact match (while preferring macros); then, look
-- for first prefix match (preferring builtins), *unless* a macro
-- overrides the builtin; see #8305 for motivation
return $ lookupExact str xcmds <|>
lookupExact str ghci_cmds <|>
(builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
builtinPfxMatch <|>
lookupPrefix str xcmds
getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
getCurrentBreakSpan = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (Just (GHC.resumeSpan r))
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (Just pan)
getCallStackAtCurrentBreakpoint :: GHCi (Maybe [String])
getCallStackAtCurrentBreakpoint = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
hsc_env <- GHC.getSession
Just <$> liftIO (costCentreStackInfo hsc_env (GHC.resumeCCS r))
getCurrentBreakModule :: GHCi (Maybe Module)
getCurrentBreakModule = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
else do
let hist = GHC.resumeHistory r !! (ix-1)
return $ Just $ GHC.getHistoryModule hist
-----------------------------------------------------------------------------
--
-- Commands
--
-----------------------------------------------------------------------------
noArgs :: GHCi () -> String -> GHCi ()
noArgs m "" = m
noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
withSandboxOnly :: String -> GHCi () -> GHCi ()
withSandboxOnly cmd this = do
dflags <- getDynFlags
if not (gopt Opt_GhciSandbox dflags)
then printForUser (text cmd <+>
ptext (sLit "is not supported with -fno-ghci-sandbox"))
else this
-----------------------------------------------------------------------------
-- :help
help :: String -> GHCi ()
help _ = do
txt <- long_help `fmap` getGHCiState
liftIO $ putStr txt
-----------------------------------------------------------------------------
-- :info
info :: Bool -> String -> InputT GHCi ()
info _ "" = throwGhcException (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
info allInfo s = handleSourceError GHC.printException $ do
unqual <- GHC.getPrintUnqual
dflags <- getDynFlags
sdocs <- mapM (infoThing allInfo) (words s)
mapM_ (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs
infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
infoThing allInfo str = do
names <- GHC.parseName str
mb_stuffs <- mapM (GHC.getInfo allInfo) names
let filtered = filterOutChildren (\(t,_f,_ci,_fi) -> t) (catMaybes mb_stuffs)
return $ vcat (intersperse (text "") $ map pprInfo filtered)
-- Filter out names whose parent is also there Good
-- example is '[]', which is both a type and data
-- constructor in the same type
filterOutChildren :: (a -> TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filterOut has_parent xs
where
all_names = mkNameSet (map (getName . get_thing) xs)
has_parent x = case tyThingParent_maybe (get_thing x) of
Just p -> getName p `elemNameSet` all_names
Nothing -> False
pprInfo :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
pprInfo (thing, fixity, cls_insts, fam_insts)
= pprTyThingInContextLoc thing
$$ show_fixity
$$ vcat (map GHC.pprInstance cls_insts)
$$ vcat (map GHC.pprFamInst fam_insts)
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> pprInfixName (GHC.getName thing)
-----------------------------------------------------------------------------
-- :main
runMain :: String -> GHCi ()
runMain s = case toArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right args ->
do dflags <- getDynFlags
let main = fromMaybe "main" (mainFunIs dflags)
-- Wrap the main function in 'void' to discard its value instead
-- of printing it (#9086). See Haskell 2010 report Chapter 5.
doWithArgs args $ "Control.Monad.void (" ++ main ++ ")"
-----------------------------------------------------------------------------
-- :run
runRun :: String -> GHCi ()
runRun s = case toCmdArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right (cmd, args) -> doWithArgs args cmd
doWithArgs :: [String] -> String -> GHCi ()
doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
show args ++ " (" ++ cmd ++ ")"]
-----------------------------------------------------------------------------
-- :cd
changeDirectory :: String -> InputT GHCi ()
changeDirectory "" = do
-- :cd on its own changes to the user's home directory
either_dir <- liftIO $ tryIO getHomeDirectory
case either_dir of
Left _e -> return ()
Right dir -> changeDirectory dir
changeDirectory dir = do
graph <- GHC.getModuleGraph
when (not (null graph)) $
liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
lift $ setContextAfterLoad False []
GHC.workingDirectoryChanged
dir' <- expandPath dir
liftIO $ setCurrentDirectory dir'
trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess act =
handleSourceError (\e -> do GHC.printException e
return Failed) $ do
act
-----------------------------------------------------------------------------
-- :edit
editFile :: String -> InputT GHCi ()
editFile str =
do file <- if null str then lift chooseEditFile else expandPath str
st <- getGHCiState
errs <- liftIO $ readIORef $ lastErrorLocations st
let cmd = editor st
when (null cmd)
$ throwGhcException (CmdLineError "editor not set, use :set editor")
lineOpt <- liftIO $ do
let sameFile p1 p2 = liftA2 (==) (canonicalizePath p1) (canonicalizePath p2)
`catchIO` (\_ -> return False)
curFileErrs <- filterM (\(f, _) -> unpackFS f `sameFile` file) errs
return $ case curFileErrs of
(_, line):_ -> " +" ++ show line
_ -> ""
let cmdArgs = ' ':(file ++ lineOpt)
code <- liftIO $ system (cmd ++ cmdArgs)
when (code == ExitSuccess)
$ reloadModule False ""
-- The user didn't specify a file so we pick one for them.
-- Our strategy is to pick the first module that failed to load,
-- or otherwise the first target.
--
-- XXX: Can we figure out what happened if the depndecy analysis fails
-- (e.g., because the porgrammeer mistyped the name of a module)?
-- XXX: Can we figure out the location of an error to pass to the editor?
-- XXX: if we could figure out the list of errors that occured during the
-- last load/reaload, then we could start the editor focused on the first
-- of those.
chooseEditFile :: GHCi String
chooseEditFile =
do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
graph <- GHC.getModuleGraph
failed_graph <- filterM hasFailed graph
let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
pick xs = case xs of
x : _ -> GHC.ml_hs_file (GHC.ms_location x)
_ -> Nothing
case pick (order failed_graph) of
Just file -> return file
Nothing ->
do targets <- GHC.getTargets
case msum (map fromTarget targets) of
Just file -> return file
Nothing -> throwGhcException (CmdLineError "No files to edit.")
where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
fromTarget _ = Nothing -- when would we get a module target?
-----------------------------------------------------------------------------
-- :def
defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
defineMacro _ (':':_) =
liftIO $ putStrLn "macro name cannot start with a colon"
defineMacro overwrite s = do
let (macro_name, definition) = break isSpace s
macros <- ghci_macros <$> getGHCiState
let defined = map cmdName macros
if null macro_name
then if null defined
then liftIO $ putStrLn "no macros defined"
else liftIO $ putStr ("the following macros are defined:\n" ++
unlines defined)
else do
if (not overwrite && macro_name `elem` defined)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is already defined"))
else do
-- compile the expression
handleSourceError GHC.printException $ do
step <- getGhciStepIO
expr <- GHC.parseExpr definition
-- > ghciStepIO . definition :: String -> IO String
let stringTy = nlHsTyVar stringTy_RDR
ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
body = nlHsVar compose_RDR `mkHsApp` step `mkHsApp` expr
tySig = mkLHsSigWcType (stringTy `nlHsFunTy` ioM)
new_expr = L (getLoc expr) $ ExprWithTySig body tySig
hv <- GHC.compileParsedExprRemote new_expr
let newCmd = Command { cmdName = macro_name
, cmdAction = lift . runMacro hv
, cmdHidden = False
, cmdCompletionFunc = noCompletion
}
-- later defined macros have precedence
modifyGHCiState $ \s ->
let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
in s { ghci_macros = newCmd : filtered }
runMacro :: GHC.ForeignHValue{-String -> IO String-} -> String -> GHCi Bool
runMacro fun s = do
hsc_env <- GHC.getSession
str <- liftIO $ evalStringToIOString hsc_env fun s
enqueueCommands (lines str)
return False
-----------------------------------------------------------------------------
-- :undef
undefineMacro :: String -> GHCi ()
undefineMacro str = mapM_ undef (words str)
where undef macro_name = do
cmds <- ghci_macros <$> getGHCiState
if (macro_name `notElem` map cmdName cmds)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is not defined"))
else do
-- This is a tad racy but really, it's a shell
modifyGHCiState $ \s ->
s { ghci_macros = filter ((/= macro_name) . cmdName)
(ghci_macros s) }
-----------------------------------------------------------------------------
-- :cmd
cmdCmd :: String -> GHCi ()
cmdCmd str = handleSourceError GHC.printException $ do
step <- getGhciStepIO
expr <- GHC.parseExpr str
-- > ghciStepIO str :: IO String
let new_expr = step `mkHsApp` expr
hv <- GHC.compileParsedExprRemote new_expr
hsc_env <- GHC.getSession
cmds <- liftIO $ evalString hsc_env hv
enqueueCommands (lines cmds)
-- | Generate a typed ghciStepIO expression
-- @ghciStepIO :: Ty String -> IO String@.
getGhciStepIO :: GHCi (LHsExpr RdrName)
getGhciStepIO = do
ghciTyConName <- GHC.getGHCiMonad
let stringTy = nlHsTyVar stringTy_RDR
ghciM = nlHsTyVar (getRdrName ghciTyConName) `nlHsAppTy` stringTy
ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
body = nlHsVar (getRdrName ghciStepIoMName)
tySig = mkLHsSigWcType (ghciM `nlHsFunTy` ioM)
return $ noLoc $ ExprWithTySig body tySig
-----------------------------------------------------------------------------
-- :check
checkModule :: String -> InputT GHCi ()
checkModule m = do
let modl = GHC.mkModuleName m
ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
dflags <- getDynFlags
liftIO $ putStrLn $ showSDoc dflags $
case GHC.moduleInfo r of
cm | Just scope <- GHC.modInfoTopLevelScope cm ->
let
(loc, glob) = ASSERT( all isExternalName scope )
partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
in
(text "global names: " <+> ppr glob) $$
(text "local names: " <+> ppr loc)
_ -> empty
return True
afterLoad (successIf ok) False
-----------------------------------------------------------------------------
-- :load, :add, :reload
-- | Sets '-fdefer-type-errors' if 'defer' is true, executes 'load' and unsets
-- '-fdefer-type-errors' again if it has not been set before.
deferredLoad :: Bool -> InputT GHCi SuccessFlag -> InputT GHCi ()
deferredLoad defer load = do
-- Force originalFlags to avoid leaking the associated HscEnv
!originalFlags <- getDynFlags
when defer $ Monad.void $
GHC.setProgramDynFlags $ setGeneralFlag' Opt_DeferTypeErrors originalFlags
Monad.void $ load
Monad.void $ GHC.setProgramDynFlags $ originalFlags
loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule fs = timeIt (const Nothing) (loadModule' fs)
-- | @:load@ command
loadModule_ :: Bool -> [FilePath] -> InputT GHCi ()
loadModule_ defer fs = deferredLoad defer (loadModule (zip fs (repeat Nothing)))
loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' files = do
let (filenames, phases) = unzip files
exp_filenames <- mapM expandPath filenames
let files' = zip exp_filenames phases
targets <- mapM (uncurry GHC.guessTarget) files'
-- NOTE: we used to do the dependency anal first, so that if it
-- fails we didn't throw away the current set of modules. This would
-- require some re-working of the GHC interface, so we'll leave it
-- as a ToDo for now.
-- unload first
_ <- GHC.abandonAll
lift discardActiveBreakPoints
GHC.setTargets []
_ <- GHC.load LoadAllTargets
GHC.setTargets targets
doLoadAndCollectInfo False LoadAllTargets
-- | @:add@ command
addModule :: [FilePath] -> InputT GHCi ()
addModule files = do
lift revertCAFs -- always revert CAFs on load/add.
files' <- mapM expandPath files
targets <- mapM (\m -> GHC.guessTarget m Nothing) files'
-- remove old targets with the same id; e.g. for :add *M
mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
mapM_ GHC.addTarget targets
_ <- doLoadAndCollectInfo False LoadAllTargets
return ()
-- | @:reload@ command
reloadModule :: Bool -> String -> InputT GHCi ()
reloadModule defer m = deferredLoad defer $
doLoadAndCollectInfo True loadTargets
where
loadTargets | null m = LoadAllTargets
| otherwise = LoadUpTo (GHC.mkModuleName m)
-- | Load/compile targets and (optionally) collect module-info
--
-- This collects the necessary SrcSpan annotated type information (via
-- 'collectInfo') required by the @:all-types@, @:loc-at@, @:type-at@,
-- and @:uses@ commands.
--
-- Meta-info collection is not enabled by default and needs to be
-- enabled explicitly via @:set +c@. The reason is that collecting
-- the type-information for all sub-spans can be quite expensive, and
-- since those commands are designed to be used by editors and
-- tooling, it's useless to collect this data for normal GHCi
-- sessions.
doLoadAndCollectInfo :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo retain_context howmuch = do
doCollectInfo <- lift (isOptionSet CollectInfo)
doLoad retain_context howmuch >>= \case
Succeeded | doCollectInfo -> do
loaded <- getModuleGraph >>= filterM GHC.isLoaded . map GHC.ms_mod_name
v <- mod_infos <$> getGHCiState
!newInfos <- collectInfo v loaded
modifyGHCiState (\st -> st { mod_infos = newInfos })
return Succeeded
flag -> return flag
doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad retain_context howmuch = do
-- turn off breakpoints before we load: we can't turn them off later, because
-- the ModBreaks will have gone away.
lift discardActiveBreakPoints
lift resetLastErrorLocations
-- Enable buffering stdout and stderr as we're compiling. Keeping these
-- handles unbuffered will just slow the compilation down, especially when
-- compiling in parallel.
gbracket (liftIO $ do hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering)
(\_ ->
liftIO $ do hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering) $ \_ -> do
ok <- trySuccess $ GHC.load howmuch
afterLoad ok retain_context
return ok
afterLoad :: SuccessFlag
-> Bool -- keep the remembered_ctx, as far as possible (:reload)
-> InputT GHCi ()
afterLoad ok retain_context = do
lift revertCAFs -- always revert CAFs on load.
lift discardTickArrays
loaded_mods <- getLoadedModules
modulesLoadedMsg ok loaded_mods
lift $ setContextAfterLoad retain_context loaded_mods
setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
setContextAfterLoad keep_ctxt [] = do
setContextKeepingPackageModules keep_ctxt []
setContextAfterLoad keep_ctxt ms = do
-- load a target if one is available, otherwise load the topmost module.
targets <- GHC.getTargets
case [ m | Just m <- map (findTarget ms) targets ] of
[] ->
let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
load_this (last graph')
(m:_) ->
load_this m
where
findTarget mds t
= case filter (`matches` t) mds of
[] -> Nothing
(m:_) -> Just m
summary `matches` Target (TargetModule m) _ _
= GHC.ms_mod_name summary == m
summary `matches` Target (TargetFile f _) _ _
| Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
_ `matches` _
= False
load_this summary | m <- GHC.ms_mod summary = do
is_interp <- GHC.moduleIsInterpreted m
dflags <- getDynFlags
let star_ok = is_interp && not (safeLanguageOn dflags)
-- We import the module with a * iff
-- - it is interpreted, and
-- - -XSafe is off (it doesn't allow *-imports)
let new_ctx | star_ok = [mkIIModule (GHC.moduleName m)]
| otherwise = [mkIIDecl (GHC.moduleName m)]
setContextKeepingPackageModules keep_ctxt new_ctx
-- | Keep any package modules (except Prelude) when changing the context.
setContextKeepingPackageModules
:: Bool -- True <=> keep all of remembered_ctx
-- False <=> just keep package imports
-> [InteractiveImport] -- new context
-> GHCi ()
setContextKeepingPackageModules keep_ctx trans_ctx = do
st <- getGHCiState
let rem_ctx = remembered_ctx st
new_rem_ctx <- if keep_ctx then return rem_ctx
else keepPackageImports rem_ctx
setGHCiState st{ remembered_ctx = new_rem_ctx,
transient_ctx = filterSubsumed new_rem_ctx trans_ctx }
setGHCContextFromGHCiState
-- | Filters a list of 'InteractiveImport', clearing out any home package
-- imports so only imports from external packages are preserved. ('IIModule'
-- counts as a home package import, because we are only able to bring a
-- full top-level into scope when the source is available.)
keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports = filterM is_pkg_import
where
is_pkg_import :: InteractiveImport -> GHCi Bool
is_pkg_import (IIModule _) = return False
is_pkg_import (IIDecl d)
= do e <- gtry $ GHC.findModule mod_name (fmap sl_fs $ ideclPkgQual d)
case e :: Either SomeException Module of
Left _ -> return False
Right m -> return (not (isHomeModule m))
where
mod_name = unLoc (ideclName d)
modulesLoadedMsg :: SuccessFlag -> [GHC.ModSummary] -> InputT GHCi ()
modulesLoadedMsg ok mods = do
dflags <- getDynFlags
unqual <- GHC.getPrintUnqual
let mod_name mod = do
is_interpreted <- GHC.isModuleInterpreted mod
return $ if is_interpreted
then ppr (GHC.ms_mod mod)
else ppr (GHC.ms_mod mod)
<> text " ("
<> text (normalise $ msObjFilePath mod)
<> text ")" -- fix #9887
mod_names <- mapM mod_name mods
let mod_commas
| null mods = text "none."
| otherwise = hsep (punctuate comma mod_names) <> text "."
status = case ok of
Failed -> text "Failed"
Succeeded -> text "Ok"
msg = status <> text ", modules loaded:" <+> mod_commas
when (verbosity dflags > 0) $
liftIO $ putStrLn $ showSDocForUser dflags unqual msg
-- | Run an 'ExceptT' wrapped 'GhcMonad' while handling source errors
-- and printing 'throwE' strings to 'stderr'
runExceptGhcMonad :: GHC.GhcMonad m => ExceptT SDoc m () -> m ()
runExceptGhcMonad act = handleSourceError GHC.printException $
either handleErr pure =<<
runExceptT act
where
handleErr sdoc = do
dflags <- getDynFlags
liftIO . hPutStrLn stderr . showSDocForUser dflags alwaysQualify $ sdoc
-- | Inverse of 'runExceptT' for \"pure\" computations
-- (c.f. 'except' for 'Except')
exceptT :: Applicative m => Either e a -> ExceptT e m a
exceptT = ExceptT . pure
-----------------------------------------------------------------------------
-- | @:type@ command
typeOfExpr :: String -> InputT GHCi ()
typeOfExpr str = handleSourceError GHC.printException $ do
ty <- GHC.exprType str
printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser ty)]
-----------------------------------------------------------------------------
-- | @:type-at@ command
typeAtCmd :: String -> InputT GHCi ()
typeAtCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
(info, ty) <- findType infos span' sample
lift $ printForUserModInfo (modinfoInfo info)
(sep [text sample,nest 2 (dcolon <+> ppr ty)])
-----------------------------------------------------------------------------
-- | @:uses@ command
usesCmd :: String -> InputT GHCi ()
usesCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
uses <- findNameUses infos span' sample
forM_ uses (liftIO . putStrLn . showSrcSpan)
-----------------------------------------------------------------------------
-- | @:loc-at@ command
locAtCmd :: String -> InputT GHCi ()
locAtCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
(_,_,sp) <- findLoc infos span' sample
liftIO . putStrLn . showSrcSpan $ sp
-----------------------------------------------------------------------------
-- | @:all-types@ command
allTypesCmd :: String -> InputT GHCi ()
allTypesCmd _ = runExceptGhcMonad $ do
infos <- mod_infos <$> getGHCiState
forM_ (M.elems infos) $ \mi ->
forM_ (modinfoSpans mi) (lift . printSpan)
where
printSpan span'
| Just ty <- spaninfoType span' = do
df <- getDynFlags
let tyInfo = unwords . words $
showSDocForUser df alwaysQualify (pprTypeForUser ty)
liftIO . putStrLn $
showRealSrcSpan (spaninfoSrcSpan span') ++ ": " ++ tyInfo
| otherwise = return ()
-----------------------------------------------------------------------------
-- Helpers for locAtCmd/typeAtCmd/usesCmd
-- | Parse a span: <module-name/filepath> <sl> <sc> <el> <ec> <string>
parseSpanArg :: String -> Either SDoc (RealSrcSpan,String)
parseSpanArg s = do
(fp,s0) <- readAsString (skipWs s)
s0' <- skipWs1 s0
(sl,s1) <- readAsInt s0'
s1' <- skipWs1 s1
(sc,s2) <- readAsInt s1'
s2' <- skipWs1 s2
(el,s3) <- readAsInt s2'
s3' <- skipWs1 s3
(ec,s4) <- readAsInt s3'
trailer <- case s4 of
[] -> Right ""
_ -> skipWs1 s4
let fs = mkFastString fp
span' = mkRealSrcSpan (mkRealSrcLoc fs sl sc)
(mkRealSrcLoc fs el ec)
return (span',trailer)
where
readAsInt :: String -> Either SDoc (Int,String)
readAsInt "" = Left "Premature end of string while expecting Int"
readAsInt s0 = case reads s0 of
[s_rest] -> Right s_rest
_ -> Left ("Couldn't read" <+> text (show s0) <+> "as Int")
readAsString :: String -> Either SDoc (String,String)
readAsString s0
| '"':_ <- s0 = case reads s0 of
[s_rest] -> Right s_rest
_ -> leftRes
| s_rest@(_:_,_) <- breakWs s0 = Right s_rest
| otherwise = leftRes
where
leftRes = Left ("Couldn't read" <+> text (show s0) <+> "as String")
skipWs1 :: String -> Either SDoc String
skipWs1 (c:cs) | isWs c = Right (skipWs cs)
skipWs1 s0 = Left ("Expected whitespace in" <+> text (show s0))
isWs = (`elem` [' ','\t'])
skipWs = dropWhile isWs
breakWs = break isWs
-- | Pretty-print \"real\" 'SrcSpan's as
-- @<filename>:(<line>,<col>)-(<line-end>,<col-end>)@
-- while simply unpacking 'UnhelpfulSpan's
showSrcSpan :: SrcSpan -> String
showSrcSpan (UnhelpfulSpan s) = unpackFS s
showSrcSpan (RealSrcSpan spn) = showRealSrcSpan spn
-- | Variant of 'showSrcSpan' for 'RealSrcSpan's
showRealSrcSpan :: RealSrcSpan -> String
showRealSrcSpan spn = concat [ fp, ":(", show sl, ",", show sc
, ")-(", show el, ",", show ec, ")"
]
where
fp = unpackFS (srcSpanFile spn)
sl = srcSpanStartLine spn
sc = srcSpanStartCol spn
el = srcSpanEndLine spn
ec = srcSpanEndCol spn
-----------------------------------------------------------------------------
-- | @:kind@ command
kindOfType :: Bool -> String -> InputT GHCi ()
kindOfType norm str = handleSourceError GHC.printException $ do
(ty, kind) <- GHC.typeKind norm str
printForUser $ vcat [ text str <+> dcolon <+> pprTypeForUser kind
, ppWhen norm $ equals <+> pprTypeForUser ty ]
-----------------------------------------------------------------------------
-- :quit
quit :: String -> InputT GHCi Bool
quit _ = return True
-----------------------------------------------------------------------------
-- :script
-- running a script file #1363
scriptCmd :: String -> InputT GHCi ()
scriptCmd ws = do
case words ws of
[s] -> runScript s
_ -> throwGhcException (CmdLineError "syntax: :script <filename>")
runScript :: String -- ^ filename
-> InputT GHCi ()
runScript filename = do
filename' <- expandPath filename
either_script <- liftIO $ tryIO (openFile filename' ReadMode)
case either_script of
Left _err -> throwGhcException (CmdLineError $ "IO error: \""++filename++"\" "
++(ioeGetErrorString _err))
Right script -> do
st <- getGHCiState
let prog = progname st
line = line_number st
setGHCiState st{progname=filename',line_number=0}
scriptLoop script
liftIO $ hClose script
new_st <- getGHCiState
setGHCiState new_st{progname=prog,line_number=line}
where scriptLoop script = do
res <- runOneCommand handler $ fileLoop script
case res of
Nothing -> return ()
Just s -> if s
then scriptLoop script
else return ()
-----------------------------------------------------------------------------
-- :issafe
-- Displaying Safe Haskell properties of a module
isSafeCmd :: String -> InputT GHCi ()
isSafeCmd m =
case words m of
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
isSafeModule md
[] -> do md <- guessCurrentModule "issafe"
isSafeModule md
_ -> throwGhcException (CmdLineError "syntax: :issafe <module>")
isSafeModule :: Module -> InputT GHCi ()
isSafeModule m = do
mb_mod_info <- GHC.getModuleInfo m
when (isNothing mb_mod_info)
(throwGhcException $ CmdLineError $ "unknown module: " ++ mname)
dflags <- getDynFlags
let iface = GHC.modInfoIface $ fromJust mb_mod_info
when (isNothing iface)
(throwGhcException $ CmdLineError $ "can't load interface file for module: " ++
(GHC.moduleNameString $ GHC.moduleName m))
(msafe, pkgs) <- GHC.moduleTrustReqs m
let trust = showPpr dflags $ getSafeMode $ GHC.mi_trust $ fromJust iface
pkg = if packageTrusted dflags m then "trusted" else "untrusted"
(good, bad) = tallyPkgs dflags pkgs
-- print info to user...
liftIO $ putStrLn $ "Trust type is (Module: " ++ trust ++ ", Package: " ++ pkg ++ ")"
liftIO $ putStrLn $ "Package Trust: " ++ (if packageTrustOn dflags then "On" else "Off")
when (not $ null good)
(liftIO $ putStrLn $ "Trusted package dependencies (trusted): " ++
(intercalate ", " $ map (showPpr dflags) good))
case msafe && null bad of
True -> liftIO $ putStrLn $ mname ++ " is trusted!"
False -> do
when (not $ null bad)
(liftIO $ putStrLn $ "Trusted package dependencies (untrusted): "
++ (intercalate ", " $ map (showPpr dflags) bad))
liftIO $ putStrLn $ mname ++ " is NOT trusted!"
where
mname = GHC.moduleNameString $ GHC.moduleName m
packageTrusted dflags md
| thisPackage dflags == moduleUnitId md = True
| otherwise = trusted $ getPackageDetails dflags (moduleUnitId md)
tallyPkgs dflags deps | not (packageTrustOn dflags) = ([], [])
| otherwise = partition part deps
where part pkg = trusted $ getPackageDetails dflags pkg
-----------------------------------------------------------------------------
-- :browse
-- Browsing a module's contents
browseCmd :: Bool -> String -> InputT GHCi ()
browseCmd bang m =
case words m of
['*':s] | looksLikeModuleName s -> do
md <- lift $ wantInterpretedModule s
browseModule bang md False
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
browseModule bang md True
[] -> do md <- guessCurrentModule ("browse" ++ if bang then "!" else "")
browseModule bang md True
_ -> throwGhcException (CmdLineError "syntax: :browse <module>")
guessCurrentModule :: String -> InputT GHCi Module
-- Guess which module the user wants to browse. Pick
-- modules that are interpreted first. The most
-- recently-added module occurs last, it seems.
guessCurrentModule cmd
= do imports <- GHC.getContext
when (null imports) $ throwGhcException $
CmdLineError (':' : cmd ++ ": no current module")
case (head imports) of
IIModule m -> GHC.findModule m Nothing
IIDecl d -> GHC.findModule (unLoc (ideclName d))
(fmap sl_fs $ ideclPkgQual d)
-- without bang, show items in context of their parents and omit children
-- with bang, show class methods and data constructors separately, and
-- indicate import modules, to aid qualifying unqualified names
-- with sorted, sort items alphabetically
browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
browseModule bang modl exports_only = do
-- :browse reports qualifiers wrt current context
unqual <- GHC.getPrintUnqual
mb_mod_info <- GHC.getModuleInfo modl
case mb_mod_info of
Nothing -> throwGhcException (CmdLineError ("unknown module: " ++
GHC.moduleNameString (GHC.moduleName modl)))
Just mod_info -> do
dflags <- getDynFlags
let names
| exports_only = GHC.modInfoExports mod_info
| otherwise = GHC.modInfoTopLevelScope mod_info
`orElse` []
-- sort alphabetically name, but putting locally-defined
-- identifiers first. We would like to improve this; see #1799.
sorted_names = loc_sort local ++ occ_sort external
where
(local,external) = ASSERT( all isExternalName names )
partition ((==modl) . nameModule) names
occ_sort = sortBy (compare `on` nameOccName)
-- try to sort by src location. If the first name in our list
-- has a good source location, then they all should.
loc_sort ns
| n:_ <- ns, isGoodSrcSpan (nameSrcSpan n)
= sortBy (compare `on` nameSrcSpan) ns
| otherwise
= occ_sort ns
mb_things <- mapM GHC.lookupName sorted_names
let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
rdr_env <- GHC.getGRE
let things | bang = catMaybes mb_things
| otherwise = filtered_things
pretty | bang = pprTyThing
| otherwise = pprTyThingInContext
labels [] = text "-- not currently imported"
labels l = text $ intercalate "\n" $ map qualifier l
qualifier :: Maybe [ModuleName] -> String
qualifier = maybe "-- defined locally"
(("-- imported via "++) . intercalate ", "
. map GHC.moduleNameString)
importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
modNames :: [[Maybe [ModuleName]]]
modNames = map (importInfo . GHC.getName) things
-- annotate groups of imports with their import modules
-- the default ordering is somewhat arbitrary, so we group
-- by header and sort groups; the names themselves should
-- really come in order of source appearance.. (trac #1799)
annotate mts = concatMap (\(m,ts)->labels m:ts)
$ sortBy cmpQualifiers $ grp mts
where cmpQualifiers =
compare `on` (map (fmap (map moduleNameFS)) . fst)
grp [] = []
grp mts@((m,_):_) = (m,map snd g) : grp ng
where (g,ng) = partition ((==m).fst) mts
let prettyThings, prettyThings' :: [SDoc]
prettyThings = map pretty things
prettyThings' | bang = annotate $ zip modNames prettyThings
| otherwise = prettyThings
liftIO $ putStrLn $ showSDocForUser dflags unqual (vcat prettyThings')
-- ToDo: modInfoInstances currently throws an exception for
-- package modules. When it works, we can do this:
-- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
-----------------------------------------------------------------------------
-- :module
-- Setting the module context. For details on context handling see
-- "remembered_ctx" and "transient_ctx" in GhciMonad.
moduleCmd :: String -> GHCi ()
moduleCmd str
| all sensible strs = cmd
| otherwise = throwGhcException (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
where
(cmd, strs) =
case str of
'+':stuff -> rest addModulesToContext stuff
'-':stuff -> rest remModulesFromContext stuff
stuff -> rest setContext stuff
rest op stuff = (op as bs, stuffs)
where (as,bs) = partitionWith starred stuffs
stuffs = words stuff
sensible ('*':m) = looksLikeModuleName m
sensible m = looksLikeModuleName m
starred ('*':m) = Left (GHC.mkModuleName m)
starred m = Right (GHC.mkModuleName m)
-- -----------------------------------------------------------------------------
-- Four ways to manipulate the context:
-- (a) :module +<stuff>: addModulesToContext
-- (b) :module -<stuff>: remModulesFromContext
-- (c) :module <stuff>: setContext
-- (d) import <module>...: addImportToContext
addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext starred unstarred = restoreContextOnFailure $ do
addModulesToContext_ starred unstarred
addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ starred unstarred = do
mapM_ addII (map mkIIModule starred ++ map mkIIDecl unstarred)
setGHCContextFromGHCiState
remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext starred unstarred = do
-- we do *not* call restoreContextOnFailure here. If the user
-- is trying to fix up a context that contains errors by removing
-- modules, we don't want GHC to silently put them back in again.
mapM_ rm (starred ++ unstarred)
setGHCContextFromGHCiState
where
rm :: ModuleName -> GHCi ()
rm str = do
m <- moduleName <$> lookupModuleName str
let filt = filter ((/=) m . iiModuleName)
modifyGHCiState $ \st ->
st { remembered_ctx = filt (remembered_ctx st)
, transient_ctx = filt (transient_ctx st) }
setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
setContext starred unstarred = restoreContextOnFailure $ do
modifyGHCiState $ \st -> st { remembered_ctx = [], transient_ctx = [] }
-- delete the transient context
addModulesToContext_ starred unstarred
addImportToContext :: String -> GHCi ()
addImportToContext str = restoreContextOnFailure $ do
idecl <- GHC.parseImportDecl str
addII (IIDecl idecl) -- #5836
setGHCContextFromGHCiState
-- Util used by addImportToContext and addModulesToContext
addII :: InteractiveImport -> GHCi ()
addII iidecl = do
checkAdd iidecl
modifyGHCiState $ \st ->
st { remembered_ctx = addNotSubsumed iidecl (remembered_ctx st)
, transient_ctx = filter (not . (iidecl `iiSubsumes`))
(transient_ctx st)
}
-- Sometimes we can't tell whether an import is valid or not until
-- we finally call 'GHC.setContext'. e.g.
--
-- import System.IO (foo)
--
-- will fail because System.IO does not export foo. In this case we
-- don't want to store the import in the context permanently, so we
-- catch the failure from 'setGHCContextFromGHCiState' and set the
-- context back to what it was.
--
-- See #6007
--
restoreContextOnFailure :: GHCi a -> GHCi a
restoreContextOnFailure do_this = do
st <- getGHCiState
let rc = remembered_ctx st; tc = transient_ctx st
do_this `gonException` (modifyGHCiState $ \st' ->
st' { remembered_ctx = rc, transient_ctx = tc })
-- -----------------------------------------------------------------------------
-- Validate a module that we want to add to the context
checkAdd :: InteractiveImport -> GHCi ()
checkAdd ii = do
dflags <- getDynFlags
let safe = safeLanguageOn dflags
case ii of
IIModule modname
| safe -> throwGhcException $ CmdLineError "can't use * imports with Safe Haskell"
| otherwise -> wantInterpretedModuleName modname >> return ()
IIDecl d -> do
let modname = unLoc (ideclName d)
pkgqual = ideclPkgQual d
m <- GHC.lookupModule modname (fmap sl_fs pkgqual)
when safe $ do
t <- GHC.isModuleTrusted m
when (not t) $ throwGhcException $ ProgramError $ ""
-- -----------------------------------------------------------------------------
-- Update the GHC API's view of the context
-- | Sets the GHC context from the GHCi state. The GHC context is
-- always set this way, we never modify it incrementally.
--
-- We ignore any imports for which the ModuleName does not currently
-- exist. This is so that the remembered_ctx can contain imports for
-- modules that are not currently loaded, perhaps because we just did
-- a :reload and encountered errors.
--
-- Prelude is added if not already present in the list. Therefore to
-- override the implicit Prelude import you can say 'import Prelude ()'
-- at the prompt, just as in Haskell source.
--
setGHCContextFromGHCiState :: GHCi ()
setGHCContextFromGHCiState = do
st <- getGHCiState
-- re-use checkAdd to check whether the module is valid. If the
-- module does not exist, we do *not* want to print an error
-- here, we just want to silently keep the module in the context
-- until such time as the module reappears again. So we ignore
-- the actual exception thrown by checkAdd, using tryBool to
-- turn it into a Bool.
iidecls <- filterM (tryBool.checkAdd) (transient_ctx st ++ remembered_ctx st)
dflags <- GHC.getSessionDynFlags
GHC.setContext $
if xopt LangExt.ImplicitPrelude dflags && not (any isPreludeImport iidecls)
then iidecls ++ [implicitPreludeImport]
else iidecls
-- XXX put prel at the end, so that guessCurrentModule doesn't pick it up.
-- -----------------------------------------------------------------------------
-- Utils on InteractiveImport
mkIIModule :: ModuleName -> InteractiveImport
mkIIModule = IIModule
mkIIDecl :: ModuleName -> InteractiveImport
mkIIDecl = IIDecl . simpleImportDecl
iiModules :: [InteractiveImport] -> [ModuleName]
iiModules is = [m | IIModule m <- is]
iiModuleName :: InteractiveImport -> ModuleName
iiModuleName (IIModule m) = m
iiModuleName (IIDecl d) = unLoc (ideclName d)
preludeModuleName :: ModuleName
preludeModuleName = GHC.mkModuleName "Prelude"
implicitPreludeImport :: InteractiveImport
implicitPreludeImport = IIDecl (simpleImportDecl preludeModuleName)
isPreludeImport :: InteractiveImport -> Bool
isPreludeImport (IIModule {}) = True
isPreludeImport (IIDecl d) = unLoc (ideclName d) == preludeModuleName
addNotSubsumed :: InteractiveImport
-> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed i is
| any (`iiSubsumes` i) is = is
| otherwise = i : filter (not . (i `iiSubsumes`)) is
-- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
-- by any of @is@.
filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
-> [InteractiveImport]
filterSubsumed is js = filter (\j -> not (any (`iiSubsumes` j) is)) js
-- | Returns True if the left import subsumes the right one. Doesn't
-- need to be 100% accurate, conservatively returning False is fine.
-- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
-- plusProv will ensue (#5904))
--
-- Note that an IIModule does not necessarily subsume an IIDecl,
-- because e.g. a module might export a name that is only available
-- qualified within the module itself.
--
-- Note that 'import M' does not necessarily subsume 'import M(foo)',
-- because M might not export foo and we want an error to be produced
-- in that case.
--
iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
iiSubsumes (IIModule m1) (IIModule m2) = m1==m2
iiSubsumes (IIDecl d1) (IIDecl d2) -- A bit crude
= unLoc (ideclName d1) == unLoc (ideclName d2)
&& ideclAs d1 == ideclAs d2
&& (not (ideclQualified d1) || ideclQualified d2)
&& (ideclHiding d1 `hidingSubsumes` ideclHiding d2)
where
_ `hidingSubsumes` Just (False,L _ []) = True
Just (False, L _ xs) `hidingSubsumes` Just (False,L _ ys)
= all (`elem` xs) ys
h1 `hidingSubsumes` h2 = h1 == h2
iiSubsumes _ _ = False
----------------------------------------------------------------------------
-- :set
-- set options in the interpreter. Syntax is exactly the same as the
-- ghc command line, except that certain options aren't available (-C,
-- -E etc.)
--
-- This is pretty fragile: most options won't work as expected. ToDo:
-- figure out which ones & disallow them.
setCmd :: String -> GHCi ()
setCmd "" = showOptions False
setCmd "-a" = showOptions True
setCmd str
= case getCmd str of
Right ("args", rest) ->
case toArgs rest of
Left err -> liftIO (hPutStrLn stderr err)
Right args -> setArgs args
Right ("prog", rest) ->
case toArgs rest of
Right [prog] -> setProg prog
_ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
Right ("prompt2", rest) -> setPrompt2 $ dropWhile isSpace rest
Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
Right ("stop", rest) -> setStop $ dropWhile isSpace rest
_ -> case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> setOptions wds
setiCmd :: String -> GHCi ()
setiCmd "" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags False
setiCmd "-a" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags True
setiCmd str =
case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> newDynFlags True wds
showOptions :: Bool -> GHCi ()
showOptions show_all
= do st <- getGHCiState
dflags <- getDynFlags
let opts = options st
liftIO $ putStrLn (showSDoc dflags (
text "options currently set: " <>
if null opts
then text "none."
else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
))
getDynFlags >>= liftIO . showDynFlags show_all
showDynFlags :: Bool -> DynFlags -> IO ()
showDynFlags show_all dflags = do
showLanguages' show_all dflags
putStrLn $ showSDoc dflags $
text "GHCi-specific dynamic flag settings:" $$
nest 2 (vcat (map (setting "-f" "-fno-" gopt) ghciFlags))
putStrLn $ showSDoc dflags $
text "other dynamic, non-language, flag settings:" $$
nest 2 (vcat (map (setting "-f" "-fno-" gopt) others))
putStrLn $ showSDoc dflags $
text "warning settings:" $$
nest 2 (vcat (map (setting "-W" "-Wno-" wopt) DynFlags.wWarningFlags))
where
setting prefix noPrefix test flag
| quiet = empty
| is_on = text prefix <> text name
| otherwise = text noPrefix <> text name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags = defaultDynFlags (settings dflags)
(ghciFlags,others) = partition (\f -> flagSpecFlag f `elem` flgs)
DynFlags.fFlags
flgs = [ Opt_PrintExplicitForalls
, Opt_PrintExplicitKinds
, Opt_PrintUnicodeSyntax
, Opt_PrintBindResult
, Opt_BreakOnException
, Opt_BreakOnError
, Opt_PrintEvldWithShow
]
setArgs, setOptions :: [String] -> GHCi ()
setProg, setEditor, setStop :: String -> GHCi ()
setArgs args = do
st <- getGHCiState
wrapper <- mkEvalWrapper (progname st) args
setGHCiState st { GhciMonad.args = args, evalWrapper = wrapper }
setProg prog = do
st <- getGHCiState
wrapper <- mkEvalWrapper prog (GhciMonad.args st)
setGHCiState st { progname = prog, evalWrapper = wrapper }
setEditor cmd = modifyGHCiState (\st -> st { editor = cmd })
setStop str@(c:_) | isDigit c
= do let (nm_str,rest) = break (not.isDigit) str
nm = read nm_str
st <- getGHCiState
let old_breaks = breaks st
if all ((/= nm) . fst) old_breaks
then printForUser (text "Breakpoint" <+> ppr nm <+>
text "does not exist")
else do
let new_breaks = map fn old_breaks
fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
| otherwise = (i,loc)
setGHCiState st{ breaks = new_breaks }
setStop cmd = modifyGHCiState (\st -> st { stop = cmd })
setPrompt :: String -> GHCi ()
setPrompt = setPrompt_ f err
where
f v st = st { prompt = v }
err st = "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
setPrompt2 :: String -> GHCi ()
setPrompt2 = setPrompt_ f err
where
f v st = st { prompt2 = v }
err st = "syntax: :set prompt2 <prompt>, currently \"" ++ prompt2 st ++ "\""
setPrompt_ :: (String -> GHCiState -> GHCiState) -> (GHCiState -> String) -> String -> GHCi ()
setPrompt_ f err value = do
st <- getGHCiState
if null value
then liftIO $ hPutStrLn stderr $ err st
else case value of
'\"' : _ -> case reads value of
[(value', xs)] | all isSpace xs ->
setGHCiState $ f value' st
_ ->
liftIO $ hPutStrLn stderr "Can't parse prompt string. Use Haskell syntax."
_ -> setGHCiState $ f value st
setOptions wds =
do -- first, deal with the GHCi opts (+s, +t, etc.)
let (plus_opts, minus_opts) = partitionWith isPlus wds
mapM_ setOpt plus_opts
-- then, dynamic flags
newDynFlags False minus_opts
packageFlagsChanged :: DynFlags -> DynFlags -> Bool
packageFlagsChanged idflags1 idflags0 =
packageFlags idflags1 /= packageFlags idflags0 ||
ignorePackageFlags idflags1 /= ignorePackageFlags idflags0 ||
pluginPackageFlags idflags1 /= pluginPackageFlags idflags0 ||
trustFlags idflags1 /= trustFlags idflags0
newDynFlags :: Bool -> [String] -> GHCi ()
newDynFlags interactive_only minus_opts = do
let lopts = map noLoc minus_opts
idflags0 <- GHC.getInteractiveDynFlags
(idflags1, leftovers, warns) <- GHC.parseDynamicFlags idflags0 lopts
liftIO $ handleFlagWarnings idflags1 warns
when (not $ null leftovers)
(throwGhcException . CmdLineError
$ "Some flags have not been recognized: "
++ (concat . intersperse ", " $ map unLoc leftovers))
when (interactive_only && packageFlagsChanged idflags1 idflags0) $ do
liftIO $ hPutStrLn stderr "cannot set package flags with :seti; use :set"
GHC.setInteractiveDynFlags idflags1
installInteractivePrint (interactivePrint idflags1) False
dflags0 <- getDynFlags
when (not interactive_only) $ do
(dflags1, _, _) <- liftIO $ GHC.parseDynamicFlags dflags0 lopts
new_pkgs <- GHC.setProgramDynFlags dflags1
-- if the package flags changed, reset the context and link
-- the new packages.
hsc_env <- GHC.getSession
let dflags2 = hsc_dflags hsc_env
when (packageFlagsChanged dflags2 dflags0) $ do
when (verbosity dflags2 > 0) $
liftIO . putStrLn $
"package flags have changed, resetting and loading new packages..."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
liftIO $ linkPackages hsc_env new_pkgs
-- package flags changed, we can't re-use any of the old context
setContextAfterLoad False []
-- and copy the package state to the interactive DynFlags
idflags <- GHC.getInteractiveDynFlags
GHC.setInteractiveDynFlags
idflags{ pkgState = pkgState dflags2
, pkgDatabase = pkgDatabase dflags2
, packageFlags = packageFlags dflags2 }
let ld0length = length $ ldInputs dflags0
fmrk0length = length $ cmdlineFrameworks dflags0
newLdInputs = drop ld0length (ldInputs dflags2)
newCLFrameworks = drop fmrk0length (cmdlineFrameworks dflags2)
hsc_env' = hsc_env { hsc_dflags =
dflags2 { ldInputs = newLdInputs
, cmdlineFrameworks = newCLFrameworks } }
when (not (null newLdInputs && null newCLFrameworks)) $
liftIO $ linkCmdLineLibs hsc_env'
return ()
unsetOptions :: String -> GHCi ()
unsetOptions str
= -- first, deal with the GHCi opts (+s, +t, etc.)
let opts = words str
(minus_opts, rest1) = partition isMinus opts
(plus_opts, rest2) = partitionWith isPlus rest1
(other_opts, rest3) = partition (`elem` map fst defaulters) rest2
defaulters =
[ ("args" , setArgs default_args)
, ("prog" , setProg default_progname)
, ("prompt" , setPrompt default_prompt)
, ("prompt2", setPrompt2 default_prompt2)
, ("editor" , liftIO findEditor >>= setEditor)
, ("stop" , setStop default_stop)
]
no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
no_flag ('-':'X':rest) = return ("-XNo" ++ rest)
no_flag f = throwGhcException (ProgramError ("don't know how to reverse " ++ f))
in if (not (null rest3))
then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
else do
mapM_ (fromJust.flip lookup defaulters) other_opts
mapM_ unsetOpt plus_opts
no_flags <- mapM no_flag minus_opts
newDynFlags False no_flags
isMinus :: String -> Bool
isMinus ('-':_) = True
isMinus _ = False
isPlus :: String -> Either String String
isPlus ('+':opt) = Left opt
isPlus other = Right other
setOpt, unsetOpt :: String -> GHCi ()
setOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> setOption o
unsetOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> unsetOption o
strToGHCiOpt :: String -> (Maybe GHCiOption)
strToGHCiOpt "m" = Just Multiline
strToGHCiOpt "s" = Just ShowTiming
strToGHCiOpt "t" = Just ShowType
strToGHCiOpt "r" = Just RevertCAFs
strToGHCiOpt "c" = Just CollectInfo
strToGHCiOpt _ = Nothing
optToStr :: GHCiOption -> String
optToStr Multiline = "m"
optToStr ShowTiming = "s"
optToStr ShowType = "t"
optToStr RevertCAFs = "r"
optToStr CollectInfo = "c"
-- ---------------------------------------------------------------------------
-- :show
showCmd :: String -> GHCi ()
showCmd "" = showOptions False
showCmd "-a" = showOptions True
showCmd str = do
st <- getGHCiState
dflags <- getDynFlags
let lookupCmd :: String -> Maybe (GHCi ())
lookupCmd name = lookup name $ map (\(_,b,c) -> (b,c)) cmds
-- (show in help?, command name, action)
action :: String -> GHCi () -> (Bool, String, GHCi ())
action name m = (True, name, m)
hidden :: String -> GHCi () -> (Bool, String, GHCi ())
hidden name m = (False, name, m)
cmds =
[ action "args" $ liftIO $ putStrLn (show (GhciMonad.args st))
, action "prog" $ liftIO $ putStrLn (show (progname st))
, action "prompt" $ liftIO $ putStrLn (show (prompt st))
, action "prompt2" $ liftIO $ putStrLn (show (prompt2 st))
, action "editor" $ liftIO $ putStrLn (show (editor st))
, action "stop" $ liftIO $ putStrLn (show (stop st))
, action "imports" $ showImports
, action "modules" $ showModules
, action "bindings" $ showBindings
, action "linker" $ getDynFlags >>= liftIO . showLinkerState
, action "breaks" $ showBkptTable
, action "context" $ showContext
, action "packages" $ showPackages
, action "paths" $ showPaths
, action "language" $ showLanguages
, hidden "languages" $ showLanguages -- backwards compat
, hidden "lang" $ showLanguages -- useful abbreviation
]
case words str of
[w] | Just action <- lookupCmd w -> action
_ -> let helpCmds = [ text name | (True, name, _) <- cmds ]
in throwGhcException $ CmdLineError $ showSDoc dflags
$ hang (text "syntax:") 4
$ hang (text ":show") 6
$ brackets (fsep $ punctuate (text " |") helpCmds)
showiCmd :: String -> GHCi ()
showiCmd str = do
case words str of
["languages"] -> showiLanguages -- backwards compat
["language"] -> showiLanguages
["lang"] -> showiLanguages -- useful abbreviation
_ -> throwGhcException (CmdLineError ("syntax: :showi language"))
showImports :: GHCi ()
showImports = do
st <- getGHCiState
dflags <- getDynFlags
let rem_ctx = reverse (remembered_ctx st)
trans_ctx = transient_ctx st
show_one (IIModule star_m)
= ":module +*" ++ moduleNameString star_m
show_one (IIDecl imp) = showPpr dflags imp
prel_imp
| any isPreludeImport (rem_ctx ++ trans_ctx) = []
| not (xopt LangExt.ImplicitPrelude dflags) = []
| otherwise = ["import Prelude -- implicit"]
trans_comment s = s ++ " -- added automatically" :: String
--
liftIO $ mapM_ putStrLn (prel_imp ++ map show_one rem_ctx
++ map (trans_comment . show_one) trans_ctx)
showModules :: GHCi ()
showModules = do
loaded_mods <- getLoadedModules
-- we want *loaded* modules only, see #1734
let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
mapM_ show_one loaded_mods
getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
getLoadedModules = do
graph <- GHC.getModuleGraph
filterM (GHC.isLoaded . GHC.ms_mod_name) graph
showBindings :: GHCi ()
showBindings = do
bindings <- GHC.getBindings
(insts, finsts) <- GHC.getInsts
docs <- mapM makeDoc (reverse bindings)
-- reverse so the new ones come last
let idocs = map GHC.pprInstanceHdr insts
fidocs = map GHC.pprFamInst finsts
mapM_ printForUserPartWay (docs ++ idocs ++ fidocs)
where
makeDoc (AnId i) = pprTypeAndContents i
makeDoc tt = do
mb_stuff <- GHC.getInfo False (getName tt)
return $ maybe (text "") pprTT mb_stuff
pprTT :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
pprTT (thing, fixity, _cls_insts, _fam_insts)
= pprTyThing thing
$$ show_fixity
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> ppr (GHC.getName thing)
printTyThing :: TyThing -> GHCi ()
printTyThing tyth = printForUser (pprTyThing tyth)
showBkptTable :: GHCi ()
showBkptTable = do
st <- getGHCiState
printForUser $ prettyLocations (breaks st)
showContext :: GHCi ()
showContext = do
resumes <- GHC.getResumeContext
printForUser $ vcat (map pp_resume (reverse resumes))
where
pp_resume res =
ptext (sLit "--> ") <> text (GHC.resumeStmt res)
$$ nest 2 (pprStopped res)
pprStopped :: GHC.Resume -> SDoc
pprStopped res =
ptext (sLit "Stopped in")
<+> ((case mb_mod_name of
Nothing -> empty
Just mod_name -> text (moduleNameString mod_name) <> char '.')
<> text (GHC.resumeDecl res))
<> char ',' <+> ppr (GHC.resumeSpan res)
where
mb_mod_name = moduleName <$> GHC.breakInfo_module <$> GHC.resumeBreakInfo res
showPackages :: GHCi ()
showPackages = do
dflags <- getDynFlags
let pkg_flags = packageFlags dflags
liftIO $ putStrLn $ showSDoc dflags $
text ("active package flags:"++if null pkg_flags then " none" else "") $$
nest 2 (vcat (map pprFlag pkg_flags))
showPaths :: GHCi ()
showPaths = do
dflags <- getDynFlags
liftIO $ do
cwd <- getCurrentDirectory
putStrLn $ showSDoc dflags $
text "current working directory: " $$
nest 2 (text cwd)
let ipaths = importPaths dflags
putStrLn $ showSDoc dflags $
text ("module import search paths:"++if null ipaths then " none" else "") $$
nest 2 (vcat (map text ipaths))
showLanguages :: GHCi ()
showLanguages = getDynFlags >>= liftIO . showLanguages' False
showiLanguages :: GHCi ()
showiLanguages = GHC.getInteractiveDynFlags >>= liftIO . showLanguages' False
showLanguages' :: Bool -> DynFlags -> IO ()
showLanguages' show_all dflags =
putStrLn $ showSDoc dflags $ vcat
[ text "base language is: " <>
case language dflags of
Nothing -> text "Haskell2010"
Just Haskell98 -> text "Haskell98"
Just Haskell2010 -> text "Haskell2010"
, (if show_all then text "all active language options:"
else text "with the following modifiers:") $$
nest 2 (vcat (map (setting xopt) DynFlags.xFlags))
]
where
setting test flag
| quiet = empty
| is_on = text "-X" <> text name
| otherwise = text "-XNo" <> text name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags =
defaultDynFlags (settings dflags) `lang_set`
case language dflags of
Nothing -> Just Haskell2010
other -> other
-- -----------------------------------------------------------------------------
-- Completion
completeCmd :: String -> GHCi ()
completeCmd argLine0 = case parseLine argLine0 of
Just ("repl", resultRange, left) -> do
(unusedLine,compls) <- ghciCompleteWord (reverse left,"")
let compls' = takeRange resultRange compls
liftIO . putStrLn $ unwords [ show (length compls'), show (length compls), show (reverse unusedLine) ]
forM_ (takeRange resultRange compls) $ \(Completion r _ _) -> do
liftIO $ print r
_ -> throwGhcException (CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
where
parseLine argLine
| null argLine = Nothing
| null rest1 = Nothing
| otherwise = (,,) dom <$> resRange <*> s
where
(dom, rest1) = breakSpace argLine
(rng, rest2) = breakSpace rest1
resRange | head rest1 == '"' = parseRange ""
| otherwise = parseRange rng
s | head rest1 == '"' = readMaybe rest1 :: Maybe String
| otherwise = readMaybe rest2
breakSpace = fmap (dropWhile isSpace) . break isSpace
takeRange (lb,ub) = maybe id (drop . pred) lb . maybe id take ub
-- syntax: [n-][m] with semantics "drop (n-1) . take m"
parseRange :: String -> Maybe (Maybe Int,Maybe Int)
parseRange s = case span isDigit s of
(_, "") ->
-- upper limit only
Just (Nothing, bndRead s)
(s1, '-' : s2)
| all isDigit s2 ->
Just (bndRead s1, bndRead s2)
_ ->
Nothing
where
bndRead x = if null x then Nothing else Just (read x)
completeGhciCommand, completeMacro, completeIdentifier, completeModule,
completeSetModule, completeSeti, completeShowiOptions,
completeHomeModule, completeSetOptions, completeShowOptions,
completeHomeModuleOrFile, completeExpression
:: CompletionFunc GHCi
-- | Provide completions for last word in a given string.
--
-- Takes a tuple of two strings. First string is a reversed line to be
-- completed. Second string is likely unused, 'completeCmd' always passes an
-- empty string as second item in tuple.
ghciCompleteWord :: CompletionFunc GHCi
ghciCompleteWord line@(left,_) = case firstWord of
-- If given string starts with `:` colon, and there is only one following
-- word then provide REPL command completions. If there is more than one
-- word complete either filename or builtin ghci commands or macros.
':':cmd | null rest -> completeGhciCommand line
| otherwise -> do
completion <- lookupCompletion cmd
completion line
-- If given string starts with `import` keyword provide module name
-- completions
"import" -> completeModule line
-- otherwise provide identifier completions
_ -> completeExpression line
where
(firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
lookupCompletion ('!':_) = return completeFilename
lookupCompletion c = do
maybe_cmd <- lookupCommand' c
case maybe_cmd of
Just cmd -> return (cmdCompletionFunc cmd)
Nothing -> return completeFilename
completeGhciCommand = wrapCompleter " " $ \w -> do
macros <- ghci_macros <$> getGHCiState
cmds <- ghci_commands `fmap` getGHCiState
let macro_names = map (':':) . map cmdName $ macros
let command_names = map (':':) . map cmdName $ filter (not . cmdHidden) cmds
let{ candidates = case w of
':' : ':' : _ -> map (':':) command_names
_ -> nub $ macro_names ++ command_names }
return $ filter (w `isPrefixOf`) candidates
completeMacro = wrapIdentCompleter $ \w -> do
cmds <- ghci_macros <$> getGHCiState
return (filter (w `isPrefixOf`) (map cmdName cmds))
completeIdentifier line@(left, _) =
-- Note: `left` is a reversed input
case left of
(x:_) | isSymbolChar x -> wrapCompleter (specials ++ spaces) complete line
_ -> wrapIdentCompleter complete line
where
complete w = do
rdrs <- GHC.getRdrNamesInScope
dflags <- GHC.getSessionDynFlags
return (filter (w `isPrefixOf`) (map (showPpr dflags) rdrs))
completeModule = wrapIdentCompleter $ \w -> do
dflags <- GHC.getSessionDynFlags
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ filter (w `isPrefixOf`)
$ map (showPpr dflags) $ loaded_mods ++ pkg_mods
completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
dflags <- GHC.getSessionDynFlags
modules <- case m of
Just '-' -> do
imports <- GHC.getContext
return $ map iiModuleName imports
_ -> do
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ loaded_mods ++ pkg_mods
return $ filter (w `isPrefixOf`) $ map (showPpr dflags) modules
completeHomeModule = wrapIdentCompleter listHomeModules
listHomeModules :: String -> GHCi [String]
listHomeModules w = do
g <- GHC.getModuleGraph
let home_mods = map GHC.ms_mod_name g
dflags <- getDynFlags
return $ sort $ filter (w `isPrefixOf`)
$ map (showPpr dflags) home_mods
completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = "args":"prog":"prompt":"prompt2":"editor":"stop":flagList
flagList = map head $ group $ sort allNonDeprecatedFlags
completeSeti = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) flagList)
where flagList = map head $ group $ sort allNonDeprecatedFlags
completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = ["args", "prog", "prompt", "prompt2", "editor", "stop",
"modules", "bindings", "linker", "breaks",
"context", "packages", "paths", "language", "imports"]
completeShowiOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) ["language"])
completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
$ unionComplete (fmap (map simpleCompletion) . listHomeModules)
listFiles
unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete f1 f2 line = do
cs1 <- f1 line
cs2 <- f2 line
return (cs1 ++ cs2)
wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter breakChars fun = completeWord Nothing breakChars
$ fmap (map simpleCompletion . nubSort) . fun
wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter = wrapCompleter word_break_chars
wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
$ \rest -> fmap (map simpleCompletion . nubSort) . fun (getModifier rest)
where
getModifier = find (`elem` modifChars)
-- | Return a list of visible module names for autocompletion.
-- (NB: exposed != visible)
allVisibleModules :: DynFlags -> [ModuleName]
allVisibleModules dflags = listVisibleModuleNames dflags
completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
completeIdentifier
-- -----------------------------------------------------------------------------
-- commands for debugger
sprintCmd, printCmd, forceCmd :: String -> GHCi ()
sprintCmd = pprintCommand False False
printCmd = pprintCommand True False
forceCmd = pprintCommand False True
pprintCommand :: Bool -> Bool -> String -> GHCi ()
pprintCommand bind force str = do
pprintClosureCommand bind force str
stepCmd :: String -> GHCi ()
stepCmd arg = withSandboxOnly ":step" $ step arg
where
step [] = doContinue (const True) GHC.SingleStep
step expression = runStmt expression GHC.SingleStep >> return ()
stepLocalCmd :: String -> GHCi ()
stepLocalCmd arg = withSandboxOnly ":steplocal" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just loc -> do
Just md <- getCurrentBreakModule
current_toplevel_decl <- enclosingTickSpan md loc
doContinue (`isSubspanOf` RealSrcSpan current_toplevel_decl) GHC.SingleStep
stepModuleCmd :: String -> GHCi ()
stepModuleCmd arg = withSandboxOnly ":stepmodule" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just pan -> do
let f some_span = srcSpanFileName_maybe pan == srcSpanFileName_maybe some_span
doContinue f GHC.SingleStep
-- | Returns the span of the largest tick containing the srcspan given
enclosingTickSpan :: Module -> SrcSpan -> GHCi RealSrcSpan
enclosingTickSpan _ (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
enclosingTickSpan md (RealSrcSpan src) = do
ticks <- getTickArray md
let line = srcSpanStartLine src
ASSERT(inRange (bounds ticks) line) do
let enclosing_spans = [ pan | (_,pan) <- ticks ! line
, realSrcSpanEnd pan >= realSrcSpanEnd src]
return . head . sortBy leftmostLargestRealSrcSpan $ enclosing_spans
where
leftmostLargestRealSrcSpan :: RealSrcSpan -> RealSrcSpan -> Ordering
leftmostLargestRealSrcSpan a b =
(realSrcSpanStart a `compare` realSrcSpanStart b)
`thenCmp`
(realSrcSpanEnd b `compare` realSrcSpanEnd a)
traceCmd :: String -> GHCi ()
traceCmd arg
= withSandboxOnly ":trace" $ tr arg
where
tr [] = doContinue (const True) GHC.RunAndLogSteps
tr expression = runStmt expression GHC.RunAndLogSteps >> return ()
continueCmd :: String -> GHCi ()
continueCmd = noArgs $ withSandboxOnly ":continue" $ doContinue (const True) GHC.RunToCompletion
-- doContinue :: SingleStep -> GHCi ()
doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue pre step = do
runResult <- resume pre step
_ <- afterRunStmt pre runResult
return ()
abandonCmd :: String -> GHCi ()
abandonCmd = noArgs $ withSandboxOnly ":abandon" $ do
b <- GHC.abandon -- the prompt will change to indicate the new context
when (not b) $ liftIO $ putStrLn "There is no computation running."
deleteCmd :: String -> GHCi ()
deleteCmd argLine = withSandboxOnly ":delete" $ do
deleteSwitch $ words argLine
where
deleteSwitch :: [String] -> GHCi ()
deleteSwitch [] =
liftIO $ putStrLn "The delete command requires at least one argument."
-- delete all break points
deleteSwitch ("*":_rest) = discardActiveBreakPoints
deleteSwitch idents = do
mapM_ deleteOneBreak idents
where
deleteOneBreak :: String -> GHCi ()
deleteOneBreak str
| all isDigit str = deleteBreak (read str)
| otherwise = return ()
historyCmd :: String -> GHCi ()
historyCmd arg
| null arg = history 20
| all isDigit arg = history (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :history [num]"
where
history num = do
resumes <- GHC.getResumeContext
case resumes of
[] -> liftIO $ putStrLn "Not stopped at a breakpoint"
(r:_) -> do
let hist = GHC.resumeHistory r
(took,rest) = splitAt num hist
case hist of
[] -> liftIO $ putStrLn $
"Empty history. Perhaps you forgot to use :trace?"
_ -> do
pans <- mapM GHC.getHistorySpan took
let nums = map (printf "-%-3d:") [(1::Int)..]
names = map GHC.historyEnclosingDecls took
printForUser (vcat(zipWith3
(\x y z -> x <+> y <+> z)
(map text nums)
(map (bold . hcat . punctuate colon . map text) names)
(map (parens . ppr) pans)))
liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
bold :: SDoc -> SDoc
bold c | do_bold = text start_bold <> c <> text end_bold
| otherwise = c
backCmd :: String -> GHCi ()
backCmd arg
| null arg = back 1
| all isDigit arg = back (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :back [num]"
where
back num = withSandboxOnly ":back" $ do
(names, _, pan, _) <- GHC.back num
printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
forwardCmd :: String -> GHCi ()
forwardCmd arg
| null arg = forward 1
| all isDigit arg = forward (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :back [num]"
where
forward num = withSandboxOnly ":forward" $ do
(names, ix, pan, _) <- GHC.forward num
printForUser $ (if (ix == 0)
then ptext (sLit "Stopped at")
else ptext (sLit "Logged breakpoint at")) <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
-- handle the "break" command
breakCmd :: String -> GHCi ()
breakCmd argLine = withSandboxOnly ":break" $ breakSwitch $ words argLine
breakSwitch :: [String] -> GHCi ()
breakSwitch [] = do
liftIO $ putStrLn "The break command requires at least one argument."
breakSwitch (arg1:rest)
| looksLikeModuleName arg1 && not (null rest) = do
md <- wantInterpretedModule arg1
breakByModule md rest
| all isDigit arg1 = do
imports <- GHC.getContext
case iiModules imports of
(mn : _) -> do
md <- lookupModuleName mn
breakByModuleLine md (read arg1) rest
[] -> do
liftIO $ putStrLn "No modules are loaded with debugging support."
| otherwise = do -- try parsing it as an identifier
wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
maybe_info <- GHC.getModuleInfo (GHC.nameModule name)
case maybe_info of
Nothing -> noCanDo name (ptext (sLit "cannot get module info"))
Just minf ->
ASSERT( isExternalName name )
findBreakAndSet (GHC.nameModule name) $
findBreakForBind name (GHC.modInfoModBreaks minf)
where
noCanDo n why = printForUser $
text "cannot set breakpoint on " <> ppr n <> text ": " <> why
breakByModule :: Module -> [String] -> GHCi ()
breakByModule md (arg1:rest)
| all isDigit arg1 = do -- looks like a line number
breakByModuleLine md (read arg1) rest
breakByModule _ _
= breakSyntax
breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
breakByModuleLine md line args
| [] <- args = findBreakAndSet md $ maybeToList . findBreakByLine line
| [col] <- args, all isDigit col =
findBreakAndSet md $ maybeToList . findBreakByCoord Nothing (line, read col)
| otherwise = breakSyntax
breakSyntax :: a
breakSyntax = throwGhcException (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
findBreakAndSet :: Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet md lookupTickTree = do
tickArray <- getTickArray md
(breakArray, _) <- getModBreak md
case lookupTickTree tickArray of
[] -> liftIO $ putStrLn $ "No breakpoints found at that location."
some -> mapM_ (breakAt breakArray) some
where
breakAt breakArray (tick, pan) = do
setBreakFlag True breakArray tick
(alreadySet, nm) <-
recordBreak $ BreakLocation
{ breakModule = md
, breakLoc = RealSrcSpan pan
, breakTick = tick
, onBreakCmd = ""
}
printForUser $
text "Breakpoint " <> ppr nm <>
if alreadySet
then text " was already set at " <> ppr pan
else text " activated at " <> ppr pan
-- When a line number is specified, the current policy for choosing
-- the best breakpoint is this:
-- - the leftmost complete subexpression on the specified line, or
-- - the leftmost subexpression starting on the specified line, or
-- - the rightmost subexpression enclosing the specified line
--
findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,RealSrcSpan)
findBreakByLine line arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (leftmostLargestRealSrcSpan `on` snd) comp) `mplus`
listToMaybe (sortBy (compare `on` snd) incomp) `mplus`
listToMaybe (sortBy (flip compare `on` snd) ticks)
where
ticks = arr ! line
starts_here = [ (ix,pan) | (ix, pan) <- ticks,
GHC.srcSpanStartLine pan == line ]
(comp, incomp) = partition ends_here starts_here
where ends_here (_,pan) = GHC.srcSpanEndLine pan == line
-- The aim is to find the breakpionts for all the RHSs of the
-- equations corresponding to a binding. So we find all breakpoints
-- for
-- (a) this binder only (not a nested declaration)
-- (b) that do not have an enclosing breakpoint
findBreakForBind :: Name -> GHC.ModBreaks -> TickArray
-> [(BreakIndex,RealSrcSpan)]
findBreakForBind name modbreaks _ = filter (not . enclosed) ticks
where
ticks = [ (index, span)
| (index, [n]) <- assocs (GHC.modBreaks_decls modbreaks),
n == occNameString (nameOccName name),
RealSrcSpan span <- [GHC.modBreaks_locs modbreaks ! index] ]
enclosed (_,sp0) = any subspan ticks
where subspan (_,sp) = sp /= sp0 &&
realSrcSpanStart sp <= realSrcSpanStart sp0 &&
realSrcSpanEnd sp0 <= realSrcSpanEnd sp
findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
-> Maybe (BreakIndex,RealSrcSpan)
findBreakByCoord mb_file (line, col) arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (flip compare `on` snd) contains ++
sortBy (compare `on` snd) after_here)
where
ticks = arr ! line
-- the ticks that span this coordinate
contains = [ tick | tick@(_,pan) <- ticks, RealSrcSpan pan `spans` (line,col),
is_correct_file pan ]
is_correct_file pan
| Just f <- mb_file = GHC.srcSpanFile pan == f
| otherwise = True
after_here = [ tick | tick@(_,pan) <- ticks,
GHC.srcSpanStartLine pan == line,
GHC.srcSpanStartCol pan >= col ]
-- For now, use ANSI bold on terminals that we know support it.
-- Otherwise, we add a line of carets under the active expression instead.
-- In particular, on Windows and when running the testsuite (which sets
-- TERM to vt100 for other reasons) we get carets.
-- We really ought to use a proper termcap/terminfo library.
do_bold :: Bool
do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
where mTerm = System.Environment.getEnv "TERM"
`catchIO` \_ -> return "TERM not set"
start_bold :: String
start_bold = "\ESC[1m"
end_bold :: String
end_bold = "\ESC[0m"
-----------------------------------------------------------------------------
-- :where
whereCmd :: String -> GHCi ()
whereCmd = noArgs $ do
mstrs <- getCallStackAtCurrentBreakpoint
case mstrs of
Nothing -> return ()
Just strs -> liftIO $ putStrLn (renderStack strs)
-----------------------------------------------------------------------------
-- :list
listCmd :: String -> InputT GHCi ()
listCmd c = listCmd' c
listCmd' :: String -> InputT GHCi ()
listCmd' "" = do
mb_span <- lift getCurrentBreakSpan
case mb_span of
Nothing ->
printForUser $ text "Not stopped at a breakpoint; nothing to list"
Just (RealSrcSpan pan) ->
listAround pan True
Just pan@(UnhelpfulSpan _) ->
do resumes <- GHC.getResumeContext
case resumes of
[] -> panic "No resumes"
(r:_) ->
do let traceIt = case GHC.resumeHistory r of
[] -> text "rerunning with :trace,"
_ -> empty
doWhat = traceIt <+> text ":back then :list"
printForUser (text "Unable to list source for" <+>
ppr pan
$$ text "Try" <+> doWhat)
listCmd' str = list2 (words str)
list2 :: [String] -> InputT GHCi ()
list2 [arg] | all isDigit arg = do
imports <- GHC.getContext
case iiModules imports of
[] -> liftIO $ putStrLn "No module to list"
(mn : _) -> do
md <- lift $ lookupModuleName mn
listModuleLine md (read arg)
list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
md <- wantInterpretedModule arg1
listModuleLine md (read arg2)
list2 [arg] = do
wantNameFromInterpretedModule noCanDo arg $ \name -> do
let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
case loc of
RealSrcLoc l ->
do tickArray <- ASSERT( isExternalName name )
lift $ getTickArray (GHC.nameModule name)
let mb_span = findBreakByCoord (Just (GHC.srcLocFile l))
(GHC.srcLocLine l, GHC.srcLocCol l)
tickArray
case mb_span of
Nothing -> listAround (realSrcLocSpan l) False
Just (_, pan) -> listAround pan False
UnhelpfulLoc _ ->
noCanDo name $ text "can't find its location: " <>
ppr loc
where
noCanDo n why = printForUser $
text "cannot list source code for " <> ppr n <> text ": " <> why
list2 _other =
liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
listModuleLine :: Module -> Int -> InputT GHCi ()
listModuleLine modl line = do
graph <- GHC.getModuleGraph
let this = filter ((== modl) . GHC.ms_mod) graph
case this of
[] -> panic "listModuleLine"
summ:_ -> do
let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
loc = mkRealSrcLoc (mkFastString (filename)) line 0
listAround (realSrcLocSpan loc) False
-- | list a section of a source file around a particular SrcSpan.
-- If the highlight flag is True, also highlight the span using
-- start_bold\/end_bold.
-- GHC files are UTF-8, so we can implement this by:
-- 1) read the file in as a BS and syntax highlight it as before
-- 2) convert the BS to String using utf-string, and write it out.
-- It would be better if we could convert directly between UTF-8 and the
-- console encoding, of course.
listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
listAround pan do_highlight = do
contents <- liftIO $ BS.readFile (unpackFS file)
-- Drop carriage returns to avoid duplicates, see #9367.
let ls = BS.split '\n' $ BS.filter (/= '\r') contents
ls' = take (line2 - line1 + 1 + pad_before + pad_after) $
drop (line1 - 1 - pad_before) $ ls
fst_line = max 1 (line1 - pad_before)
line_nos = [ fst_line .. ]
highlighted | do_highlight = zipWith highlight line_nos ls'
| otherwise = [\p -> BS.concat[p,l] | l <- ls']
bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
prefixed = zipWith ($) highlighted bs_line_nos
output = BS.intercalate (BS.pack "\n") prefixed
utf8Decoded <- liftIO $ BS.useAsCStringLen output
$ \(p,n) -> utf8DecodeString (castPtr p) n
liftIO $ putStrLn utf8Decoded
where
file = GHC.srcSpanFile pan
line1 = GHC.srcSpanStartLine pan
col1 = GHC.srcSpanStartCol pan - 1
line2 = GHC.srcSpanEndLine pan
col2 = GHC.srcSpanEndCol pan - 1
pad_before | line1 == 1 = 0
| otherwise = 1
pad_after = 1
highlight | do_bold = highlight_bold
| otherwise = highlight_carets
highlight_bold no line prefix
| no == line1 && no == line2
= let (a,r) = BS.splitAt col1 line
(b,c) = BS.splitAt (col2-col1) r
in
BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
| no == line1
= let (a,b) = BS.splitAt col1 line in
BS.concat [prefix, a, BS.pack start_bold, b]
| no == line2
= let (a,b) = BS.splitAt col2 line in
BS.concat [prefix, a, BS.pack end_bold, b]
| otherwise = BS.concat [prefix, line]
highlight_carets no line prefix
| no == line1 && no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
BS.replicate (col2-col1) '^']
| no == line1
= BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
prefix, line]
| no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
BS.pack "^^"]
| otherwise = BS.concat [prefix, line]
where
indent = BS.pack (" " ++ replicate (length (show no)) ' ')
nl = BS.singleton '\n'
-- --------------------------------------------------------------------------
-- Tick arrays
getTickArray :: Module -> GHCi TickArray
getTickArray modl = do
st <- getGHCiState
let arrmap = tickarrays st
case lookupModuleEnv arrmap modl of
Just arr -> return arr
Nothing -> do
(_breakArray, ticks) <- getModBreak modl
let arr = mkTickArray (assocs ticks)
setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
return arr
discardTickArrays :: GHCi ()
discardTickArrays = modifyGHCiState (\st -> st {tickarrays = emptyModuleEnv})
mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
mkTickArray ticks
= accumArray (flip (:)) [] (1, max_line)
[ (line, (nm,pan)) | (nm,RealSrcSpan pan) <- ticks, line <- srcSpanLines pan ]
where
max_line = foldr max 0 [ GHC.srcSpanEndLine sp | (_, RealSrcSpan sp) <- ticks ]
srcSpanLines pan = [ GHC.srcSpanStartLine pan .. GHC.srcSpanEndLine pan ]
-- don't reset the counter back to zero?
discardActiveBreakPoints :: GHCi ()
discardActiveBreakPoints = do
st <- getGHCiState
mapM_ (turnOffBreak.snd) (breaks st)
setGHCiState $ st { breaks = [] }
deleteBreak :: Int -> GHCi ()
deleteBreak identity = do
st <- getGHCiState
let oldLocations = breaks st
(this,rest) = partition (\loc -> fst loc == identity) oldLocations
if null this
then printForUser (text "Breakpoint" <+> ppr identity <+>
text "does not exist")
else do
mapM_ (turnOffBreak.snd) this
setGHCiState $ st { breaks = rest }
turnOffBreak :: BreakLocation -> GHCi ()
turnOffBreak loc = do
(arr, _) <- getModBreak (breakModule loc)
hsc_env <- GHC.getSession
liftIO $ enableBreakpoint hsc_env arr (breakTick loc) False
getModBreak :: Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak m = do
Just mod_info <- GHC.getModuleInfo m
let modBreaks = GHC.modInfoModBreaks mod_info
let arr = GHC.modBreaks_flags modBreaks
let ticks = GHC.modBreaks_locs modBreaks
return (arr, ticks)
setBreakFlag :: Bool -> ForeignRef BreakArray -> Int -> GHCi ()
setBreakFlag toggle arr i = do
hsc_env <- GHC.getSession
liftIO $ enableBreakpoint hsc_env arr i toggle
-- ---------------------------------------------------------------------------
-- User code exception handling
-- This is the exception handler for exceptions generated by the
-- user's code and exceptions coming from children sessions;
-- it normally just prints out the exception. The
-- handler must be recursive, in case showing the exception causes
-- more exceptions to be raised.
--
-- Bugfix: if the user closed stdout or stderr, the flushing will fail,
-- raising another exception. We therefore don't put the recursive
-- handler arond the flushing operation, so if stderr is closed
-- GHCi will just die gracefully rather than going into an infinite loop.
handler :: SomeException -> GHCi Bool
handler exception = do
flushInterpBuffers
liftIO installSignalHandlers
ghciHandle handler (showException exception >> return False)
showException :: SomeException -> GHCi ()
showException se =
liftIO $ case fromException se of
-- omit the location for CmdLineError:
Just (CmdLineError s) -> putException s
-- ditto:
Just other_ghc_ex -> putException (show other_ghc_ex)
Nothing ->
case fromException se of
Just UserInterrupt -> putException "Interrupted."
_ -> putException ("*** Exception: " ++ show se)
where
putException = hPutStrLn stderr
-----------------------------------------------------------------------------
-- recursive exception handlers
-- Don't forget to unblock async exceptions in the handler, or if we're
-- in an exception loop (eg. let a = error a in a) the ^C exception
-- may never be delivered. Thanks to Marcin for pointing out the bug.
ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
ghciHandle h m = gmask $ \restore -> do
-- Force dflags to avoid leaking the associated HscEnv
!dflags <- getDynFlags
gcatch (restore (GHC.prettyPrintGhcErrors dflags m)) $ \e -> restore (h e)
ghciTry :: GHCi a -> GHCi (Either SomeException a)
ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
tryBool :: GHCi a -> GHCi Bool
tryBool m = do
r <- ghciTry m
case r of
Left _ -> return False
Right _ -> return True
-- ----------------------------------------------------------------------------
-- Utils
lookupModule :: GHC.GhcMonad m => String -> m Module
lookupModule mName = lookupModuleName (GHC.mkModuleName mName)
lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
lookupModuleName mName = GHC.lookupModule mName Nothing
isHomeModule :: Module -> Bool
isHomeModule m = GHC.moduleUnitId m == mainUnitId
-- TODO: won't work if home dir is encoded.
-- (changeDirectory may not work either in that case.)
expandPath :: MonadIO m => String -> InputT m String
expandPath = liftIO . expandPathIO
expandPathIO :: String -> IO String
expandPathIO p =
case dropWhile isSpace p of
('~':d) -> do
tilde <- getHomeDirectory -- will fail if HOME not defined
return (tilde ++ '/':d)
other ->
return other
wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
wantInterpretedModule str = wantInterpretedModuleName (GHC.mkModuleName str)
wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName modname = do
modl <- lookupModuleName modname
let str = moduleNameString modname
dflags <- getDynFlags
when (GHC.moduleUnitId modl /= thisPackage dflags) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
is_interpreted <- GHC.moduleIsInterpreted modl
when (not is_interpreted) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
return modl
wantNameFromInterpretedModule :: GHC.GhcMonad m
=> (Name -> SDoc -> m ())
-> String
-> (Name -> m ())
-> m ()
wantNameFromInterpretedModule noCanDo str and_then =
handleSourceError GHC.printException $ do
names <- GHC.parseName str
case names of
[] -> return ()
(n:_) -> do
let modl = ASSERT( isExternalName n ) GHC.nameModule n
if not (GHC.isExternalName n)
then noCanDo n $ ppr n <>
text " is not defined in an interpreted module"
else do
is_interpreted <- GHC.moduleIsInterpreted modl
if not is_interpreted
then noCanDo n $ text "module " <> ppr modl <>
text " is not interpreted"
else and_then n
| GaloisInc/halvm-ghc | ghc/GHCi/UI.hs | bsd-3-clause | 141,934 | 11 | 104 | 40,582 | 34,741 | 17,308 | 17,433 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
module Tinc.RecentCheck (
isRecent
, markRecent
, tincEnvCreationTime
) where
import Data.Maybe
import Data.Time
import System.Directory
import System.FilePath
import Tinc.Facts
import Tinc.Nix
import Tinc.Sandbox
import Tinc.GhcInfo
import qualified Tinc.Config as Tinc
import qualified Hpack.Config as Hpack
import Tinc.Freeze (freezeFile)
import Util
isRecent :: Maybe UTCTime -> IO Bool
isRecent envCreationTime = case envCreationTime of
Just packageMTime -> modificationTime freezeFile >>= \case
Just freezeMTime -> do
cabalFiles <- getCabalFiles "."
xs <- mapM modificationTime (Tinc.configFile : Hpack.packageConfig : cabalFiles)
return $ maximum (freezeMTime : catMaybes xs) < packageMTime
Nothing -> return False
Nothing -> return False
tincEnvCreationTime :: Facts -> IO (Maybe UTCTime)
tincEnvCreationTime Facts{..} = if factsUseNix
then packageDotNixCreationTime
else sandboxCreationTime factsGhcInfo
modificationTime :: FilePath -> IO (Maybe UTCTime)
modificationTime file = do
exists <- doesFileExist file
if exists then Just <$> getModificationTime file else return Nothing
packageDotNixCreationTime :: IO (Maybe UTCTime)
packageDotNixCreationTime = modificationTime resolverFile
recentMarker :: GhcInfo -> FilePath
recentMarker ghcInfo = cabalSandboxDirectory </> ghcFlavor ghcInfo ++ ".tinc"
sandboxCreationTime :: GhcInfo -> IO (Maybe UTCTime)
sandboxCreationTime ghcInfo = do
modificationTime $ recentMarker ghcInfo
markRecent :: GhcInfo -> IO ()
markRecent ghcInfo = do
writeFile (recentMarker ghcInfo) ""
| haskell-tinc/tinc | src/Tinc/RecentCheck.hs | bsd-3-clause | 1,741 | 0 | 19 | 351 | 443 | 226 | 217 | 45 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Haddock
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module deals with the @haddock@ and @hscolour@ commands.
-- It uses information about installed packages (from @ghc-pkg@) to find the
-- locations of documentation for dependent packages, so it can create links.
--
-- The @hscolour@ support allows generating HTML versions of the original
-- source, with coloured syntax highlighting.
module Distribution.Simple.Haddock (
haddock, hscolour,
haddockPackagePaths
) where
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
-- local
import Distribution.Package
( PackageIdentifier(..)
, Package(..)
, PackageName(..), packageName )
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), usedExtensions
, hcSharedOptions
, Library(..), hasLibs, Executable(..)
, TestSuite(..), TestSuiteInterface(..)
, Benchmark(..), BenchmarkInterface(..) )
import Distribution.Simple.Compiler
( Compiler, compilerInfo, CompilerFlavor(..)
, compilerFlavor, compilerCompatVersion )
import Distribution.Simple.Program.GHC
( GhcOptions(..), GhcDynLinkMode(..), renderGhcOptions )
import Distribution.Simple.Program
( ConfiguredProgram(..), lookupProgramVersion, requireProgramVersion
, rawSystemProgram, rawSystemProgramStdout
, hscolourProgram, haddockProgram )
import Distribution.Simple.PreProcess
( PPSuffixHandler, preprocessComponent)
import Distribution.Simple.Setup
( defaultHscolourFlags
, Flag(..), toFlag, flagToMaybe, flagToList, fromFlag
, HaddockFlags(..), HscolourFlags(..) )
import Distribution.Simple.Build (initialBuildSteps)
import Distribution.Simple.InstallDirs
( InstallDirs(..)
, PathTemplateEnv, PathTemplate, PathTemplateVariable(..)
, toPathTemplate, fromPathTemplate
, substPathTemplate, initialPathTemplateEnv )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), Component(..), ComponentLocalBuildInfo(..)
, withAllComponentsInBuildOrder )
import Distribution.Simple.BuildPaths
( haddockName, hscolourPref, autogenModulesDir)
import Distribution.Simple.PackageIndex (dependencyClosure)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo_(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import Distribution.Simple.Utils
( die, copyFileTo, warn, notice, intercalate, setupMessage
, createDirectoryIfMissingVerbose
, TempFileOptions(..), defaultTempFileOptions
, withTempFileEx, copyFileVerbose
, withTempDirectoryEx, matchFileGlob
, findFileWithExtension, findFile )
import Distribution.Text
( display, simpleParse )
import Distribution.Utils.NubList
( toNubListR )
import Distribution.Verbosity
import Language.Haskell.Extension
import Control.Monad ( when, forM_ )
import Data.Either ( rights )
import Data.Foldable ( traverse_ )
import Data.Monoid
import Data.Maybe ( fromMaybe, listToMaybe )
import System.Directory (doesFileExist)
import System.FilePath ( (</>), (<.>)
, normalise, splitPath, joinPath, isAbsolute )
import System.IO (hClose, hPutStrLn, hSetEncoding, utf8)
import Distribution.Version
-- ------------------------------------------------------------------------------
-- Types
-- | A record that represents the arguments to the haddock executable, a product
-- monoid.
data HaddockArgs = HaddockArgs {
argInterfaceFile :: Flag FilePath,
-- ^ Path to the interface file, relative to argOutputDir, required.
argPackageName :: Flag PackageIdentifier,
-- ^ Package name, required.
argHideModules :: (All,[ModuleName.ModuleName]),
-- ^ (Hide modules ?, modules to hide)
argIgnoreExports :: Any,
-- ^ Ignore export lists in modules?
argLinkSource :: Flag (Template,Template,Template),
-- ^ (Template for modules, template for symbols, template for lines).
argCssFile :: Flag FilePath,
-- ^ Optional custom CSS file.
argContents :: Flag String,
-- ^ Optional URL to contents page.
argVerbose :: Any,
argOutput :: Flag [Output],
-- ^ HTML or Hoogle doc or both? Required.
argInterfaces :: [(FilePath, Maybe String)],
-- ^ [(Interface file, URL to the HTML docs for links)].
argOutputDir :: Directory,
-- ^ Where to generate the documentation.
argTitle :: Flag String,
-- ^ Page title, required.
argPrologue :: Flag String,
-- ^ Prologue text, required.
argGhcOptions :: Flag (GhcOptions, Version),
-- ^ Additional flags to pass to GHC.
argGhcLibDir :: Flag FilePath,
-- ^ To find the correct GHC, required.
argTargets :: [FilePath]
-- ^ Modules to process.
}
-- | The FilePath of a directory, it's a monoid under '(</>)'.
newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord)
unDir :: Directory -> FilePath
unDir = joinPath . filter (\p -> p /="./" && p /= ".") . splitPath . unDir'
type Template = String
data Output = Html | Hoogle
-- ------------------------------------------------------------------------------
-- Haddock support
haddock :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HaddockFlags
-> IO ()
haddock pkg_descr _ _ haddockFlags
| not (hasLibs pkg_descr)
&& not (fromFlag $ haddockExecutables haddockFlags)
&& not (fromFlag $ haddockTestSuites haddockFlags)
&& not (fromFlag $ haddockBenchmarks haddockFlags) =
warn (fromFlag $ haddockVerbosity haddockFlags) $
"No documentation was generated as this package does not contain "
++ "a library. Perhaps you want to use the --executables, --tests or"
++ " --benchmarks flags."
haddock pkg_descr lbi suffixes flags = do
setupMessage verbosity "Running Haddock for" (packageId pkg_descr)
(confHaddock, version, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (Version [2,0] [])) (withPrograms lbi)
-- various sanity checks
when ( flag haddockHoogle
&& version < Version [2,2] []) $
die "haddock 2.0 and 2.1 do not support the --hoogle flag."
haddockGhcVersionStr <- rawSystemProgramStdout verbosity confHaddock
["--ghc-version"]
case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of
(Nothing, _) -> die "Could not get GHC version from Haddock"
(_, Nothing) -> die "Could not get GHC version from compiler"
(Just haddockGhcVersion, Just ghcVersion)
| haddockGhcVersion == ghcVersion -> return ()
| otherwise -> die $
"Haddock's internal GHC version must match the configured "
++ "GHC version.\n"
++ "The GHC version is " ++ display ghcVersion ++ " but "
++ "haddock is using GHC version " ++ display haddockGhcVersion
-- the tools match the requests, we can proceed
initialBuildSteps (flag haddockDistPref) pkg_descr lbi verbosity
when (flag haddockHscolour) $
hscolour' (warn verbosity) pkg_descr lbi suffixes
(defaultHscolourFlags `mappend` haddockToHscolour flags)
libdirArgs <- getGhcLibDir verbosity lbi
let commonArgs = mconcat
[ libdirArgs
, fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags
, fromPackageDescription pkg_descr ]
let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes
withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do
pre component
let
doExe com = case (compToExe com) of
Just exe -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
exeArgs <- fromExecutable verbosity tmp lbi exe clbi htmlTemplate
version
let exeArgs' = commonArgs `mappend` exeArgs
runHaddock verbosity tmpFileOpts comp confHaddock exeArgs'
Nothing -> do
warn (fromFlag $ haddockVerbosity flags)
"Unsupported component, skipping..."
return ()
case component of
CLib lib -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
libArgs <- fromLibrary verbosity tmp lbi lib clbi htmlTemplate
version
let libArgs' = commonArgs `mappend` libArgs
runHaddock verbosity tmpFileOpts comp confHaddock libArgs'
CExe _ -> when (flag haddockExecutables) $ doExe component
CTest _ -> when (flag haddockTestSuites) $ doExe component
CBench _ -> when (flag haddockBenchmarks) $ doExe component
forM_ (extraDocFiles pkg_descr) $ \ fpath -> do
files <- matchFileGlob fpath
forM_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs)
where
verbosity = flag haddockVerbosity
keepTempFiles = flag haddockKeepTempFiles
comp = compiler lbi
tmpFileOpts = defaultTempFileOptions { optKeepTempFiles = keepTempFiles }
flag f = fromFlag $ f flags
htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation
$ flags
-- ------------------------------------------------------------------------------
-- Contributions to HaddockArgs.
fromFlags :: PathTemplateEnv -> HaddockFlags -> HaddockArgs
fromFlags env flags =
mempty {
argHideModules = (maybe mempty (All . not)
$ flagToMaybe (haddockInternal flags), mempty),
argLinkSource = if fromFlag (haddockHscolour flags)
then Flag ("src/%{MODULE/./-}.html"
,"src/%{MODULE/./-}.html#%{NAME}"
,"src/%{MODULE/./-}.html#line-%{LINE}")
else NoFlag,
argCssFile = haddockCss flags,
argContents = fmap (fromPathTemplate . substPathTemplate env)
(haddockContents flags),
argVerbose = maybe mempty (Any . (>= deafening))
. flagToMaybe $ haddockVerbosity flags,
argOutput =
Flag $ case [ Html | Flag True <- [haddockHtml flags] ] ++
[ Hoogle | Flag True <- [haddockHoogle flags] ]
of [] -> [ Html ]
os -> os,
argOutputDir = maybe mempty Dir . flagToMaybe $ haddockDistPref flags
}
fromPackageDescription :: PackageDescription -> HaddockArgs
fromPackageDescription pkg_descr =
mempty { argInterfaceFile = Flag $ haddockName pkg_descr,
argPackageName = Flag $ packageId $ pkg_descr,
argOutputDir = Dir $ "doc" </> "html"
</> display (packageName pkg_descr),
argPrologue = Flag $ if null desc then synopsis pkg_descr
else desc,
argTitle = Flag $ showPkg ++ subtitle
}
where
desc = PD.description pkg_descr
showPkg = display (packageId pkg_descr)
subtitle | null (synopsis pkg_descr) = ""
| otherwise = ": " ++ synopsis pkg_descr
componentGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-> GhcOptions
componentGhcOptions verbosity lbi bi clbi odir =
let f = case compilerFlavor (compiler lbi) of
GHC -> GHC.componentGhcOptions
GHCJS -> GHCJS.componentGhcOptions
_ -> error $
"Distribution.Simple.Haddock.componentGhcOptions:" ++
"haddock only supports GHC and GHCJS"
in f verbosity lbi bi clbi odir
fromLibrary :: Verbosity
-> FilePath
-> LocalBuildInfo -> Library -> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> IO HaddockArgs
fromLibrary verbosity tmp lbi lib clbi htmlTemplate haddockVersion = do
inFiles <- map snd `fmap` getLibSourceFiles lbi lib
ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate
let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) {
-- Noooooooooo!!!!!111
-- haddock stomps on our precious .hi
-- and .o files. Workaround by telling
-- haddock to write them elsewhere.
ghcOptObjDir = toFlag tmp,
ghcOptHiDir = toFlag tmp,
ghcOptStubDir = toFlag tmp,
ghcOptPackageKey = toFlag $ pkgKey lbi
} `mappend` getGhcCppOpts haddockVersion bi
sharedOpts = vanillaOpts {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra =
toNubListR $ hcSharedOptions GHC bi
}
opts <- if withVanillaLib lbi
then return vanillaOpts
else if withSharedLib lbi
then return sharedOpts
else die $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argHideModules = (mempty,otherModules $ bi),
argGhcOptions = toFlag (opts, ghcVersion),
argTargets = inFiles
}
where
bi = libBuildInfo lib
fromExecutable :: Verbosity
-> FilePath
-> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> IO HaddockArgs
fromExecutable verbosity tmp lbi exe clbi htmlTemplate haddockVersion = do
inFiles <- map snd `fmap` getExeSourceFiles lbi exe
ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate
let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) {
-- Noooooooooo!!!!!111
-- haddock stomps on our precious .hi
-- and .o files. Workaround by telling
-- haddock to write them elsewhere.
ghcOptObjDir = toFlag tmp,
ghcOptHiDir = toFlag tmp,
ghcOptStubDir = toFlag tmp
} `mappend` getGhcCppOpts haddockVersion bi
sharedOpts = vanillaOpts {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra =
toNubListR $ hcSharedOptions GHC bi
}
opts <- if withVanillaLib lbi
then return vanillaOpts
else if withSharedLib lbi
then return sharedOpts
else die $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argGhcOptions = toFlag (opts, ghcVersion),
argOutputDir = Dir (exeName exe),
argTitle = Flag (exeName exe),
argTargets = inFiles
}
where
bi = buildInfo exe
compToExe :: Component -> Maybe Executable
compToExe comp =
case comp of
CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } ->
Just Executable {
exeName = testName test,
modulePath = f,
buildInfo = testBuildInfo test
}
CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } ->
Just Executable {
exeName = benchmarkName bench,
modulePath = f,
buildInfo = benchmarkBuildInfo bench
}
CExe exe -> Just exe
_ -> Nothing
getInterfaces :: Verbosity
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> IO HaddockArgs
getInterfaces verbosity lbi clbi htmlTemplate = do
(packageFlags, warnings) <- haddockPackageFlags lbi clbi htmlTemplate
traverse_ (warn verbosity) warnings
return $ mempty {
argInterfaces = packageFlags
}
getGhcCppOpts :: Version
-> BuildInfo
-> GhcOptions
getGhcCppOpts haddockVersion bi =
mempty {
ghcOptExtensions = toNubListR [EnableExtension CPP | needsCpp],
ghcOptCppOptions = toNubListR defines
}
where
needsCpp = EnableExtension CPP `elem` usedExtensions bi
defines = [haddockVersionMacro]
haddockVersionMacro = "-D__HADDOCK_VERSION__="
++ show (v1 * 1000 + v2 * 10 + v3)
where
[v1, v2, v3] = take 3 $ versionBranch haddockVersion ++ [0,0]
getGhcLibDir :: Verbosity -> LocalBuildInfo
-> IO HaddockArgs
getGhcLibDir verbosity lbi = do
l <- case compilerFlavor (compiler lbi) of
GHC -> GHC.getLibDir verbosity lbi
GHCJS -> GHCJS.getLibDir verbosity lbi
_ -> error "haddock only supports GHC and GHCJS"
return $ mempty { argGhcLibDir = Flag l }
-- ------------------------------------------------------------------------------
-- | Call haddock with the specified arguments.
runHaddock :: Verbosity
-> TempFileOptions
-> Compiler
-> ConfiguredProgram
-> HaddockArgs
-> IO ()
runHaddock verbosity tmpFileOpts comp confHaddock args = do
let haddockVersion = fromMaybe (error "unable to determine haddock version")
(programVersion confHaddock)
renderArgs verbosity tmpFileOpts haddockVersion comp args $
\(flags,result)-> do
rawSystemProgram verbosity confHaddock flags
notice verbosity $ "Documentation created: " ++ result
renderArgs :: Verbosity
-> TempFileOptions
-> Version
-> Compiler
-> HaddockArgs
-> (([String], FilePath) -> IO a)
-> IO a
renderArgs verbosity tmpFileOpts version comp args k = do
createDirectoryIfMissingVerbose verbosity True outputDir
withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $
\prologueFileName h -> do
do
when (version >= Version [2,14,4] []) (hSetEncoding h utf8)
hPutStrLn h $ fromFlag $ argPrologue args
hClose h
let pflag = "--prologue=" ++ prologueFileName
k (pflag : renderPureArgs version comp args, result)
where
outputDir = (unDir $ argOutputDir args)
result = intercalate ", "
. map (\o -> outputDir </>
case o of
Html -> "index.html"
Hoogle -> pkgstr <.> "txt")
$ arg argOutput
where
pkgstr = display $ packageName pkgid
pkgid = arg argPackageName
arg f = fromFlag $ f args
renderPureArgs :: Version -> Compiler -> HaddockArgs -> [String]
renderPureArgs version comp args = concat
[ (:[]) . (\f -> "--dump-interface="++ unDir (argOutputDir args) </> f)
. fromFlag . argInterfaceFile $ args
, if isVersion 2 16
then (\pkg -> [ "--package-name=" ++ display (pkgName pkg)
, "--package-version="++display (pkgVersion pkg)
])
. fromFlag . argPackageName $ args
else []
, (\(All b,xs) -> bool (map (("--hide=" ++). display) xs) [] b)
. argHideModules $ args
, bool ["--ignore-all-exports"] [] . getAny . argIgnoreExports $ args
, maybe [] (\(m,e,l) ->
["--source-module=" ++ m
,"--source-entity=" ++ e]
++ if isVersion 2 14 then ["--source-entity-line=" ++ l]
else []
) . flagToMaybe . argLinkSource $ args
, maybe [] ((:[]) . ("--css="++)) . flagToMaybe . argCssFile $ args
, maybe [] ((:[]) . ("--use-contents="++)) . flagToMaybe . argContents $ args
, bool [] [verbosityFlag] . getAny . argVerbose $ args
, map (\o -> case o of Hoogle -> "--hoogle"; Html -> "--html")
. fromFlag . argOutput $ args
, renderInterfaces . argInterfaces $ args
, (:[]) . ("--odir="++) . unDir . argOutputDir $ args
, (:[]) . ("--title="++)
. (bool (++" (internal documentation)")
id (getAny $ argIgnoreExports args))
. fromFlag . argTitle $ args
, [ "--optghc=" ++ opt | (opts, _ghcVer) <- flagToList (argGhcOptions args)
, opt <- renderGhcOptions comp opts ]
, maybe [] (\l -> ["-B"++l]) $
flagToMaybe (argGhcLibDir args) -- error if Nothing?
, argTargets $ args
]
where
renderInterfaces =
map (\(i,mh) -> "--read-interface=" ++
maybe "" (++",") mh ++ i)
bool a b c = if c then a else b
isVersion major minor = version >= Version [major,minor] []
verbosityFlag
| isVersion 2 5 = "--verbosity=1"
| otherwise = "--verbose"
---------------------------------------------------------------------------------
-- | Given a list of 'InstalledPackageInfo's, return a list of interfaces and
-- HTML paths, and an optional warning for packages with missing documentation.
haddockPackagePaths :: [InstalledPackageInfo]
-> Maybe (InstalledPackageInfo -> FilePath)
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackagePaths ipkgs mkHtmlPath = do
interfaces <- sequence
[ case interfaceAndHtmlPath ipkg of
Nothing -> return (Left (packageId ipkg))
Just (interface, html) -> do
exists <- doesFileExist interface
if exists
then return (Right (interface, html))
else return (Left pkgid)
| ipkg <- ipkgs, let pkgid = packageId ipkg
, pkgName pkgid `notElem` noHaddockWhitelist
]
let missing = [ pkgid | Left pkgid <- interfaces ]
warning = "The documentation for the following packages are not "
++ "installed. No links will be generated to these packages: "
++ intercalate ", " (map display missing)
flags = rights interfaces
return (flags, if null missing then Nothing else Just warning)
where
-- Don't warn about missing documentation for these packages. See #1231.
noHaddockWhitelist = map PackageName [ "rts" ]
-- Actually extract interface and HTML paths from an 'InstalledPackageInfo'.
interfaceAndHtmlPath :: InstalledPackageInfo
-> Maybe (FilePath, Maybe FilePath)
interfaceAndHtmlPath pkg = do
interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg)
html <- case mkHtmlPath of
Nothing -> fmap fixFileUrl
(listToMaybe (InstalledPackageInfo.haddockHTMLs pkg))
Just mkPath -> Just (mkPath pkg)
return (interface, if null html then Nothing else Just html)
where
-- The 'haddock-html' field in the hc-pkg output is often set as a
-- native path, but we need it as a URL. See #1064.
fixFileUrl f | isAbsolute f = "file://" ++ f
| otherwise = f
haddockPackageFlags :: LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackageFlags lbi clbi htmlTemplate = do
let allPkgs = installedPkgs lbi
directDeps = map fst (componentPackageDeps clbi)
transitiveDeps <- case dependencyClosure allPkgs directDeps of
Left x -> return x
Right inf -> die $ "internal error when calculating transitive "
++ "package dependencies.\nDebug info: " ++ show inf
haddockPackagePaths (PackageIndex.allPackages transitiveDeps) mkHtmlPath
where
mkHtmlPath = fmap expandTemplateVars htmlTemplate
expandTemplateVars tmpl pkg =
fromPathTemplate . substPathTemplate (env pkg) $ tmpl
env pkg = haddockTemplateEnv lbi (packageId pkg)
haddockTemplateEnv :: LocalBuildInfo -> PackageIdentifier -> PathTemplateEnv
haddockTemplateEnv lbi pkg_id =
(PrefixVar, prefix (installDirTemplates lbi))
: initialPathTemplateEnv pkg_id (pkgKey lbi) (compilerInfo (compiler lbi))
(hostPlatform lbi)
-- ------------------------------------------------------------------------------
-- hscolour support.
hscolour :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour pkg_descr lbi suffixes flags = do
-- we preprocess even if hscolour won't be found on the machine
-- will this upset someone?
initialBuildSteps distPref pkg_descr lbi verbosity
hscolour' die pkg_descr lbi suffixes flags
where
verbosity = fromFlag (hscolourVerbosity flags)
distPref = fromFlag $ hscolourDistPref flags
hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found.
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour' onNoHsColour pkg_descr lbi suffixes flags =
either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<<
lookupProgramVersion verbosity hscolourProgram
(orLaterVersion (Version [1,8] [])) (withPrograms lbi)
where
go :: ConfiguredProgram -> IO ()
go hscolourProg = do
setupMessage verbosity "Running hscolour for" (packageId pkg_descr)
createDirectoryIfMissingVerbose verbosity True $
hscolourPref distPref pkg_descr
let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes
withAllComponentsInBuildOrder pkg_descr lbi $ \comp _ -> do
pre comp
let
doExe com = case (compToExe com) of
Just exe -> do
let outputDir = hscolourPref distPref pkg_descr
</> exeName exe </> "src"
runHsColour hscolourProg outputDir =<< getExeSourceFiles lbi exe
Nothing -> do
warn (fromFlag $ hscolourVerbosity flags)
"Unsupported component, skipping..."
return ()
case comp of
CLib lib -> do
let outputDir = hscolourPref distPref pkg_descr </> "src"
runHsColour hscolourProg outputDir =<< getLibSourceFiles lbi lib
CExe _ -> when (fromFlag (hscolourExecutables flags)) $ doExe comp
CTest _ -> when (fromFlag (hscolourTestSuites flags)) $ doExe comp
CBench _ -> when (fromFlag (hscolourBenchmarks flags)) $ doExe comp
stylesheet = flagToMaybe (hscolourCSS flags)
verbosity = fromFlag (hscolourVerbosity flags)
distPref = fromFlag (hscolourDistPref flags)
runHsColour prog outputDir moduleFiles = do
createDirectoryIfMissingVerbose verbosity True outputDir
case stylesheet of -- copy the CSS file
Nothing | programVersion prog >= Just (Version [1,9] []) ->
rawSystemProgram verbosity prog
["-print-css", "-o" ++ outputDir </> "hscolour.css"]
| otherwise -> return ()
Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css")
forM_ moduleFiles $ \(m, inFile) ->
rawSystemProgram verbosity prog
["-css", "-anchor", "-o" ++ outFile m, inFile]
where
outFile m = outputDir </>
intercalate "-" (ModuleName.components m) <.> "html"
haddockToHscolour :: HaddockFlags -> HscolourFlags
haddockToHscolour flags =
HscolourFlags {
hscolourCSS = haddockHscolourCss flags,
hscolourExecutables = haddockExecutables flags,
hscolourTestSuites = haddockTestSuites flags,
hscolourBenchmarks = haddockBenchmarks flags,
hscolourVerbosity = haddockVerbosity flags,
hscolourDistPref = haddockDistPref flags
}
---------------------------------------------------------------------------------
-- TODO these should be moved elsewhere.
getLibSourceFiles :: LocalBuildInfo
-> Library
-> IO [(ModuleName.ModuleName, FilePath)]
getLibSourceFiles lbi lib = getSourceFiles searchpaths modules
where
bi = libBuildInfo lib
modules = PD.exposedModules lib ++ otherModules bi
searchpaths = autogenModulesDir lbi : buildDir lbi : hsSourceDirs bi
getExeSourceFiles :: LocalBuildInfo
-> Executable
-> IO [(ModuleName.ModuleName, FilePath)]
getExeSourceFiles lbi exe = do
moduleFiles <- getSourceFiles searchpaths modules
srcMainPath <- findFile (hsSourceDirs bi) (modulePath exe)
return ((ModuleName.main, srcMainPath) : moduleFiles)
where
bi = buildInfo exe
modules = otherModules bi
searchpaths = autogenModulesDir lbi : exeBuildDir lbi exe : hsSourceDirs bi
getSourceFiles :: [FilePath]
-> [ModuleName.ModuleName]
-> IO [(ModuleName.ModuleName, FilePath)]
getSourceFiles dirs modules = flip mapM modules $ \m -> fmap ((,) m) $
findFileWithExtension ["hs", "lhs"] dirs (ModuleName.toFilePath m)
>>= maybe (notFound m) (return . normalise)
where
notFound module_ = die $ "can't find source for module " ++ display module_
-- | The directory where we put build results for an executable
exeBuildDir :: LocalBuildInfo -> Executable -> FilePath
exeBuildDir lbi exe = buildDir lbi </> exeName exe </> exeName exe ++ "-tmp"
-- ------------------------------------------------------------------------------
-- Boilerplate Monoid instance.
instance Monoid HaddockArgs where
mempty = HaddockArgs {
argInterfaceFile = mempty,
argPackageName = mempty,
argHideModules = mempty,
argIgnoreExports = mempty,
argLinkSource = mempty,
argCssFile = mempty,
argContents = mempty,
argVerbose = mempty,
argOutput = mempty,
argInterfaces = mempty,
argOutputDir = mempty,
argTitle = mempty,
argPrologue = mempty,
argGhcOptions = mempty,
argGhcLibDir = mempty,
argTargets = mempty
}
mappend a b = HaddockArgs {
argInterfaceFile = mult argInterfaceFile,
argPackageName = mult argPackageName,
argHideModules = mult argHideModules,
argIgnoreExports = mult argIgnoreExports,
argLinkSource = mult argLinkSource,
argCssFile = mult argCssFile,
argContents = mult argContents,
argVerbose = mult argVerbose,
argOutput = mult argOutput,
argInterfaces = mult argInterfaces,
argOutputDir = mult argOutputDir,
argTitle = mult argTitle,
argPrologue = mult argPrologue,
argGhcOptions = mult argGhcOptions,
argGhcLibDir = mult argGhcLibDir,
argTargets = mult argTargets
}
where mult f = f a `mappend` f b
instance Monoid Directory where
mempty = Dir "."
mappend (Dir m) (Dir n) = Dir $ m </> n
| corngood/cabal | Cabal/Distribution/Simple/Haddock.hs | bsd-3-clause | 32,693 | 0 | 26 | 9,908 | 7,351 | 3,864 | 3,487 | 605 | 7 |
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
-- |
-- Module : Data.Text.Unsafe
-- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan
-- License : BSD-style
-- Maintainer : [email protected], [email protected],
-- [email protected]
-- Stability : experimental
-- Portability : portable
--
-- A module containing unsafe 'Text' operations, for very very careful
-- use in heavily tested code.
module Data.Text.Unsafe
(
inlineInterleaveST
, inlinePerformIO
, Iter(..)
, iter
, iter_
, reverseIter
, unsafeHead
, unsafeTail
, lengthWord16
, takeWord16
, dropWord16
) where
#if defined(ASSERTS)
import Control.Exception (assert)
#endif
import Data.Text.Encoding.Utf16 (chr2)
import Data.Text.Internal (Text(..))
import Data.Text.Unsafe.Base (inlineInterleaveST, inlinePerformIO)
import Data.Text.UnsafeChar (unsafeChr)
import qualified Data.Text.Array as A
--LIQUID
import Data.Text.Axioms
import Language.Haskell.Liquid.Prelude
-- | /O(1)/ A variant of 'head' for non-empty 'Text'. 'unsafeHead'
-- omits the check for the empty case, so there is an obligation on
-- the programmer to provide a proof that the 'Text' is non-empty.
{-@ unsafeHead :: TextNE -> Char @-}
unsafeHead :: Text -> Char
unsafeHead (Text arr off _len)
| m < 0xD800 || m > 0xDBFF = unsafeChr m
| otherwise = chr2 m n
where m = A.unsafeIndexF arr off _len off
{-@ LAZYVAR n @-}
n = A.unsafeIndex arr (off+1)
{-# INLINE unsafeHead #-}
-- | /O(1)/ A variant of 'tail' for non-empty 'Text'. 'unsafeHead'
-- omits the check for the empty case, so there is an obligation on
-- the programmer to provide a proof that the 'Text' is non-empty.
{-@ unsafeTail :: t:TextNE -> {v:TextLT t | (tlength v) = ((tlength t) - 1)} @-}
unsafeTail :: Text -> Text
unsafeTail t@(Text arr off len) =
--LIQUID #if defined(ASSERTS)
--LIQUID assert (d <= len) $
--LIQUID #endif
liquidAssert (d <= len) $
Text arr (off+d) len'
where d = iter_ t 0
len' = liquidAssume (axiom_numchars_split t d) (len-d)
{-# INLINE unsafeTail #-}
data Iter = Iter {-# UNPACK #-} !Char {-# UNPACK #-} !Int
{-@ measure iter_d :: Iter -> Int
iter_d (Iter c d) = d
@-}
{-@ qualif IterD(v:Int, i:Iter) : v = (iter_d i) @-}
{-@ qualif ReverseIter(v:Int, i:Int, t:Text)
: ((((i+1)+v) >= 0) && (((i+1)+v) < (i+1))
&& ((numchars (tarr t) (toff t) ((i+1)+v))
= ((numchars (tarr t) (toff t) (i+1)) - 1))
&& ((numchars (tarr t) (toff t) ((i+1)+v)) >= -1))
@-}
-- | /O(1)/ Iterate (unsafely) one step forwards through a UTF-16
-- array, returning the current character and the delta to add to give
-- the next offset to iterate at.
{-@ iter :: t:Text
-> i:{v:Nat | v < (tlen t)}
-> {v:Iter | ((BtwnEI ((iter_d v)+i) i (tlen t))
&& ((numchars (tarr t) (toff t) (i+(iter_d v)))
= (1 + (numchars (tarr t) (toff t) i)))
&& ((numchars (tarr t) (toff t) (i+(iter_d v)))
<= (tlength t)))}
@-}
iter :: Text -> Int -> Iter
iter (Text arr off _len) i
| m < 0xD800 || m > 0xDBFF = Iter (unsafeChr m) 1
| otherwise = let k = j + 1
n = A.unsafeIndex arr k
in
Iter (chr2 m n) 2
where m = A.unsafeIndexF arr off _len j
j = off + i
{- LAZYVAR n @-}
-- n = A.unsafeIndex arr k
{- LAZYVAR k @-}
-- k = j + 1
{-# INLINE iter #-}
-- | /O(1)/ Iterate one step through a UTF-16 array, returning the
-- delta to add to give the next offset to iterate at.
{-@ iter_ :: t:Text
-> i:{v:Nat | v < (tlen t)}
-> {v:Int | (((BtwnEI (v+i) i (tlen t)))
&& ((numchars (tarr t) (toff t) (i+v))
= (1 + (numchars (tarr t) (toff t) i)))
&& ((numchars (tarr t) (toff t) (i+v))
<= (tlength t)))}
@-}
iter_ :: Text -> Int -> Int
iter_ (Text arr off _len) i | m < 0xD800 || m > 0xDBFF = 1
| otherwise = 2
--LIQUID where m = A.unsafeIndex arr (off+i)
where m = A.unsafeIndexF arr off _len (off+i)
{-# INLINE iter_ #-}
-- | /O(1)/ Iterate one step backwards through a UTF-16 array,
-- returning the current character and the delta to add (i.e. a
-- negative number) to give the next offset to iterate at.
{-@ reverseIter :: t:Text
-> i:{v:Int | (Btwn v 0 (tlen t))}
-> (Char,{v:Int | ((Btwn ((i+1)+v) 0 (i+1))
&& ((numchars (tarr t) (toff t) ((i+1)+v))
= ((numchars (tarr t) (toff t) (i+1)) - 1))
&& ((numchars (tarr t) (toff t) ((i+1)+v)) >= -1))})
@-}
--LIQUID reverseIter :: Text -> Int -> (Char,Int)
--LIQUID reverseIter (Text arr off _len) i
reverseIter :: Text -> Int -> (Char,Int)
reverseIter (Text arr off _len) i
| m < 0xDC00 || m > 0xDFFF = (unsafeChr m, neg 1)
| otherwise = let k = j - 1
n = A.unsafeIndex arr k
in
(chr2 n m, neg 2)
where m = A.unsafeIndexB arr off _len j
{- LAZYVAR n @-}
-- n = A.unsafeIndex arr k
j = off + i
{- LAZYVAR k @-}
-- k = j - 1
{-# INLINE reverseIter #-}
{-@ neg :: n:Int -> {v:Int | v = (0-n)} @-}
neg :: Int -> Int
neg n = 0-n
-- | /O(1)/ Return the length of a 'Text' in units of 'Word16'. This
-- is useful for sizing a target array appropriately before using
-- 'unsafeCopyToPtr'.
{-@ lengthWord16 :: t:Text -> {v:Int | v = (tlen t)} @-}
lengthWord16 :: Text -> Int
lengthWord16 (Text _arr _off len) = len
{-# INLINE lengthWord16 #-}
-- | /O(1)/ Unchecked take of 'k' 'Word16's from the front of a 'Text'.
{-@ takeWord16 :: k:Nat -> {v:Text | (k <= (tlen v))} -> {v:Text | (tlen v) = k} @-}
takeWord16 :: Int -> Text -> Text
takeWord16 k (Text arr off _len) = Text arr off k
{-# INLINE takeWord16 #-}
-- | /O(1)/ Unchecked drop of 'k' 'Word16's from the front of a 'Text'.
{-@ dropWord16 :: k:Nat -> t:{v:Text | (k <= (tlen v))}
-> {v:Text | (tlen v) = ((tlen t) - k)} @-}
dropWord16 :: Int -> Text -> Text
dropWord16 k (Text arr off len) = Text arr (off+k) (len-k)
{-# INLINE dropWord16 #-}
| ssaavedra/liquidhaskell | benchmarks/text-0.11.2.3/Data/Text/Unsafe.hs | bsd-3-clause | 6,469 | 0 | 11 | 1,978 | 920 | 517 | 403 | 70 | 1 |
a = b
b = a
main :: IO ()
main = return ()
| hvr/jhc | regress/tests/0_parse/2_pass/Recursive2.hs | mit | 45 | 2 | 6 | 16 | 37 | 16 | 21 | 4 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Util.Replace
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Adam Vogt <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Implements a @--replace@ behavior outside of core.
--
-----------------------------------------------------------------------------
-- refer to core patches:
-- http://article.gmane.org/gmane.comp.lang.haskell.xmonad/8358
module XMonad.Util.Replace
( -- * Usage
-- $usage
replace
-- * Notes
-- $shortcomings
-- ** Implementing a @--replace@ flag
-- $getArgs
) where
import XMonad
import Data.Function
import Control.Monad
-- $usage
-- You must run the 'replace' action before starting xmonad proper, this
-- results in xmonad replacing the currently running WM regardless of the
-- arguments it is run with:
--
-- > import XMonad
-- > import XMonad.Util.Replace
-- > main = do
-- > replace
-- > xmonad $ defaultConfig { .... }
--
-- $shortcomings
-- This doesn't seem to work for replacing WMs that have been started
-- from within xmonad, such as with @'restart' "openbox" False@, but no other
-- WMs that implements --replace manage this either. 'replace' works for
-- replacing metacity when the full gnome-session is started at least.
-- $getArgs
-- You can use 'System.Environment.getArgs' to watch for an explicit
-- @--replace@ flag:
--
-- > import XMonad
-- > import XMonad.Util.Replace (replace)
-- > import Control.Monad (when)
-- > import System.Environment (getArgs)
-- >
-- > main = do
-- > args <- getArgs
-- > when ("--replace" `elem` args) replace
-- > xmonad $ defaultConfig { .... }
--
--
-- Note that your @~\/.xmonad/xmonad-$arch-$os@ binary is not run with the same
-- flags as the @xmonad@ binary that calls it. You may be able to work around
-- this by running your @~\/.xmonad/xmonad-$arch-$os@ binary directly, which is
-- otherwise not recommended.
-- | @replace@ must be run before xmonad starts to signals to compliant window
-- managers that they must exit and let xmonad take over.
replace :: IO ()
replace = do
dpy <- openDisplay ""
let dflt = defaultScreen dpy
rootw <- rootWindow dpy dflt
-- check for other WM
wmSnAtom <- internAtom dpy ("WM_S" ++ (show dflt)) False
currentWmSnOwner <- xGetSelectionOwner dpy wmSnAtom
when (currentWmSnOwner /= 0) $ do
putStrLn $ "Screen " ++ (show dflt) ++ " on display \""
++ (displayString dpy) ++ "\" already has a window manager."
-- prepare to receive destroyNotify for old WM
selectInput dpy currentWmSnOwner structureNotifyMask
-- create off-screen window
netWmSnOwner <- allocaSetWindowAttributes $ \attributes -> do
set_override_redirect attributes True
set_event_mask attributes propertyChangeMask
let screen = defaultScreenOfDisplay dpy
let visual = defaultVisualOfScreen screen
let attrmask = cWOverrideRedirect .|. cWEventMask
createWindow dpy rootw (-100) (-100) 1 1 0 copyFromParent copyFromParent visual attrmask attributes
-- try to acquire wmSnAtom, this should signal the old WM to terminate
putStrLn $ "Replacing existing window manager..."
xSetSelectionOwner dpy wmSnAtom netWmSnOwner currentTime
-- SKIPPED: check if we acquired the selection
-- SKIPPED: send client message indicating that we are now the WM
-- wait for old WM to go away
putStr $ "Waiting for other window manager to terminate... "
fix $ \again -> do
evt <- allocaXEvent $ \event -> do
windowEvent dpy currentWmSnOwner structureNotifyMask event
get_EventType event
when (evt /= destroyNotify) again
putStrLn $ "done"
closeDisplay dpy
| markus1189/xmonad-contrib-710 | XMonad/Util/Replace.hs | bsd-3-clause | 4,020 | 0 | 19 | 933 | 448 | 244 | 204 | 35 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | An abstraction for re-running actions if values or files have changed.
--
-- This is not a full-blown make-style incremental build system, it's a bit
-- more ad-hoc than that, but it's easier to integrate with existing code.
--
-- It's a convenient interface to the "Distribution.Client.FileMonitor"
-- functions.
--
module Distribution.Client.RebuildMonad (
-- * Rebuild monad
Rebuild,
runRebuild,
execRebuild,
askRoot,
-- * Setting up file monitoring
monitorFiles,
MonitorFilePath,
monitorFile,
monitorFileHashed,
monitorNonExistentFile,
monitorDirectory,
monitorNonExistentDirectory,
monitorDirectoryExistence,
monitorFileOrDirectory,
monitorFileSearchPath,
monitorFileHashedSearchPath,
-- ** Monitoring file globs
monitorFileGlob,
monitorFileGlobExistence,
FilePathGlob(..),
FilePathRoot(..),
FilePathGlobRel(..),
GlobPiece(..),
-- * Using a file monitor
FileMonitor(..),
newFileMonitor,
rerunIfChanged,
-- * Utils
matchFileGlob,
getDirectoryContentsMonitored,
createDirectoryMonitored,
monitorDirectoryStatus,
doesFileExistMonitored,
need,
needIfExists,
findFileWithExtensionMonitored,
findFirstFileMonitored,
findFileMonitored,
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Distribution.Client.FileMonitor
import Distribution.Client.Glob hiding (matchFileGlob)
import qualified Distribution.Client.Glob as Glob (matchFileGlob)
import Distribution.Simple.Utils (debug)
import Distribution.Verbosity (Verbosity)
import Control.Monad.State as State
import Control.Monad.Reader as Reader
import System.FilePath
import System.Directory
-- | A monad layered on top of 'IO' to help with re-running actions when the
-- input files and values they depend on change. The crucial operations are
-- 'rerunIfChanged' and 'monitorFiles'.
--
newtype Rebuild a = Rebuild (ReaderT FilePath (StateT [MonitorFilePath] IO) a)
deriving (Functor, Applicative, Monad, MonadIO)
-- | Use this wihin the body action of 'rerunIfChanged' to declare that the
-- action depends on the given files. This can be based on what the action
-- actually did. It is these files that will be checked for changes next
-- time 'rerunIfChanged' is called for that 'FileMonitor'.
--
-- Relative paths are interpreted as relative to an implicit root, ultimately
-- passed in to 'runRebuild'.
--
monitorFiles :: [MonitorFilePath] -> Rebuild ()
monitorFiles filespecs = Rebuild (State.modify (filespecs++))
-- | Run a 'Rebuild' IO action.
unRebuild :: FilePath -> Rebuild a -> IO (a, [MonitorFilePath])
unRebuild rootDir (Rebuild action) = runStateT (runReaderT action rootDir) []
-- | Run a 'Rebuild' IO action.
runRebuild :: FilePath -> Rebuild a -> IO a
runRebuild rootDir (Rebuild action) = evalStateT (runReaderT action rootDir) []
-- | Run a 'Rebuild' IO action.
execRebuild :: FilePath -> Rebuild a -> IO [MonitorFilePath]
execRebuild rootDir (Rebuild action) = execStateT (runReaderT action rootDir) []
-- | The root that relative paths are interpreted as being relative to.
askRoot :: Rebuild FilePath
askRoot = Rebuild Reader.ask
-- | This captures the standard use pattern for a 'FileMonitor': given a
-- monitor, an action and the input value the action depends on, either
-- re-run the action to get its output, or if the value and files the action
-- depends on have not changed then return a previously cached action result.
--
-- The result is still in the 'Rebuild' monad, so these can be nested.
--
-- Do not share 'FileMonitor's between different uses of 'rerunIfChanged'.
--
rerunIfChanged :: (Binary a, Binary b)
=> Verbosity
-> FileMonitor a b
-> a
-> Rebuild b
-> Rebuild b
rerunIfChanged verbosity monitor key action = do
rootDir <- askRoot
changed <- liftIO $ checkFileMonitorChanged monitor rootDir key
case changed of
MonitorUnchanged result files -> do
liftIO $ debug verbosity $ "File monitor '" ++ monitorName
++ "' unchanged."
monitorFiles files
return result
MonitorChanged reason -> do
liftIO $ debug verbosity $ "File monitor '" ++ monitorName
++ "' changed: " ++ showReason reason
startTime <- liftIO $ beginUpdateFileMonitor
(result, files) <- liftIO $ unRebuild rootDir action
liftIO $ updateFileMonitor monitor rootDir
(Just startTime) files key result
monitorFiles files
return result
where
monitorName = takeFileName (fileMonitorCacheFile monitor)
showReason (MonitoredFileChanged file) = "file " ++ file
showReason (MonitoredValueChanged _) = "monitor value changed"
showReason MonitorFirstRun = "first run"
showReason MonitorCorruptCache = "invalid cache file"
-- | Utility to match a file glob against the file system, starting from a
-- given root directory. The results are all relative to the given root.
--
-- Since this operates in the 'Rebuild' monad, it also monitors the given glob
-- for changes.
--
matchFileGlob :: FilePathGlob -> Rebuild [FilePath]
matchFileGlob glob = do
root <- askRoot
monitorFiles [monitorFileGlobExistence glob]
liftIO $ Glob.matchFileGlob root glob
getDirectoryContentsMonitored :: FilePath -> Rebuild [FilePath]
getDirectoryContentsMonitored dir = do
exists <- monitorDirectoryStatus dir
if exists
then liftIO $ getDirectoryContents dir
else return []
createDirectoryMonitored :: Bool -> FilePath -> Rebuild ()
createDirectoryMonitored createParents dir = do
monitorFiles [monitorDirectoryExistence dir]
liftIO $ createDirectoryIfMissing createParents dir
-- | Monitor a directory as in 'monitorDirectory' if it currently exists or
-- as 'monitorNonExistentDirectory' if it does not.
monitorDirectoryStatus :: FilePath -> Rebuild Bool
monitorDirectoryStatus dir = do
exists <- liftIO $ doesDirectoryExist dir
monitorFiles [if exists
then monitorDirectory dir
else monitorNonExistentDirectory dir]
return exists
-- | Like 'doesFileExist', but in the 'Rebuild' monad. This does
-- NOT track the contents of 'FilePath'; use 'need' in that case.
doesFileExistMonitored :: FilePath -> Rebuild Bool
doesFileExistMonitored f = do
root <- askRoot
exists <- liftIO $ doesFileExist (root </> f)
monitorFiles [if exists
then monitorFileExistence f
else monitorNonExistentFile f]
return exists
-- | Monitor a single file
need :: FilePath -> Rebuild ()
need f = monitorFiles [monitorFileHashed f]
-- | Monitor a file if it exists; otherwise check for when it
-- gets created. This is a bit better for recompilation avoidance
-- because sometimes users give bad package metadata, and we don't
-- want to repeatedly rebuild in this case (which we would if we
-- need'ed a non-existent file).
needIfExists :: FilePath -> Rebuild ()
needIfExists f = do
root <- askRoot
exists <- liftIO $ doesFileExist (root </> f)
monitorFiles [if exists
then monitorFileHashed f
else monitorNonExistentFile f]
-- | Like 'findFileWithExtension', but in the 'Rebuild' monad.
findFileWithExtensionMonitored
:: [String]
-> [FilePath]
-> FilePath
-> Rebuild (Maybe FilePath)
findFileWithExtensionMonitored extensions searchPath baseName =
findFirstFileMonitored id
[ path </> baseName <.> ext
| path <- nub searchPath
, ext <- nub extensions ]
-- | Like 'findFirstFile', but in the 'Rebuild' monad.
findFirstFileMonitored :: (a -> FilePath) -> [a] -> Rebuild (Maybe a)
findFirstFileMonitored file = findFirst
where findFirst [] = return Nothing
findFirst (x:xs) = do exists <- doesFileExistMonitored (file x)
if exists
then return (Just x)
else findFirst xs
-- | Like 'findFile', but in the 'Rebuild' monad.
findFileMonitored :: [FilePath] -> FilePath -> Rebuild (Maybe FilePath)
findFileMonitored searchPath fileName =
findFirstFileMonitored id
[ path </> fileName
| path <- nub searchPath]
| mydaum/cabal | cabal-install/Distribution/Client/RebuildMonad.hs | bsd-3-clause | 8,448 | 0 | 17 | 1,928 | 1,519 | 807 | 712 | 149 | 5 |
{-# OPTIONS_GHC -fprof-auto #-}
module B where
plus_noinline :: Integer -> Integer -> Integer
plus_noinline x y = x + y
{-# NOINLINE plus_noinline #-}
-- | This is the key function. We do not want this to be inlined into bar, but
-- we DO want it to be inlined into main (in A.hs). Moreover, when it is inlined
-- into main, we don't want the values inside the tuple to be inlined. To
-- achieve this, in main we call bar with Nothing allowing split to be inlined
-- with the first case, where the values in tuple are calls to NOINLINE
-- functions.
split :: Integer -> Maybe Integer -> (Integer, Integer)
split n Nothing = (n `plus_noinline` 1, n `plus_noinline` 2)
split n (Just m) =
if n == 0 then (m, m) else split (n - 1) (Just m)
{- | The simplified core for bar is:
[GblId,
Arity=2,
Str=<L,U><S,1*U>,
Unf=Unf{Src=InlineStable, TopLvl=True, Value=True, ConLike=True,
WorkFree=True, Expandable=True,
Guidance=ALWAYS_IF(arity=2,unsat_ok=True,boring_ok=False)
Tmpl= \ (n_a1Gq [Occ=OnceL] :: Integer)
(m_a1Gr [Occ=OnceL] :: Maybe Integer) ->
scc<bar>
let {
ds_s2rg :: (Integer, Integer)
[LclId]
ds_s2rg = scc<bar.(...)> split n_a1Gq m_a1Gr } in
plus_noinline
(scc<bar.y>
case ds_s2rg of { (y_a2ps [Occ=Once], _ [Occ=Dead])
-> y_a2ps })
(scc<bar.z>
case ds_s2rg of { (_ [Occ=Dead], z_a2pu [Occ=Once])
-> z_a2pu })}]
bar
= \ (n_a1Gq :: Integer) (m_a1Gr :: Maybe Integer) ->
scc<bar>
case scc<bar.(...)> split n_a1Gq m_a1Gr of
{ (ww1_s2s7, ww2_s2s8) ->
plus_noinline ww1_s2s7 ww2_s2s8
}
Note that there are sccs around the (x,y) pattern match in the unfolding, but
not in the simplified function. See #5889 for a discussion on why the sccs are
present in one but not the other, and whether this is correct.
split is not inlined here, because it is a recursive function.
In A.hs, bar is called with m = Nothing, allowing split to be inlined (as it is
not recursive in that case) and the sccs ARE present in the simplified core of
main (as they are around function calls, not ids). This triggers the linker
error.
-}
bar :: Integer -> Maybe Integer -> Integer
bar n m = y `plus_noinline` z
where
(y, z) = split n m
| ezyang/ghc | testsuite/tests/profiling/should_compile/T5889/B.hs | bsd-3-clause | 2,438 | 0 | 8 | 688 | 193 | 110 | 83 | 12 | 2 |
module Q where
q = "I AM THE ONE"
| mydaum/cabal | cabal-testsuite/PackageTests/InternalLibraries/p/q/Q.hs | bsd-3-clause | 34 | 0 | 4 | 9 | 9 | 6 | 3 | 2 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-
Exercising avoidance of known landmines.
We need one each of
PostTc id Kind
PostTc id Type
PostRn id Fixity
PostRn id NameSet
-}
module MineType where
foo = undefined
| urbanslug/ghc | testsuite/tests/ghc-api/landmines/MineType.hs | bsd-3-clause | 298 | 0 | 4 | 61 | 14 | 11 | 3 | 6 | 1 |
{-# OPTIONS -XRecursiveDo -XScopedTypeVariables #-}
module Main(main) where
import Control.Monad.Fix
import Data.Array.IO
import Control.Monad
norm a = mdo (_, sz) <- getBounds a
s <- ioaA 1 s sz 0
return ()
where
ioaA i s sz acc
| i > sz = return acc
| True = do v <- readArray a i
writeArray a i (v / s)
ioaA (i+1) s sz $! (v + acc)
toList a = do (_, sz) <- getBounds a
mapM (\i -> readArray a i) [1..sz]
test :: Int -> IO ()
test sz = do
(arr :: IOArray Int Float) <- newArray (1, sz) 12
putStrLn "Before: "
toList arr >>= print
norm arr
putStrLn "After: "
lst <- toList arr
print lst
putStrLn ("Normalized sum: " ++ show (sum lst))
main = test 10
| siddhanathan/ghc | testsuite/tests/mdo/should_run/mdorun001.hs | bsd-3-clause | 740 | 4 | 12 | 223 | 342 | 166 | 176 | -1 | -1 |
{-# LANGUAGE NoMonomorphismRestriction
#-}
module Plugins.Gallery.Gallery.Manual17 where
import Diagrams.Prelude
example = position (zip (map mkPoint [-3, -2.8 .. 3]) (repeat dot))
where dot = circle 0.2 # fc black
mkPoint x = p2 (x,x^2)
| andrey013/pluginstest | Plugins/Gallery/Gallery/Manual17.hs | mit | 266 | 0 | 11 | 62 | 95 | 52 | 43 | 6 | 1 |
import Test.HUnit
foo x = x
--test1 = TestCase (assertEqual "for (foo 3)," (1,2) (foo 3))
return' a = a >> a | RAFIRAF/HASKELL | test.hs | mit | 113 | 2 | 6 | 25 | 30 | 14 | 16 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Selection.RadioButtons (
-- * The RadioButtons Widget
RadioButtons,
-- * Constructor
mkRadioButtons) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, void)
import Data.Aeson
import qualified Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import Data.Text (Text)
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | A 'RadioButtons' represents a RadioButtons widget from IPython.html.widgets.
type RadioButtons = IPythonWidget RadioButtonsType
-- | Create a new RadioButtons widget
mkRadioButtons :: IO RadioButtons
mkRadioButtons = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultSelectionWidget "RadioButtonsView" "RadioButtonsModel"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay RadioButtons where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget RadioButtons where
getCommUUID = uuid
comm widget (Object dict1) _ = do
let key1 = "sync_data" :: Text
key2 = "selected_label" :: Text
Just (Object dict2) = HM.lookup key1 dict1
Just (String label) = HM.lookup key2 dict2
opts <- getField widget Options
case opts of
OptionLabels _ -> void $ do
setField' widget SelectedLabel label
setField' widget SelectedValue label
OptionDict ps ->
case lookup label ps of
Nothing -> return ()
Just value -> void $ do
setField' widget SelectedLabel label
setField' widget SelectedValue value
triggerSelection widget
| sumitsahrawat/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/RadioButtons.hs | mit | 2,234 | 0 | 17 | 552 | 454 | 234 | 220 | 50 | 1 |
module Rebase.Data.ByteString.Builder.Scientific
(
module Data.ByteString.Builder.Scientific
)
where
import Data.ByteString.Builder.Scientific
| nikita-volkov/rebase | library/Rebase/Data/ByteString/Builder/Scientific.hs | mit | 146 | 0 | 5 | 12 | 26 | 19 | 7 | 4 | 0 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SVGFETileElement
(getIn1, SVGFETileElement(..), gTypeSVGFETileElement) where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETileElement.in1 Mozilla SVGFETileElement.in1 documentation>
getIn1 :: (MonadDOM m) => SVGFETileElement -> m SVGAnimatedString
getIn1 self = liftDOM ((self ^. js "in1") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/SVGFETileElement.hs | mit | 1,275 | 0 | 10 | 136 | 345 | 224 | 121 | 20 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveDataTypeable #-}
module SharedTypes where
import Prelude
import Data.Data
import Fay.Yesod
import Data.Text (Text)
data Command = AModel (Text) (Returns [(Text, Int)])
| AAge (Text) (Returns [(Text, Int)])
| AGen (Text,Text) (Returns [(Text, Int)])
| LkAdd (Maybe Int, Maybe Int) (Returns (Maybe (Text, Text, Text, Text)))
| LkDel (Maybe Int, Maybe Int) (Returns Bool)
| ImgAdd (Maybe Int, [Text]) (Returns [(Text, Text)])
| ImgDel (Maybe Int) (Returns Bool)
| ReqAdd (NewRequest) (Returns Bool)
| PAdd (PropertyRequest) (Returns (Maybe PropertyRequest))
| PUpd (PropertyUpdRequest) (Returns Bool)
| PriceMatrix [Price] (Returns Bool)
deriving (Typeable, Data)
data NewRequest = IR3 { ir3ge :: Text, ir3em :: Text
}
deriving (Typeable, Data)
data PropertyRequest = PRInsert { priK :: Text, priV :: Text, priD :: Text }
deriving (Typeable, Data)
data PropertyUpdRequest = PRUpdate { pruK :: Text, pruV :: Text } deriving (Typeable, Data)
data Price =
Price { val :: Text
, serv :: Maybe Int
, hyp :: Maybe Int
} deriving (Typeable, Data)
data PriceV =
PriceV { valV :: Double
, servV :: Int
, hypV :: Int
, validated :: Bool
}
| swamp-agr/carbuyer-advisor | fay-shared/SharedTypes.hs | mit | 1,423 | 0 | 11 | 432 | 492 | 287 | 205 | 34 | 0 |
module Hoton.VectorSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Control.Exception
import Hoton.TestUtils
import Hoton.Types
import Hoton.Vector
t2cart (x1,x2,x3) = Cartesian x1 x2 x3
spec :: Spec
spec = do
describe "Hoton.Vector.scalar" $ do
it "returns 0 for perpendicular vectors" $ do
Cartesian 1 0 0 `scalar` Cartesian 0 1 0 `shouldBe` (0 :: Number)
Cartesian 1 1 1 `scalar` Cartesian 0.5 (-1) 0.5 `shouldBe` (0 :: Number)
it "returns 1 for parallel unit vectors" $ do
(Cartesian (sqrt 0.5) 0 (sqrt 0.5) `scalar` Cartesian (sqrt 0.5) 0 (sqrt 0.5)) `shouldBeApprox` 1
describe "Hoton.Vector.smul" $ do
it "returns double of the vector" $ do
Cartesian 1 3 (-4) `smul` 2 `shouldBe` Cartesian 2 6 (-8)
describe "Hoton.Vector.sdiv" $ do
it "returns half of the vector" $ do
Cartesian 1 3 (-4) `sdiv` 2 `shouldBe` Cartesian 0.5 1.5 (-2)
it "throws DivideByZero if divides by zero" $ do
evaluate ((Cartesian 1 3 (-4)) `sdiv` 0) `shouldThrow` (==DivideByZero)
describe "Hoton.Vector.vadd" $ do
it "returns the sum" $ do
Cartesian 1 (-2) 7 `vadd` Cartesian 3 5 (-2) `shouldBe` Cartesian 4 3 5
describe "Hoton.Vector.norm" $ do
it "returns 1 for unit vectors" $ do
norm (Cartesian 1 0 0) `shouldBeApprox` 1
describe "Hoton.Vector.normalize" $ do
it "returns unit vector for any non-zero vector" $ do
mapM_ ((`shouldBeApprox` 1) . norm . normalize . t2cart)
[(1,2,3), (0,1,4), (-1,5,6), (9,0,4), (-3,2,-7)]
it "throws DivideByZero for zero vector" $ do
evaluate (normalize (Cartesian 0 0 0)) `shouldThrow` (==DivideByZero)
describe "Hoton.Vector.toCartesian" $ do
it "resturns (0 0 1) for theta=0, phi=0" $ do
toCartesian (Spherical 1 0 0) `shouldBeApproxV` (Cartesian 0 0 1)
it "resturns normalized (1 0 1) for theta=pi/4, phi=0" $ do
toCartesian (Spherical 1 (pi/4) 0) `shouldBeApproxV` normalize (Cartesian 1 0 1)
it "resturns normalized (1 1 (sqrt2)) for theta=pi/4, phi=pi/4" $ do
toCartesian (Spherical 1 (pi/4) (pi/4)) `shouldBeApproxV` normalize (Cartesian 1 1 (sqrt 2))
| woufrous/hoton | test/Hoton/VectorSpec.hs | mit | 2,294 | 0 | 20 | 612 | 838 | 431 | 407 | 43 | 1 |
main = print(sum [x | x <- [1..1000], mod x 3 == 0 || mod x 5 == 0])
| mhseiden/euler-haskell | src/p1.hs | mit | 70 | 0 | 13 | 20 | 57 | 28 | 29 | 1 | 1 |
-- |
-- The 'FP15.Compiler.Syntax' module contains FP15-specific parsing logic for
-- syntactic sugars.
module FP15.Compiler.Syntax (
module FP15.Compiler.Syntax.SmartSplit
, module FP15.Compiler.Syntax.Precedence
, module FP15.Compiler.Syntax.CommaNotation
) where
import FP15.Compiler.Syntax.SmartSplit
import FP15.Compiler.Syntax.Precedence
import FP15.Compiler.Syntax.CommaNotation
{-# ANN module "HLint: ignore Use import/export shortcut" #-}
| Ming-Tang/FP15 | src/FP15/Compiler/Syntax.hs | mit | 451 | 0 | 5 | 45 | 58 | 43 | 15 | 8 | 0 |
-- | Canon representation of linear program
module Numeric.Limp.Canon.Program where
import Numeric.Limp.Canon.Linear
import Numeric.Limp.Canon.Constraint
import Numeric.Limp.Rep
import Data.Map (Map)
import qualified Data.Map as M
import Data.Set (Set)
import qualified Data.Set as S
-- | A program represented by objective, constraints and bounds.
-- There is no need for an optimisation direction; the objective is just negated.
data Program z r c
= Program
{ _objective :: Linear z r c
, _constraints :: Constraint z r c
, _bounds :: Map (Either z r) (Maybe (R c), Maybe (R c))
}
-- | Find set of all variables mentioned in program
varsOfProgram :: (Ord z, Ord r) => Program z r c -> Set (Either z r)
varsOfProgram p
= S.unions
[ varsOfLinear $ _objective p
, varsOfConstraint $ _constraints p
, M.keysSet $ _bounds p ]
-- | Merge some lower and upper bounds
mergeBounds :: Rep c => (Maybe (R c), Maybe (R c)) -> (Maybe (R c), Maybe (R c)) -> (Maybe (R c), Maybe (R c))
mergeBounds (l1,u1) (l2,u2)
= ( mmaybe max l1 l2
, mmaybe min u1 u2 )
where
mmaybe f a b
= case (a,b) of
(Nothing, Nothing)
-> Nothing
(Nothing, Just b')
-> Just $ b'
(Just a', Nothing)
-> Just $ a'
(Just a', Just b')
-> Just $ f a' b'
-- | Check whether an assignment satisfies the program's constraints and bounds
checkProgram :: (Rep c, Ord z, Ord r) => Assignment z r c -> Program z r c -> Bool
checkProgram a p
= check a (_constraints p)
&& checkBounds a (_bounds p)
checkBounds :: (Rep c, Ord z, Ord r) => Assignment z r c -> Map (Either z r) (Maybe (R c), Maybe (R c)) -> Bool
checkBounds ass bs
= M.foldr (&&) True (M.mapWithKey checkB bs)
where
checkB k (lo,up)
= let v = zrOf ass k
in maybe True (<=v) lo
&& maybe True (v<=) up
| amosr/limp | src/Numeric/Limp/Canon/Program.hs | mit | 1,843 | 0 | 13 | 456 | 726 | 386 | 340 | 44 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
{- |Implementation of a connection using WebSockets.
-}
module WsConnection (WsConnection(..)) where
import App.ConnectionMgnt
import ClassyPrelude
import qualified Data.Aeson as Aeson
import qualified Network.WebSockets as WS
newtype WsConnection = WsConnection WS.Connection
instance IsConnection WsConnection where
type Pending WsConnection = WS.PendingConnection
sendMsg (WsConnection conn) =
WS.sendTextData conn . Aeson.encode
recvMsg (WsConnection conn) = do
wsData <- WS.receiveData conn
return $ Aeson.decode wsData
acceptRequest =
map WsConnection . WS.acceptRequest
| Haskell-Praxis/core-catcher | app/WsConnection.hs | mit | 731 | 0 | 10 | 164 | 146 | 81 | 65 | 17 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module Template.Module (
moduleXml,
configXml
) where
import Template (render)
import Data.Data (Data, Typeable)
data ModuleTemplate = ModuleTemplate {
codepool :: String,
fullModuleName :: String
} deriving (Data, Typeable)
moduleXml :: String -> String -> IO String
moduleXml codepool fullModuleName =
render "module/module.xml" (ModuleTemplate codepool fullModuleName)
configXml :: String -> IO String
configXml fullModuleName =
render "module/config.xml" (ModuleTemplate "" fullModuleName)
| prasmussen/magmod | Template/Module.hs | mit | 559 | 0 | 8 | 93 | 140 | 77 | 63 | 16 | 1 |
import SudokuGen
import SudokuSorted
import SudokuHelper
main = do
puzzle <- sudokuGen
putStrLn (pretty $ puzzle)
putStrLn (pretty $ solveStr puzzle)
| ztuowen/sudoku | sgen.hs | mit | 163 | 0 | 10 | 34 | 51 | 25 | 26 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html
module Stratosphere.ResourceProperties.DynamoDBTableAttributeDefinition where
import Stratosphere.ResourceImports
import Stratosphere.Types
-- | Full data type definition for DynamoDBTableAttributeDefinition. See
-- 'dynamoDBTableAttributeDefinition' for a more convenient constructor.
data DynamoDBTableAttributeDefinition =
DynamoDBTableAttributeDefinition
{ _dynamoDBTableAttributeDefinitionAttributeName :: Val Text
, _dynamoDBTableAttributeDefinitionAttributeType :: Val AttributeType
} deriving (Show, Eq)
instance ToJSON DynamoDBTableAttributeDefinition where
toJSON DynamoDBTableAttributeDefinition{..} =
object $
catMaybes
[ (Just . ("AttributeName",) . toJSON) _dynamoDBTableAttributeDefinitionAttributeName
, (Just . ("AttributeType",) . toJSON) _dynamoDBTableAttributeDefinitionAttributeType
]
-- | Constructor for 'DynamoDBTableAttributeDefinition' containing required
-- fields as arguments.
dynamoDBTableAttributeDefinition
:: Val Text -- ^ 'ddbtadAttributeName'
-> Val AttributeType -- ^ 'ddbtadAttributeType'
-> DynamoDBTableAttributeDefinition
dynamoDBTableAttributeDefinition attributeNamearg attributeTypearg =
DynamoDBTableAttributeDefinition
{ _dynamoDBTableAttributeDefinitionAttributeName = attributeNamearg
, _dynamoDBTableAttributeDefinitionAttributeType = attributeTypearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename
ddbtadAttributeName :: Lens' DynamoDBTableAttributeDefinition (Val Text)
ddbtadAttributeName = lens _dynamoDBTableAttributeDefinitionAttributeName (\s a -> s { _dynamoDBTableAttributeDefinitionAttributeName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename-attributetype
ddbtadAttributeType :: Lens' DynamoDBTableAttributeDefinition (Val AttributeType)
ddbtadAttributeType = lens _dynamoDBTableAttributeDefinitionAttributeType (\s a -> s { _dynamoDBTableAttributeDefinitionAttributeType = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/DynamoDBTableAttributeDefinition.hs | mit | 2,339 | 0 | 13 | 221 | 270 | 154 | 116 | 30 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html
module Stratosphere.Resources.BatchJobDefinition where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.BatchJobDefinitionContainerProperties
import Stratosphere.ResourceProperties.BatchJobDefinitionNodeProperties
import Stratosphere.ResourceProperties.BatchJobDefinitionRetryStrategy
import Stratosphere.ResourceProperties.BatchJobDefinitionTimeout
-- | Full data type definition for BatchJobDefinition. See
-- 'batchJobDefinition' for a more convenient constructor.
data BatchJobDefinition =
BatchJobDefinition
{ _batchJobDefinitionContainerProperties :: Maybe BatchJobDefinitionContainerProperties
, _batchJobDefinitionJobDefinitionName :: Maybe (Val Text)
, _batchJobDefinitionNodeProperties :: Maybe BatchJobDefinitionNodeProperties
, _batchJobDefinitionParameters :: Maybe Object
, _batchJobDefinitionRetryStrategy :: Maybe BatchJobDefinitionRetryStrategy
, _batchJobDefinitionTimeout :: Maybe BatchJobDefinitionTimeout
, _batchJobDefinitionType :: Val Text
} deriving (Show, Eq)
instance ToResourceProperties BatchJobDefinition where
toResourceProperties BatchJobDefinition{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::Batch::JobDefinition"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("ContainerProperties",) . toJSON) _batchJobDefinitionContainerProperties
, fmap (("JobDefinitionName",) . toJSON) _batchJobDefinitionJobDefinitionName
, fmap (("NodeProperties",) . toJSON) _batchJobDefinitionNodeProperties
, fmap (("Parameters",) . toJSON) _batchJobDefinitionParameters
, fmap (("RetryStrategy",) . toJSON) _batchJobDefinitionRetryStrategy
, fmap (("Timeout",) . toJSON) _batchJobDefinitionTimeout
, (Just . ("Type",) . toJSON) _batchJobDefinitionType
]
}
-- | Constructor for 'BatchJobDefinition' containing required fields as
-- arguments.
batchJobDefinition
:: Val Text -- ^ 'bjdType'
-> BatchJobDefinition
batchJobDefinition typearg =
BatchJobDefinition
{ _batchJobDefinitionContainerProperties = Nothing
, _batchJobDefinitionJobDefinitionName = Nothing
, _batchJobDefinitionNodeProperties = Nothing
, _batchJobDefinitionParameters = Nothing
, _batchJobDefinitionRetryStrategy = Nothing
, _batchJobDefinitionTimeout = Nothing
, _batchJobDefinitionType = typearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-containerproperties
bjdContainerProperties :: Lens' BatchJobDefinition (Maybe BatchJobDefinitionContainerProperties)
bjdContainerProperties = lens _batchJobDefinitionContainerProperties (\s a -> s { _batchJobDefinitionContainerProperties = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-jobdefinitionname
bjdJobDefinitionName :: Lens' BatchJobDefinition (Maybe (Val Text))
bjdJobDefinitionName = lens _batchJobDefinitionJobDefinitionName (\s a -> s { _batchJobDefinitionJobDefinitionName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-nodeproperties
bjdNodeProperties :: Lens' BatchJobDefinition (Maybe BatchJobDefinitionNodeProperties)
bjdNodeProperties = lens _batchJobDefinitionNodeProperties (\s a -> s { _batchJobDefinitionNodeProperties = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-parameters
bjdParameters :: Lens' BatchJobDefinition (Maybe Object)
bjdParameters = lens _batchJobDefinitionParameters (\s a -> s { _batchJobDefinitionParameters = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-retrystrategy
bjdRetryStrategy :: Lens' BatchJobDefinition (Maybe BatchJobDefinitionRetryStrategy)
bjdRetryStrategy = lens _batchJobDefinitionRetryStrategy (\s a -> s { _batchJobDefinitionRetryStrategy = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-timeout
bjdTimeout :: Lens' BatchJobDefinition (Maybe BatchJobDefinitionTimeout)
bjdTimeout = lens _batchJobDefinitionTimeout (\s a -> s { _batchJobDefinitionTimeout = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-type
bjdType :: Lens' BatchJobDefinition (Val Text)
bjdType = lens _batchJobDefinitionType (\s a -> s { _batchJobDefinitionType = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/BatchJobDefinition.hs | mit | 4,874 | 0 | 15 | 506 | 698 | 401 | 297 | 59 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html
module Stratosphere.ResourceProperties.SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters where
import Stratosphere.ResourceImports
-- | Full data type definition for
-- SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters. See
-- 'ssmMaintenanceWindowTaskMaintenanceWindowLambdaParameters' for a more
-- convenient constructor.
data SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters =
SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters
{ _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersClientContext :: Maybe (Val Text)
, _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersPayload :: Maybe (Val Text)
, _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersQualifier :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters where
toJSON SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters{..} =
object $
catMaybes
[ fmap (("ClientContext",) . toJSON) _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersClientContext
, fmap (("Payload",) . toJSON) _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersPayload
, fmap (("Qualifier",) . toJSON) _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersQualifier
]
-- | Constructor for
-- 'SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters' containing
-- required fields as arguments.
ssmMaintenanceWindowTaskMaintenanceWindowLambdaParameters
:: SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters
ssmMaintenanceWindowTaskMaintenanceWindowLambdaParameters =
SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters
{ _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersClientContext = Nothing
, _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersPayload = Nothing
, _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersQualifier = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-clientcontext
ssmmwtmwlpClientContext :: Lens' SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters (Maybe (Val Text))
ssmmwtmwlpClientContext = lens _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersClientContext (\s a -> s { _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersClientContext = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-payload
ssmmwtmwlpPayload :: Lens' SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters (Maybe (Val Text))
ssmmwtmwlpPayload = lens _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersPayload (\s a -> s { _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersPayload = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-qualifier
ssmmwtmwlpQualifier :: Lens' SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters (Maybe (Val Text))
ssmmwtmwlpQualifier = lens _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersQualifier (\s a -> s { _sSMMaintenanceWindowTaskMaintenanceWindowLambdaParametersQualifier = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/SSMMaintenanceWindowTaskMaintenanceWindowLambdaParameters.hs | mit | 3,719 | 0 | 12 | 256 | 358 | 205 | 153 | 32 | 1 |
-- Top-level functions:
-- * reading/writing morphology databases
-- * writing Lexicon, Tables, GF, XFST, Latex
-- * analysis/synthesis (Trie)
module GeneralIO where
import Print
import General
import Dictionary
import Trie
import IO
import Map
import Frontend
import List (nub)
import Maybe(fromJust)
import ErrM
type Stem = String
type Id = String
writeLex :: FilePath -> Dictionary -> IO ()
writeLex f m = writeFile f $ prFullFormLex $ dict2fullform m
outputLex m = putStrLn $ prFullFormLex $ dict2fullform m
writeTables :: FilePath -> Dictionary -> IO ()
writeTables f m = writeFile f $ prDictionary m
outputTables m = putStrLn $ prDictionary m
writeGF :: FilePath -> FilePath -> Dictionary -> IO ()
writeGF f1 f2 m = writeFile f1 $
"-- machine-generated GF file\n\n" ++
"include " ++ f2 ++ " ;\n\n" ++
prGF m
outputGF f2 m = putStrLn $
"-- machine-generated GF file\n\n" ++
"include " ++ f2 ++ " ;\n\n" ++
prGF m
writeGFRes :: FilePath -> FilePath -> Dictionary -> IO ()
writeGFRes f1 f2 m = writeFile f1 $
"-- machine-generated GF file\n\n" ++
"include " ++ f2 ++ " ;\n\n" ++
prGFRes m
outputGFRes f2 m = putStrLn $
"-- machine-generated GF file\n\n" ++
"include " ++ f2 ++ " ;\n\n" ++
prGFRes m
-- writeGF1 :: FilePath -> FilePath -> Dictionary -> IO ()
-- writeGF1 f1 f2 m = writeFile f1 $
-- "-- machine-generated GF file\n\n" ++
-- "include " ++ f2 ++ " ;\n\n" ++
-- prGF1 m
writeXML :: FilePath -> Dictionary -> IO ()
writeXML f m = writeFile f $ prXML m
outputXML m = putStrLn $ prXML m
writeXFST :: FilePath -> Dictionary -> IO ()
writeXFST f m = writeFile f $
"# machine-generated XFST file\n\n" ++
prXFST m
outputXFST m = putStrLn $
"# machine-generated XFST file\n\n" ++
prXFST m
writeLEXC :: FilePath -> Dictionary -> IO ()
writeLEXC f m = writeFile f $
"! machine-generated LEXC file\n\n" ++
prLEXC m
outputLEXC m = putStrLn $
"! machine-generated LEXC file\n\n" ++
prLEXC m
writeLatex :: FilePath -> Dictionary -> IO ()
writeLatex f m = writeFile f $ "% machine-generated LaTeX file\n" ++
prLatex m
outputLatex m = putStrLn $ "% machine-generated LaTeX file\n" ++
prLatex m
writeSQL :: FilePath -> Dictionary -> IO ()
writeSQL f m = writeFile f $ prSQL m
outputSQL :: Dictionary -> IO ()
outputSQL m = putStrLn $ prSQL m
{- this version not needed? AR
update :: Dictionary -> Dictionary -> Dictionary
update dict d = unionDictionary dict d
createDictionary :: FilePath -> IO ()
createDictionary f = writeDictionary emptyDict f
writeDictionary :: Dictionary -> FilePath -> IO ()
writeDictionary sm file
= do h <- openFile file WriteMode
hPutStr h $ unlines (map show (unDict sm))
hClose h
readDictionary :: FilePath -> IO Dictionary
readDictionary file = do h <- openFile file ReadMode
s <- hGetContents h
let ss = lines s
return $ dictionary (map (strings.read) ss)
-- readM :: String -> IO Entry
-- readM line = putChar '.' >> return (read line)
updateDictionary :: FilePath -> FilePath -> Dictionary -> IO ()
updateDictionary f1 f2 m0 = do
m <- readDictionary f1
writeDictionary (update m0 m) f2
-- Use the update_db function to extend your external resource with
-- more words. The update is non-destructive.
-- You should run 'createDictionary db' the first time you use it.
update_db :: Lang -> Dictionary -> IO ()
update_db l lex = do
let dbl = db l
m <- readDictionary dbl
writeDictionary (update (d2d lex) m) dbl
-}
-- tries...
trieDict :: Dictionary -> SATrie
trieDict d = tcompile [(s, xs) | (s,xs) <- dict2fullform d]
-- buildTrie :: Dictionary -> SATrie
-- buildTrie = tcompile . dict2fullform
analysis :: SATrie -> ([Attr] -> Bool) -> String -> [[String]]
analysis trie f s = [map snd ys | ys <- decompose trie f s]
-- trieLookup
synthesis :: Stem -> Dictionary -> [Entry]
synthesis s dict = [d | d@(s1,c,xs,t) <- unDict dict, s == s1]
lookupStem :: SATrie -> String -> [(Stem,Int)]
lookupStem trie s = [(s,read n) | s:n:_ <- map (words . snd) (snd (tlookup trie s))]
synthesiser :: Language a => a -> Dictionary -> SATrie -> IO()
synthesiser l dict trie =
do
synt trie $ [((s1,n),(c,xs,t)) | ((s1,c,xs,t),n) <- zip (unDict dict) [0..]] |->++ Map.empty
where synt trie table =
do hPutStr stdout "> "
hFlush stdout
s <- hGetLine stdin
case words s of
["q"] -> return()
["c"] -> do putStrLn $ unlines (paradigmNames l)
synt trie table
[] -> synt trie table
[w] -> case(lookupStem trie w) of
[] -> do putStrLn $ "Word '" ++ w ++ "' not in the lexicon."
synt trie table
xs -> do putStrLn $ "\n" ++ (prDictionary (dictionary (nub (concat (map (lsynt table) xs)))))
synt trie table
x:xs -> case (parseCommand l (unwords (x:xs))) of
Bad s -> do putStrLn s
synt trie table
Ok e -> do putStrLn $ prDictionary $ dictionary [e]
synt trie table
lsynt table (s,n) = nub [(s,b,c,d) | (b,c,d) <- fromJust (table ! (s,n))]
infMode :: Language a => a -> IO()
infMode l
= do putStr "> "
hFlush stdout
s <- getLine
case (words s) of
["q"] -> putStrLn "Session ended."
["c"] -> do putStrLn $ unlines (paradigmNames l)
infMode l
(x:xs) -> do case (parseCommand l (unwords (x:xs))) of
Bad s -> do putStrLn s
infMode l
Ok e -> do putStrLn $ prDictionary $ dictionary [e]
infMode l
_ -> do putStrLn "Give [command] [dictionary form]"
infMode l
imode :: Language a => a -> IO()
imode l = interact (concat . map f . lines)
where f s =
case (words s) of
(x:xs) -> do case (parseCommand l (unwords (x:xs))) of
Bad s -> s
Ok e -> unlines
["[" ++ unwords (x:xs) ++ "]",
prDictionary $ dictionary [e]]
_ -> do "Invalid format. Write: [command] [dictionary form]"
| icemorph/icemorph | bin/FM/lib/GeneralIO.hs | cc0-1.0 | 6,102 | 68 | 21 | 1,632 | 1,798 | 922 | 876 | 121 | 7 |
{- |
Module : $Header$
Description : Parser for basic specs
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Parser for abstract syntax for propositional logic
Ref.
<http://en.wikipedia.org/wiki/Propositional_logic>
-}
module Propositional.Parse_AS_Basic
( basicSpec -- Parser for basic specs
, symbItems
, symbMapItems
, impFormula
) where
import qualified Common.AnnoState as AnnoState
import qualified Common.AS_Annotation as Annotation
import Common.Id as Id
import Common.Keywords as Keywords
import Common.Lexer as Lexer
import Common.Parsec
import Common.GlobalAnnotations (PrefixMap)
import Propositional.AS_BASIC_Propositional as AS_BASIC
import Text.ParserCombinators.Parsec
propKeywords :: [String]
propKeywords =
[ Keywords.propS
, Keywords.notS
, Keywords.trueS
, Keywords.falseS ]
-- | Toplevel parser for basic specs
basicSpec :: PrefixMap -> AnnoState.AParser st AS_BASIC.BASIC_SPEC
basicSpec _ =
fmap AS_BASIC.Basic_spec (AnnoState.annosParser parseBasicItems)
<|> (Lexer.oBraceT >> Lexer.cBraceT >> return (AS_BASIC.Basic_spec []))
-- | Parser for basic items
parseBasicItems :: AnnoState.AParser st AS_BASIC.BASIC_ITEMS
parseBasicItems = parsePredDecl <|> parseAxItems
-- | parser for predicate declarations
parsePredDecl :: AnnoState.AParser st AS_BASIC.BASIC_ITEMS
parsePredDecl = fmap AS_BASIC.Pred_decl predItem
-- | parser for Axiom_items
parseAxItems :: AnnoState.AParser st AS_BASIC.BASIC_ITEMS
parseAxItems = do
d <- AnnoState.dotT
(fs, ds) <- aFormula `Lexer.separatedBy` AnnoState.dotT
(_, an) <- AnnoState.optSemi
let _ = Id.catRange (d : ds)
ns = init fs ++ [Annotation.appendAnno (last fs) an]
return $ AS_BASIC.Axiom_items ns
-- | Any word to token
propId :: GenParser Char st Id.Token
propId = Lexer.pToken $ reserved propKeywords Lexer.scanAnyWords
-- | parser for predicates = propositions
predItem :: AnnoState.AParser st AS_BASIC.PRED_ITEM
predItem = do
v <- AnnoState.asKey (Keywords.propS ++ Keywords.sS) <|>
AnnoState.asKey Keywords.propS
(ps, cs) <- propId `Lexer.separatedBy` AnnoState.anComma
return $ AS_BASIC.Pred_item ps $ Id.catRange $ v : cs
-- | Parser for implies @=>@
implKey :: AnnoState.AParser st Id.Token
implKey = AnnoState.asKey Keywords.implS
-- | Parser for and @\/\ @
andKey :: AnnoState.AParser st Id.Token
andKey = AnnoState.asKey Keywords.lAnd
-- | Parser for or @\\\/@
orKey :: AnnoState.AParser st Id.Token
orKey = AnnoState.asKey Keywords.lOr
-- | Parser for true
trueKey :: AnnoState.AParser st Id.Token
trueKey = AnnoState.asKey Keywords.trueS
-- | Parser for false
falseKey :: AnnoState.AParser st Id.Token
falseKey = AnnoState.asKey Keywords.falseS
-- | Parser for not
notKey :: AnnoState.AParser st Id.Token
notKey = AnnoState.asKey Keywords.notS
-- | Parser for negation
negKey :: AnnoState.AParser st Id.Token
negKey = AnnoState.asKey Keywords.negS
-- | Parser for equivalence @<=>@
equivKey :: AnnoState.AParser st Id.Token
equivKey = AnnoState.asKey Keywords.equivS
-- | Parser for primitive formulae
primFormula :: AnnoState.AParser st AS_BASIC.FORMULA
primFormula =
do c <- trueKey
return (AS_BASIC.True_atom $ Id.tokPos c)
<|>
do c <- falseKey
return (AS_BASIC.False_atom $ Id.tokPos c)
<|>
do c <- notKey <|> negKey <?> "\"not\""
k <- primFormula
return (AS_BASIC.Negation k $ Id.tokPos c)
<|> parenFormula
<|> fmap AS_BASIC.Predication propId
-- | Parser for formulae containing 'and' and 'or'
andOrFormula :: AnnoState.AParser st AS_BASIC.FORMULA
andOrFormula = do
f <- primFormula
do c <- andKey
(fs, ps) <- primFormula `Lexer.separatedBy` andKey
return (AS_BASIC.Conjunction (f : fs) (Id.catRange (c : ps)))
<|>
do c <- orKey
(fs, ps) <- primFormula `Lexer.separatedBy` orKey
return (AS_BASIC.Disjunction (f : fs) (Id.catRange (c : ps)))
<|> return f
-- | Parser for formulae with implications
impFormula :: AnnoState.AParser st AS_BASIC.FORMULA
impFormula = do
f <- andOrFormula
do c <- implKey
(fs, ps) <- andOrFormula `Lexer.separatedBy` implKey
return (makeImpl (f : fs) (Id.catPosAux (c : ps)))
<|>
do c <- equivKey
g <- andOrFormula
return (AS_BASIC.Equivalence f g $ Id.tokPos c)
<|> return f
where makeImpl [f, g] p =
AS_BASIC.Implication f g (Id.Range p)
makeImpl (f : r) (c : p) = AS_BASIC.Implication f
(makeImpl r p) (Id.Range [c])
makeImpl _ _ =
error "makeImpl got illegal argument"
-- | Parser for formulae with parentheses
parenFormula :: AnnoState.AParser st AS_BASIC.FORMULA
parenFormula = do
Lexer.oParenT << AnnoState.addAnnos
f <- impFormula << AnnoState.addAnnos
Lexer.cParenT >> return f
-- | Toplevel parser for formulae
aFormula :: AnnoState.AParser st (Annotation.Annoted AS_BASIC.FORMULA)
aFormula = AnnoState.allAnnoParser impFormula
-- | parsing a prop symbol
symb :: GenParser Char st SYMB
symb = fmap Symb_id propId
-- | parsing one symbol or a mapping of one to a second symbol
symbMap :: GenParser Char st SYMB_OR_MAP
symbMap = do
s <- symb
do f <- pToken $ toKey mapsTo
t <- symb
return (Symb_map s t $ tokPos f)
<|> return (Symb s)
-- | Parse a list of comma separated symbols.
symbItems :: GenParser Char st SYMB_ITEMS
symbItems = do
(is, ps) <- symbs
return (Symb_items is $ catRange ps)
-- | parse a comma separated list of symbols
symbs :: GenParser Char st ([SYMB], [Token])
symbs = do
s <- symb
do c <- commaT `followedWith` symb
(is, ps) <- symbs
return (s : is, c : ps)
<|> return ([s], [])
-- | parse a list of symbol mappings
symbMapItems :: GenParser Char st SYMB_MAP_ITEMS
symbMapItems = do
(is, ps) <- symbMaps
return (Symb_map_items is $ catRange ps)
-- | parse a comma separated list of symbol mappings
symbMaps :: GenParser Char st ([SYMB_OR_MAP], [Token])
symbMaps = do
s <- symbMap
do c <- commaT `followedWith` symb
(is, ps) <- symbMaps
return (s : is, c : ps)
<|> return ([s], [])
| nevrenato/HetsAlloy | Propositional/Parse_AS_Basic.hs | gpl-2.0 | 6,706 | 0 | 17 | 1,700 | 1,788 | 921 | 867 | 139 | 3 |
-- OmegaGB Copyright 2007 Bit Connor
-- This program is distributed under the terms of the GNU General Public License
-----------------------------------------------------------------------------
-- |
-- Module : Prerequisites
-- Copyright : (c) Bit Connor 2007 <[email protected]>
-- License : GPL
-- Maintainer : [email protected]
-- Stability : in-progress
--
-- OmegaGB
-- Game Boy Emulator
--
-- This module should be imported from all other modules
--
-----------------------------------------------------------------------------
module Prerequisites where
import Debug.Trace
import Data.Array.IArray
{-
(!) :: (Show i, IArray a e, Ix i) =>
a i e -> i -> e
a ! i = let (lowerBound, upperBound) = bounds a in
if i >= lowerBound && i <= upperBound
then a Data.Array.IArray.! i
else error ("Read out of bounds (" ++ show lowerBound ++ ", " ++ show upperBound ++ "), index = " ++ show i)
(//) :: (Show i, Show e, IArray a e, Ix i) =>
a i e -> [(i, e)] -> a i e
a // l = let (lowerBound, upperBound) = bounds a in
if all ( \(i, _) -> i >= lowerBound && i <= upperBound ) l
then a Data.Array.IArray.// l
else error ("Write out of bounds (" ++ show lowerBound ++ ", " ++ show upperBound ++ "), " ++ show l)
-}
| bitc/omegagb | src/Prerequisites.hs | gpl-2.0 | 1,332 | 0 | 4 | 333 | 32 | 27 | 5 | 3 | 0 |
module Expr
where
--
-- datatypes and expressions
-- and some functions to parse and output them
--
import Lexer
import Types
import ApplicativeParsec hiding (SourcePos)
import Text.ParserCombinators.Parsec.Expr
table :: OperatorTable Char st Expression
table = [
[prefix "+", prefix "-"],
[binary "." AssocRight],
[binary "**" AssocRight, binary "^" AssocRight, binary "^^" AssocRight],
[postfix "++"],
[binary "*" AssocLeft, binary "/" AssocLeft, binary "%" AssocLeft],
[binary "+" AssocLeft, binary "-" AssocLeft],
[binary ":" AssocRight],
[binary "==" AssocLeft, binary "!=" AssocLeft, binary "<" AssocLeft, binary "<=" AssocLeft, binary ">" AssocLeft, binary ">=" AssocLeft],
[binary "&&" AssocRight],
[binary "||" AssocRight],
[binary ">>=" AssocLeft, binary ">>" AssocLeft]
]
binary name = Infix (posOp name >>= (\p -> return (\x y -> op_to_expr p name [x,y])))
prefix name = Prefix (posOp name >>= (\p -> return (\y -> prefixop_to_expr p name [y])))
postfix name = Postfix (posOp name >>= (\p -> return (\y -> op_to_expr p name [y])))
binFunc name = Infix (f >>= (\p -> return (\x y -> (Application p (Operator p "" name) [x,y]))))
where f = getPosition <* (reservedOp name)
posOp name = getPosition <* (reservedOp name)
primitive :: CharParser st Datatype
primitive =
(try double)
<|> number
<|> chr
<|> str
<|> atom
<?> "primitive"
pattern :: CharParser st Expression
pattern =
(parens listconstructor)
<|> datatype primitive
<|> var
<|> (wildcard >> return Wildcard)
<|> datatype (list pattern)
<|> datatype (vector pattern)
<?> "pattern"
listconstructor = f <$> getPosition <*> colonSep pattern
where f x = Application x (Operator x "" ":")
{-listcomprehension =
squares (
do
patr <- pattern
reservedOp "|"
vars <- (commaSep1 (var <* reservedOp "<-" list))
compr <- (commaSep expression)
return (ListComp patr compr)
)
-}
expression :: GenParser Char st Expression
expression =
try application
<|> try (buildExpressionParser table expr)
<|> datatype lambda
<|> expr
expr =
try (parens expression)
<|> try fun
<|> datatype primitive
<|> datatype (list expression)
<|> datatype (vector expression)
<|> var
<|> prefixOp
<?> "expression"
appHead :: GenParser Char st Expression
appHead =
try (parens expression)
<|> var
<|> fun
<|> prefixOp
application :: GenParser Char st Expression
application = Application <$> getPosition <*> appHead <*> (many1 expr) <?> "function"
lambda :: CharParser st Datatype
lambda = Lambda <$> ((reservedOp "\\") *> (commaSep1 var)) <*> ((reservedOp "->") *> expression)
-- some really trivial functions
-- datatypes
atom = Atom <$> atomId
bool = Atom <$> boolId
str = String <$> stringLiteral
number = Number <$> natural
double = Float <$> float
chr = Char <$> charLiteral
list x = List <$> squares (commaSep x)
vector x = Vector <$> parens (commaSep x)
-- expressions
bareFun = Operator <$> getPosition <*> return "" <*> (funcId <|> parens operator)
bareOp = Operator <$> getPosition <*> return "" <*> operator
qualifiedFun = Operator <$> getPosition <*> (upperId2 <* (string moduleOp)) <*> (funcId <|> parens operator)
qualifiedOp = Operator <$> getPosition <*> (upperId2 <* (string moduleOp)) <*> operator
fun = bareFun <|> qualifiedFun
op = bareOp <|> qualifiedOp
prefixOp = barePrefixOp <|> qualifiedPrefixOp
barePrefixOp = Operator <$> getPosition <*> return "" <*> prefixOperator
qualifiedPrefixOp = Operator <$> getPosition <*> (upperId2 <* (string moduleOp)) <*> prefixOperator
var = Variable <$> getPosition <*> varId
datatype x = Datatype <$> getPosition <*> x
-- fmap rules
-- internal functions
op_to_expr :: SourcePos -> String -> [Expression] -> Expression
op_to_expr pos name = Application pos (Operator pos "" name)
prefixop_to_expr :: SourcePos -> String -> [Expression] -> Expression
prefixop_to_expr pos name = Application pos (convert name)
where
convert "+" = Operator pos "" "id"
convert "-" = Operator pos "" "neg"
convert x = Operator pos "" x
| Jem777/deepthought | src/Expr.hs | gpl-3.0 | 4,293 | 200 | 17 | 985 | 1,481 | 781 | 700 | 94 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : HBooru.Parsers.Konachan
-- Copyright : (c) Mateusz Kowalczyk 2013-2014
-- License : GPL-3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Module for parsing content from <http://konachan.com/ Konachan>.
module HBooru.Parsers.Konachan where
import Data.List
import HBooru.Parsers.FieldParsers
import HBooru.Types
import Text.XML.HXT.Core hiding (mkName)
-- | We use this type and its 'Site' instance to distinguish
-- between various parsers.
data Konachan = Konachan deriving (Show, Eq)
-- | Konachan post record
type KonachanPost = PR
'[ "actual_preview_height"
, "actual_preview_width"
, "author"
, "change"
, "created_at"
, "file_size"
, "file_url"
, "frames"
, "frames_pending"
, "frames_pending_string"
, "frames_string"
, "has_children"
, "height"
, "id"
, "is_held"
, "is_shown_in_index"
, "jpeg_file_size"
, "jpeg_height"
, "jpeg_url"
, "jpeg_width"
, "md5"
, "preview_height"
, "preview_url"
, "preview_width"
, "rating"
, "sample_file_size"
, "sample_height"
, "sample_url"
, "sample_width"
, "score"
, "source"
, "status"
, "tags"
, "width"
]
-- | Parser arrow used for Konachan.
parsePost ∷ (Functor (cat XmlTree), ArrowXml cat) ⇒ cat XmlTree KonachanPost
parsePost = hasName "post"
>>> actual_preview_heightA <:+> actual_preview_widthA <:+> authorA
<:+> changeA <:+> created_atA <:+> file_sizeA <:+> file_urlA
<:+> framesA <:+> frames_pendingA <:+> frames_pending_stringA
<:+> frames_stringA <:+> has_childrenA
<:+> heightA <:+> idA <:+> is_heldA <:+> is_shown_in_indexA
<:+> jpeg_file_sizeA <:+> jpeg_heightA <:+> jpeg_urlA <:+> jpeg_widthA
<:+> md5A <:+> preview_heightA <:+> preview_urlA <:+> preview_widthA
<:+> ratingA <:+> sample_file_sizeA <:+> sample_heightA <:+> sample_urlA
<:+> sample_widthA <:+> scoreA <:+> sourceA <:+> statusA <:+> tagsA
<:+> widthA
instance Postable Konachan XML where
postUrl _ _ ts =
let tags' = intercalate "+" ts
in "https://konachan.com/post/index.xml?tags=" ++ tags' ++ "&limit=1000"
hardLimit _ _ = Limit 100
instance PostablePaged Konachan XML where
postUrlPaged s r ts i = postUrl s r ts ++ "&page=" ++ show (i + 1)
instance Site Konachan where
instance PostParser Konachan XML where
type ImageTy Konachan XML = KonachanPost
parseResponse _ = runLA (xreadDoc /> parsePost) . getResponse
instance Counted Konachan XML where
parseCount _ = read . head . runLA (xreadDoc >>> hasName "posts"
>>> getAttrValue "count") . getResponse
| Fuuzetsu/h-booru | src/HBooru/Parsers/Konachan.hs | gpl-3.0 | 2,812 | 0 | 39 | 568 | 569 | 316 | 253 | 72 | 1 |
-- | Handling of the configuration file.
{-# LANGUAGE TemplateHaskell, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, UndecidableInstances #-}
module Adam.FeedTorrent.Config where
import Data.Generics.SYB.WithClass.Derive
import Text.RJson
import Adam.FeedTorrent.Imports
import Adam.FeedTorrent.Data
-- | Configuration record, contains all user settings.
data Config = Config { feedUrls :: [Url]
, torrentDir :: FilePath
, feedDir :: FilePath
, newFeedDir :: FilePath
} deriving (Eq, Show, Read)
$(derive[''Config])
configFromJson :: String -> Either String Config
configFromJson = fromJsonString (undefined :: Config)
-- | Default configuration settings.
defaultConfig :: Config
defaultConfig =
Config { feedUrls = []
, torrentDir = "torrents"
, feedDir = "feeds"
, newFeedDir = "newfeeds" }
-- | Default path to config file.
jsonFile :: FilePath
jsonFile = "config.json"
-- | Parses and fetches the config from disk, or returns a JSON parse
-- error message. If the config file does not exist one is created
-- at the specified path.
getConfig :: IO (Either String Config)
getConfig = do
t <- doesFileExist jsonFile
unless t $ writeConfig defaultConfig
configFromJson <$> readFile jsonFile
-- | Writes a configuration to disk.
writeConfig :: Config -> IO ()
writeConfig = writeFile jsonFile . show . toJson
-- | Path to feed that have not been processed. There will be no file
-- here if the file has been processed.
newFeedPath :: Config -> Feed -> FilePath
newFeedPath cfg feed = newFeedDir cfg </> feedId feed
-- | Path to feed that have been processed. There will be only be a
-- file here if the feed has ever been processed.
oldFeedPath :: Config -> Feed -> FilePath
oldFeedPath cfg feed = feedDir cfg </> feedId feed
-- | The local path to a torrent file belonging to an item. If the
-- | torrent hasn't been fetched the file won't exist.
enclosurePath :: Config -> Item -> FilePath
enclosurePath cfg item = torrentDir cfg </> itemTitle item ++ ".torrent"
| bergmark/feedtorrent | Adam/FeedTorrent/Config.hs | gpl-3.0 | 2,118 | 0 | 9 | 451 | 376 | 209 | 167 | 35 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{- vim: set foldmethod=marker : -}
module Main where
-- Imports ------------------------------------------------------------{{{
import Control.Monad (liftM, when, join)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Except (liftIO)
import Control.Monad.Trans.Except (runExceptT)
import Data.Text ( pack
, unpack
, Text )
import qualified Data.Text as T (concat)
import Data.Function (on)
import Data.Maybe (fromMaybe)
import Data.List (nub)
import Data.XML.Types (elementText, Element)
import Data.ConfigFile ( readfile
, get
, emptyCP)
import Data.ConfigFile.Types (CPError)
import Network.Xmpp ( pullMessage
, sendMessage
, jidFromText
, def
, sendPresence
, scramSha1
, session
, messagePayload
, Message )
import Network.Xmpp.IM (simpleIM)
import System.Log.Logger ( updateGlobalLogger
, setLevel
, Priority(DEBUG) )
import System.Environment (getArgs, getProgName, getEnv)
import System.Console.GetOpt ( getOpt
, ArgDescr (NoArg, ReqArg)
, ArgOrder (Permute)
, OptDescr (Option)
, usageInfo )
import Text.Printf (printf)
-----------------------------------------------------------------------}}}
-- Configuration ------------------------------------------------------{{{
data Config = Config { fileName :: String
, defSection :: String
, hostSpec :: String
, userSpec :: String
, passSpec :: String }
defaultConfig :: Config
defaultConfig = Config { fileName = ".xmppcatrc"
, defSection = "DEFAULT"
, hostSpec = "host"
, userSpec = "user"
, passSpec = "password" }
-----------------------------------------------------------------------}}}
type HostString = String
type UserString = String
type PassString = String
type RxIdString = String
data Option = Host HostString
| User UserString
| Pass PassString
| RxId RxIdString
| Help
| Debug
deriving (Eq,Ord,Show)
type Host = String
type User = Text
type Pass = Text
type RxId = Text
data MsgSpec = MsgSpec { host :: Host
, user :: User
, pass :: Pass
, rxId :: RxId
, text :: Text }
deriving (Eq,Show)
defaultMsgSpec :: MsgSpec
defaultMsgSpec = MsgSpec { host = ""
, user = ""
, pass = ""
, rxId = ""
, text = "" }
mergeMsgSpecs :: MsgSpec -> MsgSpec -> MsgSpec
mergeMsgSpecs specRec specDom =
MsgSpec { host = (mergeSpecS `on` host) specDom specRec
, user = (mergeSpec `on` user) specDom specRec
, pass = (mergeSpec `on` pass) specDom specRec
, rxId = (mergeSpec `on` rxId) specDom specRec
, text = (mergeSpec `on` text) specDom specRec }
where
mergeSpec :: Text -> Text -> Text
mergeSpec rec dom = case dom of
"" -> rec
_ -> dom
mergeSpecS :: String -> String -> String
mergeSpecS rec dom = unpack $ on mergeSpec pack rec dom
options :: [OptDescr Option]
options = [ Option "H" ["host"] (ReqArg Host "<host>")
"XMPP host domain name or IP address."
, Option "U" ["user"] (ReqArg User "<user>")
"User to identify as to the XMPP host."
, Option "P" ["password"] (ReqArg Pass "<password>")
"Password to authenticate 'user' to XMPP host."
, Option "R" ["recipient"] (ReqArg RxId "<recipient>")
"Intended recipient of message."
, Option "h" ["help"] (NoArg Help)
"Print usage help."
, Option "d" ["debug"] (NoArg Debug)
"Enable debugging output." ]
data RunFlags = RunFlags { debug :: Bool }
deriving (Eq,Show)
defaultFlags :: RunFlags
defaultFlags = RunFlags { debug = False }
data CommandSpec = RunHelp
| RunXmppCat MsgSpec
| Error String
deriving (Eq,Show)
getCommandSpec :: [Option] -> [String] -> CommandSpec
getCommandSpec opts msgs = case cleanOpts of
[Help] -> RunHelp
_ -> RunXmppCat $ foldl setOption baseMsgSpec cleanOpts
where
cleanOpts :: [Option]
cleanOpts = nub opts
baseMsgSpec :: MsgSpec
baseMsgSpec = defaultMsgSpec { text = pack $ concat msgs }
setOption :: MsgSpec -> Option -> MsgSpec
setOption msgSpec opt | (Host h) <- opt = msgSpec { host = h }
| (User u) <- opt = msgSpec { user = pack u }
| (Pass p) <- opt = msgSpec { pass = pack p }
| (RxId r) <- opt = msgSpec { rxId = pack r }
| otherwise = msgSpec
getRunFlags :: [Option] -> RunFlags
getRunFlags opts | Debug `elem` opts = defaultFlags {debug = True}
| otherwise = defaultFlags
parseArgs :: [String] -> (CommandSpec, RunFlags)
parseArgs argv = case getOpt Permute options argv of
(opts, msgs, []) -> (getCommandSpec opts msgs, getRunFlags opts)
(_, _, errs) -> (Error $ concat errs, defaultFlags)
usageHeader :: String -> String
usageHeader = printf "Usage: %s [<options>] <message>"
extractResponseText :: Message -> String
extractResponseText = unpack . T.concat . map getPayloadText . messagePayload
where
getPayloadText :: Element -> Text
getPayloadText = T.concat . elementText
parseConfig :: MonadIO m => FilePath -> m (Either CPError MsgSpec)
parseConfig configPath = runExceptT $ do
let configParser = emptyCP
section = defSection defaultConfig
hSpec = hostSpec defaultConfig
uSpec = userSpec defaultConfig
pSpec = passSpec defaultConfig
configReader <- join $ liftIO $ readfile configParser configPath
configHost <- get configReader section hSpec
configUser <- get configReader section uSpec
configPass <- get configReader section pSpec
return $ defaultMsgSpec { host = configHost
, user = pack configUser
, pass = pack configPass }
fetchReply :: MsgSpec -> IO ()
fetchReply msgSpec = do
sessionResult <- session (host msgSpec)
(Just (const [scramSha1 (user msgSpec) Nothing (pass msgSpec)]
, Nothing))
def
currentSession <- case sessionResult of
Right s -> return s
Left e -> error $ "XmppFailure: " ++ show e
_ <- sendPresence def currentSession
let recipient = fromMaybe (error "Error: Failed to find recipient.")
(jidFromText $ rxId msgSpec)
message = simpleIM recipient $ text msgSpec
_ <- sendMessage message currentSession
response <- pullMessage currentSession
case response of
Left errMsg -> error $ "Error: " ++ show errMsg
Right msg -> putStrLn $ extractResponseText msg
main :: IO ()
main = do
(commandSpec, runFlags) <- liftM parseArgs getArgs
when (debug runFlags) $ updateGlobalLogger "xmppcat" $ setLevel DEBUG
case commandSpec of
RunHelp -> getProgName >>= putStrLn . flip usageInfo options . usageHeader
Error err -> error err
RunXmppCat optionMsgSpec -> do
homeDir <- getEnv "HOME"
let configPath = homeDir ++ "/" ++ fileName defaultConfig
configParse <- parseConfig configPath
case configParse of
Left err -> putStrLn $ "Config Error: " ++ show err
Right configMsgSpec -> do
let msgSpec = mergeMsgSpecs optionMsgSpec configMsgSpec
fetchReply msgSpec
| xelxebar/xmppcat | src/Main.hs | gpl-3.0 | 8,873 | 0 | 20 | 3,482 | 2,068 | 1,123 | 945 | 185 | 4 |
import Control.Monad (when)
import System.Exit (exitFailure)
import Test.QuickCheck (quickCheckResult)
import Test.QuickCheck.Test (isSuccess)
import Data.Array.Accelerate hiding (all, not, length)
import Prelude hiding (zipWith)
-- import Data.Array.Accelerate.Interpreter as I
import Data.Array.Accelerate.CUDA as I
import Data.Array.Accelerate.BLAS.Internal.Dot
import Data.Array.Accelerate.BLAS.Internal.Gemm
import Data.Array.Accelerate.BLAS.Internal.Axpy
prop_dot_shape :: [Float] -> [Float] -> Bool
prop_dot_shape v1 v2 = length (toList $ I.run $ sdot ((use (fromList (Z:.(length v1)) v1)), (use (fromList (Z:.(length v2)) v2)))) == 1
prop_dot_440 :: Bool
prop_dot_440 = head (toList $ I.run $ sdot ((use (fromList (Z:.10) [1..])), (use (fromList (Z:.10) [2..11])))) == 440.0
prop_gemv :: Bool
prop_gemv = (toList $ I.run $ gemv ((use (fromList (Z:.3:.3) [0,5,1,2,6,-1,-4,3,7] :: Array DIM2 Float)), (use (fromList (Z:.3) [8,-2,4] :: Vector Float)))) == [-6.0,0.0,-10.0]
prop_gevm :: Bool
prop_gevm = (toList $ I.run $ gevm ((use (fromList (Z:.3) [1..] :: Vector Float)), (use (fromList (Z:.3:.2) [2,1,0,-1,2,4] :: Array DIM2 Float)))) == [8.0,11.0]
prop_outer :: Bool
prop_outer = (toList $ I.run $ gevv ((use (fromList (Z:.4) [1..] :: Vector Float)), (use (fromList (Z:.3) [2,-2,1] :: Vector Float)))) == [2.0,-2.0,1.0,4.0,-4.0,2.0,6.0,-6.0,3.0,8.0,-8.0,4.0]
prop_axpy_integrity :: [Float] -> [Float] -> Bool
prop_axpy_integrity _ [] = True
prop_axpy_integrity [] _ = True
prop_axpy_integrity v1 v2 = (v2 /= v3 || all (\x -> x == 0) v1)
where v3 = toList $ I.run $ axpy ((use (fromList (Z:.(length v1)) v1)), (use (fromList (Z:.(length v2)) v2)))
prop_axpy :: Bool
prop_axpy = (toList $ I.run $ axpy ((use (fromList (Z:.5) [2,4,6,8,10])), (use (fromList (Z:.5) [1..5])))) == [3.0,6.0,9.0,12.0,15.0]
main :: IO ()
main = do
let tests = [ quickCheckResult prop_dot_shape,
quickCheckResult prop_dot_440,
quickCheckResult prop_gemv,
quickCheckResult prop_gevm,
quickCheckResult prop_outer,
quickCheckResult prop_axpy_integrity,
quickCheckResult prop_axpy
]
success <- fmap (all isSuccess) . sequence $ tests
when (not success) $ exitFailure | kathawala/symdiff | tests/Test.hs | gpl-3.0 | 2,277 | 0 | 18 | 408 | 1,111 | 621 | 490 | 38 | 1 |
module ExpectationsAnalyzerSpec(spec) where
import Language.Mulang
import Language.Mulang.Analyzer hiding (result, spec)
import Test.Hspec
result expectationResults smells
= emptyCompletedAnalysisResult { expectationResults = expectationResults, smells = smells }
run language content expectations = analyse (expectationsAnalysis (CodeSample language content) expectations)
runAst ast expectations = analyse (expectationsAnalysis (MulangSample (Just ast)) expectations)
passed e = ExpectationResult e True
failed e = ExpectationResult e False
spec = describe "ExpectationsAnalyzer" $ do
it "works with Mulang input" $ do
let ydeclares = Expectation "*" "Declares:y"
(runAst None [ydeclares]) `shouldReturn` (result [failed ydeclares] [])
it "evaluates unknown basic expectations" $ do
let hasTurtle = Expectation "x" "HasTurtle"
(run Haskell "x = 2" [hasTurtle]) `shouldReturn` (result [passed hasTurtle] [])
it "evaluates unknown basic negated expectations" $ do
let notHasTurtle = Expectation "x" "Not:HasTurtle"
(run Haskell "x = 2" [notHasTurtle]) `shouldReturn` (result [passed notHasTurtle] [])
it "evaluates empty expectations" $ do
(run Haskell "x = 2" []) `shouldReturn` (result [] [])
it "evaluates present named expectations" $ do
let ydeclares = Expectation "*" "Declares:y"
let xdeclares = Expectation "*" "Declares:x"
(run Haskell "x = 2" [ydeclares, xdeclares]) `shouldReturn` (result [failed ydeclares, passed xdeclares] [])
it "evaluates present expectations" $ do
let declaresF = Expectation "*" "DeclaresFunction"
let declaresT = Expectation "*" "DeclaresTypeAlias"
(run Haskell "f x = 2" [declaresF, declaresT]) `shouldReturn` (result [passed declaresF, failed declaresT] [])
it "can be negated" $ do
let notDeclaresX = Expectation "*" "Not:Declares:x"
let notDeclaresY = Expectation "*" "Not:Declares:y"
(run Haskell "x = \"¡\"" [notDeclaresY, notDeclaresX]) `shouldReturn` (result [
passed notDeclaresY, failed notDeclaresX] [])
it "works with Declares" $ do
let xdeclares = Expectation "*" "Declares:x"
let ydeclares = Expectation "*" "Declares:y"
(run Haskell "x = 2" [ydeclares, xdeclares]) `shouldReturn` (result [failed ydeclares, passed xdeclares] [])
it "works with Uses" $ do
let usesy = Expectation "x" "Uses:y"
let usesz = Expectation "x" "Uses:z"
(run Haskell "x = y * 10" [usesy, usesz]) `shouldReturn` (result [passed usesy, failed usesz] [])
it "works with DeclaresComputationWithArity" $ do
let hasArity2 = Expectation "*" "DeclaresComputationWithArity2:foo"
let hasArity3 = Expectation "*" "DeclaresComputationWithArity3:foo"
(run Prolog "foo(x, y)." [hasArity2, hasArity3]) `shouldReturn` (result [passed hasArity2, failed hasArity3] [])
it "works with DeclaresTypeSignature" $ do
let declaresTypeSignature = Expectation "*" "DeclaresTypeSignature:f"
(run Haskell "f x y = y + x" [declaresTypeSignature]) `shouldReturn` (result [failed declaresTypeSignature] [])
(run Haskell "f :: Int -> Int -> Int \nf x y = y + x" [declaresTypeSignature]) `shouldReturn` (result [passed declaresTypeSignature] [])
it "works with DeclaresTypeAlias" $ do
let hasTypeAlias = Expectation "*" "DeclaresTypeAlias:Words"
(run Haskell "type Works = [String]" [hasTypeAlias]) `shouldReturn` (result [failed hasTypeAlias] [])
(run Haskell "data Words = Words" [hasTypeAlias]) `shouldReturn` (result [failed hasTypeAlias] [])
(run Haskell "type Words = [String]" [hasTypeAlias]) `shouldReturn` (result [passed hasTypeAlias] [])
it "works with UsesIf" $ do
let hasIf = Expectation "min" "UsesIf"
(run Haskell "min x y = True" [hasIf]) `shouldReturn` (result [failed hasIf] [])
(run Haskell "min x y = if x < y then x else y" [hasIf]) `shouldReturn` (result [passed hasIf] [])
it "works with UsesGuards" $ do
let hasGuards = Expectation "min" "UsesGuards"
(run Haskell "min x y = x" [hasGuards]) `shouldReturn` (result [failed hasGuards] [])
(run Haskell "min x y | x < y = x | otherwise = y" [hasGuards]) `shouldReturn` (result [passed hasGuards] [])
it "works with UsesAnonymousVariable" $ do
let hasAnonymousVariable = Expectation "c" "UsesAnonymousVariable"
(run Haskell "c x = 14" [hasAnonymousVariable]) `shouldReturn` (result [failed hasAnonymousVariable] [])
(run Haskell "c _ = 14" [hasAnonymousVariable]) `shouldReturn` (result [passed hasAnonymousVariable] [])
it "works with UsesComposition" $ do
let hasComposition = Expectation "h" "UsesComposition"
(run Haskell "h = f" [hasComposition]) `shouldReturn` (result [failed hasComposition] [])
(run Haskell "h = f . g" [hasComposition]) `shouldReturn` (result [passed hasComposition] [])
it "works with UsesForComprehension" $ do
let hasComprehension = Expectation "x" "UsesForComprehension"
(run Haskell "x = [m | m <- t]" [hasComprehension]) `shouldReturn` (result [passed hasComprehension] [])
it "works with UsesForLoop" $ do
let hasForLoop = Expectation "f" "UsesForLoop"
(run JavaScript "function f() { let x; for (x = 0; x < 10; x++) { x; } }" [hasForLoop]) `shouldReturn` (result [passed hasForLoop] [])
it "works with UsesConditional" $ do
let hasConditional = Expectation "min" "UsesConditional"
(run JavaScript "function min(x, y) { if (x < y) { return x } else { return y } }" [hasConditional]) `shouldReturn` (result [
passed hasConditional] [])
it "works with UsesWhile" $ do
let hasWhile = Expectation "f" "UsesWhile"
(run JavaScript "function f() { let x = 5; while (x < 10) { x++ } }" [hasWhile]) `shouldReturn` (result [passed hasWhile] [])
it "works with UsesForall" $ do
let hasForall = Expectation "f" "UsesForall"
(run Prolog "f(X) :- isElement(Usuario), forall(isRelated(X, Y), complies(Y))." [hasForall]) `shouldReturn` (result [
passed hasForall] [])
it "works with UsesFindall" $ do
let hasFindall = Expectation "baz" "UsesFindall"
(run Prolog "baz(X):- bar(X, Y)." [hasFindall]) `shouldReturn` (result [failed hasFindall] [])
(run Prolog "baz(X):- findall(Y, bar(X, Y), Z)." [hasFindall]) `shouldReturn` (result [passed hasFindall] [])
it "works with UsesLambda" $ do
let hasLambda = Expectation "f" "UsesLambda"
(run Haskell "f = map id" [hasLambda]) `shouldReturn` (result [failed hasLambda] [])
(run Haskell "f = map $ \\x -> x + 1" [hasLambda]) `shouldReturn` (result [passed hasLambda] [])
it "works with DeclaresRecursively" $ do
let hasDirectRecursion = Expectation "*" "DeclaresRecursively:f"
(run Haskell "f x = if x < 5 then g (x - 1) else 2" [hasDirectRecursion]) `shouldReturn` (result [failed hasDirectRecursion] [])
(run Haskell "f x = if x < 5 then f (x - 1) else 2" [hasDirectRecursion]) `shouldReturn` (result [passed hasDirectRecursion] [])
it "works with UsesNot" $ do
let hasNot = Expectation "foo" "UsesNot"
(run Prolog "foo(X) :- bar(X)." [hasNot]) `shouldReturn` (result [failed hasNot] [])
(run Prolog "foo(X) :- not(bar(X))." [hasNot]) `shouldReturn` (result [passed hasNot] [])
it "properly reports parsing errors" $ do
let hasNot = Expectation "foo" "UsesNot"
(run Haskell " foo " [hasNot]) `shouldReturn` (AnalysisFailed "Parse error")
it "works with keyword-based expectation synthesis of declares" $ do
let usesType = Expectation "*" "Uses:type"
let declaresTypeAlias = Expectation "*" "DeclaresTypeAlias"
run Haskell "type X = Int" [usesType] `shouldReturn` (result [passed declaresTypeAlias] [])
it "works with keyword-based expectation synthesis of uses" $ do
let usesType = Expectation "*" "Uses:type"
let declaresTypeAlias = Expectation "*" "DeclaresTypeAlias"
run Haskell "type X = Int" [usesType] `shouldReturn` (result [passed declaresTypeAlias] [])
it "works with operator-based expectation synthesis of declares" $ do
let declaresNot = Expectation "*" "Declares:not"
let usesNegation = Expectation "*" "DeclaresNegation"
run Haskell "x = not True" [declaresNot] `shouldReturn` (result [failed usesNegation] [])
it "works with operator-based expectation synthesis of uses" $ do
let usesNot = Expectation "*" "Uses:not"
let usesNegation = Expectation "*" "UsesNegation"
run Haskell "x = not True" [usesNot] `shouldReturn` (result [passed usesNegation] [])
it "works with operators" $ do
let usesNegation = Expectation "*" "UsesNegation"
run Haskell "x = not True" [usesNegation] `shouldReturn` (result [passed usesNegation] [])
it "works with scoped bindings" $ do
let birdWeightUsesPlace = Expectation "bird.weight" "Uses:place"
let birdPositionUsesPlace = Expectation "bird.position" "Uses:place"
let code = "let place = buenosAires; let bird = {position: place, weight: 20};";
run JavaScript code [birdWeightUsesPlace] `shouldReturn` (result [failed birdWeightUsesPlace] [])
run JavaScript code [birdPositionUsesPlace] `shouldReturn` (result [passed birdPositionUsesPlace] [])
it "works with scoped intransitive bindings" $ do
let birdWeightUsesPlace = Expectation "Intransitive:bird.weight" "Uses:place"
let birdPositionUsesPlace = Expectation "Intransitive:bird.position" "Uses:place"
let code = "let place = buenosAires; let bird = {position: place, weight: 20};";
run JavaScript code [birdWeightUsesPlace] `shouldReturn` (result [failed birdWeightUsesPlace] [])
run JavaScript code [birdPositionUsesPlace] `shouldReturn` (result [passed birdPositionUsesPlace] [])
| mumuki/mulang | spec/ExpectationsAnalyzerSpec.hs | gpl-3.0 | 9,897 | 0 | 15 | 2,012 | 2,884 | 1,414 | 1,470 | 139 | 1 |
// In Haskell, a function type is constructed using the arrow type constructor (->)
// which takes two types:
// the argument type and the result type.
// Youve already seen it in infix form, a->b,
// but it can equally well be used in prefix form, when parenthesized: (->) a b
//
// Another explanation:
// (->) is a type function:
// a function that acts on types and produces a type.
// When you apply it to two types, a and b, you get a function type, a->b.
//
// We have to solve the following puzzle:
// given a function f::a->b and a function g::r->a, create a function r->b.
//
// There is only one way we can compose the two functions, f . g
//
// fmap f g = f . g can be written in point-free notation as fmap = (.)
//
instance Functor ((->) r) where
fmap = (.)
// This combination of the type constructor (->) r with the above implementation of fmap
// is called the *reader* functor.
| sujeet4github/MyLangUtils | CategoryTheory_BartoszMilewsky/PI_07_Functors/Reader_Functor.hs | gpl-3.0 | 915 | 63 | 9 | 195 | 448 | 223 | 225 | 2 | 0 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback 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. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Constants where
import Fallback.Data.Point (Point(Point), Rect(Rect), SqDist, ofRadius)
-------------------------------------------------------------------------------
-- Real time:
-- | The number of animation frames the game draws each second.
framesPerSecond :: Int
framesPerSecond = 40
-- | The reciprocal of 'framesPerSecond'.
secondsPerFrame :: Double
secondsPerFrame = recip (fromIntegral framesPerSecond)
-------------------------------------------------------------------------------
-- Screen layout:
screenWidth, screenHeight :: Int
screenWidth = 640
screenHeight = 480
screenRect :: Rect Int
screenRect = Rect 0 0 screenWidth screenHeight
sidebarWidth :: Int
sidebarWidth = 124
cameraWidth, cameraHeight :: Int
cameraWidth = screenWidth - sidebarWidth
cameraHeight = screenHeight
cameraSize :: (Int, Int)
cameraSize = (cameraWidth, cameraHeight)
cameraCenterOffset :: Point Double
cameraCenterOffset =
Point (fromIntegral cameraWidth / 2) (fromIntegral cameraHeight / 2)
-------------------------------------------------------------------------------
-- Terrain:
-- | The width of each terrain tile, in pixels.
tileWidth :: Int
tileWidth = 28
-- | The height of each terrain tile, in pixels.
tileHeight :: Int
tileHeight = 36
-------------------------------------------------------------------------------
-- Combat arena:
combatArenaCols :: Int
combatArenaCols = cameraWidth `div` tileWidth
combatArenaRows :: Int
combatArenaRows = cameraHeight `div` tileHeight
combatArenaSize :: (Int, Int)
combatArenaSize = (combatArenaCols, combatArenaRows)
combatCameraOffset :: Point Int
combatCameraOffset = Point ((cameraWidth `mod` tileWidth) `div` 2)
((cameraHeight `mod` tileHeight) `div` 2)
-------------------------------------------------------------------------------
-- Combat time:
-- | The number of moments required for one action point, where a moment is the
-- smallest unit of a creature's time bar.
momentsPerActionPoint :: Int
momentsPerActionPoint = 100000
-- | The number of moments a creature with a speed of 1 will gain per frame
-- during the combat waiting phase.
baseMomentsPerFrame :: Int
baseMomentsPerFrame =
round (fromIntegral momentsPerActionPoint * secondsPerFrame /
baseSecondsPerActionPoint) where baseSecondsPerActionPoint = 1.0
-- | The number of frames per combat round, where a round is the unit of time
-- between period damage hits (e.g. poison), and also the length of time
-- required for a creature with a speed of 1 to gain one action point. A town
-- step is consided roughly equivalent to one combat round.
framesPerRound :: Int
framesPerRound = round (fromIntegral momentsPerActionPoint /
fromIntegral baseMomentsPerFrame :: Double)
-- | The reciprocal of 'framesPerRound'.
roundsPerFrame :: Double
roundsPerFrame = recip (fromIntegral framesPerRound)
-- | The maximum number of action points that a creature can have at once.
maxActionPoints :: Int
maxActionPoints = 4
maxMoments :: Int
maxMoments = momentsPerActionPoint * maxActionPoints
-------------------------------------------------------------------------------
maxAdrenaline :: Int
maxAdrenaline = 100
sightRange :: Int
sightRange = 10
sightRangeSquared :: SqDist
sightRangeSquared = ofRadius sightRange
talkRadius :: Int
talkRadius = 6
experienceForLevel :: Int -> Int
experienceForLevel 1 = 0
experienceForLevel 2 = 100
experienceForLevel 3 = 2000
experienceForLevel 4 = 5000
experienceForLevel 5 = 9000
experienceForLevel 6 = 14000
experienceForLevel 7 = 20000
experienceForLevel 8 = 27000
experienceForLevel 9 = 35000
experienceForLevel 10 = 44000
experienceForLevel 11 = 54000
experienceForLevel 12 = 65000
experienceForLevel 13 = 77000
experienceForLevel 14 = 90000
experienceForLevel 15 = 104000
experienceForLevel 16 = 119000
experienceForLevel 17 = 135000
experienceForLevel 18 = 152000
experienceForLevel 19 = 170000
experienceForLevel 20 = 189000
experienceForLevel 21 = 209000
experienceForLevel 22 = 230000
experienceForLevel 23 = 252000
experienceForLevel 24 = 275000
experienceForLevel 25 = 299000
experienceForLevel 26 = 324000
experienceForLevel 27 = 350000
experienceForLevel 28 = 377000
experienceForLevel 29 = 405000
experienceForLevel 30 = 434000
experienceForLevel n =
error ("experienceForLevel: argument out of range: " ++ show n)
maxPartyLevel :: Int
maxPartyLevel = 30
-------------------------------------------------------------------------------
| mdsteele/fallback | src/Fallback/Constants.hs | gpl-3.0 | 5,944 | 0 | 9 | 1,328 | 787 | 448 | 339 | 92 | 1 |
module CFrac where {
-- This module defines a Style for the display of a continued fraction (whose coefficients
-- are defined as a list of numbers).
-- Limitations:
-- At present, the size is hardwired into the function. It should be a
-- parameter. Ideally it should make use of the primitive
-- fontSize :: Format -> (Int, Int)
-- function that yields the bounding box of the largest character in the font.
--
-- Further, the "mag" function does not work correctly on the resultant style.
--
-- Yet further: when used as a style with infinite lists, it does not terminate
cFracStyle :: Color -> Style;
cFracStyle txtColor =
let {
font = SansSerif;
ptSize = 20;
w = 50;
h = 30;
fmt = Format font ptSize txtColor False False;
box = Box w h Transparent Transparent;
link = Link (w,(h+5)) True Transparent box;
fs0 = FText box 1 fmt;
fs1 = FLink box link This;
pic0 = Trans 10 20 $ PicText fmt "1";
pic1a = Trans w (h-9) $ PicText fmt "+";
pic1b = Trans (w+w) 21 $ PicText fmt "1";
pic1c = Trans 90 h $ Line 120 0 darkGray;
pic1 = pic1a `Super` pic1b `Super` pic1c;
vs0 = VIndiv NoBox CHide (0,0) [] [] pic0 NoFormat;
vs1 = VIndiv NoBox CHide (20,20) [fs0,fs1] [(0,0), (40,0)] pic1 NoFormat
} in Data [vs0, vs1]
}
| ckaestne/CIDE | CIDE_Language_Haskell/test/fromviral/CFrac.hs | gpl-3.0 | 1,333 | 0 | 12 | 351 | 357 | 206 | 151 | 21 | 1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, DeriveDataTypeable, TemplateHaskell #-}
module Language.Subleq.Configure where
-- import Language.Subleq.Model.Prim
import qualified Language.Subleq.Model.Memory as Mem
-- import Language.Subleq.Model.Architecture.IntMachine
import qualified Language.Subleq.Model.InstructionSet.Subleq as Subleq
import qualified Language.Subleq.Assembly as A
import Language.Subleq.Assembly.Export.Elf2Mem
import Text.Parsec
import Control.Applicative
import Text.PrettyPrint
import qualified Text.PrettyPrint as PP
import Text.Printf
import Data.Maybe
import Data.List
-- import Data.Map (Map)
import qualified Data.Map as M
-- import Control.Monad.State
import Control.Lens
import Data.Typeable
import Data.Data
data LocationMethod = SequenceFrom Int
| UseFrom [Int]
deriving (Read, Show, Data, Typeable)
data SubleqConfig = SubleqConfig { _instructionLength :: Integer
, _wordLengthInAddressingUnit :: Integer
, _wordLengthInBit :: Integer
, _argumentLocations :: LocationMethod
, _staticLocations :: [(A.Id, Integer)]
}
deriving (Read, Show, Data, Typeable)
makeLenses ''SubleqConfig
defaultConfig = SubleqConfig { _instructionLength = 3
, _wordLengthInAddressingUnit = 1
, _wordLengthInBit = 32
, _argumentLocations = SequenceFrom 0
, _staticLocations = [ ("Lo", 32)
, ("Hi", 33)
, ("End", -1)
, ("Z", 23)
, ("T0", 16)
, ("T1", 17)
, ("T2", 18)
, ("T3", 19)
, ("T4", 20)
, ("T5", 21)
, ("T6", 22)
, ("CW", 26)
, ("Inc", 24)
, ("Dec", 25)
]
}
cases2015Config = SubleqConfig { _instructionLength = 3
, _wordLengthInAddressingUnit = 1
, _wordLengthInBit = 32
, _argumentLocations = UseFrom [37, 38, 39]
, _staticLocations = [ ("Lo", 32)
, ("Hi", 33)
, ("End", 999)
, ("Z", 36)
, ("T0", 40)
, ("T1", 41)
, ("T2", 42)
, ("T3", 43)
, ("T4", 44)
, ("T5", 45)
, ("T6", 46)
, ("CW", 47)
, ("Inc", 48)
, ("Dec", 49)
]
}
memoryArchitectureFromConfig :: SubleqConfig -> A.MemoryArchitecture (M.Map Integer Integer)
memoryArchitectureFromConfig c = A.MemoryArchitecture { A.instructionLength = c^.instructionLength
, A.wordLength = c^.wordLengthInAddressingUnit
, A.locateArg = locateArg' . map fromIntegral . useAddrs $ c^.argumentLocations
, A.locateStatic = M.fromList $ c^.staticLocations
, A.writeWord = Mem.write
}
where
useAddrs (SequenceFrom n) = [n..]
useAddrs (UseFrom ns) = ns
locateArg' as xs = M.fromList $ zip xs as
initialValues :: (Num a, Integral a) => a -> M.Map String a
initialValues wl = M.fromList [ ("Inc", -1)
, ("Dec", 1)
, ("CW", wl)
, ("Min", - (2^(wl - 1)))
, ("Max", 2^(wl - 1) - 1)
, ("LMax", 2^(wl `div` 2) - 1)
, ("LMin", (2^(wl `div` 2 - 1)))
, ("HDec", (2^(wl `div` 2)))
, ("HInc", - (2^(wl `div` 2)))
]
initialMemFromConfigure :: (Num a, Ord a) => SubleqConfig -> M.Map a a
initialMemFromConfigure c = foldr (uncurry Mem.write) M.empty ls
where
ls = mapMaybe f sls
sls = mapped._2 %~ fromIntegral $ (c^.staticLocations)
f :: (Num a)=>(A.Id, Integer) -> Maybe (a, a)
f (i, l) = do v <- i `M.lookup` initialValues (c^.wordLengthInBit)
return (fromIntegral l, fromIntegral v)
| Hara-Laboratory/subleq-toolchain | Language/Subleq/Configure.hs | gpl-3.0 | 5,596 | 0 | 13 | 2,951 | 1,147 | 690 | 457 | -1 | -1 |
module Triplet (isPythagorean, mkTriplet, pythagoreanTriplets) where
import Data.List (sort)
isPythagorean :: (Int, Int, Int) -> Bool
isPythagorean (a', b', c') = a * a + b * b == c * c
where
[a, b, c] = sort [a', b', c']
mkTriplet :: Int -> Int -> Int -> (Int, Int, Int)
mkTriplet a' b' c' = (a, b, c)
where
[a, b, c] = sort [a', b', c']
pythagoreanTriplets :: Int -> Int -> [(Int, Int, Int)]
pythagoreanTriplets min max =
[mkTriplet a b c | a <- [min..max], b <- [a..max], c <- [b..max], isPythagorean (a, b, c)]
| daewon/til | exercism/haskell/pythagorean-triplet/src/Triplet.hs | mpl-2.0 | 533 | 0 | 9 | 118 | 285 | 163 | 122 | 11 | 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.DataFusion.Projects.Locations.Operations.Cancel
-- 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)
--
-- Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.operations.cancel@.
module Network.Google.Resource.DataFusion.Projects.Locations.Operations.Cancel
(
-- * REST Resource
ProjectsLocationsOperationsCancelResource
-- * Creating a Request
, projectsLocationsOperationsCancel
, ProjectsLocationsOperationsCancel
-- * Request Lenses
, plocXgafv
, plocUploadProtocol
, plocAccessToken
, plocUploadType
, plocPayload
, plocName
, plocCallback
) where
import Network.Google.DataFusion.Types
import Network.Google.Prelude
-- | A resource alias for @datafusion.projects.locations.operations.cancel@ method which the
-- 'ProjectsLocationsOperationsCancel' request conforms to.
type ProjectsLocationsOperationsCancelResource =
"v1" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CancelOperationRequest :>
Post '[JSON] Empty
-- | Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ 'projectsLocationsOperationsCancel' smart constructor.
data ProjectsLocationsOperationsCancel =
ProjectsLocationsOperationsCancel'
{ _plocXgafv :: !(Maybe Xgafv)
, _plocUploadProtocol :: !(Maybe Text)
, _plocAccessToken :: !(Maybe Text)
, _plocUploadType :: !(Maybe Text)
, _plocPayload :: !CancelOperationRequest
, _plocName :: !Text
, _plocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsOperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plocXgafv'
--
-- * 'plocUploadProtocol'
--
-- * 'plocAccessToken'
--
-- * 'plocUploadType'
--
-- * 'plocPayload'
--
-- * 'plocName'
--
-- * 'plocCallback'
projectsLocationsOperationsCancel
:: CancelOperationRequest -- ^ 'plocPayload'
-> Text -- ^ 'plocName'
-> ProjectsLocationsOperationsCancel
projectsLocationsOperationsCancel pPlocPayload_ pPlocName_ =
ProjectsLocationsOperationsCancel'
{ _plocXgafv = Nothing
, _plocUploadProtocol = Nothing
, _plocAccessToken = Nothing
, _plocUploadType = Nothing
, _plocPayload = pPlocPayload_
, _plocName = pPlocName_
, _plocCallback = Nothing
}
-- | V1 error format.
plocXgafv :: Lens' ProjectsLocationsOperationsCancel (Maybe Xgafv)
plocXgafv
= lens _plocXgafv (\ s a -> s{_plocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plocUploadProtocol :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadProtocol
= lens _plocUploadProtocol
(\ s a -> s{_plocUploadProtocol = a})
-- | OAuth access token.
plocAccessToken :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocAccessToken
= lens _plocAccessToken
(\ s a -> s{_plocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plocUploadType :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadType
= lens _plocUploadType
(\ s a -> s{_plocUploadType = a})
-- | Multipart request metadata.
plocPayload :: Lens' ProjectsLocationsOperationsCancel CancelOperationRequest
plocPayload
= lens _plocPayload (\ s a -> s{_plocPayload = a})
-- | The name of the operation resource to be cancelled.
plocName :: Lens' ProjectsLocationsOperationsCancel Text
plocName = lens _plocName (\ s a -> s{_plocName = a})
-- | JSONP
plocCallback :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocCallback
= lens _plocCallback (\ s a -> s{_plocCallback = a})
instance GoogleRequest
ProjectsLocationsOperationsCancel
where
type Rs ProjectsLocationsOperationsCancel = Empty
type Scopes ProjectsLocationsOperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsOperationsCancel'{..}
= go _plocName _plocXgafv _plocUploadProtocol
_plocAccessToken
_plocUploadType
_plocCallback
(Just AltJSON)
_plocPayload
dataFusionService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsOperationsCancelResource)
mempty
| brendanhay/gogol | gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Operations/Cancel.hs | mpl-2.0 | 6,638 | 0 | 16 | 1,357 | 794 | 470 | 324 | 115 | 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.Healthcare.Projects.Locations.DataSets.DicomStores.TestIAMPermissions
-- 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 permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a \`NOT_FOUND\` error. Note: This operation is designed to be used
-- for building permission-aware UIs and command-line tools, not for
-- authorization checking. This operation may \"fail open\" without
-- warning.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.testIamPermissions@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.TestIAMPermissions
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresTestIAMPermissionsResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresTestIAMPermissions
, ProjectsLocationsDataSetsDicomStoresTestIAMPermissions
-- * Request Lenses
, pldsdstipXgafv
, pldsdstipUploadProtocol
, pldsdstipAccessToken
, pldsdstipUploadType
, pldsdstipPayload
, pldsdstipResource
, pldsdstipCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.testIamPermissions@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresTestIAMPermissions' request conforms to.
type ProjectsLocationsDataSetsDicomStoresTestIAMPermissionsResource
=
"v1" :>
CaptureMode "resource" "testIamPermissions" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestIAMPermissionsRequest :>
Post '[JSON] TestIAMPermissionsResponse
-- | Returns permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a \`NOT_FOUND\` error. Note: This operation is designed to be used
-- for building permission-aware UIs and command-line tools, not for
-- authorization checking. This operation may \"fail open\" without
-- warning.
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresTestIAMPermissions' smart constructor.
data ProjectsLocationsDataSetsDicomStoresTestIAMPermissions =
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions'
{ _pldsdstipXgafv :: !(Maybe Xgafv)
, _pldsdstipUploadProtocol :: !(Maybe Text)
, _pldsdstipAccessToken :: !(Maybe Text)
, _pldsdstipUploadType :: !(Maybe Text)
, _pldsdstipPayload :: !TestIAMPermissionsRequest
, _pldsdstipResource :: !Text
, _pldsdstipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldsdstipXgafv'
--
-- * 'pldsdstipUploadProtocol'
--
-- * 'pldsdstipAccessToken'
--
-- * 'pldsdstipUploadType'
--
-- * 'pldsdstipPayload'
--
-- * 'pldsdstipResource'
--
-- * 'pldsdstipCallback'
projectsLocationsDataSetsDicomStoresTestIAMPermissions
:: TestIAMPermissionsRequest -- ^ 'pldsdstipPayload'
-> Text -- ^ 'pldsdstipResource'
-> ProjectsLocationsDataSetsDicomStoresTestIAMPermissions
projectsLocationsDataSetsDicomStoresTestIAMPermissions pPldsdstipPayload_ pPldsdstipResource_ =
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions'
{ _pldsdstipXgafv = Nothing
, _pldsdstipUploadProtocol = Nothing
, _pldsdstipAccessToken = Nothing
, _pldsdstipUploadType = Nothing
, _pldsdstipPayload = pPldsdstipPayload_
, _pldsdstipResource = pPldsdstipResource_
, _pldsdstipCallback = Nothing
}
-- | V1 error format.
pldsdstipXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions (Maybe Xgafv)
pldsdstipXgafv
= lens _pldsdstipXgafv
(\ s a -> s{_pldsdstipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldsdstipUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions (Maybe Text)
pldsdstipUploadProtocol
= lens _pldsdstipUploadProtocol
(\ s a -> s{_pldsdstipUploadProtocol = a})
-- | OAuth access token.
pldsdstipAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions (Maybe Text)
pldsdstipAccessToken
= lens _pldsdstipAccessToken
(\ s a -> s{_pldsdstipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldsdstipUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions (Maybe Text)
pldsdstipUploadType
= lens _pldsdstipUploadType
(\ s a -> s{_pldsdstipUploadType = a})
-- | Multipart request metadata.
pldsdstipPayload :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions TestIAMPermissionsRequest
pldsdstipPayload
= lens _pldsdstipPayload
(\ s a -> s{_pldsdstipPayload = a})
-- | REQUIRED: The resource for which the policy detail is being requested.
-- See the operation documentation for the appropriate value for this
-- field.
pldsdstipResource :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions Text
pldsdstipResource
= lens _pldsdstipResource
(\ s a -> s{_pldsdstipResource = a})
-- | JSONP
pldsdstipCallback :: Lens' ProjectsLocationsDataSetsDicomStoresTestIAMPermissions (Maybe Text)
pldsdstipCallback
= lens _pldsdstipCallback
(\ s a -> s{_pldsdstipCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions
where
type Rs
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions
= TestIAMPermissionsResponse
type Scopes
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresTestIAMPermissions'{..}
= go _pldsdstipResource _pldsdstipXgafv
_pldsdstipUploadProtocol
_pldsdstipAccessToken
_pldsdstipUploadType
_pldsdstipCallback
(Just AltJSON)
_pldsdstipPayload
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresTestIAMPermissionsResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/TestIAMPermissions.hs | mpl-2.0 | 7,439 | 0 | 16 | 1,444 | 791 | 467 | 324 | 126 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.