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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module GitHub.Issues.Milestones where
import GitHub.Internal
milestones o r = ownerRepo o r <> "/milestones"
milestone o r i = milestones o r <> "/" <> i
--| GET /repos/:owner/:repo/milestones
listRepositoryMilestones ::
OwnerName ->
RepoName ->
Maybe MilestoneState ->
Maybe MilestoneSort ->
Maybe SortDirection ->
GitHub MilestonesData
listRepositoryMilestones = get [] $ milestones o r i
--| GET /repos/:owner/:repo/milestones/:number
getRepositoryMilestone ::
OwnerName ->
RepoName ->
Int ->
GitHub MilestoneData
getRepositoryMilestone = get [] $ milestone o r i
--| POST /repos/:owner/:repo/milestones
createMilestone ::
OwnerName ->
RepoName ->
NewMilestone ->
GitHub MilestoneData
createMilestone = post [] $ milestones o r
--| PATCH /repos/:owner/:repo/milestones/:number
updateMilestone ::
OwnerName ->
RepoName ->
Int ->
MilestonePatch ->
GitHub MilestoneData
updateMilestone = patch [] $ milestone o r i
--| DELETE /repos/:owner/:repo/milestones/:number
deleteMilestone ::
OwnerName ->
RepoName ->
Int ->
GitHub ()
deleteMilestone = delete [] $ milestone o r i
| SaneApp/github-api | src/GitHub/Issues/Milestones.hs | mit | 1,100 | 46 | 11 | 172 | 465 | 227 | 238 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Site.Person where
import BasePrelude hiding (bool, delete, insert)
import Prelude ()
import Control.Lens
import Control.Monad.Trans (lift, liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (getCurrentTime)
import Database.Persist.Sql
import Heist
import qualified Heist.Compiled as C
import qualified Heist.Compiled.LowLevel as C
import Snap (ifTop, redirect)
import Snap.Snaplet.Heist.Compiled
import Snap.Snaplet.Persistent (runPersist)
import Text.Digestive
import Text.Digestive.Heist.Compiled
import Text.Digestive.Snap
import Phb.Db
import Site.Internal
personRoutes :: PhbRoutes
personRoutes =
[("/people",ifTop . userOrIndex . render $ "people/all")
,("/people/create",ifTop . userOrIndex . render $ "people/create")
,("/people/:id/edit",ifTop . userOrIndex . render $ "people/edit")
]
data PersonInput = PersonInput
{ _personInputName :: Text
, _personInputEmail :: Text
, _personInputDepartment :: Text
, _personInputLoginName :: Maybe Text
, _personInputReceivesHeartbeat :: Bool
, _personInputLogsTime :: Bool
}
makeLenses ''PersonInput
personForm
:: Maybe (Entity Person,Maybe (Entity PersonLogin))
-> PhbForm T.Text PersonInput
personForm e = PersonInput
<$> "name" .: check nameErrMsg isNotEmpty (text name)
<*> "email" .: check emailErrMsg isNotEmpty (text email)
<*> "department" .: check departmentErrMsg isNotEmpty (text department)
<*> "loginName" .: optionalText loginName
<*> "receivesHeartbeat" .: bool receivesHeartbeat
<*> "logsTime" .: bool logsTime
where
name = e ^?_Just._1.eVal.personName
email = e ^?_Just._1.eVal.personEmail
department = e ^?_Just._1.eVal.personDepartment
receivesHeartbeat = e ^?_Just._1.eVal.personReceivesHeartbeat
logsTime = e ^?_Just._1.eVal.personLogsTime
loginName = e ^?_Just._2._Just.eVal.personLoginLogin
nameErrMsg = "Name must not be empty"
emailErrMsg = "Email must not be empty"
departmentErrMsg = "Department must not be empty"
personFormSplices
:: PhbRuntimeSplice (Maybe (Entity Person,Maybe (Entity PersonLogin)))
-> PhbSplice
personFormSplices rts = do
promise <- C.newEmptyPromise
out <- C.withSplices
C.runChildren
("personForm" ## formSplice mempty mempty)
(C.getPromise promise)
pure . C.yieldRuntime $ do
e <- rts
ct <- liftIO getCurrentTime
(v, result) <- lift $ runForm "person" $ personForm e
case result of
Just x -> do
lift (createPerson x ct (e ^?_Just._1.eKey) (e ^?_Just._2._Just.eKey))
Nothing -> C.putPromise promise v >> C.codeGen out
where
createPerson x ct pkMay plkMay = do
-- Should probably change this so that a DB error wouldn't just
-- Crash us and should put a nice error in the form.
case pkMay of
Nothing -> do
void . runPersist $ do
pk <- insert (newPerson x)
traverse (createLogin ct pk plkMay) (x^.personInputLoginName)
flashSuccess $ "Person Created"
Just pk -> do
void . runPersist $ do
replace pk (newPerson x)
case x^.personInputLoginName of
Nothing -> traverse_ delete plkMay
Just ln -> createLogin ct pk plkMay ln
flashSuccess $ "Person Updated"
redirect "/people"
createLogin _ _ (Just plk) ln = update plk [PersonLoginLogin =. ln]
createLogin ct pk _ ln = void . insert $ PersonLogin
pk
ln
Nothing
Nothing
Nothing
0
0
Nothing
Nothing
Nothing
Nothing
Nothing
ct
ct
Nothing
Nothing
""
""
newPerson (PersonInput n e d _ rh lt) = Person n e d rh lt
personRowSplice :: PhbRuntimeSplice [Entity Person] -> PhbSplice
personRowSplice = rowSplice (ts <> ss)
where
ts = mapV (C.pureSplice . C.textSplice) $ do
"name" ## (^.eVal.personName)
"email" ## (^.eVal.personEmail)
"department" ## (^.eVal.personDepartment)
"receivesHeartbeat" ## (^.eVal.personReceivesHeartbeat.to boolYN)
"logsTime" ## (^.eVal.personLogsTime.to boolYN)
"id" ## (^.eKey.to spliceKey)
ss = mempty
boolYN True = "Yes"
boolYN False = "No"
listPeopleSplices :: PhbSplice
listPeopleSplices =
C.withSplices
C.runChildren
("personRow" ## personRowSplice)
. lift $ do
runPersist $ do
selectList [] [Asc PersonName]
createPeopleplices :: PhbSplice
createPeopleplices = personFormSplices (pure Nothing)
editPeopleplices :: PhbSplice
editPeopleplices = personFormSplices . lift $ do
p <- requireEntity "person" "id"
pl <- runPersist $ selectFirst [PersonLoginPerson ==. p^.eKey] []
pure . Just $ (p,pl)
allPersonSplices :: Splices PhbSplice
allPersonSplices = do
"allPeople" ## listPeopleSplices
"createPerson" ## createPeopleplices
"editPerson" ## editPeopleplices
| benkolera/phb | hs/Site/Person.hs | mit | 5,434 | 0 | 22 | 1,583 | 1,425 | 738 | 687 | -1 | -1 |
module Corner (
Corner (..)
) where
data Corner = URF
| UFL
| ULB
| UBR
| DFR
| DLF
| DBL
| DRB
deriving (Bounded, Enum, Eq, Ord, Show)
| v64/rubik | Corner.hs | mit | 229 | 0 | 6 | 124 | 64 | 39 | 25 | 11 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import MediaType (mediaType, destination)
import Prelude hiding (FilePath)
import Turtle
main :: IO ()
main = do
homeDir <- home
sh $ do
files <- ls $ homeDir </> "Desktop"
liftIO $ moveFile files
moveFile :: FilePath -> IO ()
moveFile fpath = do
dest <- destination $ mediaType fpath
mv fpath dest
| bendycode/desktop-cleaner | src/Main.hs | mit | 379 | 0 | 12 | 81 | 131 | 67 | 64 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Vaultaire.Collector.Ceilometer.Process.Image where
import Control.Applicative
import Control.Lens
import Control.Monad.Trans
import Data.Aeson
import qualified Data.HashMap.Strict as H
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Word
import System.Log.Logger
import Ceilometer.Types
import qualified Vaultaire.Collector.Common.Types as V (Collector)
import Vaultaire.Collector.Ceilometer.Process.Common
import Vaultaire.Collector.Ceilometer.Types
processImageSizeEvent :: MonadIO m => Metric -> V.Collector o s m [(Address, SourceDict, TimeStamp, Word64)]
processImageSizeEvent = processEvent getImagePayload
parseImageStatus :: Text -> Maybe PFImageStatus
parseImageStatus "active" = Just ImageActive
parseImageStatus "saving" = Just ImageSaving
parseImageStatus "deleted" = Just ImageDeleted
parseImageStatus "queued" = Just ImageQueued
parseImageStatus "pending_delete" = Just ImagePendingDelete
parseImageStatus "killed" = Just ImageKilled
parseImageStatus _ = Nothing
parseImageVerb :: Text -> Maybe PFImageVerb
parseImageVerb "serve" = Just ImageServe
parseImageVerb "update" = Just ImageUpdate
parseImageVerb "upload" = Just ImageUpload
parseImageVerb "download" = Just ImageDownload
parseImageVerb "delete" = Just ImageDelete
parseImageVerb _ = Nothing
-- | Constructs the compound payload for image events
getImagePayload :: Metric -> IO (Maybe Word64)
getImagePayload m@Metric{..} = do
verb <- case T.splitOn "." <$> getEventType m of
Just (_:verb:_) -> case parseImageVerb verb of
Just x -> return $ Just x
Nothing -> do
alertM "Ceilometer.Process.getImagePayload" $
"Invalid verb for image event: " <> show verb
return Nothing
Just x -> do
alertM "Ceilometer.Process.getImagePayload"
$ "Invalid parse of verb for image event" <> show x
return Nothing
Nothing -> do
alertM "Ceilometer.Process.getImagePayload"
"event_type field missing from image event"
return Nothing
status <- case H.lookup "status" metricMetadata of
Just (String status) -> case parseImageStatus status of
Just x -> return $ Just x
Nothing -> do
alertM "Ceilometer.Process.getImagePayload" $
"Invalid status for image event: " <> show status
return Nothing
Just x -> do
alertM "Ceilometer.Process.getImagePayload"
$ "Invalid parse of status for image event" <> show x
return Nothing
Nothing -> do
alertM "Ceilometer.Process.getImagePayload"
"Status field missing from image event"
return Nothing
return $ do
s <- status
v <- verb
let e = Instant
p <- fromIntegral <$> metricPayload
return $ review (prCompoundEvent . pdImage) $ PDImage s v e p
| anchor/vaultaire-collector-ceilometer | lib/Vaultaire/Collector/Ceilometer/Process/Image.hs | mit | 3,371 | 0 | 18 | 1,065 | 712 | 350 | 362 | 72 | 7 |
module TestEntry (entrySpec) where
import Test.Hspec (Spec, context, describe, it, shouldBe)
import qualified Data.Expenses.Types as E
import qualified Data.Expenses.Parse.Megaparsec.Types as PE
import qualified Data.Expenses.Parse.Megaparsec.Entry as PE
entrySpec :: Spec
entrySpec =
describe "Data.Expenses.Parse.Megaparsec.Entry" $
describe "entryFromExpense" $ do
it "should use default currency if none given" $
PE.entryFromExpense
(2018, 01, 01)
"SGD"
(PE.Expense PE.Spent (E.Amount 5 Nothing False) "" Nothing)
`shouldBe`
(E.Entry (2018, 01, 01) (5, "SGD") "" Nothing)
context "should use Expense currency if given" $ do
it "default SGD, given SGD" $
PE.entryFromExpense
(2018, 01, 01)
"SGD"
(PE.Expense PE.Spent (E.Amount 5 (Just "SGD") False) "" Nothing)
`shouldBe`
(E.Entry (2018, 01, 01) (5, "SGD") "" Nothing)
it "default VND, given SGD" $
PE.entryFromExpense
(2018, 01, 01)
"VND"
(PE.Expense PE.Spent (E.Amount 5 (Just "SGD") False) "" Nothing)
`shouldBe`
(E.Entry (2018, 01, 01) (5, "SGD") "" Nothing)
it "default SGD, given VND" $
PE.entryFromExpense
(2018, 01, 01)
"SGD"
(PE.Expense PE.Spent (E.Amount 10000 (Just "VND") False) "" Nothing)
`shouldBe`
(E.Entry (2018, 01, 01) (10000, "VND") "" Nothing)
| rgoulter/expenses-csv-utils | test/TestEntry.hs | mit | 1,523 | 0 | 19 | 470 | 478 | 266 | 212 | 38 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Partials.TagList (TagList(..)) where
import Control.Monad (forM_)
import GHC.Exts (fromString)
import Internal.FileDB
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Internal.Partial
-- | Partial "TagList" displays a sequence of <div class="chip">, one for each tag.
data TagList = TagList
instance Partial_ TagList where
partialRoutes_ _ = []
partialRender_ = _partial
partialName_ _ = "taglist"
_partial :: TagList -> FileDB -> Page -> Params -> H.Html
_partial _ _ p _ = H.div ! A.class_ (fromString "taglist") $
forM_ (tags p) ((H.div ! tagClass) . H.toHtml)
tagClass :: H.Attribute
tagClass = A.class_ (fromString "chip")
| mayeranalytics/nanoPage | src/Partials/TagList.hs | mit | 878 | 0 | 11 | 234 | 227 | 130 | 97 | 19 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
-- | TAG a stack project based on snapshot versions
module Stack.Tag where
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Traversable as T
import Control.Exception as E
import Control.Monad.Reader
import Data.Either
import Data.Maybe
import Data.Text (Text)
import System.Directory
import System.Exit
import System.Process
import Control.Concurrent.Async.Pool
data StackTagOpts = StackTagOpts {
-- | Location of the stack.yaml to generate tags for
optsStackYaml :: !(Maybe FilePath)
-- | Verbose output
, optsVerbose :: !Bool
-- | Flag to ignore any cached tags and re-run the tagger
, noCache :: !Bool
} deriving Show
data Tagger = Hasktags
| HotHasktags
| OtherTagger Text
deriving Show
data TagFmt = CTags
| ETags
| Both
| OtherFmt Text
deriving Show
type TagOutput = FilePath
type SourceDir = FilePath
type PkgName = String
data TagCmd = TagCmd Tagger TagFmt TagOutput SourceDir PkgName deriving Show
newtype StackTag a = StackTag {
runStackTag :: ReaderT StackTagOpts IO a
} deriving (
Functor
, Applicative
, Monad
, MonadReader StackTagOpts
, MonadIO
)
defStackOpts :: StackTagOpts
defStackOpts = StackTagOpts Nothing False True
stackTag :: StackTagOpts -> IO ()
stackTag = runReaderT (runStackTag app)
where
app = do chkStackCompatible
chkHaskTags
chkIsStack
sources <- stkPaths
depSources <- stkDepSources
tagSources sources depSources
--------------------------------------------------------------------------
--------------------------------------------------------------------------
io :: MonadIO m => IO a -> m a
io = liftIO
p :: String -> StackTag ()
p msg = whenM (ask >>= pure . optsVerbose) $ io (putStrLn msg)
whenM :: Monad m => m Bool -> m () -> m ()
whenM predicate go = predicate >>= flip when go
-- | Run a command using the `stack' command-line tool
-- with a list of arguments
runStk :: [String] -> StackTag (ExitCode, String, String)
runStk args = io $ readProcessWithExitCode "stack" args []
chkIsStack :: StackTag ()
chkIsStack = do
StackTagOpts {optsStackYaml=stackYaml} <- ask
sYaml <- io $ doesFileExist "stack.yaml"
case stackYaml of
Nothing -> unless sYaml $ error "stack.yaml not found or specified!"
_ -> return ()
chkHaskTags :: StackTag ()
chkHaskTags = do
ht <- io $ findExecutable "hasktags"
case ht of
Just _p -> return ()
Nothing -> error "You must have hasktags installed Run 'stack install hasktags'."
--- | Check whether the current version of stack
-- is compatible by trying to run `stack list-depenencies --help`.
chkStackCompatible :: StackTag ()
chkStackCompatible = do
(exitc, _, _) <- runStk ["ls", "dependencies", "--help"]
case exitc of
ExitSuccess -> return ()
ExitFailure _e ->
p (show exitc) >> error "You need stack version 1.7.1 or higher installed and in your PATH to use stack-tag"
-- | Get a list of relavant directories from stack using
-- the @stack path@ command
stkPaths :: StackTag [(Text,[Text])]
stkPaths = do
(_,ps,_) <- runStk ["path"]
return (parsePaths ps)
where
parsePaths = map parsePath . T.lines . T.pack
parsePath ps = let (k,vs) = T.breakOn ":" ps
in (k, splitAndStrip vs)
splitAndStrip = filter (not . T.null) . map T.strip . T.splitOn ":"
-- | Get a list of dependencies using:
-- @stack --list-dependencies --test --bench --separator=-@
stkDepSources :: StackTag [String]
stkDepSources = do
(_exitc,ls,_) <- runStk [ "ls", "dependencies", "--external"
, "--include-base", "--test"
, "--bench", "--separator=-"]
return $ lines ls
--------------------------------------------------------------------------
--------------------------------------------------------------------------
tagSources :: [(Text,[Text])] -> [FilePath] -> StackTag ()
tagSources srcs depsrcs = do
let srcDir = lookup "project-root" srcs
let tagroot = T.unpack . fromMaybe "." . listToMaybe . fromMaybe [] $ srcDir
-- alternative pooled
depTagFiles <- parTag srcs depsrcs
-- map a tag command over all provided sources
thisProj <- runTagger (TagCmd Hasktags ETags "stack.tags" tagroot "project-root")
taggedSrcs <- T.traverse (io . readFile) (rights (thisProj : depTagFiles))
let errors = lefts (thisProj : depTagFiles)
unless (null errors) $ do
let pkg_errs = map (\(pkg,err) -> pkg ++ ": " ++ err) $ take 10 errors
error $ unlines $
"[tag:error] stack-tag encountered errors creating tags"
: pkg_errs
let xs = concatMap lines taggedSrcs
ys = if False then (Set.toList . Set.fromList) xs else xs
p $ "[tag:done] built & merged tags for " ++ show (length taggedSrcs) ++ " projects"
io $ writeFile "TAGS" $ unlines ys
parTag :: [(Text, [Text])] -> [FilePath] -> StackTag [Either (PkgName, String) FilePath]
parTag srcs depsrcs = do
o@StackTagOpts {noCache=nocache} <- ask
-- control the number of jobs by using capabilities Currently,
-- capabilities creates a few too many threads which saturates the
-- CPU and network connection. For now, it's manually set to 3 until
-- a better threading story is figured out.
--
-- io $ mapCapabilityPool (tagDependency nocache srcs) depsrcs
-- WAT: rewrap the transformer. It's less heavy duty than bringing in
-- monad-control or refactoring (2018-09-14)
let worker osrc = flip runReaderT o $ do
runStackTag (tagDependency nocache srcs osrc)
io $ mapPool 3 worker depsrcs
-- | Tag a single dependency
tagDependency :: Bool -> [(Text, [Text])] -> FilePath -> StackTag (Either (PkgName, String) FilePath)
tagDependency nocache stkpaths dep = do
let snapRoot
| Just (sr : _) <- lookup "snapshot-install-root" stkpaths = sr
| otherwise = error ("[tag:error] error tagging "
++ dep
++ ". "
++ "No 'snapshot-install-root' found, aborting.")
dir = T.unpack snapRoot ++ "/packages" ++ "/" ++ dep
tagFile = dir ++ "/TAGS"
-- HACK as of Aug 5 2015, `stack unpack` can only download sources
-- into the current directory. Therefore, we move the source to
-- the correct snapshot location. This could/should be fixed in
-- the stack source (especially since --haddock has similar
-- behavior). A quick solution to avoid this might be to run the
-- entire function in the target directory
_ <- io $ readProcess "rm" ["--preserve-root", "-rf", dep] []
-- error (show dep)
exists <- io $ doesDirectoryExist dir
tagged <- io $ doesFileExist tagFile
unless exists $ void $ do
io $ createDirectoryIfMissing True dir
p $ "[tag:download] " ++ dep
(ec,stout,_) <- runStk ["unpack", dep]
case ec of
ExitFailure _ -> void $ do
p $ "[tag:download] failed to download " ++ dep ++ " - " ++ stout
ExitSuccess -> void $ do
p $ "[tag:download] cp " ++ dep ++ " to snapshot source cache in " ++ dir
io $ readProcess "mv" [dep,dir] []
if tagged && nocache
then do p $ "[tag:nocache] " ++ dep
return (Right tagFile)
else do p $ "[tag:cache] " ++ dep
runTagger (TagCmd Hasktags ETags tagFile dir dep)
runTagger :: TagCmd -> StackTag (Either (PkgName, String) TagOutput)
runTagger (TagCmd t fmt to fp dep) = do
let opts = [ tagFmt fmt
, "-R" -- tags-absolute
-- made the default & removed
-- , "--ignore-close-implementation"
, "--follow-symlinks"
-- , "--cache"
, "--output"
, to
, fp
]
(ec, stout, err) <- hasktags opts
case ec of
ExitFailure _
| null err -> return $ Left (dep, stout)
| otherwise -> return $ Left (dep, err)
ExitSuccess -> return $ Right to
where
hasktags opts = io $
readProcessWithExitCode (tagExe t) opts []
`E.catch` (\(SomeException err) -> return (ExitFailure 1, displayException err, ""))
-- TODO tagExe Hasktags = "fast-tags"
tagExe :: Tagger -> String
tagExe Hasktags = "hasktags"
tagExe _ = error "Tag command not supported. Feel free to create an issue at https://github.com/creichert/stack-tag"
tagFmt :: TagFmt -> String
tagFmt ETags = "--etags"
tagFmt CTags = "--etags"
tagFmt Both = "--both"
tagFmt _ = error "Tag format not supported. Feel free to create an issue at https://github.com/creichert/stack-tag"
| creichert/stack-tag | src/Stack/Tag.hs | mit | 9,044 | 0 | 19 | 2,454 | 2,193 | 1,134 | 1,059 | 175 | 3 |
-- Informatics 1 - Functional Programming
-- Lab week tutorial part II
--
--
import Data.Char
import PicturesSVG
import Test.QuickCheck
-- Exercise 8:
pic1 :: Picture
pic1 = undefined
pic2 :: Picture
pic2 = undefined
-- Exercise 9:
-- a)
emptyRow :: Picture
emptyRow = undefined
-- b)
otherEmptyRow :: Picture
otherEmptyRow = undefined
-- c)
middleBoard :: Picture
middleBoard = undefined
-- d)
whiteRow :: Picture
whiteRow = undefined
blackRow :: Picture
blackRow = undefined
-- e)
populatedBoard :: Picture
populatedBoard = undefined
-- Functions --
twoBeside :: Picture -> Picture
twoBeside x = beside x (invert x)
-- Exercise 10:
twoAbove :: Picture -> Picture
twoAbove x = undefined
fourPictures :: Picture -> Picture
fourPictures x = undefined
| PavelClaudiuStefan/FMI | An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator1Optional/labweekchess.hs | cc0-1.0 | 806 | 0 | 7 | 176 | 232 | 112 | 120 | 25 | 1 |
module Main (main) where
-------------------------------------------------------------------------------
import Control.Concurrent.STM (TQueue, newTQueueIO)
import Control.Monad.Trans.Maybe (runMaybeT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (void, unless)
import Control.Monad.Reader (runReaderT, asks)
import Control.Monad.State.Strict (runStateT)
import Graphics.GLUtil.JuicyTextures
import qualified Graphics.UI.GLFW as G
import qualified Graphics.Rendering.OpenGL as GL
import Model
import Events
import View
import Update
import Window (withWindow)
import Objects.Cube (makeCube)
import Paths_HOpenGL
-------------------------------------------------------------------------------
runRST :: Monad m => RST r st m a -> r -> st -> m (a,st)
runRST rst r st = flip runStateT st . flip runReaderT r $ rst
runApp :: Env -> State -> IO ()
runApp env state = void $ runRST run env state
-------------------------------------------------------------------------------
main :: IO ()
main = do
let width = 1280
height = 720
eventsChan <- newTQueueIO :: IO (TQueue Event)
withWindow width height "test" $ \win -> do
setCallbacks eventsChan win
G.setCursorInputMode win G.CursorInputMode'Disabled
GL.depthFunc GL.$= Just GL.Less
GL.cullFace GL.$= Just GL.Front
(fbWidth, fbHeight) <- G.getFramebufferSize win
mcube <- runMaybeT makeCube
texturePath <- getDataFileName "texture.png"
eitherTexture <- readTexture texturePath
maybe
(return ())
(\cube -> do
either
(\_ -> putStrLn "Failed to load texture")
(\tex -> do
let env = Env
{ envEventsChan = eventsChan
, envWindow = win
}
state = State
{ stateWindowWidth = fbWidth
, stateWindowHeight = fbHeight
, cube = cube
, cubePositions = initialCubes
, texture = tex
, player = initialPlayer
}
runApp env state)
eitherTexture)
mcube
-------------------------------------------------------------------------------
run :: App
run = do
win <- asks envWindow
update
draw
liftIO $ do
G.swapBuffers win
G.pollEvents
q <- liftIO $ G.windowShouldClose win
unless q run
| sgillis/HOpenGL | src/Main.hs | gpl-2.0 | 2,755 | 0 | 25 | 991 | 624 | 331 | 293 | 64 | 1 |
-- rectangulos_girados.hs
-- Rectángulos girados.
-- José A. Alonso Jiménez <[email protected]>
-- Sevilla, 20 de Mayo de 2013
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Ejercicio. ¿Qué dibujo genera el siguiente programa?
-- ---------------------------------------------------------------------
import Graphics.Gloss
main :: IO ()
main = display (InWindow "Dibujo" (500,300) (20,20)) white dibujo
dibujo :: Picture
dibujo = pictures [rotate x (rectangleWire 200 200) | x <- [0,10..90]]
| jaalonso/I1M-Cod-Temas | src/Tema_25/rectangulos_girados.hs | gpl-2.0 | 598 | 0 | 8 | 66 | 115 | 61 | 54 | 5 | 1 |
bubblesort :: (Ord a) => [a] -> [a]
bubblesort [] = []
bubblesort [x] = [x]
bubblesort (x:y:ys) = let (z:zs) = bubblesort (y:ys) in
if x < z then x:z:zs else bubblesort (z:x:zs)
| Jecoms/cosmos | code/sorting/bubble_sort/bubblesort.hs | gpl-3.0 | 202 | 0 | 11 | 58 | 140 | 71 | 69 | 5 | 2 |
{-# LANGUAGE TypeOperators #-}
module PixelMaps (grayscale,
onlyRed, onlyGreen, onlyBlue,
negative, sepia,
onlyY, onlyCb, onlyCr,
onlyH, onlyL, onlyS,
filterHue, filterSkin, filterRedEyes,
binarize, binarize', binarizeY, binarizeY',
boundedToBounded, triple) where
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Codec.Picture
import Data.Array.Repa (U, D, Z (..), (:.)(..))
import qualified Data.Array.Repa as R
import Pixel
import qualified YCbCr as Ycbcr
import qualified HLS as Hls
-- all functions below have type signatures:
-- f :: RGB8 -> RGB8
grayscale rgb =
(avg, avg, avg)
where (r, g, b) = fromIntegral' rgb
avg = round ((r + g + b) / 3)
onlyRed (r, g, b) = (r, 0, 0)
onlyGreen (r, g, b) = (0, g, 0)
onlyBlue (r, g, b) = (0, 0, b)
negative (r, g, b) = (maxBound - r, maxBound - g, maxBound - b)
sepia rgb =
(assertBounded' . round') (r', g', b')
where (r, g, b) = fromIntegral' rgb
r' = r * 0.393 + g * 0.769 + b * 0.189
g' = r * 0.349 + g * 0.686 + b * 0.168
b' = r * 0.272 + g * 0.534 + b * 0.131
onlyY rgb = Ycbcr.fromYcbcr (y, 0.0, 0.0)
where (y, cb, cr) = Ycbcr.toYcbcr rgb
onlyCb rgb = Ycbcr.fromYcbcr (128, cb, 0.0)
where (y, cb, cr) = Ycbcr.toYcbcr rgb
onlyCr rgb = Ycbcr.fromYcbcr (128, 0.0, cr)
where (y, cb, cr) = Ycbcr.toYcbcr rgb
onlyH rgb = Hls.fromHls (h, 0.5, 0.5)
where (h, l, s) = Hls.toHls rgb
onlyL rgb = Hls.fromHls (0, l, 0)
where (h, l, s) = Hls.toHls rgb
onlyS rgb = Hls.fromHls (h, 0.5, s)
where (h, l, s) = Hls.toHls rgb
type Range = (Double, Double)
inRange :: Range -> Double -> Bool
inRange (minVal, maxVal) val
| minVal <= maxVal = val >= minVal && val <= maxVal
| otherwise = val >= minVal || val <= maxVal
filterHls :: Range -> Range -> Range -> RGB8 -> Bool
filterHls hr lr sr rgb =
inRange hr h && inRange lr l && inRange sr s
where (h, l, s) = Hls.toHls rgb
filterHue :: Double -> Double -> RGB8 -> RGB8
filterHue l r rgb
| filterHls (l, r) (0, 360) (0, 360) rgb = rgb
| otherwise = (0, 0, 0)
filterSkin :: RGB8 -> RGB8
filterSkin rgb
| inRange (0.5, 3.0) (l/s) && filterHls (330, 28) (0, 1) (0.2, 1) rgb = rgb
| otherwise = (0, 0, 0)
where (h, l, s) = Hls.toHls rgb
filterRedEyes :: RGB8 -> RGB8
filterRedEyes rgb
| inRange (0.5, 1.5) (l/s) && filterHls (162, 7) (0.25, 1) (0.4, 1) rgb = rgb
| otherwise = Hls.fromHls (0, l, 0)
where (h, l, s) = Hls.toHls rgb
binarizeY :: (Bounded a) => Double -> Double -> Double -> a
binarizeY a b y
| y >= a && y < b = minBound
| otherwise = maxBound
binarizeY' :: (Bounded a) => Double -> Double -> Double -> (a, a, a)
binarizeY' a b y
| y >= a && y < b = (minBound, minBound, minBound)
| otherwise = (maxBound, maxBound, maxBound)
binarize :: (Bounded a) => Double -> Double -> RGB8 -> a
binarize a b rgb = binarizeY a b (Ycbcr.y rgb)
binarize' :: (Bounded a) => Double -> Double -> RGB8 -> (a, a, a)
binarize' a b rgb = binarizeY' a b (Ycbcr.y rgb)
boundedToBounded :: (Bounded a, Eq a, Bounded b) => a -> b
boundedToBounded a
| a == maxBound = maxBound
| otherwise = minBound
triple :: a -> (a, a, a)
triple a = (a, a, a)
| mikolajsacha/HaskellPics | pixelmaps.hs | gpl-3.0 | 3,317 | 0 | 12 | 864 | 1,551 | 860 | 691 | 85 | 1 |
{-# LANGUAGE OverloadedStrings,MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Alteryx.Serialization
(
buildBlock,
buildRecord,
calgaryHeaderSize,
dbFileId,
getCalgaryRecords,
getCalgaryBlockIndex,
getOneBlock,
getOneBlockCalgaryRecords,
getRecord,
getValue,
putRecord,
putValue,
headerPageSize,
miniblockThreshold,
numMetadataBytesActual,
numMetadataBytesHeader,
numBlockBytesActual,
numBlockBytesHeader,
parseRecordsUntil,
recordsPerBlock,
startOfBlocksByteIndex
) where
import Database.Alteryx.Fields
import Database.Alteryx.Types
import Blaze.ByteString.Builder
import Codec.Compression.LZF.ByteString (decompressByteStringFixed, compressByteStringFixed)
import qualified Control.Newtype as NT
import Control.Applicative
import Control.Lens
import Control.Monad as M
import Control.Monad.Loops
import Data.Array.IArray (listArray, bounds, elems)
import Data.Binary
import Data.Binary.C ()
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Conduit
import Data.Conduit.List (sourceList)
import Data.Conduit.Lazy (lazyConsume)
import qualified Data.Map as Map
import Data.Maybe (isJust, listToMaybe)
import Data.Monoid
import Data.ReinterpretCast (floatToWord, wordToFloat, doubleToWord, wordToDouble)
import Data.Text as T
import Data.Text.Encoding
import qualified Data.Text.Lazy as TL
import Data.Time.Clock.POSIX
import qualified Data.Vector as V
import System.IO.Unsafe (unsafePerformIO)
import Text.XML hiding (renderText)
import Text.XML.Cursor as XMLC
(
Cursor,
($.//),
attribute,
element,
fromDocument
)
import Text.XML.Stream.Render (renderText)
import Text.XML.Unresolved (toEvents)
-- | Number of records before each block is flushed and added to the block index
recordsPerBlock :: Int
recordsPerBlock = 0x10000
spatialIndexRecordBlockSize = 32
-- | Number of bytes taken by the fixed header
headerPageSize :: Int
headerPageSize = 512
-- | Number of bytes taken by the Calgary format's header
calgaryHeaderSize :: Int
calgaryHeaderSize = 8192
-- | When writing miniblocks, how many bytes should each miniblock aim for?
miniblockThreshold :: Int
miniblockThreshold = 0x10000
-- | When decompressing miniblocks, how many bytes should be allocated for the output?
bufferSize :: Int
bufferSize = 0x40000
dbFileId :: DbType -> Word32
dbFileId WrigleyDb = 0x00440205
dbFileId WrigleyDb_NoSpatialIndex = 0x00440204
dbFileId CalgaryDb = 0x00450101
-- Start of metadata: 8196
-- End of metadata: 10168
-- 1972 = 3da * 2 = 986 * 2
numBytes :: (Binary b, Num t) => b -> t
numBytes x = fromIntegral $ BSL.length $ runPut $ put x
numMetadataBytesHeader :: Header -> Int
numMetadataBytesHeader header = fromIntegral $ 2 * (header ^. metaInfoLength)
numMetadataBytesActual :: RecordInfo -> Int
numMetadataBytesActual recordInfo = numBytes recordInfo
numBlockBytesHeader :: Header -> Int
numBlockBytesHeader header =
let start = headerPageSize + (numMetadataBytesHeader header)
end = (fromIntegral $ header ^. recordBlockIndexPos)
in end - start
numBlockBytesActual :: Block -> Int
numBlockBytesActual block = numBytes block
startOfBlocksByteIndex :: Header -> Int
startOfBlocksByteIndex header =
headerPageSize + (numMetadataBytesHeader header)
parseRecordsUntil :: RecordInfo -> Get [Record]
parseRecordsUntil recordInfo = do
done <- isEmpty
if done
then return $ []
else (:) <$> getRecord recordInfo <*> parseRecordsUntil recordInfo
-- | This binary instance is really slow because the YxdbFile type stores a list of records. Use the Conduit functions instead.
instance Binary YxdbFile where
put yxdbFile = do
put $ yxdbFile ^. yxdbFileHeader
put $ yxdbFile ^. yxdbFileMetadata
mapM_ (putRecord $ yxdbFile ^. yxdbFileMetadata) $ yxdbFile ^. yxdbFileRecords
put $ yxdbFile ^. yxdbFileBlockIndex
get = do
fHeader <- label "Header" $ isolate (fromIntegral headerPageSize) get
fMetadata <- label "Metadata" $ isolate (numMetadataBytesHeader fHeader) $ get
let numBlockBytes = numBlockBytesHeader $ fHeader
fBlocks <- label ("Blocks of size " ++ show numBlockBytes) $
isolate numBlockBytes get :: Get Block
fBlockIndex <- label "Block Index" get
let fRecords = runGet (label "Records" $ parseRecordsUntil fMetadata) $ NT.unpack fBlocks
return $ YxdbFile {
_yxdbFileHeader = fHeader,
_yxdbFileMetadata = fMetadata,
_yxdbFileRecords = fRecords,
_yxdbFileBlockIndex = fBlockIndex
}
instance Binary CalgaryRecordInfo where
put calgaryRecordInfo = error "CalgaryRecordInfo: put undefined"
get = CalgaryRecordInfo <$> getCalgaryRecordInfo
-- Start: 27bc = 10172
-- End: 2826 = 10278
-- Diff: 106 = 6A
-- Start: 27c1 = 10177
-- End: 2998 = 10648
-- Diff: 1D7 = 471
-- 8192 byte header
-- Read 4 bytes to get number of UTF-16 characters(so double for number of bytes)
-- blockSize is 16-bit
-- block is a 32767-byte compressed buffer
-- Is follow
getCalgaryRecords :: CalgaryRecordInfo -> Get (V.Vector Record)
getCalgaryRecords (CalgaryRecordInfo recordInfo) = do
mystery1 <- getWord32le -- 0
mystery2 <- getWord32le -- 1: Number of records? Matches first word in block index
mystery3 <- getWord16le -- 0
-- let (RecordInfo fs) = recordInfo
-- f1 <- getValue $ fs !! 0
-- error $ show f1
-- bs <- getRemainingLazyByteString
-- error $ show bs
V.replicateM (fromIntegral mystery2) $ (getRecord recordInfo)
-- headend_no <- getValue $ Field "headend_no" FTInt32 Nothing Nothing
-- hh_no <- getValue $ Field "hh_no" FTInt32 Nothing Nothing
-- hashed_id <- getValue $ Field "hashed_id" FTVString Nothing Nothing
-- error $ show hashed_id
-- bs <- getRemainingLazyByteString
-- r <- getRecord recordInfo
-- V.replicateM (fromIntegral mystery2) $ (getRecord recordInfo)
-- -- error $ show [ show mystery1, show mystery2, show mystery3 ]
-- x <- getRecord recordInfo
-- y <- getRecord recordInfo
-- error $ show y
-- byte <- getValue $ Field "byte" FTByte Nothing Nothing
-- int16 <- getValue $ Field "int16" FTInt16 Nothing Nothing
-- int32 <- getValue $ Field "int32" FTInt32 Nothing Nothing
-- int64 <- getValue $ Field "int64" FTInt64 Nothing Nothing
-- decimal <- getValue $ Field "decimal" FTFixedDecimal (Just 7) Nothing
-- mystery6 <- getWord32le -- 0
-- float <- getValue $ Field "float" FTFloat Nothing Nothing
-- double <- getValue $ Field "double" FTDouble Nothing Nothing
-- string <- getValue $ Field "string" FTString (Just 7) Nothing
-- wstring <- getValue $ Field "wstring "FTWString (Just 2) Nothing
-- let vfield = Field "vstring" FTVString Nothing Nothing
-- vwfield = Field "vwstring" FTVWString Nothing Nothing
-- vstring <- getValue vfield
-- vwstring <- getValue vwfield
-- date <- getValue $ Field "date" FTDate Nothing Nothing
-- time <- getValue $ Field "time" FTTime Nothing Nothing
-- datetime <- getValue $ Field "datetime" FTDateTime Nothing Nothing
-- mystery7 <- getWord32le -- 13
-- -- error $ show [
-- -- show mystery1, show mystery2, show mystery3, show mystery4, show mystery5,
-- -- show mystery6, show mystery7
-- -- ]
-- error $ show [
-- show byte,
-- show int16,
-- show int32,
-- show int64,
-- show decimal,
-- show float,
-- show double,
-- show string,
-- show wstring,
-- show vstring,
-- show vwstring,
-- show date,
-- show time,
-- show datetime
-- ]
-- vfieldVarBs <- getVariableData
-- vwfieldVarBs <- getVariableData
-- remainder <- getRemainingLazyByteString
-- error $ show remainder
-- error $ show [
-- -- show mystery1,
-- show byte,
-- -- show byteNul,
-- -- show mystery2,
-- -- show short,
-- -- show shortNul,
-- -- show mystery3,
-- -- show int,
-- -- show intNul,
-- show int64,
-- -- show int64Nul
-- show remainder
-- ]
-- -- error $ show [ mystery1, byte, byteNul, mystery2, short, shortNul, remainder ]
getOneBlock :: Get (Maybe Block)
getOneBlock = do
blockSize <- getWord16le
block <- getByteString $ fromIntegral blockSize
let decompressed = decompressByteStringFixed 100000 block
return $ Block <$> BSL.fromStrict <$> decompressed
getOneBlockCalgaryRecords :: CalgaryRecordInfo -> Get (V.Vector Record)
getOneBlockCalgaryRecords recordInfo = do
(Just (Block block)) <- getOneBlock
let records = runGet (getCalgaryRecords recordInfo ) block
return records
instance Binary CalgaryFile where
put calgaryFile = error "CalgaryFile: put undefined"
get = do
fHeader <- label "Header" $ isolate (fromIntegral calgaryHeaderSize) get :: Get CalgaryHeader
fNumMetadataBytes <- (2*) <$> fromIntegral <$> getWord32le
fRecordInfo <- label "Metadata" $ isolate fNumMetadataBytes $ get :: Get CalgaryRecordInfo
let numRecords = fromIntegral $ fHeader ^. calgaryHeaderNumRecords
let readAllBlocks remainingRecords = do
if remainingRecords > 0
then do
records <- getOneBlockCalgaryRecords fRecordInfo
let newRecords = remainingRecords - V.length records
(records :) <$> readAllBlocks newRecords
else return []
recordses <- readAllBlocks numRecords :: Get [ V.Vector Record ]
blockIndex <- getCalgaryBlockIndex
-- Should be done by here
let result = CalgaryFile {
_calgaryFileHeader = fHeader,
_calgaryFileRecordInfo = fRecordInfo,
_calgaryFileRecords = recordses,
_calgaryFileIndex = blockIndex
}
error $ show result
getString :: Get CalgaryIndexFile
getString = do
fHeader <- isolate (fromIntegral calgaryHeaderSize) get :: Get CalgaryHeader
block <- getOneBlock
error $ show block
mystery1 <- getWord16le -- 121: Index to vardata?
mystery2 <- getWord16le -- 1: Number of records?
mystery3 <- getWord16le -- 32769 = -1
mystery4 <- getWord16le -- 512
mystery5 <- getWord16le -- 1
mystery6 <- getWord16le -- 32776 = 32768 + 8 = -8
mystery7 <- getWord16le
mystery8 <- getWord8 -- 0
value <- getLazyByteStringNul
mystery9 <- getWord16le -- 32769 = -1
mystery10 <- getWord16le -- 3104
-- mystery9 <- getWord16le
replicateM_ 31 $ do
mystery10 <- getWord16le
mystery11 <- getWord8 -- 32
return ()
mystery12 <- getWord16le -- 1: Number of values?
mystery13 <- getWord8 -- 0
mystery14 <- getWord16le -- 7: Length of platano?
value2 <- getByteString $ fromIntegral mystery14
mystery15 <- getWord64le
error $ show mystery15 -- 8192: Index of first block?
instance Binary CalgaryIndexFile where
put _ = error "CalgaryIndexFile: put undefined"
get = do
fHeader <- isolate (fromIntegral calgaryHeaderSize) get :: Get CalgaryHeader
(Just (Block block)) <- getOneBlock
let getRecords = do
mystery1 <- getWord64le -- 0
mystery2 <- getWord16le -- 1
mystery3 <- getWord64le -- 8
val <- getValue $ Field "x" FTString (Just 7) Nothing
mystery4 <- getWord16le -- -1
bs <- getRemainingLazyByteString
error $ show bs
runGet getRecords block
error $ show block
getCalgaryBlockIndex :: Get CalgaryBlockIndex
getCalgaryBlockIndex = do
let getOneIndex = do
mystery1 <- getWord64le
getWord64le
indices <- V.fromList <$> untilM' getOneIndex isEmpty
return $ CalgaryBlockIndex $ V.map fromIntegral indices
documentToTextWithoutXMLHeader :: Document -> T.Text
documentToTextWithoutXMLHeader document =
let events = Prelude.tail $ toEvents $ toXMLDocument document
in T.concat $
unsafePerformIO $
lazyConsume $
sourceList events $=
renderText def
getRecordInfoText :: Bool -> Get T.Text
getRecordInfoText isNullTerminated = do
if isNullTerminated
then do
bs <- BS.concat . BSL.toChunks <$>
getRemainingLazyByteString
when (BS.length bs < 4) $ fail $ "No trailing newline and null: " ++ show bs
let text = T.init $ T.init $ decodeUtf16LE bs
return text
else decodeUtf16LE <$> BS.concat . BSL.toChunks <$> getRemainingLazyByteString
getCalgaryRecordInfo :: Get RecordInfo
getCalgaryRecordInfo = do
text <- getRecordInfoText False
let document = parseText_ def $ TL.fromStrict text
cursor = fromDocument document
recordInfos = parseXmlRecordInfo cursor
case recordInfos of
[] -> fail "No RecordInfo entries found"
x:[] -> return x
xs -> fail "Too many RecordInfo entries found"
getYxdbRecordInfo :: Get RecordInfo
getYxdbRecordInfo = do
text <- getRecordInfoText True
let document = parseText_ def $ TL.fromStrict text
cursor = fromDocument document
recordInfos = parseXmlRecordInfo cursor
case recordInfos of
[] -> fail "No RecordInfo entries found"
x:[] -> return x
xs -> fail "Too many RecordInfo entries found"
instance Binary RecordInfo where
put metadata =
let fieldMap :: Field -> Map.Map Name Text
fieldMap field =
let
requiredAttributes =
[
("name", field ^. fieldName),
("type", renderFieldType $ field ^. fieldType)
]
sizeAttributes =
case field ^. fieldSize of
Nothing -> [ ]
Just x -> [ ("size", T.pack $ show x) ]
scaleAttributes =
case field ^. fieldScale of
Nothing -> [ ]
Just x -> [ ("scale", T.pack $ show x) ]
in Map.fromList $
Prelude.concat $
[ requiredAttributes, sizeAttributes, scaleAttributes ]
transformField field =
NodeElement $
Element "Field" (fieldMap field) [ ]
transformRecordInfo recordInfo =
NodeElement $
Element "RecordInfo" Map.empty $
Prelude.map transformField recordInfo
transformMetaInfo (RecordInfo recordInfo) =
Element "MetaInfo" Map.empty [ transformRecordInfo recordInfo]
transformToDocument node = Document (Prologue [] Nothing []) node []
renderMetaInfo metadata =
encodeUtf16LE $
flip T.snoc '\0' $
flip T.snoc '\n' $
documentToTextWithoutXMLHeader $
transformToDocument $
transformMetaInfo metadata
in putByteString $ renderMetaInfo metadata
get = getYxdbRecordInfo
parseXmlField :: Cursor -> [Field]
parseXmlField cursor = do
let fieldCursors = cursor $.// XMLC.element "Field"
fieldCursor <- fieldCursors
aName <- attribute "name" fieldCursor
aType <- attribute "type" fieldCursor
let aDesc = listToMaybe $ attribute "description" fieldCursor
let aSize = listToMaybe $ attribute "size" fieldCursor
let aScale = listToMaybe $ attribute "scale" fieldCursor
return $ Field {
_fieldName = aName,
_fieldType = parseFieldType aType,
_fieldSize = parseInt <$> aSize,
_fieldScale = parseInt <$> aScale
}
parseXmlRecordInfo :: Cursor -> [RecordInfo]
parseXmlRecordInfo cursor = do
let recordInfoCursors = cursor $.// XMLC.element "RecordInfo"
recordInfoCursor <- recordInfoCursors
let fields = parseXmlField recordInfoCursor
return $ RecordInfo fields
parseInt :: Text -> Int
parseInt text = read $ T.unpack text :: Int
-- | True if any fields have associated variable data in the variable data portion of the record.
hasVariableData :: RecordInfo -> Bool
hasVariableData (RecordInfo recordInfo) =
let fieldHasVariableData field =
case field ^. fieldType of
FTVString -> True
FTVWString -> True
FTBlob -> True
_ -> False
in Prelude.any fieldHasVariableData recordInfo
-- | Writes a record using the provided metadata.
putRecord :: RecordInfo -> Record -> Put
putRecord recordInfo record = putByteString $ toByteString $ buildRecord recordInfo record
buildRecord :: RecordInfo -> Record -> Builder
buildRecord recordInfo@(RecordInfo fields) (Record fieldValues) =
if hasVariableData recordInfo
then error "putRecord: Variable data unimplemented"
else mconcat $ Prelude.zipWith buildValue fields fieldValues
-- | Records consists of a fixed amount of data for each field, and also a possibly large amoutn of variable data at the end.
getRecord :: RecordInfo -> Get Record
getRecord recordInfo@(RecordInfo fields) = do
record <- Record <$> mapM getValue fields
when (hasVariableData recordInfo) $ do
_ <- getAllVariableData
return ()
return record
instance Binary BlockIndex where
get = do
arraySize <- label "Index Array Size" $ fromIntegral <$> getWord32le
let numBlockIndexBytes = arraySize * 8
blocks <- label ("Reading block of size " ++ show arraySize) $
isolate numBlockIndexBytes $
replicateM arraySize (fromIntegral <$> getWord64le)
return $ BlockIndex $ listArray (0, arraySize-1) blocks
put (BlockIndex blockIndex) = do
let (_, iMax) = bounds blockIndex
putWord32le $ fromIntegral $ iMax + 1
mapM_ (putWord64le . fromIntegral) $ elems blockIndex
instance Binary Block where
get =
let tryGetOne = do
done <- isEmpty
if done
then return Nothing
else Just <$> get :: Get (Maybe Miniblock)
in NT.pack <$>
BSL.fromChunks <$>
Prelude.map NT.unpack <$>
unfoldM tryGetOne
put block = putByteString $ toByteString $ buildBlock block
buildBlock :: Block -> Builder
buildBlock (Block bs) =
case BSL.toChunks bs of
[] -> buildMiniblock $ Miniblock $ BS.empty
xs -> mconcat $ Prelude.map (buildMiniblock . Miniblock) xs
instance Binary Miniblock where
get = do
writtenSize <- label "Block size" getWord32le
let compressionBitIndex = 31
let isCompressed = not $ testBit writtenSize compressionBitIndex
let size = fromIntegral $ clearBit writtenSize compressionBitIndex
bs <- label ("Block of size " ++ show size) $ isolate size $ getByteString $ size
let chunk = if isCompressed
then case decompressByteStringFixed bufferSize bs of
Nothing -> fail "Unable to decompress. Increase buffer size?"
Just x -> return $ x
else return bs
Miniblock <$> chunk
put miniblock = putByteString $ toByteString $ buildMiniblock miniblock
buildMiniblock :: Miniblock -> Builder
buildMiniblock (Miniblock bs) =
let compressionBitIndex = 31
compressedBlock = compressByteStringFixed ((BS.length bs)-1) bs
blockToWrite = case compressedBlock of
Nothing -> bs
Just x -> x
size = BS.length blockToWrite
writtenSize = if isJust compressedBlock
then size
else setBit size compressionBitIndex
in mconcat [
fromWord32le $ fromIntegral writtenSize,
fromByteString blockToWrite
]
instance Binary Header where
put header = do
let actualDescriptionBS = BS.take 64 $ encodeUtf8 $ header ^. description
let numPaddingBytes = fromIntegral $ 64 - BS.length actualDescriptionBS
let paddingDescriptionBS = BSL.toStrict $ BSL.take numPaddingBytes $ BSL.repeat 0
putByteString actualDescriptionBS
putByteString paddingDescriptionBS
putWord32le $ header ^. fileId
putWord32le $ truncate $ utcTimeToPOSIXSeconds $ header ^. creationDate
putWord32le $ header ^. flags1
putWord32le $ header ^. flags2
putWord32le $ header ^. metaInfoLength
putWord32le $ header ^. mystery
putWord64le $ header ^. spatialIndexPos
putWord64le $ header ^. recordBlockIndexPos
putWord64le $ header ^. numRecords
putWord32le $ header ^. compressionVersion
putByteString $ header ^. reservedSpace
get = do
fDescription <- label "Description" $ decodeUtf8 <$> getByteString 64
fFileId <- label "FileId" getWord32le
fCreationDate <- label "Creation Date" getWord32le
fFlags1 <- label "Flags 1" getWord32le
fFlags2 <- label "Flags 2" getWord32le
fMetaInfoLength <- label "Metadata Length" getWord32le
fMystery <- label "Mystery Field" getWord32le
fSpatialIndexPos <- label "Spatial Index" getWord64le
fRecordBlockIndexPos <- label "Record Block" getWord64le
fNumRecords <- label "Num Records" getWord64le
fCompressionVersion <- label "Compression Version" getWord32le
fReservedSpace <- label "Reserved Space" $ (BSL.toStrict <$> getRemainingLazyByteString)
return $ Header {
_description = fDescription,
_fileId = fFileId,
_creationDate = posixSecondsToUTCTime $ fromIntegral fCreationDate,
_flags1 = fFlags1,
_flags2 = fFlags2,
_metaInfoLength = fMetaInfoLength,
_mystery = fMystery,
_spatialIndexPos = fSpatialIndexPos,
_recordBlockIndexPos = fRecordBlockIndexPos,
_numRecords = fNumRecords,
_compressionVersion = fCompressionVersion,
_reservedSpace = fReservedSpace
}
instance Binary CalgaryHeader where
put header = error "CalgaryHeader::put is unimplemented"
get = do
description <- decodeUtf8 <$> getByteString 64
fileId <- getWord32le
creationDate <- posixSecondsToUTCTime <$> fromIntegral <$> getWord32le
indexPosition <- getWord32le
mystery1 <- getWord32le
numBlocks <- getWord32le
mystery2 <- getWord32le
mystery3 <- getWord32le
mystery4 <- getWord32le
mystery5 <- getWord32le
mystery6 <- getWord64le
numRecords <- getWord32le
reserved <- BSL.toStrict <$> getRemainingLazyByteString
return CalgaryHeader {
_calgaryHeaderDescription = description,
_calgaryHeaderFileId = fileId,
_calgaryHeaderCreationDate = creationDate,
_calgaryHeaderIndexPosition = indexPosition,
_calgaryHeaderMystery1 = mystery1,
_calgaryHeaderNumRecords = numRecords,
_calgaryHeaderMystery2 = mystery2,
_calgaryHeaderMystery3 = mystery3,
_calgaryHeaderMystery4 = mystery4,
_calgaryHeaderMystery5 = mystery5,
_calgaryHeaderMystery6 = mystery6,
_calgaryHeaderNumBlocks = numBlocks,
_calgaryHeaderReserved = reserved
}
| MichaelBurge/yxdb-utils | src/Database/Alteryx/Serialization.hs | gpl-3.0 | 23,858 | 0 | 21 | 6,617 | 4,776 | 2,438 | 2,338 | 464 | 4 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards#-}
module KeyHandler where
import qualified Brick.Main as BrickMain
import qualified Brick.Types as BrickTypes
import qualified Graphics.Vty as GraphicsVty
import qualified Brick.Widgets.Edit as BrickWidgetsEdit
import AppState
import Control.Lens
import Data.Text.Zipper
import qualified Control.Monad.IO.Class as IOClass
import Command
import IoNetwork
import qualified Data.Maybe as DM
import qualified System.IO as SIO
import qualified Data.List as DL
import Task
import TimeLog
type Key = GraphicsVty.Key
type EventMName = BrickTypes.EventM Name
type VtyEvent = GraphicsVty.Event
onKeyEvent :: Key -> St -> VtyEvent -> EventMName (BrickTypes.Next St)
onKeyEvent keycode st ev = do
nextEvent <- case keycode of
GraphicsVty.KEsc -> BrickMain.halt st
GraphicsVty.KEnter -> handleKeyEnter st
_ -> BrickMain.continue =<< BrickTypes.handleEventLensed st (cliEditor) BrickWidgetsEdit.handleEditorEvent ev
-- GraphicsVty.KEnter -> SuspendAndResume IO (st)
return (nextEvent)
enterNewCLICommand :: St -> [String] -> St
enterNewCLICommand st cs' = st'
where
cs = view commands st
st' = set commands cs'' st
cs''= (head cs') : cs -- be careful here, it only takes the first command line it seems and discards the rest of the edit lines
handleKeyEnter :: St -> EventMName (BrickTypes.Next St)
handleKeyEnter st = do
let st'' = eraseCommandLine' st'
BrickMain.continue st''
where
editor = st ^. cliEditor
editContents = BrickWidgetsEdit.getEditContents $ editor
st' = enterNewCLICommand st editContents
resetEdit :: St -> EditorCtrl
resetEdit st = BrickWidgetsEdit.applyEdit transformer $ st ^. cliEditor
where
transformer :: TextZipper String -> TextZipper String
transformer _ = stringZipper [] Nothing
eraseCommandLine :: St -> St
eraseCommandLine st = st'
where
e'= resetEdit st
st' = set cliEditor e' st
-- eraseCommandLine' :: St -> St
-- eraseCommandLine' st = st & cliEditor .~ (resetEdit st)
handleUserActivity :: St -> IO (St)
handleUserActivity st = do
newState <- if not hasTimeLogs
then return st
else do
IOClass.liftIO $ sendTimeLogs handle tls
return $ set timeLogsToSend [] st
return newState
where
tls = view timeLogsToSend st
hasTimeLogs = not.null $ tls
handle = DM.fromJust $ view socketHandle st
handleOnNewCliCommand :: St -> EventMName (BrickTypes.Next St)
handleOnNewCliCommand st = do
newState <- if not hasCommands
then return st
else do
st' <- IOClass.liftIO $ parseAndEvaluateCommand handle c st
let st'' = set commands (drop 1 cs) st'
st''' <- IOClass.liftIO $ handleUserActivity st'' -- what to do when there is user activity ( send time logs for example)
return st'''
BrickMain.continue newState
where
hasCommands = not . null $ st ^. commands
cmds = st ^. commands
(c:cs) = cmds
handle = DM.fromJust $ st ^. socketHandle
parseAndEvaluateCommand :: SIO.Handle -> String -> St -> IO (St)
parseAndEvaluateCommand handle cmd st = do
commandToSend <- parse cmd
st''' <- case commandToSend of
Right c -> do
eitherSt <- evaluateCommand c handle st
let st'' = case eitherSt of
Right stt -> set lastError "" stt
Left msg -> set lastError msg st
return st''
Left msg -> do
let st' = set lastError msg st
return st'
return st'''
evaluateCommand :: Command -> SIO.Handle -> St -> IO (Either String St)
evaluateCommand (AppShowDetails b) _ st = do
let st' = set isShowDetails b st
return $ Right st'
evaluateCommand (TimeLogStart cmt) _ st = do
let uuidSelected = view uuidCurrentTask st
let st' = set uuidCurrentTaskLogged (Just uuidSelected) st
let st''= set timeLogComment cmt st'
return $ Right st''
evaluateCommand (TimeLogStop) _ st = do
let st' = set uuidCurrentTaskLogged Nothing st
return $ Right st'
evaluateCommand (TimeLogComment cmt) _ st = do
let st' = set timeLogComment cmt st
return $ Right st'
evaluateCommand (TimeLogCancel) _ st = do
let st' = set timeLogsToSend [] st
let st'' = set uuidCurrentTaskLogged Nothing st'
return $ Right st''
evaluateCommand (TimeLogShow) _ st = do
let st' = set isShowTimeLogs True st
return $ Right st'
evaluateCommand (TimeLogHide) _ st = do
let st' = set isShowTimeLogs False st
return $ Right st'
evaluateCommand (TaskSelectParent) _ st = do
let u = view uuidCurrentTask st
let ts = view tasks st
let maybeTask = DL.find (\t -> (view uuid t) == u) ts
let eitherSt = case maybeTask of
Just t -> Right $ set uuidCurrentTask (view parent t) st
_ -> Left "Root task has no parent, unable to cd .."
return eitherSt
evaluateCommand (TaskSelect taskName) _ st = do
let uuidSelected = getUuidSelected taskName $ view tasks st
let st' = set uuidCurrentTask uuidSelected st
return $ Right st'
evaluateCommand (TaskCreate n u _up) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskCreate n u u')
return $ Right st
evaluateCommand (TaskSetDescription _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetDescription u' d)
return $ Right st
evaluateCommand (TaskSetWhy _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetWhy u' d)
return $ Right st
evaluateCommand (TaskSetStatus _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetStatus u' d)
return $ Right st
evaluateCommand (TaskSetAssurance _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetAssurance u' d)
return $ Right st
evaluateCommand (TaskSetCynefin _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetCynefin u' d)
return $ Right st
evaluateCommand (TaskSetValue _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetValue u' d)
return $ Right st
evaluateCommand (TaskSetEstimate _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetEstimate u' d)
return $ Right st
evaluateCommand (TaskSetPerturbation _ d) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetPerturbation u' d)
return $ Right st
evaluateCommand (TaskSetParent _ pn cn) h st = do
let u' = view uuidCurrentTask st
sendOverNetwork h (TaskSetParent u' pn cn)
return $ Right st
evaluateCommand c h st = do
sendOverNetwork h c
return $ Right st
getUuidSelected :: TaskName -> Tasks -> TaskUuid
getUuidSelected n ts = uuidFound
where
uuidFound = if not.null $ selected then view uuid $ head selected else ""
selected = filter (predicate n) ts
predicate nm t = n == startTaskName
where
taskName = view name t
lengthInput = length nm
startTaskName = take lengthInput taskName
sendTimeLogs :: SIO.Handle -> TimeLogs -> IO ()
sendTimeLogs h tls = sendOverNetwork h (TimeLogged tls)
-- eraseCommandLine :: St -> EventMName (BrickTypes.Next St)
-- eraseCommandLine st = do
-- let e = resetEdit st
-- IOClass.liftIO $ putStrLn $ show e
-- BrickMain.continue st
--emptyEditorEvent :: St -> EventMName (BrickTypes.Next St)
--emptyEditorEvent st = do
-- let test = edit1 & BrickWidgetsEdit.editContentsL .~ stringZipper [] Nothing
-- BrickMain.continue $ st
| stephane-rolland/aastraal | aastraal-client-brick/src/KeyHandler.hs | gpl-3.0 | 7,486 | 0 | 19 | 1,711 | 2,338 | 1,130 | 1,208 | 177 | 3 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- 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
(
#ifdef GRID_STYLE_FANCY
module Game.Memory.Output.Fancy,
#endif
#ifdef GRID_STYLE_PLAIN
module Game.Memory.Output.Plain,
#endif
) where
#ifdef GRID_STYLE_FANCY
import Game.Memory.Output.Fancy
#endif
#ifdef GRID_STYLE_PLAIN
import Game.Memory.Output.Plain
#endif
| karamellpelle/grid | source/Game/Memory/Output.hs | gpl-3.0 | 1,058 | 0 | 5 | 180 | 66 | 55 | 11 | 2 | 0 |
module P18TempConverterSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck ((==>))
import P18TempConverter hiding (main)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "toCelsius" $ do
prop "is idempotent on Celsius inputs" $
\x -> toCelsius (Celsius x) == (toCelsius $ toCelsius (Celsius x))
prop "is idempotent on Farenheit inputs" $
\x -> toCelsius (Farenheit x) == (toCelsius $ toCelsius (Farenheit x))
prop "is idempotent on Kelvin inputs" $
\x -> toCelsius (Kelvin x) == (toCelsius $ toCelsius (Kelvin x))
prop "has property that a Celsius temp is equal to itself" $
\x -> Celsius x == Celsius x
prop "has property that addition of 2 Celsius figures is same as constructing C after adding them" $
\x y -> Celsius (x+y) == Celsius x + Celsius y
prop "has the property that C x - C y is equal to C x-y" $
\x y -> Celsius (x-y) == Celsius x - Celsius y
prop "has the property that C x * C y is equal to C x*y" $
\x y -> Celsius (x*y) == Celsius x * Celsius y
prop "has the property that fromInteger x = C x" $
\x -> fromInteger x == Celsius (fromInteger x)
prop "has the property that abs (C x) = C (abs x)" $
\x -> abs (Celsius x) == Celsius (abs x)
prop "has the property that signum (C x) = C (signum x)" $
\x -> signum (Celsius x) == Celsius (signum x)
prop "has the property that showing C x gives the string x°C" $
\x -> show (Celsius x) `shouldBe` show x ++ "°C"
describe "toFarenheit" $ do
prop "is idempotent on Farenheit inputs" $
\x -> toFarenheit (Farenheit x) == (toFarenheit $ toFarenheit (Farenheit x))
prop "is idempotent on Farenheit inputs" $
\x -> toFarenheit (Farenheit x) == (toFarenheit $ toFarenheit (Farenheit x))
prop "is idempotent on Kelvin inputs" $
\x -> toFarenheit (Kelvin x) == (toFarenheit $ toFarenheit (Kelvin x))
prop "has property that a Farenheit temp is equal to itself" $
\x -> Farenheit x == Farenheit x
describe "toKelvin" $ do
prop "is idempotent on Kelvin inputs" $
\x -> toKelvin (Kelvin x) == (toKelvin $ toKelvin (Kelvin x))
prop "is idempotent on Farenheit inputs" $
\x -> toKelvin (Farenheit x) == (toKelvin $ toKelvin (Farenheit x))
prop "is idempotent on Kelvin inputs" $
\x -> toKelvin (Kelvin x) == (toKelvin $ toKelvin (Kelvin x))
prop "has property that a Kelvin temp is equal to itself" $
\x -> Kelvin x == Kelvin x
| ciderpunx/57-exercises-for-programmers | test/P18TempConverterSpec.hs | gpl-3.0 | 2,610 | 0 | 17 | 704 | 838 | 401 | 437 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
-- Spider for Book from OpenISBN
module Spider.Book.Copy
( insertBookCopy
) where
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Text.Printf
insertBookCopy :: Connection -> Int -> IO ()
insertBookCopy c isbn = do
rt <- execute c [sql| INSERT INTO table_book_instance
( key_uuid, key_isbn, key_status)
VALUES (uuid_generate_v4(),?,'a---')
|] (Only (printf "%010d" isbn :: String))
putStrLn $ "insert " ++ show rt ++ " book instance(s)"
return ()
| XDU-PurpleBear/database | pb-spider/src/Spider/Book/Copy.hs | gpl-3.0 | 695 | 0 | 12 | 196 | 123 | 68 | 55 | 14 | 1 |
-- Author: Viacheslav Lotsmanov
-- License: GPLv3 https://raw.githubusercontent.com/unclechu/xlib-keys-hack/master/LICENSE
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
module Types
( type AlternativeModeState
, type AlternativeModeLevel (..)
, numberToAlternativeModeLevel
) where
import "base" GHC.Generics (type Generic)
import "data-default" Data.Default (type Default (def))
import "deepseq" Control.DeepSeq (type NFData)
-- | @Bool@ indicates whether alternative mode is turned on permanently (@True@)
-- or temporarily (@False@) by holding a modifier.
type AlternativeModeState = Maybe (AlternativeModeLevel, Bool)
data AlternativeModeLevel
= FirstAlternativeModeLevel
| SecondAlternativeModeLevel
deriving (Show, Eq, Ord, Bounded, Enum, Generic, NFData)
instance Default AlternativeModeLevel where
def = FirstAlternativeModeLevel
numberToAlternativeModeLevel :: Integral a => a -> Maybe AlternativeModeLevel
numberToAlternativeModeLevel 1 = Just FirstAlternativeModeLevel
numberToAlternativeModeLevel 2 = Just SecondAlternativeModeLevel
numberToAlternativeModeLevel _ = Nothing
| unclechu/xlib-keys-hack | src/Types.hs | gpl-3.0 | 1,133 | 0 | 7 | 158 | 189 | 108 | 81 | -1 | -1 |
{-
- Copyright (C) 2014 Alexander Berntsen <[email protected]>
-
- This file is part of coreutilhs.
-
- coreutilhs 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.
-
- coreutilhs 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 coreutilhs. If not, see <http://www.gnu.org/licenses/>.
-} module Main where
import Control.Concurrent (threadDelay)
import Control.Monad (forM_)
import Data.Either (partitionEithers)
import System.Environment (getArgs)
import Text.Printf
import Text.Read (readMaybe)
main :: IO ()
main = do
input <- getArgs
case partitionEithers $ map readEither input of
([], []) -> putStrLn "sleep: missing operand"
([], ts) -> threadDelay $ sum ts * 1000000
(es, _) -> forM_ es $ printf "sleep: invalid time interval '%s'\n"
where readEither s = maybe (Left s) Right $ readMaybe s
| alexander-b/coreutilhs | sleep.hs | gpl-3.0 | 1,268 | 0 | 12 | 226 | 192 | 102 | 90 | 15 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.HTTPHealthChecks.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the list of HttpHealthCheck resources available to the
-- specified project.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.httpHealthChecks.list@.
module Network.Google.Resource.Compute.HTTPHealthChecks.List
(
-- * REST Resource
HTTPHealthChecksListResource
-- * Creating a Request
, hTTPHealthChecksList
, HTTPHealthChecksList
-- * Request Lenses
, httphclOrderBy
, httphclProject
, httphclFilter
, httphclPageToken
, httphclMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.httpHealthChecks.list@ method which the
-- 'HTTPHealthChecksList' request conforms to.
type HTTPHealthChecksListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"httpHealthChecks" :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] HTTPHealthCheckList
-- | Retrieves the list of HttpHealthCheck resources available to the
-- specified project.
--
-- /See:/ 'hTTPHealthChecksList' smart constructor.
data HTTPHealthChecksList = HTTPHealthChecksList'
{ _httphclOrderBy :: !(Maybe Text)
, _httphclProject :: !Text
, _httphclFilter :: !(Maybe Text)
, _httphclPageToken :: !(Maybe Text)
, _httphclMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'HTTPHealthChecksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'httphclOrderBy'
--
-- * 'httphclProject'
--
-- * 'httphclFilter'
--
-- * 'httphclPageToken'
--
-- * 'httphclMaxResults'
hTTPHealthChecksList
:: Text -- ^ 'httphclProject'
-> HTTPHealthChecksList
hTTPHealthChecksList pHttphclProject_ =
HTTPHealthChecksList'
{ _httphclOrderBy = Nothing
, _httphclProject = pHttphclProject_
, _httphclFilter = Nothing
, _httphclPageToken = Nothing
, _httphclMaxResults = 500
}
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- orderBy=\"creationTimestamp desc\". This sorts results based on the
-- creationTimestamp field in reverse chronological order (newest result
-- first). Use this to sort resources like operations so that the newest
-- operation is returned first. Currently, only sorting by name or
-- creationTimestamp desc is supported.
httphclOrderBy :: Lens' HTTPHealthChecksList (Maybe Text)
httphclOrderBy
= lens _httphclOrderBy
(\ s a -> s{_httphclOrderBy = a})
-- | Project ID for this request.
httphclProject :: Lens' HTTPHealthChecksList Text
httphclProject
= lens _httphclProject
(\ s a -> s{_httphclProject = a})
-- | Sets a filter expression for filtering listed resources, in the form
-- filter={expression}. Your {expression} must be in the format: field_name
-- comparison_string literal_string. The field_name is the name of the
-- field you want to compare. Only atomic field types are supported
-- (string, number, boolean). The comparison_string must be either eq
-- (equals) or ne (not equals). The literal_string is the string value to
-- filter to. The literal value must be valid for the type of field you are
-- filtering by (string, number, boolean). For string fields, the literal
-- value is interpreted as a regular expression using RE2 syntax. The
-- literal value must match the entire field. For example, to filter for
-- instances that do not have a name of example-instance, you would use
-- filter=name ne example-instance. You can filter on nested fields. For
-- example, you could filter on instances that have set the
-- scheduling.automaticRestart field to true. Use filtering on nested
-- fields to take advantage of labels to organize and search for results
-- based on label values. To filter on multiple expressions, provide each
-- separate expression within parentheses. For example,
-- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
-- expressions are treated as AND expressions, meaning that resources must
-- match all expressions to pass the filters.
httphclFilter :: Lens' HTTPHealthChecksList (Maybe Text)
httphclFilter
= lens _httphclFilter
(\ s a -> s{_httphclFilter = a})
-- | Specifies a page token to use. Set pageToken to the nextPageToken
-- returned by a previous list request to get the next page of results.
httphclPageToken :: Lens' HTTPHealthChecksList (Maybe Text)
httphclPageToken
= lens _httphclPageToken
(\ s a -> s{_httphclPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than maxResults, Compute Engine
-- returns a nextPageToken that can be used to get the next page of results
-- in subsequent list requests.
httphclMaxResults :: Lens' HTTPHealthChecksList Word32
httphclMaxResults
= lens _httphclMaxResults
(\ s a -> s{_httphclMaxResults = a})
. _Coerce
instance GoogleRequest HTTPHealthChecksList where
type Rs HTTPHealthChecksList = HTTPHealthCheckList
type Scopes HTTPHealthChecksList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient HTTPHealthChecksList'{..}
= go _httphclProject _httphclOrderBy _httphclFilter
_httphclPageToken
(Just _httphclMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy HTTPHealthChecksListResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/HTTPHealthChecks/List.hs | mpl-2.0 | 6,984 | 0 | 18 | 1,502 | 678 | 409 | 269 | 101 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{- Copyright 2010 Daniel Silva
Distributed under the AGPL v3. See LICENSE file.
-}
-- ghc --make -dynamic -shared -fPIC MobileGtk.hs -o libmobilegtk.so /usr/lib/ghc-6.12.1/libHSrts-ghc6.12.1.so -optl-Wl,-rpath,/usr/lib/ghc-6.12.1/ -optc '-DMODULE=MobileGtk' init.c
-- needs libgtk-x11-2.0.so
module MobileGtk where
import Foreign.C.Types
import Foreign.C.String
import Foreign
import Foreign.Ptr(nullPtr)
import System.Posix.DynamicLinker
import System.Posix.DynamicLinker.Prim(c_dlsym)
import Control.Monad(fmap)
type GtkWidget = Ptr ()
type GObjectClass = Ptr ()
type GtkContainer = Ptr ()
type GnomeApp = Ptr ()
type GtkToolbar = Ptr ()
type GtkScrolledWindow = Ptr ()
type GtkAdjustment = Ptr ()
type GtkFrame = Ptr ()
foreign import ccall gobj_type :: GtkWidget -> CInt
foreign import ccall gobj_get_class :: GtkWidget -> GObjectClass
foreign import ccall gobj_type_name :: GtkWidget -> CString
type WVFun = GtkWidget -> IO ()
foreign import ccall "dynamic" mkWVFun :: FunPtr WVFun -> WVFun
type WidgetWidgetFun = GtkWidget -> GtkWidget -> IO ()
foreign import ccall "dynamic" mkWidgetWidgetFun :: FunPtr WidgetWidgetFun -> WidgetWidgetFun
type CWVFun = GtkContainer -> GtkWidget -> IO ()
foreign import ccall "dynamic" mkCWVFun :: FunPtr CWVFun -> CWVFun
type PPVFun = Ptr () -> Ptr () -> IO ()
foreign import ccall "dynamic" mkPPVFun :: FunPtr PPVFun -> PPVFun
foreign import ccall "gtk/gtk.h gtk_scrolled_window_new" gtk_scrolled_window_new :: GtkAdjustment -> GtkAdjustment -> GtkWidget
foreign import ccall "gtk/gtk.h gtk_scrolled_window_get_hscrollbar" gtk_scrolled_window_get_hscrollbar :: GtkScrolledWindow -> GtkWidget
foreign import ccall "gtk/gtk.h gtk_widget_hide" gtk_widget_hide :: GtkWidget -> IO ()
--foreign import ccall "gtk/gtk.h gtk_widget_show" orig_gtk_widget_show :: GtkWidget -> IO ()
foreign import ccall "gtk/gtk.h gtk_scrolled_window_set_policy" gtk_scrolled_window_set_policy :: GtkScrolledWindow -> CInt -> CInt -> IO ()
foreign import ccall "gtk/gtk.h gtk_widget_hide_all" gtk_widget_hide_all :: GtkWidget -> IO ()
foreign import ccall "gtk/gtk.h gtk_frame_get_label" gtk_frame_get_label :: GtkFrame -> IO CString
foreign import ccall hildon_button_new_with_text :: CInt -> CInt -> CString -> CString -> IO GtkWidget
---- Need to dlsym with RTLD_NEXT by hand until this ubuntu packaging bug is fixed: https://bugs.launchpad.net/ubuntu/+source/ghc6/+bug/560502
--foreign import ccall unsafe "__hsunix_rtldNext" rtldNext :: Ptr a
foreign import ccall unsafe "dlsym" next_dlsym :: CInt -> CString -> IO (FunPtr a)
next :: String -> IO (FunPtr a)
next symbol = do
withCString symbol $ \ s -> do
next_dlsym (-1) s
nextM mk symbol = fmap mk $ next symbol
orig_gtk_widget_show = nextM mkWVFun "gtk_widget_show"
gtk_widget_show :: GtkWidget -> IO ()
gtk_widget_show w = do
typename <- peekCString $ gobj_type_name w
putStrLn ("showing widget of type " ++ typename)
case typename of
"GtkMenuBar" -> return ()
--"GtkToolbar" -> return ()
"GtkFrame" -> do
cstr <- gtk_frame_get_label w
putStrLn "got the c string"
label <- if (cstr == nullPtr) then return "" else peekCString cstr
putStrLn "got the label"
case label of
"Search results :" -> do
orig <- orig_gtk_widget_show
orig w
_ -> return ()
{-
gtk_widget_hide_all w
orig_gtk_widget_show <- nextM mkWVFun "gtk_widget_show"
orig_gtk_widget_show w -}
--"GtkOptionMenu" -> return ()
--"BonoboDockBand" -> return ()
-- GnomeAppBar is a status bar. It's clutter; just pop it up momentarily when there's some activity.
"GnomeAppBar" -> return ()
--"BonoboDockItemGrip" -> return ()
--"GtkScrolledWindow" -> orig_gtk_widget_show w
"GtkScrolledWindow" -> do
orig_gtk_widget_show <- nextM mkWVFun "gtk_widget_show"
orig_gtk_widget_show w
-- hide scrollbars. 2 here is GTK_POLICY_NEVER
gtk_scrolled_window_set_policy w 2 2
_ -> do
orig_gtk_widget_show <- nextM mkWVFun "gtk_widget_show"
orig_gtk_widget_show w
{-
_ -> withDL "libgtk-x11-2.0.so" [RTLD_LAZY] $ \gtk -> do
--ptr <- dlsym gtk "gtk_widget_show"
ptr <- next "gtk_widget_show"
let orig_gtk_widget_show = mkWidgetFun ptr
orig_gtk_widget_show w -}
foreign export ccall "gtk_widget_show" gtk_widget_show :: GtkWidget -> IO ()
orig_gtk_container_add = nextM mkCWVFun "gtk_container_add"
gtk_container_add :: GtkContainer -> GtkWidget -> IO ()
gtk_container_add container widget = do
widget_typename <- peekCString $ gobj_type_name widget
container_typename <- peekCString $ gobj_type_name container
putStrLn ("adding widget of type " ++ widget_typename ++ " to a " ++ container_typename)
case (container_typename, widget_typename) of
(_, "GtkMenuBar") -> return ()
{-
("GtkFrame", _) -> do
gtk_widget_hide widget
orig <- orig_gtk_container_add
orig container widget -}
--(_, "GtkToolbar") -> return ()
_ -> withDL "libgtk-x11-2.0.so" [RTLD_LAZY] $ \gtk -> do
ptr <- dlsym gtk "gtk_container_add"
let orig = mkCWVFun ptr
orig container widget
foreign export ccall gtk_container_add :: GtkContainer -> GtkWidget -> IO ()
-- HildonButtonArrangement
cHILDON_BUTTON_ARRANGEMENT_HORIZONTAL = 0
cHILDON_BUTTON_ARRANGEMENT_VERTICAL = 1
-- HildonSizeType
cHILDON_SIZE_AUTO_WIDTH = 0
gtk_button_new_with_label :: CString -> IO GtkWidget
gtk_button_new_with_label label = do
putStrLn "Intercepting gtk_button_new_with_label"
hildon_button_new_with_text cHILDON_SIZE_AUTO_WIDTH cHILDON_BUTTON_ARRANGEMENT_HORIZONTAL label nullPtr
foreign export ccall gtk_button_new_with_label :: CString -> IO GtkWidget
gnome_app_set_toolbar :: GnomeApp -> GtkToolbar -> IO ()
gnome_app_set_toolbar app toolbar = do
return ()
foreign export ccall gnome_app_set_toolbar :: GnomeApp -> GtkToolbar -> IO ()
| dsilva/gtk-mobile-preload | MobileGtk.hs | agpl-3.0 | 6,000 | 0 | 17 | 1,088 | 1,209 | 619 | 590 | -1 | -1 |
-- C->Haskell Compiler: information about the C implementation
--
-- Author : Manuel M T Chakravarty
-- Created: 5 February 01
--
-- Version $Revision: 1.2 $ from $Date: 2005/01/16 21:31:21 $
--
-- Copyright (c) 2001 Manuel M T Chakravarty
--
-- This file is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This file 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.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- This module provide some information about the specific implementation of
-- C that we are dealing with.
--
--- DOCU ----------------------------------------------------------------------
--
-- language: Haskell 98
--
-- Bit fields
-- ~~~~~~~~~~
-- Bit fields in C can be signed and unsigned. According to K&R A8.3, they
-- can only be formed from `int', `signed int', and `unsigned int', where for
-- `int' it is implementation dependent whether the field is signed or
-- unsigned. Moreover, the following parameters are implementation
-- dependent:
--
-- * the direction of packing bits into storage units,
-- * the size of storage units, and
-- * whether when a field that doesn't fit a partially filled storage unit
-- is split across units or the partially filled unit is padded.
--
-- Generally, unnamed fields (those without an identifier) with a width of 0
-- are guaranteed to forces the above padding. Note that in `CPrimType' we
-- only represent 0 width fields *if* they imply padding. In other words,
-- whenever they are unnamed, they are represented by a `CPrimType', and if
-- they are named, they are represented by a `CPrimType' only if that
-- targeted C compiler chooses to let them introduce padding. If a field
-- does not have any effect, it is dropped during the conversion of a C type
-- into a `CPrimType'-based representation.
--
-- In the code, we assume that the alignment of a bitfield (as determined by
-- `bitfieldAlignment') is independent of the size of the bitfield.
--
--- TODO ----------------------------------------------------------------------
--
module CInfo (
CPrimType(..), size, alignment,
bitfieldDirection, bitfieldPadding, bitfieldIntSigned, bitfieldAlignment
) where
import Foreign.C
-- we can't rely on the compiler used to compile c2hs already having the new
-- FFI, so this is system dependent
--
import C2HSConfig (Ptr, FunPtr,
bitfieldDirection, bitfieldPadding, bitfieldIntSigned,
bitfieldAlignment)
import qualified
C2HSConfig as Storable
(Storable(sizeOf, alignment))
-- calibration of C's primitive types
-- ----------------------------------
-- C's primitive types (EXPORTED)
--
-- * `CFunPtrPT' doesn't occur in Haskell representations of C types, but we
-- need to know their size, which may be different from `CPtrPT'
--
data CPrimType = CPtrPT -- void *
| CFunPtrPT -- void *()
| CCharPT -- char
| CUCharPT -- unsigned char
| CSCharPT -- signed char
| CIntPT -- int
| CShortPT -- short int
| CLongPT -- long int
| CLLongPT -- long long int
| CUIntPT -- unsigned int
| CUShortPT -- unsigned short int
| CULongPT -- unsigned long int
| CULLongPT -- unsigned long long int
| CFloatPT -- float
| CDoublePT -- double
| CLDoublePT -- long double
| CSFieldPT Int -- signed bit field
| CUFieldPT Int -- unsigned bit field
deriving (Eq)
-- size of primitive type of C (EXPORTED)
--
-- * negative size implies that it is a bit, not an octet size
--
size :: CPrimType -> Int
size CPtrPT = Storable.sizeOf (undefined :: Ptr ())
size CFunPtrPT = Storable.sizeOf (undefined :: FunPtr ())
size CCharPT = 1
size CUCharPT = 1
size CSCharPT = 1
size CIntPT = Storable.sizeOf (undefined :: CInt)
size CShortPT = Storable.sizeOf (undefined :: CShort)
size CLongPT = Storable.sizeOf (undefined :: CLong)
size CLLongPT = Storable.sizeOf (undefined :: CLLong)
size CUIntPT = Storable.sizeOf (undefined :: CUInt)
size CUShortPT = Storable.sizeOf (undefined :: CUShort)
size CULongPT = Storable.sizeOf (undefined :: CULong)
size CULLongPT = Storable.sizeOf (undefined :: CLLong)
size CFloatPT = Storable.sizeOf (undefined :: CFloat)
size CDoublePT = Storable.sizeOf (undefined :: CDouble)
size CLDoublePT = Storable.sizeOf (undefined :: CLDouble)
size (CSFieldPT bs) = -bs
size (CUFieldPT bs) = -bs
-- alignment of C's primitive types (EXPORTED)
--
-- * more precisely, the padding put before the type's member starts when the
-- preceding component is a char
--
alignment :: CPrimType -> Int
alignment CPtrPT = Storable.alignment (undefined :: Ptr ())
alignment CFunPtrPT = Storable.alignment (undefined :: FunPtr ())
alignment CCharPT = 1
alignment CUCharPT = 1
alignment CSCharPT = 1
alignment CIntPT = Storable.alignment (undefined :: CInt)
alignment CShortPT = Storable.alignment (undefined :: CShort)
alignment CLongPT = Storable.alignment (undefined :: CLong)
alignment CLLongPT = Storable.alignment (undefined :: CLLong)
alignment CUIntPT = Storable.alignment (undefined :: CUInt)
alignment CUShortPT = Storable.alignment (undefined :: CUShort)
alignment CULongPT = Storable.alignment (undefined :: CULong)
alignment CULLongPT = Storable.alignment (undefined :: CULLong)
alignment CFloatPT = Storable.alignment (undefined :: CFloat)
alignment CDoublePT = Storable.alignment (undefined :: CDouble)
alignment CLDoublePT = Storable.alignment (undefined :: CLDouble)
alignment (CSFieldPT bs) = fieldAlignment bs
alignment (CUFieldPT bs) = fieldAlignment bs
-- alignment constraint for a C bitfield
--
-- * gets the bitfield size (in bits) as an argument
--
-- * alignments constraints smaller or equal to zero are reserved for bitfield
-- alignments
--
-- * bitfields of size 0 always trigger padding; thus, they get the maximal
-- size
--
-- * if bitfields whose size exceeds the space that is still available in a
-- partially filled storage unit trigger padding, the size of a storage unit
-- is provided as the alignment constraint; otherwise, it is 0 (meaning it
-- definitely starts at the current position)
--
-- * here, alignment constraint /= 0 are somewhat subtle; they mean that is
-- the given number of bits doesn't fit in what's left in the current
-- storage unit, alignment to the start of the next storage unit has to be
-- triggered
--
fieldAlignment :: Int -> Int
fieldAlignment 0 = - (size CIntPT - 1)
fieldAlignment bs | bitfieldPadding = - bs
| otherwise = 0
| thiagoarrais/gtk2hs | tools/c2hs/gen/CInfo.hs | lgpl-2.1 | 7,214 | 8 | 8 | 1,618 | 965 | 572 | 393 | 71 | 1 |
module BOM where
import Control.Applicative
import Control.Monad.State
import Control.Monad.RWS
import Control.Monad.Logic
import Data.Function
import Data.List
import Data.Monoid
import Data.Ord
import qualified Data.Map as M
bom =
[ (1, pcb)
, (1, mcu)
, (1, avccDecouplingCapacitor)
, (1, filterBead)
, (2, decouplingCapacitor)
, (1, crystal)
, (2, crystalLoadCapacitor)
, (1, resetPullUpResistor)
]
pcb =
[ Part
{ supplier = oshPark
, partNo = "xmega e5 target board"
, minimumQty = 3
, increment = 3
, price = 4.45 / 3
}
, Part
{ supplier = oshPark
, partNo = "xmega e5 target board"
, minimumQty = 170
, increment = 10
, price = 0.8991
}
]
mcu = basicPart mouser "ATXMEGA8E5-AU"
[ (1, 1.83)
, (10, 1.53)
, (25, 1.15)
, (100, 1.04)
]
avccDecouplingCapacitor = basicPart mouser "VJ1206V106ZXQTW1BC"
[ (1, 0.06)
, (50, 0.049)
, (100, 0.042)
, (500, 0.037)
, (1000, 0.033)
]
filterBead = basicPart mouser "436-0102-RC"
[ (1, 0.05)
, (100, 0.047)
, (500, 0.039)
, (1000, 0.038)
, (4000, 0.03)
, (8000, 0.029)
, (20000, 0.026)
, (40000, 0.025)
, (100000, 0.024)
]
decouplingCapacitor = basicPart mouser "VJ0603Y104JXJPW1BC"
[ (1, 0.06)
, (50, 0.024)
, (100, 0.019)
, (500, 0.017)
, (1000, 0.015)
]
crystal = basicPart mouser "FA-20H 16.0000MF12Z-AC3"
[ (1, 0.77)
, (10, 0.60)
, (100, 0.57)
]
crystalLoadCapacitor = basicPart mouser "VJ0402A100JXAAC"
[ (1, 0.05)
, (50, 0.048)
, (100, 0.04)
, (500, 0.03)
]
resetPullUpResistor = basicPart mouser "CRCW040210K0FKED"
[ (1, 0.08)
, (10, 0.044)
, (100, 0.021)
, (1000, 0.015)
]
---------------------------------------
data Supplier = Supplier
{ supplierName :: String
, shipping :: Double -- TODO: [(Integer, Part)] -> Double
} deriving (Eq, Ord, Read, Show)
mouser = Supplier "Mouser" 4.99
oshPark = Supplier "OSH Park" 0
digikey = Supplier "Digikey" 5.47
newark = Supplier "Newark" 8.50
data Part = Part
{ supplier :: Supplier
, partNo :: String
, minimumQty :: Integer
, increment :: Integer
, price :: Double
} deriving (Eq, Ord, Read, Show)
basicPart supp num breaks =
[ Part supp num moq 1 p
| (moq, p) <- breaks
]
---------------------------------------
unitCost withShipping bom qty = cost / fromIntegral qty
where
cost | withShipping = pCost + sCost
| otherwise = pCost
(_, pCost, sCost) = selectBOM bom qty
selectParts bom = (\(a,_,_) -> a ) . selectBOM bom
orderCost bom = (\(_,b,c) -> b + c) . selectBOM bom
partsCost bom = (\(_,b,_) -> b ) . selectBOM bom
shippingCost bom = (\(_,_,c) -> c) . selectBOM bom
selectBOM parts qty = (bom, sum partCosts, shippingCost)
where
totalCost ((_, x), Sum y) = sum x + y
((bom, partCosts), Sum shippingCost) = minimumBy (comparing totalCost) $
map (\(a,b) -> (unzip a, b)) $
observeAll $
(\x -> evalRWST x () M.empty) $
flip mapM parts $ \(count, part) -> do
selectPart part (count * qty)
selectPart parts qty = do
let suppliers = nub (map supplier parts)
selected <- map supplierName <$> filterM selectSupplier suppliers
let selectedParts = filter (flip elem selected . supplierName . supplier) parts
if null selectedParts
then empty
else pure (selectPart' selectedParts qty)
selectPart' parts qty = ((actualQty part, part), extendedPrice part)
where
part = minimumBy cmpParts parts
extras part = max 0 (qty - minimumQty part)
increments part = ceiling (fromIntegral (extras part) / fromIntegral (increment part))
actualQty part = minimumQty part + increments part * increment part
extendedPrice part = price part * fromIntegral (actualQty part)
-- minimize price, break ties by maximizing qty
cmpParts = mconcat
[ comparing extendedPrice
, flip (comparing actualQty)
]
-- nondeterministically accept/reject each supplier,
-- remembering the choice and (if accepting) tallying
-- the shipping cost
selectSupplier s = do
mbPrev <- gets (M.lookup (supplierName s))
case mbPrev of
Just prev -> return prev
Nothing -> do
accept <- pure True <|> pure False
modify (M.insert (supplierName s) accept)
when accept (tell (Sum (shipping s)))
return accept
| mokus0/schematics | xmega-e5-target/BOM.hs | unlicense | 4,914 | 0 | 18 | 1,619 | 1,569 | 881 | 688 | 132 | 2 |
splitBy _ [] = []
splitBy a x =
let s = takeWhile (/= a) x
x'= dropWhile (/= a) x
in
if x' == []
then [s]
else s:(splitBy a $ drop 1 x')
ans s =
let [m,n] = map read $ splitBy ':' s :: [Double]
ang_s = 360 / 12 * m + 360 / 12 / 60 * n
ang_l = 6 * n
diff = abs (ang_s - ang_l)
d' = if diff < 180 then diff else (360-diff)
in
if d' < 30
then "alert"
else if d' < 90
then "warning"
else "safe"
main = do
n <- getLine
c <- getContents
let n' = read n :: Int
i = lines c
o = map ans i
mapM_ putStrLn o
| a143753/AOJ | 0135.hs | apache-2.0 | 603 | 0 | 14 | 235 | 300 | 155 | 145 | 25 | 4 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Arrows #-}
module Marvin.GUI.Main (mainMarvinGUI) where
import Graphics.UI.Gtk as Gtk
import Graphics.UI.Gtk.Glade
import Data.Maybe
import Data.Traversable
import Control.Arrow
import Prelude hiding (readFile)
import Data.ByteString.Lazy (readFile)
import qualified Data.ByteString as BS
import Control.Monad.Trans
import Control.Monad.Trans.Except
import Control.Monad.Trans.State
import Control.Monad.Trans.Reader
import Control.Concurrent.MVar
import Marvin.API
import Marvin.API.Table.TrainTestSplit
import Marvin.API.Table.PrettyPrint
import Marvin.API.Table.Internal
import Marvin.GUI.AlgorithmDescriptor
import Marvin.GUI.ConfigWindow
import Data.Traversable
import qualified Data.Vector as Vec
import qualified Data.Text as Text
import qualified Data.List as List
import Data.Vector (Vector)
import Data.Tuple (swap)
import qualified Data.Map as Map
type TargetColumnSelector = (ComboBox, ListStore Int, ConnectId ComboBox)
type HeaderWidget = (VBox, CheckButton, ComboBox)
data TestLoader = Split Double | Path FilePath deriving Show
data GUIGlobalState = GUIGlobalState {
trainFilePath :: Maybe FilePath
, trainHasHeader :: Bool
, tableProps :: Maybe TableProperties
, targetColSelector :: TargetColumnSelector
, tableBox :: HBox
, configButton :: Button
, runButton :: Button
, headerWidgets :: Maybe (Vector HeaderWidget)
, selectedAlgorithm :: Maybe AlgorithmDescriptor
, algorithmParams :: Maybe Parameters
, selectedTarget :: Maybe Int
, testLoader :: Maybe TestLoader
, loadedTable :: Maybe RawTable
} deriving Show
instance (Show a) => Show (ConnectId a) where
show _ = "<ConnectId>"
instance (Show a) => Show (ListStore a) where
show _ = "<ListStore>"
instance Show HBox where
show _ = "<HBox>"
instance Show VBox where
show _ = "<VBox>"
instance Show CheckButton where
show _ = "<CheckButton>"
instance Show ComboBox where
show _ = "<ComboBox>"
instance Show Button where
show _ = "<Button>"
emptyGUIState tBox targetSelector configButton_ runButton_ testLoader_ = GUIGlobalState {
trainFilePath = Nothing
, trainHasHeader = False
, tableProps = Nothing
, targetColSelector = targetSelector
, tableBox = tBox
, configButton = configButton_
, runButton = runButton_
, headerWidgets = Nothing
, selectedAlgorithm = Nothing
, algorithmParams = Nothing
, selectedTarget = Nothing
, testLoader = testLoader_
, loadedTable = Nothing
}
-- Table props --
data TableProperties = TableProperties {
selectedColumns :: Vector Bool
, selectedColumnTypes :: Vector DataType
, columnNameStrings :: Vector String
} deriving Show
defaultTableProps :: RawTable -> TableProperties
defaultTableProps t =
TableProperties {
selectedColumns = Vec.replicate n True
, selectedColumnTypes = Vec.fromList types
, columnNameStrings = names
}
where
n = numberOfColumns t
genTypeToNumNom Binary = Nominal
genTypeToNumNom Natural = Numeric
genTypeToNumNom x = x
types = fmap genTypeToNumNom $ columnTypes $ smartParseTable t
names = Vec.fromList $ zipWith (\i n -> n ++ " (" ++ show i ++ ")") [0..] $
fmap (either (const "") id) $ columnNames t
updateTableProps :: (TableProperties -> TableProperties) -> GUIGlobalState -> GUIGlobalState
updateTableProps f gui = gui { tableProps = fmap f (tableProps gui) }
parseSelectedColumnsWithTarget :: Int -> RawTable -> TableProperties ->
Fallible (DataTable, DataColumn)
parseSelectedColumnsWithTarget targetIdx textTab tab = do
xParsed <- parseWithScheme (Vec.toList xTypes) xText
yParsed <- parseColumnAs yType yText
return (xParsed, yParsed)
where
-- text szetszed, utana parse
colTypes = selectedColumnTypes tab
-- x
allIndices = Vec.fromList [0..(numberOfColumns textTab - 1)]
selectedColIndices = List.delete targetIdx $
map fst $ filter snd $ zip (Vec.toList allIndices) $ Vec.toList $ selectedColumns tab
xTypes = Vec.fromList $ map (\i -> colTypes Vec.! i) selectedColIndices
xText = unsafeSelectColumns textTab selectedColIndices
-- y
yType = colTypes Vec.! targetIdx
yText = columnsVec textTab Vec.! targetIdx
type GUIState a = StateT GUIGlobalState IO a
type GUIError a = Either String a
getsGUI :: (GUIGlobalState -> a) -> GUIMVar a
getsGUI f = do
x <- asks $ \gui -> withMVar gui (return . f)
lift x
modifyGUI :: (GUIGlobalState -> GUIGlobalState) -> GUIMVar ()
modifyGUI f = do
x <- asks $ \gui -> modifyMVar_ gui (return . f)
lift x
type GUIMVar a = ReaderT (MVar GUIGlobalState) IO a
runGUIState' :: MVar GUIGlobalState -> GUIState a -> IO a
runGUIState' mvar s = modifyMVar mvar (fmap swap . runStateT s)
runGUIMVar' :: MVar GUIGlobalState -> GUIMVar a -> IO a
runGUIMVar' guiMVar f = (runReaderT f) guiMVar
runGUIStateWithMVar :: GUIState a -> GUIMVar a
runGUIStateWithMVar guiState = do
result <- asks (\guiMVar -> runGUIState' guiMVar guiState)
lift result
mainMarvinGUI = do
-- create GUI
initGUI
Just xml <- xmlNew "gui_main.glade"
-- widgets
window <- xmlGetWidget xml castToWindow "window_main"
windowSetTitle window "Marvin GUI"
fileChooserTrain <- xmlGetWidget xml castToFileChooserButton "file_chooser_train"
widgetSetTooltipText fileChooserTrain $ Just $
"Choose a file for training data."
buttonLoadTrain <- xmlGetWidget xml castToButton "button_load_train"
widgetSetTooltipText buttonLoadTrain $ Just $
"Load training data from comma separated file. " ++
"A file must be chosen to use this."
checkButtonHeader <- xmlGetWidget xml castToCheckButton "checkbutton_header"
vBoxAlgorithm <- xmlGetWidget xml castToVBox "vbox_algorithm"
-- table space
fixedTableSpace <- xmlGetWidget xml castToFixed "fixed_table"
tableHBox <- hBoxNew False 0
fixedPut fixedTableSpace tableHBox (0, 0)
-- fixedTableSpace <- xmlGetWidget xml castToScrolledWindow "scrolledwindow"
-- tableHBox <- hBoxNew False 0
-- scrolledWindowPut fixedTableSpace tableHBox
-- target column selector
fixedTargetSelector <- xmlGetWidget xml castToFixed "fixed_target_column_selector"
(combo, model, handler) <- mkTargetColumnSelector
fixedPut fixedTargetSelector combo (0, 0)
widgetSetTooltipText fixedTargetSelector $ Just $
"Select a target variable to use in supervised learning. " ++
"A table must be loaded with selected columns to use this."
-- algo selector fixed
fixedAlgorithmSelector <- xmlGetWidget xml castToFixed "fixed_algorithm_selector"
widgetSetTooltipText fixedAlgorithmSelector $ Just
"Select an algorithm."
-- algo config button
buttonConfigAlgorithm <- xmlGetWidget xml castToButton "button_config_algorithm"
widgetSetTooltipText buttonConfigAlgorithm $ Just
"Configure algorithm parameters. An algorithm must be chosen first to use this."
-- algo run button
buttonRunAlgorithm <- xmlGetWidget xml castToButton "button_run_algorithm"
widgetSetTooltipText buttonRunAlgorithm $ Just $
"Run algorithm. To use this, an algorithm must be chosen, " ++
"a table must be loaded with at least 2 selected columns, and a target variable must be chosen."
-- output textview
textViewOutput <- xmlGetWidget xml castToTextView "textview_output"
outputBuffer <- textBufferNew Nothing
textViewSetBuffer textViewOutput outputBuffer
-- default test loader
let defaultSplit = 0.8
let defaultTestLoader = Just $ Split defaultSplit
-- init state of load page
guiState <- newMVar $ emptyGUIState tableHBox (combo, model, handler)
buttonConfigAlgorithm buttonRunAlgorithm defaultTestLoader
let runGUIState = runGUIState' guiState
let runGUIMVar = runGUIMVar' guiState
-- widget events
on fileChooserTrain fileChooserButtonFileSet $
runGUIState $ onTrainFileSet fileChooserTrain buttonLoadTrain
onClicked buttonLoadTrain $ runGUIMVar $ do
onTableLoadButtonClicked checkButtonHeader
registerColumnSelectionListeners
onClicked buttonConfigAlgorithm $
runGUIState onConfigButtonClicked
-- algorithm run
onClicked buttonRunAlgorithm $ do
fallibleResult <- runGUIState onAlgorithmRun
case fallibleResult of
Right output -> textBufferSetText outputBuffer output
Left e -> runErrorDialog e
-- test loader
mkTestLoader guiState xml defaultSplit
-- algo selector
algoSelector <- mkAlgorithmSelector guiState algorithms
fixedPut fixedAlgorithmSelector algoSelector (0, 0)
-- destroy GUI
onDestroy window mainQuit
widgetShowAll window
mainGUI
onAlgorithmRun :: GUIState (Fallible String)
onAlgorithmRun = do
Just algo <- gets selectedAlgorithm
Just targetIdx <- gets selectedTarget
Just tabProps <- gets tableProps
Just params <- gets algorithmParams
Just testLoader <- gets testLoader
Just loadedTab <- gets loadedTable
split <- loadTrainTest loadedTab testLoader
let pipe = proc table -> do
(x, y) <- inject -< parseSelectedColumnsWithTarget targetIdx table tabProps
output <- runAlgorithm algo params -< (x, y)
returnA -< output
let fallibleResult = do
(train, test) <- split
(fitThenRun pipe) train test
return fallibleResult
runErrorDialog error = do
dialog <- dialogNew
windowSetTitle dialog "ERROR"
windowSetModal dialog True
windowSetDeletable dialog False
-- button
dialogAddButton dialog "OK" ResponseOk
vbox <- dialogGetUpper dialog
errorLabel <- labelNew $ Just $ show error
boxPackStart vbox errorLabel PackNatural 0
onDestroy dialog $ dialogResponse dialog ResponseDeleteEvent
widgetShowAll dialog
response <- dialogRun dialog
widgetDestroy dialog
loadTrainTest :: RawTable -> TestLoader -> GUIState (Fallible (RawTable, RawTable))
loadTrainTest table (Split ratio) = do
split <- lift $ trainTestSplit ratio table
return split
loadTrainTest train (Path testPath) = do
header <- gets trainHasHeader
let hasHeader = case header of
True -> HasHeader
False -> NoHeader
test <- lift $ fromCsv ',' hasHeader testPath
return $ (\t -> (train, t)) <$> test
mkTestLoader :: MVar GUIGlobalState -> GladeXML -> Double -> IO ()
mkTestLoader guiState xml defaultSplit = do
let runGUIMVar = runGUIMVar' guiState
-- spin
radioButtonSplit <- xmlGetWidget xml castToRadioButton "radiobutton_test_split"
widgetSetTooltipText radioButtonSplit $ Just $
"Split data randomly to provide a training and test datasets."
radioButtonLoad <- xmlGetWidget xml castToRadioButton "radiobutton_test_load"
widgetSetTooltipText radioButtonLoad $ Just $
"Load a file for test data separately from training data."
fileChooserTest <- xmlGetWidget xml castToFileChooserButton "file_chooser_test"
widgetSetTooltipText fileChooserTest $ Just $
"Load a file for test data separately from training data."
fixedTestSplit <- xmlGetWidget xml castToFixed "fixed_test_split"
widgetSetTooltipText fixedTestSplit $ Just $
"Set the ratio of training and test data."
spinButton <- spinButtonNewWithRange 0 1 0.05
spinButtonSetValue spinButton defaultSplit
fixedPut fixedTestSplit spinButton (0, 0)
let updateSpinnedValue = runGUIMVar $ do
val <- lift $ spinButtonGetValue spinButton
modifyGUI $ \gui -> gui { testLoader = Just (Split val) }
runGUIStateWithMVar checkToActivateRunButton
let updateTestFilePath = runGUIMVar $ do
path <- lift $ fileChooserGetFilename fileChooserTest
modifyGUI $ \gui -> gui { testLoader = fmap Path path }
runGUIStateWithMVar checkToActivateRunButton
afterValueSpinned spinButton $ do
updateSpinnedValue
on fileChooserTest fileChooserButtonFileSet $ do
updateTestFilePath
on radioButtonSplit toggled $ do
active <- toggleButtonGetActive radioButtonSplit
if active
then do
widgetSetSensitive spinButton True
widgetSetSensitive fileChooserTest False
updateSpinnedValue
else return ()
on radioButtonLoad toggled $ do
active <- toggleButtonGetActive radioButtonLoad
if active
then do
widgetSetSensitive spinButton False
widgetSetSensitive fileChooserTest True
updateTestFilePath
else return ()
return ()
-- register check change listener
registerColumnSelectionListeners :: GUIMVar ()
registerColumnSelectionListeners = do
Just headers <- getsGUI headerWidgets
let checkbuttons = map (\(_,c,_) -> c) $ Vec.toList headers
gui <- ask
let registerListener checkbutton idx =
on checkbutton toggled $ do
isActive <- toggleButtonGetActive checkbutton
runGUIMVar' gui $ onColumnSelectionChanged isActive idx
lift $ sequence $ zipWith registerListener checkbuttons [0..]
return ()
onConfigButtonClicked :: GUIState ()
onConfigButtonClicked = do
-- we can avoid check as button only activates when algo is selected
Just algorithm <- gets selectedAlgorithm
Just params <- gets algorithmParams
params' <- lift $ paramsToConfigWindow params
modify $ \x -> x { algorithmParams = Just params' }
return ()
onTableLoadButtonClicked :: CheckButton -> GUIMVar ()
onTableLoadButtonClicked checkButtonHeader = do
header <- lift $ toggleButtonGetActive checkButtonHeader
let hasHeader = case header of
True -> HasHeader
False -> NoHeader
-- path must be set when load button is active, so we can skip check
Just path <- getsGUI trainFilePath
textTable <- lift $ fromCsv ',' hasHeader path
case textTable of
Right tab -> onTableLoad tab
Left error -> lift $ runErrorDialog error
return ()
onTableLoad :: RawTable -> GUIMVar ()
onTableLoad textTable = do
modifyGUI $ \x -> x {
tableProps = Just (defaultTableProps textTable)
, loadedTable = Just textTable
}
gui <- ask
lift $ runGUIState' gui $ tableToHBox textTable
-- register type change listener
Just headers <- getsGUI headerWidgets
lift $ for (zip [0..] (Vec.toList headers)) $ \(i, (_,_,combo)) -> on combo changed $ do
active <- comboBoxGetActive combo
let update = case active of
-1 -> []
0 -> [(i, Numeric)]
1 -> [(i, Nominal)]
modifyMVar_ gui $ (>>> return) $ updateTableProps $ \tabProps ->
tabProps { selectedColumnTypes = Vec.unsafeUpd (selectedColumnTypes tabProps) update }
Just names <- getsGUI (fmap columnNameStrings . tableProps)
lift $ runGUIState' gui $ setNewRender (\i -> names Vec.! i)
updateTargetColumnSelector
onColumnSelectionChanged :: Bool -> Int -> GUIMVar ()
onColumnSelectionChanged isSelected columnIdx = do
-- there must be columns when user can change selection, so we can avoid check
Just selected <- getsGUI $ fmap selectedColumns . tableProps
let selected' = Vec.unsafeUpd selected [(columnIdx, isSelected)]
modifyGUI $ updateTableProps (\x -> x { selectedColumns = selected' })
updateTargetColumnSelector
return ()
updateTargetColumnSelector :: GUIMVar ()
updateTargetColumnSelector = do
-- there must be a selector initialized when updating it, so we can avoid check
(combo, model, handler) <- getsGUI targetColSelector
Just tabProps <- getsGUI tableProps
let selected = Vec.toList $ selectedColumns tabProps
let options = Vec.fromList $ map fst $ filter snd $ zip [0..] selected
gui <- ask
-- update selector
handler' <- lift $ do
listStoreClear model
traverse (listStoreAppend model) options
signalDisconnect handler
on combo changed $ do
active <- comboBoxGetActive combo
let option = case active of
-1 -> Nothing
i -> Just $ options Vec.! i
modifyMVar_ gui $ \x -> return $ x { selectedTarget = option }
withMVar gui $ \x -> (runStateT checkToActivateRunButton) x
return ()
modifyGUI $ \x -> x { targetColSelector = (combo, model, handler') }
getsGUI $ \gui -> (runStateT checkToActivateRunButton) gui
return ()
removeAllChildren :: ContainerClass c => c -> IO ()
removeAllChildren c = do
children <- containerGetChildren c
traverse (containerRemove c) children
return ()
tableToHBox :: RawTable -> GUIState ()
tableToHBox tab = do
hbox <- gets tableBox
cols <- lift $ sequence $ Vec.fromList $ zipWith columnToVBox [0..] $ columns tab
let (vboxes, headers) = Vec.unzip cols
modify (\x -> x { headerWidgets = Just headers })
-- clear and pack hbox containing the table
lift $ do
removeAllChildren hbox
traverse (\col -> boxPackStart hbox col PackNatural 0) $ vboxes
widgetShowAll hbox
return ()
columnToVBox :: Int -> RawColumn -> IO (VBox, HeaderWidget)
columnToVBox idx col = do
let defaultType = either (const Nominal) (const Numeric)
(parseColumn col :: Fallible NumericColumn)
-- header
let name = colName idx col
(headerBox, checkbutton, combobox) <- mkHeaderWidget name defaultType
-- column
let vals = toStrCol col
treeView <- vecToTreeView vals
-- default type
-- assembly
vbox <- vBoxNew False 0
boxPackStart vbox headerBox PackNatural 0
boxPackStart vbox treeView PackNatural 0
return (vbox, (headerBox, checkbutton, combobox))
toStrCol :: RawColumn -> Vector String
toStrCol (RawColumn (_, vals)) = Vec.map bsToString vals --columnToPrettyPrintables >>> Vec.map defaultPrettyPrint
colName :: Int -> RawColumn -> String
colName idx t =
(\n -> n ++ " (" ++ show idx ++ ")") $
either (const "") id $ columnName t
vecToTreeView :: Vector String -> IO TreeView
vecToTreeView vec = do
model <- listStoreNew (Vec.toList vec)
treeView <- treeViewNewWithModel model
-- column
col <- treeViewColumnNew
rend <- cellRendererTextNew
treeViewColumnPackStart col rend True
cellLayoutSetAttributes col rend model (\row -> [ cellText := row ])
treeViewColumnSetExpand col True
treeViewAppendColumn treeView col
-- disable selection
selection <- treeViewGetSelection treeView
treeSelectionSetMode selection SelectionNone
-- TreeView settings
treeViewSetHeadersVisible treeView False
widgetShowAll treeView
return treeView
removeAllRawColumns view = do
cols <- treeViewGetColumns view
traverse (treeViewRemoveColumn view) cols
mkAlgorithmSelector :: MVar GUIGlobalState -> [AlgorithmDescriptor] -> IO ComboBox
mkAlgorithmSelector guiState algoDescs =
mkComboBox (Vec.fromList algoDescs) show $
\selected -> modifyMVar_ guiState $ \gui -> do
let button = configButton gui
widgetSetSensitive button True
let gui' = gui {
selectedAlgorithm = selected,
algorithmParams = fmap defaultAlgoParams selected
}
(runStateT checkToActivateRunButton) gui'
return gui'
checkToActivateRunButton :: GUIState ()
checkToActivateRunButton = do
button <- gets runButton
canActivate <- gets canActivateRunButton
lift $ widgetSetSensitive button canActivate
{-
run button should be active iff
. algorithm is selected
. target column is selected
. at least 2 columns are selected
. test loader is set
should check whenever selection changes or algorithm changes or test loader changes
(if we remember target column, than in that case too!)
-}
canActivateRunButton :: GUIGlobalState -> Bool
canActivateRunButton gui =
algorithmIsSelected && targetColumnIsSelected && numOfSelectedColumns > 1 && testLoaderSet
where
algorithmIsSelected = isJust $ selectedAlgorithm gui
targetColumnIsSelected = isJust $ selectedTarget gui
numOfSelectedColumns = let count = length . filter id in
maybe 0 (count . Vec.toList . selectedColumns) $ tableProps gui
testLoaderSet = isJust $ testLoader gui
mkTargetColumnSelector :: IO (ComboBox, ListStore Int, ConnectId ComboBox)
mkTargetColumnSelector = do
(combo, model) <- mkComboBox' Vec.empty (const "NO_RENDER")
widgetSetSizeRequest combo 150 30
handler <- on combo changed $ return ()
return (combo, model, handler)
mkComboBox :: Vector a -> (a -> String) -> (Maybe a -> IO ()) -> IO ComboBox
mkComboBox options rend onChange = do
(combo, _) <- mkComboBox' options rend
on combo changed $ do
active <- comboBoxGetActive combo
let option = case active of
-1 -> Nothing
i -> Just $ options Vec.! i
onChange option
return combo
setNewRender :: (Int -> String) -> GUIState ()
setNewRender render = do
(combo, store, handler) <- gets targetColSelector
lift $ do
let textColumn = makeColumnIdString 0
customStoreSetColumn store textColumn render -- set the extraction function
ren <- cellRendererTextNew
cellLayoutClear combo
cellLayoutPackEnd combo ren False
cellLayoutSetAttributes combo ren store
(\txt -> [cellText := render txt])
mkComboBox' :: Vector a -> (a -> String) -> IO (ComboBox, ListStore a)
mkComboBox' options render = do
let textColumn = makeColumnIdString 0
store <- listStoreNew $ Vec.toList options
customStoreSetColumn store textColumn render -- set the extraction function
combo <- comboBoxNewWithModel store
ren <- cellRendererTextNew
cellLayoutPackEnd combo ren False
cellLayoutSetAttributes combo ren store
(\txt -> [cellText := render txt])
widgetShow combo
return (combo, store)
mkHeaderWidget :: ColumnName -> DataType -> IO (VBox, CheckButton, ComboBox)
mkHeaderWidget name defaultType = do
let allSameSize = False
let spaceBetween = 20
box <- vBoxNew allSameSize spaceBetween
labelName <- labelNew $ Just name
widgetShow labelName
checkbutton <- checkButtonNew
toggleButtonSetActive checkbutton True
widgetShow checkbutton
-- combo box
(combo, _) <- mkComboBox' (Vec.fromList [Numeric, Nominal]) show
comboBoxSetActive combo $ case defaultType of
Numeric -> 0
Nominal -> 1
boxPackStart box checkbutton PackNatural 0
boxPackStart box combo PackNatural 0
boxPackStart box labelName PackNatural 0
widgetShow box
return (box, checkbutton, combo)
toStrCols :: DataTable -> [Vector String]
toStrCols t =
Vec.toList $ printCols
where
dataCols = Vec.map dataColumnToPrettyPrintables $ columnsVec t
printCols = (Vec.map . Vec.map) defaultPrettyPrint dataCols
exampleDT :: DataTable
exampleDT = smartParseTable exampleRawTab
exampleTrain :: RawTable
exampleTrain = exampleNamedFromCols [("a", ["2"]), ("b", ["20"]), ("c", ["200"])]
exampleTest :: RawTable
exampleTest = exampleNamedFromCols [("a", ["1"]), ("b", ["10"]), ("c", ["100"])]
exampleRawTab :: RawTable
exampleRawTab = exampleNamedFromCols [("a", ["1","2"]), ("b", ["10","20"]), ("c", ["100","200"])]
exampleNamedFromCols :: [(String, [String])] -> RawTable
exampleNamedFromCols cols =
let Right t = tab in t
where
tab = do
namedTable <- for cols $ \(name, vals) -> do
rawCol <- (fromListToRaw vals)
nameColumn name rawCol
fromColumns namedTable
onTrainFileSet :: FileChooserButton -> Button -> GUIState ()
onTrainFileSet fileChooserTrain buttonLoadTrain = do
(Just f) <- lift $ fileChooserGetFilename fileChooserTrain
-- change state
modify $ \x -> x { trainFilePath = Just f }
-- activate load button
lift $ widgetSetSensitive buttonLoadTrain True
unsafeSelectColumns :: RawTable -> [Int] -> RawTable
unsafeSelectColumns t = unsafeFromCols . Vec.fromList . map (\i -> cols Vec.! i)
where
cols = columnsVec t
| gaborhermann/marvin | src/Marvin/GUI/Main.hs | apache-2.0 | 23,273 | 1 | 21 | 4,501 | 6,420 | 3,141 | 3,279 | 517 | 3 |
module Braxton.A284431 (a284431) where
import Helpers.BraxtonHelper (enumerateSequences, SymmetricRelation(..), ReflexiveRelation(..))
a284431 n = length $ enumerateA284431 n n
enumerateA284431 = enumerateSequences NonReflexive Symmetric sum
-- (1,2,1,6,2,42,12,116,...)
-- Counts A282166
| peterokagey/haskellOEIS | src/Braxton/A284431.hs | apache-2.0 | 290 | 0 | 6 | 29 | 66 | 39 | 27 | 4 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-- | Smart constructor and destructor functions for CoreHW
module CLaSH.Core.Util where
import Data.HashMap.Lazy (HashMap)
import Unbound.Generics.LocallyNameless (Fresh, bind, embed, unbind, unembed,
unrebind, unrec)
import Unbound.Generics.LocallyNameless.Unsafe (unsafeUnbind)
import CLaSH.Core.DataCon (dcType)
import CLaSH.Core.Literal (literalType)
import CLaSH.Core.Pretty (showDoc)
import CLaSH.Core.Term (Pat (..), Term (..), TmName)
import CLaSH.Core.Type (Kind, TyName, Type (..), applyTy,
isFunTy, isPolyFunCoreTy, mkFunTy,
splitFunTy)
import CLaSH.Core.TyCon (TyCon, TyConName)
import CLaSH.Core.Var (Id, TyVar, Var (..), varType)
import CLaSH.Util
-- | Type environment/context
type Gamma = HashMap TmName Type
-- | Kind environment/context
type Delta = HashMap TyName Kind
-- | Determine the type of a term
termType :: (Functor m, Fresh m)
=> HashMap TyConName TyCon
-> Term
-> m Type
termType m e = case e of
Var t _ -> return t
Data dc -> return $ dcType dc
Literal l -> return $ literalType l
Prim _ t -> return t
Lam b -> do (v,e') <- unbind b
mkFunTy (unembed $ varType v) <$> termType m e'
TyLam b -> do (tv,e') <- unbind b
ForAllTy <$> bind tv <$> termType m e'
App _ _ -> case collectArgs e of
(fun, args) -> termType m fun >>=
(flip (applyTypeToArgs m) args)
TyApp e' ty -> termType m e' >>= (\f -> applyTy m f ty)
Letrec b -> do (_,e') <- unbind b
termType m e'
Case _ ty _ -> return ty
-- | Split a (Type)Application in the applied term and it arguments
collectArgs :: Term
-> (Term, [Either Term Type])
collectArgs = go []
where
go args (App e1 e2) = go (Left e2:args) e1
go args (TyApp e t) = go (Right t:args) e
go args e = (e, args)
-- | Split a (Type)Abstraction in the bound variables and the abstracted term
collectBndrs :: Fresh m
=> Term
-> m ([Either Id TyVar], Term)
collectBndrs = go []
where
go bs (Lam b) = do
(v,e') <- unbind b
go (Left v:bs) e'
go bs (TyLam b) = do
(tv,e') <- unbind b
go (Right tv:bs) e'
go bs e' = return (reverse bs,e')
-- | Get the result type of a polymorphic function given a list of arguments
applyTypeToArgs :: Fresh m
=> HashMap TyConName TyCon
-> Type
-> [Either Term Type]
-> m Type
applyTypeToArgs _ opTy [] = return opTy
applyTypeToArgs m opTy (Right ty:args) = applyTy m opTy ty >>=
(flip (applyTypeToArgs m) args)
applyTypeToArgs m opTy (Left e:args) = case splitFunTy m opTy of
Just (_,resTy) -> applyTypeToArgs m resTy args
Nothing -> error $
concat [ $(curLoc)
, "applyTypeToArgs splitFunTy: not a funTy:\n"
, "opTy: "
, showDoc opTy
, "\nTerm: "
, showDoc e
, "\nOtherArgs: "
, unlines (map (either showDoc showDoc) args)
]
-- | Get the list of term-binders out of a DataType pattern
patIds :: Pat -> [Id]
patIds (DataPat _ ids) = snd $ unrebind ids
patIds _ = []
-- | Make a type variable
mkTyVar :: Kind
-> TyName
-> TyVar
mkTyVar tyKind tyName = TyVar tyName (embed tyKind)
-- | Make a term variable
mkId :: Type
-> TmName
-> Id
mkId tmType tmName = Id tmName (embed tmType)
-- | Abstract a term over a list of term and type variables
mkAbstraction :: Term
-> [Either Id TyVar]
-> Term
mkAbstraction = foldr (either (Lam `dot` bind) (TyLam `dot` bind))
-- | Abstract a term over a list of term variables
mkTyLams :: Term
-> [TyVar]
-> Term
mkTyLams tm = mkAbstraction tm . map Right
-- | Abstract a term over a list of type variables
mkLams :: Term
-> [Id]
-> Term
mkLams tm = mkAbstraction tm . map Left
-- | Apply a list of types and terms to a term
mkApps :: Term
-> [Either Term Type]
-> Term
mkApps = foldl (\e a -> either (App e) (TyApp e) a)
-- | Apply a list of terms to a term
mkTmApps :: Term
-> [Term]
-> Term
mkTmApps = foldl App
-- | Apply a list of types to a term
mkTyApps :: Term
-> [Type]
-> Term
mkTyApps = foldl TyApp
-- | Does a term have a function type?
isFun :: (Functor m, Fresh m)
=> HashMap TyConName TyCon
-> Term
-> m Bool
isFun m t = fmap (isFunTy m) $ (termType m) t
-- | Does a term have a function or polymorphic type?
isPolyFun :: (Functor m, Fresh m)
=> HashMap TyConName TyCon
-> Term
-> m Bool
isPolyFun m t = isPolyFunCoreTy m <$> termType m t
-- | Is a term a term-abstraction?
isLam :: Term
-> Bool
isLam (Lam _) = True
isLam _ = False
-- | Is a term a recursive let-binding?
isLet :: Term
-> Bool
isLet (Letrec _) = True
isLet _ = False
-- | Is a term a variable reference?
isVar :: Term
-> Bool
isVar (Var _ _) = True
isVar _ = False
-- | Is a term a datatype constructor?
isCon :: Term
-> Bool
isCon (Data _) = True
isCon _ = False
-- | Is a term a primitive?
isPrim :: Term
-> Bool
isPrim (Prim _ _) = True
isPrim _ = False
-- | Make variable reference out of term variable
idToVar :: Id
-> Term
idToVar (Id nm tyE) = Var (unembed tyE) nm
idToVar tv = error $ $(curLoc) ++ "idToVar: tyVar: " ++ showDoc tv
-- | Make a term variable out of a variable reference
varToId :: Term
-> Id
varToId (Var ty nm) = Id nm (embed ty)
varToId e = error $ $(curLoc) ++ "varToId: not a var: " ++ showDoc e
termSize :: Term
-> Int
termSize (Var _ _) = 1
termSize (Data _) = 1
termSize (Literal _) = 1
termSize (Prim _ _) = 1
termSize (Lam b) = let (_,e) = unsafeUnbind b
in termSize e + 1
termSize (TyLam b) = let (_,e) = unsafeUnbind b
in termSize e
termSize (App e1 e2) = termSize e1 + termSize e2
termSize (TyApp e _) = termSize e
termSize (Letrec b) = let (bndrsR,body) = unsafeUnbind b
bndrSzs = map (termSize . unembed . snd) (unrec bndrsR)
bodySz = termSize body
in sum (bodySz:bndrSzs)
termSize (Case subj _ alts) = let subjSz = termSize subj
altSzs = map (termSize . snd . unsafeUnbind) alts
in sum (subjSz:altSzs)
| christiaanb/clash-compiler | clash-lib/src/CLaSH/Core/Util.hs | bsd-2-clause | 7,155 | 0 | 15 | 2,653 | 2,182 | 1,127 | 1,055 | 166 | 10 |
module Parser (Token(..), ParsingData(..), initParsingData, post, resultAccept, resultError) where
import SemanticData
type Value = MyType
data Token = End | UMns | Ast | Sla | Pls | Mns | LParen | RParen | Id
deriving (Enum, Eq)
data StackFrame = StackFrame {
state :: ParsingData -> Token -> Value -> (ParsingData, Bool),
gotof :: ParsingData -> Int -> Value -> (ParsingData, Bool),
value :: Value
}
data Stack = Stack {
stack :: [StackFrame],
tmp :: [StackFrame],
gap :: Int
}
data ParsingData = ParsingData {
accepted :: Bool,
parsingError :: Bool,
acceptedValue :: Value,
parsingStack :: Stack
}
resetTmp s = Stack (stack s) [] (length (stack s))
commitTmp s = Stack ((tmp s) ++ (drop ((length (stack s)) - (gap s)) (stack s))) (tmp s) (gap s)
push s f = Stack (stack s) (f : (tmp s)) (gap s)
pop s n =
if (length (tmp s)) < n
then Stack (stack s) [] ((gap s) - (n - (length (tmp s))))
else Stack (stack s) (drop n (tmp s)) (gap s)
top s =
if (length (tmp s)) > 0
then head (tmp s)
else (stack s) !! ((length (stack s)) - 1 - ((gap s) - 1))
getArg s b i =
let n = length (tmp s)
in if (b - i) <= n
then (tmp s) !! (n - 1 - (n - (b - i)))
else (stack s) !! ((length (stack s)) - 1 - (gap s) + (b - n) - i)
clear s = Stack [] (tmp s) (gap s)
stackTop p = top (parsingStack p)
getStackArg p b i = value (getArg (parsingStack p) b i)
pushStack p s g v = ParsingData (accepted p) (parsingError p) (acceptedValue p) (push (parsingStack p) (StackFrame s g v))
popStack p n = ParsingData (accepted p) (parsingError p) (acceptedValue p) (pop (parsingStack p) n)
clearStack p = ParsingData (accepted p) (parsingError p) (acceptedValue p) (clear (parsingStack p))
resetTmpStack p = ParsingData (accepted p) (parsingError p) (acceptedValue p) (resetTmp (parsingStack p))
commitTmpStack p = ParsingData (accepted p) (parsingError p) (acceptedValue p) (commitTmp (parsingStack p))
reset = commitTmpStack (pushStack (ParsingData False False defaultValue (Stack [] [] 0)) state0 gotof0 defaultValue)
initParsingData = reset
iteration p t v =
let n = (state (stackTop p)) p t v
tFirst (a, _) = a
tSecond (_, b) = b
in if tSecond n
then iteration (tFirst n) t v
else (tFirst n)
wrappedCommit p =
let p' = commitTmpStack p
in p'
post p t v =
let p' = iteration (commitTmpStack p) t v
in if parsingError p'
then p'
else wrappedCommit p'
resultAccept p = accepted p
resultError p = parsingError p
call0makeUMns p i b i0 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeUMns (getStackArg p b i0))
call0makeMlt p i b i0 i1 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeMlt (getStackArg p b i0) (getStackArg p b i1))
call0makeDiv p i b i0 i1 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeDiv (getStackArg p b i0) (getStackArg p b i1))
call0makeAdd p i b i0 i1 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeAdd (getStackArg p b i0) (getStackArg p b i1))
call0makeSub p i b i0 i1 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeSub (getStackArg p b i0) (getStackArg p b i1))
call0makeId p i b i0 =
let p' = popStack p b
in (gotof (stackTop p')) p' i (makeId (getStackArg p b i0))
gotof0 p i v =
case i of
0 -> (pushStack p state13 gotof13 v, True)
_ -> (p, False)
state0 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof1 p i v =
case i of
0 -> (pushStack p state7 gotof7 v, True)
_ -> (p, False)
state1 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof2 p i v =
case i of
0 -> (pushStack p state8 gotof8 v, True)
_ -> (p, False)
state2 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof3 p i v =
case i of
0 -> (pushStack p state9 gotof9 v, True)
_ -> (p, False)
state3 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof4 p i v =
case i of
0 -> (pushStack p state10 gotof10 v, True)
_ -> (p, False)
state4 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof5 p i v =
case i of
0 -> (pushStack p state11 gotof11 v, True)
_ -> (p, False)
state5 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof6 p i v =
case i of
0 -> (pushStack p state12 gotof12 v, True)
_ -> (p, False)
state6 p t v =
case t of
Mns -> (pushStack p state1 gotof1 v, False)
LParen -> (pushStack p state2 gotof2 v, False)
Id -> (pushStack p state14 gotof14 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof7 p i v =
case i of
_ -> (p, True)
state7 p t v =
case t of
Ast -> call0makeUMns p 0 2 1
Sla -> call0makeUMns p 0 2 1
Pls -> call0makeUMns p 0 2 1
Mns -> call0makeUMns p 0 2 1
RParen -> call0makeUMns p 0 2 1
End -> call0makeUMns p 0 2 1
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof8 p i v =
case i of
_ -> (p, True)
state8 p t v =
case t of
Ast -> (pushStack p state3 gotof3 v, False)
Sla -> (pushStack p state4 gotof4 v, False)
Pls -> (pushStack p state5 gotof5 v, False)
Mns -> (pushStack p state6 gotof6 v, False)
RParen -> (pushStack p state15 gotof15 v, False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof9 p i v =
case i of
_ -> (p, True)
state9 p t v =
case t of
Ast -> call0makeMlt p 0 3 0 2
Sla -> call0makeMlt p 0 3 0 2
Pls -> call0makeMlt p 0 3 0 2
Mns -> call0makeMlt p 0 3 0 2
RParen -> call0makeMlt p 0 3 0 2
End -> call0makeMlt p 0 3 0 2
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof10 p i v =
case i of
_ -> (p, True)
state10 p t v =
case t of
Ast -> call0makeDiv p 0 3 0 2
Sla -> call0makeDiv p 0 3 0 2
Pls -> call0makeDiv p 0 3 0 2
Mns -> call0makeDiv p 0 3 0 2
RParen -> call0makeDiv p 0 3 0 2
End -> call0makeDiv p 0 3 0 2
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof11 p i v =
case i of
_ -> (p, True)
state11 p t v =
case t of
Ast -> (pushStack p state3 gotof3 v, False)
Sla -> (pushStack p state4 gotof4 v, False)
Pls -> call0makeAdd p 0 3 0 2
Mns -> call0makeAdd p 0 3 0 2
RParen -> call0makeAdd p 0 3 0 2
End -> call0makeAdd p 0 3 0 2
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof12 p i v =
case i of
_ -> (p, True)
state12 p t v =
case t of
Ast -> (pushStack p state3 gotof3 v, False)
Sla -> (pushStack p state4 gotof4 v, False)
Pls -> call0makeSub p 0 3 0 2
Mns -> call0makeSub p 0 3 0 2
RParen -> call0makeSub p 0 3 0 2
End -> call0makeSub p 0 3 0 2
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof13 p i v =
case i of
_ -> (p, True)
state13 p t v =
case t of
Ast -> (pushStack p state3 gotof3 v, False)
Sla -> (pushStack p state4 gotof4 v, False)
Pls -> (pushStack p state5 gotof5 v, False)
Mns -> (pushStack p state6 gotof6 v, False)
End -> (ParsingData True (parsingError p) (getStackArg p 1 0) (parsingStack p), False)
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof14 p i v =
case i of
_ -> (p, True)
state14 p t v =
case t of
Ast -> call0makeId p 0 1 0
Sla -> call0makeId p 0 1 0
Pls -> call0makeId p 0 1 0
Mns -> call0makeId p 0 1 0
RParen -> call0makeId p 0 1 0
End -> call0makeId p 0 1 0
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
gotof15 p i v =
case i of
_ -> (p, True)
state15 p t v =
case t of
Ast -> call0makeId p 0 3 1
Sla -> call0makeId p 0 3 1
Pls -> call0makeId p 0 3 1
Mns -> call0makeId p 0 3 1
RParen -> call0makeId p 0 3 1
End -> call0makeId p 0 3 1
_ -> (ParsingData (accepted p) True (acceptedValue p) (parsingStack p), False)
-- module SemanticData (MyType, defaultValue, makeUMns, makeMlt, makeDiv, makeAdd, makeSub, makeId) where
| marionette-of-u/kp19pp | sample/haskell/Parser.hs | bsd-2-clause | 9,651 | 0 | 17 | 2,815 | 4,577 | 2,333 | 2,244 | 255 | 7 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module ETA.TypeCheck.TcValidity (
Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
expectedKindInCtxt,
checkValidTheta, checkValidFamPats,
checkValidInstance, validDerivPred,
checkInstTermination, checkValidTyFamInst, checkTyFamFreeness,
checkValidTyFamEqn, checkConsistentFamInst,
arityErr, badATErr, ClsInfo
) where
-- friends:
import ETA.TypeCheck.TcUnify ( tcSubType_NC )
import ETA.TypeCheck.TcSimplify ( simplifyAmbiguityCheck )
import ETA.Types.TypeRep
import ETA.TypeCheck.TcType
import ETA.TypeCheck.TcMType
import ETA.Prelude.TysWiredIn ( coercibleClass )
import ETA.Types.Type
import ETA.Types.Unify( tcMatchTyX )
import ETA.Types.Kind
import ETA.Types.CoAxiom
import ETA.Types.Class
import ETA.Types.TyCon
import ETA.BasicTypes.Unique ( hasKey )
-- others:
import ETA.HsSyn.HsSyn -- HsType
import ETA.TypeCheck.TcRnMonad -- TcType, amongst others
import ETA.TypeCheck.FunDeps
import ETA.BasicTypes.Name
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.Main.ErrUtils
import ETA.Main.DynFlags
import ETA.Utils.Util
import ETA.Utils.ListSetOps
import ETA.BasicTypes.SrcLoc
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.FastString
import Control.Monad
import Data.Maybe
import Data.List ( (\\) )
{-
************************************************************************
* *
Checking for ambiguity
* *
************************************************************************
-}
checkAmbiguity :: UserTypeCtxt -> Type -> TcM ()
checkAmbiguity ctxt ty
| GhciCtxt <- ctxt -- Allow ambiguous types in GHCi's :kind command
= return () -- E.g. type family T a :: * -- T :: forall k. k -> *
-- Then :k T should work in GHCi, not complain that
-- (T k) is ambiguous!
| InfSigCtxt {} <- ctxt -- See Note [Validity of inferred types] in TcBinds
= return ()
| otherwise
= do { traceTc "Ambiguity check for" (ppr ty)
; let free_tkvs = varSetElemsKvsFirst (closeOverKinds (tyVarsOfType ty))
; (subst, _tvs) <- tcInstSkolTyVars free_tkvs
; let ty' = substTy subst ty
-- The type might have free TyVars, esp when the ambiguity check
-- happens during a call to checkValidType,
-- so we skolemise them as TcTyVars.
-- Tiresome; but the type inference engine expects TcTyVars
-- NB: The free tyvar might be (a::k), so k is also free
-- and we must skolemise it as well. Hence closeOverKinds.
-- (Trac #9222)
-- Solve the constraints eagerly because an ambiguous type
-- can cause a cascade of further errors. Since the free
-- tyvars are skolemised, we can safely use tcSimplifyTop
; (_wrap, wanted) <- addErrCtxtM (mk_msg ty') $
captureConstraints $
tcSubType_NC ctxt ty' ty'
; simplifyAmbiguityCheck ty wanted
; traceTc "Done ambiguity check for" (ppr ty) }
where
mk_msg ty tidy_env
= do { allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes
; (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env ty
; return (tidy_env', mk_msg tidy_ty $$ ppWhen (not allow_ambiguous) ambig_msg) }
where
mk_msg ty = pprSigCtxt ctxt (ptext (sLit "the ambiguity check for")) (ppr ty)
ambig_msg = ptext (sLit "To defer the ambiguity check to use sites, enable AllowAmbiguousTypes")
{-
************************************************************************
* *
Checking validity of a user-defined type
* *
************************************************************************
When dealing with a user-written type, we first translate it from an HsType
to a Type, performing kind checking, and then check various things that should
be true about it. We don't want to perform these checks at the same time
as the initial translation because (a) they are unnecessary for interface-file
types and (b) when checking a mutually recursive group of type and class decls,
we can't "look" at the tycons/classes yet. Also, the checks are are rather
diverse, and used to really mess up the other code.
One thing we check for is 'rank'.
Rank 0: monotypes (no foralls)
Rank 1: foralls at the front only, Rank 0 inside
Rank 2: foralls at the front, Rank 1 on left of fn arrow,
basic ::= tyvar | T basic ... basic
r2 ::= forall tvs. cxt => r2a
r2a ::= r1 -> r2a | basic
r1 ::= forall tvs. cxt => r0
r0 ::= r0 -> r0 | basic
Another thing is to check that type synonyms are saturated.
This might not necessarily show up in kind checking.
type A i = i
data T k = MkT (k Int)
f :: T A -- BAD!
-}
checkValidType :: UserTypeCtxt -> Type -> TcM ()
-- Checks that the type is valid for the given context
-- Not used for instance decls; checkValidInstance instead
checkValidType ctxt ty
= do { traceTc "checkValidType" (ppr ty <+> text "::" <+> ppr (typeKind ty))
; rankn_flag <- xoptM Opt_RankNTypes
; let gen_rank :: Rank -> Rank
gen_rank r | rankn_flag = ArbitraryRank
| otherwise = r
rank1 = gen_rank r1
rank0 = gen_rank r0
r0 = rankZeroMonoType
r1 = LimitedRank True r0
rank
= case ctxt of
DefaultDeclCtxt-> MustBeMonoType
ResSigCtxt -> MustBeMonoType
PatSigCtxt -> rank0
RuleSigCtxt _ -> rank1
TySynCtxt _ -> rank0
ExprSigCtxt -> rank1
FunSigCtxt _ -> rank1
InfSigCtxt _ -> ArbitraryRank -- Inferred type
ConArgCtxt _ -> rank1 -- We are given the type of the entire
-- constructor, hence rank 1
ForSigCtxt _ -> rank1
SpecInstCtxt -> rank1
ThBrackCtxt -> rank1
GhciCtxt -> ArbitraryRank
_ -> panic "checkValidType"
-- Can't happen; not used for *user* sigs
-- Check the internal validity of the type itself
; check_type ctxt rank ty
-- Check that the thing has kind Type, and is lifted if necessary.
-- Do this *after* check_type, because we can't usefully take
-- the kind of an ill-formed type such as (a~Int)
; check_kind ctxt ty
; traceTc "checkValidType done" (ppr ty <+> text "::" <+> ppr (typeKind ty)) }
checkValidMonoType :: Type -> TcM ()
checkValidMonoType ty = check_mono_type SigmaCtxt MustBeMonoType ty
check_kind :: UserTypeCtxt -> TcType -> TcM ()
-- Check that the type's kind is acceptable for the context
check_kind ctxt ty
| TySynCtxt {} <- ctxt
, returnsConstraintKind actual_kind
= do { ck <- xoptM Opt_ConstraintKinds
; if ck
then when (isConstraintKind actual_kind)
(do { dflags <- getDynFlags
; check_pred_ty dflags ctxt ty })
else addErrTc (constraintSynErr actual_kind) }
| Just k <- expectedKindInCtxt ctxt
= checkTc (tcIsSubKind actual_kind k) (kindErr actual_kind)
| otherwise
= return () -- Any kind will do
where
actual_kind = typeKind ty
-- Depending on the context, we might accept any kind (for instance, in a TH
-- splice), or only certain kinds (like in type signatures).
expectedKindInCtxt :: UserTypeCtxt -> Maybe Kind
expectedKindInCtxt (TySynCtxt _) = Nothing -- Any kind will do
expectedKindInCtxt ThBrackCtxt = Nothing
expectedKindInCtxt GhciCtxt = Nothing
expectedKindInCtxt (ForSigCtxt _) = Just liftedTypeKind
expectedKindInCtxt InstDeclCtxt = Just constraintKind
expectedKindInCtxt SpecInstCtxt = Just constraintKind
expectedKindInCtxt _ = Just openTypeKind
{-
Note [Higher rank types]
~~~~~~~~~~~~~~~~~~~~~~~~
Technically
Int -> forall a. a->a
is still a rank-1 type, but it's not Haskell 98 (Trac #5957). So the
validity checker allow a forall after an arrow only if we allow it
before -- that is, with Rank2Types or RankNTypes
-}
data Rank = ArbitraryRank -- Any rank ok
| LimitedRank -- Note [Higher rank types]
Bool -- Forall ok at top
Rank -- Use for function arguments
| MonoType SDoc -- Monotype, with a suggestion of how it could be a polytype
| MustBeMonoType -- Monotype regardless of flags
rankZeroMonoType, tyConArgMonoType, synArgMonoType :: Rank
rankZeroMonoType = MonoType (ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types"))
tyConArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use ImpredicativeTypes"))
synArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use LiberalTypeSynonyms"))
funArgResRank :: Rank -> (Rank, Rank) -- Function argument and result
funArgResRank (LimitedRank _ arg_rank) = (arg_rank, LimitedRank (forAllAllowed arg_rank) arg_rank)
funArgResRank other_rank = (other_rank, other_rank)
forAllAllowed :: Rank -> Bool
forAllAllowed ArbitraryRank = True
forAllAllowed (LimitedRank forall_ok _) = forall_ok
forAllAllowed _ = False
----------------------------------------
check_mono_type :: UserTypeCtxt -> Rank
-> KindOrType -> TcM () -- No foralls anywhere
-- No unlifted types of any kind
check_mono_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check kinds?
| otherwise
= do { check_type ctxt rank ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
check_type :: UserTypeCtxt -> Rank -> Type -> TcM ()
-- The args say what the *type context* requires, independent
-- of *flag* settings. You test the flag settings at usage sites.
--
-- Rank is allowed rank for function args
-- Rank 0 means no for-alls anywhere
check_type ctxt rank ty
| not (null tvs && null theta)
= do { checkTc (forAllAllowed rank) (forAllTyErr rank ty)
-- Reject e.g. (Maybe (?x::Int => Int)),
-- with a decent error message
; check_valid_theta ctxt theta
; check_type ctxt rank tau -- Allow foralls to right of arrow
; checkAmbiguity ctxt ty }
where
(tvs, theta, tau) = tcSplitSigmaTy ty
check_type _ _ (TyVarTy _) = return ()
check_type ctxt rank (FunTy arg_ty res_ty)
= do { check_type ctxt arg_rank arg_ty
; check_type ctxt res_rank res_ty }
where
(arg_rank, res_rank) = funArgResRank rank
check_type ctxt rank (AppTy ty1 ty2)
= do { check_arg_type ctxt rank ty1
; check_arg_type ctxt rank ty2 }
check_type ctxt rank ty@(TyConApp tc tys)
| isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
= check_syn_tc_app ctxt rank ty tc tys
| isUnboxedTupleTyCon tc = check_ubx_tuple ctxt ty tys
| otherwise = mapM_ (check_arg_type ctxt rank) tys
check_type _ _ (LitTy {}) = return ()
check_type _ _ ty = pprPanic "check_type" (ppr ty)
----------------------------------------
check_syn_tc_app :: UserTypeCtxt -> Rank -> KindOrType
-> TyCon -> [KindOrType] -> TcM ()
-- Used for type synonyms and type synonym families,
-- which must be saturated,
-- but not data families, which need not be saturated
check_syn_tc_app ctxt rank ty tc tys
| tc_arity <= n_args -- Saturated
-- Check that the synonym has enough args
-- This applies equally to open and closed synonyms
-- It's OK to have an *over-applied* type synonym
-- data Tree a b = ...
-- type Foo a = Tree [a]
-- f :: Foo a b -> ...
= do { -- See Note [Liberal type synonyms]
; liberal <- xoptM Opt_LiberalTypeSynonyms
; if not liberal || isTypeFamilyTyCon tc then
-- For H98 and synonym families, do check the type args
mapM_ check_arg tys
else -- In the liberal case (only for closed syns), expand then check
case tcView ty of
Just ty' -> check_type ctxt rank ty'
Nothing -> pprPanic "check_tau_type" (ppr ty) }
| GhciCtxt <- ctxt -- Accept under-saturated type synonyms in
-- GHCi :kind commands; see Trac #7586
= mapM_ check_arg tys
| otherwise
= failWithTc (arityErr flavour (tyConName tc) tc_arity n_args)
where
flavour | isTypeFamilyTyCon tc = "Type family"
| otherwise = "Type synonym"
n_args = length tys
tc_arity = tyConArity tc
check_arg | isTypeFamilyTyCon tc = check_arg_type ctxt rank
| otherwise = check_mono_type ctxt synArgMonoType
----------------------------------------
check_ubx_tuple :: UserTypeCtxt -> KindOrType
-> [KindOrType] -> TcM ()
check_ubx_tuple ctxt ty tys
= do { ub_tuples_allowed <- xoptM Opt_UnboxedTuples
; checkTc ub_tuples_allowed (ubxArgTyErr ty)
; impred <- xoptM Opt_ImpredicativeTypes
; let rank' = if impred then ArbitraryRank else tyConArgMonoType
-- c.f. check_arg_type
-- However, args are allowed to be unlifted, or
-- more unboxed tuples, so can't use check_arg_ty
; mapM_ (check_type ctxt rank') tys }
----------------------------------------
check_arg_type :: UserTypeCtxt -> Rank -> KindOrType -> TcM ()
-- The sort of type that can instantiate a type variable,
-- or be the argument of a type constructor.
-- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
-- Other unboxed types are very occasionally allowed as type
-- arguments depending on the kind of the type constructor
--
-- For example, we want to reject things like:
--
-- instance Ord a => Ord (forall s. T s a)
-- and
-- g :: T s (forall b.b)
--
-- NB: unboxed tuples can have polymorphic or unboxed args.
-- This happens in the workers for functions returning
-- product types with polymorphic components.
-- But not in user code.
-- Anyway, they are dealt with by a special case in check_tau_type
check_arg_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check a kind?
| otherwise
= do { impred <- xoptM Opt_ImpredicativeTypes
; let rank' = case rank of -- Predictive => must be monotype
MustBeMonoType -> MustBeMonoType -- Monotype, regardless
_other | impred -> ArbitraryRank
| otherwise -> tyConArgMonoType
-- Make sure that MustBeMonoType is propagated,
-- so that we don't suggest -XImpredicativeTypes in
-- (Ord (forall a.a)) => a -> a
-- and so that if it Must be a monotype, we check that it is!
; check_type ctxt rank' ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
-- NB the isUnLiftedType test also checks for
-- T State#
-- where there is an illegal partial application of State# (which has
-- kind * -> #); see Note [The kind invariant] in TypeRep
----------------------------------------
forAllTyErr :: Rank -> Type -> SDoc
forAllTyErr rank ty
= vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty)
, suggestion ]
where
suggestion = case rank of
LimitedRank {} -> ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types")
MonoType d -> d
_ -> Outputable.empty -- Polytype is always illegal
unliftedArgErr, ubxArgTyErr :: Type -> SDoc
unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
kindErr :: Kind -> SDoc
kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
{-
Note [Liberal type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
doing validity checking. This allows us to instantiate a synonym defn
with a for-all type, or with a partially-applied type synonym.
e.g. type T a b = a
type S m = m ()
f :: S (T Int)
Here, T is partially applied, so it's illegal in H98. But if you
expand S first, then T we get just
f :: Int
which is fine.
IMPORTANT: suppose T is a type synonym. Then we must do validity
checking on an appliation (T ty1 ty2)
*either* before expansion (i.e. check ty1, ty2)
*or* after expansion (i.e. expand T ty1 ty2, and then check)
BUT NOT BOTH
If we do both, we get exponential behaviour!!
data TIACons1 i r c = c i ::: r c
type TIACons2 t x = TIACons1 t (TIACons1 t x)
type TIACons3 t x = TIACons2 t (TIACons1 t x)
type TIACons4 t x = TIACons2 t (TIACons2 t x)
type TIACons7 t x = TIACons4 t (TIACons3 t x)
************************************************************************
* *
\subsection{Checking a theta or source type}
* *
************************************************************************
Note [Implicit parameters in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implicit parameters _only_ allowed in type signatures; not in instance
decls, superclasses etc. The reason for not allowing implicit params in
instances is a bit subtle. If we allowed
instance (?x::Int, Eq a) => Foo [a] where ...
then when we saw
(e :: (?x::Int) => t)
it would be unclear how to discharge all the potential uses of the ?x
in e. For example, a constraint Foo [Int] might come out of e, and
applying the instance decl would show up two uses of ?x. Trac #8912.
-}
checkValidTheta :: UserTypeCtxt -> ThetaType -> TcM ()
checkValidTheta ctxt theta
= addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
-------------------------
check_valid_theta :: UserTypeCtxt -> [PredType] -> TcM ()
check_valid_theta _ []
= return ()
check_valid_theta ctxt theta
= do { dflags <- getDynFlags
; warnTc (wopt Opt_WarnDuplicateConstraints dflags &&
notNull dups) (dupPredWarn dups)
; mapM_ (check_pred_ty dflags ctxt) theta }
where
(_,dups) = removeDups cmpPred theta
-------------------------
check_pred_ty :: DynFlags -> UserTypeCtxt -> PredType -> TcM ()
-- Check the validity of a predicate in a signature
-- Do not look through any type synonyms; any constraint kinded
-- type synonyms have been checked at their definition site
-- C.f. Trac #9838
check_pred_ty dflags ctxt pred
= do { checkValidMonoType pred
; check_pred_help False dflags ctxt pred }
check_pred_help :: Bool -- True <=> under a type synonym
-> DynFlags -> UserTypeCtxt
-> PredType -> TcM ()
check_pred_help under_syn dflags ctxt pred
| Just pred' <- coreView pred
= check_pred_help True dflags ctxt pred'
| otherwise
= case classifyPredType pred of
ClassPred cls tys -> check_class_pred dflags ctxt pred cls tys
EqPred NomEq _ _ -> check_eq_pred dflags pred
EqPred ReprEq ty1 ty2 -> check_repr_eq_pred dflags ctxt pred ty1 ty2
TuplePred tys -> check_tuple_pred under_syn dflags ctxt pred tys
IrredPred _ -> check_irred_pred under_syn dflags ctxt pred
check_class_pred :: DynFlags -> UserTypeCtxt -> PredType -> Class -> [TcType] -> TcM ()
check_class_pred dflags ctxt pred cls tys
= do { -- Class predicates are valid in all contexts
; checkTc (arity == n_tys) arity_err
; checkTc (not (isIPClass cls) || okIPCtxt ctxt)
(badIPPred pred)
-- Check the form of the argument types
; check_class_pred_tys dflags ctxt pred tys
}
where
class_name = className cls
arity = classArity cls
n_tys = length tys
arity_err = arityErr "Class" class_name arity n_tys
check_eq_pred :: DynFlags -> PredType -> TcM ()
check_eq_pred dflags pred
= -- Equational constraints are valid in all contexts if type
-- families are permitted
checkTc (xopt Opt_TypeFamilies dflags || xopt Opt_GADTs dflags)
(eqPredTyErr pred)
check_repr_eq_pred :: DynFlags -> UserTypeCtxt -> PredType
-> TcType -> TcType -> TcM ()
check_repr_eq_pred dflags ctxt pred ty1 ty2
= check_class_pred_tys dflags ctxt pred tys
where
tys = [ty1, ty2]
check_tuple_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> [PredType] -> TcM ()
check_tuple_pred under_syn dflags ctxt pred ts
= do { -- See Note [ConstraintKinds in predicates]
checkTc (under_syn || xopt Opt_ConstraintKinds dflags)
(predTupleErr pred)
; mapM_ (check_pred_help under_syn dflags ctxt) ts }
-- This case will not normally be executed because without
-- -XConstraintKinds tuple types are only kind-checked as *
check_irred_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> TcM ()
check_irred_pred under_syn dflags ctxt pred
-- The predicate looks like (X t1 t2) or (x t1 t2) :: Constraint
-- where X is a type function
= do { -- If it looks like (x t1 t2), require ConstraintKinds
-- see Note [ConstraintKinds in predicates]
-- But (X t1 t2) is always ok because we just require ConstraintKinds
-- at the definition site (Trac #9838)
checkTc (under_syn || xopt Opt_ConstraintKinds dflags || not (tyvar_head pred))
(predIrredErr pred)
-- Make sure it is OK to have an irred pred in this context
-- See Note [Irreducible predicates in superclasses]
; checkTc (xopt Opt_UndecidableInstances dflags || not (dodgy_superclass ctxt))
(predIrredBadCtxtErr pred) }
where
dodgy_superclass ctxt
= case ctxt of { ClassSCCtxt _ -> True; InstDeclCtxt -> True; _ -> False }
{- Note [ConstraintKinds in predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't check for -XConstraintKinds under a type synonym, because that
was done at the type synonym definition site; see Trac #9838
e.g. module A where
type C a = (Eq a, Ix a) -- Needs -XConstraintKinds
module B where
import A
f :: C a => a -> a -- Does *not* need -XConstraintKinds
Note [Irreducible predicates in superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allowing irreducible predicates in class superclasses is somewhat dangerous
because we can write:
type family Fooish x :: * -> Constraint
type instance Fooish () = Foo
class Fooish () a => Foo a where
This will cause the constraint simplifier to loop because every time we canonicalise a
(Foo a) class constraint we add a (Fooish () a) constraint which will be immediately
solved to add+canonicalise another (Foo a) constraint.
It is equally dangerous to allow them in instance heads because in that case the
Paterson conditions may not detect duplication of a type variable or size change. -}
-------------------------
check_class_pred_tys :: DynFlags -> UserTypeCtxt
-> PredType -> [KindOrType] -> TcM ()
check_class_pred_tys dflags ctxt pred kts
= checkTc pred_ok (predTyVarErr pred $$ how_to_allow)
where
(_, tys) = span isKind kts -- see Note [Kind polymorphic type classes]
flexible_contexts = xopt Opt_FlexibleContexts dflags
undecidable_ok = xopt Opt_UndecidableInstances dflags
pred_ok = case ctxt of
SpecInstCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
InstDeclCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
-- Further checks on head and theta in
-- checkInstTermination
_ -> flexible_contexts || all tyvar_head tys
how_to_allow = parens (ptext (sLit "Use FlexibleContexts to permit this"))
-------------------------
tyvar_head :: Type -> Bool
tyvar_head ty -- Haskell 98 allows predicates of form
| tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
| otherwise -- where a is a type variable
= case tcSplitAppTy_maybe ty of
Just (ty, _) -> tyvar_head ty
Nothing -> False
-------------------------
okIPCtxt :: UserTypeCtxt -> Bool
-- See Note [Implicit parameters in instance decls]
okIPCtxt (ClassSCCtxt {}) = False
okIPCtxt (InstDeclCtxt {}) = False
okIPCtxt (SpecInstCtxt {}) = False
okIPCtxt _ = True
badIPPred :: PredType -> SDoc
badIPPred pred = ptext (sLit "Illegal implicit parameter") <+> quotes (ppr pred)
{-
Note [Kind polymorphic type classes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MultiParam check:
class C f where... -- C :: forall k. k -> Constraint
instance C Maybe where...
The dictionary gets type [C * Maybe] even if it's not a MultiParam
type class.
Flexibility check:
class C f where... -- C :: forall k. k -> Constraint
data D a = D a
instance C D where
The dictionary gets type [C * (D *)]. IA0_TODO it should be
generalized actually.
Note [The ambiguity check for type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
checkAmbiguity is a check on user-supplied type signatures. It is
*purely* there to report functions that cannot possibly be called. So for
example we want to reject:
f :: C a => Int
The idea is there can be no legal calls to 'f' because every call will
give rise to an ambiguous constraint. We could soundly omit the
ambiguity check on type signatures entirely, at the expense of
delaying ambiguity errors to call sites. Indeed, the flag
-XAllowAmbiguousTypes switches off the ambiguity check.
What about things like this:
class D a b | a -> b where ..
h :: D Int b => Int
The Int may well fix 'b' at the call site, so that signature should
not be rejected. Moreover, using *visible* fundeps is too
conservative. Consider
class X a b where ...
class D a b | a -> b where ...
instance D a b => X [a] b where...
h :: X a b => a -> a
Here h's type looks ambiguous in 'b', but here's a legal call:
...(h [True])...
That gives rise to a (X [Bool] beta) constraint, and using the
instance means we need (D Bool beta) and that fixes 'beta' via D's
fundep!
Behind all these special cases there is a simple guiding principle.
Consider
f :: <type>
f = ...blah...
g :: <type>
g = f
You would think that the definition of g would surely typecheck!
After all f has exactly the same type, and g=f. But in fact f's type
is instantiated and the instantiated constraints are solved against
the originals, so in the case an ambiguous type it won't work.
Consider our earlier example f :: C a => Int. Then in g's definition,
we'll instantiate to (C alpha) and try to deduce (C alpha) from (C a),
and fail.
So in fact we use this as our *definition* of ambiguity. We use a
very similar test for *inferred* types, to ensure that they are
unambiguous. See Note [Impedence matching] in TcBinds.
This test is very conveniently implemented by calling
tcSubType <type> <type>
This neatly takes account of the functional dependecy stuff above,
and implicit parameter (see Note [Implicit parameters and ambiguity]).
What about this, though?
g :: C [a] => Int
Is every call to 'g' ambiguous? After all, we might have
intance C [a] where ...
at the call site. So maybe that type is ok! Indeed even f's
quintessentially ambiguous type might, just possibly be callable:
with -XFlexibleInstances we could have
instance C a where ...
and now a call could be legal after all! Well, we'll reject this
unless the instance is available *here*.
Side note: the ambiguity check is only used for *user* types, not for
types coming from inteface files. The latter can legitimately have
ambiguous types. Example
class S a where s :: a -> (Int,Int)
instance S Char where s _ = (1,1)
f:: S a => [a] -> Int -> (Int,Int)
f (_::[a]) x = (a*x,b)
where (a,b) = s (undefined::a)
Here the worker for f gets the type
fw :: forall a. S a => Int -> (# Int, Int #)
Note [Implicit parameters and ambiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Only a *class* predicate can give rise to ambiguity
An *implicit parameter* cannot. For example:
foo :: (?x :: [a]) => Int
foo = length ?x
is fine. The call site will suppply a particular 'x'
Furthermore, the type variables fixed by an implicit parameter
propagate to the others. E.g.
foo :: (Show a, ?x::[a]) => Int
foo = show (?x++?x)
The type of foo looks ambiguous. But it isn't, because at a call site
we might have
let ?x = 5::Int in foo
and all is well. In effect, implicit parameters are, well, parameters,
so we can take their type variables into account as part of the
"tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
-}
checkThetaCtxt :: UserTypeCtxt -> ThetaType -> SDoc
checkThetaCtxt ctxt theta
= vcat [ptext (sLit "In the context:") <+> pprTheta theta,
ptext (sLit "While checking") <+> pprUserTypeCtxt ctxt ]
eqPredTyErr, predTyVarErr, predTupleErr, predIrredErr, predIrredBadCtxtErr :: PredType -> SDoc
eqPredTyErr pred = ptext (sLit "Illegal equational constraint") <+> pprType pred
$$
parens (ptext (sLit "Use GADTs or TypeFamilies to permit this"))
predTyVarErr pred = hang (ptext (sLit "Non type-variable argument"))
2 (ptext (sLit "in the constraint:") <+> pprType pred)
predTupleErr pred = hang (ptext (sLit "Illegal tuple constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predIrredErr pred = hang (ptext (sLit "Illegal constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predIrredBadCtxtErr pred = hang (ptext (sLit "Illegal constraint") <+> quotes (pprType pred)
<+> ptext (sLit "in a superclass/instance context"))
2 (parens undecidableMsg)
constraintSynErr :: Type -> SDoc
constraintSynErr kind = hang (ptext (sLit "Illegal constraint synonym of kind:") <+> quotes (ppr kind))
2 (parens constraintKindsMsg)
dupPredWarn :: [[PredType]] -> SDoc
dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprType (map head dups)
arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
arityErr kind name n m
= hsep [ text kind, quotes (ppr name), ptext (sLit "should have"),
n_arguments <> comma, text "but has been given",
if m==0 then text "none" else int m]
where
n_arguments | n == 0 = ptext (sLit "no arguments")
| n == 1 = ptext (sLit "1 argument")
| True = hsep [int n, ptext (sLit "arguments")]
{-
************************************************************************
* *
\subsection{Checking for a decent instance head type}
* *
************************************************************************
@checkValidInstHead@ checks the type {\em and} its syntactic constraints:
it must normally look like: @instance Foo (Tycon a b c ...) ...@
The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
flag is on, or (2)~the instance is imported (they must have been
compiled elsewhere). In these cases, we let them go through anyway.
We can also have instances for functions: @instance Foo (a -> b) ...@.
-}
checkValidInstHead :: UserTypeCtxt -> Class -> [Type] -> TcM ()
checkValidInstHead ctxt clas cls_args
= do { dflags <- getDynFlags
; checkTc (clas `notElem` abstractClasses)
(instTypeErr clas cls_args abstract_class_msg)
-- Check language restrictions;
-- but not for SPECIALISE isntance pragmas
; let ty_args = dropWhile isKind cls_args
; unless spec_inst_prag $
do { checkTc (xopt Opt_TypeSynonymInstances dflags ||
all tcInstHeadTyNotSynonym ty_args)
(instTypeErr clas cls_args head_type_synonym_msg)
; checkTc (xopt Opt_FlexibleInstances dflags ||
all tcInstHeadTyAppAllTyVars ty_args)
(instTypeErr clas cls_args head_type_args_tyvars_msg)
; checkTc (xopt Opt_MultiParamTypeClasses dflags ||
length ty_args == 1 || -- Only count type arguments
(xopt Opt_NullaryTypeClasses dflags &&
null ty_args))
(instTypeErr clas cls_args head_one_type_msg) }
-- May not contain type family applications
; mapM_ checkTyFamFreeness ty_args
; mapM_ checkValidMonoType ty_args
-- For now, I only allow tau-types (not polytypes) in
-- the head of an instance decl.
-- E.g. instance C (forall a. a->a) is rejected
-- One could imagine generalising that, but I'm not sure
-- what all the consequences might be
}
where
spec_inst_prag = case ctxt of { SpecInstCtxt -> True; _ -> False }
head_type_synonym_msg = parens (
text "All instance types must be of the form (T t1 ... tn)" $$
text "where T is not a synonym." $$
text "Use TypeSynonymInstances if you want to disable this.")
head_type_args_tyvars_msg = parens (vcat [
text "All instance types must be of the form (T a1 ... an)",
text "where a1 ... an are *distinct type variables*,",
text "and each type variable appears at most once in the instance head.",
text "Use FlexibleInstances if you want to disable this."])
head_one_type_msg = parens (
text "Only one type can be given in an instance head." $$
text "Use MultiParamTypeClasses if you want to allow more, or zero.")
abstract_class_msg =
text "The class is abstract, manual instances are not permitted."
abstractClasses :: [ Class ]
abstractClasses = [ coercibleClass ] -- See Note [Coercible Instances]
instTypeErr :: Class -> [Type] -> SDoc -> SDoc
instTypeErr cls tys msg
= hang (hang (ptext (sLit "Illegal instance declaration for"))
2 (quotes (pprClassPred cls tys)))
2 msg
{-
validDeivPred checks for OK 'deriving' context. See Note [Exotic
derived instance contexts] in TcDeriv. However the predicate is
here because it uses sizeTypes, fvTypes.
Also check for a bizarre corner case, when the derived instance decl
would look like
instance C a b => D (T a) where ...
Note that 'b' isn't a parameter of T. This gives rise to all sorts of
problems; in particular, it's hard to compare solutions for equality
when finding the fixpoint, and that means the inferContext loop does
not converge. See Trac #5287.
-}
validDerivPred :: TyVarSet -> PredType -> Bool
validDerivPred tv_set pred
= case classifyPredType pred of
ClassPred _ tys -> check_tys tys
TuplePred ps -> all (validDerivPred tv_set) ps
EqPred {} -> False -- reject equality constraints
_ -> True -- Non-class predicates are ok
where
check_tys tys = hasNoDups fvs
&& sizeTypes tys == length fvs
&& all (`elemVarSet` tv_set) fvs
fvs = fvType pred
{-
************************************************************************
* *
\subsection{Checking instance for termination}
* *
************************************************************************
-}
checkValidInstance :: UserTypeCtxt -> LHsType Name -> Type
-> TcM ([TyVar], ThetaType, Class, [Type])
checkValidInstance ctxt hs_type ty
| Just (clas,inst_tys) <- getClassPredTys_maybe tau
, inst_tys `lengthIs` classArity clas
= do { setSrcSpan head_loc (checkValidInstHead ctxt clas inst_tys)
; checkValidTheta ctxt theta
-- The Termination and Coverate Conditions
-- Check that instance inference will terminate (if we care)
-- For Haskell 98 this will already have been done by checkValidTheta,
-- but as we may be using other extensions we need to check.
--
-- Note that the Termination Condition is *more conservative* than
-- the checkAmbiguity test we do on other type signatures
-- e.g. Bar a => Bar Int is ambiguous, but it also fails
-- the termination condition, because 'a' appears more often
-- in the constraint than in the head
; undecidable_ok <- xoptM Opt_UndecidableInstances
; if undecidable_ok
then checkAmbiguity ctxt ty
else checkInstTermination inst_tys theta
; case (checkInstCoverage undecidable_ok clas theta inst_tys) of
IsValid -> return () -- Check succeeded
NotValid msg -> addErrTc (instTypeErr clas inst_tys msg)
; return (tvs, theta, clas, inst_tys) }
| otherwise
= failWithTc (ptext (sLit "Malformed instance head:") <+> ppr tau)
where
(tvs, theta, tau) = tcSplitSigmaTy ty
-- The location of the "head" of the instance
head_loc = case hs_type of
L _ (HsForAllTy _ _ _ _ (L loc _)) -> loc
L loc _ -> loc
{-
Note [Paterson conditions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Termination test: the so-called "Paterson conditions" (see Section 5 of
"Understanding functionsl dependencies via Constraint Handling Rules,
JFP Jan 2007).
We check that each assertion in the context satisfies:
(1) no variable has more occurrences in the assertion than in the head, and
(2) the assertion has fewer constructors and variables (taken together
and counting repetitions) than the head.
This is only needed with -fglasgow-exts, as Haskell 98 restrictions
(which have already been checked) guarantee termination.
The underlying idea is that
for any ground substitution, each assertion in the
context has fewer type constructors than the head.
-}
checkInstTermination :: [TcType] -> ThetaType -> TcM ()
-- See Note [Paterson conditions]
checkInstTermination tys theta
= check_preds theta
where
fvs = fvTypes tys
size = sizeTypes tys
check_preds :: [PredType] -> TcM ()
check_preds preds = mapM_ check preds
check :: PredType -> TcM ()
check pred
= case classifyPredType pred of
TuplePred preds -> check_preds preds -- Look inside tuple predicates; Trac #8359
EqPred {} -> return () -- You can't get from equalities
-- to class predicates, so this is safe
_other -- ClassPred, IrredPred
| not (null bad_tvs)
-> addErrTc (predUndecErr pred (nomoreMsg bad_tvs) $$ parens undecidableMsg)
| sizePred pred >= size
-> addErrTc (predUndecErr pred smallerMsg $$ parens undecidableMsg)
| otherwise
-> return ()
where
bad_tvs = filterOut isKindVar (fvType pred \\ fvs)
-- Rightly or wrongly, we only check for
-- excessive occurrences of *type* variables.
-- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k}))
predUndecErr :: PredType -> SDoc -> SDoc
predUndecErr pred msg = sep [msg,
nest 2 (ptext (sLit "in the constraint:") <+> pprType pred)]
nomoreMsg :: [TcTyVar] -> SDoc
nomoreMsg tvs
= sep [ ptext (sLit "Variable") <> plural tvs <+> quotes (pprWithCommas ppr tvs)
, (if isSingleton tvs then ptext (sLit "occurs")
else ptext (sLit "occur"))
<+> ptext (sLit "more often than in the instance head") ]
smallerMsg, undecidableMsg, constraintKindsMsg :: SDoc
smallerMsg = ptext (sLit "Constraint is no smaller than the instance head")
undecidableMsg = ptext (sLit "Use UndecidableInstances to permit this")
constraintKindsMsg = ptext (sLit "Use ConstraintKinds to permit this")
{-
Note [Associated type instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow this:
class C a where
type T x a
instance C Int where
type T (S y) Int = y
type T Z Int = Char
Note that
a) The variable 'x' is not bound by the class decl
b) 'x' is instantiated to a non-type-variable in the instance
c) There are several type instance decls for T in the instance
All this is fine. Of course, you can't give any *more* instances
for (T ty Int) elsewhere, because it's an *associated* type.
Note [Checking consistent instantiation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class C a b where
type T a x b
instance C [p] Int
type T [p] y Int = (p,y,y) -- Induces the family instance TyCon
-- type TR p y = (p,y,y)
So we
* Form the mini-envt from the class type variables a,b
to the instance decl types [p],Int: [a->[p], b->Int]
* Look at the tyvars a,x,b of the type family constructor T
(it shares tyvars with the class C)
* Apply the mini-evnt to them, and check that the result is
consistent with the instance types [p] y Int
We do *not* assume (at this point) the the bound variables of
the assoicated type instance decl are the same as for the parent
instance decl. So, for example,
instance C [p] Int
type T [q] y Int = ...
would work equally well. Reason: making the *kind* variables line
up is much harder. Example (Trac #7282):
class Foo (xs :: [k]) where
type Bar xs :: *
instance Foo '[] where
type Bar '[] = Int
Here the instance decl really looks like
instance Foo k ('[] k) where
type Bar k ('[] k) = Int
but the k's are not scoped, and hence won't match Uniques.
So instead we just match structure, with tcMatchTyX, and check
that distinct type variables match 1-1 with distinct type variables.
HOWEVER, we *still* make the instance type variables scope over the
type instances, to pick up non-obvious kinds. Eg
class Foo (a :: k) where
type F a
instance Foo (b :: k -> k) where
type F b = Int
Here the instance is kind-indexed and really looks like
type F (k->k) (b::k->k) = Int
But if the 'b' didn't scope, we would make F's instance too
poly-kinded.
-}
-- | Extra information needed when type-checking associated types. The 'Class' is
-- the enclosing class, and the @VarEnv Type@ maps class variables to their
-- instance types.
type ClsInfo = (Class, VarEnv Type)
checkConsistentFamInst
:: Maybe ( Class
, VarEnv Type ) -- ^ Class of associated type
-- and instantiation of class TyVars
-> TyCon -- ^ Family tycon
-> [TyVar] -- ^ Type variables of the family instance
-> [Type] -- ^ Type patterns from instance
-> TcM ()
-- See Note [Checking consistent instantiation]
checkConsistentFamInst Nothing _ _ _ = return ()
checkConsistentFamInst (Just (clas, mini_env)) fam_tc at_tvs at_tys
= do { -- Check that the associated type indeed comes from this class
checkTc (Just clas == tyConAssoc_maybe fam_tc)
(badATErr (className clas) (tyConName fam_tc))
-- See Note [Checking consistent instantiation] in TcTyClsDecls
-- Check right to left, so that we spot type variable
-- inconsistencies before (more confusing) kind variables
; discardResult $ foldrM check_arg emptyTvSubst $
tyConTyVars fam_tc `zip` at_tys }
where
at_tv_set = mkVarSet at_tvs
check_arg :: (TyVar, Type) -> TvSubst -> TcM TvSubst
check_arg (fam_tc_tv, at_ty) subst
| Just inst_ty <- lookupVarEnv mini_env fam_tc_tv
= case tcMatchTyX at_tv_set subst at_ty inst_ty of
Just subst | all_distinct subst -> return subst
_ -> failWithTc $ wrongATArgErr at_ty inst_ty
-- No need to instantiate here, because the axiom
-- uses the same type variables as the assocated class
| otherwise
= return subst -- Allow non-type-variable instantiation
-- See Note [Associated type instances]
all_distinct :: TvSubst -> Bool
-- True if all the variables mapped the substitution
-- map to *distinct* type *variables*
all_distinct subst = go [] at_tvs
where
go _ [] = True
go acc (tv:tvs) = case lookupTyVar subst tv of
Nothing -> go acc tvs
Just ty | Just tv' <- tcGetTyVar_maybe ty
, tv' `notElem` acc
-> go (tv' : acc) tvs
_other -> False
badATErr :: Name -> Name -> SDoc
badATErr clas op
= hsep [ptext (sLit "Class"), quotes (ppr clas),
ptext (sLit "does not have an associated type"), quotes (ppr op)]
wrongATArgErr :: Type -> Type -> SDoc
wrongATArgErr ty instTy =
sep [ ptext (sLit "Type indexes must match class instance head")
, ptext (sLit "Found") <+> quotes (ppr ty)
<+> ptext (sLit "but expected") <+> quotes (ppr instTy)
]
{-
************************************************************************
* *
Checking type instance well-formedness and termination
* *
************************************************************************
-}
-- Check that a "type instance" is well-formed (which includes decidability
-- unless -XUndecidableInstances is given).
--
checkValidTyFamInst :: Maybe ( Class, VarEnv Type )
-> TyCon -> CoAxBranch -> TcM ()
checkValidTyFamInst mb_clsinfo fam_tc
(CoAxBranch { cab_tvs = tvs, cab_lhs = typats
, cab_rhs = rhs, cab_loc = loc })
= checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc
-- | Do validity checks on a type family equation, including consistency
-- with any enclosing class instance head, termination, and lack of
-- polytypes.
checkValidTyFamEqn :: Maybe ClsInfo
-> TyCon -- ^ of the type family
-> [TyVar] -- ^ bound tyvars in the equation
-> [Type] -- ^ type patterns
-> Type -- ^ rhs
-> SrcSpan
-> TcM ()
checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc
= setSrcSpan loc $
do { checkValidFamPats fam_tc tvs typats
-- The argument patterns, and RHS, are all boxed tau types
-- E.g Reject type family F (a :: k1) :: k2
-- type instance F (forall a. a->a) = ...
-- type instance F Int# = ...
-- type instance F Int = forall a. a->a
-- type instance F Int = Int#
-- See Trac #9357
; mapM_ checkValidMonoType typats
; checkValidMonoType rhs
-- We have a decidable instance unless otherwise permitted
; undecidable_ok <- xoptM Opt_UndecidableInstances
; unless undecidable_ok $
mapM_ addErrTc (checkFamInstRhs typats (tcTyFamInsts rhs))
-- Check that type patterns match the class instance head
; checkConsistentFamInst mb_clsinfo fam_tc tvs typats }
-- Make sure that each type family application is
-- (1) strictly smaller than the lhs,
-- (2) mentions no type variable more often than the lhs, and
-- (3) does not contain any further type family instances.
--
checkFamInstRhs :: [Type] -- lhs
-> [(TyCon, [Type])] -- type family instances
-> [MsgDoc]
checkFamInstRhs lhsTys famInsts
= mapMaybe check famInsts
where
size = sizeTypes lhsTys
fvs = fvTypes lhsTys
check (tc, tys)
| not (all isTyFamFree tys)
= Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
| not (null bad_tvs)
= Just (famInstUndecErr famInst (nomoreMsg bad_tvs) $$ parens undecidableMsg)
| size <= sizeTypes tys
= Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
| otherwise
= Nothing
where
famInst = TyConApp tc tys
bad_tvs = filterOut isKindVar (fvTypes tys \\ fvs)
-- Rightly or wrongly, we only check for
-- excessive occurrences of *type* variables.
-- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k}))
checkValidFamPats :: TyCon -> [TyVar] -> [Type] -> TcM ()
-- Patterns in a 'type instance' or 'data instance' decl should
-- a) contain no type family applications
-- (vanilla synonyms are fine, though)
-- b) properly bind all their free type variables
-- e.g. we disallow (Trac #7536)
-- type T a = Int
-- type instance F (T a) = a
-- c) Have the right number of patterns
checkValidFamPats fam_tc tvs ty_pats
= --ASSERT( length ty_pats == tyConArity fam_tc )
-- A family instance must have exactly the same number of type
-- parameters as the family declaration. You can't write
-- type family F a :: * -> *
-- type instance F Int y = y
-- because then the type (F Int) would be like (\y.y)
-- But this is checked at the time the axiom is created
do { mapM_ checkTyFamFreeness ty_pats
; let unbound_tvs = filterOut (`elemVarSet` exactTyVarsOfTypes ty_pats) tvs
; checkTc (null unbound_tvs) (famPatErr fam_tc unbound_tvs ty_pats) }
-- Ensure that no type family instances occur in a type.
checkTyFamFreeness :: Type -> TcM ()
checkTyFamFreeness ty
= checkTc (isTyFamFree ty) $
tyFamInstIllegalErr ty
-- Check that a type does not contain any type family applications.
--
isTyFamFree :: Type -> Bool
isTyFamFree = null . tcTyFamInsts
-- Error messages
tyFamInstIllegalErr :: Type -> SDoc
tyFamInstIllegalErr ty
= hang (ptext (sLit "Illegal type synonym family application in instance") <>
colon) 2 $
ppr ty
famInstUndecErr :: Type -> SDoc -> SDoc
famInstUndecErr ty msg
= sep [msg,
nest 2 (ptext (sLit "in the type family application:") <+>
pprType ty)]
famPatErr :: TyCon -> [TyVar] -> [Type] -> SDoc
famPatErr fam_tc tvs pats
= hang (ptext (sLit "Family instance purports to bind type variable") <> plural tvs
<+> pprQuotedList tvs)
2 (hang (ptext (sLit "but the real LHS (expanding synonyms) is:"))
2 (pprTypeApp fam_tc (map expandTypeSynonyms pats) <+> ptext (sLit "= ...")))
nestedMsg, smallerAppMsg :: SDoc
nestedMsg = ptext (sLit "Nested type family application")
smallerAppMsg = ptext (sLit "Application is no smaller than the instance head")
{-
************************************************************************
* *
\subsection{Auxiliary functions}
* *
************************************************************************
-}
-- Free variables of a type, retaining repetitions, and expanding synonyms
fvType :: Type -> [TyVar]
fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
fvType (TyVarTy tv) = [tv]
fvType (TyConApp _ tys) = fvTypes tys
fvType (LitTy {}) = []
fvType (FunTy arg res) = fvType arg ++ fvType res
fvType (AppTy fun arg) = fvType fun ++ fvType arg
fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
fvTypes :: [Type] -> [TyVar]
fvTypes tys = concat (map fvType tys)
sizeType :: Type -> Int
-- Size of a type: the number of variables and constructors
sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
sizeType (TyVarTy {}) = 1
sizeType (TyConApp _ tys) = sizeTypes tys + 1
sizeType (LitTy {}) = 1
sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
sizeType (AppTy fun arg) = sizeType fun + sizeType arg
sizeType (ForAllTy _ ty) = sizeType ty
sizeTypes :: [Type] -> Int
-- IA0_NOTE: Avoid kinds.
sizeTypes xs = sum (map sizeType tys)
where tys = filter (not . isKind) xs
-- Size of a predicate
--
-- We are considering whether class constraints terminate.
-- Equality constraints and constraints for the implicit
-- parameter class always termiante so it is safe to say "size 0".
-- (Implicit parameter constraints always terminate because
-- there are no instances for them---they are only solved by
-- "local instances" in expressions).
-- See Trac #4200.
sizePred :: PredType -> Int
sizePred ty = goClass ty
where
goClass p | isIPPred p = 0
| otherwise = go (classifyPredType p)
go (ClassPred _ tys') = sizeTypes tys'
go (EqPred {}) = 0
go (TuplePred ts) = sum (map goClass ts)
go (IrredPred ty) = sizeType ty
{-
Note [Paterson conditions on PredTypes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are considering whether *class* constraints terminate
(see Note [Paterson conditions]). Precisely, the Paterson conditions
would have us check that "the constraint has fewer constructors and variables
(taken together and counting repetitions) than the head.".
However, we can be a bit more refined by looking at which kind of constraint
this actually is. There are two main tricks:
1. It seems like it should be OK not to count the tuple type constructor
for a PredType like (Show a, Eq a) :: Constraint, since we don't
count the "implicit" tuple in the ThetaType itself.
In fact, the Paterson test just checks *each component* of the top level
ThetaType against the size bound, one at a time. By analogy, it should be
OK to return the size of the *largest* tuple component as the size of the
whole tuple.
2. Once we get into an implicit parameter or equality we
can't get back to a class constraint, so it's safe
to say "size 0". See Trac #4200.
NB: we don't want to detect PredTypes in sizeType (and then call
sizePred on them), or we might get an infinite loop if that PredType
is irreducible. See Trac #5581.
-}
| alexander-at-github/eta | compiler/ETA/TypeCheck/TcValidity.hs | bsd-3-clause | 55,304 | 5 | 16 | 15,509 | 8,175 | 4,191 | 3,984 | 585 | 14 |
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_C
-- Rectangle
-- input: 3 5
-- output: 15 16
import Control.Applicative
main = do
[a, b] <- map read . words <$> getLine
let x = area a b
y = circumference a b
putStrLn $ show x ++ " " ++ show y
area :: Int -> Int -> Int
area a b = a * b
circumference :: Int -> Int -> Int
circumference a b = (a + b) * 2
| ku00/aoj-haskell | src/ITP1_1_C.hs | bsd-3-clause | 399 | 2 | 10 | 103 | 159 | 76 | 83 | 10 | 1 |
{-# LANGUAGE DataKinds, TemplateHaskell, TypeFamilies, QuasiQuotes #-}
import TICTACTOE
import Data.Type.Equality
t :: ([tq| x o x
o o x
☐ ☐ x |]) :~: SOLVE DRAW
t = Refl
game :: ([tq| x o x
o o x
☐ ☐ x |])
game = (?)
| mxswd/ylj-2014 | 2_proof/tictactoe/Main.hs | bsd-3-clause | 279 | 1 | 7 | 99 | 63 | 37 | 26 | -1 | -1 |
module AERN2.BoxFunMinMax.Expressions.EliminateFloats where
import MixedTypesNumPrelude
import AERN2.BoxFunMinMax.Expressions.Type
import AERN2.BoxFunMinMax.Expressions.Translators.FPTaylor
import System.Process
import System.IO.Unsafe
import AERN2.BoxFunMinMax.VarMap (VarMap)
import System.Exit
fpTaylorPath :: FilePath
fpTaylorPath = "/home/junaid/Research/git/FPTaylor/fptaylor"
removeFloats :: E -> E
removeFloats (Float _ e) = removeFloats e
removeFloats (Float32 _ e) = removeFloats e
removeFloats (Float64 _ e) = removeFloats e
removeFloats (EBinOp op e1 e2) = EBinOp op (removeFloats e1) (removeFloats e2)
removeFloats (EUnOp op e) = EUnOp op (removeFloats e)
removeFloats (PowI e i) = PowI (removeFloats e) i
removeFloats (Lit v) = Lit v
removeFloats (Var v) = Var v
eliminateFloatsF :: F -> VarMap -> Bool -> F
eliminateFloatsF (FConn op f1 f2) varMap addError = FConn op (eliminateFloatsF f1 varMap addError) (eliminateFloatsF f2 varMap addError)
eliminateFloatsF (FComp op e1 e2) varMap addError = FComp op (eliminateFloats e1 varMap addError) (eliminateFloats e2 varMap addError)
eliminateFloatsF (FNot f) varMap addError = FNot (eliminateFloatsF f varMap addError)
eliminateFloats :: E -> VarMap -> Bool -> E
eliminateFloats e@(Float _ _) _ _ = error $ "Cannot eliminate Float, precision unknown. Expression: " ++ show e
eliminateFloats floatE@(Float32 _ e) varMap addError =
if addError
then EBinOp Add eWithotFloats (Lit absoluteError)
else EBinOp Sub eWithotFloats (Lit absoluteError)
where
absoluteError = unsafePerformIO $ findAbsoluteErrorUsingFPTaylor floatE varMap
eWithotFloats = removeFloats e
eliminateFloats floatE@(Float64 _ e) varMap addError =
if addError
then EBinOp Add eWithotFloats (Lit absoluteError)
else EBinOp Sub eWithotFloats (Lit absoluteError)
where
absoluteError = unsafePerformIO $ findAbsoluteErrorUsingFPTaylor floatE varMap
eWithotFloats = removeFloats e
eliminateFloats (EBinOp op e1 e2) varMap addError = EBinOp op (eliminateFloats e1 varMap addError) (eliminateFloats e2 varMap addError)
eliminateFloats (EUnOp op e) varMap addError = EUnOp op (eliminateFloats e varMap addError)
eliminateFloats (Lit v) _ _ = Lit v
eliminateFloats (Var v) _ _ = Var v
eliminateFloats (PowI e i) _ _ = PowI e i
-- |Made for Float32/64 expressions
findAbsoluteErrorUsingFPTaylor :: E -> VarMap -> IO Rational
findAbsoluteErrorUsingFPTaylor e varMap =
do
writeFile fptaylorFile fptaylorInput
(exitCode, output, errDetails) <- readProcessWithExitCode fpTaylorPath [fptaylorFile] []
-- removeFile fptaylorFile
case exitCode of
ExitSuccess ->
case parseFPTaylorRational output of
Just result -> return result
Nothing -> error "Could not parse FPTaylor output"
ExitFailure _ -> error $ "Error when running FPTaylor on generated fptaylor.txt. Error message: " ++ show errDetails
where
fptaylorInput = expressionWithVarMapToFPTaylor e varMap
fptaylorFile = "fptaylor.txt"
| michalkonecny/aern2 | aern2-mfun/src/AERN2/BoxFunMinMax/Expressions/EliminateFloats.hs | bsd-3-clause | 3,082 | 0 | 13 | 565 | 906 | 456 | 450 | 55 | 3 |
module CodeWidget.CodeWidget (codeWidgetNew,
Code(..),
CwAPI(..),
CwSelection(..),
Region,
RegionID,
PageID,
rootRegion,
CwView,
CwIter ) where
import qualified Graphics.UI.Gtk as G
import qualified Graphics.UI.Gtk.SourceView as G
import Data.IORef
import CodeWidget.CodeWidgetTypes
import CodeWidget.CodeWidgetAPI
import CodeWidget.CodeWidgetSBar
{--
design considerations:
1. The way the user interacts with the debugger is going to change many times as we
experiment with it and, later, increase the level of automation. Ideally, the
source view widget interface should be general enough to accommodate these changes.
Hence I believe that the interface should be defined in terms of nested text regions,
rather than magic blocks and other synthesis-specific concepts.
2. Functions exported by the widget will take text coordinates. These coordinates should be
relative to the current region and should not be sensitive to changes in nested regions, e.g.:
BEGIN_STATIC_REGION
text
text
{nested_editable_region}
highlighted_text
END_STATIC_REGION
In this example, when the user adds some text to the editable region, coordinates of the highlighted region are returned as if the editable region was empty, i.e., had zero width and height.
--}
-- API creation
{-- codeWidgetNew - create an instance of the code widget.
codeWidgetNew :: String -- language type (file extension)
-> Int -- width
-> Int -- height
-> IO Code
--}
codeWidgetNew :: String -> Int -> Int -> IO Code
codeWidgetNew l w h = do
slm <- G.sourceLanguageManagerGetDefault
mlng <- G.sourceLanguageManagerGetLanguage slm l
lng <- (case mlng of
Nothing -> error $ "Can't find " ++ l ++ " Language Definition"
Just x -> return x)
nb <- G.notebookNew
G.notebookSetScrollable nb True
font <- G.fontDescriptionFromString fontSrc
G.widgetSetSizeRequest nb w h
G.widgetShow nb
sbar <- createSBar
G.widgetShow $ G.toWidget sbar
ref <- newIORef $ CodeView { cvNotebook = nb
, cvSBar = sbar
, cvLanguage = lng
, cvPages = []
, cvFont = font
, cvNextPage = 0
}
_ <- G.after nb G.switchPage (csbSwitchPage ref)
return $ Code { codeApi = CwAPI { pageCreate = codePageCreate ref
, regionUnderCursor = codeRegionUnderCursor ref
, regionCreate = codeRegionCreate ref
, regionCreateFrom = codeRegionCreateFrom ref
, regionDelete = codeRegionDelete ref
, regionGetText = codeRegionGetText ref
, regionGetBoundedText = codeRegionGetBoundedText ref
, regionSetText = codeRegionSetText ref
, regionDeleteText = codeRegionDeleteText ref
, regionInsertText = codeRegionInsertText ref
, regionGetAllText = codeGetAllText ref
, tagNew = codeTagNew ref
, regionApplyTag = codeRegionApplyTag ref
, regionRemoveTag = codeRegionRemoveTag ref
, regionSetMark = codeRegionSetMark ref
, regionGetIter = codeRegionGetIter ref
, regionGetSelection = codeRegionGetSelection ref
, regionScrollToPos = codeRegionScrollToPos ref
, regionEditable = codeRegionEditable ref
, dumpRegions = codeDumpRegions ref
}
, codeWidget = G.toWidget nb
, codePos = G.toWidget sbar
}
| termite2/code-widget | CodeWidget/CodeWidget.hs | bsd-3-clause | 4,604 | 0 | 14 | 2,037 | 557 | 304 | 253 | 59 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | This is a "Now Playing"-style widget that listens for MPRIS
-- events on DBus. Various media players implement this. This widget
-- works with version 2 of the MPRIS protocol
-- (http://www.mpris.org/2.0/spec.html).
--
module System.Taffybar.MPRIS2 ( mpris2New ) where
import Data.Maybe ( listToMaybe )
import DBus
import DBus.Client
import Data.List (isPrefixOf)
import Graphics.UI.Gtk hiding ( Signal, Variant )
import Text.Printf
mpris2New :: IO Widget
mpris2New = do
label <- labelNew (Nothing :: Maybe String)
widgetShowAll label
_ <- on label realize $ initLabel label
return (toWidget label)
unpack :: IsVariant a => Variant -> a
unpack var = case fromVariant var of
Just x -> x
Nothing -> error("Could not unpack variant: " ++ show var)
initLabel :: Label -> IO ()
initLabel w = do
client <- connectSession
-- Set initial song state/info
reqSongInfo w client
listen client propMatcher (callBack w)
return ()
where callBack label s = do
let items = dictionaryItems $ unpack (signalBody s !! 1)
updatePlaybackStatus label items
updateMetadata label items
return ()
propMatcher = matchAny { matchSender = Nothing
, matchDestination = Nothing
, matchPath = Just "/org/mpris/MediaPlayer2"
, matchInterface = Just "org.freedesktop.DBus.Properties"
, matchMember = Just "PropertiesChanged"
}
reqSongInfo :: Label -> Client -> IO ()
reqSongInfo w client = do
rep <- call_ client (methodCall "/org/freedesktop/DBus" "org.freedesktop.DBus" "ListNames")
{ methodCallDestination = Just "org.freedesktop.DBus" }
let plist = unpack $ methodReturnBody rep !! 0
let players = filter (isPrefixOf "org.mpris.MediaPlayer2.") plist
case length players of
0 -> return ()
_ -> do
reply <- getProperty client (players !! 0) "Metadata"
updateSongInfo w $ dictionaryItems $ (unpack . unpack) (methodReturnBody reply !! 0)
reply' <- getProperty client (players !! 0) "PlaybackStatus"
let status = (unpack . unpack) (methodReturnBody reply' !! 0) :: String
case status of
"Playing" -> postGUIAsync $ widgetShowAll w
"Paused" -> postGUIAsync $ widgetHideAll w
"Stopped" -> postGUIAsync $ widgetHideAll w
_ -> return ()
getProperty :: Client -> String -> String -> IO MethodReturn
getProperty client name property = do
call_ client (methodCall "/org/mpris/MediaPlayer2" "org.freedesktop.DBus.Properties" "Get")
{ methodCallDestination = Just (busName_ name)
, methodCallBody = [ toVariant ("org.mpris.MediaPlayer2.Player" :: String),
toVariant property ]
}
setSongInfo :: Label -> String -> String -> IO ()
setSongInfo w artist title = do
let msg :: String
msg = case artist of
"" -> escapeMarkup $ printf "%s" (truncateString 30 title)
_ -> escapeMarkup $ printf "%s - %s" (truncateString 15 artist) (truncateString 30 title)
txt = "<span fgcolor='yellow'>▶</span> " ++ msg
postGUIAsync $ do
labelSetMarkup w txt
truncateString :: Int -> String -> String
truncateString n xs | length xs <= n = xs
| otherwise = take n xs ++ "…"
updatePlaybackStatus :: Label -> [(Variant, Variant)] -> IO ()
updatePlaybackStatus w items = do
case lookup (toVariant ("PlaybackStatus" :: String)) items of
Just a -> do
case (unpack . unpack) a :: String of
"Playing" -> postGUIAsync $ widgetShowAll w
"Paused" -> postGUIAsync $ widgetHideAll w
"Stopped" -> postGUIAsync $ widgetHideAll w
_ -> return ()
Nothing -> do
return ()
updateSongInfo :: Label -> [(Variant, Variant)] -> IO ()
updateSongInfo w items = do
let artist = case readArtist of
Just x -> x
Nothing -> ""
case readTitle of
Just title -> do
setSongInfo w artist title
Nothing -> return ()
where
readArtist :: Maybe String
readArtist = do
artist <- lookup (toVariant ("xesam:artist" :: String)) items
listToMaybe $ ((unpack . unpack) artist :: [String])
readTitle :: Maybe String
readTitle = do
title <- lookup (toVariant ("xesam:title" :: String)) items
Just $ (unpack . unpack) title
updateMetadata :: Label -> [(Variant, Variant)] -> IO ()
updateMetadata w items = do
case lookup (toVariant ("Metadata" :: String)) items of
Just meta -> do
let metaItems = dictionaryItems $ (unpack . unpack) meta
updateSongInfo w metaItems
Nothing -> return ()
| Undeterminant/taffybar | src/System/Taffybar/MPRIS2.hs | bsd-3-clause | 4,783 | 0 | 18 | 1,270 | 1,422 | 700 | 722 | 106 | 5 |
------------------------------------------------------------------------------
-- | Project Euler No. 5
--
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
--
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
-- Answer: 232792560
import Data.List (find)
-- NOTE: This implementation is terribly slow...needs to improve.
is_match :: Int -> Bool
is_match x = (length result) == 19
where
factors = reverse [2..20]
result = takeWhile (== 0) [x `mod` i | i <- factors]
posibilities = [2521..]
r = find is_match posibilities
result = show (find is_match posibilities)
main :: IO ()
main = do
putStrLn result | mazelife/project_euler | five.hs | bsd-3-clause | 743 | 5 | 8 | 147 | 176 | 84 | 92 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | HTTP\/2 client library.
--
-- Example:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- > module Main where
-- >
-- > import qualified Control.Exception as E
-- > import Control.Concurrent (forkIO, threadDelay)
-- > import qualified Data.ByteString.Char8 as C8
-- > import Network.HTTP.Types
-- > import Network.Run.TCP (runTCPClient) -- network-run
-- >
-- > import Network.HTTP2.Client
-- >
-- > serverName :: String
-- > serverName = "127.0.0.1"
-- >
-- > main :: IO ()
-- > main = runTCPClient serverName "80" runHTTP2Client
-- > where
-- > cliconf = ClientConfig "http" (C8.pack serverName) 20
-- > runHTTP2Client s = E.bracket (allocSimpleConfig s 4096)
-- > freeSimpleConfig
-- > (\conf -> run cliconf conf client)
-- > client sendRequest = do
-- > let req = requestNoBody methodGet "/" []
-- > _ <- forkIO $ sendRequest req $ \rsp -> do
-- > print rsp
-- > getResponseBodyChunk rsp >>= C8.putStrLn
-- > sendRequest req $ \rsp -> do
-- > threadDelay 100000
-- > print rsp
-- > getResponseBodyChunk rsp >>= C8.putStrLn
module Network.HTTP2.Client (
-- * Runner
run
, Scheme
, Authority
-- * Runner arguments
, ClientConfig(..)
, Config(..)
, allocSimpleConfig
, freeSimpleConfig
-- * HTTP\/2 client
, Client
-- * Request
, Request
-- * Creating request
, requestNoBody
, requestFile
, requestStreaming
, requestBuilder
-- ** Trailers maker
, TrailersMaker
, NextTrailersMaker(..)
, defaultTrailersMaker
, setRequestTrailersMaker
-- * Response
, Response
-- ** Accessing response
, responseStatus
, responseHeaders
, responseBodySize
, getResponseBodyChunk
, getResponseTrailers
-- * Types
, Method
, Path
, FileSpec(..)
, FileOffset
, ByteCount
-- * RecvN
, defaultReadN
-- * Position read for files
, PositionReadMaker
, PositionRead
, Sentinel(..)
, defaultPositionReadMaker
) where
import Data.ByteString (ByteString)
import Data.ByteString.Builder (Builder)
import Data.IORef (readIORef)
import Network.HTTP.Types
import Network.HPACK
import Network.HTTP2.Arch
import Network.HTTP2.Client.Types
import Network.HTTP2.Client.Run
----------------------------------------------------------------
-- | Creating request without body.
requestNoBody :: Method -> Path -> RequestHeaders -> Request
requestNoBody m p hdr = Request $ OutObj hdr' OutBodyNone defaultTrailersMaker
where
hdr' = addHeaders m p hdr
-- | Creating request with file.
requestFile :: Method -> Path -> RequestHeaders -> FileSpec -> Request
requestFile m p hdr fileSpec = Request $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker
where
hdr' = addHeaders m p hdr
-- | Creating request with builder.
requestBuilder :: Method -> Path -> RequestHeaders -> Builder -> Request
requestBuilder m p hdr builder = Request $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker
where
hdr' = addHeaders m p hdr
-- | Creating request with streaming.
requestStreaming :: Method -> Path -> RequestHeaders
-> ((Builder -> IO ()) -> IO () -> IO ())
-> Request
requestStreaming m p hdr strmbdy = Request $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker
where
hdr' = addHeaders m p hdr
addHeaders :: Method -> Path -> RequestHeaders -> RequestHeaders
addHeaders m p hdr = (":method", m) : (":path", p) : hdr
-- | Setting 'TrailersMaker' to 'Response'.
setRequestTrailersMaker :: Request -> TrailersMaker -> Request
setRequestTrailersMaker (Request req) tm = Request req { outObjTrailers = tm }
----------------------------------------------------------------
-- | Getting the status of a response.
responseStatus :: Response -> Maybe Status
responseStatus (Response rsp) = getStatus $ inpObjHeaders rsp
-- | Getting the headers from a response.
responseHeaders :: Response -> HeaderTable
responseHeaders (Response rsp) = inpObjHeaders rsp
-- | Getting the body size from a response.
responseBodySize :: Response -> Maybe Int
responseBodySize (Response rsp) = inpObjBodySize rsp
-- | Reading a chunk of the response body.
-- An empty 'ByteString' returned when finished.
getResponseBodyChunk :: Response -> IO ByteString
getResponseBodyChunk (Response rsp) = inpObjBody rsp
-- | Reading response trailers.
-- This function must be called after 'getResponseBodyChunk'
-- returns an empty.
getResponseTrailers :: Response -> IO (Maybe HeaderTable)
getResponseTrailers (Response rsp) = readIORef (inpObjTrailers rsp)
| kazu-yamamoto/http2 | Network/HTTP2/Client.hs | bsd-3-clause | 4,669 | 0 | 14 | 973 | 783 | 455 | 328 | 71 | 1 |
{-# LANGUAGE TypeFamilies, TypeOperators, ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
-- For Transformable instance. Maybe move elsewhere
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
----------------------------------------------------------------------
-- |
-- Module : Pixie.TSFunTF
-- Copyright : (c) 2012 Tabula, Inc.
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Type-structured collections via type families
----------------------------------------------------------------------
module Pixie.TSFunTF where
-- TODO: explicit exports
import Prelude hiding (id,(.),fst,snd,curry,uncurry)
import Control.Category
import Control.Arrow
-- import Control.Newtype
import FunctorCombo.Functor (Const,Id,(:*:),(:+:),(:.),(<~))
import TypeUnary.Vec (Vec)
-- Maybe move elsewhere
import Diagrams.Prelude (Transformable(..),V)
import CatSynth.Has
import CatSynth.Decode
import CatSynth.Control.Arrow.Operations
#include "CatSynth/Has-inc.hs"
type a :* b = (a,b)
type a :+ b = Either a b
type family TS u t
type instance TS () t = ()
type instance TS (a :* b) t = TS a t :* TS b t
type instance TS (a :+ b) t = TS a t :+ TS b t -- Really?? Maybe product.
type instance TS [a] t = [TS a t]
type instance TS (Vec n a) t = Vec n (TS a t)
type instance TS Bool t = t -- TODO: add more
type TSFunX x (~>) a b = TS a x ~> TS b x
newtype TSFun x (~>) a b = TF { runTSFun :: TSFunX x (~>) a b }
inTF :: (TSFunX x (~>) a b -> TSFunX x' (+>) a' b')
-> (TSFun x (~>) a b -> TSFun x' (+>) a' b')
inTF = TF <~ runTSFun
inTF2 :: (TSFunX x (~>) a b -> TSFunX x' (+>) a' b' -> TSFunX x'' (@>) a'' b'')
-> (TSFun x (~>) a b -> TSFun x' (+>) a' b' -> TSFun x'' (@>) a'' b'')
inTF2 = inTF <~ runTSFun
-- instance Newtype (TSFun x (~>) a b) (TS a x ~> TS b x) where
-- pack = TF
-- unpack = runTSFun
--
-- Illegal type synonym family application in instance:
instance Category (~>) => Category (TSFun x (~>)) where
id = TF id
TF g . TF f = TF (g . f)
instance HasPair (~>) => Arrow (TSFun x (~>)) where
arr _ = error "arr: not defined for TSFun"
TF f *** TF g = TF (f *** g)
f &&& g = (f *** g) . dup
first f = f *** id
second g = id *** g
instance (Arrow (~>), HasPair (~>)) => HasPair (TSFun x (~>)) where
fst = TF fst
snd = TF snd
dup = TF dup
ldistribP = TF ldistribP
rdistribP = TF rdistribP
-- I don't think TSFun x can be an arrow transformer, since lift would have to
-- convert a ~> b to TS a ~> TS b.
instance (HasPair (~>), HasEither (~>), ArrowChoice (~>))
=> ArrowChoice (TSFun x (~>)) where
TF f +++ TF g = TF (f +++ g)
f ||| g = jam . (f +++ g)
left f = f +++ id
right g = id +++ g
instance (HasPair (~>), HasEither (~>)) => HasEither (TSFun x (~>)) where
lft = TF lft
rht = TF rht
jam = TF jam
ldistribS = TF ldistribS
rdistribS = TF rdistribS
-- instance (HasPair (~>), HasConst (~>)) => HasConst (TSFun x (~>)) where
-- lconst a = TF
-- class HasPair (~>) => HasConst (~>) where
-- type HasConstConstraint (~>) t :: Constraint
-- type HasConstConstraint (~>) t = HasConstConstraint0 (~>) t -- () -- NullC
-- lconst :: HasConstConstraint (~>) a => a -> (b ~> (a,b))
-- rconst :: HasConstConstraint (~>) b => b -> (a ~> (a,b))
-- const :: HasConstConstraint (~>) b => b -> (a ~> b)
-- const b = snd . rconst b
type instance TS (Id a) x = Id (TS a x)
instance HasId (~>) => HasId (TSFun x (~>)) where
toId = TF toId
unId = TF unId
type instance TS ((f :*: g) a) t = (f :*: g) (TS a t) -- etc
-- class Arrow (~>) => HasProd (~>) where
-- toProd :: (f a :* g a) ~> (f :*: g) a
-- unProd :: (f :*: g) a ~> (f a :* g a)
{-
instance (HasPair (~>), HasProd (~>)) =>
HasProd (TSFun x (~>)) where
toProd = TF toProd
-- unProd = TF unProd
-- type TSFunX x (~>) a b = TS a x ~> TS b x
-- newtype TSFun x (~>) a b = TF { runTSFun :: TSFunX x (~>) a b }
-- type instance TS (a :* b) t = TS a t :* TS b t
toProd :: (f a :* g a) ~> (f :*: g) a
want :: TS (f a :* g a) x ~> TS ((f :*: g) a) x
:: (TS (f a) x :* TS (g a) x) ~> (f :*: g) (TS a x)
-}
{--------------------------------------------------------------------
Maybe move elsewhere. Here to avoid orphans.
--------------------------------------------------------------------}
instance Transformable (TS a x ~> TS b x) =>
Transformable (TSFun x (~>) a b) where
transform tr = TF . transform tr . runTSFun
-- Needed for Transformable TSFun instance
type instance V (TSFun x (~>) a b) = V (TS a x ~> TS b x)
{--------------------------------------------------------------------
Dubious attempt at TSFun instances
--------------------------------------------------------------------}
{-
type instance TS (Const b a) t = Const (TS b t) a
type instance TS (Id a) t = Id (TS a t)
type instance TS ((f :*: g) a) t = (f :*: g) (TS a t)
-- TransInstances(TF,TSFun x,HasPair (~>))
TransInstance(HasConstF,toConst,unConst,TF,TSFun x,()~())
TransInstance(HasId,toId,unId,TF,TSFun x, ()~())
instance (HasPair(~>), Arrow (~>), HasProd (~>)) => HasProd (TSFun x (~>)) where
{ toProd = TF toProd ; unProd = TF unProd }
-- Could not deduce (TS (g a) x ~ g (TS a x))
-- from the context (HasPair (~>), Arrow (~>), HasProd (~>))
-- class Arrow (~>) => HasProd (~>) where
-- toProd :: (f a :* g a) ~> (f :*: g) a
-- unProd :: (f :*: g) a ~> (f a :* g a)
-- TransInstance(HasProd,toProd,unProd,TF,TSFun x, HasPair (~>))
-- TransInstance(HasSum,toSum,unSum,TF,TSFun x, ()~())
-- TransInstance(HasComp,toO,unO,TF,TSFun x, ()~())
-}
-- type TSFunX x (~>) a b = TS a x ~> TS b x
-- newtype TSFun x (~>) a b = TF { runTSFun :: TSFunX x (~>) a b }
-- class Category ar => Decode ar a where
-- decode :: a `ar` Decoding a
-- encode :: Decoding a `ar` a
-- instance Decode (TSFun x (->)) a where
-- -- decode :: TSFun x (->) a (Decoding a)
-- decode = TF (tsMap decode)
-- -- decode = TF (tsMap undefined)
-- Couldn't match type `TS (Decoding a) x' with `TS (Decoding a0) x0'
-- NB: `TS' is a type function, and may not be injective
-- Expected type: TSFunX x (->) a (Decoding a)
-- Actual type: TS a0 x0 -> TS (Decoding a0) x0
-- tsMap :: (a -> b) -> TS a x -> TS b x
-- tsMap = undefined
-- tsDecode :: TS a x -> TS (Decoding a) x
-- tsDecode = tsMap undefined
-- instance HasTrieCurry (~>) => HasTrieCurry (TSFun x (~>)) where
-- type TrieCurryConstraint s (TSFun x (~>)) a c =
-- ( TrieCurryConstraint (TS s x) (~>) (TS a x) (TS c x)
-- , TS (s :->: c) x ~ (TS s x :->: TS c x) )
-- trieCurry (TF f) = TF (trieCurry f)
-- class HasCurry (~>) where
-- curry :: ((a,b) ~> c) -> (a ~> (b ~> c))
-- uncurry :: (a ~> (b ~> c)) -> ((a,b) ~> c)
type instance TS (TSFun x (~>) b c) y = TS (TS x b ~> TS x c) y
instance HasCurry (~>) => HasCurry (TSFun x (~>)) where
type CurryConstraint (TSFun x (~>)) a b c =
( CurryConstraint (~>) (TS a x) (TS b x) (TS c x)
, TS (TS x b ~> TS x c) x ~ (TS b x ~> TS c x) )
curry = inTF curry
uncurry = inTF uncurry
| conal/pixie | src/Pixie/TSFunTF.hs | bsd-3-clause | 7,433 | 5 | 11 | 1,772 | 1,473 | 842 | 631 | 78 | 1 |
module Main where
multiplesOf3or5 :: Int -> Int
multiplesOf3or5 upTo = sum . takeWhile (< upTo) . filter divisibleBy3Or5 $ [1..]
where
divisibleBy3Or5 x = x `mod` 3 == 0 || x `mod` 5 == 0
main = do
let number = multiplesOf3or5 1000
putStrLn $ "Sum: " ++ (show number)
| tomob/euler | 001/001.hs | bsd-3-clause | 288 | 0 | 11 | 71 | 114 | 60 | 54 | 7 | 1 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.VertexWeighting
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the EXT_vertex_weighting extension, see
-- <http://www.opengl.org/registry/specs/EXT/vertex_weighting.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.VertexWeighting (
-- * Functions
glVertexWeightf,
glVertexWeightfv,
glVertexWeightPointer,
-- * Tokens
gl_VERTEX_WEIGHTING,
gl_MODELVIEW0,
gl_MODELVIEW1,
gl_MODELVIEW0_MATRIX,
gl_MODELVIEW1_MATRIX,
gl_CURRENT_VERTEX_WEIGHT,
gl_VERTEX_WEIGHT_ARRAY,
gl_VERTEX_WEIGHT_ARRAY_SIZE,
gl_VERTEX_WEIGHT_ARRAY_TYPE,
gl_VERTEX_WEIGHT_ARRAY_STRIDE,
gl_MODELVIEW0_STACK_DEPTH,
gl_MODELVIEW1_STACK_DEPTH,
gl_VERTEX_WEIGHT_ARRAY_POINTER
) where
import Foreign.Ptr
import Foreign.C.Types
import Graphics.Rendering.OpenGL.Raw.Core31.Types
import Graphics.Rendering.OpenGL.Raw.ARB.VertexBlend
import Graphics.Rendering.OpenGL.Raw.Extensions
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_EXT_vertex_weighting"
EXTENSION_ENTRY(dyn_glVertexWeightf,ptr_glVertexWeightf,"glVertexWeightf",glVertexWeightf,GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glVertexWeightfv,ptr_glVertexWeightfv,"glVertexWeightfv",glVertexWeightfv,Ptr GLfloat -> IO ())
EXTENSION_ENTRY(dyn_glVertexWeightPointer,ptr_glVertexWeightPointer,"glVertexWeightPointer",glVertexWeightPointer,GLint -> GLenum -> GLsizei -> Ptr a -> IO ())
gl_VERTEX_WEIGHTING :: GLenum
gl_VERTEX_WEIGHTING = 0x8509
gl_MODELVIEW0_MATRIX :: GLenum
gl_MODELVIEW0_MATRIX = 0x0BA6
gl_MODELVIEW1_MATRIX :: GLenum
gl_MODELVIEW1_MATRIX = 0x8506
gl_CURRENT_VERTEX_WEIGHT :: GLenum
gl_CURRENT_VERTEX_WEIGHT = 0x850B
gl_VERTEX_WEIGHT_ARRAY :: GLenum
gl_VERTEX_WEIGHT_ARRAY = 0x850C
gl_VERTEX_WEIGHT_ARRAY_SIZE :: GLenum
gl_VERTEX_WEIGHT_ARRAY_SIZE = 0x850D
gl_VERTEX_WEIGHT_ARRAY_TYPE :: GLenum
gl_VERTEX_WEIGHT_ARRAY_TYPE = 0x850E
gl_VERTEX_WEIGHT_ARRAY_STRIDE :: GLenum
gl_VERTEX_WEIGHT_ARRAY_STRIDE = 0x850F
gl_MODELVIEW0_STACK_DEPTH :: GLenum
gl_MODELVIEW0_STACK_DEPTH = 0x0BA3
gl_MODELVIEW1_STACK_DEPTH :: GLenum
gl_MODELVIEW1_STACK_DEPTH = 0x8502
gl_VERTEX_WEIGHT_ARRAY_POINTER :: GLenum
gl_VERTEX_WEIGHT_ARRAY_POINTER = 0x8510
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/VertexWeighting.hs | bsd-3-clause | 2,588 | 0 | 13 | 275 | 341 | 214 | 127 | -1 | -1 |
{-
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[FloatOut]{Float bindings outwards (towards the top level)}
``Long-distance'' floating of bindings towards the top level.
-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
{-# LANGUAGE CPP #-}
module Language.SequentCore.FloatOut ( runFloatOut, floatOutwards ) where
import Language.SequentCore.Arity
import Language.SequentCore.Driver.Flags
import Language.SequentCore.FloatOut.SetLevels
import Language.SequentCore.Lint
import Language.SequentCore.Syntax
import Language.SequentCore.Syntax.Util
import CoreSyn ( tickishScoped, mkNoCount )
import CoreMonad ( CoreM )
import DynFlags
import ErrUtils ( dumpIfSet_dyn )
import Id ( Id, idArity, isBottomingId, zapDemandIdInfo )
import Var ( Var )
import UniqSupply ( UniqSupply, getUniqueSupplyM )
import Bag
import Util
import Maybes
import Outputable
import FastString
import MonadUtils ( liftIO )
import Control.Applicative ( (<$>), (<*>), pure )
import Control.Monad.Trans.Writer.Lazy
import qualified Data.IntMap as M
import Data.Monoid
#define ASSERT(e) if debugIsOn && not (e) then (assertPanic __FILE__ __LINE__) else
#define ASSERT2(e,msg) if debugIsOn && not (e) then (assertPprPanic __FILE__ __LINE__ (msg)) else
#define WARN( e, msg ) (warnPprTrace (e) __FILE__ __LINE__ (msg)) $
runFloatOut :: FloatOutSwitches -> SeqFlags
-> SeqCoreProgram
-> CoreM SeqCoreProgram
runFloatOut switches sflags binds
= do
dflags <- getDynFlags
us <- getUniqueSupplyM
liftIO $ floatOutwards switches dflags sflags us binds
{-
-----------------
Overall game plan
-----------------
The Big Main Idea is:
To float out sub-expressions that can thereby get outside
a non-one-shot value lambda, and hence may be shared.
To achieve this we may need to do two thing:
a) Let-bind the sub-expression:
f (g x) ==> let lvl = f (g x) in lvl
Now we can float the binding for 'lvl'.
b) More than that, we may need to abstract wrt a type variable
\x -> ... /\a -> let v = ...a... in ....
Here the binding for v mentions 'a' but not 'x'. So we
abstract wrt 'a', to give this binding for 'v':
vp = /\a -> ...a...
v = vp a
Now the binding for vp can float out unimpeded.
I can't remember why this case seemed important enough to
deal with, but I certainly found cases where important floats
didn't happen if we did not abstract wrt tyvars.
With this in mind we can also achieve another goal: lambda lifting.
We can make an arbitrary (function) binding float to top level by
abstracting wrt *all* local variables, not just type variables, leaving
a binding that can be floated right to top level. Whether or not this
happens is controlled by a flag.
Random comments
~~~~~~~~~~~~~~~
At the moment we never float a binding out to between two adjacent
lambdas. For example:
@
\x y -> let t = x+x in ...
===>
\x -> let t = x+x in \y -> ...
@
Reason: this is less efficient in the case where the original lambda
is never partially applied.
But there's a case I've seen where this might not be true. Consider:
@
elEm2 x ys
= elem' x ys
where
elem' _ [] = False
elem' x (y:ys) = x==y || elem' x ys
@
It turns out that this generates a subexpression of the form
@
\deq x ys -> let eq = eqFromEqDict deq in ...
@
vwhich might usefully be separated to
@
\deq -> let eq = eqFromEqDict deq in \xy -> ...
@
Well, maybe. We don't do this at the moment.
%************************************************************************
%* *
\subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
%* *
%************************************************************************
-}
floatOutwards :: FloatOutSwitches
-> DynFlags
-> SeqFlags
-> UniqSupply
-> SeqCoreProgram -> IO SeqCoreProgram
floatOutwards float_sws dflags sflags us pgm
= do {
let { annotated_w_levels = setLevels dflags sflags float_sws pgm us ;
(fss, binds_s') = unzip (map floatTopBind annotated_w_levels)
} ;
dumpIfSet_dyn dflags Opt_D_verbose_core2core "Levels added:"
(vcat (map ppr annotated_w_levels));
(assertLintProgram "mid-floatOutwards" (map deTag annotated_w_levels) $
text "--- Pre-float: ---" $$ vcat (map ppr pgm))
`seq` return ();
let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "FloatOut stats:"
(hcat [ int tlets, ptext (sLit " Lets floated to top level; "),
int ntlets, ptext (sLit " Lets floated elsewhere; from "),
int lams, ptext (sLit " Lambda groups")]);
return $ assertLintProgram "floatOutwards" (bagToList (unionManyBags binds_s')) $
text "--- With levels: ---" $$ vcat (map ppr annotated_w_levels)
}
floatTopBind :: Levelled Bind -> (FloatStats, Bag SeqCoreBind)
floatTopBind bind
= case runFloatM (floatBind bind) of { (fs, floats, bind') ->
let float_bag = flattenTopFloats floats
in case bind' of
Rec prs -> (fs, unitBag (Rec (addTopFloatPairs float_bag prs)))
NonRec {} -> (fs, float_bag `snocBag` bind') }
{-
%************************************************************************
%* *
\subsection[FloatOut-Bind]{Floating in a binding (the business end)}
%* *
%************************************************************************
-}
type FloatM = Writer (FloatStats, FloatBinds)
runFloatM :: FloatM a -> (FloatStats, FloatBinds, a)
runFloatM m = case runWriter m of (a, (fs, binds)) -> (fs, binds, a)
captureFloats :: FloatM a -> FloatM (FloatBinds, a)
captureFloats m = writer $ case runWriter m of { (a, (stats, floats)) ->
((floats, a), (stats, emptyFloats)) }
emitFloats :: FloatBinds -> FloatM ()
emitFloats binds = writer ((), (zeroStats, binds))
emitLetBind :: Level -> FloatLet -> FloatM ()
emitLetBind lvl bind = emitFloats (unitLetFloat lvl bind)
-- Run an action, then remove the floated bindings of at least the given level
-- and return them with the result, keeping the lesser-level bindings in the output
captureFloatsAtLevel :: Level -> FloatM a -> FloatM (Bag FloatBind, a)
captureFloatsAtLevel lvl m
= writer $ case runWriter m of { (a, (stats, floats)) ->
case partitionByLevel lvl floats of { (floats', heres) ->
((heres, a), (stats, floats')) }}
addingToStats :: FloatM a -> FloatM a
addingToStats m
= writer $ case runWriter m of { (a, (fs, floats)) ->
(a, (add_to_stats fs floats, floats)) }
floatBind :: Levelled Bind -> FloatM SeqCoreBind
floatBind (NonRec pair)
= do
let (TB var _) = binderOfPair pair
pair' <- floatRhs pair
-- A tiresome hack:
-- see Note [Bottoming floats: eta expansion] in SetLevels
let pair'' | isBottomingId var = etaExpandRhs (idArity var) pair'
| otherwise = pair'
return $ NonRec pair''
floatBind (Rec pairs)
= mapM do_pair pairs >>= \new_pairs ->
return $ Rec (concat new_pairs)
where
do_pair pair
| isTopLvl dest_lvl -- See Note [floatBind for top level]
= captureFloats (floatRhs pair) >>= \(rhs_floats, pair') ->
return $ addTopFloatPairs (flattenTopFloats rhs_floats) [pair']
| otherwise -- Note [Floating out of Rec rhss]
= captureFloatsAtLevel dest_lvl (floatRhs pair) >>= \(heres, pair') ->
case (splitRecFloats heres) of { (pairs, case_heres) -> do
return $ installUnderLambdas case_heres pair' : pairs }
where
TB _name spec = binderOfPair pair
dest_lvl = floatSpecLevel spec
splitRecFloats :: Bag FloatBind -> ([SeqCoreBindPair], Bag FloatBind)
-- The "tail" begins with a case
-- See Note [Floating out of Rec rhss]
splitRecFloats fs
= go [] (bagToList fs)
where
go prs (FloatLet (NonRec pair) : fs) = go (pair:prs) fs
go prs (FloatLet (Rec prs') : fs) = go (prs' ++ prs) fs
go prs fs = (prs, listToBag fs)
installUnderLambdas :: Bag FloatBind -> SeqCoreBindPair -> SeqCoreBindPair
-- Note [Floating out of Rec rhss]
installUnderLambdas floats pair
| isEmptyBag floats = pair
installUnderLambdas floats (BindJoin bndr (Join bndrs comm))
= BindJoin bndr (Join bndrs (installInCommand floats comm))
installUnderLambdas floats (BindTerm bndr term)
= BindTerm bndr (go term)
where
go (Lam b e) = Lam b (go e)
go e = installInTerm floats e
floatRhs :: Levelled BindPair -> FloatM SeqCoreBindPair
floatRhs (BindTerm (TB bndr _) term)
= BindTerm bndr <$> floatTerm term
floatRhs (BindJoin (TB bndr _) join)
= BindJoin bndr <$> floatJoin join
{-
Note [Floating out of Rec rhss]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider Rec { f<1,0> = \xy. body }
From the body we may get some floats. The ones with level <1,0> must
stay here, since they may mention f. Ideally we'd like to make them
part of the Rec block pairs -- but we can't if there are any
FloatCases involved.
Nor is it a good idea to dump them in the rhs, but outside the lambda
f = case x of I# y -> \xy. body
because now f's arity might get worse, which is Not Good. (And if
there's an SCC around the RHS it might not get better again.
See Trac #5342.)
So, gruesomely, we split the floats into
* the outer FloatLets, which can join the Rec, and
* an inner batch starting in a FloatCase, which are then
pushed *inside* the lambdas.
This loses full-laziness the rare situation where there is a
FloatCase and a Rec interacting.
Note [floatBind for top level]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We may have a *nested* binding whose destination level is (FloatMe tOP_LEVEL), thus
letrec { foo <0,0> = .... (let bar<0,0> = .. in ..) .... }
The binding for bar will be in the "tops" part of the floating binds,
and thus not partioned by floatBody.
We could perhaps get rid of the 'tops' component of the floating binds,
but this case works just as well.
%************************************************************************
\subsection[FloatOut-Expr]{Floating in expressions}
%* *
%************************************************************************
-}
floatBodyComm :: Level
-> Levelled Command
-> FloatM SeqCoreCommand
floatBodyComm lvl comm -- Used case-alternative rhss
= captureFloatsAtLevel lvl (floatComm comm) >>= \(heres, comm') ->
return $ installInCommand heres comm'
floatBodyTerm :: Level
-> Levelled Term
-> FloatM SeqCoreTerm
floatBodyTerm lvl term -- Used rec rhss
= captureFloatsAtLevel lvl (floatTerm term) >>= \(heres, term') ->
return $ installInTerm heres term'
-----------------
floatTerm :: Levelled Term
-> FloatM SeqCoreTerm
floatTerm (Var v) = return $ Var v
floatTerm (Type ty) = return $ Type ty
floatTerm (Coercion co) = return $ Coercion co
floatTerm (Lit lit) = return $ Lit lit
floatTerm lam@(Lam (TB _ lam_spec) _)
= do
let (bndrs_w_lvls, body) = collectBinders lam
bndrs = [b | TB b _ <- bndrs_w_lvls]
bndr_lvl = floatSpecLevel lam_spec
-- All the binders have the same level
-- See SetLevels.lvlLamBndrs
body' <- addingToStats $ floatBodyTerm bndr_lvl body
return $ mkLambdas bndrs body'
floatTerm (Compute ty comm)
= Compute ty <$> floatComm comm
floatComm :: Levelled Command
-> FloatM SeqCoreCommand
floatComm (Let bind body)
= case bind_spec of
FloatMe dest_lvl
-> do
bind' <- floatBind bind
emitLetBind dest_lvl bind'
body' <- floatComm body
return body'
StayPut bind_lvl -- See Note [Avoiding unnecessary floating]
-> Let <$> floatBind bind <*> floatBodyComm bind_lvl body
where
bind_spec = case bindersOf bind of
TB _ s : _ -> s
_ -> panic "floatTerm"
floatComm (Eval term frames end)
= doEnd end
where
doEnd Return = do
(term', frames') <- doFrames
return $ Eval term' frames' Return
doEnd (Case (TB case_bndr case_spec) alts)
= case case_spec of
FloatMe dest_lvl -- Case expression moves
| [Alt con@(DataAlt {}) bndrs rhs] <- alts
-> do
(term', frames') <- doFrames
let scrut' = mkComputeEval term' frames'
float = unitCaseFloat dest_lvl scrut'
case_bndr con [b | TB b _ <- bndrs]
emitFloats float
floatComm rhs
| otherwise
-> pprPanic "Floating multi-case" (ppr alts)
StayPut bind_lvl -- Case expression stays put
-> do
(term', frames') <- doFrames
end' <- Case case_bndr <$> mapM (float_alt bind_lvl) alts
return $ Eval term' frames' end'
where
float_alt bind_lvl (Alt con bs rhs)
= Alt con [b | TB b _ <- bs] <$> floatBodyComm bind_lvl rhs
doFrames = go (reverse frames) []
-- In reverse because a tick influences the floats that come
-- from the term and the frames *before* it (remember that our
-- representation is "upside-down" from Core).
where
go :: [Levelled Frame] -- in reverse
-> [SeqCoreFrame] -> FloatM (SeqCoreTerm, [SeqCoreFrame])
go [] acc
= do
term' <- floatTerm term
return (term', acc)
go (App arg : fs_rev) acc
= do
-- Match GHC's float order
(floats1, arg') <- captureFloats $ floatTerm arg
(floats2, ans) <- captureFloats $ go fs_rev (App arg' : acc)
emitFloats floats2
emitFloats floats1
return ans
go (Cast co : fs_rev) acc
= go fs_rev (Cast co : acc)
go (Tick ti : fs_rev) acc
| tickishScoped ti
= do
(floats, (term', fs')) <- captureFloats $ go fs_rev (Tick ti : acc)
-- Annotate bindings floated outwards past an scc expression
-- with the cc. We mark that cc as "duplicated", though.
let annotated_floats = wrapTick (mkNoCount ti) floats
emitFloats annotated_floats
return (term', fs')
| otherwise -- not scoped, can just float
= go fs_rev (Tick ti : acc)
floatComm (Jump args j)
= Jump <$> mapM floatTerm args <*> pure j
floatJoin :: Levelled Join -> FloatM SeqCoreJoin
floatJoin (Join bndrs_w_lvls@(TB _ lam_spec : _) body)
= do
let bndrs = [b | TB b _ <- bndrs_w_lvls]
bndr_lvl = floatSpecLevel lam_spec
-- All the binders have the same level
-- See SetLevels.lvlLamBndrs
body' <- addingToStats $ floatBodyComm bndr_lvl body
return $ Join bndrs body'
floatJoin (Join [] body)
= Join [] <$> floatComm body
{-
Note [Avoiding unnecessary floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general we want to avoid floating a let unnecessarily, because
it might worsen strictness:
let
x = ...(let y = e in y+y)....
Here y is demanded. If we float it outside the lazy 'x=..' then
we'd have to zap its demand info, and it may never be restored.
So at a 'let' we leave the binding right where the are unless
the binding will escape a value lambda, e.g.
(\x -> let y = fac 100 in y)
That's what the partitionByMajorLevel does in the floatTerm (Let ...)
case.
Notice, though, that we must take care to drop any bindings
from the body of the let that depend on the staying-put bindings.
We used instead to do the partitionByMajorLevel on the RHS of an '=',
in floatRhs. But that was quite tiresome. We needed to test for
values or trival rhss, because (in particular) we don't want to insert
new bindings between the "=" and the "\". E.g.
f = \x -> let <bind> in <body>
We do not want
f = let <bind> in \x -> <body>
(a) The simplifier will immediately float it further out, so we may
as well do so right now; in general, keeping rhss as manifest
values is good
(b) If a float-in pass follows immediately, it might add yet more
bindings just after the '='. And some of them might (correctly)
be strict even though the 'let f' is lazy, because f, being a value,
gets its demand-info zapped by the simplifier.
And even all that turned out to be very fragile, and broke
altogether when profiling got in the way.
So now we do the partition right at the (Let..) itself.
%************************************************************************
%* *
\subsection{Utility bits for floating stats}
%* *
%************************************************************************
I didn't implement this with unboxed numbers. I don't want to be too
strict in this stuff, as it is rarely turned on. (WDP 95/09)
-}
data FloatStats
= FlS Int -- Number of top-floats * lambda groups they've been past
Int -- Number of non-top-floats * lambda groups they've been past
Int -- Number of lambda (groups) seen
get_stats :: FloatStats -> (Int, Int, Int)
get_stats (FlS a b c) = (a, b, c)
zeroStats :: FloatStats
zeroStats = FlS 0 0 0
sum_stats :: [FloatStats] -> FloatStats
sum_stats xs = foldr add_stats zeroStats xs
add_stats :: FloatStats -> FloatStats -> FloatStats
add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
= FlS (a1 + a2) (b1 + b2) (c1 + c2)
add_to_stats :: FloatStats -> FloatBinds -> FloatStats
add_to_stats (FlS a b c) (FB tops others)
= FlS (a + lengthBag tops) (b + lengthBag (flattenMajor others)) (c + 1)
instance Monoid FloatStats where
mempty = zeroStats
mappend = add_stats
mconcat = sum_stats
{-
%************************************************************************
%* *
\subsection{Utility bits for floating}
%* *
%************************************************************************
Note [Representation of FloatBinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FloatBinds types is somewhat important. We can get very large numbers
of floating bindings, often all destined for the top level. A typical example
is x = [4,2,5,2,5, .... ]
Then we get lots of small expressions like (fromInteger 4), which all get
lifted to top level.
The trouble is that
(a) we partition these floating bindings *at every binding site*
(b) SetLevels introduces a new bindings site for every float
So we had better not look at each binding at each binding site!
That is why MajorEnv is represented as a finite map.
We keep the bindings destined for the *top* level separate, because
we float them out even if they don't escape a *value* lambda; see
partitionByMajorLevel.
-}
type FloatLet = SeqCoreBind -- INVARIANT: a FloatLet is always lifted
type MajorEnv = M.IntMap MinorEnv -- Keyed by major level
type MinorEnv = M.IntMap (Bag FloatBind) -- Keyed by minor level
data FloatBinds = FB !(Bag FloatLet) -- Destined for top level
!MajorEnv -- Levels other than top
-- See Note [Representation of FloatBinds]
instance Outputable FloatBind where
ppr (FloatLet b) = ptext (sLit "LET") <+> ppr b
ppr (FloatCase e b c bs) = hang (ptext (sLit "CASE") <+> ppr e <+> ptext (sLit "of") <+> ppr b)
2 (ppr c <+> ppr bs)
instance Outputable FloatBinds where
ppr (FB fbs defs)
= ptext (sLit "FB") <+> (braces $ vcat
[ ptext (sLit "tops =") <+> ppr fbs
, ptext (sLit "non-tops =") <+> ppr defs ])
instance Monoid FloatBinds where
mempty = emptyFloats
mappend = plusFloats
flattenTopFloats :: FloatBinds -> Bag SeqCoreBind
flattenTopFloats (FB tops defs)
= ASSERT2( isEmptyBag (flattenMajor defs), ppr defs )
mapBag (mapBindersOfBind zapDemandIdInfo) tops
-- Can't have strict lets at top level. This appears to happen only if
-- the let was created during pre-prep to name a strict argument and then
-- floated to top level.
-- TODO: Figure out why this never has to be done in original FloatOut.
addTopFloatPairs :: Bag SeqCoreBind -> [SeqCoreBindPair] -> [SeqCoreBindPair]
addTopFloatPairs float_bag prs
= foldrBag add prs float_bag
where
add (NonRec pair) prs = pair:prs
add (Rec prs1) prs2 = prs1 ++ prs2
flattenMajor :: MajorEnv -> Bag FloatBind
flattenMajor = M.fold (unionBags . flattenMinor) emptyBag
flattenMinor :: MinorEnv -> Bag FloatBind
flattenMinor = M.fold unionBags emptyBag
emptyFloats :: FloatBinds
emptyFloats = FB emptyBag M.empty
unitCaseFloat :: Level -> SeqCoreTerm -> Id -> AltCon -> [Var] -> FloatBinds
unitCaseFloat (Level major minor) e b con bs
= FB emptyBag (M.singleton major (M.singleton minor (unitBag (FloatCase e b con bs))))
unitLetFloat :: Level -> FloatLet -> FloatBinds
unitLetFloat lvl@(Level major minor) b
| isTopLvl lvl = FB (unitBag b) M.empty
| otherwise = FB emptyBag (M.singleton major (M.singleton minor floats))
where
floats = unitBag (FloatLet b)
plusFloats :: FloatBinds -> FloatBinds -> FloatBinds
plusFloats (FB t1 l1) (FB t2 l2)
= FB (t1 `unionBags` t2) (l1 `plusMajor` l2)
plusMajor :: MajorEnv -> MajorEnv -> MajorEnv
plusMajor = M.unionWith plusMinor
plusMinor :: MinorEnv -> MinorEnv -> MinorEnv
plusMinor = M.unionWith unionBags
installInTerm :: Bag FloatBind -> SeqCoreTerm -> SeqCoreTerm
installInTerm defn_groups expr
= foldrBag wrapTermInFloat expr defn_groups
installInCommand :: Bag FloatBind -> SeqCoreCommand -> SeqCoreCommand
installInCommand defn_groups expr
= foldrBag wrapFloat expr defn_groups
partitionByLevel
:: Level -- Partitioning level
-> FloatBinds -- Defns to be divided into 2 piles...
-> (FloatBinds, -- Defns with level strictly < partition level,
Bag FloatBind) -- The rest
{-
-- ---- partitionByMajorLevel ----
-- Float it if we escape a value lambda,
-- *or* if we get to the top level
-- *or* if it's a case-float and its minor level is < current
--
-- If we can get to the top level, say "yes" anyway. This means that
-- x = f e
-- transforms to
-- lvl = e
-- x = f lvl
-- which is as it should be
partitionByMajorLevel (Level major _) (FB tops defns)
= (FB tops outer, heres `unionBags` flattenMajor inner)
where
(outer, mb_heres, inner) = M.splitLookup major defns
heres = case mb_heres of
Nothing -> emptyBag
Just h -> flattenMinor h
-}
partitionByLevel (Level major minor) (FB tops defns)
= (FB tops (outer_maj `plusMajor` M.singleton major outer_min),
here_min `unionBags` flattenMinor inner_min
`unionBags` flattenMajor inner_maj)
where
(outer_maj, mb_here_maj, inner_maj) = M.splitLookup major defns
(outer_min, mb_here_min, inner_min) = case mb_here_maj of
Nothing -> (M.empty, Nothing, M.empty)
Just min_defns -> M.splitLookup minor min_defns
here_min = mb_here_min `orElse` emptyBag
wrapTick :: Tickish Id -> FloatBinds -> FloatBinds
wrapTick t (FB tops defns)
= FB (mapBag wrap_bind tops) (M.map (M.map wrap_defns) defns)
where
wrap_defns = mapBag wrap_one
wrap_bind (NonRec pair) = NonRec (wrap_pair pair)
wrap_bind (Rec pairs) = Rec (map wrap_pair pairs)
wrap_pair (BindTerm b term) = BindTerm b (maybe_tick term)
wrap_pair _ = panic "wrapTick"
wrap_one (FloatLet bind) = FloatLet (wrap_bind bind)
wrap_one (FloatCase e b c bs) = FloatCase (maybe_tick e) b c bs
maybe_tick e | termIsHNF e = tickHNFArgs t e
| otherwise = mkTickTerm t e
-- we don't need to wrap a tick around an HNF when we float it
-- outside a tick: that is an invariant of the tick semantics
-- Conversely, inlining of HNFs inside an SCC is allowed, and
-- indeed the HNF we're floating here might well be inlined back
-- again, and we don't want to end up with duplicate ticks.
| lukemaurer/sequent-core | src/Language/SequentCore/FloatOut.hs | bsd-3-clause | 25,454 | 276 | 19 | 6,995 | 4,594 | 2,431 | 2,163 | 329 | 8 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Aeson.Versions.AesonExtensions where
import Data.Aeson
import Data.Aeson.Types
import Data.Functor.Identity
import Data.Traversable
import Data.Maybe
-- | A typeclass to represent serializations that can possibly fail
-- for example if a constructor of a sum type is not available for
-- a specific version
class FailableToJSON a where
mToJSON :: a -> Maybe Value
-- | Anything that has a non failable `ToJSON` instance can be lifted
-- into `FailableToJSON`
instance {-# OVERLAPPABLE #-} ToJSON a => FailableToJSON a where
mToJSON = Just . toJSON
-- | This is sort of analogous to how `MonadPlus` is related to
-- `Monoid`. Specifies that whatever we put inside the functor,
-- it's still serializable. Instances should just be
-- `fToJSON = toJSON`
class Functor f => FunctorToJSON f where
fToJSON :: ToJSON a => f a -> Value
-- | The opposite of `FunctorFailableToJSON` (`FromJSON` is
-- already failable). Instances should all be identical, with
-- `fParseJSON` equaling a specific instantiation of `parseJSON`
class Traversable t => TraversableFromJSON t where
fParseJSON :: FromJSON a => Value -> Parser (t a)
instance FunctorToJSON Identity where
fToJSON = toJSON
instance TraversableFromJSON Identity where
fParseJSON = parseJSON
instance FunctorToJSON [] where
fToJSON = toJSON
instance TraversableFromJSON [] where
fParseJSON = parseJSON
instance FunctorToJSON Maybe where
fToJSON = toJSON
| vfiles/aeson-versioned | src/Data/Aeson/Versions/AesonExtensions.hs | bsd-3-clause | 1,517 | 0 | 11 | 251 | 240 | 132 | 108 | 26 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
#ifdef DECLARE_NFDATA_INSTANCE
{-# LANGUAGE BangPatterns #-}
#endif
#ifdef DECLARE_SAFECOPY_INSTANCE
{-# LANGUAGE TemplateHaskell #-}
#endif
#ifdef DECLARE_DHALL_INSTANCES
{-# LANGUAGE DeriveAnyClass #-}
#endif
-- |
-- Module: $HEADER$
-- Description: Verbosity enum.
-- Copyright: (c) 2015-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Simple enum that encodes application 'Verbosity'.
module Data.Verbosity
( Verbosity(..)
, increment
, increment'
, fromInt
, parse
)
where
import Prelude
( Bounded(maxBound, minBound)
, Enum(fromEnum, succ, toEnum)
#ifdef DECLARE_BINARY_INSTANCE
, fromIntegral
#endif
)
import Data.Bool ((&&), otherwise)
import Data.Data (Data)
import Data.Eq (Eq)
import Data.Int (Int)
import Data.Kind (Type)
import Data.List (lookup)
import Data.Maybe (Maybe(Just, Nothing), fromMaybe)
import Data.Ord
( Ord
, (<)
, (<=)
, (>=)
#ifdef DECLARE_LATTICE_INSTANCES
, max
, min
#endif
)
import Data.String (IsString, String, fromString)
import GHC.Generics
( (:+:)(L1, R1)
, C1
, Constructor
, D1
, Generic
, M1(M1)
, conName
, from
)
import Text.Read (Read)
import Text.Show (Show)
#if defined(DECLARE_BINARY_INSTANCE) || defined(DECLARE_SERIALIZE_INSTANCE)
import Control.Applicative ((<$>))
import Data.Function ((.))
#endif
#ifdef DECLARE_BINARY_INSTANCE
import Data.Binary (Binary(get, put))
import qualified Data.Binary as Binary (getWord8, putWord8)
#endif
#ifdef DECLARE_SAFECOPY_INSTANCE
import Data.SafeCopy (deriveSafeCopy)
import qualified Data.SafeCopy as SafeCopy (base)
#endif
#ifdef DECLARE_SERIALIZE_INSTANCE
import qualified Data.Serialize as Cereal (Serialize(..), getWord8, putWord8)
#endif
#ifdef DECLARE_NFDATA_INSTANCE
import Control.DeepSeq (NFData(rnf))
#endif
#ifdef DECLARE_LATTICE_INSTANCES
#if MIN_VERSION_lattices(2,0,0)
import Algebra.Lattice
( BoundedJoinSemiLattice(bottom)
, BoundedMeetSemiLattice(top)
, Lattice((/\), (\/))
)
#else
import Algebra.Lattice
( BoundedJoinSemiLattice(bottom)
, BoundedLattice
, BoundedMeetSemiLattice(top)
, JoinSemiLattice((\/))
, Lattice
, MeetSemiLattice((/\))
)
#endif
#endif
#ifdef DECLARE_DHALL_INSTANCES
#if MIN_VERSION_dhall(1,27,0)
import Dhall (FromDhall, ToDhall)
#else
import qualified Dhall (Inject, Interpret)
#endif
#endif
#ifdef DECLARE_SERIALISE_INSTANCE
import Codec.Serialise (Serialise)
#endif
-- | Ordering:
--
-- @
-- 'Silent' < 'Normal' < 'Verbose' < 'Annoying'
-- @
--
-- Bounds:
--
-- @
-- 'minBound' = 'Silent'; 'maxBound' = 'Annoying'
-- @
--
-- Enum:
--
-- @
-- map 'fromEnum' ['Silent' .. 'Annoying'] = [0, 1, 2, 3]
-- @
data Verbosity
= Silent
-- ^ Don't print any messages.
| Normal
-- ^ Print only important messages. (default)
| Verbose
-- ^ Print anything that comes to mind.
| Annoying
-- ^ Print debugging\/tracing information.
deriving stock
( Bounded
, Data
, Enum
, Eq
, Generic
, Ord
, Read
, Show
)
#ifdef DECLARE_DHALL_INSTANCES
#if MIN_VERSION_dhall(1,27,0)
deriving anyclass (FromDhall, ToDhall)
#else
deriving anyclass (Dhall.Inject, Dhall.Interpret)
#endif
#endif
#ifdef DECLARE_SERIALISE_INSTANCE
deriving anyclass (Serialise)
#endif
#ifdef DECLARE_BINARY_INSTANCE
-- | Encoded as one byte in range @['minBound' .. 'maxBound' :: Verbosity]@.
instance Binary Verbosity where
get = toEnum . fromIntegral <$> Binary.getWord8
put = Binary.putWord8 . fromIntegral . fromEnum
#endif
#ifdef DECLARE_SERIALIZE_INSTANCE
-- | Encoded as one byte in range @['minBound' .. 'maxBound' :: Verbosity]@.
instance Cereal.Serialize Verbosity where
get = toEnum . fromIntegral <$> Cereal.getWord8
put = Cereal.putWord8 . fromIntegral . fromEnum
#endif
#ifdef DECLARE_SAFECOPY_INSTANCE
deriveSafeCopy 0 'SafeCopy.base ''Verbosity
#endif
#ifdef DECLARE_NFDATA_INSTANCE
instance NFData Verbosity where
rnf !_ = ()
#endif
#ifdef DECLARE_LATTICE_INSTANCES
#if MIN_VERSION_lattices(2,0,0)
-- |
-- @
-- ('\/') = 'max'
-- ('/\') = 'min'
-- @
instance Lattice Verbosity where
(\/) = max
(/\) = min
-- | @'bottom' = 'Silent'@
instance BoundedJoinSemiLattice Verbosity where
bottom = minBound
-- | @'top' = 'Annoying'@
instance BoundedMeetSemiLattice Verbosity where
top = maxBound
#else
-- | @('\/') = 'max'@
instance JoinSemiLattice Verbosity where
(\/) = max
-- | @'bottom' = 'Silent'@
instance BoundedJoinSemiLattice Verbosity where
bottom = minBound
-- | @('/\') = 'min'@
instance MeetSemiLattice Verbosity where
(/\) = min
-- | @'top' = 'Annoying'@
instance BoundedMeetSemiLattice Verbosity where
top = maxBound
instance Lattice Verbosity
instance BoundedLattice Verbosity
#endif
-- DECLARE_LATTICE_INSTANCES
#endif
-- | Increment verbosity level. Return 'Nothing' if trying to icrement beyond
-- 'maxBound'.
increment :: Verbosity -> Maybe Verbosity
increment v
| v < maxBound = Just (succ v)
| otherwise = Nothing
-- | Variant of 'increment' that doesn't fail when 'maxBound' is reached. It
-- is defined as:
--
-- @
-- 'increment'' v = 'fromMaybe' v ('increment' v)
-- @
increment' :: Verbosity -> Verbosity
increment' v = fromMaybe v (increment v)
-- | Safe version of 'toEnum' specialized to 'Verbosity'.
fromInt :: Int -> Maybe Verbosity
fromInt n
| n >= minVerbosity && n <= maxVerbosity = Just (toEnum n)
| otherwise = Nothing
where
-- This makes code robust enough to survive changes in Verbosity
-- definition.
minVerbosity = fromEnum (minBound :: Verbosity)
maxVerbosity = fromEnum (maxBound :: Verbosity)
-- | Generic 'Verbosity' parsing function.
--
-- Use <https://hackage.haskell.org/package/case-insensitive case-insensitive>
-- package to make this function case insensitive:
--
-- @
-- ghci> import Data.Verbosity as Verbosity
-- ghci> import qualified Data.CaseInsensitive as CI (mk)
-- ghci> Verbosity.parse (CI.mk "silent")
-- Just Silent
-- @
parse :: (Eq string, IsString string) => string -> Maybe Verbosity
parse = (`lookup` [(str v, v) | v <- [minBound..maxBound :: Verbosity]])
where
str = fromString . gDataConstructorName . from
class HasDataConstructors (f :: Type -> Type) where
gDataConstructorName :: f x -> String
instance HasDataConstructors f => HasDataConstructors (D1 c f) where
gDataConstructorName (M1 x) = gDataConstructorName x
instance
( HasDataConstructors x
, HasDataConstructors y
)
=> HasDataConstructors (x :+: y)
where
gDataConstructorName = \case
L1 l -> gDataConstructorName l
R1 r -> gDataConstructorName r
instance Constructor c => HasDataConstructors (C1 c f) where
gDataConstructorName = conName
| trskop/verbosity | src/Data/Verbosity.hs | bsd-3-clause | 7,206 | 0 | 10 | 1,361 | 1,186 | 740 | 446 | -1 | -1 |
-- dirichletseries.hs
module Math.DirichletSeries where
import Math.NumberTheoryFundamentals (divides)
import Math.MathsPrimitives ( ($+), ($-) )
import Math.QQ
import Math.ArithmeticFunctions
import Math.UPoly
-- Dirichlet series is sum a_n n^-s
data DirichletSeries a = DS [a]
precisionDS = 16 :: Int
coeffsDS (DS as) = as
DS as ~= DS bs = take precisionDS as == take precisionDS bs
instance Eq (DirichletSeries a) where
_ == _ = error "DirichletSeries.== : not defined, use ~= instead"
instance Show a => Show (DirichletSeries a) where
show (DS as) = "DS " ++ show (take precisionDS as)
-- NUM INSTANCE
instance Num a => Num (DirichletSeries a) where
DS as + DS bs = DS (as $+ bs)
negate (DS as) = DS (map negate as)
DS as * DS bs = DS (as $* bs)
fromInteger n = DS (fromInteger n : repeat 0)
-- as $+ bs = zipWith (+) as bs
addDS as bs = as $+ bs
as $* bs = as `multDS'` bs
-- Naive method - slower than the following, but safe
multDS as bs = map coeff [1..]
where coeff n = sum [(as !!! d) * (bs !!! (n `div` d)) | d <- [1..n], d `divides` n]
xs !!! i = xs !! (i-1) -- Dirichlet series are indexed from 1, not 0
-- More efficient - but grows heap as more coefficients required, eventually lead to failure
multDS' (a:as) bs = doMult (map (a*) bs) as 1
where doMult (c:cs) (a:as) i =
let cs' = cs `addDS` (map (a*) (i `zerosBetween` bs))
in c : doMult cs' as (i+1)
-- The Dirichlet series for [a1,a2,a3,...] * [b1,b2,b3,...] is
-- map (a1*) [b1,b2,b3,...] + map (a2*) [0,b1,0,b2,0,b3,...] + map (a3*) [0,0,b1,0,0,b2,0,0,b3,...] + ...
-- The idea of the code is to avoid an infinite sum by only adding the i'th summand at the point where we're calculating the i'th coefficient.
-- for example, when i == 1, c:cs = a1*b1 : [a1*b2, a1*b3,...], a:as = a2:[a3,a4,...]
-- so bs' = [b1,0,b2,0,...], cs' = [a1*b2, a1*b3, ...] $+ [a2*b1,0,a2*b2,0,...]
-- so when i == 2, c:cs = a1*b2+a2*b1 : [a1*b3, a1*b4+a2*b2, a1*b5, ...], a:as =a3:[a4,a5,...]
-- so bs' = [b1,0,0,b2,0,0,...], cs' = [a1*b3, a1*b4+a2*b2, a1*b5] $+ [a3*b1,0,0,a3*b2,0,0,...]
-- etc.
k `zerosBetween` (x:xs) = x : replicate k 0 ++ k `zerosBetween` xs
-- FRACTIONAL INSTANCE
instance Fractional a => Fractional (DirichletSeries a) where
recip (DS as) = DS (recipDS as)
-- Naive method
recipDS' (0:_) = error "recipDS: a1 == 0"
recipDS' as@(a:_) = (1/a) : doRecipDS 2 [1/a]
where doRecipDS n bs =
let bn = (-1/a) * sum [(as !!! d) * (bs !!! (n `div` d)) | d <- [2..n], d `divides` n]
in bn : doRecipDS (n+1) (bs ++ [bn])
-- Much faster method
recipDS (0:_) = error "recipDS: a1 == 0"
recipDS (a:as) = (1/a) : doRecip [1/a] (map ((1/a)*) as) 1
where doRecip bs (c:cs) n =
let b_n1 = -c/a
cs' = cs `addDS` (replicate n 0 ++ map (b_n1*) (n `zerosBetween` as))
in b_n1 : doRecip (bs ++ [b_n1]) cs' (n+1)
-- at step n, we have bs = [b_1..b_n], c:cs = c_n+1 : [c_n+2..], where [a1..] * [b1..bn] == [c1..]
-- we want c_n+1 == 0, so we set b_n+1 = - c_n+1 / a1
-- we must then set [c1'..] = [c1..] + b_n+1 (n+1)^-s * [a1..]
-- the thing we're adding in this case is b_n+1 a1 (n+1)^-s + b_n+1 a2 (2n+2)^-s + ... == replicate n 0 ++ map (b_n+1*) (stretch n [a1..])
-- however, in the tail recursion we only need to pass in the [c_n+2..] terms, so dropping the first n+1 terms of the above, we get the code above
-- LINEAR CHANGE OF VARIABLE
-- Given a Dirichlet series f(s) = sum a_n n^-s,
-- we support linear changes of variable, f(a*s+b), for a,b <- ZZ, a > 0
s = UP [0,1] :: UPoly Integer
-- composeDS (DS as) (UP [b,a]) | a > 0 = DS (translate b (dilate a as))
ofDS (DS as) (UP [b,a]) | a > 0 = DS (translate b (dilate a as))
-- given f(s) = sum a_n n^-s, return f(s+k) = sum a_n n^-k n^-s
translate 0 as = as
translate k as = zipWith (*) as (map (\n -> fromInteger n^^(-k)) [1..])
-- given f(s) = sum a_n n^-s, return f(k*s) == sum a_n n^-ks == sum a_n (n^k)^-s
dilate 1 as = as
dilate k as = doDilate as 1
where doDilate (a:as) i = a : replicate ((i+1)^k-i^k-1) 0 ++ doDilate as (i+1)
-- given f(s) = sum a_n n^-s, return f(2s) = sum a_n n^-2s
double as = doDouble as 2
where doDouble (a:as) i = a : replicate i 0 ++ doDouble as (i+2)
-- SOME INTERESTING DIRICHLET SERIES
-- from Hardy and Wright
-- Riemann zeta function
-- zeta(s) = 1/1^s + 1/2^s + 1/3^s +...
zetaDS :: DirichletSeries QQ
zetaDS = DS (repeat 1)
zeta f = zetaDS `ofDS` f
-- series for d n = length [d | d `divides` n]
d_DGF = (zeta s) ^2
-- series for sigma n = sum [d | d `divides` n]
sigmaDGF = zeta s * zeta (s-1)
-- series for sigma_k n = sum [d^k | d `divides` n]
sigma_kDGF k = zeta s * zeta (s-k)
mobiusDGF = 1 / zeta s
-- euler totient function, phi n = length [m | m <- [1..n], coprime m n]
eulerTotientDGF = zeta (s-1) / zeta s
-- dgf for q_2(n) == 0 if n has a square as a factor, 1 otherwise
squarefreeDGF = zeta s / zeta (2*s)
-- dgf for q_k(n) == 0 if n has a kth power as a factor, 1 otherwise
powerfreeDGF k = zeta s / zeta (k*s)
-- EULER PRODUCTS
-- given [(p,f)] for primes p, where f is Dirichlet Series of the form 1 + a_p p^-s + a_2p p^-2s + ...
-- return their product
fromPrimeProductDS pas = DS (1 : doPrimeProduct pas 2 1)
where
doPrimeProduct ((p, f):pas) p' series@(DS bs) =
drop (p'-1) (take (p-1) bs) ++ doPrimeProduct pas p (series*f)
doPrimeProduct [] p' (DS bs) = drop (p'-1) bs
-- given (p,a_p), return (1 - a_p p^-s)^-1 == 1 + a_p p^-s + a_p^2 p^-2s + ...
eulerTermDS' (p,a_p) = recip (DS (1:replicate (p-2) 0 ++ (-a_p):repeat 0))
-- This is much faster way to achieve the same result
eulerTermDS (p,a_p) = DS (doEulerTerm (1,1))
where doEulerTerm (q,a_q) = let q' = p*q in a_q : replicate (q'-q-1) 0 ++ doEulerTerm (q',a_p*a_q)
-- given [(p,a_p)] for primes p, return product (1 - a_p p^-s)^-1
fromEulerProductDS pas = fromPrimeProductDS [(p, eulerTermDS (p,a_p)) | (p,a_p) <- pas]
-- OTHER STUFF
deriv_zeta = map (negate . log . fromInteger) [1..]
-- n^-s = e^(-s log n)
-- so deriv n^-s = (- log n) e^(-s log n) = (- log n) n^-s
-- deriv as = zipWith (*) (map fromInteger as) deriv_zeta
-- lambda function: lambda (p^m) = log p, lambda n = 0 otherwise
-- lambda_dgf = map negate (deriv_zeta $* map fromInteger recip_zeta)
-- Hardy and Wright p 254ff has several others
| nfjinjing/bench-euler | src/Math/DirichletSeries.hs | bsd-3-clause | 6,524 | 2 | 18 | 1,590 | 1,900 | 1,012 | 888 | 70 | 2 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit (testCase)
import Tests.Syntax
import Tests.Syntax.JSON(methodParsingTests)
import Tests.Codegen
import Tests.Codegen.Util(utilTestGroup)
tests :: TestTree
tests = testGroup "Compiler tests"
[ testGroup "AST"
[ localOption (QuickCheckMaxSize 6) $
testProperty "roundtrip" roundtripAST
, testGroup "Compare .bond and .json"
[ testCase "attributes" $ compareAST "attributes"
, testCase "basic types" $ compareAST "basic_types"
, testCase "bond_meta types" $ compareAST "bond_meta"
, testCase "complex types" $ compareAST "complex_types"
, testCase "default values" $ compareAST "defaults"
, testCase "empty" $ compareAST "empty"
, testCase "field modifiers" $ compareAST "field_modifiers"
, testCase "generics" $ compareAST "generics"
, testCase "inheritance" $ compareAST "inheritance"
, testCase "type aliases" $ compareAST "aliases"
, testCase "documentation example" $ compareAST "example"
, testCase "simple service syntax" $ compareAST "service"
, testCase "service attributes" $ compareAST "service_attributes"
, testCase "generic service" $ compareAST "generic_service"
, testCase "streaming service" $ compareAST "streaming"
, testCase "documentation example" $ compareAST "example"
, testCase "service inheritance" $ compareAST "service_inheritance"
]
, methodParsingTests
]
, testGroup "SchemaDef"
[ verifySchemaDef "attributes" "Foo"
, verifySchemaDef "basic_types" "BasicTypes"
, verifySchemaDef "defaults" "Foo"
, verifySchemaDef "field_modifiers" "Foo"
, verifySchemaDef "inheritance" "Foo"
, verifySchemaDef "alias_key" "foo"
, verifySchemaDef "maybe_blob" "Foo"
, verifySchemaDef "nullable_alias" "foo"
, verifySchemaDef "schemadef" "AliasBase"
, verifySchemaDef "schemadef" "EnumDefault"
, verifySchemaDef "schemadef" "StringTree"
, verifySchemaDef "example" "SomeStruct"
]
, testGroup "Types"
[ testCase "type alias resolution" aliasResolution
]
, testGroup "Codegen Failures (Expect to see errors below check for OK or FAIL)"
[ testCase "Struct default value nothing" $ failBadSyntax "Should fail when default value of a struct field is 'nothing'" "struct_nothing"
, testCase "Enum no default value" $ failBadSyntax "Should fail when an enum field has no default value" "enum_no_default"
, testCase "Alias default value" $ failBadSyntax "Should fail when underlying default value is of the wrong type" "aliases_default"
, testCase "Out of range" $ failBadSyntax "Should fail, out of range for int16" "int_out_of_range"
, testCase "Duplicate method definition in service" $ failBadSyntax "Should fail, method name should be unique" "duplicate_service_method"
, testCase "Invalid service base: struct" $ failBadSyntax "Should fail, struct can't be used as service base" "service_invalid_base_struct"
, testCase "Invalid service base: type param" $ failBadSyntax "Should fail, type param can't be used as service base" "service_invalid_base_type_param"
]
, testGroup "Codegen"
[ utilTestGroup,
testGroup "C++"
[ verifyCppCodegen "attributes"
, verifyCppCodegen "basic_types"
, verifyCppCodegen "bond_meta"
, verifyCppCodegen "complex_types"
, verifyCppCodegen "defaults"
, verifyCppCodegen "empty"
, verifyCppCodegen "field_modifiers"
, verifyCppCodegen "generics"
, verifyCppCodegen "inheritance"
, verifyCppCodegen "aliases"
, verifyCppCodegen "alias_key"
, verifyCppCodegen "maybe_blob"
, verifyCppCodegen "metadata_edge_cases"
, verifyCodegen
[ "c++"
, "--enum-header"
]
"with_enum_header"
, verifyCodegen
[ "c++"
, "--import-dir=tests/schema/imports"
]
"import"
, verifyCodegen
[ "c++"
, "--allocator=arena"
]
"alias_with_allocator"
, verifyCodegen
[ "c++"
, "--allocator=arena"
, "--using=List=my::list<{0}, arena>"
, "--using=Vector=my::vector<{0}, arena>"
, "--using=Set=my::set<{0}, arena>"
, "--using=Map=my::map<{0}, {1}, arena>"
, "--using=String=my::string<arena>"
]
"custom_alias_with_allocator"
, verifyCodegen
[ "c++"
, "--allocator=arena"
, "--using=List=my::list<{0}>"
, "--using=Vector=my::vector<{0}>"
, "--using=Set=my::set<{0}>"
, "--using=Map=my::map<{0}, {1}>"
, "--using=String=my::string"
]
"custom_alias_without_allocator"
, testGroup "Apply"
[ verifyApplyCodegen
[ "c++"
, "--apply-attribute=DllExport"
]
"basic_types"
]
, testGroup "Exports"
[ verifyExportsCodegen
[ "c++"
, "--export-attribute=DllExport"
]
"service"
, verifyExportsCodegen
[ "c++"
, "--export-attribute=DllExport"
]
"with_enum_header"
]
, verifyCodegen
[ "c++"
, "--namespace=tests=nsmapped"
]
"basic_types_nsmapped"
, testGroup "Grpc"
[ verifyCppGrpcCodegen
[ "c++"
]
"service"
, verifyCppGrpcCodegen
[ "c++"
]
"generic_service"
, verifyCppGrpcCodegen
[ "c++"
]
"service_attributes"
]
]
, testGroup "C#"
[ verifyCsCodegen "attributes"
, verifyCsCodegen "basic_types"
, verifyCsCodegen "bond_meta"
, verifyCsCodegen "complex_types"
, verifyCsCodegen "defaults"
, verifyCsCodegen "empty"
, verifyCsCodegen "field_modifiers"
, verifyCsCodegen "generics"
, verifyCsCodegen "inheritance"
, verifyCsCodegen "aliases"
, verifyCsCodegen "complex_inheritance"
, verifyCodegenVariation
[ "c#"
, "--preview-constructor-parameters"
, "--readonly-properties"
]
"complex_inheritance"
"constructor-parameters"
, verifyCodegenVariation
[ "c#"
, "--preview-constructor-parameters"
, "--fields"
]
"complex_inheritance"
"constructor-parameters_fields"
, verifyCodegen
[ "c#"
, "--using=time=System.DateTime"
]
"nullable_alias"
, verifyCodegen
[ "c#"
, "--namespace=tests=nsmapped"
]
"basic_types_nsmapped"
, verifyCodegen
[ "c#"
, "--import-dir=tests/schema/imports"
]
"import"
, verifyCodegenVariation
[ "c#"
, "--preview-constructor-parameters"
, "--readonly-properties"
]
"empty_struct"
"constructor-parameters"
, testGroup "Grpc"
[ verifyCsGrpcCodegen
[ "c#"
]
"service"
, verifyCsGrpcCodegen
[ "c#"
]
"generic_service"
, verifyCsGrpcCodegen
[ "c#"
]
"service_attributes"
, verifyCsGrpcCodegen
[ "c#"
]
"streaming"
]
]
, testGroup "Java"
[ verifyJavaCodegen "attributes"
, verifyJavaCodegen "basic_types"
, verifyJavaCodegen "bond_meta"
, verifyJavaCodegen "complex_types"
, verifyJavaCodegen "defaults"
, verifyJavaCodegen "empty"
, verifyJavaCodegen "field_modifiers"
, verifyJavaCodegen "generics"
, verifyJavaCodegen "inheritance"
, verifyJavaCodegen "aliases"
, verifyCodegen
[ "java"
, "--namespace=tests=nsmapped"
]
"basic_types_nsmapped"
, verifyCodegen
[ "java"
, "--import-dir=tests/schema/imports"
]
"import"
]
]
]
main :: IO ()
main = defaultMain tests
| chwarr/bond | compiler/tests/TestMain.hs | mit | 9,804 | 0 | 13 | 3,965 | 1,216 | 631 | 585 | 204 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-|
Module : Finance.Blpapi.Impl.SessionImpl
Description : FFI for Session
Copyright : Bloomberg Finance L.P.
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : *nix, windows
-}
module Finance.Blpapi.Impl.SessionImpl where
import Control.Monad
import Finance.Blpapi.Impl.RequestImpl
import Finance.Blpapi.Impl.SessionOptionsImpl
import Finance.Blpapi.Request
import Foreign
import Foreign.C.String
import Finance.Blpapi.CorrelationId
import Finance.Blpapi.Event
import Finance.Blpapi.Impl.CorrelationIdImpl
import Finance.Blpapi.Impl.EventImpl
import Finance.Blpapi.Impl.IdentityImpl
import Finance.Blpapi.Impl.ServiceImpl
import Finance.Blpapi.Impl.SubscriptionListImpl
import Finance.Blpapi.Service
import Finance.Blpapi.Subscription
import Finance.Blpapi.Impl.ErrorImpl
newtype SessionImpl = SessionImpl (Ptr SessionImpl)
type SessionImplHandle = ForeignPtr SessionImpl
newtype EventQueueImpl = EventQueueImpl (Ptr EventQueueImpl)
foreign import ccall safe "blpapi_session.h blpapi_Session_create"
blpapi_Session_create :: Ptr SessionOptionsImpl
-> Ptr ()
-> Ptr ()
-> Ptr ()
-> IO (Ptr SessionImpl)
foreign import ccall safe "blpapi_session.h &blpapi_Session_destroy"
blpapi_Session_destroy :: FunPtr (Ptr SessionImpl -> IO ())
foreign import ccall safe "blpapi_session.h blpapi_Session_start"
blpapi_Session_start :: Ptr SessionImpl -> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_stop"
blpapi_Session_stop :: Ptr SessionImpl -> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_getService"
blpapi_Session_getService :: Ptr SessionImpl
-> Ptr (Ptr ServiceImpl)
-> CString
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_openService"
blpapi_Session_openService :: Ptr SessionImpl -> CString -> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_subscribe"
blpapi_Session_subscribe :: Ptr SessionImpl
-> Ptr SubscriptionListImpl
-> Ptr IdentityImpl
-> CString
-> Int
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_sendRequest"
blpapi_Session_sendRequest :: Ptr SessionImpl
-> Ptr RequestImpl
-> Ptr CorrelationIdImpl
-> Ptr IdentityImpl
-> Ptr EventQueueImpl
-> CString
-> Int
-> IO Int
foreign import ccall safe
"blpapi_session.h blpapi_Session_sendAuthorizationRequest"
blpapi_Session_sendAuthorizationRequest :: Ptr SessionImpl
-> Ptr RequestImpl
-> Ptr IdentityImpl
-> Ptr CorrelationIdImpl
-> Ptr EventQueueImpl
-> CString
-> Int
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_nextEvent"
blpapi_Session_nextEvent :: Ptr SessionImpl
-> Ptr (Ptr EventImpl)
-> Int
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_createIdentity"
blpapi_Session_createIdentity :: Ptr SessionImpl
-> IO (Ptr IdentityImpl)
foreign import ccall safe "blpapi_session.h blpapi_Session_generateToken"
blpapi_Session_generateToken :: Ptr SessionImpl
-> Ptr CorrelationIdImpl
-> Ptr EventQueueImpl
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_cancel"
blpapi_Session_cancel :: Ptr SessionImpl
-> Ptr CorrelationIdImpl -- Cid array
-> Int -- num cids
-> CString -- RequestLabel
-> Int -- RequestLabel size
-> IO Int
foreign import ccall safe "blpapi_session.h blpapi_Session_unsubscribe"
blpapi_Session_unsubscribe :: Ptr SessionImpl
-> Ptr SubscriptionListImpl
-> CString
-> Int
-> IO Int
createIdentityImpl :: ForeignPtr SessionImpl -> IO (ForeignPtr IdentityImpl)
createIdentityImpl session =
withForeignPtr session $ \s -> do
p <- blpapi_Session_createIdentity s
newForeignPtr blpapi_Identity_release p
subscribeImpl :: ForeignPtr SessionImpl
-> [Subscription]
-> Maybe (ForeignPtr IdentityImpl)
-> IO ()
subscribeImpl session subList idPtr =
withForeignPtr session $ \s -> do
subListImplF <- populateSubscriptionListImpl subList
withForeignPtr subListImplF $ \sl -> do
rc <- case idPtr of
Just idenPtr ->
withForeignPtr idenPtr $ \iden ->
blpapi_Session_subscribe s sl iden nullPtr 0
Nothing ->
blpapi_Session_subscribe s sl nullPtr nullPtr 0
failIfBadErrorCode rc
unsubscribeImpl :: ForeignPtr SessionImpl
-> [Subscription]
-> IO ()
unsubscribeImpl session subList =
withForeignPtr session $ \s -> do
subListImplF <- populateSubscriptionListImpl subList
withForeignPtr subListImplF $ \sl -> do
rc <- blpapi_Session_unsubscribe s sl nullPtr 0
failIfBadErrorCode rc
populateSubscriptionListImpl :: [Subscription]
-> IO (ForeignPtr SubscriptionListImpl)
populateSubscriptionListImpl xs = do
fsubsListImpl <- newSubscriptionListImpl
withForeignPtr fsubsListImpl (addSubscriptionToSubscriptionHandle xs)
return fsubsListImpl
getCidImpl :: Maybe CorrelationId -> CorrelationIdImplWrapped
getCidImpl (Just cid) = convertToCorrelationIdImpl cid
getCidImpl Nothing = createUnsetCorrelationIdImpl
withMaybeCid :: Maybe CorrelationId -> (Ptr CorrelationIdImpl -> IO a) -> IO a
withMaybeCid cid f =
alloca $ \cidPtr -> do
poke cidPtr (getCidImpl cid)
cidImpl <- newCorrelationIdImpl
withForeignPtr cidImpl $ \cidImplP -> do
blpapi_CorrelationId_convertFromWrapped cidPtr cidImplP
f cidImplP
addToSubscriptionList :: Ptr SubscriptionListImpl
-> TopicString
-> Maybe CorrelationId
-> IO Int
addToSubscriptionList lst (QualifiedTopicString s) cid =
alloca $ \cidPtr -> do
poke cidPtr (getCidImpl cid)
cidImpl <- newCorrelationIdImpl
withForeignPtr cidImpl $ \cidImplP -> do
blpapi_CorrelationId_convertFromWrapped cidPtr cidImplP
withCString s $ \cs ->
blpapi_SubscriptionList_add lst cs cidImplP nullPtr nullPtr 0 0
addToSubscriptionList lst ts cid =
addToSubscriptionList lst (convertToQualifiedString ts) cid
addSubscriptionToSubscriptionHandle :: [Subscription]
-> Ptr SubscriptionListImpl
-> IO Int
addSubscriptionToSubscriptionHandle xs p =
foldM (\_ s ->
addToSubscriptionList p
(subscriptonString s)
(subscriptionCorrelation s)) 0 xs
getNextEventImpl :: SessionImplHandle -> IO [Event]
getNextEventImpl h = withForeignPtr h getNextEventImpl'
getNextEventImpl' :: Ptr SessionImpl -> IO [Event]
getNextEventImpl' ptr =
alloca $
\p -> blpapi_Session_nextEvent ptr p 0 >> peek p >>= convertEventImpl
newSessionImpl :: Ptr SessionOptionsImpl -> IO (ForeignPtr SessionImpl)
newSessionImpl so = do
rawPtr <- blpapi_Session_create so nullPtr nullPtr nullPtr
newForeignPtr blpapi_Session_destroy rawPtr
stopImpl :: ForeignPtr SessionImpl -> IO Int
stopImpl session = withForeignPtr session $ \p -> blpapi_Session_stop p
openServiceImpl :: ForeignPtr SessionImpl
-> String
-> IO (Either String (Service, ForeignPtr ServiceImpl))
openServiceImpl session serName =
withCString serName $ \cs -> do
withForeignPtr session (`blpapi_Session_openService` cs)
getService session cs
getService :: ForeignPtr SessionImpl
-> CString
-> IO (Either String (Service, ForeignPtr ServiceImpl))
getService s serName = withForeignPtr s $ \p ->
alloca $ \rHandle -> do
rc <- blpapi_Session_getService p rHandle serName
if (rc /= 0)
then getErrorString rc >>= (return . Left)
else do
sImpl <- peek rHandle
blpapi_Service_addRef sImpl
ser <- convertServiceImpl sImpl
fsImpl <- newForeignPtr blpapi_Service_release sImpl
return $ Right (ser, fsImpl)
sendRequestImpl :: ForeignPtr SessionImpl
-> Request
-> Maybe CorrelationId
-> Maybe (ForeignPtr IdentityImpl)
-> IO ()
sendRequestImpl s req cid idPtr = do
rc <- withForeignPtr s $ \p ->
withForeignPtr (getImpl req) $ \r ->
withMaybeCid cid $ \cidPtr ->
case idPtr of
Just idenPtr ->
withForeignPtr idenPtr $ \iden ->
blpapi_Session_sendRequest p r cidPtr iden nullPtr nullPtr 0
Nothing ->
blpapi_Session_sendRequest p r cidPtr nullPtr nullPtr nullPtr 0
failIfBadErrorCode rc
sendAuthRequestImpl :: ForeignPtr SessionImpl
-> ForeignPtr IdentityImpl
-> Request
-> Maybe CorrelationId
-> IO ()
sendAuthRequestImpl s i req cid =
withForeignPtr s $ \p ->
withForeignPtr i $ \iden ->
withForeignPtr (getImpl req) $ \r ->
withMaybeCid cid $ \cidPtr -> do
rc <- blpapi_Session_sendAuthorizationRequest
p r iden cidPtr nullPtr nullPtr 0
failIfBadErrorCode rc
generateTokenImpl :: ForeignPtr SessionImpl -> Maybe CorrelationId -> IO ()
generateTokenImpl s cid =
withForeignPtr s $ \p ->
withMaybeCid cid $ \cidPtr -> do
rc <- blpapi_Session_generateToken p cidPtr nullPtr
failIfBadErrorCode rc
cancelSingleRequest :: ForeignPtr SessionImpl -> CorrelationId -> IO ()
cancelSingleRequest s cid =
withForeignPtr s $ \p ->
withMaybeCid (Just cid) $ \cidPtr -> do
rc <- blpapi_Session_cancel p cidPtr 1 nullPtr 0
failIfBadErrorCode rc
| bitemyapp/blpapi-hs | src/Finance/Blpapi/Impl/SessionImpl.hs | mit | 11,446 | 0 | 19 | 4,007 | 2,316 | 1,131 | 1,185 | 233 | 2 |
{-# LANGUAGE FlexibleInstances #-}
module Rede.SpdyProtocol.Framing.RstStream (
getRstStreamFrame
,rstStreamFrame
,getFrameResetReason
,RstStreamFrame(..)
,RstStreamValidFlags(..)
,FrameResetReason(..)
) where
import Rede.SpdyProtocol.Framing.Frame
import Data.BitSet.Generic(empty)
import Data.Binary (Binary, get, put, Get)
-- import Data.Binary.Builder (Builder)
import Data.Binary.Put (putWord32be)
import Data.Binary.Get (getWord32be)
import Data.Default
data RstStreamValidFlags = None_F
deriving (Show, Enum)
data RstStreamFrame =
RstStreamFrame {
prologue:: ControlFrame RstStreamValidFlags
, streamId:: Int
, statusCode:: FrameResetReason
}
deriving Show
instance HasStreamId RstStreamFrame where
streamIdFromFrame = streamId
instance Default (ControlFrame RstStreamValidFlags) where
def = ControlFrame RstStream_CFT (fbs1 None_F) 4
instance Binary RstStreamFrame where
put RstStreamFrame{prologue=pr, streamId=fi, statusCode=s} =
do
put pr
putWord32be $ fromIntegral fi
putWord32be $ fromIntegral $ fromEnum s
get =
do
pr <- get
w32 <- getWord32be
s <- getWord32be
return $ RstStreamFrame pr (fromIntegral w32) (toEnum $ fromIntegral s)
getFrameResetReason :: RstStreamFrame -> FrameResetReason
getFrameResetReason = statusCode
data FrameResetReason = Null_FRR
| ProtocolError_FRR
| InvalidStream_FRR
| RefusedStream_FRR
| UnsuportedVersion_FRR
| Cancel_FRR
| InternalError_FRR
| FlowControlError_FRR
| StreamInUse_FRR
| StreamAlreadyClosed_FRR
| Deprecated1_FRR
| FrameTooLarge_FRR
deriving (Show, Enum, Eq)
getRstStreamFrame :: Get RstStreamFrame
getRstStreamFrame = get
rstStreamFrame :: Int -> FrameResetReason -> RstStreamFrame
rstStreamFrame stream_id status_code =
RstStreamFrame
(ControlFrame RstStream_CFT empty 8)
stream_id status_code | alcidesv/ReH | hs-src/Rede/SpdyProtocol/Framing/RstStream.hs | bsd-3-clause | 1,934 | 20 | 12 | 365 | 467 | 262 | 205 | 60 | 1 |
module Music.Time.Split (
module Music.Time.Position,
-- * The Splittable class
Splittable(..),
-- * Miscellaneous
chunks,
) where
import Control.Lens hiding (Indexable, Level, above,
below, index, inside, parts,
reversed, transform, (<|), (|>))
import Data.AffineSpace
import Data.AffineSpace.Point
import Data.Functor.Adjunction (unzipR)
import Data.Functor.Rep
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Semigroup hiding ()
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.VectorSpace hiding (Sum (..))
import Music.Time.Internal.Util
import Music.Time.Position
-- |
-- Class of values that can be split.
--
-- Instances should satisfy:
--
-- @
-- ('beginning' t x)^.'duration' + ('ending' t x)^.'duration' = x^.'duration'
-- ('beginning' t x)^.'duration' = t `min` x^.'duration' iff t >= 0
-- ('ending' t x)^.'duration' = x^.'duration' - (t `min` x^.'duration') iff t >= 0
-- @
--
-- (Note that any of these three laws can be derived from the other two, so it is
-- sufficient to prove two!).
--
class HasDuration a => Splittable a where
-- | Split a value at the given duration and return both parts.
split :: Duration -> a -> (a, a)
split d x = (beginning d x, ending d x)
-- | Split a value at the given duration and return only the first part.
beginning :: Duration -> a -> a
-- | Split a value at the given duration and return only the second part.
ending :: Duration -> a -> a
beginning d = fst . split d
ending d = snd . split d
{-# MINIMAL (split) | (beginning, ending) #-}
instance Splittable () where
split _ x = (x, x)
instance Splittable Char where
split _ x = (x,x)
instance Splittable Int where
split _ x = (x,x)
instance Splittable Double where
split _ x = (x,x)
instance Splittable Duration where
-- Directly from the laws
-- Guard against t < 0
split t x = (t' `min` x, x ^-^ (t' `min` x))
where t' = t `max` 0
chunks :: (Transformable a, Splittable a) => Duration -> a -> [a]
chunks d xs = chunks' d xs
where
chunks' d (split d -> (x, xs)) = [x] ++ chunks d xs
| music-suite/music-score | src/Music/Time/Split.hs | bsd-3-clause | 2,463 | 0 | 10 | 781 | 552 | 329 | 223 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns
, CPP
, ExistentialQuantification
, NoImplicitPrelude
, RecordWildCards
, TypeSynonymInstances
, FlexibleInstances
#-}
-- |
-- The event manager supports event notification on fds. Each fd may
-- have multiple callbacks registered, each listening for a different
-- set of events. Registrations may be automatically deactivated after
-- the occurrence of an event ("one-shot mode") or active until
-- explicitly unregistered.
--
-- If an fd has only one-shot registrations then we use one-shot
-- polling if available. Otherwise we use multi-shot polling.
module GHC.Event.Manager
( -- * Types
EventManager
-- * Creation
, new
, newWith
, newDefaultBackend
-- * Running
, finished
, loop
, step
, shutdown
, release
, cleanup
, wakeManager
-- * State
, callbackTableVar
, emControl
-- * Registering interest in I/O events
, Lifetime (..)
, Event
, evtRead
, evtWrite
, IOCallback
, FdKey(keyFd)
, FdData
, registerFd
, unregisterFd_
, unregisterFd
, closeFd
, closeFd_
) where
------------------------------------------------------------------------
-- Imports
import Control.Concurrent.MVar (MVar, newMVar, putMVar,
tryPutMVar, takeMVar, withMVar)
import Control.Exception (onException)
import Data.Bits ((.&.))
import Data.Foldable (forM_)
import Data.Functor (void)
import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef,
writeIORef)
import Data.Maybe (maybe)
import Data.OldList (partition)
import GHC.Arr (Array, (!), listArray)
import GHC.Base
import GHC.Conc.Sync (yield)
import GHC.List (filter, replicate)
import GHC.Num (Num(..))
import GHC.Real (fromIntegral)
import GHC.Show (Show(..))
import GHC.Event.Control
import GHC.Event.IntTable (IntTable)
import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite,
Lifetime(..), EventLifetime, Timeout(..))
import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique)
import System.Posix.Types (Fd)
import qualified GHC.Event.IntTable as IT
import qualified GHC.Event.Internal as I
-- #if defined(HAVE_KQUEUE)
-- import qualified GHC.Event.KQueue as KQueue
-- #elif defined(HAVE_EPOLL)
-- import qualified GHC.Event.EPoll as EPoll
-- #elif defined(HAVE_POLL)
-- import qualified GHC.Event.Poll as Poll
-- #else
-- # error not implemented for this operating system
-- #endif
------------------------------------------------------------------------
-- Types
data FdData = FdData {
fdKey :: {-# UNPACK #-} !FdKey
, fdEvents :: {-# UNPACK #-} !EventLifetime
, _fdCallback :: !IOCallback
}
-- | A file descriptor registration cookie.
data FdKey = FdKey {
keyFd :: {-# UNPACK #-} !Fd
, keyUnique :: {-# UNPACK #-} !Unique
} deriving (Eq, Show)
-- | Callback invoked on I/O events.
type IOCallback = FdKey -> Event -> IO ()
data State = Created
| Running
| Dying
| Releasing
| Finished
deriving (Eq, Show)
-- | The event manager state.
data EventManager = EventManager
{ emBackend :: !Backend
, emFds :: {-# UNPACK #-} !(Array Int (MVar (IntTable [FdData])))
, emState :: {-# UNPACK #-} !(IORef State)
, emUniqueSource :: {-# UNPACK #-} !UniqueSource
, emControl :: {-# UNPACK #-} !Control
, emLock :: {-# UNPACK #-} !(MVar ())
}
-- must be power of 2
callbackArraySize :: Int
callbackArraySize = 32
hashFd :: Fd -> Int
hashFd fd = undefined {- fromIntegral fd TODO: channel -}
.&. (callbackArraySize - 1)
{-# INLINE hashFd #-}
callbackTableVar :: EventManager -> Fd -> MVar (IntTable [FdData])
callbackTableVar mgr fd = emFds mgr ! hashFd fd
{-# INLINE callbackTableVar #-}
haveOneShot :: Bool
{-# INLINE haveOneShot #-}
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
haveOneShot = False
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
haveOneShot = True
#else
haveOneShot = False
#endif
------------------------------------------------------------------------
-- Creation
handleControlEvent :: EventManager -> Fd -> Event -> IO ()
handleControlEvent mgr fd _evt = do
msg <- readControlMessage (emControl mgr) fd
case msg of
CMsgWakeup -> return ()
CMsgDie -> writeIORef (emState mgr) Finished
_ -> return ()
newDefaultBackend :: IO Backend
-- #if defined(HAVE_KQUEUE)
-- newDefaultBackend = KQueue.new
-- #elif defined(HAVE_EPOLL)
-- newDefaultBackend = EPoll.new
-- #elif defined(HAVE_POLL)
-- newDefaultBackend = Poll.new
-- #else
-- TODO: Implement IO Manager
newDefaultBackend = error "no back end for this platform"
-- #endif
-- | Create a new event manager.
new :: IO EventManager
new = newWith =<< newDefaultBackend
-- | Create a new 'EventManager' with the given polling backend.
newWith :: Backend -> IO EventManager
newWith be = do
iofds <- fmap (listArray (0, callbackArraySize-1)) $
replicateM callbackArraySize (newMVar =<< IT.new 8)
ctrl <- newControl False
state <- newIORef Created
us <- newSource
_ <- mkWeakIORef state $ do
st <- atomicModifyIORef' state $ \s -> (Finished, s)
when (st /= Finished) $ do
I.delete be
closeControl ctrl
lockVar <- newMVar ()
let mgr = EventManager { emBackend = be
, emFds = iofds
, emState = state
, emUniqueSource = us
, emControl = ctrl
, emLock = lockVar
}
registerControlFd mgr (controlReadFd ctrl) evtRead
registerControlFd mgr (wakeupReadFd ctrl) evtRead
return mgr
where
replicateM n x = sequence (replicate n x)
failOnInvalidFile :: String -> Fd -> IO Bool -> IO ()
failOnInvalidFile loc fd m = do
ok <- m
when (not ok) $
let msg = "Failed while attempting to modify registration of file " ++
show fd ++ " at location " ++ loc
in error msg
registerControlFd :: EventManager -> Fd -> Event -> IO ()
registerControlFd mgr fd evs =
failOnInvalidFile "registerControlFd" fd $
I.modifyFd (emBackend mgr) fd mempty evs
-- | Asynchronously shuts down the event manager, if running.
shutdown :: EventManager -> IO ()
shutdown mgr = do
state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s)
when (state == Running) $ sendDie (emControl mgr)
-- | Asynchronously tell the thread executing the event
-- manager loop to exit.
release :: EventManager -> IO ()
release EventManager{..} = do
state <- atomicModifyIORef' emState $ \s -> (Releasing, s)
when (state == Running) $ sendWakeup emControl
finished :: EventManager -> IO Bool
finished mgr = (== Finished) `liftM` readIORef (emState mgr)
cleanup :: EventManager -> IO ()
cleanup EventManager{..} = do
writeIORef emState Finished
void $ tryPutMVar emLock ()
I.delete emBackend
closeControl emControl
------------------------------------------------------------------------
-- Event loop
-- | Start handling events. This function loops until told to stop,
-- using 'shutdown'.
--
-- /Note/: This loop can only be run once per 'EventManager', as it
-- closes all of its control resources when it finishes.
loop :: EventManager -> IO ()
loop mgr@EventManager{..} = do
void $ takeMVar emLock
state <- atomicModifyIORef' emState $ \s -> case s of
Created -> (Running, s)
Releasing -> (Running, s)
_ -> (s, s)
case state of
Created -> go `onException` cleanup mgr
Releasing -> go `onException` cleanup mgr
Dying -> cleanup mgr
-- While a poll loop is never forked when the event manager is in the
-- 'Finished' state, its state could read 'Finished' once the new thread
-- actually runs. This is not an error, just an unfortunate race condition
-- in Thread.restartPollLoop. See #8235
Finished -> return ()
_ -> do cleanup mgr
error $ "GHC.Event.Manager.loop: state is already " ++
show state
where
go = do state <- step mgr
case state of
Running -> yield >> go
Releasing -> putMVar emLock ()
_ -> cleanup mgr
-- | To make a step, we first do a non-blocking poll, in case
-- there are already events ready to handle. This improves performance
-- because we can make an unsafe foreign C call, thereby avoiding
-- forcing the current Task to release the Capability and forcing a context switch.
-- If the poll fails to find events, we yield, putting the poll loop thread at
-- end of the Haskell run queue. When it comes back around, we do one more
-- non-blocking poll, in case we get lucky and have ready events.
-- If that also returns no events, then we do a blocking poll.
step :: EventManager -> IO State
step mgr@EventManager{..} = do
waitForIO
state <- readIORef emState
state `seq` return state
where
waitForIO = do
n1 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n1 <= 0) $ do
yield
n2 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n2 <= 0) $ do
_ <- I.poll emBackend (Just Forever) (onFdEvent mgr)
return ()
------------------------------------------------------------------------
-- Registering interest in I/O events
-- | Register interest in the given events, without waking the event
-- manager thread. The 'Bool' return value indicates whether the
-- event manager ought to be woken.
registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> Lifetime
-> IO (FdKey, Bool)
registerFd_ mgr@(EventManager{..}) cb fd evs lt = do
u <- newUnique emUniqueSource
let fd' = undefined -- fromIntegral fd TODO: channel
reg = FdKey fd u
el = I.eventLifetime evs lt
!fdd = FdData reg el cb
(modify,ok) <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
oldFdd <- IT.insertWith (++) fd' [fdd] tbl
let prevEvs :: EventLifetime
prevEvs = maybe mempty eventsOf oldFdd
el' :: EventLifetime
el' = prevEvs `mappend` el
case I.elLifetime el' of
-- All registrations want one-shot semantics and this is supported
OneShot | haveOneShot -> do
ok <- I.modifyFdOnce emBackend fd (I.elEvent el')
if ok
then return (False, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- We don't want or don't support one-shot semantics
_ -> do
let modify = prevEvs /= el'
ok <- if modify
then let newEvs = I.elEvent el'
oldEvs = I.elEvent prevEvs
in I.modifyFd emBackend fd oldEvs newEvs
else return True
if ok
then return (modify, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- this simulates behavior of old IO manager:
-- i.e. just call the callback if the registration fails.
when (not ok) (cb reg evs)
return (reg,modify)
{-# INLINE registerFd_ #-}
-- | @registerFd mgr cb fd evs lt@ registers interest in the events @evs@
-- on the file descriptor @fd@ for lifetime @lt@. @cb@ is called for
-- each event that occurs. Returns a cookie that can be handed to
-- 'unregisterFd'.
registerFd :: EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey
registerFd mgr cb fd evs lt = do
(r, wake) <- registerFd_ mgr cb fd evs lt
when wake $ wakeManager mgr
return r
{-# INLINE registerFd #-}
{-
Building GHC with parallel IO manager on Mac freezes when
compiling the dph libraries in the phase 2. As workaround, we
don't use oneshot and we wake up an IO manager on Mac every time
when we register an event.
For more information, please read:
http://ghc.haskell.org/trac/ghc/ticket/7651
-}
-- | Wake up the event manager.
wakeManager :: EventManager -> IO ()
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
wakeManager mgr = sendWakeup (emControl mgr)
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
wakeManager _ = return ()
#else
wakeManager mgr = sendWakeup (emControl mgr)
#endif
eventsOf :: [FdData] -> EventLifetime
eventsOf [fdd] = fdEvents fdd
eventsOf fdds = mconcat $ map fdEvents fdds
-- | Drop a previous file descriptor registration, without waking the
-- event manager thread. The return value indicates whether the event
-- manager ought to be woken.
unregisterFd_ :: EventManager -> FdKey -> IO Bool
unregisterFd_ mgr@(EventManager{..}) (FdKey fd u) =
withMVar (callbackTableVar mgr fd) $ \tbl -> do
let dropReg = nullToNothing . filter ((/= u) . keyUnique . fdKey)
fd' = undefined -- fromIntegral fd TODO: channel
pairEvents :: [FdData] -> IO (EventLifetime, EventLifetime)
pairEvents prev = do
r <- maybe mempty eventsOf `fmap` IT.lookup fd' tbl
return (eventsOf prev, r)
(oldEls, newEls) <- IT.updateWith dropReg fd' tbl >>=
maybe (return (mempty, mempty)) pairEvents
let modify = oldEls /= newEls
when modify $ failOnInvalidFile "unregisterFd_" fd $
case I.elLifetime newEls of
OneShot | I.elEvent newEls /= mempty, haveOneShot ->
I.modifyFdOnce emBackend fd (I.elEvent newEls)
_ ->
I.modifyFd emBackend fd (I.elEvent oldEls) (I.elEvent newEls)
return modify
-- | Drop a previous file descriptor registration.
unregisterFd :: EventManager -> FdKey -> IO ()
unregisterFd mgr reg = do
wake <- unregisterFd_ mgr reg
when wake $ wakeManager mgr
-- | Close a file descriptor in a race-safe way.
closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO ()
closeFd mgr close fd = do
fds <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
-- prev <- IT.delete (fromIntegral fd) tbl -- TODO: Channel
prev <- IT.delete undefined tbl
case prev of
Nothing -> close fd >> return []
Just fds -> do
let oldEls = eventsOf fds
when (I.elEvent oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
close fd
return fds
forM_ fds $ \(FdData reg el cb) -> cb reg (I.elEvent el `mappend` evtClose)
-- | Close a file descriptor in a race-safe way.
-- It assumes the caller will update the callback tables and that the caller
-- holds the callback table lock for the fd. It must hold this lock because
-- this command executes a backend command on the fd.
closeFd_ :: EventManager
-> IntTable [FdData]
-> Fd
-> IO (IO ())
closeFd_ mgr tbl fd = do
-- prev <- IT.delete (fromIntegral fd) tbl TODO: channel
prev <- IT.delete undefined tbl
case prev of
Nothing -> return (return ())
Just fds -> do
let oldEls = eventsOf fds
when (oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
return $
forM_ fds $ \(FdData reg el cb) ->
cb reg (I.elEvent el `mappend` evtClose)
------------------------------------------------------------------------
-- Utilities
-- | Call the callbacks corresponding to the given file descriptor.
onFdEvent :: EventManager -> Fd -> Event -> IO ()
onFdEvent mgr fd evs
| fd == controlReadFd (emControl mgr) || fd == wakeupReadFd (emControl mgr) =
handleControlEvent mgr fd evs
| otherwise = do
fdds <- withMVar (callbackTableVar mgr fd) $ \tbl ->
-- IT.delete (fromIntegral fd) tbl >>= maybe (return []) (selectCallbacks tbl) TODO: Channel
IT.delete undefined tbl >>= maybe (return []) (selectCallbacks tbl)
forM_ fdds $ \(FdData reg _ cb) -> cb reg evs
where
-- | Here we look through the list of registrations for the fd of interest
-- and sort out which match the events that were triggered. We,
--
-- 1. re-arm the fd as appropriate
-- 2. reinsert registrations that weren't triggered and multishot
-- registrations
-- 3. return a list containing the callbacks that should be invoked.
selectCallbacks :: IntTable [FdData] -> [FdData] -> IO [FdData]
selectCallbacks tbl fdds = do
let -- figure out which registrations have been triggered
matches :: FdData -> Bool
matches fd' = evs `I.eventIs` I.elEvent (fdEvents fd')
(triggered, notTriggered) = partition matches fdds
-- sort out which registrations we need to retain
isMultishot :: FdData -> Bool
isMultishot fd' = I.elLifetime (fdEvents fd') == MultiShot
saved = notTriggered ++ filter isMultishot triggered
savedEls = eventsOf saved
allEls = eventsOf fdds
-- Reinsert multishot registrations.
-- We deleted the table entry for this fd above so we there isn't a preexisting entry
-- _ <- IT.insertWith (\_ _ -> saved) (fromIntegral fd) saved tbl TODO: channel
_ <- IT.insertWith (\_ _ -> saved) undefined saved tbl
case I.elLifetime allEls of
-- we previously armed the fd for multiple shots, no need to rearm
MultiShot | allEls == savedEls ->
return ()
-- either we previously registered for one shot or the
-- events of interest have changed, we must re-arm
_ ->
case I.elLifetime savedEls of
OneShot | haveOneShot ->
-- if there are no saved events and we registered with one-shot
-- semantics then there is no need to re-arm
unless (OneShot == I.elLifetime allEls
&& mempty == I.elEvent savedEls) $ do
void $ I.modifyFdOnce (emBackend mgr) fd (I.elEvent savedEls)
_ ->
-- we need to re-arm with multi-shot semantics
void $ I.modifyFd (emBackend mgr) fd
(I.elEvent allEls) (I.elEvent savedEls)
return triggered
nullToNothing :: [a] -> Maybe [a]
nullToNothing [] = Nothing
nullToNothing xs@(_:_) = Just xs
unless :: Monad m => Bool -> m () -> m ()
unless p = when (not p)
| pparkkin/eta | libraries/base/GHC/Event/Manager.hs | bsd-3-clause | 18,343 | 0 | 24 | 4,803 | 4,149 | 2,158 | 1,991 | 330 | 9 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (forever)
import qualified Network.WebSockets as WS
echo :: WS.Connection -> IO ()
echo conn = forever $ do
msg <- WS.receiveDataMessage conn
WS.sendDataMessage conn msg
main :: IO ()
main = WS.runServer "0.0.0.0" 9160 $ \pending -> do
conn <- WS.acceptRequest pending
echo conn
| nsluss/websockets | benchmarks/echo.hs | bsd-3-clause | 368 | 0 | 11 | 83 | 119 | 59 | 60 | 11 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1996-1998
This module contains "tidying" code for *nested* expressions, bindings, rules.
The code for *top-level* bindings is in TidyPgm.
-}
{-# LANGUAGE CPP #-}
module CoreTidy (
tidyExpr, tidyVarOcc, tidyRule, tidyRules, tidyUnfolding
) where
#include "HsVersions.h"
import CoreSyn
import CoreArity
import Id
import IdInfo
import Type( tidyType, tidyTyCoVarBndr )
import Coercion( tidyCo )
import Var
import VarEnv
import UniqFM
import Name hiding (tidyNameOcc)
import SrcLoc
import Maybes
import Data.List
{-
************************************************************************
* *
\subsection{Tidying expressions, rules}
* *
************************************************************************
-}
tidyBind :: TidyEnv
-> CoreBind
-> (TidyEnv, CoreBind)
tidyBind env (NonRec bndr rhs)
= tidyLetBndr env env (bndr,rhs) =: \ (env', bndr') ->
(env', NonRec bndr' (tidyExpr env' rhs))
tidyBind env (Rec prs)
= let
(env', bndrs') = mapAccumL (tidyLetBndr env') env prs
in
map (tidyExpr env') (map snd prs) =: \ rhss' ->
(env', Rec (zip bndrs' rhss'))
------------ Expressions --------------
tidyExpr :: TidyEnv -> CoreExpr -> CoreExpr
tidyExpr env (Var v) = Var (tidyVarOcc env v)
tidyExpr env (Type ty) = Type (tidyType env ty)
tidyExpr env (Coercion co) = Coercion (tidyCo env co)
tidyExpr _ (Lit lit) = Lit lit
tidyExpr env (App f a) = App (tidyExpr env f) (tidyExpr env a)
tidyExpr env (Tick t e) = Tick (tidyTickish env t) (tidyExpr env e)
tidyExpr env (Cast e co) = Cast (tidyExpr env e) (tidyCo env co)
tidyExpr env (Let b e)
= tidyBind env b =: \ (env', b') ->
Let b' (tidyExpr env' e)
tidyExpr env (Case e b ty alts)
= tidyBndr env b =: \ (env', b) ->
Case (tidyExpr env e) b (tidyType env ty)
(map (tidyAlt b env') alts)
tidyExpr env (Lam b e)
= tidyBndr env b =: \ (env', b) ->
Lam b (tidyExpr env' e)
------------ Case alternatives --------------
tidyAlt :: CoreBndr -> TidyEnv -> CoreAlt -> CoreAlt
tidyAlt _case_bndr env (con, vs, rhs)
= tidyBndrs env vs =: \ (env', vs) ->
(con, vs, tidyExpr env' rhs)
------------ Tickish --------------
tidyTickish :: TidyEnv -> Tickish Id -> Tickish Id
tidyTickish env (Breakpoint ix ids) = Breakpoint ix (map (tidyVarOcc env) ids)
tidyTickish _ other_tickish = other_tickish
------------ Rules --------------
tidyRules :: TidyEnv -> [CoreRule] -> [CoreRule]
tidyRules _ [] = []
tidyRules env (rule : rules)
= tidyRule env rule =: \ rule ->
tidyRules env rules =: \ rules ->
(rule : rules)
tidyRule :: TidyEnv -> CoreRule -> CoreRule
tidyRule _ rule@(BuiltinRule {}) = rule
tidyRule env rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs,
ru_fn = fn, ru_rough = mb_ns })
= tidyBndrs env bndrs =: \ (env', bndrs) ->
map (tidyExpr env') args =: \ args ->
rule { ru_bndrs = bndrs, ru_args = args,
ru_rhs = tidyExpr env' rhs,
ru_fn = tidyNameOcc env fn,
ru_rough = map (fmap (tidyNameOcc env')) mb_ns }
{-
************************************************************************
* *
\subsection{Tidying non-top-level binders}
* *
************************************************************************
-}
tidyNameOcc :: TidyEnv -> Name -> Name
-- In rules and instances, we have Names, and we must tidy them too
-- Fortunately, we can lookup in the VarEnv with a name
tidyNameOcc (_, var_env) n = case lookupUFM var_env n of
Nothing -> n
Just v -> idName v
tidyVarOcc :: TidyEnv -> Var -> Var
tidyVarOcc (_, var_env) v = lookupVarEnv var_env v `orElse` v
-- tidyBndr is used for lambda and case binders
tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
tidyBndr env var
| isTyCoVar var = tidyTyCoVarBndr env var
| otherwise = tidyIdBndr env var
tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
tidyBndrs env vars = mapAccumL tidyBndr env vars
-- Non-top-level variables, not covars
tidyIdBndr :: TidyEnv -> Id -> (TidyEnv, Id)
tidyIdBndr env@(tidy_env, var_env) id
= -- Do this pattern match strictly, otherwise we end up holding on to
-- stuff in the OccName.
case tidyOccName tidy_env (getOccName id) of { (tidy_env', occ') ->
let
-- Give the Id a fresh print-name, *and* rename its type
-- The SrcLoc isn't important now,
-- though we could extract it from the Id
--
ty' = tidyType env (idType id)
name' = mkInternalName (idUnique id) occ' noSrcSpan
id' = mkLocalIdWithInfo name' ty' new_info
var_env' = extendVarEnv var_env id id'
-- Note [Tidy IdInfo]
new_info = vanillaIdInfo `setOccInfo` occInfo old_info
`setUnfoldingInfo` new_unf
-- see Note [Preserve OneShotInfo]
`setOneShotInfo` oneShotInfo old_info
old_info = idInfo id
old_unf = unfoldingInfo old_info
new_unf | isEvaldUnfolding old_unf = evaldUnfolding
| otherwise = noUnfolding
-- See Note [Preserve evaluatedness]
in
((tidy_env', var_env'), id')
}
tidyLetBndr :: TidyEnv -- Knot-tied version for unfoldings
-> TidyEnv -- The one to extend
-> (Id, CoreExpr) -> (TidyEnv, Var)
-- Used for local (non-top-level) let(rec)s
-- Just like tidyIdBndr above, but with more IdInfo
tidyLetBndr rec_tidy_env env@(tidy_env, var_env) (id,rhs)
= case tidyOccName tidy_env (getOccName id) of { (tidy_env', occ') ->
let
ty' = tidyType env (idType id)
name' = mkInternalName (idUnique id) occ' noSrcSpan
details = idDetails id
id' = mkLocalVar details name' ty' new_info
var_env' = extendVarEnv var_env id id'
-- Note [Tidy IdInfo]
-- We need to keep around any interesting strictness and
-- demand info because later on we may need to use it when
-- converting to A-normal form.
-- eg.
-- f (g x), where f is strict in its argument, will be converted
-- into case (g x) of z -> f z by CorePrep, but only if f still
-- has its strictness info.
--
-- Similarly for the demand info - on a let binder, this tells
-- CorePrep to turn the let into a case.
--
-- Similarly arity info for eta expansion in CorePrep
--
-- Set inline-prag info so that we preseve it across
-- separate compilation boundaries
old_info = idInfo id
new_info = vanillaIdInfo
`setOccInfo` occInfo old_info
`setArityInfo` exprArity rhs
`setStrictnessInfo` strictnessInfo old_info
`setDemandInfo` demandInfo old_info
`setInlinePragInfo` inlinePragInfo old_info
`setUnfoldingInfo` new_unf
new_unf | isStableUnfolding old_unf = tidyUnfolding rec_tidy_env old_unf old_unf
| otherwise = noUnfolding
old_unf = unfoldingInfo old_info
in
((tidy_env', var_env'), id') }
------------ Unfolding --------------
tidyUnfolding :: TidyEnv -> Unfolding -> Unfolding -> Unfolding
tidyUnfolding tidy_env df@(DFunUnfolding { df_bndrs = bndrs, df_args = args }) _
= df { df_bndrs = bndrs', df_args = map (tidyExpr tidy_env') args }
where
(tidy_env', bndrs') = tidyBndrs tidy_env bndrs
tidyUnfolding tidy_env
unf@(CoreUnfolding { uf_tmpl = unf_rhs, uf_src = src })
unf_from_rhs
| isStableSource src
= unf { uf_tmpl = tidyExpr tidy_env unf_rhs } -- Preserves OccInfo
| otherwise
= unf_from_rhs
tidyUnfolding _ unf _ = unf -- NoUnfolding or OtherCon
{-
Note [Tidy IdInfo]
~~~~~~~~~~~~~~~~~~
All nested Ids now have the same IdInfo, namely vanillaIdInfo, which
should save some space; except that we preserve occurrence info for
two reasons:
(a) To make printing tidy core nicer
(b) Because we tidy RULES and InlineRules, which may then propagate
via --make into the compilation of the next module, and we want
the benefit of that occurrence analysis when we use the rule or
or inline the function. In particular, it's vital not to lose
loop-breaker info, else we get an infinite inlining loop
Note that tidyLetBndr puts more IdInfo back.
Note [Preserve evaluatedness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Bool
....(case v of MkT y ->
let z# = case y of
True -> 1#
False -> 2#
in ...)
The z# binding is ok because the RHS is ok-for-speculation,
but Lint will complain unless it can *see* that. So we
preserve the evaluated-ness on 'y' in tidyBndr.
(Another alternative would be to tidy unboxed lets into cases,
but that seems more indirect and surprising.)
Note [Preserve OneShotInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We keep the OneShotInfo because we want it to propagate into the interface.
Not all OneShotInfo is determined by a compiler analysis; some is added by a
call of GHC.Exts.oneShot, which is then discarded before the end of the
optimisation pipeline, leaving only the OneShotInfo on the lambda. Hence we
must preserve this info in inlinings. See Note [The oneShot function] in MkId.
This applies to lambda binders only, hence it is stored in IfaceLamBndr.
-}
(=:) :: a -> (a -> b) -> b
m =: k = m `seq` k m
| mcschroeder/ghc | compiler/coreSyn/CoreTidy.hs | bsd-3-clause | 9,989 | 0 | 18 | 2,879 | 2,013 | 1,088 | 925 | 134 | 2 |
{-# LANGUAGE TemplateHaskell, GADTs #-}
module T15815B where
import T15815A
mkFoo [t| Int -> Int |]
| sdiehl/ghc | testsuite/tests/th/T15815B.hs | bsd-3-clause | 102 | 0 | 5 | 18 | 18 | 12 | 6 | 4 | 0 |
{-# LANGUAGE PolyKinds, RankNTypes #-}
module T11142 where
import Data.Kind
data SameKind :: k -> k -> *
foo :: forall b. (forall k (a :: k). SameKind a b) -> ()
foo = undefined
| sdiehl/ghc | testsuite/tests/polykinds/T11142.hs | bsd-3-clause | 182 | 0 | 10 | 39 | 65 | 39 | 26 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- | This module is not used by GHC itself. Rather, it exports all of
-- the functions and types you are likely to need when writing a
-- plugin for GHC. So authors of plugins can probably get away simply
-- with saying "import GhcPlugins".
--
-- Particularly interesting modules for plugin writers include
-- "CoreSyn" and "CoreMonad".
module GhcPlugins(
module Plugins,
module RdrName, module OccName, module Name, module Var, module Id, module IdInfo,
module CoreMonad, module CoreSyn, module Literal, module DataCon,
module CoreUtils, module MkCore, module CoreFVs, module CoreSubst,
module Rules, module Annotations,
module DynFlags, module Packages,
module Module, module Type, module TyCon, module Coercion,
module TysWiredIn, module HscTypes, module BasicTypes,
module VarSet, module VarEnv, module NameSet, module NameEnv,
module UniqSet, module UniqFM, module FiniteMap,
module Util, module GHC.Serialized, module SrcLoc, module Outputable,
module UniqSupply, module Unique, module FastString
) where
-- Plugin stuff itself
import Plugins
-- Variable naming
import RdrName
import OccName hiding ( varName {- conflicts with Var.varName -} )
import Name hiding ( varName {- reexport from OccName, conflicts with Var.varName -} )
import Var
import Id hiding ( lazySetIdInfo, setIdExported, setIdNotExported {- all three conflict with Var -} )
import IdInfo
-- Core
import CoreMonad
import CoreSyn
import Literal
import DataCon
import CoreUtils
import MkCore
import CoreFVs
import CoreSubst
-- Core "extras"
import Rules
import Annotations
-- Pipeline-related stuff
import DynFlags
import Packages
-- Important GHC types
import Module
import Type hiding {- conflict with CoreSubst -}
( substTy, extendTvSubst, extendTvSubstList, isInScope )
import Coercion hiding {- conflict with CoreSubst -}
( substCo )
import TyCon
import TysWiredIn
import HscTypes
import BasicTypes hiding ( Version {- conflicts with Packages.Version -} )
-- Collections and maps
import VarSet
import VarEnv
import NameSet
import NameEnv
import UniqSet
import UniqFM
-- Conflicts with UniqFM:
--import LazyUniqFM
import FiniteMap
-- Common utilities
import Util
import GHC.Serialized
import SrcLoc
import Outputable
import UniqSupply
import Unique ( Unique, Uniquable(..) )
import FastString
| tjakway/ghcjvm | compiler/main/GhcPlugins.hs | bsd-3-clause | 2,488 | 0 | 6 | 497 | 377 | 272 | 105 | 56 | 0 |
{-# language RecordWildCards #-}
{-# language OverloadedStrings #-}
-- | Atom and RSS feeds
module Web.Hablog.Feed where
import Web.Hablog.Config
import Web.Hablog.Post
import qualified Data.Set as S
import qualified Text.Blaze.Html.Renderer.Text as HR
import Data.Time
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Network.URI.Encode (encodeText)
import Text.Feed.Types
import qualified Text.RSS.Syntax as RSS
import qualified Text.Atom.Feed as Atom
import qualified Text.Feed.Export as Export (textFeed)
-- * RSS feed
renderRSSFeed :: RSS.RSS -> TL.Text
renderRSSFeed = fromJust . Export.textFeed . RSSFeed
rssFeed :: Config -> [Post] -> RSS.RSS
rssFeed cfg posts =
let
domain = blogDomain cfg
in
RSS.RSS
{ RSS.rssVersion = "2.0"
, RSS.rssChannel =
(RSS.nullChannel (TL.toStrict $ blogTitle cfg) (TL.toStrict domain))
{ RSS.rssItems =
map (rssItem cfg) posts
, RSS.rssCategories =
uniques (tagToCatRSS domain) postTags posts
, RSS.rssLastUpdate =
Just $ lastUpdated posts
, RSS.rssImage =
Just $ RSS.nullImage
(TL.toStrict $ domain <> "/favicon.ico")
(TL.toStrict $ blogTitle cfg)
(TL.toStrict domain)
}
, RSS.rssAttrs = []
, RSS.rssOther = []
}
rssItem :: Config -> Post -> RSS.RSSItem
rssItem Config{..} post@Post{..} =
(RSS.nullItem $ TL.toStrict postTitle)
{ RSS.rssItemLink =
Just $ TL.toStrict (blogDomain <> "/" <> getPath post)
, RSS.rssItemDescription =
-- TL.toStrict <$> previewSummary postPreview
Just $ TL.toStrict $ HR.renderHtml postContent
, RSS.rssItemCategories =
tagToCatRSS blogDomain <$> postTags
, RSS.rssItemPubDate =
Just $ showDayRfc822 postDate
-- , RSS.rssItemContent =
-- Just $ TL.toStrict $ HR.renderHtml postContent
}
tagToCatRSS :: TL.Text -> TL.Text -> RSS.RSSCategory
tagToCatRSS domain tag =
RSS.RSSCategory
{ RSS.rssCategoryValue = TL.toStrict tag
, RSS.rssCategoryDomain = Just $ TL.toStrict domain <> "/tags/" <> encodeText (TL.toStrict tag)
, RSS.rssCategoryAttrs = []
}
-- * Atom feed
renderAtomFeed :: Atom.Feed -> TL.Text
renderAtomFeed = fromJust . Export.textFeed . AtomFeed
atomFeed :: Config -> [Post] -> Atom.Feed
atomFeed cfg posts =
let
domain = blogDomain cfg
initFeed =
Atom.nullFeed
(TL.toStrict $ domain <> "/blog/atom.xml")
(Atom.TextString . TL.toStrict . blogTitle $ cfg)
(lastUpdated posts)
in
initFeed
{ Atom.feedEntries =
map (toAtomEntry domain) posts
, Atom.feedAuthors =
uniques (toPerson domain) postAuthors posts
, Atom.feedCategories =
uniques (tagToCat domain) postTags posts
, Atom.feedIcon =
Just . TL.toStrict $ domain <> "/favicon.ico"
, Atom.feedLogo =
Just . TL.toStrict $ domain <> "/favicon.ico"
}
toAtomEntry :: Text -> Post -> Atom.Entry
toAtomEntry domain post@Post{..} =
Atom.Entry
{ Atom.entryId = TL.toStrict (domain <> "/" <> getPath post)
, Atom.entryTitle = Atom.TextString $ TL.toStrict postTitle
, Atom.entryUpdated = showDayRfc822 postDate
, Atom.entryAuthors =
map (toPerson domain) postAuthors
, Atom.entryCategories =
map (tagToCat domain) postTags
, Atom.entryContent =
Just $ Atom.HTMLContent $ TL.toStrict $ HR.renderHtml postContent
, Atom.entryContributor = []
, Atom.entryLinks =
[ Atom.nullLink (TL.toStrict $ domain <> "/" <> getPath post)
]
, Atom.entryPublished = Just $ T.pack $ show postDate
, Atom.entryRights = Nothing
, Atom.entrySource = Nothing
, Atom.entrySummary =
Atom.TextString . TL.toStrict <$> previewSummary postPreview
, Atom.entryInReplyTo = Nothing
, Atom.entryInReplyTotal = Nothing
, Atom.entryAttrs = []
, Atom.entryOther = []
}
toPerson :: TL.Text -> TL.Text -> Atom.Person
toPerson domain name =
Atom.nullPerson
{ Atom.personName = TL.toStrict name
, Atom.personURI = Just $ TL.toStrict domain
, Atom.personEmail = Nothing
}
tagToCat :: TL.Text -> TL.Text -> Atom.Category
tagToCat domain tag =
(Atom.newCategory $ TL.toStrict tag)
{ Atom.catLabel = Just $ TL.toStrict tag
, Atom.catScheme = Just $ TL.toStrict domain <> "/tags/" <> encodeText (TL.toStrict tag)
}
-- * Utils
uniques :: Ord b => (b -> c) -> (a -> [b]) -> [a] -> [c]
uniques convert extract =
( map convert
. S.toList
. S.unions
. map
( S.fromList
. extract
)
)
lastUpdated :: [Post] -> T.Text
lastUpdated = T.pack . show . maximum . map postModificationTime
showDayRfc822 :: Day -> T.Text
showDayRfc822 d =
T.pack $ formatTime defaultTimeLocale rfc822DateFormat $ (UTCTime d (secondsToDiffTime 0))
| soupi/hablog | src/Web/Hablog/Feed.hs | mit | 4,922 | 0 | 16 | 1,191 | 1,488 | 812 | 676 | 126 | 1 |
module Y2018.M04.D05.Exercise where
{--
We're basically rewriting Store.SQL.Connection. Good module, if you only have
one database to manage, but now I have multiple SQL databases, so I have to
make all these functions confirgurable.
--}
import Control.Monad ((>=>))
import Database.PostgreSQL.Simple
import System.Environment
-- these functions get your database's information from the environment
dbUserName, dbPassword, dbmsServer, dbName :: String -> IO String
dbUserName = undefined
dbPassword = undefined
dbmsServer = undefined
dbName = undefined
-- this helper function may help ...
ge :: String -> String -> IO String
ge str dbname = getEnv ("SQL_DAAS_" ++ str ++ ('_':dbname))
dbPort :: String -> IO Int
dbPort = undefined
-- and with those we can do this:
connectInfo :: String -> IO ConnectInfo
connectInfo dbname = ConnectInfo <$> dbmsServer dbname
<*> (fromIntegral <$> dbPort dbname)
<*> dbUserName dbname <*> dbPassword dbname
<*> dbName dbname
-- and with that we can do this:
withConnection :: String -> (Connection -> IO a) -> IO ()
withConnection dbname fn = undefined
-- with all that now connect to your database and do something cutesies
-- ('cutesies' is a technical term)
| geophf/1HaskellADay | exercises/HAD/Y2018/M04/D05/Exercise.hs | mit | 1,286 | 0 | 11 | 275 | 240 | 133 | 107 | 20 | 1 |
module SPL.Parsers.AbsCK where
-- Haskell module generated by the BNF converter
newtype Ident = Ident String deriving (Eq,Ord,Show)
data ConfigurationKnowledge =
TConfigurationKnowledge [ConfigurationItem]
deriving (Eq,Ord,Show)
data ConfigurationItem =
TBasicConfigurationItem FeatureExp [Transformation]
| TConstrainedConfigurationItem FeatureExp [Transformation] FeatureExp FeatureExp
deriving (Eq,Ord,Show)
data Transformation =
TSelectScenario [Id]
| TEvaluateAdvice [Id]
| TBindParameter Ident Ident
| TSelectComponents [Id]
| TSelectAndMoveComponent Id Id
| TSelectBuildEntries [Id]
deriving (Eq,Ord,Show)
data Id =
TId Ident
deriving (Eq,Ord,Show)
data FeatureExp =
TBasicExp Ident
| TAndExp FeatureExp FeatureExp
| TOrExp FeatureExp FeatureExp
| TNotExp FeatureExp
deriving (Eq,Ord,Show)
| hephaestus-pl/hephaestus | willian/hephaestus-integrated/spl/src/SPL/Parsers/AbsCK.hs | mit | 839 | 0 | 7 | 130 | 233 | 133 | 100 | 26 | 0 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.MallocStatistics (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.MallocStatistics
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.MallocStatistics
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/MallocStatistics.hs | mit | 361 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# htermination sequence_ :: [[] a] -> [] () #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_sequence__2.hs | mit | 50 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Orville.PostgreSQL.SqlType
Copyright : Flipstone Technology Partners 2016-2021
License : MIT
-}
module Orville.PostgreSQL.Internal.ExecutionResult
( ExecutionResult (..),
Column (..),
Row (..),
FakeLibPQResult,
mkFakeLibPQResult,
readRows,
)
where
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import qualified Data.Maybe as Maybe
import qualified Database.PostgreSQL.LibPQ as LibPQ
import Orville.PostgreSQL.Internal.SqlValue (SqlValue)
import qualified Orville.PostgreSQL.Internal.SqlValue as SqlValue
{- |
A trivial wrapper for `Int` to help keep track of column vs row number
-}
newtype Column
= Column Int
deriving (Eq, Ord, Enum)
{- |
A trivial wrapper for `Int` to help keep track of column vs row number
-}
newtype Row
= Row Int
deriving (Eq, Ord, Enum)
{- |
`ExecutionResult` is a common interface for types that represent a result
set returned from the database. For real, live database interactions this
the concrete type will be a `LibPQ.Result`, but the `FakeLibPQResult`
may be useful as well if you are writing custom code for decoding result
sets and want to test aspects of the decoding that don't require a real
database.
-}
class ExecutionResult result where
maxRowNumber :: result -> IO (Maybe Row)
maxColumnNumber :: result -> IO (Maybe Column)
columnName :: result -> Column -> IO (Maybe BS.ByteString)
getValue :: result -> Row -> Column -> IO SqlValue
instance ExecutionResult LibPQ.Result where
maxRowNumber result = do
rowCount <- fmap fromEnum (LibPQ.ntuples result)
pure $
if rowCount > 0
then Just $ Row (rowCount - 1)
else Nothing
maxColumnNumber result = do
columnCount <- fmap fromEnum (LibPQ.nfields result)
pure $
if columnCount > 0
then Just $ Column (columnCount - 1)
else Nothing
columnName result =
LibPQ.fname result . LibPQ.toColumn . fromEnum
getValue result (Row row) (Column column) =
SqlValue.fromRawBytesNullable
<$> LibPQ.getvalue' result (LibPQ.toRow row) (LibPQ.toColumn column)
{- |
`FakeLibPQResult` provides a fake, in memory implementation of
`ExecutionResult`. This is mostly useful for writing automated tests that
can assume a result set has been loaded and just need to test decoding the
results.
-}
data FakeLibPQResult = FakeLibPQResult
{ fakeLibPQColumns :: Map.Map Column BS.ByteString
, fakeLibPQRows :: Map.Map Row (Map.Map Column SqlValue)
}
{- |
Constructs a `FakeLibPQResult`. The column names given as associated with
the values for each row by their position in list. Any missing values (e.g.
because a row is shorter than the heeader list) are treated as a SQL Null
value.
-}
mkFakeLibPQResult ::
-- | The column names for the result set
[BS.ByteString] ->
-- | The row data for the result set
[[SqlValue]] ->
FakeLibPQResult
mkFakeLibPQResult columnList valuesList =
let indexedRows = do
(rowNumber, row) <- zip [Row 0 ..] valuesList
let indexedColumns = zip [Column 0 ..] row
pure (rowNumber, Map.fromList indexedColumns)
in FakeLibPQResult
{ fakeLibPQColumns = Map.fromList (zip [Column 0 ..] columnList)
, fakeLibPQRows = Map.fromList indexedRows
}
fakeLibPQMaxRow :: FakeLibPQResult -> Maybe Row
fakeLibPQMaxRow =
fmap fst . Map.lookupMax . fakeLibPQRows
fakeLibPQMaxColumn :: FakeLibPQResult -> Maybe Column
fakeLibPQMaxColumn result =
let maxColumnsByRow =
map fst
. Maybe.mapMaybe Map.lookupMax
. Map.elems
. fakeLibPQRows
$ result
in case maxColumnsByRow of
[] ->
Nothing
_ ->
Just (maximum maxColumnsByRow)
instance ExecutionResult FakeLibPQResult where
maxRowNumber = pure . fakeLibPQMaxRow
maxColumnNumber = pure . fakeLibPQMaxColumn
columnName result = pure . fakeLibPQColumnName result
getValue result column = pure . fakeLibPQGetValue result column
fakeLibPQColumnName :: FakeLibPQResult -> Column -> (Maybe BS.ByteString)
fakeLibPQColumnName result column =
Map.lookup column (fakeLibPQColumns result)
fakeLibPQGetValue :: FakeLibPQResult -> Row -> Column -> SqlValue
fakeLibPQGetValue result rowNumber columnNumber =
Maybe.fromMaybe SqlValue.sqlNull $ do
row <- Map.lookup rowNumber (fakeLibPQRows result)
Map.lookup columnNumber row
readRows :: LibPQ.Result -> IO [[(Maybe BS.ByteString, SqlValue)]]
readRows res = do
nrows <- LibPQ.ntuples res
nfields <- LibPQ.nfields res
let rowIndices =
listOfIndicesByCount nrows
fieldIndices =
listOfIndicesByCount nfields
-- N.B. the usage of `getvalue'` here is important as this version returns a
-- _copy_ of the data in the `Result` rather than a _reference_.
-- This allows the `Result` to be garbage collected instead of being held onto indefinitely.
readValue rowIndex fieldIndex = do
name <- LibPQ.fname res fieldIndex
rawValue <- LibPQ.getvalue' res rowIndex fieldIndex
pure $
( name
, SqlValue.fromRawBytesNullable rawValue
)
readRow rowIndex =
traverse (readValue rowIndex) fieldIndices
traverse readRow rowIndices
listOfIndicesByCount :: (Num n, Ord n, Enum n) => n -> [n]
listOfIndicesByCount n =
if n > 0
then [0 .. (n - 1)]
else []
| flipstone/orville | orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/ExecutionResult.hs | mit | 5,462 | 0 | 16 | 1,212 | 1,174 | 615 | 559 | 109 | 2 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module TestUtil where
import Data.Text (Text)
import Text.ParserCombinators.Parsec
import qualified Text.Parsec as T
import Test.HUnit
testParsecExpectVal :: (Eq a, Show a) => Text
-> T.Parsec Text () a -> a -> Assertion
testParsecExpectVal = testParsecExpectTransform id
testParsecExpectFirst :: (Eq a, Show a) => Text
-> T.Parsec Text () [a] -> a -> Assertion
testParsecExpectFirst = testParsecExpectTransform head
testParsecExpectTransform :: (Eq b, Show b) => (a->b) -> Text
-> T.Parsec Text () a -> b -> Assertion
testParsecExpectTransform trans source parser expected = case parse parser "" source of
(Right x) -> assertEqual "Parse succeeded, value doesn't match"
expected (trans x)
Left pe -> assertBool ("Parse failed" ++ show pe) False
| emmanueltouzery/cigale-timesheet | tests/TestUtil.hs | mit | 856 | 0 | 11 | 172 | 267 | 140 | 127 | 18 | 2 |
module Weapons.Pistols where
import Weapon
import Damage
despair :: Weapon
despair = Weapon {
accuracy=1.0,
capacity=210,
critChance=0.025,
critMultiplier=1.5,
damage=[Damage 2 Impact, Damage 44 Puncture, Damage 8 Slash],
fireRate=3.3,
magazine=10,
multishot=0,
name="Despair",
reload=0.8,
status=0.025,
weaponType=Pistol
}
embolist :: Weapon
embolist = Weapon {
accuracy=1.0,
capacity=210,
critChance=0.025,
critMultiplier=2,
damage=[Damage 18.5 Toxic],
fireRate=10,
magazine=10,
multishot=0,
name="Embolist",
reload=1.5,
status=0.01,
weaponType=Pistol
}
hikouPrime :: Weapon
hikouPrime = Weapon {
accuracy=1.0,
capacity=210,
critChance=0.05,
critMultiplier=1.5,
damage=[Damage 3.2 Impact, Damage 27.2 Puncture, Damage 1.6 Slash],
fireRate=5.8,
magazine=26,
multishot=0,
name="Hikou Prime",
reload=0.5,
status=0.15,
weaponType=Pistol
}
lexPrime :: Weapon
lexPrime = Weapon {
accuracy=0.16,
capacity=210,
critChance=0.20,
critMultiplier=2.0,
damage=[Damage 8.5 Impact, Damage 68.0 Puncture, Damage 8.5 Slash],
fireRate=2.1,
magazine=8,
multishot=0,
name="Lex Prime",
reload=2.3,
status=0.20,
weaponType=Pistol
}
synoidGammacor :: Weapon
synoidGammacor = Weapon {
accuracy=1.0,
capacity=375,
critChance=0.1,
critMultiplier=2,
damage=[Damage 210 Magnetic],
fireRate=2,
magazine=75,
multishot=0,
name="Synoid Gammacor",
reload=2,
status=0.2,
weaponType=Pistol
}
wraithTwinVipers :: Weapon
wraithTwinVipers = Weapon {
accuracy=0.111,
capacity=210,
critChance=0.18,
critMultiplier=2.0,
damage=[Damage 14.4 Impact, Damage 1.8 Puncture, Damage 1.8 Slash],
fireRate=25.0,
magazine=40,
multishot=0,
name="Wraith Twin Vipers",
reload=2.0,
status=0.05,
weaponType=Pistol
}
vaykorMarelok :: Weapon
vaykorMarelok = Weapon {
accuracy=0.1,
capacity=210,
critChance=0.2,
critMultiplier=1.5,
damage=[Damage 48 Slash, Damage 16 Puncture, Damage 96 Impact],
fireRate=2,
magazine=10,
multishot=0,
name="Vaykor Marelok",
reload=1.7,
status=0.35,
weaponType=Pistol
}
| m4rw3r/warframe-dmg-hs | src/weapons/pistols.hs | mit | 2,311 | 0 | 8 | 563 | 736 | 461 | 275 | 101 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Pocket.Request
( request
)
where
-- aeson
import Data.Aeson (FromJSON, ToJSON)
import qualified Data.Aeson as Aeson
-- base
import Control.Monad.IO.Class (MonadIO)
-- bytestring
import Data.ByteString (ByteString)
-- exceptions
import Control.Monad.Catch (MonadThrow)
-- http-conduit
import Network.HTTP.Simple
-- http-types
import Network.HTTP.Types (HeaderName)
-- pocket
import Web.Pocket.Error (Error)
import qualified Web.Pocket.Error as Error
request
:: (MonadIO m, MonadThrow m, ToJSON a, FromJSON b)
=> String
-> a
-> m (Either Error b)
request req r = do
let
setRequest =
setRequestBodyJSON r . setRequestHeaders headers
response <- httpLBS =<< fmap setRequest (parseRequest req)
case Aeson.decode (getResponseBody response) of
Just authResponse ->
pure (Right authResponse)
Nothing ->
pure (Left (Error.fromResponse response))
headers :: [(HeaderName, ByteString)]
headers =
[ ("Content-Type", "application/json")
, ("X-Accept", "application/json")
]
| jpvillaisaza/pocket-haskell | src/Web/Pocket/Request.hs | mit | 1,074 | 0 | 15 | 192 | 309 | 176 | 133 | 31 | 2 |
{-# LANGUAGE ScopedTypeVariables, Rank2Types, CPP #-}
--
-- (c) The University of Glasgow 2002-2006
--
-- Serialized values
module GHCJS.Prim.TH.Serialized ( Serialized
, fromSerialized
, toSerialized
, serializeWithData
, deserializeWithData
) where
import Prelude
-- import Control.Applicative
import Data.Binary
import Data.Bits
import Data.Data
-- import Data.Typeable
-- import Data.Typeable.Internal
-- import Data.Word
-- | Represents a serialized value of a particular type. Attempts can be made to deserialize it at certain types
data Serialized = Serialized TypeRep [Word8]
instance Binary Serialized where
put (Serialized the_type bytes) =
put the_type >> put bytes
get = Serialized <$> get <*> get
-- | Put a Typeable value that we are able to actually turn into bytes into a 'Serialized' value ready for deserialization later
toSerialized :: Typeable a => (a -> [Word8]) -> a -> Serialized
toSerialized serialize what = Serialized (typeOf what) (serialize what)
-- | If the 'Serialized' value contains something of the given type, then use the specified deserializer to return @Just@ that.
-- Otherwise return @Nothing@.
fromSerialized :: forall a. Typeable a => ([Word8] -> a) -> Serialized -> Maybe a
fromSerialized deserialize (Serialized the_type bytes)
| the_type == typeOf (undefined :: a) = Just (deserialize bytes)
| otherwise = Nothing
-- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms
seqSerialized :: Serialized -> ()
seqSerialized (Serialized the_type bytes) = the_type `seq` bytes `seqList` ()
-- | Use a 'Data' instance to implement a serialization scheme dual to that of 'deserializeWithData'
serializeWithData :: Data a => a -> [Word8]
serializeWithData what = serializeWithData' what []
serializeWithData' :: Data a => a -> [Word8] -> [Word8]
serializeWithData' what = fst $ gfoldl (\(before, a_to_b) a -> (before . serializeWithData' a, a_to_b a))
(\x -> (serializeConstr (constrRep (toConstr what)), x))
what
-- | Use a 'Data' instance to implement a deserialization scheme dual to that of 'serializeWithData'
deserializeWithData :: Data a => [Word8] -> a
deserializeWithData = snd . deserializeWithData'
deserializeWithData' :: forall a. Data a => [Word8] -> ([Word8], a)
deserializeWithData' bytes = deserializeConstr bytes $ \constr_rep bytes ->
gunfold (\(bytes, b_to_r) -> let (bytes', b) = deserializeWithData' bytes in (bytes', b_to_r b))
(\x -> (bytes, x))
(repConstr (dataTypeOf (undefined :: a)) constr_rep)
serializeConstr :: ConstrRep -> [Word8] -> [Word8]
serializeConstr (AlgConstr ix) = serializeWord8 1 . serializeInt ix
serializeConstr (IntConstr i) = serializeWord8 2 . serializeInteger i
serializeConstr (FloatConstr r) = serializeWord8 3 . serializeRational r
serializeConstr (CharConstr c) = serializeWord8 4 . serializeChar c
deserializeConstr :: [Word8] -> (ConstrRep -> [Word8] -> a) -> a
deserializeConstr bytes k = deserializeWord8 bytes $ \constr_ix bytes ->
case constr_ix of
1 -> deserializeInt bytes $ \ix -> k (AlgConstr ix)
2 -> deserializeInteger bytes $ \i -> k (IntConstr i)
3 -> deserializeRational bytes $ \r -> k (FloatConstr r)
4 -> deserializeChar bytes $ \c -> k (CharConstr c)
x -> error $ "deserializeConstr: unrecognised serialized constructor type " ++ show x ++ " in context " ++ show bytes
serializeFixedWidthNum :: forall a. (Num a, Integral a, FiniteBits a) => a -> [Word8] -> [Word8]
serializeFixedWidthNum what = go (finiteBitSize what) what
where
go :: Int -> a -> [Word8] -> [Word8]
go size current rest
| size <= 0 = rest
| otherwise = fromIntegral (current .&. 255) : go (size - 8) (current `shiftR` 8) rest
deserializeFixedWidthNum :: forall a b. (Num a, Integral a, FiniteBits a) => [Word8] -> (a -> [Word8] -> b) -> b
deserializeFixedWidthNum bytes k = go (finiteBitSize (undefined :: a)) bytes k
where
go :: Int -> [Word8] -> (a -> [Word8] -> b) -> b
go size bytes k
| size <= 0 = k 0 bytes
| otherwise = case bytes of
(byte:bytes) -> go (size - 8) bytes (\x -> k ((x `shiftL` 8) .|. fromIntegral byte))
[] -> error "deserializeFixedWidthNum: unexpected end of stream"
serializeEnum :: (Enum a) => a -> [Word8] -> [Word8]
serializeEnum = serializeInt . fromEnum
deserializeEnum :: Enum a => [Word8] -> (a -> [Word8] -> b) -> b
deserializeEnum bytes k = deserializeInt bytes (k . toEnum)
serializeWord8 :: Word8 -> [Word8] -> [Word8]
serializeWord8 x = (x:)
deserializeWord8 :: [Word8] -> (Word8 -> [Word8] -> a) -> a
deserializeWord8 (byte:bytes) k = k byte bytes
deserializeWord8 [] _ = error "deserializeWord8: unexpected end of stream"
serializeInt :: Int -> [Word8] -> [Word8]
serializeInt = serializeFixedWidthNum
deserializeInt :: [Word8] -> (Int -> [Word8] -> a) -> a
deserializeInt = deserializeFixedWidthNum
serializeRational :: (Real a) => a -> [Word8] -> [Word8]
serializeRational = serializeString . show . toRational
deserializeRational :: (Fractional a) => [Word8] -> (a -> [Word8] -> b) -> b
deserializeRational bytes k = deserializeString bytes (k . fromRational . read)
serializeInteger :: Integer -> [Word8] -> [Word8]
serializeInteger = serializeString . show
deserializeInteger :: [Word8] -> (Integer -> [Word8] -> a) -> a
deserializeInteger bytes k = deserializeString bytes (k . read)
serializeChar :: Char -> [Word8] -> [Word8]
serializeChar = serializeString . show
deserializeChar :: [Word8] -> (Char -> [Word8] -> a) -> a
deserializeChar bytes k = deserializeString bytes (k . read)
serializeString :: String -> [Word8] -> [Word8]
serializeString = serializeList serializeEnum
deserializeString :: [Word8] -> (String -> [Word8] -> a) -> a
deserializeString = deserializeList deserializeEnum
serializeList :: (a -> [Word8] -> [Word8]) -> [a] -> [Word8] -> [Word8]
serializeList serialize_element xs = serializeInt (length xs) . foldr (.) id (map serialize_element xs)
deserializeList :: forall a b. (forall c. [Word8] -> (a -> [Word8] -> c) -> c)
-> [Word8] -> ([a] -> [Word8] -> b) -> b
deserializeList deserialize_element bytes k = deserializeInt bytes $ \len bytes -> go len bytes k
where
go :: Int -> [Word8] -> ([a] -> [Word8] -> b) -> b
go len bytes k
| len <= 0 = k [] bytes
| otherwise = deserialize_element bytes (\elt bytes -> go (len - 1) bytes (k . (elt:)))
seqList :: [a] -> b -> b
seqList [] b = b
seqList (x:xs) b = x `seq` seqList xs b
| ghcjs/ghcjs | lib/ghcjs-th/GHCJS/Prim/TH/Serialized.hs | mit | 7,100 | 0 | 18 | 1,803 | 2,264 | 1,210 | 1,054 | 104 | 5 |
import Data.Maybe (fromMaybe)
import qualified Faun.MarkovLogic as ML
mln = ML.fromStrings
[ "∀x Smoking(x) ⇒ Cancer(x) 1.5"
, "∀xy Friend(x, y) ∧ Smoking(x) ⇒ Smoking(y) 1.1"
, "∀x,y Friend(x, y) ⇔ Friend(y, x) 2.0"
, "A.x !Cancer(x) 2.0"]
cs = ["Jerry", "Elaine", "George"]
ask = ML.ask mln cs
p0 = fromMaybe (-10.0) $ ask "P(Cancer(Jerry) | Smoking(George))"
p1 = fromMaybe (-10.0) $ ask "P(Cancer(Jerry) | Smoking(George), Friend(George, Jerry))"
p2 = fromMaybe (-10.0) $ ask "P(Cancer(Jerry) | Smoking(George), Friend(Jerry, George))"
mean = (p0 + p1 + p2) / 3.0
main :: IO ()
main = putStrLn $ show mean
| PhDP/Sphinx-AI | benchmarks/ExactInference.hs | mit | 662 | 8 | 8 | 136 | 193 | 92 | 101 | 15 | 1 |
import System.Random
-- DATA STRUCTURES
type Point = (Int, Int)
type Edge = (Point, Point)
type Box = ([Edge], Int)
type Board = [[Box]]
type Strategy = (Board -> [Edge] -> IO Edge)
-- GAME LOGIC
-- Switch player
changePlayer :: Int -> Int
changePlayer 1 = 2
changePlayer 2 = 1
changeStrategy :: (Strategy, Strategy) -> (Strategy, Strategy)
changeStrategy (s1,s2) = (s2,s1)
-- Change the input format to the game format
normalizeEdge :: [String] -> String -> Edge
normalizeEdge [c1,c2] d
| d == "v" = ((x,y),(x+1,y))
| d == "h" = ((x,y),(x,y+1))
| otherwise = ((x,y),(x,y))
where x = read c1 :: Int
y = read c2 :: Int
-- BOARD UPDATING
-- Put the edge in the board, if that edge makes an square, the boolean is set to true
updateBoard :: Board -> Edge -> Int -> IO (Board, Bool)
updateBoard b e p
| isHorizontal e = return (moveHorizontal b e p)
| otherwise = return (moveVertical b e p)
moveHorizontal :: Board -> Edge -> Int -> (Board, Bool)
moveHorizontal b e@((p1,p2),(q1,q2)) p
| p1 == 0 = (y1 ++ tail b, y2)
| p1 == length b = (init b ++ x1, x2)
| otherwise = (take (p1-1) b ++ x1 ++ y1 ++ drop (p1+1) b, x2 || y2)
where x = fst $ (b !! (p1-1)) !! p2
x1 = [take p2 (b !! (p1-1)) ++ [(e:x, if x2 then p else 0)] ++ drop (p2+1) (b !! (p1-1))]
x2 = length x == 3
y = fst $ (b !! p1) !! p2
y1 = [take p2 (b !! p1) ++ [(e:y, if y2 then p else 0)] ++ drop (p2+1) (b !! p1)]
y2 = length y == 3
moveVertical :: Board -> Edge -> Int -> (Board, Bool)
moveVertical b e@((p1,p2),(q1,q2)) p
| p2 == 0 = (take (max 0 p1) b ++ [a1] ++ drop (min (length (head b)) (p1+1)) b, y1)
| p2 == length (head b) = (take (max 0 p1) b ++ [a2] ++ drop (min (length (head b)) (p1+1)) b, x1)
| otherwise = (take (max 0 p1) b ++ [a3] ++ drop (min (length (head b)) (p1+1)) b, x1 || y1)
where x = fst $ (b !! p1) !! (p2-1)
x1 = length x == 3
y = fst $ (b !! p1) !! p2
y1 = length y == 3
z = b !! p1
a1 = (e:y, if y1 then p else 0) : tail z
a2 = init z ++ [(e:x, if x1 then p else 0)]
a3 = take (p2-1) z ++ [(e:x, if x1 then p else 0)] ++ [(e:y, if y1 then p else 0)] ++ drop (p2+1) z
-- BOARD CHECKS
isAvailable :: Edge -> [Edge] -> Bool
isAvailable = elem
isHorizontal :: Edge -> Bool
isHorizontal ((_,p1),(_,p2)) = abs (p1-p2) == 1
isValid :: Edge -> Bool
isValid ((p1,p2),(q1,q2)) = x || y
where x = abs (p1-q1) == 1 && p2 == q2
y = abs (p2-q2) == 1 && p1 == q1
scores :: Board -> (Int,Int)
scores b = (length p1, length p2)
where p1 = foldl (\x y -> x ++ filter (\z -> snd z == 1) y) [] b
p2 = foldl (\x y -> x ++ filter (\z -> snd z == 2) y) [] b
-- GAME INIT
buildBoard :: Int -> Int -> Board
buildBoard 0 _ = []
buildBoard v h = buildRow h : buildBoard (v-1) h
buildRow :: Int -> [Box]
buildRow 0 = []
buildRow h = ([],0) : buildRow (h-1)
buildAvailables :: Int -> Int -> [Edge]
buildAvailables v h = horizontal ++ vertical
where horizontal = [((x,y),(x,y+1)) | x <- [0..v], y <- [0..(h-1)]]
vertical = [((x,y),(x+1,y)) | x <- [0..(v-1)], y <- [0..h]]
deleteAvailable :: Edge -> [Edge] -> [Edge]
deleteAvailable e = filter (/= e)
-- BOARD REPRESENTATION
boardToString :: Board -> String
boardToString b = x ++ "\n" ++ fst (foldl printBoxes ("",(0,0)) b)
where x = fst $ foldl printHorizontal ("*",(0,0)) $ head b
printBoxes :: (String,Point) -> [Box] -> (String,Point)
printBoxes (s,(p1,p2)) lb = (s++x++"\n"++y++"\n",(p1+1,p2))
where z = if ((p1,p2),(p1+1,p2)) `elem` fst (head lb) then "-" else " "
x = fst $ foldl printVertical (z,(p1,p2)) lb
y = fst $ foldl printHorizontal ("*",(p1+1,p2)) lb
printHorizontal :: (String,Point) -> Box -> (String,Point)
printHorizontal (s,(p1,p2)) (le,_) = if ((p1,p2),(p1,p2+1)) `elem` le then (s++" - *",(p1,p2+1)) else (s++" *",(p1,p2+1))
printVertical :: (String,Point) -> Box -> (String,Point)
printVertical (s,(p1,p2)) (le,n) = if ((p1,p2+1),(p1+1,p2+1)) `elem` le then (s++" "++show n++" -",(p1,p2+1)) else (s++" "++show n++" ",(p1,p2+1))
printBoard :: Board -> IO ()
printBoard b = do putStrLn ""
putStrLn $ boardToString b
putStrLn ""
-- GAME
main :: IO ()
main = do intro
putStrLn "Game definition:"
putStrLn "What is the size of the board in boxes? (vertical horizontal)"
size <- getLine
let v = read (head $ words size) :: Int
let h = read (last $ words size) :: Int
let board = buildBoard v h
let availables = buildAvailables v h
player1 <- selectPlayer 1
player2 <- selectPlayer 2
putStrLn ""
run 1 (player1,player2) board availables
intro :: IO ()
intro = do putStrLn "********************"
putStrLn "** DOTS & BOXES! **"
putStrLn "********************"
putStrLn ""
putStrLn "How to play:"
putStrLn "- Each turn you have to specify the line you want to draw"
putStrLn "- Each line is defined by the starting point and the direction of the line"
putStrLn "- Each point it's defined as two integers indicating it's coordinates"
putStrLn "- The coordinates of the board start at (0,0) in the upper left corner"
putStrLn "- The direction of the line could be horizontal (h) or vertical (v) (in lowercase)"
putStrLn "- Input example: 1 0 v (vertical line starting at coordinate (1,0))"
putStrLn "- When a player completes a box, he moves again"
putStrLn "- The game ends when all the boxes are completed"
putStrLn ""
example
example :: IO ()
example = do putStrLn "This is an example of a board and it's coordinates"
putStrLn " (0,0) (0,1) (0,2)"
putStrLn " (1,0) (1,1) (1,2)"
putStrLn " (2,0) (2,1) (2,2)"
putStrLn ""
putStrLn "Board representation:"
putStrLn " * It's a point"
putStrLn " - It's a line made by a player"
putStrLn " 0 This box isn't complete yet"
putStrLn " 1 Player 1 completed that box"
putStrLn " 2 Player 2 completed that box"
putStrLn ""
selectPlayer :: Int -> IO Strategy
selectPlayer n = do putStrLn $ "Choose the player " ++ show n
putStrLn "1. Human"
putStrLn "2. CPU easy"
putStrLn "3. CPU medium"
putStrLn "4. CPU hard"
n <- getLine
getPlayer (read n)
getPlayer :: Int -> IO Strategy
getPlayer 1 = return human
getPlayer 2 = return easy
getPlayer 3 = return medium
getPlayer 4 = return hard
-- The strategy is used to select the edge to be played
run :: Int -> (Strategy,Strategy) -> Board -> [Edge] -> IO ()
run _ _ b [] = gameFinished b
run p str b le = do putStrLn $ "Turn to Player " ++ show p
edge <- fst str b le
putStrLn $ "Player " ++ show p ++ " moves to " ++ show edge
nb <- updateBoard b edge p
if snd nb then do putStrLn "SQUARE!!!"
run p str (fst nb) (deleteAvailable edge le )
else run (changePlayer p) (changeStrategy str) (fst nb) (deleteAvailable edge le)
gameFinished :: Board -> IO ()
gameFinished b = do let (p1,p2) = scores b
putStrLn ""
putStrLn "GAME FINISHED!"
putStrLn ""
printBoard b
putStrLn "SCORES:"
putStr "Player 1: "
print p1
putStr "Player 2: "
print p2
putStrLn ""
-- STRATEGIES
-- Human plays. Input consist in 2 integers representing the starting coordinate
-- and a character (h or v) indicating if the line is horizontal or vertical
human :: Strategy
human b le = do printBoard b
input <- getLine
let p = take 2 $ words input
let d = last $ words input
let e = normalizeEdge p d
if not $ isValid e then do putStrLn "The selected coordinates can't make a line, please enter a correct ones"
human b le
else if not $ isAvailable e le then do putStrLn "The selected line is not available, please enter another"
human b le
else return e
-- Random choice in the given edge list
easy :: Strategy
easy b le = do r <- randomRIO (0, length le - 1)
return (le !! r)
-- Tries to complete a square, if not possible makes a random choice
medium :: Strategy
medium b le = do l <- findSquareEdges b le
easy b (if null l then le else l)
-- Tries to complete a square, if not possible tries to avoid to make
-- the third line in a square, if not possible makes a random choice
hard :: Strategy
hard b le = do l <- findSquareEdges b le
if null l then do l2 <- findGoodEdges b le
easy b (if null l2 then le else l2)
else easy b l
-- STRATEGY HELPERS
isEdgeN :: Int -> Board -> Edge -> Bool
isEdgeN n b e@((p1,p2),(q1,q2))
| h && p1 == 0 = length y == n
| h && p1 == length b = length x == n
| h = (length x == n) || (length y == n)
| p2 == 0 = length y == n
| p2 == length (head b) = length z == n
| otherwise = (length z == n) || (length y == n)
where h = isHorizontal e
x = fst $ (b !! (p1-1)) !! p2
y = fst $ (b !! p1) !! p2
z = fst $ (b !! p1) !! (p2-1)
findSquareEdges :: Board -> [Edge] -> IO [Edge]
findSquareEdges b le = return (filter (isEdgeN 3 b) le)
findGoodEdges :: Board -> [Edge] -> IO [Edge]
findGoodEdges b le = return (filter (not . isEdgeN 2 b) le)
| bmoix/dots-and-boxes | dots-boxes.hs | mit | 10,130 | 326 | 14 | 3,364 | 3,925 | 2,116 | 1,809 | 200 | 5 |
-- | "System.Process.ListLike" functions restricted to type 'Data.ByteString.Char8.ByteString'.
-- All the module's supporting functions are also re-exported here.
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module System.Process.ByteString
( readProcess
, readProcessWithExitCode
, readCreateProcess
, readCreateProcessWithExitCode
, readProcessInterleaved
, readInterleaved
, readProcessChunks
, module System.Process
, module System.Process.ListLike
) where
import Data.ByteString.Char8 (ByteString)
import System.Exit (ExitCode)
import System.IO (Handle)
import System.Process hiding (readProcess, readProcessWithExitCode)
import System.Process.ListLike hiding (readCreateProcess, readCreateProcessWithExitCode,
readProcess, readProcessWithExitCode,
readProcessInterleaved, readInterleaved, readProcessChunks)
import qualified System.Process.ListLike as LL
readProcess :: (a ~ ByteString) => FilePath -> [String] -> a -> IO a
readProcess = LL.readProcess
readProcessWithExitCode :: (a ~ ByteString) => FilePath -> [String] -> a -> IO (ExitCode, a, a)
readProcessWithExitCode = LL.readProcessWithExitCode
readCreateProcess :: (a ~ ByteString) => CreateProcess -> a -> IO a
readCreateProcess = LL.readCreateProcess
readCreateProcessWithExitCode :: (a ~ ByteString) => CreateProcess -> a -> IO (ExitCode, a, a)
readCreateProcessWithExitCode = LL.readCreateProcessWithExitCode
readProcessInterleaved :: (a ~ ByteString, ProcessOutput a b) => CreateProcess -> a -> IO b
readProcessInterleaved = LL.readProcessInterleaved
readInterleaved :: (a ~ ByteString, ProcessOutput a b) => [(a -> b, Handle)] -> IO b -> IO b
readInterleaved = LL.readInterleaved
readProcessChunks :: (a ~ ByteString) => CreateProcess -> a -> IO [LL.Chunk a]
readProcessChunks = LL.readProcessChunks
| ddssff/process-listlike-old | System/Process/ByteString.hs | mit | 1,925 | 0 | 11 | 323 | 441 | 255 | 186 | 34 | 1 |
{-# LANGUAGE ExistentialQuantification, ParallelListComp, TemplateHaskell #-}
{-| TemplateHaskell helper for Ganeti Haskell code.
As TemplateHaskell require that splices be defined in a separate
module, we combine all the TemplateHaskell functionality that HTools
needs in this module (except the one for unittests).
-}
{-
Copyright (C) 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.THH ( declareSADT
, declareLADT
, declareILADT
, declareIADT
, makeJSONInstance
, deCamelCase
, genOpID
, genAllConstr
, genAllOpIDs
, PyValue(..)
, PyValueEx(..)
, OpCodeDescriptor
, genOpCode
, genStrOfOp
, genStrOfKey
, genLuxiOp
, Field (..)
, simpleField
, withDoc
, defaultField
, optionalField
, optionalNullSerField
, renameField
, customField
, timeStampFields
, uuidFields
, serialFields
, tagsFields
, TagSet
, buildObject
, buildObjectSerialisation
, buildParam
, DictObject(..)
, genException
, excErrMsg
) where
import Control.Monad (liftM)
import Data.Char
import Data.List
import qualified Data.Set as Set
import Language.Haskell.TH
import qualified Text.JSON as JSON
import Text.JSON.Pretty (pp_value)
import Ganeti.JSON
import Data.Maybe
import Data.Functor ((<$>))
-- * Exported types
-- | Class of objects that can be converted to 'JSObject'
-- lists-format.
class DictObject a where
toDict :: a -> [(String, JSON.JSValue)]
-- | Optional field information.
data OptionalType
= NotOptional -- ^ Field is not optional
| OptionalOmitNull -- ^ Field is optional, null is not serialised
| OptionalSerializeNull -- ^ Field is optional, null is serialised
deriving (Show, Eq)
-- | Serialised field data type.
data Field = Field { fieldName :: String
, fieldType :: Q Type
, fieldRead :: Maybe (Q Exp)
, fieldShow :: Maybe (Q Exp)
, fieldExtraKeys :: [String]
, fieldDefault :: Maybe (Q Exp)
, fieldConstr :: Maybe String
, fieldIsOptional :: OptionalType
, fieldDoc :: String
}
-- | Generates a simple field.
simpleField :: String -> Q Type -> Field
simpleField fname ftype =
Field { fieldName = fname
, fieldType = ftype
, fieldRead = Nothing
, fieldShow = Nothing
, fieldExtraKeys = []
, fieldDefault = Nothing
, fieldConstr = Nothing
, fieldIsOptional = NotOptional
, fieldDoc = ""
}
withDoc :: String -> Field -> Field
withDoc doc field =
field { fieldDoc = doc }
-- | Sets the renamed constructor field.
renameField :: String -> Field -> Field
renameField constrName field = field { fieldConstr = Just constrName }
-- | Sets the default value on a field (makes it optional with a
-- default value).
defaultField :: Q Exp -> Field -> Field
defaultField defval field = field { fieldDefault = Just defval }
-- | Marks a field optional (turning its base type into a Maybe).
optionalField :: Field -> Field
optionalField field = field { fieldIsOptional = OptionalOmitNull }
-- | Marks a field optional (turning its base type into a Maybe), but
-- with 'Nothing' serialised explicitly as /null/.
optionalNullSerField :: Field -> Field
optionalNullSerField field = field { fieldIsOptional = OptionalSerializeNull }
-- | Sets custom functions on a field.
customField :: Name -- ^ The name of the read function
-> Name -- ^ The name of the show function
-> [String] -- ^ The name of extra field keys
-> Field -- ^ The original field
-> Field -- ^ Updated field
customField readfn showfn extra field =
field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn)
, fieldExtraKeys = extra }
-- | Computes the record name for a given field, based on either the
-- string value in the JSON serialisation or the custom named if any
-- exists.
fieldRecordName :: Field -> String
fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
fromMaybe (camelCase name) alias
-- | Computes the preferred variable name to use for the value of this
-- field. If the field has a specific constructor name, then we use a
-- first-letter-lowercased version of that; otherwise, we simply use
-- the field name. See also 'fieldRecordName'.
fieldVariable :: Field -> String
fieldVariable f =
case (fieldConstr f) of
Just name -> ensureLower name
_ -> map (\c -> if c == '-' then '_' else c) $ fieldName f
-- | Compute the actual field type (taking into account possible
-- optional status).
actualFieldType :: Field -> Q Type
actualFieldType f | fieldIsOptional f /= NotOptional = [t| Maybe $t |]
| otherwise = t
where t = fieldType f
-- | Checks that a given field is not optional (for object types or
-- fields which should not allow this case).
checkNonOptDef :: (Monad m) => Field -> m ()
checkNonOptDef (Field { fieldIsOptional = OptionalOmitNull
, fieldName = name }) =
fail $ "Optional field " ++ name ++ " used in parameter declaration"
checkNonOptDef (Field { fieldIsOptional = OptionalSerializeNull
, fieldName = name }) =
fail $ "Optional field " ++ name ++ " used in parameter declaration"
checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
fail $ "Default field " ++ name ++ " used in parameter declaration"
checkNonOptDef _ = return ()
-- | Produces the expression that will de-serialise a given
-- field. Since some custom parsing functions might need to use the
-- entire object, we do take and pass the object to any custom read
-- functions.
loadFn :: Field -- ^ The field definition
-> Q Exp -- ^ The value of the field as existing in the JSON message
-> Q Exp -- ^ The entire object in JSON object format
-> Q Exp -- ^ Resulting expression
loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
loadFn _ expr _ = expr
-- * Common field declarations
-- | Timestamp fields description.
timeStampFields :: [Field]
timeStampFields =
[ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
, defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
]
-- | Serial number fields description.
serialFields :: [Field]
serialFields =
[ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
-- | UUID fields description.
uuidFields :: [Field]
uuidFields = [ simpleField "uuid" [t| String |] ]
-- | Tag set type alias.
type TagSet = Set.Set String
-- | Tag field description.
tagsFields :: [Field]
tagsFields = [ defaultField [| Set.empty |] $
simpleField "tags" [t| TagSet |] ]
-- * Internal types
-- | A simple field, in constrast to the customisable 'Field' type.
type SimpleField = (String, Q Type)
-- | A definition for a single constructor for a simple object.
type SimpleConstructor = (String, [SimpleField])
-- | A definition for ADTs with simple fields.
type SimpleObject = [SimpleConstructor]
-- | A type alias for an opcode constructor of a regular object.
type OpCodeConstructor = (String, Q Type, String, [Field], String)
-- | A type alias for a Luxi constructor of a regular object.
type LuxiConstructor = (String, [Field])
-- * Helper functions
-- | Ensure first letter is lowercase.
--
-- Used to convert type name to function prefix, e.g. in @data Aa ->
-- aaToRaw@.
ensureLower :: String -> String
ensureLower [] = []
ensureLower (x:xs) = toLower x:xs
-- | Ensure first letter is uppercase.
--
-- Used to convert constructor name to component
ensureUpper :: String -> String
ensureUpper [] = []
ensureUpper (x:xs) = toUpper x:xs
-- | Helper for quoted expressions.
varNameE :: String -> Q Exp
varNameE = varE . mkName
-- | showJSON as an expression, for reuse.
showJSONE :: Q Exp
showJSONE = varE 'JSON.showJSON
-- | makeObj as an expression, for reuse.
makeObjE :: Q Exp
makeObjE = varE 'JSON.makeObj
-- | fromObj (Ganeti specific) as an expression, for reuse.
fromObjE :: Q Exp
fromObjE = varE 'fromObj
-- | ToRaw function name.
toRawName :: String -> Name
toRawName = mkName . (++ "ToRaw") . ensureLower
-- | FromRaw function name.
fromRawName :: String -> Name
fromRawName = mkName . (++ "FromRaw") . ensureLower
-- | Converts a name to it's varE\/litE representations.
reprE :: Either String Name -> Q Exp
reprE = either stringE varE
-- | Smarter function application.
--
-- This does simply f x, except that if is 'id', it will skip it, in
-- order to generate more readable code when using -ddump-splices.
appFn :: Exp -> Exp -> Exp
appFn f x | f == VarE 'id = x
| otherwise = AppE f x
-- | Builds a field for a normal constructor.
buildConsField :: Q Type -> StrictTypeQ
buildConsField ftype = do
ftype' <- ftype
return (NotStrict, ftype')
-- | Builds a constructor based on a simple definition (not field-based).
buildSimpleCons :: Name -> SimpleObject -> Q Dec
buildSimpleCons tname cons = do
decl_d <- mapM (\(cname, fields) -> do
fields' <- mapM (buildConsField . snd) fields
return $ NormalC (mkName cname) fields') cons
return $ DataD [] tname [] decl_d [''Show, ''Eq]
-- | Generate the save function for a given type.
genSaveSimpleObj :: Name -- ^ Object type
-> String -- ^ Function name
-> SimpleObject -- ^ Object definition
-> (SimpleConstructor -> Q Clause) -- ^ Constructor save fn
-> Q (Dec, Dec)
genSaveSimpleObj tname sname opdefs fn = do
let sigt = AppT (AppT ArrowT (ConT tname)) (ConT ''JSON.JSValue)
fname = mkName sname
cclauses <- mapM fn opdefs
return $ (SigD fname sigt, FunD fname cclauses)
-- * Template code for simple raw type-equivalent ADTs
-- | Generates a data type declaration.
--
-- The type will have a fixed list of instances.
strADTDecl :: Name -> [String] -> Dec
strADTDecl name constructors =
DataD [] name []
(map (flip NormalC [] . mkName) constructors)
[''Show, ''Eq, ''Enum, ''Bounded, ''Ord]
-- | Generates a toRaw function.
--
-- This generates a simple function of the form:
--
-- @
-- nameToRaw :: Name -> /traw/
-- nameToRaw Cons1 = var1
-- nameToRaw Cons2 = \"value2\"
-- @
genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
genToRaw traw fname tname constructors = do
let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
-- the body clauses, matching on the constructor and returning the
-- raw value
clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
(normalB (reprE v)) []) constructors
return [SigD fname sigt, FunD fname clauses]
-- | Generates a fromRaw function.
--
-- The function generated is monadic and can fail parsing the
-- raw value. It is of the form:
--
-- @
-- nameFromRaw :: (Monad m) => /traw/ -> m Name
-- nameFromRaw s | s == var1 = Cons1
-- | s == \"value2\" = Cons2
-- | otherwise = fail /.../
-- @
genFromRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
genFromRaw traw fname tname constructors = do
-- signature of form (Monad m) => String -> m $name
sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
-- clauses for a guarded pattern
let varp = mkName "s"
varpe = varE varp
clauses <- mapM (\(c, v) -> do
-- the clause match condition
g <- normalG [| $varpe == $(reprE v) |]
-- the clause result
r <- [| return $(conE (mkName c)) |]
return (g, r)) constructors
-- the otherwise clause (fallback)
oth_clause <- do
g <- normalG [| otherwise |]
r <- [|fail ("Invalid string value for type " ++
$(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
return (g, r)
let fun = FunD fname [Clause [VarP varp]
(GuardedB (clauses++[oth_clause])) []]
return [SigD fname sigt, fun]
-- | Generates a data type from a given raw format.
--
-- The format is expected to multiline. The first line contains the
-- type name, and the rest of the lines must contain two words: the
-- constructor name and then the string representation of the
-- respective constructor.
--
-- The function will generate the data type declaration, and then two
-- functions:
--
-- * /name/ToRaw, which converts the type to a raw type
--
-- * /name/FromRaw, which (monadically) converts from a raw type to the type
--
-- Note that this is basically just a custom show\/read instance,
-- nothing else.
declareADT
:: (a -> Either String Name) -> Name -> String -> [(String, a)] -> Q [Dec]
declareADT fn traw sname cons = do
let name = mkName sname
ddecl = strADTDecl name (map fst cons)
-- process cons in the format expected by genToRaw
cons' = map (\(a, b) -> (a, fn b)) cons
toraw <- genToRaw traw (toRawName sname) name cons'
fromraw <- genFromRaw traw (fromRawName sname) name cons'
return $ ddecl:toraw ++ fromraw
declareLADT :: Name -> String -> [(String, String)] -> Q [Dec]
declareLADT = declareADT Left
declareILADT :: String -> [(String, Int)] -> Q [Dec]
declareILADT sname cons = do
consNames <- sequence [ newName ('_':n) | (n, _) <- cons ]
consFns <- concat <$> sequence
[ do sig <- sigD n [t| Int |]
let expr = litE (IntegerL (toInteger i))
fn <- funD n [clause [] (normalB expr) []]
return [sig, fn]
| n <- consNames
| (_, i) <- cons ]
let cons' = [ (n, n') | (n, _) <- cons | n' <- consNames ]
(consFns ++) <$> declareADT Right ''Int sname cons'
declareIADT :: String -> [(String, Name)] -> Q [Dec]
declareIADT = declareADT Right ''Int
declareSADT :: String -> [(String, Name)] -> Q [Dec]
declareSADT = declareADT Right ''String
-- | Creates the showJSON member of a JSON instance declaration.
--
-- This will create what is the equivalent of:
--
-- @
-- showJSON = showJSON . /name/ToRaw
-- @
--
-- in an instance JSON /name/ declaration
genShowJSON :: String -> Q Dec
genShowJSON name = do
body <- [| JSON.showJSON . $(varE (toRawName name)) |]
return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []]
-- | Creates the readJSON member of a JSON instance declaration.
--
-- This will create what is the equivalent of:
--
-- @
-- readJSON s = case readJSON s of
-- Ok s' -> /name/FromRaw s'
-- Error e -> Error /description/
-- @
--
-- in an instance JSON /name/ declaration
genReadJSON :: String -> Q Dec
genReadJSON name = do
let s = mkName "s"
body <- [| case JSON.readJSON $(varE s) of
JSON.Ok s' -> $(varE (fromRawName name)) s'
JSON.Error e ->
JSON.Error $ "Can't parse raw value for type " ++
$(stringE name) ++ ": " ++ e ++ " from " ++
show $(varE s)
|]
return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []]
-- | Generates a JSON instance for a given type.
--
-- This assumes that the /name/ToRaw and /name/FromRaw functions
-- have been defined as by the 'declareSADT' function.
makeJSONInstance :: Name -> Q [Dec]
makeJSONInstance name = do
let base = nameBase name
showJ <- genShowJSON base
readJ <- genReadJSON base
return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
-- * Template code for opcodes
-- | Transforms a CamelCase string into an_underscore_based_one.
deCamelCase :: String -> String
deCamelCase =
intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
-- | Transform an underscore_name into a CamelCase one.
camelCase :: String -> String
camelCase = concatMap (ensureUpper . drop 1) .
groupBy (\_ b -> b /= '_' && b /= '-') . ('_':)
-- | Computes the name of a given constructor.
constructorName :: Con -> Q Name
constructorName (NormalC name _) = return name
constructorName (RecC name _) = return name
constructorName x = fail $ "Unhandled constructor " ++ show x
-- | Extract all constructor names from a given type.
reifyConsNames :: Name -> Q [String]
reifyConsNames name = do
reify_result <- reify name
case reify_result of
TyConI (DataD _ _ _ cons _) -> mapM (liftM nameBase . constructorName) cons
o -> fail $ "Unhandled name passed to reifyConsNames, expected\
\ type constructor but got '" ++ show o ++ "'"
-- | Builds the generic constructor-to-string function.
--
-- This generates a simple function of the following form:
--
-- @
-- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
-- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
-- @
--
-- This builds a custom list of name\/string pairs and then uses
-- 'genToRaw' to actually generate the function.
genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
genConstrToStr trans_fun name fname = do
cnames <- reifyConsNames name
let svalues = map (Left . trans_fun) cnames
genToRaw ''String (mkName fname) name $ zip cnames svalues
-- | Constructor-to-string for OpCode.
genOpID :: Name -> String -> Q [Dec]
genOpID = genConstrToStr deCamelCase
-- | Builds a list with all defined constructor names for a type.
--
-- @
-- vstr :: String
-- vstr = [...]
-- @
--
-- Where the actual values of the string are the constructor names
-- mapped via @trans_fun@.
genAllConstr :: (String -> String) -> Name -> String -> Q [Dec]
genAllConstr trans_fun name vstr = do
cnames <- reifyConsNames name
let svalues = sort $ map trans_fun cnames
vname = mkName vstr
sig = SigD vname (AppT ListT (ConT ''String))
body = NormalB (ListE (map (LitE . StringL) svalues))
return $ [sig, ValD (VarP vname) body []]
-- | Generates a list of all defined opcode IDs.
genAllOpIDs :: Name -> String -> Q [Dec]
genAllOpIDs = genAllConstr deCamelCase
-- | OpCode parameter (field) type.
type OpParam = (String, Q Type, Q Exp)
-- * Python code generation
-- | Converts Haskell values into Python values
--
-- This is necessary for the default values of opcode parameters and
-- return values. For example, if a default value or return type is a
-- Data.Map, then it must be shown as a Python dictioanry.
class PyValue a where
showValue :: a -> String
-- | Encapsulates Python default values
data PyValueEx = forall a. PyValue a => PyValueEx a
instance PyValue PyValueEx where
showValue (PyValueEx x) = showValue x
-- | Transfers opcode data between the opcode description (through
-- @genOpCode@) and the Python code generation functions.
type OpCodeDescriptor =
(String, String, String, [String],
[String], [Maybe PyValueEx], [String], String)
-- | Strips out the module name
--
-- @
-- pyBaseName "Data.Map" = "Map"
-- @
pyBaseName :: String -> String
pyBaseName str =
case span (/= '.') str of
(x, []) -> x
(_, _:x) -> pyBaseName x
-- | Converts a Haskell type name into a Python type name.
--
-- @
-- pyTypename "Bool" = "ht.TBool"
-- @
pyTypeName :: Show a => a -> String
pyTypeName name =
"ht.T" ++ (case pyBaseName (show name) of
"()" -> "None"
"Map" -> "DictOf"
"Set" -> "SetOf"
"ListSet" -> "SetOf"
"Either" -> "Or"
"GenericContainer" -> "DictOf"
"JSValue" -> "Any"
"JSObject" -> "Object"
str -> str)
-- | Converts a Haskell type into a Python type.
--
-- @
-- pyType [Int] = "ht.TListOf(ht.TInt)"
-- @
pyType :: Type -> Q String
pyType (AppT typ1 typ2) =
do t <- pyCall typ1 typ2
return $ t ++ ")"
pyType (ConT name) = return (pyTypeName name)
pyType ListT = return "ht.TListOf"
pyType (TupleT 0) = return "ht.TNone"
pyType (TupleT _) = return "ht.TTupleOf"
pyType typ = error $ "unhandled case for type " ++ show typ
-- | Converts a Haskell type application into a Python type.
--
-- @
-- Maybe Int = "ht.TMaybe(ht.TInt)"
-- @
pyCall :: Type -> Type -> Q String
pyCall (AppT typ1 typ2) arg =
do t <- pyCall typ1 typ2
targ <- pyType arg
return $ t ++ ", " ++ targ
pyCall typ1 typ2 =
do t1 <- pyType typ1
t2 <- pyType typ2
return $ t1 ++ "(" ++ t2
-- | @pyType opt typ@ converts Haskell type @typ@ into a Python type,
-- where @opt@ determines if the converted type is optional (i.e.,
-- Maybe).
--
-- @
-- pyType False [Int] = "ht.TListOf(ht.TInt)" (mandatory)
-- pyType True [Int] = "ht.TMaybe(ht.TListOf(ht.TInt))" (optional)
-- @
pyOptionalType :: Bool -> Type -> Q String
pyOptionalType opt typ
| opt = do t <- pyType typ
return $ "ht.TMaybe(" ++ t ++ ")"
| otherwise = pyType typ
-- | Optionally encapsulates default values in @PyValueEx@.
--
-- @maybeApp exp typ@ returns a quoted expression that encapsulates
-- the default value @exp@ of an opcode parameter cast to @typ@ in a
-- @PyValueEx@, if @exp@ is @Just@. Otherwise, it returns a quoted
-- expression with @Nothing@.
maybeApp :: Maybe (Q Exp) -> Q Type -> Q Exp
maybeApp Nothing _ =
[| Nothing |]
maybeApp (Just expr) typ =
[| Just ($(conE (mkName "PyValueEx")) ($expr :: $typ)) |]
-- | Generates a Python type according to whether the field is
-- optional
genPyType :: OptionalType -> Q Type -> Q ExpQ
genPyType opt typ =
do t <- typ
stringE <$> pyOptionalType (opt /= NotOptional) t
-- | Generates Python types from opcode parameters.
genPyTypes :: [Field] -> Q ExpQ
genPyTypes fs =
listE <$> mapM (\f -> genPyType (fieldIsOptional f) (fieldType f)) fs
-- | Generates Python default values from opcode parameters.
genPyDefaults :: [Field] -> ExpQ
genPyDefaults fs =
listE $ map (\f -> maybeApp (fieldDefault f) (fieldType f)) fs
-- | Generates a Haskell function call to "showPyClass" with the
-- necessary information on how to build the Python class string.
pyClass :: OpCodeConstructor -> ExpQ
pyClass (consName, consType, consDoc, consFields, consDscField) =
do let pyClassVar = varNameE "showPyClass"
consName' = stringE consName
consType' <- genPyType NotOptional consType
let consDoc' = stringE consDoc
consFieldNames = listE $ map (stringE . fieldName) consFields
consFieldDocs = listE $ map (stringE . fieldDoc) consFields
consFieldTypes <- genPyTypes consFields
let consFieldDefaults = genPyDefaults consFields
[| ($consName',
$consType',
$consDoc',
$consFieldNames,
$consFieldTypes,
$consFieldDefaults,
$consFieldDocs,
consDscField) |]
-- | Generates a function called "pyClasses" that holds the list of
-- all the opcode descriptors necessary for generating the Python
-- opcodes.
pyClasses :: [OpCodeConstructor] -> Q [Dec]
pyClasses cons =
do let name = mkName "pyClasses"
sig = SigD name (AppT ListT (ConT ''OpCodeDescriptor))
fn <- FunD name <$> (:[]) <$> declClause cons
return [sig, fn]
where declClause c =
clause [] (normalB (ListE <$> mapM pyClass c)) []
-- | Converts from an opcode constructor to a Luxi constructor.
opcodeConsToLuxiCons :: (a, b, c, d, e) -> (a, d)
opcodeConsToLuxiCons (x, _, _, y, _) = (x, y)
-- | Generates the OpCode data type.
--
-- This takes an opcode logical definition, and builds both the
-- datatype and the JSON serialisation out of it. We can't use a
-- generic serialisation since we need to be compatible with Ganeti's
-- own, so we have a few quirks to work around.
genOpCode :: String -- ^ Type name to use
-> [OpCodeConstructor] -- ^ Constructor name and parameters
-> Q [Dec]
genOpCode name cons = do
let tname = mkName name
decl_d <- mapM (\(cname, _, _, fields, _) -> do
-- we only need the type of the field, without Q
fields' <- mapM (fieldTypeInfo "op") fields
return $ RecC (mkName cname) fields')
cons
let declD = DataD [] tname [] decl_d [''Show, ''Eq]
let (allfsig, allffn) = genAllOpFields "allOpFields" cons
save_decs <- genSaveOpCode tname "saveOpCode" "toDictOpCode"
(map opcodeConsToLuxiCons cons) saveConstructor True
(loadsig, loadfn) <- genLoadOpCode cons
pyDecls <- pyClasses cons
return $ [declD, allfsig, allffn, loadsig, loadfn] ++ save_decs ++ pyDecls
-- | Generates the function pattern returning the list of fields for a
-- given constructor.
genOpConsFields :: OpCodeConstructor -> Clause
genOpConsFields (cname, _, _, fields, _) =
let op_id = deCamelCase cname
fvals = map (LitE . StringL) . sort . nub $
concatMap (\f -> fieldName f:fieldExtraKeys f) fields
in Clause [LitP (StringL op_id)] (NormalB $ ListE fvals) []
-- | Generates a list of all fields of an opcode constructor.
genAllOpFields :: String -- ^ Function name
-> [OpCodeConstructor] -- ^ Object definition
-> (Dec, Dec)
genAllOpFields sname opdefs =
let cclauses = map genOpConsFields opdefs
other = Clause [WildP] (NormalB (ListE [])) []
fname = mkName sname
sigt = AppT (AppT ArrowT (ConT ''String)) (AppT ListT (ConT ''String))
in (SigD fname sigt, FunD fname (cclauses++[other]))
-- | Generates the \"save\" clause for an entire opcode constructor.
--
-- This matches the opcode with variables named the same as the
-- constructor fields (just so that the spliced in code looks nicer),
-- and passes those name plus the parameter definition to 'saveObjectField'.
saveConstructor :: LuxiConstructor -- ^ The constructor
-> Q Clause -- ^ Resulting clause
saveConstructor (sname, fields) = do
let cname = mkName sname
fnames <- mapM (newName . fieldVariable) fields
let pat = conP cname (map varP fnames)
let felems = map (uncurry saveObjectField) (zip fnames fields)
-- now build the OP_ID serialisation
opid = [| [( $(stringE "OP_ID"),
JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
flist = listE (opid:felems)
-- and finally convert all this to a json object
flist' = [| concat $flist |]
clause [pat] (normalB flist') []
-- | Generates the main save opcode function.
--
-- This builds a per-constructor match clause that contains the
-- respective constructor-serialisation code.
genSaveOpCode :: Name -- ^ Object ype
-> String -- ^ To 'JSValue' function name
-> String -- ^ To 'JSObject' function name
-> [LuxiConstructor] -- ^ Object definition
-> (LuxiConstructor -> Q Clause) -- ^ Constructor save fn
-> Bool -- ^ Whether to generate
-- obj or just a
-- list\/tuple of values
-> Q [Dec]
genSaveOpCode tname jvalstr tdstr opdefs fn gen_object = do
tdclauses <- mapM fn opdefs
let typecon = ConT tname
jvalname = mkName jvalstr
jvalsig = AppT (AppT ArrowT typecon) (ConT ''JSON.JSValue)
tdname = mkName tdstr
tdsig <- [t| $(return typecon) -> [(String, JSON.JSValue)] |]
jvalclause <- if gen_object
then [| $makeObjE . $(varE tdname) |]
else [| JSON.showJSON . map snd . $(varE tdname) |]
return [ SigD tdname tdsig
, FunD tdname tdclauses
, SigD jvalname jvalsig
, ValD (VarP jvalname) (NormalB jvalclause) []]
-- | Generates load code for a single constructor of the opcode data type.
loadConstructor :: OpCodeConstructor -> Q Exp
loadConstructor (sname, _, _, fields, _) = do
let name = mkName sname
fbinds <- mapM loadObjectField fields
let (fnames, fstmts) = unzip fbinds
let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
return $ DoE fstmts'
-- | Generates the loadOpCode function.
genLoadOpCode :: [OpCodeConstructor] -> Q (Dec, Dec)
genLoadOpCode opdefs = do
let fname = mkName "loadOpCode"
arg1 = mkName "v"
objname = mkName "o"
opid = mkName "op_id"
st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
(JSON.readJSON $(varE arg1)) |]
st2 <- bindS (varP opid) [| $fromObjE $(varE objname) $(stringE "OP_ID") |]
-- the match results (per-constructor blocks)
mexps <- mapM loadConstructor opdefs
fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
let mpats = map (\(me, (consName, _, _, _, _)) ->
let mp = LitP . StringL . deCamelCase $ consName
in Match mp (NormalB me) []
) $ zip mexps opdefs
defmatch = Match WildP (NormalB fails) []
cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
body = DoE [st1, st2, cst]
sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
-- * Template code for luxi
-- | Constructor-to-string for LuxiOp.
genStrOfOp :: Name -> String -> Q [Dec]
genStrOfOp = genConstrToStr id
-- | Constructor-to-string for MsgKeys.
genStrOfKey :: Name -> String -> Q [Dec]
genStrOfKey = genConstrToStr ensureLower
-- | Generates the LuxiOp data type.
--
-- This takes a Luxi operation definition and builds both the
-- datatype and the function transforming the arguments to JSON.
-- We can't use anything less generic, because the way different
-- operations are serialized differs on both parameter- and top-level.
--
-- There are two things to be defined for each parameter:
--
-- * name
--
-- * type
--
genLuxiOp :: String -> [LuxiConstructor] -> Q [Dec]
genLuxiOp name cons = do
let tname = mkName name
decl_d <- mapM (\(cname, fields) -> do
-- we only need the type of the field, without Q
fields' <- mapM actualFieldType fields
let fields'' = zip (repeat NotStrict) fields'
return $ NormalC (mkName cname) fields'')
cons
let declD = DataD [] (mkName name) [] decl_d [''Show, ''Eq]
save_decs <- genSaveOpCode tname "opToArgs" "opToDict"
cons saveLuxiConstructor False
req_defs <- declareSADT "LuxiReq" .
map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
cons
return $ declD:save_decs ++ req_defs
-- | Generates the \"save\" clause for entire LuxiOp constructor.
saveLuxiConstructor :: LuxiConstructor -> Q Clause
saveLuxiConstructor (sname, fields) = do
let cname = mkName sname
fnames <- mapM (newName . fieldVariable) fields
let pat = conP cname (map varP fnames)
let felems = map (uncurry saveObjectField) (zip fnames fields)
flist = [| concat $(listE felems) |]
clause [pat] (normalB flist) []
-- * "Objects" functionality
-- | Extract the field's declaration from a Field structure.
fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
fieldTypeInfo field_pfx fd = do
t <- actualFieldType fd
let n = mkName . (field_pfx ++) . fieldRecordName $ fd
return (n, NotStrict, t)
-- | Build an object declaration.
buildObject :: String -> String -> [Field] -> Q [Dec]
buildObject sname field_pfx fields = do
let name = mkName sname
fields_d <- mapM (fieldTypeInfo field_pfx) fields
let decl_d = RecC name fields_d
let declD = DataD [] name [] [decl_d] [''Show, ''Eq]
ser_decls <- buildObjectSerialisation sname fields
return $ declD:ser_decls
-- | Generates an object definition: data type and its JSON instance.
buildObjectSerialisation :: String -> [Field] -> Q [Dec]
buildObjectSerialisation sname fields = do
let name = mkName sname
savedecls <- genSaveObject saveObjectField sname fields
(loadsig, loadfn) <- genLoadObject loadObjectField sname fields
shjson <- objectShowJSON sname
rdjson <- objectReadJSON sname
let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
[rdjson, shjson]
return $ savedecls ++ [loadsig, loadfn, instdecl]
-- | The toDict function name for a given type.
toDictName :: String -> Name
toDictName sname = mkName ("toDict" ++ sname)
-- | Generates the save object functionality.
genSaveObject :: (Name -> Field -> Q Exp)
-> String -> [Field] -> Q [Dec]
genSaveObject save_fn sname fields = do
let name = mkName sname
fnames <- mapM (newName . fieldVariable) fields
let pat = conP name (map varP fnames)
let tdname = toDictName sname
tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
let felems = map (uncurry save_fn) (zip fnames fields)
flist = listE felems
-- and finally convert all this to a json object
tdlist = [| concat $flist |]
iname = mkName "i"
tclause <- clause [pat] (normalB tdlist) []
cclause <- [| $makeObjE . $(varE tdname) |]
let fname = mkName ("save" ++ sname)
sigt <- [t| $(conT name) -> JSON.JSValue |]
return [SigD tdname tdsigt, FunD tdname [tclause],
SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
-- | Generates the code for saving an object's field, handling the
-- various types of fields that we have.
saveObjectField :: Name -> Field -> Q Exp
saveObjectField fvar field =
case fieldIsOptional field of
OptionalOmitNull -> [| case $(varE fvar) of
Nothing -> []
Just v -> [( $nameE, JSON.showJSON v )]
|]
OptionalSerializeNull -> [| case $(varE fvar) of
Nothing -> [( $nameE, JSON.JSNull )]
Just v -> [( $nameE, JSON.showJSON v )]
|]
NotOptional ->
case fieldShow field of
-- Note: the order of actual:extra is important, since for
-- some serialisation types (e.g. Luxi), we use tuples
-- (positional info) rather than object (name info)
Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
Just fn -> [| let (actual, extra) = $fn $fvarE
in ($nameE, JSON.showJSON actual):extra
|]
where nameE = stringE (fieldName field)
fvarE = varE fvar
-- | Generates the showJSON clause for a given object name.
objectShowJSON :: String -> Q Dec
objectShowJSON name = do
body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []]
-- | Generates the load object functionality.
genLoadObject :: (Field -> Q (Name, Stmt))
-> String -> [Field] -> Q (Dec, Dec)
genLoadObject load_fn sname fields = do
let name = mkName sname
funname = mkName $ "load" ++ sname
arg1 = mkName $ if null fields then "_" else "v"
objname = mkName "o"
opid = mkName "op_id"
st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
(JSON.readJSON $(varE arg1)) |]
fbinds <- mapM load_fn fields
let (fnames, fstmts) = unzip fbinds
let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
retstmt = [NoBindS (AppE (VarE 'return) cval)]
-- FIXME: should we require an empty dict for an empty type?
-- this allows any JSValue right now
fstmts' = if null fields
then retstmt
else st1:fstmts ++ retstmt
sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
return $ (SigD funname sigt,
FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
-- | Generates code for loading an object's field.
loadObjectField :: Field -> Q (Name, Stmt)
loadObjectField field = do
let name = fieldVariable field
fvar <- newName name
-- these are used in all patterns below
let objvar = varNameE "o"
objfield = stringE (fieldName field)
loadexp =
if fieldIsOptional field /= NotOptional
-- we treat both optional types the same, since
-- 'maybeFromObj' can deal with both missing and null values
-- appropriately (the same)
then [| $(varE 'maybeFromObj) $objvar $objfield |]
else case fieldDefault field of
Just defv ->
[| $(varE 'fromObjWithDefault) $objvar
$objfield $defv |]
Nothing -> [| $fromObjE $objvar $objfield |]
bexp <- loadFn field loadexp objvar
return (fvar, BindS (VarP fvar) bexp)
-- | Builds the readJSON instance for a given object name.
objectReadJSON :: String -> Q Dec
objectReadJSON name = do
let s = mkName "s"
body <- [| case JSON.readJSON $(varE s) of
JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
JSON.Error e ->
JSON.Error $ "Can't parse value for type " ++
$(stringE name) ++ ": " ++ e
|]
return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []]
-- * Inheritable parameter tables implementation
-- | Compute parameter type names.
paramTypeNames :: String -> (String, String)
paramTypeNames root = ("Filled" ++ root ++ "Params",
"Partial" ++ root ++ "Params")
-- | Compute information about the type of a parameter field.
paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
paramFieldTypeInfo field_pfx fd = do
t <- actualFieldType fd
let n = mkName . (++ "P") . (field_pfx ++) .
fieldRecordName $ fd
return (n, NotStrict, AppT (ConT ''Maybe) t)
-- | Build a parameter declaration.
--
-- This function builds two different data structures: a /filled/ one,
-- in which all fields are required, and a /partial/ one, in which all
-- fields are optional. Due to the current record syntax issues, the
-- fields need to be named differrently for the two structures, so the
-- partial ones get a /P/ suffix.
buildParam :: String -> String -> [Field] -> Q [Dec]
buildParam sname field_pfx fields = do
let (sname_f, sname_p) = paramTypeNames sname
name_f = mkName sname_f
name_p = mkName sname_p
fields_f <- mapM (fieldTypeInfo field_pfx) fields
fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
let decl_f = RecC name_f fields_f
decl_p = RecC name_p fields_p
let declF = DataD [] name_f [] [decl_f] [''Show, ''Eq]
declP = DataD [] name_p [] [decl_p] [''Show, ''Eq]
ser_decls_f <- buildObjectSerialisation sname_f fields
ser_decls_p <- buildPParamSerialisation sname_p fields
fill_decls <- fillParam sname field_pfx fields
return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls ++
buildParamAllFields sname fields ++
buildDictObjectInst name_f sname_f
-- | Builds a list of all fields of a parameter.
buildParamAllFields :: String -> [Field] -> [Dec]
buildParamAllFields sname fields =
let vname = mkName ("all" ++ sname ++ "ParamFields")
sig = SigD vname (AppT ListT (ConT ''String))
val = ListE $ map (LitE . StringL . fieldName) fields
in [sig, ValD (VarP vname) (NormalB val) []]
-- | Builds the 'DictObject' instance for a filled parameter.
buildDictObjectInst :: Name -> String -> [Dec]
buildDictObjectInst name sname =
[InstanceD [] (AppT (ConT ''DictObject) (ConT name))
[ValD (VarP 'toDict) (NormalB (VarE (toDictName sname))) []]]
-- | Generates the serialisation for a partial parameter.
buildPParamSerialisation :: String -> [Field] -> Q [Dec]
buildPParamSerialisation sname fields = do
let name = mkName sname
savedecls <- genSaveObject savePParamField sname fields
(loadsig, loadfn) <- genLoadObject loadPParamField sname fields
shjson <- objectShowJSON sname
rdjson <- objectReadJSON sname
let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
[rdjson, shjson]
return $ savedecls ++ [loadsig, loadfn, instdecl]
-- | Generates code to save an optional parameter field.
savePParamField :: Name -> Field -> Q Exp
savePParamField fvar field = do
checkNonOptDef field
let actualVal = mkName "v"
normalexpr <- saveObjectField actualVal field
-- we have to construct the block here manually, because we can't
-- splice-in-splice
return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
(NormalB (ConE '[])) []
, Match (ConP 'Just [VarP actualVal])
(NormalB normalexpr) []
]
-- | Generates code to load an optional parameter field.
loadPParamField :: Field -> Q (Name, Stmt)
loadPParamField field = do
checkNonOptDef field
let name = fieldName field
fvar <- newName name
-- these are used in all patterns below
let objvar = varNameE "o"
objfield = stringE name
loadexp = [| $(varE 'maybeFromObj) $objvar $objfield |]
bexp <- loadFn field loadexp objvar
return (fvar, BindS (VarP fvar) bexp)
-- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
buildFromMaybe :: String -> Q Dec
buildFromMaybe fname =
valD (varP (mkName $ "n_" ++ fname))
(normalB [| $(varE 'fromMaybe)
$(varNameE $ "f_" ++ fname)
$(varNameE $ "p_" ++ fname) |]) []
-- | Builds a function that executes the filling of partial parameter
-- from a full copy (similar to Python's fillDict).
fillParam :: String -> String -> [Field] -> Q [Dec]
fillParam sname field_pfx fields = do
let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
(sname_f, sname_p) = paramTypeNames sname
oname_f = "fobj"
oname_p = "pobj"
name_f = mkName sname_f
name_p = mkName sname_p
fun_name = mkName $ "fill" ++ sname ++ "Params"
le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
(NormalB . VarE . mkName $ oname_f) []
le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
(NormalB . VarE . mkName $ oname_p) []
obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
$ map (mkName . ("n_" ++)) fnames
le_new <- mapM buildFromMaybe fnames
funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
let sig = SigD fun_name funt
fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
(NormalB $ LetE (le_full:le_part:le_new) obj_new) []
fun = FunD fun_name [fclause]
return [sig, fun]
-- * Template code for exceptions
-- | Exception simple error message field.
excErrMsg :: (String, Q Type)
excErrMsg = ("errMsg", [t| String |])
-- | Builds an exception type definition.
genException :: String -- ^ Name of new type
-> SimpleObject -- ^ Constructor name and parameters
-> Q [Dec]
genException name cons = do
let tname = mkName name
declD <- buildSimpleCons tname cons
(savesig, savefn) <- genSaveSimpleObj tname ("save" ++ name) cons $
uncurry saveExcCons
(loadsig, loadfn) <- genLoadExc tname ("load" ++ name) cons
return [declD, loadsig, loadfn, savesig, savefn]
-- | Generates the \"save\" clause for an entire exception constructor.
--
-- This matches the exception with variables named the same as the
-- constructor fields (just so that the spliced in code looks nicer),
-- and calls showJSON on it.
saveExcCons :: String -- ^ The constructor name
-> [SimpleField] -- ^ The parameter definitions for this
-- constructor
-> Q Clause -- ^ Resulting clause
saveExcCons sname fields = do
let cname = mkName sname
fnames <- mapM (newName . fst) fields
let pat = conP cname (map varP fnames)
felems = if null fnames
then conE '() -- otherwise, empty list has no type
else listE $ map (\f -> [| JSON.showJSON $(varE f) |]) fnames
let tup = tupE [ litE (stringL sname), felems ]
clause [pat] (normalB [| JSON.showJSON $tup |]) []
-- | Generates load code for a single constructor of an exception.
--
-- Generates the code (if there's only one argument, we will use a
-- list, not a tuple:
--
-- @
-- do
-- (x1, x2, ...) <- readJSON args
-- return $ Cons x1 x2 ...
-- @
loadExcConstructor :: Name -> String -> [SimpleField] -> Q Exp
loadExcConstructor inname sname fields = do
let name = mkName sname
f_names <- mapM (newName . fst) fields
let read_args = AppE (VarE 'JSON.readJSON) (VarE inname)
let binds = case f_names of
[x] -> BindS (ListP [VarP x])
_ -> BindS (TupP (map VarP f_names))
cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) f_names
return $ DoE [binds read_args, NoBindS (AppE (VarE 'return) cval)]
{-| Generates the loadException function.
This generates a quite complicated function, along the lines of:
@
loadFn (JSArray [JSString name, args]) = case name of
"A1" -> do
(x1, x2, ...) <- readJSON args
return $ A1 x1 x2 ...
"a2" -> ...
s -> fail $ "Unknown exception" ++ s
loadFn v = fail $ "Expected array but got " ++ show v
@
-}
genLoadExc :: Name -> String -> SimpleObject -> Q (Dec, Dec)
genLoadExc tname sname opdefs = do
let fname = mkName sname
exc_name <- newName "name"
exc_args <- newName "args"
exc_else <- newName "s"
arg_else <- newName "v"
fails <- [| fail $ "Unknown exception '" ++ $(varE exc_else) ++ "'" |]
-- default match for unknown exception name
let defmatch = Match (VarP exc_else) (NormalB fails) []
-- the match results (per-constructor blocks)
str_matches <-
mapM (\(s, params) -> do
body_exp <- loadExcConstructor exc_args s params
return $ Match (LitP (StringL s)) (NormalB body_exp) [])
opdefs
-- the first function clause; we can't use [| |] due to TH
-- limitations, so we have to build the AST by hand
let clause1 = Clause [ConP 'JSON.JSArray
[ListP [ConP 'JSON.JSString [VarP exc_name],
VarP exc_args]]]
(NormalB (CaseE (AppE (VarE 'JSON.fromJSString)
(VarE exc_name))
(str_matches ++ [defmatch]))) []
-- the fail expression for the second function clause
fail_type <- [| fail $ "Invalid exception: expected '(string, [args])' " ++
" but got " ++ show (pp_value $(varE arg_else)) ++ "'"
|]
-- the second function clause
let clause2 = Clause [VarP arg_else] (NormalB fail_type) []
sigt <- [t| JSON.JSValue -> JSON.Result $(conT tname) |]
return $ (SigD fname sigt, FunD fname [clause1, clause2])
| vladimir-ipatov/ganeti | src/Ganeti/THH.hs | gpl-2.0 | 47,998 | 4 | 20 | 12,767 | 11,237 | 5,956 | 5,281 | -1 | -1 |
module Main where
import Lib
import System.Exit
import Control.Exception
main :: IO ()
main = do
anHero
res <- try mainAction :: IO (Either SomeException ())
case res of
Left e -> die $ "Ошибка : " ++ show e
Right () -> exitSuccess
| gore-v/xc | app/Main.hs | gpl-2.0 | 271 | 0 | 11 | 77 | 99 | 49 | 50 | 11 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Concurrent (newEmptyMVar, takeMVar, putMVar, threadDelay)
import Control.Concurrent.Async (async, cancel, race_)
import Control.Concurrent.STM (newTVarIO, writeTVar, atomically)
import Control.Exception (Exception(..), SomeException)
import Control.Immortal.Queue (processImmortalQueue, closeImmortalQueue)
import Control.Monad (when, forever, void, forM_)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Logger (MonadLogger, runNoLoggingT, runStderrLoggingT)
import Data.Aeson (Result(..), fromJSON)
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Monoid ((<>))
import Data.Pool (destroyAllResources)
import Data.Text.Encoding (decodeUtf8)
import Data.Version (showVersion)
import Database.Persist.Postgresql
import Network.Wai (Request, requestMethod, rawPathInfo, rawQueryString)
import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
import System.Directory (getCurrentDirectory, createDirectoryIfMissing)
import System.Environment (lookupEnv)
import System.Log.FastLogger
( LogType(LogStdout, LogFile), FileLogSpec(..), TimedFastLogger
, newTimeCache, newTimedFastLogger, defaultBufSize
)
import System.Posix.Signals (installHandler, sigTERM, Handler(CatchOnce))
import Web.Stripe.Client (StripeConfig(..), StripeKey(..))
import Api
import Auth (sessionEntropy, mkPersistentServerKey)
import Cache (initializeCaches, emptyCache)
import Config
import Models
import Models.PersistJSON (JSONValue(..))
import Paths_sese_website (version)
import StoneEdge (StoneEdgeCredentials(..))
import Workers (Task(CleanDatabase, AddSalesReportDay), taskQueueConfig, enqueueTask)
import qualified Avalara
import qualified Data.ByteString.Char8 as C
import qualified Data.Text as T
import qualified Network.Wai.Handler.Warp as Warp
import Prelude hiding (log)
-- | Connect to the database, configure the application, & start the server.
--
-- TODO: Document enviornmental variables in README.
main :: IO ()
main = do
env <- lookupSetting "ENV" Development
(avalaraLogger, stripeLogger, serverLogger, cleanupLoggers) <- makeLoggers env
let log = logMsg serverLogger
log "SESE API Server starting up."
port <- lookupSetting "PORT" 3000
mediaDir <- lookupDirectory "MEDIA" "/media/"
log $ "Media directory initialized at " <> T.pack mediaDir <> "."
smtpServer <- fromMaybe "" <$> lookupEnv "SMTP_SERVER"
smtpUser <- fromMaybe "" <$> lookupEnv "SMTP_USER"
smtpPass <- fromMaybe "" <$> lookupEnv "SMTP_PASS"
emailPool <- smtpPool smtpServer (poolSize env)
log $ "Initialized SMTP Pool at " <> T.pack smtpServer <> "."
stripeToken <- fromMaybe "" <$> lookupEnv "STRIPE_TOKEN"
cookieSecret <- mkPersistentServerKey . C.pack . fromMaybe ""
<$> lookupEnv "COOKIE_SECRET"
entropySource <- sessionEntropy
stoneEdgeAuth <- makeStoneEdgeAuth
avalaraStatus <- lookupSetting "AVATAX_STATUS" AvalaraTesting
avalaraConfig <- makeAvalaraConfig
avalaraCompanyId <- Avalara.CompanyId <$> lookupSetting "AVATAX_COMPANY_ID" 0
avalaraCompanyCode <- Avalara.CompanyCode . T.pack <$> requireSetting "AVATAX_COMPANY_CODE"
avalaraSourceLocation <- T.pack . fromMaybe "DEFAULT" <$> lookupEnv "AVATAX_LOCATION_CODE"
dbPool <- makePool env
initializeJobs dbPool
log "Initialized database pool."
cache <- newTVarIO emptyCache
void . async
$ runSqlPool initializeCaches dbPool >>= atomically . writeTVar cache
log "Started initialization of database cache."
let cfg = defaultConfig
{ getPool = dbPool
, getEnv = env
, getCaches = cache
, getMediaDirectory = mediaDir
, getSmtpPool = emailPool
, getSmtpUser = smtpUser
, getSmtpPass = smtpPass
, getStripeConfig = StripeConfig $ StripeKey $ C.pack stripeToken
, getStoneEdgeAuth = stoneEdgeAuth
, getCookieSecret = cookieSecret
, getCookieEntropySource = entropySource
, getAvalaraStatus = avalaraStatus
, getAvalaraConfig = avalaraConfig
, getAvalaraCompanyId = avalaraCompanyId
, getAvalaraCompanyCode = avalaraCompanyCode
, getAvalaraSourceLocationCode = avalaraSourceLocation
, getAvalaraLogger = avalaraLogger
, getStripeLogger = stripeLogger
, getServerLogger = serverLogger
}
log "Starting 2 worker threads."
workers <- processImmortalQueue $ taskQueueConfig 2 cfg
log $ "Serving HTTP requests on port " <> T.pack (show port) <> "."
shutdownMVar <- newEmptyMVar
void $ installHandler sigTERM (CatchOnce $ putMVar shutdownMVar ()) Nothing
asyncWarp <- async
$ Warp.runSettings (warpSettings port serverLogger) . httpLogger env
$ app cfg
race_ (takeMVar shutdownMVar) (forever $ threadDelay maxBound)
log "Received SIGTERM, starting clean shutdown."
log "Waiting for worker queue to finish..."
closeImmortalQueue workers
log "Worker queue closed."
cancel asyncWarp
log "HTTP server stopped."
destroyAllResources emailPool
log "SMTP pool closed."
destroyAllResources dbPool
log "PostgreSQL pool closed."
log "Shutdown completed successfully."
cleanupLoggers
where lookupSetting env def =
maybe def read <$> lookupEnv env
requireSetting :: String -> IO String
requireSetting env =
lookupEnv env
>>= maybe (error $ "Could not find required env variable: " ++ env) return
makePool :: Environment -> IO ConnectionPool
makePool env =
case env of
Production ->
runNoLoggingT $ makeSqlPool env
Development ->
runStderrLoggingT $ makeSqlPool env
makeSqlPool :: (MonadIO m, MonadLogger m, MonadBaseControl IO m) => Environment -> m ConnectionPool
makeSqlPool env = do
pool <- createPostgresqlPool "dbname=sese-website" $ poolSize env
runSqlPool (runMigration migrateAll) pool
return pool
poolSize env =
case env of
Production ->
8
Development ->
2
warpSettings port serverLogger =
Warp.setServerName ""
$ Warp.setOnException (exceptionHandler serverLogger)
$ Warp.setPort port Warp.defaultSettings
exceptionHandler :: TimedFastLogger -> Maybe Request -> SomeException -> IO ()
exceptionHandler logger mReq e =
let reqString = flip (maybe "") mReq $ \req ->
decodeUtf8 $
"("
<> requestMethod req
<> " "
<> rawPathInfo req
<> rawQueryString req
<> ")"
in
when (Warp.defaultShouldDisplayException e) $
logMsg logger $ T.concat
[ "Exception while processing request"
, reqString
, ": "
, T.pack $ displayException e
]
logMsg :: TimedFastLogger -> T.Text -> IO ()
logMsg logger =
logger . timedLogStr
httpLogger env =
case env of
Production ->
logStdout
Development ->
logStdoutDev
makeStoneEdgeAuth = do
secUsername <- T.pack . fromMaybe "" <$> lookupEnv "STONE_EDGE_USER"
secPassword <- T.pack . fromMaybe "" <$> lookupEnv "STONE_EDGE_PASS"
secStoreCode <- T.pack . fromMaybe "" <$> lookupEnv "STONE_EDGE_CODE"
return StoneEdgeCredentials {..}
makeAvalaraConfig :: IO Avalara.Config
makeAvalaraConfig = do
let cAppName = "SESE Retail Website"
cAppVersion = T.pack $ showVersion version
cAccountId <- Avalara.AccountId . T.pack
<$> requireSetting "AVATAX_ACCOUNT_ID"
cLicenseKey <- Avalara.LicenseKey . T.pack
<$> requireSetting "AVATAX_LICENSE_KEY"
rawEnvironment <- T.pack <$> requireSetting "AVATAX_ENVIRONMENT"
cServiceEnvironment <- case T.toLower rawEnvironment of
"sandbox" ->
return Avalara.SandboxEnvironment
"production" ->
return Avalara.ProductionEnvironment
_ ->
error $ "Invalid AVATAX_ENVIRONMENT: " ++ T.unpack rawEnvironment
++ "\n\n\tValid value are `Production` or `Sandbox`"
return Avalara.Config {..}
makeLoggers :: Environment -> IO (TimedFastLogger, TimedFastLogger, TimedFastLogger, IO ())
makeLoggers env = do
timeCache <- newTimeCache "%Y-%m-%dT%T"
case env of
Development -> do
let makeLogger = newTimedFastLogger timeCache
(avalara, aClean) <- makeLogger (LogStdout defaultBufSize)
(stripe, stripeClean) <- makeLogger (LogStdout defaultBufSize)
(server, servClean) <- makeLogger (LogStdout defaultBufSize)
return (avalara, stripe, server, aClean >> stripeClean >> servClean)
Production -> do
logDir <- lookupDirectory "LOGS" "/logs/"
let makeLogger fp = newTimedFastLogger timeCache
$ LogFile (FileLogSpec fp (1024 * 1024 * 50) 5)
defaultBufSize
(avalara, aClean) <- makeLogger $ logDir ++ "/avalara.log"
(stripe, stripeClean) <- makeLogger $ logDir ++ "/stripe.log"
(server, servClean) <- makeLogger $ logDir ++ "/server.log"
return (avalara, stripe, server, aClean >> stripeClean >> servClean)
lookupDirectory :: String -> FilePath -> IO FilePath
lookupDirectory envName defaultPath = do
dir <- lookupEnv envName
>>= maybe ((++ defaultPath) <$> getCurrentDirectory) return
createDirectoryIfMissing True dir
return dir
initializeJobs :: ConnectionPool -> IO ()
initializeJobs = runSqlPool $ do
jobs <- selectList [] []
let decodedJobs = mapMaybe (decodeJobType . entityVal) jobs
recurringTasks = [CleanDatabase, AddSalesReportDay]
forM_ recurringTasks $ \task ->
when (task `notElem` decodedJobs) $
enqueueTask Nothing task
decodeJobType :: Job -> Maybe Task
decodeJobType job =
case fromJSON (fromJSONValue $ jobAction job) of
Success j ->
Just j
Error _ ->
Nothing
| Southern-Exposure-Seed-Exchange/southernexposure.com | server/app/Main.hs | gpl-3.0 | 11,271 | 0 | 23 | 3,440 | 2,528 | 1,294 | 1,234 | 231 | 8 |
module File where
import qualified Data.ByteString.Lazy as BStr
import Control.Exception
import Crypto.Hash
import Data.List
import System.Directory
import System.Exit
import System.FilePath
import System.FilePath.Posix
import System.Posix
import System.Process
import System.IO
import Util
printError :: IOException -> IO ()
printError e = do
print e
emptyError :: IOException -> IO [t]
emptyError e = do
print e
return []
nothingError :: IOException -> IO (Maybe t)
nothingError e = do
print e
return Nothing
contentSize :: FilePath -> IO (Maybe FileOffset)
contentSize filename =
handle (nothingError) $ do
stat <- getFileStatus filename
return $ Just (fileSize stat)
-- replace with unix stat type
data FileStat = FileStat {
fileLocation :: FilePath,
fileName :: String,
isDirectory :: Bool
}
createFileStat :: FilePath -> IO FileStat
createFileStat path = do
isDir <- doesDirectoryExist path
return $ FileStat loc name isDir where
loc = takeDirectory path
name = takeFileName path
directoryContent :: FilePath -> IO [FileStat]
directoryContent p = do
allFiles <- showDirectory p
list <- mapM createFileStat (prefixSet (p ++ "/") allFiles)
return list
-- mapping from url paths to mount paths
data DirectoryUrl = DirectoryUrl {
duMount :: FilePath,
duWebRoot :: FilePath,
duDirectory :: FilePath
}
closeHandles :: [Handle] -> IO ()
closeHandles [] = do
return ()
closeHandles (h:hs) = do
hClose h
closeHandles hs
noTrailingSlash :: FilePath -> FilePath
noTrailingSlash p =
if last p == '/'
then init p
else p
webLocation :: DirectoryUrl -> FilePath
webLocation d = noTrailingSlash $ (duWebRoot d) ++ (duDirectory d)
fsLocation :: DirectoryUrl -> FilePath
fsLocation d = noTrailingSlash $ (duMount d) ++ (duDirectory d)
showDirectoryUrl :: DirectoryUrl -> String
showDirectoryUrl d = ("(" ++ (duMount d) ++ ", " ++ (duWebRoot d) ++ ", " ++ (duDirectory d) ++ ")")
fullFsPath :: DirectoryUrl -> FileStat -> FilePath
fullFsPath d f = ((fsLocation d) ++ "/" ++ (fileName f))
fullWebPath :: DirectoryUrl -> FileStat -> FilePath
fullWebPath d f = ((webLocation d) ++ "/" ++ (fileName f))
extMimeMaybe :: String -> Maybe String
extMimeMaybe ext =
if ext == ".txt" then Just "text/plain"
else if ext == ".svg" then Just "image/svg+xml"
else if ext == ".mp3" then Just "audio/mpeg"
else if ext == ".webm" then Just "video/webm"
else if ext == ".mp4" then Just "video/mp4"
else if ext == ".obv" then Just "video/ogg"
else Nothing
filePathMimeMaybe :: FilePath -> Maybe String
filePathMimeMaybe path = extMimeMaybe (takeExtension path)
showFileMime :: FilePath -> String
showFileMime path =
let ext = takeExtension path in
case extMimeMaybe ext of
Nothing -> ext
Just m -> m
readFileHash :: FilePath -> IO (Digest MD5)
readFileHash path = do
fileContent <- BStr.readFile path
let h = (hashlazy fileContent) in do
putStrLn (path ++ ":\t" ++ (show h))
return h
readFileSize :: FilePath -> IO Integer
readFileSize path = do
size <- contentSize path
case size of
Just s -> do
return $ toInteger s
Nothing -> do
return 0
fileSizeBase :: Integer -> Integer -> String
fileSizeBase b i =
if i > 1024
then fileSizeBase (b + 1) (div i 1024)
else ((show i) ++ " " ++ ext) where
ext = case b of
0 -> "Bytes"
1 -> "KB"
2 -> "MB"
3 -> "GB"
4 -> "TB"
otherwise -> "PB"
showFileSize :: Integer -> String
showFileSize s = fileSizeBase 0 s
listBlockChar :: String -> String
listBlockChar ('\\':'x':xs) = [(hexDigitToChar xs)]
listBlockChar _ = ""
-- replace symbols in url
listBlockReplace :: String -> String
listBlockReplace "" = ""
listBlockReplace url = let (a, b) = break (=='\\') url in
a ++ (listBlockChar (take 4 b)) ++ (listBlockReplace (drop 4 b))
listBlock :: [String] -> IO [[String]]
listBlock items = do
result <- readProcess "lsblk" ["-r", ("-o" ++ (intercalate "," items))] ""
return $ map2D listBlockReplace (map allWords (lines result))
listCpu :: IO [[String]]
listCpu = do
result <- readProcess "lscpu" ["-p"] ""
return $ map (wordDelim (==',')) (lines result)
-- command line actions
tryCommand :: String -> IO ExitCode
tryCommand cmd = do
putStrLn cmd
ps <- runCommand cmd
code <- waitForProcess ps
putStrLn $ show code
return code
-- return hostname
getHostname :: IO String
getHostname = readFile "/etc/hostname"
dotDirFilter :: String -> Bool
dotDirFilter [] = False
dotDirFilter (c:cs) = c /= '.'
showDirectory :: FilePath -> IO [FilePath]
showDirectory path =
handle (emptyError) $ do
content <- getDirectoryContents path
return $ filter dotDirFilter content
absolutePath :: [String] -> FilePath
absolutePath strs = ("/" ++ (intercalate "/" strs))
-- recursivly get all non-directory files
allFileContents :: FilePath -> [FilePath] -> IO [FilePath]
allFileContents _ [] = do
return []
allFileContents prefix (p:ps) = do
isDir <- doesDirectoryExist (prefix ++ "/" ++ p)
otherDirs <- allFileContents prefix ps
if isDir
then do
ct <- showDirectory (prefix ++ "/" ++ p)
dirCont <- allFileContents prefix (prefixSet (p ++ "/") ct)
return (dirCont ++ otherDirs)
else do
return (p : otherDirs)
-- recursivly get all non-directory files
allSubFiles :: FilePath -> IO [FilePath]
allSubFiles path = do
isDir <- doesDirectoryExist path
if isDir
then do
ct <- showDirectory path
dirCont <- allFileContents path ct
return dirCont
else do
return []
-- only remove empty directories
removeEmptyDirectory :: FilePath -> IO ExitCode
removeEmptyDirectory path = do
e <- tryCommand ("rmdir " ++ path)
return e
removeAllEmptyDirectory :: FilePath -> [FilePath] -> IO ()
removeAllEmptyDirectory _ [] = do
return ()
removeAllEmptyDirectory base (p:ps) = do
removeEmptyDirectory (base ++ "/" ++ p)
removeAllEmptyDirectory base ps
-- no longer used
fileErrorHandler :: IOException -> IO (String, [Handle])
fileErrorHandler e = do
print e
return ("", [])
-- no longer used
contentHandle :: FilePath -> IO (String, [Handle])
contentHandle filename =
handle (fileErrorHandler) $ do
handle <- openFile filename ReadMode
hSetBinaryMode handle True
hSetBuffering handle NoBuffering
contents <- hGetContents handle
return (contents, [handle])
-- no longer used
fileContent :: FilePath -> IO String
fileContent filename = do
(c, h) <- contentHandle filename
return c
mountDevice :: FilePath -> FilePath -> Bool -> IO ExitCode
mountDevice dev path writable = do
e1 <- tryCommand ("mkdir " ++ path)
case e1 of
ExitSuccess -> do
if writable
then do
e2 <- tryCommand ("mount -o rw " ++ dev ++ " " ++ path)
return e2
else do
e2 <- tryCommand ("mount -o ro " ++ dev ++ " " ++ path)
return e2
ExitFailure a -> do
return e1
umountDevice :: FilePath -> IO ExitCode
umountDevice path = do
e <- tryCommand ("umount " ++ path)
case e of
ExitSuccess -> do
removeEmptyDirectory path
return e
ExitFailure a -> do
return e
-- path to content files
defaultStaticPrefix :: FilePath -> FilePath -> String
defaultStaticPrefix base path = (base ++ "/static/" ++ path)
| Jon0/status | src/File.hs | gpl-3.0 | 7,655 | 0 | 20 | 1,938 | 2,555 | 1,268 | 1,287 | 222 | 7 |
{- Merch.Race.MapGen.Settlement - Generates settlements and the road network.
Copyright 2013 Alan Manuel K. Gloria
This file is part of Merchant's Race.
Merchant's Race 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.
Merchant's Race 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 Merchant's Race. If not, see <http://www.gnu.org/licenses/>.
-}
{- Generate settlements and roads. -}
module Merch.Race.MapGen.Settlement
( drawSettlement
) where
import Merch.Race.Data
import Merch.Race.Hex
import Merch.Race.MapGen.Monad
import Merch.Race.MapGen.Substep
import Control.Monad
import Data.Graph.AStar
import Data.Ix
import Data.List
import qualified Data.Map as Map
import Data.Map(Map)
import Data.Ratio
import qualified Data.Set as Set
import Data.Set(Set)
pickName :: MapGenM m => NameGenerator -> m String
pickName (NGString s) = return s
pickName (NGConcat ngs) = do
names <- mapM pickName ngs
return $ concat names
pickName (NGDistribute ngis) = do
let total = sum $ map snd ngis
ri <- mgRandom
let i = abs ri `mod` total
findLoop i ((ng, n):ngis)
| i < n = ng
| otherwise = findLoop (i - n) ngis
pickName $ findLoop i ngis
loop :: MapGenM m
=> NameGenerator -- Name generator.
-> Int -- Total number of settlements to generate.
-> Map Settlement HexCoord -- Map of already-generated settlements.
-> Map Terrain (Set HexCoord) -- Terrain locations.
-> Int -- Number of generated settlements.
-> [SettlementType] -- List of settlement types to generate.
-> m [(Settlement, HexCoord)]
loop ng total = core
where
core done tm numGen [] = mgProgress 1 >> (return $ Map.toList done)
core done tm numGen (st:sts) = do
mgProgress $ fromIntegral numGen % fromIntegral total
-- Look for candidate locations
ts <- mgRequiredTerrain st
let hs = concatMap (Set.toList . maybe Set.empty id . flip Map.lookup tm) ts
lengthHs = length hs
-- Select a candidate location.
ri <- mgRandom
let i = abs ri `mod` lengthHs
h = hs !! i
-- Pick a name.
let pickloop = do
name <- pickName ng
let settlement = Settlement name
if Map.member settlement done
then pickloop
else return settlement
s <- pickloop
-- Place the item.
mgAddSettlement s st h
let done' = Map.insert s h done
-- Create a road if needed.
when (not $ Map.null done) $ do
-- Select a random, already-done settlement.
let sizeDone = Map.size done
ri <- mgRandom
let i = abs ri `mod` sizeDone
(s2, h2) = Map.toList done !! i
-- Get the path to its location.
let neighborM h = do
let ns = neighbors h
ns' <- filterM (\n -> do t <- mgGetTerrain n
return $ not $ any (==t) [Sea,Freshwater])
ns
return $ Set.fromList ns'
movecost :: Terrain -> Rational
movecost Sea = 100000
movecost Freshwater = 100000
movecost Coast = 10
movecost Plains = 1.7
movecost Forest = 5
movecost Hill = 5.5
movecost Mountain = 7
movecostM h1 h2 = do
-- For road to road, only 1
r1 <- mgGetRoad h1
r2 <- mgGetRoad h2
if r1 && r2
then return 1
else do
-- Use the larger movement cost.
t1 <- mgGetTerrain h1
t2 <- mgGetTerrain h2
-- Adjust movement costs if going
-- to a tile that is different y-coord
-- in offset coordinates
let (_, y1) = toOffset h1
(_, y2) = toOffset h2
(c1, c2) = (movecost t1, movecost t2)
(c1', c2')
| y1 == y2 = (c1, c2)
| otherwise = (c1 * 1.05, c2 * 1.05)
return $ max c1' c2'
Just roads <- aStarM
neighborM
movecostM
(return . fromIntegral . distance h)
(return . (==h))
(return h2)
-- Fill in roads
mapM_ (flip mgPutRoad True) roads
mgPutRoad h True
mgPutRoad h2 True
-- Disallow tiles within 5 tiles of the selected tile.
let disalloweds = Set.fromList $ nearby 5 h
tm' = Map.map (Set.\\ disalloweds) tm
core done' tm' (numGen+1) sts
drawSettlement :: MapGenM m => m [(Settlement, HexCoord)]
drawSettlement = do
-- First collect the terrains.
mgStep "Preparing settlement generation"
b <- mgMapBounds
let total = fromIntegral $ rangeSize b
ths <- substep 0.00 0.10 $ forM (zip [0..] $ range b) $ \ (i, h) -> do
mgProgress $ i % total
t <- mgGetTerrain h
return (t,Set.singleton h)
let tm = foldl' (flip $ uncurry $ Map.insertWith Set.union) Map.empty ths
mgStep "Placing settlements"
ng <- mgNameGenerator
ists <- mgSettlementGenerator
let sts = concatMap (uncurry replicate) ists
total = length sts
substep 0.10 0.90 $ loop ng total Map.empty tm 0 sts
| AmkG/merchants-race | Merch/Race/MapGen/Settlement.hs | gpl-3.0 | 5,772 | 5 | 21 | 1,944 | 1,468 | 733 | 735 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Query.Field
( getDistinctFieldQuery
, getDistinctFieldLikeQuery
, getDistinctAlgorithmVersionQuery
) where
import Data.Proxy (Proxy(Proxy))
import Data.String.Interpolate.IsString (i)
import qualified Database.Persist.Sqlite as Sqlite
import Core
import Query
import Schema
import Sql.Core (MonadSql, PersistFieldSql, Transaction(..), SqlRecord)
import qualified Sql.Core as Sql
getDistinctFieldQuery
:: forall a m rec
. (MonadResource m, MonadSql m, PersistFieldSql a, SqlRecord rec)
=> EntityField rec a
-> m (Query a)
getDistinctFieldQuery entityField = Sql.runTransaction $ do
table <- Transaction $ Sqlite.getTableName (undefined :: rec)
field <- Transaction $ Sqlite.getFieldName entityField
let queryText = [i|SELECT DISTINCT #{table}.#{field} FROM #{table}|]
return Query{convert = Simple converter, ..}
where
queryName :: Text
queryName = "distinctFieldQuery"
commonTableExpressions :: [CTE]
commonTableExpressions = []
params :: [PersistValue]
params = []
converter
:: (MonadIO n, MonadLogger n, MonadThrow n)
=> [PersistValue] -> n a
converter [v] | Right val <- Sqlite.fromPersistValue v = return val
converter actualValues = logThrowM $ QueryResultUnparseable actualValues
[Sqlite.sqlType (Proxy :: Proxy a)]
getDistinctFieldLikeQuery
:: forall a m rec
. (MonadResource m, MonadSql m, PersistFieldSql a, SqlRecord rec)
=> EntityField rec a
-> Text
-> m (Query a)
getDistinctFieldLikeQuery entityField txt = Sql.runTransaction $ do
table <- Transaction $ Sqlite.getTableName (undefined :: rec)
field <- Transaction $ Sqlite.getFieldName entityField
let queryText = [i|
SELECT DISTINCT #{table}.#{field}
FROM #{table}
WHERE #{table}.#{field} LIKE (? || '%')
|]
return Query{convert = Simple converter, ..}
where
queryName :: Text
queryName = "distinctFieldLikeQuery"
commonTableExpressions :: [CTE]
commonTableExpressions = []
params :: [PersistValue]
params = [ toPersistValue txt]
converter
:: (MonadIO n, MonadLogger n, MonadThrow n)
=> [PersistValue] -> n a
converter [v] | Right val <- Sqlite.fromPersistValue v = return val
converter actualValues = logThrowM $ QueryResultUnparseable actualValues
[Sqlite.sqlType (Proxy :: Proxy a)]
getDistinctAlgorithmVersionQuery
:: Key Algorithm -> Maybe Text -> Query CommitId
getDistinctAlgorithmVersionQuery algoId prefix = Query
{ queryName = "distinctAlgorithmVersionQuery"
, commonTableExpressions = []
, params =
[ toPersistValue algoId
, toPersistValue prefix
, toPersistValue prefix
]
, queryText = [i|
SELECT DISTINCT algorithmVersion
FROM RunConfig
WHERE algorithmId = ? AND (algorithmVersion LIKE (? || '%') OR ? IS NULL)
|]
, convert = Simple converter
, ..
}
where
converter
:: (MonadIO n, MonadLogger n, MonadThrow n)
=> [PersistValue] -> n CommitId
converter [v] | Right val <- Sqlite.fromPersistValue v = return val
converter actualValues = logThrowM $ QueryResultUnparseable actualValues
[Sqlite.sqlType (Proxy :: Proxy CommitId)]
| merijn/GPU-benchmarks | benchmark-analysis/src/Query/Field.hs | gpl-3.0 | 3,388 | 0 | 12 | 714 | 877 | 472 | 405 | 80 | 2 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-|
This module exports routes for all the files in the static directory at
compile time, allowing compile-time verification that referenced files
exist. However, any files added during run-time can't be accessed this
way; use their FilePath or URL to access them.
This is a separate module to satisfy template haskell requirements.
-}
module StaticFiles where
import Yesod.Helpers.Static
import Settings (staticdir)
$(staticFiles staticdir)
| trygvis/hledger | hledger-web/StaticFiles.hs | gpl-3.0 | 509 | 0 | 7 | 76 | 30 | 18 | 12 | 5 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdSense.Accounts.Alerts.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all the alerts available in an account.
--
-- /See:/ <http://code.google.com/apis/adsense/management/ AdSense Management API Reference> for @adsense.accounts.alerts.list@.
module Network.Google.Resource.AdSense.Accounts.Alerts.List
(
-- * REST Resource
AccountsAlertsListResource
-- * Creating a Request
, accountsAlertsList
, AccountsAlertsList
-- * Request Lenses
, aalParent
, aalXgafv
, aalLanguageCode
, aalUploadProtocol
, aalAccessToken
, aalUploadType
, aalCallback
) where
import Network.Google.AdSense.Types
import Network.Google.Prelude
-- | A resource alias for @adsense.accounts.alerts.list@ method which the
-- 'AccountsAlertsList' request conforms to.
type AccountsAlertsListResource =
"v2" :>
Capture "parent" Text :>
"alerts" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "languageCode" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListAlertsResponse
-- | Lists all the alerts available in an account.
--
-- /See:/ 'accountsAlertsList' smart constructor.
data AccountsAlertsList =
AccountsAlertsList'
{ _aalParent :: !Text
, _aalXgafv :: !(Maybe Xgafv)
, _aalLanguageCode :: !(Maybe Text)
, _aalUploadProtocol :: !(Maybe Text)
, _aalAccessToken :: !(Maybe Text)
, _aalUploadType :: !(Maybe Text)
, _aalCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsAlertsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aalParent'
--
-- * 'aalXgafv'
--
-- * 'aalLanguageCode'
--
-- * 'aalUploadProtocol'
--
-- * 'aalAccessToken'
--
-- * 'aalUploadType'
--
-- * 'aalCallback'
accountsAlertsList
:: Text -- ^ 'aalParent'
-> AccountsAlertsList
accountsAlertsList pAalParent_ =
AccountsAlertsList'
{ _aalParent = pAalParent_
, _aalXgafv = Nothing
, _aalLanguageCode = Nothing
, _aalUploadProtocol = Nothing
, _aalAccessToken = Nothing
, _aalUploadType = Nothing
, _aalCallback = Nothing
}
-- | Required. The account which owns the collection of alerts. Format:
-- accounts\/{account}
aalParent :: Lens' AccountsAlertsList Text
aalParent
= lens _aalParent (\ s a -> s{_aalParent = a})
-- | V1 error format.
aalXgafv :: Lens' AccountsAlertsList (Maybe Xgafv)
aalXgafv = lens _aalXgafv (\ s a -> s{_aalXgafv = a})
-- | The language to use for translating alert messages. If unspecified, this
-- defaults to the user\'s display language. If the given language is not
-- supported, alerts will be returned in English. The language is specified
-- as an [IETF BCP-47 language
-- code](https:\/\/en.wikipedia.org\/wiki\/IETF_language_tag).
aalLanguageCode :: Lens' AccountsAlertsList (Maybe Text)
aalLanguageCode
= lens _aalLanguageCode
(\ s a -> s{_aalLanguageCode = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aalUploadProtocol :: Lens' AccountsAlertsList (Maybe Text)
aalUploadProtocol
= lens _aalUploadProtocol
(\ s a -> s{_aalUploadProtocol = a})
-- | OAuth access token.
aalAccessToken :: Lens' AccountsAlertsList (Maybe Text)
aalAccessToken
= lens _aalAccessToken
(\ s a -> s{_aalAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aalUploadType :: Lens' AccountsAlertsList (Maybe Text)
aalUploadType
= lens _aalUploadType
(\ s a -> s{_aalUploadType = a})
-- | JSONP
aalCallback :: Lens' AccountsAlertsList (Maybe Text)
aalCallback
= lens _aalCallback (\ s a -> s{_aalCallback = a})
instance GoogleRequest AccountsAlertsList where
type Rs AccountsAlertsList = ListAlertsResponse
type Scopes AccountsAlertsList =
'["https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"]
requestClient AccountsAlertsList'{..}
= go _aalParent _aalXgafv _aalLanguageCode
_aalUploadProtocol
_aalAccessToken
_aalUploadType
_aalCallback
(Just AltJSON)
adSenseService
where go
= buildClient
(Proxy :: Proxy AccountsAlertsListResource)
mempty
| brendanhay/gogol | gogol-adsense/gen/Network/Google/Resource/AdSense/Accounts/Alerts/List.hs | mpl-2.0 | 5,355 | 0 | 17 | 1,241 | 787 | 460 | 327 | 115 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.CreateSnapshot
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a snapshot of an EBS volume and stores it in Amazon S3. You can
-- use snapshots for backups, to make copies of EBS volumes, and to save
-- data before shutting down an instance.
--
-- When a snapshot is created, any AWS Marketplace product codes that are
-- associated with the source volume are propagated to the snapshot.
--
-- You can take a snapshot of an attached volume that is in use. However,
-- snapshots only capture data that has been written to your EBS volume at
-- the time the snapshot command is issued; this may exclude any data that
-- has been cached by any applications or the operating system. If you can
-- pause any file systems on the volume long enough to take a snapshot,
-- your snapshot should be complete. However, if you cannot pause all file
-- writes to the volume, you should unmount the volume from within the
-- instance, issue the snapshot command, and then remount the volume to
-- ensure a consistent and complete snapshot. You may remount and use your
-- volume while the snapshot status is 'pending'.
--
-- To create a snapshot for EBS volumes that serve as root devices, you
-- should stop the instance before taking the snapshot.
--
-- Snapshots that are taken from encrypted volumes are automatically
-- encrypted. Volumes that are created from encrypted snapshots are also
-- automatically encrypted. Your encrypted volumes and any associated
-- snapshots always remain protected.
--
-- For more information, see
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html Amazon Elastic Block Store>
-- and
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html Amazon EBS Encryption>
-- in the /Amazon Elastic Compute Cloud User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html AWS API Reference> for CreateSnapshot.
module Network.AWS.EC2.CreateSnapshot
(
-- * Creating a Request
createSnapshot
, CreateSnapshot
-- * Request Lenses
, ccDescription
, ccDryRun
, ccVolumeId
-- * Destructuring the Response
, snapshot
, Snapshot
-- * Response Lenses
, sStateMessage
, sOwnerAlias
, sDataEncryptionKeyId
, sKMSKeyId
, sTags
, sSnapshotId
, sOwnerId
, sVolumeId
, sVolumeSize
, sDescription
, sStartTime
, sProgress
, sState
, sEncrypted
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createSnapshot' smart constructor.
data CreateSnapshot = CreateSnapshot'
{ _ccDescription :: !(Maybe Text)
, _ccDryRun :: !(Maybe Bool)
, _ccVolumeId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateSnapshot' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccDescription'
--
-- * 'ccDryRun'
--
-- * 'ccVolumeId'
createSnapshot
:: Text -- ^ 'ccVolumeId'
-> CreateSnapshot
createSnapshot pVolumeId_ =
CreateSnapshot'
{ _ccDescription = Nothing
, _ccDryRun = Nothing
, _ccVolumeId = pVolumeId_
}
-- | A description for the snapshot.
ccDescription :: Lens' CreateSnapshot (Maybe Text)
ccDescription = lens _ccDescription (\ s a -> s{_ccDescription = a});
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
ccDryRun :: Lens' CreateSnapshot (Maybe Bool)
ccDryRun = lens _ccDryRun (\ s a -> s{_ccDryRun = a});
-- | The ID of the EBS volume.
ccVolumeId :: Lens' CreateSnapshot Text
ccVolumeId = lens _ccVolumeId (\ s a -> s{_ccVolumeId = a});
instance AWSRequest CreateSnapshot where
type Rs CreateSnapshot = Snapshot
request = postQuery eC2
response = receiveXML (\ s h x -> parseXML x)
instance ToHeaders CreateSnapshot where
toHeaders = const mempty
instance ToPath CreateSnapshot where
toPath = const "/"
instance ToQuery CreateSnapshot where
toQuery CreateSnapshot'{..}
= mconcat
["Action" =: ("CreateSnapshot" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"Description" =: _ccDescription,
"DryRun" =: _ccDryRun, "VolumeId" =: _ccVolumeId]
| olorin/amazonka | amazonka-ec2/gen/Network/AWS/EC2/CreateSnapshot.hs | mpl-2.0 | 5,258 | 0 | 11 | 1,083 | 564 | 355 | 209 | 76 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudSearch.Debug.Identitysources.Items.ListForunmAppedidentity
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists names of items associated with an unmapped identity. **Note:**
-- This API requires an admin account to execute.
--
-- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.debug.identitysources.items.listForunmappedidentity@.
module Network.Google.Resource.CloudSearch.Debug.Identitysources.Items.ListForunmAppedidentity
(
-- * REST Resource
DebugIdentitysourcesItemsListForunmAppedidentityResource
-- * Creating a Request
, debugIdentitysourcesItemsListForunmAppedidentity
, DebugIdentitysourcesItemsListForunmAppedidentity
-- * Request Lenses
, diilfaUserResourceName
, diilfaParent
, diilfaXgafv
, diilfaUploadProtocol
, diilfaGroupResourceName
, diilfaAccessToken
, diilfaUploadType
, diilfaDebugOptionsEnableDebugging
, diilfaPageToken
, diilfaPageSize
, diilfaCallback
) where
import Network.Google.CloudSearch.Types
import Network.Google.Prelude
-- | A resource alias for @cloudsearch.debug.identitysources.items.listForunmappedidentity@ method which the
-- 'DebugIdentitysourcesItemsListForunmAppedidentity' request conforms to.
type DebugIdentitysourcesItemsListForunmAppedidentityResource
=
"v1" :>
"debug" :>
Capture "parent" Text :>
"items:forunmappedidentity" :>
QueryParam "userResourceName" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "groupResourceName" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "debugOptions.enableDebugging" Bool :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
ListItemNamesForUnmAppedIdentityResponse
-- | Lists names of items associated with an unmapped identity. **Note:**
-- This API requires an admin account to execute.
--
-- /See:/ 'debugIdentitysourcesItemsListForunmAppedidentity' smart constructor.
data DebugIdentitysourcesItemsListForunmAppedidentity =
DebugIdentitysourcesItemsListForunmAppedidentity'
{ _diilfaUserResourceName :: !(Maybe Text)
, _diilfaParent :: !Text
, _diilfaXgafv :: !(Maybe Xgafv)
, _diilfaUploadProtocol :: !(Maybe Text)
, _diilfaGroupResourceName :: !(Maybe Text)
, _diilfaAccessToken :: !(Maybe Text)
, _diilfaUploadType :: !(Maybe Text)
, _diilfaDebugOptionsEnableDebugging :: !(Maybe Bool)
, _diilfaPageToken :: !(Maybe Text)
, _diilfaPageSize :: !(Maybe (Textual Int32))
, _diilfaCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DebugIdentitysourcesItemsListForunmAppedidentity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'diilfaUserResourceName'
--
-- * 'diilfaParent'
--
-- * 'diilfaXgafv'
--
-- * 'diilfaUploadProtocol'
--
-- * 'diilfaGroupResourceName'
--
-- * 'diilfaAccessToken'
--
-- * 'diilfaUploadType'
--
-- * 'diilfaDebugOptionsEnableDebugging'
--
-- * 'diilfaPageToken'
--
-- * 'diilfaPageSize'
--
-- * 'diilfaCallback'
debugIdentitysourcesItemsListForunmAppedidentity
:: Text -- ^ 'diilfaParent'
-> DebugIdentitysourcesItemsListForunmAppedidentity
debugIdentitysourcesItemsListForunmAppedidentity pDiilfaParent_ =
DebugIdentitysourcesItemsListForunmAppedidentity'
{ _diilfaUserResourceName = Nothing
, _diilfaParent = pDiilfaParent_
, _diilfaXgafv = Nothing
, _diilfaUploadProtocol = Nothing
, _diilfaGroupResourceName = Nothing
, _diilfaAccessToken = Nothing
, _diilfaUploadType = Nothing
, _diilfaDebugOptionsEnableDebugging = Nothing
, _diilfaPageToken = Nothing
, _diilfaPageSize = Nothing
, _diilfaCallback = Nothing
}
diilfaUserResourceName :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaUserResourceName
= lens _diilfaUserResourceName
(\ s a -> s{_diilfaUserResourceName = a})
-- | The name of the identity source, in the following format:
-- identitysources\/{source_id}}
diilfaParent :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity Text
diilfaParent
= lens _diilfaParent (\ s a -> s{_diilfaParent = a})
-- | V1 error format.
diilfaXgafv :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Xgafv)
diilfaXgafv
= lens _diilfaXgafv (\ s a -> s{_diilfaXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
diilfaUploadProtocol :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaUploadProtocol
= lens _diilfaUploadProtocol
(\ s a -> s{_diilfaUploadProtocol = a})
diilfaGroupResourceName :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaGroupResourceName
= lens _diilfaGroupResourceName
(\ s a -> s{_diilfaGroupResourceName = a})
-- | OAuth access token.
diilfaAccessToken :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaAccessToken
= lens _diilfaAccessToken
(\ s a -> s{_diilfaAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
diilfaUploadType :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaUploadType
= lens _diilfaUploadType
(\ s a -> s{_diilfaUploadType = a})
-- | If you are asked by Google to help with debugging, set this field.
-- Otherwise, ignore this field.
diilfaDebugOptionsEnableDebugging :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Bool)
diilfaDebugOptionsEnableDebugging
= lens _diilfaDebugOptionsEnableDebugging
(\ s a -> s{_diilfaDebugOptionsEnableDebugging = a})
-- | The next_page_token value returned from a previous List request, if any.
diilfaPageToken :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaPageToken
= lens _diilfaPageToken
(\ s a -> s{_diilfaPageToken = a})
-- | Maximum number of items to fetch in a request. Defaults to 100.
diilfaPageSize :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Int32)
diilfaPageSize
= lens _diilfaPageSize
(\ s a -> s{_diilfaPageSize = a})
. mapping _Coerce
-- | JSONP
diilfaCallback :: Lens' DebugIdentitysourcesItemsListForunmAppedidentity (Maybe Text)
diilfaCallback
= lens _diilfaCallback
(\ s a -> s{_diilfaCallback = a})
instance GoogleRequest
DebugIdentitysourcesItemsListForunmAppedidentity
where
type Rs
DebugIdentitysourcesItemsListForunmAppedidentity
= ListItemNamesForUnmAppedIdentityResponse
type Scopes
DebugIdentitysourcesItemsListForunmAppedidentity
=
'["https://www.googleapis.com/auth/cloud_search",
"https://www.googleapis.com/auth/cloud_search.debug"]
requestClient
DebugIdentitysourcesItemsListForunmAppedidentity'{..}
= go _diilfaParent _diilfaUserResourceName
_diilfaXgafv
_diilfaUploadProtocol
_diilfaGroupResourceName
_diilfaAccessToken
_diilfaUploadType
_diilfaDebugOptionsEnableDebugging
_diilfaPageToken
_diilfaPageSize
_diilfaCallback
(Just AltJSON)
cloudSearchService
where go
= buildClient
(Proxy ::
Proxy
DebugIdentitysourcesItemsListForunmAppedidentityResource)
mempty
| brendanhay/gogol | gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Debug/Identitysources/Items/ListForunmAppedidentity.hs | mpl-2.0 | 8,722 | 0 | 22 | 1,922 | 1,128 | 649 | 479 | 172 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Examples.Radio(radio) where
import Development.NSIS
import Development.NSIS.Plugins.EnvVarUpdate
import Development.NSIS.Plugins.Sections
radio = do
name "Radio"
outFile "radio.exe"
installDir "$DESKTOP/Radio"
requestExecutionLevel User
-- page Directory
page Components
page InstFiles
section "Core files" [Required] $ do
setOutPath "$INSTDIR"
file [] "Examples/Radio.hs"
local <- section "Add to user %PATH%" [] $ do
setEnvVarPrepend HKCU "PATH" "$INSTDIR"
global <- section "Add to system %PATH%" [] $ do
setEnvVarPrepend HKLM "PATH" "$INSTDIR"
atMostOneSection [local,global]
a <- section "I like Marmite" [] $ return ()
b <- section "I hate Marmite" [] $ return ()
c <- section "I don't care" [] $ return ()
exactlyOneSection [a,b,c]
| idleberg/NSIS | Examples/Radio.hs | apache-2.0 | 881 | 0 | 11 | 204 | 256 | 118 | 138 | 24 | 1 |
-- 510510
import Euler(allPrimes)
nn = 1000000
-- maximize n / phi(n) by finding minimal phi(n)
-- more factors => lower phi number
-- more prime factors => even lower phi number (can build more divisors)
-- if x mod n == 0 then phi(x) = phi(x*n)
-- since there is a single maximum, just multiply by primes
findMaxRatio n = last $ takeWhile (n>=) genMinTotient
where genMinTotient = map (product . flip take allPrimes) [1..]
main = putStrLn $ show $ findMaxRatio nn
| higgsd/euler | hs/69.hs | bsd-2-clause | 473 | 2 | 8 | 91 | 91 | 47 | 44 | 5 | 1 |
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Storage.WebDAV.Type
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : GPL-3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- WebDAV storage IO types
--
-----------------------------------------------------------------------------
module HEP.Storage.WebDAV.Type where
import Data.Typeable
import Data.Data
-- |
data URLtype = LocalURL FilePath
| GlobalURL String
deriving (Show)
-- |
data WebDAVProgram = UseCurl (Maybe FilePath)
-- | Cadaver (Maybe FilePath)
-- |
data Credential = CredDigest String String | NoCred
-- |
data WebDAVConfig = WebDAVConfig { webdav_credential :: Credential
, webdav_baseurl :: String
}
data WebDAVRemoteDir = WebDAVRemoteDir { webdav_remotedir :: FilePath }
deriving (Show, Typeable, Data)
data WebDAVCommand = Download | Upload
deriving (Show, Typeable, Data)
| wavewave/webdav-manager | src/HEP/Storage/WebDAV/Type.hs | bsd-2-clause | 1,173 | 0 | 8 | 281 | 163 | 103 | 60 | 15 | 0 |
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2012-2013
-- License : BSD3
-- Maintainer: Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Ermine.Parser.Keywords where
import Data.HashSet
import Data.Monoid
-- | This is the set of keywords that can only occur at the beginning of the line for auto-completion purposes.
startingKeywords :: HashSet String
startingKeywords = fromList
[ "abstract"
, "class"
, "data"
, "database"
, "export"
, "field"
, "foreign"
, "import"
, "instance"
, "private"
, "type"
]
-- | This is the set of keywords that can occur anywhere on the line for auto-completion purposes.
otherKeywords :: HashSet String
otherKeywords = fromList
[ "case"
, "constraint"
, "constructor"
, "do"
, "exists"
, "forall"
, "hole"
, "in"
, "infix"
, "infixl"
, "infixr"
, "let"
, "of"
, "phi"
, "postfix"
, "prefix"
, "rho"
, "subtype"
, "table"
, "where"
, "_"
, "Γ"
, "ρ"
, "φ"
]
-- | The set of all keywords.
--
-- @'keywords' = 'startingKeywords' '<>' 'otherKeywords'@
keywords :: HashSet String
keywords = startingKeywords <> otherKeywords
| ekmett/ermine | src/Ermine/Parser/Keywords.hs | bsd-2-clause | 1,333 | 0 | 6 | 270 | 185 | 120 | 65 | 44 | 1 |
-- 8319823
import Data.Function(on)
import Data.List(minimumBy, sort)
import Euler(allPrimes, intSqrt, toDigitsBase)
nn = 10^7
-- minimize n / phi(n) by finding maximal phi(n)
-- fewer factors => higher phi number, so build n from two primes
-- only check primes within +/- order of magnitude of sqrt(n)
totientPerms n = [(x,p) | a <- aPrimes, b <- bPrimes a,
let x = a*b, let p = (a-1)*(b-1), isPerm x p]
where q = intSqrt n
aPrimes = takeWhile (q>) $ dropWhile (q `div` 10>) allPrimes
bPrimes a = takeWhile (n `div` a>) $ dropWhile (a>) allPrimes
isPerm a b = permSort a == permSort b
permSort x = sort $ toDigitsBase 10 x
bestPerm n = fst $ minimumBy (compare `on` phiRatio) $ totientPerms n
where phiRatio (x,p) = fromIntegral x / fromIntegral p
main = putStrLn $ show $ bestPerm nn
| higgsd/euler | hs/70.hs | bsd-2-clause | 865 | 8 | 12 | 220 | 330 | 173 | 157 | 14 | 1 |
module Data.Blockchain.Types.BlockchainSpec (spec) where
import TestUtil
import qualified Control.Arrow as Arrow
import qualified Data.Aeson as Aeson
import qualified Data.HashMap.Strict as H
import qualified Data.List.NonEmpty as NonEmpty
import Data.Blockchain
spec :: Spec
spec = describe "Data.Blockchain.Blockchain" $ do
it "should serialize and validate round-trip" $ ioProperty $ do
chain <- blockchain3Block
let unverifiedBlockchain = throwLeft $ Aeson.eitherDecode (Aeson.encode chain)
return $ validate unverifiedBlockchain === Right chain
describe "validate" $ do
it "should reject a chain with invalid difficulty reference in genesis block" $ ioProperty $ do
chain <- singletonBlockchainUnvalidated
let config = (blockchainConfig chain) { initialDifficulty = minBound }
chain' = construct config (blockchainNode chain)
return $ validate chain' === Left (BlockValidationException InvalidDifficultyReference)
it "should reject a chain with invalid genesis block difficulty" $ ioProperty $ do
chain <- singletonBlockchainUnvalidated
let (BlockchainNode block nodes) = blockchainNode chain
blockHeader' = (blockHeader block) { nonce = 1 }
block' = block { blockHeader = blockHeader' }
chain' = construct (blockchainConfig chain) (BlockchainNode block' nodes)
return $ validate chain' === Left (BlockValidationException InvalidDifficulty)
prop "should reject a chain with transactions in genesis block" $ once $
\tx -> ioProperty $ do
chain <- singletonBlockchainUnvalidated
let (BlockchainNode block nodes) = blockchainNode chain
block' = block { transactions = pure tx }
chain' = construct (blockchainConfig chain) (BlockchainNode block' nodes)
return $ validate chain' === Left GenesisBlockHasTransactions
prop "should reject a chain with invalid coinbase reward in genesis block" $ once $
\txOut -> ioProperty $ do
chain <- singletonBlockchainUnvalidated
let (BlockchainNode block nodes) = blockchainNode chain
coinbase = CoinbaseTransaction $ pure $ txOut { value = 999 }
block' = block { coinbaseTransaction = coinbase }
chain' = construct (blockchainConfig chain) (BlockchainNode block' nodes)
return $ validate chain' === Left (BlockValidationException InvalidCoinbaseTransactionValue)
prop "should reject a chain with invalid coinbase hash in genesis block header" $ once $
\txOut -> ioProperty $ do
chain <- singletonBlockchainUnvalidated
let (BlockchainNode block nodes) = blockchainNode chain
coinbase = CoinbaseTransaction $ pure $ txOut { value = 100 }
block' = block { coinbaseTransaction = coinbase }
chain' = construct (blockchainConfig chain) (BlockchainNode block' nodes)
return $ validate chain' === Left (BlockValidationException InvalidCoinbaseTransactionHash)
-- TODO: test if possible, hard to do with empty transaction rule & expected header hash
-- prop "should reject a chain with invalid transaction hash in genesis block header" $
describe "addBlock" $ do
-- Note: adding valid blocks is already tested by generating by loading test data
-- prop "should add a valid block" ...
it "should reject a duplicate block" $ ioProperty $ do
blockchain <- blockchain1Block
block <- block1A
return $ addBlock block blockchain === Left BlockAlreadyExists
it "should reject a block without a parent" $ ioProperty $ do
blockchain <- singletonBlockchain
block <- block2A
return $ addBlock block blockchain === Left NoParentFound
it "should reject a block with invalid genesis block difficulty" $ ioProperty $ do
blockchain <- blockchain1Block
(Block header coinbase txs) <- block2A
let header' = header { nonce = 1 }
block = Block header' coinbase txs
return $ addBlock block blockchain === Left InvalidDifficulty
prop "should reject a block with invalid coinbase reward in block" $ once $
\txOut -> ioProperty $ do
blockchain <- blockchain1Block
(Block header _coinbase txs) <- block2A
let coinbase = CoinbaseTransaction $ pure $ txOut { value = 999 }
block = Block header coinbase txs
return $ addBlock block blockchain === Left InvalidCoinbaseTransactionValue
prop "should reject a block with invalid coinbase hash in block header" $ once $
\txOut -> ioProperty $ do
blockchain <- blockchain1Block
(Block header _coinbase txs) <- block2A
let coinbase = CoinbaseTransaction $ pure $ txOut { value = 100 }
block = Block header coinbase txs
return $ addBlock block blockchain === Left InvalidCoinbaseTransactionHash
-- prop "should reject a block with invalid transaction hash in block header" $
-- \tx -> ioProperty $ do
-- (blockchain, block) <- loadVerifiedTestBlockchainWithValidBlock
-- let block' = block { transactions = pure tx }
--
-- return $ addBlock block' blockchain === Left InvalidTransactionHashTreeRoot
prop "should reject a block with an invalid transaction out ref" $ once $
\txOutRef -> ioProperty $ do
blockchain <- blockchain1Block
(Block header coinbase txs) <- block2A
let (Transaction txIn txOut) = head txs
txIn' = pure $ (NonEmpty.head txIn) { transactionOutRef = txOutRef }
block = Block header coinbase $ pure $ Transaction txIn' txOut
return $ addBlock block blockchain === Left TransactionOutRefNotFound
prop "should reject a block with an invalid transaction signature" $ once $
\sig -> ioProperty $ do
blockchain <- blockchain1Block
(Block header coinbase txs) <- block2A
putStrLn "testing"
let (Transaction txIn txOut) = head txs
txIn' = pure $ (NonEmpty.head txIn) { signature = sig }
block = Block header coinbase $ pure $ Transaction txIn' txOut
return $ addBlock block blockchain === Left InvalidTransactionSignature
it "should reject a block with an invalid transaction value" $ ioProperty $ do
blockchain <- blockchain1Block
(Block header coinbase txs) <- block2A
let (Transaction txIn txOut) = head txs
txOut' = pure $ (NonEmpty.head txOut) { value = 999 }
block = Block header coinbase $ pure $ Transaction txIn txOut'
return $ addBlock block blockchain === Left InvalidTransactionValues
-- TODO: test
-- prop "should reject a block with a duplicate transaction" $ ioProperty $ do
describe "addressValues" $
it "should calculate unspent transaction outputs" $ ioProperty $ do
blockchain <- blockchain3Block
return $ showKeys (addressValues blockchain) === H.fromList
-- genesis coinbase, value can never be spent
[ ("8330da21047df515590bc752ac27210d3eb11bc1ec1b4dcb8f6c6b0b018fb5d44feb11798ca599b0c1549146508933833c4553d420504bef2c5f96dd42e143df", 100)
-- mined 1st and 2nd block, spent 90 of 1st block coinbase
, ("74bbe6d5f70f7d7e433b9b6d5d77a391492cc93161d9f108cef18d64959930cf1d55ef0844c0607f5568d1cd9233995154b5758915eb595e1dee472d13a18517", 110)
-- received 90 of 1st block coinbase
, ("c21609f09388037802a7c58e8135e264e8f4bac3354ee300ee73b887a7976a94614e77bcec828579562b9b3c0ac6f0de7323f3f5bcfdb3dfb190cfca1692d735", 90)
]
describe "flatten" $
it "should flatten the blockchain" $ ioProperty $ do
blockchain <- blockchain3Block
b0 <- genesisBlock
b1a <- block1A
b1b <- block1B
b2a <- block2A
return $ flatten blockchain === NonEmpty.fromList
[ NonEmpty.fromList [b0, b1b]
, NonEmpty.fromList [b0, b1a, b2a]
]
describe "longestChain" $
it "should find the longest chain" $ ioProperty $ do
blockchain <- blockchain1Block
blockchain' <- blockchain2BlockFork
blockchain'' <- blockchain3Block
b0 <- genesisBlock
b1a <- block1A
b2a <- block2A
return $ (longestChain blockchain == NonEmpty.fromList [b0, b1a]) &&
(longestChain blockchain' == NonEmpty.fromList [b0, b1a]) &&
(longestChain blockchain'' == NonEmpty.fromList [b0, b1a, b2a])
showKeys :: Show k => H.HashMap k v -> H.HashMap String v
showKeys = H.fromList . fmap (Arrow.first show) . H.toList
| TGOlson/blockchain | test/Data/Blockchain/Types/BlockchainSpec.hs | bsd-3-clause | 9,752 | 0 | 23 | 3,284 | 1,923 | 934 | 989 | 132 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
module Client.Console where
import Control.Lens ((.=), use, zoom, (^.), ix, preuse, (-=), (+=))
import Control.Monad (void, unless, when, liftM)
import Data.Bits (shiftR, shiftL, (.&.), (.|.), xor)
import Data.Char (ord, chr)
import Data.Maybe (isJust)
import Data.Word (Word8)
import Text.Printf (printf)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Storable.Mutable as MSV
import Game.CVarT
import Client.ClientStateT
import Client.ClientStaticT
import Client.ConsoleT
import Client.RefExportT
import Render.Renderer
import Types
import QuakeState
import CVarVariables
import QCommon.XCommandT
import qualified Constants
import {-# SOURCE #-} qualified Client.SCR as SCR
import {-# SOURCE #-} qualified Game.Cmd as Cmd
import {-# SOURCE #-} qualified QCommon.Com as Com
import qualified QCommon.CVar as CVar
init :: Quake ()
init = do
globals.gCon.cLineWidth .= -1
checkResize
Com.printf "Console initialized.\n"
-- register our commands
void $ CVar.get "con_notifytime" "3" 0
Cmd.addCommand "toggleconsole" (Just toggleConsoleF)
Cmd.addCommand "togglechat" (Just toggleChatF)
Cmd.addCommand "messagemode" (Just messageModeF)
Cmd.addCommand "messagemode2" (Just messageMode2F)
Cmd.addCommand "clear" (Just clearF)
Cmd.addCommand "condump" (Just dumpF)
globals.gCon.cInitialized .= True
-- If the line width has changed, reformat the buffer.
checkResize :: Quake ()
checkResize = do
vidDefWidth <- use $ globals.gVidDef.vdWidth
let w = (vidDefWidth `shiftR` 3) - 2
width = if w > Constants.maxCmdLine
then Constants.maxCmdLine
else w
lineWidth <- use $ globals.gCon.cLineWidth
unless (width == lineWidth) $ do
if width < 1 -- video hasn't been initialized yet
then do
zoom (globals.gCon) $ do
cLineWidth .= 38
cTotalLines .= Constants.conTextSize `div` 38
use (globals.gCon.cText) >>= \text ->
io $ text `MSV.set` ' '
else do
oldWidth <- use $ globals.gCon.cLineWidth
globals.gCon.cLineWidth .= width
let totalLines = Constants.conTextSize `div` width
oldTotalLines <- use $ globals.gCon.cTotalLines
globals.gCon.cTotalLines .= totalLines
let numLines = if totalLines < oldTotalLines
then totalLines
else oldTotalLines
let numChars = if width < oldWidth
then width
else oldWidth
currentLine <- use $ globals.gCon.cCurrent
use (globals.gCon.cText) >>= \text -> do
tbuf <- io $ MSV.clone text
fillInBuf text tbuf oldTotalLines oldWidth currentLine totalLines width 0 0 numLines numChars
clearNotify
totalLines <- use $ globals.gCon.cTotalLines
globals.gCon.cCurrent .= totalLines - 1
globals.gCon.cDisplay .= totalLines - 1
where fillInBuf :: MSV.IOVector Char -> MSV.IOVector Char -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Quake ()
fillInBuf text tbuf oldTotalLines oldWidth currentLine totalLines lineWidth i j maxI maxJ
| i >= maxI = return ()
| j >= maxJ = fillInBuf text tbuf oldTotalLines oldWidth currentLine totalLines lineWidth (i + 1) 0 maxI maxJ
| otherwise = do
let idx = (totalLines - 1 - i) * lineWidth + j
idx2 = ((currentLine - i + oldTotalLines) `mod` oldTotalLines) * oldWidth + j
io $ tbuf `MSV.read` idx2 >>= MSV.write text idx
fillInBuf text tbuf oldTotalLines oldWidth currentLine totalLines lineWidth i (j + 1) maxI maxJ
toggleConsoleF :: XCommandT
toggleConsoleF =
XCommandT "Console.toggleConsoleF" (do
io (putStrLn "Console.toggleConsoleF") >> undefined -- TODO
)
toggleChatF :: XCommandT
toggleChatF =
XCommandT "Console.toggleChatF" (do
io (putStrLn "Console.toggleChatF") >> undefined -- TODO
)
messageModeF :: XCommandT
messageModeF =
XCommandT "Console.messageModeF" (do
globals.gChatTeam .= False
globals.gCls.csKeyDest .= Constants.keyMessage
)
messageMode2F :: XCommandT
messageMode2F =
XCommandT "Console.messageMode2F" (do
globals.gChatTeam .= True
globals.gCls.csKeyDest .= Constants.keyMessage
)
clearF :: XCommandT
clearF =
XCommandT "Console.clearF" (do
text <- io $ MSV.replicate Constants.conTextSize ' '
globals.gCon.cText .= text
)
dumpF :: XCommandT
dumpF =
XCommandT "Console.dumpF" (do
io (putStrLn "Console.dumpF") >> undefined -- TODO
)
clearNotify :: Quake ()
clearNotify = globals.gCon.cTimes .= UV.replicate Constants.numConTimes 0
drawAltString :: Int -> Int -> B.ByteString -> Quake ()
drawAltString x y s = do
draw x 0 (B.length s)
where draw :: Int -> Int -> Int -> Quake ()
draw x' idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) x' y ((ord $ s `BC.index` idx) `xor` 0x80)
draw (x' + 8) (idx + 1) maxIdx
drawString :: Int -> Int -> B.ByteString -> Quake ()
drawString x y s =
draw x 0 (B.length s)
where draw :: Int -> Int -> Int -> Quake ()
draw x' idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) x' y (ord $ s `BC.index` idx)
draw (x' + 8) (idx + 1) maxIdx
{-
- ================ Con_DrawConsole
-
- Draws the console with the solid background ================
-}
drawConsole :: Float -> Quake ()
drawConsole frac = do
vidDef' <- use $ globals.gVidDef
let width = vidDef'^.vdWidth
height = vidDef'^.vdHeight
tmpLinesNum = truncate ((fromIntegral height) * frac)
unless (tmpLinesNum <= 0) $ do
let linesNum = if tmpLinesNum > height
then height
else tmpLinesNum
-- draw the background
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawStretchPic) 0 (-height + linesNum) width height "conback"
SCR.addDirtyPoint 0 0
SCR.addDirtyPoint (width - 1) (linesNum - 1)
let version = BC.pack (printf "v%4.2f" Constants.version)
drawVersion version width linesNum 0 5
-- draw the text
globals.gCon.cVisLines .= linesNum
console <- use $ globals.gCon
(rows, y) <- do
let rows = (linesNum - 22) `shiftR` 3 -- rows of text to draw
y = linesNum - 30
-- draw from the bottom up
if (console^.cDisplay) /= (console^.cCurrent)
then do
-- draw arrows to show the buffer is backscrolled
drawArrows 0 (console^.cLineWidth) y
return (rows - 1, y - 8)
else
return (rows, y)
let row = console^.cDisplay
drawText console row y 0 rows
download <- use $ globals.gCls.csDownload
when (isJust download) $ do
io (putStrLn "Console.drawConsole") >> undefined -- TODO
-- draw the input prompt, user text, and cursor if desired
drawInput
where drawVersion :: B.ByteString -> Int -> Int -> Int -> Int -> Quake ()
drawVersion version width linesNum idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) (width - 44 + idx * 8) (linesNum - 12) (128 + ord (BC.index version idx))
drawVersion version width linesNum (idx + 1) maxIdx
drawArrows :: Int -> Int -> Int -> Quake ()
drawArrows x maxX y
| x >= maxX = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) ((x + 1) `shiftL` 3) y (ord '^')
drawArrows (x + 4) maxX y
drawText :: ConsoleT -> Int -> Int -> Int -> Int -> Quake ()
drawText console row y idx maxIdx
| idx >= maxIdx || row < 0 || (console^.cCurrent) - row >= (console^.cTotalLines) = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
let first = (row `mod` (console^.cTotalLines)) * (console^.cLineWidth)
drawChar = renderer^.rRefExport.reDrawChar
drawLine drawChar (console^.cText) first y 0 (console^.cLineWidth)
drawText console (row - 1) (y - 8) (idx + 1) maxIdx
drawLine :: (Int -> Int -> Int -> Quake ()) -> MSV.IOVector Char -> Int -> Int -> Int -> Int -> Quake ()
drawLine drawChar text first y idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
ch <- io $ text `MSV.read` (idx + first)
drawChar ((idx + 1) `shiftL` 3) y $! (ord ch)
drawLine drawChar text first y (idx + 1) maxIdx
{-
- ================ Con_DrawNotify ================
-
- Draws the last few lines of output transparently over the game top
-}
drawNotify :: Quake ()
drawNotify = do
console <- use $ globals.gCon
vidDefWidth <- use $ globals.gVidDef.vdWidth
cls' <- use $ globals.gCls
v <- draw cls' console 0 ((console^.cCurrent) - Constants.numConTimes + 1) (console^.cCurrent)
v' <- if (cls'^.csKeyDest) == Constants.keyMessage
then do
chatTeam' <- use $ globals.gChatTeam
skip <- if chatTeam'
then do
drawString 8 v "say_team:"
return 11
else do
drawString 8 v "say:"
return 5
s <- use $ globals.gChatBuffer
chatLen <- use $ globals.gChatBufferLen
let s' = if chatLen > (vidDefWidth `shiftR` 3) - (skip + 1)
then B.drop (chatLen - ((vidDefWidth `shiftR` 3) - (skip + 1))) s
else s
drawChat s' skip v 0 (B.length s')
return (v + 8)
else
return v
when (v' /= 0) $ do
SCR.addDirtyPoint 0 0
SCR.addDirtyPoint (vidDefWidth - 1) v'
where draw :: ClientStaticT -> ConsoleT -> Int -> Int -> Int -> Quake Int
draw cls' console v idx maxIdx
| idx > maxIdx = return v
| idx < 0 = draw cls' console v (idx + 1) maxIdx
| otherwise = do
let time = truncate ((console^.cTimes) UV.! (idx `mod` Constants.numConTimes)) :: Int
if time == 0
then draw cls' console v (idx + 1) maxIdx
else do
let time' = (cls'^.csRealTime) - time
conNotifyTimeValue <- liftM (^.cvValue) conNotifyTimeCVar
if time' > truncate (conNotifyTimeValue * 1000)
then draw cls' console v (idx + 1) maxIdx
else do
let text = (idx `mod` (console^.cTotalLines)) * (console^.cLineWidth)
drawText console v text 0 (console^.cLineWidth)
draw cls' console (v + 8) (idx + 1) maxIdx
drawText :: ConsoleT -> Int -> Int -> Int -> Int -> Quake ()
drawText console v text idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
Just renderer <- use $ globals.gRenderer
c <- io $ MSV.read (console^.cText) (text + idx)
(renderer^.rRefExport.reDrawChar) ((idx + 1) `shiftL` 3) v (ord c)
drawText console v text (idx + 1) maxIdx
drawChat :: B.ByteString -> Int -> Int -> Int -> Int -> Quake ()
drawChat s skip v idx maxIdx
| idx >= maxIdx = do
realTime <- use $ globals.gCls.csRealTime
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) ((idx + skip) `shiftL` 3) v (10 + ((realTime `shiftR` 8) .&. 1))
| otherwise = do
Just renderer <- use $ globals.gRenderer
(renderer^.rRefExport.reDrawChar) ((idx + skip) `shiftL` 3) v (ord $ s `BC.index` idx)
drawChat s skip v (idx + 1) maxIdx
{-
- ================ Con_DrawInput
-
- The input line scrolls horizontally if typing goes beyond the right edge
- ================
-}
drawInput :: Quake ()
drawInput = do
keyDest <- use $ globals.gCls.csKeyDest
state <- use $ globals.gCls.csState
-- don't draw anything (always draw if not active)
unless (keyDest == Constants.keyMenu || (keyDest /= Constants.keyConsole && state == Constants.caActive)) $ do
editLine' <- use $ globals.gEditLine
Just text <- preuse $ globals.gKeyLines.ix editLine'
linePos <- use $ globals.gKeyLinePos
lineWidth <- use $ globals.gCon.cLineWidth
-- add the cursor frame and fill out remainder with spaces
realTime <- use $ globals.gCls.csRealTime
let cursorFrame :: Word8 = fromIntegral $ 10 + ((realTime `shiftR` 8) .&. 1)
fullLine = text `B.append` B.unfoldr (\i -> if i == 0
then Just (cursorFrame, 1)
else if linePos + 1 + i < lineWidth
then Just (32, i + 1)
else Nothing) 0
-- prestep if horizontally scrolling
let start = if linePos >= lineWidth
then 1 + linePos - lineWidth
else 0
-- draw it
visLines <- use $ globals.gCon.cVisLines
Just renderer <- use $ globals.gRenderer
let drawChar = renderer^.rRefExport.reDrawChar
drawInputLine drawChar fullLine (visLines - 22) start lineWidth -- TODO: make sure start is here (jake2 bug with not using start?)
where drawInputLine :: (Int -> Int -> Int -> Quake ()) -> B.ByteString -> Int -> Int -> Int -> Quake ()
drawInputLine drawChar text y idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
drawChar ((idx + 1) `shiftL` 3) y (ord $ BC.index text idx)
drawInputLine drawChar text y (idx + 1) maxIdx
{-
- ================ Con_Print
-
- Handles cursor positioning, line wrapping, etc All console printing must
- go through this in order to be logged to disk If no console is visible,
- the text will appear at the top of the game window ================
-}
print :: B.ByteString -> Quake ()
print txt = do
initialized <- use $ globals.gCon.cInitialized
when initialized $ do
let (mask, txtpos) = if txt `B.index` 0 == 1 || txt `B.index` 0 == 2
then (128, 1)
else (0, 0)
printTxt txtpos mask
where printTxt :: Int -> Int -> Quake ()
printTxt txtpos mask
| txtpos >= B.length txt = return ()
| otherwise = do
console <- use $ globals.gCon
let c = txt `BC.index` txtpos
len = findWordLen (console^.cLineWidth) txtpos 0
-- word wrap
when (len /= (console^.cLineWidth) && (console^.cX) + len > (console^.cLineWidth)) $
globals.gCon.cX .= 0
use (clientGlobals.cgCR) >>= \v ->
when (v /= 0) $ do
globals.gCon.cCurrent -= 1
clientGlobals.cgCR .= 0
use (globals.gCon) >>= \console' ->
when ((console'^.cX) == 0) $ do
lineFeed
-- mark time for transparent overlay
when ((console'^.cCurrent) >= 0) $ do
realTime <- use $ globals.gCls.csRealTime
globals.gCon.cTimes.ix ((console'^.cCurrent) `mod` Constants.numConTimes) .= fromIntegral realTime
case c of
'\n' -> do
globals.gCon.cX .= 0
printTxt (txtpos + 1) mask
'\r' -> do
globals.gCon.cX .= 0
clientGlobals.cgCR .= 1
printTxt (txtpos + 1) mask
_ -> -- display character and advance
use (globals.gCon) >>= \console' -> do
let y = (console'^.cCurrent) `mod` (console'^.cTotalLines)
idx = y * (console'^.cLineWidth) + (console'^.cX)
b = (ord c) .|. mask .|. (console'^.cOrMask)
io $ MSV.write (console'^.cText) idx (chr b)
globals.gCon.cX += 1
when ((console'^.cX) + 1 >= (console'^.cLineWidth)) $
globals.gCon.cX .= 0
printTxt (txtpos + 1) mask
findWordLen :: Int -> Int -> Int -> Int
findWordLen lineWidth txtpos idx =
if idx >= lineWidth || idx >= (B.length txt - txtpos)
then idx
else if txt `BC.index` (idx + txtpos) <= ' '
then idx
else findWordLen lineWidth txtpos (idx + 1)
lineFeed :: Quake ()
lineFeed = do
globals.gCon.cX .= 0
use (globals.gCon) >>= \console ->
when ((console^.cDisplay) == (console^.cCurrent)) $
globals.gCon.cDisplay += 1
globals.gCon.cCurrent += 1
use (globals.gCon) >>= \console -> do
let i = ((console^.cCurrent) `mod` (console^.cTotalLines)) * (console^.cLineWidth)
e = i + (console^.cLineWidth)
fillSpaces (console^.cText) i e
where fillSpaces :: MSV.IOVector Char -> Int -> Int -> Quake ()
fillSpaces text i e
| i >= e = return ()
| otherwise = do
io $ MSV.write text i ' '
fillSpaces text (i + 1) e
| ksaveljev/hake-2 | src/Client/Console.hs | bsd-3-clause | 18,127 | 1 | 26 | 6,033 | 5,777 | 2,923 | 2,854 | -1 | -1 |
module Tile where
data Point = Point Int Int deriving Show
data Tile = Wall
| Space
| Hole
| Gold
| Monster
| Player
| DStairs
| UStairs
| VDoor deriving Eq
instance Show Tile where
show Wall = "#"
show Space = "."
show Hole = " "
show Gold = "g"
show Monster = "T"
show Player = "@"
show DStairs = ">"
show UStairs = "<"
show VDoor = "|"
readTile :: Char -> Tile
readTile '#' = Wall
readTile '.' = Space
readTile ' ' = Hole
readTile 'g' = Gold
readTile 'm' = Monster
readTile '@' = Player
readTile '>' = DStairs
readTile '<' = UStairs
readTile '|' = VDoor
readTile _ = Space
| hans25041/gringotz-level | src/Tile.hs | bsd-3-clause | 714 | 0 | 6 | 258 | 221 | 118 | 103 | 32 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Tar
-- Copyright : (c) 2007 Bjorn Bringert,
-- 2008 Andrea Vezzosi,
-- 2008-2009 Duncan Coutts
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Reading, writing and manipulating \"@.tar@\" archive files.
--
-----------------------------------------------------------------------------
module Distribution.Client.Tar (
-- * High level \"all in one\" operations
createTarGzFile,
extractTarGzFile,
-- * Converting between internal and external representation
read,
write,
-- * Packing and unpacking files to\/from internal representation
pack,
unpack,
-- * Tar entry and associated types
Entry(..),
entryPath,
EntryContent(..),
Ownership(..),
FileSize,
Permissions,
EpochTime,
DevMajor,
DevMinor,
TypeCode,
Format(..),
-- * Constructing simple entry values
simpleEntry,
fileEntry,
directoryEntry,
-- * TarPath type
TarPath,
toTarPath,
fromTarPath,
-- ** Sequences of tar entries
Entries(..),
foldrEntries,
foldlEntries,
unfoldrEntries,
mapEntries,
filterEntries,
entriesIndex,
) where
import Data.Char (ord)
import Data.Int (Int64)
import Data.Bits (Bits, shiftL, testBit)
import Data.List (foldl')
import Numeric (readOct, showOct)
import Control.Monad (MonadPlus(mplus), when)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import Data.ByteString.Lazy (ByteString)
import qualified Codec.Compression.GZip as GZip
import qualified Distribution.Client.GZipUtils as GZipUtils
import System.FilePath
( (</>) )
import qualified System.FilePath as FilePath.Native
import qualified System.FilePath.Windows as FilePath.Windows
import qualified System.FilePath.Posix as FilePath.Posix
import System.Directory
( getDirectoryContents, doesDirectoryExist, getModificationTime
, getPermissions, createDirectoryIfMissing, copyFile )
import qualified System.Directory as Permissions
( Permissions(executable) )
import Distribution.Compat.FilePerms
( setFileExecutable )
import System.Posix.Types
( FileMode )
import Data.Time
import Data.Time.Clock.POSIX
import System.IO
( IOMode(ReadMode), openBinaryFile, hFileSize )
import System.IO.Unsafe (unsafeInterleaveIO)
import Prelude hiding (read)
--
-- * High level operations
--
createTarGzFile :: FilePath -- ^ Full Tarball path
-> FilePath -- ^ Base directory
-> FilePath -- ^ Directory to archive, relative to base dir
-> IO ()
createTarGzFile tar base dir =
BS.writeFile tar . GZip.compress . write =<< pack base [dir]
extractTarGzFile :: FilePath -- ^ Destination directory
-> FilePath -- ^ Expected subdir (to check for tarbombs)
-> FilePath -- ^ Tarball
-> IO ()
extractTarGzFile dir expected tar = do
unpack dir . checkTarbomb expected . read . GZipUtils.maybeDecompress =<< BS.readFile tar
--
-- * Entry type
--
type FileSize = Int64
-- | The number of seconds since the UNIX epoch
type EpochTime = Int64
type DevMajor = Int
type DevMinor = Int
type TypeCode = Char
type Permissions = FileMode
-- | Tar archive entry.
--
data Entry = Entry {
-- | The path of the file or directory within the archive. This is in a
-- tar-specific form. Use 'entryPath' to get a native 'FilePath'.
entryTarPath :: !TarPath,
-- | The real content of the entry. For 'NormalFile' this includes the
-- file data. An entry usually contains a 'NormalFile' or a 'Directory'.
entryContent :: !EntryContent,
-- | File permissions (Unix style file mode).
entryPermissions :: !Permissions,
-- | The user and group to which this file belongs.
entryOwnership :: !Ownership,
-- | The time the file was last modified.
entryTime :: !EpochTime,
-- | The tar format the archive is using.
entryFormat :: !Format
}
-- | Native 'FilePath' of the file or directory within the archive.
--
entryPath :: Entry -> FilePath
entryPath = fromTarPath . entryTarPath
-- | The content of a tar archive entry, which depends on the type of entry.
--
-- Portable archives should contain only 'NormalFile' and 'Directory'.
--
data EntryContent = NormalFile ByteString !FileSize
| Directory
| SymbolicLink !LinkTarget
| HardLink !LinkTarget
| CharacterDevice !DevMajor !DevMinor
| BlockDevice !DevMajor !DevMinor
| NamedPipe
| OtherEntryType !TypeCode ByteString !FileSize
data Ownership = Ownership {
-- | The owner user name. Should be set to @\"\"@ if unknown.
ownerName :: String,
-- | The owner group name. Should be set to @\"\"@ if unknown.
groupName :: String,
-- | Numeric owner user id. Should be set to @0@ if unknown.
ownerId :: !Int,
-- | Numeric owner group id. Should be set to @0@ if unknown.
groupId :: !Int
}
-- | There have been a number of extensions to the tar file format over the
-- years. They all share the basic entry fields and put more meta-data in
-- different extended headers.
--
data Format =
-- | This is the classic Unix V7 tar format. It does not support owner and
-- group names, just numeric Ids. It also does not support device numbers.
V7Format
-- | The \"USTAR\" format is an extension of the classic V7 format. It was
-- later standardised by POSIX. It has some restructions but is the most
-- portable format.
--
| UstarFormat
-- | The GNU tar implementation also extends the classic V7 format, though
-- in a slightly different way from the USTAR format. In general for new
-- archives the standard USTAR/POSIX should be used.
--
| GnuFormat
deriving Eq
-- | @rw-r--r--@ for normal files
ordinaryFilePermissions :: Permissions
ordinaryFilePermissions = 0o0644
-- | @rwxr-xr-x@ for executable files
executableFilePermissions :: Permissions
executableFilePermissions = 0o0755
-- | @rwxr-xr-x@ for directories
directoryPermissions :: Permissions
directoryPermissions = 0o0755
isExecutable :: Permissions -> Bool
isExecutable p = testBit p 0 || testBit p 6 -- user or other exectuable
-- | An 'Entry' with all default values except for the file name and type. It
-- uses the portable USTAR/POSIX format (see 'UstarHeader').
--
-- You can use this as a basis and override specific fields, eg:
--
-- > (emptyEntry name HardLink) { linkTarget = target }
--
simpleEntry :: TarPath -> EntryContent -> Entry
simpleEntry tarpath content = Entry {
entryTarPath = tarpath,
entryContent = content,
entryPermissions = case content of
Directory -> directoryPermissions
_ -> ordinaryFilePermissions,
entryOwnership = Ownership "" "" 0 0,
entryTime = 0,
entryFormat = UstarFormat
}
-- | A tar 'Entry' for a file.
--
-- Entry fields such as file permissions and ownership have default values.
--
-- You can use this as a basis and override specific fields. For example if you
-- need an executable file you could use:
--
-- > (fileEntry name content) { fileMode = executableFileMode }
--
fileEntry :: TarPath -> ByteString -> Entry
fileEntry name fileContent =
simpleEntry name (NormalFile fileContent (BS.length fileContent))
-- | A tar 'Entry' for a directory.
--
-- Entry fields such as file permissions and ownership have default values.
--
directoryEntry :: TarPath -> Entry
directoryEntry name = simpleEntry name Directory
--
-- * Tar paths
--
-- | The classic tar format allowed just 100 charcters for the file name. The
-- USTAR format extended this with an extra 155 characters, however it uses a
-- complex method of splitting the name between the two sections.
--
-- Instead of just putting any overflow into the extended area, it uses the
-- extended area as a prefix. The agrevating insane bit however is that the
-- prefix (if any) must only contain a directory prefix. That is the split
-- between the two areas must be on a directory separator boundary. So there is
-- no simple calculation to work out if a file name is too long. Instead we
-- have to try to find a valid split that makes the name fit in the two areas.
--
-- The rationale presumably was to make it a bit more compatible with old tar
-- programs that only understand the classic format. A classic tar would be
-- able to extract the file name and possibly some dir prefix, but not the
-- full dir prefix. So the files would end up in the wrong place, but that's
-- probably better than ending up with the wrong names too.
--
-- So it's understandable but rather annoying.
--
-- * Tar paths use posix format (ie @\'/\'@ directory separators), irrespective
-- of the local path conventions.
--
-- * The directory separator between the prefix and name is /not/ stored.
--
data TarPath = TarPath FilePath -- path name, 100 characters max.
FilePath -- path prefix, 155 characters max.
deriving (Eq, Ord)
-- | Convert a 'TarPath' to a native 'FilePath'.
--
-- The native 'FilePath' will use the native directory separator but it is not
-- otherwise checked for validity or sanity. In particular:
--
-- * The tar path may be invalid as a native path, eg the filename @\"nul\"@ is
-- not valid on Windows.
--
-- * The tar path may be an absolute path or may contain @\"..\"@ components.
-- For security reasons this should not usually be allowed, but it is your
-- responsibility to check for these conditions (eg using 'checkSecurity').
--
fromTarPath :: TarPath -> FilePath
fromTarPath (TarPath name prefix) = adjustDirectory $
FilePath.Native.joinPath $ FilePath.Posix.splitDirectories prefix
++ FilePath.Posix.splitDirectories name
where
adjustDirectory | FilePath.Posix.hasTrailingPathSeparator name
= FilePath.Native.addTrailingPathSeparator
| otherwise = id
-- | Convert a native 'FilePath' to a 'TarPath'.
--
-- The conversion may fail if the 'FilePath' is too long. See 'TarPath' for a
-- description of the problem with splitting long 'FilePath's.
--
toTarPath :: Bool -- ^ Is the path for a directory? This is needed because for
-- directories a 'TarPath' must always use a trailing @\/@.
-> FilePath -> Either String TarPath
toTarPath isDir = splitLongPath
. addTrailingSep
. FilePath.Posix.joinPath
. FilePath.Native.splitDirectories
where
addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator
| otherwise = id
-- | Take a sanitized path, split on directory separators and try to pack it
-- into the 155 + 100 tar file name format.
--
-- The stragey is this: take the name-directory components in reverse order
-- and try to fit as many components into the 100 long name area as possible.
-- If all the remaining components fit in the 155 name area then we win.
--
splitLongPath :: FilePath -> Either String TarPath
splitLongPath path =
case packName nameMax (reverse (FilePath.Posix.splitPath path)) of
Left err -> Left err
Right (name, []) -> Right (TarPath name "")
Right (name, first:rest) -> case packName prefixMax remainder of
Left err -> Left err
Right (_ , (_:_)) -> Left "File name too long (cannot split)"
Right (prefix, []) -> Right (TarPath name prefix)
where
-- drop the '/' between the name and prefix:
remainder = init first : rest
where
nameMax, prefixMax :: Int
nameMax = 100
prefixMax = 155
packName _ [] = Left "File name empty"
packName maxLen (c:cs)
| n > maxLen = Left "File name too long"
| otherwise = Right (packName' maxLen n [c] cs)
where n = length c
packName' maxLen n ok (c:cs)
| n' <= maxLen = packName' maxLen n' (c:ok) cs
where n' = n + length c
packName' _ _ ok cs = (FilePath.Posix.joinPath ok, cs)
-- | The tar format allows just 100 ASCII charcters for the 'SymbolicLink' and
-- 'HardLink' entry types.
--
newtype LinkTarget = LinkTarget FilePath
deriving (Eq, Ord)
-- | Convert a tar 'LinkTarget' to a native 'FilePath'.
--
fromLinkTarget :: LinkTarget -> FilePath
fromLinkTarget (LinkTarget path) = adjustDirectory $
FilePath.Native.joinPath $ FilePath.Posix.splitDirectories path
where
adjustDirectory | FilePath.Posix.hasTrailingPathSeparator path
= FilePath.Native.addTrailingPathSeparator
| otherwise = id
--
-- * Entries type
--
-- | A tar archive is a sequence of entries.
data Entries = Next Entry Entries
| Done
| Fail String
unfoldrEntries :: (a -> Either String (Maybe (Entry, a))) -> a -> Entries
unfoldrEntries f = unfold
where
unfold x = case f x of
Left err -> Fail err
Right Nothing -> Done
Right (Just (e, x')) -> Next e (unfold x')
foldrEntries :: (Entry -> a -> a) -> a -> (String -> a) -> Entries -> a
foldrEntries next done fail' = fold
where
fold (Next e es) = next e (fold es)
fold Done = done
fold (Fail err) = fail' err
foldlEntries :: (a -> Entry -> a) -> a -> Entries -> Either String a
foldlEntries f = fold
where
fold a (Next e es) = (fold $! f a e) es
fold a Done = Right a
fold _ (Fail err) = Left err
mapEntries :: (Entry -> Entry) -> Entries -> Entries
mapEntries f = foldrEntries (Next . f) Done Fail
filterEntries :: (Entry -> Bool) -> Entries -> Entries
filterEntries p =
foldrEntries
(\entry rest -> if p entry
then Next entry rest
else rest)
Done Fail
checkEntries :: (Entry -> Maybe String) -> Entries -> Entries
checkEntries checkEntry =
foldrEntries
(\entry rest -> case checkEntry entry of
Nothing -> Next entry rest
Just err -> Fail err)
Done Fail
entriesIndex :: Entries -> Either String (Map.Map TarPath Entry)
entriesIndex = foldlEntries (\m e -> Map.insert (entryTarPath e) e m) Map.empty
--
-- * Checking
--
-- | This function checks a sequence of tar entries for file name security
-- problems. It checks that:
--
-- * file paths are not absolute
--
-- * file paths do not contain any path components that are \"@..@\"
--
-- * file names are valid
--
-- These checks are from the perspective of the current OS. That means we check
-- for \"@C:\blah@\" files on Windows and \"\/blah\" files on unix. For archive
-- entry types 'HardLink' and 'SymbolicLink' the same checks are done for the
-- link target. A failure in any entry terminates the sequence of entries with
-- an error.
--
checkSecurity :: Entries -> Entries
checkSecurity = checkEntries checkEntrySecurity
checkTarbomb :: FilePath -> Entries -> Entries
checkTarbomb expectedTopDir = checkEntries (checkEntryTarbomb expectedTopDir)
checkEntrySecurity :: Entry -> Maybe String
checkEntrySecurity entry = case entryContent entry of
HardLink link -> check (entryPath entry)
`mplus` check (fromLinkTarget link)
SymbolicLink link -> check (entryPath entry)
`mplus` check (fromLinkTarget link)
_ -> check (entryPath entry)
where
check name
| not (FilePath.Native.isRelative name)
= Just $ "Absolute file name in tar archive: " ++ show name
| not (FilePath.Native.isValid name)
= Just $ "Invalid file name in tar archive: " ++ show name
| any (=="..") (FilePath.Native.splitDirectories name)
= Just $ "Invalid file name in tar archive: " ++ show name
| otherwise = Nothing
checkEntryTarbomb :: FilePath -> Entry -> Maybe String
checkEntryTarbomb _ entry | nonFilesystemEntry = Nothing
where
-- Ignore some special entries we will not unpack anyway
nonFilesystemEntry =
case entryContent entry of
OtherEntryType 'g' _ _ -> True --PAX global header
OtherEntryType 'x' _ _ -> True --PAX individual header
_ -> False
checkEntryTarbomb expectedTopDir entry =
case FilePath.Native.splitDirectories (entryPath entry) of
(topDir:_) | topDir == expectedTopDir -> Nothing
_ -> Just $ "File in tar archive is not in the expected directory "
++ show expectedTopDir
--
-- * Reading
--
read :: ByteString -> Entries
read = unfoldrEntries getEntry
getEntry :: ByteString -> Either String (Maybe (Entry, ByteString))
getEntry bs
| BS.length header < 512 = Left "truncated tar archive"
-- Tar files end with at least two blocks of all '0'. Checking this serves
-- two purposes. It checks the format but also forces the tail of the data
-- which is necessary to close the file if it came from a lazily read file.
| BS.head bs == 0 = case BS.splitAt 1024 bs of
(end, trailing)
| BS.length end /= 1024 -> Left "short tar trailer"
| not (BS.all (== 0) end) -> Left "bad tar trailer"
| not (BS.all (== 0) trailing) -> Left "tar file has trailing junk"
| otherwise -> Right Nothing
| otherwise = partial $ do
case (chksum_, format_) of
(Ok chksum, _ ) | correctChecksum header chksum -> return ()
(Ok _, Ok _) -> fail "tar checksum error"
_ -> fail "data is not in tar format"
-- These fields are partial, have to check them
format <- format_; mode <- mode_;
uid <- uid_; gid <- gid_;
size <- size_; mtime <- mtime_;
devmajor <- devmajor_; devminor <- devminor_;
let content = BS.take size (BS.drop 512 bs)
padding = (512 - size) `mod` 512
bs' = BS.drop (512 + size + padding) bs
entry = Entry {
entryTarPath = TarPath name prefix,
entryContent = case typecode of
'\0' -> NormalFile content size
'0' -> NormalFile content size
'1' -> HardLink (LinkTarget linkname)
'2' -> SymbolicLink (LinkTarget linkname)
'3' -> CharacterDevice devmajor devminor
'4' -> BlockDevice devmajor devminor
'5' -> Directory
'6' -> NamedPipe
'7' -> NormalFile content size
_ -> OtherEntryType typecode content size,
entryPermissions = mode,
entryOwnership = Ownership uname gname uid gid,
entryTime = mtime,
entryFormat = format
}
return (Just (entry, bs'))
where
header = BS.take 512 bs
name = getString 0 100 header
mode_ = getOct 100 8 header
uid_ = getOct 108 8 header
gid_ = getOct 116 8 header
size_ = getOct 124 12 header
mtime_ = getOct 136 12 header
chksum_ = getOct 148 8 header
typecode = getByte 156 header
linkname = getString 157 100 header
magic = getChars 257 8 header
uname = getString 265 32 header
gname = getString 297 32 header
devmajor_ = getOct 329 8 header
devminor_ = getOct 337 8 header
prefix = getString 345 155 header
-- trailing = getBytes 500 12 header
format_ = case magic of
"\0\0\0\0\0\0\0\0" -> return V7Format
"ustar\NUL00" -> return UstarFormat
"ustar \NUL" -> return GnuFormat
_ -> fail "tar entry not in a recognised format"
correctChecksum :: ByteString -> Int -> Bool
correctChecksum header checksum = checksum == checksum'
where
-- sum of all 512 bytes in the header block,
-- treating each byte as an 8-bit unsigned value
checksum' = BS.Char8.foldl' (\x y -> x + ord y) 0 header'
-- treating the 8 bytes of chksum as blank characters.
header' = BS.concat [BS.take 148 header,
BS.Char8.replicate 8 ' ',
BS.drop 156 header]
-- * TAR format primitive input
getOct :: (Integral a, Bits a) => Int64 -> Int64 -> ByteString -> Partial a
getOct off len header
| BS.head bytes == 128 = parseBinInt (BS.unpack (BS.tail bytes))
| null octstr = return 0
| otherwise = case readOct octstr of
[(x,[])] -> return x
_ -> fail "tar header is malformed (bad numeric encoding)"
where
bytes = getBytes off len header
octstr = BS.Char8.unpack
. BS.Char8.takeWhile (\c -> c /= '\NUL' && c /= ' ')
. BS.Char8.dropWhile (== ' ')
$ bytes
-- Some tar programs switch into a binary format when they try to represent
-- field values that will not fit in the required width when using the text
-- octal format. In particular, the UID/GID fields can only hold up to 2^21
-- while in the binary format can hold up to 2^32. The binary format uses
-- '\128' as the header which leaves 7 bytes. Only the last 4 are used.
parseBinInt [0, 0, 0, byte3, byte2, byte1, byte0] =
return $! shiftL (fromIntegral byte3) 24
+ shiftL (fromIntegral byte2) 16
+ shiftL (fromIntegral byte1) 8
+ shiftL (fromIntegral byte0) 0
parseBinInt _ = fail "tar header uses non-standard number encoding"
getBytes :: Int64 -> Int64 -> ByteString -> ByteString
getBytes off len = BS.take len . BS.drop off
getByte :: Int64 -> ByteString -> Char
getByte off bs = BS.Char8.index bs off
getChars :: Int64 -> Int64 -> ByteString -> String
getChars off len = BS.Char8.unpack . getBytes off len
getString :: Int64 -> Int64 -> ByteString -> String
getString off len = BS.Char8.unpack . BS.Char8.takeWhile (/='\0') . getBytes off len
data Partial a = Error String | Ok a
partial :: Partial a -> Either String a
partial (Error msg) = Left msg
partial (Ok x) = Right x
instance Monad Partial where
return = Ok
Error m >>= _ = Error m
Ok x >>= k = k x
fail = Error
--
-- * Writing
--
-- | Create the external representation of a tar archive by serialising a list
-- of tar entries.
--
-- * The conversion is done lazily.
--
write :: [Entry] -> ByteString
write es = BS.concat $ map putEntry es ++ [BS.replicate (512*2) 0]
putEntry :: Entry -> ByteString
putEntry entry = case entryContent entry of
NormalFile content size -> BS.concat [ header, content, padding size ]
OtherEntryType _ content size -> BS.concat [ header, content, padding size ]
_ -> header
where
header = putHeader entry
padding size = BS.replicate paddingSize 0
where paddingSize = fromIntegral (negate size `mod` 512)
putHeader :: Entry -> ByteString
putHeader entry =
BS.Char8.pack $ take 148 block
++ putOct 7 checksum
++ ' ' : drop 156 block
where
block = putHeaderNoChkSum entry
checksum = foldl' (\x y -> x + ord y) 0 block
putHeaderNoChkSum :: Entry -> String
putHeaderNoChkSum Entry {
entryTarPath = TarPath name prefix,
entryContent = content,
entryPermissions = permissions,
entryOwnership = ownership,
entryTime = modTime,
entryFormat = format
} =
concat
[ putString 100 $ name
, putOct 8 $ permissions
, putOct 8 $ ownerId ownership
, putOct 8 $ groupId ownership
, putOct 12 $ contentSize
, putOct 12 $ modTime
, fill 8 $ ' ' -- dummy checksum
, putChar8 $ typeCode
, putString 100 $ linkTarget
] ++
case format of
V7Format ->
fill 255 '\NUL'
UstarFormat -> concat
[ putString 8 $ "ustar\NUL00"
, putString 32 $ ownerName ownership
, putString 32 $ groupName ownership
, putOct 8 $ deviceMajor
, putOct 8 $ deviceMinor
, putString 155 $ prefix
, fill 12 $ '\NUL'
]
GnuFormat -> concat
[ putString 8 $ "ustar \NUL"
, putString 32 $ ownerName ownership
, putString 32 $ groupName ownership
, putGnuDev 8 $ deviceMajor
, putGnuDev 8 $ deviceMinor
, putString 155 $ prefix
, fill 12 $ '\NUL'
]
where
(typeCode, contentSize, linkTarget,
deviceMajor, deviceMinor) = case content of
NormalFile _ size -> ('0' , size, [], 0, 0)
Directory -> ('5' , 0, [], 0, 0)
SymbolicLink (LinkTarget link) -> ('2' , 0, link, 0, 0)
HardLink (LinkTarget link) -> ('1' , 0, link, 0, 0)
CharacterDevice major minor -> ('3' , 0, [], major, minor)
BlockDevice major minor -> ('4' , 0, [], major, minor)
NamedPipe -> ('6' , 0, [], 0, 0)
OtherEntryType code _ size -> (code, size, [], 0, 0)
putGnuDev w n = case content of
CharacterDevice _ _ -> putOct w n
BlockDevice _ _ -> putOct w n
_ -> replicate w '\NUL'
-- * TAR format primitive output
type FieldWidth = Int
putString :: FieldWidth -> String -> String
putString n s = take n s ++ fill (n - length s) '\NUL'
--TODO: check integer widths, eg for large file sizes
putOct :: (Show a, Integral a) => FieldWidth -> a -> String
putOct n x =
let octStr = take (n-1) $ showOct x ""
in fill (n - length octStr - 1) '0'
++ octStr
++ putChar8 '\NUL'
putChar8 :: Char -> String
putChar8 c = [c]
fill :: FieldWidth -> Char -> String
fill n c = replicate n c
--
-- * Unpacking
--
unpack :: FilePath -> Entries -> IO ()
unpack baseDir entries = unpackEntries [] (checkSecurity entries)
>>= emulateLinks
where
-- We're relying here on 'checkSecurity' to make sure we're not scribbling
-- files all over the place.
unpackEntries _ (Fail err) = fail err
unpackEntries links Done = return links
unpackEntries links (Next entry es) = case entryContent entry of
NormalFile file _ -> extractFile entry path file
>> unpackEntries links es
Directory -> extractDir path
>> unpackEntries links es
HardLink link -> (unpackEntries $! saveLink path link links) es
SymbolicLink link -> (unpackEntries $! saveLink path link links) es
_ -> unpackEntries links es --ignore other file types
where
path = entryPath entry
extractFile entry path content = do
-- Note that tar archives do not make sure each directory is created
-- before files they contain, indeed we may have to create several
-- levels of directory.
createDirectoryIfMissing True absDir
BS.writeFile absPath content
when (isExecutable (entryPermissions entry))
(setFileExecutable absPath)
where
absDir = baseDir </> FilePath.Native.takeDirectory path
absPath = baseDir </> path
extractDir path = createDirectoryIfMissing True (baseDir </> path)
saveLink path link links = seq (length path)
$ seq (length link')
$ (path, link'):links
where link' = fromLinkTarget link
emulateLinks = mapM_ $ \(relPath, relLinkTarget) ->
let absPath = baseDir </> relPath
absTarget = FilePath.Native.takeDirectory absPath </> relLinkTarget
in copyFile absTarget absPath
--
-- * Packing
--
pack :: FilePath -- ^ Base directory
-> [FilePath] -- ^ Files and directories to pack, relative to the base dir
-> IO [Entry]
pack baseDir paths0 = preparePaths baseDir paths0 >>= packPaths baseDir
preparePaths :: FilePath -> [FilePath] -> IO [FilePath]
preparePaths baseDir paths =
fmap concat $ interleave
[ do isDir <- doesDirectoryExist (baseDir </> path)
if isDir
then do entries <- getDirectoryContentsRecursive (baseDir </> path)
return (FilePath.Native.addTrailingPathSeparator path
: map (path </>) entries)
else return [path]
| path <- paths ]
packPaths :: FilePath -> [FilePath] -> IO [Entry]
packPaths baseDir paths =
interleave
[ do tarpath <- either fail return (toTarPath isDir relpath)
if isDir then packDirectoryEntry filepath tarpath
else packFileEntry filepath tarpath
| relpath <- paths
, let isDir = FilePath.Native.hasTrailingPathSeparator filepath
filepath = baseDir </> relpath ]
interleave :: [IO a] -> IO [a]
interleave = unsafeInterleaveIO . go
where
go [] = return []
go (x:xs) = do
x' <- x
xs' <- interleave xs
return (x':xs')
packFileEntry :: FilePath -- ^ Full path to find the file on the local disk
-> TarPath -- ^ Path to use for the tar Entry in the archive
-> IO Entry
packFileEntry filepath tarpath = do
mtime <- getModTime filepath
perms <- getPermissions filepath
file <- openBinaryFile filepath ReadMode
size <- hFileSize file
content <- BS.hGetContents file
return (simpleEntry tarpath (NormalFile content (fromIntegral size))) {
entryPermissions = if Permissions.executable perms
then executableFilePermissions
else ordinaryFilePermissions,
entryTime = mtime
}
packDirectoryEntry :: FilePath -- ^ Full path to find the file on the local disk
-> TarPath -- ^ Path to use for the tar Entry in the archive
-> IO Entry
packDirectoryEntry filepath tarpath = do
mtime <- getModTime filepath
return (directoryEntry tarpath) {
entryTime = mtime
}
getDirectoryContentsRecursive :: FilePath -> IO [FilePath]
getDirectoryContentsRecursive dir0 =
fmap tail (recurseDirectories dir0 [""])
recurseDirectories :: FilePath -> [FilePath] -> IO [FilePath]
recurseDirectories _ [] = return []
recurseDirectories base (dir:dirs) = unsafeInterleaveIO $ do
(files, dirs') <- collect [] [] =<< getDirectoryContents (base </> dir)
files' <- recurseDirectories base (dirs' ++ dirs)
return (dir : files ++ files')
where
collect files dirs' [] = return (reverse files, reverse dirs')
collect files dirs' (entry:entries) | ignore entry
= collect files dirs' entries
collect files dirs' (entry:entries) = do
let dirEntry = dir </> entry
dirEntry' = FilePath.Native.addTrailingPathSeparator dirEntry
isDirectory <- doesDirectoryExist (base </> dirEntry)
if isDirectory
then collect files (dirEntry':dirs') entries
else collect (dirEntry:files) dirs' entries
ignore ['.'] = True
ignore ['.', '.'] = True
ignore _ = False
getModTime :: FilePath -> IO EpochTime
getModTime path = do
time <- getModificationTime path
return $! floor $ utcTimeToPOSIXSeconds time
| IreneKnapp/Faction | faction/Distribution/Client/Tar.hs | bsd-3-clause | 31,452 | 0 | 19 | 8,749 | 6,929 | 3,671 | 3,258 | 575 | 15 |
module RemoteController where
import Frenetic.NetCore
import Frenetic.NetCore.JSON
import Frenetic.NetCore.Semantics
import Frenetic.Server
import Text.JSON.Generic
import Data.Generics
main addr = do
-- putStrLn . show . encodeJSON . MsgPolicy . PolProcessIn Any $ [ActFwd AllPorts unmodified]
remoteController addr 6634 (-1)
| frenetic-lang/netcore-1.0 | examples/RemoteController.hs | bsd-3-clause | 334 | 0 | 9 | 45 | 61 | 36 | 25 | 9 | 1 |
{-# LANGUAGE OverloadedStrings, MultiWayIf #-}
module ABFA.Zone where
-- the zone screen and data is defined
import qualified Data.List as L
import qualified Data.ByteString.Lazy as BS
import Data.Binary.Put
import Data.ByteString.Base64 (encode, decode)
import Control.Parallel.Strategies (parMap, rpar)
import Control.Monad.RWS.Strict (modify)
import ABFA.Data
import ABFA.Game
import ABFA.State
import ABFA.Map
nulltile = 0x00
-- gives an empty zone
blankZoneGrid :: State -> Int -> Int -> BS.ByteString
blankZoneGrid state x y = BS.replicate (fromIntegral (zonew*zoneh)) nulltile
where settings = stateSettings state
zonew = settingZoneW settings
zoneh = settingZoneH settings
-- generates the zone at a xy pos
generateZone :: State -> Int -> Int -> Zone
generateZone state x y = genZone state x y zc0 conts seeds rands nconts
where zc0 = blankZoneGrid state x y
wparams = stateWParams state
conts = wpConts wparams
seeds = wpSeeds wparams
rands = wpRands wparams
nconts = wpNConts wparams
zonew = settingZoneW settings
zoneh = settingZoneH settings
settings = stateSettings state
genZone :: State -> Int -> Int -> BS.ByteString -> [(Int, Int)] -> [[(Int, Int)]] -> [[(Int, Int)]] -> Int -> Zone
genZone state x y zc0 conts seeds rands nconts = Zone { latlong = (x, y)
, zonechunk = genZoneChunk state x y zc0 conts seeds rands nconts
}
genZoneChunk :: State -> Int -> Int -> BS.ByteString -> [(Int, Int)] -> [[(Int, Int)]] -> [[(Int, Int)]] -> Int -> ZoneChunk
genZoneChunk state x y zc0 conts seeds rands nconts = ZoneChunk { gbs = zgsr
, cbs = zcsr
, ebs = BS.empty
}
where zgsr = edgeZoneGrid zonew zoneh zcsr
zgs0 = initZoneGrid zonew zoneh zcsr
zcsr = initZoneCont state x y
zonew = settingZoneW settings
zoneh = settingZoneH settings
settings = stateSettings state
initZoneGrid :: Int -> Int -> BS.ByteString -> BS.ByteString
initZoneGrid zonew zoneh str = listToBS zonelist 1
where zonelist = take (zonew*zoneh) (repeat 13)
-- generates edges bordering tiles for the zone
edgeZoneGrid :: Int -> Int -> BS.ByteString -> BS.ByteString
edgeZoneGrid zonew zoneh str = listToBS (map edgeTile (L.zip5 tn tw te ts strlist)) 1
where (tn, ts, te, tw) = cardinals zonew zoneh strlist
strlist = bsToList str 1
edgeTile :: (Int, Int, Int, Int, Int) -> Int
edgeTile (tn, tw, te, ts, t)
| (tn /= t) && (tw /= t) && (te /= t) && (ts /= t) = 19
| (tn /= t) && (tw /= t) && (te /= t) = 16
| (tn /= t) && (tw /= t) && (ts /= t) = 18
| (tn /= t) && (te /= t) && (ts /= t) = 20
| (tw /= t) && (te /= t) && (ts /= t) = 22
| (tn /= t) && (tw /= t) = 6
| (tn /= t) && (te /= t) = 8
| (tn /= t) && (ts /= t) = 21
| (tw /= t) && (te /= t) = 15
| (tw /= t) && (ts /= t) = 12
| (te /= t) && (ts /= t) = 14
| (tn /= t) = 7
| (tw /= t) = 9
| (te /= t) = 11
| (ts /= t) = 13
| otherwise = 0
initZoneCont :: State -> Int -> Int -> BS.ByteString
initZoneCont state x y = listToBS (genZoneCont gridw gridh zonew zoneh x y zc0 types sizes rrands conts seeds rands nconts) 1
where conts = wpConts wparams
seeds = wpSeeds wparams
rands = wpRands wparams
rrands = wpRRands wparams
nconts = wpNConts wparams
types = wpTypes wparams
sizes = wpSizes wparams
worldgen = settingWGSettings settings
wparams = stateWParams state
settings = stateSettings state
zonew = settingZoneW settings
zoneh = settingZoneH settings
gridw = settingGridW settings
gridh = settingGridH settings
zc0 = take (zonew*zoneh) (repeat 1)
-- generates the continent list for a single zone
genZoneCont :: Int -> Int -> Int -> Int -> Int -> Int -> [Int] -> [Biome] -> [Int] -> [Int] -> [(Int, Int)] -> [[(Int, Int)]] -> [[(Int, Int)]] -> Int -> [Int]
genZoneCont _ _ _ _ _ _ zg0 _ _ _ [] [] [] _ = zg0
genZoneCont _ _ _ _ _ _ zg0 _ _ _ _ _ _ 0 = zg0
genZoneCont gridw gridh zonew zoneh x y zg0 types sizes rrands (l:ls) (k:ks) (j:js) n = do
let zg = genZoneContChunk gridw gridh zonew zoneh x y 0 n (fst l) (snd l) zg0 types sizes rrands k j
genZoneCont gridw gridh zonew zoneh x y zg types sizes rrands ls ks js (n-1)
-- generates a single continent
genZoneContChunk :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Int] -> [Biome] -> [Int] -> [Int] -> [(Int, Int)] -> [(Int, Int)] -> [Int]
genZoneContChunk _ _ _ _ _ _ _ _ _ _ zg _ _ _ [] [] = zg
genZoneContChunk gridw gridh zonew zoneh x y i c x0 y0 zg types sizes rrands (k:ks) (j:js) = do
let nzg = expandZone zonew zoneh zg
zg0 = map (genZoneContChunkRow gridw gridh zonew zoneh x y c i (fst k) (snd k) (fst j) (snd j) types sizes rrands) nzg
zg1 = stripGrid zg0
zg2 = flattenGrid zg1
genZoneContChunk gridw gridh zonew zoneh x y (i+1) c x0 y0 zg2 types sizes rrands ks js
genZoneContChunkRow :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Biome] -> [Int] -> [Int] -> ([(Int, Int)], Int) -> ([(Int, Int)], Int)
genZoneContChunkRow gridw gridh zonew zoneh x y i c w x0 y0 z0 types sizes rrands (t1, t2) = (map (genZoneContChunkTile gridw gridh zonew zoneh x y i c t2 w x0 y0 z0 types sizes rrands) t1, t2)
-- this is basically the same as the worldcode
genZoneContChunkTile :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Biome] -> [Int] -> [Int] -> (Int, Int) -> (Int, Int)
genZoneContChunkTile gridw gridh zonew zoneh x y it c j w x0 y0 z0 types sizes rrands (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 y0 z0 t' < fromIntegral(8*(maxdist-cfudge))) = (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w (x0+gridw) y0 z0 t' < fromIntegral(8*(maxdist-cfudge))) = (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 (y0+gridh) z0 t' < fromIntegral(8*(maxdist-cfudge))) = (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w (x0-gridw) y0 z0 t' < fromIntegral(8*(maxdist-cfudge))) = (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 (y0-gridh) z0 t' < fromIntegral(8*(maxdist-cfudge))) = (t, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 y0 z0 t' <= fromIntegral((maxdist)*4)) = (r, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w (x0+gridw) y0 z0 t' <= fromIntegral((maxdist)*4)) = (r, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 (y0+gridh) z0 t' <= fromIntegral((maxdist)*4)) = (r, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w (x0-gridw) y0 z0 t' <= fromIntegral((maxdist)*4)) = (r, i)
| (randstate == BValley) && (zoneDistance zonew zoneh x y i j w x0 (y0-gridh) z0 t' <= fromIntegral((maxdist)*4)) = (r, i)
| (randstate == BCrags) && (zoneDistance zonew zoneh x y i j w x0 y0 z0 t' < fromIntegral((maxdist-cfudge))) = (t, i)
| (randstate == BCrags) && (zoneDistance zonew zoneh x y i j w (x0+gridw) y0 z0 t' < fromIntegral((maxdist-cfudge))) = (t, i)
| (randstate == BCrags) && (zoneDistance zonew zoneh x y i j w x0 (y0+gridh) z0 t' < fromIntegral((maxdist-cfudge))) = (t, i)
| (randstate == BCrags) && (zoneDistance zonew zoneh x y i j w (x0-gridw) y0 z0 t' < fromIntegral((maxdist-cfudge))) = (t, i)
| (randstate == BCrags) && (zoneDistance zonew zoneh x y i j w x0 (y0-gridh) z0 t' < fromIntegral((maxdist-cfudge))) = (t, i)
| zoneDistance zonew zoneh x y i j w x0 y0 z0 t' <= fromIntegral(maxdist) = (r, i)
| zoneDistance zonew zoneh x y i j w (x0+gridw) y0 z0 t' <= fromIntegral(maxdist) = (r, i)
| zoneDistance zonew zoneh x y i j w x0 (y0+gridh) z0 t' <= fromIntegral(maxdist) = (r, i)
| zoneDistance zonew zoneh x y i j w (x0-gridw) y0 z0 t' <= fromIntegral(maxdist) = (r, i)
| zoneDistance zonew zoneh x y i j w x0 (y0-gridh) z0 t' <= fromIntegral(maxdist) = (r, i)
| otherwise = (t, i)
where
randstate = types !! c
r = biomeToInt randstate
maxdist = 1000 * ((sizes) !! c)
cfudge = 2 * ((rrands !! c) - 1)
t' = fromIntegral t
-- a simple conversion function to abstract biome numbers
intToBiome :: Int -> Biome
intToBiome 1 = BSea
intToBiome 2 = BShallows
intToBiome 3 = BDeeps
intToBiome 4 = BValley
intToBiome 5 = BCrags
intToBiome 6 = BPlains
intToBiome 7 = BFields
intToBiome 8 = BWastes
intToBiome 9 = BSteeps
intToBiome 10 = BPeaks
intToBiome _ = BNULL
biomeToInt :: Biome -> Int
biomeToInt BSea = 1
biomeToInt BShallows = 2
biomeToInt BDeeps = 3
biomeToInt BValley = 4
biomeToInt BCrags = 5
biomeToInt BPlains = 6
biomeToInt BFields = 7
biomeToInt BWastes = 8
biomeToInt BSteeps = 9
biomeToInt BPeaks = 10
biomeToInt _ = 0
| coghex/abridgefaraway | src/ABFA/Zone.hs | bsd-3-clause | 10,403 | 0 | 23 | 3,646 | 4,151 | 2,191 | 1,960 | 152 | 1 |
{-# LANGUAGE DoAndIfThenElse #-}
module TMChunkedQueue (
tests
) where
import Control.Monad.STM (atomically)
import Data.Monoid
import Control.Concurrent.STM.TMChunkedQueue
import TestUtils
import qualified TChunkedQueue
import Test.Tasty
import Test.Tasty.HUnit
-- | Convenience specialization to avoid "Default Constraint" warnings
settleTester :: [QueueAction Int] -> [Maybe [Int]] -> Assertion
settleTester = testActions $
TestableChunkedQueue
newTMChunkedQueueIO
(drainAndSettleTMChunkedQueue 20000)
((fmap collapseMaybe) . atomically . tryDrainTMChunkedQueue)
writeTMChunkedQueue
closeTMChunkedQueue
where
collapseMaybe Nothing = mempty
collapseMaybe (Just xs) = xs
timeoutTester :: Int -> [QueueAction Int] -> [Maybe [Int]] -> Assertion
timeoutTester timeout = testActions $
TestableChunkedQueue
newTMChunkedQueueIO
(drainWithTimeoutTMChunkedQueue timeout)
((fmap collapseMaybe) . atomically . tryDrainTMChunkedQueue)
writeTMChunkedQueue
closeTMChunkedQueue
where
collapseMaybe Nothing = mempty
collapseMaybe (Just xs) = xs
shortPause, longPause :: Int
shortPause = 10000
longPause = 60000
testClosing :: ([QueueAction Int] -> [Maybe [Int]] -> Assertion) -> [TestTree]
testClosing assertActions =
[ testCase "Two" $ assertActions [
Enqueue [0],
Close,
Enqueue [1]]
$ expect [Just [0]]
, testCase "Two with wait" $ assertActions [
Enqueue [0],
Wait shortPause,
Close,
Enqueue [1]]
$ expect [Just [0]]
]
where
expect = id
tests :: [TestTree]
tests =
[ testGroup "Settle"
[ testGroup "Non-Closing" $ TChunkedQueue.testWith settleTester
, testGroup "Closing" $ testClosing settleTester ]
, testGroup "Timeout"
[ testGroup "Non-Closing"
[ testCase "One" $ timeoutTester shortPause [
Enqueue [0],
Wait longPause,
Enqueue [1]]
$ expect [Just [0], Just [1]]
, testCase "Two" $ timeoutTester longPause [
Enqueue [0],
Wait shortPause,
Enqueue [1],
Wait longPause,
Enqueue [2]]
$ expect [Just [0, 1], Just [2]]
, testCase "Many" $ timeoutTester longPause (
concatMap (\i -> [Enqueue [i], Wait shortPause]) [1..10]
)
$ expect [Just [1..6], Just [7..10]]
]
, testGroup "Closing" $ testClosing $ timeoutTester shortPause
]
]
where
expect = id
| KholdStare/stm-chunked-queues | tests/TMChunkedQueue.hs | bsd-3-clause | 2,853 | 0 | 19 | 995 | 740 | 394 | 346 | 71 | 2 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.RobustnessCore
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.RobustnessCore (
-- * Extension Support
glGetARBRobustness,
gl_ARB_robustness,
-- * Enums
pattern GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB,
pattern GL_GUILTY_CONTEXT_RESET_ARB,
pattern GL_INNOCENT_CONTEXT_RESET_ARB,
pattern GL_LOSE_CONTEXT_ON_RESET_ARB,
pattern GL_NO_ERROR,
pattern GL_NO_RESET_NOTIFICATION_ARB,
pattern GL_RESET_NOTIFICATION_STRATEGY_ARB,
pattern GL_UNKNOWN_CONTEXT_RESET_ARB,
-- * Functions
glGetGraphicsResetStatusARB,
glGetnCompressedTexImageARB,
glGetnTexImageARB,
glGetnUniformdvARB,
glGetnUniformfvARB,
glGetnUniformivARB,
glGetnUniformuivARB,
glReadnPixelsARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/ARB/RobustnessCore.hs | bsd-3-clause | 1,170 | 0 | 5 | 150 | 113 | 78 | 35 | 23 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Main where
import Control.Concurrent (threadDelay)
import Control.Monad
import Control.Monad.IO.Class
import Data.Default
import Data.Time
import System.IO (stdout)
import System.Log.Formatter (simpleLogFormatter)
import System.Log.Handler (setFormatter)
import System.Log.Handler.Simple (streamHandler)
import System.Log.Logger
import API.IB
-- -----------------------------------------------------------------------------
-- Reference data
conES :: IBContract
conES = future "ES" "ESZ6" (Just $ fromGregorian 2016 12 16) GLOBEX "USD"
-- -----------------------------------------------------------------------------
-- Requests
requests :: IB ()
requests = do
display "Starting"
displayStatus
connect
reqConData
reqMktData
recvP 10
displayStatus
disconnect
delay 5
connect
reqMktData
recvP 10
delay 5
stop
displayStatus
display "Finished"
where
reqConData = requestContractData conES
reqMktData = requestMarketData conES [] False
displayStatus = status >>= display . show
recvP n = replicateM_ n $ recv >>= display . show
delay t = liftIO $ threadDelay (t*1000000)
display = liftIO . putStrLn
-- -----------------------------------------------------------------------------
-- Main
main :: IO ()
main = do
handler <- streamHandler stdout DEBUG >>= \h -> return $
setFormatter h $ simpleLogFormatter "$time $loggername $prio: $msg"
updateGlobalLogger rootLoggerName (setLevel DEBUG . setHandlers [handler])
runIB def requests
| cmahon/interactive-brokers | executable/Requests-Simple.hs | bsd-3-clause | 1,735 | 0 | 12 | 394 | 388 | 198 | 190 | 46 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : EasyGL.Obj.Obj2IM
-- Copyright : Copyright (c) 2017, Jose Daniel Duran Toro
-- License : BSD3
--
-- Maintainer : Jose Daniel Duran Toro <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- Functions required to transform a Obj to an EasyGL Indexed Model.
--
--------------------------------------------------------------------------------
module EasyGL.Obj.Obj2IM (
toIndexedModel,
groupToIndexedModel
)
where
import Control.Monad.Reader
import Control.Monad.ST
import Control.Monad.State.Lazy
import Data.Foldable (toList)
import qualified Data.Map.Strict as Map
import qualified Data.Maybe as M
import qualified Data.Sequence as Seq
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Storable as VS
import qualified EasyGL.IndexedModel as IM
import EasyGL.Obj.ObjData
import Graphics.Rendering.OpenGL hiding (get)
defaultNormal :: Maybe (Vector3 GLfloat) -> Vector3 GLfloat
defaultNormal (Just x) = x
defaultNormal Nothing = Vector3 0 0 0
defaultTexture :: Maybe (Vector2 GLfloat) -> Vector2 GLfloat
defaultTexture (Just x) = x
defaultTexture Nothing = Vector2 0 0
-- | A needed correction to all textureCoord, as image loading library loads everything upside down, and it is easier to correct here.
easyGLVector2Correction :: Vector2 GLfloat -> Vector2 GLfloat
easyGLVector2Correction (Vector2 x y) = Vector2 x (1-y)
-- | Turns every group within an Obj into an IndexedModel.
toIndexedModel :: Obj -> [IM.IndexedModel]
toIndexedModel = map groupToIndexedModel . groups
groupToIndexedModel :: Group -> IM.IndexedModel
groupToIndexedModel g
| M.isNothing norm0 && M.isNothing tex0 = IM.IndexedModel (V.convert vert0) VS.empty VS.empty (V.convert index0)
| M.isJust norm0 && M.isNothing tex0 = runST $ do
(newVert,newNorms,newIndex) <- rearrangeCaller defaultNormal vert0 index0 (V.fromList . toList . M.fromJust $ norm0) normIndex0
return $ IM.IndexedModel (V.convert newVert) (V.convert newNorms) VS.empty (V.convert newIndex)
| M.isNothing norm0 && M.isJust tex0 = runST $ do
(newVert,newText,newIndex) <- rearrangeCaller defaultTexture vert0 index0 (V.fromList . toList . M.fromJust $ tex0) textIndex0
return $ IM.IndexedModel (V.convert newVert) VS.empty (V.convert . V.map easyGLVector2Correction $ newText) (V.convert newIndex)
| M.isJust norm0 && M.isJust tex0 = runST $ do
(newVert,newNorms,newIndex) <- rearrangeCaller defaultNormal vert0 index0 (V.fromList . toList . M.fromJust $ norm0) normIndex0
let newThing = V.zip newVert newNorms
(newThing,newText,newIndex) <- rearrangeCaller defaultTexture newThing newIndex (V.fromList . toList . M.fromJust $ tex0) textIndex0
let (newVert,newNorms) = V.unzip newThing
return $ IM.IndexedModel (V.convert newVert) (V.convert newNorms) (V.convert . V.map easyGLVector2Correction $ newText) (V.convert newIndex)
| otherwise = IM.emptyIndexedModel
where
vert0 = V.fromList . toList $ groupVertices g
norm0 = groupNormals g
tex0 = groupTextureCoord g
(index0,textIndex0,normIndex0) = allIndexesV g
rearrangeCaller :: (Ord a,Ord b,Integral c,Num c) => (Maybe b -> b) -> V.Vector a -> V.Vector c -> V.Vector b -> V.Vector c -> ST s (V.Vector a,V.Vector b,V.Vector c)
rearrangeCaller f vectorA indexA vectorB indexB = do
mutableIndex <- V.thaw indexA
acc <- VM.replicate (V.length vectorA) Nothing
let reader = RearrangeRead vectorA vectorB acc mutableIndex indexB
(RearrangeState _ extraA extraB _) <- runReaderT (execStateT rearrange defaultRearrangeState) reader
freezed <- V.freeze acc
let returnA = vectorA V.++ (V.fromList . toList $ extraA)
returnB = V.map f freezed V.++ (V.fromList . toList $ extraB)
returnC <- V.freeze mutableIndex
return (returnA,returnB,returnC)
data RearrangeState a b c = RearrangeState {
current :: Int,
extraA :: Seq.Seq a,
extraB :: Seq.Seq b,
locator :: Map.Map (a,b) c
}
defaultRearrangeState :: RearrangeState a b c
defaultRearrangeState = RearrangeState 0 Seq.empty Seq.empty Map.empty
data RearrangeRead a b c s = RearrangeRead {
readVetorA :: V.Vector a,
readVetorB :: V.Vector b,
resulVector :: VM.MVector s (Maybe b),
indexA :: VM.MVector s c,
indexB :: V.Vector c
}
type RearrangeM a b c s = StateT (RearrangeState a b c) (ReaderT (RearrangeRead a b c s) (ST s)) ()
rearrange :: (Ord a,Ord b,Integral c,Num c) => RearrangeM a b c s
rearrange = do
readdata <- ask
state <- get
unless (current state == VM.length (indexA readdata)) $ do
currentIndexA <- VM.read (indexA readdata) (fromIntegral $ current state)
let currentIndexB = indexB readdata V.! fromIntegral (current state)
currentA = readVetorA readdata V.! fromIntegral currentIndexA
currentB = readVetorB readdata V.! fromIntegral currentIndexB
currentMaybeB <- VM.read (resulVector readdata) (fromIntegral currentIndexA)
if M.isNothing currentMaybeB then
VM.write (resulVector readdata) (fromIntegral currentIndexA) (Just currentB)
else
unless (currentB == M.fromJust currentMaybeB) $ do
let search = Map.lookup (currentA,currentB) $ locator state
case search of
Just x -> VM.write (indexA readdata) (fromIntegral $ current state) x
Nothing -> do
let newIndex = fromIntegral $ V.length (readVetorA readdata) + Seq.length (extraA state)
VM.write (indexA readdata) (fromIntegral $ current state) newIndex
modify' (\s-> s{
extraA=extraA s Seq.|> currentA,
extraB=extraB s Seq.|> currentB,
locator=Map.insert (currentA,currentB) newIndex (locator s)
}
)
modify' (\s->s{current=current state + 1})
rearrange
| JoseD92/EasyGL | src/EasyGL/Obj/Obj2IM.hs | bsd-3-clause | 6,207 | 0 | 26 | 1,414 | 1,949 | 997 | 952 | 96 | 3 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_maintenance3 - device extension
--
-- == VK_KHR_maintenance3
--
-- [__Name String__]
-- @VK_KHR_maintenance3@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 169
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1>
--
-- [__Contact__]
--
-- - Jeff Bolz
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_maintenance3] @jeffbolznv%0A<<Here describe the issue or question you have about the VK_KHR_maintenance3 extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-09-05
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.1 Core
--
-- [__Contributors__]
--
-- - Jeff Bolz, NVIDIA
--
-- == Description
--
-- @VK_KHR_maintenance3@ adds a collection of minor features that were
-- intentionally left out or overlooked from the original Vulkan 1.0
-- release.
--
-- The new features are as follows:
--
-- - A limit on the maximum number of descriptors that are supported in a
-- single descriptor set layout. Some implementations have a limit on
-- the total size of descriptors in a set, which cannot be expressed in
-- terms of the limits in Vulkan 1.0.
--
-- - A limit on the maximum size of a single memory allocation. Some
-- platforms have kernel interfaces that limit the maximum size of an
-- allocation.
--
-- == Promotion to Vulkan 1.1
--
-- All functionality in this extension is included in core Vulkan 1.1, with
-- the KHR suffix omitted. The original type, enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Commands
--
-- - 'getDescriptorSetLayoutSupportKHR'
--
-- == New Structures
--
-- - 'DescriptorSetLayoutSupportKHR'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceMaintenance3PropertiesKHR'
--
-- == New Enum Constants
--
-- - 'KHR_MAINTENANCE3_EXTENSION_NAME'
--
-- - 'KHR_MAINTENANCE3_SPEC_VERSION'
--
-- - 'KHR_MAINTENANCE_3_EXTENSION_NAME'
--
-- - 'KHR_MAINTENANCE_3_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR'
--
-- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR'
--
-- == Version History
--
-- - Revision 1, 2017-08-22
--
-- == See Also
--
-- 'DescriptorSetLayoutSupportKHR',
-- 'PhysicalDeviceMaintenance3PropertiesKHR',
-- 'getDescriptorSetLayoutSupportKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_maintenance3 Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_maintenance3 ( pattern KHR_MAINTENANCE3_SPEC_VERSION
, pattern KHR_MAINTENANCE3_EXTENSION_NAME
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR
, pattern STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR
, getDescriptorSetLayoutSupportKHR
, PhysicalDeviceMaintenance3PropertiesKHR
, DescriptorSetLayoutSupportKHR
, KHR_MAINTENANCE_3_SPEC_VERSION
, pattern KHR_MAINTENANCE_3_SPEC_VERSION
, KHR_MAINTENANCE_3_EXTENSION_NAME
, pattern KHR_MAINTENANCE_3_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance3 (getDescriptorSetLayoutSupport)
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance3 (DescriptorSetLayoutSupport)
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance3 (PhysicalDeviceMaintenance3Properties)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES))
-- No documentation found for TopLevel "VK_KHR_MAINTENANCE3_SPEC_VERSION"
pattern KHR_MAINTENANCE3_SPEC_VERSION = KHR_MAINTENANCE_3_SPEC_VERSION
-- No documentation found for TopLevel "VK_KHR_MAINTENANCE3_EXTENSION_NAME"
pattern KHR_MAINTENANCE3_EXTENSION_NAME = KHR_MAINTENANCE_3_EXTENSION_NAME
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR"
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR"
pattern STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR = STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT
-- No documentation found for TopLevel "vkGetDescriptorSetLayoutSupportKHR"
getDescriptorSetLayoutSupportKHR = getDescriptorSetLayoutSupport
-- No documentation found for TopLevel "VkPhysicalDeviceMaintenance3PropertiesKHR"
type PhysicalDeviceMaintenance3PropertiesKHR = PhysicalDeviceMaintenance3Properties
-- No documentation found for TopLevel "VkDescriptorSetLayoutSupportKHR"
type DescriptorSetLayoutSupportKHR = DescriptorSetLayoutSupport
type KHR_MAINTENANCE_3_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_KHR_MAINTENANCE_3_SPEC_VERSION"
pattern KHR_MAINTENANCE_3_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_MAINTENANCE_3_SPEC_VERSION = 1
type KHR_MAINTENANCE_3_EXTENSION_NAME = "VK_KHR_maintenance3"
-- No documentation found for TopLevel "VK_KHR_MAINTENANCE_3_EXTENSION_NAME"
pattern KHR_MAINTENANCE_3_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_MAINTENANCE_3_EXTENSION_NAME = "VK_KHR_maintenance3"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_KHR_maintenance3.hs | bsd-3-clause | 6,460 | 0 | 8 | 1,253 | 378 | 277 | 101 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Data.Streaming.Network.Internal
( ServerSettings (..)
, ClientSettings (..)
, HostPreference (..)
, Message (..)
, AppData (..)
#if !WINDOWS
, ServerSettingsUnix (..)
, ClientSettingsUnix (..)
, AppDataUnix (..)
#endif
) where
import Data.String (IsString (..))
import Data.ByteString (ByteString)
import Network.Socket (Socket, SockAddr, Family)
-- | Settings for a TCP server. It takes a port to listen on, and an optional
-- hostname to bind to.
data ServerSettings = ServerSettings
{ serverPort :: !Int
, serverHost :: !HostPreference
, serverSocket :: !(Maybe Socket) -- ^ listening socket
, serverAfterBind :: !(Socket -> IO ())
, serverNeedLocalAddr :: !Bool
, serverReadBufferSize :: !Int
}
-- | Settings for a TCP client, specifying how to connect to the server.
data ClientSettings = ClientSettings
{ clientPort :: !Int
, clientHost :: !ByteString
, clientAddrFamily :: !Family
, clientReadBufferSize :: !Int
}
-- | Which host to bind.
--
-- Note: The @IsString@ instance recognizes the following special values:
--
-- * @*@ means @HostAny@
--
-- * @*4@ means @HostIPv4@
--
-- * @!4@ means @HostIPv4Only@
--
-- * @*6@ means @HostIPv6@
--
-- * @!6@ means @HostIPv6Only@
--
-- Any other values is treated as a hostname. As an example, to bind to the
-- IPv4 local host only, use \"127.0.0.1\".
data HostPreference =
HostAny
| HostIPv4
| HostIPv4Only
| HostIPv6
| HostIPv6Only
| Host String
deriving (Eq, Ord, Show, Read)
instance IsString HostPreference where
fromString "*" = HostAny
fromString "*4" = HostIPv4
fromString "!4" = HostIPv4Only
fromString "*6" = HostIPv6
fromString "!6" = HostIPv6Only
fromString s = Host s
#if !WINDOWS
-- | Settings for a Unix domain sockets server.
data ServerSettingsUnix = ServerSettingsUnix
{ serverPath :: !FilePath
, serverAfterBindUnix :: !(Socket -> IO ())
, serverReadBufferSizeUnix :: !Int
}
-- | Settings for a Unix domain sockets client.
data ClientSettingsUnix = ClientSettingsUnix
{ clientPath :: !FilePath
, clientReadBufferSizeUnix :: !Int
}
-- | The data passed to a Unix domain sockets @Application@.
data AppDataUnix = AppDataUnix
{ appReadUnix :: !(IO ByteString)
, appWriteUnix :: !(ByteString -> IO ())
}
#endif
-- | Representation of a single UDP message
data Message = Message { msgData :: {-# UNPACK #-} !ByteString
, msgSender :: !SockAddr
}
-- | The data passed to an @Application@.
data AppData = AppData
{ appRead' :: !(IO ByteString)
, appWrite' :: !(ByteString -> IO ())
, appSockAddr' :: !SockAddr
, appLocalAddr' :: !(Maybe SockAddr)
, appCloseConnection' :: !(IO ())
, appRawSocket' :: Maybe Socket
}
| phadej/streaming-commons | Data/Streaming/Network/Internal.hs | mit | 2,855 | 0 | 13 | 661 | 559 | 333 | 226 | 105 | 0 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ja-JP">
<title>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_ja_JP/helpset_ja_JP.hs | apache-2.0 | 970 | 84 | 52 | 158 | 394 | 208 | 186 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Config where
import qualified Data.Bifunctor as BF
import Data.ByteString as BS
import qualified Data.List as List
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Data.Text hiding (empty)
import qualified Data.Text as T
import Data.Yaml (FromJSON (..), (.:), (.:?))
import qualified Data.Yaml as Y
import qualified ShellUtil
import qualified System.IO as SIO
import qualified Turtle as Tu
data ProcessedConfig =
ProcessedConfig
{ rawConfig :: Config
, inboxHandlerCommands :: CustomHandlers
, inboxRefileDests :: RefileDests
, gitHandlerCommands :: !CustomGitHandlers
} deriving (Eq, Show)
type CustomHandlers = M.Map T.Text InboxHandlerCommandSpec
-- / key is the letter of command
type CustomGitHandlers = M.Map T.Text GitHandlerCommandSpec
type RefileDests = M.Map T.Text InboxHandlerRefileDestSpec
data Config =
Config
{ locations :: [LocationSpec]
, handlers :: HandlerSpecs
} deriving (Eq, Show)
data LocationSpec
= GitLoc GitLocation
| InboxLoc InboxLocation
deriving (Eq, Show)
data GitLocation = GitLocation
{ gitLocation :: Text
, gitForce :: Bool
}
deriving (Eq, Show)
data InboxLocation = InboxLocation
{ inboxLocation :: Text
, ignoredFiles :: [Text]
}
deriving (Eq, Show)
data HandlerSpecs
= HandlerSpecs
{ handlerSpecInbox :: Maybe InboxHandlerSpec
, handlerSpecGit :: Maybe GitHandlerSpec
}
deriving (Eq, Show)
newtype GitHandlerSpec
= GitHandlerSpec {gitCommands :: Maybe [GitHandlerCommandSpec]}
deriving (Eq, Show)
data GitHandlerCommandSpec =
GitHandlerCommandSpec
{ gitCmdName :: !Text
, gitCmdSpecCmd :: !Text
, gitCmdKey :: !Text
} deriving (Eq, Show)
data InboxHandlerSpec =
InboxHandlerSpec
{ commands :: Maybe [InboxHandlerCommandSpec]
, refileDests :: Maybe [InboxHandlerRefileDestSpec]
} deriving (Eq, Show)
data InboxHandlerCommandSpec =
InboxHandlerCommandSpec
{ cmdName :: Text
, cmdSpecCmd :: Text
, cmdKey :: Text
} deriving (Eq, Show)
data InboxHandlerRefileDestSpec =
InboxHandlerRefileDestSpec
{ refileDestName :: Text
, refileDestKey :: Text
, refileDestDir :: Text
} deriving (Eq, Show)
instance FromJSON Config where
parseJSON (Y.Object v) =
Config <$>
v .: "locations" <*>
v .: "handlers"
parseJSON _ = fail "error parsing config"
instance FromJSON LocationSpec where
parseJSON = Y.withObject "LocationSpec" $ \v -> do
type' <- v .: "type"
location' <- v .: "location"
force <- v .:? "force"
ignoredFiles' <- v .:? "ignored_files"
case (T.unpack $ type') of
"git" -> return $ GitLoc $ GitLocation location' (fromMaybe False force)
"inbox" -> return $ InboxLoc $ InboxLocation location' (fromMaybe [] ignoredFiles')
_ -> fail $ "Location type must be either 'git' or 'inbox', found '" <> T.unpack type' <> "'"
instance FromJSON HandlerSpecs where
parseJSON (Y.Object v) =
HandlerSpecs <$>
v .:? "inbox" <*>
v .:? "git"
parseJSON _ = fail "error parsing handler specs"
instance FromJSON InboxHandlerSpec where
parseJSON (Y.Object v) =
InboxHandlerSpec <$>
v .:? "commands" <*>
v .:? "refile_dests"
parseJSON _ = fail "error parsing inbox handler spec"
instance FromJSON GitHandlerSpec where
parseJSON (Y.Object v) =
GitHandlerSpec <$>
v .:? "commands"
parseJSON _ = fail "error parsing git handler spec"
instance FromJSON GitHandlerCommandSpec where
parseJSON (Y.Object v) =
GitHandlerCommandSpec <$>
v .: "name" <*>
v .: "cmd" <*>
v .: "key"
parseJSON _ = fail "error parsing git handler command"
instance FromJSON InboxHandlerCommandSpec where
parseJSON (Y.Object v) =
InboxHandlerCommandSpec <$>
v .: "name" <*>
v .: "cmd" <*>
v .: "key"
parseJSON _ = fail "error parsing inbox handler command"
instance FromJSON InboxHandlerRefileDestSpec where
parseJSON (Y.Object v) =
InboxHandlerRefileDestSpec <$>
v .: "name" <*>
v .: "char" <*>
v .: "dir"
parseJSON _ = fail "error parsing inbox handler command"
getConfigFilename :: Tu.Shell SIO.FilePath
getConfigFilename = fmap (Tu.fromString . T.unpack . Tu.lineToText) (ShellUtil.expandGlob "~/.reddup.yml")
loadConfig :: Tu.Shell (Either String Config)
loadConfig = do
configFilename <- getConfigFilename
configContents <- Tu.liftIO $ (BS.readFile configFilename :: IO BS.ByteString)
let eresults = Y.decodeEither' configContents :: Either Y.ParseException Config
return (BF.first Y.prettyPrintParseException eresults)
data ConfigError
= ErrorCmdHandlerKeyWrongNumChars InboxHandlerCommandSpec
| ErrorRefileDestKeyWrongNumChars InboxHandlerRefileDestSpec
| ErrorGitCmdHandlerKeyWrongNumChars GitHandlerCommandSpec
deriving (Eq, Show)
processGitCommandHandlers ::
Maybe [GitHandlerCommandSpec] ->
([ConfigError], CustomGitHandlers)
processGitCommandHandlers maybeCmdSpecs =
let
cmdSpecs :: [GitHandlerCommandSpec]
cmdSpecs = fromMaybe [] maybeCmdSpecs
hasRightNumChars spec = (List.length $ T.unpack $ (gitCmdKey spec) ) > 0
(rightNumCharsCmds, wrongNumCharsCmds) = List.partition hasRightNumChars cmdSpecs
errors =
(ErrorGitCmdHandlerKeyWrongNumChars <$> wrongNumCharsCmds)
toPair spec = (gitCmdKey spec, spec)
successes = toPair <$> rightNumCharsCmds
in
(errors, M.fromList successes)
processInboxCommandHandlers ::
Maybe [InboxHandlerCommandSpec] ->
([ConfigError], CustomHandlers)
processInboxCommandHandlers maybeCmdSpecs =
let
cmdSpecs :: [InboxHandlerCommandSpec]
cmdSpecs = fromMaybe [] maybeCmdSpecs
hasRightNumChars spec = (List.length $ T.unpack $ (cmdKey spec) ) > 0
(rightNumCharsCmds,
wrongNumCharsCmds) = List.partition hasRightNumChars cmdSpecs
errors =
(ErrorCmdHandlerKeyWrongNumChars <$> wrongNumCharsCmds)
toPair spec = (cmdKey spec, spec)
successes = toPair <$> rightNumCharsCmds
in
(errors, M.fromList successes)
processConfig :: Config -> Either [ConfigError] ProcessedConfig
processConfig config =
let
inboxHandlerCommands' :: Maybe [InboxHandlerCommandSpec]
inboxHandlerCommands' = commands =<< handlerSpecInbox (handlers config)
(ihcErrors, ihcSuccesses) = processInboxCommandHandlers inboxHandlerCommands'
inboxRefileDests' :: Maybe [InboxHandlerRefileDestSpec]
inboxRefileDests' = refileDests =<< handlerSpecInbox (handlers config)
(refileErrors, refileDests') = processRefileDests inboxRefileDests'
gitHandlerCommands' :: Maybe [GitHandlerCommandSpec]
gitHandlerCommands' = gitCommands =<< handlerSpecGit (handlers config)
(ghcErrors, ghcSuccesses) = processGitCommandHandlers gitHandlerCommands'
allErrors = ihcErrors ++ refileErrors ++ ghcErrors
newConfig = ProcessedConfig
{ rawConfig = config
, inboxHandlerCommands = ihcSuccesses
, inboxRefileDests = refileDests'
, gitHandlerCommands = ghcSuccesses
}
in
if List.length allErrors > 0 then
Left allErrors
else
Right newConfig
moreThanOneChar :: String -> Bool
moreThanOneChar str =
List.length str > 0
processRefileDests :: Maybe [InboxHandlerRefileDestSpec] -> ([ConfigError], RefileDests)
processRefileDests maybeRefileDestSpecs =
let
refileSpecs :: [InboxHandlerRefileDestSpec]
refileSpecs = maybe [] id maybeRefileDestSpecs
hasRightNumChars :: InboxHandlerRefileDestSpec -> Bool
hasRightNumChars spec = moreThanOneChar $ T.unpack $ refileDestKey spec
(rightNumCharsCmds,
wrongNumCharsCmds) = List.partition hasRightNumChars refileSpecs
errors = ErrorRefileDestKeyWrongNumChars <$> wrongNumCharsCmds
toPair spec = (refileDestKey spec, spec)
successes = toPair <$> rightNumCharsCmds
in
(errors, M.fromList successes)
configErrorsDisplay :: [ConfigError] -> Text
configErrorsDisplay ce =
foldMap configErrorDisplay ce
configErrorDisplay :: ConfigError -> Text
configErrorDisplay ce =
case ce of
ErrorCmdHandlerKeyWrongNumChars handlerSpec ->
let
cmdName' = T.pack $ show $ cmdName handlerSpec
cmdKey' = T.pack $ show $ cmdKey handlerSpec
in
"key for command " <>
cmdName' <>
", key value is " <>
cmdKey' <>
", key must be at least one character long.\n"
ErrorRefileDestKeyWrongNumChars handlerSpec ->
let
name = T.pack $ show $ refileDestName handlerSpec
key = T.pack $ show $ refileDestKey handlerSpec
in
"key for refile destination " <>
name <>
", key value is " <>
key <>
", key must be at least one character long."
ErrorGitCmdHandlerKeyWrongNumChars handlerSpec ->
let
cmdName' = T.pack $ show $ gitCmdName handlerSpec
cmdKey' = T.pack $ show $ gitCmdKey handlerSpec
in
"key for command " <>
cmdName' <>
", key value is " <>
cmdKey' <>
", key must be at least one character long.\n"
| joelmccracken/git-stuff | src/Config.hs | bsd-3-clause | 9,261 | 0 | 17 | 2,082 | 2,256 | 1,203 | 1,053 | 246 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- Load information on package sources
module Stack.Build.Source
( loadSourceMap
, SourceMap
, PackageSource (..)
, localFlags
, getLocalPackageViews
, loadLocalPackage
, parseTargetsFromBuildOpts
) where
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Exception (assert, catch)
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import Crypto.Hash (Digest, SHA256)
import Crypto.Hash.Conduit (sinkHash)
import qualified Data.ByteString as S
import Data.Byteable (toBytes)
import Data.Conduit (($$), ZipSink (..))
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Either
import Data.Function
import qualified Data.HashSet as HashSet
import Data.List
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Distribution.Package (pkgName, pkgVersion)
import Distribution.PackageDescription (GenericPackageDescription, package, packageDescription)
import qualified Distribution.PackageDescription as C
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.IO
import Prelude
import Stack.Build.Cache
import Stack.Build.Target
import Stack.BuildPlan (loadMiniBuildPlan, shadowMiniBuildPlan,
parseCustomMiniBuildPlan)
import Stack.Constants (wiredInPackages)
import Stack.Package
import Stack.PackageIndex
import Stack.Types
import System.Directory
import System.IO (withBinaryFile, IOMode (ReadMode))
import System.IO.Error (isDoesNotExistError)
loadSourceMap :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env)
=> NeedTargets
-> BuildOpts
-> m ( Map PackageName SimpleTarget
, MiniBuildPlan
, [LocalPackage]
, Set PackageName -- non-local targets
, SourceMap
)
loadSourceMap needTargets bopts = do
bconfig <- asks getBuildConfig
rawLocals <- getLocalPackageViews
(mbp0, cliExtraDeps, targets) <- parseTargetsFromBuildOpts needTargets bopts
menv <- getMinimalEnvOverride
caches <- getPackageCaches menv
let latestVersion = Map.fromListWith max $ map toTuple $ Map.keys caches
-- Extend extra-deps to encompass targets requested on the command line
-- that are not in the snapshot.
extraDeps0 <- extendExtraDeps
(bcExtraDeps bconfig)
cliExtraDeps
(Map.keysSet $ Map.filter (== STUnknown) targets)
latestVersion
locals <- mapM (loadLocalPackage bopts targets) $ Map.toList rawLocals
checkFlagsUsed bopts locals extraDeps0 (mbpPackages mbp0)
let
-- loadLocals returns PackageName (foo) and PackageIdentifier (bar-1.2.3) targets separately;
-- here we combine them into nonLocalTargets. This is one of the
-- return values of this function.
nonLocalTargets :: Set PackageName
nonLocalTargets =
Map.keysSet $ Map.filter (not . isLocal) targets
where
isLocal (STLocalComps _) = True
isLocal STLocalAll = True
isLocal STUnknown = False
isLocal STNonLocal = False
shadowed = Map.keysSet rawLocals <> Map.keysSet extraDeps0
(mbp, extraDeps1) = shadowMiniBuildPlan mbp0 shadowed
-- Add the extra deps from the stack.yaml file to the deps grabbed from
-- the snapshot
extraDeps2 = Map.union
(Map.map (\v -> (v, Map.empty)) extraDeps0)
(Map.map (\mpi -> (mpiVersion mpi, mpiFlags mpi)) extraDeps1)
-- Overwrite any flag settings with those from the config file
extraDeps3 = Map.mapWithKey
(\n (v, f) -> PSUpstream v Local $
case ( Map.lookup (Just n) $ boptsFlags bopts
, Map.lookup Nothing $ boptsFlags bopts
, Map.lookup n $ bcFlags bconfig
) of
-- Didn't have any flag overrides, fall back to the flags
-- defined in the snapshot.
(Nothing, Nothing, Nothing) -> f
-- Either command line flag for this package, general
-- command line flag, or flag in stack.yaml is defined.
-- Take all of those and ignore the snapshot flags.
(x, y, z) -> Map.unions
[ fromMaybe Map.empty x
, fromMaybe Map.empty y
, fromMaybe Map.empty z
])
extraDeps2
let sourceMap = Map.unions
[ Map.fromList $ flip map locals $ \lp ->
let p = lpPackage lp
in (packageName p, PSLocal lp)
, extraDeps3
, flip fmap (mbpPackages mbp) $ \mpi ->
(PSUpstream (mpiVersion mpi) Snap (mpiFlags mpi))
] `Map.difference` Map.fromList (map (, ()) (HashSet.toList wiredInPackages))
return (targets, mbp, locals, nonLocalTargets, sourceMap)
-- | Use the build options and environment to parse targets.
parseTargetsFromBuildOpts
:: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env)
=> NeedTargets
-> BuildOpts
-> m (MiniBuildPlan, M.Map PackageName Version, M.Map PackageName SimpleTarget)
parseTargetsFromBuildOpts needTargets bopts = do
bconfig <- asks getBuildConfig
mbp0 <-
case bcResolver bconfig of
ResolverSnapshot snapName -> do
$logDebug $ "Checking resolver: " <> renderSnapName snapName
loadMiniBuildPlan snapName
ResolverCompiler _ -> do
-- We ignore the resolver version, as it might be
-- GhcMajorVersion, and we want the exact version
-- we're using.
version <- asks (envConfigCompilerVersion . getEnvConfig)
return MiniBuildPlan
{ mbpCompilerVersion = version
, mbpPackages = Map.empty
}
ResolverCustom _ url -> do
stackYamlFP <- asks $ bcStackYaml . getBuildConfig
parseCustomMiniBuildPlan stackYamlFP url
rawLocals <- getLocalPackageViews
workingDir <- getWorkingDir
let snapshot = mpiVersion <$> mbpPackages mbp0
flagExtraDeps <- convertSnapshotToExtra
snapshot
(bcExtraDeps bconfig)
(catMaybes $ Map.keys $ boptsFlags bopts)
(cliExtraDeps, targets) <-
parseTargets
needTargets
(bcImplicitGlobal bconfig)
snapshot
(flagExtraDeps <> bcExtraDeps bconfig)
(fst <$> rawLocals)
workingDir
(boptsTargets bopts)
return (mbp0, cliExtraDeps <> flagExtraDeps, targets)
-- | For every package in the snapshot which is referenced by a flag, give the
-- user a warning and then add it to extra-deps.
convertSnapshotToExtra
:: MonadLogger m
=> Map PackageName Version -- ^ snapshot
-> Map PackageName Version -- ^ extra-deps
-> [PackageName] -- ^ packages referenced by a flag
-> m (Map PackageName Version)
convertSnapshotToExtra snapshot extra0 flags0 =
go Map.empty flags0
where
go !extra [] = return extra
go extra (flag:flags)
| Just _ <- Map.lookup flag extra0 = go extra flags
| otherwise = case Map.lookup flag snapshot of
Nothing -> go extra flags
Just version -> do
$logWarn $ T.concat
[ "- Implicitly adding "
, T.pack $ packageNameString flag
, " to extra-deps based on command line flag"
]
go (Map.insert flag version extra) flags
-- | Parse out the local package views for the current project
getLocalPackageViews :: (MonadThrow m, MonadIO m, MonadReader env m, HasEnvConfig env)
=> m (Map PackageName (LocalPackageView, GenericPackageDescription))
getLocalPackageViews = do
econfig <- asks getEnvConfig
locals <- forM (Map.toList $ envConfigPackages econfig) $ \(dir, validWanted) -> do
cabalfp <- getCabalFileName dir
gpkg <- readPackageUnresolved cabalfp
let cabalID = package $ packageDescription gpkg
name <- parsePackageNameFromFilePath cabalfp
when (fromCabalPackageName (pkgName $ cabalID) /= name)
$ throwM $ MismatchedCabalName cabalfp name
let lpv = LocalPackageView
{ lpvVersion = fromCabalVersion $ pkgVersion cabalID
, lpvRoot = dir
, lpvCabalFP = cabalfp
, lpvExtraDep = not validWanted
, lpvComponents = getNamedComponents gpkg
}
return (name, (lpv, gpkg))
checkDuplicateNames locals
return $ Map.fromList locals
where
getNamedComponents gpkg = Set.fromList $ concat
[ maybe [] (const [CLib]) (C.condLibrary gpkg)
, go CExe C.condExecutables
, go CTest C.condTestSuites
, go CBench C.condBenchmarks
]
where
go wrapper f = map (wrapper . T.pack . fst) $ f gpkg
-- | Check if there are any duplicate package names and, if so, throw an
-- exception.
checkDuplicateNames :: MonadThrow m => [(PackageName, (LocalPackageView, gpd))] -> m ()
checkDuplicateNames locals =
case filter hasMultiples $ Map.toList $ Map.fromListWith (++) $ map toPair locals of
[] -> return ()
x -> throwM $ DuplicateLocalPackageNames x
where
toPair (pn, (lpv, _)) = (pn, [lpvRoot lpv])
hasMultiples (_, _:_:_) = True
hasMultiples _ = False
splitComponents :: [NamedComponent]
-> (Set Text, Set Text, Set Text)
splitComponents =
go id id id
where
go a b c [] = (Set.fromList $ a [], Set.fromList $ b [], Set.fromList $ c [])
go a b c (CLib:xs) = go a b c xs
go a b c (CExe x:xs) = go (a . (x:)) b c xs
go a b c (CTest x:xs) = go a (b . (x:)) c xs
go a b c (CBench x:xs) = go a b (c . (x:)) xs
-- | Upgrade the initial local package info to a full-blown @LocalPackage@
-- based on the selected components
loadLocalPackage
:: forall m env.
(MonadReader env m, HasEnvConfig env, MonadCatch m, MonadLogger m, MonadIO m)
=> BuildOpts
-> Map PackageName SimpleTarget
-> (PackageName, (LocalPackageView, GenericPackageDescription))
-> m LocalPackage
loadLocalPackage bopts targets (name, (lpv, gpkg)) = do
bconfig <- asks getBuildConfig
econfig <- asks getEnvConfig
let config = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = localFlags (boptsFlags bopts) bconfig name
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
pkg = resolvePackage config gpkg
mtarget = Map.lookup name targets
(exes, tests, benches) =
case mtarget of
Just (STLocalComps comps) -> splitComponents $ Set.toList comps
Just STLocalAll ->
( packageExes pkg
, if boptsTests bopts
then packageTests pkg
else Set.empty
, if boptsBenchmarks bopts
then packageBenchmarks pkg
else Set.empty
)
Just STNonLocal -> assert False mempty
Just STUnknown -> assert False mempty
Nothing -> mempty
btconfig = config
{ packageConfigEnableTests = not $ Set.null tests
, packageConfigEnableBenchmarks = not $ Set.null benches
}
testconfig = config
{ packageConfigEnableTests = True
, packageConfigEnableBenchmarks = False
}
benchconfig = config
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = True
}
btpkg
| Set.null tests && Set.null benches = Nothing
| otherwise = Just $ LocalPackageTB
{ lptbPackage = resolvePackage btconfig gpkg
, lptbTests = tests
, lptbBenches = benches
}
testpkg = resolvePackage testconfig gpkg
benchpkg = resolvePackage benchconfig gpkg
mbuildCache <- tryGetBuildCache $ lpvRoot lpv
(_,modFiles,otherFiles,mainFiles,extraFiles) <- getPackageFiles (packageFiles pkg) (lpvCabalFP lpv)
let files =
mconcat (M.elems modFiles) <>
mconcat (M.elems otherFiles) <>
Set.map mainIsFile (mconcat (M.elems mainFiles)) <>
extraFiles
(isDirty, newBuildCache) <- checkBuildCache
(fromMaybe Map.empty mbuildCache)
(map toFilePath $ Set.toList files)
return LocalPackage
{ lpPackage = pkg
, lpTestDeps = packageDeps $ testpkg
, lpBenchDeps = packageDeps $ benchpkg
, lpExeComponents =
case mtarget of
Nothing -> Nothing
Just _ -> Just exes
, lpTestBench = btpkg
, lpFiles = files
, lpDirtyFiles = isDirty || boptsForceDirty bopts
, lpNewBuildCache = newBuildCache
, lpCabalFile = lpvCabalFP lpv
, lpDir = lpvRoot lpv
, lpComponents = Set.unions
[ Set.map CExe exes
, Set.map CTest tests
, Set.map CBench benches
]
}
-- | Ensure that the flags specified in the stack.yaml file and on the command
-- line are used.
checkFlagsUsed :: (MonadThrow m, MonadReader env m, HasBuildConfig env)
=> BuildOpts
-> [LocalPackage]
-> Map PackageName extraDeps -- ^ extra deps
-> Map PackageName snapshot -- ^ snapshot, for error messages
-> m ()
checkFlagsUsed bopts lps extraDeps snapshot = do
bconfig <- asks getBuildConfig
-- Check if flags specified in stack.yaml and the command line are
-- used, see https://github.com/commercialhaskell/stack/issues/617
let flags = map (, FSCommandLine) [(k, v) | (Just k, v) <- Map.toList $ boptsFlags bopts]
++ map (, FSStackYaml) (Map.toList $ bcFlags bconfig)
localNameMap = Map.fromList $ map (packageName . lpPackage &&& lpPackage) lps
checkFlagUsed ((name, userFlags), source) =
case Map.lookup name localNameMap of
-- Package is not available locally
Nothing ->
case Map.lookup name extraDeps of
-- Also not in extra-deps, it's an error
Nothing ->
case Map.lookup name snapshot of
Nothing -> Just $ UFNoPackage source name
Just _ -> Just $ UFSnapshot name
-- We don't check for flag presence for extra deps
Just _ -> Nothing
-- Package exists locally, let's check if the flags are defined
Just pkg ->
let unused = Set.difference (Map.keysSet userFlags) (packageDefinedFlags pkg)
in if Set.null unused
-- All flags are defined, nothing to do
then Nothing
-- Error about the undefined flags
else Just $ UFFlagsNotDefined source pkg unused
unusedFlags = mapMaybe checkFlagUsed flags
unless (null unusedFlags)
$ throwM
$ InvalidFlagSpecification
$ Set.fromList unusedFlags
-- | All flags for a local package
localFlags :: (Map (Maybe PackageName) (Map FlagName Bool))
-> BuildConfig
-> PackageName
-> Map FlagName Bool
localFlags boptsflags bconfig name = Map.unions
[ fromMaybe Map.empty $ Map.lookup (Just name) $ boptsflags
, fromMaybe Map.empty $ Map.lookup Nothing $ boptsflags
, fromMaybe Map.empty $ Map.lookup name $ bcFlags bconfig
]
-- | Add in necessary packages to extra dependencies
--
-- Originally part of https://github.com/commercialhaskell/stack/issues/272,
-- this was then superseded by
-- https://github.com/commercialhaskell/stack/issues/651
extendExtraDeps :: (MonadThrow m, MonadReader env m, HasBuildConfig env)
=> Map PackageName Version -- ^ original extra deps
-> Map PackageName Version -- ^ package identifiers from the command line
-> Set PackageName -- ^ all packages added on the command line
-> Map PackageName Version -- ^ latest versions in indices
-> m (Map PackageName Version) -- ^ new extradeps
extendExtraDeps extraDeps0 cliExtraDeps unknowns latestVersion
| null errs = return $ Map.unions $ extraDeps1 : unknowns'
| otherwise = do
bconfig <- asks getBuildConfig
throwM $ UnknownTargets
(Set.fromList errs)
Map.empty -- TODO check the cliExtraDeps for presence in index
(bcStackYaml bconfig)
where
extraDeps1 = Map.union extraDeps0 cliExtraDeps
(errs, unknowns') = partitionEithers $ map addUnknown $ Set.toList unknowns
addUnknown pn =
case Map.lookup pn extraDeps1 of
Just _ -> Right Map.empty
Nothing ->
case Map.lookup pn latestVersion of
Just v -> Right $ Map.singleton pn v
Nothing -> Left pn
-- | Compare the current filesystem state to the cached information, and
-- determine (1) if the files are dirty, and (2) the new cache values.
checkBuildCache :: MonadIO m
=> Map FilePath FileCacheInfo -- ^ old cache
-> [FilePath] -- ^ files in package
-> m (Bool, Map FilePath FileCacheInfo)
checkBuildCache oldCache files = liftIO $ do
(Any isDirty, m) <- fmap mconcat $ mapM go files
return (isDirty, m)
where
go fp = do
mmodTime <- getModTimeMaybe fp
case mmodTime of
Nothing -> return (Any False, Map.empty)
Just modTime' -> do
(isDirty, newFci) <-
case Map.lookup fp oldCache of
Just fci
| fciModTime fci == modTime' -> return (False, fci)
| otherwise -> do
newFci <- calcFci modTime' fp
let isDirty =
fciSize fci /= fciSize newFci ||
fciHash fci /= fciHash newFci
return (isDirty, newFci)
Nothing -> do
newFci <- calcFci modTime' fp
return (True, newFci)
return (Any isDirty, Map.singleton fp newFci)
getModTimeMaybe fp =
liftIO
(catch
(liftM
(Just . modTime)
(getModificationTime fp))
(\e ->
if isDoesNotExistError e
then return Nothing
else throwM e))
calcFci modTime' fp =
withBinaryFile fp ReadMode $ \h -> do
(size, digest) <- CB.sourceHandle h $$ getZipSink
((,)
<$> ZipSink (CL.fold
(\x y -> x + fromIntegral (S.length y))
0)
<*> ZipSink sinkHash)
return FileCacheInfo
{ fciModTime = modTime'
, fciSize = size
, fciHash = toBytes (digest :: Digest SHA256)
}
| DanielG/stack | src/Stack/Build/Source.hs | bsd-3-clause | 21,051 | 0 | 27 | 7,283 | 4,856 | 2,517 | 2,339 | -1 | -1 |
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module SPARC.ShortcutJump (
JumpDest(..), getJumpDestBlockId,
canShortcut,
shortcutJump,
shortcutStatics,
shortBlockId
)
where
import SPARC.Instr
import SPARC.Imm
import CLabel
import BlockId
import Cmm
import Panic
import Unique
data JumpDest
= DestBlockId BlockId
| DestImm Imm
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
getJumpDestBlockId _ = Nothing
canShortcut :: Instr -> Maybe JumpDest
canShortcut _ = Nothing
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
shortcutJump _ other = other
shortcutStatics :: (BlockId -> Maybe JumpDest) -> CmmStatics -> CmmStatics
shortcutStatics fn (Statics lbl statics)
= Statics lbl $ map (shortcutStatic fn) statics
-- we need to get the jump tables, so apply the mapping to the entries
-- of a CmmData too.
shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
| Just uq <- maybeAsmTemp lab = shortBlockId fn (mkBlockId uq)
| otherwise = lab
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
= CmmStaticLit (CmmLabel (shortcutLabel fn lab))
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off))
= CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off)
-- slightly dodgy, we're ignoring the second label, but this
-- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
= other_static
shortBlockId :: (BlockId -> Maybe JumpDest) -> BlockId -> CLabel
shortBlockId fn blockid =
case fn blockid of
Nothing -> mkAsmTempLabel (getUnique blockid)
Just (DestBlockId blockid') -> shortBlockId fn blockid'
Just (DestImm (ImmCLbl lbl)) -> lbl
_other -> panic "shortBlockId"
| lukexi/ghc-7.8-arm64 | compiler/nativeGen/SPARC/ShortcutJump.hs | bsd-3-clause | 2,175 | 16 | 12 | 412 | 537 | 277 | 260 | 45 | 4 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module Aws.DynamoDb.Commands.Table
( -- * Commands
CreateTable(..)
, createTable
, CreateTableResult(..)
, DescribeTable(..)
, DescribeTableResult(..)
, UpdateTable(..)
, UpdateTableResult(..)
, DeleteTable(..)
, DeleteTableResult(..)
, ListTables(..)
, ListTablesResult(..)
-- * Data passed in the commands
, AttributeType(..)
, AttributeDefinition(..)
, KeySchema(..)
, Projection(..)
, LocalSecondaryIndex(..)
, LocalSecondaryIndexStatus(..)
, ProvisionedThroughput(..)
, ProvisionedThroughputStatus(..)
, GlobalSecondaryIndex(..)
, GlobalSecondaryIndexStatus(..)
, GlobalSecondaryIndexUpdate(..)
, TableDescription(..)
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Data.Aeson ((.!=), (.:), (.:?), (.=))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.Char (toUpper)
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import Data.Time
import Data.Time.Clock.POSIX
import Data.Typeable
import qualified Data.Vector as V
import GHC.Generics (Generic)
-------------------------------------------------------------------------------
import Aws.Core
import Aws.DynamoDb.Core
-------------------------------------------------------------------------------
capitalizeOpt :: A.Options
capitalizeOpt = A.defaultOptions
{ A.fieldLabelModifier = \x -> case x of
(c:cs) -> toUpper c : cs
[] -> []
}
dropOpt :: Int -> A.Options
dropOpt d = A.defaultOptions { A.fieldLabelModifier = drop d }
-- | The type of a key attribute that appears in the table key or as a
-- key in one of the indices.
data AttributeType = AttrString | AttrNumber | AttrBinary
deriving (Show, Read, Ord, Typeable, Eq, Enum, Bounded, Generic)
instance A.ToJSON AttributeType where
toJSON AttrString = A.String "S"
toJSON AttrNumber = A.String "N"
toJSON AttrBinary = A.String "B"
instance A.FromJSON AttributeType where
parseJSON (A.String str) =
case str of
"S" -> return AttrString
"N" -> return AttrNumber
"B" -> return AttrBinary
_ -> fail $ "Invalid attribute type " ++ T.unpack str
parseJSON _ = fail "Attribute type must be a string"
-- | A key attribute that appears in the table key or as a key in one of the indices.
data AttributeDefinition = AttributeDefinition {
attributeName :: T.Text
, attributeType :: AttributeType
} deriving (Eq,Read,Ord,Show,Typeable,Generic)
instance A.ToJSON AttributeDefinition where
toJSON = A.genericToJSON capitalizeOpt
instance A.FromJSON AttributeDefinition where
parseJSON = A.genericParseJSON capitalizeOpt
-- | The key schema can either be a hash of a single attribute name or a hash attribute name
-- and a range attribute name.
data KeySchema = HashOnly T.Text
| HashAndRange T.Text T.Text
deriving (Eq,Read,Show,Ord,Typeable,Generic)
instance A.ToJSON KeySchema where
toJSON (HashOnly a)
= A.Array $ V.fromList [ A.object [ "AttributeName" .= a
, "KeyType" .= (A.String "HASH")
]
]
toJSON (HashAndRange hash range)
= A.Array $ V.fromList [ A.object [ "AttributeName" .= hash
, "KeyType" .= (A.String "HASH")
]
, A.object [ "AttributeName" .= range
, "KeyType" .= (A.String "RANGE")
]
]
instance A.FromJSON KeySchema where
parseJSON (A.Array v) =
case V.length v of
1 -> do obj <- A.parseJSON (v V.! 0)
kt <- obj .: "KeyType"
if kt /= ("HASH" :: T.Text)
then fail "With only one key, the type must be HASH"
else HashOnly <$> obj .: "AttributeName"
2 -> do hash <- A.parseJSON (v V.! 0)
range <- A.parseJSON (v V.! 1)
hkt <- hash .: "KeyType"
rkt <- range .: "KeyType"
if hkt /= ("HASH" :: T.Text) || rkt /= ("RANGE" :: T.Text)
then fail "With two keys, one must be HASH and the other RANGE"
else HashAndRange <$> hash .: "AttributeName"
<*> range .: "AttributeName"
_ -> fail "Key schema must have one or two entries"
parseJSON _ = fail "Key schema must be an array"
-- | This determines which attributes are projected into a secondary index.
data Projection = ProjectKeysOnly
| ProjectAll
| ProjectInclude [T.Text]
deriving Show
instance A.ToJSON Projection where
toJSON ProjectKeysOnly = A.object [ "ProjectionType" .= ("KEYS_ONLY" :: T.Text) ]
toJSON ProjectAll = A.object [ "ProjectionType" .= ("ALL" :: T.Text) ]
toJSON (ProjectInclude a) = A.object [ "ProjectionType" .= ("INCLUDE" :: T.Text)
, "NonKeyAttributes" .= a
]
instance A.FromJSON Projection where
parseJSON (A.Object o) = do
ty <- (o .: "ProjectionType") :: A.Parser T.Text
case ty of
"KEYS_ONLY" -> return ProjectKeysOnly
"ALL" -> return ProjectAll
"INCLUDE" -> ProjectInclude <$> o .: "NonKeyAttributes"
_ -> fail "Invalid projection type"
parseJSON _ = fail "Projection must be an object"
-- | Describes a single local secondary index. The KeySchema MUST
-- share the same hash key attribute as the parent table, only the
-- range key can differ.
data LocalSecondaryIndex
= LocalSecondaryIndex {
localIndexName :: T.Text
, localKeySchema :: KeySchema
, localProjection :: Projection
}
deriving (Show, Generic)
instance A.ToJSON LocalSecondaryIndex where
toJSON = A.genericToJSON $ dropOpt 5
instance A.FromJSON LocalSecondaryIndex where
parseJSON = A.genericParseJSON $ dropOpt 5
-- | This is returned by AWS to describe the local secondary index.
data LocalSecondaryIndexStatus
= LocalSecondaryIndexStatus {
locStatusIndexName :: T.Text
, locStatusIndexSizeBytes :: Integer
, locStatusItemCount :: Integer
, locStatusKeySchema :: KeySchema
, locStatusProjection :: Projection
}
deriving (Show, Generic)
instance A.FromJSON LocalSecondaryIndexStatus where
parseJSON = A.genericParseJSON $ dropOpt 9
-- | The target provisioned throughput you are requesting for the table or global secondary index.
data ProvisionedThroughput
= ProvisionedThroughput {
readCapacityUnits :: Int
, writeCapacityUnits :: Int
}
deriving (Show, Generic)
instance A.ToJSON ProvisionedThroughput where
toJSON = A.genericToJSON capitalizeOpt
instance A.FromJSON ProvisionedThroughput where
parseJSON = A.genericParseJSON capitalizeOpt
-- | This is returned by AWS as the status of the throughput for a table or global secondary index.
data ProvisionedThroughputStatus
= ProvisionedThroughputStatus {
statusLastDecreaseDateTime :: UTCTime
, statusLastIncreaseDateTime :: UTCTime
, statusNumberOfDecreasesToday :: Int
, statusReadCapacityUnits :: Int
, statusWriteCapacityUnits :: Int
}
deriving (Show, Generic)
instance A.FromJSON ProvisionedThroughputStatus where
parseJSON = A.withObject "Throughput status must be an object" $ \o ->
ProvisionedThroughputStatus
<$> (posixSecondsToUTCTime . fromInteger <$> o .:? "LastDecreaseDateTime" .!= 0)
<*> (posixSecondsToUTCTime . fromInteger <$> o .:? "LastIncreaseDateTime" .!= 0)
<*> o .:? "NumberOfDecreasesToday" .!= 0
<*> o .: "ReadCapacityUnits"
<*> o .: "WriteCapacityUnits"
-- | Describes a global secondary index.
data GlobalSecondaryIndex
= GlobalSecondaryIndex {
globalIndexName :: T.Text
, globalKeySchema :: KeySchema
, globalProjection :: Projection
, globalProvisionedThroughput :: ProvisionedThroughput
}
deriving (Show, Generic)
instance A.ToJSON GlobalSecondaryIndex where
toJSON = A.genericToJSON $ dropOpt 6
instance A.FromJSON GlobalSecondaryIndex where
parseJSON = A.genericParseJSON $ dropOpt 6
-- | This is returned by AWS to describe the status of a global secondary index.
data GlobalSecondaryIndexStatus
= GlobalSecondaryIndexStatus {
gStatusIndexName :: T.Text
, gStatusIndexSizeBytes :: Integer
, gStatusIndexStatus :: T.Text
, gStatusItemCount :: Integer
, gStatusKeySchema :: KeySchema
, gStatusProjection :: Projection
, gStatusProvisionedThroughput :: ProvisionedThroughputStatus
}
deriving (Show, Generic)
instance A.FromJSON GlobalSecondaryIndexStatus where
parseJSON = A.genericParseJSON $ dropOpt 7
-- | This is used to request a change in the provisioned throughput of
-- a global secondary index as part of an 'UpdateTable' operation.
data GlobalSecondaryIndexUpdate
= GlobalSecondaryIndexUpdate {
gUpdateIndexName :: T.Text
, gUpdateProvisionedThroughput :: ProvisionedThroughput
}
deriving (Show, Generic)
instance A.ToJSON GlobalSecondaryIndexUpdate where
toJSON gi = A.object ["Update" .= A.genericToJSON (dropOpt 7) gi]
-- | This describes the table and is the return value from AWS for all
-- the table-related commands.
data TableDescription
= TableDescription {
rTableName :: T.Text
, rTableSizeBytes :: Integer
, rTableStatus :: T.Text -- ^ one of CREATING, UPDATING, DELETING, ACTIVE
, rCreationDateTime :: Maybe UTCTime
, rItemCount :: Integer
, rAttributeDefinitions :: [AttributeDefinition]
, rKeySchema :: Maybe KeySchema
, rProvisionedThroughput :: ProvisionedThroughputStatus
, rLocalSecondaryIndexes :: [LocalSecondaryIndexStatus]
, rGlobalSecondaryIndexes :: [GlobalSecondaryIndexStatus]
}
deriving (Show, Generic)
instance A.FromJSON TableDescription where
parseJSON = A.withObject "Table must be an object" $ \o -> do
t <- case (M.lookup "Table" o, M.lookup "TableDescription" o) of
(Just (A.Object t), _) -> return t
(_, Just (A.Object t)) -> return t
_ -> fail "Table description must have key 'Table' or 'TableDescription'"
TableDescription <$> t .: "TableName"
<*> t .: "TableSizeBytes"
<*> t .: "TableStatus"
<*> (fmap (posixSecondsToUTCTime . fromInteger) <$> t .:? "CreationDateTime")
<*> t .: "ItemCount"
<*> t .:? "AttributeDefinitions" .!= []
<*> t .:? "KeySchema"
<*> t .: "ProvisionedThroughput"
<*> t .:? "LocalSecondaryIndexes" .!= []
<*> t .:? "GlobalSecondaryIndexes" .!= []
{- Can't derive these instances onto the return values
instance ResponseConsumer r TableDescription where
type ResponseMetadata TableDescription = DyMetadata
responseConsumer _ _ = ddbResponseConsumer
instance AsMemoryResponse TableDescription where
type MemoryResponse TableDescription = TableDescription
loadToMemory = return
-}
-------------------------------------------------------------------------------
--- Commands
-------------------------------------------------------------------------------
data CreateTable = CreateTable {
createTableName :: T.Text
, createAttributeDefinitions :: [AttributeDefinition]
-- ^ only attributes appearing in a key must be listed here
, createKeySchema :: KeySchema
, createProvisionedThroughput :: ProvisionedThroughput
, createLocalSecondaryIndexes :: [LocalSecondaryIndex]
-- ^ at most 5 local secondary indices are allowed
, createGlobalSecondaryIndexes :: [GlobalSecondaryIndex]
} deriving (Show, Generic)
createTable :: T.Text -- ^ Table name
-> [AttributeDefinition]
-> KeySchema
-> ProvisionedThroughput
-> CreateTable
createTable tn ad ks p = CreateTable tn ad ks p [] []
instance A.ToJSON CreateTable where
toJSON ct = A.object $ m ++ lindex ++ gindex
where
m = [ "TableName" .= createTableName ct
, "AttributeDefinitions" .= createAttributeDefinitions ct
, "KeySchema" .= createKeySchema ct
, "ProvisionedThroughput" .= createProvisionedThroughput ct
]
-- AWS will error with 500 if (LocalSecondaryIndexes : []) is present in the JSON
lindex = if null (createLocalSecondaryIndexes ct)
then []
else [ "LocalSecondaryIndexes" .= createLocalSecondaryIndexes ct ]
gindex = if null (createGlobalSecondaryIndexes ct)
then []
else [ "GlobalSecondaryIndexes" .= createGlobalSecondaryIndexes ct ]
--instance A.ToJSON CreateTable where
-- toJSON = A.genericToJSON $ dropOpt 6
-- | ServiceConfiguration: 'DdbConfiguration'
instance SignQuery CreateTable where
type ServiceConfiguration CreateTable = DdbConfiguration
signQuery = ddbSignQuery "CreateTable"
newtype CreateTableResult = CreateTableResult { ctStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer and AsMemoryResponse can't be derived
instance ResponseConsumer r CreateTableResult where
type ResponseMetadata CreateTableResult = DdbResponse
responseConsumer _ = ddbResponseConsumer
instance AsMemoryResponse CreateTableResult where
type MemoryResponse CreateTableResult = TableDescription
loadToMemory = return . ctStatus
instance Transaction CreateTable CreateTableResult
data DescribeTable
= DescribeTable {
dTableName :: T.Text
}
deriving (Show, Generic)
instance A.ToJSON DescribeTable where
toJSON = A.genericToJSON $ dropOpt 1
-- | ServiceConfiguration: 'DdbConfiguration'
instance SignQuery DescribeTable where
type ServiceConfiguration DescribeTable = DdbConfiguration
signQuery = ddbSignQuery "DescribeTable"
newtype DescribeTableResult = DescribeTableResult { dtStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r DescribeTableResult where
type ResponseMetadata DescribeTableResult = DdbResponse
responseConsumer _ = ddbResponseConsumer
instance AsMemoryResponse DescribeTableResult where
type MemoryResponse DescribeTableResult = TableDescription
loadToMemory = return . dtStatus
instance Transaction DescribeTable DescribeTableResult
data UpdateTable
= UpdateTable {
updateTableName :: T.Text
, updateProvisionedThroughput :: ProvisionedThroughput
, updateGlobalSecondaryIndexUpdates :: [GlobalSecondaryIndexUpdate]
}
deriving (Show, Generic)
instance A.ToJSON UpdateTable where
toJSON a = A.object
$ "TableName" .= updateTableName a
: "ProvisionedThroughput" .= updateProvisionedThroughput a
: case updateGlobalSecondaryIndexUpdates a of
[] -> []
l -> [ "GlobalSecondaryIndexUpdates" .= l ]
-- | ServiceConfiguration: 'DdbConfiguration'
instance SignQuery UpdateTable where
type ServiceConfiguration UpdateTable = DdbConfiguration
signQuery = ddbSignQuery "UpdateTable"
newtype UpdateTableResult = UpdateTableResult { uStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r UpdateTableResult where
type ResponseMetadata UpdateTableResult = DdbResponse
responseConsumer _ = ddbResponseConsumer
instance AsMemoryResponse UpdateTableResult where
type MemoryResponse UpdateTableResult = TableDescription
loadToMemory = return . uStatus
instance Transaction UpdateTable UpdateTableResult
data DeleteTable
= DeleteTable {
deleteTableName :: T.Text
}
deriving (Show, Generic)
instance A.ToJSON DeleteTable where
toJSON = A.genericToJSON $ dropOpt 6
-- | ServiceConfiguration: 'DdbConfiguration'
instance SignQuery DeleteTable where
type ServiceConfiguration DeleteTable = DdbConfiguration
signQuery = ddbSignQuery "DeleteTable"
newtype DeleteTableResult = DeleteTableResult { dStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r DeleteTableResult where
type ResponseMetadata DeleteTableResult = DdbResponse
responseConsumer _ = ddbResponseConsumer
instance AsMemoryResponse DeleteTableResult where
type MemoryResponse DeleteTableResult = TableDescription
loadToMemory = return . dStatus
instance Transaction DeleteTable DeleteTableResult
-- | TODO: currently this does not support restarting a cutoff query because of size.
data ListTables = ListTables
deriving (Show)
instance A.ToJSON ListTables where
toJSON _ = A.object []
-- | ServiceConfiguration: 'DdbConfiguration'
instance SignQuery ListTables where
type ServiceConfiguration ListTables = DdbConfiguration
signQuery = ddbSignQuery "ListTables"
newtype ListTablesResult
= ListTablesResult {
tableNames :: [T.Text]
}
deriving (Show, Generic)
instance A.FromJSON ListTablesResult where
parseJSON = A.genericParseJSON capitalizeOpt
instance ResponseConsumer r ListTablesResult where
type ResponseMetadata ListTablesResult = DdbResponse
responseConsumer _ = ddbResponseConsumer
instance AsMemoryResponse ListTablesResult where
type MemoryResponse ListTablesResult = [T.Text]
loadToMemory = return . tableNames
instance Transaction ListTables ListTablesResult
| romanb/aws | Aws/DynamoDb/Commands/Table.hs | bsd-3-clause | 18,748 | 0 | 31 | 5,056 | 3,516 | 1,941 | 1,575 | -1 | -1 |
-- Get an interactive shell with the right packages to load
-- pandoc modules.
-- To use:
-- runghc Interact.hs
-- then,
-- :l Text/Pandoc.hs
-- (or whichever package you like)
-- You must have first done a 'cabal configure' or 'cabal install'
import System.Process
import Distribution.Simple.LocalBuildInfo
import Distribution.Package
import Distribution.Version
import Data.List (intercalate)
main = do
setupConfig' <- readFile "dist/setup-config"
let setupConfig = read $ unlines $ drop 1 $ lines setupConfig'
let (Just (ComponentLocalBuildInfo { componentPackageDeps = deps })) = libraryConfig setupConfig
let packageSpecs = map (toPackageSpec . snd) deps
let args = ["-optP-include", "-optP../dist/build/autogen/cabal_macros.h","-cpp","-I../dist/build/autogen","-i../dist/build/autogen"] ++ concatMap (\p -> ["-package",p]) packageSpecs
print args
ph <- runProcess "ghci" args (Just "src") Nothing Nothing Nothing Nothing
waitForProcess ph
toPackageSpec pkg = pkgN ++ "-" ++ pkgV
where (PackageName pkgN) = pkgName pkg
pkgV = intercalate "." $ map show $ versionBranch $ pkgVersion pkg
| Lythimus/lptv | sites/all/modules/jgm-pandoc-8be6cc2/Interact.hs | gpl-2.0 | 1,122 | 0 | 15 | 175 | 280 | 143 | 137 | 17 | 1 |
Subsets and Splits