code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE BangPatterns, GADTs, DeriveDataTypeable, StandaloneDeriving #-}
module Data.OrgMode.Text (
LineNumber(..), toNumber, TextLine(..), isNumber, TextLineSource(..),
normalizeInputText, lineAdd, linesStartingFrom, hasNumber, makeDrawerLines,
wrapLine, prefixLine, tlPrint, tlFormat, wrapStringVarLines
) where
import Data.List (intercalate)
import Data.Monoid
import Data.Typeable
import Data.Generics (Generic(..))
import Data.Char (isSpace, toUpper, isPrint)
import Text.Printf
import System.IO
-- | Line numbers, where we can have an unattached root.
type LineNumber = Maybe Int
lineAdd Nothing _ = Nothing
lineAdd _ Nothing = Nothing
lineAdd (Just a) (Just b) = Just (a+b)
toNumber :: Int -> LineNumber -> Int
toNumber n Nothing = n
toNumber _ (Just a) = a
isNumber :: LineNumber -> Bool
isNumber Nothing = False
isNumber (Just _) = True
linesStartingFrom :: LineNumber -> [LineNumber]
linesStartingFrom Nothing = repeat Nothing
linesStartingFrom (Just l) = map Just [l..]
-- | Raw data about each line of text. Lines with 'tlLineNum == None'
-- are generated and don't exist within the Org file (yet).
data TextLine = TextLine
{ tlIndent :: Int
-- ^how long of a whitespace (or asterisk, for 'Node') prefix is in tlText?
, tlText :: String
, tlLineNum :: LineNumber
} deriving (Eq, Typeable)
hasNumber :: TextLine -> Bool
hasNumber (TextLine _ _ (Just _)) = True
hasNumber _ = False
formatLine tl =
(printf "[%3d] " (tlIndent tl)) ++
(printf "%-8s" $ (show $ tlLineNum tl)) ++ "|" ++ (tlText tl)
instance Show TextLine where
show tl = "<" ++ (formatLine tl) ++ ">"
instance Ord TextLine where
compare a b = compare (tlLineNum a) (tlLineNum b)
-- | Implements an API for getting text lines. Useful for Org file
-- generation or mutation.
class TextLineSource s where
getTextLines :: s -> [TextLine]
-- | Normalizes out newlines to UNIX format. CR -> LF, CRLF -> LF
normalizeInputText :: String -> String
normalizeInputText text =
-- Operators that work on reversed strings.
let swapCrLf :: String -> Char -> String
swapCrLf ('\r':cs) '\n' = '\n':cs
swapCrLf ('\n':cs) '\r' = '\n':cs
swapCrLf cs c = c:cs
-- A good place for fixing unprintable chars, but we have to
-- identify them.
swapCr :: String -> Char -> String
swapCr cs '\r' = '\n':cs
swapCr cs c = c:cs
revStr = reverse text
swappedCrLf = foldl swapCrLf "" revStr
swappedCr = foldl swapCr "" swappedCrLf
in reverse swappedCr
trimEndOfLine :: String -> String
trimEndOfLine f = reverse $ dropWhile isSpace $ reverse f
wrapStringVarLines :: [Int] -> String -> String
wrapStringVarLines _ [] = []
wrapStringVarLines lens str
| length str < (head lens) = str
| otherwise =
let first_word = takeWhile (not . isSpace) str
len = head lens
is_first_too_long = length first_word >= len
wrapped_back =
if is_first_too_long
then first_word
else reverse $ dropWhile (not . isSpace) $ reverse $ take len str
remain = drop (length wrapped_back) str
in if length wrapped_back > 0 || length remain > 0
then wrapped_back ++ "\n" ++ wrapStringVarLines (drop 1 lens) remain
else ""
wrapString :: Int -> String -> String
wrapString len str = wrapStringVarLines (repeat len) str
wrapLine :: Int -> TextLine -> [TextLine]
wrapLine width (TextLine indent string linenum) =
let desired_len = width - indent
strings = concatMap lines $ map (wrapString desired_len) $ lines string
line_nrs = linesStartingFrom linenum
makeTextLine (str, nr) = TextLine indent (trimEndOfLine str) nr
in map makeTextLine $ zip strings line_nrs
prefixLine :: String -> TextLine -> TextLine
prefixLine pfx (TextLine indent string linenum) =
let new_str = pfx ++ string
new_indent = length $ takeWhile isSpace new_str
in TextLine new_indent new_str linenum
makeDrawerLines :: LineNumber -> Int -> String -> [(String, String)] -> [TextLine]
makeDrawerLines fstLine depth name props =
let !indent = take depth $ repeat ' '
headline =
TextLine depth (indent ++ ":" ++ (map toUpper name) ++ ":") fstLine
mAdd (Just x) y = Just (x + y)
mAdd Nothing y = Nothing
lastline =
TextLine depth (indent ++ ":END:") (lineAdd fstLine $ Just (length props + 1))
makePropLine ((prop, value), nr) =
TextLine depth (indent ++ ":" ++ prop ++ ": " ++ value) (lineAdd fstLine $ Just nr)
proplines = map makePropLine $ zip props [1..]
in (headline:(proplines)) ++ [lastline]
tlFormat :: (TextLineSource s) => s -> String
tlFormat s =
let lines = getTextLines s
in intercalate "\n" $ map formatLine lines
tlPrint :: (TextLineSource s) => s -> IO ()
tlPrint s = putStrLn $ tlFormat s
| lally/orgmode | src/Data/OrgMode/Text.hs | bsd-3-clause | 4,866 | 0 | 16 | 1,113 | 1,549 | 806 | 743 | 106 | 4 |
module Main where
main :: IO ()
main = do
print "Hello org-monad!"
| bonnefoa/org-monad | prog/Main.hs | bsd-3-clause | 71 | 0 | 7 | 17 | 25 | 13 | 12 | 4 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-- |
module Network.Libtorrent.Types where
import Data.Aeson
import Data.Bits (setBit, testBit)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as BS16
import qualified Data.ByteString.Char8 as BSC
import Data.Function ((&))
import Data.List (foldl')
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import Foreign.ForeignPtr (ForeignPtr)
import Foreign.Ptr (Ptr)
import GHC.Exts (IsList (..), fromList, toList)
import GHC.Generics (Generic)
class Inlinable a where
type CType a :: *
class FromPtr a where
fromPtr :: IO (Ptr (CType a)) -> IO a
class ToPtr a where
toPtr :: a -> IO (Ptr (CType a))
class WithPtr a where
withPtr :: a -> (Ptr (CType a) -> IO b) -> IO b
-- | Represent list of 'Enum' as bits in 'Int'
newtype BitFlags a = BitFlags { unBitFlags :: Set a }
deriving (Foldable, Generic)
deriving instance Eq a => Eq (BitFlags a)
deriving instance Ord a => Monoid (BitFlags a)
deriving instance (Read a, Ord a) => Read (BitFlags a)
instance Show a => Show (BitFlags a) where
show (BitFlags as) = "BitFlags " ++ (show $ Set.toList as)
instance Ord a => IsList (BitFlags a) where
type Item (BitFlags a) = a
fromList = BitFlags .Set.fromList
toList (BitFlags as) = Set.toList as
instance (Enum a, Ord a, Bounded a) => Enum (BitFlags a) where
toEnum i =
BitFlags . Set.fromList $ filter (testBit i . fromEnum) [minBound..]
fromEnum (BitFlags as) =
foldl' (\i a -> setBit i (fromEnum a)) 0 as
instance (Ord a, ToJSON a) => ToJSON (BitFlags a) where
toJSON (BitFlags as) = toJSON $ toList as
instance (Ord a, FromJSON a) => FromJSON (BitFlags a) where
parseJSON v =
BitFlags . fromList <$> parseJSON v
-- | Type to represent std::vector
newtype StdVector e = StdVector { unStdVector :: ForeignPtr (CType (StdVector e))}
-- | Type to represent std::dequeue
newtype StdDeque e = StdDeque { unStdDeque :: ForeignPtr (CType (StdDeque e))}
-- | 20-bytes torrent infohash
newtype InfoHash = InfoHash { unInfoHash :: ByteString }
deriving (Eq, Ord)
instance Show InfoHash where
show (InfoHash ih) = "InfoHash " ++ (BSC.unpack $ BS16.encode ih)
instance ToJSON InfoHash where
toJSON = toJSON . infoHashToText
instance FromJSON InfoHash where
parseJSON = withText "InfoHash" $ \txt ->
maybe mempty pure . newInfoHash $ TE.encodeUtf8 txt
-- | Create 'InfoHash' from byte string or hex-encoded byte string
newInfoHash :: ByteString -> Maybe InfoHash
newInfoHash bs
| BS.length bs == 20 = Just $ InfoHash bs
| BS.length bs == 40 = BS16.decode bs & \case
(ih, "") -> Just $ InfoHash ih
_ -> Nothing
| otherwise =
Nothing
-- | Unpack 'InfoHash' to 'ByteString'
infoHashToByteString :: InfoHash -> ByteString
infoHashToByteString = unInfoHash
-- | Unpack 'InfoHash' to hex-encoded 'Text'
infoHashToText :: InfoHash -> Text
infoHashToText =
TE.decodeUtf8 . BS16.encode . unInfoHash
| eryx67/haskell-libtorrent | src/Network/Libtorrent/Types.hs | bsd-3-clause | 3,535 | 1 | 13 | 915 | 1,068 | 575 | 493 | 76 | 2 |
-- |
module Yesod.Content.PDFSpec (main, spec) where
import Test.Hspec
import Yesod.Content.PDF
import Data.ByteString.UTF8 (toString)
import Text.Blaze.Html
main :: IO ()
main = hspec spec
h :: Html
h = toHtml ("<html><body>Hello World</body></html>" :: String)
spec :: Spec
spec = do
describe "generate PDF from HTML document" $ do
it "should generate PDF from html document" $ do
(fmap ((take 8) . toString . pdfBytes) (html2PDF def h)) `shouldReturn` ("%PDF-1.4" :: String)
| alexkyllo/yesod-content-pdf | test/Yesod/Content/PDFSpec.hs | bsd-3-clause | 495 | 0 | 20 | 88 | 159 | 89 | 70 | 14 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DataKinds #-}
-- expermenting with home made overloaded record fields
-- cf sdiehl, wiwinwlh
-- but maybe
-- http://statusfailed.com/blog/2013/02/19/overloading-record-fields-with-lens.html
-- would be better?
-- {-# LANGUAGE DataKinds #-}
-- {-# LANGUAGE KindSignatures #-}
-- {-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-matches #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides Pire's syntax for modules,
-- ie. Pire's flavour of Pi-forall syntax
-- going back to the orig record syntax, albeit w/ lenses,
-- first stab, experimental
module Pire.Syntax.Modules where
#ifdef MIN_VERSION_GLASGOW_HASKELL
#if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0)
-- ghc >= 7.10.3
#else
-- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined
#endif
#else
-- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x)
import Data.Foldable
import Data.Traversable
#endif
import Pire.Syntax.Ws
import Pire.Syntax.Token
import Pire.Syntax.Nm
import Pire.Syntax.Decl
import Pire.Syntax.ConstructorNames
import Control.Lens
-- import Control.Lens.TH (makeLenses)
-- import GHC.TypeLits
data ModuleImport t =
ModuleImport t
| ModuleImport_ {
_importtok :: Token 'ImportTokTy t
, _importnm :: Nm1 t
}
-- deriving (Show,Eq, Ord, Read, Functor, Foldable, Traversable)
deriving (Show,Eq, Ord, Functor, Foldable, Traversable)
-- usage eg
-- mm ^. decls
-- mm' ^. decl'
-- -- newtype Field (n :: Symbol) v = Field { unField :: v }
-- -- deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
data Module t a =
Module {
-- module name
_mnm' :: Nm1 t
, _imports' :: [ModuleImport t]
, _decls' :: [Decl t a]
-- , _decls :: Field "decls" [Decl t a]
, _constrs' :: ConstructorNames t
}
| Module_ {
_leadingws :: Ws t
, _mtok :: Token 'ModuleTokTy t
, _mnm :: Nm1 t
, _wheretok :: Token 'WhereTy t
, _imports :: [ModuleImport t]
, _decls :: [Decl t a]
-- , _decls :: Field "decls" [Decl t a]
, _constrs :: ConstructorNames t
}
deriving (Eq,Ord,Show,Functor,Foldable,Traversable)
makeLenses ''Module
makeLenses ''ModuleImport
| reuleaux/pire | src/Pire/Syntax/Modules.hs | bsd-3-clause | 2,739 | 0 | 10 | 679 | 334 | 208 | 126 | 40 | 0 |
{-# LANGUAGE StrictData #-}
{-# LANGUAGE Trustworthy #-}
module Network.Tox.NodeInfo.SocketAddressSpec where
import Test.Hspec
import Data.Proxy (Proxy (..))
import Network.Tox.EncodingSpec
import Network.Tox.NodeInfo.SocketAddress (SocketAddress)
import qualified Network.Tox.NodeInfo.SocketAddress as SocketAddress
spec :: Spec
spec = do
rpcSpec (Proxy :: Proxy SocketAddress)
binarySpec (Proxy :: Proxy SocketAddress)
readShowSpec (Proxy :: Proxy SocketAddress)
binaryGetPutSpec "{get,put}SocketAddress"
SocketAddress.getSocketAddress
(uncurry SocketAddress.putSocketAddress)
| iphydf/hs-toxcore | test/Network/Tox/NodeInfo/SocketAddressSpec.hs | gpl-3.0 | 665 | 0 | 10 | 139 | 132 | 76 | 56 | 16 | 1 |
{-
(c) The AQUA Project, Glasgow University, 1994-1998
\section[ErrsUtils]{Utilities for error reporting}
-}
{-# LANGUAGE CPP #-}
module ETA.Main.ErrUtils (
MsgDoc,
Validity(..), andValid, allValid, isValid, getInvalids,
ErrMsg, WarnMsg, Severity(..),
Messages, ErrorMessages, WarningMessages,
errMsgSpan, errMsgContext, errMsgShortDoc, errMsgExtraInfo,
mkLocMessage, pprMessageBag, pprErrMsgBag, pprErrMsgBagWithLoc,
pprLocErrMsg, makeIntoWarning, isWarning,
errorsFound, emptyMessages, isEmptyMessages,
mkErrMsg, mkPlainErrMsg, mkLongErrMsg, mkWarnMsg, mkPlainWarnMsg,
printBagOfErrors,
warnIsErrorMsg, mkLongWarnMsg,
ghcExit,
doIfSet, doIfSet_dyn,
dumpIfSet, dumpIfSet_dyn, dumpIfSet_dyn_printer,
mkDumpDoc, dumpSDoc,
-- * Messages during compilation
putMsg, printInfoForUser, printOutputForUser,
logInfo, logOutput,
errorMsg, warningMsg,
fatalErrorMsg, fatalErrorMsg', fatalErrorMsg'',
compilationProgressMsg,
showPass,
debugTraceMsg,
prettyPrintGhcErrors,
) where
#include "HsVersions.h"
import ETA.Utils.Bag ( Bag, bagToList, isEmptyBag, emptyBag )
import ETA.Utils.Exception
import ETA.Utils.Outputable
import ETA.Utils.Panic
import ETA.Utils.FastString
import ETA.BasicTypes.SrcLoc
import ETA.Main.DynFlags
import System.Directory
import System.Exit ( ExitCode(..), exitWith )
import System.FilePath ( takeDirectory, (</>) )
import Data.List
import qualified Data.Set as Set
import Data.IORef
import Data.Ord
import Data.Time
import Control.Monad
import Control.Monad.IO.Class
import System.IO
-------------------------
type MsgDoc = SDoc
-------------------------
data Validity
= IsValid -- Everything is fine
| NotValid MsgDoc -- A problem, and some indication of why
isValid :: Validity -> Bool
isValid IsValid = True
isValid (NotValid {}) = False
andValid :: Validity -> Validity -> Validity
andValid IsValid v = v
andValid v _ = v
allValid :: [Validity] -> Validity -- If they aren't all valid, return the first
allValid [] = IsValid
allValid (v : vs) = v `andValid` allValid vs
getInvalids :: [Validity] -> [MsgDoc]
getInvalids vs = [d | NotValid d <- vs]
-- -----------------------------------------------------------------------------
-- Basic error messages: just render a message with a source location.
type Messages = (WarningMessages, ErrorMessages)
type WarningMessages = Bag WarnMsg
type ErrorMessages = Bag ErrMsg
data ErrMsg = ErrMsg {
errMsgSpan :: SrcSpan,
errMsgContext :: PrintUnqualified,
errMsgShortDoc :: MsgDoc, -- errMsgShort* should always
errMsgShortString :: String, -- contain the same text
errMsgExtraInfo :: MsgDoc,
errMsgSeverity :: Severity
}
-- The SrcSpan is used for sorting errors into line-number order
type WarnMsg = ErrMsg
data Severity
= SevOutput
| SevDump
| SevInteractive
| SevInfo
| SevWarning
| SevError
| SevFatal
instance Show ErrMsg where
show em = errMsgShortString em
pprMessageBag :: Bag MsgDoc -> SDoc
pprMessageBag msgs = vcat (punctuate blankLine (bagToList msgs))
mkLocMessage :: Severity -> SrcSpan -> MsgDoc -> MsgDoc
-- Always print the location, even if it is unhelpful. Error messages
-- are supposed to be in a standard format, and one without a location
-- would look strange. Better to say explicitly "<no location info>".
mkLocMessage severity locn msg
= sdocWithDynFlags $ \dflags ->
let locn' = if gopt Opt_ErrorSpans dflags
then ppr locn
else ppr (srcSpanStart locn)
in hang (locn' <> colon <+> sev_info) 4 msg
where
sev_info = case severity of
SevWarning -> ptext (sLit "Warning:")
_other -> empty
-- For warnings, print Foo.hs:34: Warning:
-- <the warning message>
makeIntoWarning :: ErrMsg -> ErrMsg
makeIntoWarning err = err { errMsgSeverity = SevWarning }
isWarning :: ErrMsg -> Bool
isWarning err
| SevWarning <- errMsgSeverity err = True
| otherwise = False
-- -----------------------------------------------------------------------------
-- Collecting up messages for later ordering and printing.
mk_err_msg :: DynFlags -> Severity -> SrcSpan -> PrintUnqualified -> MsgDoc -> SDoc -> ErrMsg
mk_err_msg dflags sev locn print_unqual msg extra
= ErrMsg { errMsgSpan = locn, errMsgContext = print_unqual
, errMsgShortDoc = msg , errMsgShortString = showSDoc dflags msg
, errMsgExtraInfo = extra
, errMsgSeverity = sev }
mkLongErrMsg, mkLongWarnMsg :: DynFlags -> SrcSpan -> PrintUnqualified -> MsgDoc -> MsgDoc -> ErrMsg
-- A long (multi-line) error message
mkErrMsg, mkWarnMsg :: DynFlags -> SrcSpan -> PrintUnqualified -> MsgDoc -> ErrMsg
-- A short (one-line) error message
mkPlainErrMsg, mkPlainWarnMsg :: DynFlags -> SrcSpan -> MsgDoc -> ErrMsg
-- Variant that doesn't care about qualified/unqualified names
mkLongErrMsg dflags locn unqual msg extra = mk_err_msg dflags SevError locn unqual msg extra
mkErrMsg dflags locn unqual msg = mk_err_msg dflags SevError locn unqual msg empty
mkPlainErrMsg dflags locn msg = mk_err_msg dflags SevError locn alwaysQualify msg empty
mkLongWarnMsg dflags locn unqual msg extra = mk_err_msg dflags SevWarning locn unqual msg extra
mkWarnMsg dflags locn unqual msg = mk_err_msg dflags SevWarning locn unqual msg empty
mkPlainWarnMsg dflags locn msg = mk_err_msg dflags SevWarning locn alwaysQualify msg empty
----------------
emptyMessages :: Messages
emptyMessages = (emptyBag, emptyBag)
isEmptyMessages :: Messages -> Bool
isEmptyMessages (warns, errs) = isEmptyBag warns && isEmptyBag errs
warnIsErrorMsg :: DynFlags -> ErrMsg
warnIsErrorMsg dflags
= mkPlainErrMsg dflags noSrcSpan (text "\nFailing due to -Werror.")
errorsFound :: DynFlags -> Messages -> Bool
errorsFound _dflags (_warns, errs) = not (isEmptyBag errs)
printBagOfErrors :: DynFlags -> Bag ErrMsg -> IO ()
printBagOfErrors dflags bag_of_errors
= printMsgBag dflags bag_of_errors
pprErrMsgBag :: Bag ErrMsg -> [SDoc]
pprErrMsgBag bag
= [ sdocWithDynFlags $ \dflags ->
let style = mkErrStyle dflags unqual
in withPprStyle style (d $$ e)
| ErrMsg { errMsgShortDoc = d,
errMsgExtraInfo = e,
errMsgContext = unqual } <- sortMsgBag bag ]
pprErrMsgBagWithLoc :: Bag ErrMsg -> [SDoc]
pprErrMsgBagWithLoc bag = [ pprLocErrMsg item | item <- sortMsgBag bag ]
pprLocErrMsg :: ErrMsg -> SDoc
pprLocErrMsg (ErrMsg { errMsgSpan = s
, errMsgShortDoc = d
, errMsgExtraInfo = e
, errMsgSeverity = sev
, errMsgContext = unqual })
= sdocWithDynFlags $ \dflags ->
withPprStyle (mkErrStyle dflags unqual) (mkLocMessage sev s (d $$ e))
printMsgBag :: DynFlags -> Bag ErrMsg -> IO ()
printMsgBag dflags bag
= sequence_ [ let style = mkErrStyle dflags unqual
in log_action dflags dflags sev s style (d $$ e)
| ErrMsg { errMsgSpan = s,
errMsgShortDoc = d,
errMsgSeverity = sev,
errMsgExtraInfo = e,
errMsgContext = unqual } <- sortMsgBag bag ]
sortMsgBag :: Bag ErrMsg -> [ErrMsg]
sortMsgBag bag = sortBy (comparing errMsgSpan) $ bagToList bag
ghcExit :: DynFlags -> Int -> IO ()
ghcExit dflags val
| val == 0 = exitWith ExitSuccess
| otherwise = do errorMsg dflags (text "\nCompilation had errors\n\n")
exitWith (ExitFailure val)
doIfSet :: Bool -> IO () -> IO ()
doIfSet flag action | flag = action
| otherwise = return ()
doIfSet_dyn :: DynFlags -> GeneralFlag -> IO () -> IO()
doIfSet_dyn dflags flag action | gopt flag dflags = action
| otherwise = return ()
-- -----------------------------------------------------------------------------
-- Dumping
dumpIfSet :: DynFlags -> Bool -> String -> SDoc -> IO ()
dumpIfSet dflags flag hdr doc
| not flag = return ()
| otherwise = log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (mkDumpDoc hdr doc)
-- | a wrapper around 'dumpSDoc'.
-- First check whether the dump flag is set
-- Do nothing if it is unset
dumpIfSet_dyn :: DynFlags -> DumpFlag -> String -> SDoc -> IO ()
dumpIfSet_dyn dflags flag hdr doc
= when (dopt flag dflags) $ dumpSDoc dflags alwaysQualify flag hdr doc
-- | a wrapper around 'dumpSDoc'.
-- First check whether the dump flag is set
-- Do nothing if it is unset
--
-- Unlike 'dumpIfSet_dyn',
-- has a printer argument but no header argument
dumpIfSet_dyn_printer :: PrintUnqualified
-> DynFlags -> DumpFlag -> SDoc -> IO ()
dumpIfSet_dyn_printer printer dflags flag doc
= when (dopt flag dflags) $ dumpSDoc dflags printer flag "" doc
mkDumpDoc :: String -> SDoc -> SDoc
mkDumpDoc hdr doc
= vcat [blankLine,
line <+> text hdr <+> line,
doc,
blankLine]
where
line = text (replicate 20 '=')
-- | Write out a dump.
-- If --dump-to-file is set then this goes to a file.
-- otherwise emit to stdout.
--
-- When hdr is empty, we print in a more compact format (no separators and
-- blank lines)
--
-- The DumpFlag is used only to choose the filename to use if --dump-to-file is
-- used; it is not used to decide whether to dump the output
dumpSDoc :: DynFlags -> PrintUnqualified -> DumpFlag -> String -> SDoc -> IO ()
dumpSDoc dflags print_unqual flag hdr doc
= do let mFile = chooseDumpFile dflags flag
dump_style = mkDumpStyle print_unqual
case mFile of
Just fileName
-> do
let gdref = generatedDumps dflags
gd <- readIORef gdref
let append = Set.member fileName gd
mode = if append then AppendMode else WriteMode
when (not append) $
writeIORef gdref (Set.insert fileName gd)
createDirectoryIfMissing True (takeDirectory fileName)
handle <- openFile fileName mode
-- We do not want the dump file to be affected by
-- environment variables, but instead to always use
-- UTF8. See:
-- https://ghc.haskell.org/trac/ghc/ticket/10762
hSetEncoding handle utf8
doc' <- if null hdr
then return doc
else do t <- getCurrentTime
let d = text (show t)
$$ blankLine
$$ doc
return $ mkDumpDoc hdr d
defaultLogActionHPrintDoc dflags handle doc' dump_style
hClose handle
-- write the dump to stdout
Nothing -> do
let (doc', severity)
| null hdr = (doc, SevOutput)
| otherwise = (mkDumpDoc hdr doc, SevDump)
log_action dflags dflags severity noSrcSpan dump_style doc'
-- | Choose where to put a dump file based on DynFlags
--
chooseDumpFile :: DynFlags -> DumpFlag -> Maybe String
chooseDumpFile dflags flag
| gopt Opt_DumpToFile dflags || flag == Opt_D_th_dec_file
, Just prefix <- getPrefix
= Just $ setDir (prefix ++ (beautifyDumpName flag))
| otherwise
= Nothing
where getPrefix
-- dump file location is being forced
-- by the --ddump-file-prefix flag.
| Just prefix <- dumpPrefixForce dflags
= Just prefix
-- dump file location chosen by DriverPipeline.runPipeline
| Just prefix <- dumpPrefix dflags
= Just prefix
-- we haven't got a place to put a dump file.
| otherwise
= Nothing
setDir f = case dumpDir dflags of
Just d -> d </> f
Nothing -> f
-- | Build a nice file name from name of a GeneralFlag constructor
beautifyDumpName :: DumpFlag -> String
beautifyDumpName Opt_D_th_dec_file = "th.hs"
beautifyDumpName flag
= let str = show flag
suff = case stripPrefix "Opt_D_" str of
Just x -> x
Nothing -> panic ("Bad flag name: " ++ str)
dash = map (\c -> if c == '_' then '-' else c) suff
in dash
-- -----------------------------------------------------------------------------
-- Outputting messages from the compiler
-- We want all messages to go through one place, so that we can
-- redirect them if necessary. For example, when GHC is used as a
-- library we might want to catch all messages that GHC tries to
-- output and do something else with them.
ifVerbose :: DynFlags -> Int -> IO () -> IO ()
ifVerbose dflags val act
| verbosity dflags >= val = act
| otherwise = return ()
errorMsg :: DynFlags -> MsgDoc -> IO ()
errorMsg dflags msg
= log_action dflags dflags SevError noSrcSpan (defaultErrStyle dflags) msg
warningMsg :: DynFlags -> MsgDoc -> IO ()
warningMsg dflags msg
= log_action dflags dflags SevWarning noSrcSpan (defaultErrStyle dflags) msg
fatalErrorMsg :: DynFlags -> MsgDoc -> IO ()
fatalErrorMsg dflags msg = fatalErrorMsg' (log_action dflags) dflags msg
fatalErrorMsg' :: LogAction -> DynFlags -> MsgDoc -> IO ()
fatalErrorMsg' la dflags msg =
la dflags SevFatal noSrcSpan (defaultErrStyle dflags) msg
fatalErrorMsg'' :: FatalMessager -> String -> IO ()
fatalErrorMsg'' fm msg = fm msg
compilationProgressMsg :: DynFlags -> String -> IO ()
compilationProgressMsg dflags msg
= ifVerbose dflags 1 $
logOutput dflags defaultUserStyle (text msg)
showPass :: DynFlags -> String -> IO ()
showPass dflags what
= ifVerbose dflags 2 $
logInfo dflags defaultUserStyle (text "***" <+> text what <> colon)
debugTraceMsg :: DynFlags -> Int -> MsgDoc -> IO ()
debugTraceMsg dflags val msg = ifVerbose dflags val $
logInfo dflags defaultDumpStyle msg
putMsg :: DynFlags -> MsgDoc -> IO ()
putMsg dflags msg = logInfo dflags defaultUserStyle msg
printInfoForUser :: DynFlags -> PrintUnqualified -> MsgDoc -> IO ()
printInfoForUser dflags print_unqual msg
= logInfo dflags (mkUserStyle print_unqual AllTheWay) msg
printOutputForUser :: DynFlags -> PrintUnqualified -> MsgDoc -> IO ()
printOutputForUser dflags print_unqual msg
= logOutput dflags (mkUserStyle print_unqual AllTheWay) msg
logInfo :: DynFlags -> PprStyle -> MsgDoc -> IO ()
logInfo dflags sty msg = log_action dflags dflags SevInfo noSrcSpan sty msg
logOutput :: DynFlags -> PprStyle -> MsgDoc -> IO ()
-- Like logInfo but with SevOutput rather then SevInfo
logOutput dflags sty msg = log_action dflags dflags SevOutput noSrcSpan sty msg
prettyPrintGhcErrors :: ExceptionMonad m => DynFlags -> m a -> m a
prettyPrintGhcErrors dflags
= ghandle $ \e -> case e of
PprPanic str doc ->
pprDebugAndThen dflags panic (text str) doc
PprSorry str doc ->
pprDebugAndThen dflags sorry (text str) doc
PprProgramError str doc ->
pprDebugAndThen dflags pgmError (text str) doc
_ ->
liftIO $ throwIO e
| alexander-at-github/eta | compiler/ETA/Main/ErrUtils.hs | bsd-3-clause | 16,021 | 0 | 23 | 4,655 | 3,687 | 1,919 | 1,768 | 289 | 4 |
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.ByteString
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This is a purely internal module for interfacing with ByteStrings.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.ByteString (
B.ByteString, stringQuery, createAndTrimByteString,
withByteString, withGLstring,
packUtf8, unpackUtf8
) where
import Foreign.Ptr
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.Raw
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as BI
import qualified Data.ByteString.Unsafe as BU
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
--------------------------------------------------------------------------------
stringQuery :: (a -> GettableStateVar GLsizei)
-> (a -> GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ())
-> a
-> IO B.ByteString
stringQuery lengthVar getStr obj = do
len <- get (lengthVar obj)
createByteString len $
getStr obj len nullPtr
createByteString :: Integral a => a -> (Ptr GLchar -> IO ()) -> IO B.ByteString
createByteString size act = BI.create (fromIntegral size) (act . castPtr)
createAndTrimByteString ::
(Integral a, Integral b) => a -> (Ptr GLchar -> IO b) -> IO B.ByteString
createAndTrimByteString maxLen act =
BI.createAndTrim (fromIntegral maxLen) (fmap fromIntegral . act . castPtr)
withByteString :: B.ByteString -> (Ptr GLchar -> GLsizei -> IO b) -> IO b
withByteString bs act =
BU.unsafeUseAsCStringLen bs $ \(ptr, size) ->
act (castPtr ptr) (fromIntegral size)
withGLstring :: String -> (Ptr GLchar -> IO a) -> IO a
withGLstring s act = withByteString (packUtf8 (s ++ "\0")) (const . act)
packUtf8 :: String -> B.ByteString
packUtf8 = TE.encodeUtf8 . T.pack
unpackUtf8 :: B.ByteString -> String
unpackUtf8 = T.unpack . TE.decodeUtf8
| hesiod/OpenGL | src/Graphics/Rendering/OpenGL/GL/ByteString.hs | bsd-3-clause | 2,185 | 0 | 13 | 367 | 566 | 309 | 257 | 37 | 1 |
{-# LANGUAGE CPP, RecordWildCards, NamedFieldPuns, DeriveGeneric #-}
-- | Project configuration, implementation in terms of legacy types.
--
module Distribution.Client.ProjectConfig.Legacy (
-- * Project config in terms of legacy types
LegacyProjectConfig,
parseLegacyProjectConfig,
showLegacyProjectConfig,
-- * Conversion to and from legacy config types
commandLineFlagsToProjectConfig,
convertLegacyProjectConfig,
convertLegacyGlobalConfig,
convertToLegacyProjectConfig,
-- * Internals, just for tests
parsePackageLocationTokenQ,
renderPackageLocationToken,
) where
import Distribution.Client.ProjectConfig.Types
import Distribution.Client.Types
( RemoteRepo(..), emptyRemoteRepo )
import Distribution.Client.Dependency.Types
( ConstraintSource(..) )
import Distribution.Client.Config
( SavedConfig(..), remoteRepoFields )
import Distribution.Package
import Distribution.PackageDescription
( SourceRepo(..), RepoKind(..) )
import Distribution.PackageDescription.Parse
( sourceRepoFieldDescrs )
import Distribution.Simple.Compiler
( OptimisationLevel(..), DebugInfoLevel(..) )
import Distribution.Simple.Setup
( Flag(Flag), toFlag, fromFlagOrDefault
, ConfigFlags(..), configureOptions
, HaddockFlags(..), haddockOptions, defaultHaddockFlags
, programConfigurationPaths', splitArgs
, AllowNewer(..) )
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand
, ConfigExFlags(..), configureExOptions, defaultConfigExFlags
, InstallFlags(..), installOptions, defaultInstallFlags )
import Distribution.Simple.Program
( programName, knownPrograms )
import Distribution.Simple.Program.Db
( ProgramDb, defaultProgramDb )
import Distribution.Client.Targets
( dispFlagAssignment, parseFlagAssignment )
import Distribution.Simple.Utils
( lowercase )
import Distribution.Utils.NubList
( toNubList, fromNubList, overNubList )
import Distribution.Simple.LocalBuildInfo
( toPathTemplate, fromPathTemplate )
import Distribution.Text
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP
( ReadP, (+++), (<++) )
import qualified Text.Read as Read
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint
( Doc, ($+$) )
import qualified Distribution.ParseUtils as ParseUtils (field)
import Distribution.ParseUtils
( ParseResult(..), PError(..), syntaxError, PWarning(..), warning
, simpleField, commaNewLineListField
, showToken )
import Distribution.Client.ParseUtils
import Distribution.Simple.Command
( CommandUI(commandOptions), ShowOrParseArgs(..)
, OptionField, option, reqArg' )
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad
import qualified Data.Map as Map
import Data.Char (isSpace)
import Distribution.Compat.Semigroup
import GHC.Generics (Generic)
------------------------------------------------------------------
-- Representing the project config file in terms of legacy types
--
-- | We already have parsers\/pretty-printers for almost all the fields in the
-- project config file, but they're in terms of the types used for the command
-- line flags for Setup.hs or cabal commands. We don't want to redefine them
-- all, at least not yet so for the moment we use the parsers at the old types
-- and use conversion functions.
--
-- Ultimately if\/when this project-based approach becomes the default then we
-- can redefine the parsers directly for the new types.
--
data LegacyProjectConfig = LegacyProjectConfig {
legacyPackages :: [String],
legacyPackagesOptional :: [String],
legacyPackagesRepo :: [SourceRepo],
legacyPackagesNamed :: [Dependency],
legacySharedConfig :: LegacySharedConfig,
legacyLocalConfig :: LegacyPackageConfig,
legacySpecificConfig :: MapMappend PackageName LegacyPackageConfig
} deriving Generic
instance Monoid LegacyProjectConfig where
mempty = gmempty
mappend = (<>)
instance Semigroup LegacyProjectConfig where
(<>) = gmappend
data LegacyPackageConfig = LegacyPackageConfig {
legacyConfigureFlags :: ConfigFlags,
legacyInstallPkgFlags :: InstallFlags,
legacyHaddockFlags :: HaddockFlags
} deriving Generic
instance Monoid LegacyPackageConfig where
mempty = gmempty
mappend = (<>)
instance Semigroup LegacyPackageConfig where
(<>) = gmappend
data LegacySharedConfig = LegacySharedConfig {
legacyGlobalFlags :: GlobalFlags,
legacyConfigureShFlags :: ConfigFlags,
legacyConfigureExFlags :: ConfigExFlags,
legacyInstallFlags :: InstallFlags
} deriving Generic
instance Monoid LegacySharedConfig where
mempty = gmempty
mappend = (<>)
instance Semigroup LegacySharedConfig where
(<>) = gmappend
------------------------------------------------------------------
-- Converting from and to the legacy types
--
-- | Convert configuration from the @cabal configure@ or @cabal build@ command
-- line into a 'ProjectConfig' value that can combined with configuration from
-- other sources.
--
-- At the moment this uses the legacy command line flag types. See
-- 'LegacyProjectConfig' for an explanation.
--
commandLineFlagsToProjectConfig :: GlobalFlags
-> ConfigFlags -> ConfigExFlags
-> InstallFlags -> HaddockFlags
-> ProjectConfig
commandLineFlagsToProjectConfig globalFlags configFlags configExFlags
installFlags haddockFlags =
mempty {
projectConfigBuildOnly = convertLegacyBuildOnlyFlags
globalFlags configFlags
installFlags haddockFlags,
projectConfigShared = convertLegacyAllPackageFlags
globalFlags configFlags
configExFlags installFlags,
projectConfigLocalPackages = convertLegacyPerPackageFlags
configFlags installFlags haddockFlags
}
-- | Convert from the types currently used for the user-wide @~/.cabal/config@
-- file into the 'ProjectConfig' type.
--
-- Only a subset of the 'ProjectConfig' can be represented in the user-wide
-- config. In particular it does not include packages that are in the project,
-- and it also doesn't support package-specific configuration (only
-- configuration that applies to all packages).
--
convertLegacyGlobalConfig :: SavedConfig -> ProjectConfig
convertLegacyGlobalConfig
SavedConfig {
savedGlobalFlags = globalFlags,
savedInstallFlags = installFlags,
savedConfigureFlags = configFlags,
savedConfigureExFlags = configExFlags,
savedUserInstallDirs = _,
savedGlobalInstallDirs = _,
savedUploadFlags = _,
savedReportFlags = _,
savedHaddockFlags = haddockFlags
} =
mempty {
projectConfigShared = configAllPackages,
projectConfigLocalPackages = configLocalPackages,
projectConfigBuildOnly = configBuildOnly
}
where
--TODO: [code cleanup] eliminate use of default*Flags here and specify the
-- defaults in the various resolve functions in terms of the new types.
configExFlags' = defaultConfigExFlags <> configExFlags
installFlags' = defaultInstallFlags <> installFlags
haddockFlags' = defaultHaddockFlags <> haddockFlags
configLocalPackages = convertLegacyPerPackageFlags
configFlags installFlags' haddockFlags'
configAllPackages = convertLegacyAllPackageFlags
globalFlags configFlags
configExFlags' installFlags'
configBuildOnly = convertLegacyBuildOnlyFlags
globalFlags configFlags
installFlags' haddockFlags'
-- | Convert the project config from the legacy types to the 'ProjectConfig'
-- and associated types. See 'LegacyProjectConfig' for an explanation of the
-- approach.
--
convertLegacyProjectConfig :: LegacyProjectConfig -> ProjectConfig
convertLegacyProjectConfig
LegacyProjectConfig {
legacyPackages,
legacyPackagesOptional,
legacyPackagesRepo,
legacyPackagesNamed,
legacySharedConfig = LegacySharedConfig globalFlags configShFlags
configExFlags installSharedFlags,
legacyLocalConfig = LegacyPackageConfig configFlags installPerPkgFlags
haddockFlags,
legacySpecificConfig
} =
ProjectConfig {
projectPackages = legacyPackages,
projectPackagesOptional = legacyPackagesOptional,
projectPackagesRepo = legacyPackagesRepo,
projectPackagesNamed = legacyPackagesNamed,
projectConfigBuildOnly = configBuildOnly,
projectConfigShared = configAllPackages,
projectConfigLocalPackages = configLocalPackages,
projectConfigSpecificPackage = fmap perPackage legacySpecificConfig
}
where
configLocalPackages = convertLegacyPerPackageFlags
configFlags installPerPkgFlags haddockFlags
configAllPackages = convertLegacyAllPackageFlags
globalFlags (configFlags <> configShFlags)
configExFlags installSharedFlags
configBuildOnly = convertLegacyBuildOnlyFlags
globalFlags configShFlags
installSharedFlags haddockFlags
perPackage (LegacyPackageConfig perPkgConfigFlags perPkgInstallFlags
perPkgHaddockFlags) =
convertLegacyPerPackageFlags
perPkgConfigFlags perPkgInstallFlags perPkgHaddockFlags
-- | Helper used by other conversion functions that returns the
-- 'ProjectConfigShared' subset of the 'ProjectConfig'.
--
convertLegacyAllPackageFlags :: GlobalFlags -> ConfigFlags
-> ConfigExFlags -> InstallFlags
-> ProjectConfigShared
convertLegacyAllPackageFlags globalFlags configFlags
configExFlags installFlags =
ProjectConfigShared{..}
where
GlobalFlags {
globalConfigFile = _, -- TODO: [required feature]
globalSandboxConfigFile = _, -- ??
globalRemoteRepos = projectConfigRemoteRepos,
globalLocalRepos = projectConfigLocalRepos
} = globalFlags
ConfigFlags {
configHcFlavor = projectConfigHcFlavor,
configHcPath = projectConfigHcPath,
configHcPkg = projectConfigHcPkg,
--configInstallDirs = projectConfigInstallDirs,
--configUserInstall = projectConfigUserInstall,
--configPackageDBs = projectConfigPackageDBs,
configAllowNewer = projectConfigAllowNewer
} = configFlags
ConfigExFlags {
configCabalVersion = projectConfigCabalVersion,
configExConstraints = projectConfigConstraints,
configPreferences = projectConfigPreferences,
configSolver = projectConfigSolver
} = configExFlags
InstallFlags {
installHaddockIndex = projectConfigHaddockIndex,
--installReinstall = projectConfigReinstall,
--installAvoidReinstalls = projectConfigAvoidReinstalls,
--installOverrideReinstall = projectConfigOverrideReinstall,
installMaxBackjumps = projectConfigMaxBackjumps,
--installUpgradeDeps = projectConfigUpgradeDeps,
installReorderGoals = projectConfigReorderGoals,
--installIndependentGoals = projectConfigIndependentGoals,
--installShadowPkgs = projectConfigShadowPkgs,
installStrongFlags = projectConfigStrongFlags
} = installFlags
-- | Helper used by other conversion functions that returns the
-- 'PackageConfig' subset of the 'ProjectConfig'.
--
convertLegacyPerPackageFlags :: ConfigFlags -> InstallFlags -> HaddockFlags
-> PackageConfig
convertLegacyPerPackageFlags configFlags installFlags haddockFlags =
PackageConfig{..}
where
ConfigFlags {
configProgramPaths,
configProgramArgs,
configProgramPathExtra = packageConfigProgramPathExtra,
configVanillaLib = packageConfigVanillaLib,
configProfLib = packageConfigProfLib,
configSharedLib = packageConfigSharedLib,
configDynExe = packageConfigDynExe,
configProfExe = packageConfigProfExe,
configProf = packageConfigProf,
configProfDetail = packageConfigProfDetail,
configProfLibDetail = packageConfigProfLibDetail,
configConfigureArgs = packageConfigConfigureArgs,
configOptimization = packageConfigOptimization,
configProgPrefix = packageConfigProgPrefix,
configProgSuffix = packageConfigProgSuffix,
configGHCiLib = packageConfigGHCiLib,
configSplitObjs = packageConfigSplitObjs,
configStripExes = packageConfigStripExes,
configStripLibs = packageConfigStripLibs,
configExtraLibDirs = packageConfigExtraLibDirs,
configExtraFrameworkDirs = packageConfigExtraFrameworkDirs,
configExtraIncludeDirs = packageConfigExtraIncludeDirs,
configConfigurationsFlags = packageConfigFlagAssignment,
configTests = packageConfigTests,
configBenchmarks = packageConfigBenchmarks,
configCoverage = coverage,
configLibCoverage = libcoverage, --deprecated
configDebugInfo = packageConfigDebugInfo,
configRelocatable = packageConfigRelocatable
} = configFlags
packageConfigProgramPaths = MapLast (Map.fromList configProgramPaths)
packageConfigProgramArgs = MapMappend (Map.fromList configProgramArgs)
packageConfigCoverage = coverage <> libcoverage
--TODO: defer this merging to the resolve phase
InstallFlags {
installDocumentation = packageConfigDocumentation,
installRunTests = packageConfigRunTests
} = installFlags
HaddockFlags {
haddockHoogle = packageConfigHaddockHoogle,
haddockHtml = packageConfigHaddockHtml,
haddockHtmlLocation = packageConfigHaddockHtmlLocation,
haddockExecutables = packageConfigHaddockExecutables,
haddockTestSuites = packageConfigHaddockTestSuites,
haddockBenchmarks = packageConfigHaddockBenchmarks,
haddockInternal = packageConfigHaddockInternal,
haddockCss = packageConfigHaddockCss,
haddockHscolour = packageConfigHaddockHscolour,
haddockHscolourCss = packageConfigHaddockHscolourCss,
haddockContents = packageConfigHaddockContents
} = haddockFlags
-- | Helper used by other conversion functions that returns the
-- 'ProjectConfigBuildOnly' subset of the 'ProjectConfig'.
--
convertLegacyBuildOnlyFlags :: GlobalFlags -> ConfigFlags
-> InstallFlags -> HaddockFlags
-> ProjectConfigBuildOnly
convertLegacyBuildOnlyFlags globalFlags configFlags
installFlags haddockFlags =
ProjectConfigBuildOnly{..}
where
GlobalFlags {
globalCacheDir = projectConfigCacheDir,
globalLogsDir = projectConfigLogsDir,
globalWorldFile = projectConfigWorldFile,
globalHttpTransport = projectConfigHttpTransport,
globalIgnoreExpiry = projectConfigIgnoreExpiry
} = globalFlags
ConfigFlags {
configVerbosity = projectConfigVerbosity
} = configFlags
InstallFlags {
installDryRun = projectConfigDryRun,
installOnly = _,
installOnlyDeps = projectConfigOnlyDeps,
installRootCmd = projectConfigRootCmd,
installSummaryFile = projectConfigSummaryFile,
installLogFile = projectConfigLogFile,
installBuildReports = projectConfigBuildReports,
installReportPlanningFailure = projectConfigReportPlanningFailure,
installSymlinkBinDir = projectConfigSymlinkBinDir,
installOneShot = projectConfigOneShot,
installNumJobs = projectConfigNumJobs,
installOfflineMode = projectConfigOfflineMode
} = installFlags
HaddockFlags {
haddockKeepTempFiles = projectConfigKeepTempFiles --TODO: this ought to live elsewhere
} = haddockFlags
convertToLegacyProjectConfig :: ProjectConfig -> LegacyProjectConfig
convertToLegacyProjectConfig
projectConfig@ProjectConfig {
projectPackages,
projectPackagesOptional,
projectPackagesRepo,
projectPackagesNamed,
projectConfigLocalPackages,
projectConfigSpecificPackage
} =
LegacyProjectConfig {
legacyPackages = projectPackages,
legacyPackagesOptional = projectPackagesOptional,
legacyPackagesRepo = projectPackagesRepo,
legacyPackagesNamed = projectPackagesNamed,
legacySharedConfig = convertToLegacySharedConfig projectConfig,
legacyLocalConfig = convertToLegacyAllPackageConfig projectConfig
<> convertToLegacyPerPackageConfig
projectConfigLocalPackages,
legacySpecificConfig = fmap convertToLegacyPerPackageConfig
projectConfigSpecificPackage
}
convertToLegacySharedConfig :: ProjectConfig -> LegacySharedConfig
convertToLegacySharedConfig
ProjectConfig {
projectConfigBuildOnly = ProjectConfigBuildOnly {..},
projectConfigShared = ProjectConfigShared {..}
} =
LegacySharedConfig {
legacyGlobalFlags = globalFlags,
legacyConfigureShFlags = configFlags,
legacyConfigureExFlags = configExFlags,
legacyInstallFlags = installFlags
}
where
globalFlags = GlobalFlags {
globalVersion = mempty,
globalNumericVersion = mempty,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = projectConfigRemoteRepos,
globalCacheDir = projectConfigCacheDir,
globalLocalRepos = projectConfigLocalRepos,
globalLogsDir = projectConfigLogsDir,
globalWorldFile = projectConfigWorldFile,
globalRequireSandbox = mempty,
globalIgnoreSandbox = mempty,
globalIgnoreExpiry = projectConfigIgnoreExpiry,
globalHttpTransport = projectConfigHttpTransport
}
configFlags = mempty {
configVerbosity = projectConfigVerbosity,
configAllowNewer = projectConfigAllowNewer
}
configExFlags = ConfigExFlags {
configCabalVersion = projectConfigCabalVersion,
configExConstraints = projectConfigConstraints,
configPreferences = projectConfigPreferences,
configSolver = projectConfigSolver
}
installFlags = InstallFlags {
installDocumentation = mempty,
installHaddockIndex = projectConfigHaddockIndex,
installDryRun = projectConfigDryRun,
installReinstall = mempty, --projectConfigReinstall,
installAvoidReinstalls = mempty, --projectConfigAvoidReinstalls,
installOverrideReinstall = mempty, --projectConfigOverrideReinstall,
installMaxBackjumps = projectConfigMaxBackjumps,
installUpgradeDeps = mempty, --projectConfigUpgradeDeps,
installReorderGoals = projectConfigReorderGoals,
installIndependentGoals = mempty, --projectConfigIndependentGoals,
installShadowPkgs = mempty, --projectConfigShadowPkgs,
installStrongFlags = projectConfigStrongFlags,
installOnly = mempty,
installOnlyDeps = projectConfigOnlyDeps,
installRootCmd = projectConfigRootCmd,
installSummaryFile = projectConfigSummaryFile,
installLogFile = projectConfigLogFile,
installBuildReports = projectConfigBuildReports,
installReportPlanningFailure = projectConfigReportPlanningFailure,
installSymlinkBinDir = projectConfigSymlinkBinDir,
installOneShot = projectConfigOneShot,
installNumJobs = projectConfigNumJobs,
installRunTests = mempty,
installOfflineMode = projectConfigOfflineMode
}
convertToLegacyAllPackageConfig :: ProjectConfig -> LegacyPackageConfig
convertToLegacyAllPackageConfig
ProjectConfig {
projectConfigBuildOnly = ProjectConfigBuildOnly {..},
projectConfigShared = ProjectConfigShared {..}
} =
LegacyPackageConfig {
legacyConfigureFlags = configFlags,
legacyInstallPkgFlags= mempty,
legacyHaddockFlags = haddockFlags
}
where
configFlags = ConfigFlags {
configPrograms_ = mempty,
configProgramPaths = mempty,
configProgramArgs = mempty,
configProgramPathExtra = mempty,
configHcFlavor = projectConfigHcFlavor,
configHcPath = projectConfigHcPath,
configHcPkg = projectConfigHcPkg,
configVanillaLib = mempty,
configProfLib = mempty,
configSharedLib = mempty,
configDynExe = mempty,
configProfExe = mempty,
configProf = mempty,
configProfDetail = mempty,
configProfLibDetail = mempty,
configConfigureArgs = mempty,
configOptimization = mempty,
configProgPrefix = mempty,
configProgSuffix = mempty,
configInstallDirs = mempty,
configScratchDir = mempty,
configDistPref = mempty,
configVerbosity = mempty,
configUserInstall = mempty, --projectConfigUserInstall,
configPackageDBs = mempty, --projectConfigPackageDBs,
configGHCiLib = mempty,
configSplitObjs = mempty,
configStripExes = mempty,
configStripLibs = mempty,
configExtraLibDirs = mempty,
configExtraFrameworkDirs = mempty,
configConstraints = mempty,
configDependencies = mempty,
configExtraIncludeDirs = mempty,
configIPID = mempty,
configConfigurationsFlags = mempty,
configTests = mempty,
configCoverage = mempty, --TODO: don't merge
configLibCoverage = mempty, --TODO: don't merge
configExactConfiguration = mempty,
configBenchmarks = mempty,
configFlagError = mempty, --TODO: ???
configRelocatable = mempty,
configDebugInfo = mempty,
configAllowNewer = mempty
}
haddockFlags = mempty {
haddockKeepTempFiles = projectConfigKeepTempFiles
}
convertToLegacyPerPackageConfig :: PackageConfig -> LegacyPackageConfig
convertToLegacyPerPackageConfig PackageConfig {..} =
LegacyPackageConfig {
legacyConfigureFlags = configFlags,
legacyInstallPkgFlags = installFlags,
legacyHaddockFlags = haddockFlags
}
where
configFlags = ConfigFlags {
configPrograms_ = configPrograms_ mempty,
configProgramPaths = Map.toList (getMapLast packageConfigProgramPaths),
configProgramArgs = Map.toList (getMapMappend packageConfigProgramArgs),
configProgramPathExtra = packageConfigProgramPathExtra,
configHcFlavor = mempty,
configHcPath = mempty,
configHcPkg = mempty,
configVanillaLib = packageConfigVanillaLib,
configProfLib = packageConfigProfLib,
configSharedLib = packageConfigSharedLib,
configDynExe = packageConfigDynExe,
configProfExe = packageConfigProfExe,
configProf = packageConfigProf,
configProfDetail = packageConfigProfDetail,
configProfLibDetail = packageConfigProfLibDetail,
configConfigureArgs = packageConfigConfigureArgs,
configOptimization = packageConfigOptimization,
configProgPrefix = packageConfigProgPrefix,
configProgSuffix = packageConfigProgSuffix,
configInstallDirs = mempty,
configScratchDir = mempty,
configDistPref = mempty,
configVerbosity = mempty,
configUserInstall = mempty,
configPackageDBs = mempty,
configGHCiLib = packageConfigGHCiLib,
configSplitObjs = packageConfigSplitObjs,
configStripExes = packageConfigStripExes,
configStripLibs = packageConfigStripLibs,
configExtraLibDirs = packageConfigExtraLibDirs,
configExtraFrameworkDirs = packageConfigExtraFrameworkDirs,
configConstraints = mempty,
configDependencies = mempty,
configExtraIncludeDirs = packageConfigExtraIncludeDirs,
configIPID = mempty,
configConfigurationsFlags = packageConfigFlagAssignment,
configTests = packageConfigTests,
configCoverage = packageConfigCoverage, --TODO: don't merge
configLibCoverage = packageConfigCoverage, --TODO: don't merge
configExactConfiguration = mempty,
configBenchmarks = packageConfigBenchmarks,
configFlagError = mempty, --TODO: ???
configRelocatable = packageConfigRelocatable,
configDebugInfo = packageConfigDebugInfo,
configAllowNewer = mempty
}
installFlags = mempty {
installDocumentation = packageConfigDocumentation,
installRunTests = packageConfigRunTests
}
haddockFlags = HaddockFlags {
haddockProgramPaths = mempty,
haddockProgramArgs = mempty,
haddockHoogle = packageConfigHaddockHoogle,
haddockHtml = packageConfigHaddockHtml,
haddockHtmlLocation = packageConfigHaddockHtmlLocation,
haddockForHackage = mempty, --TODO: added recently
haddockExecutables = packageConfigHaddockExecutables,
haddockTestSuites = packageConfigHaddockTestSuites,
haddockBenchmarks = packageConfigHaddockBenchmarks,
haddockInternal = packageConfigHaddockInternal,
haddockCss = packageConfigHaddockCss,
haddockHscolour = packageConfigHaddockHscolour,
haddockHscolourCss = packageConfigHaddockHscolourCss,
haddockContents = packageConfigHaddockContents,
haddockDistPref = mempty,
haddockKeepTempFiles = mempty,
haddockVerbosity = mempty
}
------------------------------------------------
-- Parsing and showing the project config file
--
parseLegacyProjectConfig :: String -> ParseResult LegacyProjectConfig
parseLegacyProjectConfig =
parseConfig legacyProjectConfigFieldDescrs
legacyPackageConfigSectionDescrs
mempty
showLegacyProjectConfig :: LegacyProjectConfig -> String
showLegacyProjectConfig config =
Disp.render $
showConfig legacyProjectConfigFieldDescrs
legacyPackageConfigSectionDescrs
config
$+$
Disp.text ""
legacyProjectConfigFieldDescrs :: [FieldDescr LegacyProjectConfig]
legacyProjectConfigFieldDescrs =
[ newLineListField "packages"
(Disp.text . renderPackageLocationToken) parsePackageLocationTokenQ
legacyPackages
(\v flags -> flags { legacyPackages = v })
, newLineListField "optional-packages"
(Disp.text . renderPackageLocationToken) parsePackageLocationTokenQ
legacyPackagesOptional
(\v flags -> flags { legacyPackagesOptional = v })
, commaNewLineListField "extra-packages"
disp parse
legacyPackagesNamed
(\v flags -> flags { legacyPackagesNamed = v })
]
++ map (liftField
legacySharedConfig
(\flags conf -> conf { legacySharedConfig = flags }))
legacySharedConfigFieldDescrs
++ map (liftField
legacyLocalConfig
(\flags conf -> conf { legacyLocalConfig = flags }))
legacyPackageConfigFieldDescrs
-- | This is a bit tricky since it has to cover globs which have embedded @,@
-- chars. But we don't just want to parse strictly as a glob since we want to
-- allow http urls which don't parse as globs, and possibly some
-- system-dependent file paths. So we parse fairly liberally as a token, but
-- we allow @,@ inside matched @{}@ braces.
--
parsePackageLocationTokenQ :: ReadP r String
parsePackageLocationTokenQ = parseHaskellString
Parse.<++ parsePackageLocationToken
where
parsePackageLocationToken :: ReadP r String
parsePackageLocationToken = fmap fst (Parse.gather outerTerm)
where
outerTerm = alternateEither1 outerToken (braces innerTerm)
innerTerm = alternateEither innerToken (braces innerTerm)
outerToken = Parse.munch1 outerChar >> return ()
innerToken = Parse.munch1 innerChar >> return ()
outerChar c = not (isSpace c || c == '{' || c == '}' || c == ',')
innerChar c = not (isSpace c || c == '{' || c == '}')
braces = Parse.between (Parse.char '{') (Parse.char '}')
alternateEither, alternateEither1,
alternatePQs, alternate1PQs, alternateQsP, alternate1QsP
:: ReadP r () -> ReadP r () -> ReadP r ()
alternateEither1 p q = alternate1PQs p q +++ alternate1QsP q p
alternateEither p q = alternateEither1 p q +++ return ()
alternate1PQs p q = p >> alternateQsP q p
alternatePQs p q = alternate1PQs p q +++ return ()
alternate1QsP q p = Parse.many1 q >> alternatePQs p q
alternateQsP q p = alternate1QsP q p +++ return ()
renderPackageLocationToken :: String -> String
renderPackageLocationToken s | needsQuoting = show s
| otherwise = s
where
needsQuoting = not (ok 0 s)
|| s == "." -- . on its own on a line has special meaning
|| take 2 s == "--" -- on its own line is comment syntax
--TODO: [code cleanup] these "." and "--" escaping issues
-- ought to be dealt with systematically in ParseUtils.
ok :: Int -> String -> Bool
ok n [] = n == 0
ok _ ('"':_) = False
ok n ('{':cs) = ok (n+1) cs
ok n ('}':cs) = ok (n-1) cs
ok n (',':cs) = (n > 0) && ok n cs
ok _ (c:_)
| isSpace c = False
ok n (_ :cs) = ok n cs
legacySharedConfigFieldDescrs :: [FieldDescr LegacySharedConfig]
legacySharedConfigFieldDescrs =
( liftFields
legacyGlobalFlags
(\flags conf -> conf { legacyGlobalFlags = flags })
. addFields
[ newLineListField "local-repo"
showTokenQ parseTokenQ
(fromNubList . globalLocalRepos)
(\v conf -> conf { globalLocalRepos = toNubList v })
]
. filterFields
[ "remote-repo-cache"
, "logs-dir", "world-file", "ignore-expiry", "http-transport"
]
. commandOptionsToFields
) (commandOptions (globalCommand []) ParseArgs)
++
( liftFields
legacyConfigureShFlags
(\flags conf -> conf { legacyConfigureShFlags = flags })
. addFields
[ simpleField "allow-newer"
(maybe mempty dispAllowNewer) (fmap Just parseAllowNewer)
configAllowNewer (\v conf -> conf { configAllowNewer = v })
]
. filterFields ["verbose"]
. commandOptionsToFields
) (configureOptions ParseArgs)
++
( liftFields
legacyConfigureExFlags
(\flags conf -> conf { legacyConfigureExFlags = flags })
. addFields
[ commaNewLineListField "constraints"
(disp . fst) (fmap (\constraint -> (constraint, constraintSrc)) parse)
configExConstraints (\v conf -> conf { configExConstraints = v })
, commaNewLineListField "preferences"
disp parse
configPreferences (\v conf -> conf { configPreferences = v })
]
. filterFields
[ "cabal-lib-version", "solver"
-- not "constraint" or "preference", we use our own plural ones above
]
. commandOptionsToFields
) (configureExOptions ParseArgs constraintSrc)
++
( liftFields
legacyInstallFlags
(\flags conf -> conf { legacyInstallFlags = flags })
. addFields
[ newLineListField "build-summary"
(showTokenQ . fromPathTemplate) (fmap toPathTemplate parseTokenQ)
(fromNubList . installSummaryFile)
(\v conf -> conf { installSummaryFile = toNubList v })
]
. filterFields
[ "doc-index-file"
, "root-cmd", "symlink-bindir"
, "build-log"
, "remote-build-reporting", "report-planning-failure"
, "one-shot", "jobs", "offline"
-- solver flags:
, "max-backjumps", "reorder-goals", "strong-flags"
]
. commandOptionsToFields
) (installOptions ParseArgs)
where
constraintSrc = ConstraintSourceProjectConfig "TODO"
parseAllowNewer :: ReadP r AllowNewer
parseAllowNewer =
((const AllowNewerNone <$> (Parse.string "none" +++ Parse.string "None"))
+++ (const AllowNewerAll <$> (Parse.string "all" +++ Parse.string "All")))
<++ ( AllowNewerSome <$> parseOptCommaList parse)
dispAllowNewer :: AllowNewer -> Doc
dispAllowNewer AllowNewerNone = Disp.text "None"
dispAllowNewer (AllowNewerSome pkgs) = Disp.fsep . Disp.punctuate Disp.comma
. map disp $ pkgs
dispAllowNewer AllowNewerAll = Disp.text "All"
legacyPackageConfigFieldDescrs :: [FieldDescr LegacyPackageConfig]
legacyPackageConfigFieldDescrs =
( liftFields
legacyConfigureFlags
(\flags conf -> conf { legacyConfigureFlags = flags })
. addFields
[ newLineListField "extra-include-dirs"
showTokenQ parseTokenQ
configExtraIncludeDirs
(\v conf -> conf { configExtraIncludeDirs = v })
, newLineListField "extra-lib-dirs"
showTokenQ parseTokenQ
configExtraLibDirs
(\v conf -> conf { configExtraLibDirs = v })
, newLineListField "extra-framework-dirs"
showTokenQ parseTokenQ
configExtraFrameworkDirs
(\v conf -> conf { configExtraFrameworkDirs = v })
, newLineListField "extra-prog-path"
showTokenQ parseTokenQ
(fromNubList . configProgramPathExtra)
(\v conf -> conf { configProgramPathExtra = toNubList v })
, newLineListField "configure-options"
showTokenQ parseTokenQ
configConfigureArgs
(\v conf -> conf { configConfigureArgs = v })
, simpleField "flags"
dispFlagAssignment parseFlagAssignment
configConfigurationsFlags
(\v conf -> conf { configConfigurationsFlags = v })
]
. filterFields
[ "compiler", "with-compiler", "with-hc-pkg"
, "program-prefix", "program-suffix"
, "library-vanilla", "library-profiling"
, "shared", "executable-dynamic"
, "profiling", "executable-profiling"
, "profiling-detail", "library-profiling-detail"
, "optimization", "debug-info", "library-for-ghci", "split-objs"
, "executable-stripping", "library-stripping"
, "tests", "benchmarks"
, "coverage", "library-coverage"
, "relocatable"
-- not "extra-include-dirs", "extra-lib-dirs", "extra-framework-dirs"
-- or "extra-prog-path". We use corrected ones above that parse
-- as list fields.
]
. commandOptionsToFields
) (configureOptions ParseArgs)
++
liftFields
legacyConfigureFlags
(\flags conf -> conf { legacyConfigureFlags = flags })
[ overrideFieldCompiler
, overrideFieldOptimization
, overrideFieldDebugInfo
]
++
( liftFields
legacyInstallPkgFlags
(\flags conf -> conf { legacyInstallPkgFlags = flags })
. filterFields
[ "documentation", "run-tests"
]
. commandOptionsToFields
) (installOptions ParseArgs)
++
( liftFields
legacyHaddockFlags
(\flags conf -> conf { legacyHaddockFlags = flags })
. mapFieldNames
("haddock-"++)
. filterFields
[ "hoogle", "html", "html-location"
, "executables", "tests", "benchmarks", "all", "internal", "css"
, "hyperlink-source", "hscolour-css"
, "contents-location", "keep-temp-files"
]
. commandOptionsToFields
) (haddockOptions ParseArgs)
where
overrideFieldCompiler =
simpleField "compiler"
(fromFlagOrDefault Disp.empty . fmap disp)
(Parse.option mempty (fmap toFlag parse))
configHcFlavor (\v flags -> flags { configHcFlavor = v })
-- TODO: [code cleanup] The following is a hack. The "optimization" and
-- "debug-info" fields are OptArg, and viewAsFieldDescr fails on that.
-- Instead of a hand-written parser and printer, we should handle this case
-- properly in the library.
overrideFieldOptimization =
liftField configOptimization
(\v flags -> flags { configOptimization = v }) $
let name = "optimization" in
FieldDescr name
(\f -> case f of
Flag NoOptimisation -> Disp.text "False"
Flag NormalOptimisation -> Disp.text "True"
Flag MaximumOptimisation -> Disp.text "2"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoOptimisation)
| str == "True" -> ParseOk [] (Flag NormalOptimisation)
| str == "0" -> ParseOk [] (Flag NoOptimisation)
| str == "1" -> ParseOk [] (Flag NormalOptimisation)
| str == "2" -> ParseOk [] (Flag MaximumOptimisation)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoOptimisation)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalOptimisation)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
overrideFieldDebugInfo =
liftField configDebugInfo (\v flags -> flags { configDebugInfo = v }) $
let name = "debug-info" in
FieldDescr name
(\f -> case f of
Flag NoDebugInfo -> Disp.text "False"
Flag MinimalDebugInfo -> Disp.text "1"
Flag NormalDebugInfo -> Disp.text "True"
Flag MaximalDebugInfo -> Disp.text "3"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoDebugInfo)
| str == "True" -> ParseOk [] (Flag NormalDebugInfo)
| str == "0" -> ParseOk [] (Flag NoDebugInfo)
| str == "1" -> ParseOk [] (Flag MinimalDebugInfo)
| str == "2" -> ParseOk [] (Flag NormalDebugInfo)
| str == "3" -> ParseOk [] (Flag MaximalDebugInfo)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoDebugInfo)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalDebugInfo)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
legacyPackageConfigSectionDescrs :: [SectionDescr LegacyProjectConfig]
legacyPackageConfigSectionDescrs =
[ packageRepoSectionDescr
, packageSpecificOptionsSectionDescr
, liftSection
legacyLocalConfig
(\flags conf -> conf { legacyLocalConfig = flags })
programOptionsSectionDescr
, liftSection
legacyLocalConfig
(\flags conf -> conf { legacyLocalConfig = flags })
programLocationsSectionDescr
, liftSection
legacySharedConfig
(\flags conf -> conf { legacySharedConfig = flags }) $
liftSection
legacyGlobalFlags
(\flags conf -> conf { legacyGlobalFlags = flags })
remoteRepoSectionDescr
]
packageRepoSectionDescr :: SectionDescr LegacyProjectConfig
packageRepoSectionDescr =
SectionDescr {
sectionName = "source-repository-package",
sectionFields = sourceRepoFieldDescrs,
sectionSubsections = [],
sectionGet = map (\x->("", x))
. legacyPackagesRepo,
sectionSet =
\lineno unused pkgrepo projconf -> do
unless (null unused) $
syntaxError lineno "the section 'source-repository-package' takes no arguments"
return projconf {
legacyPackagesRepo = legacyPackagesRepo projconf ++ [pkgrepo]
},
sectionEmpty = SourceRepo {
repoKind = RepoThis, -- hopefully unused
repoType = Nothing,
repoLocation = Nothing,
repoModule = Nothing,
repoBranch = Nothing,
repoTag = Nothing,
repoSubdir = Nothing
}
}
packageSpecificOptionsSectionDescr :: SectionDescr LegacyProjectConfig
packageSpecificOptionsSectionDescr =
SectionDescr {
sectionName = "package",
sectionFields = legacyPackageConfigFieldDescrs
++ programOptionsFieldDescrs
(configProgramArgs . legacyConfigureFlags)
(\args pkgconf -> pkgconf {
legacyConfigureFlags = (legacyConfigureFlags pkgconf) {
configProgramArgs = args
}
}
)
++ liftFields
legacyConfigureFlags
(\flags pkgconf -> pkgconf {
legacyConfigureFlags = flags
}
)
programLocationsFieldDescrs,
sectionSubsections = [],
sectionGet = \projconf ->
[ (display pkgname, pkgconf)
| (pkgname, pkgconf) <-
Map.toList . getMapMappend
. legacySpecificConfig $ projconf ],
sectionSet =
\lineno pkgnamestr pkgconf projconf -> do
pkgname <- case simpleParse pkgnamestr of
Just pkgname -> return pkgname
Nothing -> syntaxError lineno $
"a 'package' section requires a package name "
++ "as an argument"
return projconf {
legacySpecificConfig =
MapMappend $
Map.insertWith mappend pkgname pkgconf
(getMapMappend $ legacySpecificConfig projconf)
},
sectionEmpty = mempty
}
programOptionsFieldDescrs :: (a -> [(String, [String])])
-> ([(String, [String])] -> a -> a)
-> [FieldDescr a]
programOptionsFieldDescrs get set =
commandOptionsToFields
$ programConfigurationOptions
defaultProgramDb
ParseArgs get set
programOptionsSectionDescr :: SectionDescr LegacyPackageConfig
programOptionsSectionDescr =
SectionDescr {
sectionName = "program-options",
sectionFields = programOptionsFieldDescrs
configProgramArgs
(\args conf -> conf { configProgramArgs = args }),
sectionSubsections = [],
sectionGet = (\x->[("", x)])
. legacyConfigureFlags,
sectionSet =
\lineno unused confflags pkgconf -> do
unless (null unused) $
syntaxError lineno "the section 'program-options' takes no arguments"
return pkgconf {
legacyConfigureFlags = legacyConfigureFlags pkgconf <> confflags
},
sectionEmpty = mempty
}
programLocationsFieldDescrs :: [FieldDescr ConfigFlags]
programLocationsFieldDescrs =
commandOptionsToFields
$ programConfigurationPaths'
(++ "-location")
defaultProgramDb
ParseArgs
configProgramPaths
(\paths conf -> conf { configProgramPaths = paths })
programLocationsSectionDescr :: SectionDescr LegacyPackageConfig
programLocationsSectionDescr =
SectionDescr {
sectionName = "program-locations",
sectionFields = programLocationsFieldDescrs,
sectionSubsections = [],
sectionGet = (\x->[("", x)])
. legacyConfigureFlags,
sectionSet =
\lineno unused confflags pkgconf -> do
unless (null unused) $
syntaxError lineno "the section 'program-locations' takes no arguments"
return pkgconf {
legacyConfigureFlags = legacyConfigureFlags pkgconf <> confflags
},
sectionEmpty = mempty
}
-- | For each known program @PROG@ in 'progConf', produce a @PROG-options@
-- 'OptionField'.
programConfigurationOptions
:: ProgramDb
-> ShowOrParseArgs
-> (flags -> [(String, [String])])
-> ([(String, [String])] -> (flags -> flags))
-> [OptionField flags]
programConfigurationOptions progConf showOrParseArgs get set =
case showOrParseArgs of
-- we don't want a verbose help text list so we just show a generic one:
ShowArgs -> [programOptions "PROG"]
ParseArgs -> map (programOptions . programName . fst)
(knownPrograms progConf)
where
programOptions prog =
option "" [prog ++ "-options"]
("give extra options to " ++ prog)
get set
(reqArg' "OPTS" (\args -> [(prog, splitArgs args)])
(\progArgs -> [ joinsArgs args
| (prog', args) <- progArgs, prog==prog' ]))
joinsArgs = unwords . map escape
escape arg | any isSpace arg = "\"" ++ arg ++ "\""
| otherwise = arg
remoteRepoSectionDescr :: SectionDescr GlobalFlags
remoteRepoSectionDescr =
SectionDescr {
sectionName = "repository",
sectionFields = remoteRepoFields,
sectionSubsections = [],
sectionGet = map (\x->(remoteRepoName x, x)) . fromNubList
. globalRemoteRepos,
sectionSet =
\lineno reponame repo0 conf -> do
when (null reponame) $
syntaxError lineno $ "a 'repository' section requires the "
++ "repository name as an argument"
let repo = repo0 { remoteRepoName = reponame }
when (remoteRepoKeyThreshold repo
> length (remoteRepoRootKeys repo)) $
warning $ "'key-threshold' for repository "
++ show (remoteRepoName repo)
++ " higher than number of keys"
when (not (null (remoteRepoRootKeys repo))
&& remoteRepoSecure repo /= Just True) $
warning $ "'root-keys' for repository "
++ show (remoteRepoName repo)
++ " non-empty, but 'secure' not set to True."
return conf {
globalRemoteRepos = overNubList (++[repo]) (globalRemoteRepos conf)
},
sectionEmpty = emptyRemoteRepo ""
}
-------------------------------
-- Local field utils
--
--TODO: [code cleanup] all these utils should move to Distribution.ParseUtils
-- either augmenting or replacing the ones there
--TODO: [code cleanup] this is a different definition from listField, like
-- commaNewLineListField it pretty prints on multiple lines
newLineListField :: String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
newLineListField = listFieldWithSep Disp.sep
--TODO: [code cleanup] local copy purely so we can use the fixed version
-- of parseOptCommaList below
listFieldWithSep :: ([Doc] -> Doc) -> String -> (a -> Doc) -> ReadP [a] a
-> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
listFieldWithSep separator name showF readF get set =
liftField get set' $
ParseUtils.field name showF' (parseOptCommaList readF)
where
set' xs b = set (get b ++ xs) b
showF' = separator . map showF
--TODO: [code cleanup] local redefinition that should replace the version in
-- D.ParseUtils. This version avoid parse ambiguity for list element parsers
-- that have multiple valid parses of prefixes.
parseOptCommaList :: ReadP r a -> ReadP r [a]
parseOptCommaList p = Parse.sepBy p sep
where
-- The separator must not be empty or it introduces ambiguity
sep = (Parse.skipSpaces >> Parse.char ',' >> Parse.skipSpaces)
+++ (Parse.satisfy isSpace >> Parse.skipSpaces)
--TODO: [code cleanup] local redefinition that should replace the version in
-- D.ParseUtils called showFilePath. This version escapes "." and "--" which
-- otherwise are special syntax.
showTokenQ :: String -> Doc
showTokenQ "" = Disp.empty
showTokenQ x@('-':'-':_) = Disp.text (show x)
showTokenQ x@('.':[]) = Disp.text (show x)
showTokenQ x = showToken x
-- This is just a copy of parseTokenQ, using the fixed parseHaskellString
parseTokenQ :: ReadP r String
parseTokenQ = parseHaskellString
<++ Parse.munch1 (\x -> not (isSpace x) && x /= ',')
--TODO: [code cleanup] use this to replace the parseHaskellString in
-- Distribution.ParseUtils. It turns out Read instance for String accepts
-- the ['a', 'b'] syntax, which we do not want. In particular it messes
-- up any token starting with [].
parseHaskellString :: ReadP r String
parseHaskellString =
Parse.readS_to_P $
Read.readPrec_to_S (do Read.String s <- Read.lexP; return s) 0
-- Handy util
addFields :: [FieldDescr a]
-> ([FieldDescr a] -> [FieldDescr a])
addFields = (++)
| tolysz/prepare-ghcjs | spec-lts8/cabal/cabal-install/Distribution/Client/ProjectConfig/Legacy.hs | bsd-3-clause | 51,073 | 0 | 22 | 14,893 | 8,512 | 4,859 | 3,653 | 975 | 8 |
module GameEngine.Graphics.BezierSurface
( tessellatePatch
) where
import Control.Monad
import Data.List (foldl')
import Data.Vect.Float hiding (Vector)
import Data.Vect.Float.Instances
import Data.Vector (Vector,(!))
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import GameEngine.Data.BSP
{-
See more:
http://graphics.cs.brown.edu/games/quake/quake3.html#RenderPatch
-}
tessellate :: Vector DrawVertex -> Int -> (Vector DrawVertex,Vector Int)
tessellate controls level = (v,stripsI)
where
plus (DrawVertex p1 d1 l1 n1 c1) (DrawVertex p2 d2 l2 n2 c2) = DrawVertex (p1 + p2) (d1 + d2) (l1 + l2) (n1 + n2) (c1 + c2)
mult (DrawVertex p d l n c) f = DrawVertex (p &* f) (d &* f) (l &* f) (n &* f) (c &* f)
mix a c0 c1 c2 = let b = 1 - a in (c0 `mult` (b * b)) `plus` (c1 `mult` (2 * b * a)) `plus` (c2 `mult` (a * a))
l1 = level + 1
v = V.create $ do
vertex <- MV.new (l1*l1)
forM_ [0..level] $ \i -> let a = fromIntegral i / fromIntegral level in MV.write vertex i $ mix a (controls ! 0) (controls ! 3) (controls ! 6)
forM_ [1..level] $ \i -> do
let a = fromIntegral i / fromIntegral level
c0 = mix a (controls ! 0) (controls ! 1) (controls ! 2)
c1 = mix a (controls ! 3) (controls ! 4) (controls ! 5)
c2 = mix a (controls ! 6) (controls ! 7) (controls ! 8)
forM_ [0..level] $ \j -> let a' = fromIntegral j / fromIntegral level in MV.write vertex (i * l1 + j) $ mix a' c0 c1 c2
return vertex
-- merge triangle strips using degenerate triangles
idx row col2 | col2 `mod` 2 == 1 = (row + 1) * l1 + col2 `div` 2
| otherwise = row * l1 + col2 `div` 2
strips = [V.generate (l1*2) (idx row) | row <- [0..level-1]]
separate (a:b:c:xs) = a:b:c:separate (b:c:xs)
separate [] = []
trisI = V.concat [V.fromList $ separate $ V.toList s | s <- strips]
stripsI = V.concat [V.concat [h,s,l] | s <- strips -- concatenated triangle strips using degenerated triangles
, let h = V.singleton $ V.head s -- degenerate triangles will be shown in line polygon mode
, let l = V.singleton $ V.last s
]
tessellatePatch :: V.Vector DrawVertex -> Surface -> Int -> (V.Vector DrawVertex,V.Vector Int)
tessellatePatch drawV sf level = (V.concat vl,V.concat il)
where
(w,h) = srPatchSize sf
gridF :: [DrawVertex] -> [[DrawVertex]]
gridF l = case splitAt w l of
(x,[]) -> [x]
(x,xs) -> x:gridF xs
grid = gridF $ V.toList $ V.take (srNumVertices sf) $ V.drop (srFirstVertex sf) drawV
controls = [V.fromList $ concat [take 3 $ drop x l | l <- lines] | x <- [0,2..w-3], y <- [0,2..h-3], let lines = take 3 $ drop y grid]
patches = [tessellate c level | c <- controls]
(vl,il) = unzip $ reverse $ snd $ foldl' (\(o,l) (v,i) -> (o+V.length v, (v,V.map (+o) i):l)) (0,[]) patches
| csabahruska/quake3 | game-engine/GameEngine/Graphics/BezierSurface.hs | bsd-3-clause | 3,004 | 0 | 22 | 827 | 1,430 | 760 | 670 | 46 | 2 |
module Foo() where
-- check various type synonym expansions.
type XChar = Char
xc :: XChar
xc = 'x'
type Foo = Int
type Bar = Foo
type Bug x = Char
type App f x = f (Bug x)
type Fun = App Bug (Bug Char)
f :: Foo -> Int
f = id
--(x :: Foo) = 4
y = (1 + 4 :: Bar) `div` 3
z = 'z' :: Fun
w = let f = 'z' :: App Bug Foo in 4
class Baz a where
g :: a -> Bar
instance Baz (Bug (Bug String)) where
g = fromEnum
data Bob = Fred String
data Rob = Frod { frodString :: String }
| hvr/jhc | regress/tests/1_typecheck/2_pass/TypeSynonym.hs | mit | 483 | 0 | 9 | 133 | 212 | 123 | 89 | 20 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module PackageTests.DeterministicAr.Check where
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Char (isSpace)
import Data.List
#if __GLASGOW_HASKELL__ < 710
import Data.Traversable
#endif
import PackageTests.PackageTester
import System.Exit
import System.FilePath
import System.IO
import Test.Tasty.HUnit (Assertion, assertFailure)
import Distribution.Compiler (CompilerFlavor(..), CompilerId(..))
import Distribution.Package (packageKeyHash)
import Distribution.Version (Version(..))
import Distribution.Simple.Compiler (compilerId)
import Distribution.Simple.Configure (getPersistBuildConfig)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo, compiler, pkgKey)
-- Perhaps these should live in PackageTester.
-- For a polymorphic @IO a@ rather than @Assertion = IO ()@.
assertFailure' :: String -> IO a
assertFailure' msg = assertFailure msg >> return {-unpossible!-}undefined
ghcPkg_field :: String -> String -> FilePath -> IO [FilePath]
ghcPkg_field libraryName fieldName ghcPkgPath = do
(cmd, exitCode, raw) <- run Nothing ghcPkgPath []
["--user", "field", libraryName, fieldName]
let output = filter ('\r' /=) raw -- Windows
-- copypasta of PackageTester.requireSuccess
unless (exitCode == ExitSuccess) . assertFailure $
"Command " ++ cmd ++ " failed.\n" ++ "output: " ++ output
let prefix = fieldName ++ ": "
case traverse (stripPrefix prefix) (lines output) of
Nothing -> assertFailure' $ "Command " ++ cmd ++ " failed: expected "
++ show prefix ++ " prefix on every line.\noutput: " ++ output
Just fields -> return fields
ghcPkg_field1 :: String -> String -> FilePath -> IO FilePath
ghcPkg_field1 libraryName fieldName ghcPkgPath = do
fields <- ghcPkg_field libraryName fieldName ghcPkgPath
case fields of
[field] -> return field
_ -> assertFailure' $ "Command ghc-pkg field failed: "
++ "output not a single line.\noutput: " ++ show fields
------------------------------------------------------------------------
this :: String
this = "DeterministicAr"
suite :: FilePath -> FilePath -> Assertion
suite ghcPath ghcPkgPath = do
let dir = "PackageTests" </> this
let spec = PackageSpec
{ directory = dir
, configOpts = []
, distPref = Nothing
}
unregister this ghcPkgPath
iResult <- cabal_install spec ghcPath
assertInstallSucceeded iResult
let distBuild = dir </> "dist" </> "build"
libdir <- ghcPkg_field1 this "library-dirs" ghcPkgPath
lbi <- getPersistBuildConfig (dir </> "dist")
mapM_ (checkMetadata lbi) [distBuild, libdir]
unregister this ghcPkgPath
-- Almost a copypasta of Distribution.Simple.Program.Ar.wipeMetadata
checkMetadata :: LocalBuildInfo -> FilePath -> Assertion
checkMetadata lbi dir = withBinaryFile path ReadMode $ \ h -> do
hFileSize h >>= checkArchive h
where
path = dir </> "libHS" ++ this ++ "-0"
++ (if ghc_7_10 then ("-" ++ packageKeyHash (pkgKey lbi)) else "")
++ ".a"
ghc_7_10 = case compilerId (compiler lbi) of
CompilerId GHC version | version >= Version [7, 10] [] -> True
_ -> False
checkError msg = assertFailure' $
"PackageTests.DeterministicAr.checkMetadata: " ++ msg ++
" in " ++ path
archLF = "!<arch>\x0a" -- global magic, 8 bytes
x60LF = "\x60\x0a" -- header magic, 2 bytes
metadata = BS.concat
[ "0 " -- mtime, 12 bytes
, "0 " -- UID, 6 bytes
, "0 " -- GID, 6 bytes
, "0644 " -- mode, 8 bytes
]
headerSize = 60
-- http://en.wikipedia.org/wiki/Ar_(Unix)#File_format_details
checkArchive :: Handle -> Integer -> IO ()
checkArchive h archiveSize = do
global <- BS.hGet h (BS.length archLF)
unless (global == archLF) $ checkError "Bad global header"
checkHeader (toInteger $ BS.length archLF)
where
checkHeader :: Integer -> IO ()
checkHeader offset = case compare offset archiveSize of
EQ -> return ()
GT -> checkError (atOffset "Archive truncated")
LT -> do
header <- BS.hGet h headerSize
unless (BS.length header == headerSize) $
checkError (atOffset "Short header")
let magic = BS.drop 58 header
unless (magic == x60LF) . checkError . atOffset $
"Bad magic " ++ show magic ++ " in header"
unless (metadata == BS.take 32 (BS.drop 16 header))
. checkError . atOffset $ "Metadata has changed"
let size = BS.take 10 $ BS.drop 48 header
objSize <- case reads (BS8.unpack size) of
[(n, s)] | all isSpace s -> return n
_ -> checkError (atOffset "Bad file size in header")
let nextHeader = offset + toInteger headerSize +
-- Odd objects are padded with an extra '\x0a'
if odd objSize then objSize + 1 else objSize
hSeek h AbsoluteSeek nextHeader
checkHeader nextHeader
where
atOffset msg = msg ++ " at offset " ++ show offset
| Helkafen/cabal | Cabal/tests/PackageTests/DeterministicAr/Check.hs | bsd-3-clause | 5,495 | 0 | 23 | 1,563 | 1,370 | 700 | 670 | 105 | 7 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fa-IR">
<title>Python Scripting</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> | thc202/zap-extensions | addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_fa_IR/helpset_fa_IR.hs | apache-2.0 | 970 | 98 | 27 | 156 | 390 | 207 | 183 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>Call Graph</title>
<maps>
<homeID>callgraph</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/callgraph/src/main/javahelp/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 961 | 94 | 29 | 156 | 394 | 209 | 185 | -1 | -1 |
module Data.Map.Base (trim) where
data Map k a = Tip
{-@ data Map k a <l :: root:k -> k -> Prop>
= Tip
@-}
{-@ measure isBin :: Map k a -> Prop
isBin (Tip) = false
@-}
trim :: Map k a
trim = error "TODO"
| mightymoose/liquidhaskell | tests/pos/record1.hs | bsd-3-clause | 236 | 0 | 5 | 80 | 41 | 25 | 16 | 4 | 1 |
module Handler.CommentSpec (spec) where
import TestImport
import Data.Aeson
spec :: Spec
spec = withApp $ do
describe "valid request" $ do
it "gives a 200" $ do
get HomeR
statusIs 200
let message = "My message" :: Text
body = object [ "message" .= message ]
encoded = encode body
request $ do
setMethod "POST"
setUrl CommentR
setRequestBody encoded
addRequestHeader ("Content-Type", "application/json")
addTokenFromCookie
statusIs 200
[Entity _id comment] <- runDB $ selectList [CommentMessage ==. message] []
assertEqual "Should have " comment (Comment message Nothing)
describe "invalid requests" $ do
it "400s when the JSON body is invalid" $ do
get HomeR
let body = object [ "foo" .= ("My message" :: Value) ]
request $ do
setMethod "POST"
setUrl CommentR
setRequestBody $ encode body
addRequestHeader ("Content-Type", "application/json")
addTokenFromCookie
statusIs 400
| Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes | yesod/test/Handler/CommentSpec.hs | gpl-3.0 | 1,244 | 0 | 20 | 499 | 298 | 135 | 163 | 32 | 1 |
{-# LANGUAGE CPP #-}
----------------------------------------------------------------------------
--
-- Pretty-printing of common Cmm types
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
--
-- This is where we walk over Cmm emitting an external representation,
-- suitable for parsing, in a syntax strongly reminiscent of C--. This
-- is the "External Core" for the Cmm layer.
--
-- As such, this should be a well-defined syntax: we want it to look nice.
-- Thus, we try wherever possible to use syntax defined in [1],
-- "The C-- Reference Manual", http://www.cminusminus.org/. We differ
-- slightly, in some cases. For one, we use I8 .. I64 for types, rather
-- than C--'s bits8 .. bits64.
--
-- We try to ensure that all information available in the abstract
-- syntax is reproduced, or reproducible, in the concrete syntax.
-- Data that is not in printed out can be reconstructed according to
-- conventions used in the pretty printer. There are at least two such
-- cases:
-- 1) if a value has wordRep type, the type is not appended in the
-- output.
-- 2) MachOps that operate over wordRep type are printed in a
-- C-style, rather than as their internal MachRep name.
--
-- These conventions produce much more readable Cmm output.
--
-- A useful example pass over Cmm is in nativeGen/MachCodeGen.hs
--
{-# OPTIONS_GHC -fno-warn-orphans #-}
module PprCmmDecl
( writeCmms, pprCmms, pprCmmGroup, pprSection, pprStatic
)
where
import PprCmmExpr
import Cmm
import DynFlags
import Outputable
import FastString
import Data.List
import System.IO
-- Temp Jan08
import SMRep
#include "../includes/rts/storage/FunTypes.h"
pprCmms :: (Outputable info, Outputable g)
=> [GenCmmGroup CmmStatics info g] -> SDoc
pprCmms cmms = pprCode CStyle (vcat (intersperse separator $ map ppr cmms))
where
separator = space $$ ptext (sLit "-------------------") $$ space
writeCmms :: (Outputable info, Outputable g)
=> DynFlags -> Handle -> [GenCmmGroup CmmStatics info g] -> IO ()
writeCmms dflags handle cmms = printForC dflags handle (pprCmms cmms)
-----------------------------------------------------------------------------
instance (Outputable d, Outputable info, Outputable i)
=> Outputable (GenCmmDecl d info i) where
ppr t = pprTop t
instance Outputable CmmStatics where
ppr = pprStatics
instance Outputable CmmStatic where
ppr = pprStatic
instance Outputable CmmInfoTable where
ppr = pprInfoTable
-----------------------------------------------------------------------------
pprCmmGroup :: (Outputable d, Outputable info, Outputable g)
=> GenCmmGroup d info g -> SDoc
pprCmmGroup tops
= vcat $ intersperse blankLine $ map pprTop tops
-- --------------------------------------------------------------------------
-- Top level `procedure' blocks.
--
pprTop :: (Outputable d, Outputable info, Outputable i)
=> GenCmmDecl d info i -> SDoc
pprTop (CmmProc info lbl live graph)
= vcat [ ppr lbl <> lparen <> rparen <+> ptext (sLit "// ") <+> ppr live
, nest 8 $ lbrace <+> ppr info $$ rbrace
, nest 4 $ ppr graph
, rbrace ]
-- --------------------------------------------------------------------------
-- We follow [1], 4.5
--
-- section "data" { ... }
--
pprTop (CmmData section ds) =
(hang (pprSection section <+> lbrace) 4 (ppr ds))
$$ rbrace
-- --------------------------------------------------------------------------
-- Info tables.
pprInfoTable :: CmmInfoTable -> SDoc
pprInfoTable (CmmInfoTable { cit_lbl = lbl, cit_rep = rep
, cit_prof = prof_info
, cit_srt = _srt })
= vcat [ ptext (sLit "label:") <+> ppr lbl
, ptext (sLit "rep:") <> ppr rep
, case prof_info of
NoProfilingInfo -> empty
ProfilingInfo ct cd -> vcat [ ptext (sLit "type:") <+> pprWord8String ct
, ptext (sLit "desc: ") <> pprWord8String cd ] ]
instance Outputable C_SRT where
ppr NoC_SRT = ptext (sLit "_no_srt_")
ppr (C_SRT label off bitmap)
= parens (ppr label <> comma <> ppr off <> comma <> ppr bitmap)
instance Outputable ForeignHint where
ppr NoHint = empty
ppr SignedHint = quotes(text "signed")
-- ppr AddrHint = quotes(text "address")
-- Temp Jan08
ppr AddrHint = (text "PtrHint")
-- --------------------------------------------------------------------------
-- Static data.
-- Strings are printed as C strings, and we print them as I8[],
-- following C--
--
pprStatics :: CmmStatics -> SDoc
pprStatics (Statics lbl ds) = vcat ((ppr lbl <> colon) : map ppr ds)
pprStatic :: CmmStatic -> SDoc
pprStatic s = case s of
CmmStaticLit lit -> nest 4 $ ptext (sLit "const") <+> pprLit lit <> semi
CmmUninitialised i -> nest 4 $ text "I8" <> brackets (int i)
CmmString s' -> nest 4 $ text "I8[]" <+> text (show s')
-- --------------------------------------------------------------------------
-- data sections
--
pprSection :: Section -> SDoc
pprSection s = case s of
Text -> section <+> doubleQuotes (text "text")
Data -> section <+> doubleQuotes (text "data")
ReadOnlyData -> section <+> doubleQuotes (text "readonly")
ReadOnlyData16 -> section <+> doubleQuotes (text "readonly16")
RelocatableReadOnlyData
-> section <+> doubleQuotes (text "relreadonly")
UninitialisedData -> section <+> doubleQuotes (text "uninitialised")
OtherSection s' -> section <+> doubleQuotes (text s')
where
section = ptext (sLit "section")
| siddhanathan/ghc | compiler/cmm/PprCmmDecl.hs | bsd-3-clause | 5,727 | 0 | 15 | 1,244 | 1,216 | 634 | 582 | 78 | 7 |
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
-- Trac #2714
module T2714 where
f :: ((a -> b) -> b) -> (forall c. c -> a)
f = ffmap
ffmap :: Functor f => (p->q) -> f p -> f q
ffmap = error "urk"
{-
a ~ f q
c ~ f p
(p->q) ~ (a->b) -> b
=>
a ~ f q
c ~ f p
p ~ a->b
q ~ b
=>
a ~ f b
c ~ f (a->b)
-} | urbanslug/ghc | testsuite/tests/typecheck/should_fail/T2714.hs | bsd-3-clause | 358 | 0 | 9 | 141 | 88 | 49 | 39 | 6 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
module T3101 where
type family F a :: *
data Boom = Boom (forall a. a -> F a)
deriving Show
| urbanslug/ghc | testsuite/tests/deriving/should_fail/T3101.hs | bsd-3-clause | 155 | 0 | 10 | 34 | 42 | 26 | 16 | 6 | 0 |
module MathSpec where
import Test.Hspec
import Math
main :: IO()
main = hspec $ do
describe "absolute" $ do
it "returns the original number when given a positiv integer" $
absolute 1 `shouldBe` 1
it "returns the negated result when given a negative integer" $
absolute (-1) `shouldBe` 1
it "returns zero if given integer 0" $
absolute 0 `shouldBe` 0
| Sgoettschkes/learning | haskell/LearnYouAHaskell/old/MathSpec.hs | mit | 416 | 0 | 15 | 127 | 103 | 52 | 51 | 12 | 1 |
{-# LANGUAGE TupleSections #-}
module SoOSiM.CLI.Util
( mapAccumLM
, mapAccumRM
)
where
import Control.Applicative (Applicative(..))
import Control.Monad.State (StateT(..))
import Data.Traversable (Traversable(..))
-- | The 'mapAccumLM' function behaves like a combination of 'fmap'
-- and 'foldl' in a monadic context; it applies a function to each
-- element of a structure, passing an accumulating parameter from
-- left to right, and returning a final value of this accumulator
-- together with the new structure.
mapAccumLM ::
(Monad m, Functor m, Traversable t)
=> (a -> b -> m (c,a))
-> a
-> t b
-> m (t c, a)
mapAccumLM f s t = runStateT (traverse (StateT . flip f) t) s
-- |The 'mapAccumRM' function behaves like a combination of 'fmap'
-- and 'foldr' in a monadic context; it applies a function to each
-- element of a structure, passing an accumulating parameter from
-- right to left, and returning a final value of this accumulator
-- together with the new structure.
mapAccumRM ::
(Monad m, Functor m, Traversable t)
=> (a -> b -> m (c,a))
-> a
-> t b
-> m (t c, a)
mapAccumRM f s t = runStateTR (traverse (StateTR . flip f) t) s
newtype StateTR s m a = StateTR { runStateTR :: s -> m (a, s) }
instance Functor m => Functor (StateTR s m) where
fmap f m = StateTR $ \s ->
fmap (\(~(a,s')) -> (f a, s')) $ runStateTR m s
instance (Functor m, Monad m) => Applicative (StateTR s m) where
pure x = StateTR (return . (x,))
StateTR kf <*> StateTR kv = StateTR $ \s -> do
~(v,s') <- kv s
~(f,s'') <- kf s'
return (f v, s'')
| christiaanb/SoOSiM-cli | src/SoOSiM/CLI/Util.hs | mit | 1,592 | 0 | 14 | 346 | 523 | 283 | 240 | 31 | 1 |
module Pwn.Tubes.Tube where
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.MVar
import Control.Monad (when)
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import qualified Data.Conduit as C
import qualified Data.Conduit.Binary as C (sinkHandle, sourceHandle)
import System.IO (stdin, stdout)
import Pwn.Config
import Pwn.Log
class Tube a where
recv :: MonadPwn m => a -> m BS.ByteString
recvn :: MonadPwn m => a -> Int -> m BS.ByteString
send :: MonadPwn m => a -> BS.ByteString -> m ()
isEOF :: MonadPwn m => a -> m Bool
source :: a -> C.ConduitT () BS.ByteString IO ()
sink :: a -> C.ConduitT BS.ByteString C.Void IO ()
wait :: MonadPwn m => a -> m ()
close :: MonadPwn m => a -> m ()
shutdown :: MonadPwn m => a -> m ()
recvline :: (MonadPwn m, Tube a) => a -> m BS.ByteString
recvline tube = recvuntil tube $ BS.singleton '\n'
recvuntil :: (MonadPwn m, Tube a) => a -> BS.ByteString -> m BS.ByteString
recvuntil tube suff = recvuntil' BS.empty
where recvuntil' buf = do
newbuf <- BS.append buf <$> recvn tube 1
if BS.isSuffixOf suff newbuf then return newbuf
else recvuntil' newbuf
sendline :: (MonadPwn m, Tube a) => a -> BS.ByteString -> m ()
sendline tube = send tube . appendNL
where appendNL = flip BS.snoc '\n'
interactive :: (MonadPwn m, Tube a) => a -> m ()
interactive tube = do
info "Entering interactive mode"
r <- liftIO $ do
mv <- newEmptyMVar
rx <- forkIO $ do
source tube `C.connect` C.sinkHandle stdout
putMVar mv True
tx <- forkIO $ do
C.sourceHandle stdin `C.connect` sink tube
putMVar mv False
takeMVar mv <* mapM_ killThread [rx, tx]
when r $ warning "Connection may be closed"
info "Leaving interactive mode"
| Tosainu/pwn.hs | src/Pwn/Tubes/Tube.hs | mit | 1,967 | 0 | 17 | 566 | 711 | 357 | 354 | 46 | 2 |
{-# LANGUAGE NoMonomorphismRestriction
#-}
module Plugins.Gallery.Gallery.Manual40 where
import Diagrams.Prelude
import Graphics.Rendering.Diagrams.Points
ts = mconcat . take 3 . iterate (rotateBy (1/9)) $ eqTriangle 1
example = (ts ||| stroke ts ||| strokeT ts ||| fromVertices ts) # fc red
| andrey013/pluginstest | Plugins/Gallery/Gallery/Manual40.hs | mit | 304 | 0 | 11 | 51 | 96 | 51 | 45 | 6 | 1 |
-- GENERATED by C->Haskell Compiler, version 0.16.4 Crystal Seed, 24 Jan 2009 (Haskell)
-- Edit the ORIGNAL .chs file instead!
{-# LINE 1 "Scene.chs" #-}{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# context lib="hyd" #-}
module Hyd.Scene where
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Control.Monad
import Control.Applicative
import Data.Functor
data HydScene = HydScene
{ {-#entities'hyd_scene :: Ptr ()
, sprites'hyd_scene :: Ptr ()#-}
}
instance Storable HydScene where
sizeOf _ = 32
{-# LINE 22 "Scene.chs" #-}
alignment _ = 8
{-# LINE 23 "Scene.chs" #-}
peek p = HydScene
{-#<$> ({#get hyd_scene->entities #} p)
<*> ({#get hyd_scene->sprites #} p)#-}
poke p x = do
{-#{#set hyd_scene.entities #} p (entities'hyd_scene x)
{#set hyd_scene.sprites #} p (sprites'hyd_scene x)#-}
type HydScenePtr = Ptr (HydScene)
{-# LINE 31 "Scene.chs" #-}
withT = with
hydSceneCreate :: IO (HydScene)
hydSceneCreate =
hydSceneCreate'_ >>= \res ->
withT res >>= \res' ->
return (res')
{-# LINE 36 "Scene.chs" #-}
hydSceneCreateFile :: String -> Ptr () -> Ptr () -> IO (HydScene)
hydSceneCreateFile a1 a2 a3 =
withCString a1 $ \a1' ->
let {a2' = id a2} in
let {a3' = id a3} in
hydSceneCreateFile'_ a1' a2' a3' >>= \res ->
withT res >>= \res' ->
return (res')
{-# LINE 42 "Scene.chs" #-}
hydSceneDestroy :: HydScene -> IO ()
hydSceneDestroy a1 =
withT a1 $ \a1' ->
hydSceneDestroy'_ a1' >>= \res ->
return ()
{-# LINE 45 "Scene.chs" #-}
hydSceneDraw :: HydScene -> Ptr () -> IO ()
hydSceneDraw a1 a2 =
withT a1 $ \a1' ->
let {a2' = id a2} in
hydSceneDraw'_ a1' a2' >>= \res ->
return ()
{-# LINE 48 "Scene.chs" #-}
foreign import ccall safe "Scene.chs.h hyd_scene_create"
hydSceneCreate'_ :: (IO (HydScenePtr))
foreign import ccall safe "Scene.chs.h hyd_scene_create_file"
hydSceneCreateFile'_ :: ((Ptr CChar) -> ((Ptr ()) -> ((Ptr ()) -> (IO (HydScenePtr)))))
foreign import ccall safe "Scene.chs.h hyd_scene_destroy"
hydSceneDestroy'_ :: ((HydScenePtr) -> (IO ()))
foreign import ccall safe "Scene.chs.h hyd_scene_draw"
hydSceneDraw'_ :: ((HydScenePtr) -> ((Ptr ()) -> (IO ())))
| Smilex/hyd_engine | bindings/haskell/Hyd/Scene.hs | mit | 2,210 | 43 | 14 | 406 | 597 | 327 | 270 | -1 | -1 |
module Main (main) where
import Prelude hiding (mapM, concat)
import qualified Control.Arrow as A
import Control.Monad hiding (mapM)
import Control.Exception
import Options.Applicative
import Data.Tuple.Homogenous
import Data.Foldable
import Data.Traversable
import Text.PrettyPrint.Mainland as PP
import Parser
import Reduce
import Equality
import Ast
data Options = Options
{ oIncludes :: [FilePath]
, oFuel :: Int
, oMode :: Mode
}
data Mode
= Reduce (Term String)
| Equal (Tuple2 (Term String)) (Maybe Int)
termReader :: ReadM (Term String)
termReader = eitherReader $ A.left show . parseExpr "<cmdline>"
main :: IO ()
main = work =<< execParser opts
where
opts = info (helper <*> optsParser)
( fullDesc <> header "Lambda equivalence prover" )
optsParser =
Options
<$> many (strOption (long "include" <> short 'i' <> metavar "FILE"))
<*> option auto (long "fuel" <> value 10 <> metavar "NUM" <> help "Iteration limit (default: 10)")
<*> modeParser
modeParser = asum
[ Reduce <$> option termReader (long "reduce" <> metavar "TERM")
, Equal <$ flag' () (long "equal")
<*> (sequenceA . pure $ argument termReader (metavar "TERM"))
<*> optional (option auto (long "size-limit" <> metavar "NUM" <> help "Do not consider terms that are larger than NUM"))
]
work :: Options -> IO ()
work Options{..} = do
decls <- liftM concat $ mapM (either (throwIO . ErrorCall . show) return <=< parseDeclsFile) oIncludes
let lkp = lookupFromDecls decls
case oMode of
Reduce term ->
case nf lkp oFuel term of
Just term' -> print term'
Nothing -> putStrLn "No reduced form found"
Equal terms mbLimit ->
case equal lkp oFuel mbLimit terms of
Nothing -> putStrLn "Could not prove equality"
Just reds ->
let
Tuple2 (doc1, doc2) =
(</>) <$>
(ppr <$> terms) <*>
(ppr <$> reds)
in
case untuple2 reds of
([], []) -> putStrLn "Terms are α-equivalent"
(_, []) -> putDoc doc1
([], _ ) -> putDoc doc2
_ -> putDoc $ doc1 </> line <> doc2
| feuerbach/prover | src/Main.hs | mit | 2,216 | 0 | 20 | 621 | 729 | 374 | 355 | -1 | -1 |
{-|
Module: Flaw.UI.Label
Description: One-line centered text label.
License: MIT
-}
module Flaw.UI.Label
( Label(..)
, LabelStyle(..)
, newLabel
, newTextLabel
, newTitleLabel
, renderLabel
) where
import Control.Concurrent.STM
import qualified Data.Text as T
import Flaw.Graphics
import Flaw.Graphics.Font
import Flaw.Graphics.Font.Render
import Flaw.Math
import Flaw.UI
import Flaw.UI.Drawer
data Label = Label
{ labelTextVar :: !(TVar T.Text)
, labelTextScriptVar :: !(TVar FontScript)
, labelStyle :: !LabelStyle
}
data LabelStyle
= LabelStyleText
| LabelStyleButton
| LabelStyleTitle
newLabel :: LabelStyle -> STM Label
newLabel style = do
textVar <- newTVar T.empty
textScriptVar <- newTVar fontScriptUnknown
return Label
{ labelTextVar = textVar
, labelTextScriptVar = textScriptVar
, labelStyle = style
}
newTextLabel :: STM Label
newTextLabel = newLabel LabelStyleText
newTitleLabel :: STM Label
newTitleLabel = newLabel LabelStyleTitle
instance Visual Label where
renderVisual Label
{ labelTextVar = textVar
, labelTextScriptVar = textScriptVar
, labelStyle = lstyle
} drawer position size style = do
text <- readTVar textVar
textScript <- readTVar textScriptVar
return $ renderLabel text textScript lstyle drawer position size style
instance HasText Label where
setText Label
{ labelTextVar = textVar
} = writeTVar textVar
setTextScript Label
{ labelTextScriptVar = textScriptVar
} = writeTVar textScriptVar
getText Label
{ labelTextVar = textVar
} = readTVar textVar
{-# INLINABLE renderLabel #-}
renderLabel :: Context c d => T.Text -> FontScript -> LabelStyle -> Drawer d -> Position -> Size -> Style -> Render c ()
renderLabel text textScript style Drawer
{ drawerGlyphRenderer = glyphRenderer
, drawerStyles = styles
} (Vec2 px py) (Vec2 sx sy) Style
{ styleTextColor = color
} = do
(DrawerFont
{ drawerFontRenderableFontCache = renderableFontCache
, drawerFontShaper = SomeFontShaper fontShaper
}, alignmentX, alignmentY) <- return $ case style of
LabelStyleText -> (drawerLabelFont styles, AlignLeft, AlignMiddle)
LabelStyleButton -> (drawerLabelFont styles, AlignCenter, AlignMiddle)
LabelStyleTitle -> (drawerTitleFont styles, AlignLeft, AlignMiddle)
let
(x, cursorX) = case alignmentX of
AlignLeft -> (fromIntegral px, RenderTextCursorLeft)
AlignCenter -> (fromIntegral px + fromIntegral sx * 0.5, RenderTextCursorCenter)
AlignRight -> (fromIntegral px + fromIntegral sx, RenderTextCursorRight)
(y, cursorY) = case alignmentY of
AlignTop -> (fromIntegral py, RenderTextCursorTop)
AlignMiddle -> (fromIntegral py + fromIntegral sy * 0.5, RenderTextCursorMiddle)
AlignBottom -> (fromIntegral py + fromIntegral sy, RenderTextCursorBottom)
renderGlyphs glyphRenderer renderableFontCache $
renderTexts fontShaper [(text, color)] textScript (Vec2 x y) cursorX cursorY
| quyse/flaw | flaw-ui/Flaw/UI/Label.hs | mit | 2,993 | 0 | 16 | 574 | 811 | 432 | 379 | 85 | 7 |
module Proteome.Data.AddError where
import Ribosome.Data.ErrorReport (ErrorReport(ErrorReport))
import Ribosome.Error.Report.Class (ReportError(..))
import System.Log.Logger (Priority(NOTICE))
newtype AddError =
InvalidProjectSpec Text
deriving stock (Eq, Show)
deepPrisms ''AddError
instance ReportError AddError where
errorReport (InvalidProjectSpec spec) =
ErrorReport ("no such project: " <> spec) ["AddError.InvalidProjectSpec:", spec] NOTICE
| tek/proteome | packages/proteome/lib/Proteome/Data/AddError.hs | mit | 462 | 0 | 8 | 55 | 124 | 73 | 51 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- The main entry point for the application.
module Main where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
#endif
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Char8 as BC (pack)
import Data.Maybe (fromMaybe, isJust)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack, unpack)
import qualified Database.Redis as Redis
import Network.Wai.Middleware.Static
import System.Environment (lookupEnv)
import Web.Scotty.Hastache (scottyH', setTemplatesDir)
import Web.Scotty.Trans (file, get, middleware)
import qualified Controllers.Urls as UrlsCtrl (loadRoutes)
main :: IO ()
main = do
port <- read <$> (fromMaybe "3000" <$> lookupEnv "PORT")
host <- T.pack <$>
(fromMaybe ("http://localhost:" <> show port) <$> lookupEnv "HOST")
let hostname = host <> ":" <> T.pack (show port)
liftIO $
putStrLn $ "Starting server at " ++ T.unpack hostname
!info <- getRedisConnectInfo
!conn <- Redis.connect info
let Redis.PortNumber pn = Redis.connectPort info
in liftIO $
putStrLn $
"Redis connection expected at " ++ Redis.connectHost info ++
":" ++ show pn
liftIO . putStrLn $ if isJust (Redis.connectAuth info)
then "Redis Authentication configured"
else "Redis Authentication not configured"
scottyH' port $ do
setTemplatesDir "templates"
middleware $ staticPolicy (noDots >-> addBase "static")
get "/" $ file "static/index.html"
UrlsCtrl.loadRoutes host conn
getRedisConnectInfo :: IO Redis.ConnectInfo
getRedisConnectInfo = do
!redisHost <- "REDIS_HOST" `fromEnvWithDefault` "127.0.0.1"
!redisPort <- read <$> "REDIS_PORT" `fromEnvWithDefault` "6379" :: IO Int
!mRedisAuthString <- lookupEnv "REDIS_AUTH"
let !mRedisAuth = BC.pack <$> mRedisAuthString
return $ Redis.defaultConnectInfo { Redis.connectHost = redisHost
, Redis.connectPort = Redis.PortNumber $
fromIntegral redisPort
, Redis.connectAuth = mRedisAuth
}
where
fromEnvWithDefault e d = fromMaybe d <$> lookupEnv e
| yamadapc/hshort | src/Main.hs | mit | 2,600 | 0 | 14 | 846 | 592 | 309 | 283 | 50 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, TupleSections, GADTs #-}
module Day14 where
import AdventPrelude
import qualified Crypto.Hash.MD5 as MD5
import Data.Text.Format hiding (print)
salt :: String
-- salt = "abc"
salt = "ahsbgdzn"
hashes :: [Text]
hashes =
(repack .
concat .
map (\b -> format "{}" (Only $ left 2 '0' (hex b))) .
unpack .
MD5.hash .
fromString . (salt <>) . show) <$> [0..]
isGood :: Text -> [Text] -> Bool
isGood h hs = (not . null) $ do
a <- threeX (unpack h)
let as = replicate 5 a
ts = take 1000 hs
guard (any (isInfixOf as) ts)
pure a
where threeX (a: rs@(b:c:rs'))
| a == b && a == c = [a]
| otherwise = threeX rs
threeX _ = []
filterGood :: [(Int, Text)] -> [(Int, Text)]
filterGood (h:hs)
| isGood (snd h) (snd <$> hs) = h : filterGood hs
| otherwise = filterGood hs
filterGood _ = []
result1 = (filterGood (zip [0..] hashes)) !! (64 - 1)
hashes' :: [Text]
hashes' =
(decodeUtf8 .
stretch 2017 .
fromString . (salt <>) . show) <$> [0..]
where stretch :: Int -> ByteString -> ByteString
stretch 0 h = h
stretch i h = let h' =
encodeUtf8 .
toStrict .
concat .
map (format "{}" . (Only . left 2 '0' . hex )) .
unpack $
MD5.hash h
in h' `seq` stretch (i-1) h'
result2 = take 64 (zip [1..] (filterGood (zip [0..] hashes')))
| farrellm/advent-2016 | src/Day14.hs | mit | 1,547 | 0 | 21 | 534 | 640 | 336 | 304 | 48 | 2 |
module LLVM.AbcOps (OpCode(..)) where
import Data.Word
import LLVM.Lang
import qualified Abc.Def as Abc
data OpCode = {- 0x01 -} Breakpoint
| {- 0x02 -} Nop
| {- 0x03 -} Throw
| {- 0x04 -} GetSuper Abc.MultinameIdx (Maybe String)
| {- 0x05 -} SetSuper Abc.MultinameIdx (Maybe String)
| {- 0x06 -} DefaultXmlNamespace Abc.U30
| {- 0x07 -} DefaultXmlNamespaceL
| {- 0x08 -} Kill Abc.U30
| {- 0x09 -} Label
{- 0x0A -}
{- 0x0B -}
| {- 0x0C -} IfNotLessThan Label Label
| {- 0x0D -} IfNotLessEqual Label Label
| {- 0x0E -} IfNotGreaterThan Label Label
| {- 0x0F -} IfNotGreaterEqual Label Label
| {- 0x10 -} Jump Label
| {- 0x11 -} IfTrue Label Label
| {- 0x12 -} IfFalse Label Label
| {- 0x13 -} IfEqual Label Label
| {- 0x14 -} IfNotEqual Label Label
| {- 0x15 -} IfLessThan Label Label
| {- 0x16 -} IfLessEqual Label Label
| {- 0x17 -} IfGreaterThan Label Label
| {- 0x18 -} IfGreaterEqual Label Label
| {- 0x19 -} IfStrictEqual Label Label
| {- 0x1A -} IfStrictNotEqual Label Label
| {- 0x1B -} LookupSwitch Label [Label] {- default offset, case offsets -}
| {- 0x1C -} PushWith
| {- 0x1D -} PopScope
| {- 0x1E -} NextName
| {- 0x1F -} HasNext
| {- 0x20 -} PushNull
| {- 0x21 -} PushUndefined
| {- 0x22 -} PushConstant
| {- 0x23 -} NextValue
| {- 0x24 -} PushByte Abc.U8
| {- 0x25 -} PushShort Abc.U30
| {- 0x26 -} PushTrue
| {- 0x27 -} PushFalse
| {- 0x28 -} PushNaN
| {- 0x29 -} Pop
| {- 0x2A -} Dup
| {- 0x2B -} Swap
| {- 0x2C -} PushString String
| {- 0x2D -} PushInt Abc.S32
| {- 0x2E -} PushUInt Abc.U32
| {- 0x2F -} PushDouble Double
| {- 0x30 -} PushScope
| {- 0x31 -} PushNamespace Abc.NSInfoIdx
| {- 0x32 -} HasNext2 Word32 Word32
| {- 0x33 -} PushDecimal
| {- 0x34 -} PushDNaN
{- 0x35 -}
{- 0x36 -}
{- 0x37 -}
{- 0x38 -}
{- 0x39 -}
{- 0x3A -}
{- 0x3B -}
{- 0x3C -}
{- 0x3D -}
{- 0x3E -}
{- 0x3F -}
| {- 0x40 -} NewFunction Abc.U30
| {- 0x41 -} Call Abc.U30
| {- 0x42 -} Construct Abc.U30
| {- 0x43 -} CallMethod Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x44 -} CallStatic Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x45 -} CallSuper Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x46 -} CallProperty Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x47 -} ReturnVoid
| {- 0x48 -} ReturnValue
| {- 0x49 -} ConstructSuper Abc.U30
| {- 0x4A -} ConstructProp Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x4B -} CallSuperId
| {- 0x4C -} CallPropLex Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x4D -} CallInterface
| {- 0x4E -} CallSuperVoid Abc.MultinameIdx Abc.U30 (Maybe String)
| {- 0x4F -} CallPropVoid Abc.MultinameIdx Abc.U30 (Maybe String)
{- 0x50 -}
{- 0x51 -}
{- 0x52 -}
| {- 0x53 -} ApplyType
{- 0x53 -}
| {- 0x55 -} NewObject Abc.U30
| {- 0x56 -} NewArray Abc.U30
| {- 0x57 -} NewActivation
| {- 0x58 -} NewClass Abc.ClassInfoIdx
| {- 0x59 -} GetDescendants Abc.MultinameIdx (Maybe String)
| {- 0x5A -} NewCatch Abc.ExceptionIdx
| {- 0x5B -} FindPropGlobalStrict
| {- 0x5C -} FindPropGlobal
| {- 0x5D -} FindPropStrict Abc.MultinameIdx (Maybe String)
| {- 0x5E -} FindProperty Abc.MultinameIdx (Maybe String)
| {- 0x5F -} FindDef
| {- 0x60 -} GetLex Abc.MultinameIdx (Maybe String)
| {- 0x61 -} SetProperty Abc.MultinameIdx (Maybe String)
| {- 0x62 -} GetLocal Int
| {- 0x63 -} SetLocal Int
| {- 0x64 -} GetGlobalScope
| {- 0x65 -} GetScopeObject Abc.U8
| {- 0x66 -} GetProperty Abc.MultinameIdx (Maybe String)
| {- 0x67 -} GetPropertyLate
| {- 0x68 -} InitProperty Abc.MultinameIdx (Maybe String)
| {- 0x69 -} SetPropertyLate
| {- 0x6A -} DeleteProperty Abc.MultinameIdx (Maybe String)
| {- 0x6B -} DeletePropertyLate
| {- 0x6C -} GetSlot Abc.U30
| {- 0x6D -} SetSlot Abc.U30
| {- 0x6E -} GetGlobalSlot Abc.U30
| {- 0x6F -} SetGlobalSlot Abc.U30
| {- 0x70 -} ConvertString
| {- 0x71 -} EscXmlElem
| {- 0x72 -} EscXmlAttr
| {- 0x73 -} ConvertInt
| {- 0x74 -} ConvertUInt
| {- 0x75 -} ConvertDouble
| {- 0x76 -} ConvertBoolean
| {- 0x77 -} ConvertObject
| {- 0x78 -} CheckFilter
{- 0x79 -}
{- 0x7A -}
{- 0x7B -}
{- 0x7C -}
{- 0x7D -}
{- 0x7E -}
{- 0x7F -}
| {- 0x80 -} Coerce Abc.MultinameIdx (Maybe String)
| {- 0x81 -} CoerceBoolean
| {- 0x82 -} CoerceAny
| {- 0x83 -} CoerceInt
| {- 0x84 -} CoerceDouble
| {- 0x85 -} CoerceString
| {- 0x86 -} AsType Abc.MultinameIdx (Maybe String)
| {- 0x87 -} AsTypeLate
| {- 0x88 -} CoerceUInt
| {- 0x89 -} CoerceObject
{- 0x8A -}
{- 0x8B -}
{- 0x8C -}
{- 0x8D -}
{- 0x8E -}
{- 0x8F -}
| {- 0x90 -} Negate
| {- 0x91 -} Increment
| {- 0x92 -} IncLocal Abc.U30
| {- 0x93 -} Decrement
| {- 0x94 -} DecLocal Abc.U30
| {- 0x95 -} TypeOf
| {- 0x96 -} Not
| {- 0x97 -} BitNot
{- 0x98 -}
{- 0x99 -}
| {- 0x9A -} Concat
| {- 0x9B -} AddDouble
{- 0x9C -}
{- 0x9D -}
{- 0x9E -}
{- 0x9F -}
| {- 0xA0 -} Add
| {- 0xA1 -} Subtract
| {- 0xA2 -} Multiply
| {- 0xA3 -} Divide
| {- 0xA4 -} Modulo
| {- 0xA5 -} ShiftLeft
| {- 0xA6 -} ShiftRight
| {- 0xA7 -} ShiftRightUnsigned
| {- 0xA8 -} BitAnd
| {- 0xA9 -} BitOr
| {- 0xAA -} BitXor
| {- 0xAB -} Equals
| {- 0xAC -} StrictEquals
| {- 0xAD -} LessThan
| {- 0xAE -} LessEquals
| {- 0xAF -} GreaterThan
| {- 0xB0 -} GreaterEquals
| {- 0xB1 -} InstanceOf
| {- 0xB2 -} IsType Abc.MultinameIdx (Maybe String)
| {- 0xB3 -} IsTypeLate
| {- 0xB4 -} In
{- 0xB5 -}
{- 0xB6 -}
{- 0xB7 -}
{- 0xB8 -}
{- 0xB9 -}
{- 0xBA -}
{- 0xBB -}
{- 0xBC -}
{- 0xBD -}
{- 0xBE -}
{- 0xBF -}
| {- 0xC0 -} IncrementInt
| {- 0xC1 -} DecrementInt
{- 0xC2 -}
{- 0xC3 -}
| {- 0xC4 -} NegateInt
| {- 0xC5 -} AddInt
| {- 0xC6 -} SubtractInt
| {- 0xC7 -} MultiplyInt
{- 0xC8 -}
{- 0xC9 -}
{- 0xCA -}
{- 0xCB -}
{- 0xCC -}
{- 0xCD -}
{- 0xCE -}
{- 0xCF -}
{- 0xD0 -}
{- 0xD1 -}
{- 0xD2 -}
{- 0xD3 -}
{- 0xD4 -}
{- 0xD5 -}
{- 0xD6 -}
{- 0xD7 -}
{- 0xD8 -}
{- 0xD9 -}
{- 0xDA -}
{- 0xDB -}
{- 0xDC -}
{- 0xDD -}
{- 0xDE -}
{- 0xDF -}
{- 0xE0 -}
{- 0xE1 -}
{- 0xE2 -}
{- 0xE3 -}
{- 0xE4 -}
{- 0xE5 -}
{- 0xE6 -}
{- 0xE7 -}
{- 0xE8 -}
{- 0xE9 -}
{- 0xEA -}
{- 0xEB -}
{- 0xEC -}
{- 0xED -}
{- 0xEE -} {-abs_jump-}
| {- 0xEF -} Debug Abc.U8 Abc.StringIdx Abc.U8 Abc.U30
| {- 0xF0 -} DebugLine Abc.U30
| {- 0xF1 -} DebugFile Abc.StringIdx
| {- 0xF2 -} BreakpointLine
{- 0xF3 -} {-timestamp-}
{- 0xF4 -}
{- 0xF5 -} {-verifypass-}
{- 0xF6 -} {-alloc-}
{- 0xF7 -} {-mark-}
{- 0xF8 -} {-wb-}
{- 0xF9 -} {-prologue-}
{- 0xFA -} {-sendenter-}
{- 0xFB -} {-doubletoatom-}
{- 0xFC -} {-sweep-}
{- 0xFD -} {-codegenop-}
{- 0xFE -} {-verifyop-}
{- 0xFF -} {-decode-}
| phylake/avm3 | llvm/abcops.hs | mit | 9,579 | 0 | 8 | 4,515 | 1,241 | 838 | 403 | 158 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import Lens.Family
import Graphics.Badge.Barrier
import Test.Tasty
import Test.Tasty.Golden
main :: IO ()
main = defaultMain $ testGroup ""
[ testGroup "flat"
[ goldenVsString "1" "tests/data/flat/1.svg" . return $ renderBadge flat "build" "success"
, goldenVsString "2" "tests/data/flat/2.svg" . return $ renderBadge (flat & right .~ red) "build" "failing"
, goldenVsString "3" "tests/data/flat/3.svg" . return $ renderBadge (flat & left .~ green) "leaf" "leaf"
, goldenVsString "4" "tests/data/flat/4.svg" . return $ renderBadge flat "longlonglonglonglonglonglonglonglonglonglonglong" "longlonglonglonglonglonglonglonglonglonglonglong"
]
, testGroup "flatSquare"
[ goldenVsString "1" "tests/data/flatSquare/1.svg" . return $ renderBadge flatSquare "build" "success"
, goldenVsString "2" "tests/data/flatSquare/2.svg" . return $ renderBadge (flatSquare & right .~ red) "build" "failing"
, goldenVsString "3" "tests/data/flatSquare/3.svg" . return $ renderBadge (flatSquare & left .~ green) "leaf" "leaf"
, goldenVsString "4" "tests/data/flatSquare/4.svg" . return $ renderBadge flatSquare "longlonglonglonglonglonglonglonglonglonglonglong" "longlonglonglonglonglonglonglonglonglonglonglong"
]
, testGroup "plastic"
[ goldenVsString "1" "tests/data/plastic/1.svg" . return $ renderBadge plastic "build" "success"
, goldenVsString "2" "tests/data/plastic/2.svg" . return $ renderBadge (plastic & right .~ red) "build" "failing"
, goldenVsString "3" "tests/data/plastic/3.svg" . return $ renderBadge (plastic & left .~ green) "leaf" "leaf"
, goldenVsString "4" "tests/data/plastic/4.svg" . return $ renderBadge plastic "longlonglonglonglonglonglonglonglonglonglonglong" "longlonglonglonglonglonglonglonglonglonglonglong"
]
]
| philopon/barrier | tests/tasty.hs | mit | 1,896 | 0 | 14 | 329 | 414 | 207 | 207 | 22 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Tests
where
import Data.Char (isAlpha)
import Test.Framework.TH (defaultMainGenerator)
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit ((@=?))
import WordTools (isNotAlpha, hasAlpha, takeUntil)
main = $(defaultMainGenerator)
case_isNotAlpha_1 = do False @=? isNotAlpha 'a'
case_isNotAlpha_2 = do False @=? isNotAlpha 'Z'
case_isNotAlpha_3 = do False @=? isNotAlpha 'ä'
case_isNotAlpha_4 = do True @=? isNotAlpha ' '
case_isNotAlpha_5 = do True @=? isNotAlpha '.'
case_isNotAlpha_6 = do True @=? isNotAlpha '5'
case_hasAlpha_1 = do False @=? hasAlpha ""
case_hasAlpha_2 = do False @=? hasAlpha " .'%9,_/"
case_hasAlpha_lower_a = do True @=? hasAlpha "!#¤%&a()"
case_hasAlpha_unicode = do True @=? hasAlpha "+-*/Ä,. "
case_hasAlpha_allalfa = do True @=? hasAlpha "AllAlpha"
case_takeUntil_empty = do "" @=? takeUntil isAlpha ""
case_takeUntil_one = do "Z" @=? takeUntil isAlpha "Z"
case_takeUntil_one_false = do "." @=? takeUntil isAlpha "."
case_takeUntil_first = do "A" @=?takeUntil isAlpha "A--Z"
case_takeUntil_never = do "+-*/" @=? takeUntil isAlpha "+-*/"
| akaihola/palindromi-haskell | src/Tests.hs | mit | 1,197 | 0 | 8 | 178 | 336 | 172 | 164 | 25 | 1 |
evaluate :: Num a => [String] -> [a]
evaluate ("add":h1:h2:t) = ((read h1) + (read h2)):evaluate t
worker = do
input <- getLine
putStrLn $ show . evaluate . words $ input
worker
main = worker
| teodorlu/ballmer | calc/calc.hs | gpl-2.0 | 197 | 0 | 10 | 41 | 111 | 56 | 55 | 7 | 1 |
module Main where
import Scanner
import System.Environment
main :: IO ()
main = do
args <- getArgs
let fileName = args !! 0
fileContents <- readFile fileName
putStrLn $ show $ scanTokens fileContents
| yangsiwei880813/CS644 | src/JMain.hs | gpl-2.0 | 210 | 0 | 10 | 43 | 71 | 35 | 36 | 9 | 1 |
-- some includes
import Network.HTTP
import Network.URI
import Text.HTML.TagSoup
import Data.Dates hiding (Day)
import Data.List
import Text.Printf
import Control.Monad
import qualified Codec.Binary.UTF8.String as UTF8
-----------------------------
-- some datatypes used for clarity
data Menu = Menu {
name :: String,
desc :: String,
price :: String
} deriving (Eq)
instance Show Menu where
show (Menu n d _) = printf "%s: %s" n d
data Day = Day {
date :: String,
menus :: [Menu]
}
instance Show Day where
show (Day d ms) = printf "%s:\n\n%s" d ms'
where ms' = intercalate "\n" $ map show ms
-----------------------------
-- | read in a page from an url and decode it from utf8
-- | (no idea why simpleHTTP doesn't do this)
openURL :: String -> IO String
openURL url = fmap UTF8.decodeString pageSource
where (Just uri) = parseURI url
request = mkRequest GET uri
pageSource = getResponseBody =<< simpleHTTP request
uniMensaURL = "http://www.studentenwerkbielefeld.de/index.php?id=61"
fhMensaURL = "http://www.studentenwerkbielefeld.de/index.php?id=63"
-----------------------------
-- the actual page parsing (effectivly only 14 lines and that is without much magic)
findDayBlocks :: [Tag String] -> [[Tag String]]
findDayBlocks = partitions (~== "<div class=day-block>")
parseDayInfo :: [Tag String] -> String
parseDayInfo d = fromTagText $ sections (~== "<a class=day-information>") d !! 0 !! 1
parseDayMenues :: [Tag String] -> [Menu]
parseDayMenues d = map parseMenuData $ partitions (~== "<tr>") d
parseMenuData :: [Tag String] -> Menu
parseMenuData m = Menu n d p
where columns = partitions (\t -> (t ~== "<th>") || (t ~== "<td>" )) m
[n, d, p] = map (unwords . words . innerText) columns
parseMenues :: [Tag String] -> [Day]
parseMenues tags = zipWith Day n m
where b = findDayBlocks tags
n = map parseDayInfo b
m = map parseDayMenues b
getMenues :: String -> IO [Day]
getMenues url = do
src <- openURL url
let tags = parseTags src
return $ parseMenues tags
-----------------------------
-- | get the current day as a number (Monday -> 1)
dayOfWeek :: IO Int
dayOfWeek = fmap (weekdayNumber . dateWeekDay) getCurrentDateTime
-----------------------------
-- | plug it all together
main :: IO ()
main = do
d <- dayOfWeek
when (d > 5) $ error "What are you doing here? It's weekend!"
uniMenues <- getMenues uniMensaURL
fhMenues <- getMenues fhMensaURL
putStrLn "\n --- Uni Plan --- "
print $ uniMenues !! (d - 1)
putStrLn "\n --- FH Plan --- "
print $ fhMenues !! (d - 1)
| fhaust/mensaplan | Mensaplan.hs | gpl-3.0 | 2,633 | 6 | 10 | 555 | 759 | 398 | 361 | 60 | 1 |
module Decks where
import Cards
mixed =
[ dog,
catOrDog,
dragon,
catFactory,
masterOfGreed,
buff
]
pets =
[ dog,
dog,
dog,
cat,
cat,
cat,
dragon,
dragon,
dragon
] | MoritzR/CurseOfDestiny | src/Decks.hs | gpl-3.0 | 225 | 0 | 5 | 90 | 62 | 41 | 21 | 19 | 1 |
module Server (
main,
mainTest,
lookupHandlerServer
) where
import Text.Parsec hiding (Error)
import qualified PupEventsServer as Server
import System.Environment
import Events
import Control.Concurrent.STM
import qualified Data.UUID as UUID2
import qualified Data.UUID.V4 as UUIDV4
import Data.List
import Control.Concurrent
import System.Random
import Data.Maybe
-- |Main entry point. You should pass in the address to connect to and
-- the number of priority levels desired.
main :: IO ()
main =
do args <- getArgs
let ip = args !! 0
let priorities = read (args !! 1) :: Int
games <- newTVarIO [] :: IO (TVar [Game])
usernames <- newTVarIO [] :: IO (TVar [Username])
playerInfos <- newTVarIO [] :: IO (TVar [(ThreadId, Username, Maybe Game)])
Server.server (Just ip) priorities "1267" lookupPriority lookupUnHandler (lookupHandlerServer games usernames playerInfos) parsers (Just (Logout (Username "")))
-- | Main method used for testing, it returns the state variables and an IO action to actually start the server.
mainTest :: String -> IO (TVar [Game], TVar [Username], TVar [(ThreadId, Username, Maybe Game)], IO b)
mainTest port =
do args <- getArgs
let ip = args !! 0
let priorities = read (args !! 1) :: Int
games <- newTVarIO [] :: IO (TVar [Game])
usernames <- newTVarIO [] :: IO (TVar [Username])
playerInfos <- newTVarIO [] :: IO (TVar [(ThreadId, Username, Maybe Game)])
let runnable = Server.server (Just ip) priorities port lookupPriority lookupUnHandler (lookupHandlerServer games usernames playerInfos) parsers (Just (Logout (Username "")))
return (games, usernames, playerInfos, runnable)
------------------
-- GamesRequest --
------------------
--gameRequestHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gameRequestHandlerServer games e@(GamesRequest) =
-- do gamelist <- readTVarIO games
-- return (GamesList gamelist)
-----------------
---- GamesList --
-----------------
--gamesListHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gamesListHandlerServer games e@(GamesList list) = return e
-----------------
---- GameLeave --
-----------------
--gameLeaveHandlerServer :: TVar [(ThreadId, Player)] -> TVar [(Game)] -> Event -> IO Event
--gameLeaveHandlerServer usernames games e@(GameLeave player game) =
-- do usernames' <- readTVarIO usernames
-- games' <- readTVarIO games
-- let pExists = find ((==) player . playerUsername . snd) usernames'
-- let gExists = find ((==) game) games'
-- if and $ map isJust [pExists, gExists]
-- then atomically $ modifyTVar games $ removePlayerFromGame (fromJust pExists) (fromJust gExists)
-- else return e -- TODO Unable to join game!
-- return e
-- where
-- removePlayerFromGame player game games =
-- (:) (newgame game) (delete game games)
-- where
-- newgame game' =
-- Game { gameUuid = (gameUuid game')
-- , gameAlive = delete player (gameAlive game')
-- , gameDead = gameDead game'
-- , gameStatus = gameStatus game'
-- , gameDifficulty = gameDifficulty game'
-- , gameStarted = gameStarted game'
-- , gameEnded = gameEnded game'
-- }
-----------------------
---- PlayerCollision --
-----------------------
--playerCollisionHandlerServer :: TVar [(Game)] -> Event -> IO Event
--playerCollisionHandlerServer games e@(PlayerCollision game usernames) = return e
---------------
---- GameEnd --
---------------
--gameEndHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gameEndHandlerServer games e@(GameEnd game) =
-- do games' <- readTVarIO games
-- let gExists = find ((==) game . gameUuid) games'
-- if isJust gExists
-- then atomically $ modifyTVar games $ endGame (fromJust gExists)
-- else return e -- TODO Unable to end game!
-- return e
-- where
-- endGame game games =
-- (:) (ended game) (delete game games)
-- where
-- ended game' =
-- Game { gameUuid = (gameUuid game')
-- , gameAlive = (gameAlive game')
-- , gameDead = gameDead game'
-- , gameStatus = Ended
-- , gameDifficulty = gameDifficulty game'
-- , gameStarted = gameStarted game'
-- , gameEnded = gameEnded game'
-- }
-------------------
---- GameAdvance --
-------------------
--gameAdvanceHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gameAdvanceHandlerServer games e@(GameAdvance game) = return e
-----------------
---- GameStart --
-----------------
--gameStartHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gameStartHandlerServer games e@(GameStart game) =
-- do games' <- readTVarIO games
-- let gExists = find ((==) game . gameUuid) games'
-- if isJust gExists
-- then atomically $ modifyTVar games $ startGame (fromJust gExists)
-- else return e -- TODO Unable to start game!
-- return e
-- where
-- startGame game games =
-- (:) (started game) (delete game games)
-- where
-- started game' =
-- Game { gameUuid = (gameUuid game')
-- , gameAlive = (gameAlive game')
-- , gameDead = gameDead game'
-- , gameStatus = InProgress
-- , gameDifficulty = gameDifficulty game'
-- , gameStarted = gameStarted game'
-- , gameEnded = gameEnded game'
-- }
----------------
---- GameJoin --
----------------
---- make sure game/player exists, then add player to game's alive/dead list
--gameJoinHandlerServer :: TVar [(ThreadId, Player)] -> TVar [(Game)] -> Event -> IO Event
--gameJoinHandlerServer usernames games e@(GameJoin player (UUID game)) =
-- do usernames' <- readTVarIO usernames
-- games' <- readTVarIO games
-- let pExists = find ((==) player . playerUsername) usernames'
-- let gExists = find ((==) game . gameUuid) games'
-- if and $ map isJust [pExists, gExists]
-- then atomically $ modifyTVar games $ addPlayerToGame (fromJust pExists) (fromJust gExists)
-- else return e -- TODO Unable to join game!
-- return e
-- where
-- addPlayerToGame player game games =
-- (:) (newgame game) (delete game games)
-- where
-- newgame game' =
-- Game { gameUuid = (gameUuid game')
-- , gameAlive = (setRandomPosition player):(gameAlive game')
-- , gameDead = gameDead game'
-- , gameStatus = gameStatus game'
-- , gameDifficulty = gameDifficulty game'
-- , gameStarted = gameStarted game'
-- , gameEnded = gameEnded game'
-- }
---------------
---- GameNew --
---------------
--gameNewHandlerServer :: TVar [(Game)] -> Event -> IO Event
--gameNewHandlerServer games e@(GameNew usernames) =
-- do x <- UUIDV4.nextRandom
-- let uuid = UUID2.toString x
-- let usernames' = mapM (setRandomPosition) usernames
-- let game = Game { gameUuid = (UUID uuid)
-- , gameAlive = Just usernames'
-- , gameDead = Just []
-- , gameStatus = Just Created
-- , gameDifficulty = Just 0
-- , gameStarted = Nothing
-- , gameEnded = Nothing
-- }
-- atomically $ modifyTVar games ((:) game)
-- return e
-----------------
---- MouseMove --
-----------------
--mouseMoveHandlerServer :: TVar [(Game)] -> Event -> IO Event
--mouseMoveHandlerServer games e@(MouseMove p1 p2) = return e
-----------
-- Login --
-----------
-- | Check if the requested username exists or if the user has already registered ( previous registration is signaled by this thread being in the list of playerInfos). If both of those are false than we log the user in.
loginHandlerServer :: TVar [Username] -> TVar [(ThreadId, Username, Maybe Game)] -> Event -> IO Event
loginHandlerServer usernames playerInfos e@(Login user) =
do threadid <- myThreadId
-- we do this in one atomically block so we can't have the available usernames/playerInfos change on us.
atomically $
do usernames' <- readTVar usernames
playerInfos' <- readTVar playerInfos
-- if any of the conditions are true than the user can't log in
if or [snd c | c <- conditions threadid usernames' playerInfos']
then
-- this finds the first error code that has a True condition. The use only gets one error code so he can get rid of them one by one if there are multiple errors
return $ maybe (Error GenericError) (Error . fst) (find ((==) True . snd) (conditions threadid usernames' playerInfos'))
else
-- add the user to the list of usernames and the (threadid, user, Nothing) to the playerinfos.
do modifyTVar usernames (\x -> user:x)
modifyTVar playerInfos (\x -> (threadid, user, Nothing):x)
return e
where
-- conditions, we return the error code which corresponds to a True value as well as whether or not the condition is satisfied
conditions t u p= [(UserExists, userExists u), (AlreadyRegistered, alreadyRegistered t p)]
-- check if the user is in a list of users
userExists = elem user
-- check if this threadid is in a list that has threadids
alreadyRegistered t = isJust . (find (\(x, _, _) -> x == t))
------------
-- Logout --
------------
-- | Check if the user is currently logged in, and if he is log him out.
logoutHandlerServer :: TVar [Username] -> TVar [(ThreadId, Username, Maybe Game)] -> Event -> IO Event
logoutHandlerServer usernames playerInfos e@(Logout _) =
do threadid <- myThreadId
-- we do this in one atomically block so we can't have the available usernames/playerInfos change on us.
atomically $
do usernames' <- readTVar usernames
playerInfos' <- readTVar playerInfos
-- attempt to find ourself in the playerInfos list
let pInfo = find (\(x, _, _) -> x == threadid) playerInfos'
-- If we found something then we're logged in, log us out, if not return the NotLoggedIn Error.
case pInfo of
Just pI@(_, user, _) ->
do modifyTVar usernames (delete user)
-- we need to use our own predicate to delete a playerInfo
modifyTVar playerInfos (deleteBy (\(t, _, _) (t', _, _) -> t == t') pI)
return e
Nothing -> return $ Error NotLoggedIn
-- |Returns the specified Event's handler function. This has a weird type signature because it's returning a function.
lookupHandlerServer :: TVar [Game]
-> TVar [Username]
-> TVar [(ThreadId, Username, Maybe Game)]
-> Event -> (Event -> IO Event)
--lookupHandlerServer _ games (MouseMove _ _ ) = mouseMoveHandlerServer games
lookupHandlerServer games usernames playerInfos (Login _ ) =
loginHandlerServer usernames playerInfos
lookupHandlerServer games usernames playerInfos (Logout _ ) =
logoutHandlerServer usernames playerInfos
--lookupHandlerServer _ games (GameNew _ ) = gameNewHandlerServer games
--lookupHandlerServer usernames games (GameJoin _ _ ) = gameJoinHandlerServer usernames games
--lookupHandlerServer usernames games (GameLeave _ _ ) = gameLeaveHandlerServer usernames games
--lookupHandlerServer _ games (GameStart _ ) = gameStartHandlerServer games
--lookupHandlerServer _ games (GameAdvance _ ) = gameAdvanceHandlerServer games
--lookupHandlerServer _ games (GameEnd _ ) = gameEndHandlerServer games
--lookupHandlerServer _ games (PlayerCollision _ _ ) = playerCollisionHandlerServer games
---- Helper functions
--setRandomPosition (Player username _ )=
-- do randX <- randomRIO ((-1.0), 1.0)
-- randY <- randomRIO ((-1.0), 1.0)
-- let randPos = (randX, randY)
-- return (Player username randPos)
| RocketPuppy/PupCollide | Server/Server.hs | gpl-3.0 | 12,961 | 0 | 20 | 3,941 | 1,436 | 829 | 607 | 69 | 2 |
{- Printing utilities.
-
- Copyright 2013 Raúl Benencia <rul@kalgan.cc>
-
- Licensed under the GNU GPL version 3 or higher
-
-}
module Lazymail.Print where
import Data.Char (isSpace)
import Data.List (intercalate)
import Lazymail.Email
import Codec.Text.Rfc1342
import Lazymail.Types(Flag(..), Flags, ComposeFields(..), ComposeState(..))
unquote xs= if (head xs == '"' && last xs == '"') then (tail . init) xs else xs
ppField = flat . decodeField
{- Pretty print a RFC822 date format -}
fromLen :: Int
fromLen = 20
maxFlags :: Int
maxFlags = 4
flat xs = intercalate " " $ map (dropWhile isSpace) $ map (filter (/= '\r')) $ lines xs
ppFlags :: Flags -> String
ppFlags = map ppFlag
ppFlag :: Flag -> Char
ppFlag NEW = 'N'
ppFlag SEEN = 'S'
ppFlag ANSWERED = 'A'
ppFlag FLAGGED = 'F'
ppFlag DRAFT = 'D'
ppFlag FORWARDED = 'P'
ppFlag DELETED = 'T'
ppFlag (OTHERFLAG [c]) = c
ppComposeState cs = ppComposeFields False (composeFields cs) ++
[("Body file name: " ++) $ maybe "-" id $ bodyFileName cs]
ppComposeFields removeEmpty cf | removeEmpty == False = l
| otherwise = filter (\str -> (last str) /= '-') l
where l = [ ("From: " ++) $ maybe "-" id $ fromField cf
, ("To: " ++) $ maybe "-" id $ toField cf
, ("Cc: " ++) $ maybe "-" id $ ccField cf
, ("Bcc: " ++) $ maybe "-" id $ bccField cf
, ("Reply-To: " ++) $ maybe "-" id $ replyToField cf
, ("Subject: " ++) $ maybe "-" id $ subjectField cf
]
ppSep = " "
normalizeLen len cs | (length cs > len) = shorten len cs
| otherwise = if (length cs < len)
then fillWithSpace len cs
else cs
fillWithSpace len cs = cs ++ (take (len - length cs) . repeat $ ' ')
-- The following functions are from DynamicLog xmonad-contrib source
-- | Wrap a string in delimiters, unless it is empty.
wrap :: String -- ^ left delimiter
-> String -- ^ right delimiter
-> String -- ^ output string
-> String
wrap _ _ "" = ""
wrap l r m = l ++ m ++ r
-- | Pad a string with a leading and trailing space.
pad :: String -> String
pad = wrap " " " "
-- | Trim leading and trailing whitespace from a string.
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
-- | Limit a string to a certain length, adding "..." if truncated.
shorten :: Int -> String -> String
shorten n xs | length xs < n = xs
| otherwise = take (n - length end) xs ++ end
where
end = "..."
| rul/lazymail | src/Lazymail/Print.hs | gpl-3.0 | 2,609 | 0 | 12 | 765 | 821 | 431 | 390 | 55 | 2 |
data BinOpType = Add
| Subtract
| Multiply
| Divide
deriving (Show)
data UnOpType = Negate
deriving (Show)
data Expr = BinaryExpr BinOpType Expr Expr
| UnaryExpr UnOpType Expr
| IntegerLiteral Int
deriving (Show)
left (BinaryExpr _ left _) = left
right (BinaryExpr _ _ right) = right
data Statement = Statement Expr
deriving (Show)
data StatementList = StatementList [Statement]
deriving (Show)
data Stopper a = Stopper a Int
| Stopped
deriving (Show)
stopperVal (Stopper a _) = a
stopperCount (Stopper _ c) = c
instance Monad Stopper where
return x = Stopper x 0
(Stopper a 3) >>= b = Stopped
(Stopper a num) >>= b = Stopper x y
where s = b a
x = stopperVal s
y = (stopperCount s) + 1
| zc1036/Compiler-project | src/Main.hs | gpl-3.0 | 899 | 0 | 9 | 339 | 292 | 154 | 138 | 29 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Data types, instances, and form validators
-- for storing job postings in a database.
module Snap.Snaplet.JobBoard.Types where
import Control.Applicative
import Control.Monad
import Control.Lens
{- Text -}
import Data.Text as T (Text, null, pack)
import Data.Text.Read (decimal)
{- Database -}
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.ToField
{- Time -}
import Database.PostgreSQL.Simple.Time
import Data.Time.Clock (UTCTime, getCurrentTime)
{- JSON REST interface -}
import Data.Aeson.TH (deriveJSON)
{- Snap Handlers -}
import Snap
import Snap.Snaplet.JobBoard.Util
{- Digestive-Functors Forms -}
import Text.Digestive
import Text.Digestive.Snap
-- Great postgresql-simple intro:
-- http://ocharles.org.uk/blog/posts/2012-12-03-postgresql-simple.html
-- Type class instances for Enum
data JobType = FullTime | PartTime | Contract | Academic
deriving(Eq, Enum, Bounded, Ord, Read, Show)
deriveJSON id ''JobType
jobTypeText :: JobType -> Text
jobTypeText FullTime = "Full time"
jobTypeText PartTime = "Part time"
jobTypeText Contract = "Contract"
jobTypeText Academic = "Academic"
-- | TODO: Note this defaults to FullTime for invalid enum values.
instance FromField JobType where
fromField a b = fmap (maybe FullTime id . safeToEnum) $ fromField a b
instance ToField JobType where
toField = toField . fromEnum
-- | A job posting. Note the primary key, an Int, is specifically
-- excluded. To do queries, we have to explicitly request a tuple of
-- (Int, Job)
data Job = Job
{ _owner :: Int -- ^ Foreign Key
, _employer :: Text -- ^ Name of employer
, _employerLink :: Maybe Text -- ^ Link to employer site
, _link :: Maybe Text -- ^ Link to source (not submittable)
, _title :: Text -- ^ Job Title
, _location :: Text -- ^ Job location
, _type :: JobType -- ^ Job Type
, _description :: Text -- ^ Job description
, _instructions :: Maybe Text -- ^ Application instructions
, _open :: Bool -- ^ True when position not filled
, _updated :: UTCTimestamp -- ^ Last updated time
} deriving(Read, Show, Eq)
{- Form SQL FromField/ToField Instances -}
instance FromRow Job where
fromRow = Job <$> field <*> field <*> field <*>
field <*> field <*> field <*>
field <*> field <*> field <*>
field <*> field
instance ToRow Job where
toRow (Job ow emp empl lnk tit loc ty des instr opn tim) =
[ toField ow, toField emp, toField empl, toField lnk
, toField tit, toField loc, toField ty, toField des
, toField instr, toField opn, toField tim]
-- | Newtype representing records with an ID. TODO: un-newtype?
newtype Id i a = Id { unId :: (i, a) }
-- | Parse an Id Record from a row
instance (FromField i, FromRow a) => FromRow (Id i a) where
fromRow = liftM2 ((Id .) . (,)) field fromRow
{-- Form validators & utilities --}
jobFromParams :: MonadSnap m => Int -> m (Maybe Job)
jobFromParams i =
liftIO getCurrentTime >>= fmap snd . runForm "job" . jobForm i
jobForm :: Monad m => Int -> UTCTime -> Form Text m Job
jobForm ownerId t = Job ownerId
<$> "employer" .: checkNotNull (text Nothing)
<*> "employerLink" .: optionalText Nothing
<*> "link" .: pure Nothing
<*> "title" .: checkNotNull (text Nothing)
<*> "location" .: checkNotNull (text Nothing)
<*> "type" .: validate validateType (text Nothing)
<*> "description" .: checkNotNull (text Nothing)
<*> "instructions" .: optionalText Nothing
<*> "open" .: pure True
<*> "updated" .: pure (Finite t)
where validateType ty = validateIntegral ty >>= validateEnum
checkNotNull = check "not null" (not . T.null)
-- Turn a Maybe and an error message into a Result
resultFromMaybe :: v -> Maybe a -> Result v a
resultFromMaybe v = maybe (Error v) Success
resultFromEither :: Either v a -> Result v a
resultFromEither (Left v) = Error v
resultFromEither (Right a) = Success a
-- | Validate a type by reading an Int and converting to Enum.
validateEnum :: (Enum a, Bounded a, Ord a)
=> Int -> Result Text a
validateEnum = resultFromMaybe "Invalid job type" . safeToEnum
-- | Validate an Integral type.
validateIntegral :: Integral a => Text -> Result Text a
validateIntegral = (f =<<) . resultFromEither . g . decimal
where f (i,s) = if T.null s then Success i else Error "not integral"
g = _left %~ T.pack -- use lenses to modify Left Strings
| statusfailed/snaplet-job-board | src/Snap/Snaplet/JobBoard/Types.hs | agpl-3.0 | 4,753 | 0 | 26 | 1,035 | 1,180 | 643 | 537 | 88 | 2 |
----------------------------------------------------------------
-- Jedes Modul beginnt mit diesen Teil
-- weil wir ein lauffähiges Programm haben wollen
-- schreiben wir nur das Hauptmodul (`Main`)
module Main where
-- danach kommt de Teil wo externe Module improtiert werden
import Control.Monad (forM_)
import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout)
----------------------------------------------------------------
-- dieser Teil ist der Programmeinstiegspunkt
-- `main` fragt einfach nur die Zahlen und die Zielzahl ab
-- (die Zahlen können als Liste wie in Haskell eingegeben werden)
-- berechnet dann die Lösungen und gibt diese aus
-- die Details sollen heute nicht so interessant sein
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
putStrLn "Countdown"
putStr "Liste mit verfügbaren Zahlen? "
zahlen <- read <$> getLine
putStr "Zielzahl? "
ziel <- read <$> getLine
let lösungen = bruteForceSolutions zahlen ziel
forM_ lösungen print
---------------------------------------------------------------
-- HIER beginnt der Spaß für uns ;)
-- unser ziel ist es eine Expression aufzubauen
-- deren Value Blätter nur Werte aus den gegebenen
-- Zahlen annehmen und die dem Zielwert entspricht
data Expression
= Value Int
| Apply Operand Expression Expression
deriving (Eq)
-- dafür stehen uns folgende Operationen zur Auswahl:
data Operand
= Add | Sub | Mul | Div
deriving (Eq, Ord)
-- aber nicht Operationen sind für alle Zahlen erlaubt!
-- isValidOp soll True ergeben, wenn alles in Ordnung ist,
-- aber False, falls wir nicht-positive Zahlen produzieren
-- würden (z.B. 4-6), durch 0 teilen oder beim Teilen einen
-- Rest lassen würden (7/4 - 8/4 ist ok)
isValidOp :: (Ord a, Integral a) => Operand -> a -> a -> Bool
isValidOp Add _ _ = True
isValidOp Sub x y = x > y
isValidOp Mul _ _ = True
isValidOp Div x y = x `mod` y == 0
-- apply soll zwei Zahlen mit den gegebenen Operanden
-- verknüpfen und das Ergebnis der Operation berechnen
apply :: Operand -> Int -> Int -> Int
apply Add = (+)
apply Sub = (-)
apply Mul = (*)
apply Div = div
-- wie oben erwähnt soll eine gültige Expression
-- nur Zahlen aus der gegebenen Liste enthalten
-- mit values suchen wir alle verwendeten Werte
-- (die Werte der Blätter des Expression-Baums)
values :: Expression -> [Int]
values (Value n) = [n]
values (Apply _ x y) = values x ++ values y
-- um später alle möglichen Expressions aufzulisten
-- brauchen wir alle Teillisten der Verfügbaren
-- Zahlen (wobei hier die Anordnung bestehen bleiben soll)
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = map (x:) (subs xs) ++ subs xs
-- um gleich perms zu implementieren können wir
-- pick benutzen: es liefert alle Möglichkeiten
-- ein Element aus einer Liste zu wählen (zusammen mit
-- den Rest)
-- Beispiel: pick [1,2,3] = [(1,[2,3]),(2,[1,3]),(3,[1,2])]
pick :: [a] -> [ (a,[a]) ]
pick [] = []
pick (x:xs) = (x,xs) : [ (y,x:ys) | (y,ys) <- pick xs ]
-- schließlich brauchen wir noch eine Funktion die uns
-- alle Permutationen (Umordnungen) einer Liste liefert
-- Tipp: Pick ist sicher nützlich ;)
perms :: [a] -> [[a]]
perms [] = [[]]
perms xs = [ y:ys | (y,ys') <- pick xs, ys <- perms ys' ]
-- wir haben das oben noch nicht gemacht, aber wir müssen
-- eine Expression ja noch "auswerten"
-- allerdings benutzen wir hier einen Trick: eval soll nicht
-- nur ein Ergebnis liefern - es soll auch prüfen ob überall
-- valide Operationen verwendet wurden, und dafür können wir
-- Listen und Comprehensions clever benutzen:
-- die Leere Menge steht für kein Ergebnis möglich (z.B. weil
-- irgendwo durch 0 geteilt wurde) und ein Ergebnis n wird
-- durch eine Liste mit genau einem Element [n] angezeigt
eval :: Expression -> [Int]
eval (Value n) = [ n | n > 0 ]
eval (Apply op x y) = [ apply op a b | a <- eval x, b <- eval y, isValidOp op a b ]
-- subbags verbindet jetzt einfach perms und subs: damit bekommen
-- wir alle Permutationen aller Teillisten:
subbags :: [a] -> [[a]]
subbags xs = [ zs | ys <- subs xs, zs <- perms ys ]
-- diese Funktion liefert alle Möglichkeiten wie
-- eine Liste in zwei Teile geteilt werden kann
split :: [a] -> [ ([a],[a]) ]
split [] = [ ([],[]) ]
split (x:xs) = ([], x:xs) : [ (x:ls,rs) | (ls,rs) <- split xs ]
-- allerdings interessieren wir uns nur für die Aufteilungen
-- wo kein Teil leer ist
notEmptySplit :: [a] -> [ ([a],[a]) ]
notEmptySplit = filter notEmpty . split
where notEmpty (xs,ys) = not (null xs || null ys)
-- wie wollen Expressions erzeugen und wir machen das, indem
-- wir eine Menge von Zahlen in jeder möglichen Weise in zwei
-- Teile teilen und dann rekursiv für diese Teile Expressions
-- erzeugen - die rekursiven Teile ergeben dann wieder 4
-- weitere Möglichkeiten - eine für jeden Operator, mit den
-- wir die beiden Unterexpressions verbinden können.
-- hatte die Liste nur ein Element kann es nur
-- ein Blatt (eine Value werden) und bei keinem Element ist
-- es offensichtlich unmöglich eine Expression zu erzeugen
expressions :: [Int] -> [Expression]
expressions [] = []
expressions [n] = [Value n]
expressions ns = [ Apply op l r | (ls,rs) <- notEmptySplit ns
, l <- expressions ls
, r <- expressions rs
, op <- [Add, Sub, Mul, Div] ]
-- damit können wir jetzt per Brute-Force alle Lösungen suchen:
-- für jede Teilliste und Permutation dieser (subbags) suchen
-- wir in jeder mit dieser Teilzahlenliste bildbaren Expression
-- genau die heraus, deren Auswertung n ergibt:
bruteForceSolutions :: [Int] -> Int -> [Expression]
bruteForceSolutions ns n = [ e | ns' <- subbags ns, e <- expressions ns', eval e == [n]]
------------------------------------------------------
-- dieser Teil dient nur dazu die Expressions etwas
-- shöner Darzustellen, als es `deriving Show` könnte
instance Show Expression where
show ex = snd $ formatEx 0 ex
formatEx :: Int -> Expression -> (Int, String)
formatEx _ (Value n) = (9, show n)
formatEx prec (Apply op l r)
| opPrec <= prec = (prec, "(" ++ formatted ++ ")")
| otherwise = (prec, formatted)
where opPrec = precedence op
formatted = let (lp, ls) = formatEx opPrec l
(_, rs) = formatEx lp r
in ls ++ show op ++ rs
precedence :: Operand -> Int
precedence Mul = 9
precedence Div = 8
precedence Add = 5
precedence Sub = 4
instance Show Operand where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
| CarstenKoenig/DOS2015 | Countdown/Countdown.hs | unlicense | 6,569 | 0 | 11 | 1,353 | 1,484 | 818 | 666 | 83 | 1 |
module Main (main) where
import Control.Applicative
import Control.Lens
import Criterion.Main
import Data.Time.Lite
import Data.Time.Lite.Nano
import Data.Time
import Data.Time.Clock.POSIX
import qualified Data.Thyme as Th
import qualified Data.Thyme.Time as Th
import System.Hourglass
benchmarks :: [Benchmark]
benchmarks = [
-- Data.Time
bench "getCurrentTime" $ nfIO $ getCurrentTime,
bench "getPOSIXTime" $ nfIO $ getPOSIXTime,
-- Hourglass
bench "timeCurrentP" $ whnfIO timeCurrentP,
-- Data.Thyme
bench "Thyme.getCurrentTime" $ whnfIO $ Th.getCurrentTime,
bench "Thyme.getCurrentTime compat" $ nfIO $ getCurrentTimeThyme,
-- Ours
bench "getCurrentTime'" $ nfIO $ getCurrentTime',
bench "getCurrentUTime" $ whnfIO $ getCurrentUTime,
bench "getClockUTime REALTIME" $ whnfIO $ getClockUTime CLOCK_REALTIME,
bench "getClockUTime REALTIME_COARSE" $ whnfIO $ getClockUTime CLOCK_REALTIME_COARSE
]
getCurrentTime' :: IO UTCTime
getCurrentTime' = do
UTime ns <- getCurrentUTime
let (d, dt) = ns `iQuotRem` 86400
return $ UTCTime (ModifiedJulianDay $ 40587 + d) (dt ^. nanoDiffTime)
getCurrentTimeThyme :: IO UTCTime
getCurrentTimeThyme = Th.fromThyme <$> Th.getCurrentTime
main :: IO ()
main = do
defaultMain benchmarks
| nilcons/time-lite | benchmarks/gettimeofday_bench.hs | apache-2.0 | 1,260 | 0 | 11 | 192 | 338 | 184 | 154 | 32 | 1 |
module Binary.A272756 (a272756) where
import Data.List (find)
import Data.Maybe (fromJust)
import HelperSequences.A070939 (a070939)
a272756 :: Int -> Int
a272756 n = a272756_list !! (n - 1)
a272756_list :: [Int]
a272756_list = 3 : remaining 1 where
remaining i = next_term : remaining (i + 1) where
next_term = fromJust $ find (\k -> a070939 (i * k + k) < k) [a272756 i..]
| peterokagey/haskellOEIS | src/Binary/A272756.hs | apache-2.0 | 381 | 0 | 17 | 71 | 161 | 88 | 73 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
{-| Combines the construction of RPC server components and their Python stubs.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.THH.PyRPC
( genPyUDSRpcStub
, genPyUDSRpcStubStr
) where
import Control.Monad
import Data.Char (toLower, toUpper)
import Data.Functor
import Data.Maybe (fromMaybe)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (liftString)
import Text.PrettyPrint
import Ganeti.THH.Types
-- | The indentation step in generated Python files.
pythonIndentStep :: Int
pythonIndentStep = 2
-- | A helper function that nests a block of generated output by the default
-- step (see 'pythonIndentStep').
nest' :: Doc -> Doc
nest' = nest pythonIndentStep
-- | The name of an abstract function to which all method in a Python stub
-- are forwarded to.
genericInvokeName :: String
genericInvokeName = "_GenericInvoke"
-- | The name of a function that returns the socket path for reaching the
-- appropriate RPC client.
socketPathName :: String
socketPathName = "_GetSocketPath"
-- | Create a Python expression that applies a given function to a list of
-- given expressions
apply :: String -> [Doc] -> Doc
apply name as = text name <> parens (hcat $ punctuate (text ", ") as)
-- | An empty line block.
emptyLine :: Doc
emptyLine = text "" -- apparently using 'empty' doesn't work
lowerFirst :: String -> String
lowerFirst (x:xs) = toLower x : xs
lowerFirst [] = []
upperFirst :: String -> String
upperFirst (x:xs) = toUpper x : xs
upperFirst [] = []
-- | Creates a method declaration given a function name and a list of
-- Haskell types corresponding to its arguments.
toFunc :: String -> [Type] -> Q Doc
toFunc fname as = do
args <- zipWithM varName [1..] as
let args' = text "self" : args
callName = lowerFirst fname
return $ (text "def" <+> apply fname args') <> colon $+$
nest' (text "return" <+>
text "self." <>
apply genericInvokeName (text (show callName) : args)
)
where
-- | Create a name for a method argument, given its index position
-- and Haskell type.
varName :: Int -> Type -> Q Doc
varName _ (VarT n) = lowerFirstNameQ n
varName _ (ConT n) = lowerFirstNameQ n
varName idx (AppT ListT t) = listOf idx t
varName idx (AppT (ConT n) t)
| n == ''[] = listOf idx t
| otherwise = kind1Of idx n t
varName idx (AppT (AppT (TupleT 2) t) t')
= pairOf idx t t'
varName idx (AppT (AppT (ConT n) t) t')
| n == ''(,) = pairOf idx t t'
varName idx t = do
report False $ "Don't know how to make a Python variable name from "
++ show t ++ "; using a numbered one."
return $ text ('_' : show idx)
-- | Create a name for a method argument, knowing that its a list of
-- a given type.
listOf :: Int -> Type -> Q Doc
listOf idx t = (<> text "List") <$> varName idx t
-- | Create a name for a method argument, knowing that its wrapped in
-- a type of kind @* -> *@.
kind1Of :: Int -> Name -> Type -> Q Doc
kind1Of idx name t = (<> text (nameBase name)) <$> varName idx t
-- | Create a name for a method argument, knowing that its a pair of
-- the given types.
pairOf :: Int -> Type -> Type -> Q Doc
pairOf idx t t' = do
tn <- varName idx t
tn' <- varName idx t'
return $ tn <> text "_" <> tn' <> text "_Pair"
lowerFirstNameQ :: Name -> Q Doc
lowerFirstNameQ = return . text . lowerFirst . nameBase
-- | Creates a method declaration by inspecting (reifying) Haskell's function
-- name.
nameToFunc :: Name -> Q Doc
nameToFunc name = do
(as, _) <- funArgs `liftM` typeOfFun name
-- If the function has just one argument, try if it isn't a tuple;
-- if not, use the arguments as they are.
let as' = fromMaybe as $ case as of
[t] -> tupleArgs t -- TODO CHECK!
_ -> Nothing
toFunc (upperFirst $ nameBase name) as'
-- | Generates a Python class stub, given a class name, the list of Haskell
-- functions to expose as methods, and a optionally a piece of code to
-- include.
namesToClass
:: String -- ^ the class name
-> Doc -- ^ Python code to include in the class
-> [Name] -- ^ the list of functions to include
-> Q Doc
namesToClass cname pycode fns = do
fnsCode <- mapM (liftM ($+$ emptyLine) . nameToFunc) fns
return $ vcat [ text "class" <+> apply cname [text "object"] <> colon
, nest' (
pycode $+$ vcat fnsCode
)
]
-- | Takes a list of function names and creates a RPC handler that delegates
-- calls to them, as well as writes out the corresponding Python stub.
--
-- See 'mkRpcM' for the requirements on the passed functions and the returned
-- expression.
genPyUDSRpcStub
:: String -- ^ the name of the class to be generated
-> String -- ^ the name of the constant from @constants.py@ holding
-- the path to a UDS socket
-> [Name] -- ^ names of functions to include
-> Q Doc
genPyUDSRpcStub className constName = liftM (header $+$) .
namesToClass className stubCode
where
header = text "# This file is automatically generated, do not edit!" $+$
text "# pylint: skip-file"
stubCode =
abstrMethod genericInvokeName [ text "method", text "*args"] $+$
method socketPathName [] (
text "from ganeti import pathutils" $+$
text "return" <+> text "pathutils." <> text constName)
method name args body =
text "def" <+> apply name (text "self" : args) <> colon $+$
nest' body $+$
emptyLine
abstrMethod name args = method name args $
text "raise" <+> apply "NotImplementedError" []
-- The same as 'genPyUDSRpcStub', but returns the result as a @String@
-- expression.
genPyUDSRpcStubStr
:: String -- ^ the name of the class to be generated
-> String -- ^ the constant in @pathutils.py@ holding the socket path
-> [Name] -- ^ functions to include
-> Q Exp
genPyUDSRpcStubStr className constName names =
liftString . render =<< genPyUDSRpcStub className constName names
| yiannist/ganeti | src/Ganeti/THH/PyRPC.hs | bsd-2-clause | 7,731 | 0 | 16 | 2,033 | 1,426 | 732 | 694 | 110 | 7 |
----------------------------------------------------------------------------
-- |
-- Module : Haddock.Interface.Rename
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Interface.Rename (renameInterface) where
import Data.Traversable (traverse, Traversable)
import Haddock.GhcUtils
import Haddock.Types
import Bag (emptyBag)
import GHC hiding (NoLink)
import Name
import Control.Applicative
import Control.Monad hiding (mapM)
import Data.List
import qualified Data.Map as Map hiding ( Map )
import Data.Traversable (mapM)
import Prelude hiding (mapM)
renameInterface :: DynFlags -> LinkEnv -> Bool -> Interface -> ErrMsgM Interface
renameInterface dflags renamingEnv warnings iface =
-- first create the local env, where every name exported by this module
-- is mapped to itself, and everything else comes from the global renaming
-- env
let localEnv = foldl fn renamingEnv (ifaceVisibleExports iface)
where fn env name = Map.insert name (ifaceMod iface) env
-- rename names in the exported declarations to point to things that
-- are closer to, or maybe even exported by, the current module.
(renamedExportItems, missingNames1)
= runRnFM localEnv (renameExportItems (ifaceExportItems iface))
(rnDocMap, missingNames2) = runRnFM localEnv (mapM renameDoc (ifaceDocMap iface))
(rnArgMap, missingNames3) = runRnFM localEnv (mapM (mapM renameDoc) (ifaceArgMap iface))
(finalModuleDoc, missingNames4)
= runRnFM localEnv (renameDocumentation (ifaceDoc iface))
-- combine the missing names and filter out the built-ins, which would
-- otherwise allways be missing.
missingNames = nub $ filter isExternalName -- XXX: isExternalName filters out too much
(missingNames1 ++ missingNames2 ++ missingNames3 ++ missingNames4)
-- filter out certain built in type constructors using their string
-- representation. TODO: use the Name constants from the GHC API.
-- strings = filter (`notElem` ["()", "[]", "(->)"])
-- (map pretty missingNames)
strings = map (pretty dflags) . filter (\n -> not (isSystemName n || isBuiltInSyntax n)) $ missingNames
in do
-- report things that we couldn't link to. Only do this for non-hidden
-- modules.
unless (OptHide `elem` ifaceOptions iface || null strings || not warnings) $
tell ["Warning: " ++ moduleString (ifaceMod iface) ++
": could not find link destinations for:\n"++
unwords (" " : strings) ]
return $ iface { ifaceRnDoc = finalModuleDoc,
ifaceRnDocMap = rnDocMap,
ifaceRnArgMap = rnArgMap,
ifaceRnExportItems = renamedExportItems }
--------------------------------------------------------------------------------
-- Monad for renaming
--
-- The monad does two things for us: it passes around the environment for
-- renaming, and it returns a list of names which couldn't be found in
-- the environment.
--------------------------------------------------------------------------------
newtype RnM a =
RnM { unRn :: (Name -> (Bool, DocName)) -- name lookup function
-> (a,[Name])
}
instance Monad RnM where
(>>=) = thenRn
return = returnRn
instance Functor RnM where
fmap f x = do a <- x; return (f a)
instance Applicative RnM where
pure = return
(<*>) = ap
returnRn :: a -> RnM a
returnRn a = RnM (const (a,[]))
thenRn :: RnM a -> (a -> RnM b) -> RnM b
m `thenRn` k = RnM (\lkp -> case unRn m lkp of
(a,out1) -> case unRn (k a) lkp of
(b,out2) -> (b,out1++out2))
getLookupRn :: RnM (Name -> (Bool, DocName))
getLookupRn = RnM (\lkp -> (lkp,[]))
outRn :: Name -> RnM ()
outRn name = RnM (const ((),[name]))
lookupRn :: Name -> RnM DocName
lookupRn name = do
lkp <- getLookupRn
case lkp name of
(False,maps_to) -> do outRn name; return maps_to
(True, maps_to) -> return maps_to
runRnFM :: LinkEnv -> RnM a -> (a,[Name])
runRnFM env rn = unRn rn lkp
where
lkp n = case Map.lookup n env of
Nothing -> (False, Undocumented n)
Just mdl -> (True, Documented n mdl)
--------------------------------------------------------------------------------
-- Renaming
--------------------------------------------------------------------------------
rename :: Name -> RnM DocName
rename = lookupRn
renameL :: Located Name -> RnM (Located DocName)
renameL = mapM rename
renameExportItems :: [ExportItem Name] -> RnM [ExportItem DocName]
renameExportItems = mapM renameExportItem
renameDocForDecl :: DocForDecl Name -> RnM (DocForDecl DocName)
renameDocForDecl (doc, fnArgsDoc) =
(,) <$> renameDocumentation doc <*> renameFnArgsDoc fnArgsDoc
renameDocumentation :: Documentation Name -> RnM (Documentation DocName)
renameDocumentation (Documentation mDoc mWarning) =
Documentation <$> mapM renameDoc mDoc <*> mapM renameDoc mWarning
renameLDocHsSyn :: LHsDocString -> RnM LHsDocString
renameLDocHsSyn = return
renameDoc :: Traversable t => t Name -> RnM (t DocName)
renameDoc = traverse rename
renameFnArgsDoc :: FnArgsDoc Name -> RnM (FnArgsDoc DocName)
renameFnArgsDoc = mapM renameDoc
renameLType :: LHsType Name -> RnM (LHsType DocName)
renameLType = mapM renameType
renameLKind :: LHsKind Name -> RnM (LHsKind DocName)
renameLKind = renameLType
renameMaybeLKind :: Maybe (LHsKind Name) -> RnM (Maybe (LHsKind DocName))
renameMaybeLKind = traverse renameLKind
renameType :: HsType Name -> RnM (HsType DocName)
renameType t = case t of
HsForAllTy expl extra tyvars lcontext ltype -> do
tyvars' <- renameLTyVarBndrs tyvars
lcontext' <- renameLContext lcontext
ltype' <- renameLType ltype
return (HsForAllTy expl extra tyvars' lcontext' ltype')
HsTyVar n -> return . HsTyVar =<< rename n
HsBangTy b ltype -> return . HsBangTy b =<< renameLType ltype
HsAppTy a b -> do
a' <- renameLType a
b' <- renameLType b
return (HsAppTy a' b')
HsFunTy a b -> do
a' <- renameLType a
b' <- renameLType b
return (HsFunTy a' b')
HsListTy ty -> return . HsListTy =<< renameLType ty
HsPArrTy ty -> return . HsPArrTy =<< renameLType ty
HsIParamTy n ty -> liftM (HsIParamTy n) (renameLType ty)
HsEqTy ty1 ty2 -> liftM2 HsEqTy (renameLType ty1) (renameLType ty2)
HsTupleTy b ts -> return . HsTupleTy b =<< mapM renameLType ts
HsOpTy a (w, L loc op) b -> do
op' <- rename op
a' <- renameLType a
b' <- renameLType b
return (HsOpTy a' (w, L loc op') b')
HsParTy ty -> return . HsParTy =<< renameLType ty
HsKindSig ty k -> do
ty' <- renameLType ty
k' <- renameLKind k
return (HsKindSig ty' k')
HsDocTy ty doc -> do
ty' <- renameLType ty
doc' <- renameLDocHsSyn doc
return (HsDocTy ty' doc')
HsTyLit x -> return (HsTyLit x)
HsWrapTy a b -> HsWrapTy a <$> renameType b
HsRecTy a -> HsRecTy <$> mapM renameConDeclFieldField a
HsCoreTy a -> pure (HsCoreTy a)
HsExplicitListTy a b -> HsExplicitListTy a <$> mapM renameLType b
HsExplicitTupleTy a b -> HsExplicitTupleTy a <$> mapM renameLType b
HsSpliceTy _ _ -> error "renameType: HsSpliceTy"
HsWildCardTy a -> HsWildCardTy <$> renameWildCardInfo a
renameLTyVarBndrs :: LHsTyVarBndrs Name -> RnM (LHsTyVarBndrs DocName)
renameLTyVarBndrs (HsQTvs { hsq_kvs = _, hsq_tvs = tvs })
= do { tvs' <- mapM renameLTyVarBndr tvs
; return (HsQTvs { hsq_kvs = error "haddock:renameLTyVarBndrs", hsq_tvs = tvs' }) }
-- This is rather bogus, but I'm not sure what else to do
renameLTyVarBndr :: LHsTyVarBndr Name -> RnM (LHsTyVarBndr DocName)
renameLTyVarBndr (L loc (UserTyVar n))
= do { n' <- rename n
; return (L loc (UserTyVar n')) }
renameLTyVarBndr (L loc (KindedTyVar (L lv n) kind))
= do { n' <- rename n
; kind' <- renameLKind kind
; return (L loc (KindedTyVar (L lv n') kind')) }
renameLContext :: Located [LHsType Name] -> RnM (Located [LHsType DocName])
renameLContext (L loc context) = do
context' <- mapM renameLType context
return (L loc context')
renameWildCardInfo :: HsWildCardInfo Name -> RnM (HsWildCardInfo DocName)
renameWildCardInfo (AnonWildCard _) = pure (AnonWildCard PlaceHolder)
renameWildCardInfo (NamedWildCard name) = NamedWildCard <$> rename name
renameInstHead :: InstHead Name -> RnM (InstHead DocName)
renameInstHead (className, k, types, rest) = do
className' <- rename className
k' <- mapM renameType k
types' <- mapM renameType types
rest' <- case rest of
ClassInst cs -> ClassInst <$> mapM renameType cs
TypeInst ts -> TypeInst <$> traverse renameType ts
DataInst dd -> DataInst <$> renameTyClD dd
return (className', k', types', rest')
renameLDecl :: LHsDecl Name -> RnM (LHsDecl DocName)
renameLDecl (L loc d) = return . L loc =<< renameDecl d
renameDecl :: HsDecl Name -> RnM (HsDecl DocName)
renameDecl decl = case decl of
TyClD d -> do
d' <- renameTyClD d
return (TyClD d')
SigD s -> do
s' <- renameSig s
return (SigD s')
ForD d -> do
d' <- renameForD d
return (ForD d')
InstD d -> do
d' <- renameInstD d
return (InstD d')
_ -> error "renameDecl"
renameLThing :: (a Name -> RnM (a DocName)) -> Located (a Name) -> RnM (Located (a DocName))
renameLThing fn (L loc x) = return . L loc =<< fn x
renameTyClD :: TyClDecl Name -> RnM (TyClDecl DocName)
renameTyClD d = case d of
-- TyFamily flav lname ltyvars kind tckind -> do
FamDecl { tcdFam = decl } -> do
decl' <- renameFamilyDecl decl
return (FamDecl { tcdFam = decl' })
SynDecl { tcdLName = lname, tcdTyVars = tyvars, tcdRhs = rhs, tcdFVs = _fvs } -> do
lname' <- renameL lname
tyvars' <- renameLTyVarBndrs tyvars
rhs' <- renameLType rhs
return (SynDecl { tcdLName = lname', tcdTyVars = tyvars', tcdRhs = rhs', tcdFVs = placeHolderNames })
DataDecl { tcdLName = lname, tcdTyVars = tyvars, tcdDataDefn = defn, tcdFVs = _fvs } -> do
lname' <- renameL lname
tyvars' <- renameLTyVarBndrs tyvars
defn' <- renameDataDefn defn
return (DataDecl { tcdLName = lname', tcdTyVars = tyvars', tcdDataDefn = defn', tcdFVs = placeHolderNames })
ClassDecl { tcdCtxt = lcontext, tcdLName = lname, tcdTyVars = ltyvars
, tcdFDs = lfundeps, tcdSigs = lsigs, tcdATs = ats, tcdATDefs = at_defs } -> do
lcontext' <- renameLContext lcontext
lname' <- renameL lname
ltyvars' <- renameLTyVarBndrs ltyvars
lfundeps' <- mapM renameLFunDep lfundeps
lsigs' <- mapM renameLSig lsigs
ats' <- mapM (renameLThing renameFamilyDecl) ats
at_defs' <- mapM renameLTyFamDefltEqn at_defs
-- we don't need the default methods or the already collected doc entities
return (ClassDecl { tcdCtxt = lcontext', tcdLName = lname', tcdTyVars = ltyvars'
, tcdFDs = lfundeps', tcdSigs = lsigs', tcdMeths= emptyBag
, tcdATs = ats', tcdATDefs = at_defs', tcdDocs = [], tcdFVs = placeHolderNames })
where
renameLFunDep (L loc (xs, ys)) = do
xs' <- mapM rename (map unLoc xs)
ys' <- mapM rename (map unLoc ys)
return (L loc (map noLoc xs', map noLoc ys'))
renameLSig (L loc sig) = return . L loc =<< renameSig sig
renameFamilyDecl :: FamilyDecl Name -> RnM (FamilyDecl DocName)
renameFamilyDecl (FamilyDecl { fdInfo = info, fdLName = lname
, fdTyVars = ltyvars, fdKindSig = tckind }) = do
info' <- renameFamilyInfo info
lname' <- renameL lname
ltyvars' <- renameLTyVarBndrs ltyvars
tckind' <- renameMaybeLKind tckind
return (FamilyDecl { fdInfo = info', fdLName = lname'
, fdTyVars = ltyvars', fdKindSig = tckind' })
renameFamilyInfo :: FamilyInfo Name -> RnM (FamilyInfo DocName)
renameFamilyInfo DataFamily = return DataFamily
renameFamilyInfo OpenTypeFamily = return OpenTypeFamily
renameFamilyInfo (ClosedTypeFamily eqns)
= do { eqns' <- mapM (mapM renameLTyFamInstEqn) eqns
; return $ ClosedTypeFamily eqns' }
renameDataDefn :: HsDataDefn Name -> RnM (HsDataDefn DocName)
renameDataDefn (HsDataDefn { dd_ND = nd, dd_ctxt = lcontext, dd_cType = cType
, dd_kindSig = k, dd_cons = cons }) = do
lcontext' <- renameLContext lcontext
k' <- renameMaybeLKind k
cons' <- mapM (mapM renameCon) cons
-- I don't think we need the derivings, so we return Nothing
return (HsDataDefn { dd_ND = nd, dd_ctxt = lcontext', dd_cType = cType
, dd_kindSig = k', dd_cons = cons', dd_derivs = Nothing })
renameCon :: ConDecl Name -> RnM (ConDecl DocName)
renameCon decl@(ConDecl { con_names = lnames, con_qvars = ltyvars
, con_cxt = lcontext, con_details = details
, con_res = restype, con_doc = mbldoc }) = do
lnames' <- mapM renameL lnames
ltyvars' <- renameLTyVarBndrs ltyvars
lcontext' <- renameLContext lcontext
details' <- renameDetails details
restype' <- renameResType restype
mbldoc' <- mapM renameLDocHsSyn mbldoc
return (decl { con_names = lnames', con_qvars = ltyvars', con_cxt = lcontext'
, con_details = details', con_res = restype', con_doc = mbldoc' })
where
renameDetails (RecCon (L l fields)) = do
fields' <- mapM renameConDeclFieldField fields
return (RecCon (L l fields'))
renameDetails (PrefixCon ps) = return . PrefixCon =<< mapM renameLType ps
renameDetails (InfixCon a b) = do
a' <- renameLType a
b' <- renameLType b
return (InfixCon a' b')
renameResType (ResTyH98) = return ResTyH98
renameResType (ResTyGADT l t) = return . ResTyGADT l =<< renameLType t
renameConDeclFieldField :: LConDeclField Name -> RnM (LConDeclField DocName)
renameConDeclFieldField (L l (ConDeclField names t doc)) = do
names' <- mapM renameL names
t' <- renameLType t
doc' <- mapM renameLDocHsSyn doc
return $ L l (ConDeclField names' t' doc')
renameSig :: Sig Name -> RnM (Sig DocName)
renameSig sig = case sig of
TypeSig lnames ltype _ -> do
lnames' <- mapM renameL lnames
ltype' <- renameLType ltype
return (TypeSig lnames' ltype' PlaceHolder)
PatSynSig lname (flag, qtvs) lreq lprov lty -> do
lname' <- renameL lname
qtvs' <- renameLTyVarBndrs qtvs
lreq' <- renameLContext lreq
lprov' <- renameLContext lprov
lty' <- renameLType lty
return $ PatSynSig lname' (flag, qtvs') lreq' lprov' lty'
FixSig (FixitySig lnames fixity) -> do
lnames' <- mapM renameL lnames
return $ FixSig (FixitySig lnames' fixity)
MinimalSig src s -> MinimalSig src <$> traverse renameL s
-- we have filtered out all other kinds of signatures in Interface.Create
_ -> error "expected TypeSig"
renameForD :: ForeignDecl Name -> RnM (ForeignDecl DocName)
renameForD (ForeignImport lname ltype co x) = do
lname' <- renameL lname
ltype' <- renameLType ltype
return (ForeignImport lname' ltype' co x)
renameForD (ForeignExport lname ltype co x) = do
lname' <- renameL lname
ltype' <- renameLType ltype
return (ForeignExport lname' ltype' co x)
renameInstD :: InstDecl Name -> RnM (InstDecl DocName)
renameInstD (ClsInstD { cid_inst = d }) = do
d' <- renameClsInstD d
return (ClsInstD { cid_inst = d' })
renameInstD (TyFamInstD { tfid_inst = d }) = do
d' <- renameTyFamInstD d
return (TyFamInstD { tfid_inst = d' })
renameInstD (DataFamInstD { dfid_inst = d }) = do
d' <- renameDataFamInstD d
return (DataFamInstD { dfid_inst = d' })
renameClsInstD :: ClsInstDecl Name -> RnM (ClsInstDecl DocName)
renameClsInstD (ClsInstDecl { cid_overlap_mode = omode
, cid_poly_ty =ltype, cid_tyfam_insts = lATs
, cid_datafam_insts = lADTs }) = do
ltype' <- renameLType ltype
lATs' <- mapM (mapM renameTyFamInstD) lATs
lADTs' <- mapM (mapM renameDataFamInstD) lADTs
return (ClsInstDecl { cid_overlap_mode = omode
, cid_poly_ty = ltype', cid_binds = emptyBag
, cid_sigs = []
, cid_tyfam_insts = lATs', cid_datafam_insts = lADTs' })
renameTyFamInstD :: TyFamInstDecl Name -> RnM (TyFamInstDecl DocName)
renameTyFamInstD (TyFamInstDecl { tfid_eqn = eqn })
= do { eqn' <- renameLTyFamInstEqn eqn
; return (TyFamInstDecl { tfid_eqn = eqn'
, tfid_fvs = placeHolderNames }) }
renameLTyFamInstEqn :: LTyFamInstEqn Name -> RnM (LTyFamInstEqn DocName)
renameLTyFamInstEqn (L loc (TyFamEqn { tfe_tycon = tc, tfe_pats = pats_w_bndrs, tfe_rhs = rhs }))
= do { tc' <- renameL tc
; pats' <- mapM renameLType (hswb_cts pats_w_bndrs)
; rhs' <- renameLType rhs
; return (L loc (TyFamEqn { tfe_tycon = tc'
, tfe_pats = HsWB pats' PlaceHolder PlaceHolder PlaceHolder
, tfe_rhs = rhs' })) }
renameLTyFamDefltEqn :: LTyFamDefltEqn Name -> RnM (LTyFamDefltEqn DocName)
renameLTyFamDefltEqn (L loc (TyFamEqn { tfe_tycon = tc, tfe_pats = tvs, tfe_rhs = rhs }))
= do { tc' <- renameL tc
; tvs' <- renameLTyVarBndrs tvs
; rhs' <- renameLType rhs
; return (L loc (TyFamEqn { tfe_tycon = tc'
, tfe_pats = tvs'
, tfe_rhs = rhs' })) }
renameDataFamInstD :: DataFamInstDecl Name -> RnM (DataFamInstDecl DocName)
renameDataFamInstD (DataFamInstDecl { dfid_tycon = tc, dfid_pats = pats_w_bndrs, dfid_defn = defn })
= do { tc' <- renameL tc
; pats' <- mapM renameLType (hswb_cts pats_w_bndrs)
; defn' <- renameDataDefn defn
; return (DataFamInstDecl { dfid_tycon = tc'
, dfid_pats
= HsWB pats' PlaceHolder PlaceHolder PlaceHolder
, dfid_defn = defn', dfid_fvs = placeHolderNames }) }
renameExportItem :: ExportItem Name -> RnM (ExportItem DocName)
renameExportItem item = case item of
ExportModule mdl -> return (ExportModule mdl)
ExportGroup lev id_ doc -> do
doc' <- renameDoc doc
return (ExportGroup lev id_ doc')
ExportDecl decl doc subs instances fixities splice -> do
decl' <- renameLDecl decl
doc' <- renameDocForDecl doc
subs' <- mapM renameSub subs
instances' <- forM instances $ \(inst, idoc) -> do
inst' <- renameInstHead inst
idoc' <- mapM renameDoc idoc
return (inst', idoc')
fixities' <- forM fixities $ \(name, fixity) -> do
name' <- lookupRn name
return (name', fixity)
return (ExportDecl decl' doc' subs' instances' fixities' splice)
ExportNoDecl x subs -> do
x' <- lookupRn x
subs' <- mapM lookupRn subs
return (ExportNoDecl x' subs')
ExportDoc doc -> do
doc' <- renameDoc doc
return (ExportDoc doc')
renameSub :: (Name, DocForDecl Name) -> RnM (DocName, DocForDecl DocName)
renameSub (n,doc) = do
n' <- rename n
doc' <- renameDocForDecl doc
return (n', doc')
| mrBliss/haddock | haddock-api/src/Haddock/Interface/Rename.hs | bsd-2-clause | 19,393 | 0 | 17 | 4,699 | 6,067 | 3,025 | 3,042 | 374 | 22 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK not-home #-}
#include "version-compatibility-macros.h"
-- | __Warning:__ Internal module. May change arbitrarily between versions.
module Prettyprinter.Render.Terminal.Internal (
-- * Styling
AnsiStyle(..),
Color(..),
-- ** Font color
color, colorDull,
-- ** Background color
bgColor, bgColorDull,
-- ** Font style
bold, italicized, underlined,
-- ** Internal markers
Intensity(..),
Bold(..),
Underlined(..),
Italicized(..),
-- * Conversion to ANSI-infused 'Text'
renderLazy, renderStrict,
-- * Render directly to 'stdout'
renderIO,
-- ** Convenience functions
putDoc, hPutDoc,
) where
import Control.Applicative
import Data.IORef
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified System.Console.ANSI as ANSI
import System.IO (Handle, hPutChar, stdout)
import Prettyprinter
import Prettyprinter.Render.Util.Panic
#if !(SEMIGROUP_MONOID_SUPERCLASS)
import Data.Semigroup
#endif
#if !(MIN_VERSION_base(4,6,0))
modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' ref f = do
x <- readIORef ref
let x' = f x
x' `seq` writeIORef ref x'
#endif
-- $setup
--
-- (Definitions for the doctests)
--
-- >>> :set -XOverloadedStrings
-- >>> import qualified Data.Text.Lazy.IO as TL
-- >>> import qualified Data.Text.Lazy as TL
-- >>> import Prettyprinter.Render.Terminal
-- | The 8 ANSI terminal colors.
data Color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White
deriving (Eq, Ord, Show)
-- | Dull or vivid coloring, as supported by ANSI terminals.
data Intensity = Vivid | Dull
deriving (Eq, Ord, Show)
-- | Foreground (text) or background (paper) color
data Layer = Foreground | Background
deriving (Eq, Ord, Show)
data Bold = Bold deriving (Eq, Ord, Show)
data Underlined = Underlined deriving (Eq, Ord, Show)
data Italicized = Italicized deriving (Eq, Ord, Show)
-- | Style the foreground with a vivid color.
color :: Color -> AnsiStyle
color c = mempty { ansiForeground = Just (Vivid, c) }
-- | Style the background with a vivid color.
bgColor :: Color -> AnsiStyle
bgColor c = mempty { ansiBackground = Just (Vivid, c) }
-- | Style the foreground with a dull color.
colorDull :: Color -> AnsiStyle
colorDull c = mempty { ansiForeground = Just (Dull, c) }
-- | Style the background with a dull color.
bgColorDull :: Color -> AnsiStyle
bgColorDull c = mempty { ansiBackground = Just (Dull, c) }
-- | Render in __bold__.
bold :: AnsiStyle
bold = mempty { ansiBold = Just Bold }
-- | Render in /italics/.
italicized :: AnsiStyle
italicized = mempty { ansiItalics = Just Italicized }
-- | Render underlined.
underlined :: AnsiStyle
underlined = mempty { ansiUnderlining = Just Underlined }
-- | @('renderLazy' doc)@ takes the output @doc@ from a rendering function
-- and transforms it to lazy text, including ANSI styling directives for things
-- like colorization.
--
-- ANSI color information will be discarded by this function unless you are
-- running on a Unix-like operating system. This is due to a technical
-- limitation in Windows ANSI support.
--
-- With a bit of trickery to make the ANSI codes printable, here is an example
-- that would render colored in an ANSI terminal:
--
-- >>> let render = TL.putStrLn . TL.replace "\ESC" "\\e" . renderLazy . layoutPretty defaultLayoutOptions
-- >>> let doc = annotate (color Red) ("red" <+> align (vsep [annotate (color Blue <> underlined) ("blue+u" <+> annotate bold "bold" <+> "blue+u"), "red"]))
-- >>> render (unAnnotate doc)
-- red blue+u bold blue+u
-- red
-- >>> render doc
-- \e[0;91mred \e[0;94;4mblue+u \e[0;94;1;4mbold\e[0;94;4m blue+u\e[0;91m
-- red\e[0m
--
-- Run the above via @echo -e '...'@ in your terminal to see the coloring.
renderLazy :: SimpleDocStream AnsiStyle -> TL.Text
renderLazy =
let push x = (x :)
unsafePeek [] = panicPeekedEmpty
unsafePeek (x:_) = x
unsafePop [] = panicPoppedEmpty
unsafePop (x:xs) = (x, xs)
go :: [AnsiStyle] -> SimpleDocStream AnsiStyle -> TLB.Builder
go s sds = case sds of
SFail -> panicUncaughtFail
SEmpty -> mempty
SChar c rest -> TLB.singleton c <> go s rest
SText _ t rest -> TLB.fromText t <> go s rest
SLine i rest -> TLB.singleton '\n' <> TLB.fromText (T.replicate i " ") <> go s rest
SAnnPush style rest ->
let currentStyle = unsafePeek s
newStyle = style <> currentStyle
in TLB.fromText (styleToRawText newStyle) <> go (push style s) rest
SAnnPop rest ->
let (_currentStyle, s') = unsafePop s
newStyle = unsafePeek s'
in TLB.fromText (styleToRawText newStyle) <> go s' rest
in TLB.toLazyText . go [mempty]
-- | @('renderIO' h sdoc)@ writes @sdoc@ to the handle @h@.
--
-- >>> let render = renderIO System.IO.stdout . layoutPretty defaultLayoutOptions
-- >>> let doc = annotate (color Red) ("red" <+> align (vsep [annotate (color Blue <> underlined) ("blue+u" <+> annotate bold "bold" <+> "blue+u"), "red"]))
--
-- We render the 'unAnnotate'd version here, since the ANSI codes don’t display
-- well in Haddock,
--
-- >>> render (unAnnotate doc)
-- red blue+u bold blue+u
-- red
--
-- This function behaves just like
--
-- @
-- 'renderIO' h sdoc = 'TL.hPutStr' h ('renderLazy' sdoc)
-- @
--
-- but will not generate any intermediate text, rendering directly to the
-- handle.
renderIO :: Handle -> SimpleDocStream AnsiStyle -> IO ()
renderIO h sdoc = do
styleStackRef <- newIORef [mempty]
let push x = modifyIORef' styleStackRef (x :)
unsafePeek = readIORef styleStackRef >>= \tok -> case tok of
[] -> panicPeekedEmpty
x:_ -> pure x
unsafePop = readIORef styleStackRef >>= \tok -> case tok of
[] -> panicPoppedEmpty
x:xs -> writeIORef styleStackRef xs >> pure x
let go = \sds -> case sds of
SFail -> panicUncaughtFail
SEmpty -> pure ()
SChar c rest -> do
hPutChar h c
go rest
SText _ t rest -> do
T.hPutStr h t
go rest
SLine i rest -> do
hPutChar h '\n'
T.hPutStr h (T.replicate i (T.singleton ' '))
go rest
SAnnPush style rest -> do
currentStyle <- unsafePeek
let newStyle = style <> currentStyle
push newStyle
T.hPutStr h (styleToRawText newStyle)
go rest
SAnnPop rest -> do
_currentStyle <- unsafePop
newStyle <- unsafePeek
T.hPutStr h (styleToRawText newStyle)
go rest
go sdoc
readIORef styleStackRef >>= \stack -> case stack of
[] -> panicStyleStackFullyConsumed
[_] -> pure ()
xs -> panicStyleStackNotFullyConsumed (length xs)
panicStyleStackFullyConsumed :: void
panicStyleStackFullyConsumed
= error ("There is no empty style left at the end of rendering" ++
" (but there should be). Please report this as a bug.")
panicStyleStackNotFullyConsumed :: Int -> void
panicStyleStackNotFullyConsumed len
= error ("There are " <> show len <> " styles left at the" ++
"end of rendering (there should be only 1). Please report" ++
" this as a bug.")
-- $
-- >>> let render = renderIO System.IO.stdout . layoutPretty defaultLayoutOptions
-- >>> let doc = annotate (color Red) ("red" <+> align (vsep [annotate (color Blue <> underlined) ("blue+u" <+> annotate bold "bold" <+> "blue+u"), "red"]))
-- >>> render (unAnnotate doc)
-- red blue+u bold blue+u
-- red
--
-- This test won’t work since I don’t know how to type \ESC for doctest :-/
-- -- >>> render doc
-- -- \ESC[0;91mred \ESC[0;94;4mblue+u \ESC[0;94;1;4mbold\ESC[0;94;4m blue+u\ESC[0;91m
-- -- red\ESC[0m
-- | Render the annotated document in a certain style. Styles not set in the
-- annotation will use the style of the surrounding document, or the terminal’s
-- default if none has been set yet.
--
-- @
-- style = 'color' 'Green' '<>' 'bold'
-- styledDoc = 'annotate' style "hello world"
-- @
data AnsiStyle = SetAnsiStyle
{ ansiForeground :: Maybe (Intensity, Color) -- ^ Set the foreground color, or keep the old one.
, ansiBackground :: Maybe (Intensity, Color) -- ^ Set the background color, or keep the old one.
, ansiBold :: Maybe Bold -- ^ Switch on boldness, or don’t do anything.
, ansiItalics :: Maybe Italicized -- ^ Switch on italics, or don’t do anything.
, ansiUnderlining :: Maybe Underlined -- ^ Switch on underlining, or don’t do anything.
} deriving (Eq, Ord, Show)
-- | Keep the first decision for each of foreground color, background color,
-- boldness, italication, and underlining. If a certain style is not set, the
-- terminal’s default will be used.
--
-- Example:
--
-- @
-- 'color' 'Red' '<>' 'color' 'Green'
-- @
--
-- is red because the first color wins, and not bold because (or if) that’s the
-- terminal’s default.
instance Semigroup AnsiStyle where
cs1 <> cs2 = SetAnsiStyle
{ ansiForeground = ansiForeground cs1 <|> ansiForeground cs2
, ansiBackground = ansiBackground cs1 <|> ansiBackground cs2
, ansiBold = ansiBold cs1 <|> ansiBold cs2
, ansiItalics = ansiItalics cs1 <|> ansiItalics cs2
, ansiUnderlining = ansiUnderlining cs1 <|> ansiUnderlining cs2 }
-- | 'mempty' does nothing, which is equivalent to inheriting the style of the
-- surrounding doc, or the terminal’s default if no style has been set yet.
instance Monoid AnsiStyle where
mempty = SetAnsiStyle Nothing Nothing Nothing Nothing Nothing
mappend = (<>)
styleToRawText :: AnsiStyle -> Text
styleToRawText = T.pack . ANSI.setSGRCode . stylesToSgrs
where
stylesToSgrs :: AnsiStyle -> [ANSI.SGR]
stylesToSgrs (SetAnsiStyle fg bg b i u) = catMaybes
[ Just ANSI.Reset
, fmap (\(intensity, c) -> ANSI.SetColor ANSI.Foreground (convertIntensity intensity) (convertColor c)) fg
, fmap (\(intensity, c) -> ANSI.SetColor ANSI.Background (convertIntensity intensity) (convertColor c)) bg
, fmap (\_ -> ANSI.SetConsoleIntensity ANSI.BoldIntensity) b
, fmap (\_ -> ANSI.SetItalicized True) i
, fmap (\_ -> ANSI.SetUnderlining ANSI.SingleUnderline) u
]
convertIntensity :: Intensity -> ANSI.ColorIntensity
convertIntensity = \i -> case i of
Vivid -> ANSI.Vivid
Dull -> ANSI.Dull
convertColor :: Color -> ANSI.Color
convertColor = \c -> case c of
Black -> ANSI.Black
Red -> ANSI.Red
Green -> ANSI.Green
Yellow -> ANSI.Yellow
Blue -> ANSI.Blue
Magenta -> ANSI.Magenta
Cyan -> ANSI.Cyan
White -> ANSI.White
-- | @('renderStrict' sdoc)@ takes the output @sdoc@ from a rendering and
-- transforms it to strict text.
renderStrict :: SimpleDocStream AnsiStyle -> Text
renderStrict = TL.toStrict . renderLazy
-- | @('putDoc' doc)@ prettyprints document @doc@ to standard output using
-- 'defaultLayoutOptions'.
--
-- >>> putDoc ("hello" <+> "world")
-- hello world
--
-- @
-- 'putDoc' = 'hPutDoc' 'stdout'
-- @
putDoc :: Doc AnsiStyle -> IO ()
putDoc = hPutDoc stdout
-- | Like 'putDoc', but instead of using 'stdout', print to a user-provided
-- handle, e.g. a file or a socket using 'defaultLayoutOptions'.
--
-- > main = withFile "someFile.txt" (\h -> hPutDoc h (vcat ["vertical", "text"]))
--
-- @
-- 'hPutDoc' h doc = 'renderIO' h ('layoutPretty' 'defaultLayoutOptions' doc)
-- @
hPutDoc :: Handle -> Doc AnsiStyle -> IO ()
hPutDoc h doc = renderIO h (layoutPretty defaultLayoutOptions doc)
| quchen/prettyprinter | prettyprinter-ansi-terminal/src/Prettyprinter/Render/Terminal/Internal.hs | bsd-2-clause | 12,351 | 0 | 21 | 3,186 | 2,318 | 1,272 | 1,046 | 175 | 11 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE FlexibleContexts #-}
module Propellor.Property (
-- * Property combinators
requires
, before
, onChange
, onChangeFlagOnFail
, flagFile
, flagFile'
, check
, fallback
, trivial
, revert
-- * Property descriptions
, describe
, (==>)
-- * Constructing properties
, Propellor
, property
, ensureProperty
, withOS
, makeChange
, noChange
, doNothing
, endAction
) where
import System.Directory
import System.FilePath
import Control.Monad
import Data.Monoid
import Control.Monad.IfElse
import "mtl" Control.Monad.RWS.Strict
import Propellor.Types
import Propellor.Info
import Propellor.Exception
import Utility.Monad
-- | Constructs a Property, from a description and an action to run to
-- ensure the Property is met.
property :: Desc -> Propellor Result -> Property NoInfo
property d s = simpleProperty d s mempty
-- | Makes a perhaps non-idempotent Property be idempotent by using a flag
-- file to indicate whether it has run before.
-- Use with caution.
flagFile :: Property i -> FilePath -> Property i
flagFile p = flagFile' p . return
flagFile' :: Property i -> IO FilePath -> Property i
flagFile' p getflagfile = adjustPropertySatisfy p $ \satisfy -> do
flagfile <- liftIO getflagfile
go satisfy flagfile =<< liftIO (doesFileExist flagfile)
where
go _ _ True = return NoChange
go satisfy flagfile False = do
r <- satisfy
when (r == MadeChange) $ liftIO $
unlessM (doesFileExist flagfile) $ do
createDirectoryIfMissing True (takeDirectory flagfile)
writeFile flagfile ""
return r
-- | Indicates that the first property depends on the second,
-- so before the first is ensured, the second must be ensured.
--
-- The combined property uses the description of the first property.
requires :: Combines x y => x -> y -> CombinedType x y
requires = combineWith
-- Run action of y, then x
(flip (<>))
-- When reverting, run in reverse order.
(<>)
-- | Combines together two properties, resulting in one property
-- that ensures the first, and if the first succeeds, ensures the second.
--
-- The combined property uses the description of the first property.
before :: Combines x y => x -> y -> CombinedType x y
before = combineWith
-- Run action of x, then y
(<>)
-- When reverting, run in reverse order.
(flip (<>))
-- | Whenever a change has to be made for a Property, causes a hook
-- Property to also be run, but not otherwise.
onChange
:: (Combines x y)
=> x
-> y
-> CombinedType x y
onChange = combineWith combiner revertcombiner
where
combiner p hook = do
r <- p
case r of
MadeChange -> do
r' <- hook
return $ r <> r'
_ -> return r
revertcombiner = (<>)
-- | Same as `onChange` except that if property y fails, a flag file
-- is generated. On next run, if the flag file is present, property y
-- is executed even if property x doesn't change.
--
-- With `onChange`, if y fails, the property x `onChange` y returns
-- `FailedChange`. But if this property is applied again, it returns
-- `NoChange`. This behavior can cause trouble...
onChangeFlagOnFail
:: (Combines x y)
=> FilePath
-> x
-> y
-> CombinedType x y
onChangeFlagOnFail flagfile = combineWith combiner revertcombiner
where
combiner s1 s2 = do
r1 <- s1
case r1 of
MadeChange -> flagFailed s2
_ -> ifM (liftIO $ doesFileExist flagfile)
(flagFailed s2
, return r1
)
revertcombiner = (<>)
flagFailed s = do
r <- s
liftIO $ case r of
FailedChange -> createFlagFile
_ -> removeFlagFile
return r
createFlagFile = unlessM (doesFileExist flagfile) $ do
createDirectoryIfMissing True (takeDirectory flagfile)
writeFile flagfile ""
removeFlagFile = whenM (doesFileExist flagfile) $ removeFile flagfile
-- | Changes the description of a property.
describe :: IsProp p => p -> Desc -> p
describe = setDesc
-- | Alias for @flip describe@
(==>) :: IsProp (Property i) => Desc -> Property i -> Property i
(==>) = flip describe
infixl 1 ==>
-- | For when code running in the Propellor monad needs to ensure a
-- Property.
--
-- This can only be used on a Property that has NoInfo.
ensureProperty :: Property NoInfo -> Propellor Result
ensureProperty = catchPropellor . propertySatisfy
-- | Makes a Property only need to do anything when a test succeeds.
check :: (LiftPropellor m) => m Bool -> Property i -> Property i
check c p = adjustPropertySatisfy p $ \satisfy ->
ifM (liftPropellor c)
( satisfy
, return NoChange
)
-- | Tries the first property, but if it fails to work, instead uses
-- the second.
fallback :: (Combines p1 p2) => p1 -> p2 -> CombinedType p1 p2
fallback = combineWith combiner revertcombiner
where
combiner a1 a2 = do
r <- a1
if r == FailedChange
then a2
else return r
revertcombiner = (<>)
-- | Marks a Property as trivial. It can only return FailedChange or
-- NoChange.
--
-- Useful when it's just as expensive to check if a change needs
-- to be made as it is to just idempotently assure the property is
-- satisfied. For example, chmodding a file.
trivial :: Property i -> Property i
trivial p = adjustPropertySatisfy p $ \satisfy -> do
r <- satisfy
if r == MadeChange
then return NoChange
else return r
-- | Makes a property that is satisfied differently depending on the host's
-- operating system.
--
-- Note that the operating system may not be declared for all hosts.
--
-- > myproperty = withOS "foo installed" $ \o -> case o of
-- > (Just (System (Debian suite) arch)) -> ...
-- > (Just (System (Ubuntu release) arch)) -> ...
-- > Nothing -> ...
withOS :: Desc -> (Maybe System -> Propellor Result) -> Property NoInfo
withOS desc a = property desc $ a =<< getOS
-- | Undoes the effect of a RevertableProperty.
revert :: RevertableProperty i -> RevertableProperty i
revert (RevertableProperty p1 p2) = RevertableProperty p2 p1
makeChange :: IO () -> Propellor Result
makeChange a = liftIO a >> return MadeChange
noChange :: Propellor Result
noChange = return NoChange
doNothing :: Property NoInfo
doNothing = property "noop property" noChange
-- | Registers an action that should be run at the very end, after
-- propellor has checks all the properties of a host.
endAction :: Desc -> (Result -> Propellor Result) -> Propellor ()
endAction desc a = tell [EndAction desc a]
| np/propellor | src/Propellor/Property.hs | bsd-2-clause | 6,320 | 38 | 15 | 1,282 | 1,409 | 737 | 672 | 134 | 3 |
{-# LANGUAGE CPP, PatternGuards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Convert
-- Copyright : (c) Isaac Dupree 2009,
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Conversion between TyThing and HsDecl. This functionality may be moved into
-- GHC at some point.
-----------------------------------------------------------------------------
module Haddock.Convert where
-- Some other functions turned out to be useful for converting
-- instance heads, which aren't TyThings, so just export everything.
import Bag ( emptyBag )
import BasicTypes ( TupleSort(..) )
import Class
import CoAxiom
import ConLike
import Data.Either (lefts, rights)
import DataCon
import FamInstEnv
import HsSyn
import Name
import RdrName ( mkVarUnqual )
import PatSyn
import SrcLoc ( Located, noLoc, unLoc )
import TcType ( tcSplitSigmaTy )
import TyCon
import Type
import TyCoRep
import TysPrim ( alphaTyVars )
import TysWiredIn ( listTyConName, ipTyCon )
import PrelNames ( hasKey, eqTyConKey )
import Unique ( getUnique )
import Util ( filterByList, filterOut )
import Var
import Haddock.Types
import Haddock.Interface.Specialize
-- the main function here! yay!
tyThingToLHsDecl :: TyThing -> Either ErrMsg ([ErrMsg], (HsDecl Name))
tyThingToLHsDecl t = case t of
-- ids (functions and zero-argument a.k.a. CAFs) get a type signature.
-- Including built-in functions like seq.
-- foreign-imported functions could be represented with ForD
-- instead of SigD if we wanted...
--
-- in a future code version we could turn idVarDetails = foreign-call
-- into a ForD instead of a SigD if we wanted. Haddock doesn't
-- need to care.
AnId i -> allOK $ SigD (synifyIdSig ImplicitizeForAll i)
-- type-constructors (e.g. Maybe) are complicated, put the definition
-- later in the file (also it's used for class associated-types too.)
ATyCon tc
| Just cl <- tyConClass_maybe tc -- classes are just a little tedious
-> let extractFamilyDecl :: TyClDecl a -> Either ErrMsg (LFamilyDecl a)
extractFamilyDecl (FamDecl d) = return $ noLoc d
extractFamilyDecl _ =
Left "tyThingToLHsDecl: impossible associated tycon"
atTyClDecls = [synifyTyCon Nothing at_tc | ATI at_tc _ <- classATItems cl]
atFamDecls = map extractFamilyDecl (rights atTyClDecls)
tyClErrors = lefts atTyClDecls
famDeclErrors = lefts atFamDecls
in withErrs (tyClErrors ++ famDeclErrors) . TyClD $ ClassDecl
{ tcdCtxt = synifyCtx (classSCTheta cl)
, tcdLName = synifyName cl
, tcdTyVars = synifyTyVars (classTyVars cl)
, tcdFDs = map (\ (l,r) -> noLoc
(map (noLoc . getName) l, map (noLoc . getName) r) ) $
snd $ classTvsFds cl
, tcdSigs = noLoc (MinimalSig mempty . noLoc . fmap noLoc $ classMinimalDef cl) :
map (noLoc . synifyIdSig DeleteTopLevelQuantification)
(classMethods cl)
, tcdMeths = emptyBag --ignore default method definitions, they don't affect signature
-- class associated-types are a subset of TyCon:
, tcdATs = rights atFamDecls
, tcdATDefs = [] --ignore associated type defaults
, tcdDocs = [] --we don't have any docs at this point
, tcdFVs = placeHolderNamesTc }
| otherwise
-> synifyTyCon Nothing tc >>= allOK . TyClD
-- type-constructors (e.g. Maybe) are complicated, put the definition
-- later in the file (also it's used for class associated-types too.)
ACoAxiom ax -> synifyAxiom ax >>= allOK
-- a data-constructor alone just gets rendered as a function:
AConLike (RealDataCon dc) -> allOK $ SigD (TypeSig [synifyName dc]
(synifySigWcType ImplicitizeForAll (dataConUserType dc)))
AConLike (PatSynCon ps) ->
allOK . SigD $ PatSynSig (synifyName ps) (synifySigType WithinType
(patSynType ps))
where
withErrs e x = return (e, x)
allOK x = return (mempty, x)
synifyAxBranch :: TyCon -> CoAxBranch -> TyFamInstEqn Name
synifyAxBranch tc (CoAxBranch { cab_tvs = tkvs, cab_lhs = args, cab_rhs = rhs })
= let name = synifyName tc
typats = map (synifyType WithinType) args
hs_rhs = synifyType WithinType rhs
in TyFamEqn { tfe_tycon = name
, tfe_pats = HsIB { hsib_body = typats
, hsib_vars = map tyVarName tkvs }
, tfe_rhs = hs_rhs }
synifyAxiom :: CoAxiom br -> Either ErrMsg (HsDecl Name)
synifyAxiom ax@(CoAxiom { co_ax_tc = tc })
| isOpenTypeFamilyTyCon tc
, Just branch <- coAxiomSingleBranch_maybe ax
= return $ InstD (TyFamInstD
(TyFamInstDecl { tfid_eqn = noLoc $ synifyAxBranch tc branch
, tfid_fvs = placeHolderNamesTc }))
| Just ax' <- isClosedSynFamilyTyConWithAxiom_maybe tc
, getUnique ax' == getUnique ax -- without the getUniques, type error
= synifyTyCon (Just ax) tc >>= return . TyClD
| otherwise
= Left "synifyAxiom: closed/open family confusion"
-- | Turn type constructors into type class declarations
synifyTyCon :: Maybe (CoAxiom br) -> TyCon -> Either ErrMsg (TyClDecl Name)
synifyTyCon _coax tc
| isFunTyCon tc || isPrimTyCon tc
= return $
DataDecl { tcdLName = synifyName tc
, tcdTyVars = -- tyConTyVars doesn't work on fun/prim, but we can make them up:
let mk_hs_tv realKind fakeTyVar
= noLoc $ KindedTyVar (noLoc (getName fakeTyVar))
(synifyKindSig realKind)
in HsQTvs { hsq_implicit = [] -- No kind polymorphism
, hsq_explicit = zipWith mk_hs_tv (fst (splitFunTys (tyConKind tc)))
alphaTyVars --a, b, c... which are unfortunately all kind *
}
, tcdDataDefn = HsDataDefn { dd_ND = DataType -- arbitrary lie, they are neither
-- algebraic data nor newtype:
, dd_ctxt = noLoc []
, dd_cType = Nothing
, dd_kindSig = Just (synifyKindSig (tyConKind tc))
-- we have their kind accurately:
, dd_cons = [] -- No constructors
, dd_derivs = Nothing }
, tcdFVs = placeHolderNamesTc }
synifyTyCon _coax tc
| Just flav <- famTyConFlav_maybe tc
= case flav of
-- Type families
OpenSynFamilyTyCon -> mkFamDecl OpenTypeFamily
ClosedSynFamilyTyCon mb
| Just (CoAxiom { co_ax_branches = branches }) <- mb
-> mkFamDecl $ ClosedTypeFamily $ Just
$ map (noLoc . synifyAxBranch tc) (fromBranches branches)
| otherwise
-> mkFamDecl $ ClosedTypeFamily $ Just []
BuiltInSynFamTyCon {}
-> mkFamDecl $ ClosedTypeFamily $ Just []
AbstractClosedSynFamilyTyCon {}
-> mkFamDecl $ ClosedTypeFamily Nothing
DataFamilyTyCon {}
-> mkFamDecl DataFamily
where
resultVar = famTcResVar tc
mkFamDecl i = return $ FamDecl $
FamilyDecl { fdInfo = i
, fdLName = synifyName tc
, fdTyVars = synifyTyVars (tyConTyVars tc)
, fdResultSig =
synifyFamilyResultSig resultVar tyConResKind
, fdInjectivityAnn =
synifyInjectivityAnn resultVar (tyConTyVars tc)
(familyTyConInjectivityInfo tc)
}
tyConResKind = piResultTys (tyConKind tc) (mkTyVarTys (tyConTyVars tc))
synifyTyCon coax tc
| Just ty <- synTyConRhs_maybe tc
= return $ SynDecl { tcdLName = synifyName tc
, tcdTyVars = synifyTyVars (tyConTyVars tc)
, tcdRhs = synifyType WithinType ty
, tcdFVs = placeHolderNamesTc }
| otherwise =
-- (closed) newtype and data
let
alg_nd = if isNewTyCon tc then NewType else DataType
alg_ctx = synifyCtx (tyConStupidTheta tc)
name = case coax of
Just a -> synifyName a -- Data families are named according to their
-- CoAxioms, not their TyCons
_ -> synifyName tc
tyvars = synifyTyVars (tyConTyVars tc)
kindSig = Just (tyConKind tc)
-- The data constructors.
--
-- Any data-constructors not exported from the module that *defines* the
-- type will not (cannot) be included.
--
-- Very simple constructors, Haskell98 with no existentials or anything,
-- probably look nicer in non-GADT syntax. In source code, all constructors
-- must be declared with the same (GADT vs. not) syntax, and it probably
-- is less confusing to follow that principle for the documentation as well.
--
-- There is no sensible infix-representation for GADT-syntax constructor
-- declarations. They cannot be made in source code, but we could end up
-- with some here in the case where some constructors use existentials.
-- That seems like an acceptable compromise (they'll just be documented
-- in prefix position), since, otherwise, the logic (at best) gets much more
-- complicated. (would use dataConIsInfix.)
use_gadt_syntax = any (not . isVanillaDataCon) (tyConDataCons tc)
consRaw = map (synifyDataCon use_gadt_syntax) (tyConDataCons tc)
cons = rights consRaw
-- "deriving" doesn't affect the signature, no need to specify any.
alg_deriv = Nothing
defn = HsDataDefn { dd_ND = alg_nd
, dd_ctxt = alg_ctx
, dd_cType = Nothing
, dd_kindSig = fmap synifyKindSig kindSig
, dd_cons = cons
, dd_derivs = alg_deriv }
in case lefts consRaw of
[] -> return $
DataDecl { tcdLName = name, tcdTyVars = tyvars, tcdDataDefn = defn
, tcdFVs = placeHolderNamesTc }
dataConErrs -> Left $ unlines dataConErrs
synifyInjectivityAnn :: Maybe Name -> [TyVar] -> Injectivity
-> Maybe (LInjectivityAnn Name)
synifyInjectivityAnn Nothing _ _ = Nothing
synifyInjectivityAnn _ _ NotInjective = Nothing
synifyInjectivityAnn (Just lhs) tvs (Injective inj) =
let rhs = map (noLoc . tyVarName) (filterByList inj tvs)
in Just $ noLoc $ InjectivityAnn (noLoc lhs) rhs
synifyFamilyResultSig :: Maybe Name -> Kind -> LFamilyResultSig Name
synifyFamilyResultSig Nothing kind =
noLoc $ KindSig (synifyKindSig kind)
synifyFamilyResultSig (Just name) kind =
noLoc $ TyVarSig (noLoc $ KindedTyVar (noLoc name) (synifyKindSig kind))
-- User beware: it is your responsibility to pass True (use_gadt_syntax)
-- for any constructor that would be misrepresented by omitting its
-- result-type.
-- But you might want pass False in simple enough cases,
-- if you think it looks better.
synifyDataCon :: Bool -> DataCon -> Either ErrMsg (LConDecl Name)
synifyDataCon use_gadt_syntax dc =
let
-- dataConIsInfix allegedly tells us whether it was declared with
-- infix *syntax*.
use_infix_syntax = dataConIsInfix dc
use_named_field_syntax = not (null field_tys)
name = synifyName dc
-- con_qvars means a different thing depending on gadt-syntax
(univ_tvs, ex_tvs, _eq_spec, theta, arg_tys, res_ty) = dataConFullSig dc
qvars = if use_gadt_syntax
then synifyTyVars (univ_tvs ++ ex_tvs)
else synifyTyVars ex_tvs
-- skip any EqTheta, use 'orig'inal syntax
ctx = synifyCtx theta
linear_tys =
zipWith (\ty bang ->
let tySyn = synifyType WithinType ty
in case bang of
(HsSrcBang _ NoSrcUnpack NoSrcStrict) -> tySyn
bang' -> noLoc $ HsBangTy bang' tySyn)
arg_tys (dataConSrcBangs dc)
field_tys = zipWith con_decl_field (dataConFieldLabels dc) linear_tys
con_decl_field fl synTy = noLoc $
ConDeclField [noLoc $ FieldOcc (noLoc $ mkVarUnqual $ flLabel fl) (flSelector fl)] synTy
Nothing
hs_arg_tys = case (use_named_field_syntax, use_infix_syntax) of
(True,True) -> Left "synifyDataCon: contradiction!"
(True,False) -> return $ RecCon (noLoc field_tys)
(False,False) -> return $ PrefixCon linear_tys
(False,True) -> case linear_tys of
[a,b] -> return $ InfixCon a b
_ -> Left "synifyDataCon: infix with non-2 args?"
gadt_ty = HsIB [] (synifyType WithinType res_ty)
-- finally we get synifyDataCon's result!
in hs_arg_tys >>=
\hat ->
if use_gadt_syntax
then return $ noLoc $
ConDeclGADT { con_names = [name]
, con_type = gadt_ty
, con_doc = Nothing }
else return $ noLoc $
ConDeclH98 { con_name = name
, con_qvars = Just qvars
, con_cxt = Just ctx
, con_details = hat
, con_doc = Nothing }
synifyName :: NamedThing n => n -> Located Name
synifyName = noLoc . getName
synifyIdSig :: SynifyTypeState -> Id -> Sig Name
synifyIdSig s i = TypeSig [synifyName i] (synifySigWcType s (varType i))
synifyCtx :: [PredType] -> LHsContext Name
synifyCtx = noLoc . map (synifyType WithinType)
synifyTyVars :: [TyVar] -> LHsQTyVars Name
synifyTyVars ktvs = HsQTvs { hsq_implicit = []
, hsq_explicit = map synifyTyVar ktvs }
synifyTyVar :: TyVar -> LHsTyVarBndr Name
synifyTyVar tv
| isLiftedTypeKind kind = noLoc (UserTyVar (noLoc name))
| otherwise = noLoc (KindedTyVar (noLoc name) (synifyKindSig kind))
where
kind = tyVarKind tv
name = getName tv
--states of what to do with foralls:
data SynifyTypeState
= WithinType
-- ^ normal situation. This is the safe one to use if you don't
-- quite understand what's going on.
| ImplicitizeForAll
-- ^ beginning of a function definition, in which, to make it look
-- less ugly, those rank-1 foralls are made implicit.
| DeleteTopLevelQuantification
-- ^ because in class methods the context is added to the type
-- (e.g. adding @forall a. Num a =>@ to @(+) :: a -> a -> a@)
-- which is rather sensible,
-- but we want to restore things to the source-syntax situation where
-- the defining class gets to quantify all its functions for free!
synifySigType :: SynifyTypeState -> Type -> LHsSigType Name
-- The empty binders is a bit suspicious;
-- what if the type has free variables?
synifySigType s ty = mkEmptyImplicitBndrs (synifyType s ty)
synifySigWcType :: SynifyTypeState -> Type -> LHsSigWcType Name
-- Ditto (see synifySigType)
synifySigWcType s ty = mkEmptyImplicitBndrs (mkEmptyWildCardBndrs (synifyType s ty))
synifyType :: SynifyTypeState -> Type -> LHsType Name
synifyType _ (TyVarTy tv) = noLoc $ HsTyVar $ noLoc (getName tv)
synifyType _ (TyConApp tc tys)
-- Use non-prefix tuple syntax where possible, because it looks nicer.
| Just sort <- tyConTuple_maybe tc
, tyConArity tc == length tys
= noLoc $ HsTupleTy (case sort of
BoxedTuple -> HsBoxedTuple
ConstraintTuple -> HsConstraintTuple
UnboxedTuple -> HsUnboxedTuple)
(map (synifyType WithinType) tys)
-- ditto for lists
| getName tc == listTyConName, [ty] <- tys =
noLoc $ HsListTy (synifyType WithinType ty)
-- ditto for implicit parameter tycons
| tc == ipTyCon
, [name, ty] <- tys
, Just x <- isStrLitTy name
= noLoc $ HsIParamTy (HsIPName x) (synifyType WithinType ty)
-- and equalities
| tc `hasKey` eqTyConKey
, [ty1, ty2] <- tys
= noLoc $ HsEqTy (synifyType WithinType ty1) (synifyType WithinType ty2)
-- Most TyCons:
| otherwise =
foldl (\t1 t2 -> noLoc (HsAppTy t1 t2))
(noLoc $ HsTyVar $ noLoc (getName tc))
(map (synifyType WithinType) $
filterOut isCoercionTy tys)
synifyType s (AppTy t1 (CoercionTy {})) = synifyType s t1
synifyType _ (AppTy t1 t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsAppTy s1 s2
synifyType _ (ForAllTy (Anon t1) t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsFunTy s1 s2
synifyType s forallty@(ForAllTy _tv _ty) =
let (tvs, ctx, tau) = tcSplitSigmaTy forallty
sPhi = HsQualTy { hst_ctxt = synifyCtx ctx
, hst_body = synifyType WithinType tau }
in case s of
DeleteTopLevelQuantification -> synifyType ImplicitizeForAll tau
WithinType -> noLoc $ HsForAllTy { hst_bndrs = map synifyTyVar tvs
, hst_body = noLoc sPhi }
ImplicitizeForAll -> noLoc sPhi
synifyType _ (LitTy t) = noLoc $ HsTyLit $ synifyTyLit t
synifyType s (CastTy t _) = synifyType s t
synifyType _ (CoercionTy {}) = error "synifyType:Coercion"
synifyTyLit :: TyLit -> HsTyLit
synifyTyLit (NumTyLit n) = HsNumTy mempty n
synifyTyLit (StrTyLit s) = HsStrTy mempty s
synifyKindSig :: Kind -> LHsKind Name
synifyKindSig k = synifyType WithinType k
synifyInstHead :: ([TyVar], [PredType], Class, [Type]) -> InstHead Name
synifyInstHead (_, preds, cls, types) = specializeInstHead $ InstHead
{ ihdClsName = getName cls
, ihdKinds = map (unLoc . synifyType WithinType) ks
, ihdTypes = map (unLoc . synifyType WithinType) ts
, ihdInstType = ClassInst
{ clsiCtx = map (unLoc . synifyType WithinType) preds
, clsiTyVars = synifyTyVars $ classTyVars cls
, clsiSigs = map synifyClsIdSig $ classMethods cls
, clsiAssocTys = do
(Right (FamDecl fam)) <- map (synifyTyCon Nothing) $ classATs cls
pure $ mkPseudoFamilyDecl fam
}
}
where
(ks,ts) = partitionInvisibles (classTyCon cls) id types
synifyClsIdSig = synifyIdSig DeleteTopLevelQuantification
-- Convert a family instance, this could be a type family or data family
synifyFamInst :: FamInst -> Bool -> Either ErrMsg (InstHead Name)
synifyFamInst fi opaque = do
ityp' <- ityp $ fi_flavor fi
return InstHead
{ ihdClsName = fi_fam fi
, ihdKinds = synifyTypes ks
, ihdTypes = synifyTypes ts
, ihdInstType = ityp'
}
where
ityp SynFamilyInst | opaque = return $ TypeInst Nothing
ityp SynFamilyInst =
return . TypeInst . Just . unLoc . synifyType WithinType $ fi_rhs fi
ityp (DataFamilyInst c) =
DataInst <$> synifyTyCon (Just $ famInstAxiom fi) c
(ks,ts) = partitionInvisibles (famInstTyCon fi) id $ fi_tys fi
synifyTypes = map (unLoc. synifyType WithinType)
| randen/haddock | haddock-api/src/Haddock/Convert.hs | bsd-2-clause | 19,092 | 0 | 23 | 5,452 | 4,399 | 2,292 | 2,107 | 319 | 8 |
module Propellor.Property.Cron where
import Propellor
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Apt as Apt
import Utility.SafeCommand
import Utility.FileMode
import Data.Char
-- | When to run a cron job.
--
-- The Daily, Monthly, and Weekly options allow the cron job to be run
-- by anacron, which is useful for non-servers.
data Times
= Times String -- ^ formatted as in crontab(5)
| Daily
| Weekly
| Monthly
-- | Installs a cron job, that will run as a specified user in a particular
-- directory. Note that the Desc must be unique, as it is used for the
-- cron job filename.
--
-- Only one instance of the cron job is allowed to run at a time, no matter
-- how long it runs. This is accomplished using flock locking of the cron
-- job file.
--
-- The cron job's output will only be emailed if it exits nonzero.
job :: Desc -> Times -> UserName -> FilePath -> String -> Property NoInfo
job desc times user cddir command = combineProperties ("cronned " ++ desc)
[ cronjobfile `File.hasContent`
[ "# Generated by propellor"
, ""
, "SHELL=/bin/sh"
, "PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
, ""
, case times of
Times t -> t ++ "\t" ++ user ++ "\tchronic " ++ shellEscape scriptfile
_ -> case user of
"root" -> "chronic " ++ shellEscape scriptfile
_ -> "chronic su " ++ user ++ " -c " ++ shellEscape scriptfile
]
, case times of
Times _ -> doNothing
_ -> cronjobfile `File.mode` combineModes (readModes ++ executeModes)
-- Use a separate script because it makes the cron job name
-- prettier in emails, and also allows running the job manually.
, scriptfile `File.hasContent`
[ "#!/bin/sh"
, "# Generated by propellor"
, "set -e"
, "flock -n " ++ shellEscape cronjobfile
++ " sh -c " ++ shellEscape cmdline
]
, scriptfile `File.mode` combineModes (readModes ++ executeModes)
]
`requires` Apt.serviceInstalledRunning "cron"
`requires` Apt.installed ["util-linux", "moreutils"]
where
cmdline = "cd " ++ cddir ++ " && ( " ++ command ++ " )"
cronjobfile = "/etc" </> cronjobdir </> name
cronjobdir = case times of
Times _ -> "cron.d"
Daily -> "cron.daily"
Weekly -> "cron.weekly"
Monthly -> "cron.monthly"
scriptfile = "/usr/local/bin/" ++ name ++ "_cronjob"
name = map sanitize desc
sanitize c
| isAlphaNum c = c
| otherwise = '_'
-- | Installs a cron job, and runs it niced and ioniced.
niceJob :: Desc -> Times -> UserName -> FilePath -> String -> Property NoInfo
niceJob desc times user cddir command = job desc times user cddir
("nice ionice -c 3 sh -c " ++ shellEscape command)
-- | Installs a cron job to run propellor.
runPropellor :: Times -> Property NoInfo
runPropellor times = niceJob "propellor" times "root" localdir "./propellor"
| aisamanra/smaccm-propellor | src/Propellor/Property/Cron.hs | bsd-2-clause | 2,799 | 20 | 19 | 547 | 607 | 331 | 276 | 54 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Syncthing.Types.Version
( Version(..)
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (MonadPlus (mzero))
import Data.Aeson (FromJSON, Value (..), parseJSON, (.:))
import Data.Text (Text)
-- | Current Syncthing version information.
data Version = Version {
getArch :: Text
, getLongVersion :: Text
, getOs :: Text
, getVersion :: Text
} deriving (Eq, Show)
instance FromJSON Version where
parseJSON (Object v) =
Version <$> (v .: "arch")
<*> (v .: "longVersion")
<*> (v .: "os")
<*> (v .: "version")
parseJSON _ = mzero
| jetho/syncthing-hs | Network/Syncthing/Types/Version.hs | bsd-3-clause | 840 | 0 | 11 | 334 | 203 | 124 | 79 | 20 | 0 |
-- | A module that provides an experimental syntax highlighter using TextMate
-- syntax files.
module Text.SyntaxHighlight.TextMate (
TMSyntaxFile, parseSyntaxFile,
HLFile(..), HLSegment(..), highlightFile,
) where
import Data.Array
import Data.List
import Data.List.Split
import qualified Data.Map as M
import Text.Regex.Base
import Text.Regex.PCRE.String
import Text.XML.Plist
data TMSyntaxFile =
TMSyntaxFile {
fileTypes :: [String],
fileName :: String,
patterns :: [TMRule],
repository :: M.Map String TMRule,
scopeName :: String,
uniqueId :: String
}
data TMRule =
Include {
ruleKey :: String
}
| Match {
regex :: Regex,
name :: String,
captures :: M.Map Int TMCapture
}
| RangeMatch {
startRegex :: Regex,
startCaptures :: M.Map Int TMCapture,
endRegex :: Regex,
endCaptures :: M.Map Int TMCapture,
name :: String,
contentName :: Maybe String,
rmRules :: [TMRule]
}
| MultiRule {
rmRules :: [TMRule]
}
data TMCapture = TMCapture {
identifier :: Int,
nameAttribute :: String
}
parseSyntaxFile :: String -> IO TMSyntaxFile
parseSyntaxFile str = do
root <- readPlistFromFile str
let
vForK :: PlObject -> String -> PlObject
vForK (PlDict kvs) k = head [v | (k',v) <- kvs, k' == k]
vForK _ _ = error "vForK: invalid arg"
hasKey :: PlObject -> String -> Bool
hasKey (PlDict kvs) k = length [v | (k',v) <- kvs, k' == k] > 0
hasKey _ _ = error "hasKey: invalid arg"
exStr :: PlObject -> String
exStr (PlString s) = s
exStr _ = error "exStr: not a string"
exList :: PlObject -> [PlObject]
exList (PlArray as) = as
exList _ = error "exList: not a list"
exDict :: PlObject -> [(String, PlObject)]
exDict (PlDict ds) = ds
exDict _ = error "exDict: not a dict"
convertCapture :: (String, PlObject) -> TMCapture
convertCapture (key, capObj) = TMCapture {
identifier = read key,
nameAttribute = exStr $ vForK capObj "name"
}
mkCaps cs = M.fromList [(identifier c, c) | c <- cs]
convertPattern :: PlObject -> TMRule
convertPattern patObj | hasKey patObj "match" =
Match {
regex = makeRegex $ exStr $ vForK patObj "match",
name = exStr $ vForK patObj "name",
captures = mkCaps $ map convertCapture $
if hasKey patObj "captures" then
exDict $ vForK patObj "captures"
else []
}
convertPattern patObj | hasKey patObj "include" =
Include {
ruleKey = exStr $ vForK patObj "include"
}
convertPattern patObj | hasKey patObj "begin" =
RangeMatch {
startRegex = makeRegex $ exStr $ vForK patObj "begin",
startCaptures = mkCaps $ map convertCapture $
if hasKey patObj "captures" then
exDict $ vForK patObj "captures"
else if hasKey patObj "startCaptures" then
exDict $ vForK patObj "startCaptures"
else [],
endRegex = makeRegex $ exStr $ vForK patObj "end",
endCaptures = mkCaps $ map convertCapture $
if hasKey patObj "captures" then
exDict $ vForK patObj "captures"
else if hasKey patObj "endCaptures" then
exDict $ vForK patObj "endCaptures"
else [],
name = exStr $ vForK patObj "name",
contentName =
if hasKey patObj "contentName" then
Just $ exStr $ vForK patObj "contentName"
else Nothing,
rmRules =
if hasKey patObj "patterns" then
map convertPattern $ exList $ vForK patObj "patterns"
else []
}
convertPattern patObj | hasKey patObj "patterns" =
MultiRule {
rmRules = map convertPattern $ exList $ vForK patObj "patterns"
}
convertPattern patObj = error $ "Unrecognised pattern: "++show patObj
syntaxFile :: TMSyntaxFile
syntaxFile = TMSyntaxFile {
fileTypes = map exStr $ exList $ vForK root "fileTypes",
fileName = exStr $ vForK root "name",
patterns = map convertPattern $ exList $ vForK root "patterns",
repository = let PlDict kvs = vForK root "repository" in
M.fromList [(k, convertPattern v) | (k, v) <- kvs],
scopeName = exStr $ vForK root "scopeName",
uniqueId = exStr $ vForK root "uuid"
}
return syntaxFile
-- | Alias for ease. The parse stack contains the list of rules that currently
-- are allowed, and possibly a rule that we matched the start of, but have yet
-- to find the end of (i.e. it is necessarily a RangeMatch).
type ParserState = ([TMRule], Maybe TMRule)
extractRegex :: TMRule -> (Regex, (TMRule, Bool))
extractRegex (rule@(Match r _ _)) = (r, (rule, False))
extractRegex (rule@(RangeMatch start _ _ _ _ _ _)) =
(start, (rule, False))
extractRegex _ = error "Unexpected regex"
selectBest :: [(MatchText String, a)] -> Maybe (MatchText String, a)
selectBest [] = Nothing
selectBest rs = Just $ head $
sortBy (\(mt1,_) (mt2,_) ->
let
(_, (offset1, _)) = mt1!0
(_, (offset2, _)) = mt2!0
in compare offset1 offset2) rs
highlightFile :: TMSyntaxFile -> String -> HLFile
highlightFile syntaxFile input =
let
reduceRules :: [TMRule] -> [TMRule]
reduceRules rss =
let
ruleError k = error ("Could not find rules for "++show k)
rulesForKey :: String -> [TMRule]
rulesForKey ('#':k) =
[M.findWithDefault (ruleError k) k (repository syntaxFile)]
rulesForKey "$self" = reduce (patterns syntaxFile)
rulesForKey k = ruleError k
reduce (Include k : rs) = reduce (rulesForKey k ++ rs)
reduce (rule@(Match _ _ _) : rs) = rule : reduce rs
reduce (rule@(RangeMatch _ _ _ _ _ _ _) : rs) =
rule : reduce rs
reduce (MultiRule rs : rs') = reduce (rs ++ rs')
reduce [] = []
in reduce rss
-- | Match the lines, starting in the given parse state. Returns when
-- either, all input has been consumed, or when the end regex of the
-- current rule on the stack has been hit. Returns the segments produced,
-- any remaining input.
matchLines :: ParserState -> [String] -> ([HLSegment], [String])
matchLines _ [] = ([], [])
matchLines state (line:remainingLines) =
let
(stateRules, currentRule) = state
mkCaptures :: MatchText String -> (TMRule, Bool) -> ([HLSegment], String)
mkCaptures matchText (rule, isRangeEnd) =
let
(fullMatch, (fullMatchOffset, fullMatchLength)) =
matchText!0
(0,captureCount) = bounds matchText
cs = if isRangeMatch rule then
if isRangeEnd then startCaptures rule
else endCaptures rule
else captures rule
tag = name rule
mkSegments :: Int -> String -> Int -> [HLSegment]
mkSegments _ rest capture | capture >= captureCount =
if rest /= [] then [HLString rest] else []
mkSegments offset rest capture =
case matchText!capture of
(_, (matchOffset, matchLength)) ->
let
(matched, rest') = splitAt (matchOffset+matchLength) rest
cap =
case M.lookup capture cs of
Just c -> HLTag (nameAttribute c) [HLString matched]
Nothing -> HLString matched
b = cap:mkSegments (offset+matchLength) rest' (capture+1)
(beforeText,_) = splitAt matchOffset rest
in
if matchOffset == offset then b
else HLString beforeText : b
(_, remainingLine) = splitAt (fullMatchOffset+fullMatchLength) line
segs' = if M.null cs then [HLTag tag [HLString fullMatch]]
else mkSegments 0 fullMatch 1
in ([HLTag tag segs'], remainingLine)
-- | Returns, the match, (the matching rule, isEndMatch)
matchRegexs :: [(Regex, a)] -> [(MatchText String, a)]
matchRegexs [] = []
matchRegexs ((regexp, label):rs) =
case matchOnceText regexp line of
Just (_, mt, _) -> (mt, label):matchRegexs rs
Nothing -> matchRegexs rs
matches :: [(MatchText String, (TMRule, Bool))]
matches = matchRegexs $
case currentRule of
Just r -> (endRegex r, (r, True)):map extractRegex stateRules
Nothing -> map extractRegex stateRules
isRangeMatch (RangeMatch _ _ _ _ _ _ _ ) = True
isRangeMatch _ = False
bestMatch :: Maybe (MatchText String, (TMRule, Bool))
bestMatch = selectBest matches
(segments, remainingInput) = case bestMatch of
Just (matchText, (r, True)) | isRangeMatch r ->
-- The best match was the end regex of a RangeMatch.
let (segs1, remainingLine) = mkCaptures matchText (r, True)
in (segs1, remainingLine:remainingLines)
Just (matchText, (r, False)) | isRangeMatch r ->
-- The best match was a start regex of a RangeMatch. Hence,
-- firstly match inside this RangeMatch, then continue
-- matching in the current state.
-- TODO: contentName
let
(segs1, remainingLine) = mkCaptures matchText (r, False)
input' = remainingLine:remainingLines
(segs2, input'') = matchLines (reduceRules $ rmRules r, Just r) input'
(segs3, input''') = matchLines state input''
in (HLTag (name r) (segs1++segs2) : segs3, input''')
Just (matchText, (r, False)) ->
-- Just a normal match. Compute the captures and then
-- continue matching
let
(segs1, remainingLine) = mkCaptures matchText (r, False)
(segs2, input') = matchLines state (remainingLine:remainingLines)
in (segs1++segs2, input')
Nothing ->
-- No match found, just output a plain string and
-- consume this line.
case matchLines state remainingLines of
(segs1, input') -> (HLString line : HLNewLine : segs1, input')
_ -> error "Invalid best match."
in case bestMatch of
Nothing -> (segments, remainingInput)
Just (mt, _) ->
let
(_, (offset, _)) = mt!0
(start, _) = splitAt offset line
in if offset == 0 then (segments, remainingInput)
else (HLString start : segments, remainingInput)
splitLines = split (keepDelimsR $ oneOf "\n") input
(segs, _) = matchLines (reduceRules $ patterns syntaxFile, Nothing) splitLines
in HLFile [HLTag (scopeName syntaxFile) $ init segs]
data HLFile = HLFile [HLSegment]
deriving Show
data HLSegment =
HLNewLine
| HLString String
| HLTag String [HLSegment]
deriving Show
| tomgr/webcspm | src/Text/SyntaxHighlight/TextMate.hs | bsd-3-clause | 13,036 | 0 | 29 | 5,467 | 3,283 | 1,757 | 1,526 | 235 | 25 |
module Execution where
import Syntax
import Evaluation
import Prelude hiding (lookup)
update :: Environment -> Store -> Identifier -> Int -> Store
update [] sto _ _ = sto
update ((x1,l):xls) sto x2 v = match x1 x2 (updateStore sto l v) (update xls sto x2 v)
updateStore :: Store -> Location -> Int -> Store
updateStore [] l v = []
updateStore ((l1,v1):lvs) l2 v2 = match l1 l2 ((l1,v2):lvs) ((l1,v1):updateStore lvs l2 v2)
-- Denotational semantics of Extended While, slides 545–554
exec :: Statement -> Environment -> PEnvironment -> (Store -> Store)
exec (Seq s1 s2) env penv = exec s2 env penv . exec s1 env penv
exec Skip _ _ = id
exec (IfThenElse b s1 s2) env penv = cond (evalb b env) (exec s1 env penv) (exec s2 env penv)
exec (While b s) env penv = fix f
where
f g = cond (evalb b env) (g . exec s env penv) id
exec (Call x) env penv = getProc penv x
exec (Assign x a) env penv = h
where
h sto = update env sto x (evala a env sto)
exec (Block dv dp s) env penv = h
where
h sto = exec s env' penv' sto'
where
(env', sto') = decVar dv (env, sto)
penv' = decProc dp env' penv
cond p g1 g2 sto | p sto = g1 sto
| otherwise = g2 sto
fix :: (t -> t) -> t
fix f = f (fix f)
-- slides 550, 551
decVar :: [VariableDeclaration] -> (Environment, Store) -> (Environment, Store)
decVar [] = id
decVar ((Var x a):dv) = h
where
h (env, sto) = decVar dv (modifyEnvironment env x l, modifyNext (modifySto sto l (evala a env sto)) l)
where
l = fst (head sto)
matchNmodify xys x y =
if null xys
then [(x,y)]
else match (fst (head xys)) x ((x,y):xys) (head xys:matchNmodify (tail xys) x y)
modifyEnvironment :: Environment -> Identifier -> Location -> Environment
modifyEnvironment [] x l = [(x,l)]
modifyEnvironment ((x1,l1):xls) x2 l2 = match x1 x2 ((x1,l2):xls) ((x1,l1):modifyEnvironment xls x2 l2)
modifySto :: Store -> Location -> Int -> Store
modifySto [] l v = [(l,v)]
modifySto ((l1,v1):lvs) l2 v2 = match l1 l2 ((l1,v2):lvs) ((l1,v1):modifySto lvs l2 v2)
modifyNext :: Store -> Location -> Store
modifyNext lvs l = (l+1,0):lvs
-- slides 552–554
decProc :: [ProcedureDeclaration] -> Environment -> PEnvironment -> PEnvironment
decProc [] env = id
decProc ((Proc p s):dp) env = h
where
h penv = decProc dp env (modifyPEnvironment penv p (fix (exec s env . modifyPEnvironment penv p)))
modifyPEnvironment :: PEnvironment -> Procedure -> (Store -> Store) -> PEnvironment
modifyPEnvironment [] p f = [(p,f)]
modifyPEnvironment ((p1,f1):pfs) p2 f2 = match p1 p2 ((p1,f2):pfs) ((p1,f1):modifyPEnvironment pfs p2 f2)
getProc :: Eq a => [(a,Store -> Store)] -> a -> (Store -> Store)
getProc [] a = id
getProc ((a1,b):abs) a2 = match a1 a2 b (getProc abs a2)
| grammarware/slps | topics/semantics/while/extended/Execution.hs | bsd-3-clause | 2,733 | 12 | 14 | 574 | 1,432 | 751 | 681 | 54 | 2 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
module Pakej.Daemon
( daemon
) where
import Control.Concurrent (forkIO, forkFinally, threadDelay)
import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar)
import Control.Exception (bracket)
import Control.Lens
import Control.Monad (forever)
import Control.Monad.Trans.State.Strict (StateT(..))
import Control.Monad.IO.Class (MonadIO(..))
import Control.Wire hiding (loop)
import Data.Conduit (($=), (=$), (=$=), ($$))
import Data.Conduit.Binary (sourceHandle, sinkHandle)
import Data.Conduit.Cereal (conduitGet, conduitPut)
import qualified Data.Conduit.List as CL
import Data.IORef
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as Map
import Data.HashMap.Strict (HashMap)
import Data.Serialize (get, put)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Version (showVersion)
import Network
import Prelude hiding ((.), id, fail)
import System.Directory (removeFile)
import System.IO (hClose)
import System.IO.Error (tryIOError)
import Text.Printf (printf)
import Pakej.Conf (PakejConf, addrs)
import Pakej.Daemon.Daemonize (daemonize)
import Pakej.Protocol
import Pakej.Widget
import Paths_pakej (version)
daemon :: PakejConf -> PakejWidget a -> IO ()
daemon conf w = do
greeting conf
daemonize conf $ do
ref <- newIORef Map.empty
forkIO (worker ref w)
locks <- mapM (listen ref) (view addrs conf)
mapM_ acquireLock locks
greeting :: PakejConf -> IO ()
greeting conf = do
printf "pakej %s, listening on:\n" (showVersion version)
mapM_ (putStrLn . pretty) (view addrs conf)
where
pretty p = " - " ++ site "localhost" p
listen :: IORef (HashMap Text (Access Text)) -> PortID -> IO Lock
listen ref p = do
lock <- newLock
forkFinally listenLoop (\_ -> releaseLock lock)
return lock
where
listenLoop = bracket (preparePort p >> listenOn p) sClose $ \s ->
forever $ do
(h, _, _) <- accept s
forkFinally
(sourceHandle h $= conduitGet get =$= CL.mapM respond $$ conduitPut put =$ sinkHandle h)
(\_ -> hClose h)
respond query = do
m <- liftIO $ readIORef ref
return (response m p query)
newtype Lock = Lock { unLock :: MVar () }
newLock :: IO Lock
newLock = Lock <$> newEmptyMVar
acquireLock :: Lock -> IO ()
acquireLock = takeMVar . unLock
releaseLock :: Lock -> IO ()
releaseLock (Lock var) = putMVar var ()
response :: HashMap Text (Access Text) -> PortID -> Request -> Response
response m p = \case
CQuery key -> case (Map.lookup key m, p) of
(Just (Private _), PortNumber _) ->
DQuery Nothing
(Just r, _) -> do
DQuery (Just (Text.replace (Text.pack "\n") (Text.pack "") (unAccess r)))
(Nothing, _) ->
DQuery Nothing
CStatus -> case p of
PortNumber _ ->
DStatus [k | (k, Public _) <- Map.toList m]
_ ->
DStatus (Map.keys m)
preparePort :: PortID -> IO (Either IOError ())
preparePort (UnixSocket s) = tryIOError (removeFile s)
preparePort _ = return (Right ())
worker
:: (Show l, Eq l, Hashable l, Integral n, Applicative m, MonadIO m)
=> IORef (HashMap l (Access v)) -> Widget m l v (WidgetConf n) a -> m b
worker ref w = step (unWidget w) Map.empty clockSession_
where
step w' m' session' = do
(dt, session'') <- stepSession session'
((_, w''), m'') <- runStateT (stepWire w' dt (Right defaultWidgetConf)) m'
liftIO $ do
atomicWriteIORef ref m''
threadDelay 200000
step w'' m'' session''
| supki/pakej | src/Pakej/Daemon.hs | bsd-3-clause | 3,782 | 0 | 20 | 982 | 1,376 | 725 | 651 | 97 | 5 |
module Reactive.Bacon.Examples where
import Reactive.Bacon
import Reactive.Bacon.PushStream
import Reactive.Bacon.Property
import Control.Applicative
import Control.Concurrent
import Control.Monad
pushCollectionExample = do
(stream, push) <- newPushStream
stream ==> print
push $ Next "lol"
mapFilterExample = do
sequentiallyE (seconds 1) [1, 2, 3, 1]
>>= filterE (<3)
>>= mapE (("x=" ++) . show)
>>=! print
mergeExample = do
(c1, push1) <- newPushStream
(c2, push2) <- newPushStream
mergeE c1 c2 >>= takeE 3 >>=! print
push1 $ Next "left"
push2 $ Next "right"
push1 $ Next "left2"
push2 $ Next "don't show me"
applicativeExample = do
(c1, push1) <- newPushProperty
(c2, push2) <- newPushProperty
let combo = (+) <$> c1 <*> c2
combo ==> print
push1 1
push2 2
push1 2
numExample = do
(xs, pushX) <- newPushProperty
(ys, pushY) <- newPushProperty
let sum = 100 + xs * 10 + ys
sum ==> print
pushX 1
pushY 5
pushX 2
scanExample = do
(numbers, push) <- newPushStream
(scanE append [] numbers) >>= prefix "numbers=" >>=! print
(scanE (+) 0 numbers) >>= prefix "sum=" >>=! print
(scanE (*) 1 numbers) >>= prefix "product=" >>=! print
push $ Next 1
push $ Next 2
push $ Next 3
monadExample = do
(search, push) <- newPushStream
flatMapE httpCall search
>>= mapE ("http://lol.com/lolServlet?search=" ++)
>>=! print
push $ Next "pron"
httpCall :: String -> IO (EventStream String)
httpCall request = return $ EventStream $ \sink ->
do forkIO $ do
putStrLn $ "Sending request " ++ request
threadDelay 1000000
sink $ Next $ "404 - NOT FOUND returned for " ++ request
void $ sink $ End
return (return ())
prefix p e = mapE((p ++) .show) e
append :: [a] -> a -> [a]
append xs x = xs ++ [x]
| raimohanska/reactive-bacon | src/Reactive/Bacon/Examples.hs | bsd-3-clause | 1,986 | 1 | 14 | 586 | 723 | 357 | 366 | 65 | 1 |
module Permutation where
import Data.Monoid
data PermIndex = One | Two | Three | Four | Five
deriving Show
data Perm = Perm PermIndex PermIndex PermIndex PermIndex PermIndex
deriving Show
instance Monoid Perm where
mempty = Perm One Two Three Four Five
mappend p (Perm a b c d e) =
Perm (f a) (f b) (f c) (f d) (f e)
where f = g p
g (Perm a _ _ _ _) One = a
g (Perm _ b _ _ _) Two = b
g (Perm _ _ c _ _) Three = c
g (Perm _ _ _ d _) Four = d
g (Perm _ _ _ _ e) Five = e
vertex = Perm Five One Two Three Four
edge = Perm One Three Two Five Four
--face = vertex times edge
| cullina/Hex | src/Permutation.hs | bsd-3-clause | 742 | 0 | 10 | 309 | 303 | 157 | 146 | 18 | 1 |
module Main where
import Lib
main :: IO ()
main = someFunc
{-99 Haskell Problems-}
{-| Get the last element of a list-}
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
{-| Get the second to last element of a list-}
myButtLast :: [a] -> a
myButtLast [x, _] = x
myButtLast (_:xs) = myButtLast xs
{-| Get the kth element of a list-}
elementAt :: [a] -> Int -> a
elementAt (x:_) 0 = x
elementAt (_:xs) k = elementAt xs (k - 1)
{-| Get the length of a list-}
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + (myLength xs)
{-| Reverse a list-}
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
{-| Checks if list is a palindrome.-}
myPalindrome :: (Eq a) => [a] -> Bool
myPalindrome x
| x == (reverse x) = True
| otherwise = False
{-| Remove dupes in list-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress (x:xs) = [x] ++ compress (clean x xs)
where clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Put duplicates in sublists-}
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack [x] = [[x]]
pack (x:xs) = combine x xs ++ pack (clean x xs)
where
combine _ [] = []
combine x s = [[z | z <- x:s, z == x]]
clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Does stuff-}
encode :: (Eq a) => [a] -> [(Int, a)]
encode [] = []
encode s = map (\(x:xs) -> (length (x:xs), x)) (pack s)
data List a = Single a | Multiple Int a
deriving Show
{-| Similar to before-}
encodeModified :: (Eq a) => [a] -> [List a]
encodeModified s = map f (encode s)
where f (1, x) = Single x
f (n, x) = Multiple n x
decode :: [List a] -> [a]
decode s = foldr (++) [] (map f s)
where f (Single x) = [x]
f (Multiple n x) = replicate n x
encodeDirect :: (Eq a) => [a] -> [List a]
encodeDirect [] = []
encodeDirect (x:xs) = [toList (count x (x:xs)) x] ++
encodeDirect (filter (x /=) xs)
where count x s = length (filter (x==) s)
toList 1 x = Single x
toList n x = Multiple n x
dupl :: [a] -> [a]
dupl [] = []
dupl (x:xs) = [x,x] ++ dupl xs
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = replicate n x ++ repli xs n
dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery s n = foldr (++) [] (map (f n) (zip [1..] s))
where f n (m, x)
| m `mod` n == 0 = []
| otherwise = [x]
spliter :: [a] -> Int -> [[a]]
spliter [] _ = []
spliter s n = [reverse (drop ((length s) - n) (reverse s))] ++ [drop n s]
slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = []
slice s start stop = reverse (drop (((length s)) - stop) (reverse (drop (start - 1) s)))
rotate :: [a] -> Int -> [a]
rotate [] _ = []
rotate s n = slice s ((f n (length s)) + 1) (length s) ++ slice s 1 (f n (length s))
where f n m
| n > m = f (n - m) m
| n < 0 = f (m + n) m
| otherwise = n
removeAt :: [a] -> Int -> (a, [a])
removeAt s n = (elementAt (slice s (n + 1) (n + 2)) 0,
slice s 1 n ++ slice s (n+2) (length s))
insertAt :: [a] -> a -> Int -> [a]
insertAt xs x n = slice xs 1 (n-1) ++ [x] ++ slice xs n (length xs)
range :: Int -> Int -> [Int]
range n1 n2 = [n1..n2]
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations = a
| MauriceIsAG/HaskellScratch | app/.stack-work/intero/intero116761NK.hs | bsd-3-clause | 3,349 | 0 | 13 | 953 | 1,969 | 1,039 | 930 | 95 | 3 |
-- | This mdoule provides efficient functions to render lists of queries.
module Database.Algebra.SQL.Render
( debugTransformResult
, renderCompact
, renderPretty
, renderPlain
) where
import qualified Text.PrettyPrint.ANSI.Leijen as L (Doc, SimpleDoc,
displayS, plain,
renderCompact,
renderPretty)
import Database.Algebra.SQL.Dialect
import Database.Algebra.SQL.Query (Query)
import Database.Algebra.SQL.Render.Query (renderQuery)
import Database.Algebra.SQL.Render.Tile (renderTransformResult)
import Database.Algebra.SQL.Tile (TileDep, TileTree)
renderPrettySimpleDoc :: L.Doc -> L.SimpleDoc
renderPrettySimpleDoc =
L.renderPretty 0.8 80
renderWith :: (L.Doc -> L.SimpleDoc) -> Dialect -> Query -> ShowS
renderWith f c = L.displayS . f . renderQuery c
-- | Returns a 'ShowS' containing debug information for a transform result.
debugTransformResult :: Dialect -> ([TileTree], [TileDep]) -> ShowS
debugTransformResult compat =
L.displayS . renderPrettySimpleDoc . (renderTransformResult compat)
-- | Renders a list of queries in an ugly but fast way, feasible as direct SQL
-- input.
renderCompact :: Dialect -> [Query] -> [ShowS]
renderCompact c = map $ renderWith L.renderCompact c
-- | Renders a list of queries in a beautiful way.
renderPretty :: Dialect -> [Query] -> [ShowS]
renderPretty c = map $ renderWith renderPrettySimpleDoc c
-- | Renders a list of queries without colors but formatted.
renderPlain :: Dialect -> [Query] -> [ShowS]
renderPlain c = map $ renderWith (renderPrettySimpleDoc . L.plain) c
| ulricha/algebra-sql | src/Database/Algebra/SQL/Render.hs | bsd-3-clause | 1,796 | 0 | 9 | 478 | 362 | 212 | 150 | 28 | 1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[SimplMonad]{The simplifier Monad}
-}
{-# LANGUAGE CPP #-}
module SimplEnv (
InId, InBind, InExpr, InAlt, InArg, InType, InBndr, InVar,
OutId, OutTyVar, OutBind, OutExpr, OutAlt, OutArg, OutType, OutBndr, OutVar,
InCoercion, OutCoercion,
-- The simplifier mode
setMode, getMode, updMode,
-- Environments
SimplEnv(..), StaticEnv, pprSimplEnv, -- Temp not abstract
mkSimplEnv, extendIdSubst, SimplEnv.extendTCvSubst,
zapSubstEnv, setSubstEnv,
getInScope, setInScope, setInScopeSet, modifyInScope, addNewInScopeIds,
getSimplRules,
SimplSR(..), mkContEx, substId, lookupRecBndr, refineFromInScope,
simplNonRecBndr, simplRecBndrs,
simplBinder, simplBinders,
substTy, substTyVar, getTCvSubst,
substCo, substCoVar,
-- Floats
Floats, emptyFloats, isEmptyFloats, addNonRec, addFloats, extendFloats,
wrapFloats, setFloats, zapFloats, addRecFloats, mapFloats,
doFloatFromRhs, getFloatBinds
) where
#include "HsVersions.h"
import SimplMonad
import CoreMonad ( SimplifierMode(..) )
import CoreSyn
import CoreUtils
import Var
import VarEnv
import VarSet
import OrdList
import Id
import MkCore ( mkWildValBinder )
import TysWiredIn
import qualified Type
import Type hiding ( substTy, substTyVar, substTyVarBndr )
import qualified Coercion
import Coercion hiding ( substCo, substCoVar, substCoVarBndr )
import BasicTypes
import MonadUtils
import Outputable
import Util
import Data.List
{-
************************************************************************
* *
\subsection[Simplify-types]{Type declarations}
* *
************************************************************************
-}
type InBndr = CoreBndr
type InVar = Var -- Not yet cloned
type InId = Id -- Not yet cloned
type InType = Type -- Ditto
type InBind = CoreBind
type InExpr = CoreExpr
type InAlt = CoreAlt
type InArg = CoreArg
type InCoercion = Coercion
type OutBndr = CoreBndr
type OutVar = Var -- Cloned
type OutId = Id -- Cloned
type OutTyVar = TyVar -- Cloned
type OutType = Type -- Cloned
type OutCoercion = Coercion
type OutBind = CoreBind
type OutExpr = CoreExpr
type OutAlt = CoreAlt
type OutArg = CoreArg
{-
************************************************************************
* *
\subsubsection{The @SimplEnv@ type}
* *
************************************************************************
-}
data SimplEnv
= SimplEnv {
----------- Static part of the environment -----------
-- Static in the sense of lexically scoped,
-- wrt the original expression
seMode :: SimplifierMode,
-- The current substitution
seTvSubst :: TvSubstEnv, -- InTyVar |--> OutType
seCvSubst :: CvSubstEnv, -- InCoVar |--> OutCoercion
seIdSubst :: SimplIdSubst, -- InId |--> OutExpr
----------- Dynamic part of the environment -----------
-- Dynamic in the sense of describing the setup where
-- the expression finally ends up
-- The current set of in-scope variables
-- They are all OutVars, and all bound in this module
seInScope :: InScopeSet, -- OutVars only
-- Includes all variables bound by seFloats
seFloats :: Floats
-- See Note [Simplifier floats]
}
type StaticEnv = SimplEnv -- Just the static part is relevant
pprSimplEnv :: SimplEnv -> SDoc
-- Used for debugging; selective
pprSimplEnv env
= vcat [text "TvSubst:" <+> ppr (seTvSubst env),
text "CvSubst:" <+> ppr (seCvSubst env),
text "IdSubst:" <+> ppr (seIdSubst env),
text "InScope:" <+> vcat (map ppr_one in_scope_vars)
]
where
in_scope_vars = varEnvElts (getInScopeVars (seInScope env))
ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
| otherwise = ppr v
type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
-- See Note [Extending the Subst] in CoreSubst
data SimplSR
= DoneEx OutExpr -- Completed term
| DoneId OutId -- Completed term variable
| ContEx TvSubstEnv -- A suspended substitution
CvSubstEnv
SimplIdSubst
InExpr
instance Outputable SimplSR where
ppr (DoneEx e) = text "DoneEx" <+> ppr e
ppr (DoneId v) = text "DoneId" <+> ppr v
ppr (ContEx _tv _cv _id e) = vcat [text "ContEx" <+> ppr e {-,
ppr (filter_env tv), ppr (filter_env id) -}]
-- where
-- fvs = exprFreeVars e
-- filter_env env = filterVarEnv_Directly keep env
-- keep uniq _ = uniq `elemUFM_Directly` fvs
{-
Note [SimplEnv invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~
seInScope:
The in-scope part of Subst includes *all* in-scope TyVars and Ids
The elements of the set may have better IdInfo than the
occurrences of in-scope Ids, and (more important) they will
have a correctly-substituted type. So we use a lookup in this
set to replace occurrences
The Ids in the InScopeSet are replete with their Rules,
and as we gather info about the unfolding of an Id, we replace
it in the in-scope set.
The in-scope set is actually a mapping OutVar -> OutVar, and
in case expressions we sometimes bind
seIdSubst:
The substitution is *apply-once* only, because InIds and OutIds
can overlap.
For example, we generally omit mappings
a77 -> a77
from the substitution, when we decide not to clone a77, but it's quite
legitimate to put the mapping in the substitution anyway.
Furthermore, consider
let x = case k of I# x77 -> ... in
let y = case k of I# x77 -> ... in ...
and suppose the body is strict in both x and y. Then the simplifier
will pull the first (case k) to the top; so the second (case k) will
cancel out, mapping x77 to, well, x77! But one is an in-Id and the
other is an out-Id.
Of course, the substitution *must* applied! Things in its domain
simply aren't necessarily bound in the result.
* substId adds a binding (DoneId new_id) to the substitution if
the Id's unique has changed
Note, though that the substitution isn't necessarily extended
if the type of the Id changes. Why not? Because of the next point:
* We *always, always* finish by looking up in the in-scope set
any variable that doesn't get a DoneEx or DoneVar hit in the substitution.
Reason: so that we never finish up with a "old" Id in the result.
An old Id might point to an old unfolding and so on... which gives a space
leak.
[The DoneEx and DoneVar hits map to "new" stuff.]
* It follows that substExpr must not do a no-op if the substitution is empty.
substType is free to do so, however.
* When we come to a let-binding (say) we generate new IdInfo, including an
unfolding, attach it to the binder, and add this newly adorned binder to
the in-scope set. So all subsequent occurrences of the binder will get
mapped to the full-adorned binder, which is also the one put in the
binding site.
* The in-scope "set" usually maps x->x; we use it simply for its domain.
But sometimes we have two in-scope Ids that are synomyms, and should
map to the same target: x->x, y->x. Notably:
case y of x { ... }
That's why the "set" is actually a VarEnv Var
-}
mkSimplEnv :: SimplifierMode -> SimplEnv
mkSimplEnv mode
= SimplEnv { seMode = mode
, seInScope = init_in_scope
, seFloats = emptyFloats
, seTvSubst = emptyVarEnv
, seCvSubst = emptyVarEnv
, seIdSubst = emptyVarEnv }
-- The top level "enclosing CC" is "SUBSUMED".
init_in_scope :: InScopeSet
init_in_scope = mkInScopeSet (unitVarSet (mkWildValBinder unitTy))
-- See Note [WildCard binders]
{-
Note [WildCard binders]
~~~~~~~~~~~~~~~~~~~~~~~
The program to be simplified may have wild binders
case e of wild { p -> ... }
We want to *rename* them away, so that there are no
occurrences of 'wild-id' (with wildCardKey). The easy
way to do that is to start of with a representative
Id in the in-scope set
There can be be *occurrences* of wild-id. For example,
MkCore.mkCoreApp transforms
e (a /# b) --> case (a /# b) of wild { DEFAULT -> e wild }
This is ok provided 'wild' isn't free in 'e', and that's the delicate
thing. Generally, you want to run the simplifier to get rid of the
wild-ids before doing much else.
It's a very dark corner of GHC. Maybe it should be cleaned up.
-}
getMode :: SimplEnv -> SimplifierMode
getMode env = seMode env
setMode :: SimplifierMode -> SimplEnv -> SimplEnv
setMode mode env = env { seMode = mode }
updMode :: (SimplifierMode -> SimplifierMode) -> SimplEnv -> SimplEnv
updMode upd env = env { seMode = upd (seMode env) }
---------------------
extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
= ASSERT2( isId var && not (isCoVar var), ppr var )
env {seIdSubst = extendVarEnv subst var res}
extendTCvSubst :: SimplEnv -> TyVar -> Type -> SimplEnv
extendTCvSubst env@(SimplEnv {seTvSubst = tsubst, seCvSubst = csubst}) var res
| isTyVar var
= env {seTvSubst = extendVarEnv tsubst var res}
| Just co <- isCoercionTy_maybe res
= env {seCvSubst = extendVarEnv csubst var co}
| otherwise
= pprPanic "SimplEnv.extendTCvSubst" (ppr res)
---------------------
getInScope :: SimplEnv -> InScopeSet
getInScope env = seInScope env
setInScopeSet :: SimplEnv -> InScopeSet -> SimplEnv
setInScopeSet env in_scope = env {seInScope = in_scope}
setInScope :: SimplEnv -> SimplEnv -> SimplEnv
-- Set the in-scope set, and *zap* the floats
setInScope env env_with_scope
= env { seInScope = seInScope env_with_scope,
seFloats = emptyFloats }
setFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Set the in-scope set *and* the floats
setFloats env env_with_floats
= env { seInScope = seInScope env_with_floats,
seFloats = seFloats env_with_floats }
addNewInScopeIds :: SimplEnv -> [CoreBndr] -> SimplEnv
-- The new Ids are guaranteed to be freshly allocated
addNewInScopeIds env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) vs
= env { seInScope = in_scope `extendInScopeSetList` vs,
seIdSubst = id_subst `delVarEnvList` vs }
-- Why delete? Consider
-- let x = a*b in (x, \x -> x+3)
-- We add [x |-> a*b] to the substitution, but we must
-- _delete_ it from the substitution when going inside
-- the (\x -> ...)!
modifyInScope :: SimplEnv -> CoreBndr -> SimplEnv
-- The variable should already be in scope, but
-- replace the existing version with this new one
-- which has more information
modifyInScope env@(SimplEnv {seInScope = in_scope}) v
= env {seInScope = extendInScopeSet in_scope v}
---------------------
zapSubstEnv :: SimplEnv -> SimplEnv
zapSubstEnv env = env {seTvSubst = emptyVarEnv, seCvSubst = emptyVarEnv, seIdSubst = emptyVarEnv}
setSubstEnv :: SimplEnv -> TvSubstEnv -> CvSubstEnv -> SimplIdSubst -> SimplEnv
setSubstEnv env tvs cvs ids = env { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }
mkContEx :: SimplEnv -> InExpr -> SimplSR
mkContEx (SimplEnv { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }) e = ContEx tvs cvs ids e
{-
************************************************************************
* *
\subsection{Floats}
* *
************************************************************************
Note [Simplifier floats]
~~~~~~~~~~~~~~~~~~~~~~~~~
The Floats is a bunch of bindings, classified by a FloatFlag.
* All of them satisfy the let/app invariant
Examples
NonRec x (y:ys) FltLifted
Rec [(x,rhs)] FltLifted
NonRec x* (p:q) FltOKSpec -- RHS is WHNF. Question: why not FltLifted?
NonRec x# (y +# 3) FltOkSpec -- Unboxed, but ok-for-spec'n
NonRec x* (f y) FltCareful -- Strict binding; might fail or diverge
Can't happen:
NonRec x# (a /# b) -- Might fail; does not satisfy let/app
NonRec x# (f y) -- Might diverge; does not satisfy let/app
-}
data Floats = Floats (OrdList OutBind) FloatFlag
-- See Note [Simplifier floats]
data FloatFlag
= FltLifted -- All bindings are lifted and lazy
-- Hence ok to float to top level, or recursive
| FltOkSpec -- All bindings are FltLifted *or*
-- strict (perhaps because unlifted,
-- perhaps because of a strict binder),
-- *and* ok-for-speculation
-- Hence ok to float out of the RHS
-- of a lazy non-recursive let binding
-- (but not to top level, or into a rec group)
| FltCareful -- At least one binding is strict (or unlifted)
-- and not guaranteed cheap
-- Do not float these bindings out of a lazy let
instance Outputable Floats where
ppr (Floats binds ff) = ppr ff $$ ppr (fromOL binds)
instance Outputable FloatFlag where
ppr FltLifted = text "FltLifted"
ppr FltOkSpec = text "FltOkSpec"
ppr FltCareful = text "FltCareful"
andFF :: FloatFlag -> FloatFlag -> FloatFlag
andFF FltCareful _ = FltCareful
andFF FltOkSpec FltCareful = FltCareful
andFF FltOkSpec _ = FltOkSpec
andFF FltLifted flt = flt
doFloatFromRhs :: TopLevelFlag -> RecFlag -> Bool -> OutExpr -> SimplEnv -> Bool
-- If you change this function look also at FloatIn.noFloatFromRhs
doFloatFromRhs lvl rec str rhs (SimplEnv {seFloats = Floats fs ff})
= not (isNilOL fs) && want_to_float && can_float
where
want_to_float = isTopLevel lvl || exprIsCheap rhs || exprIsExpandable rhs
-- See Note [Float when cheap or expandable]
can_float = case ff of
FltLifted -> True
FltOkSpec -> isNotTopLevel lvl && isNonRec rec
FltCareful -> isNotTopLevel lvl && isNonRec rec && str
{-
Note [Float when cheap or expandable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to float a let from a let if the residual RHS is
a) cheap, such as (\x. blah)
b) expandable, such as (f b) if f is CONLIKE
But there are
- cheap things that are not expandable (eg \x. expensive)
- expandable things that are not cheap (eg (f b) where b is CONLIKE)
so we must take the 'or' of the two.
-}
emptyFloats :: Floats
emptyFloats = Floats nilOL FltLifted
unitFloat :: OutBind -> Floats
-- This key function constructs a singleton float with the right form
unitFloat bind = Floats (unitOL bind) (flag bind)
where
flag (Rec {}) = FltLifted
flag (NonRec bndr rhs)
| not (isStrictId bndr) = FltLifted
| exprOkForSpeculation rhs = FltOkSpec -- Unlifted, and lifted but ok-for-spec (eg HNF)
| otherwise = ASSERT2( not (isUnLiftedType (idType bndr)), ppr bndr )
FltCareful
-- Unlifted binders can only be let-bound if exprOkForSpeculation holds
addNonRec :: SimplEnv -> OutId -> OutExpr -> SimplEnv
-- Add a non-recursive binding and extend the in-scope set
-- The latter is important; the binder may already be in the
-- in-scope set (although it might also have been created with newId)
-- but it may now have more IdInfo
addNonRec env id rhs
= id `seq` -- This seq forces the Id, and hence its IdInfo,
-- and hence any inner substitutions
env { seFloats = seFloats env `addFlts` unitFloat (NonRec id rhs),
seInScope = extendInScopeSet (seInScope env) id }
extendFloats :: SimplEnv -> OutBind -> SimplEnv
-- Add these bindings to the floats, and extend the in-scope env too
extendFloats env bind
= env { seFloats = seFloats env `addFlts` unitFloat bind,
seInScope = extendInScopeSetList (seInScope env) bndrs }
where
bndrs = bindersOf bind
addFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Add the floats for env2 to env1;
-- *plus* the in-scope set for env2, which is bigger
-- than that for env1
addFloats env1 env2
= env1 {seFloats = seFloats env1 `addFlts` seFloats env2,
seInScope = seInScope env2 }
addFlts :: Floats -> Floats -> Floats
addFlts (Floats bs1 l1) (Floats bs2 l2)
= Floats (bs1 `appOL` bs2) (l1 `andFF` l2)
zapFloats :: SimplEnv -> SimplEnv
zapFloats env = env { seFloats = emptyFloats }
addRecFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Flattens the floats from env2 into a single Rec group,
-- prepends the floats from env1, and puts the result back in env2
-- This is all very specific to the way recursive bindings are
-- handled; see Simplify.simplRecBind
addRecFloats env1 env2@(SimplEnv {seFloats = Floats bs ff})
= ASSERT2( case ff of { FltLifted -> True; _ -> False }, ppr (fromOL bs) )
env2 {seFloats = seFloats env1 `addFlts` unitFloat (Rec (flattenBinds (fromOL bs)))}
wrapFloats :: SimplEnv -> OutExpr -> OutExpr
-- Wrap the floats around the expression; they should all
-- satisfy the let/app invariant, so mkLets should do the job just fine
wrapFloats (SimplEnv {seFloats = Floats bs _}) body
= foldrOL Let body bs
getFloatBinds :: SimplEnv -> [CoreBind]
getFloatBinds (SimplEnv {seFloats = Floats bs _})
= fromOL bs
isEmptyFloats :: SimplEnv -> Bool
isEmptyFloats (SimplEnv {seFloats = Floats bs _})
= isNilOL bs
mapFloats :: SimplEnv -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> SimplEnv
mapFloats env@SimplEnv { seFloats = Floats fs ff } fun
= env { seFloats = Floats (mapOL app fs) ff }
where
app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'
app (Rec bs) = Rec (map fun bs)
{-
************************************************************************
* *
Substitution of Vars
* *
************************************************************************
Note [Global Ids in the substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We look up even a global (eg imported) Id in the substitution. Consider
case X.g_34 of b { (a,b) -> ... case X.g_34 of { (p,q) -> ...} ... }
The binder-swap in the occurrence analyser will add a binding
for a LocalId version of g (with the same unique though):
case X.g_34 of b { (a,b) -> let g_34 = b in
... case X.g_34 of { (p,q) -> ...} ... }
So we want to look up the inner X.g_34 in the substitution, where we'll
find that it has been substituted by b. (Or conceivably cloned.)
-}
substId :: SimplEnv -> InId -> SimplSR
-- Returns DoneEx only on a non-Var expression
substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
= case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
Nothing -> DoneId (refineFromInScope in_scope v)
Just (DoneId v) -> DoneId (refineFromInScope in_scope v)
Just (DoneEx (Var v)) -> DoneId (refineFromInScope in_scope v)
Just res -> res -- DoneEx non-var, or ContEx
-- Get the most up-to-date thing from the in-scope set
-- Even though it isn't in the substitution, it may be in
-- the in-scope set with better IdInfo
refineFromInScope :: InScopeSet -> Var -> Var
refineFromInScope in_scope v
| isLocalId v = case lookupInScope in_scope v of
Just v' -> v'
Nothing -> WARN( True, ppr v ) v -- This is an error!
| otherwise = v
lookupRecBndr :: SimplEnv -> InId -> OutId
-- Look up an Id which has been put into the envt by simplRecBndrs,
-- but where we have not yet done its RHS
lookupRecBndr (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
= case lookupVarEnv ids v of
Just (DoneId v) -> v
Just _ -> pprPanic "lookupRecBndr" (ppr v)
Nothing -> refineFromInScope in_scope v
{-
************************************************************************
* *
\section{Substituting an Id binder}
* *
************************************************************************
These functions are in the monad only so that they can be made strict via seq.
-}
simplBinders :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
simplBinders env bndrs = mapAccumLM simplBinder env bndrs
-------------
simplBinder :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- Used for lambda and case-bound variables
-- Clone Id if necessary, substitute type
-- Return with IdInfo already substituted, but (fragile) occurrence info zapped
-- The substitution is extended only if the variable is cloned, because
-- we *don't* need to use it to track occurrence info.
simplBinder env bndr
| isTyVar bndr = do { let (env', tv) = substTyVarBndr env bndr
; seqTyVar tv `seq` return (env', tv) }
| otherwise = do { let (env', id) = substIdBndr env bndr
; seqId id `seq` return (env', id) }
---------------
simplNonRecBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- A non-recursive let binder
simplNonRecBndr env id
= do { let (env1, id1) = substIdBndr env id
; seqId id1 `seq` return (env1, id1) }
---------------
simplRecBndrs :: SimplEnv -> [InBndr] -> SimplM SimplEnv
-- Recursive let binders
simplRecBndrs env@(SimplEnv {}) ids
= do { let (env1, ids1) = mapAccumL substIdBndr env ids
; seqIds ids1 `seq` return env1 }
---------------
substIdBndr :: SimplEnv -> InBndr -> (SimplEnv, OutBndr)
-- Might be a coercion variable
substIdBndr env bndr
| isCoVar bndr = substCoVarBndr env bndr
| otherwise = substNonCoVarIdBndr env bndr
---------------
substNonCoVarIdBndr
:: SimplEnv
-> InBndr -- Env and binder to transform
-> (SimplEnv, OutBndr)
-- Clone Id if necessary, substitute its type
-- Return an Id with its
-- * Type substituted
-- * UnfoldingInfo, Rules, WorkerInfo zapped
-- * Fragile OccInfo (only) zapped: Note [Robust OccInfo]
-- * Robust info, retained especially arity and demand info,
-- so that they are available to occurrences that occur in an
-- earlier binding of a letrec
--
-- For the robust info, see Note [Arity robustness]
--
-- Augment the substitution if the unique changed
-- Extend the in-scope set with the new Id
--
-- Similar to CoreSubst.substIdBndr, except that
-- the type of id_subst differs
-- all fragile info is zapped
substNonCoVarIdBndr env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst })
old_id
= ASSERT2( not (isCoVar old_id), ppr old_id )
(env { seInScope = in_scope `extendInScopeSet` new_id,
seIdSubst = new_subst }, new_id)
where
id1 = uniqAway in_scope old_id
id2 = substIdType env id1
new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding
-- and fragile OccInfo
-- Extend the substitution if the unique has changed,
-- or there's some useful occurrence information
-- See the notes with substTyVarBndr for the delSubstEnv
new_subst | new_id /= old_id
= extendVarEnv id_subst old_id (DoneId new_id)
| otherwise
= delVarEnv id_subst old_id
------------------------------------
seqTyVar :: TyVar -> ()
seqTyVar b = b `seq` ()
seqId :: Id -> ()
seqId id = seqType (idType id) `seq`
idInfo id `seq`
()
seqIds :: [Id] -> ()
seqIds [] = ()
seqIds (id:ids) = seqId id `seq` seqIds ids
{-
Note [Arity robustness]
~~~~~~~~~~~~~~~~~~~~~~~
We *do* transfer the arity from from the in_id of a let binding to the
out_id. This is important, so that the arity of an Id is visible in
its own RHS. For example:
f = \x. ....g (\y. f y)....
We can eta-reduce the arg to g, because f is a value. But that
needs to be visible.
This interacts with the 'state hack' too:
f :: Bool -> IO Int
f = \x. case x of
True -> f y
False -> \s -> ...
Can we eta-expand f? Only if we see that f has arity 1, and then we
take advantage of the 'state hack' on the result of
(f y) :: State# -> (State#, Int) to expand the arity one more.
There is a disadvantage though. Making the arity visible in the RHS
allows us to eta-reduce
f = \x -> f x
to
f = f
which technically is not sound. This is very much a corner case, so
I'm not worried about it. Another idea is to ensure that f's arity
never decreases; its arity started as 1, and we should never eta-reduce
below that.
Note [Robust OccInfo]
~~~~~~~~~~~~~~~~~~~~~
It's important that we *do* retain the loop-breaker OccInfo, because
that's what stops the Id getting inlined infinitely, in the body of
the letrec.
-}
{-
************************************************************************
* *
Impedence matching to type substitution
* *
************************************************************************
-}
getTCvSubst :: SimplEnv -> TCvSubst
getTCvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv_env })
= mkTCvSubst in_scope (tv_env, cv_env)
substTy :: SimplEnv -> Type -> Type
substTy env ty = Type.substTy (getTCvSubst env) ty
substTyVar :: SimplEnv -> TyVar -> Type
substTyVar env tv = Type.substTyVar (getTCvSubst env) tv
substTyVarBndr :: SimplEnv -> TyVar -> (SimplEnv, TyVar)
substTyVarBndr env tv
= case Type.substTyVarBndr (getTCvSubst env) tv of
(TCvSubst in_scope' tv_env' cv_env', tv')
-> (env { seInScope = in_scope', seTvSubst = tv_env', seCvSubst = cv_env' }, tv')
substCoVar :: SimplEnv -> CoVar -> Coercion
substCoVar env tv = Coercion.substCoVar (getTCvSubst env) tv
substCoVarBndr :: SimplEnv -> CoVar -> (SimplEnv, CoVar)
substCoVarBndr env cv
= case Coercion.substCoVarBndr (getTCvSubst env) cv of
(TCvSubst in_scope' tv_env' cv_env', cv')
-> (env { seInScope = in_scope', seTvSubst = tv_env', seCvSubst = cv_env' }, cv')
substCo :: SimplEnv -> Coercion -> Coercion
substCo env co = Coercion.substCo (getTCvSubst env) co
------------------
substIdType :: SimplEnv -> Id -> Id
substIdType (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv_env }) id
| (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env)
|| isEmptyVarSet (tyCoVarsOfType old_ty)
= id
| otherwise = Id.setIdType id (Type.substTy (TCvSubst in_scope tv_env cv_env) old_ty)
-- The tyCoVarsOfType is cheaper than it looks
-- because we cache the free tyvars of the type
-- in a Note in the id's type itself
where
old_ty = idType id
| gridaphobe/ghc | compiler/simplCore/SimplEnv.hs | bsd-3-clause | 27,760 | 0 | 15 | 7,521 | 4,369 | 2,414 | 1,955 | 304 | 4 |
------------------------------------------------------------------------------
-- | This module does data-type conversions and general data manipulations.
-- See LICENSE file for copyright and license info.
------------------------------------------------------------------------------
module DataConversion where
-----------------------------------------------------------------------------
-- ||| Imports
-----------------------------------------------------------------------------
import Data.Default.Class
import Control.Lens hiding (argument)
import Data.List.Split
import Data.List
import Control.Monad (when)
import System.Exit (exitSuccess)
-----------------------------------------------------------------------------
-- ||| Data conversion methods
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- | Parses a list of <delimiter>-separated string to a list of
-- | lists, containing the separated strings.
--
-- Example: ["12;10", "15;5"]
-- gives [ ["12", "10"], ["15", "5"] ]
-----------------------------------------------------------------------------
splitLinesToListOfStrings :: String -> [String] -> [[String]]
splitLinesToListOfStrings delim [] = []
splitLinesToListOfStrings delim [x] = [splitString delim x]
splitLinesToListOfStrings delim (x:xs) = [splitString delim x] ++ splitLinesToListOfStrings delim xs
-----------------------------------------------------------------------------
-- | Splits a ;-separated string into a list
--
-- Example: "12;10"
-- gives ["12", "10"]
-----------------------------------------------------------------------------
splitString :: String -> String -> [String]
splitString delim c = splitOn delim $ filter (/=' ') c
-----------------------------------------------------------------------------
-- | Convert String to Double datatype
-----------------------------------------------------------------------------
-- TODO: use reads?
convertToDouble :: String -> Double
convertToDouble aString = read aString :: Double
-----------------------------------------------------------------------------
-- ||| List conversions
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- | Converst list of strings to list of double values
-----------------------------------------------------------------------------
convertListStringToDouble :: [String] -> [Double]
convertListStringToDouble = map convertToDouble
-----------------------------------------------------------------------------
-- ||| List manipulations
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- | Drop the last n elements from a list
-----------------------------------------------------------------------------
dropLastN :: Int -> [a] -> [a]
dropLastN n xs = reverse $ drop n (reverse xs)
-----------------------------------------------------------------------------
-- | Get the last n elements from a list
-----------------------------------------------------------------------------
getLastN :: Int -> [a] -> [a]
getLastN n xs = foldl' (const . drop 1) xs (drop n xs)
| rockwolf/haskell_generic | DataConversion.hs | bsd-3-clause | 3,322 | 0 | 8 | 284 | 371 | 221 | 150 | 21 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
module Lib
( startApp
) where
import Control.Monad.Trans.Either
import Data.Aeson.TH
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
data User = User
{ userId :: Int
, userFirstName :: String
, userLastName :: String
} deriving (Eq, Show)
type Handler = EitherT ServantErr IO
type API
= "users" :> Get '[JSON] [User]
:<|> "firstUser" :> Get '[JSON] User
users :: Handler [User]
users =
return
[ User 1 "Isaac" "Newton"
, User 2 "Albert" "Einstein"
]
firstUser :: Handler User
firstUser = head <$> users
$(deriveJSON defaultOptions ''User)
startApp :: IO ()
startApp = run 8080 app
app :: Application
app = serve api server
api :: Proxy API
api = Proxy
server :: Server API
server
= users
:<|> firstUser
| frontrowed/blog-servant | src/Lib.hs | bsd-3-clause | 884 | 0 | 10 | 203 | 265 | 148 | 117 | 37 | 1 |
{-# LANGUAGE CPP #-}
#ifdef ghcjs_HOST_OS
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
#endif
{-# LANGUAGE LambdaCase #-}
module Reflex.Dom.WebSocket.Foreign
( module Reflex.Dom.WebSocket.Foreign
, JSVal
) where
import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
import Data.Bifoldable
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Text (Text)
import Data.Text.Encoding
import Foreign.JavaScript.Utils (bsFromMutableArrayBuffer, bsToArrayBuffer)
import GHCJS.DOM.CloseEvent
import GHCJS.DOM.MessageEvent
import GHCJS.DOM.Types (JSM, JSVal, liftJSM, fromJSValUnchecked, WebSocket(..))
import qualified GHCJS.DOM.WebSocket as DOM
import GHCJS.Foreign (JSType(..), jsTypeOf)
import Language.Javascript.JSaddle (fun, eval, toJSVal, call)
import Language.Javascript.JSaddle.Helper (mutableArrayBufferFromJSVal)
import Language.Javascript.JSaddle.Types (ghcjsPure)
newtype JSWebSocket = JSWebSocket { unWebSocket :: WebSocket }
class IsWebSocketMessage a where
webSocketSend :: JSWebSocket -> a -> JSM ()
instance (IsWebSocketMessage a, IsWebSocketMessage b) => IsWebSocketMessage (Either a b) where
webSocketSend jws = bitraverse_ (webSocketSend jws) (webSocketSend jws)
-- Use binary websocket communication for ByteString
-- Note: Binary websockets may not work correctly in IE 11 and below
instance IsWebSocketMessage ByteString where
webSocketSend (JSWebSocket ws) bs = do
ab <- bsToArrayBuffer bs
DOM.send ws ab
instance IsWebSocketMessage LBS.ByteString where
webSocketSend ws = webSocketSend ws . LBS.toStrict
-- Use plaintext websocket communication for Text, and String
instance IsWebSocketMessage Text where
webSocketSend (JSWebSocket ws) = DOM.sendString ws
closeWebSocket :: JSWebSocket -> Word -> Text -> JSM ()
closeWebSocket (JSWebSocket ws) code reason = DOM.close ws (Just code) (Just reason)
newWebSocket
:: Text -- url
-> [Text] -- protocols
-> (Either ByteString JSVal -> JSM ()) -- onmessage
-> JSM () -- onopen
-> JSM () -- onerror
-> ((Bool, Word, Text) -> JSM ()) -- onclose
-> JSM JSWebSocket
newWebSocket url protocols onMessage onOpen onError onClose = do
let onOpenWrapped = fun $ \_ _ _ -> onOpen
onErrorWrapped = fun $ \_ _ _ -> onError
onCloseWrapped = fun $ \_ _ (e:_) -> do
let e' = CloseEvent e
wasClean <- getWasClean e'
code <- getCode e'
reason <- getReason e'
liftJSM $ onClose (wasClean, code, reason)
onMessageWrapped = fun $ \_ _ (e:_) -> do
let e' = MessageEvent e
d <- getData e'
liftJSM $ ghcjsPure (jsTypeOf d) >>= \case
String -> onMessage $ Right d
_ -> do
ab <- mutableArrayBufferFromJSVal d
bsFromMutableArrayBuffer ab >>= onMessage . Left
newWS <- eval $ unlines
[ "(function(url, protos, open, error, close, message) {"
, " var ws = new window['WebSocket'](url, protos);"
, " ws['binaryType'] = 'arraybuffer';"
, " ws['addEventListener']('open', open);"
, " ws['addEventListener']('error', error);"
, " ws['addEventListener']('close', close);"
, " ws['addEventListener']('message', message);"
, " return ws;"
, "})"
]
url' <- toJSVal url
protocols' <- toJSVal protocols
onOpen' <- toJSVal onOpenWrapped
onError' <- toJSVal onErrorWrapped
onClose' <- toJSVal onCloseWrapped
onMessage' <- toJSVal onMessageWrapped
ws <- call newWS newWS [url', protocols', onOpen', onError', onClose', onMessage']
return $ JSWebSocket $ WebSocket ws
onBSMessage :: Either ByteString JSVal -> JSM ByteString
onBSMessage = either return $ fmap encodeUtf8 . fromJSValUnchecked
| reflex-frp/reflex-dom | reflex-dom-core/src/Reflex/Dom/WebSocket/Foreign.hs | bsd-3-clause | 3,749 | 0 | 22 | 713 | 1,006 | 538 | 468 | 80 | 2 |
{-# LANGUAGE DeriveGeneric , AutoDeriveTypeable #-}
-- | Notice that 'LongItem's are not supported as none are specified on the <http://www.usb.org/developers/hidpage/ USB Human Interface device page>
module System.USB.HID.Descriptor where
import Data.ByteString as B
import Data.Word
import GHC.Generics
data HIDDescriptor = HIDDescriptor
{hIDDescriptorType :: !Word8,
hIDcdHID :: !Version,
hIDCountryCode :: !Word8,
hIDNumDesc :: !Word8,
hIDDescType :: !Word8,
hIDDescLength :: !Int,
hIDDescType' :: !(Maybe Word8),
hIDDescLength' :: !(Maybe Word8)
} deriving (Show,Eq,Generic)
newtype HIDReportDesc = HIDReport [HIDReportItem]
deriving (Eq,Show,Generic)
data HIDPhysicalDescriptor = PD !HIDDesignator !HIDQualifier !HIDEffort
deriving (Eq,Show,Generic)
data HIDReportItem = HIDReportS !ShortItem
| HIDReportL !LongItem
deriving (Eq)
instance Show HIDReportItem where
show (HIDReportS x) = show x
show (HIDReportL x) = show x
data ShortItem = Main !HIDMainTag
| Global !HIDGlobalTag
| Local !HIDLocalTag
deriving (Eq,Generic)
instance Show ShortItem where
show (Main x) = show x
show (Global x) = show x
show (Local x) = show x
newtype LongItem = Long ()
deriving (Eq,Show,Generic)
data HIDMainTag = Input !HIDMainData
| Output !HIDMainData
| Feature !HIDMainData
| Collection !HIDCollectionData
| EndCollection
deriving (Show,Eq,Generic)
--Name these more meaningfully
data HIDMainData = HIDMainData
{bit0 :: !HDMBit0,
bit1 :: !HDMBit1,
bit2 :: !HDMBit2,
bit3 :: !HDMBit3,
bit4 :: !HDMBit4,
bit5 :: !HDMBit5,
bit6 :: !HDMBit6,
bit8 :: !HDMBit8
} deriving (Show,Eq,Generic)
constructHIDMainD :: [Int] -> HIDMainData
constructHIDMainD [a,b,c,d,e,f,g,h] = HIDMainData (toEnum a) (toEnum b) (toEnum c) (toEnum d) (toEnum e) (toEnum f) (toEnum g) (toEnum h)
data HDMBit0 = Data | Constant
deriving (Eq,Show,Enum,Generic)
data HDMBit1 = Array | Variable
deriving (Eq,Show,Enum,Generic)
data HDMBit2 = Absolute | Relative
deriving (Eq,Show,Enum,Generic)
data HDMBit3 = NoWrap | Wrap
deriving (Eq,Show,Enum,Generic)
data HDMBit4 = Linear | NonLinear
deriving (Eq,Show,Enum,Generic)
data HDMBit5 = PreferredState | NoPreferred
deriving (Eq,Show,Enum,Generic)
data HDMBit6 = NoNullPosition | NullState
deriving (Eq,Show,Enum,Generic)
data HDMBit8 = BitField | BufferedBytes
deriving (Eq,Show,Enum,Generic)
data HIDCollectionData = Physical
| Application
| Logical
| Report
| NamedArray
| UsageSwitch
| UsageModifier
deriving (Eq,Show,Enum,Generic)
data HIDGlobalTag = UsagePage !HIDUsagePage
| LogicalMinimum !Int
| LogicalMaximum !Int
| PhysicalMinimum !Int
| PhysicalMaximum !Int
| UnitExponent !Int
| Unit !Int
| ReportSize !Int
| ReportID !Int
| ReportCount !Int
| Push !Int
| Pop !Int
deriving (Show,Eq,Generic)
data HIDLocalTag = Usage !HIDUsage
| UsageMinimum !Int
| UsageMaximum !Int
| DesignatorIndex !HIDDesignator
| DesignatorMinimum !Int
| DesignatorMaximum !Int
| StringIndex !Int
| StringMinimum !Int
| StringMaximum !Int
| Delimiter !HIDDelimeter
deriving (Show,Eq,Generic)
data HIDDelimeter = Open | Close
deriving (Show,Eq,Enum,Generic)
newtype HIDUsagePage = UP Int
deriving (Show,Eq,Generic)
newtype HIDUsage = U Int
deriving (Show,Eq,Generic)
data HIDDesignator = None
| Hand
| Eyeball
| Eyebrow
| Eyelid
| Ear
| Nose
| Mouth
| UpperLip
| LowerLip
| Jaw
| Neck
| UpperArm
| Elbow
| Forearm
| Wrist
| Palm
| Thumb
| IndexFinger
| MiddleFinger
| RingFinger
| LittleFinger
| Head
| Shoulder
| Hip
| Waist
| Thigh
| Knee
| Calf
| Ankle
| Foot
| Heel
| BallOfFoot
| BigToe
| SecondToe
| ThirdToe
| FourthToe
| LittleToe
| Brow
| Cheek
deriving (Show,Eq,Enum,Generic)
data HIDQualifier = QNotApplicable
| RightSide
| LeftSide
| BothSides
| Either
| Center
deriving (Eq,Show,Enum,Generic)
data HIDBias = BNotApplicable
| RightHand
| LeftHand
| BothHands
| EitherHand
deriving (Eq,Show,Enum,Generic)
data HIDPhysDescSet = PDS !HIDBias !HIDPreference ![HIDPhysicalDescriptor]
deriving (Eq,Show,Generic)
type HIDEffort = Int
type HIDPreference = Int
data Version = V {main :: !Int,
minor :: !Int
}
deriving (Eq,Generic)
instance Show Version where
show (V ma mi) = (show ma) ++ "." ++ (show mi)
| mapinguari/usb-hid | System/USB/HID/Descriptor.hs | bsd-3-clause | 6,205 | 0 | 11 | 2,677 | 1,461 | 806 | 655 | 280 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module : Plots.Axis.ColourBar
-- Copyright : (C) 2015 Christopher Chalmers
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Christopher Chalmers
-- Stability : experimental
-- Portability : non-portable
--
-- Low level module defining type for the axis colour bar.
--
----------------------------------------------------------------------------
module Plots.Axis.ColourBar where
import Diagrams.Prelude
import Diagrams.TwoD.Text
import Plots.Types (Orientation (..), orient)
import Plots.Axis.Ticks
import Plots.Axis.Labels
import Plots.Themes
import Plots.Legend
data ColourBarOpts b n = ColourBarOpts
{ _cbOrientation :: Orientation
, _cbShow :: Bool
, _cbTickFun :: (n,n) -> [n] -- MajorTicksFunction
, _cbTicks :: Bool
, _cbTickLabels :: [n] -> (n,n) -> [(n, String)]
, _cbTextFun :: TextAlignment n -> String -> QDiagram b V2 n Any
, _cbExtent :: V2 n
, _cbGap :: n
, _cbStyle :: Style V2 n
-- , _colourBarSamples :: Sampled n
}
defColourBar :: (Renderable (Text n) b, Renderable (Path V2 n) b, TypeableFloat n, Enum n)
=> ColourBarOpts b n
defColourBar = ColourBarOpts
{ _cbOrientation = Verticle
, _cbShow = False
, _cbTextFun = mkText
, _cbTickFun = linearMajorTicks 3
, _cbTicks = True
, _cbTickLabels = atMajorTicks floatShow
, _cbExtent = V2 15 200
, _cbGap = 20
, _cbStyle = mempty
-- , _colourBarSamples :: Sampled n
}
makeLenses ''ColourBarOpts
drawColourBar :: (TypeableFloat n, Renderable (Path V2 n) b)
=> ColourBarOpts b n -> ColourMap -> n -> n -> QDiagram b V2 n Any
drawColourBar cbo cm a b = centerY $ bar ||| strutX 5 ||| labels
where
bar = square 1 # fillTexture tx
# scaleX x
# scaleY y
# applyStyle (cbo ^. cbStyle)
# alignB
labels = position (map (bimap toPos (view cbTextFun cbo tAlign)) ls)
# fontSizeO 8
V2 x y = cbo ^. cbExtent
toPos t = mkP2 0 (t * y / (b - a))
tx = mkLinearGradient (toStops cm) (mkP2 0 (-0.5)) (mkP2 0 0.5) GradPad
ps = view cbTickFun cbo (a,b)
ls = view cbTickLabels cbo ps (a,b)
tAlign = orient (cbo^.cbOrientation) (BoxAlignedText 0.5 1) (BoxAlignedText 0 0.5)
addColourBar :: (TypeableFloat n, Renderable (Path V2 n) b)
=> BoundingBox V2 n
-> ColourBarOpts b n
-> ColourMap
-> n
-> n
-> QDiagram b V2 n Any
addColourBar bb cbo cm a b
| not $ cbo^.cbShow = mempty
| otherwise = alignTo cbPos bb cbAnchor v cb
where
cbPos = orient (cbo^.cbOrientation) South East
cbAnchor = orient (cbo^.cbOrientation) AnchorTop AnchorLeft
v = (cbo^.cbGap) *^ orient (cbo^.cbOrientation) unit_Y unitX
cb = drawColourBar cbo cm a b
| bergey/plots | src/Plots/Axis/ColourBar.hs | bsd-3-clause | 3,080 | 0 | 14 | 871 | 883 | 479 | 404 | 63 | 1 |
module ExampleModule where
import Data.Char
foo :: Double -> Double -> Double
foo = (*)
bar :: Int -> Int
bar i = sum [1..i]
baz :: Int -> Bool
baz = (> 5)
arr_arg :: [Int] -> Int
arr_arg = sum
arr_ret :: Int -> [Int]
arr_ret i = [1..i]
arr_complex :: [[Int]] -> [[Int]]
arr_complex = map (map (* 2))
string_fun :: String -> String
string_fun str = str ++ reverse str
char_test :: Char -> Int
char_test = ord
| sakana/HaPy | example/haskell/ExampleModule.hs | mit | 418 | 0 | 8 | 91 | 191 | 109 | 82 | 18 | 1 |
{-|
Module : Devel.Paths
Description : For filepath related matters.
Copyright : (c) 2015 Njagi Mwaniki
License : MIT
Maintainer : njagi@urbanslug.com
Stability : experimental
Portability : POSIX
Uses the GHC package to parse .hi files.
Will hopefully be moved upstream to ide-backend.
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
module Devel.Paths
( getFilesToWatch
, getThFiles
, getCabalFile
, getRecursiveContents
-- , getRecursiveContentsRelative
) where
-- Qualified imports
import qualified Data.ByteString.Char8 as C8
import "Glob" System.FilePath.Glob (globDir, compile, Pattern, glob)
import System.FilePath.Posix (replaceExtension)
import System.Directory (doesFileExist, removeFile, getDirectoryContents, doesDirectoryExist)
import System.FilePath ((</>))
import Control.Monad.IO.Class (liftIO)
import Control.Monad (forM,filterM)
import Data.List ((\\))
getThFiles :: [FilePath] -> IO [FilePath]
getThFiles targetList = do
let dumpFiles' = map (`replaceExtension` "dump-hi") targetList
dumpFiles <- filterM doesFileExist dumpFiles'
thFiles' <- mapM parseHi dumpFiles
let thFiles = map (takeWhile (/='\"') . dropWhile (=='\"') . dropWhile (/='\"')) $ concat thFiles'
_ <- mapM removeFile dumpFiles
return thFiles
getFilesToWatch :: [FilePath] -> IO [FilePath]
getFilesToWatch targetList = do
thFiles <- getThFiles targetList
return $ thFiles ++ targetList
parseHi :: FilePath -> IO [FilePath]
parseHi path = do
dumpHI <- liftIO $ fmap C8.lines (C8.readFile path)
let thDeps' =
-- The dependent file path is surrounded by quotes but is not escaped.
-- It can be an absolute or relative path.
filter ("addDependentFile \"" `C8.isPrefixOf`) dumpHI
return $ map C8.unpack thDeps'
getRecursiveContents :: FilePath -> IO [FilePath]
getRecursiveContents topdir = do
names <- getDirectoryContents topdir
-- We want to take these files out.
let patterns :: [Pattern]
patterns = [ (compile "*.*~")
, (compile ".#*")
, (compile "*.hi")
, (compile "*.dump-hi")
, (compile "*.o")
, (compile "*.dyn_o")
, (compile "*.dyn_hi")
, (compile "*.so")
, (compile "*.conf")
, (compile "*.h")
, (compile "*.a")
, (compile "*.inplace")
, (compile "*.cache")
, (compile "*.*.el")
, (compile ".*")
]
(x, _) <- globDir patterns topdir
let properNames = filter (`notElem` [".", ".."]) names
paths <- forM properNames $ \name -> do
let path = makePathRelative topdir </> name
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path
else return $ [path] \\ concat x
return (concat paths)
where makePathRelative :: FilePath -> FilePath
makePathRelative topDir
| topDir == "." = ""
| otherwise = topDir
getCabalFile :: IO FilePath
getCabalFile = do
list <- glob "*cabal"
case list of
[] -> fail "No cabal file."
(cabalFile:_) -> return cabalFile
| urbanslug/yesod-devel | src/Devel/Paths.hs | gpl-3.0 | 3,207 | 0 | 16 | 814 | 817 | 434 | 383 | 71 | 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.STS.DecodeAuthorizationMessage
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Decodes additional information about the authorization status of a request
-- from an encoded message returned in response to an AWS request.
--
-- For example, if a user is not authorized to perform an action that he or she
-- has requested, the request returns a 'Client.UnauthorizedOperation' response
-- (an HTTP 403 response). Some AWS actions additionally return an encoded
-- message that can provide details about this authorization failure.
--
-- The message is encoded because the details of the authorization status can
-- constitute privileged information that the user who requested the action
-- should not see. To decode an authorization status message, a user must be
-- granted permissions via an IAM policy to request the 'DecodeAuthorizationMessage' ('sts:DecodeAuthorizationMessage') action.
--
-- The decoded message includes the following type of information:
--
-- Whether the request was denied due to an explicit deny or due to the
-- absence of an explicit allow. For more information, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/AccessPolicyLanguage_EvaluationLogic.html#policy-eval-denyallow Determining Whether aRequest is Allowed or Denied> in /Using IAM/. The principal who made the
-- request. The requested action. The requested resource. The values of
-- condition keys in the context of the user's request.
--
-- <http://docs.aws.amazon.com/STS/latest/APIReference/API_DecodeAuthorizationMessage.html>
module Network.AWS.STS.DecodeAuthorizationMessage
(
-- * Request
DecodeAuthorizationMessage
-- ** Request constructor
, decodeAuthorizationMessage
-- ** Request lenses
, damEncodedMessage
-- * Response
, DecodeAuthorizationMessageResponse
-- ** Response constructor
, decodeAuthorizationMessageResponse
-- ** Response lenses
, damrDecodedMessage
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.STS.Types
import qualified GHC.Exts
newtype DecodeAuthorizationMessage = DecodeAuthorizationMessage
{ _damEncodedMessage :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DecodeAuthorizationMessage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'damEncodedMessage' @::@ 'Text'
--
decodeAuthorizationMessage :: Text -- ^ 'damEncodedMessage'
-> DecodeAuthorizationMessage
decodeAuthorizationMessage p1 = DecodeAuthorizationMessage
{ _damEncodedMessage = p1
}
-- | The encoded message that was returned with the response.
damEncodedMessage :: Lens' DecodeAuthorizationMessage Text
damEncodedMessage =
lens _damEncodedMessage (\s a -> s { _damEncodedMessage = a })
newtype DecodeAuthorizationMessageResponse = DecodeAuthorizationMessageResponse
{ _damrDecodedMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'DecodeAuthorizationMessageResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'damrDecodedMessage' @::@ 'Maybe' 'Text'
--
decodeAuthorizationMessageResponse :: DecodeAuthorizationMessageResponse
decodeAuthorizationMessageResponse = DecodeAuthorizationMessageResponse
{ _damrDecodedMessage = Nothing
}
-- | An XML document that contains the decoded message. For more information, see 'DecodeAuthorizationMessage'.
damrDecodedMessage :: Lens' DecodeAuthorizationMessageResponse (Maybe Text)
damrDecodedMessage =
lens _damrDecodedMessage (\s a -> s { _damrDecodedMessage = a })
instance ToPath DecodeAuthorizationMessage where
toPath = const "/"
instance ToQuery DecodeAuthorizationMessage where
toQuery DecodeAuthorizationMessage{..} = mconcat
[ "EncodedMessage" =? _damEncodedMessage
]
instance ToHeaders DecodeAuthorizationMessage
instance AWSRequest DecodeAuthorizationMessage where
type Sv DecodeAuthorizationMessage = STS
type Rs DecodeAuthorizationMessage = DecodeAuthorizationMessageResponse
request = post "DecodeAuthorizationMessage"
response = xmlResponse
instance FromXML DecodeAuthorizationMessageResponse where
parseXML = withElement "DecodeAuthorizationMessageResult" $ \x -> DecodeAuthorizationMessageResponse
<$> x .@? "DecodedMessage"
| kim/amazonka | amazonka-sts/gen/Network/AWS/STS/DecodeAuthorizationMessage.hs | mpl-2.0 | 5,287 | 0 | 9 | 953 | 448 | 280 | 168 | 55 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
module Ef.Type.List where
import Ef.Type.Nat
import GHC.Exts
data Index (n :: Nat) where
Index :: Index n
type family Appended (xs :: [k]) (ys :: [k]) where
Appended '[] ys = ys
Appended xs '[] = xs
Appended (x ': xs) ys = x ': (Appended xs ys)
type family Offset (xs :: [k]) (x :: k) :: Nat where
Offset (x ': xs) x = 'Z
Offset (any ': xs) x = 'S (Offset xs x)
type family Removed xs x where
Removed '[] x = '[]
Removed (x ': xs) x = xs
Removed (any ': xs) x = any ': Removed xs x
type family Constrain cs as :: Constraint where
Constrain '[] as = ()
Constrain (c ': cs) as = (Constrained c as, Constrain cs as)
type family Constrained c as :: Constraint where
Constrained c '[] = ()
Constrained c (a ': as) = (c a, Constrained c as)
| grumply/Ef | src/Ef/Type/List.hs | bsd-3-clause | 939 | 0 | 8 | 213 | 406 | 231 | 175 | 28 | 0 |
module Network.Mattermost.TH where
import qualified Language.Haskell.TH.Syntax as TH
import qualified Language.Haskell.TH.Lib as TH
import Lens.Micro ((&), (.~))
import Lens.Micro.TH (DefName(..), makeLensesWith, lensRules, lensField)
suffixLenses :: TH.Name -> TH.DecsQ
suffixLenses = makeLensesWith $
lensRules & lensField .~ (\_ _ name -> [TopName $ TH.mkName $ TH.nameBase name ++ "L"])
| dagit/mattermost-api | src/Network/Mattermost/TH.hs | bsd-3-clause | 396 | 0 | 12 | 53 | 132 | 83 | 49 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Microspec
import Sound.Tidal.TidalParseTest
main :: IO ()
main = microspec $ do
Sound.Tidal.TidalParseTest.run
| d0kt0r0/Tidal | tidal-parse/test/Test.hs | gpl-3.0 | 163 | 0 | 8 | 23 | 39 | 22 | 17 | 6 | 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.IAM.GetRolePolicy
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Retrieves the specified inline policy document that is embedded with the
-- specified role.
--
-- A role can also have managed policies attached to it. To retrieve a managed
-- policy document that is attached to a role, use 'GetPolicy' to determine the
-- policy's default version, then use 'GetPolicyVersion' to retrieve the policy
-- document.
--
-- For more information about policies, refer to <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and InlinePolicies> in the /Using IAM/ guide.
--
-- For more information about roles, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html Using Roles to Delegate Permissionsand Federate Identities>.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRolePolicy.html>
module Network.AWS.IAM.GetRolePolicy
(
-- * Request
GetRolePolicy
-- ** Request constructor
, getRolePolicy
-- ** Request lenses
, grpPolicyName
, grpRoleName
-- * Response
, GetRolePolicyResponse
-- ** Response constructor
, getRolePolicyResponse
-- ** Response lenses
, grprPolicyDocument
, grprPolicyName
, grprRoleName
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data GetRolePolicy = GetRolePolicy
{ _grpPolicyName :: Text
, _grpRoleName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'GetRolePolicy' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grpPolicyName' @::@ 'Text'
--
-- * 'grpRoleName' @::@ 'Text'
--
getRolePolicy :: Text -- ^ 'grpRoleName'
-> Text -- ^ 'grpPolicyName'
-> GetRolePolicy
getRolePolicy p1 p2 = GetRolePolicy
{ _grpRoleName = p1
, _grpPolicyName = p2
}
-- | The name of the policy document to get.
grpPolicyName :: Lens' GetRolePolicy Text
grpPolicyName = lens _grpPolicyName (\s a -> s { _grpPolicyName = a })
-- | The name of the role associated with the policy.
grpRoleName :: Lens' GetRolePolicy Text
grpRoleName = lens _grpRoleName (\s a -> s { _grpRoleName = a })
data GetRolePolicyResponse = GetRolePolicyResponse
{ _grprPolicyDocument :: Text
, _grprPolicyName :: Text
, _grprRoleName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'GetRolePolicyResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grprPolicyDocument' @::@ 'Text'
--
-- * 'grprPolicyName' @::@ 'Text'
--
-- * 'grprRoleName' @::@ 'Text'
--
getRolePolicyResponse :: Text -- ^ 'grprRoleName'
-> Text -- ^ 'grprPolicyName'
-> Text -- ^ 'grprPolicyDocument'
-> GetRolePolicyResponse
getRolePolicyResponse p1 p2 p3 = GetRolePolicyResponse
{ _grprRoleName = p1
, _grprPolicyName = p2
, _grprPolicyDocument = p3
}
-- | The policy document.
grprPolicyDocument :: Lens' GetRolePolicyResponse Text
grprPolicyDocument =
lens _grprPolicyDocument (\s a -> s { _grprPolicyDocument = a })
-- | The name of the policy.
grprPolicyName :: Lens' GetRolePolicyResponse Text
grprPolicyName = lens _grprPolicyName (\s a -> s { _grprPolicyName = a })
-- | The role the policy is associated with.
grprRoleName :: Lens' GetRolePolicyResponse Text
grprRoleName = lens _grprRoleName (\s a -> s { _grprRoleName = a })
instance ToPath GetRolePolicy where
toPath = const "/"
instance ToQuery GetRolePolicy where
toQuery GetRolePolicy{..} = mconcat
[ "PolicyName" =? _grpPolicyName
, "RoleName" =? _grpRoleName
]
instance ToHeaders GetRolePolicy
instance AWSRequest GetRolePolicy where
type Sv GetRolePolicy = IAM
type Rs GetRolePolicy = GetRolePolicyResponse
request = post "GetRolePolicy"
response = xmlResponse
instance FromXML GetRolePolicyResponse where
parseXML = withElement "GetRolePolicyResult" $ \x -> GetRolePolicyResponse
<$> x .@ "PolicyDocument"
<*> x .@ "PolicyName"
<*> x .@ "RoleName"
| kim/amazonka | amazonka-iam/gen/Network/AWS/IAM/GetRolePolicy.hs | mpl-2.0 | 5,113 | 0 | 13 | 1,151 | 643 | 392 | 251 | 76 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[HsLit]{Abstract syntax: source-language literals}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
module ETA.HsSyn.HsLit where
#include "HsVersions.h"
import {-# SOURCE #-} ETA.HsSyn.HsExpr( SyntaxExpr, pprExpr )
import ETA.BasicTypes.BasicTypes ( FractionalLit(..),SourceText )
import ETA.Types.Type ( Type )
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.HsSyn.PlaceHolder ( PostTc,PostRn,DataId )
import Data.ByteString (ByteString)
import Data.Data hiding ( Fixity )
{-
************************************************************************
* *
\subsection[HsLit]{Literals}
* *
************************************************************************
-}
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data HsLit
= HsChar SourceText Char -- Character
| HsCharPrim SourceText Char -- Unboxed character
| HsString SourceText FastString -- String
| HsStringPrim SourceText ByteString -- Packed bytes
| HsInt SourceText Integer -- Genuinely an Int; arises from
-- TcGenDeriv, and from TRANSLATION
| HsIntPrim SourceText Integer -- literal Int#
| HsWordPrim SourceText Integer -- literal Word#
| HsInt64Prim SourceText Integer -- literal Int64#
| HsWord64Prim SourceText Integer -- literal Word64#
| HsInteger SourceText Integer Type -- Genuinely an integer; arises only
-- from TRANSLATION (overloaded
-- literals are done with HsOverLit)
| HsRat FractionalLit Type -- Genuinely a rational; arises only from
-- TRANSLATION (overloaded literals are
-- done with HsOverLit)
| HsFloatPrim FractionalLit -- Unboxed Float
| HsDoublePrim FractionalLit -- Unboxed Double
deriving (Data, Typeable)
instance Eq HsLit where
(HsChar _ x1) == (HsChar _ x2) = x1==x2
(HsCharPrim _ x1) == (HsCharPrim _ x2) = x1==x2
(HsString _ x1) == (HsString _ x2) = x1==x2
(HsStringPrim _ x1) == (HsStringPrim _ x2) = x1==x2
(HsInt _ x1) == (HsInt _ x2) = x1==x2
(HsIntPrim _ x1) == (HsIntPrim _ x2) = x1==x2
(HsWordPrim _ x1) == (HsWordPrim _ x2) = x1==x2
(HsInt64Prim _ x1) == (HsInt64Prim _ x2) = x1==x2
(HsWord64Prim _ x1) == (HsWord64Prim _ x2) = x1==x2
(HsInteger _ x1 _) == (HsInteger _ x2 _) = x1==x2
(HsRat x1 _) == (HsRat x2 _) = x1==x2
(HsFloatPrim x1) == (HsFloatPrim x2) = x1==x2
(HsDoublePrim x1) == (HsDoublePrim x2) = x1==x2
_ == _ = False
data HsOverLit id -- An overloaded literal
= OverLit {
ol_val :: OverLitVal,
ol_rebindable :: PostRn id Bool, -- Note [ol_rebindable]
ol_witness :: SyntaxExpr id, -- Note [Overloaded literal witnesses]
ol_type :: PostTc id Type }
deriving (Typeable)
deriving instance (DataId id) => Data (HsOverLit id)
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data OverLitVal
= HsIntegral !SourceText !Integer -- Integer-looking literals;
| HsFractional !FractionalLit -- Frac-looking literals
| HsIsString !SourceText !FastString -- String-looking literals
deriving (Data, Typeable)
overLitType :: HsOverLit a -> PostTc a Type
overLitType = ol_type
{-
Note [ol_rebindable]
~~~~~~~~~~~~~~~~~~~~
The ol_rebindable field is True if this literal is actually
using rebindable syntax. Specifically:
False iff ol_witness is the standard one
True iff ol_witness is non-standard
Equivalently it's True if
a) RebindableSyntax is on
b) the witness for fromInteger/fromRational/fromString
that happens to be in scope isn't the standard one
Note [Overloaded literal witnesses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Before* type checking, the SyntaxExpr in an HsOverLit is the
name of the coercion function, 'fromInteger' or 'fromRational'.
*After* type checking, it is a witness for the literal, such as
(fromInteger 3) or lit_78
This witness should replace the literal.
This dual role is unusual, because we're replacing 'fromInteger' with
a call to fromInteger. Reason: it allows commoning up of the fromInteger
calls, which wouldn't be possible if the desguarar made the application.
The PostTcType in each branch records the type the overload literal is
found to have.
-}
-- Comparison operations are needed when grouping literals
-- for compiling pattern-matching (module MatchLit)
instance Eq (HsOverLit id) where
(OverLit {ol_val = val1}) == (OverLit {ol_val=val2}) = val1 == val2
instance Eq OverLitVal where
(HsIntegral _ i1) == (HsIntegral _ i2) = i1 == i2
(HsFractional f1) == (HsFractional f2) = f1 == f2
(HsIsString _ s1) == (HsIsString _ s2) = s1 == s2
_ == _ = False
instance Ord (HsOverLit id) where
compare (OverLit {ol_val=val1}) (OverLit {ol_val=val2}) = val1 `compare` val2
instance Ord OverLitVal where
compare (HsIntegral _ i1) (HsIntegral _ i2) = i1 `compare` i2
compare (HsIntegral _ _) (HsFractional _) = LT
compare (HsIntegral _ _) (HsIsString _ _) = LT
compare (HsFractional f1) (HsFractional f2) = f1 `compare` f2
compare (HsFractional _) (HsIntegral _ _) = GT
compare (HsFractional _) (HsIsString _ _) = LT
compare (HsIsString _ s1) (HsIsString _ s2) = s1 `compare` s2
compare (HsIsString _ _) (HsIntegral _ _) = GT
compare (HsIsString _ _) (HsFractional _) = GT
instance Outputable HsLit where
-- Use "show" because it puts in appropriate escapes
ppr (HsChar _ c) = pprHsChar c
ppr (HsCharPrim _ c) = pprHsChar c <> char '#'
ppr (HsString _ s) = pprHsString s
ppr (HsStringPrim _ s) = pprHsBytes s <> char '#'
ppr (HsInt _ i) = integer i
ppr (HsInteger _ i _) = integer i
ppr (HsRat f _) = ppr f
ppr (HsFloatPrim f) = ppr f <> char '#'
ppr (HsDoublePrim d) = ppr d <> text "##"
ppr (HsIntPrim _ i) = integer i <> char '#'
ppr (HsWordPrim _ w) = integer w <> text "##"
ppr (HsInt64Prim _ i) = integer i <> text "L#"
ppr (HsWord64Prim _ w) = integer w <> text "L##"
-- in debug mode, print the expression that it's resolved to, too
instance OutputableBndr id => Outputable (HsOverLit id) where
ppr (OverLit {ol_val=val, ol_witness=witness})
= ppr val <+> (ifPprDebug (parens (pprExpr witness)))
instance Outputable OverLitVal where
ppr (HsIntegral _ i) = integer i
ppr (HsFractional f) = ppr f
ppr (HsIsString _ s) = pprHsString s
| alexander-at-github/eta | compiler/ETA/HsSyn/HsLit.hs | bsd-3-clause | 7,388 | 0 | 12 | 2,020 | 1,713 | 893 | 820 | 111 | 1 |
{- |
Module : XMonad.Actions.WindowGo
License : Public domain
Maintainer : <gwern0@gmail.com>
Stability : unstable
Portability : unportable
Defines a few convenient operations for raising (traveling to) windows based on XMonad's Query
monad, such as 'runOrRaise'. runOrRaise will run a shell command unless it can
find a specified window; you would use this to automatically travel to your
Firefox or Emacs session, or start a new one (for example), instead of trying to
remember where you left it or whether you still have one running. -}
module XMonad.Actions.WindowGo (
-- * Usage
-- $usage
raise,
raiseNext,
runOrRaise,
runOrRaiseNext,
raiseMaybe,
raiseNextMaybe,
raiseNextMaybeCustomFocus,
raiseBrowser,
raiseEditor,
runOrRaiseAndDo,
runOrRaiseMaster,
raiseAndDo,
raiseMaster,
ifWindows,
ifWindow,
raiseHook,
module XMonad.ManageHook
) where
import Control.Monad
import Data.Char (toLower)
import qualified Data.List as L (nub,sortBy)
import Data.Monoid
import XMonad (Query(), X(), ManageHook, WindowSet, withWindowSet, runQuery, liftIO, ask)
import Graphics.X11 (Window)
import XMonad.ManageHook
import XMonad.Operations (windows)
import XMonad.Prompt.Shell (getBrowser, getEditor)
import qualified XMonad.StackSet as W (peek, swapMaster, focusWindow, workspaces, StackSet, Workspace, integrate', tag, stack)
import XMonad.Util.Run (safeSpawnProg)
{- $usage
Import the module into your @~\/.xmonad\/xmonad.hs@:
> import XMonad.Actions.WindowGo
and define appropriate key bindings:
> , ((modm .|. shiftMask, xK_g), raise (className =? "Firefox"))
> , ((modm .|. shiftMask, xK_b), runOrRaise "firefox" (className =? "Firefox"))
(Note that Firefox v3 and up have a class-name of \"Firefox\" and \"Navigator\";
lower versions use other classnames such as \"Firefox-bin\". Either choose the
appropriate one, or cover your bases by using instead something like:
> (className =? "Firefox" <||> className =? "Firefox-bin")
For detailed instructions on editing your key bindings, see
"XMonad.Doc.Extending#Editing_key_bindings". -}
-- | Get the list of workspaces sorted by their tag
workspacesSorted :: Ord i => W.StackSet i l a s sd -> [W.Workspace i l a]
workspacesSorted s = L.sortBy (\u t -> W.tag u `compare` W.tag t) $ W.workspaces s
-- | Get a list of all windows in the 'StackSet' with an absolute ordering of workspaces
allWindowsSorted :: Ord i => Eq a => W.StackSet i l a s sd -> [a]
allWindowsSorted = L.nub . concatMap (W.integrate' . W.stack) . workspacesSorted
-- | If windows that satisfy the query exist, apply the supplied
-- function to them, otherwise run the action given as
-- second parameter.
ifWindows :: Query Bool -> ([Window] -> X ()) -> X () -> X ()
ifWindows qry f el = withWindowSet $ \wins -> do
matches <- filterM (runQuery qry) $ allWindowsSorted wins
case matches of
[] -> el
ws -> f ws
-- | The same as ifWindows, but applies a ManageHook to the first match
-- instead and discards the other matches
ifWindow :: Query Bool -> ManageHook -> X () -> X ()
ifWindow qry mh = ifWindows qry (windows . appEndo <=< runQuery mh . head)
{- | 'action' is an executable to be run via 'safeSpawnProg' (of "XMonad.Util.Run") if the Window cannot be found.
Presumably this executable is the same one that you were looking for.
Note that this does not go through the shell. If you wish to run an arbitrary IO action
(such as 'spawn', which will run its String argument through the shell), then you will want to use
'raiseMaybe' directly. -}
runOrRaise :: String -> Query Bool -> X ()
runOrRaise = raiseMaybe . safeSpawnProg
-- | See 'raiseMaybe'. If the Window can't be found, quietly give up and do nothing.
raise :: Query Bool -> X ()
raise = raiseMaybe $ return ()
{- | 'raiseMaybe' queries all Windows based on a boolean provided by the
user. Currently, there are 3 such useful booleans defined in
"XMonad.ManageHook": 'title', 'resource', 'className'. Each one tests based pretty
much as you would think. ManageHook also defines several operators, the most
useful of which is (=?). So a useful test might be finding a @Window@ whose
class is Firefox. Firefox 3 declares the class \"Firefox\", so you'd want to
pass in a boolean like @(className =? \"Firefox\")@.
If the boolean returns @True@ on one or more windows, then XMonad will quickly
make visible the first result. If no @Window@ meets the criteria, then the
first argument comes into play.
The first argument is an arbitrary IO function which will be executed if the
tests fail. This is what enables 'runOrRaise' to use 'raiseMaybe': it simply runs
the desired program if it isn't found. But you don't have to do that. Maybe
you want to do nothing if the search fails (the definition of 'raise'), or
maybe you want to write to a log file, or call some prompt function, or
something crazy like that. This hook gives you that flexibility. You can do
some cute things with this hook. Suppose you want to do the same thing for
Mutt which you just did for Firefox - but Mutt runs inside a terminal window?
No problem: you search for a terminal window calling itself \"mutt\", and if
there isn't you run a terminal with a command to run Mutt! Here's an example
(borrowing 'runInTerm' from "XMonad.Util.Run"):
> , ((modm, xK_m), raiseMaybe (runInTerm "-title mutt" "mutt") (title =? "mutt"))
-}
raiseMaybe :: X () -> Query Bool -> X ()
raiseMaybe f qry = ifWindow qry raiseHook f
-- | A manage hook that raises the window.
raiseHook :: ManageHook
raiseHook = ask >>= doF . W.focusWindow
-- | See 'runOrRaise' and 'raiseNextMaybe'. Version that allows cycling through matches.
runOrRaiseNext :: String -> Query Bool -> X ()
runOrRaiseNext = raiseNextMaybe . safeSpawnProg
-- | See 'raise' and 'raiseNextMaybe'. Version that allows cycling through matches.
raiseNext :: Query Bool -> X ()
raiseNext = raiseNextMaybe $ return ()
{- | See 'raiseMaybe'.
'raiseNextMaybe' is an alternative version that allows cycling
through the matching windows. If the focused window matches the
query the next matching window is raised. If no matches are found
the function f is executed. -}
raiseNextMaybe :: X () -> Query Bool -> X ()
raiseNextMaybe = raiseNextMaybeCustomFocus W.focusWindow
{- | See 'raiseMaybe' and 'raiseNextMaybe'.
In addition to all of the options offered by 'raiseNextMaybe'
'raiseNextMaybeCustomFocus' allows the user to supply the function that
should be used to shift the focus to any window that is found. -}
raiseNextMaybeCustomFocus :: (Window -> WindowSet -> WindowSet) -> X() -> Query Bool -> X()
raiseNextMaybeCustomFocus focusFn f qry = flip (ifWindows qry) f $ \ws -> do
foc <- withWindowSet $ return . W.peek
case foc of
Just w | w `elem` ws -> let (_:y:_) = dropWhile (/=w) $ cycle ws -- cannot fail to match
in windows $ focusFn y
_ -> windows . focusFn . head $ ws
-- | Given a function which gets us a String, we try to raise a window with that classname,
-- or we then interpret that String as a executable name.
raiseVar :: IO String -> X ()
raiseVar getvar = liftIO getvar >>= \var -> runOrRaise var (fmap (map toLower) className =? var)
{- | 'raiseBrowser' and 'raiseEditor' grab $BROWSER and $EDITOR respectively and they either
take you to the specified program's window, or they try to run it. This is most useful
if your variables are simple and look like \"firefox\" or \"emacs\". -}
raiseBrowser, raiseEditor :: X ()
raiseBrowser = raiseVar getBrowser
raiseEditor = raiseVar getEditor
{- | If the window is found the window is focused and the third argument is called
otherwise, the first argument is called
See 'raiseMaster' for an example. -}
raiseAndDo :: X () -> Query Bool -> (Window -> X ()) -> X ()
raiseAndDo f qry after = ifWindow qry (afterRaise `mappend` raiseHook) f
where afterRaise = ask >>= (>> idHook) . liftX . after
{- | If a window matching the second argument is found, the window is focused and
the third argument is called;
otherwise, the first argument is called. -}
runOrRaiseAndDo :: String -> Query Bool -> (Window -> X ()) -> X ()
runOrRaiseAndDo = raiseAndDo . safeSpawnProg
{- | if the window is found the window is focused and set to master
otherwise, the first argument is called.
> raiseMaster (runInTerm "-title ghci" "zsh -c 'ghci'") (title =? "ghci") -}
raiseMaster :: X () -> Query Bool -> X ()
raiseMaster raisef thatUserQuery = raiseAndDo raisef thatUserQuery (\_ -> windows W.swapMaster)
{- | If the window is found the window is focused and set to master
otherwise, action is run.
> runOrRaiseMaster "firefox" (className =? "Firefox")) -}
runOrRaiseMaster :: String -> Query Bool -> X ()
runOrRaiseMaster run query = runOrRaiseAndDo run query (\_ -> windows W.swapMaster)
| f1u77y/xmonad-contrib | XMonad/Actions/WindowGo.hs | bsd-3-clause | 9,236 | 0 | 19 | 2,028 | 1,316 | 695 | 621 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hadrian.Oracles.Cabal.Type
-- Copyright : (c) Andrey Mokhov 2014-2018
-- License : MIT (see the file LICENSE)
-- Maintainer : andrey.mokhov@gmail.com
-- Stability : experimental
--
-- This module defines the types of keys used by the /Cabal oracles/. See the
-- module "Hadrian.Oracles.Cabal" for supported Cabal oracle queries, and the
-- module "Hadrian.Oracles.Cabal.Rules" for the corresponing Shake rules.
-----------------------------------------------------------------------------
module Hadrian.Oracles.Cabal.Type where
import Development.Shake
import Development.Shake.Classes
import qualified Distribution.Simple as C
import qualified Distribution.System as C
import Context.Type
import Hadrian.Haskell.Cabal.Type
import Hadrian.Package
import Stage
-- | This type of oracle key is used by 'Hadrian.Oracles.Cabal.readPackageData'
-- to cache reading and parsing of 'Hadrian.Haskell.Cabal.Type.PackageData'.
newtype PackageDataKey = PackageDataKey Package
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult PackageDataKey = PackageData
-- | This type of oracle key is used by 'Hadrian.Oracles.Cabal.readContextData'
-- to cache reading and parsing of 'Hadrian.Haskell.Cabal.Type.ContextData'.
newtype ContextDataKey = ContextDataKey Context
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult ContextDataKey = ContextData
-- TODO: Should @PackageConfiguration@ be simply @()@? Presumably the pair
-- @(Compiler, Maybe Platform)@ is fully determined by the current build Stage.
-- | The result of Cabal package configuration produced by the oracle
-- 'Hadrian.Oracles.Cabal.configurePackageGHC'.
newtype PackageConfiguration = PackageConfiguration (C.Compiler, C.Platform)
deriving (Binary, Eq, Show, Typeable)
instance NFData PackageConfiguration where
rnf (PackageConfiguration (c, p)) =
rnf (C.compilerId c) `seq`
rnf (C.abiTagString $ C.compilerAbiTag c) `seq`
rnf (C.compilerCompat c) `seq`
rnf (C.compilerLanguages c) `seq`
rnf (C.compilerExtensions c) `seq`
rnf (C.compilerProperties c) `seq`
rnf p
instance Hashable PackageConfiguration where
hashWithSalt _ = hash . show
-- | This type of oracle key is used by 'Hadrian.Oracles.Cabal.configurePackageGHC'
-- to cache configuration of a Cabal package.
newtype PackageConfigurationKey = PackageConfigurationKey (Package, Stage)
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult PackageConfigurationKey = PackageConfiguration
| snowleopard/shaking-up-ghc | src/Hadrian/Oracles/Cabal/Type.hs | bsd-3-clause | 2,781 | 0 | 16 | 475 | 415 | 244 | 171 | 32 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- | Parsing the top of a Haskell source file to get its module name,
-- imports and options.
--
-- (c) Simon Marlow 2005
-- (c) Lemmih 2006
--
-----------------------------------------------------------------------------
module HeaderInfo ( getImports
, mkPrelImports -- used by the renamer too
, getOptionsFromFile, getOptions
, optionsErrorMsgs,
checkProcessArgsResult ) where
#include "HsVersions.h"
import RdrName
import HscTypes
import Parser ( parseHeader )
import Lexer
import FastString
import HsSyn
import Module
import PrelNames
import StringBuffer
import SrcLoc
import DynFlags
import ErrUtils
import Util
import Outputable
import Pretty ()
import Maybes
import Bag ( emptyBag, listToBag, unitBag )
import MonadUtils
import Exception
import BasicTypes
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import System.IO
import System.IO.Unsafe
import Data.List
------------------------------------------------------------------------------
-- | Parse the imports of a source file.
--
-- Throws a 'SourceError' if parsing fails.
getImports :: DynFlags
-> StringBuffer -- ^ Parse this.
-> FilePath -- ^ Filename the buffer came from. Used for
-- reporting parse error locations.
-> FilePath -- ^ The original source filename (used for locations
-- in the function result)
-> IO ([(Maybe FastString, Located ModuleName)],
[(Maybe FastString, Located ModuleName)],
Located ModuleName)
-- ^ The source imports, normal imports, and the module name.
getImports dflags buf filename source_filename = do
let loc = mkRealSrcLoc (mkFastString filename) 1 1
case unP parseHeader (mkPState dflags buf loc) of
PFailed span err -> parseError dflags span err
POk pst rdr_module -> do
let _ms@(_warns, errs) = getMessages pst dflags
-- don't log warnings: they'll be reported when we parse the file
-- for real. See #2500.
ms = (emptyBag, errs)
-- logWarnings warns
if errorsFound dflags ms
then throwIO $ mkSrcErr errs
else
case rdr_module of
L _ (HsModule mb_mod _ imps _ _ _) ->
let
main_loc = srcLocSpan (mkSrcLoc (mkFastString source_filename) 1 1)
mod = mb_mod `orElse` L main_loc mAIN_NAME
(src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps
-- GHC.Prim doesn't exist physically, so don't go looking for it.
ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc)
ord_idecls
implicit_prelude = xopt LangExt.ImplicitPrelude dflags
implicit_imports = mkPrelImports (unLoc mod) main_loc
implicit_prelude imps
convImport (L _ i) = (fmap sl_fs (ideclPkgQual i), ideclName i)
in
return (map convImport src_idecls,
map convImport (implicit_imports ++ ordinary_imps),
mod)
mkPrelImports :: ModuleName
-> SrcSpan -- Attribute the "import Prelude" to this location
-> Bool -> [LImportDecl RdrName]
-> [LImportDecl RdrName]
-- Consruct the implicit declaration "import Prelude" (or not)
--
-- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
-- because the former doesn't even look at Prelude.hi for instance
-- declarations, whereas the latter does.
mkPrelImports this_mod loc implicit_prelude import_decls
| this_mod == pRELUDE_NAME
|| explicit_prelude_import
|| not implicit_prelude
= []
| otherwise = [preludeImportDecl]
where
explicit_prelude_import
= notNull [ () | L _ (ImportDecl { ideclName = mod
, ideclPkgQual = Nothing })
<- import_decls
, unLoc mod == pRELUDE_NAME ]
preludeImportDecl :: LImportDecl RdrName
preludeImportDecl
= L loc $ ImportDecl { ideclSourceSrc = Nothing,
ideclName = L loc pRELUDE_NAME,
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False, -- Not a safe import
ideclQualified = False,
ideclImplicit = True, -- Implicit!
ideclAs = Nothing,
ideclHiding = Nothing }
parseError :: DynFlags -> SrcSpan -> MsgDoc -> IO a
parseError dflags span err = throwOneError $ mkPlainErrMsg dflags span err
--------------------------------------------------------------
-- Get options
--------------------------------------------------------------
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptionsFromFile :: DynFlags
-> FilePath -- ^ Input file
-> IO [Located String] -- ^ Parsed options, if any.
getOptionsFromFile dflags filename
= Exception.bracket
(openBinaryFile filename ReadMode)
(hClose)
(\handle -> do
opts <- fmap (getOptions' dflags)
(lazyGetToks dflags' filename handle)
seqList opts $ return opts)
where -- We don't need to get haddock doc tokens when we're just
-- getting the options from pragmas, and lazily lexing them
-- correctly is a little tricky: If there is "\n" or "\n-"
-- left at the end of a buffer then the haddock doc may
-- continue past the end of the buffer, despite the fact that
-- we already have an apparently-complete token.
-- We therefore just turn Opt_Haddock off when doing the lazy
-- lex.
dflags' = gopt_unset dflags Opt_Haddock
blockSize :: Int
-- blockSize = 17 -- for testing :-)
blockSize = 1024
lazyGetToks :: DynFlags -> FilePath -> Handle -> IO [Located Token]
lazyGetToks dflags filename handle = do
buf <- hGetStringBufferBlock handle blockSize
unsafeInterleaveIO $ lazyLexBuf handle (pragState dflags buf loc) False blockSize
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lazyLexBuf :: Handle -> PState -> Bool -> Int -> IO [Located Token]
lazyLexBuf handle state eof size = do
case unP (lexer False return) state of
POk state' t -> do
-- pprTrace "lazyLexBuf" (text (show (buffer state'))) (return ())
if atEnd (buffer state') && not eof
-- if this token reached the end of the buffer, and we haven't
-- necessarily read up to the end of the file, then the token might
-- be truncated, so read some more of the file and lex it again.
then getMore handle state size
else case t of
L _ ITeof -> return [t]
_other -> do rest <- lazyLexBuf handle state' eof size
return (t : rest)
_ | not eof -> getMore handle state size
| otherwise -> return [L (RealSrcSpan (last_loc state)) ITeof]
-- parser assumes an ITeof sentinel at the end
getMore :: Handle -> PState -> Int -> IO [Located Token]
getMore handle state size = do
-- pprTrace "getMore" (text (show (buffer state))) (return ())
let new_size = size * 2
-- double the buffer size each time we read a new block. This
-- counteracts the quadratic slowdown we otherwise get for very
-- large module names (#5981)
nextbuf <- hGetStringBufferBlock handle new_size
if (len nextbuf == 0) then lazyLexBuf handle state True new_size else do
newbuf <- appendStringBuffers (buffer state) nextbuf
unsafeInterleaveIO $ lazyLexBuf handle state{buffer=newbuf} False new_size
getToks :: DynFlags -> FilePath -> StringBuffer -> [Located Token]
getToks dflags filename buf = lexAll (pragState dflags buf loc)
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lexAll state = case unP (lexer False return) state of
POk _ t@(L _ ITeof) -> [t]
POk state' t -> t : lexAll state'
_ -> [L (RealSrcSpan (last_loc state)) ITeof]
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptions :: DynFlags
-> StringBuffer -- ^ Input Buffer
-> FilePath -- ^ Source filename. Used for location info.
-> [Located String] -- ^ Parsed options.
getOptions dflags buf filename
= getOptions' dflags (getToks dflags filename buf)
-- The token parser is written manually because Happy can't
-- return a partial result when it encounters a lexer error.
-- We want to extract options before the buffer is passed through
-- CPP, so we can't use the same trick as 'getImports'.
getOptions' :: DynFlags
-> [Located Token] -- Input buffer
-> [Located String] -- Options.
getOptions' dflags toks
= parseToks toks
where
getToken (L _loc tok) = tok
getLoc (L loc _tok) = loc
parseToks (open:close:xs)
| IToptions_prag str <- getToken open
, ITclose_prag <- getToken close
= case toArgs str of
Left err -> panic ("getOptions'.parseToks: " ++ err)
Right args -> map (L (getLoc open)) args ++ parseToks xs
parseToks (open:close:xs)
| ITinclude_prag str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-#include",removeSpaces str] ++
parseToks xs
parseToks (open:close:xs)
| ITdocOptions str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
++ parseToks xs
parseToks (open:xs)
| ITlanguage_prag <- getToken open
= parseLanguage xs
parseToks (comment:xs) -- Skip over comments
| isComment (getToken comment)
= parseToks xs
parseToks _ = []
parseLanguage (L loc (ITconid fs):rest)
= checkExtension dflags (L loc fs) :
case rest of
(L _loc ITcomma):more -> parseLanguage more
(L _loc ITclose_prag):more -> parseToks more
(L loc _):_ -> languagePragParseError dflags loc
[] -> panic "getOptions'.parseLanguage(1) went past eof token"
parseLanguage (tok:_)
= languagePragParseError dflags (getLoc tok)
parseLanguage []
= panic "getOptions'.parseLanguage(2) went past eof token"
isComment :: Token -> Bool
isComment c =
case c of
(ITlineComment {}) -> True
(ITblockComment {}) -> True
(ITdocCommentNext {}) -> True
(ITdocCommentPrev {}) -> True
(ITdocCommentNamed {}) -> True
(ITdocSection {}) -> True
_ -> False
-----------------------------------------------------------------------------
-- | Complain about non-dynamic flags in OPTIONS pragmas.
--
-- Throws a 'SourceError' if the input list is non-empty claiming that the
-- input flags are unknown.
checkProcessArgsResult :: MonadIO m => DynFlags -> [Located String] -> m ()
checkProcessArgsResult dflags flags
= when (notNull flags) $
liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags
where mkMsg (L loc flag)
= mkPlainErrMsg dflags loc $
(text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+>
text flag)
-----------------------------------------------------------------------------
checkExtension :: DynFlags -> Located FastString -> Located String
checkExtension dflags (L l ext)
-- Checks if a given extension is valid, and if so returns
-- its corresponding flag. Otherwise it throws an exception.
= let ext' = unpackFS ext in
if ext' `elem` supportedLanguagesAndExtensions
then L l ("-X"++ext')
else unsupportedExtnError dflags l ext'
languagePragParseError :: DynFlags -> SrcSpan -> a
languagePragParseError dflags loc =
throw $ mkSrcErr $ unitBag $
(mkPlainErrMsg dflags loc $
vcat [ text "Cannot parse LANGUAGE pragma"
, text "Expecting comma-separated list of language options,"
, text "each starting with a capital letter"
, nest 2 (text "E.g. {-# LANGUAGE TemplateHaskell, GADTs #-}") ])
unsupportedExtnError :: DynFlags -> SrcSpan -> String -> a
unsupportedExtnError dflags loc unsup =
throw $ mkSrcErr $ unitBag $
mkPlainErrMsg dflags loc $
text "Unsupported extension: " <> text unsup $$
if null suggestions then Outputable.empty else text "Perhaps you meant" <+> quotedListWithOr (map text suggestions)
where
suggestions = fuzzyMatch unsup supportedLanguagesAndExtensions
optionsErrorMsgs :: DynFlags -> [String] -> [Located String] -> FilePath -> Messages
optionsErrorMsgs dflags unhandled_flags flags_lines _filename
= (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
L l f' <- flags_lines, f == f' ]
mkMsg (L flagSpan flag) =
ErrUtils.mkPlainErrMsg dflags flagSpan $
text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag
| snoyberg/ghc | compiler/main/HeaderInfo.hs | bsd-3-clause | 14,156 | 3 | 28 | 4,447 | 2,907 | 1,495 | 1,412 | 229 | 18 |
{-|
Module : IRTS.CodegenJavaScript
Description : The JavaScript code generator.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE OverloadedStrings, PatternGuards #-}
module IRTS.CodegenJavaScript (codegenJavaScript
, codegenNode
, JSTarget(..)
) where
import Idris.AbsSyntax hiding (TypeCase)
import Idris.Core.TT
import IRTS.Bytecode
import IRTS.CodegenCommon
import IRTS.Defunctionalise
import IRTS.Exports
import IRTS.JavaScript.AST
import IRTS.Lang
import IRTS.Simplified
import IRTS.System
import Util.System
import Control.Applicative (pure, (<$>), (<*>))
import Control.Arrow
import Control.Monad (mapM)
import Control.Monad.RWS hiding (mapM)
import Control.Monad.State
import Data.Char
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Traversable hiding (mapM)
import Data.Word
import Numeric
import System.Directory
import System.FilePath
import System.IO
data CompileInfo = CompileInfo { compileInfoApplyCases :: [Int]
, compileInfoEvalCases :: [Int]
, compileInfoNeedsBigInt :: Bool
}
initCompileInfo :: [(Name, [BC])] -> CompileInfo
initCompileInfo bc =
CompileInfo (collectCases "APPLY" bc) (collectCases "EVAL" bc) (lookupBigInt bc)
where
lookupBigInt :: [(Name, [BC])] -> Bool
lookupBigInt = any (needsBigInt . snd)
where
needsBigInt :: [BC] -> Bool
needsBigInt bc = any testBCForBigInt bc
where
testBCForBigInt :: BC -> Bool
testBCForBigInt (ASSIGNCONST _ c) =
testConstForBigInt c
testBCForBigInt (CONSTCASE _ c d) =
maybe False needsBigInt d
|| any (needsBigInt . snd) c
|| any (testConstForBigInt . fst) c
testBCForBigInt (CASE _ _ c d) =
maybe False needsBigInt d
|| any (needsBigInt . snd) c
testBCForBigInt _ = False
testConstForBigInt :: Const -> Bool
testConstForBigInt (BI _) = True
testConstForBigInt (B64 _) = True
testConstForBigInt _ = False
collectCases :: String -> [(Name, [BC])] -> [Int]
collectCases fun bc = getCases $ findFunction fun bc
findFunction :: String -> [(Name, [BC])] -> [BC]
findFunction f ((MN 0 fun, bc):_)
| fun == txt f = bc
findFunction f (_:bc) = findFunction f bc
getCases :: [BC] -> [Int]
getCases = concatMap analyze
where
analyze :: BC -> [Int]
analyze (CASE _ _ b _) = map fst b
analyze _ = []
data JSTarget = Node | JavaScript deriving Eq
codegenJavaScript :: CodeGenerator
codegenJavaScript ci =
codegenJS_all JavaScript (simpleDecls ci)
(includes ci) [] (outputFile ci) (exportDecls ci) (outputType ci)
codegenNode :: CodeGenerator
codegenNode ci =
codegenJS_all Node (simpleDecls ci)
(includes ci) (compileLibs ci) (outputFile ci) (exportDecls ci) (outputType ci)
codegenJS_all
:: JSTarget
-> [(Name, SDecl)]
-> [FilePath]
-> [String]
-> FilePath
-> [ExportIFace]
-> OutputType
-> IO ()
codegenJS_all target definitions includes libs filename exports outputType = do
let bytecode = map toBC definitions
let info = initCompileInfo bytecode
let js = concatMap (translateDecl info) bytecode
let full = concatMap processFunction js
let exportedNames = map translateName ((getExpNames exports) ++ [sUN "call__IO"])
let code = deadCodeElim exportedNames full
let ext = takeExtension filename
let isHtml = target == JavaScript && ext == ".html"
let htmlPrologue = T.pack "<!doctype html><html><head><script>\n"
let htmlEpilogue = T.pack "\n</script></head><body></body></html>"
let (cons, opt) = optimizeConstructors code
let (header, rt) = case target of
Node -> ("#!/usr/bin/env node\n", "-node")
JavaScript -> ("", "-browser")
included <- concat <$> getIncludes includes
path <- getIdrisJSRTSDir
idrRuntime <- readFile $ path </> "Runtime-common.js"
tgtRuntime <- readFile $ path </> concat ["Runtime", rt, ".js"]
jsbn <- if compileInfoNeedsBigInt info
then readFile $ path </> "jsbn/jsbn.js"
else return ""
let runtime = ( header
++ includeLibs libs
++ included
++ jsbn
++ idrRuntime
++ tgtRuntime
)
let jsSource = T.pack runtime
`T.append` T.concat (map compileJS opt)
`T.append` T.concat (map compileJS cons)
`T.append` T.concat (map compileJS (map genInterface (concatMap getExps exports)))
`T.append` main
`T.append` invokeMain
let source = if isHtml
then htmlPrologue `T.append` jsSource `T.append` htmlEpilogue
else jsSource
writeSourceText filename source
setPermissions filename (emptyPermissions { readable = True
, executable = target == Node
, writable = True
})
where
deadCodeElim :: [String] -> [JS] -> [JS]
deadCodeElim exports js = concatMap (collectFunctions exports) js
where
collectFunctions :: [String] -> JS -> [JS]
collectFunctions _ fun@(JSAlloc name _)
| name == translateName (sMN 0 "runMain") = [fun]
collectFunctions exports fun@(JSAlloc name _)
| name `elem` exports = [fun]
collectFunctions _ fun@(JSAlloc name (Just (JSFunction _ body))) =
let invokations = sum $ map (
\x -> execState (countInvokations name x) 0
) js
in if invokations == 0
then []
else [fun]
countInvokations :: String -> JS -> State Int ()
countInvokations name (JSAlloc _ (Just (JSFunction _ body))) =
countInvokations name body
countInvokations name (JSSeq seq) =
void $ traverse (countInvokations name) seq
countInvokations name (JSAssign _ rhs) =
countInvokations name rhs
countInvokations name (JSCond conds) =
void $ traverse (
runKleisli $ arr id *** Kleisli (countInvokations name)
) conds
countInvokations name (JSSwitch _ conds def) =
void $ traverse (
runKleisli $ arr id *** Kleisli (countInvokations name)
) conds >> traverse (countInvokations name) def
countInvokations name (JSApp lhs rhs) =
void $ countInvokations name lhs >> traverse (countInvokations name) rhs
countInvokations name (JSNew _ args) =
void $ traverse (countInvokations name) args
countInvokations name (JSArray args) =
void $ traverse (countInvokations name) args
countInvokations name (JSIdent name')
| name == name' = get >>= put . (+1)
| otherwise = return ()
countInvokations _ _ = return ()
processFunction :: JS -> [JS]
processFunction =
collectSplitFunctions . (\x -> evalRWS (splitFunction x) () 0)
includeLibs :: [String] -> String
includeLibs =
concatMap (\lib -> "var " ++ lib ++ " = require(\"" ++ lib ++"\");\n")
getIncludes :: [FilePath] -> IO [String]
getIncludes = mapM readFile
main :: T.Text
main =
compileJS $ JSAlloc "main" (Just $
JSFunction [] (
case target of
Node -> mainFun
JavaScript -> jsMain
)
)
jsMain :: JS
jsMain =
JSCond [ (exists document `jsAnd` isReady, mainFun)
, (exists window, windowMainFun)
, (JSTrue, mainFun)
]
where
exists :: JS -> JS
exists js = jsTypeOf js `jsNotEq` JSString "undefined"
window :: JS
window = JSIdent "window"
document :: JS
document = JSIdent "document"
windowMainFun :: JS
windowMainFun =
jsMeth window "addEventListener" [ JSString "DOMContentLoaded"
, JSFunction [] ( mainFun )
, JSFalse
]
isReady :: JS
isReady = JSParens $ readyState `jsEq` JSString "complete" `jsOr` readyState `jsEq` JSString "loaded"
readyState :: JS
readyState = JSProj (JSIdent "document") "readyState"
mainFun :: JS
mainFun =
JSSeq [ JSAlloc "vm" (Just $ JSNew "i$VM" [])
, JSApp (JSIdent "i$SCHED") [JSIdent "vm"]
, JSApp (
JSIdent (translateName (sMN 0 "runMain"))
) [JSNew "i$POINTER" [JSNum (JSInt 0)]]
, JSApp (JSIdent "i$RUN") []
]
invokeMain :: T.Text
invokeMain = compileJS $ JSApp (JSIdent "main") []
getExps (Export _ _ exp) = exp
optimizeConstructors :: [JS] -> ([JS], [JS])
optimizeConstructors js =
let (js', cons) = runState (traverse optimizeConstructor' js) M.empty in
(map (allocCon . snd) (M.toList cons), js')
where
allocCon :: (String, JS) -> JS
allocCon (name, con) = JSAlloc name (Just con)
newConstructor :: Int -> String
newConstructor n = "i$CON$" ++ show n
optimizeConstructor' :: JS -> State (M.Map Int (String, JS)) JS
optimizeConstructor' js@(JSNew "i$CON" [ JSNum (JSInt tag)
, JSArray []
, a
, e
]) = do
s <- get
case M.lookup tag s of
Just (i, c) -> return $ JSIdent i
Nothing -> do let n = newConstructor tag
put $ M.insert tag (n, js) s
return $ JSIdent n
optimizeConstructor' (JSSeq seq) =
JSSeq <$> traverse optimizeConstructor' seq
optimizeConstructor' (JSSwitch reg cond def) = do
cond' <- traverse (runKleisli $ arr id *** Kleisli optimizeConstructor') cond
def' <- traverse optimizeConstructor' def
return $ JSSwitch reg cond' def'
optimizeConstructor' (JSCond cond) =
JSCond <$> traverse (runKleisli $ arr id *** Kleisli optimizeConstructor') cond
optimizeConstructor' (JSAlloc fun (Just (JSFunction args body))) = do
body' <- optimizeConstructor' body
return $ JSAlloc fun (Just (JSFunction args body'))
optimizeConstructor' (JSAssign lhs rhs) = do
lhs' <- optimizeConstructor' lhs
rhs' <- optimizeConstructor' rhs
return $ JSAssign lhs' rhs'
optimizeConstructor' js = return js
collectSplitFunctions :: (JS, [(Int,JS)]) -> [JS]
collectSplitFunctions (fun, splits) = map generateSplitFunction splits ++ [fun]
where
generateSplitFunction :: (Int,JS) -> JS
generateSplitFunction (depth, JSAlloc name fun) =
JSAlloc (name ++ "$" ++ show depth) fun
splitFunction :: JS -> RWS () [(Int,JS)] Int JS
splitFunction (JSAlloc name (Just (JSFunction args body@(JSSeq _)))) = do
body' <- splitSequence body
return $ JSAlloc name (Just (JSFunction args body'))
where
splitCondition :: JS -> RWS () [(Int,JS)] Int JS
splitCondition js
| JSCond branches <- js =
JSCond <$> processBranches branches
| JSSwitch cond branches def <- js =
JSSwitch cond <$> (processBranches branches) <*> (traverse splitSequence def)
| otherwise = return js
where
processBranches :: [(JS,JS)] -> RWS () [(Int,JS)] Int [(JS,JS)]
processBranches =
traverse (runKleisli (arr id *** Kleisli splitSequence))
splitSequence :: JS -> RWS () [(Int, JS)] Int JS
splitSequence js@(JSSeq seq) =
let (pre,post) = break isBranch seq in
case post of
[_] -> JSSeq <$> traverse splitCondition seq
[call@(JSCond _),rest@(JSApp _ _)] -> do
rest' <- splitCondition rest
call' <- splitCondition call
return $ JSSeq (pre ++ [rest', call'])
[call@(JSSwitch _ _ _),rest@(JSApp _ _)] -> do
rest' <- splitCondition rest
call' <- splitCondition call
return $ JSSeq (pre ++ [rest', call'])
(call:rest) -> do
depth <- get
put (depth + 1)
new <- splitFunction (newFun rest)
tell [(depth, new)]
call' <- splitCondition call
return $ JSSeq (pre ++ (newCall depth : [call']))
_ -> JSSeq <$> traverse splitCondition seq
splitSequence js = return js
isBranch :: JS -> Bool
isBranch (JSApp (JSIdent "i$CALL") _) = True
isBranch (JSCond _) = True
isBranch (JSSwitch _ _ _) = True
isBranch _ = False
newCall :: Int -> JS
newCall depth =
JSApp (JSIdent "i$CALL") [ JSIdent $ name ++ "$" ++ show depth
, JSArray [jsOLDBASE, jsMYOLDBASE]
]
newFun :: [JS] -> JS
newFun seq =
JSAlloc name (Just $ JSFunction ["oldbase", "myoldbase"] (JSSeq seq))
splitFunction js = return js
translateDecl :: CompileInfo -> (Name, [BC]) -> [JS]
translateDecl info (name@(MN 0 fun), bc)
| txt "APPLY" == fun =
allocCaseFunctions (snd body)
++ [ JSAlloc (
translateName name
) (Just $ JSFunction ["oldbase"] (
JSSeq $ jsFUNPRELUDE ++ map (translateBC info) (fst body) ++ [
JSCond [ ( (translateReg $ caseReg (snd body)) `jsInstanceOf` "i$CON" `jsAnd` (JSProj (translateReg $ caseReg (snd body)) "app")
, JSApp (JSProj (translateReg $ caseReg (snd body)) "app") [jsOLDBASE, jsMYOLDBASE]
)
, ( JSNoop
, JSSeq $ map (translateBC info) (defaultCase (snd body))
)
]
]
)
)
]
| txt "EVAL" == fun =
allocCaseFunctions (snd body)
++ [ JSAlloc (
translateName name
) (Just $ JSFunction ["oldbase"] (
JSSeq $ jsFUNPRELUDE ++ map (translateBC info) (fst body) ++ [
JSCond [ ( (translateReg $ caseReg (snd body)) `jsInstanceOf` "i$CON" `jsAnd` (JSProj (translateReg $ caseReg (snd body)) "ev")
, JSApp (JSProj (translateReg $ caseReg (snd body)) "ev") [jsOLDBASE, jsMYOLDBASE]
)
, ( JSNoop
, JSSeq $ map (translateBC info) (defaultCase (snd body))
)
]
]
)
)
]
where
body :: ([BC], [BC])
body = break isCase bc
isCase :: BC -> Bool
isCase bc
| CASE {} <- bc = True
| otherwise = False
defaultCase :: [BC] -> [BC]
defaultCase ((CASE _ _ _ (Just d)):_) = d
caseReg :: [BC] -> Reg
caseReg ((CASE _ r _ _):_) = r
allocCaseFunctions :: [BC] -> [JS]
allocCaseFunctions ((CASE _ _ c _):_) = splitBranches c
allocCaseFunctions _ = []
splitBranches :: [(Int, [BC])] -> [JS]
splitBranches = map prepBranch
prepBranch :: (Int, [BC]) -> JS
prepBranch (tag, code) =
JSAlloc (
translateName name ++ "$" ++ show tag
) (Just $ JSFunction ["oldbase", "myoldbase"] (
JSSeq $ map (translateBC info) code
)
)
translateDecl info (name, bc) =
[ JSAlloc (
translateName name
) (Just $ JSFunction ["oldbase"] (
JSSeq $ jsFUNPRELUDE ++ map (translateBC info)bc
)
)
]
jsFUNPRELUDE :: [JS]
jsFUNPRELUDE = [jsALLOCMYOLDBASE]
jsALLOCMYOLDBASE :: JS
jsALLOCMYOLDBASE = JSAlloc "myoldbase" (Just $ JSNew "i$POINTER" [])
translateReg :: Reg -> JS
translateReg reg
| RVal <- reg = jsRET
| Tmp <- reg = JSRaw "//TMPREG"
| L n <- reg = jsLOC n
| T n <- reg = jsTOP n
translateConstant :: Const -> JS
translateConstant (I i) = JSNum (JSInt i)
translateConstant (Fl f) = JSNum (JSFloat f)
translateConstant (Ch c) = JSString $ translateChar c
translateConstant (Str s) = JSString $ concatMap translateChar s
translateConstant (AType (ATInt ITNative)) = JSType JSIntTy
translateConstant StrType = JSType JSStringTy
translateConstant (AType (ATInt ITBig)) = JSType JSIntegerTy
translateConstant (AType ATFloat) = JSType JSFloatTy
translateConstant (AType (ATInt ITChar)) = JSType JSCharTy
translateConstant Forgot = JSType JSForgotTy
translateConstant (BI 0) = JSNum (JSInteger JSBigZero)
translateConstant (BI 1) = JSNum (JSInteger JSBigOne)
translateConstant (BI i) = jsBigInt (JSString $ show i)
translateConstant (B8 b) = JSWord (JSWord8 b)
translateConstant (B16 b) = JSWord (JSWord16 b)
translateConstant (B32 b) = JSWord (JSWord32 b)
translateConstant (B64 b) = JSWord (JSWord64 b)
translateConstant c =
JSError $ "Unimplemented Constant: " ++ show c
translateChar :: Char -> String
translateChar ch
| '\a' <- ch = "\\u0007"
| '\b' <- ch = "\\b"
| '\f' <- ch = "\\f"
| '\n' <- ch = "\\n"
| '\r' <- ch = "\\r"
| '\t' <- ch = "\\t"
| '\v' <- ch = "\\v"
| '\SO' <- ch = "\\u000E"
| '\DEL' <- ch = "\\u007F"
| '\\' <- ch = "\\\\"
| '\"' <- ch = "\\\""
| '\'' <- ch = "\\\'"
| ch `elem` asciiTab = "\\u" ++ fill (showHex (ord ch) "")
| ord ch > 255 = "\\u" ++ fill (showHex (ord ch) "")
| otherwise = [ch]
where
fill :: String -> String
fill s = case length s of
1 -> "000" ++ s
2 -> "00" ++ s
3 -> "0" ++ s
_ -> s
asciiTab =
['\NUL', '\SOH', '\STX', '\ETX', '\EOT', '\ENQ', '\ACK', '\BEL',
'\BS', '\HT', '\LF', '\VT', '\FF', '\CR', '\SO', '\SI',
'\DLE', '\DC1', '\DC2', '\DC3', '\DC4', '\NAK', '\SYN', '\ETB',
'\CAN', '\EM', '\SUB', '\ESC', '\FS', '\GS', '\RS', '\US']
translateName :: Name -> String
translateName n = "_idris_" ++ concatMap cchar (showCG n)
where cchar x | isAlphaNum x = [x]
| otherwise = "_" ++ show (fromEnum x) ++ "_"
jsASSIGN :: CompileInfo -> Reg -> Reg -> JS
jsASSIGN _ r1 r2 = JSAssign (translateReg r1) (translateReg r2)
jsASSIGNCONST :: CompileInfo -> Reg -> Const -> JS
jsASSIGNCONST _ r c = JSAssign (translateReg r) (translateConstant c)
jsCALL :: CompileInfo -> Name -> JS
jsCALL _ n =
JSApp (
JSIdent "i$CALL"
) [JSIdent (translateName n), JSArray [jsMYOLDBASE]]
jsTAILCALL :: CompileInfo -> Name -> JS
jsTAILCALL _ n =
JSApp (
JSIdent "i$CALL"
) [JSIdent (translateName n), JSArray [jsOLDBASE]]
jsFOREIGN :: CompileInfo -> Reg -> String -> [(FType, Reg)] -> JS
jsFOREIGN _ reg n args
| n == "isNull"
, [(FPtr, arg)] <- args =
JSAssign (
translateReg reg
) (
JSBinOp "==" (translateReg arg) JSNull
)
| n == "idris_eqPtr"
, [(_, lhs),(_, rhs)] <- args =
JSAssign (
translateReg reg
) (
JSBinOp "==" (translateReg lhs) (translateReg rhs)
)
| otherwise =
JSAssign (
translateReg reg
) (
JSFFI n (map generateWrapper args)
)
where
generateWrapper :: (FType, Reg) -> JS
generateWrapper (ty, reg)
| FFunction <- ty =
JSApp (JSIdent "i$ffiWrap") [ translateReg reg
, JSIdent "oldbase"
, JSIdent "myoldbase"
]
| FFunctionIO <- ty =
JSApp (JSIdent "i$ffiWrap") [ translateReg reg
, JSIdent "oldbase"
, JSIdent "myoldbase"
]
generateWrapper (_, reg) =
translateReg reg
jsREBASE :: CompileInfo -> JS
jsREBASE _ = JSAssign jsSTACKBASE (JSProj jsOLDBASE "addr")
jsSTOREOLD :: CompileInfo ->JS
jsSTOREOLD _ = JSAssign (JSProj jsMYOLDBASE "addr") jsSTACKBASE
jsADDTOP :: CompileInfo -> Int -> JS
jsADDTOP info n
| 0 <- n = JSNoop
| otherwise =
JSBinOp "+=" jsSTACKTOP (JSNum (JSInt n))
jsTOPBASE :: CompileInfo -> Int -> JS
jsTOPBASE _ 0 = JSAssign jsSTACKTOP jsSTACKBASE
jsTOPBASE _ n = JSAssign jsSTACKTOP (JSBinOp "+" jsSTACKBASE (JSNum (JSInt n)))
jsBASETOP :: CompileInfo -> Int -> JS
jsBASETOP _ 0 = JSAssign jsSTACKBASE jsSTACKTOP
jsBASETOP _ n = JSAssign jsSTACKBASE (JSBinOp "+" jsSTACKTOP (JSNum (JSInt n)))
jsNULL :: CompileInfo -> Reg -> JS
jsNULL _ r = JSClear (translateReg r)
jsERROR :: CompileInfo -> String -> JS
jsERROR _ = JSError
jsSLIDE :: CompileInfo -> Int -> JS
jsSLIDE _ 1 = JSAssign (jsLOC 0) (jsTOP 0)
jsSLIDE _ n = JSApp (JSIdent "i$SLIDE") [JSNum (JSInt n)]
jsMKCON :: CompileInfo -> Reg -> Int -> [Reg] -> JS
jsMKCON info r t rs =
JSAssign (translateReg r) (
JSNew "i$CON" [ JSNum (JSInt t)
, JSArray (map translateReg rs)
, if t `elem` compileInfoApplyCases info
then JSIdent $ translateName (sMN 0 "APPLY") ++ "$" ++ show t
else JSNull
, if t `elem` compileInfoEvalCases info
then JSIdent $ translateName (sMN 0 "EVAL") ++ "$" ++ show t
else JSNull
]
)
jsCASE :: CompileInfo -> Bool -> Reg -> [(Int, [BC])] -> Maybe [BC] -> JS
jsCASE info safe reg cases def =
JSSwitch (tag safe $ translateReg reg) (
map ((JSNum . JSInt) *** prepBranch) cases
) (fmap prepBranch def)
where
tag :: Bool -> JS -> JS
tag True = jsCTAG
tag False = jsTAG
prepBranch :: [BC] -> JS
prepBranch bc = JSSeq $ map (translateBC info) bc
jsTAG :: JS -> JS
jsTAG js =
(JSTernary (js `jsInstanceOf` "i$CON") (
JSProj js "tag"
) (JSNum (JSInt $ negate 1)))
jsCTAG :: JS -> JS
jsCTAG js = JSProj js "tag"
jsCONSTCASE :: CompileInfo -> Reg -> [(Const, [BC])] -> Maybe [BC] -> JS
jsCONSTCASE info reg cases def =
JSCond $ (
map (jsEq (translateReg reg) . translateConstant *** prepBranch) cases
) ++ (maybe [] ((:[]) . ((,) JSNoop) . prepBranch) def)
where
prepBranch :: [BC] -> JS
prepBranch bc = JSSeq $ map (translateBC info) bc
jsPROJECT :: CompileInfo -> Reg -> Int -> Int -> JS
jsPROJECT _ reg loc 0 = JSNoop
jsPROJECT _ reg loc 1 =
JSAssign (jsLOC loc) (
JSIndex (
JSProj (translateReg reg) "args"
) (
JSNum (JSInt 0)
)
)
jsPROJECT _ reg loc ar =
JSApp (JSIdent "i$PROJECT") [ translateReg reg
, JSNum (JSInt loc)
, JSNum (JSInt ar)
]
jsOP :: CompileInfo -> Reg -> PrimFn -> [Reg] -> JS
jsOP _ reg op args = JSAssign (translateReg reg) jsOP'
where
jsOP' :: JS
jsOP'
| LNoOp <- op = translateReg (last args)
| LWriteStr <- op,
(_:str:_) <- args = JSApp (JSIdent "i$putStr") [translateReg str]
| LReadStr <- op = JSApp (JSIdent "i$getLine") []
| (LZExt (ITFixed IT8) ITNative) <- op = jsUnPackBits $ translateReg (last args)
| (LZExt (ITFixed IT16) ITNative) <- op = jsUnPackBits $ translateReg (last args)
| (LZExt (ITFixed IT32) ITNative) <- op = jsUnPackBits $ translateReg (last args)
| (LZExt _ ITBig) <- op = jsBigInt $ JSApp (JSIdent "String") [translateReg (last args)]
| (LPlus (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "add" [rhs]
| (LMinus (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "subtract" [rhs]
| (LTimes (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "multiply" [rhs]
| (LSDiv (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "divide" [rhs]
| (LSRem (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "mod" [rhs]
| (LEq (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "equals" [rhs]
| (LSLt (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "lesser" [rhs]
| (LSLe (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "lesserOrEquals" [rhs]
| (LSGt (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "greater" [rhs]
| (LSGe (ATInt ITBig)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "greaterOrEquals" [rhs]
| (LPlus ATFloat) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "+" lhs rhs
| (LMinus ATFloat) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "-" lhs rhs
| (LTimes ATFloat) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "*" lhs rhs
| (LSDiv ATFloat) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "/" lhs rhs
| (LEq ATFloat) <- op
, (lhs:rhs:_) <- args = translateCompareOp "==" lhs rhs
| (LSLt ATFloat) <- op
, (lhs:rhs:_) <- args = translateCompareOp "<" lhs rhs
| (LSLe ATFloat) <- op
, (lhs:rhs:_) <- args = translateCompareOp "<=" lhs rhs
| (LSGt ATFloat) <- op
, (lhs:rhs:_) <- args = translateCompareOp ">" lhs rhs
| (LSGe ATFloat) <- op
, (lhs:rhs:_) <- args = translateCompareOp ">=" lhs rhs
| (LPlus (ATInt ITChar)) <- op
, (lhs:rhs:_) <- args =
jsCall "i$fromCharCode" [
JSBinOp "+" (
jsCall "i$charCode" [translateReg lhs]
) (
jsCall "i$charCode" [translateReg rhs]
)
]
| (LTrunc (ITFixed IT16) (ITFixed IT8)) <- op
, (arg:_) <- args =
jsPackUBits8 (
JSBinOp "&" (jsUnPackBits $ translateReg arg) (JSNum (JSInt 0xFF))
)
| (LTrunc (ITFixed IT32) (ITFixed IT16)) <- op
, (arg:_) <- args =
jsPackUBits16 (
JSBinOp "&" (jsUnPackBits $ translateReg arg) (JSNum (JSInt 0xFFFF))
)
| (LTrunc (ITFixed IT64) (ITFixed IT32)) <- op
, (arg:_) <- args =
jsPackUBits32 (
jsMeth (jsMeth (translateReg arg) "and" [
jsBigInt (JSString $ show 0xFFFFFFFF)
]) "intValue" []
)
| (LTrunc ITBig (ITFixed IT64)) <- op
, (arg:_) <- args =
jsMeth (translateReg arg) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LLSHR (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp ">>" lhs rhs
| (LLSHR (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp ">>" lhs rhs
| (LLSHR (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp ">>" lhs rhs
| (LLSHR (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args =
jsMeth (translateReg lhs) "shiftRight" [translateReg rhs]
| (LSHL (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "<<" lhs rhs
| (LSHL (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "<<" lhs rhs
| (LSHL (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "<<" lhs rhs
| (LSHL (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args =
jsMeth (jsMeth (translateReg lhs) "shiftLeft" [translateReg rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LAnd (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "&" lhs rhs
| (LAnd (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "&" lhs rhs
| (LAnd (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "&" lhs rhs
| (LAnd (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args =
jsMeth (translateReg lhs) "and" [translateReg rhs]
| (LOr (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "|" lhs rhs
| (LOr (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "|" lhs rhs
| (LOr (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "|" lhs rhs
| (LOr (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args =
jsMeth (translateReg lhs) "or" [translateReg rhs]
| (LXOr (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "^" lhs rhs
| (LXOr (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "^" lhs rhs
| (LXOr (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "^" lhs rhs
| (LXOr (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args =
jsMeth (translateReg lhs) "xor" [translateReg rhs]
| (LPlus (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "+" lhs rhs
| (LPlus (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "+" lhs rhs
| (LPlus (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "+" lhs rhs
| (LPlus (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args =
jsMeth (jsMeth (translateReg lhs) "add" [translateReg rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LMinus (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "-" lhs rhs
| (LMinus (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "-" lhs rhs
| (LMinus (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "-" lhs rhs
| (LMinus (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args =
jsMeth (jsMeth (translateReg lhs) "subtract" [translateReg rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LTimes (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args = jsPackUBits8 $ bitsBinaryOp "*" lhs rhs
| (LTimes (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args = jsPackUBits16 $ bitsBinaryOp "*" lhs rhs
| (LTimes (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args = jsPackUBits32 $ bitsBinaryOp "*" lhs rhs
| (LTimes (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args =
jsMeth (jsMeth (translateReg lhs) "multiply" [translateReg rhs]) "and" [
jsBigInt (JSString $ show 0xFFFFFFFFFFFFFFFF)
]
| (LEq (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "==" lhs rhs
| (LEq (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "==" lhs rhs
| (LEq (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "==" lhs rhs
| (LEq (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "equals" [rhs]
| (LLt (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<" lhs rhs
| (LLt (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<" lhs rhs
| (LLt (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<" lhs rhs
| (LLt (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "lesser" [rhs]
| (LLe (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<=" lhs rhs
| (LLe (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<=" lhs rhs
| (LLe (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp "<=" lhs rhs
| (LLe (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "lesserOrEquals" [rhs]
| (LGt (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">" lhs rhs
| (LGt (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">" lhs rhs
| (LGt (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">" lhs rhs
| (LGt (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "greater" [rhs]
| (LGe (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">=" lhs rhs
| (LGe (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">=" lhs rhs
| (LGe (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args = bitsCompareOp ">=" lhs rhs
| (LGe (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args = JSPreOp "+" $ invokeMeth lhs "greaterOrEquals" [rhs]
| (LUDiv (ITFixed IT8)) <- op
, (lhs:rhs:_) <- args =
jsPackUBits8 (
JSBinOp "/" (jsUnPackBits (translateReg lhs)) (jsUnPackBits (translateReg rhs))
)
| (LUDiv (ITFixed IT16)) <- op
, (lhs:rhs:_) <- args =
jsPackUBits16 (
JSBinOp "/" (jsUnPackBits (translateReg lhs)) (jsUnPackBits (translateReg rhs))
)
| (LUDiv (ITFixed IT32)) <- op
, (lhs:rhs:_) <- args =
jsPackUBits32 (
JSBinOp "/" (jsUnPackBits (translateReg lhs)) (jsUnPackBits (translateReg rhs))
)
| (LUDiv (ITFixed IT64)) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "divide" [rhs]
| (LSDiv (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits8 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (translateReg rhs)
)
)
| (LSDiv (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits16 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (translateReg rhs)
)
)
| (LSDiv (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits32 (
JSBinOp "/" (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (translateReg rhs)
)
)
| (LSDiv (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "divide" [rhs]
| (LSRem (ATInt (ITFixed IT8))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits8 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits8 $ jsUnPackBits (translateReg rhs)
)
)
| (LSRem (ATInt (ITFixed IT16))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits16 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits16 $ jsUnPackBits (translateReg rhs)
)
)
| (LSRem (ATInt (ITFixed IT32))) <- op
, (lhs:rhs:_) <- args =
jsPackSBits32 (
JSBinOp "%" (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (translateReg lhs)
) (
jsUnPackBits $ jsPackSBits32 $ jsUnPackBits (translateReg rhs)
)
)
| (LSRem (ATInt (ITFixed IT64))) <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "mod" [rhs]
| (LCompl (ITFixed IT8)) <- op
, (arg:_) <- args =
jsPackSBits8 $ JSPreOp "~" $ jsUnPackBits (translateReg arg)
| (LCompl (ITFixed IT16)) <- op
, (arg:_) <- args =
jsPackSBits16 $ JSPreOp "~" $ jsUnPackBits (translateReg arg)
| (LCompl (ITFixed IT32)) <- op
, (arg:_) <- args =
jsPackSBits32 $ JSPreOp "~" $ jsUnPackBits (translateReg arg)
| (LCompl (ITFixed IT64)) <- op
, (arg:_) <- args = invokeMeth arg "not" []
| (LPlus _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "+" lhs rhs
| (LMinus _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "-" lhs rhs
| (LTimes _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "*" lhs rhs
| (LSDiv _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "/" lhs rhs
| (LSRem _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "%" lhs rhs
| (LEq _) <- op
, (lhs:rhs:_) <- args = translateCompareOp "==" lhs rhs
| (LSLt _) <- op
, (lhs:rhs:_) <- args = translateCompareOp "<" lhs rhs
| (LSLe _) <- op
, (lhs:rhs:_) <- args = translateCompareOp "<=" lhs rhs
| (LSGt _) <- op
, (lhs:rhs:_) <- args = translateCompareOp ">" lhs rhs
| (LSGe _) <- op
, (lhs:rhs:_) <- args = translateCompareOp ">=" lhs rhs
| (LAnd _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "&" lhs rhs
| (LOr _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "|" lhs rhs
| (LXOr _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "^" lhs rhs
| (LSHL _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp "<<" rhs lhs
| (LASHR _) <- op
, (lhs:rhs:_) <- args = translateBinaryOp ">>" rhs lhs
| (LCompl _) <- op
, (arg:_) <- args = JSPreOp "~" (translateReg arg)
| LStrConcat <- op
, (lhs:rhs:_) <- args = translateBinaryOp "+" lhs rhs
| LStrEq <- op
, (lhs:rhs:_) <- args = translateCompareOp "==" lhs rhs
| LStrLt <- op
, (lhs:rhs:_) <- args = translateCompareOp "<" lhs rhs
| LStrLen <- op
, (arg:_) <- args = JSProj (translateReg arg) "length"
| (LStrInt ITNative) <- op
, (arg:_) <- args = jsCall "parseInt" [translateReg arg]
| (LIntStr ITNative) <- op
, (arg:_) <- args = jsCall "String" [translateReg arg]
| (LSExt ITNative ITBig) <- op
, (arg:_) <- args = jsBigInt $ jsCall "String" [translateReg arg]
| (LTrunc ITBig ITNative) <- op
, (arg:_) <- args = jsMeth (translateReg arg) "intValue" []
| (LIntStr ITBig) <- op
, (arg:_) <- args = jsMeth (translateReg arg) "toString" []
| (LStrInt ITBig) <- op
, (arg:_) <- args = jsBigInt $ translateReg arg
| LFloatStr <- op
, (arg:_) <- args = jsCall "String" [translateReg arg]
| LStrFloat <- op
, (arg:_) <- args = jsCall "parseFloat" [translateReg arg]
| (LIntFloat ITNative) <- op
, (arg:_) <- args = translateReg arg
| (LIntFloat ITBig) <- op
, (arg:_) <- args = jsMeth (translateReg arg) "intValue" []
| (LFloatInt ITNative) <- op
, (arg:_) <- args = translateReg arg
| (LChInt ITNative) <- op
, (arg:_) <- args = jsCall "i$charCode" [translateReg arg]
| (LIntCh ITNative) <- op
, (arg:_) <- args = jsCall "i$fromCharCode" [translateReg arg]
| LFExp <- op
, (arg:_) <- args = jsCall "Math.exp" [translateReg arg]
| LFLog <- op
, (arg:_) <- args = jsCall "Math.log" [translateReg arg]
| LFSin <- op
, (arg:_) <- args = jsCall "Math.sin" [translateReg arg]
| LFCos <- op
, (arg:_) <- args = jsCall "Math.cos" [translateReg arg]
| LFTan <- op
, (arg:_) <- args = jsCall "Math.tan" [translateReg arg]
| LFASin <- op
, (arg:_) <- args = jsCall "Math.asin" [translateReg arg]
| LFACos <- op
, (arg:_) <- args = jsCall "Math.acos" [translateReg arg]
| LFATan <- op
, (arg:_) <- args = jsCall "Math.atan" [translateReg arg]
| LFSqrt <- op
, (arg:_) <- args = jsCall "Math.sqrt" [translateReg arg]
| LFFloor <- op
, (arg:_) <- args = jsCall "Math.floor" [translateReg arg]
| LFCeil <- op
, (arg:_) <- args = jsCall "Math.ceil" [translateReg arg]
| LFNegate <- op
, (arg:_) <- args = JSPreOp "-" (translateReg arg)
| LStrCons <- op
, (lhs:rhs:_) <- args = invokeMeth lhs "concat" [rhs]
| LStrHead <- op
, (arg:_) <- args = JSIndex (translateReg arg) (JSNum (JSInt 0))
| LStrRev <- op
, (arg:_) <- args = JSProj (translateReg arg) "split('').reverse().join('')"
| LStrIndex <- op
, (lhs:rhs:_) <- args = JSIndex (translateReg lhs) (translateReg rhs)
| LStrTail <- op
, (arg:_) <- args =
let v = translateReg arg in
JSApp (JSProj v "substr") [
JSNum (JSInt 1),
JSBinOp "-" (JSProj v "length") (JSNum (JSInt 1))
]
| LStrSubstr <- op
, (offset:length:string:_) <- args =
let off = translateReg offset
len = translateReg length
str = translateReg string
in JSApp (JSProj str "substr") [
jsCall "Math.max" [JSNum (JSInt 0), off],
jsCall "Math.max" [JSNum (JSInt 0), len]
]
| LSystemInfo <- op
, (arg:_) <- args = jsCall "i$systemInfo" [translateReg arg]
| LExternal nul <- op
, nul == sUN "prim__null"
, _ <- args = JSNull
| LExternal ex <- op
, ex == sUN "prim__eqPtr"
, [lhs, rhs] <- args = translateCompareOp "==" lhs rhs
| otherwise = JSError $ "Not implemented: " ++ show op
where
translateBinaryOp :: String -> Reg -> Reg -> JS
translateBinaryOp op lhs rhs =
JSBinOp op (translateReg lhs) (translateReg rhs)
translateCompareOp :: String -> Reg -> Reg -> JS
translateCompareOp op lhs rhs =
JSPreOp "+" $ translateBinaryOp op lhs rhs
bitsBinaryOp :: String -> Reg -> Reg -> JS
bitsBinaryOp op lhs rhs =
JSBinOp op (jsUnPackBits (translateReg lhs)) (jsUnPackBits (translateReg rhs))
bitsCompareOp :: String -> Reg -> Reg -> JS
bitsCompareOp op lhs rhs =
JSPreOp "+" $ bitsBinaryOp op lhs rhs
invokeMeth :: Reg -> String -> [Reg] -> JS
invokeMeth obj meth args =
JSApp (JSProj (translateReg obj) meth) $ map translateReg args
jsRESERVE :: CompileInfo -> Int -> JS
jsRESERVE _ _ = JSNoop
jsSTACK :: JS
jsSTACK = JSIdent "i$valstack"
jsCALLSTACK :: JS
jsCALLSTACK = JSIdent "i$callstack"
jsSTACKBASE :: JS
jsSTACKBASE = JSIdent "i$valstack_base"
jsSTACKTOP :: JS
jsSTACKTOP = JSIdent "i$valstack_top"
jsOLDBASE :: JS
jsOLDBASE = JSIdent "oldbase"
jsMYOLDBASE :: JS
jsMYOLDBASE = JSIdent "myoldbase"
jsRET :: JS
jsRET = JSIdent "i$ret"
jsLOC :: Int -> JS
jsLOC 0 = JSIndex jsSTACK jsSTACKBASE
jsLOC n = JSIndex jsSTACK (JSBinOp "+" jsSTACKBASE (JSNum (JSInt n)))
jsTOP :: Int -> JS
jsTOP 0 = JSIndex jsSTACK jsSTACKTOP
jsTOP n = JSIndex jsSTACK (JSBinOp "+" jsSTACKTOP (JSNum (JSInt n)))
jsPUSH :: [JS] -> JS
jsPUSH args = JSApp (JSProj jsCALLSTACK "push") args
jsPOP :: JS
jsPOP = JSApp (JSProj jsCALLSTACK "pop") []
genInterface :: Export -> JS
genInterface (ExportData name) = JSNoop
genInterface (ExportFun name (FStr jsName) ret args) = JSAlloc jsName
(Just (JSFunction [] (JSSeq $
jsFUNPRELUDE ++
pushArgs nargs ++
[jsSTOREOLD d,
jsBASETOP d 0,
jsADDTOP d nargs,
jsCALL d name] ++
retval ret)))
where
nargs = length args
d = CompileInfo [] [] False
pushArg n = JSAssign (jsTOP n) (JSIndex (JSIdent "arguments") (JSNum (JSInt n)))
pushArgs 0 = []
pushArgs n = (pushArg (n-1)):pushArgs (n-1)
retval (FIO t) = [JSApp (JSIdent "i$RUN") [],
JSAssign (jsTOP 0) JSNull,
JSAssign (jsTOP 1) JSNull,
JSAssign (jsTOP 2) (translateReg RVal),
jsSTOREOLD d,
jsBASETOP d 0,
jsADDTOP d 3,
jsCALL d (sUN "call__IO")] ++ retval t
retval t = [JSApp (JSIdent "i$RUN") [], JSReturn (translateReg RVal)]
translateBC :: CompileInfo -> BC -> JS
translateBC info bc
| ASSIGN r1 r2 <- bc = jsASSIGN info r1 r2
| ASSIGNCONST r c <- bc = jsASSIGNCONST info r c
| UPDATE r1 r2 <- bc = jsASSIGN info r1 r2
| ADDTOP n <- bc = jsADDTOP info n
| NULL r <- bc = jsNULL info r
| CALL n <- bc = jsCALL info n
| TAILCALL n <- bc = jsTAILCALL info n
| FOREIGNCALL r _ (FStr n) args
<- bc = jsFOREIGN info r n (map fcall args)
| FOREIGNCALL _ _ _ _ <- bc = error "JS FFI call not statically known"
| TOPBASE n <- bc = jsTOPBASE info n
| BASETOP n <- bc = jsBASETOP info n
| STOREOLD <- bc = jsSTOREOLD info
| SLIDE n <- bc = jsSLIDE info n
| REBASE <- bc = jsREBASE info
| RESERVE n <- bc = jsRESERVE info n
| MKCON r _ t rs <- bc = jsMKCON info r t rs
| CASE s r c d <- bc = jsCASE info s r c d
| CONSTCASE r c d <- bc = jsCONSTCASE info r c d
| PROJECT r l a <- bc = jsPROJECT info r l a
| OP r o a <- bc = jsOP info r o a
| ERROR e <- bc = jsERROR info e
| otherwise = JSRaw $ "//" ++ show bc
where fcall (t, arg) = (toFType t, arg)
toAType (FCon i)
| i == sUN "JS_IntChar" = ATInt ITChar
| i == sUN "JS_IntNative" = ATInt ITNative
toAType t = error (show t ++ " not defined in toAType")
toFnType (FApp c [_,_,s,t])
| c == sUN "JS_Fn" = toFnType t
toFnType (FApp c [_,_,r])
| c == sUN "JS_FnIO" = FFunctionIO
toFnType (FApp c [_,r])
| c == sUN "JS_FnBase" = FFunction
toFnType t = error (show t ++ " not defined in toFnType")
toFType (FCon c)
| c == sUN "JS_Str" = FString
| c == sUN "JS_Float" = FArith ATFloat
| c == sUN "JS_Ptr" = FPtr
| c == sUN "JS_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "JS_IntT" = FArith (toAType ity)
toFType (FApp c [_,fty])
| c == sUN "JS_FnT" = toFnType fty
toFType t = error (show t ++ " not yet defined in toFType")
| ben-schulz/Idris-dev | src/IRTS/CodegenJavaScript.hs | bsd-3-clause | 48,846 | 0 | 25 | 17,584 | 18,283 | 9,128 | 9,155 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ja-JP">
<title>SAML Support</title>
<maps>
<homeID>saml</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/saml/src/main/javahelp/help_ja_JP/helpset_ja_JP.hs | apache-2.0 | 958 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-|
Module : Idris.Chaser
Description : Module chaser to determine cycles and import modules.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE FlexibleContexts #-}
module Idris.Chaser(
buildTree, getImports
, getModuleFiles
, ModuleTree(..)
) where
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Error
import Idris.Imports
import Idris.Parser
import Idris.Unlit
import Control.Monad.State
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Time.Clock
import System.Directory
import Util.System (readSource)
data ModuleTree = MTree { mod_path :: IFileType,
mod_needsRecheck :: Bool,
mod_time :: UTCTime,
mod_deps :: [ModuleTree] }
deriving Show
latest :: UTCTime -> [IFileType] -> [ModuleTree] -> UTCTime
latest tm done [] = tm
latest tm done (m : ms)
| mod_path m `elem` done = latest tm done ms
| otherwise = latest (max tm (mod_time m)) (mod_path m : done) ms
modName :: IFileType -> String
modName (IDR fp) = fp
modName (LIDR fp) = fp
modName (IBC fp src) = modName src
-- | Given a module tree, return the list of files to be loaded. If
-- any module has a descendent which needs reloading, return its
-- source, otherwise return the IBC
getModuleFiles :: [ModuleTree] -> [IFileType]
getModuleFiles ts
= let (files, (rebuild, _)) = runState (modList ts) (S.empty, M.empty) in
updateToSrc rebuild (reverse files)
where
-- Get the order of building modules. As we go we'll find things that
-- need rebuilding, which we keep track of in the Set.
-- The order of the list matters - things which get built first appear
-- in the list first. We'll remove any repetition later.
modList :: [ModuleTree] ->
State (S.Set IFileType,
M.Map IFileType (Bool, [IFileType])) [IFileType]
modList [] = return []
modList (m : ms) = do (_, fs) <- modTree S.empty m
fs' <- modList ms
pure (fs ++ fs')
modTree path m@(MTree p rechk tm deps)
= do let file = chkReload rechk p
(rebuild, res) <- get
case M.lookup file res of
Just ms -> pure ms
Nothing -> do
toBuildsAll <- mapM (modTree (S.insert (getSrc p) path)) deps
let (rechkDep_in, toBuilds) = unzip toBuildsAll
let rechkDep = or rechkDep_in
(rebuild, res) <- get
-- Needs rechecking if 'rechk' is true, or if any of the
-- modification times in 'deps' are later than tm, or
-- if any dependency needed rechecking
let depMod = latest tm [] deps
let needsRechk = rechkDep || rechk || depMod > tm
-- Remove duplicates, but keep the last...
let rnub = reverse . nub . reverse
let ret = if needsRechk
then (needsRechk, rnub (getSrc file : concat toBuilds))
else (needsRechk, rnub (file : concat toBuilds))
-- Cache the result
put (if needsRechk
then S.union path rebuild
else rebuild, M.insert file ret res)
pure ret
chkReload False p = p
chkReload True (IBC fn src) = chkReload True src
chkReload True p = p
getSrc (IBC fn src) = getSrc src
getSrc f = f
updateToSrc rebuilds [] = []
updateToSrc rebuilds (x : xs)
= if getSrc x `S.member` rebuilds
then getSrc x : updateToSrc rebuilds xs
else x : updateToSrc rebuilds xs
-- | Strip quotes and the backslash escapes that Haskeline adds
extractFileName :: String -> String
extractFileName ('"':xs) = takeWhile (/= '"') xs
extractFileName ('\'':xs) = takeWhile (/= '\'') xs
extractFileName x = build x []
where
build [] acc = reverse $ dropWhile (== ' ') acc
build ('\\':' ':xs) acc = build xs (' ':acc)
build (x:xs) acc = build xs (x:acc)
getIModTime (IBC i _) = getModificationTime i
getIModTime (IDR i) = getModificationTime i
getIModTime (LIDR i) = getModificationTime i
getImports :: [(FilePath, [ImportInfo])]
-> [FilePath]
-> Idris [(FilePath, [ImportInfo])]
getImports acc [] = return acc
getImports acc (f : fs) = do
i <- getIState
let file = extractFileName f
ibcsd <- valIBCSubDir i
idrisCatch (do
srcds <- allSourceDirs
fp <- findImport srcds ibcsd file
let parsef = fname fp
case lookup parsef acc of
Just _ -> getImports acc fs
_ -> do
exist <- runIO $ doesFileExist parsef
if exist then do
src_in <- runIO $ readSource parsef
src <- if lit fp then tclift $ unlit parsef src_in
else return src_in
(_, _, modules, _) <- parseImports parsef src
clearParserWarnings
getImports ((parsef, modules) : acc)
(fs ++ map import_path modules)
else getImports ((parsef, []) : acc) fs)
(\_ -> getImports acc fs) -- not in current soure tree, ignore
where
lit (LIDR _) = True
lit _ = False
fname (IDR fn) = fn
fname (LIDR fn) = fn
fname (IBC _ src) = fname src
buildTree :: [FilePath] -- ^ already guaranteed built
-> [(FilePath, [ImportInfo])] -- ^ import lists (don't reparse)
-> FilePath
-> Idris [ModuleTree]
buildTree built importlists fp = evalStateT (btree [] fp) []
where
addFile :: FilePath -> [ModuleTree] ->
StateT [(FilePath, [ModuleTree])] Idris [ModuleTree]
addFile f m = do fs <- get
put ((f, m) : fs)
return m
btree :: [FilePath] -> FilePath ->
StateT [(FilePath, [ModuleTree])] Idris [ModuleTree]
btree stk f =
do i <- lift getIState
let file = extractFileName f
lift $ logLvl 1 $ "CHASING " ++ show file ++ " (" ++ show fp ++ ")"
ibcsd <- lift $ valIBCSubDir i
ids <- lift allImportDirs
fp <- lift $ findImport ids ibcsd file
lift $ logLvl 1 $ "Found " ++ show fp
mt <- lift $ runIO $ getIModTime fp
if (file `elem` built)
then return [MTree fp False mt []]
else if file `elem` stk then
do lift $ tclift $ tfail
(Msg $ "Cycle detected in imports: "
++ showSep " -> " (reverse (file : stk)))
else do donetree <- get
case lookup file donetree of
Just t -> return t
_ -> do ms <- mkChildren file fp
addFile file ms
where mkChildren file (LIDR fn) = do ms <- children True fn (file : stk)
mt <- lift $ runIO $ getModificationTime fn
return [MTree (LIDR fn) True mt ms]
mkChildren file (IDR fn) = do ms <- children False fn (file : stk)
mt <- lift $ runIO $ getModificationTime fn
return [MTree (IDR fn) True mt ms]
mkChildren file (IBC fn src)
= do srcexist <- lift $ runIO $ doesFileExist (getSrcFile src)
ms <- if srcexist then
do [MTree _ _ _ ms'] <- mkChildren file src
return ms'
else return []
-- Modification time is the later of the source/ibc modification time
smt <- lift $ idrisCatch (runIO $ getIModTime src)
(\c -> runIO $ getModificationTime fn)
mt <- lift $ idrisCatch (do t <- runIO $ getModificationTime fn
return (max smt t))
(\c -> return smt)
-- FIXME: It's also not up to date if anything it imports has
-- been modified since its own ibc has.
--
-- Issue #1592 on the issue tracker.
--
-- https://github.com/idris-lang/Idris-dev/issues/1592
ibcOutdated <- lift $ fn `younger` (getSrcFile src)
-- FIXME (EB): The below 'hasValidIBCVersion' that's
-- commented out appears to be breaking reloading in vim
-- mode. Until we know why, I've commented it out.
ibcValid <- return True -- hasValidIBCVersion fn
return [MTree (IBC fn src) (ibcOutdated || not ibcValid) mt ms]
getSrcFile (IBC _ src) = getSrcFile src
getSrcFile (LIDR src) = src
getSrcFile (IDR src) = src
younger ibc src = do exist <- runIO $ doesFileExist src
if exist then do
ibct <- runIO $ getModificationTime ibc
srct <- runIO $ getModificationTime src
return (srct > ibct)
else return False
children :: Bool -> FilePath -> [FilePath] ->
StateT [(FilePath, [ModuleTree])] Idris [ModuleTree]
children lit f stk = -- idrisCatch
do exist <- lift $ runIO $ doesFileExist f
if exist then do
lift $ logLvl 1 $ "Reading source " ++ show f
let modules = maybe [] id (lookup f importlists)
ms <- mapM (btree stk . import_path) modules
return (concat ms)
else return [] -- IBC with no source available
-- (\c -> return []) -- error, can't chase modules here
| kojiromike/Idris-dev | src/Idris/Chaser.hs | bsd-3-clause | 10,173 | 12 | 24 | 4,001 | 2,844 | 1,428 | 1,416 | 185 | 11 |
-- | When there aren't enough registers to hold all the vregs we have to spill
-- some of those vregs to slots on the stack. This module is used modify the
-- code to use those slots.
module RegAlloc.Graph.Spill (
regSpill,
SpillStats(..),
accSpillSL
) where
import RegAlloc.Liveness
import Instruction
import Reg
import Cmm hiding (RegSet)
import BlockId
import MonadUtils
import State
import Unique
import UniqFM
import UniqSet
import UniqSupply
import Outputable
import Platform
import Data.List
import Data.Maybe
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Map as Map
import qualified Data.Set as Set
-- | Spill all these virtual regs to stack slots.
--
-- TODO: See if we can split some of the live ranges instead of just globally
-- spilling the virtual reg. This might make the spill cleaner's job easier.
--
-- TODO: On CISCy x86 and x86_64 we don't nessesarally have to add a mov instruction
-- when making spills. If an instr is using a spilled virtual we may be able to
-- address the spill slot directly.
--
regSpill
:: Instruction instr
=> Platform
-> [LiveCmmDecl statics instr] -- ^ the code
-> UniqSet Int -- ^ available stack slots
-> UniqSet VirtualReg -- ^ the regs to spill
-> UniqSM
([LiveCmmDecl statics instr]
-- code with SPILL and RELOAD meta instructions added.
, UniqSet Int -- left over slots
, SpillStats ) -- stats about what happened during spilling
regSpill platform code slotsFree regs
-- Not enough slots to spill these regs.
| sizeUniqSet slotsFree < sizeUniqSet regs
= pprPanic "regSpill: out of spill slots!"
( text " regs to spill = " <> ppr (sizeUniqSet regs)
$$ text " slots left = " <> ppr (sizeUniqSet slotsFree))
| otherwise
= do
-- Allocate a slot for each of the spilled regs.
let slots = take (sizeUniqSet regs) $ uniqSetToList slotsFree
let regSlotMap = listToUFM
$ zip (uniqSetToList regs) slots
-- Grab the unique supply from the monad.
us <- getUniqueSupplyM
-- Run the spiller on all the blocks.
let (code', state') =
runState (mapM (regSpill_top platform regSlotMap) code)
(initSpillS us)
return ( code'
, minusUniqSet slotsFree (mkUniqSet slots)
, makeSpillStats state')
-- | Spill some registers to stack slots in a top-level thing.
regSpill_top
:: Instruction instr
=> Platform
-> RegMap Int
-- ^ map of vregs to slots they're being spilled to.
-> LiveCmmDecl statics instr
-- ^ the top level thing.
-> SpillM (LiveCmmDecl statics instr)
regSpill_top platform regSlotMap cmm
= case cmm of
CmmData{}
-> return cmm
CmmProc info label live sccs
| LiveInfo static firstId mLiveVRegsOnEntry liveSlotsOnEntry <- info
-> do
-- We should only passed Cmms with the liveness maps filled in,
-- but we'll create empty ones if they're not there just in case.
let liveVRegsOnEntry = fromMaybe mapEmpty mLiveVRegsOnEntry
-- The liveVRegsOnEntry contains the set of vregs that are live
-- on entry to each basic block. If we spill one of those vregs
-- we remove it from that set and add the corresponding slot
-- number to the liveSlotsOnEntry set. The spill cleaner needs
-- this information to erase unneeded spill and reload instructions
-- after we've done a successful allocation.
let liveSlotsOnEntry' :: Map BlockId (Set Int)
liveSlotsOnEntry'
= mapFoldWithKey patchLiveSlot
liveSlotsOnEntry liveVRegsOnEntry
let info'
= LiveInfo static firstId
(Just liveVRegsOnEntry)
liveSlotsOnEntry'
-- Apply the spiller to all the basic blocks in the CmmProc.
sccs' <- mapM (mapSCCM (regSpill_block platform regSlotMap)) sccs
return $ CmmProc info' label live sccs'
where -- Given a BlockId and the set of registers live in it,
-- if registers in this block are being spilled to stack slots,
-- then record the fact that these slots are now live in those blocks
-- in the given slotmap.
patchLiveSlot
:: BlockId -> RegSet
-> Map BlockId (Set Int) -> Map BlockId (Set Int)
patchLiveSlot blockId regsLive slotMap
= let
-- Slots that are already recorded as being live.
curSlotsLive = fromMaybe Set.empty
$ Map.lookup blockId slotMap
moreSlotsLive = Set.fromList
$ catMaybes
$ map (lookupUFM regSlotMap)
$ uniqSetToList regsLive
slotMap'
= Map.insert blockId (Set.union curSlotsLive moreSlotsLive)
slotMap
in slotMap'
-- | Spill some registers to stack slots in a basic block.
regSpill_block
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveBasicBlock instr
-> SpillM (LiveBasicBlock instr)
regSpill_block platform regSlotMap (BasicBlock i instrs)
= do instrss' <- mapM (regSpill_instr platform regSlotMap) instrs
return $ BasicBlock i (concat instrss')
-- | Spill some registers to stack slots in a single instruction.
-- If the instruction uses registers that need to be spilled, then it is
-- prefixed (or postfixed) with the appropriate RELOAD or SPILL meta
-- instructions.
regSpill_instr
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveInstr instr
-> SpillM [LiveInstr instr]
regSpill_instr _ _ li@(LiveInstr _ Nothing)
= do return [li]
regSpill_instr platform regSlotMap
(LiveInstr instr (Just _))
= do
-- work out which regs are read and written in this instr
let RU rlRead rlWritten = regUsageOfInstr platform instr
-- sometimes a register is listed as being read more than once,
-- nub this so we don't end up inserting two lots of spill code.
let rsRead_ = nub rlRead
let rsWritten_ = nub rlWritten
-- if a reg is modified, it appears in both lists, want to undo this..
let rsRead = rsRead_ \\ rsWritten_
let rsWritten = rsWritten_ \\ rsRead_
let rsModify = intersect rsRead_ rsWritten_
-- work out if any of the regs being used are currently being spilled.
let rsSpillRead = filter (\r -> elemUFM r regSlotMap) rsRead
let rsSpillWritten = filter (\r -> elemUFM r regSlotMap) rsWritten
let rsSpillModify = filter (\r -> elemUFM r regSlotMap) rsModify
-- rewrite the instr and work out spill code.
(instr1, prepost1) <- mapAccumLM (spillRead regSlotMap) instr rsSpillRead
(instr2, prepost2) <- mapAccumLM (spillWrite regSlotMap) instr1 rsSpillWritten
(instr3, prepost3) <- mapAccumLM (spillModify regSlotMap) instr2 rsSpillModify
let (mPrefixes, mPostfixes) = unzip (prepost1 ++ prepost2 ++ prepost3)
let prefixes = concat mPrefixes
let postfixes = concat mPostfixes
-- final code
let instrs' = prefixes
++ [LiveInstr instr3 Nothing]
++ postfixes
return $ instrs'
-- | Add a RELOAD met a instruction to load a value for an instruction that
-- writes to a vreg that is being spilled.
spillRead
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillRead regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 0, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, []) )
| otherwise = panic "RegSpill.spillRead: no slot defined for spilled reg"
-- | Add a SPILL meta instruction to store a value for an instruction that
-- writes to a vreg that is being spilled.
spillWrite
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillWrite regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 0) }
return ( instr'
, ( []
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillWrite: no slot defined for spilled reg"
-- | Add both RELOAD and SPILL meta instructions for an instruction that
-- both reads and writes to a vreg that is being spilled.
spillModify
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillModify regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillModify: no slot defined for spilled reg"
-- | Rewrite uses of this virtual reg in an instr to use a different
-- virtual reg.
patchInstr
:: Instruction instr
=> Reg -> instr -> SpillM (instr, Reg)
patchInstr reg instr
= do nUnique <- newUnique
-- The register we're rewriting is suppoed to be virtual.
-- If it's not then something has gone horribly wrong.
let nReg
= case reg of
RegVirtual vr
-> RegVirtual (renameVirtualReg nUnique vr)
RegReal{}
-> panic "RegAlloc.Graph.Spill.patchIntr: not patching real reg"
let instr' = patchReg1 reg nReg instr
return (instr', nReg)
patchReg1
:: Instruction instr
=> Reg -> Reg -> instr -> instr
patchReg1 old new instr
= let patchF r
| r == old = new
| otherwise = r
in patchRegsOfInstr instr patchF
-- Spiller monad --------------------------------------------------------------
-- | State monad for the spill code generator.
type SpillM a
= State SpillS a
-- | Spill code generator state.
data SpillS
= SpillS
{ -- | Unique supply for generating fresh vregs.
stateUS :: UniqSupply
-- | Spilled vreg vs the number of times it was loaded, stored.
, stateSpillSL :: UniqFM (Reg, Int, Int) }
-- | Create a new spiller state.
initSpillS :: UniqSupply -> SpillS
initSpillS uniqueSupply
= SpillS
{ stateUS = uniqueSupply
, stateSpillSL = emptyUFM }
-- | Allocate a new unique in the spiller monad.
newUnique :: SpillM Unique
newUnique
= do us <- gets stateUS
case takeUniqFromSupply us of
(uniq, us')
-> do modify $ \s -> s { stateUS = us' }
return uniq
-- | Add a spill/reload count to a stats record for a register.
accSpillSL :: (Reg, Int, Int) -> (Reg, Int, Int) -> (Reg, Int, Int)
accSpillSL (r1, s1, l1) (_, s2, l2)
= (r1, s1 + s2, l1 + l2)
-- Spiller stats --------------------------------------------------------------
-- | Spiller statistics.
-- Tells us what registers were spilled.
data SpillStats
= SpillStats
{ spillStoreLoad :: UniqFM (Reg, Int, Int) }
-- | Extract spiller statistics from the spiller state.
makeSpillStats :: SpillS -> SpillStats
makeSpillStats s
= SpillStats
{ spillStoreLoad = stateSpillSL s }
instance Outputable SpillStats where
ppr stats
= (vcat $ map (\(r, s, l) -> ppr r <+> int s <+> int l)
$ eltsUFM (spillStoreLoad stats))
| urbanslug/ghc | compiler/nativeGen/RegAlloc/Graph/Spill.hs | bsd-3-clause | 13,266 | 0 | 16 | 4,655 | 2,492 | 1,283 | 1,209 | 226 | 2 |
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
module JSONSpec where
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as C
import Thrift.Types
import Thrift.Transport
import Thrift.Transport.Memory
import Thrift.Protocol
import Thrift.Protocol.JSON
tString :: [Char] -> ThriftVal
tString = TString . C.pack
spec :: Spec
spec = do
describe "JSONProtocol" $ do
describe "bool" $ do
it "writes true as 1" $ do
let val = True
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TBool val)
bin <-tRead trans 100
(C.unpack bin) `shouldBe` ['1']
it "writes false as 0" $ do
let val = False
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TBool val)
bin <- tRead trans 100
(C.unpack bin) `shouldBe` ['0']
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto $ TBool val
val2 <- readVal proto T_BOOL
val2 `shouldBe` (TBool val)
describe "string" $ do
it "writes" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TString $ C.pack "\"a")
bin <- tRead trans 100
(C.unpack bin) `shouldBe` "\"\\\"a\""
it "reads" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans $ C.pack "\"\\\"a\""
val <- readVal proto (T_STRING)
val `shouldBe` (TString $ C.pack "\"a")
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TString $ C.pack val)
val2 <- readVal proto (T_STRING)
val2 `shouldBe` (TString $ C.pack val)
describe "binary" $ do
it "writes with padding" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TBinary $ LBS.pack [1])
bin <- tRead trans 100
(C.unpack bin) `shouldBe` "\"AQ==\""
it "reads with padding" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans $ C.pack "\"AQ==\""
val <- readVal proto (T_BINARY)
val `shouldBe` (TBinary $ LBS.pack [1])
it "reads without padding" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans $ C.pack "\"AQ\""
val <- readVal proto (T_BINARY)
val `shouldBe` (TBinary $ LBS.pack [1])
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TBinary $ LBS.pack val)
val2 <- readVal proto (T_BINARY)
val2 `shouldBe` (TBinary $ LBS.pack val)
describe "list" $ do
it "writes empty list" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TList T_BYTE [])
bin <- tRead trans 100
(C.unpack bin) `shouldBe` "[\"i8\",0]"
it "reads empty" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",0]")
val <- readVal proto (T_LIST T_BYTE)
val `shouldBe` (TList T_BYTE [])
it "writes single element" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TList T_BYTE [TByte 0])
bin <- tRead trans 100
(C.unpack bin) `shouldBe` "[\"i8\",1,0]"
it "reads single element" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",1,0]")
val <- readVal proto (T_LIST T_BYTE)
val `shouldBe` (TList T_BYTE [TByte 0])
it "reads elements" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",2,42, 43]")
val <- readVal proto (T_LIST T_BYTE)
val `shouldBe` (TList T_BYTE [TByte 42, TByte 43])
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto $ (TList T_STRING $ map tString val)
val2 <- readVal proto $ T_LIST T_STRING
val2 `shouldBe` (TList T_STRING $ map tString val)
describe "set" $ do
it "writes empty" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TSet T_BYTE [])
bin <- tRead trans 100
(C.unpack bin) `shouldBe` "[\"i8\",0]"
it "reads empty" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",0]")
val <- readVal proto (T_SET T_BYTE)
val `shouldBe` (TSet T_BYTE [])
it "reads single element" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",1,0]")
val <- readVal proto (T_SET T_BYTE)
val `shouldBe` (TSet T_BYTE [TByte 0])
it "reads elements" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",2,42, 43]")
val <- readVal proto (T_SET T_BYTE)
val `shouldBe` (TSet T_BYTE [TByte 42, TByte 43])
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto $ (TSet T_STRING $ map tString val)
val2 <- readVal proto $ T_SET T_STRING
val2 `shouldBe` (TSet T_STRING $ map tString val)
describe "map" $ do
it "writes empty" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto (TMap T_BYTE T_BYTE [])
bin <- tRead trans 100
(C.unpack bin) `shouldBe`"[\"i8\",\"i8\",0,{}]"
it "reads empty" $ do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack "[\"i8\",\"i8\",0,{}]")
val <- readVal proto (T_MAP T_BYTE T_BYTE)
val `shouldBe` (TMap T_BYTE T_BYTE [])
it "reads string-string" $ do
let bin = "[\"str\",\"str\",2,{\"a\":\"2\",\"b\":\"blah\"}]"
trans <- openMemoryBuffer
let proto = JSONProtocol trans
tWrite trans (C.pack bin)
val <- readVal proto (T_MAP T_STRING T_STRING)
val`shouldBe` (TMap T_STRING T_STRING [(tString "a", tString "2"), (tString "b", tString "blah")])
prop "round trip" $ \val -> do
trans <- openMemoryBuffer
let proto = JSONProtocol trans
writeVal proto $ (TMap T_STRING T_STRING $ map toKV val)
val2 <- readVal proto $ T_MAP T_STRING T_STRING
val2 `shouldBe` (TMap T_STRING T_STRING $ map toKV val)
where
toKV v = (tString v, tString v)
| jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/lib/hs/test/JSONSpec.hs | apache-2.0 | 7,644 | 0 | 21 | 2,242 | 2,381 | 1,108 | 1,273 | 175 | 1 |
module ProjectEuler.Problem024 (solve) where
import Data.List
solve :: [Int]
solve = ps !! n
where
ps = sort . permutations $ [0..9]
n = 1000000 - 1
| hachibu/project-euler | src/ProjectEuler/Problem024.hs | mit | 162 | 0 | 8 | 40 | 62 | 36 | 26 | 6 | 1 |
-- Typeclasses
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
class Borked a where
bork :: a -> String
instance Borked Int where
bork = show
--instance Num a => Borked a where
-- bork = show
--instance Borked (Int, Int) where
-- bork (x, y) = bork x ++ " " ++ bork y
--instance (Borked a, Borked b) => Borked (a, b) where
-- bork (x, y) = ">>" ++ bork x ++ " " ++ bork y ++ "<<"
main :: IO ()
main = putStrLn $ bork (3::Int)
| gitrookie/functionalcode | code/Haskell/haskfeatures/src/typeclass.hs | mit | 459 | 0 | 7 | 117 | 68 | 39 | 29 | 7 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCStatsCallback
(newRTCStatsCallback, newRTCStatsCallbackSync,
newRTCStatsCallbackAsync, RTCStatsCallback)
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
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsCallback Mozilla RTCStatsCallback documentation>
newRTCStatsCallback ::
(MonadIO m) =>
(Maybe RTCStatsResponse -> IO ()) -> m RTCStatsCallback
newRTCStatsCallback callback
= liftIO
(syncCallback1 ThrowWouldBlock
(\ response ->
fromJSRefUnchecked response >>= \ response' -> callback response'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsCallback Mozilla RTCStatsCallback documentation>
newRTCStatsCallbackSync ::
(MonadIO m) =>
(Maybe RTCStatsResponse -> IO ()) -> m RTCStatsCallback
newRTCStatsCallbackSync callback
= liftIO
(syncCallback1 ContinueAsync
(\ response ->
fromJSRefUnchecked response >>= \ response' -> callback response'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsCallback Mozilla RTCStatsCallback documentation>
newRTCStatsCallbackAsync ::
(MonadIO m) =>
(Maybe RTCStatsResponse -> IO ()) -> m RTCStatsCallback
newRTCStatsCallbackAsync callback
= liftIO
(asyncCallback1
(\ response ->
fromJSRefUnchecked response >>= \ response' -> callback response')) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/RTCStatsCallback.hs | mit | 2,295 | 0 | 12 | 447 | 521 | 310 | 211 | 42 | 1 |
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : Data.Utils
Description : various utilities
Copyright : (c) Lars Brünjes, 2016
License : MIT
Maintainer : brunjlar@gmail.com
Stability : experimental
Portability : portable
This module reexports various utility modules for convenience.
-}
module Data.Utils
( module Data.FixedSize
, module Data.Utils.Analytic
, module Data.Utils.Arrow
, module Data.Utils.Cache
, module Data.Utils.Pipes
, module Data.Utils.Random
, module Data.Utils.Stack
, module Data.Utils.Statistics
, module Data.Utils.Traversable
) where
import Data.FixedSize
import Data.Utils.Analytic
import Data.Utils.Arrow
import Data.Utils.Cache
import Data.Utils.Pipes
import Data.Utils.Random
import Data.Utils.Stack
import Data.Utils.Statistics
import Data.Utils.Traversable
| brunjlar/neural | src/Data/Utils.hs | mit | 852 | 0 | 5 | 146 | 125 | 86 | 39 | 20 | 0 |
module GHCJS.DOM.SVGAnimatedRect (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/SVGAnimatedRect.hs | mit | 45 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
-- @Author: Zeyuan Shang
-- @Date: 2016-06-07 12:44:38
-- @Last Modified by: Zeyuan Shang
-- @Last Modified time: 2016-06-07 12:54:45
data Graph a = Graph [a] [(a, a)]
deriving (Show, Eq)
data Adjacency a = Adj [(a, [a])]
deriving (Show, Eq)
graphToAdj :: (Eq a) => Graph a -> Adjacency a
graphToAdj (Graph [] _) = Adj []
graphToAdj (Graph (x:xs) ys) = Adj ((x, concatMap f ys) : zs)
where
f (a, b)
| a == x = [b]
| b == x = [a]
| otherwise = []
Adj zs = graphToAdj (Graph xs ys)
main = do
let value = graphToAdj $ Graph ['b','c','d','f','g','h','k'] [('b','c'),('b','f'),('c','f'),('f','k'),('g','h')]
print value | zeyuanxy/haskell-playground | ninety-nine-haskell-problems/vol9/80.hs | mit | 716 | 0 | 13 | 211 | 335 | 185 | 150 | 15 | 1 |
-- Problems/Problem007Spec.hs
module Problems.Problem007Spec (main, spec) where
import Test.Hspec
import Problems.Problem007
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 7" $
it "Should evaluate to 104743" $
p7 `shouldBe` 104743
| Sgoettschkes/learning | haskell/ProjectEuler/tests/Problems/Problem007Spec.hs | mit | 269 | 0 | 8 | 52 | 73 | 41 | 32 | 9 | 1 |
-- MoreMonads.hs
import Control.Monad
import Control.Monad.Writer
pathsWriter :: [(Int,Int)] -> Int -> Int -> [[Int]]
pathsWriter edges start end = map execWriter (pathsWriter' edges start end)
pathsWriter' :: [(Int,Int)] -> Int -> Int -> [Writer [Int] ()]
pathsWriter' edges start end =
let e_paths = do (e_start, e_end) <- edges
guard $ e_start == start
subpath <- pathsWriter' edges e_end end
return $ do tell [start]
subpath
in if start == end then tell [start] : e_paths else e_paths
| hnfmr/beginning_haskell | chapter7/src/Chapter7/MoreMonads.hs | mit | 615 | 0 | 15 | 205 | 213 | 111 | 102 | 12 | 2 |
module Ch01Spec (spec) where
import Ch01
import Test.Hspec
spec :: Spec
spec = do
describe "toDigits" $ do
it "converts integer to digits" $ do
let int = 1234
expected = [4,3,2,1]
toDigitsRev int `shouldBe` expected
toDigits int `shouldBe` (reverse expected)
it "returns [] for 0 and nagative numbers" $ do
toDigits 0 `shouldBe` []
toDigits (-17) `shouldBe` []
describe "doubleEveryOther" $ do
it "doubles every number _beginning from the right_" $ do
let ints = [8, 7, 6, 5]
doubleEveryOther [8, 7, 6, 5] `shouldBe` [16, 7, 12, 5]
doubleEveryOther [1, 2, 3] `shouldBe` [1, 4, 3]
describe "sumDigits" $ do
it "calculates the sum of all digits" $ do
let digits = [16, 7, 12, 5]
expected = 22
sumDigits digits `shouldBe` expected
describe "validate" $ do
it "validates credit card number" $ do
let ccValid = 4012888888881881
ccInvalid = 4012888888881882
validate ccValid `shouldBe` True
validate ccInvalid `shouldBe` False
describe "hanoi" $ do
it "returns the steps need to move from peg a to b" $ do
hanoi 2 "a" "b" "c" `shouldBe` [("a", "c"), ("a", "b"), ("c", "b")]
| isaiah/cis194 | test/Ch01Spec.hs | mit | 1,220 | 0 | 16 | 333 | 434 | 227 | 207 | 33 | 1 |
module PE0007 where
-- Spotted on the front page of haskell.org
-- but Melissa O'Neil calls it The Unfaithful Sieve
-- in http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
primes' :: [Integer]
primes' = sieve [2..]
where sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
sieve [] = []
-- "We can write trial division more clearly as"
primes :: [Integer]
primes = 2 : [x | x <- [3..], isprime x]
isprime :: Integer -> Bool
isprime x = all (\p -> x `mod` p > 0) (factorsToTry x)
where
factorsToTry y = takeWhile (\p -> p*p <= y) primes
main :: IO ()
main = do
print $ primes !! 10000
| mvidner/projecteuler | src/PE0007.hs | mit | 611 | 0 | 12 | 138 | 229 | 125 | 104 | 13 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module HBF.PrgmIO.Pure
( PurePrgmIO
, runPurePrgmIO
, Val
) where
import Control.Monad.State
import Control.Monad.Writer
import HBF.PrgmIO
newtype PurePrgmIO a = PurePrgmIO {getPurePrgmIO :: WriterT [Val] (State [Val]) a} deriving (Functor, Monad)
runPurePrgmIO :: [Val] -> PurePrgmIO a -> [Val]
runPurePrgmIO input = flip evalState input . execWriterT . getPurePrgmIO
instance PrgmIO PurePrgmIO where
prgmRead = PurePrgmIO $ state (\(x:xs) -> (x, xs))
prgmWrite x = PurePrgmIO $ tell [x]
| atlaua/hbf | HBF/PrgmIO/Pure.hs | mit | 548 | 0 | 11 | 88 | 182 | 104 | 78 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-hadoopjarstepconfig.html
module Stratosphere.ResourceProperties.EMRClusterHadoopJarStepConfig where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EMRClusterKeyValue
-- | Full data type definition for EMRClusterHadoopJarStepConfig. See
-- 'emrClusterHadoopJarStepConfig' for a more convenient constructor.
data EMRClusterHadoopJarStepConfig =
EMRClusterHadoopJarStepConfig
{ _eMRClusterHadoopJarStepConfigArgs :: Maybe (ValList Text)
, _eMRClusterHadoopJarStepConfigJar :: Val Text
, _eMRClusterHadoopJarStepConfigMainClass :: Maybe (Val Text)
, _eMRClusterHadoopJarStepConfigStepProperties :: Maybe [EMRClusterKeyValue]
} deriving (Show, Eq)
instance ToJSON EMRClusterHadoopJarStepConfig where
toJSON EMRClusterHadoopJarStepConfig{..} =
object $
catMaybes
[ fmap (("Args",) . toJSON) _eMRClusterHadoopJarStepConfigArgs
, (Just . ("Jar",) . toJSON) _eMRClusterHadoopJarStepConfigJar
, fmap (("MainClass",) . toJSON) _eMRClusterHadoopJarStepConfigMainClass
, fmap (("StepProperties",) . toJSON) _eMRClusterHadoopJarStepConfigStepProperties
]
-- | Constructor for 'EMRClusterHadoopJarStepConfig' containing required
-- fields as arguments.
emrClusterHadoopJarStepConfig
:: Val Text -- ^ 'emrchjscJar'
-> EMRClusterHadoopJarStepConfig
emrClusterHadoopJarStepConfig jararg =
EMRClusterHadoopJarStepConfig
{ _eMRClusterHadoopJarStepConfigArgs = Nothing
, _eMRClusterHadoopJarStepConfigJar = jararg
, _eMRClusterHadoopJarStepConfigMainClass = Nothing
, _eMRClusterHadoopJarStepConfigStepProperties = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-hadoopjarstepconfig.html#cfn-elasticmapreduce-cluster-hadoopjarstepconfig-args
emrchjscArgs :: Lens' EMRClusterHadoopJarStepConfig (Maybe (ValList Text))
emrchjscArgs = lens _eMRClusterHadoopJarStepConfigArgs (\s a -> s { _eMRClusterHadoopJarStepConfigArgs = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-hadoopjarstepconfig.html#cfn-elasticmapreduce-cluster-hadoopjarstepconfig-jar
emrchjscJar :: Lens' EMRClusterHadoopJarStepConfig (Val Text)
emrchjscJar = lens _eMRClusterHadoopJarStepConfigJar (\s a -> s { _eMRClusterHadoopJarStepConfigJar = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-hadoopjarstepconfig.html#cfn-elasticmapreduce-cluster-hadoopjarstepconfig-mainclass
emrchjscMainClass :: Lens' EMRClusterHadoopJarStepConfig (Maybe (Val Text))
emrchjscMainClass = lens _eMRClusterHadoopJarStepConfigMainClass (\s a -> s { _eMRClusterHadoopJarStepConfigMainClass = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-hadoopjarstepconfig.html#cfn-elasticmapreduce-cluster-hadoopjarstepconfig-stepproperties
emrchjscStepProperties :: Lens' EMRClusterHadoopJarStepConfig (Maybe [EMRClusterKeyValue])
emrchjscStepProperties = lens _eMRClusterHadoopJarStepConfigStepProperties (\s a -> s { _eMRClusterHadoopJarStepConfigStepProperties = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EMRClusterHadoopJarStepConfig.hs | mit | 3,378 | 0 | 13 | 307 | 447 | 255 | 192 | 39 | 1 |
{- This module was generated from data in the Kate syntax
highlighting file julia.xml, version 0.2, by -}
module Text.Highlighting.Kate.Syntax.Julia
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
import qualified Data.Set as Set
-- | Full name of language.
syntaxName :: String
syntaxName = "Julia"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.jl"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("Julia","_normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("Julia","_normal") -> return ()
("Julia","region_marker") -> (popContext) >> pEndLine
("Julia","nested") -> return ()
("Julia","squared") -> return ()
("Julia","curly") -> return ()
("Julia","_adjoint") -> (popContext) >> pEndLine
("Julia","String") -> (popContext) >> pEndLine
("Julia","1-comment") -> (popContext) >> pEndLine
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
list_block'5fbegin = Set.fromList $ words $ "begin do for function if let quote try type while"
list_block'5feb = Set.fromList $ words $ "catch else elseif"
list_block'5fend = Set.fromList $ words $ "end"
list_keywords = Set.fromList $ words $ "abstract bitstype break ccall const continue export global import in local macro module return typealias"
list_types = Set.fromList $ words $ "AbstractArray AbstractMatrix AbstractVector Any Array ASCIIString Associative Bool ByteString Char Complex Complex64 Complex128 ComplexPair DArray Dict Exception Expr Float Float32 Float64 Function ObjectIdDict Int Int8 Int16 Int32 Int64 Integer IntSet IO IOStream Matrix Nothing None NTuple Number Ptr Range Range1 Ranges Rational Real Regex RegexMatch Set Signed StridedArray StridedMatrix StridedVecOrMat StridedVector String SubArray SubString Symbol Task Tuple Type Uint Uint8 Uint16 Uint32 Uint64 Union Unsigned UTF8String VecOrMat Vector Void WeakRef"
regex_'5ba'2dzA'2dZ'5d'5cw'2a'28'3f'3d'27'29 = compileRegex True "[a-zA-Z]\\w*(?=')"
regex_'28'5cd'2b'28'5c'2e'5cd'2b'29'3f'7c'5c'2e'5cd'2b'29'28'5beE'5d'5b'2b'2d'5d'3f'5cd'2b'29'3f'28im'29'3f'28'3f'3d'27'29 = compileRegex True "(\\d+(\\.\\d+)?|\\.\\d+)([eE][+-]?\\d+)?(im)?(?=')"
regex_'5b'5c'29'5c'5d'7d'5d'28'3f'3d'27'29 = compileRegex True "[\\)\\]}](?=')"
regex_'5c'2e'27'28'3f'3d'27'29 = compileRegex True "\\.'(?=')"
regex_'27'5b'5e'27'5d'2a'28'27'27'5b'5e'27'5d'2a'29'2a'27'28'3f'3d'5b'5e'27'5d'7c'24'29 = compileRegex True "'[^']*(''[^']*)*'(?=[^']|$)"
regex_'27'5b'5e'27'5d'2a'28'27'27'5b'5e'27'5d'2a'29'2a = compileRegex True "'[^']*(''[^']*)*"
regex_0x'5b0'2d9a'2dfA'2dF'5d'2b'28im'29'3f = compileRegex True "0x[0-9a-fA-F]+(im)?"
regex_'28'5cd'2b'28'5c'2e'5cd'2b'29'3f'7c'5c'2e'5cd'2b'29'28'5beE'5d'5b'2b'2d'5d'3f'5cd'2b'29'3f'28im'29'3f = compileRegex True "(\\d+(\\.\\d+)?|\\.\\d+)([eE][+-]?\\d+)?(im)?"
regex_'27'2b = compileRegex True "'+"
parseRules ("Julia","_normal") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_block'5fbegin >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_block'5feb >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_block'5fend >>= withAttribute KeywordTok))
<|>
((pString False "#BEGIN" >>= withAttribute CommentTok) >>~ pushContext ("Julia","region_marker"))
<|>
((pString False "#END" >>= withAttribute CommentTok) >>~ pushContext ("Julia","region_marker"))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok))
<|>
((pDetectChar False '#' >>= withAttribute CommentTok) >>~ pushContext ("Julia","1-comment"))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Julia","String"))
<|>
((pString False "..." >>= withAttribute NormalTok))
<|>
((pString False "::" >>= withAttribute NormalTok))
<|>
((pString False ">>>" >>= withAttribute NormalTok))
<|>
((pString False ">>" >>= withAttribute NormalTok))
<|>
((pString False "<<" >>= withAttribute NormalTok))
<|>
((pString False "==" >>= withAttribute NormalTok))
<|>
((pString False "!=" >>= withAttribute NormalTok))
<|>
((pString False "<=" >>= withAttribute NormalTok))
<|>
((pString False ">=" >>= withAttribute NormalTok))
<|>
((pString False "&&" >>= withAttribute NormalTok))
<|>
((pString False "||" >>= withAttribute NormalTok))
<|>
((pString False ".*" >>= withAttribute NormalTok))
<|>
((pString False ".^" >>= withAttribute NormalTok))
<|>
((pString False "./" >>= withAttribute NormalTok))
<|>
((pString False ".'" >>= withAttribute NormalTok))
<|>
((pString False "+=" >>= withAttribute NormalTok))
<|>
((pString False "-=" >>= withAttribute NormalTok))
<|>
((pString False "*=" >>= withAttribute NormalTok))
<|>
((pString False "/=" >>= withAttribute NormalTok))
<|>
((pString False "&=" >>= withAttribute NormalTok))
<|>
((pString False "|=" >>= withAttribute NormalTok))
<|>
((pString False "$=" >>= withAttribute NormalTok))
<|>
((pString False ">>>=" >>= withAttribute NormalTok))
<|>
((pString False ">>=" >>= withAttribute NormalTok))
<|>
((pString False "<<=" >>= withAttribute NormalTok))
<|>
((pRegExpr regex_'5ba'2dzA'2dZ'5d'5cw'2a'28'3f'3d'27'29 >>= withAttribute NormalTok) >>~ pushContext ("Julia","_adjoint"))
<|>
((pRegExpr regex_'28'5cd'2b'28'5c'2e'5cd'2b'29'3f'7c'5c'2e'5cd'2b'29'28'5beE'5d'5b'2b'2d'5d'3f'5cd'2b'29'3f'28im'29'3f'28'3f'3d'27'29 >>= withAttribute FloatTok) >>~ pushContext ("Julia","_adjoint"))
<|>
((pRegExpr regex_'5b'5c'29'5c'5d'7d'5d'28'3f'3d'27'29 >>= withAttribute NormalTok) >>~ pushContext ("Julia","_adjoint"))
<|>
((pRegExpr regex_'5c'2e'27'28'3f'3d'27'29 >>= withAttribute NormalTok) >>~ pushContext ("Julia","_adjoint"))
<|>
((pRegExpr regex_'27'5b'5e'27'5d'2a'28'27'27'5b'5e'27'5d'2a'29'2a'27'28'3f'3d'5b'5e'27'5d'7c'24'29 >>= withAttribute CharTok))
<|>
((pRegExpr regex_'27'5b'5e'27'5d'2a'28'27'27'5b'5e'27'5d'2a'29'2a >>= withAttribute CharTok))
<|>
((pDetectIdentifier >>= withAttribute NormalTok))
<|>
((pRegExpr regex_0x'5b0'2d9a'2dfA'2dF'5d'2b'28im'29'3f >>= withAttribute BaseNTok))
<|>
((pRegExpr regex_'28'5cd'2b'28'5c'2e'5cd'2b'29'3f'7c'5c'2e'5cd'2b'29'28'5beE'5d'5b'2b'2d'5d'3f'5cd'2b'29'3f'28im'29'3f >>= withAttribute FloatTok))
<|>
((pAnyChar "()[]{}" >>= withAttribute NormalTok))
<|>
((pAnyChar "*+-/\\&|<>~$!^=,;:@" >>= withAttribute NormalTok))
<|>
(currentContext >>= \x -> guard (x == ("Julia","_normal")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Julia","region_marker") =
(((parseRules ("Julia","1-comment")))
<|>
(currentContext >>= \x -> guard (x == ("Julia","region_marker")) >> pDefault >>= withAttribute CommentTok))
parseRules ("Julia","nested") =
(((pDetectChar False ')' >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Julia","nested")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Julia","squared") =
(((pDetectChar False ']' >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Julia","squared")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Julia","curly") =
(((pDetectChar False '}' >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Julia","curly")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Julia","_adjoint") =
(((pRegExpr regex_'27'2b >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Julia","_adjoint")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Julia","String") =
(((pDetectSpaces >>= withAttribute StringTok))
<|>
((pDetectIdentifier >>= withAttribute StringTok))
<|>
((pLineContinue >>= withAttribute StringTok))
<|>
((pHlCStringChar >>= withAttribute NormalTok))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Julia","String")) >> pDefault >>= withAttribute StringTok))
parseRules ("Julia","1-comment") =
(((pDetectSpaces >>= withAttribute CommentTok))
<|>
((pDetectIdentifier >>= withAttribute CommentTok))
<|>
(currentContext >>= \x -> guard (x == ("Julia","1-comment")) >> pDefault >>= withAttribute CommentTok))
parseRules x = parseRules ("Julia","_normal") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Julia.hs | gpl-2.0 | 10,193 | 0 | 55 | 1,597 | 2,685 | 1,415 | 1,270 | 196 | 11 |
module HEP.Automation.MadGraph.Dataset.Set20110630set1 where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine.V2
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType.V2
import HEP.Automation.MadGraph.Model.ZpH
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType.V2
psetup_zph_TTBar0or1J :: ProcessSetup ZpH
psetup_zph_TTBar0or1J = PS {
mversion = MadGraph4
, model = ZpH
, process = preDefProcess TTBar0or1J
, processBrief = "TTBar0or1J"
, workname = "630ZpH_TTBar0or1J"
}
zphParamSet :: [ModelParam ZpH]
zphParamSet = [ ZpHParam { massZp = 800.0,
gRZp = 3.4 } ]
psetuplist :: [ProcessSetup ZpH ]
psetuplist = [ psetup_zph_TTBar0or1J ]
sets :: [Int]
sets = [1..50]
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 1.2
, uc_etcutlep = 18.0
, uc_etacutjet = 2.5
, uc_etcutjet = 15.0
}
eventsets :: [EventSet]
eventsets =
[ EventSet (psetup_zph_TTBar0or1J)
(RS { param = p
, numevent = 100000
, machine = LHC7
, rgrun = Fixed
, rgscale = 200.0
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, usercut = UserCutDef ucut
, pgs = RunPGS
, jetalgo = KTJet 0.5
, uploadhep = NoUploadHEP
, setnum = num
})
| p <- zphParamSet , num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/ttbarLHC"
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110630set1.hs | gpl-3.0 | 1,720 | 0 | 10 | 559 | 372 | 236 | 136 | 49 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Serverless.AWSLambda where
import qualified Amex.DE as Amex
import qualified Amex.Request as Amex
import qualified Amex.Response as Amex
import Data.Aeson as JSON
import qualified Data.ByteString.Char8 as BS
-- import qualified Data.ByteString
import System.IO
import System.Exit
main :: IO ()
main = do
raw <- BS.hGetLine stdin
case JSON.eitherDecodeStrict raw of
Left e -> do
putStrLn "Error reading Lambda input."
putStrLn $ "Input was " ++ (BS.unpack raw)
putStrLn $ "Error was " ++ e
exitFailure
Right (r :: Amex.Req) -> do
Amex.getResult r (mapM_ print) (\xs -> print $ length xs) | jpotecki/AmexMobileBackend | src/Serverless/AWSLambda.hs | gpl-3.0 | 751 | 0 | 16 | 215 | 196 | 106 | 90 | 20 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- |
-- Copyright : (c) 2011 Benedikt Schmidt & Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <beschmi@gmail.com>
-- Portability : GHC only
--
-- Guarded formulas.
module Theory.Constraint.System.Guarded (
-- * Guarded formulas
Guarded(..)
, LGuarded
, LNGuarded
, GAtom(..)
-- ** Smart constructors
, gfalse
, gtrue
, gdisj
, gconj
, gex
, gall
, gnot
, ginduct
, formulaToGuarded
, formulaToGuarded_
-- ** Transformation
, simplifyGuarded
, simplifyGuardedOrReturn
, mapGuardedAtoms
, atomToGAtom
, sortGAtoms
-- ** Queries
, isConjunction
, isDisjunction
, isAllGuarded
, isExGuarded
, isSafetyFormula
, guardFactTags
-- ** Conversions to non-bound representations
, bvarToLVar
-- , unbindAtom
, openGuarded
-- ** Substitutions
, substBound
, substBoundAtom
, substFree
, substFreeAtom
-- ** Skolemization
, unskolemizeLNGuarded
, applySkGuarded
, skolemizeGuarded
, skolemizeTerm
, skolemizeFact
, matchAction
, matchTerm
, applySkAction
, applySkTerm
-- ** Pretty-printing
, prettyGuarded
) where
import Control.Applicative
import Control.Arrow
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.Fresh (MonadFresh, scopeFreshness)
import qualified Control.Monad.Trans.PreciseFresh as Precise (Fresh, evalFresh, evalFreshT)
import Debug.Trace
import Data.Data
import Data.Binary
import Data.DeriveTH
import Data.Either (partitionEithers)
-- import Data.Foldable (Foldable(..), foldMap)
import Data.List
import qualified Data.DList as D
-- import Data.Monoid (Monoid(..))
-- import Data.Traversable hiding (mapM, sequence)
import Logic.Connectives
import Text.PrettyPrint.Highlight
import Theory.Model
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
data Guarded s c v = GAto (Atom (VTerm c (BVar v)))
| GDisj (Disj (Guarded s c v))
| GConj (Conj (Guarded s c v))
| GGuarded Quantifier [s] [Atom (VTerm c (BVar v))] (Guarded s c v)
-- ^ Denotes @ALL xs. as => gf@ or @Ex xs. as & gf&
-- depending on the 'Quantifier'.
-- We assume that all bound variables xs occur in
-- f@i atoms in as.
deriving (Eq, Ord, Show)
isConjunction :: Guarded s c v -> Bool
isConjunction (GConj _) = True
isConjunction _ = False
isDisjunction :: Guarded s c v -> Bool
isDisjunction (GDisj _) = True
isDisjunction _ = False
isExGuarded :: Guarded s c v -> Bool
isExGuarded (GGuarded Ex _ _ _) = True
isExGuarded _ = False
isAllGuarded :: Guarded s c v -> Bool
isAllGuarded (GGuarded All _ _ _) = True
isAllGuarded _ = False
-- | Check whether the guarded formula is closed and does not contain an
-- existential quantifier. This under-approximates the question whether the
-- formula is a safety formula. A safety formula @phi@ has the property that a
-- trace violating it can never be extended to a trace satisfying it.
isSafetyFormula :: HasFrees (Guarded s c v) => Guarded s c v -> Bool
isSafetyFormula gf0 =
null (frees [gf0]) && noExistential gf0
where
noExistential (GAto _ ) = True
noExistential (GGuarded Ex _ _ _) = False
noExistential (GGuarded All _ _ gf) = noExistential gf
noExistential (GDisj disj) = all noExistential $ getDisj disj
noExistential (GConj conj) = all noExistential $ getConj conj
-- | All 'FactTag's that are used in guards.
guardFactTags :: Guarded s c v -> [FactTag]
guardFactTags =
D.toList .
foldGuarded mempty (mconcat . getDisj) (mconcat . getConj) getTags
where
getTags _qua _ss atos inner =
mconcat [ D.singleton tag | Action _ (Fact tag _) <- atos ] <> inner
-- | Atoms that are allowed as guards.
data GAtom t = GEqE t t | GAction t (Fact t)
deriving (Eq, Show, Ord)
isGAction :: GAtom t -> Bool
isGAction (GAction _ _) = True
isGAction _ = False
-- | Convert 'Atom's to 'GAtom's, if possible.
atomToGAtom :: Show t => Atom t -> GAtom t
atomToGAtom = conv
where conv (EqE s t) = GEqE s t
conv (Action i f) = GAction i f
conv a = error $ "atomsToGAtom: "++ show a
++ "is not a guarded atom."
-- | Stable sort that ensures that actions occur before equations.
sortGAtoms :: [GAtom t] -> [GAtom t]
sortGAtoms = uncurry (++) . partition isGAction
------------------------------------------------------------------------------
-- Folding
------------------------------------------------------------------------------
-- | Fold a guarded formula.
foldGuarded :: (Atom (VTerm c (BVar v)) -> b)
-> (Disj b -> b)
-> (Conj b -> b)
-> (Quantifier -> [s] -> [Atom (VTerm c (BVar v))] -> b -> b)
-> Guarded s c v
-> b
foldGuarded fAto fDisj fConj fGuarded =
go
where
go (GAto a) = fAto a
go (GDisj disj) = fDisj $ fmap go disj
go (GConj conj) = fConj $ fmap go conj
go (GGuarded qua ss as gf) = fGuarded qua ss as (go gf)
-- | Fold a guarded formula with scope info.
-- The Integer argument denotes the number of
-- quantifiers that have been encountered so far.
foldGuardedScope :: (Integer -> Atom (VTerm c (BVar v)) -> b)
-> (Disj b -> b)
-> (Conj b -> b)
-> (Quantifier -> [s] -> Integer -> [Atom (VTerm c (BVar v))] -> b -> b)
-> Guarded s c v
-> b
foldGuardedScope fAto fDisj fConj fGuarded =
go 0
where
go !i (GAto a) = fAto i a
go !i (GDisj disj) = fDisj $ fmap (go i) disj
go !i (GConj conj) = fConj $ fmap (go i) conj
go !i (GGuarded qua ss as gf) =
fGuarded qua ss i' as (go i' gf)
where
i' = i + fromIntegral (length ss)
-- | Map a guarded formula with scope info.
-- The Integer argument denotes the number of
-- quantifiers that have been encountered so far.
mapGuardedAtoms :: (Integer -> Atom (VTerm c (BVar v))
-> Atom (VTerm d (BVar w)))
-> Guarded s c v
-> Guarded s d w
mapGuardedAtoms f =
foldGuardedScope (\i a -> GAto $ f i a) GDisj GConj
(\qua ss i as gf -> GGuarded qua ss (map (f i) as) gf)
------------------------------------------------------------------------------
-- Instances
------------------------------------------------------------------------------
{-
instance Functor (Guarded s c) where
fmap f = foldGuarded (GAto . fmap (fmapTerm (fmap (fmap f)))) GDisj GConj
(\qua ss as gf -> GGuarded qua ss (map (fmap (fmapTerm (fmap (fmap f)))) as) gf)
-}
instance Foldable (Guarded s c) where
foldMap f = foldGuarded (foldMap (foldMap (foldMap (foldMap f))))
(mconcat . getDisj)
(mconcat . getConj)
(\_qua _ss as b -> foldMap (foldMap (foldMap (foldMap (foldMap f)))) as `mappend` b)
traverseGuarded :: (Applicative f, Ord c, Ord v, Ord a)
=> (a -> f v) -> Guarded s c a -> f (Guarded s c v)
traverseGuarded f = foldGuarded (liftA GAto . traverse (traverseTerm (traverse (traverse f))))
(liftA GDisj . sequenceA)
(liftA GConj . sequenceA)
(\qua ss as gf -> GGuarded qua ss <$> traverse (traverse (traverseTerm (traverse (traverse f)))) as <*> gf)
instance Ord c => HasFrees (Guarded (String, LSort) c LVar) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc _ _ = const mempty
mapFrees f = traverseGuarded (mapFrees f)
-- FIXME: remove name hints for variables for saturation?
type LGuarded c = Guarded (String, LSort) c LVar
------------------------------------------------------------------------------
-- Substitutions of bound for free and vice versa
------------------------------------------------------------------------------
-- | @substBoundAtom s a@ substitutes each occurence of a bound variables @i@
-- in @dom(s)@ with the corresponding free variable @x=s(i)@ in the atom @a@.
substBoundAtom :: Ord c => [(Integer,LVar)] -> Atom (VTerm c (BVar LVar)) -> Atom (VTerm c (BVar LVar))
substBoundAtom s = fmap (fmapTerm (fmap subst))
where subst bv@(Bound i') = case lookup i' s of
Just x -> Free x
Nothing -> bv
subst fv = fv
-- | @substBound s gf@ substitutes each occurence of a bound
-- variable @i@ in @dom(s)@ with the corresponding free variable
-- @s(i)=x@ in all atoms in @gf@.
substBound :: Ord c => [(Integer,LVar)] -> LGuarded c -> LGuarded c
substBound s = mapGuardedAtoms (\j a -> substBoundAtom [(i+j,v) | (i,v) <- s] a)
-- | @substFreeAtom s a@ substitutes each occurence of a free variables @v@
-- in @dom(s)@ with the bound variables @i=s(v)@ in the atom @a@.
substFreeAtom :: Ord c
=> [(LVar,Integer)]
-> Atom (VTerm c (BVar LVar)) -> Atom (VTerm c (BVar LVar))
substFreeAtom s = fmap (fmapTerm (fmap subst))
where subst fv@(Free x) = case lookup x s of
Just i -> Bound i
Nothing -> fv
subst bv = bv
-- | @substFreeAtom s gf@ substitutes each occurence of a free variables
-- @v in dom(s)@ with the correpsonding bound variables @i=s(v)@
-- in all atoms in @gf@.
substFree :: Ord c => [(LVar,Integer)] -> LGuarded c -> LGuarded c
substFree s = mapGuardedAtoms (\j a -> substFreeAtom [(v,i+j) | (v,i) <- s] a)
-- | Assuming that there are no more bound variables left in an atom of a
-- formula, convert it to an atom with free variables only.
bvarToLVar :: Ord c => Atom (VTerm c (BVar LVar)) -> Atom (VTerm c LVar)
bvarToLVar =
fmap (fmapTerm (fmap (foldBVar boundError id)))
where
boundError v = error $ "bvarToLVar: left-over bound variable '"
++ show v ++ "'"
-- | Assuming that there are no more bound variables left in an atom of a
-- formula, convert it to an atom with free variables only.
--bvarToMaybeLVar :: Ord c => Atom (VTerm c (BVar LVar)) -> Maybe (Atom (VTerm c LVar))
--bvarToMaybeLVar =
-- fmap (fmapTerm (fmap (foldBVar ??? id)))
-- | Provided an 'Atom' does not contain a bound variable, it is converted to
-- the type of atoms without bound varaibles.
unbindAtom :: (Ord c, Ord v) => Atom (VTerm c (BVar v)) -> Maybe (Atom (VTerm c v))
unbindAtom = traverse (traverseTerm (traverse (foldBVar (const Nothing) Just)))
------------------------------------------------------------------------------
-- Opening and Closing
------------------------------------------------------------------------------
-- | @openGuarded gf@ returns @Just (qua,vs,ats,gf')@ if @gf@ is a guarded
-- clause and @Nothing@ otherwise. In the first case, @qua@ is the quantifier,
-- @vs@ is a list of fresh variables, @ats@ is the antecedent, and @gf'@ is the
-- succedent. In both antecedent and succedent, the bound variables are
-- replaced by @vs@.
openGuarded :: (Ord c, MonadFresh m)
=> LGuarded c -> m (Maybe (Quantifier, [LVar], [Atom (VTerm c LVar)], LGuarded c))
openGuarded (GGuarded qua vs as gf) = do
xs <- mapM (\(n,s) -> freshLVar n s) vs
return $ Just (qua, xs, openas xs, opengf xs)
where
openas xs = map (bvarToLVar . substBoundAtom (subst xs)) as
opengf xs = substBound (subst xs) gf
subst xs = zip [0..] (reverse xs)
openGuarded _ = return Nothing
-- | @closeGuarded vs ats gf@ is a smart constructor for @GGuarded@.
closeGuarded :: Ord c => Quantifier -> [LVar] -> [Atom (VTerm c LVar)]
-> LGuarded c -> LGuarded c
closeGuarded qua vs as gf =
(case qua of Ex -> gex; All -> gall) vs' as' gf'
where
as' = map (substFreeAtom s . fmap (fmapTerm (fmap Free))) as
gf' = substFree s gf
s = zip (reverse vs) [0..]
vs' = map (lvarName &&& lvarSort) vs
------------------------------------------------------------------------------
-- Conversion and negation
------------------------------------------------------------------------------
type LNGuarded = Guarded (String,LSort) Name LVar
instance Apply LNGuarded where
apply subst = mapGuardedAtoms (const $ apply subst)
-- | @gtf b@ returns the guarded formula f with @b <-> f@.
gtf :: Bool -> Guarded s c v
gtf False = GDisj (Disj [])
gtf True = GConj (Conj [])
-- | @gfalse@ returns the guarded formula f with @False <-> f@.
gfalse :: Guarded s c v
gfalse = gtf False
-- | @gtrue@ returns the guarded formula f with @True <-> f@.
gtrue :: Guarded s c v
gtrue = gtf True
-- | @gnotAtom a@ returns the guarded formula f with @not a <-> f@.
gnotAtom :: Atom (VTerm c (BVar v)) -> Guarded s c v
gnotAtom a = GGuarded All [] [a] gfalse
-- | @gconj gfs@ smart constructor for the conjunction of gfs.
gconj :: (Ord s, Ord c, Ord v) => [Guarded s c v] -> Guarded s c v
gconj gfs0 = case concatMap flatten gfs0 of
[gf] -> gf
gfs | any (gfalse ==) gfs -> gfalse
-- FIXME: See 'sortednub' below.
| otherwise -> GConj $ Conj $ nub gfs
where
flatten (GConj conj) = concatMap flatten $ getConj conj
flatten gf = [gf]
-- | @gdisj gfs@ smart constructor for the disjunction of gfs.
gdisj :: (Ord s, Ord c, Ord v) => [Guarded s c v] -> Guarded s c v
gdisj gfs0 = case concatMap flatten gfs0 of
[gf] -> gf
gfs | any (gtrue ==) gfs -> gtrue
-- FIXME: Consider using 'sortednub' here. This yields stronger
-- normalizaton for formulas. However, it also means that we loose
-- invariance under renaming of free variables, as the order changes,
-- when they are renamed.
| otherwise -> GDisj $ Disj $ nub gfs
where
flatten (GDisj disj) = concatMap flatten $ getDisj disj
flatten gf = [gf]
-- @ A smart constructor for @GGuarded Ex@ that removes empty quantifications
-- and conjunctions with 'gfalse'.
gex :: (Ord s, Ord c, Ord v)
=> [s] -> [Atom (VTerm c (BVar v))] -> Guarded s c v -> Guarded s c v
gex [] as gf = gconj (map GAto as ++ [gf])
gex _ _ gf | gf == gfalse = gfalse
gex ss as gf = GGuarded Ex ss as gf
-- @ A smart constructor for @GGuarded All@ that drops implications to 'gtrue'
-- and removes empty premises.
gall :: (Eq s, Eq c, Eq v)
=> [s] -> [Atom (VTerm c (BVar v))] -> Guarded s c v -> Guarded s c v
gall _ [] gf = gf
gall _ _ gf | gf == gtrue = gtrue
gall ss atos gf = GGuarded All ss atos gf
-- Conversion of formulas to guarded formulas
---------------------------------------------
-- | Local newtype to avoid orphan instance.
newtype ErrorDoc d = ErrorDoc { unErrorDoc :: d }
deriving( Monoid, NFData, Document, HighlightDocument )
-- | @formulaToGuarded fm@ returns a guarded formula @gf@ that is
-- equivalent to @fm@ under the assumption that this is possible.
-- If not, then 'error' is called.
formulaToGuarded_ :: LNFormula -> LNGuarded
formulaToGuarded_ = either (error . render) id . formulaToGuarded
-- | @formulaToGuarded fm@ returns a guarded formula @gf@ that is
-- equivalent to @fm@ if possible.
formulaToGuarded :: HighlightDocument d => LNFormula -> Either d LNGuarded
formulaToGuarded fmOrig =
either (Left . ppError . unErrorDoc) Right
$ Precise.evalFreshT (convert False fmOrig) (avoidPrecise fmOrig)
where
ppFormula :: HighlightDocument a => LNFormula -> a
ppFormula = nest 2 . doubleQuotes . prettyLNFormula
ppError d = d $-$ text "in the formula" $-$ ppFormula fmOrig
convert True (Ato a) = pure $ gnotAtom a
convert False (Ato a) = pure $ GAto a
convert polarity (Not f) = convert (not polarity) f
convert True (Conn And f g) = gdisj <$> mapM (convert True) [f, g]
convert False (Conn And f g) = gconj <$> mapM (convert False) [f, g]
convert True (Conn Or f g) = gconj <$> mapM (convert True) [f, g]
convert False (Conn Or f g) = gdisj <$> mapM (convert False) [f, g]
convert True (Conn Imp f g ) =
gconj <$> sequence [convert False f, convert True g]
convert False (Conn Imp f g ) =
gdisj <$> sequence [convert True f, convert False g]
convert polarity (TF b) = pure $ gtf (polarity /= b)
convert polarity f0@(Qua qua0 _ _) =
-- The quantifier switch stems from our implicit negation of the formula.
case (qua0, polarity) of
(All, True ) -> convAll Ex
(All, False) -> convAll All
(Ex, True ) -> convEx All
(Ex, False) -> convEx Ex
where
noUnguardedVars [] = return ()
noUnguardedVars unguarded = throwError $ vcat
[ fsep $ text "unguarded variable(s)"
: (punctuate comma $
map (quotes . text . show) unguarded)
++ map text ["in", "the", "subformula"]
, ppFormula f0
]
conjActionsEqs (Conn And f1 f2) = conjActionsEqs f1 ++ conjActionsEqs f2
conjActionsEqs (Ato a@(Action _ _)) = [Left $ bvarToLVar a]
conjActionsEqs (Ato e@(EqE _ _)) = [Left $ bvarToLVar e]
conjActionsEqs f = [Right f]
-- Given a list of unguarded variables and a list of atoms, compute the
-- remaining unguarded variables that are not guarded by the given atoms.
remainingUnguarded ug0 atoms =
go ug0 (sortGAtoms . map atomToGAtom $ atoms)
where go ug [] = ug
go ug ((GAction a fa) :gatoms) = go (ug \\ frees (a, fa)) gatoms
-- FIXME: We do not consider the terms, e.g., for ug=[x,y],
-- s=pair(x,a), and t=pair(b,y), we could define ug'=[].
go ug ((GEqE s t):gatoms) = go ug' gatoms
where ug' | covered s ug = ug \\ frees t
| covered t ug = ug \\ frees s
| otherwise = ug
covered a vs = frees a `intersect` vs == []
convEx qua = do
(xs,_,f) <- openFormulaPrefix f0
let (as_eqs, fs) = partitionEithers $ conjActionsEqs f
-- all existentially quantified variables must be guarded
noUnguardedVars (remainingUnguarded xs as_eqs)
-- convert all other formulas
gf <- (if polarity then gdisj else gconj)
<$> mapM (convert polarity) fs
return $ closeGuarded qua xs (as_eqs) gf
convAll qua = do
(xs,_,f) <- openFormulaPrefix f0
case f of
Conn Imp ante suc -> do
let (as_eqs, fs) = partitionEithers $ conjActionsEqs ante
-- all universally quantified variables must be guarded
noUnguardedVars (remainingUnguarded xs (as_eqs))
-- negate formulas in antecedent and combine with body
gf <- (if polarity then gconj else gdisj)
<$> sequence ( map (convert (not polarity)) fs ++
[convert polarity suc] )
return $ closeGuarded qua xs as_eqs gf
_ -> throwError $
text "universal quantifier without toplevel implication" $-$
ppFormula f0
convert polarity (Conn Iff f1 f2) =
gconj <$> mapM (convert polarity) [Conn Imp f1 f2, Conn Imp f2 f1]
------------------------------------------------------------------------------
-- Induction over the trace
------------------------------------------------------------------------------
-- | Negate a guarded formula.
gnot :: (Ord s, Ord c, Ord v)
=> Guarded s c v -> Guarded s c v
gnot =
go
where
go (GGuarded All ss as gf) = gex ss as $ go gf
go (GGuarded Ex ss as gf) = gall ss as $ go gf
go (GAto ato) = gnotAtom ato
go (GDisj disj) = gconj $ map go (getDisj disj)
go (GConj conj) = gdisj $ map go (getConj conj)
-- | Checks if a doubly guarded formula is satisfied by the empty trace;
-- returns @'Left' errMsg@ if the formula is not doubly guarded.
satisfiedByEmptyTrace :: Guarded s c v -> Either String Bool
satisfiedByEmptyTrace =
foldGuarded
(\_ato -> throwError "atom outside the scope of a quantifier")
(liftM or . sequence . getDisj)
(liftM and . sequence . getConj)
(\qua _ss _as _gf -> return $ qua == All)
-- the empty trace always satisfies guarded all-quantification
-- and always dissatisfies guarded ex-quantification
-- | Tries to convert a doubly guarded formula to an induction hypothesis.
-- Returns @'Left' errMsg@ if the formula is not last-free or not doubly
-- guarded.
toInductionHypothesis :: Ord c => LGuarded c -> Either String (LGuarded c)
toInductionHypothesis =
go
where
go (GGuarded qua ss as gf)
| any isLastAtom as = throwError "formula not last-free"
| otherwise = do
gf' <- go gf
return $ case qua of
All -> gex ss as (gconj $ (gnotAtom <$> lastAtos) ++ [gf'])
Ex -> gall ss as (gdisj $ (GAto <$> lastAtos) ++ [gf'])
where
lastAtos :: [Atom (VTerm c (BVar LVar))]
lastAtos = do
(j, (_, LSortNode)) <- zip [0..] $ reverse ss
return $ Last (varTerm (Bound j))
go (GAto (Less i j)) = return $ gdisj [GAto (EqE i j), GAto (Less j i)]
go (GAto (Last _)) = throwError "formula not last-free"
go (GAto ato) = return $ gnotAtom ato
go (GDisj disj) = gconj <$> traverse go (getDisj disj)
go (GConj conj) = gdisj <$> traverse go (getConj conj)
-- | Try to prove the formula by applying induction over the trace.
-- Returns @'Left' errMsg@ if this is not possible. Returns a tuple of
-- formulas: one formalizing the proof obligation of the base-case and one
-- formalizing the proof obligation of the step-case.
ginduct :: Ord c => LGuarded c -> Either String (LGuarded c, LGuarded c)
ginduct gf = do
unless (null $ frees gf) (throwError "formula not closed")
unless (containsAction gf) (throwError "formula contains no action atom")
baseCase <- satisfiedByEmptyTrace gf
gfIH <- toInductionHypothesis gf
return (gtf baseCase, gconj [gf, gfIH])
where
containsAction = foldGuarded (const True) (or . getDisj) (or . getConj)
(\_ _ as body -> not (null as) || body)
------------------------------------------------------------------------------
-- Formula Simplification
------------------------------------------------------------------------------
-- | Simplify a 'Guarded' formula by replacing atoms with their truth value,
-- if it can be determined.
simplifyGuarded :: (LNAtom -> Maybe Bool)
-- ^ Partial assignment for truth value of atoms.
-> LNGuarded
-- ^ Original formula
-> Maybe LNGuarded
-- ^ Simplified formula, provided some simplification was
-- performed.
simplifyGuarded valuation fm0
| fm1 /= fm0 = trace (render $ ppMsg) (Just fm1)
| otherwise = Nothing
where
fm1 = simplifyGuardedOrReturn valuation fm0
ppFm = nest 2 . doubleQuotes . prettyGuarded
ppMsg = nest 2 $ text "simplified formula:" $-$
nest 2 (vcat [ ppFm fm0, text "to", ppFm fm1])
-- | Simplify a 'Guarded' formula by replacing atoms with their truth value,
-- if it can be determined. If nothing is simplified, returns the initial formula.
simplifyGuardedOrReturn :: (LNAtom -> Maybe Bool)
-- ^ Partial assignment for truth value of atoms.
-> LNGuarded
-- ^ Original formula
-> LNGuarded
-- ^ Simplified formula.
simplifyGuardedOrReturn valuation fm0 = {-trace (render ppMsg)-} fm1
where
-- ppFm = nest 2 . doubleQuotes . prettyGuarded
-- ppMsg = nest 2 $ text "simplified formula:" $-$
-- nest 2 (vcat [ ppFm fm0, text "to", ppFm fm1])
fm1 = simp fm0
simp fm@(GAto ato) = maybe fm gtf {-(trace (show (valuation =<< unbindAtom ato))-} (valuation =<< unbindAtom ato){-)-}
simp (GDisj fms) = gdisj $ map simp $ getDisj fms
simp (GConj fms) = gconj $ map simp $ getConj fms
simp (GGuarded All [] atos gf)
| any ((Just False ==) . snd) annAtos = gtrue
| otherwise =
-- keep all atoms that we cannot evaluate yet.
-- NOTE: Here we are missing the opportunity to change the valuation
-- for evaluating the body 'gf'. We could add all atoms that we have
-- as a premise.
gall [] (fst <$> filter ((Nothing ==) . snd) annAtos) (simp gf)
where
-- cache the possibly expensive evaluation of the valuation
annAtos = (\x -> (x, {-(trace (show (valuation =<< unbindAtom x))-} (valuation =<< unbindAtom x){-)-})) <$> atos
-- Note that existentials without quantifiers are already eliminated by
-- 'gex'. Moreover, we delay simplification inside guarded all
-- quantification and guarded existential quantifiers. Their body will be
-- simplified once the quantifiers are gone.
simp fm@(GGuarded _ _ _ _) = fm
------------------------------------------------------------------------------
-- Terms, facts, and formulas with skolem constants
------------------------------------------------------------------------------
-- | A constant type that supports names and skolem constants. We use the
-- skolem constants to represent fixed free variables from the constraint
-- system during matching the atoms of a guarded clause to the atoms of the
-- constraint system.
data SkConst = SkName Name
| SkConst LVar
deriving( Eq, Ord, Show, Data, Typeable )
type SkTerm = VTerm SkConst LVar
type SkFact = Fact SkTerm
type SkSubst = Subst SkConst LVar
type SkGuarded = LGuarded SkConst
-- | A term with skolem constants and bound variables
type BSkTerm = VTerm SkConst BLVar
-- | An term with skolem constants and bound variables
type BSkAtom = Atom BSkTerm
instance IsConst SkConst
-- Skolemization of terms without bound variables.
--------------------------------------------------
skolemizeTerm :: LNTerm -> SkTerm
skolemizeTerm = fmapTerm conv
where
conv :: Lit Name LVar -> Lit SkConst LVar
conv (Var v) = Con (SkConst v)
conv (Con n) = Con (SkName n)
skolemizeFact :: LNFact -> Fact SkTerm
skolemizeFact = fmap skolemizeTerm
skolemizeAtom :: BLAtom -> BSkAtom
skolemizeAtom = fmap skolemizeBTerm
skolemizeGuarded :: LNGuarded -> SkGuarded
skolemizeGuarded = mapGuardedAtoms (const skolemizeAtom)
applySkTerm :: SkSubst -> SkTerm -> SkTerm
applySkTerm subst t = applyVTerm subst t
applySkFact :: SkSubst -> SkFact -> SkFact
applySkFact subst = fmap (applySkTerm subst)
applySkAction :: SkSubst -> (SkTerm,SkFact) -> (SkTerm,SkFact)
applySkAction subst (t,f) = (applySkTerm subst t, applySkFact subst f)
-- Skolemization of terms with bound variables.
-----------------------------------------------
skolemizeBTerm :: VTerm Name BLVar -> BSkTerm
skolemizeBTerm = fmapTerm conv
where
conv :: Lit Name BLVar -> Lit SkConst BLVar
conv (Var (Free x)) = Con (SkConst x)
conv (Var (Bound b)) = Var (Bound b)
conv (Con n) = Con (SkName n)
unskolemizeBTerm :: BSkTerm -> VTerm Name BLVar
unskolemizeBTerm t = fmapTerm conv t
where
conv :: Lit SkConst BLVar -> Lit Name BLVar
conv (Con (SkConst x)) = Var (Free x)
conv (Var (Bound b)) = Var (Bound b)
conv (Var (Free v)) = error $ "unskolemizeBTerm: free variable " ++
show v++" found in "++show t
conv (Con (SkName n)) = Con n
unskolemizeBLAtom :: BSkAtom -> BLAtom
unskolemizeBLAtom = fmap unskolemizeBTerm
unskolemizeLNGuarded :: SkGuarded -> LNGuarded
unskolemizeLNGuarded = mapGuardedAtoms (const unskolemizeBLAtom)
applyBSkTerm :: SkSubst -> VTerm SkConst BLVar -> VTerm SkConst BLVar
applyBSkTerm subst =
go
where
go t = case viewTerm t of
Lit l -> applyBLLit l
FApp o as -> fApp o (map go as)
applyBLLit :: Lit SkConst BLVar -> VTerm SkConst BLVar
applyBLLit l@(Var (Free v)) =
maybe (lit l) (fmapTerm (fmap Free)) (imageOf subst v)
applyBLLit l = lit l
applyBSkAtom :: SkSubst -> Atom (VTerm SkConst BLVar) -> Atom (VTerm SkConst BLVar)
applyBSkAtom subst = fmap (applyBSkTerm subst)
applySkGuarded :: SkSubst -> LGuarded SkConst -> LGuarded SkConst
applySkGuarded subst = mapGuardedAtoms (const $ applyBSkAtom subst)
-- Matching
-----------
matchAction :: (SkTerm, SkFact) -> (SkTerm, SkFact) -> WithMaude [SkSubst]
matchAction (i1, fa1) (i2, fa2) =
solveMatchLTerm sortOfSkol (i1 `matchWith` i2 <> fa1 `matchFact` fa2)
where
sortOfSkol (SkName n) = sortOfName n
sortOfSkol (SkConst v) = lvarSort v
matchTerm :: SkTerm -> SkTerm -> WithMaude [SkSubst]
matchTerm s t =
solveMatchLTerm sortOfSkol (s `matchWith` t)
where
sortOfSkol (SkName n) = sortOfName n
sortOfSkol (SkConst v) = lvarSort v
------------------------------------------------------------------------------
-- Pretty Printing
------------------------------------------------------------------------------
-- | Pretty print a formula.
prettyGuarded :: HighlightDocument d
=> LNGuarded -- ^ Guarded Formula.
-> d -- ^ Pretty printed formula.
prettyGuarded fm =
Precise.evalFresh (pp fm) (avoidPrecise fm)
where
pp :: HighlightDocument d => LNGuarded -> Precise.Fresh d
pp (GAto a) = return $ prettyNAtom $ bvarToLVar a
pp (GDisj (Disj [])) = return $ operator_ "⊥" -- "F"
pp (GDisj (Disj xs)) = do
ps <- mapM (\x -> opParens <$> pp x) xs
return $ parens $ sep $ punctuate (operator_ " ∨") ps
-- return $ sep $ punctuate (operator_ " |") ps
pp (GConj (Conj [])) = return $ operator_ "⊤" -- "T"
pp (GConj (Conj xs)) = do
ps <- mapM (\x -> opParens <$> pp x) xs
return $ sep $ punctuate (operator_ " ∧") ps --- " &") ps
pp gf0@(GGuarded _ _ _ _) =
-- variable names invented here can be reused otherwise
scopeFreshness $ do
Just (qua, vs, atoms, gf) <- openGuarded gf0
let antecedent = (GAto . fmap (fmapTerm (fmap Free))) <$> atoms
connective = operator_ (case qua of All -> "⇒"; Ex -> "∧")
-- operator_ (case qua of All -> "==>"; Ex -> "&")
quantifier = operator_ (ppQuant qua) <-> ppVars vs <> operator_ "."
dante <- nest 1 <$> pp (GConj (Conj antecedent))
case (qua, vs, gf) of
(Ex, _, GConj (Conj [])) ->
return $ sep $ [ quantifier, dante ]
(All, [], GDisj (Disj [])) | gf == gfalse ->
return $ operator_ "¬" <> dante
_ -> do
dsucc <- nest 1 <$> pp gf
return $ sep [ quantifier, sep [dante, connective, dsucc] ]
where
ppVars = fsep . map (text . show)
ppQuant All = "∀" -- "All "
ppQuant Ex = "∃" -- "Ex "
-- Derived instances
--------------------
$( derive makeBinary ''Guarded)
$( derive makeNFData ''Guarded)
| samscott89/tamarin-prover | lib/theory/src/Theory/Constraint/System/Guarded.hs | gpl-3.0 | 32,328 | 0 | 25 | 9,091 | 8,706 | 4,477 | 4,229 | 479 | 24 |
-- Author: Stefan Eng
-- License: GPL v3
-- File: xmobar.hs
-- Description:
-- xmobar configuration file
Config { font = "xft:DejaVu-10"
, bgColor = "#000000"
, fgColor = "#BFBFBF"
, position = Top
, hideOnStart = False
, lowerOnStart = True
, persistent = False
, allDesktops = True
, overrideRedirect = True
, commands = [ Run Date "%a %b %_d %Y - %H:%M:%S" "theDate" 10
, Run BatteryP ["BAT1"]
["-t", "<fc=white>Battery:</fc> <acstatus> <left>% <timeleft>",
"-L", "10", "-H", "80", "-p", "3",
"--", "-O", "<fc=green>Charging</fc> - ", "-i", "",
"-o", "<fc=yellow>Discharging</fc> -", "-i", "",
"-L", "-15", "-H", "-5",
"-l", "red", "-m", "blue", "-h", "green"] 30
, Run Wireless "wlp1s0" [ "-t", "<fc=white>Wireless:</fc> <essid> <quality>%"]
10
, Run StdinReader
]
, sepChar = "%"
, alignSep = "}{"
, template = "%StdinReader% }{ %wlp1s0wi% | %battery% | <fc=#EE0000>%theDate%</fc>"
}
| stefaneng/dotfiles | haskell/xmobar/xmobar.hs | gpl-3.0 | 1,314 | 0 | 9 | 564 | 221 | 140 | 81 | -1 | -1 |
module System.DevUtils.MySQL.Helpers.ProcessList (
ProcessList(..),
default',
query'List,
showFullProcessList
) where
import System.DevUtils.MySQL.Helpers.ProcessList.Include (ProcessList(..), query'List)
import System.DevUtils.MySQL.Helpers.ProcessList.Default (default')
import System.DevUtils.MySQL.Helpers.ProcessList.JSON ()
import System.DevUtils.MySQL.Helpers.ProcessList.Run (showFullProcessList)
| adarqui/DevUtils-MySQL | src/System/DevUtils/MySQL/Helpers/ProcessList.hs | gpl-3.0 | 410 | 0 | 6 | 27 | 88 | 63 | 25 | 9 | 0 |
{-# LANGUAGE RecordWildCards, DeriveDataTypeable #-}
{-|
Options common to most hledger reports.
-}
module Hledger.Reports.ReportOptions (
ReportOpts(..),
BalanceType(..),
AccountListMode(..),
FormatStr,
defreportopts,
rawOptsToReportOpts,
flat_,
tree_,
dateSpanFromOpts,
intervalFromOpts,
clearedValueFromOpts,
whichDateFromOpts,
journalSelectingAmountFromOpts,
queryFromOpts,
queryFromOptsOnly,
queryOptsFromOpts,
transactionDateFn,
postingDateFn,
tests_Hledger_Reports_ReportOptions
)
where
import Data.Data (Data)
import Data.Typeable (Typeable)
import Data.Time.Calendar
import System.Console.CmdArgs.Default -- some additional default stuff
import Test.HUnit
import Hledger.Data
import Hledger.Query
import Hledger.Utils
type FormatStr = String
-- | Which balance is being shown in a multi-column balance report.
data BalanceType = PeriodBalance -- ^ The change of balance in each period.
| CumulativeBalance -- ^ The accumulated balance at each period's end, starting from zero at the report start date.
| HistoricalBalance -- ^ The historical balance at each period's end, starting from the account balances at the report start date.
deriving (Eq,Show,Data,Typeable)
instance Default BalanceType where def = PeriodBalance
-- | Should accounts be displayed: in the command's default style, hierarchically, or as a flat list ?
data AccountListMode = ALDefault | ALTree | ALFlat deriving (Eq, Show, Data, Typeable)
instance Default AccountListMode where def = ALDefault
-- | Standard options for customising report filtering and output,
-- corresponding to hledger's command-line options and query language
-- arguments. Used in hledger-lib and above.
data ReportOpts = ReportOpts {
begin_ :: Maybe Day
,end_ :: Maybe Day
,period_ :: Maybe (Interval,DateSpan)
,cleared_ :: Bool
,pending_ :: Bool
,uncleared_ :: Bool
,cost_ :: Bool
,depth_ :: Maybe Int
,display_ :: Maybe DisplayExp
,date2_ :: Bool
,empty_ :: Bool
,no_elide_ :: Bool
,real_ :: Bool
,daily_ :: Bool
,weekly_ :: Bool
,monthly_ :: Bool
,quarterly_ :: Bool
,yearly_ :: Bool
,format_ :: Maybe FormatStr
,query_ :: String -- all arguments, as a string
-- register
,average_ :: Bool
,related_ :: Bool
-- balance
,balancetype_ :: BalanceType
,accountlistmode_ :: AccountListMode
,drop_ :: Int
,row_total_ :: Bool
,no_total_ :: Bool
} deriving (Show, Data, Typeable)
instance Default ReportOpts where def = defreportopts
defreportopts :: ReportOpts
defreportopts = ReportOpts
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
def
rawOptsToReportOpts :: RawOpts -> IO ReportOpts
rawOptsToReportOpts rawopts = do
d <- getCurrentDay
return defreportopts{
begin_ = maybesmartdateopt d "begin" rawopts
,end_ = maybesmartdateopt d "end" rawopts
,period_ = maybeperiodopt d rawopts
,cleared_ = boolopt "cleared" rawopts
,pending_ = boolopt "pending" rawopts
,uncleared_ = boolopt "uncleared" rawopts
,cost_ = boolopt "cost" rawopts
,depth_ = maybeintopt "depth" rawopts
,display_ = maybedisplayopt d rawopts
,date2_ = boolopt "date2" rawopts
,empty_ = boolopt "empty" rawopts
,no_elide_ = boolopt "no-elide" rawopts
,real_ = boolopt "real" rawopts
,daily_ = boolopt "daily" rawopts
,weekly_ = boolopt "weekly" rawopts
,monthly_ = boolopt "monthly" rawopts
,quarterly_ = boolopt "quarterly" rawopts
,yearly_ = boolopt "yearly" rawopts
,format_ = maybestringopt "format" rawopts
,query_ = unwords $ listofstringopt "args" rawopts -- doesn't handle an arg like "" right
,average_ = boolopt "average" rawopts
,related_ = boolopt "related" rawopts
,balancetype_ = balancetypeopt rawopts
,accountlistmode_ = accountlistmodeopt rawopts
,drop_ = intopt "drop" rawopts
,row_total_ = boolopt "row-total" rawopts
,no_total_ = boolopt "no-total" rawopts
}
accountlistmodeopt :: RawOpts -> AccountListMode
accountlistmodeopt rawopts =
case reverse $ filter (`elem` ["tree","flat"]) $ map fst rawopts of
("tree":_) -> ALTree
("flat":_) -> ALFlat
_ -> ALDefault
balancetypeopt :: RawOpts -> BalanceType
balancetypeopt rawopts
| length [o | o <- ["cumulative","historical"], isset o] > 1
= optserror "please specify at most one of --cumulative and --historical"
| isset "cumulative" = CumulativeBalance
| isset "historical" = HistoricalBalance
| otherwise = PeriodBalance
where
isset = flip boolopt rawopts
maybesmartdateopt :: Day -> String -> RawOpts -> Maybe Day
maybesmartdateopt d name rawopts =
case maybestringopt name rawopts of
Nothing -> Nothing
Just s -> either
(\e -> optserror $ "could not parse "++name++" date: "++show e)
Just
$ fixSmartDateStrEither' d s
type DisplayExp = String
maybedisplayopt :: Day -> RawOpts -> Maybe DisplayExp
maybedisplayopt d rawopts =
maybe Nothing (Just . regexReplaceBy "\\[.+?\\]" fixbracketeddatestr) $ maybestringopt "display" rawopts
where
fixbracketeddatestr "" = ""
fixbracketeddatestr s = "[" ++ fixSmartDateStr d (init $ tail s) ++ "]"
maybeperiodopt :: Day -> RawOpts -> Maybe (Interval,DateSpan)
maybeperiodopt d rawopts =
case maybestringopt "period" rawopts of
Nothing -> Nothing
Just s -> either
(\e -> optserror $ "could not parse period option: "++show e)
Just
$ parsePeriodExpr d s
-- | Legacy-compatible convenience aliases for accountlistmode_.
tree_ :: ReportOpts -> Bool
tree_ = (==ALTree) . accountlistmode_
flat_ :: ReportOpts -> Bool
flat_ = (==ALFlat) . accountlistmode_
-- | Figure out the date span we should report on, based on any
-- begin/end/period options provided. A period option will cause begin and
-- end options to be ignored.
dateSpanFromOpts :: Day -> ReportOpts -> DateSpan
dateSpanFromOpts _ ReportOpts{..} =
case period_ of Just (_,span) -> span
Nothing -> DateSpan begin_ end_
-- | Figure out the reporting interval, if any, specified by the options.
-- --period overrides --daily overrides --weekly overrides --monthly etc.
intervalFromOpts :: ReportOpts -> Interval
intervalFromOpts ReportOpts{..} =
case period_ of
Just (interval,_) -> interval
Nothing -> i
where i | daily_ = Days 1
| weekly_ = Weeks 1
| monthly_ = Months 1
| quarterly_ = Quarters 1
| yearly_ = Years 1
| otherwise = NoInterval
-- | Get a maybe boolean representing the last cleared/uncleared option if any.
clearedValueFromOpts :: ReportOpts -> Maybe ClearedStatus
clearedValueFromOpts ReportOpts{..} | cleared_ = Just Cleared
| pending_ = Just Pending
| uncleared_ = Just Uncleared
| otherwise = Nothing
-- depthFromOpts :: ReportOpts -> Int
-- depthFromOpts opts = min (fromMaybe 99999 $ depth_ opts) (queryDepth $ queryFromOpts nulldate opts)
-- | Report which date we will report on based on --date2.
whichDateFromOpts :: ReportOpts -> WhichDate
whichDateFromOpts ReportOpts{..} = if date2_ then SecondaryDate else PrimaryDate
-- | Select the Transaction date accessor based on --date2.
transactionDateFn :: ReportOpts -> (Transaction -> Day)
transactionDateFn ReportOpts{..} = if date2_ then transactionDate2 else tdate
-- | Select the Posting date accessor based on --date2.
postingDateFn :: ReportOpts -> (Posting -> Day)
postingDateFn ReportOpts{..} = if date2_ then postingDate2 else postingDate
-- | Convert this journal's postings' amounts to the cost basis amounts if
-- specified by options.
journalSelectingAmountFromOpts :: ReportOpts -> Journal -> Journal
journalSelectingAmountFromOpts opts
| cost_ opts = journalConvertAmountsToCost
| otherwise = id
-- | Convert report options and arguments to a query.
queryFromOpts :: Day -> ReportOpts -> Query
queryFromOpts d opts@ReportOpts{..} = simplifyQuery $ And $ [flagsq, argsq]
where
flagsq = And $
[(if date2_ then Date2 else Date) $ dateSpanFromOpts d opts]
++ (if real_ then [Real True] else [])
++ (if empty_ then [Empty True] else []) -- ?
++ (maybe [] ((:[]) . Status) (clearedValueFromOpts opts))
++ (maybe [] ((:[]) . Depth) depth_)
argsq = fst $ parseQuery d query_
-- | Convert report options to a query, ignoring any non-flag command line arguments.
queryFromOptsOnly :: Day -> ReportOpts -> Query
queryFromOptsOnly d opts@ReportOpts{..} = simplifyQuery flagsq
where
flagsq = And $
[(if date2_ then Date2 else Date) $ dateSpanFromOpts d opts]
++ (if real_ then [Real True] else [])
++ (if empty_ then [Empty True] else []) -- ?
++ (maybe [] ((:[]) . Status) (clearedValueFromOpts opts))
++ (maybe [] ((:[]) . Depth) depth_)
tests_queryFromOpts :: [Test]
tests_queryFromOpts = [
"queryFromOpts" ~: do
assertEqual "" Any (queryFromOpts nulldate defreportopts)
assertEqual "" (Acct "a") (queryFromOpts nulldate defreportopts{query_="a"})
assertEqual "" (Desc "a a") (queryFromOpts nulldate defreportopts{query_="desc:'a a'"})
assertEqual "" (Date $ mkdatespan "2012/01/01" "2013/01/01")
(queryFromOpts nulldate defreportopts{begin_=Just (parsedate "2012/01/01")
,query_="date:'to 2013'"
})
assertEqual "" (Date2 $ mkdatespan "2012/01/01" "2013/01/01")
(queryFromOpts nulldate defreportopts{query_="date2:'in 2012'"})
assertEqual "" (Or [Acct "a a", Acct "'b"])
(queryFromOpts nulldate defreportopts{query_="'a a' 'b"})
]
-- | Convert report options and arguments to query options.
queryOptsFromOpts :: Day -> ReportOpts -> [QueryOpt]
queryOptsFromOpts d ReportOpts{..} = flagsqopts ++ argsqopts
where
flagsqopts = []
argsqopts = snd $ parseQuery d query_
tests_queryOptsFromOpts :: [Test]
tests_queryOptsFromOpts = [
"queryOptsFromOpts" ~: do
assertEqual "" [] (queryOptsFromOpts nulldate defreportopts)
assertEqual "" [] (queryOptsFromOpts nulldate defreportopts{query_="a"})
assertEqual "" [] (queryOptsFromOpts nulldate defreportopts{begin_=Just (parsedate "2012/01/01")
,query_="date:'to 2013'"
})
]
tests_Hledger_Reports_ReportOptions :: Test
tests_Hledger_Reports_ReportOptions = TestList $
tests_queryFromOpts
++ tests_queryOptsFromOpts
| kmels/hledger | hledger-lib/Hledger/Reports/ReportOptions.hs | gpl-3.0 | 11,444 | 0 | 16 | 3,121 | 2,599 | 1,404 | 1,195 | 242 | 4 |
module Main where
import GameLogic.Language.RawToken
import GameLogic.Language.Translation.Translator
import GameLogic.Language.Translation.Runtime
import GameLogic.Data.World
import Control.Monad (liftM)
import Control.Monad.State (runState)
import qualified Data.Map as M
import qualified Data.Monoid as Monoid
extractItemMap = liftM (trtObjectTemplateMap . snd)
extractLog = liftM (trtLog . snd)
extractResult = liftM fst
extractWorld = liftM (trtWorld . snd)
tryRight :: Monoid.Monoid m => Either n m -> m
tryRight (Right r) = r
tryRight _ = Monoid.mempty
main = do
tokens <- readFile "./Data/Raws/World3.arf"
let res = toWorld' runState tokens
putStrLn $ unlines . tryRight $ extractLog res
print $ tryRight $ extractItemMap res
print $ extractResult res
print $ extractWorld res
--writeFile "./Data/Raws/World3.adt" (show . extractWorld $ res)
putStrLn "Ok." | graninas/The-Amoeba-World | src/Amoeba/Test/TranslationTest.hs | gpl-3.0 | 912 | 0 | 10 | 159 | 255 | 135 | 120 | 24 | 1 |
import System.Exit
import Test.HUnit
import LambdaMainTest (testMainLoop)
testSuite = TestList [
testMainLoop
]
main = do
counts <- runTestTT testSuite
if errors counts > 0
then exitWith $ ExitFailure 2
else if failures counts > 0
then exitWith $ ExitFailure 1
else exitSuccess
| Sventimir/LambdaShell | testSuite.hs | gpl-3.0 | 328 | 0 | 10 | 93 | 92 | 47 | 45 | 12 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.