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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- © 2002 Peter Thiemann
module WASH.CGI.StateItem where
import Data.Char
--
-- |type of handles to a PE of type @a@
data T a = T String Int | Tvirtual { tvirtual :: a }
instance Show (T a) where
showsPrec _ (T s i) = showChar 'T' . shows s . shows i
showsPrec _ (Tvirtual _) = showChar 'V'
instance Read (T a) where
readsPrec i str =
case dropWhile isSpace str of
'T' : str' ->
[(T s i, str''') | (s, str'') <- reads str', (i, str''') <- reads str'']
'V' : str' ->
[(Tvirtual (error "uninitialized tvirtual"), str')]
_ -> []
| nh2/WashNGo | WASH/CGI/StateItem.hs | bsd-3-clause | 574 | 0 | 13 | 154 | 233 | 123 | 110 | 14 | 0 |
-- |
-- Module: $Header$
-- Description: Implementation of internal command named version
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Implementation of internal command named @version@.
module CommandWrapper.Toolset.InternalSubcommand.Version
( VersionInfo(..)
, PrettyVersion(..)
, version
, versionQQ
, versionSubcommandCompleter
, versionSubcommandDescription
, versionSubcommandHelp
)
where
import Prelude (fromIntegral)
import Control.Applicative ((<*>), (<|>), optional, pure)
import Data.Bool (Bool(True), (||), not, otherwise)
import Data.Foldable (length, null)
import Data.Function (($), (.), const)
import Data.Functor (Functor, (<$>), (<&>), fmap)
import qualified Data.List as List (drop, elem, filter, isPrefixOf, take)
import Data.Maybe (Maybe(Just), fromMaybe)
import Data.Monoid (Endo(Endo, appEndo), mempty)
import Data.Semigroup ((<>))
import Data.String (String, fromString)
import Data.Version (showVersion)
import Data.Word (Word)
import GHC.Generics (Generic)
import System.IO (Handle, IO, IOMode(WriteMode), stdout, withFile)
import Text.Show (Show)
import Data.Monoid.Endo.Fold (foldEndo)
import Data.Output
( OutputFile(OutputFile)
, OutputHandle(OutputHandle, OutputNotHandle)
, OutputStdoutOrFile
, pattern OutputStdoutOnly
)
import Data.Text (Text)
import qualified Data.Text as Text (unlines)
import qualified Data.Text.IO as Text (hPutStr)
import Data.Text.Prettyprint.Doc (Pretty(pretty), (<+>))
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty (AnsiStyle)
import qualified Data.Text.Prettyprint.Doc.Util as Pretty (reflow)
import qualified Dhall
import qualified Dhall.Pretty as Dhall (CharacterSet(Unicode))
import qualified Mainplate (applySimpleDefaults)
import qualified Options.Applicative as Options (Parser, defaultPrefs, info)
import qualified Options.Applicative.Standard as Options (outputOption)
import Safe (atMay, headMay, lastMay)
import CommandWrapper.Core.Completion.FileSystem
( FileSystemOptions
( appendSlashToSingleDirectoryResult
, expandTilde
, prefix
, word
)
, defFileSystemOptions
, fileSystemCompleter
)
--import CommandWrapper.Core.Config.Alias (applyAlias)
import CommandWrapper.Core.Config.Shell (Shell(Bash, Fish, Zsh))
import qualified CommandWrapper.Core.Config.Shell as Shell (shellOption)
import CommandWrapper.Core.Dhall as Dhall (hPut)
import CommandWrapper.Core.Environment (AppNames(AppNames, usedName))
import CommandWrapper.Core.Help.Pretty
( globalOptionsHelp
, helpOptions
, longOption
, longOptionWithArgument
, metavar
, optionDescription
, section
, shortOption
, toolsetCommand
, usageSection
)
import CommandWrapper.Core.Message (Result, out)
import CommandWrapper.Toolset.Config.Global
( Config(Config, colourOutput, verbosity)
)
import CommandWrapper.Toolset.InternalSubcommand.Utils (runMain)
import qualified CommandWrapper.Toolset.InternalSubcommand.Utils as Options
( dhallFlag
, helpFlag
)
import CommandWrapper.Toolset.InternalSubcommand.Version.Info
( PrettyVersion(..)
, VersionInfo(..)
, VersionInfoField(..)
, versionQQ
)
import qualified CommandWrapper.Toolset.Options.Optparse as Options
( internalSubcommandParse
)
data VersionMode a
= FullVersion OutputFormat OutputStdoutOrFile a
| NumericVersion (Maybe VersionInfoField) OutputStdoutOrFile a
| VersionHelp a
deriving stock (Functor, Generic, Show)
data OutputFormat
= PlainFormat
| DhallFormat
| ShellFormat Shell
deriving stock (Generic, Show)
version
:: VersionInfo
-> AppNames
-> [String]
-> Config
-> IO ()
version versionInfo appNames options config =
runMain (parseOptions appNames config options) defaults \case
FullVersion format output Config{colourOutput, verbosity} -> do
withOutputHandle output \handle -> case format of
DhallFormat ->
Dhall.hPut colourOutput Dhall.Unicode handle Dhall.inject
versionInfo
ShellFormat shell ->
(\f -> Text.hPutStr handle $ f versionInfo) case shell of
Bash -> versionInfoBash
Fish -> versionInfoFish
Zsh -> versionInfoBash -- Same syntax as Bash.
PlainFormat ->
out verbosity colourOutput handle
(versionInfoDoc versionInfo)
NumericVersion _field output Config{colourOutput, verbosity} -> do
withOutputHandle output \handle ->
out verbosity colourOutput handle "TODO: Implement"
VersionHelp config'@Config{colourOutput, verbosity} -> do
out verbosity colourOutput stdout
(versionSubcommandHelp appNames config')
where
defaults = Mainplate.applySimpleDefaults
(FullVersion PlainFormat OutputStdoutOnly config)
withOutputHandle :: OutputStdoutOrFile -> (Handle -> IO a) -> IO a
withOutputHandle = \case
OutputHandle _ -> ($ stdout)
OutputNotHandle (OutputFile fn) -> withFile fn WriteMode
versionInfoDoc :: VersionInfo -> Pretty.Doc (Result Pretty.AnsiStyle)
versionInfoDoc VersionInfo{..} = Pretty.vsep
[ "Command Wrapper Tool:" <+> pretty commandWrapper
, "Subcommand Protocol: " <+> pretty subcommandProtocol
, "Dhall Library: " <+> pretty dhallLibrary
, "Dhall Standard: " <+> pretty dhallStandard
, ""
]
versionInfoBash :: VersionInfo -> Text
versionInfoBash VersionInfo{..} = Text.unlines
[ var "TOOL" (showVersion' commandWrapper)
, var "SUBCOMMAND_PROTOCOL" (showVersion' subcommandProtocol)
, var "DHALL_LIBRARY" (showVersion' dhallLibrary)
, var "DHALL_STANDARD" (showVersion' dhallStandard)
]
where
showVersion' = fromString . showVersion . rawVersion
var n v = "COMMAND_WRAPPER_" <> n <> "_VERSION='" <> v <> "'"
versionInfoFish :: VersionInfo -> Text
versionInfoFish VersionInfo{..} = Text.unlines
[ var "TOOL" (showVersion' commandWrapper)
, var "SUBCOMMAND_PROTOCOL" (showVersion' subcommandProtocol)
, var "DHALL_LIBRARY" (showVersion' dhallLibrary)
, var "DHALL_STANDARD" (showVersion' dhallStandard)
]
where
showVersion' = fromString . showVersion . rawVersion
var n v = "set COMMAND_WRAPPER_" <> n <> "_VERSION '" <> v <> "'"
parseOptions :: AppNames -> Config -> [String] -> IO (Endo (VersionMode Config))
parseOptions appNames config options =
execParser $ foldEndo
<$> ( Options.dhallFlag switchToDhallFormat
<|> fmap switchToShellFormat Shell.shellOption
<|> Options.helpFlag switchToHelpMode
)
<*> optional outputOption
where
switchTo f = Endo \case
FullVersion _ o a -> f o a
NumericVersion _ o a -> f o a
VersionHelp a -> f OutputStdoutOnly a
switchToDhallFormat = switchTo (FullVersion DhallFormat)
switchToHelpMode = switchTo (const VersionHelp)
switchToShellFormat f =
let shell = f `appEndo` Bash
in switchTo (FullVersion (ShellFormat shell))
outputOption :: Options.Parser (Endo (VersionMode Config))
outputOption = Options.outputOption <&> \o -> Endo \case
FullVersion format _ a -> FullVersion format o a
NumericVersion field _ a -> NumericVersion field o a
VersionHelp a -> VersionHelp a
execParser parser =
Options.internalSubcommandParse appNames config "version"
Options.defaultPrefs (Options.info parser mempty) options
versionSubcommandDescription :: String
versionSubcommandDescription = "Display version information."
versionSubcommandHelp
:: AppNames
-> Config
-> Pretty.Doc (Result Pretty.AnsiStyle)
versionSubcommandHelp AppNames{usedName} _config = Pretty.vsep
[ Pretty.reflow (fromString versionSubcommandDescription)
, ""
, usageSection usedName
[ "version"
<+> Pretty.brackets
( longOption "dhall"
<> "|" <> longOptionWithArgument "shell" "SHELL"
-- <> "|" <> longOptionWithArgument "numeric" "COMPONENT"
)
<+> Pretty.brackets (longOption "output" <> "=" <> metavar "FILE")
, "version" <+> helpOptions
, "help version"
, Pretty.braces (longOption "version" <> "|" <> shortOption 'V')
]
, section "Options:"
[ optionDescription ["--dhall"]
[ Pretty.reflow "Print version information in Dhall format."
]
, optionDescription ["--shell=SHELL"]
[ Pretty.reflow
"Print version information in format suitable for SHELL."
]
, optionDescription ["--output=FILE", "--output FILE", "-o FILE"]
[ Pretty.reflow "Write optput into", metavar "FILE"
, Pretty.reflow "instead of standard output."
]
-- , optionDescription ["--numeric=COMPONENT"]
-- [ Pretty.reflow "Print version of ", metavar "COMPONENT"
-- , Pretty.reflow " in machine readable form."
-- ]
, optionDescription ["--help", "-h"]
[ Pretty.reflow "Print this help and exit. Same as"
, Pretty.squotes (toolsetCommand usedName "help version") <> "."
]
, globalOptionsHelp usedName
]
, ""
]
versionSubcommandCompleter
:: AppNames
-> Config
-> Shell
-> Word
-> [String]
-> IO [String]
versionSubcommandCompleter _appNames _config _shell index words
| Just "-o" <- lastMay wordsBeforePattern =
fsCompleter ""
| Just "--output" <- lastMay wordsBeforePattern =
fsCompleter ""
| null pat =
pure versionOptions
| "--shell=" `List.isPrefixOf` pat =
pure $ List.filter (pat `List.isPrefixOf`) shellOptions
| "--output=" `List.isPrefixOf` pat =
fsCompleter "--output="
| Just '-' <- headMay pat =
pure case List.filter (pat `List.isPrefixOf`) versionOptions of
["--shell="] -> shellOptions
opts -> opts
| otherwise =
pure []
where
wordsBeforePattern = List.take (fromIntegral index) words
pat = fromMaybe "" $ atMay words (fromIntegral index)
hadHelp =
("--help" `List.elem` wordsBeforePattern)
|| ("-h" `List.elem` wordsBeforePattern)
hadDhall = "--dhall" `List.elem` wordsBeforePattern
hadShell =
not . null
$ List.filter ("--shell=" `List.isPrefixOf`) wordsBeforePattern
versionOptions =
munless (hadDhall || hadShell || hadHelp)
["--help", "-h", "--dhall", "--shell="]
<> munless hadHelp ["-o", "--output="]
shellOptions = ("--shell=" <>) <$> ["bash", "fish", "zsh"]
munless p x = if not p then x else mempty
fsCompleter prefix =
fileSystemCompleter defFileSystemOptions
{ appendSlashToSingleDirectoryResult = True
, expandTilde = not (null prefix)
, prefix
, word = List.drop (length prefix) pat
}
| trskop/command-wrapper | command-wrapper/src/CommandWrapper/Toolset/InternalSubcommand/Version.hs | bsd-3-clause | 11,390 | 0 | 21 | 2,759 | 2,729 | 1,528 | 1,201 | -1 | -1 |
module Main (main) where
import Cudd
import Prop
import Control.Monad (guard)
import Data.List (sort)
import System.Mem (performGC)
import Text.Printf (printf)
isPermutationOf :: [Int] -> [Int] -> Bool
isPermutationOf vs vs' = sort vs == sort vs'
implies :: Prop -> Prop -> Prop
implies p q = PNot p `POr` q
conjoin = foldl PAnd PTrue
disjoin = foldl POr PFalse
-- Returns a proposition representing the nxn board with values specified
-- in row-major order according to perm.
modelBoard :: Int -> [Int] -> Prop
modelBoard n perm
| not (isPermutationOf perm [0..n * n - 1]) =
error "modelBoard: given board is not a permutation"
| otherwise = cellAssigns
where
numVals = n * n
vals = [0..n*n-1]
cells = [(i, j) | i <- [0..n-1], j <- [0..n-1]]
idxToCell 0 = (0, 0)
idxToCell i = i `divMod` (numVals * i * n)
cellHasVal (i, j) v = PVar (numVals * (i * n + j) + v)
cellAssigns = conjoin $ do
(i, v) <- zip [0..] perm
v' <- vals
let p = cellHasVal (idxToCell i) v'
return $ if v == v' then p else PNot p
-- Returns a proposition representing all valid nxn boards.
modelBoards :: Int -> Prop
modelBoards n
| n <= 0 = error "modelBoard: n is not positive"
| otherwise =
let numVals = n*n
vals = [0..n*n-1]
cells = [(i, j) | i <- [0..n-1], j <- [0..n-1]]
-- One variable per possible value ([0..n*n-1]) per cell
cellHasVal (i, j) v = PVar (numVals * (i * n + j) + v)
cellAtLeastOne c = disjoin [ cellHasVal c v | v <- vals ]
cellAtMostOne c =
conjoin [ cellHasVal c v `implies` PNot (cellHasVal c v') |
v <- vals, v' <- vals, v /= v' ]
cellsUnique = conjoin $ do
c <- cells
c' <- cells
guard (c /= c')
v <- vals
return $ cellHasVal c v `implies` PNot (cellHasVal c' v)
in conjoin ([cellAtLeastOne c `PAnd` cellAtMostOne c | c <- cells] ++
[cellsUnique])
main :: IO ()
main = do
let startPerm = [9, 11, 10, 15, 12, 7, 8, 3, 13, 6, 14, 4, 5, 1, 0, 2]
-- let goalPerm = [0..15]
mgr <- newMgr
do oldNodeLimit <- nodeLimit mgr
setNodeLimit mgr 20000000
newNodeLimit <- nodeLimit mgr
printf "changed node limit from %d to %d\n" oldNodeLimit newNodeLimit
-- enableDynamicReordering mgr cudd_reorder_window3
-- enableDynamicReordering mgr cudd_reorder_sift
-- enableReorderingReporting mgr
startBoard <- synthesizeBdd mgr (modelBoard 4 startPerm)
-- goalBoard <- modelBoard goalPerm
performGC
printf "%d BDD variables\n" =<< numVars mgr
printf "%d BDD nodes\n" =<< numNodes mgr
printf "startBoard has %.0f minterms\n" =<< bddCountMinterms startBoard
printf "startBoard has %d BDD nodes\n" =<< bddNumNodes startBoard
-- printf "goalBoard has %d minterms\n" =<< bddCountMinterms goalBoard
| bradlarsen/hs-cudd | test/SlidingTile.hs | bsd-3-clause | 2,917 | 0 | 16 | 808 | 1,011 | 523 | 488 | 63 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE TemplateHaskell #-}
module Mapnik.Color (
Color(..)
, parse
, toText
, colorParser
) where
import Mapnik.Imports
import Mapnik.Util
import Data.Monoid
import Data.Word
import Data.Text (Text)
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.Builder.Int as B
import qualified Data.Text.Lazy.Builder.RealFloat as B
import Data.Attoparsec.Text hiding (parse)
data Color = RGBA !Word8 !Word8 !Word8 !Word8
deriving (Eq, Show, Generic)
deriveMapnikJSON ''Color
parse :: Text -> Either String Color
parse = parseOnly (colorParser <* endOfInput)
colorParser :: Parser Color
--TODO Hex parser
colorParser = choice (rgb:rgba:namedColors) where
rgb = "rgb" *> bracketed (do
[r,g,b] <- sepByCommas decimal
pure (RGBA r g b 255)
)
rgba = "rgba" *> bracketed (do
r <- decimal <* commaWs
g <- decimal <* commaWs
b <- decimal <* commaWs
a <- cppDouble
pure (RGBA r g b (round (a*255)))
)
namedColors :: [Parser Color]
namedColors = ("transparent" *> pure (RGBA 0 0 0 0)) :
map (\(c,(r,g,b)) -> c *> pure (RGBA r g b 255))
[ ("aliceblue", (240, 248, 255))
, ("antiquewhite", (250, 235, 215))
, ("aqua", (0, 255, 255))
, ("aquamarine", (127, 255, 212))
, ("azure", (240, 255, 255))
, ("beige", (245, 245, 220))
, ("bisque", (255, 228, 196))
, ("black", (0, 0, 0))
, ("blanchedalmond", (255,235,205))
, ("blue", (0, 0, 255))
, ("blueviolet", (138, 43, 226))
, ("brown", (165, 42, 42))
, ("burlywood", (222, 184, 135))
, ("cadetblue", (95, 158, 160))
, ("chartreuse", (127, 255, 0))
, ("chocolate", (210, 105, 30))
, ("coral", (255, 127, 80))
, ("cornflowerblue", (100, 149, 237))
, ("cornsilk", (255, 248, 220))
, ("crimson", (220, 20, 60))
, ("cyan", (0, 255, 255))
, ("darkblue", (0, 0, 139))
, ("darkcyan", (0, 139, 139))
, ("darkgoldenrod", (184, 134, 11))
, ("darkgray", (169, 169, 169))
, ("darkgreen", (0, 100, 0))
, ("darkgrey", (169, 169, 169))
, ("darkkhaki", (189, 183, 107))
, ("darkmagenta", (139, 0, 139))
, ("darkolivegreen", (85, 107, 47))
, ("darkorange", (255, 140, 0))
, ("darkorchid", (153, 50, 204))
, ("darkred", (139, 0, 0))
, ("darksalmon", (233, 150, 122))
, ("darkseagreen", (143, 188, 143))
, ("darkslateblue", (72, 61, 139))
, ("darkslategrey", (47, 79, 79))
, ("darkturquoise", (0, 206, 209))
, ("darkviolet", (148, 0, 211))
, ("deeppink", (255, 20, 147))
, ("deepskyblue", (0, 191, 255))
, ("dimgray", (105, 105, 105))
, ("dimgrey", (105, 105, 105))
, ("dodgerblue", (30, 144, 255))
, ("firebrick", (178, 34, 34))
, ("floralwhite", (255, 250, 240))
, ("forestgreen", (34, 139, 34))
, ("fuchsia", (255, 0, 255))
, ("gainsboro", (220, 220, 220))
, ("ghostwhite", (248, 248, 255))
, ("gold", (255, 215, 0))
, ("goldenrod", (218, 165, 32))
, ("gray", (128, 128, 128))
, ("grey", (128, 128, 128))
, ("green", (0, 128, 0))
, ("greenyellow", (173, 255, 47))
, ("honeydew", (240, 255, 240))
, ("hotpink", (255, 105, 180))
, ("indianred", (205, 92, 92))
, ("indigo", (75, 0, 130))
, ("ivory", (255, 255, 240))
, ("khaki", (240, 230, 140))
, ("lavender", (230, 230, 250))
, ("lavenderblush", (255, 240, 245))
, ("lawngreen", (124, 252, 0))
, ("lemonchiffon", (255, 250, 205))
, ("lightblue", (173, 216, 230))
, ("lightcoral", (240, 128, 128))
, ("lightcyan", (224, 255, 255))
, ("lightgoldenrodyellow", (250, 250, 210))
, ("lightgray", (211, 211, 211))
, ("lightgreen", (144, 238, 144))
, ("lightgrey", (211, 211, 211))
, ("lightpink", (255, 182, 193))
, ("lightsalmon", (255, 160, 122))
, ("lightseagreen", (32, 178, 170))
, ("lightskyblue", (135, 206, 250))
, ("lightslategray", (119, 136, 153))
, ("lightslategrey", (119, 136, 153))
, ("lightsteelblue", (176, 196, 222))
, ("lightyellow", (255, 255, 224))
, ("lime", (0, 255, 0))
, ("limegreen", (50, 205, 50))
, ("linen", (250, 240, 230))
, ("magenta", (255, 0, 255))
, ("maroon", (128, 0, 0))
, ("mediumaquamarine", (102, 205, 170))
, ("mediumblue", (0, 0, 205))
, ("mediumorchid", (186, 85, 211))
, ("mediumpurple", (147, 112, 219))
, ("mediumseagreen", (60, 179, 113))
, ("mediumslateblue", (123, 104, 238))
, ("mediumspringgreen", (0, 250, 154))
, ("mediumturquoise", (72, 209, 204))
, ("mediumvioletred", (199, 21, 133))
, ("midnightblue", (25, 25, 112))
, ("mintcream", (245, 255, 250))
, ("mistyrose", (255, 228, 225))
, ("moccasin", (255, 228, 181))
, ("navajowhite", (255, 222, 173))
, ("navy", (0, 0, 128))
, ("oldlace", (253, 245, 230))
, ("olive", (128, 128, 0))
, ("olivedrab", (107, 142, 35))
, ("orange", (255, 165, 0))
, ("orangered", (255, 69, 0))
, ("orchid", (218, 112, 214))
, ("palegoldenrod", (238, 232, 170))
, ("palegreen", (152, 251, 152))
, ("paleturquoise", (175, 238, 238))
, ("palevioletred", (219, 112, 147))
, ("papayawhip", (255, 239, 213))
, ("peachpuff", (255, 218, 185))
, ("peru", (205, 133, 63))
, ("pink", (255, 192, 203))
, ("plum", (221, 160, 221))
, ("powderblue", (176, 224, 230))
, ("purple", (128, 0, 128))
, ("red", (255, 0, 0))
, ("rosybrown", (188, 143, 143))
, ("royalblue", (65, 105, 225))
, ("saddlebrown", (139, 69, 19))
, ("salmon", (250, 128, 114))
, ("sandybrown", (244, 164, 96))
, ("seagreen", (46, 139, 87))
, ("seashell", (255, 245, 238))
, ("sienna", (160, 82, 45))
, ("silver", (192, 192, 192))
, ("skyblue", (135, 206, 235))
, ("slateblue", (106, 90, 205))
, ("slategray", (112, 128, 144))
, ("slategrey", (112, 128, 144))
, ("snow", (255, 250, 250))
, ("springgreen", (0, 255, 127))
, ("steelblue", (70, 130, 180))
, ("tan", (210, 180, 140))
, ("teal", (0, 128, 128))
, ("thistle", (216, 191, 216))
, ("tomato", (255, 99, 71))
, ("turquoise", (64, 224, 208))
, ("violet", (238, 130, 238))
, ("wheat", (245, 222, 179))
, ("white", (255, 255, 255))
, ("whitesmoke", (245, 245, 245))
, ("yellow", (255, 255, 0))
, ("yellowgreen", (154, 205, 50))
]
toText :: Color -> Text
toText (RGBA r g b 255) = toStrict $ toLazyText $
"rgb(" <> B.decimal r <> ", "
<> B.decimal g <> ", "
<> B.decimal b
<> ")"
toText (RGBA r g b a) = toStrict $ toLazyText $
"rgba(" <> B.decimal r <> ", "
<> B.decimal g <> ", "
<> B.decimal b <> ", "
<> B.formatRealFloat B.Fixed (Just 3) (fromIntegral a / 255 :: Float)
<> ")"
| albertov/hs-mapnik | pure/src/Mapnik/Color.hs | bsd-3-clause | 7,184 | 0 | 18 | 1,991 | 3,247 | 2,081 | 1,166 | 204 | 1 |
{-# LANGUAGE CPP #-}
module Options.Applicative.Help.Chunk
( mappendWith
, Chunk(..)
, chunked
, listToChunk
, (<<+>>)
, (<</>>)
, vcatChunks
, vsepChunks
, isEmpty
, stringChunk
, paragraph
, extractChunk
, tabulate
) where
import Control.Applicative
import Control.Monad
import Data.Maybe
import Data.Monoid
import Options.Applicative.Help.Pretty
mappendWith :: Monoid a => a -> a -> a -> a
mappendWith s x y = mconcat [x, s, y]
-- | The free monoid on a semigroup 'a'.
newtype Chunk a = Chunk
{ unChunk :: Maybe a }
deriving (Eq, Show)
instance Functor Chunk where
fmap f = Chunk . fmap f . unChunk
instance Applicative Chunk where
pure = Chunk . pure
Chunk f <*> Chunk x = Chunk (f <*> x)
instance Monad Chunk where
return = pure
m >>= f = Chunk $ unChunk m >>= unChunk . f
instance MonadPlus Chunk where
mzero = Chunk mzero
mplus m1 m2 = Chunk $ mplus (unChunk m1) (unChunk m2)
-- | Given a semigroup structure on 'a', return a monoid structure on 'Chunk a'.
--
-- Note that this is /not/ the same as 'liftA2'.
chunked :: (a -> a -> a)
-> Chunk a -> Chunk a -> Chunk a
chunked _ (Chunk Nothing) y = y
chunked _ x (Chunk Nothing) = x
chunked f (Chunk (Just x)) (Chunk (Just y)) = Chunk (Just (f x y))
-- | Concatenate a list into a Chunk. 'listToChunk' satisfies:
--
-- > isEmpty . listToChunk = null
-- > listToChunk = mconcat . fmap pure
listToChunk :: Monoid a => [a] -> Chunk a
listToChunk [] = mempty
listToChunk xs = pure (mconcat xs)
instance Monoid a => Monoid (Chunk a) where
mempty = Chunk Nothing
mappend = chunked mappend
-- | Part of a constrained comonad instance.
--
-- This is the counit of the adjunction between 'Chunk' and the forgetful
-- functor from monoids to semigroups. It satisfies:
--
-- > extractChunk . pure = id
-- > extractChunk . fmap pure = id
extractChunk :: Monoid a => Chunk a -> a
extractChunk = fromMaybe mempty . unChunk
-- we could also define:
-- duplicate :: Monoid a => Chunk a -> Chunk (Chunk a)
-- duplicate = fmap pure
-- | Concatenate two 'Chunk's with a space in between. If one is empty, this
-- just returns the other one.
--
-- Unlike '<+>' for 'Doc', this operation has a unit element, namely the empty
-- 'Chunk'.
(<<+>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<<+>>) = chunked (<+>)
-- | Concatenate two 'Chunk's with a softline in between. This is exactly like
-- '<<+>>', but uses a softline instead of a space.
(<</>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<</>>) = chunked (</>)
-- | Concatenate 'Chunk's vertically.
vcatChunks :: [Chunk Doc] -> Chunk Doc
vcatChunks = foldr (chunked (.$.)) mempty
-- | Concatenate 'Chunk's vertically separated by empty lines.
vsepChunks :: [Chunk Doc] -> Chunk Doc
vsepChunks = foldr (chunked (\x y -> x .$. mempty .$. y)) mempty
-- | Whether a 'Chunk' is empty. Note that something like 'pure mempty' is not
-- considered an empty chunk, even though the underlying 'Doc' is empty.
isEmpty :: Chunk a -> Bool
isEmpty = isNothing . unChunk
-- | Convert a 'String' into a 'Chunk'. This satisfies:
--
-- > isEmpty . stringChunk = null
-- > extractChunk . stringChunk = string
stringChunk :: String -> Chunk Doc
stringChunk "" = mempty
stringChunk s = pure (string s)
-- | Convert a paragraph into a 'Chunk'. The resulting chunk is composed by the
-- words of the original paragraph separated by softlines, so it will be
-- automatically word-wrapped when rendering the underlying document.
--
-- This satisfies:
--
-- > isEmpty . paragraph = null . words
paragraph :: String -> Chunk Doc
paragraph = foldr (chunked (</>)) mempty
. map stringChunk
. words
tabulate' :: Int -> [(Doc, Doc)] -> Chunk Doc
tabulate' _ [] = mempty
tabulate' size table = pure $ vcat
[ indent 2 (fillBreak size key <+> value)
| (key, value) <- table ]
-- | Display pairs of strings in a table.
tabulate :: [(Doc, Doc)] -> Chunk Doc
tabulate = tabulate' 24
| thielema/optparse-applicative | Options/Applicative/Help/Chunk.hs | bsd-3-clause | 3,939 | 0 | 11 | 820 | 978 | 534 | 444 | 73 | 1 |
{--
--- Day 4: The Ideal Stocking Stuffer ---
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
For example:
If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
--- Part Two ---
Now find one that starts with six zeroes.
--}
{-# LANGUAGE OverloadedStrings #-}
module Day4
( answers
) where
import Data.Digest.Pure.MD5
import qualified Data.ByteString.Lazy.Char8 as B
secretKey :: String
secretKey = "bgvyzdsv"
findInt :: [Int] -> String -> Int -> Int
findInt (x:xs) key zeros = let hashKey = secretKey ++ show x
hash = B.pack . show $ md5 (B.pack hashKey)
zs = B.pack . take zeros $ repeat '0'
in if B.isPrefixOf zs hash
then x
else findInt xs key zeros
mine :: Int -> Int
mine = findInt [0..] secretKey
answers :: IO ()
answers = do
putStrLn $ "day 4 part 1 = " ++ show (mine 5)
putStrLn $ "day 4 part 2 = " ++ show (mine 6)
| hlmerscher/advent-of-code-2015 | src/Day4.hs | bsd-3-clause | 1,766 | 0 | 13 | 481 | 241 | 128 | 113 | 20 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Trello.Request (
getBoardById
, getCardById
, getListById
, getMemberById
, getCardsByBoardId
, getListsByBoardId
, getMembersByBoardId
) where
import Trello.Data
import Control.Applicative ((<$>), (<*>))
import Control.Monad hiding (join)
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON (..), Value (..), decode, (.:), (.:?))
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.List
import Network.HTTP.Base
import Network.HTTP.Conduit
import Trello.ApiData
baseUrl = "https://api.trello.com/1/"
boardPath = "boards"
listPath = "lists"
cardPath = "cards"
memberPath = "members"
requestURL = "https://trello.com/1/OAuthGetRequestToken"
accessURL = "https://trello.com/1/OAuthGetAccessToken"
authorizeURL = "https://trello.com/1/OAuthAuthorizeToken"
boardParams = [("lists", "all"), ("members", "all")]
listParams = [("cards", "all")]
cardParams = []
memberParams = []
type HttpParams = [(String, String)]
getBoardById :: MonadIO m => OAuth -> BoardRef -> m ByteString
getBoardById oauth (BoardRef id) = board' oauth [boardPath, id]
getCardById :: MonadIO m => OAuth -> CardRef -> m ByteString
getCardById oauth (CardRef id) = card' oauth [cardPath, id]
getListById :: MonadIO m => OAuth -> ListRef -> m ByteString
getListById oauth (ListRef id) = list' oauth [listPath, id]
getMemberById :: MonadIO m => OAuth -> MemberRef -> m ByteString
getMemberById oauth (MemberRef id) = member' oauth [memberPath, id]
getCardsByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe CardFilter -> m ByteString
getCardsByBoardId oauth (BoardRef id) Nothing = card' oauth [boardPath, id, cardPath]
getCardsByBoardId oauth (BoardRef id) (Just filter) = card' oauth [boardPath, id, cardPath, show filter]
getListsByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe ListFilter -> m ByteString
getListsByBoardId oauth (BoardRef id) Nothing = list' oauth [boardPath, id, listPath]
getListsByBoardId oauth (BoardRef id) (Just filter) = list' oauth [boardPath, id, listPath, show filter]
getMembersByBoardId :: MonadIO m => OAuth -> BoardRef -> Maybe MemberFilter -> m ByteString
getMembersByBoardId oauth (BoardRef id) Nothing = member' oauth [boardPath, id, memberPath]
getMembersByBoardId oauth (BoardRef id) (Just filter) = member' oauth [boardPath, id, memberPath, show filter]
board', card', list', member' :: MonadIO m => OAuth -> [String] -> m ByteString
board' oauth path = api' oauth path boardParams
card' oauth path = api' oauth path cardParams
list' oauth path = api' oauth path listParams
member' oauth path = api' oauth path memberParams
api' :: MonadIO m => OAuth -> [String] -> [(String, String)] -> m ByteString
api' oauth path params = simpleHttp requestURL
where requestURL = baseUrl ++ intercalate "/" path ++ "?" ++ urlEncodeVars (params ++ oauthList oauth)
oauthList :: OAuth -> [(String, String)]
oauthList (OAuth key token) = [("key", key),("token", token)]
| vamega/haskell-trello | src/Trello/Request.hs | bsd-3-clause | 3,115 | 0 | 11 | 580 | 1,010 | 552 | 458 | 59 | 1 |
module FindFlowCover where
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import Data.Array.MArray (getElems)
import Grid (initG, updateCoord, Coord, Direction)
import FindTrails
-- | Solve the Grid used depth wise back tracking search
searchForTrails :: Grid -> [FTrail]
searchForTrails (Grid size endpoints) = runST $ do
gf <- initG (maxCoords size) (map epSource endpoints) (map epSink endpoints)
result <- solveGrid1 gf True (zip endpoints [0,1..])
-- Success continuation
(\_grid route -> return $ SFinished [route])
case result of
SFinished trail -> return trail
SNext -> error "No solution exists"
-- | Solve the Grid used depth wise back tracking search
searchForCover :: Grid -> [FTrail]
searchForCover (Grid size endpoints) = runST $ do
gf <- initG maxBound (map epSource endpoints) (map epSink endpoints)
-- grid <- initBoolG maxBound False
result <- solveGrid1 gf False (zip endpoints [0,1..])
(\grid route -> do
-- Here we are at the bottom of the recursion. We only have the route
-- of the last color.
-- Check whether we have a complete cover.
elems <- getElems grid
let unCovCount = length $ filter not elems
-- I am guessing it is the case that if there is a solution with
-- exactly one square uncovered, then there is no solution with
-- all squares covered.
if unCovCount < 2 then return $ SFinished [route]
-- In this case we would like to show all the routes to see how
-- close we got, but not too often. How to do that?
-- Would need to accumulate the routes.
else return SNext)
case result of
SFinished trail -> return trail
SNext -> error "No solution exists"
where maxBound = maxCoords size
-- | Solve the grid and return solutions as coordinates
--traceTrail :: Grid -> [[Coord]]
traceTrail :: [FTrail] -> [[Coord]]
traceTrail = map (\trail -> scanl updateCoord (fst $ head trail) $ map snd trail)
trailFind :: Grid -> [[Coord]]
trailFind = traceTrail . searchForTrails
trailCover :: Grid -> [[Coord]]
trailCover = traceTrail . searchForCover
| habbler/GridFlowCover | src/FindFlowCover.hs | bsd-3-clause | 2,416 | 0 | 18 | 763 | 511 | 273 | 238 | 33 | 3 |
--------------------------------------------------------------------------------
-- | Pretty print LLVM IR Code.
--
module Llvm.PpLlvm (
-- * Top level LLVM objects.
ppLlvmModule,
ppLlvmComments,
ppLlvmComment,
ppLlvmGlobals,
ppLlvmGlobal,
ppLlvmAliases,
ppLlvmAlias,
ppLlvmMetas,
ppLlvmMeta,
ppLlvmFunctionDecls,
ppLlvmFunctionDecl,
ppLlvmFunctions,
ppLlvmFunction,
) where
#include "HsVersions.h"
import Llvm.AbsSyn
import Llvm.MetaData
import Llvm.Types
import Data.List ( intersperse )
import Outputable
import Unique
import FastString ( sLit )
--------------------------------------------------------------------------------
-- * Top Level Print functions
--------------------------------------------------------------------------------
-- | Print out a whole LLVM module.
ppLlvmModule :: LlvmModule -> SDoc
ppLlvmModule (LlvmModule comments aliases meta globals decls funcs)
= ppLlvmComments comments $+$ newLine
$+$ ppLlvmAliases aliases $+$ newLine
$+$ ppLlvmMetas meta $+$ newLine
$+$ ppLlvmGlobals globals $+$ newLine
$+$ ppLlvmFunctionDecls decls $+$ newLine
$+$ ppLlvmFunctions funcs
-- | Print out a multi-line comment, can be inside a function or on its own
ppLlvmComments :: [LMString] -> SDoc
ppLlvmComments comments = vcat $ map ppLlvmComment comments
-- | Print out a comment, can be inside a function or on its own
ppLlvmComment :: LMString -> SDoc
ppLlvmComment com = semi <+> ftext com
-- | Print out a list of global mutable variable definitions
ppLlvmGlobals :: [LMGlobal] -> SDoc
ppLlvmGlobals ls = vcat $ map ppLlvmGlobal ls
-- | Print out a global mutable variable definition
ppLlvmGlobal :: LMGlobal -> SDoc
ppLlvmGlobal (LMGlobal var@(LMGlobalVar _ _ link x a c) dat) =
let sect = case x of
Just x' -> text ", section" <+> doubleQuotes (ftext x')
Nothing -> empty
align = case a of
Just a' -> text ", align" <+> int a'
Nothing -> empty
rhs = case dat of
Just stat -> ppr stat
Nothing -> ppr (pLower $ getVarType var)
-- Position of linkage is different for aliases.
const_link = case c of
Global -> ppr link <+> text "global"
Constant -> ppr link <+> text "constant"
Alias -> ppr link <+> text "alias"
in ppAssignment var $ const_link <+> rhs <> sect <> align
$+$ newLine
ppLlvmGlobal (LMGlobal var val) = sdocWithDynFlags $ \dflags ->
error $ "Non Global var ppr as global! "
++ showSDoc dflags (ppr var) ++ " " ++ showSDoc dflags (ppr val)
-- | Print out a list of LLVM type aliases.
ppLlvmAliases :: [LlvmAlias] -> SDoc
ppLlvmAliases tys = vcat $ map ppLlvmAlias tys
-- | Print out an LLVM type alias.
ppLlvmAlias :: LlvmAlias -> SDoc
ppLlvmAlias (name, ty)
= char '%' <> ftext name <+> equals <+> text "type" <+> ppr ty
-- | Print out a list of LLVM metadata.
ppLlvmMetas :: [MetaDecl] -> SDoc
ppLlvmMetas metas = vcat $ map ppLlvmMeta metas
-- | Print out an LLVM metadata definition.
ppLlvmMeta :: MetaDecl -> SDoc
ppLlvmMeta (MetaUnamed n m)
= exclamation <> int n <> text " = " <> ppLlvmMetaExpr m
ppLlvmMeta (MetaNamed n m)
= exclamation <> ftext n <> text " = !" <> braces nodes
where
nodes = hcat $ intersperse comma $ map pprNode m
pprNode n = exclamation <> int n
-- | Print out an LLVM metadata value.
ppLlvmMetaExpr :: MetaExpr -> SDoc
ppLlvmMetaExpr (MetaStr s ) = text "metadata !" <> doubleQuotes (ftext s)
ppLlvmMetaExpr (MetaNode n ) = text "metadata !" <> int n
ppLlvmMetaExpr (MetaVar v ) = ppr v
ppLlvmMetaExpr (MetaStruct es) =
text "metadata !{" <> hsep (punctuate comma (map ppLlvmMetaExpr es)) <> char '}'
-- | Print out a list of function definitions.
ppLlvmFunctions :: LlvmFunctions -> SDoc
ppLlvmFunctions funcs = vcat $ map ppLlvmFunction funcs
-- | Print out a function definition.
ppLlvmFunction :: LlvmFunction -> SDoc
ppLlvmFunction (LlvmFunction dec args attrs sec body) =
let attrDoc = ppSpaceJoin attrs
secDoc = case sec of
Just s' -> text "section" <+> (doubleQuotes $ ftext s')
Nothing -> empty
in text "define" <+> ppLlvmFunctionHeader dec args
<+> attrDoc <+> secDoc
$+$ lbrace
$+$ ppLlvmBlocks body
$+$ rbrace
$+$ newLine
$+$ newLine
-- | Print out a function defenition header.
ppLlvmFunctionHeader :: LlvmFunctionDecl -> [LMString] -> SDoc
ppLlvmFunctionHeader (LlvmFunctionDecl n l c r varg p a) args
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align " <> ppr a'
Nothing -> empty
args' = map (\((ty,p),n) -> ppr ty <+> ppSpaceJoin p <+> char '%'
<> ftext n)
(zip p args)
in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <> lparen <>
(hsep $ punctuate comma args') <> ptext varg' <> rparen <> align
-- | Print out a list of function declaration.
ppLlvmFunctionDecls :: LlvmFunctionDecls -> SDoc
ppLlvmFunctionDecls decs = vcat $ map ppLlvmFunctionDecl decs
-- | Print out a function declaration.
-- Declarations define the function type but don't define the actual body of
-- the function.
ppLlvmFunctionDecl :: LlvmFunctionDecl -> SDoc
ppLlvmFunctionDecl (LlvmFunctionDecl n l c r varg p a)
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align" <+> ppr a'
Nothing -> empty
args = hcat $ intersperse (comma <> space) $
map (\(t,a) -> ppr t <+> ppSpaceJoin a) p
in text "declare" <+> ppr l <+> ppr c <+> ppr r <+> char '@' <>
ftext n <> lparen <> args <> ptext varg' <> rparen <> align $+$ newLine
-- | Print out a list of LLVM blocks.
ppLlvmBlocks :: LlvmBlocks -> SDoc
ppLlvmBlocks blocks = vcat $ map ppLlvmBlock blocks
-- | Print out an LLVM block.
-- It must be part of a function definition.
ppLlvmBlock :: LlvmBlock -> SDoc
ppLlvmBlock (LlvmBlock blockId stmts) =
let isLabel (MkLabel _) = True
isLabel _ = False
(block, rest) = break isLabel stmts
ppRest = case rest of
MkLabel id:xs -> ppLlvmBlock (LlvmBlock id xs)
_ -> empty
in ppLlvmBlockLabel blockId
$+$ (vcat $ map ppLlvmStatement block)
$+$ newLine
$+$ ppRest
-- | Print out an LLVM block label.
ppLlvmBlockLabel :: LlvmBlockId -> SDoc
ppLlvmBlockLabel id = pprUnique id <> colon
-- | Print out an LLVM statement.
ppLlvmStatement :: LlvmStatement -> SDoc
ppLlvmStatement stmt =
let ind = (text " " <>)
in case stmt of
Assignment dst expr -> ind $ ppAssignment dst (ppLlvmExpression expr)
Fence st ord -> ind $ ppFence st ord
Branch target -> ind $ ppBranch target
BranchIf cond ifT ifF -> ind $ ppBranchIf cond ifT ifF
Comment comments -> ind $ ppLlvmComments comments
MkLabel label -> ppLlvmBlockLabel label
Store value ptr -> ind $ ppStore value ptr
Switch scrut def tgs -> ind $ ppSwitch scrut def tgs
Return result -> ind $ ppReturn result
Expr expr -> ind $ ppLlvmExpression expr
Unreachable -> ind $ text "unreachable"
Nop -> empty
MetaStmt meta s -> ppMetaStatement meta s
-- | Print out an LLVM expression.
ppLlvmExpression :: LlvmExpression -> SDoc
ppLlvmExpression expr
= case expr of
Alloca tp amount -> ppAlloca tp amount
LlvmOp op left right -> ppMachOp op left right
Call tp fp args attrs -> ppCall tp fp (map MetaVar args) attrs
CallM tp fp args attrs -> ppCall tp fp args attrs
Cast op from to -> ppCast op from to
Compare op left right -> ppCmpOp op left right
Extract vec idx -> ppExtract vec idx
Insert vec elt idx -> ppInsert vec elt idx
GetElemPtr inb ptr indexes -> ppGetElementPtr inb ptr indexes
Load ptr -> ppLoad ptr
Malloc tp amount -> ppMalloc tp amount
Phi tp precessors -> ppPhi tp precessors
Asm asm c ty v se sk -> ppAsm asm c ty v se sk
MExpr meta expr -> ppMetaExpr meta expr
--------------------------------------------------------------------------------
-- * Individual print functions
--------------------------------------------------------------------------------
-- | Should always be a function pointer. So a global var of function type
-- (since globals are always pointers) or a local var of pointer function type.
ppCall :: LlvmCallType -> LlvmVar -> [MetaExpr] -> [LlvmFuncAttr] -> SDoc
ppCall ct fptr args attrs = case fptr of
--
-- if local var function pointer, unwrap
LMLocalVar _ (LMPointer (LMFunction d)) -> ppCall' d
-- should be function type otherwise
LMGlobalVar _ (LMFunction d) _ _ _ _ -> ppCall' d
-- not pointer or function, so error
_other -> error $ "ppCall called with non LMFunction type!\nMust be "
++ " called with either global var of function type or "
++ "local var of pointer function type."
where
ppCall' (LlvmFunctionDecl _ _ cc ret argTy params _) =
let tc = if ct == TailCall then text "tail " else empty
ppValues = ppCommaJoin args
ppArgTy = (ppCommaJoin $ map fst params) <>
(case argTy of
VarArgs -> text ", ..."
FixedArgs -> empty)
fnty = space <> lparen <> ppArgTy <> rparen <> char '*'
attrDoc = ppSpaceJoin attrs
in tc <> text "call" <+> ppr cc <+> ppr ret
<> fnty <+> ppName fptr <> lparen <+> ppValues
<+> rparen <+> attrDoc
ppMachOp :: LlvmMachOp -> LlvmVar -> LlvmVar -> SDoc
ppMachOp op left right =
(ppr op) <+> (ppr (getVarType left)) <+> ppName left
<> comma <+> ppName right
ppCmpOp :: LlvmCmpOp -> LlvmVar -> LlvmVar -> SDoc
ppCmpOp op left right =
let cmpOp
| isInt (getVarType left) && isInt (getVarType right) = text "icmp"
| isFloat (getVarType left) && isFloat (getVarType right) = text "fcmp"
| otherwise = text "icmp" -- Just continue as its much easier to debug
{-
| otherwise = error ("can't compare different types, left = "
++ (show $ getVarType left) ++ ", right = "
++ (show $ getVarType right))
-}
in cmpOp <+> ppr op <+> ppr (getVarType left)
<+> ppName left <> comma <+> ppName right
ppAssignment :: LlvmVar -> SDoc -> SDoc
ppAssignment var expr = ppName var <+> equals <+> expr
ppFence :: Bool -> LlvmSyncOrdering -> SDoc
ppFence st ord =
let singleThread = case st of True -> text "singlethread"
False -> empty
in text "fence" <+> singleThread <+> ppSyncOrdering ord
ppSyncOrdering :: LlvmSyncOrdering -> SDoc
ppSyncOrdering SyncUnord = text "unordered"
ppSyncOrdering SyncMonotonic = text "monotonic"
ppSyncOrdering SyncAcquire = text "acquire"
ppSyncOrdering SyncRelease = text "release"
ppSyncOrdering SyncAcqRel = text "acq_rel"
ppSyncOrdering SyncSeqCst = text "seq_cst"
-- XXX: On x86, vector types need to be 16-byte aligned for aligned access, but
-- we have no way of guaranteeing that this is true with GHC (we would need to
-- modify the layout of the stack and closures, change the storage manager,
-- etc.). So, we blindly tell LLVM that *any* vector store or load could be
-- unaligned. In the future we may be able to guarantee that certain vector
-- access patterns are aligned, in which case we will need a more granular way
-- of specifying alignment.
ppLoad :: LlvmVar -> SDoc
ppLoad var
| isVecPtrVar var = text "load" <+> ppr var <>
comma <+> text "align 1"
| otherwise = text "load" <+> ppr var
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppStore :: LlvmVar -> LlvmVar -> SDoc
ppStore val dst
| isVecPtrVar dst = text "store" <+> ppr val <> comma <+> ppr dst <>
comma <+> text "align 1"
| otherwise = text "store" <+> ppr val <> comma <+> ppr dst
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppCast :: LlvmCastOp -> LlvmVar -> LlvmType -> SDoc
ppCast op from to
= ppr op
<+> ppr (getVarType from) <+> ppName from
<+> text "to"
<+> ppr to
ppMalloc :: LlvmType -> Int -> SDoc
ppMalloc tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "malloc" <+> ppr tp <> comma <+> ppr amount'
ppAlloca :: LlvmType -> Int -> SDoc
ppAlloca tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "alloca" <+> ppr tp <> comma <+> ppr amount'
ppGetElementPtr :: Bool -> LlvmVar -> [LlvmVar] -> SDoc
ppGetElementPtr inb ptr idx =
let indexes = comma <+> ppCommaJoin idx
inbound = if inb then text "inbounds" else empty
in text "getelementptr" <+> inbound <+> ppr ptr <> indexes
ppReturn :: Maybe LlvmVar -> SDoc
ppReturn (Just var) = text "ret" <+> ppr var
ppReturn Nothing = text "ret" <+> ppr LMVoid
ppBranch :: LlvmVar -> SDoc
ppBranch var = text "br" <+> ppr var
ppBranchIf :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppBranchIf cond trueT falseT
= text "br" <+> ppr cond <> comma <+> ppr trueT <> comma <+> ppr falseT
ppPhi :: LlvmType -> [(LlvmVar,LlvmVar)] -> SDoc
ppPhi tp preds =
let ppPreds (val, label) = brackets $ ppName val <> comma <+> ppName label
in text "phi" <+> ppr tp <+> hsep (punctuate comma $ map ppPreds preds)
ppSwitch :: LlvmVar -> LlvmVar -> [(LlvmVar,LlvmVar)] -> SDoc
ppSwitch scrut dflt targets =
let ppTarget (val, lab) = ppr val <> comma <+> ppr lab
ppTargets xs = brackets $ vcat (map ppTarget xs)
in text "switch" <+> ppr scrut <> comma <+> ppr dflt
<+> ppTargets targets
ppAsm :: LMString -> LMString -> LlvmType -> [LlvmVar] -> Bool -> Bool -> SDoc
ppAsm asm constraints rty vars sideeffect alignstack =
let asm' = doubleQuotes $ ftext asm
cons = doubleQuotes $ ftext constraints
rty' = ppr rty
vars' = lparen <+> ppCommaJoin vars <+> rparen
side = if sideeffect then text "sideeffect" else empty
align = if alignstack then text "alignstack" else empty
in text "call" <+> rty' <+> text "asm" <+> side <+> align <+> asm' <> comma
<+> cons <> vars'
ppExtract :: LlvmVar -> LlvmVar -> SDoc
ppExtract vec idx =
text "extractelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr idx
ppInsert :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppInsert vec elt idx =
text "insertelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr (getVarType elt) <+> ppName elt <> comma
<+> ppr idx
ppMetaStatement :: [MetaAnnot] -> LlvmStatement -> SDoc
ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
ppMetaExpr :: [MetaAnnot] -> LlvmExpression -> SDoc
ppMetaExpr meta expr = ppLlvmExpression expr <> ppMetaAnnots meta
ppMetaAnnots :: [MetaAnnot] -> SDoc
ppMetaAnnots meta = hcat $ map ppMeta meta
where
ppMeta (MetaAnnot name e)
= comma <+> exclamation <> ftext name <+>
case e of
MetaNode n -> exclamation <> int n
MetaStruct ms -> exclamation <> braces (ppCommaJoin ms)
other -> exclamation <> braces (ppr other) -- possible?
--------------------------------------------------------------------------------
-- * Misc functions
--------------------------------------------------------------------------------
-- | Blank line.
newLine :: SDoc
newLine = empty
-- | Exclamation point.
exclamation :: SDoc
exclamation = char '!'
| lukexi/ghc-7.8-arm64 | compiler/llvmGen/Llvm/PpLlvm.hs | bsd-3-clause | 16,501 | 0 | 18 | 4,684 | 4,515 | 2,205 | 2,310 | 302 | 14 |
c2n :: Num a => Char -> a
c2n x = case x of
'0' -> 0
'1' -> 1
'2' -> 2
'3' -> 3
'4' -> 4
'5' -> 5
'6' -> 6
'7' -> 7
'8' -> 8
'9' -> 9
main :: IO ()
main = print . sum [c2n x | x <- show (2 ^ 1000)] | tricorder42/project-euler | 16_sum_digits_power/16_sum_digits_power.hs | bsd-3-clause | 277 | 0 | 12 | 141 | 135 | 67 | 68 | 14 | 10 |
module CVSU.Edges
( Orientation(..)
, Edge(..)
, EdgeImage(..)
, allocEdgeImage
, createEdgeImage
) where
import CVSU.Bindings.Types
import CVSU.Bindings.PixelImage
import CVSU.Bindings.Edges
import CVSU.PixelImage
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C.Types
import Foreign.Marshal.Array
import Foreign.Storable
import Data.Maybe
import System.IO.Unsafe
data Orientation = HEdge | VEdge deriving Eq
data Edge =
Edge
{ x :: Int
, y :: Int
, orientation :: Orientation
, value :: Float
} deriving Eq
data EdgeImage =
NullEdge |
EdgeImage
{ edgePtr :: !(ForeignPtr C'edge_image)
, original :: PixelImage
, hstep :: Int
, vstep :: Int
, hmargin :: Int
, vmargin :: Int
, boxWidth :: Int
, boxHeight :: Int
, dx :: Int
, dy :: Int
, hedges :: [[Edge]]
, vedges :: [[Edge]]
}
allocEdgeImage :: IO (Maybe (ForeignPtr C'edge_image))
allocEdgeImage = do
ptr <- c'edge_image_alloc
if ptr /= nullPtr
then do
foreignPtr <- newForeignPtr p'edge_image_free ptr
return $ Just foreignPtr
else do
return Nothing
createEdgeImage :: Int -> Int -> Int -> Int -> Int -> Int -> PixelImage -> IO (EdgeImage)
createEdgeImage hstep vstep hmargin vmargin bwidth blength i = do
e <- allocEdgeImage
if isNothing e
then do
return NullEdge
else do
withForeignPtr (fromJust e) $ \e_ptr ->
withForeignPtr (imagePtr i) $ \i_ptr -> do
r <- c'edge_image_create e_ptr i_ptr
(fromIntegral hstep)
(fromIntegral vstep)
(fromIntegral hmargin)
(fromIntegral vmargin)
(fromIntegral bwidth)
(fromIntegral blength)
if r /= c'SUCCESS
then return NullEdge
else do
r <- c'edge_image_update e_ptr
if r /= c'SUCCESS
then return NullEdge
else ptrToEdgeImage i (fromJust e)
eValue :: Ptr CSChar -> Int -> Float
eValue p o = fromIntegral $ unsafePerformIO $ peek (advancePtr p o)
imageToVEdgeList :: Int -> Int -> Int -> C'pixel_image -> [[Edge]]
imageToVEdgeList step hmargin vmargin
C'pixel_image
{ c'pixel_image'data = d
, c'pixel_image'width = w
, c'pixel_image'height = h
, c'pixel_image'stride = s
} = [[toVEdge d (x,vmargin+y*step,y*(fromIntegral s)+x) | x <- [hmargin..(fromIntegral w)-hmargin-1]] | y <- [0..(fromIntegral h)-1]]
where
toVEdge ptr (x,y,offset) = (Edge x y VEdge $ eValue (castPtr ptr) offset)
imageToHEdgeList :: Int -> Int -> Int -> C'pixel_image -> [[Edge]]
imageToHEdgeList step hmargin vmargin
C'pixel_image
{ c'pixel_image'data = d
, c'pixel_image'width = w
, c'pixel_image'height = h
, c'pixel_image'stride = s
} = [[toHEdge d (hmargin+x*step,y,y*(fromIntegral s)+x) | y <- [vmargin..(fromIntegral h)-vmargin-1]] | x <- [0..(fromIntegral w)-1]]
where
toHEdge ptr (x,y,offset) = (Edge x y HEdge $ eValue (castPtr ptr) offset)
ptrToEdgeImage :: PixelImage -> ForeignPtr C'edge_image -> IO (EdgeImage)
ptrToEdgeImage i fptr = do
withForeignPtr fptr $ \ptr ->
if ptr == nullPtr then return NullEdge
else do
C'edge_image{
c'edge_image'hedges = ih,
c'edge_image'vedges = iv,
c'edge_image'width = w,
c'edge_image'height = h,
c'edge_image'hstep = hs,
c'edge_image'vstep = vs,
c'edge_image'hmargin = hm,
c'edge_image'vmargin = vm,
c'edge_image'box_width = bw,
c'edge_image'box_length = bl,
c'edge_image'dx = dx,
c'edge_image'dy = dy
} <- peek ptr
return $ (EdgeImage fptr i
(fromIntegral hs)
(fromIntegral vs)
(fromIntegral hm)
(fromIntegral vm)
(fromIntegral bw)
(fromIntegral bl)
(fromIntegral dx)
(fromIntegral dy)
(imageToHEdgeList (fromIntegral hs) (fromIntegral (dx+hm)) (fromIntegral (dy+vm)) ih)
(imageToVEdgeList (fromIntegral vs) (fromIntegral (dx+hm)) (fromIntegral (dy+vm)) iv))
| amnipar/hs-cvsu | CVSU/Edges.hs | bsd-3-clause | 3,993 | 0 | 22 | 1,007 | 1,340 | 729 | 611 | 124 | 4 |
import Cookbook.Essential.IO
import Cookbook.Project.Preprocess.Preprocess
import Cookbook.Recipes.Sanitize
import Cookbook.Ingredients.Tupples.Look
import Cookbook.Essential.Continuous
import Cookbook.Ingredients.Lists.Modify
import Cookbook.Ingredients.Lists.Replace
import System.IO
import System.Environment
import System.Directory
getShortName :: String -> String
getShortName x = (rev (before (rev x) '/'))
main = do
(a:b:c:_) <- getArgs
ppFolder <- getHomePath "/.preprocess/"
files_ <- getDirectoryContents $ ppFolder
let files = blacklist files_ [".",".."]
allContents <- mapM filelines (map (ppFolder ++) files)
input <- filelines b
let appropriateParams = gPL (head $ lookList (zip (map getShortName files) allContents) a)
let translated = map ((flip replace) appropriateParams) input
writeFile c (unlines translated)
| natepisarski/WriteUtils | preprocess.hs | bsd-3-clause | 856 | 0 | 17 | 118 | 281 | 146 | 135 | 22 | 1 |
{-# LANGUAGE RankNTypes, TypeOperators, DefaultSignatures #-}
-- | Compare to indexed.Control.Comonad.Indexed (IxComonad)
module MHask.Indexed.Comonad where
import MHask.Arrow
import qualified MHask.Indexed.Functor as MHask
import qualified MHask.Indexed.Duplicate as MHask
import qualified MHask.Indexed.Copointed as MHask
-- | Indexed version of "MHask.Comonad".
-- Dual of "MHask.Indexed.Monad"
--
-- Instances must satisfy the following law:
--
-- > iextract ~<~ iduplicate ≡ identityArrow
-- > imap iextract ~<~ iduplicate ≡ identityArrow
class (MHask.IxDuplicate t, MHask.IxCopointed t) => IxComonad t where
-- | Instances must satisfy the following law:
--
-- > iextend iextract ≡ identityArrow
iextend :: (Monad m, Monad n)
=> (m <~ t j k n) -> (t i j m <~ t i k n)
default iextend ::
(Monad m, Monad n,
Monad (t i j m), Monad (t j k n), Monad (t i k n),
Monad (t i j (t j k n)))
=> (m <~ t j k n) -> (t i j m <~ t i k n)
iextend f = MHask.imap f ~<~ MHask.iduplicate
-- | If you define your IxComonad in terms of iextend and iextract,
-- then you get a free implementation of imap which can
-- be used for IxFunctor.
imapComonad :: (Monad m, Monad n, Monad (t j j n), IxComonad t)
=> (m <~ n) -> (t i j m <~ t i j n)
imapComonad f = iextend (f ~<~ MHask.iextract)
iduplicateComonad :: (Monad m, Monad (t j k m), IxComonad t)
=> t i j (t j k m) <~ t i k m
iduplicateComonad = iextend identityArrow
| DanBurton/MHask | MHask/Indexed/Comonad.hs | bsd-3-clause | 1,470 | 0 | 13 | 316 | 461 | 249 | 212 | 21 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE Safe #-}
module Data.Hexagon.LineDraw (lineDraw) where
import Control.Lens.Review
import Control.Lens.Getter
import Data.Hexagon.Distance
import Data.Hexagon.Types
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
lineDraw :: (HexCoordinate t a, Integral a) => t a -> t a -> Seq (t a)
lineDraw a b =
fmap (view _CoordinateIso) $
lineDrawCube (a ^. re _CoordinateCubeIso) (b ^. re _CoordinateCubeIso)
lineDrawCube :: (Integral t) =>
CubeCoordinate t -> CubeCoordinate t -> Seq (CubeCoordinate t)
lineDrawCube a b =
let n = (fromIntegral $ distance a b) :: Double
a' = fmap fromIntegral a
b' = fmap fromIntegral b
in fmap cubeRound . Seq.fromList $
[cubeLerp a' b' $ 1 / n * i | i <- [0..n]]
cubeLerp :: Num t => CubeCoordinate t -> CubeCoordinate t -> t -> CubeCoordinate t
cubeLerp a b t =
let x' = (a ^. cubeX + (b ^. cubeX - a ^. cubeX) * t)
y' = (a ^. cubeY + (b ^. cubeY - a ^. cubeY) * t)
z' = (a ^. cubeZ + (b ^. cubeZ - a ^. cubeZ) * t)
in _CubeCoordinate # (x', y', z')
--cubeRound' :: (Real a, Integral b) => CubeCoordinate a -> CubeCoordinate b
--cubeRound' = cubeRound . fmap (fromRational . toRational)
cubeRound :: (Integral b) => CubeCoordinate Double -> CubeCoordinate b
cubeRound h =
let r = fmap ((fromIntegral :: Integer -> Double) . round) h
diff = _CubeCoordinate # ( r ^. cubeX - h ^. cubeX
, r ^. cubeY - h ^. cubeY
, r ^. cubeZ - h ^. cubeZ
)
(rx,ry,rz) =
if ((diff ^. cubeX > diff ^. cubeY) &&
(diff ^. cubeX > diff ^. cubeZ))
then (-(r ^. cubeY)-(r ^. cubeZ), r ^. cubeY, r ^. cubeZ)
else if (diff ^. cubeY > diff ^. cubeZ)
then (r ^. cubeX, -(r ^. cubeX)-(r ^. cubeZ), r ^. cubeZ)
else (r ^. cubeX, r ^. cubeY, -(r ^. cubeX)-(r ^. cubeY))
in _CubeCoordinate # (round rx, round ry, round rz)
{-
function cube_round(h):
var rx = round(h.x)
var ry = round(h.y)
var rz = round(h.z)
var x_diff = abs(rx - h.x)
var y_diff = abs(ry - h.y)
var z_diff = abs(rz - h.z)
if x_diff > y_diff and x_diff > z_diff:
rx = -ry-rz
else if y_diff > z_diff:
ry = -rx-rz
else:
rz = -rx-ry
return Cube(rx, ry, rz)
-}
| alios/hexagon | src/Data/Hexagon/LineDraw.hs | bsd-3-clause | 2,463 | 0 | 15 | 779 | 795 | 426 | 369 | 41 | 3 |
import qualified Data.ByteString.Char8 as BLC
import System.Environment (getArgs, getExecutablePath)
import qualified System.Log.Logger as L
import Control.Distributed.Task.TaskSpawning.DeployFullBinary
import Control.Distributed.Task.Types.TaskTypes
import Control.Distributed.Task.Util.Configuration
import Control.Distributed.Task.Util.Logging
import RemoteExecutable
main :: IO ()
main = do
args <- getArgs
case args of
[ioHandling] -> executeFunction (unpackIOHandling ioHandling)
_ -> error "Syntax for relinked task: <ioHandling>\n"
executeFunction :: IOHandling -> IO ()
executeFunction ioHandling = do
initTaskLogging
fullBinaryExecution ioHandling executeF
where
executeF :: Task
executeF = remoteExecutable
initTaskLogging :: IO ()
initTaskLogging = do
conf <- getConfiguration
initLogging L.ERROR L.INFO (_taskLogFile conf)
self <- getExecutablePath
logInfo $ "started task execution for: "++self
| michaxm/task-distribution | object-code-app/RemoteExecutor.hs | bsd-3-clause | 946 | 0 | 12 | 133 | 228 | 125 | 103 | 26 | 2 |
{-# LANGUAGE CPP #-}
-- | Prelude replacement
-- Remember to import Prelude () if using this
module Util.Prelewd ( module Prelude
, module Control.Applicative
, module Control.Monad
, module Data.Bool
, module Data.Eq
, module Data.Foldable
, module Data.Function
, module Data.Int
, module Data.Maybe
, module Data.Monoid
, module Data.Ord
, module Data.Traversable
, module Data.Word
, Indeterminate (..)
, apmap
, ordEq
, mconcat
, minBy
, maxBy
, bool
, iff
, if'
, partition
, head
, last
, init
, tail
, deleteBy
, length
, div
, divMod
, mcast
, mcond
, ifm
, (!)
, (<&>)
, (.)
, (.^)
, (.$)
, ($$)
, null
, reverse
, intersperse
, intercalate
, transpose
, subsequences
, permutations
, foldl1'
, scanl
, scanl1
, scanr
, scanr1
, iterate
, repeat
, replicate
, cycle
, unfoldr
, take
, drop
, splitAt
, takeWhile
, dropWhile
, dropWhileEnd
, span
, break
, stripPrefix
, group
, isPrefixOf
, isSuffixOf
, isInfixOf
, lookup
, filter
, zip
, zipWith
, (++)
, unzip
, sequence
, sequence_
, onBoth
) where
import Prelude ( Int
, Integer
, Float
, Double
, Rational
, Enum (..)
, Bounded (..)
, Num (..)
, Real (..)
, Integral
, Fractional (..)
, Floating (..)
, RealFrac (..)
, RealFloat (..)
, quot
, rem
, mod
, quotRem
, toInteger
, subtract
, even, odd
, gcd
, lcm
, (^)
, (^^)
, fromIntegral
, realToFrac
, String
)
import Control.Applicative hiding (optional, some, many)
import Control.Monad hiding (mapM, mapM_, sequence, sequence_, msum, forM, forM_, forever, void)
import Data.Bool
import Data.Either
import Data.Eq
import Data.Fixed
import Data.Foldable hiding (concat, sequence_)
import Data.Function hiding (fix, (.))
import Data.List hiding (head, last, init, tail, partition, length, foldl, foldr, minimumBy, maximumBy, concat, deleteBy, foldr1, filter)
import Data.Int
import Data.Maybe
import Data.Monoid hiding (mconcat)
import Data.Ord
import Data.Traversable hiding (sequence)
import Data.Word
import Test.QuickCheck hiding (Fixed)
import Text.Show
import Util.Impure
#if __GLASGOW_HASKELL__ < 704
instance HasResolution a => Arbitrary (Fixed a) where
arbitrary = realToFrac <$> (arbitrary :: Gen Double)
#endif
-- | Objects with Infinity support
data Indeterminate a = Finite a
| Infinite
deriving (Show, Eq)
instance Ord a => Ord (Indeterminate a) where
compare (Finite _) Infinite = LT
compare Infinite Infinite = EQ
compare Infinite (Finite _) = GT
compare (Finite x) (Finite y) = compare x y
instance Monad Indeterminate where
return = Finite
Infinite >>= _ = Infinite
(Finite x) >>= f = f x
instance MonadPlus Indeterminate where
mzero = empty
mplus = (<|>)
instance Functor Indeterminate where
fmap = apmap
instance Applicative Indeterminate where
pure = return
(<*>) = ap
instance Alternative Indeterminate where
empty = Infinite
Infinite <|> x = x
x <|> _ = x
instance Arbitrary a => Arbitrary (Indeterminate a) where
arbitrary = maybe Infinite Finite <$> arbitrary
-- | Default fmap inmplementation for Monads
apmap :: Applicative f => (a -> b) -> f a -> f b
apmap = (<*>) . pure
-- | Default == implementation for Ords
ordEq :: Ord a => a -> a -> Bool
ordEq x y = compare x y == EQ
-- | Generalized `mconcat`
mconcat :: (Foldable t, Monoid m) => t m -> m
mconcat = foldr (<>) mempty
-- | `min` with user-supplied ordering
minBy :: (a -> a -> Ordering) -> a -> a -> a
minBy f x y = minimumBy f [x, y]
-- | `max` with user-supplied ordering
maxBy :: (a -> a -> Ordering) -> a -> a -> a
maxBy f x y = maximumBy f [x, y]
-- | Process conditionals in the same form as `maybe` and `either`
bool :: a -> a -> Bool -> a
bool f t b = iff b t f
-- | Function synonym for `if.. then.. else ..`
iff :: Bool -> a -> a -> a
iff b t f = if b then t else f
-- | Conditionally apply a transformation function
if' :: Bool -> (a -> a) -> a -> a
if' b f = f >>= iff b
-- | First element of a list
head :: [a] -> Maybe a
head = listToMaybe
-- | Last element of a finite list
last :: [a] -> Maybe a
last = Util.Prelewd.head . reverse
-- | All but the first element of a list
tail :: [a] -> Maybe [a]
tail [] = Nothing
tail (_:xs) = Just xs
-- | All but the last element of a list
init :: [a] -> Maybe [a]
init = Util.Prelewd.tail . reverse
-- | Find and remove the first occurance for which the supplied predicate is true
deleteBy :: (a -> Bool) -> [a] -> Maybe [a]
deleteBy _ [] = Nothing
deleteBy p (x:xs) = iff (p x) (Just xs) $ (x:) <$> deleteBy p xs
infixl 9 !
-- | `x ! i` is the `ith` element of `x`
(!) :: Foldable t => t a -> Integer -> a
(!) l n = case foldl (\v x -> v >>= go x) (Right n) l of
Left x -> x
Right i -> error $ "Foldable index too large by " ++ show (i + 1) ++ "."
where
go x 0 = Left x
go _ k = Right (k - 1)
-- | Split a list into a pair of lists
partition :: (a -> Either b c) -> [a] -> ([b], [c])
partition f = partitionEithers . fmap f
-- | Length of a foldable structure
-- O(n)
length :: (Integral i, Foldable t) => t a -> i
length = foldr (const (+1)) 0
-- | Division with integral result
div :: (Real a, Integral b) => a -> a -> Indeterminate b
div x y = mcond (y /= 0) $ div' x y
-- | `divMod a b = (div a b, mod a b)`
divMod :: (Real a, Integral b) => a -> a -> Indeterminate (b, a)
divMod x y = mcond (y /= 0) $ divMod' x y
-- | Interpret something as a monad
mcast :: MonadPlus m
=> (a -> Bool) -- ^ Casting function
-> a -- ^ Value to cast
-> m a -- ^ `return value` if cast succeeded, `mzero` otherwise
mcast = (mcond =<<)
-- | Conditionally create a monad
mcond :: MonadPlus m
=> Bool -- ^ If this condition is false, mzero.
-- Otherwise, return the value.
-> a -- ^ Value to make into a monad.
-> m a
mcond = ifm .^ return
-- | Conditionally nullify a monad
ifm :: MonadPlus m
=> Bool -- ^ If this condition is false, mzero.
-- Otherwise, return the monad.
-> m a -- ^ Monad to filter
-> m a
ifm = (>>) . guard
infixl 4 <&>
-- | `(<$>)` with arguments interchanged
(<&>) :: Functor f => f a -> (a -> b) -> f b
(<&>) = flip (<$>)
infixl 9 ., .^
infixl 8 .$, $$
-- | `(f . g) x = f (g x)`
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(.) = fmap
-- | `(f .$ g) x y = f x (g y)`
(.^) :: (a -> b -> c) -> (r -> b) -> a -> r -> c
(.^) f g x = f x . g
-- | Composition across two arguments
(.$) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.$) = (.).(.)
-- | (f $$ g) x y = f x y $ g x y
($$) :: (x -> y -> a -> r) -> (x -> y -> a) -> x -> y -> r
($$) f g x = f x <*> g x
-- | Keep only elements which satisfy a predicate
filter :: MonadPlus m => (a -> Bool) -> m a -> m a
filter = mfilter
-- | Collect actions in a traversable structure
sequence :: (Traversable t, Applicative f) => t (f a) -> f (t a)
sequence = sequenceA
-- | Collect actions and discard results
sequence_ :: (Foldable t, Applicative f) => t (f a) -> f ()
sequence_ = sequenceA_
-- | Apply a function across both parameters only if both exist;
-- otherwise default to the extant one
onBoth :: Alternative f => (a -> a -> a) -> f a -> f a -> f a
onBoth f x y = (f <$> x <*> y) <|> x <|> y
| cgaebel/GPG-Chat | src/Util/Prelewd.hs | bsd-3-clause | 9,213 | 4 | 12 | 3,763 | 2,554 | 1,460 | 1,094 | 233 | 3 |
{-# OPTIONS -Wall -Werror -cpp #-}
-- | POSIX time, if you need to deal with timestamps and the like.
-- Most people won't need this module.
module Data.Time.Clock.POSIX
(
posixDayLength,POSIXTime,posixSecondsToUTCTime,utcTimeToPOSIXSeconds,getPOSIXTime
) where
import Data.Time.Clock.UTC
import Data.Time.Calendar.Days
import Data.Fixed
import Control.Monad
#ifdef mingw32_HOST_OS
import Data.Word ( Word64)
import System.Win32.Time
#else
import Data.Time.Clock.CTimeval
#endif
-- | 86400 nominal seconds in every day
posixDayLength :: NominalDiffTime
posixDayLength = 86400
-- | POSIX time is the nominal time since 1970-01-01 00:00 UTC
type POSIXTime = NominalDiffTime
unixEpochDay :: Day
unixEpochDay = ModifiedJulianDay 40587
posixSecondsToUTCTime :: POSIXTime -> UTCTime
posixSecondsToUTCTime i = let
(d,t) = divMod' i posixDayLength
in UTCTime (addDays d unixEpochDay) (realToFrac t)
utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime
utcTimeToPOSIXSeconds (UTCTime d t) =
(fromInteger (diffDays d unixEpochDay) * posixDayLength) + min posixDayLength (realToFrac t)
-- | Get the current POSIX time from the system clock.
getPOSIXTime :: IO POSIXTime
#ifdef mingw32_HOST_OS
-- On Windows, the equlvalent of POSIX time is "file time", defined as
-- the number of 100-nanosecond intervals that have elapsed since
-- 12:00 A.M. January 1, 1601 (UTC). We can convert this into a POSIX
-- time by adjusting the offset to be relative to the POSIX epoch.
getPOSIXTime = do
FILETIME ft <- System.Win32.Time.getSystemTimeAsFileTime
return (fromIntegral (ft - win32_epoch_adjust) / 10000000)
win32_epoch_adjust :: Word64
win32_epoch_adjust = 116444736000000000
#else
-- Use POSIX time
ctimevalToPosixSeconds :: CTimeval -> POSIXTime
ctimevalToPosixSeconds (MkCTimeval s mus) = (fromIntegral s) + (fromIntegral mus) / 1000000
getPOSIXTime = liftM ctimevalToPosixSeconds getCTimeval
#endif
| FranklinChen/hugs98-plus-Sep2006 | packages/time/Data/Time/Clock/POSIX.hs | bsd-3-clause | 1,904 | 4 | 12 | 272 | 291 | 167 | 124 | 25 | 1 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : Tests
-- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
-- |
--
-------------------------------------------------------------------------------
module Main (main) where
import System.Exit (exitFailure)
import Test.QuickCheck.All (quickCheckAll)
import IDE.ImportTool (parseHiddenModule, HiddenModuleResult(..))
import Control.Monad (unless)
import Distribution.Package
(PackageName(..), PackageIdentifier(..))
import Distribution.Version (Version(..))
import Graphics.UI.Gtk (timeoutAddFull, initGUI)
import IDE.TextEditor.Tests (testEditors)
import System.Log.Logger
(errorM, setLevel, rootLoggerName, updateGlobalLogger)
import System.Log (Priority(..))
import Control.Concurrent
(yield, takeMVar, putMVar, newEmptyMVar, threadDelay, forkIO)
import System.Glib.MainLoop (priorityLow)
import Data.Monoid ((<>))
testString = " Could not find module `Graphics.UI.Gtk':\n"
<> " It is a member of the hidden package `gtk-0.11.0'.\n"
<> " Perhaps you need to add `gtk' to the build-depends in your .cabal file.\n"
<> " Use -v to see a list of the files searched for."
prop_parseHiddenModule = parseHiddenModule testString == Just HiddenModuleResult {hiddenModule = "Graphics.UI.Gtk", missingPackage = PackageIdentifier {pkgName = PackageName "gtk", pkgVersion = Version {versionBranch = [0,11,0], versionTags = []}}}
-- At some point the : was removed from this message...
testString2 = " Could not find module `Data.Attoparsec.Lazy'\n"
<> " It is a member of the hidden package `attoparsec-0.10.2.0'.\n"
<> " Perhaps you need to add `attoparsec' to the build-depends in your .cabal file.\n"
<> " Use -v to see a list of the files searched for.\n"
prop_parseHiddenModule2 = parseHiddenModule testString2 == Just HiddenModuleResult {hiddenModule = "Data.Attoparsec.Lazy", missingPackage = PackageIdentifier {pkgName = PackageName "attoparsec", pkgVersion = Version {versionBranch = [0,10,2,0], versionTags = []}}}
-- workaround for issue with $quickcheckall
-- see https://hackage.haskell.org/package/QuickCheck-2.4.2/docs/Test-QuickCheck-All.html
return []
main = do
result <- newEmptyMVar
forkIO $ do
updateGlobalLogger rootLoggerName (setLevel DEBUG)
allPass <- $quickCheckAll -- Run QuickCheck on all prop_ functions
initGUI
timeoutAdd PRIORITY_LOW 10 $ yield >> return True
editorsOk <- testEditors
putMVar result (allPass && editorsOk)
forkIO $ do
threadDelay 60000000
errorM "leksah tests" "Test took too long to run"
putMVar result False
r <- takeMVar result
unless r exitFailure
| JPMoresmau/leksah | tests/Tests.hs | gpl-2.0 | 3,023 | 0 | 13 | 588 | 536 | 308 | 228 | 44 | 1 |
-- Module : Network.AWS.RDS
-- 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.
-- | Amazon Relational Database Service (Amazon RDS) is a web service that makes
-- it easy to set up, operate, and scale a relational database in the cloud. It
-- provides cost-efficient and resizable capacity while managing time-consuming
-- database administration tasks, freeing you up to focus on your applications
-- and business.
module Network.AWS.RDS
( module Network.AWS.RDS.AddSourceIdentifierToSubscription
, module Network.AWS.RDS.AddTagsToResource
, module Network.AWS.RDS.ApplyPendingMaintenanceAction
, module Network.AWS.RDS.AuthorizeDBSecurityGroupIngress
, module Network.AWS.RDS.CopyDBParameterGroup
, module Network.AWS.RDS.CopyDBSnapshot
, module Network.AWS.RDS.CopyOptionGroup
, module Network.AWS.RDS.CreateDBInstance
, module Network.AWS.RDS.CreateDBInstanceReadReplica
, module Network.AWS.RDS.CreateDBParameterGroup
, module Network.AWS.RDS.CreateDBSecurityGroup
, module Network.AWS.RDS.CreateDBSnapshot
, module Network.AWS.RDS.CreateDBSubnetGroup
, module Network.AWS.RDS.CreateEventSubscription
, module Network.AWS.RDS.CreateOptionGroup
, module Network.AWS.RDS.DeleteDBInstance
, module Network.AWS.RDS.DeleteDBParameterGroup
, module Network.AWS.RDS.DeleteDBSecurityGroup
, module Network.AWS.RDS.DeleteDBSnapshot
, module Network.AWS.RDS.DeleteDBSubnetGroup
, module Network.AWS.RDS.DeleteEventSubscription
, module Network.AWS.RDS.DeleteOptionGroup
, module Network.AWS.RDS.DescribeAccountAttributes
, module Network.AWS.RDS.DescribeCertificates
, module Network.AWS.RDS.DescribeDBEngineVersions
, module Network.AWS.RDS.DescribeDBInstances
, module Network.AWS.RDS.DescribeDBLogFiles
, module Network.AWS.RDS.DescribeDBParameterGroups
, module Network.AWS.RDS.DescribeDBParameters
, module Network.AWS.RDS.DescribeDBSecurityGroups
, module Network.AWS.RDS.DescribeDBSnapshots
, module Network.AWS.RDS.DescribeDBSubnetGroups
, module Network.AWS.RDS.DescribeEngineDefaultParameters
, module Network.AWS.RDS.DescribeEventCategories
, module Network.AWS.RDS.DescribeEventSubscriptions
, module Network.AWS.RDS.DescribeEvents
, module Network.AWS.RDS.DescribeOptionGroupOptions
, module Network.AWS.RDS.DescribeOptionGroups
, module Network.AWS.RDS.DescribeOrderableDBInstanceOptions
, module Network.AWS.RDS.DescribePendingMaintenanceActions
, module Network.AWS.RDS.DescribeReservedDBInstances
, module Network.AWS.RDS.DescribeReservedDBInstancesOfferings
, module Network.AWS.RDS.DownloadDBLogFilePortion
, module Network.AWS.RDS.ListTagsForResource
, module Network.AWS.RDS.ModifyDBInstance
, module Network.AWS.RDS.ModifyDBParameterGroup
, module Network.AWS.RDS.ModifyDBSubnetGroup
, module Network.AWS.RDS.ModifyEventSubscription
, module Network.AWS.RDS.ModifyOptionGroup
, module Network.AWS.RDS.PromoteReadReplica
, module Network.AWS.RDS.PurchaseReservedDBInstancesOffering
, module Network.AWS.RDS.RebootDBInstance
, module Network.AWS.RDS.RemoveSourceIdentifierFromSubscription
, module Network.AWS.RDS.RemoveTagsFromResource
, module Network.AWS.RDS.ResetDBParameterGroup
, module Network.AWS.RDS.RestoreDBInstanceFromDBSnapshot
, module Network.AWS.RDS.RestoreDBInstanceToPointInTime
, module Network.AWS.RDS.RevokeDBSecurityGroupIngress
, module Network.AWS.RDS.Types
, module Network.AWS.RDS.Waiters
) where
import Network.AWS.RDS.AddSourceIdentifierToSubscription
import Network.AWS.RDS.AddTagsToResource
import Network.AWS.RDS.ApplyPendingMaintenanceAction
import Network.AWS.RDS.AuthorizeDBSecurityGroupIngress
import Network.AWS.RDS.CopyDBParameterGroup
import Network.AWS.RDS.CopyDBSnapshot
import Network.AWS.RDS.CopyOptionGroup
import Network.AWS.RDS.CreateDBInstance
import Network.AWS.RDS.CreateDBInstanceReadReplica
import Network.AWS.RDS.CreateDBParameterGroup
import Network.AWS.RDS.CreateDBSecurityGroup
import Network.AWS.RDS.CreateDBSnapshot
import Network.AWS.RDS.CreateDBSubnetGroup
import Network.AWS.RDS.CreateEventSubscription
import Network.AWS.RDS.CreateOptionGroup
import Network.AWS.RDS.DeleteDBInstance
import Network.AWS.RDS.DeleteDBParameterGroup
import Network.AWS.RDS.DeleteDBSecurityGroup
import Network.AWS.RDS.DeleteDBSnapshot
import Network.AWS.RDS.DeleteDBSubnetGroup
import Network.AWS.RDS.DeleteEventSubscription
import Network.AWS.RDS.DeleteOptionGroup
import Network.AWS.RDS.DescribeAccountAttributes
import Network.AWS.RDS.DescribeCertificates
import Network.AWS.RDS.DescribeDBEngineVersions
import Network.AWS.RDS.DescribeDBInstances
import Network.AWS.RDS.DescribeDBLogFiles
import Network.AWS.RDS.DescribeDBParameterGroups
import Network.AWS.RDS.DescribeDBParameters
import Network.AWS.RDS.DescribeDBSecurityGroups
import Network.AWS.RDS.DescribeDBSnapshots
import Network.AWS.RDS.DescribeDBSubnetGroups
import Network.AWS.RDS.DescribeEngineDefaultParameters
import Network.AWS.RDS.DescribeEventCategories
import Network.AWS.RDS.DescribeEventSubscriptions
import Network.AWS.RDS.DescribeEvents
import Network.AWS.RDS.DescribeOptionGroupOptions
import Network.AWS.RDS.DescribeOptionGroups
import Network.AWS.RDS.DescribeOrderableDBInstanceOptions
import Network.AWS.RDS.DescribePendingMaintenanceActions
import Network.AWS.RDS.DescribeReservedDBInstances
import Network.AWS.RDS.DescribeReservedDBInstancesOfferings
import Network.AWS.RDS.DownloadDBLogFilePortion
import Network.AWS.RDS.ListTagsForResource
import Network.AWS.RDS.ModifyDBInstance
import Network.AWS.RDS.ModifyDBParameterGroup
import Network.AWS.RDS.ModifyDBSubnetGroup
import Network.AWS.RDS.ModifyEventSubscription
import Network.AWS.RDS.ModifyOptionGroup
import Network.AWS.RDS.PromoteReadReplica
import Network.AWS.RDS.PurchaseReservedDBInstancesOffering
import Network.AWS.RDS.RebootDBInstance
import Network.AWS.RDS.RemoveSourceIdentifierFromSubscription
import Network.AWS.RDS.RemoveTagsFromResource
import Network.AWS.RDS.ResetDBParameterGroup
import Network.AWS.RDS.RestoreDBInstanceFromDBSnapshot
import Network.AWS.RDS.RestoreDBInstanceToPointInTime
import Network.AWS.RDS.RevokeDBSecurityGroupIngress
import Network.AWS.RDS.Types
import Network.AWS.RDS.Waiters
| kim/amazonka | amazonka-rds/gen/Network/AWS/RDS.hs | mpl-2.0 | 6,839 | 0 | 5 | 740 | 925 | 682 | 243 | 121 | 0 |
{-
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Language.C.Clang.Location
( SourceRange()
, rangeStart, rangeEnd
, SourceLocation()
, spellingLocation
, isInSystemHeader
, isFromMainFile
, Location(..)
)
where
import Language.C.Clang.Internal.FFI
import Language.C.Clang.Internal.Types
deriving instance Eq Location
deriving instance Show Location | chpatrick/clang-lens | src/Language/C/Clang/Location.hs | apache-2.0 | 943 | 0 | 5 | 148 | 78 | 52 | 26 | -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="es-ES">
<title>Customizable HTML Report</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>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> | veggiespam/zap-extensions | addOns/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_es_ES/helpset_es_ES.hs | apache-2.0 | 970 | 79 | 66 | 158 | 411 | 208 | 203 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Package
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Defines a package identifier along with a parser and pretty printer for it.
-- 'PackageIdentifier's consist of a name and an exact version. It also defines
-- a 'Dependency' data type. A dependency is a package name and a version
-- range, like @\"foo >= 1.2 && < 2\"@.
module Distribution.Package (
-- * Package ids
PackageName(..),
PackageIdentifier(..),
PackageId,
-- * Package keys/installed package IDs (used for linker symbols)
ComponentId(..),
UnitId(..),
mkUnitId,
mkLegacyUnitId,
getHSLibraryName,
InstalledPackageId, -- backwards compat
-- * ABI hash
AbiHash(..),
-- * Package source dependencies
Dependency(..),
thisPackageVersion,
notThisPackageVersion,
simplifyDependency,
-- * Package classes
Package(..), packageName, packageVersion,
HasUnitId(..),
installedPackageId,
PackageInstalled(..),
) where
import Distribution.Version
( Version(..), VersionRange, anyVersion, thisVersion
, notThisVersion, simplifyVersionRange )
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Distribution.Compat.ReadP
import Distribution.Compat.Binary
import Distribution.Text
import Control.DeepSeq (NFData(..))
import qualified Data.Char as Char
( isDigit, isAlphaNum, )
import Data.Data ( Data )
import Data.List ( intercalate )
import Data.Typeable ( Typeable )
import GHC.Generics (Generic)
import Text.PrettyPrint ((<>), (<+>), text)
newtype PackageName = PackageName { unPackageName :: String }
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
instance Binary PackageName
instance Text PackageName where
disp (PackageName n) = Disp.text n
parse = do
ns <- Parse.sepBy1 component (Parse.char '-')
return (PackageName (intercalate "-" ns))
where
component = do
cs <- Parse.munch1 Char.isAlphaNum
if all Char.isDigit cs then Parse.pfail else return cs
-- each component must contain an alphabetic character, to avoid
-- ambiguity in identifiers like foo-1 (the 1 is the version number).
instance NFData PackageName where
rnf (PackageName pkg) = rnf pkg
-- | Type alias so we can use the shorter name PackageId.
type PackageId = PackageIdentifier
-- | The name and version of a package.
data PackageIdentifier
= PackageIdentifier {
pkgName :: PackageName, -- ^The name of this package, eg. foo
pkgVersion :: Version -- ^the version of this package, eg 1.2
}
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
instance Binary PackageIdentifier
instance Text PackageIdentifier where
disp (PackageIdentifier n v) = case v of
Version [] _ -> disp n -- if no version, don't show version.
_ -> disp n <> Disp.char '-' <> disp v
parse = do
n <- parse
v <- (Parse.char '-' >> parse) <++ return (Version [] [])
return (PackageIdentifier n v)
instance NFData PackageIdentifier where
rnf (PackageIdentifier name version) = rnf name `seq` rnf version
-- ------------------------------------------------------------
-- * Component Source Hash
-- ------------------------------------------------------------
-- | A 'ComponentId' uniquely identifies the transitive source
-- code closure of a component. For non-Backpack components, it also
-- serves as the basis for install paths, symbols, etc.
--
data ComponentId
= ComponentId String
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data)
{-# DEPRECATED InstalledPackageId "Use UnitId instead" #-}
type InstalledPackageId = UnitId
instance Binary ComponentId
instance Text ComponentId where
disp (ComponentId str) = text str
parse = ComponentId `fmap` Parse.munch1 abi_char
where abi_char c = Char.isAlphaNum c || c `elem` "-_."
instance NFData ComponentId where
rnf (ComponentId pk) = rnf pk
-- | Returns library name prefixed with HS, suitable for filenames
getHSLibraryName :: UnitId -> String
getHSLibraryName (SimpleUnitId (ComponentId s)) = "HS" ++ s
-- | For now, there is no distinction between component IDs
-- and unit IDs in Cabal.
newtype UnitId = SimpleUnitId ComponentId
deriving (Generic, Read, Show, Eq, Ord, Typeable, Data, Binary, Text, NFData)
-- | Makes a simple-style UnitId from a string.
mkUnitId :: String -> UnitId
mkUnitId = SimpleUnitId . ComponentId
-- | Make an old-style UnitId from a package identifier
mkLegacyUnitId :: PackageId -> UnitId
mkLegacyUnitId = SimpleUnitId . ComponentId . display
-- ------------------------------------------------------------
-- * Package source dependencies
-- ------------------------------------------------------------
-- | Describes a dependency on a source package (API)
--
data Dependency = Dependency PackageName VersionRange
deriving (Generic, Read, Show, Eq, Typeable, Data)
instance Binary Dependency
instance Text Dependency where
disp (Dependency name ver) =
disp name <+> disp ver
parse = do name <- parse
Parse.skipSpaces
ver <- parse <++ return anyVersion
Parse.skipSpaces
return (Dependency name ver)
thisPackageVersion :: PackageIdentifier -> Dependency
thisPackageVersion (PackageIdentifier n v) =
Dependency n (thisVersion v)
notThisPackageVersion :: PackageIdentifier -> Dependency
notThisPackageVersion (PackageIdentifier n v) =
Dependency n (notThisVersion v)
-- | Simplify the 'VersionRange' expression in a 'Dependency'.
-- See 'simplifyVersionRange'.
--
simplifyDependency :: Dependency -> Dependency
simplifyDependency (Dependency name range) =
Dependency name (simplifyVersionRange range)
-- | Class of things that have a 'PackageIdentifier'
--
-- Types in this class are all notions of a package. This allows us to have
-- different types for the different phases that packages go though, from
-- simple name\/id, package description, configured or installed packages.
--
-- Not all kinds of packages can be uniquely identified by a
-- 'PackageIdentifier'. In particular, installed packages cannot, there may be
-- many installed instances of the same source package.
--
class Package pkg where
packageId :: pkg -> PackageIdentifier
packageName :: Package pkg => pkg -> PackageName
packageName = pkgName . packageId
packageVersion :: Package pkg => pkg -> Version
packageVersion = pkgVersion . packageId
instance Package PackageIdentifier where
packageId = id
-- | Packages that have an installed package ID
class Package pkg => HasUnitId pkg where
installedUnitId :: pkg -> UnitId
{-# DEPRECATED installedPackageId "Use installedUnitId instead" #-}
-- | Compatibility wrapper for pre-Cabal 1.23.
installedPackageId :: HasUnitId pkg => pkg -> UnitId
installedPackageId = installedUnitId
-- | Class of installed packages.
--
-- The primary data type which is an instance of this package is
-- 'InstalledPackageInfo', but when we are doing install plans in Cabal install
-- we may have other, installed package-like things which contain more metadata.
-- Installed packages have exact dependencies 'installedDepends'.
class (HasUnitId pkg) => PackageInstalled pkg where
installedDepends :: pkg -> [UnitId]
-- -----------------------------------------------------------------------------
-- ABI hash
newtype AbiHash = AbiHash String
deriving (Eq, Show, Read, Generic)
instance Binary AbiHash
instance Text AbiHash where
disp (AbiHash abi) = Disp.text abi
parse = fmap AbiHash (Parse.munch Char.isAlphaNum)
| edsko/cabal | Cabal/src/Distribution/Package.hs | bsd-3-clause | 7,999 | 0 | 13 | 1,568 | 1,501 | 835 | 666 | 129 | 1 |
module Servant.Swagger.Internal.TypeLevel (
module Servant.Swagger.Internal.TypeLevel.API,
module Servant.Swagger.Internal.TypeLevel.Every,
module Servant.Swagger.Internal.TypeLevel.TMap,
) where
import Servant.Swagger.Internal.TypeLevel.API
import Servant.Swagger.Internal.TypeLevel.Every
import Servant.Swagger.Internal.TypeLevel.TMap
| dmjio/servant-swagger | src/Servant/Swagger/Internal/TypeLevel.hs | bsd-3-clause | 374 | 0 | 5 | 54 | 62 | 47 | 15 | 7 | 0 |
{-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-}
module Main where
--------------------------------------------------------------------------
-- imports
import Test.QuickCheck
import Text.Show.Functions
import Data.List
( sort
, group
, nub
, (\\)
)
import Control.Monad
( liftM
, liftM2
)
import Data.Maybe
--import Text.Show.Functions
--------------------------------------------------------------------------
-- binary search trees
data Set a
= Node a (Set a) (Set a)
| Empty
deriving ( Eq, Ord, Show )
empty :: Set a
empty = Empty
isEmpty :: Set a -> Bool
isEmpty Empty = True
isEmpty _ = False
unit :: a -> Set a
unit x = Node x empty empty
size :: Set a -> Int
size Empty = 0
size (Node _ s1 s2) = 1 + size s1 + size s2
insert :: Ord a => a -> Set a -> Set a
insert x s = s `union` unit x
merge :: Set a -> Set a -> Set a
s `merge` Empty = s
s `merge` Node x Empty s2 = Node x s s2
s `merge` Node x (Node y s11 s12) s2 = Node y s (Node x (s11 `merge` s12) s2)
delete :: Ord a => a -> Set a -> Set a
delete x Empty = Empty
delete x (Node x' s1 s2) =
case x `compare` x' of
LT -> Node x' (delete x s1) s2
EQ -> s1 `merge` s2
GT -> Node x' s1 (delete x s2)
union :: Ord a => Set a -> Set a -> Set a
{-
s1 `union` Empty = s1
Empty `union` s2 = s2
s1@(Node x s11 s12) `union` s2@(Node y s21 s22) =
case x `compare` y of
LT -> Node x s11 (s12 `union` Node y Empty s22) `union` s21
EQ -> Node x (s11 `union` s21) (s12 `union` s22)
--GT -> s11 `union` Node y s21 (Node x Empty s12 `union` s22)
GT -> Node x (s11 `union` Node y s21 Empty) s12 `union` s22
-}
s1 `union` Empty = s1
Empty `union` s2 = s2
Node x s11 s12 `union` s2 = Node x (s11 `union` s21) (s12 `union` s22)
where
(s21,s22) = split x s2
split :: Ord a => a -> Set a -> (Set a, Set a)
split x Empty = (Empty, Empty)
split x (Node y s1 s2) =
case x `compare` y of
LT -> (s11, Node y s12 s2)
EQ -> (s1, s2)
GT -> (Node y s1 s21, s22)
where
(s11,s12) = split x s1
(s21,s22) = split x s2
mapp :: (a -> b) -> Set a -> Set b
mapp f Empty = Empty
mapp f (Node x s1 s2) = Node (f x) (mapp f s1) (mapp f s2)
fromList :: Ord a => [a] -> Set a
--fromList xs = build [ (empty,x) | x <- sort xs ]
fromList xs = build [ (empty,head x) | x <- group (sort xs) ]
where
build [] = empty
build [(s,x)] = attach x s
build sxs = build (sweep sxs)
sweep [] = []
sweep [sx] = [sx]
sweep ((s1,x1):(s2,x2):sxs) = (Node x1 s1 s2,x2) : sweep sxs
attach x Empty = unit x
attach x (Node y s1 s2) = Node y s1 (attach x s2)
toList :: Set a -> [a]
toList s = toSortedList s
toSortedList :: Set a -> [a]
toSortedList s = toList' s []
where
toList' Empty xs = xs
toList' (Node x s1 s2) xs = toList' s1 (x : toList' s2 xs)
--------------------------------------------------------------------------
-- generators
instance (Ord a, Arbitrary a) => Arbitrary (Set a) where
arbitrary = sized (arbSet Nothing Nothing)
where
arbSet mx my n =
frequency $
[ (1, return Empty) ] ++
[ (7, do mz <- arbitrary `suchThatMaybe` (isOK mx my)
case mz of
Nothing -> return Empty
Just z -> liftM2 (Node z) (arbSet mx mz n2)
(arbSet mz my n2)
where n2 = n `div` 2)
| n > 0
]
isOK mx my z =
maybe True (<z) mx && maybe True (z<) my
shrink Empty = []
shrink t@(Node x s1 s2) = [ s1, s2 ]
++ [ t' | x' <- shrink x, let t' = Node x' s1 s2, invariant t' ]
-- instance (Ord a, ShrinkSub a) => ShrinkSub (Set a)
--------------------------------------------------------------------------
-- properties
(.<) :: Ord a => Set a -> a -> Bool
Empty .< x = True
Node y _ s .< x = y < x && s .< x
(<.) :: Ord a => a -> Set a -> Bool
x <. Empty = True
x <. Node y _ s = x < y && x <. s
(==?) :: Ord a => Set a -> [a] -> Bool
s ==? xs = invariant s && sort (toList s) == nub (sort xs)
invariant :: Ord a => Set a -> Bool
invariant Empty = True
invariant (Node x s1 s2) = s1 .< x && x <. s2 && invariant s1 && invariant s2
prop_Invariant (s :: Set Int) =
invariant s
prop_Empty =
empty ==? ([] :: [Int])
prop_Unit (x :: Int) =
unit x ==? [x]
prop_Size (s :: Set Int) =
cover (size s >= 15) 60 "large" $
size s == length (toList s)
prop_Insert x (s :: Set Int) =
insert x s ==? (x : toList s)
prop_Delete x (s :: Set Int) =
delete x s ==? (toList s \\ [x])
prop_Union s1 (s2 :: Set Int) =
(s1 `union` s2) ==? (toList s1 ++ toList s2)
prop_Mapp (f :: Int -> Int) (s :: Set Int) =
expectFailure $
whenFail (putStrLn ("Fun: " ++ show [ (x,f x) | x <- toList s])) $
mapp f s ==? map f (toList s)
prop_FromList (xs :: [Int]) =
fromList xs ==? xs
prop_ToSortedList (s :: Set Int) =
s ==? xs && xs == sort xs
where
xs = toSortedList s
-- whenFail (putStrLn ("Result: " ++ show (fromList xs))) $
prop_FromList' (xs :: [Int]) =
shrinking shrink xs $ \xs' ->
fromList xs ==? xs
--------------------------------------------------------------------------
-- main
main =
do quickCheck prop_Invariant
quickCheck prop_Empty
quickCheck prop_Unit
quickCheck prop_Size
quickCheck prop_Insert
quickCheck prop_Delete
quickCheck prop_Union
quickCheck prop_Mapp
quickCheck prop_FromList
quickCheck prop_ToSortedList
--------------------------------------------------------------------------
-- the end.
| nh2/quickcheck | examples/Set.hs | bsd-3-clause | 5,702 | 0 | 18 | 1,666 | 2,330 | 1,183 | 1,147 | 139 | 6 |
--
-- (c) The University of Glasgow
--
{-# LANGUAGE DeriveDataTypeable #-}
module Avail (
Avails,
AvailInfo(..),
availsToNameSet,
availsToNameSetWithSelectors,
availsToNameEnv,
availName, availNames, availNonFldNames,
availNamesWithSelectors,
availFlds,
stableAvailCmp
) where
import Name
import NameEnv
import NameSet
import FieldLabel
import Binary
import Outputable
import Util
import Data.Function
-- -----------------------------------------------------------------------------
-- The AvailInfo type
-- | Records what things are "available", i.e. in scope
data AvailInfo = Avail Name -- ^ An ordinary identifier in scope
| AvailTC Name
[Name]
[FieldLabel]
-- ^ A type or class in scope. Parameters:
--
-- 1) The name of the type or class
-- 2) The available pieces of type or class,
-- excluding field selectors.
-- 3) The record fields of the type
-- (see Note [Representing fields in AvailInfo]).
--
-- The AvailTC Invariant:
-- * If the type or class is itself
-- to be in scope, it must be
-- *first* in this list. Thus,
-- typically: @AvailTC Eq [Eq, ==, \/=]@
deriving( Eq )
-- Equality used when deciding if the
-- interface has changed
-- | A collection of 'AvailInfo' - several things that are \"available\"
type Avails = [AvailInfo]
{-
Note [Representing fields in AvailInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When -XDuplicateRecordFields is disabled (the normal case), a
datatype like
data T = MkT { foo :: Int }
gives rise to the AvailInfo
AvailTC T [T, MkT] [FieldLabel "foo" False foo],
whereas if -XDuplicateRecordFields is enabled it gives
AvailTC T [T, MkT] [FieldLabel "foo" True $sel:foo:MkT]
since the label does not match the selector name.
The labels in a field list are not necessarily unique:
data families allow the same parent (the family tycon) to have
multiple distinct fields with the same label. For example,
data family F a
data instance F Int = MkFInt { foo :: Int }
data instance F Bool = MkFBool { foo :: Bool}
gives rise to
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" True $sel:foo:MkFBool].
Moreover, note that the flIsOverloaded flag need not be the same for
all the elements of the list. In the example above, this occurs if
the two data instances are defined in different modules, one with
`-XDuplicateRecordFields` enabled and one with it disabled. Thus it
is possible to have
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" False foo].
If the two data instances are defined in different modules, both
without `-XDuplicateRecordFields`, it will be impossible to export
them from the same module (even with `-XDuplicateRecordfields`
enabled), because they would be represented identically. The
workaround here is to enable `-XDuplicateRecordFields` on the defining
modules.
-}
-- | Compare lexicographically
stableAvailCmp :: AvailInfo -> AvailInfo -> Ordering
stableAvailCmp (Avail n1) (Avail n2) = n1 `stableNameCmp` n2
stableAvailCmp (Avail {}) (AvailTC {}) = LT
stableAvailCmp (AvailTC n ns nfs) (AvailTC m ms mfs) =
(n `stableNameCmp` m) `thenCmp`
(cmpList stableNameCmp ns ms) `thenCmp`
(cmpList (stableNameCmp `on` flSelector) nfs mfs)
stableAvailCmp (AvailTC {}) (Avail {}) = GT
-- -----------------------------------------------------------------------------
-- Operations on AvailInfo
availsToNameSet :: [AvailInfo] -> NameSet
availsToNameSet avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNames avail)
availsToNameSetWithSelectors :: [AvailInfo] -> NameSet
availsToNameSetWithSelectors avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNamesWithSelectors avail)
availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
availsToNameEnv avails = foldr add emptyNameEnv avails
where add avail env = extendNameEnvList env
(zip (availNames avail) (repeat avail))
-- | Just the main name made available, i.e. not the available pieces
-- of type or class brought into scope by the 'GenAvailInfo'
availName :: AvailInfo -> Name
availName (Avail n) = n
availName (AvailTC n _ _) = n
-- | All names made available by the availability information (excluding overloaded selectors)
availNames :: AvailInfo -> [Name]
availNames (Avail n) = [n]
availNames (AvailTC _ ns fs) = ns ++ [ flSelector f | f <- fs, not (flIsOverloaded f) ]
-- | All names made available by the availability information (including overloaded selectors)
availNamesWithSelectors :: AvailInfo -> [Name]
availNamesWithSelectors (Avail n) = [n]
availNamesWithSelectors (AvailTC _ ns fs) = ns ++ map flSelector fs
-- | Names for non-fields made available by the availability information
availNonFldNames :: AvailInfo -> [Name]
availNonFldNames (Avail n) = [n]
availNonFldNames (AvailTC _ ns _) = ns
-- | Fields made available by the availability information
availFlds :: AvailInfo -> [FieldLabel]
availFlds (AvailTC _ _ fs) = fs
availFlds _ = []
-- -----------------------------------------------------------------------------
-- Printing
instance Outputable AvailInfo where
ppr = pprAvail
pprAvail :: AvailInfo -> SDoc
pprAvail (Avail n) = ppr n
pprAvail (AvailTC n ns fs) = ppr n <> braces (hsep (punctuate comma (map ppr ns ++ map (ppr . flLabel) fs)))
instance Binary AvailInfo where
put_ bh (Avail aa) = do
putByte bh 0
put_ bh aa
put_ bh (AvailTC ab ac ad) = do
putByte bh 1
put_ bh ab
put_ bh ac
put_ bh ad
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (Avail aa)
_ -> do ab <- get bh
ac <- get bh
ad <- get bh
return (AvailTC ab ac ad)
| AlexanderPankiv/ghc | compiler/basicTypes/Avail.hs | bsd-3-clause | 6,603 | 0 | 15 | 1,918 | 1,045 | 555 | 490 | 81 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
module TcRnExports (tcRnExports) where
import HsSyn
import PrelNames
import RdrName
import TcRnMonad
import TcEnv
import TcMType
import TcType
import RnNames
import RnEnv
import ErrUtils
import Id
import IdInfo
import Module
import Name
import NameEnv
import NameSet
import Avail
import TyCon
import SrcLoc
import HscTypes
import Outputable
import ConLike
import DataCon
import PatSyn
import FastString
import Maybes
import qualified GHC.LanguageExtensions as LangExt
import Util (capitalise)
import Control.Monad
import DynFlags
import RnHsDoc ( rnHsDoc )
import RdrHsSyn ( setRdrNameSpace )
import Data.Either ( partitionEithers )
{-
************************************************************************
* *
\subsection{Export list processing}
* *
************************************************************************
Processing the export list.
You might think that we should record things that appear in the export
list as ``occurrences'' (using @addOccurrenceName@), but you'd be
wrong. We do check (here) that they are in scope, but there is no
need to slurp in their actual declaration (which is what
@addOccurrenceName@ forces).
Indeed, doing so would big trouble when compiling @PrelBase@, because
it re-exports @GHC@, which includes @takeMVar#@, whose type includes
@ConcBase.StateAndSynchVar#@, and so on...
Note [Exports of data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose you see (Trac #5306)
module M where
import X( F )
data instance F Int = FInt
What does M export? AvailTC F [FInt]
or AvailTC F [F,FInt]?
The former is strictly right because F isn't defined in this module.
But then you can never do an explicit import of M, thus
import M( F( FInt ) )
because F isn't exported by M. Nor can you import FInt alone from here
import M( FInt )
because we don't have syntax to support that. (It looks like an import of
the type FInt.)
At one point I implemented a compromise:
* When constructing exports with no export list, or with module M(
module M ), we add the parent to the exports as well.
* But not when you see module M( f ), even if f is a
class method with a parent.
* Nor when you see module M( module N ), with N /= M.
But the compromise seemed too much of a hack, so we backed it out.
You just have to use an explicit export list:
module M( F(..) ) where ...
-}
data ExportAccum -- The type of the accumulating parameter of
-- the main worker function in rnExports
= ExportAccum
[LIE Name] -- Export items with Names
ExportOccMap -- Tracks exported occurrence names
[AvailInfo] -- The accumulated exported stuff
-- Not nub'd!
emptyExportAccum :: ExportAccum
emptyExportAccum = ExportAccum [] emptyOccEnv []
type ExportOccMap = OccEnv (Name, IE RdrName)
-- Tracks what a particular exported OccName
-- in an export list refers to, and which item
-- it came from. It's illegal to export two distinct things
-- that have the same occurrence name
tcRnExports :: Bool -- False => no 'module M(..) where' header at all
-> Maybe (Located [LIE RdrName]) -- Nothing => no explicit export list
-> TcGblEnv
-> RnM TcGblEnv
-- Complains if two distinct exports have same OccName
-- Warns about identical exports.
-- Complains about exports items not in scope
tcRnExports explicit_mod exports
tcg_env@TcGblEnv { tcg_mod = this_mod,
tcg_rdr_env = rdr_env,
tcg_imports = imports }
= unsetWOptM Opt_WarnWarningsDeprecations $
-- Do not report deprecations arising from the export
-- list, to avoid bleating about re-exporting a deprecated
-- thing (especially via 'module Foo' export item)
do {
-- If the module header is omitted altogether, then behave
-- as if the user had written "module Main(main) where..."
-- EXCEPT in interactive mode, when we behave as if he had
-- written "module Main where ..."
-- Reason: don't want to complain about 'main' not in scope
-- in interactive mode
; dflags <- getDynFlags
; let real_exports
| explicit_mod = exports
| ghcLink dflags == LinkInMemory = Nothing
| otherwise
= Just (noLoc [noLoc (IEVar (noLoc main_RDR_Unqual))])
-- ToDo: the 'noLoc' here is unhelpful if 'main'
-- turns out to be out of scope
; (rn_exports, final_avails)
<- exports_from_avail real_exports rdr_env imports this_mod
; let final_ns = availsToNameSetWithSelectors final_avails
; traceRn "rnExports: Exports:" (ppr final_avails)
; let new_tcg_env =
tcg_env { tcg_exports = final_avails,
tcg_rn_exports = case tcg_rn_exports tcg_env of
Nothing -> Nothing
Just _ -> rn_exports,
tcg_dus = tcg_dus tcg_env `plusDU`
usesOnly final_ns }
; failIfErrsM
; return new_tcg_env }
exports_from_avail :: Maybe (Located [LIE RdrName])
-- Nothing => no explicit export list
-> GlobalRdrEnv
-> ImportAvails
-> Module
-> RnM (Maybe [LIE Name], [AvailInfo])
exports_from_avail Nothing rdr_env _imports _this_mod
-- The same as (module M) where M is the current module name,
-- so that's how we handle it, except we also export the data family
-- when a data instance is exported.
= let avails =
map fix_faminst . gresToAvailInfo
. filter isLocalGRE . globalRdrEnvElts $ rdr_env
in return (Nothing, avails)
where
-- #11164: when we define a data instance
-- but not data family, re-export the family
-- Even though we don't check whether this is actually a data family
-- only data families can locally define subordinate things (`ns` here)
-- without locally defining (and instead importing) the parent (`n`)
fix_faminst (AvailTC n ns flds) =
let new_ns =
case ns of
[] -> [n]
(p:_) -> if p == n then ns else n:ns
in AvailTC n new_ns flds
fix_faminst avail = avail
exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod
= do ExportAccum ie_names _ exports
<- checkNoErrs $ foldAndRecoverM do_litem emptyExportAccum rdr_items
let final_exports = nubAvails exports -- Combine families
return (Just ie_names, final_exports)
where
do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum
do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
-- Maps a parent to its in-scope children
kids_env :: NameEnv [GlobalRdrElt]
kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
imported_modules = [ imv_name imv
| xs <- moduleEnvElts $ imp_mods imports, imv <- xs ]
exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum
exports_from_item acc@(ExportAccum ie_names occs exports)
(L loc (IEModuleContents (L lm mod)))
| let earlier_mods = [ mod
| (L _ (IEModuleContents (L _ mod))) <- ie_names ]
, mod `elem` earlier_mods -- Duplicate export of M
= do { warnIf (Reason Opt_WarnDuplicateExports) True
(dupModuleExport mod) ;
return acc }
| otherwise
= do { let { exportValid = (mod `elem` imported_modules)
|| (moduleName this_mod == mod)
; gre_prs = pickGREsModExp mod (globalRdrEnvElts rdr_env)
; new_exports = map (availFromGRE . fst) gre_prs
; names = map (gre_name . fst) gre_prs
; all_gres = foldr (\(gre1,gre2) gres -> gre1 : gre2 : gres) [] gre_prs
}
; checkErr exportValid (moduleNotImported mod)
; warnIf (Reason Opt_WarnDodgyExports)
(exportValid && null gre_prs)
(nullModuleExport mod)
; traceRn "efa" (ppr mod $$ ppr all_gres)
; addUsedGREs all_gres
; occs' <- check_occs (IEModuleContents (noLoc mod)) occs names
-- This check_occs not only finds conflicts
-- between this item and others, but also
-- internally within this item. That is, if
-- 'M.x' is in scope in several ways, we'll have
-- several members of mod_avails with the same
-- OccName.
; traceRn "export_mod"
(vcat [ ppr mod
, ppr new_exports ])
; return (ExportAccum (L loc (IEModuleContents (L lm mod)) : ie_names)
occs'
(new_exports ++ exports)) }
exports_from_item acc@(ExportAccum lie_names occs exports) (L loc ie)
| isDoc ie
= do new_ie <- lookup_doc_ie ie
return (ExportAccum (L loc new_ie : lie_names) occs exports)
| otherwise
= do (new_ie, avail) <-
setSrcSpan loc $ lookup_ie ie
if isUnboundName (ieName new_ie)
then return acc -- Avoid error cascade
else do
occs' <- check_occs ie occs (availNames avail)
return (ExportAccum (L loc new_ie : lie_names) occs' (avail : exports))
-------------
lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo)
lookup_ie (IEVar (L l rdr))
= do (name, avail) <- lookupGreAvailRn rdr
return (IEVar (L l name), avail)
lookup_ie (IEThingAbs (L l rdr))
= do (name, avail) <- lookupGreAvailRn rdr
return (IEThingAbs (L l name), avail)
lookup_ie ie@(IEThingAll n)
= do
(n, avail, flds) <- lookup_ie_all ie n
let name = unLoc n
return (IEThingAll n, AvailTC name (name:avail) flds)
lookup_ie ie@(IEThingWith l wc sub_rdrs _)
= do
(lname, subs, avails, flds)
<- addExportErrCtxt ie $ lookup_ie_with l sub_rdrs
(_, all_avail, all_flds) <-
case wc of
NoIEWildcard -> return (lname, [], [])
IEWildcard _ -> lookup_ie_all ie l
let name = unLoc lname
return (IEThingWith lname wc subs (map noLoc (flds ++ all_flds)),
AvailTC name (name : avails ++ all_avail)
(flds ++ all_flds))
lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
lookup_ie_with :: Located RdrName -> [Located RdrName]
-> RnM (Located Name, [Located Name], [Name], [FieldLabel])
lookup_ie_with (L l rdr) sub_rdrs
= do name <- lookupGlobalOccRn rdr
(non_flds, flds) <- lookupChildrenExport name sub_rdrs
if isUnboundName name
then return (L l name, [], [name], [])
else return (L l name, non_flds
, map unLoc non_flds
, map unLoc flds)
lookup_ie_all :: IE RdrName -> Located RdrName
-> RnM (Located Name, [Name], [FieldLabel])
lookup_ie_all ie (L l rdr) =
do name <- lookupGlobalOccRn rdr
let gres = findChildren kids_env name
(non_flds, flds) = classifyGREs gres
addUsedKids rdr gres
warnDodgyExports <- woptM Opt_WarnDodgyExports
when (null gres) $
if isTyConName name
then when warnDodgyExports $
addWarn (Reason Opt_WarnDodgyExports)
(dodgyExportWarn name)
else -- This occurs when you export T(..), but
-- only import T abstractly, or T is a synonym.
addErr (exportItemErr ie)
return (L l name, non_flds, flds)
-------------
lookup_doc_ie :: IE RdrName -> RnM (IE Name)
lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
return (IEGroup lev rn_doc)
lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
return (IEDoc rn_doc)
lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
-- In an export item M.T(A,B,C), we want to treat the uses of
-- A,B,C as if they were M.A, M.B, M.C
-- Happily pickGREs does just the right thing
addUsedKids :: RdrName -> [GlobalRdrElt] -> RnM ()
addUsedKids parent_rdr kid_gres = addUsedGREs (pickGREs parent_rdr kid_gres)
classifyGREs :: [GlobalRdrElt] -> ([Name], [FieldLabel])
classifyGREs = partitionEithers . map classifyGRE
classifyGRE :: GlobalRdrElt -> Either Name FieldLabel
classifyGRE gre = case gre_par gre of
FldParent _ Nothing -> Right (FieldLabel (occNameFS (nameOccName n)) False n)
FldParent _ (Just lbl) -> Right (FieldLabel lbl True n)
_ -> Left n
where
n = gre_name gre
isDoc :: IE RdrName -> Bool
isDoc (IEDoc _) = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _) = True
isDoc _ = False
-- Renaming and typechecking of exports happens after everything else has
-- been typechecked.
-- Renaming exports lists is a minefield. Five different things can appear in
-- children export lists ( T(A, B, C) ).
-- 1. Record selectors
-- 2. Type constructors
-- 3. Data constructors
-- 4. Pattern Synonyms
-- 5. Pattern Synonym Selectors
--
-- However, things get put into weird name spaces.
-- 1. Some type constructors are parsed as variables (-.->) for example.
-- 2. All data constructors are parsed as type constructors
-- 3. When there is ambiguity, we default type constructors to data
-- constructors and require the explicit `type` keyword for type
-- constructors.
--
-- This function first establishes the possible namespaces that an
-- identifier might be in (`choosePossibleNameSpaces`).
--
-- Then for each namespace in turn, tries to find the correct identifier
-- there returning the first positive result or the first terminating
-- error.
--
-- Records the result of looking up a child.
data ChildLookupResult
= NameNotFound -- We couldn't find a suitable name
| NameErr ErrMsg -- We found an unambiguous name
-- but there's another error
-- we should abort from
| FoundName Name -- We resolved to a normal name
| FoundFL FieldLabel -- We resolved to a FL
instance Outputable ChildLookupResult where
ppr NameNotFound = text "NameNotFound"
ppr (FoundName n) = text "Found:" <+> ppr n
ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
ppr (NameErr _) = text "Error"
-- Left biased accumulation monoid. Chooses the left-most positive occurence.
instance Monoid ChildLookupResult where
mempty = NameNotFound
NameNotFound `mappend` m2 = m2
NameErr m `mappend` _ = NameErr m -- Abort from the first error
FoundName n1 `mappend` _ = FoundName n1
FoundFL fls `mappend` _ = FoundFL fls
lookupChildrenExport :: Name -> [Located RdrName]
-> RnM ([Located Name], [Located FieldLabel])
lookupChildrenExport parent rdr_items =
do
xs <- mapAndReportM doOne rdr_items
return $ partitionEithers xs
where
-- Pick out the possible namespaces in order of priority
-- This is a consequence of how the parser parses all
-- data constructors as type constructors.
choosePossibleNamespaces :: NameSpace -> [NameSpace]
choosePossibleNamespaces ns
| ns == varName = [varName, tcName]
| ns == tcName = [dataName, tcName]
| otherwise = [ns]
-- Process an individual child
doOne :: Located RdrName
-> RnM (Either (Located Name) (Located FieldLabel))
doOne n = do
let bareName = unLoc n
lkup v = lookupExportChild parent (setRdrNameSpace bareName v)
name <- fmap mconcat . mapM lkup $
(choosePossibleNamespaces (rdrNameSpace bareName))
-- Default to data constructors for slightly better error
-- messages
let unboundName :: RdrName
unboundName = if rdrNameSpace bareName == varName
then bareName
else setRdrNameSpace bareName dataName
case name of
NameNotFound -> Left . L (getLoc n) <$> reportUnboundName unboundName
FoundFL fls -> return $ Right (L (getLoc n) fls)
FoundName name -> return $ Left (L (getLoc n) name)
NameErr err_msg -> reportError err_msg >> failM
-- | Also captures the current context
mkNameErr :: SDoc -> TcM ChildLookupResult
mkNameErr errMsg = do
tcinit <- tcInitTidyEnv
NameErr <$> mkErrTcM (tcinit, errMsg)
-- | Used in export lists to lookup the children.
lookupExportChild :: Name -> RdrName -> RnM ChildLookupResult
lookupExportChild parent rdr_name
| isUnboundName parent
-- Avoid an error cascade
= return (FoundName (mkUnboundNameRdr rdr_name))
| otherwise = do
gre_env <- getGlobalRdrEnv
let original_gres = lookupGRE_RdrName rdr_name gre_env
-- Disambiguate the lookup based on the parent information.
-- The remaining GREs are things that we *could* export here, note that
-- this includes things which have `NoParent`. Those are sorted in
-- `checkPatSynParent`.
traceRn "lookupExportChild original_gres:" (ppr original_gres)
case picked_gres original_gres of
NoOccurence ->
noMatchingParentErr original_gres
UniqueOccurence g ->
checkPatSynParent parent (gre_name g)
DisambiguatedOccurence g ->
checkFld g
AmbiguousOccurence gres ->
mkNameClashErr gres
where
-- Convert into FieldLabel if necessary
checkFld :: GlobalRdrElt -> RnM ChildLookupResult
checkFld g@GRE{gre_name, gre_par} = do
addUsedGRE True g
return $ case gre_par of
FldParent _ mfs -> do
FoundFL (fldParentToFieldLabel gre_name mfs)
_ -> FoundName gre_name
fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
fldParentToFieldLabel name mfs =
case mfs of
Nothing ->
let fs = occNameFS (nameOccName name)
in FieldLabel fs False name
Just fs -> FieldLabel fs True name
-- Called when we fine no matching GREs after disambiguation but
-- there are three situations where this happens.
-- 1. There were none to begin with.
-- 2. None of the matching ones were the parent but
-- a. They were from an overloaded record field so we can report
-- a better error
-- b. The original lookup was actually ambiguous.
-- For example, the case where overloading is off and two
-- record fields are in scope from different record
-- constructors, neither of which is the parent.
noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
noMatchingParentErr original_gres = do
overload_ok <- xoptM LangExt.DuplicateRecordFields
case original_gres of
[] -> return NameNotFound
[g] -> mkDcErrMsg parent (gre_name g) [p | Just p <- [getParent g]]
gss@(g:_:_) ->
if all isRecFldGRE gss && overload_ok
then mkNameErr (dcErrMsg parent "record selector"
(expectJust "noMatchingParentErr" (greLabel g))
[ppr p | x <- gss, Just p <- [getParent x]])
else mkNameClashErr gss
mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
mkNameClashErr gres = do
addNameClashErrRn rdr_name gres
return (FoundName (gre_name (head gres)))
getParent :: GlobalRdrElt -> Maybe Name
getParent (GRE { gre_par = p } ) =
case p of
ParentIs cur_parent -> Just cur_parent
FldParent { par_is = cur_parent } -> Just cur_parent
NoParent -> Nothing
picked_gres :: [GlobalRdrElt] -> DisambigInfo
picked_gres gres
| isUnqual rdr_name = mconcat (map right_parent gres)
| otherwise = mconcat (map right_parent (pickGREs rdr_name gres))
right_parent :: GlobalRdrElt -> DisambigInfo
right_parent p
| Just cur_parent <- getParent p
= if parent == cur_parent
then DisambiguatedOccurence p
else NoOccurence
| otherwise
= UniqueOccurence p
-- This domain specific datatype is used to record why we decided it was
-- possible that a GRE could be exported with a parent.
data DisambigInfo
= NoOccurence
-- The GRE could never be exported. It has the wrong parent.
| UniqueOccurence GlobalRdrElt
-- The GRE has no parent. It could be a pattern synonym.
| DisambiguatedOccurence GlobalRdrElt
-- The parent of the GRE is the correct parent
| AmbiguousOccurence [GlobalRdrElt]
-- For example, two normal identifiers with the same name are in
-- scope. They will both be resolved to "UniqueOccurence" and the
-- monoid will combine them to this failing case.
instance Monoid DisambigInfo where
mempty = NoOccurence
-- This is the key line: We prefer disambiguated occurences to other
-- names.
UniqueOccurence _ `mappend` DisambiguatedOccurence g' = DisambiguatedOccurence g'
DisambiguatedOccurence g' `mappend` UniqueOccurence _ = DisambiguatedOccurence g'
NoOccurence `mappend` m = m
m `mappend` NoOccurence = m
UniqueOccurence g `mappend` UniqueOccurence g' = AmbiguousOccurence [g, g']
UniqueOccurence g `mappend` AmbiguousOccurence gs = AmbiguousOccurence (g:gs)
DisambiguatedOccurence g `mappend` DisambiguatedOccurence g' = AmbiguousOccurence [g, g']
DisambiguatedOccurence g `mappend` AmbiguousOccurence gs = AmbiguousOccurence (g:gs)
AmbiguousOccurence gs `mappend` UniqueOccurence g' = AmbiguousOccurence (g':gs)
AmbiguousOccurence gs `mappend` DisambiguatedOccurence g' = AmbiguousOccurence (g':gs)
AmbiguousOccurence gs `mappend` AmbiguousOccurence gs' = AmbiguousOccurence (gs ++ gs')
--
-- Note: [Typing Pattern Synonym Exports]
-- It proved quite a challenge to precisely specify which pattern synonyms
-- should be allowed to be bundled with which type constructors.
-- In the end it was decided to be quite liberal in what we allow. Below is
-- how Simon described the implementation.
--
-- "Personally I think we should Keep It Simple. All this talk of
-- satisfiability makes me shiver. I suggest this: allow T( P ) in all
-- situations except where `P`'s type is ''visibly incompatible'' with
-- `T`.
--
-- What does "visibly incompatible" mean? `P` is visibly incompatible
-- with
-- `T` if
-- * `P`'s type is of form `... -> S t1 t2`
-- * `S` is a data/newtype constructor distinct from `T`
--
-- Nothing harmful happens if we allow `P` to be exported with
-- a type it can't possibly be useful for, but specifying a tighter
-- relationship is very awkward as you have discovered."
--
-- Note that this allows *any* pattern synonym to be bundled with any
-- datatype type constructor. For example, the following pattern `P` can be
-- bundled with any type.
--
-- ```
-- pattern P :: (A ~ f) => f
-- ```
--
-- So we provide basic type checking in order to help the user out, most
-- pattern synonyms are defined with definite type constructors, but don't
-- actually prevent a library author completely confusing their users if
-- they want to.
--
-- So, we check for exactly four things
-- 1. The name arises from a pattern synonym definition. (Either a pattern
-- synonym constructor or a pattern synonym selector)
-- 2. The pattern synonym is only bundled with a datatype or newtype.
-- 3. Check that the head of the result type constructor is an actual type
-- constructor and not a type variable. (See above example)
-- 4. Is so, check that this type constructor is the same as the parent
-- type constructor.
--
--
-- Note: [Types of TyCon]
--
-- This check appears to be overlly complicated, Richard asked why it
-- is not simply just `isAlgTyCon`. The answer for this is that
-- a classTyCon is also an `AlgTyCon` which we explicitly want to disallow.
-- (It is either a newtype or data depending on the number of methods)
--
-- | Given a resolved name in the children export list and a parent. Decide
-- whether we are allowed to export the child with the parent.
-- Invariant: gre_par == NoParent
-- See note [Typing Pattern Synonym Exports]
checkPatSynParent :: Name -- ^ Type constructor
-> Name -- ^ Either a
-- a) Pattern Synonym Constructor
-- b) A pattern synonym selector
-> TcM ChildLookupResult
checkPatSynParent parent mpat_syn = do
parent_ty_con <- tcLookupTyCon parent
mpat_syn_thing <- tcLookupGlobal mpat_syn
let expected_res_ty =
mkTyConApp parent_ty_con (mkTyVarTys (tyConTyVars parent_ty_con))
handlePatSyn errCtxt =
addErrCtxt errCtxt
. tc_one_ps_export_with expected_res_ty parent_ty_con
-- 1. Check that the Id was actually from a thing associated with patsyns
case mpat_syn_thing of
AnId i
| isId i ->
case idDetails i of
RecSelId { sel_tycon = RecSelPatSyn p } -> handlePatSyn (selErr i) p
_ -> mkDcErrMsg parent mpat_syn []
AConLike (PatSynCon p) -> handlePatSyn (psErr p) p
_ -> mkDcErrMsg parent mpat_syn []
where
psErr = exportErrCtxt "pattern synonym"
selErr = exportErrCtxt "pattern synonym record selector"
assocClassErr :: SDoc
assocClassErr =
text "Pattern synonyms can be bundled only with datatypes."
tc_one_ps_export_with :: TcTauType -- ^ TyCon type
-> TyCon -- ^ Parent TyCon
-> PatSyn -- ^ Corresponding bundled PatSyn
-- and pretty printed origin
-> TcM ChildLookupResult
tc_one_ps_export_with expected_res_ty ty_con pat_syn
-- 2. See note [Types of TyCon]
| not $ isTyConWithSrcDataCons ty_con = mkNameErr assocClassErr
-- 3. Is the head a type variable?
| Nothing <- mtycon = return (FoundName mpat_syn)
-- 4. Ok. Check they are actually the same type constructor.
| Just p_ty_con <- mtycon, p_ty_con /= ty_con = mkNameErr typeMismatchError
-- 5. We passed!
| otherwise = return (FoundName mpat_syn)
where
(_, _, _, _, _, res_ty) = patSynSig pat_syn
mtycon = fst <$> tcSplitTyConApp_maybe res_ty
typeMismatchError :: SDoc
typeMismatchError =
text "Pattern synonyms can only be bundled with matching type constructors"
$$ text "Couldn't match expected type of"
<+> quotes (ppr expected_res_ty)
<+> text "with actual type of"
<+> quotes (ppr res_ty)
{-===========================================================================-}
check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap
check_occs ie occs names -- 'names' are the entities specifed by 'ie'
= foldlM check occs names
where
check occs name
= case lookupOccEnv occs name_occ of
Nothing -> return (extendOccEnv occs name_occ (name, ie))
Just (name', ie')
| name == name' -- Duplicate export
-- But we don't want to warn if the same thing is exported
-- by two different module exports. See ticket #4478.
-> do { warnIf (Reason Opt_WarnDuplicateExports)
(not (dupExport_ok name ie ie'))
(dupExportWarn name_occ ie ie')
; return occs }
| otherwise -- Same occ name but different names: an error
-> do { global_env <- getGlobalRdrEnv ;
addErr (exportClashErr global_env name' name ie' ie) ;
return occs }
where
name_occ = nameOccName name
dupExport_ok :: Name -> IE RdrName -> IE RdrName -> Bool
-- The Name is exported by both IEs. Is that ok?
-- "No" iff the name is mentioned explicitly in both IEs
-- or one of the IEs mentions the name *alone*
-- "Yes" otherwise
--
-- Examples of "no": module M( f, f )
-- module M( fmap, Functor(..) )
-- module M( module Data.List, head )
--
-- Example of "yes"
-- module M( module A, module B ) where
-- import A( f )
-- import B( f )
--
-- Example of "yes" (Trac #2436)
-- module M( C(..), T(..) ) where
-- class C a where { data T a }
-- instance C Int where { data T Int = TInt }
--
-- Example of "yes" (Trac #2436)
-- module Foo ( T ) where
-- data family T a
-- module Bar ( T(..), module Foo ) where
-- import Foo
-- data instance T Int = TInt
dupExport_ok n ie1 ie2
= not ( single ie1 || single ie2
|| (explicit_in ie1 && explicit_in ie2) )
where
explicit_in (IEModuleContents _) = False -- module M
explicit_in (IEThingAll r) = nameOccName n == rdrNameOcc (unLoc r) -- T(..)
explicit_in _ = True
single IEVar {} = True
single IEThingAbs {} = True
single _ = False
dupModuleExport :: ModuleName -> SDoc
dupModuleExport mod
= hsep [text "Duplicate",
quotes (text "Module" <+> ppr mod),
text "in export list"]
moduleNotImported :: ModuleName -> SDoc
moduleNotImported mod
= text "The export item `module" <+> ppr mod <>
text "' is not imported"
nullModuleExport :: ModuleName -> SDoc
nullModuleExport mod
= text "The export item `module" <+> ppr mod <> ptext (sLit "' exports nothing")
dodgyExportWarn :: Name -> SDoc
dodgyExportWarn item = dodgyMsg (text "export") item
exportErrCtxt :: Outputable o => String -> o -> SDoc
exportErrCtxt herald exp =
text "In the" <+> text (herald ++ ":") <+> ppr exp
addExportErrCtxt :: (HasOccName s, OutputableBndr s) => IE s -> TcM a -> TcM a
addExportErrCtxt ie = addErrCtxt exportCtxt
where
exportCtxt = text "In the export:" <+> ppr ie
exportItemErr :: IE RdrName -> SDoc
exportItemErr export_item
= sep [ text "The export item" <+> quotes (ppr export_item),
text "attempts to export constructors or class methods that are not visible here" ]
dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc
dupExportWarn occ_name ie1 ie2
= hsep [quotes (ppr occ_name),
text "is exported by", quotes (ppr ie1),
text "and", quotes (ppr ie2)]
dcErrMsg :: Outputable a => Name -> String -> a -> [SDoc] -> SDoc
dcErrMsg ty_con what_is thing parents =
text "The type constructor" <+> quotes (ppr ty_con)
<+> text "is not the parent of the" <+> text what_is
<+> quotes (ppr thing) <> char '.'
$$ text (capitalise what_is)
<> text "s can only be exported with their parent type constructor."
$$ (case parents of
[] -> empty
[_] -> text "Parent:"
_ -> text "Parents:") <+> fsep (punctuate comma parents)
mkDcErrMsg :: Name -> Name -> [Name] -> TcM ChildLookupResult
mkDcErrMsg parent thing parents = do
ty_thing <- tcLookupGlobal thing
mkNameErr (dcErrMsg parent (tyThingCategory' ty_thing) thing (map ppr parents))
where
tyThingCategory' :: TyThing -> String
tyThingCategory' (AnId i)
| isRecordSelector i = "record selector"
tyThingCategory' i = tyThingCategory i
exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName
-> MsgDoc
exportClashErr global_env name1 name2 ie1 ie2
= vcat [ text "Conflicting exports for" <+> quotes (ppr occ) <> colon
, ppr_export ie1' name1'
, ppr_export ie2' name2' ]
where
occ = nameOccName name1
ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> text "exports" <+>
quotes (ppr name))
2 (pprNameProvenance (get_gre name)))
-- get_gre finds a GRE for the Name, so that we can show its provenance
get_gre name
= fromMaybe (pprPanic "exportClashErr" (ppr name)) (lookupGRE_Name global_env name)
get_loc name = greSrcSpan (get_gre name)
(name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
then (name1, ie1, name2, ie2)
else (name2, ie2, name1, ie1)
| olsner/ghc | compiler/typecheck/TcRnExports.hs | bsd-3-clause | 33,896 | 1 | 21 | 10,496 | 6,438 | 3,282 | 3,156 | 478 | 16 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.LHC
-- Copyright : Isaac Jones 2003-2007
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is a fairly large module. It contains most of the GHC-specific code for
-- configuring, building and installing packages. It also exports a function
-- for finding out what packages are already installed. Configuring involves
-- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions
-- this version of ghc supports and returning a 'Compiler' value.
--
-- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out
-- what packages are installed.
--
-- Building is somewhat complex as there is quite a bit of information to take
-- into account. We have to build libs and programs, possibly for profiling and
-- shared libs. We have to support building libraries that will be usable by
-- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files
-- using ghc. Linking, especially for @split-objs@ is remarkably complex,
-- partly because there tend to be 1,000's of @.o@ files and this can often be
-- more than we can pass to the @ld@ or @ar@ programs in one go.
--
-- Installing for libs and exes involves finding the right files and copying
-- them to the right places. One of the more tricky things about this module is
-- remembering the layout of files in the build directory (which is not
-- explicitly documented) and thus what search dirs are used for various kinds
-- of files.
module Distribution.Simple.LHC (
configure, getInstalledPackages,
buildLib, buildExe,
installLib, installExe,
registerPackage,
hcPkgInfo,
ghcOptions,
ghcVerbosityOptions
) where
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..)
, Library(..), libModules, hcOptions, hcProfOptions, hcSharedOptions
, usedExtensions, allExtensions )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo
, parseInstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo(..) )
import Distribution.Simple.PackageIndex
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.ParseUtils ( ParseResult(..) )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..) )
import Distribution.Simple.InstallDirs
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Package
( Package(..), getHSLibraryName, ComponentId )
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Program
( Program(..), ConfiguredProgram(..), ProgramConfiguration
, ProgramSearchPath, ProgramLocation(..)
, rawSystemProgram, rawSystemProgramConf
, rawSystemProgramStdout, rawSystemProgramStdoutConf
, requireProgramVersion
, userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram
, arProgram, ldProgram
, gccProgram, stripProgram
, lhcProgram, lhcPkgProgram )
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import Distribution.Simple.Compiler
( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion
, OptimisationLevel(..), PackageDB(..), PackageDBStack, AbiTag(..)
, Flag, languageToFlags, extensionsToFlags )
import Distribution.Version
( Version(..), orLaterVersion )
import Distribution.System
( OS(..), buildOS )
import Distribution.Verbosity
import Distribution.Text
( display, simpleParse )
import Language.Haskell.Extension
( Language(Haskell98), Extension(..), KnownExtension(..) )
import Control.Monad ( unless, when )
import Data.List
import qualified Data.Map as M ( empty )
import Data.Maybe ( catMaybes )
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid ( Monoid(..) )
#endif
import System.Directory ( removeFile, renameFile,
getDirectoryContents, doesFileExist,
getTemporaryDirectory )
import System.FilePath ( (</>), (<.>), takeExtension,
takeDirectory, replaceExtension )
import System.IO (hClose, hPutStrLn)
import Distribution.Compat.Exception (catchExit, catchIO)
import Distribution.System ( Platform )
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf = do
(lhcProg, lhcVersion, conf') <-
requireProgramVersion verbosity lhcProgram
(orLaterVersion (Version [0,7] []))
(userMaybeSpecifyPath "lhc" hcPath conf)
(lhcPkgProg, lhcPkgVersion, conf'') <-
requireProgramVersion verbosity lhcPkgProgram
(orLaterVersion (Version [0,7] []))
(userMaybeSpecifyPath "lhc-pkg" hcPkgPath conf')
when (lhcVersion /= lhcPkgVersion) $ die $
"Version mismatch between lhc and lhc-pkg: "
++ programPath lhcProg ++ " is version " ++ display lhcVersion ++ " "
++ programPath lhcPkgProg ++ " is version " ++ display lhcPkgVersion
languages <- getLanguages verbosity lhcProg
extensions <- getExtensions verbosity lhcProg
let comp = Compiler {
compilerId = CompilerId LHC lhcVersion,
compilerAbiTag = NoAbiTag,
compilerCompat = [],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = M.empty
}
conf''' = configureToolchain lhcProg conf'' -- configure gcc and ld
compPlatform = Nothing
return (comp, compPlatform, conf''')
-- | Adjust the way we find and configure gcc and ld
--
configureToolchain :: ConfiguredProgram -> ProgramConfiguration
-> ProgramConfiguration
configureToolchain lhcProg =
addKnownProgram gccProgram {
programFindLocation = findProg gccProgram (baseDir </> "gcc.exe"),
programPostConf = configureGcc
}
. addKnownProgram ldProgram {
programFindLocation = findProg ldProgram (libDir </> "ld.exe"),
programPostConf = configureLd
}
where
compilerDir = takeDirectory (programPath lhcProg)
baseDir = takeDirectory compilerDir
libDir = baseDir </> "gcc-lib"
includeDir = baseDir </> "include" </> "mingw"
isWindows = case buildOS of Windows -> True; _ -> False
-- on Windows finding and configuring ghc's gcc and ld is a bit special
findProg :: Program -> FilePath
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
findProg prog location | isWindows = \verbosity searchpath -> do
exists <- doesFileExist location
if exists then return (Just location)
else do warn verbosity ("Couldn't find " ++ programName prog ++ " where I expected it. Trying the search path.")
programFindLocation prog verbosity searchpath
| otherwise = programFindLocation prog
configureGcc :: Verbosity -> ConfiguredProgram -> IO ConfiguredProgram
configureGcc
| isWindows = \_ gccProg -> case programLocation gccProg of
-- if it's found on system then it means we're using the result
-- of programFindLocation above rather than a user-supplied path
-- that means we should add this extra flag to tell ghc's gcc
-- where it lives and thus where gcc can find its various files:
FoundOnSystem {} -> return gccProg {
programDefaultArgs = ["-B" ++ libDir,
"-I" ++ includeDir]
}
UserSpecified {} -> return gccProg
| otherwise = \_ gccProg -> return gccProg
-- we need to find out if ld supports the -x flag
configureLd :: Verbosity -> ConfiguredProgram -> IO ConfiguredProgram
configureLd verbosity ldProg = do
tempDir <- getTemporaryDirectory
ldx <- withTempFile tempDir ".c" $ \testcfile testchnd ->
withTempFile tempDir ".o" $ \testofile testohnd -> do
hPutStrLn testchnd "int foo() { return 0; }"
hClose testchnd; hClose testohnd
rawSystemProgram verbosity lhcProg ["-c", testcfile,
"-o", testofile]
withTempFile tempDir ".o" $ \testofile' testohnd' ->
do
hClose testohnd'
_ <- rawSystemProgramStdout verbosity ldProg
["-x", "-r", testofile, "-o", testofile']
return True
`catchIO` (\_ -> return False)
`catchExit` (\_ -> return False)
if ldx
then return ldProg { programDefaultArgs = ["-x"] }
else return ldProg
getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Flag)]
getLanguages _ _ = return [(Haskell98, "")]
--FIXME: does lhc support -XHaskell98 flag? from what version?
getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Flag)]
getExtensions verbosity lhcProg = do
exts <- rawSystemStdout verbosity (programPath lhcProg)
["--supported-languages"]
-- GHC has the annoying habit of inverting some of the extensions
-- so we have to try parsing ("No" ++ ghcExtensionName) first
let readExtension str = do
ext <- simpleParse ("No" ++ str)
case ext of
UnknownExtension _ -> simpleParse str
_ -> return ext
return $ [ (ext, "-X" ++ display ext)
| Just ext <- map readExtension (lines exts) ]
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity packagedbs conf = do
checkPackageDbStack packagedbs
pkgss <- getInstalledPackages' lhcPkg verbosity packagedbs conf
let indexes = [ PackageIndex.fromList (map (substTopDir topDir) pkgs)
| (_, pkgs) <- pkgss ]
return $! (mconcat indexes)
where
-- On Windows, various fields have $topdir/foo rather than full
-- paths. We need to substitute the right value in so that when
-- we, for example, call gcc, we have proper paths to give it
Just ghcProg = lookupProgram lhcProgram conf
Just lhcPkg = lookupProgram lhcPkgProgram conf
compilerDir = takeDirectory (programPath ghcProg)
topDir = takeDirectory compilerDir
checkPackageDbStack :: PackageDBStack -> IO ()
checkPackageDbStack (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStack _ =
die $ "GHC.getInstalledPackages: the global package db must be "
++ "specified first and cannot be specified multiple times"
-- | Get the packages from specific PackageDBs, not cumulative.
--
getInstalledPackages' :: ConfiguredProgram -> Verbosity
-> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' lhcPkg verbosity packagedbs conf
=
sequence
[ do str <- rawSystemProgramStdoutConf verbosity lhcPkgProgram conf
["dump", packageDbGhcPkgFlag packagedb]
`catchExit` \_ -> die $ "ghc-pkg dump failed"
case parsePackages str of
Left ok -> return (packagedb, ok)
_ -> die "failed to parse output of 'ghc-pkg dump'"
| packagedb <- packagedbs ]
where
parsePackages str =
let parsed = map parseInstalledPackageInfo (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Left [ pkg | ParseOk _ pkg <- parsed ]
msgs -> Right msgs
splitPkgs :: String -> [String]
splitPkgs = map unlines . splitWith ("---" ==) . lines
where
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
packageDbGhcPkgFlag GlobalPackageDB = "--global"
packageDbGhcPkgFlag UserPackageDB = "--user"
packageDbGhcPkgFlag (SpecificPackageDB path) = "--" ++ packageDbFlag ++ "=" ++ path
packageDbFlag
| programVersion lhcPkg < Just (Version [7,5] [])
= "package-conf"
| otherwise
= "package-db"
substTopDir :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
substTopDir topDir ipo
= ipo {
InstalledPackageInfo.importDirs
= map f (InstalledPackageInfo.importDirs ipo),
InstalledPackageInfo.libraryDirs
= map f (InstalledPackageInfo.libraryDirs ipo),
InstalledPackageInfo.includeDirs
= map f (InstalledPackageInfo.includeDirs ipo),
InstalledPackageInfo.frameworkDirs
= map f (InstalledPackageInfo.frameworkDirs ipo),
InstalledPackageInfo.haddockInterfaces
= map f (InstalledPackageInfo.haddockInterfaces ipo),
InstalledPackageInfo.haddockHTMLs
= map f (InstalledPackageInfo.haddockHTMLs ipo)
}
where f ('$':'t':'o':'p':'d':'i':'r':rest) = topDir ++ rest
f x = x
-- -----------------------------------------------------------------------------
-- Building
-- | Build a library with LHC.
--
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
let libName = componentId clbi
pref = buildDir lbi
pkgid = packageId pkg_descr
runGhcProg = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
ifVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi)
ifProfLib = when (withProfLib lbi)
ifSharedLib = when (withSharedLib lbi)
ifGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi)
libBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfLib lbi) (libBuildInfo lib)
let libTargetDir = pref
forceVanillaLib = EnableExtension TemplateHaskell `elem` allExtensions libBi
-- TH always needs vanilla libs, even when building for profiling
createDirectoryIfMissingVerbose verbosity True libTargetDir
-- TODO: do we need to put hs-boot files into place for mutually recursive modules?
let ghcArgs =
["-package-name", display pkgid ]
++ constructGHCCmdLine lbi libBi clbi libTargetDir verbosity
++ map display (libModules lib)
lhcWrap x = ["--build-library", "--ghc-opts=" ++ unwords x]
ghcArgsProf = ghcArgs
++ ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
]
++ hcProfOptions GHC libBi
ghcArgsShared = ghcArgs
++ ["-dynamic",
"-hisuf", "dyn_hi",
"-osuf", "dyn_o", "-fPIC"
]
++ hcSharedOptions GHC libBi
unless (null (libModules lib)) $
do ifVanillaLib forceVanillaLib (runGhcProg $ lhcWrap ghcArgs)
ifProfLib (runGhcProg $ lhcWrap ghcArgsProf)
ifSharedLib (runGhcProg $ lhcWrap ghcArgsShared)
-- build any C sources
unless (null (cSources libBi)) $ do
info verbosity "Building C Sources..."
sequence_ [do let (odir,args) = constructCcCmdLine lbi libBi clbi pref
filename verbosity
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
ifSharedLib (runGhcProg (args ++ ["-fPIC", "-osuf dyn_o"]))
| filename <- cSources libBi]
-- link:
info verbosity "Linking..."
let cObjs = map (`replaceExtension` objExtension) (cSources libBi)
cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension)) (cSources libBi)
cid = compilerId (compiler lbi)
vanillaLibFilePath = libTargetDir </> mkLibName libName
profileLibFilePath = libTargetDir </> mkProfLibName libName
sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName
ghciLibFilePath = libTargetDir </> mkGHCiLibName libName
stubObjs <- fmap catMaybes $ sequence
[ findFileWithExtension [objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
stubProfObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
stubSharedObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| x <- libModules lib ]
hObjs <- getHaskellObjects lib lbi
pref objExtension True
hProfObjs <-
if (withProfLib lbi)
then getHaskellObjects lib lbi
pref ("p_" ++ objExtension) True
else return []
hSharedObjs <-
if (withSharedLib lbi)
then getHaskellObjects lib lbi
pref ("dyn_" ++ objExtension) False
else return []
unless (null hObjs && null cObjs && null stubObjs) $ do
-- first remove library files if they exists
sequence_
[ removeFile libFilePath `catchIO` \_ -> return ()
| libFilePath <- [vanillaLibFilePath, profileLibFilePath
,sharedLibFilePath, ghciLibFilePath] ]
let arVerbosity | verbosity >= deafening = "v"
| verbosity >= normal = ""
| otherwise = "c"
arArgs = ["q"++ arVerbosity]
++ [vanillaLibFilePath]
arObjArgs =
hObjs
++ map (pref </>) cObjs
++ stubObjs
arProfArgs = ["q"++ arVerbosity]
++ [profileLibFilePath]
arProfObjArgs =
hProfObjs
++ map (pref </>) cObjs
++ stubProfObjs
ldArgs = ["-r"]
++ ["-o", ghciLibFilePath <.> "tmp"]
ldObjArgs =
hObjs
++ map (pref </>) cObjs
++ stubObjs
ghcSharedObjArgs =
hSharedObjs
++ map (pref </>) cSharedObjs
++ stubSharedObjs
-- After the relocation lib is created we invoke ghc -shared
-- with the dependencies spelled out as -package arguments
-- and ghc invokes the linker with the proper library paths
ghcSharedLinkArgs =
[ "-no-auto-link-packages",
"-shared",
"-dynamic",
"-o", sharedLibFilePath ]
++ ghcSharedObjArgs
++ ["-package-name", display pkgid ]
++ ghcPackageFlags lbi clbi
++ ["-l"++extraLib | extraLib <- extraLibs libBi]
++ ["-L"++extraLibDir | extraLibDir <- extraLibDirs libBi]
runLd ldLibName args = do
exists <- doesFileExist ldLibName
-- This method is called iteratively by xargs. The
-- output goes to <ldLibName>.tmp, and any existing file
-- named <ldLibName> is included when linking. The
-- output is renamed to <libName>.
rawSystemProgramConf verbosity ldProgram (withPrograms lbi)
(args ++ if exists then [ldLibName] else [])
renameFile (ldLibName <.> "tmp") ldLibName
runAr = rawSystemProgramConf verbosity arProgram (withPrograms lbi)
--TODO: discover this at configure time or runtime on Unix
-- The value is 32k on Windows and POSIX specifies a minimum of 4k
-- but all sensible Unixes use more than 4k.
-- we could use getSysVar ArgumentLimit but that's in the Unix lib
maxCommandLineSize = 30 * 1024
ifVanillaLib False $ xargs maxCommandLineSize
runAr arArgs arObjArgs
ifProfLib $ xargs maxCommandLineSize
runAr arProfArgs arProfObjArgs
ifGHCiLib $ xargs maxCommandLineSize
(runLd ghciLibFilePath) ldArgs ldObjArgs
ifSharedLib $ runGhcProg ghcSharedLinkArgs
-- | Build an executable with LHC.
--
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi
exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
let pref = buildDir lbi
runGhcProg = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
exeBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfExe lbi) (buildInfo exe)
-- exeNameReal, the name that GHC really uses (with .exe on Windows)
let exeNameReal = exeName' <.>
(if null $ takeExtension exeName' then exeExtension else "")
let targetDir = pref </> exeName'
let exeDir = targetDir </> (exeName' ++ "-tmp")
createDirectoryIfMissingVerbose verbosity True targetDir
createDirectoryIfMissingVerbose verbosity True exeDir
-- TODO: do we need to put hs-boot files into place for mutually recursive modules?
-- FIX: what about exeName.hi-boot?
-- build executables
unless (null (cSources exeBi)) $ do
info verbosity "Building C Sources."
sequence_ [do let (odir,args) = constructCcCmdLine lbi exeBi clbi
exeDir filename verbosity
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg args
| filename <- cSources exeBi]
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
let cObjs = map (`replaceExtension` objExtension) (cSources exeBi)
let lhcWrap x = ("--ghc-opts\"":x) ++ ["\""]
let binArgs linkExe profExe =
(if linkExe
then ["-o", targetDir </> exeNameReal]
else ["-c"])
++ constructGHCCmdLine lbi exeBi clbi exeDir verbosity
++ [exeDir </> x | x <- cObjs]
++ [srcMainFile]
++ ["-optl" ++ opt | opt <- PD.ldOptions exeBi]
++ ["-l"++lib | lib <- extraLibs exeBi]
++ ["-L"++libDir | libDir <- extraLibDirs exeBi]
++ concat [["-framework", f] | f <- PD.frameworks exeBi]
++ if profExe
then ["-prof",
"-hisuf", "p_hi",
"-osuf", "p_o"
] ++ hcProfOptions GHC exeBi
else []
-- For building exe's for profiling that use TH we actually
-- have to build twice, once without profiling and the again
-- with profiling. This is because the code that TH needs to
-- run at compile time needs to be the vanilla ABI so it can
-- be loaded up and run by the compiler.
when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions exeBi)
(runGhcProg $ lhcWrap (binArgs False False))
runGhcProg (binArgs True (withProfExe lbi))
-- | Filter the "-threaded" flag when profiling as it does not
-- work with ghc-6.8 and older.
hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo
hackThreadedFlag verbosity comp prof bi
| not mustFilterThreaded = return bi
| otherwise = do
warn verbosity $ "The ghc flag '-threaded' is not compatible with "
++ "profiling in ghc-6.8 and older. It will be disabled."
return bi { options = filterHcOptions (/= "-threaded") (options bi) }
where
mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] []
&& "-threaded" `elem` hcOptions GHC bi
filterHcOptions p hcoptss =
[ (hc, if hc == GHC then filter p opts else opts)
| (hc, opts) <- hcoptss ]
-- when using -split-objs, we need to search for object files in the
-- Module_split directory for each module.
getHaskellObjects :: Library -> LocalBuildInfo
-> FilePath -> String -> Bool -> IO [FilePath]
getHaskellObjects lib lbi pref wanted_obj_ext allow_split_objs
| splitObjs lbi && allow_split_objs = do
let dirs = [ pref </> (ModuleName.toFilePath x ++ "_split")
| x <- libModules lib ]
objss <- mapM getDirectoryContents dirs
let objs = [ dir </> obj
| (objs',dir) <- zip objss dirs, obj <- objs',
let obj_ext = takeExtension obj,
'.':wanted_obj_ext == obj_ext ]
return objs
| otherwise =
return [ pref </> ModuleName.toFilePath x <.> wanted_obj_ext
| x <- libModules lib ]
constructGHCCmdLine
:: LocalBuildInfo
-> BuildInfo
-> ComponentLocalBuildInfo
-> FilePath
-> Verbosity
-> [String]
constructGHCCmdLine lbi bi clbi odir verbosity =
["--make"]
++ ghcVerbosityOptions verbosity
-- Unsupported extensions have already been checked by configure
++ ghcOptions lbi bi clbi odir
ghcVerbosityOptions :: Verbosity -> [String]
ghcVerbosityOptions verbosity
| verbosity >= deafening = ["-v"]
| verbosity >= normal = []
| otherwise = ["-w", "-v0"]
ghcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcOptions lbi bi clbi odir
= ["-hide-all-packages"]
++ ghcPackageDbOptions lbi
++ (if splitObjs lbi then ["-split-objs"] else [])
++ ["-i"]
++ ["-i" ++ odir]
++ ["-i" ++ l | l <- nub (hsSourceDirs bi)]
++ ["-i" ++ autogenModulesDir lbi]
++ ["-I" ++ autogenModulesDir lbi]
++ ["-I" ++ odir]
++ ["-I" ++ dir | dir <- PD.includeDirs bi]
++ ["-optP" ++ opt | opt <- cppOptions bi]
++ [ "-optP-include", "-optP"++ (autogenModulesDir lbi </> cppHeaderName) ]
++ [ "-#include \"" ++ inc ++ "\"" | inc <- PD.includes bi ]
++ [ "-odir", odir, "-hidir", odir ]
++ (if compilerVersion c >= Version [6,8] []
then ["-stubdir", odir] else [])
++ ghcPackageFlags lbi clbi
++ (case withOptimization lbi of
NoOptimisation -> []
NormalOptimisation -> ["-O"]
MaximumOptimisation -> ["-O2"])
++ hcOptions GHC bi
++ languageToFlags c (defaultLanguage bi)
++ extensionsToFlags c (usedExtensions bi)
where c = compiler lbi
ghcPackageFlags :: LocalBuildInfo -> ComponentLocalBuildInfo -> [String]
ghcPackageFlags lbi clbi
| ghcVer >= Version [6,11] []
= concat [ ["-package-id", display ipkgid]
| (ipkgid, _) <- componentPackageDeps clbi ]
| otherwise = concat [ ["-package", display pkgid]
| (_, pkgid) <- componentPackageDeps clbi ]
where
ghcVer = compilerVersion (compiler lbi)
ghcPackageDbOptions :: LocalBuildInfo -> [String]
ghcPackageDbOptions lbi = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs
(GlobalPackageDB:dbs) -> ("-no-user-" ++ packageDbFlag)
: concatMap specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = [ '-':packageDbFlag, db ]
specific _ = ierror
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
dbstack = withPackageDB lbi
packageDbFlag
| compilerVersion (compiler lbi) < Version [7,5] []
= "package-conf"
| otherwise
= "package-db"
constructCcCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> FilePath -> Verbosity -> (FilePath,[String])
constructCcCmdLine lbi bi clbi pref filename verbosity
= let odir | compilerVersion (compiler lbi) >= Version [6,4,1] [] = pref
| otherwise = pref </> takeDirectory filename
-- ghc 6.4.1 fixed a bug in -odir handling
-- for C compilations.
in
(odir,
ghcCcOptions lbi bi clbi odir
++ (if verbosity >= deafening then ["-v"] else [])
++ ["-c",filename])
ghcCcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> [String]
ghcCcOptions lbi bi clbi odir
= ["-I" ++ dir | dir <- PD.includeDirs bi]
++ ghcPackageDbOptions lbi
++ ghcPackageFlags lbi clbi
++ ["-optc" ++ opt | opt <- PD.ccOptions bi]
++ (case withOptimization lbi of
NoOptimisation -> []
_ -> ["-optc-O2"])
++ ["-odir", odir]
mkGHCiLibName :: ComponentId -> String
mkGHCiLibName lib = getHSLibraryName lib <.> "o"
-- -----------------------------------------------------------------------------
-- Installing
-- |Install executables for GHC.
installExe :: Verbosity
-> LocalBuildInfo
-> InstallDirs FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do
let binDir = bindir installDirs
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = exeName exe <.> exeExtension
fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> exeName exe </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
stripExe :: Verbosity -> LocalBuildInfo -> FilePath -> FilePath -> IO ()
stripExe verbosity lbi name path = when (stripExes lbi) $
case lookupProgram stripProgram (withPrograms lbi) of
Just strip -> rawSystemProgram verbosity strip args
Nothing -> unless (buildOS == Windows) $
-- Don't bother warning on windows, we don't expect them to
-- have the strip program anyway.
warn verbosity $ "Unable to strip executable '" ++ name
++ "' (missing the 'strip' program)"
where
args = path : case buildOS of
OSX -> ["-x"] -- By default, stripping the ghc binary on at least
-- some OS X installations causes:
-- HSbase-3.0.o: unknown symbol `_environ'"
-- The -x flag fixes that.
_ -> []
-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
-- copy .hi files over:
let copy src dst n = do
createDirectoryIfMissingVerbose verbosity True dst
installOrdinaryFile verbosity (src </> n) (dst </> n)
copyModuleFiles ext =
findModuleFiles [builtDir] [ext] (libModules lib)
>>= installOrdinaryFiles verbosity targetDir
ifVanilla $ copyModuleFiles "hi"
ifProf $ copyModuleFiles "p_hi"
hcrFiles <- findModuleFiles (builtDir : hsSourceDirs (libBuildInfo lib)) ["hcr"] (libModules lib)
flip mapM_ hcrFiles $ \(srcBase, srcFile) -> runLhc ["--install-library", srcBase </> srcFile]
-- copy the built library files over:
ifVanilla $ copy builtDir targetDir vanillaLibName
ifProf $ copy builtDir targetDir profileLibName
ifGHCi $ copy builtDir targetDir ghciLibName
ifShared $ copy builtDir dynlibTargetDir sharedLibName
where
cid = compilerId (compiler lbi)
libName = componentId clbi
vanillaLibName = mkLibName libName
profileLibName = mkProfLibName libName
ghciLibName = mkGHCiLibName libName
sharedLibName = mkSharedLibName cid libName
hasLib = not $ null (libModules lib)
&& null (cSources (libBuildInfo lib))
ifVanilla = when (hasLib && withVanillaLib lbi)
ifProf = when (hasLib && withProfLib lbi)
ifGHCi = when (hasLib && withGHCiLib lbi)
ifShared = when (hasLib && withSharedLib lbi)
runLhc = rawSystemProgramConf verbosity lhcProgram (withPrograms lbi)
-- -----------------------------------------------------------------------------
-- Registering
registerPackage
:: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs =
HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity packageDbs
(Right installedPkgInfo)
hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo
hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = lhcPkgProg
, HcPkg.noPkgDbStack = False
, HcPkg.noVerboseFlag = False
, HcPkg.flagPackageConf = False
, HcPkg.useSingleFileDb = True
}
where
Just lhcPkgProg = lookupProgram lhcPkgProgram conf
| enolan/cabal | Cabal/Distribution/Simple/LHC.hs | bsd-3-clause | 33,686 | 0 | 25 | 9,551 | 7,524 | 3,925 | 3,599 | 597 | 6 |
{-|
Module : CSH.Eval.Frontend.Data
Description : Yesod data declarations for the EvalFrontend site
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : pvals@csh.rit.edu
Stability : Provisional
Portability : POSIX
Defines the web application layer of Evals
-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module CSH.Eval.Frontend.Data where
import CSH.Eval.Routes (evalAPI)
import Text.Hamlet (hamletFile)
import Text.Lucius (luciusFile)
import CSH.Eval.Config (ServerCmd (..))
import CSH.Eval.Model
import Yesod
import Yesod.Static
import System.Log.Logger hiding (getLogger)
-- Declaration of location of static files
staticFiles "frontend/static"
-- | datatype for Yesod
data EvalFrontend = EvalFrontend
{ getStatic :: Static
, getConfig :: ServerCmd
, getCache :: Cache
, getFrontendLogger :: Logger
}
-- | DOCUMENT THIS!
data AccessLvl = FreshmanAccess
| MemberAccess
| EboardAccess
| AdminAccess
deriving (Eq, Ord)
-- This makes the datatypes for the evaluations frontend, for use by
-- page hanlders in different files without having recursive importing.
mkYesodData "EvalFrontend" $(parseRoutesFile "config/routes")
-- | A Yesod subsite for the evalAPI defined using servant in "CSH.Eval.Routes"
getEvalAPI :: EvalFrontend -> WaiSubsite
getEvalAPI _ = WaiSubsite evalAPI
-- | The basic layout for every CSH Eval page
evalLayout :: Widget -> Handler Html
evalLayout widget = do
pc <- widgetToPageContent $ do
widget
addStylesheetRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
addScriptRemote "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"
addStylesheet $ StaticR csh_bootstrap_min_css
addStylesheet $ StaticR syntax_css
addStylesheet $ StaticR csh_eval_css
toWidget $(luciusFile "frontend/templates/csh-eval.lucius")
addScript $ StaticR salvattore_min_js
withUrlRenderer $(hamletFile "frontend/templates/base.hamlet")
-- | The Yesod instance for the EvalFrontend
instance Yesod EvalFrontend where
defaultLayout = evalLayout
makeSessionBackend s = if tls then ssl "key.aes" else nossl
where tls = withTLS (getConfig s)
ssl = sslOnlySessions . fmap Just . defaultClientSessionBackend 120
nossl = return Nothing
yesodMiddleware = ssl . defaultYesodMiddleware
where ssl s = withTLS . getConfig <$> getYesod >>=
(\x -> if x
then sslOnlyMiddleware 120 s
else s)
| robgssp/csh-eval | src/CSH/Eval/Frontend/Data.hs | mit | 3,013 | 0 | 14 | 724 | 441 | 236 | 205 | 53 | 1 |
{-# LANGUAGE StandaloneDeriving, DeriveGeneric #-}
module SizedSeq
( SizedSeq(..)
, emptySS
, addToSS
, addListToSS
, ssElts
, sizeSS
) where
import Prelude -- See note [Why do we import Prelude here?]
import Control.DeepSeq
import Data.Binary
import Data.List
import GHC.Generics
data SizedSeq a = SizedSeq {-# UNPACK #-} !Word [a]
deriving (Generic, Show)
instance Functor SizedSeq where
fmap f (SizedSeq sz l) = SizedSeq sz (fmap f l)
instance Foldable SizedSeq where
foldr f c ss = foldr f c (ssElts ss)
instance Traversable SizedSeq where
traverse f (SizedSeq sz l) = SizedSeq sz . reverse <$> traverse f (reverse l)
instance Binary a => Binary (SizedSeq a)
instance NFData a => NFData (SizedSeq a) where
rnf (SizedSeq _ xs) = rnf xs
emptySS :: SizedSeq a
emptySS = SizedSeq 0 []
addToSS :: SizedSeq a -> a -> SizedSeq a
addToSS (SizedSeq n r_xs) x = SizedSeq (n+1) (x:r_xs)
addListToSS :: SizedSeq a -> [a] -> SizedSeq a
addListToSS (SizedSeq n r_xs) xs
= SizedSeq (n + genericLength xs) (reverse xs ++ r_xs)
ssElts :: SizedSeq a -> [a]
ssElts (SizedSeq _ r_xs) = reverse r_xs
sizeSS :: SizedSeq a -> Word
sizeSS (SizedSeq n _) = n
| sdiehl/ghc | libraries/ghci/SizedSeq.hs | bsd-3-clause | 1,176 | 0 | 9 | 237 | 464 | 238 | 226 | 35 | 1 |
module C4 where
import D4
instance SameOrNot Double where
isSameOrNot a b = a ==b
isNotSame a b = a /=b
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe left
| kmate/HaRe | old/testing/renaming/C4_TokOut.hs | bsd-3-clause | 216 | 0 | 7 | 56 | 94 | 49 | 45 | 8 | 1 |
module A1 where
import C1
import D1
sumSq xs
= ((sum (map (sq sq_f) xs)) + (sumSquares xs)) +
(sumSquares1 xs)
main = sumSq [1 .. 4]
| kmate/HaRe | old/testing/addOneParameter/A1_AstOut.hs | bsd-3-clause | 147 | 2 | 13 | 41 | 77 | 42 | 35 | 7 | 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="en-GB">
<title>Form Handler | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>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>
| veggiespam/zap-extensions | addOns/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help/helpset.hs | apache-2.0 | 986 | 82 | 67 | 172 | 423 | 216 | 207 | -1 | -1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
-- | Bug(?) in Coercible constraint solving
module T13083 where
import Data.Kind
import GHC.Generics (Par1(..),(:*:)(..))
import GHC.Exts (coerce)
-- Representation as free vector space
type family V (a :: Type) :: Type -> Type
type instance V R = Par1
type instance V (a,b) = V a :*: V b
type instance V (Par1 a) = V a
data R = R
-- Linear map in row-major order
newtype L a b = L (V b (V a R))
-- Use coerce to drop newtype wrapper
bar :: L a b -> V b (V a R)
bar = coerce
{-
[W] L a b ~R V b (V a R)
-->
V b (V a R) ~R V b (V a R)
-}
{--------------------------------------------------------------------
Bug demo
--------------------------------------------------------------------}
-- A rejected type specialization of bar with a ~ (R,R), b ~ (Par1 R,R)
foo :: L (R,R) (Par1 R,R) -> V (Par1 R,R) (V (R,R) R)
-- foo :: L (a1,R) (Par1 b1,b2) -> V (Par1 b1,b2) (V (a1,R) R)
foo = coerce
{-
[W] L (a1,R) (Par1 b1, b2) ~R V (Par1 b1,b2) (V (a1,R) R)
-->
V (Par1 b1, b2) (V (a1,R) R) ~R same
-> (V (Par1 b1) :*: V b2) ((V a1 :*: V R) R)
-> (:*:) (V b1) (V b2) (:*: (V a1) Par1 R)
-->
L (a1,R) (Par1 b1, b2) ~R (:*:) (V b1) (V b2) (:*: (V a1) Par1 R)
-}
-- • Couldn't match representation of type ‘V Par1’
-- with that of ‘Par1’
-- arising from a use of ‘coerce’
-- Note that Par1 has the wrong kind (Type -> Type) for V Par1
-- Same error:
--
-- foo :: (a ~ (R,R), b ~ (Par1 R,R)) => L a b -> V b (V a R)
-- The following similar signatures work:
-- foo :: L (R,R) (R,Par1 R) -> V (R,Par1 R) (V (R,R) R)
-- foo :: L (Par1 R,R) (R,R) -> V (R,R) (V (Par1 R,R) R)
-- Same error:
-- -- Linear map in column-major order
-- newtype L a b = L (V a (V b s))
-- foo :: L (R,R) (Par1 R,R) -> V (R,R) (V (Par1 R,R) R)
-- foo = coerce
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T13083.hs | bsd-3-clause | 1,966 | 0 | 9 | 494 | 271 | 167 | 104 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE TypeFamilies, FlexibleInstances, UndecidableInstances, FlexibleContexts #-}
class A a
class B a where b :: a -> ()
instance A a => B a where b = undefined
newtype Y a = Y (a -> ())
okIn701 :: B a => Y a
okIn701 = wrap $ const () . b
okIn702 :: B a => Y a
okIn702 = wrap $ b
okInBoth :: B a => Y a
okInBoth = Y $ const () . b
class Wrapper a where
type Wrapped a
wrap :: Wrapped a -> a
instance Wrapper (Y a) where
type Wrapped (Y a) = a -> ()
wrap = Y
fromTicket3018 :: Eq [a] => a -> ()
fromTicket3018 x = let {g :: Int -> Int; g = [x]==[x] `seq` id} in ()
main = undefined
| ghc-android/ghc | testsuite/tests/indexed-types/should_compile/T5002.hs | bsd-3-clause | 661 | 0 | 11 | 160 | 298 | 156 | 142 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
-- | C code generator. This module can convert a correct ImpCode
-- program to an equivalent C program.
module Futhark.CodeGen.Backends.MulticoreC
( compileProg,
generateContext,
GC.CParts (..),
GC.asLibrary,
GC.asExecutable,
GC.asServer,
operations,
cliOptions,
)
where
import Control.Monad
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Text as T
import qualified Futhark.CodeGen.Backends.GenericC as GC
import Futhark.CodeGen.Backends.GenericC.Options
import Futhark.CodeGen.Backends.SimpleRep
import Futhark.CodeGen.ImpCode.Multicore
import qualified Futhark.CodeGen.ImpGen.Multicore as ImpGen
import Futhark.CodeGen.RTS.C (schedulerH)
import Futhark.IR.MCMem (MCMem, Prog)
import Futhark.MonadFreshNames
import qualified Language.C.Quote.OpenCL as C
import qualified Language.C.Syntax as C
-- | Compile the program to ImpCode with multicore operations.
compileProg ::
MonadFreshNames m =>
Prog MCMem ->
m (ImpGen.Warnings, GC.CParts)
compileProg =
traverse
( GC.compileProg
"multicore"
operations
generateContext
""
[DefaultSpace]
cliOptions
)
<=< ImpGen.compileProg
generateContext :: GC.CompilerM op () ()
generateContext = do
mapM_ GC.earlyDecl [C.cunit|$esc:(T.unpack schedulerH)|]
cfg <- GC.publicDef "context_config" GC.InitDecl $ \s ->
( [C.cedecl|struct $id:s;|],
[C.cedecl|struct $id:s { int debugging;
int profiling;
int num_threads;
};|]
)
GC.publicDef_ "context_config_new" GC.InitDecl $ \s ->
( [C.cedecl|struct $id:cfg* $id:s(void);|],
[C.cedecl|struct $id:cfg* $id:s(void) {
struct $id:cfg *cfg = (struct $id:cfg*) malloc(sizeof(struct $id:cfg));
if (cfg == NULL) {
return NULL;
}
cfg->debugging = 0;
cfg->profiling = 0;
cfg->num_threads = 0;
return cfg;
}|]
)
GC.publicDef_ "context_config_free" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:cfg* cfg);|],
[C.cedecl|void $id:s(struct $id:cfg* cfg) {
free(cfg);
}|]
)
GC.publicDef_ "context_config_set_debugging" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:cfg* cfg, int flag);|],
[C.cedecl|void $id:s(struct $id:cfg* cfg, int detail) {
cfg->debugging = detail;
}|]
)
GC.publicDef_ "context_config_set_profiling" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:cfg* cfg, int flag);|],
[C.cedecl|void $id:s(struct $id:cfg* cfg, int flag) {
cfg->profiling = flag;
}|]
)
GC.publicDef_ "context_config_set_logging" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:cfg* cfg, int flag);|],
[C.cedecl|void $id:s(struct $id:cfg* cfg, int detail) {
// Does nothing for this backend.
(void)cfg; (void)detail;
}|]
)
GC.publicDef_ "context_config_set_num_threads" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:cfg *cfg, int n);|],
[C.cedecl|void $id:s(struct $id:cfg *cfg, int n) {
cfg->num_threads = n;
}|]
)
(fields, init_fields, free_fields) <- GC.contextContents
ctx <- GC.publicDef "context" GC.InitDecl $ \s ->
( [C.cedecl|struct $id:s;|],
[C.cedecl|struct $id:s {
struct scheduler scheduler;
int detail_memory;
int debugging;
int profiling;
int profiling_paused;
int logging;
typename lock_t lock;
char *error;
typename FILE *log;
int total_runs;
long int total_runtime;
$sdecls:fields
// Tuning parameters
typename int64_t tuning_timing;
typename int64_t tuning_iter;
};|]
)
GC.publicDef_ "context_new" GC.InitDecl $ \s ->
( [C.cedecl|struct $id:ctx* $id:s(struct $id:cfg* cfg);|],
[C.cedecl|struct $id:ctx* $id:s(struct $id:cfg* cfg) {
struct $id:ctx* ctx = (struct $id:ctx*) malloc(sizeof(struct $id:ctx));
if (ctx == NULL) {
return NULL;
}
// Initialize rand()
fast_srand(time(0));
ctx->detail_memory = cfg->debugging;
ctx->debugging = cfg->debugging;
ctx->profiling = cfg->profiling;
ctx->profiling_paused = 0;
ctx->logging = 0;
ctx->error = NULL;
ctx->log = stderr;
create_lock(&ctx->lock);
int tune_kappa = 0;
double kappa = 5.1f * 1000;
if (tune_kappa) {
if (determine_kappa(&kappa) != 0) {
return NULL;
}
}
if (scheduler_init(&ctx->scheduler,
cfg->num_threads > 0 ?
cfg->num_threads : num_processors(),
kappa) != 0) {
return NULL;
}
$stms:init_fields
init_constants(ctx);
return ctx;
}|]
)
GC.publicDef_ "context_free" GC.InitDecl $ \s ->
( [C.cedecl|void $id:s(struct $id:ctx* ctx);|],
[C.cedecl|void $id:s(struct $id:ctx* ctx) {
$stms:free_fields
free_constants(ctx);
(void)scheduler_destroy(&ctx->scheduler);
free_lock(&ctx->lock);
free(ctx);
}|]
)
GC.publicDef_ "context_sync" GC.InitDecl $ \s ->
( [C.cedecl|int $id:s(struct $id:ctx* ctx);|],
[C.cedecl|int $id:s(struct $id:ctx* ctx) {
(void)ctx;
return 0;
}|]
)
GC.earlyDecl [C.cedecl|static const char *tuning_param_names[0];|]
GC.earlyDecl [C.cedecl|static const char *tuning_param_vars[0];|]
GC.earlyDecl [C.cedecl|static const char *tuning_param_classes[0];|]
GC.publicDef_ "context_config_set_tuning_param" GC.InitDecl $ \s ->
( [C.cedecl|int $id:s(struct $id:cfg* cfg, const char *param_name, size_t param_value);|],
[C.cedecl|int $id:s(struct $id:cfg* cfg, const char *param_name, size_t param_value) {
(void)cfg; (void)param_name; (void)param_value;
return 1;
}|]
)
cliOptions :: [Option]
cliOptions =
[ Option
{ optionLongName = "profile",
optionShortName = Just 'P',
optionArgument = NoArgument,
optionAction = [C.cstm|futhark_context_config_set_profiling(cfg, 1);|],
optionDescription = "Gather profiling information."
},
Option
{ optionLongName = "num-threads",
optionShortName = Nothing,
optionArgument = RequiredArgument "INT",
optionAction = [C.cstm|futhark_context_config_set_num_threads(cfg, atoi(optarg));|],
optionDescription = "Set number of threads used for execution."
}
]
operations :: GC.Operations Multicore ()
operations =
GC.defaultOperations
{ GC.opsCompiler = compileOp,
GC.opsCritical =
-- The thread entering an API function is always considered
-- the "first worker" - note that this might differ from the
-- thread that created the context! This likely only matters
-- for entry points, since they are the only API functions
-- that contain parallel operations.
( [C.citems|worker_local = &ctx->scheduler.workers[0];|],
[]
)
}
closureFreeStructField :: VName -> Name
closureFreeStructField v =
nameFromString "free_" <> nameFromString (pretty v)
closureRetvalStructField :: VName -> Name
closureRetvalStructField v =
nameFromString "retval_" <> nameFromString (pretty v)
data ValueType = Prim | MemBlock | RawMem
compileFreeStructFields :: [VName] -> [(C.Type, ValueType)] -> [C.FieldGroup]
compileFreeStructFields = zipWith field
where
field name (ty, Prim) =
[C.csdecl|$ty:ty $id:(closureFreeStructField name);|]
field name (_, _) =
[C.csdecl|$ty:defaultMemBlockType $id:(closureFreeStructField name);|]
compileRetvalStructFields :: [VName] -> [(C.Type, ValueType)] -> [C.FieldGroup]
compileRetvalStructFields = zipWith field
where
field name (ty, Prim) =
[C.csdecl|$ty:ty *$id:(closureRetvalStructField name);|]
field name (_, _) =
[C.csdecl|$ty:defaultMemBlockType $id:(closureRetvalStructField name);|]
compileSetStructValues ::
C.ToIdent a =>
a ->
[VName] ->
[(C.Type, ValueType)] ->
[C.Stm]
compileSetStructValues struct = zipWith field
where
field name (_, Prim) =
[C.cstm|$id:struct.$id:(closureFreeStructField name)=$id:name;|]
field name (_, MemBlock) =
[C.cstm|$id:struct.$id:(closureFreeStructField name)=$id:name.mem;|]
field name (_, RawMem) =
[C.cstm|$id:struct.$id:(closureFreeStructField name)=$id:name;|]
compileSetRetvalStructValues ::
C.ToIdent a =>
a ->
[VName] ->
[(C.Type, ValueType)] ->
[C.Stm]
compileSetRetvalStructValues struct = zipWith field
where
field name (_, Prim) =
[C.cstm|$id:struct.$id:(closureRetvalStructField name)=&$id:name;|]
field name (_, MemBlock) =
[C.cstm|$id:struct.$id:(closureRetvalStructField name)=$id:name.mem;|]
field name (_, RawMem) =
[C.cstm|$id:struct.$id:(closureRetvalStructField name)=$id:name;|]
compileGetRetvalStructVals :: C.ToIdent a => a -> [VName] -> [(C.Type, ValueType)] -> [C.InitGroup]
compileGetRetvalStructVals struct = zipWith field
where
field name (ty, Prim) =
[C.cdecl|$ty:ty $id:name = *$id:struct->$id:(closureRetvalStructField name);|]
field name (ty, _) =
[C.cdecl|$ty:ty $id:name =
{.desc = $string:(pretty name),
.mem = $id:struct->$id:(closureRetvalStructField name),
.size = 0, .references = NULL};|]
compileGetStructVals ::
C.ToIdent a =>
a ->
[VName] ->
[(C.Type, ValueType)] ->
[C.InitGroup]
compileGetStructVals struct = zipWith field
where
field name (ty, Prim) =
[C.cdecl|$ty:ty $id:name = $id:struct->$id:(closureFreeStructField name);|]
field name (ty, _) =
[C.cdecl|$ty:ty $id:name =
{.desc = $string:(pretty name),
.mem = $id:struct->$id:(closureFreeStructField name),
.size = 0, .references = NULL};|]
compileWriteBackResVals :: C.ToIdent a => a -> [VName] -> [(C.Type, ValueType)] -> [C.Stm]
compileWriteBackResVals struct = zipWith field
where
field name (_, Prim) =
[C.cstm|*$id:struct->$id:(closureRetvalStructField name) = $id:name;|]
field name (_, _) =
[C.cstm|$id:struct->$id:(closureRetvalStructField name) = $id:name.mem;|]
paramToCType :: Param -> GC.CompilerM op s (C.Type, ValueType)
paramToCType (ScalarParam _ pt) = do
let t = GC.primTypeToCType pt
return (t, Prim)
paramToCType (MemParam name space') = mcMemToCType name space'
mcMemToCType :: VName -> Space -> GC.CompilerM op s (C.Type, ValueType)
mcMemToCType v space = do
refcount <- GC.fatMemory space
cached <- isJust <$> GC.cacheMem v
return
( GC.fatMemType space,
if refcount && not cached
then MemBlock
else RawMem
)
functionRuntime :: Name -> C.Id
functionRuntime = (`C.toIdent` mempty) . (<> "_total_runtime")
functionRuns :: Name -> C.Id
functionRuns = (`C.toIdent` mempty) . (<> "_runs")
functionIter :: Name -> C.Id
functionIter = (`C.toIdent` mempty) . (<> "_iter")
multiCoreReport :: [(Name, Bool)] -> [C.BlockItem]
multiCoreReport names = report_kernels
where
report_kernels = concatMap reportKernel names
max_name_len_pad = 40
format_string name True =
let name_s = nameToString name
padding = replicate (max_name_len_pad - length name_s) ' '
in unwords ["tid %2d -", name_s ++ padding, "ran %10d times; avg: %10ldus; total: %10ldus; time pr. iter %9.6f; iters %9ld; avg %ld\n"]
format_string name False =
let name_s = nameToString name
padding = replicate (max_name_len_pad - length name_s) ' '
in unwords [" ", name_s ++ padding, "ran %10d times; avg: %10ldus; total: %10ldus; time pr. iter %9.6f; iters %9ld; avg %ld\n"]
reportKernel (name, is_array) =
let runs = functionRuns name
total_runtime = functionRuntime name
iters = functionIter name
in if is_array
then
[ [C.citem|
for (int i = 0; i < ctx->scheduler.num_threads; i++) {
fprintf(ctx->log,
$string:(format_string name is_array),
i,
ctx->$id:runs[i],
(long int) ctx->$id:total_runtime[i] / (ctx->$id:runs[i] != 0 ? ctx->$id:runs[i] : 1),
(long int) ctx->$id:total_runtime[i],
(double) ctx->$id:total_runtime[i] / (ctx->$id:iters[i] == 0 ? 1 : (double)ctx->$id:iters[i]),
(long int) (ctx->$id:iters[i]),
(long int) (ctx->$id:iters[i]) / (ctx->$id:runs[i] != 0 ? ctx->$id:runs[i] : 1)
);
}
|]
]
else
[ [C.citem|
fprintf(ctx->log,
$string:(format_string name is_array),
ctx->$id:runs,
(long int) ctx->$id:total_runtime / (ctx->$id:runs != 0 ? ctx->$id:runs : 1),
(long int) ctx->$id:total_runtime,
(double) ctx->$id:total_runtime / (ctx->$id:iters == 0 ? 1 : (double)ctx->$id:iters),
(long int) (ctx->$id:iters),
(long int) (ctx->$id:iters) / (ctx->$id:runs != 0 ? ctx->$id:runs : 1));
|],
[C.citem|ctx->total_runtime += ctx->$id:total_runtime;|],
[C.citem|ctx->total_runs += ctx->$id:runs;|]
]
addBenchmarkFields :: Name -> Maybe VName -> GC.CompilerM op s ()
addBenchmarkFields name (Just _) = do
GC.contextFieldDyn
(functionRuntime name)
[C.cty|typename int64_t*|]
[C.cexp|calloc(sizeof(typename int64_t), ctx->scheduler.num_threads)|]
[C.cstm|free(ctx->$id:(functionRuntime name));|]
GC.contextFieldDyn
(functionRuns name)
[C.cty|int*|]
[C.cexp|calloc(sizeof(int), ctx->scheduler.num_threads)|]
[C.cstm|free(ctx->$id:(functionRuns name));|]
GC.contextFieldDyn
(functionIter name)
[C.cty|typename int64_t*|]
[C.cexp|calloc(sizeof(sizeof(typename int64_t)), ctx->scheduler.num_threads)|]
[C.cstm|free(ctx->$id:(functionIter name));|]
addBenchmarkFields name Nothing = do
GC.contextField (functionRuntime name) [C.cty|typename int64_t|] $ Just [C.cexp|0|]
GC.contextField (functionRuns name) [C.cty|int|] $ Just [C.cexp|0|]
GC.contextField (functionIter name) [C.cty|typename int64_t|] $ Just [C.cexp|0|]
benchmarkCode :: Name -> Maybe VName -> [C.BlockItem] -> GC.CompilerM op s [C.BlockItem]
benchmarkCode name tid code = do
addBenchmarkFields name tid
return
[C.citems|
typename uint64_t $id:start = 0;
if (ctx->profiling && !ctx->profiling_paused) {
$id:start = get_wall_time();
}
$items:code
if (ctx->profiling && !ctx->profiling_paused) {
typename uint64_t $id:end = get_wall_time();
typename uint64_t elapsed = $id:end - $id:start;
$items:(updateFields tid)
}
|]
where
start = name <> "_start"
end = name <> "_end"
updateFields Nothing =
[C.citems|__atomic_fetch_add(&ctx->$id:(functionRuns name), 1, __ATOMIC_RELAXED);
__atomic_fetch_add(&ctx->$id:(functionRuntime name), elapsed, __ATOMIC_RELAXED);
__atomic_fetch_add(&ctx->$id:(functionIter name), iterations, __ATOMIC_RELAXED);|]
updateFields (Just _tid') =
[C.citems|ctx->$id:(functionRuns name)[tid]++;
ctx->$id:(functionRuntime name)[tid] += elapsed;
ctx->$id:(functionIter name)[tid] += iterations;|]
functionTiming :: Name -> C.Id
functionTiming = (`C.toIdent` mempty) . (<> "_total_time")
functionIterations :: Name -> C.Id
functionIterations = (`C.toIdent` mempty) . (<> "_total_iter")
addTimingFields :: Name -> GC.CompilerM op s ()
addTimingFields name = do
GC.contextField (functionTiming name) [C.cty|typename int64_t|] $ Just [C.cexp|0|]
GC.contextField (functionIterations name) [C.cty|typename int64_t|] $ Just [C.cexp|0|]
multicoreName :: String -> GC.CompilerM op s Name
multicoreName s = do
s' <- newVName ("futhark_mc_" ++ s)
return $ nameFromString $ baseString s' ++ "_" ++ show (baseTag s')
multicoreDef :: String -> (Name -> GC.CompilerM op s C.Definition) -> GC.CompilerM op s Name
multicoreDef s f = do
s' <- multicoreName s
GC.libDecl =<< f s'
return s'
generateParLoopFn ::
C.ToIdent a =>
M.Map VName Space ->
String ->
Code ->
a ->
[(VName, (C.Type, ValueType))] ->
[(VName, (C.Type, ValueType))] ->
VName ->
VName ->
GC.CompilerM Multicore s Name
generateParLoopFn lexical basename code fstruct free retval tid ntasks = do
let (fargs, fctypes) = unzip free
let (retval_args, retval_ctypes) = unzip retval
multicoreDef basename $ \s -> do
fbody <- benchmarkCode s (Just tid) <=< GC.inNewFunction False $
GC.cachingMemory lexical $
\decl_cached free_cached -> GC.blockScope $ do
mapM_ GC.item [C.citems|$decls:(compileGetStructVals fstruct fargs fctypes)|]
mapM_ GC.item [C.citems|$decls:(compileGetRetvalStructVals fstruct retval_args retval_ctypes)|]
mapM_ GC.item decl_cached
code' <- GC.blockScope $ GC.compileCode code
mapM_ GC.item [C.citems|$items:code'|]
GC.stm [C.cstm|cleanup: {$stms:free_cached}|]
return
[C.cedecl|int $id:s(void *args, typename int64_t iterations, int tid, struct scheduler_info info) {
int err = 0;
int $id:tid = tid;
int $id:ntasks = info.nsubtasks;
struct $id:fstruct *$id:fstruct = (struct $id:fstruct*) args;
struct futhark_context *ctx = $id:fstruct->ctx;
$items:fbody
if (err == 0) {
$stms:(compileWriteBackResVals fstruct retval_args retval_ctypes)
}
return err;
}|]
prepareTaskStruct ::
String ->
[VName] ->
[(C.Type, ValueType)] ->
[VName] ->
[(C.Type, ValueType)] ->
GC.CompilerM Multicore s Name
prepareTaskStruct name free_args free_ctypes retval_args retval_ctypes = do
fstruct <- multicoreDef name $ \s ->
return
[C.cedecl|struct $id:s {
struct futhark_context *ctx;
$sdecls:(compileFreeStructFields free_args free_ctypes)
$sdecls:(compileRetvalStructFields retval_args retval_ctypes)
};|]
GC.decl [C.cdecl|struct $id:fstruct $id:fstruct;|]
GC.stm [C.cstm|$id:fstruct.ctx = ctx;|]
GC.stms [C.cstms|$stms:(compileSetStructValues fstruct free_args free_ctypes)|]
GC.stms [C.cstms|$stms:(compileSetRetvalStructValues fstruct retval_args retval_ctypes)|]
return fstruct
-- Generate a segop function for top_level and potentially nested SegOp code
compileOp :: GC.OpCompiler Multicore ()
compileOp (Segop name params seq_task par_task retvals (SchedulerInfo nsubtask e sched)) = do
let (ParallelTask seq_code tid) = seq_task
free_ctypes <- mapM paramToCType params
retval_ctypes <- mapM paramToCType retvals
let free_args = map paramName params
retval_args = map paramName retvals
free = zip free_args free_ctypes
retval = zip retval_args retval_ctypes
e' <- GC.compileExp e
let lexical = lexicalMemoryUsage $ Function Nothing [] params seq_code [] []
fstruct <-
prepareTaskStruct "task" free_args free_ctypes retval_args retval_ctypes
fpar_task <- generateParLoopFn lexical (name ++ "_task") seq_code fstruct free retval tid nsubtask
addTimingFields fpar_task
let ftask_name = fstruct <> "_task"
GC.decl [C.cdecl|struct scheduler_segop $id:ftask_name;|]
GC.stm [C.cstm|$id:ftask_name.args = &$id:fstruct;|]
GC.stm [C.cstm|$id:ftask_name.top_level_fn = $id:fpar_task;|]
GC.stm [C.cstm|$id:ftask_name.name = $string:(nameToString fpar_task);|]
GC.stm [C.cstm|$id:ftask_name.iterations = $exp:e';|]
-- Create the timing fields for the task
GC.stm [C.cstm|$id:ftask_name.task_time = &ctx->$id:(functionTiming fpar_task);|]
GC.stm [C.cstm|$id:ftask_name.task_iter = &ctx->$id:(functionIterations fpar_task);|]
case sched of
Dynamic -> GC.stm [C.cstm|$id:ftask_name.sched = DYNAMIC;|]
Static -> GC.stm [C.cstm|$id:ftask_name.sched = STATIC;|]
-- Generate the nested segop function if available
fnpar_task <- case par_task of
Just (ParallelTask nested_code nested_tid) -> do
let lexical_nested = lexicalMemoryUsage $ Function Nothing [] params nested_code [] []
fnpar_task <- generateParLoopFn lexical_nested (name ++ "_nested_task") nested_code fstruct free retval nested_tid nsubtask
GC.stm [C.cstm|$id:ftask_name.nested_fn = $id:fnpar_task;|]
return $ zip [fnpar_task] [True]
Nothing -> do
GC.stm [C.cstm|$id:ftask_name.nested_fn=NULL;|]
return mempty
free_all_mem <- GC.freeAllocatedMem
let ftask_err = fpar_task <> "_err"
code =
[C.citems|int $id:ftask_err = scheduler_prepare_task(&ctx->scheduler, &$id:ftask_name);
if ($id:ftask_err != 0) {
$items:free_all_mem;
err = 1;
goto cleanup;
}|]
mapM_ GC.item code
-- Add profile fields for -P option
mapM_ GC.profileReport $ multiCoreReport $ (fpar_task, True) : fnpar_task
compileOp (ParLoop s' i prebody body postbody free tid) = do
free_ctypes <- mapM paramToCType free
let free_args = map paramName free
let lexical =
lexicalMemoryUsage $
Function Nothing [] free (prebody <> body) [] []
fstruct <-
prepareTaskStruct (s' ++ "_parloop_struct") free_args free_ctypes mempty mempty
ftask <- multicoreDef (s' ++ "_parloop") $ \s -> do
fbody <- benchmarkCode s (Just tid)
<=< GC.inNewFunction False
$ GC.cachingMemory lexical $
\decl_cached free_cached -> GC.blockScope $ do
mapM_
GC.item
[C.citems|$decls:(compileGetStructVals fstruct free_args free_ctypes)|]
mapM_ GC.item decl_cached
GC.decl [C.cdecl|typename int64_t iterations = end - start;|]
GC.decl [C.cdecl|typename int64_t $id:i = start;|]
GC.compileCode prebody
body' <- GC.blockScope $ GC.compileCode body
GC.stm
[C.cstm|for (; $id:i < end; $id:i++) {
$items:body'
}|]
GC.compileCode postbody
GC.stm [C.cstm|cleanup: {}|]
mapM_ GC.stm free_cached
return
[C.cedecl|static int $id:s(void *args, typename int64_t start, typename int64_t end, int $id:tid, int tid) {
int err = 0;
struct $id:fstruct *$id:fstruct = (struct $id:fstruct*) args;
struct futhark_context *ctx = $id:fstruct->ctx;
$items:fbody
return err;
}|]
let ftask_name = ftask <> "_task"
GC.decl [C.cdecl|struct scheduler_parloop $id:ftask_name;|]
GC.stm [C.cstm|$id:ftask_name.name = $string:(nameToString ftask);|]
GC.stm [C.cstm|$id:ftask_name.fn = $id:ftask;|]
GC.stm [C.cstm|$id:ftask_name.args = &$id:fstruct;|]
GC.stm [C.cstm|$id:ftask_name.iterations = iterations;|]
GC.stm [C.cstm|$id:ftask_name.info = info;|]
let ftask_err = ftask <> "_err"
ftask_total = ftask <> "_total"
code' <-
benchmarkCode
ftask_total
Nothing
[C.citems|int $id:ftask_err = scheduler_execute_task(&ctx->scheduler,
&$id:ftask_name);
if ($id:ftask_err != 0) {
err = 1;
goto cleanup;
}|]
mapM_ GC.item code'
mapM_ GC.profileReport $ multiCoreReport $ zip [ftask, ftask_total] [True, False]
compileOp (Atomic aop) =
atomicOps aop
doAtomic ::
(C.ToIdent a1) =>
a1 ->
VName ->
Count u (TExp Int32) ->
Exp ->
String ->
C.Type ->
GC.CompilerM op s ()
doAtomic old arr ind val op ty = do
ind' <- GC.compileExp $ untyped $ unCount ind
val' <- GC.compileExp val
arr' <- GC.rawMem arr
GC.stm [C.cstm|$id:old = $id:op(&(($ty:ty*)$exp:arr')[$exp:ind'], ($ty:ty) $exp:val', __ATOMIC_RELAXED);|]
atomicOps :: AtomicOp -> GC.CompilerM op s ()
atomicOps (AtomicCmpXchg t old arr ind res val) = do
ind' <- GC.compileExp $ untyped $ unCount ind
new_val' <- GC.compileExp val
let cast = [C.cty|$ty:(GC.primTypeToCType t)*|]
arr' <- GC.rawMem arr
GC.stm
[C.cstm|$id:res = $id:op(&(($ty:cast)$exp:arr')[$exp:ind'],
($ty:cast)&$id:old,
$exp:new_val',
0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED);|]
where
op :: String
op = "__atomic_compare_exchange_n"
atomicOps (AtomicXchg t old arr ind val) = do
ind' <- GC.compileExp $ untyped $ unCount ind
val' <- GC.compileExp val
let cast = [C.cty|$ty:(GC.primTypeToCType t)*|]
GC.stm [C.cstm|$id:old = $id:op(&(($ty:cast)$id:arr.mem)[$exp:ind'], $exp:val', __ATOMIC_SEQ_CST);|]
where
op :: String
op = "__atomic_exchange_n"
atomicOps (AtomicAdd t old arr ind val) =
doAtomic old arr ind val "__atomic_fetch_add" [C.cty|$ty:(GC.intTypeToCType t)|]
atomicOps (AtomicSub t old arr ind val) =
doAtomic old arr ind val "__atomic_fetch_sub" [C.cty|$ty:(GC.intTypeToCType t)|]
atomicOps (AtomicAnd t old arr ind val) =
doAtomic old arr ind val "__atomic_fetch_and" [C.cty|$ty:(GC.intTypeToCType t)|]
atomicOps (AtomicOr t old arr ind val) =
doAtomic old arr ind val "__atomic_fetch_or" [C.cty|$ty:(GC.intTypeToCType t)|]
atomicOps (AtomicXor t old arr ind val) =
doAtomic old arr ind val "__atomic_fetch_xor" [C.cty|$ty:(GC.intTypeToCType t)|]
| HIPERFIT/futhark | src/Futhark/CodeGen/Backends/MulticoreC.hs | isc | 27,204 | 0 | 21 | 7,733 | 5,231 | 2,883 | 2,348 | 432 | 3 |
{-# LANGUAGE DeriveFunctor #-}
module Game.TurnCounter
( TurnCounter (..)
, newTurnCounter
, nextTurn, nextTurnWith
, previousTurn, previousTurnWith
, currentPlayer
, nextPlayer
, previousPlayer
, currentRound
) where
import Data.List (find)
data TurnCounter p
= TurnCounter
{ tcPlayers :: [p]
, tcCounter :: Int
} deriving (Eq, Show, Functor)
newTurnCounter :: [p] -> TurnCounter p
newTurnCounter players =
TurnCounter
{ tcPlayers = players
, tcCounter = 0
}
nextTurn :: TurnCounter p -> TurnCounter p
nextTurn (TurnCounter ps c) = TurnCounter ps (c+1)
nextTurnWith :: (p -> Bool) -> TurnCounter p -> Maybe (TurnCounter p)
nextTurnWith predicate tc =
find (predicate . currentPlayer) $
take (length (tcPlayers tc)) $
iterate nextTurn (nextTurn tc)
previousTurn :: TurnCounter p -> TurnCounter p
previousTurn (TurnCounter ps c) = TurnCounter ps (c-1)
previousTurnWith :: (p -> Bool) -> TurnCounter p -> Maybe (TurnCounter p)
previousTurnWith predicate tc =
find (predicate . currentPlayer) $
take (length (tcPlayers tc)) $
iterate previousTurn (previousTurn tc)
currentPlayer :: TurnCounter p -> p
currentPlayer (TurnCounter ps c) = ps !! (c `mod` length ps)
nextPlayer :: TurnCounter p -> p
nextPlayer = currentPlayer . nextTurn
previousPlayer :: TurnCounter p -> p
previousPlayer = currentPlayer . previousTurn
currentRound :: TurnCounter p -> Int
currentRound (TurnCounter ps c) = c `div` length ps
| timjb/halma | halma/src/Game/TurnCounter.hs | mit | 1,466 | 0 | 11 | 275 | 511 | 270 | 241 | 43 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
import Text.Hamlet (HtmlUrl, hamlet)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Data.Text (Text)
import Yesod
data MyRoute = Home
render :: MyRoute -> [(Text, Text)] -> Text
render Home _ = "/home"
footer :: HtmlUrl MyRoute
footer = [hamlet|
<footer>
Return to #
<a href=@{Home}>Homepage
.
|]
main :: IO ()
main = putStrLn $ renderHtml $ [hamlet|
<body>
<p>This is my page.
^{footer}
|] render | cirquit/quizlearner | resources/html/footer.hs | mit | 497 | 0 | 8 | 94 | 128 | 77 | 51 | 14 | 1 |
module Grammar.Common.Pretty where
import Data.Text (Text)
import qualified Data.Text as Text
import Grammar.Common.Types
textShow :: Show a => a -> Text
textShow = Text.pack . show
prettyMilestone :: Maybe Division :* Maybe Paragraph -> Text
prettyMilestone (Nothing, _) = ""
prettyMilestone (Just (Division b c v s l), _)
= Text.intercalate "."
. filter (\x -> not . Text.null $ x)
$ [ms b, ms c, ms v, ms s, ms l]
where
ms Nothing = ""
ms (Just x) = textShow x
prettySource :: Show a => SourceId :* Milestone :* a -> Text
prettySource (SourceId g s, (m, x)) = Text.intercalate " " $
[ g
, s
, prettyMilestone m
, "--"
, textShow $ x
]
prettyMilestoned :: Show a => Milestone :* a -> Text
prettyMilestoned (m, x) = Text.intercalate " " $
[ prettyMilestone m
, "--"
, textShow $ x
]
prettyMilestonedString :: Milestone :* String -> Text
prettyMilestonedString (m, x) = Text.intercalate " " $
[ prettyMilestone m
, "--"
, Text.pack x
]
prettyMilestoneCtx :: Milestone :* Text :* [Text] :* [Text] -> (Text, Text, Text, Text)
prettyMilestoneCtx (m, (w, (ls, rs))) =
( prettyMilestone m
, Text.intercalate " " ls
, w
, Text.intercalate " " rs
)
| ancientlanguage/haskell-analysis | grammar/src/Grammar/Common/Pretty.hs | mit | 1,199 | 0 | 12 | 265 | 499 | 269 | 230 | -1 | -1 |
module Hahet.Targets.Services where
import Hahet.Targets
import Hahet.Imports
type Started = Maybe Bool
data Service = Service Text Started
deriving (Typeable, Show)
instance Typeable c => Target c Service where
targetDesc _ (Service service _) = service
targetApply (Service _ Nothing) = return ResNoop
targetApply (Service _ (Just False)) = return $ ResFailed "Not yet implemented"
targetApply (Service _ (Just True)) = return $ ResFailed "Not yet implemented"
| SimSaladin/hahet | src/Hahet/Targets/Services.hs | mit | 495 | 0 | 10 | 99 | 160 | 82 | 78 | -1 | -1 |
import Network
import System.IO
import Control.Exception
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Fix (fix)
type Msg = (Int, String)
filename = "primes.log"
main :: IO ()
main = do
chan <- newEmptyMVar
-- sock <- socket AF_INET Stream 0
-- setSocketOption sock ReuseAddr 1
-- bindSocket sock (SockAddrInet 4242 iNADDR_ANY)
-- listen sock 2
sock <- listenOn $ PortNumber 4242
reader <- forkIO $ fix $ \loop -> do
(nr', line) <- takeMVar chan
putStrLn $ "Results returned from slave " ++ show nr'
appendFile filename (line ++ "\n")
loop
mainLoop sock chan 0
mainLoop :: Socket -> MVar (Msg) -> Int -> IO ()
mainLoop sock chan nr = do
(handle, _, _) <- accept sock
hSetBuffering handle NoBuffering
forkIO $ runConn handle chan nr
mainLoop sock chan $! nr+1
runConn :: Handle -> MVar (Msg) -> Int -> IO ()
runConn hdl chan nr = do
let broadcast msg = putMVar chan (nr, msg)
handle (\(SomeException _) -> return ()) $ fix $ \loop -> do
line <- hGetLine hdl
broadcast line
loop
hClose hdl
| Joss-Steward/Primality | logger.hs | mit | 1,132 | 0 | 14 | 269 | 399 | 198 | 201 | 33 | 1 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Prelude hiding ((.), id)
-- Morphisms
type (a ~> b) c = c a b
class Category (c :: k -> k -> *) where
id :: (a ~> a) c
(.) :: (y ~> z) c -> (x ~> y) c -> (x ~> z) c
type Hask = (->)
instance Category Hask where
id x = x
(f . g) x = f (g x)
| riwsky/wiwinwlh | src/categories.hs | mit | 356 | 3 | 11 | 93 | 166 | 94 | 72 | 12 | 0 |
main= return()
| geraldus/transient-universe | app/client/Transient/Move/Services/MonitorService.hs | mit | 15 | 0 | 6 | 2 | 11 | 5 | 6 | 1 | 1 |
module Selection where
| fatuhoku/haskell-ball-mosaic | src/Selection.hs | mit | 24 | 0 | 2 | 4 | 4 | 3 | 1 | 1 | 0 |
module Board where
import Data.List (intercalate, unfoldr)
data Cell = O | X | E deriving (Read, Show, Eq)
data Board = Board [Cell] deriving Eq
type Index = Int
instance Show Board where
show (Board cs) =
"\n" ++ intercalate "\n" (map unwords [topRow,midRow,botRow]) ++ "\n"
where lst = map show cs
[topRow,midRow,botRow] = chunks 3 lst
-- | Found this on SO. Isn't it beautiful?
chunks :: Index -> [a] -> [[a]]
chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)
-- | The "zero board"
emptyBoard :: Board
emptyBoard = Board (replicate 9 E)
-- | Convenience function that turns Xs into Os and vice versa.
invert :: Board -> Board
invert (Board cs) = Board $ map invert' cs
where invert' X = O
invert' O = X
invert' E = E
-- | Not using Maybe because this will not be exposed.
getCell :: Index -> Board -> Cell
getCell ix (Board cs)
| 0 <= ix && ix <= 8 = cs !! ix
| otherwise = error $ "Invalid index " ++ show ix
-- | Set a cell of a board to a particular value.
-- | FIXME fail if user attempts to update non-empty cell?
setCell :: Index -> Cell -> Board -> Board
setCell ix cell (Board cs) =
Board $ cs // (ix,cell)
where ls // (n,item) = a ++ (item : b)
where (a,_:b) = splitAt n ls
-- | Functions for working with the three kinds of subsets of a board
-- | that a player can "win": rows, columns and diagonals.
rows, cols, diags :: Board -> [[Cell]]
rows (Board cs) = chunks 3 cs
cols (Board cs) =
map (col cs)
[0,1,2]
where col :: [Cell] -> Index -> [Cell]
col cs ix =
map (\n -> cs !! (ix + 3 * n))
[0,1,2]
diags (Board cs) = [diag,antidiag]
where diag = map (cs !!) [0,4,8]
antidiag = map (cs !!) [2,4,7]
| mrkgnao/tictactoe-minimax | Board.hs | mit | 1,742 | 0 | 13 | 449 | 675 | 368 | 307 | -1 | -1 |
{-|
Copyright: (c) Guilherme Azzi, 2014
License: MIT
Maintainer: ggazzi@inf.ufrgs.br
Stability: experimental
A 'Monitor' for the CPU activity.
This module is meant to be imported qualified, e.g.:
> import qualified Reactive.Banana.Monitors.Cpu as Cpu
-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module Reactive.Banana.Monitors.Cpu
( CpuMonitor
, busy
, user
, nice
, system
, idle
, iowait
, irq
, softirq
, newMonitor
) where
import Reactive.Banana.Monitors.Class
import Reactive.Banana.Sources
import Control.Monad (zipWithM_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Reactive.Banana
import qualified Reactive.Banana.Monitors.Internal.Procfs as Procfs
-- | A monitor for the CPU activity.
--
-- Provides behaviors for the fraction of time that the
-- CPU is spending in several states.
data CpuMonitor t = CpuMonitor { busy :: Behavior t Double
, user :: Behavior t Double
, nice :: Behavior t Double
, system :: Behavior t Double
, idle :: Behavior t Double
, iowait :: Behavior t Double
, irq :: Behavior t Double
, softirq :: Behavior t Double
}
newMonitor :: IO (SourceOf CpuMonitor)
newMonitor = do
sources <- sequence . take 8 $ repeat (newBehavior 0)
let [busy, user, nice, system, idle, iowait, irq, softirq] = sources
return CpuSource
{ sbusy = busy
, suser = user
, snice = nice
, ssystem = system
, sidle = idle
, siowait = iowait
, sirq = irq
, ssoftirq = softirq
, updateCpuMonitor = updateMany sources
}
instance Monitor CpuMonitor where
data SourceOf CpuMonitor = CpuSource
{ sbusy :: BehaviorSource Double
, suser :: BehaviorSource Double
, snice :: BehaviorSource Double
, ssystem :: BehaviorSource Double
, sidle :: BehaviorSource Double
, siowait :: BehaviorSource Double
, sirq :: BehaviorSource Double
, ssoftirq :: BehaviorSource Double
, updateCpuMonitor :: [Double] -> IO ()
}
-- Just obtain all behaviors from behavior sources
fromMonitorSource src = CpuMonitor <$>
fromBehaviorSource (sbusy src) <*>
fromBehaviorSource (suser src) <*>
fromBehaviorSource (snice src) <*>
fromBehaviorSource (ssystem src) <*>
fromBehaviorSource (sidle src) <*>
fromBehaviorSource (siowait src) <*>
fromBehaviorSource (sirq src) <*>
fromBehaviorSource (ssoftirq src)
initMonitor src = do
-- Obtain an IORef with the current CPU time
initial <- Procfs.readStatCpu
cpuTimeRef <- newIORef initial
-- Use the IORef to update (comparing the previous times
-- with the current, for how much time was spent in each
-- state)
return $ checkCpu cpuTimeRef >>= updateCpuMonitor src
-- | Reads the current CPU state, updates it on the given
-- 'IORef' and returns the fraction of time spent on
-- each of the following states: busy (user + nice + system),
-- user, nice, system, idle, iowait, irq, softirq.
checkCpu :: IORef [Double] -> IO [Double]
checkCpu cref = do
-- Obtain the current and previous times
prev <- readIORef cref
curr <- Procfs.readStatCpu
-- Update the IORef
writeIORef cref curr
-- Calculate the time spent since last check
let dif = zipWith (-) curr prev
tot = sum dif
-- Calculate the fractions for each state
frac = map (nanProof . (/ tot)) dif
nanProof x = if isNaN x || isInfinite x then 0 else x
t = sum $ take 3 frac
return (t:frac)
-- | Update the given behaviors with the corresponding values.
--
-- Given @m@ 'BehaviorSource's and @n@ values, update the first
-- @min m n@ behaviors with the corresponding values.
updateMany :: [BehaviorSource a] -> [a] -> IO ()
updateMany = zipWithM_ update
| ggazzi/hzen | src/Reactive/Banana/Monitors/Cpu.hs | mit | 4,494 | 0 | 16 | 1,574 | 823 | 452 | 371 | 78 | 2 |
-- chaper3.hs
safetail_1 :: [a] -> [a]
safetail_1 xs = if null xs
then []
else tail xs
safetail_2 :: [a] -> [a]
safetail_2 xs | null xs = []
| otherwise = tail xs
safetail_3 :: [a] -> [a]
safetail_3 [] = []
safetail_3 (_:xs) = xs
| hnfmr/fp101x | playground/chapter3.hs | mit | 279 | 0 | 8 | 97 | 129 | 67 | 62 | 10 | 2 |
-- | Core functionality of the package. Import from either "System.Console.Ansigraph" or
-- "System.Console.Ansigraph.Core".
module System.Console.Ansigraph.Internal.Core where
import System.Console.ANSI
import System.IO (hFlush, stdout)
import Control.Monad.IO.Class (MonadIO, liftIO)
-- for GHC <= 7.8
import Control.Applicative
---- Basics ----
-- | ANSI colors are characterized by a 'Color' and a 'ColorIntensity'.
data AnsiColor = AnsiColor {
intensity :: ColorIntensity
, color :: Color
} deriving Show
-- | Record that holds graphing options.
data GraphSettings = GraphSettings {
-- | Foreground color for real number component.
realColor :: AnsiColor
-- | Foreground color for imaginary number component.
, imagColor :: AnsiColor
-- | Foreground color for negative real values. For matrix graphs only.
, realNegColor :: AnsiColor
-- | Foreground color for negative imaginary values. For matrix graphs only.
, imagNegColor :: AnsiColor
-- | Background color for real number component.
, realBG :: AnsiColor
-- | Background color for imaginary number component.
, imagBG :: AnsiColor
-- | Framerate in FPS.
, framerate :: Int
}
-- | 'Vivid' 'Blue' – used as the default real foreground color.
blue = AnsiColor Vivid Blue
-- | 'Vivid' 'Magenta' – used as the default foreground color for imaginary
-- graph component.
pink = AnsiColor Vivid Magenta
-- | 'Vivid' 'White' – used as the default graph background color
-- for both real and imaginary graph components.
white = AnsiColor Vivid White
-- | 'Vivid' 'Red' – used as the default foreground color for negative real component.
red = AnsiColor Vivid Red
-- | 'Dull' 'Green' – used as the default foreground color for negative imaginary component.
green = AnsiColor Dull Green
-- | 'Dull' 'Black'.
black = AnsiColor Dull Blue
-- | 'Vivid' 'Yellow'.
yellow = AnsiColor Vivid Yellow
-- | 'Vivid' 'Magenta'.
magenta = AnsiColor Vivid Magenta
-- | 'Vivid' 'Cyan'.
cyan = AnsiColor Vivid Cyan
-- | Default graph settings.
graphDefaults = GraphSettings blue pink red green white white 15
-- | Holds two 'Maybe' 'AnsiColor's representing foreground and background colors for display via ANSI.
-- 'Nothing' means use the default terminal color.
data Coloring = Coloring { foreground :: Maybe AnsiColor,
background :: Maybe AnsiColor } deriving Show
-- | A 'Coloring' representing default terminal colors, i.e. two 'Nothing's.
noColoring = Coloring Nothing Nothing
-- | Helper constructor function for 'Coloring' that takes straight 'AnsiColor's without 'Maybe'.
mkColoring :: AnsiColor -> AnsiColor -> Coloring
mkColoring c1 c2 = Coloring (Just c1) (Just c2)
-- | Projection retrieving foreground and background colors
-- for real number graphs in the form of a 'Coloring'.
realColors :: GraphSettings -> Coloring
realColors s = mkColoring (realColor s) (realBG s)
-- | Projection retrieving foreground and background colors
-- for imaginary component of complex number graphs in the form of a 'Coloring'.
imagColors :: GraphSettings -> Coloring
imagColors s = mkColoring (imagColor s) (imagBG s)
-- | Retrieves a pair of 'Coloring's for real and imaginary graph components respectively.
colorSets :: GraphSettings -> (Coloring,Coloring)
colorSets s = (realColors s, imagColors s)
-- | Swaps foreground and background colors within a 'Coloring'.
invert :: Coloring -> Coloring
invert (Coloring fg bg) = Coloring bg fg
-- | Easily create a 'Coloring' by specifying the background 'AnsiColor' and no custom foreground.
fromBG :: AnsiColor -> Coloring
fromBG c = Coloring Nothing (Just c)
-- | Easily create a 'Coloring' by specifying the foreground 'AnsiColor' and no custom background.
fromFG :: AnsiColor -> Coloring
fromFG c = Coloring (Just c) Nothing
-- | The SGR command corresponding to a particular 'ConsoleLayer' and 'AnsiColor'.
interpAnsiColor :: ConsoleLayer -> AnsiColor -> SGR
interpAnsiColor l (AnsiColor i c) = SetColor l i c
-- | Produce a (possibly empty) list of 'SGR' commands from a 'ConsoleLayer' and 'AnsiColor'.
-- An empty 'SGR' list is equivalent to 'Reset'.
sgrList :: ConsoleLayer -> Maybe AnsiColor -> [SGR]
sgrList l = fmap (interpAnsiColor l) . maybe [] pure
-- | Set the given 'AnsiColor' on the given 'ConsoleLayer'.
setColor :: MonadIO m => ConsoleLayer -> AnsiColor -> m ()
setColor l c = liftIO $ setSGR [interpAnsiColor l c]
-- | Apply both foreground and background color contained in a 'Coloring'.
applyColoring :: MonadIO m => Coloring -> m ()
applyColoring (Coloring fg bg) = liftIO $ do
setSGR [Reset]
setSGR $ sgrList Foreground fg ++ sgrList Background bg
-- | Clear any SGR settings and then flush stdout.
clear :: MonadIO m => m ()
clear = liftIO $ setSGR [Reset] >> hFlush stdout
putStrLn', putStr' :: MonadIO m => String -> m ()
putStrLn' = liftIO . putStrLn
putStr' = liftIO . putStr
-- | Clear any SGR settings, flush stdout and print a new line.
clearLn :: MonadIO m => m ()
clearLn = clear >> putStrLn' ""
-- | Use a particular ANSI 'Coloring' to print a string at the terminal (without a new line),
-- then clear all ANSI SGR codes and flush stdout.
colorStr :: MonadIO m => Coloring -> String -> m ()
colorStr c s = do
applyColoring c
putStr' s
clear
-- | Use a particular ANSI 'Coloring' to print a string at the terminal,
-- then clear all ANSI SGR codes, flush stdout and print a new line.
colorStrLn :: MonadIO m => Coloring -> String -> m ()
colorStrLn c s = do
applyColoring c
putStr' s
clearLn
-- | Like 'colorStr' but prints bold text.
boldStr :: MonadIO m => Coloring -> String -> m ()
boldStr c s = do
applyColoring c
liftIO $ setSGR [SetConsoleIntensity BoldIntensity]
putStr' s
clear
-- | Like 'colorStrLn' but prints bold text.
boldStrLn :: MonadIO m => Coloring -> String -> m ()
boldStrLn c s = boldStr c s >> putStrLn' ""
| BlackBrane/ansigraph | src/System/Console/Ansigraph/Internal/Core.hs | mit | 5,951 | 0 | 10 | 1,149 | 1,080 | 572 | 508 | 79 | 1 |
module DevelMain where
import Control.Concurrent
import Control.Exception (finally)
import Control.Monad ((>=>))
import Data.IORef
import Data.Time.Clock
import Foreign.Store
import GHC.Word
import Main
import Network.Wai.Handler.Warp
-- | Start or restart the server.
-- newStore is from foreign-store.
-- A Store holds onto some data across ghci reloads
update :: IO ()
update = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> do
done <- storeAction doneStore newEmptyMVar
tid <- start done
_ <- storeAction (Store tidStoreNum) (newIORef tid)
return ()
-- server is already running
Just tidStore -> restartAppInNewThread tidStore
where
doneStore :: Store (MVar ())
doneStore = Store 0
-- shut the server down with killThread and wait for the done signal
restartAppInNewThread :: Store (IORef ThreadId) -> IO ()
restartAppInNewThread tidStore = modifyStoredIORef tidStore $ \tid -> do
killThread tid
withStore doneStore takeMVar
readStore doneStore >>= start
-- | Start the server in a separate thread.
start :: MVar () -- ^ Written to when the thread is killed.
-> IO ThreadId
start done = do
app <- gitIssuesServerApp
tid <- forkIO (finally (runSettings (setPort 3000 defaultSettings) app)
-- Note that this implies concurrency
-- between shutdownApp and the next app that is starting.
-- Normally this should be fine
(putMVar done ()))
writeFile "devel-main-since" =<< show <$> getCurrentTime
return tid
-- | kill the server
shutdown :: IO ()
shutdown = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> putStrLn "no Yesod app running"
Just tidStore -> do
withStore tidStore $ readIORef >=> killThread
putStrLn "Yesod app is shutdown"
tidStoreNum :: Word32
tidStoreNum = 1
modifyStoredIORef :: Store (IORef a) -> (a -> IO a) -> IO ()
modifyStoredIORef store f = withStore store $ \ref -> do
v <- readIORef ref
f v >>= writeIORef ref
| yamadapc/git-issues | src/DevelMain.hs | mit | 2,358 | 0 | 16 | 739 | 530 | 261 | 269 | 49 | 2 |
module PerfectNumbers (classify, Classification(..)) where
data Classification = Deficient | Perfect | Abundant deriving (Eq, Show)
classify :: Int -> Maybe Classification
classify = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/perfect-numbers/src/PerfectNumbers.hs | mit | 230 | 0 | 6 | 33 | 60 | 35 | 25 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright (C) 2009-2011 John Millikin <jmillikin@gmail.com>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Main (main) where
import Control.Monad (when)
import Data.String (fromString)
import qualified Data.Text
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import DBus
import DBus.Client
import qualified DBus.Introspection as I
main :: IO ()
main = do
args <- getArgs
(service, path) <- case args of
a1:a2:_ -> return (fromString a1, fromString a2)
_ -> do
name <- getProgName
hPutStrLn stderr ("Usage: " ++ name ++ " <service> <path>")
exitFailure
client <- connectSession
printObj (introspect client service) path
introspect :: Client -> BusName -> ObjectPath -> IO I.Object
introspect client service path = do
reply <- call_ client (methodCall path "org.freedesktop.DBus.Introspectable" "Introspect")
{ methodCallDestination = Just service
}
let Just xml = fromVariant (methodReturnBody reply !! 0)
case I.parseXML path xml of
Just info -> return info
Nothing -> error ("Invalid introspection XML: " ++ show xml)
-- most of this stuff is just boring text formatting
printObj :: (ObjectPath -> IO I.Object) -> ObjectPath -> IO ()
printObj get path = do
obj <- get path
putStrLn (formatObjectPath path)
mapM_ printIface (I.objectInterfaces obj)
putStrLn ""
mapM_ (printObj get) [I.objectPath x | x <- I.objectChildren obj]
printIface :: I.Interface -> IO ()
printIface iface = do
putStr " "
putStrLn (formatInterfaceName (I.interfaceName iface))
mapM_ printMethod (I.interfaceMethods iface)
mapM_ printSignal (I.interfaceSignals iface)
mapM_ printProperty (I.interfaceProperties iface)
putStrLn ""
printMethod :: I.Method -> IO ()
printMethod method = do
putStr " method "
putStrLn (formatMemberName (I.methodName method))
mapM_ printMethodArg (I.methodArgs method)
printMethodArg :: I.MethodArg -> IO ()
printMethodArg arg = do
let dir = case I.methodArgDirection arg of
d | d == I.directionIn -> "IN "
d | d == I.directionOut -> "OUT"
_ -> " "
putStr (" [" ++ dir ++ " ")
putStr (show (formatSignature (signature_ [I.methodArgType arg])) ++ "] ")
putStrLn (I.methodArgName arg)
printSignal :: I.Signal -> IO ()
printSignal sig = do
putStr " signal "
putStrLn (formatMemberName (I.signalName sig))
mapM_ printSignalArg (I.signalArgs sig)
printSignalArg :: I.SignalArg -> IO ()
printSignalArg arg = do
putStr " ["
putStr (show (formatSignature (signature_ [I.signalArgType arg])) ++ "] ")
putStrLn (I.signalArgName arg)
printProperty :: I.Property -> IO ()
printProperty prop = do
putStr " property "
putStr (show (formatSignature (signature_ [I.propertyType prop])) ++ " ")
putStrLn (I.propertyName prop)
putStr " "
when (I.propertyRead prop) (putStr "Read")
when (I.propertyWrite prop) (putStr "Write")
putStrLn ""
| tmishima/haskell-dbus | examples/introspect.hs | gpl-3.0 | 3,638 | 10 | 17 | 723 | 1,099 | 529 | 570 | 78 | 3 |
{-
This is the bootstrapping compiler for the Bzo programming language.
Copyright (C) 2020 Charles Rosenbauer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.-}
module BzoChecker where
import BzoTypes
import HigherOrder
import Builtins
import TypeChecker
import Core
import Error
import AST
import Data.Text
import Data.Int
import Data.Either as E
import Query
import qualified Data.Map.Strict as M
import qualified Data.Maybe as Mb
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Tuple as Tp
import Control.Parallel.Strategies
import Debug.Trace
noOverloadTypes :: DefinitionTable -> [BzoErr]
noOverloadTypes dt@(DefinitionTable defs files ids _) =
let
types :: [Definition]
types = L.filter isType $ M.elems defs
nubbed:: [Definition]
nubbed = L.nubBy matchType types
in case (types L.\\ nubbed) of
[] -> []
xs -> L.map makeOverloadErr xs
where makeOverloadErr :: Definition -> BzoErr
makeOverloadErr (TypeSyntax p tname _ df) = TypeErr p $ pack $ "Type " ++ (unpack tname) ++ " is defined in multiple places."
makeOverloadErr (TyClassSyntax p tname _ df) = TypeErr p $ pack $ "Type Class " ++ (unpack tname) ++ " is defined in multiple places."
matchType :: Definition -> Definition -> Bool
matchType (TypeSyntax _ t0 f0 _) (TypeSyntax _ t1 f1 _) = (t0 == t1) && (f0 == f1)
matchType (TyClassSyntax _ t0 f0 _) (TyClassSyntax _ t1 f1 _) = (t0 == t1) && (f0 == f1)
matchType _ _ = False
-- Wow, this function is complex. I should dig through this later to see if it can be simplified.
-- Looks like generating a type visibility map sooner might strip a lot of this out.
noUndefinedErrs :: DefinitionTable -> [BzoErr]
noUndefinedErrs dt@(DefinitionTable defs files ids _) =
let
visiblemap :: M.Map Text (S.Set Int64)
visiblemap = M.fromList $ L.map (\fm -> (pack $ bfm_filepath fm, snd $ bfm_fileModel fm)) files
visdefsmap :: M.Map Text [Definition]
visdefsmap = M.map (\vis -> L.map (\x -> Mb.fromJust $ M.lookup x defs) $ S.elems vis) visiblemap
tynamesmap :: M.Map Text (S.Set Text)
tynamesmap = M.map (S.fromList . L.map identifier . L.filter isType) visdefsmap
filedefmap :: M.Map Text [Definition] -- FilePath -> [Definition]
filedefmap = insertManyList M.empty $ L.map (\df -> (hostfile df, df)) $ M.elems defs
filetypmap :: M.Map Text [(Text, BzoPos)] -- FilePath -> [(TyId, Pos)]
filetypmap = M.map (L.concatMap (fromDef getTypes)) filedefmap
typeErrs :: [BzoErr]
typeErrs = L.concat $ parMap rpar (checkScope filetypmap tynamesmap undefTyErr) $ M.keys filetypmap
filenmsmap :: M.Map Text (S.Set Text)
filenmsmap = M.fromList $ L.map (\fm-> (pack $ bfm_filepath fm, getNamespaceSet fm)) files
namedefmap :: M.Map Text [(Text, BzoPos)]
namedefmap = M.fromList $ L.map (\df-> (hostfile df, fromDef getNamespaces df)) $ M.elems defs
nameErrs :: [BzoErr]
nameErrs = L.concat $ parMap rpar (checkScope namedefmap filenmsmap undefNsErr) $ M.keys namedefmap
-- Later I'll have to do something about getting these builtins added into the Definition table.
bltinlist :: [(Text, BzoPos)]
bltinlist = L.concatMap (fromDef getBuiltins) defs
bltinErrs :: [BzoErr]
bltinErrs = L.map (\(bi,ps)-> SntxErr ps $ append bi $ pack " is not a valid built-in.") $ L.filter (\(bi,ps)->(isBuiltinFunc bi == 0) && (isBuiltinType bi == 0)) bltinlist
in typeErrs ++ nameErrs ++ bltinErrs
where
fromDef :: (Show a) => (BzoSyntax -> [a]) -> Definition -> [a]
fromDef f (FuncSyntax _ _ _ ft fd) = (f ft) ++ (L.concatMap f fd)
fromDef f (TypeSyntax _ _ _ td) = (f td)
fromDef f (TyClassSyntax _ _ _ cd) = (f cd)
fromDef f (ImplSyntax _ _ _ _ cd) = (L.concatMap f cd) -- Not sure about this
checkScope :: (M.Map Text [(Text, BzoPos)]) -> (M.Map Text (S.Set Text)) -> (BzoPos -> Text -> BzoErr) -> Text -> [BzoErr]
checkScope refmap vismap mkerr fname =
let refs = refmap M.! fname
viss = vismap M.! fname
missing = L.filter (\(ty,_)-> not $ S.member ty viss) refs
in L.map (\(ty,ps)-> mkerr ps ty) missing
undefTyErr :: BzoPos -> Text -> BzoErr
undefTyErr ps ty = SntxErr ps (append ty (pack " is not defined in the local scope."))
undefNsErr :: BzoPos -> Text -> BzoErr
undefNsErr ps ns = SntxErr ps (append ns (pack " is not a recognized namespace in the local scope."))
modelConstraints :: SymbolTable -> DefinitionTable -> Either [BzoErr] DefinitionTable
modelConstraints st dt@(DefinitionTable defs files ids top) =
let
emptyheader = TyHeader [] M.empty
modelCon :: Constraint -> Either [BzoErr] Constraint
modelCon (Constraint p t) =
let
ft :: FileTable
ft = (getSymTable st) M.! (fileName p)
in case t of
(UnresType ast) -> toRight (Constraint p) $ toRight (replaceTCs dt) $ makeType dt ft emptyheader ast
typ -> Right (Constraint p typ)
modelCons :: (TVId, THeadAtom) -> Either [BzoErr] (TVId, THeadAtom)
modelCons (v, TVrAtom p t cs) = onAllPass (L.map modelCon cs) (\xs -> (v, TVrAtom p t xs))
modelTHead :: TypeHeader -> Either [BzoErr] TypeHeader
modelTHead (TyHeader hs hmap) =
let
hmap' :: Either [BzoErr] [(TVId, THeadAtom)]
hmap' = allPass $ L.map modelCons $ M.assocs hmap
in case hmap' of
Right pass -> Right (TyHeader hs (M.fromList pass))
Left errs -> Left errs
modelType :: Definition -> Either [BzoErr] Definition
modelType (TypeDef p i h th td) =
case (modelTHead th) of
Right th' -> Right (TypeDef p i h th' td)
Left errs -> Left errs
modelType x = Right x
defs' :: Either [BzoErr] [Definition]
defs' = allPass $ L.map modelType $ M.elems defs
in case defs' of
Left errs -> Left errs
Right dfs -> Right (DefinitionTable (M.fromList $ L.zip (M.keys defs) dfs) files ids top)
-- Takes type parameters and returns an associated header
initializeTypeHeader :: TypeHeader -> BzoSyntax -> TypeHeader
initializeTypeHeader hd (BzS_Undefined p) = TyHeader [] M.empty
initializeTypeHeader hd (BzS_Expr _ [x]) = initializeTypeHeader hd x
initializeTypeHeader (TyHeader ps mp) (BzS_TyVar p v) =
TyHeader ps $ M.union mp $ M.fromList [(fromIntegral $ M.size mp, TVrAtom p v [])]
initializeTypeHeader (TyHeader ps mp) (BzS_FilterObj p v fs) =
TyHeader ps $ M.union mp $ M.fromList [(fromIntegral $ M.size mp, TVrAtom p (sid v) (L.map (\t -> Constraint p $ UnresType t) fs))]
initializeTypeHeader (TyHeader ps mp) (BzS_Cmpd _ vs) =
let atoms = L.map makeAtom vs
in TyHeader ps $ M.union mp $ M.fromList $ L.map (\(a,b) -> (fromIntegral $ a+(M.size mp), b)) $ L.zip [0..] $ L.reverse atoms
where
makeAtom :: BzoSyntax -> THeadAtom
makeAtom (BzS_TyVar p v ) =
TVrAtom p v []
makeAtom (BzS_FilterObj p v fs) =
TVrAtom p (sid v) (L.map (\t -> Constraint p $ UnresType t) fs)
makeAtom (BzS_Expr _ [x]) = makeAtom x
initializeTypeHeader hd@(TyHeader ips imp) (BzS_FnTypeDef _ ps fn (BzS_FnTy _ i o)) =
let tyhead = initializeTypeHeader hd ps
importVars :: S.Set Text
importVars = S.fromList $ L.map atomId $ M.elems imp
tvars :: [(Text, BzoPos)]
tvars = (getTVars i) ++ (getTVars o)
vnames :: S.Set Text
vnames = S.fromList $ L.filter (\x -> S.notMember x importVars) $ L.map fst tvars
tvatms :: [THeadAtom]
tvatms = L.map (\(v,p) -> TVrAtom p v []) tvars
tvatms'= L.nubBy (\(TVrAtom _ a _) (TVrAtom _ b _) -> a == b) $ L.filter (\(TVrAtom _ x _) -> S.member x vnames) tvatms
key :: Int64
key = L.maximum $ [0] ++ (M.keys $ tvarmap tyhead)
tvsold :: [(TVId, THeadAtom)]
tvsold = M.assocs $ tvarmap tyhead
tvsnew :: [(TVId, THeadAtom)]
tvsnew = L.zip (L.map (key+) [1..]) tvatms'
tvsall :: [(TVId, THeadAtom)] -- I don't fully trust the nub here, but it seems to mostly work.
tvsall = L.nubBy (\(_, (TVrAtom _ a _)) (_, (TVrAtom _ b _)) -> a == b) $ tvsold ++ tvsnew
in TyHeader ips $ M.union imp $ M.fromList tvsall
initializeTypeHeader hd (BzS_TypDef _ ps ty tydef) =
let tyhead = initializeTypeHeader hd ps
tvars :: [(Text, BzoPos)]
tvars = getTVars tydef
vnames :: S.Set Text
vnames = S.fromList $ L.map fst tvars
tvatms :: [THeadAtom]
tvatms = L.map (\(v,p) -> TVrAtom p v []) tvars
tvatms'= L.nubBy (\(TVrAtom _ a _) (TVrAtom _ b _) -> a == b) $ L.filter (\(TVrAtom _ x _) -> S.member x vnames) tvatms
key :: Int64
key = L.maximum $ [0] ++ (M.keys $ tvarmap tyhead)
tvsold :: [(TVId, THeadAtom)]
tvsold = M.assocs $ tvarmap tyhead
tvsnew :: [(TVId, THeadAtom)]
tvsnew = L.zip (L.map (key+) [1..]) tvatms'
tvsall :: [(TVId, THeadAtom)] -- I don't fully trust the nub here, but it seems to mostly work.
tvsall = L.nubBy (\(_, (TVrAtom _ a _)) (_, (TVrAtom _ b _)) -> a == b) $ tvsold ++ tvsnew
tpars :: [TVId]
tpars = L.take (L.length tvsall) [0..]
in TyHeader tpars $ M.fromList tvsall
initializeTypeHeader' :: BzoSyntax -> TypeHeader
initializeTypeHeader' ast = initializeTypeHeader (TyHeader [] M.empty) ast
makeType :: DefinitionTable -> FileTable -> TypeHeader -> BzoSyntax -> Either [BzoErr] Type
makeType dt ft th (BzS_Expr p [x]) = makeType dt ft th x
makeType dt ft th (BzS_Statement p x) = makeType dt ft th x
makeType dt ft th (BzS_Cmpd p [x]) = makeType dt ft th x
makeType dt ft th (BzS_Poly p [x]) = makeType dt ft th x
makeType dt ft th (BzS_Cmpd p xs) = onAllPass (L.map (makeType dt ft th) xs) (\ys -> CmpdType p ys)
makeType dt ft th (BzS_Poly p xs) = onAllPass (L.map (makeType dt ft th) xs) (\ys -> PolyType p ys)
makeType dt ft th (BzS_Int p n) = Right (IntType p n)
makeType dt ft th (BzS_Flt p n) = Right (FltType p n)
makeType dt ft th (BzS_Str p s) = Right (StrType p s)
makeType dt ft th (BzS_Nil p ) = Right (VoidType p)
makeType dt ft th (BzS_BTId p bit) = Right (BITyType p $ isBuiltinType bit)
makeType dt ft th (BzS_ArrayObj p s x) = onAllPass [makeType dt ft th x] (\[y] -> ArryType p s y)
makeType dt ft th (BzS_FnTy p i o) =
let i' = makeType dt ft th i
o' = makeType dt ft th o
io = rights [i', o']
er = lefts [i', o']
in case (er, io) of
([], [it, ot]) -> Right $ FuncType p it ot
(er, _ ) -> Left $ L.concat er
makeType dt ft th (BzS_Expr p xs) = onAllPass (L.map (makeType dt ft th) xs) (\ys -> MakeType p ys)
makeType dt ft th ty@(BzS_TyId p t) =
let ids = resolveTyId dt ft t
in case ids of
[] -> Left [TypeErr p $ pack ("Type " ++ (unpack t) ++ " is undefined.")]
[x] -> Right (LtrlType p x)
xs -> Left [TypeErr p $ pack ("Ambiguous reference to type " ++ (unpack t) ++ ": " ++ (show xs) ++ " / ")] -- TODO: Redesign this error message
makeType dt ft (TyHeader _ tvs) (BzS_TyVar p v) =
let tvpairs = M.assocs tvs
tvnames = L.map (\(n,atm) -> (n, atomId atm)) tvpairs
ids = L.map fst $ L.filter (\(n,atm) -> v == atm) tvnames
in case ids of
[] -> Left [TypeErr p $ pack ("Type Variable " ++ (unpack v) ++ " is not defined in the type header.")]
[x] -> Right (TVarType p x)
xs -> Left [TypeErr p $ pack ("Ambiguous reference to type variable " ++ (unpack v) ++ ": " ++ (show xs) ++ " / " ++ (show tvs))] -- TODO: Redesign this error message
makeType dt ft th (BzS_Id p f) =
let fids = resolveTyId dt ft f
in case fids of
[] -> Left [TypeErr p $ pack $ "Function " ++ (unpack f) ++ " is not defined in this scope."]
xs -> Right (FLitType p xs)
makeType dt ft th ty@(BzS_Undefined _) = Right (UnresType ty)
makeType dt ft th x = Left [TypeErr (pos x) $ pack $ "Malformed type expression: " ++ show x]
replaceTCs :: DefinitionTable -> Type -> Type
replaceTCs (DefinitionTable defs files ids top) (LtrlType p t) =
case (defs M.! t) of
(TyClassDef _ _ _ _ _) -> (TCType p t)
(TyClassSyntax _ _ _ _) -> (TCType p t)
_ -> (LtrlType p t)
replaceTCs dt (CmpdType p xs) = (CmpdType p (L.map (replaceTCs dt) xs))
replaceTCs dt (PolyType p xs) = (PolyType p (L.map (replaceTCs dt) xs))
replaceTCs dt (MakeType p xs) = (MakeType p (L.map (replaceTCs dt) xs))
replaceTCs dt (ArryType p s x) = (ArryType p s (replaceTCs dt x))
replaceTCs dt (FuncType p i o) = (FuncType p (replaceTCs dt i) (replaceTCs dt o))
replaceTCs dt t = t
data SymbolTable = SymbolTable (M.Map Text FileTable) deriving Show
getSymTable :: SymbolTable -> M.Map Text FileTable
getSymTable (SymbolTable stab) = stab
getFileTable:: SymbolTable -> Text -> Maybe FileTable
getFileTable (SymbolTable stab) file = M.lookup file stab
data FileTable = FileTable (M.Map Text [Int64]) deriving Show
resolveTyId :: DefinitionTable -> FileTable -> Text -> [Int64]
resolveTyId (DefinitionTable defs files ids top) (FileTable ds) d = L.filter (\x -> isType (defs M.! x)) $ Mb.fromMaybe [] $ M.lookup d ds
resolveFnId :: DefinitionTable -> FileTable -> Text -> [Int64]
resolveFnId (DefinitionTable defs files ids top) (FileTable ds) d = L.filter (\x -> isFunc (defs M.! x)) $ Mb.fromMaybe [] $ M.lookup d ds
makeFileTable :: M.Map Text [Int64] -> BzoFileModel (S.Set Int64, S.Set Int64) -> (Text, FileTable)
makeFileTable dmap (BzoFileModel _ fp _ (_, vis) _ _ _ _) =
let
dlist :: M.Map Text [Int64]
dlist = M.fromList $
L.filter (\(n, is) -> (L.length is) > 0) $
L.map (\(n, is) -> (n, L.filter (\v -> S.member v vis) is)) $
M.assocs dmap
in (pack fp, FileTable dlist)
makeSymbolTable :: DefinitionTable -> SymbolTable
makeSymbolTable (DefinitionTable defs files ids top) = SymbolTable $ M.fromList $ L.map (makeFileTable ids) files
makeTypes :: DefinitionTable -> Either [BzoErr] DefinitionTable
makeTypes dt@(DefinitionTable defs files ids top) =
let
-- Make Symbol Table
syms :: SymbolTable
syms = makeSymbolTable dt
-- Function for getting a File Table from a File Path
getFTab :: Text -> FileTable
getFTab fp = (getSymTable syms) M.! fp
-- Function for generating typeheaders, types, and packaging them up nicely with error handling
constructType :: BzoSyntax -> BzoSyntax -> Text -> (TypeHeader -> Type -> b) -> Either [BzoErr] b
constructType thead tdef host fn =
let
tyhead :: TypeHeader
tyhead = initializeTypeHeader' thead
typ :: Either [BzoErr] Type
typ = toRight flattenPolys $ toRight (replaceTCs dt) $ makeType dt (getFTab host) tyhead tdef
in applyRight (fn tyhead) typ
separateImpl :: BzoSyntax -> (Text, BzoSyntax)
separateImpl (BzS_FunDef _ _ fnid _ def) = (fnid, def)
getTCIds :: BzoPos -> DefinitionTable -> Text -> Text -> FilePath -> Either [BzoErr] (Int64, Int64)
getTCIds p dt@(DefinitionTable dfs fs ids top) tc ty namespace =
let
files :: [BzoFileModel (S.Set Int64, S.Set Int64)]
files = L.filter (\x -> namespace == (bfm_filepath x)) fs
visibility :: S.Set Int64
visibility = snd $ bfm_fileModel $ L.head files
-- Get ids that match tc, filter by visibility
visimps :: [Int64]
visimps = L.filter (\x -> S.member x visibility) $ Mb.fromMaybe [] $ M.lookup ty ids
vistyps :: [Int64]
vistyps = L.filter (\x -> S.member x visibility) $ Mb.fromMaybe [] $ M.lookup tc ids
-- Filter ids by Impl of Type
imps :: [Int64]
imps = L.map fst $ L.filter (\(_,x) -> tc == (classimpl x)) $ L.filter (\(_,x) -> isImpl x) $ L.map (\x -> (x, dfs M.! x)) visimps
-- Filter ids by Type. Not sure if I actually need this.
typs :: [Int64]
typs = L.map fst $ L.filter (\(_,x) -> tc == (identifier x)) $ L.filter (\(_,x) -> isType x) $ L.map (\x -> (x, dfs M.! x)) vistyps
in case (files, imps, typs) of
([] , _, _) -> Left [TypeErr p $ pack $ "Namespace " ++ namespace ++ " is invalid."]
([x], [i], [t]) -> Right (i, t)
(_ , [], ts) -> Left [TypeErr p $ pack $ "Type " ++ (unpack ty) ++ " has no implementations of class " ++ (unpack tc)]
(_ , is, []) -> Left [TypeErr p $ pack $ "Type " ++ (unpack ty) ++ " implements non-existent class " ++ (unpack tc)]
(_ , is, ts) -> Left [TypeErr p $ pack $ "Type " ++ (unpack ty) ++ " has multiple implementations of class " ++ (unpack tc)]
-- Function for translating definitions to use TYPE and TYPEHEADER rather than BZOSYNTAX.
translateDef :: DefinitionTable -> Definition -> Either [BzoErr] Definition
translateDef dt (FuncSyntax p fn host fty@(BzS_FnTypeDef _ _ _ _) []) = Left [SntxErr p $ pack $ "Function type " ++ (unpack fn) ++ " has no accompanying definition."]
translateDef dt (FuncSyntax p fn host fty@(BzS_FnTypeDef _ ps _ ft) fs) = constructType fty ft host (\th t -> (FuncDef p fn host th t fs))
translateDef dt (TypeSyntax p ty host tyd@(BzS_TypDef _ ps _ td) ) = constructType tyd td host (\th t -> (TypeDef p ty host th t ))
translateDef dt (TyClassSyntax p tc host tcd@(BzS_TyClassDef _ ps _ td) ) =
let
thead :: TypeHeader
thead = (initializeTypeHeader' ps)
interface :: Either [BzoErr] [(Text, TypeHeader, Type)]
interface = allPass $ L.map (xformTCFunc host thead) td
in case interface of
Left errs -> Left errs
Right itf -> Right (TyClassDef p tc host thead itf)
translateDef dt (ImplSyntax p it tc host fns) =
case getTCIds p dt tc it (unpack host) of
Left er -> Left er
Right (i,t) -> Right $ (ImplDef p it tc i t host (L.map separateImpl fns))
translateDef dt (FuncSyntax p fn host (BzS_Undefined _) fs) = Left [SntxErr p $ pack $ "Function definition " ++ (unpack fn) ++ " has no accompanying type."]
-- Function for reformatting typeclass interfaces
xformTCFunc :: Text -> TypeHeader -> BzoSyntax -> Either [BzoErr] (Text, TypeHeader, Type)
xformTCFunc host th fty@(BzS_FnTypeDef _ ps fn ft) =
let
thead:: TypeHeader
thead= initializeTypeHeader th fty
thead'::TypeHeader
thead'= TyHeader ((header th) ++ (header thead)) (M.union (tvarmap th) (tvarmap thead))
ftyp :: Either [BzoErr] Type
ftyp = toRight (replaceTCs dt) $ makeType dt (getFTab host) thead' ft
in case ftyp of
Right typ -> Right (fn, thead', typ)
Left err -> Left err
-- Helper function for applying xforms to key-value pairs with error handling
preserveId :: (b -> Either [c] d) -> (a, b) -> Either [c] (a, d)
preserveId f (i, x) =
case (f x) of
Left err -> Left err
Right x' -> Right (i, x')
-- Xformed Definitions
results :: Either [BzoErr] (M.Map Int64 Definition)
results = toRight M.fromList $ allPass $ L.map (preserveId (translateDef dt)) $ M.assocs defs
-- TODO:
-- -- Check that make types are all valid (e.g, nothing like "Int Bool" as a definition.)
dt' :: Either [BzoErr] DefinitionTable
dt' = modelConstraints syms (DefinitionTable (E.fromRight M.empty results) files ids top)
dt'' :: [DefinitionTable]
dt'' = rights [dt']
dterr :: [BzoErr]
dterr = E.fromLeft [] dt'
errs :: [BzoErr]
errs = (E.fromLeft [] results) ++ dterr
in if (not $ L.null errs)
then (Left errs)
else case ((recursivePolycheck $ L.head dt'') ++ (validateTypePass $ L.head dt'')) of
[] -> Right $ L.head dt''
er -> Left er
flattenPolys :: Type -> Type
flattenPolys (CmpdType p xs) = (CmpdType p $ L.map flattenPolys xs)
flattenPolys (ArryType p s t) = (ArryType p s $ flattenPolys t)
flattenPolys (FuncType p i o) = (FuncType p (flattenPolys i) (flattenPolys o))
flattenPolys (MakeType p xs) = (MakeType p $ L.map flattenPolys xs)
flattenPolys (PolyType p xs) = (PolyType p $ flatpol $ L.map flattenPolys xs)
where
flatpol:: [Type] -> [Type]
flatpol [] = []
flatpol ((PolyType p xs):xss) = xs ++ (flatpol xss)
flatpol (x:xss) = (x : flatpol xss)
flattenPolys x = x
recursivePolycheck :: DefinitionTable -> [BzoErr]
recursivePolycheck (DefinitionTable defs files ids top) =
let
getTyIds:: [Type] -> [Int64]
getTyIds ((LtrlType _ x):xs) = x : (getTyIds xs)
getTyIds (_:xs) = getTyIds xs
getTyIds [] = []
flatten :: Type -> S.Set Int64 -> S.Set Int64
flatten (PolyType _ xs) oldset = S.union oldset $ S.fromList $ getTyIds xs
flatten (LtrlType _ t) oldset = S.insert t oldset
flatten _ oldset = S.empty
recurse :: M.Map Int64 (S.Set Int64) -> S.Set Int64 -> S.Set Int64
recurse polyset oldset = L.foldl S.union S.empty $ Mb.catMaybes $ L.map (\k -> M.lookup k polyset) $ S.elems oldset
polysets :: M.Map Int64 (S.Set Int64)
polysets = M.fromList $
L.map (\(k,d) -> (k, flatten (typedef d) $ S.empty)) $
L.filter (\(k,d) -> isTyDef d) $
M.assocs defs
noPolyrec :: BzoPos -> (Int64, S.Set Int64) -> [BzoErr]
noPolyrec p (k, set) =
if (S.member k set)
then [TypeErr p $ pack ("Type " ++ (unpack $ identifier $ defs M.! k) ++ " has invalid recursive structure")]
else []
whileRec :: M.Map Int64 (S.Set Int64) -> [BzoErr]
whileRec polyset =
let
polyset' :: M.Map Int64 (S.Set Int64)
polyset' = M.map (recurse polyset) polyset
errs :: [BzoErr]
errs = L.concatMap (\(k,d) -> noPolyrec (typos $ typedef $ defs M.! k) (k,d)) $ M.assocs polyset'
grow :: Bool
grow = L.any (\(k,d) -> (S.size $ polyset M.! k) /= (S.size d)) $ M.assocs polyset
in case (errs, grow) of
([], False) -> []
([], True ) -> whileRec polyset'
(er, _ ) -> er
in whileRec polysets
checkProgram :: DefinitionTable -> Either [BzoErr] DefinitionTable
checkProgram dt@(DefinitionTable defs files ids top) =
let
-- No type overloads
err0 :: [BzoErr]
err0 = noOverloadTypes dt
-- No undefined types
err1 :: [BzoErr]
err1 = noUndefinedErrs dt
--TODO:
-- Construct namespace mapping
-- Construct types and typeheaders for all functions, types, and type classes
-- Check that types are valid - mostly that type constructors obey headers
-- Construct type class models
err2 :: [BzoErr]
dt' :: [DefinitionTable]
(err2, dt') = splitEitherList $ makeTypes dt
testerr = (\x -> trace ("Errs:\n" ++ (L.concatMap show x) ++ "\n") x) $ testTypeCheck $ L.head dt'
errs :: [BzoErr]
errs = err0 ++ err1 ++ err2
in case (errs) of
([]) -> Right $ L.head dt'
(er) -> Left er
| charlesrosenbauer/Bzo-Compiler | src/BzoChecker.hs | gpl-3.0 | 24,237 | 0 | 21 | 6,661 | 9,377 | 4,845 | 4,532 | 396 | 16 |
{-# LANGUAGE NoImplicitPrelude, FlexibleContexts, OverloadedStrings, TypeFamilies, Rank2Types, PatternGuards, RecordWildCards #-}
module Lamdu.Sugar.Convert.Binder
( convertBinder, convertLam
) where
import Prelude.Compat
import Control.Lens (Lens')
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (guard, void, when, join)
import Control.MonadA (MonadA)
import Data.Foldable (traverse_)
import qualified Data.List as List
import qualified Data.List.Utils as ListUtils
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Store.Guid (Guid)
import Data.Store.Property (Property)
import qualified Data.Store.Property as Property
import Data.Store.Transaction (Transaction, MkProperty)
import qualified Data.Store.Transaction as Transaction
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Data.Anchors as Anchors
import qualified Lamdu.Data.Ops as DataOps
import Lamdu.Eval.Val (ScopeId)
import qualified Lamdu.Eval.Val as EV
import qualified Lamdu.Expr.GenIds as GenIds
import qualified Lamdu.Expr.IRef as ExprIRef
import qualified Lamdu.Expr.Lens as ExprLens
import Lamdu.Expr.Type (Type)
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.UniqueId as UniqueId
import Lamdu.Expr.Val (Val(..))
import qualified Lamdu.Expr.Val as V
import qualified Lamdu.Infer as Infer
import Lamdu.Sugar.Convert.Expression.Actions (addActions, makeAnnotation)
import qualified Lamdu.Sugar.Convert.Input as Input
import Lamdu.Sugar.Convert.Monad (ConvertM)
import qualified Lamdu.Sugar.Convert.Monad as ConvertM
import Lamdu.Sugar.Convert.ParamList (ParamList)
import Lamdu.Sugar.Internal
import qualified Lamdu.Sugar.Internal.EntityId as EntityId
import Lamdu.Sugar.OrderTags (orderedFlatComposite)
import Lamdu.Sugar.Types
type T = Transaction
data ConventionalParams m a = ConventionalParams
{ cpTags :: Set T.Tag
, cpParamInfos :: Map T.Tag ConvertM.TagParamInfo
, _cpParams :: BinderParams Guid m
, cpMAddFirstParam :: Maybe (T m ParamAddResult)
, cpScopes :: Map ScopeId [ScopeId]
, cpMLamParam :: Maybe V.Var
}
cpParams :: Lens' (ConventionalParams m a) (BinderParams Guid m)
cpParams f ConventionalParams {..} = f _cpParams <&> \_cpParams -> ConventionalParams{..}
data FieldParam = FieldParam
{ fpTag :: T.Tag
, fpFieldType :: Type
, fpValue :: Map ScopeId [(ScopeId, EV.EvalResult ())]
}
onMatchingSubexprs ::
MonadA m => (a -> m ()) -> (a -> Val () -> Bool) -> Val a -> m ()
onMatchingSubexprs action predicate =
Lens.itraverseOf_ (ExprLens.subExprPayloads . Lens.ifiltered (flip predicate))
(const action)
onMatchingSubexprsWithPath ::
MonadA m => (a -> m ()) -> (a -> [Val ()] -> Bool) -> Val a -> m ()
onMatchingSubexprsWithPath action predicate =
Lens.itraverseOf_ (ExprLens.payloadsIndexedByPath . Lens.ifiltered (flip predicate))
(const action)
toHole :: MonadA m => ExprIRef.ValIProperty m -> T m ()
toHole = void . DataOps.setToHole
isGetVarOf :: V.Var -> Val a -> Bool
isGetVarOf = Lens.anyOf ExprLens.valVar . (==)
data StoredLam m = StoredLam
{ _slLam :: V.Lam (Val (ExprIRef.ValIProperty m))
, slLambdaProp :: ExprIRef.ValIProperty m
}
slLam :: Lens' (StoredLam m) (V.Lam (Val (ExprIRef.ValIProperty m)))
slLam f StoredLam{..} = f _slLam <&> \_slLam -> StoredLam{..}
mkStoredLam ::
V.Lam (Val (Input.Payload m a)) ->
Input.Payload m a -> Maybe (StoredLam m)
mkStoredLam lam pl =
StoredLam
<$> (lam & (traverse . traverse) (^. Input.mStored))
<*> pl ^. Input.mStored
changeRecursionsFromCalls :: MonadA m => V.Var -> Val (ExprIRef.ValIProperty m) -> T m ()
changeRecursionsFromCalls var =
onMatchingSubexprs changeRecursion (const isCall)
where
isCall (Val _ (V.BApp (V.Apply f _))) = isGetVarOf var f
isCall _ = False
changeRecursion prop =
do
body <- ExprIRef.readValBody (Property.value prop)
case body of
V.BApp (V.Apply f _) -> Property.set prop f
_ -> error "assertion: expected BApp"
makeDeleteLambda ::
MonadA m => Maybe V.Var -> StoredLam m ->
ConvertM m (T m ParamDelResult)
makeDeleteLambda mRecursiveVar (StoredLam (V.Lam paramVar lamBodyStored) lambdaProp) =
do
protectedSetToVal <- ConvertM.typeProtectedSetToVal
return $
do
getVarsToHole paramVar lamBodyStored
mRecursiveVar
& Lens._Just %%~ (`changeRecursionsFromCalls` lamBodyStored)
& void
let lamBodyI = Property.value (lamBodyStored ^. V.payload)
_ <- protectedSetToVal lambdaProp lamBodyI
return ParamDelResultDelVar
newTag :: MonadA m => T m T.Tag
newTag = GenIds.transaction GenIds.randomTag
isRecursiveCallArg :: V.Var -> [Val ()] -> Bool
isRecursiveCallArg recursiveVar (cur : parent : _) =
Lens.allOf ExprLens.valVar (/= recursiveVar) cur &&
Lens.anyOf (ExprLens.valApply . V.applyFunc . ExprLens.valVar)
(== recursiveVar) parent
isRecursiveCallArg _ _ = False
-- TODO: find nicer way to do it than using properties and rereading
-- data? Perhaps keep track of the up-to-date pure val as it is being
-- mutated?
rereadVal :: MonadA m => ExprIRef.ValIProperty m -> T m (Val (ExprIRef.ValIProperty m))
rereadVal valProp =
ExprIRef.readVal (Property.value valProp)
<&> fmap (flip (,) ())
<&> ExprIRef.addProperties (Property.set valProp)
<&> fmap fst
changeRecursiveCallArgs ::
MonadA m =>
(ExprIRef.ValI m -> T m (ExprIRef.ValI m)) ->
ExprIRef.ValIProperty m -> V.Var -> T m ()
changeRecursiveCallArgs change valProp var =
-- Reread body before fixing it,
-- to avoid re-writing old data (without converted vars)
rereadVal valProp
>>= onMatchingSubexprsWithPath changeRecurseArg (const (isRecursiveCallArg var))
where
changeRecurseArg prop =
Property.value prop
& change
>>= Property.set prop
wrapArgWithRecord :: MonadA m => T.Tag -> T.Tag -> ExprIRef.ValI m -> T m (ExprIRef.ValI m)
wrapArgWithRecord tagForExistingArg tagForNewArg oldArg =
do
hole <- DataOps.newHole
ExprIRef.newValBody (V.BLeaf V.LRecEmpty)
>>= ExprIRef.newValBody . V.BRecExtend . V.RecExtend tagForNewArg hole
>>= ExprIRef.newValBody . V.BRecExtend . V.RecExtend tagForExistingArg oldArg
convertVarToGetField ::
MonadA m => T.Tag -> V.Var -> Val (Property (T m) (ExprIRef.ValI m)) -> T m ()
convertVarToGetField tagForVar paramVar =
onMatchingSubexprs (convertVar . Property.value) (const (isGetVarOf paramVar))
where
convertVar bodyI =
ExprIRef.newValBody (V.BLeaf (V.LVar paramVar))
<&> (`V.GetField` tagForVar) <&> V.BGetField
>>= ExprIRef.writeValBody bodyI
data NewParamPosition = NewParamBefore | NewParamAfter
makeConvertToRecordParams ::
MonadA m => Maybe V.Var -> StoredLam m ->
ConvertM m (NewParamPosition -> T m ParamAddResult)
makeConvertToRecordParams mRecursiveVar (StoredLam (V.Lam paramVar lamBody) lamProp) =
do
wrapOnError <- ConvertM.wrapOnTypeError
return $ \newParamPosition ->
do
tagForVar <- newTag
tagForNewVar <- newTag
setParamList paramList $ case newParamPosition of
NewParamBefore -> [tagForNewVar, tagForVar]
NewParamAfter -> [tagForVar, tagForNewVar]
convertVarToGetField tagForVar paramVar lamBody
mRecursiveVar
& traverse_
(changeRecursiveCallArgs
(wrapArgWithRecord tagForVar tagForNewVar)
(lamBody ^. V.payload))
_ <- wrapOnError lamProp
return $ ParamAddResultVarToTags VarToTags
{ vttReplacedVar = paramVar
, vttReplacedVarEntityId = EntityId.ofLambdaParam paramVar
, vttReplacedByTag = tagGForLambdaTagParam paramVar tagForVar
, vttNewTag = tagGForLambdaTagParam paramVar tagForNewVar
}
where
paramList = Anchors.assocFieldParamList (Property.value lamProp)
tagGForLambdaTagParam :: V.Var -> T.Tag -> TagG ()
tagGForLambdaTagParam paramVar tag = TagG (EntityId.ofLambdaTagParam paramVar tag) tag ()
convertRecordParams ::
(MonadA m, Monoid a) =>
Maybe V.Var -> [FieldParam] ->
V.Lam (Val (Input.Payload m a)) -> Input.Payload m a ->
ConvertM m (ConventionalParams m a)
convertRecordParams mRecursiveVar fieldParams lam@(V.Lam param _) pl =
do
params <- traverse mkParam fieldParams
mAddFirstParam <-
mStoredLam
& Lens.traverse %%~ makeAddFieldParam mRecursiveVar param (:tags)
pure ConventionalParams
{ cpTags = Set.fromList tags
, cpParamInfos = mconcat $ mkParamInfo <$> fieldParams
, _cpParams = FieldParams params
, cpMAddFirstParam = mAddFirstParam
, cpScopes = pl ^. Input.evalAppliesOfLam <&> map fst
, cpMLamParam = Just param
}
where
tags = fpTag <$> fieldParams
fpIdEntityId = EntityId.ofLambdaTagParam param . fpTag
mkParamInfo fp =
Map.singleton (fpTag fp) . ConvertM.TagParamInfo param $ fpIdEntityId fp
mStoredLam = mkStoredLam lam pl
mkParam fp =
do
actions <-
mStoredLam
& Lens.traverse %%~ makeFieldParamActions mRecursiveVar param tags fp
pure
( fpTag fp
, FuncParam
{ _fpInfo =
NamedParamInfo
{ _npiName = UniqueId.toGuid $ fpTag fp
, _npiMActions = actions
}
, _fpId = fpIdEntityId fp
, _fpAnnotation =
Annotation
{ _aInferredType = fpFieldType fp
, _aMEvaluationResult =
do
fpValue fp & Map.null & not & guard
fpValue fp ^.. Lens.traversed . Lens.traversed
& Map.fromList & Just
}
, _fpHiddenIds = []
}
)
setParamList :: MonadA m => MkProperty m (Maybe [T.Tag]) -> [T.Tag] -> T m ()
setParamList paramListProp newParamList =
do
zip newParamList [0..] & mapM_ (uncurry setParamOrder)
Just newParamList & Transaction.setP paramListProp
where
setParamOrder = Transaction.setP . Anchors.assocTagOrder
makeAddFieldParam ::
MonadA m =>
Maybe V.Var -> V.Var -> (T.Tag -> ParamList) -> StoredLam m ->
ConvertM m (T m ParamAddResult)
makeAddFieldParam mRecursiveVar param mkNewTags storedLam =
do
wrapOnError <- ConvertM.wrapOnTypeError
return $
do
tag <- newTag
mkNewTags tag & setParamList (slParamList storedLam)
let addFieldToCall argI =
do
hole <- DataOps.newHole
ExprIRef.newValBody $ V.BRecExtend $ V.RecExtend tag hole argI
mRecursiveVar
& Lens.traverse %%~
changeRecursiveCallArgs addFieldToCall
(storedLam ^. slLam . V.lamResult . V.payload)
& void
void $ wrapOnError $ slLambdaProp storedLam
return $
ParamAddResultNewTag $
TagG (EntityId.ofLambdaTagParam param tag) tag ()
makeFieldParamActions ::
MonadA m =>
Maybe V.Var -> V.Var -> [T.Tag] -> FieldParam -> StoredLam m ->
ConvertM m (FuncParamActions m)
makeFieldParamActions mRecursiveVar param tags fp storedLam =
do
addParam <- makeAddFieldParam mRecursiveVar param mkNewTags storedLam
delParam <- makeDelFieldParam mRecursiveVar tags fp storedLam
pure FuncParamActions
{ _fpAddNext = addParam
, _fpDelete = delParam
}
where
mkNewTags tag =
break (== fpTag fp) tags & \(pre, x:post) -> pre ++ [x, tag] ++ post
fixRecursiveCallRemoveField ::
MonadA m =>
T.Tag -> ExprIRef.ValI m -> T m (ExprIRef.ValI m)
fixRecursiveCallRemoveField tag argI =
do
body <- ExprIRef.readValBody argI
case body of
V.BRecExtend (V.RecExtend t v restI)
| t == tag -> return restI
| otherwise ->
do
newRestI <- fixRecursiveCallRemoveField tag restI
when (newRestI /= restI) $
ExprIRef.writeValBody argI $
V.BRecExtend $ V.RecExtend t v newRestI
return argI
_ -> return argI
fixRecursiveCallToSingleArg ::
MonadA m => T.Tag -> ExprIRef.ValI m -> T m (ExprIRef.ValI m)
fixRecursiveCallToSingleArg tag argI =
do
body <- ExprIRef.readValBody argI
case body of
V.BRecExtend (V.RecExtend t v restI)
| t == tag -> return v
| otherwise -> fixRecursiveCallToSingleArg tag restI
_ -> return argI
getFieldParamsToParams :: MonadA m => StoredLam m -> T.Tag -> T m ()
getFieldParamsToParams (StoredLam (V.Lam param lamBody) _) tag =
onMatchingSubexprs (toParam . Property.value)
(const (isGetFieldParam param tag)) lamBody
where
toParam bodyI = ExprIRef.writeValBody bodyI $ V.BLeaf $ V.LVar param
makeDelFieldParam ::
MonadA m =>
Maybe V.Var -> [T.Tag] -> FieldParam -> StoredLam m ->
ConvertM m (T m ParamDelResult)
makeDelFieldParam mRecursiveVar tags fp storedLam =
do
wrapOnError <- ConvertM.wrapOnTypeError
return $
do
Transaction.setP (slParamList storedLam) newTags
getFieldParamsToHole tag storedLam
mLastTag
& traverse_ (getFieldParamsToParams storedLam)
mRecursiveVar
& traverse_
(changeRecursiveCallArgs fixRecurseArg
(storedLam ^. slLam . V.lamResult . V.payload))
_ <- wrapOnError $ slLambdaProp storedLam
return delResult
where
paramVar = storedLam ^. slLam . V.lamParamId
tag = fpTag fp
fixRecurseArg =
maybe (fixRecursiveCallRemoveField tag)
fixRecursiveCallToSingleArg mLastTag
(newTags, mLastTag, delResult) =
case List.delete tag tags of
[x] ->
( Nothing
, Just x
, ParamDelResultTagsToVar TagsToVar
{ ttvReplacedTag = tagGForLambdaTagParam paramVar x
, ttvReplacedByVar = paramVar
, ttvReplacedByVarEntityId = EntityId.ofLambdaParam paramVar
, ttvDeletedTag = tagGForLambdaTagParam paramVar tag
}
)
xs -> (Just xs, Nothing, ParamDelResultDelTag)
slParamList :: MonadA m => StoredLam m -> Transaction.MkProperty m (Maybe ParamList)
slParamList = Anchors.assocFieldParamList . Property.value . slLambdaProp
makeNonRecordParamActions ::
MonadA m => Maybe V.Var -> StoredLam m ->
ConvertM m (FuncParamActions m, T m ParamAddResult)
makeNonRecordParamActions mRecursiveVar storedLam =
do
delete <- makeDeleteLambda mRecursiveVar storedLam
convertToRecordParams <- makeConvertToRecordParams mRecursiveVar storedLam
return
( FuncParamActions
{ _fpAddNext = convertToRecordParams NewParamAfter
, _fpDelete = delete
}
, convertToRecordParams NewParamBefore
)
lamParamType :: Input.Payload m a -> Type
lamParamType lamExprPl =
fromMaybe (error "Lambda value not inferred to a function type?!") $
lamExprPl ^? Input.inferred . Infer.plType . ExprLens._TFun . _1
mkFuncParam :: EntityId -> Input.Payload m a -> info -> FuncParam info
mkFuncParam paramEntityId lamExprPl info =
FuncParam
{ _fpInfo = info
, _fpId = paramEntityId
, _fpAnnotation =
Annotation
{ _aInferredType = lamParamType lamExprPl
, _aMEvaluationResult =
do
lamExprPl ^. Input.evalAppliesOfLam
& Map.null & not & guard
lamExprPl ^.. Input.evalAppliesOfLam .
Lens.traversed . Lens.traversed
& Map.fromList & Just
}
, _fpHiddenIds = []
}
convertNonRecordParam ::
MonadA m => Maybe V.Var ->
V.Lam (Val (Input.Payload m a)) -> Input.Payload m a ->
ConvertM m (ConventionalParams m a)
convertNonRecordParam mRecursiveVar lam@(V.Lam param _) lamExprPl =
do
mActions <- mStoredLam & Lens._Just %%~ makeNonRecordParamActions mRecursiveVar
let funcParam =
case lamParamType lamExprPl of
T.TRecord T.CEmpty
| isParamUnused lam ->
mActions
<&> (^. _1 . fpDelete)
<&> void
<&> NullParamActions
& NullParamInfo
& mkFuncParam paramEntityId lamExprPl & NullParam
_ ->
NamedParamInfo
{ _npiName = UniqueId.toGuid param
, _npiMActions = mActions <&> fst
} & mkFuncParam paramEntityId lamExprPl & VarParam
pure ConventionalParams
{ cpTags = mempty
, cpParamInfos = Map.empty
, _cpParams = funcParam
, cpMAddFirstParam = mActions <&> snd
, cpScopes = lamExprPl ^. Input.evalAppliesOfLam <&> map fst
, cpMLamParam = Just param
}
where
mStoredLam = mkStoredLam lam lamExprPl
paramEntityId = EntityId.ofLambdaParam param
isParamAlwaysUsedWithGetField :: V.Lam (Val a) -> Bool
isParamAlwaysUsedWithGetField (V.Lam param body) =
Lens.nullOf (ExprLens.payloadsIndexedByPath . Lens.ifiltered cond) body
where
cond (_ : Val () V.BGetField{} : _) _ = False
cond (Val () (V.BLeaf (V.LVar v)) : _) _ = v == param
cond _ _ = False
-- TODO: move to eval vals
extractField :: T.Tag -> EV.EvalResult pl -> EV.EvalResult pl
extractField _ (Left err) = Left err
extractField tag (Right (EV.HRecExtend (V.RecExtend vt vv vr)))
| vt == tag = vv
| otherwise = extractField tag vr
extractField tag (Right x) =
"Expected record with tag: " ++ show tag ++ " got: " ++ show (void x)
& EV.EvalTypeError & Left
isParamUnused :: V.Lam (Val a) -> Bool
isParamUnused (V.Lam var body) =
Lens.allOf (ExprLens.valLeafs . ExprLens._LVar) (/= var) body
convertLamParams ::
(MonadA m, Monoid a) =>
Maybe V.Var ->
V.Lam (Val (Input.Payload m a)) -> Input.Payload m a ->
ConvertM m (ConventionalParams m a)
convertLamParams mRecursiveVar lambda lambdaPl =
do
tagsInOuterScope <- ConvertM.readContext <&> Map.keysSet . (^. ConvertM.scTagParamInfos)
case lambdaPl ^. Input.inferred . Infer.plType of
T.TFun (T.TRecord composite) _
| Nothing <- extension
, ListUtils.isLengthAtLeast 2 fields
, Set.null (tagsInOuterScope `Set.intersection` tagsInInnerScope)
, isParamAlwaysUsedWithGetField lambda ->
convertRecordParams mRecursiveVar fieldParams lambda lambdaPl
where
tagsInInnerScope = Set.fromList $ fst <$> fields
(fields, extension) = orderedFlatComposite composite
fieldParams = map makeFieldParam fields
_ -> convertNonRecordParam mRecursiveVar lambda lambdaPl
where
makeFieldParam (tag, typeExpr) =
FieldParam
{ fpTag = tag
, fpFieldType = typeExpr
, fpValue =
lambdaPl ^. Input.evalAppliesOfLam
<&> Lens.mapped . Lens._2 %~ extractField tag
}
convertEmptyParams :: MonadA m =>
Maybe V.Var -> Val (Input.Payload m a) -> ConvertM m (ConventionalParams m a)
convertEmptyParams mRecursiveVar val =
do
protectedSetToVal <- ConvertM.typeProtectedSetToVal
let makeAddFirstParam storedVal =
do
(newParam, dst) <- DataOps.lambdaWrap (storedVal ^. V.payload)
case mRecursiveVar of
Nothing -> return ()
Just recursiveVar -> changeRecursionsToCalls recursiveVar storedVal
void $ protectedSetToVal (storedVal ^. V.payload) dst
return $
ParamAddResultNewVar (EntityId.ofLambdaParam newParam) newParam
pure
ConventionalParams
{ cpTags = mempty
, cpParamInfos = Map.empty
, _cpParams = DefintionWithoutParams
, cpMAddFirstParam =
val
<&> (^. Input.mStored)
& sequenceA
& Lens._Just %~ makeAddFirstParam
, cpScopes =
-- Collect scopes from all evaluated subexpressions.
val ^..
ExprLens.subExprPayloads . Input.evalResults .
Lens.to Map.keys . Lens.traversed
<&> join (,) & Map.fromList <&> (:[])
, cpMLamParam = Nothing
}
convertParams ::
(MonadA m, Monoid a) =>
Maybe V.Var -> Val (Input.Payload m a) ->
ConvertM m
( ConventionalParams m a
, Val (Input.Payload m a)
)
convertParams mRecursiveVar expr =
case expr ^. V.body of
V.BAbs lambda ->
do
params <-
convertLamParams mRecursiveVar lambda (expr ^. V.payload)
-- The lambda disappears here, so add its id to the first
-- param's hidden ids:
<&> cpParams . _VarParam . fpHiddenIds <>~ hiddenIds
<&> cpParams . _FieldParams . Lens.ix 0 . _2 . fpHiddenIds <>~ hiddenIds
return (params, lambda ^. V.lamResult)
where
hiddenIds = [expr ^. V.payload . Input.entityId]
_ ->
do
params <- convertEmptyParams mRecursiveVar expr
return (params, expr)
changeRecursionsToCalls :: MonadA m => V.Var -> Val (ExprIRef.ValIProperty m) -> T m ()
changeRecursionsToCalls =
onMatchingSubexprs changeRecursion . const . isGetVarOf
where
changeRecursion prop =
DataOps.newHole
>>= ExprIRef.newValBody . V.BApp . V.Apply (Property.value prop)
>>= Property.set prop
data ExprLetItem a = ExprLetItem
{ ewiBody :: Val a
, ewiBodyScopesMap :: Map ScopeId ScopeId
, ewiParam :: V.Var
, ewiArg :: Val a
, ewiHiddenPayloads :: [a]
, ewiAnnotation :: Annotation
}
mExtractLet :: Val (Input.Payload m a) -> Maybe (ExprLetItem (Input.Payload m a))
mExtractLet expr = do
V.Apply func arg <- expr ^? ExprLens.valApply
V.Lam param body <- func ^? V.body . ExprLens._BAbs
Just ExprLetItem
{ ewiBody = body
, ewiBodyScopesMap =
func ^. V.payload . Input.evalAppliesOfLam
<&> extractRedexApplies
, ewiParam = param
, ewiArg = arg
, ewiHiddenPayloads = (^. V.payload) <$> [expr, func]
, ewiAnnotation = makeAnnotation (arg ^. V.payload)
}
where
extractRedexApplies [(scopeId, _)] = scopeId
extractRedexApplies _ =
error "redex should only be applied once per parent scope"
onGetVars ::
MonadA m =>
(ExprIRef.ValIProperty m -> T m ()) -> V.Var ->
Val (ExprIRef.ValIProperty m) -> T m ()
onGetVars f = onMatchingSubexprs f . const . isGetVarOf
getVarsToHole :: MonadA m => V.Var -> Val (ExprIRef.ValIProperty m) -> T m ()
getVarsToHole = onGetVars toHole
isGetFieldParam :: V.Var -> T.Tag -> Val t -> Bool
isGetFieldParam param tag
(Val _ (V.BGetField (V.GetField (Val _ (V.BLeaf (V.LVar v))) t)))
= t == tag && v == param
isGetFieldParam _ _ _ = False
getFieldParamsToHole :: MonadA m => T.Tag -> StoredLam m -> T m ()
getFieldParamsToHole tag (StoredLam (V.Lam param lamBody) _) =
onMatchingSubexprs toHole (const (isGetFieldParam param tag)) lamBody
mkExtract ::
MonadA m =>
[V.Var] -> V.Var -> Transaction m () ->
Val (ExprIRef.ValIProperty m) -> Val (ExprIRef.ValIProperty m) ->
ConvertM m (Transaction m EntityId)
mkExtract binderScopeVars param delItem bodyStored argStored =
do
ctx <- ConvertM.readContext
do
mapM_ (`getVarsToHole` argStored) binderScopeVars
delItem
case ctx ^. ConvertM.scMBodyStored of
Nothing ->
do
getVarsToHole param bodyStored
getVarsToHole Builtins.recurseVar argStored
DataOps.newDefinitionWithPane
(ctx ^. ConvertM.scCodeAnchors) extractedI
<&> EntityId.ofIRef
Just scopeBodyP ->
DataOps.redexWrapWithGivenParam param extractedI scopeBodyP
& Lens.mapped .~ EntityId.ofLambdaParam param
& return
where
extractedI = argStored ^. V.payload & Property.value
mkWIActions ::
MonadA m =>
[V.Var] -> V.Var -> ExprIRef.ValIProperty m ->
Val (ExprIRef.ValIProperty m) -> Val (ExprIRef.ValIProperty m) ->
ConvertM m (LetItemActions m)
mkWIActions binderScopeVars param topLevelProp bodyStored argStored =
do
extr <- mkExtract binderScopeVars param del bodyStored argStored
return
LetItemActions
{ _liDelete = getVarsToHole param bodyStored >> del
, _liAddNext =
DataOps.redexWrap topLevelProp <&> EntityId.ofLambdaParam . fst
, _liExtract = extr
}
where
del = bodyStored ^. V.payload & replaceWith topLevelProp & void
convertLetItems ::
(MonadA m, Monoid a) =>
[V.Var] -> Val (Input.Payload m a) ->
ConvertM m
( [LetItem Guid m (ExpressionU m a)]
, Val (Input.Payload m a)
, Map ScopeId ScopeId
)
convertLetItems binderScopeVars expr =
case mExtractLet expr of
Nothing -> return ([], expr, Map.empty)
Just ewi ->
do
value <- convertBinder Nothing defGuid (ewiArg ewi)
actions <-
mkWIActions binderScopeVars param
<$> expr ^. V.payload . Input.mStored
<*> traverse (^. Input.mStored) (ewiBody ewi)
<*> traverse (^. Input.mStored) (ewiArg ewi)
& Lens.sequenceOf Lens._Just
(items, body, bodyScopesMap) <-
ewiBody ewi & convertLetItems (ewiParam ewi : binderScopeVars)
return
( LetItem
{ _liEntityId = defEntityId
, _liValue =
value
& bBody . rPayload . plData <>~
ewiHiddenPayloads ewi ^. Lens.traversed . Input.userData
, _liActions = actions
, _liName = UniqueId.toGuid param
, _liAnnotation = ewiAnnotation ewi
, _liScopes =
ewiBodyScopesMap ewi
& Map.keys & map (join (,)) & Map.fromList
}
:
( items
<&> liScopes %~ appendScopeMaps (ewiBodyScopesMap ewi)
)
, body
, appendScopeMaps (ewiBodyScopesMap ewi) bodyScopesMap
)
where
param = ewiParam ewi
defGuid = UniqueId.toGuid param
defEntityId = EntityId.ofLambdaParam param
appendScopeMaps x y = x <&> overrideId y
overrideId :: Ord a => Map a a -> a -> a
overrideId mapping k = Map.lookup k mapping & fromMaybe k
makeBinder :: (MonadA m, Monoid a) =>
Maybe (MkProperty m (Maybe ScopeId)) ->
Maybe (MkProperty m PresentationMode) ->
ConventionalParams m a -> Val (Input.Payload m a) ->
ConvertM m (Binder Guid m (ExpressionU m a))
makeBinder mChosenScopeProp mPresentationModeProp convParams funcBody =
do
(letItems, letBody, bodyScopesMap) <-
convertLetItems (cpMLamParam convParams ^.. Lens._Just) funcBody
bodyS <-
ConvertM.convertSubexpression letBody
& ConvertM.local
( ConvertM.scMBodyStored .~
letBody ^. V.payload . Input.mStored
)
let binderScopes s = (s, overrideId bodyScopesMap s)
return Binder
{ _bParams = convParams ^. cpParams
, _bMPresentationModeProp = mPresentationModeProp
, _bMChosenScopeProp = mChosenScopeProp
, _bBody = bodyS
, _bScopes = cpScopes convParams <&> map binderScopes
, _bLetItems = letItems
, _bMActions =
mkActions
<$> cpMAddFirstParam convParams
<*> letBody ^. V.payload . Input.mStored
}
& ConvertM.local addParams
where
addParams ctx =
ctx
& ConvertM.scTagParamInfos <>~ cpParamInfos convParams
& ConvertM.scNullParams <>~
case convParams ^. cpParams of
NullParam {} -> Set.fromList (cpMLamParam convParams ^.. Lens._Just)
_ -> Set.empty
mkActions addFirstParam letStored =
BinderActions
{ _baAddFirstParam = addFirstParam
, _baAddInnermostLetItem =
EntityId.ofLambdaParam . fst <$> DataOps.redexWrap letStored
}
convertLam ::
(MonadA m, Monoid a) =>
V.Lam (Val (Input.Payload m a)) ->
Input.Payload m a -> ConvertM m (ExpressionU m a)
convertLam lam@(V.Lam _ lamBody) exprPl =
do
mDeleteLam <- mkStoredLam lam exprPl & Lens._Just %%~ makeDeleteLambda Nothing
convParams <- convertLamParams Nothing lam exprPl
binder <-
makeBinder
(exprPl ^. Input.mStored <&> Anchors.assocScopeRef . Property.value)
Nothing convParams (lam ^. V.lamResult)
let setToInnerExprAction =
maybe NoInnerExpr SetToInnerExpr $
do
guard $ Lens.nullOf ExprLens.valHole lamBody
mDeleteLam
<&> Lens.mapped .~ binder ^. bBody . rPayload . plEntityId
BodyLam binder
& addActions exprPl
<&> rPayload . plActions . Lens._Just . setToInnerExpr .~ setToInnerExprAction
-- Let-item or definition (form of <name> [params] = <body>)
convertBinder ::
(MonadA m, Monoid a) =>
Maybe V.Var -> Guid ->
Val (Input.Payload m a) -> ConvertM m (Binder Guid m (ExpressionU m a))
convertBinder mRecursiveVar defGuid expr =
do
(convParams, funcBody) <- convertParams mRecursiveVar expr
let mPresentationModeProp
| Lens.has (cpParams . _FieldParams) convParams =
Just $ Anchors.assocPresentationMode defGuid
| otherwise = Nothing
makeBinder (Just (Anchors.assocScopeRef defGuid)) mPresentationModeProp
convParams funcBody
| rvion/lamdu | Lamdu/Sugar/Convert/Binder.hs | gpl-3.0 | 32,381 | 0 | 24 | 10,650 | 8,702 | 4,397 | 4,305 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
module Dep.Ui.Utils.Boxes (
Boxes(),hBoxes,vBoxes,setBoxesSpacing,
getBoxChildSizePolicy,setBoxChildSizePolicy,
withBoxesSpacing,switchOrientation,Orientation(..)
) where
import Control.Exception(throw)
import Control.Monad(liftM,filterM)
import Data.List(intersperse)
import Graphics.Vty.Attributes(Attr(..))
import Graphics.Vty.Prelude(DisplayRegion)
import Graphics.Vty.Image(Image,imageWidth,imageHeight,emptyImage,charFill,(<|>),(<->))
import Graphics.Vty.Input.Events(Key,Modifier)
import Graphics.Vty.Widgets.All(Widget,newWidget,WidgetImpl(..),RenderContext(..),getNormalAttr,getState)
import Graphics.Vty.Widgets.Core(handleKeyEvent,render,getCursorPosition,getCurrentSize,setCurrentPosition,growHorizontal,growVertical,relayFocusEvents,updateWidgetState,(<~~),FocusGroup(..),newFocusGroup,addToFocusGroup)
import Graphics.Vty.Widgets.Box(IndividualPolicy(..),BoxError(..))
import Graphics.Vty.Widgets.Util(plusWidth,plusHeight,withWidth,withHeight)
import Dep.Utils(setFst,setSnd,distribution100)
import Dep.Utils.MdUtils(orBoolM,orMaybeM)
import Dep.Ui.Utils(isFocused)
data Orientation = Horizontal | Vertical deriving (Eq,Enum,Bounded,Show)
data ChildsSizePolicy = PerChild [IndividualPolicy] | Percentage [Int] deriving (Show, Eq)
data Boxes a = Boxes { boxChildsSizePolicy :: ChildsSizePolicy, boxItems :: [Widget a], boxOrientation :: Orientation, boxSpacing :: Int, grows :: [IO Bool], imgCat :: Image -> Image -> Image, regDimension :: DisplayRegion -> Int, imgDimension :: Image -> Int, withDimension :: DisplayRegion -> Int -> DisplayRegion }
opposite :: Orientation -> Orientation
opposite Horizontal = Vertical
opposite Vertical = Horizontal
orDim :: Orientation -> Image -> Int
orDim Horizontal = imageWidth
orDim _ = imageHeight
orWith :: Orientation -> DisplayRegion -> Int -> DisplayRegion
orWith Horizontal = withWidth
orWith _ = withHeight
orDim2 :: Orientation -> Image -> Int
orDim2 Horizontal = imageHeight
orDim2 _ = imageWidth
orGet :: Orientation -> (a,a) -> a
orGet Horizontal = fst
orGet _ = snd
orSet2 :: Orientation -> a -> (a,a) -> (a,a)
orSet2 Horizontal = setSnd
orSet2 _ = setFst
orImgCat :: Orientation -> Image -> Image -> Image
orImgCat Horizontal = (<|>)
orImgCat _ = (<->)
orGrow :: Orientation -> Widget a -> IO Bool
orGrow Horizontal = growHorizontal
orGrow _ = growVertical
spacer :: Attr -> Int -> Orientation -> [Image] -> Image
spacer _ 0 _ _ = emptyImage
spacer a n o is = charFillTpl a ' ' dm
where s = maximum $ map (orDim2 o) is
dm = orSet2 o s (n,n)
charFillTpl :: Attr -> Char -> (Int,Int) -> Image
charFillTpl a c = uncurry (charFill a c)
instance Show (Boxes a) where
show b = concat ["Box { spacing = ", show $ boxSpacing b,
", childSizePolicy = ", show $ boxChildsSizePolicy b,
", orientation = ", show $ boxOrientation b,
" }"]
hBoxes :: Show a => [Widget a] -> IO (Widget (Boxes a),Widget FocusGroup)
hBoxes = boxes Horizontal 0
vBoxes :: Show a => [Widget a] -> IO (Widget (Boxes a),Widget FocusGroup)
vBoxes = boxes Vertical 0
defaultChildsSizePolicy :: Int -> ChildsSizePolicy
defaultChildsSizePolicy n = PerChild $ replicate n BoxAuto
boxes :: Show a => Orientation -> Int -> [Widget a] -> IO (Widget (Boxes a),Widget FocusGroup)
boxes o sp ws = do
let initSt = Boxes {
boxChildsSizePolicy = defaultChildsSizePolicy $ length ws,
boxOrientation = o,
boxSpacing = sp,
boxItems = ws,
grows = map (orGrow o) ws,
imgCat = orImgCat o,
regDimension = orGet o,
imgDimension = orDim o,
withDimension = orWith o
}
fg <- newFocusGroup
mapM_ (addToFocusGroup fg) ws
wRef <- newWidget initSt $ \w -> --WARNING: make sure no `o` is given in the function: orientation can change at runtime.
w {
growHorizontal_ = growPolicy growHorizontal Horizontal,
growVertical_ = growPolicy growVertical Vertical,
keyEventHandler = \this key mods -> getState this >>= orBoolM (\x -> handleKeyEvent x key mods) . boxItems,
render_ = \this s ctx -> getState this >>= renderBoxes s ctx,
getCursorPosition_ = gcp,
setCurrentPosition_ = \this dr -> getState this >>= flip setCurrentPos dr
}
mapM_ (relayFocusEvents wRef) ws
return (wRef,fg)
gcp :: Widget (Boxes a) -> IO (Maybe (Int,Int))
gcp wg = do
st <- getState wg
fcd <- filterM isFocused $ boxItems st
orMaybeM getCursorPosition fcd
switchOrientation :: Widget (Boxes a) -> IO ()
switchOrientation w = updateWidgetState w $ \b -> b { boxOrientation = opposite $ boxOrientation b }
setBoxesSpacing :: Widget (Boxes a) -> Int -> IO ()
setBoxesSpacing wRef spacing = updateWidgetState wRef $ \b -> b { boxSpacing = spacing }
withBoxesSpacing :: Int -> Widget (Boxes a) -> IO (Widget (Boxes a))
withBoxesSpacing spacing wRef = do
setBoxesSpacing wRef spacing
return wRef
getBoxChildSizePolicy :: Widget (Boxes a) -> IO ChildsSizePolicy
getBoxChildSizePolicy = (boxChildsSizePolicy <~~)
setBoxChildSizePolicy :: Widget (Boxes a) -> ChildsSizePolicy -> IO ()
setBoxChildSizePolicy b p@(Percentage l) | distribution100 l = sbcp b l p
setBoxChildSizePolicy b p@(PerChild l) = sbcp b l p
setBoxChildSizePolicy _ _ = throw BadPercentage
sbcp :: forall a b . Widget (Boxes b) -> [a] -> ChildsSizePolicy -> IO ()
sbcp w i p = do
s <- getState w
if length i == length (boxItems s) then updateWidgetState w $ \b -> b {boxChildsSizePolicy = p} else throw BadPercentage
setCurrentPos :: Boxes a -> DisplayRegion -> IO ()
setCurrentPos b | boxOrientation b == Horizontal = scp fst plusWidth (boxSpacing b) (boxItems b)
| otherwise = scp snd plusHeight (boxSpacing b) (boxItems b)
where scp :: (DisplayRegion -> Int) -> (DisplayRegion -> Int -> DisplayRegion) -> Int -> [Widget a] -> DisplayRegion -> IO ()
scp fa fb s = scpi
where scpi :: [Widget a] -> DisplayRegion -> IO ()
scpi (x:xs) pos = do
szi <- getCurrentSize x
setCurrentPosition x pos
scpi xs $ fb pos (fa szi + s)
scpi _ _ = return ()
growPolicy :: (Widget a -> IO Bool) -> Orientation -> Boxes a -> IO Bool
growPolicy g h b | h == boxOrientation b = liftM or boxbmap
| PerChild ips <- boxChildsSizePolicy b = liftM (or . zipWith (\x y -> y && x == BoxAuto) ips) boxbmap
| otherwise = return False --True??
where boxbmap = mapM g $ boxItems b
boxesKeyEventHandler :: Widget (Boxes a) -> Key -> [Modifier] -> IO Bool
boxesKeyEventHandler this key mods = do
b <- getState this
f $ boxItems b
where f (x:xs) = do
handled <- handleKeyEvent x key mods
if handled then return True else f xs
f _ = return False
renderBoxes :: Show a => DisplayRegion -> RenderContext -> Boxes a -> IO Image
renderBoxes s ctx this = do
is <- mapM (\x -> render x s ctx) $ boxItems this
return $ foldl1 (imgCat this) $ intersperse (spacer a (boxSpacing this) Horizontal is) is
where a = normalAttr ctx
rBoxes :: Show a => DisplayRegion -> RenderContext -> Boxes a -> IO Image
rBoxes d r b = rBoxes' (boxChildsSizePolicy b)
where rBoxes' :: ChildsSizePolicy -> IO Image
rBoxes' (Percentage ls) = throw BadPercentage
rBoxes' (PerChild ls) = throw BadPercentage
| KommuSoft/dep-software | Dep.Ui.Utils.Boxes.hs | gpl-3.0 | 7,654 | 0 | 18 | 1,791 | 2,703 | 1,411 | 1,292 | 148 | 3 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Memory.Output.Fancy
(
outputBeginShow,
outputShow,
outputShow',
outputBeginPlay,
outputPlay,
outputPlay',
outputFailure,
outputFailure',
) where
import MyPrelude
import Game
import Game.Grid
import Game.Grid.Output
import Game.Memory
import Game.Run.RunWorld
import Game.Memory.Output.Fancy.Sound
import Game.Memory.Output.Fancy.Screen
import Game.Memory.Output.Fancy.State
import OpenGL
import OpenGL.Helpers
--------------------------------------------------------------------------------
-- Show
outputBeginShow :: MemoryWorld -> RunWorld -> MEnv' (MemoryWorld, RunWorld)
outputBeginShow = \mem run -> do
gamedata <- resourceGameData
io $ do
(mem', run') <- stateSetBeginShow mem run
putStrLn "Memory.iterationBeginShow"
outputSoundBeginShow gamedata mem' run'
outputScreenBeginShow gamedata mem' run'
return (mem', run')
outputShow :: MemoryWorld -> RunWorld -> MEnv' (MemoryWorld, RunWorld)
outputShow = \mem run -> do
gamedata <- resourceGameData
io $ do
putStrLn "Memory.iterationShow"
outputSoundShow gamedata mem run
outputScreenShow gamedata mem run
return (mem, run)
outputShow' :: s -> MemoryWorld -> RunWorld -> MEnv' (s, MemoryWorld, RunWorld)
outputShow' = \s mem run -> do
gamedata <- resourceGameData
let scene = runScene run
proj2D = sceneProj2D scene
proj3D = sceneProj3D scene
modv3D = (cameraViewMat4 $ memoryCamera mem) `mappend`
(cameraModelMat4 $ memoryCamera mem)
io $ do
outputSoundShow' gamedata proj2D proj3D modv3D s mem run
outputScreenShow' gamedata proj2D proj3D modv3D s mem run
return (s, mem, run)
--------------------------------------------------------------------------------
-- Play
outputBeginPlay :: MemoryWorld -> RunWorld -> MEnv' (MemoryWorld, RunWorld)
outputBeginPlay = \mem run -> do
gamedata <- resourceGameData
io $ do
putStrLn "Memory.iterationBeginPlay"
outputSoundBeginPlay gamedata mem run
outputScreenBeginPlay gamedata mem run
return (mem, run)
outputPlay :: MemoryWorld -> RunWorld -> MEnv' (MemoryWorld, RunWorld)
outputPlay = \mem run -> do
gamedata <- resourceGameData
io $ do
putStrLn "Memory.iterationPlay"
outputSoundPlay gamedata mem run
outputScreenPlay gamedata mem run
return (mem, run)
outputPlay' :: s -> MemoryWorld -> RunWorld -> MEnv' (s, MemoryWorld, RunWorld)
outputPlay' = \s mem run -> do
gamedata <- resourceGameData
let scene = runScene run
proj2D = sceneProj2D scene
proj3D = sceneProj3D scene
modv3D = (cameraViewMat4 $ memoryCamera mem) `mappend`
(cameraModelMat4 $ memoryCamera mem)
io $ do
outputSoundPlay' gamedata proj2D proj3D modv3D s mem run
outputScreenPlay' gamedata proj2D proj3D modv3D s mem run
return (s, mem, run)
--------------------------------------------------------------------------------
-- Failure
outputFailure :: MemoryWorld -> RunWorld -> MEnv' (MemoryWorld, RunWorld)
outputFailure = \mem run -> do
gamedata <- resourceGameData
io $ do
putStrLn "Memory.iterationFailure"
outputSoundFailure gamedata mem run
outputScreenFailure gamedata mem run
return (mem, run)
outputFailure' :: s -> MemoryWorld -> RunWorld -> MEnv' (s, MemoryWorld, RunWorld)
outputFailure' = \s mem run -> do
gamedata <- resourceGameData
let scene = runScene run
proj2D = sceneProj2D scene
proj3D = sceneProj3D scene
modv3D = (cameraViewMat4 $ memoryCamera mem) `mappend`
(cameraModelMat4 $ memoryCamera mem)
io $ do
outputSoundFailure' gamedata proj2D proj3D modv3D s mem run
outputScreenFailure' gamedata proj2D proj3D modv3D s mem run
return (s, mem, run)
| karamellpelle/grid | source/Game/Memory/Output/Fancy.hs | gpl-3.0 | 4,665 | 0 | 14 | 1,032 | 1,068 | 555 | 513 | 98 | 1 |
module Test.RSCoin.Full.Arbitrary
(
) where
import Data.Time.Units (TimeUnit, convertUnit,
fromMicroseconds)
import Test.QuickCheck (Arbitrary (arbitrary), choose)
import System.Random (StdGen, mkStdGen)
import qualified Control.TimeWarp.Timed.MonadTimed as T
convertMicroSecond :: TimeUnit t => T.Microsecond -> t
convertMicroSecond = convertUnit
instance Arbitrary T.Microsecond where
-- no more than 10 minutes
arbitrary = fromMicroseconds <$> choose (0, 600 * 1000 * 1000)
instance Arbitrary T.Millisecond where
arbitrary = convertMicroSecond <$> arbitrary
instance Arbitrary T.Second where
arbitrary = convertMicroSecond <$> arbitrary
instance Arbitrary T.Minute where
arbitrary = convertMicroSecond <$> arbitrary
instance Arbitrary StdGen where
arbitrary = mkStdGen <$> arbitrary
| input-output-hk/rscoin-haskell | test/Test/RSCoin/Full/Arbitrary.hs | gpl-3.0 | 971 | 0 | 10 | 277 | 202 | 117 | 85 | 19 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.AdExchangeBuyer
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Accesses your bidding-account information, submits creatives for
-- validation, finds available direct deals, and retrieves performance
-- reports.
--
-- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference>
module Network.Google.AdExchangeBuyer
(
-- * Service Configuration
adExchangeBuyerService
-- * OAuth Scopes
, adExchangeBuyerScope
-- * API Declaration
, AdExchangeBuyerAPI
-- * Resources
-- ** adexchangebuyer.accounts.get
, module Network.Google.Resource.AdExchangeBuyer.Accounts.Get
-- ** adexchangebuyer.accounts.list
, module Network.Google.Resource.AdExchangeBuyer.Accounts.List
-- ** adexchangebuyer.accounts.patch
, module Network.Google.Resource.AdExchangeBuyer.Accounts.Patch
-- ** adexchangebuyer.accounts.update
, module Network.Google.Resource.AdExchangeBuyer.Accounts.Update
-- ** adexchangebuyer.billingInfo.get
, module Network.Google.Resource.AdExchangeBuyer.BillingInfo.Get
-- ** adexchangebuyer.billingInfo.list
, module Network.Google.Resource.AdExchangeBuyer.BillingInfo.List
-- ** adexchangebuyer.budget.get
, module Network.Google.Resource.AdExchangeBuyer.Budget.Get
-- ** adexchangebuyer.budget.patch
, module Network.Google.Resource.AdExchangeBuyer.Budget.Patch
-- ** adexchangebuyer.budget.update
, module Network.Google.Resource.AdExchangeBuyer.Budget.Update
-- ** adexchangebuyer.creatives.addDeal
, module Network.Google.Resource.AdExchangeBuyer.Creatives.AddDeal
-- ** adexchangebuyer.creatives.get
, module Network.Google.Resource.AdExchangeBuyer.Creatives.Get
-- ** adexchangebuyer.creatives.insert
, module Network.Google.Resource.AdExchangeBuyer.Creatives.Insert
-- ** adexchangebuyer.creatives.list
, module Network.Google.Resource.AdExchangeBuyer.Creatives.List
-- ** adexchangebuyer.creatives.listDeals
, module Network.Google.Resource.AdExchangeBuyer.Creatives.ListDeals
-- ** adexchangebuyer.creatives.removeDeal
, module Network.Google.Resource.AdExchangeBuyer.Creatives.RemoveDeal
-- ** adexchangebuyer.marketplacedeals.delete
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Delete
-- ** adexchangebuyer.marketplacedeals.insert
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Insert
-- ** adexchangebuyer.marketplacedeals.list
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.List
-- ** adexchangebuyer.marketplacedeals.update
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Update
-- ** adexchangebuyer.marketplacenotes.insert
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceNotes.Insert
-- ** adexchangebuyer.marketplacenotes.list
, module Network.Google.Resource.AdExchangeBuyer.MarketplaceNotes.List
-- ** adexchangebuyer.marketplaceprivateauction.updateproposal
, module Network.Google.Resource.AdExchangeBuyer.Marketplaceprivateauction.Updateproposal
-- ** adexchangebuyer.performanceReport.list
, module Network.Google.Resource.AdExchangeBuyer.PerformanceReport.List
-- ** adexchangebuyer.pretargetingConfig.delete
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Delete
-- ** adexchangebuyer.pretargetingConfig.get
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Get
-- ** adexchangebuyer.pretargetingConfig.insert
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Insert
-- ** adexchangebuyer.pretargetingConfig.list
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.List
-- ** adexchangebuyer.pretargetingConfig.patch
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Patch
-- ** adexchangebuyer.pretargetingConfig.update
, module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Update
-- ** adexchangebuyer.products.get
, module Network.Google.Resource.AdExchangeBuyer.Products.Get
-- ** adexchangebuyer.products.search
, module Network.Google.Resource.AdExchangeBuyer.Products.Search
-- ** adexchangebuyer.proposals.get
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Get
-- ** adexchangebuyer.proposals.insert
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Insert
-- ** adexchangebuyer.proposals.patch
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Patch
-- ** adexchangebuyer.proposals.search
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Search
-- ** adexchangebuyer.proposals.setupcomplete
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Setupcomplete
-- ** adexchangebuyer.proposals.update
, module Network.Google.Resource.AdExchangeBuyer.Proposals.Update
-- ** adexchangebuyer.pubprofiles.list
, module Network.Google.Resource.AdExchangeBuyer.PubproFiles.List
-- * Types
-- ** MarketplaceNote
, MarketplaceNote
, marketplaceNote
, mnNote
, mnKind
, mnTimestampMs
, mnProposalId
, mnDealId
, mnProposalRevisionNumber
, mnNoteId
, mnCreatorRole
-- ** CreativeNATiveAd
, CreativeNATiveAd
, creativeNATiveAd
, cnataImage
, cnataAppIcon
, cnataClickTrackingURL
, cnataClickLinkURL
, cnataBody
, cnataHeadline
, cnataImpressionTrackingURL
, cnataCallToAction
, cnataStore
, cnataVideoURL
, cnataPrice
, cnataAdvertiser
, cnataStarRating
, cnataLogo
-- ** EditAllOrderDealsResponse
, EditAllOrderDealsResponse
, editAllOrderDealsResponse
, eaodrDeals
, eaodrOrderRevisionNumber
-- ** CreativesList
, CreativesList
, creativesList
, clNextPageToken
, clKind
, clItems
-- ** CreativeDealIdsDealStatusesItem
, CreativeDealIdsDealStatusesItem
, creativeDealIdsDealStatusesItem
, cdidsiArcStatus
, cdidsiWebPropertyId
, cdidsiDealId
-- ** CreativeServingRestrictionsItemContextsItem
, CreativeServingRestrictionsItemContextsItem
, creativeServingRestrictionsItemContextsItem
, csriciPlatform
, csriciContextType
, csriciAuctionType
, csriciGeoCriteriaId
-- ** CreateOrdersResponse
, CreateOrdersResponse
, createOrdersResponse
, corProposals
-- ** AccountBidderLocationItem
, AccountBidderLocationItem
, accountBidderLocationItem
, abliURL
, abliMaximumQps
, abliRegion
, abliBidProtocol
-- ** PrivateData
, PrivateData
, privateData
, pdReferencePayload
, pdReferenceId
-- ** Budget
, Budget
, budget
, bCurrencyCode
, bKind
, bBudgetAmount
, bAccountId
, bId
, bBillingId
-- ** AddOrderNotesRequest
, AddOrderNotesRequest
, addOrderNotesRequest
, aonrNotes
-- ** DeliveryControlFrequencyCap
, DeliveryControlFrequencyCap
, deliveryControlFrequencyCap
, dcfcMaxImpressions
, dcfcNumTimeUnits
, dcfcTimeUnitType
-- ** MarketplaceDealParty
, MarketplaceDealParty
, marketplaceDealParty
, mdpSeller
, mdpBuyer
-- ** GetOrderNotesResponse
, GetOrderNotesResponse
, getOrderNotesResponse
, gonrNotes
-- ** GetOrdersResponse
, GetOrdersResponse
, getOrdersResponse
, gorProposals
-- ** CreativeServingRestrictionsItemDisApprovalReasonsItem
, CreativeServingRestrictionsItemDisApprovalReasonsItem
, creativeServingRestrictionsItemDisApprovalReasonsItem
, csridariReason
, csridariDetails
-- ** AccountsList
, AccountsList
, accountsList
, alKind
, alItems
-- ** Dimension
, Dimension
, dimension
, dDimensionValues
, dDimensionType
-- ** CreateOrdersRequest
, CreateOrdersRequest
, createOrdersRequest
, cProposals
, cWebPropertyCode
-- ** CreativeCorrectionsItem
, CreativeCorrectionsItem
, creativeCorrectionsItem
, cciContexts
, cciReason
, cciDetails
-- ** DealTermsRubiconNonGuaranteedTerms
, DealTermsRubiconNonGuaranteedTerms
, dealTermsRubiconNonGuaranteedTerms
, dtrngtPriorityPrice
, dtrngtStandardPrice
-- ** DealServingMetadata
, DealServingMetadata
, dealServingMetadata
, dsmDealPauseStatus
-- ** AddOrderDealsResponse
, AddOrderDealsResponse
, addOrderDealsResponse
, aodrDeals
, aodrProposalRevisionNumber
-- ** DeliveryControl
, DeliveryControl
, deliveryControl
, dcCreativeBlockingLevel
, dcFrequencyCaps
, dcDeliveryRateType
-- ** PricePerBuyer
, PricePerBuyer
, pricePerBuyer
, ppbPrice
, ppbAuctionTier
, ppbBuyer
-- ** Creative
, Creative
, creative
, cAttribute
, cNATiveAd
, cHeight
, cBuyerCreativeId
, cAdvertiserName
, cAdChoicesDestinationURL
, cAgencyId
, cCorrections
, cProductCategories
, cKind
, cHTMLSnippet
, cAdvertiserId
, cRestrictedCategories
, cDealsStatus
, cWidth
, cClickThroughURL
, cLanguages
, cVendorType
, cAccountId
, cImpressionTrackingURL
, cFilteringReasons
, cVersion
, cSensitiveCategories
, cVideoURL
, cAPIUploadTimestamp
, cServingRestrictions
, cDetectedDomains
, cOpenAuctionStatus
-- ** TargetingValueDayPartTargetingDayPart
, TargetingValueDayPartTargetingDayPart
, targetingValueDayPartTargetingDayPart
, tvdptdpEndHour
, tvdptdpStartHour
, tvdptdpStartMinute
, tvdptdpDayOfWeek
, tvdptdpEndMinute
-- ** DimensionDimensionValue
, DimensionDimensionValue
, dimensionDimensionValue
, ddvName
, ddvId
, ddvPercentage
-- ** PretargetingConfigList
, PretargetingConfigList
, pretargetingConfigList
, pclKind
, pclItems
-- ** DealTermsNonGuaranteedFixedPriceTerms
, DealTermsNonGuaranteedFixedPriceTerms
, dealTermsNonGuaranteedFixedPriceTerms
, dtngfptFixedPrices
-- ** PerformanceReport
, PerformanceReport
, performanceReport
, prFilteredBidRate
, prKind
, prLatency95thPercentile
, prCookieMatcherStatusRate
, prHostedMatchStatusRate
, prUnsuccessfulRequestRate
, prBidRequestRate
, prQuotaThrottledLimit
, prQuotaConfiguredLimit
, prSuccessfulRequestRate
, prLatency85thPercentile
, prCalloutStatusRate
, prLatency50thPercentile
, prBidRate
, prCreativeStatusRate
, prNoQuotaInRegion
, prRegion
, prInventoryMatchRate
, prPixelMatchResponses
, prTimestamp
, prPixelMatchRequests
, prOutOfQuota
-- ** PretargetingConfigExcludedPlacementsItem
, PretargetingConfigExcludedPlacementsItem
, pretargetingConfigExcludedPlacementsItem
, pcepiToken
, pcepiType
-- ** Seller
, Seller
, seller
, sAccountId
, sSubAccountId
-- ** Account
, Account
, account
, aMaximumTotalQps
, aKind
, aCookieMatchingURL
, aMaximumActiveCreatives
, aCookieMatchingNid
, aNumberActiveCreatives
, aId
, aBidderLocation
-- ** DeleteOrderDealsRequest
, DeleteOrderDealsRequest
, deleteOrderDealsRequest
, dodrUpdateAction
, dodrDealIds
, dodrProposalRevisionNumber
-- ** CreativesListOpenAuctionStatusFilter
, CreativesListOpenAuctionStatusFilter (..)
-- ** ContactInformation
, ContactInformation
, contactInformation
, ciEmail
, ciName
-- ** CreativeNATiveAdLogo
, CreativeNATiveAdLogo
, creativeNATiveAdLogo
, cnatalHeight
, cnatalURL
, cnatalWidth
-- ** GetOrderDealsResponse
, GetOrderDealsResponse
, getOrderDealsResponse
, godrDeals
-- ** PerformanceReportList
, PerformanceReportList
, performanceReportList
, prlKind
, prlPerformanceReport
-- ** PretargetingConfig
, PretargetingConfig
, pretargetingConfig
, pcPlatforms
, pcMobileCarriers
, pcVendorTypes
, pcExcludedGeoCriteriaIds
, pcSupportedCreativeAttributes
, pcUserLists
, pcKind
, pcExcludedPlacements
, pcUserIdentifierDataRequired
, pcMinimumViewabilityDecile
, pcMobileDevices
, pcLanguages
, pcVerticals
, pcVideoPlayerSizes
, pcConfigId
, pcPlacements
, pcExcludedUserLists
, pcConfigName
, pcGeoCriteriaIds
, pcDimensions
, pcExcludedVerticals
, pcCreativeType
, pcIsActive
, pcExcludedContentLabels
, pcBillingId
, pcMobileOperatingSystemVersions
-- ** CreativeFilteringReasons
, CreativeFilteringReasons
, creativeFilteringReasons
, cfrReasons
, cfrDate
-- ** TargetingValueCreativeSize
, TargetingValueCreativeSize
, targetingValueCreativeSize
, tvcsSize
, tvcsCompanionSizes
, tvcsSkippableAdType
, tvcsCreativeSizeType
-- ** DealTermsGuaranteedFixedPriceTermsBillingInfo
, DealTermsGuaranteedFixedPriceTermsBillingInfo
, dealTermsGuaranteedFixedPriceTermsBillingInfo
, dtgfptbiCurrencyConversionTimeMs
, dtgfptbiDfpLineItemId
, dtgfptbiPrice
, dtgfptbiOriginalContractedQuantity
-- ** GetPublisherProFilesByAccountIdResponse
, GetPublisherProFilesByAccountIdResponse
, getPublisherProFilesByAccountIdResponse
, gppfbairProFiles
-- ** Proposal
, Proposal
, proposal
, pBuyerPrivateData
, pIsSetupComplete
, pInventorySource
, pBuyerContacts
, pKind
, pOriginatorRole
, pDBmAdvertiserIds
, pRevisionNumber
, pBilledBuyer
, pPrivateAuctionId
, pIsRenegotiating
, pHasSellerSignedOff
, pSeller
, pProposalId
, pName
, pSellerContacts
, pLabels
, pRevisionTimeMs
, pProposalState
, pLastUpdaterOrCommentorRole
, pNegotiationId
, pHasBuyerSignedOff
, pBuyer
-- ** BillingInfoList
, BillingInfoList
, billingInfoList
, bilKind
, bilItems
-- ** AddOrderNotesResponse
, AddOrderNotesResponse
, addOrderNotesResponse
, aNotes
-- ** TargetingValueSize
, TargetingValueSize
, targetingValueSize
, tvsHeight
, tvsWidth
-- ** UpdatePrivateAuctionProposalRequest
, UpdatePrivateAuctionProposalRequest
, updatePrivateAuctionProposalRequest
, upaprExternalDealId
, upaprUpdateAction
, upaprNote
, upaprProposalRevisionNumber
-- ** PretargetingConfigDimensionsItem
, PretargetingConfigDimensionsItem
, pretargetingConfigDimensionsItem
, pcdiHeight
, pcdiWidth
-- ** CreativeCorrectionsItemContextsItem
, CreativeCorrectionsItemContextsItem
, creativeCorrectionsItemContextsItem
, cciciPlatform
, cciciContextType
, cciciAuctionType
, cciciGeoCriteriaId
-- ** PublisherProvidedForecast
, PublisherProvidedForecast
, publisherProvidedForecast
, ppfWeeklyImpressions
, ppfWeeklyUniques
, ppfDimensions
-- ** TargetingValue
, TargetingValue
, targetingValue
, tvCreativeSizeValue
, tvStringValue
, tvLongValue
, tvDayPartTargetingValue
-- ** CreativeNATiveAdAppIcon
, CreativeNATiveAdAppIcon
, creativeNATiveAdAppIcon
, cnataaiHeight
, cnataaiURL
, cnataaiWidth
-- ** Price
, Price
, price
, pCurrencyCode
, pAmountMicros
, pPricingType
, pExpectedCpmMicros
-- ** PretargetingConfigVideoPlayerSizesItem
, PretargetingConfigVideoPlayerSizesItem
, pretargetingConfigVideoPlayerSizesItem
, pcvpsiMinWidth
, pcvpsiAspectRatio
, pcvpsiMinHeight
-- ** EditAllOrderDealsRequest
, EditAllOrderDealsRequest
, editAllOrderDealsRequest
, eUpdateAction
, eDeals
, eProposalRevisionNumber
, eProposal
-- ** BillingInfo
, BillingInfo
, billingInfo
, biKind
, biAccountName
, biAccountId
, biBillingId
-- ** TargetingValueDayPartTargeting
, TargetingValueDayPartTargeting
, targetingValueDayPartTargeting
, tvdptTimeZoneType
, tvdptDayParts
-- ** SharedTargeting
, SharedTargeting
, sharedTargeting
, stKey
, stExclusions
, stInclusions
-- ** CreativeNATiveAdImage
, CreativeNATiveAdImage
, creativeNATiveAdImage
, cnataiHeight
, cnataiURL
, cnataiWidth
-- ** Product
, Product
, product
, proState
, proInventorySource
, proWebPropertyCode
, proCreationTimeMs
, proTerms
, proLastUpdateTimeMs
, proKind
, proRevisionNumber
, proPrivateAuctionId
, proDeliveryControl
, proHasCreatorSignedOff
, proFlightStartTimeMs
, proSharedTargetings
, proSeller
, proSyndicationProduct
, proFlightEndTimeMs
, proName
, proCreatorContacts
, proMarketplacePublisherProFileId
, proPublisherProvidedForecast
, proLabels
, proPublisherProFileId
, proLegacyOfferId
, proProductId
-- ** CreativeServingRestrictionsItem
, CreativeServingRestrictionsItem
, creativeServingRestrictionsItem
, csriContexts
, csriReason
, csriDisApprovalReasons
-- ** DeleteOrderDealsResponse
, DeleteOrderDealsResponse
, deleteOrderDealsResponse
, dDeals
, dProposalRevisionNumber
-- ** PretargetingConfigPlacementsItem
, PretargetingConfigPlacementsItem
, pretargetingConfigPlacementsItem
, pcpiToken
, pcpiType
-- ** PublisherProFileAPIProto
, PublisherProFileAPIProto
, publisherProFileAPIProto
, ppfapAudience
, ppfapState
, ppfapMediaKitLink
, ppfapDirectContact
, ppfapSamplePageLink
, ppfapLogoURL
, ppfapKind
, ppfapExchange
, ppfapOverview
, ppfapGooglePlusLink
, ppfapProFileId
, ppfapIsParent
, ppfapSeller
, ppfapAccountId
, ppfapName
, ppfapBuyerPitchStatement
, ppfapPublisherProvidedForecast
, ppfapIsPublished
, ppfapPublisherDomains
, ppfapPublisherProFileId
, ppfapRateCardInfoLink
, ppfapTopHeadlines
, ppfapProgrammaticContact
-- ** MarketplaceDeal
, MarketplaceDeal
, marketplaceDeal
, mdExternalDealId
, mdBuyerPrivateData
, mdWebPropertyCode
, mdCreationTimeMs
, mdTerms
, mdLastUpdateTimeMs
, mdKind
, mdDeliveryControl
, mdDealServingMetadata
, mdFlightStartTimeMs
, mdSharedTargetings
, mdIsRfpTemplate
, mdProposalId
, mdDealId
, mdInventoryDescription
, mdSyndicationProduct
, mdFlightEndTimeMs
, mdName
, mdSellerContacts
, mdProgrammaticCreativeSource
, mdCreativePreApprovalPolicy
, mdProductRevisionNumber
, mdProductId
, mdCreativeSafeFrameCompatibility
-- ** GetOffersResponse
, GetOffersResponse
, getOffersResponse
, gorProducts
-- ** DealTermsNonGuaranteedAuctionTerms
, DealTermsNonGuaranteedAuctionTerms
, dealTermsNonGuaranteedAuctionTerms
, dtngatReservePricePerBuyers
, dtngatAutoOptimizePrivateAuction
-- ** CreativeFilteringReasonsReasonsItem
, CreativeFilteringReasonsReasonsItem
, creativeFilteringReasonsReasonsItem
, cfrriFilteringStatus
, cfrriFilteringCount
-- ** ProposalsPatchUpdateAction
, ProposalsPatchUpdateAction (..)
-- ** CreativesListDealsStatusFilter
, CreativesListDealsStatusFilter (..)
-- ** DealTerms
, DealTerms
, dealTerms
, dtEstimatedGrossSpend
, dtNonGuaranteedFixedPriceTerms
, dtNonGuaranteedAuctionTerms
, dtRubiconNonGuaranteedTerms
, dtBrandingType
, dtCrossListedExternalDealIdType
, dtEstimatedImpressionsPerDay
, dtSellerTimeZone
, dtGuaranteedFixedPriceTerms
, dtDescription
-- ** CreativeDealIds
, CreativeDealIds
, creativeDealIds
, cdiKind
, cdiDealStatuses
-- ** MarketplaceLabel
, MarketplaceLabel
, marketplaceLabel
, mlDeprecatedMarketplaceDealParty
, mlAccountId
, mlCreateTimeMs
, mlLabel
-- ** Buyer
, Buyer
, buyer
, buyAccountId
-- ** ProposalsUpdateUpdateAction
, ProposalsUpdateUpdateAction (..)
-- ** AddOrderDealsRequest
, AddOrderDealsRequest
, addOrderDealsRequest
, aUpdateAction
, aDeals
, aProposalRevisionNumber
-- ** DealServingMetadataDealPauseStatus
, DealServingMetadataDealPauseStatus
, dealServingMetadataDealPauseStatus
, dsmdpsFirstPausedBy
, dsmdpsBuyerPauseReason
, dsmdpsHasBuyerPaused
, dsmdpsSellerPauseReason
, dsmdpsHasSellerPaused
-- ** DealTermsGuaranteedFixedPriceTerms
, DealTermsGuaranteedFixedPriceTerms
, dealTermsGuaranteedFixedPriceTerms
, dtgfptGuaranteedLooks
, dtgfptGuaranteedImpressions
, dtgfptBillingInfo
, dtgfptFixedPrices
, dtgfptMinimumDailyLooks
) where
import Network.Google.AdExchangeBuyer.Types
import Network.Google.Prelude
import Network.Google.Resource.AdExchangeBuyer.Accounts.Get
import Network.Google.Resource.AdExchangeBuyer.Accounts.List
import Network.Google.Resource.AdExchangeBuyer.Accounts.Patch
import Network.Google.Resource.AdExchangeBuyer.Accounts.Update
import Network.Google.Resource.AdExchangeBuyer.BillingInfo.Get
import Network.Google.Resource.AdExchangeBuyer.BillingInfo.List
import Network.Google.Resource.AdExchangeBuyer.Budget.Get
import Network.Google.Resource.AdExchangeBuyer.Budget.Patch
import Network.Google.Resource.AdExchangeBuyer.Budget.Update
import Network.Google.Resource.AdExchangeBuyer.Creatives.AddDeal
import Network.Google.Resource.AdExchangeBuyer.Creatives.Get
import Network.Google.Resource.AdExchangeBuyer.Creatives.Insert
import Network.Google.Resource.AdExchangeBuyer.Creatives.List
import Network.Google.Resource.AdExchangeBuyer.Creatives.ListDeals
import Network.Google.Resource.AdExchangeBuyer.Creatives.RemoveDeal
import Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Delete
import Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Insert
import Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.List
import Network.Google.Resource.AdExchangeBuyer.MarketplaceDeals.Update
import Network.Google.Resource.AdExchangeBuyer.MarketplaceNotes.Insert
import Network.Google.Resource.AdExchangeBuyer.MarketplaceNotes.List
import Network.Google.Resource.AdExchangeBuyer.Marketplaceprivateauction.Updateproposal
import Network.Google.Resource.AdExchangeBuyer.PerformanceReport.List
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Delete
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Get
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Insert
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.List
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Patch
import Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Update
import Network.Google.Resource.AdExchangeBuyer.Products.Get
import Network.Google.Resource.AdExchangeBuyer.Products.Search
import Network.Google.Resource.AdExchangeBuyer.Proposals.Get
import Network.Google.Resource.AdExchangeBuyer.Proposals.Insert
import Network.Google.Resource.AdExchangeBuyer.Proposals.Patch
import Network.Google.Resource.AdExchangeBuyer.Proposals.Search
import Network.Google.Resource.AdExchangeBuyer.Proposals.Setupcomplete
import Network.Google.Resource.AdExchangeBuyer.Proposals.Update
import Network.Google.Resource.AdExchangeBuyer.PubproFiles.List
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Ad Exchange Buyer API service.
type AdExchangeBuyerAPI =
MarketplaceNotesInsertResource :<|>
MarketplaceNotesListResource
:<|> ProposalsInsertResource
:<|> ProposalsPatchResource
:<|> ProposalsSetupcompleteResource
:<|> ProposalsGetResource
:<|> ProposalsSearchResource
:<|> ProposalsUpdateResource
:<|> AccountsListResource
:<|> AccountsPatchResource
:<|> AccountsGetResource
:<|> AccountsUpdateResource
:<|> BudgetPatchResource
:<|> BudgetGetResource
:<|> BudgetUpdateResource
:<|> CreativesInsertResource
:<|> CreativesRemoveDealResource
:<|> CreativesListResource
:<|> CreativesListDealsResource
:<|> CreativesGetResource
:<|> CreativesAddDealResource
:<|> PerformanceReportListResource
:<|> PretargetingConfigInsertResource
:<|> PretargetingConfigListResource
:<|> PretargetingConfigPatchResource
:<|> PretargetingConfigGetResource
:<|> PretargetingConfigDeleteResource
:<|> PretargetingConfigUpdateResource
:<|> PubproFilesListResource
:<|> BillingInfoListResource
:<|> BillingInfoGetResource
:<|> ProductsGetResource
:<|> ProductsSearchResource
:<|> MarketplaceDealsInsertResource
:<|> MarketplaceDealsListResource
:<|> MarketplaceDealsDeleteResource
:<|> MarketplaceDealsUpdateResource
:<|> MarketplaceprivateauctionUpdateproposalResource
| rueshyna/gogol | gogol-adexchange-buyer/gen/Network/Google/AdExchangeBuyer.hs | mpl-2.0 | 26,009 | 0 | 41 | 5,500 | 2,687 | 1,905 | 782 | 667 | 0 |
{-# LANGUAGE ViewPatterns #-}
import qualified Data.Sequence as S
enqueue d x (S.viewl -> S.EmptyL) = S.singleton (x, 1)
enqueue d x q@(S.viewl -> (top, n) S.:< ss) =
let need = top + d
in case compare need x of
LT -> enqueue d x ss
EQ -> ss S.|> (need, n + 1)
GT -> q S.|> (x, 1)
intervals d = go S.empty
where
go _ [] = []
go q (x:xs) = go' (enqueue d x q) xs
go' q@(S.viewr -> _ S.:> x) = (x :) . go q
triples = filter ((> 2) . snd)
countTriples d = length . triples . intervals d
readN n = fmap (take n . map read . words) getLine
main = do
[n, d] <- readN 2
xs <- readN n
print $ countTriples d xs
| itsbruce/hackerrank | alg/implementation/beautiful.hs | unlicense | 694 | 3 | 12 | 230 | 380 | 188 | 192 | 20 | 3 |
-- Sample Haskell code for a functional approach to the expression problem.
--
-- Eli Bendersky [http://eli.thegreenplace.net]
-- This code is in the public domain.
module Expressions where
data Expr = Constant Double
| BinaryPlus Expr Expr
stringify :: Expr -> String
stringify (Constant c) = show c
stringify (BinaryPlus lhs rhs) = stringify lhs
++ " + "
++ stringify rhs
evaluate :: Expr -> Double
evaluate (Constant c) = c
evaluate (BinaryPlus lhs rhs) = evaluate lhs + evaluate rhs
-- To try this, run:
-- $ ghci functional.hs
-- ...
-- *Expressions> let x = Constant 1.1
-- *Expressions> let y = Constant 2.2
-- *Expressions> let p1 = BinaryPlus x y
-- *Expressions> let p2 = BinaryPlus p1 y
-- *Expressions> stringify p2
-- "1.1 + 2.2 + 2.2"
-- *Expressions> evaluate p2
-- 5.5 | eliben/code-for-blog | 2016/expression-problem/haskell/functional.hs | unlicense | 864 | 0 | 7 | 218 | 140 | 78 | 62 | 11 | 1 |
import Data.List
parts :: [Integer] -> [[(Integer, Integer)]]
parts ps = foldl' f [] (reverse ps)
where
f [] price = [(price, price)] : []
f result@(cur@((price', maxprice) : _) : rest') price | price > maxprice = [(price, price)] : result
| otherwise = ((price, maxprice) : cur) : rest'
sol = sum . (map (sum . (map (uncurry $ flip (-)))))
explode = unfoldr f
where f str = let (chunk, rest) = span (/= ' ') str in if null chunk then Nothing else if null rest then Just (chunk, rest) else Just (chunk, tail rest)
tst = getLine >> getLine >>= (putStrLn . show . sol . parts . (map read) . explode)
main = getLine >>= (\t -> mapM_ (const tst) [1 .. (read t)])
| pbl64k/CodeSprints | CodeSprint-2012-02-25-Systems/StockTrading/st.accepted.hs | bsd-2-clause | 753 | 7 | 13 | 224 | 400 | 205 | 195 | 11 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Handler.TimesGallery where
import Import
import qualified Data.Map as M
import Andon.Types
import Andon.ClassData
import Andon.Gallery
getTimesGalleryR :: OrdInt -> Handler RepHtml
getTimesGalleryR times = defaultLayout $ do
setTitle $ toHtml $ "Gallery " ++ show times
$(widgetFile "times-gallery")
where
classes = filter ((== times) . getTimes) classData
| amutake/andon-yesod | Handler/TimesGallery.hs | bsd-2-clause | 416 | 0 | 10 | 69 | 108 | 59 | 49 | 12 | 1 |
{-# LANGUAGE FlexibleInstances #-}
import Test.Framework (defaultMain)
import Data.Object.Json
import Data.Object
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit hiding (Test)
import Test.QuickCheck (Arbitrary (..), oneof)
import Control.Applicative
import Numeric
import qualified Data.ByteString.Char8 as S8
input :: String
input = "{\"this\":[\"is\",\"a\",\"sample\"],\"numbers\":[5,6,7890,\"456\",1234567890]}"
output :: StringObject
output = Mapping
[ ("numbers", Sequence $ map Scalar
[ "5"
, "6"
, "7890"
, "456"
, "1234567890"
])
, ("this", Sequence $ map Scalar ["is", "a", "sample"])
]
caseInputOutput :: Assertion
caseInputOutput = do
so <- decode $ S8.pack input
output @=? so
propInputOutput :: StringObject -> Bool
propInputOutput so = decode (encode so) == Just so
main :: IO ()
main = defaultMain
[ testCase "caseInputOutput" caseInputOutput
, testProperty "propInputOutput" propInputOutput
, testProperty "propShowSignedInt" propShowSignedInt
]
instance Arbitrary (Object String String) where
arbitrary = oneof
[ Scalar <$> arbitrary
, do
i <- arbitrary
let s = showSignedInt (i * 1000000000 :: Integer)
return $ Scalar s
, do
a <- arbitrary
b <- arbitrary
return $ Sequence [a, b]
, do
k1 <- arbitrary
v1 <- arbitrary
return $ Mapping [(k1, v1)]
]
propShowSignedInt :: Integer -> Bool
propShowSignedInt i = read (showSignedInt i) == i
showSignedInt :: Integral a => a -> String
showSignedInt i
| i < 0 = '-' : showSignedInt (negate i)
| otherwise = showInt i ""
| snoyberg/data-object-json | runtests.hs | bsd-2-clause | 2,098 | 2 | 15 | 770 | 524 | 274 | 250 | 54 | 1 |
module Main (main) where
import Control.Monad (when)
import Bankotrav.Formatting
import Bankotrav.Random
import Bankotrav.Compression
main :: IO ()
main = do
putStrLn "Generating random board..."
board <- randomBoardIO
putStr $ formatBoard board
putStrLn "Compressing board..."
let idx = compressBoard board
putStrLn ("Board index: " ++ show idx ++ "; binary: " ++ formatBinary idx)
putStrLn "Decompressing board..."
let board' = decompressBoard idx
putStr $ formatBoard board'
when (board /= board') $ putStrLn "BOARDS NOT EQUAL!"
| Athas/banko | bankotrav/src/bankotrav.hs | bsd-2-clause | 556 | 0 | 12 | 98 | 165 | 77 | 88 | 17 | 1 |
module Hint.GHC (
module GHC,
module Outputable,
module ErrUtils, Message,
module Pretty,
module DriverPhases,
module StringBuffer,
module Lexer,
module Parser,
module DynFlags,
module FastString,
#if __GLASGOW_HASKELL__ >= 610
module Control.Monad.Ghc,
module HscTypes,
module Bag,
#endif
#if __GLASGOW_HASKELL__ >= 608
module PprTyThing,
#elif __GLASGOW_HASKELL__ < 608
module SrcLoc,
#endif
#if __GLASGOW_HASKELL__ >= 702
module SrcLoc,
#endif
#if __GLASGOW_HASKELL__ >= 708
module ConLike,
#endif
)
where
#if __GLASGOW_HASKELL__ >= 610
import GHC hiding ( Phase, GhcT, runGhcT )
import Control.Monad.Ghc ( GhcT, runGhcT )
import HscTypes ( SourceError, srcErrorMessages, GhcApiError )
import Bag ( bagToList )
#else
import GHC hiding ( Phase )
#endif
import Outputable ( PprStyle, SDoc, Outputable(ppr),
showSDoc, showSDocForUser, showSDocUnqual,
withPprStyle, defaultErrStyle )
import ErrUtils ( mkLocMessage )
#if __GLASGOW_HASKELL__ < 706
import ErrUtils ( Message )
#else
import ErrUtils ( MsgDoc ) -- we alias it as Message below
#endif
import Pretty ( Doc )
import DriverPhases ( Phase(Cpp), HscSource(HsSrcFile) )
import StringBuffer ( stringToStringBuffer )
import Lexer ( P(..), ParseResult(..), mkPState )
import Parser ( parseStmt, parseType )
import FastString ( fsLit )
#if __GLASGOW_HASKELL__ >= 700
import DynFlags ( supportedLanguagesAndExtensions, xFlags, xopt )
#else
import DynFlags ( supportedLanguages )
#endif
#if __GLASGOW_HASKELL__ >=704
import DynFlags ( LogAction )
#endif
#if __GLASGOW_HASKELL__ >= 608
import PprTyThing ( pprTypeForUser )
#elif __GLASGOW_HASKELL__ < 608
import SrcLoc ( SrcSpan )
#endif
#if __GLASGOW_HASKELL__ >= 702
import SrcLoc ( mkRealSrcLoc )
#endif
#if __GLASGOW_HASKELL__ >= 708
import ConLike ( ConLike(RealDataCon) )
#endif
#if __GLASGOW_HASKELL__ >= 706
type Message = MsgDoc
#endif
| flowbox-public/hint | src/Hint/GHC.hs | bsd-3-clause | 2,033 | 0 | 6 | 441 | 340 | 238 | 102 | 26 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Numeral.FA.Rules
( rules ) where
import Control.Monad (join)
import Data.HashMap.Strict (HashMap)
import Data.Maybe
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
zeroNineteenMap :: HashMap Text Integer
zeroNineteenMap = HashMap.fromList
[ ("صفر", 0)
, ("یک", 1)
, ("دو", 2)
, ("سه", 3)
, ("چهار", 4)
, ("پنج", 5)
, ("شش", 6)
, ("شیش", 6)
, ("هفت", 7)
, ("هشت", 8)
, ("نه", 9)
, ("ده", 10)
, ("یازده", 11)
, ("دوازده", 12)
, ("سیزده", 13)
, ("چهارده", 14)
, ("پانزده", 15)
, ("پونزده", 15)
, ("شانزده", 16)
, ("شونزده", 16)
, ("هفده", 17)
, ("هیفده", 17)
, ("هجده", 18)
, ("هیجده", 18)
, ("نوزده", 19)
]
ruleToNineteen :: Rule
ruleToNineteen = Rule
{ name = "integer (0..19)"
, pattern =
[ regex "(صفر|یک|سه|چهارده|چهار|پنج|شی?ش|هفت|هشت|نه|یازده|دوازده|سیزده|پ(ا|و)نزده|ش(ا|و)نزده|هی?فده|هی?جده|نوزده|ده|دو)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
let x = Text.toLower match in
(HashMap.lookup x zeroNineteenMap >>= integer)
_ -> Nothing
}
tensMap :: HashMap Text Integer
tensMap = HashMap.fromList
[ ( "بیست" , 20 )
, ( "سی" , 30 )
, ( "چهل" , 40 )
, ( "پنجاه" , 50 )
, ( "شصت" , 60 )
, ( "هفتاد" , 70 )
, ( "هشتاد" , 80 )
, ( "نود" , 90 )
, ( "صد" , 100 )
, ( "دویست" , 200 )
, ( "سیصد" , 300 )
, ( "سی صد" , 300 )
, ( "چهارصد" , 400 )
, ( "چهار صد" , 400 )
, ( "پانصد" , 500 )
, ( "پونصد" , 500 )
, ( "شیشصد" , 600 )
, ( "شیش صد" , 600 )
, ( "ششصد" , 600 )
, ( "شش صد" , 600 )
, ( "هفتصد" , 700 )
, ( "هفت صد" , 700 )
, ( "هشتصد" , 800 )
, ( "هشت صد" , 800 )
, ( "نهصد" , 900 )
, ( "نه صد" , 900 )
]
ruleTens :: Rule
ruleTens = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(دویست|(سی|چهار|پان|پون|شی?ش|هفت|هشت|نه)? ?صد|بیست|سی|چهل|پنجاه|شصت|هفتاد|هشتاد|نود)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) tensMap >>= integer
_ -> Nothing
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(هزار|میلیون|ملیون|میلیارد)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"هزار" -> double 1e3 >>= withGrain 2 >>= withMultipliable
"میلیون" -> double 1e6 >>= withGrain 3 >>= withMultipliable
"ملیون" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"میلیارد" -> double 1e9 >>= withGrain 9 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
ruleCompositeTens :: Rule
ruleCompositeTens = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [20,30..90]
, regex "و"
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
_:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleCompositeHundred :: Rule
ruleCompositeHundred = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [100,200..900]
, regex "و"
, numberBetween 1 100
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = tens}:
_:
Token Numeral NumeralData{TNumeral.value = units}:
_) -> double $ tens + units
_ -> Nothing
}
ruleSum :: Rule
ruleSum = Rule
{ name = "intersect 2 numbers"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleSumAnd :: Rule
ruleSumAnd = Rule
{ name = "intersect 2 numbers (with and)"
, pattern =
[ Predicate $ and . sequence [hasGrain, isPositive]
, regex "و"
, Predicate $ and . sequence [not . isMultipliable, isPositive]
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = val1, TNumeral.grain = Just g}:
_:
Token Numeral NumeralData{TNumeral.value = val2}:
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, Predicate isMultipliable
]
, prod = \tokens -> case tokens of
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
numeralToStringMap :: HashMap Char String
numeralToStringMap =
HashMap.fromList
[ ('۰', "0")
, ('۱', "1")
, ('۲', "2")
, ('۳', "3")
, ('۴', "4")
, ('۵', "5")
, ('۶', "6")
, ('۷', "7")
, ('۸', "8")
, ('۹', "9")
]
parseIntAsText :: Text -> Text
parseIntAsText =
Text.pack
. join
. mapMaybe (`HashMap.lookup` numeralToStringMap)
. Text.unpack
parseIntegerFromText :: Text -> Maybe Integer
parseIntegerFromText = parseInteger . parseIntAsText
ruleIntegerNumeric :: Rule
ruleIntegerNumeric = Rule
{ name = "Persian integer numeric"
, pattern =
[ regex "([۰-۹]{1,18})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseIntegerFromText match >>= integer
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleIntegerNumeric
, ruleToNineteen
, ruleTens
, rulePowersOfTen
, ruleCompositeTens
, ruleCompositeHundred
, ruleSum
, ruleSumAnd
, ruleMultiply
]
| facebookincubator/duckling | Duckling/Numeral/FA/Rules.hs | bsd-3-clause | 6,842 | 0 | 18 | 1,649 | 2,031 | 1,184 | 847 | 206 | 6 |
{-
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2001-2003
--
-- Access to system tools: gcc, cp, rm etc
--
-----------------------------------------------------------------------------
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module SysTools (
-- Initialisation
initSysTools,
-- Interface to system tools
runUnlit, runCpp, runCc, -- [Option] -> IO ()
runPp, -- [Option] -> IO ()
runSplit, -- [Option] -> IO ()
runAs, runLink, runLibtool, -- [Option] -> IO ()
runMkDLL,
runWindres,
runLlvmOpt,
runLlvmLlc,
runClang,
figureLlvmVersion,
readElfSection,
getLinkerInfo,
getCompilerInfo,
linkDynLib,
askCc,
touch, -- String -> String -> IO ()
copy,
copyWithHeader,
-- Temporary-file management
setTmpDir,
newTempName,
cleanTempDirs, cleanTempFiles, cleanTempFilesExcept,
addFilesToClean,
Option(..)
) where
#include "HsVersions.h"
import DriverPhases
import Module
import Packages
import Config
import Outputable
import ErrUtils
import Panic
import Platform
import Util
import DynFlags
import Exception
import Data.IORef
import Control.Monad
import System.Exit
import System.Environment
import System.FilePath
import System.IO
import System.IO.Error as IO
import System.Directory
import Data.Char
import Data.List
import qualified Data.Map as Map
import Text.ParserCombinators.ReadP hiding (char)
import qualified Text.ParserCombinators.ReadP as R
#ifndef mingw32_HOST_OS
import qualified System.Posix.Internals
#else /* Must be Win32 */
import Foreign
import Foreign.C.String
#endif
import System.Process
import Control.Concurrent
import FastString
import SrcLoc ( SrcLoc, mkSrcLoc, noSrcSpan, mkSrcSpan )
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
{-
How GHC finds its files
~~~~~~~~~~~~~~~~~~~~~~~
[Note topdir]
GHC needs various support files (library packages, RTS etc), plus
various auxiliary programs (cp, gcc, etc). It starts by finding topdir,
the root of GHC's support files
On Unix:
- ghc always has a shell wrapper that passes a -B<dir> option
On Windows:
- ghc never has a shell wrapper.
- we can find the location of the ghc binary, which is
$topdir/bin/<something>.exe
where <something> may be "ghc", "ghc-stage2", or similar
- we strip off the "bin/<something>.exe" to leave $topdir.
from topdir we can find package.conf, ghc-asm, etc.
SysTools.initSysProgs figures out exactly where all the auxiliary programs
are, and initialises mutable variables to make it easy to call them.
To to this, it makes use of definitions in Config.hs, which is a Haskell
file containing variables whose value is figured out by the build system.
Config.hs contains two sorts of things
cGCC, The *names* of the programs
cCPP e.g. cGCC = gcc
cUNLIT cCPP = gcc -E
etc They do *not* include paths
cUNLIT_DIR The *path* to the directory containing unlit, split etc
cSPLIT_DIR *relative* to the root of the build tree,
for use when running *in-place* in a build tree (only)
---------------------------------------------
NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
Another hair-brained scheme for simplifying the current tool location
nightmare in GHC: Simon originally suggested using another
configuration file along the lines of GCC's specs file - which is fine
except that it means adding code to read yet another configuration
file. What I didn't notice is that the current package.conf is
general enough to do this:
Package
{name = "tools", import_dirs = [], source_dirs = [],
library_dirs = [], hs_libraries = [], extra_libraries = [],
include_dirs = [], c_includes = [], package_deps = [],
extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${topdir}/bin/unlit", ... etc.],
extra_cc_opts = [], extra_ld_opts = []}
Which would have the advantage that we get to collect together in one
place the path-specific package stuff with the path-specific tool
stuff.
End of NOTES
---------------------------------------------
************************************************************************
* *
\subsection{Initialisation}
* *
************************************************************************
-}
initSysTools :: Maybe String -- Maybe TopDir path (without the '-B' prefix)
-> IO Settings -- Set all the mutable variables above, holding
-- (a) the system programs
-- (b) the package-config file
-- (c) the GHC usage message
initSysTools mbMinusB
= do top_dir <- findTopDir mbMinusB
-- see [Note topdir]
-- NB: top_dir is assumed to be in standard Unix
-- format, '/' separated
let settingsFile = top_dir </> "settings"
platformConstantsFile = top_dir </> "platformConstants"
installed :: FilePath -> FilePath
installed file = top_dir </> file
settingsStr <- readFile settingsFile
platformConstantsStr <- readFile platformConstantsFile
mySettings <- case maybeReadFuzzy settingsStr of
Just s ->
return s
Nothing ->
pgmError ("Can't parse " ++ show settingsFile)
platformConstants <- case maybeReadFuzzy platformConstantsStr of
Just s ->
return s
Nothing ->
pgmError ("Can't parse " ++
show platformConstantsFile)
let getSetting key = case lookup key mySettings of
Just xs ->
return $ case stripPrefix "$topdir" xs of
Just [] ->
top_dir
Just xs'@(c:_)
| isPathSeparator c ->
top_dir ++ xs'
_ ->
xs
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
getBooleanSetting key = case lookup key mySettings of
Just "YES" -> return True
Just "NO" -> return False
Just xs -> pgmError ("Bad value for " ++ show key ++ ": " ++ show xs)
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
readSetting key = case lookup key mySettings of
Just xs ->
case maybeRead xs of
Just v -> return v
Nothing -> pgmError ("Failed to read " ++ show key ++ " value " ++ show xs)
Nothing -> pgmError ("No entry for " ++ show key ++ " in " ++ show settingsFile)
targetArch <- readSetting "target arch"
targetOS <- readSetting "target os"
targetWordSize <- readSetting "target word size"
targetUnregisterised <- getBooleanSetting "Unregisterised"
targetHasGnuNonexecStack <- readSetting "target has GNU nonexec stack"
targetHasIdentDirective <- readSetting "target has .ident directive"
targetHasSubsectionsViaSymbols <- readSetting "target has subsections via symbols"
myExtraGccViaCFlags <- getSetting "GCC extra via C opts"
-- On Windows, mingw is distributed with GHC,
-- so we look in TopDir/../mingw/bin
-- It would perhaps be nice to be able to override this
-- with the settings file, but it would be a little fiddly
-- to make that possible, so for now you can't.
gcc_prog <- getSetting "C compiler command"
gcc_args_str <- getSetting "C compiler flags"
cpp_prog <- getSetting "Haskell CPP command"
cpp_args_str <- getSetting "Haskell CPP flags"
let unreg_gcc_args = if targetUnregisterised
then ["-DNO_REGS", "-DUSE_MINIINTERPRETER"]
else []
-- TABLES_NEXT_TO_CODE affects the info table layout.
tntc_gcc_args
| mkTablesNextToCode targetUnregisterised
= ["-DTABLES_NEXT_TO_CODE"]
| otherwise = []
cpp_args= map Option (words cpp_args_str)
gcc_args = map Option (words gcc_args_str
++ unreg_gcc_args
++ tntc_gcc_args)
ldSupportsCompactUnwind <- getBooleanSetting "ld supports compact unwind"
ldSupportsBuildId <- getBooleanSetting "ld supports build-id"
ldSupportsFilelist <- getBooleanSetting "ld supports filelist"
ldIsGnuLd <- getBooleanSetting "ld is GNU ld"
perl_path <- getSetting "perl command"
let pkgconfig_path = installed "package.conf.d"
ghc_usage_msg_path = installed "ghc-usage.txt"
ghci_usage_msg_path = installed "ghci-usage.txt"
-- For all systems, unlit, split, mangle are GHC utilities
-- architecture-specific stuff is done when building Config.hs
unlit_path = installed cGHC_UNLIT_PGM
-- split is a Perl script
split_script = installed cGHC_SPLIT_PGM
windres_path <- getSetting "windres command"
libtool_path <- getSetting "libtool command"
tmpdir <- getTemporaryDirectory
touch_path <- getSetting "touch command"
let -- On Win32 we don't want to rely on #!/bin/perl, so we prepend
-- a call to Perl to get the invocation of split.
-- On Unix, scripts are invoked using the '#!' method. Binary
-- installations of GHC on Unix place the correct line on the
-- front of the script at installation time, so we don't want
-- to wire-in our knowledge of $(PERL) on the host system here.
(split_prog, split_args)
| isWindowsHost = (perl_path, [Option split_script])
| otherwise = (split_script, [])
mkdll_prog <- getSetting "dllwrap command"
let mkdll_args = []
-- cpp is derived from gcc on all platforms
-- HACK, see setPgmP below. We keep 'words' here to remember to fix
-- Config.hs one day.
-- Other things being equal, as and ld are simply gcc
gcc_link_args_str <- getSetting "C compiler link flags"
let as_prog = gcc_prog
as_args = gcc_args
ld_prog = gcc_prog
ld_args = gcc_args ++ map Option (words gcc_link_args_str)
-- We just assume on command line
lc_prog <- getSetting "LLVM llc command"
lo_prog <- getSetting "LLVM opt command"
let platform = Platform {
platformArch = targetArch,
platformOS = targetOS,
platformWordSize = targetWordSize,
platformUnregisterised = targetUnregisterised,
platformHasGnuNonexecStack = targetHasGnuNonexecStack,
platformHasIdentDirective = targetHasIdentDirective,
platformHasSubsectionsViaSymbols = targetHasSubsectionsViaSymbols
}
return $ Settings {
sTargetPlatform = platform,
sTmpDir = normalise tmpdir,
sGhcUsagePath = ghc_usage_msg_path,
sGhciUsagePath = ghci_usage_msg_path,
sTopDir = top_dir,
sRawSettings = mySettings,
sExtraGccViaCFlags = words myExtraGccViaCFlags,
sSystemPackageConfig = pkgconfig_path,
sLdSupportsCompactUnwind = ldSupportsCompactUnwind,
sLdSupportsBuildId = ldSupportsBuildId,
sLdSupportsFilelist = ldSupportsFilelist,
sLdIsGnuLd = ldIsGnuLd,
sPgm_L = unlit_path,
sPgm_P = (cpp_prog, cpp_args),
sPgm_F = "",
sPgm_c = (gcc_prog, gcc_args),
sPgm_s = (split_prog,split_args),
sPgm_a = (as_prog, as_args),
sPgm_l = (ld_prog, ld_args),
sPgm_dll = (mkdll_prog,mkdll_args),
sPgm_T = touch_path,
sPgm_sysman = top_dir ++ "/ghc/rts/parallel/SysMan",
sPgm_windres = windres_path,
sPgm_libtool = libtool_path,
sPgm_lo = (lo_prog,[]),
sPgm_lc = (lc_prog,[]),
-- Hans: this isn't right in general, but you can
-- elaborate it in the same way as the others
sOpt_L = [],
sOpt_P = [],
sOpt_F = [],
sOpt_c = [],
sOpt_a = [],
sOpt_l = [],
sOpt_windres = [],
sOpt_lo = [],
sOpt_lc = [],
sPlatformConstants = platformConstants
}
-- returns a Unix-format path (relying on getBaseDir to do so too)
findTopDir :: Maybe String -- Maybe TopDir path (without the '-B' prefix).
-> IO String -- TopDir (in Unix format '/' separated)
findTopDir (Just minusb) = return (normalise minusb)
findTopDir Nothing
= do -- Get directory of executable
maybe_exec_dir <- getBaseDir
case maybe_exec_dir of
-- "Just" on Windows, "Nothing" on unix
Nothing -> throwGhcExceptionIO (InstallationError "missing -B<dir> option")
Just dir -> return dir
{-
************************************************************************
* *
\subsection{Running an external program}
* *
************************************************************************
-}
runUnlit :: DynFlags -> [Option] -> IO ()
runUnlit dflags args = do
let prog = pgm_L dflags
opts = getOpts dflags opt_L
runSomething dflags "Literate pre-processor" prog
(map Option opts ++ args)
runCpp :: DynFlags -> [Option] -> IO ()
runCpp dflags args = do
let (p,args0) = pgm_P dflags
args1 = map Option (getOpts dflags opt_P)
args2 = if gopt Opt_WarnIsError dflags
then [Option "-Werror"]
else []
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "C pre-processor" p
(args0 ++ args1 ++ args2 ++ args) mb_env
runPp :: DynFlags -> [Option] -> IO ()
runPp dflags args = do
let prog = pgm_F dflags
opts = map Option (getOpts dflags opt_F)
runSomething dflags "Haskell pre-processor" prog (args ++ opts)
runCc :: DynFlags -> [Option] -> IO ()
runCc dflags args = do
let (p,args0) = pgm_c dflags
args1 = map Option (getOpts dflags opt_c)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingFiltered dflags cc_filter "C Compiler" p args2 mb_env
where
-- discard some harmless warnings from gcc that we can't turn off
cc_filter = unlines . doFilter . lines
{-
gcc gives warnings in chunks like so:
In file included from /foo/bar/baz.h:11,
from /foo/bar/baz2.h:22,
from wibble.c:33:
/foo/flibble:14: global register variable ...
/foo/flibble:15: warning: call-clobbered r...
We break it up into its chunks, remove any call-clobbered register
warnings from each chunk, and then delete any chunks that we have
emptied of warnings.
-}
doFilter = unChunkWarnings . filterWarnings . chunkWarnings []
-- We can't assume that the output will start with an "In file inc..."
-- line, so we start off expecting a list of warnings rather than a
-- location stack.
chunkWarnings :: [String] -- The location stack to use for the next
-- list of warnings
-> [String] -- The remaining lines to look at
-> [([String], [String])]
chunkWarnings loc_stack [] = [(loc_stack, [])]
chunkWarnings loc_stack xs
= case break loc_stack_start xs of
(warnings, lss:xs') ->
case span loc_start_continuation xs' of
(lsc, xs'') ->
(loc_stack, warnings) : chunkWarnings (lss : lsc) xs''
_ -> [(loc_stack, xs)]
filterWarnings :: [([String], [String])] -> [([String], [String])]
filterWarnings [] = []
-- If the warnings are already empty then we are probably doing
-- something wrong, so don't delete anything
filterWarnings ((xs, []) : zs) = (xs, []) : filterWarnings zs
filterWarnings ((xs, ys) : zs) = case filter wantedWarning ys of
[] -> filterWarnings zs
ys' -> (xs, ys') : filterWarnings zs
unChunkWarnings :: [([String], [String])] -> [String]
unChunkWarnings [] = []
unChunkWarnings ((xs, ys) : zs) = xs ++ ys ++ unChunkWarnings zs
loc_stack_start s = "In file included from " `isPrefixOf` s
loc_start_continuation s = " from " `isPrefixOf` s
wantedWarning w
| "warning: call-clobbered register used" `isContainedIn` w = False
| otherwise = True
isContainedIn :: String -> String -> Bool
xs `isContainedIn` ys = any (xs `isPrefixOf`) (tails ys)
askCc :: DynFlags -> [Option] -> IO String
askCc dflags args = do
let (p,args0) = pgm_c dflags
args1 = map Option (getOpts dflags opt_c)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingWith dflags "gcc" p args2 $ \real_args ->
readCreateProcess (proc p real_args){ env = mb_env }
-- Version of System.Process.readProcessWithExitCode that takes an environment
readCreateProcess
:: CreateProcess
-> IO (ExitCode, String) -- ^ stdout
readCreateProcess proc = do
(_, Just outh, _, pid) <-
createProcess proc{ std_out = CreatePipe }
-- fork off a thread to start consuming the output
output <- hGetContents outh
outMVar <- newEmptyMVar
_ <- forkIO $ evaluate (length output) >> putMVar outMVar ()
-- wait on the output
takeMVar outMVar
hClose outh
-- wait on the process
ex <- waitForProcess pid
return (ex, output)
readProcessEnvWithExitCode
:: String -- ^ program path
-> [String] -- ^ program args
-> [(String, String)] -- ^ environment to override
-> IO (ExitCode, String, String) -- ^ (exit_code, stdout, stderr)
readProcessEnvWithExitCode prog args env_update = do
current_env <- getEnvironment
let new_env = env_update ++ [ (k, v)
| let overriden_keys = map fst env_update
, (k, v) <- current_env
, k `notElem` overriden_keys
]
p = proc prog args
(_stdin, Just stdoh, Just stdeh, pid) <-
createProcess p{ std_out = CreatePipe
, std_err = CreatePipe
, env = Just new_env
}
outMVar <- newEmptyMVar
errMVar <- newEmptyMVar
_ <- forkIO $ do
stdo <- hGetContents stdoh
_ <- evaluate (length stdo)
putMVar outMVar stdo
_ <- forkIO $ do
stde <- hGetContents stdeh
_ <- evaluate (length stde)
putMVar errMVar stde
out <- takeMVar outMVar
hClose stdoh
err <- takeMVar errMVar
hClose stdeh
ex <- waitForProcess pid
return (ex, out, err)
-- Don't let gcc localize version info string, #8825
en_locale_env :: [(String, String)]
en_locale_env = [("LANGUAGE", "en")]
-- If the -B<dir> option is set, add <dir> to PATH. This works around
-- a bug in gcc on Windows Vista where it can't find its auxiliary
-- binaries (see bug #1110).
getGccEnv :: [Option] -> IO (Maybe [(String,String)])
getGccEnv opts =
if null b_dirs
then return Nothing
else do env <- getEnvironment
return (Just (map mangle_path env))
where
(b_dirs, _) = partitionWith get_b_opt opts
get_b_opt (Option ('-':'B':dir)) = Left dir
get_b_opt other = Right other
mangle_path (path,paths) | map toUpper path == "PATH"
= (path, '\"' : head b_dirs ++ "\";" ++ paths)
mangle_path other = other
runSplit :: DynFlags -> [Option] -> IO ()
runSplit dflags args = do
let (p,args0) = pgm_s dflags
runSomething dflags "Splitter" p (args0++args)
runAs :: DynFlags -> [Option] -> IO ()
runAs dflags args = do
let (p,args0) = pgm_a dflags
args1 = map Option (getOpts dflags opt_a)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "Assembler" p args2 mb_env
-- | Run the LLVM Optimiser
runLlvmOpt :: DynFlags -> [Option] -> IO ()
runLlvmOpt dflags args = do
let (p,args0) = pgm_lo dflags
args1 = map Option (getOpts dflags opt_lo)
runSomething dflags "LLVM Optimiser" p (args0 ++ args1 ++ args)
-- | Run the LLVM Compiler
runLlvmLlc :: DynFlags -> [Option] -> IO ()
runLlvmLlc dflags args = do
let (p,args0) = pgm_lc dflags
args1 = map Option (getOpts dflags opt_lc)
runSomething dflags "LLVM Compiler" p (args0 ++ args1 ++ args)
-- | Run the clang compiler (used as an assembler for the LLVM
-- backend on OS X as LLVM doesn't support the OS X system
-- assembler)
runClang :: DynFlags -> [Option] -> IO ()
runClang dflags args = do
-- we simply assume its available on the PATH
let clang = "clang"
-- be careful what options we call clang with
-- see #5903 and #7617 for bugs caused by this.
(_,args0) = pgm_a dflags
args1 = map Option (getOpts dflags opt_a)
args2 = args0 ++ args1 ++ args
mb_env <- getGccEnv args2
Exception.catch (do
runSomethingFiltered dflags id "Clang (Assembler)" clang args2 mb_env
)
(\(err :: SomeException) -> do
errorMsg dflags $
text ("Error running clang! you need clang installed to use the" ++
"LLVM backend") $+$
text "(or GHC tried to execute clang incorrectly)"
throwIO err
)
-- | Figure out which version of LLVM we are running this session
figureLlvmVersion :: DynFlags -> IO (Maybe Int)
figureLlvmVersion dflags = do
let (pgm,opts) = pgm_lc dflags
args = filter notNull (map showOpt opts)
-- we grab the args even though they should be useless just in
-- case the user is using a customised 'llc' that requires some
-- of the options they've specified. llc doesn't care what other
-- options are specified when '-version' is used.
args' = args ++ ["-version"]
ver <- catchIO (do
(pin, pout, perr, _) <- runInteractiveProcess pgm args'
Nothing Nothing
{- > llc -version
Low Level Virtual Machine (http://llvm.org/):
llvm version 2.8 (Ubuntu 2.8-0Ubuntu1)
...
-}
hSetBinaryMode pout False
_ <- hGetLine pout
vline <- hGetLine pout
v <- case filter isDigit vline of
[] -> fail "no digits!"
[x] -> fail $ "only 1 digit! (" ++ show x ++ ")"
(x:y:_) -> return ((read [x,y]) :: Int)
hClose pin
hClose pout
hClose perr
return $ Just v
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out LLVM version):" <+>
text (show err))
errorMsg dflags $ vcat
[ text "Warning:", nest 9 $
text "Couldn't figure out LLVM version!" $$
text "Make sure you have installed LLVM"]
return Nothing)
return ver
{- Note [Windows stack usage]
See: Trac #8870 (and #8834 for related info)
On Windows, occasionally we need to grow the stack. In order to do
this, we would normally just bump the stack pointer - but there's a
catch on Windows.
If the stack pointer is bumped by more than a single page, then the
pages between the initial pointer and the resulting location must be
properly committed by the Windows virtual memory subsystem. This is
only needed in the event we bump by more than one page (i.e 4097 bytes
or more).
Windows compilers solve this by emitting a call to a special function
called _chkstk, which does this committing of the pages for you.
The reason this was causing a segfault was because due to the fact the
new code generator tends to generate larger functions, we needed more
stack space in GHC itself. In the x86 codegen, we needed approximately
~12kb of stack space in one go, which caused the process to segfault,
as the intervening pages were not committed.
In the future, we should do the same thing, to make the problem
completely go away. In the mean time, we're using a workaround: we
instruct the linker to specify the generated PE as having an initial
reserved stack size of 8mb, as well as a initial *committed* stack
size of 8mb. The default committed size was previously only 4k.
Theoretically it's possible to still hit this problem if you request a
stack bump of more than 8mb in one go. But the amount of code
necessary is quite large, and 8mb "should be more than enough for
anyone" right now (he said, before millions of lines of code cried out
in terror).
-}
{- Note [Run-time linker info]
See also: Trac #5240, Trac #6063
Before 'runLink', we need to be sure to get the relevant information
about the linker we're using at runtime to see if we need any extra
options. For example, GNU ld requires '--reduce-memory-overheads' and
'--hash-size=31' in order to use reasonable amounts of memory (see
trac #5240.) But this isn't supported in GNU gold.
Generally, the linker changing from what was detected at ./configure
time has always been possible using -pgml, but on Linux it can happen
'transparently' by installing packages like binutils-gold, which
change what /usr/bin/ld actually points to.
Clang vs GCC notes:
For gcc, 'gcc -Wl,--version' gives a bunch of output about how to
invoke the linker before the version information string. For 'clang',
the version information for 'ld' is all that's output. For this
reason, we typically need to slurp up all of the standard error output
and look through it.
Other notes:
We cache the LinkerInfo inside DynFlags, since clients may link
multiple times. The definition of LinkerInfo is there to avoid a
circular dependency.
-}
neededLinkArgs :: LinkerInfo -> [Option]
neededLinkArgs (GnuLD o) = o
neededLinkArgs (GnuGold o) = o
neededLinkArgs (DarwinLD o) = o
neededLinkArgs (SolarisLD o) = o
neededLinkArgs UnknownLD = []
-- Grab linker info and cache it in DynFlags.
getLinkerInfo :: DynFlags -> IO LinkerInfo
getLinkerInfo dflags = do
info <- readIORef (rtldInfo dflags)
case info of
Just v -> return v
Nothing -> do
v <- getLinkerInfo' dflags
writeIORef (rtldInfo dflags) (Just v)
return v
-- See Note [Run-time linker info].
getLinkerInfo' :: DynFlags -> IO LinkerInfo
getLinkerInfo' dflags = do
let platform = targetPlatform dflags
os = platformOS platform
(pgm,args0) = pgm_l dflags
args1 = map Option (getOpts dflags opt_l)
args2 = args0 ++ args1
args3 = filter notNull (map showOpt args2)
-- Try to grab the info from the process output.
parseLinkerInfo stdo _stde _exitc
| any ("GNU ld" `isPrefixOf`) stdo =
-- GNU ld specifically needs to use less memory. This especially
-- hurts on small object files. Trac #5240.
return (GnuLD $ map Option ["-Wl,--hash-size=31",
"-Wl,--reduce-memory-overheads"])
| any ("GNU gold" `isPrefixOf`) stdo =
-- GNU gold does not require any special arguments.
return (GnuGold [])
-- Unknown linker.
| otherwise = fail "invalid --version output, or linker is unsupported"
-- Process the executable call
info <- catchIO (do
case os of
OSSolaris2 ->
-- Solaris uses its own Solaris linker. Even all
-- GNU C are recommended to configure with Solaris
-- linker instead of using GNU binutils linker. Also
-- all GCC distributed with Solaris follows this rule
-- precisely so we assume here, the Solaris linker is
-- used.
return $ SolarisLD []
OSDarwin ->
-- Darwin has neither GNU Gold or GNU LD, but a strange linker
-- that doesn't support --version. We can just assume that's
-- what we're using.
return $ DarwinLD []
OSiOS ->
-- Ditto for iOS
return $ DarwinLD []
OSMinGW32 ->
-- GHC doesn't support anything but GNU ld on Windows anyway.
-- Process creation is also fairly expensive on win32, so
-- we short-circuit here.
return $ GnuLD $ map Option
[ -- Reduce ld memory usage
"-Wl,--hash-size=31"
, "-Wl,--reduce-memory-overheads"
-- Increase default stack, see
-- Note [Windows stack usage]
, "-Xlinker", "--stack=0x800000,0x800000" ]
_ -> do
-- In practice, we use the compiler as the linker here. Pass
-- -Wl,--version to get linker version info.
(exitc, stdo, stde) <- readProcessEnvWithExitCode pgm
(["-Wl,--version"] ++ args3)
en_locale_env
-- Split the output by lines to make certain kinds
-- of processing easier. In particular, 'clang' and 'gcc'
-- have slightly different outputs for '-Wl,--version', but
-- it's still easy to figure out.
parseLinkerInfo (lines stdo) (lines stde) exitc
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out linker information):" <+>
text (show err))
errorMsg dflags $ hang (text "Warning:") 9 $
text "Couldn't figure out linker information!" $$
text "Make sure you're using GNU ld, GNU gold" <+>
text "or the built in OS X linker, etc."
return UnknownLD)
return info
-- Grab compiler info and cache it in DynFlags.
getCompilerInfo :: DynFlags -> IO CompilerInfo
getCompilerInfo dflags = do
info <- readIORef (rtccInfo dflags)
case info of
Just v -> return v
Nothing -> do
v <- getCompilerInfo' dflags
writeIORef (rtccInfo dflags) (Just v)
return v
-- See Note [Run-time linker info].
getCompilerInfo' :: DynFlags -> IO CompilerInfo
getCompilerInfo' dflags = do
let (pgm,_) = pgm_c dflags
-- Try to grab the info from the process output.
parseCompilerInfo _stdo stde _exitc
-- Regular GCC
| any ("gcc version" `isPrefixOf`) stde =
return GCC
-- Regular clang
| any ("clang version" `isPrefixOf`) stde =
return Clang
-- XCode 5.1 clang
| any ("Apple LLVM version 5.1" `isPrefixOf`) stde =
return AppleClang51
-- XCode 5 clang
| any ("Apple LLVM version" `isPrefixOf`) stde =
return AppleClang
-- XCode 4.1 clang
| any ("Apple clang version" `isPrefixOf`) stde =
return AppleClang
-- Unknown linker.
| otherwise = fail "invalid -v output, or compiler is unsupported"
-- Process the executable call
info <- catchIO (do
(exitc, stdo, stde) <-
readProcessEnvWithExitCode pgm ["-v"] en_locale_env
-- Split the output by lines to make certain kinds
-- of processing easier.
parseCompilerInfo (lines stdo) (lines stde) exitc
)
(\err -> do
debugTraceMsg dflags 2
(text "Error (figuring out C compiler information):" <+>
text (show err))
errorMsg dflags $ hang (text "Warning:") 9 $
text "Couldn't figure out C compiler information!" $$
text "Make sure you're using GNU gcc, or clang"
return UnknownCC)
return info
runLink :: DynFlags -> [Option] -> IO ()
runLink dflags args = do
-- See Note [Run-time linker info]
linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
let (p,args0) = pgm_l dflags
args1 = map Option (getOpts dflags opt_l)
args2 = args0 ++ args1 ++ args ++ linkargs
mb_env <- getGccEnv args2
runSomethingFiltered dflags ld_filter "Linker" p args2 mb_env
where
ld_filter = case (platformOS (targetPlatform dflags)) of
OSSolaris2 -> sunos_ld_filter
_ -> id
{-
SunOS/Solaris ld emits harmless warning messages about unresolved
symbols in case of compiling into shared library when we do not
link against all the required libs. That is the case of GHC which
does not link against RTS library explicitly in order to be able to
choose the library later based on binary application linking
parameters. The warnings look like:
Undefined first referenced
symbol in file
stg_ap_n_fast ./T2386_Lib.o
stg_upd_frame_info ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_litE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_appE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_conE_closure ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziSyntax_mkNameGzud_closure ./T2386_Lib.o
newCAF ./T2386_Lib.o
stg_bh_upd_frame_info ./T2386_Lib.o
stg_ap_ppp_fast ./T2386_Lib.o
templatezmhaskell_LanguageziHaskellziTHziLib_stringL_closure ./T2386_Lib.o
stg_ap_p_fast ./T2386_Lib.o
stg_ap_pp_fast ./T2386_Lib.o
ld: warning: symbol referencing errors
this is actually coming from T2386 testcase. The emitting of those
warnings is also a reason why so many TH testcases fail on Solaris.
Following filter code is SunOS/Solaris linker specific and should
filter out only linker warnings. Please note that the logic is a
little bit more complex due to the simple reason that we need to preserve
any other linker emitted messages. If there are any. Simply speaking
if we see "Undefined" and later "ld: warning:..." then we omit all
text between (including) the marks. Otherwise we copy the whole output.
-}
sunos_ld_filter :: String -> String
sunos_ld_filter = unlines . sunos_ld_filter' . lines
sunos_ld_filter' x = if (undefined_found x && ld_warning_found x)
then (ld_prefix x) ++ (ld_postfix x)
else x
breakStartsWith x y = break (isPrefixOf x) y
ld_prefix = fst . breakStartsWith "Undefined"
undefined_found = not . null . snd . breakStartsWith "Undefined"
ld_warn_break = breakStartsWith "ld: warning: symbol referencing errors"
ld_postfix = tail . snd . ld_warn_break
ld_warning_found = not . null . snd . ld_warn_break
runLibtool :: DynFlags -> [Option] -> IO ()
runLibtool dflags args = do
linkargs <- neededLinkArgs `fmap` getLinkerInfo dflags
let args1 = map Option (getOpts dflags opt_l)
args2 = [Option "-static"] ++ args1 ++ args ++ linkargs
libtool = pgm_libtool dflags
mb_env <- getGccEnv args2
runSomethingFiltered dflags id "Linker" libtool args2 mb_env
runMkDLL :: DynFlags -> [Option] -> IO ()
runMkDLL dflags args = do
let (p,args0) = pgm_dll dflags
args1 = args0 ++ args
mb_env <- getGccEnv (args0++args)
runSomethingFiltered dflags id "Make DLL" p args1 mb_env
runWindres :: DynFlags -> [Option] -> IO ()
runWindres dflags args = do
let (gcc, gcc_args) = pgm_c dflags
windres = pgm_windres dflags
opts = map Option (getOpts dflags opt_windres)
quote x = "\"" ++ x ++ "\""
args' = -- If windres.exe and gcc.exe are in a directory containing
-- spaces then windres fails to run gcc. We therefore need
-- to tell it what command to use...
Option ("--preprocessor=" ++
unwords (map quote (gcc :
map showOpt gcc_args ++
map showOpt opts ++
["-E", "-xc", "-DRC_INVOKED"])))
-- ...but if we do that then if windres calls popen then
-- it can't understand the quoting, so we have to use
-- --use-temp-file so that it interprets it correctly.
-- See #1828.
: Option "--use-temp-file"
: args
mb_env <- getGccEnv gcc_args
runSomethingFiltered dflags id "Windres" windres args' mb_env
touch :: DynFlags -> String -> String -> IO ()
touch dflags purpose arg =
runSomething dflags purpose (pgm_T dflags) [FileOption "" arg]
copy :: DynFlags -> String -> FilePath -> FilePath -> IO ()
copy dflags purpose from to = copyWithHeader dflags purpose Nothing from to
copyWithHeader :: DynFlags -> String -> Maybe String -> FilePath -> FilePath
-> IO ()
copyWithHeader dflags purpose maybe_header from to = do
showPass dflags purpose
hout <- openBinaryFile to WriteMode
hin <- openBinaryFile from ReadMode
ls <- hGetContents hin -- inefficient, but it'll do for now. ToDo: speed up
maybe (return ()) (header hout) maybe_header
hPutStr hout ls
hClose hout
hClose hin
where
-- write the header string in UTF-8. The header is something like
-- {-# LINE "foo.hs" #-}
-- and we want to make sure a Unicode filename isn't mangled.
header h str = do
hSetEncoding h utf8
hPutStr h str
hSetBinaryMode h True
-- | read the contents of the named section in an ELF object as a
-- String.
readElfSection :: DynFlags -> String -> FilePath -> IO (Maybe String)
readElfSection _dflags section exe = do
let
prog = "readelf"
args = [Option "-p", Option section, FileOption "" exe]
--
r <- readProcessEnvWithExitCode prog (filter notNull (map showOpt args))
en_locale_env
case r of
(ExitSuccess, out, _err) -> return (doFilter (lines out))
_ -> return Nothing
where
doFilter [] = Nothing
doFilter (s:r) = case readP_to_S parse s of
[(p,"")] -> Just p
_r -> doFilter r
where parse = do
skipSpaces
_ <- R.char '['
skipSpaces
_ <- string "0]"
skipSpaces
munch (const True)
{-
************************************************************************
* *
\subsection{Managing temporary files
* *
************************************************************************
-}
cleanTempDirs :: DynFlags -> IO ()
cleanTempDirs dflags
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = dirsToClean dflags
ds <- atomicModifyIORef ref $ \ds -> (Map.empty, ds)
removeTmpDirs dflags (Map.elems ds)
cleanTempFiles :: DynFlags -> IO ()
cleanTempFiles dflags
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = filesToClean dflags
fs <- atomicModifyIORef ref $ \fs -> ([],fs)
removeTmpFiles dflags fs
cleanTempFilesExcept :: DynFlags -> [FilePath] -> IO ()
cleanTempFilesExcept dflags dont_delete
= unless (gopt Opt_KeepTmpFiles dflags)
$ mask_
$ do let ref = filesToClean dflags
to_delete <- atomicModifyIORef ref $ \files ->
let (to_keep,to_delete) = partition (`elem` dont_delete) files
in (to_keep,to_delete)
removeTmpFiles dflags to_delete
-- Return a unique numeric temp file suffix
newTempSuffix :: DynFlags -> IO Int
newTempSuffix dflags = atomicModifyIORef (nextTempSuffix dflags) $ \n -> (n+1,n)
-- Find a temporary name that doesn't already exist.
newTempName :: DynFlags -> Suffix -> IO FilePath
newTempName dflags extn
= do d <- getTempDir dflags
x <- getProcessID
findTempName (d </> "ghc" ++ show x ++ "_")
where
findTempName :: FilePath -> IO FilePath
findTempName prefix
= do n <- newTempSuffix dflags
let filename = prefix ++ show n <.> extn
b <- doesFileExist filename
if b then findTempName prefix
else do -- clean it up later
consIORef (filesToClean dflags) filename
return filename
-- Return our temporary directory within tmp_dir, creating one if we
-- don't have one yet.
getTempDir :: DynFlags -> IO FilePath
getTempDir dflags = do
mapping <- readIORef dir_ref
case Map.lookup tmp_dir mapping of
Nothing -> do
pid <- getProcessID
let prefix = tmp_dir </> "ghc" ++ show pid ++ "_"
mask_ $ mkTempDir prefix
Just dir -> return dir
where
tmp_dir = tmpDir dflags
dir_ref = dirsToClean dflags
mkTempDir :: FilePath -> IO FilePath
mkTempDir prefix = do
n <- newTempSuffix dflags
let our_dir = prefix ++ show n
-- 1. Speculatively create our new directory.
createDirectory our_dir
-- 2. Update the dirsToClean mapping unless an entry already exists
-- (i.e. unless another thread beat us to it).
their_dir <- atomicModifyIORef dir_ref $ \mapping ->
case Map.lookup tmp_dir mapping of
Just dir -> (mapping, Just dir)
Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing)
-- 3. If there was an existing entry, return it and delete the
-- directory we created. Otherwise return the directory we created.
case their_dir of
Nothing -> do
debugTraceMsg dflags 2 $
text "Created temporary directory:" <+> text our_dir
return our_dir
Just dir -> do
removeDirectory our_dir
return dir
`catchIO` \e -> if isAlreadyExistsError e
then mkTempDir prefix else ioError e
addFilesToClean :: DynFlags -> [FilePath] -> IO ()
-- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
addFilesToClean dflags new_files
= atomicModifyIORef (filesToClean dflags) $ \files -> (new_files++files, ())
removeTmpDirs :: DynFlags -> [FilePath] -> IO ()
removeTmpDirs dflags ds
= traceCmd dflags "Deleting temp dirs"
("Deleting: " ++ unwords ds)
(mapM_ (removeWith dflags removeDirectory) ds)
removeTmpFiles :: DynFlags -> [FilePath] -> IO ()
removeTmpFiles dflags fs
= warnNon $
traceCmd dflags "Deleting temp files"
("Deleting: " ++ unwords deletees)
(mapM_ (removeWith dflags removeFile) deletees)
where
-- Flat out refuse to delete files that are likely to be source input
-- files (is there a worse bug than having a compiler delete your source
-- files?)
--
-- Deleting source files is a sign of a bug elsewhere, so prominently flag
-- the condition.
warnNon act
| null non_deletees = act
| otherwise = do
putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees))
act
(non_deletees, deletees) = partition isHaskellUserSrcFilename fs
removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO ()
removeWith dflags remover f = remover f `catchIO`
(\e ->
let msg = if isDoesNotExistError e
then ptext (sLit "Warning: deleting non-existent") <+> text f
else ptext (sLit "Warning: exception raised when deleting")
<+> text f <> colon
$$ text (show e)
in debugTraceMsg dflags 2 msg
)
-----------------------------------------------------------------------------
-- Running an external program
runSomething :: DynFlags
-> String -- For -v message
-> String -- Command name (possibly a full path)
-- assumed already dos-ified
-> [Option] -- Arguments
-- runSomething will dos-ify them
-> IO ()
runSomething dflags phase_name pgm args =
runSomethingFiltered dflags id phase_name pgm args Nothing
runSomethingFiltered
:: DynFlags -> (String->String) -> String -> String -> [Option]
-> Maybe [(String,String)] -> IO ()
runSomethingFiltered dflags filter_fn phase_name pgm args mb_env = do
runSomethingWith dflags phase_name pgm args $ \real_args -> do
r <- builderMainLoop dflags filter_fn pgm real_args mb_env
return (r,())
runSomethingWith
:: DynFlags -> String -> String -> [Option]
-> ([String] -> IO (ExitCode, a))
-> IO a
runSomethingWith dflags phase_name pgm args io = do
let real_args = filter notNull (map showOpt args)
cmdLine = showCommandForUser pgm real_args
traceCmd dflags phase_name cmdLine $ handleProc pgm phase_name $ io real_args
handleProc :: String -> String -> IO (ExitCode, r) -> IO r
handleProc pgm phase_name proc = do
(rc, r) <- proc `catchIO` handler
case rc of
ExitSuccess{} -> return r
ExitFailure n
-- rawSystem returns (ExitFailure 127) if the exec failed for any
-- reason (eg. the program doesn't exist). This is the only clue
-- we have, but we need to report something to the user because in
-- the case of a missing program there will otherwise be no output
-- at all.
| n == 127 -> does_not_exist
| otherwise -> throwGhcExceptionIO (PhaseFailed phase_name rc)
where
handler err =
if IO.isDoesNotExistError err
then does_not_exist
else IO.ioError err
does_not_exist = throwGhcExceptionIO (InstallationError ("could not execute: " ++ pgm))
builderMainLoop :: DynFlags -> (String -> String) -> FilePath
-> [String] -> Maybe [(String, String)]
-> IO ExitCode
builderMainLoop dflags filter_fn pgm real_args mb_env = do
chan <- newChan
(hStdIn, hStdOut, hStdErr, hProcess) <- runInteractiveProcess pgm real_args Nothing mb_env
-- and run a loop piping the output from the compiler to the log_action in DynFlags
hSetBuffering hStdOut LineBuffering
hSetBuffering hStdErr LineBuffering
_ <- forkIO (readerProc chan hStdOut filter_fn)
_ <- forkIO (readerProc chan hStdErr filter_fn)
-- we don't want to finish until 2 streams have been completed
-- (stdout and stderr)
-- nor until 1 exit code has been retrieved.
rc <- loop chan hProcess (2::Integer) (1::Integer) ExitSuccess
-- after that, we're done here.
hClose hStdIn
hClose hStdOut
hClose hStdErr
return rc
where
-- status starts at zero, and increments each time either
-- a reader process gets EOF, or the build proc exits. We wait
-- for all of these to happen (status==3).
-- ToDo: we should really have a contingency plan in case any of
-- the threads dies, such as a timeout.
loop _ _ 0 0 exitcode = return exitcode
loop chan hProcess t p exitcode = do
mb_code <- if p > 0
then getProcessExitCode hProcess
else return Nothing
case mb_code of
Just code -> loop chan hProcess t (p-1) code
Nothing
| t > 0 -> do
msg <- readChan chan
case msg of
BuildMsg msg -> do
log_action dflags dflags SevInfo noSrcSpan defaultUserStyle msg
loop chan hProcess t p exitcode
BuildError loc msg -> do
log_action dflags dflags SevError (mkSrcSpan loc loc) defaultUserStyle msg
loop chan hProcess t p exitcode
EOF ->
loop chan hProcess (t-1) p exitcode
| otherwise -> loop chan hProcess t p exitcode
readerProc :: Chan BuildMessage -> Handle -> (String -> String) -> IO ()
readerProc chan hdl filter_fn =
(do str <- hGetContents hdl
loop (linesPlatform (filter_fn str)) Nothing)
`finally`
writeChan chan EOF
-- ToDo: check errors more carefully
-- ToDo: in the future, the filter should be implemented as
-- a stream transformer.
where
loop [] Nothing = return ()
loop [] (Just err) = writeChan chan err
loop (l:ls) in_err =
case in_err of
Just err@(BuildError srcLoc msg)
| leading_whitespace l -> do
loop ls (Just (BuildError srcLoc (msg $$ text l)))
| otherwise -> do
writeChan chan err
checkError l ls
Nothing -> do
checkError l ls
_ -> panic "readerProc/loop"
checkError l ls
= case parseError l of
Nothing -> do
writeChan chan (BuildMsg (text l))
loop ls Nothing
Just (file, lineNum, colNum, msg) -> do
let srcLoc = mkSrcLoc (mkFastString file) lineNum colNum
loop ls (Just (BuildError srcLoc (text msg)))
leading_whitespace [] = False
leading_whitespace (x:_) = isSpace x
parseError :: String -> Maybe (String, Int, Int, String)
parseError s0 = case breakColon s0 of
Just (filename, s1) ->
case breakIntColon s1 of
Just (lineNum, s2) ->
case breakIntColon s2 of
Just (columnNum, s3) ->
Just (filename, lineNum, columnNum, s3)
Nothing ->
Just (filename, lineNum, 0, s2)
Nothing -> Nothing
Nothing -> Nothing
breakColon :: String -> Maybe (String, String)
breakColon xs = case break (':' ==) xs of
(ys, _:zs) -> Just (ys, zs)
_ -> Nothing
breakIntColon :: String -> Maybe (Int, String)
breakIntColon xs = case break (':' ==) xs of
(ys, _:zs)
| not (null ys) && all isAscii ys && all isDigit ys ->
Just (read ys, zs)
_ -> Nothing
data BuildMessage
= BuildMsg !SDoc
| BuildError !SrcLoc !SDoc
| EOF
traceCmd :: DynFlags -> String -> String -> IO a -> IO a
-- trace the command (at two levels of verbosity)
traceCmd dflags phase_name cmd_line action
= do { let verb = verbosity dflags
; showPass dflags phase_name
; debugTraceMsg dflags 3 (text cmd_line)
; case flushErr dflags of
FlushErr io -> io
-- And run it!
; action `catchIO` handle_exn verb
}
where
handle_exn _verb exn = do { debugTraceMsg dflags 2 (char '\n')
; debugTraceMsg dflags 2 (ptext (sLit "Failed:") <+> text cmd_line <+> text (show exn))
; throwGhcExceptionIO (PhaseFailed phase_name (ExitFailure 1)) }
{-
************************************************************************
* *
\subsection{Support code}
* *
************************************************************************
-}
-----------------------------------------------------------------------------
-- Define getBaseDir :: IO (Maybe String)
getBaseDir :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
-- Assuming we are running ghc, accessed by path $(stuff)/bin/ghc.exe,
-- return the path $(stuff)/lib.
getBaseDir = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> fmap (Just . rootDir) $ peekCWString buf
| otherwise -> try_size (size * 2)
rootDir s = case splitFileName $ normalise s of
(d, ghc_exe)
| lower ghc_exe `elem` ["ghc.exe",
"ghc-stage1.exe",
"ghc-stage2.exe",
"ghc-stage3.exe"] ->
case splitFileName $ takeDirectory d of
-- ghc is in $topdir/bin/ghc.exe
(d', bin) | lower bin == "bin" -> takeDirectory d' </> "lib"
_ -> fail
_ -> fail
where fail = panic ("can't decompose ghc.exe path: " ++ show s)
lower = map toLower
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
#else
getBaseDir = return Nothing
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
#else
getProcessID :: IO Int
getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
#endif
-- Divvy up text stream into lines, taking platform dependent
-- line termination into account.
linesPlatform :: String -> [String]
#if !defined(mingw32_HOST_OS)
linesPlatform ls = lines ls
#else
linesPlatform "" = []
linesPlatform xs =
case lineBreak xs of
(as,xs1) -> as : linesPlatform xs1
where
lineBreak "" = ("","")
lineBreak ('\r':'\n':xs) = ([],xs)
lineBreak ('\n':xs) = ([],xs)
lineBreak (x:xs) = let (as,bs) = lineBreak xs in (x:as,bs)
#endif
linkDynLib :: DynFlags -> [String] -> [PackageKey] -> IO ()
linkDynLib dflags0 o_files dep_packages
= do
let -- This is a rather ugly hack to fix dynamically linked
-- GHC on Windows. If GHC is linked with -threaded, then
-- it links against libHSrts_thr. But if base is linked
-- against libHSrts, then both end up getting loaded,
-- and things go wrong. We therefore link the libraries
-- with the same RTS flags that we link GHC with.
dflags1 = if cGhcThreaded then addWay' WayThreaded dflags0
else dflags0
dflags2 = if cGhcDebugged then addWay' WayDebug dflags1
else dflags1
dflags = updateWays dflags2
verbFlags = getVerbFlags dflags
o_file = outputFile dflags
pkgs <- getPreloadPackagesAnd dflags dep_packages
let pkg_lib_paths = collectLibraryPaths pkgs
let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
get_pkg_lib_path_opts l
| ( osElfTarget (platformOS (targetPlatform dflags)) ||
osMachOTarget (platformOS (targetPlatform dflags)) ) &&
dynLibLoader dflags == SystemDependent &&
not (gopt Opt_Static dflags)
= ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
| otherwise = ["-L" ++ l]
let lib_paths = libraryPaths dflags
let lib_path_opts = map ("-L"++) lib_paths
-- We don't want to link our dynamic libs against the RTS package,
-- because the RTS lib comes in several flavours and we want to be
-- able to pick the flavour when a binary is linked.
-- On Windows we need to link the RTS import lib as Windows does
-- not allow undefined symbols.
-- The RTS library path is still added to the library search path
-- above in case the RTS is being explicitly linked in (see #3807).
let platform = targetPlatform dflags
os = platformOS platform
pkgs_no_rts = case os of
OSMinGW32 ->
pkgs
_ ->
filter ((/= rtsPackageKey) . packageConfigId) pkgs
let pkg_link_opts = let (package_hs_libs, extra_libs, other_flags) = collectLinkOpts dflags pkgs_no_rts
in package_hs_libs ++ extra_libs ++ other_flags
-- probably _stub.o files
-- and last temporary shared object file
let extra_ld_inputs = ldInputs dflags
case os of
OSMinGW32 -> do
-------------------------------------------------------------
-- Making a DLL
-------------------------------------------------------------
let output_fn = case o_file of
Just s -> s
Nothing -> "HSdll.dll"
runLink dflags (
map Option verbFlags
++ [ Option "-o"
, FileOption "" output_fn
, Option "-shared"
] ++
[ FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
| gopt Opt_SharedImplib dflags
]
++ map (FileOption "") o_files
-- Permit the linker to auto link _symbol to _imp_symbol
-- This lets us link against DLLs without needing an "import library"
++ [Option "-Wl,--enable-auto-import"]
++ extra_ld_inputs
++ map Option (
lib_path_opts
++ pkg_lib_path_opts
++ pkg_link_opts
))
OSDarwin -> do
-------------------------------------------------------------------
-- Making a darwin dylib
-------------------------------------------------------------------
-- About the options used for Darwin:
-- -dynamiclib
-- Apple's way of saying -shared
-- -undefined dynamic_lookup:
-- Without these options, we'd have to specify the correct
-- dependencies for each of the dylibs. Note that we could
-- (and should) do without this for all libraries except
-- the RTS; all we need to do is to pass the correct
-- HSfoo_dyn.dylib files to the link command.
-- This feature requires Mac OS X 10.3 or later; there is
-- a similar feature, -flat_namespace -undefined suppress,
-- which works on earlier versions, but it has other
-- disadvantages.
-- -single_module
-- Build the dynamic library as a single "module", i.e. no
-- dynamic binding nonsense when referring to symbols from
-- within the library. The NCG assumes that this option is
-- specified (on i386, at least).
-- -install_name
-- Mac OS/X stores the path where a dynamic library is (to
-- be) installed in the library itself. It's called the
-- "install name" of the library. Then any library or
-- executable that links against it before it's installed
-- will search for it in its ultimate install location.
-- By default we set the install name to the absolute path
-- at build time, but it can be overridden by the
-- -dylib-install-name option passed to ghc. Cabal does
-- this.
-------------------------------------------------------------------
let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
instName <- case dylibInstallName dflags of
Just n -> return n
Nothing -> return $ "@rpath" `combine` (takeFileName output_fn)
runLink dflags (
map Option verbFlags
++ [ Option "-dynamiclib"
, Option "-o"
, FileOption "" output_fn
]
++ map Option o_files
++ [ Option "-undefined",
Option "dynamic_lookup",
Option "-single_module" ]
++ (if platformArch platform == ArchX86_64
then [ ]
else [ Option "-Wl,-read_only_relocs,suppress" ])
++ [ Option "-install_name", Option instName ]
++ map Option lib_path_opts
++ extra_ld_inputs
++ map Option pkg_lib_path_opts
++ map Option pkg_link_opts
)
OSiOS -> throwGhcExceptionIO (ProgramError "dynamic libraries are not supported on iOS target")
_ -> do
-------------------------------------------------------------------
-- Making a DSO
-------------------------------------------------------------------
let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
let buildingRts = thisPackage dflags == rtsPackageKey
let bsymbolicFlag = if buildingRts
then -- -Bsymbolic breaks the way we implement
-- hooks in the RTS
[]
else -- we need symbolic linking to resolve
-- non-PIC intra-package-relocations
["-Wl,-Bsymbolic"]
runLink dflags (
map Option verbFlags
++ [ Option "-o"
, FileOption "" output_fn
]
++ map Option o_files
++ [ Option "-shared" ]
++ map Option bsymbolicFlag
-- Set the library soname. We use -h rather than -soname as
-- Solaris 10 doesn't support the latter:
++ [ Option ("-Wl,-h," ++ takeFileName output_fn) ]
++ extra_ld_inputs
++ map Option lib_path_opts
++ map Option pkg_lib_path_opts
++ map Option pkg_link_opts
)
| bitemyapp/ghc | compiler/main/SysTools.hs | bsd-3-clause | 63,869 | 66 | 22 | 21,351 | 11,339 | 5,780 | 5,559 | 920 | 13 |
{-# LANGUAGE GeneralizedNewtypeDeriving,FlexibleInstances,MultiParamTypeClasses,UndecidableInstances #-}
module Counter (CounterT(CounterT), runCounterT, getAndInc) where
import Control.Applicative
import Control.Monad.Trans
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State
newtype CounterT s m a = CounterT { unCounterT :: StateT s m a } deriving (Monad,Functor,MonadTrans,Applicative)
instance MonadReader r m => MonadReader r (CounterT s m) where
ask = lift ask
local fun m = CounterT (local fun (unCounterT m))
instance MonadIO m => MonadIO (CounterT s m) where
liftIO = lift . liftIO
instance (MonadWriter w m) => MonadWriter w (CounterT s m) where
tell = lift . tell
listen m = CounterT (listen (unCounterT m))
pass m = CounterT (pass (unCounterT m))
instance (MonadState s m) => MonadState s (CounterT c m) where
get = lift get
put = lift . put
runCounterT :: Monad m => s -> CounterT s m a -> m a
runCounterT s m = liftM fst (runStateT (unCounterT m) s)
getAndInc :: Functor m => Monad m => Enum s => CounterT s m s
getAndInc = CounterT (get <* modify succ)
| olsner/m3 | Counter.hs | bsd-3-clause | 1,122 | 0 | 10 | 193 | 425 | 222 | 203 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
module Data.Type.Product.Quote
( qP
) where
import Data.Type.Quote
import Data.Type.Product
import Language.Haskell.TH
import Language.Haskell.TH.Quote
qP :: QuasiQuoter
qP = QuasiQuoter
{ quoteExp = parseProd (parseExp qq) prodExp
, quotePat = parseProd (parsePat qq) prodPat
, quoteType = stub qq "quoteType not provided"
, quoteDec = stub qq "quoteDec not provided"
}
where
qq = "qP"
parseProd :: (String -> Q a) -> ([Q a] -> Q a) -> String -> Q a
parseProd prs bld = bld . map prs . commaSep
prodExp :: [Q Exp] -> Q Exp
prodExp = \case
e : es -> [| $e :< $(prodExp es) |]
_ -> [| Ø |]
prodPat :: [Q Pat] -> Q Pat
prodPat = \case
e : es -> [p| $e :< $(prodPat es) |]
_ -> [p| Ø |]
| kylcarte/type-combinators-quote | src/Data/Type/Product/Quote.hs | bsd-3-clause | 889 | 0 | 10 | 198 | 281 | 161 | 120 | 28 | 2 |
module Playground08 where
import qualified Data.Text.All as T
-- Using map 8.1
reverseMyDogs :: [[a]] -> [[a]]
reverseMyDogs dogs = map reverse dogs
filterMyDogs :: [String] -> [String]
filterMyDogs dogs = filter (\ x -> (T.toLower (T.pack x)) == (T.toLower ( T.pack "Axel")) ) dogs
-- Folding a list 8.4
foldMyDogs :: Foldable t => t [a] -> [a]
foldMyDogs dogs = foldl (++) [] dogs
myReverse :: Foldable t => t a -> [a]
myReverse xs = foldl rcons [] xs
where rcons x y = y:x
| stefanocerruti/haskell-primer-alpha | src/Playground08.hs | bsd-3-clause | 490 | 0 | 13 | 102 | 220 | 119 | 101 | 11 | 1 |
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, FlexibleContexts, RankNTypes, GADTs #-}
module QueryArrow.DBMap where
import QueryArrow.DB.DB
import QueryArrow.Syntax.Type
import QueryArrow.Semantics.TypeChecker
import QueryArrow.Config
import QueryArrow.Translation
import QueryArrow.Cache
import QueryArrow.Plugin
import QueryArrow.Sum
import QueryArrow.Include
import Data.Maybe
import Prelude hiding (lookup)
import Data.Map.Strict (fromList, Map, lookup)
-- import Plugins
import qualified QueryArrow.SQL.HDBC.PostgreSQL as PostgreSQL
import qualified QueryArrow.SQL.HDBC.CockroachDB as CockroachDB
import qualified QueryArrow.Cypher.Neo4j as Neo4j
import QueryArrow.InMemory.BuiltIn
import QueryArrow.InMemory.Map
import qualified QueryArrow.ElasticSearch.ElasticSearch as ElasticSearch
import qualified QueryArrow.SQL.HDBC.Sqlite3 as Sqlite3
-- import qualified QueryArrow.Remote.NoTranslation.TCP.TCP as Remote.TCP
-- import qualified QueryArrow.FileSystem.FileSystem as FileSystem
import qualified QueryArrow.SQL.LibPQ.PostgreSQL as LibPQ
type DBMap = Map String (AbstractPlugin MapResultRow)
getDB2 :: DBMap -> GetDBFunction MapResultRow
getDB2 dbMap ps = case lookup (catalog_database_type ps) dbMap of
Just (AbstractPlugin getDBFunc) ->
getDB getDBFunc (getDB2 dbMap) ps
Nothing -> error ("unimplemented database type " ++ (catalog_database_type ps))
dbMap0 :: DBMap
dbMap0 = fromList [
("SQL/HDBC/PostgreSQL", AbstractPlugin PostgreSQL.PostgreSQLPlugin),
("SQL/HDBC/CockroachDB", AbstractPlugin CockroachDB.CockroachDBPlugin),
("SQL/HDBC/Sqlite3", AbstractPlugin Sqlite3.SQLite3Plugin),
("SQL/LibPQ", AbstractPlugin LibPQ.PostgreSQLPlugin),
("Cypher/Neo4j", AbstractPlugin Neo4j.Neo4jPlugin),
("InMemory/BuiltIn", AbstractPlugin builtInPlugin),
("InMemory/Map", AbstractPlugin mapPlugin),
("InMemory/MutableMap", AbstractPlugin stateMapPlugin),
("ElasticSearch/ElasticSearch", AbstractPlugin ElasticSearch.ElasticSearchPlugin),
-- ("Remote/TCP", AbstractPlugin Remote.TCP.RemoteTCPPlugin),
-- ("FileSystem", AbstractPlugin FileSystem.FileSystemPlugin),
("Cache", AbstractPlugin CachePlugin),
("Translation", AbstractPlugin TransPlugin),
("Include", AbstractPlugin IncludePlugin),
("Sum", AbstractPlugin SumPlugin)
];
transDB :: TranslationInfo -> IO (AbstractDatabase MapResultRow FormulaT)
transDB transinfo =
getDB2 dbMap0 (db_plugin transinfo)
| xu-hao/QueryArrow | QueryArrow-plugins/src/QueryArrow/DBMap.hs | bsd-3-clause | 2,554 | 0 | 12 | 354 | 486 | 289 | 197 | 46 | 2 |
-- | Dyck paths, lattice paths, etc
--
-- For example, the following figure represents a Dyck path of height 5 with 3 zero-touches (not counting the starting point,
-- but counting the endpoint) and 7 peaks:
--
-- <<svg/dyck_path.svg>>
--
{-# LANGUAGE BangPatterns #-}
module Math.Combinat.LatticePaths where
--------------------------------------------------------------------------------
import Data.List
import System.Random
import Math.Combinat.Numbers
import Math.Combinat.Trees.Binary
import Math.Combinat.ASCII as ASCII
--------------------------------------------------------------------------------
-- * Types
-- | A step in a lattice path
data Step
= UpStep -- ^ the step @(1,1)@
| DownStep -- ^ the step @(1,-1)@
deriving (Eq,Ord,Show)
-- | A lattice path is a path using only the allowed steps, never going below the zero level line @y=0@.
--
-- Note that if you rotate such a path by 45 degrees counterclockwise,
-- you get a path which uses only the steps @(1,0)@ and @(0,1)@, and stays
-- above the main diagonal (hence the name, we just use a different convention).
--
type LatticePath = [Step]
--------------------------------------------------------------------------------
-- * ascii drawing of paths
-- | Draws the path into a list of lines. For example try:
--
-- > autotabulate RowMajor (Right 5) (map asciiPath $ dyckPaths 4)
--
asciiPath :: LatticePath -> ASCII
asciiPath p = asciiFromLines $ transpose (go 0 p) where
go !h [] = []
go !h (x:xs) = case x of
UpStep -> ee h x : go (h+1) xs
DownStep -> ee (h-1) x : go (h-1) xs
maxh = pathHeight p
ee h x = replicate (maxh-h-1) ' ' ++ [ch x] ++ replicate h ' '
ch x = case x of
UpStep -> '/'
DownStep -> '\\'
--------------------------------------------------------------------------------
-- * elementary queries
-- | A lattice path is called \"valid\", if it never goes below the @y=0@ line.
isValidPath :: LatticePath -> Bool
isValidPath = go 0 where
go !y [] = y>=0
go !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in if y'<0 then False
else go y' ts
-- | A Dyck path is a lattice path whose last point lies on the @y=0@ line
isDyckPath :: LatticePath -> Bool
isDyckPath = go 0 where
go !y [] = y==0
go !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in if y'<0 then False
else go y' ts
-- | Maximal height of a lattice path
pathHeight :: LatticePath -> Int
pathHeight = go 0 0 where
go !h !y [] = h
go !h !y (t:ts) = case t of
UpStep -> go (max h (y+1)) (y+1) ts
DownStep -> go h (y-1) ts
-- | Endpoint of a lattice path, which starts from @(0,0)@.
pathEndpoint :: LatticePath -> (Int,Int)
pathEndpoint = go 0 0 where
go !x !y [] = (x,y)
go !x !y (t:ts) = case t of
UpStep -> go (x+1) (y+1) ts
DownStep -> go (x+1) (y-1) ts
-- | Returns the coordinates of the path (excluding the starting point @(0,0)@, but including
-- the endpoint)
pathCoordinates :: LatticePath -> [(Int,Int)]
pathCoordinates = go 0 0 where
go _ _ [] = []
go !x !y (t:ts) = let x' = x + 1
y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
in (x',y') : go x' y' ts
-- | Counts the up-steps
pathNumberOfUpSteps :: LatticePath -> Int
pathNumberOfUpSteps = fst . pathNumberOfUpDownSteps
-- | Counts the down-steps
pathNumberOfDownSteps :: LatticePath -> Int
pathNumberOfDownSteps = snd . pathNumberOfUpDownSteps
-- | Counts both the up-steps and down-steps
pathNumberOfUpDownSteps :: LatticePath -> (Int,Int)
pathNumberOfUpDownSteps = go 0 0 where
go !u !d (p:ps) = case p of
UpStep -> go (u+1) d ps
DownStep -> go u (d+1) ps
go !u !d [] = (u,d)
--------------------------------------------------------------------------------
-- * path-specific queries
-- | Number of peaks of a path (excluding the endpoint)
pathNumberOfPeaks :: LatticePath -> Int
pathNumberOfPeaks = go 0 where
go !k (x:xs@(y:_)) = go (if x==UpStep && y==DownStep then k+1 else k) xs
go !k [x] = k
go !k [ ] = k
-- | Number of points on the path which touch the @y=0@ zero level line
-- (excluding the starting point @(0,0)@, but including the endpoint; that is, for Dyck paths it this is always positive!).
pathNumberOfZeroTouches :: LatticePath -> Int
pathNumberOfZeroTouches = pathNumberOfTouches' 0
-- | Number of points on the path which touch the level line at height @h@
-- (excluding the starting point @(0,0)@, but including the endpoint).
pathNumberOfTouches'
:: Int -- ^ @h@ = the touch level
-> LatticePath -> Int
pathNumberOfTouches' h = go 0 0 0 where
go !cnt _ _ [] = cnt
go !cnt !x !y (t:ts) = let y' = case t of { UpStep -> y+1 ; DownStep -> y-1 }
cnt' = if y'==h then cnt+1 else cnt
in go cnt' (x+1) y' ts
--------------------------------------------------------------------------------
-- * Dyck paths
-- | @dyckPaths m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@.
--
-- Remark: Dyck paths are obviously in bijection with nested parentheses, and thus
-- also with binary trees.
--
-- Order is reverse lexicographical:
--
-- > sort (dyckPaths m) == reverse (dyckPaths m)
--
dyckPaths :: Int -> [LatticePath]
dyckPaths = map nestedParensToDyckPath . nestedParentheses
-- | @dyckPaths m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@.
--
-- > sort (dyckPathsNaive m) == sort (dyckPaths m)
--
-- Naive recursive algorithm, order is ad-hoc
--
dyckPathsNaive :: Int -> [LatticePath]
dyckPathsNaive = worker where
worker 0 = [[]]
worker m = as ++ bs where
as = [ bracket p | p <- worker (m-1) ]
bs = [ bracket p ++ q | k <- [1..m-1] , p <- worker (k-1) , q <- worker (m-k) ]
bracket p = UpStep : p ++ [DownStep]
-- | The number of Dyck paths from @(0,0)@ to @(2m,0)@ is simply the m\'th Catalan number.
countDyckPaths :: Int -> Integer
countDyckPaths m = catalan m
-- | The trivial bijection
nestedParensToDyckPath :: [Paren] -> LatticePath
nestedParensToDyckPath = map f where
f p = case p of { LeftParen -> UpStep ; RightParen -> DownStep }
-- | The trivial bijection in the other direction
dyckPathToNestedParens :: LatticePath -> [Paren]
dyckPathToNestedParens = map g where
g s = case s of { UpStep -> LeftParen ; DownStep -> RightParen }
--------------------------------------------------------------------------------
-- * Bounded Dyck paths
-- | @boundedDyckPaths h m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ whose height is at most @h@.
-- Synonym for 'boundedDyckPathsNaive'.
--
boundedDyckPaths
:: Int -- ^ @h@ = maximum height
-> Int -- ^ @m@ = half-length
-> [LatticePath]
boundedDyckPaths = boundedDyckPathsNaive
-- | @boundedDyckPathsNaive h m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ whose height is at most @h@.
--
-- > sort (boundedDyckPaths h m) == sort [ p | p <- dyckPaths m , pathHeight p <= h ]
-- > sort (boundedDyckPaths m m) == sort (dyckPaths m)
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
boundedDyckPathsNaive
:: Int -- ^ @h@ = maximum height
-> Int -- ^ @m@ = half-length
-> [LatticePath]
boundedDyckPathsNaive = worker where
worker !h !m
| h<0 = []
| m<0 = []
| m==0 = [[]]
| h<=0 = []
| otherwise = as ++ bs
where
bracket p = UpStep : p ++ [DownStep]
as = [ bracket p | p <- boundedDyckPaths (h-1) (m-1) ]
bs = [ bracket p ++ q | k <- [1..m-1] , p <- boundedDyckPaths (h-1) (k-1) , q <- boundedDyckPaths h (m-k) ]
--------------------------------------------------------------------------------
-- * More general lattice paths
-- | All lattice paths from @(0,0)@ to @(x,y)@. Clearly empty unless @x-y@ is even.
-- Synonym for 'latticePathsNaive'
--
latticePaths :: (Int,Int) -> [LatticePath]
latticePaths = latticePathsNaive
-- | All lattice paths from @(0,0)@ to @(x,y)@. Clearly empty unless @x-y@ is even.
--
-- Note that
--
-- > sort (dyckPaths n) == sort (latticePaths (0,2*n))
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
latticePathsNaive :: (Int,Int) -> [LatticePath]
latticePathsNaive (x,y) = worker x y where
worker !x !y
| odd (x-y) = []
| x<0 = []
| y<0 = []
| y==0 = dyckPaths (div x 2)
| x==1 && y==1 = [[UpStep]]
| otherwise = as ++ bs
where
bracket p = UpStep : p ++ [DownStep]
as = [ UpStep : p | p <- worker (x-1) (y-1) ]
bs = [ bracket p ++ q | k <- [1..(div x 2)] , p <- dyckPaths (k-1) , q <- worker (x-2*k) y ]
-- | Lattice paths are counted by the numbers in the Catalan triangle.
countLatticePaths :: (Int,Int) -> Integer
countLatticePaths (x,y)
| even (x+y) = catalanTriangle (div (x+y) 2) (div (x-y) 2)
| otherwise = 0
--------------------------------------------------------------------------------
-- * Zero-level touches
-- | @touchingDyckPaths k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ which touch the
-- zero level line @y=0@ exactly @k@ times (excluding the starting point, but including the endpoint;
-- thus, @k@ should be positive). Synonym for 'touchingDyckPathsNaive'.
touchingDyckPaths
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> [LatticePath]
touchingDyckPaths = touchingDyckPathsNaive
-- | @touchingDyckPathsNaive k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ which touch the
-- zero level line @y=0@ exactly @k@ times (excluding the starting point, but including the endpoint;
-- thus, @k@ should be positive).
--
-- > sort (touchingDyckPathsNaive k m) == sort [ p | p <- dyckPaths m , pathNumberOfZeroTouches p == k ]
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
touchingDyckPathsNaive
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> [LatticePath]
touchingDyckPathsNaive = worker where
worker !k !m
| m == 0 = if k==0 then [[]] else []
| k <= 0 = []
| m < 0 = []
| k == 1 = [ bracket p | p <- dyckPaths (m-1) ]
| otherwise = [ bracket p ++ q | l <- [1..m-1] , p <- dyckPaths (l-1) , q <- worker (k-1) (m-l) ]
where
bracket p = UpStep : p ++ [DownStep]
-- | There is a bijection from the set of non-empty Dyck paths of length @2n@ which touch the zero lines @t@ times,
-- to lattice paths from @(0,0)@ to @(2n-t-1,t-1)@ (just remove all the down-steps just before touching
-- the zero line, and also the very first up-step). This gives us a counting formula.
countTouchingDyckPaths
:: Int -- ^ @k@ = number of zero-touches
-> Int -- ^ @m@ = half-length
-> Integer
countTouchingDyckPaths t n
| t==0 && n==0 = 1
| otherwise = countLatticePaths (2*n-t-1,t-1)
--------------------------------------------------------------------------------
-- * Dyck paths with given number of peaks
-- | @peakingDyckPaths k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ with exactly @k@ peaks.
--
-- Synonym for 'peakingDyckPathsNaive'
--
peakingDyckPaths
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> [LatticePath]
peakingDyckPaths = peakingDyckPathsNaive
-- | @peakingDyckPathsNaive k m@ lists all Dyck paths from @(0,0)@ to @(2m,0)@ with exactly @k@ peaks.
--
-- > sort (peakingDyckPathsNaive k m) = sort [ p | p <- dyckPaths m , pathNumberOfPeaks p == k ]
--
-- Naive recursive algorithm, resulting order is pretty ad-hoc.
--
peakingDyckPathsNaive
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> [LatticePath]
peakingDyckPathsNaive = worker where
worker !k !m
| m == 0 = if k==0 then [[]] else []
| k <= 0 = []
| m < 0 = []
| k == 1 = [ singlePeak m ]
| otherwise = as ++ bs ++ cs
where
as = [ bracket p | p <- worker k (m-1) ]
bs = [ smallHill ++ q | q <- worker (k-1) (m-1) ]
cs = [ bracket p ++ q | l <- [2..m-1] , a <- [1..k-1] , p <- worker a (l-1) , q <- worker (k-a) (m-l) ]
smallHill = [ UpStep , DownStep ]
singlePeak !m = replicate m UpStep ++ replicate m DownStep
bracket p = UpStep : p ++ [DownStep]
-- | Dyck paths of length @2m@ with @k@ peaks are counted by the Narayana numbers @N(m,k) = \binom{m}{k} \binom{m}{k-1} / m@
countPeakingDyckPaths
:: Int -- ^ @k@ = number of peaks
-> Int -- ^ @m@ = half-length
-> Integer
countPeakingDyckPaths k m
| m == 0 = if k==0 then 1 else 0
| k <= 0 = 0
| m < 0 = 0
| k == 1 = 1
| otherwise = div (binomial m k * binomial m (k-1)) (fromIntegral m)
--------------------------------------------------------------------------------
-- * Random lattice paths
-- | A uniformly random Dyck path of length @2m@
randomDyckPath :: RandomGen g => Int -> g -> (LatticePath,g)
randomDyckPath m g0 = (nestedParensToDyckPath parens, g1) where
(parens,g1) = randomNestedParentheses m g0
--------------------------------------------------------------------------------
| chadbrewbaker/combinat | Math/Combinat/LatticePaths.hs | bsd-3-clause | 13,782 | 0 | 15 | 3,718 | 3,311 | 1,773 | 1,538 | 191 | 4 |
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Data.Gogol.DatastoreEntity (
EntityTransform(..)
, DatastoreEntity(..)
, _ToDatastoreEntity
, _FromDatastoreEntity
) where
import Control.Applicative ((<|>))
import Control.Lens (Getter, at, over, view, (&), (.~),
(?~), (^.), (^?), _1, _Just, _head)
import qualified Control.Lens.Getter as L
import Data.ByteString (ByteString)
import qualified Data.HashMap.Lazy as HM
import Data.Int (Int32, Int64)
import Data.List.NonEmpty (NonEmpty, fromList, toList)
import Data.Maybe (fromMaybe)
import Data.Text (Text, pack)
import Data.Time.Clock (UTCTime)
import GHC.Float (double2Float, float2Double)
import GHC.Generics
import Network.Google.Datastore (Entity, Key, LatLng, Value,
arrayValue, avValues, eKey,
eProperties, eProperties, entity,
entityProperties, epAddtional, kPath,
key, pathElement, peKind,
vArrayValue, vBlobValue,
vBooleanValue, vDoubleValue,
vEntityValue, vGeoPointValue,
vIntegerValue, vKeyValue,
vStringValue, vTimestampValue, value)
data EntityTransform
= EntityC Text [(Text, Value)]
| EntityP [(Text, Value)]
| V Value
| None
deriving (Eq, Show)
class DatastoreEntity a where
toEntity :: a -> EntityTransform
fromEntity :: EntityTransform -> Maybe a
default toEntity :: (Generic a, GDatastorePut (Rep a)) => a -> EntityTransform
toEntity = gEntPut . from
default fromEntity ::(Generic a, GDatastoreGet (Rep a)) => EntityTransform -> Maybe a
fromEntity x = to <$> gEntGet x
class GDatastorePut f where
gEntPut :: f a -> EntityTransform
class GDatastoreGet f where
gEntGet :: EntityTransform -> Maybe (f a)
instance GDatastorePut U1 where
gEntPut _ = None
instance GDatastoreGet U1 where
gEntGet _ = Nothing
instance (GDatastorePut a, GDatastorePut b) => GDatastorePut (a :+: b) where
gEntPut (L1 x) = gEntPut x
gEntPut (R1 x) = gEntPut x
instance (GDatastoreGet a, GDatastoreGet b) => GDatastoreGet (a :+: b) where
gEntGet e = L1 <$> gEntGet e <|> R1 <$> gEntGet e
instance (GDatastorePut a, GDatastorePut b) => GDatastorePut (a :*: b) where
gEntPut (a :*: b) = case (gEntPut a, gEntPut b) of
(EntityP xs, EntityP ys) -> EntityP $ xs ++ ys
_ -> None
instance (GDatastoreGet a, GDatastoreGet b) => GDatastoreGet (a :*: b) where
gEntGet e = (:*:) <$> gEntGet e <*> gEntGet e
instance GDatastorePut f => GDatastorePut (D1 d f) where
gEntPut = gEntPut . unM1
instance GDatastoreGet f => GDatastoreGet (D1 d f) where
gEntGet = fmap M1 . gEntGet
instance (GDatastorePut f, Constructor c) => GDatastorePut (C1 c f) where
gEntPut x
| conIsRecord x = case gEntPut $ unM1 x of
EntityP xs -> EntityC (pack (conName x)) xs
v -> v
| otherwise = gEntPut $ unM1 x
instance (GDatastoreGet f, Constructor c) => GDatastoreGet (C1 c f) where
gEntGet (EntityC _ xs) = M1 <$> gEntGet (EntityP xs)
gEntGet (EntityP xs) = M1 <$> gEntGet (EntityP xs)
gEntGet (V v) = do props <- v^.vEntityValue
ep <- props^.eProperties
gEntGet (EntityP . HM.toList $ ep^.epAddtional)
gEntGet None = Nothing
instance (GDatastorePut f, Selector c) => GDatastorePut (S1 c f) where
gEntPut s@(M1 x) = case gEntPut x of
V v -> EntityP [(pack (selName s), v)]
EntityP xs -> EntityP $ over _1 (const (pack (selName s))) <$> xs
EntityC _ xs -> EntityP [(pack (selName s), mkEntityV xs)]
_ -> None
where mkEntityV xs = value & vEntityValue ?~
(entity & eProperties ?~
entityProperties (HM.fromList xs))
instance (GDatastoreGet f, Selector c) => GDatastoreGet (S1 c f) where
gEntGet (EntityP xs) = gEntGet =<< V <$> HM.fromList xs^.at s
where s = pack $ selName (undefined :: t c f p)
gEntGet (V v) = M1 <$> gEntGet (V v)
gEntGet _ = Nothing
instance DatastoreEntity a => GDatastorePut (K1 i a) where
gEntPut = toEntity . unK1
instance DatastoreEntity a => GDatastoreGet (K1 i a) where
gEntGet = fmap K1 . fromEntity
instance DatastoreEntity Bool where
toEntity b = V $ value & vBooleanValue ?~ b
fromEntity (V v) = v^.vBooleanValue
fromEntity _ = Nothing
instance DatastoreEntity Int where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Integer where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Int32 where
toEntity i = V $ value & vIntegerValue ?~ fromIntegral i
fromEntity (V v) = fromIntegral <$> v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Int64 where
toEntity i = V $ value & vIntegerValue ?~ i
fromEntity (V v) = v^.vIntegerValue
fromEntity _ = Nothing
instance DatastoreEntity Float where
toEntity f = V $ value & vDoubleValue ?~ float2Double f
fromEntity (V v) = double2Float <$> v^.vDoubleValue
fromEntity _ = Nothing
instance DatastoreEntity Double where
toEntity d = V $ value & vDoubleValue ?~ d
fromEntity (V v) = v^.vDoubleValue
fromEntity _ = Nothing
instance DatastoreEntity ByteString where
toEntity b = V $ value & vBlobValue ?~ b
fromEntity (V v) = v^.vBlobValue
fromEntity _ = Nothing
instance DatastoreEntity Text where
toEntity x = V $ value & vStringValue ?~ x
fromEntity (V v) = v^.vStringValue
fromEntity _ = Nothing
instance DatastoreEntity Key where
toEntity k = V $ value & vKeyValue ?~ k
fromEntity (V v) = v^.vKeyValue
fromEntity _ = Nothing
instance DatastoreEntity UTCTime where
toEntity t = V $ value & vTimestampValue ?~ t
fromEntity (V v) = v^.vTimestampValue
fromEntity _ = Nothing
instance DatastoreEntity LatLng where
toEntity l = V $ value & vGeoPointValue ?~ l
fromEntity (V v) = v^.vGeoPointValue
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity (NonEmpty a) where
toEntity xs = V $ value & vArrayValue ?~ (arrayValue & avValues .~
(toList xs >>= indiv))
where indiv x = case toEntity x of
V v -> [v]
ec@(EntityC _ _) -> [value & vEntityValue .~ toEntity' ec]
_ -> []
fromEntity (V v) = do av <- v^.vArrayValue
parsed <- traverse fromEntity (V <$> av^.avValues)
return $ fromList parsed
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity [a] where
toEntity xs = V $ value & vArrayValue ?~ (arrayValue & avValues .~
(xs >>= indiv))
where indiv x = case toEntity x of
V v -> [v]
ec@(EntityC _ _) -> [value & vEntityValue .~ toEntity' ec]
_ -> []
fromEntity (V v) = do av <- v^.vArrayValue
traverse fromEntity (V <$> av^.avValues)
fromEntity _ = Nothing
instance DatastoreEntity a => DatastoreEntity (Maybe a) where
toEntity (Just x) = toEntity x
toEntity Nothing = V value
fromEntity z@(V _) = (pure <$> fromEntity z) <|> pure Nothing
fromEntity _ = Nothing
_ToDatastoreEntity :: DatastoreEntity a => Getter a (Maybe Entity)
_ToDatastoreEntity = L.to (toEntity' . toEntity)
toEntity' :: EntityTransform -> Maybe Entity
toEntity' (EntityC k params) =
pure $ entity & eKey ?~ (key & kPath .~ [pathElement & peKind ?~ k])
& eProperties ?~ entityProperties (HM.fromList params)
toEntity' _ = Nothing
_FromDatastoreEntity :: DatastoreEntity a => Getter Entity (Maybe a)
_FromDatastoreEntity = L.to (fromEntity . toTransform)
where toTransform e =
fromMaybe None $ EntityC <$> (view kPath <$> e^.eKey)^._Just._head.peKind
<*> (HM.toList <$> (e^?eProperties._Just.epAddtional))
| jamesthompson/nosql-generic | src/Data/Gogol/DatastoreEntity.hs | bsd-3-clause | 8,885 | 0 | 17 | 2,751 | 2,923 | 1,510 | 1,413 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, LambdaCase, RankNTypes #-}
module Main where
import Criterion
import Criterion.Main
import Data.RDF
import qualified Data.Text as T
-- The `bills.102.rdf` XML file is needed to run this benchmark suite
--
-- $ wget https://www.govtrack.us/data/rdf/bills.102.rdf.gz
-- $ gzip -d bills.102.rdf.gz
parseTurtle :: RDF rdf => String -> rdf
parseTurtle s =
let (Right rdf) = parseString (TurtleParser Nothing Nothing) (T.pack s)
in rdf
queryGr :: RDF rdf => (Maybe Node,Maybe Node,Maybe Node,rdf) -> [Triple]
queryGr (maybeS,maybeP,maybeO,rdf) = query rdf maybeS maybeP maybeO
selectGr :: RDF rdf => (NodeSelector,NodeSelector,NodeSelector,rdf) -> [Triple]
selectGr (selectorS,selectorP,selectorO,rdf) = select rdf selectorS selectorP selectorO
main :: IO ()
main = defaultMain [
env (readFile "bills.102.ttl") $ \ ~(ttl_countries) ->
bgroup "parse" [
bench "HashMapS" $
nf (parseTurtle :: String -> HashMapS) ttl_countries
, bench "HashMapSP" $
nf (parseTurtle :: String -> HashMapSP) ttl_countries
, bench "MapSP" $
nf (parseTurtle :: String -> MapSP) ttl_countries
, bench "TriplesList" $
nf (parseTurtle :: String -> TriplesList) ttl_countries
, bench "ListPatriciaTree" $
nf (parseTurtle :: String -> TriplesPatriciaTree) ttl_countries
]
,
env (do ttl_countries <- readFile "bills.102.ttl"
let (Right rdf1) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf2) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf3) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf4) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf5) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
return (rdf1 :: TriplesPatriciaTree,rdf2 :: TriplesList,rdf3 :: HashMapS,rdf4 :: MapSP,rdf5::HashMapSP) )
$ \ ~(triplesPatriciaTree,triplesList,hashMapS,mapSP,hashMapSP) ->
bgroup "query"
(queryBench "TriplesList" triplesList
++ queryBench "HashMapS" hashMapS
++ queryBench "MapSP" mapSP
++ queryBench "HashMapSP" hashMapSP
++ queryBench "TriplesPatriciaTree" triplesPatriciaTree)
,
env (do ttl_countries <- readFile "bills.102.ttl"
let (Right rdf1) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf2) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf3) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf4) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
let (Right rdf5) = parseString (TurtleParser Nothing Nothing) (T.pack ttl_countries)
return (rdf1 :: TriplesPatriciaTree,rdf2 :: TriplesList,rdf3 :: HashMapS,rdf4 :: MapSP,rdf5 :: HashMapSP) )
$ \ ~(triplesPatriciaTree,triplesList,hashMapS,mapSP,hashMapSP) ->
bgroup "select"
(selectBench "TriplesList" triplesList
++ selectBench "HashMapS" hashMapS
++ selectBench "MapSP" mapSP
++ selectBench "HashMapSP" hashMapSP
++ selectBench "TriplesPatriciaTree" triplesPatriciaTree)
]
selectBench :: forall rdf. RDF rdf => String -> rdf -> [Benchmark]
selectBench label gr =
[ bench (label ++ " SPO") $ nf selectGr (subjSelect,predSelect,objSelect,gr)
, bench (label ++ " SP") $ nf selectGr (subjSelect,predSelect,selectNothing,gr)
, bench (label ++ " S") $ nf selectGr (subjSelect,selectNothing,selectNothing,gr)
, bench (label ++ " PO") $ nf selectGr (selectNothing,predSelect,objSelect,gr)
, bench (label ++ " SO") $ nf selectGr (subjSelect,selectNothing,objSelect,gr)
, bench (label ++ " P") $ nf selectGr (selectNothing,predSelect,selectNothing,gr)
, bench (label ++ " O") $ nf selectGr (selectNothing,selectNothing,objSelect,gr)
]
subjSelect, predSelect, objSelect, selectNothing :: Maybe (Node -> Bool)
subjSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
predSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
objSelect = Just (\case { (UNode n) -> T.length n > 12 ; _ -> False })
selectNothing = Nothing
subjQuery, predQuery, objQuery, queryNothing :: Maybe Node
subjQuery = Just (UNode "http://www.rdfabout.com/rdf/usgov/congress/102/bills/h5694")
predQuery = Just (UNode "bill:congress")
objQuery = Just (LNode (PlainL (T.pack "102")))
queryNothing = Nothing
queryBench :: forall rdf. RDF rdf => String -> rdf -> [Benchmark]
queryBench label gr =
[ bench (label ++ " SPO") $ nf queryGr (subjQuery,predQuery,objQuery,gr)
, bench (label ++ " SP") $ nf queryGr (subjQuery,predQuery,queryNothing,gr)
, bench (label ++ " S") $ nf queryGr (subjQuery,queryNothing,queryNothing,gr)
, bench (label ++ " PO") $ nf queryGr (queryNothing,predQuery,objQuery,gr)
, bench (label ++ " SO") $ nf queryGr (subjQuery,queryNothing,objQuery,gr)
, bench (label ++ " P") $ nf queryGr (queryNothing,predQuery,queryNothing,gr)
, bench (label ++ " O") $ nf queryGr (queryNothing,queryNothing,objQuery,gr)
]
| jutaro/rdf4h | bench/MainCriterion.hs | bsd-3-clause | 5,204 | 0 | 18 | 992 | 1,805 | 951 | 854 | 84 | 2 |
-- | Context-free grammars.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Cfg.Cfg(
-- * Class
Cfg(..),
-- * Vocabulary
V(..),
Vs,
isNT,
isT,
vocabulary,
usedVocabulary,
undeclaredVocabulary,
isFullyDeclared,
-- * productions
Production(..),
productions,
lookupProductions,
-- * production maps
ProductionMap,
productionMap,
-- * Utility functions
eqCfg {- ,
compareCfg -}) where
import Data.Bifunctor
import Data.Data(Data, Typeable)
import qualified Data.Map as M
import qualified Data.Set as S
------------------------------------------------------------
-- | Represents a context-free grammar with its nonterminal and
-- terminal types.
class Cfg cfg t nt where
nonterminals :: cfg t nt -> S.Set nt
-- ^ the nonterminals of the grammar
terminals :: cfg t nt -> S.Set t
-- ^ the terminals of the grammar
productionRules :: cfg t nt -> nt -> S.Set (Vs t nt)
-- ^ the productions of the grammar
startSymbol :: cfg t nt -> nt
-- ^ the start symbol of the grammar; must be an element of
-- 'nonterminals' 'cfg'
------------------------------------------------------------
-- | Vocabulary symbols of the grammar.
data V t nt = T t -- ^ a terminal
| NT nt -- ^ a nonterminal
deriving (Eq, Ord, Show, Data, Typeable)
instance Functor (V t) where
fmap _f (T t) = T t
fmap f (NT nt) = NT $ f nt
instance Bifunctor V where
bimap f _g (T t) = T $ f t
bimap _f g (NT nt) = NT $ g nt
-- | Returns 'True' iff the vocabularly symbols is a terminal.
isT :: V t nt -> Bool
isT (T _) = True
isT _ = False
-- | Returns 'True' iff the vocabularly symbols is a nonterminal.
isNT :: V t nt -> Bool
isNT (NT _) = True
isNT _ = False
-- | Returns the vocabulary symbols of the grammar: elements of
-- 'terminals' and 'nonterminals'.
vocabulary :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> S.Set (V t nt)
vocabulary cfg = S.map T (terminals cfg)
`S.union` S.map NT (nonterminals cfg)
-- | Synonym for lists of vocabulary symbols.
type Vs t nt = [V t nt]
-- | Productions over vocabulary symbols
data Production t nt = Production {
productionHead :: nt,
productionRhs :: Vs t nt
}
deriving (Eq, Ord, Show, Data, Typeable)
instance Bifunctor Production where
bimap f g (Production nt rhs) = Production (g nt) (map (bimap f g) rhs)
-- | The productions of the grammar.
productions :: (Cfg cfg t nt) => cfg t nt -> [Production t nt]
productions cfg = do
nt <- S.toList $ nonterminals cfg
vs <- S.toList $ productionRules cfg nt
return $ Production nt vs
-- | The productions for the given nonterminal
lookupProductions :: Eq nt => nt -> [Production t nt] -> [Vs t nt]
lookupProductions nt prods = [ rhs | Production nt' rhs <- prods,
nt == nt' ]
-- | Productions of a grammar collected by their left-hand sides.
type ProductionMap t nt = M.Map nt (S.Set (Vs t nt))
-- | The 'ProductionMap' for the grammar
productionMap :: (Cfg cfg t nt, Ord nt) => cfg t nt -> ProductionMap t nt
productionMap cfg
= M.fromList [(nt, productionRules cfg nt)
| nt <- S.toList $ nonterminals cfg]
-- | Returns 'True' iff the two inhabitants of 'Cfg' are equal.
eqCfg :: forall cfg cfg' t nt
. (Cfg cfg t nt, Cfg cfg' t nt, Eq nt, Eq t)
=> cfg t nt -> cfg' t nt -> Bool
eqCfg cfg cfg' = to4Tuple cfg == to4Tuple cfg'
{------------------------------------------------------------
-- | Compares the two inhabitants of 'Cfg'.
compareCfg :: forall cfg cfg' t nt
. (Cfg cfg t nt, Cfg cfg' t nt, Ord nt, Ord t)
=> cfg t nt -> cfg' t nt -> Ordering
compareCfg cfg cfg' = compare (to4Tuple cfg) (to4Tuple cfg')
------------------------------------------------------------}
-- | Converts the 'Cfg' to a 4-tuple that inhabits both 'Eq' and 'Ord'
-- if 't' and 'nt' do.
to4Tuple :: forall cfg t nt . (Cfg cfg t nt)
=> cfg t nt -> (nt, S.Set nt, S.Set t, [Production t nt])
-- We move the start symbol first to optimize the operations
-- since it's most likely to differ.
to4Tuple cfg = (
startSymbol cfg,
nonterminals cfg,
terminals cfg,
productions cfg)
-- | Returns all vocabulary used in the productions plus the start
-- symbol.
usedVocabulary :: (Cfg cfg t nt, Ord nt, Ord t)
=> cfg t nt -> S.Set (V t nt)
usedVocabulary cfg
= S.fromList
$ NT (startSymbol cfg) :
concat [ NT nt : vs | Production nt vs <- productions cfg]
-- | Returns all vocabulary used in the productions plus the start
-- symbol but not declared in 'nonterminals' or 'terminals'.
undeclaredVocabulary :: (Cfg cfg t nt, Ord nt, Ord t)
=> cfg t nt -> S.Set (V t nt)
undeclaredVocabulary cfg = usedVocabulary cfg S.\\ vocabulary cfg
------------------------------------------------------------
-- | Returns 'True' all the vocabulary used in the grammar is
-- declared.
isFullyDeclared :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> Bool
isFullyDeclared = S.null . undeclaredVocabulary
| nedervold/context-free-grammar | src/Data/Cfg/Cfg.hs | bsd-3-clause | 5,238 | 0 | 11 | 1,313 | 1,366 | 728 | 638 | 88 | 1 |
module Passman.Engine.KeyDerivationSpec where
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Expectations.Pretty
import qualified Passman.Engine.ByteString as B
import Passman.Engine.KeyDerivation
k :: String -> Key
k = Key . B.fromString
pbkdf2Salt :: Salt
pbkdf2Salt = Salt $ B.pack [ 0x19, 0x2a, 0x3b, 0x4c, 0x5d, 0x6e, 0x7f, 0x80 ]
pbkdf2DerivesExpectedKeyAscii :: () -> Expectation
pbkdf2DerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey (PBKDF2WithHmacSHA1 1000) (Parameters 1 20) (k "passw0rd") pbkdf2Salt
expected = [ 0xac, 0x22, 0x98, 0xff, 0x9e, 0xc6, 0xd2, 0xaa
, 0x17, 0x16, 0x81, 0x29, 0x12, 0x48, 0xb5, 0x16
, 0xc7, 0x79, 0xca, 0xaa ]
pbkdf2DerivesExpectedKeyUtf8 :: () -> Expectation
pbkdf2DerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey (PBKDF2WithHmacSHA1 1000) (Parameters 1 20) (k "pässw0rð") pbkdf2Salt
expected = [ 0x3a, 0xb9, 0xe9, 0xd1, 0x97, 0xd1, 0x40, 0x50
, 0x25, 0xfd, 0xd3, 0x1e, 0x24, 0x7d, 0xd5, 0xb0
, 0xba, 0x2d, 0x7b, 0x04 ]
sha512DigestSalt :: Salt
sha512DigestSalt = Salt $ B.pack [ 0x24, 0x78, 0x5a, 0x5b, 0x75, 0x28, 0x2d, 0x54, 0x72, 0x66 ]
sha512DigestDerivesExpectedKeyAscii :: () -> Expectation
sha512DigestDerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Digest (Parameters 1 64) (k "password") sha512DigestSalt
expected = [ 0x8b, 0x0e, 0x37, 0x48, 0x61, 0xb5, 0xbc, 0xe4
, 0x79, 0xf3, 0x8d, 0x70, 0x81, 0xf5, 0xea, 0x43
, 0xcc, 0xfc, 0xa4, 0x82, 0x36, 0x01, 0x59, 0xdc
, 0xd5, 0xfe, 0x22, 0x63, 0x49, 0xff, 0x92, 0xa2
, 0x62, 0xa6, 0x9e, 0xc9, 0xac, 0x8a, 0x30, 0x3f
, 0x0b, 0xdd, 0xf6, 0xd7, 0xf1, 0xac, 0xd6, 0x2f
, 0x8a, 0x16, 0x0e, 0x11, 0xd3, 0x49, 0xbf, 0x5e
, 0xc3, 0x8b, 0x23, 0xf8, 0x25, 0x54, 0x77, 0xc3
]
sha512DigestDerivesExpectedKeyUtf8 :: () -> Expectation
sha512DigestDerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Digest (Parameters 1 64) (k "pássw0rð") sha512DigestSalt
expected = [ 0x01, 0x7b, 0x8c, 0xc2, 0xb5, 0xcb, 0xc9, 0x34
, 0x09, 0xe1, 0x64, 0x6e, 0xaa, 0x3e, 0x97, 0x93
, 0x25, 0x45, 0xdc, 0xbe, 0x6b, 0x99, 0xf0, 0x53
, 0xd5, 0xf6, 0x9b, 0x31, 0xdd, 0x6f, 0xa9, 0xa3
, 0xa6, 0xd2, 0x5e, 0xa1, 0xcf, 0x6f, 0xf2, 0x45
, 0xef, 0xfc, 0x56, 0x18, 0x79, 0xaf, 0x29, 0xb3
, 0x00, 0xc8, 0x1f, 0xa2, 0x6e, 0x65, 0xe8, 0xa7
, 0xe4, 0x6e, 0xd4, 0x5b, 0x92, 0xbf, 0xc4, 0xf3
]
sha512PasswordSalt :: Salt
sha512PasswordSalt = Salt $ B.pack [ 0x73, 0x61, 0x6c, 0x74, 0x73, 0x61, 0x6c, 0x74 ]
sha512PasswordDerivesExpectedKeyAscii :: () -> Expectation
sha512PasswordDerivesExpectedKeyAscii _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 1 64) (k "password") sha512PasswordSalt
expected = [ 0x45, 0x44, 0x33, 0xaa, 0xef, 0x02, 0xa4, 0x0c
, 0xa7, 0x21, 0x24, 0xad, 0x7a, 0xad, 0x26, 0x40
, 0x67, 0x8b, 0x0e, 0x54, 0xde, 0xa8, 0x98, 0xe7
, 0x67, 0xa4, 0x13, 0xa6, 0xda, 0x18, 0xc8, 0x5f
, 0x8a, 0xca, 0x07, 0x95, 0x96, 0xf3, 0xbe, 0x2f
, 0x95, 0xe1, 0xcf, 0xdd, 0x01, 0x42, 0x5b, 0xf5
, 0x82, 0x89, 0x31, 0x86, 0xfb, 0x2c, 0x90, 0x7c
, 0x70, 0x3c, 0xdd, 0xf0, 0xa3, 0xa2, 0x08, 0x50
]
sha512PasswordDerivesExpectedKey2Iterations :: () -> Expectation
sha512PasswordDerivesExpectedKey2Iterations _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 2 64) (k "password") sha512PasswordSalt
expected = [ 0xbe, 0x87, 0x8f, 0xa3, 0x35, 0xfb, 0xe1, 0xe7
, 0x34, 0xbb, 0xec, 0x35, 0xbc, 0x12, 0x10, 0x60
, 0x92, 0xa3, 0x1a, 0xc5, 0x37, 0xe1, 0xd1, 0xcb
, 0x33, 0xed, 0x49, 0xdb, 0x1c, 0xfa, 0x2a, 0xeb
, 0x8d, 0x4c, 0x7b, 0x59, 0x9a, 0x59, 0xcd, 0x72
, 0xdc, 0x06, 0x9b, 0x36, 0x63, 0x89, 0x70, 0x1e
, 0x41, 0x01, 0x79, 0x98, 0x2b, 0xaa, 0x6e, 0x5a
, 0x19, 0x4a, 0x95, 0x7a, 0x5b, 0x40, 0x61, 0x43
]
sha512PasswordDerivesExpectedKeyUtf8 :: () -> Expectation
sha512PasswordDerivesExpectedKeyUtf8 _ =
actual `shouldBe` Right expected
where
actual = B.unpack <$> deriveKey SHA512Password (Parameters 1 64) (k "pássw0rð") sha512PasswordSalt
expected = [ 0x47, 0xbc, 0x66, 0x00, 0xae, 0x7f, 0xbc, 0xb6
, 0x74, 0xe9, 0x99, 0x8f, 0x3a, 0x12, 0x0c, 0x02
, 0x21, 0xbd, 0x44, 0x53, 0xf1, 0xf5, 0x13, 0x0f
, 0x55, 0x42, 0x75, 0x15, 0x9d, 0xd4, 0xbe, 0xcf
, 0x65, 0xff, 0x7d, 0x0e, 0x69, 0xba, 0x3a, 0xdc
, 0x68, 0x7e, 0xc8, 0xdd, 0x30, 0xcb, 0x09, 0x74
, 0x10, 0x65, 0x32, 0x1b, 0xe1, 0xf5, 0x1b, 0xd8
, 0xba, 0xe7, 0xc5, 0xd6, 0x85, 0x33, 0xfc, 0x49
]
spec :: Spec
spec = do
describe "PBKDF2/SHA1 derivation" $ do
it "should produce the expected key from ascii password" $
pbkdf2DerivesExpectedKeyAscii ()
it "should produce the expected key from non-ascii password" $
pbkdf2DerivesExpectedKeyUtf8 ()
describe "SHA512 digest derivation" $ do
it "should produce the expected key from ascii password" $
sha512DigestDerivesExpectedKeyAscii ()
it "should produce the expected key from non-ascii password" $
sha512DigestDerivesExpectedKeyUtf8 ()
describe "SHA512 password derivation" $ do
it "should produce the expected key from ascii password" $
sha512PasswordDerivesExpectedKeyAscii ()
it "should produce the expected key from ascii password with 2 iterations" $
sha512PasswordDerivesExpectedKey2Iterations ()
it "should produce the expected key from non-ascii password" $
sha512PasswordDerivesExpectedKeyUtf8 ()
| chwthewke/passman-hs | test/Passman/Engine/KeyDerivationSpec.hs | bsd-3-clause | 6,604 | 0 | 12 | 2,022 | 1,920 | 1,162 | 758 | 106 | 1 |
module Day10 where
import Data.List
repeatLookAndSay :: Int -> String -> String
repeatLookAndSay n = (!! n) . iterate lookAndSay
lookAndSay :: String -> String
lookAndSay = (>>= say) . group
where say g = show (length g) ++ take 1 g | patrickherrmann/advent | src/Day10.hs | bsd-3-clause | 237 | 0 | 10 | 46 | 91 | 49 | 42 | 7 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | The central type in TagSoup
module Text.HTML.TagSoup.Type(
-- * Data structures and parsing
StringLike, Tag(..), Attribute, Row, Column,
-- * Position manipulation
Position(..), tagPosition, nullPosition, positionChar, positionString,
-- * Tag identification
isTagOpen, isTagClose, isTagText, isTagWarning, isTagPosition,
isTagOpenName, isTagCloseName, isTagComment,
-- * Extraction
fromTagText, fromAttrib,
maybeTagText, maybeTagWarning,
innerText,
) where
import Data.List (foldl')
import Data.Maybe (fromMaybe, mapMaybe)
import Text.StringLike
import Data.Data(Data, Typeable)
-- | An HTML attribute @id=\"name\"@ generates @(\"id\",\"name\")@
type Attribute str = (str,str)
-- | The row/line of a position, starting at 1
type Row = Int
-- | The column of a position, starting at 1
type Column = Int
--- All positions are stored as a row and a column, with (1,1) being the
--- top-left position
data Position = Position !Row !Column deriving (Show,Eq,Ord)
nullPosition :: Position
nullPosition = Position 1 1
positionString :: Position -> String -> Position
positionString = foldl' positionChar
positionChar :: Position -> Char -> Position
positionChar (Position r c) x = case x of
'\n' -> Position (r+1) 1
'\t' -> Position r (c + 8 - mod (c-1) 8)
_ -> Position r (c+1)
tagPosition :: Position -> Tag str
tagPosition (Position r c) = TagPosition r c
-- | A single HTML element. A whole document is represented by a list of @Tag@.
-- There is no requirement for 'TagOpen' and 'TagClose' to match.
data Tag str =
TagOpen str [Attribute str] -- ^ An open tag with 'Attribute's in their original order
| TagClose str -- ^ A closing tag
| TagText str -- ^ A text node, guaranteed not to be the empty string
| TagComment str -- ^ A comment
| TagWarning str -- ^ Meta: A syntax error in the input file
| TagPosition !Row !Column -- ^ Meta: The position of a parsed element
deriving (Show, Eq, Ord, Data, Typeable)
instance Functor Tag where
fmap f (TagOpen x y) = TagOpen (f x) [(f a, f b) | (a,b) <- y]
fmap f (TagClose x) = TagClose (f x)
fmap f (TagText x) = TagText (f x)
fmap f (TagComment x) = TagComment (f x)
fmap f (TagWarning x) = TagWarning (f x)
fmap f (TagPosition x y) = TagPosition x y
-- | Test if a 'Tag' is a 'TagOpen'
isTagOpen :: Tag str -> Bool
isTagOpen (TagOpen {}) = True; isTagOpen _ = False
-- | Test if a 'Tag' is a 'TagClose'
isTagClose :: Tag str -> Bool
isTagClose (TagClose {}) = True; isTagClose _ = False
-- | Test if a 'Tag' is a 'TagText'
isTagText :: Tag str -> Bool
isTagText (TagText {}) = True; isTagText _ = False
-- | Extract the string from within 'TagText', otherwise 'Nothing'
maybeTagText :: Tag str -> Maybe str
maybeTagText (TagText x) = Just x
maybeTagText _ = Nothing
-- | Extract the string from within 'TagText', crashes if not a 'TagText'
fromTagText :: Show str => Tag str -> str
fromTagText (TagText x) = x
fromTagText x = error $ "(" ++ show x ++ ") is not a TagText"
-- | Extract all text content from tags (similar to Verbatim found in HaXml)
innerText :: StringLike str => [Tag str] -> str
innerText = strConcat . mapMaybe maybeTagText
-- | Test if a 'Tag' is a 'TagWarning'
isTagWarning :: Tag str -> Bool
isTagWarning (TagWarning {}) = True; isTagWarning _ = False
-- | Extract the string from within 'TagWarning', otherwise 'Nothing'
maybeTagWarning :: Tag str -> Maybe str
maybeTagWarning (TagWarning x) = Just x
maybeTagWarning _ = Nothing
-- | Test if a 'Tag' is a 'TagPosition'
isTagPosition :: Tag str -> Bool
isTagPosition TagPosition{} = True; isTagPosition _ = False
-- | Extract an attribute, crashes if not a 'TagOpen'.
-- Returns @\"\"@ if no attribute present.
--
-- Warning: does not distinquish between missing attribute
-- and present attribute with value @\"\"@.
fromAttrib :: (Show str, Eq str, StringLike str) => str -> Tag str -> str
fromAttrib att tag = fromMaybe empty $ maybeAttrib att tag
-- | Extract an attribute, crashes if not a 'TagOpen'.
-- Returns @Nothing@ if no attribute present.
maybeAttrib :: (Show str, Eq str) => str -> Tag str -> Maybe str
maybeAttrib att (TagOpen _ atts) = lookup att atts
maybeAttrib _ x = error ("(" ++ show x ++ ") is not a TagOpen")
-- | Returns True if the 'Tag' is 'TagOpen' and matches the given name
isTagOpenName :: Eq str => str -> Tag str -> Bool
isTagOpenName name (TagOpen n _) = n == name
isTagOpenName _ _ = False
-- | Returns True if the 'Tag' is 'TagClose' and matches the given name
isTagCloseName :: Eq str => str -> Tag str -> Bool
isTagCloseName name (TagClose n) = n == name
isTagCloseName _ _ = False
-- | Test if a 'Tag' is a 'TagComment'
isTagComment :: Tag str -> Bool
isTagComment TagComment {} = True; isTagComment _ = False
| ndmitchell/tagsoup | src/Text/HTML/TagSoup/Type.hs | bsd-3-clause | 4,929 | 0 | 13 | 1,054 | 1,284 | 688 | 596 | 85 | 3 |
{-# LANGUAGE MagicHash #-}
-- |
-- Module: $HEADER$
-- Description: Splitting numbers in to digits and vice versa.
-- Copyright: (c) 2009, 2013, 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: non-portable (MagicHash, uses GHC internals)
--
-- Functions for splitting numbers in to digits and summing them back together.
module Data.Digits
(
-- * Counting Digits of a Number
numberOfDigits
, numberOfDigitsInBase
-- * Splitting Number in to Digits
, digits
, reverseDigits
, digitsInBase
, reverseDigitsInBase
, genericDigitsInBase
-- * Joining Digits to a Number
, fromDigits
, fromDigitsInBase
)
where
import GHC.Base (Int(..), (+#))
import Data.Word (Word, Word8, Word16, Word32, Word64)
-- Solely required for SPECIALIZE pragmas.
-- | Return number of digits number is consisting from in a specified base.
--
-- Zero is an exception, because this function returns zero for it and not one
-- as it might be expected. This is due to the fact, that if numbers are
-- represented as a list of digits, it's often desired to interpret zero as an
-- empty list and not list with one element that is zero.
--
-- Some properties that hold:
--
-- > forall b. Integral b > 0 =>
-- > numberOfDigitsInBase b 0 = 0
-- > numberOfDigitsInBase b n /= 0 when n /= 0
-- > numberOfDigitsInBase b (negate n) = numberOfDigits b n
numberOfDigitsInBase :: Integral a => a -> a -> Int
numberOfDigitsInBase = numberOfDigitsInBaseImpl "numberOfDigitsInBase"
-- | Implementation behind 'numberOfDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
numberOfDigitsInBaseImpl :: Integral a => String -> a -> a -> Int
numberOfDigitsInBaseImpl _ _ 0 = 0
numberOfDigitsInBaseImpl functionName base n
| base <= 0 = negativeOrZeroBaseError functionName
| otherwise = numberOfDigitsInBase# 1# $ if n < 0 then negate n else n
where
numberOfDigitsInBase# d# m = case m `quot` base of
0 -> I# d#
o -> numberOfDigitsInBase# (d# +# 1#) o
{-# INLINE numberOfDigitsInBaseImpl #-}
-- | Return number of digits in base 10. It's implemented in terms of
-- 'numberOfDigitsInBase' so all it's properties apply also here.
numberOfDigits :: Integral a => a -> Int
numberOfDigits = numberOfDigitsInBaseImpl "numberOfDigits" 10
{-# SPECIALIZE numberOfDigits :: Int -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word8 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word16 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word32 -> Int #-}
{-# SPECIALIZE numberOfDigits :: Word64 -> Int #-}
-- | Split number in to digits.
--
-- Negative nubers are negated before they are split in to digits. It's similar
-- to how 'numberOfDigitsInBase' handles it.
--
-- This function uses very generic interface so it's possible to use it for any
-- list-like data type. It also works for string/text types like @ByteString@s.
--
-- For an example, of how it can be used, we can look in to definitions of
-- 'digitsInBase' and 'reverseDigitsInBase':
--
-- > digitsInBase :: Integral a => a -> a -> [a]
-- > digitsInBase base n = genericDigitsInBase (:) (.) base n []
-- >
-- > reverseDigitsInBase :: Integral a => a -> a -> [a]
-- > reverseDigitsInBase base n = genericDigitsInBase (:) (flip (.)) base n []
genericDigitsInBase
:: Integral a
=> (a -> l -> l)
-- ^ Cons function, for @[a]@ it's @(:) :: a -> [a] -> [a]@.
-> ((l -> l) -> (l -> l) -> l -> l)
-- ^ Composition function of list transformation, most commonly it's
-- either @(.)@ or @flip (.)@. This allows to implement 'digits' and
-- 'reverseDigits' using one underlying function.
-> a
-- ^ Base in which we are operating.
-> a
-- ^ Number to be split in to digits.
-> l -> l
genericDigitsInBase = genericDigitsInBaseImpl "genericDigitsInBase"
-- | Implementation behind 'genericDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
genericDigitsInBaseImpl
:: Integral a
=> String
-> (a -> l -> l)
-> ((l -> l) -> (l -> l) -> l -> l)
-> a
-> a
-> l -> l
genericDigitsInBaseImpl _ _ _ _ 0 = id
genericDigitsInBaseImpl functionName cons o base n
| base <= 0 = negativeOrZeroBaseError functionName
| otherwise = genericDigitsInBase' $ if n < 0 then negate n else n
where
genericDigitsInBase' m
| rest == 0 = cons d
| otherwise = genericDigitsInBase' rest `o` cons d
where
(rest, d) = m `quotRem` base
{-# INLINE genericDigitsInBaseImpl #-}
-- | Split number in to list of digits in specified base.
--
-- Example:
--
-- >>> digitsInBase 10 1234567890
-- [1,2,3,4,5,6,7,8,9,0]
digitsInBase :: Integral a => a -> a -> [a]
digitsInBase = digitsInBaseImpl "digitsInBase"
{-# SPECIALIZE digitsInBase :: Int -> Int -> [Int] #-}
{-# SPECIALIZE digitsInBase :: Word -> Word -> [Word] #-}
{-# SPECIALIZE digitsInBase :: Word8 -> Word8 -> [Word8] #-}
{-# SPECIALIZE digitsInBase :: Word16 -> Word16 -> [Word16] #-}
{-# SPECIALIZE digitsInBase :: Word32 -> Word32 -> [Word32] #-}
{-# SPECIALIZE digitsInBase :: Word64 -> Word64 -> [Word64] #-}
-- | Implementation behind 'digitsInBase' that is parametrized by function name
-- which allows it to print more specific error messages.
--
-- *Should not be exported.*
digitsInBaseImpl :: Integral a => String -> a -> a -> [a]
digitsInBaseImpl functionName base n =
genericDigitsInBaseImpl functionName (:) (.) base n []
-- | Split number in to list of digits in base 10.
--
-- Example:
--
-- >>> digits 1234567890
-- [1,2,3,4,5,6,7,8,9,0]
digits :: Integral a => a -> [a]
digits = digitsInBaseImpl "digits" 10
{-# SPECIALIZE digits :: Int -> [Int] #-}
{-# SPECIALIZE digits :: Word -> [Word] #-}
{-# SPECIALIZE digits :: Word8 -> [Word8] #-}
{-# SPECIALIZE digits :: Word16 -> [Word16] #-}
{-# SPECIALIZE digits :: Word32 -> [Word32] #-}
{-# SPECIALIZE digits :: Word64 -> [Word64] #-}
-- | Split number in to list of digits in specified base, but in reverse order.
--
-- Example:
--
-- >>> reverseDigitsInBase 10 1234567890
-- [0,9,8,7,6,5,4,3,2,1]
reverseDigitsInBase :: Integral a => a -> a -> [a]
reverseDigitsInBase = reverseDigitsInBaseImpl "reverseDigitsInBase"
{-# SPECIALIZE reverseDigitsInBase :: Int -> Int -> [Int] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word -> Word -> [Word] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word8 -> Word8 -> [Word8] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word16 -> Word16 -> [Word16] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word32 -> Word32 -> [Word32] #-}
{-# SPECIALIZE reverseDigitsInBase :: Word64 -> Word64 -> [Word64] #-}
-- | Implementation behind 'reverseDigitsInBase' that is parametrized by
-- function name which allows it to print more specific error messages.
--
-- *Should not be exported.*
reverseDigitsInBaseImpl :: Integral a => String -> a -> a -> [a]
reverseDigitsInBaseImpl functionName base n =
genericDigitsInBaseImpl functionName (:) (flip (.)) base n []
-- | Split number in to list of digits in base 10, but in reverse order.
--
-- Example:
--
-- >>> reverseDigits 1234567890
-- [0,9,8,7,6,5,4,3,2,1]
reverseDigits :: Integral a => a -> [a]
reverseDigits = reverseDigitsInBaseImpl "reverseDigits" 10
{-# SPECIALIZE reverseDigits :: Int -> [Int] #-}
{-# SPECIALIZE reverseDigits :: Word -> [Word] #-}
{-# SPECIALIZE reverseDigits :: Word8 -> [Word8] #-}
{-# SPECIALIZE reverseDigits :: Word16 -> [Word16] #-}
{-# SPECIALIZE reverseDigits :: Word32 -> [Word32] #-}
{-# SPECIALIZE reverseDigits :: Word64 -> [Word64] #-}
-- | Sum list of digits in specified base.
fromDigitsInBase :: Integral a => a -> [a] -> a
fromDigitsInBase base = foldl ((+) . (base *)) 0
{-# SPECIALIZE fromDigitsInBase :: Int -> [Int] -> Int #-}
{-# SPECIALIZE fromDigitsInBase :: Word -> [Word] -> Word #-}
{-# SPECIALIZE fromDigitsInBase :: Word8 -> [Word8] -> Word8 #-}
{-# SPECIALIZE fromDigitsInBase :: Word16 -> [Word16] -> Word16 #-}
{-# SPECIALIZE fromDigitsInBase :: Word32 -> [Word32] -> Word32 #-}
{-# SPECIALIZE fromDigitsInBase :: Word64 -> [Word64] -> Word64 #-}
-- | Sum list of digits in base 10.
fromDigits :: Integral a => [a] -> a
fromDigits = fromDigitsInBase 10
{-# SPECIALIZE fromDigits :: [Int] -> Int #-}
{-# SPECIALIZE fromDigits :: [Word] -> Word #-}
{-# SPECIALIZE fromDigits :: [Word8] -> Word8 #-}
{-# SPECIALIZE fromDigits :: [Word16] -> Word16 #-}
{-# SPECIALIZE fromDigits :: [Word32] -> Word32 #-}
{-# SPECIALIZE fromDigits :: [Word64] -> Word64 #-}
-- | Throw error in case when base value doesn't make sense.
--
-- *Should not be exported.*
negativeOrZeroBaseError :: String -> a
negativeOrZeroBaseError =
error . (++ ": Negative or zero base doesn't make sense.")
{-# INLINE negativeOrZeroBaseError #-}
| trskop/hs-not-found | not-found-digits/src/Data/Digits.hs | bsd-3-clause | 8,996 | 0 | 13 | 1,741 | 1,047 | 619 | 428 | 116 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-unused-imports #-}
module Main where
import Control.Monad (unless)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Config.Parser
import Data.Config.Types (Config)
import Data.Config.Pretty (pretty)
import Data.Text (Text)
import qualified Data.Text.IO as T
import Data.Attoparsec.Text
import System.Environment (getArgs)
import System.Exit (die)
main :: IO ()
main = do
args <- getArgs
let file = case length args of
1 -> head args
_ -> error "Die a horrible death"
body <- T.readFile file
let result = parseOnly konvigParser body
let text = case result of
Right config -> pretty config
Left msg -> error msg
T.putStr text
| afcowie/konvig | tests/RoundTrip.hs | bsd-3-clause | 778 | 0 | 13 | 184 | 226 | 122 | 104 | 25 | 3 |
module Ivory.Tower.AST.Init where
data Init = Init
deriving (Eq, Show, Ord)
| GaloisInc/tower | tower/src/Ivory/Tower/AST/Init.hs | bsd-3-clause | 80 | 0 | 6 | 15 | 30 | 18 | 12 | 3 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Real.CBOR (serialise, deserialise, deserialiseNull) where
import Real.Types
import Data.Binary.Serialise.CBOR.Class
import Data.Binary.Serialise.CBOR.Encoding hiding (Tokens(..))
import Data.Binary.Serialise.CBOR.Decoding
import Data.Binary.Serialise.CBOR.Read
import Data.Binary.Serialise.CBOR.Write
import qualified Data.Binary.Get as Bin
import Data.Word
import Data.Monoid
import Control.Applicative
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Internal as BS
import qualified Data.ByteString.Builder as BS
serialise :: [GenericPackageDescription] -> BS.ByteString
--serialise :: Serialise a => a -> BS.ByteString
serialise = BS.toLazyByteString . toBuilder . encode
deserialise :: BS.ByteString -> [GenericPackageDescription]
--deserialise :: Serialise a => BS.ByteString -> a
deserialise bs = feedAll (deserialiseIncremental decode) bs
where
feedAll (Bin.Done _ _ x) _ = x
feedAll (Bin.Partial k) lbs = case lbs of
BS.Chunk bs lbs' -> feedAll (k (Just bs)) lbs'
BS.Empty -> feedAll (k Nothing) BS.empty
feedAll (Bin.Fail _ pos msg) _ =
error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
deserialiseNull :: BS.ByteString -> ()
deserialiseNull bs = feedAll (deserialiseIncremental decodeListNull) bs
where
decodeListNull = do decodeListLenIndef; go
go = do stop <- decodeBreakOr
if stop then return ()
else do !x <- decode :: Decoder GenericPackageDescription
go
feedAll (Bin.Done _ _ x) _ = x
feedAll (Bin.Partial k) lbs = case lbs of
BS.Chunk bs lbs' -> feedAll (k (Just bs)) lbs'
BS.Empty -> feedAll (k Nothing) BS.empty
feedAll (Bin.Fail _ pos msg) _ =
error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
encodeCtr0 :: Word -> Encoding
encodeCtr1 :: Serialise a => Word -> a -> Encoding
encodeCtr2 :: (Serialise a, Serialise b) => Word -> a -> b -> Encoding
encodeCtr0 n = encodeListLen 1 <> encode (n :: Word)
encodeCtr1 n a = encodeListLen 2 <> encode (n :: Word) <> encode a
encodeCtr2 n a b = encodeListLen 3 <> encode (n :: Word) <> encode a <> encode b
encodeCtr3 n a b c
= encodeListLen 4 <> encode (n :: Word) <> encode a <> encode b
<> encode c
encodeCtr4 n a b c d
= encodeListLen 5 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d
encodeCtr6 n a b c d e f
= encodeListLen 7 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d <> encode e <> encode f
encodeCtr7 n a b c d e f g
= encodeListLen 8 <> encode (n :: Word) <> encode a <> encode b
<> encode c <> encode d <> encode e <> encode f
<> encode g
{-# INLINE encodeCtr0 #-}
{-# INLINE encodeCtr1 #-}
{-# INLINE encodeCtr2 #-}
{-# INLINE encodeCtr3 #-}
{-# INLINE encodeCtr4 #-}
{-# INLINE encodeCtr6 #-}
{-# INLINE encodeCtr7 #-}
{-# INLINE decodeCtrTag #-}
{-# INLINE decodeCtrBody0 #-}
{-# INLINE decodeCtrBody1 #-}
{-# INLINE decodeCtrBody2 #-}
{-# INLINE decodeCtrBody3 #-}
decodeCtrTag = (\len tag -> (tag, len)) <$> decodeListLen <*> decodeWord
decodeCtrBody0 1 f = pure f
decodeCtrBody1 2 f = do x1 <- decode
return $! f x1
decodeCtrBody2 3 f = do x1 <- decode
x2 <- decode
return $! f x1 x2
decodeCtrBody3 4 f = do x1 <- decode
x2 <- decode
x3 <- decode
return $! f x1 x2 x3
{-# INLINE decodeSingleCtr0 #-}
{-# INLINE decodeSingleCtr1 #-}
{-# INLINE decodeSingleCtr2 #-}
{-# INLINE decodeSingleCtr3 #-}
{-# INLINE decodeSingleCtr4 #-}
{-# INLINE decodeSingleCtr6 #-}
{-# INLINE decodeSingleCtr7 #-}
decodeSingleCtr0 v f = decodeListLenOf 1 *> decodeWordOf v *> pure f
decodeSingleCtr1 v f = decodeListLenOf 2 *> decodeWordOf v *> pure f <*> decode
decodeSingleCtr2 v f = decodeListLenOf 3 *> decodeWordOf v *> pure f <*> decode <*> decode
decodeSingleCtr3 v f = decodeListLenOf 4 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode
decodeSingleCtr4 v f = decodeListLenOf 5 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode
decodeSingleCtr6 v f = decodeListLenOf 7 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
decodeSingleCtr7 v f = decodeListLenOf 8 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
instance Serialise PackageName where
encode (PackageName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 PackageName
instance Serialise Version where
encode (Version a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 Version
instance Serialise PackageId where
encode (PackageId a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 PackageId
instance Serialise VersionRange where
encode AnyVersion = encodeCtr0 1
encode (ThisVersion a) = encodeCtr1 2 a
encode (LaterVersion a) = encodeCtr1 3 a
encode (EarlierVersion a) = encodeCtr1 4 a
encode (WildcardVersion a) = encodeCtr1 5 a
encode (UnionVersionRanges a b) = encodeCtr2 6 a b
encode (IntersectVersionRanges a b) = encodeCtr2 7 a b
encode (VersionRangeParens a) = encodeCtr1 8 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l AnyVersion
2 -> decodeCtrBody1 l ThisVersion
3 -> decodeCtrBody1 l LaterVersion
4 -> decodeCtrBody1 l EarlierVersion
5 -> decodeCtrBody1 l WildcardVersion
6 -> decodeCtrBody2 l UnionVersionRanges
7 -> decodeCtrBody2 l IntersectVersionRanges
8 -> decodeCtrBody1 l VersionRangeParens
instance Serialise Dependency where
encode (Dependency a b) = encodeCtr2 1 a b
decode = decodeSingleCtr2 1 Dependency
instance Serialise CompilerFlavor where
encode GHC = encodeCtr0 1
encode NHC = encodeCtr0 2
encode YHC = encodeCtr0 3
encode Hugs = encodeCtr0 4
encode HBC = encodeCtr0 5
encode Helium = encodeCtr0 6
encode JHC = encodeCtr0 7
encode LHC = encodeCtr0 8
encode UHC = encodeCtr0 9
encode (HaskellSuite a) = encodeCtr1 10 a
encode (OtherCompiler a) = encodeCtr1 11 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l GHC
2 -> decodeCtrBody0 l NHC
3 -> decodeCtrBody0 l YHC
4 -> decodeCtrBody0 l Hugs
5 -> decodeCtrBody0 l HBC
6 -> decodeCtrBody0 l Helium
7 -> decodeCtrBody0 l JHC
8 -> decodeCtrBody0 l LHC
9 -> decodeCtrBody0 l UHC
10 -> decodeCtrBody1 l HaskellSuite
11 -> decodeCtrBody1 l OtherCompiler
instance Serialise License where
encode (GPL a) = encodeCtr1 1 a
encode (AGPL a) = encodeCtr1 2 a
encode (LGPL a) = encodeCtr1 3 a
encode BSD3 = encodeCtr0 4
encode BSD4 = encodeCtr0 5
encode MIT = encodeCtr0 6
encode (Apache a) = encodeCtr1 7 a
encode PublicDomain = encodeCtr0 8
encode AllRightsReserved = encodeCtr0 9
encode OtherLicense = encodeCtr0 10
encode (UnknownLicense a) = encodeCtr1 11 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l GPL
2 -> decodeCtrBody1 l AGPL
3 -> decodeCtrBody1 l LGPL
4 -> decodeCtrBody0 l BSD3
5 -> decodeCtrBody0 l BSD4
6 -> decodeCtrBody0 l MIT
7 -> decodeCtrBody1 l Apache
8 -> decodeCtrBody0 l PublicDomain
9 -> decodeCtrBody0 l AllRightsReserved
10 -> decodeCtrBody0 l OtherLicense
11 -> decodeCtrBody1 l UnknownLicense
instance Serialise SourceRepo where
encode (SourceRepo a b c d e f g) = encodeCtr7 1 a b c d e f g
decode = decodeSingleCtr7 1 SourceRepo
instance Serialise RepoKind where
encode RepoHead = encodeCtr0 1
encode RepoThis = encodeCtr0 2
encode (RepoKindUnknown a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l RepoHead
2 -> decodeCtrBody0 l RepoThis
3 -> decodeCtrBody1 l RepoKindUnknown
instance Serialise RepoType where
encode Darcs = encodeCtr0 1
encode Git = encodeCtr0 2
encode SVN = encodeCtr0 3
encode CVS = encodeCtr0 4
encode Mercurial = encodeCtr0 5
encode GnuArch = encodeCtr0 6
encode Bazaar = encodeCtr0 7
encode Monotone = encodeCtr0 8
encode (OtherRepoType a) = encodeCtr1 9 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Darcs
2 -> decodeCtrBody0 l Git
3 -> decodeCtrBody0 l SVN
4 -> decodeCtrBody0 l CVS
5 -> decodeCtrBody0 l Mercurial
6 -> decodeCtrBody0 l GnuArch
7 -> decodeCtrBody0 l Bazaar
8 -> decodeCtrBody0 l Monotone
9 -> decodeCtrBody1 l OtherRepoType
instance Serialise BuildType where
encode Simple = encodeCtr0 1
encode Configure = encodeCtr0 2
encode Make = encodeCtr0 3
encode Custom = encodeCtr0 4
encode (UnknownBuildType a) = encodeCtr1 5 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Simple
2 -> decodeCtrBody0 l Configure
3 -> decodeCtrBody0 l Make
4 -> decodeCtrBody0 l Custom
5 -> decodeCtrBody1 l UnknownBuildType
instance Serialise Library where
encode (Library a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 Library
instance Serialise Executable where
encode (Executable a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 Executable
instance Serialise TestSuite where
encode (TestSuite a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 TestSuite
instance Serialise TestSuiteInterface where
encode (TestSuiteExeV10 a b) = encodeCtr2 1 a b
encode (TestSuiteLibV09 a b) = encodeCtr2 2 a b
encode (TestSuiteUnsupported a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody2 l TestSuiteExeV10
2 -> decodeCtrBody2 l TestSuiteLibV09
3 -> decodeCtrBody1 l TestSuiteUnsupported
instance Serialise TestType where
encode (TestTypeExe a) = encodeCtr1 1 a
encode (TestTypeLib a) = encodeCtr1 2 a
encode (TestTypeUnknown a b) = encodeCtr2 3 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l TestTypeExe
2 -> decodeCtrBody1 l TestTypeLib
3 -> decodeCtrBody2 l TestTypeUnknown
instance Serialise Benchmark where
encode (Benchmark a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 Benchmark
instance Serialise BenchmarkInterface where
encode (BenchmarkExeV10 a b) = encodeCtr2 1 a b
encode (BenchmarkUnsupported a) = encodeCtr1 2 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody2 l BenchmarkExeV10
2 -> decodeCtrBody1 l BenchmarkUnsupported
instance Serialise BenchmarkType where
encode (BenchmarkTypeExe a) = encodeCtr1 1 a
encode (BenchmarkTypeUnknown a b) = encodeCtr2 2 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l BenchmarkTypeExe
2 -> decodeCtrBody2 l BenchmarkTypeUnknown
instance Serialise ModuleName where
encode (ModuleName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 ModuleName
instance Serialise BuildInfo where
encode (BuildInfo a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20
a21 a22 a23 a24 a25) =
encodeListLen 26 <> encode (1 :: Word) <>
encode a1 <> encode a2 <> encode a3 <> encode a4 <> encode a5 <>
encode a6 <> encode a7 <> encode a8 <> encode a9 <> encode a10 <>
encode a11 <> encode a12 <> encode a13 <> encode a14 <> encode a15 <>
encode a16 <> encode a17 <> encode a18 <> encode a19 <> encode a20 <>
encode a21 <> encode a22 <> encode a23 <> encode a24 <> encode a25
decode = decodeListLenOf 26 *> decodeWordOf 1 *>
pure BuildInfo <*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
instance Serialise Language where
encode Haskell98 = encodeCtr0 1
encode Haskell2010 = encodeCtr0 2
encode (UnknownLanguage a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Haskell98
2 -> decodeCtrBody0 l Haskell2010
3 -> decodeCtrBody1 l UnknownLanguage
instance Serialise Extension where
encode (EnableExtension a) = encodeCtr1 1 a
encode (DisableExtension a) = encodeCtr1 2 a
encode (UnknownExtension a) = encodeCtr1 3 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l EnableExtension
2 -> decodeCtrBody1 l DisableExtension
3 -> decodeCtrBody1 l UnknownExtension
instance Serialise KnownExtension where
encode ke = encodeCtr1 1 (fromEnum ke)
decode = decodeSingleCtr1 1 toEnum
instance Serialise PackageDescription where
encode (PackageDescription a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a11 a12 a13 a14 a15 a16 a17 a18 a19 a20
a21 a22 a23 a24 a25 a26 a27 a28) =
encodeListLen 29 <> encode (1 :: Word) <>
encode a1 <> encode a2 <> encode a3 <> encode a4 <> encode a5 <>
encode a6 <> encode a7 <> encode a8 <> encode a9 <> encode a10 <>
encode a11 <> encode a12 <> encode a13 <> encode a14 <> encode a15 <>
encode a16 <> encode a17 <> encode a18 <> encode a19 <> encode a20 <>
encode a21 <> encode a22 <> encode a23 <> encode a24 <> encode a25 <>
encode a26 <> encode a27 <> encode a28
decode = decodeListLenOf 29 *> decodeWordOf 1 *>
pure PackageDescription
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode <*> decode <*> decode
<*> decode <*> decode <*> decode
instance Serialise OS where
encode Linux = encodeCtr0 1
encode Windows = encodeCtr0 2
encode OSX = encodeCtr0 3
encode FreeBSD = encodeCtr0 4
encode OpenBSD = encodeCtr0 5
encode NetBSD = encodeCtr0 6
encode Solaris = encodeCtr0 7
encode AIX = encodeCtr0 8
encode HPUX = encodeCtr0 9
encode IRIX = encodeCtr0 10
encode HaLVM = encodeCtr0 11
encode IOS = encodeCtr0 12
encode (OtherOS a) = encodeCtr1 13 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l Linux
2 -> decodeCtrBody0 l Windows
3 -> decodeCtrBody0 l OSX
4 -> decodeCtrBody0 l FreeBSD
5 -> decodeCtrBody0 l OpenBSD
6 -> decodeCtrBody0 l NetBSD
7 -> decodeCtrBody0 l Solaris
8 -> decodeCtrBody0 l AIX
9 -> decodeCtrBody0 l HPUX
10 -> decodeCtrBody0 l IRIX
11 -> decodeCtrBody0 l HaLVM
12 -> decodeCtrBody0 l IOS
13 -> decodeCtrBody1 l OtherOS
instance Serialise Arch where
encode I386 = encodeCtr0 1
encode X86_64 = encodeCtr0 2
encode PPC = encodeCtr0 3
encode PPC64 = encodeCtr0 4
encode Sparc = encodeCtr0 5
encode Arm = encodeCtr0 6
encode Mips = encodeCtr0 7
encode SH = encodeCtr0 8
encode IA64 = encodeCtr0 9
encode S390 = encodeCtr0 10
encode Alpha = encodeCtr0 11
encode Hppa = encodeCtr0 12
encode Rs6000 = encodeCtr0 13
encode M68k = encodeCtr0 14
encode (OtherArch a) = encodeCtr1 15 a
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody0 l I386
2 -> decodeCtrBody0 l X86_64
3 -> decodeCtrBody0 l PPC
4 -> decodeCtrBody0 l PPC64
5 -> decodeCtrBody0 l Sparc
6 -> decodeCtrBody0 l Arm
7 -> decodeCtrBody0 l Mips
8 -> decodeCtrBody0 l SH
9 -> decodeCtrBody0 l IA64
10 -> decodeCtrBody0 l S390
11 -> decodeCtrBody0 l Alpha
12 -> decodeCtrBody0 l Hppa
13 -> decodeCtrBody0 l Rs6000
14 -> decodeCtrBody0 l M68k
15 -> decodeCtrBody1 l OtherArch
instance Serialise Flag where
encode (MkFlag a b c d) = encodeCtr4 1 a b c d
decode = decodeSingleCtr4 1 MkFlag
instance Serialise FlagName where
encode (FlagName a) = encodeCtr1 1 a
decode = decodeSingleCtr1 1 FlagName
instance (Serialise a, Serialise b, Serialise c) => Serialise (CondTree a b c) where
encode (CondNode a b c) = encodeCtr3 1 a b c
decode = decodeSingleCtr3 1 CondNode
{-# SPECIALIZE instance Serialise c => Serialise (CondTree ConfVar [Dependency] c) #-}
instance Serialise ConfVar where
encode (OS a) = encodeCtr1 1 a
encode (Arch a) = encodeCtr1 2 a
encode (Flag a) = encodeCtr1 3 a
encode (Impl a b) = encodeCtr2 4 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l OS
2 -> decodeCtrBody1 l Arch
3 -> decodeCtrBody1 l Flag
4 -> decodeCtrBody2 l Impl
instance Serialise a => Serialise (Condition a) where
encode (Var a) = encodeCtr1 1 a
encode (Lit a) = encodeCtr1 2 a
encode (CNot a) = encodeCtr1 3 a
encode (COr a b) = encodeCtr2 4 a b
encode (CAnd a b) = encodeCtr2 5 a b
decode = do
(t,l) <- decodeCtrTag
case t of
1 -> decodeCtrBody1 l Var
2 -> decodeCtrBody1 l Lit
3 -> decodeCtrBody1 l CNot
4 -> decodeCtrBody2 l COr
5 -> decodeCtrBody2 l CAnd
{-# SPECIALIZE instance Serialise (Condition ConfVar) #-}
instance Serialise GenericPackageDescription where
encode (GenericPackageDescription a b c d e f) = encodeCtr6 1 a b c d e f
decode = decodeSingleCtr6 1 GenericPackageDescription
| thoughtpolice/binary-serialise-cbor | bench/Real/CBOR.hs | bsd-3-clause | 18,142 | 0 | 36 | 4,973 | 6,071 | 2,919 | 3,152 | 441 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Site
( app
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad.Trans
import Data.ByteString (ByteString)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time.Clock
import Snap.Snaplet
import Snap.Snaplet.Auth hiding (session)
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Fay
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Util.FileServe
------------------------------------------------------------------------------
import Application
import Application.SharedTypes
currentTimeAjax :: AppHandler Time
currentTimeAjax = Time . T.pack . show <$> liftIO getCurrentTime
-- TODO this can be handled automatically by heistServe
registerForm :: AppHandler ()
registerForm = render "register-form"
loginForm :: AppHandler ()
loginForm = render "login-form"
register :: UserRegister -> Handler App (AuthManager App) UserRegisterResponse
register (UserRegister u p pc)
| T.length u < 4 || T.length p < 4 || p /= pc = return Fail
| otherwise = do
exists <- usernameExists u
if exists then return Fail else (createUser u (T.encodeUtf8 p) >> return OK)
login :: UserLogin -> Handler App (AuthManager App) UserLoginResponse
login (UserLogin u p r) =
either (return BadLogin) (return LoggedIn) <$>
loginByUsername u (ClearText $ T.encodeUtf8 p) r
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [
("/ajax/current-time", toFayax currentTimeAjax)
, ("/ajax/login", with auth $ fayax login)
, ("/ajax/login-form", loginForm)
, ("/ajax/logout", with auth logout)
, ("/ajax/register", with auth $ fayax register)
, ("/ajax/register-form", registerForm)
, ("/fay", with fay fayServe)
, ("/static", serveDirectory "static")
]
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
s <- nestSnaplet "sess" session $
initCookieSessionManager "site_key.txt" "sess" (Just 3600)
h <- nestSnaplet "" heist $ heistInit "templates"
f <- nestSnaplet "fay" fay $ initFay
a <- nestSnaplet "auth" auth $ initJsonFileAuthManager defAuthSettings session "users.json"
addAuthSplices h auth
addRoutes routes
return $ App h f s a
| faylang/snaplet-fay | example/src/Site.hs | bsd-3-clause | 2,933 | 0 | 14 | 742 | 680 | 360 | 320 | 54 | 2 |
{-# Language ScopedTypeVariables #-}
module Symmetry.IL.Deadlock where
import Data.List
import Data.Maybe
import Data.Generics
import Symmetry.IL.AST as AST
import Symmetry.IL.Model
import Symmetry.IL.ConfigInfo
{-
A configuration is deadlocked if
1. All processes are either blocked (i.e. at a receive) or stopped (PC = -1)
2. At least one process is not done
-}
-- Collect blocked states
-- /\_p (blocked-or-done p) /\ (\/_p' blocked p')
blockedLocs :: (Data a, Identable a)
=> Config a -> [(Pid, [(Type, Int)])]
blockedLocs Config{ cProcs = ps }
= blockedLocsOfProc <$> ps
procAtRecv :: ILModel e => ConfigInfo Int -> Pid -> [(Type, Int)] -> e
procAtRecv ci p tis
= ors [ readPC ci (extAbs p) (extAbs p) `eq` int i | (_, i) <- tis ]
procDone :: ILModel e => ConfigInfo a -> Pid -> e
procDone ci p@(PAbs _ _)
= readPC ci (univAbs p) (univAbs p) `eq` int (-1)
procDone ci p
= readPC ci (univAbs p) (univAbs p) `eq` int (-1)
extAbs :: Pid -> Pid
extAbs p@(PAbs _ s) = PAbs (GV (pidIdx p ++ "_1")) s
extAbs p = p
univAbs :: Pid -> Pid
univAbs p@(PAbs _ s) = PAbs (GV (pidIdx p ++ "_0")) s
univAbs p = p
procBlocked :: (Identable a, ILModel e) => ConfigInfo a -> Pid -> [(Type, Int)] -> e
procBlocked ci p@(PAbs _ s) tis
= ors [ ands [ readPC ci p' p' `eq` int i, blocked t ] | (t, i) <- tis ]
where
blocked t = lte (readPtrW ci p' p' t) (readPtrR ci p' p' t)
p' = extAbs p
procBlocked ci p tis
= ors [ ands [readPC ci p p `eq` (int i), blocked t] | (t, i) <- tis ]
where
blocked t = lte (readPtrW ci p p t) (readPtrR ci p p t)
-- (P, Q) P ==> Q where P = \forall procs p, p blocked or done
-- Q = \forall procs p, p done
deadlockFree :: (Data a, Identable a, ILModel e) => ConfigInfo a -> (e, e)
deadlockFree ci@CInfo { config = Config { cProcs = ps } }
= (assumption, consequence)
-- , ands (procDone ci . fst <$> ps) -- ors (badConfig <$> locs)
-- ]
where
badConfig (p, tis) = procBlocked ci p tis
assumption = ands [ blockedOrDone q | q <- fst <$> ps ]
consequence = ands [ procDone ci q | q <- fst <$> ps ]
locs = blockedLocs (config ci)
lkup p = fromJust $ lookup p locs
blockedOrDone p@(PConc _) = ors [ procDone ci p, procBlocked ci p (lkup p) ]
-- blockedOrDone p@(PAbs _ _) = ands [ ors [ procDone ci p, procBlocked ci p (lkup p) ]
-- , eq (counters p (lkup p))
-- (decr (readRoleBound ci p))
-- ]
blockedOrDone p@(PAbs _ _) = ands [ eq (readEnabled ci p) emptySet
, ors [ ands [ procDone ci p, eq (readPCK p (-1)) (readRoleBound ci p) ]
, procBlocked ci p (lkup p)
]
]
-- (readPCK p (-1) `add` blockedCounter ci p p) `lt` (readRoleBound ci p)
counters p = (foldl' add (readPCK p (-1)) . (readPCK p . snd <$>))
readPCK p i = readMap (readPCCounter ci p) (int i)
| gokhankici/symmetry | checker/src/Symmetry/IL/Deadlock.hs | mit | 3,198 | 0 | 17 | 1,070 | 1,117 | 589 | 528 | 48 | 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.KMS.Decrypt
-- 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.
-- | Decrypts ciphertext. Ciphertext is plaintext that has been previously
-- encrypted by using any of the following functions: 'GenerateDataKey' 'GenerateDataKeyWithoutPlaintext' 'Encrypt'
--
-- Note that if a caller has been granted access permissions to all keys
-- (through, for example, IAM user policies that grant 'Decrypt' permission on all
-- resources), then ciphertext encrypted by using keys in other accounts where
-- the key grants access to the caller can be decrypted. To remedy this, we
-- recommend that you do not grant 'Decrypt' access in an IAM user policy. Instead
-- grant 'Decrypt' access only in key policies. If you must grant 'Decrypt' access
-- in an IAM user policy, you should scope the resource to specific keys or to
-- specific trusted accounts.
--
-- <http://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html>
module Network.AWS.KMS.Decrypt
(
-- * Request
Decrypt
-- ** Request constructor
, decrypt
-- ** Request lenses
, dCiphertextBlob
, dEncryptionContext
, dGrantTokens
-- * Response
, DecryptResponse
-- ** Response constructor
, decryptResponse
-- ** Response lenses
, drKeyId
, drPlaintext
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.KMS.Types
import qualified GHC.Exts
data Decrypt = Decrypt
{ _dCiphertextBlob :: Base64
, _dEncryptionContext :: Map Text Text
, _dGrantTokens :: List "GrantTokens" Text
} deriving (Eq, Read, Show)
-- | 'Decrypt' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dCiphertextBlob' @::@ 'Base64'
--
-- * 'dEncryptionContext' @::@ 'HashMap' 'Text' 'Text'
--
-- * 'dGrantTokens' @::@ ['Text']
--
decrypt :: Base64 -- ^ 'dCiphertextBlob'
-> Decrypt
decrypt p1 = Decrypt
{ _dCiphertextBlob = p1
, _dEncryptionContext = mempty
, _dGrantTokens = mempty
}
-- | Ciphertext to be decrypted. The blob includes metadata.
dCiphertextBlob :: Lens' Decrypt Base64
dCiphertextBlob = lens _dCiphertextBlob (\s a -> s { _dCiphertextBlob = a })
-- | The encryption context. If this was specified in the 'Encrypt' function, it
-- must be specified here or the decryption operation will fail. For more
-- information, see <http://docs.aws.amazon.com/kms/latest/developerguide/encrypt-context.html Encryption Context>.
dEncryptionContext :: Lens' Decrypt (HashMap Text Text)
dEncryptionContext =
lens _dEncryptionContext (\s a -> s { _dEncryptionContext = a })
. _Map
-- | For more information, see <http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token Grant Tokens>.
dGrantTokens :: Lens' Decrypt [Text]
dGrantTokens = lens _dGrantTokens (\s a -> s { _dGrantTokens = a }) . _List
data DecryptResponse = DecryptResponse
{ _drKeyId :: Maybe Text
, _drPlaintext :: Maybe Base64
} deriving (Eq, Read, Show)
-- | 'DecryptResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drKeyId' @::@ 'Maybe' 'Text'
--
-- * 'drPlaintext' @::@ 'Maybe' 'Base64'
--
decryptResponse :: DecryptResponse
decryptResponse = DecryptResponse
{ _drKeyId = Nothing
, _drPlaintext = Nothing
}
-- | ARN of the key used to perform the decryption. This value is returned if no
-- errors are encountered during the operation.
drKeyId :: Lens' DecryptResponse (Maybe Text)
drKeyId = lens _drKeyId (\s a -> s { _drKeyId = a })
-- | Decrypted plaintext data. This value may not be returned if the customer
-- master key is not available or if you didn't have permission to use it.
drPlaintext :: Lens' DecryptResponse (Maybe Base64)
drPlaintext = lens _drPlaintext (\s a -> s { _drPlaintext = a })
instance ToPath Decrypt where
toPath = const "/"
instance ToQuery Decrypt where
toQuery = const mempty
instance ToHeaders Decrypt
instance ToJSON Decrypt where
toJSON Decrypt{..} = object
[ "CiphertextBlob" .= _dCiphertextBlob
, "EncryptionContext" .= _dEncryptionContext
, "GrantTokens" .= _dGrantTokens
]
instance AWSRequest Decrypt where
type Sv Decrypt = KMS
type Rs Decrypt = DecryptResponse
request = post "Decrypt"
response = jsonResponse
instance FromJSON DecryptResponse where
parseJSON = withObject "DecryptResponse" $ \o -> DecryptResponse
<$> o .:? "KeyId"
<*> o .:? "Plaintext"
| romanb/amazonka | amazonka-kms/gen/Network/AWS/KMS/Decrypt.hs | mpl-2.0 | 5,498 | 0 | 11 | 1,183 | 683 | 413 | 270 | 76 | 1 |
{-# LANGUAGE LambdaCase #-}
foo = f >>= \case
Just h -> loadTestDB (h ++ "/.testdb")
Nothing -> fmap S.Right initTestDB
{-| Is the alarm set - i.e. will it go off at some point in the future even if `setAlarm` is not called? -}
isAlarmSetSTM :: AlarmClock -> STM Bool
isAlarmSetSTM AlarmClock{..} = readTVar acNewSetting
>>= \case { AlarmNotSet -> readTVar acIsSet; _ -> return True }
| mpickering/ghc-exactprint | tests/examples/ghc710/LambdaCase.hs | bsd-3-clause | 405 | 2 | 11 | 88 | 104 | 52 | 52 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}
-- |
-- Module : Scion.Configure
-- Copyright : (c) Thomas Schilling 2008
-- License : BSD-style
--
-- Maintainer : nominolo@googlemail.com
-- Stability : experimental
-- Portability : portable
--
module Scion.Configure where
import Scion.Types
import Scion.Session
import GHC hiding ( load )
import DynFlags ( dopt_set )
import GHC.Paths ( ghc, ghc_pkg )
import Exception
import Data.Typeable
import Outputable
import System.Directory
import System.FilePath
import System.IO ( openTempFile, hPutStr, hClose )
import Control.Monad
import Control.Exception ( IOException )
import Distribution.Simple.Configure
import Distribution.PackageDescription.Parse ( readPackageDescription )
import qualified Distribution.Verbosity as V ( normal, deafening )
import Distribution.Simple.Program ( defaultProgramConfiguration, userSpecifyPaths )
import Distribution.Simple.Setup ( defaultConfigFlags, ConfigFlags(..), Flag(..) )
------------------------------------------------------------------------------
-- | Open or configure a Cabal project using the Cabal library.
--
-- Tries to open an existing Cabal project or configures it if opening
-- failed.
--
-- Throws:
--
-- * 'CannotOpenCabalProject' if configuration failed.
--
openOrConfigureCabalProject ::
FilePath -- ^ The project root. (Where the .cabal file resides)
-> FilePath -- ^ dist dir, i.e., directory where to put generated files.
-> [String] -- ^ command line arguments to "configure".
-> ScionM ()
openOrConfigureCabalProject root_dir dist_dir extra_args =
openCabalProject root_dir dist_dir
`gcatch` (\(_ :: CannotOpenCabalProject) ->
configureCabalProject root_dir dist_dir extra_args)
-- | Configure a Cabal project using the Cabal library.
--
-- This is roughly equivalent to calling "./Setup configure" on the command
-- line. The difference is that this makes sure to use the same version of
-- Cabal and the GHC API that Scion was built against. This is important to
-- avoid compatibility problems.
--
-- If configuration succeeded, sets it as the current project.
--
-- TODO: Figure out a way to report more helpful error messages.
--
-- Throws:
--
-- * 'CannotOpenCabalProject' if configuration failed.
--
configureCabalProject ::
FilePath -- ^ The project root. (Where the .cabal file resides)
-> FilePath -- ^ dist dir, i.e., directory where to put generated files.
-> [String] -- ^ command line arguments to "configure". [XXX: currently
-- ignored!]
-> ScionM ()
configureCabalProject root_dir dist_dir _extra_args = do
cabal_file <- find_cabal_file
gen_pkg_descr <- liftIO $ readPackageDescription V.normal cabal_file
let prog_conf =
userSpecifyPaths [("ghc", ghc), ("ghc-pkg", ghc_pkg)]
defaultProgramConfiguration
let config_flags =
(defaultConfigFlags prog_conf)
{ configDistPref = Flag dist_dir
, configVerbosity = Flag V.deafening
, configUserInstall = Flag True
-- TODO: parse flags properly
}
setWorkingDir root_dir
ghandle (\(_ :: IOError) ->
liftIO $ throwIO $
CannotOpenCabalProject "Failed to configure") $ do
lbi <- liftIO $ configure (Left gen_pkg_descr, (Nothing, [])) config_flags
liftIO $ writePersistBuildConfig dist_dir lbi
openCabalProject root_dir dist_dir
where
find_cabal_file = do
fs <- liftIO $ getDirectoryContents root_dir
case [ f | f <- fs, takeExtension f == ".cabal" ] of
[f] -> return $ root_dir </> f
[] -> liftIO $ throwIO $ CannotOpenCabalProject "no .cabal file"
_ -> liftIO $ throwIO $ CannotOpenCabalProject "Too many .cabal files"
-- | Something went wrong during "cabal configure".
--
-- TODO: Add more detail.
data ConfigException = ConfigException deriving (Show, Typeable)
instance Exception ConfigException
-- | Do the equivalent of @runghc Setup.hs <args>@ using the GHC API.
--
-- Instead of "runghc", this function uses the GHC API so that the correct
-- version of GHC and package database is used.
--
-- TODO: Return exception or error message in failure case.
cabalSetupWithArgs ::
FilePath -- ^ Path to .cabal file. TODO: ATM, we only need the
-- directory
-> [String] -- ^ Command line arguments.
-> ScionM Bool
cabalSetupWithArgs cabal_file args =
ghandle (\(_ :: ConfigException) -> return False) $ do
ensureCabalFileExists
let dir = dropFileName cabal_file
(setup, delete_when_done) <- findSetup dir
liftIO $ putStrLn $ "Using setup file: " ++ setup
_mainfun <- compileMain setup
when (delete_when_done) $
liftIO (removeFile setup)
return True
where
ensureCabalFileExists = do
ok <- liftIO (doesFileExist cabal_file)
unless ok (liftIO $ throwIO ConfigException)
findSetup dir = do
let candidates = map ((dir </> "Setup.")++) ["lhs", "hs"]
existing <- mapM (liftIO . doesFileExist) candidates
case [ f | (f,ok) <- zip candidates existing, ok ] of
f:_ -> return (f, False)
[] -> liftIO $ do
ghandle (\(_ :: IOException) -> throwIO $ ConfigException) $ do
tmp_dir <- getTemporaryDirectory
(fp, hdl) <- openTempFile tmp_dir "Setup.hs"
hPutStr hdl (unlines default_cabal_setup)
hClose hdl
return (fp, True)
default_cabal_setup =
["#!/usr/bin/env runhaskell",
"import Distribution.Simple",
"main :: IO ()",
"main = defaultMain"]
compileMain file = do
resetSessionState
dflags <- getSessionDynFlags
setSessionDynFlags $
dopt_set (dflags { hscTarget = HscInterpreted
, ghcLink = LinkInMemory
})
Opt_ForceRecomp -- to avoid picking up Setup.{hi,o}
t <- guessTarget file Nothing
liftIO $ putStrLn $ "target: " ++ (showSDoc $ ppr t)
setTargets [t]
load LoadAllTargets
m <- findModule (mkModuleName "Main") Nothing
env <- findModule (mkModuleName "System.Environment") Nothing
GHC.setContext [m] [env]
mainfun <- runStmt ("System.Environment.withArgs "
++ show args
++ "(main)")
RunToCompletion
return mainfun
| CristhianMotoche/scion | lib/Scion/Configure.hs | bsd-3-clause | 6,450 | 0 | 20 | 1,567 | 1,246 | 666 | 580 | 113 | 3 |
module Data.Binary.Strict.BitUtil
( topNBits
, bottomNBits
, leftShift
, rightShift
, leftTruncateBits
, rightTruncateBits
) where
import Data.Word (Word8)
import qualified Data.ByteString as B
import Data.Bits (shiftL, shiftR, (.|.), (.&.))
-- | This is used for masking the last byte of a ByteString so that extra
-- bits don't leak in
topNBits :: Int -> Word8
topNBits 0 = 0
topNBits 1 = 0x80
topNBits 2 = 0xc0
topNBits 3 = 0xe0
topNBits 4 = 0xf0
topNBits 5 = 0xf8
topNBits 6 = 0xfc
topNBits 7 = 0xfe
topNBits 8 = 0xff
topNBits x = error ("topNBits undefined for " ++ show x)
-- | Return a Word8 with the bottom n bits set
bottomNBits :: Int -> Word8
bottomNBits 0 = 0
bottomNBits 1 = 0x01
bottomNBits 2 = 0x03
bottomNBits 3 = 0x07
bottomNBits 4 = 0x0f
bottomNBits 5 = 0x1f
bottomNBits 6 = 0x3f
bottomNBits 7 = 0x7f
bottomNBits 8 = 0xff
bottomNBits x = error ("bottomNBits undefined for " ++ show x)
-- | Shift the whole ByteString some number of bits left where 0 <= @n@ < 8
leftShift :: Int -> B.ByteString -> B.ByteString
leftShift 0 = id
leftShift n = snd . B.mapAccumR f 0 where
f acc b = (b `shiftR` (8 - n), (b `shiftL` n) .|. acc)
-- | Shift the whole ByteString some number of bits right where 0 <= @n@ < 8
rightShift :: Int -> B.ByteString -> B.ByteString
rightShift 0 = id
rightShift n = snd . B.mapAccumL f 0 where
f acc b = (b .&. (bottomNBits n), (b `shiftR` n) .|. (acc `shiftL` (8 - n)))
-- | Truncate a ByteString to a given number of bits (counting from the left)
-- by masking out extra bits in the last byte
leftTruncateBits :: Int -> B.ByteString -> B.ByteString
leftTruncateBits n = B.take ((n + 7) `div` 8) . snd . B.mapAccumL f n where
f bits w | bits >= 8 = (bits - 8, w)
| bits == 0 = (0, 0)
| otherwise = (0, w .&. topNBits bits)
-- | Truncate a ByteString to a given number of bits (counting from the right)
-- by masking out extra bits in the first byte
rightTruncateBits :: Int -> B.ByteString -> B.ByteString
rightTruncateBits n bs = B.drop (B.length bs - ((n + 7) `div` 8)) $ snd $ B.mapAccumR f n bs where
f bits w | bits >= 8 = (bits - 8, w)
| bits == 0 = (0, 0)
| otherwise = (0, w .&. bottomNBits bits)
| KrzyStar/binary-low-level | src/Data/Binary/Strict/BitUtil.hs | bsd-3-clause | 2,221 | 0 | 13 | 505 | 755 | 407 | 348 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Server.Protocol where
import Data.Aeson
import Language.Parser.Errors ( ImprovizCodeError(..) )
data ImprovizResponse
= ImprovizOKResponse String
| ImprovizErrorResponse String
| ImprovizCodeErrorResponse [ImprovizCodeError]
deriving (Show, Eq)
instance ToJSON ImprovizResponse where
toJSON (ImprovizOKResponse payload) =
object [("status", "ok"), "payload" .= payload]
toJSON (ImprovizErrorResponse payload) =
object [("status", "server-error"), "payload" .= payload]
toJSON (ImprovizCodeErrorResponse payload) =
object [("status", "error"), "payload" .= payload]
| rumblesan/improviz | src/Server/Protocol.hs | bsd-3-clause | 666 | 0 | 8 | 121 | 167 | 95 | 72 | 16 | 0 |
{-# LANGUAGE CPP, LambdaCase, BangPatterns, MagicHash, TupleSections, ScopedTypeVariables #-}
{-# OPTIONS_GHC -w #-} -- Suppress warnings for unimplemented methods
------------- WARNING ---------------------
--
-- This program is utterly bogus. It takes a value of type ()
-- and unsafe-coerces it to a function, and applies it.
-- This is caught by an ASSERT with a debug compiler.
--
-- See Trac #9208 for discussion
--
--------------------------------------------
{- | Evaluate Template Haskell splices on node.js,
using pipes to communicate with GHCJS
-}
-- module GHCJS.Prim.TH.Eval
module Eval (
runTHServer
) where
import Control.Applicative
import Control.Monad
#if __GLASGOW_HASKELL__ >= 800
import Control.Monad.Fail (MonadFail(fail))
#endif
import Data.Binary
import Data.Binary.Get
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import GHC.Prim
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
import Unsafe.Coerce
data THResultType = THExp | THPat | THType | THDec
data Message
-- | GHCJS compiler to node.js requests
= RunTH THResultType ByteString TH.Loc
-- | node.js to GHCJS compiler responses
| RunTH' THResultType ByteString [TH.Dec] -- ^ serialized AST and additional toplevel declarations
instance Binary THResultType where
put _ = return ()
get = return undefined
instance Binary Message where
put _ = return ()
get = return undefined
data QState = QState
data GHCJSQ a = GHCJSQ { runGHCJSQ :: QState -> IO (a, QState) }
instance Functor GHCJSQ where
fmap f (GHCJSQ s) = GHCJSQ $ fmap (\(x,s') -> (f x,s')) . s
instance Applicative GHCJSQ where
f <*> a = GHCJSQ $ \s ->
do (f',s') <- runGHCJSQ f s
(a', s'') <- runGHCJSQ a s'
return (f' a', s'')
pure x = GHCJSQ (\s -> return (x,s))
instance Monad GHCJSQ where
(>>=) m f = GHCJSQ $ \s ->
do (m', s') <- runGHCJSQ m s
(a, s'') <- runGHCJSQ (f m') s'
return (a, s'')
return = pure
#if __GLASGOW_HASKELL__ >= 800
instance MonadFail GHCJSQ where
fail = undefined
#endif
instance TH.Quasi GHCJSQ where qRunIO m = GHCJSQ $ \s -> fmap (,s) m
-- | the Template Haskell server
runTHServer :: IO ()
runTHServer = void $ runGHCJSQ server QState
where
server = TH.qRunIO awaitMessage >>= \case
RunTH t code loc -> do
a <- TH.qRunIO $ loadTHData code
runTH t a loc
_ -> TH.qRunIO (putStrLn "warning: ignoring unexpected message type")
runTH :: THResultType -> Any -> TH.Loc -> GHCJSQ ()
runTH rt obj loc = do
res <- case rt of
THExp -> runTHCode (unsafeCoerce obj :: TH.Q TH.Exp)
THPat -> runTHCode (unsafeCoerce obj :: TH.Q TH.Pat)
THType -> runTHCode (unsafeCoerce obj :: TH.Q TH.Type)
THDec -> runTHCode (unsafeCoerce obj :: TH.Q [TH.Dec])
TH.qRunIO (sendResult $ RunTH' rt res [])
runTHCode :: {- Binary a => -} TH.Q a -> GHCJSQ ByteString
runTHCode c = TH.runQ c >> return B.empty
loadTHData :: ByteString -> IO Any
loadTHData bs = return (unsafeCoerce ())
awaitMessage :: IO Message
awaitMessage = fmap (runGet get) (return BL.empty)
-- | send result back
sendResult :: Message -> IO ()
sendResult msg = return ()
| mcschroeder/ghc | testsuite/tests/stranal/should_compile/T9208.hs | bsd-3-clause | 3,414 | 0 | 15 | 821 | 967 | 517 | 450 | 65 | 4 |
module HList
( H
, repH
, absH
) where
type H a = [a] -> [a]
-- {-# INLINE repH #-}
repH :: [a] -> H a
repH xs = (xs ++)
-- {-# INLINE absH #-}
absH :: H a -> [a]
absH f = f []
-- -- Should be in a "List" module
-- {-# RULES "++ []" forall xs . xs ++ [] = xs #-}
-- {-# RULES "++ strict" (++) undefined = undefined #-}
-- -- The "Algebra" for repH
-- {-# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #-}
-- {-# RULES "repH []" repH [] = id #-}
-- {-# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs #-}
| ku-fpg/hermit | examples/reverse/HList.hs | bsd-2-clause | 633 | 0 | 6 | 228 | 96 | 59 | 37 | 9 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{- |
Copyright : Copyright (C) 2006-2018 Bjorn Buckwalter
License : BSD3
Maintainer : bjorn@buckwalter.se
Stability : Stable
Portability: GHC only
This module provides types and functions for manipulating unit names.
Please note that the details of the name representation may be less stable than the other APIs
provided by this package, as new features using them are still being developed.
-}
module Numeric.Units.Dimensional.UnitNames
(
-- * Data Types
UnitName, NameAtom, Prefix, PrefixName, Metricality(..),
-- * Construction of Unit Names
atom, applyPrefix, (*), (/), (^), product, reduce, grouped,
-- * Standard Names
baseUnitName, siPrefixes, nOne,
-- * Inspecting Prefixes
prefixName, scaleFactor,
-- * Convenience Type Synonyms for Unit Name Transformations
UnitNameTransformer, UnitNameTransformer2,
-- * Forgetting Unwanted Phantom Types
weaken, strengthen, relax,
name_en, abbreviation_en, asAtomic
)
where
import Numeric.Units.Dimensional.UnitNames.Internal
import Numeric.Units.Dimensional.Variants
import Prelude hiding ((*), (/), (^), product)
| bjornbm/dimensional | src/Numeric/Units/Dimensional/UnitNames.hs | bsd-3-clause | 1,146 | 4 | 5 | 193 | 145 | 105 | 40 | 13 | 0 |
{-# LANGUAGE Rank2Types #-}
module Main where
-- order of imports analogous to cabal build-depends
-- base
import System.Environment(getArgs)
import Data.IORef
import Control.Monad ((=<<))
-- gtk
import Graphics.UI.Gtk hiding (get)
-- hint
import Language.Haskell.Interpreter hiding ((:=),set,get)
-- astview-utils
import Language.Hareview.Language
-- local
import Language.Hareview.GUIActions (actionEmptyGUI,actionLoadHeadless)
import Language.Hareview.GUIData
import Language.Hareview.Registry (loadLanguages)
import Language.Hareview.GUI (buildAststate)
-- --------------------------------------------------------
-- * main ()
-- --------------------------------------------------------
-- | loads LanguageRegistration, inits GTK-GUI, checks for a
-- CLI-argument (one file to parse) and finally starts the GTK-GUI
main :: IO ()
main = do
let os = Options "Monospace" 9
ref <- buildAststate os =<< loadLanguages
args <- getArgs
case length args of
0 -> actionEmptyGUI ref
1 -> actionLoadHeadless L (head args) ref
2 -> do
actionLoadHeadless L (head args) ref
actionLoadHeadless R (last args) ref
_ -> error "Zero, one or two parameter expected"
gui <- getGui ref
-- show UI
widgetShowAll $ window gui
mainGUI
| RefactoringTools/HaRe | hareview/src/Main.hs | bsd-3-clause | 1,281 | 0 | 14 | 220 | 282 | 156 | 126 | 27 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : RefacUnfoldAsPatterns
-- Copyright : (c) Christopher Brown 2007
--
-- Maintainer : cmb21@kent.ac.uk
-- Stability : provisional
-- Portability : portable
--
-- This module contains a transformation for HaRe.
-- unfold all references to an AS pattern in a function.
--
-----------------------------------------------------------------------------
module RefacUnfoldAsPatterns where
import System.IO.Unsafe
import PrettyPrint
import RefacTypeSyn
import RefacLocUtils
import Data.Char
import GHC.Unicode
import AbstractIO
import Data.Maybe
import Data.List
import RefacUtils
data Patt = Match HsMatchP | MyAlt HsAltP | MyDo HsStmtP | MyListComp HsExpP
deriving (Show)
data Expp = MyExp HsExpP | MyStmt (HsStmt HsExpP HsPatP [HsDeclP]) | MyGuard (SrcLoc, HsExpP, HsExpP) | DefaultExp
deriving (Show)
refacUnfoldAsPatterns args
= do let
fileName = args!!0
beginRow = read (args!!1)::Int
beginCol = read (args!!2)::Int
endRow = read (args!!3)::Int
endCol = read (args!!4)::Int
AbstractIO.putStrLn "refacUnfoldAsPatterns"
-- Parse the input file.
modInfo@(inscps, exps, mod, tokList) <- parseSourceFile fileName
let (pat, term) = findPattern tokList (beginRow, beginCol) (endRow, endCol) mod
case pat of
Pat (HsPId (HsVar defaultPNT))
-> do
-- writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
-- Allow the highlighting of a particular expression
-- rather than a pattern. (For Some).
let exp = locToExp (beginRow, beginCol) (endRow, endCol) tokList mod
let (pat, term) = patDefinesExp exp mod
patsInTerm <- getPats term
let patsPNT = hsPNTs pat
let patsPNT2 = hsPNTs patsInTerm
when (patsPNT `myElem` patsPNT2) $ error "There are conflicts in the binding analysis! Please do a renaming"
((_,m), (newToks, (newMod, _))) <- applyRefac (changeExpression True exp pat)
(Just (inscps, exps, mod, tokList)) fileName
when (newMod == mod)
$ AbstractIO.putStrLn
( "Warning: the expression:\n" ++ ((render.ppi) exp) ++ "\nis not associated with a pattern!" )
writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
AbstractIO.putStrLn "Completed.\n"
_ -> do
-- Allow the highlighting of a particular as-pattern
-- t@p
-- this should substitute all t for p in scope.
-- derive the patterns defined in the term (the RHS of the selected pattern)
patsInTerm <- getPats term
let patsPNT = hsPNTs pat
let patsPNT2 = hsPNTs patsInTerm
when (patsPNT `myElem` patsPNT2) $ error "There are conflicts in the binding analysis! Please do a renaming"
exp <- getExpAssociatedPat pat mod
let patWOParen = convertPat pat
((_,m), (newToks, newMod)) <- doRefac True changeExpression exp patWOParen inscps exps mod tokList fileName
writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
AbstractIO.putStrLn "Completed.\n"
myElem :: [PNT] -> [PNT] -> Bool
myElem [] list = False
myElem (p:pnts) list
| p `elem` list = error ("Please rename: " ++ ((render.ppi) p) ++ " as it conflicts with patterns of the same name.")
| otherwise = myElem pnts list
-- = or ((p `elem` list) : [myElem pnts list])
getPats :: (MonadPlus m) => Expp -> m [HsPatP]
getPats (MyExp e)
= hsPats e
getPats (MyStmt (HsGenerator _ p _ rest))
= do pats <- hsPats p
result <- getPats (MyStmt rest)
return (pats ++ result)
getPats (MyStmt (HsQualifier e rest))
= getPats (MyStmt rest)
getPats (MyStmt (HsLetStmt ds rest))
= do
pats <- hsPats ds
result <- getPats (MyStmt rest)
return (pats ++ result)
getPats (MyStmt (HsLast e))
= return []
getPats (MyGuard (_, e1, e2))
= hsPats e2 -- modify this? lets in e2?
getPats _ = error "Pattern is not associated with an as-pattern. Check Pattern is highlight correctly!"
hsPats :: (MonadPlus m, Term t) => t -> m [HsPatP]
hsPats t = applyTU (full_tdTU (constTU [] `adhocTU` inPat)) t
where
inPat (p::HsPatP) = return [p]
convertPat :: HsPatP -> HsPatP
convertPat (Pat (HsPParen p)) = p
convertPat p = p
doRefac predPat f [] p inscps exps mod tokList fileName =
return ((fileName, True), (tokList, mod))
doRefac predPat f (exp:_) p inscps exps mod tokList fileName
= do
((_,m), (newToks, (newMod, newPat))) <- applyRefac (f predPat exp p) (Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles True [((fileName, m), (newToks, newMod))]
modInfo@(inscps', exps', mod', tokList') <- parseSourceFile fileName
newExps <- getExpAssociatedPat p mod'
-- error $ show newExps
if length newExps == 1
then do
rest <- doRefac False f newExps newPat inscps' exps' mod' tokList' fileName
return rest
else do
let (_, es) = splitAt 1 newExps
rest <- doRefac False f es newPat inscps' exps' mod' tokList' fileName
return rest
getExpAssociatedPat :: (Term t, MonadPlus m) => HsPatP -> t -> m [HsExpP]
getExpAssociatedPat (Pat (HsPParen p)) t = getExpAssociatedPat p t
getExpAssociatedPat pat@(Pat (HsPAsPat p1 p)) t
= applyTU (full_tdTU (constTU [] `adhocTU` inPnt)) t
where
inPnt e@(Exp (HsId (HsVar p2)))
| definesPNT p1 p2 = return [e]
inPnt _ = return []
-- changeExpression [] pat (a,b,t) = return t
changeExpression predPat exp pat (a, b,t)
= do
names <- addName exp t
(newExp, newPat) <- checkPats names pat exp
newT <- update exp newExp t
-- liftIO (AbstractIO.putStrLn $ show (exp,newExp))
if predPat == True
then do
newT2 <- update pat newPat newT
return (newT2, newPat)
else do
return (newT, newPat)
addName e mod = do
names <- hsVisibleNames e mod
return names
checkPats :: (MonadPlus m, Monad m) => [String] -> HsPatP -> HsExpP -> m (HsExpP, HsPatP)
checkPats names (Pat (HsPParen p)) e
= do
(a,b) <- checkPats names p e
return (a, Pat (HsPParen b))
checkPats names (pat@(Pat (HsPAsPat i p))) e
= do
-- names <- addName e t
let (newExp1, newPat) = rewritePats names 1 p
newExp2 <- rewriteExp i newExp1 e
return ((Exp (HsParen newExp2)), (Pat (HsPAsPat i newPat)))
-- rewrite exp checks to see whether the given expression occurs within
-- the second exp. If it does, the expression is replaced with the name of the 'as'
-- pattern.
-- rewriteExp :: String -> HsExpP -> HsExpP -> HsExpP
rewriteExp name e1 e2
= applyTP (full_tdTP (idTP `adhocTP` (inExp e1))) e2
where
-- inExp :: HsExpP -> HsExpP -> HsExpP
inExp (Exp (HsParen e1)::HsExpP) (e2@(Exp (HsId (HsVar pnt@(PNT pname ty loc))))::HsExpP)
= do
if (rmLocs pnt) == (rmLocs name)
then do
return e1
else do
return e2
inExp (e1::HsExpP) (e2@(Exp (HsId (HsVar pnt@(PNT pname ty loc))))::HsExpP)
| findPNT pnt pname = return e1
| otherwise = return e2
inExp e1 e2 = return e2
allDefined e t
= applyTU (full_tdTU (constTU [] `adhocTU` inPNT)) e
where
inPNT (p@(PNT pname ty _)::PNT)
= return [findPN pname t]
rewritePats :: [ String ] -> Int -> HsPatP -> (HsExpP, HsPatP)
rewritePats names index (pat1@(Pat (HsPRec x y)))
= (Exp (HsRecConstr loc0 x (map sortField y)), pat1)
where
sortField :: HsFieldI a HsPatP -> HsFieldI a HsExpP
sortField (HsField i e) = (HsField i es)
where
(es, ps) = rewritePats names index e
rewritePats _ _ (pat1@(Pat (HsPLit x y)))
= (Exp (HsLit x y), pat1)
rewritePats names index (pat1@(Pat (HsPAsPat i p1)))
= (Exp (HsAsPat i es), (Pat (HsPAsPat i ps)))
where
(es, ps) = rewritePats names index p1
rewritePats names index (pat1@(Pat (HsPIrrPat p1)))
= (Exp (HsIrrPat es), Pat (HsPIrrPat ps))
where
(es, ps) = rewritePats names index p1
rewritePats names i (pat1@(Pat (HsPWildCard)))
= (nameToExp (mkNewName "a" names i), nameToPat (mkNewName "a" names i))
rewritePats names i (pat1@(Pat (HsPApp i1 p1)))
= (createFuncFromPat i1 es, Pat (HsPApp i1 ps))
where
es = map fst result
ps = map snd result
result = myMap (rewritePats names) i p1
rewritePats names i (pat1@(Pat (HsPList i2 p1)))
= (Exp (HsList es), Pat (HsPList i2 ps))
where
es = map fst result
ps = map snd result
result = myMap (rewritePats names) i p1
rewritePats names i (pat1@(Pat (HsPTuple i1 p1)))
= (Exp (HsTuple es), Pat (HsPTuple i1 ps))
where
es = map fst result
ps = map snd result
result = myMap (rewritePats names) i p1
rewritePats names i (pat1@(Pat (HsPInfixApp p1 x p2)))
= (Exp (HsInfixApp es
(HsCon x)
es2),
Pat (HsPInfixApp ps
x
ps2))
where
(es, ps) = rewritePats names i p1
(es2, ps2) = rewritePats names (i+42) p2
rewritePats names i (pat@(Pat (HsPParen p1)))
= (Exp (HsParen es), (Pat (HsPParen ps)))
where
(es, ps) = rewritePats names i p1
rewritePats _ _ (pat1@(Pat (HsPId (HsVar (PNT (PN (UnQual (i:is)) a) b c)))))
| isUpper i = ((Exp (HsId (HsCon (PNT (PN (UnQual (i:is)) a) b c)))), pat1)
| otherwise = ((Exp (HsId (HsVar (PNT (PN (UnQual (i:is)) a) b c)))), pat1)
rewritePats _ _ (pat1@(Pat (HsPId (HsCon (PNT (PN (UnQual (i:is)) a) b c)))))
= ((Exp (HsId (HsCon (PNT (PN (UnQual (i:is)) a) b c)))), pat1)
-- rewritePats p = error $ show p
myMap _ _ [] = []
myMap f i (x:xs) = f i x : myMap f (i+1) xs
-- strip removes whitespace and '\n' from a given string
strip :: String -> String
strip [] = []
strip (' ':xs) = strip xs
strip ('\n':xs) = strip xs
strip (x:xs) = x : strip xs
isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
--check whether the cursor points to the beginning of the datatype declaration
--taken from RefacADT.hs
checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP
checkCursor fileName row col mod
= case locToTypeDecl of
Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the definition!")
Just decl -> Right decl
where
locToTypeDecl = find (definesPNT (locToPNT fileName (row, col) mod)) (hsModDecls mod)
definesPNT pnt d@(Dec (HsPatBind loc p e ds))
= findPNT pnt d
definesPNT pnt d@(Dec (HsFunBind loc ms)) = findPNT pnt d
definesPNT pnt _ = False
findGuard [] exp = error "The expression is not defined within a guard!"
findGuard ((a ,e1, e2):gs) exp
| findEntityWithLocation exp e2 = (a,e1,e2)
| otherwise = findGuard gs exp
patDefinesExp exp t
= fromMaybe (defaultPat, DefaultExp)
(applyTU (once_tdTU (failTU `adhocTU` inMatch
`adhocTU` inCase
`adhocTU` inDo
`adhocTU` inList )) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats (HsGuard (g@(_,_,e):gs)) ds)::HsMatchP)
-- is the highlighted region selecting a pattern?
| inPat pats == Nothing = Nothing
| otherwise = do
let guard = findGuard (g:gs) exp
let pat = fromJust (inPat pats)
Just (pat, MyGuard guard)
inMatch (match@(HsMatch loc1 pnt pats (HsBody rhs) ds)::HsMatchP)
-- is the highlighted region selecting a pattern?
| inPat pats == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat pats)
Just (pat, MyExp rhs)
inCase (alt@(HsAlt s p (HsGuard (g@(_,_,e):gs)) ds)::HsAltP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let guard = findGuard (g:gs) exp
let pat = fromJust (inPat [p])
Just (pat, MyGuard guard)
inCase (alt@(HsAlt s p (HsBody rhs) ds)::HsAltP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyExp rhs)
inDo (inDo@(HsGenerator s p e rest)::HsStmtP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyStmt rest)
inDo x = Nothing
inList (inlist@(Exp (HsListComp (HsGenerator s p e rest)))::HsExpP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyStmt rest)
inList x = Nothing
inPat p
= (applyTU (once_tdTU (failTU `adhocTU` worker))) p
worker (pat@(Pat (HsPAsPat i p))::HsPatP)
| expToPNT exp == i
= Just pat
worker p = Nothing
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
{-findPattern :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (SrcLoc, PNT, FunctionPats, HsExpP, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
-}
findPattern toks beginPos endPos t
= fromMaybe (defaultPat, DefaultExp)
(applyTU (once_tdTU (failTU `adhocTU` inMatch
`adhocTU` inCase
`adhocTU` inDo
`adhocTU` inList )) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats (HsGuard (g@(_,_,e):gs)) ds)::HsMatchP)
-- is the highlighted region selecting a pattern?
| inPat pats == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat pats)
Just (pat, MyGuard g)
inMatch (match@(HsMatch loc1 pnt pats (HsBody rhs) ds)::HsMatchP)
-- is the highlighted region selecting a pattern?
| inPat pats == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat pats)
Just (pat, MyExp rhs)
inCase (alt@(HsAlt s p (HsGuard (g@(_,_,e):gs)) ds)::HsAltP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyGuard g)
inCase (alt@(HsAlt s p (HsBody rhs) ds)::HsAltP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyExp rhs)
inDo (inDo@(HsGenerator s p e rest)::HsStmtP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyStmt rest)
inDo x = Nothing
inList (inlist@(Exp (HsListComp (HsGenerator s p e rest)))::HsExpP)
| inPat [p] == Nothing = Nothing
| otherwise = do
let pat = fromJust (inPat [p])
Just (pat, MyStmt rest)
inList x = Nothing
inPat :: [HsPatP] -> Maybe HsPatP
inPat [] = Nothing
inPat (p:ps)
= if p1 /= defaultPat
then Just p1
else inPat ps
where
p1 = locToLocalPat beginPos endPos toks p
-- inPat _ = Nothing
| kmate/HaRe | old/refactorer/RefacUnfoldAsPatterns.hs | bsd-3-clause | 17,830 | 0 | 21 | 6,553 | 5,677 | 2,907 | 2,770 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Mode.IReader
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- A simple text mode; it does very little besides define a comment
-- syntax. We have it as a separate mode so users can bind the
-- commands to this mode specifically.
module Yi.Mode.IReader where
import Lens.Micro.Platform ((%~))
import Data.Char (intToDigit)
import Data.Text ()
import Yi.Buffer.Misc
import Yi.Editor (printMsg, withCurrentBuffer)
import Yi.IReader
import Yi.Keymap (YiM, topKeymapA)
import Yi.Keymap.Keys (choice, important, metaCh, (?>>!))
import Yi.Mode.Common (anyExtension, fundamentalMode)
abstract :: Mode syntax
abstract = fundamentalMode { modeApplies = anyExtension ["irtxt"]
, modeKeymap = topKeymapA %~ ikeys }
where
ikeys = important $ choice m
m = [ metaCh '`' ?>>! saveAsNewArticle
, metaCh '0' ?>>! deleteAndNextArticle
]
++ map (\x -> metaCh (intToDigit x) ?>>! saveAndNextArticle x) [1..9]
ireaderMode :: Mode syntax
ireaderMode = abstract { modeName = "interactive reading of text" }
ireadMode :: YiM ()
ireadMode = do
withCurrentBuffer $ setAnyMode $ AnyMode ireaderMode
nextArticle
printMsg "M-` new; M-0 delete; M-[1-9]: save w/higher priority"
| siddhanathan/yi | yi-ireader/src/Yi/Mode/IReader.hs | gpl-2.0 | 1,427 | 0 | 14 | 299 | 296 | 173 | 123 | 26 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Distributed.Process
hiding (Message, mask, finally, handleMessage, proxy)
import Control.Distributed.Process.Closure
import Control.Concurrent.Async
import Control.Monad.IO.Class
import Control.Monad
import Text.Printf
import Control.Concurrent
import GHC.Generics (Generic)
import Data.Binary
import Data.Typeable
import Network
import System.IO
import Control.Concurrent.STM
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Foldable as F
import Control.Exception
import ConcurrentUtils
import DistribUtils
-- ---------------------------------------------------------------------------
-- Data structures and initialisation
-- <<Client
type ClientName = String
data Client
= ClientLocal LocalClient
| ClientRemote RemoteClient
data RemoteClient = RemoteClient
{ remoteName :: ClientName
, clientHome :: ProcessId
}
data LocalClient = LocalClient
{ localName :: ClientName
, clientHandle :: Handle
, clientKicked :: TVar (Maybe String)
, clientSendChan :: TChan Message
}
clientName :: Client -> ClientName
clientName (ClientLocal c) = localName c
clientName (ClientRemote c) = remoteName c
newLocalClient :: ClientName -> Handle -> STM LocalClient
newLocalClient name handle = do
c <- newTChan
k <- newTVar Nothing
return LocalClient { localName = name
, clientHandle = handle
, clientSendChan = c
, clientKicked = k
}
-- >>
-- <<Message
data Message = Notice String
| Tell ClientName String
| Broadcast ClientName String
| Command String
deriving (Typeable, Generic)
instance Binary Message
-- >>
-- <<PMessage
data PMessage
= MsgServers [ProcessId]
| MsgSend ClientName Message
| MsgBroadcast Message
| MsgKick ClientName ClientName
| MsgNewClient ClientName ProcessId
| MsgClientDisconnected ClientName ProcessId
deriving (Typeable, Generic)
instance Binary PMessage
-- >>
-- <<Server
data Server = Server
{ clients :: TVar (Map ClientName Client)
, proxychan :: TChan (Process ())
, servers :: TVar [ProcessId]
, spid :: ProcessId
}
newServer :: [ProcessId] -> Process Server
newServer pids = do
pid <- getSelfPid
liftIO $ do
s <- newTVarIO pids
c <- newTVarIO Map.empty
o <- newTChanIO
return Server { clients = c, servers = s, proxychan = o, spid = pid }
-- >>
-- -----------------------------------------------------------------------------
-- Basic operations
-- <<sendLocal
sendLocal :: LocalClient -> Message -> STM ()
sendLocal LocalClient{..} msg = writeTChan clientSendChan msg
-- >>
-- <<sendRemote
sendRemote :: Server -> ProcessId -> PMessage -> STM ()
sendRemote Server{..} pid pmsg = writeTChan proxychan (send pid pmsg)
-- >>
-- <<sendMessage
sendMessage :: Server -> Client -> Message -> STM ()
sendMessage server (ClientLocal client) msg =
sendLocal client msg
sendMessage server (ClientRemote client) msg =
sendRemote server (clientHome client) (MsgSend (remoteName client) msg)
-- >>
-- <<sendToName
sendToName :: Server -> ClientName -> Message -> STM Bool
sendToName server@Server{..} name msg = do
clientmap <- readTVar clients
case Map.lookup name clientmap of
Nothing -> return False
Just client -> sendMessage server client msg >> return True
-- >>
-- <<sendRemoteAll
sendRemoteAll :: Server -> PMessage -> STM ()
sendRemoteAll server@Server{..} pmsg = do
pids <- readTVar servers
mapM_ (\pid -> sendRemote server pid pmsg) pids
-- >>
-- <<broadcastLocal
broadcastLocal :: Server -> Message -> STM ()
broadcastLocal server@Server{..} msg = do
clientmap <- readTVar clients
mapM_ sendIfLocal (Map.elems clientmap)
where
sendIfLocal (ClientLocal c) = sendLocal c msg
sendIfLocal (ClientRemote _) = return ()
-- >>
-- <<broadcast
broadcast :: Server -> Message -> STM ()
broadcast server@Server{..} msg = do
sendRemoteAll server (MsgBroadcast msg)
broadcastLocal server msg
-- >>
-- <<tell
tell :: Server -> LocalClient -> ClientName -> String -> IO ()
tell server@Server{..} LocalClient{..} who msg = do
ok <- atomically $ sendToName server who (Tell localName msg)
if ok
then return ()
else hPutStrLn clientHandle (who ++ " is not connected.")
-- >>
-- <<kick
kick :: Server -> ClientName -> ClientName -> STM ()
kick server@Server{..} who by = do
clientmap <- readTVar clients
case Map.lookup who clientmap of
Nothing ->
void $ sendToName server by (Notice $ who ++ " is not connected")
Just (ClientLocal victim) -> do
writeTVar (clientKicked victim) $ Just ("by " ++ by)
void $ sendToName server by (Notice $ "you kicked " ++ who)
Just (ClientRemote victim) -> do
sendRemote server (clientHome victim) (MsgKick who by)
-- >>
-- -----------------------------------------------------------------------------
-- Handle a local client
talk :: Server -> Handle -> IO ()
talk server@Server{..} handle = do
hSetNewlineMode handle universalNewlineMode
-- Swallow carriage returns sent by telnet clients
hSetBuffering handle LineBuffering
readName
where
-- <<readName
readName = do
hPutStrLn handle "What is your name?"
name <- hGetLine handle
if null name
then readName
else mask $ \restore -> do
client <- atomically $ newLocalClient name handle
ok <- atomically $ checkAddClient server (ClientLocal client)
if not ok
then restore $ do
hPrintf handle
"The name %s is in use, please choose another\n" name
readName
else do
atomically $ sendRemoteAll server (MsgNewClient name spid)
restore (runClient server client)
`finally` disconnectLocalClient server name
-- >>
checkAddClient :: Server -> Client -> STM Bool
checkAddClient server@Server{..} client = do
clientmap <- readTVar clients
let name = clientName client
if Map.member name clientmap
then return False
else do writeTVar clients (Map.insert name client clientmap)
broadcastLocal server $ Notice $ name ++ " has connected"
return True
deleteClient :: Server -> ClientName -> STM ()
deleteClient server@Server{..} name = do
modifyTVar' clients $ Map.delete name
broadcastLocal server $ Notice $ name ++ " has disconnected"
disconnectLocalClient :: Server -> ClientName -> IO ()
disconnectLocalClient server@Server{..} name = atomically $ do
deleteClient server name
sendRemoteAll server (MsgClientDisconnected name spid)
-- <<runClient
runClient :: Server -> LocalClient -> IO ()
runClient serv@Server{..} client@LocalClient{..} = do
race server receive
return ()
where
receive = forever $ do
msg <- hGetLine clientHandle
atomically $ sendLocal client (Command msg)
server = join $ atomically $ do
k <- readTVar clientKicked
case k of
Just reason -> return $
hPutStrLn clientHandle $ "You have been kicked: " ++ reason
Nothing -> do
msg <- readTChan clientSendChan
return $ do
continue <- handleMessage serv client msg
when continue $ server
-- >>
-- <<handleMessage
handleMessage :: Server -> LocalClient -> Message -> IO Bool
handleMessage server client@LocalClient{..} message =
case message of
Notice msg -> output $ "*** " ++ msg
Tell name msg -> output $ "*" ++ name ++ "*: " ++ msg
Broadcast name msg -> output $ "<" ++ name ++ ">: " ++ msg
Command msg ->
case words msg of
["/kick", who] -> do
atomically $ kick server who localName
return True
"/tell" : who : what -> do
tell server client who (unwords what)
return True
["/quit"] ->
return False
('/':_):_ -> do
hPutStrLn clientHandle $ "Unrecognised command: " ++ msg
return True
_ -> do
atomically $ broadcast server $ Broadcast localName msg
return True
where
output s = do hPutStrLn clientHandle s; return True
-- >>
-- -----------------------------------------------------------------------------
-- Main server
-- <<socketListener
socketListener :: Server -> Int -> IO ()
socketListener server port = withSocketsDo $ do
sock <- listenOn (PortNumber (fromIntegral port))
printf "Listening on port %d\n" port
forever $ do
(handle, host, port) <- accept sock
printf "Accepted connection from %s: %s\n" host (show port)
forkFinally (talk server handle)
(\_ -> hClose handle)
-- >>
-- <<proxy
proxy :: Server -> Process ()
proxy Server{..} = forever $ join $ liftIO $ atomically $ readTChan proxychan
-- >>
-- <<chatServer
chatServer :: Int -> Process ()
chatServer port = do
server <- newServer []
liftIO $ forkIO (socketListener server port) -- <1>
spawnLocal (proxy server) -- <2>
forever $ do m <- expect; handleRemoteMessage server m -- <3>
-- >>
-- <<handleRemoteMessage
handleRemoteMessage :: Server -> PMessage -> Process ()
handleRemoteMessage server@Server{..} m = liftIO $ atomically $
case m of
MsgServers pids -> writeTVar servers (filter (/= spid) pids) -- <1>
MsgSend name msg -> void $ sendToName server name msg -- <2>
MsgBroadcast msg -> broadcastLocal server msg -- <2>
MsgKick who by -> kick server who by -- <2>
MsgNewClient name pid -> do -- <3>
ok <- checkAddClient server (ClientRemote (RemoteClient name pid))
when (not ok) $
sendRemote server pid (MsgKick name "SYSTEM")
MsgClientDisconnected name pid -> do -- <4>
clientmap <- readTVar clients
case Map.lookup name clientmap of
Nothing -> return ()
Just (ClientRemote (RemoteClient _ pid')) | pid == pid' ->
deleteClient server name
Just _ ->
return ()
-- >>
remotable ['chatServer]
-- <<main
port :: Int
port = 44444
master :: [NodeId] -> Process ()
master peers = do
let run nid port = do
say $ printf "spawning on %s" (show nid)
spawn nid ($(mkClosure 'chatServer) port)
pids <- zipWithM run peers [port+1..]
mypid <- getSelfPid
let all_pids = mypid : pids
mapM_ (\pid -> send pid (MsgServers all_pids)) all_pids
chatServer port
main = distribMain master Main.__remoteTable
-- >>
| prt2121/haskell-practice | parconc/distrib-chat/chat.hs | apache-2.0 | 10,981 | 24 | 18 | 2,956 | 3,228 | 1,599 | 1,629 | 248 | 8 |
module Data.Foo where
foo :: Int
foo = undefined
fibonacci :: Int -> Integer
fibonacci n = fib 1 0 1
where
fib m x y
| n == m = y
| otherwise = fib (m+1) y (x + y)
| yuga/ghc-mod | test/data/ghc-mod-check/Data/Foo.hs | bsd-3-clause | 187 | 0 | 10 | 64 | 94 | 48 | 46 | 8 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, GADTs #-}
module FDsFromGivens where
class C a b | a -> b where
cop :: a -> b -> ()
data KCC where
KCC :: C Char Char => () -> KCC
{- Failing, as it righteously should!
g1 :: (C Char [a], C Char Bool) => a -> ()
g1 x = ()
-}
f :: C Char [a] => a -> a
f = undefined
bar (KCC _) = f
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_fail/FDsFromGivens.hs | bsd-3-clause | 385 | 0 | 9 | 104 | 102 | 56 | 46 | 9 | 1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
-- Tests the special case of
-- non-recursive, function binding,
-- with no type signature
module ShouldCompile where
f = \ (x :: forall a. a->a) -> (x True, x 'c')
g (x :: forall a. a->a) = x | wxwxwwxxx/ghc | testsuite/tests/typecheck/should_compile/tc194.hs | bsd-3-clause | 247 | 0 | 9 | 49 | 70 | 41 | 29 | 4 | 1 |
{-source: http://overtond.blogspot.sg/2008/07/pre.html-}
runTest = runFD test
test = do
x <- newVar [0..3]
y <- newVar [0..3]
((x .<. y) `mplus` (x `same` y))
x `hasValue` 2
labelling [x, y]
| calvinchengx/learnhaskell | constraints/constraint.hs | mit | 214 | 0 | 10 | 53 | 94 | 50 | 44 | 7 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE OverloadedStrings #-}
module View where
import Lucid
index :: Html () -> Html ()
index bd = head_ $ do
head_ hd
body_ bd
hd :: Html ()
hd = do
meta_ [charset_ "utf-8"]
meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1"]
title_ "Enrichment center"
link_ [rel_ "stylesheet",
type_ "text/css",
href_ "http://fonts.googleapis.com/css?family=Roboto"]
link_ [rel_ "stylesheet",
type_ "text/css",
href_ "assets/normalize.css"]
link_ [rel_ "stylesheet",
type_ "text/css",
href_ "https://storage.googleapis.com/code.getmdl.io/1.0.3/material.indigo-pink.min.css"]
script_ [src_ "https://storage.googleapis.com/code.getmdl.io/1.0.3/material.min.js"] ""
link_ [rel_ "stylesheet",
href_ "https://fonts.googleapis.com/icon?family=Material+Icons"]
link_ [rel_ "stylesheet",
type_ "text/css",
href_ "assets/generated.css"]
main' :: Html ()
main' = do
div_ [class_ "mdl-layout mdl-js-layout mdl-layout--fixed-header"] $ do
header_ [class_ "mdl-layout__header"] $
div_ [class_ "mdl-layout__header-row"] $ do
div_ [class_ "title"] "pfennig"
div_ [class_ "mdl-layout-spacer"] ""
nav_ [class_ "mdl-navigation mdl-layout--large-screen-only"] $ do
a_ [href_ "/logout"] "Logout"
main_ [class_ "mdl-layout__content"] $
h1_ "Welcome to the Aperture Enrichment Center!"
login :: Html ()
login =
div_ [class_ "center"] $
form_ [class_ "login", method_ "post", action_ "/login"] $ do
h3_ "Login"
div_ [class_ "row mdl-textfield mdl-js-textfield mdl-textfield--floating-label"] $ do
input_ [id_ "email",
class_ "mdl-textfield__input",
name_ "email",
type_ "email"]
label_ [class_ "mdl-textfield__label",
for_ "email"] "E-Mail"
div_ [class_ "row mdl-textfield mdl-js-textfield mdl-textfield--floating-label"] $ do
input_ [id_ "pass",
class_ "mdl-textfield__input",
name_ "pass",
type_ "password"]
label_ [class_ "mdl-textfield__label",
for_ "pass"] "Password"
div_ [class_ "row mdl-textfield"] $ do
label_ [for_ "remember",
class_ "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect"] $ do
input_ [id_ "remember",
type_ "checkbox",
name_ "remember",
value_ "remember",
class_ "mdl-checkbox__input"]
span_ [class_ "mdl-checkbox__label"] "Remember me"
div_ [class_ "row"] $ do
a_ [href_ "/register",
class_ "frm-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect"] "Register"
a_ [href_ "#",
class_ "frm-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect"] "Forgot password?"
div_ [class_ "row"] $
button_ [type_ "submit",
class_ "frm-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored",
value_ "submit"] "Login"
register :: Html ()
register =
div_ [class_ "center"] $
form_ [class_ "registration column", method_ "post", action_ "/register"] $ do
h3_ "Register"
div_ [class_ "mdl-textfield mdl-js-textfield mdl-textfield--floating-label"] $ do
input_ [id_ "email",
class_ "mdl-textfield__input",
name_ "email",
type_ "email",
required_ "",
autofocus_]
label_ [class_ "mdl-textfield__label",
for_ "email"] "E-Mail"
div_ [class_ "mdl-textfield mdl-js-textfield mdl-textfield--floating-label"] $ do
input_ [id_ "pass",
class_ "mdl-textfield__input",
name_ "pass",
pattern_ ".{5,128}",
required_ "",
type_ "password"]
label_ [class_ "mdl-textfield__label",
for_ "pass"] "Password"
span_ [class_"mdl-textfield__error"] "Password must contain at least five characters"
div_ [class_ "row"] $
button_ [type_ "submit",
class_ "frm-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored",
value_ "submit"] "Register"
notFound :: Html ()
notFound = div_ [] "No matching route found"
| muhbaasu/pfennig-server | src/Pfennig/View.hs | mit | 4,510 | 0 | 18 | 1,282 | 1,029 | 473 | 556 | 106 | 1 |
module Glob (namesMatching) where
import System.Directory (doesDirectoryExist, doesFileExist, getCurrentDirectory, getDirectoryContents)
import System.FilePath (dropTrailingPathSeparator, splitFileName, (</>))
import Control.Exception (handle)
import Control.Monad (forM)
import GlobRegex (matchesGlob, matchesGlobCs)
import System.Info (os)
import System.Posix.Files (fileExist)
isPattern :: String -> Bool
isPattern = any (`elem` "[*?")
namesMatching :: String -> IO[String]
namesMatching pat
| not (isPattern pat) = do
exists <- fileExist pat
return (if exists then [pat] else [])
| otherwise = do
case splitFileName pat of
("", baseName) -> do
curDir <- getCurrentDirectory
listMatches curDir baseName
(dirName, baseName) -> do
dirs <- if isPattern dirName
then namesMatching (dropTrailingPathSeparator dirName)
else return [dirName]
let listDir = if isPattern baseName
then listMatches
else listPlain
pathNames <- forM dirs $ \dir -> do
baseNames <- listDir dir baseName
return (map (dir </>) baseNames)
return (concat pathNames)
-- returns all files matching the glob pattern in a directory (Windows not cs / otherwise cs)
listMatches :: FilePath -> String -> IO [String]
listMatches dirName pat = do
dirName' <- if null dirName
then getCurrentDirectory
else return dirName
names <- getDirectoryContents dirName' -- not exceptoion handling (p. 208)
let names' = if isHidden pat
then filter isHidden names
else filter (not . isHidden) names
if os == "windows" then return (filter (`matchesGlob` pat) names')
else return (filter (`matchesGlobCs` pat) names')
isHidden :: String -> Bool
isHidden ('.':_) = True
isHidden _ = False
listPlain :: FilePath -> String -> IO [String]
listPlain dirName baseName = do
exists <- if null baseName
then doesDirectoryExist dirName
else fileExist (dirName </> baseName)
return (if exists then [baseName] else [])
-- checking for directory OR file (already imported with fileExist from System.Posix.Files)
{-doesNameExist :: FilePath -> IO Bool
doesNameExist name = do
fileExists <- doesFileExist name
if fileExists
then return True
else doesDirectoryExist name
-}
| cirquit/Personal-Repository | Haskell/RWH/Regex/Glob.hs | mit | 3,249 | 0 | 21 | 1,439 | 627 | 330 | 297 | 51 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.