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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS -XCPP -#include "comPrim.h" #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Win32.Com.Exception
-- Copyright : (c) 2009, Sigbjorn Finne
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Representing and working with COM's 'exception model' (@HRESULT@s) in Haskell.
-- Failures in COM method calls are mapped into 'Control.Exception' Haskell exceptions,
-- providing convenient handlers to catch and throw these.
--
-----------------------------------------------------------------------------
module System.Win32.Com.Exception where
import System.Win32.Com.HDirect.HDirect hiding ( readFloat )
import System.Win32.Com.Base
import Data.Int
import Data.Word
import Data.Bits
import Data.Dynamic
import Data.Maybe ( isJust, fromMaybe )
import Numeric ( showHex )
import System.IO.Error ( ioeGetErrorString )
#if BASE == 3
import GHC.IOBase
import Control.Exception
-- | @act `catchComException` (ex -> hdlr ex)@ performs the
-- IO action @act@, but catches any IO or COM exceptions @ex@,
-- passing them to the handler @hdlr@.
catchComException :: IO a -> (Com_Exception -> IO a) -> IO a
catchComException act hdlr =
Control.Exception.catch act
(\ ex ->
case ex of
DynException d ->
case fromDynamic d of
Just ce -> hdlr (Right ce)
_ -> throwIO ex
IOException ioe -> hdlr (Left ioe)
_ -> throwIO ex)
catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a
catch_ce_ act hdlr =
catchComException
act
(\ e ->
case e of
Left ioe -> hdlr Nothing
Right ce -> hdlr (Just ce))
#else
import Control.Exception
-- | @act `catchComException` (ex -> hdlr ex)@ performs the
-- IO action @act@, but catches any IO or COM exceptions @ex@,
-- passing them to the handler @hdlr@.
catchComException :: IO a -> (Com_Exception -> IO a) -> IO a
catchComException act hdlr =
Control.Exception.catch act
(\ e ->
case fromException e of
Just ioe -> hdlr (Left ioe)
_ -> case fromException e of
Just d -> hdlr (Right d)
_ -> throwIO e)
catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a
catch_ce_ act hdlr =
catchComException
act
(\ e ->
case e of
Left ioe -> hdlr Nothing
Right ce -> hdlr (Just ce))
#endif
-- | @Com_Exception@ is either an 'IOException' or 'ComException';
-- no attempt is made to embed one inside the other.
type Com_Exception = Either IOException ComException
-- | @throwIOComException ex@ raises/throws the exception @ex@;
-- @ex@ is either an 'IOException' or a 'ComException'.
throwIOComException :: Com_Exception -> IO a
throwIOComException (Left e) = ioError e
throwIOComException (Right ce) = throwComException ce
-- | @check2HR hr@ triggers a COM exception if the HRESULT
-- @hr@ represent an error condition. The current /last error/
-- value embedded in the exception gives more information about
-- cause.
check2HR :: HRESULT -> IO ()
check2HR hr
| succeeded hr = return ()
| otherwise = do
dw <- getLastError
coFailHR (word32ToInt32 dw)
-- | @checkBool mbZero@ raises a COM exception if @mbZero@ is equal
-- to...zero. The /last error/ is embedded inside the exception.
checkBool :: Int32 -> IO ()
checkBool flg
| flg /=0 = return ()
| otherwise = do
dw <- getLastError
coFailHR (word32ToInt32 dw)
-- | @returnHR act@ runs the IO action @act@, catching any
-- COM exceptions. Success or failure is then mapped back into
-- the corresponding HRESULT. In the case of success, 's_OK'.
returnHR :: IO () -> IO HRESULT
returnHR act =
catch_ce_
(act >> return s_OK)
(\ mb_hr -> return (maybe failure toHR mb_hr))
where
toHR ComException{comException=(ComError hr)} = hr
-- better return codes could easily be imagined..
failure = e_FAIL
-- | @isCoError e@ returns @True@ for COM exceptions; @False@
-- for IO exception values.
isCoError :: Com_Exception -> Bool
isCoError Right{} = True
isCoError Left{} = False
-- | @coGetException ei@ picks out the COM exception @ei@, if one.
coGetException :: Com_Exception -> Maybe ComException
coGetException (Right ce) = Just ce
coGetException _ = Nothing
-- | @coGetException ei@ picks out the COM HRESULT from the exception, if any.
coGetErrorHR :: Com_Exception -> Maybe HRESULT
coGetErrorHR Left{} = Nothing
coGetErrorHR (Right ce) = Just (case comException ce of (ComError hr) -> hr)
-- | @coGetException ei@ returns a user-friendlier representation of the @ei@ exception.
coGetErrorString :: Com_Exception -> String
coGetErrorString (Left ioe) = ioeGetErrorString ioe
coGetErrorString (Right ce) =
comExceptionMsg ce ++
showParen True (showHex (int32ToWord32 (comExceptionHR ce))) ""
printComError :: Com_Exception -> IO ()
printComError ce = putStrLn (coGetErrorString ce)
-- | An alias to 'coGetErrorString'.
hresultToString :: HRESULT -> IO String
hresultToString = stringFromHR
coAssert :: Bool -> String -> IO ()
coAssert True msg = return ()
coAssert False msg = coFail msg
coOnFail :: IO a -> String -> IO a
coOnFail io msg = catchComException io
(\ e ->
case e of
Left ioe -> coFail (msg ++ ": " ++ ioeGetErrorString ioe)
Right ce -> coFail (msg ++ ": " ++ comExceptionMsg ce))
-- | @coFail msg@ raised the @E_FAIL@ COM exception along with
-- the descriptive string @msg@.
coFail :: String -> IO a
coFail = coFailWithHR e_FAIL
-- | @s_OK@ and @s_FALSE@ are the boolean values encoded as 'HRESULT's.
s_FALSE, s_OK :: HRESULT
s_OK = 0
s_FALSE = 1
nOERROR :: HRESULT
nOERROR = 0
nO_ERROR :: HRESULT
nO_ERROR = 0
sEVERITY_ERROR :: Int32
sEVERITY_ERROR = 1
sEVERITY_SUCCESS :: Int32
sEVERITY_SUCCESS = 0
succeeded :: HRESULT -> Bool
succeeded hr = hr >=0
winErrorToHR :: Int32 -> HRESULT
winErrorToHR 0 = 0
winErrorToHR x = (fACILITY_WIN32 `shiftL` 16) .|. (bit 31) .|. (x .&. 0xffff)
hRESULT_CODE :: HRESULT -> Int32
hRESULT_CODE hr = hr .&. (fromIntegral 0xffff)
hRESULT_FACILITY :: HRESULT -> Int32
hRESULT_FACILITY hr = (hr `shiftR` 16) .&. 0x1fff
hRESULT_SEVERITY :: HRESULT -> Int32
hRESULT_SEVERITY hr = (hr `shiftR` 31) .&. 0x1
mkHRESULT :: Int32 -> Int32 -> Int32 -> HRESULT
mkHRESULT sev fac code =
word32ToInt32 (
((int32ToWord32 sev) `shiftL` 31) .|.
((int32ToWord32 fac) `shiftL` 16) .|.
(int32ToWord32 code)
)
cAT_E_CATIDNOEXIST :: HRESULT
cAT_E_CATIDNOEXIST = word32ToInt32 (0x80040160 ::Word32)
cAT_E_FIRST :: HRESULT
cAT_E_FIRST = word32ToInt32 (0x80040160 ::Word32)
cAT_E_LAST :: HRESULT
cAT_E_LAST = word32ToInt32 (0x80040161 ::Word32)
cAT_E_NODESCRIPTION :: HRESULT
cAT_E_NODESCRIPTION = word32ToInt32 (0x80040161 ::Word32)
cLASS_E_CLASSNOTAVAILABLE :: HRESULT
cLASS_E_CLASSNOTAVAILABLE = word32ToInt32 (0x80040111 ::Word32)
cLASS_E_NOAGGREGATION :: HRESULT
cLASS_E_NOAGGREGATION = word32ToInt32 (0x80040110 ::Word32)
cLASS_E_NOTLICENSED :: HRESULT
cLASS_E_NOTLICENSED = word32ToInt32 (0x80040112 ::Word32)
cO_E_ACCESSCHECKFAILED :: HRESULT
cO_E_ACCESSCHECKFAILED = word32ToInt32 (0x80040207 ::Word32)
cO_E_ACESINWRONGORDER :: HRESULT
cO_E_ACESINWRONGORDER = word32ToInt32 (0x80040217 ::Word32)
cO_E_ACNOTINITIALIZED :: HRESULT
cO_E_ACNOTINITIALIZED = word32ToInt32 (0x8004021B ::Word32)
cO_E_ALREADYINITIALIZED :: HRESULT
cO_E_ALREADYINITIALIZED = word32ToInt32 (0x800401F1 ::Word32)
cO_E_APPDIDNTREG :: HRESULT
cO_E_APPDIDNTREG = word32ToInt32 (0x800401FE ::Word32)
cO_E_APPNOTFOUND :: HRESULT
cO_E_APPNOTFOUND = word32ToInt32 (0x800401F5 ::Word32)
cO_E_APPSINGLEUSE :: HRESULT
cO_E_APPSINGLEUSE = word32ToInt32 (0x800401F6 ::Word32)
cO_E_BAD_PATH :: HRESULT
cO_E_BAD_PATH = word32ToInt32 (0x80080004 ::Word32)
cO_E_BAD_SERVER_NAME :: HRESULT
cO_E_BAD_SERVER_NAME = word32ToInt32 (0x80004014 ::Word32)
cO_E_CANTDETERMINECLASS :: HRESULT
cO_E_CANTDETERMINECLASS = word32ToInt32 (0x800401F2 ::Word32)
cO_E_CANT_REMOTE :: HRESULT
cO_E_CANT_REMOTE = word32ToInt32 (0x80004013 ::Word32)
cO_E_CLASSSTRING :: HRESULT
cO_E_CLASSSTRING = word32ToInt32 (0x800401F3 ::Word32)
cO_E_CLASS_CREATE_FAILED :: HRESULT
cO_E_CLASS_CREATE_FAILED = word32ToInt32 (0x80080001 ::Word32)
cO_E_CLSREG_INCONSISTENT :: HRESULT
cO_E_CLSREG_INCONSISTENT = word32ToInt32 (0x8000401F ::Word32)
cO_E_CONVERSIONFAILED :: HRESULT
cO_E_CONVERSIONFAILED = word32ToInt32 (0x8004020B ::Word32)
cO_E_CREATEPROCESS_FAILURE :: HRESULT
cO_E_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004018 ::Word32)
cO_E_DECODEFAILED :: HRESULT
cO_E_DECODEFAILED = word32ToInt32 (0x8004021A ::Word32)
cO_E_DLLNOTFOUND :: HRESULT
cO_E_DLLNOTFOUND = word32ToInt32 (0x800401F8 ::Word32)
cO_E_ERRORINAPP :: HRESULT
cO_E_ERRORINAPP = word32ToInt32 (0x800401F7 ::Word32)
cO_E_ERRORINDLL :: HRESULT
cO_E_ERRORINDLL = word32ToInt32 (0x800401F9 ::Word32)
cO_E_EXCEEDSYSACLLIMIT :: HRESULT
cO_E_EXCEEDSYSACLLIMIT = word32ToInt32 (0x80040216 ::Word32)
cO_E_FAILEDTOCLOSEHANDLE :: HRESULT
cO_E_FAILEDTOCLOSEHANDLE = word32ToInt32 (0x80040215 ::Word32)
cO_E_FAILEDTOCREATEFILE :: HRESULT
cO_E_FAILEDTOCREATEFILE = word32ToInt32 (0x80040214 ::Word32)
cO_E_FAILEDTOGENUUID :: HRESULT
cO_E_FAILEDTOGENUUID = word32ToInt32 (0x80040213 ::Word32)
cO_E_FAILEDTOGETSECCTX :: HRESULT
cO_E_FAILEDTOGETSECCTX = word32ToInt32 (0x80040201 ::Word32)
cO_E_FAILEDTOGETTOKENINFO :: HRESULT
cO_E_FAILEDTOGETTOKENINFO = word32ToInt32 (0x80040203 ::Word32)
cO_E_FAILEDTOGETWINDIR :: HRESULT
cO_E_FAILEDTOGETWINDIR = word32ToInt32 (0x80040211 ::Word32)
cO_E_FAILEDTOIMPERSONATE :: HRESULT
cO_E_FAILEDTOIMPERSONATE = word32ToInt32 (0x80040200 ::Word32)
cO_E_FAILEDTOOPENPROCESSTOKEN :: HRESULT
cO_E_FAILEDTOOPENPROCESSTOKEN = word32ToInt32 (0x80040219 ::Word32)
cO_E_FAILEDTOOPENTHREADTOKEN :: HRESULT
cO_E_FAILEDTOOPENTHREADTOKEN = word32ToInt32 (0x80040202 ::Word32)
cO_E_FAILEDTOQUERYCLIENTBLANKET :: HRESULT
cO_E_FAILEDTOQUERYCLIENTBLANKET = word32ToInt32 (0x80040205 ::Word32)
cO_E_FAILEDTOSETDACL :: HRESULT
cO_E_FAILEDTOSETDACL = word32ToInt32 (0x80040206 ::Word32)
cO_E_FIRST :: HRESULT
cO_E_FIRST = word32ToInt32 (0x800401F0 ::Word32)
cO_E_IIDREG_INCONSISTENT :: HRESULT
cO_E_IIDREG_INCONSISTENT = word32ToInt32 (0x80004020 ::Word32)
cO_E_IIDSTRING :: HRESULT
cO_E_IIDSTRING = word32ToInt32 (0x800401F4 ::Word32)
cO_E_INCOMPATIBLESTREAMVERSION :: HRESULT
cO_E_INCOMPATIBLESTREAMVERSION = word32ToInt32 (0x80040218 ::Word32)
cO_E_INIT_CLASS_CACHE :: HRESULT
cO_E_INIT_CLASS_CACHE = word32ToInt32 (0x80004009 ::Word32)
cO_E_INIT_MEMORY_ALLOCATOR :: HRESULT
cO_E_INIT_MEMORY_ALLOCATOR = word32ToInt32 (0x80004008 ::Word32)
cO_E_INIT_ONLY_SINGLE_THREADED :: HRESULT
cO_E_INIT_ONLY_SINGLE_THREADED = word32ToInt32 (0x80004012 ::Word32)
cO_E_INIT_RPC_CHANNEL :: HRESULT
cO_E_INIT_RPC_CHANNEL = word32ToInt32 (0x8000400A ::Word32)
cO_E_INIT_SCM_EXEC_FAILURE :: HRESULT
cO_E_INIT_SCM_EXEC_FAILURE = word32ToInt32 (0x80004011 ::Word32)
cO_E_INIT_SCM_FILE_MAPPING_EXISTS :: HRESULT
cO_E_INIT_SCM_FILE_MAPPING_EXISTS = word32ToInt32 (0x8000400F ::Word32)
cO_E_INIT_SCM_MAP_VIEW_OF_FILE :: HRESULT
cO_E_INIT_SCM_MAP_VIEW_OF_FILE = word32ToInt32 (0x80004010 ::Word32)
cO_E_INIT_SCM_MUTEX_EXISTS :: HRESULT
cO_E_INIT_SCM_MUTEX_EXISTS = word32ToInt32 (0x8000400E ::Word32)
cO_E_INIT_SHARED_ALLOCATOR :: HRESULT
cO_E_INIT_SHARED_ALLOCATOR = word32ToInt32 (0x80004007 ::Word32)
cO_E_INIT_TLS :: HRESULT
cO_E_INIT_TLS = word32ToInt32 (0x80004006 ::Word32)
cO_E_INIT_TLS_CHANNEL_CONTROL :: HRESULT
cO_E_INIT_TLS_CHANNEL_CONTROL = word32ToInt32 (0x8000400C ::Word32)
cO_E_INIT_TLS_SET_CHANNEL_CONTROL :: HRESULT
cO_E_INIT_TLS_SET_CHANNEL_CONTROL = word32ToInt32 (0x8000400B ::Word32)
cO_E_INIT_UNACCEPTED_USER_ALLOCATOR :: HRESULT
cO_E_INIT_UNACCEPTED_USER_ALLOCATOR = word32ToInt32 (0x8000400D ::Word32)
cO_E_INVALIDSID :: HRESULT
cO_E_INVALIDSID = word32ToInt32 (0x8004020A ::Word32)
cO_E_LAST :: HRESULT
cO_E_LAST = word32ToInt32 (0x800401FF ::Word32)
cO_E_LAUNCH_PERMSSION_DENIED :: HRESULT
cO_E_LAUNCH_PERMSSION_DENIED = word32ToInt32 (0x8000401B ::Word32)
cO_E_LOOKUPACCNAMEFAILED :: HRESULT
cO_E_LOOKUPACCNAMEFAILED = word32ToInt32 (0x8004020F ::Word32)
cO_E_LOOKUPACCSIDFAILED :: HRESULT
cO_E_LOOKUPACCSIDFAILED = word32ToInt32 (0x8004020D ::Word32)
cO_E_MSI_ERROR :: HRESULT
cO_E_MSI_ERROR = word32ToInt32 (0x80004023 ::Word32)
cO_E_NETACCESSAPIFAILED :: HRESULT
cO_E_NETACCESSAPIFAILED = word32ToInt32 (0x80040208 ::Word32)
cO_E_NOMATCHINGNAMEFOUND :: HRESULT
cO_E_NOMATCHINGNAMEFOUND = word32ToInt32 (0x8004020E ::Word32)
cO_E_NOMATCHINGSIDFOUND :: HRESULT
cO_E_NOMATCHINGSIDFOUND = word32ToInt32 (0x8004020C ::Word32)
cO_E_NOTINITIALIZED :: HRESULT
cO_E_NOTINITIALIZED = word32ToInt32 (0x800401F0 ::Word32)
cO_E_NOT_SUPPORTED :: HRESULT
cO_E_NOT_SUPPORTED = word32ToInt32 (0x80004021 ::Word32)
cO_E_OBJISREG :: HRESULT
cO_E_OBJISREG = word32ToInt32 (0x800401FC ::Word32)
cO_E_OBJNOTCONNECTED :: HRESULT
cO_E_OBJNOTCONNECTED = word32ToInt32 (0x800401FD ::Word32)
cO_E_OBJNOTREG :: HRESULT
cO_E_OBJNOTREG = word32ToInt32 (0x800401FB ::Word32)
cO_E_OBJSRV_RPC_FAILURE :: HRESULT
cO_E_OBJSRV_RPC_FAILURE = word32ToInt32 (0x80080006 ::Word32)
cO_E_OLE1DDE_DISABLED :: HRESULT
cO_E_OLE1DDE_DISABLED = word32ToInt32 (0x80004016 ::Word32)
cO_E_PATHTOOLONG :: HRESULT
cO_E_PATHTOOLONG = word32ToInt32 (0x80040212 ::Word32)
cO_E_RELEASED :: HRESULT
cO_E_RELEASED = word32ToInt32 (0x800401FF ::Word32)
cO_E_RELOAD_DLL :: HRESULT
cO_E_RELOAD_DLL = word32ToInt32 (0x80004022 ::Word32)
cO_E_REMOTE_COMMUNICATION_FAILURE :: HRESULT
cO_E_REMOTE_COMMUNICATION_FAILURE = word32ToInt32 (0x8000401D ::Word32)
cO_E_RUNAS_CREATEPROCESS_FAILURE :: HRESULT
cO_E_RUNAS_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004019 ::Word32)
cO_E_RUNAS_LOGON_FAILURE :: HRESULT
cO_E_RUNAS_LOGON_FAILURE = word32ToInt32 (0x8000401A ::Word32)
cO_E_RUNAS_SYNTAX :: HRESULT
cO_E_RUNAS_SYNTAX = word32ToInt32 (0x80004017 ::Word32)
cO_E_SCM_ERROR :: HRESULT
cO_E_SCM_ERROR = word32ToInt32 (0x80080002 ::Word32)
cO_E_SCM_RPC_FAILURE :: HRESULT
cO_E_SCM_RPC_FAILURE = word32ToInt32 (0x80080003 ::Word32)
cO_E_SERVER_EXEC_FAILURE :: HRESULT
cO_E_SERVER_EXEC_FAILURE = word32ToInt32 (0x80080005 ::Word32)
cO_E_SERVER_START_TIMEOUT :: HRESULT
cO_E_SERVER_START_TIMEOUT = word32ToInt32 (0x8000401E ::Word32)
cO_E_SERVER_STOPPING :: HRESULT
cO_E_SERVER_STOPPING = word32ToInt32 (0x80080008 ::Word32)
cO_E_SETSERLHNDLFAILED :: HRESULT
cO_E_SETSERLHNDLFAILED = word32ToInt32 (0x80040210 ::Word32)
cO_E_START_SERVICE_FAILURE :: HRESULT
cO_E_START_SERVICE_FAILURE = word32ToInt32 (0x8000401C ::Word32)
cO_E_TRUSTEEDOESNTMATCHCLIENT :: HRESULT
cO_E_TRUSTEEDOESNTMATCHCLIENT = word32ToInt32 (0x80040204 ::Word32)
cO_E_WRONGOSFORAPP :: HRESULT
cO_E_WRONGOSFORAPP = word32ToInt32 (0x800401FA ::Word32)
cO_E_WRONGTRUSTEENAMESYNTAX :: HRESULT
cO_E_WRONGTRUSTEENAMESYNTAX = word32ToInt32 (0x80040209 ::Word32)
cO_E_WRONG_SERVER_IDENTITY :: HRESULT
cO_E_WRONG_SERVER_IDENTITY = word32ToInt32 (0x80004015 ::Word32)
cO_S_FIRST :: HRESULT
cO_S_FIRST = word32ToInt32 (0x000401F0 ::Word32)
cO_S_LAST :: HRESULT
cO_S_LAST = word32ToInt32 (0x000401FF ::Word32)
cO_S_NOTALLINTERFACES :: HRESULT
cO_S_NOTALLINTERFACES = word32ToInt32 (0x00080012 ::Word32)
dISP_E_ARRAYISLOCKED :: HRESULT
dISP_E_ARRAYISLOCKED = word32ToInt32 (0x8002000D ::Word32)
dISP_E_BADCALLEE :: HRESULT
dISP_E_BADCALLEE = word32ToInt32 (0x80020010 ::Word32)
dISP_E_BADINDEX :: HRESULT
dISP_E_BADINDEX = word32ToInt32 (0x8002000B ::Word32)
dISP_E_BADPARAMCOUNT :: HRESULT
dISP_E_BADPARAMCOUNT = word32ToInt32 (0x8002000E ::Word32)
dISP_E_BADVARTYPE :: HRESULT
dISP_E_BADVARTYPE = word32ToInt32 (0x80020008 ::Word32)
dISP_E_DIVBYZERO :: HRESULT
dISP_E_DIVBYZERO = word32ToInt32 (0x80020012 ::Word32)
dISP_E_EXCEPTION :: HRESULT
dISP_E_EXCEPTION = word32ToInt32 (0x80020009 ::Word32)
dISP_E_MEMBERNOTFOUND :: HRESULT
dISP_E_MEMBERNOTFOUND = word32ToInt32 (0x80020003 ::Word32)
dISP_E_NONAMEDARGS :: HRESULT
dISP_E_NONAMEDARGS = word32ToInt32 (0x80020007 ::Word32)
dISP_E_NOTACOLLECTION :: HRESULT
dISP_E_NOTACOLLECTION = word32ToInt32 (0x80020011 ::Word32)
dISP_E_OVERFLOW :: HRESULT
dISP_E_OVERFLOW = word32ToInt32 (0x8002000A ::Word32)
dISP_E_PARAMNOTFOUND :: HRESULT
dISP_E_PARAMNOTFOUND = word32ToInt32 (0x80020004 ::Word32)
dISP_E_PARAMNOTOPTIONAL :: HRESULT
dISP_E_PARAMNOTOPTIONAL = word32ToInt32 (0x8002000F ::Word32)
dISP_E_TYPEMISMATCH :: HRESULT
dISP_E_TYPEMISMATCH = word32ToInt32 (0x80020005 ::Word32)
dISP_E_UNKNOWNINTERFACE :: HRESULT
dISP_E_UNKNOWNINTERFACE = word32ToInt32 (0x80020001 ::Word32)
dISP_E_UNKNOWNLCID :: HRESULT
dISP_E_UNKNOWNLCID = word32ToInt32 (0x8002000C ::Word32)
dISP_E_UNKNOWNNAME :: HRESULT
dISP_E_UNKNOWNNAME = word32ToInt32 (0x80020006 ::Word32)
dV_E_CLIPFORMAT :: HRESULT
dV_E_CLIPFORMAT = word32ToInt32 (0x8004006A ::Word32)
dV_E_DVASPECT :: HRESULT
dV_E_DVASPECT = word32ToInt32 (0x8004006B ::Word32)
dV_E_DVTARGETDEVICE :: HRESULT
dV_E_DVTARGETDEVICE = word32ToInt32 (0x80040065 ::Word32)
dV_E_DVTARGETDEVICE_SIZE :: HRESULT
dV_E_DVTARGETDEVICE_SIZE = word32ToInt32 (0x8004006C ::Word32)
dV_E_FORMATETC :: HRESULT
dV_E_FORMATETC = word32ToInt32 (0x80040064 ::Word32)
dV_E_LINDEX :: HRESULT
dV_E_LINDEX = word32ToInt32 (0x80040068 ::Word32)
dV_E_NOIVIEWOBJECT :: HRESULT
dV_E_NOIVIEWOBJECT = word32ToInt32 (0x8004006D ::Word32)
dV_E_STATDATA :: HRESULT
dV_E_STATDATA = word32ToInt32 (0x80040067 ::Word32)
dV_E_STGMEDIUM :: HRESULT
dV_E_STGMEDIUM = word32ToInt32 (0x80040066 ::Word32)
dV_E_TYMED :: HRESULT
dV_E_TYMED = word32ToInt32 (0x80040069 ::Word32)
e_ABORT :: HRESULT
e_ABORT = word32ToInt32 (0x80004004 ::Word32)
e_ACCESSDENIED :: HRESULT
e_ACCESSDENIED = word32ToInt32 (0x80070005 ::Word32)
e_FAIL :: HRESULT
e_FAIL = word32ToInt32 (0x80004005 ::Word32)
e_HANDLE :: HRESULT
e_HANDLE = word32ToInt32 (0x80070006 ::Word32)
e_INVALIDARG :: HRESULT
e_INVALIDARG = word32ToInt32 (0x80070057 ::Word32)
e_NOINTERFACE :: HRESULT
e_NOINTERFACE = word32ToInt32 (0x80004002 ::Word32)
e_NOTIMPL :: HRESULT
e_NOTIMPL = word32ToInt32 (0x80004001 ::Word32)
e_OUTOFMEMORY :: HRESULT
e_OUTOFMEMORY = word32ToInt32 (0x8007000E ::Word32)
e_PENDING :: HRESULT
e_PENDING = word32ToInt32 (0x8000000A ::Word32)
e_POINTER :: HRESULT
e_POINTER = word32ToInt32 (0x80004003 ::Word32)
e_UNEXPECTED :: HRESULT
e_UNEXPECTED = word32ToInt32 (0x8000FFFF ::Word32)
fACILITY_CERT :: HRESULT
fACILITY_CERT = 11
fACILITY_CONTROL :: HRESULT
fACILITY_CONTROL = 10
fACILITY_DISPATCH :: HRESULT
fACILITY_DISPATCH = 2
fACILITY_INTERNET :: HRESULT
fACILITY_INTERNET = 12
fACILITY_ITF :: HRESULT
fACILITY_ITF = 4
fACILITY_MEDIASERVER :: HRESULT
fACILITY_MEDIASERVER = 13
fACILITY_MSMQ :: HRESULT
fACILITY_MSMQ = 14
fACILITY_NT_BIT :: HRESULT
fACILITY_NT_BIT = word32ToInt32 (0x10000000 ::Word32)
fACILITY_NULL :: HRESULT
fACILITY_NULL = 0
fACILITY_RPC :: HRESULT
fACILITY_RPC = 1
fACILITY_SETUPAPI :: HRESULT
fACILITY_SETUPAPI = 15
fACILITY_SSPI :: HRESULT
fACILITY_SSPI = 9
fACILITY_STORAGE :: HRESULT
fACILITY_STORAGE = 3
fACILITY_WIN32 :: HRESULT
fACILITY_WIN32 = 7
fACILITY_WINDOWS :: HRESULT
fACILITY_WINDOWS = 8
iNPLACE_E_FIRST :: HRESULT
iNPLACE_E_FIRST = word32ToInt32 (0x800401A0 ::Word32)
iNPLACE_E_LAST :: HRESULT
iNPLACE_E_LAST = word32ToInt32 (0x800401AF ::Word32)
iNPLACE_E_NOTOOLSPACE :: HRESULT
iNPLACE_E_NOTOOLSPACE = word32ToInt32 (0x800401A1 ::Word32)
iNPLACE_E_NOTUNDOABLE :: HRESULT
iNPLACE_E_NOTUNDOABLE = word32ToInt32 (0x800401A0 ::Word32)
iNPLACE_S_FIRST :: HRESULT
iNPLACE_S_FIRST = word32ToInt32 (0x000401A0 ::Word32)
iNPLACE_S_LAST :: HRESULT
iNPLACE_S_LAST = word32ToInt32 (0x000401AF ::Word32)
iNPLACE_S_TRUNCATED :: HRESULT
iNPLACE_S_TRUNCATED = word32ToInt32 (0x000401A0 ::Word32)
mARSHAL_E_FIRST :: HRESULT
mARSHAL_E_FIRST = word32ToInt32 (0x80040120 ::Word32)
mARSHAL_E_LAST :: HRESULT
mARSHAL_E_LAST = word32ToInt32 (0x8004012F ::Word32)
mARSHAL_S_FIRST :: HRESULT
mARSHAL_S_FIRST = word32ToInt32 (0x00040120 ::Word32)
mARSHAL_S_LAST :: HRESULT
mARSHAL_S_LAST = word32ToInt32 (0x0004012F ::Word32)
mEM_E_INVALID_LINK :: HRESULT
mEM_E_INVALID_LINK = word32ToInt32 (0x80080010 ::Word32)
mEM_E_INVALID_ROOT :: HRESULT
mEM_E_INVALID_ROOT = word32ToInt32 (0x80080009 ::Word32)
mEM_E_INVALID_SIZE :: HRESULT
mEM_E_INVALID_SIZE = word32ToInt32 (0x80080011 ::Word32)
mK_E_CANTOPENFILE :: HRESULT
mK_E_CANTOPENFILE = word32ToInt32 (0x800401EA ::Word32)
mK_E_CONNECTMANUALLY :: HRESULT
mK_E_CONNECTMANUALLY = word32ToInt32 (0x800401E0 ::Word32)
mK_E_ENUMERATION_FAILED :: HRESULT
mK_E_ENUMERATION_FAILED = word32ToInt32 (0x800401EF ::Word32)
mK_E_EXCEEDEDDEADLINE :: HRESULT
mK_E_EXCEEDEDDEADLINE = word32ToInt32 (0x800401E1 ::Word32)
mK_E_FIRST :: HRESULT
mK_E_FIRST = word32ToInt32 (0x800401E0 ::Word32)
mK_E_INTERMEDIATEINTERFACENOTSUPPORTED :: HRESULT
mK_E_INTERMEDIATEINTERFACENOTSUPPORTED = word32ToInt32 (0x800401E7 ::Word32)
mK_E_INVALIDEXTENSION :: HRESULT
mK_E_INVALIDEXTENSION = word32ToInt32 (0x800401E6 ::Word32)
mK_E_LAST :: HRESULT
mK_E_LAST = word32ToInt32 (0x800401EF ::Word32)
mK_E_MUSTBOTHERUSER :: HRESULT
mK_E_MUSTBOTHERUSER = word32ToInt32 (0x800401EB ::Word32)
mK_E_NEEDGENERIC :: HRESULT
mK_E_NEEDGENERIC = word32ToInt32 (0x800401E2 ::Word32)
mK_E_NOINVERSE :: HRESULT
mK_E_NOINVERSE = word32ToInt32 (0x800401EC ::Word32)
mK_E_NOOBJECT :: HRESULT
mK_E_NOOBJECT = word32ToInt32 (0x800401E5 ::Word32)
mK_E_NOPREFIX :: HRESULT
mK_E_NOPREFIX = word32ToInt32 (0x800401EE ::Word32)
mK_E_NOSTORAGE :: HRESULT
mK_E_NOSTORAGE = word32ToInt32 (0x800401ED ::Word32)
mK_E_NOTBINDABLE :: HRESULT
mK_E_NOTBINDABLE = word32ToInt32 (0x800401E8 ::Word32)
mK_E_NOTBOUND :: HRESULT
mK_E_NOTBOUND = word32ToInt32 (0x800401E9 ::Word32)
mK_E_NO_NORMALIZED :: HRESULT
mK_E_NO_NORMALIZED = word32ToInt32 (0x80080007 ::Word32)
mK_E_SYNTAX :: HRESULT
mK_E_SYNTAX = word32ToInt32 (0x800401E4 ::Word32)
mK_E_UNAVAILABLE :: HRESULT
mK_E_UNAVAILABLE = word32ToInt32 (0x800401E3 ::Word32)
mK_S_FIRST :: HRESULT
mK_S_FIRST = word32ToInt32 (0x000401E0 ::Word32)
mK_S_HIM :: HRESULT
mK_S_HIM = word32ToInt32 (0x000401E5 ::Word32)
mK_S_LAST :: HRESULT
mK_S_LAST = word32ToInt32 (0x000401EF ::Word32)
mK_S_ME :: HRESULT
mK_S_ME = word32ToInt32 (0x000401E4 ::Word32)
mK_S_MONIKERALREADYREGISTERED :: HRESULT
mK_S_MONIKERALREADYREGISTERED = word32ToInt32 (0x000401E7 ::Word32)
mK_S_REDUCED_TO_SELF :: HRESULT
mK_S_REDUCED_TO_SELF = word32ToInt32 (0x000401E2 ::Word32)
mK_S_US :: HRESULT
mK_S_US = word32ToInt32 (0x000401E6 ::Word32)
oLEOBJ_E_FIRST :: HRESULT
oLEOBJ_E_FIRST = word32ToInt32 (0x80040180 ::Word32)
oLEOBJ_E_INVALIDVERB :: HRESULT
oLEOBJ_E_INVALIDVERB = word32ToInt32 (0x80040181 ::Word32)
oLEOBJ_E_LAST :: HRESULT
oLEOBJ_E_LAST = word32ToInt32 (0x8004018F ::Word32)
oLEOBJ_E_NOVERBS :: HRESULT
oLEOBJ_E_NOVERBS = word32ToInt32 (0x80040180 ::Word32)
oLEOBJ_S_CANNOT_DOVERB_NOW :: HRESULT
oLEOBJ_S_CANNOT_DOVERB_NOW = word32ToInt32 (0x00040181 ::Word32)
oLEOBJ_S_FIRST :: HRESULT
oLEOBJ_S_FIRST = word32ToInt32 (0x00040180 ::Word32)
oLEOBJ_S_INVALIDHWND :: HRESULT
oLEOBJ_S_INVALIDHWND = word32ToInt32 (0x00040182 ::Word32)
oLEOBJ_S_INVALIDVERB :: HRESULT
oLEOBJ_S_INVALIDVERB = word32ToInt32 (0x00040180 ::Word32)
oLEOBJ_S_LAST :: HRESULT
oLEOBJ_S_LAST = word32ToInt32 (0x0004018F ::Word32)
oLE_E_ADVF :: HRESULT
oLE_E_ADVF = word32ToInt32 (0x80040001 ::Word32)
oLE_E_ADVISENOTSUPPORTED :: HRESULT
oLE_E_ADVISENOTSUPPORTED = word32ToInt32 (0x80040003 ::Word32)
oLE_E_BLANK :: HRESULT
oLE_E_BLANK = word32ToInt32 (0x80040007 ::Word32)
oLE_E_CANTCONVERT :: HRESULT
oLE_E_CANTCONVERT = word32ToInt32 (0x80040011 ::Word32)
oLE_E_CANT_BINDTOSOURCE :: HRESULT
oLE_E_CANT_BINDTOSOURCE = word32ToInt32 (0x8004000A ::Word32)
oLE_E_CANT_GETMONIKER :: HRESULT
oLE_E_CANT_GETMONIKER = word32ToInt32 (0x80040009 ::Word32)
oLE_E_CLASSDIFF :: HRESULT
oLE_E_CLASSDIFF = word32ToInt32 (0x80040008 ::Word32)
oLE_E_ENUM_NOMORE :: HRESULT
oLE_E_ENUM_NOMORE = word32ToInt32 (0x80040002 ::Word32)
oLE_E_FIRST :: HRESULT
oLE_E_FIRST = word32ToInt32 (0x80040000::Word32)
oLE_E_INVALIDHWND :: HRESULT
oLE_E_INVALIDHWND = word32ToInt32 (0x8004000F ::Word32)
oLE_E_INVALIDRECT :: HRESULT
oLE_E_INVALIDRECT = word32ToInt32 (0x8004000D ::Word32)
oLE_E_LAST :: HRESULT
oLE_E_LAST = word32ToInt32 (0x800400FF::Word32)
oLE_E_NOCACHE :: HRESULT
oLE_E_NOCACHE = word32ToInt32 (0x80040006 ::Word32)
oLE_E_NOCONNECTION :: HRESULT
oLE_E_NOCONNECTION = word32ToInt32 (0x80040004 ::Word32)
oLE_E_NOSTORAGE :: HRESULT
oLE_E_NOSTORAGE = word32ToInt32 (0x80040012 ::Word32)
oLE_E_NOTRUNNING :: HRESULT
oLE_E_NOTRUNNING = word32ToInt32 (0x80040005 ::Word32)
oLE_E_NOT_INPLACEACTIVE :: HRESULT
oLE_E_NOT_INPLACEACTIVE = word32ToInt32 (0x80040010 ::Word32)
oLE_E_OLEVERB :: HRESULT
oLE_E_OLEVERB = word32ToInt32 (0x80040000 ::Word32)
oLE_E_PROMPTSAVECANCELLED :: HRESULT
oLE_E_PROMPTSAVECANCELLED = word32ToInt32 (0x8004000C ::Word32)
oLE_E_STATIC :: HRESULT
oLE_E_STATIC = word32ToInt32 (0x8004000B ::Word32)
oLE_E_WRONGCOMPOBJ :: HRESULT
oLE_E_WRONGCOMPOBJ = word32ToInt32 (0x8004000E ::Word32)
oLE_S_FIRST :: HRESULT
oLE_S_FIRST = word32ToInt32 (0x00040000 ::Word32)
oLE_S_LAST :: HRESULT
oLE_S_LAST = word32ToInt32 (0x000400FF ::Word32)
oLE_S_MAC_CLIPFORMAT :: HRESULT
oLE_S_MAC_CLIPFORMAT = word32ToInt32 (0x00040002 ::Word32)
oLE_S_STATIC :: HRESULT
oLE_S_STATIC = word32ToInt32 (0x00040001 ::Word32)
oLE_S_USEREG :: HRESULT
oLE_S_USEREG = word32ToInt32 (0x00040000 ::Word32)
pERSIST_E_NOTSELFSIZING :: HRESULT
pERSIST_E_NOTSELFSIZING = word32ToInt32 (0x800B000B ::Word32)
pERSIST_E_SIZEDEFINITE :: HRESULT
pERSIST_E_SIZEDEFINITE = word32ToInt32 (0x800B0009 ::Word32)
pERSIST_E_SIZEINDEFINITE :: HRESULT
pERSIST_E_SIZEINDEFINITE = word32ToInt32 (0x800B000A ::Word32)
sTG_E_ABNORMALAPIEXIT :: HRESULT
sTG_E_ABNORMALAPIEXIT = word32ToInt32 (0x800300FA ::Word32)
sTG_E_ACCESSDENIED :: HRESULT
sTG_E_ACCESSDENIED = word32ToInt32 (0x80030005 ::Word32)
sTG_E_BADBASEADDRESS :: HRESULT
sTG_E_BADBASEADDRESS = word32ToInt32 (0x80030110 ::Word32)
sTG_E_CANTSAVE :: HRESULT
sTG_E_CANTSAVE = word32ToInt32 (0x80030103 ::Word32)
sTG_E_DISKISWRITEPROTECTED :: HRESULT
sTG_E_DISKISWRITEPROTECTED = word32ToInt32 (0x80030013 ::Word32)
sTG_E_DOCFILECORRUPT :: HRESULT
sTG_E_DOCFILECORRUPT = word32ToInt32 (0x80030109 ::Word32)
sTG_E_EXTANTMARSHALLINGS :: HRESULT
sTG_E_EXTANTMARSHALLINGS = word32ToInt32 (0x80030108 ::Word32)
sTG_E_FILEALREADYEXISTS :: HRESULT
sTG_E_FILEALREADYEXISTS = word32ToInt32 (0x80030050 ::Word32)
sTG_E_FILENOTFOUND :: HRESULT
sTG_E_FILENOTFOUND = word32ToInt32 (0x80030002 ::Word32)
sTG_E_INCOMPLETE :: HRESULT
sTG_E_INCOMPLETE = word32ToInt32 (0x80030201 ::Word32)
sTG_E_INSUFFICIENTMEMORY :: HRESULT
sTG_E_INSUFFICIENTMEMORY = word32ToInt32 (0x80030008 ::Word32)
sTG_E_INUSE :: HRESULT
sTG_E_INUSE = word32ToInt32 (0x80030100 ::Word32)
sTG_E_INVALIDFLAG :: HRESULT
sTG_E_INVALIDFLAG = word32ToInt32 (0x800300FF ::Word32)
sTG_E_INVALIDFUNCTION :: HRESULT
sTG_E_INVALIDFUNCTION = word32ToInt32 (0x80030001 ::Word32)
sTG_E_INVALIDHANDLE :: HRESULT
sTG_E_INVALIDHANDLE = word32ToInt32 (0x80030006 ::Word32)
sTG_E_INVALIDHEADER :: HRESULT
sTG_E_INVALIDHEADER = word32ToInt32 (0x800300FB ::Word32)
sTG_E_INVALIDNAME :: HRESULT
sTG_E_INVALIDNAME = word32ToInt32 (0x800300FC ::Word32)
sTG_E_INVALIDPARAMETER :: HRESULT
sTG_E_INVALIDPARAMETER = word32ToInt32 (0x80030057 ::Word32)
sTG_E_INVALIDPOINTER :: HRESULT
sTG_E_INVALIDPOINTER = word32ToInt32 (0x80030009 ::Word32)
sTG_E_LOCKVIOLATION :: HRESULT
sTG_E_LOCKVIOLATION = word32ToInt32 (0x80030021 ::Word32)
sTG_E_MEDIUMFULL :: HRESULT
sTG_E_MEDIUMFULL = word32ToInt32 (0x80030070 ::Word32)
sTG_E_NOMOREFILES :: HRESULT
sTG_E_NOMOREFILES = word32ToInt32 (0x80030012 ::Word32)
sTG_E_NOTCURRENT :: HRESULT
sTG_E_NOTCURRENT = word32ToInt32 (0x80030101 ::Word32)
sTG_E_NOTFILEBASEDSTORAGE :: HRESULT
sTG_E_NOTFILEBASEDSTORAGE = word32ToInt32 (0x80030107 ::Word32)
sTG_E_OLDDLL :: HRESULT
sTG_E_OLDDLL = word32ToInt32 (0x80030105 ::Word32)
sTG_E_OLDFORMAT :: HRESULT
sTG_E_OLDFORMAT = word32ToInt32 (0x80030104 ::Word32)
sTG_E_PATHNOTFOUND :: HRESULT
sTG_E_PATHNOTFOUND = word32ToInt32 (0x80030003 ::Word32)
sTG_E_PROPSETMISMATCHED :: HRESULT
sTG_E_PROPSETMISMATCHED = word32ToInt32 (0x800300F0 ::Word32)
sTG_E_READFAULT :: HRESULT
sTG_E_READFAULT = word32ToInt32 (0x8003001E ::Word32)
sTG_E_REVERTED :: HRESULT
sTG_E_REVERTED = word32ToInt32 (0x80030102 ::Word32)
sTG_E_SEEKERROR :: HRESULT
sTG_E_SEEKERROR = word32ToInt32 (0x80030019 ::Word32)
sTG_E_SHAREREQUIRED :: HRESULT
sTG_E_SHAREREQUIRED = word32ToInt32 (0x80030106 ::Word32)
sTG_E_SHAREVIOLATION :: HRESULT
sTG_E_SHAREVIOLATION = word32ToInt32 (0x80030020 ::Word32)
sTG_E_TERMINATED :: HRESULT
sTG_E_TERMINATED = word32ToInt32 (0x80030202 ::Word32)
sTG_E_TOOMANYOPENFILES :: HRESULT
sTG_E_TOOMANYOPENFILES = word32ToInt32 (0x80030004 ::Word32)
sTG_E_UNIMPLEMENTEDFUNCTION :: HRESULT
sTG_E_UNIMPLEMENTEDFUNCTION = word32ToInt32 (0x800300FE ::Word32)
sTG_E_UNKNOWN :: HRESULT
sTG_E_UNKNOWN = word32ToInt32 (0x800300FD ::Word32)
sTG_E_WRITEFAULT :: HRESULT
sTG_E_WRITEFAULT = word32ToInt32 (0x8003001D ::Word32)
sTG_S_BLOCK :: HRESULT
sTG_S_BLOCK = word32ToInt32 (0x00030201 ::Word32)
sTG_S_CANNOTCONSOLIDATE :: HRESULT
sTG_S_CANNOTCONSOLIDATE = word32ToInt32 (0x00030206 ::Word32)
sTG_S_CONSOLIDATIONFAILED :: HRESULT
sTG_S_CONSOLIDATIONFAILED = word32ToInt32 (0x00030205 ::Word32)
sTG_S_CONVERTED :: HRESULT
sTG_S_CONVERTED = word32ToInt32 (0x00030200 ::Word32)
sTG_S_MONITORING :: HRESULT
sTG_S_MONITORING = word32ToInt32 (0x00030203 ::Word32)
sTG_S_MULTIPLEOPENS :: HRESULT
sTG_S_MULTIPLEOPENS = word32ToInt32 (0x00030204 ::Word32)
sTG_S_RETRYNOW :: HRESULT
sTG_S_RETRYNOW = word32ToInt32 (0x00030202 ::Word32)
tYPE_E_AMBIGUOUSNAME :: HRESULT
tYPE_E_AMBIGUOUSNAME = word32ToInt32 (0x8002802C ::Word32)
tYPE_E_BADMODULEKIND :: HRESULT
tYPE_E_BADMODULEKIND = word32ToInt32 (0x800288BD ::Word32)
tYPE_E_BUFFERTOOSMALL :: HRESULT
tYPE_E_BUFFERTOOSMALL = word32ToInt32 (0x80028016 ::Word32)
tYPE_E_CANTCREATETMPFILE :: HRESULT
tYPE_E_CANTCREATETMPFILE = word32ToInt32 (0x80028CA3 ::Word32)
tYPE_E_CANTLOADLIBRARY :: HRESULT
tYPE_E_CANTLOADLIBRARY = word32ToInt32 (0x80029C4A ::Word32)
tYPE_E_CIRCULARTYPE :: HRESULT
tYPE_E_CIRCULARTYPE = word32ToInt32 (0x80029C84 ::Word32)
tYPE_E_DLLFUNCTIONNOTFOUND :: HRESULT
tYPE_E_DLLFUNCTIONNOTFOUND = word32ToInt32 (0x8002802F ::Word32)
tYPE_E_DUPLICATEID :: HRESULT
tYPE_E_DUPLICATEID = word32ToInt32 (0x800288C6 ::Word32)
tYPE_E_ELEMENTNOTFOUND :: HRESULT
tYPE_E_ELEMENTNOTFOUND = word32ToInt32 (0x8002802B ::Word32)
tYPE_E_FIELDNOTFOUND :: HRESULT
tYPE_E_FIELDNOTFOUND = word32ToInt32 (0x80028017 ::Word32)
tYPE_E_INCONSISTENTPROPFUNCS :: HRESULT
tYPE_E_INCONSISTENTPROPFUNCS = word32ToInt32 (0x80029C83 ::Word32)
tYPE_E_INVALIDID :: HRESULT
tYPE_E_INVALIDID = word32ToInt32 (0x800288CF ::Word32)
tYPE_E_INVALIDSTATE :: HRESULT
tYPE_E_INVALIDSTATE = word32ToInt32 (0x80028029 ::Word32)
tYPE_E_INVDATAREAD :: HRESULT
tYPE_E_INVDATAREAD = word32ToInt32 (0x80028018 ::Word32)
tYPE_E_IOERROR :: HRESULT
tYPE_E_IOERROR = word32ToInt32 (0x80028CA2 ::Word32)
tYPE_E_LIBNOTREGISTERED :: HRESULT
tYPE_E_LIBNOTREGISTERED = word32ToInt32 (0x8002801D ::Word32)
tYPE_E_NAMECONFLICT :: HRESULT
tYPE_E_NAMECONFLICT = word32ToInt32 (0x8002802D ::Word32)
tYPE_E_OUTOFBOUNDS :: HRESULT
tYPE_E_OUTOFBOUNDS = word32ToInt32 (0x80028CA1 ::Word32)
tYPE_E_QUALIFIEDNAMEDISALLOWED :: HRESULT
tYPE_E_QUALIFIEDNAMEDISALLOWED = word32ToInt32 (0x80028028 ::Word32)
tYPE_E_REGISTRYACCESS :: HRESULT
tYPE_E_REGISTRYACCESS = word32ToInt32 (0x8002801C ::Word32)
tYPE_E_SIZETOOBIG :: HRESULT
tYPE_E_SIZETOOBIG = word32ToInt32 (0x800288C5 ::Word32)
tYPE_E_TYPEMISMATCH :: HRESULT
tYPE_E_TYPEMISMATCH = word32ToInt32 (0x80028CA0 ::Word32)
tYPE_E_UNDEFINEDTYPE :: HRESULT
tYPE_E_UNDEFINEDTYPE = word32ToInt32 (0x80028027 ::Word32)
tYPE_E_UNKNOWNLCID :: HRESULT
tYPE_E_UNKNOWNLCID = word32ToInt32 (0x8002802E ::Word32)
tYPE_E_UNSUPFORMAT :: HRESULT
tYPE_E_UNSUPFORMAT = word32ToInt32 (0x80028019 ::Word32)
tYPE_E_WRONGTYPEKIND :: HRESULT
tYPE_E_WRONGTYPEKIND = word32ToInt32 (0x8002802A ::Word32)
vIEW_E_DRAW :: HRESULT
vIEW_E_DRAW = word32ToInt32 (0x80040140 ::Word32)
vIEW_E_FIRST :: HRESULT
vIEW_E_FIRST = word32ToInt32 (0x80040140 ::Word32)
vIEW_E_LAST :: HRESULT
vIEW_E_LAST = word32ToInt32 (0x8004014F ::Word32)
vIEW_S_ALREADY_FROZEN :: HRESULT
vIEW_S_ALREADY_FROZEN = word32ToInt32 (0x00040140 ::Word32)
vIEW_S_FIRST :: HRESULT
vIEW_S_FIRST = word32ToInt32 (0x00040140 ::Word32)
vIEW_S_LAST :: HRESULT
vIEW_S_LAST = word32ToInt32 (0x0004014F ::Word32)
| HJvT/com | System/Win32/Com/Exception.hs | bsd-3-clause | 32,564 | 0 | 16 | 3,896 | 6,940 | 3,950 | 2,990 | 711 | 3 |
-- |
-- Module : Crypto.Cipher.Types
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : Stable
-- Portability : Excellent
--
-- symmetric cipher basic types
--
module Crypto.Internal
(
-- * Key type and constructor
KeyError(..)
, Key(..)
, makeKey
-- * pack/unpack
, myPack
, myUnpack
) where
import Data.Char (ord,chr)
-- | Create a Key for a specified cipher
makeKey :: String -> Key
makeKey b' = either (error . show) id key
where b = myUnpack b'
smLen = length b
key :: Either KeyError Key
key | smLen < 6 = Left KeyErrorTooSmall
| smLen > 56 = Left KeyErrorTooBig
| otherwise = Right $ Key b
-- | Possible Error that can be reported when initializating a key
data KeyError =
KeyErrorTooSmall
| KeyErrorTooBig
deriving (Show,Eq)
-- | a Key parametrized by the cipher
newtype Key = Key [Int] deriving (Eq)
myPack :: [Int] -> String
myPack = map chr
myUnpack :: String -> [Int]
myUnpack = map (fromIntegral . ord)
| jonathankochems/hs-crypto-cipher | src/Crypto/Internal.hs | bsd-3-clause | 1,085 | 0 | 10 | 301 | 253 | 144 | 109 | 25 | 1 |
-- Copyright © 2010 Greg Weber and Bart Massey
-- [This program is licensed under the "3-clause ('new') BSD License"]
-- Please see the file COPYING in this distribution for license information.
-- | Read a spelling dictionary.
module Text.SpellingSuggest.Dictionary (
defaultDictionary, readDictionary
) where
import Data.Maybe
import System.IO
-- | File path for default dictionary.
defaultDictionary :: String
defaultDictionary = "/usr/share/dict/words"
-- | Read the words out of the dictionary at the given
-- path. XXX Will leak a file handle until/unless it is
-- finalized, since there's no non-trivial way to arrange
-- for the dictionary file to be closed explicitly.
readDictionary :: Maybe String -> IO [String]
readDictionary dictPath = do
wf <- flip openFile ReadMode $ fromMaybe defaultDictionary dictPath
hSetEncoding wf utf8
wc <- hGetContents wf
return $ lines wc
| gregwebs/haskell-spell-suggest | Text/SpellingSuggest/Dictionary.hs | bsd-3-clause | 899 | 0 | 9 | 150 | 119 | 64 | 55 | 12 | 1 |
module Main where
import Ivory.Tower.Options
import Tower.AADL
import Ivory.Tower.Config
import Tower.AADL.Build.Common
import Tower.AADL.Build.EChronos
import Ivory.BSP.STM32.Config
import BSP.Tests.Platforms
import BSP.Tests.LED.TestApp (app)
main :: IO ()
main = compileTowerAADLForPlatform f p $ do
app testplatform_leds
where
f :: TestPlatform -> (AADLConfig, OSSpecific STM32Config)
f tp = ( defaultAADLConfig { configSystemOS = EChronos
, configSystemHW = PIXHAWK
}
, defaultEChronosOS (testplatform_stm32 tp)
)
p :: TOpts -> IO TestPlatform
p topts = fmap fst (getConfig' topts testPlatformParser)
| GaloisInc/ivory-tower-stm32 | ivory-bsp-tests/tests/LEDAADLTest.hs | bsd-3-clause | 704 | 0 | 10 | 172 | 180 | 103 | 77 | 18 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Hspec
import Test.QuickCheck
import Flux
main = hspec $ do
describe "The delegation graph" $
it "Should have size 0 when empty" $ do
graphSize emptyGraph `shouldBe` 0
-- adding and removing a voter is a no-op
-- adding a voter is idempotent
-- removing a voter is idempotent
-- graph always meets internal invariants
instance Arbitrary VoterId where
arbitrary = VoterId <$> choose (0,9)
| timbod7/flux-model | test/Spec.hs | bsd-3-clause | 477 | 0 | 12 | 113 | 83 | 45 | 38 | 10 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE BangPatterns #-}
module Sky.Parsing.Invertible3.Isomorphism where
import Prelude hiding (id, (.))
import Data.Data (Data)
import Data.Proxy (Proxy(..))
import Control.Category (Category(..))
import Sky.Parsing.Invertible3.PartialType
-- import Data.Function ((&))
-- import Debug.Trace
----------------------------------------------------------------------------------------------------
-- class IsoError e where
-- errorComposition :: Iso e b c -> Iso e a b -> e
-- showError :: e -> String
class Category i => Isomorphism i where
apply :: i s a -> s -> a
unapply :: i s a -> a -> s
reverseIso :: i s a -> i a s
addIso :: (Data s) => i s a -> i s b -> i s (Either a b)
----------------------------------------------------------------------------------------------------
-- Implementation: Errors
data IsoError
= CompositionError
{ codomainLeft :: PartialType'
, domainRight :: PartialType'
}
| IsoAdditionError
{ domain1 :: PartialType'
, domain2 :: PartialType'
}
-- instance IsoError DefaultIsoError where
-- errorComposition isoBC isoAB = CompositionError (_codomain isoAB) (_domain isoBC)
-- showError (CompositionError codom dom) = "Iso composition domain mismatch: " ++ show codom ++ " vs " ++ show dom
errorComposition :: Iso b c -> Iso a b -> IsoError
errorComposition isoBC isoAB = CompositionError (_codomain isoAB) (_domain isoBC)
errorAddition :: Iso s a -> Iso s b -> IsoError
errorAddition isoS1A isoS2B = IsoAdditionError (_domain isoS1A) (_domain isoS2B)
--err = error $ "Iso sum domain clash: " ++ show (_domain isoS1A) ++ " vs " ++ show (_domain isoS2B)
showError :: IsoError -> String
showError (CompositionError codom dom) =
"Isomorphisms mismatch on composition:\n"
++ " The codomain of the first isomorphism:\n"
++ " " ++ show codom ++ "\n"
++ " doesn't match the domain of the second:\n"
++ " " ++ show dom ++ "\n"
showError (IsoAdditionError dom1 dom2) =
"Isomorphisms mismatch on addition:\n"
++ " The domain of the first isomorphism:\n"
++ " " ++ show dom1 ++ "\n"
++ " is not disjunct from the the domain of the second:\n"
++ " " ++ show dom2 ++ "\n"
--throwError :: IsoError e => e -> a
throwError :: IsoError -> a
throwError e = error $ showError e
----------------------------------------------------------------------------------------------------
-- Implementation: Iso
data Iso s a
= Iso
{ _rawIso :: (s -> a, a -> s)
, _domain :: PartialType s
, _codomain :: PartialType a
}
| Error IsoError
instance Category (Iso) where
id :: Iso a a
id = iso id id
(.) :: Iso b c -> Iso a b -> Iso a c
(.) (Error e) _ = Error e
(.) _ (Error e) = Error e
(.) !isoBC !isoAB = if check then isoAC else err where
check = _codomain isoAB == _domain isoBC
-- & ( trace $ "Check " ++ (show $ _codomain isoAB) ++ " == " ++ (show $ _domain isoBC) )
err = Error $ errorComposition isoBC isoAB
(bmc, cmb) = _rawIso isoBC
(amb, bma) = _rawIso isoAB
amc = bmc . amb
cma = bma . cmb
isoAC = Iso (amc, cma) (_domain isoAB) (_codomain isoBC)
instance Isomorphism (Iso) where
apply (Error e) = throwError e
apply (Iso (forward, _) _ _) = forward
unapply (Error e) = throwError e
unapply (Iso (_, backward) _ _) = backward
reverseIso (Error e) = Error e
reverseIso (Iso (f, b) d c) = Iso (b, f) c d
addIso :: forall s a b. (Data s) => Iso s a -> Iso s b -> Iso s (Either a b)
addIso (Error e) _ = Error e
addIso _ (Error e) = Error e
addIso isoS1A isoS2B = if check then Iso (forward, backward) newDomain newCodomain else err where
check = disjunct (_domain isoS1A) (_domain isoS2B)
err = Error $ errorAddition isoS1A isoS2B
newDomain = (_domain isoS1A) `union` (_domain isoS2B)
newCodomain = basicType (Proxy :: Proxy (Either a b))
forward :: s -> Either a b
forward v = if v `isOfType` _domain isoS1A
then Left $ apply isoS1A v
else Right $ apply isoS2B v
backward :: Either a b -> s
backward (Left b1) = unapply isoS1A b1
backward (Right b2) = unapply isoS2B b2
----------------------------------------------------------------------------------------------------
-- Simple total iso
iso :: (s -> a) -> (a -> s) -> Iso s a
iso forward backward = Iso (forward, backward) (basicType (Proxy :: Proxy s)) (basicType (Proxy :: Proxy a))
-- Construction from a data constructor: Partial on the left data type (s)
partialIso :: forall e s a. (Data s) => s -> (s -> a) -> (a -> s) -> Iso s a
partialIso dConstr forward backward = Iso (forward, backward) (partialAlgebraicType dConstr) (basicType (Proxy :: Proxy a))
-- Construction from a data constructor: Partial on the right data type (s)
partialIsoR :: forall e s a. (Data a) => a -> (s -> a) -> (a -> s) -> Iso s a
partialIsoR dConstr forward backward = Iso (forward, backward) (basicType (Proxy :: Proxy s)) (partialAlgebraicType dConstr)
--partialIsoR dConstr forward backward = reverseIso $ partialIso dConstr backward forward
----------------------------------------------------------------------------------------------------
-- For invertible syntax parsing we need:
-- A "failure" isomorphism
-- TODO: The "parser" side should not accept anything, this still has to compose (e.g. with alt)
isoFail :: String -> Iso a b
isoFail e = iso (error e) (error e)
-- An isomorphism between fixed values (i.e. "pure" & "token" for the parser)
isoPure :: s -> a -> Iso s a
isoPure s a = iso (const a) (const s)
-- Alternative choice: Having parsed either "s" or "t", generate "a"
-- this is just "addIso" for the partial isos above! (reversed, in this case)
isoAlt :: (Data a) => Iso s a -> Iso t a -> Iso (Either s t) a
isoAlt sa ta = reverseIso $ addIso (reverseIso sa) (reverseIso ta)
-- Sequential combination
-- TODO: Parse side needs to be able to make a choice (for determinism)
isoSeq :: Iso [s] a -> Iso [s] b -> Iso [s] (a, b)
isoSeq lsa lsb = error $ "TODO"
-- Because it happens a lot and haskell would "do it wrong":
isoSeqL :: Iso [s] a -> Iso [s] () -> Iso [s] a
isoSeqL lsa lsb = error $ "TODO"
isoSeqR :: Iso [s] () -> Iso [s] b -> Iso [s] b
isoSeqR lsa lsb = error $ "TODO"
----------------------------------------------------------------------------------------------------
-- Debug
checkIso :: Iso a b -> Iso a b
checkIso (Error e) = throwError e
checkIso iso = iso
instance Show (Iso a b) where
show (Error e) = showError e
show _ = "Iso (FIXME)"
| xicesky/sky-haskell-playground | src/Sky/Parsing/Invertible3/Isomorphism.hs | bsd-3-clause | 6,820 | 0 | 12 | 1,610 | 1,938 | 1,023 | 915 | 106 | 1 |
module WildBind.ForTest
( SampleInput(..),
SampleState(..),
SampleBackState(..),
inputAll,
execAll,
evalStateEmpty,
boundDescs,
boundDescs',
curBoundInputs,
curBoundDescs,
curBoundDesc,
checkBoundInputs,
checkBoundDescs,
checkBoundDesc,
withRefChecker
) where
import Control.Applicative ((<$>), (<*>), pure)
import Control.Monad (join)
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Control.Monad.Trans.State as State
import Data.IORef (IORef, newIORef, readIORef)
import Data.Monoid (mempty)
import Test.QuickCheck (Arbitrary(arbitrary,shrink), arbitraryBoundedEnum)
import Test.Hspec (shouldReturn, shouldMatchList, shouldBe)
import qualified WildBind.Binding as WB
import qualified WildBind.Description as WBD
data SampleInput = SIa | SIb | SIc
deriving (Show, Eq, Ord, Enum, Bounded)
instance Arbitrary SampleInput where
arbitrary = arbitraryBoundedEnum
data SampleState = SS { unSS :: String }
deriving (Show, Eq, Ord)
instance Arbitrary SampleState where
arbitrary = SS <$> arbitrary
shrink (SS s) = SS <$> shrink s
data SampleBackState = SB { unSB :: Int }
deriving (Show, Eq, Ord)
instance Enum SampleBackState where
toEnum = SB
fromEnum = unSB
inputAll :: Ord i => WB.Binding s i -> s -> [i] -> IO (WB.Binding s i)
inputAll b _ [] = return b
inputAll binding state (i:rest) = case WB.boundAction binding state i of
Nothing -> inputAll binding state rest
Just act -> join $ inputAll <$> WB.actDo act <*> return state <*> return rest
execAll :: Ord i => s -> [i] -> State.StateT (WB.Binding s i) IO ()
execAll state inputs = do
b <- State.get
next_b <- liftIO $ inputAll b state inputs
State.put next_b
evalStateEmpty :: State.StateT (WB.Binding SampleState SampleInput) IO () -> IO ()
evalStateEmpty s = State.evalStateT s mempty
toDesc :: (i, WB.Action m a) -> (i, WBD.ActionDescription)
toDesc (i, act) = (i, WB.actDescription act)
boundDescs :: WB.Binding s i -> s -> [(i, WBD.ActionDescription)]
boundDescs b s = map toDesc $ WB.boundActions b s
boundDescs' :: WB.Binding' bs fs i -> bs -> fs -> [(i, WBD.ActionDescription)]
boundDescs' b bs fs = map toDesc $ WB.boundActions' b bs fs
curBoundInputs :: s -> State.StateT (WB.Binding s i) IO [i]
curBoundInputs s = State.gets WB.boundInputs <*> pure s
curBoundDescs :: s -> State.StateT (WB.Binding s i) IO [(i, WBD.ActionDescription)]
curBoundDescs s = State.gets boundDescs <*> pure s
curBoundDesc :: Ord i => s -> i -> State.StateT (WB.Binding s i) IO (Maybe WBD.ActionDescription)
curBoundDesc s i = (fmap . fmap) WB.actDescription $ State.gets WB.boundAction <*> pure s <*> pure i
checkBoundInputs :: (Eq i, Show i) => s -> [i] -> State.StateT (WB.Binding s i) IO ()
checkBoundInputs fs expected = liftIO . (`shouldMatchList` expected) =<< curBoundInputs fs
checkBoundDescs :: (Eq i, Show i) => s -> [(i, WBD.ActionDescription)] -> State.StateT (WB.Binding s i) IO ()
checkBoundDescs fs expected = liftIO . (`shouldMatchList` expected) =<< curBoundDescs fs
checkBoundDesc :: (Ord i) => s -> i -> WBD.ActionDescription -> State.StateT (WB.Binding s i) IO ()
checkBoundDesc fs input expected = liftIO . (`shouldBe` Just expected) =<< curBoundDesc fs input
withRefChecker :: (Eq a, Show a, MonadIO m)
=> a
-> (IORef a -> (a -> m ()) -> m ())
-> m ()
withRefChecker init_ref action = do
out <- liftIO $ newIORef init_ref
let checkOut expected = liftIO $ readIORef out `shouldReturn` expected
action out checkOut
| debug-ito/wild-bind | wild-bind/test/WildBind/ForTest.hs | bsd-3-clause | 3,683 | 0 | 14 | 802 | 1,403 | 744 | 659 | 78 | 2 |
module GLogger.Client (
initLogger,
cleanLog,
logDebug,
logInfo,
logNotice,
logWarning,
logError,
logCritical,
logAlert,
logEmergency
) where
import qualified System.Log.Logger as SL
import System.Log.Handler.Simple (fileHandler)
import System.Log.Handler (setFormatter)
import System.Log.Formatter (tfLogFormatter)
import System.IO (withFile, IOMode(..))
import Control.Monad (when)
logFileName :: String
logFileName = "client.log"
loggerName :: String
loggerName = "clientLogger"
enableLogging :: Bool
enableLogging = True
initLogger :: IO ()
initLogger = when enableLogging $ do
h <- fileHandler logFileName SL.DEBUG >>= \lh -> return $
setFormatter lh (tfLogFormatter "%T:%q" "[$time: $loggername : $prio] $msg")
SL.updateGlobalLogger loggerName (SL.setLevel SL.DEBUG)
SL.updateGlobalLogger loggerName (SL.addHandler h)
cleanLog :: IO ()
cleanLog = when enableLogging $ do
withFile logFileName WriteMode (\_ -> return ())
logDebug :: String -> IO ()
logDebug string = when enableLogging $ do
SL.debugM loggerName string
logInfo :: String -> IO ()
logInfo string = when enableLogging $ do
SL.infoM loggerName string
logNotice :: String -> IO ()
logNotice string = when enableLogging $ do
SL.noticeM loggerName string
logWarning :: String -> IO ()
logWarning string = when enableLogging $ do
SL.warningM loggerName string
logError :: String -> IO ()
logError string = when enableLogging $ do
SL.errorM loggerName string
logCritical :: String -> IO ()
logCritical string = when enableLogging $ do
SL.criticalM loggerName string
logAlert :: String -> IO ()
logAlert string = when enableLogging $ do
SL.alertM loggerName string
logEmergency :: String -> IO ()
logEmergency string = when enableLogging $ do
SL.emergencyM loggerName string | cernat-catalin/haskellGame | src/GLogger/Client.hs | bsd-3-clause | 1,815 | 0 | 14 | 314 | 595 | 302 | 293 | 56 | 1 |
{-# LANGUAGE ViewPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.FocusNth
-- Description : Focus the nth window of the current workspace.
-- Copyright : (c) Karsten Schoelzel <[email protected]>
-- License : BSD
--
-- Maintainer : Karsten Schoelzel <[email protected]>
-- Stability : stable
-- Portability : unportable
--
-- Focus the nth window of the current workspace.
-----------------------------------------------------------------------------
module XMonad.Actions.FocusNth (
-- * Usage
-- $usage
focusNth,focusNth',
swapNth,swapNth') where
import XMonad
import XMonad.Prelude
import XMonad.StackSet
-- $usage
-- Add the import to your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.FocusNth
--
-- Then add appropriate keybindings, for example:
--
-- > -- mod4-[1..9] @@ Switch to window N
-- > ++ [((modm, k), focusNth i)
-- > | (i, k) <- zip [0 .. 8] [xK_1 ..]]
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- | Give focus to the nth window of the current workspace.
focusNth :: Int -> X ()
focusNth = windows . modify' . focusNth'
focusNth' :: Int -> Stack a -> Stack a
focusNth' n s | n >= 0, (ls, t:rs) <- splitAt n (integrate s) = Stack t (reverse ls) rs
| otherwise = s
-- | Swap current window with nth. Focus stays in the same position
swapNth :: Int -> X ()
swapNth = windows . modify' . swapNth'
swapNth' :: Int -> Stack a -> Stack a
swapNth' n s@(Stack c l r)
| (n < 0) || (n > length l + length r) || (n == length l) = s
| n < length l = let (nl, notEmpty -> nc :| nr) = splitAt (length l - n - 1) l in Stack nc (nl ++ c : nr) r
| otherwise = let (nl, notEmpty -> nc :| nr) = splitAt (n - length l - 1) r in Stack nc l (nl ++ c : nr)
| xmonad/xmonad-contrib | XMonad/Actions/FocusNth.hs | bsd-3-clause | 1,920 | 0 | 14 | 441 | 450 | 241 | 209 | 19 | 1 |
module Language.Haskell.Liquid.Bare.SymSort (
txRefSort
) where
import Control.Applicative ((<$>))
import qualified Data.List as L
import Language.Fixpoint.Misc (errorstar, safeZip, fst3, snd3)
import Language.Fixpoint.Types (meet)
import Language.Haskell.Liquid.Types.RefType (appRTyCon, strengthen)
import Language.Haskell.Liquid.Types
import Language.Haskell.Liquid.Misc (safeZipWithError)
-- EFFECTS: TODO is this the SAME as addTyConInfo? No. `txRefSort`
-- (1) adds the _real_ sorts to RProp,
-- (2) gathers _extra_ RProp at turnst them into refinements,
-- e.g. tests/pos/multi-pred-app-00.hs
txRefSort tyi tce = mapBot (addSymSort tce tyi)
addSymSort tce tyi (RApp rc@(RTyCon _ _ _) ts rs r)
= RApp rc ts (zipWith3 (addSymSortRef rc) pvs rargs [1..]) r'
where
rc' = appRTyCon tce tyi rc ts
pvs = rTyConPVs rc'
(rargs, rrest) = splitAt (length pvs) rs
r' = L.foldl' go r rrest
go r (RProp _ (RHole r')) = r' `meet` r
go r (RProp _ _ ) = r -- is this correct?
addSymSort _ _ t
= t
addSymSortRef rc p r i | isPropPV p = addSymSortRef' rc i p r
| otherwise = errorstar "addSymSortRef: malformed ref application"
addSymSortRef' _ _ p (RProp s (RVar v r)) | isDummy v
= RProp xs t
where
t = ofRSort (pvType p) `strengthen` r
xs = spliceArgs "addSymSortRef 1" s p
addSymSortRef' rc i p (RProp _ (RHole r@(MkUReft _ (Pr [up]) _)))
= RProp xts (RHole r) -- (ofRSort (pvType p) `strengthen` r)
where
xts = safeZipWithError msg xs ts
xs = snd3 <$> pargs up
ts = fst3 <$> pargs p
msg = intToString i ++ " argument of " ++ show rc ++ " is " ++ show (pname up)
++ " that expects " ++ show (length ts) ++ " arguments, but it has " ++ show (length xs)
addSymSortRef' _ _ _ (RProp s (RHole r))
= RProp s (RHole r) -- (ofRSort (pvType p) `strengthen` r)
addSymSortRef' _ _ p (RProp s t)
= RProp xs t
where
xs = spliceArgs "addSymSortRef 2" s p
spliceArgs msg s p = safeZip msg (fst <$> s) (fst3 <$> pargs p)
intToString 1 = "1st"
intToString 2 = "2nd"
intToString 3 = "3rd"
intToString n = show n ++ "th"
| abakst/liquidhaskell | src/Language/Haskell/Liquid/Bare/SymSort.hs | bsd-3-clause | 2,198 | 0 | 15 | 556 | 762 | 397 | 365 | 43 | 2 |
{-
Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{-# LANGUAGE DeriveDataTypeable, NamedFieldPuns #-}
module Main where
import Prelude hiding (writeFile, readFile, print, putStrLn)
import Data.Functor (void)
import System.IO
import System.Timeout
import System.Process (system)
import Language.Clafer
main :: IO ()
main = do
(args', model) <- mainArgs
let timeInSec = (timeout_analysis args') * 10^(6::Integer)
if timeInSec > 0
then timeout timeInSec $ start args' model
else Just `fmap` start args' model
return ()
start :: ClaferArgs -> InputModel-> IO ()
start args' model = if ecore2clafer args'
then runEcore2Clafer (file args') $ (tooldir args')
else runCompiler Nothing args' model
runEcore2Clafer :: FilePath -> FilePath -> IO ()
runEcore2Clafer ecoreFile toolPath
| null ecoreFile = do
putStrLn "Error: Provide a file name of an ECore model."
| otherwise = do
putStrLn $ "Converting " ++ ecoreFile ++ " into Clafer"
void $ system $ "java -jar " ++ toolPath ++ "/ecore2clafer.jar " ++ ecoreFile
| juodaspaulius/clafer | src-cmd/clafer.hs | mit | 2,148 | 0 | 13 | 393 | 317 | 163 | 154 | 27 | 2 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./Comorphisms/ExtModal2ExtModalTotal.hs
Description : coding out subsorting
Copyright : (c) C. Maeder DFKI GmbH 2012
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic.Logic)
Coding out subsorting (SubPCFOL= -> PCFOL=),
following Chap. III:3.1 of the CASL Reference Manual
-}
module Comorphisms.ExtModal2ExtModalTotal where
import Logic.Logic
import Logic.Comorphism
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Common.Lib.MapSet as MapSet
import Common.AS_Annotation
import Common.ProofUtils
-- CASL
import CASL.AS_Basic_CASL
import CASL.Fold
import CASL.Morphism
import CASL.Sign
import CASL.Simplify
import CASL.Sublogic
import CASL.Utils
import ExtModal.Logic_ExtModal
import ExtModal.AS_ExtModal
import ExtModal.ExtModalSign
import ExtModal.StatAna
import ExtModal.Sublogic as EM
import Comorphisms.CASL2SubCFOL
-- | The identity of the comorphism
data ExtModal2ExtModalTotal = ExtModal2ExtModalTotal deriving Show
instance Language ExtModal2ExtModalTotal -- default definition is okay
instance Comorphism ExtModal2ExtModalTotal
ExtModal ExtModalSL EM_BASIC_SPEC ExtModalFORMULA SYMB_ITEMS
SYMB_MAP_ITEMS ExtModalSign ExtModalMorph
Symbol RawSymbol ()
ExtModal ExtModalSL EM_BASIC_SPEC ExtModalFORMULA SYMB_ITEMS
SYMB_MAP_ITEMS ExtModalSign ExtModalMorph
Symbol RawSymbol () where
sourceLogic ExtModal2ExtModalTotal = ExtModal
sourceSublogic ExtModal2ExtModalTotal = mkTop maxSublogic
targetLogic ExtModal2ExtModalTotal = ExtModal
mapSublogic ExtModal2ExtModalTotal sl = Just
$ if has_part sl then sl
{ has_part = False -- partiality is coded out
, has_pred = True
, which_logic = max Horn $ which_logic sl
, has_eq = True} else sl
map_theory ExtModal2ExtModalTotal (sig, sens) = let
bsrts = emsortsWithBottom sig
sens1 = generateAxioms True bsrts sig
sens2 = map (mapNamed (noCondsEMFormula . simplifyEMFormula
. codeEMFormula bsrts)) sens
in return
( emEncodeSig bsrts sig
, nameAndDisambiguate $ sens1 ++ sens2)
map_morphism ExtModal2ExtModalTotal mor@Morphism
{msource = src, mtarget = tar}
= return
mor { msource = emEncodeSig (emsortsWithBottom src) src
, mtarget = emEncodeSig (emsortsWithBottom tar) tar
, op_map = Map.map (\ (i, _) -> (i, Total)) $ op_map mor }
map_sentence ExtModal2ExtModalTotal sig sen = let
bsrts = emsortsWithBottom sig
in return $ simplifyEMFormula $ codeEMFormula bsrts sen
map_symbol ExtModal2ExtModalTotal _ s =
Set.singleton s { symbType = totalizeSymbType $ symbType s }
has_model_expansion ExtModal2ExtModalTotal = True
is_weakly_amalgamable ExtModal2ExtModalTotal = True
emEncodeSig :: Set.Set SORT -> Sign f EModalSign -> Sign f EModalSign
emEncodeSig bsrts sig = (encodeSig bsrts sig)
{ extendedInfo = let extInfo = extendedInfo sig in
extInfo { flexOps = MapSet.map mkTotal $ flexOps extInfo }}
emsortsWithBottom :: Sign f e -> Set.Set SORT
emsortsWithBottom sig = sortsWithBottom NoMembershipOrCast sig Set.empty
simplifyEM :: EM_FORMULA -> EM_FORMULA
simplifyEM = mapExtForm simplifyEMFormula
simplifyEMFormula :: FORMULA EM_FORMULA -> FORMULA EM_FORMULA
simplifyEMFormula = simplifyFormula simplifyEM
noCondsEM :: EM_FORMULA -> EM_FORMULA
noCondsEM = mapExtForm noCondsEMFormula
noCondsEMFormula :: FORMULA EM_FORMULA -> FORMULA EM_FORMULA
noCondsEMFormula = codeOutConditionalF noCondsEM
codeEM :: Set.Set SORT -> EM_FORMULA -> EM_FORMULA
codeEM = mapExtForm . codeEMFormula
codeEMFormula :: Set.Set SORT -> FORMULA EM_FORMULA -> FORMULA EM_FORMULA
codeEMFormula bsrts = foldFormula (codeRecord True bsrts $ codeEM bsrts)
| spechub/Hets | Comorphisms/ExtModal2ExtModalTotal.hs | gpl-2.0 | 4,067 | 0 | 15 | 823 | 852 | 450 | 402 | 79 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Book
( Book (..)
, Part (..)
, Chapter (..)
, loadBook
) where
import Control.Exception (SomeException, evaluate, handle,
throw)
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Trans.Resource
import Control.Monad.Trans.Writer
import qualified Data.ByteString.Lazy as L
import Data.Conduit
import Data.Conduit.Binary (sourceFile)
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Text as CT
import qualified Data.Map as Map
import Data.Maybe (listToMaybe, mapMaybe)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Filesystem as F
import qualified Filesystem.Path.CurrentOS as F
import Prelude
import Text.Blaze.Html (Html, toHtml)
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.XML as X
data Book = Book
{ bookParts :: [Part]
, bookChapterMap :: Map.Map Text Chapter
}
data Part = Part
{ partTitle :: Text
, partChapters :: [Chapter]
}
data Chapter = Chapter
{ chapterTitle :: Text
, chapterPath :: F.FilePath
, chapterSlug :: Text
, chapterHtml :: Html
}
getTitle :: [Node] -> IO (Text, [Node])
getTitle =
go id
where
go _ [] = error "Title not found"
go front (NodeElement (Element "title" _ [NodeContent t]):rest) =
return (t, front rest)
go front (n:ns) = go (front . (n:)) ns
mapWhile :: Monad m => (a -> Maybe b) -> Conduit a m b
mapWhile f =
loop
where
loop = await >>= maybe (return ()) go
go x =
case f x of
Just y -> yield y >> loop
Nothing -> leftover x
data BookLine = Title Text | Include Text
parseBookLine :: Text -> Maybe BookLine
parseBookLine t
| Just t' <- T.stripPrefix "= " t = Just $ Title t'
| Just t' <- T.stripPrefix "include::chapters/" t
>>= T.stripSuffix ".asciidoc[]" = Just $ Include t'
| Just t' <- T.stripPrefix "include::" t
>>= T.stripSuffix ".asciidoc[]" = Just $ Include t'
| otherwise = Nothing
loadBook :: F.FilePath -> IO Book
loadBook dir = handle (\(e :: SomeException) -> return (throw e)) $ do
fp <- trySuffixes
[ "yesod-web-framework-book.asciidoc"
, "asciidoc/book.asciidoc"
]
parts <- runResourceT
$ sourceFile (F.encodeString fp)
$$ CT.decode CT.utf8
=$ CT.lines
=$ CL.mapMaybe parseBookLine
=$ (CL.drop 1 >> parseParts)
=$ CL.consume
let m = Map.fromList $ concatMap goP parts
goC c = (chapterSlug c, c)
goP = map goC . partChapters
return $ Book parts m
where
trySuffixes [] = error "No suffixes worked for loading book"
trySuffixes (x:xs) = do
let fp = dir F.</> x
exists <- F.isFile fp
if exists then return fp else trySuffixes xs
parseParts :: MonadIO m => Conduit BookLine m Part
parseParts =
start
where
start = await >>= maybe (return ()) start'
start' (Title t) = do
let getInclude (Include x) = Just x
getInclude _ = Nothing
chapters <- mapWhile getInclude =$= CL.mapM (liftIO . parseChapter) =$= CL.consume
yield $ Part t chapters
start
start' (Include _t) = start -- error $ "Invalid beginning of a Part: " ++ show t
ps = def { psDecodeEntities = decodeHtmlEntities }
-- Read a chapter as an XML file, converting from AsciiDoc as necessary
chapterToDoc fp'
| F.hasExtension fp' "ad" || F.hasExtension fp' "asciidoc" =
let fp'' = F.directory fp' F.</> "../generated-xml" F.</> F.replaceExtension (F.filename fp') "xml"
in X.readFile ps $ F.encodeString fp''
| otherwise = X.readFile ps $ F.encodeString fp'
getSection (NodeElement e@(Element "section" _ _)) = Just e
getSection (NodeElement e@(Element "appendix" _ _)) = Just e
getSection _ = Nothing
parseChapter :: Text -> IO Chapter
parseChapter slug = do
let fp' = dir F.</> "generated-xml" F.</> F.fromText slug F.<.> "xml"
Document _ (Element name _ csOrig) _ <- chapterToDoc fp'
cs <-
case name of
"article" ->
case listToMaybe $ mapMaybe getSection csOrig of
Nothing -> error "article without child section"
Just (Element _ _ cs) -> return cs
"chapter" -> return csOrig
_ -> error $ "Unknown root element: " ++ show name
(title, rest) <- getTitle cs
let content = mconcat $ map toHtml $ concatMap (goNode False) rest
!_ <- evaluate $ L.length $ renderHtml content -- FIXME comment out to avoid eager error checking
return $ Chapter title fp' slug content
goNode :: Bool -> Node -> [Node]
goNode b (NodeElement e) = goElem b e
goNode _ n = [n]
goElem :: Bool -- ^ inside figure?
-> Element -> [Node]
{-
goElem _ (Element "apiname" _ [NodeContent t]) = goApiname t
-}
goElem _ (Element "programlisting" as [NodeContent t]) | Just "lhaskell" <- Map.lookup "language" as = goLHS t
goElem _ (Element "programlisting" as [NodeContent t]) | Just "haskell" <- Map.lookup "language" as =
[ NodeElement $ Element "pre" as
[ NodeElement $ Element
"code"
(Map.singleton "class" $ T.unwords $ execWriter $ do
tell ["haskell"]
case filter ("main = " `T.isPrefixOf`) $ T.lines t of
rest:_ -> do
tell ["active"]
when ("warp" `elem` T.words rest) $ tell ["web"]
[] -> return ()
)
[ NodeContent $ goStartStop t
]
]
]
goElem insideFigure (Element n as cs)
{-
| insideFigure && n == "h1" = [NodeElement $ Element "figcaption" as cs']
-}
| nameLocalName n `Set.member` unchanged = [NodeElement $ Element n as cs']
| Just n' <- Map.lookup n simples = [NodeElement $ Element n' as cs']
| Just (n', clazz) <- Map.lookup n classes = [NodeElement $ Element n' (Map.insert "class" clazz as) cs']
| n `Set.member` deleted = []
| n `Set.member` stripped = cs'
| n == "programlisting" = [NodeElement $ Element "pre" as [NodeElement $ Element "code" Map.empty cs']]
| n == "imagedata" = goImage as cs'
| n == "varlistentry" = goVarListEntry insideFigure cs
| n == "ulink", Just url <- Map.lookup "url" as =
[ NodeElement $ Element
"a"
(Map.delete "url" $ Map.insert "href" url as)
cs'
]
| otherwise = error $ "Unknown: " ++ show (nameLocalName n)
where
cs' = concatMap (goNode $ insideFigure || n == "figure") cs
unchanged = Set.fromList $ T.words "section figure table tgroup thead tbody blockquote code"
simples = Map.fromList
[ ("para", "p")
, ("simpara", "p")
, ("emphasis", "em")
, ("title", "h1")
, ("itemizedlist", "ul")
, ("orderedlist", "ol")
, ("listitem", "li")
, ("link", "a")
, ("variablelist", "dl")
, ("term", "dt")
, ("literal", "code")
, ("screen", "pre")
, ("quote", "q")
, ("row", "tr")
, ("entry", "td")
, ("citation", "cite")
, ("literallayout", "pre")
, ("informaltable", "table")
, ("formalpara", "section")
, ("attribution", "cite")
]
{-
, ("title", "h1")
]
-}
classes = Map.fromList
[ ("glossterm", ("span", "term"))
, ("function", ("span", "apiname"))
, ("command", ("span", "cmdname"))
, ("note", ("aside", "note"))
, ("userinput", ("span", "userinput"))
, ("varname", ("span", "varname"))
, ("filename", ("span", "filepath"))
]
{-
, ("msgblock", ("pre", "msgblock"))
]
-}
deleted = Set.fromList
[ "textobject"
, "colspec"
]
stripped = Set.fromList
[ "mediaobject"
, "imageobject"
]
{-
[ "conbody"
, "dlentry"
]
-}
goVarListEntry insideFigure =
concatMap go
where
go (NodeElement (Element "term" _ cs)) =
[ NodeElement $ Element "dt" Map.empty $
concatMap (goNode insideFigure) cs
]
go (NodeElement (Element "listitem" _ cs)) =
[ NodeElement $ Element "dd" Map.empty $
concatMap (goNode insideFigure) cs
]
go _ = []
goStartStop t
| "-- START" `elem` ls = T.unlines $ go False ls
| otherwise = t
where
ls = T.lines t
go _ [] = []
go _ ("-- START":xs) = go True xs
go _ ("-- STOP":xs) = go False xs
go True (x:xs) = x : go True xs
go False (_:xs) = go False xs
goLHS t0 =
map go lhBlocks
where
ls = T.lines t0
lhLines = map lhLine ls
lhBlocks = map (fmap T.unlines) $ toBlocks lhLines
go (LHCode t) = NodeElement $ Element "pre" Map.empty [NodeElement $ Element "code" Map.empty [NodeContent t]]
go (LHText t) = NodeElement $ Element "p" (Map.singleton "style" "white-space:pre") [NodeContent t]
goImage as cs =
[NodeElement $ Element "img" (Map.singleton "src" href') cs]
where
href' =
case Map.lookup "fileref" as of
Just href ->
let name = either id id $ F.toText $ F.basename $ F.fromText href
in T.append "image/" name
Nothing -> error "image without href"
data LHask t = LHCode t | LHText t
instance Functor LHask where
fmap f (LHCode x) = LHCode (f x)
fmap f (LHText x) = LHText (f x)
lhLine :: Text -> LHask [Text]
lhLine t =
case T.stripPrefix "> " t of
Nothing -> LHText [t]
Just s -> LHCode [s]
toBlocks :: [LHask [Text]] -> [LHask [Text]]
toBlocks [] = []
toBlocks (LHCode x:LHCode y:rest) = toBlocks $ LHCode (x ++ y) : rest
toBlocks (LHText x:LHText y:rest) = toBlocks $ LHText (x ++ y) : rest
toBlocks (x:rest) = x : toBlocks rest
| wolftune/yesodweb.com | Book.hs | bsd-2-clause | 10,973 | 0 | 28 | 3,884 | 3,464 | 1,795 | 1,669 | 239 | 22 |
-- print2.hs
module Print2 where
main :: IO ()
main = do
putStrLn "Count to four for me:"
putStr "one, two"
putStr ", three, and"
putStrLn " four!"
| OCExercise/haskellbook-solutions | chapters/chapter03/scratch/print2.hs | bsd-2-clause | 169 | 0 | 7 | 49 | 44 | 20 | 24 | 7 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Copyright : (c) 2010 Simon Meier
--
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Conversion of 'Float's and 'Double's to 'Word32's and 'Word64's.
--
module Data.ByteString.Builder.Prim.Internal.Floating
(
-- coerceFloatToWord32
-- , coerceDoubleToWord64
encodeFloatViaWord32F
, encodeDoubleViaWord64F
) where
import Foreign
import Data.ByteString.Builder.Prim.Internal
{-
We work around ticket http://ghc.haskell.org/trac/ghc/ticket/4092 using the
FFI to store the Float/Double in the buffer and peek it out again from there.
-}
-- | Encode a 'Float' using a 'Word32' encoding.
--
-- PRE: The 'Word32' encoding must have a size of at least 4 bytes.
{-# INLINE encodeFloatViaWord32F #-}
encodeFloatViaWord32F :: FixedPrim Word32 -> FixedPrim Float
encodeFloatViaWord32F w32fe
| size w32fe < sizeOf (undefined :: Float) =
error $ "encodeFloatViaWord32F: encoding not wide enough"
| otherwise = fixedPrim (size w32fe) $ \x op -> do
poke (castPtr op) x
x' <- peek (castPtr op)
runF w32fe x' op
-- | Encode a 'Double' using a 'Word64' encoding.
--
-- PRE: The 'Word64' encoding must have a size of at least 8 bytes.
{-# INLINE encodeDoubleViaWord64F #-}
encodeDoubleViaWord64F :: FixedPrim Word64 -> FixedPrim Double
encodeDoubleViaWord64F w64fe
| size w64fe < sizeOf (undefined :: Float) =
error $ "encodeDoubleViaWord64F: encoding not wide enough"
| otherwise = fixedPrim (size w64fe) $ \x op -> do
poke (castPtr op) x
x' <- peek (castPtr op)
runF w64fe x' op
| CloudI/CloudI | src/api/haskell/external/bytestring-0.10.10.0/Data/ByteString/Builder/Prim/Internal/Floating.hs | mit | 1,783 | 0 | 13 | 348 | 292 | 156 | 136 | 26 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Vimus.Command.Help (
Help (..)
, help
, commandShortHelp
, commandHelpText
) where
import Control.Monad
import Data.Maybe
import Data.String
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
import Vimus.Command.Type
import Vimus.Util (strip)
-- | A `QuasiQuoter` for help text.
help :: QuasiQuoter
help = QuasiQuoter {
quoteExp = lift . parseHelp
, quotePat = error "Command.Help.help: quotePat is undefined!"
, quoteType = error "Command.Help.help: quoteType is undefined!"
, quoteDec = error "Command.Help.help: quoteDec is undefined!"
}
instance Lift Help where
lift (Help xs) = AppE `fmap` [|Help|] `ap` lift xs
instance IsString Help where
fromString = parseHelp
-- | Parse help text.
parseHelp :: String -> Help
parseHelp = Help . go . map strip . lines
where
go l = case dropWhile null l of
[] -> []
xs -> let (ys, zs) = break null xs in (wordWrapping . unwords) ys ++ go zs
-- | Apply automatic word wrapping.
wordWrapping :: String -> [String]
wordWrapping = run . words
where
-- we start each recursion step at 2, this makes sure that each step
-- consumes at least one word
run = go 2
go n xs
| null xs = []
| 60 < length (unwords ys) = let (as, bs) = splitAt (pred n) xs in unwords as : run bs
| null zs = [unwords ys]
| otherwise = go (succ n) xs
where
(ys, zs) = splitAt n xs
-- | The first line of the command description.
commandShortHelp :: Command -> String
commandShortHelp = fromMaybe "" . listToMaybe . unHelp . commandHelp_
commandHelpText :: Command -> [String]
commandHelpText = unHelp . commandHelp_
| haasn/vimus | src/Vimus/Command/Help.hs | mit | 1,881 | 0 | 15 | 509 | 510 | 275 | 235 | 43 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.IAM.UploadSigningCertificate
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Uploads an X.509 signing certificate and associates it with the specified
-- user. Some AWS services use X.509 signing certificates to validate requests
-- that are signed with a corresponding private key. When you upload the
-- certificate, its default status is 'Active'.
--
-- If the 'UserName' field is not specified, the user name is determined
-- implicitly based on the AWS access key ID used to sign the request. Because
-- this action works for access keys under the AWS account, you can use this
-- action to manage root credentials even if the AWS account has no associated
-- users.
--
-- Because the body of a X.509 certificate can be large, you should use POST
-- rather than GET when calling 'UploadSigningCertificate'. For information about
-- setting up signatures and authorization through the API, go to <http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html Signing AWSAPI Requests> in the /AWS General Reference/. For general information about
-- using the Query API with IAM, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html Making Query Requests> in the /Using IAM/guide.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UploadSigningCertificate.html>
module Network.AWS.IAM.UploadSigningCertificate
(
-- * Request
UploadSigningCertificate
-- ** Request constructor
, uploadSigningCertificate
-- ** Request lenses
, usc1CertificateBody
, usc1UserName
-- * Response
, UploadSigningCertificateResponse
-- ** Response constructor
, uploadSigningCertificateResponse
-- ** Response lenses
, uscrCertificate
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data UploadSigningCertificate = UploadSigningCertificate
{ _usc1CertificateBody :: Text
, _usc1UserName :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'UploadSigningCertificate' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'usc1CertificateBody' @::@ 'Text'
--
-- * 'usc1UserName' @::@ 'Maybe' 'Text'
--
uploadSigningCertificate :: Text -- ^ 'usc1CertificateBody'
-> UploadSigningCertificate
uploadSigningCertificate p1 = UploadSigningCertificate
{ _usc1CertificateBody = p1
, _usc1UserName = Nothing
}
-- | The contents of the signing certificate.
usc1CertificateBody :: Lens' UploadSigningCertificate Text
usc1CertificateBody =
lens _usc1CertificateBody (\s a -> s { _usc1CertificateBody = a })
-- | The name of the user the signing certificate is for.
usc1UserName :: Lens' UploadSigningCertificate (Maybe Text)
usc1UserName = lens _usc1UserName (\s a -> s { _usc1UserName = a })
newtype UploadSigningCertificateResponse = UploadSigningCertificateResponse
{ _uscrCertificate :: SigningCertificate
} deriving (Eq, Read, Show)
-- | 'UploadSigningCertificateResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uscrCertificate' @::@ 'SigningCertificate'
--
uploadSigningCertificateResponse :: SigningCertificate -- ^ 'uscrCertificate'
-> UploadSigningCertificateResponse
uploadSigningCertificateResponse p1 = UploadSigningCertificateResponse
{ _uscrCertificate = p1
}
-- | Information about the certificate.
uscrCertificate :: Lens' UploadSigningCertificateResponse SigningCertificate
uscrCertificate = lens _uscrCertificate (\s a -> s { _uscrCertificate = a })
instance ToPath UploadSigningCertificate where
toPath = const "/"
instance ToQuery UploadSigningCertificate where
toQuery UploadSigningCertificate{..} = mconcat
[ "CertificateBody" =? _usc1CertificateBody
, "UserName" =? _usc1UserName
]
instance ToHeaders UploadSigningCertificate
instance AWSRequest UploadSigningCertificate where
type Sv UploadSigningCertificate = IAM
type Rs UploadSigningCertificate = UploadSigningCertificateResponse
request = post "UploadSigningCertificate"
response = xmlResponse
instance FromXML UploadSigningCertificateResponse where
parseXML = withElement "UploadSigningCertificateResult" $ \x -> UploadSigningCertificateResponse
<$> x .@ "Certificate"
| romanb/amazonka | amazonka-iam/gen/Network/AWS/IAM/UploadSigningCertificate.hs | mpl-2.0 | 5,344 | 0 | 9 | 1,035 | 501 | 310 | 191 | 61 | 1 |
module Control.Search.Combinator.Let (let', set') where
import Control.Search.Language
import Control.Search.GeneratorInfo
import Control.Search.Generator
import Control.Search.Stat
stmPrefixLoop stm super = super { tryH = \i -> (stm i) @>>>@ (tryE super) i, startTryH = \i -> (stm i) @>>>@ (startTryH super) i, toString = "prefix(" ++ toString super ++ ")" }
letLoop :: Evalable m => VarId -> Stat -> Eval m -> Eval m
letLoop v@(VarId i) val super'' =
let super' = evalStat val super''
super = super' { evalState_ = ("var" ++ (show i), Int, \i -> setVarInfo v i >> readStat val >>= \x -> return (x i)) : evalState_ super',
toString = "let(" ++ show v ++ "," ++ show val ++ "," ++ toString super'' ++ ")" }
in commentEval super
let'
:: VarId
-> Stat
-> Search
-> Search
let' var val s =
case s of
Search { mkeval = evals, runsearch = runs } ->
Search { mkeval = \super -> do { ss <- evals super
; return $ letLoop var val ss
}
, runsearch = runs
}
set' :: VarId -> Stat -> Search -> Search
set' var val s = case s of
Search { mkeval = evals, runsearch = runs } ->
Search { mkeval = \super -> do { ss <- evals super
; let ss1 = evalStat (varStat var) ss
; let ss2 = evalStat val ss1
; return $ stmPrefixLoop (\i -> readStat (varStat var) >>= \rvar -> readStat val >>= \rval -> return $ Assign (rvar i) (rval i)) ss2
}
, runsearch = runs
}
| neothemachine/monadiccp | src/Control/Search/Combinator/Let.hs | bsd-3-clause | 1,680 | 0 | 24 | 603 | 605 | 319 | 286 | 31 | 1 |
{-|
Module : CSH.Eval.Cacheable.Make
Description : Cacheable Actions to Create Objects
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : [email protected]
Stability : Provisional
Portability : POSIX
CSH.Eval.Cacheable.Make defines 'Cacheable' computations for introducing state
objects.
-}
{-# LANGUAGE OverloadedStrings #-}
module CSH.Eval.Cacheable.Make (
-- * Object Instantiating Functions
-- ** Member
mkIntroMember
, mkExtantMember
-- ** Event
, mkEvent
-- ** Project
, mkProject
-- ** Evaluation
, mkEvaluation
-- ** Conditional
, mkConditional
-- ** FreshmanProject
, mkFreshmanProject
-- ** Packet
, mkPacket
-- ** Application
, mkApplication
-- ** Metric
, mkMetric
-- ** Review
, mkReview
-- ** Interview
, mkInterview
-- ** Question
, mkQuestion
-- ** Term
, mkTerm
-- * Context Instantiating Functions
-- ** Eboard
, grEboard
-- ** Room
, grRoom
-- ** Queue
, grQueue
-- ** Membership
, grMembership
-- ** EventAttendee
, grEventAttendee
-- ** ProjectParticipant
, grProjectParticipant
-- ** FreshmanProjectParticipant
, grFreshmanProjectParticipant
-- ** Signature
, grSignature
-- ** ReviewMetric
, grReviewMetric
-- ** InterviewMetric
, grInterviewMetric
-- ** Answer
, grAnswer
-- ** Dues
, grDues
-- * ToRow Functions
) where
import Data.Word
import Data.UUID
import Data.Time
import qualified Data.ByteString as B
import qualified Data.Text as T
import CSH.Eval.Model
import CSH.Eval.DB.Statements
import CSH.Eval.Cacheable.Prim
import CSH.Eval.Cacheable.Fetch
mkIntroMember :: UUID -- ^ Member UUID.
-> T.Text -- ^ Username.
-> T.Text -- ^ Common name.
-> B.ByteString -- ^ Passowrd hash.
-> B.ByteString -- ^ Passowrd salt
-> Cacheable ()
mkIntroMember uu u cn ph ps c = do
mid <- liftInsertSingleQ (mkIntroMemberP uu u cn ph ps) c
let m = Member mid
uu
u
cn
Nothing
0
False
(getMemberEboards mid)
(getMemberRooms mid)
(getMemberMemberships mid)
(getMemberEvaluations mid)
(getMemberPackets mid)
(getMemberQueues mid)
(getMemberApplications mid)
(getMemberDues mid)
singletonGhost memberIDCache mid m c
mkExtantMember :: UUID -- ^ Member UUID.
-> T.Text -- ^ Username.
-> T.Text -- ^ Common name.
-> Int -- ^ Housing points.
-> Bool -- ^ On floor status.
-> Cacheable ()
mkExtantMember uu u cn hp os c = do
mid <- liftInsertSingleQ (mkExtantMemberP uu u cn hp os) c
let m = Member mid
uu
u
cn
Nothing
hp
os
(getMemberEboards mid)
(getMemberRooms mid)
(getMemberMemberships mid)
(getMemberEvaluations mid)
(getMemberPackets mid)
(getMemberQueues mid)
(getMemberApplications mid)
(getMemberDues mid)
singletonGhost memberIDCache mid m c
mkEvent :: T.Text -- ^ Title.
-> UTCTime -- ^ Held time.
-> EventType -- ^ Event type
-> Committee -- ^ Event Committee
-> T.Text -- ^ Description
-> Cacheable ()
mkEvent t h et ec d c = do
eid <- liftInsertSingleQ (mkEventP t h (eventTypeToVal et) (committeeToVal ec) d) c
let e = Event eid
t
h
et
ec
d
(getEventEventAttendees eid)
singletonGhost eventIDCache eid e c
mkProject :: T.Text -- ^ Title.
-> T.Text -- ^ Description.
-> UTCTime -- ^ Submission time.
-> Committee -- ^ Project committee.
-> ProjectType -- ^ Project type.
-> Cacheable ()
mkProject t d st pc pt c = do
pid <- liftInsertSingleQ (mkProjectP t d st (committeeToVal pc) (projectTypeToVal pt)) c
let p = Project pid
t
d
st
Nothing
pc
pt
T.empty
Pending
(getProjectProjectParticipants pid)
singletonGhost projectIDCache pid p c
mkEvaluation :: Word64 -- ^ Member ID.
-> UTCTime -- ^ Evaluation deadline.
-> EvaluationType -- ^ Evaluation type.
-> Cacheable ()
mkEvaluation mid t et c = do
eid <- liftInsertSingleQ (mkEvaluationP mid t (evaluationTypeToVal et)) c
let e = Evaluation eid
T.empty
t
False
Pending
et
(getMemberID mid)
(getEvaluationConditionals eid)
(getEvaluationFreshmanProjectParticipants eid)
singletonGhost evaluationIDCache eid e c
mkConditional :: Word64 -- ^ Evaluation ID.
-> UTCTime -- ^ Due date.
-> T.Text -- ^ Description.
-> Cacheable ()
mkConditional eid dt d c = do
cid <- liftInsertSingleQ (mkConditionalP eid dt d) c
let c' = Conditional cid
dt
d
T.empty
(getEvaluationID eid)
singletonGhost conditionalIDCache cid c' c
mkFreshmanProject :: Word64 -- ^ Term ID.
-> Word64 -- ^ Event ID.
-> T.Text -- ^ Description.
-> Cacheable ()
mkFreshmanProject tid eid d c = do
fpid <- liftInsertSingleQ (mkFreshmanProjectP tid eid d) c
let fp = FreshmanProject fpid
d
(getTermID tid)
(getEventID eid)
(getFreshmanProjectFreshmanProjectParticipants fpid)
singletonGhost freshmanProjectIDCache fpid fp c
mkPacket :: Word64 -- ^ Member ID.
-> UTCTime -- ^ Due date.
-> Int -- ^ Percent required.
-> Cacheable ()
mkPacket mid d p c = do
pid <- liftInsertSingleQ (mkPacketP mid d p) c
let p' = Packet pid
d
p
(getMemberID mid)
(getPacketSignatures pid)
singletonGhost packetIDCache pid p' c
mkApplication :: Word64 -- ^ Member ID.
-> UTCTime -- ^ Creation time.
-> Cacheable ()
mkApplication mid t c = do
aid <- liftInsertSingleQ (mkApplicationP mid t) c
let a = Application aid
t
Pending
(getMemberID mid)
(getApplicationReviews aid)
(getApplicationInterviews aid)
(getApplicationAnswers aid)
singletonGhost applicationIDCache aid a c
mkMetric :: T.Text -- ^ Description.
-> Cacheable ()
mkMetric d c = do
mid <- liftInsertSingleQ (mkMetricP d) c
let m = Metric mid
d
True
singletonGhost metricIDCache mid m c
mkReview :: Word64 -- ^ Member ID(reviewer).
-> Word64 -- ^ Application ID.
-> UTCTime -- ^ Start time.
-> UTCTime -- ^ Submission time.
-> Cacheable ()
mkReview mid aid st et c = do
rid <- liftInsertSingleQ (mkReviewP mid aid st et) c
let r = Review rid
st
et
(getMemberID mid)
(getApplicationID aid)
(getReviewReviewMetrics rid)
singletonGhost reviewIDCache rid r c
mkInterview :: Word64 -- ^ Member ID(interviewer).
-> Word64 -- ^ Application ID.
-> UTCTime -- ^ Interview time.
-> Cacheable ()
mkInterview mid aid t c = do
iid <- liftInsertSingleQ (mkInterviewP mid aid t) c
let i = Interview iid
t
(getMemberID mid)
(getApplicationID aid)
(getInterviewInterviewMetrics iid)
singletonGhost interviewIDCache iid i c
mkQuestion :: T.Text -- ^ Query.
-> Cacheable ()
mkQuestion q c = do
qid <- liftInsertSingleQ (mkQuestionP q) c
let q' = Question qid
q
True
singletonGhost questionIDCache qid q' c
mkTerm :: Day -- ^ Start date.
-> Cacheable ()
mkTerm s c = do
tid <- liftInsertSingleQ (mkTermP s) c
let t = Term tid
s
Nothing
singletonGhost termIDCache tid t c
grEboard :: Word64 -- ^ Member ID.
-> Committee -- ^ Committee.
-> Day -- ^ Service start date.
-> Cacheable ()
grEboard mid cm s c = do
liftUnitQ (grEboardP mid (committeeToVal cm) s) c
let e = Eboard cm
s
Nothing
(getMemberID mid)
appendGhost eboardMemberIDCache mid e c
grRoom :: Word64 -- ^ Member ID.
-> T.Text -- ^ Room number.
-> Day -- ^ Residence start date.
-> Cacheable ()
grRoom mid rn s c = do
liftUnitQ (grRoomP mid rn s) c
let r = Room rn
s
Nothing
(getMemberID mid)
appendGhost roomMemberIDCache mid r c
grQueue :: Word64 -- ^ Member ID.
-> UTCTime -- ^ Entrance time.
-> Cacheable ()
grQueue mid t c = do
liftUnitQ (grQueueP mid t) c
let q = Queue t
Nothing
(getMemberID mid)
appendGhost queueMemberIDCache mid q c
grMembership :: Word64 -- ^ Member ID.
-> MemberStatus -- ^ Membership status.
-> Day -- ^ Effective date.
-> Cacheable ()
grMembership mid ms t c = do
liftUnitQ (grMembershipP mid (memberStatusToVal ms) t) c
let m = Membership ms
t
Nothing
(getMemberID mid)
appendGhost membershipMemberIDCache mid m c
grEventAttendee :: Word64 -- ^ Member ID.
-> Word64 -- ^ Event ID.
-> Bool -- ^ Host status.
-> Cacheable ()
grEventAttendee mid eid h c = do
liftUnitQ (grEventAttendeeP mid eid h) c
let e = EventAttendee h
(getMemberID mid)
(getEventID eid)
appendGhost eventAttendeeMemberIDCache mid e c
appendGhost eventAttendeeEventIDCache eid e c
grProjectParticipant :: Word64 -- ^ Member ID.
-> Word64 -- ^ Project ID.
-> T.Text -- ^ Description.
-> Cacheable ()
grProjectParticipant mid pid d c = do
liftUnitQ (grProjectParticipantP mid pid d) c
let p = ProjectParticipant d
(getMemberID mid)
(getProjectID pid)
appendGhost projectParticipantMemberIDCache mid p c
appendGhost projectParticipantProjectIDCache pid p c
grFreshmanProjectParticipant :: Word64 -- ^ Freshman Project ID.
-> Word64 -- ^ Evaluation ID.
-> Cacheable ()
grFreshmanProjectParticipant pid eid c = do
liftUnitQ (grFreshmanProjectParticipantP pid eid) c
let f = FreshmanProjectParticipant False
Pending
T.empty
(getFreshmanProjectID pid)
(getEvaluationID eid)
appendGhost freshProjParticipantProjectIDCache pid f c
appendGhost freshProjParticipantEvaluationIDCache eid f c
grSignature :: Word64 -- ^ Member ID.
-> Word64 -- ^ Packet ID.
-> Bool -- ^ Required.
-> Cacheable ()
grSignature mid pid r c = do
liftUnitQ (grSignatureP mid pid r) c
let s = Signature r
Nothing
(getMemberID mid)
(getPacketID pid)
appendGhost signatureMemberIDCache mid s c
appendGhost signaturePacketIDCache pid s c
grReviewMetric :: Word64 -- ^ Metric ID.
-> Word64 -- ^ Review ID.
-> Int -- ^ Score.
-> Cacheable ()
grReviewMetric mid rid s c = do
liftUnitQ (grReviewMetricP mid rid s) c
let r = ReviewMetric s
(getMetricID mid)
(getReviewID rid)
appendGhost reviewMetricMetricIDCache mid r c
appendGhost reviewMetricReviewIDCache rid r c
grInterviewMetric :: Word64 -- ^ Metric ID.
-> Word64 -- ^ Interview ID.
-> Int -- ^ Score.
-> Cacheable ()
grInterviewMetric mid iid s c = do
liftUnitQ (grInterviewMetricP mid iid s) c
let i = InterviewMetric s
(getMetricID mid)
(getInterviewID iid)
appendGhost interviewMetricMetricIDCache mid i c
appendGhost interviewMetricInterviewIDCache iid i c
grAnswer :: Word64 -- ^ Application ID
-> Word64 -- ^ Question ID
-> T.Text -- ^ Response
-> Cacheable ()
grAnswer aid qid r c = do
liftUnitQ (grAnswerP aid qid r) c
let a = Answer r
(getQuestionID qid)
(getApplicationID aid)
appendGhost answerQuestionIDCache qid a c
appendGhost answerApplicationIDCache aid a c
grDues :: Word64 -- ^ Term ID.
-> Word64 -- ^ Member ID.
-> DuesStatus -- ^ Dues status.
-> Cacheable ()
grDues tid mid s c = do
liftUnitQ (grDuesP tid mid (duesStatusToVal s)) c
let d = Dues s
(getMemberID mid)
(getTermID tid)
appendGhost duesMemberIDCache mid d c
appendGhost duesTermIDCache tid d c
| TravisWhitaker/csh-eval | src/CSH/Eval/Cacheable/Make.hs | mit | 14,290 | 0 | 12 | 5,752 | 3,094 | 1,541 | 1,553 | 367 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="el-GR">
<title>Port Scan | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Ευρετήριο</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Αναζήτηση</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/zest/src/main/javahelp/org/zaproxy/zap/extension/zest/resources/help_el_GR/helpset_el_GR.hs | apache-2.0 | 996 | 80 | 66 | 160 | 449 | 226 | 223 | -1 | -1 |
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Core.Execute (execute) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import IRTS.Lang(FDesc(..), FType(..))
import Idris.Primitives(Prim(..), primitives)
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Idris.Error
import Debug.Trace
import Util.DynamicLinker
import Util.System
import Control.Applicative hiding (Const)
import Control.Exception
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Control.Monad hiding (forM)
import Data.Maybe
import Data.Bits
import Data.Traversable (forM)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Map as M
#ifdef IDRIS_FFI
import Foreign.LibFFI
import Foreign.C.String
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr
#endif
import System.IO
#ifndef IDRIS_FFI
execute :: Term -> Idris Term
execute tm = fail "libffi not supported, rebuild Idris with -f FFI"
#else
-- else is rest of file
readMay :: (Read a) => String -> Maybe a
readMay s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show
data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad
, binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT
}
data ExecVal = EP NameType Name ExecVal
| EV Int
| EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal)
| EApp ExecVal ExecVal
| EType UExp
| EUType Universe
| EErased
| EConstant Const
| forall a. EPtr (Ptr a)
| EThunk Context ExecEnv Term
| EHandle Handle
instance Show ExecVal where
show (EP _ n _) = show n
show (EV i) = "!!V" ++ show i ++ "!!"
show (EBind n b body) = "EBind " ++ show b ++ " <<fn>>"
show (EApp e1 e2) = show e1 ++ " (" ++ show e2 ++ ")"
show (EType _) = "Type"
show (EUType _) = "UType"
show EErased = "[__]"
show (EConstant c) = show c
show (EPtr p) = "<<ptr " ++ show p ++ ">>"
show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>"
show (EHandle h) = "<<handle " ++ show h ++ ">>"
toTT :: ExecVal -> Exec Term
toTT (EP nt n ty) = (P nt n) <$> (toTT ty)
toTT (EV i) = return $ V i
toTT (EBind n b body) = do n' <- newN n
body' <- body $ EP Bound n' EErased
b' <- fixBinder b
Bind n' b' <$> toTT body'
where fixBinder (Lam t) = Lam <$> toTT t
fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k
fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2
fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2
fixBinder (Hole t) = Hole <$> toTT t
fixBinder (GHole i ns t) = GHole i ns <$> toTT t
fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2
fixBinder (PVar t) = PVar <$> toTT t
fixBinder (PVTy t) = PVTy <$> toTT t
newN n = do (ExecState hs ns) <- lift get
let n' = uniqueName n ns
lift (put (ExecState hs (n':ns)))
return n'
toTT (EApp e1 e2) = do e1' <- toTT e1
e2' <- toTT e2
return $ App Complete e1' e2'
toTT (EType u) = return $ TType u
toTT (EUType u) = return $ UType u
toTT EErased = return Erased
toTT (EConstant c) = return (Constant c)
toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
return $ normalise ctxt env' tm
where toBinder (n, v) = do v' <- toTT v
return (n, Let Erased v')
toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution."
toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution."
unApplyV :: ExecVal -> (ExecVal, [ExecVal])
unApplyV tm = ua [] tm
where ua args (EApp f a) = ua (a:args) f
ua args t = (t, args)
mkEApp :: ExecVal -> [ExecVal] -> ExecVal
mkEApp f [] = f
mkEApp f (a:args) = mkEApp (EApp f a) args
initState :: Idris ExecState
initState = do ist <- getIState
return $ ExecState (idris_dynamic_libs ist) []
type Exec = ExceptT Err (StateT ExecState IO)
runExec :: Exec a -> ExecState -> IO (Either Err a)
runExec ex st = fst <$> runStateT (runExceptT ex) st
getExecState :: Exec ExecState
getExecState = lift get
putExecState :: ExecState -> Exec ()
putExecState = lift . put
execFail :: Err -> Exec a
execFail = throwE
execIO :: IO a -> Exec a
execIO = lift . lift
execute :: Term -> Idris Term
execute tm = do est <- initState
ctxt <- getContext
res <- lift . lift . flip runExec est $
do res <- doExec [] ctxt tm
toTT res
case res of
Left err -> ierror err
Right tm' -> return tm'
ioWrap :: ExecVal -> ExecVal
ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm]
ioUnit :: ExecVal
ioUnit = ioWrap (EP Ref unitCon EErased)
type ExecEnv = [(Name, ExecVal)]
doExec :: ExecEnv -> Context -> Term -> Exec ExecVal
doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v
doExec env ctxt p@(P Ref n ty) =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> doExec env ctxt tm
[TyDecl _ _] -> return (EP Ref n EErased) -- abstract def
[Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
doExec env ctxt tm
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased)
[] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions."
other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n
| otherwise -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n
doExec env ctxt p@(P Bound n ty) =
case lookup n env of
Nothing -> execFail . Msg $ "not found"
Just tm -> return tm
doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased)
doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased)
doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))
| otherwise = execFail . Msg $ "env too small"
doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v
doExec ((n, v'):env) ctxt body
doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined
doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)
return $
EBind n b' (\arg -> doExec ((n, arg):env) ctxt body)
doExec env ctxt a@(App _ _ _) =
do let (f, args) = unApply a
f' <- doExec env ctxt f
args' <- case f' of
(EP _ d _) | d == delay ->
case args of
[t,a,tm] -> do t' <- doExec env ctxt t
a' <- doExec env ctxt a
return [t', a', EThunk ctxt env tm]
_ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate
fun' -> do mapM (doExec env ctxt) args
execApp env ctxt f' args'
doExec env ctxt (Constant c) = return (EConstant c)
doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
doExec env ctxt ((x:xs) !! i)
doExec env ctxt Erased = return EErased
doExec env ctxt Impossible = fail "Tried to execute an impossible case"
doExec env ctxt (TType u) = return (EType u)
doExec env ctxt (UType u) = return (EUType u)
execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal
execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls
execApp env ctxt (EP _ f _) (t:a:delayed:rest)
| f == force
, (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed =
do tm' <- doExec tmEnv tmCtxt tm
execApp env ctxt tm' rest
execApp env ctxt (EP _ fp _) (ty:action:rest)
| fp == upio,
(prim__IO, [_, v]) <- unApplyV action
= execApp env ctxt v rest
execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest)
| fp == piobind,
(prim__IO, [_, v']) <- unApplyV v =
do res <- execApp env ctxt k [v']
execApp env ctxt res rest
execApp env ctxt con@(EP _ fp _) args@(tp:v:rest)
| fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest
-- Special cases arising from not having access to the C RTS in the interpreter
execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args')
| fp == mkfprim,
(ty : fn : w : rest) <- reverse args' =
execForeign env ctxt getArity ty fn rest (mkEApp f args)
where getArity = case unEList xs of
Just as -> length as
_ -> 0
execApp env ctxt c@(EP (DCon _ arity _) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt c@(EP (TCon _ arity) n _) args =
do let args' = take arity args
let restArgs = drop arity args
execApp env ctxt (mkEApp c args') restArgs
execApp env ctxt f@(EP _ n _) args
| Just (res, rest) <- getOp n args = do r <- res
execApp env ctxt r rest
execApp env ctxt f@(EP _ n _) args =
do let val = lookupDef n ctxt
case val of
[Function _ tm] -> fail "should already have been eval'd"
[TyDecl nt ty] -> return $ mkEApp f args
[Operator tp arity op] ->
if length args >= arity
then let args' = take arity args in
case getOp n args' of
Just (res, []) -> do r <- res
execApp env ctxt r (drop arity args)
_ -> return (mkEApp f args)
else return (mkEApp f args)
[CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
do rhs <- doExec env ctxt tm
execApp env ctxt rhs args
[CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] ->
do res <- execCase env ctxt ns sc args
return $ fromMaybe (mkEApp f args) res
thing -> return $ mkEApp f args
execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg
let (f', as) = unApplyV ret
execApp env ctxt f' (as ++ args)
execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2)
execApp env ctxt f args = return (mkEApp f args)
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs
= case str of
EConstant (Str arg) -> do execIO (putStr arg)
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putStr should be a constant string, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs
= case ch of
EConstant (Ch c) -> do execIO (putChar c)
execApp env ctxt ioUnit (drop arity xs)
EConstant (I i) -> do execIO (putChar (toEnum i))
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to putchar should be a constant character, but it was " ++
show str ++
". Are all cases covered?"
| Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do contents <- execIO $ hGetLine h
execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs)
_ -> execFail . Msg $
"The argument to idris_readStr should be a handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs
= do -- The C API returns an Int which Idris library code
-- converts; thus, we must make an int here.
ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar
execApp env ctxt ch xs
| Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs
= do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime
| Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs
= case (fileStr, modeStr) of
(EConstant (Str f), EConstant (Str mode)) ->
do f <- execIO $
catch (do let m = case mode of
"r" -> Right ReadMode
"w" -> Right WriteMode
"a" -> Right AppendMode
"rw" -> Right ReadWriteMode
"wr" -> Right ReadWriteMode
"r+" -> Right ReadWriteMode
_ -> Left ("Invalid mode for " ++ f ++ ": " ++ mode)
case fmap (openFile f) m of
Right h -> do h' <- h
hSetBinaryMode h' True
return $ Right (ioWrap (EHandle h'), drop arity xs)
Left err -> return $ Left err)
(\e -> let _ = ( e::SomeException)
in return $ Right (ioWrap (EPtr nullPtr), drop arity xs))
case f of
Left err -> execFail . Msg $ err
Right (res, rest) -> execApp env ctxt res rest
_ -> execFail . Msg $
"The arguments to fileOpen should be constant strings, but they were " ++
show fileStr ++ " and " ++ show modeStr ++
". Are all cases covered?"
| Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do eofp <- execIO $ hIsEOF h
let res = ioWrap (EConstant (I $ if eofp then 1 else 0))
execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to fileEOF should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "fileError" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
-- errors handled differently in Haskell than in C, so if
-- there's been an error we'll have had an exception already.
-- Therefore, assume we're okay.
EHandle h -> do let res = ioWrap (EConstant (I 0))
execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to fileError should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs
= case handle of
EHandle h -> do execIO $ hClose h
execApp env ctxt ioUnit (drop arity xs)
_ -> execFail . Msg $
"The argument to fileClose should be a file handle, but it was " ++
show handle ++
". Are all cases covered?"
| Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs
= case ptr of
EPtr p -> let res = ioWrap . EConstant . I $
if p == nullPtr then 1 else 0
in execApp env ctxt res (drop arity xs)
-- Handles will be checked as null pointers sometimes - but if we got a
-- real Handle, then it's valid, so just return 1.
EHandle h -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
-- A foreign-returned char* has to be tested for NULL sometimes
EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
_ -> execFail . Msg $
"The argument to isNull should be a pointer or file handle or string, but it was " ++
show ptr ++
". Are all cases covered?"
-- Right now, there's no way to send command-line arguments to the executor,
-- so just return 0.
execForeign env ctxt arity ty fn xs onfail
| Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs
= let res = ioWrap . EConstant . I $ 0
in execApp env ctxt res (drop arity xs)
execForeign env ctxt arity ty fn xs onfail
= case foreignFromTT arity ty fn xs of
Just ffun@(FFun f argTs retT) | length xs >= arity ->
do let (args', xs') = (take arity xs, -- foreign args
drop arity xs) -- rest
res <- call ffun (map snd argTs)
case res of
Nothing -> fail $ "Could not call foreign function \"" ++ f ++
"\" with args " ++ show (map snd argTs)
Just r -> return (mkEApp r xs')
_ -> return onfail
splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits
= Just (toFDesc l, r)
splitArg _ = Nothing
toFDesc tm
| (EP _ n _, []) <- unApplyV tm = FCon (deNS n)
| (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as)
toFDesc _ = FUnknown
deNS (NS n _) = n
deNS n = n
prf = sUN "prim__readFile"
pwf = sUN "prim__writeFile"
prs = sUN "prim__readString"
pws = sUN "prim__writeString"
pbm = sUN "prim__believe_me"
pstdin = sUN "prim__stdin"
pstdout = sUN "prim__stdout"
mkfprim = sUN "mkForeignPrim"
pioret = sUN "prim_io_return"
piobind = sUN "prim_io_bind"
upio = sUN "unsafePerformPrimIO"
delay = sUN "Delay"
force = sUN "Force"
-- | Look up primitive operations in the global table and transform
-- them into ExecVal functions
getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal])
getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs)
getOp fn (_ : EConstant (Str n) : xs)
| fn == pws =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_:xs)
| fn == prs =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs)
| fn == pwf && fn' == pstdout =
Just (do execIO $ putStr n
return (EConstant (I 0)), xs)
getOp fn (_ : EP _ fn' _ : xs)
| fn == prf && fn' == pstdin =
Just (do line <- execIO getLine
return (EConstant (Str line)), xs)
getOp fn (_ : EHandle h : EConstant (Str n) : xs)
| fn == pwf =
Just (do execIO $ hPutStr h n
return (EConstant (I 0)), xs)
getOp fn (_ : EHandle h : xs)
| fn == prf =
Just (do contents <- execIO $ hGetLine h
return (EConstant (Str (contents ++ "\n"))), xs)
getOp fn (_ : arg : xs)
| fn == prf =
Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs)
getOp n args = do (arity, prim) <- getPrim n primitives
if (length args >= arity)
then do res <- applyPrim prim (take arity args)
Just (res, drop arity args)
else Nothing
where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal)
getPrim n [] = Nothing
getPrim n ((Prim pn _ arity def _ _) : prims)
| n == pn = Just (arity, execPrim def)
| otherwise = getPrim n prims
execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal
execPrim f args = EConstant <$> (mapM getConst args >>= f)
getConst (EConstant c) = Just c
getConst _ = Nothing
applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal)
applyPrim fn args = return <$> fn args
-- | Overall wrapper for case tree execution. If there are enough arguments, it takes them,
-- evaluates them, then begins the checks for matching cases.
execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal)
execCase env ctxt ns sc args =
let arity = length ns in
if arity <= length args
then do let amap = zip ns args
-- trace ("Case " ++ show sc ++ "\n in " ++ show amap ++"\n in env " ++ show env ++ "\n\n" ) $ return ()
caseRes <- execCase' env ctxt amap sc
case caseRes of
Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args)
Nothing -> return Nothing
else return Nothing
-- | Take bindings and a case tree and examines them, executing the matching case if possible.
execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal)
execCase' env ctxt amap (UnmatchedCase _) = return Nothing
execCase' env ctxt amap (STerm tm) =
Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm
execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap =
case chooseAlt tm alts of
Just (newCase, newBindings) ->
let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in
execCase' env ctxt amap' newCase
Nothing -> return Nothing
execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec " ++ show cse
chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)])
chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, [])
| otherwise = Nothing
where -- Default cases should only work on applications of constructors or on constants
ok (EApp f x) = ok f
ok (EP Bound _ _) = False
ok (EP Ref _ _) = False
ok _ = True
chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, [])
chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm
, cn == n = Just (sc, zip ns args)
| otherwise = chooseAlt tm alts
chooseAlt tm (_:alts) = chooseAlt tm alts
chooseAlt _ [] = Nothing
data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show
toFType :: FDesc -> FType
toFType (FCon c)
| c == sUN "C_Str" = FString
| c == sUN "C_Float" = FArith ATFloat
| c == sUN "C_Ptr" = FPtr
| c == sUN "C_MPtr" = FManagedPtr
| c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "C_IntT" = FArith (toAType ity)
where toAType (FCon i)
| i == sUN "C_IntChar" = ATInt ITChar
| i == sUN "C_IntNative" = ATInt ITNative
| i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
| i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
| i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
| i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
toAType t = error (show t ++ " not defined in toAType")
toFType (FApp c [_])
| c == sUN "C_Any" = FAny
toFType t = error (show t ++ " not defined in toFType")
call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal)
call (FFun name argTypes retType) args =
do fn <- findForeign name
maybe (return Nothing)
(\f -> Just . ioWrap <$> call' f args (toFType retType)) fn
where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal
call' (Fun _ h) args (FArith (ATInt ITNative)) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (I (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (B8 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do
res <- execIO $ callFFI h retCWchar (prepArgs args)
return (EConstant (B16 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do
res <- execIO $ callFFI h retCInt (prepArgs args)
return (EConstant (B32 (fromIntegral res)))
call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do
res <- execIO $ callFFI h retCLong (prepArgs args)
return (EConstant (B64 (fromIntegral res)))
call' (Fun _ h) args (FArith ATFloat) = do
res <- execIO $ callFFI h retCDouble (prepArgs args)
return (EConstant (Fl (realToFrac res)))
call' (Fun _ h) args (FArith (ATInt ITChar)) = do
res <- execIO $ callFFI h retCChar (prepArgs args)
return (EConstant (Ch (castCCharToChar res)))
call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args)
if res == nullPtr
then return (EPtr res)
else do hStr <- execIO $ peekCString res
return (EConstant (Str hStr))
call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args))
call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args)
return $ EP Ref unitCon EErased
call' _ _ _ = fail "the impossible happened in call' in Execute.hs"
prepArgs = map prepArg
prepArg (EConstant (I i)) = argCInt (fromIntegral i)
prepArg (EConstant (B8 i)) = argCChar (fromIntegral i)
prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i)
prepArg (EConstant (B32 i)) = argCInt (fromIntegral i)
prepArg (EConstant (B64 i)) = argCLong (fromIntegral i)
prepArg (EConstant (Fl f)) = argCDouble (realToFrac f)
prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars
-- Issue #1720 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1720
prepArg (EConstant (Str s)) = argString s
prepArg (EPtr p) = argPtr p
prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined
foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign
foreignFromTT arity ty (EConstant (Str name)) args
= do argFTyVals <- mapM splitArg (take arity args)
return $ FFun name argFTyVals (toFDesc ty)
foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing
getFTy :: ExecVal -> Maybe FType
getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))
| fi == txt "FIntT" =
case str intTy of
"ITNative" -> Just (FArith (ATInt ITNative))
"ITChar" -> Just (FArith (ATInt ITChar))
"IT8" -> Just (FArith (ATInt (ITFixed IT8)))
"IT16" -> Just (FArith (ATInt (ITFixed IT16)))
"IT32" -> Just (FArith (ATInt (ITFixed IT32)))
"IT64" -> Just (FArith (ATInt (ITFixed IT64)))
_ -> Nothing
getFTy (EP _ (UN t) _) =
case str t of
"FFloat" -> Just (FArith ATFloat)
"FString" -> Just FString
"FPtr" -> Just FPtr
"FUnit" -> Just FUnit
_ -> Nothing
getFTy _ = Nothing
unEList :: ExecVal -> Maybe [ExecVal]
unEList tm = case unApplyV tm of
(nil, [_]) -> Just []
(cons, ([_, x, xs])) ->
do rest <- unEList xs
return $ x:rest
(f, args) -> Nothing
toConst :: Term -> Maybe Const
toConst (Constant c) = Just c
toConst _ = Nothing
mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f [] = return []
mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs
maybe rest (:rest) <$> f x
findForeign :: String -> Exec (Maybe ForeignFun)
findForeign fn = do est <- getExecState
let libs = exec_dynamic_libs est
fns <- mapMaybeM getFn libs
case fns of
[f] -> return (Just f)
[] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found"
return Nothing
fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++
show (length fs) ++ " occurrences."
return Nothing
where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing)
#endif
| TimRichter/Idris-dev | src/Idris/Core/Execute.hs | bsd-3-clause | 30,115 | 0 | 6 | 11,119 | 259 | 166 | 93 | 28 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Network.Wai.Middleware.RequestLogger.JSON (formatAsJSON) where
import qualified Blaze.ByteString.Builder as BB
import Data.Aeson
import Data.CaseInsensitive (original)
import Data.Monoid ((<>))
import qualified Data.ByteString.Char8 as S8
import Data.IP
import qualified Data.Text as T
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import Data.Time (NominalDiffTime)
import Data.Word (Word32)
import Network.HTTP.Types as H
import Network.Socket (SockAddr (..), PortNumber)
import Network.Wai
import Network.Wai.Middleware.RequestLogger
import System.Log.FastLogger (toLogStr)
import Text.Printf (printf)
formatAsJSON :: OutputFormatterWithDetails
formatAsJSON date req status responseSize duration reqBody response =
toLogStr (encode $
object
[ "request" .= requestToJSON duration req reqBody
, "response" .=
object
[ "status" .= statusCode status
, "size" .= responseSize
, "body" .=
if statusCode status >= 400
then Just . decodeUtf8 . BB.toByteString $ response
else Nothing
]
, "time" .= decodeUtf8 date
]) <> "\n"
word32ToHostAddress :: Word32 -> Text
word32ToHostAddress = T.intercalate "." . map (T.pack . show) . fromIPv4 . fromHostAddress
readAsDouble :: String -> Double
readAsDouble = read
requestToJSON :: NominalDiffTime -> Request -> [S8.ByteString] -> Value
requestToJSON duration req reqBody =
object
[ "method" .= decodeUtf8 (requestMethod req)
, "path" .= decodeUtf8 (rawPathInfo req)
, "queryString" .= map queryItemToJSON (queryString req)
, "durationMs" .= (readAsDouble . printf "%.2f" . rationalToDouble $ toRational duration * 1000)
, "size" .= requestBodyLengthToJSON (requestBodyLength req)
, "body" .= decodeUtf8 (S8.concat reqBody)
, "remoteHost" .= sockToJSON (remoteHost req)
, "httpVersion" .= httpVersionToJSON (httpVersion req)
, "headers" .= requestHeadersToJSON (requestHeaders req)
]
where
rationalToDouble :: Rational -> Double
rationalToDouble = fromRational
sockToJSON :: SockAddr -> Value
sockToJSON (SockAddrInet pn ha) =
object
[ "port" .= portToJSON pn
, "hostAddress" .= word32ToHostAddress ha
]
sockToJSON (SockAddrInet6 pn _ ha _) =
object
[ "port" .= portToJSON pn
, "hostAddress" .= ha
]
sockToJSON (SockAddrUnix sock) =
object [ "unix" .= sock ]
sockToJSON (SockAddrCan i) =
object [ "can" .= i ]
queryItemToJSON :: QueryItem -> Value
queryItemToJSON (name, mValue) = toJSON (decodeUtf8 name, fmap decodeUtf8 mValue)
requestHeadersToJSON :: RequestHeaders -> Value
requestHeadersToJSON = toJSON . map hToJ where
-- Redact cookies
hToJ ("Cookie", _) = toJSON ("Cookie" :: Text, "-RDCT-" :: Text)
hToJ hd = headerToJSON hd
headerToJSON :: Header -> Value
headerToJSON (headerName, header) = toJSON (decodeUtf8 . original $ headerName, decodeUtf8 header)
portToJSON :: PortNumber -> Value
portToJSON = toJSON . toInteger
httpVersionToJSON :: HttpVersion -> Value
httpVersionToJSON (HttpVersion major minor) = String $ T.pack (show major) <> "." <> T.pack (show minor)
requestBodyLengthToJSON :: RequestBodyLength -> Value
requestBodyLengthToJSON ChunkedBody = String "Unknown"
requestBodyLengthToJSON (KnownLength l) = toJSON l
| rgrinberg/wai | wai-extra/Network/Wai/Middleware/RequestLogger/JSON.hs | mit | 3,346 | 0 | 18 | 625 | 972 | 524 | 448 | 80 | 2 |
-- Copyright (c) 2014-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is distributed under the terms of a BSD license,
-- found in the LICENSE file. An additional grant of patent rights can
-- be found in the PATENTS file.
{-# LANGUAGE CPP #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A cache mapping data requests to their results.
module Haxl.Core.DataCache
( DataCache
, empty
, insert
, lookup
, showCache
) where
import Data.HashMap.Strict (HashMap)
import Data.Hashable
import Prelude hiding (lookup)
import Unsafe.Coerce
import qualified Data.HashMap.Strict as HashMap
import Data.Typeable.Internal
import Data.Maybe
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative hiding (empty)
#endif
import Control.Exception
import Haxl.Core.Types
-- | The 'DataCache' maps things of type @f a@ to @'ResultVar' a@, for
-- any @f@ and @a@ provided @f a@ is an instance of 'Typeable'. In
-- practice @f a@ will be a request type parameterised by its result.
--
-- See the definition of 'ResultVar' for more details.
newtype DataCache res = DataCache (HashMap TypeRep (SubCache res))
-- | The implementation is a two-level map: the outer level maps the
-- types of requests to 'SubCache', which maps actual requests to their
-- results. So each 'SubCache' contains requests of the same type.
-- This works well because we only have to store the dictionaries for
-- 'Hashable' and 'Eq' once per request type.
data SubCache res =
forall req a . (Hashable (req a), Eq (req a), Show (req a), Show a) =>
SubCache ! (HashMap (req a) (res a))
-- NB. the inner HashMap is strict, to avoid building up
-- a chain of thunks during repeated insertions.
-- | A new, empty 'DataCache'.
empty :: DataCache res
empty = DataCache HashMap.empty
-- | Inserts a request-result pair into the 'DataCache'.
insert
:: (Hashable (req a), Typeable (req a), Eq (req a), Show (req a), Show a)
=> req a
-- ^ Request
-> res a
-- ^ Result
-> DataCache res
-> DataCache res
insert req result (DataCache m) =
DataCache $
HashMap.insertWith fn (typeOf req)
(SubCache (HashMap.singleton req result)) m
where
fn (SubCache new) (SubCache old) =
SubCache (unsafeCoerce new `HashMap.union` old)
-- | Looks up the cached result of a request.
lookup
:: Typeable (req a)
=> req a
-- ^ Request
-> DataCache res
-> Maybe (res a)
lookup req (DataCache m) =
case HashMap.lookup (typeOf req) m of
Nothing -> Nothing
Just (SubCache sc) ->
unsafeCoerce (HashMap.lookup (unsafeCoerce req) sc)
-- | Dumps the contents of the cache, with requests and responses
-- converted to 'String's using 'show'. The entries are grouped by
-- 'TypeRep'.
--
showCache
:: DataCache ResultVar
-> IO [(TypeRep, [(String, Either SomeException String)])]
showCache (DataCache cache) = mapM goSubCache (HashMap.toList cache)
where
goSubCache
:: (TypeRep,SubCache ResultVar)
-> IO (TypeRep,[(String, Either SomeException String)])
goSubCache (ty, SubCache hmap) = do
elems <- catMaybes <$> mapM go (HashMap.toList hmap)
return (ty, elems)
go :: (Show (req a), Show a)
=> (req a, ResultVar a)
-> IO (Maybe (String, Either SomeException String))
go (req, rvar) = do
maybe_r <- tryReadResult rvar
case maybe_r of
Nothing -> return Nothing
Just (Left e) -> return (Just (show req, Left e))
Just (Right result) -> return (Just (show req, Right (show result)))
| hiteshsuthar/Haxl | Haxl/Core/DataCache.hs | bsd-3-clause | 3,612 | 5 | 18 | 778 | 876 | 477 | 399 | 69 | 3 |
module ConstructorIn1 where
data MyBTree a
= Empty | T a (MyBTree a) (MyBTree a) deriving Show
buildtree :: Ord a => [a] -> MyBTree a
buildtree [] = Empty
buildtree ((x : xs)) = insert x (buildtree xs)
insert :: Ord a => a -> (MyBTree a) -> MyBTree a
insert val Empty = T val Empty Empty
insert val tree@(T tval left right)
| val > tval = T tval left (insert val right)
| otherwise = T tval (insert val left) right
main :: MyBTree Int
main = buildtree [3, 1, 2]
| mpickering/HaRe | old/testing/renaming/ConstructorIn1_AstOut.hs | bsd-3-clause | 487 | 0 | 9 | 120 | 240 | 122 | 118 | 13 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -O #-}
module T12944 () where
class AdditiveGroup v where
(^+^) :: v -> v -> v
negateV :: v -> v
(^-^) :: v -> v -> v
v ^-^ v' = v ^+^ negateV v'
class AdditiveGroup v => VectorSpace v where
type Scalar v :: *
(*^) :: Scalar v -> v -> v
data Poly1 a = Poly1 a a
data IntOfLog poly a = IntOfLog !a !(poly a)
instance Num a => AdditiveGroup (Poly1 a) where
{-# INLINE (^+^) #-}
{-# INLINE negateV #-}
Poly1 a b ^+^ Poly1 a' b' = Poly1 (a + a') (b + b')
negateV (Poly1 a b) = Poly1 (negate a) (negate b)
instance (AdditiveGroup (poly a), Num a) => AdditiveGroup (IntOfLog poly a) where
{-# INLINE (^+^) #-}
{-# INLINE negateV #-}
IntOfLog k p ^+^ IntOfLog k' p' = IntOfLog (k + k') (p ^+^ p')
negateV (IntOfLog k p) = IntOfLog (negate k) (negateV p)
{-# SPECIALISE instance Num a => AdditiveGroup (IntOfLog Poly1 a) #-}
-- This pragmas casued the crash
instance (VectorSpace (poly a), Scalar (poly a) ~ a, Num a) => VectorSpace (IntOfLog poly a) where
type Scalar (IntOfLog poly a) = a
s *^ IntOfLog k p = IntOfLog (s * k) (s *^ p)
| ezyang/ghc | testsuite/tests/deSugar/should_compile/T12944.hs | bsd-3-clause | 1,147 | 0 | 10 | 291 | 465 | 240 | 225 | -1 | -1 |
module Complex(Complex((:+)), realPart, imagPart, conjugate, mkPolar,
cis, polar, magnitude, phase) where
--import Prelude
infix 6 :+
data (RealFloat a) => Complex a = !a :+ !a deriving (Eq,Read,Show)
realPart, imagPart :: (RealFloat a) => Complex a -> a
realPart (x:+y) = x
imagPart (x:+y) = y
conjugate :: (RealFloat a) => Complex a -> Complex a
conjugate (x:+y) = x :+ (-y)
mkPolar :: (RealFloat a) => a -> a -> Complex a
mkPolar r theta = r * cos theta :+ r * sin theta
cis :: (RealFloat a) => a -> Complex a
cis theta = cos theta :+ sin theta
polar :: (RealFloat a) => Complex a -> (a,a)
polar z = (magnitude z, phase z)
magnitude :: (RealFloat a) => Complex a -> a
magnitude (x:+y) = scaleFloat k
(sqrt ((scaleFloat mk x)^(2::Int) + (scaleFloat mk y)^(2::Int)))
where k = max (exponent x) (exponent y)
mk = - k
phase :: (RealFloat a) => Complex a -> a
phase (0 :+ 0) = 0
phase (x :+ y) = atan2 y x
instance (RealFloat a) => Num (Complex a) where
(x:+y) + (x':+y') = (x+x') :+ (y+y')
(x:+y) - (x':+y') = (x-x') :+ (y-y')
(x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
negate (x:+y) = negate x :+ negate y
abs z = magnitude z :+ 0
signum 0 = 0
signum z@(x:+y) = (x/r) :+ (y/r) where r = magnitude z
fromInteger n = fromInteger n :+ 0
instance (RealFloat a) => Fractional (Complex a) where
(x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
where x'' = scaleFloat k x'
y'' = scaleFloat k y'
k = - max (exponent x') (exponent y')
d = x'*x'' + y'*y''
fromRational a = fromRational a :+ 0
instance (RealFloat a) => Floating (Complex a) where
pi = pi :+ 0
exp (x:+y) = expx * cos y :+ expx * sin y
where expx = exp x
log z = log (magnitude z) :+ phase z
sqrt 0 = 0
sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
where (u,v) = if x < 0 then (v',u') else (u',v')
v' = abs y / (u'*2)
u' = sqrt ((magnitude z + abs x) / 2)
sin (x:+y) = sin x * cosh y :+ cos x * sinh y
cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
where sinx = sin x
cosx = cos x
sinhy = sinh y
coshy = cosh y
sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
where siny = sin y
cosy = cos y
sinhx = sinh x
coshx = cosh x
asin z@(x:+y) = y':+(-x')
where (x':+y') = log (((-y):+x) + sqrt (1 - z*z))
acos z@(x:+y) = y'':+(-x'')
where (x'':+y'') = log (z + ((-y'):+x'))
(x':+y') = sqrt (1 - z*z)
atan z@(x:+y) = y':+(-x')
where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = log ((1+z) / sqrt (1-z*z))
| forste/haReFork | tools/base/tests/HaskellLibraries/Complex.hs | bsd-3-clause | 3,383 | 4 | 14 | 1,293 | 1,856 | 974 | 882 | 79 | 1 |
{-# LANGUAGE GADTs #-}
-- It's not clear whether this one should succeed or fail,
-- Arguably it should succeed because the type refinement on
-- T1 should make (y::Int). Currently, though, it fails.
module ShouldFail where
data T a where
T1 :: Int -> T Int
f :: (T a, a) -> Int
f ~(T1 x, y) = x+y
| olsner/ghc | testsuite/tests/gadt/lazypatok.hs | bsd-3-clause | 306 | 0 | 8 | 68 | 65 | 38 | 27 | 6 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLBaseFontElement
(js_setColor, setColor, js_getColor, getColor, js_setFace, setFace,
js_getFace, getFace, js_setSize, setSize, js_getSize, getSize,
HTMLBaseFontElement, castToHTMLBaseFontElement,
gTypeHTMLBaseFontElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"color\"] = $2;" js_setColor
:: HTMLBaseFontElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.color Mozilla HTMLBaseFontElement.color documentation>
setColor ::
(MonadIO m, ToJSString val) => HTMLBaseFontElement -> val -> m ()
setColor self val = liftIO (js_setColor (self) (toJSString val))
foreign import javascript unsafe "$1[\"color\"]" js_getColor ::
HTMLBaseFontElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.color Mozilla HTMLBaseFontElement.color documentation>
getColor ::
(MonadIO m, FromJSString result) => HTMLBaseFontElement -> m result
getColor self = liftIO (fromJSString <$> (js_getColor (self)))
foreign import javascript unsafe "$1[\"face\"] = $2;" js_setFace ::
HTMLBaseFontElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.face Mozilla HTMLBaseFontElement.face documentation>
setFace ::
(MonadIO m, ToJSString val) => HTMLBaseFontElement -> val -> m ()
setFace self val = liftIO (js_setFace (self) (toJSString val))
foreign import javascript unsafe "$1[\"face\"]" js_getFace ::
HTMLBaseFontElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.face Mozilla HTMLBaseFontElement.face documentation>
getFace ::
(MonadIO m, FromJSString result) => HTMLBaseFontElement -> m result
getFace self = liftIO (fromJSString <$> (js_getFace (self)))
foreign import javascript unsafe "$1[\"size\"] = $2;" js_setSize ::
HTMLBaseFontElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.size Mozilla HTMLBaseFontElement.size documentation>
setSize :: (MonadIO m) => HTMLBaseFontElement -> Int -> m ()
setSize self val = liftIO (js_setSize (self) val)
foreign import javascript unsafe "$1[\"size\"]" js_getSize ::
HTMLBaseFontElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseFontElement.size Mozilla HTMLBaseFontElement.size documentation>
getSize :: (MonadIO m) => HTMLBaseFontElement -> m Int
getSize self = liftIO (js_getSize (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLBaseFontElement.hs | mit | 3,387 | 42 | 10 | 465 | 800 | 461 | 339 | 48 | 1 |
-- Word a9n (abbreviation)
-- http://www.codewars.com/kata/5375f921003bf62192000746/
module A9n where
import Data.Char (isLetter)
import Data.List (groupBy)
import Data.Function (on)
abbreviate :: String -> String
abbreviate = concatMap (\w -> if isLetter . head $ w then f w else w) . groupBy ((==) `on` isLetter)
where f x | length x < 4 = x
| otherwise = [head x] ++ show (length x -2) ++ [last x]
| gafiatulin/codewars | src/6 kyu/A9n.hs | mit | 422 | 0 | 13 | 88 | 163 | 88 | 75 | 8 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid
import Web.Scotty
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.Encoding (decodeUtf8)
import qualified Views.Index
import Text.Blaze.Html.Renderer.Text
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.Static
blaze = html . renderHtml
main = scotty 9001 $ do
-- Log requests
middleware logStdoutDev
-- Set up static folder
middleware $ staticPolicy (noDots >-> addBase "static")
get "/" $ do
blaze Views.Index.render
matchAny "api/:width/:height" $ do
width <- param "width"
height <- param "height"
html $ mconcat ["Width: ", width, " Height: ", height]
| Pholey/place-puppy | Placepuppy/Main.hs | mit | 680 | 0 | 13 | 115 | 181 | 98 | 83 | 19 | 1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable #-}
import System.Console.CmdArgs
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import Data.NGH.Alignments
import Data.NGH.Formats.Sam
import Data.Void
import Data.Conduit
import Data.Maybe
import Data.List (isSuffixOf)
import Data.Conduit.Zlib (ungzip)
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Binary as CB -- bytes
import Data.NGH.Trim
import Control.Monad
import Data.IORef
import Utils
data SamCmd = SamCmd
{ input :: String
, output :: String
} deriving (Eq, Show, Data, Typeable)
samcmds = SamCmd
{ input = "-" &= argPos 0 &= typ "Input-file"
, output = "-" &= argPos 1 &= typ "Output-file"
} &=
verbosity &=
summary sumtext &=
details ["Filter non-match queries from SAM files"]
where sumtext = "sam-filter v0.1 (C) Luis Pedro Coelho 2012"
main :: IO ()
main = do
SamCmd finput foutput <- cmdArgs samcmds
v <- getVerbosity
let q = v == Quiet
total <- newIORef (0.0 :: Double)
good <- newIORef (0.0 :: Double)
_ <- runResourceT $
readerC finput
=$= mayunzip finput
=$= CB.lines
=$= CL.filter ((/='@').S8.head)
=$= counter total
=$= CL.filter (\ell -> (isAligned $ readSamLine $ L.fromChunks [ell]))
=$= counter good
=$= CL.map (\s -> S.concat [s,S8.pack "\n"])
$$ writerC foutput
t <- readIORef total
g <- readIORef good
unless q
(putStrLn $ concat ["Processed ", show $ round t, " lines."])
unless q
(putStrLn $ concat ["There were matches in ", show $ round g, " (", take 4 $ show (100.0*g/t), "%) of them."])
| luispedro/NGH | bin/sam-filter.hs | mit | 1,832 | 1 | 18 | 500 | 572 | 308 | 264 | 53 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Data structures needed for interfacing with the Websocket
-- Gateway
module Network.Discord.Types.Gateway where
import Control.Monad (mzero)
import System.Info
import Data.Aeson
import Data.Aeson.Types
import Network.WebSockets
import Network.Discord.Types.Prelude
-- |Represents all sorts of things that we can send to Discord.
data Payload = Dispatch
Object
Integer
String
| Heartbeat
Integer
| Identify
Auth
Bool
Integer
(Int, Int)
| StatusUpdate
(Maybe Integer)
(Maybe String)
| VoiceStatusUpdate
{-# UNPACK #-} !Snowflake
!(Maybe Snowflake)
Bool
Bool
| Resume
String
String
Integer
| Reconnect
| RequestGuildMembers
{-# UNPACK #-} !Snowflake
String
Integer
| InvalidSession
| Hello
Int
| HeartbeatAck
| ParseError String
deriving Show
instance FromJSON Payload where
parseJSON = withObject "payload" $ \o -> do
op <- o .: "op" :: Parser Int
case op of
0 -> Dispatch <$> o .: "d" <*> o .: "s" <*> o .: "t"
1 -> Heartbeat <$> o .: "d"
7 -> return Reconnect
9 -> return InvalidSession
10 -> (\od -> Hello <$> od .: "heartbeat_interval") =<< o .: "d"
11 -> return HeartbeatAck
_ -> mzero
instance ToJSON Payload where
toJSON (Heartbeat i) = object [ "op" .= (1 :: Int), "d" .= i ]
toJSON (Identify token compress large shard) = object [
"op" .= (2 :: Int)
, "d" .= object [
"token" .= authToken token
, "properties" .= object [
"$os" .= os
, "$browser" .= ("discord.hs" :: String)
, "$device" .= ("discord.hs" :: String)
, "$referrer" .= ("" :: String)
, "$referring_domain" .= ("" :: String)
]
, "compress" .= compress
, "large_threshold" .= large
, "shard" .= shard
]
]
toJSON (StatusUpdate idle game) = object [
"op" .= (3 :: Int)
, "d" .= object [
"idle_since" .= idle
, "game" .= object [
"name" .= game
]
]
]
toJSON (VoiceStatusUpdate guild channel mute deaf) = object [
"op" .= (4 :: Int)
, "d" .= object [
"guild_id" .= guild
, "channel_id" .= channel
, "self_mute" .= mute
, "self_deaf" .= deaf
]
]
toJSON (Resume token session seqId) = object [
"op" .= (6 :: Int)
, "d" .= object [
"token" .= token
, "session_id" .= session
, "seq" .= seqId
]
]
toJSON (RequestGuildMembers guild query limit) = object [
"op" .= (8 :: Int)
, "d" .= object [
"guild_id" .= guild
, "query" .= query
, "limit" .= limit
]
]
toJSON _ = object []
instance WebSocketsData Payload where
fromLazyByteString bs = case eitherDecode bs of
Right payload -> payload
Left reason -> ParseError reason
toLazyByteString = encode
| jano017/Discord.hs | src/Network/Discord/Types/Gateway.hs | mit | 3,325 | 0 | 18 | 1,303 | 845 | 456 | 389 | 101 | 0 |
{-# LANGUAGE ViewPatterns #-}
module Unison.Util.Set where
import Data.Set
symmetricDifference :: Ord a => Set a -> Set a -> Set a
symmetricDifference a b = (a `difference` b) `union` (b `difference` a)
mapMaybe :: (Ord a, Ord b) => (a -> Maybe b) -> Set a -> Set b
mapMaybe f s = fromList [ r | (f -> Just r) <- toList s ]
| unisonweb/platform | unison-core/src/Unison/Util/Set.hs | mit | 327 | 0 | 11 | 69 | 157 | 83 | 74 | 7 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Processor.Sprockell where
{-------------------------------------------------------------
|
| SPROCKELL: Simple PROCessor in hasKELL :-)
|
| [email protected]
| October 14, 2012
|
-------------------------------------------------------------}
{-------------------------------------------------------------
| Assembly language
| Together with function to generate machine code
-------------------------------------------------------------}
data OpCode = Incr | Decr | Add | Sub | Mul | Div | Mod | Eq | NEq | Gt | Lt | And | Or | Not | NoOp
deriving (Eq,Show)
data Value = Addr Int
| Imm Int
deriving (Eq,Show)
data Assembly = Load Value Int -- Load (Addr a) r : from "memory a" to "regbank r"
-- Load (Imm v) r : put "Int v" in "regbank r"
| Store Value Int -- Store (Addr r) a: from "regbank r" to "memory a"
-- Store (Imm v) r: put "Int v" in "memory r"
| Calc OpCode Int Int Int -- Calc opc r0 r1 r2: "regbank r0" and "regbank r1" go to "alu",
-- do "opc", result to "regbank r2"
| Jump Int -- JumpAbs n: set program counter to n
| CJump Int -- JumpCond n: set program counter to n if bool b is 1
| RJump Int
| RCJump Int
| EndProg -- end of program, handled bij exec function
deriving (Eq,Show)
{-------------------------------------------------------------
| Machine code
-------------------------------------------------------------}
data State = State { dmem :: [Int] -- main memory, data memory
, regbank :: [Int] -- register bank
, pc :: Int -- program counter
, cnd :: Int -- condition register (whether condition was true)
}
deriving (Eq,Show)
dmemsize = 8 -- sizes of memory may be extended
regbanksize = 8
initstate = State { dmem = replicate dmemsize 0
, regbank = replicate regbanksize (0)
, pc = 0
, cnd = 0
}
data MachCode = MachCode { loadInstr :: Int -- 0/1: load from dmem to rbank?
, imm :: Int -- 0/1: immediate
, opc :: OpCode -- opcode
, fromaddr :: Int -- address in dmem
, toaddr :: Int -- address in dmem
, fromreg0 :: Int -- ibid, first parameter of Calc
, fromreg1 :: Int -- ibid, second parameter of Calc
, toreg :: Int -- ibid, third parameter of Calc
, value :: Int -- value from Immediate
, jmp :: Int -- 0/1: indicates a jump
, cjmp :: Int -- 0/1: indicates a conditional jump
, rjmp :: Int -- 0/1: indicates a relative jump
, rcjmp :: Int -- 0/1: indicates a relative, conditonal jump
, instrnr :: Int -- which instruction to jump to
}
deriving (Eq,Show)
nullcode = MachCode { loadInstr=0, imm=0, opc=NoOp, fromaddr=0, toaddr=0,
fromreg0=0, fromreg1=0, toreg=0, value=0,
jmp=0, cjmp=0, rjmp=0, rcjmp=0, instrnr=0}
{-------------------------------------------------------------
| The actual Sprockell
-------------------------------------------------------------}
tobit True = 1
tobit False = 0
xs <: (0,x) = 0 : tail xs
xs <: (i,x) = take i xs ++ [x] ++ drop (i+1) xs
op opc = case opc of
Incr -> \x0 -> \x1 -> x0+1 -- increment first argument with 1
Decr -> \x0 -> \x1 -> x0-1 -- decrement first argument with 1
Add -> (+) -- goes without saying
Sub -> (-)
Mul -> (*)
Div -> div
Mod -> mod
Eq -> (tobit.).(==) -- test for equality; result 0 or 1
NEq -> (tobit.).(/=) -- test for inequality
Gt -> (tobit.).(>)
Lt -> (tobit.).(<)
And -> (*)
Or -> max
Not -> \x0 -> \x1 -> 1-x0
NoOp -> \x0 -> \x1 -> 0 -- result will always be 0
decode instr = case instr of
Load (Addr a) r -> nullcode {loadInstr=1, imm=0, fromaddr=a, toreg=r}
Load (Imm v) r -> nullcode {loadInstr=1, imm=1, value =v, toreg=r}
Store (Addr r) a -> nullcode {imm=0, fromreg0=r, toaddr=a}
Store (Imm v) a -> nullcode {imm=1, value =v, toaddr=a}
Calc c r0 r1 r2 -> nullcode {loadInstr=0, opc=c, fromreg0=r0, fromreg1=r1, toreg=r2}
Jump n -> nullcode {jmp=1, instrnr=n}
CJump n -> nullcode {cjmp=1, instrnr=n}
RJump n -> nullcode {rjmp=1, instrnr=n}
RCJump n -> nullcode {rcjmp=1, instrnr=n}
load (regbank,dmem) (loadInstr,fromaddr,toreg,imm,value,y)
| loadInstr ==0 = regbank <: (toreg,y)
| imm==1 = regbank <: (toreg,value)
| imm==0 = regbank <: (toreg,dmem!!fromaddr)
store (regbank,dmem) (toaddr,fromreg0,imm,value)
| imm==1 = dmem <: (toaddr,value)
| imm==0 = dmem <: (toaddr,regbank!!fromreg0)
alu opc x0 x1 = (cnd,y)
where
y = op opc x0 x1
cnd = y `mod` 2
next (pc,jmp,cjmp,rjmp,rcjmp,instrnr,cnd)
| jmp == 1 = instrnr
| cjmp == 1 && cnd == 1 = instrnr
| rjmp == 1 = pc + instrnr
| rcjmp == 1 && cnd == 1 = pc + instrnr
| otherwise = pc + 1
sprockell prog state tick = State {dmem=dmem',regbank=regbank',pc=pc',cnd=cnd'}
where
State{..} = state
MachCode{..} = decode (prog!!pc)
x0 = regbank!!fromreg0
x1 = regbank!!fromreg1
(cnd',y) = alu opc x0 x1
dmem' = store (regbank,dmem) (toaddr,fromreg0,imm,value)
regbank' = load (regbank,dmem) (loadInstr,fromaddr,toreg,imm,value,y)
pc' = next (pc,jmp,cjmp,rjmp,rcjmp,instrnr,cnd)
| thomasbrus/imperia | src/Processor/Sprockell.hs | mit | 5,676 | 4 | 10 | 1,713 | 1,629 | 956 | 673 | 100 | 15 |
factors n = [x | x <- [1..n], n `mod` x == 0]
perfects :: Int -> [Int]
perfects n = [x | x <- [1..n], isPerfect x]
where isPerfect n' = sum (factors n') - n' == n'
-- using filter but not so good
perfects' :: Int -> [Int]
perfects' n = [x | x <- [1..n], isPerfect x]
where isPerfect n' = sum (filter (/= n') (factors n')) == n'
perfects'' :: Int -> [Int]
perfects'' n = [x | x <- [1..n], isPerfect x]
where isPerfect n' = sum (init (factors n')) == n'
perfects''' :: Int -> [Int]
perfects''' n = [x | x <- [1..n], isPerfect x]
where isPerfect n' = sumFactors n' == n'
sumFactors = sum . init . factors
main = do
print $ perfects 500
print $ perfects' 500
print $ perfects'' 500
print $ perfects''' 500
| fabioyamate/programming-in-haskell | ch05/ex04.hs | mit | 749 | 0 | 12 | 194 | 378 | 193 | 185 | 19 | 1 |
module Session where
import Data.IntMap (adjust)
import PeaCoq
isAlive :: SessionState -> Bool
isAlive (SessionState alive _) = alive
markStale :: SessionState -> SessionState
markStale (SessionState _ hs) = SessionState False hs
touchSession :: SessionState -> SessionState
touchSession (SessionState _ hs) = SessionState True hs
adjustSession :: (SessionState -> SessionState) -> Int -> GlobalState ->
(GlobalState, ())
adjustSession f mapKey gs =
(gs { gActiveSessions = adjust f mapKey (gActiveSessions gs) }, ())
| Ptival/peacoq-server | lib/Session.hs | mit | 542 | 0 | 10 | 97 | 175 | 94 | 81 | 13 | 1 |
import Churro.Interpreter
import System.Environment
import System.IO
{-
Opens a file and interprets the Churro code.
-}
main :: IO ()
main =
do{ args <- getArgs
; case args of
x:xs ->
do{ handle <- openFile x ReadMode
; code <- hGetContents handle
; parseAndInterpret code x
}
_ ->
do{ putStrLn "Usage: churro <filename>.ch" }
} | TheLastBanana/Churro | Main.hs | mit | 475 | 0 | 13 | 203 | 107 | 55 | 52 | 13 | 2 |
module Main where
import Prelude ()
import Common
import Blas
import qualified C
import qualified Fortran as F
mapFst f (x, y) = (f x, y)
convRet config (Just t) = (F.typeMap config t, F.returnConventionMap config t)
convRet _ Nothing = (C.Void, F.ReturnValue)
convIntent F.In = C.Const
convIntent _ = id
convParamF config (F.DeclType t a i) =
(if a then C.Pointer else applyConvention) .
convIntent i $ F.typeMap config t
where applyConvention = F.applyParamConvention $
F.paramConventionMap config t
convParamC config (F.DeclType t a i) =
(if a then C.Pointer . convIntent i else id) $ F.typeMap config t
convArg (F.DeclType _ a _, n) = (if a then "" else "&") <> n
cWrap config (BFun varTypes func) = convert config . func <$> varTypes
convert config (F.FunctionDecl name params ret) =
(fDecl, wDecl, "{\n" <> wBody <> "}\n\n")
where fDecl = F.applyReturnConvention cvn fName fParams wRet
fName = F.mangle config name
fParams = (mapFst $ convParamF config) <$> params
args = intercalate ", " $ convArg <$> params
call args = fName <> "(" <> args <> ");\n"
(wRet, cvn) = convRet config ret
wDecl = C.FunctionDecl wName wParams wRet
wName = modifyName $ toLower <$> name
wParams = (mapFst $ convParamC config) <$> params
wBody = case cvn of
F.ReturnValue -> (<> call args) $
case wRet of
C.Void -> " "
_ -> " return "
F.FirstParamByPointer ->
" " <> C.prettyType' wRet "return_value" <> ";\n" <>
" " <> call ("&return_value, " <> args) <>
" return return_value;\n"
showDecl = (<> ";\n\n") . C.prettyFunctionDecl
modifyName = ("bls_" <>)
main = do
let wraps = mconcat $ cWrap F.defaultConfig <$> blasFuns
let fDecls = (<$> wraps) $ \ (x, _, _) -> x
let wDecls = (<$> wraps) $ \ (_, x, _) -> x
let wDefs = (<$> wraps) $ \ (_, decl, body) ->
C.prettyFunctionDecl decl <> "\n" <> body
let fnRoot = "blas"
let headerFn = fnRoot <> ".h"
let sourceFn = fnRoot <> ".c"
let guardName = "SIINKPBGOYKIBQIVESTPJJLLJJRXQXDVBZSDSRYQ"
-- header
withFile ("dist/include/" <> headerFn) WriteMode $ \ h -> do
hPutStrLn h `mapM_`
[ "#ifndef " <> guardName
, "#define " <> guardName
, "#ifndef HAVE_COMPLEX_TYPEDEFS"
, "#include \"complex_typedefs.h\""
, "#endif"
, "#ifdef __cplusplus"
, "extern \"C\" {"
, "#endif"
, ""
]
hPutStr h `mapM_` (showDecl <$> wDecls)
hPutStrLn h `mapM_`
[ "#ifdef __cplusplus"
, "}"
, "#endif"
, "#endif"
]
-- source
withFile ("dist/src/" <> sourceFn) WriteMode $ \ h -> do
hPutStrLn h `mapM_`
[ "#include \"" <> headerFn <> "\""
]
hPutStr h `mapM_` (showDecl <$> fDecls)
hPutStr h `mapM_` wDefs
| Rufflewind/blas-shim | Main.hs | mit | 2,975 | 0 | 16 | 901 | 993 | 528 | 465 | 74 | 3 |
xs <- get
get >>= (\xs -> put (result : xs))
State (\s -> (s,s)) >>= (\xs -> put (result:xs))
State (\s -> (s,s)) >>= (\xs -> State (\_ -> ((), (result:xs))))
f = (\s -> (s,s))
g = (\xs -> State (\_ -> ((), (result:xs))))
State $ (\s -> let (a,s') = (\s -> (s,s)) s in runState (g a) s'
a ~ s
s' ~ s
reduces to:
State $ (\s -> runState (g s) s)
(g s) ~ (\xs -> State (\_ -> ((), (result:xs)))
(\s -> State (\_ -> ((), result:s)))
State (\_ -> ((), result:s))
(\_ -> ((), result:s))
((), result:s)
runState (g a) s'
runState ((\xs -> State (\_ -> ((), result:xs)) s) s
| JustinUnger/haskell-book | ch23/foo.hs | mit | 585 | 8 | 13 | 137 | 477 | 268 | 209 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGFEDisplacementMapElement
(pattern SVG_CHANNEL_UNKNOWN, pattern SVG_CHANNEL_R,
pattern SVG_CHANNEL_G, pattern SVG_CHANNEL_B,
pattern SVG_CHANNEL_A, js_getIn1, getIn1, js_getIn2, getIn2,
js_getScale, getScale, js_getXChannelSelector, getXChannelSelector,
js_getYChannelSelector, getYChannelSelector,
SVGFEDisplacementMapElement, castToSVGFEDisplacementMapElement,
gTypeSVGFEDisplacementMapElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
pattern SVG_CHANNEL_UNKNOWN = 0
pattern SVG_CHANNEL_R = 1
pattern SVG_CHANNEL_G = 2
pattern SVG_CHANNEL_B = 3
pattern SVG_CHANNEL_A = 4
foreign import javascript unsafe "$1[\"in1\"]" js_getIn1 ::
JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.in1 Mozilla SVGFEDisplacementMapElement.in1 documentation>
getIn1 ::
(MonadIO m) =>
SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedString)
getIn1 self
= liftIO
((js_getIn1 (unSVGFEDisplacementMapElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"in2\"]" js_getIn2 ::
JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.in2 Mozilla SVGFEDisplacementMapElement.in2 documentation>
getIn2 ::
(MonadIO m) =>
SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedString)
getIn2 self
= liftIO
((js_getIn2 (unSVGFEDisplacementMapElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"scale\"]" js_getScale ::
JSRef SVGFEDisplacementMapElement -> IO (JSRef SVGAnimatedNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.scale Mozilla SVGFEDisplacementMapElement.scale documentation>
getScale ::
(MonadIO m) =>
SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedNumber)
getScale self
= liftIO
((js_getScale (unSVGFEDisplacementMapElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"xChannelSelector\"]"
js_getXChannelSelector ::
JSRef SVGFEDisplacementMapElement ->
IO (JSRef SVGAnimatedEnumeration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.xChannelSelector Mozilla SVGFEDisplacementMapElement.xChannelSelector documentation>
getXChannelSelector ::
(MonadIO m) =>
SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedEnumeration)
getXChannelSelector self
= liftIO
((js_getXChannelSelector (unSVGFEDisplacementMapElement self)) >>=
fromJSRef)
foreign import javascript unsafe "$1[\"yChannelSelector\"]"
js_getYChannelSelector ::
JSRef SVGFEDisplacementMapElement ->
IO (JSRef SVGAnimatedEnumeration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFEDisplacementMapElement.yChannelSelector Mozilla SVGFEDisplacementMapElement.yChannelSelector documentation>
getYChannelSelector ::
(MonadIO m) =>
SVGFEDisplacementMapElement -> m (Maybe SVGAnimatedEnumeration)
getYChannelSelector self
= liftIO
((js_getYChannelSelector (unSVGFEDisplacementMapElement self)) >>=
fromJSRef) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/SVGFEDisplacementMapElement.hs | mit | 4,146 | 30 | 11 | 662 | 818 | 469 | 349 | 74 | 1 |
module GrabBag where
-- Question 3a
addOneIfOdd n = case odd n of
True -> f n
False -> n
where f = (\n -> n + 1) -- could also do (+1) and get rid of the function
-- Question 3b
addFive = \x -> \y -> (if x > y then y else x) + 5
-- Question 3c
mflip f x y = f y x
| rasheedja/HaskellFromFirstPrinciples | Chapter7/grabBag.hs | mit | 273 | 0 | 10 | 78 | 108 | 60 | 48 | 7 | 2 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Misc
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Various high-level functions to further classify.
module Yi.Misc ( getAppropriateFiles, getFolder, cd, pwd, matchingFileNames
, rot13Char, placeMark, selectAll, adjBlock, adjIndent
, promptFile , promptFileChangingHints, matchFile, completeFile
, printFileInfoE, debugBufferContent
) where
import Control.Applicative
import Control.Lens (assign)
import Control.Monad ((>=>), filterM)
import Control.Monad.Base
import Data.Char (chr, isAlpha, isLower, isUpper, ord)
import Data.List ((\\))
import Data.Maybe (isNothing)
import qualified Data.Text as T
import System.CanonicalizePath (canonicalizePath, replaceShorthands,
replaceShorthands)
import System.Directory (doesDirectoryExist, getDirectoryContents,
getCurrentDirectory, setCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath (takeDirectory, (</>), takeFileName,
addTrailingPathSeparator,
hasTrailingPathSeparator)
import System.FriendlyPath (expandTilda, isAbsolute')
import Yi.Buffer
import Yi.Completion (completeInList')
import Yi.Editor
import Yi.Keymap
import Yi.MiniBuffer (withMinibufferGen, mkCompleteFn,
debugBufferContent)
import Yi.Monad
import qualified Yi.Rope as R
import Yi.Utils (io)
-- | Given a possible starting path (which if not given defaults to
-- the current directory) and a fragment of a path we find all files
-- within the given (or current) directory which can complete the
-- given path fragment. We return a pair of both directory plus the
-- filenames on their own that is without their directories. The
-- reason for this is that if we return all of the filenames then we
-- get a 'hint' which is way too long to be particularly useful.
getAppropriateFiles :: Maybe T.Text -> T.Text -> YiM (T.Text, [ T.Text ])
getAppropriateFiles start s' = do
curDir <- case start of
Nothing -> do bufferPath <- withCurrentBuffer $ gets file
liftBase $ getFolder bufferPath
Just path -> return $ T.unpack path
let s = T.unpack $ replaceShorthands s'
sDir = if hasTrailingPathSeparator s then s else takeDirectory s
searchDir
| null sDir = curDir
| isAbsolute' sDir = sDir
| otherwise = curDir </> sDir
searchDir' <- liftBase $ expandTilda searchDir
let fixTrailingPathSeparator f = do
isDir <- doesDirectoryExist (searchDir' </> f)
return . T.pack $ if isDir then addTrailingPathSeparator f else f
files <- liftBase $ getDirectoryContents searchDir'
-- Remove the two standard current-dir and parent-dir as we do not
-- need to complete or hint about these as they are known by users.
let files' = files \\ [ ".", ".." ]
fs <- liftBase $ mapM fixTrailingPathSeparator files'
let matching = filter (T.isPrefixOf . T.pack $ takeFileName s) fs
return (T.pack sDir, matching)
-- | Given a path, trim the file name bit if it exists. If no path
-- given, return current directory.
getFolder :: Maybe String -> IO String
getFolder Nothing = getCurrentDirectory
getFolder (Just path) = do
isDir <- doesDirectoryExist path
let dir = if isDir then path else takeDirectory path
if null dir then getCurrentDirectory else return dir
-- | Given a possible path and a prefix, return matching file names.
matchingFileNames :: Maybe T.Text -> T.Text -> YiM [T.Text]
matchingFileNames start s = do
(sDir, files) <- getAppropriateFiles start s
-- There is one common case when we don't need to prepend @sDir@ to @files@:
--
-- Suppose user just wants to edit a file "foobar" in current directory
-- and inputs ":e foo<Tab>"
--
-- @sDir@ in this case equals to "." and "foo" would not be
-- a prefix of ("." </> "foobar"), resulting in a failed completion
--
-- However, if user inputs ":e ./foo<Tab>", we need to prepend @sDir@ to @files@
let results = if isNothing start && sDir == "." && not ("./" `T.isPrefixOf` s)
then files
else fmap (T.pack . (T.unpack sDir </>) . T.unpack) files
return results
-- | Place mark at current point
placeMark :: BufferM ()
placeMark = do
assign highlightSelectionA True
pointB >>= setSelectionMarkPointB
-- | Select the contents of the whole buffer
selectAll :: BufferM ()
selectAll = botB >> placeMark >> topB >> setVisibleSelection True
adjBlock :: Int -> BufferM ()
adjBlock x = withSyntaxB' (\m s -> modeAdjustBlock m s x)
-- | A simple wrapper to adjust the current indentation using
-- the mode specific indentation function but according to the
-- given indent behaviour.
adjIndent :: IndentBehaviour -> BufferM ()
adjIndent ib = withSyntaxB' (\m s -> modeIndent m s ib)
-- | Generic emacs style prompt file action. Takes a @prompt@ and a continuation
-- @act@ and prompts the user with file hints.
promptFile :: T.Text -> (T.Text -> YiM ()) -> YiM ()
promptFile prompt act = promptFileChangingHints prompt (const return) act
-- | As 'promptFile' but additionally allows the caller to transform
-- the list of hints arbitrarily, such as only showing directories.
promptFileChangingHints :: T.Text -- ^ Prompt
-> (T.Text -> [T.Text] -> YiM [T.Text])
-- ^ Hint transformer: current path, generated hints
-> (T.Text -> YiM ()) -- ^ Action over choice
-> YiM ()
promptFileChangingHints prompt ht act = do
maybePath <- withCurrentBuffer $ gets file
startPath <- T.pack . addTrailingPathSeparator
<$> liftBase (canonicalizePath =<< getFolder maybePath)
-- TODO: Just call withMinibuffer
withMinibufferGen startPath (\x -> findFileHint startPath x >>= ht x) prompt
(completeFile startPath) showCanon (act . replaceShorthands)
where
showCanon = withCurrentBuffer . replaceBufferContent . R.fromText . replaceShorthands
matchFile :: T.Text -> T.Text -> Maybe T.Text
matchFile path proposedCompletion =
let realPath = replaceShorthands path
in T.append path <$> T.stripPrefix realPath proposedCompletion
completeFile :: T.Text -> T.Text -> YiM T.Text
completeFile startPath =
mkCompleteFn completeInList' matchFile $ matchingFileNames (Just startPath)
-- | For use as the hint when opening a file using the minibuffer. We
-- essentially return all the files in the given directory which have
-- the given prefix.
findFileHint :: T.Text -> T.Text -> YiM [T.Text]
findFileHint startPath s = snd <$> getAppropriateFiles (Just startPath) s
onCharLetterCode :: (Int -> Int) -> Char -> Char
onCharLetterCode f c | isAlpha c = chr (f (ord c - a) `mod` 26 + a)
| otherwise = c
where a | isUpper c = ord 'A'
| isLower c = ord 'a'
| otherwise = undefined
-- | Like @M-x cd@, it changes the current working directory. Mighty
-- useful when we don't start Yi from the project directory or want to
-- switch projects, as many tools only use the current working
-- directory.
cd :: YiM ()
cd = promptFileChangingHints "switch directory to:" dirs $ \path ->
io $ getFolder (Just $ T.unpack path) >>= clean . T.pack
>>= System.Directory.setCurrentDirectory . addTrailingPathSeparator
where
replaceHome p@('~':'/':xs) = lookupEnv "HOME" >>= return . \case
Nothing -> p
Just h -> h </> xs
replaceHome p = return p
clean = replaceHome . T.unpack . replaceShorthands >=> canonicalizePath
x <//> y = T.pack $ takeDirectory (T.unpack x) </> T.unpack y
dirs :: T.Text -> [T.Text] -> YiM [T.Text]
dirs x xs = do
xsc <- io $ mapM (\y -> (,y) <$> clean (x <//> y)) xs
filterM (io . doesDirectoryExist . fst) xsc >>= return . map snd
-- | Shows current working directory. Also see 'cd'.
pwd :: YiM ()
pwd = io getCurrentDirectory >>= printMsg . T.pack
rot13Char :: Char -> Char
rot13Char = onCharLetterCode (+13)
printFileInfoE :: EditorM ()
printFileInfoE = printMsg . showBufInfo =<< withCurrentBuffer bufInfoB
where showBufInfo :: BufferFileInfo -> T.Text
showBufInfo bufInfo = T.concat
[ T.pack $ bufInfoFileName bufInfo
, " Line "
, T.pack . show $ bufInfoLineNo bufInfo
, " ["
, bufInfoPercent bufInfo
, "]"
]
| atsukotakahashi/wi | src/library/Yi/Misc.hs | gpl-2.0 | 8,968 | 0 | 17 | 2,282 | 2,029 | 1,064 | 965 | -1 | -1 |
{-# LANGUAGE BangPatterns, GADTs, TypeFamilies #-}
{- The guts of the arrowized Esterel circuit translation.
- Copyright : (C)opyright 2006, 2009-2011 peteg42 at gmail dot com
- License : GPL (see COPYING for details)
-
- The 'E' arrow acts as an /environment transformer/.
-
- Sketch following Berry, CONSTRUCTIVE SEMANTICS OF ESTEREL.
-
- Invariants:
- completion codes are one-hot p113.
FIXME lint all the signatures.
FIXME ifE etc: intuitively this represents control flow choice. Data
should depend on signals, not control flow. Make this clear. For this
reason we don't allow ifE etc. to return data.
FIXME we don't try to treat schizophrenia here: we just want something
that plays nicely with our circuit combinators (probes and
kTests). Berry's full circuit translation duplicates things in
inconvenient ways; we could make it work, but it's too much hassle.
FIXME verify: According to Berry Ch12, the constructivity checker will
reject some "constructive" Esterel programs. These get compiled to
non-constructive circuits, and the schizophrenia machinery would
duplicate logic to make it all work.
This is probably what Lusterel is trying to fix.
Completion codes:
K0 -> terminated
K1 -> paused
Kn, n > 1 -> exception
FIXME:
- local signals are totally unsafe presently.
- one case where a static/dynamic split would be useful.
Observe that we cannot chain the environments through in the obvious
way: each leaf command has to determine the signal and exception
signals, for otherwise the ultimate combinational loop is underdefined
- it will be undefined if the signal is not emitted.
According to Berry this translation is "partially correct" -- I think this
means that if this translation miscompiles an Esterel program according to
his semantics then the resulting circuit is non-constructive.
Idiomatically everywhere Berry uses signals we want to use circuits,
and then provide a signal-to-circuit Arrow.
FIXME play the Optimise game at the Kesterel level? We certainly can
remove some trivial structural things, e.g. x |||| nothingE --> x.
-}
module ADHOC.Control.Kesterel.Kernel where
-------------------------------------------------------------------
-- Dependencies.
-------------------------------------------------------------------
import Prelude ()
import ADHOC.Circuits hiding ( rem, sin )
import ADHOC.Generics
import ADHOC.Model ( KF, ArrowAgent(..), ArrowKTest(..), ArrowProbe(..),
RenderInState(..) )
import ADHOC.NonDet -- FIXME ( ArrowUnsafeNonDet(..) )
import Data.Sequence ( Seq, (|>), (><), ViewR(..) )
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import ADHOC.Constructivity ( CArrow )
import ADHOC.NetList ( NLArrow )
-------------------------------------------------------------------
-- Cheap and cheerful Environment/Reader monad.
-------------------------------------------------------------------
-- | Environment/Reader functor/monad.
newtype EnvM s a = EnvM { runEnvM :: s -> a }
instance Functor (EnvM s) where
fmap f (EnvM g) = EnvM (g >>> f)
instance Monad (EnvM s) where
return = EnvM . const
f >>= g = EnvM (\s -> runEnvM (g (runEnvM f s)) s)
readEnvM :: EnvM s s
readEnvM = EnvM id
inEnvEM :: s -> EnvM s a -> EnvM s a
inEnvEM s f = EnvM $ const (runEnvM f s)
-------------------------------------------------------------------
-- Extra Sequence combinators.
-------------------------------------------------------------------
-- | Combinational loop over a vector of signals.
combLoopF :: ArrowCombLoop (~>) r
=> Int
-> (b, Seq r) ~> (c, Seq r)
-> b ~> c
combLoopF k0 f = arr (\b -> (b, Seq.empty)) >>> cl k0 >>> arr fst
where
cl 0 = f
cl k = proc (b, xs) ->
(| combLoop (\x ->
do ~(c, d) <- cl (k - 1) -< (b, xs |> x)
let (xs' :> x') = Seq.viewr d
returnA -< ((c, xs'), x')) |)
lift2 :: Arrow (~>)
=> Int
-> ((c, d) ~> e)
-> (Seq c, Seq d) ~> Seq e
lift2 k0 f = opL k0
where
opL 0 = arr (const Seq.empty)
opL k = proc (xs, ys) ->
do let !(xs' :> x') = Seq.viewr xs
!(ys' :> y') = Seq.viewr ys
(| (liftA2 (|>)) (opL (k - 1) -< (xs', ys')) (f -< (x', y')) |)
-- FIXME verify: process the sequence right-to-left.
rowA :: Arrow (~>)
=> Int
-> ((a, b) ~> (a, c))
-> (a, Seq b) ~> (a, Seq c)
rowA k0 f = opL k0
where
opL 0 = arr (\(a, _) -> (a, Seq.empty))
opL k = proc (a, xs) ->
do let !(xs' :> x') = Seq.viewr xs
(a', c) <- f -< (a, x')
(a'', cs) <- opL (k - 1) -< (a', xs')
returnA -< (a'', cs |> c)
-------------------------------------------------------------------
-- Esterel translation boilerplate.
-------------------------------------------------------------------
-- | We need to track some static information: signal and exception
-- scopes.
data Static
= Static
{ exnID :: !Int
, sigID :: !Int
} deriving Show
-- | The dynamic environment: the values of signals.
newtype Esigs b = Esigs { eSigs :: Seq b }
deriving Show
instance StructureDest b b => StructureDest b (Esigs b) where
destructure = F.toList . eSigs
instance RenderInState b b' => RenderInState (Esigs b) b' where
renderInState = mconcat . map renderInState . F.toList . eSigs
cenv_exns_empty :: Static -> b -> (Esigs b, Seq b)
cenv_exns_empty s ff =
( Esigs{eSigs = Seq.replicate (sigID s) ff}
, Seq.replicate (exnID s) ff )
-- | Dynamic control inputs for 'E' sub-circuits.
data Cin b
= Cin
{ ciGo :: b
, ciRes :: b
, ciSusp :: b
, ciKill :: b
} deriving Show
instance StructureDest b b => StructureDest b (Cin b) where
destructure = \(Cin a b c d) -> [a,b,c,d]
instance RenderInState b b' => RenderInState (Cin b) b' where
renderInState (Cin g r s k) = mconcat (map renderInState [g, r, s, k])
-- | Dynamic control outputs for 'E' sub-circuits. Mandatory: 'coSelected', 'coTerminated'.
data Cout b
= Cout
{ coSelected :: b -- ^ Selected (an enclosed 'pause' is paused)
, coTerminated :: b
, coPaused :: b
, coExns :: Seq b
} deriving Show
-- | The dynamic part of the @E@ arrow: map control and data inputs
-- into control and data outputs.
type Dynamic (~>) c d =
(Cin (B (~>)), Esigs (B (~>)), c) ~> (Cout (B (~>)), Esigs (B (~>)), d)
-- | The @E@ arrow.
newtype E (~>) c d = E { unE :: EnvM Static (Dynamic (~>) c d) }
-- | A typical Esterel program needs these classes.
class (ArrowLoop (~>), ArrowDelay (~>) (B (~>)), ArrowCombLoop (~>) (B (~>)),
ArrowComb (~>), ArrowInit (~>))
=> EC (~>)
instance EC CArrow
instance EC (NLArrow detail)
-- | Lift up computations in the underlying arrow.
instance EC (~>) => ArrowTransformer (E) (~>) where
lift = liftE
instance EC (~>) => Category (E (~>)) where
id = lift id
f . g = seqE g f
-- FIXME first can be implemented much more efficiently
instance EC (~>) => Arrow (E (~>)) where
arr = lift . arr
first f = f *** id
(***) = seqE_par_env
instance EC (~>) => ArrowLoop (E (~>)) where
loop = arrowLoopE
-- Lift circuits in the obvious way. Handy for boolean combinations of
-- signals.
instance EC (~>) => ArrowComb (E (~>)) where
-- The type of a single rail.
type B (E (~>)) = B (~>)
falseA = lift falseA
trueA = lift trueA
andA = lift andA
notA = lift notA
nandA = lift nandA
orA = lift orA
xorA = lift xorA
iffA = lift iffA
impA = lift impA
-------------------------------------------------------------------
-- Lifting and looping.
-------------------------------------------------------------------
-- | Lift an underlying arrow /f/, which is executed at every instant.
liftE :: forall (~>) b c. EC (~>) => (b ~> c) -> E (~>) b c
liftE f = E $
do s <- readEnvM
return $ proc (cin, _ienv, c) ->
do d <- f -< c
ff <- falseA -< ()
let (oenv, exns) = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = ff
, coTerminated = ciGo cin
, coPaused = ff
, coExns = exns }
, oenv
, d)
-- | Does nothing, consumes no time.
nothingE :: EC (~>) => E (~>) env ()
nothingE = arr (const ())
-- | Data recursion: hoist up an underlying instance of
-- 'ArrowLoop'. Otherwise oblivious to the 'E' shenanigans.
arrowLoopE :: EC (~>) => E (~>) (b, d) (c, d) -> E (~>) b c
arrowLoopE (E fE) = E $
do f <- fE
return $ proc (cin, ienv, b) ->
do rec ~(cout, f_env, ~(c, d)) <- f -< (cin, ienv, (b, d))
returnA -< (cout, f_env, c)
-------------------------------------------------------------------
-- Kernel Esterel
-------------------------------------------------------------------
-- | Rest here for an instant.
pauseE_prim :: forall (~>) env. EC (~>) => (B (~>) ~> B (~>)) -> E (~>) env ()
pauseE_prim pA = E $
do s <- readEnvM
return $ note "pauseE" $ proc (cin, _ienv, _c) ->
do nKill <- notA -< ciKill cin
rec reg <- (| delayAC (falseA -< ()) (andA -< (t, nKill)) |)
t <- orA <<< second andA -< (ciGo cin, (ciSusp cin, reg))
pA -< reg
terminated <- andA -< (reg, ciRes cin)
ff <- falseA -< ()
let (oenv, exns) = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = reg
, coTerminated = terminated
, coPaused = ciGo cin
, coExns = exns }
, oenv
, () )
pauseE :: EC (~>) => E (~>) env ()
pauseE = pauseE_prim id
probePauseE :: (EC (~>), ArrowProbe (~>) (B (~>)))
=> ProbeID -> E (~>) env ()
probePauseE = pauseE_prim . probeA
-- | Infinitely loop.
-- FIXME not correct for unsafe loops?
-- This definitely requires 'ArrowCombLoop': see Berry p131.
loopE :: EC (~>)
=> E (~>) env b
-> E (~>) env b
loopE (E fE) = E $
do f <- fE
return $ note "loopE" $ proc (cin, ienv, c) ->
(| combLoop (\terminated ->
do f_go <- orA -< (ciGo cin, terminated)
(f_cout, f_env, d) <- f -< (cin{ciGo = f_go}, ienv, c)
ff <- falseA -< ()
returnA -< ( (f_cout{coTerminated = ff}, f_env, d)
, coTerminated f_cout ) ) |)
-- | Sequential composition of two 'E' computations, chaining the data
-- output of the first into the second.
seqE :: forall (~>) b c d.
ArrowComb (~>)
=> E (~>) b c -> E (~>) c d -> E (~>) b d
(E fE) `seqE` (E gE) = E $
do f <- fE
g <- gE
s <- readEnvM
return $ {- note "seqE" $ -} proc (cin, ienv, c) ->
do (f_cout, f_env, d) <- f -< (cin, ienv, c)
(g_cout, g_env, e) <- g -< (cin{ciGo = coTerminated f_cout}, ienv, d)
oenv <- combine_envs s -< (f_env, g_env)
cout <- combine_seq_couts s -< (f_cout, g_cout)
returnA -< (cout, oenv, e)
-- | Sequential composition of two 'E' computations, splitting the
-- data between the two. For @(***)@.
seqE_par_env :: forall (~>) env env' b b'.
ArrowComb (~>)
=> E (~>) env b
-> E (~>) env' b'
-> E (~>) (env, env') (b, b')
(E fE) `seqE_par_env` (E gE) = E $
do f <- fE
g <- gE
s <- readEnvM
return $ {- note "seqE" $ -} proc (cin, ienv, (c, c')) ->
do (f_cout, f_env, d ) <- f -< (cin, ienv, c)
(g_cout, g_env, d') <- g -< (cin{ciGo = coTerminated f_cout}, ienv, c')
oenv <- combine_envs s -< (f_env, g_env)
cout <- combine_seq_couts s -< (f_cout, g_cout)
returnA -< (cout, oenv, (d, d'))
combine_envs :: forall (~>). (ArrowComb (~>))
=> Static -> (Esigs (B (~>)), Esigs (B (~>))) ~> Esigs (B (~>))
combine_envs s = proc (f_env, g_env) ->
do sigs' <- lift2 (sigID s) orA -< (eSigs f_env, eSigs g_env)
returnA -< Esigs{eSigs = sigs'}
combine_seq_couts :: ArrowComb (~>)
=> Static -> (Cout (B (~>)), Cout (B (~>))) ~> Cout (B (~>))
combine_seq_couts s = proc (f_cout, g_cout) ->
do selected <- orA -< (coSelected f_cout, coSelected g_cout)
let terminated = coTerminated g_cout
paused <- orA -< (coPaused f_cout, coPaused g_cout)
exns <- lift2 (exnID s) orA -< (coExns f_cout, coExns g_cout)
returnA -< Cout { coSelected = selected
, coTerminated = terminated
, coPaused = paused
, coExns = exns }
-------------------------------------------------------------------
-- Parallel composition.
-------------------------------------------------------------------
infixr 2 ||||
(||||) :: EC (~>) => E (~>) env () -> E (~>) env () -> E (~>) env ()
f |||| g = f `parE` g >>> arr (const ())
-- | Parallel composition. Think of this as "control-parallelism", not
-- the "data-parallelism" provided by 'seqE_par_env'.
parE :: forall (~>) env b b'. EC (~>)
=> E (~>) env b -> E (~>) env b' -> E (~>) env (b, b')
(E fE) `parE` (E gE) = E $
do f <- fE
g <- gE
s <- readEnvM
return $ note "parE" $ proc (cin, ienv, c) ->
do (f_cout, f_env, d ) <- f -< (cin, ienv, c)
(g_cout, g_env, d') <- g -< (cin, ienv, c)
selected <- orA -< (coSelected f_cout, coSelected g_cout)
(terminated, paused, exns) <- synchronise s -< (cin, f_cout, g_cout)
oenv <- combine_envs s -< (f_env, g_env)
returnA -< ( Cout { coSelected = selected
, coTerminated = terminated
, coPaused = paused
, coExns = exns }
, oenv
, (d, d') )
-- | Synchronisation, following Berry p122: compute the completion
-- code of the two threads.
synchronise :: forall (~>).
ArrowComb (~>)
=> Static
-> (Cin (B (~>)), Cout (B (~>)), Cout (B (~>)))
~> (B (~>), B (~>), Seq (B (~>)))
synchronise s = note "synchronise" $ proc (cin, f_cout, g_cout) ->
do lem <- notA <<< orA -< (coSelected f_cout, ciGo cin)
rem <- notA <<< orA -< (coSelected g_cout, ciGo cin)
((l0, r0), terminated) <- max_completion_code -< ((lem, rem), (coTerminated f_cout, coTerminated g_cout))
((l1, r1), paused) <- max_completion_code -< ((l0, r0), (coPaused f_cout, coPaused g_cout))
(_, exns') <- rowA (exnID s) max_completion_code -< ((l1, r1), Seq.zip (coExns f_cout) (coExns g_cout))
returnA -< (terminated, paused, exns')
max_completion_code :: ArrowComb (~>)
=> ((B (~>), B (~>)), (B (~>), B (~>))) ~> ((B (~>), B (~>)), B (~>))
max_completion_code = proc ((lprev, rprev), (lexn, rexn)) ->
do lnext <- orA -< (lprev, lexn)
rnext <- orA -< (rprev, rexn)
exn_both <- orA -< (lexn, rexn)
exn <- andA <<< second andA -< (exn_both, (lnext, rnext))
returnA -< ((lnext, rnext), exn)
-------------------------------------------------------------------
-- Local signals.
-------------------------------------------------------------------
-- | User-visible signals.
newtype Signal = Signal Int
instance StructureDest Signal Signal where
destructure = (:[])
instance Structure Signal Signal where
type SIwidth Signal Signal = One
structure = sallocSM
-- | Allocate scoped local 'Signal's.
--
-- We don't need to worry about signal scopes here! If they get
-- Arrow-returned that's OK, there's no combinator @E (~>)
-- Signal b@.
signalE :: forall (~>) env b v.
(EC (~>), Structure Signal v)
=> (v -> E (~>) env b)
-> E (~>) env b
signalE fE = E $
do s <- readEnvM
let next_sid = sigID s + fromInteger width
sids = [sigID s .. next_sid - 1]
s' = s{sigID = next_sid}
(v, xs) = runStateM structure (map Signal sids)
f <- assert (null xs) $ inEnvEM s' (unE (fE v))
return $ proc (cin, ienv, c) ->
do (| (combLoopF (fromInteger width)) (\s_vals ->
do (f_cout, f_env, d) <- f -< (cin, ienv{eSigs = eSigs ienv >< s_vals}, c)
let (penv, s_vals') = sigID s `Seq.splitAt` eSigs f_env
oenv = f_env{eSigs = penv}
returnA -<
-- trace ("ienv: " ++ show (Seq.length (eSigs ienv))
-- ++ " fenv: " ++ show (Seq.length (eSigs f_env))
-- ++ " s_vals: " ++ show (Seq.length s_vals)
-- ++ " s_vals': " ++ show (Seq.length s_vals')
-- ++ " oenv: " ++ show (Seq.length (eSigs oenv))) $
-- assert (Seq.length penv == Seq.length (eSigs ienv)) $
-- assert (Seq.length s_vals == fromInteger width) $
-- assert (Seq.length s_vals' == fromInteger width) $
-- assert (Seq.length (eSigs ienv) == Seq.length (eSigs oenv)) $
((f_cout, oenv, d), s_vals') ) |)
where
width = c2num (undefined :: SIwidth Signal v) :: Integer
-- | Project a signal out of the Esterel environment.
sigE :: forall (~>) env.
ArrowComb (~>)
=> Signal -> E (~>) env (B (~>))
sigE (Signal sid) = E $
do s <- readEnvM
return $ proc (cin, ienv, _c) ->
do ff <- falseA -< ()
let (oenv, exns') = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = ff
, coTerminated = ciGo cin
, coPaused = ff
, coExns = exns' }
, oenv
, eSigs ienv `Seq.index` sid )
-- | Emit a 'Signal'.
emitE :: forall (~>) env. EC (~>) => Signal -> E (~>) env ()
emitE (Signal sid) = E $
do s <- readEnvM
return $ proc (cin, _ienv, _c) ->
do ff <- falseA -< ()
let (oenv, exns) = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = ff
, coTerminated = ciGo cin
, coPaused = ff
, coExns = exns }
, oenv{eSigs = Seq.update sid (ciGo cin) (eSigs oenv)}
, () )
-- | Branch on an arbitrary test.
ifE :: forall (~>) env. EC (~>)
=> (env ~> B (~>))
-> E (~>) env ()
-> E (~>) env ()
-> E (~>) env ()
ifE cond (E thenEM) (E elseEM) = E $
do thenE <- thenEM
elseE <- elseEM
s <- readEnvM
return $ note "ifE" $ proc (cin, ienv, c) ->
do t <- cond -< c
t_go <- andA -< (ciGo cin, t)
e_go <- (returnA -< ciGo cin) `andAC` (notA -< t)
(t_cout, t_env, _t_d) <- thenE -< (cin{ciGo = t_go}, ienv, c)
(e_cout, e_env, _e_d) <- elseE -< (cin{ciGo = e_go}, ienv, c)
oenv <- combine_envs s -< (t_env, e_env)
exns' <- lift2 (exnID s) orA -< (coExns t_cout, coExns e_cout)
selected <- orA -< (coSelected t_cout, coSelected e_cout)
terminated <- orA -< (coTerminated t_cout, coTerminated e_cout)
paused <- orA -< (coPaused t_cout, coPaused e_cout)
returnA -< ( Cout { coSelected = selected
, coTerminated = terminated
, coPaused = paused
, coExns = exns' }
, oenv
, () )
-- | FIXME variant: test is in an Esterel context. The type is totally bizarre.
-- ifE' :: (ArrowComb (~>), ArrowMux (~>) d)
-- => E (~>) c (B (~>))
-- -> E (~>) c d
-- -> E (~>) c d
-- -> E (~>) c d
ifE' condE thenE elseE = proc c ->
do cond <- condE -< c
(| (ifE_perm thenE elseE) (returnA -< cond) |)
-- FIXME putting this in a where clause triggers a GHC 7.0.3 bug
ifE_perm thenE elseE i = ifE i thenE elseE
-- | Test for the presence of a signal.
presentE :: EC (~>)
=> Signal
-> E (~>) c ()
-> E (~>) c ()
-> E (~>) c ()
presentE s thenE elseE = proc c ->
do v <- sigE s -< c
(| ifE (returnA -< v) (thenE -< c) (elseE -< c) |)
-- | Non-deterministcally choose between two "E" computations.
--
-- FIXME This formulation using "unsafeNonDetInstAC" leads to less
-- branching in the resulting automaton. Unfortunately it doesn't seem
-- to be correct.
-- nondetE :: forall (~>) env. (ArrowUnsafeNonDet (~>) (B (~>)), EC (~>))
-- => E (~>) env ()
-- -> E (~>) env ()
-- -> E (~>) env ()
nondetE = ifE nondetBitA
{-
nondetE (E fE) (E gE) = E $
do f <- fE
g <- gE
s <- readEnvM
return $ note "ifE" $ proc (cin, ienv, c) ->
do -- If this statement is active then make a choice, otherwise don't (t=tt).
t <- (| unsafeNonDetInstAC (\x -> (| orAC (returnA -< ciGo cin) (returnA -< x) |) ) |)
t_go <- andA -< (ciGo cin, t)
e_go <- andA <<< second notA -< (ciGo cin, t)
(t_cout, t_env, _t_d) <- f -< (cin{ciGo = t_go}, ienv, c)
(e_cout, e_env, _e_d) <- g -< (cin{ciGo = e_go}, ienv, c)
oenv <- combine_envs s -< (t_env, e_env)
exns' <- lift2 (exnID s) orA -< (coExns t_cout, coExns e_cout)
selected <- orA -< (coSelected t_cout, coSelected e_cout)
terminated <- orA -< (coTerminated t_cout, coTerminated e_cout)
paused <- orA -< (coPaused t_cout, coPaused e_cout)
returnA -< ( Cout { coSelected = selected
, coTerminated = terminated
, coPaused = paused
, coExns = exns' }
, oenv
, () )
-}
-------------------------------------------------------------------
-- Exceptions.
-------------------------------------------------------------------
newtype Exception = Exception Int
-- | Allocate a scoped local 'Exception'.
catchE :: forall (~>) env b. EC (~>) => (Exception -> E (~>) env b)
-> E (~>) env b
catchE fE = E $
do s <- readEnvM
let eid = exnID s
s' = s{exnID = succ eid}
f <- inEnvEM s' (unE (fE (Exception eid)))
return $ note ("catchE: " ++ show eid) $ proc (cin, ienv, env) ->
do rec kill <- orA -< (ciKill cin, e_thrown)
(f_cout, f_env, b) <- f -< (cin{ciKill = kill}, ienv, env)
let !(exns :> e_thrown) = Seq.viewr (coExns f_cout)
term <- orA -<
-- trace ("catchE: coExns len: " ++ show (Seq.length (coExns f_cout)) ++ " / s: " ++ show s) $
(coTerminated f_cout, e_thrown)
returnA -< ( f_cout{coTerminated = term, coExns = exns}
, f_env
, b )
-- | Throw an 'Exception'.
throwE :: forall (~>) env. EC (~>) => Exception -> E (~>) env ()
throwE (Exception eid) = E $
do s <- readEnvM
return $ note ("throwE: " ++ show eid) $ proc (cin, _ienv, _c) ->
do ff <- falseA -< ()
let (oenv, exns) = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = ff
, coTerminated = ff
, coPaused = ff
, coExns = Seq.update eid (ciGo cin) exns }
, oenv
, () )
-------------------------------------------------------------------
-- Pre-emption (abort/when, previously do/watching (>>)).
-- Intended to be used infix.
-------------------------------------------------------------------
-- FIXME get names straight
abortE :: EC (~>) => E (~>) env c -> Signal -> E (~>) env c
abortE fE s = proc env ->
do c <- sigE s -< ()
(| abort_primE (returnA -< c) (fE -< env) |)
abortE' :: EC (~>) => E (~>) env (B (~>)) -> E (~>) env c -> E (~>) env c
abortE' condE fE = proc env ->
do c <- condE -< env
(| abort_primE (returnA -< c) (fE -< env) |)
-- | The combinational loop involves the 'abortE' @coTerminated@
-- output, I think. See test 112 for an example that loops if we use
-- 'loop'.
abort_primE :: EC (~>) => (env ~> B (~>)) -> E (~>) env c -> E (~>) env c
abort_primE cond (E fE) = E $
do f <- fE
return $ note "abortE" $ proc (cin, ienv, env) ->
do c <- cond -< env
((f_cout, f_env, d), t) <-
(| combLoop (\selected ->
do t <- andA -< (selected, ciRes cin)
res <- andA <<< second notA -< (t, c)
fout@(f_cout, _f_env, _d) <- f -< (cin{ciRes = res}, ienv, env)
returnA -< ((fout, t), coSelected f_cout) ) |)
terminated <- orA <<< second andA -< (coTerminated f_cout, (c, t))
returnA -< (f_cout{coTerminated = terminated}, f_env, d)
-------------------------------------------------------------------
-- Suspend.
-------------------------------------------------------------------
-- | Suspend on a boolean signal.
-- FIXME semantics.
-- FIXME verify acyclic.
suspendE :: (ArrowComb (~>), ArrowLoop (~>))
=> E (~>) gin gout
-> E (~>) (gin, B (~>)) gout
suspendE f = error "suspendE"
{-
MkE $ \s e ->
let
arrowF = runE f s e
arrow =
proc (cin, (gin, cond)) ->
do rec t0 <- andA -< (sel', eciRes cin)
res' <- andA <<< second notA -< (t0, cond)
t1 <- andA -< (t0, cond)
susp' <- orA -< (eciSusp cin, t1)
let cin' = cin{ eciRes = res', eciSusp = susp' }
(cout@(MkECout { ecoSelected = sel'}), gout)
<- arrowF -< (cin', gin)
paused' <- orA -< (ecoPaused cout, t1)
returnA -< (cout { ecoPaused = paused' }, gout)
in arrow
-}
-------------------------------------------------------------------
-- Knowledge.
-------------------------------------------------------------------
{-
Knowledge gets messy in concert with combinational cycles.
-}
kTestE :: (EC (~>), ArrowKTest (~>))
=> KF -> E (~>) env () -> E (~>) env () -> E (~>) env ()
kTestE kf = ifE (kTest kf)
agentE :: ArrowAgent (~>) (Cin (B (~>)), Esigs (B (~>)), obs)
=> AgentID -> E (~>) obs action -> E (~>) obs action
agentE aid (E fA) = E $ fmap (agent aid) fA
-- | Probe a value.
probeE :: (EC (~>), ArrowProbe (~>) v)
=> String -> E (~>) v v
probeE = lift . probeA
-- | Probe a "Signal".
probeSigE :: (EC (~>), ArrowProbe (~>) (B (~>)))
=> String -> Signal -> E (~>) env ()
probeSigE l s = sigE s >>> probeE l >>> arr (const ())
-------------------------------------------------------------------
-- | Often we want to emit a signal until a computation has finished.
--
-- More precisely, we want to emit it while control resides with the
-- computation, i.e. when it pauses. If the computation does not pause
-- then the signal never gets emitted.
--
-- We aim to do this without extra state.
--
-- FIXME we want this to work with both E and bus signals, so we might
-- have to consider ciGo too.
sustainWhileE :: forall (~>) env. EC (~>) => Signal -> E (~>) env () -> E (~>) env ()
sustainWhileE (Signal sid) (E fE) = E $
do f <- fE
return $ proc (cin, ienv, c) ->
do (f_cout, f_env, d) <- f -< (cin, ienv, c)
-- active <- orA -< (ciGo cin, coPaused f_cout)
let active = coPaused f_cout
sval <- orA -< (eSigs f_env `Seq.index` sid, active)
let oenv = Seq.update sid sval (eSigs f_env)
returnA -< (f_cout, f_env{eSigs = oenv}, d)
-------------------------------------------------------------------
-- Debugging
-------------------------------------------------------------------
-- | Add a probe: true if this statement is active.
activeE :: forall (~>) v. (EC (~>), ArrowProbe (~>) (B (~>)))
=> ProbeID -> E (~>) v v
activeE pid = E $
do s <- readEnvM
return $ proc (cin, _ienv, c) ->
do probeA pid -< ciGo cin
ff <- falseA -< ()
let (oenv, exns) = cenv_exns_empty s ff
returnA -< ( Cout { coSelected = ff
, coTerminated = ciGo cin
, coPaused = ff
, coExns = exns }
, oenv
, c)
-------------------------------------------------------------------
-- Esterel top-level.
-------------------------------------------------------------------
-- | FIXME top-level.
-- FIXME assert something about f_env
runE' :: EC (~>) => E (~>) c d -> (c ~> (B (~>), d))
runE' fE = note "runE" $ proc c ->
do boot <- isInitialState -< ()
ff <- falseA -< ()
tt <- trueA -< ()
let cin = Cin { ciGo = boot
, ciRes = tt
, ciSusp = ff
, ciKill = ff
}
(f_cout, f_env, d) <- f -< (cin, e0, c)
returnA -<
-- trace ("runE': coExns: " ++ show (Seq.length (coExns f_cout))
-- ++ " sigs: " ++ show (Seq.length (eSigs f_env)))
assert (Seq.length (coExns f_cout) == 0) $
assert (Seq.length (eSigs f_env) == 0) $
(coTerminated f_cout, d)
where
e0 = Esigs {eSigs = Seq.empty}
s0 = Static {exnID = 0, sigID = 0}
f = runEnvM (unE fE) s0
| peteg/ADHOC | ADHOC/Control/Kesterel/Kernel.hs | gpl-2.0 | 29,163 | 105 | 25 | 8,759 | 8,509 | 4,677 | 3,832 | -1 | -1 |
module HSE.Type(module HSE.Type, module Export) where
-- Almost all from the Annotated module, but the fixity resolution from Annotated
-- uses the unannotated Assoc enumeration, so export that instead
import Language.Haskell.Exts.Annotated as Export hiding (parse, loc, parseFile, paren, Assoc(..))
import Language.Haskell.Exts as Export(Assoc(..))
import Data.Generics.Uniplate.Data as Export
type S = SrcSpanInfo
type Module_ = Module S
type Decl_ = Decl S
type Exp_ = Exp S
type Pat_ = Pat S
type Type_ = Type S
{-!
deriving instance UniplateDirect (Pat S) (Pat S)
deriving instance UniplateDirect (Exp S)
deriving instance UniplateDirect (Pat S)
deriving instance UniplateDirect (Pat S) (Exp S)
deriving instance UniplateDirect (Binds S) (Exp S)
deriving instance UniplateDirect (Alt S) (Exp S)
deriving instance UniplateDirect (Stmt S) (Exp S)
deriving instance UniplateDirect (QualStmt S) (Exp S)
deriving instance UniplateDirect [QualStmt S] (Exp S)
deriving instance UniplateDirect (Bracket S) (Exp S)
deriving instance UniplateDirect (Splice S) (Exp S)
deriving instance UniplateDirect (XAttr S) (Exp S)
deriving instance UniplateDirect (Maybe (Exp S)) (Exp S)
deriving instance UniplateDirect (FieldUpdate S) (Exp S)
deriving instance UniplateDirect (PatField S) (Pat S)
deriving instance UniplateDirect (Exp S) (Pat S)
deriving instance UniplateDirect (RPat S) (Pat S)
deriving instance UniplateDirect (PXAttr S) (Pat S)
deriving instance UniplateDirect (Maybe (Pat S)) (Pat S)
deriving instance UniplateDirect (PatField S) (Exp S)
deriving instance UniplateDirect (RPat S) (Exp S)
deriving instance UniplateDirect (PXAttr S) (Exp S)
deriving instance UniplateDirect (Maybe (Pat S)) (Exp S)
deriving instance UniplateDirect (Decl S) (Exp S)
deriving instance UniplateDirect (IPBind S) (Exp S)
deriving instance UniplateDirect (GuardedAlts S) (Exp S)
deriving instance UniplateDirect (Maybe (Binds S)) (Exp S)
deriving instance UniplateDirect (Maybe (Exp S)) (Exp S)
deriving instance UniplateDirect (FieldUpdate S) (Exp S)
deriving instance UniplateDirect (PatField S) (Pat S)
deriving instance UniplateDirect (Exp S) (Pat S)
deriving instance UniplateDirect (RPat S) (Pat S)
deriving instance UniplateDirect (PXAttr S) (Pat S)
deriving instance UniplateDirect (Maybe (Pat S)) (Pat S)
deriving instance UniplateDirect (PatField S) (Exp S)
deriving instance UniplateDirect (RPat S) (Exp S)
deriving instance UniplateDirect (PXAttr S) (Exp S)
deriving instance UniplateDirect (Maybe (Pat S)) (Exp S)
deriving instance UniplateDirect (Decl S) (Exp S)
deriving instance UniplateDirect (IPBind S) (Exp S)
deriving instance UniplateDirect (GuardedAlts S) (Exp S)
deriving instance UniplateDirect (Maybe (Binds S)) (Exp S)
deriving instance UniplateDirect (Binds S) (Pat S)
deriving instance UniplateDirect (Alt S) (Pat S)
deriving instance UniplateDirect (Stmt S) (Pat S)
deriving instance UniplateDirect (Maybe (Exp S)) (Pat S)
deriving instance UniplateDirect (FieldUpdate S) (Pat S)
deriving instance UniplateDirect (QualStmt S) (Pat S)
deriving instance UniplateDirect [QualStmt S] (Pat S)
deriving instance UniplateDirect (Bracket S) (Pat S)
deriving instance UniplateDirect (Splice S) (Pat S)
deriving instance UniplateDirect (XAttr S) (Pat S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Exp S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Exp S)
deriving instance UniplateDirect (Match S) (Exp S)
deriving instance UniplateDirect (Rhs S) (Exp S)
deriving instance UniplateDirect (Rule S) (Exp S)
deriving instance UniplateDirect (GuardedAlt S) (Exp S)
deriving instance UniplateDirect (Decl S) (Pat S)
deriving instance UniplateDirect (IPBind S) (Pat S)
deriving instance UniplateDirect (GuardedAlts S) (Pat S)
deriving instance UniplateDirect (Maybe (Binds S)) (Pat S)
deriving instance UniplateDirect (ClassDecl S) (Exp S)
deriving instance UniplateDirect (InstDecl S) (Exp S)
deriving instance UniplateDirect (GuardedRhs S) (Exp S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Pat S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Pat S)
deriving instance UniplateDirect (Match S) (Pat S)
deriving instance UniplateDirect (Rhs S) (Pat S)
deriving instance UniplateDirect (Rule S) (Pat S)
deriving instance UniplateDirect (GuardedAlt S) (Pat S)
deriving instance UniplateDirect (ClassDecl S) (Pat S)
deriving instance UniplateDirect (InstDecl S) (Pat S)
deriving instance UniplateDirect (GuardedRhs S) (Pat S)
deriving instance UniplateDirect (Maybe (Binds S)) (Decl S)
deriving instance UniplateDirect (Exp S) (Name S)
deriving instance UniplateDirect (Decl S)
deriving instance UniplateDirect (Binds S) (Decl S)
deriving instance UniplateDirect (Name S)
deriving instance UniplateDirect (QName S) (Name S)
deriving instance UniplateDirect (QOp S) (Name S)
deriving instance UniplateDirect (Pat S) (Name S)
deriving instance UniplateDirect (Binds S) (Name S)
deriving instance UniplateDirect (Alt S) (Name S)
deriving instance UniplateDirect (Stmt S) (Name S)
deriving instance UniplateDirect (Maybe (Exp S)) (Name S)
deriving instance UniplateDirect (FieldUpdate S) (Name S)
deriving instance UniplateDirect (QualStmt S) (Name S)
deriving instance UniplateDirect [QualStmt S] (Name S)
deriving instance UniplateDirect (Type S) (Name S)
deriving instance UniplateDirect (Bracket S) (Name S)
deriving instance UniplateDirect (Splice S) (Name S)
deriving instance UniplateDirect (XAttr S) (Name S)
deriving instance UniplateDirect (Decl S) (Name S)
deriving instance UniplateDirect (Exp S) (Decl S)
deriving instance UniplateDirect (GuardedAlts S) (Name S)
deriving instance UniplateDirect (IPBind S) (Decl S)
deriving instance UniplateDirect (IPBind S) (Name S)
deriving instance UniplateDirect (Kind S) (Name S)
deriving instance UniplateDirect (Match S) (Decl S)
deriving instance UniplateDirect (Maybe (Binds S)) (Name S)
deriving instance UniplateDirect (Maybe (Context S)) (Name S)
deriving instance UniplateDirect (Maybe (Pat S)) (Name S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Decl S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Decl S)
deriving instance UniplateDirect (Maybe [TyVarBind S]) (Name S)
deriving instance UniplateDirect (PXAttr S) (Name S)
deriving instance UniplateDirect (Pat S) (Decl S)
deriving instance UniplateDirect (PatField S) (Name S)
deriving instance UniplateDirect (RPat S) (Name S)
deriving instance UniplateDirect (Rhs S) (Decl S)
deriving instance UniplateDirect (Rule S) (Decl S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Name S)
deriving instance UniplateDirect (InstHead S) (Name S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Name S)
deriving instance UniplateDirect (Op S) (Name S)
deriving instance UniplateDirect (Match S) (Name S)
deriving instance UniplateDirect (Maybe (Type S)) (Name S)
deriving instance UniplateDirect (Rhs S) (Name S)
deriving instance UniplateDirect (Rule S) (Name S)
deriving instance UniplateDirect ([Name S], String) (Name S)
deriving instance UniplateDirect (Alt S) (Decl S)
deriving instance UniplateDirect (Stmt S) (Decl S)
deriving instance UniplateDirect (Maybe (Exp S)) (Decl S)
deriving instance UniplateDirect (FieldUpdate S) (Decl S)
deriving instance UniplateDirect (QualStmt S) (Decl S)
deriving instance UniplateDirect [QualStmt S] (Decl S)
deriving instance UniplateDirect (Bracket S) (Decl S)
deriving instance UniplateDirect (Splice S) (Decl S)
deriving instance UniplateDirect (XAttr S) (Decl S)
deriving instance UniplateDirect (GuardedAlt S) (Name S)
deriving instance UniplateDirect (Context S) (Name S)
deriving instance UniplateDirect (ClassDecl S) (Decl S)
deriving instance UniplateDirect (InstDecl S) (Decl S)
deriving instance UniplateDirect (TyVarBind S) (Name S)
deriving instance UniplateDirect (PatField S) (Decl S)
deriving instance UniplateDirect (RPat S) (Decl S)
deriving instance UniplateDirect (PXAttr S) (Decl S)
deriving instance UniplateDirect (Maybe (Pat S)) (Decl S)
deriving instance UniplateDirect (GuardedRhs S) (Decl S)
deriving instance UniplateDirect (DeclHead S) (Name S)
deriving instance UniplateDirect (Maybe (Kind S)) (Name S)
deriving instance UniplateDirect (QualConDecl S) (Name S)
deriving instance UniplateDirect (Maybe (Deriving S)) (Name S)
deriving instance UniplateDirect (GadtDecl S) (Name S)
deriving instance UniplateDirect (FunDep S) (Name S)
deriving instance UniplateDirect (ClassDecl S) (Name S)
deriving instance UniplateDirect (InstDecl S) (Name S)
deriving instance UniplateDirect (GuardedRhs S) (Name S)
deriving instance UniplateDirect (Maybe [RuleVar S]) (Name S)
deriving instance UniplateDirect (GuardedAlts S) (Decl S)
deriving instance UniplateDirect (Asst S) (Name S)
deriving instance UniplateDirect (ConDecl S) (Name S)
deriving instance UniplateDirect (Deriving S) (Name S)
deriving instance UniplateDirect (RuleVar S) (Name S)
deriving instance UniplateDirect (GuardedAlt S) (Decl S)
deriving instance UniplateDirect (BangType S) (Name S)
deriving instance UniplateDirect (FieldDecl S) (Name S)
deriving instance UniplateDirect (Module S) (FunDep S)
deriving instance UniplateDirect (Module S) (IPName S)
deriving instance UniplateDirect (Module S) (Decl S)
deriving instance UniplateDirect (Module S) (Kind S)
deriving instance UniplateDirect (Module S) (Pat S)
deriving instance UniplateDirect (Module S) (CallConv S)
deriving instance UniplateDirect (Module S) (GuardedRhs S)
deriving instance UniplateDirect (Module S) (GuardedAlt S)
deriving instance UniplateDirect (Module S) (PatField S)
deriving instance UniplateDirect (Module S) Boxed
deriving instance UniplateDirect (Module S) (ImportDecl S)
deriving instance UniplateDirect (Module S) (Exp S)
deriving instance UniplateDirect (Module S) (QualStmt S)
deriving instance UniplateDirect (Exp S) (CallConv S)
deriving instance UniplateDirect (GuardedRhs S)
deriving instance UniplateDirect (Decl S) (GuardedRhs S)
deriving instance UniplateDirect (XAttr S) (GuardedRhs S)
deriving instance UniplateDirect (Maybe (Exp S)) (GuardedRhs S)
deriving instance UniplateDirect (Exp S) (GuardedRhs S)
deriving instance UniplateDirect (GuardedAlt S)
deriving instance UniplateDirect (Decl S) (GuardedAlt S)
deriving instance UniplateDirect (XAttr S) (GuardedAlt S)
deriving instance UniplateDirect (Maybe (Exp S)) (GuardedAlt S)
deriving instance UniplateDirect (Exp S) (GuardedAlt S)
deriving instance UniplateDirect (PatField S)
deriving instance UniplateDirect (Decl S) (PatField S)
deriving instance UniplateDirect (XAttr S) (PatField S)
deriving instance UniplateDirect (Maybe (Exp S)) (PatField S)
deriving instance UniplateDirect (Exp S) (PatField S)
deriving instance UniplateDirect Boxed
deriving instance UniplateDirect (Maybe (ModuleHead S)) Boxed
deriving instance UniplateDirect (Decl S) Boxed
deriving instance UniplateDirect (XAttr S) Boxed
deriving instance UniplateDirect (Maybe (Exp S)) Boxed
deriving instance UniplateDirect (Exp S) Boxed
deriving instance UniplateDirect (ImportDecl S)
deriving instance UniplateDirect (QualStmt S)
deriving instance UniplateDirect (Decl S) (QualStmt S)
deriving instance UniplateDirect (XAttr S) (QualStmt S)
deriving instance UniplateDirect (Maybe (Exp S)) (QualStmt S)
deriving instance UniplateDirect (Exp S) (QualStmt S)
deriving instance UniplateDirect (Maybe (Type S)) Boxed
deriving instance UniplateDirect (Rhs S) Boxed
deriving instance UniplateDirect (Maybe (Binds S)) Boxed
deriving instance UniplateDirect (Rule S) Boxed
deriving instance UniplateDirect (QName S) Boxed
deriving instance UniplateDirect (QOp S) Boxed
deriving instance UniplateDirect (Binds S) Boxed
deriving instance UniplateDirect (Alt S) Boxed
deriving instance UniplateDirect (Stmt S) Boxed
deriving instance UniplateDirect (FieldUpdate S) Boxed
deriving instance UniplateDirect (QualStmt S) Boxed
deriving instance UniplateDirect [QualStmt S] Boxed
deriving instance UniplateDirect (Bracket S) Boxed
deriving instance UniplateDirect (Splice S) Boxed
deriving instance UniplateDirect (Stmt S) (QualStmt S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (QualStmt S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (QualStmt S)
deriving instance UniplateDirect (Match S) (QualStmt S)
deriving instance UniplateDirect (Pat S) (QualStmt S)
deriving instance UniplateDirect (Rhs S) (QualStmt S)
deriving instance UniplateDirect (Maybe (Binds S)) (QualStmt S)
deriving instance UniplateDirect (Rule S) (QualStmt S)
deriving instance UniplateDirect (Binds S) (QualStmt S)
deriving instance UniplateDirect (Alt S) (QualStmt S)
deriving instance UniplateDirect (FieldUpdate S) (QualStmt S)
deriving instance UniplateDirect [QualStmt S] (QualStmt S)
deriving instance UniplateDirect (Bracket S) (QualStmt S)
deriving instance UniplateDirect (Splice S) (QualStmt S)
deriving instance UniplateDirect (FunDep S)
deriving instance UniplateDirect (Decl S) (FunDep S)
deriving instance UniplateDirect (XAttr S) (FunDep S)
deriving instance UniplateDirect (Maybe (Exp S)) (FunDep S)
deriving instance UniplateDirect (Exp S) (FunDep S)
deriving instance UniplateDirect (IPName S)
deriving instance UniplateDirect (Decl S) (IPName S)
deriving instance UniplateDirect (XAttr S) (IPName S)
deriving instance UniplateDirect (Maybe (Exp S)) (IPName S)
deriving instance UniplateDirect (Exp S) (IPName S)
deriving instance UniplateDirect (Kind S)
deriving instance UniplateDirect (Decl S) (Kind S)
deriving instance UniplateDirect (XAttr S) (Kind S)
deriving instance UniplateDirect (Maybe (Exp S)) (Kind S)
deriving instance UniplateDirect (Exp S) (Kind S)
deriving instance UniplateDirect (CallConv S)
deriving instance UniplateDirect (Decl S) (CallConv S)
deriving instance UniplateDirect (XAttr S) (CallConv S)
deriving instance UniplateDirect (Maybe (Exp S)) (CallConv S)
deriving instance UniplateDirect (CallConv S)
deriving instance UniplateDirect (Pat S) (CallConv S)
deriving instance UniplateDirect (Binds S) (CallConv S)
deriving instance UniplateDirect (Alt S) (CallConv S)
deriving instance UniplateDirect (Stmt S) (CallConv S)
deriving instance UniplateDirect (FieldUpdate S) (CallConv S)
deriving instance UniplateDirect (QualStmt S) (CallConv S)
deriving instance UniplateDirect [QualStmt S] (CallConv S)
deriving instance UniplateDirect (Bracket S) (CallConv S)
deriving instance UniplateDirect (Splice S) (CallConv S)
deriving instance UniplateDirect (Stmt S) (GuardedRhs S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (GuardedRhs S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (GuardedRhs S)
deriving instance UniplateDirect (Match S) (GuardedRhs S)
deriving instance UniplateDirect (Pat S) (GuardedRhs S)
deriving instance UniplateDirect (Rhs S) (GuardedRhs S)
deriving instance UniplateDirect (Maybe (Binds S)) (GuardedRhs S)
deriving instance UniplateDirect (Rule S) (GuardedRhs S)
deriving instance UniplateDirect (Binds S) (GuardedRhs S)
deriving instance UniplateDirect (Alt S) (GuardedRhs S)
deriving instance UniplateDirect (FieldUpdate S) (GuardedRhs S)
deriving instance UniplateDirect (QualStmt S) (GuardedRhs S)
deriving instance UniplateDirect [QualStmt S] (GuardedRhs S)
deriving instance UniplateDirect (Bracket S) (GuardedRhs S)
deriving instance UniplateDirect (Splice S) (GuardedRhs S)
deriving instance UniplateDirect (Stmt S) (GuardedAlt S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (GuardedAlt S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (GuardedAlt S)
deriving instance UniplateDirect (Match S) (GuardedAlt S)
deriving instance UniplateDirect (Pat S) (GuardedAlt S)
deriving instance UniplateDirect (Rhs S) (GuardedAlt S)
deriving instance UniplateDirect (Maybe (Binds S)) (GuardedAlt S)
deriving instance UniplateDirect (Rule S) (GuardedAlt S)
deriving instance UniplateDirect (Binds S) (GuardedAlt S)
deriving instance UniplateDirect (Alt S) (GuardedAlt S)
deriving instance UniplateDirect (FieldUpdate S) (GuardedAlt S)
deriving instance UniplateDirect (QualStmt S) (GuardedAlt S)
deriving instance UniplateDirect [QualStmt S] (GuardedAlt S)
deriving instance UniplateDirect (Bracket S) (GuardedAlt S)
deriving instance UniplateDirect (Splice S) (GuardedAlt S)
deriving instance UniplateDirect (Pat S) (PatField S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (PatField S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (PatField S)
deriving instance UniplateDirect (Match S) (PatField S)
deriving instance UniplateDirect (Rhs S) (PatField S)
deriving instance UniplateDirect (Maybe (Binds S)) (PatField S)
deriving instance UniplateDirect (Rule S) (PatField S)
deriving instance UniplateDirect (Binds S) (PatField S)
deriving instance UniplateDirect (Alt S) (PatField S)
deriving instance UniplateDirect (Stmt S) (PatField S)
deriving instance UniplateDirect (FieldUpdate S) (PatField S)
deriving instance UniplateDirect (QualStmt S) (PatField S)
deriving instance UniplateDirect [QualStmt S] (PatField S)
deriving instance UniplateDirect (Bracket S) (PatField S)
deriving instance UniplateDirect (Splice S) (PatField S)
deriving instance UniplateDirect (ModuleHead S) Boxed
deriving instance UniplateDirect (Type S) Boxed
deriving instance UniplateDirect (Maybe (Context S)) Boxed
deriving instance UniplateDirect (QualConDecl S) Boxed
deriving instance UniplateDirect (Maybe (Deriving S)) Boxed
deriving instance UniplateDirect (GadtDecl S) Boxed
deriving instance UniplateDirect (Maybe [ClassDecl S]) Boxed
deriving instance UniplateDirect (InstHead S) Boxed
deriving instance UniplateDirect (Maybe [InstDecl S]) Boxed
deriving instance UniplateDirect (Match S) Boxed
deriving instance UniplateDirect (Pat S) Boxed
deriving instance UniplateDirect (GuardedRhs S) Boxed
deriving instance UniplateDirect (Maybe [RuleVar S]) Boxed
deriving instance UniplateDirect (SpecialCon S) Boxed
deriving instance UniplateDirect (IPBind S) Boxed
deriving instance UniplateDirect (GuardedAlts S) Boxed
deriving instance UniplateDirect (ClassDecl S) (QualStmt S)
deriving instance UniplateDirect (InstDecl S) (QualStmt S)
deriving instance UniplateDirect (PatField S) (QualStmt S)
deriving instance UniplateDirect (RPat S) (QualStmt S)
deriving instance UniplateDirect (PXAttr S) (QualStmt S)
deriving instance UniplateDirect (Maybe (Pat S)) (QualStmt S)
deriving instance UniplateDirect (GuardedRhs S) (QualStmt S)
deriving instance UniplateDirect (IPBind S) (QualStmt S)
deriving instance UniplateDirect (GuardedAlts S) (QualStmt S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (FunDep S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (FunDep S)
deriving instance UniplateDirect (Match S) (FunDep S)
deriving instance UniplateDirect (Pat S) (FunDep S)
deriving instance UniplateDirect (Rhs S) (FunDep S)
deriving instance UniplateDirect (Maybe (Binds S)) (FunDep S)
deriving instance UniplateDirect (Rule S) (FunDep S)
deriving instance UniplateDirect (Binds S) (FunDep S)
deriving instance UniplateDirect (Alt S) (FunDep S)
deriving instance UniplateDirect (Stmt S) (FunDep S)
deriving instance UniplateDirect (FieldUpdate S) (FunDep S)
deriving instance UniplateDirect (QualStmt S) (FunDep S)
deriving instance UniplateDirect [QualStmt S] (FunDep S)
deriving instance UniplateDirect (Bracket S) (FunDep S)
deriving instance UniplateDirect (Splice S) (FunDep S)
deriving instance UniplateDirect (Type S) (IPName S)
deriving instance UniplateDirect (Maybe (Context S)) (IPName S)
deriving instance UniplateDirect (QualConDecl S) (IPName S)
deriving instance UniplateDirect (Maybe (Deriving S)) (IPName S)
deriving instance UniplateDirect (GadtDecl S) (IPName S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (IPName S)
deriving instance UniplateDirect (InstHead S) (IPName S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (IPName S)
deriving instance UniplateDirect (Match S) (IPName S)
deriving instance UniplateDirect (Pat S) (IPName S)
deriving instance UniplateDirect (Maybe (Type S)) (IPName S)
deriving instance UniplateDirect (Rhs S) (IPName S)
deriving instance UniplateDirect (Maybe (Binds S)) (IPName S)
deriving instance UniplateDirect (Rule S) (IPName S)
deriving instance UniplateDirect (Binds S) (IPName S)
deriving instance UniplateDirect (Alt S) (IPName S)
deriving instance UniplateDirect (Stmt S) (IPName S)
deriving instance UniplateDirect (FieldUpdate S) (IPName S)
deriving instance UniplateDirect (QualStmt S) (IPName S)
deriving instance UniplateDirect [QualStmt S] (IPName S)
deriving instance UniplateDirect (Bracket S) (IPName S)
deriving instance UniplateDirect (Splice S) (IPName S)
deriving instance UniplateDirect (DeclHead S) (Kind S)
deriving instance UniplateDirect (Type S) (Kind S)
deriving instance UniplateDirect (Maybe (Kind S)) (Kind S)
deriving instance UniplateDirect (Maybe (Context S)) (Kind S)
deriving instance UniplateDirect (QualConDecl S) (Kind S)
deriving instance UniplateDirect (Maybe (Deriving S)) (Kind S)
deriving instance UniplateDirect (GadtDecl S) (Kind S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Kind S)
deriving instance UniplateDirect (InstHead S) (Kind S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Kind S)
deriving instance UniplateDirect (Match S) (Kind S)
deriving instance UniplateDirect (Pat S) (Kind S)
deriving instance UniplateDirect (Maybe (Type S)) (Kind S)
deriving instance UniplateDirect (Rhs S) (Kind S)
deriving instance UniplateDirect (Maybe (Binds S)) (Kind S)
deriving instance UniplateDirect (Rule S) (Kind S)
deriving instance UniplateDirect (Binds S) (Kind S)
deriving instance UniplateDirect (Alt S) (Kind S)
deriving instance UniplateDirect (Stmt S) (Kind S)
deriving instance UniplateDirect (FieldUpdate S) (Kind S)
deriving instance UniplateDirect (QualStmt S) (Kind S)
deriving instance UniplateDirect [QualStmt S] (Kind S)
deriving instance UniplateDirect (Bracket S) (Kind S)
deriving instance UniplateDirect (Splice S) (Kind S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (CallConv S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (CallConv S)
deriving instance UniplateDirect (Match S) (CallConv S)
deriving instance UniplateDirect (Rhs S) (CallConv S)
deriving instance UniplateDirect (Maybe (Binds S)) (CallConv S)
deriving instance UniplateDirect (Rule S) (CallConv S)
deriving instance UniplateDirect (PatField S) (CallConv S)
deriving instance UniplateDirect (RPat S) (CallConv S)
deriving instance UniplateDirect (PXAttr S) (CallConv S)
deriving instance UniplateDirect (Maybe (Pat S)) (CallConv S)
deriving instance UniplateDirect (IPBind S) (CallConv S)
deriving instance UniplateDirect (GuardedAlts S) (CallConv S)
deriving instance UniplateDirect (ClassDecl S) (GuardedRhs S)
deriving instance UniplateDirect (InstDecl S) (GuardedRhs S)
deriving instance UniplateDirect (PatField S) (GuardedRhs S)
deriving instance UniplateDirect (RPat S) (GuardedRhs S)
deriving instance UniplateDirect (PXAttr S) (GuardedRhs S)
deriving instance UniplateDirect (Maybe (Pat S)) (GuardedRhs S)
deriving instance UniplateDirect (IPBind S) (GuardedRhs S)
deriving instance UniplateDirect (GuardedAlts S) (GuardedRhs S)
deriving instance UniplateDirect (ClassDecl S) (GuardedAlt S)
deriving instance UniplateDirect (InstDecl S) (GuardedAlt S)
deriving instance UniplateDirect (PatField S) (GuardedAlt S)
deriving instance UniplateDirect (RPat S) (GuardedAlt S)
deriving instance UniplateDirect (PXAttr S) (GuardedAlt S)
deriving instance UniplateDirect (Maybe (Pat S)) (GuardedAlt S)
deriving instance UniplateDirect (GuardedRhs S) (GuardedAlt S)
deriving instance UniplateDirect (IPBind S) (GuardedAlt S)
deriving instance UniplateDirect (GuardedAlts S) (GuardedAlt S)
deriving instance UniplateDirect (RPat S) (PatField S)
deriving instance UniplateDirect (PXAttr S) (PatField S)
deriving instance UniplateDirect (Maybe (Pat S)) (PatField S)
deriving instance UniplateDirect (ClassDecl S) (PatField S)
deriving instance UniplateDirect (InstDecl S) (PatField S)
deriving instance UniplateDirect (GuardedRhs S) (PatField S)
deriving instance UniplateDirect (IPBind S) (PatField S)
deriving instance UniplateDirect (GuardedAlts S) (PatField S)
deriving instance UniplateDirect (Maybe (ExportSpecList S)) Boxed
deriving instance UniplateDirect (Context S) Boxed
deriving instance UniplateDirect (ConDecl S) Boxed
deriving instance UniplateDirect (Deriving S) Boxed
deriving instance UniplateDirect (ClassDecl S) Boxed
deriving instance UniplateDirect (InstDecl S) Boxed
deriving instance UniplateDirect (PatField S) Boxed
deriving instance UniplateDirect (RPat S) Boxed
deriving instance UniplateDirect (PXAttr S) Boxed
deriving instance UniplateDirect (Maybe (Pat S)) Boxed
deriving instance UniplateDirect (RuleVar S) Boxed
deriving instance UniplateDirect (GuardedAlt S) Boxed
deriving instance UniplateDirect (GuardedAlt S) (QualStmt S)
deriving instance UniplateDirect (ClassDecl S) (FunDep S)
deriving instance UniplateDirect (InstDecl S) (FunDep S)
deriving instance UniplateDirect (PatField S) (FunDep S)
deriving instance UniplateDirect (RPat S) (FunDep S)
deriving instance UniplateDirect (PXAttr S) (FunDep S)
deriving instance UniplateDirect (Maybe (Pat S)) (FunDep S)
deriving instance UniplateDirect (GuardedRhs S) (FunDep S)
deriving instance UniplateDirect (IPBind S) (FunDep S)
deriving instance UniplateDirect (GuardedAlts S) (FunDep S)
deriving instance UniplateDirect (Context S) (IPName S)
deriving instance UniplateDirect (ConDecl S) (IPName S)
deriving instance UniplateDirect (Deriving S) (IPName S)
deriving instance UniplateDirect (ClassDecl S) (IPName S)
deriving instance UniplateDirect (InstDecl S) (IPName S)
deriving instance UniplateDirect (PatField S) (IPName S)
deriving instance UniplateDirect (RPat S) (IPName S)
deriving instance UniplateDirect (PXAttr S) (IPName S)
deriving instance UniplateDirect (Maybe (Pat S)) (IPName S)
deriving instance UniplateDirect (GuardedRhs S) (IPName S)
deriving instance UniplateDirect (Maybe [RuleVar S]) (IPName S)
deriving instance UniplateDirect (IPBind S) (IPName S)
deriving instance UniplateDirect (GuardedAlts S) (IPName S)
deriving instance UniplateDirect (TyVarBind S) (Kind S)
deriving instance UniplateDirect (Maybe [TyVarBind S]) (Kind S)
deriving instance UniplateDirect (Context S) (Kind S)
deriving instance UniplateDirect (ConDecl S) (Kind S)
deriving instance UniplateDirect (Deriving S) (Kind S)
deriving instance UniplateDirect (ClassDecl S) (Kind S)
deriving instance UniplateDirect (InstDecl S) (Kind S)
deriving instance UniplateDirect (PatField S) (Kind S)
deriving instance UniplateDirect (RPat S) (Kind S)
deriving instance UniplateDirect (PXAttr S) (Kind S)
deriving instance UniplateDirect (Maybe (Pat S)) (Kind S)
deriving instance UniplateDirect (GuardedRhs S) (Kind S)
deriving instance UniplateDirect (Maybe [RuleVar S]) (Kind S)
deriving instance UniplateDirect (IPBind S) (Kind S)
deriving instance UniplateDirect (GuardedAlts S) (Kind S)
deriving instance UniplateDirect (ClassDecl S) (CallConv S)
deriving instance UniplateDirect (InstDecl S) (CallConv S)
deriving instance UniplateDirect (GuardedRhs S) (CallConv S)
deriving instance UniplateDirect (GuardedAlt S) (CallConv S)
deriving instance UniplateDirect (GuardedAlt S) (GuardedRhs S)
deriving instance UniplateDirect (GuardedAlt S) (PatField S)
deriving instance UniplateDirect (ExportSpecList S) Boxed
deriving instance UniplateDirect (Asst S) Boxed
deriving instance UniplateDirect (BangType S) Boxed
deriving instance UniplateDirect (FieldDecl S) Boxed
deriving instance UniplateDirect (GuardedAlt S) (FunDep S)
deriving instance UniplateDirect (Asst S) (IPName S)
deriving instance UniplateDirect (BangType S) (IPName S)
deriving instance UniplateDirect (FieldDecl S) (IPName S)
deriving instance UniplateDirect (RuleVar S) (IPName S)
deriving instance UniplateDirect (GuardedAlt S) (IPName S)
deriving instance UniplateDirect (Asst S) (Kind S)
deriving instance UniplateDirect (BangType S) (Kind S)
deriving instance UniplateDirect (FieldDecl S) (Kind S)
deriving instance UniplateDirect (RuleVar S) (Kind S)
deriving instance UniplateDirect (GuardedAlt S) (Kind S)
deriving instance UniplateDirect (ExportSpec S) Boxed
deriving instance UniplateDirect (Module S) (Splice S)
deriving instance UniplateDirect (Module S) (Bracket S)
deriving instance UniplateDirect (Splice S)
deriving instance UniplateDirect (Decl S) (Splice S)
deriving instance UniplateDirect (XAttr S) (Splice S)
deriving instance UniplateDirect (Maybe (Exp S)) (Splice S)
deriving instance UniplateDirect (Exp S) (Splice S)
deriving instance UniplateDirect (Bracket S)
deriving instance UniplateDirect (Decl S) (Bracket S)
deriving instance UniplateDirect (XAttr S) (Bracket S)
deriving instance UniplateDirect (Maybe (Exp S)) (Bracket S)
deriving instance UniplateDirect (Exp S) (Bracket S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Splice S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Splice S)
deriving instance UniplateDirect (Match S) (Splice S)
deriving instance UniplateDirect (Pat S) (Splice S)
deriving instance UniplateDirect (Rhs S) (Splice S)
deriving instance UniplateDirect (Maybe (Binds S)) (Splice S)
deriving instance UniplateDirect (Rule S) (Splice S)
deriving instance UniplateDirect (Binds S) (Splice S)
deriving instance UniplateDirect (Alt S) (Splice S)
deriving instance UniplateDirect (Stmt S) (Splice S)
deriving instance UniplateDirect (FieldUpdate S) (Splice S)
deriving instance UniplateDirect (QualStmt S) (Splice S)
deriving instance UniplateDirect [QualStmt S] (Splice S)
deriving instance UniplateDirect (Bracket S) (Splice S)
deriving instance UniplateDirect (Pat S) (Bracket S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Bracket S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Bracket S)
deriving instance UniplateDirect (Match S) (Bracket S)
deriving instance UniplateDirect (Rhs S) (Bracket S)
deriving instance UniplateDirect (Maybe (Binds S)) (Bracket S)
deriving instance UniplateDirect (Rule S) (Bracket S)
deriving instance UniplateDirect (Binds S) (Bracket S)
deriving instance UniplateDirect (Alt S) (Bracket S)
deriving instance UniplateDirect (Stmt S) (Bracket S)
deriving instance UniplateDirect (FieldUpdate S) (Bracket S)
deriving instance UniplateDirect (QualStmt S) (Bracket S)
deriving instance UniplateDirect [QualStmt S] (Bracket S)
deriving instance UniplateDirect (Splice S) (Bracket S)
deriving instance UniplateDirect (ClassDecl S) (Splice S)
deriving instance UniplateDirect (InstDecl S) (Splice S)
deriving instance UniplateDirect (PatField S) (Splice S)
deriving instance UniplateDirect (RPat S) (Splice S)
deriving instance UniplateDirect (PXAttr S) (Splice S)
deriving instance UniplateDirect (Maybe (Pat S)) (Splice S)
deriving instance UniplateDirect (GuardedRhs S) (Splice S)
deriving instance UniplateDirect (IPBind S) (Splice S)
deriving instance UniplateDirect (GuardedAlts S) (Splice S)
deriving instance UniplateDirect (PatField S) (Bracket S)
deriving instance UniplateDirect (RPat S) (Bracket S)
deriving instance UniplateDirect (PXAttr S) (Bracket S)
deriving instance UniplateDirect (Maybe (Pat S)) (Bracket S)
deriving instance UniplateDirect (ClassDecl S) (Bracket S)
deriving instance UniplateDirect (InstDecl S) (Bracket S)
deriving instance UniplateDirect (GuardedRhs S) (Bracket S)
deriving instance UniplateDirect (IPBind S) (Bracket S)
deriving instance UniplateDirect (GuardedAlts S) (Bracket S)
deriving instance UniplateDirect (GuardedAlt S) (Splice S)
deriving instance UniplateDirect (GuardedAlt S) (Bracket S)
deriving instance UniplateDirect (Exp S) (Exp S)
deriving instance UniplateDirect [Pat S] (Pat S)
deriving instance UniplateDirect (Module S) (Name S)
deriving instance UniplateDirect (Maybe (ModuleHead S)) (Name S)
deriving instance UniplateDirect (OptionPragma S) (Name S)
deriving instance UniplateDirect (ImportDecl S) (Name S)
deriving instance UniplateDirect (ModuleHead S) (Name S)
deriving instance UniplateDirect (Maybe (ImportSpecList S)) (Name S)
deriving instance UniplateDirect (Maybe (ExportSpecList S)) (Name S)
deriving instance UniplateDirect (ImportSpecList S) (Name S)
deriving instance UniplateDirect (ExportSpecList S) (Name S)
deriving instance UniplateDirect (ImportSpec S) (Name S)
deriving instance UniplateDirect (ExportSpec S) (Name S)
deriving instance UniplateDirect (CName S) (Name S)
deriving instance UniplateDirect [Stmt S] (Exp S)
deriving instance UniplateDirect (Decl S) (Type S)
deriving instance UniplateDirect (Type S)
deriving instance UniplateDirect (Maybe (Context S)) (Type S)
deriving instance UniplateDirect (QualConDecl S) (Type S)
deriving instance UniplateDirect (Maybe (Deriving S)) (Type S)
deriving instance UniplateDirect (GadtDecl S) (Type S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (Type S)
deriving instance UniplateDirect (InstHead S) (Type S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (Type S)
deriving instance UniplateDirect (Exp S) (Type S)
deriving instance UniplateDirect (Match S) (Type S)
deriving instance UniplateDirect (Pat S) (Type S)
deriving instance UniplateDirect (Maybe (Type S)) (Type S)
deriving instance UniplateDirect (Rhs S) (Type S)
deriving instance UniplateDirect (Maybe (Binds S)) (Type S)
deriving instance UniplateDirect (Rule S) (Type S)
deriving instance UniplateDirect (Context S) (Type S)
deriving instance UniplateDirect (ConDecl S) (Type S)
deriving instance UniplateDirect (Deriving S) (Type S)
deriving instance UniplateDirect (ClassDecl S) (Type S)
deriving instance UniplateDirect (InstDecl S) (Type S)
deriving instance UniplateDirect (Binds S) (Type S)
deriving instance UniplateDirect (Alt S) (Type S)
deriving instance UniplateDirect (Stmt S) (Type S)
deriving instance UniplateDirect (Maybe (Exp S)) (Type S)
deriving instance UniplateDirect (FieldUpdate S) (Type S)
deriving instance UniplateDirect (QualStmt S) (Type S)
deriving instance UniplateDirect [QualStmt S] (Type S)
deriving instance UniplateDirect (Bracket S) (Type S)
deriving instance UniplateDirect (Splice S) (Type S)
deriving instance UniplateDirect (XAttr S) (Type S)
deriving instance UniplateDirect (PatField S) (Type S)
deriving instance UniplateDirect (RPat S) (Type S)
deriving instance UniplateDirect (PXAttr S) (Type S)
deriving instance UniplateDirect (Maybe (Pat S)) (Type S)
deriving instance UniplateDirect (GuardedRhs S) (Type S)
deriving instance UniplateDirect (Maybe [RuleVar S]) (Type S)
deriving instance UniplateDirect (Asst S) (Type S)
deriving instance UniplateDirect (BangType S) (Type S)
deriving instance UniplateDirect (FieldDecl S) (Type S)
deriving instance UniplateDirect (IPBind S) (Type S)
deriving instance UniplateDirect (GuardedAlts S) (Type S)
deriving instance UniplateDirect (RuleVar S) (Type S)
deriving instance UniplateDirect (GuardedAlt S) (Type S)
deriving instance UniplateDirect (Exp S) (QName S)
deriving instance UniplateDirect (QName S)
deriving instance UniplateDirect (QOp S) (QName S)
deriving instance UniplateDirect (Pat S) (QName S)
deriving instance UniplateDirect (Binds S) (QName S)
deriving instance UniplateDirect (Alt S) (QName S)
deriving instance UniplateDirect (Stmt S) (QName S)
deriving instance UniplateDirect (Maybe (Exp S)) (QName S)
deriving instance UniplateDirect (FieldUpdate S) (QName S)
deriving instance UniplateDirect (QualStmt S) (QName S)
deriving instance UniplateDirect [QualStmt S] (QName S)
deriving instance UniplateDirect (Type S) (QName S)
deriving instance UniplateDirect (Bracket S) (QName S)
deriving instance UniplateDirect (Splice S) (QName S)
deriving instance UniplateDirect (XAttr S) (QName S)
deriving instance UniplateDirect (PatField S) (QName S)
deriving instance UniplateDirect (RPat S) (QName S)
deriving instance UniplateDirect (PXAttr S) (QName S)
deriving instance UniplateDirect (Maybe (Pat S)) (QName S)
deriving instance UniplateDirect (Decl S) (QName S)
deriving instance UniplateDirect (IPBind S) (QName S)
deriving instance UniplateDirect (GuardedAlts S) (QName S)
deriving instance UniplateDirect (Maybe (Binds S)) (QName S)
deriving instance UniplateDirect (Maybe (Context S)) (QName S)
deriving instance UniplateDirect (QualConDecl S) (QName S)
deriving instance UniplateDirect (Maybe (Deriving S)) (QName S)
deriving instance UniplateDirect (GadtDecl S) (QName S)
deriving instance UniplateDirect (Maybe [ClassDecl S]) (QName S)
deriving instance UniplateDirect (InstHead S) (QName S)
deriving instance UniplateDirect (Maybe [InstDecl S]) (QName S)
deriving instance UniplateDirect (Match S) (QName S)
deriving instance UniplateDirect (Maybe (Type S)) (QName S)
deriving instance UniplateDirect (Rhs S) (QName S)
deriving instance UniplateDirect (Rule S) (QName S)
deriving instance UniplateDirect (GuardedAlt S) (QName S)
deriving instance UniplateDirect (Context S) (QName S)
deriving instance UniplateDirect (ConDecl S) (QName S)
deriving instance UniplateDirect (Deriving S) (QName S)
deriving instance UniplateDirect (ClassDecl S) (QName S)
deriving instance UniplateDirect (InstDecl S) (QName S)
deriving instance UniplateDirect (GuardedRhs S) (QName S)
deriving instance UniplateDirect (Maybe [RuleVar S]) (QName S)
deriving instance UniplateDirect (Asst S) (QName S)
deriving instance UniplateDirect (BangType S) (QName S)
deriving instance UniplateDirect (FieldDecl S) (QName S)
deriving instance UniplateDirect (RuleVar S) (QName S)
!-}
| alphaHeavy/hlint | src/HSE/Type.hs | gpl-2.0 | 37,438 | 0 | 6 | 4,741 | 129 | 85 | 44 | 10 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-------------------------------------------------------------------------------
-- |
--
-- Rewrite/simplification of yesod-markdown written by ajdunlap.
--
-- Forked from <https://github.com/ajdunlap/yesod-markdown>.
--
-------------------------------------------------------------------------------
module Yesod.Markdown
( Markdown(..)
-- * Wrappers
, markdownToHtml
, markdownToHtmlTrusted
, markdownFromFile
-- * Conversions
, parseMarkdown
, writePandoc
, writePandocTrusted
-- * Option sets
, yesodDefaultWriterOptions
, yesodDefaultReaderOptions
-- * Form helper
, markdownField
)
where
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid (Monoid)
#endif
import Data.String (IsString)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Database.Persist (PersistField, SqlType(SqlString))
import Database.Persist.Sql (PersistFieldSql(..))
import System.Directory (doesFileExist)
import Text.Blaze (ToMarkup (toMarkup))
import Text.Blaze.Html (preEscapedToMarkup)
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Text.Hamlet (hamlet, Html)
import Text.Pandoc
import Text.Pandoc.Error
import Yesod.Core (RenderMessage, HandlerSite)
import Yesod.Form.Functions (parseHelper)
import Yesod.Form.Types
import Yesod.Core.Widget (toWidget)
import qualified Data.ByteString as B
import qualified Data.Text as T
newtype Markdown = Markdown { unMarkdown :: Text }
deriving (Eq, Ord, Show, Read, PersistField, IsString, Monoid)
instance PersistFieldSql Markdown where
sqlType _ = SqlString
instance ToMarkup Markdown where
-- | Sanitized by default
toMarkup = handleError . markdownToHtml
markdownField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Markdown
markdownField = Field
{ fieldParse = parseHelper $ Right . Markdown . T.filter (/= '\r')
, fieldView = \theId name attrs val _isReq -> toWidget
[hamlet|$newline never
<textarea id="#{theId}" name="#{name}" *{attrs}>#{either id unMarkdown val}
|]
, fieldEnctype = UrlEncoded
}
markdownToHtml :: Markdown -> Either PandocError Html
markdownToHtml = fmap (writePandoc yesodDefaultWriterOptions)
. parseMarkdown yesodDefaultReaderOptions
-- | No HTML sanitization
markdownToHtmlTrusted :: Markdown -> Either PandocError Html
markdownToHtmlTrusted = fmap (writePandocTrusted yesodDefaultWriterOptions)
. parseMarkdown yesodDefaultReaderOptions
-- | Returns the empty string if the file does not exist
markdownFromFile :: FilePath -> IO Markdown
markdownFromFile f = do
exists <- doesFileExist f
content <-
if exists
then readFileUtf8 f
else return ""
return $ Markdown content
where
readFileUtf8 :: FilePath -> IO Text
readFileUtf8 fp = do
bs <- B.readFile fp
return $ decodeUtf8With lenientDecode bs
writePandoc :: WriterOptions -> Pandoc -> Html
writePandoc wo = preEscapedToMarkup . sanitizeBalance . T.pack . writeHtmlString wo
writePandocTrusted :: WriterOptions -> Pandoc -> Html
writePandocTrusted wo = preEscapedToMarkup . writeHtmlString wo
parseMarkdown :: ReaderOptions -> Markdown -> Either PandocError Pandoc
parseMarkdown ro = readMarkdown ro . T.unpack . unMarkdown
-- | Defaults plus Html5, minus WrapText
yesodDefaultWriterOptions :: WriterOptions
yesodDefaultWriterOptions = def
{ writerHtml5 = True
, writerWrapText = False
, writerHighlight = True
}
-- | Defaults plus Smart and ParseRaw
yesodDefaultReaderOptions :: ReaderOptions
yesodDefaultReaderOptions = def
{ readerSmart = True
, readerParseRaw = True
}
| robgssp/yesod-markdown | src/Yesod/Markdown.hs | gpl-2.0 | 4,075 | 0 | 11 | 781 | 792 | 456 | 336 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, UndecidableInstances, FlexibleContexts #-}
module NFA.Nerode.Congruent.Instance where
import Autolib.Reader
import Autolib.ToDoc
import Convert.Language
import Autolib.Exp
import Autolib.NFA ( NFAC )
import Data.Typeable
data NFAC c Int => Instance c =
Instance { language :: Language c
, goal :: [c]
, wanted :: Int
, minimal_length :: Int
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Instance])
example :: Instance Char
example = Instance
{ language = Convert.Language.example
, goal = "ab"
, wanted = 4
, minimal_length = 6
}
-- local variables:
-- mode: haskell
-- end;
| Erdwolf/autotool-bonn | src/NFA/Nerode/Congruent/Instance.hs | gpl-2.0 | 757 | 0 | 9 | 209 | 168 | 102 | 66 | 21 | 1 |
{- hpodder component
Copyright (C) 2006-2008 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Config
Copyright : Copyright (C) 2006-2008 John Goerzen
License : GNU GPL, version 2 or above
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: portable
Written by John Goerzen, jgoerzen\@complete.org
-}
module Config where
import System.Directory
import Data.ConfigFile
import Control.Monad
import Data.Either.Utils
import System.Path
import Data.String.Utils(strip, split)
getFeedTmp =
do appdir <- getAppDir
return $ appdir ++ "/feedxfer"
bracketFeedCWD func =
do feeddir <- getFeedTmp
brackettmpdirCWD (feeddir ++ "/tmp-XXXXXX") func
getEnclTmp =
do appdir <- getAppDir
return $ appdir ++ "/enclosurexfer"
getAppDir = do appdir <- getAppUserDataDirectory "hpodder"
return appdir
getDBName =
do appdir <- getAppDir
return $ appdir ++ "/hpodder.db"
getDefaultCP =
do docsdir <- getUserDocumentsDirectory
let downloaddir = docsdir ++ "/podcasts"
return $ forceEither $
do cp <- add_section startingcp "general"
cp <- set cp "general" "showintro" "yes"
cp <- set cp "DEFAULT" "downloaddir" downloaddir
cp <- set cp "DEFAULT" "namingpatt"
"%(safecasttitle)s/%(safefilename)s"
cp <- set cp "DEFAULT" "maxthreads" "2"
cp <- set cp "DEFAULT" "progressinterval" "1"
cp <- set cp "DEFAULT" "podcastfaildays" "21"
cp <- set cp "DEFAULT" "podcastfailattempts" "15"
cp <- set cp "DEFAULT" "epfaildays" "21"
cp <- set cp "DEFAULT" "epfailattempts" "15"
cp <- set cp "DEFAULT" "renametypes" "audio/mpeg:.mp3,audio/mp3:.mp3,x-audio/mp3:.mp3"
cp <- set cp "DEFAULT" "postproctypes" "audio/mpeg,audio/mp3,x-audio/mp3"
cp <- set cp "DEFAULT" "gettypecommand" "file -b -i \"${EPFILENAME}\""
cp <- set cp "DEFAULT" "postproccommand" "mid3v2 -T \"${EPID}\" -A \"${CASTTITLE}\" -t \"${EPTITLE}\" --WOAF \"${EPURL}\" --WOAS \"${FEEDURL}\" \"${EPFILENAME}\""
return cp
startingcp = emptyCP {accessfunc = interpolatingAccess 10}
getCPName =
do appdir <- getAppDir
return $ appdir ++ "/hpodder.conf"
loadCP =
do cpname <- getCPName
defaultcp <- getDefaultCP
dfe <- doesFileExist cpname
if dfe
then do cp <- readfile defaultcp cpname
return $ forceEither cp
else return defaultcp
writeCP cp =
do cpname <- getCPName
writeFile cpname (to_string cp)
-- FIXME: these may be inefficient [PERFORMANCE]
getMaxThreads :: IO Int
getMaxThreads =
do cp <- loadCP
return $ read . forceEither $ get cp "general" "maxthreads"
getProgressInterval :: IO Int
getProgressInterval =
do cp <- loadCP
return $ read . forceEither $ get cp "general" "progressinterval"
getList :: ConfigParser -> String -> String -> Maybe [String]
getList cp sect key =
case get cp sect key of
Right x -> Just (splitit x)
Left _ -> Nothing
where splitit x = filter (/= "") . map strip . split "," $ x
| jgoerzen/hpodder | Config.hs | gpl-2.0 | 3,992 | 0 | 11 | 1,056 | 754 | 356 | 398 | 70 | 2 |
module FQuoter.Templating.TemplateParserSpec (main, spec) where
import Text.ParserCombinators.Parsec.Error
import Test.Hspec
import FQuoter.Templating.TemplateTypes
import FQuoter.Templating.TemplateParser
import FQuoter.Config.Config
main :: IO()
main = hspec spec
parse f = case parseTemplate f of
Left e -> error $ (show e)
Right x -> x
simpleOne = "%al"
simpleOne' = [One [] $ AuthorInfo AuthorLastName]
simpleModOne = "{cap}%t"
simpleModOne' = [One [Capital] $ SourceInfo SourceTitle]
simpleOr = "|%al|%an|"
simpleOr' = [Or [One [] $ AuthorInfo AuthorLastName] [One [] $ AuthorInfo AuthorNickName]]
simpleMany = "[%al]"
simpleMany' = [SomeAuthors All [One [] $ AuthorInfo AuthorLastName]]
simpleConstant = "constant!"
simpleConstant' = [One [] $ ConstantString simpleConstant]
defaultTemplate = currentTemplate $ buildDefaultConfig
defaultTree = [SomeAuthors (Only 2)
[Or [One [Capital] $ AuthorInfo AuthorLastName
,One [] (ConstantString ", ")
,One [Initial, Capital] $ AuthorInfo AuthorFirstName]
[One [Capital] $ AuthorInfo AuthorNickName]]
,One [] $ ConstantString " "
,Condition (SourceInfo $ SourceMetadata "Date")
[One [] $ ConstantString "("
,One [] (SourceInfo $ SourceMetadata "Date")
,One [] $ ConstantString ") "]
,One [Italics] $ (SourceInfo SourceTitle)
,One [] $ ConstantString ". "
,One [] (SourceInfo $ SourceMetadata "Place")
,One [] $ ConstantString " : "
,One [] (SourceInfo $ SourceMetadata "Publisher")
,One [] $ ConstantString "."]
spec = do
describe "Template strings are transformed in Template Tree." $ do
it "Read a simple template string with just one thing to display." $ do
parse simpleOne `shouldBe` simpleOne'
it "Read a template with just one thing to display, with modificator" $ do
parse simpleModOne `shouldBe` simpleModOne'
it "Read an Or case, with one thing to display or the other." $ do
parse simpleOr `shouldBe` simpleOr'
it "Read a multi-author display." $ do
parse simpleMany `shouldBe` simpleMany'
it "Read a constant." $ do
parse simpleConstant `shouldBe` simpleConstant'
describe "Default case can be handled." $ do
it "Display gives the default parsing tree." $ do
parse defaultTemplate `shouldBe` defaultTree
| Raveline/FQuoter | testsuite/FQuoter/Templating/TemplateParserSpec.hs | gpl-3.0 | 2,613 | 0 | 14 | 753 | 710 | 355 | 355 | 53 | 2 |
module ConfigParser where
{ import Char;
import ParseToken;
import Text.ParserCombinators.Parsec;
import Config;
type ConfigBuilder = Config -> Config;
parseConfig :: String -> IO (Either ParseError ConfigBuilder);
parseConfig fname
= do { input <- readFile fname;
return $ parse configParser fname (dropComments input)};
dropComments "" = "";
dropComments ('#' : xs) = dropComments (dropWhile (/= '\n') xs);
dropComments ('"' : xs) = '"' : copyToEOL xs;
dropComments (x : xs) = x : dropComments xs;
copyToEOL "" = "";
copyToEOL ('\n' : xs) = '\n' : dropComments xs;
copyToEOL (x : xs) = x : copyToEOL xs;
ws_char = oneOf (" \t");
ws = many ws_char;
ws1 = many1 ws_char;
configParser :: Parser ConfigBuilder;
configParser
= do { whiteSpace;
cs <- many
(do { c <- configLine;
newLine;
whiteSpace;
return c});
eof;
return (foldr (.) id cs)};
newLine = ws >> char '\n';
configLine :: Parser ConfigBuilder;
configLine
= do { (reserved "userdir" >> p_userDir)} <|>
(reserved "user" >> p_user)
<|> (reserved "group" >> p_group)
<|> (reserved "serveradmin" >> p_serverAdmin)
<|> (reserved "servername" >> p_serverName)
<|> (reserved "serveralias" >> p_serverAlias)
<|> (reserved "serversignature" >> p_ignoreString)
<|> (reserved "usecanonicalname" >> p_useCanonicalName)
<|> (reserved "documentroot" >> p_documentRoot)
<|> (reserved "servertype" >> p_ignoreString)
<|> (reserved "serverroot" >> p_ignoreString)
<|> (reserved "lockfile" >> p_ignoreString)
<|> (reserved "pidfile" >> p_ignoreString)
<|> (reserved "scoreboardfile" >> p_ignoreString)
<|> (reserved "keepalivetimeout" >> p_keepAliveTimeout)
<|> (reserved "keepalive" >> p_ignoreString)
<|> (reserved "maxkeepaliverequests" >> p_ignoreString)
<|> (reserved "maxspareservers" >> p_ignoreString)
<|> (reserved "minspareservers" >> p_ignoreString)
<|> (reserved "startservers" >> p_ignoreString)
<|> (reserved "maxrequestsperchild" >> p_ignoreString)
<|> (reserved "include" >> p_ignoreString)
<|> (reserved "clearmodulelist" >> return id)
<|> (reserved "addmodule" >> p_ignoreString)
<|> (reserved "loadmodule" >> p_ignoreString2)
<|> (reserved "extendedstatus" >> p_ignoreString)
<|> (reserved "customlog" >> p_ignoreString2)
<|> (reserved "port" >> p_port)
<|> (reserved "maxclients" >> p_maxClients)
<|> (reserved "timeout" >> p_timeout)
<|> (reserved "directoryindex" >> p_directoryIndex)
<|> (reserved "accessfilename" >> p_accessFileName)
<|> (reserved "typesconfig" >> p_typesConfig)
<|> (reserved "scriptalias" >> p_scriptAlias)
<|> (reserved "defaulttype" >> p_defaultType)
<|> (reserved "hostnamelookups" >> p_hostnameLookups)
<|> (reserved "errorlog" >> p_errorLog)
<|> (reserved "loglevel" >> p_logLevel)
<|> (reserved "logFormat" >> p_logFormat)
<|> (reserved "accesslogfile" >> p_accessLogFile)
<|> (reserved "accesslogformat" >> p_accessLogFormat)
<|> (reserved "listen" >> p_listen)
<|> (reserved "addlanguage" >> p_addlanguage)
<|> (reserved "languagepriority" >> p_languagepriority)
<|> (p_element >> return id);
p_user
= do { str <- p_lit_or_string;
return (\ c -> c{user = str})};
p_timeout
= do { i <- int;
return (\ c -> c{requestTimeout = i})};
p_keepAliveTimeout
= do { i <- int;
return (\ c -> c{keepAliveTimeout = i})};
p_maxClients
= do { i <- int;
return (\ c -> c{maxClients = i})};
p_port
= do { i <- int;
return (\ c -> c{port = i})};
p_group
= do { str <- p_lit_or_string;
return (\ c -> c{group = str})};
p_serverAdmin
= do { str <- p_lit_or_string;
return (\ c -> c{serverAdmin = str})};
p_serverName
= do { str <- p_lit_or_string;
return (\ c -> c{serverName = str})};
p_serverAlias
= do { str <- p_lit_or_string;
return (\ c -> c{serverAlias = str : serverAlias c})};
p_useCanonicalName
= do { b <- bool;
return (\ c -> c{useCanonicalName = b})};
p_documentRoot
= do { str <- p_lit_or_string;
return (\ c -> c{documentRoot = str})};
p_ignoreString
= do { str <- p_lit_or_string;
return (\ c -> c)};
p_ignoreString2
= do { str <- p_lit_or_string;
str2 <- p_lit_or_string;
return (\ c -> c)};
p_logFormat
= do { p_lit_or_string;
p_lit_or_string;
return id};
p_scriptAlias
= do { str <- p_lit_or_string;
str1 <- p_lit_or_string;
return (\ c -> c{scriptAlias = Just (str, str1)})};
p_userDir
= do { str <- p_lit_or_string;
return (\ c -> c{userDir = str})};
p_directoryIndex
= do { str <- p_lit_or_string;
return (\ c -> c{directoryIndex = str})};
p_accessFileName
= do { str <- p_lit_or_string;
return (\ c -> c{accessFileName = str})};
p_typesConfig
= do { str <- p_lit_or_string;
return (\ c -> c{typesConfig = str})};
p_defaultType
= do { str <- p_lit_or_string;
return (\ c -> c{defaultType = str})};
p_hostnameLookups
= do { b <- bool;
return (\ c -> c{hostnameLookups = b})};
p_errorLog
= do { str <- p_lit_or_string;
return (\ c -> c{errorLogFile = str})};
p_logLevel
= do { i <- (ll <|> int);
return (\ c -> c{logLevel = i})};
p_accessLogFile
= do { str <- p_lit_or_string;
return (\ c -> c{accessLogFile = str})};
p_accessLogFormat
= do { str <- p_lit_or_string;
return (\ c -> c{accessLogFormat = str})};
p_listen
= do { i <- int;
return (\ c -> c{listen = i : listen c})};
p_addlanguage
= do { lang <- p_lit_or_string;
ext <- p_lit_or_string;
return (\ c -> c{addLanguage = (lang, ext) : addLanguage c})};
p_languagepriority
= do { langs <- many p_lit_or_string;
return (\ c -> c{languagePriority = langs})};
bool
= do { string "On";
return True}
<|>
do { string "Off";
return False};
ll :: Parser Int;
ll
= do { string "debug";
return 7}
<|>
do { string "info";
return 6}
<|>
do { string "notice";
return 5}
<|>
do { string "warn";
return 4}
<|>
do { string "error";
return 3}
<|>
do { string "crit";
return 2}
<|>
do { string "alert";
return 1}
<|>
do { string "emerg";
return 0};
int :: Parser Int;
int
= do { str <- many1 digit;
return (read str)};
p_element
= do { symbol "<";
tag <- many alphaNum;
p_rest tag};
p_rest tag
= do { many (satisfy (/= '>'));
symbol ">";
let { p_contents
= (symbol "<" >>
((symbol "/" >> ((symbol tag >> symbol ">"))) <|>
do { newt <- many alphaNum;
p_rest newt;
p_contents}))
<|> (p_lit_or_string >> p_contents)
<|> (ws >> p_contents)
<|> (many (noneOf "<\"#") >> p_contents)};
p_contents};
p_literal
= do { many1
(satisfy (\ c -> not (isSpace c || c `elem` "\"<>")))};
p_string
= do { char '"';
str <- many (noneOf "\n\"\\");
char '"';
return str};
p_lit_or_string = ws >> (p_literal <|> p_string)}
| ckaestne/CIDE | CIDE_Language_Haskell/test/WSP/Webserver/ConfigParser.hs | gpl-3.0 | 8,038 | 0 | 53 | 2,678 | 2,656 | 1,432 | 1,224 | 227 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Sound.Tidal.Pattern where
import Control.Applicative
import Data.Monoid
import Data.Fixed
import Data.List
import Data.Maybe
import Data.Ratio
import Debug.Trace
import Data.Typeable
import Data.Function
import System.Random.Mersenne.Pure64
import Music.Theory.Bjorklund
import Sound.Tidal.Time
import Sound.Tidal.Utils
-- | The pattern datatype, a function from a time @Arc@ to @Event@
-- values. For discrete patterns, this returns the events which are
-- active during that time. For continuous patterns, events with
-- values for the midpoint of the given @Arc@ is returned.
data Pattern a = Pattern {arc :: Arc -> [Event a]}
-- | @show (p :: Pattern)@ returns a text string representing the
-- event values active during the first cycle of the given pattern.
instance (Show a) => Show (Pattern a) where
show p@(Pattern _) = show $ arc p (0, 1)
instance Functor Pattern where
fmap f (Pattern a) = Pattern $ fmap (fmap (mapThd' f)) a
-- | @pure a@ returns a pattern with an event with value @a@, which
-- has a duration of one cycle, and repeats every cycle.
instance Applicative Pattern where
pure x = Pattern $ \(s, e) -> map
(\t -> ((t%1, (t+1)%1),
(t%1, (t+1)%1),
x
)
)
[floor s .. ((ceiling e) - 1)]
(Pattern fs) <*> (Pattern xs) =
Pattern $ \a -> concatMap applyX (fs a)
where applyX ((s,e), (s', e'), f) =
map (\(_, _, x) -> ((s,e), (s', e'), f x))
(filter
(\(_, a', _) -> isIn a' s)
(xs (s',e'))
)
-- | @mempty@ is a synonym for @silence@.
-- | @mappend@ is a synonym for @overlay@.
instance Monoid (Pattern a) where
mempty = silence
mappend = overlay
instance Monad Pattern where
return = pure
p >>= f = -- unwrap (f <$> p)
Pattern (\a -> concatMap
-- TODO - this is a total guess
(\((s,e), (s',e'), x) -> mapSnds' (const (s',e')) $
filter
(\(_, a', _) -> isIn a' s)
(arc (f x) (s',e'))
)
(arc p a)
)
-- join x = x >>= id
-- Take a pattern, and function from elements in the pattern to another pattern,
-- and then return that pattern
--bind :: Pattern a -> (a -> Pattern b) -> Pattern b
--bind p f =
-- this is actually join
unwrap :: Pattern (Pattern a) -> Pattern a
unwrap p = Pattern $ \a -> concatMap ((\p' -> arc p' a) . thd') (arc p a)
-- | @atom@ is a synonym for @pure@.
atom :: a -> Pattern a
atom = pure
-- | @silence@ returns a pattern with no events.
silence :: Pattern a
silence = Pattern $ const []
-- | @withQueryArc f p@ returns a new @Pattern@ with function @f@
-- applied to the @Arc@ values passed to the original @Pattern@ @p@.
withQueryArc :: (Arc -> Arc) -> Pattern a -> Pattern a
withQueryArc f p = Pattern $ \a -> arc p (f a)
-- | @withQueryTime f p@ returns a new @Pattern@ with function @f@
-- applied to the both the start and end @Time@ of the @Arc@ passed to
-- @Pattern@ @p@.
withQueryTime :: (Time -> Time) -> Pattern a -> Pattern a
withQueryTime = withQueryArc . mapArc
-- | @withResultArc f p@ returns a new @Pattern@ with function @f@
-- applied to the @Arc@ values in the events returned from the
-- original @Pattern@ @p@.
withResultArc :: (Arc -> Arc) -> Pattern a -> Pattern a
withResultArc f p = Pattern $ \a -> mapArcs f $ arc p a
-- | @withResultTime f p@ returns a new @Pattern@ with function @f@
-- applied to the both the start and end @Time@ of the @Arc@ values in
-- the events returned from the original @Pattern@ @p@.
withResultTime :: (Time -> Time) -> Pattern a -> Pattern a
withResultTime = withResultArc . mapArc
-- | @overlay@ combines two @Pattern@s into a new pattern, so that
-- their events are combined over time.
overlay :: Pattern a -> Pattern a -> Pattern a
overlay p p' = Pattern $ \a -> (arc p a) ++ (arc p' a)
(>+<) = overlay
-- | @stack@ combines a list of @Pattern@s into a new pattern, so that
-- their events are combined over time.
stack :: [Pattern a] -> Pattern a
stack ps = foldr overlay silence ps
-- | @append@ combines two patterns @Pattern@s into a new pattern, so
-- that the events of the second pattern are appended to those of the
-- first pattern, within a single cycle
append :: Pattern a -> Pattern a -> Pattern a
append a b = cat [a,b]
-- | @append'@ does the same as @append@, but over two cycles, so that
-- the cycles alternate between the two patterns.
append' :: Pattern a -> Pattern a -> Pattern a
append' a b = slow 2 $ cat [a,b]
-- | @cat@ returns a new pattern which interlaces the cycles of the
-- given patterns, within a single cycle. It's the equivalent of
-- @append@, but with a list of patterns.
cat :: [Pattern a] -> Pattern a
cat ps = density (fromIntegral $ length ps) $ slowcat ps
splitAtSam :: Pattern a -> Pattern a
splitAtSam p =
splitQueries $ Pattern $ \(s,e) -> mapSnds' (trimArc (sam s)) $ arc p (s,e)
where trimArc s' (s,e) = (max (s') s, min (s'+1) e)
-- | @slowcat@ does the same as @cat@, but maintaining the duration of
-- the original patterns. It is the equivalent of @append'@, but with
-- a list of patterns.
slowcat :: [Pattern a] -> Pattern a
slowcat [] = silence
slowcat ps = splitQueries $ Pattern f
where ps' = map splitAtSam ps
l = length ps'
f (s,e) = arc (withResultTime (+offset) p) (s',e')
where p = ps' !! n
r = (floor s) :: Int
n = (r `mod` l) :: Int
offset = (fromIntegral $ r - ((r - n) `div` l)) :: Time
(s', e') = (s-offset, e-offset)
-- | @listToPat@ turns the given list of values to a Pattern, which
-- cycles through the list.
listToPat :: [a] -> Pattern a
listToPat = cat . map atom
-- | @maybeListToPat@ is similar to @listToPat@, but allows values to
-- be optional using the @Maybe@ type, so that @Nothing@ results in
-- gaps in the pattern.
maybeListToPat :: [Maybe a] -> Pattern a
maybeListToPat = cat . map f
where f Nothing = silence
f (Just x) = atom x
-- | @run@ @n@ returns a pattern representing a cycle of numbers from @0@ to @n-1@.
run n = listToPat [0 .. n-1]
scan n = cat $ map run [1 .. n]
-- | @density@ returns the given pattern with density increased by the
-- given @Time@ factor. Therefore @density 2 p@ will return a pattern
-- that is twice as fast, and @density (1%3) p@ will return one three
-- times as slow.
density :: Time -> Pattern a -> Pattern a
density 0 p = silence
density 1 p = p
density r p = withResultTime (/ r) $ withQueryTime (* r) p
-- | @densityGap@ is similar to @density@ but maintains its cyclic
-- alignment. For example, @densityGap 2 p@ would squash the events in
-- pattern @p@ into the first half of each cycle (and the second
-- halves would be empty).
densityGap :: Time -> Pattern a -> Pattern a
densityGap 0 p = silence
densityGap r p = splitQueries $ withResultArc (\(s,e) -> (sam s + ((s - sam s)/r), (sam s + ((e - sam s)/r)))) $ Pattern (\a -> arc p $ mapArc (\t -> sam t + (min 1 (r * cyclePos t))) a)
-- | @slow@ does the opposite of @density@, i.e. @slow 2 p@ will
-- return a pattern that is half the speed.
slow :: Time -> Pattern a -> Pattern a
slow 0 = id
slow t = density (1/t)
-- | The @<~@ operator shifts (or rotates) a pattern to the left (or
-- counter-clockwise) by the given @Time@ value. For example
-- @(1%16) <~ p@ will return a pattern with all the events moved
-- one 16th of a cycle to the left.
(<~) :: Time -> Pattern a -> Pattern a
(<~) t p = withResultTime (subtract t) $ withQueryTime (+ t) p
-- | The @~>@ operator does the same as @~>@ but shifts events to the
-- right (or clockwise) rather than to the left.
(~>) :: Time -> Pattern a -> Pattern a
(~>) = (<~) . (0-)
brak :: Pattern a -> Pattern a
brak = when ((== 1) . (`mod` 2)) (((1%4) ~>) . (\x -> cat [x, silence]))
iter :: Int -> Pattern a -> Pattern a
iter n p = slowcat $ map (\i -> ((fromIntegral i)%(fromIntegral n)) <~ p) [0 .. n]
-- | @rev p@ returns @p@ with the event positions in each cycle
-- reversed (or mirrored).
rev :: Pattern a -> Pattern a
rev p = splitQueries $ Pattern $ \a -> mapArcs mirrorArc (arc p (mirrorArc a))
-- | @palindrome p@ applies @rev@ to @p@ every other cycle, so that
-- the pattern alternates between forwards and backwards.
palindrome p = append' p (rev p)
-- | @when test f p@ applies the function @f@ to @p@, but in a way
-- which only affects cycles where the @test@ function applied to the
-- cycle number returns @True@.
when :: (Int -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
when test f p = splitQueries $ Pattern apply
where apply a | test (floor $ fst a) = (arc $ f p) a
| otherwise = (arc p) a
whenT :: (Time -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
whenT test f p = splitQueries $ Pattern apply
where apply a | test (fst a) = (arc $ f p) a
| otherwise = (arc p) a
playWhen :: (Time -> Bool) -> Pattern a -> Pattern a
playWhen test (Pattern f) = Pattern $ (filter (\e -> test (eventOnset e))) . f
playFor :: Time -> Time -> Pattern a -> Pattern a
playFor s e = playWhen (\t -> and [t >= s, t < e])
seqP :: [(Time, Time, Pattern a)] -> Pattern a
seqP = stack . (map (\(s, e, p) -> playFor s e ((sam s) ~> p)))
-- | @every n f p@ applies the function @f@ to @p@, but only affects
-- every @n@ cycles.
every :: Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
every 0 f p = p
every n f p = when ((== 0) . (`mod` n)) f p
-- | @foldEvery ns f p@ applies the function @f@ to @p@, and is applied for
-- each cycle in @ns@.
foldEvery :: [Int] -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
foldEvery ns f p = foldr ($) p (map (\x -> every x f) ns)
-- | @sig f@ takes a function from time to values, and turns it into a
-- @Pattern@.
sig :: (Time -> a) -> Pattern a
sig f = Pattern f'
where f' (s,e) | s > e = []
| otherwise = [((s,e), (s,e), f s)]
-- | @sinewave@ returns a @Pattern@ of continuous @Double@ values following a
-- sinewave with frequency of one cycle, and amplitude from -1 to 1.
sinewave :: Pattern Double
sinewave = sig $ \t -> sin $ pi * 2 * (fromRational t)
-- | @sine@ is a synonym for @sinewave.
sine = sinewave
-- | @sinerat@ is equivalent to @sinewave@ for @Rational@ values,
-- suitable for use as @Time@ offsets.
sinerat = fmap toRational sine
ratsine = sinerat
-- | @sinewave1@ is equivalent to @sinewave@, but with amplitude from 0 to 1.
sinewave1 :: Pattern Double
sinewave1 = fmap ((/ 2) . (+ 1)) sinewave
-- | @sine1@ is a synonym for @sinewave1@.
sine1 = sinewave1
-- | @sinerat1@ is equivalent to @sinerat@, but with amplitude from 0 to 1.
sinerat1 = fmap toRational sine1
-- | @sineAmp1 d@ returns @sinewave1@ with its amplitude offset by @d@.
sineAmp1 :: Double -> Pattern Double
sineAmp1 offset = (+ offset) <$> sinewave1
-- | @sawwave@ is the equivalent of @sinewave@ for sawtooth waves.
sawwave :: Pattern Double
sawwave = ((subtract 1) . (* 2)) <$> sawwave1
-- | @saw@ is a synonym for @sawwave@.
saw = sawwave
-- | @sawrat@ is the same as @sawwave@ but returns @Rational@ values
-- suitable for use as @Time@ offsets.
sawrat = fmap toRational saw
sawwave1 :: Pattern Double
sawwave1 = sig $ \t -> mod' (fromRational t) 1
saw1 = sawwave1
sawrat1 = fmap toRational saw1
-- | @triwave@ is the equivalent of @sinewave@ for triangular waves.
triwave :: Pattern Double
triwave = ((subtract 1) . (* 2)) <$> triwave1
-- | @tri@ is a synonym for @triwave@.
tri = triwave
-- | @trirat@ is the same as @triwave@ but returns @Rational@ values
-- suitable for use as @Time@ offsets.
trirat = fmap toRational tri
triwave1 :: Pattern Double
triwave1 = append sawwave1 (rev sawwave1)
tri1 = triwave1
trirat1 = fmap toRational tri1
-- todo - triangular waves again
squarewave1 :: Pattern Double
squarewave1 = sig $
\t -> fromIntegral $ floor $ (mod' (fromRational t) 1) * 2
square1 = squarewave1
squarewave :: Pattern Double
squarewave = ((subtract 1) . (* 2)) <$> squarewave1
square = squarewave
-- | @envL@ is a @Pattern@ of continuous @Double@ values, representing
-- a linear interpolation between 0 and 1 during the first cycle, then
-- staying constant at 1 for all following cycles. Possibly only
-- useful if you're using something like the retrig function defined
-- in tidal.el.
envL :: Pattern Double
envL = sig $ \t -> max 0 $ min (fromRational t) 1
fadeOut :: Time -> Pattern a -> Pattern a
fadeOut n = spread' (degradeBy) (slow n $ envL)
fadeIn :: Time -> Pattern a -> Pattern a
fadeIn n = spread' (degradeBy) (slow n $ (1-) <$> envL)
spread :: (a -> t -> Pattern b) -> [a] -> t -> Pattern b
spread f xs p = cat $ map (\x -> f x p) xs
slowspread :: (a -> t -> Pattern b) -> [a] -> t -> Pattern b
slowspread f xs p = slowcat $ map (\x -> f x p) xs
spread' :: (a -> Pattern b -> Pattern c) -> Pattern a -> Pattern b -> Pattern c
spread' f timepat pat =
Pattern $ \r -> concatMap (\(_,r', x) -> (arc (f x pat) r')) (rs r)
where rs r = arc (filterOnsetsInRange timepat) r
filterValues :: (a -> Bool) -> Pattern a -> Pattern a
filterValues f (Pattern x) = Pattern $ (filter (f . thd')) . x
-- Filter out events that have had their onsets cut off
filterOnsets :: Pattern a -> Pattern a
filterOnsets (Pattern f) =
Pattern $ (filter (\e -> eventOnset e >= eventStart e)) . f
-- Filter events which have onsets, which are within the given range
filterStartInRange :: Pattern a -> Pattern a
filterStartInRange (Pattern f) =
Pattern $ \(s,e) -> filter ((>= s) . eventOnset) $ f (s,e)
filterOnsetsInRange = filterOnsets . filterStartInRange
seqToRelOnsets :: Arc -> Pattern a -> [(Double, a)]
seqToRelOnsets (s, e) p = map (\((s', _), _, x) -> (fromRational $ (s'-s) / (e-s), x)) $ arc (filterOnsetsInRange p) (s, e)
segment :: Pattern a -> Pattern [a]
segment p = Pattern $ \(s,e) -> filter (\(_,(s',e'),_) -> s' < e && e' > s) $ groupByTime (segment' (arc p (s,e)))
segment' :: [Event a] -> [Event a]
segment' es = foldr split es pts
where pts = nub $ points es
split :: Time -> [Event a] -> [Event a]
split _ [] = []
split t ((ev@(a,(s,e), v)):es) | t > s && t < e = (a,(s,t),v):(a,(t,e),v):(split t es)
| otherwise = ev:split t es
points :: [Event a] -> [Time]
points [] = []
points ((_,(s,e), _):es) = s:e:(points es)
groupByTime :: [Event a] -> [Event [a]]
groupByTime es = map mrg $ groupBy ((==) `on` snd') $ sortBy (compare `on` snd') es
where mrg es@((a, a', _):_) = (a, a', map thd' es)
ifp :: (Int -> Bool) -> (Pattern a -> Pattern a) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
ifp test f1 f2 p = splitQueries $ Pattern apply
where apply a | test (floor $ fst a) = (arc $ f1 p) a
| otherwise = (arc $ f2 p) a
rand :: Pattern Double
rand = Pattern $ \a -> [(a, a, fst $ randomDouble $ pureMT $ floor $ (*1000000) $ (midPoint a))]
irand :: Double -> Pattern Int
irand i = (floor . (*i)) <$> rand
degradeBy :: Double -> Pattern a -> Pattern a
degradeBy x p = unMaybe $ (\a f -> toMaybe (f > x) a) <$> p <*> rand
where toMaybe False _ = Nothing
toMaybe True a = Just a
unMaybe = (fromJust <$>) . filterValues isJust
unDegradeBy :: Double -> Pattern a -> Pattern a
unDegradeBy x p = unMaybe $ (\a f -> toMaybe (f <= x) a) <$> p <*> rand
where toMaybe False _ = Nothing
toMaybe True a = Just a
unMaybe = (fromJust <$>) . filterValues isJust
sometimesBy :: Double -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
sometimesBy x f p = overlay (degradeBy x p) (f $ unDegradeBy x p)
sometimes = sometimesBy 0.5
often = sometimesBy 0.75
rarely = sometimesBy 0.25
almostNever = sometimesBy 0.1
almostAlways = sometimesBy 0.9
degrade :: Pattern a -> Pattern a
degrade = degradeBy 0.5
-- | @wedge t p p'@ combines patterns @p@ and @p'@ by squashing the
-- @p@ into the portion of each cycle given by @t@, and @p'@ into the
-- remainer of each cycle.
wedge :: Time -> Pattern a -> Pattern a -> Pattern a
wedge t p p' = overlay (densityGap (1/t) p) (t <~ densityGap (1/(1-t)) p')
whenmod :: Int -> Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
whenmod a b = Sound.Tidal.Pattern.when ((\t -> (t `mod` a) >= b ))
superimpose f p = stack [p, f p]
-- | @splitQueries p@ wraps `p` to ensure that it does not get
-- queries that | span arcs. For example `arc p (0.5, 1.5)` would be
-- turned into two queries, `(0.5,1)` and `(1,1.5)`, and the results
-- combined. Being able to assume queries don't span cycles often
-- makes transformations easier to specify.
splitQueries :: Pattern a -> Pattern a
splitQueries p = Pattern $ \a -> concatMap (arc p) $ arcCycles a
trunc :: Time -> Pattern a -> Pattern a
trunc t p = slow t $ splitQueries $ p'
where p' = Pattern $ \a -> mapArcs (stretch . trunc') $ arc p (trunc' a)
trunc' (s,e) = (min s ((sam s) + t), min e ((sam s) + t))
stretch (s,e) = (sam s + ((s - sam s) / t), sam s + ((e - sam s) / t))
zoom :: Arc -> Pattern a -> Pattern a
zoom a@(s,e) p = splitQueries $ withResultArc (mapCycle ((/d) . (subtract s))) $ withQueryArc (mapCycle ((+s) . (*d))) p
where d = e-s
compress :: Arc -> Pattern a -> Pattern a
compress a@(s,e) p | s >= e = silence
| otherwise = s ~> densityGap (1/(e-s)) p
sliceArc :: Arc -> Pattern a -> Pattern a
sliceArc a@(s,e) p | s >= e = silence
| otherwise = compress a $ zoom a p
-- @within@ uses @compress@ and @zoom to apply @f@ to only part of pattern @p@
-- for example, @within (1%2) (3%4) ((1%8) <~) "bd sn bd cp"@ would shift only
-- the second @bd@
within :: Arc -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a
within (s,e) f p = stack [sliceArc (0,s) p,
compress (s,e) $ f $ zoom (s,e) p,
sliceArc (e,1) p
]
revArc a = within a rev
e :: Int -> Int -> Pattern a -> Pattern a
e n k p = (flip const) <$> (filterValues (== True) $ listToPat $ bjorklund (n,k)) <*> p
e' :: Int -> Int -> Pattern a -> Pattern a
e' n k p = cat $ map (\x -> if x then p else silence) (bjorklund (n,k))
index :: Real b => b -> Pattern b -> Pattern c -> Pattern c
index sz indexpat pat = spread' (zoom' $ toRational sz) (toRational . (*(1-sz)) <$> indexpat) pat
where zoom' sz start = zoom (start, start+sz)
| unthingable/Tidal | Sound/Tidal/Pattern.hs | gpl-3.0 | 18,654 | 0 | 18 | 4,578 | 6,382 | 3,391 | 2,991 | 271 | 2 |
{-# LANGUAGE CPP #-}
--
-- Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
module System.Plugins.Consts where
#include "config.h"
#if __GLASGOW_HASKELL__ >= 604
import System.Directory ( getTemporaryDirectory )
import System.IO.Unsafe ( unsafePerformIO )
#endif
-- | path to *build* dir, used by eval() for testing the examples
top = TOP
-- | what is ghc called?
ghc = WITH_GHC
-- | path to standard ghc libraries
ghcLibraryPath = GHC_LIB_PATH
-- | name of the system package.conf file
sysPkgConf = "package.conf"
-- | This code is from runtime_loader:
-- The extension used by system modules.
sysPkgSuffix = ".a"
objSuf = ".o"
hiSuf = ".hi"
hsSuf = ".hs"
#if defined(CYGWIN) || defined(__MINGW32__)
dllSuf = ".dll"
#else
dllSuf = ".so"
#endif
-- | The prefix used by system modules. This, in conjunction with
-- 'systemModuleExtension', will result in a module filename that looks
-- like \"HSconcurrent.o\"
sysPkgPrefix = "HS"
-- | '_' on a.out, and Darwin
#if LEADING_UNDERSCORE == 1
prefixUnderscore = "_"
#else
prefixUnderscore = ""
#endif
-- | Define tmpDir to where tmp files should be created on your platform
#if __GLASGOW_HASKELL__ >= 604
tmpDir = unsafePerformIO getTemporaryDirectory
{-# NOINLINE tmpDir #-}
#else
#if !defined(__MINGW32__)
tmpDir = "/tmp"
#else
tmpDir = error "tmpDir not defined for this platform. Try setting the TMPDIR env var"
#endif
#endif
| stepcut/plugins | src/System/Plugins/Consts.hs | lgpl-2.1 | 2,250 | 0 | 5 | 462 | 135 | 99 | 36 | 14 | 1 |
{-# LANGUAGE CPP #-}
module API.Question.GetQuestion.Url (url) where
url :: String
url = "/api/getQuestion"
| DataStewardshipPortal/ds-wizard | DSServer/app/API/Question/GetQuestion/Url.hs | apache-2.0 | 111 | 0 | 4 | 17 | 24 | 16 | 8 | 4 | 1 |
module Common where
import Test.QuickCheck
import SIL.TypeChecker
import SIL
class TestableIExpr a where
getIExpr :: a -> IExpr
data TestIExpr = TestIExpr IExpr
data ValidTestIExpr = ValidTestIExpr TestIExpr
data ZeroTypedTestIExpr = ZeroTypedTestIExpr TestIExpr
data ArrowTypedTestIExpr = ArrowTypedTestIExpr TestIExpr
instance TestableIExpr TestIExpr where
getIExpr (TestIExpr x) = x
instance Show TestIExpr where
show (TestIExpr t) = show t
instance TestableIExpr ValidTestIExpr where
getIExpr (ValidTestIExpr x) = getIExpr x
instance Show ValidTestIExpr where
show (ValidTestIExpr v) = show v
instance TestableIExpr ZeroTypedTestIExpr where
getIExpr (ZeroTypedTestIExpr x) = getIExpr x
instance Show ZeroTypedTestIExpr where
show (ZeroTypedTestIExpr v) = show v
instance TestableIExpr ArrowTypedTestIExpr where
getIExpr (ArrowTypedTestIExpr x) = getIExpr x
instance Show ArrowTypedTestIExpr where
show (ArrowTypedTestIExpr x) = show x
lift1Texpr :: (IExpr -> IExpr) -> TestIExpr -> TestIExpr
lift1Texpr f (TestIExpr x) = TestIExpr $ f x
lift2Texpr :: (IExpr -> IExpr -> IExpr) -> TestIExpr -> TestIExpr -> TestIExpr
lift2Texpr f (TestIExpr a) (TestIExpr b) = TestIExpr $ f a b
instance Arbitrary TestIExpr where
arbitrary = sized tree where
tree i = let half = div i 2
pure2 = pure . TestIExpr
in case i of
0 -> oneof $ map pure2 [zero, var]
x -> oneof
[ pure2 zero
, pure2 var
, lift2Texpr pair <$> tree half <*> tree half
, lift1Texpr SetEnv <$> tree (i - 1)
, lift1Texpr Defer <$> tree (i - 1)
, lift2Texpr check <$> tree half <*> tree half
, lift1Texpr gate <$> tree (i - 1)
, lift1Texpr pleft <$> tree (i - 1)
, lift1Texpr pright <$> tree (i - 1)
, lift1Texpr Trace <$> tree (i - 1)
]
shrink (TestIExpr x) = case x of
Zero -> []
Env -> []
(Gate x) -> TestIExpr x : (map (lift1Texpr gate) . shrink $ TestIExpr x)
(PLeft x) -> TestIExpr x : (map (lift1Texpr pleft) . shrink $ TestIExpr x)
(PRight x) -> TestIExpr x : (map (lift1Texpr pright) . shrink $ TestIExpr x)
(Trace x) -> TestIExpr x : (map (lift1Texpr Trace) . shrink $ TestIExpr x)
(SetEnv x) -> TestIExpr x : (map (lift1Texpr SetEnv) . shrink $ TestIExpr x)
(Defer x) -> TestIExpr x : (map (lift1Texpr Defer) . shrink $ TestIExpr x)
(Abort x) -> TestIExpr x : (map (lift1Texpr Abort) . shrink $ TestIExpr x)
(Pair a b) -> TestIExpr a : TestIExpr b :
[lift2Texpr pair a' b' | (a', b') <- shrink (TestIExpr a, TestIExpr b)]
typeable x = case inferType (getIExpr x) of
Left _ -> False
_ -> True
instance Arbitrary ValidTestIExpr where
arbitrary = ValidTestIExpr <$> suchThat arbitrary typeable
shrink (ValidTestIExpr te) = map ValidTestIExpr . filter typeable $ shrink te
zeroTyped x = inferType (getIExpr x) == Right ZeroTypeP
instance Arbitrary ZeroTypedTestIExpr where
arbitrary = ZeroTypedTestIExpr <$> suchThat arbitrary zeroTyped
shrink (ZeroTypedTestIExpr ztte) = map ZeroTypedTestIExpr . filter zeroTyped $ shrink ztte
simpleArrowTyped x = inferType (getIExpr x) == Right (ArrTypeP ZeroTypeP ZeroTypeP)
instance Arbitrary ArrowTypedTestIExpr where
arbitrary = ArrowTypedTestIExpr <$> suchThat arbitrary simpleArrowTyped
shrink (ArrowTypedTestIExpr atte) = map ArrowTypedTestIExpr . filter simpleArrowTyped $ shrink atte
| sfultong/stand-in-language | test/Common.hs | apache-2.0 | 3,591 | 0 | 18 | 908 | 1,275 | 622 | 653 | 73 | 2 |
{-# LANGUAGE PackageImports #-}
import "fun-w-yesod" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "dist/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| tomasherman/fun-w-yesod | devel.hs | bsd-2-clause | 705 | 0 | 10 | 123 | 186 | 101 | 85 | 23 | 2 |
{- path manipulation
-
- Copyright 2010-2014 Joey Hess <[email protected]>
-
- License: BSD-2-clause
-}
{-# LANGUAGE PackageImports, CPP #-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Utility.Path where
import Data.String.Utils
import System.FilePath
import Data.List
import Data.Maybe
import Data.Char
import Control.Applicative
import Prelude
#ifdef mingw32_HOST_OS
import qualified System.FilePath.Posix as Posix
#else
import System.Posix.Files
import Utility.Exception
#endif
import qualified "MissingH" System.Path as MissingH
import Utility.Monad
import Utility.UserInfo
import Utility.Directory
{- Simplifies a path, removing any "." component, collapsing "dir/..",
- and removing the trailing path separator.
-
- On Windows, preserves whichever style of path separator might be used in
- the input FilePaths. This is done because some programs in Windows
- demand a particular path separator -- and which one actually varies!
-
- This does not guarantee that two paths that refer to the same location,
- and are both relative to the same location (or both absolute) will
- yeild the same result. Run both through normalise from System.FilePath
- to ensure that.
-}
simplifyPath :: FilePath -> FilePath
simplifyPath path = dropTrailingPathSeparator $
joinDrive drive $ joinPath $ norm [] $ splitPath path'
where
(drive, path') = splitDrive path
norm c [] = reverse c
norm c (p:ps)
| p' == ".." && not (null c) && dropTrailingPathSeparator (c !! 0) /= ".." =
norm (drop 1 c) ps
| p' == "." = norm c ps
| otherwise = norm (p:c) ps
where
p' = dropTrailingPathSeparator p
{- Makes a path absolute.
-
- The first parameter is a base directory (ie, the cwd) to use if the path
- is not already absolute, and should itsef be absolute.
-
- Does not attempt to deal with edge cases or ensure security with
- untrusted inputs.
-}
absPathFrom :: FilePath -> FilePath -> FilePath
absPathFrom dir path = simplifyPath (combine dir path)
{- On Windows, this converts the paths to unix-style, in order to run
- MissingH's absNormPath on them. -}
absNormPathUnix :: FilePath -> FilePath -> Maybe FilePath
#ifndef mingw32_HOST_OS
absNormPathUnix dir path = MissingH.absNormPath dir path
#else
absNormPathUnix dir path = todos <$> MissingH.absNormPath (fromdos dir) (fromdos path)
where
fromdos = replace "\\" "/"
todos = replace "/" "\\"
#endif
{- takeDirectory "foo/bar/" is "foo/bar". This instead yields "foo" -}
parentDir :: FilePath -> FilePath
parentDir = takeDirectory . dropTrailingPathSeparator
{- Just the parent directory of a path, or Nothing if the path has no
- parent (ie for "/" or ".") -}
upFrom :: FilePath -> Maybe FilePath
upFrom dir
| length dirs < 2 = Nothing
| otherwise = Just $ joinDrive drive (intercalate s $ init dirs)
where
-- on Unix, the drive will be "/" when the dir is absolute, otherwise ""
(drive, path) = splitDrive dir
dirs = filter (not . null) $ split s path
s = [pathSeparator]
prop_upFrom_basics :: FilePath -> Bool
prop_upFrom_basics dir
| null dir = True
| dir == "/" = p == Nothing
| otherwise = p /= Just dir
where
p = upFrom dir
{- Checks if the first FilePath is, or could be said to contain the second.
- For example, "foo/" contains "foo/bar". Also, "foo", "./foo", "foo/" etc
- are all equivilant.
-}
dirContains :: FilePath -> FilePath -> Bool
dirContains a b = a == b || a' == b' || (addTrailingPathSeparator a') `isPrefixOf` b'
where
a' = norm a
b' = norm b
norm = normalise . simplifyPath
{- Converts a filename into an absolute path.
-
- Unlike Directory.canonicalizePath, this does not require the path
- already exists. -}
absPath :: FilePath -> IO FilePath
absPath file = do
cwd <- getCurrentDirectory
return $ absPathFrom cwd file
{- Constructs a relative path from the CWD to a file.
-
- For example, assuming CWD is /tmp/foo/bar:
- relPathCwdToFile "/tmp/foo" == ".."
- relPathCwdToFile "/tmp/foo/bar" == ""
-}
relPathCwdToFile :: FilePath -> IO FilePath
relPathCwdToFile f = do
c <- getCurrentDirectory
relPathDirToFile c f
{- Constructs a relative path from a directory to a file. -}
relPathDirToFile :: FilePath -> FilePath -> IO FilePath
relPathDirToFile from to = relPathDirToFileAbs <$> absPath from <*> absPath to
{- This requires the first path to be absolute, and the
- second path cannot contain ../ or ./
-
- On Windows, if the paths are on different drives,
- a relative path is not possible and the path is simply
- returned as-is.
-}
relPathDirToFileAbs :: FilePath -> FilePath -> FilePath
relPathDirToFileAbs from to
| takeDrive from /= takeDrive to = to
| otherwise = intercalate s $ dotdots ++ uncommon
where
s = [pathSeparator]
pfrom = split s from
pto = split s to
common = map fst $ takeWhile same $ zip pfrom pto
same (c,d) = c == d
uncommon = drop numcommon pto
dotdots = replicate (length pfrom - numcommon) ".."
numcommon = length common
prop_relPathDirToFile_basics :: FilePath -> FilePath -> Bool
prop_relPathDirToFile_basics from to
| null from || null to = True
| from == to = null r
| otherwise = not (null r)
where
r = relPathDirToFileAbs from to
prop_relPathDirToFile_regressionTest :: Bool
prop_relPathDirToFile_regressionTest = same_dir_shortcurcuits_at_difference
where
{- Two paths have the same directory component at the same
- location, but it's not really the same directory.
- Code used to get this wrong. -}
same_dir_shortcurcuits_at_difference =
relPathDirToFileAbs (joinPath [pathSeparator : "tmp", "r", "lll", "xxx", "yyy", "18"])
(joinPath [pathSeparator : "tmp", "r", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"])
== joinPath ["..", "..", "..", "..", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"]
{- Given an original list of paths, and an expanded list derived from it,
- which may be arbitrarily reordered, generates a list of lists, where
- each sublist corresponds to one of the original paths.
-
- When the original path is a directory, any items in the expanded list
- that are contained in that directory will appear in its segment.
-
- The order of the original list of paths is attempted to be preserved in
- the order of the returned segments. However, doing so has a O^NM
- growth factor. So, if the original list has more than 100 paths on it,
- we stop preserving ordering at that point. Presumably a user passing
- that many paths in doesn't care too much about order of the later ones.
-}
segmentPaths :: [FilePath] -> [FilePath] -> [[FilePath]]
segmentPaths [] new = [new]
segmentPaths [_] new = [new] -- optimisation
segmentPaths (l:ls) new = found : segmentPaths ls rest
where
(found, rest) = if length ls < 100
then partition (l `dirContains`) new
else break (\p -> not (l `dirContains` p)) new
{- This assumes that it's cheaper to call segmentPaths on the result,
- than it would be to run the action separately with each path. In
- the case of git file list commands, that assumption tends to hold.
-}
runSegmentPaths :: ([FilePath] -> IO [FilePath]) -> [FilePath] -> IO [[FilePath]]
runSegmentPaths a paths = segmentPaths paths <$> a paths
{- Converts paths in the home directory to use ~/ -}
relHome :: FilePath -> IO String
relHome path = do
home <- myHomeDir
return $ if dirContains home path
then "~/" ++ relPathDirToFileAbs home path
else path
{- Checks if a command is available in PATH.
-
- The command may be fully-qualified, in which case, this succeeds as
- long as it exists. -}
inPath :: String -> IO Bool
inPath command = isJust <$> searchPath command
{- Finds a command in PATH and returns the full path to it.
-
- The command may be fully qualified already, in which case it will
- be returned if it exists.
-}
searchPath :: String -> IO (Maybe FilePath)
searchPath command
| isAbsolute command = check command
| otherwise = getSearchPath >>= getM indir
where
indir d = check $ d </> command
check f = firstM doesFileExist
#ifdef mingw32_HOST_OS
[f, f ++ ".exe"]
#else
[f]
#endif
{- Checks if a filename is a unix dotfile. All files inside dotdirs
- count as dotfiles. -}
dotfile :: FilePath -> Bool
dotfile file
| f == "." = False
| f == ".." = False
| f == "" = False
| otherwise = "." `isPrefixOf` f || dotfile (takeDirectory file)
where
f = takeFileName file
{- Converts a DOS style path to a msys2 style path. Only on Windows.
- Any trailing '\' is preserved as a trailing '/'
-
- Taken from: http://sourceforge.net/p/msys2/wiki/MSYS2%20introduction/i
-
- The virtual filesystem contains:
- /c, /d, ... mount points for Windows drives
-}
toMSYS2Path :: FilePath -> FilePath
#ifndef mingw32_HOST_OS
toMSYS2Path = id
#else
toMSYS2Path p
| null drive = recombine parts
| otherwise = recombine $ "/" : driveletter drive : parts
where
(drive, p') = splitDrive p
parts = splitDirectories p'
driveletter = map toLower . takeWhile (/= ':')
recombine = fixtrailing . Posix.joinPath
fixtrailing s
| hasTrailingPathSeparator p = Posix.addTrailingPathSeparator s
| otherwise = s
#endif
{- Maximum size to use for a file in a specified directory.
-
- Many systems have a 255 byte limit to the name of a file,
- so that's taken as the max if the system has a larger limit, or has no
- limit.
-}
fileNameLengthLimit :: FilePath -> IO Int
#ifdef mingw32_HOST_OS
fileNameLengthLimit _ = return 255
#else
fileNameLengthLimit dir = do
-- getPathVar can fail due to statfs(2) overflow
l <- catchDefaultIO 0 $
fromIntegral <$> getPathVar dir FileNameLimit
if l <= 0
then return 255
else return $ minimum [l, 255]
#endif
{- Given a string that we'd like to use as the basis for FilePath, but that
- was provided by a third party and is not to be trusted, returns the closest
- sane FilePath.
-
- All spaces and punctuation and other wacky stuff are replaced
- with '_', except for '.'
- "../" will thus turn into ".._", which is safe.
-}
sanitizeFilePath :: String -> FilePath
sanitizeFilePath = map sanitize
where
sanitize c
| c == '.' = c
| isSpace c || isPunctuation c || isSymbol c || isControl c || c == '/' = '_'
| otherwise = c
{- Similar to splitExtensions, but knows that some things in FilePaths
- after a dot are too long to be extensions. -}
splitShortExtensions :: FilePath -> (FilePath, [String])
splitShortExtensions = splitShortExtensions' 5 -- enough for ".jpeg"
splitShortExtensions' :: Int -> FilePath -> (FilePath, [String])
splitShortExtensions' maxextension = go []
where
go c f
| len > 0 && len <= maxextension && not (null base) =
go (ext:c) base
| otherwise = (f, c)
where
(base, ext) = splitExtension f
len = length ext
| ArchiveTeam/glowing-computing-machine | src/Utility/Path.hs | bsd-2-clause | 10,692 | 20 | 15 | 2,063 | 1,928 | 1,000 | 928 | 141 | 2 |
module Args
(
theLast
, ljust
, nonNegative
, parseArgs
, positive
, printUsage
) where
import Data.Monoid (Monoid(..), Last(..))
import System.Console.GetOpt (OptDescr, ArgOrder(Permute), getOpt, usageInfo)
import System.Environment (getProgName)
import System.Exit (ExitCode(..), exitWith)
import System.IO (hPutStrLn, stderr)
-- | Deconstructor for 'Last' values.
theLast :: (cfg -> Last a) -- ^ Field to access.
-> cfg
-> a
theLast f cfg = case f cfg of
Last Nothing -> error "some horrible config sin has occurred"
Last (Just a) -> a
-- | Parse command line options.
parseArgs :: Monoid cfg => cfg -> [OptDescr (IO cfg)] -> [String]
-> IO (cfg, [String])
parseArgs defCfg options args =
case getOpt Permute options args of
(_, _, (err:_)) -> parseError err
(opts, rest, _) -> do
cfg <- (mappend defCfg . mconcat) `fmap` sequence opts
return (cfg, rest)
-- | Constructor for 'Last' values.
ljust :: a -> Last a
ljust = Last . Just
-- | Parse a positive number.
nonNegative :: (Num a, Ord a, Read a) =>
String -> (Last a -> cfg) -> String -> IO cfg
nonNegative q f s =
case reads s of
[(n,"")] | n >= 0 -> return . f $ ljust n
| otherwise -> parseError $ q ++ " must be non negative"
_ -> parseError $ "invalid " ++ q ++ " provided"
-- | Parse a positive number.
positive :: (Num a, Ord a, Read a) =>
String -> (Last a -> cfg) -> String -> IO cfg
positive q f s =
case reads s of
[(n,"")] | n > 0 -> return . f $ ljust n
| otherwise -> parseError $ q ++ " must be positive"
_ -> parseError $ "invalid " ++ q ++ " provided"
-- | Display an error message from a command line parsing failure, and
-- exit.
parseError :: String -> IO a
parseError msg = do
progName <- getProgName
hPutStrLn stderr $ "Error: " ++ msg
hPutStrLn stderr $ "Run \"" ++ progName ++ " --help\" for usage information\n"
exitWith (ExitFailure 64)
printUsage :: [OptDescr b] -> ExitCode -> IO a
printUsage options exitCode = do
p <- getProgName
putStr (usageInfo ("Usage: " ++ p ++ " [OPTIONS] [ARGS]") options)
mapM_ putStrLn [
""
, "hi mom!"
]
exitWith exitCode
| tibbe/event | benchmarks/Args.hs | bsd-2-clause | 2,332 | 0 | 14 | 678 | 794 | 414 | 380 | 57 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- 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 Prelude ()
import Distribution.Compat.Prelude
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
-- local
import Distribution.Backpack.DescribeUnitId
import Distribution.Types.ForeignLib
import Distribution.Types.UnqualComponentName
import Distribution.Types.ComponentLocalBuildInfo
import Distribution.Types.ExecutableScope
import Distribution.Package
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription as PD hiding (Flag)
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.Program.GHC
import Distribution.Simple.Program
import Distribution.Simple.PreProcess
import Distribution.Simple.Setup
import Distribution.Simple.Build
import Distribution.Simple.InstallDirs
import Distribution.Simple.LocalBuildInfo hiding (substPathTemplate)
import Distribution.Simple.BuildPaths
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
import Distribution.InstalledPackageInfo ( InstalledPackageInfo )
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Text
import Distribution.Utils.NubList
import Distribution.Version
import Distribution.Verbosity
import Language.Haskell.Extension
import Distribution.Compat.Semigroup (All (..), Any (..))
import Data.Either ( rights )
import System.Directory (doesFileExist)
import System.FilePath ( (</>), (<.>), normalise, isAbsolute )
import System.IO (hClose, hPutStr, hPutStrLn, hSetEncoding, utf8)
-- ------------------------------------------------------------------------------
-- 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.
} deriving Generic
-- | The FilePath of a directory, it's a monoid under '(</>)'.
newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord)
unDir :: Directory -> FilePath
unDir = normalise . 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)
&& not (fromFlag $ haddockForeignLibs 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,"
++ " --benchmarks or --foreign-libraries flags."
haddock pkg_descr lbi suffixes flags' = do
let verbosity = flag haddockVerbosity
comp = compiler lbi
platform = hostPlatform lbi
flags = case haddockTarget of
ForDevelopment -> flags'
ForHackage -> flags'
{ haddockHoogle = Flag True
, haddockHtml = Flag True
, haddockHtmlLocation = Flag (pkg_url ++ "/docs")
, haddockContents = Flag (toPathTemplate pkg_url)
, haddockHscolour = Flag True
}
pkg_url = "/package/$pkg-$version"
flag f = fromFlag $ f flags
tmpFileOpts = defaultTempFileOptions
{ optKeepTempFiles = flag haddockKeepTempFiles }
htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation
$ flags
haddockTarget =
fromFlagOrDefault ForDevelopment (haddockForHackage flags')
(haddockProg, version, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (mkVersion [2,0])) (withPrograms lbi)
-- various sanity checks
when ( flag haddockHoogle
&& version < mkVersion [2,2]) $
die' verbosity "haddock 2.0 and 2.1 do not support the --hoogle flag."
haddockGhcVersionStr <- getProgramOutput verbosity haddockProg
["--ghc-version"]
case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of
(Nothing, _) -> die' verbosity "Could not get GHC version from Haddock"
(_, Nothing) -> die' verbosity "Could not get GHC version from compiler"
(Just haddockGhcVersion, Just ghcVersion)
| haddockGhcVersion == ghcVersion -> return ()
| otherwise -> die' verbosity $
"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
when (flag haddockHscolour) $
hscolour' (warn verbosity) haddockTarget pkg_descr lbi suffixes
(defaultHscolourFlags `mappend` haddockToHscolour flags)
libdirArgs <- getGhcLibDir verbosity lbi
let commonArgs = mconcat
[ libdirArgs
, fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags
, fromPackageDescription haddockTarget pkg_descr ]
withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do
componentInitialBuildSteps (flag haddockDistPref) pkg_descr lbi clbi verbosity
preprocessComponent pkg_descr component lbi clbi False verbosity suffixes
let
doExe com = case (compToExe com) of
Just exe -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
exeArgs <- fromExecutable verbosity tmp lbi clbi htmlTemplate
version exe
let exeArgs' = commonArgs `mappend` exeArgs
runHaddock verbosity tmpFileOpts comp platform
haddockProg exeArgs'
Nothing -> do
warn (fromFlag $ haddockVerbosity flags)
"Unsupported component, skipping..."
return ()
-- We define 'smsg' once and then reuse it inside the case, so that
-- we don't say we are running Haddock when we actually aren't
-- (e.g., Haddock is not run on non-libraries)
smsg :: IO ()
smsg = setupMessage' verbosity "Running Haddock on" (packageId pkg_descr)
(componentLocalName clbi) (maybeComponentInstantiatedWith clbi)
case component of
CLib lib -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
smsg
libArgs <- fromLibrary verbosity tmp lbi clbi htmlTemplate
version lib
let libArgs' = commonArgs `mappend` libArgs
runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs'
CFLib flib -> when (flag haddockForeignLibs) $ do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
smsg
flibArgs <- fromForeignLib verbosity tmp lbi clbi htmlTemplate
version flib
let libArgs' = commonArgs `mappend` flibArgs
runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs'
CExe _ -> when (flag haddockExecutables) $ smsg >> doExe component
CTest _ -> when (flag haddockTestSuites) $ smsg >> doExe component
CBench _ -> when (flag haddockBenchmarks) $ smsg >> doExe component
for_ (extraDocFiles pkg_descr) $ \ fpath -> do
files <- matchFileGlob fpath
for_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs)
-- ------------------------------------------------------------------------------
-- Contributions to HaddockArgs (see also Doctest.hs for very similar code).
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 :: HaddockTarget -> PackageDescription -> HaddockArgs
fromPackageDescription haddockTarget pkg_descr =
mempty { argInterfaceFile = Flag $ haddockName pkg_descr,
argPackageName = Flag $ packageId $ pkg_descr,
argOutputDir = Dir $
"doc" </> "html" </> haddockDirName haddockTarget 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
mkHaddockArgs :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> [FilePath]
-> BuildInfo
-> IO HaddockArgs
mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles bi = do
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' verbosity $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die' verbosity "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argGhcOptions = toFlag (opts, ghcVersion),
argTargets = inFiles
}
fromLibrary :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> Library
-> IO HaddockArgs
fromLibrary verbosity tmp lbi clbi htmlTemplate haddockVersion lib = do
inFiles <- map snd `fmap` getLibSourceFiles verbosity lbi lib clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion
inFiles (libBuildInfo lib)
return args {
argHideModules = (mempty, otherModules (libBuildInfo lib))
}
fromExecutable :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> Executable
-> IO HaddockArgs
fromExecutable verbosity tmp lbi clbi htmlTemplate haddockVersion exe = do
inFiles <- map snd `fmap` getExeSourceFiles verbosity lbi exe clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate
haddockVersion inFiles (buildInfo exe)
return args {
argOutputDir = Dir $ unUnqualComponentName $ exeName exe,
argTitle = Flag $ unUnqualComponentName $ exeName exe
}
fromForeignLib :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> ForeignLib
-> IO HaddockArgs
fromForeignLib verbosity tmp lbi clbi htmlTemplate haddockVersion flib = do
inFiles <- map snd `fmap` getFLibSourceFiles verbosity lbi flib clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate
haddockVersion inFiles (foreignLibBuildInfo flib)
return args {
argOutputDir = Dir $ unUnqualComponentName $ foreignLibName flib,
argTitle = Flag $ unUnqualComponentName $ foreignLibName flib
}
compToExe :: Component -> Maybe Executable
compToExe comp =
case comp of
CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } ->
Just Executable {
exeName = testName test,
modulePath = f,
exeScope = ExecutablePublic,
buildInfo = testBuildInfo test
}
CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } ->
Just Executable {
exeName = benchmarkName bench,
modulePath = f,
exeScope = ExecutablePublic,
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 verbosity lbi clbi htmlTemplate
traverse_ (warn (verboseUnmarkOutput 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 $ versionNumbers 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
-> Platform
-> ConfiguredProgram
-> HaddockArgs
-> IO ()
runHaddock verbosity tmpFileOpts comp platform haddockProg args = do
let haddockVersion = fromMaybe (error "unable to determine haddock version")
(programVersion haddockProg)
renderArgs verbosity tmpFileOpts haddockVersion comp platform args $
\(flags,result)-> do
runProgram verbosity haddockProg flags
notice verbosity $ "Documentation created: " ++ result
renderArgs :: Verbosity
-> TempFileOptions
-> Version
-> Compiler
-> Platform
-> HaddockArgs
-> (([String], FilePath) -> IO a)
-> IO a
renderArgs verbosity tmpFileOpts version comp platform args k = do
let haddockSupportsUTF8 = version >= mkVersion [2,14,4]
haddockSupportsResponseFiles = version > mkVersion [2,16,2]
createDirectoryIfMissingVerbose verbosity True outputDir
withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $
\prologueFileName h -> do
do
when haddockSupportsUTF8 (hSetEncoding h utf8)
hPutStrLn h $ fromFlag $ argPrologue args
hClose h
let pflag = "--prologue=" ++ prologueFileName
renderedArgs = pflag : renderPureArgs version comp platform args
if haddockSupportsResponseFiles
then
withTempFileEx tmpFileOpts outputDir "haddock-response.txt" $
\responseFileName hf -> do
when haddockSupportsUTF8 (hSetEncoding hf utf8)
let responseContents =
unlines $ map escapeArg renderedArgs
hPutStr hf responseContents
hClose hf
info verbosity $ responseFileName ++ " contents: <<<"
info verbosity responseContents
info verbosity $ ">>> " ++ responseFileName
let respFile = "@" ++ responseFileName
k ([respFile], result)
else
k (renderedArgs, 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
-- Support a gcc-like response file syntax. Each separate
-- argument and its possible parameter(s), will be separated in the
-- response file by an actual newline; all other whitespace,
-- single quotes, double quotes, and the character used for escaping
-- (backslash) are escaped. The called program will need to do a similar
-- inverse operation to de-escape and re-constitute the argument list.
escape cs c
| isSpace c
|| '\\' == c
|| '\'' == c
|| '"' == c = c:'\\':cs -- n.b., our caller must reverse the result
| otherwise = c:cs
escapeArg = reverse . foldl' escape []
renderPureArgs :: Version -> Compiler -> Platform -> HaddockArgs -> [String]
renderPureArgs version comp platform 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 platform 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 >= mkVersion [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)
-> NoCallStackIO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackagePaths ipkgs mkHtmlPath = do
interfaces <- sequenceA
[ 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 mkPackageName [ "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 :: Verbosity
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackageFlags verbosity lbi clbi htmlTemplate = do
let allPkgs = installedPkgs lbi
directDeps = map fst (componentPackageDeps clbi)
transitiveDeps <- case PackageIndex.dependencyClosure allPkgs directDeps of
Left x -> return x
Right inf -> die' verbosity $ "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))
-- We want the legacy unit ID here, because it gives us nice paths
-- (Haddock people don't care about the dependencies)
: initialPathTemplateEnv
pkg_id
(mkLegacyUnitId pkg_id)
(compilerInfo (compiler lbi))
(hostPlatform lbi)
-- ------------------------------------------------------------------------------
-- hscolour support.
hscolour :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour = hscolour' dieNoVerbosity ForDevelopment
hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found.
-> HaddockTarget
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour' onNoHsColour haddockTarget pkg_descr lbi suffixes flags =
either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<<
lookupProgramVersion verbosity hscolourProgram
(orLaterVersion (mkVersion [1,8])) (withPrograms lbi)
where
go :: ConfiguredProgram -> IO ()
go hscolourProg = do
setupMessage verbosity "Running hscolour for" (packageId pkg_descr)
createDirectoryIfMissingVerbose verbosity True $
hscolourPref haddockTarget distPref pkg_descr
withAllComponentsInBuildOrder pkg_descr lbi $ \comp clbi -> do
componentInitialBuildSteps distPref pkg_descr lbi clbi verbosity
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
let
doExe com = case (compToExe com) of
Just exe -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr
</> unUnqualComponentName (exeName exe) </> "src"
runHsColour hscolourProg outputDir =<< getExeSourceFiles verbosity lbi exe clbi
Nothing -> do
warn (fromFlag $ hscolourVerbosity flags)
"Unsupported component, skipping..."
return ()
case comp of
CLib lib -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr </> "src"
runHsColour hscolourProg outputDir =<< getLibSourceFiles verbosity lbi lib clbi
CFLib flib -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr
</> unUnqualComponentName (foreignLibName flib) </> "src"
runHsColour hscolourProg outputDir =<< getFLibSourceFiles verbosity lbi flib clbi
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 (mkVersion [1,9]) ->
runProgram verbosity prog
["-print-css", "-o" ++ outputDir </> "hscolour.css"]
| otherwise -> return ()
Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css")
for_ moduleFiles $ \(m, inFile) ->
runProgram 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,
hscolourForeignLibs = haddockForeignLibs flags,
hscolourVerbosity = haddockVerbosity flags,
hscolourDistPref = haddockDistPref flags
}
-- ------------------------------------------------------------------------------
-- Boilerplate Monoid instance.
instance Monoid HaddockArgs where
mempty = gmempty
mappend = (<>)
instance Semigroup HaddockArgs where
(<>) = gmappend
instance Monoid Directory where
mempty = Dir "."
mappend = (<>)
instance Semigroup Directory where
Dir m <> Dir n = Dir $ m </> n
| mydaum/cabal | Cabal/Distribution/Simple/Haddock.hs | bsd-3-clause | 32,090 | 0 | 28 | 9,606 | 6,996 | 3,598 | 3,398 | 586 | 9 |
{-# LANGUAGE QuasiQuotes #-}
module Huff (
huff,
Spec,
Domain(),
Problem(),
Literal(),
Term(),
module Huff
) where
import Huff.Compile.AST (Problem,Term(..),Literal(..))
import Huff.Input (Spec,Domain,Operator(..))
import Huff.QQ (huff)
import qualified Huff.FF.Planner as FF
import Data.Maybe (mapMaybe)
infixr 3 /\
(/\) :: Term -> Term -> Term
p /\ q = TAnd [p,q]
infixr 4 \/
(\/) :: Term -> Term -> Term
p \/ q = TOr [p,q]
imply :: Term -> Term -> Term
imply = TImply
class Has_neg a where
neg :: a -> a
instance Has_neg Literal where
neg (LAtom a) = LNot a
neg (LNot a) = LAtom a
instance Has_neg Term where
neg = TNot
findPlan :: Spec a -> IO (Maybe [a])
findPlan (prob,dom) =
do mb <- FF.findPlan prob dom
case mb of
Just xs -> return (Just (mapMaybe opVal (FF.resSteps xs)))
Nothing -> return Nothing
| elliottt/huff | src/Huff.hs | bsd-3-clause | 913 | 0 | 17 | 246 | 388 | 216 | 172 | 44 | 2 |
{-# LANGUAGE NoImplicitPrelude
, CPP
, GADTs
, FlexibleContexts
, ScopedTypeVariables
, KindSignatures
, TypeFamilies
, DeriveDataTypeable
, TypeOperators
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Math.Combinatorics.Species.Enumerate
-- Copyright : (c) Brent Yorgey 2010
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Enumeration (i.e. exhaustive generation of structures) of both
-- labeled and unlabeled species.
--
-----------------------------------------------------------------------------
module Math.Combinatorics.Species.Enumerate
(
-- * Enumeration methods
enumerate
, enumerateL
, enumerateU
, enumerateM
, enumerateAll
, enumerateAllU
-- * Tools for dealing with structure types
, Enumerable(..)
, Structure(..), extractStructure, unsafeExtractStructure
, structureType, showStructureType
-- * Where all the work actually happens
, enumerate', enumerateE
) where
import Math.Combinatorics.Species.Class
import Math.Combinatorics.Species.Types
import Math.Combinatorics.Species.AST
import Math.Combinatorics.Species.Structures
import qualified Math.Combinatorics.Species.Util.Interval as I
import qualified Math.Combinatorics.Multiset as MS
import Math.Combinatorics.Multiset (Multiset(..), (+:))
import Data.Typeable
import NumericPrelude
#if MIN_VERSION_numeric_prelude(0,2,0)
#else
import PreludeBase hiding (cycle)
#endif
-- | Given an AST describing a species, with a phantom type parameter
-- representing the structure of the species, and an underlying
-- multiset of elements, compute a list of all possible structures
-- built over the underlying multiset. (Of course, it would be
-- really nice to have a real dependently-typed language for this!)
--
-- Unfortunately, 'TSpeciesAST' cannot be made an instance of
-- 'Species', so if we want to be able to enumerate structures given
-- an expression of the 'Species' DSL as input, the output must be
-- existentially quantified; see 'enumerateE'.
--
-- Generating structures over base elements from a /multiset/
-- unifies labeled and unlabeled generation into one framework.
-- To enumerate labeled structures, use a multiset where each
-- element occurs exactly once; to enumerate unlabeled structures,
-- use a multiset with the desired number of copies of a single
-- element. To do labeled generation we could get away without the
-- generality of multisets, but to do unlabeled generation we need
-- the full generality anyway.
--
-- 'enumerate'' does all the actual work, but is not meant to be used
-- directly; use one of the specialized @enumerateXX@ methods.
enumerate' :: TSpeciesAST s -> Multiset a -> [s a]
enumerate' TZero _ = []
enumerate' TOne (MS []) = [Unit]
enumerate' TOne _ = []
enumerate' (TN n) (MS []) = map Const [1..n]
enumerate' (TN _) _ = []
enumerate' TX (MS [(x,1)]) = [Id x]
enumerate' TX _ = []
enumerate' TE xs = [Set (MS.toList xs)]
enumerate' TC m = map Cycle (MS.cycles m)
enumerate' TL xs = MS.permutations xs
enumerate' TSubset xs = map (Set . MS.toList . fst) (MS.splits xs)
enumerate' (TKSubset k) xs = map (Set . MS.toList)
(MS.kSubsets (fromIntegral k) xs)
enumerate' TElt xs = map (Id . fst) . MS.toCounts $ xs
enumerate' (f :+:: g) xs = map Inl (enumerate' (stripI f) xs)
++ map Inr (enumerate' (stripI g) xs)
-- A better solution here might be to change MS.splits to only
-- return splits which are of appropriate sizes.
enumerate' (f :*:: g) xs = [ x :*: y
| (s1,s2) <- MS.splits xs
, (fromIntegral $ MS.size s1) `I.elem` (getI f)
, (fromIntegral $ MS.size s2) `I.elem` (getI g)
, x <- enumerate' (stripI f) s1
, y <- enumerate' (stripI g) s2
]
enumerate' (f :.:: g) xs = [ Comp y
| p <- MS.partitions xs
, (fromIntegral $ MS.size p) `I.elem` (getI f)
, all ((`I.elem` (getI g)) . fromIntegral . MS.size) (MS.toList p)
, xs' <- MS.sequenceMS . fmap (enumerate' (stripI g)) $ p
, y <- enumerate' (stripI f) xs'
]
enumerate' (f :><:: g) xs
| any (/= 1) $ MS.getCounts xs
= error "Unlabeled enumeration does not (yet) work with cartesian product."
enumerate' (f :><:: g) xs = [ x :*: y
| x <- enumerate' (stripI f) xs
, y <- enumerate' (stripI g) xs
]
enumerate' (f :@:: g) xs
| any (/= 1) $ MS.getCounts xs
= error "Unlabeled enumeration does not (yet) work with functor composition."
enumerate' (f :@:: g) xs = map Comp
. enumerate' (stripI f)
. MS.fromDistinctList
. enumerate' (stripI g)
$ xs
enumerate' (TDer f) xs = map Comp
. enumerate' (stripI f)
$ (Star,1) +: fmap Original xs
enumerate' (TNonEmpty f) (MS []) = []
enumerate' (TNonEmpty f) xs = enumerate' (stripI f) xs
enumerate' (TRec f) xs = map Mu $ enumerate' (apply f (TRec f)) xs
enumerate' (TOfSize f p) xs
| p (fromIntegral . sum . MS.getCounts $ xs)
= enumerate' (stripI f) xs
| otherwise = []
enumerate' (TOfSizeExactly f n) xs
| (fromIntegral . sum . MS.getCounts $ xs) == n
= enumerate' (stripI f) xs
| otherwise = []
-- | An existential wrapper for structures, hiding the structure
-- functor and ensuring that it is 'Typeable'.
data Structure a where
Structure :: Typeable f => f a -> Structure a
-- | Extract the contents from a 'Structure' wrapper, if we know the
-- type, and map it into an isomorphic type. If the type doesn't
-- match, return a helpful error message instead.
extractStructure :: forall f a. (Enumerable f, Typeable a) =>
Structure a -> Either String (f a)
extractStructure (Structure s) =
case cast s of
Nothing -> Left $
"Structure type mismatch.\n"
++ " Expected: " ++ showStructureType (typeOf (undefined :: StructTy f a)) ++ "\n"
++ " Inferred: " ++ showStructureType (typeOf s)
Just y -> Right (iso y)
-- | A version of 'extractStructure' which calls 'error' with the
-- message in the case of a type mismatch, instead of returning an
-- 'Either'.
unsafeExtractStructure :: (Enumerable f, Typeable a) => Structure a -> f a
unsafeExtractStructure = either error id . extractStructure
-- | @'structureType' s@ returns a String representation of the
-- functor type which represents the structure of the species @s@.
-- In particular, if @structureType s@ prints @\"T\"@, then you can
-- safely use 'enumerate' and friends by writing
--
-- > enumerate s ls :: [T a]
--
-- where @ls :: [a]@.
--
-- For example,
--
-- > > structureType octopus
-- > "Comp Cycle []"
-- > > enumerate octopus [1,2,3] :: [Comp Cycle [] Int]
-- > [<[3,2,1]>,<[3,1,2]>,<[2,3,1]>,<[2,1,3]>,<[1,3,2]>
-- > ,<[1,2,3]>,<[1],[3,2]>,<[1],[2,3]>,<[3,1],[2]>
-- > ,<[1,3],[2]>,<[2,1],[3]>,<[1,2],[3]>,<[2],[1],[3]>
-- > ,<[1],[2],[3]>]
--
-- Note, however, that providing a type annotation on 'enumerate' in
-- this way is usually only necessary at the @ghci@ prompt; when used
-- in the context of a larger program the type of a call to
-- 'enumerate' can often be inferred.
structureType :: ESpeciesAST -> String
structureType (Wrap s) = showStructureType . extractType $ (stripI s)
where extractType :: forall s. Typeable s => TSpeciesAST s -> TypeRep
extractType _ = typeOf1 (undefined :: s ())
-- | Show a 'TypeRep' while stripping off qualifier portions of 'TyCon'
-- names. This is essentially copied and pasted from the
-- "Data.Typeable" source, with a number of cases taken out that we
-- don't care about (special cases for @(->)@, tuples, etc.).
showStructureType :: TypeRep -> String
showStructureType t = showsPrecST 0 t ""
where showsPrecST :: Int -> TypeRep -> ShowS
showsPrecST p t =
case splitTyConApp t of
(tycon, []) -> showString (dropQuals $ tyConName tycon)
(tycon, [x]) | tyConName tycon == "[]"
-> showChar '[' . showsPrecST 11 x . showChar ']'
(tycon, args) -> showParen (p > 9)
$ showString (dropQuals $ tyConName tycon)
. showChar ' '
. showArgsST args
showArgsST :: [TypeRep] -> ShowS
showArgsST [] = id
showArgsST [t] = showsPrecST 10 t
showArgsST (t:ts) = showsPrecST 10 t . showChar ' ' . showArgsST ts
dropQuals :: String -> String
dropQuals = reverse . takeWhile (/= '.') . reverse
-- | 'enumerateE' is a variant of 'enumerate'' which takes an
-- (existentially quantified) typed AST and returns a list of
-- existentially quantified structures. This is also not meant to
-- be used directly. Instead, you should use one of the other
-- @enumerateX@ methods.
enumerateE :: ESpeciesAST -> Multiset a -> [Structure a]
enumerateE (Wrap s) m
| fromIntegral (sum (MS.getCounts m)) `I.elem` (getI s)
= map Structure (enumerate' (stripI s) m)
| otherwise = []
-- XXX add examples to all of these.
-- | @enumerate s ls@ computes a complete list of distinct
-- @s@-structures over the underlying multiset of labels @ls@. For
-- example:
--
-- > > enumerate octopi [1,2,3] :: [Comp Cycle [] Int]
-- > [<[3,2,1]>,<[3,1,2]>,<[2,3,1]>,<[2,1,3]>,<[1,3,2]>,<[1,2,3]>,
-- > <[1],[3,2]>,<[1],[2,3]>,<[3,1],[2]>,<[1,3],[2]>,<[2,1],[3]>,
-- > <[1,2],[3]>,<[2],[1],[3]>,<[1],[2],[3]>]
-- >
-- > > enumerate octopi [1,1,2] :: [Comp Cycle [] Int]
-- > [<[2,1,1]>,<[1,2,1]>,<[1,1,2]>,<[2,1],[1]>,<[1,2],[1]>,
-- > <[1,1],[2]>,<[1],[1],[2]>]
-- >
-- > > enumerate subsets "abc" :: [Set Int]
-- > [{'a','b','c'},{'a','b'},{'a','c'},{'a'},{'b','c'},{'b'},{'c'},{}]
-- >
-- > > enumerate simpleGraphs [1,2,3] :: [Comp Set Set Int]
-- > [{{1,2},{1,3},{2,3}},{{1,2},{1,3}},{{1,2},{2,3}},{{1,2}},{{1,3},{2,3}},
-- > {{1,3}},{{2,3}},{}]
--
-- There is one caveat: since the type of the generated structures
-- is different for each species, they must be cast (using the magic
-- of "Data.Typeable") out of an existential wrapper; this is why
-- type annotations are required in all the examples above. Of
-- course, if a call to 'enumerate' is used in the context of some
-- larger program, a type annotation will probably not be needed,
-- due to the magic of type inference.
--
-- For help in knowing what type annotation you can give when
-- enumerating the structures of a particular species at the @ghci@
-- prompt, see the 'structureType' function. To be able to use your
-- own custom data type in an enumeration, just make your data type
-- an instance of the 'Enumerable' type class; this can be done for
-- you automatically by "Math.Combinatorics.Species.TH".
--
-- If an invalid type annotation is given, 'enumerate' will call
-- 'error' with a helpful error message. This should not be much of
-- an issue in practice, since usually 'enumerate' will be used at a
-- specific type; it's hard to imagine a usage of 'enumerate' which
-- will sometimes work and sometimes fail. However, those who like
-- their functions total can use 'extractStructure' to make a
-- version of 'enumerate' (or the other variants) with a return type
-- of @['Either' 'String' (f a)]@ (which will return an annoying ton of
-- duplicate error messages) or @'Either' 'String' [f a]@ (which has the
-- unfortunate property of being much less lazy than the current
-- versions, since it must compute the entire list before deciding
-- whether to return @'Left'@ or @'Right'@).
--
-- For slight variants on 'enumerate', see 'enumerateL',
-- 'enumerateU', and 'enumerateM'.
enumerate :: (Enumerable f, Typeable a, Eq a) => SpeciesAST -> [a] -> [f a]
enumerate s = enumerateM s . MS.fromListEq
-- | Labeled enumeration: given a species expression and a list of
-- labels (which are assumed to be distinct), compute the list of
-- all structures built from the given labels. If the type given
-- for the enumeration does not match the species expression (via an
-- 'Enumerable' instance), call 'error' with an error message
-- explaining the mismatch. This is slightly more efficient than
-- 'enumerate' for lists of labels which are known to be distinct,
-- since it doesn't have to waste time checking for
-- duplicates. (However, it probably doesn't really make much
-- difference, since the time to do the actual enumeration will
-- usually dwarf the time to process the list of labels anyway.)
--
-- For example:
--
-- > > enumerateL ballots [1,2,3] :: [Comp [] Set Int]
-- > [[{1,2,3}],[{2,3},{1}],[{1},{2,3}],[{2},{1,3}],[{1,3},{2}],[{3},{1,2}]
-- > ,[{1,2},{3}],[{3},{2},{1}],[{3},{1},{2}],[{2},{3},{1}],[{2},{1},{3}]
-- > ,[{1},{3},{2}],[{1},{2},{3}]]
enumerateL :: (Enumerable f, Typeable a) => SpeciesAST -> [a] -> [f a]
enumerateL s = enumerateM s . MS.fromDistinctList
-- | Unlabeled enumeration: given a species expression and an integer
-- indicating the number of labels to use, compute the list of all
-- unlabeled structures of the given size. If the type given for
-- the enumeration does not match the species expression, call
-- 'error' with an error message explaining the mismatch.
--
-- Note that @'enumerateU' s n@ is equivalent to @'enumerate' s
-- (replicate n ())@.
--
-- For example:
--
-- > > enumerateU octopi 4 :: [Comp Cycle [] ()]
-- > [<[(),(),(),()]>,<[(),()],[(),()]>,<[(),(),()],[()]>
-- > ,<[(),()],[()],[()]>,<[()],[()],[()],[()]>]
enumerateU :: Enumerable f => SpeciesAST -> Int -> [f ()]
enumerateU s n = enumerateM s (MS.fromCounts [((),n)])
-- | General enumeration: given a species expression and a multiset of
-- labels, compute the list of all distinct structures built from
-- the given labels. If the type given for the enumeration does not
-- match the species expression, call 'error' with a message
-- explaining the mismatch.
enumerateM :: (Enumerable f, Typeable a) => SpeciesAST -> Multiset a -> [f a]
enumerateM s m = map unsafeExtractStructure $ enumerateE (annotate s) m
-- | Lazily enumerate all unlabeled structures.
--
-- For example:
--
-- > > take 10 $ enumerateAllU octopi :: [Comp Cycle [] ()]
-- > [<[()]>,<[(),()]>,<[()],[()]>,<[(),(),()]>,<[(),()],[()]>
-- > ,<[()],[()],[()]>,<[(),(),(),()]>,<[(),()],[(),()]>
-- > ,<[(),(),()],[()]>,<[(),()],[()],[()]>]
enumerateAllU :: Enumerable f => SpeciesAST -> [f ()]
enumerateAllU s = concatMap (enumerateU s) [0..]
-- | Lazily enumerate all labeled structures, using [1..] as the
-- labels.
--
-- For example:
--
-- > > take 10 $ enumerateAll ballots :: [Comp [] Set Int]
-- > [[],[{1}],[{1,2}],[{2},{1}],[{1},{2}],[{1,2,3}],[{2,3},{1}]
-- > ,[{1},{2,3}],[{2},{1,3}],[{1,3},{2}]]
enumerateAll :: Enumerable f => SpeciesAST -> [f Int]
enumerateAll s = concatMap (\n -> enumerateL s (take n [1..])) [0..]
-- | The 'Enumerable' class allows you to enumerate structures of any
-- type, by declaring an instance of 'Enumerable'. The 'Enumerable'
-- instance requires you to declare a standard structure type (see
-- "Math.Combinatorics.Species.Structures") associated with your
-- type, and a mapping 'iso' from the standard type to your custom
-- one. Instances are provided for all the standard structure types
-- so you can enumerate species without having to provide your own
-- custom data type as the target of the enumeration if you don't
-- want to.
--
-- You should only rarely have to explicitly make an instance of
-- 'Enumerable' yourself; Template Haskell code to derive instances
-- for you is provided in "Math.Combinatorics.Species.TH".
class Typeable (StructTy f) => Enumerable (f :: * -> *) where
-- | The standard structure type (see
-- "Math.Combinatorics.Species.Structures") that will map into @f@.
type StructTy f :: * -> *
-- | The mapping from @'StructTy' f@ to @f@.
iso :: StructTy f a -> f a
instance Enumerable Void where
type StructTy Void = Void
iso = id
instance Enumerable Unit where
type StructTy Unit = Unit
iso = id
instance Typeable a => Enumerable (Const a) where
type StructTy (Const a) = Const a
iso = id
instance Enumerable Id where
type StructTy Id = Id
iso = id
instance (Enumerable f, Enumerable g) => Enumerable (f :+: g) where
type StructTy (f :+: g) = StructTy f :+: StructTy g
iso (Inl x) = Inl (iso x)
iso (Inr y) = Inr (iso y)
instance (Enumerable f, Enumerable g) => Enumerable (f :*: g) where
type StructTy (f :*: g) = StructTy f :*: StructTy g
iso (x :*: y) = iso x :*: iso y
instance (Enumerable f, Functor f, Enumerable g) => Enumerable (f :.: g) where
type StructTy (f :.: g) = StructTy f :.: StructTy g
iso (Comp fgx) = Comp (fmap iso (iso fgx))
instance Enumerable [] where
type StructTy [] = []
iso = id
instance Enumerable Cycle where
type StructTy Cycle = Cycle
iso = id
instance Enumerable Set where
type StructTy Set = Set
iso = id
instance Enumerable Star where
type StructTy Star = Star
iso = id
instance Typeable f => Enumerable (Mu f) where
type StructTy (Mu f) = Mu f
iso = id
instance Enumerable Maybe where
type StructTy Maybe = Unit :+: Id
iso (Inl Unit) = Nothing
iso (Inr (Id x)) = Just x
| timsears/species | Math/Combinatorics/Species/Enumerate.hs | bsd-3-clause | 18,320 | 0 | 16 | 4,626 | 3,199 | 1,736 | 1,463 | 184 | 5 |
module Language.Granule.Syntax.Preprocessor.Latex
( processGranuleLatex
, unLatex
)
where
import Data.Char (isSpace)
import Control.Arrow ((>>>))
data DocType
= Latex
| GranuleBlock
-- | Extract @\begin{env}@ code blocks @\end{env}@ from tex files on a
-- line-by-line basis, where @env@ is the name of the relevant environment. Maps
-- other lines to the empty string, such that line numbers are preserved.
unLatex :: String -> (String -> String)
unLatex env = processGranuleLatex (const "") env id
-- | Transform the input by the given processing functions for Granule and Latex
-- (currently operating on a line-by-line basis)
processGranuleLatex
:: (String -> String) -- ^ the processing function to apply to each line of latex
-> String -- ^ the name of the environment to check
-> (String -> String) -- ^ the processing function to apply to each line of granule code
-> (String -> String)
processGranuleLatex fTex env fGr = lines >>> (`zip` [1..]) >>> go Latex >>> unlines
where
go :: DocType -> [(String, Int)] -> [String]
go Latex ((line, lineNumber) : ls)
| strip line == "\\begin{" <> env <> "}" = fTex line : go GranuleBlock ls
| strip line == "\\end{" <> env <> "}" = error $ "Unmatched `\\end{" <> env <> "}` on line " <> show lineNumber
| otherwise = fTex line : go Latex ls
go GranuleBlock ((line, lineNumber) : ls)
| strip line == "\\end{" <> env <> "}" = fTex line : go Latex ls
| strip line == "\\begin{" <> env <> "}" = error $ "Unmatched `\\begin{" <> env <> "}` on line " <> show lineNumber
| otherwise = fGr line : go GranuleBlock ls
go _ [] = []
-- Remove trailing whitespace (hey, should we be using @Text@?)
strip :: String -> String
strip = reverse . dropWhile isSpace . reverse . dropWhile isSpace
| dorchard/gram_lang | frontend/src/Language/Granule/Syntax/Preprocessor/Latex.hs | bsd-3-clause | 1,907 | 0 | 13 | 489 | 482 | 252 | 230 | 28 | 3 |
{-# LANGUAGE OverloadedStrings #-}
import Network.NetSpec
import Network.NetSpec.Text
-- Notice the restrictions NetSpec places on how you can communicate.
-- Working within NetSpec isn't well-suited for all situations;
-- it is specialized for situations where there is
-- a deterministic sequence of communication.
main :: IO ()
main = runSpec ServerSpec {
_ports = [PortNumber 5001, PortNumber 5002]
, _begin = \hs -> do
hs ! "Welcome to the one-for-one chat program."
hs ! "Send a message in order to receive one."
hs ! "Say \"bye\" to stop."
, _loop = \[a, b] () -> do
lineA <- receive a
lineB <- receive b
a ! lineB
b ! lineA
if lineA == "bye\r" || lineB == "bye\r"
then stop_ else continue_
, _end = \hs () -> hs ! "That's all folks."
}
| DanBurton/netspec | examples/Chat.hs | bsd-3-clause | 826 | 1 | 14 | 216 | 187 | 98 | 89 | 18 | 2 |
------------------------------------------------------------------------------
-- |
-- Maintainer : Ralf Laemmel, Joost Visser
-- Stability : experimental
-- Portability : portable
--
-- This module is part of 'Sdf2Haskell', a tool for generating a set of
-- Haskell data types from an SDF grammar. This module provides functionality
-- for calling the external parser SGLR from within Haskell and marshalling
-- the resulting abstract syntax tree to a strongly-typed Haskell term.
------------------------------------------------------------------------------
module SGLR where
import System.Exit
import System.Environment (getProgName)
import System.Cmd (system)
import Data.Unique (newUnique, hashUnique)
import System.IO (readFile,hPutStrLn,stderr)
import System.Directory (removeFile)
import Data.ATerm.Lib (fromATerm, readATerm, ATermConvertible,
dehyphenAST, afunCap, ATerm(..)
)
import ImplodePT (compensateImplodePT)
------------------------------------------------------------------------------
-- * Interaction with the system.
-- | Call the external sglr parser.
sglr :: ATermConvertible a
=> FilePath -- ^ table
-> FilePath -- ^ term
-> String -- ^ top sort
-> IO a
sglr tableName termName sortName
= do unique <- newUnique
let newName = termName++(show . hashUnique $ unique)
let asfixName = newName++".asfix"
let afName = newName++".af"
let sglrCmd = "sglr -p "++tableName++
" -i "++termName++
" -o "++asfixName++
" -s "++sortName
let implodeCmd = "implodePT -t -ALclpqX"++
" -i "++asfixName++
" -o "++afName
progName <- getProgName
errLn $ "["++progName++"] "++sglrCmd
exitOK $ system sglrCmd
errLn $ "["++progName++"] "++implodeCmd
exitOK $ system implodeCmd
af <- readFile afName
--return . fromATerm . afunCap . implodeLit . readATerm . dehyphen $ af
--let t1 = readATerm . dehyphen $ af
let t1 = dehyphenAST . readATerm $ af
--putStrLn $ "After dehyphen: \n"++show t1
let t2 = compensateImplodePT t1
--putStrLn $ "After implodeOpt: \n"++show t2
let t3 = afunCap t2
return . fromATerm $ t3
-- | Call the external sglr parser but only sends msgs on error and cleans
-- temporary files.
sglrSilent :: ATermConvertible a
=> FilePath
-> FilePath
-> String
-> IO a
sglrSilent tableName termName sortName
= do progName <- getProgName
unique <- newUnique
let newName = termName ++ (show . hashUnique $ unique)
let asfixName = newName ++ ".asfix"
let sglrCmd = concat [ "sglr -p ", tableName, " -i ", termName
, " -o ", asfixName, " -s ", sortName]
exitCode <- system sglrCmd
case exitCode of
(ExitFailure code) -> do errLn $ "["++progName++"] "++sglrCmd
removeFile asfixName
fail $ "Exit code: " ++ show code
(ExitSuccess) -> return ()
let afName = newName ++ ".af"
let implodeCmd = concat [ "implodePT -t -ALclpqX -i ", asfixName
, " -o ", afName]
exitCode <- system implodeCmd
case exitCode of
(ExitFailure code) -> do errLn $ "["++progName++"] "++implodeCmd
removeFile afName
fail $ "Exit code: " ++ show code
(ExitSuccess) -> return ()
af <- readFile afName
_ <- removeFile asfixName
_ <- removeFile afName
let t1 = dehyphenAST . readATerm $ af
let t2 = compensateImplodePT t1
let t3 = afunCap t2
return . fromATerm $ t3
-- | Helper function for reporting errors and progress to stderr
errLn :: String -> IO ()
errLn str = hPutStrLn stderr str
-- | Ensure that the given computation exits with an error code
-- that indicates successful execution.
exitOK :: IO ExitCode -> IO ()
exitOK io
= do exitCode <- io
case exitCode of
(ExitSuccess) -> return ()
(ExitFailure code) -> fail $ "Exit code: " ++ show code
| jkoppel/Strafunski-Sdf2Haskell | generator/SGLR.hs | bsd-3-clause | 4,290 | 41 | 16 | 1,303 | 891 | 461 | 430 | 79 | 3 |
{-# LANGUAGE TypeFamilies, DataKinds, TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
module Database.SQLFragment.Operators where
-- standard
import Data.Monoid
import Data.List (intercalate)
import Data.String
import GHC.TypeLits
-- third-party
import Data.HList
-- local
import Database.SQLFragment.SQLFragment
import Database.SQLFragment.Internal
import Database.SQLFragment.TypeFamilies
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> :set -XDataKinds
--
-- >>> let toSelectQuery' q = unwords.lines.toSelectQuery $ q
--
-- * Combination
infixl 1 !&!, !::!, !:@!, !::#!
infixl 3 !\!, !%!, !%%!
infixl 4 !>!, !<!, !>=!, !<=!, !=!, !/=!, !&&!, !||!, !=%!, !=~!
infixl 4 !>?!, !<?!, !>=?!, !<=?!, !=?!, !/=?!, !&&?!, !||?!, !=%?!, !=~?!
infixl 8 !#!, !#:!, !#:@!, !#:#!
-- | Combines two fragments. Similar to '<>' but combines
-- phantom types as well.
--
-- >>> toSelectQuery' $ "a" !&! "t."
-- "SELECT a FROM t"
-- >>> toSelectQuery' $ "a" !&! "b"
-- "SELECT a, b"
-- >>> toSelectQuery' $ "t.a1" !&! "s.b" !&! "t.a2"
-- "SELECT t.a1, s.b, t.a2 FROM t, s"
(!&!) :: SQLFragment e p
-> SQLFragment e' p'
-> SQLFragment (HAppendListR e e') (HAppendListR p p')
q !&! q' = forgetTypes $ (clearTypes q) <> (clearTypes q')
-- | Same as !&! but higher fixity
(!#!) :: SQLFragment e p
-> SQLFragment e' p'
-> SQLFragment (HAppendListR e e') (HAppendListR p p')
q !#! q' = forgetTypes $ q !&! q'
-- * Columns Promotions
--
-- | Promotes columns to the WHERE clause
--
-- >>> toSelectQuery' $ "" !\! "a > 1" !#! "b > 1"
-- "WHERE (a > 1) AND (b > 1)"
-- >>> toSelectQuery' $ "a" !\! "b > 1"
-- "SELECT a WHERE (b > 1)"
--
(!\!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b')
q !\! q' = forgetTypes $ q !&! q0' !&! q'' where
q0' = clearSection COLUMN q'
q'' = pickSection COLUMN WHERE q'
-- | Promotes columns to the HAVINg clause.
--
-- >>> toSelectQuery' $ "a" !\\! "b > 1"
-- "SELECT a HAVING (b > 1)"
--
(!\\!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b')
q !\\! q' = forgetTypes $ q !&! q0' !&! q'' where
q0' = clearSection COLUMN q'
q'' = pickSection COLUMN HAVING q'
-- | Promotes columns to GROUP clause and
-- criteria to HAVING Clauses
--
-- >>> toSelectQuery' $ "t.a" !~! ("a" !\! "b > 1")
-- "SELECT t.a FROM t GROUP BY a HAVING (b > 1)"
--
(!~!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b')
q !~! q' = forgetTypes$ q !&! q0' !&! q'' where
q0' = clearSection COLUMN . clearSection WHERE $ q'
q'' = pickSection COLUMN GROUP q' !&! pickSection WHERE HAVING q'
-- | Promotes columns to ORDER BY clause (Ascending)
--
-- >>> toSelectQuery' $ "t.a" !^! "order"
-- "SELECT t.a FROM t ORDER BY order"
--
(!^!) :: SQLFragment a b -> SQLFragment a' '[] -> SQLFragment a b
q !^! q' = forgetTypes$ q !&! qorder where
qorder = pickSection COLUMN ORDER q'
-- | Promotes columns to ORDER BY clause (Descending)
--
-- >>> toSelectQuery' $ "t.a" !^-! "order"
-- "SELECT t.a FROM t ORDER BY order DESC"
--
(!^-!) :: SQLFragment a b -> SQLFragment a' '[] -> SQLFragment a b
q !^-! q' = q !^! (fromString "$1 DESC" !%! q')
-- * Combining & Formating
-- | Replaces "$n" with columns. Can be chained to combined
-- 2 or more columns into one.
--
-- >>> toSelectQuery' $ "IF($1>0, $1, 0)" !%! "t.a"
-- "SELECT IF(t.a>0, t.a, 0) FROM t"
-- >>> let a = forgetTypes $ "a1" !#! "b1" :: SQLFragment '[String, Double] '[]
-- >>> let b = forgetTypes $ "a2" !#! "b2" :: SQLFragment '[String, Double] '[]
-- >>> toSelectQuery' $ "$1 > $2" !%! a !%! b
-- "SELECT a1 > a2, b1 > b2"
(!%!) :: SQLFragment e '[] -> SQLFragment e '[] -> SQLFragment e '[]
q !%! q' = forgetTypes $ setSection COLUMN formatted (q !&! q') where
formatted = zipWith format
(cycle $ getSection COLUMN q)
(getSection COLUMN q')
-- | Replace $1 with all the column together.
--
-- >>> toSelectQuery' $ "DISTINCT $1" !%%! "a" !#! "b"
-- "SELECT DISTINCT a, b"
(!%%!) :: SQLFragment e p -> SQLFragment e p -> SQLFragment e p
q !%%! q' = forgetTypes $ setSection COLUMN formatted q where
cols = getSection COLUMN q'
cols' = intercalate ", " cols
formatted = zipWith format
(cycle $ getSection COLUMN q)
[cols']
-- ** Arithemitic operators
internOperator1 :: String-> SQLFragment e '[] -> SQLFragment e' '[]
internOperator1 op q = forgetTypes $ fromString op !%! q
internOperator2 :: String-> SQLFragment e '[] -> SQLFragment e '[] -> SQLFragment e '[]
internOperator2 op q q' = forgetTypes $ fromString op !%! q !%! q'
-- SQLFragment are also number, allowings for example
-- >>> "count" * 5
-- | List of Num.
class Nums (a::[*])
instance Nums '[]
instance (Num a, Nums as) => Nums (a ': as)
instance Nums a => Num (SQLFragment a '[]) where
-- instance Num (SQLFragment a '[]) where
(+) = internOperator2 "$1+$2"
(*) = internOperator2 "$1*$2"
(-) = internOperator2 "$1-$2"
negate = internOperator1 "-$1"
abs = internOperator1 "ABS($1)"
signum = error "`signum` not defined for `SQLFragment`"
fromInteger a = fromString $ show a
instance Fractionals a => Fractional (SQLFragment a '[]) where
(/) = internOperator2 "$1/$2"
recip a = 1/a -- internOperator1 "1/$1" a
fromRational a = fromString $ show a
-- | List of Fractional.
class Nums a => Fractionals (a :: [*])
instance Fractionals '[]
instance (Fractional a, Fractionals as) => Fractionals (a ': as)
-- ** Comparaison Operators
-- | columns comparaison operators. Note the result is a column
-- and has to be promoted to a where clause if necessary.
--
-- >>> let a = "a" :: SQLFragment '[String, Maybe Double, String] '[]
-- >>> let b = "b" :: SQLFragment '[Maybe String, Double, String] '[]
-- >>> :t a !>! b
-- a !>! b :: SQLFragment '[Maybe Bool, Maybe Bool, Bool] '[]
-- >>> toSelectQuery$ a !>! b
-- "SELECT (a)>(b)"
-- >>> let x = "x" :: SQLFragment '[String] '[]
-- >>> let y = "y" :: SQLFragment '[Int] '[]
-- >>> toSelectQuery'$ x !\! y !>! "5"
-- "SELECT x WHERE ((y)>(5))"
(!>!) = boolOperator ">"
(!<!) = boolOperator "<"
(!>=!) = boolOperator ">="
(!<=!) = boolOperator "<="
(!=!) = boolOperator "="
(!/=!) = boolOperator "!="
(!&&!) = boolOperator " AND "
(!||!) = boolOperator " OR "
(!=%!) = boolOperator " LIKE "
(!=~!) = boolOperator " RLIKE "
boolOperator :: String
-> SQLFragment a '[]
-> SQLFragment b '[]
-> SQLFragment (ZipToBool a b) '[]
boolOperator op q q' = forgetTypes$ fromString ("($1)"++op++"($2)") !%! q0 !%! q0' where
q0 = clearTypes q
q0' = clearTypes q'
-- ** Comparaison
-- | Comparaison operators with external parameters
-- Note, the result is promoted as in where clause.
--
-- >>> let a = "a" :: SQLFragment '[String, Maybe Double, String] '[]
-- >>> let b = "b" :: SQLFragment '[String] '[]
-- >>> :t a !>?! b
-- a !>?! b :: SQLFragment '[String, Maybe Double, String] '[String]
-- >>> toSelectQuery' $ a !>?! b
-- "SELECT a WHERE ((b)>(?))"
(!>?!) = buildBoolParamOp (!>!)
(!<?!) = buildBoolParamOp (!<!)
(!>=?!) = buildBoolParamOp (!>=!)
(!<=?!) = buildBoolParamOp (!<=!)
(!=?!) = buildBoolParamOp (!=!)
(!/=?!) = buildBoolParamOp (!/=!)
(!&&?!) = buildBoolParamOp (!&&!)
(!||?!) = buildBoolParamOp (!||!)
(!=%?!) = buildBoolParamOp (!=%!)
(!=~?!) = buildBoolParamOp (!=~!)
buildBoolParamOp :: (SQLFragment p' '[]
-> SQLFragment b '[]
-> SQLFragment (ZipToBool p' b) '[])
-> SQLFragment e p
-> SQLFragment p' '[]
-> SQLFragment e (HAppendListR p p')
buildBoolParamOp op q q' = forgetTypes $ q !\! op q' (fromString "?")
type family ZipToBool (a :: [*]) (b :: [*]) :: [*] where
ZipToBool '[] '[] = '[]
ZipToBool ((Tagged l a) ': as) ((Tagged l' b) ': bs) = Tagged l (IfMaybe2 a b Bool) ': ZipToBool as bs
ZipToBool (a ': as) (b ': bs) = IfMaybe2 a b Bool ': ZipToBool as bs
-- * Type operations
-- ** Full type
-- | Retype a fragment with the right one
(!::!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment e' p'
q !::! _ = forgetTypes q
-- | Same as !::! but with higher fixity
(!#:!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment e' p'
q !#:! _ = forgetTypes q
-- ** Label
-- | Label a fragment with the given label
(!:@!) :: SQLFragment '[a] p -> Label (l' :: Symbol) -> SQLFragment '[Tagged l' (GetValue a)] p
q !:@! _ = forgetTypes q
-- | Same as !:@! but with hight fixity
(!#:@!) :: SQLFragment '[a] p -> Label (l' :: Symbol) -> SQLFragment '[Tagged l' (GetValue a)] p
q !#:@! _ = forgetTypes q
-- ** Underlying Type
-- | Change the underlying type but keep the actual label
(!::#!) :: SQLFragment '[Tagged (l::Symbol) a] p -> SQLFragment '[b] '[] -> SQLFragment '[Tagged l (GetValue b)] p
q !::#! _ = forgetTypes q
(!#:#!) :: SQLFragment '[Tagged (l:: Symbol) a] p -> SQLFragment '[b] '[] -> SQLFragment '[Tagged l (GetValue b)] p
q !#:#! _ = forgetTypes q
| maxigit/sql-fragment | src/Database/SQLFragment/Operators.hs | bsd-3-clause | 9,043 | 0 | 12 | 1,981 | 2,434 | 1,321 | 1,113 | -1 | -1 |
-- | TODO: Put some kind of a tutorial here
module Sound.Fluidsynth
( module Sound.Fluidsynth.Audio
, module Sound.Fluidsynth.Event
, module Sound.Fluidsynth.Gen
, module Sound.Fluidsynth.Log
, module Sound.Fluidsynth.Midi
, module Sound.Fluidsynth.Misc
, module Sound.Fluidsynth.Settings
, module Sound.Fluidsynth.Synth
, module Sound.Fluidsynth.Types
) where
import Sound.Fluidsynth.Audio
import Sound.Fluidsynth.Event
import Sound.Fluidsynth.Gen
import Sound.Fluidsynth.Log
import Sound.Fluidsynth.Midi
import Sound.Fluidsynth.Misc
import Sound.Fluidsynth.Settings
import Sound.Fluidsynth.Synth
import Sound.Fluidsynth.Types
| projedi/fluidsynth-hs-complete | src/Sound/Fluidsynth.hs | bsd-3-clause | 659 | 0 | 5 | 90 | 126 | 87 | 39 | 19 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-}
{- A high level language of tactic composition, for building
elaborators from a high level language into the core theory.
This is our interface to proof construction, rather than
ProofState, because this gives us a language to build derived
tactics out of the primitives.
-}
module Idris.Core.Elaborate(module Idris.Core.Elaborate,
module Idris.Core.ProofState) where
import Idris.Core.ProofState
import Idris.Core.ProofTerm(bound_in, getProofTerm, mkProofTerm, bound_in_term,
refocus)
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Typecheck
import Idris.Core.Unify
import Idris.Core.DeepSeq
import Control.DeepSeq
import Control.Monad.State.Strict
import Data.Char
import Data.List
import Debug.Trace
import Util.Pretty hiding (fill)
data ElabState aux = ES (ProofState, aux) String (Maybe (ElabState aux))
deriving Show
type Elab' aux a = StateT (ElabState aux) TC a
type Elab a = Elab' () a
proof :: ElabState aux -> ProofState
proof (ES (p, _) _ _) = p
-- Insert a 'proofSearchFail' error if necessary to shortcut any further
-- fruitless searching
proofFail :: Elab' aux a -> Elab' aux a
proofFail e = do s <- get
case runStateT e s of
OK (a, s') -> do put s'
return $! a
Error err -> lift $ Error (ProofSearchFail err)
explicit :: Name -> Elab' aux ()
explicit n = do ES (p, a) s m <- get
let p' = p { dontunify = n : dontunify p }
put (ES (p', a) s m)
saveState :: Elab' aux ()
saveState = do e@(ES p s _) <- get
put (ES p s (Just e))
loadState :: Elab' aux ()
loadState = do (ES p s e) <- get
case e of
Just st -> put st
_ -> lift $ Error . Msg $ "Nothing to undo"
getNameFrom :: Name -> Elab' aux Name
getNameFrom n = do (ES (p, a) s e) <- get
let next = nextname p
let p' = p { nextname = next + 1 }
put (ES (p', a) s e)
let n' = case n of
UN x -> MN (next+100) x
MN i x -> if i == 99999
then MN (next+500) x
else MN (next+100) x
NS (UN x) s -> MN (next+100) x
_ -> n
return $! n'
setNextName :: Elab' aux ()
setNextName = do env <- get_env
ES (p, a) s e <- get
let pargs = map fst (getArgTys (ptype p))
initNextNameFrom (pargs ++ map fst env)
initNextNameFrom :: [Name] -> Elab' aux ()
initNextNameFrom ns = do ES (p, a) s e <- get
let n' = maxName (nextname p) ns
put (ES (p { nextname = n' }, a) s e)
where
maxName m ((MN i _) : xs) = maxName (max m i) xs
maxName m (_ : xs) = maxName m xs
maxName m [] = m + 1
errAt :: String -> Name -> Elab' aux a -> Elab' aux a
errAt thing n elab = do s <- get
case runStateT elab s of
OK (a, s') -> do put s'
return $! a
Error (At f e) ->
lift $ Error (At f (Elaborating thing n e))
Error e -> lift $ Error (Elaborating thing n e)
erun :: FC -> Elab' aux a -> Elab' aux a
erun f elab = do s <- get
case runStateT elab s of
OK (a, s') -> do put s'
return $! a
Error (ProofSearchFail (At f e))
-> lift $ Error (ProofSearchFail (At f e))
Error (At f e) -> lift $ Error (At f e)
Error e -> lift $ Error (At f e)
runElab :: aux -> Elab' aux a -> ProofState -> TC (a, ElabState aux)
runElab a e ps = runStateT e (ES (ps, a) "" Nothing)
execElab :: aux -> Elab' aux a -> ProofState -> TC (ElabState aux)
execElab a e ps = execStateT e (ES (ps, a) "" Nothing)
initElaborator :: Name -> Context -> Ctxt TypeInfo -> Type -> ProofState
initElaborator = newProof
elaborate :: Context -> Ctxt TypeInfo -> Name -> Type -> aux -> Elab' aux a -> TC (a, String)
elaborate ctxt datatypes n ty d elab = do let ps = initElaborator n ctxt datatypes ty
(a, ES ps' str _) <- runElab d elab ps
return $! (a, str)
-- | Modify the auxiliary state
updateAux :: (aux -> aux) -> Elab' aux ()
updateAux f = do ES (ps, a) l p <- get
put (ES (ps, f a) l p)
-- | Get the auxiliary state
getAux :: Elab' aux aux
getAux = do ES (ps, a) _ _ <- get
return $! a
-- | Set whether to show the unifier log
unifyLog :: Bool -> Elab' aux ()
unifyLog log = do ES (ps, a) l p <- get
put (ES (ps { unifylog = log }, a) l p)
getUnifyLog :: Elab' aux Bool
getUnifyLog = do ES (ps, a) l p <- get
return (unifylog ps)
-- | Process a tactic within the current elaborator state
processTactic' :: Tactic -> Elab' aux ()
processTactic' t = do ES (p, a) logs prev <- get
(p', log) <- lift $ processTactic t p
put (ES (p', a) (logs ++ log) prev)
return $! ()
updatePS :: (ProofState -> ProofState) -> Elab' aux ()
updatePS f = do ES (ps, a) logs prev <- get
put $ ES (f ps, a) logs prev
now_elaborating :: FC -> Name -> Name -> Elab' aux ()
now_elaborating fc f a = updatePS (nowElaboratingPS fc f a)
done_elaborating_app :: Name -> Elab' aux ()
done_elaborating_app f = updatePS (doneElaboratingAppPS f)
done_elaborating_arg :: Name -> Name -> Elab' aux ()
done_elaborating_arg f a = updatePS (doneElaboratingArgPS f a)
elaborating_app :: Elab' aux [(FC, Name, Name)]
elaborating_app = do ES (ps, _) _ _ <- get
return $ map (\ (FailContext x y z) -> (x, y, z))
(while_elaborating ps)
-- Some handy gadgets for pulling out bits of state
-- | Get the global context
get_context :: Elab' aux Context
get_context = do ES p _ _ <- get
return $! (context (fst p))
-- | Update the context.
-- (should only be used for adding temporary definitions or all sorts of
-- stuff could go wrong)
set_context :: Context -> Elab' aux ()
set_context ctxt = do ES (p, a) logs prev <- get
put (ES (p { context = ctxt }, a) logs prev)
get_datatypes :: Elab' aux (Ctxt TypeInfo)
get_datatypes = do ES p _ _ <- get
return $! (datatypes (fst p))
set_datatypes :: Ctxt TypeInfo -> Elab' aux ()
set_datatypes ds = do ES (p, a) logs prev <- get
put (ES (p { datatypes = ds }, a) logs prev)
-- | get the proof term
get_term :: Elab' aux Term
get_term = do ES p _ _ <- get
return $! (getProofTerm (pterm (fst p)))
-- | modify the proof term
update_term :: (Term -> Term) -> Elab' aux ()
update_term f = do ES (p,a) logs prev <- get
let p' = p { pterm = mkProofTerm (f (getProofTerm (pterm p))) }
put (ES (p', a) logs prev)
-- | get the local context at the currently in focus hole
get_env :: Elab' aux Env
get_env = do ES p _ _ <- get
lift $ envAtFocus (fst p)
get_inj :: Elab' aux [Name]
get_inj = do ES p _ _ <- get
return $! (injective (fst p))
get_holes :: Elab' aux [Name]
get_holes = do ES p _ _ <- get
return $! (holes (fst p))
get_probs :: Elab' aux Fails
get_probs = do ES p _ _ <- get
return $! (problems (fst p))
-- | Return recently solved names (that is, the names solved since the
-- last call to get_recents)
get_recents :: Elab' aux [Name]
get_recents = do ES (p, a) l prev <- get
put (ES (p { recents = [] }, a) l prev)
return (recents p)
-- | get the current goal type
goal :: Elab' aux Type
goal = do ES p _ _ <- get
b <- lift $ goalAtFocus (fst p)
return $! (binderTy b)
is_guess :: Elab' aux Bool
is_guess = do ES p _ _ <- get
b <- lift $ goalAtFocus (fst p)
case b of
Guess _ _ -> return True
_ -> return False
-- | Get the guess at the current hole, if there is one
get_guess :: Elab' aux Term
get_guess = do ES p _ _ <- get
b <- lift $ goalAtFocus (fst p)
case b of
Guess t v -> return $! v
_ -> fail "Not a guess"
-- | Typecheck locally
get_type :: Raw -> Elab' aux Type
get_type tm = do ctxt <- get_context
env <- get_env
(val, ty) <- lift $ check ctxt env tm
return $! (finalise ty)
get_type_val :: Raw -> Elab' aux (Term, Type)
get_type_val tm = do ctxt <- get_context
env <- get_env
(val, ty) <- lift $ check ctxt env tm
return $! (finalise val, finalise ty)
-- | get holes we've deferred for later definition
get_deferred :: Elab' aux [Name]
get_deferred = do ES p _ _ <- get
return $! (deferred (fst p))
checkInjective :: (Term, Term, Term) -> Elab' aux ()
checkInjective (tm, l, r) = do ctxt <- get_context
if isInj ctxt tm then return $! ()
else lift $ tfail (NotInjective tm l r)
where isInj ctxt (P _ n _)
| isConName n ctxt = True
isInj ctxt (App _ f a) = isInj ctxt f
isInj ctxt (Constant _) = True
isInj ctxt (TType _) = True
isInj ctxt (Bind _ (Pi _ _ _) sc) = True
isInj ctxt _ = False
-- | get instance argument names
get_instances :: Elab' aux [Name]
get_instances = do ES p _ _ <- get
return $! (instances (fst p))
-- | get auto argument names
get_autos :: Elab' aux [(Name, [Name])]
get_autos = do ES p _ _ <- get
return $! (autos (fst p))
-- | given a desired hole name, return a unique hole name
unique_hole :: Name -> Elab' aux Name
unique_hole = unique_hole' False
unique_hole' :: Bool -> Name -> Elab' aux Name
unique_hole' reusable n
= do ES p _ _ <- get
let bs = bound_in (pterm (fst p)) ++
bound_in_term (ptype (fst p))
let nouse = holes (fst p) ++ bs ++ dontunify (fst p) ++ usedns (fst p)
n' <- return $! uniqueNameCtxt (context (fst p)) n nouse
ES (p, a) s u <- get
case n' of
MN i _ -> when (i >= nextname p) $
put (ES (p { nextname = i + 1 }, a) s u)
_ -> return $! ()
return $! n'
elog :: String -> Elab' aux ()
elog str = do ES p logs prev <- get
put (ES p (logs ++ str ++ "\n") prev)
getLog :: Elab' aux String
getLog = do ES p logs _ <- get
return $! logs
-- The primitives, from ProofState
attack :: Elab' aux ()
attack = processTactic' Attack
claim :: Name -> Raw -> Elab' aux ()
claim n t = processTactic' (Claim n t)
claimFn :: Name -> Name -> Raw -> Elab' aux ()
claimFn n bn t = processTactic' (ClaimFn n bn t)
unifyGoal :: Raw -> Elab' aux ()
unifyGoal t = processTactic' (UnifyGoal t)
exact :: Raw -> Elab' aux ()
exact t = processTactic' (Exact t)
fill :: Raw -> Elab' aux ()
fill t = processTactic' (Fill t)
match_fill :: Raw -> Elab' aux ()
match_fill t = processTactic' (MatchFill t)
prep_fill :: Name -> [Name] -> Elab' aux ()
prep_fill n ns = processTactic' (PrepFill n ns)
complete_fill :: Elab' aux ()
complete_fill = processTactic' CompleteFill
solve :: Elab' aux ()
solve = processTactic' Solve
start_unify :: Name -> Elab' aux ()
start_unify n = processTactic' (StartUnify n)
end_unify :: Elab' aux ()
end_unify = processTactic' EndUnify
-- Clear the list of variables not to unify, and try to solve them
unify_all :: Elab' aux ()
unify_all = processTactic' UnifyAll
regret :: Elab' aux ()
regret = processTactic' Regret
compute :: Elab' aux ()
compute = processTactic' Compute
computeLet :: Name -> Elab' aux ()
computeLet n = processTactic' (ComputeLet n)
simplify :: Elab' aux ()
simplify = processTactic' Simplify
hnf_compute :: Elab' aux ()
hnf_compute = processTactic' HNF_Compute
eval_in :: Raw -> Elab' aux ()
eval_in t = processTactic' (EvalIn t)
check_in :: Raw -> Elab' aux ()
check_in t = processTactic' (CheckIn t)
intro :: Maybe Name -> Elab' aux ()
intro n = processTactic' (Intro n)
introTy :: Raw -> Maybe Name -> Elab' aux ()
introTy ty n = processTactic' (IntroTy ty n)
forall :: Name -> Maybe ImplicitInfo -> Raw -> Elab' aux ()
forall n i t = processTactic' (Forall n i t)
letbind :: Name -> Raw -> Raw -> Elab' aux ()
letbind n t v = processTactic' (LetBind n t v)
expandLet :: Name -> Term -> Elab' aux ()
expandLet n v = processTactic' (ExpandLet n v)
rewrite :: Raw -> Elab' aux ()
rewrite tm = processTactic' (Rewrite tm)
induction :: Raw -> Elab' aux ()
induction tm = processTactic' (Induction tm)
casetac :: Raw -> Elab' aux ()
casetac tm = processTactic' (CaseTac tm)
equiv :: Raw -> Elab' aux ()
equiv tm = processTactic' (Equiv tm)
-- | Turn the current hole into a pattern variable with the provided
-- name, made unique if MN
patvar :: Name -> Elab' aux ()
patvar n@(SN _) = do apply (Var n) []; solve
patvar n = do env <- get_env
hs <- get_holes
if (n `elem` map fst env) then do apply (Var n) []; solve
else do n' <- case n of
UN _ -> return $! n
MN _ _ -> unique_hole n
NS _ _ -> return $! n
x -> return $! n
processTactic' (PatVar n')
-- | Turn the current hole into a pattern variable with the provided
-- name, but don't make MNs unique.
patvar' :: Name -> Elab' aux ()
patvar' n@(SN _) = do apply (Var n) [] ; solve
patvar' n = do env <- get_env
hs <- get_holes
if (n `elem` map fst env) then do apply (Var n) [] ; solve
else processTactic' (PatVar n)
patbind :: Name -> Elab' aux ()
patbind n = processTactic' (PatBind n)
focus :: Name -> Elab' aux ()
focus n = processTactic' (Focus n)
movelast :: Name -> Elab' aux ()
movelast n = processTactic' (MoveLast n)
dotterm :: Elab' aux ()
dotterm = do ES (p, a) s m <- get
tm <- get_term
case holes p of
[] -> return ()
(h : hs) ->
do let outer = findOuter h [] tm
let p' = p { dotted = (h, outer) : dotted p }
-- trace ("DOTTING " ++ show (h, outer) ++ "\n" ++
-- show tm) $
put $ ES (p', a) s m
where
findOuter h env (P _ n _) | h == n = env
findOuter h env (Bind n b sc)
= union (foB b)
(findOuter h env (instantiate (P Bound n (binderTy b)) sc))
where foB (Guess t v) = union (findOuter h env t) (findOuter h (n:env) v)
foB (Let t v) = union (findOuter h env t) (findOuter h env v)
foB b = findOuter h env (binderTy b)
findOuter h env (App _ f a)
= union (findOuter h env f) (findOuter h env a)
findOuter h env _ = []
get_dotterm :: Elab' aux [(Name, [Name])]
get_dotterm = do ES (p, a) s m <- get
return (dotted p)
-- | Set the zipper in the proof state to point at the current sub term
-- (This currently happens automatically, so this will have no effect...)
zipHere :: Elab' aux ()
zipHere = do ES (ps, a) s m <- get
let pt' = refocus (Just (head (holes ps))) (pterm ps)
put (ES (ps { pterm = pt' }, a) s m)
matchProblems :: Bool -> Elab' aux ()
matchProblems all = processTactic' (MatchProblems all)
unifyProblems :: Elab' aux ()
unifyProblems = processTactic' UnifyProblems
defer :: [Name] -> Name -> Elab' aux ()
defer ds n = do n' <- unique_hole n
processTactic' (Defer ds n')
deferType :: Name -> Raw -> [Name] -> Elab' aux ()
deferType n ty ns = processTactic' (DeferType n ty ns)
instanceArg :: Name -> Elab' aux ()
instanceArg n = processTactic' (Instance n)
autoArg :: Name -> Elab' aux ()
autoArg n = processTactic' (AutoArg n)
setinj :: Name -> Elab' aux ()
setinj n = processTactic' (SetInjective n)
proofstate :: Elab' aux ()
proofstate = processTactic' ProofState
reorder_claims :: Name -> Elab' aux ()
reorder_claims n = processTactic' (Reorder n)
qed :: Elab' aux Term
qed = do processTactic' QED
ES p _ _ <- get
return $! (getProofTerm (pterm (fst p)))
undo :: Elab' aux ()
undo = processTactic' Undo
-- | Prepare to apply a function by creating holes to be filled by the arguments
prepare_apply :: Raw -- ^ The operation being applied
-> [Bool] -- ^ Whether arguments are implicit
-> Elab' aux [(Name, Name)] -- ^ The names of the arguments and their holes to be filled with elaborated argument values
prepare_apply fn imps =
do ty <- get_type fn
ctxt <- get_context
env <- get_env
-- let claims = getArgs ty imps
-- claims <- mkClaims (normalise ctxt env ty) imps []
claims <- -- trace (show (fn, imps, ty, map fst env, normalise ctxt env (finalise ty))) $
mkClaims (finalise ty)
(normalise ctxt env (finalise ty))
imps [] (map fst env)
ES (p, a) s prev <- get
-- reverse the claims we made so that args go left to right
let n = length (filter not imps)
let (h : hs) = holes p
put (ES (p { holes = h : (reverse (take n hs) ++ drop n hs) }, a) s prev)
return $! claims
where
mkClaims :: Type -- ^ The type of the operation being applied
-> Type -- ^ Normalised version if we need it
-> [Bool] -- ^ Whether the arguments are implicit
-> [(Name, Name)] -- ^ Accumulator for produced claims
-> [Name] -- ^ Hypotheses
-> Elab' aux [(Name, Name)] -- ^ The names of the arguments and their holes, resp.
mkClaims (Bind n' (Pi _ t_in _) sc) (Bind _ _ scn) (i : is) claims hs =
do let t = rebind hs t_in
n <- getNameFrom (mkMN n')
-- when (null claims) (start_unify n)
let sc' = instantiate (P Bound n t) sc
env <- get_env
claim n (forgetEnv (map fst env) t)
when i (movelast n)
mkClaims sc' scn is ((n', n) : claims) hs
-- if we run out of arguments, we need the normalised version...
mkClaims t tn@(Bind _ _ sc) (i : is) cs hs = mkClaims tn tn (i : is) cs hs
mkClaims t _ [] claims _ = return $! (reverse claims)
mkClaims _ _ _ _ _
| Var n <- fn
= do ctxt <- get_context
case lookupTy n ctxt of
[] -> lift $ tfail $ NoSuchVariable n
_ -> lift $ tfail $ TooManyArguments n
| otherwise = fail $ "Too many arguments for " ++ show fn
doClaim ((i, _), n, t) = do claim n t
when i (movelast n)
mkMN n@(MN i _) = n
mkMN n@(UN x) = MN 99999 x
mkMN n@(SN s) = sMN 99999 (show s)
mkMN (NS n xs) = NS (mkMN n) xs
rebind hs (Bind n t sc)
| n `elem` hs = let n' = uniqueName n hs in
Bind n' (fmap (rebind hs) t) (rebind (n':hs) sc)
| otherwise = Bind n (fmap (rebind hs) t) (rebind (n:hs) sc)
rebind hs (App s f a) = App s (rebind hs f) (rebind hs a)
rebind hs t = t
-- | Apply an operator, solving some arguments by unification or matching.
apply, match_apply :: Raw -- ^ The operator to apply
-> [(Bool, Int)] -- ^ For each argument, whether to
-- attempt to solve it and the
-- priority in which to do so
-> Elab' aux [(Name, Name)]
apply = apply' fill
match_apply = apply' match_fill
apply' :: (Raw -> Elab' aux ()) -> Raw -> [(Bool, Int)] -> Elab' aux [(Name, Name)]
apply' fillt fn imps =
do args <- prepare_apply fn (map fst imps)
-- _Don't_ solve the arguments we're specifying by hand.
-- (remove from unified list before calling end_unify)
hs <- get_holes
ES (p, a) s prev <- get
let dont = if null imps
then head hs : dontunify p
else getNonUnify (head hs : dontunify p) imps args
let (n, hunis) = -- trace ("AVOID UNIFY: " ++ show (fn, dont)) $
unified p
let unify = -- trace ("Not done " ++ show hs) $
dropGiven dont hunis hs
let notunify = -- trace ("Not done " ++ show (hs, hunis)) $
keepGiven dont hunis hs
put (ES (p { dontunify = dont, unified = (n, unify),
notunified = notunify ++ notunified p }, a) s prev)
fillt (raw_apply fn (map (Var . snd) args))
ulog <- getUnifyLog
g <- goal
traceWhen ulog ("Goal " ++ show g ++ " -- when elaborating " ++ show fn) $
end_unify
return $! (map (\(argName, argHole) -> (argName, updateUnify unify argHole)) args)
where updateUnify us n = case lookup n us of
Just (P _ t _) -> t
_ -> n
getNonUnify acc [] _ = acc
getNonUnify acc _ [] = acc
getNonUnify acc ((i,_):is) ((a, t):as)
| i = getNonUnify acc is as
| otherwise = getNonUnify (t : acc) is as
-- getNonUnify imps args = map fst (filter (not . snd) (zip (map snd args) (map fst imps)))
apply2 :: Raw -> [Maybe (Elab' aux ())] -> Elab' aux ()
apply2 fn elabs =
do args <- prepare_apply fn (map isJust elabs)
fill (raw_apply fn (map (Var . snd) args))
elabArgs (map snd args) elabs
ES (p, a) s prev <- get
let (n, hs) = unified p
end_unify
solve
where elabArgs [] [] = return $! ()
elabArgs (n:ns) (Just e:es) = do focus n; e
elabArgs ns es
elabArgs (n:ns) (_:es) = elabArgs ns es
isJust (Just _) = False
isJust _ = True
apply_elab :: Name -> [Maybe (Int, Elab' aux ())] -> Elab' aux ()
apply_elab n args =
do ty <- get_type (Var n)
ctxt <- get_context
env <- get_env
claims <- doClaims (hnf ctxt env ty) args []
prep_fill n (map fst claims)
let eclaims = sortBy (\ (_, x) (_,y) -> priOrder x y) claims
elabClaims [] False claims
complete_fill
end_unify
where
priOrder Nothing Nothing = EQ
priOrder Nothing _ = LT
priOrder _ Nothing = GT
priOrder (Just (x, _)) (Just (y, _)) = compare x y
doClaims (Bind n' (Pi _ t _) sc) (i : is) claims =
do n <- unique_hole (mkMN n')
when (null claims) (start_unify n)
let sc' = instantiate (P Bound n t) sc
claim n (forget t)
case i of
Nothing -> return $! ()
Just _ -> -- don't solve by unification as there is an explicit value
do ES (p, a) s prev <- get
put (ES (p { dontunify = n : dontunify p }, a) s prev)
doClaims sc' is ((n, i) : claims)
doClaims t [] claims = return $! (reverse claims)
doClaims _ _ _ = fail $ "Wrong number of arguments for " ++ show n
elabClaims failed r []
| null failed = return $! ()
| otherwise = if r then elabClaims [] False failed
else return $! ()
elabClaims failed r ((n, Nothing) : xs) = elabClaims failed r xs
elabClaims failed r (e@(n, Just (_, elaboration)) : xs)
| r = try (do ES p _ _ <- get
focus n; elaboration; elabClaims failed r xs)
(elabClaims (e : failed) r xs)
| otherwise = do ES p _ _ <- get
focus n; elaboration; elabClaims failed r xs
mkMN n@(MN _ _) = n
mkMN n@(UN x) = MN 0 x
mkMN (NS n ns) = NS (mkMN n) ns
-- If the goal is not a Pi-type, invent some names and make it a pi type
checkPiGoal :: Name -> Elab' aux ()
checkPiGoal n
= do g <- goal
case g of
Bind _ (Pi _ _ _) _ -> return ()
_ -> do a <- getNameFrom (sMN 0 "pargTy")
b <- getNameFrom (sMN 0 "pretTy")
f <- getNameFrom (sMN 0 "pf")
claim a RType
claim b RType
claim f (RBind n (Pi Nothing (Var a) RType) (Var b))
movelast a
movelast b
fill (Var f)
solve
focus f
simple_app :: Bool -> Elab' aux () -> Elab' aux () -> String -> Elab' aux ()
simple_app infer fun arg str =
do a <- getNameFrom (sMN 0 "argTy")
b <- getNameFrom (sMN 0 "retTy")
f <- getNameFrom (sMN 0 "f")
s <- getNameFrom (sMN 0 "s")
claim a RType
claim b RType
claim f (RBind (sMN 0 "aX") (Pi Nothing (Var a) RType) (Var b))
tm <- get_term
start_unify s
-- if 'infer' is set, we're assuming it's a simply typed application
-- so safe to unify with the goal type (as there'll be no dependencies)
when infer $ unifyGoal (Var b)
hs <- get_holes
claim s (Var a)
prep_fill f [s]
focus f; fun
focus s; arg
tm <- get_term
ps <- get_probs
ty <- goal
hs <- get_holes
complete_fill
env <- get_env
-- We don't need a and b in the hole queue any more since they were
-- just for checking f, so move them to the end. If they never end up
-- getting solved, we'll get an 'Incomplete term' error.
hs <- get_holes
when (a `elem` hs) $ do movelast a
when (b `elem` hs) $ do movelast b
end_unify
where
regretWith err = try regret (lift $ tfail err)
-- Abstract over an argument of unknown type, giving a name for the hole
-- which we'll fill with the argument type too.
arg :: Name -> Maybe ImplicitInfo -> Name -> Elab' aux ()
arg n i tyhole = do ty <- unique_hole tyhole
claim ty RType
movelast ty
forall n i (Var ty)
-- try a tactic, if it adds any unification problem, return an error
no_errors :: Elab' aux () -> Maybe Err -> Elab' aux ()
no_errors tac err
= do ps <- get_probs
s <- get
case err of
Nothing -> tac
Just e -> -- update the error, if there is one.
case runStateT tac s of
Error _ -> lift $ Error e
OK (a, s') -> do put s'
return a
unifyProblems
ps' <- get_probs
if (length ps' > length ps) then
case reverse ps' of
((x, y, _, env, inerr, while, _) : _) ->
let (xp, yp) = getProvenance inerr
env' = map (\(x, b) -> (x, binderTy b)) env in
lift $ tfail $
case err of
Nothing -> CantUnify False (x, xp) (y, yp) inerr env' 0
Just e -> e
else return $! ()
-- Try a tactic, if it fails, try another
try :: Elab' aux a -> Elab' aux a -> Elab' aux a
try t1 t2 = try' t1 t2 False
handleError :: (Err -> Bool) -> Elab' aux a -> Elab' aux a -> Elab' aux a
handleError p t1 t2
= do s <- get
ps <- get_probs
case runStateT t1 s of
OK (v, s') -> do put s'
return $! v
Error e1 -> if p e1 then
do case runStateT t2 s of
OK (v, s') -> do put s'; return $! v
Error e2 -> if score e1 >= score e2
then lift (tfail e1)
else lift (tfail e2)
else lift (tfail e1)
try' :: Elab' aux a -> Elab' aux a -> Bool -> Elab' aux a
try' t1 t2 proofSearch
= do s <- get
ps <- get_probs
ulog <- getUnifyLog
ivs <- get_instances
case prunStateT 999999 False ps t1 s of
OK ((v, _, _), s') -> do put s'
return $! v
Error e1 -> traceWhen ulog ("try failed " ++ show e1) $
if recoverableErr e1 then
do case runStateT t2 s of
OK (v, s') -> do put s'; return $! v
Error e2 -> if score e1 >= score e2
then lift (tfail e1)
else lift (tfail e2)
else lift (tfail e1)
where recoverableErr err@(CantUnify r x y _ _ _)
= -- traceWhen r (show err) $
r || proofSearch
recoverableErr (CantSolveGoal _ _) = False
recoverableErr (CantResolveAlts _) = False
recoverableErr (ProofSearchFail (Msg _)) = True
recoverableErr (ProofSearchFail _) = False
recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e
recoverableErr (At _ e) = recoverableErr e
recoverableErr (ElabScriptDebug _ _ _) = False
recoverableErr _ = True
tryCatch :: Elab' aux a -> (Err -> Elab' aux a) -> Elab' aux a
tryCatch t1 t2
= do s <- get
ps <- get_probs
ulog <- getUnifyLog
case prunStateT 999999 False ps t1 s of
OK ((v, _, _), s') -> do put s'
return $! v
Error e1 -> traceWhen ulog ("tryCatch failed " ++ show e1) $
case runStateT (t2 e1) s of
OK (v, s') -> do put s'
return $! v
Error e2 -> if score e1 >= score e2
then lift (tfail e1)
else lift (tfail e2)
tryWhen :: Bool -> Elab' aux a -> Elab' aux a -> Elab' aux a
tryWhen True a b = try a b
tryWhen False a b = a
-- Bool says whether it's okay to create new unification problems. If set
-- to False, then the whole tactic fails if there are any new problems
tryAll :: [(Elab' aux a, Name)] -> Elab' aux a
tryAll [(x, _)] = x
tryAll xs = tryAll' [] 999999 (cantResolve, 0) xs
where
cantResolve :: Elab' aux a
cantResolve = lift $ tfail $ CantResolveAlts (map snd xs)
tryAll' :: [Elab' aux a] -> -- successes
Int -> -- most problems
(Elab' aux a, Int) -> -- smallest failure
[(Elab' aux a, Name)] -> -- still to try
Elab' aux a
tryAll' [res] pmax _ [] = res
tryAll' (_:_) pmax _ [] = cantResolve
tryAll' [] pmax (f, _) [] = f
tryAll' cs pmax f ((x, msg):xs)
= do s <- get
ps <- get_probs
case prunStateT pmax True ps x s of
OK ((v, newps, probs), s') ->
do let cs' = if (newps < pmax)
then [do put s'; return $! v]
else (do put s'; return $! v) : cs
tryAll' cs' newps f xs
Error err -> do put s
-- if (score err) < 100
tryAll' cs pmax (better err f) xs
-- else tryAll' [] pmax (better err f) xs -- give up
better err (f, i) = let s = score err in
if (s >= i) then (lift (tfail err), s)
else (f, i)
prunStateT
:: Int
-> Bool
-> [a]
-> Control.Monad.State.Strict.StateT
(ElabState t) TC t1
-> ElabState t
-> TC ((t1, Int, Idris.Core.Unify.Fails), ElabState t)
prunStateT pmax zok ps x s
= case runStateT x s of
OK (v, s'@(ES (p, _) _ _)) ->
let newps = length (problems p) - length ps
newpmax = if newps < 0 then 0 else newps in
if (newpmax > pmax || (not zok && newps > 0)) -- length ps == 0 && newpmax > 0))
then case reverse (problems p) of
((_,_,_,_,e,_,_):_) -> Error e
else OK ((v, newpmax, problems p), s')
Error e -> Error e
debugElaborator :: [ErrorReportPart] -> Elab' aux a
debugElaborator msg = do ps <- fmap proof get
saveState -- so we don't need to remember the hole order
hs <- get_holes
holeInfo <- mapM getHoleInfo hs
loadState
lift . Error $ ElabScriptDebug msg (getProofTerm (pterm ps)) holeInfo
where getHoleInfo :: Name -> Elab' aux (Name, Type, [(Name, Binder Type)])
getHoleInfo h = do focus h
g <- goal
env <- get_env
return (h, g, env)
qshow :: Fails -> String
qshow fs = show (map (\ (x, y, _, _, _, _, _) -> (x, y)) fs)
dumpprobs [] = ""
dumpprobs ((_,_,_,e):es) = show e ++ "\n" ++ dumpprobs es
| bkoropoff/Idris-dev | src/Idris/Core/Elaborate.hs | bsd-3-clause | 34,029 | 11 | 22 | 12,976 | 12,275 | 6,078 | 6,197 | 695 | 13 |
{-# LANGUAGE RecordWildCards, PolymorphicComponents, GADTs, TemplateHaskell #-}
module Synthesis.Interface where
import Control.Monad.ST
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Monad.State
import Control.Arrow
import Data.List as List
import Safe
import Data.Tuple.All
import Control.Lens
import Cudd.MTR
import Synthesis.BddRecord
import Synthesis.RefineUtil
--types that appear in the backend syntax tree
data BAVar sp lp where
StateVar :: sp -> Int -> BAVar sp lp
LabelVar :: lp -> Int -> BAVar sp lp
OutVar :: lp -> Int -> BAVar sp lp
deriving (Show, Eq, Ord)
--Operations that are given to the backend for compilation.
data VarOps pdb v s u = VarOps {
getVar :: v -> Maybe String -> StateT pdb (ST s) [DDNode s u],
withTmp :: forall a. (DDNode s u -> StateT pdb (ST s) a) -> StateT pdb (ST s) a,
allVars :: StateT pdb (ST s) [v]
}
--Generic utility functions
findWithDefaultM :: (Monad m, Ord k) => (v -> v') -> k -> Map k v -> m v' -> m v'
findWithDefaultM modF key theMap func = maybe func (return . modF) $ Map.lookup key theMap
findWithDefaultProcessM :: (Monad m, Ord k) => (v -> v') -> k -> Map k v -> m v' -> (v -> m ()) -> m v'
findWithDefaultProcessM modF key theMap funcAbsent funcPresent = maybe funcAbsent func $ Map.lookup key theMap
where
func v = do
funcPresent v
return $ modF v
modifyM :: Monad m => (s -> m s) -> StateT s m ()
modifyM f = get >>= (lift . f) >>= put
--Variable type
getNode = fst
getIdx = snd
--Symbol table
data SymbolInfo s u sp lp = SymbolInfo {
--below maps are used for update function compilation and constructing
_initVars :: Map sp ([DDNode s u], [Int], [DDNode s u], [Int]),
_stateVars :: Map sp ([DDNode s u], [Int], [DDNode s u], [Int]),
_labelVars :: Map lp ([DDNode s u], [Int], DDNode s u, Int),
_outcomeVars :: Map lp ([DDNode s u], [Int]),
--mappings from index to variable/predicate
_stateRev :: Map Int sp,
_labelRev :: Map Int (lp, Bool)
}
makeLenses ''SymbolInfo
initialSymbolTable = SymbolInfo Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty
--Sections
data SectionInfo s u = SectionInfo {
_trackedCube :: DDNode s u,
_trackedNodes :: [DDNode s u],
_trackedInds :: [Int],
_untrackedCube :: DDNode s u,
_untrackedInds :: [Int],
_labelCube :: DDNode s u,
_outcomeCube :: DDNode s u,
_nextCube :: DDNode s u,
_nextNodes :: [DDNode s u]
}
makeLenses ''SectionInfo
initialSectionInfo Ops{..} = SectionInfo btrue [] [] btrue [] btrue btrue btrue []
derefSectionInfo :: Ops s u -> SectionInfo s u -> ST s ()
derefSectionInfo Ops{..} SectionInfo{..} = do
deref _trackedCube
deref _untrackedCube
deref _labelCube
deref _outcomeCube
deref _nextCube
--Variable/predicate database
data DB s u sp lp = DB {
_symbolTable :: SymbolInfo s u sp lp,
_sections :: SectionInfo s u,
_avlOffset :: Int,
_freeInds :: [Int],
_groups :: Map String (Int, Int, Int)
}
makeLenses ''DB
initialDB ops@Ops{..} = do
let isi@SectionInfo{..} = initialSectionInfo ops
let res = DB initialSymbolTable isi 0 [] Map.empty
ref _trackedCube
ref _untrackedCube
ref _labelCube
ref _outcomeCube
ref _nextCube
return res
extractStatePreds :: DB s u sp lp -> [sp]
extractStatePreds db = map sel1 $ filter (filt . snd) $ Map.toList (_stateVars $ _symbolTable db)
where filt vars = not $ null $ sel2 vars `intersect` _trackedInds (_sections db)
extractUntrackedPreds :: DB s u sp lp -> [sp]
extractUntrackedPreds db = map sel1 $ filter (filt . snd) $ Map.toList (_stateVars $ _symbolTable db)
where filt vars = not $ null $ sel2 vars `intersect` _untrackedInds (_sections db)
--Below two functions are only used for temporary variables
allocIdx :: StateT (DB s u sp lp) (ST s) Int
allocIdx = do
st <- use freeInds
case st of
[] -> do
ind <- use avlOffset
avlOffset += 1
return ind
x:xs -> do
freeInds .= xs
return x
freeIdx :: Int -> StateT (DB s u sp lp) (ST s) ()
freeIdx idx = freeInds %= (idx :)
--Generic variable allocations
allocN :: Ops s u -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) ([DDNode s u], [Int])
allocN Ops{..} size group = do
offset <- use avlOffset
avlOffset += size
case group of
Nothing -> do
let indices = take size $ iterate (+1) offset
res <- lift $ mapM ithVar indices
lift $ makeTreeNode offset size 4
return (res, indices)
Just grName -> do
grps <- use groups
case Map.lookup grName grps of
Nothing -> do
let indices = take size $ iterate (+1) offset
res <- lift $ mapM ithVar indices
lift $ makeTreeNode offset size 4
lift $ makeTreeNode offset size 4
groups %= Map.insert grName (offset, size, last indices)
return (res, indices)
Just (startIdx, sizeGrp, lastIdx) -> do
lvl <- lift $ readPerm lastIdx
let levels = take size $ iterate (+1) (lvl + 1)
let indices = take size $ iterate (+1) offset
res <- lift $ mapM varAtLevel levels
lift $ makeTreeNode (head indices) size 4
lift $ makeTreeNode startIdx (sizeGrp + size) 4
tr <- lift readTree
lvl <- lift $ readPerm startIdx
oldGroup <- lift $ mtrFindGroup tr lvl sizeGrp
lift $ mtrDissolveGroup oldGroup
groups %= Map.insert grName (startIdx, sizeGrp + size, last indices)
return (res, indices)
deinterleave :: [a] -> ([a], [a])
deinterleave [] = ([], [])
deinterleave (x:y:rst) = (x:xs, y:ys)
where (xs, ys) = deinterleave rst
allocNPair :: Ops s u -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s ) (([DDNode s u], [Int]), ([DDNode s u], [Int]))
allocNPair ops size group = do
(vars, idxs) <- allocN ops (size*2) group
let (vc, vn) = deinterleave vars
(ic, inn) = deinterleave idxs
return ((vc, ic), (vn, inn))
--Do the variable allocation and symbol table tracking
addToCubeDeref :: Ops s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)
addToCubeDeref Ops{..} add cb = do
res <- add .& cb
deref add
deref cb
return res
subFromCubeDeref :: Ops s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)
subFromCubeDeref Ops{..} sub cb = do
res <- bexists sub cb
deref sub
deref cb
return res
--initial state helpers
allocInitVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u]
allocInitVar ops@Ops{..} v size group = do
((cn, ci), (nn, ni)) <- allocNPair ops size group
symbolTable . initVars %= Map.insert v (cn, ci, nn, ni)
symbolTable . stateRev %= flip (foldl func) ci
return cn
where func theMap idx = Map.insert idx v theMap
-- === goal helpers ===
data NewVars s u sp = NewVars {
_allocatedStateVars :: [(sp, [DDNode s u])]
}
makeLenses ''NewVars
data GoalState s u sp lp = GoalState {
_nv :: NewVars s u sp,
_db :: DB s u sp lp
}
makeLenses ''GoalState
liftToGoalState :: StateT (DB s u sp lp) (ST s) a -> StateT (GoalState s u sp lp) (ST s) a
liftToGoalState (StateT func) = StateT $ \st -> do
(res, st') <- func (_db st)
return (res, GoalState (_nv st) st')
allocStateVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (GoalState s u sp lp) (ST s) [DDNode s u]
allocStateVar ops@Ops{..} name size group = do
((cn, ci), (nn, ni)) <- liftToGoalState $ allocNPair ops size group
addVarToState ops name cn ci nn ni
return cn
type Update a = a -> a
addStateVarSymbol :: (Ord sp) => sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> Update (SymbolInfo s u sp lp)
addStateVarSymbol name vars idxs vars' idxs' =
stateVars %~ Map.insert name (vars, idxs, vars', idxs') >>>
--TODO dont need to do this every time
stateRev %~ flip (foldl func) idxs
where func theMap idx = Map.insert idx name theMap
addVarToStateSection :: Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (GoalState s u sp lp )(ST s) ()
addVarToStateSection ops@Ops{..} name varsCurrent idxsCurrent varsNext idxsNext = do
db . sections . trackedNodes %= (varsCurrent ++)
db . sections . trackedInds %= (idxsCurrent ++)
modifyM $ db . sections . trackedCube %%~ \c -> do
cb <- nodesToCube varsCurrent
addToCubeDeref ops c cb
db . sections . nextNodes %= (varsNext ++)
modifyM $ db . sections . nextCube %%~ \c -> do
cb <- nodesToCube varsNext
addToCubeDeref ops c cb
nv . allocatedStateVars %= ((name, varsNext) :)
addVarToState :: (Ord sp) => Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (GoalState s u sp lp) (ST s) ()
addVarToState ops@Ops{..} name vars idxs vars' idxs' = do
db . symbolTable %= addStateVarSymbol name vars idxs vars' idxs'
addVarToStateSection ops name vars idxs vars' idxs'
-- === update helpers ===
allocUntrackedVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u]
allocUntrackedVar ops@Ops{..} var size group = do
((cn, ci), (nn, ni)) <- allocNPair ops size group
addVarToUntracked ops var cn ci nn ni
return cn
addVarToUntracked :: (Ord sp) => Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (DB s u sp lp) (ST s) ()
addVarToUntracked ops@Ops {..} name vars idxs vars' idxs' = do
symbolTable %= addStateVarSymbol name vars idxs vars' idxs'
sections . untrackedInds %= (idxs ++)
modifyM $ sections . untrackedCube %%~ \c -> do
cb <- nodesToCube vars
addToCubeDeref ops c cb
allocLabelVar :: (Ord lp) => Ops s u -> lp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u]
allocLabelVar ops@Ops{..} var size group = do
(vars', idxs') <- allocN ops (size + 1) group
let (en, enIdx) = (head vars', head idxs')
(vars, idxs) = (tail vars', tail idxs')
symbolTable . labelVars %= Map.insert var (vars, idxs, en, enIdx)
symbolTable . labelRev %= (
flip (foldl (func vars idxs)) idxs >>>
Map.insert enIdx (var, True)
)
modifyM $ sections . labelCube %%~ \c -> do
cb <- nodesToCube vars
r1 <- addToCubeDeref ops cb c
addToCubeDeref ops en r1
return vars
where func vars idxs theMap idx = Map.insert idx (var, False) theMap
allocOutcomeVar :: (Ord lp) => Ops s u -> lp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u]
allocOutcomeVar ops@Ops{..} name size group = do
(vars, idxs) <- allocN ops size group
symbolTable . outcomeVars %= Map.insert name (vars, idxs)
modifyM $ sections . outcomeCube %%~ \c -> do
cb <- nodesToCube vars
addToCubeDeref ops cb c
return vars
-- === Variable promotion helpers ===
promoteUntrackedVar :: (Ord sp) => Ops s u -> sp -> StateT (GoalState s u sp lp) (ST s) ()
promoteUntrackedVar ops@Ops{..} var = do
mp <- use $ db . symbolTable . stateVars
let (vars, idxs, vars', idxs') = fromJustNote "promoteUntrackedVar" $ Map.lookup var mp
addVarToStateSection ops var vars idxs vars' idxs'
db . sections . untrackedInds %= (\\ idxs)
modifyM $ db . sections . untrackedCube %%~ \c -> do
cb <- nodesToCube vars
subFromCubeDeref ops cb c
promoteUntrackedVars :: (Ord sp) => Ops s u -> [sp] -> StateT (DB s u sp lp) (ST s) (NewVars s u sp)
promoteUntrackedVars ops vars = StateT $ \st -> do
(_, GoalState{..}) <- runStateT (mapM_ (promoteUntrackedVar ops) vars) (GoalState (NewVars []) st)
return (_nv, _db)
withTmp' :: Ops s u -> (DDNode s u -> StateT (DB s u sp lp) (ST s) a) -> StateT (DB s u sp lp) (ST s) a
withTmp' Ops{..} func = do
ind <- allocIdx
var <- lift $ ithVar ind
res <- func var
freeIdx ind
lift $ deref var
return res
withTmpGoal' :: Ops s u -> (DDNode s u -> StateT (GoalState s u sp lp) (ST s) a) -> StateT (GoalState s u sp lp) (ST s) a
withTmpGoal' Ops{..} func = do
ind <- liftToGoalState allocIdx
var <- lift $ ithVar ind
res <- func var
liftToGoalState $ freeIdx ind
lift $ deref var
return res
allVars' :: StateT (DB s u sp lp) (ST s) [BAVar sp lp]
allVars' = do
SymbolInfo {..} <- use symbolTable
return $ map (uncurry StateVar . second (length . sel1)) (Map.toList _stateVars) ++ map (uncurry LabelVar . second (length . sel1)) (Map.toList _labelVars) ++ map (uncurry OutVar . second (length . sel1)) (Map.toList _outcomeVars)
--Construct the VarOps for compiling particular parts of the spec
goalOps :: Ord sp => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u
goalOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..}
where
getVar (StateVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var)
getVar _ _ = error "Requested non-state variable when compiling goal section"
doGoal :: (Ord sp, Monad (rm (ST s)))
=> Ops s u
-> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT st (StateT (GoalState s u sp lp) (rm (ST s))) a)
-> StateT st (StateT (DB s u sp lp) (rm (ST s))) (a, NewVars s u sp)
doGoal ops complFunc = StateT $ \st1 -> StateT $ \st -> do
((res, st1'), GoalState{..}) <- runStateT (runStateT (complFunc $ goalOps ops) st1) (GoalState (NewVars []) st)
return (((res, _nv), st1'), _db)
stateLabelOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u
stateLabelOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..}
where
getVar (StateVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var)
getVar (LabelVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
liftToGoalState $ findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group
getVar _ _ = error "Requested non-state variable when compiling goal section"
doStateLabel :: (Ord sp, Ord lp, Monad (rm (ST s)))
=> Ops s u
-> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT st (StateT (GoalState s u sp lp) (rm (ST s))) a)
-> StateT st (StateT (DB s u sp lp) (rm (ST s))) (a, NewVars s u sp)
doStateLabel ops complFunc = StateT $ \st1 -> StateT $ \st -> do
((res, st1'), GoalState{..}) <- runStateT (runStateT (complFunc $ stateLabelOps ops) st1) (GoalState (NewVars []) st)
return (((res, _nv), st1'), _db)
stateLabelOutcomeOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u
stateLabelOutcomeOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..}
where
getVar (StateVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var)
getVar (LabelVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
liftToGoalState $ findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group
getVar (OutVar var size) group = do
SymbolInfo{..} <- use $ db . symbolTable
liftToGoalState $ findWithDefaultM sel1 var _outcomeVars $ allocOutcomeVar ops var size group
getVar _ _ = error "Requested non-state variable when compiling goal section"
doStateLabelOutcome :: (Ord sp, Ord lp) => Ops s u -> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT (GoalState s u sp lp) (ST s) a) -> StateT (DB s u sp lp) (ST s) (a, NewVars s u sp)
doStateLabelOutcome ops complFunc = StateT $ \st -> do
(res, GoalState{..}) <- runStateT (complFunc $ stateLabelOps ops) (GoalState (NewVars []) st)
return ((res, _nv), _db)
initOps :: Ord sp => Ops s u -> VarOps (DB s u sp lp) (BAVar sp lp) s u
initOps ops = VarOps {withTmp = withTmp' ops, allVars = allVars', ..}
where
getVar (StateVar var size) group = do
SymbolInfo{..} <- use symbolTable
findWithDefaultM sel1 var _initVars (allocInitVar ops var size group)
getVar _ _ = error "Requested non-state variable when compiling init section"
doInit :: Ord sp => Ops s u -> (VarOps (DB s u sp lp) (BAVar sp lp) s u -> a) -> a
doInit ops complFunc = complFunc (initOps ops)
updateOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (DB s u sp lp) (BAVar sp lp) s u
updateOps ops = VarOps {withTmp = withTmp' ops, allVars = allVars', ..}
where
getVar (StateVar var size) group = do
SymbolInfo{..} <- use symbolTable
findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocUntrackedVar ops var size group) (uncurryN $ addVarToUntracked ops var)
getVar (LabelVar var size) group = do
SymbolInfo{..} <- use symbolTable
findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group
getVar (OutVar var size) group = do
SymbolInfo{..} <- use symbolTable
findWithDefaultM sel1 var _outcomeVars $ allocOutcomeVar ops var size group
doUpdate :: (Ord sp, Ord lp) => Ops s u -> (VarOps (DB s u sp lp) (BAVar sp lp) s u -> a) -> a
doUpdate ops complFunc = complFunc (updateOps ops)
getStaticVar :: Ord sp => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u]
getStaticVar ops var size group = StateT $ \st -> do
(res, st') <- flip runStateT (GoalState (NewVars []) st) $ do
SymbolInfo{..} <- use $ db . symbolTable
findWithDefaultM sel3 var _stateVars $ findWithDefaultProcessM sel3 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var)
return (res, _db st')
| termite2/synthesis | Synthesis/Interface.hs | bsd-3-clause | 18,474 | 0 | 23 | 4,784 | 7,915 | 3,955 | 3,960 | -1 | -1 |
module BoardSpec (spec) where
import Control.Exception (evaluate)
import Data.Function (on)
import Data.List (nubBy, (\\))
import Test.Hspec
import Test.QuickCheck
import Board
import Clues (clueAt)
import Position (axis, positionsByColumn)
import Tile (clueFor, isVoltorb, isOptional, isRequired)
import ArrayGenerators (completeBoundedArray, incompleteBoundedArray, distinctAssocsTuple)
import TileSpec ()
import PositionSpec ()
instance Arbitrary Board where
arbitrary = board <$> completeBoundedArray
fst3 :: (a, b, c) -> a
fst3 (a, _, _) = a
spec :: Spec
spec = do
describe "board" $ do
context "given an Array with complete bounds" $ do
it "is inverted by unBoard" $ property $
forAll (completeBoundedArray) $ \a ->
unBoard (board a) `shouldBe` a
context "given an Array with incomplete bounds" $ do
it "returns an error" $ property $
forAll (incompleteBoundedArray) $ \arr ->
evaluate (board arr) `shouldThrow` errorCall "Array does not have complete bounds"
describe "tileAt" $ do
context "getting the Tile at a Position of a Board that was just updated" $ do
it "returns the Tile that was updated" $ property $
\b p t -> tileAt (updateTileAt b p t) p `shouldBe` t
describe "updateTileAt" $ do
it "returns a valid Board" $ property $
\b p t -> updateTileAt b p t `shouldSatisfy` isValidBoard
context "updating the Tile at a Position of a Board with the Tile at that Position" $ do
it "returns the original Board" $ property $
\b p -> updateTileAt b p (tileAt b p) `shouldBe` b
context "updating a Tile at a Position of a Board twice" $ do
it "returns the same Board that results from only updating the Board the second time" $ property $
\b p t t' -> updateTileAt (updateTileAt b p t) p t' `shouldBe` updateTileAt b p t'
describe "tilesAt" $ do
context "getting the Tiles at some Positions of a Board that were just updated" $ do
it "returns the Tiles that were updated" $ property $
forAll (arbitrary) $ \b ->
forAll (distinctAssocsTuple) $ \(ps, ts) ->
tilesAt (updateTilesAt b $ ps `zip` ts) ps `shouldBe` ts
describe "updateTilesAt" $ do
it "returns a valid Board" $ property $
\b as -> updateTilesAt b as `shouldSatisfy` isValidBoard
context "updating the Tiles at some Positions of a Board with the Tiles at those Positions" $ do
it "returns the original Board" $ property $
\b ps -> updateTilesAt b (ps `zip` tilesAt b ps) `shouldBe` b
context "updating some Tiles at some Positions of a Board twice" $ do
it "returns the same result Board that results from only updating the Board a second time" $ property $
forAll (arbitrary) $ \b ->
forAll (fmap (unzip3 . nubBy ((==) `on` fst3)) arbitrary) $ \(ps, ts, ts') ->
updateTilesAt (updateTilesAt b $ ps `zip` ts) (ps `zip` ts') `shouldBe` updateTilesAt b (ps `zip` ts')
describe "findVoltorbTiles" $ do
it "returns a list of Positions such that every Position in the list contains an Voltorb Tile" $ property $
\b -> findVoltorbTiles b `shouldSatisfy` all (isVoltorb . tileAt b)
it "returns a list of Positions such that every Position not in the list contains a non-Voltorb Tile" $ property $
\b -> positionsByColumn \\ findVoltorbTiles b `shouldSatisfy` all (not . isVoltorb . tileAt b)
describe "findOptionalTiles" $ do
it "returns a list of Positions such that every Position in the list contains an optional Tile" $ property $
\b -> findOptionalTiles b `shouldSatisfy` all (isOptional . tileAt b)
it "returns a list of Positions such that every Position not in the list contains a non-optional Tile" $ property $
\b -> positionsByColumn \\ findOptionalTiles b `shouldSatisfy` all (not . isOptional . tileAt b)
describe "findRequiredTiles" $ do
it "returns a list of Positions such that every Position in the list contains a non-trivial Tile" $ property $
\b -> findRequiredTiles b `shouldSatisfy` all (isRequired . tileAt b)
it "returns a list of Positions such that every Position not in the list contains a trivial Tile" $ property $
\b -> positionsByColumn \\ findRequiredTiles b `shouldSatisfy` all (not . isRequired . tileAt b)
describe "cluesFor" $ do
it "returns Clues containing the Clue for each Axis" $ property $
\b a -> cluesFor b `clueAt` a `shouldBe` (clueFor $ tilesAt b $ axis a)
| jameshales/voltorb-flip | test/BoardSpec.hs | bsd-3-clause | 4,488 | 0 | 23 | 1,022 | 1,226 | 625 | 601 | 76 | 1 |
module Control.Monad.Extensions (satisfiesM,if') where
import Control.Applicative (Applicative,liftA3)
satisfiesM :: Monad m => (a -> Bool) -> m a -> m a
satisfiesM p x = x >>= if' p return (const (satisfiesM p x))
if' :: Applicative f => f Bool -> f a -> f a -> f a
if' = liftA3 (\ c t e -> if c then t else e)
| bitemyapp/checkers | src/Control/Monad/Extensions.hs | bsd-3-clause | 315 | 0 | 10 | 67 | 160 | 83 | 77 | 6 | 2 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.MBox
-- Copyright : (c) Jose A Ortega Ruiz
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A Ortega Ruiz <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A plugin for checking mail in mbox files.
--
-----------------------------------------------------------------------------
module Plugins.MBox (MBox(..)) where
import Prelude
import Plugins
#ifdef INOTIFY
import Plugins.Utils (changeLoop, expandHome)
import Control.Monad (when)
import Control.Concurrent.STM
import Control.Exception (SomeException (..), handle, evaluate)
import System.Console.GetOpt
import System.Directory (doesFileExist)
import System.FilePath ((</>))
import System.INotify (Event(..), EventVariety(..), initINotify, addWatch)
import qualified Data.ByteString.Lazy.Char8 as B
data Options = Options
{ oAll :: Bool
, oUniq :: Bool
, oDir :: FilePath
, oPrefix :: String
, oSuffix :: String
}
defaults :: Options
defaults = Options {
oAll = False, oUniq = False, oDir = "", oPrefix = "", oSuffix = ""
}
options :: [OptDescr (Options -> Options)]
options =
[ Option "a" ["all"] (NoArg (\o -> o { oAll = True })) ""
, Option "u" [] (NoArg (\o -> o { oUniq = True })) ""
, Option "d" ["dir"] (ReqArg (\x o -> o { oDir = x }) "") ""
, Option "p" ["prefix"] (ReqArg (\x o -> o { oPrefix = x }) "") ""
, Option "s" ["suffix"] (ReqArg (\x o -> o { oSuffix = x }) "") ""
]
parseOptions :: [String] -> IO Options
parseOptions args =
case getOpt Permute options args of
(o, _, []) -> return $ foldr id defaults o
(_, _, errs) -> ioError . userError $ concat errs
#else
import System.IO
#endif
-- | A list of display names, paths to mbox files and display colours,
-- followed by a list of options.
data MBox = MBox [(String, FilePath, String)] [String] String
deriving (Read, Show)
instance Exec MBox where
alias (MBox _ _ a) = a
#ifndef INOTIFY
start _ _ = do
hPutStrLn stderr $ "Warning: xmobar is not compiled with -fwith_inotify" ++
" but the MBox plugin requires it"
#else
start (MBox boxes args _) cb = do
opts <- parseOptions args
let showAll = oAll opts
prefix = oPrefix opts
suffix = oSuffix opts
uniq = oUniq opts
names = map (\(t, _, _) -> t) boxes
colors = map (\(_, _, c) -> c) boxes
extractPath (_, f, _) = expandHome $ oDir opts </> f
events = [CloseWrite]
i <- initINotify
vs <- mapM (\b -> do
f <- extractPath b
exists <- doesFileExist f
n <- if exists then countMails f else return (-1)
v <- newTVarIO (f, n)
when exists $
addWatch i events f (handleNotification v) >> return ()
return v)
boxes
changeLoop (mapM (fmap snd . readTVar) vs) $ \ns ->
let s = unwords [ showC uniq m n c | (m, n, c) <- zip3 names ns colors
, showAll || n > 0 ]
in cb (if null s then "" else prefix ++ s ++ suffix)
showC :: Bool -> String -> Int -> String -> String
showC u m n c =
if c == "" then msg else "<fc=" ++ c ++ ">" ++ msg ++ "</fc>"
where msg = m ++ if not u || n > 1 then show n else ""
countMails :: FilePath -> IO Int
countMails f =
handle (\(SomeException _) -> evaluate 0)
(do txt <- B.readFile f
evaluate $! length . filter (B.isPrefixOf from) . B.lines $ txt)
where from = B.pack "From "
handleNotification :: TVar (FilePath, Int) -> Event -> IO ()
handleNotification v _ = do
(p, _) <- atomically $ readTVar v
n <- countMails p
atomically $ writeTVar v (p, n)
#endif
| apoikos/pkg-xmobar | src/Plugins/MBox.hs | bsd-3-clause | 3,906 | 0 | 12 | 1,119 | 634 | 379 | 255 | 12 | 0 |
module QuoteUtils
( compileQuote
, compileSimpleQuoteBTCBuy
, compileSimpleQuoteBTCSell
, QuoteCompilation(..)
, QCError(..)
) where
import Control.Error
import Control.Monad.IO.Class
import Network.MtGoxAPI
import Network.MtGoxAPI.DepthStore
import qualified Data.Text as T
import CommonTypes
import Config
import DbUtils
data QuoteCompilation a = SuccessfulQuote a
| QuoteCompilationError QCError
data QCError = HadNotEnoughDepth
| DepthStoreWasUnavailable
deriving (Show)
compileSimpleQuoteBTCBuy :: BridgewalkerHandles -> Integer -> IO (QuoteCompilation Integer)
compileSimpleQuoteBTCBuy bwHandles btcAmount = runAsQuoteCompilation $ do
usdAmount <- simulateBTCBuy' bwHandles btcAmount
return $ addFee usdAmount (getActualFee bwHandles)
compileSimpleQuoteBTCSell :: BridgewalkerHandles -> Integer -> IO (QuoteCompilation Integer)
compileSimpleQuoteBTCSell bwHandles btcAmount = runAsQuoteCompilation $ do
usdAmount <- simulateBTCSell' bwHandles btcAmount
return $ addFee usdAmount (-1 * getActualFee bwHandles)
compileQuote :: BridgewalkerHandles-> BridgewalkerAccount -> Maybe T.Text -> AmountType -> IO (QuoteCompilation QuoteData)
compileQuote bwHandles account mAddress amountType = runAsQuoteCompilation $ do
let typicalTxFee = bcTypicalTxFee . bhConfig $ bwHandles
actualFee = getActualFee bwHandles
dbConn = bhDBConnCH bwHandles
-- some preparation
otherAccountM <- case mAddress of
Nothing -> return Nothing
Just address ->
liftIO $ getAccountByAddress dbConn address
let isInternalTransfer = isJust otherAccountM
txFeeUSD <- do
usdAmount <- simulateBTCBuy' bwHandles typicalTxFee
return $ addFee usdAmount actualFee
-- main calculation
pqdInternal <- case amountType of
AmountBasedOnBTC btc -> do
usdForRecipient <- simulateBTCSell' bwHandles btc
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdForRecipient
, pqdUSDAccount = usdForRecipient
}
AmountBasedOnUSDBeforeFees usdForRecipient -> do
btc <- simulateUSDBuy' bwHandles usdForRecipient
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdForRecipient
, pqdUSDAccount = usdForRecipient
}
AmountBasedOnUSDAfterFees usdFromOurAccount -> do
btc <- simulateUSDBuy' bwHandles usdFromOurAccount
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdFromOurAccount
, pqdUSDAccount = usdFromOurAccount
}
pqdExternal <- case amountType of
AmountBasedOnBTC btc -> do
usdNeeded <- simulateBTCBuy' bwHandles btc
let usdNeededWithFee = addFee usdNeeded actualFee
usdForRecipient <- simulateBTCSell' bwHandles btc
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdForRecipient
, pqdUSDAccount = usdNeededWithFee
+ txFeeUSD
}
AmountBasedOnUSDBeforeFees usdForRecipient -> do
btc <- simulateUSDBuy' bwHandles usdForRecipient
usdNeeded <- simulateBTCBuy' bwHandles btc
let usdNeededWithFee = addFee usdNeeded actualFee
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdForRecipient
, pqdUSDAccount = usdNeededWithFee
+ txFeeUSD
}
AmountBasedOnUSDAfterFees usdFromOurAccount -> do
let usdBeforeFee =
subtractFee (usdFromOurAccount - txFeeUSD) actualFee
if usdBeforeFee > 0
then do
btc <- simulateUSDSell' bwHandles usdBeforeFee
usdForRecipient <- simulateBTCSell' bwHandles btc
return PureQuoteData { pqdBTC = btc
, pqdUSDRecipient = usdForRecipient
, pqdUSDAccount = usdFromOurAccount
}
else
return PureQuoteData { pqdBTC = 0
, pqdUSDRecipient = 0
, pqdUSDAccount = usdFromOurAccount
}
let pqd = if isInternalTransfer
then pqdInternal
else pqdExternal
-- fill in some additional infos
usdBalance <- liftIO $ getUSDBalance dbConn (bAccount account)
return QuoteData { qdBTC = pqdBTC pqd
, qdUSDRecipient = pqdUSDRecipient pqd
, qdUSDAccount = pqdUSDAccount pqd
, qdSufficientBalance = pqdUSDAccount pqd <= usdBalance
}
runAsQuoteCompilation :: Monad m => EitherT QCError m a -> m (QuoteCompilation a)
runAsQuoteCompilation f = do
result <- runEitherT f
return $ case result of
Right quote -> SuccessfulQuote quote
Left errMsg -> QuoteCompilationError errMsg
getActualFee :: BridgewalkerHandles -> Double
getActualFee bwHandles =
let mtgoxFee = bhMtGoxFee bwHandles
targetFee = bcTargetExchangeFee . bhConfig $ bwHandles
in max mtgoxFee targetFee
addFee :: Integer -> Double -> Integer
addFee amount fee =
let markup = round $ fromIntegral amount * (fee / 100)
in amount + markup
subtractFee :: Integer -> Double -> Integer
subtractFee amount fee =
round $ fromIntegral amount * (100.0 / (100.0 + fee))
simulateBTCBuy' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer
simulateBTCBuy' = depthStoreAction simulateBTCBuy
simulateBTCSell' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer
simulateBTCSell' = depthStoreAction simulateBTCSell
simulateUSDBuy' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer
simulateUSDBuy' = depthStoreAction simulateUSDBuy
simulateUSDSell' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer
simulateUSDSell' = depthStoreAction simulateUSDSell
depthStoreAction :: MonadIO m =>(DepthStoreHandle -> t -> IO DepthStoreAnswer)-> BridgewalkerHandles -> t -> EitherT QCError m Integer
depthStoreAction action bwHandles amount = do
let depthStoreHandle = mtgoxDepthStoreHandle . bhMtGoxHandles $ bwHandles
answerM <- liftIO $ action depthStoreHandle amount
case answerM of
DepthStoreAnswer answer -> return answer
NotEnoughDepth -> left HadNotEnoughDepth
DepthStoreUnavailable -> left DepthStoreWasUnavailable
_debugQuoting :: Show a => IO (QuoteCompilation a) -> IO ()
_debugQuoting f = do
result <- f
case result of
SuccessfulQuote quote -> print quote
QuoteCompilationError errMsg -> print errMsg
| javgh/bridgewalker | src/QuoteUtils.hs | bsd-3-clause | 7,325 | 0 | 19 | 2,418 | 1,512 | 748 | 764 | 134 | 8 |
module Bamboo.Plugin.Photo.Util where
import Bamboo.Plugin.Photo.Config
import MPSUTF8
import Prelude hiding ((.), (>), (^), (/), id)
import System.Directory
mkdir :: String -> IO ()
mkdir = u2b > createDirectory
show_data :: (Show a) => a -> String
show_data = show > snake_case
parse_boolean :: String -> Bool
parse_boolean = belongs_to ["true", "1", "y", "yes", "yeah"]
ls_l :: String -> IO [String]
ls_l x = ls x ^ map (x /)
image_path :: String -> String
image_path id = image_uri / id
spaced_url :: String -> String
spaced_url = gsub "/" " / "
id_to_resource :: String -> String
id_to_resource x = x.split "/" .tail.join "/" | nfjinjing/bamboo-plugin-photo | src/Bamboo/Plugin/Photo/Util.hs | bsd-3-clause | 638 | 1 | 7 | 111 | 241 | 139 | 102 | 19 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Game.GameLocalsT where
import Control.Lens (makeLenses)
import qualified Data.Vector as V
import qualified Constants
import Game.GClientT
import Types
makeLenses ''GameLocalsT
newGameLocalsT :: GameLocalsT
newGameLocalsT = GameLocalsT
{ _glHelpMessage1 = ""
, _glHelpMessage2 = ""
, _glHelpChanged = 0
, _glClients = V.generate Constants.maxClients newGClientT
, _glSpawnPoint = ""
, _glMaxClients = 0
, _glMaxEntities = 0
, _glServerFlags = 0
, _glNumItems = 0
, _glAutosaved = False
} | ksaveljev/hake-2 | src/Game/GameLocalsT.hs | bsd-3-clause | 624 | 0 | 8 | 170 | 126 | 79 | 47 | 20 | 1 |
{-# LANGUAGE OverlappingInstances, FunctionalDependencies, ScopedTypeVariables,
MultiParamTypeClasses, FlexibleInstances, UndecidableInstances,
FlexibleContexts, DeriveFunctor #-}
{-# OPTIONS_HADDOCK hide #-}
module Happstack.StaticRouting.Internal where
import Happstack.Server(askRq, rqPaths, rqMethod, localRq, ServerMonad,
HasRqData, methodM, look, FromReqURI)
import qualified Happstack.Server as H
import Control.Monad(msum, MonadPlus, mzero, mplus)
import Control.Monad.IO.Class(MonadIO)
import Control.Arrow(first, second)
import qualified Data.ListTrie.Map as Trie
import Data.Map(Map)
import qualified Data.Map as Map
import Data.List(intercalate)
import Data.Maybe
-- | Static routing tables consisting of handlers of type 'a'.
data Route a =
Dir Segment (Route a)
| Handler EndSegment a
| Param String (Route a)
| Choice [Route a]
deriving Functor
-- For backwards compatibility with GHC 6.12
handler :: EndSegment -> a -> Route a
handler = Handler
newtype Segment =
StringS String
deriving (Show, Eq, Ord)
type EndSegment = (Maybe Int, H.Method)
-- | Support for varying number of arguments to 'path' handlers.
class Path m hm a b | a b -> m hm where
pathHandler :: (m b -> hm c) -> a -> hm c
arity :: m b -> a -> Int
instance (FromReqURI d, ServerMonad hm, MonadPlus hm, Path m hm a b)
=> Path m hm (d -> a) b where
pathHandler w f = H.path (pathHandler w . f)
arity m f = 1 + arity m (f undefined)
instance Path m hm (m b) b where
pathHandler w m = w m
arity _ _ = 0
-- | Pop a path element if it matches the given string.
dir :: String -> Route a -> Route a
dir = Dir . StringS
-- | Combine several route alternatives into one.
choice :: [Route a] -> Route a
choice = Choice
-- | Expect the given method, and exactly 'n' more segments, where 'n' is the arity of the handler.
path :: forall m hm h a b. Path m hm h a => H.Method -> (m a -> hm b) -> h -> Route (hm b)
path m w h = Handler (Just (arity (undefined::m a) h),m) (pathHandler w h)
-- | Expect zero or more segments.
remainingPath :: H.Method -> h -> Route h
remainingPath m = Handler (Nothing,m)
-- | DEPRECATED. Expect a specific parameter to be present.
param :: String -> Route a -> Route a
param = Param
-- | Extract handler monad from a route.
extract :: (ServerMonad m, MonadPlus m, HasRqData m, MonadIO m) => Route (m a) -> m a
extract = f Nothing where
f p (Dir (StringS s) r) = H.dir s (f p r)
f (Just p) (Param p' _) = error $ "extract: cannot handle more than one param: "++ show(p,p')
f _ (Param p r) = f (Just p) r
f p (Handler (_,m) a) = doParam p >> methodM m >> a
f p (Choice rs) = msum (map (f p) rs)
doParam :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) =>
Maybe String -> m ()
doParam Nothing = return ()
doParam (Just p) = H.getDataFn (look p) >>= either (const mzero) (const (return ()))
type Param = Maybe String
newtype RouteTree a =
R { unR :: Trie.TrieMap Map Segment (Map EndSegment (Map Param [a])) } deriving (Show)
type Segments = ([Segment],EndSegment)
routeTree :: (ServerMonad m, MonadPlus m) => Route (m a) -> RouteTree (m a)
routeTree r = R $ foldr (\(((ps,es),mp),m) ->
Trie.insertWith (Map.unionWith (Map.unionWith (++)))
ps
(Map.singleton es (Map.singleton mp [m])))
Trie.empty (flatten r)
flatten :: (ServerMonad m, MonadPlus m) => Route (m a) -> [((Segments, Param), m a)]
flatten = f Nothing where
f p (Dir s r) = map (first (first (first (s:)))) (f p r)
f (Just p) (Param p' _) = error $ "flatten: cannot handle more than one param: "++show (p,p')
f _ (Param p' r) = f (Just p') r
f p (Handler e a) = [((([], e),p), a)]
f p (Choice rs) = concatMap (f p) rs
-- | Compile routes, also return possible overlap report. If the
-- overlap report is 'Nothing', the routing table is order
-- independent. If the overlap report is @Just s@, then @s@ is a
-- textual representation of all the paths that are order dependent,
-- suitable for a warning message.
compile :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) =>
Route (m a) -> (m a, Maybe String)
compile r = ( dispatch t
, if null os then Nothing
else Just $ "Overlapping handlers: \n"++ showOverlaps os
)
where t = routeTree r
os = overlaps True t
maybezero :: MonadPlus m => Maybe a -> (a -> m b) -> m b
maybezero = flip (maybe mzero)
-- | Dispatch a request given a route. Give priority to more specific paths
-- in case of overlap.
dispatch :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) =>
RouteTree (m a) -> m a
dispatch (R t) = do
let m = Trie.children1 t
rq <- askRq
let ps = rqPaths rq
(case ps of
p:xs -> maybezero (Map.lookup (StringS p) m)
(localRq (\newRq -> newRq{rqPaths = xs}) . dispatch . R)
[] -> mzero)
-- most specific: match against a given next segment
`mplus`
(maybezero (Trie.lookup [] t) $ \em ->
maybezero (Map.lookup (Just (length ps), rqMethod rq) em) dispatchParams
-- or else a 'path' taking a given specific number of remaining segments
`mplus`
maybezero (Map.lookup (Nothing, rqMethod rq) em) dispatchRemainingPath
-- least specific: a 'remainingPath' taking any number of remaining segments
)
-- We want first to handle ones with params
dispatchParams :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) =>
Map (Maybe String) [m a] -> m a
dispatchParams m = let
(paramfull,paramless) = Map.partitionWithKey (const . isJust) m
in msum $ [doParam p >> msum hs | (p,hs) <- Map.assocs paramfull] ++ [msum hs | (Nothing,hs) <- Map.assocs paramless]
dispatchRemainingPath :: MonadPlus m => Map k [m a] -> m a
dispatchRemainingPath m = msum (map msum (Map.elems m))
-- | All paths with more than one handler.
overlaps :: forall a .
Bool -- ^ Only include order-dependent paths (exclude paths overlapping with more specific paths)
-> RouteTree a -> [[([Segment],[(EndSegment,[(Param,[a])])])]]
overlaps eso t = (filter (not . null) $
map (filter (not . null . snd) . (:[]) . second f) $
flattenTree t) ++
if eso then [] else pathOverlaps t
where f :: [(EndSegment,[(Param,[a])])] -> [(EndSegment,[(Param,[a])])]
f l = (filter (not . null . snd) . map (second g)) l
g l@((Nothing,_):_:_) | not eso = l -- non-parameter handler overlaps with parameter handlers
g l = filter ((>1) . length . snd) l -- more than one handler for this path
pathOverlaps :: RouteTree a -> [[([Segment], [(EndSegment, [(Param, [a])])])]]
pathOverlaps (R t) =
(case Trie.lookup [] t of
Just em -> filter ((>1) . length) $ map f (Map.keys em)
where f es1 = filter ((>0) . length . snd)
[ (ks, filter (lengthOverlaps es1 (length ks)) as)
| (ks,as) <- flattenTree (R t) ]
lengthOverlaps (a1,m1) ksl ((a2,m2),_) =
m1 == m2 && case (a1,a2) of
(Nothing,_) -> True
(Just i1,Nothing) -> i1 >= ksl
(Just i1,Just i2) -> i1 == ksl + i2
Nothing -> []) ++
[ [ (k:ks,a) | (ks,a) <- l ]
| (k,t') <- Map.assocs (Trie.children1 t)
, l <- pathOverlaps (R t') ]
showOverlaps :: [[([Segment],[(EndSegment,[(Param,[a])])])]] -> String
showOverlaps = unlines . intercalate [[]] . map (concatMap showPath)
showPath :: ([Segment],[(EndSegment,[(Param,[a])])]) -> [String]
showPath (ss,es) =
[ intercalate "/" (map showSegment ss++
showArity i)++
showParam p++showMethod m++
showHandlers hs
| ((i,m),ps) <- es, (p,hs) <- ps ]
where showParam Nothing = ""
showParam (Just p) = "?"++p++"=*"
showMethod H.GET = ""
showMethod m = " ("++show m++")"
showSegment (StringS s) = s
showArity Nothing = ["**"]
showArity (Just i) = replicate i "*"
showHandlers hs | length hs == 1 = ""
| otherwise = " -> "++show (length hs)
-- | Convert to a list of path-value pairs.
flattenTree :: RouteTree a -> [([Segment],[(EndSegment,[(Param,[a])])])]
flattenTree (R t) =
(case Trie.lookup [] t of
Just em -> [([], map (second Map.assocs) (Map.assocs em))]
Nothing -> []) ++
[ (k:ks,a) | (k,t') <- Map.assocs (Trie.children1 t)
, (ks,a) <- flattenTree (R t') ]
| carlssonia/happstack-static-routing | src/Happstack/StaticRouting/Internal.hs | bsd-3-clause | 8,603 | 0 | 20 | 2,252 | 3,429 | 1,827 | 1,602 | 159 | 5 |
{-# language CPP #-}
-- No documentation found for Chapter "Promoted_From_VK_KHR_format_feature_flags2"
module Vulkan.Core13.Promoted_From_VK_KHR_format_feature_flags2 ( FormatProperties3(..)
, StructureType(..)
, FormatFeatureFlagBits2(..)
, FormatFeatureFlags2
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlags2)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_FORMAT_PROPERTIES_3))
import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlagBits2(..))
import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlags2)
import Vulkan.Core10.Enums.StructureType (StructureType(..))
-- | VkFormatProperties3 - Structure specifying image format properties
--
-- = Description
--
-- The bits reported in @linearTilingFeatures@, @optimalTilingFeatures@ and
-- @bufferFeatures@ /must/ include the bits reported in the corresponding
-- fields of
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.FormatProperties2'::@formatProperties@.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_format_feature_flags2 VK_KHR_format_feature_flags2>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_3 VK_VERSION_1_3>,
-- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlags2',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data FormatProperties3 = FormatProperties3
{ -- | @linearTilingFeatures@ is a bitmask of
-- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2'
-- specifying features supported by images created with a @tiling@
-- parameter of 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR'.
linearTilingFeatures :: FormatFeatureFlags2
, -- | @optimalTilingFeatures@ is a bitmask of
-- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2'
-- specifying features supported by images created with a @tiling@
-- parameter of 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_OPTIMAL'.
optimalTilingFeatures :: FormatFeatureFlags2
, -- | @bufferFeatures@ is a bitmask of
-- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2'
-- specifying features supported by buffers.
bufferFeatures :: FormatFeatureFlags2
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (FormatProperties3)
#endif
deriving instance Show FormatProperties3
instance ToCStruct FormatProperties3 where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p FormatProperties3{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_FORMAT_PROPERTIES_3)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr FormatFeatureFlags2)) (linearTilingFeatures)
poke ((p `plusPtr` 24 :: Ptr FormatFeatureFlags2)) (optimalTilingFeatures)
poke ((p `plusPtr` 32 :: Ptr FormatFeatureFlags2)) (bufferFeatures)
f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_FORMAT_PROPERTIES_3)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct FormatProperties3 where
peekCStruct p = do
linearTilingFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 16 :: Ptr FormatFeatureFlags2))
optimalTilingFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 24 :: Ptr FormatFeatureFlags2))
bufferFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 32 :: Ptr FormatFeatureFlags2))
pure $ FormatProperties3
linearTilingFeatures optimalTilingFeatures bufferFeatures
instance Storable FormatProperties3 where
sizeOf ~_ = 40
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero FormatProperties3 where
zero = FormatProperties3
zero
zero
zero
| expipiplus1/vulkan | src/Vulkan/Core13/Promoted_From_VK_KHR_format_feature_flags2.hs | bsd-3-clause | 4,812 | 0 | 14 | 855 | 900 | 526 | 374 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Cataskell.Server.MessageTypesSpec (main, spec) where
import Test.Hspec
import Cataskell.Server.MessageTypes
import Data.Aeson
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $
describe "Message types" $ do
describe "AddUser" $
it "can be decoded from a string" $ do
let obj = AddUser "Test"
let obj' = fromJSON "Test" :: Result AddUser
obj' `shouldBe` Success obj
describe "NewMessage" $
it "contains a message from the user" $ do
let obj = NewMessage "Hello world."
let obj' = fromJSON "Hello world." :: Result NewMessage
obj' `shouldBe` Success obj
describe "UserName" $
it "contains a username" $ do
let obj = UserName "Test2"
let obj' = fromJSON "Test2" :: Result UserName
obj' `shouldBe` Success obj
describe "UserJoined" $
it "contains a username and the current number of users" $ do
let obj = UserJoined "Joiner" 3
let obj' = decode "{\"username\": \"Joiner\", \"numUsers\": 3}" :: Maybe UserJoined
obj' `shouldBe` Just obj
| corajr/cataskell | test-server/Cataskell/Server/MessageTypesSpec.hs | bsd-3-clause | 1,128 | 0 | 14 | 298 | 309 | 146 | 163 | 30 | 1 |
module Utils where
pkgToDir str =
let xs =
map
(\c ->
if c == '.'
then '/'
else c)
str
in "src/" ++ xs ++ "/"
| robstewart57/ripl | src/Utils.hs | bsd-3-clause | 186 | 0 | 13 | 103 | 56 | 30 | 26 | 10 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Generics
-- Copyright : (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2014
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- @since 4.6.0.0
--
-- If you're using @GHC.Generics@, you should consider using the
-- <http://hackage.haskell.org/package/generic-deriving> package, which
-- contains many useful generic functions.
module GHC.Generics (
-- * Introduction
--
-- |
--
-- Datatype-generic functions are based on the idea of converting values of
-- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@.
-- The type @'Rep' T@ is
-- built from a limited set of type constructors, all provided by this module. A
-- datatype-generic function is then an overloaded function with instances
-- for most of these type constructors, together with a wrapper that performs
-- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need
-- a few generic instances in order to implement functionality that works for any
-- representable type.
--
-- Representable types are collected in the 'Generic' class, which defines the
-- associated type 'Rep' as well as conversion functions 'from' and 'to'.
-- Typically, you will not define 'Generic' instances by hand, but have the compiler
-- derive them for you.
-- ** Representing datatypes
--
-- |
--
-- The key to defining your own datatype-generic functions is to understand how to
-- represent datatypes using the given set of type constructors.
--
-- Let us look at an example first:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
-- deriving 'Generic'
-- @
--
-- The above declaration (which requires the language pragma @DeriveGeneric@)
-- causes the following representation to be generated:
--
-- @
-- instance 'Generic' (Tree a) where
-- type 'Rep' (Tree a) =
-- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' a))
-- ':+:'
-- 'C1' ('MetaCons \"Node\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' (Tree a))
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' (Tree a))))
-- ...
-- @
--
-- /Hint:/ You can obtain information about the code being generated from GHC by passing
-- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using
-- the @:kind!@ command.
--
-- This is a lot of information! However, most of it is actually merely meta-information
-- that makes names of datatypes and constructors and more available on the type level.
--
-- Here is a reduced representation for @Tree@ with nearly all meta-information removed,
-- for now keeping only the most essential aspects:
--
-- @
-- instance 'Generic' (Tree a) where
-- type 'Rep' (Tree a) =
-- 'Rec0' a
-- ':+:'
-- ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a))
-- @
--
-- The @Tree@ datatype has two constructors. The representation of individual constructors
-- is combined using the binary type constructor ':+:'.
--
-- The first constructor consists of a single field, which is the parameter @a@. This is
-- represented as @'Rec0' a@.
--
-- The second constructor consists of two fields. Each is a recursive field of type @Tree a@,
-- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using
-- the binary type constructor ':*:'.
--
-- Now let us explain the additional tags being used in the complete representation:
--
-- * The @'S1' ('MetaSel 'Nothing 'NoSourceUnpackedness 'NoSourceStrictness
-- 'DecidedLazy)@ tag indicates several things. The @'Nothing@ indicates
-- that there is no record field selector associated with this field of
-- the constructor (if there were, it would have been marked @'Just
-- \"recordName\"@ instead). The other types contain meta-information on
-- the field's strictness:
--
-- * There is no @{\-\# UNPACK \#-\}@ or @{\-\# NOUNPACK \#-\}@ annotation
-- in the source, so it is tagged with @'NoSourceUnpackedness@.
--
-- * There is no strictness (@!@) or laziness (@~@) annotation in the
-- source, so it is tagged with @'NoSourceStrictness@.
--
-- * The compiler infers that the field is lazy, so it is tagged with
-- @'DecidedLazy@. Bear in mind that what the compiler decides may be
-- quite different from what is written in the source. See
-- 'DecidedStrictness' for a more detailed explanation.
--
-- The @'MetaSel@ type is also an instance of the type class 'Selector',
-- which can be used to obtain information about the field at the value
-- level.
--
-- * The @'C1' ('MetaCons \"Leaf\" 'PrefixI 'False)@ and
-- @'C1' ('MetaCons \"Node\" 'PrefixI 'False)@ invocations indicate that the enclosed part is
-- the representation of the first and second constructor of datatype @Tree@, respectively.
-- Here, the meta-information regarding constructor names, fixity and whether
-- it has named fields or not is encoded at the type level. The @'MetaCons@
-- type is also an instance of the type class 'Constructor'. This type class can be used
-- to obtain information about the constructor at the value level.
--
-- * The @'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)@ tag
-- indicates that the enclosed part is the representation of the
-- datatype @Tree@. Again, the meta-information is encoded at the type level.
-- The @'MetaData@ type is an instance of class 'Datatype', which
-- can be used to obtain the name of a datatype, the module it has been
-- defined in, the package it is located under, and whether it has been
-- defined using @data@ or @newtype@ at the value level.
-- ** Derived and fundamental representation types
--
-- |
--
-- There are many datatype-generic functions that do not distinguish between positions that
-- are parameters or positions that are recursive calls. There are also many datatype-generic
-- functions that do not care about the names of datatypes and constructors at all. To keep
-- the number of cases to consider in generic functions in such a situation to a minimum,
-- it turns out that many of the type constructors introduced above are actually synonyms,
-- defining them to be variants of a smaller set of constructors.
-- *** Individual fields of constructors: 'K1'
--
-- |
--
-- The type constructor 'Rec0' is a variant of 'K1':
--
-- @
-- type 'Rec0' = 'K1' 'R'
-- @
--
-- Here, 'R' is a type-level proxy that does not have any associated values.
--
-- There used to be another variant of 'K1' (namely @Par0@), but it has since
-- been deprecated.
-- *** Meta information: 'M1'
--
-- |
--
-- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1':
--
-- @
-- type 'S1' = 'M1' 'S'
-- type 'C1' = 'M1' 'C'
-- type 'D1' = 'M1' 'D'
-- @
--
-- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create
-- several variants of 'M1'.
-- *** Additional generic representation type constructors
--
-- |
--
-- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur
-- in the representations of other datatypes.
-- **** Empty datatypes: 'V1'
--
-- |
--
-- For empty datatypes, 'V1' is used as a representation. For example,
--
-- @
-- data Empty deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' Empty where
-- type 'Rep' Empty =
-- 'D1' ('MetaData \"Empty\" \"Main\" \"package-name\" 'False) 'V1'
-- @
-- **** Constructors without fields: 'U1'
--
-- |
--
-- If a constructor has no arguments, then 'U1' is used as its representation. For example
-- the representation of 'Bool' is
--
-- @
-- instance 'Generic' Bool where
-- type 'Rep' Bool =
-- 'D1' ('MetaData \"Bool\" \"Data.Bool\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"False\" 'PrefixI 'False) 'U1' ':+:' 'C1' ('MetaCons \"True\" 'PrefixI 'False) 'U1')
-- @
-- *** Representation of types with many constructors or many fields
--
-- |
--
-- As ':+:' and ':*:' are just binary operators, one might ask what happens if the
-- datatype has more than two constructors, or a constructor with more than two
-- fields. The answer is simple: the operators are used several times, to combine
-- all the constructors and fields as needed. However, users /should not rely on
-- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is
-- free to choose any nesting it prefers. (In practice, the current implementation
-- tries to produce a more-or-less balanced nesting, so that the traversal of
-- the structure of the datatype from the root to a particular component can be
-- performed in logarithmic rather than linear time.)
-- ** Defining datatype-generic functions
--
-- |
--
-- A datatype-generic function comprises two parts:
--
-- 1. /Generic instances/ for the function, implementing it for most of the representation
-- type constructors introduced above.
--
-- 2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion
-- between the original value and its `Rep`-based representation and then invokes the
-- generic instances.
--
-- As an example, let us look at a function @encode@ that produces a naive, but lossless
-- bit encoding of values of various datatypes. So we are aiming to define a function
--
-- @
-- encode :: 'Generic' a => a -> [Bool]
-- @
--
-- where we use 'Bool' as our datatype for bits.
--
-- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized
-- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation
-- type constructors operate with kind @* -> *@ as base kind. But the type argument is never
-- being used. This may be changed at some point in the future. The class has a single method,
-- and we use the type we want our final function to have, but we replace the occurrences of
-- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used).
--
-- > class Encode' f where
-- > encode' :: f p -> [Bool]
--
-- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define
-- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'.
-- *** Definition of the generic representation types
--
-- |
--
-- In order to be able to do this, we need to know the actual definitions of these types:
--
-- @
-- data 'V1' p -- lifted version of Empty
-- data 'U1' p = 'U1' -- lifted version of ()
-- data (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either'
-- data (':*:') f g p = (f p) ':*:' (g p) -- lifted version of (,)
-- newtype 'K1' i c p = 'K1' { 'unK1' :: c } -- a container for a c
-- newtype 'M1' i t f p = 'M1' { 'unM1' :: f p } -- a wrapper
-- @
--
-- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either',
-- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value
-- of a specific type @c@, and 'M1' wraps a value of the generic type argument,
-- which in the lifted world is an @f p@ (where we do not care about @p@).
-- *** Generic instances
--
-- |
--
-- The instance for 'V1' is slightly awkward (but also rarely used):
--
-- @
-- instance Encode' 'V1' where
-- encode' x = undefined
-- @
--
-- There are no values of type @V1 p@ to pass (except undefined), so this is
-- actually impossible. One can ask why it is useful to define an instance for
-- 'V1' at all in this case? Well, an empty type can be used as an argument to
-- a non-empty type, and you might still want to encode the resulting type.
-- As a somewhat contrived example, consider @[Empty]@, which is not an empty
-- type, but contains just the empty list. The 'V1' instance ensures that we
-- can call the generic function on such types.
--
-- There is exactly one value of type 'U1', so encoding it requires no
-- knowledge, and we can use zero bits:
--
-- @
-- instance Encode' 'U1' where
-- encode' 'U1' = []
-- @
--
-- In the case for ':+:', we produce 'False' or 'True' depending on whether
-- the constructor of the value provided is located on the left or on the right:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where
-- encode' ('L1' x) = False : encode' x
-- encode' ('R1' x) = True : encode' x
-- @
--
-- (Note that this encoding strategy may not be reliable across different
-- versions of GHC. Recall that the compiler is free to choose any nesting
-- of ':+:' it chooses, so if GHC chooses @(a ':+:' b) ':+:' c@, then the
-- encoding for @a@ would be @[False, False]@, @b@ would be @[False, True]@,
-- and @c@ would be @[True]@. However, if GHC chooses @a ':+:' (b ':+:' c)@,
-- then the encoding for @a@ would be @[False]@, @b@ would be @[True, False]@,
-- and @c@ would be @[True, True]@.)
--
-- In the case for ':*:', we append the encodings of the two subcomponents:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where
-- encode' (x ':*:' y) = encode' x ++ encode' y
-- @
--
-- The case for 'K1' is rather interesting. Here, we call the final function
-- @encode@ that we yet have to define, recursively. We will use another type
-- class @Encode@ for that function:
--
-- @
-- instance (Encode c) => Encode' ('K1' i c) where
-- encode' ('K1' x) = encode x
-- @
--
-- Note how we can define a uniform instance for 'M1', because we completely
-- disregard all meta-information:
--
-- @
-- instance (Encode' f) => Encode' ('M1' i t f) where
-- encode' ('M1' x) = encode' x
-- @
--
-- Unlike in 'K1', the instance for 'M1' refers to @encode'@, not @encode@.
-- *** The wrapper and generic default
--
-- |
--
-- We now define class @Encode@ for the actual @encode@ function:
--
-- @
-- class Encode a where
-- encode :: a -> [Bool]
-- default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
-- encode x = encode' ('from' x)
-- @
--
-- The incoming @x@ is converted using 'from', then we dispatch to the
-- generic instances using @encode'@. We use this as a default definition
-- for @encode@. We need the @default encode@ signature because ordinary
-- Haskell default methods must not introduce additional class constraints,
-- but our generic default does.
--
-- Defining a particular instance is now as simple as saying
--
-- @
-- instance (Encode a) => Encode (Tree a)
-- @
--
#if 0
-- /TODO:/ Add usage example?
--
#endif
-- The generic default is being used. In the future, it will hopefully be
-- possible to use @deriving Encode@ as well, but GHC does not yet support
-- that syntax for this situation.
--
-- Having @Encode@ as a class has the advantage that we can define
-- non-generic special cases, which is particularly useful for abstract
-- datatypes that have no structural representation. For example, given
-- a suitable integer encoding function @encodeInt@, we can define
--
-- @
-- instance Encode Int where
-- encode = encodeInt
-- @
-- *** Omitting generic instances
--
-- |
--
-- It is not always required to provide instances for all the generic
-- representation types, but omitting instances restricts the set of
-- datatypes the functions will work for:
--
-- * If no ':+:' instance is given, the function may still work for
-- empty datatypes or datatypes that have a single constructor,
-- but will fail on datatypes with more than one constructor.
--
-- * If no ':*:' instance is given, the function may still work for
-- datatypes where each constructor has just zero or one field,
-- in particular for enumeration types.
--
-- * If no 'K1' instance is given, the function may still work for
-- enumeration types, where no constructor has any fields.
--
-- * If no 'V1' instance is given, the function may still work for
-- any datatype that is not empty.
--
-- * If no 'U1' instance is given, the function may still work for
-- any datatype where each constructor has at least one field.
--
-- An 'M1' instance is always required (but it can just ignore the
-- meta-information, as is the case for @encode@ above).
#if 0
-- *** Using meta-information
--
-- |
--
-- TODO
#endif
-- ** Generic constructor classes
--
-- |
--
-- Datatype-generic functions as defined above work for a large class
-- of datatypes, including parameterized datatypes. (We have used @Tree@
-- as our example above, which is of kind @* -> *@.) However, the
-- 'Generic' class ranges over types of kind @*@, and therefore, the
-- resulting generic functions (such as @encode@) must be parameterized
-- by a generic type argument of kind @*@.
--
-- What if we want to define generic classes that range over type
-- constructors (such as 'Data.Functor.Functor',
-- 'Data.Traversable.Traversable', or 'Data.Foldable.Foldable')?
-- *** The 'Generic1' class
--
-- |
--
-- Like 'Generic', there is a class 'Generic1' that defines a
-- representation 'Rep1' and conversion functions 'from1' and 'to1',
-- only that 'Generic1' ranges over types of kind @* -> *@. (More generally,
-- it can range over types of kind @k -> *@, for any kind @k@, if the
-- @PolyKinds@ extension is enabled. More on this later.)
-- The 'Generic1' class is also derivable.
--
-- The representation 'Rep1' is ever so slightly different from 'Rep'.
-- Let us look at @Tree@ as an example again:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
-- deriving 'Generic1'
-- @
--
-- The above declaration causes the following representation to be generated:
--
-- @
-- instance 'Generic1' Tree where
-- type 'Rep1' Tree =
-- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1')
-- ':+:'
-- 'C1' ('MetaCons \"Node\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec1' Tree)
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec1' Tree)))
-- ...
-- @
--
-- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well
-- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we
-- carry around the dummy type argument for kind-@*@-types, but there are
-- already enough different names involved without duplicating each of
-- these.)
--
-- What's different is that we now use 'Par1' to refer to the parameter
-- (and that parameter, which used to be @a@), is not mentioned explicitly
-- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@.
-- *** Representation of @* -> *@ types
--
-- |
--
-- Unlike 'Rec0', the 'Par1' and 'Rec1' type constructors do not
-- map to 'K1'. They are defined directly, as follows:
--
-- @
-- newtype 'Par1' p = 'Par1' { 'unPar1' :: p } -- gives access to parameter p
-- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper
-- @
--
-- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply
-- wraps an application of @f@ to @p@.
--
-- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation,
-- namely when the datatype has a field that does not mention the parameter.
--
-- The declaration
--
-- @
-- data WithInt a = WithInt Int a
-- deriving 'Generic1'
-- @
--
-- yields
--
-- @
-- instance 'Generic1' WithInt where
-- type 'Rep1' WithInt =
-- 'D1' ('MetaData \"WithInt\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"WithInt\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' Int)
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1'))
-- @
--
-- If the parameter @a@ appears underneath a composition of other type constructors,
-- then the representation involves composition, too:
--
-- @
-- data Rose a = Fork a [Rose a]
-- @
--
-- yields
--
-- @
-- instance 'Generic1' Rose where
-- type 'Rep1' Rose =
-- 'D1' ('MetaData \"Rose\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Fork\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1'
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ([] ':.:' 'Rec1' Rose)))
-- @
--
-- where
--
-- @
-- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) }
-- @
-- *** Representation of @k -> *@ types
--
-- |
--
-- The 'Generic1' class can be generalized to range over types of kind
-- @k -> *@, for any kind @k@. To do so, derive a 'Generic1' instance with the
-- @PolyKinds@ extension enabled. For example, the declaration
--
-- @
-- data Proxy (a :: k) = Proxy deriving 'Generic1'
-- @
--
-- yields a slightly different instance depending on whether @PolyKinds@ is
-- enabled. If compiled without @PolyKinds@, then @'Rep1' Proxy :: * -> *@, but
-- if compiled with @PolyKinds@, then @'Rep1' Proxy :: k -> *@.
-- *** Representation of unlifted types
--
-- |
--
-- If one were to attempt to derive a Generic instance for a datatype with an
-- unlifted argument (for example, 'Int#'), one might expect the occurrence of
-- the 'Int#' argument to be marked with @'Rec0' 'Int#'@. This won't work,
-- though, since 'Int#' is of an unlifted kind, and 'Rec0' expects a type of
-- kind @*@.
--
-- One solution would be to represent an occurrence of 'Int#' with 'Rec0 Int'
-- instead. With this approach, however, the programmer has no way of knowing
-- whether the 'Int' is actually an 'Int#' in disguise.
--
-- Instead of reusing 'Rec0', a separate data family 'URec' is used to mark
-- occurrences of common unlifted types:
--
-- @
-- data family URec a p
--
-- data instance 'URec' ('Ptr' ()) p = 'UAddr' { 'uAddr#' :: 'Addr#' }
-- data instance 'URec' 'Char' p = 'UChar' { 'uChar#' :: 'Char#' }
-- data instance 'URec' 'Double' p = 'UDouble' { 'uDouble#' :: 'Double#' }
-- data instance 'URec' 'Int' p = 'UFloat' { 'uFloat#' :: 'Float#' }
-- data instance 'URec' 'Float' p = 'UInt' { 'uInt#' :: 'Int#' }
-- data instance 'URec' 'Word' p = 'UWord' { 'uWord#' :: 'Word#' }
-- @
--
-- Several type synonyms are provided for convenience:
--
-- @
-- type 'UAddr' = 'URec' ('Ptr' ())
-- type 'UChar' = 'URec' 'Char'
-- type 'UDouble' = 'URec' 'Double'
-- type 'UFloat' = 'URec' 'Float'
-- type 'UInt' = 'URec' 'Int'
-- type 'UWord' = 'URec' 'Word'
-- @
--
-- The declaration
--
-- @
-- data IntHash = IntHash Int#
-- deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' IntHash where
-- type 'Rep' IntHash =
-- 'D1' ('MetaData \"IntHash\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"IntHash\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'UInt'))
-- @
--
-- Currently, only the six unlifted types listed above are generated, but this
-- may be extended to encompass more unlifted types in the future.
#if 0
-- *** Limitations
--
-- |
--
-- /TODO/
--
-- /TODO:/ Also clear up confusion about 'Rec0' and 'Rec1' not really indicating recursion.
--
#endif
-----------------------------------------------------------------------------
-- * Generic representation types
V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..)
, (:+:)(..), (:*:)(..), (:.:)(..)
-- ** Unboxed representation types
, URec(..)
, type UAddr, type UChar, type UDouble
, type UFloat, type UInt, type UWord
-- ** Synonyms for convenience
, Rec0, R
, D1, C1, S1, D, C, S
-- * Meta-information
, Datatype(..), Constructor(..), Selector(..)
, Fixity(..), FixityI(..), Associativity(..), prec
, SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..)
, Meta(..)
-- * Generic type classes
, Generic(..), Generic1(..)
) where
-- We use some base types
import Data.Either ( Either (..) )
import Data.Maybe ( Maybe(..), fromMaybe )
import Data.Ord ( Down(..) )
import GHC.Integer ( Integer, integerToInt )
import GHC.Prim ( Addr#, Char#, Double#, Float#, Int#, Word# )
import GHC.Ptr ( Ptr )
import GHC.Types
-- Needed for instances
import GHC.Ix ( Ix )
import GHC.Base ( Alternative(..), Applicative(..), Functor(..)
, Monad(..), MonadPlus(..), NonEmpty(..), String, coerce
, Semigroup(..), Monoid(..) )
import GHC.Classes ( Eq(..), Ord(..) )
import GHC.Enum ( Bounded, Enum )
import GHC.Read ( Read(..) )
import GHC.Show ( Show(..), showString )
-- Needed for metadata
import Data.Proxy ( Proxy(..) )
import GHC.TypeLits ( KnownSymbol, KnownNat, symbolVal, natVal )
--------------------------------------------------------------------------------
-- Representation types
--------------------------------------------------------------------------------
-- | Void: used for datatypes without constructors
data V1 (p :: k)
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Read -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.12.0.0
instance Semigroup (V1 p) where
v <> _ = v
-- | Unit: used for constructors without arguments
data U1 (p :: k) = U1
deriving ( Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.9.0.0
instance Eq (U1 p) where
_ == _ = True
-- | @since 4.7.0.0
instance Ord (U1 p) where
compare _ _ = EQ
-- | @since 4.9.0.0
deriving instance Read (U1 p)
-- | @since 4.9.0.0
instance Show (U1 p) where
showsPrec _ _ = showString "U1"
-- | @since 4.9.0.0
instance Functor U1 where
fmap _ _ = U1
-- | @since 4.9.0.0
instance Applicative U1 where
pure _ = U1
_ <*> _ = U1
liftA2 _ _ _ = U1
-- | @since 4.9.0.0
instance Alternative U1 where
empty = U1
_ <|> _ = U1
-- | @since 4.9.0.0
instance Monad U1 where
_ >>= _ = U1
-- | @since 4.9.0.0
instance MonadPlus U1
-- | @since 4.12.0.0
instance Semigroup (U1 p) where
_ <> _ = U1
-- | @since 4.12.0.0
instance Monoid (U1 p) where
mempty = U1
-- | Used for marking occurrences of the parameter
newtype Par1 p = Par1 { unPar1 :: p }
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.9.0.0
instance Applicative Par1 where
pure = Par1
(<*>) = coerce
liftA2 = coerce
-- | @since 4.9.0.0
instance Monad Par1 where
Par1 x >>= f = f x
-- | @since 4.12.0.0
deriving instance Semigroup p => Semigroup (Par1 p)
-- | @since 4.12.0.0
deriving instance Monoid p => Monoid (Par1 p)
-- | Recursive calls of kind @* -> *@ (or kind @k -> *@, when @PolyKinds@
-- is enabled)
newtype Rec1 (f :: k -> Type) (p :: k) = Rec1 { unRec1 :: f p }
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.9.0.0
deriving instance Applicative f => Applicative (Rec1 f)
-- | @since 4.9.0.0
deriving instance Alternative f => Alternative (Rec1 f)
-- | @since 4.9.0.0
instance Monad f => Monad (Rec1 f) where
Rec1 x >>= f = Rec1 (x >>= \a -> unRec1 (f a))
-- | @since 4.9.0.0
deriving instance MonadPlus f => MonadPlus (Rec1 f)
-- | @since 4.12.0.0
deriving instance Semigroup (f p) => Semigroup (Rec1 f p)
-- | @since 4.12.0.0
deriving instance Monoid (f p) => Monoid (Rec1 f p)
-- | Constants, additional parameters and recursion of kind @*@
newtype K1 (i :: Type) c (p :: k) = K1 { unK1 :: c }
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.12.0.0
instance Monoid c => Applicative (K1 i c) where
pure _ = K1 mempty
liftA2 = \_ -> coerce (mappend :: c -> c -> c)
(<*>) = coerce (mappend :: c -> c -> c)
-- | @since 4.12.0.0
deriving instance Semigroup c => Semigroup (K1 i c p)
-- | @since 4.12.0.0
deriving instance Monoid c => Monoid (K1 i c p)
-- | @since 4.9.0.0
deriving instance Applicative f => Applicative (M1 i c f)
-- | @since 4.9.0.0
deriving instance Alternative f => Alternative (M1 i c f)
-- | @since 4.9.0.0
deriving instance Monad f => Monad (M1 i c f)
-- | @since 4.9.0.0
deriving instance MonadPlus f => MonadPlus (M1 i c f)
-- | @since 4.12.0.0
deriving instance Semigroup (f p) => Semigroup (M1 i c f p)
-- | @since 4.12.0.0
deriving instance Monoid (f p) => Monoid (M1 i c f p)
-- | Meta-information (constructor names, etc.)
newtype M1 (i :: Type) (c :: Meta) (f :: k -> Type) (p :: k) =
M1 { unM1 :: f p }
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Sums: encode choice between constructors
infixr 5 :+:
data (:+:) (f :: k -> Type) (g :: k -> Type) (p :: k) = L1 (f p) | R1 (g p)
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Products: encode multiple arguments to constructors
infixr 6 :*:
data (:*:) (f :: k -> Type) (g :: k -> Type) (p :: k) = f p :*: g p
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.9.0.0
instance (Applicative f, Applicative g) => Applicative (f :*: g) where
pure a = pure a :*: pure a
(f :*: g) <*> (x :*: y) = (f <*> x) :*: (g <*> y)
liftA2 f (a :*: b) (x :*: y) = liftA2 f a x :*: liftA2 f b y
-- | @since 4.9.0.0
instance (Alternative f, Alternative g) => Alternative (f :*: g) where
empty = empty :*: empty
(x1 :*: y1) <|> (x2 :*: y2) = (x1 <|> x2) :*: (y1 <|> y2)
-- | @since 4.9.0.0
instance (Monad f, Monad g) => Monad (f :*: g) where
(m :*: n) >>= f = (m >>= \a -> fstP (f a)) :*: (n >>= \a -> sndP (f a))
where
fstP (a :*: _) = a
sndP (_ :*: b) = b
-- | @since 4.9.0.0
instance (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g)
-- | @since 4.12.0.0
instance (Semigroup (f p), Semigroup (g p)) => Semigroup ((f :*: g) p) where
(x1 :*: y1) <> (x2 :*: y2) = (x1 <> x2) :*: (y1 <> y2)
-- | @since 4.12.0.0
instance (Monoid (f p), Monoid (g p)) => Monoid ((f :*: g) p) where
mempty = mempty :*: mempty
-- | Composition of functors
infixr 7 :.:
newtype (:.:) (f :: k2 -> Type) (g :: k1 -> k2) (p :: k1) =
Comp1 { unComp1 :: f (g p) }
deriving ( Eq -- ^ @since 4.7.0.0
, Ord -- ^ @since 4.7.0.0
, Read -- ^ @since 4.7.0.0
, Show -- ^ @since 4.7.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | @since 4.9.0.0
instance (Applicative f, Applicative g) => Applicative (f :.: g) where
pure x = Comp1 (pure (pure x))
Comp1 f <*> Comp1 x = Comp1 (liftA2 (<*>) f x)
liftA2 f (Comp1 x) (Comp1 y) = Comp1 (liftA2 (liftA2 f) x y)
-- | @since 4.9.0.0
instance (Alternative f, Applicative g) => Alternative (f :.: g) where
empty = Comp1 empty
(<|>) = coerce ((<|>) :: f (g a) -> f (g a) -> f (g a)) ::
forall a . (f :.: g) a -> (f :.: g) a -> (f :.: g) a
-- | @since 4.12.0.0
deriving instance Semigroup (f (g p)) => Semigroup ((f :.: g) p)
-- | @since 4.12.0.0
deriving instance Monoid (f (g p)) => Monoid ((f :.: g) p)
-- | Constants of unlifted kinds
--
-- @since 4.9.0.0
data family URec (a :: Type) (p :: k)
-- | Used for marking occurrences of 'Addr#'
--
-- @since 4.9.0.0
data instance URec (Ptr ()) (p :: k) = UAddr { uAddr# :: Addr# }
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Used for marking occurrences of 'Char#'
--
-- @since 4.9.0.0
data instance URec Char (p :: k) = UChar { uChar# :: Char# }
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Used for marking occurrences of 'Double#'
--
-- @since 4.9.0.0
data instance URec Double (p :: k) = UDouble { uDouble# :: Double# }
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Used for marking occurrences of 'Float#'
--
-- @since 4.9.0.0
data instance URec Float (p :: k) = UFloat { uFloat# :: Float# }
deriving ( Eq, Ord, Show
, Functor -- ^ @since 4.9.0.0
, Generic
, Generic1 -- ^ @since 4.9.0.0
)
-- | Used for marking occurrences of 'Int#'
--
-- @since 4.9.0.0
data instance URec Int (p :: k) = UInt { uInt# :: Int# }
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Used for marking occurrences of 'Word#'
--
-- @since 4.9.0.0
data instance URec Word (p :: k) = UWord { uWord# :: Word# }
deriving ( Eq -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Functor -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
, Generic1 -- ^ @since 4.9.0.0
)
-- | Type synonym for @'URec' 'Addr#'@
--
-- @since 4.9.0.0
type UAddr = URec (Ptr ())
-- | Type synonym for @'URec' 'Char#'@
--
-- @since 4.9.0.0
type UChar = URec Char
-- | Type synonym for @'URec' 'Double#'@
--
-- @since 4.9.0.0
type UDouble = URec Double
-- | Type synonym for @'URec' 'Float#'@
--
-- @since 4.9.0.0
type UFloat = URec Float
-- | Type synonym for @'URec' 'Int#'@
--
-- @since 4.9.0.0
type UInt = URec Int
-- | Type synonym for @'URec' 'Word#'@
--
-- @since 4.9.0.0
type UWord = URec Word
-- | Tag for K1: recursion (of kind @Type@)
data R
-- | Type synonym for encoding recursion (of kind @Type@)
type Rec0 = K1 R
-- | Tag for M1: datatype
data D
-- | Tag for M1: constructor
data C
-- | Tag for M1: record selector
data S
-- | Type synonym for encoding meta-information for datatypes
type D1 = M1 D
-- | Type synonym for encoding meta-information for constructors
type C1 = M1 C
-- | Type synonym for encoding meta-information for record selectors
type S1 = M1 S
-- | Class for datatypes that represent datatypes
class Datatype d where
-- | The name of the datatype (unqualified)
datatypeName :: t d (f :: k -> Type) (a :: k) -> [Char]
-- | The fully-qualified name of the module where the type is declared
moduleName :: t d (f :: k -> Type) (a :: k) -> [Char]
-- | The package name of the module where the type is declared
--
-- @since 4.9.0.0
packageName :: t d (f :: k -> Type) (a :: k) -> [Char]
-- | Marks if the datatype is actually a newtype
--
-- @since 4.7.0.0
isNewtype :: t d (f :: k -> Type) (a :: k) -> Bool
isNewtype _ = False
-- | @since 4.9.0.0
instance (KnownSymbol n, KnownSymbol m, KnownSymbol p, SingI nt)
=> Datatype ('MetaData n m p nt) where
datatypeName _ = symbolVal (Proxy :: Proxy n)
moduleName _ = symbolVal (Proxy :: Proxy m)
packageName _ = symbolVal (Proxy :: Proxy p)
isNewtype _ = fromSing (sing :: Sing nt)
-- | Class for datatypes that represent data constructors
class Constructor c where
-- | The name of the constructor
conName :: t c (f :: k -> Type) (a :: k) -> [Char]
-- | The fixity of the constructor
conFixity :: t c (f :: k -> Type) (a :: k) -> Fixity
conFixity _ = Prefix
-- | Marks if this constructor is a record
conIsRecord :: t c (f :: k -> Type) (a :: k) -> Bool
conIsRecord _ = False
-- | @since 4.9.0.0
instance (KnownSymbol n, SingI f, SingI r)
=> Constructor ('MetaCons n f r) where
conName _ = symbolVal (Proxy :: Proxy n)
conFixity _ = fromSing (sing :: Sing f)
conIsRecord _ = fromSing (sing :: Sing r)
-- | Datatype to represent the fixity of a constructor. An infix
-- | declaration directly corresponds to an application of 'Infix'.
data Fixity = Prefix | Infix Associativity Int
deriving ( Eq -- ^ @since 4.6.0.0
, Show -- ^ @since 4.6.0.0
, Ord -- ^ @since 4.6.0.0
, Read -- ^ @since 4.6.0.0
, Generic -- ^ @since 4.7.0.0
)
-- | This variant of 'Fixity' appears at the type level.
--
-- @since 4.9.0.0
data FixityI = PrefixI | InfixI Associativity Nat
-- | Get the precedence of a fixity value.
prec :: Fixity -> Int
prec Prefix = 10
prec (Infix _ n) = n
-- | Datatype to represent the associativity of a constructor
data Associativity = LeftAssociative
| RightAssociative
| NotAssociative
deriving ( Eq -- ^ @since 4.6.0.0
, Show -- ^ @since 4.6.0.0
, Ord -- ^ @since 4.6.0.0
, Read -- ^ @since 4.6.0.0
, Enum -- ^ @since 4.9.0.0
, Bounded -- ^ @since 4.9.0.0
, Ix -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.7.0.0
)
-- | The unpackedness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor Int
-- {\-\# NOUNPACK \#-\} Int
-- {\-\# UNPACK \#-\} Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceUnpackedness',
-- 'SourceNoUnpack', and 'SourceUnpack', respectively.
--
-- @since 4.9.0.0
data SourceUnpackedness = NoSourceUnpackedness
| SourceNoUnpack
| SourceUnpack
deriving ( Eq -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Read -- ^ @since 4.9.0.0
, Enum -- ^ @since 4.9.0.0
, Bounded -- ^ @since 4.9.0.0
, Ix -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
)
-- | The strictness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor Int ~Int !Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceStrictness',
-- 'SourceLazy', and 'SourceStrict', respectively.
--
-- @since 4.9.0.0
data SourceStrictness = NoSourceStrictness
| SourceLazy
| SourceStrict
deriving ( Eq -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Read -- ^ @since 4.9.0.0
, Enum -- ^ @since 4.9.0.0
, Bounded -- ^ @since 4.9.0.0
, Ix -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
)
-- | The strictness that GHC infers for a field during compilation. Whereas
-- there are nine different combinations of 'SourceUnpackedness' and
-- 'SourceStrictness', the strictness that GHC decides will ultimately be one
-- of lazy, strict, or unpacked. What GHC decides is affected both by what the
-- user writes in the source code and by GHC flags. As an example, consider
-- this data type:
--
-- @
-- data E = ExampleConstructor {\-\# UNPACK \#-\} !Int !Int Int
-- @
--
-- * If compiled without optimization or other language extensions, then the
-- fields of @ExampleConstructor@ will have 'DecidedStrict', 'DecidedStrict',
-- and 'DecidedLazy', respectively.
--
-- * If compiled with @-XStrictData@ enabled, then the fields will have
-- 'DecidedStrict', 'DecidedStrict', and 'DecidedStrict', respectively.
--
-- * If compiled with @-O2@ enabled, then the fields will have 'DecidedUnpack',
-- 'DecidedStrict', and 'DecidedLazy', respectively.
--
-- @since 4.9.0.0
data DecidedStrictness = DecidedLazy
| DecidedStrict
| DecidedUnpack
deriving ( Eq -- ^ @since 4.9.0.0
, Show -- ^ @since 4.9.0.0
, Ord -- ^ @since 4.9.0.0
, Read -- ^ @since 4.9.0.0
, Enum -- ^ @since 4.9.0.0
, Bounded -- ^ @since 4.9.0.0
, Ix -- ^ @since 4.9.0.0
, Generic -- ^ @since 4.9.0.0
)
-- | Class for datatypes that represent records
class Selector s where
-- | The name of the selector
selName :: t s (f :: k -> Type) (a :: k) -> [Char]
-- | The selector's unpackedness annotation (if any)
--
-- @since 4.9.0.0
selSourceUnpackedness :: t s (f :: k -> Type) (a :: k) -> SourceUnpackedness
-- | The selector's strictness annotation (if any)
--
-- @since 4.9.0.0
selSourceStrictness :: t s (f :: k -> Type) (a :: k) -> SourceStrictness
-- | The strictness that the compiler inferred for the selector
--
-- @since 4.9.0.0
selDecidedStrictness :: t s (f :: k -> Type) (a :: k) -> DecidedStrictness
-- | @since 4.9.0.0
instance (SingI mn, SingI su, SingI ss, SingI ds)
=> Selector ('MetaSel mn su ss ds) where
selName _ = fromMaybe "" (fromSing (sing :: Sing mn))
selSourceUnpackedness _ = fromSing (sing :: Sing su)
selSourceStrictness _ = fromSing (sing :: Sing ss)
selDecidedStrictness _ = fromSing (sing :: Sing ds)
-- | Representable types of kind @*@.
-- This class is derivable in GHC with the @DeriveGeneric@ flag on.
--
-- A 'Generic' instance must satisfy the following laws:
--
-- @
-- 'from' . 'to' ≡ 'Prelude.id'
-- 'to' . 'from' ≡ 'Prelude.id'
-- @
class Generic a where
-- | Generic representation type
type Rep a :: Type -> Type
-- | Convert from the datatype to its representation
from :: a -> (Rep a) x
-- | Convert from the representation to the datatype
to :: (Rep a) x -> a
-- | Representable types of kind @* -> *@ (or kind @k -> *@, when @PolyKinds@
-- is enabled).
-- This class is derivable in GHC with the @DeriveGeneric@ flag on.
--
-- A 'Generic1' instance must satisfy the following laws:
--
-- @
-- 'from1' . 'to1' ≡ 'Prelude.id'
-- 'to1' . 'from1' ≡ 'Prelude.id'
-- @
class Generic1 (f :: k -> Type) where
-- | Generic representation type
type Rep1 f :: k -> Type
-- | Convert from the datatype to its representation
from1 :: f a -> (Rep1 f) a
-- | Convert from the representation to the datatype
to1 :: (Rep1 f) a -> f a
--------------------------------------------------------------------------------
-- Meta-data
--------------------------------------------------------------------------------
-- | Datatype to represent metadata associated with a datatype (@MetaData@),
-- constructor (@MetaCons@), or field selector (@MetaSel@).
--
-- * In @MetaData n m p nt@, @n@ is the datatype's name, @m@ is the module in
-- which the datatype is defined, @p@ is the package in which the datatype
-- is defined, and @nt@ is @'True@ if the datatype is a @newtype@.
--
-- * In @MetaCons n f s@, @n@ is the constructor's name, @f@ is its fixity,
-- and @s@ is @'True@ if the constructor contains record selectors.
--
-- * In @MetaSel mn su ss ds@, if the field uses record syntax, then @mn@ is
-- 'Just' the record name. Otherwise, @mn@ is 'Nothing'. @su@ and @ss@ are
-- the field's unpackedness and strictness annotations, and @ds@ is the
-- strictness that GHC infers for the field.
--
-- @since 4.9.0.0
data Meta = MetaData Symbol Symbol Symbol Bool
| MetaCons Symbol FixityI Bool
| MetaSel (Maybe Symbol)
SourceUnpackedness SourceStrictness DecidedStrictness
--------------------------------------------------------------------------------
-- Derived instances
--------------------------------------------------------------------------------
-- | @since 4.6.0.0
deriving instance Generic [a]
-- | @since 4.6.0.0
deriving instance Generic (NonEmpty a)
-- | @since 4.6.0.0
deriving instance Generic (Maybe a)
-- | @since 4.6.0.0
deriving instance Generic (Either a b)
-- | @since 4.6.0.0
deriving instance Generic Bool
-- | @since 4.6.0.0
deriving instance Generic Ordering
-- | @since 4.6.0.0
deriving instance Generic (Proxy t)
-- | @since 4.6.0.0
deriving instance Generic ()
-- | @since 4.6.0.0
deriving instance Generic ((,) a b)
-- | @since 4.6.0.0
deriving instance Generic ((,,) a b c)
-- | @since 4.6.0.0
deriving instance Generic ((,,,) a b c d)
-- | @since 4.6.0.0
deriving instance Generic ((,,,,) a b c d e)
-- | @since 4.6.0.0
deriving instance Generic ((,,,,,) a b c d e f)
-- | @since 4.6.0.0
deriving instance Generic ((,,,,,,) a b c d e f g)
-- | @since 4.12.0.0
deriving instance Generic (Down a)
-- | @since 4.6.0.0
deriving instance Generic1 []
-- | @since 4.6.0.0
deriving instance Generic1 NonEmpty
-- | @since 4.6.0.0
deriving instance Generic1 Maybe
-- | @since 4.6.0.0
deriving instance Generic1 (Either a)
-- | @since 4.6.0.0
deriving instance Generic1 Proxy
-- | @since 4.6.0.0
deriving instance Generic1 ((,) a)
-- | @since 4.6.0.0
deriving instance Generic1 ((,,) a b)
-- | @since 4.6.0.0
deriving instance Generic1 ((,,,) a b c)
-- | @since 4.6.0.0
deriving instance Generic1 ((,,,,) a b c d)
-- | @since 4.6.0.0
deriving instance Generic1 ((,,,,,) a b c d e)
-- | @since 4.6.0.0
deriving instance Generic1 ((,,,,,,) a b c d e f)
-- | @since 4.12.0.0
deriving instance Generic1 Down
--------------------------------------------------------------------------------
-- Copied from the singletons package
--------------------------------------------------------------------------------
-- | The singleton kind-indexed data family.
data family Sing (a :: k)
-- | A 'SingI' constraint is essentially an implicitly-passed singleton.
class SingI (a :: k) where
-- | Produce the singleton explicitly. You will likely need the @ScopedTypeVariables@
-- extension to use this method the way you want.
sing :: Sing a
-- | The 'SingKind' class is essentially a /kind/ class. It classifies all kinds
-- for which singletons are defined. The class supports converting between a singleton
-- type and the base (unrefined) type which it is built from.
class SingKind k where
-- | Get a base type from a proxy for the promoted kind. For example,
-- @DemoteRep Bool@ will be the type @Bool@.
type DemoteRep k :: Type
-- | Convert a singleton to its unrefined version.
fromSing :: Sing (a :: k) -> DemoteRep k
-- Singleton symbols
data instance Sing (s :: Symbol) where
SSym :: KnownSymbol s => Sing s
-- | @since 4.9.0.0
instance KnownSymbol a => SingI a where sing = SSym
-- | @since 4.9.0.0
instance SingKind Symbol where
type DemoteRep Symbol = String
fromSing (SSym :: Sing s) = symbolVal (Proxy :: Proxy s)
-- Singleton booleans
data instance Sing (a :: Bool) where
STrue :: Sing 'True
SFalse :: Sing 'False
-- | @since 4.9.0.0
instance SingI 'True where sing = STrue
-- | @since 4.9.0.0
instance SingI 'False where sing = SFalse
-- | @since 4.9.0.0
instance SingKind Bool where
type DemoteRep Bool = Bool
fromSing STrue = True
fromSing SFalse = False
-- Singleton Maybe
data instance Sing (b :: Maybe a) where
SNothing :: Sing 'Nothing
SJust :: Sing a -> Sing ('Just a)
-- | @since 4.9.0.0
instance SingI 'Nothing where sing = SNothing
-- | @since 4.9.0.0
instance SingI a => SingI ('Just a) where sing = SJust sing
-- | @since 4.9.0.0
instance SingKind a => SingKind (Maybe a) where
type DemoteRep (Maybe a) = Maybe (DemoteRep a)
fromSing SNothing = Nothing
fromSing (SJust a) = Just (fromSing a)
-- Singleton Fixity
data instance Sing (a :: FixityI) where
SPrefix :: Sing 'PrefixI
SInfix :: Sing a -> Integer -> Sing ('InfixI a n)
-- | @since 4.9.0.0
instance SingI 'PrefixI where sing = SPrefix
-- | @since 4.9.0.0
instance (SingI a, KnownNat n) => SingI ('InfixI a n) where
sing = SInfix (sing :: Sing a) (natVal (Proxy :: Proxy n))
-- | @since 4.9.0.0
instance SingKind FixityI where
type DemoteRep FixityI = Fixity
fromSing SPrefix = Prefix
fromSing (SInfix a n) = Infix (fromSing a) (I# (integerToInt n))
-- Singleton Associativity
data instance Sing (a :: Associativity) where
SLeftAssociative :: Sing 'LeftAssociative
SRightAssociative :: Sing 'RightAssociative
SNotAssociative :: Sing 'NotAssociative
-- | @since 4.9.0.0
instance SingI 'LeftAssociative where sing = SLeftAssociative
-- | @since 4.9.0.0
instance SingI 'RightAssociative where sing = SRightAssociative
-- | @since 4.9.0.0
instance SingI 'NotAssociative where sing = SNotAssociative
-- | @since 4.0.0.0
instance SingKind Associativity where
type DemoteRep Associativity = Associativity
fromSing SLeftAssociative = LeftAssociative
fromSing SRightAssociative = RightAssociative
fromSing SNotAssociative = NotAssociative
-- Singleton SourceUnpackedness
data instance Sing (a :: SourceUnpackedness) where
SNoSourceUnpackedness :: Sing 'NoSourceUnpackedness
SSourceNoUnpack :: Sing 'SourceNoUnpack
SSourceUnpack :: Sing 'SourceUnpack
-- | @since 4.9.0.0
instance SingI 'NoSourceUnpackedness where sing = SNoSourceUnpackedness
-- | @since 4.9.0.0
instance SingI 'SourceNoUnpack where sing = SSourceNoUnpack
-- | @since 4.9.0.0
instance SingI 'SourceUnpack where sing = SSourceUnpack
-- | @since 4.9.0.0
instance SingKind SourceUnpackedness where
type DemoteRep SourceUnpackedness = SourceUnpackedness
fromSing SNoSourceUnpackedness = NoSourceUnpackedness
fromSing SSourceNoUnpack = SourceNoUnpack
fromSing SSourceUnpack = SourceUnpack
-- Singleton SourceStrictness
data instance Sing (a :: SourceStrictness) where
SNoSourceStrictness :: Sing 'NoSourceStrictness
SSourceLazy :: Sing 'SourceLazy
SSourceStrict :: Sing 'SourceStrict
-- | @since 4.9.0.0
instance SingI 'NoSourceStrictness where sing = SNoSourceStrictness
-- | @since 4.9.0.0
instance SingI 'SourceLazy where sing = SSourceLazy
-- | @since 4.9.0.0
instance SingI 'SourceStrict where sing = SSourceStrict
-- | @since 4.9.0.0
instance SingKind SourceStrictness where
type DemoteRep SourceStrictness = SourceStrictness
fromSing SNoSourceStrictness = NoSourceStrictness
fromSing SSourceLazy = SourceLazy
fromSing SSourceStrict = SourceStrict
-- Singleton DecidedStrictness
data instance Sing (a :: DecidedStrictness) where
SDecidedLazy :: Sing 'DecidedLazy
SDecidedStrict :: Sing 'DecidedStrict
SDecidedUnpack :: Sing 'DecidedUnpack
-- | @since 4.9.0.0
instance SingI 'DecidedLazy where sing = SDecidedLazy
-- | @since 4.9.0.0
instance SingI 'DecidedStrict where sing = SDecidedStrict
-- | @since 4.9.0.0
instance SingI 'DecidedUnpack where sing = SDecidedUnpack
-- | @since 4.9.0.0
instance SingKind DecidedStrictness where
type DemoteRep DecidedStrictness = DecidedStrictness
fromSing SDecidedLazy = DecidedLazy
fromSing SDecidedStrict = DecidedStrict
fromSing SDecidedUnpack = DecidedUnpack
| sdiehl/ghc | libraries/base/GHC/Generics.hs | bsd-3-clause | 54,675 | 0 | 12 | 13,656 | 7,223 | 4,427 | 2,796 | -1 | -1 |
{-# LANGUAGE Rank2Types, ScopedTypeVariables, FlexibleInstances, OverloadedStrings, TypeSynonymInstances, TypeOperators, GADTs #-}
module Paskell.Syntax.Haskell where
import Paskell.Expr
import Paskell.EvalM
import Control.Monad
import Data.Maybe
import System.IO.Unsafe
import Control.Monad.Error
import Control.Monad.Writer
import Control.Monad.Trans
import Data.String
instance IsString E where
fromString s = EVar s
instance IsString Pat where
fromString s = PVar s
instance IsString [Pat] where
fromString = map fromString . words
infixl 0 =:
infixl 1 $-
f $- x = f x
class HasAssign a where
(=:) :: Pat -> E -> a
instance HasAssign D where
p =: e = DLet p e
instance HasAssign E where
p =: e = EAssign p e
tint = TCon "Int"
treal = TCon "Real"
tstring = TCon "String"
tunit = TCon "Unit"
a = TVar "a"
b = TVar "b"
c = TVar "c"
vunit = pack ()
infixr 3 ~>
targs ~> t2 = TLam targs t2
instance Num E where
e1 + e2 = EVar "+" $> [e1, e2]
e1 - e2 = EVar "-" $> [e1, e2]
e1 * e2 = EVar "*" $> [e1, e2]
abs e = EVar "abs" $> [e]
signum e = EVar "signum" $> [e]
fromInteger n = ECon (VInt $ fromInteger n)
instance Num Pat where
e1 + e2 = error "Pattern nummeric instance"
e1 - e2 = error "Pattern nummeric instance"
e1 * e2 = error "Pattern nummeric instance"
abs e = error "Pattern nummeric instance"
signum e = error "Pattern nummeric instance"
fromInteger n = PLit (VInt $ fromInteger n)
class Reify a where
reify :: V-> Maybe a
pack :: a->V
packType :: a->T
instance Reify V where
reify = Just
pack = id
packType = undefined
instance Reify Double where
reify (VReal x) = Just x
reify v = Nothing
pack = VReal
packType _ = treal
instance Reify Int where
reify (VInt x) = Just x
reify v = Nothing
pack = VInt
packType _ = tint
instance Reify () where
reify (VCons "unit" []) = Just ()
reify v = Nothing
pack () = VCons "unit" []
packType _ = TCon "Unit"
newtype String_ = String_ { unString :: [Char] }
instance Reify String_ where
reify (VString s) = Just $ String_ s
reify v = Nothing
pack (String_ s) = VString s
packType _ = tint
instance Reify Bool where
reify (VCons "True" []) = Just True
reify (VCons "False" []) = Just False
reify v = Nothing
pack True = VCons "True" []
pack False = VCons "False" []
packType _ = TCon "Bool"
instance (Reify a, Reify b) => Reify (a-> IO b) where
reify (VLam f)
= Just $
\hsArgs-> do
res <- runErrorT $ f $ [pack hsArgs]
case res of
Left s -> error $ "error in reify function: "++s
Right v -> return $ fromJust $ reify v
reify _ = Nothing
pack f = VLam $
\[v]-> case reify v of
Nothing -> fail $ "pack function: fail for argument"
++ show v++" for function of type "++show (packType f)
Just x -> do v<- liftIO $ f x
return $ pack v
packType f = typeFIO f
typeFIO :: forall a b. (Reify a, Reify b) => (a-> IO b) -> T
typeFIO f = let x = undefined :: a --undefined
y = unsafePerformIO $ f x
in [packType x] ~> packType y
typeF :: forall a b. (Reify a, Reify b) => (a-> b) -> T
typeF f = let x = undefined :: a --undefined
y = f x
in [packType x] ~> packType y
typeF2 :: forall a b c. (Reify a, Reify b, Reify c) => (a-> b -> c) -> T
typeF2 f = let x = undefined :: a --undefined
y = undefined :: b
z = f x y
in [packType x, packType y] ~> packType y
packF1 :: (Reify a, Reify b) => (a->b) -> (T,V)
packF1 f = (typeF f, VLam $ \[v] -> case reify v of
Nothing -> error $ "pack function: fail for argument"
++ show v++" for function of type "++show (typeF f)
Just x -> return $ pack $ (f x ))
packF2 :: (Reify a, Reify b, Reify c) => (a->b->c) -> (T,V)
packF2 f = (typeF2 f, VLam $ \[vx,vy] -> case liftM2 (,) (reify vx) (reify vy) of
Nothing -> error $ "pack function: fail for argument"
++ show vx++" for function of type "++show (typeF2 f)
Just (x,y) -> return $ pack $ (f x y))
type TopLevel a = Writer [D] a
type CasePates = Writer [Pat :-> Function ()] ()
type Function a = Writer [E] a
infixl 1 -:>
p -:> es = tell [p :-> es]
instance HasAssign (TopLevel a) where
p =: e = tell [DLet p e] >> return undefined
instance HasAssign (Function a) where
p =: e = tell [p =: e] >> return undefined
lam :: [Pat] -> Function () -> E
lam pats fwriter = ELam pats $ execWriter fwriter
module_ :: TopLevel () -> [D]
module_ = execWriter
d :: D -> TopLevel ()
d = tell . (:[])
e :: ToExprs a => a -> Function ()
e = tell . toExprs
e $>> es = tell [e $> es]
for n m ix bd = "for" $>> [n, m, ELam ix (execWriter bd)]
infixl 5 :->
data a :-> b = a :-> b
data Then = Then
data Else = Else
if_ :: E -> Then ->Function () -> Else -> Function () -> Function ()
if_ p _ c _ a = tell [EIf p (execWriter c) (execWriter a)]
caseOf :: E -> CasePates -> Function ()
caseOf e pates = tell [ECase e $ map f $ execWriter pates] where
f (p:->es) = (p,execWriter es)
class ToExprs a where
toExprs :: a -> [E]
instance ToExprs E where
toExprs = (:[])
instance ToExprs [Char] where
toExprs = (:[]) . EVar
instance ToExprs [E] where
toExprs = id
instance ToExprs V where
toExprs = (:[]) . ECon
instance ToExprs () where
toExprs _ = [ECon (pack ())]
instance ToExprs (Function ()) where
toExprs w = execWriter w
class CallResult a where
($>) :: E -> [E] -> a
instance CallResult (Function a) where
f $> args = tell [EApp f args] >> return undefined
instance CallResult (E) where
f $> args = EApp f args
--($>) = call
--($>) :: E -> [E] -> E
--f $> es = EApp f es
| glutamate/paskell | Paskell/Syntax/Haskell.hs | bsd-3-clause | 6,071 | 0 | 15 | 1,875 | 2,543 | 1,294 | 1,249 | 173 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
-- #define DEBUG
{-|
Module : AERN2.Poly.Ball
Description : Polynomial enclosures with large radii
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Polynomial enclosures with large radii
-}
module AERN2.Poly.Ball
-- (
-- )
where
#ifdef DEBUG
import Debug.Trace (trace)
#define maybeTrace trace
#else
#define maybeTrace (flip const)
#endif
import MixedTypesNumPrelude
-- import qualified Prelude as P
-- import Text.Printf
-- import qualified Data.Map as Map
-- import qualified Data.List as List
-- import Test.Hspec
-- import Test.QuickCheck
import Control.CollectErrors
import AERN2.Normalize
import AERN2.MP hiding (ball_value, ball_error)
-- import qualified AERN2.MP.Ball as MPBall
import AERN2.MP.Dyadic
import AERN2.Real hiding (ball_value)
import AERN2.Interval
import AERN2.RealFun.Operations
import AERN2.Poly.Cheb as ChPoly
{- examples -}
_pb_const1 :: PolyBall
_pb_const1 =
constFn (dom, bits 100) 1
where
dom = dyadicInterval (0.0,1.0)
_pb_X :: PolyBall
_pb_X =
varFn (dom, bits 100) ()
where
dom = dyadicInterval (0.0,1.0)
{- type -}
type PolyBall = Ball (ChPoly MPBall)
polyBall :: (ConvertibleExactly t PolyBall) => t -> PolyBall
polyBall = convertExactly
data Ball t = Ball { ball_value :: t, ball_radius :: ErrorBound }
instance (Show t) => Show (Ball t) where
show (Ball c e) = "Ball " ++ (show c) ++ "+-" ++ (show e)
instance (CanBeErrors es) => CanEnsureCE es (Ball t)
instance (CanBeErrors es) => CanExtractCE es Ball where
extractCE sample_es (Ball cCE e) =
case ensureNoCE sample_es cCE of
(Just c, es) -> CollectErrors (Just (Ball c e)) es
(_, es) -> CollectErrors Nothing es
degree :: PolyBall -> Integer
degree (Ball c _e) = ChPoly.degree c
ballLift1R :: (IsBall t) => (t -> t1) -> (Ball t -> t1)
ballLift1R f (Ball c e) = f (updateRadius (+ e) c)
ballLift1TR :: (IsBall t) => (t -> t1 -> t2) -> (Ball t -> t1 -> t2)
ballLift1TR f (Ball c e) = f (updateRadius (+ e) c)
ballLift1T :: (IsBall t) => (t -> t1 -> t) -> (Ball t -> t1 -> Ball t)
ballLift1T f (Ball c e) t = Ball fceC fceE
where
fceC = centreAsBall fce
fceE = radius fce
fce = f (updateRadius (+e) c) t
ballLift1TCN ::
(IsBall t, CanEnsureCN t) =>
(t -> t1 -> EnsureCN t) -> (Ball t -> t1 -> CN (Ball t))
ballLift1TCN f b@(Ball c e) t =
case deEnsureCN fceCN of
Right fce ->
let
fceC = centreAsBall fce
fceE = radius fce
in
cn $ Ball fceC fceE
Left es ->
noValueECN (Just b) es
where
fceCN = f (updateRadius (+e) c) t
-- instance CanExtractCE es Ball where
-- extractCE sample_es
ballLift1 :: (IsBall t) => (t -> t) -> (Ball t -> Ball t)
ballLift1 f (Ball c1 e1) = Ball fceC fceE
where
fceC = centreAsBall fce
fceE = radius fce
fce = f (updateRadius (+e1) c1)
ballLift2 :: (IsBall t) => (t -> t -> t) -> (Ball t -> Ball t -> Ball t)
ballLift2 f (Ball c1 e1) (Ball c2 e2) = Ball fceC fceE
where
fceC = centreAsBall fce
fceE = radius fce
fce = f (updateRadius (+e1) c1) (updateRadius (+e2) c2)
instance (IsBall t) => IsBall (Ball t) where
type CentreType (Ball t) = t
centre = ball_value
radius = ball_radius
updateRadius updateFn (Ball c r) = Ball c (updateFn r)
centreAsBallAndRadius (Ball c r) = (Ball c (errorBound 0), r)
instance (IsBall t, CanNormalize t) => CanNormalize (Ball t) where
normalize (Ball x e) = Ball (centreAsBall xN) (radius xN + e)
where
xN = normalize x
instance
HasFnConstructorInfo t
=>
HasFnConstructorInfo (Ball t)
where
type FnConstructorInfo (Ball t) = FnConstructorInfo t
getFnConstructorInfo (Ball c _) = getFnConstructorInfo c
instance (ConvertibleExactly (i, t2) t) =>
ConvertibleExactly (i, t2) (Ball t)
where
safeConvertExactly (constrInfo, x) =
case safeConvertExactly (constrInfo, x) of
Right c -> Right $ Ball c (errorBound 0)
Left e -> Left e
-- instance (ConvertibleExactly (t, t2) t) =>
-- ConvertibleExactly (Ball t, t2) (Ball t)
-- where
-- safeConvertExactly (Ball sample eb, x) =
-- case safeConvertExactly (sample, x) of
-- Right c -> Right $ Ball c eb
-- Left e -> Left e
instance (HasDomain t) => HasDomain (Ball t)
where
type Domain (Ball t) = Domain t
getDomain = getDomain . ball_value
instance (HasVars t) => HasVars (Ball t) where
type Var (Ball t) = Var t
varFn constrInfo var = Ball (varFn constrInfo var) (errorBound 0)
{- precision -}
instance (HasPrecision t, IsBall t) => HasPrecision (Ball t) where
getPrecision = ballLift1R getPrecision
instance (CanSetPrecision t, IsBall t) => CanSetPrecision (Ball t) where
setPrecision prc (Ball c e) = Ball (setPrecision prc c) e
{- accuracy -}
instance (HasAccuracy t, IsBall t) => HasAccuracy (Ball t) where
getAccuracy= ballLift1R getAccuracy
getFiniteAccuracy= ballLift1R getFiniteAccuracy
instance (HasAccuracyGuide t, IsBall t) => HasAccuracyGuide (Ball t) where
getAccuracyGuide = ballLift1R getAccuracyGuide
instance (CanSetAccuracyGuide t, IsBall t) => CanSetAccuracyGuide (Ball t) where
setAccuracyGuide acGuide = ballLift1 (setAccuracyGuide acGuide)
instance
(IsBall t, CanNormalize t, CanReduceSizeUsingAccuracyGuide t)
=>
CanReduceSizeUsingAccuracyGuide (Ball t)
where
reduceSizeUsingAccuracyGuide ac (Ball c e) =
normalize $ Ball (reduceSizeUsingAccuracyGuide ac c) e
{- negation -}
instance CanNegSameType t => CanNeg (Ball t) where
type NegType (Ball t) = Ball t
negate (Ball x e) = Ball (negate x) e
{- addition -}
instance (IsBall t, CanNormalize t, CanAddSameType t) => CanAddAsymmetric (Ball t) (Ball t) where
type AddType (Ball t) (Ball t) = Ball t
add (Ball x1 e1) (Ball x2 e2) =
normalize $ Ball (x1 + x2) (e1 + e2)
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]]
(\ t -> [d|
instance (CanAddThis t $t, IsBall t, CanNormalize t) => CanAddAsymmetric $t (Ball t) where
type AddType $t (Ball t) = Ball t
add n (Ball x e) = normalize $ Ball (x + n) e
instance (CanAddThis t $t, IsBall t, CanNormalize t) => CanAddAsymmetric (Ball t) $t where
type AddType (Ball t) $t = Ball t
add (Ball x e) n = normalize $ Ball (x + n) e
|]))
{- subtraction -}
instance (IsBall t, CanNormalize t, CanAddSameType t, CanNegSameType t) => CanSub (Ball t) (Ball t)
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]]
(\ t -> [d|
instance (IsBall t, CanNormalize t, CanAddThis t $t, CanNegSameType t) => CanSub $t (Ball t)
instance (IsBall t, CanNormalize t, CanAddThis t $t) => CanSub (Ball t) $t
|]))
{- multiplication -}
multiplyWithBounds :: PolyBall -> MPBall -> PolyBall -> MPBall -> PolyBall
multiplyWithBounds (Ball p ep) bp (Ball q eq) bq =
makeExactCentre res
where
res = Ball (p * q) e
e = ep*(errorBound bq) + (errorBound bp)*eq + ep*eq
multiplyAccurate :: PolyBall -> PolyBall -> PolyBall
multiplyAccurate f g =
multiplyWithAccuracy (min ((getFiniteAccuracy f) + 1) ((getFiniteAccuracy g) + 1)) f g
multiplyWithAccuracy :: Accuracy -> PolyBall -> PolyBall -> PolyBall
multiplyWithAccuracy ac f@(Ball p _) g@(Ball q _) =
multiplyWithBounds f (rangeWithAccuracy p) g (rangeWithAccuracy q)
where
rangeWithAccuracy h =
let
Interval a' b' = chPoly_dom h
pr = getPrecision h
a = setPrecision pr $ mpBall a'
b = setPrecision pr $ mpBall b'
in
max (abs $ maximumOptimisedWithAccuracy ac h a b 5 5)
(abs $ minimumOptimisedWithAccuracy ac h a b 5 5)
instance
-- (IsBall t, CanNormalize t, CanMulSameType t)
-- =>
-- CanMulAsymmetric (Ball t) (Ball t) where
-- type MulType (Ball t) (Ball t) = Ball t
CanMulAsymmetric PolyBall PolyBall where
type MulType PolyBall PolyBall = PolyBall
mul = ballLift2 mul
-- mul = multiplyWithAccuracy (bits 0)
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]]
(\ t -> [d|
instance (CanMulBy t $t, IsBall t, CanNormalize t) => CanMulAsymmetric $t (Ball t) where
type MulType $t (Ball t) = Ball t
mul = flip (ballLift1T (flip mul))
instance (CanMulBy t $t, IsBall t, CanNormalize t) => CanMulAsymmetric (Ball t) $t where
type MulType (Ball t) $t = Ball t
mul = ballLift1T mul
|]))
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]]
(\ t -> [d|
instance (CanDivCNBy t $t, IsBall t, CanNormalize t, CanEnsureCN t) => CanDiv (Ball t) $t where
type DivTypeNoCN (Ball t) $t = Ball t
divideNoCN = ballLift1T divideNoCN
type DivType (Ball t) $t = EnsureCN (Ball t)
divide = ballLift1TCN divide
|]))
{- evaluation -}
instance CanApply PolyBall MPBall where
type ApplyType PolyBall MPBall = MPBall
apply (Ball c e) y = updateRadius (+e) (apply c y)
instance CanApplyApprox PolyBall DyadicInterval where
type ApplyApproxType PolyBall DyadicInterval = MPBall
applyApprox (Ball c e) y =
updateRadius (+e) (applyApprox c y)
{- maximisation -}
instance CanMaximiseOverDom PolyBall DyadicInterval where
type MaximumOverDomType PolyBall DyadicInterval = MPBall
maximumOverDom (Ball c e) di =
maximumOverDom (updateRadius (+e) c) di
instance CanMinimiseOverDom PolyBall DyadicInterval where
type MinimumOverDomType PolyBall DyadicInterval = MPBall
minimumOverDom (Ball c e) di =
minimumOverDom (updateRadius (+e) c) di
{- integration -}
instance CanIntegrateOverDom PolyBall DyadicInterval where
type IntegralOverDomType PolyBall DyadicInterval = MPBall
integrateOverDom (Ball c e) di =
integrateOverDom (updateRadius (+e) c) di
instance CanSinCosSameType t => CanSinCos (Ball t) where
type SinCosType (Ball t) = Ball t
sin (Ball x e) = Ball (sin x) e
cos (Ball x e) = Ball (cos x) e
| michalkonecny/aern2 | aern2-fun-univariate/src/AERN2/Poly/Ball.hs | bsd-3-clause | 10,071 | 0 | 13 | 2,184 | 3,161 | 1,708 | 1,453 | -1 | -1 |
module Paths ( vheDirStructure
, cabalConfigLocation
, getVirtualEnvironment
) where
import System.FilePath ((</>))
import System.Directory (getCurrentDirectory)
import System.Environment (getEnvironment)
import Types
import MyMonad
-- returns record containing paths to all important directories
-- inside virtual environment dir structure
vheDirStructure :: MyMonad DirStructure
vheDirStructure = do
cwd <- liftIO getCurrentDirectory
let virthualEnvLocation = cwd
virthualEnvDirLocation = virthualEnvLocation </> ".virthualenv"
cabalDirLocation = virthualEnvDirLocation </> "cabal"
ghcDirLocation = virthualEnvDirLocation </> "ghc"
return DirStructure { virthualEnv = virthualEnvLocation
, virthualEnvDir = virthualEnvDirLocation
, ghcPackagePath = virthualEnvDirLocation </> "ghc_pkg_db"
, cabalDir = cabalDirLocation
, cabalBinDir = cabalDirLocation </> "bin"
, virthualEnvBinDir = virthualEnvDirLocation </> "bin"
, ghcDir = ghcDirLocation
, ghcBinDir = ghcDirLocation </> "bin"
}
-- returns location of cabal's config file inside virtual environment dir structure
cabalConfigLocation :: MyMonad FilePath
cabalConfigLocation = do
dirStructure <- vheDirStructure
return $ cabalDir dirStructure </> "config"
-- returns environment dictionary used in Virtual Haskell Environment
-- it's inherited from the current process, but variable
-- GHC_PACKAGE_PATH is altered.
getVirtualEnvironment :: MyMonad [(String, String)]
getVirtualEnvironment = do
env <- liftIO getEnvironment
dirStructure <- vheDirStructure
return $ ("GHC_PACKAGE_PATH", ghcPackagePath dirStructure) : filter (\(k,_) -> k /= "GHC_PACKAGE_PATH") env
| Paczesiowa/virthualenv | src/Paths.hs | bsd-3-clause | 1,935 | 0 | 11 | 506 | 306 | 172 | 134 | 32 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Zodiac.HttpClient.TSRP(
authedHttpClientRequest
, macHttpClientRequest
, httpAuthHeader
, httpClientKeyId
, httpClientAuthHeader
, verifyHttpClientRequest
, verifyHttpClientRequest'
) where
import Data.Time.Clock (UTCTime, getCurrentTime)
import Network.HTTP.Client (Request(..), requestHeaders)
import Network.HTTP.Types (Header)
import Network.HTTP.Types.Header (hAuthorization)
import P
import System.IO (IO)
import Tinfoil.Data (Verified(..), MAC)
import Zodiac.Core.Request
import Zodiac.TSRP.Data
import Zodiac.TSRP.Symmetric
import Zodiac.HttpClient.Error
import Zodiac.HttpClient.Request
-- | Authenticate an http-client request. If the request isn't
-- malformed, the output is a Request object with the necessary
-- Authorization header added which can be sent directly to a server
-- supporting TSRP.
authedHttpClientRequest :: KeyId
-> TSRPKey
-> RequestExpiry
-> Request
-> RequestTimestamp
-> Either RequestError Request
authedHttpClientRequest kid sk re r rt =
toCanonicalRequest r >>= \cr ->
let mac = macRequest TSRPv1 kid rt re cr sk
authH = httpAuthHeader TSRPv1 kid rt re cr mac
newHeaders = authH : (requestHeaders r) in
Right $ r { requestHeaders = newHeaders }
-- | Works as 'verifyHttpClientRequest'', but uses the current time to verify
-- the request.
verifyHttpClientRequest :: KeyId
-> TSRPKey
-> Request
-> IO Verified
verifyHttpClientRequest kid sk r =
getCurrentTime >>= (verifyHttpClientRequest' kid sk r)
-- | Verify an authenticated http-client request. The 'KeyId' parameter
-- can be extracted with 'httpClientKeyId'; the 'TSRPKey' should be
-- the one associated with the 'KeyId'.
verifyHttpClientRequest' :: KeyId
-> TSRPKey
-> Request
-> UTCTime
-> IO Verified
verifyHttpClientRequest' kid sk req now =
case httpClientAuthHeader req of
Left _ ->
pure NotVerified
Right sah ->
case toCanonicalRequest req of
Left _ -> pure NotVerified
Right cr -> verifyRequest kid sk cr sah now
-- | Extract the 'KeyId' from a request.
httpClientKeyId :: Request
-> Either ProtocolError KeyId
httpClientKeyId r =
httpClientAuthHeader r >>= (pure . sahKeyId)
httpClientAuthHeader :: Request
-> Either ProtocolError SymmetricAuthHeader
httpClientAuthHeader r =
let hs = requestHeaders r in
case filter ((== hAuthorization) . fst) hs of
[] ->
Left NoAuthHeader
[(_, v)] ->
maybe' (Left MalformedAuthHeader) Right $ parseSymmetricAuthHeader v
_ -> Left MultipleAuthHeaders
-- | Given a precomputed MAC of a request, construct the appropriate
-- Authorization header in a form suitable to be used with
-- http-client.
httpAuthHeader :: SymmetricProtocol
-> KeyId
-> RequestTimestamp
-> RequestExpiry
-> CRequest
-> MAC
-> Header
httpAuthHeader TSRPv1 kid rt re cr mac =
let sh = signedHeaders cr
sah = SymmetricAuthHeader TSRPv1 kid rt re sh mac in
(hAuthorization, renderSymmetricAuthHeader sah)
-- | Create a detached MAC of an http-client request. This MAC can be
-- converted to an http-client-compatible Authorization header using
-- 'httpAuthHeader'.
macHttpClientRequest :: KeyId
-> TSRPKey
-> RequestExpiry
-> Request
-> RequestTimestamp
-> Either RequestError MAC
macHttpClientRequest kid sk re r rts = do
cr <- toCanonicalRequest r
pure $ macRequest TSRPv1 kid rts re cr sk
| ambiata/zodiac | zodiac-http-client/src/Zodiac/HttpClient/TSRP.hs | bsd-3-clause | 4,068 | 0 | 13 | 1,248 | 750 | 400 | 350 | 87 | 3 |
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE RankNTypes #-}
module Test.Integration.Framework.DSL
(
-- * Scenario
scenario
, xscenario
, pendingWith
, Scenarios
, Context(..)
-- * Steps
, Setup(..)
, setup
, request
, request_
, successfulRequest
, unsafeRequest
, verify
-- * Requests (Only API types)
, NewAddress(..)
, NewWallet (..)
, NewAccount (..)
, PasswordUpdate (..)
, Payment (..)
, Redemption (..)
, WalletUpdate(..)
, ShieldedRedemptionCode (..)
, FilterOperations(..)
, SortOperations(..)
, WalletOperation(..)
, AssuranceLevel(..)
, DestinationChoice(..)
, defaultAccountId
, defaultAssuranceLevel
, defaultDistribution
, customDistribution
, defaultGroupingPolicy
, defaultPage
, defaultPerPage
, defaultSetup
, defaultSource
, defaultSpendingPassword
, defaultWalletName
, mkSpendingPassword
, noRedemptionMnemonic
, noSpendingPassword
-- * Expectations
, WalletError(..)
, ErrNotEnoughMoney(..)
, TransactionStatus(..)
, expectAddressInIndexOf
, expectListSizeEqual
, expectListItemFieldEqual
, expectEqual
, expectError
, expectFieldEqual
, expectFieldDiffer
, expectJSONError
, expectSuccess
, expectTxInHistoryOf
, expectTxStatusEventually
, expectTxStatusNever
, expectWalletError
, expectWalletEventuallyRestored
, expectWalletUTxO
-- * Helpers
, ($-)
, (</>)
, (!!)
, addresses
, walAddresses
, amount
, assuranceLevel
, backupPhrase
, failures
, initialCoins
, mnemonicWords
, spendingPassword
, totalSuccess
, rawPassword
, address
, wallet
, wallets
, walletId
, walletName
, spendingPasswordLastUpdate
, json
, hasSpendingPassword
, mkAddress
, mkBackupPhrase
) where
import Universum hiding (getArgs, second)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Crypto.Hash (hash)
import Crypto.Hash.Algorithms (Blake2b_256)
import Data.Aeson.QQ (aesonQQ)
import qualified Data.ByteArray as ByteArray
import qualified Data.Foldable as F
import Data.Generics.Internal.VL.Lens (lens)
import Data.Generics.Product.Fields (field)
import Data.Generics.Product.Typed (HasType, typed)
import Data.List ((!!))
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Language.Haskell.TH.Quote (QuasiQuoter)
import Test.Hspec.Core.Spec (SpecM, it, xit)
import qualified Test.Hspec.Core.Spec as H
import Test.Hspec.Expectations.Lifted
import Test.QuickCheck (arbitrary, generate)
import Web.HttpApiData (ToHttpApiData (..))
import Cardano.Mnemonic (mkMnemonic, mnemonicToSeed)
import Cardano.Wallet.API.Request.Filter (FilterOperations (..))
import Cardano.Wallet.API.Request.Pagination (Page, PerPage)
import Cardano.Wallet.API.Request.Sort (SortOperations (..))
import Cardano.Wallet.API.Response (JSONValidationError (..))
import Cardano.Wallet.API.V1.Types
import Cardano.Wallet.Client.Http (BaseUrl, ClientError (..), Manager,
WalletClient)
import qualified Cardano.Wallet.Client.Http as Client
import Pos.Chain.Txp (TxIn (..), TxOut (..), TxOutAux (..))
import Pos.Core (Coin, IsBootstrapEraAddr (..), deriveLvl2KeyPair,
mkCoin, unsafeGetCoin)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (ShouldCheckPassphrase (..),
safeDeterministicKeyGen)
import Test.Integration.Framework.Request (HasHttpClient, request,
request_, successfulRequest, unsafeRequest, ($-))
import Test.Integration.Framework.Scenario (Scenario)
--
-- SCENARIO
--
-- Prior to starting integration tests, we setup a global context
-- and "prepare" a few faucet wallets which all contains some funds.
-- This helps speed up testing and isolate them.
data Context = Context
{ _faucets
:: [FilePath]
-- Already funded faucet wallets
, _client
:: WalletClient IO
-- A handle to the underlying wallet backend server
, _manager
:: (BaseUrl, Manager)
-- The underlying BaseUrl and Manager used by the Wallet Client
} deriving (Generic)
-- | Just a type-alias to 'SpecM', like 'scenario'. Ultimately, everything is
-- made in such way that we can use normal (albeit lifted) HSpec functions and
-- utilities if needed (and rely on its CLI as well when needed).
type Scenarios ctx = SpecM (MVar ctx) ()
-- | Just a slightly-specialized alias for 'it' to help lil'GHC. Also, makes
-- sure the wallet has been cleared out completely before running the scenario.
scenario
:: String
-> Scenario Context IO ()
-> Scenarios Context
scenario title spec = it title (successfulRequest Client.resetWalletState >> spec)
xscenario
:: String
-> Scenario Context IO ()
-> Scenarios Context
xscenario = xit
-- | Lifted version of `H.pendingWith` allowing for temporarily skipping
-- scenarios from execution with a reason, like:
--
-- scenario title $ do
-- pendingWith "This test fails due to bug #213"
-- test
pendingWith
:: (MonadIO m)
=> String
-> m ()
pendingWith = liftIO . H.pendingWith
--
-- TYPES
--
data DestinationChoice
= RandomDestination
| LockedDestination
deriving (Show, Generic)
newtype RawPassword = RawPassword { getRawPassword :: Text }
deriving stock (Show, Generic)
deriving newtype (Monoid, Semigroup)
instance IsString RawPassword where
fromString = RawPassword . T.pack
--
-- STEPS
--
data Setup = Setup
{ _initialCoins
:: [Coin]
, _walletName
:: Text
, _assuranceLevel
:: AssuranceLevel
, _mnemonicWords
:: [Text]
, _rawPassword
:: RawPassword
} deriving (Show, Generic)
data Fixture = Fixture
{ _wallet
:: Wallet
, _destinations
:: NonEmpty Address
, _backupPhrase
:: BackupPhrase
, _spendingPassword
:: SpendingPassword
} deriving (Show, Generic)
-- | Setup a wallet with the given parameters.
setup
:: Setup
-> Scenario Context IO Fixture
setup args = do
phrase <- if null (args ^. mnemonicWords)
then liftIO $ generate arbitrary
else mkBackupPhrase (args ^. mnemonicWords)
let password = mkPassword (args ^. rawPassword)
wal <- setupWallet args phrase
addrs <- forM (RandomDestination :| []) setupDestination
return $ Fixture wal addrs phrase password
-- | Apply 'a' to all actions in sequence
verify :: (Monad m) => a -> [a -> m ()] -> m ()
verify a = mapM_ (a &)
--
-- DEFAULT VALUES
--
defaultAccountId :: AccountIndex
defaultAccountId = minBound
defaultAssuranceLevel :: AssuranceLevel
defaultAssuranceLevel = NormalAssurance
defaultDistribution
:: HasType (NonEmpty Address) s
=> Word64
-> s
-> NonEmpty PaymentDistribution
defaultDistribution c s = pure $
PaymentDistribution (V1 $ head $ s ^. typed) (V1 $ mkCoin c)
customDistribution
:: NonEmpty (Account, Word64)
-> NonEmpty PaymentDistribution
customDistribution payees =
let recepientWalAddresses =
NonEmpty.fromList
$ map (view walAddresses)
$ concatMap (view addresses . fst)
$ payees
in NonEmpty.zipWith
PaymentDistribution
recepientWalAddresses
(map ((\coin -> V1 $ mkCoin coin) . snd) payees)
defaultGroupingPolicy :: Maybe (V1 InputSelectionPolicy)
defaultGroupingPolicy = Nothing
defaultPage :: Maybe Page
defaultPage = Nothing
defaultPerPage :: Maybe PerPage
defaultPerPage = Nothing
defaultSetup :: Setup
defaultSetup = Setup
{ _initialCoins = []
, _walletName = defaultWalletName
, _assuranceLevel = defaultAssuranceLevel
, _mnemonicWords = []
, _rawPassword = mempty
}
defaultSource
:: HasType Wallet s
=> s
-> PaymentSource
defaultSource s =
PaymentSource (s ^. wallet . walletId) defaultAccountId
defaultSpendingPassword :: SpendingPassword
defaultSpendingPassword = mempty
defaultWalletName :: Text
defaultWalletName = "Fixture Wallet"
noRedemptionMnemonic :: Maybe RedemptionMnemonic
noRedemptionMnemonic = Nothing
noSpendingPassword :: Maybe SpendingPassword
noSpendingPassword = Nothing
--
-- HELPERS
--
json :: QuasiQuoter
json = aesonQQ
infixr 5 </>
(</>) :: ToHttpApiData a => Text -> a -> Text
base </> next = mconcat [base, "/", toQueryParam next]
address
:: HasType (V1 Address) s
=> Lens' s (V1 Address)
address = typed
amount
:: HasType (V1 Coin) s
=> Lens' s Word64
amount =
lens _get _set
where
_get :: HasType (V1 Coin) s => s -> Word64
_get = unsafeGetCoin . unV1 . view typed
_set :: HasType (V1 Coin) s => (s, Word64) -> s
_set (s, v) = set typed (V1 $ mkCoin v) s
assuranceLevel :: HasType AssuranceLevel s => Lens' s AssuranceLevel
assuranceLevel = typed
backupPhrase :: HasType BackupPhrase s => Lens' s BackupPhrase
backupPhrase = typed
failures :: Lens' (BatchImportResult a) [a]
failures = field @"aimFailures"
faucets :: HasType [FilePath] s => Lens' s [FilePath]
faucets = typed
initialCoins
:: HasType [Coin] s
=> Lens' s [Word64]
initialCoins =
lens _get _set
where
_get :: HasType [Coin] s => s -> [Word64]
_get = map unsafeGetCoin . view typed
_set :: HasType [Coin] s => (s, [Word64]) -> s
_set (s, v) = set typed (map mkCoin v) s
mnemonicWords :: HasType [Text] s => Lens' s [Text]
mnemonicWords = typed
hasSpendingPassword :: HasType Bool s => Lens' s Bool
hasSpendingPassword = typed
rawPassword :: HasType RawPassword s => Lens' s RawPassword
rawPassword = typed
spendingPassword :: HasType SpendingPassword s => Lens' s SpendingPassword
spendingPassword = typed
totalSuccess :: Lens' (BatchImportResult a) Natural
totalSuccess = field @"aimTotalSuccess"
wallet :: HasType Wallet s => Lens' s Wallet
wallet = typed
wallets :: HasType [Wallet] s => Lens' s [Wallet]
wallets = typed
walletId :: HasType WalletId s => Lens' s WalletId
walletId = typed
walletName :: HasType Text s => Lens' s Text
walletName = typed
spendingPasswordLastUpdate :: Lens' Wallet (V1 Timestamp)
spendingPasswordLastUpdate = field @"walSpendingPasswordLastUpdate"
addresses :: HasType [WalletAddress] s => Lens' s [WalletAddress]
addresses = typed
walAddresses :: HasType (V1 Address) s => Lens' s (V1 Address)
walAddresses = typed
--
-- EXPECTATIONS
--
-- | Expects data list returned by the API to be of certain length
expectListSizeEqual
:: (MonadIO m, MonadFail m, Foldable xs)
=> Int
-> Either ClientError (xs a)
-> m ()
expectListSizeEqual l = \case
Left e -> wantedSuccessButError e
Right xs -> length (F.toList xs) `shouldBe` l
-- | Expects that returned data list's particular item field matches the expected value
--
-- e.g.
-- verify response
-- [ expectDataListItemFieldEqual 0 walletName "first"
-- , expectDataListItemFieldEqual 1 walletName "second"
-- ]
expectListItemFieldEqual
:: (MonadIO m, MonadFail m, Show a, Eq a)
=> Int
-> Lens' s a
-> a
-> Either ClientError [s]
-> m ()
expectListItemFieldEqual i getter a = \case
Left e -> wantedSuccessButError e
Right s
| length s > i -> expectFieldEqual getter a (Right (s !! i))
| otherwise -> fail $
"expectListItemFieldEqual: trying to access the #" <> show i <>
" element from a list but there's none! "
-- | The type signature is more scary than it seems. This drills into a given
-- `a` type through the provided lens and sees whether field matches.
--
-- e.g.
-- do
-- expectFieldEqual #walAssuranceLevel AssuranceStrict response
-- expectFieldEqual #walName "My Wallet" response
expectFieldEqual
:: (MonadIO m, MonadFail m, Show a, Eq a)
=> Lens' s a
-> a
-> Either ClientError s
-> m ()
expectFieldEqual getter a = \case
Left e -> wantedSuccessButError e
Right s -> view getter s `shouldBe` a
-- | The opposite to 'expectFieldEqual'.
expectFieldDiffer
:: (MonadIO m, MonadFail m, Show a, Eq a)
=> Lens' s a
-> a
-> Either ClientError s
-> m ()
expectFieldDiffer getter a = \case
Left e -> wantedSuccessButError e
Right s -> view getter s `shouldNotBe` a
-- | Expects entire equality of two types
expectEqual
:: (MonadIO m, MonadFail m, Show a, Eq a)
=> a
-> Either ClientError a
-> m ()
expectEqual =
expectFieldEqual id
-- | Expect an errored response, without any further assumptions
expectError
:: (MonadIO m, MonadFail m, Show a)
=> Either ClientError a
-> m ()
expectError = \case
Left _ -> return ()
Right a -> wantedErrorButSuccess a
-- | Expect a successful response, without any further assumptions
expectSuccess
:: (MonadIO m, MonadFail m)
=> Either ClientError a
-> m ()
expectSuccess = \case
Left e -> wantedSuccessButError e
Right _ -> return ()
-- | Expect a transaction to be part of a wallet history.
expectTxInHistoryOf
:: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx)
=> Wallet
-> Either ClientError Transaction
-> m ()
expectTxInHistoryOf w = \case
Left e -> wantedSuccessButError e
Right txn -> tryNextPage (on (==) txId txn) 1
where
tryNextPage predicate i = do
txns <- successfulRequest $ Client.getTransactionIndexFilterSorts
$- Just (walId w)
$- Nothing
$- Nothing
$- Just (fromInteger i)
$- Just 50
$- NoFilters
$- NoSorts
when (null txns) $
fail "expectTxInHistoryOf: couldn't find transaction in history"
case find predicate txns of
Nothing -> tryNextPage predicate (i + 1)
Just _ -> return ()
-- | Expect an address to be part of the global index
expectAddressInIndexOf
:: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx)
=> Either ClientError WalletAddress
-> m ()
expectAddressInIndexOf = \case
Left e -> wantedSuccessButError e
Right addr -> tryNextPage ((==) addr) 1
where
tryNextPage predicate i = do
addrs <- successfulRequest $ Client.getAddressIndexPaginated
$- Just (fromInteger i)
$- Just 50
when (null addrs) $
fail "expectAddressInIndexOf: couldn't find address in history"
case find predicate addrs of
Nothing -> tryNextPage predicate (i + 1)
Just _ -> return ()
-- | Wait for a transaction to reach one of the given status. Fails after 60
-- seconds if not.
expectTxStatusEventually
:: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx)
=> [TransactionStatus]
-> Either ClientError Transaction
-> m ()
expectTxStatusEventually statuses = \case
Left e -> wantedSuccessButError e
Right txn -> do
result <- ask >>= \ctx -> timeout (120 * second) (waitForTxStatus ctx statuses txn)
case result of
Nothing -> fail "expectTxStatusEventually: waited too long for statuses."
Just _ -> return ()
-- | Checks that a transacton "never" reaches one of the given status. Never
-- really means 60 seconds, you know...
expectTxStatusNever
:: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx)
=> [TransactionStatus]
-> Either ClientError Transaction
-> m ()
expectTxStatusNever statuses = \case
Left e -> wantedSuccessButError e
Right txn -> do
result <- ask >>= \ctx -> timeout (120 * second) (waitForTxStatus ctx statuses txn)
case result of
Nothing -> return ()
Just _ -> fail "expectTxStatusNever: reached one of the provided statuses."
-- | Wait until a wallet is restored, up to a certain point.
expectWalletEventuallyRestored
:: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx)
=> Either ClientError Wallet
-> m ()
expectWalletEventuallyRestored = \case
Left e -> wantedSuccessButError e
Right w -> do
result <- ask >>= \ctx -> timeout (120 * second) (waitForRestored ctx w)
case result of
Nothing -> fail "expectWalletEventuallyRestored: waited too long for restoration."
Just _ -> return ()
expectWalletError
:: (MonadIO m, MonadFail m, Show a)
=> WalletError
-> Either ClientError a
-> m ()
expectWalletError e' = \case
Right a -> wantedErrorButSuccess a
Left e -> e `shouldBe` (ClientWalletError e')
-- | Verifies that the response is errored from a failed JSON validation
-- matching part of the given message.
expectJSONError
:: (MonadIO m, MonadFail m, Show a)
=> String
-> Either ClientError a
-> m ()
expectJSONError excerpt = \case
Right a -> wantedErrorButSuccess a
Left (ClientJSONError (JSONValidationFailed msg)) ->
T.unpack msg `shouldContain` excerpt
Left e ->
fail $ "expectJSONError: got something else than a JSON validation failure: " <> show e
expectWalletUTxO
:: (MonadIO m, MonadFail m)
=> [Word64]
-> Either ClientError UtxoStatistics
-> m ()
expectWalletUTxO coins = \case
Left e -> wantedSuccessButError e
Right stats -> do
addr <- liftIO $ generate arbitrary
let constructUtxoEntry input coin =
( TxInUnknown input "arbitrary input"
, TxOutAux (TxOut addr (mkCoin coin))
)
let utxo = Map.fromList $ zipWith constructUtxoEntry [0..] coins
computeUtxoStatistics log10 [utxo] `shouldBe` stats
--
-- INTERNALS
--
wantedSuccessButError
:: (MonadFail m, Show e)
=> e
-> m void
wantedSuccessButError =
fail . ("expected a successful response but got an error: " <>) . show
wantedErrorButSuccess
:: (MonadFail m, Show a)
=> a
-> m void
wantedErrorButSuccess =
fail . ("expected an error but got a successful response: " <>) . show
timeout :: (MonadIO m) => Int -> IO a -> m (Maybe a)
timeout maxWaitingTime action = liftIO $ do
race (threadDelay maxWaitingTime) action >>= \case
Left _ -> return Nothing
Right a -> return (Just a)
second :: Int
second = 1000000
-- | Wait until the given transaction reaches the given status. Potentially
-- loop ad infinitum; Caller is expected to cancel the thread at some point.
waitForTxStatus
:: HasHttpClient ctx
=> ctx
-> [TransactionStatus]
-> Transaction
-> IO ()
waitForTxStatus ctx statuses txn = do
-- NOTE
-- A bit tricky here, we can't just fire async operation on anything else
-- but plain `IO`. Hence the explicit context passing here.
txns <- flip runReaderT ctx $ successfulRequest $ Client.getTransactionIndex
$- Nothing
$- Nothing
$- Nothing
let tx = find (on (==) txId txn) txns
if ((fmap txStatus tx) `elem` (fmap Just statuses)) then
return ()
else
threadDelay (5 * second) >> waitForTxStatus ctx statuses txn
-- | Wait until the given wallet is restored.
waitForRestored
:: HasHttpClient ctx
=> ctx
-> Wallet
-> IO ()
waitForRestored ctx w = do
response <- flip runReaderT ctx $ successfulRequest $ Client.getWallet
$- w ^. walletId
case walSyncState response of
Synced -> return ()
_ -> threadDelay (5 * second) >> waitForRestored ctx w
-- | Make a backup phrase from a raw list of words.
mkBackupPhrase
:: (MonadIO m, MonadFail m)
=> [Text]
-> m BackupPhrase
mkBackupPhrase ws = either onError onSuccess (mkMnemonic ws)
where
onError err =
fail $ "Invalid BackupPhrase provided: " <> show ws <> ". We expect 12\
\ valid english mnemonic words but the following error has occured:"
<> show err
onSuccess =
return . BackupPhrase
-- | Create a Base16-encoded spending password from raw text
mkPassword
:: RawPassword
-> SpendingPassword
mkPassword (RawPassword txt)
| null txt = mempty
| otherwise = txt
& T.encodeUtf8
& hash @ByteString @Blake2b_256
& ByteArray.convert
& V1
mkAddress
:: (MonadIO m, MonadFail m)
=> BackupPhrase
-> Word32
-> m (V1 Address)
mkAddress (BackupPhrase mnemonic) ix = do
let (_, esk) = safeDeterministicKeyGen
(mnemonicToSeed mnemonic)
mempty
let maddr = fst <$> deriveLvl2KeyPair
NetworkMainOrStage
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase False)
mempty
esk
(getAccIndex minBound)
ix
case maddr of
Nothing ->
fail "The impossible happened: failed to generate a\
\ random address. This can only happened if you\
\ provided a derivation index that is out-of-bound!"
Just addr ->
return (V1 addr)
-- | Execute the given setup action with using the next faucet wallet. It fails
-- hard if there's no more faucet wallet available.
withNextFaucet
:: (Wallet -> Scenario Context IO c)
-> Scenario Context IO c
withNextFaucet actionWithFaucet = do
ctx <- get
when (null $ ctx ^. faucets) $ fail $
"\nFailed to setup new scenario: there's no more available faucet wallets!\
\\nWe import a faucet wallet for each scenario but only have a limited\
\ number of them. This can be modified directly in the configuration file,\
\ by default in: \n\n\ttest/integration/configuration.yaml\
\\n\ntry increasing the number of available 'poors' wallets\
\\n\nspec: &default_core_genesis_spec\
\\n\tinitializer:\
\\n\t\ttestBalance:\
\\n\t\t\tpoors: ???\n"
let acquireFaucet = do
let (key:rest) = ctx ^. faucets
put (ctx & faucets .~ rest)
successfulRequest $ Client.importWallet $- WalletImport Nothing key
let releaseFaucet faucet = do
successfulRequest (Client.deleteWallet $- walId faucet)
bracket acquireFaucet releaseFaucet actionWithFaucet
-- | Setup a given wallet and pre-fill it with given coins.
setupWallet
:: Setup
-> BackupPhrase
-> Scenario Context IO Wallet
setupWallet args phrase = do
wal <- successfulRequest $ Client.postWallet $- NewWallet
phrase
Nothing
(args ^. assuranceLevel)
(args ^. walletName)
CreateWallet
unless (null $ args ^. initialCoins) $ withNextFaucet $ \faucet -> do
let paymentSource = PaymentSource (walId faucet) minBound
let paymentDist (addr, coin) = pure $ PaymentDistribution (addrId addr) (V1 $ mkCoin coin)
forM_ (args ^. initialCoins) $ \coin -> do
-- NOTE
-- Making payments to a different address each time to cope with
-- grouping policy. That's actually a behavior we might want to
-- test in the future. So, we'll need to do something smarter here.
addr <- successfulRequest $ Client.postAddress $- NewAddress
Nothing
minBound
(walId wal)
txn <- request $ Client.postTransaction $- Payment
paymentSource
(paymentDist (addr, coin))
Nothing
Nothing
expectTxStatusEventually [InNewestBlocks, Persisted] txn
return wal
-- | Generate some destinations for payments.
--
-- - RandomDestination generates fake addresses going nowhere (hopefully :) ...)
-- - LockedDestination generates addresses that points to an asset-locked wallet
setupDestination
:: DestinationChoice
-> Scenario Context IO Address
setupDestination = \case
RandomDestination -> do
bp <- liftIO (generate arbitrary)
unV1 <$> mkAddress bp 1
LockedDestination ->
fail "Asset-locked destination aren't yet implemented. This\
\ requires slightly more work than it seems and will be\
\ implemented later."
| input-output-hk/pos-haskell-prototype | wallet/test/integration/Test/Integration/Framework/DSL.hs | mit | 24,605 | 0 | 20 | 6,487 | 5,890 | 3,134 | 2,756 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Emacs
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module aims at a mode that should be (mostly) intuitive to
-- emacs users, but mapping things into the Yi world when convenient.
-- Hence, do not go into the trouble of trying 100% emulation. For
-- example, @M-x@ gives access to Yi (Haskell) functions, with their
-- native names.
module Yi.Keymap.Emacs ( keymap
, mkKeymapSet
, defKeymap
, ModeMap(..)
, eKeymap
, completionCaseSensitive
) where
import Control.Applicative (Alternative ((<|>), empty, some))
import Control.Monad (replicateM_, unless, void)
import Control.Monad.State (gets)
import Data.Char (digitToInt, isDigit)
import Data.Maybe (fromMaybe)
import Data.Prototype (Proto (Proto), extractValue)
import Data.Text ()
import Lens.Micro.Platform ((.=), makeLenses, (%=))
import Yi.Buffer
import Yi.Command (shellCommandE)
import Yi.Core
import Yi.Dired (dired)
import Yi.Editor
import Yi.File (fwriteE, fwriteToE)
import Yi.Keymap (Keymap, KeymapSet, YiAction (..), YiM, modelessKeymapSet, write)
import Yi.Keymap.Emacs.KillRing
import Yi.Keymap.Emacs.Utils
import Yi.Keymap.Keys
import Yi.MiniBuffer
import Yi.Misc (adjIndent, placeMark, selectAll)
import Yi.Mode.Buffers (listBuffers)
import Yi.Rectangle
import Yi.Search (isearchFinishWithE, resetRegexE, getRegexE)
import Yi.TextCompletion (resetComplete, wordComplete')
data ModeMap = ModeMap { _eKeymap :: Keymap
, _completionCaseSensitive :: Bool
}
$(makeLenses ''ModeMap)
keymap :: KeymapSet
keymap = mkKeymapSet defKeymap
mkKeymapSet :: Proto ModeMap -> KeymapSet
mkKeymapSet = modelessKeymapSet . _eKeymap . extractValue
defKeymap :: Proto ModeMap
defKeymap = Proto template
where
template self = ModeMap { _eKeymap = emacsKeymap
, _completionCaseSensitive = False }
where
emacsKeymap :: Keymap
emacsKeymap = selfInsertKeymap Nothing isDigit <|> completionKm (_completionCaseSensitive self) <|>
do univArg <- readUniversalArg
selfInsertKeymap univArg (not . isDigit) <|> emacsKeys univArg
selfInsertKeymap :: Maybe Int -> (Char -> Bool) -> Keymap
selfInsertKeymap univArg condition = do
c <- printableChar
unless (condition c) empty
let n = argToInt univArg
write (replicateM_ n (insertB c))
completionKm :: Bool -> Keymap
completionKm caseSensitive = do void $ some (meta (char '/') ?>>! wordComplete' caseSensitive)
deprioritize
write resetComplete
-- 'adjustPriority' is there to lift the ambiguity between "continuing" completion
-- and resetting it (restarting at the 1st completion).
deleteB' :: BufferM ()
deleteB' = deleteN 1
-- | Wrapper around 'moveE' which also cancels incremental search. See
-- issue #499 for details.
moveE :: TextUnit -> Direction -> EditorM ()
moveE u d = do
getRegexE >>= \case
-- let's check whether searching is in progress (issues #738, #610)
Nothing -> return ()
_ -> isearchFinishWithE resetRegexE
withCurrentBuffer (moveB u d)
emacsKeys :: Maybe Int -> Keymap
emacsKeys univArg =
choice [ -- First all the special key bindings
spec KTab ?>>! adjIndent IncreaseCycle
, shift (spec KTab) ?>>! adjIndent DecreaseCycle
, spec KEnter ?>>! repeatingArg newlineB
, spec KDel ?>>! deleteRegionOr deleteForward
, spec KBS ?>>! deleteRegionOr deleteBack
, spec KHome ?>>! repeatingArg moveToSol
, spec KEnd ?>>! repeatingArg moveToEol
, spec KLeft ?>>! repeatingArg $ moveE Character Backward
, spec KRight ?>>! repeatingArg $ moveE Character Forward
, spec KUp ?>>! repeatingArg $ moveE VLine Backward
, spec KDown ?>>! repeatingArg $ moveE VLine Forward
, spec KPageDown ?>>! repeatingArg downScreenB
, spec KPageUp ?>>! repeatingArg upScreenB
, shift (spec KUp) ?>>! repeatingArg (scrollB (-1))
, shift (spec KDown) ?>>! repeatingArg (scrollB 1)
-- All the keybindings of the form 'Ctrl + special key'
, ctrl (spec KLeft) ?>>! repeatingArg prevWordB
, ctrl (spec KRight) ?>>! repeatingArg nextWordB
, ctrl (spec KHome) ?>>! repeatingArg topB
, ctrl (spec KEnd) ?>>! repeatingArg botB
, ctrl (spec KUp) ?>>! repeatingArg (prevNParagraphs 1)
, ctrl (spec KDown) ?>>! repeatingArg (nextNParagraphs 1)
-- All the keybindings of the form "C-c" where 'c' is some character
, ctrlCh '@' ?>>! placeMark
, ctrlCh ' ' ?>>! placeMark
, ctrlCh '/' ?>>! repeatingArg undoB
, ctrlCh '_' ?>>! repeatingArg undoB
, ctrlCh 'a' ?>>! repeatingArg (maybeMoveB Line Backward)
, ctrlCh 'b' ?>>! repeatingArg $ moveE Character Backward
, ctrlCh 'd' ?>>! deleteForward
, ctrlCh 'e' ?>>! repeatingArg (maybeMoveB Line Forward)
, ctrlCh 'f' ?>>! repeatingArg $ moveE Character Forward
, ctrlCh 'g' ?>>! setVisibleSelection False
, ctrlCh 'h' ?>> char 'b' ?>>! acceptedInputsOtherWindow
, ctrlCh 'i' ?>>! adjIndent IncreaseOnly
, ctrlCh 'j' ?>>! newlineAndIndentB
, ctrlCh 'k' ?>>! killLine univArg
, ctrlCh 'l' ?>>! (withCurrentBuffer scrollToCursorB >> userForceRefresh)
, ctrlCh 'm' ?>>! repeatingArg (insertB '\n')
, ctrlCh 'n' ?>>! repeatingArg (moveE VLine Forward)
, ctrlCh 'o' ?>>! repeatingArg (insertB '\n' >> leftB)
, ctrlCh 'p' ?>>! repeatingArg (moveE VLine Backward)
, ctrlCh 'q' ?>> insertNextC univArg
, ctrlCh 'r' ?>> isearchKeymap Backward
, ctrlCh 's' ?>> isearchKeymap Forward
, ctrlCh 't' ?>>! repeatingArg swapB
, ctrlCh 'v' ?>>! scrollDownE univArg
, ctrlCh 'w' ?>>! killRegion
, ctrlCh 'y' ?>>! yank
, ctrlCh 'z' ?>>! suspendEditor
, ctrlCh '+' ?>>! repeatingArg (increaseFontSize 1)
, ctrlCh '-' ?>>! repeatingArg (decreaseFontSize 1)
-- All the keybindings of the form "C-M-c" where 'c' is some character
, ctrl (metaCh 'w') ?>>! appendNextKillE
, ctrl (metaCh ' ') ?>>! layoutManagersNextE
, ctrl (metaCh ',') ?>>! layoutManagerNextVariantE
, ctrl (metaCh '.') ?>>! layoutManagerPreviousVariantE
, ctrl (metaCh 'j') ?>>! nextWinE
, ctrl (metaCh 'k') ?>>! prevWinE
, ctrl (meta $ spec KEnter) ?>>! swapWinWithFirstE
-- All the keybindings of the form "S-C-M-c" where 'c' is some key
, shift (ctrl $ metaCh 'j') ?>>! moveWinNextE
, shift (ctrl $ metaCh 'k') ?>>! moveWinPrevE
, shift (ctrl $ meta $ spec KEnter) ?>>! pushWinToFirstE
, Event (KASCII ' ') [MShift,MCtrl,MMeta] ?>>! layoutManagersPreviousE
-- All the key-bindings which are preceded by a 'C-x'
, ctrlCh 'x' ?>> ctrlX
, ctrlCh 'c' ?>> ctrlC
-- All The key-bindings of the form M-c where 'c' is some character.
, metaCh ' ' ?>>! justOneSep univArg
, metaCh 'v' ?>>! scrollUpE univArg
, metaCh '!' ?>>! shellCommandE
, metaCh '<' ?>>! repeatingArg topB
, metaCh '>' ?>>! repeatingArg botB
, metaCh '%' ?>>! queryReplaceE
, metaCh '^' ?>>! joinLinesE univArg
, metaCh ';' ?>>! commentRegion
, metaCh 'a' ?>>! repeatingArg (moveE unitSentence Backward)
, metaCh 'b' ?>>! repeatingArg prevWordB
, metaCh 'c' ?>>! repeatingArg capitaliseWordB
, metaCh 'd' ?>>! repeatingArg killWordB
, metaCh 'e' ?>>! repeatingArg (moveE unitSentence Forward)
, metaCh 'f' ?>>! repeatingArg nextWordB
, metaCh 'h' ?>>! repeatingArg (selectNParagraphs 1)
, metaCh 'k' ?>>! repeatingArg (deleteB unitSentence Forward)
, metaCh 'l' ?>>! repeatingArg lowercaseWordB
, metaCh 'm' ?>>! firstNonSpaceB
, metaCh 'q' ?>>! withSyntax modePrettify
, metaCh 'r' ?>>! repeatingArg moveToMTB
, metaCh 'u' ?>>! repeatingArg uppercaseWordB
, metaCh 't' ?>>! repeatingArg (transposeB unitWord Forward)
, metaCh 'w' ?>>! killRingSave
, metaCh 'x' ?>>! executeExtendedCommandE
, metaCh 'y' ?>>! yankPopE
, metaCh '.' ?>>! promptTag
, metaCh '{' ?>>! repeatingArg (prevNParagraphs 1)
, metaCh '}' ?>>! repeatingArg (nextNParagraphs 1)
, metaCh '=' ?>>! countWordsRegion
, metaCh '\\' ?>>! deleteHorizontalSpaceB univArg
, metaCh '@' ?>>! repeatingArg markWord
-- Other meta key-bindings
, meta (spec KBS) ?>>! repeatingArg bkillWordB
, metaCh 'g' ?>>
optMod meta (char 'g') >>! (gotoLn . fromDoc :: Int ::: LineNumber -> BufferM Int)
]
where
-- inserting the empty string prevents the deletion from appearing in the killring
-- which is a good thing when we are deleting individuals characters. See
-- http://code.google.com/p/yi-editor/issues/detail?id=212
blockKillring = insertN ""
withUnivArg :: YiAction (m ()) () => (Maybe Int -> m ()) -> YiM ()
withUnivArg cmd = runAction $ makeAction (cmd univArg)
repeatingArg :: (Monad m, YiAction (m ()) ()) => m () -> YiM ()
repeatingArg f = withIntArg $ \n -> replicateM_ n f
withIntArg :: YiAction (m ()) () => (Int -> m ()) -> YiM ()
withIntArg cmd = withUnivArg $ \arg -> cmd (fromMaybe 1 arg)
deleteBack :: YiM ()
deleteBack = repeatingArg $ blockKillring >> bdeleteB
deleteForward :: YiM ()
deleteForward = repeatingArg $ blockKillring >> deleteB'
-- Deletes current region if any, otherwise executes the given
-- action.
deleteRegionOr :: (Show a, YiAction (m a) a) => m a -> YiM ()
deleteRegionOr f = do
b <- gets currentBuffer
r <- withGivenBuffer b getSelectRegionB
if regionSize r == 0
then runAction $ makeAction f
else withGivenBuffer b $ deleteRegionB r
ctrlC = choice [ ctrlCh 'c' ?>>! commentRegion ]
rectangleFunctions = choice [ char 'o' ?>>! openRectangle
, char 't' ?>>! stringRectangle
, char 'k' ?>>! killRectangle
, char 'y' ?>>! yankRectangle
]
tabFunctions :: Keymap
tabFunctions = choice [ optMod ctrl (char 'n') >>! nextTabE
, optMod ctrl (char 'p') >>! previousTabE
, optMod ctrl (char 't') >>! newTabE
, optMod ctrl (char 'e') >>! findFileNewTab
, optMod ctrl (char 'd') >>! deleteTabE
, charOf id '0' '9' >>=! moveTabE . Just . digitToInt
]
-- These keybindings are all preceded by a 'C-x' so for example to
-- quit the editor we do a 'C-x C-c'
ctrlX = choice [ ctrlCh 'o' ?>>! deleteBlankLinesB
, char '0' ?>>! closeWindowEmacs
, char '1' ?>>! closeOtherE
, char '2' ?>>! splitE
, char 'h' ?>>! selectAll
, char 's' ?>>! askSaveEditor
, ctrlCh 'b' ?>>! listBuffers
, ctrlCh 'c' ?>>! askQuitEditor
, ctrlCh 'f' ?>>! findFile
, ctrlCh 'r' ?>>! findFileReadOnly
, ctrlCh 'q' ?>>!
((withCurrentBuffer (readOnlyA %= not)) :: EditorM ())
, ctrlCh 's' ?>>! fwriteE
, ctrlCh 'w' ?>>! promptFile "Write file:" (void . fwriteToE)
, ctrlCh 'x' ?>>! (exchangePointAndMarkB >>
highlightSelectionA .= True)
, char 'b' ?>>! switchBufferE
, char 'd' ?>>! dired
, char 'e' ?>>
char 'e' ?>>! evalRegionE
, char 'o' ?>>! nextWinE
, char 'k' ?>>! killBufferE
, char 'r' ?>> rectangleFunctions
, char 'u' ?>>! repeatingArg undoB
, optMod ctrl (char 't') >> tabFunctions
]
| noughtmare/yi | yi-keymap-emacs/src/Yi/Keymap/Emacs.hs | gpl-2.0 | 13,706 | 0 | 15 | 4,828 | 3,167 | 1,609 | 1,558 | -1 | -1 |
{-
Copyright (C) 2007-2010 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.TeXMath
Copyright : Copyright (C) 2007-2010 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of TeX math to a list of 'Pandoc' inline elements.
-}
module Text.Pandoc.Readers.TeXMath ( readTeXMath ) where
import Text.Pandoc.Definition
import Text.TeXMath.Types
import Text.TeXMath.Parser
-- | Converts a raw TeX math formula to a list of 'Pandoc' inlines.
-- Defaults to raw formula between @$@ characters if entire formula
-- can't be converted.
readTeXMath :: String -- ^ String to parse (assumes @'\n'@ line endings)
-> [Inline]
readTeXMath inp = case texMathToPandoc inp of
Left _ -> [Str ("$" ++ inp ++ "$")]
Right res -> res
texMathToPandoc :: String -> Either String [Inline]
texMathToPandoc inp = inp `seq`
case parseFormula inp of
Left err -> Left err
Right exps -> case expsToInlines exps of
Nothing -> Left "Formula too complex for [Inline]"
Just r -> Right r
expsToInlines :: [Exp] -> Maybe [Inline]
expsToInlines xs = do
res <- mapM expToInlines xs
return (concat res)
expToInlines :: Exp -> Maybe [Inline]
expToInlines (ENumber s) = Just [Str s]
expToInlines (EIdentifier s) = Just [Emph [Str s]]
expToInlines (EMathOperator s) = Just [Str s]
expToInlines (ESymbol t s) = Just $ addSpace t (Str s)
where addSpace Op x = [x, thinspace]
addSpace Bin x = [medspace, x, medspace]
addSpace Rel x = [widespace, x, widespace]
addSpace Pun x = [x, thinspace]
addSpace _ x = [x]
thinspace = Str "\x2006"
medspace = Str "\x2005"
widespace = Str "\x2004"
expToInlines (EStretchy x) = expToInlines x
expToInlines (EGrouped xs) = expsToInlines xs
expToInlines (ESpace _) = Just [Str " "] -- variable widths not supported
expToInlines (EBinary _ _ _) = Nothing
expToInlines (ESub x y) = do
x' <- expToInlines x
y' <- expToInlines y
return $ x' ++ [Subscript y']
expToInlines (ESuper x y) = do
x' <- expToInlines x
y' <- expToInlines y
return $ x' ++ [Superscript y']
expToInlines (ESubsup x y z) = do
x' <- expToInlines x
y' <- expToInlines y
z' <- expToInlines z
return $ x' ++ [Subscript y'] ++ [Superscript z']
expToInlines (EDown x y) = expToInlines (ESub x y)
expToInlines (EUp x y) = expToInlines (ESuper x y)
expToInlines (EDownup x y z) = expToInlines (ESubsup x y z)
expToInlines (EText "normal" x) = Just [Str x]
expToInlines (EText "bold" x) = Just [Strong [Str x]]
expToInlines (EText "monospace" x) = Just [Code nullAttr x]
expToInlines (EText "italic" x) = Just [Emph [Str x]]
expToInlines (EText _ x) = Just [Str x]
expToInlines (EOver (EGrouped [EIdentifier [c]]) (ESymbol Accent [accent])) =
case accent of
'\x203E' -> Just [Emph [Str [c,'\x0304']]] -- bar
'\x00B4' -> Just [Emph [Str [c,'\x0301']]] -- acute
'\x0060' -> Just [Emph [Str [c,'\x0300']]] -- grave
'\x02D8' -> Just [Emph [Str [c,'\x0306']]] -- breve
'\x02C7' -> Just [Emph [Str [c,'\x030C']]] -- check
'.' -> Just [Emph [Str [c,'\x0307']]] -- dot
'\x00B0' -> Just [Emph [Str [c,'\x030A']]] -- ring
'\x20D7' -> Just [Emph [Str [c,'\x20D7']]] -- arrow right
'\x20D6' -> Just [Emph [Str [c,'\x20D6']]] -- arrow left
'\x005E' -> Just [Emph [Str [c,'\x0302']]] -- hat
'\x0302' -> Just [Emph [Str [c,'\x0302']]] -- hat
'~' -> Just [Emph [Str [c,'\x0303']]] -- tilde
_ -> Nothing
expToInlines _ = Nothing
| Lythimus/lptv | sites/all/modules/jgm-pandoc-8be6cc2/src/Text/Pandoc/Readers/TeXMath.hs | gpl-2.0 | 4,486 | 0 | 13 | 1,104 | 1,343 | 680 | 663 | 74 | 17 |
module Rasa.Ext.Views
( viewports
-- * Working with Views
, View(..)
, viewable
, splitRule
, active
, scrollPos
, getViews
-- * View Structure
-- | Views are stored as a Tree, with 'Split's determining
-- the layout of each branch.
, Split(..)
, Dir(..)
, SplitRule(..)
, Window
, BiTree(..)
, BiTreeF(..)
-- * ProvidedApps
, A.rotate
, A.closeInactive
, A.focusViewLeft
, A.focusViewRight
, A.focusViewAbove
, A.focusViewBelow
, A.hSplit
, A.vSplit
, A.addSplit
, A.nextBuf
, A.prevBuf
, A.focusDo
, A.focusDo_
, A.focusedBufs
, A.isFocused
, A.scrollBy
-- * Creating Widgets
, Widgets
-- | Lenses for accessing parts of 'Widgets':
, topBar
, bottomBar
, leftBar
, rightBar
, HasWidgets(..)
-- ** Providing Widgets
-- | The following functions register a BufAction which yields some renderable;
-- On each render that renderable will be used as a top/bottom/left/right bar respectively.
, addTopBar
, addBottomBar
, addLeftBar
, addRightBar
-- * Provided Widgets
, enableLineNumbers
, disableLineNumbers
, toggleLineNumbers
, checkLineNumbers
, addTopStatus
, addBottomStatus
) where
import Rasa.Ext
import Rasa.Ext.Views.Internal.BiTree
import Rasa.Ext.Views.Internal.Views
import Rasa.Ext.Views.Internal.Widgets
import Rasa.Ext.Views.Internal.LineNumbers
import Rasa.Ext.Views.Internal.StatusBar
import Rasa.Ext.Views.Internal.Actions as A
-- | Main export from the views extension, add this to your rasa config.
viewports :: App ()
viewports = do
onBufAdded_ A.addSplit
lineNumbers
| ChrisPenner/rasa | rasa-ext-views/src/Rasa/Ext/Views.hs | gpl-3.0 | 1,615 | 0 | 8 | 337 | 297 | 198 | 99 | 57 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SWF.PollForActivityTask
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Used by workers to get an 'ActivityTask' from the specified activity 'taskList'.
-- This initiates a long poll, where the service holds the HTTP connection open
-- and responds as soon as a task becomes available. The maximum time the
-- service holds on to the request before responding is 60 seconds. If no task
-- is available within 60 seconds, the poll will return an empty result. An
-- empty result, in this context, means that an ActivityTask is returned, but
-- that the value of taskToken is an empty string. If a task is returned, the
-- worker should use its type to identify and process it correctly.
--
-- Workers should set their client side socket timeout to at least 70 seconds
-- (10 seconds higher than the maximum time service may hold the poll request). Access Control
--
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. Constrain the 'taskList.name' parameter by using a Condition
-- element with the 'swf:taskList.name' key to allow the action to access only
-- certain task lists. If the caller does not have sufficient permissions to
-- invoke the action, or the parameter values fall outside the specified
-- constraints, the action fails. The associated event attribute's cause
-- parameter will be set to OPERATION_NOT_PERMITTED. For details and example IAM
-- policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_PollForActivityTask.html>
module Network.AWS.SWF.PollForActivityTask
(
-- * Request
PollForActivityTask
-- ** Request constructor
, pollForActivityTask
-- ** Request lenses
, pfatDomain
, pfatIdentity
, pfatTaskList
-- * Response
, PollForActivityTaskResponse
-- ** Response constructor
, pollForActivityTaskResponse
-- ** Response lenses
, pfatrActivityId
, pfatrActivityType
, pfatrInput
, pfatrStartedEventId
, pfatrTaskToken
, pfatrWorkflowExecution
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data PollForActivityTask = PollForActivityTask
{ _pfatDomain :: Text
, _pfatIdentity :: Maybe Text
, _pfatTaskList :: TaskList
} deriving (Eq, Read, Show)
-- | 'PollForActivityTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pfatDomain' @::@ 'Text'
--
-- * 'pfatIdentity' @::@ 'Maybe' 'Text'
--
-- * 'pfatTaskList' @::@ 'TaskList'
--
pollForActivityTask :: Text -- ^ 'pfatDomain'
-> TaskList -- ^ 'pfatTaskList'
-> PollForActivityTask
pollForActivityTask p1 p2 = PollForActivityTask
{ _pfatDomain = p1
, _pfatTaskList = p2
, _pfatIdentity = Nothing
}
-- | The name of the domain that contains the task lists being polled.
pfatDomain :: Lens' PollForActivityTask Text
pfatDomain = lens _pfatDomain (\s a -> s { _pfatDomain = a })
-- | Identity of the worker making the request, recorded in the 'ActivityTaskStarted'
-- event in the workflow history. This enables diagnostic tracing when problems
-- arise. The form of this identity is user defined.
pfatIdentity :: Lens' PollForActivityTask (Maybe Text)
pfatIdentity = lens _pfatIdentity (\s a -> s { _pfatIdentity = a })
-- | Specifies the task list to poll for activity tasks.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '/' (slash), '|' (vertical bar), or any control characters
-- (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal
-- string quotarnquot.
pfatTaskList :: Lens' PollForActivityTask TaskList
pfatTaskList = lens _pfatTaskList (\s a -> s { _pfatTaskList = a })
data PollForActivityTaskResponse = PollForActivityTaskResponse
{ _pfatrActivityId :: Text
, _pfatrActivityType :: ActivityType
, _pfatrInput :: Maybe Text
, _pfatrStartedEventId :: Integer
, _pfatrTaskToken :: Text
, _pfatrWorkflowExecution :: WorkflowExecution
} deriving (Eq, Read, Show)
-- | 'PollForActivityTaskResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pfatrActivityId' @::@ 'Text'
--
-- * 'pfatrActivityType' @::@ 'ActivityType'
--
-- * 'pfatrInput' @::@ 'Maybe' 'Text'
--
-- * 'pfatrStartedEventId' @::@ 'Integer'
--
-- * 'pfatrTaskToken' @::@ 'Text'
--
-- * 'pfatrWorkflowExecution' @::@ 'WorkflowExecution'
--
pollForActivityTaskResponse :: Text -- ^ 'pfatrTaskToken'
-> Text -- ^ 'pfatrActivityId'
-> Integer -- ^ 'pfatrStartedEventId'
-> WorkflowExecution -- ^ 'pfatrWorkflowExecution'
-> ActivityType -- ^ 'pfatrActivityType'
-> PollForActivityTaskResponse
pollForActivityTaskResponse p1 p2 p3 p4 p5 = PollForActivityTaskResponse
{ _pfatrTaskToken = p1
, _pfatrActivityId = p2
, _pfatrStartedEventId = p3
, _pfatrWorkflowExecution = p4
, _pfatrActivityType = p5
, _pfatrInput = Nothing
}
-- | The unique ID of the task.
pfatrActivityId :: Lens' PollForActivityTaskResponse Text
pfatrActivityId = lens _pfatrActivityId (\s a -> s { _pfatrActivityId = a })
-- | The type of this activity task.
pfatrActivityType :: Lens' PollForActivityTaskResponse ActivityType
pfatrActivityType =
lens _pfatrActivityType (\s a -> s { _pfatrActivityType = a })
-- | The inputs provided when the activity task was scheduled. The form of the
-- input is user defined and should be meaningful to the activity implementation.
pfatrInput :: Lens' PollForActivityTaskResponse (Maybe Text)
pfatrInput = lens _pfatrInput (\s a -> s { _pfatrInput = a })
-- | The id of the 'ActivityTaskStarted' event recorded in the history.
pfatrStartedEventId :: Lens' PollForActivityTaskResponse Integer
pfatrStartedEventId =
lens _pfatrStartedEventId (\s a -> s { _pfatrStartedEventId = a })
-- | The opaque string used as a handle on the task. This token is used by workers
-- to communicate progress and response information back to the system about the
-- task.
pfatrTaskToken :: Lens' PollForActivityTaskResponse Text
pfatrTaskToken = lens _pfatrTaskToken (\s a -> s { _pfatrTaskToken = a })
-- | The workflow execution that started this activity task.
pfatrWorkflowExecution :: Lens' PollForActivityTaskResponse WorkflowExecution
pfatrWorkflowExecution =
lens _pfatrWorkflowExecution (\s a -> s { _pfatrWorkflowExecution = a })
instance ToPath PollForActivityTask where
toPath = const "/"
instance ToQuery PollForActivityTask where
toQuery = const mempty
instance ToHeaders PollForActivityTask
instance ToJSON PollForActivityTask where
toJSON PollForActivityTask{..} = object
[ "domain" .= _pfatDomain
, "taskList" .= _pfatTaskList
, "identity" .= _pfatIdentity
]
instance AWSRequest PollForActivityTask where
type Sv PollForActivityTask = SWF
type Rs PollForActivityTask = PollForActivityTaskResponse
request = post "PollForActivityTask"
response = jsonResponse
instance FromJSON PollForActivityTaskResponse where
parseJSON = withObject "PollForActivityTaskResponse" $ \o -> PollForActivityTaskResponse
<$> o .: "activityId"
<*> o .: "activityType"
<*> o .:? "input"
<*> o .: "startedEventId"
<*> o .: "taskToken"
<*> o .: "workflowExecution"
| romanb/amazonka | amazonka-swf/gen/Network/AWS/SWF/PollForActivityTask.hs | mpl-2.0 | 8,888 | 0 | 19 | 1,910 | 973 | 595 | 378 | 107 | 1 |
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, and (b) the type signatures,
-- the structure should not be too overwhelming.
module PPC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import GhcPrelude
import CodeGen.Platform
import PPC.Instr
import PPC.Cond
import PPC.Regs
import CPrim
import NCGMonad
import Instruction
import PIC
import Format
import RegClass
import Reg
import TargetReg
import Platform
-- Our intermediate code:
import BlockId
import PprCmm ( pprExpr )
import Cmm
import CmmUtils
import CmmSwitch
import CLabel
import Hoopl.Block
import Hoopl.Graph
-- The rest:
import OrdList
import Outputable
import DynFlags
import Control.Monad ( mapAndUnzipM, when )
import Data.Bits
import Data.Word
import BasicTypes
import FastString
import Util
-- -----------------------------------------------------------------------------
-- Top-level of the instruction selector
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal (pre-order?) yields the insns in the correct
-- order.
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
arch = platformArch $ targetPlatform dflags
case arch of
ArchPPC | os == OSAIX -> return tops
| otherwise -> do
picBaseMb <- getPicBaseMaybeNat
case picBaseMb of
Just picBase -> initializePicBase_ppc arch os picBase tops
Nothing -> return tops
ArchPPC_64 ELF_V1 -> fixup_entry tops
-- generating function descriptor is handled in
-- pretty printer
ArchPPC_64 ELF_V2 -> fixup_entry tops
-- generating function prologue is handled in
-- pretty printer
_ -> panic "PPC.cmmTopCodeGen: unknown arch"
where
fixup_entry (CmmProc info lab live (ListGraph (entry:blocks)) : statics)
= do
let BasicBlock bID insns = entry
bID' <- if lab == (blockLbl bID)
then newBlockId
else return bID
let b' = BasicBlock bID' insns
return (CmmProc info lab live (ListGraph (b':blocks)) : statics)
fixup_entry _ = panic "cmmTopCodegen: Broken CmmProc"
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: Block CmmNode C C
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| target32Bit (targetPlatform dflags) &&
isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false prediction -> do
b1 <- genCondJump true arg prediction
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Format Reg InstrBlock
| Any Format (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Format -> Register
swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code
swizzleRegisterRep (Any _ codefn) format = Any format codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> CmmReg -> Reg
getRegisterReg _ (CmmLocal (LocalReg u pk))
= RegVirtual $ mkVirtualReg u (cmmTypeFormat pk)
getRegisterReg platform (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = blockLbl blockid
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr
mangleIndexTree dflags (CmmRegOff reg off)
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
mangleIndexTree _ _
= panic "PPC.CodeGen.mangleIndexTree: no match"
-- -----------------------------------------------------------------------------
-- Code gen for 64-bit arithmetic on 32-bit platforms
{-
Simple support for generating 64-bit code (ie, 64 bit values and 64
bit assignments) on 32-bit platforms. Unlike the main code generator
we merely shoot for generating working code as simply as possible, and
pay little attention to code quality. Specifically, there is no
attempt to deal cleverly with the fixed-vs-floating register
distinction; all values are generated into (pairs of) floating
registers, even if this would mean some redundant reg-reg moves as a
result. Only one of the VRegUniques is returned, since it will be
of the VRegUniqueLo form, and the upper-half VReg can be determined
by applying getHiVRegFromLo to it.
-}
data ChildCode64 -- a.k.a "Register64"
= ChildCode64
InstrBlock -- code
Reg -- the lower 32-bit temporary which contains the
-- result; use getHiVRegFromLo to find the other
-- VRegUnique. Rules of this simplified insn
-- selection game are therefore that the returned
-- Reg may be modified
-- | Compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
getI64Amodes addrTree = do
Amode hi_addr addr_code <- getAmode D addrTree
case addrOffset hi_addr 4 of
Just lo_addr -> return (hi_addr, lo_addr, addr_code)
Nothing -> do (hi_ptr, code) <- getSomeReg addrTree
return (AddrRegImm hi_ptr (ImmInt 0),
AddrRegImm hi_ptr (ImmInt 4),
code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Big-endian store
mov_hi = ST II32 rhi hi_addr
mov_lo = ST II32 rlo lo_addr
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MR r_dst_lo r_src_lo
mov_hi = MR r_dst_hi r_src_hi
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(powerpc): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
(hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LD II32 rhi hi_addr
mov_lo = LD II32 rlo lo_addr
return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
half0 = fromIntegral (fromIntegral i :: Word16)
half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16)
half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16)
half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16)
code = toOL [
LIS rlo (ImmInt half1),
OR rlo rlo (RIImm $ ImmInt half0),
LIS rhi (ImmInt half3),
OR rhi rhi (RIImm $ ImmInt half2)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ ADDC rlo r1lo r2lo,
ADDE rhi r1hi r2hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ SUBFC rlo r2lo (RIReg r1lo),
SUBFE rhi r2hi r1hi ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do
(expr_reg,expr_code) <- getSomeReg expr
(rlo, rhi) <- getNewRegPairNat II32
let mov_hi = LI rhi (ImmInt 0)
mov_lo = MR rlo expr_reg
return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
iselExpr64 expr
= pprPanic "iselExpr64(powerpc)" (pprExpr expr)
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
getRegister' dflags e
getRegister' :: DynFlags -> CmmExpr -> NatM Register
getRegister' dflags (CmmReg (CmmGlobal PicBaseReg))
| OSAIX <- platformOS (targetPlatform dflags) = do
let code dst = toOL [ LD II32 dst tocAddr ]
tocAddr = AddrRegImm toc (ImmLit (text "ghc_toc_table[TC]"))
return (Any II32 code)
| target32Bit (targetPlatform dflags) = do
reg <- getPicBaseNat $ archWordFormat (target32Bit (targetPlatform dflags))
return (Fixed (archWordFormat (target32Bit (targetPlatform dflags)))
reg nilOL)
| otherwise = return (Fixed II64 toc nilOL)
getRegister' dflags (CmmReg reg)
= return (Fixed (cmmTypeFormat (cmmRegType dflags reg))
(getRegisterReg (targetPlatform dflags) reg) nilOL)
getRegister' dflags tree@(CmmRegOff _ _)
= getRegister' dflags (mangleIndexTree dflags tree)
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x])
| target32Bit (targetPlatform dflags) = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' dflags (CmmLoad mem pk)
| not (isWord64 pk) = do
let platform = targetPlatform dflags
Amode addr addr_code <- getAmode D mem
let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk)
addr_code `snocOL` LD format dst addr
return (Any format code)
| not (target32Bit (targetPlatform dflags)) = do
Amode addr addr_code <- getAmode DS mem
let code dst = addr_code `snocOL` LD II64 dst addr
return (Any II64 code)
where format = cmmTypeFormat pk
-- catch simple cases of zero- or sign-extended load
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr))
-- Note: there is no Load Byte Arithmetic instruction, so no signed case here
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr))
getRegister' _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _]) = do
Amode addr addr_code <- getAmode D mem
return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr))
getRegister' _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _]) = do
-- lwa is DS-form. See Note [Power instruction format]
Amode addr addr_code <- getAmode DS mem
return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr))
getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps
= case mop of
MO_Not rep -> triv_ucode_int rep NOT
MO_F_Neg w -> triv_ucode_float w FNEG
MO_S_Neg w -> triv_ucode_int w NEG
MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x
MO_FF_Conv W32 W64 -> conversionNop FF64 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_SS_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_SS_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit int register"
| otherwise -> conversionNop (intFormat to) x
MO_SS_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise -> case to of
W64 -> triv_ucode_int to (EXTS II32)
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_SS_Conv W16 W8 -> conversionNop II8 x
MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8)
MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16)
MO_UU_Conv from to
| from == to -> conversionNop (intFormat to) x
-- narrowing is a nop: we treat the high bits as undefined
MO_UU_Conv W64 to
| arch32 -> panic "PPC.CodeGen.getRegister no 64 bit target"
| otherwise -> conversionNop (intFormat to) x
MO_UU_Conv W32 to
| arch32 -> conversionNop (intFormat to) x
| otherwise ->
case to of
W64 -> trivialCode to False AND x (CmmLit (CmmInt 4294967295 W64))
W16 -> conversionNop II16 x
W8 -> conversionNop II8 x
_ -> panic "PPC.CodeGen.getRegister: no match"
MO_UU_Conv W16 W8 -> conversionNop II8 x
MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32))
MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32))
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_ucode_int width instr = trivialUCode (intFormat width) instr x
triv_ucode_float width instr = trivialUCode (floatFormat width) instr x
conversionNop new_format expr
= do e_code <- getRegister' dflags expr
return (swizzleRegisterRep e_code new_format)
arch32 = target32Bit $ targetPlatform dflags
getRegister' dflags (CmmMachOp mop [x, y]) -- dyadic PrimOps
= case mop of
MO_F_Eq _ -> condFltReg EQQ x y
MO_F_Ne _ -> condFltReg NE x y
MO_F_Gt _ -> condFltReg GTT x y
MO_F_Ge _ -> condFltReg GE x y
MO_F_Lt _ -> condFltReg LTT x y
MO_F_Le _ -> condFltReg LE x y
MO_Eq rep -> condIntReg EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntReg NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntReg GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntReg GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntReg LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntReg LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntReg GU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Ge rep -> condIntReg GEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Lt rep -> condIntReg LU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_U_Le rep -> condIntReg LEU (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_F_Add w -> triv_float w FADD
MO_F_Sub w -> triv_float w FSUB
MO_F_Mul w -> triv_float w FMUL
MO_F_Quot w -> triv_float w FDIV
-- optimize addition with 32-bit immediate
-- (needed for PIC)
MO_Add W32 ->
case y of
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True imm
-> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep)
CmmLit lit
-> do
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
code dst = srcCode `appOL` toOL [
ADDIS dst src (HA imm),
ADD dst dst (RIImm (LO imm))
]
return (Any II32 code)
_ -> trivialCode W32 True ADD x y
MO_Add rep -> trivialCode rep True ADD x y
MO_Sub rep ->
case y of
CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
-> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
_ -> case x of
CmmLit (CmmInt imm _)
| Just _ <- makeImmediate rep True imm
-- subfi ('substract from' with immediate) doesn't exist
-> trivialCode rep True SUBFC y x
_ -> trivialCodeNoImm' (intFormat rep) SUBF y x
MO_Mul rep -> shiftMulCode rep True MULL x y
MO_S_MulMayOflo rep -> do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
format = intFormat rep
code dst = code1 `appOL` code2
`appOL` toOL [ MULLO format dst src1 src2
, MFOV format dst
]
return (Any format code)
MO_S_Quot rep -> trivialCodeNoImmSign (intFormat rep) True DIV
(extendSExpr dflags rep x) (extendSExpr dflags rep y)
MO_U_Quot rep -> trivialCodeNoImmSign (intFormat rep) False DIV
(extendUExpr dflags rep x) (extendUExpr dflags rep y)
MO_S_Rem rep -> remainderCode rep True (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Rem rep -> remainderCode rep False (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_And rep -> case y of
(CmmLit (CmmInt imm _)) | imm == -8 || imm == -4
-> do
(src, srcCode) <- getSomeReg x
let clear_mask = if imm == -4 then 2 else 3
fmt = intFormat rep
code dst = srcCode
`appOL` unitOL (CLRRI fmt dst src clear_mask)
return (Any fmt code)
_ -> trivialCode rep False AND x y
MO_Or rep -> trivialCode rep False OR x y
MO_Xor rep -> trivialCode rep False XOR x y
MO_Shl rep -> shiftMulCode rep False SL x y
MO_S_Shr rep -> shiftMulCode rep False SRA (extendSExpr dflags rep x) y
MO_U_Shr rep -> shiftMulCode rep False SR (extendUExpr dflags rep x) y
_ -> panic "PPC.CodeGen.getRegister: no match"
where
triv_float :: Width -> (Format -> Reg -> Reg -> Reg -> Instr) -> NatM Register
triv_float width instr = trivialCodeNoImm (floatFormat width) instr x y
getRegister' _ (CmmLit (CmmInt i rep))
| Just imm <- makeImmediate rep True i
= let
code dst = unitOL (LI dst imm)
in
return (Any (intFormat rep) code)
getRegister' _ (CmmLit (CmmFloat f frep)) = do
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let format = floatFormat frep
code dst =
LDATA (Section ReadOnlyData lbl)
(Statics lbl [CmmStaticLit (CmmFloat f frep)])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' dflags (CmmLit lit)
| target32Bit (targetPlatform dflags)
= let rep = cmmLitType dflags lit
imm = litToImm lit
code dst = toOL [
LIS dst (HA imm),
ADD dst dst (RIImm (LO imm))
]
in return (Any (cmmTypeFormat rep) code)
| otherwise
= do lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let rep = cmmLitType dflags lit
format = cmmTypeFormat rep
code dst =
LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit lit])
`consOL` (addr_code `snocOL` LD format dst addr)
return (Any format code)
getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other)
-- extend?Rep: wrap integer expression of type rep
-- in a conversion to II32 or II64 resp.
extendSExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendSExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendSExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendSExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_SS_Conv rep size) [x]
extendUExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr
extendUExpr dflags W32 x
| target32Bit (targetPlatform dflags) = x
extendUExpr dflags W64 x
| not (target32Bit (targetPlatform dflags)) = x
extendUExpr dflags rep x =
let size = if target32Bit $ targetPlatform dflags
then W32
else W64
in CmmMachOp (MO_UU_Conv rep size) [x]
-- -----------------------------------------------------------------------------
-- The 'Amode' type: Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to a CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
{- Note [Power instruction format]
In some instructions the 16 bit offset must be a multiple of 4, i.e.
the two least significant bits must be zero. The "Power ISA" specification
calls these instruction formats "DS-FORM" and the instructions with
arbitrary 16 bit offsets are "D-FORM".
The Power ISA specification document can be obtained from www.power.org.
-}
data InstrForm = D | DS
getAmode :: InstrForm -> CmmExpr -> NatM Amode
getAmode inf tree@(CmmRegOff _ _)
= do dflags <- getDynFlags
getAmode inf (mangleIndexTree dflags tree)
getAmode _ (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W32 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode D (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
return (Amode (AddrRegImm reg off) code)
getAmode DS (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True (-i)
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
getAmode DS (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)])
| Just off <- makeImmediate W64 True i
= do
(reg, code) <- getSomeReg x
(reg', off', code') <-
if i `mod` 4 == 0
then do return (reg, off, code)
else do
tmp <- getNewRegNat II64
return (tmp, ImmInt 0,
code `snocOL` ADD tmp reg (RIImm off))
return (Amode (AddrRegImm reg' off') code')
-- optimize addition with 32-bit immediate
-- (needed for PIC)
getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit lit])
= do
dflags <- getDynFlags
(src, srcCode) <- getSomeReg x
let imm = litToImm lit
case () of
_ | OSAIX <- platformOS (targetPlatform dflags)
, isCmmLabelType lit ->
-- HA16/LO16 relocations on labels not supported on AIX
return (Amode (AddrRegImm src imm) srcCode)
| otherwise -> do
tmp <- getNewRegNat II32
let code = srcCode `snocOL` ADDIS tmp src (HA imm)
return (Amode (AddrRegImm tmp (LO imm)) code)
where
isCmmLabelType (CmmLabel {}) = True
isCmmLabelType (CmmLabelOff {}) = True
isCmmLabelType (CmmLabelDiffOff {}) = True
isCmmLabelType _ = False
getAmode _ (CmmLit lit)
= do
dflags <- getDynFlags
case platformArch $ targetPlatform dflags of
ArchPPC -> do
tmp <- getNewRegNat II32
let imm = litToImm lit
code = unitOL (LIS tmp (HA imm))
return (Amode (AddrRegImm tmp (LO imm)) code)
_ -> do -- TODO: Load from TOC,
-- see getRegister' _ (CmmLit lit)
tmp <- getNewRegNat II64
let imm = litToImm lit
code = toOL [
LIS tmp (HIGHESTA imm),
OR tmp tmp (RIImm (HIGHERA imm)),
SL II64 tmp tmp (RIImm (ImmInt 32)),
ORIS tmp tmp (HA imm)
]
return (Amode (AddrRegImm tmp (LO imm)) code)
getAmode _ (CmmMachOp (MO_Add W32) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ (CmmMachOp (MO_Add W64) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmode _ other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
-- The 'CondCode' type: Condition codes passed up the tree.
data CondCode
= CondCode Bool Cond InstrBlock
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- almost the same as everywhere else - but we need to
-- extend small integers to 32 bit or 64 bit first
getCondCode (CmmMachOp mop [x, y])
= do
dflags <- getDynFlags
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq rep -> condIntCode EQQ (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_Ne rep -> condIntCode NE (extendUExpr dflags rep x)
(extendUExpr dflags rep y)
MO_S_Gt rep -> condIntCode GTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Ge rep -> condIntCode GE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Lt rep -> condIntCode LTT (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_S_Le rep -> condIntCode LE (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Gt rep -> condIntCode GU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Ge rep -> condIntCode GEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Lt rep -> condIntCode LU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
MO_U_Le rep -> condIntCode LEU (extendSExpr dflags rep x)
(extendSExpr dflags rep y)
_ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
getCondCode _ = panic "getCondCode(2)(powerpc)"
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- optimize pointer tag checks. Operation andi. sets condition register
-- so cmpi ..., 0 is redundant.
condIntCode cond (CmmMachOp (MO_And _) [x, CmmLit (CmmInt imm rep)])
(CmmLit (CmmInt 0 _))
| not $ condUnsigned cond,
Just src2 <- makeImmediate rep False imm
= do
(src1, code) <- getSomeReg x
let code' = code `snocOL` AND r0 src1 (RIImm src2)
return (CondCode False cond code')
condIntCode cond x (CmmLit (CmmInt y rep))
| Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
= do
(src1, code) <- getSomeReg x
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIImm src2)
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
dflags <- getDynFlags
let format = archWordFormat $ target32Bit $ targetPlatform dflags
code' = code1 `appOL` code2 `snocOL`
(if condUnsigned cond then CMPL else CMP) format src1 (RIReg src2)
return (CondCode False cond code')
condFltCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code' = code1 `appOL` code2 `snocOL` FCMP src1 src2
code'' = case cond of -- twiddle CR to handle unordered case
GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
_ -> code'
where
ltbit = 0 ; eqbit = 2 ; gtbit = 1
return (CondCode True cond code'')
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- case pk of
II64 -> getAmode DS addr
_ -> getAmode D addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src
= do
dflags <- getDynFlags
let dst = getRegisterReg (targetPlatform dflags) reg
r <- getRegister src
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` MR dst freg
-- Easy, isn't it?
assignMem_FltCode = assignMem_IntCode
assignReg_FltCode = assignReg_IntCode
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (unitOL $ JMP lbl)
genJump tree
= do
dflags <- getDynFlags
genJump' tree (platformToGCP (targetPlatform dflags))
genJump' :: CmmExpr -> GenCCallPlatform -> NatM InstrBlock
genJump' tree (GCPLinux64ELF 1)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm target (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm target (ImmInt 16))
`snocOL` BCTR [] Nothing)
genJump' tree (GCPLinux64ELF 2)
= do
(target,code) <- getSomeReg tree
return (code
`snocOL` MR r12 target
`snocOL` MTCTR r12
`snocOL` BCTR [] Nothing)
genJump' tree _
= do
(target,code) <- getSomeReg tree
return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> Maybe Bool
-> NatM InstrBlock
genCondJump id bool prediction = do
CondCode _ cond code <- getCondCode bool
return (code `snocOL` BCC cond id prediction)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
genCCall :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ unitOL LWSYNC
genCCall (PrimTarget MO_Touch) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n]
= do dflags <- getDynFlags
let platform = targetPlatform dflags
fmt = intFormat width
reg_dst = getRegisterReg platform (CmmLocal dst)
(instr, n_code) <- case amop of
AMO_Add -> getSomeRegOrImm ADD True reg_dst
AMO_Sub -> case n of
CmmLit (CmmInt i _)
| Just imm <- makeImmediate width True (-i)
-> return (ADD reg_dst reg_dst (RIImm imm), nilOL)
_
-> do
(n_reg, n_code) <- getSomeReg n
return (SUBF reg_dst n_reg reg_dst, n_code)
AMO_And -> getSomeRegOrImm AND False reg_dst
AMO_Nand -> do (n_reg, n_code) <- getSomeReg n
return (NAND reg_dst reg_dst n_reg, n_code)
AMO_Or -> getSomeRegOrImm OR False reg_dst
AMO_Xor -> getSomeRegOrImm XOR False reg_dst
Amode addr_reg addr_code <- getAmodeIndex addr
lbl_retry <- getBlockIdNat
return $ n_code `appOL` addr_code
`appOL` toOL [ HWSYNC
, BCC ALWAYS lbl_retry Nothing
, NEWBLOCK lbl_retry
, LDR fmt reg_dst addr_reg
, instr
, STC fmt reg_dst addr_reg
, BCC NE lbl_retry (Just False)
, ISYNC
]
where
getAmodeIndex (CmmMachOp (MO_Add _) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
getAmodeIndex other
= do
(reg, code) <- getSomeReg other
return (Amode (AddrRegReg r0 reg) code) -- NB: r0 is 0 here!
getSomeRegOrImm op sign dst
= case n of
CmmLit (CmmInt i _) | Just imm <- makeImmediate width sign i
-> return (op dst dst (RIImm imm), nilOL)
_
-> do
(n_reg, n_code) <- getSomeReg n
return (op dst dst (RIReg n_reg), n_code)
genCCall (PrimTarget (MO_AtomicRead width)) [dst] [addr]
= do dflags <- getDynFlags
let platform = targetPlatform dflags
fmt = intFormat width
reg_dst = getRegisterReg platform (CmmLocal dst)
form = if widthInBits width == 64 then DS else D
Amode addr_reg addr_code <- getAmode form addr
lbl_end <- getBlockIdNat
return $ addr_code `appOL` toOL [ HWSYNC
, LD fmt reg_dst addr_reg
, CMP fmt reg_dst (RIReg reg_dst)
, BCC NE lbl_end (Just False)
, BCC ALWAYS lbl_end Nothing
-- See Note [Seemingly useless cmp and bne]
, NEWBLOCK lbl_end
, ISYNC
]
-- Note [Seemingly useless cmp and bne]
-- In Power ISA, Book II, Section 4.4.1, Instruction Synchronize Instruction
-- the second paragraph says that isync may complete before storage accesses
-- "associated" with a preceding instruction have been performed. The cmp
-- operation and the following bne introduce a data and control dependency
-- on the load instruction (See also Power ISA, Book II, Appendix B.2.3, Safe
-- Fetch).
-- This is also what gcc does.
genCCall (PrimTarget (MO_AtomicWrite width)) [] [addr, val] = do
code <- assignMem_IntCode (intFormat width) addr val
return $ unitOL(HWSYNC) `appOL` code
genCCall (PrimTarget (MO_Clz width)) [dst] [src]
= do dflags <- getDynFlags
let platform = targetPlatform dflags
reg_dst = getRegisterReg platform (CmmLocal dst)
if target32Bit platform && width == W64
then do
ChildCode64 code vr_lo <- iselExpr64 src
lbl1 <- getBlockIdNat
lbl2 <- getBlockIdNat
lbl3 <- getBlockIdNat
let vr_hi = getHiVRegFromLo vr_lo
cntlz = toOL [ CMPL II32 vr_hi (RIImm (ImmInt 0))
, BCC NE lbl2 Nothing
, BCC ALWAYS lbl1 Nothing
, NEWBLOCK lbl1
, CNTLZ II32 reg_dst vr_lo
, ADD reg_dst reg_dst (RIImm (ImmInt 32))
, BCC ALWAYS lbl3 Nothing
, NEWBLOCK lbl2
, CNTLZ II32 reg_dst vr_hi
, BCC ALWAYS lbl3 Nothing
, NEWBLOCK lbl3
]
return $ code `appOL` cntlz
else do
let format = if width == W64 then II64 else II32
(s_reg, s_code) <- getSomeReg src
(pre, reg , post) <-
case width of
W64 -> return (nilOL, s_reg, nilOL)
W32 -> return (nilOL, s_reg, nilOL)
W16 -> do
reg_tmp <- getNewRegNat format
return
( unitOL $ AND reg_tmp s_reg (RIImm (ImmInt 65535))
, reg_tmp
, unitOL $ ADD reg_dst reg_dst (RIImm (ImmInt (-16)))
)
W8 -> do
reg_tmp <- getNewRegNat format
return
( unitOL $ AND reg_tmp s_reg (RIImm (ImmInt 255))
, reg_tmp
, unitOL $ ADD reg_dst reg_dst (RIImm (ImmInt (-24)))
)
_ -> panic "genCall: Clz wrong format"
let cntlz = unitOL (CNTLZ format reg_dst reg)
return $ s_code `appOL` pre `appOL` cntlz `appOL` post
genCCall (PrimTarget (MO_Ctz width)) [dst] [src]
= do dflags <- getDynFlags
let platform = targetPlatform dflags
reg_dst = getRegisterReg platform (CmmLocal dst)
if target32Bit platform && width == W64
then do
let format = II32
ChildCode64 code vr_lo <- iselExpr64 src
lbl1 <- getBlockIdNat
lbl2 <- getBlockIdNat
lbl3 <- getBlockIdNat
x' <- getNewRegNat format
x'' <- getNewRegNat format
r' <- getNewRegNat format
cnttzlo <- cnttz format reg_dst vr_lo
let vr_hi = getHiVRegFromLo vr_lo
cnttz64 = toOL [ CMPL format vr_lo (RIImm (ImmInt 0))
, BCC NE lbl2 Nothing
, BCC ALWAYS lbl1 Nothing
, NEWBLOCK lbl1
, ADD x' vr_hi (RIImm (ImmInt (-1)))
, ANDC x'' x' vr_hi
, CNTLZ format r' x''
-- 32 + (32 - clz(x''))
, SUBFC reg_dst r' (RIImm (ImmInt 64))
, BCC ALWAYS lbl3 Nothing
, NEWBLOCK lbl2
]
`appOL` cnttzlo `appOL`
toOL [ BCC ALWAYS lbl3 Nothing
, NEWBLOCK lbl3
]
return $ code `appOL` cnttz64
else do
let format = if width == W64 then II64 else II32
(s_reg, s_code) <- getSomeReg src
(reg_ctz, pre_code) <-
case width of
W64 -> return (s_reg, nilOL)
W32 -> return (s_reg, nilOL)
W16 -> do
reg_tmp <- getNewRegNat format
return (reg_tmp, unitOL $ ORIS reg_tmp s_reg (ImmInt 1))
W8 -> do
reg_tmp <- getNewRegNat format
return (reg_tmp, unitOL $ OR reg_tmp s_reg (RIImm (ImmInt 256)))
_ -> panic "genCall: Ctz wrong format"
ctz_code <- cnttz format reg_dst reg_ctz
return $ s_code `appOL` pre_code `appOL` ctz_code
where
-- cnttz(x) = sizeof(x) - cntlz(~x & (x - 1))
-- see Henry S. Warren, Hacker's Delight, p 107
cnttz format dst src = do
let format_bits = 8 * formatInBytes format
x' <- getNewRegNat format
x'' <- getNewRegNat format
r' <- getNewRegNat format
return $ toOL [ ADD x' src (RIImm (ImmInt (-1)))
, ANDC x'' x' src
, CNTLZ format r' x''
, SUBFC dst r' (RIImm (ImmInt (format_bits)))
]
genCCall target dest_regs argsAndHints
= do dflags <- getDynFlags
let platform = targetPlatform dflags
case target of
PrimTarget (MO_S_QuotRem width) -> divOp1 platform True width
dest_regs argsAndHints
PrimTarget (MO_U_QuotRem width) -> divOp1 platform False width
dest_regs argsAndHints
PrimTarget (MO_U_QuotRem2 width) -> divOp2 platform width dest_regs
argsAndHints
PrimTarget (MO_U_Mul2 width) -> multOp2 platform width dest_regs
argsAndHints
PrimTarget (MO_Add2 _) -> add2Op platform dest_regs argsAndHints
PrimTarget (MO_SubWordC _) -> subcOp platform dest_regs argsAndHints
PrimTarget (MO_AddIntC width) -> addSubCOp ADDO platform width
dest_regs argsAndHints
PrimTarget (MO_SubIntC width) -> addSubCOp SUBFO platform width
dest_regs argsAndHints
PrimTarget MO_F64_Fabs -> fabs platform dest_regs argsAndHints
PrimTarget MO_F32_Fabs -> fabs platform dest_regs argsAndHints
_ -> genCCall' dflags (platformToGCP platform)
target dest_regs argsAndHints
where divOp1 platform signed width [res_q, res_r] [arg_x, arg_y]
= do let reg_q = getRegisterReg platform (CmmLocal res_q)
reg_r = getRegisterReg platform (CmmLocal res_r)
fmt = intFormat width
(x_reg, x_code) <- getSomeReg arg_x
(y_reg, y_code) <- getSomeReg arg_y
return $ y_code `appOL` x_code
`appOL` toOL [ DIV fmt signed reg_q x_reg y_reg
, MULL fmt reg_r reg_q (RIReg y_reg)
, SUBF reg_r reg_r x_reg
]
divOp1 _ _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp1"
divOp2 platform width [res_q, res_r]
[arg_x_high, arg_x_low, arg_y]
= do let reg_q = getRegisterReg platform (CmmLocal res_q)
reg_r = getRegisterReg platform (CmmLocal res_r)
fmt = intFormat width
half = 4 * (formatInBytes fmt)
(xh_reg, xh_code) <- getSomeReg arg_x_high
(xl_reg, xl_code) <- getSomeReg arg_x_low
(y_reg, y_code) <- getSomeReg arg_y
s <- getNewRegNat fmt
b <- getNewRegNat fmt
v <- getNewRegNat fmt
vn1 <- getNewRegNat fmt
vn0 <- getNewRegNat fmt
un32 <- getNewRegNat fmt
tmp <- getNewRegNat fmt
un10 <- getNewRegNat fmt
un1 <- getNewRegNat fmt
un0 <- getNewRegNat fmt
q1 <- getNewRegNat fmt
rhat <- getNewRegNat fmt
tmp1 <- getNewRegNat fmt
q0 <- getNewRegNat fmt
un21 <- getNewRegNat fmt
again1 <- getBlockIdNat
no1 <- getBlockIdNat
then1 <- getBlockIdNat
endif1 <- getBlockIdNat
again2 <- getBlockIdNat
no2 <- getBlockIdNat
then2 <- getBlockIdNat
endif2 <- getBlockIdNat
return $ y_code `appOL` xl_code `appOL` xh_code `appOL`
-- see Hacker's Delight p 196 Figure 9-3
toOL [ -- b = 2 ^ (bits_in_word / 2)
LI b (ImmInt 1)
, SL fmt b b (RIImm (ImmInt half))
-- s = clz(y)
, CNTLZ fmt s y_reg
-- v = y << s
, SL fmt v y_reg (RIReg s)
-- vn1 = upper half of v
, SR fmt vn1 v (RIImm (ImmInt half))
-- vn0 = lower half of v
, CLRLI fmt vn0 v half
-- un32 = (u1 << s)
-- | (u0 >> (bits_in_word - s))
, SL fmt un32 xh_reg (RIReg s)
, SUBFC tmp s
(RIImm (ImmInt (8 * formatInBytes fmt)))
, SR fmt tmp xl_reg (RIReg tmp)
, OR un32 un32 (RIReg tmp)
-- un10 = u0 << s
, SL fmt un10 xl_reg (RIReg s)
-- un1 = upper half of un10
, SR fmt un1 un10 (RIImm (ImmInt half))
-- un0 = lower half of un10
, CLRLI fmt un0 un10 half
-- q1 = un32/vn1
, DIV fmt False q1 un32 vn1
-- rhat = un32 - q1*vn1
, MULL fmt tmp q1 (RIReg vn1)
, SUBF rhat tmp un32
, BCC ALWAYS again1 Nothing
, NEWBLOCK again1
-- if (q1 >= b || q1*vn0 > b*rhat + un1)
, CMPL fmt q1 (RIReg b)
, BCC GEU then1 Nothing
, BCC ALWAYS no1 Nothing
, NEWBLOCK no1
, MULL fmt tmp q1 (RIReg vn0)
, SL fmt tmp1 rhat (RIImm (ImmInt half))
, ADD tmp1 tmp1 (RIReg un1)
, CMPL fmt tmp (RIReg tmp1)
, BCC LEU endif1 Nothing
, BCC ALWAYS then1 Nothing
, NEWBLOCK then1
-- q1 = q1 - 1
, ADD q1 q1 (RIImm (ImmInt (-1)))
-- rhat = rhat + vn1
, ADD rhat rhat (RIReg vn1)
-- if (rhat < b) goto again1
, CMPL fmt rhat (RIReg b)
, BCC LTT again1 Nothing
, BCC ALWAYS endif1 Nothing
, NEWBLOCK endif1
-- un21 = un32*b + un1 - q1*v
, SL fmt un21 un32 (RIImm (ImmInt half))
, ADD un21 un21 (RIReg un1)
, MULL fmt tmp q1 (RIReg v)
, SUBF un21 tmp un21
-- compute second quotient digit
-- q0 = un21/vn1
, DIV fmt False q0 un21 vn1
-- rhat = un21- q0*vn1
, MULL fmt tmp q0 (RIReg vn1)
, SUBF rhat tmp un21
, BCC ALWAYS again2 Nothing
, NEWBLOCK again2
-- if (q0>b || q0*vn0 > b*rhat + un0)
, CMPL fmt q0 (RIReg b)
, BCC GEU then2 Nothing
, BCC ALWAYS no2 Nothing
, NEWBLOCK no2
, MULL fmt tmp q0 (RIReg vn0)
, SL fmt tmp1 rhat (RIImm (ImmInt half))
, ADD tmp1 tmp1 (RIReg un0)
, CMPL fmt tmp (RIReg tmp1)
, BCC LEU endif2 Nothing
, BCC ALWAYS then2 Nothing
, NEWBLOCK then2
-- q0 = q0 - 1
, ADD q0 q0 (RIImm (ImmInt (-1)))
-- rhat = rhat + vn1
, ADD rhat rhat (RIReg vn1)
-- if (rhat<b) goto again2
, CMPL fmt rhat (RIReg b)
, BCC LTT again2 Nothing
, BCC ALWAYS endif2 Nothing
, NEWBLOCK endif2
-- compute remainder
-- r = (un21*b + un0 - q0*v) >> s
, SL fmt reg_r un21 (RIImm (ImmInt half))
, ADD reg_r reg_r (RIReg un0)
, MULL fmt tmp q0 (RIReg v)
, SUBF reg_r tmp reg_r
, SR fmt reg_r reg_r (RIReg s)
-- compute quotient
-- q = q1*b + q0
, SL fmt reg_q q1 (RIImm (ImmInt half))
, ADD reg_q reg_q (RIReg q0)
]
divOp2 _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp2"
multOp2 platform width [res_h, res_l] [arg_x, arg_y]
= do let reg_h = getRegisterReg platform (CmmLocal res_h)
reg_l = getRegisterReg platform (CmmLocal res_l)
fmt = intFormat width
(x_reg, x_code) <- getSomeReg arg_x
(y_reg, y_code) <- getSomeReg arg_y
return $ y_code `appOL` x_code
`appOL` toOL [ MULL fmt reg_l x_reg (RIReg y_reg)
, MULHU fmt reg_h x_reg y_reg
]
multOp2 _ _ _ _
= panic "genCall: Wrong number of arguments for multOp2"
add2Op platform [res_h, res_l] [arg_x, arg_y]
= do let reg_h = getRegisterReg platform (CmmLocal res_h)
reg_l = getRegisterReg platform (CmmLocal res_l)
(x_reg, x_code) <- getSomeReg arg_x
(y_reg, y_code) <- getSomeReg arg_y
return $ y_code `appOL` x_code
`appOL` toOL [ LI reg_h (ImmInt 0)
, ADDC reg_l x_reg y_reg
, ADDZE reg_h reg_h
]
add2Op _ _ _
= panic "genCCall: Wrong number of arguments/results for add2"
-- PowerPC subfc sets the carry for rT = ~(rA) + rB + 1,
-- which is 0 for borrow and 1 otherwise. We need 1 and 0
-- so xor with 1.
subcOp platform [res_r, res_c] [arg_x, arg_y]
= do let reg_r = getRegisterReg platform (CmmLocal res_r)
reg_c = getRegisterReg platform (CmmLocal res_c)
(x_reg, x_code) <- getSomeReg arg_x
(y_reg, y_code) <- getSomeReg arg_y
return $ y_code `appOL` x_code
`appOL` toOL [ LI reg_c (ImmInt 0)
, SUBFC reg_r y_reg (RIReg x_reg)
, ADDZE reg_c reg_c
, XOR reg_c reg_c (RIImm (ImmInt 1))
]
subcOp _ _ _
= panic "genCCall: Wrong number of arguments/results for subc"
addSubCOp instr platform width [res_r, res_c] [arg_x, arg_y]
= do let reg_r = getRegisterReg platform (CmmLocal res_r)
reg_c = getRegisterReg platform (CmmLocal res_c)
(x_reg, x_code) <- getSomeReg arg_x
(y_reg, y_code) <- getSomeReg arg_y
return $ y_code `appOL` x_code
`appOL` toOL [ instr reg_r y_reg x_reg,
-- SUBFO argument order reversed!
MFOV (intFormat width) reg_c
]
addSubCOp _ _ _ _ _
= panic "genCall: Wrong number of arguments/results for addC"
fabs platform [res] [arg]
= do let res_r = getRegisterReg platform (CmmLocal res)
(arg_reg, arg_code) <- getSomeReg arg
return $ arg_code `snocOL` FABS res_r arg_reg
fabs _ _ _
= panic "genCall: Wrong number of arguments/results for fabs"
-- TODO: replace 'Int' by an enum such as 'PPC_64ABI'
data GenCCallPlatform = GCPLinux | GCPDarwin | GCPLinux64ELF !Int | GCPAIX
platformToGCP :: Platform -> GenCCallPlatform
platformToGCP platform = case platformOS platform of
OSLinux -> case platformArch platform of
ArchPPC -> GCPLinux
ArchPPC_64 ELF_V1 -> GCPLinux64ELF 1
ArchPPC_64 ELF_V2 -> GCPLinux64ELF 2
_ -> panic "PPC.CodeGen.platformToGCP: Unknown Linux"
OSAIX -> GCPAIX
OSDarwin -> GCPDarwin
_ -> panic "PPC.CodeGen.platformToGCP: not defined for this OS"
genCCall'
:: DynFlags
-> GenCCallPlatform
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
{-
The PowerPC calling convention for Darwin/Mac OS X
is described in Apple's document
"Inside Mac OS X - Mach-O Runtime Architecture".
PowerPC Linux uses the System V Release 4 Calling Convention
for PowerPC. It is described in the
"System V Application Binary Interface PowerPC Processor Supplement".
Both conventions are similar:
Parameters may be passed in general-purpose registers starting at r3, in
floating point registers starting at f1, or on the stack.
But there are substantial differences:
* The number of registers used for parameter passing and the exact set of
nonvolatile registers differs (see MachRegs.hs).
* On Darwin, stack space is always reserved for parameters, even if they are
passed in registers. The called routine may choose to save parameters from
registers to the corresponding space on the stack.
* On Darwin, a corresponding amount of GPRs is skipped when a floating point
parameter is passed in an FPR.
* SysV insists on either passing I64 arguments on the stack, or in two GPRs,
starting with an odd-numbered GPR. It may skip a GPR to achieve this.
Darwin just treats an I64 like two separate II32s (high word first).
* I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only
4-byte aligned like everything else on Darwin.
* The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on
PowerPC Linux does not agree, so neither do we.
PowerPC 64 Linux uses the System V Release 4 Calling Convention for
64-bit PowerPC. It is specified in
"64-bit PowerPC ELF Application Binary Interface Supplement 1.9"
(PPC64 ELF v1.9).
PowerPC 64 Linux in little endian mode uses the "Power Architecture 64-Bit
ELF V2 ABI Specification -- OpenPOWER ABI for Linux Supplement"
(PPC64 ELF v2).
AIX follows the "PowerOpen ABI: Application Binary Interface Big-Endian
32-Bit Hardware Implementation"
According to all conventions, the parameter area should be part of the
caller's stack frame, allocated in the caller's prologue code (large enough
to hold the parameter lists for all called routines). The NCG already
uses the stack for register spilling, leaving 64 bytes free at the top.
If we need a larger parameter area than that, we just allocate a new stack
frame just before ccalling.
-}
genCCall' dflags gcp target dest_regs args
= ASSERT(not $ any (`elem` [II16]) $ map cmmTypeFormat argReps)
-- we rely on argument promotion in the codeGen
do
(finalStack,passArgumentsCode,usedRegs) <- passArguments
(zip args argReps)
allArgRegs
(allFPArgRegs platform)
initialStackOffset
(toOL []) []
(labelOrExpr, reduceToFF32) <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do
uses_pic_base_implicitly
return (Left lbl, False)
ForeignTarget expr _ -> do
uses_pic_base_implicitly
return (Right expr, False)
PrimTarget mop -> outOfLineMachOp mop
let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
codeAfter = move_sp_up finalStack `appOL` moveResult reduceToFF32
case labelOrExpr of
Left lbl -> do -- the linker does all the work for us
return ( codeBefore
`snocOL` BL lbl usedRegs
`appOL` maybeNOP -- some ABI require a NOP after BL
`appOL` codeAfter)
Right dyn -> do -- implement call through function pointer
(dynReg, dynCode) <- getSomeReg dyn
case gcp of
GCPLinux64ELF 1 -> return ( dynCode
`appOL` codeBefore
`snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 40))
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 0))
`snocOL` LD II64 toc (AddrRegImm dynReg (ImmInt 8))
`snocOL` MTCTR r11
`snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 16))
`snocOL` BCTRL usedRegs
`snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 40))
`appOL` codeAfter)
GCPLinux64ELF 2 -> return ( dynCode
`appOL` codeBefore
`snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 24))
`snocOL` MR r12 dynReg
`snocOL` MTCTR r12
`snocOL` BCTRL usedRegs
`snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 24))
`appOL` codeAfter)
GCPAIX -> return ( dynCode
-- AIX/XCOFF follows the PowerOPEN ABI
-- which is quite similiar to LinuxPPC64/ELFv1
`appOL` codeBefore
`snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 20))
`snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 0))
`snocOL` LD II32 toc (AddrRegImm dynReg (ImmInt 4))
`snocOL` MTCTR r11
`snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 8))
`snocOL` BCTRL usedRegs
`snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 20))
`appOL` codeAfter)
_ -> return ( dynCode
`snocOL` MTCTR dynReg
`appOL` codeBefore
`snocOL` BCTRL usedRegs
`appOL` codeAfter)
where
platform = targetPlatform dflags
uses_pic_base_implicitly = do
-- See Note [implicit register in PPC PIC code]
-- on why we claim to use PIC register here
when (positionIndependent dflags && target32Bit platform) $ do
_ <- getPicBaseNat $ archWordFormat True
return ()
initialStackOffset = case gcp of
GCPAIX -> 24
GCPDarwin -> 24
GCPLinux -> 8
GCPLinux64ELF 1 -> 48
GCPLinux64ELF 2 -> 32
_ -> panic "genCall': unknown calling convention"
-- size of linkage area + size of arguments, in bytes
stackDelta finalStack = case gcp of
GCPAIX ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPDarwin ->
roundTo 16 $ (24 +) $ max 32 $ sum $
map (widthInBytes . typeWidth) argReps
GCPLinux -> roundTo 16 finalStack
GCPLinux64ELF 1 ->
roundTo 16 $ (48 +) $ max 64 $ sum $
map (roundTo 8 . widthInBytes . typeWidth)
argReps
GCPLinux64ELF 2 ->
roundTo 16 $ (32 +) $ max 64 $ sum $
map (roundTo 8 . widthInBytes . typeWidth)
argReps
_ -> panic "genCall': unknown calling conv."
argReps = map (cmmExprType dflags) args
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
spFormat = if target32Bit platform then II32 else II64
-- TODO: Do not create a new stack frame if delta is too large.
move_sp_down finalStack
| delta > stackFrameHeaderSize dflags =
toOL [STU spFormat sp (AddrRegImm sp (ImmInt (-delta))),
DELTA (-delta)]
| otherwise = nilOL
where delta = stackDelta finalStack
move_sp_up finalStack
| delta > stackFrameHeaderSize dflags =
toOL [ADD sp sp (RIImm (ImmInt delta)),
DELTA 0]
| otherwise = nilOL
where delta = stackDelta finalStack
-- A NOP instruction is required after a call (bl instruction)
-- on AIX and 64-Bit Linux.
-- If the call is to a function with a different TOC (r2) the
-- link editor replaces the NOP instruction with a load of the TOC
-- from the stack to restore the TOC.
maybeNOP = case gcp of
-- See Section 3.9.4 of OpenPower ABI
GCPAIX -> unitOL NOP
-- See Section 3.5.11 of PPC64 ELF v1.9
GCPLinux64ELF 1 -> unitOL NOP
-- See Section 2.3.6 of PPC64 ELF v2
GCPLinux64ELF 2 -> unitOL NOP
_ -> nilOL
passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
passArguments ((arg,arg_ty):args) gprs fprs stackOffset
accumCode accumUsed | isWord64 arg_ty
&& target32Bit (targetPlatform dflags) =
do
ChildCode64 code vr_lo <- iselExpr64 arg
let vr_hi = getHiVRegFromLo vr_lo
case gcp of
GCPAIX -> -- same as for Darwin
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPDarwin ->
do let storeWord vr (gpr:_) _ = MR gpr vr
storeWord vr [] offset
= ST II32 vr (AddrRegImm sp (ImmInt offset))
passArguments args
(drop 2 gprs)
fprs
(stackOffset+8)
(accumCode `appOL` code
`snocOL` storeWord vr_hi gprs stackOffset
`snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
((take 2 gprs) ++ accumUsed)
GCPLinux ->
do let stackOffset' = roundTo 8 stackOffset
stackCode = accumCode `appOL` code
`snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
`snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
regCode hireg loreg =
accumCode `appOL` code
`snocOL` MR hireg vr_hi
`snocOL` MR loreg vr_lo
case gprs of
hireg : loreg : regs | even (length gprs) ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_skipped : hireg : loreg : regs ->
passArguments args regs fprs stackOffset
(regCode hireg loreg) (hireg : loreg : accumUsed)
_ -> -- only one or no regs left
passArguments args [] fprs (stackOffset'+8)
stackCode accumUsed
GCPLinux64ELF _ -> panic "passArguments: 32 bit code"
passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
| reg : _ <- regs = do
register <- getRegister arg
let code = case register of
Fixed _ freg fcode -> fcode `snocOL` MR reg freg
Any _ acode -> acode reg
stackOffsetRes = case gcp of
-- The Darwin ABI requires that we reserve
-- stack slots for register parameters
GCPDarwin -> stackOffset + stackBytes
-- ... so does the PowerOpen ABI.
GCPAIX -> stackOffset + stackBytes
-- ... the SysV ABI 32-bit doesn't.
GCPLinux -> stackOffset
-- ... but SysV ABI 64-bit does.
GCPLinux64ELF _ -> stackOffset + stackBytes
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
stackOffsetRes
(accumCode `appOL` code)
(reg : accumUsed)
| otherwise = do
(vr, code) <- getSomeReg arg
passArguments args
(drop nGprs gprs)
(drop nFprs fprs)
(stackOffset' + stackBytes)
(accumCode `appOL` code `snocOL` ST (cmmTypeFormat rep) vr stackSlot)
accumUsed
where
stackOffset' = case gcp of
GCPDarwin ->
-- stackOffset is at least 4-byte aligned
-- The Darwin ABI is happy with that.
stackOffset
GCPAIX ->
-- The 32bit PowerOPEN ABI is happy with
-- 32bit-alignment as well...
stackOffset
GCPLinux
-- ... the SysV ABI requires 8-byte
-- alignment for doubles.
| isFloatType rep && typeWidth rep == W64 ->
roundTo 8 stackOffset
| otherwise ->
stackOffset
GCPLinux64ELF _ ->
-- Everything on the stack is mapped to
-- 8-byte aligned doublewords
stackOffset
stackOffset''
| isFloatType rep && typeWidth rep == W32 =
case gcp of
-- The ELF v1 ABI Section 3.2.3 requires:
-- "Single precision floating point values
-- are mapped to the second word in a single
-- doubleword"
GCPLinux64ELF 1 -> stackOffset' + 4
_ -> stackOffset'
| otherwise = stackOffset'
stackSlot = AddrRegImm sp (ImmInt stackOffset'')
(nGprs, nFprs, stackBytes, regs)
= case gcp of
GCPAIX ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The PowerOpen ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
--
-- E.g. for a `double` two GPRs are skipped,
-- whereas for a `float` one GPR is skipped
-- when parameters are assigned to
-- registers.
--
-- The PowerOpen ABI specification can be found at
-- ftp://www.sourceware.org/pub/binutils/ppc-docs/ppc-poweropen/
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPDarwin ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- The Darwin ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 4, fprs)
FF64 -> (2, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux ->
case cmmTypeFormat rep of
II8 -> (1, 0, 4, gprs)
II16 -> (1, 0, 4, gprs)
II32 -> (1, 0, 4, gprs)
-- ... the SysV ABI doesn't.
FF32 -> (0, 1, 4, fprs)
FF64 -> (0, 1, 8, fprs)
II64 -> panic "genCCall' passArguments II64"
FF80 -> panic "genCCall' passArguments FF80"
GCPLinux64ELF _ ->
case cmmTypeFormat rep of
II8 -> (1, 0, 8, gprs)
II16 -> (1, 0, 8, gprs)
II32 -> (1, 0, 8, gprs)
II64 -> (1, 0, 8, gprs)
-- The ELFv1 ABI requires that we skip a
-- corresponding number of GPRs when we use
-- the FPRs.
FF32 -> (1, 1, 8, fprs)
FF64 -> (1, 1, 8, fprs)
FF80 -> panic "genCCall' passArguments FF80"
moveResult reduceToFF32 =
case dest_regs of
[] -> nilOL
[dest]
| reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1)
| isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1)
| isWord64 rep && target32Bit (targetPlatform dflags)
-> toOL [MR (getHiVRegFromLo r_dest) r3,
MR r_dest r4]
| otherwise -> unitOL (MR r_dest r3)
where rep = cmmRegType dflags (CmmLocal dest)
r_dest = getRegisterReg platform (CmmLocal dest)
_ -> panic "genCCall' moveResult: Bad dest_regs"
outOfLineMachOp mop =
do
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference $
mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction
let mopLabelOrExpr = case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return (mopLabelOrExpr, reduce)
where
(functionName, reduce) = case mop of
MO_F32_Exp -> (fsLit "exp", True)
MO_F32_Log -> (fsLit "log", True)
MO_F32_Sqrt -> (fsLit "sqrt", True)
MO_F32_Fabs -> unsupported
MO_F32_Sin -> (fsLit "sin", True)
MO_F32_Cos -> (fsLit "cos", True)
MO_F32_Tan -> (fsLit "tan", True)
MO_F32_Asin -> (fsLit "asin", True)
MO_F32_Acos -> (fsLit "acos", True)
MO_F32_Atan -> (fsLit "atan", True)
MO_F32_Sinh -> (fsLit "sinh", True)
MO_F32_Cosh -> (fsLit "cosh", True)
MO_F32_Tanh -> (fsLit "tanh", True)
MO_F32_Pwr -> (fsLit "pow", True)
MO_F64_Exp -> (fsLit "exp", False)
MO_F64_Log -> (fsLit "log", False)
MO_F64_Sqrt -> (fsLit "sqrt", False)
MO_F64_Fabs -> unsupported
MO_F64_Sin -> (fsLit "sin", False)
MO_F64_Cos -> (fsLit "cos", False)
MO_F64_Tan -> (fsLit "tan", False)
MO_F64_Asin -> (fsLit "asin", False)
MO_F64_Acos -> (fsLit "acos", False)
MO_F64_Atan -> (fsLit "atan", False)
MO_F64_Sinh -> (fsLit "sinh", False)
MO_F64_Cosh -> (fsLit "cosh", False)
MO_F64_Tanh -> (fsLit "tanh", False)
MO_F64_Pwr -> (fsLit "pow", False)
MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False)
MO_Memcpy _ -> (fsLit "memcpy", False)
MO_Memset _ -> (fsLit "memset", False)
MO_Memmove _ -> (fsLit "memmove", False)
MO_Memcmp _ -> (fsLit "memcmp", False)
MO_BSwap w -> (fsLit $ bSwapLabel w, False)
MO_PopCnt w -> (fsLit $ popCntLabel w, False)
MO_Pdep w -> (fsLit $ pdepLabel w, False)
MO_Pext w -> (fsLit $ pextLabel w, False)
MO_Clz _ -> unsupported
MO_Ctz _ -> unsupported
MO_AtomicRMW {} -> unsupported
MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False)
MO_AtomicRead _ -> unsupported
MO_AtomicWrite _ -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
MO_Prefetch_Data _ -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| OSAIX <- platformOS (targetPlatform dflags)
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
LD fmt tmp (AddrRegReg tableReg tmp),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| (positionIndependent dflags) || (not $ target32Bit $ targetPlatform dflags)
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let code = e_code `appOL` t_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
LD fmt tmp (AddrRegReg tableReg tmp),
ADD tmp tmp (RIReg tableReg),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
| otherwise
= do
(reg,e_code) <- getSomeReg (cmmOffset dflags expr offset)
let fmt = archWordFormat $ target32Bit $ targetPlatform dflags
sha = if target32Bit $ targetPlatform dflags then 2 else 3
tmp <- getNewRegNat fmt
lbl <- getNewLabelNat
let code = e_code `appOL` toOL [
SL fmt tmp reg (RIImm (ImmInt sha)),
ADDIS tmp tmp (HA (ImmCLbl lbl)),
LD fmt tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
MTCTR tmp,
BCTR ids (Just lbl)
]
return code
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (BCTR ids (Just lbl)) =
let jumpTable
| (positionIndependent dflags)
|| (not $ target32Bit $ targetPlatform dflags)
= map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
where jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = blockLbl blockid
in Just (CmmData (Section ReadOnlyData lbl) (Statics lbl jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condReg :: NatM CondCode -> NatM Register
condReg getCond = do
CondCode _ cond cond_code <- getCond
dflags <- getDynFlags
let
code dst = cond_code
`appOL` negate_code
`appOL` toOL [
MFCR dst,
RLWINM dst dst (bit + 1) 31 31
]
negate_code | do_negate = unitOL (CRNOR bit bit bit)
| otherwise = nilOL
(bit, do_negate) = case cond of
LTT -> (0, False)
LE -> (1, True)
EQQ -> (2, False)
GE -> (0, True)
GTT -> (1, False)
NE -> (2, True)
LU -> (0, False)
LEU -> (1, True)
GEU -> (0, True)
GU -> (1, False)
_ -> panic "PPC.CodeGen.codeReg: no match"
format = archWordFormat $ target32Bit $ targetPlatform dflags
return (Any format code)
condIntReg cond x y = condReg (condIntCode cond x y)
condFltReg cond x y = condReg (condFltCode cond x y)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
Wolfgang's PowerPC version of The Rules:
A slightly modified version of The Rules to take advantage of the fact
that PowerPC instructions work on all registers and don't implicitly
clobber any fixed registers.
* The only expression for which getRegister returns Fixed is (CmmReg reg).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
It may *not* modify global registers, unless the global
register happens to be the destination register.
It may not clobber any other registers. In fact, only ccalls clobber any
fixed registers.
Also, it may not modify the counter register (used by genCCall).
Corollary: If a getRegister for a subexpression returns Fixed, you need
not move it to a fresh temporary before evaluating the next subexpression.
The Fixed register won't be modified.
Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
* SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
the value of the destination register.
-}
trivialCode
:: Width
-> Bool
-> (Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
trivialCode rep signed instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate rep signed y
= do
(src1, code1) <- getSomeReg x
let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
return (Any (intFormat rep) code)
trivialCode rep _ instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
return (Any (intFormat rep) code)
shiftMulCode
:: Width
-> Bool
-> (Format-> Reg -> Reg -> RI -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
shiftMulCode width sign instr x (CmmLit (CmmInt y _))
| Just imm <- makeImmediate width sign y
= do
(src1, code1) <- getSomeReg x
let format = intFormat width
let code dst = code1 `snocOL` instr format dst src1 (RIImm imm)
return (Any format code)
shiftMulCode width _ instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let format = intFormat width
let code dst = code1 `appOL` code2 `snocOL` instr format dst src1 (RIReg src2)
return (Any format code)
trivialCodeNoImm' :: Format -> (Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm' format instr x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
return (Any format code)
trivialCodeNoImm :: Format -> (Format -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImm format instr x y = trivialCodeNoImm' format (instr format) x y
trivialCodeNoImmSign :: Format -> Bool
-> (Format -> Bool -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCodeNoImmSign format sgn instr x y
= trivialCodeNoImm' format (instr format sgn) x y
trivialUCode
:: Format
-> (Reg -> Reg -> Instr)
-> CmmExpr
-> NatM Register
trivialUCode rep instr x = do
(src, code) <- getSomeReg x
let code' dst = code `snocOL` instr dst src
return (Any rep code')
-- There is no "remainder" instruction on the PPC, so we have to do
-- it the hard way.
-- The "sgn" parameter is the signedness for the division instruction
remainderCode :: Width -> Bool -> CmmExpr -> CmmExpr -> NatM Register
remainderCode rep sgn x y = do
let fmt = intFormat rep
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let code dst = code1 `appOL` code2 `appOL` toOL [
DIV fmt sgn dst src1 src2,
MULL fmt dst dst (RIReg src2),
SUBF dst dst src1
]
return (Any (intFormat rep) code)
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceInt2FP' arch fromRep toRep x
coerceInt2FP' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP' ArchPPC fromRep toRep x = do
(src, code) <- getSomeReg x
lbl <- getNewLabelNat
itmp <- getNewRegNat II32
ftmp <- getNewRegNat FF64
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
Amode addr addr_code <- getAmode D dynRef
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
LDATA (Section ReadOnlyData lbl) $ Statics lbl
[CmmStaticLit (CmmInt 0x43300000 W32),
CmmStaticLit (CmmInt 0x80000000 W32)],
XORIS itmp src (ImmInt 0x8000),
ST II32 itmp (spRel dflags 3),
LIS itmp (ImmInt 0x4330),
ST II32 itmp (spRel dflags 2),
LD FF64 ftmp (spRel dflags 2)
] `appOL` addr_code `appOL` toOL [
LD FF64 dst addr,
FSUB FF64 dst ftmp dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
-- On an ELF v1 Linux we use the compiler doubleword in the stack frame
-- this is the TOC pointer doubleword on ELF v2 Linux. The latter is only
-- set right before a call and restored right after return from the call.
-- So it is fine.
coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do
(src, code) <- getSomeReg x
dflags <- getDynFlags
let
code' dst = code `appOL` maybe_exts `appOL` toOL [
ST II64 src (spRel dflags 3),
LD FF64 dst (spRel dflags 3),
FCFID dst dst
] `appOL` maybe_frsp dst
maybe_exts = case fromRep of
W8 -> unitOL $ EXTS II8 src src
W16 -> unitOL $ EXTS II16 src src
W32 -> unitOL $ EXTS II32 src src
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
maybe_frsp dst
= case toRep of
W32 -> unitOL $ FRSP dst dst
W64 -> nilOL
_ -> panic "PPC.CodeGen.coerceInt2FP: no match"
return (Any (floatFormat toRep) code')
coerceInt2FP' _ _ _ _ = panic "PPC.CodeGen.coerceInt2FP: unknown arch"
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int fromRep toRep x = do
dflags <- getDynFlags
let arch = platformArch $ targetPlatform dflags
coerceFP2Int' arch fromRep toRep x
coerceFP2Int' :: Arch -> Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int' ArchPPC _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II32->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIWZ tmp src,
-- store value (64bit) from FP to stack
ST FF64 tmp (spRel dflags 2),
-- read low word of value (high word is undefined)
LD II32 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' (ArchPPC_64 _) _ toRep x = do
dflags <- getDynFlags
-- the reps don't really matter: F*->FF64 and II64->I* are no-ops
(src, code) <- getSomeReg x
tmp <- getNewRegNat FF64
let
code' dst = code `appOL` toOL [
-- convert to int in FP reg
FCTIDZ tmp src,
-- store value (64bit) from FP to compiler word on stack
ST FF64 tmp (spRel dflags 3),
LD II64 dst (spRel dflags 3)]
return (Any (intFormat toRep) code')
coerceFP2Int' _ _ _ _ = panic "PPC.CodeGen.coerceFP2Int: unknown arch"
-- Note [.LCTOC1 in PPC PIC code]
-- The .LCTOC1 label is defined to point 32768 bytes into the GOT table
-- to make the most of the PPC's 16-bit displacements.
-- As 16-bit signed offset is used (usually via addi/lwz instructions)
-- first element will have '-32768' offset against .LCTOC1.
-- Note [implicit register in PPC PIC code]
-- PPC generates calls by labels in assembly
-- in form of:
-- bl puts+32768@plt
-- in this form it's not seen directly (by GHC NCG)
-- that r30 (PicBaseReg) is used,
-- but r30 is a required part of PLT code setup:
-- puts+32768@plt:
-- lwz r11,-30484(r30) ; offset in .LCTOC1
-- mtctr r11
-- bctr
| shlevy/ghc | compiler/nativeGen/PPC/CodeGen.hs | bsd-3-clause | 102,542 | 0 | 30 | 40,522 | 24,696 | 12,241 | 12,455 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Util.Proxy.Tests (tests) where
------------------------------------------------------------------------------
import Control.Monad.State.Strict (modify)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.CaseInsensitive (CI (..))
import qualified Data.Map as Map
import Snap.Core (Request (rqClientAddr, rqClientPort), Snap, rqRemotePort, withRequest)
import Snap.Test (RequestBuilder, evalHandler, get, setHeader)
import Snap.Test.Common (coverEqInstance, coverOrdInstance, coverReadInstance, coverShowInstance)
import Snap.Util.Proxy (ProxyType (NoProxy, X_Forwarded_For), behindProxy)
import Test.Framework (Test)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertEqual)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testNoProxy
, testForwardedFor
, testTrivials
]
---------------
-- Constants --
---------------
------------------------------------------------------------------------------
initialPort :: Int
initialPort = 9999
initialAddr :: ByteString
initialAddr = "127.0.0.1"
-----------
-- Tests --
-----------
------------------------------------------------------------------------------
testNoProxy :: Test
testNoProxy = testCase "proxy/no-proxy" $ do
a <- evalHandler (mkReq $ forwardedFor ["4.3.2.1"])
(behindProxy NoProxy reportRemoteAddr)
p <- evalHandler (mkReq $ forwardedFor ["4.3.2.1"] >> xForwardedPort [10903])
(behindProxy NoProxy reportRemotePort)
assertEqual "NoProxy leaves request alone" initialAddr a
assertEqual "NoProxy leaves request alone" initialPort p
--------------------------------------------------------------------------
b <- evalHandler (mkReq $ xForwardedFor ["2fe3::d4"])
(behindProxy NoProxy reportRemoteAddr)
assertEqual "NoProxy leaves request alone" initialAddr b
--------------------------------------------------------------------------
c <- evalHandler (mkReq $ return ())
(behindProxy NoProxy reportRemoteAddr)
assertEqual "NoProxy leaves request alone" initialAddr c
------------------------------------------------------------------------------
testForwardedFor :: Test
testForwardedFor = testCase "proxy/forwarded-for" $ do
(a,p) <- evalHandler (mkReq $ return ()) handler
assertEqual "No Forwarded-For, no change" initialAddr a
assertEqual "port" initialPort p
--------------------------------------------------------------------------
(b,q) <- evalHandler (mkReq $ forwardedFor [ip4]) handler
assertEqual "Behind 5.6.7.8" ip4 b
assertEqual "No Forwarded-Port, no port change" initialPort q
--------------------------------------------------------------------------
(c,_) <- evalHandler (mkReq $ xForwardedFor [ip4, ip6]) handler
assertEqual "Behind 23fe::d4" ip6 c
--------------------------------------------------------------------------
(d,r) <- evalHandler (mkReq $ xForwardedFor [ip6, ip4] >> xForwardedPort [20202, port]) handler
assertEqual "Behind 5.6.7.8" ip4 d
assertEqual "port change" port r
where
handler = behindProxy X_Forwarded_For $ do
!a <- reportRemoteAddr
!p <- reportRemotePort'
return $! (a,p)
ip4 = "5.6.7.8"
ip6 = "23fe::d4"
port = 10101
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "proxy/trivials" $ do
coverShowInstance NoProxy
coverReadInstance NoProxy
coverEqInstance NoProxy
coverOrdInstance NoProxy
---------------
-- Functions --
---------------
------------------------------------------------------------------------------
mkReq :: RequestBuilder IO () -> RequestBuilder IO ()
mkReq m = do
get "/" Map.empty
modify $ \req -> req { rqClientAddr = initialAddr
, rqClientPort = initialPort
}
m
------------------------------------------------------------------------------
reportRemoteAddr :: Snap ByteString
reportRemoteAddr = withRequest $ \req -> return $ rqClientAddr req
------------------------------------------------------------------------------
reportRemotePort :: Snap Int
reportRemotePort = withRequest $ \req -> return $ rqClientPort req
------------------------------------------------------------------------------
-- Cover deprecated rqRemotePort
reportRemotePort' :: Snap Int
reportRemotePort' = withRequest $ \req -> return $ rqRemotePort req
------------------------------------------------------------------------------
forwardedFor' :: CI ByteString -- ^ header name
-> [ByteString] -- ^ list of "forwarded-for"
-> RequestBuilder IO ()
forwardedFor' hdr addrs =
setHeader hdr $ S.intercalate ", " addrs
------------------------------------------------------------------------------
forwardedFor :: [ByteString]
-> RequestBuilder IO ()
forwardedFor = forwardedFor' "Forwarded-For"
------------------------------------------------------------------------------
xForwardedFor :: [ByteString]
-> RequestBuilder IO ()
xForwardedFor = forwardedFor' "X-Forwarded-For"
------------------------------------------------------------------------------
xForwardedPort :: [Int] -- ^ list of "forwarded-port"
-> RequestBuilder IO ()
xForwardedPort ports =
setHeader "X-Forwarded-Port" $ S.intercalate ", " $ map (S.pack . show) $ ports
| snapframework/snap-core | test/Snap/Util/Proxy/Tests.hs | bsd-3-clause | 6,436 | 0 | 14 | 1,584 | 1,107 | 595 | 512 | 91 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2010
--
-- The Session type and related functionality
--
-- -----------------------------------------------------------------------------
module Eta.Main.GhcMonad (
-- * 'Ghc' monad stuff
GhcMonad(..),
Ghc(..),
GhcT(..), liftGhcT,
reflectGhc, reifyGhc,
getSessionDynFlags,
liftIO,
Session(..), withSession, modifySession, withTempSession,
-- ** Warnings
logWarnings, printException,
WarnErrLogger, defaultWarnErrLogger
) where
import Eta.Utils.MonadUtils
import Eta.Main.HscTypes
import Eta.Main.DynFlags
import Eta.Utils.Exception
import Eta.Main.ErrUtils
import Data.IORef
-- -----------------------------------------------------------------------------
-- | A monad that has all the features needed by GHC API calls.
--
-- In short, a GHC monad
--
-- - allows embedding of IO actions,
--
-- - can log warnings,
--
-- - allows handling of (extensible) exceptions, and
--
-- - maintains a current session.
--
-- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad'
-- before any call to the GHC API functions can occur.
--
class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where
getSession :: m HscEnv
setSession :: HscEnv -> m ()
-- | Call the argument with the current session.
withSession :: GhcMonad m => (HscEnv -> m a) -> m a
withSession f = getSession >>= f
-- | Grabs the DynFlags from the Session
getSessionDynFlags :: GhcMonad m => m DynFlags
getSessionDynFlags = withSession (return . hsc_dflags)
-- | Set the current session to the result of applying the current session to
-- the argument.
modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m ()
modifySession f = do h <- getSession
setSession $! f h
withSavedSession :: GhcMonad m => m a -> m a
withSavedSession m = do
saved_session <- getSession
m `gfinally` setSession saved_session
-- | Call an action with a temporarily modified Session.
withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a
withTempSession f m =
withSavedSession $ modifySession f >> m
-- -----------------------------------------------------------------------------
-- | A monad that allows logging of warnings.
logWarnings :: GhcMonad m => WarningMessages -> m ()
logWarnings warns = do
dflags <- getSessionDynFlags
liftIO $ printOrThrowWarnings dflags warns
-- -----------------------------------------------------------------------------
-- | A minimal implementation of a 'GhcMonad'. If you need a custom monad,
-- e.g., to maintain additional state consider wrapping this monad or using
-- 'GhcT'.
newtype Ghc a = Ghc { unGhc :: Session -> IO a }
-- | The Session is a handle to the complete state of a compilation
-- session. A compilation session consists of a set of modules
-- constituting the current program or library, the context for
-- interactive evaluation, and various caches.
data Session = Session !(IORef HscEnv)
instance Functor Ghc where
fmap f m = Ghc $ \s -> f `fmap` unGhc m s
instance Applicative Ghc where
pure = return
g <*> m = do f <- g; a <- m; return (f a)
instance Monad Ghc where
return a = Ghc $ \_ -> return a
m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s
instance MonadIO Ghc where
liftIO ioA = Ghc $ \_ -> ioA
instance MonadFix Ghc where
mfix f = Ghc $ \s -> mfix (\x -> unGhc (f x) s)
instance ExceptionMonad Ghc where
gcatch act handle =
Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s
gmask f =
Ghc $ \s -> gmask $ \io_restore ->
let
g_restore (Ghc m) = Ghc $ \s -> io_restore (m s)
in
unGhc (f g_restore) s
instance HasDynFlags Ghc where
getDynFlags = getSessionDynFlags
instance GhcMonad Ghc where
getSession = Ghc $ \(Session r) -> readIORef r
setSession s' = Ghc $ \(Session r) -> writeIORef r s'
-- | Reflect a computation in the 'Ghc' monad into the 'IO' monad.
--
-- You can use this to call functions returning an action in the 'Ghc' monad
-- inside an 'IO' action. This is needed for some (too restrictive) callback
-- arguments of some library functions:
--
-- > libFunc :: String -> (Int -> IO a) -> IO a
-- > ghcFunc :: Int -> Ghc a
-- >
-- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a
-- > ghcFuncUsingLibFunc str =
-- > reifyGhc $ \s ->
-- > libFunc $ \i -> do
-- > reflectGhc (ghcFunc i) s
--
reflectGhc :: Ghc a -> Session -> IO a
reflectGhc m = unGhc m
-- > Dual to 'reflectGhc'. See its documentation.
reifyGhc :: (Session -> IO a) -> Ghc a
reifyGhc act = Ghc $ act
-- -----------------------------------------------------------------------------
-- | A monad transformer to add GHC specific features to another monad.
--
-- Note that the wrapped monad must support IO and handling of exceptions.
newtype GhcT m a = GhcT { unGhcT :: Session -> m a }
liftGhcT :: Monad m => m a -> GhcT m a
liftGhcT m = GhcT $ \_ -> m
instance Functor m => Functor (GhcT m) where
fmap f m = GhcT $ \s -> f `fmap` unGhcT m s
instance Applicative m => Applicative (GhcT m) where
pure x = GhcT $ \_ -> pure x
g <*> m = GhcT $ \s -> unGhcT g s <*> unGhcT m s
instance Monad m => Monad (GhcT m) where
return x = GhcT $ \_ -> return x
m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s
instance MonadIO m => MonadIO (GhcT m) where
liftIO ioA = GhcT $ \_ -> liftIO ioA
instance ExceptionMonad m => ExceptionMonad (GhcT m) where
gcatch act handle =
GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s
gmask f =
GhcT $ \s -> gmask $ \io_restore ->
let
g_restore (GhcT m) = GhcT $ \s -> io_restore (m s)
in
unGhcT (f g_restore) s
instance (Functor m, ExceptionMonad m, MonadIO m) => HasDynFlags (GhcT m) where
getDynFlags = getSessionDynFlags
instance (Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) where
getSession = GhcT $ \(Session r) -> liftIO $ readIORef r
setSession s' = GhcT $ \(Session r) -> liftIO $ writeIORef r s'
-- | Print the error message and all warnings. Useful inside exception
-- handlers. Clears warnings after printing.
printException :: GhcMonad m => SourceError -> m ()
printException err = do
dflags <- getSessionDynFlags
liftIO $ printBagOfErrors dflags (srcErrorMessages err)
-- | A function called to log warnings and errors.
type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m ()
defaultWarnErrLogger :: WarnErrLogger
defaultWarnErrLogger Nothing = return ()
defaultWarnErrLogger (Just e) = printException e
| rahulmutt/ghcvm | compiler/Eta/Main/GhcMonad.hs | bsd-3-clause | 6,934 | 0 | 18 | 1,622 | 1,758 | 925 | 833 | 106 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.S3.GetBucketLocation
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns the region the bucket resides in.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketLocation.html>
module Network.AWS.S3.GetBucketLocation
(
-- * Request
GetBucketLocation
-- ** Request constructor
, getBucketLocation
-- ** Request lenses
, gblBucket
-- * Response
, GetBucketLocationResponse
-- ** Response constructor
, getBucketLocationResponse
-- ** Response lenses
, gblrLocationConstraint
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
newtype GetBucketLocation = GetBucketLocation
{ _gblBucket :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetBucketLocation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gblBucket' @::@ 'Text'
--
getBucketLocation :: Text -- ^ 'gblBucket'
-> GetBucketLocation
getBucketLocation p1 = GetBucketLocation
{ _gblBucket = p1
}
gblBucket :: Lens' GetBucketLocation Text
gblBucket = lens _gblBucket (\s a -> s { _gblBucket = a })
newtype GetBucketLocationResponse = GetBucketLocationResponse
{ _gblrLocationConstraint :: Maybe Region
} deriving (Eq, Read, Show)
-- | 'GetBucketLocationResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gblrLocationConstraint' @::@ 'Maybe' 'Region'
--
getBucketLocationResponse :: GetBucketLocationResponse
getBucketLocationResponse = GetBucketLocationResponse
{ _gblrLocationConstraint = Nothing
}
gblrLocationConstraint :: Lens' GetBucketLocationResponse (Maybe Region)
gblrLocationConstraint =
lens _gblrLocationConstraint (\s a -> s { _gblrLocationConstraint = a })
instance ToPath GetBucketLocation where
toPath GetBucketLocation{..} = mconcat
[ "/"
, toText _gblBucket
]
instance ToQuery GetBucketLocation where
toQuery = const "location"
instance ToHeaders GetBucketLocation
instance ToXMLRoot GetBucketLocation where
toXMLRoot = const (namespaced ns "GetBucketLocation" [])
instance ToXML GetBucketLocation
instance AWSRequest GetBucketLocation where
type Sv GetBucketLocation = S3
type Rs GetBucketLocation = GetBucketLocationResponse
request = get
response = xmlResponse
instance FromXML GetBucketLocationResponse where
parseXML x = GetBucketLocationResponse
<$> x .@? "LocationConstraint"
| romanb/amazonka | amazonka-s3/gen/Network/AWS/S3/GetBucketLocation.hs | mpl-2.0 | 3,491 | 0 | 9 | 745 | 445 | 268 | 177 | 58 | 1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
module Cryptol.ModuleSystem.Renamer (
NamingEnv(), shadowing
, BindsNames(..)
, checkNamingEnv
, Rename(..), runRenamer
, RenamerError(..)
, RenamerWarning(..)
) where
import Cryptol.ModuleSystem.NamingEnv
import Cryptol.Prims.Syntax
import Cryptol.Parser.AST
import Cryptol.Parser.Names (tnamesP)
import Cryptol.Parser.Position
import Cryptol.Utils.Panic (panic)
import Cryptol.Utils.PP
import MonadLib
import qualified Data.Map as Map
import GHC.Generics (Generic)
import Control.DeepSeq
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative(Applicative(..),(<$>))
import Data.Foldable (foldMap)
import Data.Monoid (Monoid(..))
import Data.Traversable (traverse)
#endif
-- Errors ----------------------------------------------------------------------
data RenamerError
= MultipleSyms (Located QName) [NameOrigin]
-- ^ Multiple imported symbols contain this name
| UnboundExpr (Located QName)
-- ^ Expression name is not bound to any definition
| UnboundType (Located QName)
-- ^ Type name is not bound to any definition
| OverlappingSyms [NameOrigin]
-- ^ An environment has produced multiple overlapping symbols
| ExpectedValue (Located QName)
-- ^ When a value is expected from the naming environment, but one or more
-- types exist instead.
| ExpectedType (Located QName)
-- ^ When a type is missing from the naming environment, but one or more
-- values exist with the same name.
| FixityError (Located QName) (Located QName)
-- ^ When the fixity of two operators conflict
| InvalidConstraint Type
-- ^ When it's not possible to produce a Prop from a Type.
| MalformedConstraint (Located Type)
-- ^ When a constraint appears within another constraint
deriving (Show,Generic)
instance NFData RenamerError
instance PP RenamerError where
ppPrec _ e = case e of
MultipleSyms lqn qns ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 $ (text "Multiple definitions for symbol:" <+> pp (thing lqn))
$$ vcat (map pp qns)
UnboundExpr lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (text "Value not in scope:" <+> pp (thing lqn))
UnboundType lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (text "Type not in scope:" <+> pp (thing lqn))
OverlappingSyms qns ->
hang (text "[error]")
4 $ text "Overlapping symbols defined:"
$$ vcat (map pp qns)
ExpectedValue lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (fsep [ text "Expected a value named", quotes (pp (thing lqn))
, text "but found a type instead"
, text "Did you mean `(" <> pp (thing lqn) <> text")?" ])
ExpectedType lqn ->
hang (text "[error] at" <+> pp (srcRange lqn))
4 (fsep [ text "Expected a type named", quotes (pp (thing lqn))
, text "but found a value instead" ])
FixityError o1 o2 ->
hang (text "[error]")
4 (fsep [ text "The fixities of", pp o1, text "and", pp o2
, text "are not compatible. "
, text "You may use explicit parenthesis to disambiguate" ])
InvalidConstraint ty ->
hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) (getLoc ty))
4 (fsep [ pp ty, text "is not a valid constraint" ])
MalformedConstraint t ->
hang (text "[error] at" <+> pp (srcRange t))
4 (sep [ quotes (pp (thing t))
, text "is not a valid argument to a constraint" ])
-- Warnings --------------------------------------------------------------------
data RenamerWarning
= SymbolShadowed NameOrigin [NameOrigin]
deriving (Show,Generic)
instance NFData RenamerWarning
instance PP RenamerWarning where
ppPrec _ (SymbolShadowed new originals) =
hang (text "[warning] at" <+> loc)
4 $ fsep [ text "This binding for" <+> sym
, text "shadows the existing binding" <> plural <+> text "from" ]
$$ vcat (map pp originals)
where
plural | length originals > 1 = char 's'
| otherwise = empty
(loc,sym) = case new of
Local lqn -> (pp (srcRange lqn), pp (thing lqn))
Imported qn -> (empty, pp qn)
-- Renaming Monad --------------------------------------------------------------
data RO = RO
{ roLoc :: Range
, roNames :: NamingEnv
}
data Out = Out
{ oWarnings :: [RenamerWarning]
, oErrors :: [RenamerError]
} deriving (Show)
instance Monoid Out where
mempty = Out [] []
mappend l r = Out (oWarnings l `mappend` oWarnings r)
(oErrors l `mappend` oErrors r)
newtype RenameM a = RenameM
{ unRenameM :: ReaderT RO (WriterT Out Id) a }
instance Functor RenameM where
{-# INLINE fmap #-}
fmap f m = RenameM (fmap f (unRenameM m))
instance Applicative RenameM where
{-# INLINE pure #-}
pure x = RenameM (pure x)
{-# INLINE (<*>) #-}
l <*> r = RenameM (unRenameM l <*> unRenameM r)
instance Monad RenameM where
{-# INLINE return #-}
return x = RenameM (return x)
{-# INLINE (>>=) #-}
m >>= k = RenameM (unRenameM m >>= unRenameM . k)
runRenamer :: NamingEnv -> RenameM a
-> (Either [RenamerError] a,[RenamerWarning])
runRenamer env m = (res,oWarnings out)
where
(a,out) = runM (unRenameM m) RO { roLoc = emptyRange, roNames = env }
res | null (oErrors out) = Right a
| otherwise = Left (oErrors out)
record :: RenamerError -> RenameM ()
record err = records [err]
records :: [RenamerError] -> RenameM ()
records errs = RenameM (put mempty { oErrors = errs })
located :: a -> RenameM (Located a)
located a = RenameM $ do
ro <- ask
return Located { srcRange = roLoc ro, thing = a }
withLoc :: HasLoc loc => loc -> RenameM a -> RenameM a
withLoc loc m = RenameM $ case getLoc loc of
Just range -> do
ro <- ask
local ro { roLoc = range } (unRenameM m)
Nothing -> unRenameM m
-- | Shadow the current naming environment with some more names.
shadowNames :: BindsNames env => env -> RenameM a -> RenameM a
shadowNames names m = RenameM $ do
let env = namingEnv names
ro <- ask
put (checkEnv env (roNames ro))
let ro' = ro { roNames = env `shadowing` roNames ro }
local ro' (unRenameM m)
-- | Generate warnings when the left environment shadows things defined in
-- the right. Additionally, generate errors when two names overlap in the
-- left environment.
checkEnv :: NamingEnv -> NamingEnv -> Out
checkEnv l r = Map.foldlWithKey (step neExprs) mempty (neExprs l)
`mappend` Map.foldlWithKey (step neTypes) mempty (neTypes l)
where
step prj acc k ns = acc `mappend` mempty
{ oWarnings = case Map.lookup k (prj r) of
Nothing -> []
Just os -> [SymbolShadowed (origin (head ns)) (map origin os)]
, oErrors = containsOverlap ns
}
-- | Check the RHS of a single name rewrite for conflicting sources.
containsOverlap :: HasQName a => [a] -> [RenamerError]
containsOverlap [_] = []
containsOverlap [] = panic "Renamer" ["Invalid naming environment"]
containsOverlap ns = [OverlappingSyms (map origin ns)]
-- | Throw errors for any names that overlap in a rewrite environment.
checkNamingEnv :: NamingEnv -> ([RenamerError],[RenamerWarning])
checkNamingEnv env = (out, [])
where
out = Map.foldr check outTys (neExprs env)
outTys = Map.foldr check mempty (neTypes env)
check ns acc = containsOverlap ns ++ acc
-- Renaming --------------------------------------------------------------------
class Rename a where
rename :: a -> RenameM a
instance Rename a => Rename [a] where
rename = traverse rename
instance Rename a => Rename (Maybe a) where
rename = traverse rename
instance Rename a => Rename (Located a) where
rename loc = withLoc loc $ do
a' <- rename (thing loc)
return loc { thing = a' }
instance Rename a => Rename (Named a) where
rename n = do
a' <-rename (value n)
return n { value = a' }
instance Rename Module where
rename m = do
decls' <- rename (mDecls m)
return m { mDecls = decls' }
instance Rename TopDecl where
rename td = case td of
Decl d -> Decl <$> rename d
TDNewtype n -> TDNewtype <$> rename n
Include{} -> return td
instance Rename a => Rename (TopLevel a) where
rename tl = do
a' <- rename (tlValue tl)
return tl { tlValue = a' }
instance Rename Decl where
rename d = case d of
DSignature ns sig -> DSignature ns <$> rename sig
DPragma ns p -> DPragma ns <$> rename p
DBind b -> DBind <$> rename b
DPatBind pat e -> DPatBind pat <$> shadowNames (namingEnv pat) (rename e)
DType syn -> DType <$> rename syn
DLocated d' r -> withLoc r
$ DLocated <$> rename d' <*> pure r
DFixity{} -> panic "Renamer" ["Unexpected fixity declaration", show d]
instance Rename Newtype where
rename n = do
name' <- renameLoc renameType (nName n)
body' <- shadowNames (nParams n) (rename (nBody n))
return Newtype { nName = name'
, nParams = nParams n
, nBody = body' }
renameVar :: QName -> RenameM QName
renameVar qn = do
ro <- RenameM ask
case Map.lookup qn (neExprs (roNames ro)) of
Just [en] -> return (qname en)
Just [] ->
panic "Renamer" ["Invalid expression renaming environment"]
Just syms ->
do n <- located qn
record (MultipleSyms n (map origin syms))
return qn
Nothing ->
do n <- located qn
case Map.lookup qn (neTypes (roNames ro)) of
-- types existed with the name of the value expected
Just _ -> record (ExpectedValue n)
-- the value is just missing
Nothing -> record (UnboundExpr n)
return qn
renameType :: QName -> RenameM QName
renameType qn = do
ro <- RenameM ask
case Map.lookup qn (neTypes (roNames ro)) of
Just [tn] -> return (qname tn)
Just [] -> panic "Renamer" ["Invalid type renaming environment"]
Just syms ->
do n <- located qn
record (MultipleSyms n (map origin syms))
return qn
Nothing ->
do n <- located qn
case Map.lookup qn (neExprs (roNames ro)) of
-- values exist with the same name, so throw a different error
Just _ -> record (ExpectedType n)
-- no terms with the same name, so the type is just unbound
Nothing -> record (UnboundType n)
return qn
-- | Rename a schema, assuming that none of its type variables are already in
-- scope.
instance Rename Schema where
rename s@(Forall ps _ _ _) = shadowNames ps (renameSchema s)
-- | Rename a schema, assuming that the type variables have already been brought
-- into scope.
renameSchema :: Schema -> RenameM Schema
renameSchema (Forall ps p ty loc) = Forall ps <$> rename p <*> rename ty
<*> pure loc
instance Rename Prop where
rename p = case p of
CFin t -> CFin <$> rename t
CEqual l r -> CEqual <$> rename l <*> rename r
CGeq l r -> CGeq <$> rename l <*> rename r
CArith t -> CArith <$> rename t
CCmp t -> CCmp <$> rename t
CLocated p' r -> withLoc r
$ CLocated <$> rename p' <*> pure r
-- here, we rename the type and then require that it produces something that
-- looks like a Prop
CType t -> translateProp t
translateProp :: Type -> RenameM Prop
translateProp ty = go =<< rnType True ty
where
go t = case t of
TLocated t' r -> (`CLocated` r) <$> go t'
TUser (QName Nothing p) [l,r]
| p == mkName "==" -> pure (CEqual l r)
| p == mkName ">=" -> pure (CGeq l r)
| p == mkName "<=" -> pure (CGeq r l)
_ ->
do record (InvalidConstraint ty)
return (CType t)
instance Rename Type where
rename = rnType False
rnType :: Bool -> Type -> RenameM Type
rnType isProp = go
where
go t = case t of
TFun a b -> TFun <$> go a <*> go b
TSeq n a -> TSeq <$> go n <*> go a
TBit -> return t
TNum _ -> return t
TChar _ -> return t
TInf -> return t
TUser (QName Nothing n) ps
| n == mkName "inf", null ps -> return TInf
| n == mkName "Bit", null ps -> return TBit
| n == mkName "min" -> TApp TCMin <$> traverse go ps
| n == mkName "max" -> TApp TCMax <$> traverse go ps
| n == mkName "lengthFromThen" -> TApp TCLenFromThen <$> traverse go ps
| n == mkName "lengthFromThenTo" -> TApp TCLenFromThenTo <$> traverse go ps
| n == mkName "width" -> TApp TCWidth <$> traverse go ps
-- This should only happen in error, as fin constraints are constructed
-- in the parser. (Cryptol.Parser.ParserUtils.mkProp)
| n == mkName "fin" && isProp ->
do locTy <- located t
record (MalformedConstraint locTy)
return t
TUser qn ps -> TUser <$> renameType qn <*> traverse go ps
TApp f xs -> TApp f <$> traverse go xs
TRecord fs -> TRecord <$> traverse (traverse go) fs
TTuple fs -> TTuple <$> traverse go fs
TWild -> return t
TLocated t' r -> withLoc r
$ TLocated <$> go t' <*> pure r
TParens t' -> TParens <$> go t'
TInfix a o _ b ->
do op <- renameTypeOp isProp o
a' <- go a
b' <- go b
mkTInfix isProp a' op b'
type TOp = Type -> Type -> Type
mkTInfix :: Bool -> Type -> (TOp,Fixity) -> Type -> RenameM Type
-- this should be one of the props, or an error, so just assume that its fixity
-- is `infix 0`.
mkTInfix True t@(TUser o1 [x,y]) op@(o2,f2) z =
do let f1 = Fixity NonAssoc 0
case compareFixity f1 f2 of
FCLeft -> return (o2 t z)
FCRight -> do r <- mkTInfix True y op z
return (TUser o1 [x,r])
-- Just reconstruct with the TUser part being an application. If this was
-- a real error, it will have been caught by now.
FCError -> return (o2 t z)
-- In this case, we know the fixities of both sides.
mkTInfix isProp t@(TApp o1 [x,y]) op@(o2,f2) z
| Just (a1,p1) <- Map.lookup o1 tBinOpPrec =
case compareFixity (Fixity a1 p1) f2 of
FCLeft -> return (o2 t z)
FCRight -> do r <- mkTInfix isProp y op z
return (TApp o1 [x,r])
-- As the fixity table is known, and this is a case where the fixity came
-- from that table, it's a real error if the fixities didn't work out.
FCError -> panic "Renamer" [ "fixity problem for type operators"
, show (o2 t z) ]
mkTInfix isProp (TLocated t _) op z =
mkTInfix isProp t op z
mkTInfix _ t (op,_) z =
return (op t z)
-- | Rename a type operator, mapping it to a real type function. When isProp is
-- True, it's assumed that the renaming is happening in the context of a Prop,
-- which allows unresolved operators to propagate without an error. They will
-- be resolved in the CType case for Prop.
renameTypeOp :: Bool -> Located QName -> RenameM (TOp,Fixity)
renameTypeOp isProp op =
do let sym = unqual (thing op)
props = [ mkName "==", mkName ">=", mkName "<=" ]
lkp = do n <- Map.lookup (thing op) tfunNames
(fAssoc,fLevel) <- Map.lookup n tBinOpPrec
return (n,Fixity { .. })
case lkp of
Just (p,f) ->
return (\x y -> TApp p [x,y], f)
Nothing
| isProp && sym `elem` props ->
return (\x y -> TUser (thing op) [x,y], Fixity NonAssoc 0)
| otherwise ->
do record (UnboundType op)
return (\x y -> TUser (thing op) [x,y], defaultFixity)
instance Rename Pragma where
rename p = case p of
PragmaNote _ -> return p
PragmaProperty -> return p
-- | The type renaming environment generated by a binding.
bindingTypeEnv :: Bind -> NamingEnv
bindingTypeEnv b = patParams `shadowing` sigParams
where
-- type parameters
sigParams = namingEnv (bSignature b)
-- pattern type parameters
patParams = foldMap (foldMap qualType . tnamesP) (bParams b)
qualType qn = singletonT qn (TFromParam qn)
-- | Rename a binding.
--
-- NOTE: this does not bind its own name into the naming context of its body.
-- The assumption here is that this has been done by the enclosing environment,
-- to allow for top-level renaming
instance Rename Bind where
rename b = do
n' <- renameLoc renameVar (bName b)
shadowNames (bindingTypeEnv b) $ do
(patenv,pats') <- renamePats (bParams b)
sig' <- traverse renameSchema (bSignature b)
shadowNames patenv $
do e' <- rename (bDef b)
p' <- rename (bPragmas b)
return b { bName = n'
, bParams = pats'
, bDef = e'
, bSignature = sig'
, bPragmas = p'
}
instance Rename BindDef where
rename DPrim = return DPrim
rename (DExpr e) = DExpr <$> rename e
-- NOTE: this only renames types within the pattern.
instance Rename Pattern where
rename p = case p of
PVar _ -> pure p
PWild -> pure p
PTuple ps -> PTuple <$> rename ps
PRecord nps -> PRecord <$> rename nps
PList elems -> PList <$> rename elems
PTyped p' t -> PTyped <$> rename p' <*> rename t
PSplit l r -> PSplit <$> rename l <*> rename r
PLocated p' loc -> withLoc loc
$ PLocated <$> rename p' <*> pure loc
instance Rename Expr where
rename e = case e of
EVar n -> EVar <$> renameVar n
ELit _ -> return e
ETuple es -> ETuple <$> rename es
ERecord fs -> ERecord <$> rename fs
ESel e' s -> ESel <$> rename e' <*> pure s
EList es -> EList <$> rename es
EFromTo s n e'-> EFromTo <$> rename s <*> rename n <*> rename e'
EInfFrom a b -> EInfFrom<$> rename a <*> rename b
EComp e' bs -> do bs' <- mapM renameMatch bs
shadowNames (namingEnv bs')
(EComp <$> rename e' <*> pure bs')
EApp f x -> EApp <$> rename f <*> rename x
EAppT f ti -> EAppT <$> rename f <*> rename ti
EIf b t f -> EIf <$> rename b <*> rename t <*> rename f
EWhere e' ds -> shadowNames ds (EWhere <$> rename e' <*> rename ds)
ETyped e' ty -> ETyped <$> rename e' <*> rename ty
ETypeVal ty -> ETypeVal<$> rename ty
EFun ps e' -> do ps' <- rename ps
shadowNames ps' (EFun ps' <$> rename e')
ELocated e' r -> withLoc r
$ ELocated <$> rename e' <*> pure r
EParens p -> EParens <$> rename p
EInfix x y _ z-> do op <- renameOp y
x' <- rename x
z' <- rename z
mkEInfix x' op z'
mkEInfix :: Expr -- ^ May contain infix expressions
-> (Located QName,Fixity) -- ^ The operator to use
-> Expr -- ^ Will not contain infix expressions
-> RenameM Expr
mkEInfix e@(EInfix x o1 f1 y) op@(o2,f2) z =
case compareFixity f1 f2 of
FCLeft -> return (EInfix e o2 f2 z)
FCRight -> do r <- mkEInfix y op z
return (EInfix x o1 f1 r)
FCError -> do record (FixityError o1 o2)
return (EInfix e o2 f2 z)
mkEInfix (ELocated e' _) op z =
mkEInfix e' op z
mkEInfix e (o,f) z =
return (EInfix e o f z)
renameOp :: Located QName -> RenameM (Located QName,Fixity)
renameOp ln = withLoc ln $
do n <- renameVar (thing ln)
ro <- RenameM ask
case Map.lookup n (neFixity (roNames ro)) of
Just [fixity] -> return (ln { thing = n },fixity)
_ -> return (ln { thing = n },defaultFixity)
instance Rename TypeInst where
rename ti = case ti of
NamedInst nty -> NamedInst <$> rename nty
PosInst ty -> PosInst <$> rename ty
renameMatch :: [Match] -> RenameM [Match]
renameMatch = loop
where
loop ms = case ms of
m:rest -> do
m' <- rename m
(m':) <$> shadowNames m' (loop rest)
[] -> return []
renamePats :: [Pattern] -> RenameM (NamingEnv,[Pattern])
renamePats = loop
where
loop ps = case ps of
p:rest -> do
p' <- rename p
let pe = namingEnv p'
(env',rest') <- loop rest
return (pe `mappend` env', p':rest')
[] -> return (mempty, [])
instance Rename Match where
rename m = case m of
Match p e -> Match <$> rename p <*> rename e
MatchLet b -> shadowNames b (MatchLet <$> rename b)
instance Rename TySyn where
rename (TySyn n ps ty) =
shadowNames ps (TySyn <$> renameLoc renameType n <*> pure ps <*> rename ty)
renameLoc :: (a -> RenameM b) -> Located a -> RenameM (Located b)
renameLoc by loc = do
a' <- by (thing loc)
return loc { thing = a' }
| beni55/cryptol | src/Cryptol/ModuleSystem/Renamer.hs | bsd-3-clause | 21,636 | 0 | 18 | 6,602 | 7,115 | 3,473 | 3,642 | 458 | 15 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation: the binding environment
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmEnv (
CgIdInfo,
litIdInfo, lneIdInfo, rhsIdInfo, mkRhsInit,
idInfoToAmode,
addBindC, addBindsC,
bindArgsToRegs, bindToReg, rebindToReg,
bindArgToReg, idToReg,
getArgAmode, getNonVoidArgAmodes,
getCgIdInfo,
maybeLetNoEscape,
) where
#include "HsVersions.h"
import TyCon
import StgCmmMonad
import StgCmmUtils
import StgCmmClosure
import CLabel
import BlockId
import CmmExpr
import CmmUtils
import DynFlags
import Id
import MkGraph
import Name
import Outputable
import StgSyn
import UniqFM
import VarEnv
-------------------------------------
-- Manipulating CgIdInfo
-------------------------------------
mkCgIdInfo :: Id -> LambdaFormInfo -> CmmExpr -> CgIdInfo
mkCgIdInfo id lf expr
= CgIdInfo { cg_id = id, cg_lf = lf
, cg_loc = CmmLoc expr }
litIdInfo :: DynFlags -> Id -> LambdaFormInfo -> CmmLit -> CgIdInfo
litIdInfo dflags id lf lit
= CgIdInfo { cg_id = id, cg_lf = lf
, cg_loc = CmmLoc (addDynTag dflags (CmmLit lit) tag) }
where
tag = lfDynTag dflags lf
lneIdInfo :: DynFlags -> Id -> [NonVoid Id] -> CgIdInfo
lneIdInfo dflags id regs
= CgIdInfo { cg_id = id, cg_lf = lf
, cg_loc = LneLoc blk_id (map (idToReg dflags) regs) }
where
lf = mkLFLetNoEscape
blk_id = mkBlockId (idUnique id)
rhsIdInfo :: Id -> LambdaFormInfo -> FCode (CgIdInfo, LocalReg)
rhsIdInfo id lf_info
= do dflags <- getDynFlags
reg <- newTemp (gcWord dflags)
return (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg)), reg)
mkRhsInit :: DynFlags -> LocalReg -> LambdaFormInfo -> CmmExpr -> CmmAGraph
mkRhsInit dflags reg lf_info expr
= mkAssign (CmmLocal reg) (addDynTag dflags expr (lfDynTag dflags lf_info))
idInfoToAmode :: CgIdInfo -> CmmExpr
-- Returns a CmmExpr for the *tagged* pointer
idInfoToAmode (CgIdInfo { cg_loc = CmmLoc e }) = e
idInfoToAmode cg_info
= pprPanic "idInfoToAmode" (ppr (cg_id cg_info)) -- LneLoc
addDynTag :: DynFlags -> CmmExpr -> DynTag -> CmmExpr
-- A tag adds a byte offset to the pointer
addDynTag dflags expr tag = cmmOffsetB dflags expr tag
maybeLetNoEscape :: CgIdInfo -> Maybe (BlockId, [LocalReg])
maybeLetNoEscape (CgIdInfo { cg_loc = LneLoc blk_id args}) = Just (blk_id, args)
maybeLetNoEscape _other = Nothing
---------------------------------------------------------
-- The binding environment
--
-- There are three basic routines, for adding (addBindC),
-- modifying(modifyBindC) and looking up (getCgIdInfo) bindings.
---------------------------------------------------------
addBindC :: CgIdInfo -> FCode ()
addBindC stuff_to_bind = do
binds <- getBinds
setBinds $ extendVarEnv binds (cg_id stuff_to_bind) stuff_to_bind
addBindsC :: [CgIdInfo] -> FCode ()
addBindsC new_bindings = do
binds <- getBinds
let new_binds = foldl (\ binds info -> extendVarEnv binds (cg_id info) info)
binds
new_bindings
setBinds new_binds
getCgIdInfo :: Id -> FCode CgIdInfo
getCgIdInfo id
= do { dflags <- getDynFlags
; local_binds <- getBinds -- Try local bindings first
; case lookupVarEnv local_binds id of {
Just info -> return info ;
Nothing -> do {
-- Should be imported; make up a CgIdInfo for it
let name = idName id
; if isExternalName name then
let ext_lbl = CmmLabel (mkClosureLabel name $ idCafInfo id)
in return (litIdInfo dflags id (mkLFImported id) ext_lbl)
else
cgLookupPanic id -- Bug
}}}
cgLookupPanic :: Id -> FCode a
cgLookupPanic id
= do local_binds <- getBinds
pprPanic "StgCmmEnv: variable not found"
(vcat [ppr id,
text "local binds for:",
pprUFM local_binds $ \infos ->
vcat [ ppr (cg_id info) | info <- infos ]
])
--------------------
getArgAmode :: NonVoid StgArg -> FCode CmmExpr
getArgAmode (NonVoid (StgVarArg var)) = idInfoToAmode <$> getCgIdInfo var
getArgAmode (NonVoid (StgLitArg lit)) = CmmLit <$> cgLit lit
getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr]
-- NB: Filters out void args,
-- so the result list may be shorter than the argument list
getNonVoidArgAmodes [] = return []
getNonVoidArgAmodes (arg:args)
| isVoidRep (argPrimRep arg) = getNonVoidArgAmodes args
| otherwise = do { amode <- getArgAmode (NonVoid arg)
; amodes <- getNonVoidArgAmodes args
; return ( amode : amodes ) }
------------------------------------------------------------------------
-- Interface functions for binding and re-binding names
------------------------------------------------------------------------
bindToReg :: NonVoid Id -> LambdaFormInfo -> FCode LocalReg
-- Bind an Id to a fresh LocalReg
bindToReg nvid@(NonVoid id) lf_info
= do dflags <- getDynFlags
let reg = idToReg dflags nvid
addBindC (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg)))
return reg
rebindToReg :: NonVoid Id -> FCode LocalReg
-- Like bindToReg, but the Id is already in scope, so
-- get its LF info from the envt
rebindToReg nvid@(NonVoid id)
= do { info <- getCgIdInfo id
; bindToReg nvid (cg_lf info) }
bindArgToReg :: NonVoid Id -> FCode LocalReg
bindArgToReg nvid@(NonVoid id) = bindToReg nvid (mkLFArgument id)
bindArgsToRegs :: [NonVoid Id] -> FCode [LocalReg]
bindArgsToRegs args = mapM bindArgToReg args
idToReg :: DynFlags -> NonVoid Id -> LocalReg
-- Make a register from an Id, typically a function argument,
-- free variable, or case binder
--
-- We re-use the Unique from the Id to make it easier to see what is going on
--
-- By now the Ids should be uniquely named; else one would worry
-- about accidental collision
idToReg dflags (NonVoid id)
= LocalReg (idUnique id)
(case idPrimRep id of VoidRep -> pprPanic "idToReg" (ppr id)
_ -> primRepCmmType dflags (idPrimRep id))
| olsner/ghc | compiler/codeGen/StgCmmEnv.hs | bsd-3-clause | 6,443 | 0 | 20 | 1,586 | 1,556 | 812 | 744 | 119 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE Trustworthy #-} -- can't use Safe due to IsList instance
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.List.NonEmpty
-- Copyright : (C) 2011-2015 Edward Kmett,
-- (C) 2010 Tony Morris, Oliver Taylor, Eelis van der Weegen
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- A 'NonEmpty' list is one which always has at least one element, but
-- is otherwise identical to the traditional list type in complexity
-- and in terms of API. You will almost certainly want to import this
-- module @qualified@.
--
-- @since 4.9.0.0
----------------------------------------------------------------------------
module Data.List.NonEmpty (
-- * The type of non-empty streams
NonEmpty(..)
-- * Non-empty stream transformations
, map -- :: (a -> b) -> NonEmpty a -> NonEmpty b
, intersperse -- :: a -> NonEmpty a -> NonEmpty a
, scanl -- :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b
, scanr -- :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b
, scanl1 -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a
, scanr1 -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a
, transpose -- :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a)
, sortBy -- :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a
, sortWith -- :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a
-- * Basic functions
, length -- :: NonEmpty a -> Int
, head -- :: NonEmpty a -> a
, tail -- :: NonEmpty a -> [a]
, last -- :: NonEmpty a -> a
, init -- :: NonEmpty a -> [a]
, (<|), cons -- :: a -> NonEmpty a -> NonEmpty a
, uncons -- :: NonEmpty a -> (a, Maybe (NonEmpty a))
, unfoldr -- :: (a -> (b, Maybe a)) -> a -> NonEmpty b
, sort -- :: NonEmpty a -> NonEmpty a
, reverse -- :: NonEmpty a -> NonEmpty a
, inits -- :: Foldable f => f a -> NonEmpty a
, tails -- :: Foldable f => f a -> NonEmpty a
-- * Building streams
, iterate -- :: (a -> a) -> a -> NonEmpty a
, repeat -- :: a -> NonEmpty a
, cycle -- :: NonEmpty a -> NonEmpty a
, unfold -- :: (a -> (b, Maybe a) -> a -> NonEmpty b
, insert -- :: (Foldable f, Ord a) => a -> f a -> NonEmpty a
, some1 -- :: Alternative f => f a -> f (NonEmpty a)
-- * Extracting sublists
, take -- :: Int -> NonEmpty a -> [a]
, drop -- :: Int -> NonEmpty a -> [a]
, splitAt -- :: Int -> NonEmpty a -> ([a], [a])
, takeWhile -- :: Int -> NonEmpty a -> [a]
, dropWhile -- :: Int -> NonEmpty a -> [a]
, span -- :: Int -> NonEmpty a -> ([a],[a])
, break -- :: Int -> NonEmpty a -> ([a],[a])
, filter -- :: (a -> Bool) -> NonEmpty a -> [a]
, partition -- :: (a -> Bool) -> NonEmpty a -> ([a],[a])
, group -- :: Foldable f => Eq a => f a -> [NonEmpty a]
, groupBy -- :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a]
, groupWith -- :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a]
, groupAllWith -- :: (Foldable f, Ord b) => (a -> b) -> f a -> [NonEmpty a]
, group1 -- :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a)
, groupBy1 -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a)
, groupWith1 -- :: (Foldable f, Eq b) => (a -> b) -> f a -> NonEmpty (NonEmpty a)
, groupAllWith1 -- :: (Foldable f, Ord b) => (a -> b) -> f a -> NonEmpty (NonEmpty a)
-- * Sublist predicates
, isPrefixOf -- :: Foldable f => f a -> NonEmpty a -> Bool
-- * \"Set\" operations
, nub -- :: Eq a => NonEmpty a -> NonEmpty a
, nubBy -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a
-- * Indexing streams
, (!!) -- :: NonEmpty a -> Int -> a
-- * Zipping and unzipping streams
, zip -- :: NonEmpty a -> NonEmpty b -> NonEmpty (a,b)
, zipWith -- :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
, unzip -- :: NonEmpty (a, b) -> (NonEmpty a, NonEmpty b)
-- * Converting to and from a list
, fromList -- :: [a] -> NonEmpty a
, toList -- :: NonEmpty a -> [a]
, nonEmpty -- :: [a] -> Maybe (NonEmpty a)
, xor -- :: NonEmpty a -> Bool
) where
import Prelude hiding (break, cycle, drop, dropWhile,
filter, foldl, foldr, head, init, iterate,
last, length, map, repeat, reverse,
scanl, scanl1, scanr, scanr1, span,
splitAt, tail, take, takeWhile,
unzip, zip, zipWith, (!!))
import qualified Prelude
import Control.Applicative (Alternative, many)
import Control.Monad (ap)
import Control.Monad.Fix
import Control.Monad.Zip (MonadZip(..))
import Data.Data (Data)
import Data.Foldable hiding (length, toList)
import qualified Data.Foldable as Foldable
import Data.Function (on)
import qualified Data.List as List
import Data.Ord (comparing)
import qualified GHC.Exts as Exts (IsList(..))
import GHC.Generics (Generic, Generic1)
infixr 5 :|, <|
-- | Non-empty (and non-strict) list type.
--
-- @since 4.9.0.0
data NonEmpty a = a :| [a]
deriving ( Eq, Ord, Show, Read, Data, Generic, Generic1 )
instance Exts.IsList (NonEmpty a) where
type Item (NonEmpty a) = a
fromList = fromList
toList = toList
instance MonadFix NonEmpty where
mfix f = case fix (f . head) of
~(x :| _) -> x :| mfix (tail . f)
instance MonadZip NonEmpty where
mzip = zip
mzipWith = zipWith
munzip = unzip
-- | Number of elements in 'NonEmpty' list.
length :: NonEmpty a -> Int
length (_ :| xs) = 1 + Prelude.length xs
-- | Compute n-ary logic exclusive OR operation on 'NonEmpty' list.
xor :: NonEmpty Bool -> Bool
xor (x :| xs) = foldr xor' x xs
where xor' True y = not y
xor' False y = y
-- | 'unfold' produces a new stream by repeatedly applying the unfolding
-- function to the seed value to produce an element of type @b@ and a new
-- seed value. When the unfolding function returns 'Nothing' instead of
-- a new seed value, the stream ends.
unfold :: (a -> (b, Maybe a)) -> a -> NonEmpty b
unfold f a = case f a of
(b, Nothing) -> b :| []
(b, Just c) -> b <| unfold f c
-- | 'nonEmpty' efficiently turns a normal list into a 'NonEmpty' stream,
-- producing 'Nothing' if the input is empty.
nonEmpty :: [a] -> Maybe (NonEmpty a)
nonEmpty [] = Nothing
nonEmpty (a:as) = Just (a :| as)
-- | 'uncons' produces the first element of the stream, and a stream of the
-- remaining elements, if any.
uncons :: NonEmpty a -> (a, Maybe (NonEmpty a))
uncons ~(a :| as) = (a, nonEmpty as)
-- | The 'unfoldr' function is analogous to "Data.List"'s
-- 'Data.List.unfoldr' operation.
unfoldr :: (a -> (b, Maybe a)) -> a -> NonEmpty b
unfoldr f a = case f a of
(b, mc) -> b :| maybe [] go mc
where
go c = case f c of
(d, me) -> d : maybe [] go me
instance Functor NonEmpty where
fmap f ~(a :| as) = f a :| fmap f as
b <$ ~(_ :| as) = b :| (b <$ as)
instance Applicative NonEmpty where
pure a = a :| []
(<*>) = ap
instance Monad NonEmpty where
~(a :| as) >>= f = b :| (bs ++ bs')
where b :| bs = f a
bs' = as >>= toList . f
instance Traversable NonEmpty where
traverse f ~(a :| as) = (:|) <$> f a <*> traverse f as
instance Foldable NonEmpty where
foldr f z ~(a :| as) = f a (foldr f z as)
foldl f z ~(a :| as) = foldl f (f z a) as
foldl1 f ~(a :| as) = foldl f a as
foldMap f ~(a :| as) = f a `mappend` foldMap f as
fold ~(m :| ms) = m `mappend` fold ms
-- | Extract the first element of the stream.
head :: NonEmpty a -> a
head ~(a :| _) = a
-- | Extract the possibly-empty tail of the stream.
tail :: NonEmpty a -> [a]
tail ~(_ :| as) = as
-- | Extract the last element of the stream.
last :: NonEmpty a -> a
last ~(a :| as) = List.last (a : as)
-- | Extract everything except the last element of the stream.
init :: NonEmpty a -> [a]
init ~(a :| as) = List.init (a : as)
-- | Prepend an element to the stream.
(<|) :: a -> NonEmpty a -> NonEmpty a
a <| ~(b :| bs) = a :| b : bs
-- | Synonym for '<|'.
cons :: a -> NonEmpty a -> NonEmpty a
cons = (<|)
-- | Sort a stream.
sort :: Ord a => NonEmpty a -> NonEmpty a
sort = lift List.sort
-- | Converts a normal list to a 'NonEmpty' stream.
--
-- Raises an error if given an empty list.
fromList :: [a] -> NonEmpty a
fromList (a:as) = a :| as
fromList [] = error "NonEmpty.fromList: empty list"
-- | Convert a stream to a normal list efficiently.
toList :: NonEmpty a -> [a]
toList ~(a :| as) = a : as
-- | Lift list operations to work on a 'NonEmpty' stream.
--
-- /Beware/: If the provided function returns an empty list,
-- this will raise an error.
lift :: Foldable f => ([a] -> [b]) -> f a -> NonEmpty b
lift f = fromList . f . Foldable.toList
-- | Map a function over a 'NonEmpty' stream.
map :: (a -> b) -> NonEmpty a -> NonEmpty b
map f ~(a :| as) = f a :| fmap f as
-- | The 'inits' function takes a stream @xs@ and returns all the
-- finite prefixes of @xs@.
inits :: Foldable f => f a -> NonEmpty [a]
inits = fromList . List.inits . Foldable.toList
-- | The 'tails' function takes a stream @xs@ and returns all the
-- suffixes of @xs@.
tails :: Foldable f => f a -> NonEmpty [a]
tails = fromList . List.tails . Foldable.toList
-- | @'insert' x xs@ inserts @x@ into the last position in @xs@ where it
-- is still less than or equal to the next element. In particular, if the
-- list is sorted beforehand, the result will also be sorted.
insert :: (Foldable f, Ord a) => a -> f a -> NonEmpty a
insert a = fromList . List.insert a . Foldable.toList
-- | @'some1' x@ sequences @x@ one or more times.
some1 :: Alternative f => f a -> f (NonEmpty a)
some1 x = (:|) <$> x <*> many x
-- | 'scanl' is similar to 'foldl', but returns a stream of successive
-- reduced values from the left:
--
-- > scanl f z [x1, x2, ...] == z :| [z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
scanl :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b
scanl f z = fromList . List.scanl f z . Foldable.toList
-- | 'scanr' is the right-to-left dual of 'scanl'.
-- Note that
--
-- > head (scanr f z xs) == foldr f z xs.
scanr :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b
scanr f z = fromList . List.scanr f z . Foldable.toList
-- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
--
-- > scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...]
scanl1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a
scanl1 f ~(a :| as) = fromList (List.scanl f a as)
-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a
scanr1 f ~(a :| as) = fromList (List.scanr1 f (a:as))
-- | 'intersperse x xs' alternates elements of the list with copies of @x@.
--
-- > intersperse 0 (1 :| [2,3]) == 1 :| [0,2,0,3]
intersperse :: a -> NonEmpty a -> NonEmpty a
intersperse a ~(b :| bs) = b :| case bs of
[] -> []
_ -> a : List.intersperse a bs
-- | @'iterate' f x@ produces the infinite sequence
-- of repeated applications of @f@ to @x@.
--
-- > iterate f x = x :| [f x, f (f x), ..]
iterate :: (a -> a) -> a -> NonEmpty a
iterate f a = a :| List.iterate f (f a)
-- | @'cycle' xs@ returns the infinite repetition of @xs@:
--
-- > cycle [1,2,3] = 1 :| [2,3,1,2,3,...]
cycle :: NonEmpty a -> NonEmpty a
cycle = fromList . List.cycle . toList
-- | 'reverse' a finite NonEmpty stream.
reverse :: NonEmpty a -> NonEmpty a
reverse = lift List.reverse
-- | @'repeat' x@ returns a constant stream, where all elements are
-- equal to @x@.
repeat :: a -> NonEmpty a
repeat a = a :| List.repeat a
-- | @'take' n xs@ returns the first @n@ elements of @xs@.
take :: Int -> NonEmpty a -> [a]
take n = List.take n . toList
-- | @'drop' n xs@ drops the first @n@ elements off the front of
-- the sequence @xs@.
drop :: Int -> NonEmpty a -> [a]
drop n = List.drop n . toList
-- | @'splitAt' n xs@ returns a pair consisting of the prefix of @xs@
-- of length @n@ and the remaining stream immediately following this prefix.
--
-- > 'splitAt' n xs == ('take' n xs, 'drop' n xs)
-- > xs == ys ++ zs where (ys, zs) = 'splitAt' n xs
splitAt :: Int -> NonEmpty a -> ([a],[a])
splitAt n = List.splitAt n . toList
-- | @'takeWhile' p xs@ returns the longest prefix of the stream
-- @xs@ for which the predicate @p@ holds.
takeWhile :: (a -> Bool) -> NonEmpty a -> [a]
takeWhile p = List.takeWhile p . toList
-- | @'dropWhile' p xs@ returns the suffix remaining after
-- @'takeWhile' p xs@.
dropWhile :: (a -> Bool) -> NonEmpty a -> [a]
dropWhile p = List.dropWhile p . toList
-- | @'span' p xs@ returns the longest prefix of @xs@ that satisfies
-- @p@, together with the remainder of the stream.
--
-- > 'span' p xs == ('takeWhile' p xs, 'dropWhile' p xs)
-- > xs == ys ++ zs where (ys, zs) = 'span' p xs
span :: (a -> Bool) -> NonEmpty a -> ([a], [a])
span p = List.span p . toList
-- | The @'break' p@ function is equivalent to @'span' (not . p)@.
break :: (a -> Bool) -> NonEmpty a -> ([a], [a])
break p = span (not . p)
-- | @'filter' p xs@ removes any elements from @xs@ that do not satisfy @p@.
filter :: (a -> Bool) -> NonEmpty a -> [a]
filter p = List.filter p . toList
-- | The 'partition' function takes a predicate @p@ and a stream
-- @xs@, and returns a pair of lists. The first list corresponds to the
-- elements of @xs@ for which @p@ holds; the second corresponds to the
-- elements of @xs@ for which @p@ does not hold.
--
-- > 'partition' p xs = ('filter' p xs, 'filter' (not . p) xs)
partition :: (a -> Bool) -> NonEmpty a -> ([a], [a])
partition p = List.partition p . toList
-- | The 'group' function takes a stream and returns a list of
-- streams such that flattening the resulting list is equal to the
-- argument. Moreover, each stream in the resulting list
-- contains only equal elements. For example, in list notation:
--
-- > 'group' $ 'cycle' "Mississippi"
-- > = "M" : "i" : "ss" : "i" : "ss" : "i" : "pp" : "i" : "M" : "i" : ...
group :: (Foldable f, Eq a) => f a -> [NonEmpty a]
group = groupBy (==)
-- | 'groupBy' operates like 'group', but uses the provided equality
-- predicate instead of `==`.
groupBy :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a]
groupBy eq0 = go eq0 . Foldable.toList
where
go _ [] = []
go eq (x : xs) = (x :| ys) : groupBy eq zs
where (ys, zs) = List.span (eq x) xs
-- | 'groupWith' operates like 'group', but uses the provided projection when
-- comparing for equality
groupWith :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a]
groupWith f = groupBy ((==) `on` f)
-- | 'groupAllWith' operates like 'groupWith', but sorts the list
-- first so that each equivalence class has, at most, one list in the
-- output
groupAllWith :: (Ord b) => (a -> b) -> [a] -> [NonEmpty a]
groupAllWith f = groupWith f . List.sortBy (compare `on` f)
-- | 'group1' operates like 'group', but uses the knowledge that its
-- input is non-empty to produce guaranteed non-empty output.
group1 :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a)
group1 = groupBy1 (==)
-- | 'groupBy1' is to 'group1' as 'groupBy' is to 'group'.
groupBy1 :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a)
groupBy1 eq (x :| xs) = (x :| ys) :| groupBy eq zs
where (ys, zs) = List.span (eq x) xs
-- | 'groupWith1' is to 'group1' as 'groupWith' is to 'group'
groupWith1 :: (Eq b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)
groupWith1 f = groupBy1 ((==) `on` f)
-- | 'groupAllWith1' is to 'groupWith1' as 'groupAllWith' is to 'groupWith'
groupAllWith1 :: (Ord b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)
groupAllWith1 f = groupWith1 f . sortWith f
-- | The 'isPrefix' function returns @True@ if the first argument is
-- a prefix of the second.
isPrefixOf :: Eq a => [a] -> NonEmpty a -> Bool
isPrefixOf [] _ = True
isPrefixOf (y:ys) (x :| xs) = (y == x) && List.isPrefixOf ys xs
-- | @xs !! n@ returns the element of the stream @xs@ at index
-- @n@. Note that the head of the stream has index 0.
--
-- /Beware/: a negative or out-of-bounds index will cause an error.
(!!) :: NonEmpty a -> Int -> a
(!!) ~(x :| xs) n
| n == 0 = x
| n > 0 = xs List.!! (n - 1)
| otherwise = error "NonEmpty.!! negative argument"
-- | The 'zip' function takes two streams and returns a stream of
-- corresponding pairs.
zip :: NonEmpty a -> NonEmpty b -> NonEmpty (a,b)
zip ~(x :| xs) ~(y :| ys) = (x, y) :| List.zip xs ys
-- | The 'zipWith' function generalizes 'zip'. Rather than tupling
-- the elements, the elements are combined using the function
-- passed as the first argument.
zipWith :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
zipWith f ~(x :| xs) ~(y :| ys) = f x y :| List.zipWith f xs ys
-- | The 'unzip' function is the inverse of the 'zip' function.
unzip :: Functor f => f (a,b) -> (f a, f b)
unzip xs = (fst <$> xs, snd <$> xs)
-- | The 'nub' function removes duplicate elements from a list. In
-- particular, it keeps only the first occurence of each element.
-- (The name 'nub' means \'essence\'.)
-- It is a special case of 'nubBy', which allows the programmer to
-- supply their own inequality test.
nub :: Eq a => NonEmpty a -> NonEmpty a
nub = nubBy (==)
-- | The 'nubBy' function behaves just like 'nub', except it uses a
-- user-supplied equality predicate instead of the overloaded '=='
-- function.
nubBy :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a
nubBy eq (a :| as) = a :| List.nubBy eq (List.filter (\b -> not (eq a b)) as)
-- | 'transpose' for 'NonEmpty', behaves the same as 'Data.List.transpose'
-- The rows/columns need not be the same length, in which case
-- > transpose . transpose /= id
transpose :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a)
transpose = fmap fromList
. fromList . List.transpose . Foldable.toList
. fmap Foldable.toList
-- | 'sortBy' for 'NonEmpty', behaves the same as 'Data.List.sortBy'
sortBy :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a
sortBy f = lift (List.sortBy f)
-- | 'sortWith' for 'NonEmpty', behaves the same as:
--
-- > sortBy . comparing
sortWith :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a
sortWith = sortBy . comparing
| da-x/ghc | libraries/base/Data/List/NonEmpty.hs | bsd-3-clause | 18,767 | 0 | 13 | 4,782 | 4,320 | 2,370 | 1,950 | 247 | 2 |
module Network.HTTP.UserAgent where
import Control.Monad.Error
import Data.ByteString.Lazy.Char8 ( ByteString )
import qualified Data.ByteString.Lazy.Char8 as BS
import Network.HTTP
import Network.URI
import Data.Maybe ( maybe )
-----------------------------------------------------------------------------
defaultRequest :: Request
defaultRequest = Request { rqURI = undefined
, rqMethod = GET
, rqHeaders = []
, rqBody = BS.empty
}
uri :: (MonadError e m, Monad m, HTTPError e) => String -> Request -> m Request
uri str r = do u <- parseURI' str; return $ r { rqURI = u }
headerAdderM :: Monad m => m Header -> Request -> m Request
headerAdderM hm r@(Request{rqHeaders = hs}) =
do h <- hm; return $ r { rqHeaders = h:hs }
headerAdder :: Monad m => Header -> Request -> m Request
headerAdder h r@(Request{rqHeaders = hs}) = return $ r { rqHeaders = h:hs }
hExpires :: Monad m => Int -> Request -> m Request
hExpires n = headerAdder (Header HdrExpires (show n))
hReferer :: (MonadError e m, HTTPError e, Monad m) => String -> Request -> m Request
hReferer str = headerAdderM $
do uri <- parseURI' str
return $ Header HdrReferer (show uri)
exampleRequest :: (MonadError e m, Monad m, HTTPError e) => m Request
exampleRequest = mkRequest [uri "http://www.google.com", hExpires 4]
mkRequest :: (MonadError e m, Monad m, HTTPError e) =>
[Request -> m Request] -> m Request
mkRequest mods = f mods defaultRequest
where f [] x = return x
f (m:ms) x = m x >>= f ms
parseURI' :: (MonadError e m, HTTPError e) => String -> m URI
parseURI' str = maybe (throwHTTPError URIErr) return $ parseURI str
-- | Perform HTTP request after parsing the URI string.
get :: (MonadError e m, MonadIO m, HTTPError e) => String -> m Response
get uriString = mkRequest [uri uriString] >>= simpleHTTP
-- | Directly get the content of the given String which is parsed as a URI.
-- FIXME: Not sure this is a good name
getContent :: (MonadError e m, MonadIO m, HTTPError e) =>
String -> m ByteString
getContent uriString = get uriString >>= return . rspBody
| beni55/HTTP | Network/HTTP/UserAgent.hs | bsd-3-clause | 2,287 | 0 | 11 | 607 | 761 | 397 | 364 | 39 | 2 |
-- |
-- Copyright : (c) 2012 Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <[email protected]>
--
-- Provided NFData instance for ByteString (with bytestring < 0.10)
module Extension.Data.ByteString (
) where
import Data.ByteString ()
| rsasse/tamarin-prover | lib/utils/src/Extension/Data/ByteString.hs | gpl-3.0 | 286 | 0 | 4 | 52 | 25 | 19 | 6 | 2 | 0 |
module Options.Misc where
import Types
miscOptions :: [Flag]
miscOptions =
[ flag { flagName = "-jN"
, flagDescription =
"When compiling with :ghc-flag:`--make`, compile ⟨N⟩ modules in parallel."
, flagType = DynamicFlag
}
, flag { flagName = "-fno-hi-version-check"
, flagDescription = "Don't complain about ``.hi`` file mismatches"
, flagType = DynamicFlag
}
, flag { flagName = "-fhistory-size"
, flagDescription = "Set simplification history size"
, flagType = DynamicFlag
}
, flag { flagName = "-fno-ghci-history"
, flagDescription =
"Do not use the load/store the GHCi command history from/to "++
"``ghci_history``."
, flagType = DynamicFlag
}
, flag { flagName = "-fno-ghci-sandbox"
, flagDescription =
"Turn off the GHCi sandbox. Means computations are run in "++
"the main thread, rather than a forked thread."
, flagType = DynamicFlag
}
, flag { flagName = "-freverse-errors"
, flagDescription =
"Display errors in GHC/GHCi sorted by reverse order of "++
"source code line numbers."
, flagType = DynamicFlag
, flagReverse = "-fno-reverse-errors"
}
, flag { flagName = "-flocal-ghci-history"
, flagDescription =
"Use current directory for the GHCi command history "++
"file ``.ghci-history``."
, flagType = DynamicFlag
, flagReverse = "-fno-local-ghci-history"
}
]
| olsner/ghc | utils/mkUserGuidePart/Options/Misc.hs | bsd-3-clause | 1,602 | 0 | 8 | 516 | 211 | 135 | 76 | 36 | 1 |
-- parser produced by Happy Version 1.11
module PropParser (parse) where
import PropSyntax
import PropSyntaxUtil
import ParseMonad
import Lexer
import LexUtil(readInteger, readRational)
import ParseUtil
--import Rewrite
import IOExts
import Char(showLitChar)
data HappyAbsSyn
= HappyTerminal Token
| HappyErrorToken Int
| HappyAbsSyn4 (HsModuleR)
| HappyAbsSyn5 (([HsImportDecl], [HsDecl]))
| HappyAbsSyn7 (())
| HappyAbsSyn8 (Maybe [HsExportSpec])
| HappyAbsSyn9 ([HsExportSpec])
| HappyAbsSyn12 (HsExportSpec)
| HappyAbsSyn13 ([HsName])
| HappyAbsSyn14 (HsName)
| HappyAbsSyn15 ([HsImportDecl])
| HappyAbsSyn16 (HsImportDecl)
| HappyAbsSyn17 (Bool)
| HappyAbsSyn18 (Maybe Module)
| HappyAbsSyn19 (Maybe (Bool, [HsImportSpec]))
| HappyAbsSyn20 ((Bool, [HsImportSpec]))
| HappyAbsSyn21 ([HsImportSpec])
| HappyAbsSyn22 (HsImportSpec)
| HappyAbsSyn25 ([HsDecl])
| HappyAbsSyn26 (HsDecl)
| HappyAbsSyn27 (Int)
| HappyAbsSyn28 (HsAssoc)
| HappyAbsSyn29 ([HsIdent])
| HappyAbsSyn37 (HsType)
| HappyAbsSyn41 (([HsType],HsType))
| HappyAbsSyn42 ([HsType])
| HappyAbsSyn43 (([HsType], [HsType]))
| HappyAbsSyn46 (([HsType], HsName))
| HappyAbsSyn47 ([HsConDecl HsType ])
| HappyAbsSyn48 (HsConDecl HsType)
| HappyAbsSyn49 ((HsName, [HsBangType HsType]))
| HappyAbsSyn51 (HsBangType HsType)
| HappyAbsSyn53 ([([HsName], HsBangType HsType)])
| HappyAbsSyn54 (([HsName], HsBangType HsType))
| HappyAbsSyn66 (HsRhs HsExp)
| HappyAbsSyn67 ([(SrcLoc, HsExp, HsExp)])
| HappyAbsSyn68 ((SrcLoc, HsExp, HsExp))
| HappyAbsSyn69 (HsExp)
| HappyAbsSyn73 ([HsExp])
| HappyAbsSyn80 ([HsStmtAtom HsExp HsPat [HsDecl] ])
| HappyAbsSyn81 (HsStmtAtom HsExp HsPat [HsDecl])
| HappyAbsSyn82 ([HsAlt HsExp HsPat [HsDecl]])
| HappyAbsSyn84 (HsAlt HsExp HsPat [HsDecl])
| HappyAbsSyn88 ([HsStmtAtom HsExp HsPat [HsDecl]])
| HappyAbsSyn91 ([HsFieldUpdate HsExp])
| HappyAbsSyn92 (HsFieldUpdate HsExp)
| HappyAbsSyn102 (HsIdent)
| HappyAbsSyn115 (SrcLoc)
| HappyAbsSyn119 (Module)
| HappyAbsSyn126 (HsQuantifier)
type HappyReduction =
Int
-> (Token)
-> HappyState (Token) (HappyStk HappyAbsSyn -> PM(HappyAbsSyn))
-> [HappyState (Token) (HappyStk HappyAbsSyn -> PM(HappyAbsSyn))]
-> HappyStk HappyAbsSyn
-> PM(HappyAbsSyn)
action_0,
action_1,
action_2,
action_3,
action_4,
action_5,
action_6,
action_7,
action_8,
action_9,
action_10,
action_11,
action_12,
action_13,
action_14,
action_15,
action_16,
action_17,
action_18,
action_19,
action_20,
action_21,
action_22,
action_23,
action_24,
action_25,
action_26,
action_27,
action_28,
action_29,
action_30,
action_31,
action_32,
action_33,
action_34,
action_35,
action_36,
action_37,
action_38,
action_39,
action_40,
action_41,
action_42,
action_43,
action_44,
action_45,
action_46,
action_47,
action_48,
action_49,
action_50,
action_51,
action_52,
action_53,
action_54,
action_55,
action_56,
action_57,
action_58,
action_59,
action_60,
action_61,
action_62,
action_63,
action_64,
action_65,
action_66,
action_67,
action_68,
action_69,
action_70,
action_71,
action_72,
action_73,
action_74,
action_75,
action_76,
action_77,
action_78,
action_79,
action_80,
action_81,
action_82,
action_83,
action_84,
action_85,
action_86,
action_87,
action_88,
action_89,
action_90,
action_91,
action_92,
action_93,
action_94,
action_95,
action_96,
action_97,
action_98,
action_99,
action_100,
action_101,
action_102,
action_103,
action_104,
action_105,
action_106,
action_107,
action_108,
action_109,
action_110,
action_111,
action_112,
action_113,
action_114,
action_115,
action_116,
action_117,
action_118,
action_119,
action_120,
action_121,
action_122,
action_123,
action_124,
action_125,
action_126,
action_127,
action_128,
action_129,
action_130,
action_131,
action_132,
action_133,
action_134,
action_135,
action_136,
action_137,
action_138,
action_139,
action_140,
action_141,
action_142,
action_143,
action_144,
action_145,
action_146,
action_147,
action_148,
action_149,
action_150,
action_151,
action_152,
action_153,
action_154,
action_155,
action_156,
action_157,
action_158,
action_159,
action_160,
action_161,
action_162,
action_163,
action_164,
action_165,
action_166,
action_167,
action_168,
action_169,
action_170,
action_171,
action_172,
action_173,
action_174,
action_175,
action_176,
action_177,
action_178,
action_179,
action_180,
action_181,
action_182,
action_183,
action_184,
action_185,
action_186,
action_187,
action_188,
action_189,
action_190,
action_191,
action_192,
action_193,
action_194,
action_195,
action_196,
action_197,
action_198,
action_199,
action_200,
action_201,
action_202,
action_203,
action_204,
action_205,
action_206,
action_207,
action_208,
action_209,
action_210,
action_211,
action_212,
action_213,
action_214,
action_215,
action_216,
action_217,
action_218,
action_219,
action_220,
action_221,
action_222,
action_223,
action_224,
action_225,
action_226,
action_227,
action_228,
action_229,
action_230,
action_231,
action_232,
action_233,
action_234,
action_235,
action_236,
action_237,
action_238,
action_239,
action_240,
action_241,
action_242,
action_243,
action_244,
action_245,
action_246,
action_247,
action_248,
action_249,
action_250,
action_251,
action_252,
action_253,
action_254,
action_255,
action_256,
action_257,
action_258,
action_259,
action_260,
action_261,
action_262,
action_263,
action_264,
action_265,
action_266,
action_267,
action_268,
action_269,
action_270,
action_271,
action_272,
action_273,
action_274,
action_275,
action_276,
action_277,
action_278,
action_279,
action_280,
action_281,
action_282,
action_283,
action_284,
action_285,
action_286,
action_287,
action_288,
action_289,
action_290,
action_291,
action_292,
action_293,
action_294,
action_295,
action_296,
action_297,
action_298,
action_299,
action_300,
action_301,
action_302,
action_303,
action_304,
action_305,
action_306,
action_307,
action_308,
action_309,
action_310,
action_311,
action_312,
action_313,
action_314,
action_315,
action_316,
action_317,
action_318,
action_319,
action_320,
action_321,
action_322,
action_323,
action_324,
action_325,
action_326,
action_327,
action_328,
action_329,
action_330,
action_331,
action_332,
action_333,
action_334,
action_335,
action_336,
action_337,
action_338,
action_339,
action_340,
action_341,
action_342,
action_343,
action_344,
action_345,
action_346,
action_347,
action_348,
action_349,
action_350,
action_351,
action_352,
action_353,
action_354,
action_355,
action_356,
action_357,
action_358,
action_359,
action_360,
action_361,
action_362,
action_363,
action_364,
action_365,
action_366,
action_367,
action_368,
action_369,
action_370,
action_371,
action_372,
action_373,
action_374,
action_375,
action_376,
action_377,
action_378,
action_379,
action_380,
action_381,
action_382,
action_383,
action_384,
action_385,
action_386,
action_387,
action_388,
action_389,
action_390,
action_391,
action_392,
action_393,
action_394,
action_395,
action_396,
action_397,
action_398,
action_399,
action_400,
action_401,
action_402,
action_403,
action_404,
action_405,
action_406,
action_407,
action_408,
action_409,
action_410,
action_411,
action_412,
action_413,
action_414,
action_415,
action_416,
action_417,
action_418,
action_419,
action_420,
action_421,
action_422,
action_423,
action_424,
action_425,
action_426,
action_427,
action_428,
action_429,
action_430,
action_431,
action_432,
action_433,
action_434,
action_435,
action_436,
action_437,
action_438,
action_439,
action_440,
action_441,
action_442,
action_443,
action_444,
action_445,
action_446,
action_447,
action_448,
action_449,
action_450,
action_451,
action_452,
action_453,
action_454,
action_455,
action_456,
action_457,
action_458,
action_459,
action_460,
action_461,
action_462,
action_463,
action_464,
action_465,
action_466,
action_467,
action_468,
action_469,
action_470,
action_471,
action_472,
action_473,
action_474,
action_475,
action_476,
action_477,
action_478,
action_479,
action_480,
action_481,
action_482,
action_483,
action_484,
action_485,
action_486,
action_487,
action_488,
action_489,
action_490,
action_491,
action_492,
action_493,
action_494,
action_495,
action_496,
action_497,
action_498,
action_499,
action_500,
action_501,
action_502,
action_503,
action_504,
action_505,
action_506,
action_507,
action_508,
action_509,
action_510,
action_511,
action_512,
action_513,
action_514,
action_515,
action_516,
action_517,
action_518,
action_519,
action_520,
action_521,
action_522,
action_523,
action_524,
action_525,
action_526,
action_527,
action_528,
action_529,
action_530,
action_531,
action_532 :: Int -> HappyReduction
happyReduce_1,
happyReduce_2,
happyReduce_3,
happyReduce_4,
happyReduce_5,
happyReduce_6,
happyReduce_7,
happyReduce_8,
happyReduce_9,
happyReduce_10,
happyReduce_11,
happyReduce_12,
happyReduce_13,
happyReduce_14,
happyReduce_15,
happyReduce_16,
happyReduce_17,
happyReduce_18,
happyReduce_19,
happyReduce_20,
happyReduce_21,
happyReduce_22,
happyReduce_23,
happyReduce_24,
happyReduce_25,
happyReduce_26,
happyReduce_27,
happyReduce_28,
happyReduce_29,
happyReduce_30,
happyReduce_31,
happyReduce_32,
happyReduce_33,
happyReduce_34,
happyReduce_35,
happyReduce_36,
happyReduce_37,
happyReduce_38,
happyReduce_39,
happyReduce_40,
happyReduce_41,
happyReduce_42,
happyReduce_43,
happyReduce_44,
happyReduce_45,
happyReduce_46,
happyReduce_47,
happyReduce_48,
happyReduce_49,
happyReduce_50,
happyReduce_51,
happyReduce_52,
happyReduce_53,
happyReduce_54,
happyReduce_55,
happyReduce_56,
happyReduce_57,
happyReduce_58,
happyReduce_59,
happyReduce_60,
happyReduce_61,
happyReduce_62,
happyReduce_63,
happyReduce_64,
happyReduce_65,
happyReduce_66,
happyReduce_67,
happyReduce_68,
happyReduce_69,
happyReduce_70,
happyReduce_71,
happyReduce_72,
happyReduce_73,
happyReduce_74,
happyReduce_75,
happyReduce_76,
happyReduce_77,
happyReduce_78,
happyReduce_79,
happyReduce_80,
happyReduce_81,
happyReduce_82,
happyReduce_83,
happyReduce_84,
happyReduce_85,
happyReduce_86,
happyReduce_87,
happyReduce_88,
happyReduce_89,
happyReduce_90,
happyReduce_91,
happyReduce_92,
happyReduce_93,
happyReduce_94,
happyReduce_95,
happyReduce_96,
happyReduce_97,
happyReduce_98,
happyReduce_99,
happyReduce_100,
happyReduce_101,
happyReduce_102,
happyReduce_103,
happyReduce_104,
happyReduce_105,
happyReduce_106,
happyReduce_107,
happyReduce_108,
happyReduce_109,
happyReduce_110,
happyReduce_111,
happyReduce_112,
happyReduce_113,
happyReduce_114,
happyReduce_115,
happyReduce_116,
happyReduce_117,
happyReduce_118,
happyReduce_119,
happyReduce_120,
happyReduce_121,
happyReduce_122,
happyReduce_123,
happyReduce_124,
happyReduce_125,
happyReduce_126,
happyReduce_127,
happyReduce_128,
happyReduce_129,
happyReduce_130,
happyReduce_131,
happyReduce_132,
happyReduce_133,
happyReduce_134,
happyReduce_135,
happyReduce_136,
happyReduce_137,
happyReduce_138,
happyReduce_139,
happyReduce_140,
happyReduce_141,
happyReduce_142,
happyReduce_143,
happyReduce_144,
happyReduce_145,
happyReduce_146,
happyReduce_147,
happyReduce_148,
happyReduce_149,
happyReduce_150,
happyReduce_151,
happyReduce_152,
happyReduce_153,
happyReduce_154,
happyReduce_155,
happyReduce_156,
happyReduce_157,
happyReduce_158,
happyReduce_159,
happyReduce_160,
happyReduce_161,
happyReduce_162,
happyReduce_163,
happyReduce_164,
happyReduce_165,
happyReduce_166,
happyReduce_167,
happyReduce_168,
happyReduce_169,
happyReduce_170,
happyReduce_171,
happyReduce_172,
happyReduce_173,
happyReduce_174,
happyReduce_175,
happyReduce_176,
happyReduce_177,
happyReduce_178,
happyReduce_179,
happyReduce_180,
happyReduce_181,
happyReduce_182,
happyReduce_183,
happyReduce_184,
happyReduce_185,
happyReduce_186,
happyReduce_187,
happyReduce_188,
happyReduce_189,
happyReduce_190,
happyReduce_191,
happyReduce_192,
happyReduce_193,
happyReduce_194,
happyReduce_195,
happyReduce_196,
happyReduce_197,
happyReduce_198,
happyReduce_199,
happyReduce_200,
happyReduce_201,
happyReduce_202,
happyReduce_203,
happyReduce_204,
happyReduce_205,
happyReduce_206,
happyReduce_207,
happyReduce_208,
happyReduce_209,
happyReduce_210,
happyReduce_211,
happyReduce_212,
happyReduce_213,
happyReduce_214,
happyReduce_215,
happyReduce_216,
happyReduce_217,
happyReduce_218,
happyReduce_219,
happyReduce_220,
happyReduce_221,
happyReduce_222,
happyReduce_223,
happyReduce_224,
happyReduce_225,
happyReduce_226,
happyReduce_227,
happyReduce_228,
happyReduce_229,
happyReduce_230,
happyReduce_231,
happyReduce_232,
happyReduce_233,
happyReduce_234,
happyReduce_235,
happyReduce_236,
happyReduce_237,
happyReduce_238,
happyReduce_239,
happyReduce_240,
happyReduce_241,
happyReduce_242,
happyReduce_243,
happyReduce_244,
happyReduce_245,
happyReduce_246,
happyReduce_247,
happyReduce_248,
happyReduce_249,
happyReduce_250,
happyReduce_251,
happyReduce_252,
happyReduce_253,
happyReduce_254,
happyReduce_255,
happyReduce_256,
happyReduce_257,
happyReduce_258,
happyReduce_259,
happyReduce_260,
happyReduce_261,
happyReduce_262,
happyReduce_263,
happyReduce_264,
happyReduce_265,
happyReduce_266,
happyReduce_267,
happyReduce_268,
happyReduce_269,
happyReduce_270,
happyReduce_271,
happyReduce_272,
happyReduce_273,
happyReduce_274,
happyReduce_275,
happyReduce_276,
happyReduce_277,
happyReduce_278,
happyReduce_279,
happyReduce_280,
happyReduce_281,
happyReduce_282,
happyReduce_283,
happyReduce_284,
happyReduce_285,
happyReduce_286,
happyReduce_287,
happyReduce_288,
happyReduce_289,
happyReduce_290,
happyReduce_291,
happyReduce_292,
happyReduce_293,
happyReduce_294,
happyReduce_295 :: HappyReduction
action_0 (145) = happyShift action_6
action_0 (182) = happyShift action_2
action_0 (4) = happyGoto action_3
action_0 (5) = happyGoto action_4
action_0 (118) = happyGoto action_5
action_0 _ = happyReduce_282
action_1 (182) = happyShift action_2
action_1 _ = happyFail
action_2 (130) = happyShift action_73
action_2 (119) = happyGoto action_72
action_2 _ = happyFail
action_3 (195) = happyAccept
action_3 _ = happyFail
action_4 _ = happyReduce_2
action_5 (128) = happyShift action_34
action_5 (129) = happyShift action_35
action_5 (130) = happyShift action_36
action_5 (131) = happyShift action_37
action_5 (132) = happyShift action_38
action_5 (137) = happyShift action_39
action_5 (138) = happyShift action_40
action_5 (139) = happyShift action_41
action_5 (140) = happyShift action_42
action_5 (141) = happyShift action_43
action_5 (142) = happyShift action_44
action_5 (148) = happyShift action_45
action_5 (151) = happyShift action_46
action_5 (157) = happyShift action_47
action_5 (162) = happyShift action_48
action_5 (165) = happyShift action_49
action_5 (166) = happyShift action_50
action_5 (167) = happyShift action_51
action_5 (168) = happyShift action_52
action_5 (169) = happyShift action_53
action_5 (171) = happyShift action_54
action_5 (173) = happyShift action_55
action_5 (174) = happyShift action_56
action_5 (175) = happyShift action_57
action_5 (177) = happyShift action_58
action_5 (178) = happyShift action_59
action_5 (179) = happyShift action_60
action_5 (180) = happyShift action_61
action_5 (181) = happyShift action_62
action_5 (183) = happyShift action_63
action_5 (186) = happyShift action_64
action_5 (188) = happyShift action_65
action_5 (189) = happyShift action_66
action_5 (190) = happyShift action_67
action_5 (191) = happyShift action_68
action_5 (192) = happyShift action_69
action_5 (193) = happyShift action_70
action_5 (194) = happyShift action_71
action_5 (6) = happyGoto action_8
action_5 (15) = happyGoto action_9
action_5 (16) = happyGoto action_10
action_5 (25) = happyGoto action_11
action_5 (26) = happyGoto action_12
action_5 (28) = happyGoto action_13
action_5 (30) = happyGoto action_14
action_5 (33) = happyGoto action_15
action_5 (35) = happyGoto action_16
action_5 (36) = happyGoto action_17
action_5 (64) = happyGoto action_18
action_5 (70) = happyGoto action_19
action_5 (71) = happyGoto action_20
action_5 (72) = happyGoto action_21
action_5 (74) = happyGoto action_22
action_5 (75) = happyGoto action_23
action_5 (93) = happyGoto action_24
action_5 (95) = happyGoto action_25
action_5 (97) = happyGoto action_26
action_5 (104) = happyGoto action_27
action_5 (105) = happyGoto action_28
action_5 (106) = happyGoto action_29
action_5 (108) = happyGoto action_30
action_5 (114) = happyGoto action_31
action_5 (125) = happyGoto action_32
action_5 (126) = happyGoto action_33
action_5 _ = happyReduce_8
action_6 (117) = happyGoto action_7
action_6 _ = happyReduce_281
action_7 (128) = happyShift action_34
action_7 (129) = happyShift action_35
action_7 (130) = happyShift action_36
action_7 (131) = happyShift action_37
action_7 (132) = happyShift action_38
action_7 (137) = happyShift action_39
action_7 (138) = happyShift action_40
action_7 (139) = happyShift action_41
action_7 (140) = happyShift action_42
action_7 (141) = happyShift action_43
action_7 (142) = happyShift action_44
action_7 (148) = happyShift action_45
action_7 (151) = happyShift action_46
action_7 (157) = happyShift action_47
action_7 (162) = happyShift action_48
action_7 (165) = happyShift action_49
action_7 (166) = happyShift action_50
action_7 (167) = happyShift action_51
action_7 (168) = happyShift action_52
action_7 (169) = happyShift action_53
action_7 (171) = happyShift action_54
action_7 (173) = happyShift action_55
action_7 (174) = happyShift action_56
action_7 (175) = happyShift action_57
action_7 (177) = happyShift action_58
action_7 (178) = happyShift action_59
action_7 (179) = happyShift action_60
action_7 (180) = happyShift action_61
action_7 (181) = happyShift action_62
action_7 (183) = happyShift action_63
action_7 (186) = happyShift action_64
action_7 (188) = happyShift action_65
action_7 (189) = happyShift action_66
action_7 (190) = happyShift action_67
action_7 (191) = happyShift action_68
action_7 (192) = happyShift action_69
action_7 (193) = happyShift action_70
action_7 (194) = happyShift action_71
action_7 (6) = happyGoto action_148
action_7 (15) = happyGoto action_9
action_7 (16) = happyGoto action_10
action_7 (25) = happyGoto action_11
action_7 (26) = happyGoto action_12
action_7 (28) = happyGoto action_13
action_7 (30) = happyGoto action_14
action_7 (33) = happyGoto action_15
action_7 (35) = happyGoto action_16
action_7 (36) = happyGoto action_17
action_7 (64) = happyGoto action_18
action_7 (70) = happyGoto action_19
action_7 (71) = happyGoto action_20
action_7 (72) = happyGoto action_21
action_7 (74) = happyGoto action_22
action_7 (75) = happyGoto action_23
action_7 (93) = happyGoto action_24
action_7 (95) = happyGoto action_25
action_7 (97) = happyGoto action_26
action_7 (104) = happyGoto action_27
action_7 (105) = happyGoto action_28
action_7 (106) = happyGoto action_29
action_7 (108) = happyGoto action_30
action_7 (114) = happyGoto action_31
action_7 (125) = happyGoto action_32
action_7 (126) = happyGoto action_33
action_7 _ = happyReduce_8
action_8 (1) = happyShift action_146
action_8 (147) = happyShift action_147
action_8 (116) = happyGoto action_145
action_8 _ = happyFail
action_9 (144) = happyShift action_144
action_9 (7) = happyGoto action_143
action_9 _ = happyReduce_10
action_10 _ = happyReduce_30
action_11 (144) = happyShift action_142
action_11 (7) = happyGoto action_141
action_11 _ = happyReduce_10
action_12 _ = happyReduce_75
action_13 (115) = happyGoto action_140
action_13 _ = happyReduce_278
action_14 _ = happyReduce_52
action_15 _ = happyReduce_69
action_16 _ = happyReduce_74
action_17 (150) = happyShift action_139
action_17 (115) = happyGoto action_138
action_17 _ = happyReduce_278
action_18 _ = happyReduce_76
action_19 (132) = happyShift action_137
action_19 (133) = happyShift action_118
action_19 (134) = happyShift action_119
action_19 (135) = happyShift action_120
action_19 (136) = happyShift action_121
action_19 (152) = happyShift action_124
action_19 (153) = happyShift action_125
action_19 (164) = happyShift action_126
action_19 (99) = happyGoto action_109
action_19 (101) = happyGoto action_110
action_19 (103) = happyGoto action_133
action_19 (109) = happyGoto action_134
action_19 (110) = happyGoto action_113
action_19 (111) = happyGoto action_135
action_19 (112) = happyGoto action_115
action_19 (113) = happyGoto action_116
action_19 (115) = happyGoto action_136
action_19 _ = happyReduce_278
action_20 _ = happyReduce_161
action_21 (128) = happyShift action_34
action_21 (129) = happyShift action_35
action_21 (130) = happyShift action_36
action_21 (131) = happyShift action_37
action_21 (137) = happyShift action_39
action_21 (138) = happyShift action_40
action_21 (139) = happyShift action_41
action_21 (140) = happyShift action_42
action_21 (141) = happyShift action_43
action_21 (142) = happyShift action_44
action_21 (148) = happyShift action_45
action_21 (151) = happyShift action_46
action_21 (162) = happyShift action_48
action_21 (165) = happyShift action_49
action_21 (173) = happyShift action_55
action_21 (188) = happyShift action_65
action_21 (74) = happyGoto action_132
action_21 (75) = happyGoto action_23
action_21 (93) = happyGoto action_24
action_21 (95) = happyGoto action_90
action_21 (97) = happyGoto action_26
action_21 (104) = happyGoto action_27
action_21 (105) = happyGoto action_28
action_21 (106) = happyGoto action_29
action_21 (108) = happyGoto action_30
action_21 (114) = happyGoto action_31
action_21 _ = happyReduce_170
action_22 (145) = happyShift action_131
action_22 _ = happyReduce_172
action_23 _ = happyReduce_176
action_24 _ = happyReduce_178
action_25 (150) = happyReduce_82
action_25 (155) = happyReduce_82
action_25 (161) = happyShift action_130
action_25 _ = happyReduce_177
action_26 _ = happyReduce_232
action_27 _ = happyReduce_235
action_28 _ = happyReduce_253
action_29 _ = happyReduce_239
action_30 _ = happyReduce_259
action_31 _ = happyReduce_179
action_32 _ = happyReduce_77
action_33 (128) = happyShift action_34
action_33 (129) = happyShift action_35
action_33 (130) = happyShift action_36
action_33 (131) = happyShift action_37
action_33 (137) = happyShift action_39
action_33 (138) = happyShift action_40
action_33 (139) = happyShift action_41
action_33 (140) = happyShift action_42
action_33 (141) = happyShift action_43
action_33 (142) = happyShift action_44
action_33 (148) = happyShift action_45
action_33 (151) = happyShift action_46
action_33 (162) = happyShift action_48
action_33 (165) = happyShift action_49
action_33 (173) = happyShift action_55
action_33 (188) = happyShift action_65
action_33 (73) = happyGoto action_129
action_33 (74) = happyGoto action_100
action_33 (75) = happyGoto action_23
action_33 (93) = happyGoto action_24
action_33 (95) = happyGoto action_90
action_33 (97) = happyGoto action_26
action_33 (104) = happyGoto action_27
action_33 (105) = happyGoto action_28
action_33 (106) = happyGoto action_29
action_33 (108) = happyGoto action_30
action_33 (114) = happyGoto action_31
action_33 _ = happyFail
action_34 _ = happyReduce_255
action_35 _ = happyReduce_254
action_36 _ = happyReduce_263
action_37 _ = happyReduce_260
action_38 (128) = happyShift action_34
action_38 (129) = happyShift action_35
action_38 (130) = happyShift action_36
action_38 (131) = happyShift action_37
action_38 (137) = happyShift action_39
action_38 (138) = happyShift action_40
action_38 (139) = happyShift action_41
action_38 (140) = happyShift action_42
action_38 (141) = happyShift action_43
action_38 (142) = happyShift action_44
action_38 (148) = happyShift action_45
action_38 (151) = happyShift action_46
action_38 (162) = happyShift action_48
action_38 (165) = happyShift action_49
action_38 (173) = happyShift action_55
action_38 (188) = happyShift action_65
action_38 (72) = happyGoto action_128
action_38 (74) = happyGoto action_22
action_38 (75) = happyGoto action_23
action_38 (93) = happyGoto action_24
action_38 (95) = happyGoto action_90
action_38 (97) = happyGoto action_26
action_38 (104) = happyGoto action_27
action_38 (105) = happyGoto action_28
action_38 (106) = happyGoto action_29
action_38 (108) = happyGoto action_30
action_38 (114) = happyGoto action_31
action_38 _ = happyFail
action_39 (153) = happyShift action_127
action_39 _ = happyFail
action_40 _ = happyReduce_274
action_41 _ = happyReduce_277
action_42 _ = happyReduce_275
action_43 _ = happyReduce_276
action_44 (128) = happyShift action_34
action_44 (129) = happyShift action_35
action_44 (130) = happyShift action_36
action_44 (131) = happyShift action_37
action_44 (132) = happyShift action_117
action_44 (133) = happyShift action_118
action_44 (134) = happyShift action_119
action_44 (135) = happyShift action_120
action_44 (136) = happyShift action_121
action_44 (137) = happyShift action_39
action_44 (138) = happyShift action_40
action_44 (139) = happyShift action_41
action_44 (140) = happyShift action_42
action_44 (141) = happyShift action_43
action_44 (142) = happyShift action_44
action_44 (143) = happyShift action_122
action_44 (148) = happyShift action_45
action_44 (150) = happyShift action_123
action_44 (151) = happyShift action_46
action_44 (152) = happyShift action_124
action_44 (153) = happyShift action_125
action_44 (157) = happyShift action_47
action_44 (162) = happyShift action_48
action_44 (164) = happyShift action_126
action_44 (165) = happyShift action_49
action_44 (166) = happyShift action_50
action_44 (171) = happyShift action_54
action_44 (173) = happyShift action_55
action_44 (174) = happyShift action_56
action_44 (181) = happyShift action_62
action_44 (188) = happyShift action_65
action_44 (191) = happyShift action_68
action_44 (192) = happyShift action_69
action_44 (193) = happyShift action_70
action_44 (194) = happyShift action_71
action_44 (69) = happyGoto action_105
action_44 (70) = happyGoto action_106
action_44 (71) = happyGoto action_20
action_44 (72) = happyGoto action_21
action_44 (74) = happyGoto action_22
action_44 (75) = happyGoto action_23
action_44 (76) = happyGoto action_107
action_44 (77) = happyGoto action_108
action_44 (93) = happyGoto action_24
action_44 (95) = happyGoto action_90
action_44 (97) = happyGoto action_26
action_44 (99) = happyGoto action_109
action_44 (101) = happyGoto action_110
action_44 (103) = happyGoto action_111
action_44 (104) = happyGoto action_27
action_44 (105) = happyGoto action_28
action_44 (106) = happyGoto action_29
action_44 (108) = happyGoto action_30
action_44 (109) = happyGoto action_112
action_44 (110) = happyGoto action_113
action_44 (111) = happyGoto action_114
action_44 (112) = happyGoto action_115
action_44 (113) = happyGoto action_116
action_44 (114) = happyGoto action_31
action_44 (126) = happyGoto action_33
action_44 _ = happyFail
action_45 (128) = happyShift action_34
action_45 (129) = happyShift action_35
action_45 (130) = happyShift action_36
action_45 (131) = happyShift action_37
action_45 (132) = happyShift action_38
action_45 (137) = happyShift action_39
action_45 (138) = happyShift action_40
action_45 (139) = happyShift action_41
action_45 (140) = happyShift action_42
action_45 (141) = happyShift action_43
action_45 (142) = happyShift action_44
action_45 (148) = happyShift action_45
action_45 (149) = happyShift action_104
action_45 (151) = happyShift action_46
action_45 (157) = happyShift action_47
action_45 (162) = happyShift action_48
action_45 (165) = happyShift action_49
action_45 (166) = happyShift action_50
action_45 (171) = happyShift action_54
action_45 (173) = happyShift action_55
action_45 (174) = happyShift action_56
action_45 (181) = happyShift action_62
action_45 (188) = happyShift action_65
action_45 (191) = happyShift action_68
action_45 (192) = happyShift action_69
action_45 (193) = happyShift action_70
action_45 (194) = happyShift action_71
action_45 (69) = happyGoto action_101
action_45 (70) = happyGoto action_89
action_45 (71) = happyGoto action_20
action_45 (72) = happyGoto action_21
action_45 (74) = happyGoto action_22
action_45 (75) = happyGoto action_23
action_45 (78) = happyGoto action_102
action_45 (79) = happyGoto action_103
action_45 (93) = happyGoto action_24
action_45 (95) = happyGoto action_90
action_45 (97) = happyGoto action_26
action_45 (104) = happyGoto action_27
action_45 (105) = happyGoto action_28
action_45 (106) = happyGoto action_29
action_45 (108) = happyGoto action_30
action_45 (114) = happyGoto action_31
action_45 (126) = happyGoto action_33
action_45 _ = happyFail
action_46 _ = happyReduce_186
action_47 (128) = happyShift action_34
action_47 (129) = happyShift action_35
action_47 (130) = happyShift action_36
action_47 (131) = happyShift action_37
action_47 (137) = happyShift action_39
action_47 (138) = happyShift action_40
action_47 (139) = happyShift action_41
action_47 (140) = happyShift action_42
action_47 (141) = happyShift action_43
action_47 (142) = happyShift action_44
action_47 (148) = happyShift action_45
action_47 (151) = happyShift action_46
action_47 (162) = happyShift action_48
action_47 (165) = happyShift action_49
action_47 (173) = happyShift action_55
action_47 (188) = happyShift action_65
action_47 (73) = happyGoto action_99
action_47 (74) = happyGoto action_100
action_47 (75) = happyGoto action_23
action_47 (93) = happyGoto action_24
action_47 (95) = happyGoto action_90
action_47 (97) = happyGoto action_26
action_47 (104) = happyGoto action_27
action_47 (105) = happyGoto action_28
action_47 (106) = happyGoto action_29
action_47 (108) = happyGoto action_30
action_47 (114) = happyGoto action_31
action_47 _ = happyFail
action_48 (128) = happyShift action_34
action_48 (129) = happyShift action_35
action_48 (130) = happyShift action_36
action_48 (131) = happyShift action_37
action_48 (137) = happyShift action_39
action_48 (138) = happyShift action_40
action_48 (139) = happyShift action_41
action_48 (140) = happyShift action_42
action_48 (141) = happyShift action_43
action_48 (142) = happyShift action_44
action_48 (148) = happyShift action_45
action_48 (151) = happyShift action_46
action_48 (162) = happyShift action_48
action_48 (165) = happyShift action_49
action_48 (173) = happyShift action_55
action_48 (188) = happyShift action_65
action_48 (75) = happyGoto action_98
action_48 (93) = happyGoto action_24
action_48 (95) = happyGoto action_90
action_48 (97) = happyGoto action_26
action_48 (104) = happyGoto action_27
action_48 (105) = happyGoto action_28
action_48 (106) = happyGoto action_29
action_48 (108) = happyGoto action_30
action_48 (114) = happyGoto action_31
action_48 _ = happyFail
action_49 _ = happyReduce_256
action_50 (128) = happyShift action_34
action_50 (129) = happyShift action_35
action_50 (130) = happyShift action_36
action_50 (131) = happyShift action_37
action_50 (132) = happyShift action_38
action_50 (137) = happyShift action_39
action_50 (138) = happyShift action_40
action_50 (139) = happyShift action_41
action_50 (140) = happyShift action_42
action_50 (141) = happyShift action_43
action_50 (142) = happyShift action_44
action_50 (148) = happyShift action_45
action_50 (151) = happyShift action_46
action_50 (157) = happyShift action_47
action_50 (162) = happyShift action_48
action_50 (165) = happyShift action_49
action_50 (166) = happyShift action_50
action_50 (171) = happyShift action_54
action_50 (173) = happyShift action_55
action_50 (174) = happyShift action_56
action_50 (181) = happyShift action_62
action_50 (188) = happyShift action_65
action_50 (191) = happyShift action_68
action_50 (192) = happyShift action_69
action_50 (193) = happyShift action_70
action_50 (194) = happyShift action_71
action_50 (69) = happyGoto action_97
action_50 (70) = happyGoto action_89
action_50 (71) = happyGoto action_20
action_50 (72) = happyGoto action_21
action_50 (74) = happyGoto action_22
action_50 (75) = happyGoto action_23
action_50 (93) = happyGoto action_24
action_50 (95) = happyGoto action_90
action_50 (97) = happyGoto action_26
action_50 (104) = happyGoto action_27
action_50 (105) = happyGoto action_28
action_50 (106) = happyGoto action_29
action_50 (108) = happyGoto action_30
action_50 (114) = happyGoto action_31
action_50 (126) = happyGoto action_33
action_50 _ = happyFail
action_51 (115) = happyGoto action_96
action_51 _ = happyReduce_278
action_52 (115) = happyGoto action_95
action_52 _ = happyReduce_278
action_53 (115) = happyGoto action_94
action_53 _ = happyReduce_278
action_54 (145) = happyShift action_93
action_54 (88) = happyGoto action_91
action_54 (118) = happyGoto action_92
action_54 _ = happyReduce_282
action_55 _ = happyReduce_258
action_56 (128) = happyShift action_34
action_56 (129) = happyShift action_35
action_56 (130) = happyShift action_36
action_56 (131) = happyShift action_37
action_56 (132) = happyShift action_38
action_56 (137) = happyShift action_39
action_56 (138) = happyShift action_40
action_56 (139) = happyShift action_41
action_56 (140) = happyShift action_42
action_56 (141) = happyShift action_43
action_56 (142) = happyShift action_44
action_56 (148) = happyShift action_45
action_56 (151) = happyShift action_46
action_56 (157) = happyShift action_47
action_56 (162) = happyShift action_48
action_56 (165) = happyShift action_49
action_56 (166) = happyShift action_50
action_56 (171) = happyShift action_54
action_56 (173) = happyShift action_55
action_56 (174) = happyShift action_56
action_56 (181) = happyShift action_62
action_56 (188) = happyShift action_65
action_56 (191) = happyShift action_68
action_56 (192) = happyShift action_69
action_56 (193) = happyShift action_70
action_56 (194) = happyShift action_71
action_56 (69) = happyGoto action_88
action_56 (70) = happyGoto action_89
action_56 (71) = happyGoto action_20
action_56 (72) = happyGoto action_21
action_56 (74) = happyGoto action_22
action_56 (75) = happyGoto action_23
action_56 (93) = happyGoto action_24
action_56 (95) = happyGoto action_90
action_56 (97) = happyGoto action_26
action_56 (104) = happyGoto action_27
action_56 (105) = happyGoto action_28
action_56 (106) = happyGoto action_29
action_56 (108) = happyGoto action_30
action_56 (114) = happyGoto action_31
action_56 (126) = happyGoto action_33
action_56 _ = happyFail
action_57 (115) = happyGoto action_87
action_57 _ = happyReduce_278
action_58 _ = happyReduce_56
action_59 _ = happyReduce_57
action_60 _ = happyReduce_58
action_61 (115) = happyGoto action_86
action_61 _ = happyReduce_278
action_62 (145) = happyShift action_85
action_62 (34) = happyGoto action_83
action_62 (118) = happyGoto action_84
action_62 _ = happyReduce_282
action_63 (115) = happyGoto action_82
action_63 _ = happyReduce_278
action_64 (130) = happyShift action_36
action_64 (44) = happyGoto action_79
action_64 (108) = happyGoto action_80
action_64 (121) = happyGoto action_81
action_64 _ = happyFail
action_65 _ = happyReduce_257
action_66 (115) = happyGoto action_78
action_66 _ = happyReduce_278
action_67 (115) = happyGoto action_77
action_67 _ = happyReduce_278
action_68 _ = happyReduce_290
action_69 _ = happyReduce_291
action_70 _ = happyReduce_292
action_71 _ = happyReduce_293
action_72 (142) = happyShift action_76
action_72 (8) = happyGoto action_74
action_72 (9) = happyGoto action_75
action_72 _ = happyReduce_12
action_73 _ = happyReduce_283
action_74 (187) = happyShift action_244
action_74 _ = happyFail
action_75 _ = happyReduce_11
action_76 (128) = happyShift action_34
action_76 (129) = happyShift action_35
action_76 (130) = happyShift action_36
action_76 (131) = happyShift action_200
action_76 (142) = happyShift action_241
action_76 (143) = happyShift action_242
action_76 (165) = happyShift action_49
action_76 (173) = happyShift action_55
action_76 (182) = happyShift action_243
action_76 (188) = happyShift action_65
action_76 (11) = happyGoto action_236
action_76 (12) = happyGoto action_237
action_76 (95) = happyGoto action_238
action_76 (104) = happyGoto action_27
action_76 (105) = happyGoto action_28
action_76 (107) = happyGoto action_239
action_76 (108) = happyGoto action_80
action_76 (121) = happyGoto action_198
action_76 (122) = happyGoto action_240
action_76 _ = happyFail
action_77 (130) = happyShift action_36
action_77 (108) = happyGoto action_235
action_77 _ = happyFail
action_78 (128) = happyShift action_34
action_78 (142) = happyShift action_157
action_78 (165) = happyShift action_49
action_78 (173) = happyShift action_55
action_78 (188) = happyShift action_65
action_78 (94) = happyGoto action_234
action_78 (105) = happyGoto action_156
action_78 _ = happyFail
action_79 (115) = happyGoto action_233
action_79 _ = happyReduce_278
action_80 _ = happyReduce_285
action_81 (128) = happyShift action_34
action_81 (165) = happyShift action_49
action_81 (173) = happyShift action_55
action_81 (188) = happyShift action_65
action_81 (45) = happyGoto action_231
action_81 (105) = happyGoto action_196
action_81 (124) = happyGoto action_232
action_81 _ = happyReduce_107
action_82 (128) = happyShift action_34
action_82 (130) = happyShift action_36
action_82 (131) = happyShift action_200
action_82 (137) = happyShift action_201
action_82 (142) = happyShift action_202
action_82 (148) = happyShift action_203
action_82 (165) = happyShift action_49
action_82 (173) = happyShift action_55
action_82 (188) = happyShift action_65
action_82 (37) = happyGoto action_228
action_82 (38) = happyGoto action_192
action_82 (39) = happyGoto action_193
action_82 (40) = happyGoto action_194
action_82 (43) = happyGoto action_229
action_82 (44) = happyGoto action_206
action_82 (105) = happyGoto action_196
action_82 (107) = happyGoto action_197
action_82 (108) = happyGoto action_80
action_82 (121) = happyGoto action_230
action_82 (124) = happyGoto action_199
action_82 _ = happyFail
action_83 (176) = happyShift action_227
action_83 _ = happyFail
action_84 (128) = happyShift action_34
action_84 (129) = happyShift action_35
action_84 (130) = happyShift action_36
action_84 (131) = happyShift action_37
action_84 (132) = happyShift action_38
action_84 (137) = happyShift action_39
action_84 (138) = happyShift action_40
action_84 (139) = happyShift action_41
action_84 (140) = happyShift action_42
action_84 (141) = happyShift action_43
action_84 (142) = happyShift action_44
action_84 (144) = happyShift action_226
action_84 (148) = happyShift action_45
action_84 (151) = happyShift action_46
action_84 (157) = happyShift action_47
action_84 (162) = happyShift action_48
action_84 (165) = happyShift action_49
action_84 (166) = happyShift action_50
action_84 (171) = happyShift action_54
action_84 (173) = happyShift action_55
action_84 (174) = happyShift action_56
action_84 (177) = happyShift action_58
action_84 (178) = happyShift action_59
action_84 (179) = happyShift action_60
action_84 (181) = happyShift action_62
action_84 (188) = happyShift action_65
action_84 (190) = happyShift action_67
action_84 (191) = happyShift action_68
action_84 (192) = happyShift action_69
action_84 (193) = happyShift action_70
action_84 (194) = happyShift action_71
action_84 (7) = happyGoto action_222
action_84 (26) = happyGoto action_12
action_84 (28) = happyGoto action_13
action_84 (31) = happyGoto action_223
action_84 (32) = happyGoto action_224
action_84 (33) = happyGoto action_225
action_84 (35) = happyGoto action_16
action_84 (36) = happyGoto action_17
action_84 (64) = happyGoto action_18
action_84 (70) = happyGoto action_19
action_84 (71) = happyGoto action_20
action_84 (72) = happyGoto action_21
action_84 (74) = happyGoto action_22
action_84 (75) = happyGoto action_23
action_84 (93) = happyGoto action_24
action_84 (95) = happyGoto action_25
action_84 (97) = happyGoto action_26
action_84 (104) = happyGoto action_27
action_84 (105) = happyGoto action_28
action_84 (106) = happyGoto action_29
action_84 (108) = happyGoto action_30
action_84 (114) = happyGoto action_31
action_84 (125) = happyGoto action_32
action_84 (126) = happyGoto action_33
action_84 _ = happyReduce_10
action_85 (117) = happyGoto action_221
action_85 _ = happyReduce_281
action_86 (128) = happyShift action_34
action_86 (130) = happyShift action_36
action_86 (131) = happyShift action_200
action_86 (137) = happyShift action_201
action_86 (142) = happyShift action_202
action_86 (148) = happyShift action_203
action_86 (165) = happyShift action_49
action_86 (173) = happyShift action_55
action_86 (188) = happyShift action_65
action_86 (37) = happyGoto action_191
action_86 (38) = happyGoto action_192
action_86 (39) = happyGoto action_193
action_86 (40) = happyGoto action_194
action_86 (41) = happyGoto action_220
action_86 (105) = happyGoto action_196
action_86 (107) = happyGoto action_197
action_86 (108) = happyGoto action_80
action_86 (121) = happyGoto action_198
action_86 (124) = happyGoto action_199
action_86 _ = happyFail
action_87 (188) = happyShift action_219
action_87 (17) = happyGoto action_218
action_87 _ = happyReduce_33
action_88 (185) = happyShift action_217
action_88 _ = happyFail
action_89 (132) = happyShift action_137
action_89 (133) = happyShift action_118
action_89 (134) = happyShift action_119
action_89 (135) = happyShift action_120
action_89 (136) = happyShift action_121
action_89 (152) = happyShift action_124
action_89 (153) = happyShift action_125
action_89 (155) = happyShift action_181
action_89 (164) = happyShift action_126
action_89 (99) = happyGoto action_109
action_89 (101) = happyGoto action_110
action_89 (103) = happyGoto action_133
action_89 (109) = happyGoto action_134
action_89 (110) = happyGoto action_113
action_89 (111) = happyGoto action_135
action_89 (112) = happyGoto action_115
action_89 (113) = happyGoto action_116
action_89 _ = happyReduce_160
action_90 (161) = happyShift action_130
action_90 _ = happyReduce_177
action_91 _ = happyReduce_169
action_92 (128) = happyShift action_34
action_92 (129) = happyShift action_35
action_92 (130) = happyShift action_36
action_92 (131) = happyShift action_37
action_92 (132) = happyShift action_38
action_92 (137) = happyShift action_39
action_92 (138) = happyShift action_40
action_92 (139) = happyShift action_41
action_92 (140) = happyShift action_42
action_92 (141) = happyShift action_43
action_92 (142) = happyShift action_44
action_92 (148) = happyShift action_45
action_92 (151) = happyShift action_46
action_92 (157) = happyShift action_47
action_92 (162) = happyShift action_48
action_92 (165) = happyShift action_49
action_92 (166) = happyShift action_50
action_92 (171) = happyShift action_54
action_92 (173) = happyShift action_55
action_92 (174) = happyShift action_56
action_92 (181) = happyShift action_216
action_92 (188) = happyShift action_65
action_92 (191) = happyShift action_68
action_92 (192) = happyShift action_69
action_92 (193) = happyShift action_70
action_92 (194) = happyShift action_71
action_92 (69) = happyGoto action_211
action_92 (70) = happyGoto action_212
action_92 (71) = happyGoto action_20
action_92 (72) = happyGoto action_21
action_92 (74) = happyGoto action_22
action_92 (75) = happyGoto action_23
action_92 (81) = happyGoto action_213
action_92 (89) = happyGoto action_214
action_92 (90) = happyGoto action_215
action_92 (93) = happyGoto action_24
action_92 (95) = happyGoto action_90
action_92 (97) = happyGoto action_26
action_92 (104) = happyGoto action_27
action_92 (105) = happyGoto action_28
action_92 (106) = happyGoto action_29
action_92 (108) = happyGoto action_30
action_92 (114) = happyGoto action_31
action_92 (126) = happyGoto action_33
action_92 _ = happyFail
action_93 (117) = happyGoto action_210
action_93 _ = happyReduce_281
action_94 (128) = happyShift action_34
action_94 (130) = happyShift action_36
action_94 (131) = happyShift action_200
action_94 (137) = happyShift action_201
action_94 (142) = happyShift action_202
action_94 (148) = happyShift action_203
action_94 (165) = happyShift action_49
action_94 (173) = happyShift action_55
action_94 (188) = happyShift action_65
action_94 (37) = happyGoto action_209
action_94 (38) = happyGoto action_192
action_94 (39) = happyGoto action_193
action_94 (40) = happyGoto action_194
action_94 (105) = happyGoto action_196
action_94 (107) = happyGoto action_197
action_94 (108) = happyGoto action_80
action_94 (121) = happyGoto action_198
action_94 (124) = happyGoto action_199
action_94 _ = happyFail
action_95 (128) = happyShift action_34
action_95 (130) = happyShift action_36
action_95 (131) = happyShift action_200
action_95 (137) = happyShift action_201
action_95 (142) = happyShift action_202
action_95 (148) = happyShift action_203
action_95 (165) = happyShift action_49
action_95 (173) = happyShift action_55
action_95 (188) = happyShift action_65
action_95 (37) = happyGoto action_204
action_95 (38) = happyGoto action_192
action_95 (39) = happyGoto action_193
action_95 (40) = happyGoto action_194
action_95 (43) = happyGoto action_205
action_95 (44) = happyGoto action_206
action_95 (46) = happyGoto action_207
action_95 (105) = happyGoto action_196
action_95 (107) = happyGoto action_197
action_95 (108) = happyGoto action_80
action_95 (121) = happyGoto action_208
action_95 (124) = happyGoto action_199
action_95 _ = happyFail
action_96 (128) = happyShift action_34
action_96 (130) = happyShift action_36
action_96 (131) = happyShift action_200
action_96 (137) = happyShift action_201
action_96 (142) = happyShift action_202
action_96 (148) = happyShift action_203
action_96 (165) = happyShift action_49
action_96 (173) = happyShift action_55
action_96 (188) = happyShift action_65
action_96 (37) = happyGoto action_191
action_96 (38) = happyGoto action_192
action_96 (39) = happyGoto action_193
action_96 (40) = happyGoto action_194
action_96 (41) = happyGoto action_195
action_96 (105) = happyGoto action_196
action_96 (107) = happyGoto action_197
action_96 (108) = happyGoto action_80
action_96 (121) = happyGoto action_198
action_96 (124) = happyGoto action_199
action_96 _ = happyFail
action_97 (184) = happyShift action_190
action_97 _ = happyFail
action_98 _ = happyReduce_187
action_99 (128) = happyShift action_34
action_99 (129) = happyShift action_35
action_99 (130) = happyShift action_36
action_99 (131) = happyShift action_37
action_99 (137) = happyShift action_39
action_99 (138) = happyShift action_40
action_99 (139) = happyShift action_41
action_99 (140) = happyShift action_42
action_99 (141) = happyShift action_43
action_99 (142) = happyShift action_44
action_99 (148) = happyShift action_45
action_99 (151) = happyShift action_46
action_99 (160) = happyShift action_189
action_99 (162) = happyShift action_48
action_99 (165) = happyShift action_49
action_99 (173) = happyShift action_55
action_99 (188) = happyShift action_65
action_99 (74) = happyGoto action_167
action_99 (75) = happyGoto action_23
action_99 (93) = happyGoto action_24
action_99 (95) = happyGoto action_90
action_99 (97) = happyGoto action_26
action_99 (104) = happyGoto action_27
action_99 (105) = happyGoto action_28
action_99 (106) = happyGoto action_29
action_99 (108) = happyGoto action_30
action_99 (114) = happyGoto action_31
action_99 _ = happyFail
action_100 (145) = happyShift action_131
action_100 _ = happyReduce_174
action_101 (150) = happyShift action_186
action_101 (154) = happyShift action_187
action_101 (158) = happyShift action_188
action_101 _ = happyReduce_192
action_102 (149) = happyShift action_185
action_102 _ = happyFail
action_103 (150) = happyShift action_184
action_103 _ = happyReduce_193
action_104 _ = happyReduce_227
action_105 (143) = happyShift action_182
action_105 (150) = happyShift action_183
action_105 _ = happyFail
action_106 (132) = happyShift action_137
action_106 (133) = happyShift action_118
action_106 (134) = happyShift action_119
action_106 (135) = happyShift action_120
action_106 (136) = happyShift action_121
action_106 (152) = happyShift action_124
action_106 (153) = happyShift action_125
action_106 (155) = happyShift action_181
action_106 (164) = happyShift action_126
action_106 (99) = happyGoto action_109
action_106 (101) = happyGoto action_110
action_106 (103) = happyGoto action_180
action_106 (109) = happyGoto action_134
action_106 (110) = happyGoto action_113
action_106 (111) = happyGoto action_135
action_106 (112) = happyGoto action_115
action_106 (113) = happyGoto action_116
action_106 _ = happyReduce_160
action_107 (143) = happyShift action_178
action_107 (150) = happyShift action_179
action_107 _ = happyFail
action_108 (143) = happyShift action_176
action_108 (150) = happyShift action_177
action_108 _ = happyFail
action_109 _ = happyReduce_251
action_110 _ = happyReduce_252
action_111 (128) = happyShift action_34
action_111 (129) = happyShift action_35
action_111 (130) = happyShift action_36
action_111 (131) = happyShift action_37
action_111 (132) = happyShift action_38
action_111 (137) = happyShift action_39
action_111 (138) = happyShift action_40
action_111 (139) = happyShift action_41
action_111 (140) = happyShift action_42
action_111 (141) = happyShift action_43
action_111 (142) = happyShift action_44
action_111 (148) = happyShift action_45
action_111 (151) = happyShift action_46
action_111 (157) = happyShift action_47
action_111 (162) = happyShift action_48
action_111 (165) = happyShift action_49
action_111 (166) = happyShift action_50
action_111 (171) = happyShift action_54
action_111 (173) = happyShift action_55
action_111 (174) = happyShift action_56
action_111 (181) = happyShift action_62
action_111 (188) = happyShift action_65
action_111 (191) = happyShift action_68
action_111 (192) = happyShift action_69
action_111 (193) = happyShift action_70
action_111 (194) = happyShift action_71
action_111 (70) = happyGoto action_175
action_111 (71) = happyGoto action_20
action_111 (72) = happyGoto action_21
action_111 (74) = happyGoto action_22
action_111 (75) = happyGoto action_23
action_111 (93) = happyGoto action_24
action_111 (95) = happyGoto action_90
action_111 (97) = happyGoto action_26
action_111 (104) = happyGoto action_27
action_111 (105) = happyGoto action_28
action_111 (106) = happyGoto action_29
action_111 (108) = happyGoto action_30
action_111 (114) = happyGoto action_31
action_111 (126) = happyGoto action_33
action_111 _ = happyFail
action_112 (143) = happyShift action_174
action_112 _ = happyReduce_247
action_113 _ = happyReduce_264
action_114 (143) = happyShift action_173
action_114 _ = happyReduce_243
action_115 _ = happyReduce_267
action_116 _ = happyReduce_268
action_117 (128) = happyShift action_34
action_117 (129) = happyShift action_35
action_117 (130) = happyShift action_36
action_117 (131) = happyShift action_37
action_117 (137) = happyShift action_39
action_117 (138) = happyShift action_40
action_117 (139) = happyShift action_41
action_117 (140) = happyShift action_42
action_117 (141) = happyShift action_43
action_117 (142) = happyShift action_44
action_117 (148) = happyShift action_45
action_117 (151) = happyShift action_46
action_117 (162) = happyShift action_48
action_117 (165) = happyShift action_49
action_117 (173) = happyShift action_55
action_117 (188) = happyShift action_65
action_117 (72) = happyGoto action_128
action_117 (74) = happyGoto action_22
action_117 (75) = happyGoto action_23
action_117 (93) = happyGoto action_24
action_117 (95) = happyGoto action_90
action_117 (97) = happyGoto action_26
action_117 (104) = happyGoto action_27
action_117 (105) = happyGoto action_28
action_117 (106) = happyGoto action_29
action_117 (108) = happyGoto action_30
action_117 (114) = happyGoto action_31
action_117 _ = happyReduce_270
action_118 _ = happyReduce_269
action_119 _ = happyReduce_266
action_120 _ = happyReduce_273
action_121 _ = happyReduce_265
action_122 _ = happyReduce_226
action_123 _ = happyReduce_189
action_124 (128) = happyShift action_34
action_124 (129) = happyShift action_35
action_124 (130) = happyShift action_36
action_124 (131) = happyShift action_37
action_124 (165) = happyShift action_49
action_124 (173) = happyShift action_55
action_124 (188) = happyShift action_65
action_124 (104) = happyGoto action_171
action_124 (105) = happyGoto action_28
action_124 (106) = happyGoto action_172
action_124 (108) = happyGoto action_30
action_124 _ = happyFail
action_125 _ = happyReduce_272
action_126 _ = happyReduce_271
action_127 (142) = happyShift action_169
action_127 (148) = happyShift action_170
action_127 _ = happyFail
action_128 (128) = happyShift action_34
action_128 (129) = happyShift action_35
action_128 (130) = happyShift action_36
action_128 (131) = happyShift action_37
action_128 (137) = happyShift action_39
action_128 (138) = happyShift action_40
action_128 (139) = happyShift action_41
action_128 (140) = happyShift action_42
action_128 (141) = happyShift action_43
action_128 (142) = happyShift action_44
action_128 (148) = happyShift action_45
action_128 (151) = happyShift action_46
action_128 (162) = happyShift action_48
action_128 (165) = happyShift action_49
action_128 (173) = happyShift action_55
action_128 (188) = happyShift action_65
action_128 (74) = happyGoto action_132
action_128 (75) = happyGoto action_23
action_128 (93) = happyGoto action_24
action_128 (95) = happyGoto action_90
action_128 (97) = happyGoto action_26
action_128 (104) = happyGoto action_27
action_128 (105) = happyGoto action_28
action_128 (106) = happyGoto action_29
action_128 (108) = happyGoto action_30
action_128 (114) = happyGoto action_31
action_128 _ = happyReduce_168
action_129 (128) = happyShift action_34
action_129 (129) = happyShift action_35
action_129 (130) = happyShift action_36
action_129 (131) = happyShift action_37
action_129 (137) = happyShift action_39
action_129 (138) = happyShift action_40
action_129 (139) = happyShift action_41
action_129 (140) = happyShift action_42
action_129 (141) = happyShift action_43
action_129 (142) = happyShift action_44
action_129 (148) = happyShift action_45
action_129 (151) = happyShift action_46
action_129 (153) = happyShift action_168
action_129 (162) = happyShift action_48
action_129 (165) = happyShift action_49
action_129 (173) = happyShift action_55
action_129 (188) = happyShift action_65
action_129 (74) = happyGoto action_167
action_129 (75) = happyGoto action_23
action_129 (93) = happyGoto action_24
action_129 (95) = happyGoto action_90
action_129 (97) = happyGoto action_26
action_129 (104) = happyGoto action_27
action_129 (105) = happyGoto action_28
action_129 (106) = happyGoto action_29
action_129 (108) = happyGoto action_30
action_129 (114) = happyGoto action_31
action_129 _ = happyFail
action_130 (128) = happyShift action_34
action_130 (129) = happyShift action_35
action_130 (130) = happyShift action_36
action_130 (131) = happyShift action_37
action_130 (137) = happyShift action_39
action_130 (138) = happyShift action_40
action_130 (139) = happyShift action_41
action_130 (140) = happyShift action_42
action_130 (141) = happyShift action_43
action_130 (142) = happyShift action_44
action_130 (148) = happyShift action_45
action_130 (151) = happyShift action_46
action_130 (162) = happyShift action_48
action_130 (165) = happyShift action_49
action_130 (173) = happyShift action_55
action_130 (188) = happyShift action_65
action_130 (75) = happyGoto action_166
action_130 (93) = happyGoto action_24
action_130 (95) = happyGoto action_90
action_130 (97) = happyGoto action_26
action_130 (104) = happyGoto action_27
action_130 (105) = happyGoto action_28
action_130 (106) = happyGoto action_29
action_130 (108) = happyGoto action_30
action_130 (114) = happyGoto action_31
action_130 _ = happyFail
action_131 (117) = happyGoto action_165
action_131 _ = happyReduce_281
action_132 (145) = happyShift action_131
action_132 _ = happyReduce_171
action_133 (128) = happyShift action_34
action_133 (129) = happyShift action_35
action_133 (130) = happyShift action_36
action_133 (131) = happyShift action_37
action_133 (132) = happyShift action_38
action_133 (137) = happyShift action_39
action_133 (138) = happyShift action_40
action_133 (139) = happyShift action_41
action_133 (140) = happyShift action_42
action_133 (141) = happyShift action_43
action_133 (142) = happyShift action_44
action_133 (148) = happyShift action_45
action_133 (151) = happyShift action_46
action_133 (157) = happyShift action_47
action_133 (162) = happyShift action_48
action_133 (165) = happyShift action_49
action_133 (166) = happyShift action_50
action_133 (171) = happyShift action_54
action_133 (173) = happyShift action_55
action_133 (174) = happyShift action_56
action_133 (181) = happyShift action_62
action_133 (188) = happyShift action_65
action_133 (191) = happyShift action_68
action_133 (192) = happyShift action_69
action_133 (193) = happyShift action_70
action_133 (194) = happyShift action_71
action_133 (71) = happyGoto action_164
action_133 (72) = happyGoto action_21
action_133 (74) = happyGoto action_22
action_133 (75) = happyGoto action_23
action_133 (93) = happyGoto action_24
action_133 (95) = happyGoto action_90
action_133 (97) = happyGoto action_26
action_133 (104) = happyGoto action_27
action_133 (105) = happyGoto action_28
action_133 (106) = happyGoto action_29
action_133 (108) = happyGoto action_30
action_133 (114) = happyGoto action_31
action_133 (126) = happyGoto action_33
action_133 _ = happyFail
action_134 _ = happyReduce_247
action_135 _ = happyReduce_243
action_136 (156) = happyShift action_162
action_136 (158) = happyShift action_163
action_136 (66) = happyGoto action_159
action_136 (67) = happyGoto action_160
action_136 (68) = happyGoto action_161
action_136 _ = happyFail
action_137 _ = happyReduce_270
action_138 (155) = happyShift action_158
action_138 _ = happyFail
action_139 (128) = happyShift action_34
action_139 (142) = happyShift action_157
action_139 (165) = happyShift action_49
action_139 (173) = happyShift action_55
action_139 (188) = happyShift action_65
action_139 (94) = happyGoto action_155
action_139 (105) = happyGoto action_156
action_139 _ = happyFail
action_140 (138) = happyShift action_154
action_140 (27) = happyGoto action_153
action_140 _ = happyReduce_54
action_141 _ = happyReduce_6
action_142 (128) = happyShift action_34
action_142 (129) = happyShift action_35
action_142 (130) = happyShift action_36
action_142 (131) = happyShift action_37
action_142 (132) = happyShift action_38
action_142 (137) = happyShift action_39
action_142 (138) = happyShift action_40
action_142 (139) = happyShift action_41
action_142 (140) = happyShift action_42
action_142 (141) = happyShift action_43
action_142 (142) = happyShift action_44
action_142 (148) = happyShift action_45
action_142 (151) = happyShift action_46
action_142 (157) = happyShift action_47
action_142 (162) = happyShift action_48
action_142 (165) = happyShift action_49
action_142 (166) = happyShift action_50
action_142 (167) = happyShift action_51
action_142 (168) = happyShift action_52
action_142 (169) = happyShift action_53
action_142 (171) = happyShift action_54
action_142 (173) = happyShift action_55
action_142 (174) = happyShift action_56
action_142 (177) = happyShift action_58
action_142 (178) = happyShift action_59
action_142 (179) = happyShift action_60
action_142 (180) = happyShift action_61
action_142 (181) = happyShift action_62
action_142 (183) = happyShift action_63
action_142 (186) = happyShift action_64
action_142 (188) = happyShift action_65
action_142 (189) = happyShift action_66
action_142 (190) = happyShift action_67
action_142 (191) = happyShift action_68
action_142 (192) = happyShift action_69
action_142 (193) = happyShift action_70
action_142 (194) = happyShift action_71
action_142 (26) = happyGoto action_12
action_142 (28) = happyGoto action_13
action_142 (30) = happyGoto action_152
action_142 (33) = happyGoto action_15
action_142 (35) = happyGoto action_16
action_142 (36) = happyGoto action_17
action_142 (64) = happyGoto action_18
action_142 (70) = happyGoto action_19
action_142 (71) = happyGoto action_20
action_142 (72) = happyGoto action_21
action_142 (74) = happyGoto action_22
action_142 (75) = happyGoto action_23
action_142 (93) = happyGoto action_24
action_142 (95) = happyGoto action_25
action_142 (97) = happyGoto action_26
action_142 (104) = happyGoto action_27
action_142 (105) = happyGoto action_28
action_142 (106) = happyGoto action_29
action_142 (108) = happyGoto action_30
action_142 (114) = happyGoto action_31
action_142 (125) = happyGoto action_32
action_142 (126) = happyGoto action_33
action_142 _ = happyReduce_9
action_143 _ = happyReduce_7
action_144 (128) = happyShift action_34
action_144 (129) = happyShift action_35
action_144 (130) = happyShift action_36
action_144 (131) = happyShift action_37
action_144 (132) = happyShift action_38
action_144 (137) = happyShift action_39
action_144 (138) = happyShift action_40
action_144 (139) = happyShift action_41
action_144 (140) = happyShift action_42
action_144 (141) = happyShift action_43
action_144 (142) = happyShift action_44
action_144 (148) = happyShift action_45
action_144 (151) = happyShift action_46
action_144 (157) = happyShift action_47
action_144 (162) = happyShift action_48
action_144 (165) = happyShift action_49
action_144 (166) = happyShift action_50
action_144 (167) = happyShift action_51
action_144 (168) = happyShift action_52
action_144 (169) = happyShift action_53
action_144 (171) = happyShift action_54
action_144 (173) = happyShift action_55
action_144 (174) = happyShift action_56
action_144 (175) = happyShift action_57
action_144 (177) = happyShift action_58
action_144 (178) = happyShift action_59
action_144 (179) = happyShift action_60
action_144 (180) = happyShift action_61
action_144 (181) = happyShift action_62
action_144 (183) = happyShift action_63
action_144 (186) = happyShift action_64
action_144 (188) = happyShift action_65
action_144 (189) = happyShift action_66
action_144 (190) = happyShift action_67
action_144 (191) = happyShift action_68
action_144 (192) = happyShift action_69
action_144 (193) = happyShift action_70
action_144 (194) = happyShift action_71
action_144 (16) = happyGoto action_150
action_144 (25) = happyGoto action_151
action_144 (26) = happyGoto action_12
action_144 (28) = happyGoto action_13
action_144 (30) = happyGoto action_14
action_144 (33) = happyGoto action_15
action_144 (35) = happyGoto action_16
action_144 (36) = happyGoto action_17
action_144 (64) = happyGoto action_18
action_144 (70) = happyGoto action_19
action_144 (71) = happyGoto action_20
action_144 (72) = happyGoto action_21
action_144 (74) = happyGoto action_22
action_144 (75) = happyGoto action_23
action_144 (93) = happyGoto action_24
action_144 (95) = happyGoto action_25
action_144 (97) = happyGoto action_26
action_144 (104) = happyGoto action_27
action_144 (105) = happyGoto action_28
action_144 (106) = happyGoto action_29
action_144 (108) = happyGoto action_30
action_144 (114) = happyGoto action_31
action_144 (125) = happyGoto action_32
action_144 (126) = happyGoto action_33
action_144 _ = happyReduce_9
action_145 _ = happyReduce_4
action_146 _ = happyReduce_280
action_147 _ = happyReduce_279
action_148 (146) = happyShift action_149
action_148 _ = happyFail
action_149 _ = happyReduce_3
action_150 _ = happyReduce_29
action_151 (144) = happyShift action_142
action_151 (7) = happyGoto action_325
action_151 _ = happyReduce_10
action_152 _ = happyReduce_51
action_153 (132) = happyShift action_137
action_153 (133) = happyShift action_118
action_153 (134) = happyShift action_119
action_153 (152) = happyShift action_324
action_153 (153) = happyShift action_125
action_153 (164) = happyShift action_126
action_153 (29) = happyGoto action_318
action_153 (98) = happyGoto action_319
action_153 (100) = happyGoto action_320
action_153 (102) = happyGoto action_321
action_153 (110) = happyGoto action_322
action_153 (112) = happyGoto action_323
action_153 _ = happyFail
action_154 _ = happyReduce_55
action_155 _ = happyReduce_81
action_156 _ = happyReduce_233
action_157 (132) = happyShift action_137
action_157 (133) = happyShift action_118
action_157 (153) = happyShift action_125
action_157 (164) = happyShift action_126
action_157 (112) = happyGoto action_317
action_157 _ = happyFail
action_158 (128) = happyShift action_34
action_158 (130) = happyShift action_36
action_158 (131) = happyShift action_200
action_158 (137) = happyShift action_201
action_158 (142) = happyShift action_202
action_158 (148) = happyShift action_203
action_158 (165) = happyShift action_49
action_158 (173) = happyShift action_55
action_158 (188) = happyShift action_65
action_158 (37) = happyGoto action_191
action_158 (38) = happyGoto action_192
action_158 (39) = happyGoto action_193
action_158 (40) = happyGoto action_194
action_158 (41) = happyGoto action_316
action_158 (105) = happyGoto action_196
action_158 (107) = happyGoto action_197
action_158 (108) = happyGoto action_80
action_158 (121) = happyGoto action_198
action_158 (124) = happyGoto action_199
action_158 _ = happyFail
action_159 (187) = happyShift action_315
action_159 (65) = happyGoto action_314
action_159 _ = happyReduce_153
action_160 (158) = happyShift action_163
action_160 (68) = happyGoto action_313
action_160 _ = happyReduce_155
action_161 _ = happyReduce_157
action_162 (128) = happyShift action_34
action_162 (129) = happyShift action_35
action_162 (130) = happyShift action_36
action_162 (131) = happyShift action_37
action_162 (132) = happyShift action_38
action_162 (137) = happyShift action_39
action_162 (138) = happyShift action_40
action_162 (139) = happyShift action_41
action_162 (140) = happyShift action_42
action_162 (141) = happyShift action_43
action_162 (142) = happyShift action_44
action_162 (148) = happyShift action_45
action_162 (151) = happyShift action_46
action_162 (157) = happyShift action_47
action_162 (162) = happyShift action_48
action_162 (165) = happyShift action_49
action_162 (166) = happyShift action_50
action_162 (171) = happyShift action_54
action_162 (173) = happyShift action_55
action_162 (174) = happyShift action_56
action_162 (181) = happyShift action_62
action_162 (188) = happyShift action_65
action_162 (191) = happyShift action_68
action_162 (192) = happyShift action_69
action_162 (193) = happyShift action_70
action_162 (194) = happyShift action_71
action_162 (69) = happyGoto action_312
action_162 (70) = happyGoto action_89
action_162 (71) = happyGoto action_20
action_162 (72) = happyGoto action_21
action_162 (74) = happyGoto action_22
action_162 (75) = happyGoto action_23
action_162 (93) = happyGoto action_24
action_162 (95) = happyGoto action_90
action_162 (97) = happyGoto action_26
action_162 (104) = happyGoto action_27
action_162 (105) = happyGoto action_28
action_162 (106) = happyGoto action_29
action_162 (108) = happyGoto action_30
action_162 (114) = happyGoto action_31
action_162 (126) = happyGoto action_33
action_162 _ = happyFail
action_163 (128) = happyShift action_34
action_163 (129) = happyShift action_35
action_163 (130) = happyShift action_36
action_163 (131) = happyShift action_37
action_163 (132) = happyShift action_38
action_163 (137) = happyShift action_39
action_163 (138) = happyShift action_40
action_163 (139) = happyShift action_41
action_163 (140) = happyShift action_42
action_163 (141) = happyShift action_43
action_163 (142) = happyShift action_44
action_163 (148) = happyShift action_45
action_163 (151) = happyShift action_46
action_163 (157) = happyShift action_47
action_163 (162) = happyShift action_48
action_163 (165) = happyShift action_49
action_163 (166) = happyShift action_50
action_163 (171) = happyShift action_54
action_163 (173) = happyShift action_55
action_163 (174) = happyShift action_56
action_163 (181) = happyShift action_62
action_163 (188) = happyShift action_65
action_163 (191) = happyShift action_68
action_163 (192) = happyShift action_69
action_163 (193) = happyShift action_70
action_163 (194) = happyShift action_71
action_163 (69) = happyGoto action_311
action_163 (70) = happyGoto action_89
action_163 (71) = happyGoto action_20
action_163 (72) = happyGoto action_21
action_163 (74) = happyGoto action_22
action_163 (75) = happyGoto action_23
action_163 (93) = happyGoto action_24
action_163 (95) = happyGoto action_90
action_163 (97) = happyGoto action_26
action_163 (104) = happyGoto action_27
action_163 (105) = happyGoto action_28
action_163 (106) = happyGoto action_29
action_163 (108) = happyGoto action_30
action_163 (114) = happyGoto action_31
action_163 (126) = happyGoto action_33
action_163 _ = happyFail
action_164 _ = happyReduce_162
action_165 (128) = happyShift action_34
action_165 (129) = happyShift action_35
action_165 (142) = happyShift action_241
action_165 (165) = happyShift action_49
action_165 (173) = happyShift action_55
action_165 (188) = happyShift action_65
action_165 (91) = happyGoto action_308
action_165 (92) = happyGoto action_309
action_165 (95) = happyGoto action_310
action_165 (104) = happyGoto action_27
action_165 (105) = happyGoto action_28
action_165 _ = happyFail
action_166 _ = happyReduce_185
action_167 (145) = happyShift action_131
action_167 _ = happyReduce_173
action_168 (128) = happyShift action_34
action_168 (129) = happyShift action_35
action_168 (130) = happyShift action_36
action_168 (131) = happyShift action_37
action_168 (132) = happyShift action_38
action_168 (137) = happyShift action_39
action_168 (138) = happyShift action_40
action_168 (139) = happyShift action_41
action_168 (140) = happyShift action_42
action_168 (141) = happyShift action_43
action_168 (142) = happyShift action_44
action_168 (148) = happyShift action_45
action_168 (151) = happyShift action_46
action_168 (157) = happyShift action_47
action_168 (162) = happyShift action_48
action_168 (165) = happyShift action_49
action_168 (166) = happyShift action_50
action_168 (171) = happyShift action_54
action_168 (173) = happyShift action_55
action_168 (174) = happyShift action_56
action_168 (181) = happyShift action_62
action_168 (188) = happyShift action_65
action_168 (191) = happyShift action_68
action_168 (192) = happyShift action_69
action_168 (193) = happyShift action_70
action_168 (194) = happyShift action_71
action_168 (69) = happyGoto action_307
action_168 (70) = happyGoto action_89
action_168 (71) = happyGoto action_20
action_168 (72) = happyGoto action_21
action_168 (74) = happyGoto action_22
action_168 (75) = happyGoto action_23
action_168 (93) = happyGoto action_24
action_168 (95) = happyGoto action_90
action_168 (97) = happyGoto action_26
action_168 (104) = happyGoto action_27
action_168 (105) = happyGoto action_28
action_168 (106) = happyGoto action_29
action_168 (108) = happyGoto action_30
action_168 (114) = happyGoto action_31
action_168 (126) = happyGoto action_33
action_168 _ = happyFail
action_169 (143) = happyShift action_306
action_169 (150) = happyShift action_123
action_169 (76) = happyGoto action_305
action_169 _ = happyFail
action_170 (149) = happyShift action_304
action_170 _ = happyFail
action_171 (152) = happyShift action_303
action_171 _ = happyFail
action_172 (152) = happyShift action_302
action_172 _ = happyFail
action_173 _ = happyReduce_236
action_174 _ = happyReduce_240
action_175 (132) = happyShift action_137
action_175 (133) = happyShift action_118
action_175 (134) = happyShift action_119
action_175 (135) = happyShift action_120
action_175 (136) = happyShift action_121
action_175 (143) = happyShift action_301
action_175 (152) = happyShift action_124
action_175 (153) = happyShift action_125
action_175 (164) = happyShift action_126
action_175 (99) = happyGoto action_109
action_175 (101) = happyGoto action_110
action_175 (103) = happyGoto action_133
action_175 (109) = happyGoto action_134
action_175 (110) = happyGoto action_113
action_175 (111) = happyGoto action_135
action_175 (112) = happyGoto action_115
action_175 (113) = happyGoto action_116
action_175 _ = happyFail
action_176 _ = happyReduce_181
action_177 (128) = happyShift action_34
action_177 (129) = happyShift action_35
action_177 (130) = happyShift action_36
action_177 (131) = happyShift action_37
action_177 (132) = happyShift action_38
action_177 (137) = happyShift action_39
action_177 (138) = happyShift action_40
action_177 (139) = happyShift action_41
action_177 (140) = happyShift action_42
action_177 (141) = happyShift action_43
action_177 (142) = happyShift action_44
action_177 (148) = happyShift action_45
action_177 (151) = happyShift action_46
action_177 (157) = happyShift action_47
action_177 (162) = happyShift action_48
action_177 (165) = happyShift action_49
action_177 (166) = happyShift action_50
action_177 (171) = happyShift action_54
action_177 (173) = happyShift action_55
action_177 (174) = happyShift action_56
action_177 (181) = happyShift action_62
action_177 (188) = happyShift action_65
action_177 (191) = happyShift action_68
action_177 (192) = happyShift action_69
action_177 (193) = happyShift action_70
action_177 (194) = happyShift action_71
action_177 (69) = happyGoto action_300
action_177 (70) = happyGoto action_89
action_177 (71) = happyGoto action_20
action_177 (72) = happyGoto action_21
action_177 (74) = happyGoto action_22
action_177 (75) = happyGoto action_23
action_177 (93) = happyGoto action_24
action_177 (95) = happyGoto action_90
action_177 (97) = happyGoto action_26
action_177 (104) = happyGoto action_27
action_177 (105) = happyGoto action_28
action_177 (106) = happyGoto action_29
action_177 (108) = happyGoto action_30
action_177 (114) = happyGoto action_31
action_177 (126) = happyGoto action_33
action_177 _ = happyFail
action_178 _ = happyReduce_228
action_179 _ = happyReduce_188
action_180 (128) = happyShift action_34
action_180 (129) = happyShift action_35
action_180 (130) = happyShift action_36
action_180 (131) = happyShift action_37
action_180 (132) = happyShift action_38
action_180 (137) = happyShift action_39
action_180 (138) = happyShift action_40
action_180 (139) = happyShift action_41
action_180 (140) = happyShift action_42
action_180 (141) = happyShift action_43
action_180 (142) = happyShift action_44
action_180 (143) = happyShift action_299
action_180 (148) = happyShift action_45
action_180 (151) = happyShift action_46
action_180 (157) = happyShift action_47
action_180 (162) = happyShift action_48
action_180 (165) = happyShift action_49
action_180 (166) = happyShift action_50
action_180 (171) = happyShift action_54
action_180 (173) = happyShift action_55
action_180 (174) = happyShift action_56
action_180 (181) = happyShift action_62
action_180 (188) = happyShift action_65
action_180 (191) = happyShift action_68
action_180 (192) = happyShift action_69
action_180 (193) = happyShift action_70
action_180 (194) = happyShift action_71
action_180 (71) = happyGoto action_164
action_180 (72) = happyGoto action_21
action_180 (74) = happyGoto action_22
action_180 (75) = happyGoto action_23
action_180 (93) = happyGoto action_24
action_180 (95) = happyGoto action_90
action_180 (97) = happyGoto action_26
action_180 (104) = happyGoto action_27
action_180 (105) = happyGoto action_28
action_180 (106) = happyGoto action_29
action_180 (108) = happyGoto action_30
action_180 (114) = happyGoto action_31
action_180 (126) = happyGoto action_33
action_180 _ = happyFail
action_181 (115) = happyGoto action_298
action_181 _ = happyReduce_278
action_182 _ = happyReduce_180
action_183 (128) = happyShift action_34
action_183 (129) = happyShift action_35
action_183 (130) = happyShift action_36
action_183 (131) = happyShift action_37
action_183 (132) = happyShift action_38
action_183 (137) = happyShift action_39
action_183 (138) = happyShift action_40
action_183 (139) = happyShift action_41
action_183 (140) = happyShift action_42
action_183 (141) = happyShift action_43
action_183 (142) = happyShift action_44
action_183 (148) = happyShift action_45
action_183 (151) = happyShift action_46
action_183 (157) = happyShift action_47
action_183 (162) = happyShift action_48
action_183 (165) = happyShift action_49
action_183 (166) = happyShift action_50
action_183 (171) = happyShift action_54
action_183 (173) = happyShift action_55
action_183 (174) = happyShift action_56
action_183 (181) = happyShift action_62
action_183 (188) = happyShift action_65
action_183 (191) = happyShift action_68
action_183 (192) = happyShift action_69
action_183 (193) = happyShift action_70
action_183 (194) = happyShift action_71
action_183 (69) = happyGoto action_297
action_183 (70) = happyGoto action_89
action_183 (71) = happyGoto action_20
action_183 (72) = happyGoto action_21
action_183 (74) = happyGoto action_22
action_183 (75) = happyGoto action_23
action_183 (93) = happyGoto action_24
action_183 (95) = happyGoto action_90
action_183 (97) = happyGoto action_26
action_183 (104) = happyGoto action_27
action_183 (105) = happyGoto action_28
action_183 (106) = happyGoto action_29
action_183 (108) = happyGoto action_30
action_183 (114) = happyGoto action_31
action_183 (126) = happyGoto action_33
action_183 _ = happyFail
action_184 (128) = happyShift action_34
action_184 (129) = happyShift action_35
action_184 (130) = happyShift action_36
action_184 (131) = happyShift action_37
action_184 (132) = happyShift action_38
action_184 (137) = happyShift action_39
action_184 (138) = happyShift action_40
action_184 (139) = happyShift action_41
action_184 (140) = happyShift action_42
action_184 (141) = happyShift action_43
action_184 (142) = happyShift action_44
action_184 (148) = happyShift action_45
action_184 (151) = happyShift action_46
action_184 (157) = happyShift action_47
action_184 (162) = happyShift action_48
action_184 (165) = happyShift action_49
action_184 (166) = happyShift action_50
action_184 (171) = happyShift action_54
action_184 (173) = happyShift action_55
action_184 (174) = happyShift action_56
action_184 (181) = happyShift action_62
action_184 (188) = happyShift action_65
action_184 (191) = happyShift action_68
action_184 (192) = happyShift action_69
action_184 (193) = happyShift action_70
action_184 (194) = happyShift action_71
action_184 (69) = happyGoto action_296
action_184 (70) = happyGoto action_89
action_184 (71) = happyGoto action_20
action_184 (72) = happyGoto action_21
action_184 (74) = happyGoto action_22
action_184 (75) = happyGoto action_23
action_184 (93) = happyGoto action_24
action_184 (95) = happyGoto action_90
action_184 (97) = happyGoto action_26
action_184 (104) = happyGoto action_27
action_184 (105) = happyGoto action_28
action_184 (106) = happyGoto action_29
action_184 (108) = happyGoto action_30
action_184 (114) = happyGoto action_31
action_184 (126) = happyGoto action_33
action_184 _ = happyFail
action_185 _ = happyReduce_182
action_186 (128) = happyShift action_34
action_186 (129) = happyShift action_35
action_186 (130) = happyShift action_36
action_186 (131) = happyShift action_37
action_186 (132) = happyShift action_38
action_186 (137) = happyShift action_39
action_186 (138) = happyShift action_40
action_186 (139) = happyShift action_41
action_186 (140) = happyShift action_42
action_186 (141) = happyShift action_43
action_186 (142) = happyShift action_44
action_186 (148) = happyShift action_45
action_186 (151) = happyShift action_46
action_186 (157) = happyShift action_47
action_186 (162) = happyShift action_48
action_186 (165) = happyShift action_49
action_186 (166) = happyShift action_50
action_186 (171) = happyShift action_54
action_186 (173) = happyShift action_55
action_186 (174) = happyShift action_56
action_186 (181) = happyShift action_62
action_186 (188) = happyShift action_65
action_186 (191) = happyShift action_68
action_186 (192) = happyShift action_69
action_186 (193) = happyShift action_70
action_186 (194) = happyShift action_71
action_186 (69) = happyGoto action_295
action_186 (70) = happyGoto action_89
action_186 (71) = happyGoto action_20
action_186 (72) = happyGoto action_21
action_186 (74) = happyGoto action_22
action_186 (75) = happyGoto action_23
action_186 (93) = happyGoto action_24
action_186 (95) = happyGoto action_90
action_186 (97) = happyGoto action_26
action_186 (104) = happyGoto action_27
action_186 (105) = happyGoto action_28
action_186 (106) = happyGoto action_29
action_186 (108) = happyGoto action_30
action_186 (114) = happyGoto action_31
action_186 (126) = happyGoto action_33
action_186 _ = happyFail
action_187 (128) = happyShift action_34
action_187 (129) = happyShift action_35
action_187 (130) = happyShift action_36
action_187 (131) = happyShift action_37
action_187 (132) = happyShift action_38
action_187 (137) = happyShift action_39
action_187 (138) = happyShift action_40
action_187 (139) = happyShift action_41
action_187 (140) = happyShift action_42
action_187 (141) = happyShift action_43
action_187 (142) = happyShift action_44
action_187 (148) = happyShift action_45
action_187 (151) = happyShift action_46
action_187 (157) = happyShift action_47
action_187 (162) = happyShift action_48
action_187 (165) = happyShift action_49
action_187 (166) = happyShift action_50
action_187 (171) = happyShift action_54
action_187 (173) = happyShift action_55
action_187 (174) = happyShift action_56
action_187 (181) = happyShift action_62
action_187 (188) = happyShift action_65
action_187 (191) = happyShift action_68
action_187 (192) = happyShift action_69
action_187 (193) = happyShift action_70
action_187 (194) = happyShift action_71
action_187 (69) = happyGoto action_294
action_187 (70) = happyGoto action_89
action_187 (71) = happyGoto action_20
action_187 (72) = happyGoto action_21
action_187 (74) = happyGoto action_22
action_187 (75) = happyGoto action_23
action_187 (93) = happyGoto action_24
action_187 (95) = happyGoto action_90
action_187 (97) = happyGoto action_26
action_187 (104) = happyGoto action_27
action_187 (105) = happyGoto action_28
action_187 (106) = happyGoto action_29
action_187 (108) = happyGoto action_30
action_187 (114) = happyGoto action_31
action_187 (126) = happyGoto action_33
action_187 _ = happyReduce_194
action_188 (128) = happyShift action_34
action_188 (129) = happyShift action_35
action_188 (130) = happyShift action_36
action_188 (131) = happyShift action_37
action_188 (132) = happyShift action_38
action_188 (137) = happyShift action_39
action_188 (138) = happyShift action_40
action_188 (139) = happyShift action_41
action_188 (140) = happyShift action_42
action_188 (141) = happyShift action_43
action_188 (142) = happyShift action_44
action_188 (148) = happyShift action_45
action_188 (151) = happyShift action_46
action_188 (157) = happyShift action_47
action_188 (162) = happyShift action_48
action_188 (165) = happyShift action_49
action_188 (166) = happyShift action_50
action_188 (171) = happyShift action_54
action_188 (173) = happyShift action_55
action_188 (174) = happyShift action_56
action_188 (181) = happyShift action_216
action_188 (188) = happyShift action_65
action_188 (191) = happyShift action_68
action_188 (192) = happyShift action_69
action_188 (193) = happyShift action_70
action_188 (194) = happyShift action_71
action_188 (69) = happyGoto action_291
action_188 (70) = happyGoto action_212
action_188 (71) = happyGoto action_20
action_188 (72) = happyGoto action_21
action_188 (74) = happyGoto action_22
action_188 (75) = happyGoto action_23
action_188 (80) = happyGoto action_292
action_188 (81) = happyGoto action_293
action_188 (93) = happyGoto action_24
action_188 (95) = happyGoto action_90
action_188 (97) = happyGoto action_26
action_188 (104) = happyGoto action_27
action_188 (105) = happyGoto action_28
action_188 (106) = happyGoto action_29
action_188 (108) = happyGoto action_30
action_188 (114) = happyGoto action_31
action_188 (126) = happyGoto action_33
action_188 _ = happyFail
action_189 (128) = happyShift action_34
action_189 (129) = happyShift action_35
action_189 (130) = happyShift action_36
action_189 (131) = happyShift action_37
action_189 (132) = happyShift action_38
action_189 (137) = happyShift action_39
action_189 (138) = happyShift action_40
action_189 (139) = happyShift action_41
action_189 (140) = happyShift action_42
action_189 (141) = happyShift action_43
action_189 (142) = happyShift action_44
action_189 (148) = happyShift action_45
action_189 (151) = happyShift action_46
action_189 (157) = happyShift action_47
action_189 (162) = happyShift action_48
action_189 (165) = happyShift action_49
action_189 (166) = happyShift action_50
action_189 (171) = happyShift action_54
action_189 (173) = happyShift action_55
action_189 (174) = happyShift action_56
action_189 (181) = happyShift action_62
action_189 (188) = happyShift action_65
action_189 (191) = happyShift action_68
action_189 (192) = happyShift action_69
action_189 (193) = happyShift action_70
action_189 (194) = happyShift action_71
action_189 (69) = happyGoto action_290
action_189 (70) = happyGoto action_89
action_189 (71) = happyGoto action_20
action_189 (72) = happyGoto action_21
action_189 (74) = happyGoto action_22
action_189 (75) = happyGoto action_23
action_189 (93) = happyGoto action_24
action_189 (95) = happyGoto action_90
action_189 (97) = happyGoto action_26
action_189 (104) = happyGoto action_27
action_189 (105) = happyGoto action_28
action_189 (106) = happyGoto action_29
action_189 (108) = happyGoto action_30
action_189 (114) = happyGoto action_31
action_189 (126) = happyGoto action_33
action_189 _ = happyFail
action_190 (145) = happyShift action_289
action_190 (82) = happyGoto action_287
action_190 (118) = happyGoto action_288
action_190 _ = happyReduce_282
action_191 (163) = happyShift action_286
action_191 _ = happyReduce_101
action_192 (128) = happyShift action_34
action_192 (130) = happyShift action_36
action_192 (131) = happyShift action_200
action_192 (137) = happyShift action_201
action_192 (142) = happyShift action_202
action_192 (148) = happyShift action_203
action_192 (160) = happyShift action_285
action_192 (165) = happyShift action_49
action_192 (173) = happyShift action_55
action_192 (188) = happyShift action_65
action_192 (39) = happyGoto action_284
action_192 (40) = happyGoto action_194
action_192 (105) = happyGoto action_196
action_192 (107) = happyGoto action_197
action_192 (108) = happyGoto action_80
action_192 (121) = happyGoto action_198
action_192 (124) = happyGoto action_199
action_192 _ = happyReduce_84
action_193 _ = happyReduce_86
action_194 _ = happyReduce_87
action_195 (187) = happyShift action_283
action_195 (58) = happyGoto action_282
action_195 _ = happyReduce_138
action_196 _ = happyReduce_288
action_197 _ = happyReduce_92
action_198 _ = happyReduce_261
action_199 _ = happyReduce_88
action_200 _ = happyReduce_262
action_201 (153) = happyShift action_281
action_201 _ = happyFail
action_202 (128) = happyShift action_34
action_202 (130) = happyShift action_36
action_202 (131) = happyShift action_200
action_202 (137) = happyShift action_201
action_202 (142) = happyShift action_202
action_202 (143) = happyShift action_279
action_202 (148) = happyShift action_203
action_202 (150) = happyShift action_123
action_202 (160) = happyShift action_280
action_202 (165) = happyShift action_49
action_202 (173) = happyShift action_55
action_202 (188) = happyShift action_65
action_202 (37) = happyGoto action_276
action_202 (38) = happyGoto action_192
action_202 (39) = happyGoto action_193
action_202 (40) = happyGoto action_194
action_202 (42) = happyGoto action_277
action_202 (76) = happyGoto action_278
action_202 (105) = happyGoto action_196
action_202 (107) = happyGoto action_197
action_202 (108) = happyGoto action_80
action_202 (121) = happyGoto action_198
action_202 (124) = happyGoto action_199
action_202 _ = happyFail
action_203 (128) = happyShift action_34
action_203 (130) = happyShift action_36
action_203 (131) = happyShift action_200
action_203 (137) = happyShift action_201
action_203 (142) = happyShift action_202
action_203 (148) = happyShift action_203
action_203 (149) = happyShift action_275
action_203 (165) = happyShift action_49
action_203 (173) = happyShift action_55
action_203 (188) = happyShift action_65
action_203 (37) = happyGoto action_274
action_203 (38) = happyGoto action_192
action_203 (39) = happyGoto action_193
action_203 (40) = happyGoto action_194
action_203 (105) = happyGoto action_196
action_203 (107) = happyGoto action_197
action_203 (108) = happyGoto action_80
action_203 (121) = happyGoto action_198
action_203 (124) = happyGoto action_199
action_203 _ = happyFail
action_204 (163) = happyShift action_273
action_204 _ = happyFail
action_205 (156) = happyShift action_272
action_205 _ = happyFail
action_206 _ = happyReduce_105
action_207 _ = happyReduce_67
action_208 (128) = happyShift action_34
action_208 (130) = happyReduce_261
action_208 (131) = happyReduce_261
action_208 (137) = happyReduce_261
action_208 (142) = happyReduce_261
action_208 (148) = happyReduce_261
action_208 (156) = happyReduce_107
action_208 (160) = happyReduce_261
action_208 (163) = happyReduce_261
action_208 (165) = happyShift action_49
action_208 (173) = happyShift action_55
action_208 (188) = happyShift action_65
action_208 (45) = happyGoto action_231
action_208 (105) = happyGoto action_196
action_208 (124) = happyGoto action_232
action_208 _ = happyReduce_111
action_209 _ = happyReduce_66
action_210 (128) = happyShift action_34
action_210 (129) = happyShift action_35
action_210 (130) = happyShift action_36
action_210 (131) = happyShift action_37
action_210 (132) = happyShift action_38
action_210 (137) = happyShift action_39
action_210 (138) = happyShift action_40
action_210 (139) = happyShift action_41
action_210 (140) = happyShift action_42
action_210 (141) = happyShift action_43
action_210 (142) = happyShift action_44
action_210 (148) = happyShift action_45
action_210 (151) = happyShift action_46
action_210 (157) = happyShift action_47
action_210 (162) = happyShift action_48
action_210 (165) = happyShift action_49
action_210 (166) = happyShift action_50
action_210 (171) = happyShift action_54
action_210 (173) = happyShift action_55
action_210 (174) = happyShift action_56
action_210 (181) = happyShift action_216
action_210 (188) = happyShift action_65
action_210 (191) = happyShift action_68
action_210 (192) = happyShift action_69
action_210 (193) = happyShift action_70
action_210 (194) = happyShift action_71
action_210 (69) = happyGoto action_211
action_210 (70) = happyGoto action_212
action_210 (71) = happyGoto action_20
action_210 (72) = happyGoto action_21
action_210 (74) = happyGoto action_22
action_210 (75) = happyGoto action_23
action_210 (81) = happyGoto action_213
action_210 (89) = happyGoto action_271
action_210 (90) = happyGoto action_215
action_210 (93) = happyGoto action_24
action_210 (95) = happyGoto action_90
action_210 (97) = happyGoto action_26
action_210 (104) = happyGoto action_27
action_210 (105) = happyGoto action_28
action_210 (106) = happyGoto action_29
action_210 (108) = happyGoto action_30
action_210 (114) = happyGoto action_31
action_210 (126) = happyGoto action_33
action_210 _ = happyFail
action_211 (144) = happyReduce_204
action_211 _ = happyReduce_220
action_212 (132) = happyShift action_137
action_212 (133) = happyShift action_118
action_212 (134) = happyShift action_119
action_212 (135) = happyShift action_120
action_212 (136) = happyShift action_121
action_212 (152) = happyShift action_124
action_212 (153) = happyShift action_125
action_212 (155) = happyShift action_181
action_212 (159) = happyShift action_270
action_212 (164) = happyShift action_126
action_212 (99) = happyGoto action_109
action_212 (101) = happyGoto action_110
action_212 (103) = happyGoto action_133
action_212 (109) = happyGoto action_134
action_212 (110) = happyGoto action_113
action_212 (111) = happyGoto action_135
action_212 (112) = happyGoto action_115
action_212 (113) = happyGoto action_116
action_212 _ = happyReduce_160
action_213 _ = happyReduce_222
action_214 (1) = happyShift action_146
action_214 (147) = happyShift action_147
action_214 (116) = happyGoto action_269
action_214 _ = happyFail
action_215 (144) = happyShift action_268
action_215 _ = happyFail
action_216 (145) = happyShift action_85
action_216 (34) = happyGoto action_267
action_216 (118) = happyGoto action_84
action_216 _ = happyReduce_282
action_217 (128) = happyShift action_34
action_217 (129) = happyShift action_35
action_217 (130) = happyShift action_36
action_217 (131) = happyShift action_37
action_217 (132) = happyShift action_38
action_217 (137) = happyShift action_39
action_217 (138) = happyShift action_40
action_217 (139) = happyShift action_41
action_217 (140) = happyShift action_42
action_217 (141) = happyShift action_43
action_217 (142) = happyShift action_44
action_217 (148) = happyShift action_45
action_217 (151) = happyShift action_46
action_217 (157) = happyShift action_47
action_217 (162) = happyShift action_48
action_217 (165) = happyShift action_49
action_217 (166) = happyShift action_50
action_217 (171) = happyShift action_54
action_217 (173) = happyShift action_55
action_217 (174) = happyShift action_56
action_217 (181) = happyShift action_62
action_217 (188) = happyShift action_65
action_217 (191) = happyShift action_68
action_217 (192) = happyShift action_69
action_217 (193) = happyShift action_70
action_217 (194) = happyShift action_71
action_217 (69) = happyGoto action_266
action_217 (70) = happyGoto action_89
action_217 (71) = happyGoto action_20
action_217 (72) = happyGoto action_21
action_217 (74) = happyGoto action_22
action_217 (75) = happyGoto action_23
action_217 (93) = happyGoto action_24
action_217 (95) = happyGoto action_90
action_217 (97) = happyGoto action_26
action_217 (104) = happyGoto action_27
action_217 (105) = happyGoto action_28
action_217 (106) = happyGoto action_29
action_217 (108) = happyGoto action_30
action_217 (114) = happyGoto action_31
action_217 (126) = happyGoto action_33
action_217 _ = happyFail
action_218 (130) = happyShift action_73
action_218 (119) = happyGoto action_265
action_218 _ = happyFail
action_219 _ = happyReduce_32
action_220 (187) = happyShift action_264
action_220 (62) = happyGoto action_263
action_220 _ = happyReduce_148
action_221 (128) = happyShift action_34
action_221 (129) = happyShift action_35
action_221 (130) = happyShift action_36
action_221 (131) = happyShift action_37
action_221 (132) = happyShift action_38
action_221 (137) = happyShift action_39
action_221 (138) = happyShift action_40
action_221 (139) = happyShift action_41
action_221 (140) = happyShift action_42
action_221 (141) = happyShift action_43
action_221 (142) = happyShift action_44
action_221 (144) = happyShift action_226
action_221 (148) = happyShift action_45
action_221 (151) = happyShift action_46
action_221 (157) = happyShift action_47
action_221 (162) = happyShift action_48
action_221 (165) = happyShift action_49
action_221 (166) = happyShift action_50
action_221 (171) = happyShift action_54
action_221 (173) = happyShift action_55
action_221 (174) = happyShift action_56
action_221 (177) = happyShift action_58
action_221 (178) = happyShift action_59
action_221 (179) = happyShift action_60
action_221 (181) = happyShift action_62
action_221 (188) = happyShift action_65
action_221 (190) = happyShift action_67
action_221 (191) = happyShift action_68
action_221 (192) = happyShift action_69
action_221 (193) = happyShift action_70
action_221 (194) = happyShift action_71
action_221 (7) = happyGoto action_222
action_221 (26) = happyGoto action_12
action_221 (28) = happyGoto action_13
action_221 (31) = happyGoto action_262
action_221 (32) = happyGoto action_224
action_221 (33) = happyGoto action_225
action_221 (35) = happyGoto action_16
action_221 (36) = happyGoto action_17
action_221 (64) = happyGoto action_18
action_221 (70) = happyGoto action_19
action_221 (71) = happyGoto action_20
action_221 (72) = happyGoto action_21
action_221 (74) = happyGoto action_22
action_221 (75) = happyGoto action_23
action_221 (93) = happyGoto action_24
action_221 (95) = happyGoto action_25
action_221 (97) = happyGoto action_26
action_221 (104) = happyGoto action_27
action_221 (105) = happyGoto action_28
action_221 (106) = happyGoto action_29
action_221 (108) = happyGoto action_30
action_221 (114) = happyGoto action_31
action_221 (125) = happyGoto action_32
action_221 (126) = happyGoto action_33
action_221 _ = happyReduce_10
action_222 _ = happyReduce_71
action_223 (1) = happyShift action_146
action_223 (147) = happyShift action_147
action_223 (116) = happyGoto action_261
action_223 _ = happyFail
action_224 (144) = happyShift action_260
action_224 (7) = happyGoto action_259
action_224 _ = happyReduce_10
action_225 _ = happyReduce_73
action_226 _ = happyReduce_9
action_227 (128) = happyShift action_34
action_227 (129) = happyShift action_35
action_227 (130) = happyShift action_36
action_227 (131) = happyShift action_37
action_227 (132) = happyShift action_38
action_227 (137) = happyShift action_39
action_227 (138) = happyShift action_40
action_227 (139) = happyShift action_41
action_227 (140) = happyShift action_42
action_227 (141) = happyShift action_43
action_227 (142) = happyShift action_44
action_227 (148) = happyShift action_45
action_227 (151) = happyShift action_46
action_227 (157) = happyShift action_47
action_227 (162) = happyShift action_48
action_227 (165) = happyShift action_49
action_227 (166) = happyShift action_50
action_227 (171) = happyShift action_54
action_227 (173) = happyShift action_55
action_227 (174) = happyShift action_56
action_227 (181) = happyShift action_62
action_227 (188) = happyShift action_65
action_227 (191) = happyShift action_68
action_227 (192) = happyShift action_69
action_227 (193) = happyShift action_70
action_227 (194) = happyShift action_71
action_227 (69) = happyGoto action_258
action_227 (70) = happyGoto action_89
action_227 (71) = happyGoto action_20
action_227 (72) = happyGoto action_21
action_227 (74) = happyGoto action_22
action_227 (75) = happyGoto action_23
action_227 (93) = happyGoto action_24
action_227 (95) = happyGoto action_90
action_227 (97) = happyGoto action_26
action_227 (104) = happyGoto action_27
action_227 (105) = happyGoto action_28
action_227 (106) = happyGoto action_29
action_227 (108) = happyGoto action_30
action_227 (114) = happyGoto action_31
action_227 (126) = happyGoto action_33
action_227 _ = happyFail
action_228 (163) = happyShift action_257
action_228 _ = happyFail
action_229 (156) = happyShift action_256
action_229 _ = happyFail
action_230 (128) = happyShift action_34
action_230 (156) = happyReduce_107
action_230 (165) = happyShift action_49
action_230 (173) = happyShift action_55
action_230 (188) = happyShift action_65
action_230 (45) = happyGoto action_231
action_230 (105) = happyGoto action_196
action_230 (124) = happyGoto action_232
action_230 _ = happyReduce_261
action_231 (128) = happyShift action_34
action_231 (165) = happyShift action_49
action_231 (173) = happyShift action_55
action_231 (188) = happyShift action_65
action_231 (105) = happyGoto action_196
action_231 (124) = happyGoto action_255
action_231 _ = happyReduce_106
action_232 _ = happyReduce_109
action_233 (156) = happyShift action_254
action_233 _ = happyFail
action_234 (155) = happyShift action_253
action_234 _ = happyFail
action_235 (128) = happyShift action_34
action_235 (165) = happyShift action_49
action_235 (173) = happyShift action_55
action_235 (188) = happyShift action_65
action_235 (105) = happyGoto action_251
action_235 (127) = happyGoto action_252
action_235 _ = happyReduce_295
action_236 (150) = happyShift action_250
action_236 (10) = happyGoto action_249
action_236 _ = happyReduce_16
action_237 _ = happyReduce_18
action_238 _ = happyReduce_19
action_239 _ = happyReduce_286
action_240 (142) = happyShift action_248
action_240 _ = happyReduce_20
action_241 (132) = happyShift action_137
action_241 (133) = happyShift action_118
action_241 (135) = happyShift action_120
action_241 (153) = happyShift action_125
action_241 (164) = happyShift action_126
action_241 (111) = happyGoto action_247
action_241 (112) = happyGoto action_115
action_241 (113) = happyGoto action_116
action_241 _ = happyFail
action_242 _ = happyReduce_14
action_243 (130) = happyShift action_73
action_243 (119) = happyGoto action_246
action_243 _ = happyFail
action_244 (145) = happyShift action_6
action_244 (5) = happyGoto action_245
action_244 (118) = happyGoto action_5
action_244 _ = happyReduce_282
action_245 _ = happyReduce_1
action_246 _ = happyReduce_24
action_247 (143) = happyShift action_173
action_247 _ = happyFail
action_248 (128) = happyShift action_34
action_248 (129) = happyShift action_35
action_248 (130) = happyShift action_36
action_248 (131) = happyShift action_37
action_248 (142) = happyShift action_383
action_248 (143) = happyShift action_384
action_248 (154) = happyShift action_385
action_248 (165) = happyShift action_49
action_248 (173) = happyShift action_55
action_248 (188) = happyShift action_65
action_248 (13) = happyGoto action_379
action_248 (14) = happyGoto action_380
action_248 (95) = happyGoto action_381
action_248 (97) = happyGoto action_382
action_248 (104) = happyGoto action_27
action_248 (105) = happyGoto action_28
action_248 (106) = happyGoto action_29
action_248 (108) = happyGoto action_30
action_248 _ = happyFail
action_249 (143) = happyShift action_378
action_249 _ = happyFail
action_250 (128) = happyShift action_34
action_250 (129) = happyShift action_35
action_250 (130) = happyShift action_36
action_250 (131) = happyShift action_200
action_250 (142) = happyShift action_241
action_250 (165) = happyShift action_49
action_250 (173) = happyShift action_55
action_250 (182) = happyShift action_243
action_250 (188) = happyShift action_65
action_250 (12) = happyGoto action_377
action_250 (95) = happyGoto action_238
action_250 (104) = happyGoto action_27
action_250 (105) = happyGoto action_28
action_250 (107) = happyGoto action_239
action_250 (108) = happyGoto action_80
action_250 (121) = happyGoto action_198
action_250 (122) = happyGoto action_240
action_250 _ = happyReduce_15
action_251 (128) = happyShift action_34
action_251 (165) = happyShift action_49
action_251 (173) = happyShift action_55
action_251 (188) = happyShift action_65
action_251 (105) = happyGoto action_251
action_251 (127) = happyGoto action_376
action_251 _ = happyReduce_295
action_252 (156) = happyShift action_375
action_252 _ = happyFail
action_253 (128) = happyShift action_34
action_253 (130) = happyShift action_36
action_253 (131) = happyShift action_200
action_253 (137) = happyShift action_201
action_253 (142) = happyShift action_202
action_253 (148) = happyShift action_203
action_253 (165) = happyShift action_49
action_253 (173) = happyShift action_55
action_253 (188) = happyShift action_65
action_253 (37) = happyGoto action_374
action_253 (38) = happyGoto action_192
action_253 (39) = happyGoto action_193
action_253 (40) = happyGoto action_194
action_253 (105) = happyGoto action_196
action_253 (107) = happyGoto action_197
action_253 (108) = happyGoto action_80
action_253 (121) = happyGoto action_198
action_253 (124) = happyGoto action_199
action_253 _ = happyFail
action_254 (128) = happyShift action_34
action_254 (130) = happyShift action_36
action_254 (131) = happyShift action_200
action_254 (137) = happyShift action_201
action_254 (142) = happyShift action_202
action_254 (148) = happyShift action_203
action_254 (165) = happyShift action_49
action_254 (173) = happyShift action_55
action_254 (188) = happyShift action_65
action_254 (37) = happyGoto action_373
action_254 (38) = happyGoto action_192
action_254 (39) = happyGoto action_193
action_254 (40) = happyGoto action_194
action_254 (105) = happyGoto action_196
action_254 (107) = happyGoto action_197
action_254 (108) = happyGoto action_80
action_254 (121) = happyGoto action_198
action_254 (124) = happyGoto action_199
action_254 _ = happyFail
action_255 _ = happyReduce_108
action_256 (48) = happyGoto action_372
action_256 (115) = happyGoto action_360
action_256 _ = happyReduce_278
action_257 (130) = happyShift action_36
action_257 (44) = happyGoto action_356
action_257 (108) = happyGoto action_80
action_257 (121) = happyGoto action_81
action_257 _ = happyFail
action_258 _ = happyReduce_165
action_259 _ = happyReduce_70
action_260 (128) = happyShift action_34
action_260 (129) = happyShift action_35
action_260 (130) = happyShift action_36
action_260 (131) = happyShift action_37
action_260 (132) = happyShift action_38
action_260 (137) = happyShift action_39
action_260 (138) = happyShift action_40
action_260 (139) = happyShift action_41
action_260 (140) = happyShift action_42
action_260 (141) = happyShift action_43
action_260 (142) = happyShift action_44
action_260 (148) = happyShift action_45
action_260 (151) = happyShift action_46
action_260 (157) = happyShift action_47
action_260 (162) = happyShift action_48
action_260 (165) = happyShift action_49
action_260 (166) = happyShift action_50
action_260 (171) = happyShift action_54
action_260 (173) = happyShift action_55
action_260 (174) = happyShift action_56
action_260 (177) = happyShift action_58
action_260 (178) = happyShift action_59
action_260 (179) = happyShift action_60
action_260 (181) = happyShift action_62
action_260 (188) = happyShift action_65
action_260 (190) = happyShift action_67
action_260 (191) = happyShift action_68
action_260 (192) = happyShift action_69
action_260 (193) = happyShift action_70
action_260 (194) = happyShift action_71
action_260 (26) = happyGoto action_12
action_260 (28) = happyGoto action_13
action_260 (33) = happyGoto action_371
action_260 (35) = happyGoto action_16
action_260 (36) = happyGoto action_17
action_260 (64) = happyGoto action_18
action_260 (70) = happyGoto action_19
action_260 (71) = happyGoto action_20
action_260 (72) = happyGoto action_21
action_260 (74) = happyGoto action_22
action_260 (75) = happyGoto action_23
action_260 (93) = happyGoto action_24
action_260 (95) = happyGoto action_25
action_260 (97) = happyGoto action_26
action_260 (104) = happyGoto action_27
action_260 (105) = happyGoto action_28
action_260 (106) = happyGoto action_29
action_260 (108) = happyGoto action_30
action_260 (114) = happyGoto action_31
action_260 (125) = happyGoto action_32
action_260 (126) = happyGoto action_33
action_260 _ = happyReduce_9
action_261 _ = happyReduce_79
action_262 (146) = happyShift action_370
action_262 _ = happyFail
action_263 _ = happyReduce_65
action_264 (145) = happyShift action_369
action_264 (118) = happyGoto action_368
action_264 _ = happyReduce_282
action_265 (165) = happyShift action_367
action_265 (18) = happyGoto action_366
action_265 _ = happyReduce_35
action_266 (172) = happyShift action_365
action_266 _ = happyFail
action_267 (176) = happyShift action_227
action_267 _ = happyReduce_205
action_268 (128) = happyShift action_34
action_268 (129) = happyShift action_35
action_268 (130) = happyShift action_36
action_268 (131) = happyShift action_37
action_268 (132) = happyShift action_38
action_268 (137) = happyShift action_39
action_268 (138) = happyShift action_40
action_268 (139) = happyShift action_41
action_268 (140) = happyShift action_42
action_268 (141) = happyShift action_43
action_268 (142) = happyShift action_44
action_268 (148) = happyShift action_45
action_268 (151) = happyShift action_46
action_268 (157) = happyShift action_47
action_268 (162) = happyShift action_48
action_268 (165) = happyShift action_49
action_268 (166) = happyShift action_50
action_268 (171) = happyShift action_54
action_268 (173) = happyShift action_55
action_268 (174) = happyShift action_56
action_268 (181) = happyShift action_216
action_268 (188) = happyShift action_65
action_268 (191) = happyShift action_68
action_268 (192) = happyShift action_69
action_268 (193) = happyShift action_70
action_268 (194) = happyShift action_71
action_268 (69) = happyGoto action_363
action_268 (70) = happyGoto action_212
action_268 (71) = happyGoto action_20
action_268 (72) = happyGoto action_21
action_268 (74) = happyGoto action_22
action_268 (75) = happyGoto action_23
action_268 (81) = happyGoto action_364
action_268 (93) = happyGoto action_24
action_268 (95) = happyGoto action_90
action_268 (97) = happyGoto action_26
action_268 (104) = happyGoto action_27
action_268 (105) = happyGoto action_28
action_268 (106) = happyGoto action_29
action_268 (108) = happyGoto action_30
action_268 (114) = happyGoto action_31
action_268 (126) = happyGoto action_33
action_268 _ = happyFail
action_269 _ = happyReduce_218
action_270 (128) = happyShift action_34
action_270 (129) = happyShift action_35
action_270 (130) = happyShift action_36
action_270 (131) = happyShift action_37
action_270 (132) = happyShift action_38
action_270 (137) = happyShift action_39
action_270 (138) = happyShift action_40
action_270 (139) = happyShift action_41
action_270 (140) = happyShift action_42
action_270 (141) = happyShift action_43
action_270 (142) = happyShift action_44
action_270 (148) = happyShift action_45
action_270 (151) = happyShift action_46
action_270 (157) = happyShift action_47
action_270 (162) = happyShift action_48
action_270 (165) = happyShift action_49
action_270 (166) = happyShift action_50
action_270 (171) = happyShift action_54
action_270 (173) = happyShift action_55
action_270 (174) = happyShift action_56
action_270 (181) = happyShift action_62
action_270 (188) = happyShift action_65
action_270 (191) = happyShift action_68
action_270 (192) = happyShift action_69
action_270 (193) = happyShift action_70
action_270 (194) = happyShift action_71
action_270 (69) = happyGoto action_362
action_270 (70) = happyGoto action_89
action_270 (71) = happyGoto action_20
action_270 (72) = happyGoto action_21
action_270 (74) = happyGoto action_22
action_270 (75) = happyGoto action_23
action_270 (93) = happyGoto action_24
action_270 (95) = happyGoto action_90
action_270 (97) = happyGoto action_26
action_270 (104) = happyGoto action_27
action_270 (105) = happyGoto action_28
action_270 (106) = happyGoto action_29
action_270 (108) = happyGoto action_30
action_270 (114) = happyGoto action_31
action_270 (126) = happyGoto action_33
action_270 _ = happyFail
action_271 (146) = happyShift action_361
action_271 _ = happyFail
action_272 (47) = happyGoto action_358
action_272 (48) = happyGoto action_359
action_272 (115) = happyGoto action_360
action_272 _ = happyReduce_278
action_273 (130) = happyShift action_36
action_273 (44) = happyGoto action_356
action_273 (108) = happyGoto action_80
action_273 (121) = happyGoto action_357
action_273 _ = happyFail
action_274 (149) = happyShift action_355
action_274 _ = happyFail
action_275 _ = happyReduce_94
action_276 (143) = happyShift action_353
action_276 (150) = happyShift action_354
action_276 _ = happyFail
action_277 (143) = happyShift action_351
action_277 (150) = happyShift action_352
action_277 _ = happyFail
action_278 (143) = happyShift action_350
action_278 (150) = happyShift action_179
action_278 _ = happyFail
action_279 _ = happyReduce_93
action_280 (143) = happyShift action_349
action_280 _ = happyFail
action_281 (142) = happyShift action_347
action_281 (148) = happyShift action_348
action_281 _ = happyFail
action_282 _ = happyReduce_64
action_283 (145) = happyShift action_346
action_283 (118) = happyGoto action_345
action_283 _ = happyReduce_282
action_284 _ = happyReduce_85
action_285 (128) = happyShift action_34
action_285 (130) = happyShift action_36
action_285 (131) = happyShift action_200
action_285 (137) = happyShift action_201
action_285 (142) = happyShift action_202
action_285 (148) = happyShift action_203
action_285 (165) = happyShift action_49
action_285 (173) = happyShift action_55
action_285 (188) = happyShift action_65
action_285 (37) = happyGoto action_344
action_285 (38) = happyGoto action_192
action_285 (39) = happyGoto action_193
action_285 (40) = happyGoto action_194
action_285 (105) = happyGoto action_196
action_285 (107) = happyGoto action_197
action_285 (108) = happyGoto action_80
action_285 (121) = happyGoto action_198
action_285 (124) = happyGoto action_199
action_285 _ = happyFail
action_286 (128) = happyShift action_34
action_286 (130) = happyShift action_36
action_286 (131) = happyShift action_200
action_286 (137) = happyShift action_201
action_286 (142) = happyShift action_202
action_286 (148) = happyShift action_203
action_286 (165) = happyShift action_49
action_286 (173) = happyShift action_55
action_286 (188) = happyShift action_65
action_286 (37) = happyGoto action_343
action_286 (38) = happyGoto action_192
action_286 (39) = happyGoto action_193
action_286 (40) = happyGoto action_194
action_286 (105) = happyGoto action_196
action_286 (107) = happyGoto action_197
action_286 (108) = happyGoto action_80
action_286 (121) = happyGoto action_198
action_286 (124) = happyGoto action_199
action_286 _ = happyFail
action_287 _ = happyReduce_167
action_288 (128) = happyShift action_34
action_288 (129) = happyShift action_35
action_288 (130) = happyShift action_36
action_288 (131) = happyShift action_37
action_288 (132) = happyShift action_38
action_288 (137) = happyShift action_39
action_288 (138) = happyShift action_40
action_288 (139) = happyShift action_41
action_288 (140) = happyShift action_42
action_288 (141) = happyShift action_43
action_288 (142) = happyShift action_44
action_288 (148) = happyShift action_45
action_288 (151) = happyShift action_46
action_288 (157) = happyShift action_47
action_288 (162) = happyShift action_48
action_288 (165) = happyShift action_49
action_288 (166) = happyShift action_50
action_288 (171) = happyShift action_54
action_288 (173) = happyShift action_55
action_288 (174) = happyShift action_56
action_288 (181) = happyShift action_62
action_288 (188) = happyShift action_65
action_288 (191) = happyShift action_68
action_288 (192) = happyShift action_69
action_288 (193) = happyShift action_70
action_288 (194) = happyShift action_71
action_288 (70) = happyGoto action_340
action_288 (71) = happyGoto action_20
action_288 (72) = happyGoto action_21
action_288 (74) = happyGoto action_22
action_288 (75) = happyGoto action_23
action_288 (83) = happyGoto action_341
action_288 (84) = happyGoto action_342
action_288 (93) = happyGoto action_24
action_288 (95) = happyGoto action_90
action_288 (97) = happyGoto action_26
action_288 (104) = happyGoto action_27
action_288 (105) = happyGoto action_28
action_288 (106) = happyGoto action_29
action_288 (108) = happyGoto action_30
action_288 (114) = happyGoto action_31
action_288 (126) = happyGoto action_33
action_288 _ = happyFail
action_289 (117) = happyGoto action_339
action_289 _ = happyReduce_281
action_290 _ = happyReduce_163
action_291 _ = happyReduce_204
action_292 (150) = happyShift action_338
action_292 _ = happyReduce_198
action_293 _ = happyReduce_202
action_294 _ = happyReduce_196
action_295 (154) = happyShift action_337
action_295 _ = happyReduce_200
action_296 _ = happyReduce_199
action_297 _ = happyReduce_191
action_298 (128) = happyShift action_34
action_298 (130) = happyShift action_36
action_298 (131) = happyShift action_200
action_298 (137) = happyShift action_201
action_298 (142) = happyShift action_202
action_298 (148) = happyShift action_203
action_298 (165) = happyShift action_49
action_298 (173) = happyShift action_55
action_298 (188) = happyShift action_65
action_298 (37) = happyGoto action_191
action_298 (38) = happyGoto action_192
action_298 (39) = happyGoto action_193
action_298 (40) = happyGoto action_194
action_298 (41) = happyGoto action_336
action_298 (105) = happyGoto action_196
action_298 (107) = happyGoto action_197
action_298 (108) = happyGoto action_80
action_298 (121) = happyGoto action_198
action_298 (124) = happyGoto action_199
action_298 _ = happyFail
action_299 _ = happyReduce_183
action_300 _ = happyReduce_190
action_301 _ = happyReduce_184
action_302 _ = happyReduce_248
action_303 _ = happyReduce_244
action_304 _ = happyReduce_230
action_305 (143) = happyShift action_335
action_305 (150) = happyShift action_179
action_305 _ = happyFail
action_306 _ = happyReduce_229
action_307 _ = happyReduce_164
action_308 (146) = happyShift action_333
action_308 (150) = happyShift action_334
action_308 _ = happyFail
action_309 _ = happyReduce_224
action_310 (156) = happyShift action_332
action_310 _ = happyFail
action_311 (115) = happyGoto action_331
action_311 _ = happyReduce_278
action_312 _ = happyReduce_154
action_313 _ = happyReduce_156
action_314 _ = happyReduce_151
action_315 (145) = happyShift action_85
action_315 (34) = happyGoto action_330
action_315 (118) = happyGoto action_84
action_315 _ = happyReduce_282
action_316 _ = happyReduce_80
action_317 (143) = happyShift action_329
action_317 _ = happyFail
action_318 _ = happyReduce_53
action_319 _ = happyReduce_249
action_320 _ = happyReduce_250
action_321 (150) = happyShift action_328
action_321 _ = happyReduce_60
action_322 _ = happyReduce_245
action_323 _ = happyReduce_241
action_324 (128) = happyShift action_34
action_324 (130) = happyShift action_36
action_324 (165) = happyShift action_49
action_324 (173) = happyShift action_55
action_324 (188) = happyShift action_65
action_324 (105) = happyGoto action_326
action_324 (108) = happyGoto action_327
action_324 _ = happyFail
action_325 _ = happyReduce_5
action_326 (152) = happyShift action_436
action_326 _ = happyFail
action_327 (152) = happyShift action_435
action_327 _ = happyFail
action_328 (132) = happyShift action_137
action_328 (133) = happyShift action_118
action_328 (134) = happyShift action_119
action_328 (152) = happyShift action_324
action_328 (153) = happyShift action_125
action_328 (164) = happyShift action_126
action_328 (29) = happyGoto action_434
action_328 (98) = happyGoto action_319
action_328 (100) = happyGoto action_320
action_328 (102) = happyGoto action_321
action_328 (110) = happyGoto action_322
action_328 (112) = happyGoto action_323
action_328 _ = happyFail
action_329 _ = happyReduce_234
action_330 _ = happyReduce_152
action_331 (156) = happyShift action_433
action_331 _ = happyFail
action_332 (128) = happyShift action_34
action_332 (129) = happyShift action_35
action_332 (130) = happyShift action_36
action_332 (131) = happyShift action_37
action_332 (132) = happyShift action_38
action_332 (137) = happyShift action_39
action_332 (138) = happyShift action_40
action_332 (139) = happyShift action_41
action_332 (140) = happyShift action_42
action_332 (141) = happyShift action_43
action_332 (142) = happyShift action_44
action_332 (148) = happyShift action_45
action_332 (151) = happyShift action_46
action_332 (157) = happyShift action_47
action_332 (162) = happyShift action_48
action_332 (165) = happyShift action_49
action_332 (166) = happyShift action_50
action_332 (171) = happyShift action_54
action_332 (173) = happyShift action_55
action_332 (174) = happyShift action_56
action_332 (181) = happyShift action_62
action_332 (188) = happyShift action_65
action_332 (191) = happyShift action_68
action_332 (192) = happyShift action_69
action_332 (193) = happyShift action_70
action_332 (194) = happyShift action_71
action_332 (69) = happyGoto action_432
action_332 (70) = happyGoto action_89
action_332 (71) = happyGoto action_20
action_332 (72) = happyGoto action_21
action_332 (74) = happyGoto action_22
action_332 (75) = happyGoto action_23
action_332 (93) = happyGoto action_24
action_332 (95) = happyGoto action_90
action_332 (97) = happyGoto action_26
action_332 (104) = happyGoto action_27
action_332 (105) = happyGoto action_28
action_332 (106) = happyGoto action_29
action_332 (108) = happyGoto action_30
action_332 (114) = happyGoto action_31
action_332 (126) = happyGoto action_33
action_332 _ = happyFail
action_333 _ = happyReduce_175
action_334 (128) = happyShift action_34
action_334 (129) = happyShift action_35
action_334 (142) = happyShift action_241
action_334 (165) = happyShift action_49
action_334 (173) = happyShift action_55
action_334 (188) = happyShift action_65
action_334 (92) = happyGoto action_431
action_334 (95) = happyGoto action_310
action_334 (104) = happyGoto action_27
action_334 (105) = happyGoto action_28
action_334 _ = happyFail
action_335 _ = happyReduce_231
action_336 _ = happyReduce_159
action_337 (128) = happyShift action_34
action_337 (129) = happyShift action_35
action_337 (130) = happyShift action_36
action_337 (131) = happyShift action_37
action_337 (132) = happyShift action_38
action_337 (137) = happyShift action_39
action_337 (138) = happyShift action_40
action_337 (139) = happyShift action_41
action_337 (140) = happyShift action_42
action_337 (141) = happyShift action_43
action_337 (142) = happyShift action_44
action_337 (148) = happyShift action_45
action_337 (151) = happyShift action_46
action_337 (157) = happyShift action_47
action_337 (162) = happyShift action_48
action_337 (165) = happyShift action_49
action_337 (166) = happyShift action_50
action_337 (171) = happyShift action_54
action_337 (173) = happyShift action_55
action_337 (174) = happyShift action_56
action_337 (181) = happyShift action_62
action_337 (188) = happyShift action_65
action_337 (191) = happyShift action_68
action_337 (192) = happyShift action_69
action_337 (193) = happyShift action_70
action_337 (194) = happyShift action_71
action_337 (69) = happyGoto action_430
action_337 (70) = happyGoto action_89
action_337 (71) = happyGoto action_20
action_337 (72) = happyGoto action_21
action_337 (74) = happyGoto action_22
action_337 (75) = happyGoto action_23
action_337 (93) = happyGoto action_24
action_337 (95) = happyGoto action_90
action_337 (97) = happyGoto action_26
action_337 (104) = happyGoto action_27
action_337 (105) = happyGoto action_28
action_337 (106) = happyGoto action_29
action_337 (108) = happyGoto action_30
action_337 (114) = happyGoto action_31
action_337 (126) = happyGoto action_33
action_337 _ = happyReduce_195
action_338 (128) = happyShift action_34
action_338 (129) = happyShift action_35
action_338 (130) = happyShift action_36
action_338 (131) = happyShift action_37
action_338 (132) = happyShift action_38
action_338 (137) = happyShift action_39
action_338 (138) = happyShift action_40
action_338 (139) = happyShift action_41
action_338 (140) = happyShift action_42
action_338 (141) = happyShift action_43
action_338 (142) = happyShift action_44
action_338 (148) = happyShift action_45
action_338 (151) = happyShift action_46
action_338 (157) = happyShift action_47
action_338 (162) = happyShift action_48
action_338 (165) = happyShift action_49
action_338 (166) = happyShift action_50
action_338 (171) = happyShift action_54
action_338 (173) = happyShift action_55
action_338 (174) = happyShift action_56
action_338 (181) = happyShift action_216
action_338 (188) = happyShift action_65
action_338 (191) = happyShift action_68
action_338 (192) = happyShift action_69
action_338 (193) = happyShift action_70
action_338 (194) = happyShift action_71
action_338 (69) = happyGoto action_291
action_338 (70) = happyGoto action_212
action_338 (71) = happyGoto action_20
action_338 (72) = happyGoto action_21
action_338 (74) = happyGoto action_22
action_338 (75) = happyGoto action_23
action_338 (81) = happyGoto action_429
action_338 (93) = happyGoto action_24
action_338 (95) = happyGoto action_90
action_338 (97) = happyGoto action_26
action_338 (104) = happyGoto action_27
action_338 (105) = happyGoto action_28
action_338 (106) = happyGoto action_29
action_338 (108) = happyGoto action_30
action_338 (114) = happyGoto action_31
action_338 (126) = happyGoto action_33
action_338 _ = happyFail
action_339 (128) = happyShift action_34
action_339 (129) = happyShift action_35
action_339 (130) = happyShift action_36
action_339 (131) = happyShift action_37
action_339 (132) = happyShift action_38
action_339 (137) = happyShift action_39
action_339 (138) = happyShift action_40
action_339 (139) = happyShift action_41
action_339 (140) = happyShift action_42
action_339 (141) = happyShift action_43
action_339 (142) = happyShift action_44
action_339 (148) = happyShift action_45
action_339 (151) = happyShift action_46
action_339 (157) = happyShift action_47
action_339 (162) = happyShift action_48
action_339 (165) = happyShift action_49
action_339 (166) = happyShift action_50
action_339 (171) = happyShift action_54
action_339 (173) = happyShift action_55
action_339 (174) = happyShift action_56
action_339 (181) = happyShift action_62
action_339 (188) = happyShift action_65
action_339 (191) = happyShift action_68
action_339 (192) = happyShift action_69
action_339 (193) = happyShift action_70
action_339 (194) = happyShift action_71
action_339 (70) = happyGoto action_340
action_339 (71) = happyGoto action_20
action_339 (72) = happyGoto action_21
action_339 (74) = happyGoto action_22
action_339 (75) = happyGoto action_23
action_339 (83) = happyGoto action_428
action_339 (84) = happyGoto action_342
action_339 (93) = happyGoto action_24
action_339 (95) = happyGoto action_90
action_339 (97) = happyGoto action_26
action_339 (104) = happyGoto action_27
action_339 (105) = happyGoto action_28
action_339 (106) = happyGoto action_29
action_339 (108) = happyGoto action_30
action_339 (114) = happyGoto action_31
action_339 (126) = happyGoto action_33
action_339 _ = happyFail
action_340 (132) = happyShift action_137
action_340 (133) = happyShift action_118
action_340 (134) = happyShift action_119
action_340 (135) = happyShift action_120
action_340 (136) = happyShift action_121
action_340 (152) = happyShift action_124
action_340 (153) = happyShift action_125
action_340 (164) = happyShift action_126
action_340 (99) = happyGoto action_109
action_340 (101) = happyGoto action_110
action_340 (103) = happyGoto action_133
action_340 (109) = happyGoto action_134
action_340 (110) = happyGoto action_113
action_340 (111) = happyGoto action_135
action_340 (112) = happyGoto action_115
action_340 (113) = happyGoto action_116
action_340 (115) = happyGoto action_427
action_340 _ = happyReduce_278
action_341 (144) = happyShift action_426
action_341 (7) = happyGoto action_425
action_341 _ = happyReduce_10
action_342 _ = happyReduce_209
action_343 _ = happyReduce_100
action_344 _ = happyReduce_83
action_345 (128) = happyShift action_34
action_345 (129) = happyShift action_35
action_345 (142) = happyShift action_241
action_345 (144) = happyShift action_226
action_345 (165) = happyShift action_49
action_345 (173) = happyShift action_55
action_345 (188) = happyShift action_65
action_345 (7) = happyGoto action_420
action_345 (35) = happyGoto action_421
action_345 (36) = happyGoto action_17
action_345 (59) = happyGoto action_422
action_345 (60) = happyGoto action_423
action_345 (95) = happyGoto action_424
action_345 (104) = happyGoto action_27
action_345 (105) = happyGoto action_28
action_345 _ = happyReduce_10
action_346 (117) = happyGoto action_419
action_346 _ = happyReduce_281
action_347 (143) = happyShift action_418
action_347 (150) = happyShift action_123
action_347 (76) = happyGoto action_417
action_347 _ = happyFail
action_348 (149) = happyShift action_416
action_348 _ = happyFail
action_349 _ = happyReduce_95
action_350 _ = happyReduce_96
action_351 _ = happyReduce_89
action_352 (128) = happyShift action_34
action_352 (130) = happyShift action_36
action_352 (131) = happyShift action_200
action_352 (137) = happyShift action_201
action_352 (142) = happyShift action_202
action_352 (148) = happyShift action_203
action_352 (165) = happyShift action_49
action_352 (173) = happyShift action_55
action_352 (188) = happyShift action_65
action_352 (37) = happyGoto action_415
action_352 (38) = happyGoto action_192
action_352 (39) = happyGoto action_193
action_352 (40) = happyGoto action_194
action_352 (105) = happyGoto action_196
action_352 (107) = happyGoto action_197
action_352 (108) = happyGoto action_80
action_352 (121) = happyGoto action_198
action_352 (124) = happyGoto action_199
action_352 _ = happyFail
action_353 _ = happyReduce_91
action_354 (128) = happyShift action_34
action_354 (130) = happyShift action_36
action_354 (131) = happyShift action_200
action_354 (137) = happyShift action_201
action_354 (142) = happyShift action_202
action_354 (148) = happyShift action_203
action_354 (165) = happyShift action_49
action_354 (173) = happyShift action_55
action_354 (188) = happyShift action_65
action_354 (37) = happyGoto action_414
action_354 (38) = happyGoto action_192
action_354 (39) = happyGoto action_193
action_354 (40) = happyGoto action_194
action_354 (105) = happyGoto action_196
action_354 (107) = happyGoto action_197
action_354 (108) = happyGoto action_80
action_354 (121) = happyGoto action_198
action_354 (124) = happyGoto action_199
action_354 _ = happyFail
action_355 _ = happyReduce_90
action_356 _ = happyReduce_104
action_357 (128) = happyShift action_34
action_357 (156) = happyReduce_107
action_357 (165) = happyShift action_49
action_357 (173) = happyShift action_55
action_357 (188) = happyShift action_65
action_357 (45) = happyGoto action_231
action_357 (105) = happyGoto action_196
action_357 (124) = happyGoto action_232
action_357 _ = happyReduce_110
action_358 (158) = happyShift action_413
action_358 (170) = happyShift action_392
action_358 (56) = happyGoto action_412
action_358 _ = happyReduce_130
action_359 _ = happyReduce_113
action_360 (128) = happyShift action_34
action_360 (130) = happyShift action_36
action_360 (131) = happyShift action_200
action_360 (137) = happyShift action_201
action_360 (142) = happyShift action_410
action_360 (148) = happyShift action_203
action_360 (164) = happyShift action_411
action_360 (165) = happyShift action_49
action_360 (173) = happyShift action_55
action_360 (188) = happyShift action_65
action_360 (38) = happyGoto action_404
action_360 (39) = happyGoto action_193
action_360 (40) = happyGoto action_194
action_360 (49) = happyGoto action_405
action_360 (50) = happyGoto action_406
action_360 (52) = happyGoto action_407
action_360 (96) = happyGoto action_408
action_360 (105) = happyGoto action_196
action_360 (107) = happyGoto action_197
action_360 (108) = happyGoto action_409
action_360 (121) = happyGoto action_198
action_360 (124) = happyGoto action_199
action_360 _ = happyFail
action_361 _ = happyReduce_217
action_362 _ = happyReduce_203
action_363 (144) = happyReduce_204
action_363 _ = happyReduce_219
action_364 _ = happyReduce_221
action_365 (128) = happyShift action_34
action_365 (129) = happyShift action_35
action_365 (130) = happyShift action_36
action_365 (131) = happyShift action_37
action_365 (132) = happyShift action_38
action_365 (137) = happyShift action_39
action_365 (138) = happyShift action_40
action_365 (139) = happyShift action_41
action_365 (140) = happyShift action_42
action_365 (141) = happyShift action_43
action_365 (142) = happyShift action_44
action_365 (148) = happyShift action_45
action_365 (151) = happyShift action_46
action_365 (157) = happyShift action_47
action_365 (162) = happyShift action_48
action_365 (165) = happyShift action_49
action_365 (166) = happyShift action_50
action_365 (171) = happyShift action_54
action_365 (173) = happyShift action_55
action_365 (174) = happyShift action_56
action_365 (181) = happyShift action_62
action_365 (188) = happyShift action_65
action_365 (191) = happyShift action_68
action_365 (192) = happyShift action_69
action_365 (193) = happyShift action_70
action_365 (194) = happyShift action_71
action_365 (69) = happyGoto action_403
action_365 (70) = happyGoto action_89
action_365 (71) = happyGoto action_20
action_365 (72) = happyGoto action_21
action_365 (74) = happyGoto action_22
action_365 (75) = happyGoto action_23
action_365 (93) = happyGoto action_24
action_365 (95) = happyGoto action_90
action_365 (97) = happyGoto action_26
action_365 (104) = happyGoto action_27
action_365 (105) = happyGoto action_28
action_365 (106) = happyGoto action_29
action_365 (108) = happyGoto action_30
action_365 (114) = happyGoto action_31
action_365 (126) = happyGoto action_33
action_365 _ = happyFail
action_366 (142) = happyShift action_401
action_366 (173) = happyShift action_402
action_366 (19) = happyGoto action_399
action_366 (20) = happyGoto action_400
action_366 _ = happyReduce_37
action_367 (130) = happyShift action_73
action_367 (119) = happyGoto action_398
action_367 _ = happyFail
action_368 (128) = happyShift action_34
action_368 (129) = happyShift action_35
action_368 (130) = happyShift action_36
action_368 (131) = happyShift action_37
action_368 (132) = happyShift action_38
action_368 (137) = happyShift action_39
action_368 (138) = happyShift action_40
action_368 (139) = happyShift action_41
action_368 (140) = happyShift action_42
action_368 (141) = happyShift action_43
action_368 (142) = happyShift action_44
action_368 (144) = happyShift action_226
action_368 (148) = happyShift action_45
action_368 (151) = happyShift action_46
action_368 (157) = happyShift action_47
action_368 (162) = happyShift action_48
action_368 (165) = happyShift action_49
action_368 (166) = happyShift action_50
action_368 (171) = happyShift action_54
action_368 (173) = happyShift action_55
action_368 (174) = happyShift action_56
action_368 (181) = happyShift action_62
action_368 (188) = happyShift action_65
action_368 (191) = happyShift action_68
action_368 (192) = happyShift action_69
action_368 (193) = happyShift action_70
action_368 (194) = happyShift action_71
action_368 (7) = happyGoto action_394
action_368 (61) = happyGoto action_395
action_368 (63) = happyGoto action_396
action_368 (64) = happyGoto action_397
action_368 (70) = happyGoto action_19
action_368 (71) = happyGoto action_20
action_368 (72) = happyGoto action_21
action_368 (74) = happyGoto action_22
action_368 (75) = happyGoto action_23
action_368 (93) = happyGoto action_24
action_368 (95) = happyGoto action_90
action_368 (97) = happyGoto action_26
action_368 (104) = happyGoto action_27
action_368 (105) = happyGoto action_28
action_368 (106) = happyGoto action_29
action_368 (108) = happyGoto action_30
action_368 (114) = happyGoto action_31
action_368 (126) = happyGoto action_33
action_368 _ = happyReduce_10
action_369 (117) = happyGoto action_393
action_369 _ = happyReduce_281
action_370 _ = happyReduce_78
action_371 _ = happyReduce_72
action_372 (170) = happyShift action_392
action_372 (56) = happyGoto action_391
action_372 _ = happyReduce_130
action_373 _ = happyReduce_61
action_374 _ = happyReduce_68
action_375 (128) = happyShift action_34
action_375 (129) = happyShift action_35
action_375 (130) = happyShift action_36
action_375 (131) = happyShift action_37
action_375 (132) = happyShift action_38
action_375 (137) = happyShift action_39
action_375 (138) = happyShift action_40
action_375 (139) = happyShift action_41
action_375 (140) = happyShift action_42
action_375 (141) = happyShift action_43
action_375 (142) = happyShift action_44
action_375 (148) = happyShift action_45
action_375 (151) = happyShift action_46
action_375 (157) = happyShift action_47
action_375 (162) = happyShift action_48
action_375 (165) = happyShift action_49
action_375 (166) = happyShift action_50
action_375 (171) = happyShift action_54
action_375 (173) = happyShift action_55
action_375 (174) = happyShift action_56
action_375 (181) = happyShift action_62
action_375 (188) = happyShift action_65
action_375 (191) = happyShift action_68
action_375 (192) = happyShift action_69
action_375 (193) = happyShift action_70
action_375 (194) = happyShift action_71
action_375 (69) = happyGoto action_390
action_375 (70) = happyGoto action_89
action_375 (71) = happyGoto action_20
action_375 (72) = happyGoto action_21
action_375 (74) = happyGoto action_22
action_375 (75) = happyGoto action_23
action_375 (93) = happyGoto action_24
action_375 (95) = happyGoto action_90
action_375 (97) = happyGoto action_26
action_375 (104) = happyGoto action_27
action_375 (105) = happyGoto action_28
action_375 (106) = happyGoto action_29
action_375 (108) = happyGoto action_30
action_375 (114) = happyGoto action_31
action_375 (126) = happyGoto action_33
action_375 _ = happyFail
action_376 _ = happyReduce_294
action_377 _ = happyReduce_17
action_378 _ = happyReduce_13
action_379 (143) = happyShift action_388
action_379 (150) = happyShift action_389
action_379 _ = happyFail
action_380 _ = happyReduce_26
action_381 _ = happyReduce_27
action_382 _ = happyReduce_28
action_383 (132) = happyShift action_137
action_383 (133) = happyShift action_118
action_383 (134) = happyShift action_119
action_383 (135) = happyShift action_120
action_383 (136) = happyShift action_121
action_383 (153) = happyShift action_125
action_383 (164) = happyShift action_126
action_383 (109) = happyGoto action_387
action_383 (110) = happyGoto action_113
action_383 (111) = happyGoto action_247
action_383 (112) = happyGoto action_115
action_383 (113) = happyGoto action_116
action_383 _ = happyFail
action_384 _ = happyReduce_22
action_385 (143) = happyShift action_386
action_385 _ = happyFail
action_386 _ = happyReduce_21
action_387 (143) = happyShift action_174
action_387 _ = happyFail
action_388 _ = happyReduce_23
action_389 (128) = happyShift action_34
action_389 (129) = happyShift action_35
action_389 (130) = happyShift action_36
action_389 (131) = happyShift action_37
action_389 (142) = happyShift action_383
action_389 (165) = happyShift action_49
action_389 (173) = happyShift action_55
action_389 (188) = happyShift action_65
action_389 (14) = happyGoto action_474
action_389 (95) = happyGoto action_381
action_389 (97) = happyGoto action_382
action_389 (104) = happyGoto action_27
action_389 (105) = happyGoto action_28
action_389 (106) = happyGoto action_29
action_389 (108) = happyGoto action_30
action_389 _ = happyFail
action_390 _ = happyReduce_289
action_391 _ = happyReduce_63
action_392 (130) = happyShift action_36
action_392 (131) = happyShift action_200
action_392 (142) = happyShift action_473
action_392 (107) = happyGoto action_471
action_392 (108) = happyGoto action_80
action_392 (121) = happyGoto action_198
action_392 (123) = happyGoto action_472
action_392 _ = happyFail
action_393 (128) = happyShift action_34
action_393 (129) = happyShift action_35
action_393 (130) = happyShift action_36
action_393 (131) = happyShift action_37
action_393 (132) = happyShift action_38
action_393 (137) = happyShift action_39
action_393 (138) = happyShift action_40
action_393 (139) = happyShift action_41
action_393 (140) = happyShift action_42
action_393 (141) = happyShift action_43
action_393 (142) = happyShift action_44
action_393 (144) = happyShift action_226
action_393 (148) = happyShift action_45
action_393 (151) = happyShift action_46
action_393 (157) = happyShift action_47
action_393 (162) = happyShift action_48
action_393 (165) = happyShift action_49
action_393 (166) = happyShift action_50
action_393 (171) = happyShift action_54
action_393 (173) = happyShift action_55
action_393 (174) = happyShift action_56
action_393 (181) = happyShift action_62
action_393 (188) = happyShift action_65
action_393 (191) = happyShift action_68
action_393 (192) = happyShift action_69
action_393 (193) = happyShift action_70
action_393 (194) = happyShift action_71
action_393 (7) = happyGoto action_394
action_393 (61) = happyGoto action_395
action_393 (63) = happyGoto action_470
action_393 (64) = happyGoto action_397
action_393 (70) = happyGoto action_19
action_393 (71) = happyGoto action_20
action_393 (72) = happyGoto action_21
action_393 (74) = happyGoto action_22
action_393 (75) = happyGoto action_23
action_393 (93) = happyGoto action_24
action_393 (95) = happyGoto action_90
action_393 (97) = happyGoto action_26
action_393 (104) = happyGoto action_27
action_393 (105) = happyGoto action_28
action_393 (106) = happyGoto action_29
action_393 (108) = happyGoto action_30
action_393 (114) = happyGoto action_31
action_393 (126) = happyGoto action_33
action_393 _ = happyReduce_10
action_394 _ = happyReduce_150
action_395 (144) = happyShift action_469
action_395 (7) = happyGoto action_468
action_395 _ = happyReduce_10
action_396 (1) = happyShift action_146
action_396 (147) = happyShift action_147
action_396 (116) = happyGoto action_467
action_396 _ = happyFail
action_397 _ = happyReduce_145
action_398 _ = happyReduce_34
action_399 _ = happyReduce_31
action_400 _ = happyReduce_36
action_401 (128) = happyShift action_34
action_401 (130) = happyShift action_36
action_401 (142) = happyShift action_157
action_401 (165) = happyShift action_49
action_401 (173) = happyShift action_55
action_401 (188) = happyShift action_65
action_401 (21) = happyGoto action_462
action_401 (22) = happyGoto action_463
action_401 (94) = happyGoto action_464
action_401 (105) = happyGoto action_156
action_401 (108) = happyGoto action_465
action_401 (120) = happyGoto action_466
action_401 _ = happyFail
action_402 (142) = happyShift action_461
action_402 _ = happyFail
action_403 _ = happyReduce_166
action_404 (128) = happyShift action_34
action_404 (130) = happyShift action_36
action_404 (131) = happyShift action_200
action_404 (134) = happyReduce_123
action_404 (137) = happyShift action_201
action_404 (142) = happyShift action_202
action_404 (148) = happyShift action_203
action_404 (152) = happyReduce_123
action_404 (164) = happyShift action_460
action_404 (165) = happyShift action_49
action_404 (173) = happyShift action_55
action_404 (188) = happyShift action_65
action_404 (39) = happyGoto action_284
action_404 (40) = happyGoto action_194
action_404 (105) = happyGoto action_196
action_404 (107) = happyGoto action_197
action_404 (108) = happyGoto action_80
action_404 (121) = happyGoto action_198
action_404 (124) = happyGoto action_199
action_404 _ = happyReduce_117
action_405 _ = happyReduce_114
action_406 (128) = happyShift action_34
action_406 (130) = happyShift action_36
action_406 (131) = happyShift action_200
action_406 (137) = happyShift action_201
action_406 (142) = happyShift action_202
action_406 (148) = happyShift action_203
action_406 (164) = happyShift action_459
action_406 (165) = happyShift action_49
action_406 (173) = happyShift action_55
action_406 (188) = happyShift action_65
action_406 (39) = happyGoto action_457
action_406 (40) = happyGoto action_194
action_406 (51) = happyGoto action_458
action_406 (105) = happyGoto action_196
action_406 (107) = happyGoto action_197
action_406 (108) = happyGoto action_80
action_406 (121) = happyGoto action_198
action_406 (124) = happyGoto action_199
action_406 _ = happyReduce_118
action_407 (134) = happyShift action_119
action_407 (152) = happyShift action_456
action_407 (100) = happyGoto action_455
action_407 (110) = happyGoto action_322
action_407 _ = happyFail
action_408 (145) = happyShift action_454
action_408 _ = happyFail
action_409 (145) = happyReduce_237
action_409 _ = happyReduce_285
action_410 (128) = happyShift action_34
action_410 (130) = happyShift action_36
action_410 (131) = happyShift action_200
action_410 (134) = happyShift action_119
action_410 (137) = happyShift action_201
action_410 (142) = happyShift action_202
action_410 (143) = happyShift action_279
action_410 (148) = happyShift action_203
action_410 (150) = happyShift action_123
action_410 (160) = happyShift action_280
action_410 (165) = happyShift action_49
action_410 (173) = happyShift action_55
action_410 (188) = happyShift action_65
action_410 (37) = happyGoto action_276
action_410 (38) = happyGoto action_192
action_410 (39) = happyGoto action_193
action_410 (40) = happyGoto action_194
action_410 (42) = happyGoto action_277
action_410 (76) = happyGoto action_278
action_410 (105) = happyGoto action_196
action_410 (107) = happyGoto action_197
action_410 (108) = happyGoto action_80
action_410 (110) = happyGoto action_453
action_410 (121) = happyGoto action_198
action_410 (124) = happyGoto action_199
action_410 _ = happyFail
action_411 (128) = happyShift action_34
action_411 (130) = happyShift action_36
action_411 (131) = happyShift action_200
action_411 (137) = happyShift action_201
action_411 (142) = happyShift action_202
action_411 (148) = happyShift action_203
action_411 (165) = happyShift action_49
action_411 (173) = happyShift action_55
action_411 (188) = happyShift action_65
action_411 (39) = happyGoto action_452
action_411 (40) = happyGoto action_194
action_411 (105) = happyGoto action_196
action_411 (107) = happyGoto action_197
action_411 (108) = happyGoto action_80
action_411 (121) = happyGoto action_198
action_411 (124) = happyGoto action_199
action_411 _ = happyFail
action_412 _ = happyReduce_62
action_413 (48) = happyGoto action_451
action_413 (115) = happyGoto action_360
action_413 _ = happyReduce_278
action_414 _ = happyReduce_103
action_415 _ = happyReduce_102
action_416 _ = happyReduce_98
action_417 (143) = happyShift action_450
action_417 (150) = happyShift action_179
action_417 _ = happyFail
action_418 _ = happyReduce_97
action_419 (128) = happyShift action_34
action_419 (129) = happyShift action_35
action_419 (142) = happyShift action_241
action_419 (144) = happyShift action_226
action_419 (165) = happyShift action_49
action_419 (173) = happyShift action_55
action_419 (188) = happyShift action_65
action_419 (7) = happyGoto action_420
action_419 (35) = happyGoto action_421
action_419 (36) = happyGoto action_17
action_419 (59) = happyGoto action_449
action_419 (60) = happyGoto action_423
action_419 (95) = happyGoto action_424
action_419 (104) = happyGoto action_27
action_419 (105) = happyGoto action_28
action_419 _ = happyReduce_10
action_420 _ = happyReduce_141
action_421 _ = happyReduce_143
action_422 (1) = happyShift action_146
action_422 (147) = happyShift action_147
action_422 (116) = happyGoto action_448
action_422 _ = happyFail
action_423 (144) = happyShift action_447
action_423 (7) = happyGoto action_446
action_423 _ = happyReduce_10
action_424 _ = happyReduce_82
action_425 (1) = happyShift action_146
action_425 (147) = happyShift action_147
action_425 (116) = happyGoto action_445
action_425 _ = happyFail
action_426 (128) = happyShift action_34
action_426 (129) = happyShift action_35
action_426 (130) = happyShift action_36
action_426 (131) = happyShift action_37
action_426 (132) = happyShift action_38
action_426 (137) = happyShift action_39
action_426 (138) = happyShift action_40
action_426 (139) = happyShift action_41
action_426 (140) = happyShift action_42
action_426 (141) = happyShift action_43
action_426 (142) = happyShift action_44
action_426 (148) = happyShift action_45
action_426 (151) = happyShift action_46
action_426 (157) = happyShift action_47
action_426 (162) = happyShift action_48
action_426 (165) = happyShift action_49
action_426 (166) = happyShift action_50
action_426 (171) = happyShift action_54
action_426 (173) = happyShift action_55
action_426 (174) = happyShift action_56
action_426 (181) = happyShift action_62
action_426 (188) = happyShift action_65
action_426 (191) = happyShift action_68
action_426 (192) = happyShift action_69
action_426 (193) = happyShift action_70
action_426 (194) = happyShift action_71
action_426 (70) = happyGoto action_340
action_426 (71) = happyGoto action_20
action_426 (72) = happyGoto action_21
action_426 (74) = happyGoto action_22
action_426 (75) = happyGoto action_23
action_426 (84) = happyGoto action_444
action_426 (93) = happyGoto action_24
action_426 (95) = happyGoto action_90
action_426 (97) = happyGoto action_26
action_426 (104) = happyGoto action_27
action_426 (105) = happyGoto action_28
action_426 (106) = happyGoto action_29
action_426 (108) = happyGoto action_30
action_426 (114) = happyGoto action_31
action_426 (126) = happyGoto action_33
action_426 _ = happyReduce_9
action_427 (158) = happyShift action_442
action_427 (160) = happyShift action_443
action_427 (85) = happyGoto action_439
action_427 (86) = happyGoto action_440
action_427 (87) = happyGoto action_441
action_427 _ = happyFail
action_428 (144) = happyShift action_426
action_428 (7) = happyGoto action_438
action_428 _ = happyReduce_10
action_429 _ = happyReduce_201
action_430 _ = happyReduce_197
action_431 _ = happyReduce_223
action_432 _ = happyReduce_225
action_433 (128) = happyShift action_34
action_433 (129) = happyShift action_35
action_433 (130) = happyShift action_36
action_433 (131) = happyShift action_37
action_433 (132) = happyShift action_38
action_433 (137) = happyShift action_39
action_433 (138) = happyShift action_40
action_433 (139) = happyShift action_41
action_433 (140) = happyShift action_42
action_433 (141) = happyShift action_43
action_433 (142) = happyShift action_44
action_433 (148) = happyShift action_45
action_433 (151) = happyShift action_46
action_433 (157) = happyShift action_47
action_433 (162) = happyShift action_48
action_433 (165) = happyShift action_49
action_433 (166) = happyShift action_50
action_433 (171) = happyShift action_54
action_433 (173) = happyShift action_55
action_433 (174) = happyShift action_56
action_433 (181) = happyShift action_62
action_433 (188) = happyShift action_65
action_433 (191) = happyShift action_68
action_433 (192) = happyShift action_69
action_433 (193) = happyShift action_70
action_433 (194) = happyShift action_71
action_433 (69) = happyGoto action_437
action_433 (70) = happyGoto action_89
action_433 (71) = happyGoto action_20
action_433 (72) = happyGoto action_21
action_433 (74) = happyGoto action_22
action_433 (75) = happyGoto action_23
action_433 (93) = happyGoto action_24
action_433 (95) = happyGoto action_90
action_433 (97) = happyGoto action_26
action_433 (104) = happyGoto action_27
action_433 (105) = happyGoto action_28
action_433 (106) = happyGoto action_29
action_433 (108) = happyGoto action_30
action_433 (114) = happyGoto action_31
action_433 (126) = happyGoto action_33
action_433 _ = happyFail
action_434 _ = happyReduce_59
action_435 _ = happyReduce_246
action_436 _ = happyReduce_242
action_437 _ = happyReduce_158
action_438 (146) = happyShift action_497
action_438 _ = happyFail
action_439 (187) = happyShift action_496
action_439 _ = happyReduce_210
action_440 (158) = happyShift action_442
action_440 (87) = happyGoto action_495
action_440 _ = happyReduce_213
action_441 _ = happyReduce_215
action_442 (115) = happyGoto action_494
action_442 _ = happyReduce_278
action_443 (128) = happyShift action_34
action_443 (129) = happyShift action_35
action_443 (130) = happyShift action_36
action_443 (131) = happyShift action_37
action_443 (132) = happyShift action_38
action_443 (137) = happyShift action_39
action_443 (138) = happyShift action_40
action_443 (139) = happyShift action_41
action_443 (140) = happyShift action_42
action_443 (141) = happyShift action_43
action_443 (142) = happyShift action_44
action_443 (148) = happyShift action_45
action_443 (151) = happyShift action_46
action_443 (157) = happyShift action_47
action_443 (162) = happyShift action_48
action_443 (165) = happyShift action_49
action_443 (166) = happyShift action_50
action_443 (171) = happyShift action_54
action_443 (173) = happyShift action_55
action_443 (174) = happyShift action_56
action_443 (181) = happyShift action_62
action_443 (188) = happyShift action_65
action_443 (191) = happyShift action_68
action_443 (192) = happyShift action_69
action_443 (193) = happyShift action_70
action_443 (194) = happyShift action_71
action_443 (69) = happyGoto action_493
action_443 (70) = happyGoto action_89
action_443 (71) = happyGoto action_20
action_443 (72) = happyGoto action_21
action_443 (74) = happyGoto action_22
action_443 (75) = happyGoto action_23
action_443 (93) = happyGoto action_24
action_443 (95) = happyGoto action_90
action_443 (97) = happyGoto action_26
action_443 (104) = happyGoto action_27
action_443 (105) = happyGoto action_28
action_443 (106) = happyGoto action_29
action_443 (108) = happyGoto action_30
action_443 (114) = happyGoto action_31
action_443 (126) = happyGoto action_33
action_443 _ = happyFail
action_444 _ = happyReduce_208
action_445 _ = happyReduce_207
action_446 _ = happyReduce_140
action_447 (128) = happyShift action_34
action_447 (129) = happyShift action_35
action_447 (130) = happyShift action_36
action_447 (131) = happyShift action_37
action_447 (132) = happyShift action_38
action_447 (137) = happyShift action_39
action_447 (138) = happyShift action_40
action_447 (139) = happyShift action_41
action_447 (140) = happyShift action_42
action_447 (141) = happyShift action_43
action_447 (142) = happyShift action_44
action_447 (148) = happyShift action_45
action_447 (151) = happyShift action_46
action_447 (157) = happyShift action_47
action_447 (162) = happyShift action_48
action_447 (165) = happyShift action_49
action_447 (166) = happyShift action_50
action_447 (171) = happyShift action_54
action_447 (173) = happyShift action_55
action_447 (174) = happyShift action_56
action_447 (181) = happyShift action_62
action_447 (188) = happyShift action_65
action_447 (191) = happyShift action_68
action_447 (192) = happyShift action_69
action_447 (193) = happyShift action_70
action_447 (194) = happyShift action_71
action_447 (35) = happyGoto action_491
action_447 (36) = happyGoto action_17
action_447 (61) = happyGoto action_492
action_447 (64) = happyGoto action_397
action_447 (70) = happyGoto action_19
action_447 (71) = happyGoto action_20
action_447 (72) = happyGoto action_21
action_447 (74) = happyGoto action_22
action_447 (75) = happyGoto action_23
action_447 (93) = happyGoto action_24
action_447 (95) = happyGoto action_25
action_447 (97) = happyGoto action_26
action_447 (104) = happyGoto action_27
action_447 (105) = happyGoto action_28
action_447 (106) = happyGoto action_29
action_447 (108) = happyGoto action_30
action_447 (114) = happyGoto action_31
action_447 (126) = happyGoto action_33
action_447 _ = happyReduce_9
action_448 _ = happyReduce_137
action_449 (146) = happyShift action_490
action_449 _ = happyFail
action_450 _ = happyReduce_99
action_451 _ = happyReduce_112
action_452 _ = happyReduce_124
action_453 (143) = happyShift action_489
action_453 _ = happyFail
action_454 (117) = happyGoto action_488
action_454 _ = happyReduce_281
action_455 (128) = happyShift action_34
action_455 (130) = happyShift action_36
action_455 (131) = happyShift action_200
action_455 (137) = happyShift action_201
action_455 (142) = happyShift action_202
action_455 (148) = happyShift action_203
action_455 (164) = happyShift action_411
action_455 (165) = happyShift action_49
action_455 (173) = happyShift action_55
action_455 (188) = happyShift action_65
action_455 (38) = happyGoto action_486
action_455 (39) = happyGoto action_193
action_455 (40) = happyGoto action_194
action_455 (52) = happyGoto action_487
action_455 (105) = happyGoto action_196
action_455 (107) = happyGoto action_197
action_455 (108) = happyGoto action_80
action_455 (121) = happyGoto action_198
action_455 (124) = happyGoto action_199
action_455 _ = happyFail
action_456 (130) = happyShift action_36
action_456 (108) = happyGoto action_327
action_456 _ = happyFail
action_457 _ = happyReduce_121
action_458 _ = happyReduce_120
action_459 (128) = happyShift action_34
action_459 (130) = happyShift action_36
action_459 (131) = happyShift action_200
action_459 (137) = happyShift action_201
action_459 (142) = happyShift action_202
action_459 (148) = happyShift action_203
action_459 (165) = happyShift action_49
action_459 (173) = happyShift action_55
action_459 (188) = happyShift action_65
action_459 (39) = happyGoto action_485
action_459 (40) = happyGoto action_194
action_459 (105) = happyGoto action_196
action_459 (107) = happyGoto action_197
action_459 (108) = happyGoto action_80
action_459 (121) = happyGoto action_198
action_459 (124) = happyGoto action_199
action_459 _ = happyFail
action_460 (128) = happyShift action_34
action_460 (130) = happyShift action_36
action_460 (131) = happyShift action_200
action_460 (137) = happyShift action_201
action_460 (142) = happyShift action_202
action_460 (148) = happyShift action_203
action_460 (165) = happyShift action_49
action_460 (173) = happyShift action_55
action_460 (188) = happyShift action_65
action_460 (39) = happyGoto action_484
action_460 (40) = happyGoto action_194
action_460 (105) = happyGoto action_196
action_460 (107) = happyGoto action_197
action_460 (108) = happyGoto action_80
action_460 (121) = happyGoto action_198
action_460 (124) = happyGoto action_199
action_460 _ = happyFail
action_461 (128) = happyShift action_34
action_461 (130) = happyShift action_36
action_461 (142) = happyShift action_157
action_461 (165) = happyShift action_49
action_461 (173) = happyShift action_55
action_461 (188) = happyShift action_65
action_461 (21) = happyGoto action_483
action_461 (22) = happyGoto action_463
action_461 (94) = happyGoto action_464
action_461 (105) = happyGoto action_156
action_461 (108) = happyGoto action_465
action_461 (120) = happyGoto action_466
action_461 _ = happyFail
action_462 (150) = happyShift action_482
action_462 (10) = happyGoto action_481
action_462 _ = happyReduce_16
action_463 _ = happyReduce_41
action_464 _ = happyReduce_42
action_465 _ = happyReduce_284
action_466 (142) = happyShift action_480
action_466 _ = happyReduce_43
action_467 _ = happyReduce_147
action_468 _ = happyReduce_149
action_469 (128) = happyShift action_34
action_469 (129) = happyShift action_35
action_469 (130) = happyShift action_36
action_469 (131) = happyShift action_37
action_469 (132) = happyShift action_38
action_469 (137) = happyShift action_39
action_469 (138) = happyShift action_40
action_469 (139) = happyShift action_41
action_469 (140) = happyShift action_42
action_469 (141) = happyShift action_43
action_469 (142) = happyShift action_44
action_469 (148) = happyShift action_45
action_469 (151) = happyShift action_46
action_469 (157) = happyShift action_47
action_469 (162) = happyShift action_48
action_469 (165) = happyShift action_49
action_469 (166) = happyShift action_50
action_469 (171) = happyShift action_54
action_469 (173) = happyShift action_55
action_469 (174) = happyShift action_56
action_469 (181) = happyShift action_62
action_469 (188) = happyShift action_65
action_469 (191) = happyShift action_68
action_469 (192) = happyShift action_69
action_469 (193) = happyShift action_70
action_469 (194) = happyShift action_71
action_469 (64) = happyGoto action_479
action_469 (70) = happyGoto action_19
action_469 (71) = happyGoto action_20
action_469 (72) = happyGoto action_21
action_469 (74) = happyGoto action_22
action_469 (75) = happyGoto action_23
action_469 (93) = happyGoto action_24
action_469 (95) = happyGoto action_90
action_469 (97) = happyGoto action_26
action_469 (104) = happyGoto action_27
action_469 (105) = happyGoto action_28
action_469 (106) = happyGoto action_29
action_469 (108) = happyGoto action_30
action_469 (114) = happyGoto action_31
action_469 (126) = happyGoto action_33
action_469 _ = happyReduce_9
action_470 (146) = happyShift action_478
action_470 _ = happyFail
action_471 _ = happyReduce_287
action_472 _ = happyReduce_131
action_473 (130) = happyShift action_36
action_473 (131) = happyShift action_200
action_473 (143) = happyShift action_477
action_473 (57) = happyGoto action_475
action_473 (107) = happyGoto action_471
action_473 (108) = happyGoto action_80
action_473 (121) = happyGoto action_198
action_473 (123) = happyGoto action_476
action_473 _ = happyFail
action_474 _ = happyReduce_25
action_475 (143) = happyShift action_515
action_475 (150) = happyShift action_516
action_475 _ = happyFail
action_476 _ = happyReduce_135
action_477 _ = happyReduce_132
action_478 _ = happyReduce_146
action_479 _ = happyReduce_144
action_480 (128) = happyShift action_34
action_480 (130) = happyShift action_36
action_480 (142) = happyShift action_512
action_480 (143) = happyShift action_513
action_480 (154) = happyShift action_514
action_480 (165) = happyShift action_49
action_480 (173) = happyShift action_55
action_480 (188) = happyShift action_65
action_480 (23) = happyGoto action_507
action_480 (24) = happyGoto action_508
action_480 (94) = happyGoto action_509
action_480 (96) = happyGoto action_510
action_480 (105) = happyGoto action_156
action_480 (108) = happyGoto action_511
action_480 _ = happyFail
action_481 (143) = happyShift action_506
action_481 _ = happyFail
action_482 (128) = happyShift action_34
action_482 (130) = happyShift action_36
action_482 (142) = happyShift action_157
action_482 (165) = happyShift action_49
action_482 (173) = happyShift action_55
action_482 (188) = happyShift action_65
action_482 (22) = happyGoto action_505
action_482 (94) = happyGoto action_464
action_482 (105) = happyGoto action_156
action_482 (108) = happyGoto action_465
action_482 (120) = happyGoto action_466
action_482 _ = happyReduce_15
action_483 (150) = happyShift action_482
action_483 (10) = happyGoto action_504
action_483 _ = happyReduce_16
action_484 _ = happyReduce_119
action_485 _ = happyReduce_122
action_486 (128) = happyShift action_34
action_486 (130) = happyShift action_36
action_486 (131) = happyShift action_200
action_486 (137) = happyShift action_201
action_486 (142) = happyShift action_202
action_486 (148) = happyShift action_203
action_486 (165) = happyShift action_49
action_486 (173) = happyShift action_55
action_486 (188) = happyShift action_65
action_486 (39) = happyGoto action_284
action_486 (40) = happyGoto action_194
action_486 (105) = happyGoto action_196
action_486 (107) = happyGoto action_197
action_486 (108) = happyGoto action_80
action_486 (121) = happyGoto action_198
action_486 (124) = happyGoto action_199
action_486 _ = happyReduce_123
action_487 _ = happyReduce_115
action_488 (128) = happyShift action_34
action_488 (129) = happyShift action_35
action_488 (142) = happyShift action_241
action_488 (165) = happyShift action_49
action_488 (173) = happyShift action_55
action_488 (188) = happyShift action_65
action_488 (36) = happyGoto action_501
action_488 (53) = happyGoto action_502
action_488 (54) = happyGoto action_503
action_488 (95) = happyGoto action_424
action_488 (104) = happyGoto action_27
action_488 (105) = happyGoto action_28
action_488 _ = happyFail
action_489 _ = happyReduce_238
action_490 _ = happyReduce_136
action_491 _ = happyReduce_142
action_492 (144) = happyShift action_469
action_492 (7) = happyGoto action_500
action_492 _ = happyReduce_10
action_493 _ = happyReduce_212
action_494 (128) = happyShift action_34
action_494 (129) = happyShift action_35
action_494 (130) = happyShift action_36
action_494 (131) = happyShift action_37
action_494 (132) = happyShift action_38
action_494 (137) = happyShift action_39
action_494 (138) = happyShift action_40
action_494 (139) = happyShift action_41
action_494 (140) = happyShift action_42
action_494 (141) = happyShift action_43
action_494 (142) = happyShift action_44
action_494 (148) = happyShift action_45
action_494 (151) = happyShift action_46
action_494 (157) = happyShift action_47
action_494 (162) = happyShift action_48
action_494 (165) = happyShift action_49
action_494 (166) = happyShift action_50
action_494 (171) = happyShift action_54
action_494 (173) = happyShift action_55
action_494 (174) = happyShift action_56
action_494 (181) = happyShift action_62
action_494 (188) = happyShift action_65
action_494 (191) = happyShift action_68
action_494 (192) = happyShift action_69
action_494 (193) = happyShift action_70
action_494 (194) = happyShift action_71
action_494 (69) = happyGoto action_499
action_494 (70) = happyGoto action_89
action_494 (71) = happyGoto action_20
action_494 (72) = happyGoto action_21
action_494 (74) = happyGoto action_22
action_494 (75) = happyGoto action_23
action_494 (93) = happyGoto action_24
action_494 (95) = happyGoto action_90
action_494 (97) = happyGoto action_26
action_494 (104) = happyGoto action_27
action_494 (105) = happyGoto action_28
action_494 (106) = happyGoto action_29
action_494 (108) = happyGoto action_30
action_494 (114) = happyGoto action_31
action_494 (126) = happyGoto action_33
action_494 _ = happyFail
action_495 _ = happyReduce_214
action_496 (145) = happyShift action_85
action_496 (34) = happyGoto action_498
action_496 (118) = happyGoto action_84
action_496 _ = happyReduce_282
action_497 _ = happyReduce_206
action_498 _ = happyReduce_211
action_499 (160) = happyShift action_525
action_499 _ = happyFail
action_500 _ = happyReduce_139
action_501 (150) = happyShift action_139
action_501 (155) = happyShift action_524
action_501 _ = happyFail
action_502 (146) = happyShift action_522
action_502 (150) = happyShift action_523
action_502 _ = happyFail
action_503 _ = happyReduce_126
action_504 (143) = happyShift action_521
action_504 _ = happyFail
action_505 _ = happyReduce_40
action_506 _ = happyReduce_38
action_507 (143) = happyShift action_519
action_507 (150) = happyShift action_520
action_507 _ = happyFail
action_508 _ = happyReduce_48
action_509 _ = happyReduce_49
action_510 _ = happyReduce_50
action_511 _ = happyReduce_237
action_512 (132) = happyShift action_137
action_512 (133) = happyShift action_118
action_512 (134) = happyShift action_119
action_512 (153) = happyShift action_125
action_512 (164) = happyShift action_126
action_512 (110) = happyGoto action_453
action_512 (112) = happyGoto action_317
action_512 _ = happyFail
action_513 _ = happyReduce_45
action_514 (143) = happyShift action_518
action_514 _ = happyFail
action_515 _ = happyReduce_133
action_516 (130) = happyShift action_36
action_516 (131) = happyShift action_200
action_516 (107) = happyGoto action_471
action_516 (108) = happyGoto action_80
action_516 (121) = happyGoto action_198
action_516 (123) = happyGoto action_517
action_516 _ = happyFail
action_517 _ = happyReduce_134
action_518 _ = happyReduce_44
action_519 _ = happyReduce_46
action_520 (128) = happyShift action_34
action_520 (130) = happyShift action_36
action_520 (142) = happyShift action_512
action_520 (165) = happyShift action_49
action_520 (173) = happyShift action_55
action_520 (188) = happyShift action_65
action_520 (24) = happyGoto action_531
action_520 (94) = happyGoto action_509
action_520 (96) = happyGoto action_510
action_520 (105) = happyGoto action_156
action_520 (108) = happyGoto action_511
action_520 _ = happyFail
action_521 _ = happyReduce_39
action_522 _ = happyReduce_116
action_523 (128) = happyShift action_34
action_523 (129) = happyShift action_35
action_523 (142) = happyShift action_241
action_523 (165) = happyShift action_49
action_523 (173) = happyShift action_55
action_523 (188) = happyShift action_65
action_523 (36) = happyGoto action_501
action_523 (54) = happyGoto action_530
action_523 (95) = happyGoto action_424
action_523 (104) = happyGoto action_27
action_523 (105) = happyGoto action_28
action_523 _ = happyFail
action_524 (128) = happyShift action_34
action_524 (130) = happyShift action_36
action_524 (131) = happyShift action_200
action_524 (137) = happyShift action_201
action_524 (142) = happyShift action_202
action_524 (148) = happyShift action_203
action_524 (164) = happyShift action_529
action_524 (165) = happyShift action_49
action_524 (173) = happyShift action_55
action_524 (188) = happyShift action_65
action_524 (37) = happyGoto action_527
action_524 (38) = happyGoto action_192
action_524 (39) = happyGoto action_193
action_524 (40) = happyGoto action_194
action_524 (55) = happyGoto action_528
action_524 (105) = happyGoto action_196
action_524 (107) = happyGoto action_197
action_524 (108) = happyGoto action_80
action_524 (121) = happyGoto action_198
action_524 (124) = happyGoto action_199
action_524 _ = happyFail
action_525 (128) = happyShift action_34
action_525 (129) = happyShift action_35
action_525 (130) = happyShift action_36
action_525 (131) = happyShift action_37
action_525 (132) = happyShift action_38
action_525 (137) = happyShift action_39
action_525 (138) = happyShift action_40
action_525 (139) = happyShift action_41
action_525 (140) = happyShift action_42
action_525 (141) = happyShift action_43
action_525 (142) = happyShift action_44
action_525 (148) = happyShift action_45
action_525 (151) = happyShift action_46
action_525 (157) = happyShift action_47
action_525 (162) = happyShift action_48
action_525 (165) = happyShift action_49
action_525 (166) = happyShift action_50
action_525 (171) = happyShift action_54
action_525 (173) = happyShift action_55
action_525 (174) = happyShift action_56
action_525 (181) = happyShift action_62
action_525 (188) = happyShift action_65
action_525 (191) = happyShift action_68
action_525 (192) = happyShift action_69
action_525 (193) = happyShift action_70
action_525 (194) = happyShift action_71
action_525 (69) = happyGoto action_526
action_525 (70) = happyGoto action_89
action_525 (71) = happyGoto action_20
action_525 (72) = happyGoto action_21
action_525 (74) = happyGoto action_22
action_525 (75) = happyGoto action_23
action_525 (93) = happyGoto action_24
action_525 (95) = happyGoto action_90
action_525 (97) = happyGoto action_26
action_525 (104) = happyGoto action_27
action_525 (105) = happyGoto action_28
action_525 (106) = happyGoto action_29
action_525 (108) = happyGoto action_30
action_525 (114) = happyGoto action_31
action_525 (126) = happyGoto action_33
action_525 _ = happyFail
action_526 _ = happyReduce_216
action_527 _ = happyReduce_128
action_528 _ = happyReduce_127
action_529 (128) = happyShift action_34
action_529 (130) = happyShift action_36
action_529 (131) = happyShift action_200
action_529 (137) = happyShift action_201
action_529 (142) = happyShift action_202
action_529 (148) = happyShift action_203
action_529 (165) = happyShift action_49
action_529 (173) = happyShift action_55
action_529 (188) = happyShift action_65
action_529 (39) = happyGoto action_532
action_529 (40) = happyGoto action_194
action_529 (105) = happyGoto action_196
action_529 (107) = happyGoto action_197
action_529 (108) = happyGoto action_80
action_529 (121) = happyGoto action_198
action_529 (124) = happyGoto action_199
action_529 _ = happyFail
action_530 _ = happyReduce_125
action_531 _ = happyReduce_47
action_532 _ = happyReduce_129
happyReduce_1 = happyReduce 5 4 happyReduction_1
happyReduction_1 ((HappyAbsSyn5 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn8 happy_var_3) `HappyStk`
(HappyAbsSyn119 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn4
(hsModule happy_var_2 happy_var_3 happy_var_5
) `HappyStk` happyRest
happyReduce_2 = happySpecReduce_1 4 happyReduction_2
happyReduction_2 (HappyAbsSyn5 happy_var_1)
= HappyAbsSyn4
(hsModule main_mod Nothing happy_var_1
)
happyReduction_2 _ = notHappyAtAll
happyReduce_3 = happyReduce 4 5 happyReduction_3
happyReduction_3 (_ `HappyStk`
(HappyAbsSyn5 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn5
(happy_var_3
) `HappyStk` happyRest
happyReduce_4 = happySpecReduce_3 5 happyReduction_4
happyReduction_4 _
(HappyAbsSyn5 happy_var_2)
_
= HappyAbsSyn5
(happy_var_2
)
happyReduction_4 _ _ _ = notHappyAtAll
happyReduce_5 = happyReduce 4 6 happyReduction_5
happyReduction_5 (_ `HappyStk`
(HappyAbsSyn25 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn15 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn5
((happy_var_1, happy_var_3)
) `HappyStk` happyRest
happyReduce_6 = happySpecReduce_2 6 happyReduction_6
happyReduction_6 _
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn5
(([], happy_var_1)
)
happyReduction_6 _ _ = notHappyAtAll
happyReduce_7 = happySpecReduce_2 6 happyReduction_7
happyReduction_7 _
(HappyAbsSyn15 happy_var_1)
= HappyAbsSyn5
((happy_var_1, [])
)
happyReduction_7 _ _ = notHappyAtAll
happyReduce_8 = happySpecReduce_0 6 happyReduction_8
happyReduction_8 = HappyAbsSyn5
(([], [])
)
happyReduce_9 = happySpecReduce_1 7 happyReduction_9
happyReduction_9 _
= HappyAbsSyn7
(()
)
happyReduce_10 = happySpecReduce_0 7 happyReduction_10
happyReduction_10 = HappyAbsSyn7
(()
)
happyReduce_11 = happySpecReduce_1 8 happyReduction_11
happyReduction_11 (HappyAbsSyn9 happy_var_1)
= HappyAbsSyn8
(Just happy_var_1
)
happyReduction_11 _ = notHappyAtAll
happyReduce_12 = happySpecReduce_0 8 happyReduction_12
happyReduction_12 = HappyAbsSyn8
(Nothing
)
happyReduce_13 = happyReduce 4 9 happyReduction_13
happyReduction_13 (_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn9 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn9
(reverse happy_var_2
) `HappyStk` happyRest
happyReduce_14 = happySpecReduce_2 9 happyReduction_14
happyReduction_14 _
_
= HappyAbsSyn9
([]
)
happyReduce_15 = happySpecReduce_1 10 happyReduction_15
happyReduction_15 _
= HappyAbsSyn7
(()
)
happyReduce_16 = happySpecReduce_0 10 happyReduction_16
happyReduction_16 = HappyAbsSyn7
(()
)
happyReduce_17 = happySpecReduce_3 11 happyReduction_17
happyReduction_17 (HappyAbsSyn12 happy_var_3)
_
(HappyAbsSyn9 happy_var_1)
= HappyAbsSyn9
(happy_var_3 : happy_var_1
)
happyReduction_17 _ _ _ = notHappyAtAll
happyReduce_18 = happySpecReduce_1 11 happyReduction_18
happyReduction_18 (HappyAbsSyn12 happy_var_1)
= HappyAbsSyn9
([happy_var_1]
)
happyReduction_18 _ = notHappyAtAll
happyReduce_19 = happySpecReduce_1 12 happyReduction_19
happyReduction_19 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn12
(HsEVar happy_var_1
)
happyReduction_19 _ = notHappyAtAll
happyReduce_20 = happySpecReduce_1 12 happyReduction_20
happyReduction_20 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn12
(HsEAbs happy_var_1
)
happyReduction_20 _ = notHappyAtAll
happyReduce_21 = happyReduce 4 12 happyReduction_21
happyReduction_21 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn12
(HsEThingAll happy_var_1
) `HappyStk` happyRest
happyReduce_22 = happySpecReduce_3 12 happyReduction_22
happyReduction_22 _
_
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn12
(HsEThingWith happy_var_1 []
)
happyReduction_22 _ _ _ = notHappyAtAll
happyReduce_23 = happyReduce 4 12 happyReduction_23
happyReduction_23 (_ `HappyStk`
(HappyAbsSyn13 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn12
(HsEThingWith happy_var_1 (reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_24 = happySpecReduce_2 12 happyReduction_24
happyReduction_24 (HappyAbsSyn119 happy_var_2)
_
= HappyAbsSyn12
(HsEModuleContents happy_var_2
)
happyReduction_24 _ _ = notHappyAtAll
happyReduce_25 = happySpecReduce_3 13 happyReduction_25
happyReduction_25 (HappyAbsSyn14 happy_var_3)
_
(HappyAbsSyn13 happy_var_1)
= HappyAbsSyn13
(happy_var_3 : happy_var_1
)
happyReduction_25 _ _ _ = notHappyAtAll
happyReduce_26 = happySpecReduce_1 13 happyReduction_26
happyReduction_26 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn13
([happy_var_1]
)
happyReduction_26 _ = notHappyAtAll
happyReduce_27 = happySpecReduce_1 14 happyReduction_27
happyReduction_27 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_27 _ = notHappyAtAll
happyReduce_28 = happySpecReduce_1 14 happyReduction_28
happyReduction_28 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_28 _ = notHappyAtAll
happyReduce_29 = happySpecReduce_3 15 happyReduction_29
happyReduction_29 (HappyAbsSyn16 happy_var_3)
_
(HappyAbsSyn15 happy_var_1)
= HappyAbsSyn15
(happy_var_3 : happy_var_1
)
happyReduction_29 _ _ _ = notHappyAtAll
happyReduce_30 = happySpecReduce_1 15 happyReduction_30
happyReduction_30 (HappyAbsSyn16 happy_var_1)
= HappyAbsSyn15
([happy_var_1]
)
happyReduction_30 _ = notHappyAtAll
happyReduce_31 = happyReduce 6 16 happyReduction_31
happyReduction_31 ((HappyAbsSyn19 happy_var_6) `HappyStk`
(HappyAbsSyn18 happy_var_5) `HappyStk`
(HappyAbsSyn119 happy_var_4) `HappyStk`
(HappyAbsSyn17 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn16
(HsImportDecl happy_var_2 happy_var_4 happy_var_3 happy_var_5 happy_var_6
) `HappyStk` happyRest
happyReduce_32 = happySpecReduce_1 17 happyReduction_32
happyReduction_32 _
= HappyAbsSyn17
(True
)
happyReduce_33 = happySpecReduce_0 17 happyReduction_33
happyReduction_33 = HappyAbsSyn17
(False
)
happyReduce_34 = happySpecReduce_2 18 happyReduction_34
happyReduction_34 (HappyAbsSyn119 happy_var_2)
_
= HappyAbsSyn18
(Just happy_var_2
)
happyReduction_34 _ _ = notHappyAtAll
happyReduce_35 = happySpecReduce_0 18 happyReduction_35
happyReduction_35 = HappyAbsSyn18
(Nothing
)
happyReduce_36 = happySpecReduce_1 19 happyReduction_36
happyReduction_36 (HappyAbsSyn20 happy_var_1)
= HappyAbsSyn19
(Just happy_var_1
)
happyReduction_36 _ = notHappyAtAll
happyReduce_37 = happySpecReduce_0 19 happyReduction_37
happyReduction_37 = HappyAbsSyn19
(Nothing
)
happyReduce_38 = happyReduce 4 20 happyReduction_38
happyReduction_38 (_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn21 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn20
((False, reverse happy_var_2)
) `HappyStk` happyRest
happyReduce_39 = happyReduce 5 20 happyReduction_39
happyReduction_39 (_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn21 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn20
((True, reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_40 = happySpecReduce_3 21 happyReduction_40
happyReduction_40 (HappyAbsSyn22 happy_var_3)
_
(HappyAbsSyn21 happy_var_1)
= HappyAbsSyn21
(happy_var_3 : happy_var_1
)
happyReduction_40 _ _ _ = notHappyAtAll
happyReduce_41 = happySpecReduce_1 21 happyReduction_41
happyReduction_41 (HappyAbsSyn22 happy_var_1)
= HappyAbsSyn21
([happy_var_1]
)
happyReduction_41 _ = notHappyAtAll
happyReduce_42 = happySpecReduce_1 22 happyReduction_42
happyReduction_42 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn22
(HsIVar happy_var_1
)
happyReduction_42 _ = notHappyAtAll
happyReduce_43 = happySpecReduce_1 22 happyReduction_43
happyReduction_43 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn22
(HsIAbs happy_var_1
)
happyReduction_43 _ = notHappyAtAll
happyReduce_44 = happyReduce 4 22 happyReduction_44
happyReduction_44 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn22
(HsIThingAll happy_var_1
) `HappyStk` happyRest
happyReduce_45 = happySpecReduce_3 22 happyReduction_45
happyReduction_45 _
_
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn22
(HsIThingWith happy_var_1 []
)
happyReduction_45 _ _ _ = notHappyAtAll
happyReduce_46 = happyReduce 4 22 happyReduction_46
happyReduction_46 (_ `HappyStk`
(HappyAbsSyn13 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn22
(HsIThingWith happy_var_1 (reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_47 = happySpecReduce_3 23 happyReduction_47
happyReduction_47 (HappyAbsSyn14 happy_var_3)
_
(HappyAbsSyn13 happy_var_1)
= HappyAbsSyn13
(happy_var_3 : happy_var_1
)
happyReduction_47 _ _ _ = notHappyAtAll
happyReduce_48 = happySpecReduce_1 23 happyReduction_48
happyReduction_48 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn13
([happy_var_1]
)
happyReduction_48 _ = notHappyAtAll
happyReduce_49 = happySpecReduce_1 24 happyReduction_49
happyReduction_49 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_49 _ = notHappyAtAll
happyReduce_50 = happySpecReduce_1 24 happyReduction_50
happyReduction_50 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_50 _ = notHappyAtAll
happyReduce_51 = happySpecReduce_3 25 happyReduction_51
happyReduction_51 (HappyAbsSyn26 happy_var_3)
_
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(funCons happy_var_3 happy_var_1
)
happyReduction_51 _ _ _ = notHappyAtAll
happyReduce_52 = happySpecReduce_1 25 happyReduction_52
happyReduction_52 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn25
([happy_var_1]
)
happyReduction_52 _ = notHappyAtAll
happyReduce_53 = happyReduce 4 26 happyReduction_53
happyReduction_53 ((HappyAbsSyn29 happy_var_4) `HappyStk`
(HappyAbsSyn27 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
(HappyAbsSyn28 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn26
(hsInfixDecl happy_var_2 (HsFixity happy_var_1 happy_var_3) happy_var_4
) `HappyStk` happyRest
happyReduce_54 = happySpecReduce_0 27 happyReduction_54
happyReduction_54 = HappyAbsSyn27
(9
)
happyReduce_55 = happySpecReduce_1 27 happyReduction_55
happyReduction_55 (HappyTerminal (IntTok happy_var_1))
= HappyAbsSyn27
(fromInteger (readInteger happy_var_1)
)
happyReduction_55 _ = notHappyAtAll
happyReduce_56 = happySpecReduce_1 28 happyReduction_56
happyReduction_56 _
= HappyAbsSyn28
(HsAssocNone
)
happyReduce_57 = happySpecReduce_1 28 happyReduction_57
happyReduction_57 _
= HappyAbsSyn28
(HsAssocLeft
)
happyReduce_58 = happySpecReduce_1 28 happyReduction_58
happyReduction_58 _
= HappyAbsSyn28
(HsAssocRight
)
happyReduce_59 = happySpecReduce_3 29 happyReduction_59
happyReduction_59 (HappyAbsSyn29 happy_var_3)
_
(HappyAbsSyn102 happy_var_1)
= HappyAbsSyn29
(happy_var_1 : happy_var_3
)
happyReduction_59 _ _ _ = notHappyAtAll
happyReduce_60 = happySpecReduce_1 29 happyReduction_60
happyReduction_60 (HappyAbsSyn102 happy_var_1)
= HappyAbsSyn29
([happy_var_1]
)
happyReduction_60 _ = notHappyAtAll
happyReduce_61 = happyReduce 5 30 happyReduction_61
happyReduction_61 ((HappyAbsSyn37 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn115 happy_var_3) `HappyStk`
(HappyAbsSyn42 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsTypeDecl happy_var_3 happy_var_2 happy_var_5
) `HappyStk` happyRest
happyReduce_62 = happyReduce 6 30 happyReduction_62
happyReduction_62 ((HappyAbsSyn13 happy_var_6) `HappyStk`
(HappyAbsSyn47 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn43 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsDataDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) (reverse happy_var_5) happy_var_6
) `HappyStk` happyRest
happyReduce_63 = happyReduce 6 30 happyReduction_63
happyReduction_63 ((HappyAbsSyn13 happy_var_6) `HappyStk`
(HappyAbsSyn48 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn43 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsNewTypeDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) happy_var_5 happy_var_6
) `HappyStk` happyRest
happyReduce_64 = happyReduce 4 30 happyReduction_64
happyReduction_64 ((HappyAbsSyn25 happy_var_4) `HappyStk`
(HappyAbsSyn41 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsClassDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) [] happy_var_4
) `HappyStk` happyRest
happyReduce_65 = happyReduce 4 30 happyReduction_65
happyReduction_65 ((HappyAbsSyn25 happy_var_4) `HappyStk`
(HappyAbsSyn41 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsInstDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) happy_var_4
) `HappyStk` happyRest
happyReduce_66 = happySpecReduce_3 30 happyReduction_66
happyReduction_66 (HappyAbsSyn37 happy_var_3)
(HappyAbsSyn115 happy_var_2)
_
= HappyAbsSyn26
(hsDefaultDecl happy_var_2 happy_var_3
)
happyReduction_66 _ _ _ = notHappyAtAll
happyReduce_67 = happySpecReduce_3 30 happyReduction_67
happyReduction_67 (HappyAbsSyn46 happy_var_3)
(HappyAbsSyn115 happy_var_2)
_
= HappyAbsSyn26
(hsPrimitiveTypeDecl happy_var_2 (fst happy_var_3) (snd happy_var_3)
)
happyReduction_67 _ _ _ = notHappyAtAll
happyReduce_68 = happyReduce 5 30 happyReduction_68
happyReduction_68 ((HappyAbsSyn37 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsPrimitiveBind happy_var_2 happy_var_3 happy_var_5
) `HappyStk` happyRest
happyReduce_69 = happySpecReduce_1 30 happyReduction_69
happyReduction_69 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_69 _ = notHappyAtAll
happyReduce_70 = happySpecReduce_2 31 happyReduction_70
happyReduction_70 _
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(reverse happy_var_1
)
happyReduction_70 _ _ = notHappyAtAll
happyReduce_71 = happySpecReduce_1 31 happyReduction_71
happyReduction_71 _
= HappyAbsSyn25
([]
)
happyReduce_72 = happySpecReduce_3 32 happyReduction_72
happyReduction_72 (HappyAbsSyn26 happy_var_3)
_
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(funCons happy_var_3 happy_var_1
)
happyReduction_72 _ _ _ = notHappyAtAll
happyReduce_73 = happySpecReduce_1 32 happyReduction_73
happyReduction_73 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn25
([happy_var_1]
)
happyReduction_73 _ = notHappyAtAll
happyReduce_74 = happySpecReduce_1 33 happyReduction_74
happyReduction_74 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_74 _ = notHappyAtAll
happyReduce_75 = happySpecReduce_1 33 happyReduction_75
happyReduction_75 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_75 _ = notHappyAtAll
happyReduce_76 = happySpecReduce_1 33 happyReduction_76
happyReduction_76 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_76 _ = notHappyAtAll
happyReduce_77 = happySpecReduce_1 33 happyReduction_77
happyReduction_77 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_77 _ = notHappyAtAll
happyReduce_78 = happyReduce 4 34 happyReduction_78
happyReduction_78 (_ `HappyStk`
(HappyAbsSyn25 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn25
(happy_var_3
) `HappyStk` happyRest
happyReduce_79 = happySpecReduce_3 34 happyReduction_79
happyReduction_79 _
(HappyAbsSyn25 happy_var_2)
_
= HappyAbsSyn25
(happy_var_2
)
happyReduction_79 _ _ _ = notHappyAtAll
happyReduce_80 = happyReduce 4 35 happyReduction_80
happyReduction_80 ((HappyAbsSyn41 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
(HappyAbsSyn13 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn26
(hsTypeSig happy_var_2 (reverse happy_var_1) (fst happy_var_4) (snd happy_var_4)
) `HappyStk` happyRest
happyReduce_81 = happySpecReduce_3 36 happyReduction_81
happyReduction_81 (HappyAbsSyn14 happy_var_3)
_
(HappyAbsSyn13 happy_var_1)
= HappyAbsSyn13
(happy_var_3 : happy_var_1
)
happyReduction_81 _ _ _ = notHappyAtAll
happyReduce_82 = happyMonadReduce 1 36 happyReduction_82
happyReduction_82 ((HappyAbsSyn14 happy_var_1) `HappyStk`
happyRest)
= happyThen ( case happy_var_1 of
Qual _ _ -> parseError "bad qvar in vars."
_ -> return [happy_var_1]
) (\r -> happyReturn (HappyAbsSyn13 r))
happyReduce_83 = happySpecReduce_3 37 happyReduction_83
happyReduction_83 (HappyAbsSyn37 happy_var_3)
_
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn37
(hsTyFun happy_var_1 happy_var_3
)
happyReduction_83 _ _ _ = notHappyAtAll
happyReduce_84 = happySpecReduce_1 37 happyReduction_84
happyReduction_84 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn37
(happy_var_1
)
happyReduction_84 _ = notHappyAtAll
happyReduce_85 = happySpecReduce_2 38 happyReduction_85
happyReduction_85 (HappyAbsSyn37 happy_var_2)
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn37
(hsTyApp happy_var_1 happy_var_2
)
happyReduction_85 _ _ = notHappyAtAll
happyReduce_86 = happySpecReduce_1 38 happyReduction_86
happyReduction_86 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn37
(happy_var_1
)
happyReduction_86 _ = notHappyAtAll
happyReduce_87 = happySpecReduce_1 39 happyReduction_87
happyReduction_87 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn37
(hsTyCon happy_var_1
)
happyReduction_87 _ = notHappyAtAll
happyReduce_88 = happySpecReduce_1 39 happyReduction_88
happyReduction_88 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn37
(hsTyVar happy_var_1
)
happyReduction_88 _ = notHappyAtAll
happyReduce_89 = happySpecReduce_3 39 happyReduction_89
happyReduction_89 _
(HappyAbsSyn42 happy_var_2)
_
= HappyAbsSyn37
(hsTyTuple (reverse happy_var_2)
)
happyReduction_89 _ _ _ = notHappyAtAll
happyReduce_90 = happySpecReduce_3 39 happyReduction_90
happyReduction_90 _
(HappyAbsSyn37 happy_var_2)
_
= HappyAbsSyn37
(hsTyApp list_tycon happy_var_2
)
happyReduction_90 _ _ _ = notHappyAtAll
happyReduce_91 = happySpecReduce_3 39 happyReduction_91
happyReduction_91 _
(HappyAbsSyn37 happy_var_2)
_
= HappyAbsSyn37
(happy_var_2
)
happyReduction_91 _ _ _ = notHappyAtAll
happyReduce_92 = happySpecReduce_1 40 happyReduction_92
happyReduction_92 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_92 _ = notHappyAtAll
happyReduce_93 = happySpecReduce_2 40 happyReduction_93
happyReduction_93 _
_
= HappyAbsSyn14
(unit_tycon_name
)
happyReduce_94 = happySpecReduce_2 40 happyReduction_94
happyReduction_94 _
_
= HappyAbsSyn14
(list_tycon_name
)
happyReduce_95 = happySpecReduce_3 40 happyReduction_95
happyReduction_95 _
_
_
= HappyAbsSyn14
(fun_tycon_name
)
happyReduce_96 = happySpecReduce_3 40 happyReduction_96
happyReduction_96 _
(HappyAbsSyn27 happy_var_2)
_
= HappyAbsSyn14
(tuple_tycon_name happy_var_2
)
happyReduction_96 _ _ _ = notHappyAtAll
happyReduce_97 = happyReduce 4 40 happyReduction_97
happyReduction_97 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyTerminal (QModId happy_var_1)) `HappyStk`
happyRest)
= HappyAbsSyn14
(qualify happy_var_1 "()"
) `HappyStk` happyRest
happyReduce_98 = happyReduce 4 40 happyReduction_98
happyReduction_98 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyTerminal (QModId happy_var_1)) `HappyStk`
happyRest)
= HappyAbsSyn14
(qualify happy_var_1 "[]"
) `HappyStk` happyRest
happyReduce_99 = happyReduce 5 40 happyReduction_99
happyReduction_99 (_ `HappyStk`
(HappyAbsSyn27 happy_var_4) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyTerminal (QModId happy_var_1)) `HappyStk`
happyRest)
= HappyAbsSyn14
(qualify happy_var_1 (tuple happy_var_4)
) `HappyStk` happyRest
happyReduce_100 = happySpecReduce_3 41 happyReduction_100
happyReduction_100 (HappyAbsSyn37 happy_var_3)
_
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn41
((reverse (tupleTypeToContext happy_var_1), happy_var_3)
)
happyReduction_100 _ _ _ = notHappyAtAll
happyReduce_101 = happySpecReduce_1 41 happyReduction_101
happyReduction_101 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn41
(([], happy_var_1)
)
happyReduction_101 _ = notHappyAtAll
happyReduce_102 = happySpecReduce_3 42 happyReduction_102
happyReduction_102 (HappyAbsSyn37 happy_var_3)
_
(HappyAbsSyn42 happy_var_1)
= HappyAbsSyn42
(happy_var_3 : happy_var_1
)
happyReduction_102 _ _ _ = notHappyAtAll
happyReduce_103 = happySpecReduce_3 42 happyReduction_103
happyReduction_103 (HappyAbsSyn37 happy_var_3)
_
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn42
([happy_var_3, happy_var_1]
)
happyReduction_103 _ _ _ = notHappyAtAll
happyReduce_104 = happySpecReduce_3 43 happyReduction_104
happyReduction_104 (HappyAbsSyn42 happy_var_3)
_
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn43
((reverse (tupleTypeToContext happy_var_1), happy_var_3)
)
happyReduction_104 _ _ _ = notHappyAtAll
happyReduce_105 = happySpecReduce_1 43 happyReduction_105
happyReduction_105 (HappyAbsSyn42 happy_var_1)
= HappyAbsSyn43
(([], happy_var_1)
)
happyReduction_105 _ = notHappyAtAll
happyReduce_106 = happySpecReduce_2 44 happyReduction_106
happyReduction_106 (HappyAbsSyn42 happy_var_2)
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn42
(hsTyCon happy_var_1 : (reverse happy_var_2)
)
happyReduction_106 _ _ = notHappyAtAll
happyReduce_107 = happySpecReduce_1 44 happyReduction_107
happyReduction_107 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn42
([hsTyCon happy_var_1]
)
happyReduction_107 _ = notHappyAtAll
happyReduce_108 = happySpecReduce_2 45 happyReduction_108
happyReduction_108 (HappyAbsSyn14 happy_var_2)
(HappyAbsSyn42 happy_var_1)
= HappyAbsSyn42
((hsTyVar happy_var_2) : happy_var_1
)
happyReduction_108 _ _ = notHappyAtAll
happyReduce_109 = happySpecReduce_1 45 happyReduction_109
happyReduction_109 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn42
([hsTyVar happy_var_1]
)
happyReduction_109 _ = notHappyAtAll
happyReduce_110 = happySpecReduce_3 46 happyReduction_110
happyReduction_110 (HappyAbsSyn14 happy_var_3)
_
(HappyAbsSyn37 happy_var_1)
= HappyAbsSyn46
((reverse (tupleTypeToContext happy_var_1), happy_var_3)
)
happyReduction_110 _ _ _ = notHappyAtAll
happyReduce_111 = happySpecReduce_1 46 happyReduction_111
happyReduction_111 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn46
(([], happy_var_1)
)
happyReduction_111 _ = notHappyAtAll
happyReduce_112 = happySpecReduce_3 47 happyReduction_112
happyReduction_112 (HappyAbsSyn48 happy_var_3)
_
(HappyAbsSyn47 happy_var_1)
= HappyAbsSyn47
(happy_var_3 : happy_var_1
)
happyReduction_112 _ _ _ = notHappyAtAll
happyReduce_113 = happySpecReduce_1 47 happyReduction_113
happyReduction_113 (HappyAbsSyn48 happy_var_1)
= HappyAbsSyn47
([happy_var_1]
)
happyReduction_113 _ = notHappyAtAll
happyReduce_114 = happySpecReduce_2 48 happyReduction_114
happyReduction_114 (HappyAbsSyn49 happy_var_2)
(HappyAbsSyn115 happy_var_1)
= HappyAbsSyn48
(HsConDecl happy_var_1 (fst happy_var_2) (snd happy_var_2)
)
happyReduction_114 _ _ = notHappyAtAll
happyReduce_115 = happyReduce 4 48 happyReduction_115
happyReduction_115 ((HappyAbsSyn51 happy_var_4) `HappyStk`
(HappyAbsSyn14 happy_var_3) `HappyStk`
(HappyAbsSyn51 happy_var_2) `HappyStk`
(HappyAbsSyn115 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn48
(HsConDecl happy_var_1 happy_var_3 [happy_var_2, happy_var_4]
) `HappyStk` happyRest
happyReduce_116 = happyReduce 6 48 happyReduction_116
happyReduction_116 (_ `HappyStk`
(HappyAbsSyn53 happy_var_5) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn14 happy_var_2) `HappyStk`
(HappyAbsSyn115 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn48
(HsRecDecl happy_var_1 happy_var_2 (reverse happy_var_5)
) `HappyStk` happyRest
happyReduce_117 = happyMonadReduce 1 49 happyReduction_117
happyReduction_117 ((HappyAbsSyn37 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { (c, ts) <- splitTyConApp happy_var_1 ;
return (c, map HsUnBangedType ts)
}
) (\r -> happyReturn (HappyAbsSyn49 r))
happyReduce_118 = happySpecReduce_1 49 happyReduction_118
happyReduction_118 (HappyAbsSyn49 happy_var_1)
= HappyAbsSyn49
(happy_var_1
)
happyReduction_118 _ = notHappyAtAll
happyReduce_119 = happyMonadReduce 3 50 happyReduction_119
happyReduction_119 ((HappyAbsSyn37 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn37 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { (c, ts) <- splitTyConApp happy_var_1 ;
return (c, map HsUnBangedType ts ++ [HsBangedType happy_var_3])
}
) (\r -> happyReturn (HappyAbsSyn49 r))
happyReduce_120 = happySpecReduce_2 50 happyReduction_120
happyReduction_120 (HappyAbsSyn51 happy_var_2)
(HappyAbsSyn49 happy_var_1)
= HappyAbsSyn49
((fst happy_var_1, snd happy_var_1 ++ [happy_var_2] )
)
happyReduction_120 _ _ = notHappyAtAll
happyReduce_121 = happySpecReduce_1 51 happyReduction_121
happyReduction_121 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn51
(HsUnBangedType happy_var_1
)
happyReduction_121 _ = notHappyAtAll
happyReduce_122 = happySpecReduce_2 51 happyReduction_122
happyReduction_122 (HappyAbsSyn37 happy_var_2)
_
= HappyAbsSyn51
(HsBangedType happy_var_2
)
happyReduction_122 _ _ = notHappyAtAll
happyReduce_123 = happySpecReduce_1 52 happyReduction_123
happyReduction_123 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn51
(HsUnBangedType happy_var_1
)
happyReduction_123 _ = notHappyAtAll
happyReduce_124 = happySpecReduce_2 52 happyReduction_124
happyReduction_124 (HappyAbsSyn37 happy_var_2)
_
= HappyAbsSyn51
(HsBangedType happy_var_2
)
happyReduction_124 _ _ = notHappyAtAll
happyReduce_125 = happySpecReduce_3 53 happyReduction_125
happyReduction_125 (HappyAbsSyn54 happy_var_3)
_
(HappyAbsSyn53 happy_var_1)
= HappyAbsSyn53
(happy_var_3 : happy_var_1
)
happyReduction_125 _ _ _ = notHappyAtAll
happyReduce_126 = happySpecReduce_1 53 happyReduction_126
happyReduction_126 (HappyAbsSyn54 happy_var_1)
= HappyAbsSyn53
([happy_var_1]
)
happyReduction_126 _ = notHappyAtAll
happyReduce_127 = happySpecReduce_3 54 happyReduction_127
happyReduction_127 (HappyAbsSyn51 happy_var_3)
_
(HappyAbsSyn13 happy_var_1)
= HappyAbsSyn54
((reverse happy_var_1, happy_var_3)
)
happyReduction_127 _ _ _ = notHappyAtAll
happyReduce_128 = happySpecReduce_1 55 happyReduction_128
happyReduction_128 (HappyAbsSyn37 happy_var_1)
= HappyAbsSyn51
(HsUnBangedType happy_var_1
)
happyReduction_128 _ = notHappyAtAll
happyReduce_129 = happySpecReduce_2 55 happyReduction_129
happyReduction_129 (HappyAbsSyn37 happy_var_2)
_
= HappyAbsSyn51
(HsBangedType happy_var_2
)
happyReduction_129 _ _ = notHappyAtAll
happyReduce_130 = happySpecReduce_0 56 happyReduction_130
happyReduction_130 = HappyAbsSyn13
([]
)
happyReduce_131 = happySpecReduce_2 56 happyReduction_131
happyReduction_131 (HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn13
([happy_var_2]
)
happyReduction_131 _ _ = notHappyAtAll
happyReduce_132 = happySpecReduce_3 56 happyReduction_132
happyReduction_132 _
_
_
= HappyAbsSyn13
([]
)
happyReduce_133 = happyReduce 4 56 happyReduction_133
happyReduction_133 (_ `HappyStk`
(HappyAbsSyn13 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn13
(reverse happy_var_3
) `HappyStk` happyRest
happyReduce_134 = happySpecReduce_3 57 happyReduction_134
happyReduction_134 (HappyAbsSyn14 happy_var_3)
_
(HappyAbsSyn13 happy_var_1)
= HappyAbsSyn13
(happy_var_3 : happy_var_1
)
happyReduction_134 _ _ _ = notHappyAtAll
happyReduce_135 = happySpecReduce_1 57 happyReduction_135
happyReduction_135 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn13
([happy_var_1]
)
happyReduction_135 _ = notHappyAtAll
happyReduce_136 = happyReduce 5 58 happyReduction_136
happyReduction_136 (_ `HappyStk`
(HappyAbsSyn25 happy_var_4) `HappyStk`
_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn25
(happy_var_4
) `HappyStk` happyRest
happyReduce_137 = happyReduce 4 58 happyReduction_137
happyReduction_137 (_ `HappyStk`
(HappyAbsSyn25 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn25
(happy_var_3
) `HappyStk` happyRest
happyReduce_138 = happySpecReduce_0 58 happyReduction_138
happyReduction_138 = HappyAbsSyn25
([]
)
happyReduce_139 = happyReduce 4 59 happyReduction_139
happyReduction_139 (_ `HappyStk`
(HappyAbsSyn25 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn25 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn25
(reverse happy_var_1 ++ reverse happy_var_3
) `HappyStk` happyRest
happyReduce_140 = happySpecReduce_2 59 happyReduction_140
happyReduction_140 _
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(reverse happy_var_1
)
happyReduction_140 _ _ = notHappyAtAll
happyReduce_141 = happySpecReduce_1 59 happyReduction_141
happyReduction_141 _
= HappyAbsSyn25
([]
)
happyReduce_142 = happySpecReduce_3 60 happyReduction_142
happyReduction_142 (HappyAbsSyn26 happy_var_3)
_
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(funCons happy_var_3 happy_var_1
)
happyReduction_142 _ _ _ = notHappyAtAll
happyReduce_143 = happySpecReduce_1 60 happyReduction_143
happyReduction_143 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn25
([happy_var_1]
)
happyReduction_143 _ = notHappyAtAll
happyReduce_144 = happySpecReduce_3 61 happyReduction_144
happyReduction_144 (HappyAbsSyn26 happy_var_3)
_
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(funCons happy_var_3 happy_var_1
)
happyReduction_144 _ _ _ = notHappyAtAll
happyReduce_145 = happySpecReduce_1 61 happyReduction_145
happyReduction_145 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn25
([happy_var_1]
)
happyReduction_145 _ = notHappyAtAll
happyReduce_146 = happyReduce 5 62 happyReduction_146
happyReduction_146 (_ `HappyStk`
(HappyAbsSyn25 happy_var_4) `HappyStk`
_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn25
(happy_var_4
) `HappyStk` happyRest
happyReduce_147 = happyReduce 4 62 happyReduction_147
happyReduction_147 (_ `HappyStk`
(HappyAbsSyn25 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn25
(happy_var_3
) `HappyStk` happyRest
happyReduce_148 = happySpecReduce_0 62 happyReduction_148
happyReduction_148 = HappyAbsSyn25
([]
)
happyReduce_149 = happySpecReduce_2 63 happyReduction_149
happyReduction_149 _
(HappyAbsSyn25 happy_var_1)
= HappyAbsSyn25
(reverse happy_var_1
)
happyReduction_149 _ _ = notHappyAtAll
happyReduce_150 = happySpecReduce_1 63 happyReduction_150
happyReduction_150 _
= HappyAbsSyn25
([]
)
happyReduce_151 = happyMonadReduce 4 64 happyReduction_151
happyReduction_151 ((HappyAbsSyn25 happy_var_4) `HappyStk`
(HappyAbsSyn66 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= happyThen ( if isPatternExp happy_var_1
then mkValDef happy_var_1 happy_var_2 happy_var_3 happy_var_4
else mkFunDef happy_var_1 happy_var_2 happy_var_3 happy_var_4
) (\r -> happyReturn (HappyAbsSyn26 r))
happyReduce_152 = happySpecReduce_2 65 happyReduction_152
happyReduction_152 (HappyAbsSyn25 happy_var_2)
_
= HappyAbsSyn25
(happy_var_2
)
happyReduction_152 _ _ = notHappyAtAll
happyReduce_153 = happySpecReduce_0 65 happyReduction_153
happyReduction_153 = HappyAbsSyn25
([]
)
happyReduce_154 = happySpecReduce_2 66 happyReduction_154
happyReduction_154 (HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn66
(HsBody happy_var_2
)
happyReduction_154 _ _ = notHappyAtAll
happyReduce_155 = happySpecReduce_1 66 happyReduction_155
happyReduction_155 (HappyAbsSyn67 happy_var_1)
= HappyAbsSyn66
(HsGuard (reverse happy_var_1)
)
happyReduction_155 _ = notHappyAtAll
happyReduce_156 = happySpecReduce_2 67 happyReduction_156
happyReduction_156 (HappyAbsSyn68 happy_var_2)
(HappyAbsSyn67 happy_var_1)
= HappyAbsSyn67
(happy_var_2 : happy_var_1
)
happyReduction_156 _ _ = notHappyAtAll
happyReduce_157 = happySpecReduce_1 67 happyReduction_157
happyReduction_157 (HappyAbsSyn68 happy_var_1)
= HappyAbsSyn67
([happy_var_1]
)
happyReduction_157 _ = notHappyAtAll
happyReduce_158 = happyReduce 5 68 happyReduction_158
happyReduction_158 ((HappyAbsSyn69 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn115 happy_var_3) `HappyStk`
(HappyAbsSyn69 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn68
((happy_var_3, happy_var_2, happy_var_5)
) `HappyStk` happyRest
happyReduce_159 = happyReduce 4 69 happyReduction_159
happyReduction_159 ((HappyAbsSyn41 happy_var_4) `HappyStk`
(HappyAbsSyn115 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn69
(hsExpTypeSig happy_var_3 happy_var_1 (fst happy_var_4) (snd happy_var_4)
) `HappyStk` happyRest
happyReduce_160 = happySpecReduce_1 69 happyReduction_160
happyReduction_160 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_160 _ = notHappyAtAll
happyReduce_161 = happySpecReduce_1 70 happyReduction_161
happyReduction_161 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_161 _ = notHappyAtAll
happyReduce_162 = happySpecReduce_3 70 happyReduction_162
happyReduction_162 (HappyAbsSyn69 happy_var_3)
(HappyAbsSyn102 happy_var_2)
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsInfixApp happy_var_1 happy_var_2 happy_var_3
)
happyReduction_162 _ _ _ = notHappyAtAll
happyReduce_163 = happyMonadReduce 4 71 happyReduction_163
happyReduction_163 ((HappyAbsSyn69 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn73 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= happyThen ( do { ps <- mapM expToPat happy_var_2 ;
return (hsLambda (reverse ps) happy_var_4)
}
) (\r -> happyReturn (HappyAbsSyn69 r))
happyReduce_164 = happyMonadReduce 4 71 happyReduction_164
happyReduction_164 ((HappyAbsSyn69 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn73 happy_var_2) `HappyStk`
(HappyAbsSyn126 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { ps <- mapM expToPat happy_var_2 ;
return (mkQuant happy_var_1 (reverse ps) happy_var_4)
}
) (\r -> happyReturn (HappyAbsSyn69 r))
happyReduce_165 = happyReduce 4 71 happyReduction_165
happyReduction_165 ((HappyAbsSyn69 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn25 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsLet happy_var_2 happy_var_4
) `HappyStk` happyRest
happyReduce_166 = happyReduce 6 71 happyReduction_166
happyReduction_166 ((HappyAbsSyn69 happy_var_6) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsIf happy_var_2 happy_var_4 happy_var_6
) `HappyStk` happyRest
happyReduce_167 = happyReduce 4 71 happyReduction_167
happyReduction_167 ((HappyAbsSyn82 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsCase happy_var_2 happy_var_4
) `HappyStk` happyRest
happyReduce_168 = happySpecReduce_2 71 happyReduction_168
happyReduction_168 (HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn69
(hsNegApp happy_var_2
)
happyReduction_168 _ _ = notHappyAtAll
happyReduce_169 = happySpecReduce_2 71 happyReduction_169
happyReduction_169 (HappyAbsSyn88 happy_var_2)
_
= HappyAbsSyn69
(hsDo (atoms2Stmt happy_var_2)
)
happyReduction_169 _ _ = notHappyAtAll
happyReduce_170 = happySpecReduce_1 71 happyReduction_170
happyReduction_170 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_170 _ = notHappyAtAll
happyReduce_171 = happySpecReduce_2 72 happyReduction_171
happyReduction_171 (HappyAbsSyn69 happy_var_2)
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsApp happy_var_1 happy_var_2
)
happyReduction_171 _ _ = notHappyAtAll
happyReduce_172 = happySpecReduce_1 72 happyReduction_172
happyReduction_172 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_172 _ = notHappyAtAll
happyReduce_173 = happySpecReduce_2 73 happyReduction_173
happyReduction_173 (HappyAbsSyn69 happy_var_2)
(HappyAbsSyn73 happy_var_1)
= HappyAbsSyn73
(happy_var_2 : happy_var_1
)
happyReduction_173 _ _ = notHappyAtAll
happyReduce_174 = happySpecReduce_1 73 happyReduction_174
happyReduction_174 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn73
([happy_var_1]
)
happyReduction_174 _ = notHappyAtAll
happyReduce_175 = happyReduce 5 74 happyReduction_175
happyReduction_175 (_ `HappyStk`
(HappyAbsSyn91 happy_var_4) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn69
(mkRecord happy_var_1 (reverse happy_var_4)
) `HappyStk` happyRest
happyReduce_176 = happySpecReduce_1 74 happyReduction_176
happyReduction_176 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_176 _ = notHappyAtAll
happyReduce_177 = happySpecReduce_1 75 happyReduction_177
happyReduction_177 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn69
(hsEVar (happy_var_1 :: HsName)
)
happyReduction_177 _ = notHappyAtAll
happyReduce_178 = happySpecReduce_1 75 happyReduction_178
happyReduction_178 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_178 _ = notHappyAtAll
happyReduce_179 = happySpecReduce_1 75 happyReduction_179
happyReduction_179 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(happy_var_1
)
happyReduction_179 _ = notHappyAtAll
happyReduce_180 = happySpecReduce_3 75 happyReduction_180
happyReduction_180 _
(HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn69
(hsParen happy_var_2
)
happyReduction_180 _ _ _ = notHappyAtAll
happyReduce_181 = happySpecReduce_3 75 happyReduction_181
happyReduction_181 _
(HappyAbsSyn73 happy_var_2)
_
= HappyAbsSyn69
(hsTuple (reverse happy_var_2)
)
happyReduction_181 _ _ _ = notHappyAtAll
happyReduce_182 = happySpecReduce_3 75 happyReduction_182
happyReduction_182 _
(HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn69
(happy_var_2
)
happyReduction_182 _ _ _ = notHappyAtAll
happyReduce_183 = happyReduce 4 75 happyReduction_183
happyReduction_183 (_ `HappyStk`
(HappyAbsSyn102 happy_var_3) `HappyStk`
(HappyAbsSyn69 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsLeftSection happy_var_2 happy_var_3
) `HappyStk` happyRest
happyReduce_184 = happyReduce 4 75 happyReduction_184
happyReduction_184 (_ `HappyStk`
(HappyAbsSyn69 happy_var_3) `HappyStk`
(HappyAbsSyn102 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsRightSection happy_var_2 happy_var_3
) `HappyStk` happyRest
happyReduce_185 = happySpecReduce_3 75 happyReduction_185
happyReduction_185 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn69
(hsAsPat happy_var_1 happy_var_3
)
happyReduction_185 _ _ _ = notHappyAtAll
happyReduce_186 = happySpecReduce_1 75 happyReduction_186
happyReduction_186 _
= HappyAbsSyn69
(hsWildCard
)
happyReduce_187 = happySpecReduce_2 75 happyReduction_187
happyReduction_187 (HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn69
(hsIrrPat happy_var_2
)
happyReduction_187 _ _ = notHappyAtAll
happyReduce_188 = happySpecReduce_2 76 happyReduction_188
happyReduction_188 _
(HappyAbsSyn27 happy_var_1)
= HappyAbsSyn27
(happy_var_1 + 1
)
happyReduction_188 _ _ = notHappyAtAll
happyReduce_189 = happySpecReduce_1 76 happyReduction_189
happyReduction_189 _
= HappyAbsSyn27
(1
)
happyReduce_190 = happySpecReduce_3 77 happyReduction_190
happyReduction_190 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn73 happy_var_1)
= HappyAbsSyn73
(happy_var_3 : happy_var_1
)
happyReduction_190 _ _ _ = notHappyAtAll
happyReduce_191 = happySpecReduce_3 77 happyReduction_191
happyReduction_191 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn73
([happy_var_3, happy_var_1]
)
happyReduction_191 _ _ _ = notHappyAtAll
happyReduce_192 = happySpecReduce_1 78 happyReduction_192
happyReduction_192 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsList [happy_var_1]
)
happyReduction_192 _ = notHappyAtAll
happyReduce_193 = happySpecReduce_1 78 happyReduction_193
happyReduction_193 (HappyAbsSyn73 happy_var_1)
= HappyAbsSyn69
(hsList (reverse happy_var_1)
)
happyReduction_193 _ = notHappyAtAll
happyReduce_194 = happySpecReduce_2 78 happyReduction_194
happyReduction_194 _
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsEnumFrom happy_var_1
)
happyReduction_194 _ _ = notHappyAtAll
happyReduce_195 = happyReduce 4 78 happyReduction_195
happyReduction_195 (_ `HappyStk`
(HappyAbsSyn69 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn69
(hsEnumFromThen happy_var_1 happy_var_3
) `HappyStk` happyRest
happyReduce_196 = happySpecReduce_3 78 happyReduction_196
happyReduction_196 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsEnumFromTo happy_var_1 happy_var_3
)
happyReduction_196 _ _ _ = notHappyAtAll
happyReduce_197 = happyReduce 5 78 happyReduction_197
happyReduction_197 ((HappyAbsSyn69 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn69
(hsEnumFromThenTo happy_var_1 happy_var_3 happy_var_5
) `HappyStk` happyRest
happyReduce_198 = happySpecReduce_3 78 happyReduction_198
happyReduction_198 (HappyAbsSyn80 happy_var_3)
_
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn69
(hsListComp (atoms2Stmt (reverse happy_var_3 ++ [HsQualifierAtom happy_var_1]))
)
happyReduction_198 _ _ _ = notHappyAtAll
happyReduce_199 = happySpecReduce_3 79 happyReduction_199
happyReduction_199 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn73 happy_var_1)
= HappyAbsSyn73
(happy_var_3 : happy_var_1
)
happyReduction_199 _ _ _ = notHappyAtAll
happyReduce_200 = happySpecReduce_3 79 happyReduction_200
happyReduction_200 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn69 happy_var_1)
= HappyAbsSyn73
([happy_var_3,happy_var_1]
)
happyReduction_200 _ _ _ = notHappyAtAll
happyReduce_201 = happySpecReduce_3 80 happyReduction_201
happyReduction_201 (HappyAbsSyn81 happy_var_3)
_
(HappyAbsSyn80 happy_var_1)
= HappyAbsSyn80
(happy_var_3 : happy_var_1
)
happyReduction_201 _ _ _ = notHappyAtAll
happyReduce_202 = happySpecReduce_1 80 happyReduction_202
happyReduction_202 (HappyAbsSyn81 happy_var_1)
= HappyAbsSyn80
([happy_var_1]
)
happyReduction_202 _ = notHappyAtAll
happyReduce_203 = happyMonadReduce 3 81 happyReduction_203
happyReduction_203 ((HappyAbsSyn69 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { p <- expToPat happy_var_1 ;
return (HsGeneratorAtom p happy_var_3)
}
) (\r -> happyReturn (HappyAbsSyn81 r))
happyReduce_204 = happySpecReduce_1 81 happyReduction_204
happyReduction_204 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn81
(HsQualifierAtom happy_var_1
)
happyReduction_204 _ = notHappyAtAll
happyReduce_205 = happySpecReduce_2 81 happyReduction_205
happyReduction_205 (HappyAbsSyn25 happy_var_2)
_
= HappyAbsSyn81
(HsLetStmtAtom happy_var_2
)
happyReduction_205 _ _ = notHappyAtAll
happyReduce_206 = happyReduce 5 82 happyReduction_206
happyReduction_206 (_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn82 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn82
(reverse happy_var_3
) `HappyStk` happyRest
happyReduce_207 = happyReduce 4 82 happyReduction_207
happyReduction_207 (_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn82 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn82
(reverse happy_var_2
) `HappyStk` happyRest
happyReduce_208 = happySpecReduce_3 83 happyReduction_208
happyReduction_208 (HappyAbsSyn84 happy_var_3)
_
(HappyAbsSyn82 happy_var_1)
= HappyAbsSyn82
(happy_var_3 : happy_var_1
)
happyReduction_208 _ _ _ = notHappyAtAll
happyReduce_209 = happySpecReduce_1 83 happyReduction_209
happyReduction_209 (HappyAbsSyn84 happy_var_1)
= HappyAbsSyn82
([happy_var_1]
)
happyReduction_209 _ = notHappyAtAll
happyReduce_210 = happyMonadReduce 3 84 happyReduction_210
happyReduction_210 ((HappyAbsSyn66 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { p <- expToPat happy_var_1 ;
return (HsAlt happy_var_2 p happy_var_3 [])
}
) (\r -> happyReturn (HappyAbsSyn84 r))
happyReduce_211 = happyMonadReduce 5 84 happyReduction_211
happyReduction_211 ((HappyAbsSyn25 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn66 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
(HappyAbsSyn69 happy_var_1) `HappyStk`
happyRest)
= happyThen ( do { p <- expToPat happy_var_1 ;
return (HsAlt happy_var_2 p happy_var_3 happy_var_5)
}
) (\r -> happyReturn (HappyAbsSyn84 r))
happyReduce_212 = happySpecReduce_2 85 happyReduction_212
happyReduction_212 (HappyAbsSyn69 happy_var_2)
_
= HappyAbsSyn66
(HsBody happy_var_2
)
happyReduction_212 _ _ = notHappyAtAll
happyReduce_213 = happySpecReduce_1 85 happyReduction_213
happyReduction_213 (HappyAbsSyn67 happy_var_1)
= HappyAbsSyn66
(HsGuard (reverse happy_var_1)
)
happyReduction_213 _ = notHappyAtAll
happyReduce_214 = happySpecReduce_2 86 happyReduction_214
happyReduction_214 (HappyAbsSyn68 happy_var_2)
(HappyAbsSyn67 happy_var_1)
= HappyAbsSyn67
(happy_var_2 : happy_var_1
)
happyReduction_214 _ _ = notHappyAtAll
happyReduce_215 = happySpecReduce_1 86 happyReduction_215
happyReduction_215 (HappyAbsSyn68 happy_var_1)
= HappyAbsSyn67
([happy_var_1]
)
happyReduction_215 _ = notHappyAtAll
happyReduce_216 = happyReduce 5 87 happyReduction_216
happyReduction_216 ((HappyAbsSyn69 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn69 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn68
((happy_var_2, happy_var_3, happy_var_5)
) `HappyStk` happyRest
happyReduce_217 = happyReduce 4 88 happyReduction_217
happyReduction_217 (_ `HappyStk`
(HappyAbsSyn88 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn88
(happy_var_3
) `HappyStk` happyRest
happyReduce_218 = happySpecReduce_3 88 happyReduction_218
happyReduction_218 _
(HappyAbsSyn88 happy_var_2)
_
= HappyAbsSyn88
(happy_var_2
)
happyReduction_218 _ _ _ = notHappyAtAll
happyReduce_219 = happySpecReduce_3 89 happyReduction_219
happyReduction_219 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn88 happy_var_1)
= HappyAbsSyn88
(reverse (HsQualifierAtom happy_var_3 : happy_var_1)
)
happyReduction_219 _ _ _ = notHappyAtAll
happyReduce_220 = happySpecReduce_1 89 happyReduction_220
happyReduction_220 (HappyAbsSyn69 happy_var_1)
= HappyAbsSyn88
([HsQualifierAtom happy_var_1]
)
happyReduction_220 _ = notHappyAtAll
happyReduce_221 = happySpecReduce_3 90 happyReduction_221
happyReduction_221 (HappyAbsSyn81 happy_var_3)
_
(HappyAbsSyn88 happy_var_1)
= HappyAbsSyn88
(happy_var_3 : happy_var_1
)
happyReduction_221 _ _ _ = notHappyAtAll
happyReduce_222 = happySpecReduce_1 90 happyReduction_222
happyReduction_222 (HappyAbsSyn81 happy_var_1)
= HappyAbsSyn88
([happy_var_1]
)
happyReduction_222 _ = notHappyAtAll
happyReduce_223 = happySpecReduce_3 91 happyReduction_223
happyReduction_223 (HappyAbsSyn92 happy_var_3)
_
(HappyAbsSyn91 happy_var_1)
= HappyAbsSyn91
(happy_var_3 : happy_var_1
)
happyReduction_223 _ _ _ = notHappyAtAll
happyReduce_224 = happySpecReduce_1 91 happyReduction_224
happyReduction_224 (HappyAbsSyn92 happy_var_1)
= HappyAbsSyn91
([happy_var_1]
)
happyReduction_224 _ = notHappyAtAll
happyReduce_225 = happySpecReduce_3 92 happyReduction_225
happyReduction_225 (HappyAbsSyn69 happy_var_3)
_
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn92
(HsFieldUpdate happy_var_1 (happy_var_3)
)
happyReduction_225 _ _ _ = notHappyAtAll
happyReduce_226 = happySpecReduce_2 93 happyReduction_226
happyReduction_226 _
_
= HappyAbsSyn69
(hsECon (qualify "Prelude" "()")
)
happyReduce_227 = happySpecReduce_2 93 happyReduction_227
happyReduction_227 _
_
= HappyAbsSyn69
(hsList []
)
happyReduce_228 = happySpecReduce_3 93 happyReduction_228
happyReduction_228 _
(HappyAbsSyn27 happy_var_2)
_
= HappyAbsSyn69
(hsECon (qualify "Prelude" (tuple happy_var_2))
)
happyReduction_228 _ _ _ = notHappyAtAll
happyReduce_229 = happyReduce 4 93 happyReduction_229
happyReduction_229 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyTerminal (QModId happy_var_1)) `HappyStk`
happyRest)
= HappyAbsSyn69
(hsECon (qualify happy_var_1 "()")
) `HappyStk` happyRest
happyReduce_230 = happyReduce 4 93 happyReduction_230
happyReduction_230 (_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn69
(hsList []
) `HappyStk` happyRest
happyReduce_231 = happyReduce 5 93 happyReduction_231
happyReduction_231 (_ `HappyStk`
(HappyAbsSyn27 happy_var_4) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyTerminal (QModId happy_var_1)) `HappyStk`
happyRest)
= HappyAbsSyn69
(hsECon (qualify happy_var_1 (tuple happy_var_4))
) `HappyStk` happyRest
happyReduce_232 = happySpecReduce_1 93 happyReduction_232
happyReduction_232 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn69
(hsECon happy_var_1
)
happyReduction_232 _ = notHappyAtAll
happyReduce_233 = happySpecReduce_1 94 happyReduction_233
happyReduction_233 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_233 _ = notHappyAtAll
happyReduce_234 = happySpecReduce_3 94 happyReduction_234
happyReduction_234 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_234 _ _ _ = notHappyAtAll
happyReduce_235 = happySpecReduce_1 95 happyReduction_235
happyReduction_235 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_235 _ = notHappyAtAll
happyReduce_236 = happySpecReduce_3 95 happyReduction_236
happyReduction_236 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_236 _ _ _ = notHappyAtAll
happyReduce_237 = happySpecReduce_1 96 happyReduction_237
happyReduction_237 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_237 _ = notHappyAtAll
happyReduce_238 = happySpecReduce_3 96 happyReduction_238
happyReduction_238 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_238 _ _ _ = notHappyAtAll
happyReduce_239 = happySpecReduce_1 97 happyReduction_239
happyReduction_239 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_239 _ = notHappyAtAll
happyReduce_240 = happySpecReduce_3 97 happyReduction_240
happyReduction_240 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_240 _ _ _ = notHappyAtAll
happyReduce_241 = happySpecReduce_1 98 happyReduction_241
happyReduction_241 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_241 _ = notHappyAtAll
happyReduce_242 = happySpecReduce_3 98 happyReduction_242
happyReduction_242 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_242 _ _ _ = notHappyAtAll
happyReduce_243 = happySpecReduce_1 99 happyReduction_243
happyReduction_243 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_243 _ = notHappyAtAll
happyReduce_244 = happySpecReduce_3 99 happyReduction_244
happyReduction_244 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_244 _ _ _ = notHappyAtAll
happyReduce_245 = happySpecReduce_1 100 happyReduction_245
happyReduction_245 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_245 _ = notHappyAtAll
happyReduce_246 = happySpecReduce_3 100 happyReduction_246
happyReduction_246 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_246 _ _ _ = notHappyAtAll
happyReduce_247 = happySpecReduce_1 101 happyReduction_247
happyReduction_247 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_247 _ = notHappyAtAll
happyReduce_248 = happySpecReduce_3 101 happyReduction_248
happyReduction_248 _
(HappyAbsSyn14 happy_var_2)
_
= HappyAbsSyn14
(happy_var_2
)
happyReduction_248 _ _ _ = notHappyAtAll
happyReduce_249 = happySpecReduce_1 102 happyReduction_249
happyReduction_249 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn102
(hsVar happy_var_1
)
happyReduction_249 _ = notHappyAtAll
happyReduce_250 = happySpecReduce_1 102 happyReduction_250
happyReduction_250 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn102
(hsCon happy_var_1
)
happyReduction_250 _ = notHappyAtAll
happyReduce_251 = happySpecReduce_1 103 happyReduction_251
happyReduction_251 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn102
(hsVar happy_var_1
)
happyReduction_251 _ = notHappyAtAll
happyReduce_252 = happySpecReduce_1 103 happyReduction_252
happyReduction_252 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn102
(hsCon happy_var_1
)
happyReduction_252 _ = notHappyAtAll
happyReduce_253 = happySpecReduce_1 104 happyReduction_253
happyReduction_253 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_253 _ = notHappyAtAll
happyReduce_254 = happySpecReduce_1 104 happyReduction_254
happyReduction_254 (HappyTerminal (QVarId happy_var_1))
= HappyAbsSyn14
(uncurry (Qual . Module) happy_var_1
)
happyReduction_254 _ = notHappyAtAll
happyReduce_255 = happySpecReduce_1 105 happyReduction_255
happyReduction_255 (HappyTerminal (VarId happy_var_1))
= HappyAbsSyn14
(UnQual happy_var_1
)
happyReduction_255 _ = notHappyAtAll
happyReduce_256 = happySpecReduce_1 105 happyReduction_256
happyReduction_256 _
= HappyAbsSyn14
(as_name
)
happyReduce_257 = happySpecReduce_1 105 happyReduction_257
happyReduction_257 _
= HappyAbsSyn14
(qualified_name
)
happyReduce_258 = happySpecReduce_1 105 happyReduction_258
happyReduction_258 _
= HappyAbsSyn14
(hiding_name
)
happyReduce_259 = happySpecReduce_1 106 happyReduction_259
happyReduction_259 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_259 _ = notHappyAtAll
happyReduce_260 = happySpecReduce_1 106 happyReduction_260
happyReduction_260 (HappyTerminal (QConId happy_var_1))
= HappyAbsSyn14
(uncurry (Qual . Module) happy_var_1
)
happyReduction_260 _ = notHappyAtAll
happyReduce_261 = happySpecReduce_1 107 happyReduction_261
happyReduction_261 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_261 _ = notHappyAtAll
happyReduce_262 = happySpecReduce_1 107 happyReduction_262
happyReduction_262 (HappyTerminal (QConId happy_var_1))
= HappyAbsSyn14
(uncurry (Qual . Module) happy_var_1
)
happyReduction_262 _ = notHappyAtAll
happyReduce_263 = happySpecReduce_1 108 happyReduction_263
happyReduction_263 (HappyTerminal (ConId happy_var_1))
= HappyAbsSyn14
(UnQual happy_var_1
)
happyReduction_263 _ = notHappyAtAll
happyReduce_264 = happySpecReduce_1 109 happyReduction_264
happyReduction_264 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_264 _ = notHappyAtAll
happyReduce_265 = happySpecReduce_1 109 happyReduction_265
happyReduction_265 (HappyTerminal (QConSym happy_var_1))
= HappyAbsSyn14
(uncurry (Qual . Module) happy_var_1
)
happyReduction_265 _ = notHappyAtAll
happyReduce_266 = happySpecReduce_1 110 happyReduction_266
happyReduction_266 (HappyTerminal (ConSym happy_var_1))
= HappyAbsSyn14
(UnQual happy_var_1
)
happyReduction_266 _ = notHappyAtAll
happyReduce_267 = happySpecReduce_1 111 happyReduction_267
happyReduction_267 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_267 _ = notHappyAtAll
happyReduce_268 = happySpecReduce_1 111 happyReduction_268
happyReduction_268 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_268 _ = notHappyAtAll
happyReduce_269 = happySpecReduce_1 112 happyReduction_269
happyReduction_269 (HappyTerminal (VarSym happy_var_1))
= HappyAbsSyn14
(UnQual happy_var_1
)
happyReduction_269 _ = notHappyAtAll
happyReduce_270 = happySpecReduce_1 112 happyReduction_270
happyReduction_270 _
= HappyAbsSyn14
(minus_name
)
happyReduce_271 = happySpecReduce_1 112 happyReduction_271
happyReduction_271 _
= HappyAbsSyn14
(pling_name
)
happyReduce_272 = happySpecReduce_1 112 happyReduction_272
happyReduction_272 _
= HappyAbsSyn14
(period_name
)
happyReduce_273 = happySpecReduce_1 113 happyReduction_273
happyReduction_273 (HappyTerminal (QVarSym happy_var_1))
= HappyAbsSyn14
(uncurry (Qual . Module) happy_var_1
)
happyReduction_273 _ = notHappyAtAll
happyReduce_274 = happySpecReduce_1 114 happyReduction_274
happyReduction_274 (HappyTerminal (IntTok happy_var_1))
= HappyAbsSyn69
(hsLit (HsInt (readInteger happy_var_1))
)
happyReduction_274 _ = notHappyAtAll
happyReduce_275 = happySpecReduce_1 114 happyReduction_275
happyReduction_275 (HappyTerminal (Character happy_var_1))
= HappyAbsSyn69
(hsLit (HsChar happy_var_1)
)
happyReduction_275 _ = notHappyAtAll
happyReduce_276 = happySpecReduce_1 114 happyReduction_276
happyReduction_276 (HappyTerminal (StringTok happy_var_1))
= HappyAbsSyn69
(hsLit (HsString happy_var_1)
)
happyReduction_276 _ = notHappyAtAll
happyReduce_277 = happySpecReduce_1 114 happyReduction_277
happyReduction_277 (HappyTerminal (FloatTok happy_var_1))
= HappyAbsSyn69
(hsLit (HsFrac (readRational happy_var_1))
)
happyReduction_277 _ = notHappyAtAll
happyReduce_278 = happyMonadReduce 0 115 happyReduction_278
happyReduction_278 (happyRest)
= happyThen ( getSrcLoc
) (\r -> happyReturn (HappyAbsSyn115 r))
happyReduce_279 = happySpecReduce_1 116 happyReduction_279
happyReduction_279 _
= HappyAbsSyn7
(()
)
happyReduce_280 = happyMonadReduce 1 116 happyReduction_280
happyReduction_280 (_ `HappyStk`
happyRest)
= happyThen ( popContext
) (\r -> happyReturn (HappyAbsSyn7 r))
happyReduce_281 = happyMonadReduce 0 117 happyReduction_281
happyReduction_281 (happyRest)
= happyThen ( pushContext NoLayout
) (\r -> happyReturn (HappyAbsSyn7 r))
happyReduce_282 = happyMonadReduce 0 118 happyReduction_282
happyReduction_282 (happyRest)
= happyThen ( do { SrcLoc _ _ c <- getSrcLoc ;
pushContext (Layout c)
}
) (\r -> happyReturn (HappyAbsSyn7 r))
happyReduce_283 = happySpecReduce_1 119 happyReduction_283
happyReduction_283 (HappyTerminal (ConId happy_var_1))
= HappyAbsSyn119
(Module happy_var_1
)
happyReduction_283 _ = notHappyAtAll
happyReduce_284 = happySpecReduce_1 120 happyReduction_284
happyReduction_284 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_284 _ = notHappyAtAll
happyReduce_285 = happySpecReduce_1 121 happyReduction_285
happyReduction_285 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_285 _ = notHappyAtAll
happyReduce_286 = happySpecReduce_1 122 happyReduction_286
happyReduction_286 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_286 _ = notHappyAtAll
happyReduce_287 = happySpecReduce_1 123 happyReduction_287
happyReduction_287 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_287 _ = notHappyAtAll
happyReduce_288 = happySpecReduce_1 124 happyReduction_288
happyReduction_288 (HappyAbsSyn14 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_288 _ = notHappyAtAll
happyReduce_289 = happyReduce 6 125 happyReduction_289
happyReduction_289 ((HappyAbsSyn69 happy_var_6) `HappyStk`
_ `HappyStk`
(HappyAbsSyn13 happy_var_4) `HappyStk`
(HappyAbsSyn14 happy_var_3) `HappyStk`
(HappyAbsSyn115 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn26
(hsProperty happy_var_2 happy_var_3 happy_var_4 happy_var_6
) `HappyStk` happyRest
happyReduce_290 = happySpecReduce_1 126 happyReduction_290
happyReduction_290 _
= HappyAbsSyn126
(hsPropForall
)
happyReduce_291 = happySpecReduce_1 126 happyReduction_291
happyReduction_291 _
= HappyAbsSyn126
(hsPropExists
)
happyReduce_292 = happySpecReduce_1 126 happyReduction_292
happyReduction_292 _
= HappyAbsSyn126
(hsPropForallDefined
)
happyReduce_293 = happySpecReduce_1 126 happyReduction_293
happyReduction_293 _
= HappyAbsSyn126
(hsPropExistsUnique
)
happyReduce_294 = happySpecReduce_2 127 happyReduction_294
happyReduction_294 (HappyAbsSyn13 happy_var_2)
(HappyAbsSyn14 happy_var_1)
= HappyAbsSyn13
(happy_var_1 : happy_var_2
)
happyReduction_294 _ _ = notHappyAtAll
happyReduce_295 = happySpecReduce_0 127 happyReduction_295
happyReduction_295 = HappyAbsSyn13
([]
)
happyNewToken action sts stk
= lexer(\tk ->
let cont i = action i i tk (HappyState action) sts stk in
case tk of {
EOF -> action 195 195 (error "reading EOF!") (HappyState action) sts stk;
VarId happy_dollar_dollar -> cont 128;
QVarId happy_dollar_dollar -> cont 129;
ConId happy_dollar_dollar -> cont 130;
QConId happy_dollar_dollar -> cont 131;
VarSym "-" -> cont 132;
VarSym happy_dollar_dollar -> cont 133;
ConSym happy_dollar_dollar -> cont 134;
QVarSym happy_dollar_dollar -> cont 135;
QConSym happy_dollar_dollar -> cont 136;
QModId happy_dollar_dollar -> cont 137;
IntTok happy_dollar_dollar -> cont 138;
FloatTok happy_dollar_dollar -> cont 139;
Character happy_dollar_dollar -> cont 140;
StringTok happy_dollar_dollar -> cont 141;
LeftParen -> cont 142;
RightParen -> cont 143;
SemiColon -> cont 144;
LeftCurly -> cont 145;
RightCurly -> cont 146;
VRightCurly -> cont 147;
LeftSquare -> cont 148;
RightSquare -> cont 149;
Comma -> cont 150;
Underscore -> cont 151;
BackQuote -> cont 152;
Period -> cont 153;
DotDot -> cont 154;
DoubleColon -> cont 155;
Equals -> cont 156;
Backslash -> cont 157;
Bar -> cont 158;
LeftArrow -> cont 159;
RightArrow -> cont 160;
At -> cont 161;
Tilde -> cont 162;
DoubleArrow -> cont 163;
Exclamation -> cont 164;
KW_As -> cont 165;
KW_Case -> cont 166;
KW_Class -> cont 167;
KW_Data -> cont 168;
KW_Default -> cont 169;
KW_Deriving -> cont 170;
KW_Do -> cont 171;
KW_Else -> cont 172;
KW_Hiding -> cont 173;
KW_If -> cont 174;
KW_Import -> cont 175;
KW_In -> cont 176;
KW_Infix -> cont 177;
KW_InfixL -> cont 178;
KW_InfixR -> cont 179;
KW_Instance -> cont 180;
KW_Let -> cont 181;
KW_Module -> cont 182;
KW_NewType -> cont 183;
KW_Of -> cont 184;
KW_Then -> cont 185;
KW_Type -> cont 186;
KW_Where -> cont 187;
KW_Qualified -> cont 188;
KW_Primitive -> cont 189;
KW_Property -> cont 190;
KW_QAll -> cont 191;
KW_QExists -> cont 192;
KW_QAllDef -> cont 193;
KW_QExistsU -> cont 194;
})
happyThen :: PM a -> (a -> PM b) -> PM b
happyThen = (thenPM)
happyReturn = (returnPM)
happyThen1 = happyThen
happyReturn1 = happyReturn
parse = happyThen (happyParse action_0) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll })
happyError = parseError "parse error"
{-# LINE 1 "GenericTemplate.hs" #-}
{-# LINE 1 "GenericTemplate.hs" #-}
-- $Id: PropParser.hs,v 1.10 2001/11/06 06:33:37 hallgren Exp $
{-# LINE 15 "GenericTemplate.hs" #-}
infixr 9 `HappyStk`
data HappyStk a = HappyStk a (HappyStk a)
-----------------------------------------------------------------------------
-- starting the parse
happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll
-----------------------------------------------------------------------------
-- Accepting the parse
happyAccept j tk st sts (HappyStk ans _) =
(happyReturn1 ans)
-----------------------------------------------------------------------------
-- Arrays only: do the next action
{-# LINE 138 "GenericTemplate.hs" #-}
-----------------------------------------------------------------------------
-- HappyState data type (not arrays)
newtype HappyState b c = HappyState
(Int -> -- token number
Int -> -- token number (yes, again)
b -> -- token semantic value
HappyState b c -> -- current state
[HappyState b c] -> -- state stack
c)
-----------------------------------------------------------------------------
-- Shifting a token
happyShift new_state (1) tk st sts stk@(x `HappyStk` _) =
let i = (case x of { HappyErrorToken (i) -> i }) in
-- trace "shifting the error token" $
new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk)
happyShift new_state i tk st sts stk =
happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk)
-- happyReduce is specialised for the common cases.
happySpecReduce_0 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk
= action nt j tk st ((st):(sts)) (fn `HappyStk` stk)
happySpecReduce_1 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk')
= action nt j tk st sts (fn v1 `HappyStk` stk')
happySpecReduce_2 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk')
= action nt j tk st sts (fn v1 v2 `HappyStk` stk')
happySpecReduce_3 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk')
= action nt j tk st sts (fn v1 v2 v3 `HappyStk` stk')
happyReduce k i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyReduce k nt fn j tk st sts stk = action nt j tk st1 sts1 (fn stk)
where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts))
happyMonadReduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonadReduce k nt fn j tk st sts stk =
happyThen1 (fn stk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk))
where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
happyDrop (0) l = l
happyDrop n ((_):(t)) = happyDrop (n - ((1) :: Int)) t
happyDropStk (0) l = l
happyDropStk n (x `HappyStk` xs) = happyDropStk (n - ((1)::Int)) xs
-----------------------------------------------------------------------------
-- Moving to a new state after a reduction
happyGoto action j tk st = action j j tk (HappyState action)
-----------------------------------------------------------------------------
-- Error recovery ((1) is the error token)
-- parse error if we are in recovery and we fail again
happyFail (1) tk old_st _ stk =
-- trace "failing" $
happyError
{- We don't need state discarding for our restricted implementation of
"error". In fact, it can cause some bogus parses, so I've disabled it
for now --SDM
-- discard a state
happyFail (1) tk old_st (((HappyState (action))):(sts))
(saved_tok `HappyStk` _ `HappyStk` stk) =
-- trace ("discarding state, depth " ++ show (length stk)) $
action (1) (1) tk (HappyState (action)) sts ((saved_tok`HappyStk`stk))
-}
-- Enter error recovery: generate an error token,
-- save the old token and carry on.
happyFail i tk (HappyState (action)) sts stk =
-- trace "entering error recovery" $
action (1) (1) tk (HappyState (action)) sts ( (HappyErrorToken (i)) `HappyStk` stk)
-- Internal happy errors:
notHappyAtAll = error "Internal Happy error\n"
-----------------------------------------------------------------------------
-- Hack to get the typechecker to accept our action functions
-----------------------------------------------------------------------------
-- Don't inline any functions from the template. GHC has a nasty habit
-- of deciding to inline happyGoto everywhere, which increases the size of
-- the generated parser quite a bit.
{-# NOINLINE happyShift #-}
{-# NOINLINE happySpecReduce_0 #-}
{-# NOINLINE happySpecReduce_1 #-}
{-# NOINLINE happySpecReduce_2 #-}
{-# NOINLINE happySpecReduce_3 #-}
{-# NOINLINE happyReduce #-}
{-# NOINLINE happyMonadReduce #-}
{-# NOINLINE happyGoto #-}
{-# NOINLINE happyFail #-}
-- end of Happy Template.
| forste/haReFork | tools/property/parse/extras/PropParser.hs | bsd-3-clause | 240,488 | 8,942 | 22 | 33,646 | 74,153 | 39,836 | 34,317 | 6,961 | 68 |
module Main where
import Test.Hspec
import SpecHelper
import Spec
main :: IO ()
main = resetDb >> hspec spec
| Drooids/postgrest | test/Main.hs | mit | 111 | 0 | 6 | 21 | 37 | 21 | 16 | 6 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Char
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- The Char type and associated operations.
--
-----------------------------------------------------------------------------
module Data.Char
(
Char
-- * Character classification
-- | Unicode characters are divided into letters, numbers, marks,
-- punctuation, symbols, separators (including spaces) and others
-- (including control characters).
, isControl, isSpace
, isLower, isUpper, isAlpha, isAlphaNum, isPrint
, isDigit, isOctDigit, isHexDigit
, isLetter, isMark, isNumber, isPunctuation, isSymbol, isSeparator
-- ** Subranges
, isAscii, isLatin1
, isAsciiUpper, isAsciiLower
-- ** Unicode general categories
, GeneralCategory(..), generalCategory
-- * Case conversion
, toUpper, toLower, toTitle
-- * Single digit characters
, digitToInt
, intToDigit
-- * Numeric representations
, ord
, chr
-- * String representations
, showLitChar
, lexLitChar
, readLitChar
) where
import GHC.Base
import GHC.Arr (Ix)
import GHC.Char
import GHC.Real (fromIntegral)
import GHC.Show
import GHC.Read (Read, readLitChar, lexLitChar)
import GHC.Unicode
import GHC.Num
import GHC.Enum
-- $setup
-- Allow the use of Prelude in doctests.
-- >>> import Prelude
-- | Convert a single digit 'Char' to the corresponding 'Int'. This
-- function fails unless its argument satisfies 'isHexDigit', but
-- recognises both upper- and lower-case hexadecimal digits (that
-- is, @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@).
--
-- ==== __Examples__
--
-- Characters @\'0\'@ through @\'9\'@ are converted properly to
-- @0..9@:
--
-- >>> map digitToInt ['0'..'9']
-- [0,1,2,3,4,5,6,7,8,9]
--
-- Both upper- and lower-case @\'A\'@ through @\'F\'@ are converted
-- as well, to @10..15@.
--
-- >>> map digitToInt ['a'..'f']
-- [10,11,12,13,14,15]
-- >>> map digitToInt ['A'..'F']
-- [10,11,12,13,14,15]
--
-- Anything else throws an exception:
--
-- >>> digitToInt 'G'
-- *** Exception: Char.digitToInt: not a digit 'G'
-- >>> digitToInt '♥'
-- *** Exception: Char.digitToInt: not a digit '\9829'
--
digitToInt :: Char -> Int
digitToInt c
| (fromIntegral dec::Word) <= 9 = dec
| (fromIntegral hexl::Word) <= 5 = hexl + 10
| (fromIntegral hexu::Word) <= 5 = hexu + 10
| otherwise = error ("Char.digitToInt: not a digit " ++ show c) -- sigh
where
dec = ord c - ord '0'
hexl = ord c - ord 'a'
hexu = ord c - ord 'A'
-- | Unicode General Categories (column 2 of the UnicodeData table) in
-- the order they are listed in the Unicode standard (the Unicode
-- Character Database, in particular).
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> :t OtherLetter
-- OtherLetter :: GeneralCategory
--
-- 'Eq' instance:
--
-- >>> UppercaseLetter == UppercaseLetter
-- True
-- >>> UppercaseLetter == LowercaseLetter
-- False
--
-- 'Ord' instance:
--
-- >>> NonSpacingMark <= MathSymbol
-- True
--
-- 'Enum' instance:
--
-- >>> enumFromTo ModifierLetter SpacingCombiningMark
-- [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]
--
-- 'Read' instance:
--
-- >>> read "DashPunctuation" :: GeneralCategory
-- DashPunctuation
-- >>> read "17" :: GeneralCategory
-- *** Exception: Prelude.read: no parse
--
-- 'Show' instance:
--
-- >>> show EnclosingMark
-- "EnclosingMark"
--
-- 'Bounded' instance:
--
-- >>> minBound :: GeneralCategory
-- UppercaseLetter
-- >>> maxBound :: GeneralCategory
-- NotAssigned
--
-- 'Ix' instance:
--
-- >>> import Data.Ix ( index )
-- >>> index (OtherLetter,Control) FinalQuote
-- 12
-- >>> index (OtherLetter,Control) Format
-- *** Exception: Error in array index
--
data GeneralCategory
= UppercaseLetter -- ^ Lu: Letter, Uppercase
| LowercaseLetter -- ^ Ll: Letter, Lowercase
| TitlecaseLetter -- ^ Lt: Letter, Titlecase
| ModifierLetter -- ^ Lm: Letter, Modifier
| OtherLetter -- ^ Lo: Letter, Other
| NonSpacingMark -- ^ Mn: Mark, Non-Spacing
| SpacingCombiningMark -- ^ Mc: Mark, Spacing Combining
| EnclosingMark -- ^ Me: Mark, Enclosing
| DecimalNumber -- ^ Nd: Number, Decimal
| LetterNumber -- ^ Nl: Number, Letter
| OtherNumber -- ^ No: Number, Other
| ConnectorPunctuation -- ^ Pc: Punctuation, Connector
| DashPunctuation -- ^ Pd: Punctuation, Dash
| OpenPunctuation -- ^ Ps: Punctuation, Open
| ClosePunctuation -- ^ Pe: Punctuation, Close
| InitialQuote -- ^ Pi: Punctuation, Initial quote
| FinalQuote -- ^ Pf: Punctuation, Final quote
| OtherPunctuation -- ^ Po: Punctuation, Other
| MathSymbol -- ^ Sm: Symbol, Math
| CurrencySymbol -- ^ Sc: Symbol, Currency
| ModifierSymbol -- ^ Sk: Symbol, Modifier
| OtherSymbol -- ^ So: Symbol, Other
| Space -- ^ Zs: Separator, Space
| LineSeparator -- ^ Zl: Separator, Line
| ParagraphSeparator -- ^ Zp: Separator, Paragraph
| Control -- ^ Cc: Other, Control
| Format -- ^ Cf: Other, Format
| Surrogate -- ^ Cs: Other, Surrogate
| PrivateUse -- ^ Co: Other, Private Use
| NotAssigned -- ^ Cn: Other, Not Assigned
deriving (Eq, Ord, Enum, Read, Show, Bounded, Ix)
-- | The Unicode general category of the character. This relies on the
-- 'Enum' instance of 'GeneralCategory', which must remain in the
-- same order as the categories are presented in the Unicode
-- standard.
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> generalCategory 'a'
-- LowercaseLetter
-- >>> generalCategory 'A'
-- UppercaseLetter
-- >>> generalCategory '0'
-- DecimalNumber
-- >>> generalCategory '%'
-- OtherPunctuation
-- >>> generalCategory '♥'
-- OtherSymbol
-- >>> generalCategory '\31'
-- Control
-- >>> generalCategory ' '
-- Space
--
generalCategory :: Char -> GeneralCategory
generalCategory c = toEnum $ fromIntegral $ wgencat $ fromIntegral $ ord c
-- derived character classifiers
-- | Selects alphabetic Unicode characters (lower-case, upper-case and
-- title-case letters, plus letters of caseless scripts and
-- modifiers letters). This function is equivalent to
-- 'Data.Char.isAlpha'.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'UppercaseLetter'
-- * 'LowercaseLetter'
-- * 'TitlecaseLetter'
-- * 'ModifierLetter'
-- * 'OtherLetter'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Letter\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isLetter 'a'
-- True
-- >>> isLetter 'A'
-- True
-- >>> isLetter '0'
-- False
-- >>> isLetter '%'
-- False
-- >>> isLetter '♥'
-- False
-- >>> isLetter '\31'
-- False
--
-- Ensure that 'isLetter' and 'isAlpha' are equivalent.
--
-- >>> let chars = [(chr 0)..]
-- >>> let letters = map isLetter chars
-- >>> let alphas = map isAlpha chars
-- >>> letters == alphas
-- True
--
isLetter :: Char -> Bool
isLetter c = case generalCategory c of
UppercaseLetter -> True
LowercaseLetter -> True
TitlecaseLetter -> True
ModifierLetter -> True
OtherLetter -> True
_ -> False
-- | Selects Unicode mark characters, for example accents and the
-- like, which combine with preceding characters.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'NonSpacingMark'
-- * 'SpacingCombiningMark'
-- * 'EnclosingMark'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Mark\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isMark 'a'
-- False
-- >>> isMark '0'
-- False
--
-- Combining marks such as accent characters usually need to follow
-- another character before they become printable:
--
-- >>> map isMark "ò"
-- [False,True]
--
-- Puns are not necessarily supported:
--
-- >>> isMark '✓'
-- False
--
isMark :: Char -> Bool
isMark c = case generalCategory c of
NonSpacingMark -> True
SpacingCombiningMark -> True
EnclosingMark -> True
_ -> False
-- | Selects Unicode numeric characters, including digits from various
-- scripts, Roman numerals, et cetera.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'DecimalNumber'
-- * 'LetterNumber'
-- * 'OtherNumber'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Number\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isNumber 'a'
-- False
-- >>> isNumber '%'
-- False
-- >>> isNumber '3'
-- True
--
-- ASCII @\'0\'@ through @\'9\'@ are all numbers:
--
-- >>> and $ map isNumber ['0'..'9']
-- True
--
-- Unicode Roman numerals are \"numbers\" as well:
--
-- >>> isNumber 'Ⅸ'
-- True
--
isNumber :: Char -> Bool
isNumber c = case generalCategory c of
DecimalNumber -> True
LetterNumber -> True
OtherNumber -> True
_ -> False
-- | Selects Unicode punctuation characters, including various kinds
-- of connectors, brackets and quotes.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'ConnectorPunctuation'
-- * 'DashPunctuation'
-- * 'OpenPunctuation'
-- * 'ClosePunctuation'
-- * 'InitialQuote'
-- * 'FinalQuote'
-- * 'OtherPunctuation'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Punctuation\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isPunctuation 'a'
-- False
-- >>> isPunctuation '7'
-- False
-- >>> isPunctuation '♥'
-- False
-- >>> isPunctuation '"'
-- True
-- >>> isPunctuation '?'
-- True
-- >>> isPunctuation '—'
-- True
--
isPunctuation :: Char -> Bool
isPunctuation c = case generalCategory c of
ConnectorPunctuation -> True
DashPunctuation -> True
OpenPunctuation -> True
ClosePunctuation -> True
InitialQuote -> True
FinalQuote -> True
OtherPunctuation -> True
_ -> False
-- | Selects Unicode symbol characters, including mathematical and
-- currency symbols.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'MathSymbol'
-- * 'CurrencySymbol'
-- * 'ModifierSymbol'
-- * 'OtherSymbol'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Symbol\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isSymbol 'a'
-- False
-- >>> isSymbol '6'
-- False
-- >>> isSymbol '='
-- True
--
-- The definition of \"math symbol\" may be a little
-- counter-intuitive depending on one's background:
--
-- >>> isSymbol '+'
-- True
-- >>> isSymbol '-'
-- False
--
isSymbol :: Char -> Bool
isSymbol c = case generalCategory c of
MathSymbol -> True
CurrencySymbol -> True
ModifierSymbol -> True
OtherSymbol -> True
_ -> False
-- | Selects Unicode space and separator characters.
--
-- This function returns 'True' if its argument has one of the
-- following 'GeneralCategory's, or 'False' otherwise:
--
-- * 'Space'
-- * 'LineSeparator'
-- * 'ParagraphSeparator'
--
-- These classes are defined in the
-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,
-- part of the Unicode standard. The same document defines what is
-- and is not a \"Separator\".
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isSeparator 'a'
-- False
-- >>> isSeparator '6'
-- False
-- >>> isSeparator ' '
-- True
--
-- Warning: newlines and tab characters are not considered
-- separators.
--
-- >>> isSeparator '\n'
-- False
-- >>> isSeparator '\t'
-- False
--
-- But some more exotic characters are (like HTML's @ @):
--
-- >>> isSeparator '\160'
-- True
--
isSeparator :: Char -> Bool
isSeparator c = case generalCategory c of
Space -> True
LineSeparator -> True
ParagraphSeparator -> True
_ -> False
| beni55/haste-compiler | libraries/ghc-7.10/base/Data/Char.hs | bsd-3-clause | 13,652 | 0 | 10 | 3,221 | 1,216 | 842 | 374 | 115 | 8 |
{-# LANGUAGE TemplateHaskell, GADTs #-}
module T4188 where
import Language.Haskell.TH
import System.IO
class C a where {}
data T1 a where
MkT1 :: a -> b -> T1 a
data T2 a where
MkT2 :: (C a, C b) => a -> b -> T2 a
data T3 x where
MkT3 :: (C x, C y) => x -> y -> T3 (x,y)
$(do { dec1 <- reify ''T1
; runIO (putStrLn (pprint dec1))
; dec2 <- reify ''T2
; runIO (putStrLn (pprint dec2))
; dec3 <- reify ''T3
; runIO (putStrLn (pprint dec3))
; runIO (hFlush stdout)
; return [] })
| oldmanmike/ghc | testsuite/tests/th/T4188.hs | bsd-3-clause | 525 | 0 | 13 | 150 | 252 | 132 | 120 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.