code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-ssekmsencryptedobjects.html
module Stratosphere.ResourceProperties.S3BucketSseKmsEncryptedObjects where
import Stratosphere.ResourceImports
-- | Full data type definition for S3BucketSseKmsEncryptedObjects. See
-- 's3BucketSseKmsEncryptedObjects' for a more convenient constructor.
data S3BucketSseKmsEncryptedObjects =
S3BucketSseKmsEncryptedObjects
{ _s3BucketSseKmsEncryptedObjectsStatus :: Val Text
} deriving (Show, Eq)
instance ToJSON S3BucketSseKmsEncryptedObjects where
toJSON S3BucketSseKmsEncryptedObjects{..} =
object $
catMaybes
[ (Just . ("Status",) . toJSON) _s3BucketSseKmsEncryptedObjectsStatus
]
-- | Constructor for 'S3BucketSseKmsEncryptedObjects' containing required
-- fields as arguments.
s3BucketSseKmsEncryptedObjects
:: Val Text -- ^ 'sbskeoStatus'
-> S3BucketSseKmsEncryptedObjects
s3BucketSseKmsEncryptedObjects statusarg =
S3BucketSseKmsEncryptedObjects
{ _s3BucketSseKmsEncryptedObjectsStatus = statusarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-ssekmsencryptedobjects.html#cfn-s3-bucket-ssekmsencryptedobjects-status
sbskeoStatus :: Lens' S3BucketSseKmsEncryptedObjects (Val Text)
sbskeoStatus = lens _s3BucketSseKmsEncryptedObjectsStatus (\s a -> s { _s3BucketSseKmsEncryptedObjectsStatus = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/S3BucketSseKmsEncryptedObjects.hs | mit | 1,541 | 0 | 13 | 164 | 174 | 100 | 74 | 23 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE OverloadedStrings #-}
#ifndef NO_OVERLAP
{-# LANGUAGE OverlappingInstances #-}
#endif
module Database.Persist.Class.PersistField
( PersistField (..)
, SomePersistField (..)
, getPersistMap
) where
import Database.Persist.Types.Base
import Data.Time (Day(..), TimeOfDay, UTCTime)
#ifdef HIGH_PRECISION_DATE
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
#endif
import Data.ByteString.Char8 (ByteString, unpack, readInt)
import Control.Applicative
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import Data.Text (Text)
import Data.Text.Read (double)
import Data.Fixed
import Data.Monoid ((<>))
import Text.Blaze.Html
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.ByteString.Lazy as L
import Control.Monad ((<=<))
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Aeson as A
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
-- | A value which can be marshalled to and from a 'PersistValue'.
class PersistField a where
toPersistValue :: a -> PersistValue
fromPersistValue :: PersistValue -> Either T.Text a
#ifndef NO_OVERLAP
instance PersistField String where
toPersistValue = PersistText . T.pack
fromPersistValue (PersistText s) = Right $ T.unpack s
fromPersistValue (PersistByteString bs) =
Right $ T.unpack $ T.decodeUtf8With T.lenientDecode bs
fromPersistValue (PersistInt64 i) = Right $ Prelude.show i
fromPersistValue (PersistDouble d) = Right $ Prelude.show d
fromPersistValue (PersistRational r) = Right $ Prelude.show r
fromPersistValue (PersistDay d) = Right $ Prelude.show d
fromPersistValue (PersistTimeOfDay d) = Right $ Prelude.show d
fromPersistValue (PersistUTCTime d) = Right $ Prelude.show d
fromPersistValue PersistNull = Left $ T.pack "Unexpected null"
fromPersistValue (PersistBool b) = Right $ Prelude.show b
fromPersistValue (PersistList _) = Left $ T.pack "Cannot convert PersistList to String"
fromPersistValue (PersistMap _) = Left $ T.pack "Cannot convert PersistMap to String"
fromPersistValue (PersistDbSpecific _) = Left $ T.pack "Cannot convert PersistDbSpecific to String"
fromPersistValue (PersistObjectId _) = Left $ T.pack "Cannot convert PersistObjectId to String"
#endif
instance PersistField ByteString where
toPersistValue = PersistByteString
fromPersistValue (PersistByteString bs) = Right bs
fromPersistValue x = T.encodeUtf8 <$> fromPersistValue x
instance PersistField T.Text where
toPersistValue = PersistText
fromPersistValue = fromPersistValueText
instance PersistField TL.Text where
toPersistValue = toPersistValue . TL.toStrict
fromPersistValue = fmap TL.fromStrict . fromPersistValue
instance PersistField Html where
toPersistValue = PersistText . TL.toStrict . renderHtml
fromPersistValue = fmap (preEscapedToMarkup :: T.Text -> Html) . fromPersistValue
instance PersistField Int where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistDouble i) = Right (truncate i :: Int) -- oracle
fromPersistValue x = Left $ T.pack $ "int Expected Integer, received: " ++ show x
instance PersistField Int8 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistDouble i) = Right (truncate i :: Int8) -- oracle
fromPersistValue x = Left $ T.pack $ "int8 Expected Integer, received: " ++ show x
instance PersistField Int16 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistDouble i) = Right (truncate i :: Int16) -- oracle
fromPersistValue x = Left $ T.pack $ "int16 Expected Integer, received: " ++ show x
instance PersistField Int32 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistDouble i) = Right (truncate i :: Int32) -- oracle
fromPersistValue x = Left $ T.pack $ "int32 Expected Integer, received: " ++ show x
instance PersistField Int64 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistDouble i) = Right (truncate i :: Int64) -- oracle
fromPersistValue x = Left $ T.pack $ "int64 Expected Integer, received: " ++ show x
instance PersistField Word where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ T.pack $ "Expected Word, received: " ++ show x
instance PersistField Word8 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ T.pack $ "Expected Word, received: " ++ show x
instance PersistField Word16 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ T.pack $ "Expected Word, received: " ++ show x
instance PersistField Word32 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ T.pack $ "Expected Word, received: " ++ show x
instance PersistField Word64 where
toPersistValue = PersistInt64 . fromIntegral
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ T.pack $ "Expected Word, received: " ++ show x
instance PersistField Double where
toPersistValue = PersistDouble
fromPersistValue (PersistDouble d) = Right d
fromPersistValue (PersistRational r) = Right $ fromRational r
fromPersistValue x = Left $ T.pack $ "Expected Double, received: " ++ show x
instance (HasResolution a) => PersistField (Fixed a) where
toPersistValue = PersistRational . toRational
fromPersistValue (PersistRational r) = Right $ fromRational r
fromPersistValue (PersistText t) = case reads $ T.unpack t of -- NOTE: Sqlite can store rationals just as string
[(a, "")] -> Right a
_ -> Left $ "Can not read " <> t <> " as Fixed"
fromPersistValue (PersistDouble d) = Right $ realToFrac d
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue x = Left $ "PersistField Fixed:Expected Rational, received: " <> T.pack (show x)
instance PersistField Rational where
toPersistValue = PersistRational
fromPersistValue (PersistRational r) = Right r
fromPersistValue (PersistDouble d) = Right $ toRational d
fromPersistValue (PersistText t) = case reads $ T.unpack t of -- NOTE: Sqlite can store rationals just as string
[(a, "")] -> Right $ toRational (a :: Pico)
_ -> Left $ "Can not read " <> t <> " as Rational (Pico in fact)"
fromPersistValue (PersistInt64 i) = Right $ fromIntegral i
fromPersistValue (PersistByteString bs) = case double $ T.cons '0' $ T.decodeUtf8With T.lenientDecode bs of
Right (ret,"") -> Right $ toRational ret
Right (a,b) -> Left $ "Invalid bytestring[" <> T.pack (show bs) <> "]: expected a double but returned " <> T.pack (show (a,b))
Left xs -> Left $ "Invalid bytestring[" <> T.pack (show bs) <> "]: expected a double but returned " <> T.pack (show xs)
fromPersistValue x = Left $ "PersistField Rational:Expected Rational, received: " <> T.pack (show x)
instance PersistField Bool where
toPersistValue = PersistBool
fromPersistValue (PersistBool b) = Right b
fromPersistValue (PersistInt64 i) = Right $ i /= 0
fromPersistValue (PersistByteString i) = case readInt i of
Just (0,"") -> Right False
Just (1,"") -> Right True
xs -> error $ "PersistField Bool failed parsing PersistByteString xs["++show xs++"] i["++show i++"]"
fromPersistValue x = Left $ T.pack $ "Expected Bool, received: " ++ show x
instance PersistField Day where
toPersistValue = PersistDay
fromPersistValue (PersistDay d) = Right d
fromPersistValue (PersistInt64 i) = Right $ ModifiedJulianDay $ toInteger i
fromPersistValue x@(PersistText t) =
case reads $ T.unpack t of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected Day, received " ++ show x
fromPersistValue x@(PersistByteString s) =
case reads $ unpack s of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected Day, received " ++ show x
fromPersistValue x = Left $ T.pack $ "Expected Day, received: " ++ show x
instance PersistField TimeOfDay where
toPersistValue = PersistTimeOfDay
fromPersistValue (PersistTimeOfDay d) = Right d
fromPersistValue x@(PersistText t) =
case reads $ T.unpack t of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected TimeOfDay, received " ++ show x
fromPersistValue x@(PersistByteString s) =
case reads $ unpack s of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected TimeOfDay, received " ++ show x
fromPersistValue x = Left $ T.pack $ "Expected TimeOfDay, received: " ++ show x
instance PersistField UTCTime where
toPersistValue = PersistUTCTime
fromPersistValue (PersistUTCTime d) = Right d
#ifdef HIGH_PRECISION_DATE
fromPersistValue (PersistInt64 i) = Right $ posixSecondsToUTCTime $ (/ (1000 * 1000 * 1000)) $ fromIntegral $ i
#endif
fromPersistValue x@(PersistText t) =
case reads $ T.unpack t of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected UTCTime, received " ++ show x
fromPersistValue x@(PersistByteString s) =
case reads $ unpack s of
(d, _):_ -> Right d
_ -> Left $ T.pack $ "Expected UTCTime, received " ++ show x
fromPersistValue x = Left $ T.pack $ "Expected UTCTime, received: " ++ show x
instance PersistField a => PersistField (Maybe a) where
toPersistValue Nothing = PersistNull
toPersistValue (Just a) = toPersistValue a
fromPersistValue PersistNull = Right Nothing
fromPersistValue x = fmap Just $ fromPersistValue x
instance PersistField a => PersistField [a] where
toPersistValue = PersistList . map toPersistValue
fromPersistValue (PersistList l) = fromPersistList l
fromPersistValue (PersistText t) = fromPersistValue (PersistByteString $ TE.encodeUtf8 t)
fromPersistValue (PersistByteString bs)
| Just values <- A.decode' (L.fromChunks [bs]) = fromPersistList values
-- avoid the need for a migration to fill in empty lists.
-- also useful when Persistent is not the only one filling in the data
fromPersistValue (PersistNull) = Right []
fromPersistValue x = Left $ T.pack $ "Expected PersistList, received: " ++ show x
instance PersistField a => PersistField (V.Vector a) where
toPersistValue = toPersistValue . V.toList
fromPersistValue = either (\e -> Left ("Vector: " `T.append` e))
(Right . V.fromList) . fromPersistValue
instance (Ord a, PersistField a) => PersistField (S.Set a) where
toPersistValue = PersistList . map toPersistValue . S.toList
fromPersistValue (PersistList list) =
either Left (Right . S.fromList) $ fromPersistList list
fromPersistValue (PersistText t) = fromPersistValue (PersistByteString $ TE.encodeUtf8 t)
fromPersistValue (PersistByteString bs)
| Just values <- A.decode' (L.fromChunks [bs]) =
either Left (Right . S.fromList) $ fromPersistList values
fromPersistValue PersistNull = Right S.empty
fromPersistValue x = Left $ T.pack $ "Expected PersistSet, received: " ++ show x
instance (PersistField a, PersistField b) => PersistField (a,b) where
toPersistValue (x,y) = PersistList [toPersistValue x, toPersistValue y]
fromPersistValue v =
case fromPersistValue v of
Right (x:y:[]) -> (,) <$> fromPersistValue x <*> fromPersistValue y
Left e -> Left e
_ -> Left $ T.pack $ "Expected 2 item PersistList, received: " ++ show v
instance PersistField v => PersistField (M.Map T.Text v) where
toPersistValue = PersistMap . map (\(k,v) -> (k, toPersistValue v)) . M.toList
fromPersistValue = fromPersistMap <=< getPersistMap
instance PersistField PersistValue where
toPersistValue = id
fromPersistValue = Right
fromPersistList :: PersistField a => [PersistValue] -> Either T.Text [a]
fromPersistList = mapM fromPersistValue
fromPersistMap :: PersistField v
=> [(T.Text, PersistValue)]
-> Either T.Text (M.Map T.Text v)
fromPersistMap = foldShortLeft fromPersistValue [] where
-- a fold that short-circuits on Left.
foldShortLeft f = go
where
go acc [] = Right $ M.fromList acc
go acc ((k, v):kvs) =
case f v of
Left e -> Left e
Right v' -> go ((k,v'):acc) kvs
getPersistMap :: PersistValue -> Either T.Text [(T.Text, PersistValue)]
getPersistMap (PersistMap kvs) = Right kvs
getPersistMap (PersistText t) = getPersistMap (PersistByteString $ TE.encodeUtf8 t)
getPersistMap (PersistByteString bs)
| Just pairs <- A.decode' (L.fromChunks [bs]) = Right pairs
getPersistMap PersistNull = Right []
getPersistMap x = Left $ T.pack $ "Expected PersistMap, received: " ++ show x
data SomePersistField = forall a. PersistField a => SomePersistField a
instance PersistField SomePersistField where
toPersistValue (SomePersistField a) = toPersistValue a
fromPersistValue x = fmap SomePersistField (fromPersistValue x :: Either Text Text)
instance PersistField Checkmark where
toPersistValue Active = PersistBool True
toPersistValue Inactive = PersistNull
fromPersistValue PersistNull = Right Inactive
fromPersistValue (PersistBool True) = Right Active
fromPersistValue (PersistInt64 1) = Right Active
fromPersistValue (PersistByteString i) = case readInt i of
Just (0,"") -> Left $ T.pack "PersistField Checkmark: found unexpected 0 value"
Just (1,"") -> Right Active
xs -> Left $ T.pack $ "PersistField Checkmark failed parsing PersistByteString xs["++show xs++"] i["++show i++"]"
fromPersistValue (PersistBool False) =
Left $ T.pack "PersistField Checkmark: found unexpected FALSE value"
fromPersistValue other =
Left $ T.pack $ "PersistField Checkmark: unknown value " ++ show other
| junjihashimoto/persistent | persistent/Database/Persist/Class/PersistField.hs | mit | 15,253 | 0 | 15 | 3,432 | 4,449 | 2,267 | 2,182 | 263 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Compiler
( renderKaTeX
, renderFontAwesome
, optimizeSVGCompiler
, absolutizeUrls
, prependBaseUrl
, cleanIndexHtmls
, modifyExternalLinkAttributes
) where
import Control.Monad
import Data.Char
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import Hakyll
import System.FilePath
import qualified Text.HTML.TagSoup as TS
import qualified Text.HTML.TagSoup.Tree as TST
import FontAwesome
renderKaTeX :: Item String -> Compiler (Item String)
renderKaTeX =
withItemBody $ fmap (TST.renderTreeOptions tagSoupOption) . transformTreeM f . TST.parseTree
where
f tag@(TST.TagBranch _ as [TST.TagLeaf (TS.TagText e)])
| hasMathClass as =
TST.parseTree <$> unixFilter "tools/katex.js" ["displayMode" | hasDisplayClass as] e
| otherwise = return [tag]
f tag = return [tag]
hasDisplayClass = elem "display" . classes
hasMathClass = elem "math" . classes
classes = words . fromMaybe "" . lookup "class"
renderFontAwesome :: FontAwesomeIcons -> Item String -> Compiler (Item String)
renderFontAwesome icons = return . fmap
(TST.renderTreeOptions tagSoupOption . TST.transformTree renderFontAwesome' . TST.parseTree)
where
renderFontAwesome' tag@(TST.TagBranch "i" as []) =
case toFontAwesome $ classes as of
Just tree -> [tree]
Nothing -> [tag]
renderFontAwesome' tag = [tag]
toFontAwesome (prefix:('f':'a':'-':name):cs) =
fmap (`appendClasses` cs) (fontawesome icons prefix name)
toFontAwesome _ = Nothing
appendClasses t [] = t
appendClasses (TST.TagBranch x y z) cs =
let as1 = HM.fromList y
as2 = HM.singleton "class" $ unwords cs
y' = HM.toList $ HM.unionWith (\v1 v2 -> v1 ++ " " ++ v2) as1 as2
in TST.TagBranch x y' z
appendClasses t _ = t
classes = words . fromMaybe "" . lookup "class"
optimizeSVGCompiler :: [String] -> Compiler (Item String)
optimizeSVGCompiler opts = getResourceString >>=
withItemBody (unixFilter "node_modules/svgo/bin/svgo" $ ["-i", "-", "-o", "-"] ++ opts)
absolutizeUrls :: Item String -> Compiler (Item String)
absolutizeUrls item = do
r <- getRoute =<< getUnderlying
return $ case r of
Just r' -> fmap (withUrls (absolutizeUrls' r')) item
_ -> item
where
absolutizeUrls' r u
| not (isExternal u) && isRelative u = normalise $ "/" </> takeDirectory r </> u
| otherwise = u
prependBaseUrl :: String -> Item String -> Compiler (Item String)
prependBaseUrl base = return . fmap (withUrls prependBaseUrl')
where
prependBaseUrl' u
| not (isExternal u) && isAbsolute u = base <> u
| otherwise = u
cleanIndexHtmls :: Item String -> Compiler (Item String)
cleanIndexHtmls = return . fmap (withUrls removeIndexHtml)
where
removeIndexHtml path
| not (isExternal path) && takeFileName path == "index.html" = dropFileName path
| otherwise = path
modifyExternalLinkAttributes :: Item String -> Compiler (Item String)
modifyExternalLinkAttributes = return . fmap (withTags f)
where
f t | isExternalLink t = let (TS.TagOpen "a" as) = t
in (TS.TagOpen "a" $ as <> extraAttributs)
| otherwise = t
isExternalLink = liftM2 (&&) (TS.isTagOpenName "a") (isExternal . TS.fromAttrib "href")
extraAttributs = [("target", "_blank"), ("rel", "nofollow noopener")]
-- https://github.com/jaspervdj/hakyll/blob/v4.11.0.0/lib/Hakyll/Web/Html.hs#L77-L90
tagSoupOption :: TS.RenderOptions String
tagSoupOption = TS.RenderOptions
{ TS.optRawTag = (`elem` ["script", "style"]) . map toLower
, TS.optMinimize = (`elem` minimize) . map toLower
, TS.optEscape = TS.escapeHTML
}
where
minimize = ["area", "br", "col", "embed", "hr", "img", "input", "meta", "link" , "param"]
concatMapM :: Monad m=> (a -> m [b]) -> [a] -> m [b]
concatMapM f xs = liftM concat (mapM f xs)
transformTreeM :: Monad m
=> (TST.TagTree str -> m [TST.TagTree str])
-> [TST.TagTree str]
-> m [TST.TagTree str]
transformTreeM act = concatMapM f
where
f (TST.TagBranch a b inner) = transformTreeM act inner >>= act . TST.TagBranch a b
f x = act x
| Tosainu/blog | src/Compiler.hs | mit | 4,376 | 0 | 16 | 1,065 | 1,474 | 752 | 722 | 92 | 6 |
{-# Language OverloadedStrings #-}
import Control.Arrow ((&&&), first, (>>>))
import System.Environment (getArgs)
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.IO as T
main :: IO ()
main = getArgs >>= run
run :: [String] -> IO ()
run [] = exec "\t" "\t"
run ["-h"] = help
run ["--help"] = help
run ["--", sep] = exec sep sep
run ["--", inSep, outSep] = exec inSep outSep
run [sep] = exec sep sep
run [inSep, outSep] = exec inSep outSep
run _ = help
help :: IO ()
help = putStrLn "Usage: tabulate [-h|--help] [--] [delimiter] [joiner]"
exec :: String -> String -> IO ()
exec inSepS outSepS = T.interact tabulate where
tabulate = T.lines
>>> map splitRow
>>> (map L.length &&& id)
>>> (fst &&& rectangle)
>>> uncurry (zipWith L.take)
>>> map joinRow
>>> T.unlines
rectangle = first maximum
>>> uncurry strip
>>> toColumns
>>> (lengths &&& id)
>>> uncurry (zipWith justify)
>>> toRows
splitRow = T.splitOn inSep
strip num = map ((++ L.repeat "") >>> L.take num)
toColumns = L.transpose
toRows = L.transpose
lengths = map (map T.length >>> maximum)
justify width = map (T.justifyLeft width ' ')
joinRow = T.intercalate outSep >>> T.stripEnd
inSep = T.pack inSepS
outSep = T.pack outSepS
| sordina/tabulate | tabulate.hs | mit | 1,691 | 0 | 15 | 671 | 516 | 272 | 244 | 43 | 1 |
-- |
-- Module : Graphics.WaveFront.Model
-- Description :
-- Copyright : (c) Jonatan H Sundqvist, 2016
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : stable
-- Portability : portable
--
-- TODO | - Single-pass (eg. consume all tokens only once) for additional performance (?)
-- -
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC Extensions
--------------------------------------------------------------------------------------------------------------------------------------------
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE OverloadedLists #-}
--------------------------------------------------------------------------------------------------------------------------------------------
-- Section
--------------------------------------------------------------------------------------------------------------------------------------------
-- TODO | - Clean this up
-- - Decide on API
module Graphics.WaveFront.Model (
BoundingBox(..),
facesOf, materialsOf,
tessellate, bounds,
hasTextures, textures,
createModel, createMTLTable,
fromIndices, fromFaceIndices, diffuseColours
) where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import qualified Data.Vector as V
import Data.Vector (Vector, (!?))
import Data.Text (Text)
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import Data.List (groupBy)
import Data.Maybe (listToMaybe, catMaybes)
import Linear (V2(..), V3(..))
import Control.Lens ((^.), (.~), (%~), (&), _1, _2, _3)
import Cartesian.Core (BoundingBox(..), fromExtents, x, y, z)
import Graphics.WaveFront.Types
import Graphics.WaveFront.Lenses
--------------------------------------------------------------------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
-- TODO | - Factor out these combinators
-- | Performs a computation on adjacent pairs in a list
-- TODO | - Factor out and make generic
pairwise :: (a -> a -> b) -> [a] -> [b]
pairwise f xs = zipWith f xs (drop 1 xs)
-- | Convers an Either to a Maybe
eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Right b) = Just b
eitherToMaybe (Left _) = Nothing
-- | Converts a Maybe to an Either
maybeToEither :: a -> Maybe b -> Either a b
maybeToEither _ (Just b) = Right b
maybeToEither a (Nothing) = Left a
-- Parser output churners (OBJ) ------------------------------------------------------------------------------------------------------------
-- TODO | - Move to separate module (eg. WaveFront.Model)
-- | Creates a mapping between group names and the corresponding bounds ([lower, upper)).
--
-- TODO | - Figure out how to deal with multiple group names (eg. "g mesh1 nose head")
-- - Include not just face indices but vertex indices (makes it easier to 'slice' GPU buffers) (maybe in a separate function)
groupsOf :: (Ord s, Integral i) => [OBJToken f s i m] -> Map (Set s) (i, i)
groupsOf = buildIndexMapWith . filter notObject
where
notObject (Object _) = False
notObject _ = True
-- | Creates a mapping between object names and the corresponding bounds ([lower, upper)).
objectsOf :: (Ord s, Integral i) => [OBJToken f s i m] -> Map (Set s) (i, i)
objectsOf = buildIndexMapWith . filter notGroup
where
notGroup (Group _) = False
notGroup _ = True
-- | Creates a mapping between names (of groups or objects) to face indices
--
-- TODO | - Refactor, simplify
-- - What happens if the same group or object appears multiple times (is that possible?)
-- - Rename or add function parameter (the -With suffix implies a function parameter)
buildIndexMapWith :: (Ord s, Integral i) => [OBJToken f s i m] -> Map (Set s) (i, i)
buildIndexMapWith = M.fromList . pairwise zipIndices . update 0
where
zipIndices (names, low) (_, upp) = (names, (low, upp))
-- TODO | - Separate Group and Object lists
-- - Rename (?)
-- - Factor out (might be useful for testing) (?)
update faceCount [] = [(S.empty, faceCount)]
update faceCount (Group names:xs) = (names, faceCount) : update faceCount xs
update faceCount (Object names:xs) = (names, faceCount) : update faceCount xs
update faceCount (OBJFace _:xs) = update (faceCount + 1) xs
update faceCount (_:xs) = update faceCount xs
-- | Filters out faces from a stream of OBJTokens and attaches the currently selected material,
-- as defined by the most recent LibMTL and UseMTL tokens.
facesOf :: forall f s i m. Ord s => MTLTable f s -> [OBJToken f s i m] -> [Either String (Face f s i m)]
facesOf materials' = makeFaces Nothing Nothing
where
-- | It's not always rude to make faces
-- TODO | - Keep refactoring...
-- - Rename (?)
makeFaces :: Maybe s -> Maybe s -> [OBJToken f s i m] -> [Either String (Face f s i m)]
makeFaces _ _ [] = []
makeFaces lib@(Just libName) mat@(Just matName) (OBJFace is:xs) = createFace materials' libName matName is : makeFaces lib mat xs
makeFaces lib@Nothing mat (OBJFace _:xs) = Left "No library selected for face" : makeFaces lib mat xs
makeFaces lib mat@Nothing (OBJFace _:xs) = Left "No material selected for face" : makeFaces lib mat xs
makeFaces _ mat (LibMTL libName:xs) = makeFaces (Just libName) mat xs
makeFaces lib _ (UseMTL matName:xs) = makeFaces lib (Just matName) xs
makeFaces lib mat (_:xs) = makeFaces lib mat xs
-- |
createFace :: Ord s => MTLTable f s -> s -> s -> m (VertexIndices i) -> Either String (Face f s i m)
createFace materials' libName matName indices' = do
material' <- lookupMaterial materials' libName matName
Right $ Face { fIndices=indices', fMaterial=material' }
-- | Tries to find a given material in the specified MTL table
-- TODO | - Specify missing material or library name (would require additional constraints on 's')
-- - Refactor
lookupMaterial :: Ord s => MTLTable f s -> s -> s -> Either String (Material f s)
lookupMaterial materials' libName matName = do
library <- maybeToEither "No such library" (M.lookup libName materials')
maybeToEither "No such material" (M.lookup matName library)
-- Parser output churners (MTL) ------------------------------------------------------------------------------------------------------------
-- | Constructs an MTL table from a list of (libraryName, token stream) pairs.
-- TODO | - Refactor, simplify
createMTLTable :: Ord s => [(s, [MTLToken f s])] -> Either String (MTLTable f s)
createMTLTable = fmap M.fromList . mapM (\(name, tokens) -> (name,) <$> materialsOf tokens)
-- | Constructs a map between names and materials. Incomplete material definitions
-- result in an error (Left ...).
--
-- TODO | - Debug information (eg. attributes without an associated material)
-- - Pass in error function (would allow for more flexible error handling) (?)
-- - Deal with duplicated attributes (probably won't crop up in any real situations)
materialsOf :: Ord s => [MTLToken f s] -> Either String (Map s (Material f s))
materialsOf = fmap M.fromList . mapM createMaterial . partitionMaterials
-- | Creates a new (name, material) pair from a stream of MTL tokens.
-- The first token should be a new material name.
createMaterial :: [MTLToken f s] -> Either String (s, Material f s)
createMaterial (NewMaterial name:attrs) = (name,) <$> fromAttributes attrs
createMaterial attrs = Left $ "Free-floating attributes"
-- | Breaks a stream of MTL tokens into lists of material definitions
-- TODO | - Rename (eg. groupMaterials) (?)
partitionMaterials :: [MTLToken f s] -> [[MTLToken f s]]
partitionMaterials = groupBy (\_ b -> not $ isNewMaterial b)
where
isNewMaterial (NewMaterial _) = True
isNewMaterial _ = False
-- | Creates a material
fromAttributes :: [MTLToken f s] -> Either String (Material f s)
fromAttributes attrs = case colours' of
Nothing -> Left $ "Missing colour(s)" -- TODO: More elaborate message (eg. which colour)
Just (amb, diff, spec) -> Right $ Material { fAmbient=amb,fDiffuse=diff, fSpecular=spec, fTexture=texture' }
where
colours' = materialColours attrs
texture' = listToMaybe [ name | MapDiffuse name <- attrs ]
-- | Tries to extract a diffuse colour, a specular colour, and an ambient colour from a list of MTL tokens
-- TODO | - Should we really require all three colour types (?)
-- - Rename (?)
materialColours :: [MTLToken f s] -> Maybe (Colour f, Colour f, Colour f)
materialColours attrs = (,,) <$>
listToMaybe [ c | (Diffuse c) <- attrs ] <*>
listToMaybe [ c | (Specular c) <- attrs ] <*>
listToMaybe [ c | (Ambient c) <- attrs ]
-- API functions ---------------------------------------------------------------------------------------------------------------------------
-- | Constructs a model from a stream of OBJ tokens, a materials table and an optional path to root of the model (used for textures, etc.)
--
-- TODO | - Performance, how are 'copies' of coordinates handled (?)
-- - Performance, one pass (with a fold perhaps)
--
-- I never knew pattern matching in list comprehensions could be used to filter by constructor
createModel :: (Ord s, Integral i) => OBJ f s i [] -> MTLTable f s -> Maybe FilePath -> Either String (Model f s i Vector)
createModel tokens materials root = do
faces' <- sequence $ facesOf materials tokens
return $ Model { fVertices = V.fromList [ vec | OBJVertex vec <- tokens ],
fNormals = V.fromList [ vec | OBJNormal vec <- tokens ],
fTexcoords = V.fromList [ vec | OBJTexCoord vec <- tokens ],
fFaces = packFaces faces',
fGroups = groupsOf tokens,
fObjects = objectsOf tokens,
fMaterials = materials,
fRoot = root }
where
packFace :: Face f s i [] -> Face f s i Vector
packFace face@Face{fIndices} = face { fIndices=V.fromList fIndices } -- indices %~ (_) -- TODO: Type-changing lenses
packFaces :: [] (Face f s i []) -> Vector (Face f s i Vector)
packFaces = V.fromList . map (packFace . tessellate)
-- |
-- TODO | - Specialise to [[Face]] (?)
-- - Check vertex count (has to be atleast three)
-- - Better names (?)
tessellate :: Face f s i [] -> Face f s i []
tessellate = indices %~ triangles
where
triangles [] = []
triangles (a:rest) = concat $ pairwise (\b c -> [a, b, c]) rest
-- | Finds the axis-aligned bounding box of the model
-- TODO | - Deal with empty vertex lists (?)
-- - Refactor
-- - Folding over applicative (fold in parallel)
-- - Make sure the order is right
bounds :: (Num f, Ord f, Foldable m, HasVertices (Model f s i m) (m (V3 f))) => Model f s i m -> BoundingBox (V3 f)
bounds model = fromExtents $ axisBounds (model^.vertices) <$> V3 x y z
where
-- TODO | - Factor out 'minmax'
minmaxBy :: (Ord o, Num o, Foldable m) => (a -> o) -> m a -> (o, o)
minmaxBy f values = foldr (\val' acc -> let val = f val' in (min val (fst acc), max val (snd acc))) (0, 0) values -- TODO: Factor out
axisBounds vs axis = minmaxBy (^.axis) vs
-- Orphaned TODOs?
-- TODO | - Deal with missing values properly
-- - Indexing should be defined in an API function
--------------------------------------------------------------------------------------------------------------------------------------------
-- TODO | - Polymorphic indexing and traversing
-- - Profile, optimise
-- - Index buffers
-- | Takes a vector of data, an index function, a choice function, a vector of some type with indices
-- and uses the indices to constructs a new Vector with the data in the original vector.
--
-- TODO | - Factor out the buffer-building logic
-- - Rewrite the above docstring...
fromIndices :: Vector v -> (Vector v -> i -> b) -> (a -> i) -> Vector a -> Vector b
fromIndices data' index choose = V.map (index data' . choose)
-- |
fromFaceIndices :: Integral i => Vector (v f) -> (Vector (v f) -> a -> b) -> (VertexIndices i -> a) -> Vector (Face f Text i Vector) -> Vector b
fromFaceIndices data' index choose = V.concatMap (fromIndices data' index (choose) . (^.indices))
-- |
-- TODO: Factor out per-vertex logic so we don't have to redefine this function entirely for each colour type
diffuseColours :: Vector (Face f s i Vector) -> Vector (Colour f)
diffuseColours faces' = V.concatMap (\f -> V.replicate (V.length $ f^.indices) (f^.material.diffuse)) faces'
-- TODO | - Do not create intermediate vectors (automatic fusion?)
-- - Allow fallback values (or function), or use Either
-- - Add docstrings
-- |
unindexedVertices :: Model f Text Int Vector -> Maybe (Vector (V3 f))
unindexedVertices model = sequence $ fromFaceIndices (model^.vertices) (index) (^.ivertex) (model^.faces)
where
index coords i = coords !? (i-1)
unindexedNormals :: Model f Text Int Vector -> Maybe (Vector (V3 f))
unindexedNormals model = sequence $ fromFaceIndices (model^.normals) (index) (^.inormal) (model^.faces)
where
index coords mi = mi >>= \i -> coords !? (i-1)
unindexedTexcoords :: Model f Text Int Vector -> Maybe (Vector (V2 f))
unindexedTexcoords model = sequence $ fromFaceIndices (model^.texcoords) (index) (^.itexcoord) (model^.faces)
where
index coords mi = mi >>= \i -> coords !? (i-1)
-- Model queries ---------------------------------------------------------------------------------------------------------------------------
-- TODO: Turn into Lenses/Getters/Isos (?)
-- | Does the model have textures?
hasTextures :: Ord s => Model f s i m -> Bool
hasTextures = not . S.null . textures
-- | The set of all texture names
textures :: Ord s => Model f s i m -> S.Set s
textures = S.fromList . catMaybes . map (^.texture) . concatMap M.elems . M.elems . (^.materials)
| SwiftsNamesake/3DWaves | src/Graphics/WaveFront/Model.hs | mit | 15,133 | 0 | 15 | 3,276 | 3,511 | 1,887 | 1,624 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Course.FastAnagrams where
import Course.Core
import Course.List
import Course.Functor
import qualified Data.Set as S
-- Return all anagrams of the given string
-- that appear in the given dictionary file.
fastAnagrams ::
Chars
-> Filename
-> IO (List Chars)
fastAnagrams =
error "todo: Course.FastAnagrams#fastAnagrams"
newtype NoCaseString =
NoCaseString {
ncString :: Chars
}
instance Eq NoCaseString where
(==) = (==) `on` map toLower . ncString
instance Show NoCaseString where
show = show . ncString
| harrisi/on-being-better | list-expansion/Haskell/course/src/Course/FastAnagrams.hs | cc0-1.0 | 610 | 0 | 9 | 108 | 123 | 74 | 49 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
import Hakyll
--------------------------------------------------------------------------------
main :: IO ()
main = hakyll $ do
match "css/*" $ compile compressCssCompiler
match ("js/*" .||. "images/*") $ do
route idRoute
compile copyFileCompiler
create ["site.css"] $ do
route idRoute
compile $ bundleCss
["css/bootstrap.css", "css/theme.css", "css/sugar.css"]
match "templates/*" $ compile templateCompiler
match ("about.markdown" .||. "index.markdown") $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/panel.html" defaultContext
>>= loadAndApplyTemplate "templates/layout.html" defaultContext
>>= relativizeUrls
--------------------------------------------------------------------------------
-- | Bundle css files to minimize HTTP requests.
bundleCss :: [Identifier] -> Compiler (Item String)
bundleCss ids = concatMap itemBody `fmap` mapM load ids >>= makeItem
| abeidler/abeidler.github.io | Site.hs | gpl-2.0 | 1,164 | 0 | 14 | 237 | 224 | 106 | 118 | 21 | 1 |
{-| Base common functionality.
This module holds common functionality shared across Ganeti daemons,
HTools and any other programs.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 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.Common
( GenericOptType
, StandardOptions(..)
, OptCompletion(..)
, ArgCompletion(..)
, PersonalityList
, optComplYesNo
, oShowHelp
, oShowVer
, oShowComp
, usageHelp
, versionInfo
, formatCommands
, reqWithConversion
, parseYesNo
, parseOpts
, parseOptsInner
, parseOptsCmds
, genericMainCmds
) where
import Control.Monad (foldM)
import Data.Char (toLower)
import Data.List (intercalate, stripPrefix, sortBy)
import Data.Maybe (fromMaybe)
import Data.Ord (comparing)
import qualified Data.Version
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.Info
import System.IO
import Text.Printf (printf)
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.Utils (wrap)
import qualified Ganeti.Version as Version (version)
-- | Parameter type.
data OptCompletion = OptComplNone -- ^ No parameter to this option
| OptComplFile -- ^ An existing file
| OptComplDir -- ^ An existing directory
| OptComplHost -- ^ Host name
| OptComplInetAddr -- ^ One ipv4\/ipv6 address
| OptComplOneNode -- ^ One node
| OptComplManyNodes -- ^ Many nodes, comma-sep
| OptComplOneInstance -- ^ One instance
| OptComplManyInstances -- ^ Many instances, comma-sep
| OptComplOneOs -- ^ One OS name
| OptComplOneIallocator -- ^ One iallocator
| OptComplInstAddNodes -- ^ Either one or two nodes
| OptComplOneGroup -- ^ One group
| OptComplInteger -- ^ Integer values
| OptComplFloat -- ^ Float values
| OptComplJobId -- ^ Job Id
| OptComplCommand -- ^ Command (executable)
| OptComplString -- ^ Arbitrary string
| OptComplChoices [String] -- ^ List of string choices
| OptComplSuggest [String] -- ^ Suggested choices
deriving (Show, Eq)
-- | Argument type. This differs from (and wraps) an Option by the
-- fact that it can (and usually does) support multiple repetitions of
-- the same argument, via a min and max limit.
data ArgCompletion = ArgCompletion OptCompletion Int (Maybe Int)
deriving (Show, Eq)
-- | A personality definition.
type Personality a = ( a -> [String] -> IO () -- The main function
, IO [GenericOptType a] -- The options
, [ArgCompletion] -- The description of args
, String -- Description
)
-- | Personality lists type, common across all binaries that expose
-- multiple personalities.
type PersonalityList a = [(String, Personality a)]
-- | Yes\/no choices completion.
optComplYesNo :: OptCompletion
optComplYesNo = OptComplChoices ["yes", "no"]
-- | Text serialisation for 'OptCompletion', used on the Python side.
complToText :: OptCompletion -> String
complToText (OptComplChoices choices) = "choices=" ++ intercalate "," choices
complToText (OptComplSuggest choices) = "suggest=" ++ intercalate "," choices
complToText compl =
let show_compl = show compl
stripped = stripPrefix "OptCompl" show_compl
in map toLower $ fromMaybe show_compl stripped
-- | Text serialisation for 'ArgCompletion'.
argComplToText :: ArgCompletion -> String
argComplToText (ArgCompletion optc min_cnt max_cnt) =
complToText optc ++ " " ++ show min_cnt ++ " " ++ maybe "none" show max_cnt
-- | Abbreviation for the option type.
type GenericOptType a = (OptDescr (a -> Result a), OptCompletion)
-- | Type class for options which support help and version.
class StandardOptions a where
helpRequested :: a -> Bool
verRequested :: a -> Bool
compRequested :: a -> Bool
requestHelp :: a -> a
requestVer :: a -> a
requestComp :: a -> a
-- | Option to request help output.
oShowHelp :: (StandardOptions a) => GenericOptType a
oShowHelp = (Option "h" ["help"] (NoArg (Ok . requestHelp)) "show help",
OptComplNone)
-- | Option to request version information.
oShowVer :: (StandardOptions a) => GenericOptType a
oShowVer = (Option "V" ["version"] (NoArg (Ok . requestVer))
"show the version of the program",
OptComplNone)
-- | Option to request completion information
oShowComp :: (StandardOptions a) => GenericOptType a
oShowComp =
(Option "" ["help-completion"] (NoArg (Ok . requestComp) )
"show completion info", OptComplNone)
-- | Usage info.
usageHelp :: String -> [GenericOptType a] -> String
usageHelp progname =
usageInfo (printf "%s %s\nUsage: %s [OPTION...]"
progname Version.version progname) . map fst
-- | Show the program version info.
versionInfo :: String -> String
versionInfo progname =
printf "%s %s\ncompiled with %s %s\nrunning on %s %s\n"
progname Version.version compilerName
(Data.Version.showVersion compilerVersion)
os arch
-- | Show completion info.
completionInfo :: String -> [GenericOptType a] -> [ArgCompletion] -> String
completionInfo _ opts args =
unlines $
map (\(Option shorts longs _ _, compinfo) ->
let all_opts = map (\c -> ['-', c]) shorts ++ map ("--" ++) longs
in intercalate "," all_opts ++ " " ++ complToText compinfo
) opts ++
map argComplToText args
-- | Helper for parsing a yes\/no command line flag.
parseYesNo :: Bool -- ^ Default value (when we get a @Nothing@)
-> Maybe String -- ^ Parameter value
-> Result Bool -- ^ Resulting boolean value
parseYesNo v Nothing = return v
parseYesNo _ (Just "yes") = return True
parseYesNo _ (Just "no") = return False
parseYesNo _ (Just s) = fail ("Invalid choice '" ++ s ++
"', pass one of 'yes' or 'no'")
-- | Helper function for required arguments which need to be converted
-- as opposed to stored just as string.
reqWithConversion :: (String -> Result a)
-> (a -> b -> Result b)
-> String
-> ArgDescr (b -> Result b)
reqWithConversion conversion_fn updater_fn =
ReqArg (\string_opt opts -> do
parsed_value <- conversion_fn string_opt
updater_fn parsed_value opts)
-- | Max command length when formatting command list output.
maxCmdLen :: Int
maxCmdLen = 60
-- | Formats the description of various commands.
formatCommands :: (StandardOptions a) => PersonalityList a -> [String]
formatCommands personalities =
concatMap (\(cmd, (_, _, _, desc)) ->
fmtDesc cmd (wrap maxWidth desc) "-" []) $
sortBy (comparing fst) personalities
where mlen = min maxCmdLen . maximum $ map (length . fst) personalities
maxWidth = 79 - 3 - mlen
fmtDesc _ [] _ acc = reverse acc
fmtDesc cmd (d : ds) sep acc =
fmtDesc "" ds " " (printf " %-*s %s %s" mlen cmd sep d : acc)
-- | Formats usage for a multi-personality program.
formatCmdUsage :: (StandardOptions a) => String -> PersonalityList a -> String
formatCmdUsage prog personalities =
let header = [ printf "Usage: %s {command} [options...] [argument...]" prog
, printf "%s <command> --help to see details, or man %s"
prog prog
, ""
, "Commands:"
]
rows = formatCommands personalities
in unlines $ header ++ rows
-- | Displays usage for a program and exits.
showCmdUsage :: (StandardOptions a) =>
String -- ^ Program name
-> PersonalityList a -- ^ Personality list
-> Bool -- ^ Whether the exit code is success or not
-> IO b
showCmdUsage prog personalities success = do
let usage = formatCmdUsage prog personalities
putStr usage
if success
then exitSuccess
else exitWith $ ExitFailure C.exitFailure
-- | Generates completion information for a multi-command binary.
multiCmdCompletion :: (StandardOptions a) => PersonalityList a -> String
multiCmdCompletion personalities =
argComplToText $
ArgCompletion (OptComplChoices (map fst personalities))
1 (Just 1)
-- | Displays completion information for a multi-command binary and exits.
showCmdCompletion :: (StandardOptions a) => PersonalityList a -> IO b
showCmdCompletion personalities =
putStrLn (multiCmdCompletion personalities) >> exitSuccess
-- | Command line parser, using a generic 'Options' structure.
parseOpts :: (StandardOptions a) =>
a -- ^ The default options
-> [String] -- ^ The command line arguments
-> String -- ^ The program name
-> [GenericOptType a] -- ^ The supported command line options
-> [ArgCompletion] -- ^ The supported command line arguments
-> IO (a, [String]) -- ^ The resulting options and
-- leftover arguments
parseOpts defaults argv progname options arguments =
case parseOptsInner defaults argv progname options arguments of
Left (code, msg) -> do
hPutStr (if code == ExitSuccess then stdout else stderr) msg
exitWith code
Right result ->
return result
-- | Command line parser, for programs with sub-commands.
parseOptsCmds :: (StandardOptions a) =>
a -- ^ The default options
-> [String] -- ^ The command line arguments
-> String -- ^ The program name
-> PersonalityList a -- ^ The supported commands
-> [GenericOptType a] -- ^ Generic options
-> IO (a, [String], a -> [String] -> IO ())
-- ^ The resulting options and leftover arguments
parseOptsCmds defaults argv progname personalities genopts = do
let usage = showCmdUsage progname personalities
check c = case c of
-- hardcoded option strings here!
"--version" -> putStrLn (versionInfo progname) >> exitSuccess
"--help" -> usage True
"--help-completion" -> showCmdCompletion personalities
_ -> return c
(cmd, cmd_args) <- case argv of
cmd:cmd_args -> do
cmd' <- check cmd
return (cmd', cmd_args)
[] -> usage False
case cmd `lookup` personalities of
Nothing -> usage False
Just (mainfn, optdefs, argdefs, _) -> do
optdefs' <- optdefs
(opts, args) <- parseOpts defaults cmd_args progname
(optdefs' ++ genopts) argdefs
return (opts, args, mainfn)
-- | Inner parse options. The arguments are similar to 'parseOpts',
-- but it returns either a 'Left' composed of exit code and message,
-- or a 'Right' for the success case.
parseOptsInner :: (StandardOptions a) =>
a
-> [String]
-> String
-> [GenericOptType a]
-> [ArgCompletion]
-> Either (ExitCode, String) (a, [String])
parseOptsInner defaults argv progname options arguments =
case getOpt Permute (map fst options) argv of
(opts, args, []) ->
case foldM (flip id) defaults opts of
Bad msg -> Left (ExitFailure 1,
"Error while parsing command line arguments:\n"
++ msg ++ "\n")
Ok parsed ->
select (Right (parsed, args))
[ (helpRequested parsed,
Left (ExitSuccess, usageHelp progname options))
, (verRequested parsed,
Left (ExitSuccess, versionInfo progname))
, (compRequested parsed,
Left (ExitSuccess, completionInfo progname options
arguments))
]
(_, _, errs) ->
Left (ExitFailure 2, "Command line error: " ++ concat errs ++ "\n" ++
usageHelp progname options)
-- | Parse command line options and execute the main function of a
-- multi-personality binary.
genericMainCmds :: (StandardOptions a) =>
a
-> PersonalityList a
-> [GenericOptType a]
-> IO ()
genericMainCmds defaults personalities genopts = do
cmd_args <- getArgs
prog <- getProgName
(opts, args, fn) <-
parseOptsCmds defaults cmd_args prog personalities genopts
fn opts args
| damoxc/ganeti | src/Ganeti/Common.hs | gpl-2.0 | 13,664 | 0 | 18 | 4,144 | 2,690 | 1,453 | 1,237 | 245 | 6 |
module Handler.Schule where
import Import
import Autolib.Multilingual
spracheMsg :: Language -> AutotoolMessage
spracheMsg sprache' = case sprache' of
DE -> MsgSpracheDE
NL -> MsgSpracheNL
UK -> MsgSpracheUK
spracheOptionen :: Handler (OptionList Language)
spracheOptionen = optionsPairs $ map (\s -> (spracheMsg s, s)) [DE, NL, UK]
getSchuleR :: SchuleId -> Handler Html
getSchuleR = postSchuleR
postSchuleR :: SchuleId -> Handler Html
postSchuleR schuleId = do
schule <- runDB $ get404 schuleId
((result, formWidget), formEnctype) <- runFormPost $ schuleForm $ Just schule
case result of
FormMissing -> return ()
FormFailure _ -> return ()
FormSuccess schule' -> do
runDB $ replace schuleId schule'
setMessageI MsgSchuleBearbeitet
defaultLayout $
formToWidget (SchuleR schuleId) Nothing formEnctype formWidget
schuleForm :: Maybe Schule -> Form Schule
schuleForm mschule =
renderBootstrap3 BootstrapBasicForm $ Schule
<$> areq textField (bfs MsgSchuleName) (schuleName <$> mschule)
<*> aopt textField (bfs MsgSchuleSuffix) (schuleMailSuffix <$> mschule)
<*> pure (maybe False schuleUseShibboleth mschule)
<*> areq (selectField spracheOptionen) (bfs MsgSchuleSprache) (schulePreferredLanguage <$> mschule)
<* bootstrapSubmit (BootstrapSubmit (maybe MsgSchuleAnlegen (\ _ -> MsgSchuleBearbeiten) mschule) "btn-success" [])
| marcellussiegburg/autotool | yesod/Handler/Schule.hs | gpl-2.0 | 1,393 | 0 | 13 | 238 | 431 | 215 | 216 | 32 | 3 |
import qualified SimpleArithmeticTest as Arith
import qualified IdempotenceTest as Idem
import Test.QuickCheck
main :: IO ()
main = do
quickCheck Arith.prop_halfIdentity
quickCheck Arith.prop_stringListOrdered
quickCheck Arith.plusAssociative
quickCheck Arith.plusCommutative
quickCheck Arith.productAssociative
quickCheck Arith.productCommutative
quickCheck Arith.prop_quotRem
quickCheck Arith.prop_divMod
quickCheck Arith.prop_powerNotAssociative
quickCheck Arith.prop_powerNotCommutative
quickCheck Arith.prop_listDoubleReverse
quickCheck Arith.prop_dollarFunction
quickCheck Arith.prop_compositionFunction
quickCheck Arith.prop_cons
quickCheck Arith.f
quickCheck Arith.f'
quickCheck Idem.f
quickCheck Idem.f'
| nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles | Testing/quickcheck-testing/test/Main.hs | gpl-3.0 | 786 | 0 | 8 | 128 | 177 | 75 | 102 | 23 | 1 |
-- Propositional logic
module PropLogicLib (
Form(F, T, Var, Neg, Conj, Disj, Imp, Equiv),
showForm, readsForm, pf,
Theorem(),
projHyps, projForm,
taut, disch, mp,
andIntro, andElimL, andElimR,
orIntroL, orIntroR, orElim,
notIntro, notElim,
trueIntro, falseElim
)
where {
import List;
import Char;
import Parse;
import Set;
data Form = F
| T
| Var String
| Neg Form
| Conj Form Form
| Disj Form Form
| Imp Form Form
| Equiv Form Form;
-- This function restricts variable names to proper identifiers
mkVar :: String -> Var;
mkVar s = if isIdentifier s then
Var s
else
error "PropLogic.mkVar: bad identifer: " + s;
isIdentifier s = isAlpha (head s) &&
and (map isAlphaNum (tail s));
-- Equality of formulae
instance Equal Form where
eq fm1 fm2 =
case (fm1, fm2) of {
(F, F) -> True;
(T, T) -> True;
(Var s1, Var s2) -> (s1 `eq` s2);
(Neg fm1a, Neg fm2a) -> (eq fm1a fm2a);
(Conj fm1a fm1b, Conj fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Disj fm1a fm1b, Disj fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Imp fm1a fm1b, Imp fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Equiv fm1a fm1b, Equiv fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
_ -> False
};
instance Show Form where {
shows fm s = showForm fm ++ s;
show fm = showForm fm
};
-- The first arg (fm) is present purely in order so that the dynamic class
-- mechanism can determine which instance to use. It is not used in computing the result.
instance Read Form where
reads fm = readsForm;
-- A convenient "parse form" function
pf :: String -> Form;
pf = unique (exact readsForm);
-- Unparsing functions
showForm :: Form -> String;
showForm fm =
case fm of {
F -> "F";
T -> "T";
Var s -> s;
Neg fm -> "~ " ++ showParenForm fm;
Conj fm1 fm2 -> opForm fm1 " & " fm2;
Disj fm1 fm2 -> opForm fm1 " | " fm2;
Imp fm1 fm2 -> opForm fm1 " => " fm2;
Equiv fm1 fm2 -> opForm fm1 " == " fm2
};
opForm fm1 op fm2 = showParenForm fm1 ++ op ++ showParenForm fm2;
-- A formula is deemed to be atomic (for unparsing) if it is a truth value, a Var or a Neg of an atomic formula
isAtomic fm =
case fm of {
F -> True;
T -> True;
Var _ -> True;
Neg fm -> isAtomic fm;
_ -> False
};
-- Apply paretheses unless atomic
showParenForm fm =
if isAtomic fm then
showForm fm
else
"(" ++ showForm fm ++ ")";
-- Parsing functions
readsForm :: Reads Form;
readsForm = readsAtomicForm <> readsBinOpForm;
readsAtomicForm = readsTruthValue <> readsVar <> readsNegForm <> readsBracketedForm;
readsTruthValue = spaced ((char 'F' ~> const F) <> (char 'T' ~> const T));
readsVar = spaced identifier ~> Var;
readsNegForm = (spaced (char '~') >> readsAtomicForm) ~> (Neg. snd);
readsBracketedForm = bracketed readsForm;
readsBinOpForm = (readsAtomicForm >> spaced operator >> readsAtomicForm) ~> mkBinForm;
mkBinForm x =
case x of {
((f1, "&" ), f2) -> Conj f1 f2;
((f1, "|" ), f2) -> Disj f1 f2;
((f1, "=>"), f2) -> Imp f1 f2;
((f1, "=="), f2) -> Equiv f1 f2;
((f1, op ), f2) -> error "PropLogic.mkBinForm: unknown operator: " ++ op
};
-- --- Theorems ---------------------------------------------------------------------------------------------
type Name = String;
type Hyp = (Name, Form);
type Hyps = [Hyp];
data Theorem = Thm Hyps Form;
projHyps :: Thm -> Hyps;
projHyps thm = case thm of Thm hyps _ -> hyps;
projForm :: Thm -> Form;
projForm thm = case thm of Thm _ fm -> fm;
instance Show Theorem where {
shows thm s = showThm thm ++ s;
show thm = showThm thm
};
showThm :: Theorem -> String;
showThm thm =
case thm of
Thm hyps conc -> showNames (map fst hyps) ++ " |- " ++ showForm conc;
showNames :: [Name] -> String;
showNames names =
if null names then
""
else
'{' : head names ++ concat [ ", " ++ name | name <- tail names] ++ "} ";
-- Natural deduction inference rules ----------------------------------------------------------------------
taut :: Name -> Form -> Thm;
taut name fm = Thm [(name,fm)] fm;
disch :: Name -> Theorem -> Theorem;
disch name thm =
case thm of
Thm hyps conc ->
let { p = \hyp -> fst hyp `eq` name;
hypsPair = partition p hyps;
hyps1 = fst hypsPair;
hyps2 = snd hypsPair
} in case hyps1 of {
[(nm, fm)] -> Thm hyps2 (Imp fm conc);
_ -> error "PropLogic.impIntro: hypothesis not present"
};
mp :: Theorem -> Theorem -> Theorem;
mp thm1 thm2 =
case (thm1, thm2) of {
(Thm hyps1 (Imp fm1a fm1b), Thm hyps2 fm2) ->
let { clashes = isClash hyps1 hyps2;
hyps = hyps1 ++ hyps2
} in if null clashes then
if fm1a `eq` fm2 then
Thm hyps fm1b
else
error "PropLogic.mp: formulae do not match"
else
error ("PropLogic.mp: " ++ showNames clashes);
_ -> error "PropLogic.mp: not an implication"
};
andIntro :: Theorem -> Theorem -> Theorem;
andIntro thm1 thm2 =
case (thm1, thm2) of
((Thm hyps1 conc1), (Thm hyps2 conc2)) ->
Thm (merge hyps1 hyps2) (Conj conc1 conc2);
andElimL, andElimR :: Theorem -> Theorem;
andElimL thm =
case thm of {
Thm hyps (Conj fmL fmR) -> Thm hyps fmL;
_ -> error "PropLogic.andElimL: not a conjunction"
};
andElimR thm =
case thm of {
Thm hyps (Conj fmL fmR) -> Thm hyps fmR;
_ -> error "PropLogic.andElimR: not a conjunction"
};
orIntroL, orIntroR :: Theorem -> Form -> Theorem;
orIntroL thm fmR =
case thm of
Thm hyps fmL -> Thm hyps (Disj fmL fmR);
orIntroR thm fmL =
case thm of
Thm hyps fmR -> Thm hyps (Disj fmL fmR);
orElim :: Theorem -> Theorem -> Theorem -> Theorem;
orElim thm thm1 thm2 =
case (thm, (thm1, thm2)) of
(Thm hyps fm, (Thm hyps1 fm1, Thm hyps2 fm2)) ->
case fm of {
Disj fmL fmR ->
let { hyps1' = removeForm fmL hyps1;
hyps2' = removeForm fmR hyps2;
hyps' = merge hyps (merge hyps1' hyps2')
} in if eq fm1 fm2 then
Thm hyps' fm1
else
error ("PropLogic.orElim: theorems do not match: " ++ show fm1 ++ ", and " ++ show fm2);
_ -> error ("PropLogic.orElim: not a disjunction: " ++ show fm)
};
notIntro :: Name -> Theorem -> Theorem;
notIntro nm thm =
case thm of
Thm hyps fm ->
if (fm `neq` F) then
error ("PropLogic.notIntro: not F: " ++ show fm)
else
let { p = \hyp -> fst hyp `eq` nm;
hypsPair = partition p hyps;
hyps1 = fst hypsPair;
hyps2 = snd hypsPair
} in case hyps1 of {
[(nm,fm)] -> Thm hyps2 (Neg fm);
_ -> error ("PropLogic.notIntro: hyp not present: " ++ nm)
};
notElim :: Theorem -> Theorem -> Theorem;
notElim thm1 thm2 =
case (thm1, thm2) of {
((Thm hyps1 fm1),(Thm hyps2 (Neg fm2))) ->
if (fm1 `eq` fm2) then
Thm (merge hyps1 hyps2) F
else
error "PropLogic.notElim: non-matching formulae";
_ -> error "PropLogic.notElim: not a negation"
};
trueIntro :: Theorem;
trueIntro = Thm [] T;
falseElim :: Theorem -> Form -> Theorem;
falseElim thm fm =
case thm of {
Thm hyps F -> Thm hyps fm;
_ -> error "PropLogic.falseElim: non-false theorem"
};
-- Attempt to merge two list of hypotheses. Throws an error if the same name occurs
-- in each list but associated with a different formula.
merge :: Hyps -> Hyps -> Hyps;
merge hyps1 hyps2 =
let clashes = isClash hyps1 hyps2
in if null clashes then
nub (hyps1 ++ hyps2)
else
error ("PropLogic.merge: " ++ showNames clashes);
-- ---------------------------------------
-- This function compares two sets of hypotheses; it returns a list of the names of any
-- clashes. Thus, the return of an empty list denotes success.
isClash :: [Hyp] -> [Hyp] -> [Name];
isClash hyps1 hyps2 =
case hyps2 of {
[] -> [];
hyp:hyps -> isClash' hyps1 hyp ++ isClash hyps1 hyps
};
isClash' :: [Hyp] -> Hyp -> [Name];
isClash' hyps hyp =
case hyps of {
[] -> [];
hyp1:hyps1 -> isClash'' hyp hyp1 ++ isClash' hyps1 hyp
};
isClash'' :: Hyp -> Hyp -> [Name];
isClash'' hyp1 hyp2 =
case (hyp1, hyp2) of {
((name1, fm1), (name2, fm2)) ->
if (name1 `neq` name2) || (fm1 `eq` fm2) then
[]
else
[name1];
_ -> hyp1
};
-- This function removes a formula from a list of hypotheses. It fails if the formula is not present
removeForm :: Form -> [Hyp] -> [Hyp];
removeForm fm hyps =
case hyps of {
[] -> error ("PropLogic.removeHyp: formula not found: " ++ show fm);
hyp: hyps -> if eq fm (snd hyp) then
hyps
else
hyp : removeForm fm hyps
}
}
| ckaestne/CIDE | CIDE_Language_Haskell/test/fromviral/PropLogicLib.hs | gpl-3.0 | 10,238 | 16 | 19 | 3,865 | 3,003 | 1,649 | 1,354 | -1 | -1 |
module MaFRP.Netwire.Test where
import Control.Wire
import Prelude hiding
((.)
, id
)
wire :: (Monad m, HasTime t s) => Wire s () m a t
wire = time
main :: IO ()
main = testWire clockSession_ wire
| KenetJervet/mapensee | haskell/frp/Netwire/Test.hs | gpl-3.0 | 221 | 0 | 7 | 62 | 86 | 49 | 37 | 9 | 1 |
module L0229 where
data Maybe1 a = Just1 a | Nothing1 deriving Show
instance Functor Maybe1 where
fmap f Nothing1 = Nothing1
fmap f (Just1 a) = Just1 (f a)
instance Applicative Maybe1 where
pure = Just1
(<*>) Nothing1 _ = Nothing1
(<*>) _ Nothing1 = Nothing1
(<*>) (Just1 a) (Just1 b) = Just1 (a b)
instance Monad Maybe1 where
(>>=) Nothing1 f = Nothing1
(>>=) (Just1 x) f = f x
data Expr = Val Int | Div Expr Expr
eval0 :: Expr -> Int
eval0 (Val a) = a
eval0 (Div x y) = div (eval0 x) (eval0 y)
eval1 :: Expr -> Maybe1 Int
eval1 (Val a) = Just1 a
eval1 (Div x y) = case eval1 x of
Nothing1 -> Nothing1
Just1 n -> case eval1 y of
Nothing1 -> Nothing1
Just1 m -> safeDiv n m
safeDiv _ 0 = Nothing1
safeDiv n m = Just1 (div n m)
--eval2 :: Expr -> Maybe1: Int
--eval2 (Val n) = pure n
--eval2 (Div x y) = pure safeDiv <*> eval2 x <*> eval2 y
eval3 :: Expr -> Maybe1 Int
eval3 (Val n) = Just1 n
eval3 (Div x y) = eval3 x >>= \n ->
eval3 y >>= \m ->
safeDiv n m
eval4 :: Expr -> Maybe1 Int
eval4 (Val n) = Just1 n
eval4 (Div x y) = do
n <- eval4 x
m <- eval4 y
safeDiv n m
pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do
x <- xs
y <- ys
return (x,y)
pairs' :: [a] -> [b] -> [(a,b)]
pairs' xs ys = [(x,y)|x <- xs,y <- ys]
pairs'' :: [a] -> [b] -> [(a,b)]
pairs'' xs ys = pure (\x->(\y->(x,y))) <*> xs <*> ys
--pairs''' xs ys = xs >>= \x ->
-- ys >>= \y ->
-- (x,y)
| cwlmyjm/haskell | AFP/L0229.hs | mpl-2.0 | 1,557 | 0 | 12 | 503 | 722 | 376 | 346 | 46 | 3 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.Redis.Resp
( Resp (..)
, resp
, encode
, decode
) where
import Control.Applicative
import Control.Monad (replicateM)
import Data.Attoparsec.ByteString.Char8 hiding (char8)
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Builder
import Data.Int
import Data.Monoid
import Prelude hiding (take, takeWhile)
import qualified Data.Attoparsec.ByteString.Lazy as P
import qualified Data.ByteString.Lazy as Lazy
-- | 'Resp' defines the various RESP constructors.
data Resp
= Str !ByteString -- ^ RESP simple strings
| Err !ByteString -- ^ RESP errors
| Int !Int64 -- ^ RESP integers
| Bulk !ByteString -- ^ RESP bulk strings
| Array !Int [Resp] -- ^ RESP arrays
| NullArray
| NullBulk
deriving (Eq, Ord, Show)
decode :: ByteString -> Either String Resp
decode = P.eitherResult . P.parse resp
encode :: Resp -> Lazy.ByteString
encode d = toLazyByteString (go d)
where
go (Str x) = char8 '+' <> lazyByteString x <> crlf'
go (Err x) = char8 '-' <> lazyByteString x <> crlf'
go (Int x) = char8 ':' <> int64Dec x <> crlf'
go (Bulk x) = char8 '$'
<> int64Dec (Lazy.length x)
<> crlf'
<> lazyByteString x
<> crlf'
go (Array n x) = char8 '*'
<> intDec n
<> crlf'
<> foldr (<>) mempty (map go x)
go NullArray = nullArray
go NullBulk = nullBulk
-----------------------------------------------------------------------------
-- Parsing
-- | An attoparsec parser to parse a single 'Resp' value.
resp :: Parser Resp
resp = do
t <- anyChar
case t of
'+' -> Str `fmap` bytes <* crlf
'-' -> Err `fmap` bytes <* crlf
':' -> Int <$> signed decimal <* crlf
'$' -> bulk
'*' -> array
_ -> fail $ "invalid type tag: " ++ show t
bulk :: Parser Resp
bulk = do
n <- signed decimal <* crlf
if | n >= 0 -> Bulk . Lazy.fromStrict <$> take n <* crlf
| n == -1 -> return NullBulk
| otherwise -> fail "negative bulk length"
array :: Parser Resp
array = do
n <- signed decimal <* crlf :: Parser Int
if | n >= 0 -> Array n <$> replicateM n resp
| n == -1 -> return NullArray
| otherwise -> fail "negative array length"
bytes :: Parser ByteString
bytes = Lazy.fromStrict <$> takeWhile (/= '\r')
crlf :: Parser ()
crlf = string "\r\n" >> return ()
-----------------------------------------------------------------------------
-- Serialising
nullArray, nullBulk, crlf' :: Builder
nullArray = byteString "*-1\r\n"
nullBulk = byteString "$-1\r\n"
crlf' = byteString "\r\n"
| twittner/redis-resp | src/Data/Redis/Resp.hs | mpl-2.0 | 2,938 | 0 | 14 | 760 | 817 | 428 | 389 | 84 | 7 |
-- brittany { lconfig_indentAmount: 4, lconfig_indentPolicy: IndentPolicyMultiple }
foo = do
let aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
foo
| lspitzner/brittany | data/Test355.hs | agpl-3.0 | 218 | 0 | 10 | 38 | 23 | 11 | 12 | 4 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Core.ModelSpec where
import Core.Database ((=:))
import Core.Model
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified GHC.Generics as GN
import qualified Misc.Json as Json
import SpecHelper
data Post = Post
{ postId :: Maybe Text
, count :: Integer
, email :: Text
, password :: Text
} deriving (GN.Generic)
instance Model Post
spec :: Spec
spec =
describe "Core.ModelSpec" $
context "Simple Text" $ do
it "parses json with postId" $
gToJson (GN.from dataWithPostId) `shouldBe`
Json.JSObject
(M.fromList
[ ("count", Json.JSInt 3)
, ("email", Json.JSString "hello@world.com")
, ("password", Json.JSString "SHA256")
, ("post_id", Json.JSString "Hello")
])
it "parses json without postId" $
gToJson (GN.from dataWithoutPostId) `shouldBe`
Json.JSObject
(M.fromList
[ ("count", Json.JSInt 2)
, ("email", Json.JSString "admin@hello.com")
, ("password", Json.JSString "MD5")
])
it "parses bson with postId" $
gToDocument (GN.from dataWithPostId) `shouldBe`
[ "post_id" =: ("Hello" :: Text)
, "count" =: (3 :: Int)
, "email" =: ("hello@world.com" :: Text)
, "password" =: ("SHA256" :: Text)
]
it "parses bson without postId" $
gToDocument (GN.from dataWithoutPostId) `shouldBe`
[ "count" =: (2 :: Int)
, "email" =: ("admin@hello.com" :: Text)
, "password" =: ("MD5" :: Text)
]
where
dataWithPostId = Post (Just "Hello") 3 "hello@world.com" "SHA256"
dataWithoutPostId = Post Nothing 2 "admin@hello.com" "MD5"
main :: IO ()
main = hspec spec
| inq/agitpunkt | spec/Core/ModelSpec.hs | agpl-3.0 | 1,853 | 0 | 15 | 538 | 516 | 289 | 227 | 51 | 1 |
-- |
-- Module: SwiftNav.SBP
-- Copyright: Copyright (C) 2015 Swift Navigation, Inc.
-- License: LGPL-3
-- Maintainer: Mark Fine <dev@swiftnav.com>
-- Stability: experimental
-- Portability: portable
module SwiftNav.SBP where
import BasicPrelude
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.ByteString
import Data.Word
((*- for m in modules *))
import (((m)))
((*- endfor *))
msgPreamble :: Word8
msgPreamble = 0x55
data Msg = Msg
{ msgSBPType :: Word16
, msgSBPSender :: Word16
, msgSBPLen :: Word8
, msgSBPPayload :: ByteString
, msgSBPCrc :: Word16
} deriving ( Show, Read, Eq )
instance Binary Msg where
get = do
msgSBPType <- getWord16le
msgSBPSender <- getWord16le
msgSBPLen <- getWord8
msgSBPPayload <- getByteString $ fromIntegral msgSBPLen
msgSBPCrc <- getWord16le
return Msg {..}
put Msg {..} = do
putWord16le msgSBPType
putWord16le msgSBPSender
putWord8 msgSBPLen
putByteString msgSBPPayload
putWord16le msgSBPCrc
getMsg :: Get Msg
getMsg = do
preamble <- getWord8
if preamble /= msgPreamble then getMsg else get
putMsg :: Msg -> Put
putMsg msg = do
putWord8 msgPreamble
put msg
((* for m in msgs *))
((*- if loop.first *))
data SBPMsg =
SBP(((m))) (((m)))
((*- else *))
| SBP(((m))) (((m)))
((*- endif *))
((*- if loop.last *))
deriving ( Show, Read, Eq )
((*- endif *))
((*- endfor *))
| paparazzi/libsbp | generator/sbpg/targets/resources/SbpTemplate.hs | lgpl-3.0 | 1,443 | 6 | 10 | 316 | 496 | 277 | 219 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
module Sqlcmds where
import Str(str)
-- -----------------------------------------------------------------------------------------------------
-- ----------------------------------------------------------------------------------------------------
stuff = [str|
SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, c.relname AS TABLE_NAME,
CASE n.nspname ~ '^pg_' OR n.nspname = 'information_schema'
WHEN true THEN
CASE
WHEN n.nspname = 'pg_catalog' OR n.nspname = 'information_schema' THEN
CASE c.relkind WHEN 'r' THEN 'SYSTEM TABLE' WHEN 'v' THEN 'SYSTEM VIEW' WHEN 'i' THEN 'SYSTEM INDEX' ELSE NULL END
WHEN n.nspname = 'pg_toast' THEN
CASE c.relkind WHEN 'r' THEN 'SYSTEM TOAST TABLE' WHEN 'i' THEN 'SYSTEM TOAST INDEX' ELSE NULL END ELSE CASE c.relkind WHEN 'r' THEN 'TEMPORARY TABLE' WHEN 'i' THEN 'TEMPORARY INDEX' WHEN 'S' THEN 'TEMPORARY SEQUENCE' WHEN 'v' THEN 'TEMPORARY VIEW' ELSE NULL END
END
WHEN false THEN
CASE c.relkind
WHEN 'r' THEN 'TABLE'
WHEN 'i' THEN 'INDEX'
WHEN 'S' THEN 'SEQUENCE'
WHEN 'v' THEN 'VIEW'
WHEN 'c' THEN 'TYPE'
WHEN 'f' THEN 'FOREIGN TABLE'
ELSE NULL
END
ELSE NULL
END AS TABLE_TYPE,
d.description AS REMARKS
FROM pg_catalog.pg_namespace n, pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_description d ON (c.oid = d.objoid AND d.objsubid = 0) LEFT JOIN pg_catalog.pg_class dc ON (d.classoid=dc.oid AND dc.relname='pg_class') LEFT JOIN pg_catalog.pg_namespace dn ON (dn.oid=dc.relnamespace AND dn.nspname='pg_catalog') WHERE c.relnamespace = n.oid AND n.nspname LIKE 'account' AND (false OR ( c.relkind = 'r' AND n.nspname !~ '^pg_' AND n.nspname <> 'information_schema' ) )
ORDER BY TABLE_TYPE,TABLE_SCHEM,TABLE_NAME
|]
| sourcewave/pg-schema-diff | Sqlcmds.hs | unlicense | 1,882 | 0 | 5 | 419 | 24 | 18 | 6 | 4 | 1 |
--
-- Emmental.hs
-- Interpreter for the Emmental Programming Language
-- Chris Pressey, Cat's Eye Technologies
-- This work is in the public domain. See UNLICENSE for more information.
--
module Language.Emmental where
import Prelude (
Show, Char, IO, putStr, getChar, putChar, last, init,
(++), (+), (-), (*), mod, div, return, take, reverse, show
)
import qualified Data.Map as Map
import qualified Data.Char as Char
-----------------------------------------------------------------------
-- ============================ Symbols ============================ --
-----------------------------------------------------------------------
type Symbol = Char
-----------------------------------------------------------------------
-- ======================== Program States ========================= --
-----------------------------------------------------------------------
data State = State {
stack :: [Symbol],
queue :: [Symbol],
getCh :: IO Char,
putCh :: Char -> IO ()
}
instance Show State where
show State{ stack=stack, queue=queue } =
"State {stack = " ++ (show stack) ++ ", queue = " ++ (show queue) ++ "}"
pop st@State{ stack=(head:tail) } = (head, st{ stack=tail })
push st@State{ stack=stack } sym = st{ stack=(sym:stack) }
popString st@State{ stack=(';':tail) } = ([], st{ stack=tail })
popString st@State{ stack=(head:tail) } =
let
(string, state') = popString st{ stack=tail }
in
(string ++ [head], state')
enqueue st@State{ queue=queue } symbol = st{ queue=(symbol:queue) }
dequeue st@State{ queue=queue } =
let
symbol = last queue
queue' = init queue
in
(symbol, st{ queue=queue' })
-----------------------------------------------------------------------
-- ========================= Interpreters ========================== --
-----------------------------------------------------------------------
data Interpreter = Interp (Map.Map Symbol Operation)
fetch (Interp map) sym = Map.findWithDefault (fitRegOp opNop) sym map
supplant (Interp map) sym op = (Interp (Map.insert sym op map))
-----------------------------------------------------------------------
-- ========================== Operations =========================== --
-----------------------------------------------------------------------
type Operation = State -> Interpreter -> IO (State, Interpreter)
composeOps :: Operation -> Operation -> Operation
composeOps op1 op2 = f where
f state interpreter = do
(state', interpreter') <- op1 state interpreter
op2 state' interpreter'
createOp :: Interpreter -> [Symbol] -> Operation
createOp interpreter [] =
(fitRegOp opNop)
createOp interpreter (head:tail) =
composeOps (fetch interpreter head) (createOp interpreter tail)
--
-- It's useful for us to express a lot of our operators as non-monadic
-- functions that don't affect the interpreter. This is a little "adapter"
-- function that lets us create monadic functions with the right signature
-- from them.
--
fitRegOp :: (State -> State) -> Operation
fitRegOp regop = f where
f state interpreter =
let
state' = regop state
in
do return (state', interpreter)
------------------------------------------------------------
--------------- The operations themselves. -----------------
------------------------------------------------------------
--
-- Redefine the meaning of the symbol on the stack with
-- a mini-program also popped off the stack.
--
opSupplant state interpreter =
let
(opSym, state') = pop state
(newOpDefn, state'') = popString state'
newOp = createOp interpreter newOpDefn
in
do return (state'', supplant interpreter opSym newOp)
--
-- Execute the symbol on the stack with the current interpreter.
--
opEval state interpreter =
let
(opSym, state') = pop state
newOp = createOp interpreter [opSym]
in
newOp state' interpreter
--
-- I/O.
--
opInput state@State{ getCh=getCh } interpreter = do
symbol <- getCh
do return (push state symbol, interpreter)
opOutput state@State{ putCh=putCh } interpreter =
let
(symbol, state') = pop state
in do
putCh symbol
return (state', interpreter)
--
-- Primitive arithmetic.
--
opAdd state =
let
(symA, state') = pop state
(symB, state'') = pop state'
in
push state'' (Char.chr (((Char.ord symB) + (Char.ord symA)) `mod` 256))
opSubtract state =
let
(symA, state') = pop state
(symB, state'') = pop state'
in
push state'' (Char.chr (((Char.ord symB) - (Char.ord symA)) `mod` 256))
discreteLog 0 = 8
discreteLog 1 = 0
discreteLog 2 = 1
discreteLog n = (discreteLog (n `div` 2)) + 1
opDiscreteLog state =
let
(symbol, state') = pop state
in
push state' (Char.chr (discreteLog (Char.ord symbol)))
--
-- Stack manipulation.
--
--
-- Pop the top symbol of the stack, make a copy of it, push it back onto the
-- stack, and enqueue the copy onto the queue.
--
opEnqueueCopy state =
let
(sym, _) = pop state
in
enqueue state sym
--
-- Dequeue a symbol from the queue and push it onto the stack.
--
opDequeue state =
let
(sym, state') = dequeue state
in
push state' sym
--
-- Duplicate the top symbol of the stack.
--
opDuplicate state =
let
(symbol, _) = pop state
in
push state symbol
--
-- Miscellaneous operations.
--
opNop state =
state
--
-- Parameterizable operations.
--
opPushValue value state =
push state (Char.chr value)
opAccumValue value state =
let
(sym, state') = pop state
value' = ((Char.ord sym) * 10) + value
in
push state' (Char.chr (value' `mod` 256))
-----------------------------------------------------------------------
-- ===================== Debugging Functions ======================= --
-----------------------------------------------------------------------
type Debugger = State -> Interpreter -> IO ()
debugNop s i = do
return ()
debugPrintState s i = do
putStr ((show s) ++ "\n")
return ()
-----------------------------------------------------------------------
-- ============================ Executor =========================== --
-----------------------------------------------------------------------
execute :: [Symbol] -> State -> Interpreter -> Debugger -> IO (State, Interpreter)
execute [] state interpreter debugger =
return (state, interpreter)
execute (opSym:program') state interpreter debugger =
let
operation = fetch interpreter opSym
in do
(state', interpreter') <- operation state interpreter
debugger state' interpreter'
execute program' state' interpreter' debugger
-----------------------------------------------------------------------
-- ====================== Top-Level Function ======================= --
-----------------------------------------------------------------------
initialInterpreter = Interp
(Map.fromList
[
('.', opOutput),
(',', opInput),
('#', fitRegOp (opPushValue 0)),
('0', fitRegOp (opAccumValue 0)),
('1', fitRegOp (opAccumValue 1)),
('2', fitRegOp (opAccumValue 2)),
('3', fitRegOp (opAccumValue 3)),
('4', fitRegOp (opAccumValue 4)),
('5', fitRegOp (opAccumValue 5)),
('6', fitRegOp (opAccumValue 6)),
('7', fitRegOp (opAccumValue 7)),
('8', fitRegOp (opAccumValue 8)),
('9', fitRegOp (opAccumValue 9)),
('+', fitRegOp opAdd),
('-', fitRegOp opSubtract),
('~', fitRegOp opDiscreteLog),
('^', fitRegOp opEnqueueCopy),
('v', fitRegOp opDequeue),
(':', fitRegOp opDuplicate),
('!', opSupplant),
('?', opEval),
(';', fitRegOp (opPushValue (Char.ord ';')))
]
)
initialState = State { stack=[], queue=[], getCh=getChar, putCh=putChar }
emmental string = do
(state, interpreter) <- execute string initialState initialInterpreter debugNop
return state
emmentalWithIO getCh putCh string =
let
i = initialState
i' = i{ getCh=getCh, putCh=putCh }
in do
(state, interpreter) <- execute string i' initialInterpreter debugNop
return state
debug string = do
(state, interpreter) <- execute string initialState initialInterpreter debugPrintState
return state
-----------------------------------------------------------------------
-- ========================== Test Cases =========================== --
-----------------------------------------------------------------------
--
-- Drivers for test cases. 'demo' runs them straight, whereas 'test'
-- uses the debugger.
--
demo n = emmental (testProg n)
test n = debug (testProg n)
--
-- Here we introduce a bit of a cheat, in order to make writing
-- complex Emmental programs tolerable. You can still see the
-- programs in their full glory by executing "show (testProg n)".
--
quote [] = []
quote (symbol:rest) = "#" ++ (show (Char.ord symbol)) ++ (quote rest)
--
-- Add one and one.
--
testProg 1 = "#1#1+"
--
-- Redefine & as "+".
--
testProg 2 = ";#43#38!#1#1&" -- 59,43,38 ==> ";+&"
--
-- Redefine 0 as "9".
--
testProg 3 = ";#57#48!#0" -- 59,57,48 ==> ";90"
--
-- Redefine 0 as "#48?". This results in an infinite loop when 0 is executed.
--
testProg 4 = ";#35#52#56#63#48!0" -- 59,35,52,56,63,48 ==> ";#48?0"
--
-- Redefine $ as ".#36?". This results in a loop that pops symbols and
-- and prints them, until the stack underflows, when $ is executed.
--
testProg 5 = ";#46#35#51#54#63#36! #65#66#67#68#69$"
--
-- Duplicate the top stack element (assuming an empty queue.)
-- This shows that the : operation is not strictly necessary
-- (when you know the size of the queue.)
--
testProg 6 = "#65^v"
--
-- Discard the top stack element (assuming more than one element
-- on the stack, and an empty queue.)
--
testProg 7 = "#33#123^v-+"
--
-- Swap the top two elements of the stack (assuming an empty queue.)
--
testProg 8 = "#67#66#65^v^-+^^v^v^v-+^v-+^v-+vv"
--
-- Input a symbol. Report whether its ASCII value is even or odd.
--
testProg 9 = (quote ";^v:") ++ "!" ++ -- : = dup
(quote ";#69.") ++ "#!" ++ -- NUL = print "E"
(quote ";#79.") ++ "#128!" ++ -- \128 = print "O"
(quote (";" ++ (take 127 [':',':'..]) ++ -- m = mul by 128
(take 127 ['+','+'..]) ++ "m")) ++ "!" ++
",m?"
--
-- Input a symbol. Report whether it is M or not.
--
testProg 10 = (quote ";#78.") ++ "#!" ++ -- NUL = print "N"
";##1!" ++ -- SOH = same as NUL
";##2!" ++ -- STX = same as NUL
";##3!" ++ -- ETX = same as NUL
";##4!" ++ -- EOT = same as NUL
";##5!" ++ -- ENQ = same as NUL
";##6!" ++ -- ACK = same as NUL
";##7!" ++ -- BEL = same as NUL
(quote ";#89.") ++ "#8!" ++ -- BS = print "Y"
",#77-~?"
--
-- Same as testProg 5, except stop printing when a NUL is
-- encountered, instead of just underflowing the stack.
--
testProg 11 = ";" ++ (quote ":~?$") ++ "!" ++ -- $ = dup & test
";" ++ (quote ".$") ++ "#!" ++ -- NUL = print & repeat
";#0#1!" ++ -- SOH = same as NUL
";#0#2!" ++ -- STX = same as NUL
";#0#3!" ++ -- ETX = same as NUL
";#0#4!" ++ -- EOT = same as NUL
";#0#5!" ++ -- ENQ = same as NUL
";#0#6!" ++ -- ACK = same as NUL
";#0#7!" ++ -- BEL = same as NUL
-- BS = stop (nop)
"#0" ++ (quote (reverse "Hello!")) ++ "$"
| catseye/Emmental | src/Language/Emmental.hs | unlicense | 12,572 | 2 | 21 | 3,553 | 2,813 | 1,550 | 1,263 | 200 | 1 |
data Tree a
= Empty
| Node a (Tree a) (Tree a)
deriving (Show)
-- Example tree number 1
tree1 :: Tree Int
tree1 =
Node 1
(Node 2
(Node 3 Empty Empty)
(Node 4 Empty Empty)
)
(Node 5
(Node 6 Empty Empty)
(Node 7 Empty Empty)
)
-- Example tree number 2
tree2 :: Tree Int
tree2 =
Node 1
(Node 2
(Node 3 Empty Empty)
Empty
)
(Node 4 Empty Empty)
-- Sum of a single binary tree
treeSum :: Tree Int -> Int
treeSum Empty = 0
treeSum (Node x l r) = x + treeSum l + treeSum r
-- Sums two binary trees together
binarySum :: Tree Int -> Tree Int -> Int
binarySum a b = treeSum a + treeSum b
-- Prints a binary tree by depth
-- Example: tree1 would be 1, 2, 3, 4, 5, 6, 7
printByDepth :: Tree Int -> String
printByDepth Empty = ""
printByDepth (Node x l r) = show x ++ printByDepth l ++ printByDepth r
-- Prints a binary tree by level
-- Example: tree1 would be 1, 2, 5, 3, 4, 6, 7
printByLevel :: Tree Int -> String
printByLevel (Node x Empty Empty) = show x
printByLevel (Node x (Node y ll lr) (Node z rl rr)) =
concat $ map show [x, y, z] ++ map printByLevel [ll, lr, rl, rr]
--
-- Other problems:
--
-- Step Climbing
-- Size of the staircase (in steps) and the length of the steps you can take
staircase :: Int -> [Int] -> Int
staircase n m
| n < 0 = 0
| n == 0 = 1
| otherwise = sum $ map (\x -> staircase (n - x) m) m
-- Matrix size (x and y)
taxis :: Int -> Int -> Int
taxis x y
| x < 1 || y < 1 = 1
| otherwise = (taxis (x - 1) y) + (taxis x (y - 1))
| gnclmorais/interview-prep | recursion/04april/05treesSum.hs | unlicense | 1,554 | 0 | 12 | 438 | 608 | 310 | 298 | 41 | 1 |
t2s m s d = m * 60 + s + d / 100.0
ans (t1:t2:_)
| (t1 < (t2s 0 35 50)) && (t2 < (t2s 1 11 00)) = "AAA"
| (t1 < (t2s 0 37 50)) && (t2 < (t2s 1 17 00)) = "AA"
| (t1 < (t2s 0 40 00)) && (t2 < (t2s 1 23 00)) = "A"
| (t1 < (t2s 0 43 00)) && (t2 < (t2s 1 29 00)) = "B"
| (t1 < (t2s 0 50 00)) && (t2 < (t2s 1 45 00)) = "C"
| (t1 < (t2s 0 55 00)) && (t2 < (t2s 1 56 00)) = "D"
| (t1 < (t2s 1 10 00)) && (t2 < (t2s 2 28 00)) = "E"
| otherwise = "NA"
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Float]]
o = map ans i
mapM_ putStrLn o
| a143753/AOJ | 0123.hs | apache-2.0 | 588 | 0 | 14 | 190 | 454 | 228 | 226 | 15 | 1 |
ans (m:f:b:_) =
if m >= b
then "0"
else if (m+f) >= b
then show (b-m)
else "NA"
main = do
l <- getLine
let i = map read $ words l :: [Int]
o = ans i
putStrLn o
| a143753/AOJ | 0358.hs | apache-2.0 | 200 | 0 | 11 | 81 | 116 | 59 | 57 | 11 | 3 |
-- Copyright 2020 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Regular where
import {-# SOURCE #-} Boot
data Regular = Regular Int Boot | Nil
| google/cabal2bazel | bzl/tests/recursive/Regular.hs | apache-2.0 | 677 | 0 | 6 | 119 | 35 | 27 | 8 | 3 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Default
import Data.Int (Int64)
import Data.Text (Text)
import qualified API
import qualified Data.Text as Text
import qualified Data.Text.Lazy as ZText
import qualified Text.Markdown as Markdown
import Servant
import Servant.Docs
import Servant.JS
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Servant.Swagger
import Data.ByteString.Lazy.Char8 as ZChar8
import qualified Data.Aeson.Encode.Pretty as Aeson
import Data.Swagger -- .Internal.Schema
api :: Proxy API.API
api = Proxy
instance ToSample API.User
instance ToSample Int where
toSamples _ = singleSample 3
instance ToSample Int64 where
toSamples _ = singleSample 1478
instance ToSample Text where
toSamples _ = singleSample "foo"
instance ToSample API.Sorting
instance ToSample API.SortBy
instance ToSample API.Direction
instance ToSample API.Name
instance ToSample API.Address
instance ToParam (QueryParam "limit" Int) where
toParam _ = DocQueryParam "limit" []
"The maximum number of records to return."
Normal
instance ToParam (QueryParam "offset" Int) where
toParam _ = DocQueryParam "limit" []
"The offset of where to start returning records."
Normal
instance ToCapture (Capture "userId" Int64) where
toCapture _ = DocCapture "userId" "Id of the user record to fetch."
instance ToSchema API.User
instance ToSchema API.Name
instance ToSchema API.Sorting
instance ToSchema API.Address
instance ToSchema API.SortBy
instance ToSchema API.Direction
intros :: [ DocIntro ]
intros = [
DocIntro "The WebBench API Documentation." []
]
main :: IO ()
main = do
Prelude.writeFile "./webbench.html" $
(ZText.unpack . renderHtml . Markdown.markdown def . ZText.pack
. markdown . docsWithIntros intros . pretty) api
writeJSForAPI api vanillaJS "./webbench.vanilla.js"
writeJSForAPI api jquery "./webbench.jquery.js"
writeJSForAPI api (angular defAngularOptions)
"./webbench.angular.js"
writeJSForAPI api (angularService defAngularOptions)
"./webbench.angular-server.js"
writeJSForAPI api (axios defAxiosOptions) "./webbench.axios.js"
ZChar8.writeFile "./webbench.swagger.json" $ Aeson.encodePretty $
toSwagger api
| Sapiens-OpenSource/webbench | haskell/docs/src/Main.hs | bsd-2-clause | 2,667 | 0 | 16 | 733 | 577 | 297 | 280 | 66 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module Cauterize.JavaScript.TestClientTemplate
( testClientFromSpec
) where
import Data.String.Interpolate
import Data.Text.Lazy (unpack)
import qualified Cauterize.Specification as S
testClientFromSpec :: S.Spec -> String
testClientFromSpec spec =
let ln = unpack $ S.specName spec
in [i|
/*global Uint8Array */
'use strict';
var lib = require('./lib#{ln}.js');
var c = require('./libcaut/cauterize.js');
var cb = require('./libcaut/buffer.js');
var buf = new cb.CautBuffer();
process.stdin.on('readable', function () {
var chunk = process.stdin.read();
if (null !== chunk) {
buf.addU8Array(new Uint8Array(chunk));
}
});
process.stdin.on('end', function () {
var clib = new c.Cauterize(lib.SpecificationInfo);
var t = clib.decode(buf);
var e = clib.encode(t);
var ad = e.allData();
process.stdout.write(new Buffer(ad));
});
|]
| cauterize-tools/caut-javascript-ref | src/Cauterize/JavaScript/TestClientTemplate.hs | bsd-3-clause | 896 | 0 | 11 | 140 | 81 | 49 | 32 | 10 | 1 |
module Import
( module Import
) where
import Prelude as Import hiding (head, init, last,
readFile, tail, writeFile)
import Yesod as Import hiding (Route (..))
import Control.Applicative as Import (pure, (<$>), (<*>))
import Data.Text as Import (Text)
import Foundation as Import
import Settings as Import
import Settings.Development as Import
import Settings.StaticFiles as Import
import Data.Aeson as Import (toJSON)
#if __GLASGOW_HASKELL__ >= 704
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat),
(<>))
#else
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat))
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif
| Tener/deeplearning-thesis | yesod/abaloney/Import.hs | bsd-3-clause | 1,066 | 0 | 6 | 506 | 149 | 108 | 41 | 17 | 1 |
{-# LANGUAGE FlexibleInstances
, MultiParamTypeClasses
, TemplateHaskell
, TypeFamilies
, TypeOperators
, ViewPatterns
#-}
module Examples.ForceLayout where
import Graphics.UI.Toy.Prelude
import Prelude hiding ((.))
import Control.Category ((.))
import Data.AffineSpace.Point (Point(..))
import Data.Default
import Data.Label
import qualified Data.Map as M
import Physics.ForceLayout
import System.IO.Unsafe (unsafePerformIO)
import System.Random (newStdGen, randomRs)
data State = State (Ensemble R2) (M.Map PID (Draggable CairoDiagram)) Config
config :: State :-> Config
config = lens (\(State _ _ c) -> c) (\c (State a b _) -> State a b c)
-- TODO: add sliders to control constraints
data Config = Config
{ _dampingSlider :: CairoSlider Double
}
$(mkLabels [''Config])
type instance V State = R2
main :: IO ()
main = runToy (def :: State)
instance Default State where
def = State e hm $ Config mkDefaultSlider
where
handle = circle 5 # lc black # lw 2
hm = M.fromList $ [ (k, mkDraggable p handle)
| (k, get pos -> (P p)) <- M.toList particleMap
]
e = Ensemble [ (edges, hookeForce 0.1 40)
, (allPairs, coulombForce 1)
]
particleMap
-- EWWW!
entropy1 = unsafePerformIO $ newStdGen
entropy2 = unsafePerformIO $ newStdGen
entropy3 = unsafePerformIO $ newStdGen
entropy4 = unsafePerformIO $ newStdGen
count = 20
edges = filter (uncurry (/=))
. take (count * 2)
$ zip (randomRs (0, count) entropy1) (randomRs (0, count) entropy2)
allPairs = [(x, y) | x <- [1..count - 1], y <- [x + 1..count]]
particleMap = M.fromList . zip [1..]
. take count
. map (initParticle . p2)
$ zip (randomRs (0, 200.0) entropy3)
(randomRs (0, 200.0) entropy4)
uiOffset = 10 & 100
instance Interactive Gtk State where
mouse m i s = do
s' <- simpleMouse (\p m (State e hm c)
-> State e (M.map (mouseDrag p m) hm) c) m i s
slider <- mouse m (translate uiOffset i) $ get (dampingSlider . config) s'
return $ set (dampingSlider . config) slider s'
tick = simpleTick update
keyboard = handleKeys escapeKeyHandler
instance Diagrammable Cairo R2 State where
diagram (State e hm conf)
= (mconcat . map diagram $ M.elems hm)
<> translate uiOffset (diagram $ get dampingSlider conf)
instance GtkDisplay State where
display = displayDiagram diagram
update :: State -> State
update (State e hm conf)
= State ( modify particles (M.intersectionWith constrain hm)
$ ensembleStep (get (sliderValue . dampingSlider) conf) e )
( M.intersectionWith update hm $ get particles e )
conf
where
-- Move particle to its handle if dragged.
constrain d p
| isDragging d = set pos (P $ get dragOffset d) p
| otherwise = p
-- Move non-dragging handles to their particles.
update d (get pos -> P p)
| isDragging d = d
| otherwise = set dragOffset p d
| mgsloan/toy-gtk-diagrams | Examples/ForceLayout.hs | bsd-3-clause | 3,162 | 0 | 16 | 916 | 1,087 | 570 | 517 | 75 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Network.CommSec.KeyExchange.Socket
( Network.CommSec.KeyExchange.Socket.connect
, Network.CommSec.KeyExchange.Socket.accept
, Net.listen, Net.bind, Net.socket
, CS.send
, CS.recv
, CS.Connection
, CS.close
) where
import Control.Concurrent.MVar
import Crypto.Types.PubKey.RSA
import Data.Traversable (traverse)
import Network.CommSec
import Network.CommSec.KeyExchange.Internal as I
import qualified Network.CommSec as CS
import qualified Network.CommSec.Package as CSP
import qualified Network.Socket as Net
connect :: Net.Socket
-> Net.SockAddr
-> [PublicKey]
-> PrivateKey
-> IO (Maybe (PublicKey, Connection))
connect socket addr pubKeys privateMe = do
Net.connect socket addr
Net.setSocketOption socket Net.NoDelay 1
res <- I.keyExchangeInit socket pubKeys privateMe
traverse (wrapContexts socket addr) res
accept :: Net.Socket
-> [PublicKey]
-> PrivateKey
-> IO (Maybe (PublicKey, Connection))
accept sock pubKeys privateMe = do
(socket,sa) <- Net.accept sock
Net.setSocketOption socket Net.NoDelay 1
res <- keyExchangeResp socket pubKeys privateMe
traverse (wrapContexts socket sa) res
-- Helper function for wrapping up the results of a key exchange into a 'Connection'
wrapContexts :: Net.Socket -> Net.SockAddr -> (PublicKey, CSP.OutContext, CSP.InContext) -> IO (PublicKey, Connection)
wrapContexts socket socketAddr (t, oCtx, iCtx) = do
outCtx <- newMVar oCtx
inCtx <- newMVar iCtx
return (t, Conn {..})
| TomMD/commsec-keyexchange | Network/CommSec/KeyExchange/Socket.hs | bsd-3-clause | 1,588 | 0 | 12 | 308 | 450 | 247 | 203 | 41 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Mistral.CodeGen.LambdaLift (
lambdaLift
) where
import Mistral.Driver
import Mistral.ModuleSystem.Export ( Export(..) )
import Mistral.TypeCheck.AST
import Mistral.TypeCheck.Unify
import Mistral.Utils.Names
import Mistral.Utils.PP
import Mistral.Utils.SCC ( Group(..), groupElems, scc )
import Control.Applicative ( Applicative(..), (<$>), Alternative )
import Control.Monad ( MonadPlus )
import qualified Data.Foldable as F
import qualified Data.Map as Map
import Data.Maybe ( mapMaybe, catMaybes )
import Data.Monoid ( mappend, mconcat )
import qualified Data.Set as Set
import qualified Data.Traversable as T
import MonadLib ( runM, BaseM(..), WriterT, put, ReaderT, ask, local )
-- | Perform lambda-lifting on a module.
lambdaLift :: Module -> Driver Module
lambdaLift m = phase "ll" $
do (m',lifted) <- runLL (llModule m)
let binds = concatMap groupElems (modBinds m')
++ concatMap groupElems lifted
let ll = m' { modBinds = scc binds }
traceMsg (text "" $$ pp ll)
return ll
-- Lambda-lifting Monad --------------------------------------------------------
type Closure = Map.Map Name Type
paramClosure :: [Param] -> Closure
paramClosure ps = Map.fromList [ (n,ty) | Param n ty <- ps ]
patClosure :: Pattern -> Closure
patClosure pat = case pat of
PCon _ ps -> paramClosure (catMaybes ps)
PTuple ps -> paramClosure (catMaybes ps)
PLit _ -> Map.empty
ppClosure :: Closure -> PPDoc
ppClosure clos =
commas [ pp x <> char ':' <> pp ty | (x,ty) <- Map.toList clos ]
closTParams :: Closure -> [TParam]
closTParams clos = Set.toList (typeVars (Map.elems clos))
closParams :: Closure -> [Param]
closParams clos = [ Param n ty | (n,ty) <- Map.toList clos ]
-- | Call-site rewriting.
type Rewrite = Map.Map Name Closure
rewrite :: Name -> Closure -> Rewrite
rewrite = Map.singleton
data Env = Env { envDepth :: !Int
-- ^ Number of type parameters bound
, envClosure :: Closure
-- ^ The current largest closure
, envParams :: Closure
-- ^ Names provided as paramters
, envRewrite :: Rewrite
-- ^ Rewriting call sites
}
emptyEnv :: Env
emptyEnv = Env { envDepth = 0
, envClosure = Map.empty
, envParams = Map.empty
, envRewrite = Map.empty }
newtype LL a = LL { unLL :: ReaderT Env (WriterT [Group Decl] Driver) a
} deriving (Functor,Applicative,Monad,MonadPlus,Alternative)
runLL :: LL a -> Driver (a,[Group Decl])
runLL m = runM (unLL m) emptyEnv
instance BaseM LL Driver where
{-# INLINE inBase #-}
inBase m = LL (inBase m)
-- | Emit a group of declarations to the top level. It's assumed that these
-- have already had their closures and call-sites adjusted.
emitGroup :: Group Decl -> LL ()
emitGroup g = LL (put [fmap mkTopLevel g])
where
mkTopLevel b = b { bExport = Private }
-- | Merge some rewrites into the environment.
addRewrite :: Rewrite -> LL a -> LL a
addRewrite rw m = LL $
do env <- ask
local env { envRewrite = rw `Map.union` envRewrite env } (unLL m)
-- | Rewrite the use of a name, adding any additional closure arguments
-- required.
rewriteCall :: Name -> [Type] -> LL Expr
rewriteCall n ts = LL $
do env <- ask
case Map.lookup n (envRewrite env) of
Nothing -> return (tappE (EVar n) ts)
Just clos ->
do let tys = [ TVar (TVFree p) | p <- closTParams clos ]
cps = [ EVar (pName p) | p <- closParams clos ]
new = appC (tappE (EVar n) (ts ++ tys)) cps
traceMsg (pp (tappE (EVar n) ts) <+> text "~>" <+> pp new)
return new
-- | Given the free variables in a structure, determine which variables in the
-- current closure it will require.
getClosure :: FreeVars a => a -> LL Closure
getClosure a = LL $
do env <- ask
let fvs = freeVars a
-- variables captured in the closure
fromEnv = Map.filterWithKey (\k _ -> k `Set.member` fvs)
(envClosure env)
-- variables added by the closure of others
fromRewrites = mapMaybe step (Set.toList fvs)
where
step n = Map.lookup n (envRewrite env)
return (Map.unions (fromEnv : fromRewrites))
-- | Extend the current closure.
extendClosure :: Closure -> LL a -> LL a
extendClosure clos m = LL $
do env <- ask
local env { envClosure = clos `Map.union` envClosure env } (unLL m)
-- | Run an action with the binding environment produced by a binding.
--
-- XXX this doesn't apply the substitution to the body of the binding at all, so
-- if we ever implement scoped-type-variables, we'll have to switch to passing a
-- substituted body in the continuation as well.
withParams :: Bind a -> (Subst -> LL b) -> LL b
withParams b body = LL $
do env <- ask
let -- introduce variables for type parameters...
var i p = (p, TVar (TVFree (p { tpIndex = i })))
to = boundBinds (zipWith var [envDepth env ..] (bTParams b))
-- ... and remove them later
bind i p = (p { tpIndex = i }, TVar (TVBound p))
from = freeBinds (zipWith bind [envDepth env ..] (bTParams b))
-- instantiate the arguments
toParam p = (pName p, pType p)
params = Map.fromList (map toParam (apply to (bParams b)))
local env { envDepth = envDepth env + length (bTParams b)
, envClosure = envParams env `Map.union` envClosure env
, envParams = params
} (unLL (body from))
-- | Generate the closure for bindings that have no type or closure arguments.
groupEnv :: Group (Bind a) -> Closure
groupEnv g = case g of
NonRecursive b -> bind b
Recursive bs -> F.foldMap bind bs
where
-- only bind monomorphic value definitions
bind b | null (bTParams b) && null (bCParams b) && null (bParams b)
= Map.singleton (bName b) (bResult b)
| otherwise
= Map.empty
-- Traversal -------------------------------------------------------------------
-- | Lambda lift the expressions of a module.
--
-- XXX this doesn't currently perform lambda-lifting on the expressions that
-- form the body of a task.
llModule :: Module -> LL Module
llModule m =
do binds' <- mapM (T.traverse (llTopBind llExpr)) (modBinds m)
return m { modBinds = binds' }
-- | Top-level bindings don't get lifted.
llTopBind :: Types a => (a -> LL a) -> Bind a -> LL (Bind a)
llTopBind llBody bind = withParams bind $ \ subst ->
do body' <- llBody (bBody bind)
return bind { bBody = apply subst body' }
-- | Lambda lift declarations from within an expression.
llExpr :: Expr -> LL Expr
llExpr e = case e of
ETApp (EVar n) ts -> rewriteCall n ts
EVar n -> rewriteCall n []
EApp f x -> EApp <$> llExpr f <*> llExpr x
ELet ds b ty -> llLet ds b ty
EPrim {} -> return e
ECon {} -> return e
ECase src arms rty -> ECase src <$> llMatch arms <*> pure rty
EStmts ity ty as -> EStmts ity ty <$> T.traverse llAction as
ELit {} -> return e
ETApp f ty -> ETApp <$> llExpr f <*> pure ty
ECApp f cs -> ECApp <$> llExpr f <*> T.traverse llExpr cs
EMkList ty es -> EMkList ty <$> T.traverse llExpr es
EMkTuple elems -> let (tys,es) = unzip elems
in EMkTuple . zip tys <$> T.traverse llExpr es
ETopo {} -> return e
ETaskSet {} -> return e
ESchedule {} -> return e
llLet :: [Group Decl] -> Expr -> Type -> LL Expr
llLet decls body ty = llDecls decls $ \ decls' ->
do body' <- llExpr body
return (letE decls' body' ty)
-- | Lambda lift a match, extending the closure with anything introduced.
llMatch :: Match Pattern -> LL (Match Pattern)
llMatch m = case m of
MCase s sty m' -> MCase <$> llExpr s <*> pure sty <*> llMatch m'
MRename n e ty m' -> extendClosure (Map.singleton n ty) $
MRename n <$> llExpr e <*> pure ty <*> llMatch m'
MGuard g m' -> MGuard <$> llExpr g <*> llMatch m'
MPat pat m' -> extendClosure (patClosure pat) (MPat pat <$> llMatch m')
MSplit l r -> MSplit <$> llMatch l <*> llMatch r
MFail -> pure m
MExpr e -> MExpr <$> llExpr e
llAction :: Action -> LL Action
llAction a = case a of
ABind mb e ty -> ABind mb <$> llExpr e <*> pure ty
AReceive r fs to w -> AReceive r <$> T.traverse llFrom fs
<*> T.traverse llTimeout to
<*> T.traverse llExpr w
llFrom :: From -> LL From
llFrom (From src msg msgTy body) = From src msg msgTy <$> llMatch body
llTimeout :: Timeout -> LL Timeout
llTimeout (Timeout to body) = Timeout to <$> llExpr body
-- Lambda Lifting --------------------------------------------------------------
-- | Calculate the closure that a binding requires.
bindClosure :: Decl -> LL Closure
bindClosure bind = withParams bind $ \ _ ->
do clos <- getClosure (bBody bind)
traceMsg $ hang (text "closure for" <+> pp (bName bind) <> char ':')
2 (ppClosure clos)
return clos
-- | Generate the rewriting for a binding, given its closure.
bindRewrite :: Decl -> Closure -> Rewrite
bindRewrite b = rewrite (bName b)
-- | Lambda-lift a group of declarations, then run a continuation in their
-- modified environment, passing in the declarations that weren't lifted.
llDecls :: [Group Decl] -> ([Group Decl] -> LL a) -> LL a
llDecls gs k = go [] gs
where
go acc groups = case groups of
g:rest -> do e <- llGroup g
case e of
Right g' -> extendClosure (groupEnv g') (go (g' : acc) rest)
Left rw -> addRewrite rw (go acc rest)
[] -> k (reverse acc)
-- | Lambda-lift a group of declarations. This generates a rewrite when the
-- declarations have been lifted, or a new group when they are kept.
llGroup :: Group Decl -> LL (Either Rewrite (Group Decl))
llGroup g = case g of
NonRecursive d ->
do (mb,[d']) <- llBinds False [d]
let g' = NonRecursive d'
case mb of
Nothing -> return (Right g')
Just rw -> do emitGroup g'
return (Left rw)
Recursive ds ->
do (mb,ds') <- llBinds True ds
let g' = Recursive ds'
case mb of
Nothing -> return (Right g')
Just rw -> do emitGroup g'
return (Left rw)
-- | Lambda-lift a group of declarations at one time.
--
-- XXX this currently treats all bindings as functions, so things like
--
-- let x = y + 1
-- in ...
--
-- will be lifted out to the top-level as functions of their closures.
llBinds :: Bool -> [Decl] -> LL (Maybe Rewrite,[Decl])
llBinds isRec ds =
do clos <- mconcat `fmap` mapM bindClosure ds
traceMsg $ hang (text "group closure:")
2 (ppClosure clos)
-- expressions need lifting when they are part of a recursive block, or
-- contain parameters
let needsLifting = isRec || any (not . null . bParams) ds
-- expressions need rewriting when they're going to be lifted, and have
-- a non-empty closure
needsRewriting = needsLifting && not (Map.null clos)
traceMsg (text "needs lifting:" <+> text (show needsLifting))
-- generate the local rewrite
let rw | needsRewriting = F.foldMap (`bindRewrite` clos) ds
| otherwise = Map.empty
process b = withParams b $ \ from ->
do body' <- addRewrite rw (llExpr (bBody b))
-- substitute away all free type vars
let tps = closTParams clos
next = [ length (bTParams b) .. ]
bind p i = (p, p { tpIndex = i })
binds = zipWith bind tps next
bvs = map snd binds
subst = freeBinds [ (p, TVar (TVBound g)) | (p,g) <- binds]
`mappend` from
if needsRewriting
then return b { bTParams = bTParams b ++ bvs
, bCParams = apply subst (closParams clos)
, bBody = apply subst body' }
else return b { bBody = body' }
ds' <- mapM process ds
if needsLifting
then return (Just rw, ds')
else return (Nothing, ds')
| GaloisInc/mistral | src/Mistral/CodeGen/LambdaLift.hs | bsd-3-clause | 12,480 | 0 | 23 | 3,637 | 3,958 | 1,988 | 1,970 | 228 | 16 |
module Options.Warnings where
import Types
warningsOptions :: [Flag]
warningsOptions =
[ flag { flagName = "-W"
, flagDescription = "enable normal warnings"
, flagType = DynamicFlag
, flagReverse = "-w"
}
, flag { flagName = "-w"
, flagDescription = "disable all warnings"
, flagType = DynamicFlag
}
, flag { flagName = "-Wall"
, flagDescription =
"enable almost all warnings (details in :ref:`options-sanity`)"
, flagType = DynamicFlag
, flagReverse = "-w"
}
, flag { flagName = "-Wcompat"
, flagDescription =
"enable future compatibility warnings " ++
"(details in :ref:`options-sanity`)"
, flagType = DynamicFlag
, flagReverse = "-Wno-compat"
}
, flag { flagName = "-Werror"
, flagDescription = "make warnings fatal"
, flagType = DynamicFlag
, flagReverse = "-Wwarn"
}
, flag { flagName = "-Wwarn"
, flagDescription = "make warnings non-fatal"
, flagType = DynamicFlag
, flagReverse = "-Werror"
}
, flag { flagName = "-fdefer-type-errors"
, flagDescription =
"Turn type errors into warnings, :ref:`deferring the error until "++
"runtime <defer-type-errors>`. Implies ``-fdefer-typed-holes``. "++
"See also ``-Wdeferred-type-errors``"
, flagType = DynamicFlag
, flagReverse = "-fno-defer-type-errors"
}
, flag { flagName = "-fdefer-typed-holes"
, flagDescription =
"Convert :ref:`typed hole <typed-holes>` errors into warnings, "++
":ref:`deferring the error until runtime <defer-type-errors>`. "++
"Implied by ``-fdefer-type-errors``. "++
"See also ``-Wtyped-holes``."
, flagType = DynamicFlag
, flagReverse = "-fno-defer-typed-holes"
}
, flag { flagName = "-fhelpful-errors"
, flagDescription = "Make suggestions for mis-spelled names."
, flagType = DynamicFlag
, flagReverse = "-fno-helpful-errors"
}
, flag { flagName = "-Wdeprecated-flags"
, flagDescription =
"warn about uses of commandline flags that are deprecated"
, flagType = DynamicFlag
, flagReverse = "-Wno-deprecated-flags"
}
, flag { flagName = "-Wduplicate-constraints"
, flagDescription =
"warn when a constraint appears duplicated in a type signature"
, flagType = DynamicFlag
, flagReverse = "-Wno-duplicate-constraints"
}
, flag { flagName = "-Wduplicate-exports"
, flagDescription = "warn when an entity is exported multiple times"
, flagType = DynamicFlag
, flagReverse = "-Wno-duplicate-exports"
}
, flag { flagName = "-Whi-shadowing"
, flagDescription =
"warn when a ``.hi`` file in the current directory shadows a library"
, flagType = DynamicFlag
, flagReverse = "-Wno-hi-shadowing"
}
, flag { flagName = "-Widentities"
, flagDescription =
"warn about uses of Prelude numeric conversions that are probably "++
"the identity (and hence could be omitted)"
, flagType = DynamicFlag
, flagReverse = "-Wno-identities"
}
, flag { flagName = "-Wimplicit-prelude"
, flagDescription = "warn when the Prelude is implicitly imported"
, flagType = DynamicFlag
, flagReverse = "-Wno-implicit-prelude"
}
, flag { flagName = "-Wincomplete-patterns"
, flagDescription = "warn when a pattern match could fail"
, flagType = DynamicFlag
, flagReverse = "-Wno-incomplete-patterns"
}
, flag { flagName = "-Wincomplete-uni-patterns"
, flagDescription =
"warn when a pattern match in a lambda expression or "++
"pattern binding could fail"
, flagType = DynamicFlag
, flagReverse = "-Wno-incomplete-uni-patterns"
}
, flag { flagName = "-Wincomplete-record-updates"
, flagDescription = "warn when a record update could fail"
, flagType = DynamicFlag
, flagReverse = "-Wno-incomplete-record-updates"
}
, flag { flagName = "-Wlazy-unlifted-bindings"
, flagDescription =
"*(deprecated)* warn when a pattern binding looks lazy but "++
"must be strict"
, flagType = DynamicFlag
, flagReverse = "-Wno-lazy-unlifted-bindings"
}
, flag { flagName = "-Wmissing-fields"
, flagDescription = "warn when fields of a record are uninitialised"
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-fields"
}
, flag { flagName = "-Wmissing-import-lists"
, flagDescription =
"warn when an import declaration does not explicitly list all the"++
"names brought into scope"
, flagType = DynamicFlag
, flagReverse = "-fnowarn-missing-import-lists"
}
, flag { flagName = "-Wmissing-methods"
, flagDescription = "warn when class methods are undefined"
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-methods"
}
, flag { flagName = "-Wmissing-signatures"
, flagDescription = "warn about top-level functions without signatures"
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-signatures"
}
, flag { flagName = "-Wmissing-exported-sigs"
, flagDescription =
"warn about top-level functions without signatures, only if they "++
"are exported. takes precedence over -Wmissing-signatures"
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-exported-sigs"
}
, flag { flagName = "-Wmissing-local-sigs"
, flagDescription =
"warn about polymorphic local bindings without signatures"
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-local-sigs"
}
, flag { flagName = "-Wmissing-monadfail-instance"
, flagDescription =
"warn when a failable pattern is used in a do-block that does " ++
"not have a ``MonadFail`` instance."
, flagType = DynamicFlag
, flagReverse = "-Wno-missing-monadfail-instance"
}
, flag { flagName = "-Wsemigroup"
, flagDescription =
"warn when a ``Monoid`` is not ``Semigroup``, and on non-" ++
"``Semigroup`` definitions of ``(<>)``?"
, flagType = DynamicFlag
, flagReverse = "-Wno-semigroup"
}
, flag { flagName = "-Wmissed-specialisations"
, flagDescription =
"warn when specialisation of an imported, overloaded function fails."
, flagType = DynamicFlag
, flagReverse = "-Wno-missed-specialisations"
}
, flag { flagName = "-Wall-missed-specialisations"
, flagDescription =
"warn when specialisation of any overloaded function fails."
, flagType = DynamicFlag
, flagReverse = "-Wno-all-missed-specialisations"
}
, flag { flagName = "-Wmonomorphism-restriction"
, flagDescription = "warn when the Monomorphism Restriction is applied"
, flagType = DynamicFlag
, flagReverse = "-Wno-monomorphism-restriction"
}
, flag { flagName = "-Wname-shadowing"
, flagDescription = "warn when names are shadowed"
, flagType = DynamicFlag
, flagReverse = "-Wno-name-shadowing"
}
, flag { flagName = "-Wnoncanonical-monad-instance"
, flagDescription =
"warn when ``Applicative`` or ``Monad`` instances have "++
"noncanonical definitions of ``return``, ``pure``, ``(>>)``, "++
"or ``(*>)``. "++
"See flag description in :ref:`options-sanity` for more details."
, flagType = DynamicFlag
, flagReverse = "-Wno-noncanonical-monad-instance"
}
, flag { flagName = "-Wnoncanonical-monoid-instance"
, flagDescription =
"warn when ``Semigroup`` or ``Monoid`` instances have "++
"noncanonical definitions of ``(<>)`` or ``mappend``. "++
"See flag description in :ref:`options-sanity` for more details."
, flagType = DynamicFlag
, flagReverse = "-Wno-noncanonical-monoid-instance"
}
, flag { flagName = "-Worphans"
, flagDescription =
"warn when the module contains :ref:`orphan instance declarations "++
"or rewrite rules <orphan-modules>`"
, flagType = DynamicFlag
, flagReverse = "-Wno-orphans"
}
, flag { flagName = "-Woverlapping-patterns"
, flagDescription = "warn about overlapping patterns"
, flagType = DynamicFlag
, flagReverse = "-Wno-overlapping-patterns"
}
, flag { flagName = "-Wtabs"
, flagDescription = "warn if there are tabs in the source file"
, flagType = DynamicFlag
, flagReverse = "-Wno-tabs"
}
, flag { flagName = "-Wtoo-many-guards"
, flagDescription = "warn when a match has too many guards"
, flagType = DynamicFlag
, flagReverse = "-Wno-too-many-guards"
}
, flag { flagName = "-Wtype-defaults"
, flagDescription = "warn when defaulting happens"
, flagType = DynamicFlag
, flagReverse = "-Wno-type-defaults"
}
, flag { flagName = "-Wunrecognised-pragmas"
, flagDescription =
"warn about uses of pragmas that GHC doesn't recognise"
, flagType = DynamicFlag
, flagReverse = "-Wno-unrecognised-pragmas"
}
, flag { flagName = "-Wunticked-promoted-constructors"
, flagDescription = "warn if promoted constructors are not ticked"
, flagType = DynamicFlag
, flagReverse = "-Wno-unticked-promoted-constructors"
}
, flag { flagName = "-Wunused-binds"
, flagDescription =
"warn about bindings that are unused. Alias for "++
"``-Wunused-top-binds``, ``-Wunused-local-binds`` and "++
"``-Wunused-pattern-binds``"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-binds"
}
, flag { flagName = "-Wunused-top-binds"
, flagDescription = "warn about top-level bindings that are unused"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-top-binds"
}
, flag { flagName = "-Wunused-local-binds"
, flagDescription = "warn about local bindings that are unused"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-local-binds"
}
, flag { flagName = "-Wunused-pattern-binds"
, flagDescription = "warn about pattern match bindings that are unused"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-pattern-binds"
}
, flag { flagName = "-Wunused-imports"
, flagDescription = "warn about unnecessary imports"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-imports"
}
, flag { flagName = "-Wunused-matches"
, flagDescription = "warn about variables in patterns that aren't used"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-matches"
}
, flag { flagName = "-Wunused-do-bind"
, flagDescription =
"warn about do bindings that appear to throw away values of types "++
"other than ``()``"
, flagType = DynamicFlag
, flagReverse = "-Wno-unused-do-bind"
}
, flag { flagName = "-Wwrong-do-bind"
, flagDescription =
"warn about do bindings that appear to throw away monadic values "++
"that you should have bound instead"
, flagType = DynamicFlag
, flagReverse = "-Wno-wrong-do-bind"
}
, flag { flagName = "-Wunsafe"
, flagDescription =
"warn if the module being compiled is regarded to be unsafe. "++
"Should be used to check the safety status of modules when using "++
"safe inference. Works on all module types, even those using "++
"explicit :ref:`Safe Haskell <safe-haskell>` modes (such as "++
"``-XTrustworthy``) and so can be used to have the compiler check "++
"any assumptions made."
, flagType = DynamicFlag
, flagReverse = "-Wno-unsafe"
}
, flag { flagName = "-Wsafe"
, flagDescription =
"warn if the module being compiled is regarded to be safe. Should "++
"be used to check the safety status of modules when using safe "++
"inference. Works on all module types, even those using explicit "++
":ref:`Safe Haskell <safe-haskell>` modes (such as "++
"``-XTrustworthy``) and so can be used to have the compiler check "++
"any assumptions made."
, flagType = DynamicFlag
, flagReverse = "-Wno-safe"
}
, flag { flagName = "-Wtrustworthy-safe"
, flagDescription =
"warn if the module being compiled is marked as ``-XTrustworthy`` "++
"but it could instead be marked as ``-XSafe``, a more informative "++
"bound. Can be used to detect once a Safe Haskell bound can be "++
"improved as dependencies are updated."
, flagType = DynamicFlag
, flagReverse = "-Wno-safe"
}
, flag { flagName = "-Wwarnings-deprecations"
, flagDescription =
"warn about uses of functions & types that have warnings or "++
"deprecated pragmas"
, flagType = DynamicFlag
, flagReverse = "-Wno-warnings-deprecations"
}
, flag { flagName = "-Wamp"
, flagDescription =
"*(deprecated)* warn on definitions conflicting with the "++
"Applicative-Monad Proposal (AMP)"
, flagType = DynamicFlag
, flagReverse = "-Wno-amp"
}
, flag { flagName = "-Wdeferred-type-errors"
, flagDescription =
"Report warnings when :ref:`deferred type errors "++
"<defer-type-errors>` are enabled. This option is enabled by "++
"default. See ``-fdefer-type-errors``."
, flagType = DynamicFlag
, flagReverse = "-Wno-deferred-type-errors"
}
, flag { flagName = "-Wtyped-holes"
, flagDescription =
"Report warnings when :ref:`typed hole <typed-holes>` errors are "++
":ref:`deferred until runtime <defer-type-errors>`. See "++
"``-fdefer-typed-holes``."
, flagType = DynamicFlag
, flagReverse = "-Wno-typed-holes"
}
, flag { flagName = "-Wpartial-type-signatures"
, flagDescription =
"warn about holes in partial type signatures when "++
"``-XPartialTypeSignatures`` is enabled. Not applicable when "++
"``-XPartialTypesignatures`` is not enabled, in which case errors "++
"are generated for such holes. See :ref:`partial-type-signatures`."
, flagType = DynamicFlag
, flagReverse = "-Wno-partial-type-signatures"
}
, flag { flagName = "-Wderiving-typeable"
, flagDescription =
"warn when encountering a request to derive an instance of class "++
"``Typeable``. As of GHC 7.10, such declarations are unnecessary "++
"and are ignored by the compiler because GHC has a custom solver "++
"for discharging this type of constraint."
, flagType = DynamicFlag
, flagReverse = "-Wno-deriving-typeable"
}
, flag { flagName = "-ffull-guard-reasoning"
, flagDescription =
"enable the full reasoning of the pattern match checker "++
"concerning guards, for more precise exhaustiveness/coverage "++
"warnings"
, flagType = DynamicFlag
, flagReverse = "-fno-full-guard-reasoning"
}
]
| gridaphobe/ghc | utils/mkUserGuidePart/Options/Warnings.hs | bsd-3-clause | 16,097 | 0 | 12 | 4,970 | 1,898 | 1,212 | 686 | 319 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Module : Game.GoreAndAsh.GLFW.Module
Description : Monad transformer of the module
Copyright : (c) Anton Gushcha, 2015-2016
License : BSD3
Maintainer : ncrashed@gmail.com
Stability : experimental
Portability : POSIX
The module contains declaration of monad transformer of the core module and
instance for 'GameModule' class.
-}
module Game.GoreAndAsh.GLFW.Module(
GLFWT(..)
) where
import Control.Monad.Catch
import Control.Monad.Extra
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.State.Strict
import Data.IORef
import Data.Proxy
import Graphics.UI.GLFW
import qualified Data.HashMap.Strict as M
import Game.GoreAndAsh
import Game.GoreAndAsh.GLFW.State
-- | Monad transformer that handles GLFW specific API
--
-- [@s@] - State of next core module in modules chain;
--
-- [@m@] - Next monad in modules monad stack;
--
-- [@a@] - Type of result value;
--
-- How to embed module:
--
-- @
-- type AppStack = ModuleStack [GLFWT, ... other modules ... ] IO
--
-- newtype AppMonad a = AppMonad (AppStack a)
-- deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadThrow, MonadCatch, MonadSDL)
-- @
--
-- The module is NOT pure within first phase (see 'ModuleStack' docs), therefore currently only 'IO' end monad can handler the module.
newtype GLFWT s m a = GLFWT { runGLFWT :: StateT (GLFWState s) m a }
deriving (Functor, Applicative, Monad, MonadState (GLFWState s), MonadFix, MonadThrow, MonadCatch, MonadMask)
instance GameModule m s => GameModule (GLFWT s m) (GLFWState s) where
type ModuleState (GLFWT s m) = GLFWState s
runModule (GLFWT m) s_ = do
liftIO $ pollEvents
close <- readCloseEvent s_
let s = s_ { glfwClose = close }
((a, s'@GLFWState{..}), nextState) <- runModule (runStateT m s) (glfwNextState s)
bindWindow glfwPrevWindow glfwWindow glfwKeyChannel glfwMouseButtonChannel
glfwMousePosChannel glfwWindowSizeChannel glfwScrollChannel glfwCloseChannel
keys <- readAllKeys s'
buttons <- readAllButtons s'
mpos <- readMousePos s'
wsize <- readWindowSize s'
scroll <- readMouseScroll s'
return (a, s' {
glfwKeys = keys
, glfwMouseButtons = buttons
, glfwMousePos = mpos
, glfwNextState = nextState
, glfwWindowSize = wsize
, glfwScroll = scroll
, glfwClose = False
})
where
readAllKeys GLFWState{..} = liftIO $ do
keys <- readAllChan glfwBufferSize glfwKeyChannel
return $ M.fromList $ (\(k, ks, mds) -> (k, (ks, mds))) <$> reverse keys
readAllButtons GLFWState{..} = liftIO $ do
btns <- readAllChan glfwBufferSize glfwMouseButtonChannel
return $ M.fromList $ (\(b, bs, mds) -> (b, (bs, mds))) <$> reverse btns
readMousePos GLFWState{..} = liftIO $
readIORef glfwMousePosChannel
readWindowSize GLFWState{..} = liftIO $
readIORef glfwWindowSizeChannel
readMouseScroll GLFWState{..} = liftIO $
readAllChan glfwBufferSize glfwScrollChannel
readCloseEvent GLFWState{..} = liftIO $
readIORef glfwCloseChannel
newModuleState = do
s <- newModuleState
kc <- liftIO $ newIORef []
mbc <- liftIO $ newIORef []
mpc <- liftIO $ newIORef (0, 0)
wsc <- liftIO $ newIORef Nothing
sch <- liftIO $ newIORef []
cch <- liftIO $ newIORef False
return $ GLFWState {
glfwNextState = s
, glfwKeyChannel = kc
, glfwKeys = M.empty
, glfwMouseButtonChannel = mbc
, glfwMouseButtons = M.empty
, glfwMousePos = (0, 0)
, glfwMousePosChannel = mpc
, glfwWindow = Nothing
, glfwPrevWindow = Nothing
, glfwWindowSize = Nothing
, glfwWindowSizeChannel = wsc
, glfwScroll = []
, glfwScrollChannel = sch
, glfwClose = False
, glfwCloseChannel = cch
, glfwBufferSize = 100
}
withModule _ = withModule (Proxy :: Proxy m)
cleanupModule _ = return ()
instance MonadTrans (GLFWT s) where
lift = GLFWT . lift
instance MonadIO m => MonadIO (GLFWT s m) where
liftIO = GLFWT . liftIO
-- | Updates handlers when current window changes
bindWindow :: MonadIO m => Maybe Window -> Maybe Window
-> KeyChannel -> ButtonChannel -> MouseChannel -> WindowSizeChannel
-> ScrollChannel -> CloseChannel -> m ()
bindWindow prev cur kch mbch mpch wsch sch cch = unless (prev == cur) $ liftIO $ do
whenJust prev $ \w -> do
setKeyCallback w Nothing
setMouseButtonCallback w Nothing
setCursorPosCallback w Nothing
setWindowSizeCallback w Nothing >> atomicWriteIORef wsch Nothing
setScrollCallback w Nothing
setWindowCloseCallback w Nothing
whenJust cur $ \w -> do
bindKeyListener kch w
bindMouseButtonListener mbch w
bindMousePosListener mpch w
bindWindowSizeListener wsch w
-- update window size
(!sx, !sy) <- getWindowSize w
atomicWriteIORef wsch $! Just (fromIntegral sx, fromIntegral sy)
bindScrollListener sch w
bindCloseCallback cch w
atomicAppendIORef :: IORef [a] -> a -> IO ()
atomicAppendIORef ref a = atomicModifyIORef ref $ \as -> (a : as, ())
-- | Bind callback that passes keyboard info to channel
bindKeyListener :: KeyChannel -> Window -> IO ()
bindKeyListener kch w = setKeyCallback w (Just f)
where
f :: Window -> Key -> Int -> KeyState -> ModifierKeys -> IO ()
f _ k _ ks mds = atomicAppendIORef kch (k, ks, mds)
-- | Bind callback that passes mouse button info to channel
bindMouseButtonListener :: ButtonChannel -> Window -> IO ()
bindMouseButtonListener mbch w = setMouseButtonCallback w (Just f)
where
f :: Window -> MouseButton -> MouseButtonState -> ModifierKeys -> IO ()
f _ b bs mds = atomicAppendIORef mbch (b, bs, mds)
-- | Bind callback that passes mouse position info to channel
bindMousePosListener :: MouseChannel -> Window -> IO ()
bindMousePosListener mpch w = setCursorPosCallback w (Just f)
where
f :: Window -> Double -> Double -> IO ()
f w' x y = do
(sx, sy) <- getWindowSize w'
let x' = 2 * (x / fromIntegral sx - 0.5)
y' = 2 * (0.5 - y / fromIntegral sy)
atomicWriteIORef mpch $! x' `seq` y' `seq` (x', y')
-- | Bind callback that passes window size info to channel
bindWindowSizeListener :: WindowSizeChannel -> Window -> IO ()
bindWindowSizeListener wsch w = setWindowSizeCallback w (Just f)
where
f :: Window -> Int -> Int -> IO ()
f _ sx sy = do
let sx' = fromIntegral sx
sy' = fromIntegral sy
atomicWriteIORef wsch . Just $! sx' `seq` sy' `seq` (sx', sy')
-- | Bind callback that passes scoll info to channel
bindScrollListener :: ScrollChannel -> Window -> IO ()
bindScrollListener sch w = setScrollCallback w (Just f)
where
f :: Window -> Double -> Double -> IO ()
f _ !sx !sy = atomicAppendIORef sch $! (sx, sy)
-- | Bind callback that passes close event to channel
bindCloseCallback :: CloseChannel -> Window -> IO ()
bindCloseCallback cch w = setWindowCloseCallback w (Just f)
where
f :: Window -> IO ()
f _ = atomicWriteIORef cch True
-- | Helper function to read all elements from channel
readAllChan :: Int -> IORef [a] -> IO [a]
readAllChan mi chan = do
xs <- readIORef chan
atomicWriteIORef chan []
return $ take mi xs | Teaspot-Studio/gore-and-ash-glfw | src/Game/GoreAndAsh/GLFW/Module.hs | bsd-3-clause | 7,332 | 0 | 16 | 1,693 | 2,070 | 1,067 | 1,003 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Data.API.Tutorial (
-- * Introduction
-- $introduction
-- * The api DSL
-- $api
-- ** Generating types for an API
-- $generate
-- * Generating tools for an API
-- $tools
-- * Data migration
-- $migration
-- ** Custom migrations
-- $custom
-- * Documenting a REST-like API
-- $docs
) where
import Data.API.Changes
import Data.API.Doc.Call
import Data.API.Doc.Dir
import Data.API.Doc.Types
import Data.API.JSON
import Data.API.Parse
import Data.API.Tools
import Data.API.Types
import Data.Text
import Data.Time
{- $introduction
The @api-tools@ library provides a compact DSL for describing an API.
It uses Template Haskell to generate the corresponding data types and
assorted tools for working with it, including code for converting
between JSON and the generated types and writing unit tests. It
supports maintaining a log of changes to the API and migrating data
between different versions.
-}
{- $api
An 'API' is a list of datatypes, which must be in one of five
simple forms:
* Records, which have one constructor but many fields
* Unions, which have many constructors each with a single argument
* Enumerations, which have many nullary constructors
* Newtypes, which wrap a built-in basic type
* Type synonyms
To define an 'API', you can use the 'parseAPI' function or the 'api'
quasi-quoter, like this:
> example :: API
> example = [api|
>
> rec :: MyRecord
> // A record type containing two fields
> = record
> x :: [integer] // one field
> y :: ? [utc] // another field
>
> chc :: MyChoice
> // A disjoint union
> = union
> | a :: MyRecord
> | b :: string
>
> enm :: MyEnum
> // An enumeration
> = enum
> | e1
> | e2
>
> str :: MyString
> // A newtype
> = basic string
>
> flg :: MyFlag
> // A type synonym
> = boolean
>
> |]
The basic types available (and their Haskell representations) are
@string@ ('Text'), @binary@ ('Binary'), @integer@ ('Int'), @boolean@
('Bool') and @utc@ ('UTCTime').
The prefix (given before the @::@ on each type declaration) is used to
name record fields and enumeration/union constructors in the generated
Haskell code. It must be unique throughout the API. It is not a type
signature, despite the appearance!
-}
{- $generate
Once an API is defined, the 'generate' function can be used in a
Template Haskell splice to produce the corresponding Haskell datatype
declarations. Thus @$(generate example)@ will produce something like:
> data MyRecord = MyRecord { rec_x :: [Int]
> , rec_y :: Maybe [UTCTime]
> }
>
> data MyChoice = CHC_a MyRecord | CHC_b String
>
> data MyEnum = ENM_e1 | ENM_e2
>
> newtype MyString = MyString { _MyString :: String }
>
> type MyFlag = Bool
The Template Haskell staging restriction means that @example@ must be
defined in one module and imported into another to call @generate@.
-}
{- $tools
Once the Haskell datatypes have been created by 'generate', additional
tools can be created with 'generateAPITools'. See "Data.API.Tools"
for a list of tools supplied with the library. For example, the call
> $(generateAPITools [enumTool, jsonTool, quickCheckTool] example)
will define:
* @_text_MyEnum :: MyEnum -> 'Text'@ and @_map_MyEnum :: Map 'Text' MyEnum@,
for converting between enumerations and text representations
* 'ToJSON', 'FromJSONWithErrs' and 'Arbitrary' instances for all the
generated types
-}
{- $migration
A key feature of @api-tools@ is support for migrating data between
different versions of an 'API'. The 'apiWithChangelog' quasi-quoter
allows an API to be followed by a changelog in a formal syntax,
providing a record of changes between versions. For example:
> example :: API
> exampleChangelog :: APIChangelog
> (example, exampleChangelog) = [apiWithChangelog|
>
> // ...api specification as before...
>
> changes
>
> version "0.3"
> added MyFlag boolean
>
> version "0.2"
> changed record MyRecord
> field added y :: ? [utc]
>
> // Initial version
> version "0.1"
> |]
The 'migrateDataDump' function can be used to migrate data, encoded
with JSON, from a previous API version to a more recent version. The
old and new 'API's must be supplied, and the changes in the changelog
must describe how to get from the old to the new 'API'. The
'validateChanges' function can be used to check that a changelog is
sufficient.
A changelog consists of the keyword @changes@ and a list of version
blocks. A version block consists of the keyword @version@ starting in
the leftmost column, a version number in double quotes, then a list of
changes. The following changes are available:
> added <Type name> <Specification>
> removed <Type name>
> renamed <Source type> to <Target type>
> changed record <Type name>
> field added <field name> :: <Type> [default <value>]
> field removed <field name>
> field renamed <source field> to <target field>
> field changed <field name> :: <New type> migration <Migration name>
> changed union <Type name>
> alternative added <alternative name> :: <Type>
> alternative removed <alternative name>
> alternative renamed <source alternative> to <target alternative>
> changed enum <Type name>
> alternative added <value name>
> alternative removed <value name>
> alternative renamed <source value> to <target value>
> migration <Migration name>
> migration record <Type name> <Migration name>
-}
{- $custom
For more extensive changes to the 'API' that cannot be expressed using
the primitive changes, /custom/ migrations can be used to migrate data
between versions.
Custom migrations can be applied to the whole dataset, a single record
or an individual record field, thus:
> version "0.42"
> migration MigrateWholeDataset
> migration record Widget MigrateWidgetRecord
> changed record Widget where
> field changed foo :: String migration MigrateFooField
The 'generateMigrationKinds' function creates enumeration types
corresponding to the custom migration names used in a changelog.
These types should then be used to create a 'CustomMigrations' record,
which describes how to transform the data (and 'API', if appropriate)
for each custom migration. For example,
> $(generateMigrationKinds myChangelog "DatabaseMigration" "RecordMigration" "FieldMigration")
with the changelog fragment above would give
> data DatabaseMigration = MigrateWholeDatabase | ...
> data RecordMigration = MigrateWidgetRecord | ...
> data FieldMigration = MigrateFooField | ...
Calls to 'migrateDataDump' should include a suitable
'CustomMigrations' record, which includes functions to perform the
migrations on the underlying data, represented as an Aeson 'Value'.
For example, suppose the @foo@ field of the @Widget@ record previously
contained a boolean: a suitable 'fieldMigration' implementation might be:
> fieldMigration :: FieldMigration -> Value -> Either ValueError Value
> fieldMigration MigrateFooField (Bool b) = Right $ toJSON $ show b
> fieldMigration MigrateFooField v = Left $ CustomMigrationError "oops" v
> ...
A field migration may change the type of the field by listing the new
type in the changelog. Whole-database and individual-record
migrations may describe the changes they make to the schema in the
'databaseMigrationSchema' and 'recordMigrationSchema' fields of the
'CustomMigrations' record.
In order to check that custom migrations result in data that matches
the schema, the 'DataChecks' parameter of 'migrateDataDump' can be set
to 'CheckCustom' or 'CheckAll'. This will validate the data against
the schema after calling the custom migration code.
-}
{- $docs
A 'Call' is a description of a web resource, intended to be generated
in an application-specific way from the code of a web server. The
'callHtml' function can be used to generate HTML documentation of
individual resources, and 'dirHtml' can be used to generate an index
page for the documentation of a collection of resources.
-}
| adinapoli/api-tools | src/Data/API/Tutorial.hs | bsd-3-clause | 8,102 | 0 | 4 | 1,579 | 93 | 70 | 23 | 12 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Schedooler.Internal where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.PSQueue
import Data.Time
data Task = Task { name :: String
, action :: IO ()
, frequency :: String }
instance Eq Task where
(Task n1 _ f1) == (Task n2 _ f2) = n1 == n2 && f1 == f2
_ == _ = False
instance Ord Task where
(Task _ _ f1) `compare` (Task _ _ f2) = LT
instance Show Task where
show (Task n _ f) = "Task " ++ n ++ " " ++ show f
-- Task should be the key, not the priority, duh
type Q = PSQ Task String
data Schedule = Schedule { threadId :: TVar (Maybe ThreadId)
, queue :: TVar Q
}
addTask :: Task -> Schedule -> STM Schedule
addTask task schedule = do
modifyTVar (queue schedule) (insert task (frequency task))
return schedule
newQ :: IO Schedule
newQ = do
q <- newTVarIO Data.PSQueue.empty
tid <- newTVarIO Nothing
return $ Schedule tid q
start :: Schedule -> IO ()
start (Schedule t q) = do
mtid <- readTVarIO t
case mtid of
Just _ -> putStrLn "Already running"
Nothing -> do
tid <- forkIO (loop q)
atomically $ writeTVar t (Just tid)
stop :: Schedule -> IO ()
stop (Schedule t _) = do
mtid <- readTVarIO t
case mtid of
Just tid -> do
killThread tid
atomically $ writeTVar t Nothing
Nothing -> putStrLn "Not running"
simpleAdd :: IO () -> Schedule -> IO ()
simpleAdd a s = do
let task = Task "action" a "1 second"
void $ atomically $ addTask task s
loop :: TVar Q -> IO ()
loop tq = do
q <- readTVarIO tq
let tasks = map key $ toList q
forM_ tasks action
putStrLn $ "tasks executed: " ++ show q
threadDelay 1000000
loop tq
pinsert x [] = [x]
pinsert x (y:ys) = if x < y then x:y:ys
else y:(pinsert x ys)
| darthdeus/schedooler | src/Schedooler/Internal.hs | bsd-3-clause | 1,971 | 0 | 15 | 629 | 761 | 369 | 392 | 60 | 2 |
module Game
( freshPuzzle
, runGame
) where
import Control.Monad (forever, when)
import Data.Maybe (isJust, fromMaybe)
import Data.List (intersperse)
import System.Exit (exitSuccess)
data Puzzle = Puzzle String [Maybe Char] [Char]
instance Show Puzzle where
show (Puzzle _ hits guessed) =
intersperse ' ' (fmap renderPuzzleChar hits) ++ " Guessed so far: " ++ guessed
freshPuzzle :: String -> Puzzle
freshPuzzle str =
Puzzle str hits []
where
len = length str
hits = replicate len Nothing
charInWord :: Puzzle -> Char -> Bool
charInWord (Puzzle secret _ _) guess =
guess `elem` secret
alreadyGuessed :: Puzzle -> Char -> Bool
alreadyGuessed (Puzzle _ _ guessed) guess =
guess `elem` guessed
renderPuzzleChar :: Maybe Char -> Char
renderPuzzleChar =
fromMaybe '_'
fillInCharacter :: Puzzle -> Char -> Puzzle
fillInCharacter (Puzzle secret hits guessed) guess =
Puzzle secret newHits (guessed ++ [guess])
where
zipper g sChar gChar =
if sChar == g
then Just g
else gChar
newHits =
zipWith (zipper guess) secret hits
handleGuess :: Puzzle -> Char -> IO Puzzle
handleGuess puzzle guess = do
putStrLn $ "Your guess was: " ++ [guess]
case (charInWord puzzle guess
, alreadyGuessed puzzle guess) of
(_, True) -> do
putStrLn "You already guessed that\
\ character, pick something else!"
return puzzle
(True, _) -> do
putStrLn "This character was in the word,\
\ filling in the word accordingly"
return (fillInCharacter puzzle guess)
(False, _) -> do
putStrLn "This character wasn't in\
\ the word, try again."
return (fillInCharacter puzzle guess)
gameOver :: Puzzle -> IO ()
gameOver (Puzzle secret hits guessed) =
when (badGuesses > 8) $
do
putStrLn "You lose!"
putStrLn $ "The word was: " ++ secret
exitSuccess
where
successfulHits = length $ filter isJust hits
badGuesses = length guessed - successfulHits
gameWin :: Puzzle -> IO ()
gameWin (Puzzle _ hits _) =
when (all isJust hits) $
do
putStrLn "You win!"
exitSuccess
runGame :: Puzzle -> IO ()
runGame puzzle = forever $ do
gameOver puzzle
gameWin puzzle
putStrLn $ "\nCurrent puzzle is: " ++ show puzzle
putStr "Guess a letter: "
guess <- getLine
case guess of
[c] -> handleGuess puzzle c >>= runGame
_ ->putStrLn "Your guess must\
\ be a single character"
| NewMountain/hangmanSimple | src/Game.hs | bsd-3-clause | 2,715 | 0 | 14 | 873 | 768 | 383 | 385 | 73 | 3 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeInType #-}
module Servant.API.Named (
Named(..),
NameList(..),
(::=)(..),
Nil,
(:=),
(::<|>),
FromNamed,
fromNamed
) where
import Servant.API.Named.Internal
import Data.Kind (Type)
import GHC.TypeLits (Symbol, CmpSymbol)
type Nil = '[]
infix 8 :=
-- | Notational convenience to make value and type level defns match up
type family n := a where
(Named n) := a = '(n, a)
infixr 7 ::<|>
-- | Notational convenience to make value and type level defns match up
type family x ::<|> y where
x ::<|> y = x ': y
type family Insert (x :: (Symbol, Type)) (xs :: [(Symbol, Type)]) :: [(Symbol, Type)] where
Insert x '[] = '[x]
Insert '(xName, x) ( '(yName, y) ': ys) = If ((CmpSymbol xName yName) == 'LT)
( '(xName, x) ': '(yName, y) ': ys )
( '(yName, y) ': Insert '(xName, x) ys )
type family Sort (xs :: [(Symbol, Type)]) :: [(Symbol, Type)] where
Sort '[] = '[]
Sort (x ': xs) = Insert x (Sort xs)
sInsert :: Named name -> a -> NameList xs -> NameList (Insert '(name, a) xs)
sInsert pName val Nil = pName := val ::<|> Nil
sInsert xName xVal xs@(yName := yVal ::<|> rest) = sIf (sCompare xName yName) (xName := xVal ::<|> xs) (yName := yVal ::<|> (sInsert xName xVal rest))
sSort :: NameList xs -> NameList (Sort xs)
sSort Nil = Nil
sSort (name := val ::<|> rest) = sInsert name val (sSort rest)
type family FromNamed xs where
FromNamed xs = FromNamedSorted (Sort xs)
fromNamed :: NameList xs -> FromNamed xs
fromNamed xs = fromNamedSorted (sSort xs)
| benweitzman/servant-named | src/Servant/API/Named.hs | bsd-3-clause | 1,962 | 0 | 12 | 459 | 687 | 396 | 291 | 49 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.Multihash
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.List
import System.Console.GetOpt
import System.IO hiding (withFile)
import System.Environment
import System.Exit
import Text.Printf (printf)
main :: IO ()
main = do
(_args, files) <- getArgs >>= parse
mapM_ printers files
putStrLn "Done! Note: shake-128/256 are not yet part of the library"
printer :: (HashAlgorithm a, Codable a, Show a) => a -> ByteString -> IO ()
printer alg bs = do
let m = multihash alg bs
putStrLn $ printf "Hash algorithm: %s" (show alg)
putStrLn $ printf "Base16: %s" (encode' Base16 m :: String)
putStrLn $ printf "Base32: %s" (encode' Base32 m :: String)
putStrLn $ printf "Base58: %s" (encode' Base58 m :: String)
putStrLn $ printf "Base64: %s" (encode' Base64 m :: String)
putStrLn ""
printers :: FilePath -> IO ()
printers f = do
d <- withFile f
putStrLn $ printf "Hashing %s\n" (if f == "-" then show d else show f)
printer SHA1 d
printer SHA256 d
printer SHA512 d
printer SHA3_512 d
printer SHA3_384 d
printer SHA3_256 d
printer SHA3_224 d
printer Blake2b_512 d
printer Blake2s_256 d
putStrLn ""
where withFile f = if f == "-" then B.getContents else B.readFile f
data Flag = Help -- --help
deriving (Eq,Ord,Enum,Show,Bounded)
flags :: [OptDescr Flag]
flags = [Option [] ["help"] (NoArg Help) "Print this help message"]
parse :: [String] -> IO ([Flag], [String])
parse argv = case getOpt Permute flags argv of
(args,fs,[]) -> do
let files = if null fs then ["-"] else fs
if Help `elem` args
then do hPutStrLn stderr (usageInfo header flags)
exitSuccess
else return (nub (concatMap set args), files)
(_,_,errs) -> do
hPutStrLn stderr (concat errs ++ usageInfo header flags)
exitWith (ExitFailure 1)
where header = "Usage: mh [file ...]"
set f = [f]
| mseri/crypto-multihash | app/Main.hs | bsd-3-clause | 2,032 | 0 | 15 | 490 | 747 | 374 | 373 | 57 | 4 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Types.Stash where
import qualified Data.IntMap.Strict as IntMap
import Data.IntMap.Strict (IntMap)
import qualified Data.HashSet as HashSet
import Data.HashSet (HashSet)
import Data.Maybe
import Prelude
import Duckling.Types
newtype Stash = Stash { getSet :: IntMap (HashSet Node) }
filter :: (Node -> Bool) -> Stash -> Stash
filter p Stash{..} = Stash (IntMap.map (HashSet.filter p) getSet)
toPosOrderedList:: Stash -> [Node]
toPosOrderedList Stash{..} = concatMap HashSet.toList $ IntMap.elems getSet
toPosOrderedListFrom :: Stash -> Int -> [Node]
toPosOrderedListFrom Stash{..} pos =
concatMap HashSet.toList $ maybeToList equal ++ IntMap.elems bigger
where
(_smaller, equal, bigger) = IntMap.splitLookup pos getSet
-- this is where we take advantage of the order
empty :: Stash
empty = Stash IntMap.empty
fromList :: [Node] -> Stash
fromList ns = Stash (IntMap.fromListWith HashSet.union $ map mkKV ns)
where
mkKV n@Node{nodeRange = Range start _} = (start, HashSet.singleton n)
union :: Stash -> Stash -> Stash
union (Stash set1) (Stash set2) =
Stash (IntMap.unionWith HashSet.union set1 set2)
-- Checks if two stashes have equal amount of Nodes on each position.
-- Used to detect a fixpoint, because the Stashes are only growing.
--
-- Not proud of this, but the algorithm shouldn't use it as the termination
-- condition, it should know when it stopped adding tokens
sizeEqual :: Stash -> Stash -> Bool
sizeEqual (Stash set1) (Stash set2) =
go (IntMap.toAscList set1) (IntMap.toAscList set2)
where
go [] [] = True
go [] (_:_) = False
go (_:_) [] = False
go ((k1, h1):rest1) ((k2, h2):rest2) =
k1 == k2 && HashSet.size h1 == HashSet.size h2 && go rest1 rest2
null :: Stash -> Bool
null (Stash set) = IntMap.null set
| facebookincubator/duckling | Duckling/Types/Stash.hs | bsd-3-clause | 2,057 | 0 | 12 | 355 | 619 | 333 | 286 | 37 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
module Control.Pipe.Attoparsec (
ParseError(..),
pipeParser,
) where
import qualified Control.Exception as E
import Control.Pipe
import Control.Pipe.Combinators
import Control.Pipe.Exception
import Data.Attoparsec.Types
import Data.Maybe
import Data.Monoid
import Data.Typeable
-- | A parse error as returned by Attoparsec.
data ParseError
= ParseError {
errorContexts :: [String], -- ^ Contexts where the error occurred.
errorMessage :: String -- ^ Error message.
}
| DivergentParser -- ^ Returned if a parser does not terminate
-- when its input is exhausted.
deriving (Show, Typeable)
instance E.Exception ParseError
-- | Convert a parser continuation into a Pipe.
--
-- To get a parser continuation from a 'Parser', use the @parse@ function of the
-- appropriate Attoparsec module.
pipeParser :: (Monoid a, Monad m) => (a -> IResult a r) -> Pipe a x m (a, Either ParseError r)
pipeParser p = go p
where
go p = do
chunk <- tryAwait
case p (maybe mempty id chunk) of
Fail leftover contexts msg ->
return (leftover, Left $ ParseError contexts msg)
Partial p' ->
if isNothing chunk
then return (mempty, Left DivergentParser)
else go p'
Done leftover result ->
return (leftover, Right result)
| pcapriotti/pipes-attoparsec | Control/Pipe/Attoparsec.hs | bsd-3-clause | 1,412 | 0 | 15 | 373 | 316 | 175 | 141 | 32 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module CacheDNS.APP.Types
( ServerConfig(..)
, DNSKey(..)
, DNSServer(..)
, GlobalConfig(..)
)
where
import qualified CacheDNS.DNS as DNS
data ServerConfig = ServerConfig { server_host :: Maybe String
, server_port :: Maybe String
} deriving (Show)
data DNSServer = DNSServer { host :: Maybe String
, port :: Maybe String
, method :: Maybe String
, password :: Maybe String
} deriving (Show)
data GlobalConfig = GlobalConfig { server :: DNSServer
, stype :: String
, nserver :: Maybe [DNSServer]
, cserver :: Maybe [DNSServer]
, chinese :: Maybe String
} deriving (Show)
type DNSKey = (DNS.Domain,Int) | DavidAlphaFox/CacheDNS | app/CacheDNS/APP/Types.hs | bsd-3-clause | 1,006 | 0 | 10 | 468 | 207 | 126 | 81 | 22 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Dense.Base
-- Copyright : (c) Christopher Chalmers
-- License : BSD3
--
-- Maintainer : Christopher Chalmers
-- Stability : provisional
-- Portability : non-portable
--
-- Base module for multidimensional arrays. This module exports the
-- constructors for the 'Array' data type.
--
-- Also, to prevent this module becomming too large, only the data types
-- and the functions nessesary for the instances are defined here. All
-- other functions are defined in "Data.Dense.Generic".
-----------------------------------------------------------------------------
module Data.Dense.Base
(
-- * Array types
Array (..)
, Boxed
-- ** Lenses
, vector
, values
-- ** Conversion to/from mutable arrays
, unsafeThaw
, unsafeFreeze
-- * Delayed
, Delayed (..)
, delay
, manifest
, genDelayed
, indexDelayed
-- * Focused
, Focused (..)
) where
#if __GLASGOW_HASKELL__ <= 708
import Control.Applicative (pure, (*>))
import Data.Foldable (Foldable)
import Data.Monoid (Monoid, mappend, mempty)
#endif
import Control.Applicative (liftA2)
import Control.Comonad
import Control.Comonad.Store
import Control.DeepSeq
import Control.Lens
import Control.Lens.Internal (noEffect)
import Control.Monad (guard, liftM)
import Control.Monad.Primitive
import Data.Binary as Binary
import Data.Bytes.Serial
import Data.Data
import qualified Data.Foldable as F
import Data.Functor.Apply
import Data.Functor.Classes
import Data.Functor.Extend
import Data.Hashable
import Data.Serialize as Cereal
import Data.Traversable (for)
import qualified Data.Vector as B
import Data.Vector.Generic (Vector)
import qualified Data.Vector.Generic as G
import Data.Vector.Generic.Lens (vectorTraverse)
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Generic.New as New
-- import GHC.Generics (Generic, Generic1)
import Linear hiding (vector)
import Text.ParserCombinators.ReadPrec (readS_to_Prec)
import qualified Text.Read as Read
import Data.Dense.Index
import Data.Dense.Mutable (MArray (..))
import Control.Concurrent (forkOn, getNumCapabilities,
newEmptyMVar, putMVar,
takeMVar)
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (null, replicate,
zipWith, zipWith3)
import GHC.Types (SPEC (..))
-- | An 'Array' is a vector with a shape.
data Array v f a = Array !(Layout f) !(v a)
deriving Typeable
-- Lenses --------------------------------------------------------------
-- | Indexed traversal over the elements of an array. The index is the
-- current position in the array.
values :: (Shape f, Vector v a, Vector w b)
=> IndexedTraversal (f Int) (Array v f a) (Array w f b) a b
values = \f arr -> reindexed (shapeFromIndex $ extent arr) (vector . vectorTraverse) f arr
{-# INLINE values #-}
-- | Indexed lens over the underlying vector of an array. The index is
-- the 'extent' of the array. You must _not_ change the length of the
-- vector, otherwise an error will be thrown (even for 'V1' layouts,
-- use 'flat' for 'V1').
vector :: (Vector v a, Vector w b) => IndexedLens (Layout f) (Array v f a) (Array w f b) (v a) (w b)
vector f (Array l v) =
indexed f l v <&> \w ->
sizeMissmatch (G.length v) (G.length w)
("vector: trying to replace vector of length " ++ show (G.length v) ++ " with one of length " ++ show (G.length w))
$ Array l w
{-# INLINE vector #-}
-- Mutable conversion --------------------------------------------------
-- | O(1) Unsafe convert a mutable array to an immutable one without
-- copying. The mutable array may not be used after this operation.
unsafeFreeze :: (PrimMonad m, Vector v a)
=> MArray (G.Mutable v) f (PrimState m) a -> m (Array v f a)
unsafeFreeze (MArray l mv) = Array l `liftM` G.unsafeFreeze mv
{-# INLINE unsafeFreeze #-}
-- | O(1) Unsafely convert an immutable array to a mutable one without
-- copying. The immutable array may not be used after this operation.
unsafeThaw :: (PrimMonad m, Vector v a)
=> Array v f a -> m (MArray (G.Mutable v) f (PrimState m) a)
unsafeThaw (Array l v) = MArray l `liftM` G.unsafeThaw v
{-# INLINE unsafeThaw #-}
------------------------------------------------------------------------
-- Instances
------------------------------------------------------------------------
-- | The 'size' of the 'layout' __must__ remain the same or an error is thrown.
instance Shape f => HasLayout f (Array v f a) where
layout f (Array l v) = f l <&> \l' ->
sizeMissmatch (shapeSize l) (shapeSize l')
("layout (Array): trying to replace shape " ++ showShape l ++ " with " ++ showShape l')
$ Array l' v
{-# INLINE layout #-}
-- layout :: (Shape l, Shape t) => Lens (Array v l a) (Array v t a) (Layout l) (Layout t)
instance (Vector v a, Eq1 f, Eq a) => Eq (Array v f a) where
Array l1 v1 == Array l2 v2 = eq1 l1 l2 && G.eq v1 v2
{-# INLINE (==) #-}
instance (Vector v a, Show1 f, Show a) => Show (Array v f a) where
showsPrec p (Array l v2) = showParen (p > 10) $
showString "Array " . showsPrec1 11 l . showChar ' ' . G.showsPrec 11 v2
type instance Index (Array v f a) = f Int
type instance IxValue (Array v f a) = a
instance (Shape f, Vector v a) => Ixed (Array v f a) where
ix x f (Array l v)
| shapeInRange l x = f (G.unsafeIndex v i) <&>
\a -> Array l (G.modify (\mv -> GM.unsafeWrite mv i a) v)
where i = shapeToIndex l x
ix _ _ arr = pure arr
{-# INLINE ix #-}
instance (Vector v a, Vector v b) => Each (Array v f a) (Array v f b) a b where
each = vector . vectorTraverse
{-# INLINE each #-}
instance (Shape f, Vector v a) => AsEmpty (Array v f a) where
_Empty = nearly (Array zero G.empty) (F.all (==0) . extent)
{-# INLINE _Empty #-}
instance (Vector v a, Read1 f, Read a) => Read (Array v f a) where
readPrec = Read.parens $ Read.prec 10 $ do
Read.Ident "Array" <- Read.lexP
l <- readS_to_Prec readsPrec1
v <- G.readPrec
return $ Array l v
instance (NFData (f Int), NFData (v a)) => NFData (Array v f a) where
rnf (Array l v) = rnf l `seq` rnf v
{-# INLINE rnf #-}
-- Boxed instances -----------------------------------------------------
-- | The vector is the boxed vector.
type Boxed v = v ~ B.Vector
instance Boxed v => Functor (Array v f) where
fmap = over vector . fmap
{-# INLINE fmap #-}
instance Boxed v => F.Foldable (Array v f) where
foldMap f = F.foldMap f . view vector
{-# INLINE foldMap #-}
instance Boxed v => Traversable (Array v f) where
traverse = each
{-# INLINE traverse #-}
#if (MIN_VERSION_transformers(0,5,0)) || !(MIN_VERSION_transformers(0,4,0))
instance (Boxed v, Eq1 f) => Eq1 (Array v f) where
liftEq f (Array l1 v1) (Array l2 v2) = eq1 l1 l2 && G.and (G.zipWith f v1 v2)
{-# INLINE liftEq #-}
instance (Boxed v, Read1 f) => Read1 (Array v f) where
liftReadsPrec _ f = readsData $ readsBinaryWith readsPrec1 (const f) "Array" (\c l -> Array c (G.fromList l))
{-# INLINE liftReadsPrec #-}
#else
instance (Boxed v, Eq1 f) => Eq1 (Array v f) where
eq1 = (==)
{-# INLINE eq1 #-}
instance (Boxed v, Read1 f) => Read1 (Array v f) where
readsPrec1 = readsPrec
{-# INLINE readsPrec1 #-}
#endif
instance (Boxed v, Shape f) => FunctorWithIndex (f Int) (Array v f)
instance (Boxed v, Shape f) => FoldableWithIndex (f Int) (Array v f)
instance (Boxed v, Shape f) => TraversableWithIndex (f Int) (Array v f) where
itraverse = itraverseOf values
{-# INLINE itraverse #-}
itraversed = values
{-# INLINE itraversed #-}
instance (Boxed v, Shape f, Serial1 f) => Serial1 (Array v f) where
serializeWith putF (Array l v) = do
serializeWith serialize l
F.traverse_ putF v
deserializeWith = genGet (deserializeWith deserialize)
-- deriving instance (Generic1 v, Generic1 f) => Generic1 (Array v f)
-- instance (v ~ B.Vector, Shape l) => Apply (Array v l) where
-- instance (v ~ B.Vector, Shape l) => Bind (Array v l) where
-- instance (v ~ B.Vector, Shape l) => Additive (Array v l) where
-- instance (v ~ B.Vector, Shape l) => Metric (Array v l) where
-- V1 instances --------------------------------------------------------
-- Array v V1 a is essentially v a with a wrapper.
type instance G.Mutable (Array v f) = MArray (G.Mutable v) f
-- | 1D Arrays can be used as a generic 'Vector'.
instance (Vector v a, f ~ V1) => Vector (Array v f) a where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
basicUnsafeFreeze = unsafeFreeze
basicUnsafeThaw = unsafeThaw
basicLength (Array (V1 n) _) = n
basicUnsafeSlice i n (Array _ v) = Array (V1 n) $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (Array _ v) = G.basicUnsafeIndexM v
-- Serialise instances -------------------------------------------------
instance (Vector v a, Shape f, Serial1 f, Serial a) => Serial (Array v f a) where
serialize (Array l v) = do
serializeWith serialize l
traverseOf_ vectorTraverse serialize v
{-# INLINE serialize #-}
deserialize = genGet (deserializeWith deserialize) deserialize
{-# INLINE deserialize #-}
instance (Vector v a, Shape f, Binary (f Int), Binary a) => Binary (Array v f a) where
put (Array l v) = do
Binary.put l
traverseOf_ vectorTraverse Binary.put v
{-# INLINE put #-}
get = genGet Binary.get Binary.get
{-# INLINE get #-}
instance (Vector v a, Shape f, Serialize (f Int), Serialize a) => Serialize (Array v f a) where
put (Array l v) = do
Cereal.put l
traverseOf_ vectorTraverse Cereal.put v
{-# INLINE put #-}
get = genGet Cereal.get Cereal.get
{-# INLINE get #-}
genGet :: Monad m => (Vector v a, Shape f) => m (f Int) -> m a -> m (Array v f a)
genGet getL getA = do
l <- getL
let n = shapeSize l
nv0 = New.create (GM.new n)
f acc i = (\a -> New.modify (\mv -> GM.write mv i a) acc) `liftM` getA
nv <- F.foldlM f nv0 [0 .. n - 1]
return $! Array l (G.new nv)
{-# INLINE genGet #-}
instance (Vector v a, Foldable f, Hashable a) => Hashable (Array v f a) where
hashWithSalt s (Array l v) = G.foldl' hashWithSalt s' v
where s' = F.foldl' hashWithSalt s l
{-# INLINE hashWithSalt #-}
-- deriving instance (Generic (v a), Generic1 f) => Generic (Array v f a)
deriving instance (Typeable f, Typeable v, Typeable a, Data (f Int), Data (v a)) => Data (Array v f a)
-- instance (Vector v a, Typeable v, Typeable l, Shape l, Data a) => Data (Array v l a) where
-- gfoldl f z (Array l a) =
-- z (\l' a' -> Array (l & partsOf traverse .~ l') (G.fromList a')) `f` F.toList l `f` G.toList a
-- gunfold k z _ = k (k (z (\l a -> Array (zero & partsOf traverse .~ l) (G.fromList a))))
-- toConstr _ = con
-- dataTypeOf _ = ty
-- dataCast1 = gcast1
-- ty :: DataType
-- ty = mkDataType "Array" [con]
-- con :: Constr
-- con = mkConstr ty "Array" [] Prefix
------------------------------------------------------------------------
-- Delayed
------------------------------------------------------------------------
-- | A delayed representation of an array. This useful for mapping over
-- an array in parallel.
data Delayed f a = Delayed !(Layout f) (f Int -> a)
deriving (Typeable, Functor)
-- | Turn a material array into a delayed one with the same shape.
delay :: (Vector v a, Shape f) => Array v f a -> Delayed f a
delay (Array l v) = Delayed l (G.unsafeIndex v . shapeToIndex l)
{-# INLINE delay #-}
-- | The 'size' of the 'layout' __must__ remain the same or an error is thrown.
instance Shape f => HasLayout f (Delayed f a) where
layout f (Delayed l ixF) = f l <&> \l' ->
sizeMissmatch (shapeSize l) (shapeSize l')
("layout (Delayed): trying to replace shape " ++ showShape l ++ " with " ++ showShape l')
$ Delayed l' ixF
{-# INLINE layout #-}
-- | 'foldMap' in parallel.
instance Shape f => Foldable (Delayed f) where
foldr f b (Delayed l ixF) = foldrOf shapeIndexes (\x -> f (ixF x)) b l
{-# INLINE foldr #-}
foldMap = foldDelayed . const
#if __GLASGOW_HASKELL__ >= 710
length = size
{-# INLINE length #-}
#endif
instance (Shape f, Show1 f, Show a) => Show (Delayed f a) where
showsPrec p arr@(Delayed l _) = showParen (p > 10) $
showString "Delayed " . showsPrec1 11 l . showChar ' ' . showsPrec 11 (F.toList arr)
-- instance (Shape f, Show1 f) => Show1 (Delayed f) where
-- showsPrec1 = showsPrec
instance Shape f => Traversable (Delayed f) where
traverse f arr = delay <$> traversed f (manifest arr)
instance Shape f => Apply (Delayed f) where
{-# INLINE (<.>) #-}
{-# INLINE (<. ) #-}
{-# INLINE ( .>) #-}
(<.>) = liftI2 id
(<. ) = liftI2 const
( .>) = liftI2 (const id)
instance Shape f => Additive (Delayed f) where
zero = _Empty # ()
{-# INLINE zero #-}
-- This can only be satisfied on if one array is larger than the other
-- in all dimensions, otherwise there will be gaps in the array
liftU2 f (Delayed l ixF) (Delayed k ixG)
| l `eq1` k = Delayed l (liftA2 f ixF ixG)
-- l > k
| F.all (>= EQ) cmp = Delayed l $ \x ->
if | shapeInRange l x -> liftA2 f ixF ixG x
| otherwise -> ixF x
-- k > l
| F.all (<= EQ) cmp = Delayed k $ \x ->
if | shapeInRange k x -> liftA2 f ixF ixG x
| otherwise -> ixG x
-- not possible to union array sizes because there would be gaps,
-- just intersect them instead
| otherwise = Delayed (shapeIntersect l k) $ liftA2 f ixF ixG
where cmp = liftI2 compare l k
liftI2 f (Delayed l ixF) (Delayed k ixG) = Delayed (shapeIntersect l k) $ liftA2 f ixF ixG
{-# INLINE liftI2 #-}
instance Shape f => Metric (Delayed f)
instance FunctorWithIndex (f Int) (Delayed f) where
imap f (Delayed l ixF) = Delayed l $ \x -> f x (ixF x)
{-# INLINE imap #-}
-- | 'ifoldMap' in parallel.
instance Shape f => FoldableWithIndex (f Int) (Delayed f) where
ifoldr f b (Delayed l ixF) = foldrOf shapeIndexes (\x -> f x (ixF x)) b l
{-# INLINE ifoldr #-}
ifolded = ifoldring ifoldr
{-# INLINE ifolded #-}
ifoldMap = foldDelayed
{-# INLINE ifoldMap #-}
instance Shape f => TraversableWithIndex (f Int) (Delayed f) where
itraverse f arr = delay <$> itraverse f (manifest arr)
{-# INLINE itraverse #-}
instance Shape f => Each (Delayed f a) (Delayed f b) a b where
each = traversed
{-# INLINE each #-}
instance Shape f => AsEmpty (Delayed f a) where
_Empty = nearly (Delayed zero (error "empty delayed array"))
(\(Delayed l _) -> F.all (==0) l)
{-# INLINE _Empty #-}
type instance Index (Delayed f a) = f Int
type instance IxValue (Delayed f a) = a
instance Shape f => Ixed (Delayed f a) where
ix x f arr@(Delayed l ixF)
| shapeInRange l x = f (ixF x) <&> \a ->
let g y | eq1 x y = a
| otherwise = ixF x
in Delayed l g
| otherwise = pure arr
{-# INLINE ix #-}
-- | Index a delayed array, returning a 'IndexOutOfBounds' exception if
-- the index is out of range.
indexDelayed :: Shape f => Delayed f a -> f Int -> a
indexDelayed (Delayed l ixF) x =
boundsCheck l x $ ixF x
{-# INLINE indexDelayed #-}
foldDelayed :: (Shape f, Monoid m) => (f Int -> a -> m) -> (Delayed f a) -> m
foldDelayed f (Delayed l ixF) = unsafePerformIO $ do
childs <- for [0 .. threads - 1] $ \c -> do
child <- newEmptyMVar
_ <- forkOn c $ do
let k | c == threads - 1 = q + r
| otherwise = q
x = c * q
m = x + k
go i (Just s) acc
| i >= m = acc
| otherwise = let !acc' = acc `mappend` f s (ixF s)
in go (i+1) (shapeStep l s) acc'
go _ Nothing acc = acc
putMVar child $! go x (Just $ shapeFromIndex l x) mempty
return child
F.fold <$> for childs takeMVar
where
!n = shapeSize l
!(q, r) = n `quotRem` threads
!threads = unsafePerformIO getNumCapabilities
{-# INLINE foldDelayed #-}
-- | Parallel manifestation of a delayed array into a material one.
manifest :: (Vector v a, Shape f) => Delayed f a -> Array v f a
manifest (Delayed l ixF) = Array l v
where
!v = unsafePerformIO $! do
mv <- GM.new n
childs <- for [0 .. threads - 1] $ \c -> do
child <- newEmptyMVar
_ <- forkOn c $ do
let k | c == threads - 1 = q + r
| otherwise = q
x = c * q
iforOf_ (linearIndexesBetween x (x+k)) l $ \i s ->
GM.unsafeWrite mv i (ixF s)
putMVar child ()
return child
F.for_ childs takeMVar
G.unsafeFreeze mv
!n = shapeSize l
!(q, r) = n `quotRem` threads
!threads = unsafePerformIO getNumCapabilities
{-# INLINE manifest #-}
linearIndexesBetween :: Shape f => Int -> Int -> IndexedFold Int (Layout f) (f Int)
linearIndexesBetween i0 k g l = go SPEC i0 (Just $ shapeFromIndex l i0)
where
go !_ i (Just x) = indexed g i x *> go SPEC (i+1) (guard (i+1 < k) *> shapeStep l x)
go !_ _ _ = noEffect
{-# INLINE linearIndexesBetween #-}
-- | Generate a 'Delayed' array using the given 'Layout' and
-- construction function.
genDelayed :: Layout f -> (f Int -> a) -> Delayed f a
genDelayed = Delayed
{-# INLINE genDelayed #-}
------------------------------------------------------------------------
-- Focused
------------------------------------------------------------------------
-- | A delayed representation of an array with a focus on a single
-- element. This element is the target of 'extract'.
data Focused f a = Focused !(f Int) !(Delayed f a)
deriving (Typeable, Functor)
-- | The 'size' of the 'layout' __must__ remain the same or an error is thrown.
instance Shape f => HasLayout f (Focused f a) where
layout f (Focused x (Delayed l ixF)) = f l <&> \l' ->
sizeMissmatch (shapeSize l) (shapeSize l')
("layout (Focused): trying to replace shape " ++ showShape l ++ " with " ++ showShape l')
$ Focused x (Delayed l' ixF)
{-# INLINE layout #-}
instance Shape f => Comonad (Focused f) where
{-# INLINE extract #-}
{-# INLINE extend #-}
extract (Focused x d) = indexDelayed d x
extend f (Focused x d@(Delayed l _)) =
Focused x (genDelayed l $ \i -> f (Focused i d))
instance Shape f => Extend (Focused f) where
{-# INLINE extended #-}
extended = extend
instance Shape f => ComonadStore (f Int) (Focused f) where
{-# INLINE pos #-}
{-# INLINE peek #-}
{-# INLINE peeks #-}
{-# INLINE seek #-}
{-# INLINE seeks #-}
pos (Focused x _) = x
peek x (Focused _ d) = indexDelayed d x
peeks f (Focused x d) = indexDelayed d (f x)
seek x (Focused _ d) = Focused x d
seeks f (Focused x d) = Focused (f x) d
instance (Shape f, Show1 f, Show a) => Show (Focused f a) where
showsPrec p (Focused l d) = showParen (p > 10) $
showString "Focused " . showsPrec1 11 l . showChar ' ' . showsPrec 11 d
-- instance (Shape f, Show1 f) => Show1 (Focused f) where
-- showsPrec1 = showsPrec
type instance Index (Focused f a) = f Int
type instance IxValue (Focused f a) = a
instance Shape f => Foldable (Focused f) where
foldr f b (Focused _ d) = F.foldr f b d
{-# INLINE foldr #-}
foldMap f (Focused _ d) = F.foldMap f d
{-# INLINE foldMap #-}
#if __GLASGOW_HASKELL__ >= 710
length = size
{-# INLINE length #-}
#endif
instance Shape f => Traversable (Focused f) where
traverse f (Focused u d) = Focused u <$> traverse f d
{-# INLINE traverse #-}
-- | Index relative to focus.
instance Shape f => FunctorWithIndex (f Int) (Focused f) where
imap f (Focused u d) = Focused u (imap (f . (^-^ u)) d)
{-# INLINE imap #-}
-- | Index relative to focus.
instance Shape f => FoldableWithIndex (f Int) (Focused f) where
ifoldr f b (Focused u d) = ifoldr (f . (^-^ u)) b d
{-# INLINE ifoldr #-}
ifolded = ifoldring ifoldr
{-# INLINE ifolded #-}
ifoldMap f (Focused u d) = ifoldMap (f . (^-^) u) d
{-# INLINE ifoldMap #-}
-- | Index relative to focus.
instance Shape f => TraversableWithIndex (f Int) (Focused f) where
itraverse f (Focused u d) = Focused u <$> itraverse (f . (^-^ u)) d
{-# INLINE itraverse #-}
-- | Index relative to focus.
instance Shape f => Ixed (Focused f a) where
ix i f (Focused u d) = Focused u <$> ix (i ^-^ u) f d
{-# INLINE ix #-}
| cchalmers/shaped | src/Data/Dense/Base.hs | bsd-3-clause | 21,760 | 3 | 28 | 5,715 | 6,469 | 3,346 | 3,123 | 391 | 2 |
module Foreign.CRCSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
| smurphy8/crc-fast | test/Foreign/CRCSpec.hs | bsd-3-clause | 208 | 0 | 13 | 49 | 76 | 40 | 36 | 9 | 1 |
import qualified Language.Structure.Dependency as Dep (drawTree)
import qualified Language.Structure.Dependency.Parse as Dep (pTree,pDeps)
import Text.ParserCombinators.UU.Utils (runParser)
main :: IO ()
main =
putStrLn
. Dep.drawTree
. runParser "stdin" Dep.pDeps
=<< getContents
| pepijnkokke/Dep2Con | src/PrintDep.hs | bsd-3-clause | 314 | 0 | 8 | 63 | 81 | 49 | 32 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module DigitalOcean.Droplet(
Droplet(..),
droplets
) where
import Control.Applicative ()
import Control.Monad (liftM, mzero)
import Control.Monad.IO.Class
import Data.Aeson ((.:), FromJSON(..), Value(..), decode)
import DigitalOcean.Base
-- $setup
-- >>> import System.Environment
-- >>> import DigitalOcean.Base(Authentication(..))
-- >>> import Data.Maybe(isJust)
data Droplet = Droplet {
did :: Integer,
dname :: String,
dmemory :: Integer,
dvcpus :: Integer,
disk :: Integer,
dlocked :: Bool,
createdAtv2 :: String,
dstatus :: String,
backupIds :: [Integer]
} deriving (Show, Read)
newtype Droplets = Droplets [Droplet]
instance FromJSON Droplets where
parseJSON (Object v) = Droplets <$> v.: "droplets"
parseJSON _ = mzero
instance FromJSON Droplet where
parseJSON (Object v) =
Droplet <$>
(v .: "id") <*>
(v .: "name") <*>
(v .: "memory") <*>
(v .: "vcpus") <*>
(v .: "disk") <*>
(v .: "locked") <*>
(v .: "created_at") <*>
(v .: "status") <*>
(v .: "backup_ids")
parseJSON _ = mzero
-- | List all Droplets
--
-- @
-- do
-- tkn <- getEnv "DIGITAL_OCEAN_PERSONAL_ACCESS_TOKEN"
-- maybeDroplets <- droplets $ Authentication tkn
-- print $ show $ isJust maybeDroplets
-- @
--
droplets :: Authentication -> (MonadIO m) => m (Maybe [Droplet])
droplets a = liftM toList $ liftM decode (requestGet "droplets?page=1&per_page=100" a)
toList :: Maybe Droplets -> Maybe [Droplet]
toList = \ds -> case ds of Just(Droplets l) -> Just l
Nothing -> Nothing
| satokazuma/digitalocean-kzs | src/DigitalOcean/Droplet.hs | mit | 1,682 | 0 | 16 | 397 | 464 | 269 | 195 | 43 | 2 |
module Java.Annotations (
getAnnotations,
parseModifier
) where
import Language.Java.Syntax
import Java.Helper (concatIdent)
getAnnotations :: CompilationUnit -> [String]
getAnnotations (CompilationUnit _ _ typeDecls) =
concatMap fromTypeDecls typeDecls ++
concatMap methods typeDecls
fromTypeDecls :: TypeDecl -> [String]
fromTypeDecls (ClassTypeDecl (ClassDecl an _ _ _ _ _)) =
(filter (/="") . map parseModifier) an
fromTypeDecls _ = []
parseModifier :: Modifier -> String
parseModifier (Annotation (MarkerAnnotation name)) = concatIdent name
parseModifier (Annotation (NormalAnnotation name _)) = concatIdent name
parseModifier (Annotation (SingleElementAnnotation name _)) = concatIdent name
parseModifier _ = []
methods :: TypeDecl -> [String]
methods (ClassTypeDecl (ClassDecl _ _ _ _ _ cb)) =
classBody cb
methods _ = []
classBody :: ClassBody -> [String]
classBody (ClassBody decl) = concatMap fromDecl decl
fromDecl :: Decl -> [String]
fromDecl (MemberDecl mb) = methodDecl mb
fromDecl _ = []
methodDecl :: MemberDecl -> [String]
methodDecl (MethodDecl modifier _ _ _ _ _ _) = map parseModifier modifier
methodDecl (MemberClassDecl classDecl) =
fromTypeDecls (ClassTypeDecl classDecl)
methodDecl _ = []
| SmallImprovements/spring-clean | src/Java/Annotations.hs | mit | 1,235 | 0 | 9 | 186 | 439 | 225 | 214 | 32 | 1 |
module Helper (
module Test.Hspec
, module Test.QuickCheck
, module Control.Applicative
, module Data.IORef
) where
import Test.Hspec
import Test.QuickCheck
import Control.Applicative
import Data.IORef
| hspec/hspec | hspec-contrib/test/Helper.hs | mit | 245 | 0 | 5 | 67 | 50 | 32 | 18 | 9 | 0 |
{-# LANGUAGE PatternGuards, CPP, ScopedTypeVariables, ViewPatterns, FlexibleContexts #-}
{-
Copyright (C) 2010-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.EPUB
Copyright : Copyright (C) 2010-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to EPUB.
-}
module Text.Pandoc.Writers.EPUB ( writeEPUB ) where
import Data.IORef ( IORef, newIORef, readIORef, modifyIORef )
import qualified Data.Map as M
import Data.Maybe ( fromMaybe, catMaybes )
import Data.List ( isPrefixOf, isInfixOf, intercalate )
import System.Environment ( getEnv )
import Text.Printf (printf)
import System.FilePath ( takeExtension, takeFileName )
import System.FilePath.Glob ( namesMatching )
import Network.HTTP ( urlEncode )
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Text.Pandoc.UTF8 as UTF8
import Codec.Archive.Zip ( emptyArchive, addEntryToArchive, eRelativePath, fromEntry , Entry, toEntry, fromArchive)
import Data.Time.Clock.POSIX ( getPOSIXTime )
import Text.Pandoc.Compat.Time
import Text.Pandoc.Shared ( renderTags', safeRead, uniqueIdent, trim
, normalizeDate, readDataFile, stringify, warn
, hierarchicalize, fetchItem' )
import qualified Text.Pandoc.Shared as S (Element(..))
import Text.Pandoc.Builder (fromList, setMeta)
import Text.Pandoc.Options ( WriterOptions(..)
, HTMLMathMethod(..)
, EPUBVersion(..)
, ObfuscationMethod(NoObfuscation) )
import Text.Pandoc.Definition
import Text.Pandoc.Walk (walk, walkM, query)
import Data.Default
import Text.Pandoc.Writers.Markdown (writePlain)
import Control.Monad.State (modify, get, State, put, evalState)
import Control.Monad (mplus, liftM, when)
import Text.XML.Light ( unode, Element(..), unqual, Attr(..), add_attrs
, strContent, lookupAttr, Node(..), QName(..), parseXML
, onlyElems, node, ppElement)
import Text.Pandoc.UUID (getRandomUUID)
import Text.Pandoc.Writers.HTML ( writeHtml )
import Data.Char ( toLower, isDigit, isAlphaNum )
import Text.Pandoc.MIME (MimeType, getMimeType, extensionFromMimeType)
import qualified Control.Exception as E
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.HTML.TagSoup (Tag(TagOpen), fromAttrib, parseTags)
-- A Chapter includes a list of blocks and maybe a section
-- number offset. Note, some chapters are unnumbered. The section
-- number is different from the index number, which will be used
-- in filenames, chapter0003.xhtml.
data Chapter = Chapter (Maybe [Int]) [Block]
data EPUBMetadata = EPUBMetadata{
epubIdentifier :: [Identifier]
, epubTitle :: [Title]
, epubDate :: [Date]
, epubLanguage :: String
, epubCreator :: [Creator]
, epubContributor :: [Creator]
, epubSubject :: [String]
, epubDescription :: Maybe String
, epubType :: Maybe String
, epubFormat :: Maybe String
, epubPublisher :: Maybe String
, epubSource :: Maybe String
, epubRelation :: Maybe String
, epubCoverage :: Maybe String
, epubRights :: Maybe String
, epubCoverImage :: Maybe String
, epubStylesheet :: Maybe Stylesheet
, epubPageDirection :: Maybe ProgressionDirection
} deriving Show
data Stylesheet = StylesheetPath FilePath
| StylesheetContents String
deriving Show
data Date = Date{
dateText :: String
, dateEvent :: Maybe String
} deriving Show
data Creator = Creator{
creatorText :: String
, creatorRole :: Maybe String
, creatorFileAs :: Maybe String
} deriving Show
data Identifier = Identifier{
identifierText :: String
, identifierScheme :: Maybe String
} deriving Show
data Title = Title{
titleText :: String
, titleFileAs :: Maybe String
, titleType :: Maybe String
} deriving Show
data ProgressionDirection = LTR | RTL deriving Show
dcName :: String -> QName
dcName n = QName n Nothing (Just "dc")
dcNode :: Node t => String -> t -> Element
dcNode = node . dcName
opfName :: String -> QName
opfName n = QName n Nothing (Just "opf")
toId :: FilePath -> String
toId = map (\x -> if isAlphaNum x || x == '-' || x == '_'
then x
else '_') . takeFileName
removeNote :: Inline -> Inline
removeNote (Note _) = Str ""
removeNote x = x
getEPUBMetadata :: WriterOptions -> Meta -> IO EPUBMetadata
getEPUBMetadata opts meta = do
let md = metadataFromMeta opts meta
let elts = onlyElems $ parseXML $ writerEpubMetadata opts
let md' = foldr addMetadataFromXML md elts
let addIdentifier m =
if null (epubIdentifier m)
then do
randomId <- fmap show getRandomUUID
return $ m{ epubIdentifier = [Identifier randomId Nothing] }
else return m
let addLanguage m =
if null (epubLanguage m)
then case lookup "lang" (writerVariables opts) of
Just x -> return m{ epubLanguage = x }
Nothing -> do
localeLang <- E.catch (liftM
(map (\c -> if c == '_' then '-' else c) .
takeWhile (/='.')) $ getEnv "LANG")
(\e -> let _ = (e :: E.SomeException) in return "en-US")
return m{ epubLanguage = localeLang }
else return m
let fixDate m =
if null (epubDate m)
then do
currentTime <- getCurrentTime
return $ m{ epubDate = [ Date{
dateText = showDateTimeISO8601 currentTime
, dateEvent = Nothing } ] }
else return m
let addAuthor m =
if any (\c -> creatorRole c == Just "aut") $ epubCreator m
then return m
else do
let authors' = map stringify $ docAuthors meta
let toAuthor name = Creator{ creatorText = name
, creatorRole = Just "aut"
, creatorFileAs = Nothing }
return $ m{ epubCreator = map toAuthor authors' ++ epubCreator m }
addIdentifier md' >>= fixDate >>= addAuthor >>= addLanguage
addMetadataFromXML :: Element -> EPUBMetadata -> EPUBMetadata
addMetadataFromXML e@(Element (QName name _ (Just "dc")) attrs _ _) md
| name == "identifier" = md{ epubIdentifier =
Identifier{ identifierText = strContent e
, identifierScheme = lookupAttr (opfName "scheme") attrs
} : epubIdentifier md }
| name == "title" = md{ epubTitle =
Title{ titleText = strContent e
, titleFileAs = getAttr "file-as"
, titleType = getAttr "type"
} : epubTitle md }
| name == "date" = md{ epubDate =
Date{ dateText = fromMaybe "" $ normalizeDate' $ strContent e
, dateEvent = getAttr "event"
} : epubDate md }
| name == "language" = md{ epubLanguage = strContent e }
| name == "creator" = md{ epubCreator =
Creator{ creatorText = strContent e
, creatorRole = getAttr "role"
, creatorFileAs = getAttr "file-as"
} : epubCreator md }
| name == "contributor" = md{ epubContributor =
Creator { creatorText = strContent e
, creatorRole = getAttr "role"
, creatorFileAs = getAttr "file-as"
} : epubContributor md }
| name == "subject" = md{ epubSubject = strContent e : epubSubject md }
| name == "description" = md { epubDescription = Just $ strContent e }
| name == "type" = md { epubType = Just $ strContent e }
| name == "format" = md { epubFormat = Just $ strContent e }
| name == "type" = md { epubType = Just $ strContent e }
| name == "publisher" = md { epubPublisher = Just $ strContent e }
| name == "source" = md { epubSource = Just $ strContent e }
| name == "relation" = md { epubRelation = Just $ strContent e }
| name == "coverage" = md { epubCoverage = Just $ strContent e }
| name == "rights" = md { epubRights = Just $ strContent e }
| otherwise = md
where getAttr n = lookupAttr (opfName n) attrs
addMetadataFromXML _ md = md
metaValueToString :: MetaValue -> String
metaValueToString (MetaString s) = s
metaValueToString (MetaInlines ils) = writePlain def
(Pandoc nullMeta [Plain ils])
metaValueToString (MetaBlocks bs) = writePlain def (Pandoc nullMeta bs)
metaValueToString (MetaBool b) = show b
metaValueToString _ = ""
getList :: String -> Meta -> (MetaValue -> a) -> [a]
getList s meta handleMetaValue =
case lookupMeta s meta of
Just (MetaList xs) -> map handleMetaValue xs
Just mv -> [handleMetaValue mv]
Nothing -> []
getIdentifier :: Meta -> [Identifier]
getIdentifier meta = getList "identifier" meta handleMetaValue
where handleMetaValue (MetaMap m) =
Identifier{ identifierText = maybe "" metaValueToString
$ M.lookup "text" m
, identifierScheme = metaValueToString <$>
M.lookup "scheme" m }
handleMetaValue mv = Identifier (metaValueToString mv) Nothing
getTitle :: Meta -> [Title]
getTitle meta = getList "title" meta handleMetaValue
where handleMetaValue (MetaMap m) =
Title{ titleText = maybe "" metaValueToString $ M.lookup "text" m
, titleFileAs = metaValueToString <$> M.lookup "file-as" m
, titleType = metaValueToString <$> M.lookup "type" m }
handleMetaValue mv = Title (metaValueToString mv) Nothing Nothing
getCreator :: String -> Meta -> [Creator]
getCreator s meta = getList s meta handleMetaValue
where handleMetaValue (MetaMap m) =
Creator{ creatorText = maybe "" metaValueToString $ M.lookup "text" m
, creatorFileAs = metaValueToString <$> M.lookup "file-as" m
, creatorRole = metaValueToString <$> M.lookup "role" m }
handleMetaValue mv = Creator (metaValueToString mv) Nothing Nothing
getDate :: String -> Meta -> [Date]
getDate s meta = getList s meta handleMetaValue
where handleMetaValue (MetaMap m) =
Date{ dateText = maybe "" id $
M.lookup "text" m >>= normalizeDate' . metaValueToString
, dateEvent = metaValueToString <$> M.lookup "event" m }
handleMetaValue mv = Date { dateText = maybe ""
id $ normalizeDate' $ metaValueToString mv
, dateEvent = Nothing }
simpleList :: String -> Meta -> [String]
simpleList s meta =
case lookupMeta s meta of
Just (MetaList xs) -> map metaValueToString xs
Just x -> [metaValueToString x]
Nothing -> []
metadataFromMeta :: WriterOptions -> Meta -> EPUBMetadata
metadataFromMeta opts meta = EPUBMetadata{
epubIdentifier = identifiers
, epubTitle = titles
, epubDate = date
, epubLanguage = language
, epubCreator = creators
, epubContributor = contributors
, epubSubject = subjects
, epubDescription = description
, epubType = epubtype
, epubFormat = format
, epubPublisher = publisher
, epubSource = source
, epubRelation = relation
, epubCoverage = coverage
, epubRights = rights
, epubCoverImage = coverImage
, epubStylesheet = stylesheet
, epubPageDirection = pageDirection
}
where identifiers = getIdentifier meta
titles = getTitle meta
date = getDate "date" meta
language = maybe "" metaValueToString $
lookupMeta "language" meta `mplus` lookupMeta "lang" meta
creators = getCreator "creator" meta
contributors = getCreator "contributor" meta
subjects = simpleList "subject" meta
description = metaValueToString <$> lookupMeta "description" meta
epubtype = metaValueToString <$> lookupMeta "type" meta
format = metaValueToString <$> lookupMeta "format" meta
publisher = metaValueToString <$> lookupMeta "publisher" meta
source = metaValueToString <$> lookupMeta "source" meta
relation = metaValueToString <$> lookupMeta "relation" meta
coverage = metaValueToString <$> lookupMeta "coverage" meta
rights = metaValueToString <$> lookupMeta "rights" meta
coverImage = lookup "epub-cover-image" (writerVariables opts) `mplus`
(metaValueToString <$> lookupMeta "cover-image" meta)
stylesheet = (StylesheetContents <$> writerEpubStylesheet opts) `mplus`
((StylesheetPath . metaValueToString) <$>
lookupMeta "stylesheet" meta)
pageDirection = case map toLower . metaValueToString <$>
lookupMeta "page-progression-direction" meta of
Just "ltr" -> Just LTR
Just "rtl" -> Just RTL
_ -> Nothing
-- | Produce an EPUB file from a Pandoc document.
writeEPUB :: WriterOptions -- ^ Writer options
-> Pandoc -- ^ Document to convert
-> IO B.ByteString
writeEPUB opts doc@(Pandoc meta _) = do
let version = fromMaybe EPUB2 (writerEpubVersion opts)
let epub3 = version == EPUB3
epochtime <- floor `fmap` getPOSIXTime
let mkEntry path content = toEntry path epochtime content
let vars = ("epub3", if epub3 then "true" else "false")
: ("css", "stylesheet.css")
: writerVariables opts
let opts' = opts{ writerEmailObfuscation = NoObfuscation
, writerStandalone = True
, writerSectionDivs = True
, writerHtml5 = epub3
, writerVariables = vars
, writerHTMLMathMethod =
if epub3
then MathML Nothing
else writerHTMLMathMethod opts
, writerWrapText = True }
metadata <- getEPUBMetadata opts' meta
-- cover page
(cpgEntry, cpicEntry) <-
case epubCoverImage metadata of
Nothing -> return ([],[])
Just img -> do
let coverImage = "media/" ++ takeFileName img
let cpContent = renderHtml $ writeHtml
opts'{ writerVariables = ("coverpage","true"):vars }
(Pandoc meta [RawBlock (Format "html") $ "<div id=\"cover-image\">\n<img src=\"" ++ coverImage ++ "\" alt=\"cover image\" />\n</div>"])
imgContent <- B.readFile img
return ( [mkEntry "cover.xhtml" cpContent]
, [mkEntry coverImage imgContent] )
-- title page
let tpContent = renderHtml $ writeHtml opts'{
writerVariables = ("titlepage","true"):vars }
(Pandoc meta [])
let tpEntry = mkEntry "title_page.xhtml" tpContent
-- handle pictures
mediaRef <- newIORef []
Pandoc _ blocks <- walkM (transformInline opts' mediaRef) doc >>=
walkM (transformBlock opts' mediaRef)
picEntries <- (catMaybes . map (snd . snd)) <$> readIORef mediaRef
-- handle fonts
let matchingGlob f = do
xs <- namesMatching f
when (null xs) $
warn $ f ++ " did not match any font files."
return xs
let mkFontEntry f = mkEntry (takeFileName f) `fmap` B.readFile f
fontFiles <- concat <$> mapM matchingGlob (writerEpubFonts opts')
fontEntries <- mapM mkFontEntry fontFiles
-- set page progression direction attribution
let progressionDirection = case epubPageDirection metadata of
Just LTR | epub3 ->
[("page-progression-direction", "ltr")]
Just RTL | epub3 ->
[("page-progression-direction", "rtl")]
_ -> []
-- body pages
-- add level 1 header to beginning if none there
let blocks' = addIdentifiers
$ case blocks of
(Header 1 _ _ : _) -> blocks
_ -> Header 1 ("",["unnumbered"],[])
(docTitle' meta) : blocks
let chapterHeaderLevel = writerEpubChapterLevel opts
let isChapterHeader (Header n _ _) = n <= chapterHeaderLevel
isChapterHeader (Div ("",["references"],[]) (Header n _ _:_)) =
n <= chapterHeaderLevel
isChapterHeader _ = False
let toChapters :: [Block] -> State [Int] [Chapter]
toChapters [] = return []
toChapters (Div ("",["references"],[]) bs@(Header 1 _ _:_) : rest) =
toChapters (bs ++ rest)
toChapters (Header n attr@(_,classes,_) ils : bs) = do
nums <- get
mbnum <- if "unnumbered" `elem` classes
then return Nothing
else case splitAt (n - 1) nums of
(ks, (m:_)) -> do
let nums' = ks ++ [m+1]
put nums'
return $ Just (ks ++ [m])
-- note, this is the offset not the sec number
(ks, []) -> do
let nums' = ks ++ [1]
put nums'
return $ Just ks
let (xs,ys) = break isChapterHeader bs
(Chapter mbnum (Header n attr ils : xs) :) `fmap` toChapters ys
toChapters (b:bs) = do
let (xs,ys) = break isChapterHeader bs
(Chapter Nothing (b:xs) :) `fmap` toChapters ys
let chapters' = evalState (toChapters blocks') []
let extractLinkURL' :: Int -> Inline -> [(String, String)]
extractLinkURL' num (Span (ident, _, _) _)
| not (null ident) = [(ident, showChapter num ++ ('#':ident))]
extractLinkURL' _ _ = []
let extractLinkURL :: Int -> Block -> [(String, String)]
extractLinkURL num (Div (ident, _, _) _)
| not (null ident) = [(ident, showChapter num ++ ('#':ident))]
extractLinkURL num (Header _ (ident, _, _) _)
| not (null ident) = [(ident, showChapter num ++ ('#':ident))]
extractLinkURL num b = query (extractLinkURL' num) b
let reftable = concat $ zipWith (\(Chapter _ bs) num ->
query (extractLinkURL num) bs)
chapters' [1..]
let fixInternalReferences :: Inline -> Inline
fixInternalReferences (Link lab ('#':xs, tit)) =
case lookup xs reftable of
Just ys -> Link lab (ys, tit)
Nothing -> Link lab ('#':xs, tit)
fixInternalReferences x = x
-- internal reference IDs change when we chunk the file,
-- so that '#my-header-1' might turn into 'chap004.xhtml#my-header'.
-- this fixes that:
let chapters = map (\(Chapter mbnum bs) ->
Chapter mbnum $ walk fixInternalReferences bs)
chapters'
let chapToEntry :: Int -> Chapter -> Entry
chapToEntry num (Chapter mbnum bs) = mkEntry (showChapter num)
$ renderHtml
$ writeHtml opts'{ writerNumberOffset =
fromMaybe [] mbnum }
$ case bs of
(Header _ _ xs : _) ->
-- remove notes or we get doubled footnotes
Pandoc (setMeta "title" (walk removeNote $ fromList xs)
nullMeta) bs
_ ->
Pandoc nullMeta bs
let chapterEntries = zipWith chapToEntry [1..] chapters
-- incredibly inefficient (TODO):
let containsMathML ent = epub3 &&
"<math" `isInfixOf` (B8.unpack $ fromEntry ent)
let containsSVG ent = epub3 &&
"<svg" `isInfixOf` (B8.unpack $ fromEntry ent)
let props ent = ["mathml" | containsMathML ent] ++ ["svg" | containsSVG ent]
-- contents.opf
let chapterNode ent = unode "item" !
([("id", toId $ eRelativePath ent),
("href", eRelativePath ent),
("media-type", "application/xhtml+xml")]
++ case props ent of
[] -> []
xs -> [("properties", unwords xs)])
$ ()
let chapterRefNode ent = unode "itemref" !
[("idref", toId $ eRelativePath ent)] $ ()
let pictureNode ent = unode "item" !
[("id", toId $ eRelativePath ent),
("href", eRelativePath ent),
("media-type", fromMaybe "application/octet-stream"
$ mediaTypeOf $ eRelativePath ent)] $ ()
let fontNode ent = unode "item" !
[("id", toId $ eRelativePath ent),
("href", eRelativePath ent),
("media-type", fromMaybe "" $ getMimeType $ eRelativePath ent)] $ ()
let plainTitle = case docTitle' meta of
[] -> case epubTitle metadata of
[] -> "UNTITLED"
(x:_) -> titleText x
x -> stringify x
let tocTitle = fromMaybe plainTitle $
metaValueToString <$> lookupMeta "toc-title" meta
let uuid = case epubIdentifier metadata of
(x:_) -> identifierText x -- use first identifier as UUID
[] -> error "epubIdentifier is null" -- shouldn't happen
currentTime <- getCurrentTime
let contentsData = UTF8.fromStringLazy $ ppTopElement $
unode "package" ! [("version", case version of
EPUB2 -> "2.0"
EPUB3 -> "3.0")
,("xmlns","http://www.idpf.org/2007/opf")
,("unique-identifier","epub-id-1")] $
[ metadataElement version metadata currentTime
, unode "manifest" $
[ unode "item" ! [("id","ncx"), ("href","toc.ncx")
,("media-type","application/x-dtbncx+xml")] $ ()
, unode "item" ! [("id","style"), ("href","stylesheet.css")
,("media-type","text/css")] $ ()
, unode "item" ! ([("id","nav")
,("href","nav.xhtml")
,("media-type","application/xhtml+xml")] ++
[("properties","nav") | epub3 ]) $ ()
] ++
map chapterNode (cpgEntry ++ (tpEntry : chapterEntries)) ++
(case cpicEntry of
[] -> []
(x:_) -> [add_attrs
[Attr (unqual "properties") "cover-image" | epub3]
(pictureNode x)]) ++
map pictureNode picEntries ++
map fontNode fontEntries
, unode "spine" ! ([("toc","ncx")] ++ progressionDirection) $
case epubCoverImage metadata of
Nothing -> []
Just _ -> [ unode "itemref" !
[("idref", "cover_xhtml")] $ () ]
++ ((unode "itemref" ! [("idref", "title_page_xhtml")
,("linear",
case lookupMeta "title" meta of
Just _ -> "yes"
Nothing -> "no")] $ ()) :
[unode "itemref" ! [("idref", "nav")] $ ()
| writerTableOfContents opts ] ++
map chapterRefNode chapterEntries)
, unode "guide" $
[ unode "reference" !
[("type","toc"),("title", tocTitle),
("href","nav.xhtml")] $ ()
] ++
[ unode "reference" !
[("type","cover"),("title","Cover"),("href","cover.xhtml")] $ () | epubCoverImage metadata /= Nothing
]
]
let contentsEntry = mkEntry "content.opf" contentsData
-- toc.ncx
let secs = hierarchicalize blocks'
let tocLevel = writerTOCDepth opts
let navPointNode :: (Int -> String -> String -> [Element] -> Element)
-> S.Element -> State Int Element
navPointNode formatter (S.Sec _ nums (ident,_,_) ils children) = do
n <- get
modify (+1)
let showNums :: [Int] -> String
showNums = intercalate "." . map show
let tit' = stringify ils
let tit = if writerNumberSections opts && not (null nums)
then showNums nums ++ " " ++ tit'
else tit'
let src = case lookup ident reftable of
Just x -> x
Nothing -> error (ident ++ " not found in reftable")
let isSec (S.Sec lev _ _ _ _) = lev <= tocLevel
isSec _ = False
let subsecs = filter isSec children
subs <- mapM (navPointNode formatter) subsecs
return $ formatter n tit src subs
navPointNode _ (S.Blk _) = error "navPointNode encountered Blk"
let navMapFormatter :: Int -> String -> String -> [Element] -> Element
navMapFormatter n tit src subs = unode "navPoint" !
[("id", "navPoint-" ++ show n)] $
[ unode "navLabel" $ unode "text" tit
, unode "content" ! [("src", src)] $ ()
] ++ subs
let tpNode = unode "navPoint" ! [("id", "navPoint-0")] $
[ unode "navLabel" $ unode "text" (stringify $ docTitle' meta)
, unode "content" ! [("src","title_page.xhtml")] $ () ]
let tocData = UTF8.fromStringLazy $ ppTopElement $
unode "ncx" ! [("version","2005-1")
,("xmlns","http://www.daisy.org/z3986/2005/ncx/")] $
[ unode "head" $
[ unode "meta" ! [("name","dtb:uid")
,("content", uuid)] $ ()
, unode "meta" ! [("name","dtb:depth")
,("content", "1")] $ ()
, unode "meta" ! [("name","dtb:totalPageCount")
,("content", "0")] $ ()
, unode "meta" ! [("name","dtb:maxPageNumber")
,("content", "0")] $ ()
] ++ case epubCoverImage metadata of
Nothing -> []
Just img -> [unode "meta" ! [("name","cover"),
("content", toId img)] $ ()]
, unode "docTitle" $ unode "text" $ plainTitle
, unode "navMap" $
tpNode : evalState (mapM (navPointNode navMapFormatter) secs) 1
]
let tocEntry = mkEntry "toc.ncx" tocData
let navXhtmlFormatter :: Int -> String -> String -> [Element] -> Element
navXhtmlFormatter n tit src subs = unode "li" !
[("id", "toc-li-" ++ show n)] $
(unode "a" ! [("href",src)]
$ tit)
: case subs of
[] -> []
(_:_) -> [unode "ol" ! [("class","toc")] $ subs]
let navtag = if epub3 then "nav" else "div"
let navBlocks = [RawBlock (Format "html") $ ppElement $
unode navtag ! ([("epub:type","toc") | epub3] ++
[("id","toc")]) $
[ unode "h1" ! [("id","toc-title")] $ tocTitle
, unode "ol" ! [("class","toc")] $ evalState (mapM (navPointNode navXhtmlFormatter) secs) 1]]
let landmarks = if epub3
then [RawBlock (Format "html") $ ppElement $
unode "nav" ! [("epub:type","landmarks")
,("hidden","hidden")] $
[ unode "ol" $
[ unode "li"
[ unode "a" ! [("href", "cover.xhtml")
,("epub:type", "cover")] $
"Cover"] |
epubCoverImage metadata /= Nothing
] ++
[ unode "li"
[ unode "a" ! [("href", "#toc")
,("epub:type", "toc")] $
"Table of contents"
] | writerTableOfContents opts
]
]
]
else []
let navData = renderHtml $ writeHtml opts'
(Pandoc (setMeta "title"
(walk removeNote $ fromList $ docTitle' meta) nullMeta)
(navBlocks ++ landmarks))
let navEntry = mkEntry "nav.xhtml" navData
-- mimetype
let mimetypeEntry = mkEntry "mimetype" $ UTF8.fromStringLazy "application/epub+zip"
-- container.xml
let containerData = UTF8.fromStringLazy $ ppTopElement $
unode "container" ! [("version","1.0")
,("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")] $
unode "rootfiles" $
unode "rootfile" ! [("full-path","content.opf")
,("media-type","application/oebps-package+xml")] $ ()
let containerEntry = mkEntry "META-INF/container.xml" containerData
-- com.apple.ibooks.display-options.xml
let apple = UTF8.fromStringLazy $ ppTopElement $
unode "display_options" $
unode "platform" ! [("name","*")] $
unode "option" ! [("name","specified-fonts")] $ "true"
let appleEntry = mkEntry "META-INF/com.apple.ibooks.display-options.xml" apple
-- stylesheet
stylesheet <- case epubStylesheet metadata of
Just (StylesheetPath fp) -> UTF8.readFile fp
Just (StylesheetContents s) -> return s
Nothing -> UTF8.toString `fmap`
readDataFile (writerUserDataDir opts) "epub.css"
let stylesheetEntry = mkEntry "stylesheet.css" $ UTF8.fromStringLazy stylesheet
-- construct archive
let archive = foldr addEntryToArchive emptyArchive
(mimetypeEntry : containerEntry : appleEntry : stylesheetEntry : tpEntry :
contentsEntry : tocEntry : navEntry :
(picEntries ++ cpicEntry ++ cpgEntry ++ chapterEntries ++ fontEntries))
return $ fromArchive archive
metadataElement :: EPUBVersion -> EPUBMetadata -> UTCTime -> Element
metadataElement version md currentTime =
unode "metadata" ! [("xmlns:dc","http://purl.org/dc/elements/1.1/")
,("xmlns:opf","http://www.idpf.org/2007/opf")] $ mdNodes
where mdNodes = identifierNodes ++ titleNodes ++ dateNodes ++ languageNodes
++ creatorNodes ++ contributorNodes ++ subjectNodes
++ descriptionNodes ++ typeNodes ++ formatNodes
++ publisherNodes ++ sourceNodes ++ relationNodes
++ coverageNodes ++ rightsNodes ++ coverImageNodes
++ modifiedNodes
withIds base f = concat . zipWith f (map (\x -> base ++ ('-' : show x))
([1..] :: [Int]))
identifierNodes = withIds "epub-id" toIdentifierNode $
epubIdentifier md
titleNodes = withIds "epub-title" toTitleNode $ epubTitle md
dateNodes = if version == EPUB2
then withIds "epub-date" toDateNode $ epubDate md
else -- epub3 allows only one dc:date
-- http://www.idpf.org/epub/30/spec/epub30-publications.html#sec-opf-dcdate
case epubDate md of
[] -> []
(x:_) -> [dcNode "date" ! [("id","epub-date")]
$ dateText x]
languageNodes = [dcTag "language" $ epubLanguage md]
creatorNodes = withIds "epub-creator" (toCreatorNode "creator") $
epubCreator md
contributorNodes = withIds "epub-contributor"
(toCreatorNode "contributor") $ epubContributor md
subjectNodes = map (dcTag "subject") $ epubSubject md
descriptionNodes = maybe [] (dcTag' "description") $ epubDescription md
typeNodes = maybe [] (dcTag' "type") $ epubType md
formatNodes = maybe [] (dcTag' "format") $ epubFormat md
publisherNodes = maybe [] (dcTag' "publisher") $ epubPublisher md
sourceNodes = maybe [] (dcTag' "source") $ epubSource md
relationNodes = maybe [] (dcTag' "relation") $ epubRelation md
coverageNodes = maybe [] (dcTag' "coverage") $ epubCoverage md
rightsNodes = maybe [] (dcTag' "rights") $ epubRights md
coverImageNodes = maybe []
(\img -> [unode "meta" ! [("name","cover"),
("content",toId img)] $ ()])
$ epubCoverImage md
modifiedNodes = [ unode "meta" ! [("property", "dcterms:modified")] $
(showDateTimeISO8601 currentTime) | version == EPUB3 ]
dcTag n s = unode ("dc:" ++ n) s
dcTag' n s = [dcTag n s]
toIdentifierNode id' (Identifier txt scheme)
| version == EPUB2 = [dcNode "identifier" !
([("id",id')] ++ maybe [] (\x -> [("opf:scheme", x)]) scheme) $
txt]
| otherwise = [dcNode "identifier" ! [("id",id')] $ txt] ++
maybe [] (\x -> [unode "meta" !
[("refines",'#':id'),("property","identifier-type"),
("scheme","onix:codelist5")] $ x])
(schemeToOnix `fmap` scheme)
toCreatorNode s id' creator
| version == EPUB2 = [dcNode s !
(("id",id') :
maybe [] (\x -> [("opf:file-as",x)]) (creatorFileAs creator) ++
maybe [] (\x -> [("opf:role",x)])
(creatorRole creator >>= toRelator)) $ creatorText creator]
| otherwise = [dcNode s ! [("id",id')] $ creatorText creator] ++
maybe [] (\x -> [unode "meta" !
[("refines",'#':id'),("property","file-as")] $ x])
(creatorFileAs creator) ++
maybe [] (\x -> [unode "meta" !
[("refines",'#':id'),("property","role"),
("scheme","marc:relators")] $ x])
(creatorRole creator >>= toRelator)
toTitleNode id' title
| version == EPUB2 = [dcNode "title" !
(("id",id') :
-- note: EPUB2 doesn't accept opf:title-type
maybe [] (\x -> [("opf:file-as",x)]) (titleFileAs title)) $
titleText title]
| otherwise = [dcNode "title" ! [("id",id')] $ titleText title]
++
maybe [] (\x -> [unode "meta" !
[("refines",'#':id'),("property","file-as")] $ x])
(titleFileAs title) ++
maybe [] (\x -> [unode "meta" !
[("refines",'#':id'),("property","title-type")] $ x])
(titleType title)
toDateNode id' date = [dcNode "date" !
(("id",id') :
maybe [] (\x -> [("opf:event",x)]) (dateEvent date)) $
dateText date]
schemeToOnix "ISBN-10" = "02"
schemeToOnix "GTIN-13" = "03"
schemeToOnix "UPC" = "04"
schemeToOnix "ISMN-10" = "05"
schemeToOnix "DOI" = "06"
schemeToOnix "LCCN" = "13"
schemeToOnix "GTIN-14" = "14"
schemeToOnix "ISBN-13" = "15"
schemeToOnix "Legal deposit number" = "17"
schemeToOnix "URN" = "22"
schemeToOnix "OCLC" = "23"
schemeToOnix "ISMN-13" = "25"
schemeToOnix "ISBN-A" = "26"
schemeToOnix "JP" = "27"
schemeToOnix "OLCC" = "28"
schemeToOnix _ = "01"
showDateTimeISO8601 :: UTCTime -> String
showDateTimeISO8601 = formatTime defaultTimeLocale "%FT%TZ"
transformTag :: WriterOptions
-> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath, entry) media
-> Tag String
-> IO (Tag String)
transformTag opts mediaRef tag@(TagOpen name attr)
| name `elem` ["video", "source", "img", "audio"] &&
lookup "data-external" attr == Nothing = do
let src = fromAttrib "src" tag
let poster = fromAttrib "poster" tag
newsrc <- modifyMediaRef opts mediaRef src
newposter <- modifyMediaRef opts mediaRef poster
let attr' = filter (\(x,_) -> x /= "src" && x /= "poster") attr ++
[("src", newsrc) | not (null newsrc)] ++
[("poster", newposter) | not (null newposter)]
return $ TagOpen name attr'
transformTag _ _ tag = return tag
modifyMediaRef :: WriterOptions
-> IORef [(FilePath, (FilePath, Maybe Entry))]
-> FilePath
-> IO FilePath
modifyMediaRef _ _ "" = return ""
modifyMediaRef opts mediaRef oldsrc = do
media <- readIORef mediaRef
case lookup oldsrc media of
Just (n,_) -> return n
Nothing -> do
res <- fetchItem' (writerMediaBag opts)
(writerSourceURL opts) oldsrc
(new, mbEntry) <-
case res of
Left _ -> do
warn $ "Could not find media `" ++ oldsrc ++ "', skipping..."
return (oldsrc, Nothing)
Right (img,mbMime) -> do
let new = "media/file" ++ show (length media) ++
fromMaybe (takeExtension (takeWhile (/='?') oldsrc))
(('.':) <$> (mbMime >>= extensionFromMimeType))
epochtime <- floor `fmap` getPOSIXTime
let entry = toEntry new epochtime $ B.fromChunks . (:[]) $ img
return (new, Just entry)
modifyIORef mediaRef ( (oldsrc, (new, mbEntry)): )
return new
transformBlock :: WriterOptions
-> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath, entry) media
-> Block
-> IO Block
transformBlock opts mediaRef (RawBlock fmt raw)
| fmt == Format "html" = do
let tags = parseTags raw
tags' <- mapM (transformTag opts mediaRef) tags
return $ RawBlock fmt (renderTags' tags')
transformBlock _ _ b = return b
transformInline :: WriterOptions
-> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath) media
-> Inline
-> IO Inline
transformInline opts mediaRef (Image lab (src,tit)) = do
newsrc <- modifyMediaRef opts mediaRef src
return $ Image lab (newsrc, tit)
transformInline opts mediaRef (x@(Math t m))
| WebTeX url <- writerHTMLMathMethod opts = do
newsrc <- modifyMediaRef opts mediaRef (url ++ urlEncode m)
let mathclass = if t == DisplayMath then "display" else "inline"
return $ Span ("",["math",mathclass],[]) [Image [x] (newsrc, "")]
transformInline opts mediaRef (RawInline fmt raw)
| fmt == Format "html" = do
let tags = parseTags raw
tags' <- mapM (transformTag opts mediaRef) tags
return $ RawInline fmt (renderTags' tags')
transformInline _ _ x = return x
(!) :: Node t => (t -> Element) -> [(String, String)] -> t -> Element
(!) f attrs n = add_attrs (map (\(k,v) -> Attr (unqual k) v) attrs) (f n)
-- | Version of 'ppTopElement' that specifies UTF-8 encoding.
ppTopElement :: Element -> String
ppTopElement = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ++) . unEntity . ppElement
-- unEntity removes numeric entities introduced by ppElement
-- (kindlegen seems to choke on these).
where unEntity [] = ""
unEntity ('&':'#':xs) =
let (ds,ys) = break (==';') xs
rest = drop 1 ys
in case safeRead ('\'':'\\':ds ++ "'") of
Just x -> x : unEntity rest
Nothing -> '&':'#':unEntity xs
unEntity (x:xs) = x : unEntity xs
mediaTypeOf :: FilePath -> Maybe MimeType
mediaTypeOf x =
let mediaPrefixes = ["image", "video", "audio"] in
case getMimeType x of
Just y | any (`isPrefixOf` y) mediaPrefixes -> Just y
_ -> Nothing
-- Returns filename for chapter number.
showChapter :: Int -> String
showChapter = printf "ch%03d.xhtml"
-- Add identifiers to any headers without them.
addIdentifiers :: [Block] -> [Block]
addIdentifiers bs = evalState (mapM go bs) []
where go (Header n (ident,classes,kvs) ils) = do
ids <- get
let ident' = if null ident
then uniqueIdent ils ids
else ident
put $ ident' : ids
return $ Header n (ident',classes,kvs) ils
go x = return x
-- Variant of normalizeDate that allows partial dates: YYYY, YYYY-MM
normalizeDate' :: String -> Maybe String
normalizeDate' xs =
let xs' = trim xs in
case xs' of
[y1,y2,y3,y4] | all isDigit [y1,y2,y3,y4] -> Just xs' -- YYYY
[y1,y2,y3,y4,'-',m1,m2] | all isDigit [y1,y2,y3,y4,m1,m2] -- YYYY-MM
-> Just xs'
_ -> normalizeDate xs'
toRelator :: String -> Maybe String
toRelator x
| x `elem` relators = Just x
| otherwise = lookup (map toLower x) relatorMap
relators :: [String]
relators = map snd relatorMap
relatorMap :: [(String, String)]
relatorMap =
[("abridger", "abr")
,("actor", "act")
,("adapter", "adp")
,("addressee", "rcp")
,("analyst", "anl")
,("animator", "anm")
,("annotator", "ann")
,("appellant", "apl")
,("appellee", "ape")
,("applicant", "app")
,("architect", "arc")
,("arranger", "arr")
,("art copyist", "acp")
,("art director", "adi")
,("artist", "art")
,("artistic director", "ard")
,("assignee", "asg")
,("associated name", "asn")
,("attributed name", "att")
,("auctioneer", "auc")
,("author", "aut")
,("author in quotations or text abstracts", "aqt")
,("author of afterword, colophon, etc.", "aft")
,("author of dialog", "aud")
,("author of introduction, etc.", "aui")
,("autographer", "ato")
,("bibliographic antecedent", "ant")
,("binder", "bnd")
,("binding designer", "bdd")
,("blurb writer", "blw")
,("book designer", "bkd")
,("book producer", "bkp")
,("bookjacket designer", "bjd")
,("bookplate designer", "bpd")
,("bookseller", "bsl")
,("braille embosser", "brl")
,("broadcaster", "brd")
,("calligrapher", "cll")
,("cartographer", "ctg")
,("caster", "cas")
,("censor", "cns")
,("choreographer", "chr")
,("cinematographer", "cng")
,("client", "cli")
,("collection registrar", "cor")
,("collector", "col")
,("collotyper", "clt")
,("colorist", "clr")
,("commentator", "cmm")
,("commentator for written text", "cwt")
,("compiler", "com")
,("complainant", "cpl")
,("complainant-appellant", "cpt")
,("complainant-appellee", "cpe")
,("composer", "cmp")
,("compositor", "cmt")
,("conceptor", "ccp")
,("conductor", "cnd")
,("conservator", "con")
,("consultant", "csl")
,("consultant to a project", "csp")
,("contestant", "cos")
,("contestant-appellant", "cot")
,("contestant-appellee", "coe")
,("contestee", "cts")
,("contestee-appellant", "ctt")
,("contestee-appellee", "cte")
,("contractor", "ctr")
,("contributor", "ctb")
,("copyright claimant", "cpc")
,("copyright holder", "cph")
,("corrector", "crr")
,("correspondent", "crp")
,("costume designer", "cst")
,("court governed", "cou")
,("court reporter", "crt")
,("cover designer", "cov")
,("creator", "cre")
,("curator", "cur")
,("dancer", "dnc")
,("data contributor", "dtc")
,("data manager", "dtm")
,("dedicatee", "dte")
,("dedicator", "dto")
,("defendant", "dfd")
,("defendant-appellant", "dft")
,("defendant-appellee", "dfe")
,("degree granting institution", "dgg")
,("delineator", "dln")
,("depicted", "dpc")
,("depositor", "dpt")
,("designer", "dsr")
,("director", "drt")
,("dissertant", "dis")
,("distribution place", "dbp")
,("distributor", "dst")
,("donor", "dnr")
,("draftsman", "drm")
,("dubious author", "dub")
,("editor", "edt")
,("editor of compilation", "edc")
,("editor of moving image work", "edm")
,("electrician", "elg")
,("electrotyper", "elt")
,("enacting jurisdiction", "enj")
,("engineer", "eng")
,("engraver", "egr")
,("etcher", "etr")
,("event place", "evp")
,("expert", "exp")
,("facsimilist", "fac")
,("field director", "fld")
,("film director", "fmd")
,("film distributor", "fds")
,("film editor", "flm")
,("film producer", "fmp")
,("filmmaker", "fmk")
,("first party", "fpy")
,("forger", "frg")
,("former owner", "fmo")
,("funder", "fnd")
,("geographic information specialist", "gis")
,("honoree", "hnr")
,("host", "hst")
,("host institution", "his")
,("illuminator", "ilu")
,("illustrator", "ill")
,("inscriber", "ins")
,("instrumentalist", "itr")
,("interviewee", "ive")
,("interviewer", "ivr")
,("inventor", "inv")
,("issuing body", "isb")
,("judge", "jud")
,("jurisdiction governed", "jug")
,("laboratory", "lbr")
,("laboratory director", "ldr")
,("landscape architect", "lsa")
,("lead", "led")
,("lender", "len")
,("libelant", "lil")
,("libelant-appellant", "lit")
,("libelant-appellee", "lie")
,("libelee", "lel")
,("libelee-appellant", "let")
,("libelee-appellee", "lee")
,("librettist", "lbt")
,("licensee", "lse")
,("licensor", "lso")
,("lighting designer", "lgd")
,("lithographer", "ltg")
,("lyricist", "lyr")
,("manufacture place", "mfp")
,("manufacturer", "mfr")
,("marbler", "mrb")
,("markup editor", "mrk")
,("metadata contact", "mdc")
,("metal-engraver", "mte")
,("moderator", "mod")
,("monitor", "mon")
,("music copyist", "mcp")
,("musical director", "msd")
,("musician", "mus")
,("narrator", "nrt")
,("onscreen presenter", "osp")
,("opponent", "opn")
,("organizer of meeting", "orm")
,("originator", "org")
,("other", "oth")
,("owner", "own")
,("panelist", "pan")
,("papermaker", "ppm")
,("patent applicant", "pta")
,("patent holder", "pth")
,("patron", "pat")
,("performer", "prf")
,("permitting agency", "pma")
,("photographer", "pht")
,("plaintiff", "ptf")
,("plaintiff-appellant", "ptt")
,("plaintiff-appellee", "pte")
,("platemaker", "plt")
,("praeses", "pra")
,("presenter", "pre")
,("printer", "prt")
,("printer of plates", "pop")
,("printmaker", "prm")
,("process contact", "prc")
,("producer", "pro")
,("production company", "prn")
,("production designer", "prs")
,("production manager", "pmn")
,("production personnel", "prd")
,("production place", "prp")
,("programmer", "prg")
,("project director", "pdr")
,("proofreader", "pfr")
,("provider", "prv")
,("publication place", "pup")
,("publisher", "pbl")
,("publishing director", "pbd")
,("puppeteer", "ppt")
,("radio director", "rdd")
,("radio producer", "rpc")
,("recording engineer", "rce")
,("recordist", "rcd")
,("redaktor", "red")
,("renderer", "ren")
,("reporter", "rpt")
,("repository", "rps")
,("research team head", "rth")
,("research team member", "rtm")
,("researcher", "res")
,("respondent", "rsp")
,("respondent-appellant", "rst")
,("respondent-appellee", "rse")
,("responsible party", "rpy")
,("restager", "rsg")
,("restorationist", "rsr")
,("reviewer", "rev")
,("rubricator", "rbr")
,("scenarist", "sce")
,("scientific advisor", "sad")
,("screenwriter", "aus")
,("scribe", "scr")
,("sculptor", "scl")
,("second party", "spy")
,("secretary", "sec")
,("seller", "sll")
,("set designer", "std")
,("setting", "stg")
,("signer", "sgn")
,("singer", "sng")
,("sound designer", "sds")
,("speaker", "spk")
,("sponsor", "spn")
,("stage director", "sgd")
,("stage manager", "stm")
,("standards body", "stn")
,("stereotyper", "str")
,("storyteller", "stl")
,("supporting host", "sht")
,("surveyor", "srv")
,("teacher", "tch")
,("technical director", "tcd")
,("television director", "tld")
,("television producer", "tlp")
,("thesis advisor", "ths")
,("transcriber", "trc")
,("translator", "trl")
,("type designer", "tyd")
,("typographer", "tyg")
,("university place", "uvp")
,("videographer", "vdg")
,("witness", "wit")
,("wood engraver", "wde")
,("woodcutter", "wdc")
,("writer of accompanying material", "wam")
,("writer of added commentary", "wac")
,("writer of added lyrics", "wal")
,("writer of added text", "wat")
]
docTitle' :: Meta -> [Inline]
docTitle' meta = fromMaybe [] $ go <$> lookupMeta "title" meta
where go (MetaString s) = [Str s]
go (MetaInlines xs) = xs
go (MetaBlocks [Para xs]) = xs
go (MetaBlocks [Plain xs]) = xs
go (MetaMap m) =
case M.lookup "type" m of
Just x | stringify x == "main" ->
maybe [] go $ M.lookup "text" m
_ -> []
go (MetaList xs) = concatMap go xs
go _ = []
| alexvong1995/pandoc | src/Text/Pandoc/Writers/EPUB.hs | gpl-2.0 | 53,512 | 0 | 27 | 19,306 | 14,685 | 8,001 | 6,684 | 1,078 | 38 |
{-# OPTIONS -O2 -Wall #-}
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-}
module Data.Store.Rev.Version
(VersionData, depth, parent, changes,
Version, versionIRef, versionData,
makeInitialVersion, newVersion, mostRecentAncestor,
walkUp, walkDown, versionsBetween)
where
import Control.Monad (liftM, liftM2, join)
import Data.Binary (Binary(..))
import Data.Store.IRef (IRef)
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import Data.Store.Rev.Change (Change(..), Key, Value)
import Data.Derive.Binary(makeBinary)
import Data.DeriveTH(derive)
newtype Version = Version { versionIRef :: IRef VersionData }
deriving (Eq, Ord, Read, Show, Binary)
data VersionData = VersionData {
depth :: Int,
parent :: Maybe Version,
changes :: [Change]
}
deriving (Eq, Ord, Read, Show)
$(derive makeBinary ''VersionData)
makeInitialVersion :: Monad m => [(Key, Value)] -> Transaction t m Version
makeInitialVersion initialValues = liftM Version . Transaction.newIRef . VersionData 0 Nothing $ map makeChange initialValues
where
makeChange (key, value) = Change key Nothing (Just value)
versionData :: Monad m => Version -> Transaction t m VersionData
versionData = Transaction.readIRef . versionIRef
newVersion :: Monad m => Version -> [Change] -> Transaction t m Version
newVersion version newChanges = do
parentDepth <- liftM depth . versionData $ version
liftM Version .
Transaction.newIRef .
VersionData (parentDepth+1) (Just version) $
newChanges
mostRecentAncestor :: Monad m => Version -> Version -> Transaction t m Version
mostRecentAncestor aVersion bVersion
| aVersion == bVersion = return aVersion
| otherwise = do
VersionData aDepth aMbParentRef _aChanges <- versionData aVersion
VersionData bDepth bMbParentRef _bChanges <- versionData bVersion
case compare aDepth bDepth of
LT -> (aVersion `mostRecentAncestor`) =<< upToDepth aDepth bVersion
GT -> (`mostRecentAncestor` bVersion) =<< upToDepth bDepth aVersion
EQ -> if aDepth == 0
then fail "Two versions without common ancestor given"
else join $ liftM2 mostRecentAncestor (getParent aMbParentRef) (getParent bMbParentRef)
where
upToDepth depthToReach version = do
VersionData curDepth curMbParentRef _curChanges <- versionData version
if curDepth > depthToReach
then upToDepth depthToReach =<< getParent curMbParentRef
else return version
getParent = maybe (fail "Non-0 depth must have a parent") return
walkUp :: Monad m => (VersionData -> Transaction t m ()) -> Version -> Version -> Transaction t m ()
walkUp onVersion topRef bottomRef
| bottomRef == topRef = return ()
| otherwise = do
versionD <- versionData bottomRef
onVersion versionD
maybe (fail "Invalid path given, hit top") (walkUp onVersion topRef) $
parent versionD
-- We can't directly walkDown (we don't have references pointing
-- downwards... But we can generate a list of versions by walking up
-- and accumulating a reverse list)
versionsBetween :: Monad m => Version -> Version -> Transaction t m [VersionData]
versionsBetween topRef = accumulateWalkUp []
where
accumulateWalkUp vs curRef
| topRef == curRef = return vs
| otherwise = do
versionD <- versionData curRef
maybe (fail "Invalid path given, hit top") (accumulateWalkUp (versionD:vs)) $
parent versionD
-- Implement in terms of versionsBetween
walkDown :: Monad m => (VersionData -> Transaction t m ()) -> Version -> Version -> Transaction t m ()
walkDown onVersion topRef bottomRef =
mapM_ onVersion =<< versionsBetween topRef bottomRef
| alonho/bottle | src/Data/Store/Rev/Version.hs | gpl-3.0 | 3,821 | 0 | 15 | 814 | 1,078 | 552 | 526 | 72 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElasticBeanstalk.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.ElasticBeanstalk.Types.Sum where
import Network.AWS.Prelude
data ConfigurationDeploymentStatus
= Deployed
| Failed
| Pending
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ConfigurationDeploymentStatus where
parser = takeLowerText >>= \case
"deployed" -> pure Deployed
"failed" -> pure Failed
"pending" -> pure Pending
e -> fromTextError $ "Failure parsing ConfigurationDeploymentStatus from value: '" <> e
<> "'. Accepted values: deployed, failed, pending"
instance ToText ConfigurationDeploymentStatus where
toText = \case
Deployed -> "deployed"
Failed -> "failed"
Pending -> "pending"
instance Hashable ConfigurationDeploymentStatus
instance ToByteString ConfigurationDeploymentStatus
instance ToQuery ConfigurationDeploymentStatus
instance ToHeader ConfigurationDeploymentStatus
instance FromXML ConfigurationDeploymentStatus where
parseXML = parseXMLText "ConfigurationDeploymentStatus"
data ConfigurationOptionValueType
= List
| Scalar
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ConfigurationOptionValueType where
parser = takeLowerText >>= \case
"list" -> pure List
"scalar" -> pure Scalar
e -> fromTextError $ "Failure parsing ConfigurationOptionValueType from value: '" <> e
<> "'. Accepted values: List, Scalar"
instance ToText ConfigurationOptionValueType where
toText = \case
List -> "List"
Scalar -> "Scalar"
instance Hashable ConfigurationOptionValueType
instance ToByteString ConfigurationOptionValueType
instance ToQuery ConfigurationOptionValueType
instance ToHeader ConfigurationOptionValueType
instance FromXML ConfigurationOptionValueType where
parseXML = parseXMLText "ConfigurationOptionValueType"
data EnvironmentHealth
= Green
| Grey
| Red
| Yellow
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EnvironmentHealth where
parser = takeLowerText >>= \case
"green" -> pure Green
"grey" -> pure Grey
"red" -> pure Red
"yellow" -> pure Yellow
e -> fromTextError $ "Failure parsing EnvironmentHealth from value: '" <> e
<> "'. Accepted values: Green, Grey, Red, Yellow"
instance ToText EnvironmentHealth where
toText = \case
Green -> "Green"
Grey -> "Grey"
Red -> "Red"
Yellow -> "Yellow"
instance Hashable EnvironmentHealth
instance ToByteString EnvironmentHealth
instance ToQuery EnvironmentHealth
instance ToHeader EnvironmentHealth
instance FromXML EnvironmentHealth where
parseXML = parseXMLText "EnvironmentHealth"
data EnvironmentHealthAttribute
= EHAAll
| EHAApplicationMetrics
| EHACauses
| EHAColor
| EHAHealthStatus
| EHAInstancesHealth
| EHARefreshedAt
| EHAStatus
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EnvironmentHealthAttribute where
parser = takeLowerText >>= \case
"all" -> pure EHAAll
"applicationmetrics" -> pure EHAApplicationMetrics
"causes" -> pure EHACauses
"color" -> pure EHAColor
"healthstatus" -> pure EHAHealthStatus
"instanceshealth" -> pure EHAInstancesHealth
"refreshedat" -> pure EHARefreshedAt
"status" -> pure EHAStatus
e -> fromTextError $ "Failure parsing EnvironmentHealthAttribute from value: '" <> e
<> "'. Accepted values: All, ApplicationMetrics, Causes, Color, HealthStatus, InstancesHealth, RefreshedAt, Status"
instance ToText EnvironmentHealthAttribute where
toText = \case
EHAAll -> "All"
EHAApplicationMetrics -> "ApplicationMetrics"
EHACauses -> "Causes"
EHAColor -> "Color"
EHAHealthStatus -> "HealthStatus"
EHAInstancesHealth -> "InstancesHealth"
EHARefreshedAt -> "RefreshedAt"
EHAStatus -> "Status"
instance Hashable EnvironmentHealthAttribute
instance ToByteString EnvironmentHealthAttribute
instance ToQuery EnvironmentHealthAttribute
instance ToHeader EnvironmentHealthAttribute
data EnvironmentHealthStatus
= EHSDegraded
| EHSInfo
| EHSNoData
| EHSOK
| EHSPending
| EHSSevere
| EHSUnknown
| EHSWarning
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EnvironmentHealthStatus where
parser = takeLowerText >>= \case
"degraded" -> pure EHSDegraded
"info" -> pure EHSInfo
"nodata" -> pure EHSNoData
"ok" -> pure EHSOK
"pending" -> pure EHSPending
"severe" -> pure EHSSevere
"unknown" -> pure EHSUnknown
"warning" -> pure EHSWarning
e -> fromTextError $ "Failure parsing EnvironmentHealthStatus from value: '" <> e
<> "'. Accepted values: Degraded, Info, NoData, Ok, Pending, Severe, Unknown, Warning"
instance ToText EnvironmentHealthStatus where
toText = \case
EHSDegraded -> "Degraded"
EHSInfo -> "Info"
EHSNoData -> "NoData"
EHSOK -> "Ok"
EHSPending -> "Pending"
EHSSevere -> "Severe"
EHSUnknown -> "Unknown"
EHSWarning -> "Warning"
instance Hashable EnvironmentHealthStatus
instance ToByteString EnvironmentHealthStatus
instance ToQuery EnvironmentHealthStatus
instance ToHeader EnvironmentHealthStatus
instance FromXML EnvironmentHealthStatus where
parseXML = parseXMLText "EnvironmentHealthStatus"
data EnvironmentInfoType
= Bundle
| Tail
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EnvironmentInfoType where
parser = takeLowerText >>= \case
"bundle" -> pure Bundle
"tail" -> pure Tail
e -> fromTextError $ "Failure parsing EnvironmentInfoType from value: '" <> e
<> "'. Accepted values: bundle, tail"
instance ToText EnvironmentInfoType where
toText = \case
Bundle -> "bundle"
Tail -> "tail"
instance Hashable EnvironmentInfoType
instance ToByteString EnvironmentInfoType
instance ToQuery EnvironmentInfoType
instance ToHeader EnvironmentInfoType
instance FromXML EnvironmentInfoType where
parseXML = parseXMLText "EnvironmentInfoType"
data EnvironmentStatus
= Launching
| Ready
| Terminated
| Terminating
| Updating
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EnvironmentStatus where
parser = takeLowerText >>= \case
"launching" -> pure Launching
"ready" -> pure Ready
"terminated" -> pure Terminated
"terminating" -> pure Terminating
"updating" -> pure Updating
e -> fromTextError $ "Failure parsing EnvironmentStatus from value: '" <> e
<> "'. Accepted values: Launching, Ready, Terminated, Terminating, Updating"
instance ToText EnvironmentStatus where
toText = \case
Launching -> "Launching"
Ready -> "Ready"
Terminated -> "Terminated"
Terminating -> "Terminating"
Updating -> "Updating"
instance Hashable EnvironmentStatus
instance ToByteString EnvironmentStatus
instance ToQuery EnvironmentStatus
instance ToHeader EnvironmentStatus
instance FromXML EnvironmentStatus where
parseXML = parseXMLText "EnvironmentStatus"
data EventSeverity
= LevelDebug
| LevelError'
| LevelFatal
| LevelInfo
| LevelTrace
| LevelWarn
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EventSeverity where
parser = takeLowerText >>= \case
"debug" -> pure LevelDebug
"error" -> pure LevelError'
"fatal" -> pure LevelFatal
"info" -> pure LevelInfo
"trace" -> pure LevelTrace
"warn" -> pure LevelWarn
e -> fromTextError $ "Failure parsing EventSeverity from value: '" <> e
<> "'. Accepted values: DEBUG, ERROR, FATAL, INFO, TRACE, WARN"
instance ToText EventSeverity where
toText = \case
LevelDebug -> "DEBUG"
LevelError' -> "ERROR"
LevelFatal -> "FATAL"
LevelInfo -> "INFO"
LevelTrace -> "TRACE"
LevelWarn -> "WARN"
instance Hashable EventSeverity
instance ToByteString EventSeverity
instance ToQuery EventSeverity
instance ToHeader EventSeverity
instance FromXML EventSeverity where
parseXML = parseXMLText "EventSeverity"
data InstancesHealthAttribute
= All
| ApplicationMetrics
| Causes
| Color
| HealthStatus
| LaunchedAt
| RefreshedAt
| System
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText InstancesHealthAttribute where
parser = takeLowerText >>= \case
"all" -> pure All
"applicationmetrics" -> pure ApplicationMetrics
"causes" -> pure Causes
"color" -> pure Color
"healthstatus" -> pure HealthStatus
"launchedat" -> pure LaunchedAt
"refreshedat" -> pure RefreshedAt
"system" -> pure System
e -> fromTextError $ "Failure parsing InstancesHealthAttribute from value: '" <> e
<> "'. Accepted values: All, ApplicationMetrics, Causes, Color, HealthStatus, LaunchedAt, RefreshedAt, System"
instance ToText InstancesHealthAttribute where
toText = \case
All -> "All"
ApplicationMetrics -> "ApplicationMetrics"
Causes -> "Causes"
Color -> "Color"
HealthStatus -> "HealthStatus"
LaunchedAt -> "LaunchedAt"
RefreshedAt -> "RefreshedAt"
System -> "System"
instance Hashable InstancesHealthAttribute
instance ToByteString InstancesHealthAttribute
instance ToQuery InstancesHealthAttribute
instance ToHeader InstancesHealthAttribute
data ValidationSeverity
= Error'
| Warning
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ValidationSeverity where
parser = takeLowerText >>= \case
"error" -> pure Error'
"warning" -> pure Warning
e -> fromTextError $ "Failure parsing ValidationSeverity from value: '" <> e
<> "'. Accepted values: error, warning"
instance ToText ValidationSeverity where
toText = \case
Error' -> "error"
Warning -> "warning"
instance Hashable ValidationSeverity
instance ToByteString ValidationSeverity
instance ToQuery ValidationSeverity
instance ToHeader ValidationSeverity
instance FromXML ValidationSeverity where
parseXML = parseXMLText "ValidationSeverity"
| fmapfmapfmap/amazonka | amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/Types/Sum.hs | mpl-2.0 | 11,167 | 0 | 12 | 2,619 | 2,211 | 1,111 | 1,100 | 287 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | @SPECIALIZE@ pragma declarations for RGBA images.
module Vision.Image.RGBA.Specialize () where
import Data.Int
import Vision.Histogram (Histogram, histogram, histogram2D)
import Vision.Image.RGBA.Type (RGBA)
import Vision.Image.Transform (
InterpolMethod, crop, resize, horizontalFlip, verticalFlip
)
import Vision.Primitive (DIM4, DIM6, Rect, Size)
{-# SPECIALIZE histogram :: Maybe DIM4 -> RGBA -> Histogram DIM4 Int32
, Maybe DIM4 -> RGBA -> Histogram DIM4 Double
, Maybe DIM4 -> RGBA -> Histogram DIM4 Float #-}
{-# SPECIALIZE histogram2D :: DIM6 -> RGBA -> Histogram DIM6 Int32
, DIM6 -> RGBA -> Histogram DIM6 Double
, DIM6 -> RGBA -> Histogram DIM6 Float #-}
{-# SPECIALIZE crop :: Rect -> RGBA -> RGBA #-}
{-# SPECIALIZE resize :: InterpolMethod -> Size -> RGBA -> RGBA #-}
{-# SPECIALIZE horizontalFlip :: RGBA -> RGBA #-}
{-# SPECIALIZE verticalFlip :: RGBA -> RGBA #-}
| RaphaelJ/friday | src/Vision/Image/RGBA/Specialize.hs | lgpl-3.0 | 1,069 | 0 | 5 | 284 | 94 | 64 | 30 | 18 | 0 |
-- |
-- DNA is a data flow DSL aimed at expressing data movement and initiation of
-- computational kernels for numerical calculations. We use the "actor/channel"
-- paradigm, which allows for a descriptive approach that separates definition
-- from execution strategy. Our target is data intensive high performance computing
-- applications that employ hierarchical cluster scheduling techniques. Furthermore,
-- we provide infrastructure for detailed profiling and high availability, allowing
-- recovery for certain types of failures.
--
-- DNA is presently implemented as an embedded monadic DSL on top of the
-- well-established distributed programming framework "Cloud Haskell".
-- This document describes the structure of the language at a high level,
-- followed by detailed specifications and use cases for the introduced
-- primitives. We will give examples at several points.
--
--
-- === High level structure
--
-- DNA programs are composed of actors and channels. DNA provides means for
-- defining an abstract data flow graph using programming language primitives.
--
-- Actors are executed concurrently, don't share state and can only communicate
-- using a restricted message passing scheme.
--
-- Every actor can receive either one or many inputs of the same type and produce
-- either one or multiple outputs. This depends on the type of the actor: For example,
-- a single 'Actor' will only ever accept one input parameter and produce one
-- result. On the other hand, a group of 'Actor's will produce an unordered set of
-- values of same type. Finally, a 'CollectActor' receives a group of values
-- while producing a single result. In general, actors have no knowledge where
-- their input parameters come from or where result will be sent, these connections
-- will be made from the outside.
--
-- Actors are spawned hierarchically, so every actor but the first will be created
-- by a parent actor. Communication is forced to flow along these hierarchies:
-- Both inputs and results can only be sent to and received from either the parent
-- actor or sibling actors on the same level.
--
-- Furthermore, DNA offers the possibility to spawn /groups/ of actors. Every actor
-- in a group will run the same code, but using different input parameters. To
-- distinguish actors in a group, they get assigned ranks from /0/ to /N-1/.
-- Conceptually, a group of actors is treated as single actor which runs on
-- several execution elements simultaneously.
--
-- To illustrate this, here is example of distributed dot product. We assume that
-- 'ddpComputeVector', 'ddpReadVector' and 'splitSlice' are already defined:
--
-- > -- Calculate dot product of slice of full vector
-- > ddpProductSlice = actor $ \(fullSlice) -> duration "vector slice" $ do
-- > -- Calculate offsets
-- > slices <- scatterSlice <$> groupSize
-- > slice <- (slices !!) <$> rank
-- > -- First we need to generate files on tmpfs
-- > fname <- duration "generate" $ eval ddpGenerateVector n
-- > -- Start local processes
-- > shellVA <- startActor (N 0) $
-- > useLocal >> return $(mkStaticClosure 'ddpComputeVector)
-- > shellVB <- startActor (N 0) $
-- > useLocal >> return $(mkStaticClosure 'ddpReadVector)
-- > -- Connect actors
-- > sendParam slice shellVA
-- > sendParam (fname, Slice 0 n) shellVB
-- > futVA <- delay Local shellVA
-- > futVB <- delay Local shellVB
-- > -- Await results
-- > va <- duration "receive compute" $ await futVA
-- > vb <- duration "receive read" $ await futVB
-- > -- Clean up, compute sum
-- > kernel "compute sum" [FloatHint 0 (2 * fromIntegral n)] $
-- > return (S.sum $ S.zipWith (*) va vb :: Double)
-- >
-- > -- Calculate dot product of full vector
-- > ddpDotProduct :: Actor Int64 Double
-- > ddpDotProduct = actor $ \size -> do
-- > -- Chunk & send out
-- > shell <- startGroup (Frac 1) (NNodes 1) $ do
-- > useLocal
-- > return $(mkStaticClosure 'ddpProductSlice)
-- > broadcast (Slice 0 size) shell
-- > -- Collect results
-- > partials <- delayGroup shell
-- > duration "collecting vectors" $ gather partials (+) 0
-- >
-- > main :: IO ()
-- > main = dnaRun (...) $
-- > liftIO . print =<< eval ddpDotProduct (400*1000*1000)
--
-- This generates an actor tree of the following shape:
--
-- @
-- ddpDotProduct
-- |
-- ddpProductSlice
-- / \\
-- ddpComputeVector ddpReadVector
-- @
--
-- Here 'ddpDotProduct' is a single actor, which takes exactly one
-- parameter 'size' and produces exactly the sum as its output. On the
-- other hand, 'ddpProductSlice' is an actor group, which sums up a
-- portion of the full dot-product. Each actor in group spawns two
-- child actors: 'ddpComputeVector' and 'ddpReadVector' are two child
-- actors, which for our example are supposed to generate or read the
-- requested vector slice from the hard desk, respectively.
--
--
-- === Scheduling data flow programs for execution.
--
-- Scheduling, spawning and generation of the runtime data flow graph are handled
-- separately. The starting point for scheduling is the cluster architecture
-- descriptor, which describes the resources available to the program.
--
-- For DNA, we are using the following simple algorithm: First a
-- control actor starts the program. It's actor which passed to
-- 'runDna' as parameter. This actor will be assigned exclusively all
-- resources available to the program, which it can then in turn
-- allocate to it spawn child actors. When a child actor finishes
-- execution (either normally or abnormally), its resources are
-- returned to parent actor's resource pool and can be reused.
--
--
-- === High Availability
--
-- We must account for the fact that every actor could fail at any point. This could
-- not only happen because of hardware failures, but also due to programming errors.
-- In order to maintain the liveness of the data flow network, we must detect such
-- failures, no matter the concrete reason. In the worst case, our only choice is to
-- simply terminate all child processes and propagate the error to actors which depend
-- on the failed actor. This approach is obviously problematic for achieving
-- fault tolerance since we always have a single point of failure.
--
-- To improve stability, we need to make use of special cases. For
-- example, let us assume that a single actor instance in large group
-- fails. Then in some case it makes sense to simply ignore the
-- failure and discard the partial result. This is the \"failout\"
-- model. To use these semantics in the DNA program, all we need to do
-- is to specify 'failout' when spawning the actor with
-- 'startGroup'. To make use of failout example above should be changed to:
--
-- > ...
-- > shell <- startGroup (Frac 1) (NNodes 1) $ do
-- > useLocal
-- > failout
-- > return $(mkStaticClosure 'ddpProductSlice)
-- > ...
--
-- Another important recovery technique is restarting failed
-- processes. This obviously loses the current state of the restarted
-- process, so any accumulated data is lost. In the current design, we
-- only support this approach for 'CollectActor's. Similarly only
-- change to program is addition of 'respawnOnFail' to parameters of
-- actors.
--
--
--
-- === Profiling
--
-- For maintaing a robust system performance, we track
-- the performance of all actors and channels. This should allow us
-- to assess exactly how performance is shaped by not only scheduling
-- and resource allocation, but also performance of individual software
-- and hardware components. For example, we might decide
-- to change the scheduling with the goal of eliminating idle times,
-- optimise kernels better or decide to run a kernel on more suitable
-- computation hardware were available.
--
-- However, in order to facilitate making informed decisions about such changes,
-- it is not only important to collect raw performance numbers such as
-- time spent or memory consumed. For understanding the performance of
-- the whole system we need to put our measurements into context. This
-- means that we should associate them from the ground up with the
-- data flow structure of the program.
--
-- Our approach is therefore to implement profiling as an integral
-- service of the DNA runtime. The generated profile will automatically
-- track the overall performance of the system, capturing timings of all
-- involved actors and channels. Furthermore, wherever possible the data
-- flow program should contribute extra information about its activity,
-- such as number of floating point operations expected or
-- amount of raw data transferred. In the end, we will use the key
-- performance metrics derived from these values in order to visualise the
-- whole system performance in a way that will hopefully allow for
-- painless optimisation of the whole system.
module DNA (
-- * DNA monad
DNA
, dnaRun
-- ** Groups of actors
-- |
-- Actor could run in groups. These groups are treated as single
-- logical actor. Each actor in group is assigned rank from /0/
-- to /N-1/ where /N/ is group size. For uniformity single
-- actors are treated as members of group of size 1. Both group
-- size and rank could be accessed using 'rank' and 'groupSize'
, rank
, groupSize
-- ** Logging and profiling
-- |
-- DNA programs write logs in GHC's eventlog format for
-- recording execution progress and performance monitoring. Logs
-- are written in following locations:
-- @~\/_dna\/logs\/PID-u\/{N}\/program-name.eventlog@ if program
-- was started using UNIX startup or
-- @~\/_dna\/logs\/SLURM_JOB_ID-s\/{N}\/program-name.eventlog@
-- if it was started by SLURM (see 'runDna' for detail of
-- starting DNA program). They're stored in GHC's eventlog
-- format.
, logMessage
, duration
-- * Kernels
, Kern
, kernel
, unboundKernel
, ProfileHint(..)
, floatHint, memHint, ioHint, haskellHint, cudaHint
-- * Actors
, Actor
, actor
, CollectActor
, collectActor
-- * Spawning
-- |
-- Actors could be spawned using start* functions. They spawn
-- new actors which are executed asynchronously and usually on
-- remote nodes. Nodes for newly spawned actor(s) are taken from
-- pool of free nodes. If there's not enough nodes it's runtime
-- error. eval* functions allows to execute actor synchronously.
-- ** Eval
, eval
, evalClosure
-- ** Spawn parameters
, Spawn
, useLocal
, failout
, respawnOnFail
, debugFlags
, DebugFlag(..)
-- ** Resources
-- |
-- These data types are used for describing how much resources
-- should be allocated to nodes and are passed as parameters to
-- start* functions.
, Res(..)
, ResGroup(..)
, Location(..)
, availableNodes
, waitForResources
-- ** Function to spawn new actors
-- |
-- All functions for starting new actors following same
-- pattern. They take parameter which describe how many nodes
-- should be allocated to actor(s) and 'Closure' to actor to be
-- spawned. They all return handle to running actor (see
-- documentation of 'Shell' for details).
--
-- Here is example of spawning single actor on remote node. To
-- be able to create 'Closure' to execute actor on remote node
-- we need to make it \"remotable\". For details of 'remotable'
-- semantics refer to distributed-process documentation,. (This
-- could change in future version of @distributed-process@ when
-- it start use StaticPointers language extension)
--
-- > someActor :: Actor Int Int
-- > someActor = actor $ \i -> ...
-- >
-- > remotable [ 'someActor ]
--
-- Finally we start actor and allocate 3 nodes to it:
--
-- > do a <- startActor (N 3) (return $(mkStaticClosure 'someActor))
-- > ...
--
-- In next example we start group of actors, use half of
-- available nodes and local node in addition to that. These
-- nodes will be evenly divided between 4 actors:
--
-- > do a <- startGroup (Frac 0.5) (NWorkers 4) $ do
-- > useLocal
-- > return $(mkStaticClosure 'someActor)
-- > ...
--
-- All other start* functions share same pattern and could be
-- used in similar manner.
, startActor
, startGroup
-- , startGroupN
, startCollector
, startCollectorTree
, startCollectorTreeGroup
-- ** Shell
, Shell
, Val
, Grp
, Scatter
-- * Connecting actors
-- | Each actor must be connected to exactly one destination and
-- consequently could only receive input from a single
-- source. Trying to connect an actor twice will result in a
-- runtime error. Functions 'sendParam', 'broadcast',
-- 'distributeWork', 'connect', 'delay', and 'delayGroup' count
-- to this.
, sendParam
, broadcast
, distributeWork
, connect
-- ** File channels.
, FileChan
, createFileChan
-- * Promises
, Promise
, delay
, await
, Group
, delayGroup
, gather
-- * Reexports
, MonadIO(..)
, remotable
, mkStaticClosure
) where
import Control.Monad.IO.Class
import Control.Distributed.Process.Closure (mkStaticClosure,remotable)
import DNA.DSL
import DNA.Types
import DNA.Run
import DNA.Logging
| SKA-ScienceDataProcessor/RC | MS5/dna/core/DNA.hs | apache-2.0 | 13,704 | 0 | 5 | 3,153 | 506 | 427 | 79 | 59 | 0 |
-- | Delay a thread for n seconds or minutes.
module Control.Concurrent.Delay
(delaySeconds
,delayMinutes)
where
import Control.Concurrent
-- | Delay the current thread for at least n seconds.
delaySeconds :: Integer -> IO ()
delaySeconds 0 = return ()
delaySeconds n = do threadDelay (1000 * 1000); delaySeconds (n-1)
-- | Delay the current thread for at least n minutes.
delayMinutes :: Integer -> IO ()
delayMinutes = delaySeconds . (*60)
| yuvallanger/threepenny-gui | src/Control/Concurrent/Delay.hs | bsd-3-clause | 452 | 0 | 9 | 81 | 112 | 61 | 51 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Stack.Types.TemplateNameSpec where
import Stack.Types.TemplateName
import Path.Internal
import System.Info (os)
import Test.Hspec
spec :: Spec
spec =
describe "TemplateName" $ do
describe "parseTemplateNameFromString" $ do
let pathOf s = either error templatePath (parseTemplateNameFromString s)
it "parses out the TemplatePath" $ do
pathOf "github:user/name" `shouldBe` RepoPath (RepoTemplatePath Github "user" "name.hsfiles")
pathOf "bitbucket:user/name" `shouldBe` RepoPath (RepoTemplatePath Bitbucket "user" "name.hsfiles")
pathOf "gitlab:user/name" `shouldBe` RepoPath (RepoTemplatePath Gitlab "user" "name.hsfiles")
pathOf "http://www.com/file" `shouldBe` UrlPath "http://www.com/file"
pathOf "https://www.com/file" `shouldBe` UrlPath "https://www.com/file"
pathOf "name" `shouldBe` RelPath "name.hsfiles" (Path "name.hsfiles")
pathOf "name.hsfile" `shouldBe` RelPath "name.hsfile.hsfiles" (Path "name.hsfile.hsfiles")
pathOf "name.hsfiles" `shouldBe` RelPath "name.hsfiles" (Path "name.hsfiles")
pathOf "" `shouldBe` RelPath ".hsfiles" (Path ".hsfiles")
if os == "mingw32"
then do
pathOf "//home/file" `shouldBe` AbsPath (Path "\\\\home\\file.hsfiles")
pathOf "/home/file" `shouldBe` RelPath "/home/file.hsfiles" (Path "\\home\\file.hsfiles")
pathOf "/home/file.hsfiles" `shouldBe` RelPath "/home/file.hsfiles" (Path "\\home\\file.hsfiles")
pathOf "c:\\home\\file" `shouldBe` AbsPath (Path "C:\\home\\file.hsfiles")
pathOf "with/slash" `shouldBe` RelPath "with/slash.hsfiles" (Path "with\\slash.hsfiles")
let colonAction =
do
return $! pathOf "with:colon"
colonAction `shouldThrow` anyErrorCall
else do
pathOf "//home/file" `shouldBe` AbsPath (Path "/home/file.hsfiles")
pathOf "/home/file" `shouldBe` AbsPath (Path "/home/file.hsfiles")
pathOf "/home/file.hsfiles" `shouldBe` AbsPath (Path "/home/file.hsfiles")
pathOf "c:\\home\\file" `shouldBe` RelPath "c:\\home\\file.hsfiles" (Path "c:\\home\\file.hsfiles")
pathOf "with/slash" `shouldBe` RelPath "with/slash.hsfiles" (Path "with/slash.hsfiles")
pathOf "with:colon" `shouldBe` RelPath "with:colon.hsfiles" (Path "with:colon.hsfiles")
| juhp/stack | src/test/Stack/Types/TemplateNameSpec.hs | bsd-3-clause | 2,635 | 0 | 23 | 695 | 579 | 281 | 298 | 39 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-missing-fields #-}
-- overlapping instances is for automatic lifting
-- while avoiding an orphan of Lift for Text
{-# LANGUAGE OverlappingInstances #-}
-- | This module provides utilities for creating backends. Regular users do not
-- need to use this module.
module Database.Persist.TH
( -- * Parse entity defs
persistWith
, persistUpperCase
, persistLowerCase
, persistFileWith
-- * Turn @EntityDef@s into types
, mkPersist
, MkPersistSettings
, mpsBackend
, mpsGeneric
, mpsPrefixFields
, mpsEntityJSON
, mpsGenerateLenses
, EntityJSON(..)
, mkPersistSettings
, sqlSettings
, sqlOnlySettings
-- * Various other TH functions
, mkMigrate
, mkSave
, mkDeleteCascade
, share
, derivePersistField
, derivePersistFieldJSON
, persistFieldFromEntity
-- * Internal
, packPTH
, lensPTH
) where
import Prelude hiding ((++), take, concat, splitAt, exp)
import Database.Persist
import Database.Persist.Sql (Migration, migrate, SqlBackend, PersistFieldSql)
import Database.Persist.Quasi
import Language.Haskell.TH.Lib (varE)
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
import Data.Char (toLower, toUpper)
import Control.Monad (forM, (<=<), mzero)
import qualified System.IO as SIO
import Data.Text (pack, Text, append, unpack, concat, uncons, cons, stripPrefix, stripSuffix)
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Int (Int64)
import Data.List (foldl')
import Data.Maybe (isJust, listToMaybe, mapMaybe, fromMaybe)
import Data.Monoid (mappend, mconcat)
import Text.Read (readPrec, lexP, step, prec, parens, Lexeme(Ident))
import qualified Data.Map as M
import qualified Data.HashMap.Strict as HM
import Data.Aeson
( ToJSON (toJSON), FromJSON (parseJSON), (.=), object
, Value (Object), (.:), (.:?)
, eitherDecodeStrict'
)
import Control.Applicative (pure, (<$>), (<*>))
import Database.Persist.Sql (sqlType)
import Data.Proxy (Proxy (Proxy))
import Web.PathPieces (PathPiece, toPathPiece, fromPathPiece)
import GHC.Generics (Generic)
import qualified Data.Text.Encoding as TE
-- | Converts a quasi-quoted syntax into a list of entity definitions, to be
-- used as input to the template haskell generation code (mkPersist).
persistWith :: PersistSettings -> QuasiQuoter
persistWith ps = QuasiQuoter
{ quoteExp = parseReferences ps . pack
}
-- | Apply 'persistWith' to 'upperCaseSettings'.
persistUpperCase :: QuasiQuoter
persistUpperCase = persistWith upperCaseSettings
-- | Apply 'persistWith' to 'lowerCaseSettings'.
persistLowerCase :: QuasiQuoter
persistLowerCase = persistWith lowerCaseSettings
-- | Same as 'persistWith', but uses an external file instead of a
-- quasiquotation.
persistFileWith :: PersistSettings -> FilePath -> Q Exp
persistFileWith ps fp = do
#ifdef GHC_7_4
qAddDependentFile fp
#endif
h <- qRunIO $ SIO.openFile fp SIO.ReadMode
qRunIO $ SIO.hSetEncoding h SIO.utf8_bom
s <- qRunIO $ TIO.hGetContents h
parseReferences ps s
-- calls parse to Quasi.parse individual entities in isolation
-- afterwards, sets references to other entities
parseReferences :: PersistSettings -> Text -> Q Exp
parseReferences ps s = lift $
map (mkEntityDefSqlTypeExp embedEntityMap entMap) noCycleEnts
where
entMap = M.fromList $ map (\ent -> (entityHaskell ent, ent)) noCycleEnts
noCycleEnts = map breakCycleEnt entsWithEmbeds
-- every EntityDef could reference each-other (as an EmbedRef)
-- let Haskell tie the knot
embedEntityMap = M.fromList $ map (\ent -> (entityHaskell ent, toEmbedEntityDef ent)) entsWithEmbeds
entsWithEmbeds = map setEmbedEntity rawEnts
setEmbedEntity ent = ent
{ entityFields = map (setEmbedField (entityHaskell ent) embedEntityMap) $ entityFields ent
}
rawEnts = parse ps s
-- self references are already broken
-- look at every emFieldEmbed to see if it refers to an already seen HaskellName
-- so start with entityHaskell ent and accumulate embeddedHaskell em
breakCycleEnt entDef =
let entName = entityHaskell entDef
in entDef { entityFields = map (breakCycleField entName) $ entityFields entDef }
breakCycleField entName f@(FieldDef { fieldReference = EmbedRef em }) =
f { fieldReference = EmbedRef $ breakCycleEmbed [entName] em }
breakCycleField _ f = f
breakCycleEmbed ancestors em =
em { embeddedFields = map (breakCycleEmField $ emName : ancestors)
(embeddedFields em)
}
where
emName = embeddedHaskell em
breakCycleEmField ancestors emf = case embeddedHaskell <$> membed of
Nothing -> emf
Just embName -> if embName `elem` ancestors
then emf { emFieldEmbed = Nothing, emFieldCycle = Just embName }
else emf { emFieldEmbed = breakCycleEmbed ancestors <$> membed }
where
membed = emFieldEmbed emf
stripId :: FieldType -> Maybe Text
stripId (FTTypeCon Nothing t) = stripSuffix "Id" t
stripId _ = Nothing
foreignReference :: FieldDef -> Maybe HaskellName
foreignReference field = case fieldReference field of
ForeignRef ref _ -> Just ref
_ -> Nothing
-- fieldSqlType at parse time can be an Exp
-- This helps delay setting fieldSqlType until lift time
data EntityDefSqlTypeExp = EntityDefSqlTypeExp EntityDef SqlTypeExp [SqlTypeExp]
deriving Show
data SqlTypeExp = SqlTypeExp FieldType
| SqlType' SqlType
deriving Show
instance Lift SqlTypeExp where
lift (SqlType' t) = lift t
lift (SqlTypeExp ftype) = return st
where
typ = ftToType ftype
mtyp = (ConT ''Proxy `AppT` typ)
typedNothing = SigE (ConE 'Proxy) mtyp
st = VarE 'sqlType `AppE` typedNothing
data FieldsSqlTypeExp = FieldsSqlTypeExp [FieldDef] [SqlTypeExp]
instance Lift FieldsSqlTypeExp where
lift (FieldsSqlTypeExp fields sqlTypeExps) =
lift $ zipWith FieldSqlTypeExp fields sqlTypeExps
data FieldSqlTypeExp = FieldSqlTypeExp FieldDef SqlTypeExp
instance Lift FieldSqlTypeExp where
lift (FieldSqlTypeExp (FieldDef{..}) sqlTypeExp) =
[|FieldDef fieldHaskell fieldDB fieldType $(lift sqlTypeExp) fieldAttrs fieldStrict fieldReference|]
instance Lift EntityDefSqlTypeExp where
lift (EntityDefSqlTypeExp ent sqlTypeExp sqlTypeExps) =
[|ent { entityFields = $(lift $ FieldsSqlTypeExp (entityFields ent) sqlTypeExps)
, entityId = $(lift $ FieldSqlTypeExp (entityId ent) sqlTypeExp)
}
|]
instance Lift ReferenceDef where
lift NoReference = [|NoReference|]
lift (ForeignRef name ft) = [|ForeignRef name ft|]
lift (EmbedRef em) = [|EmbedRef em|]
lift (CompositeRef cdef) = [|CompositeRef cdef|]
lift (SelfReference) = [|SelfReference|]
instance Lift EmbedEntityDef where
lift (EmbedEntityDef name fields) = [|EmbedEntityDef name fields|]
instance Lift EmbedFieldDef where
lift (EmbedFieldDef name em cyc) = [|EmbedFieldDef name em cyc|]
type EmbedEntityMap = M.Map HaskellName EmbedEntityDef
type EntityMap = M.Map HaskellName EntityDef
data FTTypeConDescr = FTKeyCon deriving Show
mEmbedded :: EmbedEntityMap -> FieldType -> Either (Maybe FTTypeConDescr) EmbedEntityDef
mEmbedded _ (FTTypeCon Just{} _) = Left Nothing
mEmbedded ents (FTTypeCon Nothing n) = let name = HaskellName n in
maybe (Left Nothing) Right $ M.lookup name ents
mEmbedded ents (FTList x) = mEmbedded ents x
mEmbedded ents (FTApp x y) =
-- Key converts an Record to a RecordId
-- special casing this is obviously a hack
-- This problem may not be solvable with the current QuasiQuoted approach though
if x == FTTypeCon Nothing "Key"
then Left $ Just FTKeyCon
else mEmbedded ents y
setEmbedField :: HaskellName -> EmbedEntityMap -> FieldDef -> FieldDef
setEmbedField entName allEntities field = field
{ fieldReference = case fieldReference field of
NoReference ->
case mEmbedded allEntities (fieldType field) of
Left _ -> case stripId $ fieldType field of
Nothing -> NoReference
Just name -> case M.lookup (HaskellName name) allEntities of
Nothing -> NoReference
Just x -> ForeignRef (HaskellName name)
-- This can get corrected in mkEntityDefSqlTypeExp
(FTTypeCon (Just "Data.Int") "Int64")
Right em -> if embeddedHaskell em /= entName
then EmbedRef em
else if maybeNullable field
then SelfReference
else error $ unpack $ unHaskellName entName `mappend` ": a self reference must be a Maybe"
existing@_ -> existing
}
mkEntityDefSqlTypeExp :: EmbedEntityMap -> EntityMap -> EntityDef -> EntityDefSqlTypeExp
mkEntityDefSqlTypeExp emEntities entMap ent = EntityDefSqlTypeExp ent
(getSqlType $ entityId ent)
$ (map getSqlType $ entityFields ent)
where
getSqlType field = maybe
(defaultSqlTypeExp field)
(SqlType' . SqlOther)
(listToMaybe $ mapMaybe (stripPrefix "sqltype=") $ fieldAttrs field)
-- In the case of embedding, there won't be any datatype created yet.
-- We just use SqlString, as the data will be serialized to JSON.
defaultSqlTypeExp field = case mEmbedded emEntities ftype of
Right _ -> SqlType' SqlString
Left (Just FTKeyCon) -> SqlType' SqlString
Left Nothing -> case fieldReference field of
ForeignRef refName ft -> case M.lookup refName entMap of
Nothing -> SqlTypeExp ft
-- A ForeignRef is blindly set to an Int64 in setEmbedField
-- correct that now
Just ent -> case entityPrimary ent of
Nothing -> SqlTypeExp ft
Just pdef -> case compositeFields pdef of
[] -> error "mkEntityDefSqlTypeExp: no composite fields"
[x] -> SqlTypeExp $ fieldType x
_ -> SqlType' $ SqlOther "Composite Reference"
CompositeRef _ -> SqlType' $ SqlOther "Composite Reference"
_ -> case ftype of
-- In the case of lists, we always serialize to a string
-- value (via JSON).
--
-- Normally, this would be determined automatically by
-- SqlTypeExp. However, there's one corner case: if there's
-- a list of entity IDs, the datatype for the ID has not
-- yet been created, so the compiler will fail. This extra
-- clause works around this limitation.
FTList _ -> SqlType' SqlString
_ -> SqlTypeExp ftype
where
ftype = fieldType field
-- | Create data types and appropriate 'PersistEntity' instances for the given
-- 'EntityDef's. Works well with the persist quasi-quoter.
mkPersist :: MkPersistSettings -> [EntityDef] -> Q [Dec]
mkPersist mps ents' = do
x <- fmap mconcat $ mapM (persistFieldFromEntity mps) ents
y <- fmap mconcat $ mapM (mkEntity mps) ents
z <- fmap mconcat $ mapM (mkJSON mps) ents
return $ mconcat [x, y, z]
where
ents = map fixEntityDef ents'
-- | Implement special preprocessing on EntityDef as necessary for 'mkPersist'.
-- For example, strip out any fields marked as MigrationOnly.
fixEntityDef :: EntityDef -> EntityDef
fixEntityDef ed =
ed { entityFields = filter keepField $ entityFields ed }
where
keepField fd = "MigrationOnly" `notElem` fieldAttrs fd &&
"SafeToRemove" `notElem` fieldAttrs fd
-- | Settings to be passed to the 'mkPersist' function.
data MkPersistSettings = MkPersistSettings
{ mpsBackend :: Type
-- ^ Which database backend we\'re using.
--
-- When generating data types, each type is given a generic version- which
-- works with any backend- and a type synonym for the commonly used
-- backend. This is where you specify that commonly used backend.
, mpsGeneric :: Bool
-- ^ Create generic types that can be used with multiple backends. Good for
-- reusable code, but makes error messages harder to understand. Default:
-- True.
, mpsPrefixFields :: Bool
-- ^ Prefix field names with the model name. Default: True.
, mpsEntityJSON :: Maybe EntityJSON
-- ^ Generate @ToJSON@/@FromJSON@ instances for each model types. If it's
-- @Nothing@, no instances will be generated. Default:
--
-- @
-- Just EntityJSON
-- { entityToJSON = 'keyValueEntityToJSON
-- , entityFromJSON = 'keyValueEntityFromJSON
-- }
-- @
, mpsGenerateLenses :: !Bool
-- ^ Instead of generating normal field accessors, generator lens-style accessors.
--
-- Default: False
--
-- Since 1.3.1
}
data EntityJSON = EntityJSON
{ entityToJSON :: Name
-- ^ Name of the @toJSON@ implementation for @Entity a@.
, entityFromJSON :: Name
-- ^ Name of the @fromJSON@ implementation for @Entity a@.
}
-- | Create an @MkPersistSettings@ with default values.
mkPersistSettings :: Type -- ^ Value for 'mpsBackend'
-> MkPersistSettings
mkPersistSettings t = MkPersistSettings
{ mpsBackend = t
, mpsGeneric = False
, mpsPrefixFields = True
, mpsEntityJSON = Just EntityJSON
{ entityToJSON = 'entityIdToJSON
, entityFromJSON = 'entityIdFromJSON
}
, mpsGenerateLenses = False
}
-- | Use the 'SqlPersist' backend.
sqlSettings :: MkPersistSettings
sqlSettings = mkPersistSettings $ ConT ''SqlBackend
-- | Same as 'sqlSettings'.
--
-- Since 1.1.1
sqlOnlySettings :: MkPersistSettings
sqlOnlySettings = sqlSettings
{-# DEPRECATED sqlOnlySettings "use sqlSettings" #-}
recNameNoUnderscore :: MkPersistSettings -> HaskellName -> HaskellName -> Text
recNameNoUnderscore mps dt f
| mpsPrefixFields mps = lowerFirst (unHaskellName dt) ++ upperFirst ft
| otherwise = lowerFirst ft
where ft = unHaskellName f
recName :: MkPersistSettings -> HaskellName -> HaskellName -> Text
recName mps dt f =
addUnderscore $ recNameNoUnderscore mps dt f
where
addUnderscore
| mpsGenerateLenses mps = ("_" ++)
| otherwise = id
lowerFirst :: Text -> Text
lowerFirst t =
case uncons t of
Just (a, b) -> cons (toLower a) b
Nothing -> t
upperFirst :: Text -> Text
upperFirst t =
case uncons t of
Just (a, b) -> cons (toUpper a) b
Nothing -> t
dataTypeDec :: MkPersistSettings -> EntityDef -> Dec
dataTypeDec mps t =
DataD [] nameFinal paramsFinal constrs
$ map (mkName . unpack) $ entityDerives t
where
mkCol x fd@FieldDef {..} =
(mkName $ unpack $ recName mps x fieldHaskell,
if fieldStrict then IsStrict else NotStrict,
maybeIdType mps fd Nothing Nothing
)
(nameFinal, paramsFinal)
| mpsGeneric mps = (nameG, [PlainTV backend])
| otherwise = (name, [])
nameG = mkName $ unpack $ unHaskellName (entityHaskell t) ++ "Generic"
name = mkName $ unpack $ unHaskellName $ entityHaskell t
cols = map (mkCol $ entityHaskell t) $ entityFields t
backend = backendName
constrs
| entitySum t = map sumCon $ entityFields t
| otherwise = [RecC name cols]
sumCon fd = NormalC
(sumConstrName mps t fd)
[(NotStrict, maybeIdType mps fd Nothing Nothing)]
sumConstrName :: MkPersistSettings -> EntityDef -> FieldDef -> Name
sumConstrName mps t FieldDef {..} = mkName $ unpack $ concat
[ if mpsPrefixFields mps
then unHaskellName $ entityHaskell t
else ""
, upperFirst $ unHaskellName fieldHaskell
, "Sum"
]
uniqueTypeDec :: MkPersistSettings -> EntityDef -> Dec
uniqueTypeDec mps t =
DataInstD [] ''Unique
[genericDataType mps (entityHaskell t) backendT]
(map (mkUnique mps t) $ entityUniques t)
[]
mkUnique :: MkPersistSettings -> EntityDef -> UniqueDef -> Con
mkUnique mps t (UniqueDef (HaskellName constr) _ fields attrs) =
NormalC (mkName $ unpack constr) types
where
types = map (go . flip lookup3 (entityFields t))
$ map (unHaskellName . fst) fields
force = "!force" `elem` attrs
go :: (FieldDef, IsNullable) -> (Strict, Type)
go (_, Nullable _) | not force = error nullErrMsg
go (fd, y) = (NotStrict, maybeIdType mps fd Nothing (Just y))
lookup3 :: Text -> [FieldDef] -> (FieldDef, IsNullable)
lookup3 s [] =
error $ unpack $ "Column not found: " ++ s ++ " in unique " ++ constr
lookup3 x (fd@FieldDef {..}:rest)
| x == unHaskellName fieldHaskell = (fd, nullable fieldAttrs)
| otherwise = lookup3 x rest
nullErrMsg =
mconcat [ "Error: By default we disallow NULLables in an uniqueness "
, "constraint. The semantics of how NULL interacts with those "
, "constraints is non-trivial: two NULL values are not "
, "considered equal for the purposes of an uniqueness "
, "constraint. If you understand this feature, it is possible "
, "to use it your advantage. *** Use a \"!force\" attribute "
, "on the end of the line that defines your uniqueness "
, "constraint in order to disable this check. ***" ]
maybeIdType :: MkPersistSettings
-> FieldDef
-> Maybe Name -- ^ backend
-> Maybe IsNullable
-> Type
maybeIdType mps fd mbackend mnull = maybeTyp mayNullable idtyp
where
mayNullable = case mnull of
(Just (Nullable ByMaybeAttr)) -> True
_ -> maybeNullable fd
idtyp = idType mps fd mbackend
backendDataType :: MkPersistSettings -> Type
backendDataType mps
| mpsGeneric mps = backendT
| otherwise = mpsBackend mps
genericDataType :: MkPersistSettings
-> HaskellName -- ^ entity name
-> Type -- ^ backend
-> Type
genericDataType mps (HaskellName typ') backend
| mpsGeneric mps = ConT (mkName $ unpack $ typ' ++ "Generic") `AppT` backend
| otherwise = ConT $ mkName $ unpack typ'
idType :: MkPersistSettings -> FieldDef -> Maybe Name -> Type
idType mps fd mbackend =
case foreignReference fd of
Just typ ->
ConT ''Key
`AppT` genericDataType mps typ (VarT $ fromMaybe backendName mbackend)
Nothing -> ftToType $ fieldType fd
degen :: [Clause] -> [Clause]
degen [] =
let err = VarE 'error `AppE` LitE (StringL
"Degenerate case, should never happen")
in [normalClause [WildP] err]
degen x = x
mkToPersistFields :: MkPersistSettings -> String -> EntityDef -> Q Dec
mkToPersistFields mps constr ed@EntityDef { entitySum = isSum, entityFields = fields } = do
clauses <-
if isSum
then sequence $ zipWith goSum fields [1..]
else fmap return go
return $ FunD 'toPersistFields clauses
where
go :: Q Clause
go = do
xs <- sequence $ replicate fieldCount $ newName "x"
let pat = ConP (mkName constr) $ map VarP xs
sp <- [|SomePersistField|]
let bod = ListE $ map (AppE sp . VarE) xs
return $ normalClause [pat] bod
fieldCount = length fields
goSum :: FieldDef -> Int -> Q Clause
goSum fd idx = do
let name = sumConstrName mps ed fd
enull <- [|SomePersistField PersistNull|]
let beforeCount = idx - 1
afterCount = fieldCount - idx
before = replicate beforeCount enull
after = replicate afterCount enull
x <- newName "x"
sp <- [|SomePersistField|]
let body = ListE $ mconcat
[ before
, [sp `AppE` VarE x]
, after
]
return $ normalClause [ConP name [VarP x]] body
mkToFieldNames :: [UniqueDef] -> Q Dec
mkToFieldNames pairs = do
pairs' <- mapM go pairs
return $ FunD 'persistUniqueToFieldNames $ degen pairs'
where
go (UniqueDef constr _ names _) = do
names' <- lift names
return $
normalClause
[RecP (mkName $ unpack $ unHaskellName constr) []]
names'
mkUniqueToValues :: [UniqueDef] -> Q Dec
mkUniqueToValues pairs = do
pairs' <- mapM go pairs
return $ FunD 'persistUniqueToValues $ degen pairs'
where
go :: UniqueDef -> Q Clause
go (UniqueDef constr _ names _) = do
xs <- mapM (const $ newName "x") names
let pat = ConP (mkName $ unpack $ unHaskellName constr) $ map VarP xs
tpv <- [|toPersistValue|]
let bod = ListE $ map (AppE tpv . VarE) xs
return $ normalClause [pat] bod
isNotNull :: PersistValue -> Bool
isNotNull PersistNull = False
isNotNull _ = True
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft _ (Right r) = Right r
mapLeft f (Left l) = Left (f l)
fieldError :: Text -> Text -> Text
fieldError fieldName err = "field " `mappend` fieldName `mappend` ": " `mappend` err
mkFromPersistValues :: MkPersistSettings -> EntityDef -> Q [Clause]
mkFromPersistValues _ t@(EntityDef { entitySum = False }) =
fromValues t "fromPersistValues" entE $ entityFields t
where
entE = ConE $ mkName $ unpack entName
entName = unHaskellName $ entityHaskell t
mkFromPersistValues mps t@(EntityDef { entitySum = True }) = do
nothing <- [|Left ("Invalid fromPersistValues input: sum type with all nulls. Entity: " `mappend` entName)|]
clauses <- mkClauses [] $ entityFields t
return $ clauses `mappend` [normalClause [WildP] nothing]
where
entName = unHaskellName $ entityHaskell t
mkClauses _ [] = return []
mkClauses before (field:after) = do
x <- newName "x"
let null' = ConP 'PersistNull []
pat = ListP $ mconcat
[ map (const null') before
, [VarP x]
, map (const null') after
]
constr = ConE $ sumConstrName mps t field
fs <- [|fromPersistValue $(return $ VarE x)|]
let guard' = NormalG $ VarE 'isNotNull `AppE` VarE x
let clause = Clause [pat] (GuardedB [(guard', InfixE (Just constr) fmapE (Just fs))]) []
clauses <- mkClauses (field : before) after
return $ clause : clauses
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
lensPTH :: (s -> a) -> (s -> b -> t) -> Lens s t a b
lensPTH sa sbt afb s = fmap (sbt s) (afb $ sa s)
fmapE :: Exp
fmapE = VarE 'fmap
mkLensClauses :: MkPersistSettings -> EntityDef -> Q [Clause]
mkLensClauses mps t = do
lens' <- [|lensPTH|]
getId <- [|entityKey|]
setId <- [|\(Entity _ value) key -> Entity key value|]
getVal <- [|entityVal|]
dot <- [|(.)|]
keyVar <- newName "key"
valName <- newName "value"
xName <- newName "x"
let idClause = normalClause
[ConP (keyIdName t) []]
(lens' `AppE` getId `AppE` setId)
if entitySum t
then return $ idClause : map (toSumClause lens' keyVar valName xName) (entityFields t)
else return $ idClause : map (toClause lens' getVal dot keyVar valName xName) (entityFields t)
where
toClause lens' getVal dot keyVar valName xName f = normalClause
[ConP (filterConName mps t f) []]
(lens' `AppE` getter `AppE` setter)
where
fieldName = mkName $ unpack $ recName mps (entityHaskell t) (fieldHaskell f)
getter = InfixE (Just $ VarE fieldName) dot (Just getVal)
setter = LamE
[ ConP 'Entity [VarP keyVar, VarP valName]
, VarP xName
]
$ ConE 'Entity `AppE` VarE keyVar `AppE` RecUpdE
(VarE valName)
[(fieldName, VarE xName)]
toSumClause lens' keyVar valName xName f = normalClause
[ConP (filterConName mps t f) []]
(lens' `AppE` getter `AppE` setter)
where
emptyMatch = Match WildP (NormalB $ VarE 'error `AppE` LitE (StringL "Tried to use fieldLens on a Sum type")) []
getter = LamE
[ ConP 'Entity [WildP, VarP valName]
] $ CaseE (VarE valName)
$ Match (ConP (sumConstrName mps t f) [VarP xName]) (NormalB $ VarE xName) []
-- FIXME It would be nice if the types expressed that the Field is
-- a sum type and therefore could result in Maybe.
: if length (entityFields t) > 1 then [emptyMatch] else []
setter = LamE
[ ConP 'Entity [VarP keyVar, WildP]
, VarP xName
]
$ ConE 'Entity `AppE` VarE keyVar `AppE` (ConE (sumConstrName mps t f) `AppE` VarE xName)
-- | declare the key type and associated instances
-- a PathPiece instance is only generated for a Key with one field
mkKeyTypeDec :: MkPersistSettings -> EntityDef -> Q (Dec, [Dec])
mkKeyTypeDec mps t = do
(instDecs, i) <-
if mpsGeneric mps
then if not useNewtype
then do pfDec <- pfInstD
return (pfDec, [''Generic])
else do gi <- genericNewtypeInstances
return (gi, [])
else if not useNewtype
then do pfDec <- pfInstD
return (pfDec, [''Show, ''Read, ''Eq, ''Ord, ''Generic])
else do
let allInstances = [''Show, ''Read, ''Eq, ''Ord, ''PathPiece, ''PersistField, ''PersistFieldSql, ''ToJSON, ''FromJSON]
if customKeyType
then return ([], allInstances)
else do
bi <- backendKeyI
return (bi, allInstances)
let kd = if useNewtype
then NewtypeInstD [] k [recordType] dec i
else DataInstD [] k [recordType] [dec] i
return (kd, instDecs)
where
keyConE = keyConExp t
unKeyE = unKeyExp t
dec = RecC (keyConName t) (keyFields mps t)
k = ''Key
recordType = genericDataType mps (entityHaskell t) backendT
pfInstD = -- FIXME: generate a PersistMap instead of PersistList
[d|instance PersistField (Key $(pure recordType)) where
toPersistValue = PersistList . keyToValues
fromPersistValue (PersistList l) = keyFromValues l
fromPersistValue got = error $ "fromPersistValue: expected PersistList, got: " `mappend` show got
instance PersistFieldSql (Key $(pure recordType)) where
sqlType _ = SqlString
instance ToJSON (Key $(pure recordType))
instance FromJSON (Key $(pure recordType))
|]
keyStringL = StringL . keyString
-- ghc 7.6 cannot parse the left arrow Ident $() <- lexP
keyPattern = BindS (ConP 'Ident [LitP $ keyStringL t])
backendKeyGenericI =
[d| instance PersistStore $(pure backendT) =>
ToBackendKey $(pure backendT) $(pure recordType) where
toBackendKey = $(return unKeyE)
fromBackendKey = $(return keyConE)
|]
backendKeyI = let bdt = backendDataType mps in
[d| instance ToBackendKey $(pure bdt) $(pure recordType) where
toBackendKey = $(return unKeyE)
fromBackendKey = $(return keyConE)
|]
-- truly unfortunate that TH doesn't support standalone deriving
-- https://ghc.haskell.org/trac/ghc/ticket/8100
genericNewtypeInstances = do
instances <- [|lexP|] >>= \lexPE -> [| step readPrec >>= return . ($(pure keyConE) )|] >>= \readE -> do
alwaysInstances <-
[d|instance Show (BackendKey $(pure backendT)) => Show (Key $(pure recordType)) where
showsPrec i x = showParen (i > app_prec) $
(showString $ $(pure $ LitE $ keyStringL t) `mappend` " ") .
showsPrec i ($(return unKeyE) x)
where app_prec = (10::Int)
instance Read (BackendKey $(pure backendT)) => Read (Key $(pure recordType)) where
readPrec = parens $ (prec app_prec $ $(pure $ DoE [keyPattern lexPE, NoBindS readE]))
where app_prec = (10::Int)
instance Eq (BackendKey $(pure backendT)) => Eq (Key $(pure recordType)) where
x == y =
($(return unKeyE) x) ==
($(return unKeyE) y)
x /= y =
($(return unKeyE) x) ==
($(return unKeyE) y)
instance Ord (BackendKey $(pure backendT)) => Ord (Key $(pure recordType)) where
compare x y = compare
($(return unKeyE) x)
($(return unKeyE) y)
instance PathPiece (BackendKey $(pure backendT)) => PathPiece (Key $(pure recordType)) where
toPathPiece = toPathPiece . $(return unKeyE)
fromPathPiece = fmap $(return keyConE) . fromPathPiece
instance PersistField (BackendKey $(pure backendT)) => PersistField (Key $(pure recordType)) where
toPersistValue = toPersistValue . $(return unKeyE)
fromPersistValue = fmap $(return keyConE) . fromPersistValue
instance PersistFieldSql (BackendKey $(pure backendT)) => PersistFieldSql (Key $(pure recordType)) where
sqlType = sqlType . fmap $(return unKeyE)
instance ToJSON (BackendKey $(pure backendT)) => ToJSON (Key $(pure recordType)) where
toJSON = toJSON . $(return unKeyE)
instance FromJSON (BackendKey $(pure backendT)) => FromJSON (Key $(pure recordType)) where
parseJSON = fmap $(return keyConE) . parseJSON
|]
if customKeyType then return alwaysInstances
else fmap (alwaysInstances `mappend`) backendKeyGenericI
return instances
useNewtype = pkNewtype mps t
customKeyType = not (defaultIdType t) || not useNewtype || isJust (entityPrimary t)
keyIdName :: EntityDef -> Name
keyIdName = mkName . unpack . keyIdText
keyIdText :: EntityDef -> Text
keyIdText t = (unHaskellName $ entityHaskell t) `mappend` "Id"
unKeyName :: EntityDef -> Name
unKeyName t = mkName $ "un" `mappend` keyString t
unKeyExp :: EntityDef -> Exp
unKeyExp = VarE . unKeyName
backendT :: Type
backendT = VarT backendName
backendName :: Name
backendName = mkName "backend"
keyConName :: EntityDef -> Name
keyConName t = mkName $ resolveConflict $ keyString t
where
resolveConflict kn = if conflict then kn `mappend` "'" else kn
conflict = any ((== HaskellName "key") . fieldHaskell) $ entityFields t
keyConExp :: EntityDef -> Exp
keyConExp = ConE . keyConName
keyString :: EntityDef -> String
keyString = unpack . keyText
keyText :: EntityDef -> Text
keyText t = unHaskellName (entityHaskell t) ++ "Key"
pkNewtype :: MkPersistSettings -> EntityDef -> Bool
pkNewtype mps t = length (keyFields mps t) < 2
defaultIdType :: EntityDef -> Bool
defaultIdType t = fieldType (entityId t) == FTTypeCon Nothing (keyIdText t)
keyFields :: MkPersistSettings -> EntityDef -> [(Name, Strict, Type)]
keyFields mps t = case entityPrimary t of
Just pdef -> map primaryKeyVar $ (compositeFields pdef)
Nothing -> if defaultIdType t
then [idKeyVar backendKeyType]
else [idKeyVar $ ftToType $ fieldType $ entityId t]
where
backendKeyType
| mpsGeneric mps = ConT ''BackendKey `AppT` backendT
| otherwise = ConT ''BackendKey `AppT` mpsBackend mps
idKeyVar ft = (unKeyName t, NotStrict, ft)
primaryKeyVar fd = ( keyFieldName mps t fd
, NotStrict
, ftToType $ fieldType fd
)
keyFieldName :: MkPersistSettings -> EntityDef -> FieldDef -> Name
keyFieldName mps t fd
| pkNewtype mps t = unKeyName t
| otherwise = mkName $ unpack
$ lowerFirst (keyText t) `mappend` (unHaskellName $ fieldHaskell fd)
mkKeyToValues :: MkPersistSettings -> EntityDef -> Q Dec
mkKeyToValues mps t = do
(p, e) <- case entityPrimary t of
Nothing ->
([],) <$> [|(:[]) . toPersistValue . $(return $ unKeyExp t)|]
Just pdef ->
return $ toValuesPrimary pdef
return $ FunD 'keyToValues $ return $ normalClause p e
where
toValuesPrimary pdef =
( [VarP recordName]
, ListE $ map (\fd -> VarE 'toPersistValue `AppE` (VarE (keyFieldName mps t fd) `AppE` VarE recordName)) $ compositeFields pdef
)
recordName = mkName "record"
normalClause :: [Pat] -> Exp -> Clause
normalClause p e = Clause p (NormalB e) []
mkKeyFromValues :: MkPersistSettings -> EntityDef -> Q Dec
mkKeyFromValues _mps t = do
clauses <- case entityPrimary t of
Nothing -> do
e <- [|fmap $(return $ keyConE) . fromPersistValue . headNote|]
return $ [normalClause [] e]
Just pdef ->
fromValues t "keyFromValues" keyConE (compositeFields pdef)
return $ FunD 'keyFromValues clauses
where
keyConE = keyConExp t
headNote :: [PersistValue] -> PersistValue
headNote (x:[]) = x
headNote xs = error $ "mkKeyFromValues: expected a list of one element, got: "
`mappend` show xs
fromValues :: EntityDef -> Text -> Exp -> [FieldDef] -> Q [Clause]
fromValues t funName conE fields = do
x <- newName "x"
let funMsg = entityText t `mappend` ": " `mappend` funName `mappend` " failed on: "
patternMatchFailure <-
[|Left $ mappend funMsg (pack $ show $(return $ VarE x))|]
suc <- patternSuccess fields
return [ suc, normalClause [VarP x] patternMatchFailure ]
where
patternSuccess [] = do
rightE <- [|Right|]
return $ normalClause [ListP []] (rightE `AppE` conE)
patternSuccess fieldsNE = do
x1 <- newName "x1"
restNames <- mapM (\i -> newName $ "x" `mappend` show i) [2..length fieldsNE]
(fpv1:mkPersistValues) <- mapM mkPvFromFd fieldsNE
app1E <- [|(<$>)|]
let conApp = infixFromPersistValue app1E fpv1 conE x1
applyE <- [|(<*>)|]
let applyFromPersistValue = infixFromPersistValue applyE
return $ normalClause
[ListP $ map VarP (x1:restNames)]
(foldl' (\exp (name, fpv) -> applyFromPersistValue fpv exp name) conApp (zip restNames mkPersistValues))
where
infixFromPersistValue applyE fpv exp name =
UInfixE exp applyE (fpv `AppE` VarE name)
mkPvFromFd = mkPersistValue . unHaskellName . fieldHaskell
mkPersistValue fieldName = [|mapLeft (fieldError fieldName) . fromPersistValue|]
mkEntity :: MkPersistSettings -> EntityDef -> Q [Dec]
mkEntity mps t = do
t' <- lift t
let nameT = unHaskellName entName
let nameS = unpack nameT
let clazz = ConT ''PersistEntity `AppT` genDataType
tpf <- mkToPersistFields mps nameS t
fpv <- mkFromPersistValues mps t
utv <- mkUniqueToValues $ entityUniques t
puk <- mkUniqueKeys t
fkc <- mapM (mkForeignKeysComposite mps t) $ entityForeigns t
let primaryField = entityId t
fields <- mapM (mkField mps t) $ primaryField : entityFields t
toFieldNames <- mkToFieldNames $ entityUniques t
(keyTypeDec, keyInstanceDecs) <- mkKeyTypeDec mps t
keyToValues' <- mkKeyToValues mps t
keyFromValues' <- mkKeyFromValues mps t
let addSyn -- FIXME maybe remove this
| mpsGeneric mps = (:) $
TySynD (mkName nameS) [] $
genericDataType mps entName $ mpsBackend mps
| otherwise = id
lensClauses <- mkLensClauses mps t
lenses <- mkLenses mps t
let instanceConstraint = if not (mpsGeneric mps) then [] else
[mkClassP ''PersistStore [backendT]]
return $ addSyn $
dataTypeDec mps t : mconcat fkc `mappend`
([ TySynD (keyIdName t) [] $
ConT ''Key `AppT` ConT (mkName nameS)
, InstanceD instanceConstraint clazz $
[ uniqueTypeDec mps t
, keyTypeDec
, keyToValues'
, keyFromValues'
, FunD 'entityDef [normalClause [WildP] t']
, tpf
, FunD 'fromPersistValues fpv
, toFieldNames
, utv
, puk
, DataInstD
[]
''EntityField
[ genDataType
, VarT $ mkName "typ"
]
(map fst fields)
[]
, FunD 'persistFieldDef (map snd fields)
, TySynInstD
''PersistEntityBackend
#if MIN_VERSION_template_haskell(2,9,0)
(TySynEqn
[genDataType]
(backendDataType mps))
#else
[genDataType]
(backendDataType mps)
#endif
, FunD 'persistIdField [normalClause [] (ConE $ keyIdName t)]
, FunD 'fieldLens lensClauses
]
] `mappend` lenses) `mappend` keyInstanceDecs
where
genDataType = genericDataType mps entName backendT
entName = entityHaskell t
entityText :: EntityDef -> Text
entityText = unHaskellName . entityHaskell
mkLenses :: MkPersistSettings -> EntityDef -> Q [Dec]
mkLenses mps _ | not (mpsGenerateLenses mps) = return []
mkLenses _ ent | entitySum ent = return []
mkLenses mps ent = fmap mconcat $ forM (entityFields ent) $ \field -> do
let lensName' = recNameNoUnderscore mps (entityHaskell ent) (fieldHaskell field)
lensName = mkName $ unpack lensName'
fieldName = mkName $ unpack $ "_" ++ lensName'
needleN <- newName "needle"
setterN <- newName "setter"
fN <- newName "f"
aN <- newName "a"
yN <- newName "y"
let needle = VarE needleN
setter = VarE setterN
f = VarE fN
a = VarE aN
y = VarE yN
fT = mkName "f"
-- FIXME if we want to get really fancy, then: if this field is the
-- *only* Id field present, then set backend1 and backend2 to different
-- values
backend1 = backendName
backend2 = backendName
aT = maybeIdType mps field (Just backend1) Nothing
bT = maybeIdType mps field (Just backend2) Nothing
mkST backend = genericDataType mps (entityHaskell ent) (VarT backend)
sT = mkST backend1
tT = mkST backend2
t1 `arrow` t2 = ArrowT `AppT` t1 `AppT` t2
vars = PlainTV fT
: (if mpsGeneric mps then [PlainTV backend1{-, PlainTV backend2-}] else [])
return
[ SigD lensName $ ForallT vars [mkClassP ''Functor [VarT fT]] $
(aT `arrow` (VarT fT `AppT` bT)) `arrow`
(sT `arrow` (VarT fT `AppT` tT))
, FunD lensName $ return $ Clause
[VarP fN, VarP aN]
(NormalB $ fmapE
`AppE` setter
`AppE` (f `AppE` needle))
[ FunD needleN [normalClause [] (VarE fieldName `AppE` a)]
, FunD setterN $ return $ normalClause
[VarP yN]
(RecUpdE a
[ (fieldName, y)
])
]
]
mkForeignKeysComposite :: MkPersistSettings -> EntityDef -> ForeignDef -> Q [Dec]
mkForeignKeysComposite mps t ForeignDef {..} = do
let fieldName f = mkName $ unpack $ recName mps (entityHaskell t) f
let fname = fieldName foreignConstraintNameHaskell
let reftableString = unpack $ unHaskellName $ foreignRefTableHaskell
let reftableKeyName = mkName $ reftableString `mappend` "Key"
let tablename = mkName $ unpack $ entityText t
recordName <- newName "record"
let fldsE = map (\((foreignName, _),_) -> VarE (fieldName $ foreignName)
`AppE` VarE recordName) foreignFields
let mkKeyE = foldl' AppE (maybeExp foreignNullable $ ConE reftableKeyName) fldsE
let fn = FunD fname [normalClause [VarP recordName] mkKeyE]
let t2 = maybeTyp foreignNullable $ ConT ''Key `AppT` ConT (mkName reftableString)
let sig = SigD fname $ (ArrowT `AppT` (ConT tablename)) `AppT` t2
return [sig, fn]
maybeExp :: Bool -> Exp -> Exp
maybeExp may exp | may = fmapE `AppE` exp
| otherwise = exp
maybeTyp :: Bool -> Type -> Type
maybeTyp may typ | may = ConT ''Maybe `AppT` typ
| otherwise = typ
-- | produce code similar to the following:
--
-- @
-- instance PersistEntity e => PersistField e where
-- toPersistValue = PersistMap $ zip columNames (map toPersistValue . toPersistFields)
-- fromPersistValue (PersistMap o) =
-- let columns = HM.fromList o
-- in fromPersistValues $ map (\name ->
-- case HM.lookup name columns of
-- Just v -> v
-- Nothing -> PersistNull
-- fromPersistValue x = Left $ "Expected PersistMap, received: " ++ show x
-- sqlType _ = SqlString
-- @
persistFieldFromEntity :: MkPersistSettings -> EntityDef -> Q [Dec]
persistFieldFromEntity mps e = do
ss <- [|SqlString|]
obj <- [|\ent -> PersistMap $ zip (map pack columnNames) (map toPersistValue $ toPersistFields ent)|]
fpv <- [|\x -> let columns = HM.fromList x
in fromPersistValues $ map
(\(name) ->
case HM.lookup (pack name) columns of
Just v -> v
Nothing -> PersistNull)
$ columnNames
|]
compose <- [|(<=<)|]
getPersistMap' <- [|getPersistMap|]
return
[ persistFieldInstanceD (mpsGeneric mps) typ
[ FunD 'toPersistValue [ normalClause [] obj ]
, FunD 'fromPersistValue
[ normalClause [] (InfixE (Just fpv) compose $ Just getPersistMap')
]
]
, persistFieldSqlInstanceD (mpsGeneric mps) typ
[ sqlTypeFunD ss
]
]
where
typ = genericDataType mps (entityHaskell e) backendT
entFields = entityFields e
columnNames = map (unpack . unHaskellName . fieldHaskell) entFields
-- | Apply the given list of functions to the same @EntityDef@s.
--
-- This function is useful for cases such as:
--
-- >>> share [mkSave "myDefs", mkPersist sqlSettings] [persistLowerCase|...|]
share :: [[EntityDef] -> Q [Dec]] -> [EntityDef] -> Q [Dec]
share fs x = fmap mconcat $ mapM ($ x) fs
-- | Save the @EntityDef@s passed in under the given name.
mkSave :: String -> [EntityDef] -> Q [Dec]
mkSave name' defs' = do
let name = mkName name'
defs <- lift defs'
return [ SigD name $ ListT `AppT` ConT ''EntityDef
, FunD name [normalClause [] defs]
]
data Dep = Dep
{ depTarget :: HaskellName
, depSourceTable :: HaskellName
, depSourceField :: HaskellName
, depSourceNull :: IsNullable
}
-- | Generate a 'DeleteCascade' instance for the given @EntityDef@s.
mkDeleteCascade :: MkPersistSettings -> [EntityDef] -> Q [Dec]
mkDeleteCascade mps defs = do
let deps = concatMap getDeps defs
mapM (go deps) defs
where
getDeps :: EntityDef -> [Dep]
getDeps def =
concatMap getDeps' $ entityFields $ fixEntityDef def
where
getDeps' :: FieldDef -> [Dep]
getDeps' field@FieldDef {..} =
case foreignReference field of
Just name ->
return Dep
{ depTarget = name
, depSourceTable = entityHaskell def
, depSourceField = fieldHaskell
, depSourceNull = nullable fieldAttrs
}
Nothing -> []
go :: [Dep] -> EntityDef -> Q Dec
go allDeps EntityDef{entityHaskell = name} = do
let deps = filter (\x -> depTarget x == name) allDeps
key <- newName "key"
let del = VarE 'delete
let dcw = VarE 'deleteCascadeWhere
just <- [|Just|]
filt <- [|Filter|]
eq <- [|Eq|]
left <- [|Left|]
let mkStmt :: Dep -> Stmt
mkStmt dep = NoBindS
$ dcw `AppE`
ListE
[ filt `AppE` ConE filtName
`AppE` (left `AppE` val (depSourceNull dep))
`AppE` eq
]
where
filtName = filterConName' mps (depSourceTable dep) (depSourceField dep)
val (Nullable ByMaybeAttr) = just `AppE` VarE key
val _ = VarE key
let stmts :: [Stmt]
stmts = map mkStmt deps `mappend`
[NoBindS $ del `AppE` VarE key]
let entityT = genericDataType mps name backendT
return $
InstanceD
[ mkClassP ''PersistQuery [backendT]
, mkEqualP (ConT ''PersistEntityBackend `AppT` entityT) backendT
]
(ConT ''DeleteCascade `AppT` entityT `AppT` backendT)
[ FunD 'deleteCascade
[normalClause [VarP key] (DoE stmts)]
]
mkUniqueKeys :: EntityDef -> Q Dec
mkUniqueKeys def | entitySum def =
return $ FunD 'persistUniqueKeys [normalClause [WildP] (ListE [])]
mkUniqueKeys def = do
c <- clause
return $ FunD 'persistUniqueKeys [c]
where
clause = do
xs <- forM (entityFields def) $ \fd -> do
let x = fieldHaskell fd
x' <- newName $ '_' : unpack (unHaskellName x)
return (x, x')
let pcs = map (go xs) $ entityUniques def
let pat = ConP
(mkName $ unpack $ unHaskellName $ entityHaskell def)
(map (VarP . snd) xs)
return $ normalClause [pat] (ListE pcs)
go :: [(HaskellName, Name)] -> UniqueDef -> Exp
go xs (UniqueDef name _ cols _) =
foldl' (go' xs) (ConE (mkName $ unpack $ unHaskellName name)) (map fst cols)
go' :: [(HaskellName, Name)] -> Exp -> HaskellName -> Exp
go' xs front col =
let Just col' = lookup col xs
in front `AppE` VarE col'
sqlTypeFunD :: Exp -> Dec
sqlTypeFunD st = FunD 'sqlType
[ normalClause [WildP] st ]
typeInstanceD :: Name
-> Bool -- ^ include PersistStore backend constraint
-> Type -> [Dec] -> Dec
typeInstanceD clazz hasBackend typ =
InstanceD ctx (ConT clazz `AppT` typ)
where
ctx
| hasBackend = [mkClassP ''PersistStore [backendT]]
| otherwise = []
persistFieldInstanceD :: Bool -- ^ include PersistStore backend constraint
-> Type -> [Dec] -> Dec
persistFieldInstanceD = typeInstanceD ''PersistField
persistFieldSqlInstanceD :: Bool -- ^ include PersistStore backend constraint
-> Type -> [Dec] -> Dec
persistFieldSqlInstanceD = typeInstanceD ''PersistFieldSql
-- | Automatically creates a valid 'PersistField' instance for any datatype
-- that has valid 'Show' and 'Read' instances. Can be very convenient for
-- 'Enum' types.
derivePersistField :: String -> Q [Dec]
derivePersistField s = do
ss <- [|SqlString|]
tpv <- [|PersistText . pack . show|]
fpv <- [|\dt v ->
case fromPersistValue v of
Left e -> Left e
Right s' ->
case reads $ unpack s' of
(x, _):_ -> Right x
[] -> Left $ pack "Invalid " ++ pack dt ++ pack ": " ++ s'|]
return
[ persistFieldInstanceD False (ConT $ mkName s)
[ FunD 'toPersistValue
[ normalClause [] tpv
]
, FunD 'fromPersistValue
[ normalClause [] (fpv `AppE` LitE (StringL s))
]
]
, persistFieldSqlInstanceD False (ConT $ mkName s)
[ sqlTypeFunD ss
]
]
-- | Automatically creates a valid 'PersistField' instance for any datatype
-- that has valid 'ToJSON' and 'FromJSON' instances. For a datatype @T@ it
-- generates instances similar to these:
--
-- @
-- instance PersistField T where
-- toPersistValue = PersistByteString . L.toStrict . encode
-- fromPersistValue = (left T.pack) . eitherDecodeStrict' <=< fromPersistValue
-- instance PersistFieldSql T where
-- sqlType _ = SqlString
-- @
derivePersistFieldJSON :: String -> Q [Dec]
derivePersistFieldJSON s = do
ss <- [|SqlString|]
tpv <- [|PersistText . toJsonText|]
fpv <- [|\dt v -> do
text <- fromPersistValue v
let bs' = TE.encodeUtf8 text
case eitherDecodeStrict' bs' of
Left e -> Left $ pack "JSON decoding error for " ++ pack dt ++ pack ": " ++ pack e ++ pack ". On Input: " ++ decodeUtf8 bs'
Right x -> Right x|]
return
[ persistFieldInstanceD False (ConT $ mkName s)
[ FunD 'toPersistValue
[ normalClause [] tpv
]
, FunD 'fromPersistValue
[ normalClause [] (fpv `AppE` LitE (StringL s))
]
]
, persistFieldSqlInstanceD False (ConT $ mkName s)
[ sqlTypeFunD ss
]
]
-- | Creates a single function to perform all migrations for the entities
-- defined here. One thing to be aware of is dependencies: if you have entities
-- with foreign references, make sure to place those definitions after the
-- entities they reference.
mkMigrate :: String -> [EntityDef] -> Q [Dec]
mkMigrate fun allDefs = do
body' <- body
return
[ SigD (mkName fun) typ
, FunD (mkName fun) [normalClause [] body']
]
where
defs = filter isMigrated allDefs
isMigrated def = not $ "no-migrate" `elem` entityAttrs def
typ = ConT ''Migration
body :: Q Exp
body =
case defs of
[] -> [|return ()|]
_ -> do
defsName <- newName "defs"
defsStmt <- do
defs' <- mapM lift defs
let defsExp = ListE defs'
return $ LetS [ValD (VarP defsName) (NormalB defsExp) []]
stmts <- mapM (toStmt $ VarE defsName) defs
return (DoE $ defsStmt : stmts)
toStmt :: Exp -> EntityDef -> Q Stmt
toStmt defsExp ed = do
u <- lift ed
m <- [|migrate|]
return $ NoBindS $ m `AppE` defsExp `AppE` u
instance Lift EntityDef where
lift EntityDef{..} =
[|EntityDef
entityHaskell
entityDB
entityId
entityAttrs
entityFields
entityUniques
entityForeigns
entityDerives
entityExtra
entitySum
|]
instance Lift FieldDef where
lift (FieldDef a b c d e f g) = [|FieldDef a b c d e f g|]
instance Lift UniqueDef where
lift (UniqueDef a b c d) = [|UniqueDef a b c d|]
instance Lift CompositeDef where
lift (CompositeDef a b) = [|CompositeDef a b|]
instance Lift ForeignDef where
lift (ForeignDef a b c d e f g) = [|ForeignDef a b c d e f g|]
-- | A hack to avoid orphans.
class Lift' a where
lift' :: a -> Q Exp
instance Lift' Text where
lift' = liftT
instance Lift' a => Lift' [a] where
lift' xs = do { xs' <- mapM lift' xs; return (ListE xs') }
instance (Lift' k, Lift' v) => Lift' (M.Map k v) where
lift' m = [|M.fromList $(fmap ListE $ mapM liftPair $ M.toList m)|]
-- auto-lifting, means instances are overlapping
instance Lift' a => Lift a where
lift = lift'
packPTH :: String -> Text
packPTH = pack
#if !MIN_VERSION_text(0, 11, 2)
{-# NOINLINE packPTH #-}
#endif
liftT :: Text -> Q Exp
liftT t = [|packPTH $(lift (unpack t))|]
liftPair :: (Lift' k, Lift' v) => (k, v) -> Q Exp
liftPair (k, v) = [|($(lift' k), $(lift' v))|]
instance Lift HaskellName where
lift (HaskellName t) = [|HaskellName t|]
instance Lift DBName where
lift (DBName t) = [|DBName t|]
instance Lift FieldType where
lift (FTTypeCon Nothing t) = [|FTTypeCon Nothing t|]
lift (FTTypeCon (Just x) t) = [|FTTypeCon (Just x) t|]
lift (FTApp x y) = [|FTApp x y|]
lift (FTList x) = [|FTList x|]
instance Lift PersistFilter where
lift Eq = [|Eq|]
lift Ne = [|Ne|]
lift Gt = [|Gt|]
lift Lt = [|Lt|]
lift Ge = [|Ge|]
lift Le = [|Le|]
lift In = [|In|]
lift NotIn = [|NotIn|]
lift (BackendSpecificFilter x) = [|BackendSpecificFilter x|]
instance Lift PersistUpdate where
lift Assign = [|Assign|]
lift Add = [|Add|]
lift Subtract = [|Subtract|]
lift Multiply = [|Multiply|]
lift Divide = [|Divide|]
lift (BackendSpecificUpdate x) = [|BackendSpecificUpdate x|]
instance Lift SqlType where
lift SqlString = [|SqlString|]
lift SqlInt32 = [|SqlInt32|]
lift SqlInt64 = [|SqlInt64|]
lift SqlReal = [|SqlReal|]
lift (SqlNumeric x y) =
[|SqlNumeric (fromInteger x') (fromInteger y')|]
where
x' = fromIntegral x :: Integer
y' = fromIntegral y :: Integer
lift SqlBool = [|SqlBool|]
lift SqlDay = [|SqlDay|]
lift SqlTime = [|SqlTime|]
lift SqlDayTime = [|SqlDayTime|]
lift SqlBlob = [|SqlBlob|]
lift (SqlOther a) = [|SqlOther a|]
-- Ent
-- fieldName FieldType
--
-- forall . typ ~ FieldType => EntFieldName
--
-- EntFieldName = FieldDef ....
mkField :: MkPersistSettings -> EntityDef -> FieldDef -> Q (Con, Clause)
mkField mps et cd = do
let con = ForallC
[]
[mkEqualP (VarT $ mkName "typ") $ maybeIdType mps cd Nothing Nothing]
$ NormalC name []
bod <- lift cd
let cla = normalClause
[ConP name []]
bod
return (con, cla)
where
name = filterConName mps et cd
maybeNullable :: FieldDef -> Bool
maybeNullable fd = nullable (fieldAttrs fd) == Nullable ByMaybeAttr
filterConName :: MkPersistSettings
-> EntityDef
-> FieldDef
-> Name
filterConName mps entity field = filterConName' mps (entityHaskell entity) (fieldHaskell field)
filterConName' :: MkPersistSettings
-> HaskellName -- ^ table
-> HaskellName -- ^ field
-> Name
filterConName' mps entity field = mkName $ unpack $ concat
[ if mpsPrefixFields mps || field == HaskellName "Id"
then unHaskellName entity
else ""
, upperFirst $ unHaskellName field
]
ftToType :: FieldType -> Type
ftToType (FTTypeCon Nothing t) = ConT $ mkName $ unpack t
-- This type is generated from the Quasi-Quoter.
-- Adding this special case avoids users needing to import Data.Int
ftToType (FTTypeCon (Just "Data.Int") "Int64") = ConT ''Int64
ftToType (FTTypeCon (Just m) t) = ConT $ mkName $ unpack $ concat [m, ".", t]
ftToType (FTApp x y) = ftToType x `AppT` ftToType y
ftToType (FTList x) = ListT `AppT` ftToType x
infixr 5 ++
(++) :: Text -> Text -> Text
(++) = append
mkJSON :: MkPersistSettings -> EntityDef -> Q [Dec]
mkJSON _ def | not ("json" `elem` entityAttrs def) = return []
mkJSON mps def = do
pureE <- [|pure|]
apE' <- [|(<*>)|]
packE <- [|pack|]
dotEqualE <- [|(.=)|]
dotColonE <- [|(.:)|]
dotColonQE <- [|(.:?)|]
objectE <- [|object|]
obj <- newName "obj"
mzeroE <- [|mzero|]
xs <- mapM (newName . unpack . unHaskellName . fieldHaskell)
$ entityFields def
let conName = mkName $ unpack $ unHaskellName $ entityHaskell def
typ = genericDataType mps (entityHaskell def) backendT
toJSONI = typeInstanceD ''ToJSON (mpsGeneric mps) typ [toJSON']
toJSON' = FunD 'toJSON $ return $ normalClause
[ConP conName $ map VarP xs]
(objectE `AppE` ListE pairs)
pairs = zipWith toPair (entityFields def) xs
toPair f x = InfixE
(Just (packE `AppE` LitE (StringL $ unpack $ unHaskellName $ fieldHaskell f)))
dotEqualE
(Just $ VarE x)
fromJSONI = typeInstanceD ''FromJSON (mpsGeneric mps) typ [parseJSON']
parseJSON' = FunD 'parseJSON
[ normalClause [ConP 'Object [VarP obj]]
(foldl'
(\x y -> InfixE (Just x) apE' (Just y))
(pureE `AppE` ConE conName)
pulls
)
, normalClause [WildP] mzeroE
]
pulls = map toPull $ entityFields def
toPull f = InfixE
(Just $ VarE obj)
(if maybeNullable f then dotColonQE else dotColonE)
(Just $ AppE packE $ LitE $ StringL $ unpack $ unHaskellName $ fieldHaskell f)
case mpsEntityJSON mps of
Nothing -> return [toJSONI, fromJSONI]
Just entityJSON -> do
entityJSONIs <- if mpsGeneric mps
then [d|
#if MIN_VERSION_base(4, 6, 0)
instance PersistStore backend => ToJSON (Entity $(pure typ)) where
toJSON = $(varE (entityToJSON entityJSON))
instance PersistStore backend => FromJSON (Entity $(pure typ)) where
parseJSON = $(varE (entityFromJSON entityJSON))
#endif
|]
else [d|
instance ToJSON (Entity $(pure typ)) where
toJSON = $(varE (entityToJSON entityJSON))
instance FromJSON (Entity $(pure typ)) where
parseJSON = $(varE (entityFromJSON entityJSON))
|]
return $ toJSONI : fromJSONI : entityJSONIs
mkClassP :: Name -> [Type] -> Pred
#if MIN_VERSION_template_haskell(2,10,0)
mkClassP cla tys = foldl AppT (ConT cla) tys
#else
mkClassP = ClassP
#endif
mkEqualP :: Type -> Type -> Pred
#if MIN_VERSION_template_haskell(2,10,0)
mkEqualP tleft tright = foldl AppT EqualityT [tleft, tright]
#else
mkEqualP = EqualP
#endif
-- entityUpdates :: EntityDef -> [(HaskellName, FieldType, IsNullable, PersistUpdate)]
-- entityUpdates =
-- concatMap go . entityFields
-- where
-- go FieldDef {..} = map (\a -> (fieldHaskell, fieldType, nullable fieldAttrs, a)) [minBound..maxBound]
-- mkToUpdate :: String -> [(String, PersistUpdate)] -> Q Dec
-- mkToUpdate name pairs = do
-- pairs' <- mapM go pairs
-- return $ FunD (mkName name) $ degen pairs'
-- where
-- go (constr, pu) = do
-- pu' <- lift pu
-- return $ normalClause [RecP (mkName constr) []] pu'
-- mkToFieldName :: String -> [(String, String)] -> Dec
-- mkToFieldName func pairs =
-- FunD (mkName func) $ degen $ map go pairs
-- where
-- go (constr, name) =
-- normalClause [RecP (mkName constr) []] (LitE $ StringL name)
-- mkToValue :: String -> [String] -> Dec
-- mkToValue func = FunD (mkName func) . degen . map go
-- where
-- go constr =
-- let x = mkName "x"
-- in normalClause [ConP (mkName constr) [VarP x]]
-- (VarE 'toPersistValue `AppE` VarE x)
| jasonzoladz/persistent | persistent-template/Database/Persist/TH.hs | mit | 59,086 | 0 | 23 | 17,395 | 14,828 | 7,779 | 7,049 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>AMF Support</title>
<maps>
<homeID>amf</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/amf/src/main/javahelp/help_id_ID/helpset_id_ID.hs | apache-2.0 | 956 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Pkg.Package where
import System.Process
import System.Directory
import System.Exit
import System.IO
import System.FilePath ((</>), addTrailingPathSeparator, takeFileName, takeDirectory, normalise)
import System.Directory (createDirectoryIfMissing, copyFile)
import Util.System
import Control.Monad
import Control.Monad.Trans.State.Strict (execStateT)
import Control.Monad.Trans.Except (runExceptT)
import Data.List
import Data.List.Split(splitOn)
import Idris.Core.TT
import Idris.REPL
import Idris.Parser (loadModule)
import Idris.Output (pshow)
import Idris.AbsSyntax
import Idris.IdrisDoc
import Idris.IBC
import Idris.Output
import Idris.Imports
import Pkg.PParser
import IRTS.System
-- To build a package:
-- * read the package description
-- * check all the library dependencies exist
-- * invoke the makefile if there is one
-- * invoke idris on each module, with idris_opts
-- * install everything into datadir/pname, if install flag is set
-- | Run the package through the idris compiler.
buildPkg :: Bool -> (Bool, FilePath) -> IO ()
buildPkg warnonly (install, fp)
= do pkgdesc <- parseDesc fp
dir <- getCurrentDirectory
let idx = PkgIndex (pkgIndex (pkgname pkgdesc))
ok <- mapM (testLib warnonly (pkgname pkgdesc)) (libdeps pkgdesc)
when (and ok) $
do m_ist <- inPkgDir pkgdesc $
do make (makefile pkgdesc)
case (execout pkgdesc) of
Nothing -> buildMods (idx : NoREPL : Verbose : idris_opts pkgdesc)
(modules pkgdesc)
Just o -> do let exec = dir </> o
buildMods
(idx : NoREPL : Verbose : Output exec : idris_opts pkgdesc)
[idris_main pkgdesc]
case m_ist of
Nothing -> exitWith (ExitFailure 1)
Just ist -> do
-- Quit with error code if there was a problem
case errSpan ist of
Just _ -> exitWith (ExitFailure 1)
_ -> return ()
when install $ installPkg pkgdesc
-- | Type check packages only
--
-- This differs from build in that executables are not built, if the
-- package contains an executable.
checkPkg :: Bool -- ^ Show Warnings
-> Bool -- ^ quit on failure
-> FilePath -- ^ Path to ipkg file.
-> IO ()
checkPkg warnonly quit fpath
= do pkgdesc <- parseDesc fpath
ok <- mapM (testLib warnonly (pkgname pkgdesc)) (libdeps pkgdesc)
when (and ok) $
do res <- inPkgDir pkgdesc $
do make (makefile pkgdesc)
buildMods (NoREPL : Verbose : idris_opts pkgdesc)
(modules pkgdesc)
when quit $ case res of
Nothing -> exitWith (ExitFailure 1)
Just res' -> do
case errSpan res' of
Just _ -> exitWith (ExitFailure 1)
_ -> return ()
-- | Check a package and start a REPL
replPkg :: FilePath -> Idris ()
replPkg fp = do orig <- getIState
runIO $ checkPkg False False fp
pkgdesc <- runIO $ parseDesc fp -- bzzt, repetition!
let opts = idris_opts pkgdesc
let mod = idris_main pkgdesc
let f = toPath (showCG mod)
putIState orig
dir <- runIO $ getCurrentDirectory
runIO $ setCurrentDirectory $ dir </> sourcedir pkgdesc
if (f /= "")
then idrisMain ((Filename f) : opts)
else iputStrLn "Can't start REPL: no main module given"
runIO $ setCurrentDirectory dir
where toPath n = foldl1' (</>) $ splitOn "." n
-- | Clean Package build files
cleanPkg :: FilePath -- ^ Path to ipkg file.
-> IO ()
cleanPkg fp
= do pkgdesc <- parseDesc fp
dir <- getCurrentDirectory
inPkgDir pkgdesc $
do clean (makefile pkgdesc)
mapM_ rmIBC (modules pkgdesc)
rmIdx (pkgname pkgdesc)
case execout pkgdesc of
Nothing -> return ()
Just s -> rmFile $ dir </> s
-- | Generate IdrisDoc for package
-- TODO: Handle case where module does not contain a matching namespace
-- E.g. from prelude.ipkg: IO, Prelude.Chars, Builtins
--
-- Issue number #1572 on the issue tracker
-- https://github.com/idris-lang/Idris-dev/issues/1572
documentPkg :: FilePath -- ^ Path to .ipkg file.
-> IO ()
documentPkg fp =
do pkgdesc <- parseDesc fp
cd <- getCurrentDirectory
let pkgDir = cd </> takeDirectory fp
outputDir = cd </> pkgname pkgdesc ++ "_doc"
opts = NoREPL : Verbose : idris_opts pkgdesc
mods = modules pkgdesc
fs = map (foldl1' (</>) . splitOn "." . showCG) mods
setCurrentDirectory $ pkgDir </> sourcedir pkgdesc
make (makefile pkgdesc)
setCurrentDirectory pkgDir
let run l = runExceptT . execStateT l
load [] = return ()
load (f:fs) = do loadModule f; load fs
loader = do idrisMain opts; addImportDir (sourcedir pkgdesc); load fs
idrisInstance <- run loader idrisInit
setCurrentDirectory cd
case idrisInstance of
Left err -> do putStrLn $ pshow idrisInit err; exitWith (ExitFailure 1)
Right ist ->
do docRes <- generateDocs ist mods outputDir
case docRes of
Right _ -> return ()
Left msg -> do putStrLn msg
exitWith (ExitFailure 1)
-- | Build a package with a sythesized main function that runs the tests
testPkg :: FilePath -> IO ()
testPkg fp
= do pkgdesc <- parseDesc fp
ok <- mapM (testLib True (pkgname pkgdesc)) (libdeps pkgdesc)
when (and ok) $
do m_ist <- inPkgDir pkgdesc $
do make (makefile pkgdesc)
-- Get a temporary file to save the tests' source in
(tmpn, tmph) <- tempIdr
hPutStrLn tmph $
"module Test_______\n" ++
concat ["import " ++ show m ++ "\n"
| m <- modules pkgdesc] ++
"namespace Main\n" ++
" main : IO ()\n" ++
" main = do " ++
concat [show t ++ "\n "
| t <- idris_tests pkgdesc]
hClose tmph
(tmpn', tmph') <- tempfile
hClose tmph'
m_ist <- idris (Filename tmpn : NoREPL : Verbose : Output tmpn' : idris_opts pkgdesc)
rawSystem tmpn' []
return m_ist
case m_ist of
Nothing -> exitWith (ExitFailure 1)
Just ist -> do
-- Quit with error code if problem building
case errSpan ist of
Just _ -> exitWith (ExitFailure 1)
_ -> return ()
where tempIdr :: IO (FilePath, Handle)
tempIdr = do dir <- getTemporaryDirectory
openTempFile (normalise dir) "idristests.idr"
-- | Install package
installPkg :: PkgDesc -> IO ()
installPkg pkgdesc
= inPkgDir pkgdesc $
do case (execout pkgdesc) of
Nothing -> do mapM_ (installIBC (pkgname pkgdesc)) (modules pkgdesc)
installIdx (pkgname pkgdesc)
Just o -> return () -- do nothing, keep executable locally, for noe
mapM_ (installObj (pkgname pkgdesc)) (objs pkgdesc)
-- ---------------------------------------------------------- [ Helper Methods ]
-- Methods for building, testing, installing, and removal of idris
-- packages.
buildMods :: [Opt] -> [Name] -> IO (Maybe IState)
buildMods opts ns = do let f = map (toPath . showCG) ns
idris (map Filename f ++ opts)
where toPath n = foldl1' (</>) $ splitOn "." n
testLib :: Bool -> String -> String -> IO Bool
testLib warn p f
= do d <- getDataDir
gcc <- getCC
(tmpf, tmph) <- tempfile
hClose tmph
let libtest = d </> "rts" </> "libtest.c"
e <- rawSystem gcc [libtest, "-l" ++ f, "-o", tmpf]
case e of
ExitSuccess -> return True
_ -> do if warn
then do putStrLn $ "Not building " ++ p ++
" due to missing library " ++ f
return False
else fail $ "Missing library " ++ f
rmIBC :: Name -> IO ()
rmIBC m = rmFile $ toIBCFile m
rmIdx :: String -> IO ()
rmIdx p = do let f = pkgIndex p
ex <- doesFileExist f
when ex $ rmFile f
toIBCFile (UN n) = str n ++ ".ibc"
toIBCFile (NS n ns) = foldl1' (</>) (reverse (toIBCFile n : map str ns))
installIBC :: String -> Name -> IO ()
installIBC p m = do let f = toIBCFile m
d <- getTargetDir
let destdir = d </> p </> getDest m
putStrLn $ "Installing " ++ f ++ " to " ++ destdir
createDirectoryIfMissing True destdir
copyFile f (destdir </> takeFileName f)
return ()
where getDest (UN n) = ""
getDest (NS n ns) = foldl1' (</>) (reverse (getDest n : map str ns))
installIdx :: String -> IO ()
installIdx p = do d <- getTargetDir
let f = pkgIndex p
let destdir = d </> p
putStrLn $ "Installing " ++ f ++ " to " ++ destdir
createDirectoryIfMissing True destdir
copyFile f (destdir </> takeFileName f)
return ()
installObj :: String -> String -> IO ()
installObj p o = do d <- getTargetDir
let destdir = addTrailingPathSeparator (d </> p)
putStrLn $ "Installing " ++ o ++ " to " ++ destdir
createDirectoryIfMissing True destdir
copyFile o (destdir </> takeFileName o)
return ()
#ifdef mingw32_HOST_OS
mkDirCmd = "mkdir "
#else
mkDirCmd = "mkdir -p "
#endif
inPkgDir :: PkgDesc -> IO a -> IO a
inPkgDir pkgdesc action =
do dir <- getCurrentDirectory
when (sourcedir pkgdesc /= "") $
do putStrLn $ "Entering directory `" ++ ("." </> sourcedir pkgdesc) ++ "'"
setCurrentDirectory $ dir </> sourcedir pkgdesc
res <- action
when (sourcedir pkgdesc /= "") $
do putStrLn $ "Leaving directory `" ++ ("." </> sourcedir pkgdesc) ++ "'"
setCurrentDirectory dir
return res
-- ------------------------------------------------------- [ Makefile Commands ]
-- | Invoke a Makefile's default target.
make :: Maybe String -> IO ()
make Nothing = return ()
make (Just s) = do rawSystem "make" ["-f", s]
return ()
-- | Invoke a Makefile's clean target.
clean :: Maybe String -> IO ()
clean Nothing = return ()
clean (Just s) = do rawSystem "make" ["-f", s, "clean"]
return ()
-- --------------------------------------------------------------------- [ EOF ]
| osa1/Idris-dev | src/Pkg/Package.hs | bsd-3-clause | 11,857 | 0 | 24 | 4,586 | 3,140 | 1,498 | 1,642 | 232 | 4 |
{-# LANGUAGE GADTs, TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Machine.Is
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : GADTs, Type Families
--
----------------------------------------------------------------------------
module Data.Machine.Is
( Is(..)
) where
import Control.Category
import Data.Monoid
import Prelude
-- | Witnessed type equality
data Is a b where
Refl :: Is a a
instance Show (Is a b) where
showsPrec _ Refl = showString "Refl"
instance Eq (Is a b) where
Refl == Refl = True
{-# INLINE (==) #-}
instance Ord (Is a b) where
Refl `compare` Refl = EQ
{-# INLINE compare #-}
instance (a ~ b) => Monoid (Is a b) where
mempty = Refl
{-# INLINE mempty #-}
mappend Refl Refl = Refl
{-# INLINE mappend #-}
instance (a ~ b) => Read (Is a b) where
readsPrec d = readParen (d > 10) (\r -> [(Refl,s) | ("Refl",s) <- lex r ])
instance Category Is where
id = Refl
{-# INLINE id #-}
Refl . Refl = Refl
{-# INLINE (.) #-}
| fumieval/machines | src/Data/Machine/Is.hs | bsd-3-clause | 1,192 | 0 | 12 | 249 | 296 | 168 | 128 | 28 | 0 |
module B1 (myFringe) where
import D1 ()
import D1 hiding (sumSquares, fringe)
import D1 (fringe)
import C1 hiding (myFringe)
myFringe :: (Tree a) -> [a]
myFringe (Leaf x) = [x]
myFringe (Branch left right) = myFringe right
sumSquares ((x : xs)) = (x ^ 2) + (sumSquares xs)
sumSquares [] = 0
| kmate/HaRe | old/testing/mkImpExplicit/B1AST.hs | bsd-3-clause | 296 | 0 | 8 | 57 | 143 | 81 | 62 | 10 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.HcPkg
-- Copyright : Duncan Coutts 2009, 2013
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module provides an library interface to the @hc-pkg@ program.
-- Currently only GHC, GHCJS and LHC have hc-pkg programs.
module Distribution.Simple.Program.HcPkg (
HcPkgInfo(..),
init,
invoke,
register,
reregister,
unregister,
expose,
hide,
dump,
list,
-- * Program invocations
initInvocation,
registerInvocation,
reregisterInvocation,
unregisterInvocation,
exposeInvocation,
hideInvocation,
dumpInvocation,
listInvocation,
) where
import Prelude hiding (init)
import Distribution.Package
( PackageId, InstalledPackageId(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo, InstalledPackageInfo(..)
, showInstalledPackageInfo
, emptyInstalledPackageInfo, fieldsInstalledPackageInfo )
import Distribution.ParseUtils
import Distribution.Simple.Compiler
( PackageDB(..), PackageDBStack )
import Distribution.Simple.Program.Types
( ConfiguredProgram(programId) )
import Distribution.Simple.Program.Run
( ProgramInvocation(..), IOEncoding(..), programInvocation
, runProgramInvocation, getProgramInvocationOutput )
import Distribution.Text
( display, simpleParse )
import Distribution.Simple.Utils
( die )
import Distribution.Verbosity
( Verbosity, deafening, silent )
import Distribution.Compat.Exception
( catchExit )
import Data.Char
( isSpace )
import Data.List
( stripPrefix )
import System.FilePath as FilePath
( (</>), splitPath, splitDirectories, joinPath, isPathSeparator )
import qualified System.FilePath.Posix as FilePath.Posix
-- | Information about the features and capabilities of an @hc-pkg@
-- program.
--
data HcPkgInfo = HcPkgInfo
{ hcPkgProgram :: ConfiguredProgram
, noPkgDbStack :: Bool -- ^ no package DB stack supported
, noVerboseFlag :: Bool -- ^ hc-pkg does not support verbosity flags
, flagPackageConf :: Bool -- ^ use package-conf option instead of package-db
, useSingleFileDb :: Bool -- ^ requires single file package database
}
-- | Call @hc-pkg@ to initialise a package database at the location {path}.
--
-- > hc-pkg init {path}
--
init :: HcPkgInfo -> Verbosity -> FilePath -> IO ()
init hpi verbosity path =
runProgramInvocation verbosity (initInvocation hpi verbosity path)
-- | Run @hc-pkg@ using a given package DB stack, directly forwarding the
-- provided command-line arguments to it.
invoke :: HcPkgInfo -> Verbosity -> PackageDBStack -> [String] -> IO ()
invoke hpi verbosity dbStack extraArgs =
runProgramInvocation verbosity invocation
where
args = packageDbStackOpts hpi dbStack ++ extraArgs
invocation = programInvocation (hcPkgProgram hpi) args
-- | Call @hc-pkg@ to register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
register :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
register hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(registerInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to re-register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
reregister :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
reregister hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(reregisterInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to unregister a package
--
-- > hc-pkg unregister [pkgid] [--user | --global | --package-db]
--
unregister :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
unregister hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(unregisterInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to expose a package.
--
-- > hc-pkg expose [pkgid] [--user | --global | --package-db]
--
expose :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
expose hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(exposeInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to hide a package.
--
-- > hc-pkg hide [pkgid] [--user | --global | --package-db]
--
hide :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
hide hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(hideInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to get all the details of all the packages in the given
-- package database.
--
dump :: HcPkgInfo -> Verbosity -> PackageDB -> IO [InstalledPackageInfo]
dump hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(dumpInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " dump failed"
case parsePackages output of
Left ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " dump'"
where
parsePackages str =
let parsed = map parseInstalledPackageInfo' (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Left [ setInstalledPackageId
. maybe id mungePackagePaths (pkgRoot pkg)
$ pkg
| ParseOk _ pkg <- parsed ]
msgs -> Right msgs
parseInstalledPackageInfo' =
parseFieldsFlat fieldsInstalledPackageInfo emptyInstalledPackageInfo
--TODO: this could be a lot faster. We're doing normaliseLineEndings twice
-- and converting back and forth with lines/unlines.
splitPkgs :: String -> [String]
splitPkgs = checkEmpty . map unlines . splitWith ("---" ==) . lines
where
-- Handle the case of there being no packages at all.
checkEmpty [s] | all isSpace s = []
checkEmpty ss = ss
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
mungePackagePaths :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
mungePackagePaths pkgroot pkginfo =
pkginfo {
importDirs = mungePaths (importDirs pkginfo),
includeDirs = mungePaths (includeDirs pkginfo),
libraryDirs = mungePaths (libraryDirs pkginfo),
frameworkDirs = mungePaths (frameworkDirs pkginfo),
haddockInterfaces = mungePaths (haddockInterfaces pkginfo),
haddockHTMLs = mungeUrls (haddockHTMLs pkginfo)
}
where
mungePaths = map mungePath
mungeUrls = map mungeUrl
mungePath p = case stripVarPrefix "${pkgroot}" p of
Just p' -> pkgroot </> p'
Nothing -> p
mungeUrl p = case stripVarPrefix "${pkgrooturl}" p of
Just p' -> toUrlPath pkgroot p'
Nothing -> p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath (r : FilePath.splitDirectories p)
stripVarPrefix var p =
case splitPath p of
(root:path') -> case stripPrefix var root of
Just [sep] | isPathSeparator sep -> Just (joinPath path')
_ -> Nothing
_ -> Nothing
-- Older installed package info files did not have the installedPackageId
-- field, so if it is missing then we fill it as the source package ID.
setInstalledPackageId :: InstalledPackageInfo -> InstalledPackageInfo
setInstalledPackageId pkginfo@InstalledPackageInfo {
installedPackageId = InstalledPackageId "",
sourcePackageId = pkgid
}
= pkginfo {
--TODO use a proper named function for the conversion
-- from source package id to installed package id
installedPackageId = InstalledPackageId (display pkgid)
}
setInstalledPackageId pkginfo = pkginfo
-- | Call @hc-pkg@ to get the source package Id of all the packages in the
-- given package database.
--
-- This is much less information than with 'dump', but also rather quicker.
-- Note in particular that it does not include the 'InstalledPackageId', just
-- the source 'PackageId' which is not necessarily unique in any package db.
--
list :: HcPkgInfo -> Verbosity -> PackageDB
-> IO [PackageId]
list hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(listInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " list failed"
case parsePackageIds output of
Just ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " list'"
where
parsePackageIds = sequence . map simpleParse . words
--------------------------
-- The program invocations
--
initInvocation :: HcPkgInfo -> Verbosity -> FilePath -> ProgramInvocation
initInvocation hpi verbosity path =
programInvocation (hcPkgProgram hpi) args
where
args = ["init", path]
++ verbosityOpts hpi verbosity
registerInvocation, reregisterInvocation
:: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation = registerInvocation' "register"
reregisterInvocation = registerInvocation' "update"
registerInvocation' :: String -> HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation' cmdname hpi verbosity packagedbs (Left pkgFile) =
programInvocation (hcPkgProgram hpi) args
where
args = [cmdname, pkgFile]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
registerInvocation' cmdname hpi verbosity packagedbs (Right pkgInfo) =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeInput = Just (showInstalledPackageInfo pkgInfo),
progInvokeInputEncoding = IOEncodingUTF8
}
where
args = [cmdname, "-"]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
unregisterInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
unregisterInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["unregister", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
exposeInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
exposeInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["expose", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
hideInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
hideInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["hide", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
dumpInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
dumpInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["dump", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
listInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
listInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["list", "--simple-output", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
packageDbStackOpts :: HcPkgInfo -> PackageDBStack -> [String]
packageDbStackOpts hpi dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> "--global"
: "--user"
: map specific dbs
(GlobalPackageDB:dbs) -> "--global"
: ("--no-user-" ++ packageDbFlag hpi)
: map specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
specific _ = ierror
ierror :: a
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
packageDbFlag :: HcPkgInfo -> String
packageDbFlag hpi
| flagPackageConf hpi
= "package-conf"
| otherwise
= "package-db"
packageDbOpts :: HcPkgInfo -> PackageDB -> String
packageDbOpts _ GlobalPackageDB = "--global"
packageDbOpts _ UserPackageDB = "--user"
packageDbOpts hpi (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
verbosityOpts :: HcPkgInfo -> Verbosity -> [String]
verbosityOpts hpi v
| noVerboseFlag hpi
= []
| v >= deafening = ["-v2"]
| v == silent = ["-v0"]
| otherwise = []
| x-y-z/cabal | Cabal/Distribution/Simple/Program/HcPkg.hs | bsd-3-clause | 14,214 | 0 | 18 | 3,628 | 2,855 | 1,521 | 1,334 | 250 | 5 |
{- Criterion-based benchmarks. Criterion displays and minimises the impact
of time variance and charts the results. -}
import Criterion.Main
import System.Environment (withArgs)
import qualified HledgerMain
main = defaultMain [
bench "balance_100x100x10" $ nfIO $ withArgs ["balance", "-f", "100x100x10.ledger", ">/dev/null"] HledgerMain.main
]
| kmels/hledger | tools/criterionbench.hs | gpl-3.0 | 362 | 0 | 9 | 58 | 62 | 35 | 27 | 5 | 1 |
module Type.Constrain.Literal where
import qualified AST.Literal as L
import qualified Reporting.Error.Type as Error
import qualified Reporting.Region as R
import qualified Type.Type as T
import qualified Type.Environment as Env
constrain
:: Env.Environment
-> R.Region
-> L.Literal
-> T.Type
-> IO T.TypeConstraint
constrain env region literal tipe =
do tipe' <- litType
return (T.CEqual (Error.Literal name) region tipe tipe')
where
prim name =
return (Env.get env Env.types name)
litType =
case literal of
L.IntNum _ -> T.varN `fmap` T.variable (T.Is T.Number)
L.FloatNum _ -> prim "Float"
L.Chr _ -> prim "Char"
L.Str _ -> prim "String"
L.Boolean _ -> prim "Bool"
name =
case literal of
L.IntNum _ -> "number"
L.FloatNum _ -> "float"
L.Chr _ -> "character"
L.Str _ -> "string"
L.Boolean _ -> "boolean"
| Axure/elm-compiler | src/Type/Constrain/Literal.hs | bsd-3-clause | 1,004 | 0 | 14 | 322 | 321 | 165 | 156 | 31 | 9 |
import InferTests (allTests)
import qualified Test.Framework as TestFramework
main :: IO ()
main = TestFramework.defaultMain allTests
| aleksj/lamdu | test/test_Infer.hs | gpl-3.0 | 135 | 0 | 6 | 17 | 37 | 21 | 16 | 4 | 1 |
{-# LANGUAGE RecordWildCards #-}
module T8448 where
data R = R {r :: Int}
f x = undefined [] {r = x}
| urbanslug/ghc | testsuite/tests/rename/should_fail/T8448.hs | bsd-3-clause | 104 | 0 | 8 | 25 | 41 | 24 | 17 | 4 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Control.Teardown.Internal.Printer where
import RIO hiding ((<>))
import Data.Typeable (typeOf)
import qualified RIO.Text as Text
import Data.Text.Prettyprint.Doc
import Control.Teardown.Internal.Types
treeTrunk :: Int -> Int -> Doc ann
treeTrunk start level = hcat (map (\_ -> " ") [1 .. start])
<> hcat (map (\_ -> " |") [start .. level - 1])
-- | Renders an ASCII Tree with the "TeardownResult" of a "Teardown" sub-routine
-- execution
prettyTeardownResult :: TeardownResult -> Doc ann
prettyTeardownResult result = render 0 0 result <> hardline
where
renderError start level (SomeException err) =
let
(fstErrLine, errLines) = case Text.lines (tshow err) of
[] ->
error "Expecting reported error to have a line of content, got none"
(fstErrLine' : errLines') -> (fstErrLine', errLines')
errorReport =
treeTrunk (start - 1) (level + 1)
<> ">"
<> indent 2 (pretty (show (typeOf err)) <> ":")
<+> pretty (Text.unpack fstErrLine)
: map
(\l -> treeTrunk (start - 1) (level + 1) <> ">" <> indent
2
(pretty $ Text.unpack l)
)
errLines
in
vcat errorReport
renderTree start level disposeResults = case disposeResults of
[] -> mempty
[lastResult] ->
treeTrunk start (level + 1) <> render (start + 1) (level + 1) lastResult
(r : results) ->
treeTrunk start (level + 1)
<> render start (level + 1) r
<> hardline
<> renderTree start level results
render start level disposeResult = case disposeResult of
EmptyResult desc ->
"`-" <+> "✓" <+> pretty (Text.unpack desc) <+> "(empty)"
LeafResult desc elapsed Nothing ->
"`-" <+> "✓" <+> pretty (Text.unpack desc) <+> pretty
("(" <> show elapsed <> ")")
LeafResult desc elapsed (Just err) ->
"`-"
<+> "✘"
<+> pretty (Text.unpack desc)
<+> pretty ("(" <> show elapsed <> ")")
<> hardline
<> renderError start level err
BranchResult desc elapsed didFail results -> vcat
[ "`-"
<+> (if didFail then "✘" else "✓")
<+> pretty (Text.unpack desc)
<+> parens (pretty $ show elapsed)
, renderTree start level results
]
| roman/Haskell-teardown | src/Control/Teardown/Internal/Printer.hs | isc | 2,429 | 0 | 21 | 723 | 772 | 398 | 374 | 58 | 8 |
import Control.Applicative
import Control.Monad
import Data.List
data KnightPos = KP Int Int KnightPos | Start deriving Show
instance Eq KnightPos where
(KP lx ly lk) == (KP rx ry rk) = lx == rx
&& ly == ry
-- && lk == rk
-- Start == Start = True
_ == _ = False
moveKnight :: KnightPos -> [KnightPos]
moveKnight p@(KP c r _) = do
(c', r', p') <- [(a, b, p) | (a, b) <- [ (c+2, r-1), (c+2, r+1)
, (c-2, r-1), (c-2, r+1)
, (c+1, r-2), (c+1, r+2)
, (c-1, r-2), (c-1, r+2)
] ]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return $ KP c' r' p'
getsIn3 :: KnightPos -> KnightPos -> [KnightPos]
getsIn3 from to = filter (== to) result
where result = return from
>>= moveKnight
>>= moveKnight
>>= moveKnight
flatten :: KnightPos -> [KnightPos]
flatten Start = []
flatten (KP c r k) = KP c r Start : flatten k
moveSomewhereUnique :: KnightPos -> [KnightPos]
moveSomewhereUnique from = filter once result
where result = moveKnight from
once = (==) <$>
length . flatten <*>
length . nub . flatten
makeNUniqueSteps :: Int -> KnightPos -> [KnightPos]
makeNUniqueSteps 0 a = return a
makeNUniqueSteps n k = result >>= makeNUniqueSteps (n-1)
where result = nubBy unique $
moveSomewhereUnique k
unique l r = (0 ==) . length $
intersect (flatten l) (flatten r)
| sukhmel/experiments.haskell | knight.hs | mit | 2,030 | 0 | 13 | 1,019 | 641 | 346 | 295 | 38 | 1 |
-- List Sum using folds
mysuml xs = foldl (+) 0 xs
mysumr xs = foldr (+) 0 xs
smallestDivisor n = helper 2 n
where helper x n | x * x > n = n
| n `rem` x == 0 = x
| otherwise = if x ==2
then helper (x+1) n
else helper (x+2) n
isPrime n = if n == 1
then False
else smallestDivisor n == n
-- General Accumulation
genAccumulate combiner f initVal n filterFunc = foldl (\x y -> combiner x $ f y) initVal $ filter filterFunc [1..n]
length_foldl xs = foldl (\acc _ -> acc + 1) 0 xs
length_foldr xs = foldr (\_ acc -> 1 + acc) 0 xs
reverse_foldl xs = foldl (\acc x -> x : acc) [] xs
reverse_foldr xs = foldr (\x acc -> x : acc) [] xs
| gitrookie/functionalcode | code/Haskell/snippets/folds.hs | mit | 763 | 0 | 11 | 281 | 342 | 174 | 168 | 16 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Hspec
import Database.Persist.Quasi
import Database.Persist.Types
main :: IO ()
main = hspec $ do
describe "tokenization" $ do
it "handles normal words" $
tokenize " foo bar baz" `shouldBe`
[ Spaces 1
, Token "foo"
, Spaces 3
, Token "bar"
, Spaces 2
, Token "baz"
]
it "handles quotes" $
tokenize " \"foo bar\" \"baz\"" `shouldBe`
[ Spaces 2
, Token "foo bar"
, Spaces 2
, Token "baz"
]
it "handles unnested parantheses" $
tokenize " (foo bar) (baz)" `shouldBe`
[ Spaces 2
, Token "foo bar"
, Spaces 2
, Token "baz"
]
it "handles nested parantheses" $
tokenize " (foo (bar)) (baz)" `shouldBe`
[ Spaces 2
, Token "foo (bar)"
, Spaces 2
, Token "baz"
]
it "escaping " $
tokenize " (foo \\(bar) \"baz\\\"\"" `shouldBe`
[ Spaces 2
, Token "foo (bar"
, Spaces 2
, Token "baz\""
]
describe "parseFieldType" $ do
it "simple types" $
parseFieldType "FooBar" `shouldBe` Just (FTTypeCon Nothing "FooBar")
it "module types" $
parseFieldType "Data.Map.FooBar" `shouldBe` Just (FTTypeCon (Just "Data.Map") "FooBar")
it "application" $
parseFieldType "Foo Bar" `shouldBe` Just (
FTTypeCon Nothing "Foo" `FTApp` FTTypeCon Nothing "Bar")
it "application multiple" $
parseFieldType "Foo Bar Baz" `shouldBe` Just (
(FTTypeCon Nothing "Foo" `FTApp` FTTypeCon Nothing "Bar")
`FTApp` FTTypeCon Nothing "Baz"
)
it "parens" $ do
let foo = FTTypeCon Nothing "Foo"
bar = FTTypeCon Nothing "Bar"
baz = FTTypeCon Nothing "Baz"
parseFieldType "Foo (Bar Baz)" `shouldBe` Just (
foo `FTApp` (bar `FTApp` baz))
it "lists" $ do
let foo = FTTypeCon Nothing "Foo"
bar = FTTypeCon Nothing "Bar"
bars = FTList bar
baz = FTTypeCon Nothing "Baz"
parseFieldType "Foo [Bar] Baz" `shouldBe` Just (
foo `FTApp` bars `FTApp` baz)
describe "stripId" $ do
it "works" $
(parseFieldType "FooId" >>= stripId) `shouldBe` Just "Foo"
| gbwey/persistentold | persistent/test/main.hs | mit | 2,728 | 0 | 19 | 1,196 | 645 | 318 | 327 | 67 | 1 |
{-# LANGUAGE PackageImports, TypeSynonymInstances, FlexibleInstances #-}
module Prelude(
module CorePrelude,
module IORef,
(++),
unpack,
error,
P.show,
P.length
) where
import CorePrelude hiding (on, error)
import qualified "base" Prelude as P
import qualified Data.Text as T
import Data.IORef as IORef
class Concatable a where
(++) :: a -> a -> a
instance Concatable [a] where
(++) = (P.++)
instance Concatable T.Text where
(++) = T.append
class StringLike a where
unpack :: a -> String
instance StringLike String where
unpack = id
instance StringLike T.Text where
unpack = T.unpack
error :: StringLike string => string -> b
error = P.error . unpack | zsedem/haskell-playground | gitcommander/src/Prelude.hs | mit | 712 | 0 | 8 | 161 | 210 | 127 | 83 | 27 | 1 |
module Test.Hspec.Wai.Matcher (
ResponseMatcher(..)
, match
) where
import Control.Monad
import Data.Monoid
import Data.Functor
import Data.String
import Data.Text.Lazy.Encoding (encodeUtf8)
import qualified Data.ByteString.Lazy as LB
import Network.HTTP.Types
import Network.Wai.Test
import Test.Hspec.Wai.Util
data ResponseMatcher = ResponseMatcher {
matchStatus :: Int
, matchHeaders :: [Header]
, matchBody :: Maybe LB.ByteString
}
instance IsString ResponseMatcher where
fromString s = ResponseMatcher 200 [] (Just . encodeUtf8 . fromString $ s)
instance Num ResponseMatcher where
fromInteger n = ResponseMatcher (fromInteger n) [] Nothing
(+) = error "ResponseMatcher does not support (+)"
(-) = error "ResponseMatcher does not support (-)"
(*) = error "ResponseMatcher does not support (*)"
abs = error "ResponseMatcher does not support `abs`"
signum = error "ResponseMatcher does not support `signum`"
match :: SResponse -> ResponseMatcher -> Maybe String
match (SResponse (Status status _) headers body) (ResponseMatcher expectedStatus expectedHeaders expectedBody) = mconcat [
actualExpected "status mismatch:" (show status) (show expectedStatus) <$ guard (status /= expectedStatus)
, checkHeaders headers expectedHeaders
, expectedBody >>= matchBody_ body
]
where
matchBody_ actual expected = actualExpected "body mismatch:" actual_ expected_ <$ guard (actual /= expected)
where
(actual_, expected_) = case (safeToString $ LB.toStrict actual, safeToString $ LB.toStrict expected) of
(Just x, Just y) -> (x, y)
_ -> (show actual, show expected)
actualExpected :: String -> String -> String -> String
actualExpected message actual expected = unlines [
message
, " expected: " ++ expected
, " but got: " ++ actual
]
checkHeaders :: [Header] -> [Header] -> Maybe String
checkHeaders actual expected = case filter (`notElem` actual) expected of
[] -> Nothing
missing ->
let msg
| length missing == 1 = "missing header:"
| otherwise = "missing headers:"
in Just $ unlines (msg : formatHeaders missing ++ "the actual headers were:" : formatHeaders actual)
where
formatHeaders = map ((" " ++) . formatHeader)
| begriffs/hspec-wai | src/Test/Hspec/Wai/Matcher.hs | mit | 2,357 | 0 | 16 | 542 | 652 | 349 | 303 | 48 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Hafer.Export.ExportMethod
( module Hafer.Export.ExportMethod
) where
class ExportMethod g o where
exprt :: g -> o
| ooz/Hafer | src/Hafer/Export/ExportMethod.hs | mit | 167 | 0 | 7 | 28 | 37 | 22 | 15 | 5 | 0 |
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-}
module Timed where
import Control.Lens
import Control.Arrow ((&&&))
import Control.Lens.TH
import Data.List
import Data.Ord
import List
data Timed m = Timed {
_ttl :: Int,
_hits :: Int,
_message :: m
}
deriving Show
$(makeLenses ''Timed)
decTimed :: Timed m -> Timed m
decTimed = over ttl $ subtract 1
hit :: Timed m -> Timed m
hit = over hits (+1)
least :: [Timed m] -> Maybe (m,Int)
least [] = Nothing
least xs = Just . (view message &&& view ttl). head . sortBy (comparing $ view hits) $ xs
hitm :: Eq m => (m,Int) -> [Timed m] -> [Timed m]
hitm (x,t) ys = maybe (Timed t 1 x:ys) (\(c,f) -> f $ hit c) $ select ((==x) . view message) $ ys
type TimedTimed m = Timed (Timed m)
-- eliminate all timed values where time is over (negative) after subtracting 1
turn :: [Timed m] -> [Timed m]
turn = filter ((>0) . view ttl) . map decTimed
| paolino/touchnet | Timed.hs | mit | 936 | 0 | 11 | 221 | 413 | 222 | 191 | 26 | 1 |
{-# LANGUAGE Safe #-}
module Control.Concurrent.Transactional.EventHandle (
EventHandle (), newEventHandle, wrapEvent
) where
import Control.Concurrent.Transactional.Event.Base
import Control.Monad (void)
import Data.IORef (IORef, newIORef, mkWeakIORef)
-- |Event handles are values that fire an event when they are garbage collected.
data EventHandle = EventHandle { unEventHandle :: IORef () }
-- |Creates a new event handle, and returns it along with an event that becomes
-- available when the event handle is garbage collected.
newEventHandle :: Event (EventHandle, Event ())
newEventHandle = do
(waitFront, waitBack) <- swap
unsafeLiftIO $ do
ref <- newIORef ()
void $ mkWeakIORef ref $ sync $ waitFront ()
return (EventHandle ref, waitBack ())
-- |Associates an event handle with an event. As long as the event remains
-- alive, so will the event handle.
wrapEvent :: EventHandle -> Event a -> Event a
wrapEvent = fmap . seq . unEventHandle
| YellPika/Hannel | src/Control/Concurrent/Transactional/EventHandle.hs | mit | 991 | 0 | 13 | 185 | 213 | 117 | 96 | 19 | 1 |
module HTMLTokenizer.Parsing
(
token,
attribute,
name,
)
where
import HTMLTokenizer.Prelude hiding (takeWhile)
import HTMLTokenizer.Data
import Data.Attoparsec.Text
import HTMLEntities.Parser (htmlEntity)
import qualified Text.Builder as A
import qualified HTMLTokenizer.MonadPlus as B
import qualified VectorBuilder.MonadPlus as C
import qualified Data.Text as D
{-|
Token parser, which also decodes entities.
-}
token :: Parser Token
token =
labeled "HTML Token" $
join
(mplus
(do
char '<'
mplus
(do
char '!'
mplus
(string "--" $> commentTagBody)
(asciiCI "doctype" $> doctypeTagBody))
(mplus
(char '/' $> closingTagBody)
(pure
(mplus
openingTagBody
(pure (TextToken "<"))))))
(pure (TextToken <$> textBetweenTags)))
where
commentTagBody =
labeled "Comment" (CommentToken . A.run <$> loop mempty)
where
loop !builder =
do
textWithoutDashes <- A.text <$> takeWhile (/= '-')
mplus
(string "-->" $> builder <> textWithoutDashes)
(mplus
(char '-' *> loop (builder <> textWithoutDashes <> A.char '-'))
(return (builder <> textWithoutDashes)))
where
textWithoutDashes =
A.text <$> takeWhile1 (/= '-')
doctypeTagBody =
labeled "Doctype" $ do
space
skipSpace
contents <- takeWhile1 (/= '>')
char '>'
return (DoctypeToken contents)
closingTagBody =
labeled "Closing tag" $
skipSpace *> (ClosingTagToken <$> name) <* skipSpace <* char '>'
openingTagBody =
labeled "Opening tag" $ do
skipSpace
tagName <- name
attributes <- C.many (space *> skipSpace *> attribute)
skipSpace
closed <- (char '/' $> True) <|> pure False
char '>'
return (OpeningTagToken tagName attributes closed)
textBetweenTags :: Parser Text
textBetweenTags =
labeled "Text between tags" $ do
prefixSpace <- (space *> skipSpace $> A.char ' ') <|> pure mempty
text <- loop prefixSpace mempty
if A.null text
then mzero
else return (A.run text)
where
loop !builder !unconsumedSpace =
mplus word end
where
word =
do
parsedWord <- word
space <- takeWhile isSpace
if D.null space
then return (builder <> A.text unconsumedSpace <> parsedWord)
else loop (builder <> A.text unconsumedSpace <> parsedWord) space
where
word =
B.concat1 (normalChunk <|> entity <|> ampersand)
where
normalChunk =
A.text <$> takeWhile1 (\ x -> not (isSpace x) && x /= '<' && x /= '&')
entity =
A.text <$> htmlEntity
ampersand =
A.char <$> char '&'
end =
if D.null unconsumedSpace
then return builder
else return (builder <> A.char ' ')
attribute :: Parser Attribute
attribute =
labeled "Attribute" $ do
attributeName <- name
mplus
(do
skipSpace
char '='
skipSpace
attributeValue <- msum (map quotedContent ['"', '\'', '`']) <|> unquotedContent
return (Attribute attributeName attributeValue))
(return (Attribute attributeName ""))
quotedContent :: Char -> Parser Text
quotedContent quotChar =
char quotChar *> (A.run <$> B.concat escapedContentChunk) <* char quotChar
where
escapedContentChunk =
normal <|> entity <|> escaped <|> failedEscaping
where
normal =
A.text <$> takeWhile1 (\ x -> x /= quotChar && x /= '&' && x /= '\\')
entity =
A.text <$> htmlEntity
escaped =
char '\\' *> (A.char <$> satisfy (\ x -> x == quotChar || x == '\\'))
failedEscaping =
A.char <$> char '\\'
unquotedContent :: Parser Text
unquotedContent =
isolatedTextInsideTag
name :: Parser Name
name =
labeled "Name" $ do
c1 <- D.toLower <$> isolatedTextInsideTag
(mplus
(do
skipSpace
char ':'
skipSpace
c2 <- D.toLower <$> isolatedTextInsideTag
return (PrefixedName c1 c2))
(return (UnprefixedName c1)))
isolatedTextInsideTag :: Parser Text
isolatedTextInsideTag =
A.run <$> B.concat1 (normal <|> entity <|> ampersand)
where
normal =
A.text <$> takeWhile1 predicate
where
predicate x =
x /= '>' && x /= '/' && not (isSpace x) && x /= '=' &&
x /= '&' && x /= '<' &&
x /= '"' && x /= '\'' && x /= '`'
entity =
A.text <$> htmlEntity
ampersand =
A.char <$> char '&'
shouldFail :: Parser a -> Parser ()
shouldFail p =
join ((p $> empty) <|> pure (pure ()))
skipSpaceLeaving1 :: Parser ()
skipSpaceLeaving1 =
mplus
(do
space
peekedChar <- peekChar'
if isSpace peekedChar
then skipSpaceLeaving1
else mzero)
(return ())
{-# INLINE labeled #-}
labeled :: String -> Parser a -> Parser a
labeled label parser =
parser <?> label
| nikita-volkov/html-tokenizer | library/HTMLTokenizer/Parsing.hs | mit | 5,270 | 0 | 24 | 1,778 | 1,576 | 782 | 794 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies, ViewPatterns, MultiParamTypeClasses, FlexibleInstances #-}
module Main where
{-
Simple demonstration of building routes
Note: Look at the code in subsites/ for an example of building the same functionality as a subsite.
-}
import Wai.Routes
import Network.Wai.Handler.Warp
import Network.Wai.Application.Static
import qualified Data.Text as T
import Data.Maybe (fromMaybe)
-- The Master Site argument
data MyRoute = MyRoute
-- Generate routing code
mkRoute "MyRoute" [parseRoutes|
/ HomeR GET
/hello HelloR GET
/post PostR POST
/upper UpperR:
/ UpperBasementR GET
/lower LowerR:
/ LowerBasementR GET
|]
-- Handlers
-- Homepage
getHomeR :: Handler MyRoute
getHomeR = runHandlerM $ do
Just r <- maybeRoute
html $ T.concat
[ "<h1>Home</h1>"
, "<p>You are on route - ", showRoute r, "</p>"
, "<p>"
, "<a href=\"", showRoute HelloR, "\">Go to hello</a>"
, " to be greeted!"
, "</p>"
, "<p>"
, "<a href=\"", showRoute (UpperR UpperBasementR), "\">Explore the basement</a>"
, "</p>"
]
-- Hello
getHelloR :: Handler MyRoute
getHelloR = runHandlerM $ do
html $ T.concat
[ "<h1>Hello World!</h1>"
, "<a href=\"", showRoute HomeR, "\">Go back</a>"
]
-- Post parameters (getParam can also be used for query params)
postPostR :: Handler MyRoute
postPostR = runHandlerM $ do
name' <- getParam "name"
let name = fromMaybe "unnamed" name'
html $ T.concat
[ "<h1>Hello '", name, "'!</h1>"
, "<a href=\"", showRoute HomeR, "\">Go back</a>"
]
-- Nested hierarchical routes
getUpperBasementR :: Handler MyRoute
getUpperBasementR = runHandlerM $ do
html $ T.concat
[ "<h1>You are at the upper basement!</h1>"
, "<p>"
, "<a href=\"", showRoute HomeR, "\">Go back up</a>"
, "</p>"
, "<p>"
, "<a href=\"", showRoute (UpperR $ LowerR LowerBasementR), "\">Take the stairs down</a>"
, "</p>"
]
getLowerBasementR :: Handler MyRoute
getLowerBasementR = runHandlerM $ do
html $ T.concat
[ "<h1>You found the lower basement!</h1>"
, "<a href=\"", showRoute (UpperR UpperBasementR), "\">Take the stairs up</a>"
]
-- An example of an unrouted handler
handleInfoRequest :: Handler DefaultMaster
handleInfoRequest = runHandlerM $ do
Just (DefaultRoute (_,query)) <- maybeRoute
case lookup "info" query of
-- If an override param "info" was supplied then display info
Just _ -> plain "Wai-routes, hello world example, handleInfoRequest"
-- Else, move on to the next handler (i.e. do nothing special)
Nothing -> next
-- The application that uses our route
-- NOTE: We use the Route Monad to simplify routing
application :: RouteM ()
application = do
middleware logStdoutDev
handler handleInfoRequest
route MyRoute
catchall $ staticApp $ defaultFileServerSettings "static"
-- Run the application
main :: IO ()
main = do
putStrLn "Starting server on port 8080"
run 8080 $ waiApp application
| ajnsit/wai-routes | examples/hello-world/src/Main.hs | mit | 3,022 | 0 | 14 | 616 | 570 | 305 | 265 | 65 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- | A 'MonadSTM' implementation, which can be run on top of 'IO' or
-- 'ST'.
module Test.DejaFu.STM
( -- * The @STMLike@ Monad
STMLike
, STMST
, STMIO
, Result(..)
, runTransaction
, runTransactionST
, runTransactionIO
-- * Software Transactional Memory
, retry
, orElse
, check
, throwSTM
, catchSTM
-- * @CTVar@s
, CTVar
, CTVarId
, newCTVar
, readCTVar
, writeCTVar
) where
import Control.Exception (Exception, SomeException(..))
import Control.Monad (liftM)
import Control.Monad.Catch (MonadCatch(..), MonadThrow(..))
import Control.Monad.Cont (cont)
import Control.Monad.ST (ST, runST)
import Data.IORef (IORef)
import Data.STRef (STRef)
import Test.DejaFu.Internal
import Test.DejaFu.STM.Internal
import qualified Control.Monad.STM.Class as C
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative)
#endif
{-# ANN module ("HLint: ignore Use record patterns" :: String) #-}
-- | The 'MonadSTM' implementation, it encapsulates a single atomic
-- transaction. The environment, that is, the collection of defined
-- 'CTVar's is implicit, there is no list of them, they exist purely
-- as references. This makes the types simpler, but means you can't
-- really get an aggregate of them (if you ever wanted to for some
-- reason).
newtype STMLike t n r a = S { unS :: M t n r a } deriving (Functor, Applicative, Monad)
-- | A convenience wrapper around 'STMLike' using 'STRef's.
type STMST t a = STMLike t (ST t) (STRef t) a
-- | A convenience wrapper around 'STMLike' using 'IORef's.
type STMIO t a = STMLike t IO IORef a
instance MonadThrow (STMLike t n r) where
throwM = throwSTM
instance MonadCatch (STMLike t n r) where
catch = catchSTM
instance Monad n => C.MonadSTM (STMLike t n r) where
type CTVar (STMLike t n r) = CTVar t r
retry = retry
orElse = orElse
newCTVar = newCTVar
readCTVar = readCTVar
writeCTVar = writeCTVar
-- | Abort the current transaction, restoring any 'CTVar's written to,
-- and returning the list of 'CTVar's read.
retry :: Monad n => STMLike t n r a
retry = S $ cont $ const ARetry
-- | Run the first transaction and, if it 'retry's,
orElse :: Monad n => STMLike t n r a -> STMLike t n r a -> STMLike t n r a
orElse a b = S $ cont $ AOrElse (unS a) (unS b)
-- | Check whether a condition is true and, if not, call 'retry'.
check :: Monad n => Bool -> STMLike t n r ()
check = C.check
-- | Throw an exception. This aborts the transaction and propagates
-- the exception.
throwSTM :: Exception e => e -> STMLike t n r a
throwSTM e = S $ cont $ const $ AThrow (SomeException e)
-- | Handling exceptions from 'throwSTM'.
catchSTM :: Exception e => STMLike t n r a -> (e -> STMLike t n r a) -> STMLike t n r a
catchSTM stm handler = S $ cont $ ACatch (unS stm) (unS . handler)
-- | Create a new 'CTVar' containing the given value.
newCTVar :: Monad n => a -> STMLike t n r (CTVar t r a)
newCTVar a = S $ cont lifted where
lifted c = ANew $ \ref ctvid -> c `liftM` newCTVar' ref ctvid
newCTVar' ref ctvid = (\r -> V (ctvid, r)) `liftM` newRef ref a
-- | Return the current value stored in a 'CTVar'.
readCTVar :: Monad n => CTVar t r a -> STMLike t n r a
readCTVar ctvar = S $ cont $ ARead ctvar
-- | Write the supplied value into the 'CTVar'.
writeCTVar :: Monad n => CTVar t r a -> a -> STMLike t n r ()
writeCTVar ctvar a = S $ cont $ \c -> AWrite ctvar a $ c ()
-- | Run a transaction in the 'ST' monad, starting from a clean
-- environment, and discarding the environment afterwards. This is
-- suitable for testing individual transactions, but not for composing
-- multiple ones.
runTransaction :: (forall t. STMST t a) -> Result a
runTransaction ma = fst $ runST $ runTransactionST ma 0
-- | Run a transaction in the 'ST' monad, returning the result and new
-- initial 'CTVarId'. If the transaction ended by calling 'retry', any
-- 'CTVar' modifications are undone.
runTransactionST :: STMST t a -> CTVarId -> ST t (Result a, CTVarId)
runTransactionST = runTransactionM fixedST where
fixedST = refST $ \mb -> cont (\c -> ALift $ c `liftM` mb)
-- | Run a transaction in the 'IO' monad, returning the result and new
-- initial 'CTVarId'. If the transaction ended by calling 'retry', any
-- 'CTVar' modifications are undone.
runTransactionIO :: STMIO t a -> CTVarId -> IO (Result a, CTVarId)
runTransactionIO = runTransactionM fixedIO where
fixedIO = refIO $ \mb -> cont (\c -> ALift $ c `liftM` mb)
-- | Run a transaction in an arbitrary monad.
runTransactionM :: Monad n
=> Fixed t n r -> STMLike t n r a -> CTVarId -> n (Result a, CTVarId)
runTransactionM ref ma ctvid = do
(res, undo, ctvid') <- doTransaction ref (unS ma) ctvid
case res of
Success _ _ _ -> return (res, ctvid')
_ -> undo >> return (res, ctvid)
| bitemyapp/dejafu | Test/DejaFu/STM.hs | mit | 4,959 | 0 | 13 | 1,056 | 1,323 | 722 | 601 | 82 | 2 |
module Sieve
( primesUpTo
) where
-- You should not use any of the division operations when implementing
-- the sieve of Eratosthenes.
import Prelude hiding (div, divMod, mod, quot, quotRem, rem, (/))
import Data.Set (Set)
import qualified Data.Set as Set
primesUpTo :: Integer -> [Integer]
primesUpTo n = sieveUpTo [2 .. n] n
sieveUpTo [] _ = []
sieveUpTo (prime:xs) n = prime : sieveUpTo xs' n
where
xs' = xs `without` multiples
multiples = Set.fromList . takeWhile (<= n) $ [x * prime | x <- [2 .. n]]
xs `without` set = Set.toList . (Set.\\ set) . Set.fromList $ xs
| enolive/exercism | haskell/sieve/src/Sieve.hs | mit | 613 | 0 | 11 | 146 | 220 | 128 | 92 | 12 | 1 |
module Geometry.Vector (
Scalar,
Vector,
(<+>),
(<->),
(<*>),
mult,
vecSum,
normalise,
computeBisector,
computeReflection
) where
import Prelude hiding ((<*>))
type Scalar = Double
type Vector = (Scalar, Scalar, Scalar)
(<+>) :: Vector -> Vector -> Vector
(x1, y1, z1) <+> (x2, y2, z2) = (x1+x2, y1+y2, z1+z2)
(<->) :: Vector -> Vector -> Vector
(x1, y1, z1) <-> (x2, y2, z2) = (x1-x2, y1-y2, z1-z2)
(<*>) :: Vector -> Vector -> Scalar
(x1, y1, z1) <*> (x2, y2, z2) = x1*x2 + y1*y2 + z1*z2
mult :: Vector -> Scalar -> Vector
mult (x, y, z) c = (c*x, c*y, c*z)
vecSum :: Vector -> Scalar
vecSum (x, y, z) = x + y + z
mag :: Vector -> Scalar
mag (x, y, z) = sqrt $ x*x + y*y + z*z
normalise :: Vector -> Vector
normalise (x, y, z) = (x/m, y/m, z/m)
where m = mag (x, y, z)
computeBisector :: Vector -> Vector -> Vector
computeBisector x y = mult sumVec (1/sumMag)
where sumVec = x <+> y
sumMag = mag sumVec
-- ray-direction surface-normal
-- returns the reflection direction
computeReflection :: Vector -> Vector -> Vector
computeReflection direction normal = direction <-> mult normal (2* (direction <*> normal))
| dongy7/raytracer | src/Geometry/Vector.hs | mit | 1,155 | 0 | 10 | 247 | 575 | 333 | 242 | 35 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString as B
import Data.ByteString.Builder
import qualified Data.ByteString.Char8 as C
import Data.Char (toLower)
import Data.Maybe
import Data.Monoid
import System.IO
import qualified Pipes as P
import qualified Pipes.ByteString as PB
import qualified Pipes.Parse as PP
import qualified Pipes.Attoparsec as PA
data Package = Package String PkgBody deriving Show
data PkgBody = PkgBody { relocated :: Bool
, depend :: [String]
, containermd5 :: Maybe String
, srccontainermd5 :: Maybe String
, doccontainermd5 :: Maybe String
} deriving Show
-- key, value, and maybe files
data Entry = Entry String String [String] deriving Show
buildPackage :: Package -> Builder
buildPackage (Package name (PkgBody{..})) = mconcat $ map ((indent <>) . (<> char7 '\n')) lines
where
indent = string7 " "
equals = string7 " = "
quote str = char7 '"' <> string7 str <> char7 '"'
lines = [quote name <> equals <> char7 '{']
++ map ((indent <>) . (<> char7 ';')) rest
++ [string7 "};"]
rest = [ string7 "relocated" <> equals <> string7 (map toLower $ show relocated)
, string7 "depend" <> equals <> char7 '[' <> deps <> char7 ']'
] ++ md5 "containermd5" containermd5
++ md5 "srccontainermd5" srccontainermd5
++ md5 "doccontainermd5" doccontainermd5
md5 str = maybeToList . fmap (\m -> string7 str <> equals <> quote m)
deps = foldr (\l r -> quote (archify l) <> char7 ' ' <> r) mempty depend
archify str = case splitAt (length str - 4) str of
(left, "ARCH") -> left ++ "${arch}"
_ -> str
entry :: Parser Entry
entry = Entry <$> (many1 (satisfy inValue) <* char ' ')
<*> manyTill anyChar endOfLine
<*> many' (char ' ' *> manyTill anyChar (char '\n'))
where
inValue = (||) <$> isDigit <*> ((||) <$> isAlpha_ascii <*> (==) '-')
exactlyOne :: [a] -> Maybe a
exactlyOne [a] = Just a
exactlyOne _ = Nothing
lookupOne :: String -> [Entry] -> Maybe String
lookupOne = ((.).(.)) exactlyOne lookupMany
lookupMany :: String -> [Entry] -> [String]
lookupMany key entries = [ value | Entry k value _ <- entries, k == key ]
toPkgBody :: [Entry] -> PkgBody
toPkgBody = PkgBody <$> (maybe False (const True) <$> (lookupOne "relocated"))
<*> lookupMany "depend"
<*> lookupOne "containermd5"
<*> lookupOne "srccontainermd5"
<*> lookupOne "doccontainermd5"
toPackage :: [Entry] -> Maybe Package
toPackage ((Entry "name" name _):rest) = Just . Package name $ toPkgBody rest
toPackage _ = Nothing
main :: IO ()
main = do
putStrLn "arch: {"
maybe (return ()) (hPutStrLn stderr) <$> PP.evalStateT parser PB.stdin
putStrLn "}"
where
parser :: PP.Parser B.ByteString IO (Maybe String)
parser = do
parsed <- PA.parse (many1 entry <* endOfLine)
case parsed of
Nothing -> return Nothing
Just (Left (PA.ParsingError _ msg)) -> return (Just msg)
Just (Right entries) -> case toPackage entries of
Nothing -> return (Just "malformed package")
Just pkg -> PP.lift (hPutBuilder stdout (buildPackage pkg)) >> parser
-- main :: IO ()
-- main = putStrLn "arch: {" >> getPackages' >> putStrLn "}"
-- where
-- getPackages' = getPackages (Partial (parse package))
-- getPackages (Fail _ _ reason) = putStrLn reason
-- getPackages (Partial f) = do
-- eof <- hIsEOF stdin
-- if eof
-- then return ()
-- else do
-- line <- B.hGetLine stdin
-- getPackages (f (line <> C.pack "\n"))
-- getPackages (Done i r) = do
-- hPutBuilder stdout (buildPackage r)
-- getPackages'
-- package :: Parser Package
-- package = do
-- entries <- many' entry
-- case toPackage entries of
-- Just package -> return package
-- Nothing -> fail "package had no name"
| nickspinale/nix-tex | tl-pkgs/tl2nix/Main.hs | mit | 4,280 | 1 | 20 | 1,257 | 1,192 | 632 | 560 | 76 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Eval (
evalText,
evalFile,
runParseTest,
safeExec,
-- testing
runASTinEnv,
basicEnv,
fileToEvalForm,
textToEvalForm,
getFileContents
) where
import Prim ( primEnv, unop )
import Parser ( readExpr, readExprFile )
import LispVal
( LispException(Default, PError, UnboundVar, TypeMismatch,
BadSpecialForm, NotFunction),
IFunc(IFunc),
LispVal(..),
Eval(unEval),
EnvCtx(..),
showVal )
import Data.Map as Map
( empty, fromList, insert, lookup, partition, toList, union, Map )
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Directory ( doesFileExist )
import Text.Parsec ( ParseError )
import Control.Monad.Reader
( asks, MonadIO(liftIO), MonadReader(local, ask), ReaderT(runReaderT) )
import Control.Exception
( try, throw, Exception(fromException), SomeException )
funcEnv :: Map.Map T.Text LispVal
funcEnv = Map.fromList $ primEnv
<> [("read" , Fun $ IFunc $ unop readFn),
("parse", Fun $ IFunc $ unop parseFn),
("eval", Fun $ IFunc $ unop eval),
("show", Fun $ IFunc $ unop (return . String . showVal))]
basicEnv :: EnvCtx
basicEnv = EnvCtx Map.empty funcEnv
readFn :: LispVal -> Eval LispVal
readFn (String txt) = lineToEvalForm txt
readFn val = throw $ TypeMismatch "read expects string, instead got: " val
parseFn :: LispVal -> Eval LispVal
parseFn (String txt) = either (throw . PError . show) return $ readExpr txt
parseFn val = throw $ TypeMismatch "parse expects string, instead got: " val
safeExec :: IO a -> IO (Either String a)
safeExec m = do
result <- Control.Exception.try m
case result of
Left (eTop :: SomeException) ->
case fromException eTop of
Just (enclosed :: LispException) -> return $ Left (show enclosed)
Nothing -> return $ Left (show eTop)
Right val -> return $ Right val
runASTinEnv :: EnvCtx -> Eval b -> IO b
runASTinEnv code action = runReaderT (unEval action) code
lineToEvalForm :: T.Text -> Eval LispVal
lineToEvalForm input = either (throw . PError . show ) eval $ readExpr input
evalFile :: FilePath -> T.Text -> IO () --program file
evalFile filePath fileExpr = runASTinEnv basicEnv (fileToEvalForm filePath fileExpr) >>= print
fileToEvalForm :: FilePath -> T.Text -> Eval LispVal
fileToEvalForm filePath input = either (throw . PError . show ) evalBody $ readExprFile filePath input
runParseTest :: T.Text -> T.Text -- for view AST
runParseTest input = either (T.pack . show) (T.pack . show) $ readExpr input
sTDLIB :: FilePath
sTDLIB = "lib/stdlib.scm"
endOfList :: LispVal -> LispVal -> LispVal
endOfList (List x) expr = List $ x ++ [expr]
endOfList n _ = throw $ TypeMismatch "failure to get variable: " n
parseWithLib :: T.Text -> T.Text -> Either ParseError LispVal
parseWithLib std inp = do
stdlib <- readExprFile sTDLIB std
expr <- readExpr inp
return $ endOfList stdlib expr
getFileContents :: FilePath -> IO T.Text
getFileContents fname = do
exists <- doesFileExist fname
if exists then TIO.readFile fname else return "File does not exist."
textToEvalForm :: T.Text -> T.Text -> Eval LispVal
textToEvalForm std input = either (throw . PError . show ) evalBody $ parseWithLib std input
evalText :: T.Text -> IO () --REPL
evalText textExpr = do
stdlib <- getFileContents sTDLIB
res <- runASTinEnv basicEnv $ textToEvalForm stdlib textExpr
print res
getVar :: LispVal -> Eval LispVal
getVar (Atom atom) = do
EnvCtx{..} <- ask
case Map.lookup atom (Map.union fenv env) of -- lookup, but prefer functions
Just x -> return x
Nothing -> throw $ UnboundVar atom
getVar n = throw $ TypeMismatch "failure to get variable: " n
ensureAtom :: LispVal -> Eval LispVal
ensureAtom n@(Atom _) = return n
ensureAtom n = throw $ TypeMismatch "expected an atomic value" n
extractVar :: LispVal -> T.Text
extractVar (Atom atom) = atom
extractVar n = throw $ TypeMismatch "expected an atomic value" n
getEven :: [t] -> [t]
getEven [] = []
getEven (x:xs) = x : getOdd xs
getOdd :: [t] -> [t]
getOdd [] = []
getOdd (_:xs) = getEven xs
applyLambda :: LispVal -> [LispVal] -> [LispVal] -> Eval LispVal
applyLambda expr params args = bindArgsEval params args expr
bindArgsEval :: [LispVal] -> [LispVal] -> LispVal -> Eval LispVal
bindArgsEval params args expr = do
EnvCtx{..} <- ask
let newVars = zipWith (\a b -> (extractVar a,b)) params args
let (newEnv, newFenv) = Map.partition (not . isLambda) $ Map.fromList newVars
local (const $ EnvCtx (newEnv <> env) (newFenv <> fenv)) $ eval expr
isLambda :: LispVal -> Bool
isLambda (List ((Atom "lambda"):_)) = True
isLambda _ = False
eval :: LispVal -> Eval LispVal
eval (List [Atom "dumpEnv", x]) = do
EnvCtx{..} <- ask
liftIO $ print $ toList env
liftIO $ print $ toList fenv
eval x
eval (Number i) = return $ Number i
eval (String s) = return $ String s
eval (Bool b) = return $ Bool b
eval (List []) = return Nil
eval Nil = return Nil
eval n@(Atom _) = getVar n
eval (List [Atom "showSF", rest]) = return . String . T.pack $ show rest
eval (List ((:) (Atom "showSF") rest)) = return . String . T.pack . show $ List rest
eval (List [Atom "quote", val]) = return val
eval (List [Atom "if", predicate, truExpr, flsExpr]) = do
ifRes <- eval predicate
case ifRes of
(Bool True) -> eval truExpr
(Bool False) -> eval flsExpr
_ -> throw $ BadSpecialForm "if's first arg must eval into a boolean"
eval (List ( (:) (Atom "if") _)) = throw $ BadSpecialForm "(if <bool> <s-expr> <s-expr>)"
eval (List [Atom "begin", rest]) = evalBody rest
eval (List ((:) (Atom "begin") rest )) = evalBody $ List rest
eval (List [Atom "define", varExpr, defExpr]) = do --top-level define
EnvCtx{} <- ask
_varAtom <- ensureAtom varExpr
_evalVal <- eval defExpr
bindArgsEval [varExpr] [defExpr] varExpr
eval (List [Atom "let", List pairs, expr]) = do
EnvCtx{} <- ask
atoms <- mapM ensureAtom $ getEven pairs
vals <- mapM eval $ getOdd pairs
bindArgsEval atoms vals expr
eval (List (Atom "let":_) ) = throw $ BadSpecialForm "let function expects list of parameters and S-Expression body\n(let <pairs> <s-expr>)"
eval (List [Atom "lambda", List params, expr]) = do
asks (Lambda (IFunc $ applyLambda expr params))
eval (List (Atom "lambda":_) ) = throw $ BadSpecialForm "lambda function expects list of parameters and S-Expression body\n(lambda <params> <s-expr>)"
-- needed to get cadr, etc to work
eval (List [Atom "cdr", List [Atom "quote", List (_:xs)]]) =
return $ List xs
eval (List [Atom "cdr", arg@(List (x:xs))]) =
case x of
-- proxy for if the list can be evaluated
Atom _ -> do val <- eval arg
eval $ List [Atom "cdr", val]
_ -> return $ List xs
eval (List [Atom "car", List [Atom "quote", List (x:_)]]) =
return x
eval (List [Atom "car", arg@(List (x:_))]) =
case x of
Atom _ -> do val <- eval arg
eval $ List [Atom "car", val]
_ -> return x
eval (List ((:) x xs)) = do
EnvCtx{..} <- ask
funVar <- eval x
xVal <- mapM eval xs
--liftIO $ TIO.putStr $ T.concat ["eval:\n ", T.pack $ show all,"\n * fnCall: ", T.pack $ show x, "\n * fnVar ", T.pack $ show funVar,"\n * args: ",T.concat (T.pack . show <$> xVal) ,T.pack "\n"]
case funVar of
(Fun (IFunc internalFn)) -> internalFn xVal
(Lambda (IFunc definedFn) (EnvCtx benv _bfenv)) -> local (const $ EnvCtx benv fenv) $ definedFn xVal
_ -> throw $ NotFunction funVar
eval x = throw $ Default x --fall thru
updateEnv :: T.Text -> LispVal -> EnvCtx -> EnvCtx
updateEnv var e@(Fun _) EnvCtx{..} = EnvCtx env $ Map.insert var e fenv
updateEnv var e@(Lambda _ _) EnvCtx{..} = EnvCtx env $ Map.insert var e fenv
updateEnv var e EnvCtx{..} = EnvCtx (Map.insert var e env) fenv
evalBody :: LispVal -> Eval LispVal
evalBody (List [List ((:) (Atom "define") [Atom var, defExpr]), rest]) = do
evalVal <- eval defExpr
ctx <- ask
local (const $ updateEnv var evalVal ctx) $ eval rest
evalBody (List ((:) (List ((:) (Atom "define") [Atom var, defExpr])) rest)) = do
evalVal <- eval defExpr
ctx <- ask
local (const $ updateEnv var evalVal ctx) $ evalBody $ List rest
evalBody x = eval x
| write-you-a-scheme-v2/scheme | src/Eval.hs | mit | 8,481 | 0 | 16 | 1,904 | 3,294 | 1,667 | 1,627 | 192 | 7 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module DataAnalysis.Application.Prelude
( runAnalysisAppDb
)
where
import Control.Monad.Logger
-- import Control.Monad.Reader (ReaderT)
-- import Data.ByteString (ByteString)
import Data.CSV.Conduit.Persist
import Data.Conduit
import qualified Data.Conduit.List as CL
-- import Data.Default
import Data.IORef
import Data.Proxy
import qualified Data.Text as T
import Data.Time
import DataAnalysis.Application.Dispatch ()
import DataAnalysis.Application.Types
import Database.Persist.Sqlite
import Network.HTTP.Client (newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Skel.MVP.UserModel
import Skel.MVP.UserParameters
import System.IO
-- import Yesod
import Yesod.Static
-- | Run the analysis web app with a conduit from the database.
runAnalysisAppDb
::
Text
-> SqlPersistM a
-> (MvpParams
-> Conduit Security (YesodDB App) DataPoint)
-> IO ()
runAnalysisAppDb title migrate analysis = do
s <- static "static"
man <- newManager tlsManagerSettings
now <- getCurrentTime
pool <- makePool migrate
from <- fmap utctDay getCurrentTime
to <- fmap utctDay getCurrentTime
warpEnv
(App man
title
(getSomeAnalysisDb from to analysis)
s
now
pool)
where getSomeAnalysisDb from to userAnalysis = SomeAnalysis
form
(Left ((\countRef params ->
selectSource ([SecurityDate >=. d | Just d <- [paramsFrom params]] ++
[SecurityDate <=. d | Just d <- [paramsTo params]])
[Asc SecurityDate] =$=
CL.iterM (const (liftIO (modifyIORef' countRef (+1)))) =$=
CL.map entityVal =$=
userAnalysis params)))
(Just (\name source ->
do xs <- liftIO (runResourceT (source $= fromBinary $$ CL.consume))
mapM_ (insert . convert name) xs))
(MvpParams Nothing Nothing)
True
where modifyIORef' :: IORef a -> (a -> a) -> IO ()
modifyIORef' ref f = do
x <- readIORef ref
let x' = f x
x' `seq` writeIORef ref x'
fromBinary =
csvIntoEntities (Proxy :: Proxy Stock) =$=
CL.mapM (either (monadThrow . Ex) return)
convert :: Text -> Stock -> Security
convert name (Stock day _open _high _low close _vol _adj) =
Security name day close
-- | Make a pool and migrate it.
makePool :: SqlPersistM a -> IO ConnectionPool
makePool migrate =
do (fp,h) <- openTempFile "/tmp/" "finance.db"
hClose h
pool <- runNoLoggingT (createSqlitePool (T.pack fp) 1)
day <- fmap utctDay getCurrentTime
runSqlPersistMPool migrate pool
return pool
| teuffy/min-var-ci | src/DataAnalysis/Application/Prelude.hs | mit | 3,251 | 0 | 23 | 1,114 | 784 | 405 | 379 | 78 | 1 |
{-# LANGUAGE CPP, NoImplicitPrelude, PackageImports #-}
module Text.Read.Compat (
module Base
) where
import "base-compat" Text.Read.Compat as Base
| haskell-compat/base-compat | base-compat-batteries/src/Text/Read/Compat.hs | mit | 151 | 0 | 4 | 21 | 23 | 17 | 6 | 4 | 0 |
#! /usr/bin/env runhaskell
import Text.Pandoc.JSON
main :: IO ()
main = toJSONFilter includeMarkdown
includeMarkdown :: Block -> IO Block
includeMarkdown cb@(CodeBlock (_,_,namevals)_) =
case lookup "markdown" namevals of
Just f -> return . RawBlock (Format "markdown") =<< readFile f
Nothing -> return cb
includeMarkdown x = return x
| spanners/dissertation | dissertation/includeMarkdown.hs | mit | 360 | 0 | 12 | 73 | 124 | 62 | 62 | 9 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html
module Stratosphere.ResourceProperties.EC2SpotFleetSpotFleetTagSpecification where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.Tag
-- | Full data type definition for EC2SpotFleetSpotFleetTagSpecification. See
-- 'ec2SpotFleetSpotFleetTagSpecification' for a more convenient
-- constructor.
data EC2SpotFleetSpotFleetTagSpecification =
EC2SpotFleetSpotFleetTagSpecification
{ _eC2SpotFleetSpotFleetTagSpecificationResourceType :: Maybe (Val Text)
, _eC2SpotFleetSpotFleetTagSpecificationTags :: Maybe [Tag]
} deriving (Show, Eq)
instance ToJSON EC2SpotFleetSpotFleetTagSpecification where
toJSON EC2SpotFleetSpotFleetTagSpecification{..} =
object $
catMaybes
[ fmap (("ResourceType",) . toJSON) _eC2SpotFleetSpotFleetTagSpecificationResourceType
, fmap (("Tags",) . toJSON) _eC2SpotFleetSpotFleetTagSpecificationTags
]
-- | Constructor for 'EC2SpotFleetSpotFleetTagSpecification' containing
-- required fields as arguments.
ec2SpotFleetSpotFleetTagSpecification
:: EC2SpotFleetSpotFleetTagSpecification
ec2SpotFleetSpotFleetTagSpecification =
EC2SpotFleetSpotFleetTagSpecification
{ _eC2SpotFleetSpotFleetTagSpecificationResourceType = Nothing
, _eC2SpotFleetSpotFleetTagSpecificationTags = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html#cfn-ec2-spotfleet-spotfleettagspecification-resourcetype
ecsfsftsResourceType :: Lens' EC2SpotFleetSpotFleetTagSpecification (Maybe (Val Text))
ecsfsftsResourceType = lens _eC2SpotFleetSpotFleetTagSpecificationResourceType (\s a -> s { _eC2SpotFleetSpotFleetTagSpecificationResourceType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-tagspecifications.html#cfn-ec2-spotfleet-tags
ecsfsftsTags :: Lens' EC2SpotFleetSpotFleetTagSpecification (Maybe [Tag])
ecsfsftsTags = lens _eC2SpotFleetSpotFleetTagSpecificationTags (\s a -> s { _eC2SpotFleetSpotFleetTagSpecificationTags = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EC2SpotFleetSpotFleetTagSpecification.hs | mit | 2,425 | 0 | 12 | 205 | 265 | 154 | 111 | 28 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-simpledb.html
module Stratosphere.Resources.SDBDomain where
import Stratosphere.ResourceImports
-- | Full data type definition for SDBDomain. See 'sdbDomain' for a more
-- convenient constructor.
data SDBDomain =
SDBDomain
{ _sDBDomainDescription :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToResourceProperties SDBDomain where
toResourceProperties SDBDomain{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::SDB::Domain"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("Description",) . toJSON) _sDBDomainDescription
]
}
-- | Constructor for 'SDBDomain' containing required fields as arguments.
sdbDomain
:: SDBDomain
sdbDomain =
SDBDomain
{ _sDBDomainDescription = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-simpledb.html#cfn-sdb-domain-description
sdbdDescription :: Lens' SDBDomain (Maybe (Val Text))
sdbdDescription = lens _sDBDomainDescription (\s a -> s { _sDBDomainDescription = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/SDBDomain.hs | mit | 1,252 | 0 | 14 | 189 | 186 | 108 | 78 | 24 | 1 |
module Yi.UI.Batch (start) where
import Yi.UI.Common
import Yi.Config
-- | Initialise the ui
start :: UIBoot
start _cfg _ch _outCh _ed = do
mapM_ putStrLn ["Starting 'batch' UI...",
"Are you sure you compiled with support for any real UI?",
"(for example, pass -fvty to cabal install)"]
return dummyUI
| codemac/yi-editor | src/Yi/UI/Batch.hs | gpl-2.0 | 358 | 0 | 8 | 104 | 66 | 37 | 29 | 9 | 1 |
-- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.DataType
-- Copyright : (c) Sven Panne 2002-2009
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : sven.panne@aedion.de
-- Stability : stable
-- Portability : portable
--
-- This is a purely internal module for (un-)marshaling DataType.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.DataType (
DataType(..), marshalDataType, unmarshalDataType
) where
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility (
gl_2_BYTES, gl_3_BYTES, gl_4_BYTES, gl_BITMAP )
import Graphics.Rendering.OpenGL.Raw.Core31
--------------------------------------------------------------------------------
-- basically table 3.2 (pixel data type parameter) plus a few additions
data DataType =
UnsignedByte
| Byte
| UnsignedShort
| Short
| UnsignedInt
| Int
| HalfFloat
| Float
| UnsignedByte332
| UnsignedByte233Rev
| UnsignedShort565
| UnsignedShort565Rev
| UnsignedShort4444
| UnsignedShort4444Rev
| UnsignedShort5551
| UnsignedShort1555Rev
| UnsignedInt8888
| UnsignedInt8888Rev
| UnsignedInt1010102
| UnsignedInt2101010Rev
| UnsignedInt248
| UnsignedInt10f11f11fRev
| UnsignedInt5999Rev
| Float32UnsignedInt248Rev
| Bitmap -- pixel data, deprecated in 3.1
| UnsignedShort88 -- MESA_ycbcr_texture/APPLE_ycbcr_422
| UnsignedShort88Rev -- MESA_ycbcr_texture/APPLE_ycbcr_422
| Double -- vertex arrays (EXT_vertex_array, now core)
| TwoBytes -- CallLists
| ThreeBytes -- CallLists
| FourBytes -- CallLists
deriving ( Eq, Ord, Show )
marshalDataType :: DataType -> GLenum
marshalDataType x = case x of
UnsignedByte -> gl_UNSIGNED_BYTE
Byte -> gl_BYTE
UnsignedShort -> gl_UNSIGNED_SHORT
Short -> gl_SHORT
UnsignedInt -> gl_UNSIGNED_INT
Int -> gl_INT
HalfFloat -> gl_HALF_FLOAT
Float -> gl_FLOAT
UnsignedByte332 -> gl_UNSIGNED_BYTE_3_3_2
UnsignedByte233Rev -> gl_UNSIGNED_BYTE_2_3_3_REV
UnsignedShort565 -> gl_UNSIGNED_SHORT_5_6_5
UnsignedShort565Rev -> gl_UNSIGNED_SHORT_5_6_5_REV
UnsignedShort4444 -> gl_UNSIGNED_SHORT_4_4_4_4
UnsignedShort4444Rev -> gl_UNSIGNED_SHORT_4_4_4_4_REV
UnsignedShort5551 -> gl_UNSIGNED_SHORT_5_5_5_1
UnsignedShort1555Rev -> gl_UNSIGNED_SHORT_1_5_5_5_REV
UnsignedInt8888 -> gl_UNSIGNED_INT_8_8_8_8
UnsignedInt8888Rev -> gl_UNSIGNED_INT_8_8_8_8_REV
UnsignedInt1010102 -> gl_UNSIGNED_INT_10_10_10_2
UnsignedInt2101010Rev -> gl_UNSIGNED_INT_2_10_10_10_REV
UnsignedInt248 -> gl_UNSIGNED_INT_24_8
UnsignedInt10f11f11fRev -> gl_UNSIGNED_INT_10F_11F_11F_REV
UnsignedInt5999Rev -> gl_UNSIGNED_INT_5_9_9_9_REV
Float32UnsignedInt248Rev -> gl_FLOAT_32_UNSIGNED_INT_24_8_REV
Bitmap -> gl_BITMAP
-- TODO: Use UNSIGNED_SHORT_8_8_APPLE from APPLE_ycbcr_422 extension
UnsignedShort88 -> 0x85ba
-- TODO: Use UNSIGNED_SHORT_8_8_REV_APPLE from APPLE_ycbcr_422 extension
UnsignedShort88Rev -> 0x85bb
Double -> gl_DOUBLE
TwoBytes -> gl_2_BYTES
ThreeBytes -> gl_3_BYTES
FourBytes -> gl_4_BYTES
unmarshalDataType :: GLenum -> DataType
unmarshalDataType x
| x == gl_UNSIGNED_BYTE = UnsignedByte
| x == gl_BYTE = Byte
| x == gl_UNSIGNED_SHORT = UnsignedShort
| x == gl_SHORT = Short
| x == gl_UNSIGNED_INT = UnsignedInt
| x == gl_INT = Int
| x == gl_HALF_FLOAT = HalfFloat
| x == gl_FLOAT = Float
| x == gl_UNSIGNED_BYTE_3_3_2 = UnsignedByte332
| x == gl_UNSIGNED_BYTE_2_3_3_REV = UnsignedByte233Rev
| x == gl_UNSIGNED_SHORT_5_6_5 = UnsignedShort565
| x == gl_UNSIGNED_SHORT_5_6_5_REV = UnsignedShort565Rev
| x == gl_UNSIGNED_SHORT_4_4_4_4 = UnsignedShort4444
| x == gl_UNSIGNED_SHORT_4_4_4_4_REV = UnsignedShort4444Rev
| x == gl_UNSIGNED_SHORT_5_5_5_1 = UnsignedShort5551
| x == gl_UNSIGNED_SHORT_1_5_5_5_REV = UnsignedShort1555Rev
| x == gl_UNSIGNED_INT_8_8_8_8 = UnsignedInt8888
| x == gl_UNSIGNED_INT_8_8_8_8_REV = UnsignedInt8888Rev
| x == gl_UNSIGNED_INT_10_10_10_2 = UnsignedInt1010102
| x == gl_UNSIGNED_INT_2_10_10_10_REV = UnsignedInt2101010Rev
| x == gl_UNSIGNED_INT_24_8 = UnsignedInt248
| x == gl_UNSIGNED_INT_10F_11F_11F_REV = UnsignedInt10f11f11fRev
| x == gl_UNSIGNED_INT_5_9_9_9_REV = UnsignedInt5999Rev
| x == gl_FLOAT_32_UNSIGNED_INT_24_8_REV = Float32UnsignedInt248Rev
| x == gl_BITMAP = Bitmap
-- TODO: Use UNSIGNED_SHORT_8_8_APPLE from APPLE_ycbcr_422 extension
| x == 0x85ba = UnsignedShort88
-- TODO: Use UNSIGNED_SHORT_8_8_REV_APPLE from APPLE_ycbcr_422 extension
| x == 0x85bb = UnsignedShort88Rev
| x == gl_DOUBLE = Double
| x == gl_2_BYTES = TwoBytes
| x == gl_3_BYTES = ThreeBytes
| x == gl_4_BYTES = FourBytes
| otherwise = error ("unmarshalDataType: illegal value " ++ show x)
| ducis/haAni | hs/common/Graphics/Rendering/OpenGL/GL/DataType.hs | gpl-2.0 | 5,061 | 0 | 9 | 944 | 840 | 445 | 395 | 105 | 31 |
-- create pqueue
do p1 <- newTChanIO
p2 <- newTChanIO
p3 <- newTChanIO
pQueue <- newTVarIO (p1, p2, p3)
--read pqueue
atomically $
do (p1, p2, p3) <- readTVar pQueue
| RocketPuppy/PupEvents | PQueue.hs | gpl-3.0 | 195 | 0 | 9 | 58 | 72 | 35 | 37 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Estuary.Types.Database where
import Database.SQLite.Simple
import Database.SQLite.Simple.FromRow
import Database.SQLite.Simple.ToRow
import Database.SQLite.Simple.FromField
import Database.SQLite.Simple.ToField
import Database.SQLite.Simple.Ok
import Data.Map as Map
import Data.IntMap as IntMap
import Data.Time.Clock
import Data.Aeson
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as Lazy
import qualified Data.Text.Lazy.Encoding as Lazy
import TextShow
import GHC.Generics
import Data.Aeson
import Control.Concurrent.STM
import Control.Concurrent
import Estuary.Types.View
import Estuary.Types.EnsembleS
import qualified Estuary.Types.Ensemble as Ensemble
import Estuary.Types.ServerState
openDatabase :: IO Connection
openDatabase = do
c <- open "Estuary.db"
createEnsembleTable c
putStrLn "database opened"
return c
closeDatabase :: Connection -> IO ()
closeDatabase = close
createEnsembleTable :: Connection -> IO ()
createEnsembleTable c = do
execute_ c "CREATE TABLE IF NOT EXISTS ensembles (name TEXT NOT NULL, json TEXT, PRIMARY KEY (name))"
data EnsembleD = EnsembleD {
ensemble :: Ensemble.Ensemble,
ownerPassword :: Text,
joinPassword :: Text,
creationTime :: UTCTime,
expiry :: Maybe NominalDiffTime,
lastActionTime :: UTCTime
} deriving (Generic)
instance ToJSON EnsembleD
instance FromJSON EnsembleD
ensembleStoEnsembleD :: EnsembleS -> IO EnsembleD
ensembleStoEnsembleD x = do
t <- atomically $ readTempo x
zs <- atomically $ readZones x
vs <- atomically $ readViews x
rs <- atomically $ readResourceOps x
lat <- atomically $ readTVar $ Estuary.Types.EnsembleS.lastActionTime x
let e = Ensemble.Ensemble {
Ensemble.ensembleName = Estuary.Types.EnsembleS.ensembleName x,
Ensemble.tempo = t,
Ensemble.zones = zs,
Ensemble.views = vs,
Ensemble.resourceOps = rs,
Ensemble.chats = [],
Ensemble.participants = Map.empty,
Ensemble.anonymousParticipants = 0
}
return $ EnsembleD {
ensemble = e,
Estuary.Types.Database.ownerPassword = Estuary.Types.EnsembleS.ownerPassword x,
Estuary.Types.Database.joinPassword = Estuary.Types.EnsembleS.joinPassword x,
Estuary.Types.Database.creationTime = Estuary.Types.EnsembleS.creationTime x,
Estuary.Types.Database.expiry = Estuary.Types.EnsembleS.expiry x,
Estuary.Types.Database.lastActionTime = lat
}
ensembleDtoEnsembleS :: EnsembleD -> IO EnsembleS
ensembleDtoEnsembleS x = do
t <- atomically $ newTVar (Ensemble.tempo (ensemble x))
let zs = Ensemble.zones (ensemble x)
zs' <- atomically (mapM newTVar zs >>= newTVar)
let vs = Ensemble.views (ensemble x)
vs' <- atomically (mapM newTVar vs >>= newTVar)
rs' <- atomically $ newTVar (Ensemble.resourceOps (ensemble x))
lat <- atomically $ newTVar $ Estuary.Types.Database.lastActionTime x
connectionsTvar <- atomically $ newTVar IntMap.empty
namedConnectionsTvar <- atomically $ newTVar IntMap.empty
anonymousConnectionsTvar <- atomically $ newTVar 0
return $ EnsembleS {
Estuary.Types.EnsembleS.ensembleName = Ensemble.ensembleName $ ensemble x,
Estuary.Types.EnsembleS.connections = connectionsTvar,
Estuary.Types.EnsembleS.namedConnections = namedConnectionsTvar,
Estuary.Types.EnsembleS.anonymousConnections = anonymousConnectionsTvar,
Estuary.Types.EnsembleS.ownerPassword = Estuary.Types.Database.ownerPassword x,
Estuary.Types.EnsembleS.joinPassword = Estuary.Types.Database.joinPassword x,
Estuary.Types.EnsembleS.creationTime = Estuary.Types.Database.creationTime x,
Estuary.Types.EnsembleS.expiry = Estuary.Types.Database.expiry x,
Estuary.Types.EnsembleS.lastActionTime = lat,
tempo = t,
zones = zs',
views = vs',
resourceOps = rs'
}
writeEnsemble :: Connection -> EnsembleS -> IO ()
writeEnsemble c e = do
e' <- ensembleStoEnsembleD e
let eName = Estuary.Types.EnsembleS.ensembleName e
execute c "REPLACE INTO ensembles (name,json) VALUES (?,?)" (eName,e')
writeAllEnsembles :: Connection -> ServerState -> IO Int
writeAllEnsembles c ss = do
x <- atomically $ readTVar $ ensembles ss
xs <- mapM readTVarIO x
mapM_ (writeEnsemble c) xs
return $ Map.size xs
deleteEnsemble :: Connection -> Text -> IO ()
deleteEnsemble c eName = execute c "DELETE FROM ensembles WHERE name=?" (Only eName)
readEnsembles :: Connection -> IO (Map Text EnsembleS)
readEnsembles c = do
r <- query_ c "SELECT name,json FROM ensembles" -- [(n,j)]
mapM ensembleDtoEnsembleS $ Map.fromList r
instance ToField EnsembleD where
toField = SQLText . Lazy.toStrict . Lazy.decodeUtf8 . encode
instance FromField EnsembleD where
fromField = f . eitherDecode . g . fieldData
where g (SQLText t) = Lazy.encodeUtf8 $ Lazy.fromStrict t
g _ = Lazy.encodeUtf8 ""
f (Right x) = Database.SQLite.Simple.Ok.Ok x
f (Left x) = error x
| d0kt0r0/estuary | server/src/Estuary/Types/Database.hs | gpl-3.0 | 4,987 | 0 | 13 | 805 | 1,381 | 750 | 631 | 121 | 1 |
module System.DevUtils.Base.Url.File (
File(..),
defaultFile
) where
data File = File {
_path :: FilePath
} deriving (Show, Read)
defaultFile :: File
defaultFile = File {
_path = "/tmp/poop"
}
| adarqui/DevUtils-Base | src/System/DevUtils/Base/Url/File.hs | gpl-3.0 | 201 | 0 | 8 | 38 | 65 | 41 | 24 | 9 | 1 |
{-# LANGUAGE PackageImports #-}
import "TS" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| minamiyama1994/T-shirt-creator | devel.hs | gpl-3.0 | 703 | 0 | 10 | 123 | 186 | 101 | 85 | 23 | 2 |
#!/usr/bin/env runhaskell
--
-- Copyright 2014 Wesley Tanaka <http://wtanaka.com/>
--
-- This file is part of https://github.com/wtanaka/haskell
--
-- https://github.com/wtanaka/haskell 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.
--
-- https://github.com/wtanaka/haskell 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 https://github.com/wtanaka/haskell . If not, see
-- <http://www.gnu.org/licenses/>.
module Main(main) where
import Data.ByteString.Lazy.Builder (Builder)
import Data.Char (ord)
import Data.Int (Int64)
import Data.List (sort)
import Data.Monoid (mappend)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Builder as BSB
import qualified Data.Word8 as Word8
import qualified System.Console.GetOpt as GetOpt
import System.Environment
import System.IO
import Text.Printf
-- Represents a single command line option
data Option =
Bytes
| Lines
| Words
| Help
deriving (Show, Eq)
-- Option requested -- should be one of
data OutputOption =
OutputBytes
| OutputLines
| OutputWords
deriving (Show, Eq)
_optionOrdMap OutputLines = 0
_optionOrdMap OutputWords = 1
_optionOrdMap OutputBytes = 2
instance Ord OutputOption where
compare a b = compare (_optionOrdMap a) (_optionOrdMap b)
_optionFunctionMap :: OutputOption -> BSL.ByteString -> Int64
_optionFunctionMap OutputLines = numLines
_optionFunctionMap OutputBytes = numBytes
_optionFunctionMap OutputWords = numWords
_lf = fromIntegral (ord '\n')
newtype WordCountAccum = WordCountAccum Int
_optDescr :: [GetOpt.OptDescr Option]
_optDescr = [
GetOpt.Option "h" ["help"] (GetOpt.NoArg Help)
"display this help and exit"
, GetOpt.Option "l" ["lines"] (GetOpt.NoArg Lines)
"print the newline counts"
, GetOpt.Option "c" ["bytes"] (GetOpt.NoArg Bytes)
"print the byte counts"
, GetOpt.Option "w" ["words"] (GetOpt.NoArg Words)
"print the word counts"
]
appendEol :: Builder -> Builder
appendEol x = x `mappend` BSB.char7 '\n'
numLines :: BSL.ByteString -> Int64
numLines = BSL.count _lf
numBytes :: BSL.ByteString -> Int64
numBytes = BSL.length
_numWordsStartsWithSpace :: BSL.ByteString -> WordCountAccum -> Int64
_numWordsStartsWithSpace bs (WordCountAccum acc) = let
firstWordIdx = BSL.findIndex (not . Word8.isSpace) bs
in case firstWordIdx of
Nothing -> fromIntegral acc
Just idx ->
_numWordsStartsWithNonSpace (BSL.drop idx bs) (WordCountAccum acc)
_numWordsStartsWithNonSpace :: BSL.ByteString -> WordCountAccum -> Int64
_numWordsStartsWithNonSpace bs (WordCountAccum acc)
| BSL.null bs = fromIntegral acc
| otherwise = let firstSpaceIdx = BSL.findIndex Word8.isSpace bs
in case firstSpaceIdx of
Nothing -> fromIntegral (acc + 1)
Just idx ->
_numWordsStartsWithSpace (BSL.drop idx bs) (WordCountAccum (acc + 1))
numWords :: BSL.ByteString -> Int64
numWords bs
| BSL.null bs = 0
| otherwise = (if Word8.isSpace (BSL.index bs 0)
then _numWordsStartsWithSpace
else _numWordsStartsWithNonSpace) bs (WordCountAccum 0)
leftPadUntil :: (Integral a, PrintfArg a) => Int -> a -> Builder
leftPadUntil n value = BSB.string7 $ printf (concat ["%", show n, "d"]) value
-- Get the output flags (lines, words, bytes) from the given input
-- flags
_outOptions :: [Option] -> [OutputOption]
_outOptions [] = []
-- List everything explicitly so that we get a compile error when we
-- add a new Option type.
-- http://www.haskell.org/haskellwiki/Scrap_your_boilerplate may offer
-- a better approach
_outOptions (x : xs) =
(case x of
Bytes -> (:) OutputBytes
Lines -> (:) OutputLines
Words -> (:) OutputWords
Help -> id) $ _outOptions xs
outOptions :: [Option] -> [OutputOption]
outOptions os = let oos = _outOptions os
in sort $ if null oos then [OutputBytes, OutputLines, OutputWords] else oos
singleFlagInteract :: OutputOption -> BSL.ByteString -> Builder
singleFlagInteract option inputStr =
BSB.string7 $ show (_optionFunctionMap option inputStr)
multiFlagInteract :: [OutputOption] -> BSL.ByteString -> Builder
multiFlagInteract [] _ = BSB.string7 ""
multiFlagInteract (o : os) inputStr =
leftPadUntil 7 (_optionFunctionMap o inputStr)
`mappend` multiFlagInteract os inputStr
interactFunction :: [Option] -> BSL.ByteString -> BSL.ByteString
interactFunction opts inputStr = let outOpts = outOptions opts
in BSB.toLazyByteString $ appendEol (
if 1 == length outOpts
then singleFlagInteract (head outOpts) inputStr
else multiFlagInteract outOpts inputStr)
main :: IO ()
main = do
argv <- getArgs
let (opts, _args, errs) = GetOpt.getOpt GetOpt.RequireOrder _optDescr argv
in if not $ null errs
then ioError (userError
(concat errs ++ GetOpt.usageInfo "" _optDescr))
else
if Help `elem` opts
then
hPutStrLn stderr (GetOpt.usageInfo "" _optDescr)
else
BSL.interact $ interactFunction opts
| wtanaka/haskell | Wc.hs | gpl-3.0 | 5,516 | 0 | 16 | 1,093 | 1,368 | 730 | 638 | 109 | 4 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Sound.Tidal.Dirt where
import Sound.OSC.FD
import qualified Data.Map as Map
import Control.Applicative
import Control.Concurrent.MVar
--import Visual
import Data.Colour.SRGB
import Data.Colour.Names
import Data.Hashable
import Data.Bits
import Data.Maybe
import System.Process
import Sound.Tidal.Stream
import Sound.Tidal.Pattern
import Sound.Tidal.Parse
dirt :: OscShape
dirt = OscShape {path = "/play",
params = [ S "sound" Nothing,
F "offset" (Just 0),
F "begin" (Just 0),
F "end" (Just 1),
F "speed" (Just 1),
F "pan" (Just 0.5),
F "velocity" (Just 0),
S "vowel" (Just ""),
F "cutoff" (Just 0),
F "resonance" (Just 0),
F "accelerate" (Just 0),
F "shape" (Just 0),
I "kriole" (Just 0),
F "gain" (Just 1),
I "cut" (Just (0)),
F "delay" (Just (0)),
F "delaytime" (Just (-1)),
F "delayfeedback" (Just (-1)),
F "crush" (Just 0),
I "coarse" (Just 0),
F "hcutoff" (Just 0),
F "hresonance" (Just 0),
F "bandf" (Just 0),
F "bandq" (Just 0),
S "unit" (Just "rate")
],
cpsStamp = True,
timestamp = MessageStamp,
latency = 0.04,
namedParams = False,
preamble = []
}
kriole :: OscShape
kriole = OscShape {path = "/trigger",
params = [ I "ksymbol" Nothing,
F "kpitch" (Just 1)
],
cpsStamp = False,
timestamp = MessageStamp,
latency = 0.04,
namedParams = False,
preamble = []
}
dirtstart name = start "127.0.0.1" 7771 dirt
dirtStream = stream "127.0.0.1" 7771 dirt
-- disused parameter..
dirtstream _ = dirtStream
kstream name = stream "127.0.0.1" 6040 kriole
doubledirt = do remote <- stream "178.77.72.138" 7777 dirt
local <- stream "192.168.0.102" 7771 dirt
return $ \p -> do remote p
local p
return ()
dirtToColour :: OscPattern -> Pattern ColourD
dirtToColour p = s
where s = fmap (\x -> maybe black (maybe black datumToColour) (Map.lookup (param dirt "sound") x)) p
showToColour :: Show a => a -> ColourD
showToColour = stringToColour . show
datumToColour :: Datum -> ColourD
datumToColour = showToColour
stringToColour :: String -> ColourD
stringToColour s = sRGB (r/256) (g/256) (b/256)
where i = (hash s) `mod` 16777216
r = fromIntegral $ (i .&. 0xFF0000) `shiftR` 16;
g = fromIntegral $ (i .&. 0x00FF00) `shiftR` 8;
b = fromIntegral $ (i .&. 0x0000FF);
{-
visualcallback :: IO (OscPattern -> IO ())
visualcallback = do t <- ticker
mv <- startVis t
let f p = do let p' = dirtToColour p
swapMVar mv p'
return ()
return f
-}
--dirtyvisualstream name = do cb <- visualcallback
-- streamcallback cb "127.0.0.1" "127.0.0.1" name "127.0.0.1" 7771 dirt
sound = makeS dirt "sound"
offset = makeF dirt "offset"
begin = makeF dirt "begin"
end = makeF dirt "end"
speed = makeF dirt "speed"
pan = makeF dirt "pan"
velocity = makeF dirt "velocity"
vowel = makeS dirt "vowel"
cutoff = makeF dirt "cutoff"
resonance = makeF dirt "resonance"
accelerate = makeF dirt "accelerate"
shape = makeF dirt "shape"
gain = makeF dirt "gain"
delay = makeF dirt "delay"
delaytime = makeF dirt "delaytime"
delayfeedback = makeF dirt "delayfeedback"
crush = makeF dirt "crush"
coarse :: Pattern Int -> OscPattern
coarse = makeI dirt "coarse"
hcutoff = makeF dirt "hcutoff"
hresonance = makeF dirt "hresonance"
bandf = makeF dirt "bandf"
bandq = makeF dirt "bandq"
unit = makeS dirt "unit"
cut :: Pattern Int -> OscPattern
cut = makeI dirt "cut"
ksymbol = makeF kriole "ksymbol"
kpitch = makeF kriole "kpitch"
pick :: String -> Int -> String
pick name n = name ++ "/" ++ (show n)
striate :: Int -> OscPattern -> OscPattern
striate n p = cat $ map (\x -> off (fromIntegral x) p) [0 .. n-1]
where off i p = p
|+| begin (atom (fromIntegral i / fromIntegral n))
|+| end (atom (fromIntegral (i+1) / fromIntegral n))
striate' :: Int -> Double -> OscPattern -> OscPattern
striate' n f p = cat $ map (\x -> off (fromIntegral x) p) [0 .. n-1]
where off i p = p |+| begin (atom (slot * i) :: Pattern Double) |+| end (atom ((slot * i) + f) :: Pattern Double)
slot = (1 - f) / (fromIntegral n)
striateO :: OscPattern -> Int -> Double -> OscPattern
striateO p n o = cat $ map (\x -> off (fromIntegral x) p) [0 .. n-1]
where off i p = p |+| begin ((atom $ (fromIntegral i / fromIntegral n) + o) :: Pattern Double) |+| end ((atom $ (fromIntegral (i+1) / fromIntegral n) + o) :: Pattern Double)
metronome = slow 2 $ sound (p "[odx, [hh]*8]")
| unthingable/Tidal | Sound/Tidal/Dirt.hs | gpl-3.0 | 5,767 | 0 | 17 | 2,256 | 1,736 | 913 | 823 | 121 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EMR.DescribeJobFlows
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This API is deprecated and will eventually be removed. We recommend you use 'ListClusters', 'DescribeCluster', 'ListSteps', 'ListInstanceGroups' and 'ListBootstrapActions'
-- instead.
--
-- DescribeJobFlows returns a list of job flows that match all of the supplied
-- parameters. The parameters can include a list of job flow IDs, job flow
-- states, and restrictions on job flow creation date and time.
--
-- Regardless of supplied parameters, only job flows created within the last
-- two months are returned.
--
-- If no parameters are supplied, then job flows matching either of the
-- following criteria are returned:
--
-- Job flows created and completed in the last two weeks Job flows created
-- within the last two months that are in one of the following states: 'RUNNING', 'WAITING', 'SHUTTING_DOWN', 'STARTING' Amazon Elastic MapReduce can return a maximum of
-- 512 job flow descriptions.
--
-- <http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_DescribeJobFlows.html>
module Network.AWS.EMR.DescribeJobFlows
(
-- * Request
DescribeJobFlows
-- ** Request constructor
, describeJobFlows
-- ** Request lenses
, djfCreatedAfter
, djfCreatedBefore
, djfJobFlowIds
, djfJobFlowStates
-- * Response
, DescribeJobFlowsResponse
-- ** Response constructor
, describeJobFlowsResponse
-- ** Response lenses
, djfrJobFlows
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.EMR.Types
import qualified GHC.Exts
data DescribeJobFlows = DescribeJobFlows
{ _djfCreatedAfter :: Maybe POSIX
, _djfCreatedBefore :: Maybe POSIX
, _djfJobFlowIds :: List "JobFlowIds" Text
, _djfJobFlowStates :: List "JobFlowStates" JobFlowExecutionState
} deriving (Eq, Read, Show)
-- | 'DescribeJobFlows' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'djfCreatedAfter' @::@ 'Maybe' 'UTCTime'
--
-- * 'djfCreatedBefore' @::@ 'Maybe' 'UTCTime'
--
-- * 'djfJobFlowIds' @::@ ['Text']
--
-- * 'djfJobFlowStates' @::@ ['JobFlowExecutionState']
--
describeJobFlows :: DescribeJobFlows
describeJobFlows = DescribeJobFlows
{ _djfCreatedAfter = Nothing
, _djfCreatedBefore = Nothing
, _djfJobFlowIds = mempty
, _djfJobFlowStates = mempty
}
-- | Return only job flows created after this date and time.
djfCreatedAfter :: Lens' DescribeJobFlows (Maybe UTCTime)
djfCreatedAfter = lens _djfCreatedAfter (\s a -> s { _djfCreatedAfter = a }) . mapping _Time
-- | Return only job flows created before this date and time.
djfCreatedBefore :: Lens' DescribeJobFlows (Maybe UTCTime)
djfCreatedBefore = lens _djfCreatedBefore (\s a -> s { _djfCreatedBefore = a }) . mapping _Time
-- | Return only job flows whose job flow ID is contained in this list.
djfJobFlowIds :: Lens' DescribeJobFlows [Text]
djfJobFlowIds = lens _djfJobFlowIds (\s a -> s { _djfJobFlowIds = a }) . _List
-- | Return only job flows whose state is contained in this list.
djfJobFlowStates :: Lens' DescribeJobFlows [JobFlowExecutionState]
djfJobFlowStates = lens _djfJobFlowStates (\s a -> s { _djfJobFlowStates = a }) . _List
newtype DescribeJobFlowsResponse = DescribeJobFlowsResponse
{ _djfrJobFlows :: List "JobFlows" JobFlowDetail
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeJobFlowsResponse where
type Item DescribeJobFlowsResponse = JobFlowDetail
fromList = DescribeJobFlowsResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _djfrJobFlows
-- | 'DescribeJobFlowsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'djfrJobFlows' @::@ ['JobFlowDetail']
--
describeJobFlowsResponse :: DescribeJobFlowsResponse
describeJobFlowsResponse = DescribeJobFlowsResponse
{ _djfrJobFlows = mempty
}
-- | A list of job flows matching the parameters supplied.
djfrJobFlows :: Lens' DescribeJobFlowsResponse [JobFlowDetail]
djfrJobFlows = lens _djfrJobFlows (\s a -> s { _djfrJobFlows = a }) . _List
instance ToPath DescribeJobFlows where
toPath = const "/"
instance ToQuery DescribeJobFlows where
toQuery = const mempty
instance ToHeaders DescribeJobFlows
instance ToJSON DescribeJobFlows where
toJSON DescribeJobFlows{..} = object
[ "CreatedAfter" .= _djfCreatedAfter
, "CreatedBefore" .= _djfCreatedBefore
, "JobFlowIds" .= _djfJobFlowIds
, "JobFlowStates" .= _djfJobFlowStates
]
instance AWSRequest DescribeJobFlows where
type Sv DescribeJobFlows = EMR
type Rs DescribeJobFlows = DescribeJobFlowsResponse
request = post "DescribeJobFlows"
response = jsonResponse
instance FromJSON DescribeJobFlowsResponse where
parseJSON = withObject "DescribeJobFlowsResponse" $ \o -> DescribeJobFlowsResponse
<$> o .:? "JobFlows" .!= mempty
| dysinger/amazonka | amazonka-emr/gen/Network/AWS/EMR/DescribeJobFlows.hs | mpl-2.0 | 5,908 | 0 | 10 | 1,156 | 739 | 444 | 295 | 76 | 1 |
-- Copyright 2011 by Joshua Simmons <joshua.simmons@emptypath.com>
module Canvas where
import qualified Data.Map as M
import Control.Monad.State
import Text.Printf
import Data.List
import Game
import SGF
import qualified Graphics.Rendering.Cairo as C
import Data.Ord (comparing)
import Config
data Canvas s c = -- stateType and canvas result type
Canvas { setupCanvas :: Point -- board size
-> (Point, Point) -- view rectangle (UL, BR), inclusive
-> (Integer, Integer) -- available screen space (pixels)
-> c
-> StateT s IO c
, nextPlayer :: Color
-> c
-> StateT s IO c
, placeStone :: (Point, Color)
-> c
-> StateT s IO c
, placeMark :: (Point, MarkType)
-> c
-> StateT s IO c
, finalize :: c
-> StateT s IO c
, initState :: s
}
printOn :: Canvas s a -> a -> Game -> IO a
printOn c init g' =
do (a, s) <- runStateT (setupStep
>>= nextPlayerStep
>>= stoneSteps
>>= markSteps
>>= finalizeStep) (initState c)
return a
where setupStep = (setupCanvas c) (bs g) (v g) screenSpace init
nextPlayerStep = (nextPlayer c) (toPlay g)
stoneSteps x = foldl' (>>=) (return x) (map (placeStone c) (M.assocs (stones $ board g)))
markSteps x = foldl' (>>=) (return x) (map (placeMark c) (M.assocs (marks g)))
finalizeStep = (finalize c)
bs g = size $ board g
v g = simpleView ((M.keys $ stones $ board g) ++ (M.keys $ marks g) ++ (view g))
(bs g)
resultingStoneSize g = snd $ pixelMap (v g) screenSpace
g = maxBy resultingStoneSize g' (flipBoard g')
maxBy f a b = if f a < f b then b else a
simpleView :: [Point] -> Point -> (Point, Point)
simpleView pps (a, b) =
fixup $ foldl' minMax init pps
where init = ((a, b), (-1, -1))
minMax ((lx, ly), (gx, gy)) (x, y) = ((min x lx, min y ly), (max x gx, max y gy))
(a', b') = (a - 1, b - 1)
-- fixup too small view, including negative view if pps == []
fixup ((lx, ly), (gx, gy)) = if (((gx - lx) < 4 && (gy - ly) < 4) ||
(gx - lx) <= 0 || (gy - ly) <= 0)
then ((0, 0), (a', b'))
else fixup' $
((max (lx - margin) 0 , max (ly - margin) 0),
(min (gx + margin) a', min (gy + margin) b'))
margin = 2 -- extra space around view
-- fixup' move view to board edges if it's already close
-- makes board sized problems look much nicer
fixup' ((lx, ly), (gx, gy)) = ((lx', ly'), (gx', gy'))
where lx' = if lx <= 3 then 0 else lx
ly' = if ly <= 3 then 0 else ly
gx' = if a' - gx <= 3 then a' else gx
gy' = if b' - gy <= 3 then b' else gy
-- integer division
(//) :: (Integral a) => a -> a -> a
a // b = truncate $ (fromIntegral a) / (fromIntegral b)
pixelMap :: (Point, Point) -> (Integer, Integer) -> ((Point -> Point), Integer)
pixelMap v scSz =
((\(a, b) -> ((a - vxl) * stoneSize, (b - vyl) * stoneSize)), stoneSize)
where stoneSize = if odd stoneSize' then stoneSize' else stoneSize' - 1
stoneSize' = min (stoneSize'' vxl vxg scSzx) (stoneSize'' vyl vyg scSzy)
stoneSize'' l g sz = sz // (g - l + 1)
((vxl,vyl), (vxg, vyg)) = v
(scSzx, scSzy) = scSz
noopSetup _ _ _ = return
noopToPlay _ = return
noopPlaceStone _ = return
noopPlaceMark _ = return
noopFinalize = return
noopCanvas = Canvas { setupCanvas = noopSetup
, nextPlayer = noopToPlay
, placeStone = noopPlaceStone
, placeMark = noopPlaceMark
, finalize = noopFinalize
, initState = ()
}
toplayToPlay color _ = return $ show color
toplayCanvas = noopCanvas{nextPlayer = toplayToPlay}
jsSetup sz v scSz c =
do put (pixelMap v scSz)
return $ c ++ "window.bbls_pts =\n[\n"
jsPlaceStone (p, col) c =
do (m, sz) <- get
let (x', y') = m p
let sz' = sz // 2
return $ c ++ (printf "[%d,%d,%d,%s],\n" x' y' sz' col')
where col' = if col == Black then "\"000000\"" else "\"d0d0d0\""
jsToPlay _ c = return c
jsPlaceMark _ c = return c
jsFinalize c = return $ c ++ "\n]"
jsCanvas = Canvas { setupCanvas = jsSetup
, nextPlayer = jsToPlay
, placeStone = jsPlaceStone
, placeMark = jsPlaceMark
, finalize = jsFinalize
, initState = undefined :: ((Point -> Point), Integer)
}
convertPoint ssz (a, b) = (ssz / 2 + fromIntegral a, ssz / 2 + fromIntegral b)
createBoard scSz@(scw, sch) v@((lx, ly), (gx, gy)) (bw, bh) =
do board <- C.createImageSurface C.FormatARGB32 boardw boardh
C.renderWith board drawBoard
return (board, toPixel, ssz')
where (boardw, boardh) = (fromInteger $ (gx - lx + 1) * ssz,
fromInteger $ (gy - ly + 1) * ssz)
(m, ssz) = pixelMap v scSz
ssz' = fromIntegral ssz
toPixel = convertPoint ssz' . m
toPixelx x = fst $ toPixel (x, undefined)
toPixely y = snd $ toPixel (undefined, y)
boardEdgex x = x == 0 || x == bw - 1
boardEdgey y = y == 0 || y == bh - 1
drawBoard =
do let (bwp, bhp) = (fromIntegral boardw, fromIntegral boardh)
C.setSourceRGBA 0 0 0 0
C.rectangle 0 0 bwp bhp
C.fill
let lxp = if boardEdgex lx then toPixelx lx else 0.5
let lyp = if boardEdgey ly then toPixely ly else 0.5
let gxp = if boardEdgex gx then toPixelx gx else bwp + 0.5
let gyp = if boardEdgey gy then toPixely gy else bhp + 0.5
let setupLine edge = if edge
then C.setSourceRGB 0 0 0
else C.setSourceRGB 0.6 0.6 0.6
let drawLinex x = do setupLine (boardEdgex x)
let xp = toPixelx x
C.moveTo xp lyp
C.lineTo xp gyp
C.stroke
let drawLiney y = do setupLine (boardEdgey y)
let yp = toPixely y
C.moveTo lxp yp
C.lineTo gxp yp
C.stroke
C.setSourceRGB 0.86667 0.73725 0.41960 -- woodish color
C.rectangle lxp lyp (gxp - lxp) (gyp - lyp)
C.fill -- color board
C.setAntialias C.AntialiasNone
C.setLineWidth 1
C.setLineCap C.LineCapSquare
let xlines = map (\x -> (boardEdgex x, drawLinex x)) [lx..gx]
let ylines = map (\y -> (boardEdgey y, drawLiney y)) [ly..gy]
-- draw the board edges last, so they don't get overwritten
foldl1 (>>) $ map snd $ sortBy (comparing fst) $ xlines ++ ylines
let inView (x, y) = x <= gx && y <= gy && x >= lx && y >= ly
let hoshis = filter inView $ hoshiPoints bw bh
let drawHoshi p = do setupLine False
let (x, y) = toPixel p
let rad = if ssz >= 10 then 2 else 1
C.arc x y rad 0 (2 * pi)
C.strokePreserve
C.fill
foldl' (>>) (return ()) $ map drawHoshi hoshis
hoshiPoints w h | w /= h = []
| w < 3 || w == 4 = []
| w == 3 = [(1, 1)]
| w == 5 = [(1, 1), (1, 3), (2, 2), (3, 1), (3, 3)]
| otherwise = cornerHoshi ++ sideHoshi ++ centerHoshi
where (w', h') = (w - 1, h - 1)
ledge = if w < 12 then 2 else 3
hedge = w' - ledge
mid = w // 2
cornerHoshi = [(ledge, ledge), (hedge, hedge), (ledge, hedge), (hedge, ledge)]
sideHoshi = if odd w && w > 12 then [(ledge, mid), (mid, ledge), (hedge, mid), (mid, hedge)] else []
centerHoshi = if odd w then [(mid, mid)] else []
drawStone col pnt (m, ssz) =
do if col == Black then C.setSourceRGB 0 0 0 else C.setSourceRGB 1 1 1
let (xp, yp) = m pnt
C.setAntialias C.AntialiasDefault
C.setLineWidth 1
C.arc xp yp (ssz / 2 - 0.5) 0 (2 * pi)
C.fillPreserve
if ssz > 6 then C.setSourceRGB 0 0 0 else return ()
C.stroke
drawMark p _ (m, ssz) =
do let (xp, yp) = m p
C.setAntialias C.AntialiasDefault
C.setLineWidth (if ssz > 14 then 2 else 1)
C.setSourceRGB 1 0 0
let drawSize = if ssz < 8 then 0.5 else ssz / 6
C.arc xp yp drawSize 0 (2 * pi)
C.stroke
imgSetup sz v scSz _ =
do (board, pixelMap, ssz) <- liftIO $ createBoard scSz v sz
put (pixelMap, ssz)
return board
imgToPlay _ c = return c
imgPlaceStone (pnt, col) c =
do st <- get
liftIO $ C.renderWith c (drawStone col pnt st)
return c
imgPlaceMark (p, mrk) c =
do st <- get
liftIO $ C.renderWith c (drawMark p mrk st)
return c
imgFinalize c = return c
imgCanvas = Canvas { setupCanvas = imgSetup
, nextPlayer = imgToPlay
, placeStone = imgPlaceStone
, placeMark = imgPlaceMark
, finalize = imgFinalize
, initState = undefined :: (Point -> (Double, Double), Double)
}
| kadoban/sgf | Canvas.hs | agpl-3.0 | 10,170 | 0 | 18 | 4,201 | 3,640 | 1,925 | 1,715 | -1 | -1 |
module Git.Command.PatchId (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/PatchId.hs | unlicense | 85 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE DataKinds #-}
module DumpSerialisationSpec where
import Test.Hspec
import Linear
import Data.Maybe
import Data.Foldable
import Bio.Motions.Format.DumpDeserialisation
import Bio.Motions.Format.DumpSerialisation
import Bio.Motions.Format.Proto.Delta
import Bio.Motions.Representation.Dump
import Bio.Motions.Types
import Bio.Motions.Callback.GyrationRadius
import Bio.Motions.Callback.Class
import Bio.Motions.Callback.Serialisation
import Bio.Motions.Callback.Periodic
import SimpleCallback
dump :: Dump
dump = Dump
{ dumpBinders =
[ BinderInfo (V3 0 1 2) bi0
, BinderInfo (V3 0 1 3) bi0
, BinderInfo (V3 5 5 5) bi1
]
, dumpChains =
[ [ DumpBeadInfo (V3 0 1 1) ev0
, DumpBeadInfo (V3 5 6 6) ev1
, DumpBeadInfo (V3 5 5 6) ev0
]
, [ DumpBeadInfo (V3 0 0 2) ev0
, DumpBeadInfo (V3 5 4 5) ev1
]
, [ DumpBeadInfo (V3 7 7 7) ev0
, DumpBeadInfo (V3 7 8 8) ev0
]
]
}
where
[bi0, bi1] = map BinderType [0, 1]
(ev0, ev1) = ([1, 0], [0, 1000])
move :: Move
move = Move
{ moveFrom = V3 1 2 3
, moveDiff = V3 1 1 0
}
spec :: Spec
spec = context "when serialising and deserialising dumps and moves" $ do
let h = getHeader "a" "b" [] ["x", "y", "z"] dump
kf = getKeyframe dump ([], []) 0
let Just dumpAgain = deserialiseDump h kf
it "should return the same dump" $
dump `shouldBe` dumpAgain
let delta = serialiseMove move ([], []) 0
let Just moveAgain = deserialiseMove delta
it "should return the same move" $
move `shouldBe` moveAgain
let serialisedCallbacks =
toList $ callbacks $ serialiseMove move
([CallbackResult $ GyrationRadius [10.1, 2.2]
, CallbackResult (PeriodicWait 1 :: (Periodic (SimpleCallback 42)))
, CallbackResult $ PeriodicValue (SimpleCallback 10 :: (SimpleCallback 41))]
,[]) 0
let serialisedCallbacksOK = map fromJust [serialiseCallback "SimpleCallback" (10::Int),
serialiseCallback "Gyration Radius" ([10.1, 2.2]::[Double])]
it "should return serialised callbacks" $
serialisedCallbacks `shouldMatchList` serialisedCallbacksOK
| Motions/motions | test/DumpSerialisationSpec.hs | apache-2.0 | 2,377 | 0 | 20 | 690 | 725 | 395 | 330 | 58 | 1 |
module LibSpec
where
import Test.Hspec
import Lib
import Grammar
libSpec :: IO()
libSpec = hspec $ do
describe "Lib" $ do
it "Assign a value correctly" $ do
let expression = [(Assign "a" (Int 1))]
let expected = [("a", 1)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Calc a value given a variable" $ do
let expression = [(Assign "a" (Int 1)), (Assign "a" (Plus (Sym "a") (Sym "a")))]
let expected = [("a", 2)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Does anything when undeclared variable" $ do
let expression = [Tok (Sym "abc")]
let expected = []
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Evaluate and if (condition true)" $ do
let expression = [IfExp (If (Less (Int 3) (Int 4)) [Assign "a" (Int 3)])]
let expected = [("a", 3)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Evaluate and if (condition false)" $ do
let expression = [IfExp (If (Greater (Int 3) (Int 4)) [Assign "a" (Int 3)])]
let expected = []
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Evaluate and ifelse (condition true)" $ do
let expression = [IfExp (IfElse (Less (Int 3) (Int 4)) [Assign "a" (Int 3)] [Assign "a" (Int 4)])]
let expected = [("a", 3)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Evaluate and ifelse (condition false)" $ do
let expression = [IfExp (IfElse (Greater (Int 3) (Int 4)) [Assign "a" (Int 3)] [Assign "a" (Int 4)])]
let expected = [("a", 4)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "Print something!" $ do
let expression = [Print (Int 2)]
let expected = []
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected
it "While expression finished with value expected" $ do
let expression = [Assign "a" (Int 3), WhileExp (Greater (Sym "a") (Int 0)) [Assign "a" (Minus (Sym "a") (Int 1))]]
let expected = [("a", 0)]
obtained <- eval expression emptyDataStore
obtained `shouldBe` expected | JCepedaVillamayor/functional-compiler | test/LibSpec.hs | bsd-3-clause | 2,551 | 0 | 24 | 848 | 928 | 454 | 474 | 52 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{- |
Module : Control.Concurrent.Async.Lifted.Safe
Copyright : Copyright (C) 2012-2015 Mitsutoshi Aoe
License : BSD-style (see the file LICENSE)
Maintainer : Mitsutoshi Aoe <maoe@foldr.in>
Stability : experimental
This is a safe variant of @Control.Concurrent.Async.Lifted@.
This module assumes your monad stack to satisfy @'StM' m a ~ a@ so you can't
mess up monadic effects. If your monad stack is stateful, use
@Control.Concurrent.Async.Lifted@ with special care.
-}
module Control.Concurrent.Async.Lifted.Safe
#if MIN_VERSION_monad_control(1, 0, 0)
(
-- * Asynchronous actions
A.Async
, Pure
, Forall
-- ** Spawning
, async, asyncBound, asyncOn, asyncWithUnmask, asyncOnWithUnmask
-- ** Spawning with automatic 'cancel'ation
, withAsync, withAsyncBound, withAsyncOn
, withAsyncWithUnmask, withAsyncOnWithUnmask
-- ** Quering 'Async's
, wait, poll, waitCatch
, cancel, cancelWith
, A.asyncThreadId
-- ** STM operations
, A.waitSTM, A.pollSTM, A.waitCatchSTM
-- ** Waiting for multiple 'Async's
, waitAny, waitAnyCatch, waitAnyCancel, waitAnyCatchCancel
, waitEither, waitEitherCatch, waitEitherCancel, waitEitherCatchCancel
, Unsafe.waitEither_
, waitBoth
-- ** Linking
, Unsafe.link, Unsafe.link2
-- * Convenient utilities
, race, race_, concurrently, mapConcurrently
, Concurrently(..)
)
#else
{-# WARNING
"This module is available only if built with @monad-control >= 1.0.0@.\
If you have an older version of @monad-control@, use\
@Control.Concurrent.Async.Lifted@ instead."
#-}
#endif
where
#if MIN_VERSION_monad_control(1, 0, 0)
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Monad
import Control.Concurrent.Async (Async)
import Control.Exception.Lifted (SomeException, Exception)
import Control.Monad.Base (MonadBase(..))
import Control.Monad.Trans.Control hiding (restoreM)
import Data.Constraint ((\\), (:-))
import Data.Constraint.Forall (Forall, inst)
import qualified Control.Concurrent.Async as A
import qualified Control.Concurrent.Async.Lifted as Unsafe
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 710
import Data.Traversable
#endif
-- | Generalized version of 'A.async'.
async
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> m a -> m (Async a)
async = Unsafe.async
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.asyncBound'.
asyncBound
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> m a -> m (Async a)
asyncBound = Unsafe.asyncBound
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.asyncOn'.
asyncOn
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> Int -> m a -> m (Async a)
asyncOn cpu m = Unsafe.asyncOn cpu m
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.asyncWithUnmask'.
asyncWithUnmask
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> ((forall b. m b -> m b) -> m a)
-> m (Async a)
asyncWithUnmask restore = Unsafe.asyncWithUnmask restore
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.asyncOnWithUnmask'.
asyncOnWithUnmask
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> Int
-> ((forall b. m b -> m b) -> m a)
-> m (Async a)
asyncOnWithUnmask cpu restore = Unsafe.asyncOnWithUnmask cpu restore
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.withAsync'.
withAsync
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> m a
-> (Async a -> m b)
-> m b
withAsync = Unsafe.withAsync
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.withAsyncBound'.
withAsyncBound
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> m a
-> (Async a -> m b)
-> m b
withAsyncBound = Unsafe.withAsyncBound
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.withAsyncOn'.
withAsyncOn
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Int
-> m a
-> (Async a -> m b)
-> m b
withAsyncOn = Unsafe.withAsyncOn
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.withAsyncWithUnmask'.
withAsyncWithUnmask
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> ((forall c. m c -> m c) -> m a)
-> (Async a -> m b)
-> m b
withAsyncWithUnmask restore = Unsafe.withAsyncWithUnmask restore
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.withAsyncOnWithUnmask'.
withAsyncOnWithUnmask
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Int
-> ((forall c. m c -> m c) -> m a)
-> (Async a -> m b)
-> m b
withAsyncOnWithUnmask cpu restore = Unsafe.withAsyncOnWithUnmask cpu restore
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.wait'.
wait
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> Async a -> m a
wait = Unsafe.wait
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.poll'.
poll
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> m (Maybe (Either SomeException a))
poll = Unsafe.poll
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.waitCatch'.
waitCatch
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> m (Either SomeException a)
waitCatch = Unsafe.waitCatch
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.cancel'.
cancel :: MonadBase IO m => Async a -> m ()
cancel = Unsafe.cancel
-- | Generalized version of 'A.cancelWith'.
cancelWith :: (MonadBase IO m, Exception e) => Async a -> e -> m ()
cancelWith = Unsafe.cancelWith
-- | Generalized version of 'A.waitAny'.
waitAny
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> [Async a] -> m (Async a, a)
waitAny = Unsafe.waitAny
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.waitAnyCatch'.
waitAnyCatch
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> [Async a]
-> m (Async a, Either SomeException a)
waitAnyCatch = Unsafe.waitAnyCatch
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.waitAnyCancel'.
waitAnyCancel
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> [Async a]
-> m (Async a, a)
waitAnyCancel = Unsafe.waitAnyCancel
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.waitAnyCatchCancel'.
waitAnyCatchCancel
:: forall m a. (MonadBaseControl IO m, Forall (Pure m))
=> [Async a]
-> m (Async a, Either SomeException a)
waitAnyCatchCancel = Unsafe.waitAnyCatchCancel
\\ (inst :: Forall (Pure m) :- Pure m a)
-- | Generalized version of 'A.waitEither'.
waitEither
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> Async b
-> m (Either a b)
waitEither = Unsafe.waitEither
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.waitEitherCatch'.
waitEitherCatch
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> Async b
-> m (Either (Either SomeException a) (Either SomeException b))
waitEitherCatch = Unsafe.waitEitherCatch
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.waitEitherCancel'.
waitEitherCancel
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> Async b
-> m (Either a b)
waitEitherCancel = Unsafe.waitEitherCancel
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.waitEitherCatchCancel'.
waitEitherCatchCancel
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> Async b
-> m (Either (Either SomeException a) (Either SomeException b))
waitEitherCatchCancel = Unsafe.waitEitherCatchCancel
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.waitBoth'.
waitBoth
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> Async a
-> Async b
-> m (a, b)
waitBoth = Unsafe.waitBoth
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.race'.
race
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> m a -> m b -> m (Either a b)
race = Unsafe.race
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.race_'.
race_
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> m a -> m b -> m ()
race_ = Unsafe.race_
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.concurrently'.
concurrently
:: forall m a b. (MonadBaseControl IO m, Forall (Pure m))
=> m a -> m b -> m (a, b)
concurrently = Unsafe.concurrently
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
-- | Generalized version of 'A.mapConcurrently'.
mapConcurrently
:: (Traversable t, MonadBaseControl IO m, Forall (Pure m))
=> (a -> m b)
-> t a
-> m (t b)
mapConcurrently f = runConcurrently . traverse (Concurrently . f)
-- | Generalized version of 'A.Concurrently'.
--
-- A value of type @'Concurrently' m a@ is an IO-based operation that can be
-- composed with other 'Concurrently' values, using the 'Applicative' and
-- 'Alternative' instances.
--
-- Calling 'runConcurrently' on a value of type @'Concurrently' m a@ will
-- execute the IO-based lifted operations it contains concurrently, before
-- delivering the result of type 'a'.
--
-- For example
--
-- @
-- (page1, page2, page3) <- 'runConcurrently' $ (,,)
-- '<$>' 'Concurrently' (getURL "url1")
-- '<*>' 'Concurrently' (getURL "url2")
-- '<*>' 'Concurrently' (getURL "url3")
-- @
data Concurrently m a where
Concurrently
:: Forall (Pure m) => { runConcurrently :: m a } -> Concurrently m a
-- | Most of the functions in this module have @'Forall' ('Pure' m)@ in their
-- constraints, which means they require the monad 'm' satisfies
-- @'StM' m a ~ a@ for all 'a'.
class StM m a ~ a => Pure m a
instance StM m a ~ a => Pure m a
instance Functor m => Functor (Concurrently m) where
fmap f (Concurrently a) = Concurrently $ f <$> a
instance (MonadBaseControl IO m, Forall (Pure m)) =>
Applicative (Concurrently m) where
pure = Concurrently . pure
Concurrently (fs :: m (a -> b)) <*> Concurrently as =
Concurrently (uncurry ($) <$> concurrently fs as)
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m (a -> b))
instance (MonadBaseControl IO m, Forall (Pure m)) =>
Alternative (Concurrently m) where
empty = Concurrently $ liftBaseWith $ const (forever $ threadDelay maxBound)
Concurrently (as :: m a) <|> Concurrently bs =
Concurrently (either id id <$> race as bs)
\\ (inst :: Forall (Pure m) :- Pure m a)
\\ (inst :: Forall (Pure m) :- Pure m b)
instance (MonadBaseControl IO m, Forall (Pure m)) =>
Monad (Concurrently m) where
return = Concurrently . return
Concurrently a >>= f = Concurrently $ a >>= runConcurrently . f
#endif
| dmjio/lifted-async | src/Control/Concurrent/Async/Lifted/Safe.hs | bsd-3-clause | 11,525 | 0 | 14 | 2,327 | 3,756 | 1,998 | 1,758 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Doc.Extending
-- Copyright : (C) 2007 Andrea Rossato
-- License : BSD3
--
-- Maintainer : andrea.rossato@unibz.it
-- Stability : unstable
-- Portability : portable
--
-- This module documents the xmonad-contrib library and
-- how to use it to extend the capabilities of xmonad.
--
-- Reading this document should not require a deep knowledge of
-- Haskell; the examples are intended to be useful and understandable
-- for those users who do not know Haskell and don't want to have to
-- learn it just to configure xmonad. You should be able to get by
-- just fine by ignoring anything you don't understand and using the
-- provided examples as templates. However, relevant Haskell features
-- are discussed when appropriate, so this document will hopefully be
-- useful for more advanced Haskell users as well.
--
-- Those wishing to be totally hardcore and develop their own xmonad
-- extensions (it's easier than it sounds, we promise!) should read
-- the documentation in "XMonad.Doc.Developing".
--
-- More configuration examples may be found on the Haskell wiki:
--
-- <http://haskell.org/haskellwiki/Xmonad/Config_archive>
--
-----------------------------------------------------------------------------
module XMonad.Doc.Extending
(
-- * The xmonad-contrib library
-- $library
-- ** Actions
-- $actions
-- ** Configurations
-- $configs
-- ** Hooks
-- $hooks
-- ** Layouts
-- $layouts
-- ** Prompts
-- $prompts
-- ** Utilities
-- $utils
-- * Extending xmonad
-- $extending
-- ** Editing key bindings
-- $keys
-- *** Adding key bindings
-- $keyAdding
-- *** Removing key bindings
-- $keyDel
-- *** Adding and removing key bindings
-- $keyAddDel
-- ** Editing mouse bindings
-- $mouse
-- ** Editing the layout hook
-- $layoutHook
-- ** Editing the manage hook
-- $manageHook
-- ** The log hook and external status bars
-- $logHook
) where
--------------------------------------------------------------------------------
--
-- The XmonadContrib Library
--
--------------------------------------------------------------------------------
{- $library
The xmonad-contrib (xmc) library is a set of extension modules
contributed by xmonad hackers and users, which provide additional
xmonad features. Examples include various layout modes (tabbed,
spiral, three-column...), prompts, program launchers, the ability to
manipulate windows and workspaces in various ways, alternate
navigation modes, and much more. There are also \"meta-modules\"
which make it easier to write new modules and extensions.
This is a concise yet complete overview of the xmonad-contrib modules.
For more information about any particular module, just click on its
name to view its Haddock documentation; each module should come with
extensive documentation. If you find a module that could be better
documented, or has incorrect documentation, please report it as a bug
(<https://github.com/xmonad/xmonad/issues>)!
-}
{- $actions
In the @XMonad.Actions@ namespace you can find modules exporting
various functions that are usually intended to be bound to key
combinations or mouse actions, in order to provide functionality
beyond the standard keybindings provided by xmonad.
See "XMonad.Doc.Extending#Editing_key_bindings" for instructions on how to
edit your key bindings.
* "XMonad.Actions.Commands":
Allows you to run internal xmonad commands (X () actions) using
a dmenu menu in addition to key bindings. Requires dmenu and
the Dmenu XMonad.Actions module.
* "XMonad.Actions.ConstrainedResize":
Lets you constrain the aspect ratio of a floating
window (by, say, holding shift while you resize).
Useful for making a nice circular XClock window.
* "XMonad.Actions.CopyWindow":
Provides bindings to duplicate a window on multiple workspaces,
providing dwm-like tagging functionality.
* "XMonad.Actions.CycleRecentWS":
Provides bindings to cycle through most recently used workspaces
with repeated presses of a single key (as long as modifier key is
held down). This is similar to how many window managers handle
window switching.
* "XMonad.Actions.CycleSelectedLayouts":
This module allows to cycle through the given subset of layouts.
* "XMonad.Actions.CycleWS":
Provides bindings to cycle forward or backward through the list of
workspaces, to move windows between workspaces, and to cycle
between screens. Replaces the former XMonad.Actions.RotView.
* "XMonad.Actions.CycleWindows":
Provides bindings to cycle windows up or down on the current workspace
stack while maintaining focus in place.
* "XMonad.Actions.DeManage":
This module provides a method to cease management of a window
without unmapping it. "XMonad.Hooks.ManageDocks" is a
more automated solution if your panel supports it.
* "XMonad.Actions.DwmPromote":
Dwm-like swap function for xmonad.
Swaps focused window with the master window. If focus is in the
master, swap it with the next window in the stack. Focus stays in the
master.
* "XMonad.Actions.DynamicWorkspaces":
Provides bindings to add and delete workspaces. Note that you may only
delete a workspace that is already empty.
* "XMonad.Actions.FindEmptyWorkspace":
Find an empty workspace.
* "XMonad.Actions.FlexibleManipulate":
Move and resize floating windows without warping the mouse.
* "XMonad.Actions.FlexibleResize":
Resize floating windows from any corner.
* "XMonad.Actions.FloatKeys":
Move and resize floating windows.
* "XMonad.Actions.FloatSnap":
Move and resize floating windows using other windows and the edge of the
screen as guidelines.
* "XMonad.Actions.FocusNth":
Focus the nth window of the current workspace.
* "XMonad.Actions.GridSelect":
GridSelect displays items(e.g. the opened windows) in a 2D grid and lets
the user select from it with the cursor/hjkl keys or the mouse.
* "XMonad.Actions.MessageFeedback":
Alternative to 'XMonad.Operations.sendMessage' that provides knowledge
of whether the message was handled, and utility functions based on
this facility.
* "XMonad.Actions.MouseGestures":
Support for simple mouse gestures.
* "XMonad.Actions.MouseResize":
A layout modifier to resize windows with the mouse by grabbing the
window's lower right corner.
* "XMonad.Actions.NoBorders":
This module provides helper functions for dealing with window borders.
* "XMonad.Actions.OnScreen":
Control workspaces on different screens (in xinerama mode).
* "XMonad.Actions.PerWorkspaceKeys":
Define key-bindings on per-workspace basis.
* "XMonad.Actions.PhysicalScreens":
Manipulate screens ordered by physical location instead of ID
* "XMonad.Actions.Plane":
This module has functions to navigate through workspaces in a bidimensional
manner.
* "XMonad.Actions.Promote":
Alternate promote function for xmonad.
* "XMonad.Actions.RandomBackground":
An action to start terminals with a random background color
* "XMonad.Actions.RotSlaves":
Rotate all windows except the master window and keep the focus in
place.
* "XMonad.Actions.Search":
A module for easily running Internet searches on web sites through xmonad.
Modeled after the handy Surfraw CLI search tools at <https://secure.wikimedia.org/wikipedia/en/wiki/Surfraw>.
* "XMonad.Actions.SimpleDate":
An example external contrib module for XMonad.
Provides a simple binding to dzen2 to print the date as a popup menu.
* "XMonad.Actions.SinkAll":
(Deprecated) Provides a simple binding that pushes all floating windows on the
current workspace back into tiling. Instead, use the more general
"XMonad.Actions.WithAll"
* "XMonad.Actions.SpawnOn":
Provides a way to modify a window spawned by a command(e.g shift it to the workspace
it was launched on) by using the _NET_WM_PID property that most windows set on creation.
* "XMonad.Actions.Submap":
A module that allows the user to create a sub-mapping of key bindings.
* "XMonad.Actions.SwapWorkspaces":
Lets you swap workspace tags, so you can keep related ones next to
each other, without having to move individual windows.
* "XMonad.Actions.TagWindows":
Functions for tagging windows and selecting them by tags.
* "XMonad.Actions.TopicSpace":
Turns your workspaces into a more topic oriented system.
* "XMonad.Actions.UpdateFocus":
Updates the focus on mouse move in unfocused windows.
* "XMonad.Actions.UpdatePointer":
Causes the pointer to follow whichever window focus changes to.
* "XMonad.Actions.Warp":
Warp the pointer to a given window or screen.
* "XMonad.Actions.WindowBringer":
dmenu operations to bring windows to you, and bring you to windows.
That is to say, it pops up a dmenu with window names, in case you forgot
where you left your XChat.
* "XMonad.Actions.WindowGo":
Defines a few convenient operations for raising (traveling to) windows based on XMonad's Query
monad, such as 'runOrRaise'.
* "XMonad.Actions.WindowMenu":
Uses "XMonad.Actions.GridSelect" to display a number of actions related to
window management in the center of the focused window.
* "XMonad.Actions.WindowNavigation":
Experimental rewrite of "XMonad.Layout.WindowNavigation".
* "XMonad.Actions.WithAll":
Provides functions for performing a given action on all windows of
the current workspace.
* "XMonad.Actions.WorkspaceCursors":
Like "XMonad.Actions.Plane" for an arbitrary number of dimensions.
-}
{- $configs
In the @XMonad.Config@ namespace you can find modules exporting the
configurations used by some of the xmonad and xmonad-contrib
developers. You can look at them for examples while creating your own
configuration; you can also simply import them and use them as your
own configuration, possibly with some modifications.
* "XMonad.Config.Arossato"
This module specifies my xmonad defaults.
* "XMonad.Config.Azerty"
Fixes some keybindings for users of French keyboard layouts.
* "XMonad.Config.Desktop"
This module provides core desktop environment settings used
in the Gnome, Kde, and Xfce config configs. It is also useful
for people using other environments such as lxde, or using
tray or panel applications without full desktop environments.
* "XMonad.Config.Gnome"
* "XMonad.Config.Kde"
* "XMonad.Config.Sjanssen"
* "XMonad.Config.Xfce"
-}
{- $hooks
In the @XMonad.Hooks@ namespace you can find modules exporting
hooks. Hooks are actions that xmonad performs when certain events
occur. The two most important hooks are:
* 'XMonad.Core.manageHook': this hook is called when a new window
xmonad must take care of is created. This is a very powerful hook,
since it lets us examine the new window's properties and act
accordingly. For instance, we can configure xmonad to put windows
belonging to a given application in the float layer, not to manage
dock applications, or open them in a given workspace. See
"XMonad.Doc.Extending#Editing_the_manage_hook" for more information on
customizing 'XMonad.Core.manageHook'.
* 'XMonad.Core.logHook': this hook is called when the stack of windows
managed by xmonad has been changed, by calling the
'XMonad.Operations.windows' function. For instance
"XMonad.Hooks.DynamicLog" will produce a string (whose format can be
configured) to be printed to the standard output. This can be used
to display some information about the xmonad state in a status bar.
See "XMonad.Doc.Extending#The_log_hook_and_external_status_bars" for more
information.
* 'XMonad.Core.handleEventHook': this hook is called on all events handled
by xmonad, thus it is extremely powerful. See "Graphics.X11.Xlib.Extras"
and xmonad source and development documentation for more details.
Here is a list of the modules found in @XMonad.Hooks@:
* "XMonad.Hooks.DynamicHooks":
One-shot and permanent ManageHooks that can be updated at runtime.
* "XMonad.Hooks.DynamicLog": for use with 'XMonad.Core.logHook'; send
information about xmonad's state to standard output, suitable for
putting in a status bar of some sort. See
"XMonad.Doc.Extending#The_log_hook_and_external_status_bars".
* "XMonad.Hooks.EwmhDesktops":
Makes xmonad use the EWMH hints to tell panel applications about its
workspaces and the windows therein. It also allows the user to interact
with xmonad by clicking on panels and window lists.
* "XMonad.Hooks.FadeInactive":
Makes XMonad set the _NET_WM_WINDOW_OPACITY atom for inactive windows,
which causes those windows to become slightly translucent if something
like xcompmgr is running
* "XMonad.Hooks.FloatNext":
Hook and keybindings for automatically sending the next
spawned window(s) to the floating layer.
* "XMonad.Hooks.InsertPosition":
Configure where new windows should be added and which window should be
focused.
* "XMonad.Hooks.ManageDocks":
This module provides tools to automatically manage 'dock' type programs,
such as gnome-panel, kicker, dzen, and xmobar.
* "XMonad.Hooks.ManageHelpers": provide helper functions to be used
in @manageHook@.
* "XMonad.Hooks.Minimize":
Handles window manager hints to minimize and restore windows. Use
this with XMonad.Layout.Minimize.
* "XMonad.Hooks.Place":
Automatic placement of floating windows.
* "XMonad.Hooks.RestoreMinimized":
(Deprecated: Use XMonad.Hooks.Minimize) Lets you restore minimized
windows (see "XMonad.Layout.Minimize") by selecting them on a
taskbar (listens for _NET_ACTIVE_WINDOW and WM_CHANGE_STATE).
* "XMonad.Hooks.Script":
Provides a simple interface for running a ~\/.xmonad\/hooks script with the
name of a hook.
* "XMonad.Hooks.ServerMode": Allows sending commands to a running xmonad process.
* "XMonad.Hooks.SetCursor":
Set a default mouse cursor on startup.
* "XMonad.Hooks.SetWMName":
Sets the WM name to a given string, so that it could be detected using
_NET_SUPPORTING_WM_CHECK protocol. May be useful for making Java GUI
programs work.
* "XMonad.Hooks.UrgencyHook":
UrgencyHook lets you configure an action to occur when a window demands
your attention. (In traditional WMs, this takes the form of \"flashing\"
on your \"taskbar.\" Blech.)
* "XMonad.Hooks.WorkspaceByPos":
Useful in a dual-head setup: Looks at the requested geometry of
new windows and moves them to the workspace of the non-focused
screen if necessary.
* "XMonad.Hooks.XPropManage":
A ManageHook matching on XProperties.
-}
{- $layouts
In the @XMonad.Layout@ namespace you can find modules exporting
contributed tiling algorithms, such as a tabbed layout, a circle, a spiral,
three columns, and so on.
You will also find modules which provide facilities for combining
different layouts, such as "XMonad.Layout.Combo", "XMonad.Layout.ComboP",
"XMonad.Layout.LayoutBuilder", "XMonad.Layout.SubLayouts", or
"XMonad.Layout.LayoutCombinators".
Layouts can be also modified with layout modifiers. A general
interface for writing layout modifiers is implemented in
"XMonad.Layout.LayoutModifier".
For more information on using those modules for customizing your
'XMonad.Core.layoutHook' see "XMonad.Doc.Extending#Editing_the_layout_hook".
* "XMonad.Layout.Accordion":
LayoutClass that puts non-focused windows in ribbons at the top and bottom
of the screen.
* "XMonad.Layout.AutoMaster":
Provides layout modifier AutoMaster. It separates screen in two parts -
master and slave. Size of slave area automatically changes depending on
number of slave windows.
* "XMonad.Layout.BorderResize":
This layout modifier will allow to resize windows by dragging their
borders with the mouse. However, it only works in layouts or modified
layouts that react to the SetGeometry message.
"XMonad.Layout.WindowArranger" can be used to create such a setup.
BorderResize is probably most useful in floating layouts.
* "XMonad.Layout.BoringWindows":
BoringWindows is an extension to allow windows to be marked boring
* "XMonad.Layout.CenteredMaster":
Two layout modifiers. centerMaster places master window at center,
on top of all other windows, which are managed by base layout.
topRightMaster is similar, but places master window in top right corner
instead of center.
* "XMonad.Layout.Circle":
Circle is an elliptical, overlapping layout.
* "XMonad.Layout.Column":
Provides Column layout that places all windows in one column. Windows
heights are calculated from equation: H1/H2 = H2/H3 = ... = q, where q is
given. With Shrink/Expand messages you can change the q value.
* "XMonad.Layout.Combo":
A layout that combines multiple layouts.
* "XMonad.Layout.ComboP":
A layout that combines multiple layouts and allows to specify where to put
new windows.
* "XMonad.Layout.Cross":
A Cross Layout with the main window in the center.
* "XMonad.Layout.Decoration":
A layout modifier and a class for easily creating decorated
layouts.
* "XMonad.Layout.DecorationMadness":
A collection of decorated layouts: some of them may be nice, some
usable, others just funny.
* "XMonad.Layout.Dishes":
Dishes is a layout that stacks extra windows underneath the master
windows.
* "XMonad.Layout.DragPane":
Layouts that splits the screen either horizontally or vertically and
shows two windows. The first window is always the master window, and
the other is either the currently focused window or the second window in
layout order. See also "XMonad.Layout.MouseResizableTall"
* "XMonad.Layout.DwmStyle":
A layout modifier for decorating windows in a dwm like style.
* "XMonad.Layout.FixedColumn":
A layout much like Tall, but using a multiple of a window's minimum
resize amount instead of a percentage of screen to decide where to
split. This is useful when you usually leave a text editor or
terminal in the master pane and like it to be 80 columns wide.
* "XMonad.Layout.Gaps":
Create manually-sized gaps along edges of the screen which will not
be used for tiling, along with support for toggling gaps on and
off. You probably want "XMonad.Hooks.ManageDocks".
* "XMonad.Layout.Grid":
A simple layout that attempts to put all windows in a square grid.
* "XMonad.Layout.GridVariants":
Two layouts: one is a variant of the Grid layout that allows the
desired aspect ratio of windows to be specified. The other is like
Tall but places a grid with fixed number of rows and columns in the
master area and uses an aspect-ratio-specified layout for the
slaves.
* "XMonad.Layout.HintedGrid":
A not so simple layout that attempts to put all windows in a square grid
while obeying their size hints.
* "XMonad.Layout.HintedTile":
A gapless tiled layout that attempts to obey window size hints,
rather than simply ignoring them.
* "XMonad.Layout.IM":
Layout modfier suitable for workspace with multi-windowed instant messenger
(like Psi or Tkabber).
* "XMonad.Layout.IndependentScreens":
Utility functions for simulating independent sets of workspaces on
each screen (like dwm's workspace model), using internal tags to
distinguish workspaces associated with each screen.
* "XMonad.Layout.LayoutBuilder":
A layout combinator that sends a specified number of windows to one rectangle
and the rest to another.
* "XMonad.Layout.LayoutCombinators":
The "XMonad.Layout.LayoutCombinators" module provides combinators
for easily combining multiple layouts into one composite layout, as
well as a way to jump directly to any particular layout (say, with
a keybinding) without having to cycle through other layouts to get
to it.
* "XMonad.Layout.LayoutHints":
Make layouts respect size hints.
* "XMonad.Layout.LayoutModifier":
A module for writing easy layout modifiers, which do not define a
layout in and of themselves, but modify the behavior of or add new
functionality to other layouts. If you ever find yourself writing
a layout which takes another layout as a parameter, chances are you
should be writing a LayoutModifier instead!
In case it is not clear, this module is not intended to help you
configure xmonad, it is to help you write other extension modules.
So get hacking!
* "XMonad.Layout.LayoutScreens":
Divide a single screen into multiple screens.
* "XMonad.Layout.LimitWindows":
A layout modifier that limits the number of windows that can be shown.
* "XMonad.Layout.MagicFocus":
Automagically put the focused window in the master area.
* "XMonad.Layout.Magnifier":
Screenshot : <http://caladan.rave.org/magnifier.png>
This is a layout modifier that will make a layout increase the size
of the window that has focus.
* "XMonad.Layout.Master":
Layout modfier that adds a master window to another layout.
* "XMonad.Layout.Maximize":
Temporarily yanks the focused window out of the layout to mostly fill
the screen.
* "XMonad.Layout.MessageControl":
Provides message escaping and filtering facilities which
help control complex nested layouts.
* "XMonad.Layout.Minimize":
Makes it possible to minimize windows, temporarily removing them
from the layout until they are restored.
* "XMonad.Layout.Monitor":
Layout modfier for displaying some window (monitor) above other windows
* "XMonad.Layout.Mosaic":
Based on MosaicAlt, but aspect ratio messages always change the aspect
ratios, and rearranging the window stack changes the window sizes.
* "XMonad.Layout.MosaicAlt":
A layout which gives each window a specified amount of screen space
relative to the others. Compared to the 'Mosaic' layout, this one
divides the space in a more balanced way.
* "XMonad.Layout.MouseResizableTile":
A layout in the spirit of "XMonad.Layout.ResizableTile", but with the option
to use the mouse to adjust the layout.
* "XMonad.Layout.MultiToggle":
Dynamically apply and unapply transformers to your window layout. This can
be used to rotate your window layout by 90 degrees, or to make the
currently focused window occupy the whole screen (\"zoom in\") then undo
the transformation (\"zoom out\").
* "XMonad.Layout.Named":
A module for assigning a name to a given layout.
* "XMonad.Layout.NoBorders":
Make a given layout display without borders. This is useful for
full-screen or tabbed layouts, where you don't really want to waste a
couple of pixels of real estate just to inform yourself that the visible
window has focus.
* "XMonad.Layout.NoFrillsDecoration":
Most basic version of decoration for windows without any additional
modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will
result in title bars that span the entire window instead of being only the
length of the window title.
* "XMonad.Layout.OneBig":
Places one (master) window at top left corner of screen, and other (slave)
windows at the top.
* "XMonad.Layout.PerWorkspace":
Configure layouts on a per-workspace basis: use layouts and apply
layout modifiers selectively, depending on the workspace.
* "XMonad.Layout.Reflect":
Reflect a layout horizontally or vertically.
* "XMonad.Layout.ResizableTile":
More useful tiled layout that allows you to change a width\/height of window.
See also "XMonad.Layout.MouseResizableTile".
* "XMonad.Layout.ResizeScreen":
A layout transformer to have a layout respect a given screen
geometry. Mostly used with "Decoration" (the Horizontal and the
Vertical version will react to SetTheme and change their dimension
accordingly.
* "XMonad.Layout.Roledex":
This is a completely pointless layout which acts like Microsoft's Flip 3D
* "XMonad.Layout.ShowWName":
This is a layout modifier that will show the workspace name
* "XMonad.Layout.SimpleDecoration":
A layout modifier for adding simple decorations to the windows of a
given layout. The decorations are in the form of ion-like tabs
for window titles.
* "XMonad.Layout.SimpleFloat":
A basic floating layout.
* "XMonad.Layout.Simplest":
A very simple layout. The simplest, afaik. Used as a base for
decorated layouts.
* "XMonad.Layout.SimplestFloat":
A basic floating layout like SimpleFloat but without the decoration.
* "XMonad.Layout.Spacing":
Add a configurable amount of space around windows.
* "XMonad.Layout.Spiral":
A spiral tiling layout.
* "XMonad.Layout.Square":
A layout that splits the screen into a square area and the rest of the
screen.
This is probably only ever useful in combination with
"XMonad.Layout.Combo".
It sticks one window in a square region, and makes the rest
of the windows live with what's left (in a full-screen sense).
* "XMonad.Layout.StackTile":
A stacking layout, like dishes but with the ability to resize master pane.
Mostly useful on small screens.
* "XMonad.Layout.SubLayouts":
A layout combinator that allows layouts to be nested.
* "XMonad.Layout.TabBarDecoration":
A layout modifier to add a bar of tabs to your layouts.
* "XMonad.Layout.Tabbed":
A tabbed layout for the Xmonad Window Manager
* "XMonad.Layout.ThreeColumns":
A layout similar to tall but with three columns. With 2560x1600 pixels this
layout can be used for a huge main window and up to six reasonable sized
slave windows.
* "XMonad.Layout.ToggleLayouts":
A module to toggle between two layouts.
* "XMonad.Layout.TwoPane":
A layout that splits the screen horizontally and shows two windows. The
left window is always the master window, and the right is either the
currently focused window or the second window in layout order.
* "XMonad.Layout.WindowArranger":
This is a pure layout modifier that will let you move and resize
windows with the keyboard in any layout.
* "XMonad.Layout.WindowNavigation":
WindowNavigation is an extension to allow easy navigation of a workspace.
See also "XMonad.Actions.WindowNavigation".
* "XMonad.Layout.WorkspaceDir":
WorkspaceDir is an extension to set the current directory in a workspace.
Actually, it sets the current directory in a layout, since there's no way I
know of to attach a behavior to a workspace. This means that any terminals
(or other programs) pulled up in that workspace (with that layout) will
execute in that working directory. Sort of handy, I think.
Note this extension requires the 'directory' package to be installed.
-}
{- $prompts
In the @XMonad.Prompt@ name space you can find modules providing
graphical prompts for getting user input and using it to perform
various actions.
The "XMonad.Prompt" provides a library for easily writing new prompt
modules.
These are the available prompts:
* "XMonad.Prompt.AppLauncher":
A module for launch applicationes that receive parameters in the command
line. The launcher call a prompt to get the parameters.
* "XMonad.Prompt.AppendFile":
A prompt for appending a single line of text to a file. Useful for
keeping a file of notes, things to remember for later, and so on---
using a keybinding, you can write things down just about as quickly
as you think of them, so it doesn't have to interrupt whatever else
you're doing.
Who knows, it might be useful for other purposes as well!
* "XMonad.Prompt.DirExec":
A directory file executables prompt for XMonad. This might be useful if you
don't want to have scripts in your PATH environment variable (same
executable names, different behavior) - otherwise you might want to use
"XMonad.Prompt.Shell" instead - but you want to have easy access to these
executables through the xmonad's prompt.
* "XMonad.Prompt.Directory":
A directory prompt for XMonad
* "XMonad.Prompt.Email":
A prompt for sending quick, one-line emails, via the standard GNU
\'mail\' utility (which must be in your $PATH). This module is
intended mostly as an example of using "XMonad.Prompt.Input" to
build an action requiring user input.
* "XMonad.Prompt.Input":
A generic framework for prompting the user for input and passing it
along to some other action.
* "XMonad.Prompt.Layout":
A layout-selection prompt for XMonad
* "XMonad.Prompt.Man":
A manual page prompt for XMonad window manager.
TODO
* narrow completions by section number, if the one is specified
(like @\/etc\/bash_completion@ does)
* "XMonad.Prompt.RunOrRaise":
A prompt for XMonad which will run a program, open a file,
or raise an already running program, depending on context.
* "XMonad.Prompt.Shell":
A shell prompt for XMonad
* "XMonad.Prompt.Ssh":
A ssh prompt for XMonad
* "XMonad.Prompt.Theme":
A prompt for changing the theme of the current workspace
* "XMonad.Prompt.Window":
xprompt operations to bring windows to you, and bring you to windows.
* "XMonad.Prompt.Workspace":
A workspace prompt for XMonad
* "XMonad.Prompt.XMonad":
A prompt for running XMonad commands
Usually a prompt is called by some key binding. See
"XMonad.Doc.Extending#Editing_key_bindings", which includes examples
of adding some prompts.
-}
{- $utils
In the @XMonad.Util@ namespace you can find modules exporting various
utility functions that are used by the other modules of the
xmonad-contrib library.
There are also utilities for helping in configuring xmonad or using
external utilities.
A non complete list with a brief description:
* "XMonad.Util.Cursor": configure the default cursor/pointer glyph.
* "XMonad.Util.CustomKeys": configure key bindings (see
"XMonad.Doc.Extending#Editing_key_bindings").
* "XMonad.Util.Dmenu":
A convenient binding to dmenu.
Requires the process-1.0 package
* "XMonad.Util.Dzen":
Handy wrapper for dzen. Requires dzen >= 0.2.4.
* "XMonad.Util.EZConfig": configure key bindings easily, including a
parser for writing key bindings in "M-C-x" style.
* "XMonad.Util.Font": A module for abstracting a font facility over
Core fonts and Xft
* "XMonad.Util.Invisible":
A data type to store the layout state
* "XMonad.Util.Loggers":
A collection of simple logger functions and formatting utilities
which can be used in the 'XMonad.Hooks.DynamicLog.ppExtras' field of
a pretty-printing status logger format. See "XMonad.Hooks.DynamicLog"
for more information.
* "XMonad.Util.NamedActions":
A wrapper for keybinding configuration that can list the available
keybindings.
* "XMonad.Util.NamedScratchpad":
Like "XMonad.Util.Scratchpad" toggle windows to and from the current
workspace. Supports several arbitrary applications at the same time.
* "XMonad.Util.NamedWindows":
This module allows you to associate the X titles of windows with
them.
* "XMonad.Util.Paste":
A module for sending key presses to windows. This modules provides generalized
and specialized functions for this task.
* "XMonad.Util.Replace":
Implements a @--replace@ flag outside of core.
* "XMonad.Util.Run":
This modules provides several commands to run an external process.
It is composed of functions formerly defined in "XMonad.Util.Dmenu" (by
Spencer Janssen), "XMonad.Util.Dzen" (by glasser\@mit.edu) and
XMonad.Util.RunInXTerm (by Andrea Rossato).
* "XMonad.Util.Scratchpad":
Very handy hotkey-launched toggleable floating terminal window.
* "XMonad.Util.StringProp":
Internal utility functions for storing Strings with the root window.
Used for global state like IORefs with string keys, but more latency,
persistent between xmonad restarts.
* "XMonad.Util.Themes":
A (hopefully) growing collection of themes for decorated layouts.
* "XMonad.Util.Timer":
A module for setting up timers
* "XMonad.Util.Types":
Miscellaneous commonly used types.
* "XMonad.Util.WindowProperties":
EDSL for specifying window properties; various utilities related to window
properties.
* "XMonad.Util.XSelection":
A module for accessing and manipulating X Window's mouse selection (the buffer used in copy and pasting).
'getSelection' and 'putSelection' are adaptations of Hxsel.hs and Hxput.hs from the XMonad-utils
* "XMonad.Util.XUtils":
A module for painting on the screen
-}
--------------------------------------------------------------------------------
--
-- Extending Xmonad
--
--------------------------------------------------------------------------------
{- $extending
#Extending_xmonad#
Since the @xmonad.hs@ file is just another Haskell module, you may
import and use any Haskell code or libraries you wish, such as
extensions from the xmonad-contrib library, or other code you write
yourself.
-}
{- $keys
#Editing_key_bindings#
Editing key bindings means changing the 'XMonad.Core.XConfig.keys'
field of the 'XMonad.Core.XConfig' record used by xmonad. For
example, you could write:
> import XMonad
>
> main = xmonad $ def { keys = myKeys }
and provide an appropriate definition of @myKeys@, such as:
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
This particular definition also requires importing "XMonad.Prompt",
"XMonad.Prompt.Shell", "XMonad.Prompt.XMonad", and "Data.Map":
> import qualified Data.Map as M
> import XMonad.Prompt
> import XMonad.Prompt.Shell
> import XMonad.Prompt.XMonad
For a list of the names of particular keys (such as xK_F12, and so
on), see
<http://hackage.haskell.org/packages/archive/X11/latest/doc/html/Graphics-X11-Types.html>
Usually, rather than completely redefining the key bindings, as we did
above, we want to simply add some new bindings and\/or remove existing
ones.
-}
{- $keyAdding
#Adding_key_bindings#
Adding key bindings can be done in different ways. See the end of this
section for the easiest ways. The type signature of
'XMonad.Core.XConfig.keys' is:
> keys :: XConfig Layout -> M.Map (ButtonMask,KeySym) (X ())
In order to add new key bindings, you need to first create an
appropriate 'Data.Map.Map' from a list of key bindings using
'Data.Map.fromList'. This 'Data.Map.Map' of new key bindings then
needs to be joined to a 'Data.Map.Map' of existing bindings using
'Data.Map.union'.
Since we are going to need some of the functions of the "Data.Map"
module, before starting we must first import this modules:
> import qualified Data.Map as M
For instance, if you have defined some additional key bindings like
these:
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
then you can create a new key bindings map by joining the default one
with yours:
> newKeys x = myKeys x `M.union` keys def x
Finally, you can use @newKeys@ in the 'XMonad.Core.XConfig.keys' field
of the configuration:
> main = xmonad $ def { keys = newKeys }
Alternatively, the '<+>' operator can be used which in this usage does exactly
the same as the explicit usage of 'M.union' and propagation of the config
argument, thanks to appropriate instances in "Data.Monoid".
> main = xmonad $ def { keys = myKeys <+> keys def }
All together, your @~\/.xmonad\/xmonad.hs@ would now look like this:
> module Main (main) where
>
> import XMonad
>
> import qualified Data.Map as M
> import Graphics.X11.Xlib
> import XMonad.Prompt
> import XMonad.Prompt.Shell
> import XMonad.Prompt.XMonad
>
> main :: IO ()
> main = xmonad $ def { keys = myKeys <+> keys def }
>
> myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
> [ ((modm, xK_F12), xmonadPrompt def)
> , ((modm, xK_F3 ), shellPrompt def)
> ]
There are much simpler ways to accomplish this, however, if you are
willing to use an extension module to help you configure your keys.
For instance, "XMonad.Util.EZConfig" and "XMonad.Util.CustomKeys" both
provide useful functions for editing your key bindings; "XMonad.Util.EZConfig" even lets you use emacs-style keybinding descriptions like \"M-C-<F12>\".
-}
{- $keyDel
#Removing_key_bindings#
Removing key bindings requires modifying the 'Data.Map.Map' which
stores the key bindings. This can be done with 'Data.Map.difference'
or with 'Data.Map.delete'.
For example, suppose you want to get rid of @mod-q@ and @mod-shift-q@
(you just want to leave xmonad running forever). To do this you need
to define @newKeys@ as a 'Data.Map.difference' between the default
map and the map of the key bindings you want to remove. Like so:
> newKeys x = keys def x `M.difference` keysToRemove x
>
> keysToRemove :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
> keysToRemove x = M.fromList
> [ ((modm , xK_q ), return ())
> , ((modm .|. shiftMask, xK_q ), return ())
> ]
As you can see, it doesn't matter what actions we associate with the
keys listed in @keysToRemove@, so we just use @return ()@ (the
\"null\" action).
It is also possible to simply define a list of keys we want to unbind
and then use 'Data.Map.delete' to remove them. In that case we would
write something like:
> newKeys x = foldr M.delete (keys def x) (keysToRemove x)
>
> keysToRemove :: XConfig Layout -> [(KeyMask, KeySym)]
> keysToRemove x =
> [ (modm , xK_q )
> , (modm .|. shiftMask, xK_q )
> ]
Another even simpler possibility is the use of some of the utilities
provided by the xmonad-contrib library. Look, for instance, at
'XMonad.Util.EZConfig.removeKeys'.
-}
{- $keyAddDel
#Adding_and_removing_key_bindings#
Adding and removing key bindings requires simply combining the steps
for removing and adding. Here is an example from
"XMonad.Config.Arossato":
> defKeys = keys def
> delKeys x = foldr M.delete (defKeys x) (toRemove x)
> newKeys x = foldr (uncurry M.insert) (delKeys x) (toAdd x)
> -- remove some of the default key bindings
> toRemove XConfig{modMask = modm} =
> [ (modm , xK_j )
> , (modm , xK_k )
> , (modm , xK_p )
> , (modm .|. shiftMask, xK_p )
> , (modm .|. shiftMask, xK_q )
> , (modm , xK_q )
> ] ++
> -- I want modm .|. shiftMask 1-9 to be free!
> [(shiftMask .|. modm, k) | k <- [xK_1 .. xK_9]]
> -- These are my personal key bindings
> toAdd XConfig{modMask = modm} =
> [ ((modm , xK_F12 ), xmonadPrompt def )
> , ((modm , xK_F3 ), shellPrompt def )
> ] ++
> -- Use modm .|. shiftMask .|. controlMask 1-9 instead
> [( (m .|. modm, k), windows $ f i)
> | (i, k) <- zip (workspaces x) [xK_1 .. xK_9]
> , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask .|. controlMask)]
> ]
You can achieve the same result using the "XMonad.Util.CustomKeys"
module; take a look at the 'XMonad.Util.CustomKeys.customKeys'
function in particular.
NOTE: modm is defined as the modMask you defined (or left as the default) in
your config.
-}
{- $mouse
#Editing_mouse_bindings#
Most of the previous discussion of key bindings applies to mouse
bindings as well. For example, you could configure button4 to close
the window you click on like so:
> import qualified Data.Map as M
>
> myMouse x = [ (0, button4), (\w -> focus w >> kill) ]
>
> newMouse x = M.union (mouseBindings def x) (M.fromList (myMouse x))
>
> main = xmonad $ def { ..., mouseBindings = newMouse, ... }
Overriding or deleting mouse bindings works similarly. You can also
configure mouse bindings much more easily using the
'XMonad.Util.EZConfig.additionalMouseBindings' and
'XMonad.Util.EZConfig.removeMouseBindings' functions from the
"XMonad.Util.EZConfig" module.
-}
{- $layoutHook
#Editing_the_layout_hook#
When you start an application that opens a new window, when you change
the focused window, or move it to another workspace, or change that
workspace's layout, xmonad will use the 'XMonad.Core.layoutHook' for
reordering the visible windows on the visible workspace(s).
Since different layouts may be attached to different workspaces, and
you can change them, xmonad needs to know which one to use. In this
sense the layoutHook may be thought as the list of layouts that
xmonad will use for laying out windows on the screen(s).
The problem is that the layout subsystem is implemented with an
advanced feature of the Haskell programming language: type classes.
This allows us to very easily write new layouts, combine or modify
existing layouts, create layouts with internal state, etc. See
"XMonad.Doc.Extending#The_LayoutClass" for more information. This
means that we cannot simply have a list of layouts as we used to have
before the 0.5 release: a list requires every member to belong to the
same type!
Instead the combination of layouts to be used by xmonad is created
with a specific layout combinator: 'XMonad.Layout.|||'.
Suppose we want a list with the 'XMonad.Layout.Full',
'XMonad.Layout.Tabbed.tabbed' and
'XMonad.Layout.Accordion.Accordion' layouts. First we import, in our
@~\/.xmonad\/xmonad.hs@, all the needed modules:
> import XMonad
>
> import XMonad.Layout.Tabbed
> import XMonad.Layout.Accordion
Then we create the combination of layouts we need:
> mylayoutHook = Full ||| tabbed shrinkText def ||| Accordion
Now, all we need to do is change the 'XMonad.Core.layoutHook'
field of the 'XMonad.Core.XConfig' record, like so:
> main = xmonad $ def { layoutHook = mylayoutHook }
Thanks to the new combinator, we can apply a layout modifier to a
whole combination of layouts, instead of applying it to each one. For
example, suppose we want to use the
'XMonad.Layout.NoBorders.noBorders' layout modifier, from the
"XMonad.Layout.NoBorders" module (which must be imported):
> mylayoutHook = noBorders (Full ||| tabbed shrinkText def ||| Accordion)
If we want only the tabbed layout without borders, then we may write:
> mylayoutHook = Full ||| noBorders (tabbed shrinkText def) ||| Accordion
Our @~\/.xmonad\/xmonad.hs@ will now look like this:
> import XMonad
>
> import XMonad.Layout.Tabbed
> import XMonad.Layout.Accordion
> import XMonad.Layout.NoBorders
>
> mylayoutHook = Full ||| noBorders (tabbed shrinkText def) ||| Accordion
>
> main = xmonad $ def { layoutHook = mylayoutHook }
That's it!
-}
{- $manageHook
#Editing_the_manage_hook#
The 'XMonad.Core.manageHook' is a very powerful tool for customizing
the behavior of xmonad with regard to new windows. Whenever a new
window is created, xmonad calls the 'XMonad.Core.manageHook', which
can thus be used to perform certain actions on the new window, such as
placing it in a specific workspace, ignoring it, or placing it in the
float layer.
The default 'XMonad.Core.manageHook' causes xmonad to float MPlayer
and Gimp, and to ignore gnome-panel, desktop_window, kicker, and
kdesktop.
The "XMonad.ManageHook" module provides some simple combinators that
can be used to alter the 'XMonad.Core.manageHook' by replacing or adding
to the default actions.
Let's start by analyzing the default 'XMonad.Config.manageHook', defined
in "XMonad.Config":
> manageHook :: ManageHook
> manageHook = composeAll
> [ className =? "MPlayer" --> doFloat
> , className =? "Gimp" --> doFloat
> , resource =? "desktop_window" --> doIgnore
> , resource =? "kdesktop" --> doIgnore ]
'XMonad.ManageHook.composeAll' can be used to compose a list of
different 'XMonad.Config.ManageHook's. In this example we have a list
of 'XMonad.Config.ManageHook's formed by the following commands: the
Mplayer's and the Gimp's windows, whose 'XMonad.ManageHook.className'
are, respectively \"Mplayer\" and \"Gimp\", are to be placed in the
float layer with the 'XMonad.ManageHook.doFloat' function; the windows
whose resource names are respectively \"desktop_window\" and
\kdesktop\" are to be ignored with the 'XMonad.ManageHook.doIgnore'
function.
This is another example of 'XMonad.Config.manageHook', taken from
"XMonad.Config.Arossato":
> myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat
> , resource =? "win" --> doF (W.shift "doc") -- xpdf
> , resource =? "firefox-bin" --> doF (W.shift "web")
> ]
> newManageHook = myManageHook <+> manageHook def
Again we use 'XMonad.ManageHook.composeAll' to compose a list of
different 'XMonad.Config.ManageHook's. The first one will put
RealPlayer on the float layer, the second one will put the xpdf
windows in the workspace named \"doc\", with 'XMonad.ManageHook.doF'
and 'XMonad.StackSet.shift' functions, and the third one will put all
firefox windows on the workspace called "web". Then we use the
'XMonad.ManageHook.<+>' combinator to compose @myManageHook@ with the
default 'XMonad.Config.manageHook' to form @newManageHook@.
Each 'XMonad.Config.ManageHook' has the form:
> property =? match --> action
Where @property@ can be:
* 'XMonad.ManageHook.title': the window's title
* 'XMonad.ManageHook.resource': the resource name
* 'XMonad.ManageHook.className': the resource class name.
* 'XMonad.ManageHook.stringProperty' @somestring@: the contents of the
property @somestring@.
(You can retrieve the needed information using the X utility named
@xprop@; for example, to find the resource class name, you can type
> xprop | grep WM_CLASS
at a prompt, then click on the window whose resource class you want to
know.)
@match@ is the string that will match the property value (for instance
the one you retrieved with @xprop@).
An @action@ can be:
* 'XMonad.ManageHook.doFloat': to place the window in the float layer;
* 'XMonad.ManageHook.doIgnore': to ignore the window;
* 'XMonad.ManageHook.doF': to execute a function with the window as
argument.
For example, suppose we want to add a 'XMonad.Config.manageHook' to
float RealPlayer, which usually has a 'XMonad.ManageHook.resource'
name of \"realplay.bin\".
First we need to import "XMonad.ManageHook":
> import XMonad.ManageHook
Then we create our own 'XMonad.Config.manageHook':
> myManageHook = resource =? "realplay.bin" --> doFloat
We can now use the 'XMonad.ManageHook.<+>' combinator to add our
'XMonad.Config.manageHook' to the default one:
> newManageHook = myManageHook <+> manageHook def
(Of course, if we wanted to completely replace the default
'XMonad.Config.manageHook', this step would not be necessary.) Now,
all we need to do is change the 'XMonad.Core.manageHook' field of the
'XMonad.Core.XConfig' record, like so:
> main = xmonad def { ..., manageHook = newManageHook, ... }
And we are done.
Obviously, we may wish to add more then one
'XMonad.Config.manageHook'. In this case we can use a list of hooks,
compose them all with 'XMonad.ManageHook.composeAll', and add the
composed to the default one.
For instance, if we want RealPlayer to float and thunderbird always
opened in the workspace named "mail", we can do so like this:
> myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat
> , resource =? "thunderbird-bin" --> doF (W.shift "mail")
> ]
Remember to import the module that defines the 'XMonad.StackSet.shift'
function, "XMonad.StackSet", like this:
> import qualified XMonad.StackSet as W
And then we can add @myManageHook@ to the default one to create
@newManageHook@ as we did in the previous example.
One more thing to note about this system is that if
a window matches multiple rules in a 'XMonad.Config.manageHook', /all/
of the corresponding actions will be run (in the order in which they
are defined). This is a change from versions before 0.5, when only
the first rule that matched was run.
Finally, for additional rules and actions you can use in your
manageHook, check out the contrib module "XMonad.Hooks.ManageHelpers".
-}
{- $logHook
#The_log_hook_and_external_status_bars#
When the stack of the windows managed by xmonad changes for any
reason, xmonad will call 'XMonad.Core.logHook', which can be used to
output some information about the internal state of xmonad, such as the
layout that is presently in use, the workspace we are in, the focused
window's title, and so on.
Extracting information about the internal xmonad state can be somewhat
difficult if you are not familiar with the source code. Therefore,
it's usually easiest to use a module that has been designed
specifically for logging some of the most interesting information
about the internal state of xmonad: "XMonad.Hooks.DynamicLog". This
module can be used with an external status bar to print the produced
logs in a convenient way; the most commonly used status bars are dzen
and xmobar.
By default the 'XMonad.Core.logHook' doesn't produce anything. To
enable it you need first to import "XMonad.Hooks.DynamicLog":
> import XMonad.Hooks.DynamicLog
Then you just need to update the 'XMonad.Core.logHook' field of the
'XMonad.Core.XConfig' record with one of the provided functions. For
example:
> main = xmonad def { logHook = dynamicLog }
More interesting configurations are also possible; see the
"XMonad.Hooks.DynamicLog" module for more possibilities.
You may now enjoy your extended xmonad experience.
Have fun!
-}
| CaptainPatate/xmonad-contrib | XMonad/Doc/Extending.hs | bsd-3-clause | 50,029 | 0 | 3 | 9,658 | 99 | 96 | 3 | 2 | 0 |
module Database.DSH.Backend.Sql.Relational.Synthetic
(
) where
| ulricha/dsh-sql | src/Database/DSH/Backend/Sql/Relational/Synthetic.hs | bsd-3-clause | 71 | 0 | 3 | 13 | 13 | 10 | 3 | 2 | 0 |
module Score where
import Control.Arrow ((&&&))
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.List (group,sort,sortBy,unfoldr,isPrefixOf)
import Data.Ord (comparing)
import qualified Data.Set as Set
import Types
import Command
move_score :: Pt -> Pt -> Pt -> Pt
move_score size ls ls_old = points + line_bonus
where
points = size + 50 * (1 + ls) * ls
line_bonus = if ls_old > 1
then ((ls_old - 1) * points `div` 10)
else 0
power_score :: [String] -> Commands -> Pt
power_score phs cmds = fst $ power_score' phs cmds
power_score' :: [String] -> Commands -> (Pt, String)
power_score' phs cmds = (computePowerScoreFromString phs s, s)
where
s = head $ commandsToString $ reverse cmds
{-
power_score' :: [String] -> Commands -> (Pt, String)
power_score' phs cmds = case countPhrases phs s of
[] -> (0, s)
xs -> ((uncurry (+) . (sum . map snd &&& (300 *) . length . group . sort)) xs, s)
where
s = head $ commandsToString $ reverse cmds
-}
countPhrases :: [String] -> String -> [(String,Int)]
countPhrases phs = unfoldr phi
where
phi [] = Nothing
phi xs@(_:rs) = case checkPrefixString phs' xs of
[] -> phi rs
(p,len):_ -> Just ((p,len*2),drop len xs)
phs' = sortBy (flip (comparing snd)) $ map (id &&& length) $ phs
checkPrefixString :: [(String,Int)] -> String -> [(String,Int)]
checkPrefixString pps cmdstr
= [ pp | pp@(p,_) <- pps, isPrefixOf p cmdstr ]
revcmds :: [(Commands,Pt)]
revcmds = map (f . reverse) $ fst $ unzip phraseDict
where
f = id &&& (2*) . length
checkRevCmdPrefix :: Commands -> [(Pt,Commands)]
checkRevCmdPrefix ts
= [(pt,drop clen ts) | e@(cs,pt) <- revcmds
, let pre = zipWith (==) ts cs
, and pre
, let plen = length pre
, let clen = length cs
, clen == plen
]
computePowerScoreFromString :: [String] -> String -> Pt
computePowerScoreFromString ps s = sum $ do
p <- ps
let p' = BS.pack p
resp = length $ BS.findSubstrings p' s'
guard $ resp > 0
return $ 2 * BS.length p' * resp + 300
where
s' = BS.pack s
| msakai/icfpc2015 | src/Score.hs | bsd-3-clause | 2,248 | 0 | 13 | 638 | 793 | 432 | 361 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.