code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.Wai.Handler.Warp.Internal (
-- * Settings
Settings (..)
, ProxyProtocol(..)
-- * Low level run functions
, runSettingsConnection
, runSettingsConnectionMaker
, runSettingsConnectionMakerSecure
, Transport (..)
-- * Connection
, Connection (..)
, socketConnection
-- ** Receive
, Recv
, RecvBuf
, makePlainReceiveN
-- ** Buffer
, Buffer
, BufSize
, bufferSize
, allocateBuffer
, freeBuffer
, copy
-- ** Sendfile
, FileId (..)
, SendFile
, sendFile
, readSendFile
-- * Version
, warpVersion
-- * Data types
, InternalInfo (..)
, HeaderValue
, IndexedHeader
, requestMaxIndex
-- * Time out manager
-- |
--
-- In order to provide slowloris protection, Warp provides timeout handlers. We
-- follow these rules:
--
-- * A timeout is created when a connection is opened.
--
-- * When all request headers are read, the timeout is tickled.
--
-- * Every time at least the slowloris size settings number of bytes of the request
-- body are read, the timeout is tickled.
--
-- * The timeout is paused while executing user code. This will apply to both
-- the application itself, and a ResponseSource response. The timeout is
-- resumed as soon as we return from user code.
--
-- * Every time data is successfully sent to the client, the timeout is tickled.
, module Network.Wai.Handler.Warp.Timeout
-- * File descriptor cache
, module Network.Wai.Handler.Warp.FdCache
-- * File information cache
, module Network.Wai.Handler.Warp.FileInfoCache
-- * Date
, module Network.Wai.Handler.Warp.Date
-- * Request and response
, Source
, recvRequest
, sendResponse
) where
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Date
import Network.Wai.Handler.Warp.FdCache
import Network.Wai.Handler.Warp.FileInfoCache
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Recv
import Network.Wai.Handler.Warp.Request
import Network.Wai.Handler.Warp.Response
import Network.Wai.Handler.Warp.Run
import Network.Wai.Handler.Warp.SendFile
import Network.Wai.Handler.Warp.Settings
import Network.Wai.Handler.Warp.Timeout
import Network.Wai.Handler.Warp.Types
| frontrowed/wai | warp/Network/Wai/Handler/Warp/Internal.hs | mit | 2,325 | 0 | 5 | 480 | 293 | 221 | 72 | 48 | 0 |
{-# LANGUAGE CPP #-}
import Data.Function
import System.Environment
import System.FilePath
import Test.Haddock
import Test.Haddock.Utils
checkConfig :: CheckConfig String
checkConfig = CheckConfig
{ ccfgRead = Just
, ccfgClean = \_ -> id
, ccfgDump = id
, ccfgEqual = (==) `on` crlfToLf
}
dirConfig :: DirConfig
dirConfig = defaultDirConfig $ takeDirectory __FILE__
main :: IO ()
main = do
cfg <- parseArgs checkConfig dirConfig =<< getArgs
runAndCheck $ cfg
{ cfgHaddockArgs = cfgHaddockArgs cfg ++
[ "--package-name=test"
, "--package-version=0.0.0"
, "--hoogle"
]
}
| Fuuzetsu/haddock | hoogle-test/Main.hs | bsd-2-clause | 670 | 0 | 11 | 183 | 159 | 91 | 68 | 22 | 1 |
import StackTest
import System.Directory (createDirectoryIfMissing)
import System.Environment (getEnv, setEnv)
import System.FilePath ((</>))
main :: IO ()
main = do
putStrLn "With pantry, non-Hackage Security indices are no longer supported, skipping test"
{-
home <- getEnv "HOME"
setEnv "STACK_ROOT" (home </> ".stack") -- Needed for Windows
createDirectoryIfMissing True (home </> ".stack" </> "indices" </> "CustomIndex")
copy "CustomIndex/01-index.tar" (home </> ".stack" </> "indices" </> "CustomIndex" </> "01-index.tar")
stack ["build"]
-}
| juhp/stack | test/integration/tests/3396-package-indices/Main.hs | bsd-3-clause | 612 | 0 | 7 | 131 | 61 | 35 | 26 | 7 | 1 |
{-# LANGUAGE ScopedTypeVariables, PatternGuards, ViewPatterns #-}
{-
Copyright (C) 2012-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.Docx
Copyright : Copyright (C) 2012-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 docx.
-}
module Text.Pandoc.Writers.Docx ( writeDocx ) where
import Data.List ( intercalate, isPrefixOf, isSuffixOf )
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Map as M
import qualified Text.Pandoc.UTF8 as UTF8
import Text.Pandoc.Compat.Monoid ((<>))
import Codec.Archive.Zip
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Time.Format
import System.Environment
import Text.Pandoc.Compat.Locale (defaultTimeLocale)
import Text.Pandoc.Definition
import Text.Pandoc.Generic
import Text.Pandoc.ImageSize
import Text.Pandoc.Shared hiding (Element)
import Text.Pandoc.Writers.Shared (fixDisplayMath)
import Text.Pandoc.Options
import Text.Pandoc.Readers.TeXMath
import Text.Pandoc.Highlighting ( highlight )
import Text.Pandoc.Walk
import Text.Highlighting.Kate.Types ()
import Text.XML.Light as XML
import Text.TeXMath
import Text.Pandoc.Readers.Docx.StyleMap
import Text.Pandoc.Readers.Docx.Util (elemName)
import Control.Monad.State
import Text.Highlighting.Kate
import Data.Unique (hashUnique, newUnique)
import System.Random (randomRIO)
import Text.Printf (printf)
import qualified Control.Exception as E
import Text.Pandoc.MIME (MimeType, getMimeType, getMimeTypeDef,
extensionFromMimeType)
import Control.Applicative ((<$>), (<|>), (<*>))
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Char (ord)
data ListMarker = NoMarker
| BulletMarker
| NumberMarker ListNumberStyle ListNumberDelim Int
deriving (Show, Read, Eq, Ord)
listMarkerToId :: ListMarker -> String
listMarkerToId NoMarker = "990"
listMarkerToId BulletMarker = "991"
listMarkerToId (NumberMarker sty delim n) =
'9' : '9' : styNum : delimNum : show n
where styNum = case sty of
DefaultStyle -> '2'
Example -> '3'
Decimal -> '4'
LowerRoman -> '5'
UpperRoman -> '6'
LowerAlpha -> '7'
UpperAlpha -> '8'
delimNum = case delim of
DefaultDelim -> '0'
Period -> '1'
OneParen -> '2'
TwoParens -> '3'
data WriterState = WriterState{
stTextProperties :: [Element]
, stParaProperties :: [Element]
, stFootnotes :: [Element]
, stSectionIds :: [String]
, stExternalLinks :: M.Map String String
, stImages :: M.Map FilePath (String, String, Maybe MimeType, Element, B.ByteString)
, stListLevel :: Int
, stListNumId :: Int
, stLists :: [ListMarker]
, stInsId :: Int
, stDelId :: Int
, stInDel :: Bool
, stChangesAuthor :: String
, stChangesDate :: String
, stPrintWidth :: Integer
, stStyleMaps :: StyleMaps
, stFirstPara :: Bool
, stTocTitle :: [Inline]
}
defaultWriterState :: WriterState
defaultWriterState = WriterState{
stTextProperties = []
, stParaProperties = []
, stFootnotes = defaultFootnotes
, stSectionIds = []
, stExternalLinks = M.empty
, stImages = M.empty
, stListLevel = -1
, stListNumId = 1
, stLists = [NoMarker]
, stInsId = 1
, stDelId = 1
, stInDel = False
, stChangesAuthor = "unknown"
, stChangesDate = "1969-12-31T19:00:00Z"
, stPrintWidth = 1
, stStyleMaps = defaultStyleMaps
, stFirstPara = False
, stTocTitle = normalizeInlines [Str "Table of Contents"]
}
type WS a = StateT WriterState IO a
mknode :: Node t => String -> [(String,String)] -> t -> Element
mknode s attrs =
add_attrs (map (\(k,v) -> Attr (nodename k) v) attrs) . node (nodename s)
nodename :: String -> QName
nodename s = QName{ qName = name, qURI = Nothing, qPrefix = prefix }
where (name, prefix) = case break (==':') s of
(xs,[]) -> (xs, Nothing)
(ys, _:zs) -> (zs, Just ys)
toLazy :: B.ByteString -> BL.ByteString
toLazy = BL.fromChunks . (:[])
renderXml :: Element -> BL.ByteString
renderXml elt = BL8.pack "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" <>
UTF8.fromStringLazy (showElement elt)
renumIdMap :: Int -> [Element] -> M.Map String String
renumIdMap _ [] = M.empty
renumIdMap n (e:es)
| Just oldId <- findAttr (QName "Id" Nothing Nothing) e =
M.insert oldId ("rId" ++ (show n)) (renumIdMap (n+1) es)
| otherwise = renumIdMap n es
replaceAttr :: (QName -> Bool) -> String -> [XML.Attr] -> [XML.Attr]
replaceAttr _ _ [] = []
replaceAttr f val (a:as) | f (attrKey a) =
(XML.Attr (attrKey a) val) : (replaceAttr f val as)
| otherwise = a : (replaceAttr f val as)
renumId :: (QName -> Bool) -> (M.Map String String) -> Element -> Element
renumId f renumMap e
| Just oldId <- findAttrBy f e
, Just newId <- M.lookup oldId renumMap =
let attrs' = replaceAttr f newId (elAttribs e)
in
e { elAttribs = attrs' }
| otherwise = e
renumIds :: (QName -> Bool) -> (M.Map String String) -> [Element] -> [Element]
renumIds f renumMap = map (renumId f renumMap)
-- | Certain characters are invalid in XML even if escaped.
-- See #1992
stripInvalidChars :: String -> String
stripInvalidChars = filter isValidChar
-- | See XML reference
isValidChar :: Char -> Bool
isValidChar (ord -> c)
| c == 0x9 = True
| c == 0xA = True
| c == 0xD = True
| 0x20 <= c && c <= 0xD7FF = True
| 0xE000 <= c && c <= 0xFFFD = True
| 0x10000 <= c && c <= 0x10FFFF = True
| otherwise = False
metaValueToInlines :: MetaValue -> [Inline]
metaValueToInlines (MetaString s) = normalizeInlines [Str s]
metaValueToInlines (MetaInlines ils) = ils
metaValueToInlines (MetaBlocks bs) = query return bs
metaValueToInlines (MetaBool b) = [Str $ show b]
metaValueToInlines _ = []
-- | Produce an Docx file from a Pandoc document.
writeDocx :: WriterOptions -- ^ Writer options
-> Pandoc -- ^ Document to convert
-> IO BL.ByteString
writeDocx opts doc@(Pandoc meta _) = do
let datadir = writerUserDataDir opts
let doc' = walk fixDisplayMath $ doc
username <- lookup "USERNAME" <$> getEnvironment
utctime <- getCurrentTime
distArchive <- getDefaultReferenceDocx Nothing
refArchive <- case writerReferenceDocx opts of
Just f -> liftM (toArchive . toLazy) $ B.readFile f
Nothing -> getDefaultReferenceDocx datadir
parsedDoc <- parseXml refArchive distArchive "word/document.xml"
let wname f qn = qPrefix qn == Just "w" && f (qName qn)
let mbsectpr = filterElementName (wname (=="sectPr")) parsedDoc
-- Gets the template size
let mbpgsz = mbsectpr >>= (filterElementName (wname (=="pgSz")))
let mbAttrSzWidth = (elAttribs <$> mbpgsz) >>= (lookupAttrBy ((=="w") . qName))
let mbpgmar = mbsectpr >>= (filterElementName (wname (=="pgMar")))
let mbAttrMarLeft = (elAttribs <$> mbpgmar) >>= (lookupAttrBy ((=="left") . qName))
let mbAttrMarRight = (elAttribs <$> mbpgmar) >>= (lookupAttrBy ((=="right") . qName))
-- Get the avaible area (converting the size and the margins to int and
-- doing the difference
let pgContentWidth = (-) <$> (read <$> mbAttrSzWidth ::Maybe Integer)
<*> (
(+) <$> (read <$> mbAttrMarRight ::Maybe Integer)
<*> (read <$> mbAttrMarLeft ::Maybe Integer)
)
-- styles
let stylepath = "word/styles.xml"
styledoc <- parseXml refArchive distArchive stylepath
-- parse styledoc for heading styles
let styleMaps = getStyleMaps styledoc
let tocTitle = fromMaybe (stTocTitle defaultWriterState) $
metaValueToInlines <$> lookupMeta "toc-title" meta
((contents, footnotes), st) <- runStateT (writeOpenXML opts{writerWrapText = False} doc')
defaultWriterState{ stChangesAuthor = fromMaybe "unknown" username
, stChangesDate = formatTime defaultTimeLocale "%FT%XZ" utctime
, stPrintWidth = (maybe 420 (\x -> quot x 20) pgContentWidth)
, stStyleMaps = styleMaps
, stTocTitle = tocTitle
}
let epochtime = floor $ utcTimeToPOSIXSeconds utctime
let imgs = M.elems $ stImages st
-- create entries for images in word/media/...
let toImageEntry (_,path,_,_,img) = toEntry ("word/" ++ path) epochtime $ toLazy img
let imageEntries = map toImageEntry imgs
let stdAttributes =
[("xmlns:w","http://schemas.openxmlformats.org/wordprocessingml/2006/main")
,("xmlns:m","http://schemas.openxmlformats.org/officeDocument/2006/math")
,("xmlns:r","http://schemas.openxmlformats.org/officeDocument/2006/relationships")
,("xmlns:o","urn:schemas-microsoft-com:office:office")
,("xmlns:v","urn:schemas-microsoft-com:vml")
,("xmlns:w10","urn:schemas-microsoft-com:office:word")
,("xmlns:a","http://schemas.openxmlformats.org/drawingml/2006/main")
,("xmlns:pic","http://schemas.openxmlformats.org/drawingml/2006/picture")
,("xmlns:wp","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")]
parsedRels <- parseXml refArchive distArchive "word/_rels/document.xml.rels"
let isHeaderNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
let isFooterNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"
let headers = filterElements isHeaderNode parsedRels
let footers = filterElements isFooterNode parsedRels
let extractTarget = findAttr (QName "Target" Nothing Nothing)
-- we create [Content_Types].xml and word/_rels/document.xml.rels
-- from scratch rather than reading from reference.docx,
-- because Word sometimes changes these files when a reference.docx is modified,
-- e.g. deleting the reference to footnotes.xml or removing default entries
-- for image content types.
-- [Content_Types].xml
let mkOverrideNode (part', contentType') = mknode "Override"
[("PartName",part'),("ContentType",contentType')] ()
let mkImageOverride (_, imgpath, mbMimeType, _, _) =
mkOverrideNode ("/word/" ++ imgpath,
fromMaybe "application/octet-stream" mbMimeType)
let mkMediaOverride imgpath =
mkOverrideNode ('/':imgpath, getMimeTypeDef imgpath)
let overrides = map mkOverrideNode (
[("/word/webSettings.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml")
,("/word/numbering.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml")
,("/word/settings.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml")
,("/word/theme/theme1.xml",
"application/vnd.openxmlformats-officedocument.theme+xml")
,("/word/fontTable.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml")
,("/docProps/app.xml",
"application/vnd.openxmlformats-officedocument.extended-properties+xml")
,("/docProps/core.xml",
"application/vnd.openxmlformats-package.core-properties+xml")
,("/word/styles.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")
,("/word/document.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
,("/word/footnotes.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml")
] ++
map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml")) headers ++
map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml")) footers) ++
map mkImageOverride imgs ++
map mkMediaOverride [ eRelativePath e | e <- zEntries refArchive
, "word/media/" `isPrefixOf` eRelativePath e ]
let defaultnodes = [mknode "Default"
[("Extension","xml"),("ContentType","application/xml")] (),
mknode "Default"
[("Extension","rels"),("ContentType","application/vnd.openxmlformats-package.relationships+xml")] ()]
let contentTypesDoc = mknode "Types" [("xmlns","http://schemas.openxmlformats.org/package/2006/content-types")] $ defaultnodes ++ overrides
let contentTypesEntry = toEntry "[Content_Types].xml" epochtime
$ renderXml contentTypesDoc
-- word/_rels/document.xml.rels
let toBaseRel (url', id', target') = mknode "Relationship"
[("Type",url')
,("Id",id')
,("Target",target')] ()
let baserels' = map toBaseRel
[("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
"rId1",
"numbering.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
"rId2",
"styles.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
"rId3",
"settings.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
"rId4",
"webSettings.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
"rId5",
"fontTable.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
"rId6",
"theme/theme1.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
"rId7",
"footnotes.xml")
]
let idMap = renumIdMap (length baserels' + 1) (headers ++ footers)
let renumHeaders = renumIds (\q -> qName q == "Id") idMap headers
let renumFooters = renumIds (\q -> qName q == "Id") idMap footers
let baserels = baserels' ++ renumHeaders ++ renumFooters
let toImgRel (ident,path,_,_,_) = mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"),("Id",ident),("Target",path)] ()
let imgrels = map toImgRel imgs
let toLinkRel (src,ident) = mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"),("Id",ident),("Target",src),("TargetMode","External") ] ()
let linkrels = map toLinkRel $ M.toList $ stExternalLinks st
let reldoc = mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")] $ baserels ++ imgrels ++ linkrels
let relEntry = toEntry "word/_rels/document.xml.rels" epochtime
$ renderXml reldoc
-- adjust contents to add sectPr from reference.docx
let sectpr = case mbsectpr of
Just sectpr' -> let cs = renumIds
(\q -> qName q == "id" && qPrefix q == Just "r")
idMap
(elChildren sectpr')
in
add_attrs (elAttribs sectpr') $ mknode "w:sectPr" [] cs
Nothing -> (mknode "w:sectPr" [] ())
-- let sectpr = fromMaybe (mknode "w:sectPr" [] ()) mbsectpr'
let contents' = contents ++ [sectpr]
let docContents = mknode "w:document" stdAttributes
$ mknode "w:body" [] contents'
-- word/document.xml
let contentEntry = toEntry "word/document.xml" epochtime
$ renderXml docContents
-- footnotes
let notes = mknode "w:footnotes" stdAttributes footnotes
let footnotesEntry = toEntry "word/footnotes.xml" epochtime $ renderXml notes
-- footnote rels
let footnoteRelEntry = toEntry "word/_rels/footnotes.xml.rels" epochtime
$ renderXml $ mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")]
linkrels
-- styles
let newstyles = styleToOpenXml styleMaps $ writerHighlightStyle opts
let styledoc' = styledoc{ elContent = modifyContent (elContent styledoc) }
where
modifyContent
| writerHighlight opts = (++ map Elem newstyles)
| otherwise = filter notTokStyle
notTokStyle (Elem el) = notStyle el || notTokId el
notTokStyle _ = True
notStyle = (/= elemName' "style") . elName
notTokId = maybe True (`notElem` tokStys) . findAttr (elemName' "styleId")
tokStys = "SourceCode" : map show (enumFromTo KeywordTok NormalTok)
elemName' = elemName (sNameSpaces styleMaps) "w"
let styleEntry = toEntry stylepath epochtime $ renderXml styledoc'
-- construct word/numbering.xml
let numpath = "word/numbering.xml"
numbering <- parseXml refArchive distArchive numpath
newNumElts <- mkNumbering (stLists st)
let allElts = onlyElems (elContent numbering) ++ newNumElts
let numEntry = toEntry numpath epochtime $ renderXml numbering{ elContent =
-- we want all the abstractNums first, then the nums,
-- otherwise things break:
[Elem e | e <- allElts
, qName (elName e) == "abstractNum" ] ++
[Elem e | e <- allElts
, qName (elName e) == "num" ] }
let docPropsPath = "docProps/core.xml"
let docProps = mknode "cp:coreProperties"
[("xmlns:cp","http://schemas.openxmlformats.org/package/2006/metadata/core-properties")
,("xmlns:dc","http://purl.org/dc/elements/1.1/")
,("xmlns:dcterms","http://purl.org/dc/terms/")
,("xmlns:dcmitype","http://purl.org/dc/dcmitype/")
,("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")]
$ mknode "dc:title" [] (stringify $ docTitle meta)
: mknode "dc:creator" [] (intercalate "; " (map stringify $ docAuthors meta))
: maybe []
(\x -> [ mknode "dcterms:created" [("xsi:type","dcterms:W3CDTF")] x
, mknode "dcterms:modified" [("xsi:type","dcterms:W3CDTF")] x
]) (normalizeDate $ stringify $ docDate meta)
let docPropsEntry = toEntry docPropsPath epochtime $ renderXml docProps
let relsPath = "_rels/.rels"
let rels = mknode "Relationships" [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
$ map (\attrs -> mknode "Relationship" attrs ())
[ [("Id","rId1")
,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
,("Target","word/document.xml")]
, [("Id","rId4")
,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties")
,("Target","docProps/app.xml")]
, [("Id","rId3")
,("Type","http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties")
,("Target","docProps/core.xml")]
]
let relsEntry = toEntry relsPath epochtime $ renderXml rels
-- we use dist archive for settings.xml, because Word sometimes
-- adds references to footnotes or endnotes we don't have...
-- we do, however, copy some settings over from reference
let settingsPath = "word/settings.xml"
settingsList = [ "w:autoHyphenation"
, "w:consecutiveHyphenLimit"
, "w:hyphenationZone"
, "w:doNotHyphenateCap"
]
settingsEntry <- copyChildren refArchive distArchive settingsPath epochtime settingsList
let entryFromArchive arch path =
maybe (fail $ path ++ " missing in reference docx")
return
(findEntryByPath path arch `mplus` findEntryByPath path distArchive)
docPropsAppEntry <- entryFromArchive refArchive "docProps/app.xml"
themeEntry <- entryFromArchive refArchive "word/theme/theme1.xml"
fontTableEntry <- entryFromArchive refArchive "word/fontTable.xml"
webSettingsEntry <- entryFromArchive refArchive "word/webSettings.xml"
headerFooterEntries <- mapM (entryFromArchive refArchive) $
mapMaybe (fmap ("word/" ++) . extractTarget)
(headers ++ footers)
let miscRelEntries = [ e | e <- zEntries refArchive
, "word/_rels/" `isPrefixOf` (eRelativePath e)
, ".xml.rels" `isSuffixOf` (eRelativePath e)
, eRelativePath e /= "word/_rels/document.xml.rels"
, eRelativePath e /= "word/_rels/footnotes.xml.rels" ]
let otherMediaEntries = [ e | e <- zEntries refArchive
, "word/media/" `isPrefixOf` eRelativePath e ]
-- Create archive
let archive = foldr addEntryToArchive emptyArchive $
contentTypesEntry : relsEntry : contentEntry : relEntry :
footnoteRelEntry : numEntry : styleEntry : footnotesEntry :
docPropsEntry : docPropsAppEntry : themeEntry :
fontTableEntry : settingsEntry : webSettingsEntry :
imageEntries ++ headerFooterEntries ++
miscRelEntries ++ otherMediaEntries
return $ fromArchive archive
styleToOpenXml :: StyleMaps -> Style -> [Element]
styleToOpenXml sm style =
maybeToList parStyle ++ mapMaybe toStyle alltoktypes
where alltoktypes = enumFromTo KeywordTok NormalTok
toStyle toktype | hasStyleName (show toktype) (sCharStyleMap sm) = Nothing
| otherwise = Just $
mknode "w:style" [("w:type","character"),
("w:customStyle","1"),("w:styleId",show toktype)]
[ mknode "w:name" [("w:val",show toktype)] ()
, mknode "w:basedOn" [("w:val","VerbatimChar")] ()
, mknode "w:rPr" [] $
[ mknode "w:color" [("w:val",tokCol toktype)] ()
| tokCol toktype /= "auto" ] ++
[ mknode "w:shd" [("w:val","clear"),("w:fill",tokBg toktype)] ()
| tokBg toktype /= "auto" ] ++
[ mknode "w:b" [] () | tokFeature tokenBold toktype ] ++
[ mknode "w:i" [] () | tokFeature tokenItalic toktype ] ++
[ mknode "w:u" [] () | tokFeature tokenUnderline toktype ]
]
tokStyles = tokenStyles style
tokFeature f toktype = maybe False f $ lookup toktype tokStyles
tokCol toktype = maybe "auto" (drop 1 . fromColor)
$ (tokenColor =<< lookup toktype tokStyles)
`mplus` defaultColor style
tokBg toktype = maybe "auto" (drop 1 . fromColor)
$ (tokenBackground =<< lookup toktype tokStyles)
`mplus` backgroundColor style
parStyle | hasStyleName "Source Code" (sParaStyleMap sm) = Nothing
| otherwise = Just $
mknode "w:style" [("w:type","paragraph"),
("w:customStyle","1"),("w:styleId","SourceCode")]
[ mknode "w:name" [("w:val","Source Code")] ()
, mknode "w:basedOn" [("w:val","Normal")] ()
, mknode "w:link" [("w:val","VerbatimChar")] ()
, mknode "w:pPr" []
$ mknode "w:wordWrap" [("w:val","off")] ()
: mknode "w:noProof" [] ()
: ( maybe [] (\col -> [mknode "w:shd" [("w:val","clear"),("w:fill",drop 1 $ fromColor col)] ()])
$ backgroundColor style )
]
copyChildren :: Archive -> Archive -> String -> Integer -> [String] -> IO Entry
copyChildren refArchive distArchive path timestamp elNames = do
ref <- parseXml refArchive distArchive path
dist <- parseXml distArchive distArchive path
return $ toEntry path timestamp $ renderXml dist{
elContent = elContent dist ++ copyContent ref
}
where
strName QName{qName=name, qPrefix=prefix}
| Just p <- prefix = p++":"++name
| otherwise = name
shouldCopy = (`elem` elNames) . strName
cleanElem el@Element{elName=name} = Elem el{elName=name{qURI=Nothing}}
copyContent = map cleanElem . filterChildrenName shouldCopy
-- this is the lowest number used for a list numId
baseListId :: Int
baseListId = 1000
mkNumbering :: [ListMarker] -> IO [Element]
mkNumbering lists = do
elts <- mapM mkAbstractNum (ordNub lists)
return $ elts ++ zipWith mkNum lists [baseListId..(baseListId + length lists - 1)]
mkNum :: ListMarker -> Int -> Element
mkNum marker numid =
mknode "w:num" [("w:numId",show numid)]
$ mknode "w:abstractNumId" [("w:val",listMarkerToId marker)] ()
: case marker of
NoMarker -> []
BulletMarker -> []
NumberMarker _ _ start ->
map (\lvl -> mknode "w:lvlOverride" [("w:ilvl",show (lvl :: Int))]
$ mknode "w:startOverride" [("w:val",show start)] ()) [0..6]
mkAbstractNum :: ListMarker -> IO Element
mkAbstractNum marker = do
nsid <- randomRIO (0x10000000 :: Integer, 0xFFFFFFFF :: Integer)
return $ mknode "w:abstractNum" [("w:abstractNumId",listMarkerToId marker)]
$ mknode "w:nsid" [("w:val", printf "%8x" nsid)] ()
: mknode "w:multiLevelType" [("w:val","multilevel")] ()
: map (mkLvl marker) [0..6]
mkLvl :: ListMarker -> Int -> Element
mkLvl marker lvl =
mknode "w:lvl" [("w:ilvl",show lvl)] $
[ mknode "w:start" [("w:val",start)] ()
| marker /= NoMarker && marker /= BulletMarker ] ++
[ mknode "w:numFmt" [("w:val",fmt)] ()
, mknode "w:lvlText" [("w:val",lvltxt)] ()
, mknode "w:lvlJc" [("w:val","left")] ()
, mknode "w:pPr" []
[ mknode "w:tabs" []
$ mknode "w:tab" [("w:val","num"),("w:pos",show $ lvl * step)] ()
, mknode "w:ind" [("w:left",show $ lvl * step + hang),("w:hanging",show hang)] ()
]
]
where (fmt, lvltxt, start) =
case marker of
NoMarker -> ("bullet"," ","1")
BulletMarker -> ("bullet",bulletFor lvl,"1")
NumberMarker st de n -> (styleFor st lvl
,patternFor de ("%" ++ show (lvl + 1))
,show n)
step = 720
hang = 480
bulletFor 0 = "\x2022" -- filled circle
bulletFor 1 = "\x2013" -- en dash
bulletFor 2 = "\x2022" -- hyphen bullet
bulletFor 3 = "\x2013"
bulletFor 4 = "\x2022"
bulletFor 5 = "\x2013"
bulletFor _ = "\x2022"
styleFor UpperAlpha _ = "upperLetter"
styleFor LowerAlpha _ = "lowerLetter"
styleFor UpperRoman _ = "upperRoman"
styleFor LowerRoman _ = "lowerRoman"
styleFor Decimal _ = "decimal"
styleFor DefaultStyle 1 = "decimal"
styleFor DefaultStyle 2 = "lowerLetter"
styleFor DefaultStyle 3 = "lowerRoman"
styleFor DefaultStyle 4 = "decimal"
styleFor DefaultStyle 5 = "lowerLetter"
styleFor DefaultStyle 6 = "lowerRoman"
styleFor _ _ = "decimal"
patternFor OneParen s = s ++ ")"
patternFor TwoParens s = "(" ++ s ++ ")"
patternFor _ s = s ++ "."
getNumId :: WS Int
getNumId = (((baseListId - 1) +) . length) `fmap` gets stLists
makeTOC :: WriterOptions -> WS [Element]
makeTOC opts | writerTableOfContents opts = do
let depth = "1-"++(show (writerTOCDepth opts))
let tocCmd = "TOC \\o \""++depth++"\" \\h \\z \\u"
tocTitle <- gets stTocTitle
title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para tocTitle])
return $
[mknode "w:sdt" [] ([
mknode "w:sdtPr" [] (
mknode "w:docPartObj" [] (
[mknode "w:docPartGallery" [("w:val","Table of Contents")] (),
mknode "w:docPartUnique" [] ()]
) -- w:docPartObj
), -- w:sdtPr
mknode "w:sdtContent" [] (title++[
mknode "w:p" [] (
mknode "w:r" [] ([
mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
mknode "w:instrText" [("xml:space","preserve")] tocCmd,
mknode "w:fldChar" [("w:fldCharType","separate")] (),
mknode "w:fldChar" [("w:fldCharType","end")] ()
]) -- w:r
) -- w:p
])
])] -- w:sdt
makeTOC _ = return []
-- | Convert Pandoc document to two lists of
-- OpenXML elements (the main document and footnotes).
writeOpenXML :: WriterOptions -> Pandoc -> WS ([Element], [Element])
writeOpenXML opts (Pandoc meta blocks) = do
let tit = docTitle meta ++ case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> LineBreak : xs
_ -> []
let auths = docAuthors meta
let dat = docDate meta
let abstract' = case lookupMeta "abstract" meta of
Just (MetaBlocks bs) -> bs
Just (MetaInlines ils) -> [Plain ils]
_ -> []
let subtitle' = case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> xs
Just (MetaBlocks [Para xs]) -> xs
Just (MetaInlines xs) -> xs
_ -> []
title <- withParaPropM (pStyleM "Title") $ blocksToOpenXML opts [Para tit | not (null tit)]
subtitle <- withParaPropM (pStyleM "Subtitle") $ blocksToOpenXML opts [Para subtitle' | not (null subtitle')]
authors <- withParaProp (pCustomStyle "Author") $ blocksToOpenXML opts $
map Para auths
date <- withParaPropM (pStyleM "Date") $ blocksToOpenXML opts [Para dat | not (null dat)]
abstract <- if null abstract'
then return []
else withParaProp (pCustomStyle "Abstract") $ blocksToOpenXML opts abstract'
let convertSpace (Str x : Space : Str y : xs) = Str (x ++ " " ++ y) : xs
convertSpace (Str x : Str y : xs) = Str (x ++ y) : xs
convertSpace xs = xs
let blocks' = bottomUp convertSpace blocks
doc' <- (setFirstPara >> blocksToOpenXML opts blocks')
notes' <- reverse `fmap` gets stFootnotes
toc <- makeTOC opts
let meta' = title ++ subtitle ++ authors ++ date ++ abstract ++ toc
return (meta' ++ doc', notes')
-- | Convert a list of Pandoc blocks to OpenXML.
blocksToOpenXML :: WriterOptions -> [Block] -> WS [Element]
blocksToOpenXML opts bls = concat `fmap` mapM (blockToOpenXML opts) bls
pCustomStyle :: String -> Element
pCustomStyle sty = mknode "w:pStyle" [("w:val",sty)] ()
pStyleM :: String -> WS XML.Element
pStyleM styleName = do
styleMaps <- gets stStyleMaps
let sty' = getStyleId styleName $ sParaStyleMap styleMaps
return $ mknode "w:pStyle" [("w:val",sty')] ()
rCustomStyle :: String -> Element
rCustomStyle sty = mknode "w:rStyle" [("w:val",sty)] ()
rStyleM :: String -> WS XML.Element
rStyleM styleName = do
styleMaps <- gets stStyleMaps
let sty' = getStyleId styleName $ sCharStyleMap styleMaps
return $ mknode "w:rStyle" [("w:val",sty')] ()
getUniqueId :: MonadIO m => m String
-- the + 20 is to ensure that there are no clashes with the rIds
-- already in word/document.xml.rel
getUniqueId = liftIO $ (show . (+ 20) . hashUnique) `fmap` newUnique
-- | Convert a Pandoc block element to OpenXML.
blockToOpenXML :: WriterOptions -> Block -> WS [Element]
blockToOpenXML _ Null = return []
blockToOpenXML opts (Div (_,["references"],_) bs) = do
let (hs, bs') = span isHeaderBlock bs
header <- blocksToOpenXML opts hs
-- We put the Bibliography style on paragraphs after the header
rest <- withParaPropM (pStyleM "Bibliography") $ blocksToOpenXML opts bs'
return (header ++ rest)
blockToOpenXML opts (Div _ bs) = blocksToOpenXML opts bs
blockToOpenXML opts (Header lev (ident,_,_) lst) = do
setFirstPara
paraProps <- withParaPropM (pStyleM ("Heading "++show lev)) $
getParaProps False
contents <- inlinesToOpenXML opts lst
usedIdents <- gets stSectionIds
let bookmarkName = if null ident
then uniqueIdent lst usedIdents
else ident
modify $ \s -> s{ stSectionIds = bookmarkName : stSectionIds s }
id' <- getUniqueId
let bookmarkStart = mknode "w:bookmarkStart" [("w:id", id')
,("w:name",bookmarkName)] ()
let bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
return [mknode "w:p" [] (paraProps ++ [bookmarkStart, bookmarkEnd] ++ contents)]
blockToOpenXML opts (Plain lst) = withParaProp (pCustomStyle "Compact")
$ blockToOpenXML opts (Para lst)
-- title beginning with fig: indicates that the image is a figure
blockToOpenXML opts (Para [Image alt (src,'f':'i':'g':':':tit)]) = do
setFirstPara
pushParaProp $ pCustomStyle $
if null alt
then "Figure"
else "FigureWithCaption"
paraProps <- getParaProps False
popParaProp
contents <- inlinesToOpenXML opts [Image alt (src,tit)]
captionNode <- withParaProp (pCustomStyle "ImageCaption")
$ blockToOpenXML opts (Para alt)
return $ mknode "w:p" [] (paraProps ++ contents) : captionNode
-- fixDisplayMath sometimes produces a Para [] as artifact
blockToOpenXML _ (Para []) = return []
blockToOpenXML opts (Para lst) = do
isFirstPara <- gets stFirstPara
paraProps <- getParaProps $ case lst of
[Math DisplayMath _] -> True
_ -> False
bodyTextStyle <- pStyleM "Body Text"
let paraProps' = case paraProps of
[] | isFirstPara -> [mknode "w:pPr" [] [pCustomStyle "FirstParagraph"]]
[] -> [mknode "w:pPr" [] [bodyTextStyle]]
ps -> ps
modify $ \s -> s { stFirstPara = False }
contents <- inlinesToOpenXML opts lst
return [mknode "w:p" [] (paraProps' ++ contents)]
blockToOpenXML _ (RawBlock format str)
| format == Format "openxml" = return [ x | Elem x <- parseXML str ]
| otherwise = return []
blockToOpenXML opts (BlockQuote blocks) = do
p <- withParaPropM (pStyleM "Block Text") $ blocksToOpenXML opts blocks
setFirstPara
return p
blockToOpenXML opts (CodeBlock attrs str) = do
p <- withParaProp (pCustomStyle "SourceCode") (blockToOpenXML opts $ Para [Code attrs str])
setFirstPara
return p
blockToOpenXML _ HorizontalRule = do
setFirstPara
return [
mknode "w:p" [] $ mknode "w:r" [] $ mknode "w:pict" []
$ mknode "v:rect" [("style","width:0;height:1.5pt"),
("o:hralign","center"),
("o:hrstd","t"),("o:hr","t")] () ]
blockToOpenXML opts (Table caption aligns widths headers rows) = do
setFirstPara
let captionStr = stringify caption
caption' <- if null caption
then return []
else withParaProp (pCustomStyle "TableCaption")
$ blockToOpenXML opts (Para caption)
let alignmentFor al = mknode "w:jc" [("w:val",alignmentToString al)] ()
let cellToOpenXML (al, cell) = withParaProp (alignmentFor al)
$ blocksToOpenXML opts cell
headers' <- mapM cellToOpenXML $ zip aligns headers
rows' <- mapM (mapM cellToOpenXML . zip aligns) rows
let borderProps = mknode "w:tcPr" []
[ mknode "w:tcBorders" []
$ mknode "w:bottom" [("w:val","single")] ()
, mknode "w:vAlign" [("w:val","bottom")] () ]
let emptyCell = [mknode "w:p" [] [pCustomStyle "Compact"]]
let mkcell border contents = mknode "w:tc" []
$ [ borderProps | border ] ++
if null contents
then emptyCell
else contents
let mkrow border cells = mknode "w:tr" [] $
[mknode "w:trPr" [] [
mknode "w:cnfStyle" [("w:firstRow","1")] ()] | border]
++ map (mkcell border) cells
let textwidth = 7920 -- 5.5 in in twips, 1/20 pt
let fullrow = 5000 -- 100% specified in pct
let rowwidth = fullrow * sum widths
let mkgridcol w = mknode "w:gridCol"
[("w:w", show (floor (textwidth * w) :: Integer))] ()
let hasHeader = not (all null headers)
return $
caption' ++
[mknode "w:tbl" []
( mknode "w:tblPr" []
( mknode "w:tblStyle" [("w:val","TableNormal")] () :
mknode "w:tblW" [("w:type", "pct"), ("w:w", show rowwidth)] () :
mknode "w:tblLook" [("w:firstRow","1") | hasHeader ] () :
[ mknode "w:tblCaption" [("w:val", captionStr)] ()
| not (null caption) ] )
: mknode "w:tblGrid" []
(if all (==0) widths
then []
else map mkgridcol widths)
: [ mkrow True headers' | hasHeader ] ++
map (mkrow False) rows'
)]
blockToOpenXML opts (BulletList lst) = do
let marker = BulletMarker
addList marker
numid <- getNumId
l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
setFirstPara
return l
blockToOpenXML opts (OrderedList (start, numstyle, numdelim) lst) = do
let marker = NumberMarker numstyle numdelim start
addList marker
numid <- getNumId
l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
setFirstPara
return l
blockToOpenXML opts (DefinitionList items) = do
l <- concat `fmap` mapM (definitionListItemToOpenXML opts) items
setFirstPara
return l
definitionListItemToOpenXML :: WriterOptions -> ([Inline],[[Block]]) -> WS [Element]
definitionListItemToOpenXML opts (term,defs) = do
term' <- withParaProp (pCustomStyle "DefinitionTerm")
$ blockToOpenXML opts (Para term)
defs' <- withParaProp (pCustomStyle "Definition")
$ concat `fmap` mapM (blocksToOpenXML opts) defs
return $ term' ++ defs'
addList :: ListMarker -> WS ()
addList marker = do
lists <- gets stLists
modify $ \st -> st{ stLists = lists ++ [marker] }
listItemToOpenXML :: WriterOptions -> Int -> [Block] -> WS [Element]
listItemToOpenXML _ _ [] = return []
listItemToOpenXML opts numid (first:rest) = do
first' <- withNumId numid $ blockToOpenXML opts first
-- baseListId is the code for no list marker:
rest' <- withNumId baseListId $ blocksToOpenXML opts rest
return $ first' ++ rest'
alignmentToString :: Alignment -> [Char]
alignmentToString alignment = case alignment of
AlignLeft -> "left"
AlignRight -> "right"
AlignCenter -> "center"
AlignDefault -> "left"
-- | Convert a list of inline elements to OpenXML.
inlinesToOpenXML :: WriterOptions -> [Inline] -> WS [Element]
inlinesToOpenXML opts lst = concat `fmap` mapM (inlineToOpenXML opts) lst
withNumId :: Int -> WS a -> WS a
withNumId numid p = do
origNumId <- gets stListNumId
modify $ \st -> st{ stListNumId = numid }
result <- p
modify $ \st -> st{ stListNumId = origNumId }
return result
asList :: WS a -> WS a
asList p = do
origListLevel <- gets stListLevel
modify $ \st -> st{ stListLevel = stListLevel st + 1 }
result <- p
modify $ \st -> st{ stListLevel = origListLevel }
return result
getTextProps :: WS [Element]
getTextProps = do
props <- gets stTextProperties
return $ if null props
then []
else [mknode "w:rPr" [] props]
pushTextProp :: Element -> WS ()
pushTextProp d = modify $ \s -> s{ stTextProperties = d : stTextProperties s }
popTextProp :: WS ()
popTextProp = modify $ \s -> s{ stTextProperties = drop 1 $ stTextProperties s }
withTextProp :: Element -> WS a -> WS a
withTextProp d p = do
pushTextProp d
res <- p
popTextProp
return res
withTextPropM :: WS Element -> WS a -> WS a
withTextPropM = (. flip withTextProp) . (>>=)
getParaProps :: Bool -> WS [Element]
getParaProps displayMathPara = do
props <- gets stParaProperties
listLevel <- gets stListLevel
numid <- gets stListNumId
let listPr = if listLevel >= 0 && not displayMathPara
then [ mknode "w:numPr" []
[ mknode "w:numId" [("w:val",show numid)] ()
, mknode "w:ilvl" [("w:val",show listLevel)] () ]
]
else []
return $ case props ++ listPr of
[] -> []
ps -> [mknode "w:pPr" [] ps]
pushParaProp :: Element -> WS ()
pushParaProp d = modify $ \s -> s{ stParaProperties = d : stParaProperties s }
popParaProp :: WS ()
popParaProp = modify $ \s -> s{ stParaProperties = drop 1 $ stParaProperties s }
withParaProp :: Element -> WS a -> WS a
withParaProp d p = do
pushParaProp d
res <- p
popParaProp
return res
withParaPropM :: WS Element -> WS a -> WS a
withParaPropM = (. flip withParaProp) . (>>=)
formattedString :: String -> WS [Element]
formattedString str = do
props <- getTextProps
inDel <- gets stInDel
return [ mknode "w:r" [] $
props ++
[ mknode (if inDel then "w:delText" else "w:t")
[("xml:space","preserve")] (stripInvalidChars str) ] ]
setFirstPara :: WS ()
setFirstPara = modify $ \s -> s { stFirstPara = True }
-- | Convert an inline element to OpenXML.
inlineToOpenXML :: WriterOptions -> Inline -> WS [Element]
inlineToOpenXML _ (Str str) = formattedString str
inlineToOpenXML opts Space = inlineToOpenXML opts (Str " ")
inlineToOpenXML opts (Span (_,classes,kvs) ils)
| "insertion" `elem` classes = do
defaultAuthor <- gets stChangesAuthor
defaultDate <- gets stChangesDate
let author = fromMaybe defaultAuthor (lookup "author" kvs)
date = fromMaybe defaultDate (lookup "date" kvs)
insId <- gets stInsId
modify $ \s -> s{stInsId = (insId + 1)}
x <- inlinesToOpenXML opts ils
return [ mknode "w:ins" [("w:id", (show insId)),
("w:author", author),
("w:date", date)]
x ]
| "deletion" `elem` classes = do
defaultAuthor <- gets stChangesAuthor
defaultDate <- gets stChangesDate
let author = fromMaybe defaultAuthor (lookup "author" kvs)
date = fromMaybe defaultDate (lookup "date" kvs)
delId <- gets stDelId
modify $ \s -> s{stDelId = (delId + 1)}
modify $ \s -> s{stInDel = True}
x <- inlinesToOpenXML opts ils
modify $ \s -> s{stInDel = False}
return [ mknode "w:del" [("w:id", (show delId)),
("w:author", author),
("w:date", date)]
x ]
| otherwise = do
let off x = withTextProp (mknode x [("w:val","0")] ())
((if "csl-no-emph" `elem` classes then off "w:i" else id) .
(if "csl-no-strong" `elem` classes then off "w:b" else id) .
(if "csl-no-smallcaps" `elem` classes then off "w:smallCaps" else id))
$ inlinesToOpenXML opts ils
inlineToOpenXML opts (Strong lst) =
withTextProp (mknode "w:b" [] ()) $ inlinesToOpenXML opts lst
inlineToOpenXML opts (Emph lst) =
withTextProp (mknode "w:i" [] ()) $ inlinesToOpenXML opts lst
inlineToOpenXML opts (Subscript lst) =
withTextProp (mknode "w:vertAlign" [("w:val","subscript")] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (Superscript lst) =
withTextProp (mknode "w:vertAlign" [("w:val","superscript")] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (SmallCaps lst) =
withTextProp (mknode "w:smallCaps" [] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (Strikeout lst) =
withTextProp (mknode "w:strike" [] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML _ LineBreak = return [br]
inlineToOpenXML _ (RawInline f str)
| f == Format "openxml" = return [ x | Elem x <- parseXML str ]
| otherwise = return []
inlineToOpenXML opts (Quoted quoteType lst) =
inlinesToOpenXML opts $ [Str open] ++ lst ++ [Str close]
where (open, close) = case quoteType of
SingleQuote -> ("\x2018", "\x2019")
DoubleQuote -> ("\x201C", "\x201D")
inlineToOpenXML opts (Math mathType str) = do
let displayType = if mathType == DisplayMath
then DisplayBlock
else DisplayInline
case writeOMML displayType <$> readTeX str of
Right r -> return [r]
Left _ -> inlinesToOpenXML opts (texMathToInlines mathType str)
inlineToOpenXML opts (Cite _ lst) = inlinesToOpenXML opts lst
inlineToOpenXML opts (Code attrs str) = do
let unhighlighted = intercalate [br] `fmap`
(mapM formattedString $ lines str)
formatOpenXML _fmtOpts = intercalate [br] . map (map toHlTok)
toHlTok (toktype,tok) = mknode "w:r" []
[ mknode "w:rPr" []
[ rCustomStyle (show toktype) ]
, mknode "w:t" [("xml:space","preserve")] tok ]
withTextProp (rCustomStyle "VerbatimChar")
$ if writerHighlight opts
then case highlight formatOpenXML attrs str of
Nothing -> unhighlighted
Just h -> return h
else unhighlighted
inlineToOpenXML opts (Note bs) = do
notes <- gets stFootnotes
notenum <- getUniqueId
footnoteStyle <- rStyleM "Footnote Reference"
let notemarker = mknode "w:r" []
[ mknode "w:rPr" [] footnoteStyle
, mknode "w:footnoteRef" [] () ]
let notemarkerXml = RawInline (Format "openxml") $ ppElement notemarker
let insertNoteRef (Plain ils : xs) = Plain (notemarkerXml : ils) : xs
insertNoteRef (Para ils : xs) = Para (notemarkerXml : ils) : xs
insertNoteRef xs = Para [notemarkerXml] : xs
oldListLevel <- gets stListLevel
oldParaProperties <- gets stParaProperties
oldTextProperties <- gets stTextProperties
modify $ \st -> st{ stListLevel = -1, stParaProperties = [], stTextProperties = [] }
contents <- withParaPropM (pStyleM "Footnote Text") $ blocksToOpenXML opts
$ insertNoteRef bs
modify $ \st -> st{ stListLevel = oldListLevel, stParaProperties = oldParaProperties,
stTextProperties = oldTextProperties }
let newnote = mknode "w:footnote" [("w:id", notenum)] $ contents
modify $ \s -> s{ stFootnotes = newnote : notes }
return [ mknode "w:r" []
[ mknode "w:rPr" [] footnoteStyle
, mknode "w:footnoteReference" [("w:id", notenum)] () ] ]
-- internal link:
inlineToOpenXML opts (Link txt ('#':xs,_)) = do
contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
return [ mknode "w:hyperlink" [("w:anchor",xs)] contents ]
-- external link:
inlineToOpenXML opts (Link txt (src,_)) = do
contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
extlinks <- gets stExternalLinks
id' <- case M.lookup src extlinks of
Just i -> return i
Nothing -> do
i <- ("rId"++) `fmap` getUniqueId
modify $ \st -> st{ stExternalLinks =
M.insert src i extlinks }
return i
return [ mknode "w:hyperlink" [("r:id",id')] contents ]
inlineToOpenXML opts (Image alt (src, tit)) = do
-- first, check to see if we've already done this image
pageWidth <- gets stPrintWidth
imgs <- gets stImages
case M.lookup src imgs of
Just (_,_,_,elt,_) -> return [elt]
Nothing -> do
res <- liftIO $
fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
case res of
Left (_ :: E.SomeException) -> do
liftIO $ warn $ "Could not find image `" ++ src ++ "', skipping..."
-- emit alt text
inlinesToOpenXML opts alt
Right (img, mt) -> do
ident <- ("rId"++) `fmap` getUniqueId
(xpt,ypt) <- case imageSize img of
Right size -> return $ sizeInPoints size
Left msg -> do
liftIO $ warn $
"Could not determine image size in `" ++
src ++ "': " ++ msg
return (120,120)
-- 12700 emu = 1 pt
let (xemu,yemu) = fitToPage (xpt * 12700, ypt * 12700) (pageWidth * 12700)
let cNvPicPr = mknode "pic:cNvPicPr" [] $
mknode "a:picLocks" [("noChangeArrowheads","1"),("noChangeAspect","1")] ()
let nvPicPr = mknode "pic:nvPicPr" []
[ mknode "pic:cNvPr"
[("descr",src),("id","0"),("name","Picture")] ()
, cNvPicPr ]
let blipFill = mknode "pic:blipFill" []
[ mknode "a:blip" [("r:embed",ident)] ()
, mknode "a:stretch" [] $ mknode "a:fillRect" [] () ]
let xfrm = mknode "a:xfrm" []
[ mknode "a:off" [("x","0"),("y","0")] ()
, mknode "a:ext" [("cx",show xemu),("cy",show yemu)] () ]
let prstGeom = mknode "a:prstGeom" [("prst","rect")] $
mknode "a:avLst" [] ()
let ln = mknode "a:ln" [("w","9525")]
[ mknode "a:noFill" [] ()
, mknode "a:headEnd" [] ()
, mknode "a:tailEnd" [] () ]
let spPr = mknode "pic:spPr" [("bwMode","auto")]
[xfrm, prstGeom, mknode "a:noFill" [] (), ln]
let graphic = mknode "a:graphic" [] $
mknode "a:graphicData" [("uri","http://schemas.openxmlformats.org/drawingml/2006/picture")]
[ mknode "pic:pic" []
[ nvPicPr
, blipFill
, spPr ] ]
let imgElt = mknode "w:r" [] $
mknode "w:drawing" [] $
mknode "wp:inline" []
[ mknode "wp:extent" [("cx",show xemu),("cy",show yemu)] ()
, mknode "wp:effectExtent" [("b","0"),("l","0"),("r","0"),("t","0")] ()
, mknode "wp:docPr" [("descr",tit),("id","1"),("name","Picture")] ()
, graphic ]
let imgext = case mt >>= extensionFromMimeType of
Just x -> '.':x
Nothing -> case imageType img of
Just Png -> ".png"
Just Jpeg -> ".jpeg"
Just Gif -> ".gif"
Just Pdf -> ".pdf"
Just Eps -> ".eps"
Nothing -> ""
if null imgext
then -- without an extension there is no rule for content type
inlinesToOpenXML opts alt -- return alt to avoid corrupted docx
else do
let imgpath = "media/" ++ ident ++ imgext
let mbMimeType = mt <|> getMimeType imgpath
-- insert mime type to use in constructing [Content_Types].xml
modify $ \st -> st{ stImages =
M.insert src (ident, imgpath, mbMimeType, imgElt, img)
$ stImages st }
return [imgElt]
br :: Element
br = mknode "w:r" [] [mknode "w:br" [("w:type","textWrapping")] () ]
-- Word will insert these footnotes into the settings.xml file
-- (whether or not they're visible in the document). If they're in the
-- file, but not in the footnotes.xml file, it will produce
-- problems. So we want to make sure we insert them into our document.
defaultFootnotes :: [Element]
defaultFootnotes = [ mknode "w:footnote"
[("w:type", "separator"), ("w:id", "-1")] $
[ mknode "w:p" [] $
[mknode "w:r" [] $
[ mknode "w:separator" [] ()]]]
, mknode "w:footnote"
[("w:type", "continuationSeparator"), ("w:id", "0")] $
[ mknode "w:p" [] $
[ mknode "w:r" [] $
[ mknode "w:continuationSeparator" [] ()]]]]
parseXml :: Archive -> Archive -> String -> IO Element
parseXml refArchive distArchive relpath =
case findEntryByPath relpath refArchive `mplus`
findEntryByPath relpath distArchive of
Nothing -> fail $ relpath ++ " missing in reference docx"
Just e -> case parseXMLDoc . UTF8.toStringLazy . fromEntry $ e of
Nothing -> fail $ relpath ++ " corrupt in reference docx"
Just d -> return d
-- | Scales the image to fit the page
-- sizes are passed in emu
fitToPage :: (Integer, Integer) -> Integer -> (Integer, Integer)
fitToPage (x, y) pageWidth
-- Fixes width to the page width and scales the height
| x > pageWidth =
(pageWidth, round $
((fromIntegral pageWidth) / ((fromIntegral :: Integer -> Double) x)) * (fromIntegral y))
| otherwise = (x, y)
| nvasilakis/pandoc | src/Text/Pandoc/Writers/Docx.hs | gpl-2.0 | 55,962 | 0 | 28 | 16,806 | 15,619 | 8,044 | 7,575 | 1,020 | 22 |
<?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="sq-AL">
<title>Report Generation</title>
<maps>
<homeID>reports</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/reports/src/main/javahelp/org/zaproxy/addon/reports/resources/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 966 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module ListIn1 where
f :: [Int] -> Int
f [1, 2]
= case [1, 2] of
[x, y] -> y
_ -> 1
f_1 [1, 2]
= case [1, 2] of
[x, y] -> return 0
_ -> return 1
| kmate/HaRe | old/testing/simplifyExpr/ListIn1AST.hs | bsd-3-clause | 210 | 0 | 8 | 105 | 106 | 60 | 46 | 10 | 2 |
module A5 where
data Data1 b a = C1 a Int Char | C2 Int | C3 b Float
f :: (Data1 b a) -> Int
f (C1 a b c) = b
f (C2 a) = a
f (C3 a) = 42
g (C1 (C1 x y z) b c) = y
h :: Data1 b a
h = C2 42
| kmate/HaRe | old/testing/addField/A5AST.hs | bsd-3-clause | 199 | 0 | 9 | 73 | 140 | 74 | 66 | 9 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- #3406
-- A pattern signature that discards the bound variables
module T3406 where
type ItemColID a b = Int -- Discards a,b
get :: ItemColID a b -> a -> ItemColID a b
get (x :: ItemColID a b) = x :: ItemColID a b
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/T3406.hs | bsd-3-clause | 257 | 0 | 8 | 55 | 67 | 38 | 29 | 5 | 1 |
{-|
Module : Idris.Unlit
Description : Turn literate programs into normal programs.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Unlit(unlit) where
import Idris.Core.TT
import Data.Char
unlit :: FilePath -> String -> TC String
unlit f s = do let s' = map ulLine (lines s)
check f 1 s'
return $ unlines (map snd s')
data LineType = Prog | Blank | Comm
ulLine :: String -> (LineType, String)
ulLine ('>':' ':xs) = (Prog, ' ':' ':xs) -- Replace with spaces, otherwise text position numbers will be bogus.
ulLine ('>':xs) = (Prog, ' ' :xs) -- The parser can deal with this, because /every/ (code) line is prefixed
-- with a '>'.
ulLine xs | all isSpace xs = (Blank, "")
-- make sure it's not a doc comment
| otherwise = (Comm, '-':'-':' ':'>':xs)
check :: FilePath -> Int -> [(LineType, String)] -> TC ()
check f l (a:b:cs) = do chkAdj f l (fst a) (fst b)
check f (l+1) (b:cs)
check f l [x] = return ()
check f l [ ] = return ()
-- Issue #1593 on the issue checker.
--
-- https://github.com/idris-lang/Idris-dev/issues/1593
--
chkAdj :: FilePath -> Int -> LineType -> LineType -> TC ()
chkAdj f l Prog Comm = tfail $ At (FC f (l, 0) (l, 0)) ProgramLineComment --TODO: Span correctly
chkAdj f l Comm Prog = tfail $ At (FC f (l, 0) (l, 0)) ProgramLineComment --TODO: Span correctly
chkAdj f l _ _ = return ()
| kojiromike/Idris-dev | src/Idris/Unlit.hs | bsd-3-clause | 1,489 | 0 | 12 | 416 | 525 | 277 | 248 | 22 | 1 |
@interface TestClass
+ (int) test;
@end
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/objc.dg/pch/interface-1.hs | gpl-2.0 | 41 | 2 | 6 | 7 | 26 | 11 | 15 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
-- | Extraction of parallelism from a SOACs program. This generates
-- parallel constructs aimed at CPU execution, which in particular may
-- involve ad-hoc irregular nested parallelism.
module Futhark.Pass.ExtractMulticore (extractMulticore) where
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Bitraversable
import Futhark.Analysis.Rephrase
import Futhark.IR
import Futhark.IR.MC
import qualified Futhark.IR.MC as MC
import Futhark.IR.SOACS hiding
( Body,
Exp,
LParam,
Lambda,
Pat,
Stm,
)
import qualified Futhark.IR.SOACS as SOACS
import qualified Futhark.IR.SOACS.Simplify as SOACS
import Futhark.Pass
import Futhark.Pass.ExtractKernels.DistributeNests
import Futhark.Pass.ExtractKernels.ToGPU (injectSOACS)
import Futhark.Tools
import qualified Futhark.Transform.FirstOrderTransform as FOT
import Futhark.Transform.Rename (Rename, renameSomething)
import Futhark.Util (takeLast)
import Futhark.Util.Log
newtype ExtractM a = ExtractM (ReaderT (Scope MC) (State VNameSource) a)
deriving
( Functor,
Applicative,
Monad,
HasScope MC,
LocalScope MC,
MonadFreshNames
)
-- XXX: throwing away the log here...
instance MonadLogger ExtractM where
addLog _ = pure ()
indexArray :: VName -> LParam SOACS -> VName -> Stm MC
indexArray i (Param _ p t) arr =
Let (Pat [PatElem p t]) (defAux ()) . BasicOp $
case t of
Acc {} -> SubExp $ Var arr
_ -> Index arr $ Slice $ DimFix (Var i) : map sliceDim (arrayDims t)
mapLambdaToBody ::
(Body SOACS -> ExtractM (Body MC)) ->
VName ->
Lambda SOACS ->
[VName] ->
ExtractM (Body MC)
mapLambdaToBody onBody i lam arrs = do
let indexings = zipWith (indexArray i) (lambdaParams lam) arrs
Body () stms res <- inScopeOf indexings $ onBody $ lambdaBody lam
return $ Body () (stmsFromList indexings <> stms) res
mapLambdaToKernelBody ::
(Body SOACS -> ExtractM (Body MC)) ->
VName ->
Lambda SOACS ->
[VName] ->
ExtractM (KernelBody MC)
mapLambdaToKernelBody onBody i lam arrs = do
Body () stms res <- mapLambdaToBody onBody i lam arrs
let ret (SubExpRes cs se) = Returns ResultMaySimplify cs se
return $ KernelBody () stms $ map ret res
reduceToSegBinOp :: Reduce SOACS -> ExtractM (Stms MC, SegBinOp MC)
reduceToSegBinOp (Reduce comm lam nes) = do
((lam', nes', shape), stms) <- runBuilder $ determineReduceOp lam nes
lam'' <- transformLambda lam'
return (stms, SegBinOp comm lam'' nes' shape)
scanToSegBinOp :: Scan SOACS -> ExtractM (Stms MC, SegBinOp MC)
scanToSegBinOp (Scan lam nes) = do
((lam', nes', shape), stms) <- runBuilder $ determineReduceOp lam nes
lam'' <- transformLambda lam'
return (stms, SegBinOp Noncommutative lam'' nes' shape)
histToSegBinOp :: SOACS.HistOp SOACS -> ExtractM (Stms MC, MC.HistOp MC)
histToSegBinOp (SOACS.HistOp num_bins rf dests nes op) = do
((op', nes', shape), stms) <- runBuilder $ determineReduceOp op nes
op'' <- transformLambda op'
return (stms, MC.HistOp num_bins rf dests nes' shape op'')
mkSegSpace :: MonadFreshNames m => SubExp -> m (VName, SegSpace)
mkSegSpace w = do
flat <- newVName "flat_tid"
gtid <- newVName "gtid"
let space = SegSpace flat [(gtid, w)]
return (gtid, space)
transformLoopForm :: LoopForm SOACS -> LoopForm MC
transformLoopForm (WhileLoop cond) = WhileLoop cond
transformLoopForm (ForLoop i it bound params) = ForLoop i it bound params
transformStm :: Stm SOACS -> ExtractM (Stms MC)
transformStm (Let pat aux (BasicOp op)) =
pure $ oneStm $ Let pat aux $ BasicOp op
transformStm (Let pat aux (Apply f args ret info)) =
pure $ oneStm $ Let pat aux $ Apply f args ret info
transformStm (Let pat aux (DoLoop merge form body)) = do
let form' = transformLoopForm form
body' <-
localScope (scopeOfFParams (map fst merge) <> scopeOf form') $
transformBody body
return $ oneStm $ Let pat aux $ DoLoop merge form' body'
transformStm (Let pat aux (If cond tbranch fbranch ret)) =
oneStm . Let pat aux
<$> (If cond <$> transformBody tbranch <*> transformBody fbranch <*> pure ret)
transformStm (Let pat aux (WithAcc inputs lam)) =
oneStm . Let pat aux
<$> (WithAcc <$> mapM transformInput inputs <*> transformLambda lam)
where
transformInput (shape, arrs, op) =
(shape,arrs,) <$> traverse (bitraverse transformLambda pure) op
transformStm (Let pat aux (Op op)) =
fmap (certify (stmAuxCerts aux)) <$> transformSOAC pat (stmAuxAttrs aux) op
transformLambda :: Lambda SOACS -> ExtractM (Lambda MC)
transformLambda (Lambda params body ret) =
Lambda params
<$> localScope (scopeOfLParams params) (transformBody body)
<*> pure ret
transformStms :: Stms SOACS -> ExtractM (Stms MC)
transformStms stms =
case stmsHead stms of
Nothing -> return mempty
Just (stm, stms') -> do
stm_stms <- transformStm stm
inScopeOf stm_stms $ (stm_stms <>) <$> transformStms stms'
transformBody :: Body SOACS -> ExtractM (Body MC)
transformBody (Body () stms res) =
Body () <$> transformStms stms <*> pure res
sequentialiseBody :: Body SOACS -> ExtractM (Body MC)
sequentialiseBody = pure . runIdentity . rephraseBody toMC
where
toMC = injectSOACS OtherOp
transformFunDef :: FunDef SOACS -> ExtractM (FunDef MC)
transformFunDef (FunDef entry attrs name rettype params body) = do
body' <- localScope (scopeOfFParams params) $ transformBody body
return $ FunDef entry attrs name rettype params body'
-- Sets the chunk size to one.
unstreamLambda :: Attrs -> [SubExp] -> Lambda SOACS -> ExtractM (Lambda SOACS)
unstreamLambda attrs nes lam = do
let (chunk_param, acc_params, slice_params) =
partitionChunkedFoldParameters (length nes) (lambdaParams lam)
inp_params <- forM slice_params $ \(Param _ p t) ->
newParam (baseString p) (rowType t)
body <- runBodyBuilder $
localScope (scopeOfLParams inp_params) $ do
letBindNames [paramName chunk_param] $
BasicOp $ SubExp $ intConst Int64 1
forM_ (zip acc_params nes) $ \(p, ne) ->
letBindNames [paramName p] $ BasicOp $ SubExp ne
forM_ (zip slice_params inp_params) $ \(slice, v) ->
letBindNames [paramName slice] $
BasicOp $ ArrayLit [Var $ paramName v] (paramType v)
(red_res, map_res) <- splitAt (length nes) <$> bodyBind (lambdaBody lam)
map_res' <- forM map_res $ \(SubExpRes cs se) -> do
v <- letExp "map_res" $ BasicOp $ SubExp se
v_t <- lookupType v
certifying cs . letSubExp "chunk" . BasicOp $
Index v $ fullSlice v_t [DimFix $ intConst Int64 0]
pure $ mkBody mempty $ red_res <> subExpsRes map_res'
let (red_ts, map_ts) = splitAt (length nes) $ lambdaReturnType lam
map_lam =
Lambda
{ lambdaReturnType = red_ts ++ map rowType map_ts,
lambdaParams = inp_params,
lambdaBody = body
}
soacs_scope <- castScope <$> askScope
map_lam' <- runReaderT (SOACS.simplifyLambda map_lam) soacs_scope
if "sequential_inner" `inAttrs` attrs
then FOT.transformLambda map_lam'
else return map_lam'
-- Code generation for each parallel basic block is parameterised over
-- how we handle parallelism in the body (whether it's sequentialised
-- by keeping it as SOACs, or turned into SegOps).
data NeedsRename = DoRename | DoNotRename
renameIfNeeded :: Rename a => NeedsRename -> a -> ExtractM a
renameIfNeeded DoRename = renameSomething
renameIfNeeded DoNotRename = pure
transformMap ::
NeedsRename ->
(Body SOACS -> ExtractM (Body MC)) ->
SubExp ->
Lambda SOACS ->
[VName] ->
ExtractM (SegOp () MC)
transformMap rename onBody w map_lam arrs = do
(gtid, space) <- mkSegSpace w
kbody <- mapLambdaToKernelBody onBody gtid map_lam arrs
renameIfNeeded rename $
SegMap () space (lambdaReturnType map_lam) kbody
transformRedomap ::
NeedsRename ->
(Body SOACS -> ExtractM (Body MC)) ->
SubExp ->
[Reduce SOACS] ->
Lambda SOACS ->
[VName] ->
ExtractM ([Stms MC], SegOp () MC)
transformRedomap rename onBody w reds map_lam arrs = do
(gtid, space) <- mkSegSpace w
kbody <- mapLambdaToKernelBody onBody gtid map_lam arrs
(reds_stms, reds') <- unzip <$> mapM reduceToSegBinOp reds
op' <-
renameIfNeeded rename $
SegRed () space reds' (lambdaReturnType map_lam) kbody
return (reds_stms, op')
transformHist ::
NeedsRename ->
(Body SOACS -> ExtractM (Body MC)) ->
SubExp ->
[SOACS.HistOp SOACS] ->
Lambda SOACS ->
[VName] ->
ExtractM ([Stms MC], SegOp () MC)
transformHist rename onBody w hists map_lam arrs = do
(gtid, space) <- mkSegSpace w
kbody <- mapLambdaToKernelBody onBody gtid map_lam arrs
(hists_stms, hists') <- unzip <$> mapM histToSegBinOp hists
op' <-
renameIfNeeded rename $
SegHist () space hists' (lambdaReturnType map_lam) kbody
return (hists_stms, op')
transformParStream ::
NeedsRename ->
(Body SOACS -> ExtractM (Body MC)) ->
SubExp ->
Commutativity ->
Lambda SOACS ->
[SubExp] ->
Lambda SOACS ->
[VName] ->
ExtractM (Stms MC, SegOp () MC)
transformParStream rename onBody w comm red_lam red_nes map_lam arrs = do
(gtid, space) <- mkSegSpace w
kbody <- mapLambdaToKernelBody onBody gtid map_lam arrs
(red_stms, red) <- reduceToSegBinOp $ Reduce comm red_lam red_nes
op <-
renameIfNeeded rename $
SegRed () space [red] (lambdaReturnType map_lam) kbody
return (red_stms, op)
transformSOAC :: Pat Type -> Attrs -> SOAC SOACS -> ExtractM (Stms MC)
transformSOAC pat _ (Screma w arrs form)
| Just lam <- isMapSOAC form = do
seq_op <- transformMap DoNotRename sequentialiseBody w lam arrs
if lambdaContainsParallelism lam
then do
par_op <- transformMap DoRename transformBody w lam arrs
return $ oneStm (Let pat (defAux ()) $ Op $ ParOp (Just par_op) seq_op)
else return $ oneStm (Let pat (defAux ()) $ Op $ ParOp Nothing seq_op)
| Just (reds, map_lam) <- isRedomapSOAC form = do
(seq_reds_stms, seq_op) <-
transformRedomap DoNotRename sequentialiseBody w reds map_lam arrs
if lambdaContainsParallelism map_lam
then do
(par_reds_stms, par_op) <-
transformRedomap DoRename transformBody w reds map_lam arrs
return $
mconcat (seq_reds_stms <> par_reds_stms)
<> oneStm (Let pat (defAux ()) $ Op $ ParOp (Just par_op) seq_op)
else
return $
mconcat seq_reds_stms
<> oneStm (Let pat (defAux ()) $ Op $ ParOp Nothing seq_op)
| Just (scans, map_lam) <- isScanomapSOAC form = do
(gtid, space) <- mkSegSpace w
kbody <- mapLambdaToKernelBody transformBody gtid map_lam arrs
(scans_stms, scans') <- unzip <$> mapM scanToSegBinOp scans
return $
mconcat scans_stms
<> oneStm
( Let pat (defAux ()) $
Op $
ParOp Nothing $
SegScan () space scans' (lambdaReturnType map_lam) kbody
)
| otherwise = do
-- This screma is too complicated for us to immediately do
-- anything, so split it up and try again.
scope <- castScope <$> askScope
transformStms =<< runBuilderT_ (dissectScrema pat w form arrs) scope
transformSOAC pat _ (Scatter w ivs lam dests) = do
(gtid, space) <- mkSegSpace w
Body () kstms res <- mapLambdaToBody transformBody gtid lam ivs
let rets = takeLast (length dests) $ lambdaReturnType lam
kres = do
(a_w, a, is_vs) <- groupScatterResults dests res
let cs =
foldMap (foldMap resCerts . fst) is_vs
<> foldMap (resCerts . snd) is_vs
is_vs' = [(Slice $ map (DimFix . resSubExp) is, resSubExp v) | (is, v) <- is_vs]
return $ WriteReturns cs a_w a is_vs'
kbody = KernelBody () kstms kres
return $
oneStm $
Let pat (defAux ()) $
Op $
ParOp Nothing $
SegMap () space rets kbody
transformSOAC pat _ (Hist w arrs hists map_lam) = do
(seq_hist_stms, seq_op) <-
transformHist DoNotRename sequentialiseBody w hists map_lam arrs
if lambdaContainsParallelism map_lam
then do
(par_hist_stms, par_op) <-
transformHist DoRename transformBody w hists map_lam arrs
return $
mconcat (seq_hist_stms <> par_hist_stms)
<> oneStm (Let pat (defAux ()) $ Op $ ParOp (Just par_op) seq_op)
else
return $
mconcat seq_hist_stms
<> oneStm (Let pat (defAux ()) $ Op $ ParOp Nothing seq_op)
transformSOAC pat attrs (Stream w arrs (Parallel _ comm red_lam) red_nes fold_lam)
| not $ null red_nes = do
map_lam <- unstreamLambda attrs red_nes fold_lam
(seq_red_stms, seq_op) <-
transformParStream
DoNotRename
sequentialiseBody
w
comm
red_lam
red_nes
map_lam
arrs
if lambdaContainsParallelism map_lam
then do
(par_red_stms, par_op) <-
transformParStream DoRename transformBody w comm red_lam red_nes map_lam arrs
return $
seq_red_stms <> par_red_stms
<> oneStm (Let pat (defAux ()) $ Op $ ParOp (Just par_op) seq_op)
else
return $
seq_red_stms
<> oneStm (Let pat (defAux ()) $ Op $ ParOp Nothing seq_op)
transformSOAC pat _ (Stream w arrs _ nes lam) = do
-- Just remove the stream and transform the resulting stms.
soacs_scope <- castScope <$> askScope
stream_stms <-
flip runBuilderT_ soacs_scope $
sequentialStreamWholeArray pat w nes lam arrs
transformStms stream_stms
transformProg :: Prog SOACS -> PassM (Prog MC)
transformProg (Prog consts funs) =
modifyNameSource $ runState (runReaderT m mempty)
where
ExtractM m = do
consts' <- transformStms consts
funs' <- inScopeOf consts' $ mapM transformFunDef funs
return $ Prog consts' funs'
-- | Transform a program using SOACs to a program in the 'MC'
-- representation, using some amount of flattening.
extractMulticore :: Pass SOACS MC
extractMulticore =
Pass
{ passName = "extract multicore parallelism",
passDescription = "Extract multicore parallelism",
passFunction = transformProg
}
| diku-dk/futhark | src/Futhark/Pass/ExtractMulticore.hs | isc | 14,295 | 0 | 20 | 3,277 | 4,882 | 2,394 | 2,488 | 341 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Substitutions where
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Text.HTML.DOM
import Text.XML
import Web.Larceny
import Data (Team (..), teamDatabase)
teamSubs :: Team -> Substitutions ()
teamSubs (Team i n y d) =
subs [ ("id", textFill $ T.pack $ show i)
, ("name", textFill n)
, ("foundedIn", textFill y)
, ("longDesc", textFill d)]
defaultSubs :: Substitutions ()
defaultSubs =
subs [ ("page-title", textFill "The Best Roller Derby Teams")
, ("teams", mapSubs
teamSubs
teamDatabase )
, ("shorten", useAttrs (a"length" %
a"text")
shortenFill)
, ("buggyReverse", buggyReverseFill)
, ("reverse", reverseFill)]
where shortenFill maybeNumber fullText = textFill $
case maybeNumber of
Just numChars -> T.take numChars fullText <> "..."
Nothing -> fullText
buggyReverseFill :: Fill s
buggyReverseFill = Fill reverseFill'
where reverseFill' _attrs (pth,tpl)lib = do
children <- runTemplate tpl pth mempty lib
return (T.reverse children)
reverseFill :: Fill s
reverseFill = Fill reverseFill'
where reverseFill' _attrs (pth,tpl)lib = do
children <- runTemplate tpl pth mempty lib
-- html-conduit assumes a single root element
-- it just abandons orphan text, so wrap in a parent
let wrappedChildren = "<div>" <> children <> "</div>"
let doc = parseLT (LT.fromStrict wrappedChildren)
return (LT.toStrict $ renderText def (reverseDoc doc))
reverseElement :: Element -> Element
reverseElement e =
e { elementNodes = map reverseNode (reverse $ elementNodes e) }
reverseDoc :: Document -> Document
reverseDoc doc =
let e = documentRoot doc in
doc { documentRoot = reverseElement e }
reverseNode :: Node -> Node
reverseNode (NodeElement e) = NodeElement (reverseElement e)
reverseNode (NodeContent c) = NodeContent (T.reverse c)
reverseNode anything = anything
| positiondev/larceny | example/Substitutions.hs | isc | 2,220 | 0 | 15 | 638 | 625 | 331 | 294 | 53 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
module Control.Monad.Gen.Class where
-- Import the non-depricated one
#if MIN_VERSION_mtl(2, 2, 1)
import Control.Monad.Except
#else
import Control.Monad.Trans.Error
#endif
import Control.Monad.Cont
import Control.Monad.List
import Control.Monad.RWS
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Monad.State.Strict as SS
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import Control.Monad.Writer
import qualified Control.Monad.Writer.Strict as SW
-- | The MTL style class for generating fresh values
class Monad m => MonadGen e m | m -> e where
-- | Generate a fresh value @e@, @gen@ should never produce the
-- same value within a monadic computation.
gen :: m e
instance MonadGen e m => MonadGen e (IdentityT m) where
gen = lift gen
instance MonadGen e m => MonadGen e (StateT s m) where
gen = lift gen
instance MonadGen e m => MonadGen e (ReaderT s m) where
gen = lift gen
instance (MonadGen e m, Monoid s) => MonadGen e (WriterT s m) where
gen = lift gen
instance MonadGen e m => MonadGen e (ListT m) where
gen = lift gen
instance MonadGen e m => MonadGen e (MaybeT m) where
gen = lift gen
instance MonadGen e m => MonadGen e (ContT r m) where
gen = lift gen
instance (Monoid w, MonadGen e m) => MonadGen e (RWST r w s m) where
gen = lift gen
instance MonadGen e m => MonadGen e (SS.StateT s m) where
gen = lift gen
instance (Monoid w, MonadGen e m) => MonadGen e (SW.WriterT w m) where
gen = lift gen
#if MIN_VERSION_mtl(2, 2, 1)
instance (MonadGen e m) => MonadGen e (ExceptT e' m) where
gen = lift gen
#else
instance (MonadGen e m, Error e') => MonadGen e (ErrorT e' m) where
gen = lift gen
#endif
| jozefg/monad-gen | src/Control/Monad/Gen/Class.hs | mit | 1,980 | 0 | 8 | 448 | 544 | 296 | 248 | 41 | 0 |
module Main where
main :: IO()
main = putStrLn "hello world"
| rockdragon/julia-programming | code/haskell/HelloWorld.hs | mit | 62 | 0 | 6 | 12 | 22 | 12 | 10 | 3 | 1 |
module FRP.ClassicFRP where
| HaskellZhangSong/classic-frp | src/FRP/ClassicFRP.hs | mit | 31 | 0 | 3 | 6 | 6 | 4 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Tombstone.Routes.Sessions
( routes
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad.IO.Class
import Data.Monoid
import Lucid
import Web.Spock.Safe
-------------------------------------------------------------------------------
import Web.Tombstone.Types
-------------------------------------------------------------------------------
routes :: SpockT AppM ()
routes =
get "new" $ do
cid <- configGHClientId . asConfig <$> getState
renderHTML $ newSessionView cid
renderHTML :: MonadIO m => Html a -> ActionT m a
renderHTML h = do
setHeader "Content-Type" "text/html; charset=utf-8"
lazyBytes $ renderBS h
newSessionView :: GithubClientId -> Html ()
newSessionView (GithubClientId cid) =
doctypehtml_ $
html_ $
body_ $ do
p_ "Well, hello there!"
p_ $ do
"We're going to now talk to the GitHub API. Ready? "
a_ [href_ $ "https://github.com/login/oauth/authorize?scope=user:email&client_id=" <> cid] "Click here"
" to begin!"
| ShadowBan/tombstone | src/Web/Tombstone/Routes/Sessions.hs | mit | 1,204 | 0 | 14 | 264 | 226 | 115 | 111 | 28 | 1 |
data NestedList a = Elem a | List [NestedList a]
--failed this one..
--flatten :: NestedList x -> [x]
--flatten (Elem b) = [b]
--flatten (List []) = []
--flatten (List [c,d]) = (flatten c) ++ (flatten d)
flatten :: NestedList x -> [x]
flatten (Elem x ) = [x]
flatten (List xs) = foldr (++) [] $ map flatten xs
--from the website:
--very simple, it seems....
flatten' (Elem x) = [x]
flatten' (List x) = concatMap flatten' x
-- this one seems simpler:
-- concatMap is probably a map with the concat function as default
-- in layman's terms...concatMap produces a list. it takes a list and runs each (individual) element in it through a function like ( a -> [a] ) that creates lists. at the end all results are concatenated together.
--examples:
-- concatMap (\x -> [x,x*2]) [1,2,3]
-- =>[1,2,2,4,3,6]
-- concatMap (\x -> [x*2]) [1,2,3]
-- [2,4,6]
-- which is equivalent to map (\x -> x*2) [1,2,3]
| queirozfcom/haskell-99-problems | problem7.hs | mit | 910 | 0 | 8 | 177 | 138 | 79 | 59 | 6 | 1 |
{-# LANGUAGE CPP, FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Stability : experimental
-- Portability : tested on GHC only
--
-- Testing composition of 'Builders'.
module Data.ByteString.Builder.Tests (tests) where
import Control.Applicative
import Control.Monad.State
import Control.Monad.Writer
import Foreign (Word, Word8, minusPtr)
import System.IO.Unsafe (unsafePerformIO)
import Data.Char (ord, chr)
import qualified Data.DList as D
import Data.Foldable (asum, foldMap)
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Short as Sh
import Data.ByteString.Builder
import Data.ByteString.Builder.Extra
import Data.ByteString.Builder.Internal (Put, putBuilder, fromPut)
import qualified Data.ByteString.Builder.Internal as BI
import qualified Data.ByteString.Builder.Prim as BP
import Data.ByteString.Builder.Prim.TestUtils
import Control.Exception (evaluate)
import System.IO (openTempFile, hPutStr, hClose, hSetBinaryMode)
import System.IO (hSetEncoding, utf8)
import System.Directory
import Foreign (ForeignPtr, withForeignPtr, castPtr)
#if defined(HAVE_TEST_FRAMEWORK)
import Test.Framework
import Test.Framework.Providers.QuickCheck2
#else
import TestFramework
#endif
import Test.QuickCheck
( Arbitrary(..), oneof, choose, listOf, elements
, UnicodeString(..) )
import Test.QuickCheck.Property
( printTestCase, morallyDubiousIOProperty )
tests :: [Test]
tests =
[ testBuilderRecipe
, testHandlePutBuilder
, testHandlePutBuilderChar8
, testPut
, testRunBuilder
] ++
testsEncodingToBuilder ++
testsBinary ++
testsASCII ++
testsChar8 ++
testsUtf8
------------------------------------------------------------------------------
-- Testing 'Builder' execution
------------------------------------------------------------------------------
testBuilderRecipe :: Test
testBuilderRecipe =
testProperty "toLazyByteStringWith" $ testRecipe <$> arbitrary
where
testRecipe r =
printTestCase msg $ x1 == x2
where
x1 = renderRecipe r
x2 = buildRecipe r
toString = map (chr . fromIntegral)
msg = unlines
[ "recipe: " ++ show r
, "render: " ++ toString x1
, "build : " ++ toString x2
, "diff : " ++ show (dropWhile (uncurry (==)) $ zip x1 x2)
]
testHandlePutBuilder :: Test
testHandlePutBuilder =
testProperty "hPutBuilder" testRecipe
where
testRecipe :: (UnicodeString, UnicodeString, UnicodeString, Recipe) -> Bool
testRecipe args@(UnicodeString before,
UnicodeString between,
UnicodeString after, recipe) =
unsafePerformIO $ do
tempDir <- getTemporaryDirectory
(tempFile, tempH) <- openTempFile tempDir "TestBuilder"
-- switch to UTF-8 encoding
hSetEncoding tempH utf8
-- output recipe with intermediate direct writing to handle
let b = fst $ recipeComponents recipe
hPutStr tempH before
hPutBuilder tempH b
hPutStr tempH between
hPutBuilder tempH b
hPutStr tempH after
hClose tempH
-- read file
lbs <- L.readFile tempFile
_ <- evaluate (L.length $ lbs)
removeFile tempFile
-- compare to pure builder implementation
let lbsRef = toLazyByteString $ mconcat
[stringUtf8 before, b, stringUtf8 between, b, stringUtf8 after]
-- report
let msg = unlines
[ "task: " ++ show args
, "via file: " ++ show lbs
, "direct : " ++ show lbsRef
-- , "diff : " ++ show (dropWhile (uncurry (==)) $ zip x1 x2)
]
success = lbs == lbsRef
unless success (error msg)
return success
testHandlePutBuilderChar8 :: Test
testHandlePutBuilderChar8 =
testProperty "char8 hPutBuilder" testRecipe
where
testRecipe :: (String, String, String, Recipe) -> Bool
testRecipe args@(before, between, after, recipe) = unsafePerformIO $ do
tempDir <- getTemporaryDirectory
(tempFile, tempH) <- openTempFile tempDir "TestBuilder"
-- switch to binary / latin1 encoding
hSetBinaryMode tempH True
-- output recipe with intermediate direct writing to handle
let b = fst $ recipeComponents recipe
hPutStr tempH before
hPutBuilder tempH b
hPutStr tempH between
hPutBuilder tempH b
hPutStr tempH after
hClose tempH
-- read file
lbs <- L.readFile tempFile
_ <- evaluate (L.length $ lbs)
removeFile tempFile
-- compare to pure builder implementation
let lbsRef = toLazyByteString $ mconcat
[string8 before, b, string8 between, b, string8 after]
-- report
let msg = unlines
[ "task: " ++ show args
, "via file: " ++ show lbs
, "direct : " ++ show lbsRef
-- , "diff : " ++ show (dropWhile (uncurry (==)) $ zip x1 x2)
]
success = lbs == lbsRef
unless success (error msg)
return success
-- Recipes with which to test the builder functions
---------------------------------------------------
data Mode =
Threshold Int
| Insert
| Copy
| Smart
| Hex
deriving( Eq, Ord, Show )
data Action =
SBS Mode S.ByteString
| LBS Mode L.ByteString
| ShBS Sh.ShortByteString
| W8 Word8
| W8S [Word8]
| String String
| FDec Float
| DDec Double
| Flush
| EnsureFree Word
| ModState Int
deriving( Eq, Ord, Show )
data Strategy = Safe | Untrimmed
deriving( Eq, Ord, Show )
data Recipe = Recipe Strategy Int Int L.ByteString [Action]
deriving( Eq, Ord, Show )
renderRecipe :: Recipe -> [Word8]
renderRecipe (Recipe _ firstSize _ cont as) =
D.toList $ execWriter (evalStateT (mapM_ renderAction as) firstSize)
`mappend` renderLBS cont
where
renderAction (SBS Hex bs) = tell $ foldMap hexWord8 $ S.unpack bs
renderAction (SBS _ bs) = tell $ D.fromList $ S.unpack bs
renderAction (LBS Hex lbs) = tell $ foldMap hexWord8 $ L.unpack lbs
renderAction (LBS _ lbs) = tell $ renderLBS lbs
renderAction (ShBS sbs) = tell $ D.fromList $ Sh.unpack sbs
renderAction (W8 w) = tell $ return w
renderAction (W8S ws) = tell $ D.fromList ws
renderAction (String cs) = tell $ foldMap (D.fromList . charUtf8_list) cs
renderAction Flush = tell $ mempty
renderAction (EnsureFree _) = tell $ mempty
renderAction (FDec f) = tell $ D.fromList $ encodeASCII $ show f
renderAction (DDec d) = tell $ D.fromList $ encodeASCII $ show d
renderAction (ModState i) = do
s <- get
tell (D.fromList $ encodeASCII $ show s)
put (s - i)
renderLBS = D.fromList . L.unpack
hexWord8 = D.fromList . wordHexFixed_list
buildAction :: Action -> StateT Int Put ()
buildAction (SBS Hex bs) = lift $ putBuilder $ byteStringHex bs
buildAction (SBS Smart bs) = lift $ putBuilder $ byteString bs
buildAction (SBS Copy bs) = lift $ putBuilder $ byteStringCopy bs
buildAction (SBS Insert bs) = lift $ putBuilder $ byteStringInsert bs
buildAction (SBS (Threshold i) bs) = lift $ putBuilder $ byteStringThreshold i bs
buildAction (LBS Hex lbs) = lift $ putBuilder $ lazyByteStringHex lbs
buildAction (LBS Smart lbs) = lift $ putBuilder $ lazyByteString lbs
buildAction (LBS Copy lbs) = lift $ putBuilder $ lazyByteStringCopy lbs
buildAction (LBS Insert lbs) = lift $ putBuilder $ lazyByteStringInsert lbs
buildAction (LBS (Threshold i) lbs) = lift $ putBuilder $ lazyByteStringThreshold i lbs
buildAction (ShBS sbs) = lift $ putBuilder $ shortByteString sbs
buildAction (W8 w) = lift $ putBuilder $ word8 w
buildAction (W8S ws) = lift $ putBuilder $ BP.primMapListFixed BP.word8 ws
buildAction (String cs) = lift $ putBuilder $ stringUtf8 cs
buildAction (FDec f) = lift $ putBuilder $ floatDec f
buildAction (DDec d) = lift $ putBuilder $ doubleDec d
buildAction Flush = lift $ putBuilder $ flush
buildAction (EnsureFree minFree) = lift $ putBuilder $ ensureFree $ fromIntegral minFree
buildAction (ModState i) = do
s <- get
lift $ putBuilder $ intDec s
put (s - i)
buildRecipe :: Recipe -> [Word8]
buildRecipe recipe =
L.unpack $ toLBS b
where
(b, toLBS) = recipeComponents recipe
recipeComponents :: Recipe -> (Builder, Builder -> L.ByteString)
recipeComponents (Recipe how firstSize otherSize cont as) =
(b, toLBS)
where
toLBS = toLazyByteStringWith (strategy how firstSize otherSize) cont
where
strategy Safe = safeStrategy
strategy Untrimmed = untrimmedStrategy
b = fromPut $ evalStateT (mapM_ buildAction as) firstSize
-- 'Arbitary' instances
-----------------------
instance Arbitrary L.ByteString where
arbitrary = L.fromChunks <$> listOf arbitrary
shrink lbs
| L.null lbs = []
| otherwise = pure $ L.take (L.length lbs `div` 2) lbs
instance Arbitrary S.ByteString where
arbitrary =
trim S.drop =<< trim S.take =<< S.pack <$> listOf arbitrary
where
trim f bs = oneof [pure bs, f <$> choose (0, S.length bs) <*> pure bs]
shrink bs
| S.null bs = []
| otherwise = pure $ S.take (S.length bs `div` 2) bs
instance Arbitrary Mode where
arbitrary = oneof
[Threshold <$> arbitrary, pure Smart, pure Insert, pure Copy, pure Hex]
shrink (Threshold i) = Threshold <$> shrink i
shrink _ = []
instance Arbitrary Action where
arbitrary = oneof
[ SBS <$> arbitrary <*> arbitrary
, LBS <$> arbitrary <*> arbitrary
, ShBS . Sh.toShort <$> arbitrary
, W8 <$> arbitrary
, W8S <$> listOf arbitrary
-- ensure that larger character codes are also tested
, String . getUnicodeString <$> arbitrary
, pure Flush
-- never request more than 64kb free space
, (EnsureFree . (`mod` 0xffff)) <$> arbitrary
, FDec <$> arbitrary
, DDec <$> arbitrary
, ModState <$> arbitrary
]
where
shrink (SBS m bs) =
(SBS <$> shrink m <*> pure bs) <|>
(SBS <$> pure m <*> shrink bs)
shrink (LBS m lbs) =
(LBS <$> shrink m <*> pure lbs) <|>
(LBS <$> pure m <*> shrink lbs)
shrink (ShBS sbs) =
ShBS . Sh.toShort <$> shrink (Sh.fromShort sbs)
shrink (W8 w) = W8 <$> shrink w
shrink (W8S ws) = W8S <$> shrink ws
shrink (String cs) = String <$> shrink cs
shrink Flush = []
shrink (EnsureFree i) = EnsureFree <$> shrink i
shrink (FDec f) = FDec <$> shrink f
shrink (DDec d) = DDec <$> shrink d
shrink (ModState i) = ModState <$> shrink i
instance Arbitrary Strategy where
arbitrary = elements [Safe, Untrimmed]
shrink _ = []
instance Arbitrary Recipe where
arbitrary =
Recipe <$> arbitrary
<*> ((`mod` 33333) <$> arbitrary) -- bound max chunk-sizes
<*> ((`mod` 33337) <$> arbitrary)
<*> arbitrary
<*> listOf arbitrary
-- shrinking the actions first is desirable
shrink (Recipe a b c d e) = asum
[ (\x -> Recipe a b c d x) <$> shrink e
, (\x -> Recipe a b c x e) <$> shrink d
, (\x -> Recipe a b x d e) <$> shrink c
, (\x -> Recipe a x c d e) <$> shrink b
, (\x -> Recipe x b c d e) <$> shrink a
]
------------------------------------------------------------------------------
-- Creating Builders from basic encodings
------------------------------------------------------------------------------
testsEncodingToBuilder :: [Test]
testsEncodingToBuilder =
[ test_encodeUnfoldrF
, test_encodeUnfoldrB
]
-- Unfoldr fused with encoding
------------------------------
test_encodeUnfoldrF :: Test
test_encodeUnfoldrF =
compareImpls "encodeUnfoldrF word8" id encode
where
toLBS = toLazyByteStringWith (safeStrategy 23 101) L.empty
encode =
L.unpack . toLBS . BP.primUnfoldrFixed BP.word8 go
where
go [] = Nothing
go (w:ws) = Just (w, ws)
test_encodeUnfoldrB :: Test
test_encodeUnfoldrB =
compareImpls "encodeUnfoldrB charUtf8" (concatMap charUtf8_list) encode
where
toLBS = toLazyByteStringWith (safeStrategy 23 101) L.empty
encode =
L.unpack . toLBS . BP.primUnfoldrBounded BP.charUtf8 go
where
go [] = Nothing
go (c:cs) = Just (c, cs)
------------------------------------------------------------------------------
-- Testing the Put monad
------------------------------------------------------------------------------
testPut :: Test
testPut = testGroup "Put monad"
[ testLaw "identity" (\v -> (pure id <*> putInt v) `eqPut` (putInt v))
, testLaw "composition" $ \(u, v, w) ->
(pure (.) <*> minusInt u <*> minusInt v <*> putInt w) `eqPut`
(minusInt u <*> (minusInt v <*> putInt w))
, testLaw "homomorphism" $ \(f, x) ->
(pure (f -) <*> pure x) `eqPut` (pure (f - x))
, testLaw "interchange" $ \(u, y) ->
(minusInt u <*> pure y) `eqPut` (pure ($ y) <*> minusInt u)
, testLaw "ignore left value" $ \(u, v) ->
(putInt u *> putInt v) `eqPut` (pure (const id) <*> putInt u <*> putInt v)
, testLaw "ignore right value" $ \(u, v) ->
(putInt u <* putInt v) `eqPut` (pure const <*> putInt u <*> putInt v)
, testLaw "functor" $ \(f, x) ->
(fmap (f -) (putInt x)) `eqPut` (pure (f -) <*> putInt x)
]
where
putInt i = putBuilder (integerDec i) >> return i
minusInt i = (-) <$> putInt i
run p = toLazyByteString $ fromPut (do i <- p; _ <- putInt i; return ())
eqPut p1 p2 = (run p1, run p2)
testLaw name f = compareImpls name (fst . f) (snd . f)
------------------------------------------------------------------------------
-- Testing the Driver <-> Builder protocol
------------------------------------------------------------------------------
-- | Ensure that there are at least 'n' free bytes for the following 'Builder'.
{-# INLINE ensureFree #-}
ensureFree :: Int -> Builder
ensureFree minFree =
BI.builder step
where
step k br@(BI.BufferRange op ope)
| ope `minusPtr` op < minFree = return $ BI.bufferFull minFree op next
| otherwise = k br
where
next br'@(BI.BufferRange op' ope')
| freeSpace < minFree =
error $ "ensureFree: requested " ++ show minFree ++ " bytes, " ++
"but got only " ++ show freeSpace ++ " bytes"
| otherwise = k br'
where
freeSpace = ope' `minusPtr` op'
------------------------------------------------------------------------------
-- Testing the Builder runner
------------------------------------------------------------------------------
testRunBuilder :: Test
testRunBuilder =
testProperty "runBuilder" prop
where
prop actions =
morallyDubiousIOProperty $ do
let (builder, _) = recipeComponents recipe
expected = renderRecipe recipe
actual <- bufferWriterOutput (runBuilder builder)
return (S.unpack actual == expected)
where
recipe = Recipe Safe 0 0 mempty actions
bufferWriterOutput :: BufferWriter -> IO S.ByteString
bufferWriterOutput bwrite0 = do
let len0 = 8
buf <- S.mallocByteString len0
bss <- go [] buf len0 bwrite0
return (S.concat (reverse bss))
where
go :: [S.ByteString] -> ForeignPtr Word8 -> Int -> BufferWriter -> IO [S.ByteString]
go bss !buf !len bwrite = do
(wc, next) <- withForeignPtr buf $ \ptr -> bwrite ptr len
bs <- getBuffer buf wc
case next of
Done -> return (bs:bss)
More m bwrite' | m <= len -> go (bs:bss) buf len bwrite'
| otherwise -> do let len' = m
buf' <- S.mallocByteString len'
go (bs:bss) buf' len' bwrite'
Chunk c bwrite' -> go (c:bs:bss) buf len bwrite'
getBuffer :: ForeignPtr Word8 -> Int -> IO S.ByteString
getBuffer buf len = withForeignPtr buf $ \ptr ->
S.packCStringLen (castPtr ptr, len)
------------------------------------------------------------------------------
-- Testing the pre-defined builders
------------------------------------------------------------------------------
testBuilderConstr :: (Arbitrary a, Show a)
=> TestName -> (a -> [Word8]) -> (a -> Builder) -> Test
testBuilderConstr name ref mkBuilder =
testProperty name check
where
check x =
(ws ++ ws) ==
(L.unpack $ toLazyByteString $ mkBuilder x `mappend` mkBuilder x)
where
ws = ref x
testsBinary :: [Test]
testsBinary =
[ testBuilderConstr "word8" bigEndian_list word8
, testBuilderConstr "int8" bigEndian_list int8
-- big-endian
, testBuilderConstr "int16BE" bigEndian_list int16BE
, testBuilderConstr "int32BE" bigEndian_list int32BE
, testBuilderConstr "int64BE" bigEndian_list int64BE
, testBuilderConstr "word16BE" bigEndian_list word16BE
, testBuilderConstr "word32BE" bigEndian_list word32BE
, testBuilderConstr "word64BE" bigEndian_list word64BE
, testBuilderConstr "floatLE" (float_list littleEndian_list) floatLE
, testBuilderConstr "doubleLE" (double_list littleEndian_list) doubleLE
-- little-endian
, testBuilderConstr "int16LE" littleEndian_list int16LE
, testBuilderConstr "int32LE" littleEndian_list int32LE
, testBuilderConstr "int64LE" littleEndian_list int64LE
, testBuilderConstr "word16LE" littleEndian_list word16LE
, testBuilderConstr "word32LE" littleEndian_list word32LE
, testBuilderConstr "word64LE" littleEndian_list word64LE
, testBuilderConstr "floatBE" (float_list bigEndian_list) floatBE
, testBuilderConstr "doubleBE" (double_list bigEndian_list) doubleBE
-- host dependent
, testBuilderConstr "int16Host" hostEndian_list int16Host
, testBuilderConstr "int32Host" hostEndian_list int32Host
, testBuilderConstr "int64Host" hostEndian_list int64Host
, testBuilderConstr "intHost" hostEndian_list intHost
, testBuilderConstr "word16Host" hostEndian_list word16Host
, testBuilderConstr "word32Host" hostEndian_list word32Host
, testBuilderConstr "word64Host" hostEndian_list word64Host
, testBuilderConstr "wordHost" hostEndian_list wordHost
, testBuilderConstr "floatHost" (float_list hostEndian_list) floatHost
, testBuilderConstr "doubleHost" (double_list hostEndian_list) doubleHost
]
testsASCII :: [Test]
testsASCII =
[ testBuilderConstr "char7" char7_list char7
, testBuilderConstr "string7" (concatMap char7_list) string7
, testBuilderConstr "int8Dec" dec_list int8Dec
, testBuilderConstr "int16Dec" dec_list int16Dec
, testBuilderConstr "int32Dec" dec_list int32Dec
, testBuilderConstr "int64Dec" dec_list int64Dec
, testBuilderConstr "intDec" dec_list intDec
, testBuilderConstr "word8Dec" dec_list word8Dec
, testBuilderConstr "word16Dec" dec_list word16Dec
, testBuilderConstr "word32Dec" dec_list word32Dec
, testBuilderConstr "word64Dec" dec_list word64Dec
, testBuilderConstr "wordDec" dec_list wordDec
, testBuilderConstr "integerDec" (dec_list . enlarge) (integerDec . enlarge)
, testBuilderConstr "floatDec" dec_list floatDec
, testBuilderConstr "doubleDec" dec_list doubleDec
, testBuilderConstr "word8Hex" hex_list word8Hex
, testBuilderConstr "word16Hex" hex_list word16Hex
, testBuilderConstr "word32Hex" hex_list word32Hex
, testBuilderConstr "word64Hex" hex_list word64Hex
, testBuilderConstr "wordHex" hex_list wordHex
, testBuilderConstr "word8HexFixed" wordHexFixed_list word8HexFixed
, testBuilderConstr "word16HexFixed" wordHexFixed_list word16HexFixed
, testBuilderConstr "word32HexFixed" wordHexFixed_list word32HexFixed
, testBuilderConstr "word64HexFixed" wordHexFixed_list word64HexFixed
, testBuilderConstr "int8HexFixed" int8HexFixed_list int8HexFixed
, testBuilderConstr "int16HexFixed" int16HexFixed_list int16HexFixed
, testBuilderConstr "int32HexFixed" int32HexFixed_list int32HexFixed
, testBuilderConstr "int64HexFixed" int64HexFixed_list int64HexFixed
, testBuilderConstr "floatHexFixed" floatHexFixed_list floatHexFixed
, testBuilderConstr "doubleHexFixed" doubleHexFixed_list doubleHexFixed
]
where
enlarge (n, e) = n ^ (abs (e `mod` (50 :: Integer)))
testsChar8 :: [Test]
testsChar8 =
[ testBuilderConstr "charChar8" char8_list char8
, testBuilderConstr "stringChar8" (concatMap char8_list) string8
]
testsUtf8 :: [Test]
testsUtf8 =
[ testBuilderConstr "charUtf8" charUtf8_list charUtf8
, testBuilderConstr "stringUtf8" (concatMap charUtf8_list) stringUtf8
]
| CloudI/CloudI | src/api/haskell/external/bytestring-0.10.10.0/tests/builder/Data/ByteString/Builder/Tests.hs | mit | 21,800 | 0 | 17 | 5,723 | 5,899 | 3,044 | 2,855 | -1 | -1 |
module Main (main) where
import System.Win32.Security.Sid
main :: IO ()
main =
getCurrentProcess >>= getProcessUserSid >>= lookupAccountSid Nothing >>= printMaybeAcct
printMaybeAcct :: Maybe LookedUpAccount -> IO ()
printMaybeAcct maybel = case maybel of
Just l -> do
print (lookedUpAccountName l)
print (lookedUpReferencedDomainName l)
print (lookedUpUse l)
s <- convertSidToStringSid (lookedUpSid l)
print s
Nothing ->
putStrLn "Nothing found"
| anton-dessiatov/Win32-security | tests/get-process-sid/Main.hs | mit | 479 | 0 | 13 | 91 | 151 | 72 | 79 | 15 | 2 |
module BitStringIndRunner where
import CongruentGenerator
import Control.Lens
import Control.Monad.State
import Data.List
import GenAlgEngine
import Individual
defaultGenAlgContext = GenAlgContext {_rndContext = simpleRndContext 100,
_mutationProb = 15,
_crossoverProb = 60,
_maxCount = 10000,
_count = 0}
--- Invariants of running functions
processGAPop :: Individual i => Int -> Int -> Int -> (Int -> i) -> (Int, [i])
processGAPop popSize maxLocale maxFit factoryFunc =
runGAS defaultGenAlgContext (randomGenomeInit popSize maxLocale factoryFunc) (maxFitnesseStop maxFit)
processGAInd :: Individual i => Int -> Int -> Int -> (Int -> i) -> (Int, Maybe i)
processGAInd popSize maxLocale maxFit factoryFunc =
let (cnt, pop) = processGAPop popSize maxLocale maxFit factoryFunc
in (cnt, find (maxFitnesseReached maxFit) pop)
processGAPhen :: Individual i => Int -> Int -> Int -> (Int -> i) -> (i -> a) -> (Int, Maybe a)
processGAPhen popSize maxLocale maxFit factoryFunc phenotypeFunc =
let (cnt, ind) = processGAInd popSize maxLocale maxFit factoryFunc
phen = case ind of
Nothing -> Nothing
Just ind -> Just $ phenotypeFunc ind
in (cnt, phen)
--at the end returns last decoded population
processGALastPhen :: Individual i => Int -> Int -> Int -> (Int -> i) -> (i -> a) -> (Int, [a])
processGALastPhen popSize maxLocale maxFit factoryFunc phenotypeFunc =
let (cnt, inds) = processGAPop popSize maxLocale maxFit factoryFunc
phens = map phenotypeFunc inds
in (cnt, phens)
----
randomGenomeInit :: Individual i => Int -> Int -> (Int -> i) -> State GenAlgContext [i]
randomGenomeInit popSize maxLocale factoryFunc =
do zoom rndContext $
do genomes <- randVectorS popSize maxLocale
let initInds = do dice <- genomes
return $ factoryFunc dice
return initInds
| salamansar/GA-cube | src/BitStringIndRunner.hs | mit | 1,913 | 0 | 16 | 425 | 609 | 318 | 291 | 38 | 2 |
module Engine.Graphics where
import Util.Vector2
import Util.GL
import Control.Applicative
import qualified Graphics.GLUtil as GLU
import qualified Graphics.Rendering.OpenGL as GL
renderVertex :: Vector2 -> IO ()
renderVertex (Vector2 x y) = GL.vertex $ GL.Vertex2 (float2gl x) (float2gl y)
texCoord :: GL.GLfloat -> GL.GLfloat -> IO ()
texCoord u v = GL.texCoord (GL.TexCoord2 u v :: GL.TexCoord2 GL.GLfloat)
renderTriangle :: [Vector2] -> IO ()
renderTriangle vertices =
GL.renderPrimitive GL.Triangles $ mapM_ (GL.vertex . vertex2) vertices
renderRectangle :: [Vector2] -> IO ()
renderRectangle vertices = GL.renderPrimitive GL.Quads $ mapM_ makeQuadPart $ zip vertices texCoords
where texCoords = [(1, 1), (0, 1), (0, 0), (1, 0)]
makeQuadPart (vertex, (a, b)) = do
renderVertex vertex
texCoord a b
vector3 :: Vector2 -> GL.Vector3 GL.GLfloat
vector3 (Vector2 x y) = GL.Vector3 (realToFrac x) (realToFrac y) 0
vertex2 :: Vector2 -> GL.Vertex2 GL.GLfloat
vertex2 (Vector2 x y) = GL.Vertex2 (realToFrac x) (realToFrac y)
makeTexture :: FilePath -> IO GL.TextureObject
makeTexture f = do
t <- either error id <$> GLU.readTexture f
GL.textureFilter GL.Texture2D GL.$= ((GL.Linear', Nothing), GL.Linear')
GLU.texture2DWrap GL.$= (GL.Mirrored, GL.ClampToEdge)
pure t
| kaisellgren/ankka | src/Engine/Graphics.hs | mit | 1,324 | 0 | 10 | 236 | 531 | 275 | 256 | 29 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text.Lazy as T
import TwitterMarkov.IO
import TwitterMarkov.MarkovModel
import TwitterMarkov.TweetMarkov
import Control.Monad.Except
import Control.Monad.State
import System.Environment
import System.Random
main :: IO ()
main = do
args <- getArgs
stdGen <- getStdGen
t <- evalStateT (runExceptT (generateTweet (args !! 0))) stdGen
print (T.unwords <$> t)
generateTweet :: FilePath -> ExceptT ParseError (StateT StdGen IO) [T.Text]
generateTweet fp = do
tweets <- parseDir fp
generateRandom (tweetsModel tweets)
| beala/twitter-markov | src/main/Main.hs | mit | 701 | 0 | 14 | 173 | 183 | 96 | 87 | 20 | 1 |
module Solar.Cast where
| Cordite-Studios/solar-wind | Solar/Cast.hs | mit | 24 | 0 | 3 | 3 | 6 | 4 | 2 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Parser where
import Prelude hiding (takeWhile)
import Datatypes
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
ident :: Parser ByteString
ident = BS.cons <$> satisfy (inClass alphabet) <*> takeWhile (inClass x)
where f _ _ = Nothing
alphabet = "A-Za-z"
numbers = "0-9_"
x = alphabet ++ numbers
junk :: Parser ()
junk = () <$ takeWhile isSpace
parens :: Parser x -> Parser x
parens x = char '(' *> junk *> x <* junk <* char ')'
word :: ByteString -> Parser ByteString
word x = junk *> string x <* junk
variable :: Parser Variable
variable = Variable . BS.unpack <$> (junk *> ident)
block :: Parser Block
block = junk *> char '{' *> junk *>
(Block <$> many statement)
<* junk <* char '}'
mchoice :: (a -> Parser b) -> [a] -> Parser b
mchoice f = choice . map f
typePlaceholder :: Parser ()
typePlaceholder = () <$ (optional
(mchoice f
["void"
,"int"
,"bool"]))
where f s = string s
definition :: Parser Definition
definition = junk *> typePlaceholder <* junk *> do
x <- variable
junk
def x
where def x = deffun x <|> defvar x
defvar :: Variable -> Parser Definition
defvar x =
DefVar x <$> (optional (assigOp *> junk *> expr))
deffun :: Variable -> Parser Definition
deffun x = DefFun x <$> parens (sepBy variable (char ','))
<*> block
statement :: Parser Statement
statement = junk *> (sif <|> swhile <|> sassig <|> sdef <|> sfcall)
<* junk <* char ';'
sif :: Parser Statement
sif =
word "if" *>
(Sif <$> parens expr
<*> block
<*> (maybe (Block []) id <$> optional block))
swhile :: Parser Statement
swhile =
word "while" *>
(Swhile <$> parens expr
<*> block)
sdef :: Parser Statement
sdef = Sdef <$> definition
assigOp :: Parser ()
assigOp = () <$
try (choice (map string
[":="
,"="
,"<-"]))
sassig :: Parser Statement
sassig =
Sassig <$> variable
<*> (assigOp *> expr)
sepByIgn :: Parser x -> Parser sep -> Parser [Maybe x]
sepByIgn elm sep = go
where go = do
p <- junk *> optional elm
s <- junk *> optional sep
case s of
Nothing -> return [p]
Just _ -> (p:) <$> go
sfcall :: Parser Statement
sfcall =
Sfcall <$> variable
<*> parens (sepByIgn expr (char ','))
efcall :: Parser Expr
efcall =
Efcall <$> expr
<*> parens (sepBy expr (char ','))
operator :: ByteString -> (Expr -> Expr -> x) -> Parser x
operator op f = do
x <- expr
word op
y <- expr
return (f x y)
numop :: ByteString -> (Int -> Int -> Int) -> Parser Expr
numop op f = operator op (EIntOP (F f))
-- need some less dirty way to deal with a*b+c such that it doesn't get parsed incorrectly
eequ :: Parser Expr
eequ = operator "==" EEqu
eand :: Parser Expr
eand = operator "&&" EAnd
eor :: Parser Expr
eor = operator "||" EOr
eplus :: Parser Expr
eplus = numop "+" (+)
eminus :: Parser Expr
eminus = numop "-" (-)
expr :: Parser Expr
expr = junk *>
(parens expr
<|> varlookup
<|> eequ
<|> eand
<|> eor
<|> efcall)
varlookup :: Parser Expr
varlookup = ELookup <$> variable
program :: Parser Program
program =
(Program <$> many (junk *> definition)) <* junk | EXio4/zyw-pl | src/Parser.hs | mit | 3,714 | 0 | 13 | 1,222 | 1,286 | 652 | 634 | 120 | 2 |
module NormalForm where
-- data Fiction = Fiction deriving Show
-- data NonFiction = NonFiction deriving Show
--
-- data BookType =
-- FictionBook Fiction
-- | NonFictionBook NonFiction
-- deriving Show
type AuthorName = String
-- non normal form
-- data Author = Author (AuthorName, BookType)
-- same as Author type but in normal form
data AuthorNormal =
Fiction AuthorName
| NonFiction AuthorName
deriving (Eq, Show)
-- data FlowerType =
-- Gardenia
-- | Daisy
-- | Rose
-- | Lilac
-- deriving Show
type Gardener = String
-- non normal form
-- data Garden =
-- Garden Gardener FlowerType
-- deriving Show
data Garden =
Gardenia Gardener
| Daisy Gardener
| Rose Gardener
| Lilac Gardener
deriving Show
| andrewMacmurray/haskell-book-solutions | src/ch11/normalForm.hs | mit | 756 | 0 | 6 | 173 | 88 | 61 | 27 | 13 | 0 |
{-# OPTIONS_GHC -fwarn-unused-do-bind #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PartialTypeSignatures #-}
module Test where
import Language.C.Data.InputStream
import Language.C.Data.Ident
import Language.C.Data.Position
import Language.C.Data.Node
import Language.C.Data.Name
import Language.C.Parser
import Language.C.Pretty
import Language.C.Syntax.AST
import Language.C.Syntax.Constants
import Debug.Trace
import Data.Proxy
import Data.Typeable
import Language.HLC.Util.Names
import Language.HLC.Quasi.Parser
import Language.HLC.Quasi.QuasiC
import Language.HLC.Quasi.QuasiTypes
import Language.HLC.HighLevelC.HLC
import Language.HLC.HighLevelC.HLCCalls
import Language.HLC.HighLevelC.HLCTypes
import Language.HLC.HighLevelC.CWriter
import Language.HLC.HighLevelC.BasicTypes
import Language.HLC.HighLevelC.PrimFunctions
import Language.HLC.HighLevelC.VarDecls
import Language.HLC.HighLevelC.Operators
import Language.HLC.HighLevelC.TypeSynonyms
import Language.HLC.HighLevelC.LangConstructs
import Language.HLC.Libraries.Memory
import Language.HLC.IntermediateLang.ILTypes
import Language.HLC.PostProcess.Printer
import Language.HLC.PostProcess.SymbolRewrite
import Language.HLC.PostProcess.ObjectRewrite
import Language.Haskell.TH
import Language.Haskell.TH as TH
$(generateStructDesc [structDefn|StructA {} where
isPassable = True
constructor = consA
destructor = destA|])
consA _ this ret = do
v <- makeVar :: Var HLCInt
v =: intLit 3
ret
destA _ this ret = do
v <- makeVar :: Var HLCInt
v =: intLit 4
ret
$(generateStructDesc [structDefn|StructB {structBElt :: StructA} where
isPassable = True
constructor = consB
destructor = destB|])
consB _ this ret = do
v <- makeVar :: Var HLCChar
v =: fromIntType (intLit 5)
ret
destB _ this ret = do
v <- makeVar :: Var HLCChar
v =: fromIntType (intLit 6)
ret
$(generateStructDesc [structDefn|PrimeField {order :: HLCInt,foo :: HLCPrimArray HLCChar 3} where
isPassable = True
constructor = primeFieldCons
destructor = primeFieldDest|])
primeFieldCons _ this ret = do
this %. order =: (intLit 2)
ret
primeFieldDest _ this ret = ret
initPrimeField field n =
field %. order =: n
class Group g elt | elt -> g where
add' :: g -> elt -> elt -> elt
toInt' :: elt -> Type_Int
add :: (ClassWrap2 Group g elt) =>
FuncTyWrap3 g elt elt elt
add = funcWrap3 add'
toInt :: (ClassWrap2 Group g elt) =>
FuncTyWrap1 elt HLCInt
toInt = funcWrap1 toInt'
$(generateStructDesc [structDefn|PrimeFieldElt {pfieldElt :: HLCInt}|])
$(generateFunction [funcDefn|primeFieldAdd PrimeField -> PrimeFieldElt -> PrimeFieldElt -> PrimeFieldElt|])
primeFieldAdd ret field lhs rhs = do
retVal <- makeVar :: Var PrimeFieldElt
retVal %. pfieldElt =: (((lhs%.pfieldElt) %+ (rhs%.pfieldElt)) %% (field %. order))
ret (lhsExpr retVal)
$(generateFunction [funcDefn|primeFieldToInt PrimeFieldElt -> HLCInt|])
primeFieldToInt ret elt = do
ret $ (elt %. pfieldElt)
instance Group (ExprTy PrimeField) (ExprTy PrimeFieldElt) where
add' = call_primeFieldAdd
toInt' = call_primeFieldToInt
makePrimeFieldElt n = do
elt <- makeVar :: Var PrimeFieldElt
elt %. pfieldElt =: n
return elt
$(generateFunction [funcDefn|arithmetic HLCInt|])
arithmetic ret = do
field <- makeVar :: Var PrimeField
initPrimeField field (intLit 7)
q <- makeVar :: Var (HLCPrimArray HLCInt 5)
m <- makePrimeFieldElt (intLit 5)
n <- makePrimeFieldElt (intLit 2)
m =: add field m n
ifThenElse (toInt m %== intLit 0)
(do exprStmt $ callVarFunction printf (stringLit "Success: 5+2=0 (mod 7)\n" :+: HNil)
ret (intLit 0))
(do exprStmt $ callVarFunction printf (stringLit "Error\n" :+: HNil)
ret (intLit 1))
$(generateFunction [funcDefn|test HLCVoid|])
test ret = do
ifThenElseRest (intLit 15 %<= intLit 5)
(\c -> do
x <- makeVar :: Var HLCInt
x =: intLit 12
c
)
(\c -> do
x <- makeVar :: Var HLCInt
x =: intLit 13
c
)
whileStmt (intLit 3 %<= intLit 10)
(\break cont -> do
x <- makeVar :: Var HLCInt
x =: intLit 7
ifThenElseRest (intLit 3 %<= intLit 10)
(\c -> do
break
)
id
cont
)
exprStmt $ callVarFunction printf
(stringLit "Hello, world! This is an integer: %d\n" :+: intLit 15 :+: HNil)
ret void
$(generateFunction [funcDefn|fact HLCInt -> HLCInt|])
fact ret n = do
ifThenElse (n %<= intLit 1)
(ret n)
(ret $ (n %* (call_fact (n %- intLit 1))))
$(generateFunction [funcDefn|hlcMain HLCInt -> HLCPtr (HLCPtr HLCChar) -> HLCInt|])
hlcMain ret argc argv = do
v <- makeVar :: Var HLCInt
argc =: v
argv =: nullPtr
a <- makeUniquePtr (intLit 1) :: Var (UniquePtr HLCInt)
b <- makeUniquePtr (intLit 2) :: Var (UniquePtr PrimeFieldElt)
c <- makeVar :: Var (HLCPtr HLCInt)
d <- makeUniquePtr (intLit 2) :: Var (UniquePtr HLCInt)
deref c =: intLit 3
deref (weakRef a) =: intLit 2
(weakRef a %@ intLit 0) =: intLit 10
(weakRef a %@ intLit 1) =: intLit 10
exprStmt $ call_test
exprStmt $ call_arithmetic
v1 <- makeVar :: Var StructA
v2 <- makeVar :: Var StructB
v3 <- makeVar :: Var (FunctionPtr '[HLCInt] HLCInt)
v3 =: addrOfFunc (Proxy :: Proxy Fact)
exprStmt $ callFunPtr v3 (intLit 4 :+: HNil)
ret (call_fact (intLit 5))
main :: IO ()
main = print $ printWholeTU (Just 'hlcMain) $ runOuterHLC $ do
_ <- call_test
_ <- call_fact withType
_ <- call_hlcMain withType withType
_ <- call_primeFieldAdd withType withType withType
_ <- call_primeFieldToInt (withType :: (ExprTy PrimeFieldElt))
declareObj (Proxy :: Proxy StructA)
declareObj (Proxy :: Proxy StructB)
_ <- call_arithmetic
return ()
| alexstachnik/High-Level-C | src/Test.hs | gpl-2.0 | 6,573 | 0 | 16 | 1,473 | 1,883 | 961 | 922 | 177 | 1 |
S = \xyz.xz(yz)
K = \x\y.x
SKK = \z.Kz(Kz) -- Done in two steps, first x, then y.
= \z.(\x\y.x)z((\x\y.x)z) -- Should the second K be evaluated? Yep.
= \z.(\y.z)((\x\y.y)z)
= \z.z -- beta Normal form
(\x.xx)(\x.xx) -- Non-terminating reduction. twice twice!
-- Numbers
_0 = \xy.y
_1 = \xy.xy
--- ... ---
_n = \xy.(x^n y)
--succ _n = \xy.x(n x y)
-- = \xy._1 x (n x y)
succ = \nxy.x(n x y)
add = \mnxy.n x (m x y)
-- Generation of G-code
-- example of G-machine execution (18.2)
-- Miranda program:
-- from n = n : from (succ n)
-- succ n = n + 1
-- ---------------------------
-- from (succ 0)
--
-- Start point: stack: | | |
-- tree of application: @ -> @ -> 0
-- -> succ
-- -> from
-- |--> stored in stack.
-- Go down the tree (along the applications, called the spine) and find the last application, say of function f.
-- Let f's arity be n. Then go up n applications to obtain the redex.
--
-- UNWIND - a loaded (!) instruction.
-- In the above tree, the first @ is the spine, and since f's arity is 1, it is also the root of the redex.
--
-- Executing the body of a function is merely constructing an equivalent graph and evaluating it.
--
-- list o intermeditae function:
-- 1. UNWIND
-- 2. PUHGLOBAL STACK
--
--
--Example:
-- f x = x + x
-- g y = 1 + y
-- prog = f (g 2)
--
-- First: Unwind.
-- UNWIND
-- PUSHINT 2
-- PUSHGLOBAL g
-- MKAP
-- PUSHGLOBAL f
-- MKAP
-- UPDATE 1
-- UNWIND
--
-- The tree still has a redex.
-- Expanding f's body:
-- PUSH 0
-- PUSH 0
-- PUSHGLOBAL +
-- MKAP
-- MKAP
-- UPDATE 2
-- POP 1
--
-- In the case of +, as an operator behaving differently from user defined functions,
-- |__________|------------ @
-- |__________|------- @ _ -- Usually we evaluate these two parameters: PUSH 1; EVAl; PUSH 1; EVAL; ADD; UPDATE 3; POP 2; UNWIND;
-- |__________| + _ ^
-- |__________|-------------^ ^
-- |__________|-----------------^
--
-- Here,
--
| murukeshm/scratchpad | haskell/lambda.hs | gpl-2.0 | 1,969 | 45 | 8 | 472 | 304 | 205 | 99 | -1 | -1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell #-}
module Machine.Numerical.Type where
import qualified Machine.Numerical.Config as Con
import qualified Arithmetic.Op as A
import Autolib.Informed
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Reporter
import Data.Typeable
data Computer = Computer
deriving Typeable
$(derives [makeReader, makeToDoc] [''Computer])
class (ToDoc c, Reader c, Con.Check c m) => TypeC c m
instance (ToDoc c, Reader c, Con.Check c m) => TypeC c m
data Type c m =
Make { op :: A.Exp Integer
, key :: Integer
, fun_info :: Doc -- funktions-name/-erklärung
, extra_info :: Doc -- extra erklärung/bedingung
, args :: [[ Integer ]] -- argumente zum testen
, cut :: Int -- höchstens soviele schritte
, checks :: [c]
, start :: m -- damit soll der student anfangen
}
deriving Typeable
-- obsolete fields:
-- zu berechnende funktion
fun :: Type c m -> [ Integer ] -> Reporter Integer
fun mk = \ xs -> A.eval ( mkargs xs ( key mk ) ) ( op mk )
-- sonstige Bedingungen an Maschine
check :: Con.Check c m => Type c m -> m -> Reporter ()
check mk = check_all (checks mk)
check_all :: Con.Check c m
=> [c] -> m -> Reporter ()
check_all cs = \ m -> sequence_ $ do c <- cs ; return $ Con.check c m
mkargs xs key = A.bind $ ( "mat", key ) : do
(i, x) <- zip [ 1 :: Int .. ] xs
return ( "x" ++ show i , x )
instance Informed ( Type c m ) where
info m = fun_info m
informed info m = m { fun_info = info }
$(derives [makeReader, makeToDoc] [''Type])
| florianpilz/autotool | src/Machine/Numerical/Type.hs | gpl-2.0 | 1,596 | 4 | 11 | 397 | 564 | 309 | 255 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
module Language.Eval (expr, eval) where
import Data.Text
import Text.Parsec.Text
import Text.Parsec.Prim
import Text.Parsec.Expr
import Text.Parsec.Token
import Text.Parsec.Char (satisfy, alphaNum, char, oneOf, letter)
import Text.Parsec.Language (emptyDef, javaStyle)
import Data.Functor.Identity
import Data.Bits
-- I really wanted to avoid this bit but in order to parse Text
-- it's necessary to define the full type of the language for the
-- lexer
ezLanguage :: GenLanguageDef Text [Integer] Identity
ezLanguage = LanguageDef {
caseSensitive = True
, commentStart = "/*"
, commentEnd = "*/"
, commentLine = "#"
, nestedComments = False
, identStart = letter
-- TODO: Only single-letter idents
, identLetter = letter -- satisfy $ const False
, opStart = oneOf "<>+-&|"
, opLetter = oneOf "<>"
, reservedNames = names
, reservedOpNames = ops
}
where
names = []
ops = ["<<",">>", "&", "|", "+", "-", "*"]
lexer = makeTokenParser ezLanguage
expr :: Stream Text Identity Char => ParsecT Text [Integer] Identity Integer
expr = buildExpressionParser table term
<?> "expression"
substituteSymbol = do
s <- lexeme lexer letter <?> "variable"
let idx = fromEnum s - fromEnum 'a'
u <- getState
-- TODO: friendlier error when idx is out of the array
-- now it throws an exception. Rather make it a parse
-- error
return $ u !! idx
term = parens lexer expr
<|> integer lexer
<|> substituteSymbol
<?> "simple expression"
shiftr :: Bits a => a -> Integer -> a
shiftr x b = shiftR x (fromIntegral b)
shiftl :: Bits a => a -> Integer -> a
shiftl x b = shiftL x (fromIntegral b)
table = [ [prefix "-" negate, prefix "+" id ]
, [postfix "++" (+1)]
, [binary "<<" shiftl AssocLeft, binary ">>" shiftr AssocLeft ]
, [binary "*" (*) AssocLeft, binary "/" div AssocLeft, binary "&" (.&.) AssocLeft ]
, [binary "+" (+) AssocLeft, binary "-" (-) AssocLeft ]
, [binary "|" (.|.) AssocLeft ]
]
binary name fun = Infix (do{ reservedOp lexer name; return fun })
prefix name fun = Prefix (do{ reservedOp lexer name; return fun })
postfix name fun = Postfix (do{ reservedOp lexer name; return fun })
-- Will substitute 1 for 'a', 2 for 'b'
test = runParser expr [1, 2] "" "(0xff & 0xf) << (a + b)"
eval :: Text -> [Integer] -> Integer
eval s vars = case runParser expr vars "" s of
Left e -> error $ show e
Right i -> i
| gitfoxi/Language.Eval | Language/Eval.hs | gpl-2.0 | 2,711 | 0 | 11 | 718 | 771 | 424 | 347 | 59 | 2 |
import System.Random
import qualified Data.Map as Map
ns = [7,6..1]
chunks n xs
| n <= length xs = fst (splitAt n xs) : chunks n (tail xs)
| otherwise = []
intToDouble :: Int -> Double
intToDouble = fromRational . toRational
rootmap str =
Map.fromListWith (Map.unionWith (+)) t
where
t = [(init s, Map.singleton (last s) 1) | s <- chks str]
chks str = concat [chunks x str | x <- ns]
mapAccumFsum = Map.mapAccum fsum 0
where
fsum a b = (a + b, (a+1,a+b))
scale :: Int -> Double -> Int
scale i r = min i t
where
itd = intToDouble i
t = floor (r*(itd+1))
rands :: IO [Double]
rands = do
g <- getStdGen
let rs = randomRs (0.0,1.0) g
return rs
lastN n xs = reverse (take n (reverse xs))
floorLogBase = floor . logBase 0.5
flipTrunc a b x = if x > b then a else a `max` x
filterMe (d,m) c = Map.filter (\(a,b) -> a<=c && c<=b) m
randLength rnd = (flipTrunc 0 6) (floorLogBase rnd)
randAccum rmap x out = findAccum rmap (drop out x)
findAccum rmap x = lookAccum rmap (Map.lookup x rmap) x
lookAccum rmap (Just x) str = (str,x)
lookAccum rmap Nothing str = lookAccum rmap (Map.lookup next rmap) next
where
next = drop 1 str
extTuple tree rndout rand accum = ((accum, l, rndout, limit, scaledRand), ks)
where
l = length accum
ks = Map.keys (filterMe (limit,i) scaledRand)
(limit,i) = mapAccumFsum tree
scaledRand = (scale (limit-1) rand) + 1
accumLen = 6
genAccum rmap rands accum =
accTuple : genAccum rmap newRands newAccum
where
newRands = drop 2 rands
newAccum = lastN accumLen (accum ++ c)
(_,c) = accTuple
rndout = randLength (rands!!0)
(accu,tree) = randAccum rmap accum rndout
accTuple = extTuple tree rndout (rands!!1) accu
main = do
rs <- rands
--content <- readFile "matkustus-maan-keskipisteeseen.txt"
content <- readFile "journey-to-centre-of-earth.txt"
let
example = take 10000 content
rmap = rootmap example
accum = take accumLen example
accums = genAccum rmap rs accum
mapM_ (putStrLn . show) (take 55 accums)
| jsavatgy/dit-doo | code/first-debug.hs | gpl-2.0 | 2,067 | 0 | 11 | 494 | 939 | 484 | 455 | 56 | 2 |
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules, NoMonomorphismRestriction #-}
import Network.HTTP
import Network.URI
import Data.Char
import Data.List (elemIndex)
import Data.Maybe
import Text.XML.HXT.Core
import Data.Tree.NTree.TypeDefs
import System.Environment
import Text.JSON
import Database.MongoDB
import Control.Concurrent (threadDelay)
import Control.Monad.Trans (liftIO)
import qualified Data.Map as M
import qualified Data.Text as T
data Person = Person
{ firstName :: String
, lastName :: String
, email :: String
, other :: [(String, String)]
} deriving (Show, Eq)
instance JSON Person where
showJSON p = jobj [ ("firstName", jstr $ firstName p)
, ("lastName", jstr $ lastName p)
, ("email", jstr $ email p)
, ("other", jobj $ map toJSValTuple (other p)) ]
data SearchResultErr = NoResultsErr | TooManyResultsErr deriving (Show, Eq)
instance JSON SearchResultErr where
showJSON NoResultsErr = jobj [("err", jstr "No Results")]
showJSON TooManyResultsErr = jobj [("err", jstr "Too Many Results")]
type SearchResult = Either SearchResultErr [Person]
-- ./main "abba" # searches only "abba"
-- ./main "b" "c" # searches between "b" and "c"
-- ./main # searches everything
main = do
args <- getArgs
pipe <- runIOE $ connect (readHostPort mongoURL)
doWork args pipe
Database.MongoDB.close pipe
doWork args pipe
| null args = main' "a" "{" pipe
| length args == 1 = do
let query = head args
doc <- getDoc query
searchResult <- scanDoc query doc
print $ encode $ showJSON searchResult
| otherwise = main' (head args) (args !! 1) pipe
main' query stop pipe = do
print query
doc <- getDoc query
searchResult <- scanDoc query doc
print searchResult
case searchResult of
Right plist -> access pipe (ConfirmWrites ["w" =: 2]) "graphuva" (runInsert plist)
_ -> access pipe master "graphuva" (runInsert [])
if searchResult == Left TooManyResultsErr
then main' (nextDeepQuery query) stop pipe
else if next >= stop then print "done!" else main' next stop pipe where next = nextQuery query
getDoc query = do
rsp <- simpleHTTP $ uvaRequest query
html <- fmap (takeWhile isAscii) (getResponseBody rsp)
return $ readString [withParseHTML yes, withWarnings no] html
scanDoc :: String -> IOStateArrow () XmlTree XmlTree -> IO SearchResult
scanDoc query doc = do
h3s <- runX $ doc //> hasName "h3"
if length h3s == 2
then do
let errMsg = (getText'.getTreeVal.head.getTreeChildren.head) h3s
return $ Left $ if errMsg == "No matching entries were found"
then NoResultsErr
else TooManyResultsErr
else do
centers <- runX $ doc //> hasName "center"
if length centers == 2
then do
texts <- runX $ doc //> hasName "td" //> getText
let textList = (tail.tail.tail) texts
let fullName = (unwords.init.words) (texts !! 1)
let computingId = (tail.init.last.words) (texts !! 1)
let person = Person {
firstName = clean $ (head.words) fullName,
lastName = clean $ (last.words) fullName,
email = clean $ map toLower $
findKeyInList textList "Primary E-Mail Address",
other = [ ("status", clean $ trim $
findKeyInList textList "Classification")
, ("department", clean $ trim $
findKeyInList textList "Department")
, ("computingId", computingId) ]
}
return $ Right [person]
else do
rows <- runX $ doc //> hasName "tr"
return $ Right (readTableRows rows)
findKeyInList list key = case elemIndex key list of
Just i -> list !! (i+1)
Nothing -> ""
safeMap f ls n = if length ls >= n then map f $ ls !! n else ""
nextDeepQuery query = query ++ "a"
nextQuery "z" = "{"
nextQuery query = if last query == 'z'
then nextQuery $ init query
else init query ++ [succ $ last query]
readTableRows :: [NTree XNode] -> [Person]
readTableRows (a:b:rows) = fmap parseRow rows
readTableRows rows = []
parseRow row = Person {
firstName = clean $ (head.tail.words) fullName,
lastName = clean $ (init.head.words) fullName,
email = clean $ map toLower $ getEmailFromTr row,
other = [ ("phoneNumber", clean pNum)
, ("status", clean $ getTypeFromTr row)
, ("department", clean $ getDepartmentFromTr row)
, ("computingId", computingId)]
}
where fullName = (unwords.init.words) $ getNameFromTr row
computingId = (tail.init.last.words) $ getNameFromTr row
pNum = getPhoneNumberFromTr row
getNameFromTr row = getLinkTextFromTd $ getTreeChildren row !! 3
getEmailFromTr row = getLinkTextFromTd $ getTreeChildren row !! 5
getPhoneNumberFromTr row = getTextFromTd $ getTreeChildren row !! 7
getTypeFromTr row = getTextFromTd $ getTreeChildren row !! 9
getDepartmentFromTr row = getTextFromTd $ getTreeChildren row !! 11
getTextFromTd tree = getText' $ getTreeVal $ head $ getTreeChildren tree
getLinkTextFromTd tree =
if null val then "" else (getText'.getTreeVal.head) val
where val = (getTreeChildren.head.getTreeChildren) tree
getTreeVal (NTree a b) = a
getTreeChildren (NTree a b) = b
getText' (XText a) = a
uvaRequest :: String -> Request_String
uvaRequest query = Request {
rqURI = case parseURI "http://www.virginia.edu/cgi-local/ldapweb" of Just u -> u
, rqMethod = POST
, rqHeaders = [ mkHeader HdrContentType "text/html"
, mkHeader HdrContentLength $ show $ length body
]
, rqBody = body
}
where body = "whitepages=" ++ query
toJSValTuple (a, b) = (a, jstr b)
jstr :: String -> JSValue
jstr = JSString . toJSString
jobj :: [(String,JSValue)] -> JSValue
jobj = JSObject . toJSObject
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
clean :: String -> String
clean str = if str == "\160" then "" else str
mongoURL = "ds053788.mongolab.com:53788"
runInsert plist = do
auth "hermes" "hermes"
insertPeople' plist
{-
insertPeople plist = do
case null plist of
True -> find (select [] "people2") {sort = ["home.city" =: 1]}
False -> do
insertPerson' (head plist)
runInsert (tail plist)
-}
insertPeople' plist = insertMany "people" (bsonList plist)
insertPerson p = repsert (select ["_id" =: computingId p] "people") (bsonStruct p)
insertPerson' p = save "people" (bsonStruct p)
bsonTuple [] = []
bsonTuple ((a,b):xs) = ((T.pack a) =: b) : (bsonTuple xs)
bsonStruct p = [ "_id" =: computingId p
, "firstName" =: firstName p
, "lastName" =: lastName p
, "email" =: email p
, "other" =: (bsonTuple.other) p ]
computingId p = getValFromMap (other p) "computingId"
getValFromMap m key = (fromMaybe "" $ M.lookup key (M.fromList m))
bsonList [] = []
bsonList (p:ps) = bsonStruct p : bsonList ps | BinRoot/graphUVA | main.hs | gpl-2.0 | 7,204 | 0 | 21 | 1,923 | 2,301 | 1,176 | 1,125 | 161 | 4 |
{-| Module : TypeConversion
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
The conversion from UHA types to Tp (a simpler representation), and vice versa.
-}
module Helium.StaticAnalysis.Miscellaneous.TypeConversion where
import Helium.Syntax.UHA_Utils (getNameName, nameFromString)
import Helium.Syntax.UHA_Range (noRange)
import Helium.Utils.Utils (internalError)
import Data.List (union)
import Data.Maybe
import Helium.Syntax.UHA_Syntax
import Top.Types
----------------------------------------------------------------------
-- conversion functions from and to UHA
namesInTypes :: Types -> Names
namesInTypes = foldr (union . namesInType) []
namesInType :: Type -> Names
namesInType uhaType = case uhaType of
Type_Application _ _ fun args -> namesInTypes (fun : args)
Type_Variable _ name -> [name]
Type_Constructor _ _ -> []
Type_Parenthesized _ t -> namesInType t
Type_Qualified _ _ t -> namesInType t
Type_Forall{} -> internalError "TypeConversion.hs" "namesInType" "universal types are currently not supported"
Type_Exists{} -> internalError "TypeConversion.hs" "namesInType" "existential types are currently not supported"
-- name maps play an important role in converting since they map UHA type variables (string) to TVar's (int)
makeNameMap :: Names -> [(Name,Tp)]
makeNameMap = flip zip (map TVar [0..])
-- also return the name map
makeTpSchemeFromType' :: Type -> (TpScheme, [(Int, Name)])
makeTpSchemeFromType' uhaType =
let names = namesInType uhaType
nameMap = makeNameMap names
intMap = zip [0..] names
context = predicatesFromContext nameMap uhaType
tp = makeTpFromType nameMap uhaType
scheme = Quantification (ftv tp, [ (i,getNameName n) | (n,TVar i) <- nameMap], context .=>. tp)
in (scheme, intMap)
makeTpSchemeFromType :: Type -> TpScheme
makeTpSchemeFromType = fst . makeTpSchemeFromType'
predicatesFromContext :: [(Name,Tp)] -> Type -> Predicates
predicatesFromContext nameMap (Type_Qualified _ is _) =
concatMap predicateFromContext is
where
predicateFromContext (ContextItem_ContextItem _ cn [Type_Variable _ vn]) =
case lookup vn nameMap of
Nothing -> []
Just tp -> [Predicate (getNameName cn) tp]
predicateFromContext _ = internalError "TypeConversion.hs" "predicateFromContext" "malformed type in context"
predicatesFromContext _ _ = []
makeTpFromType :: [(Name,Tp)] -> Type -> Tp
makeTpFromType nameMap = rec_
where
rec_ :: Type -> Tp
rec_ uhaType = case uhaType of
Type_Application _ _ fun args -> foldl TApp (rec_ fun) (map rec_ args)
Type_Variable _ name -> fromMaybe (TCon "???") (lookup name nameMap)
Type_Constructor _ name -> TCon (getNameName name)
Type_Parenthesized _ t -> rec_ t
Type_Qualified _ _ t -> rec_ t
Type_Forall{} -> internalError "TypeConversion.hs" "makeTpFromType" "universal types are currently not supported"
Type_Exists{} -> internalError "TypeConversion.hs" "makeTpFromType" "existential types are currently not supported"
convertFromSimpleTypeAndTypes :: SimpleType -> Types -> (Tp,Tps)
convertFromSimpleTypeAndTypes stp tps =
let SimpleType_SimpleType _ name typevariables = stp
nameMap = makeNameMap (foldr union [] (typevariables : map namesInType tps))
simpletype = foldl TApp (TCon (getNameName name)) (take (length typevariables) (map TVar [0..]))
in (simpletype,map (makeTpFromType nameMap) tps)
makeTypeFromTp :: Tp -> Type
makeTypeFromTp t =
let (x,xs) = leftSpine t
in if null xs
then f x
else Type_Application noRange True (f x) (map makeTypeFromTp xs)
where f (TVar i) = Type_Variable noRange (nameFromString ('v' : show i))
f (TCon s) = Type_Constructor noRange (nameFromString s)
f (TApp _ _) = error "TApp case in makeTypeFromTp"
| roberth/uu-helium | src/Helium/StaticAnalysis/Miscellaneous/TypeConversion.hs | gpl-3.0 | 4,411 | 0 | 15 | 1,250 | 1,090 | 560 | 530 | 67 | 7 |
-- Doing websocket requests from multiple places over a single connection
-- using the Requester class
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Reflex.Dom.Core
import Control.Monad.IO.Class
import Control.Monad.Primitive
import Reflex.Dom.WebSocket.Monad
import Reflex.Dom.WebSocket.Message
import qualified Data.Text as T
import Data.Monoid
-- Example Code
import Shared
codeToRun
:: (MonadWidget t m)
=> WithWebSocketT Shared.Request t m ()
codeToRun = do
ev1 <- button "Request1"
ti1 <- textInput def
respEv1 <- getWebSocketResponse (Request1 <$> tagPromptlyDyn (value ti1) ev1)
widgetHold (text "Waiting for Response1")
((\(Response1 l) -> text ("Length is: " <> T.pack (show l))) <$> respEv1)
ev2 <- button "Request2"
ti2 <- textInput def
respEv2 <- getWebSocketResponse (Request2 <$> tagPromptlyDyn (zipDyn (value ti1) (value ti2)) ev2)
widgetHold (text "Waiting for Response2")
((\(Response2 t) -> text ("Concat string: " <> t)) <$> respEv2)
ev2 <- button "Show Widget4"
widgetHold (return ()) (widget4 <$ ev2)
return ()
widget4 = do
respEv4 <- getWebSocketPushResponse
(Request4 "Request 4 Text")
widgetHold (text "Waiting for Response4")
((\(Response4 t) -> text ("Counter:" ++ T.pack (show t)))
<$> respEv4)
myWidget ::
(MonadWidget t m)
=> m ()
myWidget = do
text "Test WithWebsocket"
(_,_) <- withWSConnection "ws://127.0.0.1:3000/" never False codeToRun
return ()
main = mainWidget myWidget
| dfordivam/reflex-websocket-interface | example/pushResponse/app/Main.hs | gpl-3.0 | 1,558 | 0 | 17 | 275 | 492 | 251 | 241 | 43 | 1 |
{-#LANGUAGE TypeOperators, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Carnap.Languages.PureFirstOrder.Logic.Magnus (magnusQLCalc,parseMagnusQL, MagnusQL(..)) where
import Data.Map as M (lookup, Map,empty)
import Text.Parsec
import Carnap.Core.Data.Types (Form)
import Carnap.Languages.PureFirstOrder.Syntax
import Carnap.Languages.PureFirstOrder.Parser
import Carnap.Languages.PurePropositional.Logic.Magnus hiding (Pr)
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineFitchMemo, hoProcessLineFitch)
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericConstructors
import Carnap.Languages.PurePropositional.Logic.Rules (fitchAssumptionCheck)
import Carnap.Languages.PureFirstOrder.Logic.Rules
import Carnap.Languages.PurePropositional.Logic.Rules (premConstraint,axiom)
--------------------
-- 3. System QL --
--------------------
-- A system of first-order logic resembling system QL from PD Magnus'
-- magnus
data MagnusQL = MagnusSL MagnusSL | UI | UE | EI | EE1 | EE2 | IDI | IDE1 | IDE2
| Pr (Maybe [(ClassicalSequentOver PureLexiconFOL (Sequent (Form Bool)))])
deriving Eq
instance Show MagnusQL where
show (MagnusSL x) = show x
show UI = "∀I"
show UE = "∀E"
show EI = "∃I"
show EE1 = "∃E"
show EE2 = "∃E"
show IDI = "=I"
show IDE1 = "=E"
show IDE2 = "=E"
show (Pr _) = "PR"
instance Inference MagnusQL PureLexiconFOL (Form Bool) where
ruleOf UI = universalGeneralization
ruleOf UE = universalInstantiation
ruleOf EI = existentialGeneralization
ruleOf EE1 = existentialDerivation !! 0
ruleOf EE2 = existentialDerivation !! 1
ruleOf IDI = eqReflexivity
ruleOf IDE1 = leibnizLawVariations !! 0
ruleOf IDE2 = leibnizLawVariations !! 1
ruleOf (Pr _) = axiom
premisesOf (MagnusSL x) = map liftSequent (premisesOf x)
premisesOf r = upperSequents (ruleOf r)
conclusionOf (MagnusSL x) = liftSequent (conclusionOf x)
conclusionOf r = lowerSequent (ruleOf r)
indirectInference (MagnusSL x) = indirectInference x
indirectInference x
| x `elem` [ EE1,EE2 ] = Just assumptiveProof
| otherwise = Nothing
restriction UI = Just (eigenConstraint tau (SS (lall "v" $ phi' 1)) (fogamma 1))
restriction EE1 = Just (eigenConstraint tau (SS (lsome "v" $ phi' 1) :-: SS (phin 1)) (fogamma 1 :+: fogamma 2))
restriction EE2 = Just (eigenConstraint tau (SS (lsome "v" $ phi' 1) :-: SS (phin 1)) (fogamma 1 :+: fogamma 2))
restriction (Pr prems) = Just (premConstraint prems)
restriction _ = Nothing
globalRestriction (Left ded) n (MagnusSL CondIntro1) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (MagnusSL CondIntro2) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2])]
globalRestriction (Left ded) n (MagnusSL BicoIntro1) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2]), ([phin 2], [phin 1])]
globalRestriction (Left ded) n (MagnusSL BicoIntro2) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2]), ([phin 2], [phin 1])]
globalRestriction (Left ded) n (MagnusSL BicoIntro3) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2]), ([phin 2], [phin 1])]
globalRestriction (Left ded) n (MagnusSL BicoIntro4) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2]), ([phin 2], [phin 1])]
globalRestriction (Left ded) n (MagnusSL NegeIntro1) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeIntro2) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeIntro3) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeIntro4) = Just $ fitchAssumptionCheck n ded [([phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeElim1) = Just $ fitchAssumptionCheck n ded [([lneg $ phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeElim2) = Just $ fitchAssumptionCheck n ded [([lneg $ phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeElim3) = Just $ fitchAssumptionCheck n ded [([lneg $ phin 1], [phin 2, lneg $ phin 2])]
globalRestriction (Left ded) n (MagnusSL NegeElim4) = Just $ fitchAssumptionCheck n ded [([lneg $ phin 1], [phin 2, lneg $ phin 2])]
globalRestriction _ _ _ = Nothing
isAssumption (MagnusSL x) = isAssumption x
isAssumption _ = False
isPremise (Pr _) = True
isPremise _ = False
parseMagnusQL rtc = try quantRule <|> liftProp
where liftProp = do r <- parseMagnusSL (RuntimeNaturalDeductionConfig mempty mempty)
return (map MagnusSL r)
quantRule = do r <- choice (map (try . string) ["∀I", "AI", "∀E", "AE", "∃I", "EI", "∃E", "EE", "=I","=E","PR"])
case r of
r | r `elem` ["∀I","AI"] -> return [UI]
| r `elem` ["∀E","AE"] -> return [UE]
| r `elem` ["∃I","EI"] -> return [EI]
| r `elem` ["∃E","EE"] -> return [EE1, EE2]
| r == "PR" -> return [Pr (problemPremises rtc)]
| r == "=I" -> return [IDI]
| r == "=E" -> return [IDE1,IDE2]
parseMagnusQLProof :: RuntimeNaturalDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine MagnusQL PureLexiconFOL (Form Bool)]
parseMagnusQLProof rtc = toDeductionFitch (parseMagnusQL rtc) magnusFOLFormulaParser
magnusQLCalc = mkNDCalc
{ ndRenderer = FitchStyle StandardFitch
, ndParseProof = parseMagnusQLProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver magnusFOLFormulaParser
, ndParseForm = magnusFOLFormulaParser
, ndNotation = ndNotation magnusSLCalc
}
| gleachkr/Carnap | Carnap/src/Carnap/Languages/PureFirstOrder/Logic/Magnus.hs | gpl-3.0 | 6,636 | 0 | 17 | 1,711 | 2,268 | 1,202 | 1,066 | 96 | 1 |
{-# LANGUAGE BangPatterns, CPP, RankNTypes, MagicHash, UnboxedTuples, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, DeriveDataTypeable, UnliftedFFITypes #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Array.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (MPTCs, uses Control.Monad.ST)
--
-- Basis for IArray and MArray. Not intended for external consumption;
-- use IArray or MArray instead.
--
-----------------------------------------------------------------------------
module Data.Array.Base where
import Control.Monad.ST.Lazy ( strictToLazyST )
import qualified Control.Monad.ST.Lazy as Lazy (ST)
import Data.Ix ( Ix, range, index, rangeSize )
import Foreign.C.Types
import Foreign.StablePtr
import Data.Char
import GHC.Arr ( STArray )
import qualified GHC.Arr as Arr
import qualified GHC.Arr as ArrST
import GHC.ST ( ST(..), runST )
import GHC.Base
import GHC.Ptr ( Ptr(..), FunPtr(..), nullPtr, nullFunPtr )
import GHC.Stable ( StablePtr(..) )
#if !MIN_VERSION_base(4,6,0)
import GHC.Exts ( Word(..) )
#endif
import GHC.Int ( Int8(..), Int16(..), Int32(..), Int64(..) )
import GHC.Word ( Word8(..), Word16(..), Word32(..), Word64(..) )
import GHC.IO ( stToIO )
import GHC.IOArray ( IOArray(..),
newIOArray, unsafeReadIOArray, unsafeWriteIOArray )
import Data.Typeable
#include "MachDeps.h"
-----------------------------------------------------------------------------
-- Class of immutable arrays
{- | Class of immutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type. The @IArray@ class is
parameterised over both @a@ and @e@, so that instances specialised to
certain element types can be defined.
-}
class IArray a e where
-- | Extracts the bounds of an immutable array
bounds :: Ix i => a i e -> (i,i)
numElements :: Ix i => a i e -> Int
unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> a i e
unsafeAt :: Ix i => a i e -> Int -> e
unsafeReplace :: Ix i => a i e -> [(Int, e)] -> a i e
unsafeAccum :: Ix i => (e -> e' -> e) -> a i e -> [(Int, e')] -> a i e
unsafeAccumArray :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> a i e
unsafeReplace arr ies = runST (unsafeReplaceST arr ies >>= unsafeFreeze)
unsafeAccum f arr ies = runST (unsafeAccumST f arr ies >>= unsafeFreeze)
unsafeAccumArray f e lu ies = runST (unsafeAccumArrayST f e lu ies >>= unsafeFreeze)
{-# INLINE safeRangeSize #-}
safeRangeSize :: Ix i => (i, i) -> Int
safeRangeSize (l,u) = let r = rangeSize (l, u)
in if r < 0 then error "Negative range size"
else r
{-# INLINE safeIndex #-}
safeIndex :: Ix i => (i, i) -> Int -> i -> Int
safeIndex (l,u) n i = let i' = index (l,u) i
in if (0 <= i') && (i' < n)
then i'
else error ("Error in array index; " ++ show i' ++
" not in range [0.." ++ show n ++ ")")
{-# INLINE unsafeReplaceST #-}
unsafeReplaceST :: (IArray a e, Ix i) => a i e -> [(Int, e)] -> ST s (STArray s i e)
unsafeReplaceST arr ies = do
marr <- thaw arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
return marr
{-# INLINE unsafeAccumST #-}
unsafeAccumST :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumST f arr ies = do
marr <- thaw arr
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE unsafeAccumArrayST #-}
unsafeAccumArrayST :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumArrayST f e (l,u) ies = do
marr <- newArray (l,u) e
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE array #-}
{-| Constructs an immutable array from a pair of bounds and a list of
initial associations.
The bounds are specified as a pair of the lowest and highest bounds in
the array respectively. For example, a one-origin vector of length 10
has bounds (1,10), and a one-origin 10 by 10 matrix has bounds
((1,1),(10,10)).
An association is a pair of the form @(i,x)@, which defines the value of
the array at index @i@ to be @x@. The array is undefined if any index
in the list is out of bounds. If any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
Because the indices must be checked for these errors, 'array' is
strict in the bounds argument and in the indices of the association
list. Whether @array@ is strict or non-strict in the elements depends
on the array type: 'Data.Array.Array' is a non-strict array type, but
all of the 'Data.Array.Unboxed.UArray' arrays are strict. Thus in a
non-strict array, recurrences such as the following are possible:
> a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i \<- [2..100]])
Not every index within the bounds of the array need appear in the
association list, but the values associated with indices that do not
appear will be undefined.
If, in any dimension, the lower bound is greater than the upper bound,
then the array is legal, but empty. Indexing an empty array always
gives an array-bounds error, but 'bounds' still yields the bounds with
which the array was constructed.
-}
array :: (IArray a e, Ix i)
=> (i,i) -- ^ bounds of the array: (lowest,highest)
-> [(i, e)] -- ^ list of associations
-> a i e
array (l,u) ies
= let n = safeRangeSize (l,u)
in unsafeArray (l,u)
[(safeIndex (l,u) n i, e) | (i, e) <- ies]
-- Since unsafeFreeze is not guaranteed to be only a cast, we will
-- use unsafeArray and zip instead of a specialized loop to implement
-- listArray, unlike Array.listArray, even though it generates some
-- unnecessary heap allocation. Will use the loop only when we have
-- fast unsafeFreeze, namely for Array and UArray (well, they cover
-- almost all cases).
{-# INLINE [1] listArray #-}
-- | Constructs an immutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
listArray :: (IArray a e, Ix i) => (i,i) -> [e] -> a i e
listArray (l,u) es =
let n = safeRangeSize (l,u)
in unsafeArray (l,u) (zip [0 .. n - 1] es)
{-# INLINE listArrayST #-}
listArrayST :: Ix i => (i,i) -> [e] -> ST s (STArray s i e)
listArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# RULES
"listArray/Array" listArray =
\lu es -> runST (listArrayST lu es >>= ArrST.unsafeFreezeSTArray)
#-}
{-# INLINE listUArrayST #-}
listUArrayST :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [e] -> ST s (STUArray s i e)
listUArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
-- I don't know how to write a single rule for listUArrayST, because
-- the type looks like constrained over 's', which runST doesn't
-- like. In fact all MArray (STUArray s) instances are polymorphic
-- wrt. 's', but runST can't know that.
--
-- More precisely, we'd like to write this:
-- listUArray :: (forall s. MArray (STUArray s) e (ST s), Ix i)
-- => (i,i) -> [e] -> UArray i e
-- listUArray lu = runST (listUArrayST lu es >>= unsafeFreezeSTUArray)
-- {-# RULES listArray = listUArray
-- Then we could call listUArray at any type 'e' that had a suitable
-- MArray instance. But sadly we can't, because we don't have quantified
-- constraints. Hence the mass of rules below.
-- I would like also to write a rule for listUArrayST (or listArray or
-- whatever) applied to unpackCString#. Unfortunately unpackCString#
-- calls seem to be floated out, then floated back into the middle
-- of listUArrayST, so I was not able to do this.
type ListUArray e = forall i . Ix i => (i,i) -> [e] -> UArray i e
{-# RULES
"listArray/UArray/Bool" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Bool
"listArray/UArray/Char" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Char
"listArray/UArray/Int" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int
"listArray/UArray/Word" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word
"listArray/UArray/Ptr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (Ptr a)
"listArray/UArray/FunPtr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (FunPtr a)
"listArray/UArray/Float" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Float
"listArray/UArray/Double" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Double
"listArray/UArray/StablePtr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (StablePtr a)
"listArray/UArray/Int8" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int8
"listArray/UArray/Int16" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int16
"listArray/UArray/Int32" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int32
"listArray/UArray/Int64" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int64
"listArray/UArray/Word8" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word8
"listArray/UArray/Word16" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word16
"listArray/UArray/Word32" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word32
"listArray/UArray/Word64" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word64
#-}
{-# INLINE (!) #-}
-- | Returns the element of an immutable array at the specified index.
(!) :: (IArray a e, Ix i) => a i e -> i -> e
(!) arr i = case bounds arr of
(l,u) -> unsafeAt arr $ safeIndex (l,u) (numElements arr) i
{-# INLINE indices #-}
-- | Returns a list of all the valid indices in an array.
indices :: (IArray a e, Ix i) => a i e -> [i]
indices arr = case bounds arr of (l,u) -> range (l,u)
{-# INLINE elems #-}
-- | Returns a list of all the elements of an array, in the same order
-- as their indices.
elems :: (IArray a e, Ix i) => a i e -> [e]
elems arr = case bounds arr of
(_l, _u) -> [unsafeAt arr i | i <- [0 .. numElements arr - 1]]
{-# INLINE assocs #-}
-- | Returns the contents of an array as a list of associations.
assocs :: (IArray a e, Ix i) => a i e -> [(i, e)]
assocs arr = case bounds arr of
(l,u) -> [(i, arr ! i) | i <- range (l,u)]
{-# INLINE accumArray #-}
{-|
Constructs an immutable array from a list of associations. Unlike
'array', the same index is allowed to occur multiple times in the list
of associations; an /accumulating function/ is used to combine the
values of elements with the same index.
For example, given a list of values of some index type, hist produces
a histogram of the number of occurrences of each index within a
specified range:
> hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
> hist bnds is = accumArray (+) 0 bnds [(i, 1) | i\<-is, inRange bnds i]
-}
accumArray :: (IArray a e, Ix i)
=> (e -> e' -> e) -- ^ An accumulating function
-> e -- ^ A default element
-> (i,i) -- ^ The bounds of the array
-> [(i, e')] -- ^ List of associations
-> a i e -- ^ Returns: the array
accumArray f initialValue (l,u) ies =
let n = safeRangeSize (l, u)
in unsafeAccumArray f initialValue (l,u)
[(safeIndex (l,u) n i, e) | (i, e) <- ies]
{-# INLINE (//) #-}
{-|
Takes an array and a list of pairs and returns an array identical to
the left argument except that it has been updated by the associations
in the right argument. For example, if m is a 1-origin, n by n matrix,
then @m\/\/[((i,i), 0) | i \<- [1..n]]@ is the same matrix, except with
the diagonal zeroed.
As with the 'array' function, if any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
For most array types, this operation is O(/n/) where /n/ is the size
of the array. However, the diffarray package provides an array type
for which this operation has complexity linear in the number of updates.
-}
(//) :: (IArray a e, Ix i) => a i e -> [(i, e)] -> a i e
arr // ies = case bounds arr of
(l,u) -> unsafeReplace arr [ (safeIndex (l,u) (numElements arr) i, e)
| (i, e) <- ies]
{-# INLINE accum #-}
{-|
@accum f@ takes an array and an association list and accumulates pairs
from the list into the array with the accumulating function @f@. Thus
'accumArray' can be defined using 'accum':
> accumArray f z b = accum f (array b [(i, z) | i \<- range b])
-}
accum :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(i, e')] -> a i e
accum f arr ies = case bounds arr of
(l,u) -> let n = numElements arr
in unsafeAccum f arr [(safeIndex (l,u) n i, e) | (i, e) <- ies]
{-# INLINE amap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the elements.
amap :: (IArray a e', IArray a e, Ix i) => (e' -> e) -> a i e' -> a i e
amap f arr = case bounds arr of
(l,u) -> let n = numElements arr
in unsafeArray (l,u) [ (i, f (unsafeAt arr i))
| i <- [0 .. n - 1]]
{-# INLINE ixmap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the indices.
ixmap :: (IArray a e, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> a i e
ixmap (l,u) f arr =
array (l,u) [(i, arr ! f i) | i <- range (l,u)]
-----------------------------------------------------------------------------
-- Normal polymorphic arrays
instance IArray Arr.Array e where
{-# INLINE bounds #-}
bounds = Arr.bounds
{-# INLINE numElements #-}
numElements = Arr.numElements
{-# INLINE unsafeArray #-}
unsafeArray = Arr.unsafeArray
{-# INLINE unsafeAt #-}
unsafeAt = Arr.unsafeAt
{-# INLINE unsafeReplace #-}
unsafeReplace = Arr.unsafeReplace
{-# INLINE unsafeAccum #-}
unsafeAccum = Arr.unsafeAccum
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray = Arr.unsafeAccumArray
-----------------------------------------------------------------------------
-- Flat unboxed arrays
-- | Arrays with unboxed elements. Instances of 'IArray' are provided
-- for 'UArray' with certain element types ('Int', 'Float', 'Char',
-- etc.; see the 'UArray' class for a full list).
--
-- A 'UArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent 'Data.Array.Array' with the same
-- element type. However, 'UArray' is strict in its elements - so
-- don\'t use 'UArray' if you require the non-strictness that
-- 'Data.Array.Array' provides.
--
-- Because the @IArray@ interface provides operations overloaded on
-- the type of the array, it should be possible to just change the
-- array type being used by a program from say @Array@ to @UArray@ to
-- get the benefits of unboxed arrays (don\'t forget to import
-- "Data.Array.Unboxed" instead of "Data.Array").
--
data UArray i e = UArray !i !i !Int ByteArray#
deriving Typeable
{-# INLINE unsafeArrayUArray #-}
unsafeArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [(Int, e)] -> e -> ST s (UArray i e)
unsafeArrayUArray (l,u) ies default_elem = do
marr <- newArray (l,u) default_elem
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeFreezeSTUArray #-}
unsafeFreezeSTUArray :: STUArray s i e -> ST s (UArray i e)
unsafeFreezeSTUArray (STUArray l u n marr#) = ST $ \s1# ->
case unsafeFreezeByteArray# marr# s1# of { (# s2#, arr# #) ->
(# s2#, UArray l u n arr# #) }
{-# INLINE unsafeReplaceUArray #-}
unsafeReplaceUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> UArray i e -> [(Int, e)] -> ST s (UArray i e)
unsafeReplaceUArray arr ies = do
marr <- thawSTUArray arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumUArray #-}
unsafeAccumUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> UArray i e -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumUArray f arr ies = do
marr <- thawSTUArray arr
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumArrayUArray #-}
unsafeAccumArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumArrayUArray f initialValue (l,u) ies = do
marr <- newArray (l,u) initialValue
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE eqUArray #-}
eqUArray :: (IArray UArray e, Ix i, Eq e) => UArray i e -> UArray i e -> Bool
eqUArray arr1@(UArray l1 u1 n1 _) arr2@(UArray l2 u2 n2 _) =
if n1 == 0 then n2 == 0 else
l1 == l2 && u1 == u2 &&
and [unsafeAt arr1 i == unsafeAt arr2 i | i <- [0 .. n1 - 1]]
{-# INLINE [1] cmpUArray #-}
cmpUArray :: (IArray UArray e, Ix i, Ord e) => UArray i e -> UArray i e -> Ordering
cmpUArray arr1 arr2 = compare (assocs arr1) (assocs arr2)
{-# INLINE cmpIntUArray #-}
cmpIntUArray :: (IArray UArray e, Ord e) => UArray Int e -> UArray Int e -> Ordering
cmpIntUArray arr1@(UArray l1 u1 n1 _) arr2@(UArray l2 u2 n2 _) =
if n1 == 0 then if n2 == 0 then EQ else LT else
if n2 == 0 then GT else
case compare l1 l2 of
EQ -> foldr cmp (compare u1 u2) [0 .. (n1 `min` n2) - 1]
other -> other
where
cmp i rest = case compare (unsafeAt arr1 i) (unsafeAt arr2 i) of
EQ -> rest
other -> other
{-# RULES "cmpUArray/Int" cmpUArray = cmpIntUArray #-}
-----------------------------------------------------------------------------
-- Showing IArrays
{-# SPECIALISE
showsIArray :: (IArray UArray e, Ix i, Show i, Show e) =>
Int -> UArray i e -> ShowS
#-}
showsIArray :: (IArray a e, Ix i, Show i, Show e) => Int -> a i e -> ShowS
showsIArray p a =
showParen (p > 9) $
showString "array " .
shows (bounds a) .
showChar ' ' .
shows (assocs a)
-----------------------------------------------------------------------------
-- Flat unboxed arrays: instances
instance IArray UArray Bool where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies False)
{-# INLINE unsafeAt #-}
#if __GLASGOW_HASKELL__ > 706
unsafeAt (UArray _ _ _ arr#) (I# i#) = isTrue#
#else
unsafeAt (UArray _ _ _ arr#) (I# i#) =
#endif
((indexWordArray# arr# (bOOL_INDEX i#) `and#` bOOL_BIT i#)
`neWord#` int2Word# 0#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Char where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies '\0')
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = C# (indexWideCharArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I# (indexIntArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W# (indexWordArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (Ptr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullPtr)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = Ptr (indexAddrArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (FunPtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullFunPtr)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = FunPtr (indexAddrArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Float where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = F# (indexFloatArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Double where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = D# (indexDoubleArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (StablePtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullStablePtr)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = StablePtr (indexStablePtrArray# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
-- bogus StablePtr value for initialising a UArray of StablePtr.
nullStablePtr :: StablePtr a
nullStablePtr = StablePtr (unsafeCoerce# 0#)
instance IArray UArray Int8 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I8# (indexInt8Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int16 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I16# (indexInt16Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int32 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I32# (indexInt32Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int64 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I64# (indexInt64Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word8 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W8# (indexWord8Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word16 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W16# (indexWord16Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word32 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W32# (indexWord32Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word64 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W64# (indexWord64Array# arr# i#)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance (Ix ix, Eq e, IArray UArray e) => Eq (UArray ix e) where
(==) = eqUArray
instance (Ix ix, Ord e, IArray UArray e) => Ord (UArray ix e) where
compare = cmpUArray
instance (Ix ix, Show ix, Show e, IArray UArray e) => Show (UArray ix e) where
showsPrec = showsIArray
-----------------------------------------------------------------------------
-- Mutable arrays
{-# NOINLINE arrEleBottom #-}
arrEleBottom :: a
arrEleBottom = error "MArray: undefined array element"
{-| Class of mutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type.
The @MArray@ class is parameterised over both @a@ and @e@ (so that
instances specialised to certain element types can be defined, in the
same way as for 'IArray'), and also over the type of the monad, @m@,
in which the mutable array will be manipulated.
-}
class (Monad m) => MArray a e m where
-- | Returns the bounds of the array
getBounds :: Ix i => a i e -> m (i,i)
-- | Returns the number of elements in the array
getNumElements :: Ix i => a i e -> m Int
-- | Builds a new array, with every element initialised to the supplied
-- value.
newArray :: Ix i => (i,i) -> e -> m (a i e)
-- | Builds a new array, with every element initialised to an
-- undefined value. In a monadic context in which operations must
-- be deterministic (e.g. the ST monad), the array elements are
-- initialised to a fixed but undefined value, such as zero.
newArray_ :: Ix i => (i,i) -> m (a i e)
-- | Builds a new array, with every element initialised to an undefined
-- value.
unsafeNewArray_ :: Ix i => (i,i) -> m (a i e)
unsafeRead :: Ix i => a i e -> Int -> m e
unsafeWrite :: Ix i => a i e -> Int -> e -> m ()
{-# INLINE newArray #-}
-- The INLINE is crucial, because until we know at least which monad
-- we are in, the code below allocates like crazy. So inline it,
-- in the hope that the context will know the monad.
newArray (l,u) initialValue = do
let n = safeRangeSize (l,u)
marr <- unsafeNewArray_ (l,u)
sequence_ [unsafeWrite marr i initialValue | i <- [0 .. n - 1]]
return marr
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = newArray (l,u) arrEleBottom
{-# INLINE newArray_ #-}
newArray_ (l,u) = newArray (l,u) arrEleBottom
-- newArray takes an initialiser which all elements of
-- the newly created array are initialised to. unsafeNewArray_ takes
-- no initialiser, it is assumed that the array is initialised with
-- "undefined" values.
-- why not omit unsafeNewArray_? Because in the unboxed array
-- case we would like to omit the initialisation altogether if
-- possible. We can't do this for boxed arrays, because the
-- elements must all have valid values at all times in case of
-- garbage collection.
-- why not omit newArray? Because in the boxed case, we can omit the
-- default initialisation with undefined values if we *do* know the
-- initial value and it is constant for all elements.
instance MArray IOArray e IO where
{-# INLINE getBounds #-}
getBounds (IOArray marr) = stToIO $ getBounds marr
{-# INLINE getNumElements #-}
getNumElements (IOArray marr) = stToIO $ getNumElements marr
newArray = newIOArray
unsafeRead = unsafeReadIOArray
unsafeWrite = unsafeWriteIOArray
{-# INLINE newListArray #-}
-- | Constructs a mutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
newListArray :: (MArray a e m, Ix i) => (i,i) -> [e] -> m (a i e)
newListArray (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# INLINE readArray #-}
-- | Read an element from a mutable array
readArray :: (MArray a e m, Ix i) => a i e -> i -> m e
readArray marr i = do
(l,u) <- getBounds marr
n <- getNumElements marr
unsafeRead marr (safeIndex (l,u) n i)
{-# INLINE writeArray #-}
-- | Write an element in a mutable array
writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
writeArray marr i e = do
(l,u) <- getBounds marr
n <- getNumElements marr
unsafeWrite marr (safeIndex (l,u) n i) e
{-# INLINE getElems #-}
-- | Return a list of all the elements of a mutable array
getElems :: (MArray a e m, Ix i) => a i e -> m [e]
getElems marr = do
(_l, _u) <- getBounds marr
n <- getNumElements marr
sequence [unsafeRead marr i | i <- [0 .. n - 1]]
{-# INLINE getAssocs #-}
-- | Return a list of all the associations of a mutable array, in
-- index order.
getAssocs :: (MArray a e m, Ix i) => a i e -> m [(i, e)]
getAssocs marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
sequence [ do e <- unsafeRead marr (safeIndex (l,u) n i); return (i,e)
| i <- range (l,u)]
{-# INLINE mapArray #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the elements.
mapArray :: (MArray a e' m, MArray a e m, Ix i) => (e' -> e) -> a i e' -> m (a i e)
mapArray f marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
marr' <- newArray_ (l,u)
sequence_ [do e <- unsafeRead marr i
unsafeWrite marr' i (f e)
| i <- [0 .. n - 1]]
return marr'
{-# INLINE mapIndices #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the indices.
mapIndices :: (MArray a e m, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> m (a i e)
mapIndices (l',u') f marr = do
marr' <- newArray_ (l',u')
n' <- getNumElements marr'
sequence_ [do e <- readArray marr (f i')
unsafeWrite marr' (safeIndex (l',u') n' i') e
| i' <- range (l',u')]
return marr'
-----------------------------------------------------------------------------
-- Polymorphic non-strict mutable arrays (ST monad)
instance MArray (STArray s) e (ST s) where
{-# INLINE getBounds #-}
getBounds arr = return $! ArrST.boundsSTArray arr
{-# INLINE getNumElements #-}
getNumElements arr = return $! ArrST.numElementsSTArray arr
{-# INLINE newArray #-}
newArray = ArrST.newSTArray
{-# INLINE unsafeRead #-}
unsafeRead = ArrST.unsafeReadSTArray
{-# INLINE unsafeWrite #-}
unsafeWrite = ArrST.unsafeWriteSTArray
instance MArray (STArray s) e (Lazy.ST s) where
{-# INLINE getBounds #-}
getBounds arr = strictToLazyST (return $! ArrST.boundsSTArray arr)
{-# INLINE getNumElements #-}
getNumElements arr = strictToLazyST (return $! ArrST.numElementsSTArray arr)
{-# INLINE newArray #-}
newArray (l,u) e = strictToLazyST (ArrST.newSTArray (l,u) e)
{-# INLINE unsafeRead #-}
unsafeRead arr i = strictToLazyST (ArrST.unsafeReadSTArray arr i)
{-# INLINE unsafeWrite #-}
unsafeWrite arr i e = strictToLazyST (ArrST.unsafeWriteSTArray arr i e)
-----------------------------------------------------------------------------
-- Flat unboxed mutable arrays (ST monad)
-- | A mutable array with unboxed elements, that can be manipulated in
-- the 'ST' monad. The type arguments are as follows:
--
-- * @s@: the state variable argument for the 'ST' type
--
-- * @i@: the index type of the array (should be an instance of @Ix@)
--
-- * @e@: the element type of the array. Only certain element types
-- are supported.
--
-- An 'STUArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent boxed version ('STArray') with the same
-- element type. However, 'STUArray' is strict in its elements - so
-- don\'t use 'STUArray' if you require the non-strictness that
-- 'STArray' provides.
data STUArray s i e = STUArray !i !i !Int (MutableByteArray# s)
deriving Typeable
instance Eq (STUArray s i e) where
STUArray _ _ _ arr1# == STUArray _ _ _ arr2# =
#if __GLASGOW_HASKELL__ > 706
isTrue# (sameMutableByteArray# arr1# arr2#)
#else
sameMutableByteArray# arr1# arr2#
#endif
{-# INLINE unsafeNewArraySTUArray_ #-}
unsafeNewArraySTUArray_ :: Ix i
=> (i,i) -> (Int# -> Int#) -> ST s (STUArray s i e)
unsafeNewArraySTUArray_ (l,u) elemsToBytes
= case rangeSize (l,u) of
n@(I# n#) ->
ST $ \s1# ->
case newByteArray# (elemsToBytes n#) s1# of
(# s2#, marr# #) ->
(# s2#, STUArray l u n marr# #)
instance MArray (STUArray s) Bool (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE newArray #-}
newArray (l,u) initialValue = ST $ \s1# ->
case safeRangeSize (l,u) of { n@(I# n#) ->
case newByteArray# (bOOL_SCALE n#) s1# of { (# s2#, marr# #) ->
case bOOL_WORD_SCALE n# of { n'# ->
#if __GLASGOW_HASKELL__ > 706
let loop i# s3# | isTrue# (i# ==# n'#) = s3#
#else
let loop i# s3# | i# ==# n'# = s3#
#endif
| otherwise =
case writeWordArray# marr# i# e# s3# of { s4# ->
loop (i# +# 1#) s4# } in
case loop 0# s2# of { s3# ->
(# s3#, STUArray l u n marr# #) }}}}
where
!(W# e#) = if initialValue then maxBound else 0
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) bOOL_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds False
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWordArray# marr# (bOOL_INDEX i#) s1# of { (# s2#, e# #) ->
#if __GLASGOW_HASKELL__ > 706
(# s2#, isTrue# ((e# `and#` bOOL_BIT i#) `neWord#` int2Word# 0#) :: Bool #) }
#else
(# s2#, (e# `and#` bOOL_BIT i# `neWord#` int2Word# 0#) :: Bool #) }
#endif
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) e = ST $ \s1# ->
case bOOL_INDEX i# of { j# ->
case readWordArray# marr# j# s1# of { (# s2#, old# #) ->
case if e then old# `or#` bOOL_BIT i#
else old# `and#` bOOL_NOT_BIT i# of { e# ->
case writeWordArray# marr# j# e# s2# of { s3# ->
(# s3#, () #) }}}}
instance MArray (STUArray s) Char (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds (chr 0)
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWideCharArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, C# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (C# e#) = ST $ \s1# ->
case writeWideCharArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readIntArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I# e#) = ST $ \s1# ->
case writeIntArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWordArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W# e#) = ST $ \s1# ->
case writeWordArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (Ptr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds nullPtr
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readAddrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, Ptr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (Ptr e#) = ST $ \s1# ->
case writeAddrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (FunPtr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds nullFunPtr
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readAddrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, FunPtr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (FunPtr e#) = ST $ \s1# ->
case writeAddrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Float (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) fLOAT_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readFloatArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, F# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (F# e#) = ST $ \s1# ->
case writeFloatArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Double (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) dOUBLE_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readDoubleArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, D# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (D# e#) = ST $ \s1# ->
case writeDoubleArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (StablePtr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds (castPtrToStablePtr nullPtr)
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readStablePtrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2# , StablePtr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (StablePtr e#) = ST $ \s1# ->
case writeStablePtrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int8 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (\x -> x)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt8Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I8# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I8# e#) = ST $ \s1# ->
case writeInt8Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int16 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 2#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt16Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I16# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I16# e#) = ST $ \s1# ->
case writeInt16Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int32 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt32Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I32# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I32# e#) = ST $ \s1# ->
case writeInt32Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int64 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 8#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt64Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I64# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I64# e#) = ST $ \s1# ->
case writeInt64Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word8 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (\x -> x)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord8Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W8# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W8# e#) = ST $ \s1# ->
case writeWord8Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word16 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 2#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord16Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W16# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W16# e#) = ST $ \s1# ->
case writeWord16Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word32 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord32Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W32# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W32# e#) = ST $ \s1# ->
case writeWord32Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word64 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 8#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord64Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W64# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W64# e#) = ST $ \s1# ->
case writeWord64Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
-----------------------------------------------------------------------------
-- Translation between elements and bytes
bOOL_SCALE, bOOL_WORD_SCALE,
wORD_SCALE, dOUBLE_SCALE, fLOAT_SCALE :: Int# -> Int#
bOOL_SCALE n# = (n# +# last#) `uncheckedIShiftRA#` 3#
where !(I# last#) = SIZEOF_HSWORD * 8 - 1
bOOL_WORD_SCALE n# = bOOL_INDEX (n# +# last#)
where !(I# last#) = SIZEOF_HSWORD * 8 - 1
wORD_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSWORD
dOUBLE_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSDOUBLE
fLOAT_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSFLOAT
bOOL_INDEX :: Int# -> Int#
#if SIZEOF_HSWORD == 4
bOOL_INDEX i# = i# `uncheckedIShiftRA#` 5#
#elif SIZEOF_HSWORD == 8
bOOL_INDEX i# = i# `uncheckedIShiftRA#` 6#
#endif
bOOL_BIT, bOOL_NOT_BIT :: Int# -> Word#
bOOL_BIT n# = int2Word# 1# `uncheckedShiftL#` (word2Int# (int2Word# n# `and#` mask#))
where !(W# mask#) = SIZEOF_HSWORD * 8 - 1
bOOL_NOT_BIT n# = bOOL_BIT n# `xor#` mb#
where !(W# mb#) = maxBound
-----------------------------------------------------------------------------
-- Freezing
-- | Converts a mutable array (any instance of 'MArray') to an
-- immutable array (any instance of 'IArray') by taking a complete
-- copy of it.
freeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
{-# NOINLINE [1] freeze #-}
freeze marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
es <- mapM (unsafeRead marr) [0 .. n - 1]
-- The old array and index might not be well-behaved, so we need to
-- use the safe array creation function here.
return (listArray (l,u) es)
freezeSTUArray :: Ix i => STUArray s i e -> ST s (UArray i e)
freezeSTUArray (STUArray l u n marr#) = ST $ \s1# ->
case sizeofMutableByteArray# marr# of { n# ->
case newByteArray# n# s1# of { (# s2#, marr'# #) ->
case memcpy_freeze marr'# marr# (fromIntegral (I# n#)) of { IO m ->
case unsafeCoerce# m s2# of { (# s3#, _ #) ->
case unsafeFreezeByteArray# marr'# s3# of { (# s4#, arr# #) ->
(# s4#, UArray l u n arr# #) }}}}}
foreign import ccall unsafe "memcpy"
memcpy_freeze :: MutableByteArray# s -> MutableByteArray# s -> CSize
-> IO (Ptr a)
{-# RULES
"freeze/STArray" freeze = ArrST.freezeSTArray
"freeze/STUArray" freeze = freezeSTUArray
#-}
-- In-place conversion of mutable arrays to immutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- freeze it (and, subsequently mutate it, I suspect).
{- |
Converts an mutable array into an immutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is safe to use, therefore, if
the mutable version is never modified after the freeze operation.
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeFreeze'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.IO.IOUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.ST.STUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.IO.IOArray' -> 'Data.Array.Array'
* 'Data.Array.ST.STArray' -> 'Data.Array.Array'
-}
{-# INLINE [1] unsafeFreeze #-}
unsafeFreeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
unsafeFreeze = freeze
{-# RULES
"unsafeFreeze/STArray" unsafeFreeze = ArrST.unsafeFreezeSTArray
"unsafeFreeze/STUArray" unsafeFreeze = unsafeFreezeSTUArray
#-}
-----------------------------------------------------------------------------
-- Thawing
-- | Converts an immutable array (any instance of 'IArray') into a
-- mutable array (any instance of 'MArray') by taking a complete copy
-- of it.
thaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
{-# NOINLINE [1] thaw #-}
thaw arr = case bounds arr of
(l,u) -> do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
sequence_ [ unsafeWrite marr i (unsafeAt arr i)
| i <- [0 .. n - 1]]
return marr
thawSTUArray :: Ix i => UArray i e -> ST s (STUArray s i e)
thawSTUArray (UArray l u n arr#) = ST $ \s1# ->
case sizeofByteArray# arr# of { n# ->
case newByteArray# n# s1# of { (# s2#, marr# #) ->
case memcpy_thaw marr# arr# (fromIntegral (I# n#)) of { IO m ->
case unsafeCoerce# m s2# of { (# s3#, _ #) ->
(# s3#, STUArray l u n marr# #) }}}}
foreign import ccall unsafe "memcpy"
memcpy_thaw :: MutableByteArray# s -> ByteArray# -> CSize
-> IO (Ptr a)
{-# RULES
"thaw/STArray" thaw = ArrST.thawSTArray
"thaw/STUArray" thaw = thawSTUArray
#-}
-- In-place conversion of immutable arrays to mutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- thaw it (and, subsequently mutate it, I suspect).
{- |
Converts an immutable array into a mutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is only safe to use,
therefore, if the immutable array is never referenced again in this
thread, and there is no possibility that it can be also referenced
in another thread. If you use an unsafeThaw/write/unsafeFreeze
sequence in a multi-threaded setting, then you must ensure that
this sequence is atomic with respect to other threads, or a garbage
collector crash may result (because the write may be writing to a
frozen array).
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeThaw'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.IO.IOUArray'
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.ST.STUArray'
* 'Data.Array.Array' -> 'Data.Array.IO.IOArray'
* 'Data.Array.Array' -> 'Data.Array.ST.STArray'
-}
{-# INLINE [1] unsafeThaw #-}
unsafeThaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
unsafeThaw = thaw
{-# INLINE unsafeThawSTUArray #-}
unsafeThawSTUArray :: Ix i => UArray i e -> ST s (STUArray s i e)
unsafeThawSTUArray (UArray l u n marr#) =
return (STUArray l u n (unsafeCoerce# marr#))
{-# RULES
"unsafeThaw/STArray" unsafeThaw = ArrST.unsafeThawSTArray
"unsafeThaw/STUArray" unsafeThaw = unsafeThawSTUArray
#-}
{-# INLINE unsafeThawIOArray #-}
unsafeThawIOArray :: Ix ix => Arr.Array ix e -> IO (IOArray ix e)
unsafeThawIOArray arr = stToIO $ do
marr <- ArrST.unsafeThawSTArray arr
return (IOArray marr)
{-# RULES
"unsafeThaw/IOArray" unsafeThaw = unsafeThawIOArray
#-}
thawIOArray :: Ix ix => Arr.Array ix e -> IO (IOArray ix e)
thawIOArray arr = stToIO $ do
marr <- ArrST.thawSTArray arr
return (IOArray marr)
{-# RULES
"thaw/IOArray" thaw = thawIOArray
#-}
freezeIOArray :: Ix ix => IOArray ix e -> IO (Arr.Array ix e)
freezeIOArray (IOArray marr) = stToIO (ArrST.freezeSTArray marr)
{-# RULES
"freeze/IOArray" freeze = freezeIOArray
#-}
{-# INLINE unsafeFreezeIOArray #-}
unsafeFreezeIOArray :: Ix ix => IOArray ix e -> IO (Arr.Array ix e)
unsafeFreezeIOArray (IOArray marr) = stToIO (ArrST.unsafeFreezeSTArray marr)
{-# RULES
"unsafeFreeze/IOArray" unsafeFreeze = unsafeFreezeIOArray
#-}
-- | Casts an 'STUArray' with one element type into one with a
-- different element type. All the elements of the resulting array
-- are undefined (unless you know what you\'re doing...).
castSTUArray :: STUArray s ix a -> ST s (STUArray s ix b)
castSTUArray (STUArray l u n marr#) = return (STUArray l u n marr#)
| jwiegley/ghc-release | libraries/array/Data/Array/Base.hs | gpl-3.0 | 63,941 | 0 | 27 | 15,580 | 16,661 | 8,752 | 7,909 | -1 | -1 |
{-# language PatternSignatures #-}
{-# language DeriveDataTypeable #-}
module Call where
import Spieler
import State
import Control.Concurrent.STM
import Control.Exception
import qualified System.Timeout
import Network.XmlRpc.Client
import Control.Monad ( void )
import Data.Typeable
import qualified Data.Set as S
data ProtocolE = ProtocolE Spieler deriving ( Show, Typeable )
instance Exception ProtocolE
data TimeoutE = TimeoutE deriving ( Show, Typeable )
instance Exception TimeoutE
second = 10^ 6
timeout = 10 * second
timed :: Int -> IO a -> IO a
timed to action = do
res <- System.Timeout.timeout to action
case res of
Nothing -> throwIO TimeoutE
Just res -> return res
logging = False
logged0 server s cmd = do
let Callback c = callback s
message server $ RPC_Call s cmd
handle ( \ ( e :: SomeException ) -> do
message server $ RPC_Error $ show e
add_offender server s
throwIO $ ProtocolE s )
$ timed timeout
$ remote c cmd
logged1 server s cmd arg = do
message server $ RPC_Call s cmd
let Callback c = callback s
handle ( \ ( e :: SomeException ) -> do
message server $ RPC_Error $ show e
add_offender server s
throwIO $ ProtocolE s )
$ timed timeout
$ remote c cmd arg
add_offender server s = atomically $ do
os <- readTVar $ offenders server
writeTVar ( offenders server ) $ S.insert s os
ignore_errors server action =
handle ( \ ( SomeException e ) -> return () ) ( void action )
| jwaldmann/mex | src/Call.hs | gpl-3.0 | 1,617 | 0 | 16 | 471 | 530 | 257 | 273 | 48 | 2 |
{-# LANGUAGE RankNTypes #-}
module StationCrawler.Workers (generalWorker) where
import StationCrawler.Types
import StationCrawler.IdManipulations
import StationCrawler.Queuers (queueStations, queueTrains)
import Types
import Fetchers (getRequest)
import TrainParsers (parseTrain)
import StationParsers (parseStationPage)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Data.Maybe
import Network.HTTP.Conduit
import Control.Concurrent.STM
import Control.Monad.State
import qualified Control.Exception as X
import qualified Debug.Trace as DT
import qualified Data.ByteString.Lazy as BL
import Text.XML.Cursor (fromDocument, attribute)
import Text.HTML.DOM (parseLBS)
performReq request manager = httpLbs request manager `X.catch` (handleConnError request manager)
handleConnError :: Request -> Manager -> X.SomeException -> IO (Response BL.ByteString)
handleConnError request manager _ = DT.trace "exception" $ performReq request manager
makeReq manager request = do
response <- performReq request manager
return . fromDocument . parseLBS . responseBody $ response
getTrainIds :: Maybe Station -> IO [Integer]
getTrainIds wrappedStation = case wrappedStation of
Nothing -> return []
Just station -> return $ map connId (connections station)
trainWorker :: Manager -> TVar StationState -> Integer -> IO ()
trainWorker manager stateVar trainId = do
-- Fetch and parse the page
trainResp <- getRequest TrainRequest trainId >>= makeReq manager
let stationIds = parseTrain trainResp
-- Update the ids
atomically $ updateIds stateVar queueStations stationIds
stationWorker :: Manager -> TVar StationState -> TChan Station -> Integer -> IO ()
stationWorker manager stateVar results stationId = do
-- Fetch the page
stationResp <- getRequest StationRequest stationId >>= makeReq manager
-- Parse the page
let parsedStation = parseStationPage stationId stationResp
-- Extract train ids from the parsed page
trainIds <- getTrainIds parsedStation
-- Update train ids left to fetch
atomically $ updateIds stateVar queueTrains trainIds
-- Write the results into results channel
when (isJust parsedStation) $ atomically $ writeTChan results (fromJust $! parsedStation)
-- A worker that can either crawl a station or a train, depending on need
generalWorker :: Manager ->
TVar StationState ->
TChan Station ->
TVar Int ->
Int ->
IO ()
generalWorker manager stateVar results waitingCount workerCount = do
maybeId <- getId stateVar waitingCount workerCount
case maybeId of
Just (updateType, id) -> case updateType of
TrainUpdate -> trainWorker manager stateVar id
StationUpdate -> stationWorker manager stateVar results id
Nothing -> return ()
when (isJust maybeId) $ generalWorker manager stateVar results waitingCount workerCount
| mkawalec/infopassenger-crawler | src/StationCrawler/Workers.hs | gpl-3.0 | 2,810 | 0 | 13 | 447 | 726 | 371 | 355 | 55 | 3 |
{-# LANGUAGE DeriveGeneric #-}
module Format
( FromJSON
, dec
, EncodeJSON(enc)
, Conf(..)
, initConf
) where
import Data.Text
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict, toStrict)
import GHC.Generics (Generic)
import Data.Aeson
import Data.Aeson.Encode.Pretty
dec :: FromJSON a => ByteString -> Either String a
dec = eitherDecode . fromStrict
encBase :: ToJSON a => [Text] -> a -> ByteString
encBase keys = (toStrict .) $ encodePretty' $ defConfig
{ confIndent = (Spaces 4)
, confCompare = keyOrder keys
}
-- a separate class for explicit ordering of JSON fields
class EncodeJSON a where
enc :: a -> ByteString
data Conf = Conf
{ owner :: !Text
, repo :: !Text
, tokenPath :: !Text
}
deriving (Show, Generic)
instance FromJSON Conf
instance ToJSON Conf
instance EncodeJSON Conf where
enc = encBase ["owner", "repo", "tokenPath"]
initConf :: Conf
initConf = Conf
"owner"
"repo"
"/path/to/tokenfile"
| kinoru/wild | src/Format.hs | agpl-3.0 | 1,017 | 0 | 9 | 228 | 293 | 166 | 127 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Blockchain as BC (Block, BlockData, Blockchain,
addBlock, generateNextBlock,
genesisBlock, isValidChain)
import BlockchainState (initialBlockchainState)
import CommandDispatcher
import Consensus
import Http (commandReceiver)
import Logging (configureLogging)
import TransportUDP (startNodeComm)
import Control.Concurrent (MVar, newEmptyMVar, putMVar, takeMVar,
withMVar)
import Control.Lens (element, (^?))
import Data.Aeson (encode)
import Data.ByteString.Lazy (toStrict)
import Network.Socket (HostName, PortNumber)
import System.Environment (getArgs)
defaultHost :: HostName
defaultHost = "224.0.0.99"
defaultPort :: PortNumber
defaultPort = 9160
main :: IO ()
main = do
xs <- getArgs
case xs of
[] -> doIt defaultPort defaultHost (read (show defaultPort) :: PortNumber)
[httpPort,h,p] -> doIt (read httpPort :: PortNumber) h (read p :: PortNumber)
xss -> error (show xss)
doIt :: PortNumber -> HostName -> PortNumber -> IO ()
doIt httpPort host port = do
configureLogging
commandDispatcher <- initializeCommandDispatcher
startNodeComm commandDispatcher host port
commandReceiver commandDispatcher "0.0.0.0" httpPort
initializeCommandDispatcher :: IO CommandDispatcher
initializeCommandDispatcher = do
blockchainState <- initialBlockchainState
mv <- newEmptyMVar
return (CommandDispatcher
Consensus.handleConsensusMessage
(getMsgsToSendToConsensusNodes mv)
(sendToConsensusNodes mv)
(Main.listBlocks blockchainState)
(Main.addBlock mv)
(Main.isValid blockchainState))
getMsgsToSendToConsensusNodes :: MVar BlockData -> IO BlockData
getMsgsToSendToConsensusNodes = takeMVar
sendToConsensusNodes :: MVar BlockData -> BlockData -> IO ()
sendToConsensusNodes = putMVar
listBlocks :: MVar Blockchain -> Maybe Int -> IO (Maybe Blockchain)
listBlocks blockchain i =
case i of
-- return all entries
Nothing -> withMVar blockchain $ return . Just
-- return the single entry (as a one-element list)
Just i' -> withMVar blockchain $ \bc -> case bc ^? element i' of
Nothing -> return Nothing
Just el -> return (Just [el])
addBlock :: MVar BlockData -> BlockData -> IO Block
addBlock sendToConsensusNodesMV blockdata = do
let newBlock = generateNextBlock genesisBlock "fake timestamp" blockdata
-- send block to verifiers
putMVar sendToConsensusNodesMV (toStrict (encode (AppendEntry newBlock)))
-- return block to caller
return newBlock
isValid :: MVar Blockchain -> Block -> IO (Maybe String)
isValid blockchain blk =
withMVar blockchain $ \bc -> return $ isValidChain (BC.addBlock blk bc)
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/blockchain/blockchain-framework-DELETE/app/Main.hs | unlicense | 3,178 | 0 | 16 | 950 | 749 | 389 | 360 | 65 | 3 |
-- | Parsers for first-order logic and other important structures (e.g. Markov
-- logic networks).
module Akarui.Parser.Term (
parseFunForm,
parseTerm
) where
import Data.Char (isLower)
import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.String (Parser)
import Akarui.Parser.Core
import Akarui.FOL.Term
-- | Parse function-like objects of the form Name(args0, args1, args2, ...).
parseFunForm :: Parser (T.Text, [Term])
parseFunForm = do
n <- identifier
reservedOp "("
ts <- commaSep parseTerm
reservedOp ")"
return (T.pack n, ts)
-- | Parse basic terms.
parseTerm, parseVarCon, parseFunction :: Parser Term
parseTerm = try parseFunction <|> parseVarCon
parseFunction = do
args <- parseFunForm
return $ uncurry Function args
parseVarCon = do
n <- identifier
return $ (if isLower $ head n then Variable else Constant) (T.pack n)
| PhDP/Manticore | Akarui/Parser/Term.hs | apache-2.0 | 873 | 0 | 12 | 148 | 231 | 126 | 105 | 24 | 2 |
module DBus.Introspection
( module X
) where
import DBus.Introspection.Types as X
import DBus.Introspection.Parse as X
import DBus.Introspection.Render as X
| rblaze/haskell-dbus | lib/DBus/Introspection.hs | apache-2.0 | 166 | 0 | 4 | 28 | 36 | 26 | 10 | 5 | 0 |
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE Rank2Types #-}
module Language.Drasil.Code.Imperative.Import (codeType,
publicFunc, privateMethod, publicInOutFunc, privateInOutMethod,
genConstructor, mkVar, mkVal, convExpr, genCalcBlock, CalcType(..), genModDef,
genModFuncs, readData, renderC
) where
import Language.Drasil hiding (int, log, ln, exp,
sin, cos, tan, csc, sec, cot, arcsin, arccos, arctan)
import Database.Drasil (symbResolve)
import Language.Drasil.Code.Imperative.Comments (paramComment, returnComment)
import Language.Drasil.Code.Imperative.ConceptMatch (conceptToGOOL)
import Language.Drasil.Code.Imperative.GenerateGOOL (auxClass, fApp, ctorCall,
genModuleWithImports, mkParam, primaryClass)
import Language.Drasil.Code.Imperative.Helpers (getUpperBound, liftS, lookupC)
import Language.Drasil.Code.Imperative.Logging (maybeLog, logBody)
import Language.Drasil.Code.Imperative.Parameters (getCalcParams)
import Language.Drasil.Code.Imperative.DrasilState (DrasilState(..))
import Language.Drasil.Chunk.Code (CodeIdea(codeName), codevar, quantvar,
quantfunc)
import Language.Drasil.Chunk.CodeDefinition (CodeDefinition, codeEquat)
import Language.Drasil.Code.CodeQuantityDicts (inFileName, inParams, consts)
import Language.Drasil.CodeSpec (CodeSpec(..), CodeSystInfo(..), Comments(..),
ConstantRepr(..), ConstantStructure(..), Structure(..))
import Language.Drasil.Code.DataDesc (DataItem, LinePattern(Repeat, Straight),
Data(Line, Lines, JunkData, Singleton), DataDesc, isLine, isLines, getInputs,
getPatternInputs)
import Language.Drasil.Mod (Func(..), FuncData(..), FuncDef(..), FuncStmt(..),
Mod(..), Name, fstdecl)
import qualified Language.Drasil.Mod as M (Class(..))
import GOOL.Drasil (Label, ProgramSym, FileSym(..), PermanenceSym(..),
BodySym(..), BlockSym(..), TypeSym(..), VariableSym(..), ValueSym(..),
NumericExpression(..), BooleanExpression(..), ValueExpression(..),
objMethodCallMixedArgs, FunctionSym(..), SelectorFunction(..),
StatementSym(..), ControlStatementSym(..), ScopeSym(..), ParameterSym(..),
MethodSym(..), StateVarSym(..), ClassSym(..), nonInitConstructor, convType,
CodeType(..), FS, CS, MS, VS, onStateValue)
import qualified GOOL.Drasil as C (CodeType(List))
import Prelude hiding (sin, cos, tan, log, exp)
import Data.List ((\\), intersect)
import qualified Data.Map as Map (lookup)
import Data.Maybe (maybe)
import Control.Applicative ((<$>))
import Control.Monad (liftM2,liftM3)
import Control.Monad.Reader (Reader, ask)
import Control.Lens ((^.))
codeType :: (HasSpace c) => c -> Reader DrasilState CodeType
codeType c = do
g <- ask
return $ spaceMatches g (c ^. typ)
value :: (ProgramSym repr) => UID -> String -> VS (repr (Type repr)) ->
Reader DrasilState (VS (repr (Value repr)))
value u s t = do
g <- ask
let cs = codeSpec g
mm = constMap cs
cm = concMatches g
maybeInline Inline m = Just m
maybeInline _ _ = Nothing
maybe (maybe (do { v <- variable s t; return $ valueOf v })
(convExpr . codeEquat) (Map.lookup u mm >>= maybeInline (conStruct g)))
(return . conceptToGOOL) (Map.lookup u cm)
variable :: (ProgramSym repr) => String -> VS (repr (Type repr)) ->
Reader DrasilState (VS (repr (Variable repr)))
variable s t = do
g <- ask
let cs = csi $ codeSpec g
defFunc Var = var
defFunc Const = staticVar
if s `elem` map codeName (inputs cs)
then inputVariable (inStruct g) Var (var s t)
else if s `elem` map codeName (constants $ csi $ codeSpec g)
then constVariable (conStruct g) (conRepr g) ((defFunc $ conRepr g) s t)
else return $ var s t
inputVariable :: (ProgramSym repr) => Structure -> ConstantRepr ->
VS (repr (Variable repr)) -> Reader DrasilState (VS (repr (Variable repr)))
inputVariable Unbundled _ v = return v
inputVariable Bundled Var v = do
g <- ask
let inClsName = "InputParameters"
ip <- mkVar (codevar inParams)
return $ if currentClass g == inClsName then objVarSelf v else ip $-> v
inputVariable Bundled Const v = do
ip <- mkVar (codevar inParams)
classVariable ip v
constVariable :: (ProgramSym repr) => ConstantStructure -> ConstantRepr ->
VS (repr (Variable repr)) -> Reader DrasilState (VS (repr (Variable repr)))
constVariable (Store Bundled) Var v = do
cs <- mkVar (codevar consts)
return $ cs $-> v
constVariable (Store Bundled) Const v = do
cs <- mkVar (codevar consts)
classVariable cs v
constVariable WithInputs cr v = do
g <- ask
inputVariable (inStruct g) cr v
constVariable _ _ v = return v
classVariable :: (ProgramSym repr) => VS (repr (Variable repr)) ->
VS (repr (Variable repr)) -> Reader DrasilState (VS (repr (Variable repr)))
classVariable c v = do
g <- ask
let checkCurrent m = if currentModule g == m then classVar else extClassVar
return $ v >>= (\v' -> maybe (error $ "Variable " ++ variableName v' ++
" missing from export map") checkCurrent (Map.lookup (variableName v')
(eMap $ codeSpec g)) (onStateValue variableType c) v)
mkVal :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) => c ->
Reader DrasilState (VS (repr (Value repr)))
mkVal v = do
t <- codeType v
value (v ^. uid) (codeName v) (convType t)
mkVar :: (ProgramSym repr, HasSpace c, CodeIdea c) => c ->
Reader DrasilState (VS (repr (Variable repr)))
mkVar v = do
t <- codeType v
variable (codeName v) (convType t)
publicFunc :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) =>
Label -> VS (repr (Type repr)) -> String -> [c] -> Maybe String ->
[MS (repr (Block repr))] -> Reader DrasilState (MS (repr (Method repr)))
publicFunc n t = genMethod (function n public static t) n
privateMethod :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) =>
Label -> VS (repr (Type repr)) -> String -> [c] -> Maybe String ->
[MS (repr (Block repr))] -> Reader DrasilState (MS (repr (Method repr)))
privateMethod n t = genMethod (method n private dynamic t) n
publicInOutFunc :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c, Eq c)
=> Label -> String -> [c] -> [c] -> [MS (repr (Block repr))] ->
Reader DrasilState (MS (repr (Method repr)))
publicInOutFunc n = genInOutFunc (inOutFunc n) (docInOutFunc n) public static n
privateInOutMethod :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c,
Eq c) => Label -> String -> [c] -> [c] -> [MS (repr (Block repr))]
-> Reader DrasilState (MS (repr (Method repr)))
privateInOutMethod n = genInOutFunc (inOutMethod n) (docInOutMethod n)
private dynamic n
genConstructor :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) =>
Label -> String -> [c] -> [MS (repr (Block repr))] ->
Reader DrasilState (MS (repr (Method repr)))
genConstructor n desc p = genMethod nonInitConstructor n desc p Nothing
genInitConstructor :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) =>
Label -> String -> [c] ->
[(VS (repr (Variable repr)), VS (repr (Value repr)))] ->
[MS (repr (Block repr))] -> Reader DrasilState (MS (repr (Method repr)))
genInitConstructor n desc p is = genMethod (`constructor` is) n desc p
Nothing
genMethod :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c) =>
([MS (repr (Parameter repr))] -> MS (repr (Body repr)) ->
MS (repr (Method repr))) -> Label -> String -> [c] -> Maybe String ->
[MS (repr (Block repr))] -> Reader DrasilState (MS (repr (Method repr)))
genMethod f n desc p r b = do
g <- ask
vars <- mapM mkVar p
bod <- logBody n vars b
let ps = map mkParam vars
fn = f ps bod
pComms <- mapM (paramComment . (^. uid)) p
return $ if CommentFunc `elem` commented g
then docFunc desc pComms r fn else fn
genInOutFunc :: (ProgramSym repr, HasUID c, HasSpace c, CodeIdea c, Eq c) =>
(repr (Scope repr) -> repr (Permanence repr) -> [VS (repr (Variable repr))]
-> [VS (repr (Variable repr))] -> [VS (repr (Variable repr))] ->
MS (repr (Body repr)) -> MS (repr (Method repr))) ->
(repr (Scope repr) -> repr (Permanence repr) -> String ->
[(String, VS (repr (Variable repr)))] ->
[(String, VS (repr (Variable repr)))] ->
[(String, VS (repr (Variable repr)))] -> MS (repr (Body repr)) ->
MS (repr (Method repr))) ->
repr (Scope repr) -> repr (Permanence repr) -> Label -> String -> [c] ->
[c] -> [MS (repr (Block repr))] ->
Reader DrasilState (MS (repr (Method repr)))
genInOutFunc f docf s pr n desc ins' outs' b = do
g <- ask
let ins = ins' \\ outs'
outs = outs' \\ ins'
both = ins' `intersect` outs'
inVs <- mapM mkVar ins
outVs <- mapM mkVar outs
bothVs <- mapM mkVar both
bod <- logBody n (bothVs ++ inVs) b
pComms <- mapM (paramComment . (^. uid)) ins
oComms <- mapM (paramComment . (^. uid)) outs
bComms <- mapM (paramComment . (^. uid)) both
return $ if CommentFunc `elem` commented g
then docf s pr desc (zip pComms inVs) (zip oComms outVs) (zip
bComms bothVs) bod else f s pr inVs outVs bothVs bod
convExpr :: (ProgramSym repr) => Expr -> Reader DrasilState (VS (repr (Value repr)))
convExpr (Dbl d) = do
g <- ask
let sm = spaceMatches g
getLiteral Double = litDouble d
getLiteral Float = litFloat (realToFrac d)
getLiteral _ = error "convExpr: Real space matched to invalid CodeType; should be Double or Float"
return $ getLiteral (sm Real)
convExpr (Int i) = return $ litInt i
convExpr (Str s) = return $ litString s
convExpr (Perc a b) = do
g <- ask
let sm = spaceMatches g
getLiteral Double = litDouble
getLiteral Float = litFloat . realToFrac
getLiteral _ = error "convExpr: Rational space matched to invalid CodeType; should be Double or Float"
return $ getLiteral (sm Rational) (fromIntegral a / (10 ** fromIntegral b))
convExpr (AssocA Add l) = foldl1 (#+) <$> mapM convExpr l
convExpr (AssocA Mul l) = foldl1 (#*) <$> mapM convExpr l
convExpr (AssocB And l) = foldl1 (?&&) <$> mapM convExpr l
convExpr (AssocB Or l) = foldl1 (?||) <$> mapM convExpr l
convExpr Deriv{} = return $ litString "**convExpr :: Deriv unimplemented**"
convExpr (C c) = do
g <- ask
let v = quantvar (lookupC g c)
mkVal v
convExpr (FCall c x ns) = convCall c x ns fApp
convExpr (New c x ns) = convCall c x ns (\m _ -> ctorCall m)
convExpr (Message a m x ns) = do
g <- ask
let info = sysinfodb $ csi $ codeSpec g
objCd = quantvar (symbResolve info a)
o <- mkVal objCd
convCall m x ns (\_ n t ps nas -> return (objMethodCallMixedArgs t o n ps nas))
convExpr (UnaryOp o u) = fmap (unop o) (convExpr u)
convExpr (BinaryOp Frac (Int a) (Int b)) = do -- hack to deal with integer division
g <- ask
let sm = spaceMatches g
getLiteral Double = litDouble (fromIntegral a) #/ litDouble (fromIntegral b)
getLiteral Float = litFloat (fromIntegral a) #/ litFloat (fromIntegral b)
getLiteral _ = error "convExpr: Rational space matched to invalid CodeType; should be Double or Float"
return $ getLiteral (sm Rational)
convExpr (BinaryOp o a b) = liftM2 (bfunc o) (convExpr a) (convExpr b)
convExpr (Case c l) = doit l -- FIXME this is sub-optimal
where
doit [] = error "should never happen"
doit [(e,_)] = convExpr e -- should always be the else clause
doit ((e,cond):xs) = liftM3 inlineIf (convExpr cond) (convExpr e)
(convExpr (Case c xs))
convExpr Matrix{} = error "convExpr: Matrix"
convExpr Operator{} = error "convExpr: Operator"
convExpr IsIn{} = error "convExpr: IsIn"
convExpr (RealI c ri) = do
g <- ask
convExpr $ renderRealInt (lookupC g c) ri
convCall :: (ProgramSym repr) => UID -> [Expr] -> [(UID, Expr)] ->
(String -> String -> VS (repr (Type repr)) -> [VS (repr (Value repr))] ->
[(VS (repr (Variable repr)), VS (repr (Value repr)))] ->
Reader DrasilState (VS (repr (Value repr)))) ->
Reader DrasilState (VS (repr (Value repr)))
convCall c x ns f = do
g <- ask
let info = sysinfodb $ csi $ codeSpec g
mem = eMap $ codeSpec g
funcCd = quantfunc (symbResolve info c)
funcNm = codeName funcCd
funcTp <- codeType funcCd
args <- mapM convExpr x
nms <- mapM (mkVar . quantfunc . symbResolve info . fst) ns
nargs <- mapM (convExpr . snd) ns
maybe (error $ "Call to non-existent function " ++ funcNm) (\m -> f m funcNm
(convType funcTp) args (zip nms nargs)) (Map.lookup funcNm mem)
renderC :: (HasUID c, HasSymbol c) => c -> Constraint -> Expr
renderC s (Range _ rr) = renderRealInt s rr
renderC s (EnumeratedReal _ rr) = IsIn (sy s) (DiscreteD rr)
renderC s (EnumeratedStr _ rr) = IsIn (sy s) (DiscreteS rr)
renderRealInt :: (HasUID c, HasSymbol c) => c -> RealInterval Expr Expr -> Expr
renderRealInt s (Bounded (Inc,a) (Inc,b)) = (a $<= sy s) $&& (sy s $<= b)
renderRealInt s (Bounded (Inc,a) (Exc,b)) = (a $<= sy s) $&& (sy s $< b)
renderRealInt s (Bounded (Exc,a) (Inc,b)) = (a $< sy s) $&& (sy s $<= b)
renderRealInt s (Bounded (Exc,a) (Exc,b)) = (a $< sy s) $&& (sy s $< b)
renderRealInt s (UpTo (Inc,a)) = sy s $<= a
renderRealInt s (UpTo (Exc,a)) = sy s $< a
renderRealInt s (UpFrom (Inc,a)) = sy s $>= a
renderRealInt s (UpFrom (Exc,a)) = sy s $> a
unop :: (ProgramSym repr) => UFunc -> (VS (repr (Value repr)) ->
VS (repr (Value repr)))
unop Sqrt = (#/^)
unop Log = log
unop Ln = ln
unop Abs = (#|)
unop Exp = exp
unop Sin = sin
unop Cos = cos
unop Tan = tan
unop Csc = csc
unop Sec = sec
unop Cot = cot
unop Arcsin = arcsin
unop Arccos = arccos
unop Arctan = arctan
unop Dim = listSize
unop Norm = error "unop: Norm not implemented"
unop Not = (?!)
unop Neg = (#~)
bfunc :: (ProgramSym repr) => BinOp -> (VS (repr (Value repr)) ->
VS (repr (Value repr)) -> VS (repr (Value repr)))
bfunc Eq = (?==)
bfunc NEq = (?!=)
bfunc Gt = (?>)
bfunc Lt = (?<)
bfunc LEq = (?<=)
bfunc GEq = (?>=)
bfunc Cross = error "bfunc: Cross not implemented"
bfunc Pow = (#^)
bfunc Subt = (#-)
bfunc Impl = error "convExpr :=>"
bfunc Iff = error "convExpr :<=>"
bfunc Dot = error "convExpr DotProduct"
bfunc Frac = (#/)
bfunc Index = listAccess
------- CALC ----------
genCalcFunc :: (ProgramSym repr) => CodeDefinition ->
Reader DrasilState (MS (repr (Method repr)))
genCalcFunc cdef = do
parms <- getCalcParams cdef
let nm = codeName cdef
tp <- codeType cdef
blck <- genCalcBlock CalcReturn cdef (codeEquat cdef)
desc <- returnComment $ cdef ^. uid
publicFunc
nm
(convType tp)
("Calculates " ++ desc)
parms
(Just desc)
[blck]
data CalcType = CalcAssign | CalcReturn deriving Eq
genCalcBlock :: (ProgramSym repr) => CalcType -> CodeDefinition -> Expr ->
Reader DrasilState (MS (repr (Block repr)))
genCalcBlock t v (Case c e) = genCaseBlock t v c e
genCalcBlock t v e
| t == CalcAssign = fmap block $ liftS $ do { vv <- mkVar v; ee <-
convExpr e; l <- maybeLog vv; return $ multi $ assign vv ee : l}
| otherwise = block <$> liftS (returnState <$> convExpr e)
genCaseBlock :: (ProgramSym repr) => CalcType -> CodeDefinition -> Completeness
-> [(Expr,Relation)] -> Reader DrasilState (MS (repr (Block repr)))
genCaseBlock _ _ _ [] = error $ "Case expression with no cases encountered" ++
" in code generator"
genCaseBlock t v c cs = do
ifs <- mapM (\(e,r) -> liftM2 (,) (convExpr r) (calcBody e)) (ifEs c)
els <- elseE c
return $ block [ifCond ifs els]
where calcBody e = fmap body $ liftS $ genCalcBlock t v e
ifEs Complete = init cs
ifEs Incomplete = cs
elseE Complete = calcBody $ fst $ last cs
elseE Incomplete = return $ oneLiner $ throw $
"Undefined case encountered in function " ++ codeName v
-- medium hacks --
genModDef :: (ProgramSym repr) => Mod ->
Reader DrasilState (FS (repr (RenderFile repr)))
genModDef (Mod n desc is cs fs) = genModuleWithImports n desc is (map (fmap
Just . genFunc) fs)
(case cs of [] -> []
(cl:cls) -> fmap Just (genClass primaryClass cl) :
map (fmap Just . genClass auxClass) cls)
genModFuncs :: (ProgramSym repr) => Mod ->
[Reader DrasilState (MS (repr (Method repr)))]
genModFuncs (Mod _ _ _ _ fs) = map genFunc fs
genClass :: (ProgramSym repr) => (String -> Label -> Maybe Label ->
[CS (repr (StateVar repr))] -> Reader DrasilState [MS (repr (Method repr))]
-> Reader DrasilState (CS (repr (Class repr)))) -> M.Class ->
Reader DrasilState (CS (repr (Class repr)))
genClass f (M.ClassDef n i desc svs ms) = do
svrs <- mapM (\v -> fmap (pubMVar . var (codeName v) . convType) (codeType v))
svs
f n desc i svrs (mapM genFunc ms)
genFunc :: (ProgramSym repr) => Func -> Reader DrasilState (MS (repr (Method repr)))
genFunc (FDef (FuncDef n desc parms o rd s)) = do
g <- ask
stmts <- mapM convStmt s
vars <- mapM mkVar (fstdecl (sysinfodb $ csi $ codeSpec g) s \\ parms)
publicFunc n (convType $ spaceMatches g o) desc parms rd
[block $ map varDec vars ++ stmts]
genFunc (FDef (CtorDef n desc parms i s)) = do
g <- ask
inits <- mapM (convExpr . snd) i
initvars <- mapM ((\iv -> fmap (var (codeName iv) . convType) (codeType iv))
. fst) i
stmts <- mapM convStmt s
vars <- mapM mkVar (fstdecl (sysinfodb $ csi $ codeSpec g) s \\ parms)
genInitConstructor n desc parms (zip initvars inits)
[block $ map varDec vars ++ stmts]
genFunc (FData (FuncData n desc ddef)) = genDataFunc n desc ddef
genFunc (FCD cd) = genCalcFunc cd
convStmt :: (ProgramSym repr) => FuncStmt -> Reader DrasilState (MS (repr (Statement repr)))
convStmt (FAsg v e) = do
e' <- convExpr e
v' <- mkVar v
l <- maybeLog v'
return $ multi $ assign v' e' : l
convStmt (FAsgIndex v i e) = do
e' <- convExpr e
v' <- mkVar v
let vi = arrayElem i v'
l <- maybeLog vi
return $ multi $ assign vi e' : l
convStmt (FAsgObjVar o v e) = do
e' <- convExpr e
o' <- mkVar o
t <- codeType v
let ov = objVar o' (var (codeName v) (convType t))
l <- maybeLog ov
return $ multi $ assign ov e' : l
convStmt (FFor v e st) = do
stmts <- mapM convStmt st
vari <- mkVar v
e' <- convExpr $ getUpperBound e
return $ forRange vari (litInt 0) e' (litInt 1) (bodyStatements stmts)
convStmt (FForEach v e st) = do
stmts <- mapM convStmt st
vari <- mkVar v
e' <- convExpr e
return $ forEach vari e' (bodyStatements stmts)
convStmt (FWhile e st) = do
stmts <- mapM convStmt st
e' <- convExpr e
return $ while e' (bodyStatements stmts)
convStmt (FCond e tSt []) = do
stmts <- mapM convStmt tSt
e' <- convExpr e
return $ ifNoElse [(e', bodyStatements stmts)]
convStmt (FCond e tSt eSt) = do
stmt1 <- mapM convStmt tSt
stmt2 <- mapM convStmt eSt
e' <- convExpr e
return $ ifCond [(e', bodyStatements stmt1)] (bodyStatements stmt2)
convStmt (FRet e) = do
e' <- convExpr e
return $ returnState e'
convStmt (FThrow s) = return $ throw s
convStmt (FTry t c) = do
stmt1 <- mapM convStmt t
stmt2 <- mapM convStmt c
return $ tryCatch (bodyStatements stmt1) (bodyStatements stmt2)
convStmt FContinue = return continue
convStmt (FDec v) = do
vari <- mkVar v
let convDec (C.List _) = listDec 0 vari
convDec _ = varDec vari
fmap convDec (codeType v)
convStmt (FDecDef v e) = do
v' <- mkVar v
l <- maybeLog v'
let convDecDef (Matrix [lst]) = do
e' <- mapM convExpr lst
return $ listDecDef v' e'
convDecDef _ = do
e' <- convExpr e
return $ varDecDef v' e'
dd <- convDecDef e
return $ multi $ dd : l
convStmt (FVal e) = do
e' <- convExpr e
return $ valState e'
convStmt (FMulti ss) = do
stmts <- mapM convStmt ss
return $ multi stmts
convStmt (FAppend a b) = do
a' <- convExpr a
b' <- convExpr b
return $ valState $ listAppend a' b'
genDataFunc :: (ProgramSym repr) => Name -> String -> DataDesc ->
Reader DrasilState (MS (repr (Method repr)))
genDataFunc nameTitle desc ddef = do
let parms = getInputs ddef
bod <- readData ddef
publicFunc nameTitle void desc (codevar inFileName : parms) Nothing bod
-- this is really ugly!!
readData :: (ProgramSym repr) => DataDesc -> Reader DrasilState
[MS (repr (Block repr))]
readData ddef = do
inD <- mapM inData ddef
v_filename <- mkVal $ codevar inFileName
return [block $
varDec var_infile :
(if any (\d -> isLine d || isLines d) ddef then [varDec var_line, listDec 0 var_linetokens] else []) ++
[listDec 0 var_lines | any isLines ddef] ++
openFileR var_infile v_filename :
concat inD ++ [
closeFile v_infile ]]
where inData :: (ProgramSym repr) => Data -> Reader DrasilState [MS (repr (Statement repr))]
inData (Singleton v) = do
vv <- mkVar v
l <- maybeLog vv
return [multi $ getFileInput v_infile vv : l]
inData JunkData = return [discardFileLine v_infile]
inData (Line lp d) = do
lnI <- lineData Nothing lp
logs <- getEntryVarLogs lp
return $ [getFileInputLine v_infile var_line,
stringSplit d var_linetokens v_line] ++ lnI ++ logs
inData (Lines lp ls d) = do
lnV <- lineData (Just "_temp") lp
logs <- getEntryVarLogs lp
let readLines Nothing = [getFileInputAll v_infile var_lines,
forRange var_i (litInt 0) (listSize v_lines) (litInt 1)
(bodyStatements $ stringSplit d var_linetokens (
listAccess v_lines v_i) : lnV)]
readLines (Just numLines) = [forRange var_i (litInt 0)
(litInt numLines) (litInt 1)
(bodyStatements $
[getFileInputLine v_infile var_line,
stringSplit d var_linetokens v_line
] ++ lnV)]
return $ readLines ls ++ logs
---------------
lineData :: (ProgramSym repr) => Maybe String -> LinePattern ->
Reader DrasilState [MS (repr (Statement repr))]
lineData s p@(Straight _) = do
vs <- getEntryVars s p
return [stringListVals vs v_linetokens]
lineData s p@(Repeat ds) = do
vs <- getEntryVars s p
sequence $ clearTemps s ds ++ return (stringListLists vs v_linetokens)
: appendTemps s ds
---------------
clearTemps :: (ProgramSym repr) => Maybe String -> [DataItem] ->
[Reader DrasilState (MS (repr (Statement repr)))]
clearTemps Nothing _ = []
clearTemps (Just sfx) es = map (clearTemp sfx) es
---------------
clearTemp :: (ProgramSym repr) => String -> DataItem ->
Reader DrasilState (MS (repr (Statement repr)))
clearTemp sfx v = fmap (\t -> listDecDef (var (codeName v ++ sfx)
(listInnerType $ convType t)) []) (codeType v)
---------------
appendTemps :: (ProgramSym repr) => Maybe String -> [DataItem] ->
[Reader DrasilState (MS (repr (Statement repr)))]
appendTemps Nothing _ = []
appendTemps (Just sfx) es = map (appendTemp sfx) es
---------------
appendTemp :: (ProgramSym repr) => String -> DataItem ->
Reader DrasilState (MS (repr (Statement repr)))
appendTemp sfx v = fmap (\t -> valState $ listAppend
(valueOf $ var (codeName v) (convType t))
(valueOf $ var (codeName v ++ sfx) (convType t))) (codeType v)
---------------
l_line, l_lines, l_linetokens, l_infile, l_i :: Label
var_line, var_lines, var_linetokens, var_infile, var_i ::
(ProgramSym repr) => VS (repr (Variable repr))
v_line, v_lines, v_linetokens, v_infile, v_i ::
(ProgramSym repr) => VS (repr (Value repr))
l_line = "line"
var_line = var l_line string
v_line = valueOf var_line
l_lines = "lines"
var_lines = var l_lines (listType string)
v_lines = valueOf var_lines
l_linetokens = "linetokens"
var_linetokens = var l_linetokens (listType string)
v_linetokens = valueOf var_linetokens
l_infile = "infile"
var_infile = var l_infile infile
v_infile = valueOf var_infile
l_i = "i"
var_i = var l_i int
v_i = valueOf var_i
getEntryVars :: (ProgramSym repr) => Maybe String -> LinePattern ->
Reader DrasilState [VS (repr (Variable repr))]
getEntryVars s lp = mapM (maybe mkVar (\st v -> codeType v >>= (variable
(codeName v ++ st) . listInnerType . convType)) s) (getPatternInputs lp)
getEntryVarLogs :: (ProgramSym repr) => LinePattern ->
Reader DrasilState [MS (repr (Statement repr))]
getEntryVarLogs lp = do
vs <- getEntryVars Nothing lp
logs <- mapM maybeLog vs
return $ concat logs
| JacquesCarette/literate-scientific-software | code/drasil-code/Language/Drasil/Code/Imperative/Import.hs | bsd-2-clause | 24,517 | 0 | 22 | 5,626 | 10,622 | 5,365 | 5,257 | 550 | 9 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Numeric.QuaterDoubleTest (runTests) where
import Numeric.Arbitraries
import Numeric.Basics
import Numeric.Quaternion
import Numeric.Vector
import Test.QuickCheck
type T = Double
-- | Some non-linear function are very unstable;
-- it would be a downting task to determine the uncertainty precisely.
-- Instead, I just make sure the tolerance is small enough to find at least
-- the most obvious bugs.
-- This function increases the tolerance by the span of magnitudes in q.
qSpan :: Quater T -> T
qSpan (Quater a b c d) = asSpan . foldl mm (1,1) $ map (\x -> x*x) [a, b, c, d]
where
mm :: (T,T) -> T -> (T,T)
mm (mi, ma) x
| x > M_EPS = (min mi x, max ma x)
| otherwise = (mi, ma)
asSpan :: (T,T) -> T
asSpan (mi, ma) = ma / mi
prop_Eq :: Quater T -> Bool
prop_Eq q = and
[ q == q
, Quater (takei q) (takej q) (takek q) (taker q) == q
, fromVecNum (imVec q) (taker q) == q
, im q + re q == q
, fromVec4 (toVec4 q) == q
]
prop_DoubleConjugate :: Quater T -> Property
prop_DoubleConjugate q = property $ conjugate (conjugate q) == q
prop_Square :: Quater T -> Property
prop_Square q = q * conjugate q =~= realToFrac (square q)
prop_RotScale :: Quater T -> Vector T 3 -> Property
prop_RotScale q v = fromVecNum (rotScale q v) 0 =~= q * fromVecNum v 0 * conjugate q
prop_GetRotScale :: Vector T 3 -> Vector T 3 -> Property
prop_GetRotScale a b
= normL2 a * ab > M_EPS * normL2 b
==> approxEq (recip ab) b (rotScale q a)
where
q = getRotScale a b
-- when a and b are almost opposite, precision of getRotScale suffers a lot
-- compensate it by increasing tolerance:
ab = min 1 $ 1 + normalized a `dot` normalized b
prop_InverseRotScale :: Quater T -> Vector T 3 -> Property
prop_InverseRotScale q v
= min (recip s) s > M_EPS ==> v =~= rotScale (1/q) (rotScale q v)
where
s = square q
prop_NegateToMatrix33 :: Quater T -> Bool
prop_NegateToMatrix33 q = toMatrix33 q == toMatrix33 (negate q)
prop_NegateToMatrix44 :: Quater T -> Bool
prop_NegateToMatrix44 q = toMatrix44 q == toMatrix44 (negate q)
prop_FromToMatrix33 :: Quater T -> Property
prop_FromToMatrix33 q
= q /= 0 ==> fromMatrix33 (toMatrix33 q) =~= q
.||. fromMatrix33 (toMatrix33 q) =~= negate q
prop_FromToMatrix44 :: Quater T -> Property
prop_FromToMatrix44 q
= q /= 0 ==> fromMatrix44 (toMatrix44 q) =~= q
.||. fromMatrix44 (toMatrix44 q) =~= negate q
prop_RotationArg :: Quater T -> Property
prop_RotationArg q | q == 0 = axisRotation (imVec q) (qArg q) =~= 1
| otherwise = axisRotation (imVec q) (qArg q) =~= signum q
prop_UnitQ :: Quater T -> Property
prop_UnitQ q
= square q > M_EPS ==> square (q / q) =~= 1
prop_ExpLog :: Quater T -> Property
prop_ExpLog q | square q < M_EPS = approxEq (qSpan q) q $ log (exp q)
| otherwise = approxEq (qSpan q) q $ exp (log q)
prop_SinAsin :: Quater T -> Property
prop_SinAsin q = approxEq (qSpan q `max` qSpan q') q $ sin q'
where
q' = asin q
prop_CosAcos :: Quater T -> Property
prop_CosAcos q = approxEq (qSpan q `max` qSpan q') q $ cos q'
where
q' = acos q
prop_TanAtan :: Quater T -> Property
prop_TanAtan q = approxEq (qSpan q `max` qSpan q') q $ tan q'
where
q' = atan q
prop_SinhAsinh :: Quater T -> Property
prop_SinhAsinh q = approxEq (qSpan q `max` qSpan q') q $ sinh q'
where
q' = asinh q
prop_CoshAcosh :: Quater T -> Property
prop_CoshAcosh q = approxEq (qSpan q `max` qSpan q') q $ cosh q'
where
q' = acosh q
prop_TanhAtanh :: Quater T -> Property
prop_TanhAtanh q = approxEq (qSpan q `max` qSpan q') q $ tanh q'
where
q' = atanh q
prop_SqrtSqr :: Quater T -> Property
prop_SqrtSqr q = approxEq (qSpan q) q $ sqrt q * sqrt q
prop_SinCos :: Quater T -> Property
prop_SinCos q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c + s * s
where
q = signum q' -- avoid exploding exponents
s = sin q
c = cos q
prop_SinhCosh :: Quater T -> Property
prop_SinhCosh q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c - s * s
where
q = signum q' -- avoid exploding exponents
s = sinh q
c = cosh q
prop_ReadShow :: Quater T -> Bool
prop_ReadShow q = q == read (show q)
return []
runTests :: Int -> IO Bool
runTests n = $forAllProperties
$ quickCheckWithResult stdArgs { maxSuccess = n }
| achirkin/easytensor | easytensor/test/Numeric/QuaterDoubleTest.hs | bsd-3-clause | 4,489 | 0 | 12 | 1,148 | 1,759 | 873 | 886 | 97 | 1 |
-- 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 GADTs #-}
module Duckling.Rules.ET
( defaultRules
, langRules
, localeRules
) where
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Numeral.ET.Rules as Numeral
import qualified Duckling.Ordinal.ET.Rules as Ordinal
defaultRules :: Seal Dimension -> [Rule]
defaultRules = langRules
localeRules :: Region -> Seal Dimension -> [Rule]
localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim
localeRules _ _ = []
langRules :: Seal Dimension -> [Rule]
langRules (Seal AmountOfMoney) = []
langRules (Seal CreditCardNumber) = []
langRules (Seal Distance) = []
langRules (Seal Duration) = []
langRules (Seal Email) = []
langRules (Seal Numeral) = Numeral.rules
langRules (Seal Ordinal) = Ordinal.rules
langRules (Seal PhoneNumber) = []
langRules (Seal Quantity) = []
langRules (Seal RegexMatch) = []
langRules (Seal Temperature) = []
langRules (Seal Time) = []
langRules (Seal TimeGrain) = []
langRules (Seal Url) = []
langRules (Seal Volume) = []
langRules (Seal (CustomDimension dim)) = dimLangRules ET dim
| facebookincubator/duckling | Duckling/Rules/ET.hs | bsd-3-clause | 1,309 | 0 | 9 | 201 | 418 | 224 | 194 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HUnit.Blending (tests) where
import Data.Convertible
import Data.Prizm.Color
import Data.Prizm.Color.CIE as CIE
import Test.Framework (Test)
import Test.Framework.Providers.HUnit as HUnit
import Test.HUnit (Assertion, (@?=))
tests :: [Test]
tests =
[ testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 0%" $ blendPinkGreen 0 (mkRGB 255 0 255)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 10%" $ blendPinkGreen 10 (mkRGB 255 0 210)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 20%" $ blendPinkGreen 20 (mkRGB 255 0 163)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 30%" $ blendPinkGreen 30 (mkRGB 255 0 115)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 40%" $ blendPinkGreen 40 (mkRGB 255 51 67)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 50%" $ blendPinkGreen 50 (mkRGB 255 111 0)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 60%" $ blendPinkGreen 60 (mkRGB 255 152 0)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 70%" $ blendPinkGreen 70 (mkRGB 255 186 0)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 80%" $ blendPinkGreen 80 (mkRGB 222 213 0)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 90%" $ blendPinkGreen 90 (mkRGB 172 236 0)
, testCase "Blend #ff00ff (pink) with #66ff00 (green) @ 100%" $ blendPinkGreen 100 (mkRGB 102 255 0)
]
blendPinkGreen :: Percent -> RGB -> Assertion
blendPinkGreen pct expected =
let pink :: CIE.LCH = convert $ mkRGB 255 0 255
green :: CIE.LCH = convert $ mkRGB 102 255 0
blended :: RGB = convert $ interpolate pct (pink,green)
in blended @?= expected
| ixmatus/prizm | tests/HUnit/Blending.hs | bsd-3-clause | 1,831 | 0 | 11 | 432 | 459 | 237 | 222 | 28 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Server
( serve
, response
, reqUri
) where
import Control.Concurrent
import Control.Exception
import Control.Monad.Reader
import Control.Monad.Trans
import Data.ByteString.Char8
import Network hiding (accept)
import Network.Socket hiding (sClose, recv)
import Network.Socket.ByteString (sendAll, recv)
import Prelude hiding (length, intercalate, readFile)
import System.Posix.Env.ByteString
import Text.Regex.PCRE
import Ecumenical
serve :: PortNumber -> IO ()
serve port = withSocketsDo $ do
sock <- listenOn $ PortNumber port
loop sock
loop sock = do
(conn, _) <- accept sock
forkIO $ body conn
loop sock
where
body conn = do
req <- recv conn 4096
-- Print incoming request information
peer <- getPeerName conn
Prelude.putStrLn $ show peer ++ ": " ++ show req
Prelude.putStrLn $ "Requested URI: " ++ show (reqUri req)
resp <- handleRequest req
sendAll conn $ resp
sClose conn
handleRequest :: ByteString -> IO ByteString
handleRequest request = case (reqUri request) of
Nothing -> return $ response "400 NEED A DRINK" page400
Just uri -> do
-- Treat URIs starting with static/ as requests for static files;
-- everything else goes to the as yet nonexistent blog.
case (stripPrefix "/static/" uri) of
Just path -> serveFile path
Nothing -> do
value <- retrieve uri
case value of
Just value -> return $ response "200 DRINK" value
Nothing -> return $ response "404 THE FECK" page404
staticFilesPath :: IO ByteString
staticFilesPath = do
args <- getArgs
return $ case args of
[path] -> path
[] -> "static"
_ -> "static"
-- This typeclass abstracts the IO-dependent static file server
class Monad m => StaticFileServer m where
serveFile :: ByteString -> m ByteString
instance StaticFileServer IO where
serveFile = serveStatic
newtype MockStaticFileServer m a =
MockStaticFileServer (ReaderT (ByteString -> ByteString) m a)
deriving ( Applicative
, Functor
, Monad
, MonadTrans
, MonadReader (ByteString -> ByteString)
)
runMockServer :: MockStaticFileServer m a -> (ByteString -> ByteString) -> m a
runMockServer (MockStaticFileServer s) = runReaderT s
-- Serve static file
serveStatic :: ByteString -> IO ByteString
serveStatic path = do
prefix <- staticFilesPath
result <- fileContents (prefix `append` "/" `append` path)
case result of
Nothing -> return $ response "404 NO TEA" page404
Just garbage -> return $ response "200 ARSE" garbage
page400 :: ByteString
page400 = "<html><center><h1>400 NEED A DRINK</h1><hr/>\
\How did that <em>gobshite</em> get on the socket?!</html>"
page403 :: ByteString
page403 = "<html><center><h1>403 Feck Off, Cup!</h1><hr/>\
\And what do you say to a cup of tea?</html>"
page404 :: ByteString
page404 = "<html><center><h1>404 Shut Up Dougal</h1><hr/>\
\One last time. These packets are <em>small</em>, but the ones \
\out there are <em>far away</em>.</html>"
reqUri :: ByteString -> Maybe ByteString
reqUri r = group1 $ ((r =~ pattern) :: [[ByteString]])
where pattern = "GET ([^ ]+) HTTP/1\\.1" :: ByteString
group1 :: [[ByteString]] -> Maybe ByteString
group1 [[_, x]] = Just x
group1 _ = Nothing
fileContents :: ByteString -> IO (Maybe ByteString)
fileContents path = do
-- XXX: this annotation is annoying, please slay it
-- XXX: also, whytf does ByteString.readFile take a [Char]???
contents <- (try $ readFile $ unpack path) :: IO (Either IOException ByteString)
case contents of
Left _ -> return Nothing
Right text -> return $ Just text
response :: ByteString -> ByteString -> ByteString
response status body =
intercalate "\r\n" [
"HTTP/1.1 " `append` status
, "Content-Length: " `append` (pack $ show $ length body)
, ""
, body]
| tripped/hlog | src/Server.hs | bsd-3-clause | 4,242 | 0 | 19 | 1,141 | 1,028 | 530 | 498 | 97 | 4 |
module Syllables where
import Data.List (sortBy)
import Data.Ord (comparing)
import Text.ParserCombinators.Parsec
type Syllable = (String, String, String)
type ONC = ([String], [String], [String])
syllabifyString onc input = case parse (ipaSyllable onc) "(unknown)" input of
Right fm -> fm
Left e -> error $ show e
ipaSyllable :: ONC -> GenParser Char st [Syllable]
ipaSyllable onc@(os, _, _) = (ipaOnset os) >>= (\ons -> (ipaRhyme onc) >>= (\((nuc, cod), syls) -> return ((ons, nuc, cod):syls)))
ipaOnset :: [String] -> GenParser Char st String
ipaOnset os = choice $ map (try . string) os
ipaRhyme :: ONC -> GenParser Char st ((String, String), [Syllable])
ipaRhyme onc@(_, ns, _) = choice (map (\s -> try (string s >>= \nuc -> (ipaNext onc >>= \(cod, syls) -> return ((nuc, cod), syls)))) ns)
ipaNext :: ONC -> GenParser Char st (String, [Syllable])
ipaNext onc@(_, _, cs) = (eof >> return ("", []))
<|> try (ipaSyllable onc >>= \syls -> return ("", syls))
<|> try (ipaCoda cs >>= \coda -> eof >> return (coda, []))
<|> try (ipaCoda cs >>= \coda -> (ipaSyllable onc >>= \syls -> return (coda, syls)))
ipaCoda :: [String] -> GenParser Char st String
ipaCoda cs = choice $ map (try . string) cs
onsets = reverse $ sortBy (comparing length)
["","p","t","k","r","m","n","ŋ","s","j","w","pr","tr","kr","sp","st","sk","sn"]
nuclei = sortBy (comparing length)
["a","e","i","o","u","aw","aj"]
codas = reverse $ sortBy (comparing length)
["", "p","t","k","r","m","n","ŋ","s"] | dmort27/HsSPE | Data/Phonology/Syllables.hs | bsd-3-clause | 1,592 | 0 | 19 | 345 | 772 | 435 | 337 | 28 | 2 |
{-|
Module : Idris.ProofSearch
Description : Searches current context for proofs'
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.ProofSearch(
trivial
, trivialHoles
, proofSearch
, resolveTC
) where
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.TT
import Idris.Core.Unify
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Idris.Core.Typecheck
import Idris.AbsSyntax
import Idris.Delaborate
import Idris.Error
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.State.Strict
import qualified Data.Set as S
import Data.List
import Debug.Trace
-- Pass in a term elaborator to avoid a cyclic dependency with ElabTerm
trivial :: (PTerm -> ElabD ()) -> IState -> ElabD ()
trivial = trivialHoles [] []
trivialHoles :: [Name] -> -- user visible names, when working
-- in interactive mode
[(Name, Int)] -> (PTerm -> ElabD ()) -> IState -> ElabD ()
trivialHoles psnames ok elab ist
= try' (do elab (PApp (fileFC "prf") (PRef (fileFC "prf") [] eqCon) [pimp (sUN "A") Placeholder False, pimp (sUN "x") Placeholder False])
return ())
(do env <- get_env
g <- goal
tryAll env
return ()) True
where
tryAll [] = fail "No trivial solution"
tryAll ((x, b):xs)
= do -- if type of x has any holes in it, move on
hs <- get_holes
let badhs = hs -- filter (flip notElem holesOK) hs
g <- goal
-- anywhere but the top is okay for a hole, if holesOK set
if -- all (\n -> not (n `elem` badhs)) (freeNames (binderTy b))
(holesOK hs (binderTy b) && (null psnames || x `elem` psnames))
then try' (elab (PRef (fileFC "prf") [] x))
(tryAll xs) True
else tryAll xs
holesOK hs ap@(App _ _ _)
| (P _ n _, args) <- unApply ap
= holeArgsOK hs n 0 args
holesOK hs (App _ f a) = holesOK hs f && holesOK hs a
holesOK hs (P _ n _) = not (n `elem` hs)
holesOK hs (Bind n b sc) = holesOK hs (binderTy b) &&
holesOK hs sc
holesOK hs _ = True
holeArgsOK hs n p [] = True
holeArgsOK hs n p (a : as)
| (n, p) `elem` ok = holeArgsOK hs n (p + 1) as
| otherwise = holesOK hs a && holeArgsOK hs n (p + 1) as
trivialTCs :: [(Name, Int)] -> (PTerm -> ElabD ()) -> IState -> ElabD ()
trivialTCs ok elab ist
= try' (do elab (PApp (fileFC "prf") (PRef (fileFC "prf") [] eqCon) [pimp (sUN "A") Placeholder False, pimp (sUN "x") Placeholder False])
return ())
(do env <- get_env
g <- goal
tryAll env
return ()) True
where
tryAll [] = fail "No trivial solution"
tryAll ((x, b):xs)
= do -- if type of x has any holes in it, move on
hs <- get_holes
let badhs = hs -- filter (flip notElem holesOK) hs
g <- goal
env <- get_env
-- anywhere but the top is okay for a hole, if holesOK set
if -- all (\n -> not (n `elem` badhs)) (freeNames (binderTy b))
(holesOK hs (binderTy b) && tcArg env (binderTy b))
then try' (elab (PRef (fileFC "prf") [] x))
(tryAll xs) True
else tryAll xs
tcArg env ty
| (P _ n _, args) <- unApply (getRetTy (normalise (tt_ctxt ist) env ty))
= case lookupCtxtExact n (idris_interfaces ist) of
Just _ -> True
_ -> False
| otherwise = False
holesOK hs ap@(App _ _ _)
| (P _ n _, args) <- unApply ap
= holeArgsOK hs n 0 args
holesOK hs (App _ f a) = holesOK hs f && holesOK hs a
holesOK hs (P _ n _) = not (n `elem` hs)
holesOK hs (Bind n b sc) = holesOK hs (binderTy b) &&
holesOK hs sc
holesOK hs _ = True
holeArgsOK hs n p [] = True
holeArgsOK hs n p (a : as)
| (n, p) `elem` ok = holeArgsOK hs n (p + 1) as
| otherwise = holesOK hs a && holeArgsOK hs n (p + 1) as
cantSolveGoal :: ElabD a
cantSolveGoal = do g <- goal
env <- get_env
lift $ tfail $
CantSolveGoal g (map (\(n,b) -> (n, binderTy b)) env)
proofSearch :: Bool -- ^ recursive search (False for 'refine')
-> Bool -- ^ invoked from a tactic proof. If so, making new metavariables is meaningless, and there should be an error reported instead.
-> Bool -- ^ ambiguity ok
-> Bool -- ^ defer on failure
-> Int -- ^ maximum depth
-> (PTerm -> ElabD ())
-> Maybe Name
-> Name
-> [Name]
-> [Name]
-> IState
-> ElabD ()
proofSearch False fromProver ambigok deferonfail depth elab _ nroot psnames [fn] ist
= do -- get all possible versions of the name, take the first one that
-- works
let all_imps = lookupCtxtName fn (idris_implicits ist)
tryAllFns all_imps
where
-- if nothing worked, make a new metavariable
tryAllFns [] | fromProver = cantSolveGoal
tryAllFns [] = do attack; defer [] nroot; solve
tryAllFns (f : fs) = try' (tryFn f) (tryAllFns fs) True
tryFn (f, args) = do let imps = map isImp args
ps <- get_probs
hs <- get_holes
args <- map snd <$> try' (apply (Var f) imps)
(match_apply (Var f) imps) True
ps' <- get_probs
-- when (length ps < length ps') $ fail "Can't apply constructor"
-- Make metavariables for new holes
hs' <- get_holes
ptm <- get_term
if fromProver then cantSolveGoal
else do
mapM_ (\ h -> do focus h
attack; defer [] nroot; solve)
(hs' \\ hs)
-- (filter (\ (x, y) -> not x) (zip (map fst imps) args))
solve
isImp (PImp p _ _ _ _) = (True, p)
isImp arg = (True, priority arg) -- try to get all of them by unification
proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot psnames hints ist
= do compute
ty <- goal
hs <- get_holes
env <- get_env
tm <- get_term
argsok <- conArgsOK ty
if ambigok || argsok then
case lookupCtxt nroot (idris_tyinfodata ist) of
[TISolution ts] -> findInferredTy ts
_ -> if ambigok then psRec rec maxDepth [] S.empty
-- postpone if it fails early in elaboration
else handleError cantsolve
(psRec rec maxDepth [] S.empty)
(autoArg (sUN "auto"))
else autoArg (sUN "auto") -- not enough info in the type yet
where
findInferredTy (t : _) = elab (delab ist (toUN t))
cantsolve (InternalMsg _) = True
cantsolve (CantSolveGoal _ _) = True
cantsolve (IncompleteTerm _) = True
cantsolve (At _ e) = cantsolve e
cantsolve (Elaborating _ _ _ e) = cantsolve e
cantsolve (ElaboratingArg _ _ _ e) = cantsolve e
cantsolve err = False
conArgsOK ty
= let (f, as) = unApply ty in
case f of
P _ n _ ->
let autohints = case lookupCtxtExact n (idris_autohints ist) of
Nothing -> []
Just hs -> hs in
case lookupCtxtExact n (idris_datatypes ist) of
Just t -> do rs <- mapM (conReady as)
(autohints ++ con_names t)
return (and rs)
Nothing -> -- local variable, go for it
return True
TType _ -> return True
_ -> typeNotSearchable ty
conReady :: [Term] -> Name -> ElabD Bool
conReady as n
= case lookupTyExact n (tt_ctxt ist) of
Just ty -> do let (_, cs) = unApply (getRetTy ty)
-- if any metavariables in 'as' correspond to
-- a constructor form in 'cs', then we're not
-- ready to run auto yet. Otherwise, go for it
hs <- get_holes
return $ and (map (notHole hs) (zip as cs))
Nothing -> fail "Can't happen"
-- if n is a metavariable, and c is a constructor form, we're not ready
-- to run yet
notHole hs (P _ n _, c)
| (P _ cn _, _) <- unApply c,
n `elem` hs && isConName cn (tt_ctxt ist) = False
| Constant _ <- c = not (n `elem` hs)
-- if fa is a metavariable applied to anything, we're not ready to run yet.
notHole hs (fa, c)
| (P _ fn _, args@(_:_)) <- unApply fa = fn `notElem` hs
notHole _ _ = True
inHS hs (P _ n _) = n `elem` hs
isHS _ _ = False
toUN t@(P nt (MN i n) ty)
| ('_':xs) <- str n = t
| otherwise = P nt (UN n) ty
toUN (App s f a) = App s (toUN f) (toUN a)
toUN t = t
-- psRec counts depth and the local variable applications we're under
-- (so we don't try a pointless application of something to itself,
-- which obviously won't work anyway but might lead us on a wild
-- goose chase...)
-- Also keep track of the types we've proved so far in this branch
-- (if we get back to one we've been to before, we're just in a cycle and
-- that's no use)
psRec :: Bool -> Int -> [Name] -> S.Set Type -> ElabD ()
psRec _ 0 locs tys | fromProver = cantSolveGoal
psRec rec 0 locs tys = do attack; defer [] nroot; solve --fail "Maximum depth reached"
psRec False d locs tys = tryCons d locs tys hints
psRec True d locs tys
= do compute
ty <- goal
when (S.member ty tys) $ fail "Been here before"
let tys' = S.insert ty tys
try' (try' (trivialHoles psnames [] elab ist)
(resolveTC False False 20 ty nroot elab ist)
True)
(try' (try' (resolveByCon (d - 1) locs tys')
(resolveByLocals (d - 1) locs tys')
True)
-- if all else fails, make a new metavariable
(if fromProver
then fail "cantSolveGoal"
else do attack; defer [] nroot; solve) True) True
-- get recursive function name. Only user given names make sense.
getFn d (Just f) | d < maxDepth-1 && usersname f = [f]
| otherwise = []
getFn d _ = []
usersname (UN _) = True
usersname (NS n _) = usersname n
usersname _ = False
resolveByCon d locs tys
= do t <- goal
let (f, _) = unApply t
case f of
P _ n _ ->
do let autohints = case lookupCtxtExact n (idris_autohints ist) of
Nothing -> []
Just hs -> hs
case lookupCtxtExact n (idris_datatypes ist) of
Just t -> do
let others = hints ++ con_names t ++ autohints
tryCons d locs tys (others ++ getFn d fn)
Nothing -> typeNotSearchable t
_ -> typeNotSearchable t
-- if there are local variables which have a function type, try
-- applying them too
resolveByLocals d locs tys
= do env <- get_env
tryLocals d locs tys env
tryLocals d locs tys [] = fail "Locals failed"
tryLocals d locs tys ((x, t) : xs)
| x `elem` locs || x `notElem` psnames = tryLocals d locs tys xs
| otherwise = try' (tryLocal d (x : locs) tys x t)
(tryLocals d locs tys xs) True
tryCons d locs tys [] = fail "Constructors failed"
tryCons d locs tys (c : cs)
= try' (tryCon d locs tys c) (tryCons d locs tys cs) True
tryLocal d locs tys n t
= do let a = getPArity (delab ist (binderTy t))
tryLocalArg d locs tys n a
tryLocalArg d locs tys n 0 = elab (PRef (fileFC "prf") [] n)
tryLocalArg d locs tys n i
= simple_app False (tryLocalArg d locs tys n (i - 1))
(psRec True d locs tys) "proof search local apply"
-- Like interface resolution, but searching with constructors
tryCon d locs tys n =
do ty <- goal
let imps = case lookupCtxtExact n (idris_implicits ist) of
Nothing -> []
Just args -> map isImp args
ps <- get_probs
hs <- get_holes
args <- map snd <$> try' (apply (Var n) imps)
(match_apply (Var n) imps) True
ps' <- get_probs
hs' <- get_holes
when (length ps < length ps') $ fail "Can't apply constructor"
let newhs = filter (\ (x, y) -> not x) (zip (map fst imps) args)
mapM_ (\ (_, h) -> do focus h
aty <- goal
psRec True d locs tys) newhs
solve
isImp (PImp p _ _ _ _) = (True, p)
isImp arg = (False, priority arg)
typeNotSearchable ty =
lift $ tfail $ FancyMsg $
[TextPart "Attempted to find an element of type",
TermPart ty,
TextPart "using proof search, but proof search only works on datatypes with constructors."] ++
case ty of
(Bind _ (Pi _ _ _) _) -> [TextPart "In particular, function types are not supported."]
_ -> []
-- | Resolve interfaces. This will only pick up 'normal'
-- implementations, never named implementations (which is enforced by
-- 'findImplementations').
resolveTC :: Bool -- ^ using default Int
-> Bool -- ^ allow open implementations
-> Int -- ^ depth
-> Term -- ^ top level goal, for error messages
-> Name -- ^ top level function name, to prevent loops
-> (PTerm -> ElabD ()) -- ^ top level elaborator
-> IState -> ElabD ()
resolveTC def openOK depth top fn elab ist
= do hs <- get_holes
resTC' [] def openOK hs depth top fn elab ist
resTC' tcs def openOK topholes 0 topg fn elab ist = fail "Can't resolve interface"
resTC' tcs def openOK topholes 1 topg fn elab ist = try' (trivial elab ist) (resolveTC def False 0 topg fn elab ist) True
resTC' tcs defaultOn openOK topholes depth topg fn elab ist
= do compute
if openOK
then try' (resolveOpen (idris_openimpls ist))
resolveNormal
True
else resolveNormal
where
-- try all the Open implementations first
resolveOpen open = do t <- goal
blunderbuss t depth [] open
resolveNormal = do
-- Resolution can proceed only if there is something concrete in the
-- determining argument positions. Keep track of the holes in the
-- non-determining position, because it's okay for 'trivial' to solve
-- those holes and no others.
g <- goal
let (argsok, okholePos) = case tcArgsOK g topholes of
Nothing -> (False, [])
Just hs -> (True, hs)
env <- get_env
probs <- get_probs
if not argsok -- && not mvok)
then lift $ tfail $ CantResolve True topg (probErr probs)
else do
ptm <- get_term
ulog <- getUnifyLog
hs <- get_holes
env <- get_env
t <- goal
let (tc, ttypes) = unApply (getRetTy t)
let okholes = case tc of
P _ n _ -> zip (repeat n) okholePos
_ -> []
traceWhen ulog ("Resolving interface " ++ show g ++ "\nin" ++ show env ++ "\n" ++ show okholes) $
try' (trivialTCs okholes elab ist)
(do addDefault t tc ttypes
let stk = map fst (filter snd $ elab_stack ist)
let impls = idris_openimpls ist ++ findImplementations ist t
blunderbuss t depth stk (stk ++ impls)) True
-- returns Just hs if okay, where hs are holes which are okay in the
-- goal, or Nothing if not okay to proceed
tcArgsOK ty hs | (P _ nc _, as) <- unApply (getRetTy ty), nc == numinterface && defaultOn
= Just []
tcArgsOK ty hs -- if any determining arguments are metavariables, postpone
= let (f, as) = unApply (getRetTy ty) in
case f of
P _ cn _ -> case lookupCtxtExact cn (idris_interfaces ist) of
Just ci -> tcDetArgsOK 0 (interface_determiners ci) hs as
Nothing -> if any (isMeta hs) as
then Nothing
else Just []
_ -> if any (isMeta hs) as
then Nothing
else Just []
-- return the list of argument positions which can safely be a hole
-- or Nothing if one of the determining arguments is a hole
tcDetArgsOK i ds hs (x : xs)
| i `elem` ds = if isMeta hs x
then Nothing
else tcDetArgsOK (i + 1) ds hs xs
| otherwise = do rs <- tcDetArgsOK (i + 1) ds hs xs
case x of
P _ n _ -> Just (i : rs)
_ -> Just rs
tcDetArgsOK _ _ _ [] = Just []
probErr [] = Msg ""
probErr ((_,_,_,_,err,_,_) : _) = err
isMeta :: [Name] -> Term -> Bool
isMeta ns (P _ n _) = n `elem` ns
isMeta _ _ = False
notHole hs (P _ n _, c)
| (P _ cn _, _) <- unApply (getRetTy c),
n `elem` hs && isConName cn (tt_ctxt ist) = False
| Constant _ <- c = not (n `elem` hs)
notHole _ _ = True
numinterface = sNS (sUN "Num") ["Interfaces","Prelude"]
addDefault t num@(P _ nc _) [P Bound a _] | nc == numinterface && defaultOn
= do focus a
fill (RConstant (AType (ATInt ITBig))) -- default Integer
solve
addDefault t f as
| all boundVar as = return () -- True -- fail $ "Can't resolve " ++ show t
addDefault t f a = return () -- trace (show t) $ return ()
boundVar (P Bound _ _) = True
boundVar _ = False
blunderbuss t d stk [] = do ps <- get_probs
lift $ tfail $ CantResolve False topg (probErr ps)
blunderbuss t d stk (n:ns)
| n /= fn -- && (n `elem` stk)
= tryCatch (resolve n d)
(\e -> case e of
CantResolve True _ _ -> lift $ tfail e
_ -> blunderbuss t d stk ns)
| otherwise = blunderbuss t d stk ns
introImps = do g <- goal
case g of
(Bind _ (Pi _ _ _) sc) -> do attack; intro Nothing
num <- introImps
return (num + 1)
_ -> return 0
solven n = replicateM_ n solve
resolve n depth
| depth == 0 = fail "Can't resolve interface"
| otherwise
= do lams <- introImps
t <- goal
let (tc, ttypes) = trace (show t) $ unApply (getRetTy t)
-- if (all boundVar ttypes) then resolveTC (depth - 1) fn impls ist
-- else do
-- if there's a hole in the goal, don't even try
let imps = case lookupCtxtName n (idris_implicits ist) of
[] -> []
[args] -> map isImp (snd args) -- won't be overloaded!
xs -> error "The impossible happened - overloading is not expected here!"
ps <- get_probs
tm <- get_term
args <- map snd <$> apply (Var n) imps
solven lams -- close any implicit lambdas we introduced
ps' <- get_probs
when (length ps < length ps' || unrecoverable ps') $
fail "Can't apply interface"
-- traceWhen (all boundVar ttypes) ("Progress: " ++ show t ++ " with " ++ show n) $
mapM_ (\ (_,n) -> do focus n
t' <- goal
let (tc', ttype) = unApply (getRetTy t')
let got = fst (unApply (getRetTy t))
let depth' = if tc' `elem` tcs
then depth - 1 else depth
resTC' (got : tcs) defaultOn openOK topholes depth' topg fn elab ist)
(filter (\ (x, y) -> not x) (zip (map fst imps) args))
-- if there's any arguments left, we've failed to resolve
hs <- get_holes
ulog <- getUnifyLog
solve
traceWhen ulog ("Got " ++ show n) $ return ()
where isImp (PImp p _ _ _ _) = (True, p)
isImp arg = (False, priority arg)
-- | Find the names of implementations that have been designeated for
-- searching (i.e. non-named implementations or implementations from Elab scripts)
findImplementations :: IState -> Term -> [Name]
findImplementations ist t
| (P _ n _, _) <- unApply (getRetTy t)
= case lookupCtxt n (idris_interfaces ist) of
[CI _ _ _ _ _ ins _] ->
[n | (n, True) <- ins, accessible n]
_ -> []
| otherwise = []
where accessible n = case lookupDefAccExact n False (tt_ctxt ist) of
Just (_, Hidden) -> False
Just (_, Private) -> False
_ -> True
| enolan/Idris-dev | src/Idris/ProofSearch.hs | bsd-3-clause | 23,070 | 160 | 22 | 9,737 | 6,142 | 3,222 | 2,920 | 422 | 39 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Syncthing.Types.SystemMsg
( SystemMsg(..)
) where
import Control.Applicative ((<$>), (*>), (<*), (<|>), pure)
import Control.Monad (MonadPlus (mzero))
import Data.Aeson (FromJSON, Value (..), parseJSON, (.:))
import qualified Data.Attoparsec.Text as A
import Data.Text (Text)
import Network.Syncthing.Types.Common (FolderName)
-- | System messages.
data SystemMsg
= Restarting
| ShuttingDown
| ResettingDatabase
| ResettingFolder FolderName
| OtherSystemMsg Text
deriving (Eq, Show)
instance FromJSON SystemMsg where
parseJSON (Object v) = parseSystemMsg <$> (v .: "ok")
parseJSON _ = mzero
parseSystemMsg :: Text -> SystemMsg
parseSystemMsg msg =
case A.parseOnly sysMsgParser msg of
Left _ -> OtherSystemMsg msg
Right m -> m
sysMsgParser :: A.Parser SystemMsg
sysMsgParser =
"restarting" *> pure Restarting
<|> "shutting down" *> pure ShuttingDown
<|> "resetting database" *> pure ResettingDatabase
<|> ResettingFolder <$> ("resetting folder " *> A.takeText)
| jetho/syncthing-hs | Network/Syncthing/Types/SystemMsg.hs | bsd-3-clause | 1,192 | 0 | 12 | 310 | 304 | 177 | 127 | 30 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar.Plugins
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <andrea.rossato@unibz.it>
-- Stability : unstable
-- Portability : unportable
--
-- This module exports the API for plugins.
--
-- Have a look at Plugins\/HelloWorld.hs
--
-----------------------------------------------------------------------------
module Plugins
( Exec (..)
, tenthSeconds
, readFileSafe
, hGetLineSafe
) where
import Commands
import XUtil
| neglectedvalue/xmobar-freebsd | Plugins.hs | bsd-3-clause | 616 | 0 | 5 | 111 | 43 | 34 | 9 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Blaze.Svg
(
Svg
, Path
, toSvg
-- * SVG Path combinators
, mkPath
-- ** \"moveto\" commands
, m, mr
-- ** \"closepath\" command
, z
-- ** \"lineto\" commands
, l, lr, h, hr, v, vr
-- ** The cubic Bézier curve commands
, c, cr, s, sr
-- ** The quadratic Bézier curve commands
, q, qr, t, tr
-- ** Elliptical arc
, aa , ar
-- * SVG Transform combinators
, translate, rotate, rotateAround, scale
, skewX, skewY
, matrix
) where
import Text.Blaze.Svg.Internal
| deepakjois/blaze-svg | src/Text/Blaze/Svg.hs | bsd-3-clause | 600 | 0 | 4 | 189 | 115 | 80 | 35 | 17 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIX.PolynomialFFD
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIX/polynomial_ffd.txt SGIX_polynomial_ffd> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIX.PolynomialFFD (
-- * Enums
gl_DEFORMATIONS_MASK_SGIX,
gl_GEOMETRY_DEFORMATION_BIT_SGIX,
gl_GEOMETRY_DEFORMATION_SGIX,
gl_MAX_DEFORMATION_ORDER_SGIX,
gl_TEXTURE_DEFORMATION_BIT_SGIX,
gl_TEXTURE_DEFORMATION_SGIX,
-- * Functions
glDeformSGIX,
glDeformationMap3dSGIX,
glDeformationMap3fSGIX,
glLoadIdentityDeformationMapSGIX
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/SGIX/PolynomialFFD.hs | bsd-3-clause | 997 | 0 | 4 | 112 | 73 | 56 | 17 | 13 | 0 |
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------
-- a parser for Haskell patterns --
-- (don't ask...) --
-----------------------------------
module PattParser (
parsePatt, parseVar
) where
import Text.ParserCombinators.Parsec
import Language.Haskell.TH
import Data.Char
varStartChars = ['a'..'z']
ctorStartChars = ['A'..'Z']
identChars = varStartChars ++ ctorStartChars ++ ['0'..'9'] ++ "'_"
varParser :: GenParser Char st String
varParser =
do char1 <- oneOf varStartChars
char_rest <- many (oneOf identChars)
return (char1 : char_rest)
ctorParser :: GenParser Char st String
ctorParser =
do char1 <- oneOf ctorStartChars
char_rest <- many (oneOf identChars)
return (char1 : char_rest)
stringParser :: GenParser Char st String
stringParser =
do char '"'
res <- stringContentsParser
return res
stringContentsParser =
many (noneOf "\\\"") >>= \prefix ->
(char '"' >> return prefix)
<|>
(char '\\' >> do c <- anyChar
rest <- stringContentsParser
return $ prefix ++ [c] ++ rest)
charParser :: GenParser Char st Char
charParser =
do char '\''
c <- ((char '\\' >> anyChar) <|> anyChar)
char '\''
return c
digitsToInt digits = helper digits 0
where helper [] accum = accum
helper (digit:digits) accum =
helper digits (accum * 10 + (digitToInt digit))
intToRational :: Int -> Rational
intToRational = fromIntegral
digitsToFrac digits = helper digits
where helper [] = 0.0
helper (digit:digits) = ((helper digits) + (intToRational $ digitToInt digit)) / 10
numParser :: GenParser Char st Lit
numParser =
do base_digits <- many1 (oneOf ['0'..'9'])
((do char '.'
frac_digits <- many1 (oneOf ['0'..'9'])
return (RationalL $ (intToRational $ digitsToInt base_digits) + digitsToFrac frac_digits))
<|> return (IntegerL $ fromIntegral $ digitsToInt base_digits))
litParser :: GenParser Char st Lit
litParser = (charParser >>= return . CharL) <|>
(stringParser >>= return . StringL) <|>
numParser
commaSepParser :: GenParser Char st [Pat]
commaSepParser =
do first <- pattParser
rest <- (char ',' >> commaSepParser) <|> (return [])
return (first:rest)
tokenParser :: GenParser Char st Pat
tokenParser =
-- literals
(litParser >>= return . LitP) <|>
-- wildcards
(char '_' >> return WildP) <|>
-- vars
(varParser >>= return . VarP . mkName) <|>
-- tuples; NOTE: we parse any parenthesized expression as a tuple,
-- and remove the TupP constructor when there are no commas
(do char '('
tup <- commaSepParser
char ')'
return (case tup of
[] -> ConP '() []
[patt] -> patt
_ -> TupP tup)) <|>
-- constructor applications
(do ctor <- ctorParser
args <- many (try pattParser)
return $ ConP (mkName ctor) args) <|>
-- lists
(do char '['
elems <- commaSepParser
char ']'
return $ ListP elems)
wsParser :: GenParser Char st ()
wsParser = many (oneOf " \t\n\r") >> return ()
pattParser :: GenParser Char st Pat
pattParser = do wsParser
res <- tokenParser
wsParser
return res
varOnlyParser :: GenParser Char st String
varOnlyParser = do wsParser
res <- varParser
wsParser
eof
return res
----------------------------------------
-- Finally, the external interface... --
----------------------------------------
parsePatt str = case parse pattParser "" str of
Left err -> error $ show err
Right patt -> patt
parseVar str = case parse varOnlyParser "" str of
Left err -> error $ show err
Right str -> str
| eddywestbrook/hobbits | archival/PattParser.hs | bsd-3-clause | 3,993 | 0 | 18 | 1,205 | 1,184 | 583 | 601 | 100 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency.Types
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Common types for dependency resolution.
-----------------------------------------------------------------------------
module Distribution.Client.Dependency.Types (
PreSolver(..),
Solver(..),
DependencyResolver,
ResolverPackage(..),
AllowNewer(..), isAllowNewer,
PackageConstraint(..),
showPackageConstraint,
PackagePreferences(..),
InstalledPreference(..),
PackagesPreferenceDefault(..),
Progress(..),
foldProgress,
LabeledPackageConstraint(..),
ConstraintSource(..),
unlabelPackageConstraint,
showConstraintSource
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
( Applicative(..) )
#endif
import Control.Applicative
( Alternative(..) )
import Data.Char
( isAlpha, toLower )
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import Distribution.Client.Types
( OptionalStanza(..), SourcePackage(..), ConfiguredPackage )
import qualified Distribution.Compat.ReadP as Parse
( pfail, munch1 )
import Distribution.PackageDescription
( FlagAssignment, FlagName(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import qualified Distribution.Client.PackageIndex as PackageIndex
( PackageIndex )
import Distribution.Simple.PackageIndex ( InstalledPackageIndex )
import Distribution.Package
( PackageName )
import Distribution.Version
( VersionRange, simplifyVersionRange )
import Distribution.Compiler
( CompilerInfo )
import Distribution.System
( Platform )
import Distribution.Text
( Text(..), display )
import Text.PrettyPrint
( text )
import GHC.Generics (Generic)
import Distribution.Compat.Binary (Binary(..))
import Prelude hiding (fail)
-- | All the solvers that can be selected.
data PreSolver = AlwaysTopDown | AlwaysModular | Choose
deriving (Eq, Ord, Show, Bounded, Enum, Generic)
-- | All the solvers that can be used.
data Solver = TopDown | Modular
deriving (Eq, Ord, Show, Bounded, Enum, Generic)
instance Binary PreSolver
instance Binary Solver
instance Text PreSolver where
disp AlwaysTopDown = text "topdown"
disp AlwaysModular = text "modular"
disp Choose = text "choose"
parse = do
name <- Parse.munch1 isAlpha
case map toLower name of
"topdown" -> return AlwaysTopDown
"modular" -> return AlwaysModular
"choose" -> return Choose
_ -> Parse.pfail
-- | A dependency resolver is a function that works out an installation plan
-- given the set of installed and available packages and a set of deps to
-- solve for.
--
-- The reason for this interface is because there are dozens of approaches to
-- solving the package dependency problem and we want to make it easy to swap
-- in alternatives.
--
type DependencyResolver = Platform
-> CompilerInfo
-> InstalledPackageIndex
-> PackageIndex.PackageIndex SourcePackage
-> (PackageName -> PackagePreferences)
-> [LabeledPackageConstraint]
-> [PackageName]
-> Progress String String [ResolverPackage]
-- | The dependency resolver picks either pre-existing installed packages
-- or it picks source packages along with package configuration.
--
-- This is like the 'InstallPlan.PlanPackage' but with fewer cases.
--
data ResolverPackage = PreExisting InstalledPackageInfo
| Configured ConfiguredPackage
-- | Per-package constraints. Package constraints must be respected by the
-- solver. Multiple constraints for each package can be given, though obviously
-- it is possible to construct conflicting constraints (eg impossible version
-- range or inconsistent flag assignment).
--
data PackageConstraint
= PackageConstraintVersion PackageName VersionRange
| PackageConstraintInstalled PackageName
| PackageConstraintSource PackageName
| PackageConstraintFlags PackageName FlagAssignment
| PackageConstraintStanzas PackageName [OptionalStanza]
deriving (Eq,Show,Generic)
instance Binary PackageConstraint
-- | Provide a textual representation of a package constraint
-- for debugging purposes.
--
showPackageConstraint :: PackageConstraint -> String
showPackageConstraint (PackageConstraintVersion pn vr) =
display pn ++ " " ++ display (simplifyVersionRange vr)
showPackageConstraint (PackageConstraintInstalled pn) =
display pn ++ " installed"
showPackageConstraint (PackageConstraintSource pn) =
display pn ++ " source"
showPackageConstraint (PackageConstraintFlags pn fs) =
"flags " ++ display pn ++ " " ++ unwords (map (uncurry showFlag) fs)
where
showFlag (FlagName f) True = "+" ++ f
showFlag (FlagName f) False = "-" ++ f
showPackageConstraint (PackageConstraintStanzas pn ss) =
"stanzas " ++ display pn ++ " " ++ unwords (map showStanza ss)
where
showStanza TestStanzas = "test"
showStanza BenchStanzas = "bench"
-- | Per-package preferences on the version. It is a soft constraint that the
-- 'DependencyResolver' should try to respect where possible. It consists of
-- an 'InstalledPreference' which says if we prefer versions of packages
-- that are already installed. It also has (possibly multiple)
-- 'PackageVersionPreference's which are suggested constraints on the version
-- number. The resolver should try to use package versions that satisfy
-- the maximum number of the suggested version constraints.
--
-- It is not specified if preferences on some packages are more important than
-- others.
--
data PackagePreferences = PackagePreferences [VersionRange]
InstalledPreference
[OptionalStanza]
-- | Whether we prefer an installed version of a package or simply the latest
-- version.
--
data InstalledPreference = PreferInstalled | PreferLatest
deriving Show
-- | Global policy for all packages to say if we prefer package versions that
-- are already installed locally or if we just prefer the latest available.
--
data PackagesPreferenceDefault =
-- | Always prefer the latest version irrespective of any existing
-- installed version.
--
-- * This is the standard policy for upgrade.
--
PreferAllLatest
-- | Always prefer the installed versions over ones that would need to be
-- installed. Secondarily, prefer latest versions (eg the latest installed
-- version or if there are none then the latest source version).
| PreferAllInstalled
-- | Prefer the latest version for packages that are explicitly requested
-- but prefers the installed version for any other packages.
--
-- * This is the standard policy for install.
--
| PreferLatestForSelected
deriving Show
-- | Policy for relaxing upper bounds in dependencies. For example, given
-- 'build-depends: array >= 0.3 && < 0.5', are we allowed to relax the upper
-- bound and choose a version of 'array' that is greater or equal to 0.5? By
-- default the upper bounds are always strictly honored.
data AllowNewer =
-- | Default: honor the upper bounds in all dependencies, never choose
-- versions newer than allowed.
AllowNewerNone
-- | Ignore upper bounds in dependencies on the given packages.
| AllowNewerSome [PackageName]
-- | Ignore upper bounds in dependencies on all packages.
| AllowNewerAll
deriving (Eq, Ord, Show, Generic)
instance Binary AllowNewer
-- | Convert 'AllowNewer' to a boolean.
isAllowNewer :: AllowNewer -> Bool
isAllowNewer AllowNewerNone = False
isAllowNewer (AllowNewerSome _) = True
isAllowNewer AllowNewerAll = True
-- | A type to represent the unfolding of an expensive long running
-- calculation that may fail. We may get intermediate steps before the final
-- result which may be used to indicate progress and\/or logging messages.
--
data Progress step fail done = Step step (Progress step fail done)
| Fail fail
| Done done
deriving Functor
-- | Consume a 'Progress' calculation. Much like 'foldr' for lists but with two
-- base cases, one for a final result and one for failure.
--
-- Eg to convert into a simple 'Either' result use:
--
-- > foldProgress (flip const) Left Right
--
foldProgress :: (step -> a -> a) -> (fail -> a) -> (done -> a)
-> Progress step fail done -> a
foldProgress step fail done = fold
where fold (Step s p) = step s (fold p)
fold (Fail f) = fail f
fold (Done r) = done r
instance Monad (Progress step fail) where
return = pure
p >>= f = foldProgress Step Fail f p
instance Applicative (Progress step fail) where
pure a = Done a
p <*> x = foldProgress Step Fail (flip fmap x) p
instance Monoid fail => Alternative (Progress step fail) where
empty = Fail mempty
p <|> q = foldProgress Step (const q) Done p
-- | 'PackageConstraint' labeled with its source.
data LabeledPackageConstraint
= LabeledPackageConstraint PackageConstraint ConstraintSource
unlabelPackageConstraint :: LabeledPackageConstraint -> PackageConstraint
unlabelPackageConstraint (LabeledPackageConstraint pc _) = pc
-- | Source of a 'PackageConstraint'.
data ConstraintSource =
-- | Main config file, which is ~/.cabal/config by default.
ConstraintSourceMainConfig FilePath
-- | Sandbox config file, which is ./cabal.sandbox.config by default.
| ConstraintSourceSandboxConfig FilePath
-- | User config file, which is ./cabal.config by default.
| ConstraintSourceUserConfig FilePath
-- | Flag specified on the command line.
| ConstraintSourceCommandlineFlag
-- | Target specified by the user, e.g., @cabal install package-0.1.0.0@
-- implies @package==0.1.0.0@.
| ConstraintSourceUserTarget
-- | Internal requirement to use installed versions of packages like ghc-prim.
| ConstraintSourceNonUpgradeablePackage
-- | Internal requirement to use the add-source version of a package when that
-- version is installed and the source is modified.
| ConstraintSourceModifiedAddSourceDep
-- | Internal constraint used by @cabal freeze@.
| ConstraintSourceFreeze
-- | Constraint specified by a config file, a command line flag, or a user
-- target, when a more specific source is not known.
| ConstraintSourceConfigFlagOrTarget
-- | The source of the constraint is not specified.
| ConstraintSourceUnknown
deriving (Eq, Show, Generic)
instance Binary ConstraintSource
-- | Description of a 'ConstraintSource'.
showConstraintSource :: ConstraintSource -> String
showConstraintSource (ConstraintSourceMainConfig path) =
"main config " ++ path
showConstraintSource (ConstraintSourceSandboxConfig path) =
"sandbox config " ++ path
showConstraintSource (ConstraintSourceUserConfig path)= "user config " ++ path
showConstraintSource ConstraintSourceCommandlineFlag = "command line flag"
showConstraintSource ConstraintSourceUserTarget = "user target"
showConstraintSource ConstraintSourceNonUpgradeablePackage =
"non-upgradeable package"
showConstraintSource ConstraintSourceModifiedAddSourceDep =
"modified add-source dependency"
showConstraintSource ConstraintSourceFreeze = "cabal freeze"
showConstraintSource ConstraintSourceConfigFlagOrTarget =
"config file, command line flag, or user target"
showConstraintSource ConstraintSourceUnknown = "unknown source"
| lukexi/cabal | cabal-install/Distribution/Client/Dependency/Types.hs | bsd-3-clause | 11,908 | 0 | 13 | 2,437 | 1,701 | 977 | 724 | 176 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Server.Http
( startHttpServer
)
where
import Network.Wai.Handler.Warp
import Web.Scotty
import Control.Concurrent ( ThreadId
, forkIO
)
import Control.Concurrent.STM ( TVar
, atomically
, modifyTVar
)
import Control.Monad.Trans ( liftIO )
import System.FilePath.Posix ( (</>) )
import Data.ByteString.Lazy.Char8 ( ByteString
, pack
, unpack
)
import qualified Data.Map.Strict as M
import Logging ( logError
, logInfo
)
import qualified Language as L
import Language.Ast ( Value(Number) )
import Language.Parser.Errors ( prettyPrintErrors
, parseErrorsOut
)
import qualified Gfx.Materials as GM
import Server.Protocol
import qualified Configuration as C
import Improviz ( ImprovizEnv )
import qualified Improviz as I
import qualified Improviz.Runtime as IR
import Improviz.UI ( ImprovizUI )
import qualified Improviz.UI as IUI
import Lens.Simple ( set
, (^.)
)
editorHtmlFilePath :: FilePath
editorHtmlFilePath = "html/editor.html"
updateProgram :: ImprovizEnv -> String -> IO ImprovizResponse
updateProgram env newProgram = case L.parse newProgram of
Right newAst -> do
atomically $ do
modifyTVar (env ^. I.runtime) (IR.updateProgram newProgram newAst)
modifyTVar (env ^. I.ui) (set IUI.currentText newProgram)
let msg = "Parsed Successfully"
logInfo msg
return $ ImprovizOKResponse msg
Left err -> do
logError $ prettyPrintErrors err
return $ ImprovizCodeErrorResponse $ parseErrorsOut err
updateMaterial :: ImprovizEnv -> ByteString -> IO ImprovizResponse
updateMaterial env newMaterial = case GM.loadMaterialString newMaterial of
Right materialData -> do
atomically $ modifyTVar (env ^. I.runtime) (addToMaterialQueue materialData)
let msg = "Material Queued Successfully"
logInfo msg
return $ ImprovizOKResponse msg
Left err -> do
logError err
return $ ImprovizErrorResponse err
where
addToMaterialQueue md rt =
set IR.materialsToLoad (md : rt ^. IR.materialsToLoad) rt
toggleTextDisplay :: TVar ImprovizUI -> IO ImprovizResponse
toggleTextDisplay ui = do
atomically $ modifyTVar ui IUI.toggleTextDisplay
let msg = "Text display toggled"
logInfo msg
return $ ImprovizOKResponse msg
updateExternalVar :: ImprovizEnv -> String -> Float -> IO ImprovizResponse
updateExternalVar env name value = do
atomically $ modifyTVar (env ^. I.externalVars) (M.insert name (Number value))
return $ ImprovizOKResponse $ name ++ " variable updated"
startHttpServer :: ImprovizEnv -> IO ThreadId
startHttpServer env =
let port = (env ^. I.config . C.serverPort)
settings = setPort port defaultSettings
options = Options { verbose = 0, settings = settings }
in do
logInfo $ "Improviz HTTP server listening on port " ++ show port
forkIO $ scottyOpts options $ do
get "/" $ text "SERVING"
get "/editor" $ do
html <-
liftIO
$ readFile
$ (env ^. I.config . C.assetsDirectory)
</> editorHtmlFilePath
raw $ pack html
post "/read/material" $ do
b <- body
resp <- liftIO $ updateMaterial env b
json resp
post "/read" $ do
b <- body
resp <- liftIO $ updateProgram env (unpack b)
json resp
post "/toggle/text" $ do
resp <- liftIO $ toggleTextDisplay (env ^. I.ui)
json resp
post "/vars/edit/:name" $ do
name <- param "name"
b <- body
case reads (unpack b) of
[(v, _)] -> do
resp <- liftIO $ updateExternalVar env name v
json resp
_ ->
json
$ ImprovizErrorResponse
$ name
++ " variable not updated. Value invalid"
| rumblesan/proviz | src/Server/Http.hs | bsd-3-clause | 4,979 | 0 | 22 | 2,135 | 1,091 | 551 | 540 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Prompt.Ssh
-- Copyright : (C) 2007 Andrea Rossato
-- License : BSD3
--
-- Maintainer : andrea.rossato@unibz.it
-- Stability : unstable
-- Portability : unportable
--
-- A ssh prompt for XMonad
--
-----------------------------------------------------------------------------
module XMonad.Prompt.Ssh
( -- * Usage
-- $usage
sshPrompt
) where
import XMonad
import XMonad.Util.Run
import XMonad.Prompt
import System.Directory
import System.Environment
import Control.Monad
import Data.Maybe
-- $usage
-- 1. In your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Prompt
-- > import XMonad.Prompt.Ssh
--
-- 2. In your keybindings add something like:
--
-- > , ((modm .|. controlMask, xK_s), sshPrompt defaultXPConfig)
--
-- Keep in mind, that if you want to use the completion you have to
-- disable the "HashKnownHosts" option in your ssh_config
--
-- For detailed instruction on editing the key binding see
-- "XMonad.Doc.Extending#Editing_key_bindings".
data Ssh = Ssh
instance XPrompt Ssh where
showXPrompt Ssh = "SSH to: "
commandToComplete _ c = c
nextCompletion _ = getNextCompletion
sshPrompt :: XPConfig -> X ()
sshPrompt c = do
sc <- io sshComplList
mkXPrompt Ssh c (mkComplFunFromList sc) ssh
ssh :: String -> X ()
ssh = runInTerm "" . ("ssh " ++ )
sshComplList :: IO [String]
sshComplList = uniqSort `fmap` liftM2 (++) sshComplListLocal sshComplListGlobal
sshComplListLocal :: IO [String]
sshComplListLocal = do
h <- getEnv "HOME"
s1 <- sshComplListFile $ h ++ "/.ssh/known_hosts"
s2 <- sshComplListConf $ h ++ "/.ssh/config"
return $ s1 ++ s2
sshComplListGlobal :: IO [String]
sshComplListGlobal = do
env <- getEnv "SSH_KNOWN_HOSTS" `catch` (\_ -> return "/nonexistent")
fs <- mapM fileExists [ env
, "/usr/local/etc/ssh/ssh_known_hosts"
, "/usr/local/etc/ssh_known_hosts"
, "/etc/ssh/ssh_known_hosts"
, "/etc/ssh_known_hosts"
]
case catMaybes fs of
[] -> return []
(f:_) -> sshComplListFile' f
sshComplListFile :: String -> IO [String]
sshComplListFile kh = do
f <- doesFileExist kh
if f then sshComplListFile' kh
else return []
sshComplListFile' :: String -> IO [String]
sshComplListFile' kh = do
l <- readFile kh
return $ map (getWithPort . takeWhile (/= ',') . concat . take 1 . words)
$ filter nonComment
$ lines l
sshComplListConf :: String -> IO [String]
sshComplListConf kh = do
f <- doesFileExist kh
if f then sshComplListConf' kh
else return []
sshComplListConf' :: String -> IO [String]
sshComplListConf' kh = do
l <- readFile kh
return $ map (!!1)
$ filter isHost
$ map words
$ lines l
where
isHost ws = take 1 ws == ["Host"] && length ws > 1
fileExists :: String -> IO (Maybe String)
fileExists kh = do
f <- doesFileExist kh
if f then return $ Just kh
else return Nothing
nonComment :: String -> Bool
nonComment [] = False
nonComment ('#':_) = False
nonComment ('|':_) = False -- hashed, undecodeable
nonComment _ = True
getWithPort :: String -> String
getWithPort ('[':str) = host ++ " -p " ++ port
where (host,p) = break (==']') str
port = case p of
']':':':x -> x
_ -> "22"
getWithPort str = str
| MasseR/xmonadcontrib | XMonad/Prompt/Ssh.hs | bsd-3-clause | 3,516 | 0 | 17 | 880 | 902 | 471 | 431 | 81 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module Control.Isomorphism.Partial.TH
( defineIsomorphisms
, defineIsomorphisms'
) where
----------------------------------------
-- SITE-PACKAGES
----------------------------------------
import Language.Haskell.TH ( lamE, tupP, appE, conE, varP, caseE
, match, conP, normalB, newName, clause
, funD, mkName, reify, varE, nameBase
, Info(..), Dec(..), Con(..), wildP, tupE
, Name, Q, MatchQ
)
import Control.Monad (replicateM)
import Data.List (find)
import Data.Char (toLower)
----------------------------------------
-- LOCAL
----------------------------------------
import Control.Isomorphism.Partial.Iso (Iso, unsafeMakeIso)
defineIsomorphisms :: Name -> Q [Dec]
defineIsomorphisms d = defineIsomorphisms' d (\(x:xs) -> (toLower x):xs)
defineIsomorphisms' :: Name -> (String -> String) -> Q [Dec]
defineIsomorphisms' d renameFun =
do info <- reify d
let cs = case info of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD _ _ _ _ cs _) -> cs
TyConI (NewtypeD _ _ _ _ c _) -> [c]
#else
TyConI (DataD _ _ _ cs _) -> cs
TyConI (NewtypeD _ _ _ c _) -> [c]
#endif
otherwise -> error $ show d ++
" neither denotes a data or newtype declaration. Found: " ++
show info
mapM (defFromCon (length cs > 1) renameFun) cs
defFromCon :: Bool -> (String -> String) -> Con -> Q Dec
defFromCon wc renameFun con@(NormalC n fields) = funCreation wc n (length fields) renameFun
defFromCon wc renameFun con@(RecC n fields) = funCreation wc n (length fields) renameFun
defFromCon wc renameFun con@(InfixC _ n _) = funCreation wc n 2 renameFun
defFromCon wc renameFun con@(ForallC _ _ _) = error $ "defineIsomorphisms not available for " ++
"existential data constructors"
funCreation :: Bool -> Name -> Int -> (String -> String) -> Q Dec
funCreation wc n nfields renameFun =
funD (mkName $ renameFun $ nameBase n)
[clause [] (normalB (isoFromCon (wildcard wc) n nfields)) []]
isoFromCon wildcard conName nfields =
do (paths, exprs) <- genPE nfields
dat <- newName "x"
let f = lamE [nested tupP paths]
[| Just $(foldl appE (conE conName) exprs) |]
let g = lamE [varP dat]
(caseE (varE dat) $
[ match (conP conName paths)
(normalB [| Just $(nested tupE exprs) |]) []
] ++ wildcard)
[| unsafeMakeIso $f $g |]
wildcard :: Bool -> [MatchQ]
wildcard True = [match (wildP) (normalB [| Nothing |]) []]
wildcard _ = []
genPE number = do
ids <- replicateM number (newName "x")
return (map varP ids, map varE ids)
checkInfix :: Con -> Bool
checkInfix (InfixC _ _ _) = False
checkInfix _ = True
nested tup [] = tup []
nested tup [x] = x
nested tup (x:xs) = tup [x, nested tup xs]
| skogsbaer/roundtrip | src/Control/Isomorphism/Partial/TH.hs | bsd-3-clause | 3,164 | 0 | 17 | 974 | 985 | 525 | 460 | 59 | 3 |
{-# language CPP #-}
-- | = Name
--
-- VK_NV_scissor_exclusive - device extension
--
-- == VK_NV_scissor_exclusive
--
-- [__Name String__]
-- @VK_NV_scissor_exclusive@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 206
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Contact__]
--
-- - Pat Brown
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_NV_scissor_exclusive] @nvpbrown%0A<<Here describe the issue or question you have about the VK_NV_scissor_exclusive extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2018-07-31
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Interactions and External Dependencies__]
-- None
--
-- [__Contributors__]
--
-- - Pat Brown, NVIDIA
--
-- - Jeff Bolz, NVIDIA
--
-- - Piers Daniell, NVIDIA
--
-- - Daniel Koch, NVIDIA
--
-- == Description
--
-- This extension adds support for an exclusive scissor test to Vulkan. The
-- exclusive scissor test behaves like the scissor test, except that the
-- exclusive scissor test fails for pixels inside the corresponding
-- rectangle and passes for pixels outside the rectangle. If the same
-- rectangle is used for both the scissor and exclusive scissor tests, the
-- exclusive scissor test will pass if and only if the scissor test fails.
--
-- == New Commands
--
-- - 'cmdSetExclusiveScissorNV'
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2',
-- 'Vulkan.Core10.Device.DeviceCreateInfo':
--
-- - 'PhysicalDeviceExclusiveScissorFeaturesNV'
--
-- - Extending 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo':
--
-- - 'PipelineViewportExclusiveScissorStateCreateInfoNV'
--
-- == New Enum Constants
--
-- - 'NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME'
--
-- - 'NV_SCISSOR_EXCLUSIVE_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.DynamicState.DynamicState':
--
-- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV'
--
-- == Issues
--
-- 1) For the scissor test, the viewport state must be created with a
-- matching number of scissor and viewport rectangles. Should we have the
-- same requirement for exclusive scissors?
--
-- __RESOLVED__: For exclusive scissors, we relax this requirement and
-- allow an exclusive scissor rectangle count that is either zero or equal
-- to the number of viewport rectangles. If you pass in an exclusive
-- scissor count of zero, the exclusive scissor test is treated as
-- disabled.
--
-- == Version History
--
-- - Revision 1, 2018-07-31 (Pat Brown)
--
-- - Internal revisions
--
-- == See Also
--
-- 'PhysicalDeviceExclusiveScissorFeaturesNV',
-- 'PipelineViewportExclusiveScissorStateCreateInfoNV',
-- 'cmdSetExclusiveScissorNV'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_NV_scissor_exclusive Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_NV_scissor_exclusive ( cmdSetExclusiveScissorNV
, PhysicalDeviceExclusiveScissorFeaturesNV(..)
, PipelineViewportExclusiveScissorStateCreateInfoNV(..)
, NV_SCISSOR_EXCLUSIVE_SPEC_VERSION
, pattern NV_SCISSOR_EXCLUSIVE_SPEC_VERSION
, NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME
, pattern NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (CommandBuffer)
import Vulkan.Core10.Handles (CommandBuffer(..))
import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer))
import Vulkan.Core10.Handles (CommandBuffer_T)
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetExclusiveScissorNV))
import Vulkan.Core10.FundamentalTypes (Rect2D)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetExclusiveScissorNV
:: FunPtr (Ptr CommandBuffer_T -> Word32 -> Word32 -> Ptr Rect2D -> IO ()) -> Ptr CommandBuffer_T -> Word32 -> Word32 -> Ptr Rect2D -> IO ()
-- | vkCmdSetExclusiveScissorNV - Set exclusive scissor rectangles
-- dynamically for a command buffer
--
-- = Description
--
-- The scissor rectangles taken from element i of @pExclusiveScissors@
-- replace the current state for the scissor index @firstExclusiveScissor@
-- + i, for i in [0, @exclusiveScissorCount@).
--
-- This command sets the exclusive scissor rectangles for subsequent
-- drawing commands when the graphics pipeline is created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV'
-- set in
-- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@.
-- Otherwise, this state is specified by the
-- 'PipelineViewportExclusiveScissorStateCreateInfoNV'::@pExclusiveScissors@
-- values used to create the currently active pipeline.
--
-- == Valid Usage
--
-- - #VUID-vkCmdSetExclusiveScissorNV-None-02031# The
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-exclusiveScissor exclusive scissor>
-- feature /must/ be enabled
--
-- - #VUID-vkCmdSetExclusiveScissorNV-firstExclusiveScissor-02034# The
-- sum of @firstExclusiveScissor@ and @exclusiveScissorCount@ /must/ be
-- between @1@ and
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxViewports@,
-- inclusive
--
-- - #VUID-vkCmdSetExclusiveScissorNV-firstExclusiveScissor-02035# If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @firstExclusiveScissor@ /must/ be @0@
--
-- - #VUID-vkCmdSetExclusiveScissorNV-exclusiveScissorCount-02036# If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @exclusiveScissorCount@ /must/ be @1@
--
-- - #VUID-vkCmdSetExclusiveScissorNV-x-02037# The @x@ and @y@ members of
-- @offset@ in each member of @pExclusiveScissors@ /must/ be greater
-- than or equal to @0@
--
-- - #VUID-vkCmdSetExclusiveScissorNV-offset-02038# Evaluation of
-- (@offset.x@ + @extent.width@) for each member of
-- @pExclusiveScissors@ /must/ not cause a signed integer addition
-- overflow
--
-- - #VUID-vkCmdSetExclusiveScissorNV-offset-02039# Evaluation of
-- (@offset.y@ + @extent.height@) for each member of
-- @pExclusiveScissors@ /must/ not cause a signed integer addition
-- overflow
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetExclusiveScissorNV-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
-- 'Vulkan.Core10.Handles.CommandBuffer' handle
--
-- - #VUID-vkCmdSetExclusiveScissorNV-pExclusiveScissors-parameter#
-- @pExclusiveScissors@ /must/ be a valid pointer to an array of
-- @exclusiveScissorCount@ 'Vulkan.Core10.FundamentalTypes.Rect2D'
-- structures
--
-- - #VUID-vkCmdSetExclusiveScissorNV-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetExclusiveScissorNV-commandBuffer-cmdpool# The
-- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was
-- allocated from /must/ support graphics operations
--
-- - #VUID-vkCmdSetExclusiveScissorNV-exclusiveScissorCount-arraylength#
-- @exclusiveScissorCount@ /must/ be greater than @0@
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
-- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
-- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> |
-- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+
-- | Primary | Both | Graphics |
-- | Secondary | | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_scissor_exclusive VK_NV_scissor_exclusive>,
-- 'Vulkan.Core10.Handles.CommandBuffer',
-- 'Vulkan.Core10.FundamentalTypes.Rect2D'
cmdSetExclusiveScissorNV :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer into which the command will be
-- recorded.
CommandBuffer
-> -- | @firstExclusiveScissor@ is the index of the first exclusive scissor
-- rectangle whose state is updated by the command.
("firstExclusiveScissor" ::: Word32)
-> -- | @pExclusiveScissors@ is a pointer to an array of
-- 'Vulkan.Core10.FundamentalTypes.Rect2D' structures defining exclusive
-- scissor rectangles.
("exclusiveScissors" ::: Vector Rect2D)
-> io ()
cmdSetExclusiveScissorNV commandBuffer firstExclusiveScissor exclusiveScissors = liftIO . evalContT $ do
let vkCmdSetExclusiveScissorNVPtr = pVkCmdSetExclusiveScissorNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetExclusiveScissorNVPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetExclusiveScissorNV is null" Nothing Nothing
let vkCmdSetExclusiveScissorNV' = mkVkCmdSetExclusiveScissorNV vkCmdSetExclusiveScissorNVPtr
pPExclusiveScissors <- ContT $ allocaBytes @Rect2D ((Data.Vector.length (exclusiveScissors)) * 16)
lift $ Data.Vector.imapM_ (\i e -> poke (pPExclusiveScissors `plusPtr` (16 * (i)) :: Ptr Rect2D) (e)) (exclusiveScissors)
lift $ traceAroundEvent "vkCmdSetExclusiveScissorNV" (vkCmdSetExclusiveScissorNV' (commandBufferHandle (commandBuffer)) (firstExclusiveScissor) ((fromIntegral (Data.Vector.length $ (exclusiveScissors)) :: Word32)) (pPExclusiveScissors))
pure $ ()
-- | VkPhysicalDeviceExclusiveScissorFeaturesNV - Structure describing
-- exclusive scissor features that can be supported by an implementation
--
-- = Members
--
-- This structure describes the following feature:
--
-- = Description
--
-- See
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#fragops-exclusive-scissor Exclusive Scissor Test>
-- for more information.
--
-- If the 'PhysicalDeviceExclusiveScissorFeaturesNV' structure is included
-- in the @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2',
-- it is filled in to indicate whether each corresponding feature is
-- supported. 'PhysicalDeviceExclusiveScissorFeaturesNV' /can/ also be used
-- in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to
-- selectively enable these features.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_scissor_exclusive VK_NV_scissor_exclusive>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceExclusiveScissorFeaturesNV = PhysicalDeviceExclusiveScissorFeaturesNV
{ -- | #features-exclusiveScissor# @exclusiveScissor@ indicates that the
-- implementation supports the exclusive scissor test.
exclusiveScissor :: Bool }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceExclusiveScissorFeaturesNV)
#endif
deriving instance Show PhysicalDeviceExclusiveScissorFeaturesNV
instance ToCStruct PhysicalDeviceExclusiveScissorFeaturesNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceExclusiveScissorFeaturesNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (exclusiveScissor))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_EXCLUSIVE_SCISSOR_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceExclusiveScissorFeaturesNV where
peekCStruct p = do
exclusiveScissor <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
pure $ PhysicalDeviceExclusiveScissorFeaturesNV
(bool32ToBool exclusiveScissor)
instance Storable PhysicalDeviceExclusiveScissorFeaturesNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceExclusiveScissorFeaturesNV where
zero = PhysicalDeviceExclusiveScissorFeaturesNV
zero
-- | VkPipelineViewportExclusiveScissorStateCreateInfoNV - Structure
-- specifying parameters controlling exclusive scissor testing
--
-- = Description
--
-- If the
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV'
-- dynamic state is enabled for a pipeline, the @pExclusiveScissors@ member
-- is ignored.
--
-- When this structure is included in the @pNext@ chain of
-- 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo', it defines
-- parameters of the exclusive scissor test. If this structure is not
-- included in the @pNext@ chain, it is equivalent to specifying this
-- structure with a @exclusiveScissorCount@ of @0@.
--
-- == Valid Usage
--
-- - #VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02027#
-- If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @exclusiveScissorCount@ /must/ be @0@ or @1@
--
-- - #VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02028#
-- @exclusiveScissorCount@ /must/ be less than or equal to
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxViewports@
--
-- - #VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-exclusiveScissorCount-02029#
-- @exclusiveScissorCount@ /must/ be @0@ or greater than or equal to
-- the @viewportCount@ member of
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPipelineViewportExclusiveScissorStateCreateInfoNV-sType-sType#
-- @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_scissor_exclusive VK_NV_scissor_exclusive>,
-- 'Vulkan.Core10.FundamentalTypes.Rect2D',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PipelineViewportExclusiveScissorStateCreateInfoNV = PipelineViewportExclusiveScissorStateCreateInfoNV
{ -- | @pExclusiveScissors@ is a pointer to an array of
-- 'Vulkan.Core10.FundamentalTypes.Rect2D' structures defining exclusive
-- scissor rectangles.
exclusiveScissors :: Vector Rect2D }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineViewportExclusiveScissorStateCreateInfoNV)
#endif
deriving instance Show PipelineViewportExclusiveScissorStateCreateInfoNV
instance ToCStruct PipelineViewportExclusiveScissorStateCreateInfoNV where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineViewportExclusiveScissorStateCreateInfoNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (exclusiveScissors)) :: Word32))
pPExclusiveScissors' <- ContT $ allocaBytes @Rect2D ((Data.Vector.length (exclusiveScissors)) * 16)
lift $ Data.Vector.imapM_ (\i e -> poke (pPExclusiveScissors' `plusPtr` (16 * (i)) :: Ptr Rect2D) (e)) (exclusiveScissors)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Rect2D))) (pPExclusiveScissors')
lift $ f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_EXCLUSIVE_SCISSOR_STATE_CREATE_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct PipelineViewportExclusiveScissorStateCreateInfoNV where
peekCStruct p = do
exclusiveScissorCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pExclusiveScissors <- peek @(Ptr Rect2D) ((p `plusPtr` 24 :: Ptr (Ptr Rect2D)))
pExclusiveScissors' <- generateM (fromIntegral exclusiveScissorCount) (\i -> peekCStruct @Rect2D ((pExclusiveScissors `advancePtrBytes` (16 * (i)) :: Ptr Rect2D)))
pure $ PipelineViewportExclusiveScissorStateCreateInfoNV
pExclusiveScissors'
instance Zero PipelineViewportExclusiveScissorStateCreateInfoNV where
zero = PipelineViewportExclusiveScissorStateCreateInfoNV
mempty
type NV_SCISSOR_EXCLUSIVE_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_NV_SCISSOR_EXCLUSIVE_SPEC_VERSION"
pattern NV_SCISSOR_EXCLUSIVE_SPEC_VERSION :: forall a . Integral a => a
pattern NV_SCISSOR_EXCLUSIVE_SPEC_VERSION = 1
type NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME = "VK_NV_scissor_exclusive"
-- No documentation found for TopLevel "VK_NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME"
pattern NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern NV_SCISSOR_EXCLUSIVE_EXTENSION_NAME = "VK_NV_scissor_exclusive"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_NV_scissor_exclusive.hs | bsd-3-clause | 22,552 | 0 | 18 | 3,939 | 2,522 | 1,541 | 981 | -1 | -1 |
module Oxymoron.Scene
( module Oxymoron.Scene.Attribute
, module Oxymoron.Scene.FragmentShader
, module Oxymoron.Scene.Material
, module Oxymoron.Scene.Mesh
, module Oxymoron.Scene.Program
, module Oxymoron.Scene.Renderable
, module Oxymoron.Scene.Uniform
, module Oxymoron.Scene.Varying
, module Oxymoron.Scene.VertexShader
) where
import Oxymoron.Scene.Attribute
import Oxymoron.Scene.FragmentShader
import Oxymoron.Scene.Material
import Oxymoron.Scene.Mesh
import Oxymoron.Scene.Program
import Oxymoron.Scene.Renderable
import Oxymoron.Scene.Uniform
import Oxymoron.Scene.Varying
import Oxymoron.Scene.VertexShader
| jfischoff/oxymoron | src/Oxymoron/Scene.hs | bsd-3-clause | 651 | 0 | 5 | 82 | 125 | 86 | 39 | 19 | 0 |
module Cauterize.Crucible.TesterOpts
( TesterOpts(..)
, testerOptions
) where
import Cauterize.Crucible.Prototypes
import Cauterize.Generate
import Control.Monad (liftM)
import Options.Applicative
import qualified Data.Text as T
data TesterOpts = TesterOpts
{ buildCmds :: [T.Text]
, runCmd :: T.Text
, schemaCount :: Integer
, instanceCount :: Integer
, schemaTypeCount :: Integer -- number of types
, schemaEncSize :: Integer -- maximum encoded size
, allowedPrototypes :: [PrototypeVariant]
} deriving (Show)
defaultSchemaCount, defaultInstanceCount :: Integer
defaultSchemaCount = 1
defaultInstanceCount = 100
-- Generate a number of schemas, insert their schemas and meta files into a
-- target generator, run the generator in the test loop, report the exit codes
-- from server and client as results.
--
-- Expanded tokens:
-- %s - the path to the specification file.
-- %d - the path to the working directory of the crucible command.
--
-- cauterize-test crucible --build-cmd="foo --schema=%s --output=%d/cmd"
-- --build-cmd="cd %d/cmd && cabal build"
-- --run-cmd="%d/dist/build/cmd/cmd"
-- --schema-count=5
-- --instance-count=100
-- --schema-size=50
testerOptions :: Parser TesterOpts
testerOptions = TesterOpts
<$> parseBuild
<*> parseRun
<*> parseSchemaCount
<*> parseInstanceCount
<*> parseSchemaTypeCount
<*> parseSchemaEncSize
<*> parseAllowedPrototypes
where
parseBuild = many $ option txt ( long "build-cmd"
<> metavar "BLDCMD"
<> help buildCmdHelp )
parseRun = option txt ( long "run-cmd"
<> metavar "RUNCMD"
<> help runCmdHelp )
parseSchemaCount = option auto ( long "schema-count"
<> metavar "SCMCNT"
<> value defaultSchemaCount
<> help schemaCountHelp )
parseInstanceCount = option auto ( long "instance-count"
<> metavar "INSCNT"
<> value defaultInstanceCount
<> help instanceCountHelp )
parseSchemaTypeCount = option auto ( long "type-count"
<> metavar "SCMSIZE"
<> value defaultMaximumTypes
<> help schemaSizeHelp )
parseSchemaEncSize = option auto ( long "enc-size"
<> metavar "ENCSIZE"
<> value defaultMaximumSize
<> help schemaSizeHelp )
parseAllowedPrototypes = option (str >>= parsePrototypeVariants . T.pack)
(long "prototypes"
<> metavar "PROTOTYPES"
<> value allPrototypeVariants
<> help allowedPrototypesHelp )
buildCmdHelp = "The command to build the generated test client. Can be specified more than once."
runCmdHelp = "The command to run the built test client. Can be specified more than once."
schemaCountHelp = "The number of schemas to test."
instanceCountHelp = "The number of instances of each schema to test."
schemaSizeHelp = "The number of types to generate in each schema."
allowedPrototypesHelp = concat [ "Which prototypes to include in schema generation. "
, "Define using a comma-separated list including only the following elements: "
, "array,combination,record,synonym,union,vector."
]
txt = liftM T.pack str
| cauterize-tools/crucible | lib/Cauterize/Crucible/TesterOpts.hs | bsd-3-clause | 3,875 | 0 | 12 | 1,404 | 513 | 280 | 233 | 65 | 1 |
{-# LANGUAGE MultiParamTypeClasses,
FlexibleInstances,
FlexibleContexts,
UndecidableInstances,
GADTs #-}
module Obsidian.GCDObsidian.Array ((!) -- pull array apply (index into)
,(!*) -- push array apply
, mkPullArray
, mkPushArray
, resize
, namedArray
, indexArray
, len
, globLen
, Array(..)
, Pushy
, PushyInternal
, pushGlobal
, push
, push' -- this is for "internal" use
, push'' -- this is for "internal" use
, P(..)
, block
, unblock
, GlobalArray(..)
, mkGlobalPushArray
, mkGlobalPullArray
, Pull(..)
, Push(..)
)where
import Obsidian.GCDObsidian.Exp
import Obsidian.GCDObsidian.Types
import Obsidian.GCDObsidian.Globs
import Obsidian.GCDObsidian.Program
import Data.List
import Data.Word
----------------------------------------------------------------------------
--
------------------------------------------------------------------------------
data Push a = Push {pushFun :: P (Exp Word32,a)}
data Pull a = Pull {pullFun :: Exp Word32 -> a}
{-
data Push ix a = Push {pushFun :: P (ix,a))
data Pull ix a = Pull {pullFun :: ix -> a))
data Dim1 = Dim1 Word32
data Dim2 = Dim2 Word32 Word32
data Dim3 = Dim3 Word32 Word32 Word32
data Array p a d = Array (p a) d
type PullArray a = Array (Pull Ix1D a) Dim1
type PullArray2D a = Array (Pull Ix2D a) Dim2
type PullArray3D a = Array (Pull Ix3D a) Dim3
type PushArray a = Array (Push Ix1D a) Dim1
type PushArray2D a = Array (Push Ix2D a) Dim2
type PushArray3D a = Array (Push Ix3D a) Dim3
What happens once someone tries to nest these..
PullArray3D (PullArray3D (Exp Int))
More things to consider here:
- Grid dimensions will be FIXED throughout the execution
of a kernel.
- Maybe it is better to Emulate the 2d and 3d blocks.
For example a single kernel might handle an array of size 256
and a at the same time a 16*16 Array2D. This means this kernel
needs to use 256 threads. But does it need 256 threads as 16*16 or 256*1.
Of course only one option is possible and either way leads to some extra arith.
(arr256[tid.y*16+tid.x] and arr16x16[tid.y][tid.x]) or
(arr256[tid.x] and arr16x16[tid.x `div` 16][tid.x `mod` 16]
- This can get more complicated.
A single kernel could operate on many different multidimensional arrays.
arr16x16 and arr4x12 for example. This would lead to things like
if (threadIdx.x < 12 && threadIdx.y < 4 ) {
arr4x12[threadIdx.y][threadIdx.x] = ...
}
arr16x16[threadIdx.y][threadIdx.x] = ...
- And even worse!!
arr16x16 and arr128x4
- Add 3D arrays to this mix and it gets very complicated.
-}
-- Arrays!
--data Array a = Array (Exp Word32 -> a) Word32
--data Array a = Array (Exp Word32 -> a) Word32
-- PUSHY ARRAYS!
type P a = (a -> Program ()) -> Program ()
data Array p a = Array (p a) Word32
type PushArray a = Array Push a
type PullArray a = Array Pull a
mkPushArray p n = Array (Push p) n
mkPullArray p n = Array (Pull p) n
resize (Array p n) m = Array p m
{-
To look at later !!!! (needs to be a newtype though!
instance Monad P where
return a = P $ \k -> k a
(>>=) (P m) f = P $ \k -> m (\a -> runP (f a) k)
instance Functor P where
...
instance Applicative P where
...
-}
-- data ArrayP a = ArrayP (P (Exp Word32, a)) Word32
-- data ArrayP a = ArrayP ((Exp Word32 -> a -> Program ()) -> Program ()) Word32
-- pushApp (ArrayP func n) a = func a
-- TODO: Do you need (Exp e) where there is only e ?
class PushyInternal a where
push' :: Word32 -> a e -> Array Push e
push'' :: Word32 -> a e -> Array Push e
instance PushyInternal (Array Pull) where
push' m (Array (Pull ixf) n) =
Array (Push (\func -> ForAll (\i -> foldr1 (*>*)
[func (ix,a)
| j <- [0..m-1],
let ix = (i*(fromIntegral m) + (fromIntegral j)),
let a = ixf ix
]) (n `div` m))) n
push'' m (Array (Pull ixf) n) =
Array (Push (\func -> ForAll (\i -> foldr1 (*>*)
[func (ix,a)
| j <- [0..m-1],
let ix = (i+((fromIntegral ((n `div` m) * j)))),
let a = ixf ix
]) (n `div` m))) n
class Pushy a where
push :: a e -> Array Push e
instance Pushy (Array Push) where
push = id
instance Pushy (Array Pull) where
push (Array (Pull ixf) n) = Array (Push (\func -> ForAll (\i -> func (i,ixf i)) n)) n
class PushGlobal a where
pushGlobal :: a e -> GlobalArray Push e
instance PushGlobal (GlobalArray Pull) where
pushGlobal (GlobalArray (Pull ixf) n) =
GlobalArray (Push (\func -> ForAllGlobal (\i -> func (i,ixf i)) n )) n
----------------------------------------------------------------------------
--
namedArray name n = mkPullArray (\ix -> index name ix) n
indexArray n = mkPullArray (\ix -> ix) n
class Indexible a e where
access :: a e -> Exp Word32 -> e
instance Indexible (Array Pull) a where
access (Array ixf _) ix = pullFun ixf ix
class PushApp a where
papp :: a e -> ((Exp Word32,e) -> Program ()) -> Program ()
instance PushApp (Array Push) where
papp (Array (Push f) n) a = f a
instance PushApp (GlobalArray Push) where
papp (GlobalArray (Push f) n) a = f a
class Len a where
len :: a e -> Word32
instance Len (Array p) where
len (Array _ n) = n
infixl 9 !
(!) :: Indexible a e => a e -> Exp Word32 -> e
(!) = access
infixl 9 !*
(!*) :: PushApp a => a e -> ((Exp Word32,e) -> Program ()) -> Program ()
(!*) p a = papp p a
------------------------------------------------------------------------------
-- Show
instance Show a => Show (Array Pull a) where
show arr | len arr <= 10 = "[" ++
(concat . intersperse ",")
[show (arr ! (fromIntegral i)) | i <- [0..len arr-1]] ++
"]"
| otherwise = "[" ++
(concat . intersperse ",")
[show (arr ! (fromIntegral i)) | i <- [0..3]] ++
"...]"
--------------------------------------------------------------------------
-- Global array related stuff
-- This is also quite directly influencing "coordination"
-- of kernels.
data GlobalArray p a = GlobalArray (p a) (Exp Word32)
mkGlobalPushArray p n = GlobalArray (Push p) n
mkGlobalPullArray f n = GlobalArray (Pull f) n
instance Functor (GlobalArray Pull) where
fmap f (GlobalArray (Pull g) n) = GlobalArray (Pull (f . g)) n
instance Indexible (GlobalArray Pull) a where
access (GlobalArray ixf _) ix = pullFun ixf ix
globLen (GlobalArray _ n) = n
----------------------------------------------------------------------------
-- Block and unblock
-- TODO: These should be somewhere else !!!
-- TODO: Should these "Be" at all ?
block :: Word32 -> GlobalArray Pull a -> Array Pull a
block blockSize glob = Array (Pull newFun) blockSize
where
newFun ix = (pullFun pull) ((bid * (fromIntegral blockSize)) + ix)
(GlobalArray pull n) = glob
bid = BlockIdx X -- variable "bid"
nblks = GridDim X -- variable "gridDim.x"
unblock :: Array Push a -> GlobalArray Push a
unblock array = GlobalArray newFun (nblks * (fromIntegral n))
-- from a kernel's point of view the arrays is (nblks * n) long
where
(Array (Push fun) n) = array
newFun = Push (\func -> fun (\(i,a) -> func (bid * (fromIntegral n)+i,a)))
| svenssonjoel/GCDObsidian | Obsidian/GCDObsidian/Array.hs | bsd-3-clause | 8,675 | 0 | 28 | 3,137 | 1,955 | 1,037 | 918 | 122 | 1 |
module SimulationDSL.Language.UninferredEquations
( UninferredEquations
, emptyUninferredEquations
, addUninferredEquation
, addInitialCondition
, uninferredEquation
, uninferredEquations
, inferredEquations
) where
import Data.Maybe
import qualified Data.Map as M
import SimulationDSL.Data.Value
import SimulationDSL.Data.ExpType
import SimulationDSL.Language.Exp
import SimulationDSL.Language.Equation
import SimulationDSL.Language.Equations hiding ( addInitialCondition )
import qualified SimulationDSL.Language.Equations as E ( addInitialCondition )
import SimulationDSL.Language.UninferredEquation
import SimulationDSL.Language.InitialCondition
data UninferredEquations = UninferredEquations (M.Map String UninferredEquation)
(M.Map String InitialCondition)
emptyUninferredEquations :: UninferredEquations
emptyUninferredEquations = UninferredEquations M.empty M.empty
uninferredEquation :: UninferredEquations -> String -> UninferredEquation
uninferredEquation (UninferredEquations x _) symbol
= case M.lookup symbol x of
Just x -> x
Nothing -> error "uninferredEquation: symbol not found"
uninferredEquations :: UninferredEquations -> [(String,UninferredEquation)]
uninferredEquations (UninferredEquations x _) = M.assocs x
addUninferredEquation :: UninferredEquations -> String -> Maybe ExpType -> Exp -> UninferredEquations
addUninferredEquation (UninferredEquations eqs ics) symbol t exp
= UninferredEquations eqs' ics
where eqs' = M.insert symbol (makeUninferredEquation symbol t exp) eqs
addInitialCondition :: UninferredEquations -> String -> InitialCondition -> UninferredEquations
addInitialCondition (UninferredEquations eqs ics) symbol ic
= UninferredEquations eqs ics'
where ics' = M.insert symbol ic ics
inferredEquations :: UninferredEquations -> Equations
inferredEquations eqs@(UninferredEquations xs ys) = Equations xs' ys
where xs' = M.map (inferEquation eqs) xs
inferEquation :: UninferredEquations -> UninferredEquation -> Equation
inferEquation eqs eq = makeEquation symbol t' exp
where symbol = uninferredEquationSymbol eq
t = uninferredEquationType eq
exp = uninferredEquationExp eq
t' = case t of
Just x -> x
Nothing -> inferExpType eqs symbol exp
inferExpType :: UninferredEquations -> String -> Exp -> ExpType
inferExpType eqs s0 (Integral exp) = inferExpType eqs s0 exp
inferExpType _ _ (Constant (ValueScalar _)) = ExpTypeScalar
inferExpType _ _ (Constant (ValueVector _)) = ExpTypeVector
inferExpType eqs s0 (Var symbol)
| isJust t = fromJust t
| symbol == s0 = error "inferExpType: circular reference"
| otherwise = inferExpType eqs s0 exp
where t = uninferredEquationType $ uninferredEquation eqs symbol
exp = uninferredEquationExp $ uninferredEquation eqs symbol
inferExpType eqs s0 (Var' symbol)
| isJust t = fromJust t
| symbol == s0 = error "inferExpType: circular reference"
| otherwise = inferExpType eqs s0 exp
where t = uninferredEquationType $ uninferredEquation eqs symbol
exp = uninferredEquationExp $ uninferredEquation eqs symbol
inferExpType eqs s0 (Add x y)
= case (inferExpType eqs s0 x, inferExpType eqs s0 y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeVector) -> ExpTypeVector
otherwise -> error "inferExpType: invalid operand(s)"
inferExpType eqs s0 (Sub x y)
= case (inferExpType eqs s0 x, inferExpType eqs s0 y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeVector) -> ExpTypeVector
otherwise -> error "inferExpType: invalid operand(s)"
inferExpType eqs s0 (Mul x y)
= case (inferExpType eqs s0 x, inferExpType eqs s0 y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeScalar, ExpTypeVector) -> ExpTypeVector
(ExpTypeVector, ExpTypeScalar) -> ExpTypeVector
otherwise -> error "inferExpType: invalid operand(s)"
inferExpType eqs s0 (Div x y)
= case (inferExpType eqs s0 x, inferExpType eqs s0 y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeScalar) -> ExpTypeVector
otherwise -> error "inferExpType: invalid operand(s)"
inferExpType eqs s0 (Norm x)
= case inferExpType eqs s0 x of
ExpTypeVector -> ExpTypeScalar
otherwise -> error "inferExpType: invalid operand"
inferExpType eqs s0 (Sigma exp) = inferExpType eqs s0 exp
| takagi/SimulationDSL | SimulationDSL/SimulationDSL/Language/UninferredEquations.hs | bsd-3-clause | 4,612 | 0 | 10 | 945 | 1,192 | 613 | 579 | 90 | 11 |
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC
import Test.Tasty.SmallCheck as SC
import qualified LexerTest as LexT
import qualified ParserTest as ParserT
import Data.List
import Data.Ord
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [lexerUnitTests, parserUnitTests]
lexerTests :: TestTree
lexerTests = testGroup "Tests" [lexerUnitTests]
parserTests :: TestTree
parserTests = testGroup "Tests" [parserUnitTests]
properties :: TestTree
properties = testGroup "Properties" [scProps, qcProps]
scProps = testGroup "(checked by SmallCheck)"
[ SC.testProperty "sort == sort . reverse" $
\list -> sort (list :: [Int]) == sort (reverse list)
, SC.testProperty "Fermat's little theorem" $
\x -> ((x :: Integer)^7 - x) `mod` 7 == 0
-- the following property does not hold
, SC.testProperty "Fermat's last theorem" $
\x y z n ->
(n :: Integer) >= 3 SC.==> x^n + y^n /= (z^n :: Integer)
]
qcProps = testGroup "(checked by QuickCheck)"
[ QC.testProperty "sort == sort . reverse" $
\list -> sort (list :: [Int]) == sort (reverse list)
, QC.testProperty "Fermat's little theorem" $
\x -> ((x :: Integer)^7 - x) `mod` 7 == 0
-- the following property does not hold
, QC.testProperty "Fermat's last theorem" $
\x y z n ->
(n :: Integer) >= 3 QC.==> x^n + y^n /= (z^n :: Integer)
]
unitTests = testGroup "Unit tests"
[ testCase "List comparison (different length)" $
[1, 2, 3] `compare` [1,2] @?= GT
-- the following test does not hold
, testCase "List comparison (same length)" $
[1, 2, 3] `compare` [1,2,2] @?= LT
]
lexerUnitTests = testGroup "Lexer unit tests" LexT.testCases
parserUnitTests = testGroup "Parser unit tests" ParserT.testCases
| sukwon0709/mysql | tests/test.hs | bsd-3-clause | 1,869 | 6 | 14 | 452 | 614 | 325 | 289 | -1 | -1 |
module Data.RDF.Graph.HashMapS_Test (triplesOf',uniqTriplesOf',empty',mkRdf') where
import Data.RDF.Types
import Data.RDF.Graph.HashMapS (HashMapS)
import Data.RDF.GraphTestUtils
import qualified Data.Map as Map
import Control.Monad
import Test.QuickCheck
instance Arbitrary HashMapS where
arbitrary = liftM3 mkRdf arbitraryTs (return Nothing) (return $ PrefixMappings Map.empty)
--coarbitrary = undefined
empty' :: HashMapS
empty' = empty
mkRdf' :: Triples -> Maybe BaseUrl -> PrefixMappings -> HashMapS
mkRdf' = mkRdf
triplesOf' :: HashMapS -> Triples
triplesOf' = triplesOf
uniqTriplesOf' :: HashMapS -> Triples
uniqTriplesOf' = uniqTriplesOf
| jutaro/rdf4h | testsuite/tests/Data/RDF/Graph/HashMapS_Test.hs | bsd-3-clause | 657 | 0 | 10 | 84 | 168 | 99 | 69 | 17 | 1 |
{-#LANGUAGE OverloadedStrings#-}
{-
Project name: Remove rRNA from annotated read count list.
Min Zhang
Date: Oct 21, 2015
Version: v.0.1.0
README:
#Biomart Homo sapiens genes (GRCh38.p3)
#Filters:Mt_rRNA, Mt_tRNA, rRNA, snoRNA, snRNA
-}
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as TextIO
import qualified Data.Char as C
import Control.Applicative
import qualified Data.List as L
import Control.Monad (fmap)
import Data.Ord (comparing)
import Data.Function (on)
import qualified Safe as S
import qualified Data.Set as Set
import qualified Data.Map as M
import qualified Data.Maybe as Maybe
import qualified Data.Foldable as F (all)
import Data.Traversable (sequenceA)
import qualified System.IO as IO
import System.Environment
import System.Directory
import MyText
import MyTable
import Util
hg38 = do
input <- drop 3 <$> smartTable "/Users/minzhang/Documents/private_git/fourseq/share/genome/hg38.rrna.txt"
return $ Set.fromList $ map last input
hg19refseq =
let inputpath = "/Users/minzhang/Documents/private_git/fourseq/share/genome/refseq_hg19_geneName_symbol.txt"
in
smartTable inputpath >>= return . Set.fromList . map last . tail
{-
main = do
[inputPath, outputPath] <- getArgs
hg38rRNAset <- hg38
input <- smartTable inputPath
let header = head input
let body = filter (\x->not $ Set.member (head x) hg38rRNAset) (tail input)
let output = header : body
TextIO.writeFile outputPath (T.unlines (map untab output))
-}
-- include the genes in the hg19refseq
main = do
[inputPath, outputPath] <- getArgs
hg19genesym <- hg19refseq
input <- smartTable inputPath
let header = head input
let body = filter (\x->Set.member (head x) hg19genesym) (tail input)
let output = header : body
TextIO.writeFile outputPath (T.unlines (map untab output))
| Min-/fourseq | src/utils/RemoverRNA.hs | bsd-3-clause | 1,822 | 3 | 15 | 284 | 372 | 205 | 167 | 35 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.OrgMode.Parse.Attoparsec.Time
-- Copyright : © 2014 Parnell Springmeyer
-- License : All Rights Reserved
-- Maintainer : Parnell Springmeyer <parnell@digitalmentat.com>
-- Stability : stable
--
-- Parsing combinators for org-mode timestamps; both active and
-- inactive.
----------------------------------------------------------------------------
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
module Data.OrgMode.Parse.Attoparsec.Time
( parsePlannings
, parseClock
, parseTimestamp
)
where
import Control.Applicative
import Data.Attoparsec.Combinator as Attoparsec
import Data.Attoparsec.Text
import Data.Attoparsec.Types as Attoparsec (Parser)
import Data.Functor (($>))
import Data.Maybe (listToMaybe)
import Data.Semigroup ((<>))
import Data.Text (Text)
import Data.Thyme.Format (buildTime, timeParser)
import Data.Thyme.LocalTime (Hours, Minutes)
import Prelude hiding (repeat)
import System.Locale (defaultTimeLocale)
import Data.OrgMode.Types
import qualified Data.OrgMode.Parse.Attoparsec.Util as Util
import qualified Data.Attoparsec.ByteString as Attoparsec.ByteString
import qualified Data.ByteString.Char8 as BS
import qualified Data.Text as Text
-- | Parse a planning line.
--
-- Plannings inhabit a heading section and are formatted as a keyword
-- and a timestamp. There can be more than one, but they are all on
-- the same line e.g:
--
-- > DEADLINE: <2015-05-10 17:00> CLOSED: <2015-04-1612:00>
parsePlannings :: Attoparsec.Parser Text [Planning]
parsePlannings = many' (skipSpace *> planning <* Util.skipOnlySpace)
where
planning = Planning <$> keyword <* char ':' <*> (skipSpace *> parseTimestamp)
keyword =
choice [ string "SCHEDULED" $> SCHEDULED
, string "DEADLINE" $> DEADLINE
, string "CLOSED" $> CLOSED
]
-- | Parse a clock line.
--
-- A heading's section contains one line per clock entry. Clocks may
-- have a timestamp, a duration, both, or neither e.g.:
--
-- > CLOCK: [2014-12-10 Fri 2:30]--[2014-12-10 Fri 10:30] => 08:00
parseClock :: Attoparsec.Parser Text Clock
parseClock = Clock <$> ((,) <$> (skipSpace *> string "CLOCK: " *> ts) <*> dur)
where
ts = optional parseTimestamp
dur = optional (string " => " *> skipSpace *> parseHM)
-- | Parse a timestamp.
--
-- Timestamps may be timepoints or timeranges, and they indicate
-- whether they are active or closed by using angle or square brackets
-- respectively.
--
-- Time ranges are formatted by infixing two timepoints with a double
-- hyphen, @--@; or, by appending two @hh:mm@ timestamps together in a
-- single timepoint with one hyphen @-@.
--
-- Each timepoint includes an optional repeater flag and an optional
-- delay flag.
parseTimestamp :: Attoparsec.Parser Text Timestamp
parseTimestamp = do
(ts1, tsb1, act) <- transformBracketedDateTime <$> parseBracketedDateTime
blk2 <- fmap (fmap transformBracketedDateTime) optionalBracketedDateTime
-- TODO: refactor this case logic
case (tsb1, blk2) of
(Nothing, Nothing) ->
pure (Timestamp ts1 act Nothing)
(Nothing, Just (ts2, Nothing, _)) ->
pure (Timestamp ts1 act (Just ts2))
(Nothing, Just _) ->
-- TODO: improve error message with an example of what would
-- cause this case
fail "Illegal time range in second timerange timestamp"
(Just (h',m'), Nothing) ->
pure (Timestamp ts1 act
(Just $ ts1 {hourMinute = Just (h',m')
,repeater = Nothing
,delay = Nothing}))
(Just _, Just _) ->
-- TODO: improve error message with an example of what would
-- cause thise case
fail "Illegal mix of time range and timestamp range"
where
optionalBracketedDateTime =
optional (string "--" *> parseBracketedDateTime)
-- | Parse a single time part.
--
-- > [2015-03-27 Fri 10:20 +4h]
--
-- Returns:
--
-- - The basic timestamp
-- - Whether there was a time interval in place of a single time
-- (this will be handled upstream by parseTimestamp)
-- - Whether the time is active or inactive
parseBracketedDateTime :: Attoparsec.Parser Text BracketedDateTime
parseBracketedDateTime = do
openingBracket <- char '<' <|> char '['
brkDateTime <- BracketedDateTime <$>
parseDate <* skipSpace
<*> optionalParse parseDay
<*> optionalParse parseTime'
<*> maybeListParse parseRepeater
<*> maybeListParse parseDelay
<*> pure (activeBracket openingBracket)
closingBracket <- char '>' <|> char ']'
finally brkDateTime openingBracket closingBracket
where
optionalParse p = optional p <* skipSpace
maybeListParse p = listToMaybe <$> many' p <* skipSpace
activeBracket ((=='<') -> active) =
if active then Active else Inactive
finally bkd ob cb | complementaryBracket ob /= cb =
-- TODO: improve this error message with an
-- example of what would cause this case
fail "mismatched timestamp brackets"
| otherwise = return bkd
complementaryBracket '<' = '>'
complementaryBracket '[' = ']'
complementaryBracket x = x
-- | Given a @BracketedDateTime@ data type, transform it into a triple
-- composed of a @DateTime@, possibly a @(Hours, Minutes)@ tuple
-- signifying the end of a timestamp range, and a boolean indic
transformBracketedDateTime :: BracketedDateTime
-> (DateTime, Maybe (Hours, Minutes), ActiveState)
transformBracketedDateTime BracketedDateTime{..} =
maybe dateStamp timeStamp timePart
where
defdt = DateTime datePart dayNamePart Nothing repeat delayPart
timeStamp (AbsoluteTime (hs,ms)) =
( defdt { hourMinute = Just (hs,ms) }
, Nothing
, activeState
)
timeStamp (TimeStampRange (t0,t1)) =
( defdt { hourMinute = Just t0 }
, Just t1
, activeState
)
dateStamp = (defdt, Nothing, activeState)
-- | Parse a day name in the same way as org-mode does.
--
-- The character set (@]+0123456789>\r\n -@) is based on a part of a
-- regexp named @org-ts-regexp0@ found in org.el.
parseDay :: Attoparsec.Parser Text Text
parseDay = Text.pack <$> some (Attoparsec.satisfyElem isDayChar)
where
isDayChar :: Char -> Bool
isDayChar = (`notElem` nonDayChars)
-- | This is based on: @[^]+0-9>\r\n -]+@, a part of a regexp
-- named org-ts-regexp0 in org.el.
nonDayChars = "]+0123456789>\r\n -" :: String
-- | Parse the time-of-day part of a time part, as a single point or a
-- time range.
parseTime' :: Attoparsec.Parser Text TimePart
parseTime' = stampRng <|> stampAbs
where
stampRng = do
beg <- parseHM <* char '-'
end <- parseHM
pure $ TimeStampRange (beg,end)
stampAbs = AbsoluteTime <$> parseHM
-- | Parse the YYYY-MM-DD part of a time part.
parseDate :: Attoparsec.Parser Text YearMonthDay
parseDate = consumeDate >>= either bad good . dateParse
where
bad e = fail ("failure parsing date: " <> e)
good t = pure (buildTime t)
consumeDate = manyTill anyChar (char ' ')
dateParse = Attoparsec.ByteString.parseOnly dpCombinator . BS.pack
dpCombinator = timeParser defaultTimeLocale "%Y-%m-%d"
-- | Parse a single @HH:MM@ point.
parseHM :: Attoparsec.Parser Text (Hours, Minutes)
parseHM = (,) <$> decimal <* char ':' <*> decimal
-- | Parse the Timeunit part of a delay or repeater flag.
parseTimeUnit :: Attoparsec.Parser Text TimeUnit
parseTimeUnit =
choice [ char 'h' $> UnitHour
, char 'd' $> UnitDay
, char 'w' $> UnitWeek
, char 'm' $> UnitMonth
, char 'y' $> UnitYear
]
-- | Parse a repeater flag, e.g. @.+4w@, or @++1y@.
parseRepeater :: Attoparsec.Parser Text Repeater
parseRepeater =
Repeater
<$> choice
[ string "++" $> RepeatCumulate
, char '+' $> RepeatCatchUp
, string ".+" $> RepeatRestart
]
<*> decimal
<*> parseTimeUnit
-- | Parse a delay flag, e.g. @--1d@ or @-2w@.
parseDelay :: Attoparsec.Parser Text Delay
parseDelay =
Delay
<$> choice
[ string "--" $> DelayFirst
, char '-' $> DelayAll
]
<*> decimal
<*> parseTimeUnit
| digitalmentat/orgmode-parse | src/Data/OrgMode/Parse/Attoparsec/Time.hs | bsd-3-clause | 8,707 | 0 | 18 | 2,206 | 1,596 | 887 | 709 | 137 | 5 |
module Math.IRT.MLE.Truncated
( DF (..)
, MLEResult (..)
, mleEst
) where
import Data.Default.Class
import Statistics.Distribution
import Math.IRT.Internal.Distribution
import Math.IRT.Internal.LogLikelihood
import Math.IRT.MLE.Internal.Generic
data DF = DF { steps :: !Int
, thetaEstimate :: !Double
, lower_bound :: !Double
, upper_bound :: !Double }
instance Default DF where
def = DF 10 0.0 (-3.5) 3.5
mleEst :: (Distribution d, ContDistr d, DensityDeriv d, LogLikelihood d) => DF -> [Bool] -> [d] -> MLEResult
mleEst (DF n th lb ub) rs params =
let res = generic_mleEst rs params n th
in res { theta = min ub $ max lb $ theta res }
| argiopetech/irt | Math/IRT/MLE/Truncated.hs | bsd-3-clause | 714 | 0 | 11 | 180 | 243 | 137 | 106 | 27 | 1 |
-- mpoly.hs
module Math.MPoly (MPoly (..), TermOrder (..), VarSet(..),
x, y, z, s, t, u, v, w, a, b, c, d, constMP,
x0, x1, x2, x3, x_, monomial,
paramsMP, termsMP, termOrderMP, varsMP,
toMonicMP, degMP,
changeTermOrder,
quotRemMP, lt, lc, lp, ltMP,
dividesTm, properlyDividesTm, divTm, lcmTm, gcdTm, degTm, (*/),
(/%), (%%), isReducibleMP,
toHomogeneous, fromHomogeneous,
evalMP, substMP) where
import List(intersperse)
import Math.QQ
import Math.FF
import Math.MergeSort
import Math.MathsPrimitives ( ($+), ($-), ($.) )
infix 5 /%, %%
-- MULTIVARIATE POLYNOMIALS
data TermOrder = Lex | Glex | Grevlex | Elim Int | Elimv [Int] deriving (Eq, Show)
data VarSet = Xyz | Xi deriving (Eq, Show)
data MPoly a = MP (TermOrder, VarSet) [Term a]
-- ACCESSOR FUNCTIONS
paramsMP (MP params _) = params
termsMP (MP _ terms) = terms
termOrderMP (MP (termOrder, _) _) = termOrder
varsMP (MP (_, vars) _) = vars
-- PRE-DEFINED VARIABLES
x = MP (Grevlex, Xyz) [(Q 1 1, [1])]
y = MP (Grevlex, Xyz) [(Q 1 1, [0,1])]
z = MP (Grevlex, Xyz) [(Q 1 1, [0,0,1])]
s = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,1])]
t = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,1])]
u = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,1])]
v = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,1])]
w = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,0,1])]
a = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,0,0,1])]
b = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,0,0,0,1])]
c = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,0,0,0,0,1])]
d = MP (Grevlex, Xyz) [(Q 1 1, [0,0,0,0,0,0,0,0,0,0,0,1])]
constMP c = MP (Grevlex, Xyz) [(c,[])]
-- Normally use x1.., and reserve x0 for dealing with homogeneous case
-- xvar i = MP Grevlex Xi [(Q 1 1, replicate i 0 ++ [1])]
x_ i = MP (Grevlex, Xi) [(Q 1 1, replicate i 0 ++ [1])]
x0 = MP (Grevlex, Xi) [(Q 1 1, [1])]
x1 = MP (Grevlex, Xi) [(Q 1 1, [0,1])]
x2 = MP (Grevlex, Xi) [(Q 1 1, [0,0,1])]
x3 = MP (Grevlex, Xi) [(Q 1 1, [0,0,0,1])]
monomial as = MP (Grevlex, Xi) [(Q 1 1, 0:as)]
-- POWER PRODUCTS
-- for example x^3 y^2 is represented as [3,2]
type PowerProduct = [Int]
-- we allow PP lists of unequal lengths, so need our own version of (==)
eqPP as bs = all (==0) (as $- bs)
multPP as bs = as $+ bs
dividesPP as bs = all (>=0) (bs $- as)
divPP as bs = as $- bs
gcdPP as [] = []
gcdPP [] bs = []
gcdPP (a:as) (b:bs) = min a b : gcdPP as bs
lcmPP as [] = as
lcmPP [] bs = bs
lcmPP (a:as) (b:bs) = max a b : lcmPP as bs
-- TERMS
-- for example, 3xy is represented as (3,[1,1])
-- !! It might be better to go directly to power products, and reduce our use of terms
type Term a = (a, PowerProduct)
eqTm (c,as) (d,bs) = c == d && as `eqPP` bs
multTm (c,as) (d,bs) = (c*d, multPP as bs)
dividesTm (_,as) (_,bs) = dividesPP as bs
-- properlyDividesTm t@(_,as) u@(_,bs) = dividesTm t u && sum as < sum bs
properlyDividesTm (_,as) (_,bs) = dividesPP as bs && not (eqPP as bs)
divTm (c,as) (d,bs) = (c/d, divPP as bs)
lcmTm (c,as) (d,bs) = (c*d, lcmPP as bs) -- !! the c*d here is arbitrary
gcdTm (c,as) (_,bs) = (c/c, gcdPP as bs)
degTm (_,as) = sum as
-- TERM ORDERINGS
isGraded Grevlex = True
isGraded Glex = True
isGraded _ = False
type TermOrdering a = Term a -> Term a -> Bool
-- in practice, term orderings always ignore the coefficients and only use the PowerProduct
lexgt (_,as) (_,bs) =
let ds = dropWhile (==0) (as $- bs)
in if null ds then False else head ds > 0
-- ie first non-zero difference is positive
revlexgt (_,as) (_,bs) =
let ds = dropWhile (==0) (reverse (as $- bs))
in if null ds then False else head ds < 0
-- ie last non-zero difference is negative
-- convert an ungraded term ordering into a graded term ordering
gradedgt :: TermOrdering a -> TermOrdering a
gradedgt termordgt t u =
degt > degu ||
(degt == degu && termordgt t u)
where
degt = degTm t
degu = degTm u
glexgt :: TermOrdering a
glexgt = gradedgt lexgt
grevlexgt :: TermOrdering a
grevlexgt = gradedgt revlexgt
-- Elimination order - Cox et al, Ideals, Varieties and Algorithms
elim l t@(_,as) u@(_,bs) = sumlas > sumlbs || (sumlas == sumlbs && grevlexgt t u)
where
sumlas = sum (take l as)
sumlbs = sum (take l bs)
elimv vs t@(_,as) u@(_,bs) = sumvas > sumvbs || (sumvas == sumvbs && grevlexgt t u)
where
sumvas = vs $. as
sumvbs = vs $. bs
-- collectTerms :: TermOrdering -> [Term] -> [Term]
collectTerms order f = doCollectTerms (mergeSort' order f)
where
doCollectTerms [] = []
doCollectTerms (t@(c,as):[])
| c == 0 = []
| otherwise = t:[]
doCollectTerms (t1@(c,as):t2@(d,bs):ts)
| c == 0 = doCollectTerms (t2:ts)
| as `eqPP` bs = doCollectTerms ((c+d,as):ts)
| otherwise = t1 : doCollectTerms (t2:ts)
termOrderToFn to = case to of
Lex -> lexgt
Glex -> glexgt
Grevlex -> grevlexgt
Elim l -> elim l
Elimv vs -> elimv vs
termOrderFn f = termOrderToFn (termOrderMP f)
-- EQ INSTANCE
instance Eq a => Eq (MPoly a) where
MP _ [] == MP _ [] = True
MP _ [(c,[])] == MP _ [(d,[])] = c == d
MP params ts == MP params' ts' = params == params' && length ts == length ts' && and (zipWith eqTm ts ts')
-- ORD INSTANCE
instance (Eq a, Ord a) => Ord (MPoly a) where
compare f g
| paramsMP f /= paramsMP g = error "MPoly.compare: parameter mismatch"
| otherwise = doCompare (termOrderFn f) (termsMP f) (termsMP g)
doCompare _ [] [] = EQ
doCompare _ _ [] = GT
doCompare _ [] _ = LT
doCompare termord (t@(c,as):ts) (u@(d,bs):us) =
if eqPP as bs
then case compare c d of
LT -> LT
GT -> GT
EQ -> doCompare termord ts us
else if termord t u then GT else LT
-- SHOW INSTANCE
instance (Show a, Num a) => Show (MPoly a) where
show f =
let vars = case varsMP f of
Xyz -> ["x", "y", "z", "s", "t", "u", "v", "w", "a", "b", "c", "d"] ++ map (:[]) ['e'..'r']
Xi -> ["x" ++ show i | i <- [0..]]
in showTerms vars (termsMP f)
-- showTerms vars ts = concat (intersperse "+" (map (showTerm vars) ts))
showTerms _ [] = "0"
showTerms vars ts = foldl1 linkTerms (map (showTerm vars) ts)
where linkTerms t u = if head u == '-' then t ++ u else t ++ "+" ++ u
showTerm vars (c,as) = showCoeff c as ++ showPP vars as
showCoeff c as =
let c' = show c in case c' of
"1" -> if any (/=0) as then "" else "1"
"-1" -> if any (/=0) as then "-" else "-1"
otherwise -> c'
showPP vars indices = concat (map showPower (zip vars indices))
where
showPower (var,index)
| index == 0 = ""
| index == 1 = var
| otherwise = var ++ '^': show index
changeTermOrder to (MP (_, vs) ts) = MP (to, vs) ts'
where ts' = collectTerms (termOrderToFn to) ts
-- RING OPERATIONS FOR MULTIVARIATE POLYNOMIALS
instance Num a => Num (MPoly a) where
MP params@(to,_) f + MP params' g | params == params' = MP params (addMP tofn f g)
where tofn = termOrderToFn to
f@(MP params _) + MP _ g@[(_,[])] = f + MP params g -- if one of the summands is a constant, ignore parameter mismatch
MP _ f@[(_,[])] + g@(MP params _) = MP params f + g
f + MP _ [] = f -- if one of the summands is zero, ignore parameter mismatch
MP _ [] + g = g
negate (MP params f) = MP params (negateMP f)
MP params@(to,_) f * MP params' g | params == params' = MP params (multMP tofn f g)
where tofn = termOrderToFn to
f@(MP params _) * MP _ g@[(_,[])] = f * MP params g -- if one of the summands is a constant, ignore parameter mismatch
MP _ f@[(_,[])] * g@(MP params _) = MP params f * g
_ * (MP _ []) = 0
(MP _ []) * _ = 0
fromInteger 0 = MP (Grevlex, Xyz) []
fromInteger n = MP (Grevlex, Xyz) [(fromInteger n, [])]
-- NOTE: fromInteger gives you Grevlex over Q.
-- If you want something else, use the conversion functions, or construct by hand
-- convert an mpoly from rationals to a finite field
(/%) :: MPoly QQ -> Integer -> MPoly FF
MP params ts /% p = MP params ts''
where
ts' = map (\(Q n 1, as) -> (toFp p n, as)) ts
ts'' = filter (\(F _ x, _) -> x /= 0) ts'
addMP _ f [] = f
addMP _ [] f = f
addMP termord (t@(c,as):ts) (u@(d,bs):us) =
if as `eqPP` bs
then
if c+d == 0
then addMP termord ts us
else (c+d,as) : (addMP termord ts us)
else
if termord t u
then t : (addMP termord ts (u:us))
else u : (addMP termord (t:ts) us)
negateMP f = map (\(c,as) -> (-c,as)) f
subMP termord f g = addMP termord f (negateMP g)
multMP _ _ [] = []
multMP _ [] _ = []
multMP termord (t:ts) (u:us) =
let
hh = [multTm t u]
ht = map (multTm t) us
th = map (multTm u) ts
tt = multMP termord ts us
in addMP termord (addMP termord hh tt) (addMP termord ht th)
-- !! experiment with addition orders. hh will be largest term, so will add in one step
instance Fractional a => Fractional (MPoly a) where
recip (MP params [(c,[])]) = MP params [(recip c,[])]
recip _ = error "recip not defined for non-constant MPoly"
toMonicMP f@(MP _ []) = f
toMonicMP (MP params ts@((k,_):_)) = MP params (map (\(c,as)->(c/k,as)) ts)
-- DIVISION ALGORITHM
-- initial term
ltMP (MP params (t:_)) = MP params [t]
lt f
| null ts = error "lt 0"
| otherwise = head ts
where ts = termsMP f
ltSplit (MP params (t:ts)) = (MP params [t], MP params ts)
lc f = let (c,_) = lt f in c
lp f = let (_,as) = lt f in as
divideslt f g = dividesTm (lt f) (lt g)
divlt (MP params (t:_)) (MP _ (u:_)) = MP params [divTm t u]
degMP (MP (to, _) ts)
| null ts = -1
| isGraded to = degTm (head ts)
| otherwise = foldl max 0 (map degTm ts)
t */ MP params ts = MP params (map (multTm t) ts)
quotRemMP f@(MP (termord, vs) _) gs = doQuotRemMP f (replicate (length gs) zero, zero)
where
zero = MP (termord, vs) [] -- slight kludge
doQuotRemMP h (us,r)
| null (termsMP h) = (us,r)
| otherwise = doDivisionStep h (gs,[],us,r)
doDivisionStep h ([],us',[],r) =
let (lth,h') = ltSplit h
in doQuotRemMP h' (reverse us', r + lth)
-- let lth = ltMP h
-- in doQuotRemMP (h - lth) (reverse us', r + lth)
doDivisionStep h (g:gs,us',u:us,r) =
if divideslt g h
then
let
newTerm = divlt h g
u' = u + newTerm
h' = h - (newTerm * g)
in doQuotRemMP h' (reverse us' ++ (u' : us), r)
else doDivisionStep h (gs,u:us',us,r)
reduceMP f gs = r where (_,r) = quotRemMP f gs
(%%) :: (Num a, Fractional a) => MPoly a -> [MPoly a] -> MPoly a
(%%) = reduceMP
isReducibleMP f gs = or [lt g `dividesTm` lt f | g <- gs]
-- evaluate the mpoly at the point passed in - eg evalMP (x^2+y) [1,2]
evalMP f vs = sum (map (\t -> evalTerm t vs) (termsMP f))
where evalTerm (c,as) vs = foldl (*) c (zipWith (^) vs as)
-- substitute expressions for the vars - eg substMP (x1x2) [1,x+y,x^2+y^2] - (note we need to pass an expression for x0 too)
substMP f vs = sum (map (\t -> evalTerm t vs) (termsMP f))
where evalTerm (c,as) vs = foldl (*) (constMP c) (zipWith (^) vs as)
-- (Could perhaps be called composeMP instead)
-- NOTE: The following two functions don't individually preserve variable names (though fromHomogeneous . toHomogeneous does)
toHomogeneous f@(MP params ts) =
let
d = degMP f
ts' = collectTerms (termOrderFn f) (map (\(c,as) -> (c, d - sum as : as)) ts)
in MP params ts'
fromHomogeneous f@(MP params ts) =
let ts' = collectTerms (termOrderFn f) (map (\(c,as) -> if null as then (c,[]) else (c, tail as)) ts)
in MP params ts'
-- Will also provide two functions toHomogeneousUsing, fromHomogeneousUsing, where you can specify the variable to be used
{-
isHomogeneousMP f = case termsMP f of
[] -> True
(t:ts) -> all (== degTm t) (map degTm ts)
-}
| nfjinjing/bench-euler | src/Math/MPoly.hs | bsd-3-clause | 11,962 | 60 | 17 | 3,157 | 5,791 | 3,122 | 2,669 | 238 | 5 |
module Parser where
import Data.Char (isDigit, isSpace, isAlpha)
import Data.List (isPrefixOf)
newtype Parser a
= Parser { runParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap f (Parser p) =
Parser (\inp ->
case p inp of
Nothing -> Nothing
Just (v,rem) -> Just (f v, rem))
instance Applicative Parser where
pure x = Parser (\inp -> Just (x, inp))
(Parser f) <*> (Parser x) =
Parser (\inp ->
case f inp of
Nothing -> Nothing
Just (f,rem) ->
case x rem of
Nothing -> Nothing
Just (x, rem') ->
Just (f x, rem'))
instance Monad Parser where
return = pure
(Parser m) >>= f =
Parser (\inp ->
case m inp of
Nothing -> Nothing
Just (x,rem) -> runParser (f x) rem)
eval :: Parser a -> String -> Maybe a
eval p = (fst <$>) . runParser p
failParse :: Parser a
failParse = Parser (\_ -> Nothing)
parseEither :: Parser a -> Parser a -> Parser a
parseEither pa pb =
Parser (\inp ->
case runParser pa inp of
Nothing -> runParser pb inp
success -> success)
parseMany :: Parser a -> Parser [a]
parseMany p =
Parser (\inp ->
case runParser p inp of
Nothing -> Just ([], inp)
Just (x, rem) ->
case runParser (parseMany p) rem of
Nothing -> Just ([x], rem)
Just (xs, rem') -> Just (x:xs, rem'))
parseAny :: Parser Char
parseAny =
Parser (\inp ->
case inp of
c:rem -> Just (c, rem)
_ -> Nothing)
parseChar :: (Char -> Bool) -> Parser Char
parseChar f =
Parser (\inp ->
case inp of
c:rem | f c -> Just (c, rem)
_ -> Nothing)
parseString :: String -> Parser ()
parseString s =
Parser (\inp ->
if s `isPrefixOf` inp
then Just ((), drop (length s) inp)
else Nothing)
parseDigits :: Parser String
parseDigits = parseMany parseDigit
parseAlphas :: Parser String
parseAlphas = parseMany parseAlpha
parseN :: Parser a -> Int -> Parser [a]
parseN p 0 = pure []
parseN p n = do
a <- p
as <- parseN p (n-1)
return $ a:as
parseWhiteSpaces :: Parser ()
parseWhiteSpaces = do
_ <- parseMany parseWhiteSpace
return ()
parseNumber :: Parser Int
parseNumber = do
parseWhiteSpaces
ds <- parseDigits
if null ds
then failParse
else do
parseWhiteSpaces
return (read ds)
parseAlpha :: Parser Char
parseAlpha = parseChar isAlpha
parseDigit :: Parser Char
parseDigit = parseChar isDigit
parseWhiteSpace :: Parser Char
parseWhiteSpace = parseChar isSpace
| CarstenKoenig/AdventOfCode2016 | Day9/Parser.hs | mit | 2,831 | 0 | 17 | 1,005 | 1,067 | 543 | 524 | 95 | 3 |
-- a type constructor `T` constructs a type `T a` from a type `a`.
-- It can have multiple _constructors_, in this case List is either constructed
-- as `Nil` (empty), or as a pair of an `a` along with a `List a`
-- (recursive definition!)
data List a = Nil | Cons a (List a)
-- to turn it into a functor, we have to define `fmap`
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x xs) = Cons (f x) (fmap f xs)
hed :: List a -> Maybe a
hed Nil = Nothing
hed (Cons x xs) = Just x
main = do
let xs = Cons 'b' (Cons 'c' Nil)
putStrLn (show (hed xs))
| jwbuurlage/category-theory-programmers | examples/haskell/functors.hs | mit | 575 | 3 | 12 | 141 | 187 | 86 | 101 | 10 | 1 |
module MultipleOuterEntriesRemoved where
import Language.Haskell.Exts (Module(Module)
,parseFile
,readExtensions)
foo = Module
| serokell/importify | test/test-data/haskell-src-exts@constructors/05-MultipleOuterEntriesRemoved.hs | mit | 187 | 0 | 6 | 71 | 30 | 20 | 10 | 5 | 1 |
{- |
Module : ./CASL/CompositionTable/Pretty2.hs
Description : pretty output for composition tables
Copyright : (c) Christian Maeder DFKI 2012
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
-}
module CASL.CompositionTable.Pretty2 where
import CASL.CompositionTable.CompositionTable
import CASL.CompositionTable.ModelTable
import CASL.CompositionTable.Keywords
import qualified Data.IntSet as IntSet
import qualified Data.IntMap as IntMap
import Common.Doc
ctxt :: String -> Doc
ctxt = text . (':' :)
table2Doc :: Table2 -> Doc
table2Doc (Table2 name br m brs cs ct) =
parens $ text defCalculusS <+> doubleQuotes (text name)
$+$ ctxt identityRelationS <+> baserel m br
$+$ (if IntSet.null brs then empty else
ctxt baseRelationsS <+> parens
(hsep $ map (baserel m) $ IntSet.toList brs))
$+$ conversetable m ct
$+$ (if IntMap.null cs then empty else
colon <> (text compositionOperationS $+$
parens (vcat $ concatMap (cmptab m) $ IntMap.toList cs)))
baserel :: IntMap.IntMap Baserel -> Int -> Doc
baserel m i = case IntMap.lookup i m of
Just (Baserel br) -> text br
Nothing -> error $ "CASL.CompositionTable.Pretty2.baserel " ++ show i
cmptab :: IntMap.IntMap Baserel -> (Int, IntMap.IntMap IntSet.IntSet) -> [Doc]
cmptab m (a1, m2) = map
(\ (a2, s) -> parens $ baserel m a1 <+> baserel m a2
<+> parens (hsep $ map (baserel m) $ IntSet.toList s))
$ IntMap.toList m2
conversetable :: IntMap.IntMap Baserel -> ConTables -> Doc
conversetable m (l, l1, l2, l3) =
vcat [ contab m converseOperationS l
, contab m inverseOperationS l1
, contab m shortcutOperationS l2
, contab m homingOperationS l3 ]
contab :: IntMap.IntMap Baserel -> String -> ConTable -> Doc
contab m t l = if IntMap.null l then empty else
colon <> (text t $+$ parens (vcat $ map (contabentry m) $ IntMap.toList l))
contabentry :: IntMap.IntMap Baserel -> (Int, IntSet.IntSet) -> Doc
contabentry m (a, bs) = parens $ baserel m a <+> case IntSet.toList bs of
[b] -> baserel m b
l -> parens $ hsep $ map (baserel m) l
| spechub/Hets | CASL/CompositionTable/Pretty2.hs | gpl-2.0 | 2,214 | 0 | 17 | 484 | 739 | 379 | 360 | 42 | 3 |
{- | Module : ./GMP/GMP-CoLoSS/GMP/Logics/IneqSolver.hs
Description : Inequality Solver for Graded Modal Logics
Copyright : (c) Georgel Calin & Lutz Schroeder, DFKI Lab Bremen
License : GPLv2 or higher, see LICENSE.txt
Maintainer : g.calin@jacobs-university.de
Stability : provisional
Portability : non-portable (various -fglasgow-exts extensions)
Provides an implementation for solving the system
0 >= 1 + sum x_i*n_i + sum y_i*p_i
with unknowns x_i and y_i within given limits.
-}
module GMP.Logics.IneqSolver where
-- | Coefficients: negative\/positive signed grades on the left\/right.
data Coeffs = Coeffs [Int] [Int]
deriving (Eq, Ord, Show)
-- | Datatype for negative\/positive unknowns; the second Int is the flag.
data IntFlag = IF Int Int
deriving (Eq, Ord)
{- | Sort increasingly a list of pairs.
The sorting is done over the first element of the pair
-}
sort :: Ord a => [(a, b)] -> [(a, b)]
sort list =
let insert x l =
case l of
h : t -> if fst x < fst h
then x : l
else h : insert x t
[] -> [x]
in case list of
h : t -> insert h (sort t)
[] -> []
-- | Compute the minimal point-wise extremal sum of an IntFlag list.
minSum :: [IntFlag] -> Int -> Int -> Int
minSum l lim c =
case l of
IF x 0 : t -> minSum t lim c - lim * x
IF x 1 : t -> minSum t lim c + x
[] -> c
_ -> error "IneqSolver.minSum"
-- | Compute the maximal point-wise extremal sum of an IntFlag list.
maxSum :: [IntFlag] -> Int -> Int -> Int
maxSum l lim c =
case l of
IF x 0 : t -> maxSum t lim c - x
IF x 1 : t -> maxSum t lim c + lim * x
[] -> c
_ -> error "IneqSolver.maxSum"
{- | Returns the updated bound for the unknown corresponding to the negative
- coeff. h where t holds the coefficients for the not yet set unknowns -}
negBound :: Int -> [IntFlag] -> Int -> Int -> Int
negBound h t lim c =
let tmp = case h of
0 -> -1 -- error "div by 0 @ IneqSolver.negBound"
_ -> div (negate (minSum t lim c)) h
in if tmp < 0 then min tmp (-1) else - 1
{- | Returns the updated bound for the unknown corresponding to the positive
- coeff. h where t holds the coefficients for the not yet set unknowns -}
posBound :: Int -> [IntFlag] -> Int -> Int -> Int
posBound h t lim c =
let tmp = case h of
0 -> lim -- error "div by 0 @ IneqSolver.posBound"
_ -> div (negate (minSum t lim c)) h
in if tmp > 0 then min tmp lim else lim
mapAppend :: a -> [[a]] -> [[a]]
mapAppend x = map (x :)
-- | Generate all posible solutions of unknowns
getUnknowns :: [IntFlag] -> Int -> Int -> [[Int]]
getUnknowns list lim c =
if maxSum list lim c <= 0
then
[map (\ x -> case x of
IF _ 0 -> -1
IF _ 1 -> lim
_ -> error "IneqSolver.getUnknowns.if"
) list]
else
case list of
IF h 0 : t -> let aux = negBound h t lim c
in concatMap (\ x -> mapAppend x (getUnknowns t lim (c + x * h)))
[(-lim) .. aux]
IF h 1 : t -> let aux = posBound h t lim c
in concatMap (\ x -> mapAppend x (getUnknowns t lim (c + x * h)))
[1 .. aux]
[] -> []
_ -> error "IneqSolver.getUnknowns.else"
{- | Returns all solutions (x,y) with 1<=-x_i,y_j<=L for the inequality
- 0 >= 1 + sum x_i*n_i + sum y_j*p_j
- with coefficients n_j>0, p_j>0 known -}
ineqSolver :: Coeffs -> Int -> [([Int], [Int])]
ineqSolver (Coeffs n p) bound =
let combinedList = map (`IF` 0) n ++ map (`IF` 1) p -- merge lists & add flags
(sortedList, indexOrder) = (unzip . sort) (zip combinedList [(1 :: Int) ..]) -- sort by coefficents
unOrdered = getUnknowns sortedList bound 1 -- get solutions for the sorted list of coefficients
reOrder list order = (snd . unzip . sort) (zip order list) -- revert list to its initial order
splitList l = case l of -- split a result list in a pair as used by the implementation
h : t -> if h < 0 then let tmp = splitList t
in (h : fst tmp, snd tmp)
else ([], l)
[] -> ([], [])
in map (\ l -> splitList (reOrder l indexOrder)) unOrdered
-- for each element in the result list reorder it and split it
| spechub/Hets | GMP/GMP-CoLoSS/GMP/Logics/IneqSolver.hs | gpl-2.0 | 4,518 | 0 | 19 | 1,488 | 1,280 | 669 | 611 | 73 | 7 |
module Control.Monad.Trans.Either.Utils
( leftToJust, justToLeft
) where
import Control.Monad (mzero, (<=<))
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Either (EitherT(..), left)
import Control.Monad.Trans.Maybe (MaybeT(..))
justToLeft :: Monad m => MaybeT m a -> EitherT a m ()
justToLeft = maybe (return ()) left <=< lift . runMaybeT
leftToJust :: Monad m => EitherT a m () -> MaybeT m a
leftToJust = either return (const mzero) <=< lift . runEitherT
| Mathnerd314/lamdu | bottlelib/Control/Monad/Trans/Either/Utils.hs | gpl-3.0 | 484 | 0 | 10 | 74 | 189 | 107 | 82 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CodeDeploy.RemoveTagsFromOnPremisesInstances
-- 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)
--
-- Removes one or more tags from one or more on-premises instances.
--
-- /See:/ <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_RemoveTagsFromOnPremisesInstances.html AWS API Reference> for RemoveTagsFromOnPremisesInstances.
module Network.AWS.CodeDeploy.RemoveTagsFromOnPremisesInstances
(
-- * Creating a Request
removeTagsFromOnPremisesInstances
, RemoveTagsFromOnPremisesInstances
-- * Request Lenses
, rtfopiTags
, rtfopiInstanceNames
-- * Destructuring the Response
, removeTagsFromOnPremisesInstancesResponse
, RemoveTagsFromOnPremisesInstancesResponse
) where
import Network.AWS.CodeDeploy.Types
import Network.AWS.CodeDeploy.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a remove tags from on-premises instances
-- operation.
--
-- /See:/ 'removeTagsFromOnPremisesInstances' smart constructor.
data RemoveTagsFromOnPremisesInstances = RemoveTagsFromOnPremisesInstances'
{ _rtfopiTags :: ![Tag]
, _rtfopiInstanceNames :: ![Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RemoveTagsFromOnPremisesInstances' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtfopiTags'
--
-- * 'rtfopiInstanceNames'
removeTagsFromOnPremisesInstances
:: RemoveTagsFromOnPremisesInstances
removeTagsFromOnPremisesInstances =
RemoveTagsFromOnPremisesInstances'
{ _rtfopiTags = mempty
, _rtfopiInstanceNames = mempty
}
-- | The tag key-value pairs to remove from the on-premises instances.
rtfopiTags :: Lens' RemoveTagsFromOnPremisesInstances [Tag]
rtfopiTags = lens _rtfopiTags (\ s a -> s{_rtfopiTags = a}) . _Coerce;
-- | The names of the on-premises instances to remove tags from.
rtfopiInstanceNames :: Lens' RemoveTagsFromOnPremisesInstances [Text]
rtfopiInstanceNames = lens _rtfopiInstanceNames (\ s a -> s{_rtfopiInstanceNames = a}) . _Coerce;
instance AWSRequest RemoveTagsFromOnPremisesInstances
where
type Rs RemoveTagsFromOnPremisesInstances =
RemoveTagsFromOnPremisesInstancesResponse
request = postJSON codeDeploy
response
= receiveNull
RemoveTagsFromOnPremisesInstancesResponse'
instance ToHeaders RemoveTagsFromOnPremisesInstances
where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("CodeDeploy_20141006.RemoveTagsFromOnPremisesInstances"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON RemoveTagsFromOnPremisesInstances
where
toJSON RemoveTagsFromOnPremisesInstances'{..}
= object
(catMaybes
[Just ("tags" .= _rtfopiTags),
Just ("instanceNames" .= _rtfopiInstanceNames)])
instance ToPath RemoveTagsFromOnPremisesInstances
where
toPath = const "/"
instance ToQuery RemoveTagsFromOnPremisesInstances
where
toQuery = const mempty
-- | /See:/ 'removeTagsFromOnPremisesInstancesResponse' smart constructor.
data RemoveTagsFromOnPremisesInstancesResponse =
RemoveTagsFromOnPremisesInstancesResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RemoveTagsFromOnPremisesInstancesResponse' with the minimum fields required to make a request.
--
removeTagsFromOnPremisesInstancesResponse
:: RemoveTagsFromOnPremisesInstancesResponse
removeTagsFromOnPremisesInstancesResponse =
RemoveTagsFromOnPremisesInstancesResponse'
| fmapfmapfmap/amazonka | amazonka-codedeploy/gen/Network/AWS/CodeDeploy/RemoveTagsFromOnPremisesInstances.hs | mpl-2.0 | 4,482 | 0 | 12 | 911 | 486 | 292 | 194 | 72 | 1 |
--------------------------------------------------------------------
-- |
-- Module : Control.Comonad.Memo
-- Copyright : (c) Edward Kmett 2008
-- License : BSD3
--
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability: portable
--
--------------------------------------------------------------------
module Control.Comonad.Memo (newMemo, Memo, pureMemo) where
import Control.Comonad
import Data.Map
import Control.Concurrent.MVar
import System.IO.Unsafe(unsafePerformIO)
-- TODO: rewrite with a memoizing context comonad
newtype Memo k v = Memo (MVar (Map k v)) (k -> v) k
newMemo :: Ord k => (k -> v) -> k -> IO (Memo k v)
newMemo f k = fmap (gen f) (newMVar Map.empty)
where gen _ r = Memo (unsafePerformIO . update f r) ()
update :: MVar (Data.Map k v) -> IO v
update f r k = do
m <- takeMVar r
let v = f k
putMVar r (Map.insert k v m)
return v
pureMemo :: (k -> v) -> Memo k v ()
pureMemo f = Memo f ()
instance Functor (Memo k v) where
fmap f (g,a) = (g, f a)
-- TODO: map this over the memo-table!
instance Bifunctor (Memo k) where
bimap f g (Memo h a)) = Memo (f . h) (g a)
instance Ord k => Copointed (Memo k v) where
extract (Memo _ a) = a
instance Ord k => Comonad (Memo k v) where
duplicate (Memo f a) = Memo f (Memo f a)
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Comonad/Memo.hs | apache-2.0 | 1,345 | 26 | 12 | 301 | 435 | 247 | 188 | -1 | -1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
module NanoML.Eval (module NanoML.Eval, module NanoML.Monad) where
import Control.Arrow (first, second)
import Control.Exception
import Control.Monad
import Control.Monad.Except
import Control.Monad.Fix
import Control.Monad.Random
import Control.Monad.RWS hiding (Alt)
import Data.IORef
import Data.List
import qualified Data.Map as Map
import qualified Data.Vector as Vector
import System.IO.Unsafe
import Text.Printf
import NanoML.Gen
import NanoML.Misc
import NanoML.Monad
import NanoML.Parser
import NanoML.Pretty
import NanoML.Prim
import NanoML.Types
import Debug.Trace
----------------------------------------------------------------------
-- Evaluation
----------------------------------------------------------------------
-- evalString :: MonadEval m => String -> m Value
-- evalString s = case parseExpr s of
-- Left e -> throwError (ParseError e)
-- Right e -> eval e
-- evalDecl :: MonadEval m => Decl -> m ()
-- evalDecl decl = case decl of
-- DFun _ Rec binds -> evalRecBinds binds >>= setVarEnv
-- DFun _ NonRec binds -> evalNonRecBinds binds >>= setVarEnv
-- DEvl _ expr -> void $ eval expr
-- DTyp _ decls -> mapM_ addType decls
-- DExn _ decl -> extendType "exn" decl
-- evalRecBinds :: MonadEval m => [(Pat,Expr)] -> m Env
-- evalRecBinds binds = do
-- penv <- gets stVarEnv
-- mfix $ \fenv -> do
-- setVarEnv fenv
-- bnd <- evalBinds binds
-- allocEnvWith "let-rec" penv bnd
-- evalNonRecBinds :: MonadEval m => [(Pat,Expr)] -> m Env
-- evalNonRecBinds binds = do
-- bnd <- evalBinds binds
-- allocEnv "let" bnd
-- evalBinds :: MonadEval m => [(Pat,Expr)] -> m [(Var,Value)]
-- evalBinds binds = concatMapM evalBind binds
-- -- | @evalBind (p,e) env@ returns the environment matched by @p@
-- evalBind :: MonadEval m => (Pat,Expr) -> m [(Var,Value)]
-- evalBind (p,e) = withCurrentExpr e $ do
-- v <- eval e
-- matchPat v p >>= \case
-- Nothing -> withCurrentProvM $ \prv -> throwError $ MLException (mkExn "Match_failure" [] prv)
-- Just env -> return env
logEnv :: MonadEval m => m Env -> m Env
logEnv = id
-- logEnv m = mycensor (\env w -> mkLog env) m
-- where
-- mkLog env = map (uncurry (=:)) (toListEnv env)
logMaybeEnv :: MonadEval m => m (Maybe Env) -> m (Maybe Env)
logMaybeEnv = id
-- logMaybeEnv m = mycensor (\env w -> mkLog env) m
-- where
-- mkLog (Just env) = map (uncurry (=:)) (toListEnv env)
-- mkLog _ = []
logExpr :: MonadEval m => Expr -> m Value -> m Value
logExpr _ = id
-- logExpr (Var v) m = mycensor (\v w -> []) (tell [pretty (Var v)] >> m)
-- logExpr (Lit l) m = mycensor (\v w -> []) (tell [pretty (Lit l)] >> m)
-- logExpr (Lam p e) m = mycensor (\v w -> []) (tell [pretty (Lam p e)] >> m)
-- logExpr (Val v) m = mycensor (\v w -> []) (tell [pretty (Val v)] >> m)
-- logExpr e@(ConApp "[]" Nothing) m = mycensor (\v w -> []) (tell [pretty e] >> m)
-- logExpr expr m = mycensor (\v w -> [expr ==> v]) (tell [pretty expr] >> m)
mycensor :: MonadWriter w m => (a -> w -> w) -> m a -> m a
mycensor f m = pass $ do
a <- m
return (a, f a)
-- eval :: MonadEval m => Expr -> m Value
-- eval expr = logExpr expr $ case expr of
-- Var ms v ->
-- lookupVar v
-- Lam ms p e _ ->
-- Lam ms p e . Just <$> gets stVarEnv
-- App ms f args -> do
-- vf <- eval f
-- vargs <- mapM eval args
-- -- FIXME: this appears to be discarding bindings introduced by the
-- -- function application
-- foldM evalApp vf vargs
-- Bop ms b e1 e2 -> do
-- v1 <- eval e1
-- v2 <- eval e2
-- evalBop b v1 v2
-- Uop ms u e -> do
-- v <- eval e
-- evalUop u v
-- Lit ms l -> litValue l
-- Let ms Rec binds body -> do
-- env <- evalRecBinds binds
-- eval body `withEnv` env
-- Let ms NonRec binds body -> do
-- env <- evalNonRecBinds binds
-- eval body `withEnv` env
-- Ite ms eb et ef -> do
-- vb <- eval eb
-- case vb of
-- VB _ True -> eval et
-- VB _ False -> eval ef
-- _ -> typeError (typeOf vb) (tCon tBOOL)
-- Seq ms e1 e2 ->
-- eval e1 >> eval e2
-- Case ms e as -> do
-- v <- eval e
-- evalAlts v as
-- Tuple ms es -> do
-- vs <- mapM eval es
-- withCurrentProv $ \prv -> (VT prv vs)
-- ConApp ms "()" Nothing _ -> withCurrentProv VU
-- ConApp ms "[]" Nothing _ -> withCurrentProv $ \prv -> (VL prv [])
-- ConApp ms "::" (Just (Tuple ms' [h,t])) _ -> do
-- vh <- eval h
-- vt <- eval t
-- force vt (tL (typeOf vh)) $ \(VL _ vt) su -> do
-- withCurrentProv $ \prv -> (VL prv (vh:vt))
-- ConApp ms dc Nothing _ -> do
-- evalConApp dc Nothing
-- ConApp ms dc (Just e) _ -> do
-- v <- eval e
-- evalConApp dc (Just v)
-- Record ms flds _ -> do
-- td@TypeDecl {tyCon, tyRhs = TRec fs} <- lookupField $ fst $ head flds
-- unless (all (`elem` map fst3 fs) (map fst flds)) $
-- otherError $ printf "invalid fields for type %s: %s" tyCon (show $ pretty expr)
-- unless (all (`elem` map fst flds) (map fst3 fs)) $
-- otherError $ printf "missing fields for type %s: %s" tyCon (show $ pretty expr)
-- (vs, sus) <- fmap unzip $ forM fs $ \ (f, m, t) -> do
-- let e = fromJust $ lookup f flds
-- v <- eval e
-- force v t $ \v su -> do
-- su <- unify t (typeOf v)
-- i <- fresh
-- writeStore i (m,v)
-- return ((f, Ref i),su)
-- let t = subst (mconcat sus) $ typeDeclType td
-- withCurrentProv $ \prv -> (VR prv vs (Just t))
-- Field ms e f -> do
-- v <- eval e
-- getField v f
-- SetField ms r f e -> do
-- vr <- eval r
-- v <- eval e
-- setField vr f v
-- withCurrentProv VU
-- Array ms [] -> withCurrentProv $ \prv -> (VV prv [])
-- Array ms es -> do
-- (v:vs) <- mapM eval es
-- mapM_ (unify (typeOf v) . typeOf) vs
-- withCurrentProv $ \prv -> (VV prv (v:vs))
-- Try ms e alts -> do
-- env <- gets stVarEnv
-- eval e `catchError` \e -> do
-- setVarEnv env
-- case e of
-- MLException ex -> evalAlts ex alts
-- _ -> maybeThrow e
-- -- FIXME:
-- _ -> return expr
-- Prim1 _ (P1 p f t) e -> do
-- v <- eval e
-- force v t $ \v su -> f v
-- Prim2 _ (P2 p f t1 t2) e1 e2 -> do
-- v1 <- eval e1
-- v2 <- eval e2
-- forces [(v1,t1),(v2,t2)] $ \[v1,v2] su -> f v1 v2
force :: MonadEval m => Value -> Type -> (Value -> m a) -> m a
force x t k = do
t' <- substM t
-- traceShowM ("force", x, t')
force' x t' k
force' x@(Hole _ _ Nothing) (TVar {}) k = k x -- delay instantiation until we have a concrete type
force' x@(Hole _ _ (Just (TVar {}))) (TVar {}) k = k x -- delay instantiation until we have a concrete type
force' h@(Hole _ r mt) t k = do
-- x <- lookupStore r
-- traceShowM (h, t, x)
lookupStore r >>= \case
Just (_,v) -> do
vt <- typeOfM v
t' <- substM t
unify vt t'
k v
-- su <- getSubst
-- k (onType (subst su) v)
Nothing -> do
env <- gets stTypeEnv
ht <- maybe (TVar <$> freshTVar) return mt
t' <- substM t
unify ht t'
su <- getSubst
v <- genValue (subst su t') env
-- traceShowM (t', subst su t', v)
writeStore r (NonMut,v)
k v
force' v t k = do
vt <- typeOfM v
t' <- substM t
unify vt t'
-- su <- getSubst
-- k (onType (subst su) v)
k v
forces :: MonadEval m => [(Value,Type)] -> ([Value] -> m a) -> m a
forces vts k = go vts []
where
go [] vs = k (reverse vs)
go ((v,t):vts) vs = force v t (\v -> go vts (v:vs))
forceSame :: MonadEval m => Value -> Value -> (Value -> Value -> m a) -> m a
forceSame x y k = do
x' <- fillHole x
y' <- fillHole y
forceSame' x' y' k
fillHole :: MonadEval m => Value -> m Value
fillHole h@(Hole _ r _) = do
lookupStore r >>= \case
Just (_,v) -> return v
Nothing -> return h
fillHole x = return x
forceSame' :: MonadEval m => Value -> Value -> (Value -> Value -> m a) -> m a
-- forceSame x@(Hole {}) y@(Hole {}) k =
-- forces [(x,tCon tINT),(y,tCon tINT)] $ \[x,y] -> k x y
forceSame' x@(Hole {}) y@(Hole {}) k = do
xt <- substM =<< typeOfM x
yt <- substM =<< typeOfM y
unify xt yt
k x y
forceSame' x@(Hole {}) y k = do
yt <- substM =<< typeOfM y
force x yt $ \x -> k x y
forceSame' x y@(Hole {}) k = do
xt <- substM =<< typeOfM x
force y xt $ \y -> k x y
forceSame' x y k = do
xt <- substM =<< typeOfM x
yt <- substM =<< typeOfM y
unify xt yt
k x y
-- su <- getSubst
-- k (onType (subst su) x) (onType (subst su) y)
-- evalApp :: MonadEval m => Value -> Value -> m Value
-- evalApp = error "evalApp"
-- evalApp f a = logExpr (App Nothing (Val Nothing f) [Val Nothing a]) $ case f of
-- VF _ (Func (Lam ms p e) env) -> do
-- Just pat_env <- matchPat a p
-- eval e `withEnv` error "evalApp" -- joinEnv pat_env env
-- _ -> otherError "tried to apply a non-function"
evalConApp :: MonadEval m => DCon -> Maybe Value -> m Value
evalConApp dc v = do
dd <- lookupDataCon dc
prv <- getCurrentProv
let tvs = tyVars (dType dd)
su <- fmap Map.fromList $ forM tvs $ \tv ->
(tv,) . TVar <$> freshTVar
case (map (subst su) (dArgs dd), v) of
([], Nothing)
| dc == "()" -> return (VU prv)
| dc == "[]" -> VL prv [] . Just . TVar <$> freshTVar
| otherwise -> return (VA prv dc v (Just . subst su . typeDeclType $ dType dd))
([a], Just v) -> force v a $ \v -> do
vt <- typeOfM v
unify vt a
t <- substM $ mkTApps (tyCon (dType dd)) (map (subst su . TVar) tvs)
return (VA prv dc (Just v) (Just t))
(as, Just (VT _ vs))
| dc == "::"
, [vh, vt] <- vs -> do
a <- freshTVar
force vt (tL (TVar a)) $ \(VL _ vt mt) -> do
t <- substM (TVar a)
force vh (subst su t) $ \vh -> do
th <- typeOfM vh
return (VL prv (vh : vt) (Just th))
| length as == length vs -> forces (zip vs as) $ \vs -> do
t <- substM $ mkTApps (tyCon (dType dd)) (map (subst su . TVar) tvs)
return (VA prv dc v (Just t))
(as, _) -> do
let nArgs = case v of
Nothing -> 0
Just (VT _ vs) -> length vs
Just _ -> 1
otherError (printf "%s expects %d arguments, but was given %d"
dc (length as) nArgs)
evalBop :: MonadEval m
=> Bop -> Value -> Value -> m Value
evalBop bop v1 v2 = withCurrentProvM $ \prv ->
logExpr (Bop Nothing bop v1 v2) $ case bop of
Eq -> forceSame v1 v2 $ \v1 v2 -> VB prv <$> eqVal v1 v2
Neq -> forceSame v1 v2 $ \v1 v2 -> VB prv . not <$> eqVal v1 v2
Lt -> forceSame v1 v2 $ \v1 v2 -> VB prv <$> ltVal v1 v2
Le -> forceSame v1 v2 $ \v1 v2 -> (\x y -> VB prv (x || y)) <$> ltVal v1 v2 <*> eqVal v1 v2
Gt -> forceSame v1 v2 $ \v1 v2 -> VB prv <$> gtVal v1 v2
Ge -> forceSame v1 v2 $ \v1 v2 -> (\x y -> VB prv (x || y)) <$> gtVal v1 v2 <*> eqVal v1 v2
And -> forces [(v1,tCon tBOOL),(v2,tCon tBOOL)] $ \[v1,v2] -> pand v1 v2
Or -> forces [(v1,tCon tBOOL),(v2,tCon tBOOL)] $ \[v1,v2] -> por v1 v2
Plus -> forces [(v1,tCon tINT),(v2,tCon tINT)] $ \[v1,v2] -> plusVal v1 v2
Minus -> forces [(v1,tCon tINT),(v2,tCon tINT)] $ \[v1,v2] -> minusVal v1 v2
Times -> forces [(v1,tCon tINT),(v2,tCon tINT)] $ \[v1,v2] -> timesVal v1 v2
Div -> forces [(v1,tCon tINT),(v2,tCon tINT)] $ \[v1,v2] -> divVal v1 v2
Mod -> forces [(v1,tCon tINT),(v2,tCon tINT)] $ \[v1,v2] -> modVal v1 v2
FPlus -> forces [(v1,tCon tFLOAT),(v2,tCon tFLOAT)] $ \[v1,v2] -> plusVal v1 v2
FMinus -> forces [(v1,tCon tFLOAT),(v2,tCon tFLOAT)] $ \[v1,v2] -> minusVal v1 v2
FTimes -> forces [(v1,tCon tFLOAT),(v2,tCon tFLOAT)] $ \[v1,v2] -> timesVal v1 v2
FDiv -> forces [(v1,tCon tFLOAT),(v2,tCon tFLOAT)] $ \[v1,v2] -> divVal v1 v2
evalUop :: MonadEval m => Uop -> Value -> m Value
evalUop Neg v = force v (tCon tINT) $ \(VI _ i) -> withCurrentProv $ \prv -> VI prv (negate i)
evalUop FNeg v = force v (tCon tFLOAT) $ \(VD _ d) -> withCurrentProv $ \prv -> VD prv (negate d)
-- ltVal (VI x) (VI y) = return (x < y)
-- ltVal (VD x) (VD y) = return (x < y)
-- ltVal x y = typeError "cannot compare ordering of non-numeric types"
-- gtVal (VI x) (VI y) = return (x > y)
-- gtVal (VD x) (VD y) = return (x > y)
-- gtVal x y = typeError "cannot compare ordering of non-numeric types"
ltVal x y = do
VI _ i <- cmpVal x y
return (i == (-1))
gtVal x y = do
VI _ i <- cmpVal x y
return (i == 1)
plusVal (VI _ i) (VI _ j) = withCurrentProv $ \prv -> VI prv (i+j)
plusVal (VD _ i) (VD _ j) = withCurrentProv $ \prv -> VD prv (i+j)
-- plusVal _ _ = typeError "+ can only be applied to ints"
minusVal (VI _ i) (VI _ j) = withCurrentProv $ \prv -> VI prv (i-j)
minusVal (VD _ i) (VD _ j) = withCurrentProv $ \prv -> VD prv (i-j)
-- minusVal _ _ = typeError "- can only be applied to ints"
timesVal (VI _ i) (VI _ j) = withCurrentProv $ \prv -> VI prv (i*j)
timesVal (VD _ i) (VD _ j) = withCurrentProv $ \prv -> VD prv (i*j)
-- timesVal _ _ = typeError "* can only be applied to ints"
divVal (VI {}) (VI _ 0) = withCurrentProvM $ \prv ->
maybeThrow $ MLException (mkExn "Division_by_zero" [] prv)
divVal (VD {}) (VD _ 0) = withCurrentProvM $ \prv ->
maybeThrow $ MLException (mkExn "Division_by_zero" [] prv)
divVal (VI _ i) (VI _ j) = withCurrentProv $ \prv -> VI prv (i `div` j)
divVal (VD _ i) (VD _ j) = withCurrentProv $ \prv -> VD prv (i / j)
-- divVal _ _ = typeError "/ can only be applied to ints"
modVal (VI _ i) (VI _ j) = withCurrentProv $ \prv -> VI prv (i `mod` j)
-- modVal _ _ = typeError "mod can only be applied to ints"
litValue :: MonadEval m => Literal -> m Value
litValue (LI i) = withCurrentProv $ \prv -> VI prv i
litValue (LD d) = withCurrentProv $ \prv -> VD prv d
litValue (LB b) = withCurrentProv $ \prv -> VB prv b
litValue (LC c) = withCurrentProv $ \prv -> VC prv c
litValue (LS s) = withCurrentProv $ \prv -> VS prv s
--litValue LU = VU
-- evalAlts :: MonadEval m => Value -> [Alt] -> m Value
-- evalAlts _ []
-- = withCurrentProvM $ \prv -> maybeThrow $ MLException (mkExn "Match_failure" [] prv)
-- evalAlts v ((p,g,e):as)
-- = matchPat v p >>= \case
-- Nothing -> evalAlts v as
-- Just bnd -> do newenv <- error "evalAlts" -- joinEnv bnd <$> gets stVarEnv
-- case g of
-- Nothing -> eval e `withEnv` newenv
-- Just g ->
-- eval g `withEnv` newenv >>= \case
-- VB _ True -> eval e `withEnv` newenv
-- VB _ False -> evalAlts v as
-- | If a @Pat@ matches a @Value@, returns the @Env@ bound by the
-- pattern.
matchPat :: MonadEval m => Value -> Pat -> m (Maybe [(Var,Value)])
-- NOTE: it's crucial that we refresh the bound value before placing it
-- in the environment, so we maintain the invariant that each expr has
-- AT MOST ONE incoming StepsTo edge. consider
--
-- let x = 1 + 1 in x
--
-- we'll have a node for the expression '2' with a StepsTo edge coming
-- from '1 + 1'. if we do not refresh the '2' before we bind it to 'x',
-- we'll end up with a separate incoming StepsTo edge from 'x'. this
-- will HORRIBLY confuse the reduction graph traversal functions.
-- FIXME: this is NOT QUITE RIGHT, see onlyEvens example from
-- discussion2.ml
-- maybe we need to just deal with multiple incoming edges and
-- always have a PATH that we insert nodes from, instead of literally
-- walking backwards from the final node
matchPat v p = -- refreshExpr v' >>= \v ->
case p of
VarPat _ var ->
return $ Just [(var,v)]
LitPat _ lit -> force v (typeOfLit lit) $ \v -> do
b <- matchLit v lit
return $ if b then Just mempty else Nothing
IntervalPat _ lo hi -> force v (typeOfLit lo) $ \v -> do
VB _ b <- do lb <- evalBop Ge v (Lit Nothing lo)
gb <- evalBop Le v (Lit Nothing hi)
evalBop And lb gb
-- eval (mkApps Nothing (Var Nothing "&&")
-- [ mkApps Nothing (Var Nothing ">=") [v, Lit Nothing lo]
-- , mkApps Nothing (Var Nothing "<=") [v, Lit Nothing hi]])
return $ if b then Just mempty else Nothing
ConsPat _ p ps -> do
a <- freshTVar
force v (tL (TVar a)) $ \v -> do
case v of
VL _ [] _ -> return Nothing
VL _ _ _ -> do
(x,xs) <- unconsVal v
menv1 <- matchPat x p
menv2 <- matchPat xs ps
case (menv1, menv2) of
(Just env1, Just env2) -> return $ Just (env1 <> env2)
_ -> return Nothing
ListPat _ ps -> do
a <- freshTVar
force v (tL (TVar a)) $ \(VL _ vs mt) -> do
if length ps /= length vs
then return Nothing
else fmap mconcat . sequence -- :: [Maybe _] -> Maybe [_])
<$> zipWithM matchPat vs ps
TuplePat _ ps -> do
ts <- replicateM (length ps) (TVar <$> freshTVar)
force v (TTup ts) $ \(VT _ vs) -> do
fmap mconcat . sequence -- :: [Maybe _] -> Maybe [_])
<$> zipWithM matchPat vs ps
WildPat _ ->
return $ Just mempty
ConPat _ "[]" Nothing -> do
a <- freshTVar
force v (tL (TVar a)) $ \v -> case v of
-- case vs of
VL _ [] _ -> return (Just mempty)
VL _ _ _ -> return Nothing
_ -> error $ "matchPat: impossible: " ++ show v
ConPat _ "()" Nothing -> force v tU $ \v ->
return (Just mempty)
ConPat _ dc p' -> do
-- FIXME: this is confusing
dd <- lookupDataCon dc
-- su <- fmap Map.fromList $ forM (tyVars (dType dd)) $ \tv ->
-- (tv,) . TVar <$> freshTVar
tvs <- replicateM (length (tyVars (dType dd))) (TVar <$> freshTVar)
force v (mkTApps (tyCon (dType dd)) tvs) $ \(VA _ c v' t) -> do
unless (safeMatch (dArgs dd) p') err
if dc /= c
then return Nothing
else case (p', v') of
(Nothing, Nothing) -> return (Just mempty)
(Just p, Nothing) -> err
(Nothing, Just p) -> err
(Just p, Just v) -> matchPat v p
AsPat _ p x -> do
Just env <- matchPat v p
return (Just ((x,v) : env))
ConstraintPat _ p t -> force v t $ \v -> do
matchPat v p
_ -> err
where err = otherError (printf "tried to match %s against %s"
(show $ pretty v) (show $ pretty p) :: String)
safeMatch [] Nothing = True
safeMatch [t] (Just p) = True
safeMatch ts (Just (TuplePat _ ps)) = True
safeMatch ts (Just (WildPat _)) = True
safeMatch _ _ = False
unconsVal :: MonadEval m => Value -> m (Value, Value)
unconsVal (VL prv (x:xs) mt) = return (x, VL prv xs mt) -- FIXME: is this the right provenance??
unconsVal _ = otherError "type error: uncons can only be applied to lists"
matchLit :: MonadEval m => Value -> Literal -> m Bool
matchLit (VI _ i1) (LI i2) = return $ i1 == i2
matchLit (VD _ d1) (LD d2) = return $ d1 == d2
matchLit (VB _ b1) (LB b2) = return $ b1 == b2
matchLit (VC _ c1) (LC c2) = return $ c1 == c2
matchLit (VS _ s1) (LS s2) = return $ s1 == s2
--matchLit VU LU = return True
matchLit v l = do
--lv <- litValue l
vt <- typeOfM v
typeError vt (typeOfLit l)
-- testEval :: String -> IO ()
-- testEval s = let Right e = parseExpr s
-- in print $ runEval stdOpts (eval e)
| ucsd-progsys/nanomaly | src/NanoML/Eval.hs | bsd-3-clause | 19,653 | 0 | 25 | 5,560 | 5,655 | 2,914 | 2,741 | 269 | 24 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- | Provides an abstract class for monads that create artifacts
-- (results of compilation). The most common use of this is to
-- produce object files.
module Control.Monad.Artifacts.Class(
MonadArtifacts(..)
) where
import Blaze.ByteString.Builder
import Control.Monad.Cont
import Control.Monad.Except
import Control.Monad.List
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Journal
import Control.Monad.Writer
import qualified Data.ByteString as Strict
import qualified Data.ByteString.Lazy as Lazy
-- | A class of monads that create artifacts.
class Monad m => MonadArtifacts path m where
-- | Create an artifact with the given pathname from a Builder.
artifact :: path
-- ^ The path for the artifact.
-> Builder
-- ^ A 'Builder' for the content of the artifact.
-> m (Maybe IOError)
-- | Create an artifact with a strict bytestring as contents.
artifactBytestring :: path
-- ^ The path for the artifact.
-> Strict.ByteString
-- ^ The contents of the artifact.
-> m (Maybe IOError)
artifactBytestring path = artifact path . fromByteString
-- | Create an artifact with a strict bytestring as contents.
artifactLazyBytestring :: path
-- ^ The path for the artifact.
-> Lazy.ByteString
-- ^ The contents of the artifact.
-> m (Maybe IOError)
artifactLazyBytestring path = artifact path . fromLazyByteString
instance MonadArtifacts path m => MonadArtifacts path (ContT r m) where
artifact path = lift . artifact path
instance (MonadArtifacts path m) => MonadArtifacts path (ExceptT e m) where
artifact path = lift . artifact path
instance (MonadArtifacts path m) => MonadArtifacts path (JournalT e m) where
artifact path = lift . artifact path
instance MonadArtifacts path m => MonadArtifacts path (ListT m) where
artifact path = lift . artifact path
instance MonadArtifacts path m => MonadArtifacts path (ReaderT r m) where
artifact path = lift . artifact path
instance MonadArtifacts path m => MonadArtifacts path (StateT s m) where
artifact path = lift . artifact path
instance (MonadArtifacts path m, Monoid w) =>
MonadArtifacts path (WriterT w m) where
artifact path = lift . artifact path
| saltlang/compiler-toolbox | src/Control/Monad/Artifacts/Class.hs | bsd-3-clause | 4,066 | 0 | 11 | 893 | 546 | 304 | 242 | 41 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Network.BitTorrent.Tracker.RPC.HTTPSpec (spec) where
import Control.Monad
import Data.Default
import Data.List as L
import Test.Hspec
import Network.BitTorrent.Internal.Progress
import Network.BitTorrent.Tracker.Message as Message
import Network.BitTorrent.Tracker.RPC.HTTP
import Network.BitTorrent.Tracker.TestData
import Network.BitTorrent.Tracker.MessageSpec hiding (spec)
validateInfo :: AnnounceQuery -> AnnounceInfo -> Expectation
validateInfo _ (Message.Failure reason) = do
error $ "validateInfo: " ++ show reason
validateInfo AnnounceQuery {..} AnnounceInfo {..} = do
return ()
-- case respComplete <|> respIncomplete of
-- Nothing -> return ()
-- Just n -> n `shouldBe` L.length (getPeerList respPeers)
isUnrecognizedScheme :: RpcException -> Bool
isUnrecognizedScheme (RequestFailed _) = True
isUnrecognizedScheme _ = False
isNotResponding :: RpcException -> Bool
isNotResponding (RequestFailed _) = True
isNotResponding _ = False
spec :: Spec
spec = parallel $ do
describe "Manager" $ do
describe "newManager" $ do
it "" $ pending
describe "closeManager" $ do
it "" $ pending
describe "withManager" $ do
it "" $ pending
describe "RPC" $ do
describe "announce" $ do
it "must fail on bad uri scheme" $ do
withManager def $ \ mgr -> do
q <- arbitrarySample
announce mgr "magnet://foo.bar" q
`shouldThrow` isUnrecognizedScheme
describe "scrape" $ do
it "must fail on bad uri scheme" $ do
withManager def $ \ mgr -> do
scrape mgr "magnet://foo.bar" []
`shouldThrow` isUnrecognizedScheme
forM_ (L.filter isHttpTracker trackers) $ \ TrackerEntry {..} ->
context trackerName $ do
describe "announce" $ do
if tryAnnounce
then do
it "have valid response" $ do
withManager def $ \ mgr -> do
-- q <- arbitrarySample
let ih = maybe def L.head hashList
let q = AnnounceQuery ih "-HS0003-203534.37420" 6000
(Progress 0 0 0) Nothing Nothing (Just Started)
info <- announce mgr trackerURI q
validateInfo q info
else do
it "should fail with RequestFailed" $ do
withManager def $ \ mgr -> do
q <- arbitrarySample
announce mgr trackerURI q
`shouldThrow` isNotResponding
describe "scrape" $ do
if tryScraping
then do
it "have valid response" $ do
withManager def $ \ mgr -> do
xs <- scrape mgr trackerURI [def]
L.length xs `shouldSatisfy` (>= 1)
else do
it "should fail with ScrapelessTracker" $ do
pending
when (not tryAnnounce) $ do
it "should fail with RequestFailed" $ do
withManager def $ \ mgr -> do
scrape mgr trackerURI [def]
`shouldThrow` isNotResponding
| DavidAlphaFox/bittorrent | tests/Network/BitTorrent/Tracker/RPC/HTTPSpec.hs | bsd-3-clause | 3,178 | 0 | 34 | 1,047 | 793 | 388 | 405 | 76 | 3 |
module B1.Data.ListTest
( getTestGroup
) where
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit
import Test.QuickCheck
import B1.Data.List
import qualified Test.Framework.Providers.API
getTestGroup :: Test.Framework.Providers.API.Test
getTestGroup = testGroup "B1.Data.ListTest"
[ testCase "case_groupElements" case_groupElements
]
case_groupElements :: Assertion
case_groupElements =
assertEqual "" expected $ groupElements numPerGroup list
where
list = [1, 2, 3, 4, 5, 6]
numPerGroup = 3
expected = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
| madjestic/b1 | tests/B1/Data/ListTest.hs | bsd-3-clause | 649 | 0 | 8 | 101 | 190 | 119 | 71 | 18 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Vimus.CommandSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Test.Hspec.Expectations.Contrib
import Vimus.Type (Vimus)
import Vimus.Command.Core
import Vimus.Command.Parser
import Vimus.Command.Completion
import Vimus.Command
main :: IO ()
main = hspec spec
type ParseResult a = Either ParseError (a, String)
spec :: Spec
spec = do
describe "MacroName as an argument" $ do
describe "argumentParser" $ do
it "parses key references" $ do
runParser argumentParser "<ESC>" `shouldBe` Right (MacroName "\ESC", "")
it "fails on unterminated key references" $ do
runParser argumentParser "<ESC" `shouldBe` (Left . SpecificArgumentError $ "unterminated key reference \"ESC\"" :: ParseResult MacroName)
it "fails on invalid key references" $ do
runParser argumentParser "<foo>" `shouldBe` (Left . SpecificArgumentError $ "unknown key reference \"foo\"" :: ParseResult MacroName)
describe "completeCommand" $ do
let complete = completeCommand [command "map" "" (undefined :: MacroName -> MacroExpansion -> Vimus ())]
it "completes key references" $ do
complete "map <Es" `shouldBe` Right "map <Esc>"
it "keeps any prefix on completion" $ do
complete "map foo<Es" `shouldBe` Right "map foo<Esc>"
describe "argument MacroExpansion" $ do
it "is never null" $ property $
\xs -> case runParser argumentParser xs of
Left _ -> True
Right (MacroExpansion ys, _) -> (not . null) ys
describe "argument ShellCommand" $ do
it "is never null" $ property $
\xs -> case runParser argumentParser xs of
Left _ -> True
Right (ShellCommand ys, _) -> (not . null) ys
describe "argument Volume" $ do
it "returns exact volume value for positve integers" $ do
runParser argumentParser "10" `shouldBe` Right (Volume 10, "")
it "returns a positive offset if prefixed by +" $ do
runParser argumentParser "+10" `shouldBe` Right (VolumeOffset 10, "")
it "returns a negative offset if prefixed by -" $ do
runParser argumentParser "-10" `shouldBe` Right (VolumeOffset (-10), "")
it "returns nothing if given only a sign" $ do
runParser (argumentParser :: Parser Volume) "+" `shouldSatisfy` isLeft
it "fails if exact volume exceeds 0-100" $ do
runParser (argumentParser :: Parser Volume) "110" `shouldSatisfy` isLeft
it "fails if offset exceeds 0-100" $ do
runParser (argumentParser :: Parser Volume) "+110" `shouldSatisfy` isLeft
| haasn/vimus | test/Vimus/CommandSpec.hs | mit | 2,658 | 0 | 23 | 644 | 722 | 355 | 367 | 52 | 3 |
{- This module contains code for escaping/unescaping text in attributes
and elements in the HaXml Element type, replacing characters by character
references or vice-versa. Two uses are envisaged for this:
(1) stopping HaXml generating incorrect XML when a character is included
which is also the appropriate XML terminating character, for example
when an attribute includes a double quote.
(2) representing XML which contains non-ASCII characters as ASCII.
-}
module Text.XML.HaXml.Escape(
xmlEscape,
-- :: XmlEscaper -> Element i -> Element i
xmlUnEscape,
-- :: XmlEscaper -> Element i -> Element i
xmlEscapeContent,
-- :: XmlEscaper -> [Content i] -> [Content i]
xmlUnEscapeContent,
-- :: XmlEscaper -> [Content i] -> [Content i]
XmlEscaper,
-- Something describing a particular set of escapes.
stdXmlEscaper,
-- Standard boilerplate escaper, escaping everything that is
-- nonprintable, non-ASCII, or might conceivably cause problems by
-- parsing XML, for example quotes, < signs, and ampersands.
mkXmlEscaper,
-- :: [(Char,String)] -> (Char -> Bool) -> XmlEscaper
-- The first argument contains a list of characters, with their
-- corresponding character reference names.
-- For example [('\60',"lt"),('\62',"gt"),('\38',"amp"),
-- ('\39',"apos"),('\34',"quot")] will give you the "standard"
-- XML escapes listed in section 4.6 of the XML standard, so that
-- """ will automatically get translated into a double
-- quotation mark.
--
-- It's the caller's responsibility to see that the reference
-- names ("lt","gt","amp","apos" and "quot" in the above example)
-- are valid XML reference names. A sequence of letters, digits,
-- "." or ":" characters should be fine so long as the first one
-- isn't a digit.
--
-- The second argument is a function applied to each text character.
-- If it returns True, that means we should escape this character.
-- Policy: on escaping, we expand all characters for which the
-- (Char -> Bool) function returns True, either giving the corresponding
-- character reference name if one was supplied, or else using a
-- hexadecimal CharRef.
--
-- on unescaping, we translate all the references we understand
-- (hexadecimal,decimal, and the ones in the [(Char,String)] list,
-- and leave the others alone.
) where
import Data.Char
-- import Numeric
import Text.XML.HaXml.Types
#if __GLASGOW_HASKELL__ >= 604 || __NHC__ >= 118 || defined(__HUGS__)
-- emulate older finite map interface using Data.Map, if it is available
import qualified Data.Map as Map
type FiniteMap a b = Map.Map a b
listToFM :: Ord a => [(a,b)] -> FiniteMap a b
listToFM = Map.fromList
lookupFM :: Ord a => FiniteMap a b -> a -> Maybe b
lookupFM = flip Map.lookup
#elif __GLASGOW_HASKELL__ >= 504 || __NHC__ > 114
-- real finite map, if it is available
import Data.FiniteMap
#else
-- otherwise, a very simple and inefficient implementation of a finite map
type FiniteMap a b = [(a,b)]
listToFM :: Eq a => [(a,b)] -> FiniteMap a b
listToFM = id
lookupFM :: Eq a => FiniteMap a b -> a -> Maybe b
lookupFM fm k = lookup k fm
#endif
-- ------------------------------------------------------------------------
-- Data types
-- ------------------------------------------------------------------------
data XmlEscaper = XmlEscaper {
toEscape :: FiniteMap Char String,
fromEscape :: FiniteMap String Char,
isEscape :: Char -> Bool
}
-- ------------------------------------------------------------------------
-- Escaping
-- ------------------------------------------------------------------------
xmlEscape :: XmlEscaper -> Element i -> Element i
xmlEscape xmlEscaper element =
compressElement (escapeElement xmlEscaper element)
xmlEscapeContent :: XmlEscaper -> [Content i] -> [Content i]
xmlEscapeContent xmlEscaper cs =
compressContent (escapeContent xmlEscaper cs)
escapeElement :: XmlEscaper -> Element i -> Element i
escapeElement xmlEscaper (Elem name attributes content) =
Elem name (escapeAttributes xmlEscaper attributes)
(escapeContent xmlEscaper content)
escapeAttributes :: XmlEscaper -> [Attribute] -> [Attribute]
escapeAttributes xmlEscaper atts =
map
(\ (name,av) -> (name,escapeAttValue xmlEscaper av))
atts
escapeAttValue :: XmlEscaper -> AttValue -> AttValue
escapeAttValue xmlEscaper (AttValue attValList) =
AttValue (
concat (
map
(\ av -> case av of
Right _ -> [av]
Left s ->
map
(\ c -> if isEscape xmlEscaper c
then
Right (mkEscape xmlEscaper c)
else
Left [c]
)
s
)
attValList
)
)
escapeContent :: XmlEscaper -> [Content i] -> [Content i]
escapeContent xmlEscaper contents =
concat
(map
(\ content -> case content of
(CString b str i) ->
map
(\ c -> if isEscape xmlEscaper c
then
CRef (mkEscape xmlEscaper c) i
else
CString b [c] i
)
str
(CElem element i) -> [CElem (escapeElement xmlEscaper element) i]
_ -> [content]
)
contents
)
mkEscape :: XmlEscaper -> Char -> Reference
mkEscape (XmlEscaper {toEscape = toescape}) ch =
case lookupFM toescape ch of
Nothing -> RefChar (ord ch)
Just str -> RefEntity str
-- where
-- _ = showIntAtBase 16 intToDigit
-- -- It should be, but in GHC it isn't.
-- ------------------------------------------------------------------------
-- Unescaping
-- ------------------------------------------------------------------------
xmlUnEscape :: XmlEscaper -> Element i -> Element i
xmlUnEscape xmlEscaper element =
compressElement (unEscapeElement xmlEscaper element)
xmlUnEscapeContent :: XmlEscaper -> [Content i] -> [Content i]
xmlUnEscapeContent xmlEscaper cs =
compressContent (unEscapeContent xmlEscaper cs)
unEscapeElement :: XmlEscaper -> Element i -> Element i
unEscapeElement xmlEscaper (Elem name attributes content) =
Elem name (unEscapeAttributes xmlEscaper attributes)
(unEscapeContent xmlEscaper content)
unEscapeAttributes :: XmlEscaper -> [Attribute] -> [Attribute]
unEscapeAttributes xmlEscaper atts =
map
(\ (name,av) -> (name,unEscapeAttValue xmlEscaper av))
atts
unEscapeAttValue :: XmlEscaper -> AttValue -> AttValue
unEscapeAttValue xmlEscaper (AttValue attValList) =
AttValue (
map
(\ av -> case av of
Left _ -> av
Right ref -> case unEscapeChar xmlEscaper ref of
Just c -> Left [c]
Nothing -> av
)
attValList
)
unEscapeContent :: XmlEscaper -> [Content i] -> [Content i]
unEscapeContent xmlEscaper content =
map
(\ cntnt -> case cntnt of
CRef ref i -> case unEscapeChar xmlEscaper ref of
Just c -> CString False [c] i
Nothing -> cntnt
CElem element i -> CElem (unEscapeElement xmlEscaper element) i
_ -> cntnt
)
content
unEscapeChar :: XmlEscaper -> Reference -> Maybe Char
unEscapeChar xmlEscaper ref =
case ref of
RefChar i -> Just (chr i)
RefEntity name -> lookupFM (fromEscape xmlEscaper) name
-- ------------------------------------------------------------------------
-- After escaping and unescaping we rebuild the lists, compressing
-- adjacent identical character data.
-- ------------------------------------------------------------------------
compressElement :: Element i -> Element i
compressElement (Elem name attributes content) =
Elem name (compressAttributes attributes) (compressContent content)
compressAttributes :: [(QName,AttValue)] -> [(QName,AttValue)]
compressAttributes atts =
map
(\ (name,av) -> (name,compressAttValue av))
atts
compressAttValue :: AttValue -> AttValue
compressAttValue (AttValue l) = AttValue (compress l)
where
compress :: [Either String Reference] -> [Either String Reference]
compress [] = []
compress (Right ref : es) = Right ref : (compress es)
compress ( (ls @ (Left s1)) : es) =
case compress es of
(Left s2 : es2) -> Left (s1 ++ s2) : es2
es2 -> ls : es2
compressContent :: [Content i] -> [Content i]
compressContent [] = []
compressContent ((csb @ (CString b1 s1 i1)) : cs) =
case compressContent cs of
(CString b2 s2 _) : cs2
| b1 == b2
-> CString b1 (s1 ++ s2) i1: cs2
cs2 -> csb : cs2
compressContent (CElem element i : cs) =
CElem (compressElement element) i : compressContent cs
compressContent (c : cs) = c : compressContent cs
-- ------------------------------------------------------------------------
-- Making XmlEscaper values.
-- ------------------------------------------------------------------------
stdXmlEscaper :: XmlEscaper
stdXmlEscaper = mkXmlEscaper
[('\60',"lt"),('\62',"gt"),('\38',"amp"),('\39',"apos"),('\34',"quot")]
(\ ch ->
let
i = ord ch
in
i < 10 || (10<i && i<32) || i >= 127 ||
case ch of
'\'' -> True
'\"' -> True
'&' -> True
'<' -> True
'>' -> True
_ -> False
)
mkXmlEscaper :: [(Char,String)] -> (Char -> Bool) -> XmlEscaper
mkXmlEscaper escapes isescape =
XmlEscaper {
toEscape = listToFM escapes,
fromEscape = listToFM (map (\ (c,str) -> (str,c)) escapes),
isEscape = isescape
}
| alexbaluta/courseography | dependencies/HaXml-1.25.3/src/Text/XML/HaXml/Escape.hs | gpl-3.0 | 10,049 | 2 | 21 | 2,745 | 2,007 | 1,059 | 948 | 155 | 6 |
<?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="de-DE">
<title>Context Alert Filters | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/alertFilters/resources/help_de_DE/helpset_de_DE.hs | apache-2.0 | 983 | 80 | 66 | 161 | 417 | 211 | 206 | -1 | -1 |
{-# LANGUAGE DeriveFunctor, ExistentialQuantification, Rank2Types, UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : FreeGame.UI
-- Copyright : (C) 2013 Fumiaki Kinoshita
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Fumiaki Kinoshita <fumiexcel@gmail.com>
-- Stability : provisional
-- Portability : non-portable
-- Provides the "free" embodiment.
----------------------------------------------------------------------------
module FreeGame.UI (
UI(..)
, Drawable
, reUI
, reFrame
, reGame
, Frame
, Game
, FreeGame(..)
) where
import FreeGame.Class
import FreeGame.Internal.Finalizer
import FreeGame.Types
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import qualified Data.Map as Map
import FreeGame.Data.Bitmap (Bitmap)
import Data.Color
import Control.Monad.Free.Church (F, iterM)
import Control.Monad.Trans.Iter (IterT, foldM)
import Control.Monad (join)
class (Applicative f, Monad f, Picture2D f, Local f) => Drawable f where { }
instance (Applicative f, Monad f, Picture2D f, Local f) => Drawable f where { }
data UI a =
Draw (forall m. Drawable m => m a)
| PreloadBitmap Bitmap a
| FromFinalizer (FinalizerT IO a)
| KeyStates (Map.Map Key ButtonState -> a)
| MouseButtons (Map.Map Int ButtonState -> a)
| MousePosition (Vec2 -> a)
| MouseInWindow (Bool -> a)
| MouseScroll (Vec2 -> a)
| TakeScreenshot (Bitmap -> a)
| Bracket (Frame a)
| SetFPS Double a
| SetTitle String a
| ShowCursor a
| HideCursor a
| ClearColor (Color Float) a
| GetFPS (Int -> a)
| ForkFrame (Frame ()) a
| GetBoundingBox (BoundingBox2 -> a)
| SetBoundingBox BoundingBox2 a
deriving Functor
type Game = IterT Frame
type Frame = F UI
-- | Generalize `Game` to any monad based on `FreeGame`.
reGame :: (FreeGame m, Monad m) => Game a -> m a
reGame = Control.Monad.Trans.Iter.foldM (join . reFrame)
{-# RULES "reGame/sameness" reGame = id #-}
{-# INLINE[1] reGame #-}
-- | Generalize `Frame` to any monad based on `FreeGame`.
reFrame :: (FreeGame m, Monad m) => Frame a -> m a
reFrame = iterM (join . reUI)
{-# RULES "reFrame/sameness" reFrame = id #-}
{-# INLINE[1] reFrame #-}
reUI :: FreeGame f => UI a -> f a
reUI (Draw m) = draw m
reUI (PreloadBitmap bmp cont) = cont <$ preloadBitmap bmp
reUI (FromFinalizer m) = fromFinalizer m
reUI (KeyStates cont) = cont <$> keyStates_
reUI (MouseButtons cont) = cont <$> mouseButtons_
reUI (MousePosition cont) = cont <$> globalMousePosition
reUI (MouseInWindow cont) = cont <$> mouseInWindow
reUI (MouseScroll cont) = cont <$> mouseScroll
reUI (TakeScreenshot cont) = cont <$> takeScreenshot
reUI (Bracket m) = bracket m
reUI (SetFPS i cont) = cont <$ setFPS i
reUI (SetTitle t cont) = cont <$ setTitle t
reUI (ShowCursor cont) = cont <$ showCursor
reUI (HideCursor cont) = cont <$ hideCursor
reUI (ClearColor col cont) = cont <$ clearColor col
reUI (GetFPS cont) = cont <$> getFPS
reUI (ForkFrame m cont) = cont <$ forkFrame m
reUI (GetBoundingBox cont) = cont <$> getBoundingBox
reUI (SetBoundingBox bb cont) = cont <$ setBoundingBox bb
{-# INLINE[1] reUI #-}
{-# RULES "reUI/sameness" reUI = id #-}
class (Picture2D m, Local m, Keyboard m, Mouse m, FromFinalizer m) => FreeGame m where
-- | Draw an action that consist of 'Picture2D''s methods.
draw :: (forall f. Drawable f => f a) -> m a
-- | Load a 'Bitmap' to avoid the cost of the first invocation of 'bitmap'.
preloadBitmap :: Bitmap -> m ()
-- | Run a 'Frame', and release all the matter happened.
bracket :: Frame a -> m a
-- | Run a 'Frame' action concurrently. Do not use this function to draw pictures.
forkFrame :: Frame () -> m ()
-- | Generate a 'Bitmap' from the front buffer.
takeScreenshot :: m Bitmap
-- | Set the goal FPS.
setFPS :: Double -> m ()
setTitle :: String -> m ()
showCursor :: m ()
hideCursor :: m ()
clearColor :: Color Float -> m ()
-- | Get the actual FPS value.
getFPS :: m Int
getBoundingBox :: m BoundingBox2
setBoundingBox :: BoundingBox2 -> m ()
instance FreeGame UI where
draw = Draw
{-# INLINE draw #-}
preloadBitmap bmp = PreloadBitmap bmp ()
{-# INLINE preloadBitmap #-}
bracket = Bracket
{-# INLINE bracket #-}
forkFrame m = ForkFrame m ()
takeScreenshot = TakeScreenshot id
setFPS a = SetFPS a ()
setTitle t = SetTitle t ()
showCursor = ShowCursor ()
hideCursor = HideCursor ()
clearColor c = ClearColor c ()
getFPS = GetFPS id
getBoundingBox = GetBoundingBox id
setBoundingBox s = SetBoundingBox s ()
overDraw :: (forall m. Drawable m => m a -> m a) -> UI a -> UI a
overDraw f (Draw m) = Draw (f m)
overDraw _ x = x
{-# INLINE overDraw #-}
instance Affine UI where
translate v = overDraw (translate v)
{-# INLINE translate #-}
rotateR t = overDraw (rotateR t)
{-# INLINE rotateR #-}
rotateD t = overDraw (rotateD t)
{-# INLINE rotateD #-}
scale v = overDraw (scale v)
{-# INLINE scale #-}
instance Picture2D UI where
bitmap x = Draw (bitmap x)
{-# INLINE bitmap #-}
bitmapOnce x = Draw (bitmapOnce x)
{-# INLINE bitmapOnce #-}
line vs = Draw (line vs)
polygon vs = Draw (polygon vs)
polygonOutline vs = Draw (polygonOutline vs)
circle r = Draw (circle r)
circleOutline r = Draw (circleOutline r)
thickness t = overDraw (thickness t)
{-# INLINE thickness #-}
color c = overDraw (color c)
{-# INLINE color #-}
blendMode m = overDraw (blendMode m)
{-# INLINE blendMode #-}
instance Local UI where
getLocation = Draw getLocation
instance FromFinalizer UI where
fromFinalizer = FromFinalizer
{-# INLINE fromFinalizer #-}
instance Keyboard UI where
keyStates_ = KeyStates id
instance Mouse UI where
globalMousePosition = MousePosition id
-- mouseWheel = MouseWheel id
mouseButtons_ = MouseButtons id
mouseInWindow = MouseInWindow id
mouseScroll = MouseScroll id
| jwvg0425/free-game | FreeGame/UI.hs | bsd-3-clause | 6,299 | 0 | 11 | 1,553 | 1,772 | 930 | 842 | -1 | -1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveFoldable, DeriveTraversable #-}
module Distribution.Client.Dependency.Modular.PSQ
( PSQ(..) -- Unit test needs constructor access
, casePSQ
, cons
, delete
, length
, llength
, lookup
, filter
, filterKeys
, fromList
, keys
, map
, mapKeys
, mapWithKey
, mapWithKeyState
, null
, snoc
, sortBy
, sortByKeys
, splits
, toList
, union
) where
-- Priority search queues.
--
-- I am not yet sure what exactly is needed. But we need a data structure with
-- key-based lookup that can be sorted. We're using a sequence right now with
-- (inefficiently implemented) lookup, because I think that queue-based
-- operations and sorting turn out to be more efficiency-critical in practice.
import qualified Data.Foldable as F
import Data.Function
import qualified Data.List as S
import Data.Traversable
import Prelude hiding (foldr, length, lookup, filter, null, map)
newtype PSQ k v = PSQ [(k, v)]
deriving (Eq, Show, Functor, F.Foldable, Traversable) -- Qualified Foldable to avoid issues with FTP
keys :: PSQ k v -> [k]
keys (PSQ xs) = fmap fst xs
lookup :: Eq k => k -> PSQ k v -> Maybe v
lookup k (PSQ xs) = S.lookup k xs
map :: (v1 -> v2) -> PSQ k v1 -> PSQ k v2
map f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f v)) xs)
mapKeys :: (k1 -> k2) -> PSQ k1 v -> PSQ k2 v
mapKeys f (PSQ xs) = PSQ (fmap (\ (k, v) -> (f k, v)) xs)
mapWithKey :: (k -> a -> b) -> PSQ k a -> PSQ k b
mapWithKey f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f k v)) xs)
mapWithKeyState :: (s -> k -> a -> (b, s)) -> PSQ k a -> s -> PSQ k b
mapWithKeyState p (PSQ xs) s0 =
PSQ (F.foldr (\ (k, v) r s -> case p s k v of
(w, n) -> (k, w) : (r n))
(const []) xs s0)
delete :: Eq k => k -> PSQ k a -> PSQ k a
delete k (PSQ xs) = PSQ (snd (S.partition ((== k) . fst) xs))
fromList :: [(k, a)] -> PSQ k a
fromList = PSQ
cons :: k -> a -> PSQ k a -> PSQ k a
cons k x (PSQ xs) = PSQ ((k, x) : xs)
snoc :: PSQ k a -> k -> a -> PSQ k a
snoc (PSQ xs) k x = PSQ (xs ++ [(k, x)])
casePSQ :: PSQ k a -> r -> (k -> a -> PSQ k a -> r) -> r
casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys)
splits :: PSQ k a -> PSQ k (a, PSQ k a)
splits = go id
where
go f xs = casePSQ xs
(PSQ [])
(\ k v ys -> cons k (v, f ys) (go (f . cons k v) ys))
sortBy :: (a -> a -> Ordering) -> PSQ k a -> PSQ k a
sortBy cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` snd) xs)
sortByKeys :: (k -> k -> Ordering) -> PSQ k a -> PSQ k a
sortByKeys cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` fst) xs)
filterKeys :: (k -> Bool) -> PSQ k a -> PSQ k a
filterKeys p (PSQ xs) = PSQ (S.filter (p . fst) xs)
filter :: (a -> Bool) -> PSQ k a -> PSQ k a
filter p (PSQ xs) = PSQ (S.filter (p . snd) xs)
length :: PSQ k a -> Int
length (PSQ xs) = S.length xs
-- | "Lazy length".
--
-- Only approximates the length, but doesn't force the list.
llength :: PSQ k a -> Int
llength (PSQ []) = 0
llength (PSQ (_:[])) = 1
llength (PSQ (_:_:[])) = 2
llength (PSQ _) = 3
null :: PSQ k a -> Bool
null (PSQ xs) = S.null xs
toList :: PSQ k a -> [(k, a)]
toList (PSQ xs) = xs
union :: PSQ k a -> PSQ k a -> PSQ k a
union (PSQ xs) (PSQ ys) = PSQ (xs ++ ys)
| randen/cabal | cabal-install/Distribution/Client/Dependency/Modular/PSQ.hs | bsd-3-clause | 3,330 | 0 | 15 | 936 | 1,644 | 871 | 773 | 85 | 2 |
-- {-# LANGUAGE ScopedTypeVariables #-}
{- |
Finite categories are categories with a finite number of arrows.
In our case, this corresponds to functions with finite domains (and hence, ranges).
These functions have a number of possible representations.
Which is best will depend on the given function.
One common property is that these functions support decidable equality.
-}
module SubHask.Category.Finite
(
-- * Function representations
-- ** Sparse permutations
SparseFunction
, proveSparseFunction
, list2sparseFunction
-- ** Sparse monoids
, SparseFunctionMonoid
-- ** Dense functions
, DenseFunction
, proveDenseFunction
-- * Finite types
, FiniteType (..)
, ZIndex
)
where
import Control.Monad
import GHC.Prim
import GHC.TypeLits
import Data.Proxy
import qualified Data.Map as Map
import qualified Data.Vector.Unboxed as VU
import qualified Prelude as P
import SubHask.Algebra
import SubHask.Algebra.Group
import SubHask.Category
import SubHask.Internal.Prelude
import SubHask.SubType
import SubHask.TemplateHaskell.Deriving
-------------------------------------------------------------------------------
-- | A type is finite if there is a bijection between it and the natural numbers.
-- The 'index'/'deZIndex' functions implement this bijection.
class KnownNat (Order a) => FiniteType a where
type Order a :: Nat
index :: a -> ZIndex a
deZIndex :: ZIndex a -> a
enumerate :: [a]
getOrder :: a -> Integer
instance KnownNat n => FiniteType (Z n) where
type Order (Z n) = n
index i = ZIndex i
deZIndex (ZIndex i) = i
enumerate = [ mkQuotient i | i <- [0..n - 1] ]
where
n = natVal (Proxy :: Proxy n)
getOrder z = natVal (Proxy :: Proxy n)
-- | The 'ZIndex' class is a newtype wrapper around the natural numbers 'Z'.
--
-- FIXME: remove this layer; I don't think it helps
--
newtype ZIndex a = ZIndex (Z (Order a))
deriveHierarchy ''ZIndex [ ''Eq_, ''P.Ord ]
-- | Swap the phantom type between two indices.
swapZIndex :: Order a ~ Order b => ZIndex a -> ZIndex b
swapZIndex (ZIndex i) = ZIndex i
-------------------------------------------------------------------------------
-- | Represents finite functions as a map associating input/output pairs.
data SparseFunction a b where
SparseFunction ::
( FiniteType a
, FiniteType b
, Order a ~ Order b
) => Map.Map (ZIndex a) (ZIndex b) -> SparseFunction a b
instance Category SparseFunction where
type ValidCategory SparseFunction a =
( FiniteType a
)
id = SparseFunction $ Map.empty
(SparseFunction f1).(SparseFunction f2) = SparseFunction
(Map.map (\a -> find a f1) f2)
where
find k map = case Map.lookup k map of
Just v -> v
Nothing -> swapZIndex k
-- instance Sup SparseFunction (->) (->)
-- instance Sup (->) SparseFunction (->)
-- instance SparseFunction <: (->) where
-- embedType_ = Embed2 $ map2function f
-- where
-- map2function map k = case Map.lookup (index k) map of
-- Just v -> deZIndex v
-- Nothing -> deZIndex $ swapZIndex $ index k
-- | Generates a sparse representation of a 'Hask' function.
-- This proof will always succeed, although it may be computationally expensive if the 'Order' of a and b is large.
proveSparseFunction ::
( ValidCategory SparseFunction a
, ValidCategory SparseFunction b
, Order a ~ Order b
) => (a -> b) -> SparseFunction a b
proveSparseFunction f = SparseFunction
$ Map.fromList
$ P.map (\a -> (index a,index $ f a)) enumerate
-- | Generate sparse functions on some subset of the domain.
list2sparseFunction ::
( ValidCategory SparseFunction a
, ValidCategory SparseFunction b
, Order a ~ Order b
) => [Z (Order a)] -> SparseFunction a b
list2sparseFunction xs = SparseFunction $ Map.fromList $ go xs
where
go (y:[]) = [(ZIndex y, ZIndex $ P.head xs)]
go (y1:y2:ys) = (ZIndex y1,ZIndex y2):go (y2:ys)
-------------------------------------------------------------------------------
data SparseFunctionMonoid a b where
SparseFunctionMonoid ::
( FiniteType a
, FiniteType b
, Monoid a
, Monoid b
, Order a ~ Order b
) => Map.Map (ZIndex a) (ZIndex b) -> SparseFunctionMonoid a b
instance Category SparseFunctionMonoid where
type ValidCategory SparseFunctionMonoid a =
( FiniteType a
, Monoid a
)
id :: forall a. ValidCategory SparseFunctionMonoid a => SparseFunctionMonoid a a
id = SparseFunctionMonoid $ Map.fromList $ P.zip xs xs
where
xs = P.map index (enumerate :: [a])
(SparseFunctionMonoid f1).(SparseFunctionMonoid f2) = SparseFunctionMonoid
(Map.map (\a -> find a f1) f2)
where
find k map = case Map.lookup k map of
Just v -> v
Nothing -> index zero
-- instance Sup SparseFunctionMonoid (->) (->)
-- instance Sup (->) SparseFunctionMonoid (->)
-- instance (SparseFunctionMonoid <: (->)) where
-- embedType_ = Embed2 $ map2function f
-- where
-- map2function map k = case Map.lookup (index k) map of
-- Just v -> deZIndex v
-- Nothing -> zero
---------------------------------------
{-
instance (FiniteType b, Semigroup b) => Semigroup (SparseFunctionMonoid a b) where
(SparseFunctionMonoid f1)+(SparseFunctionMonoid f2) = SparseFunctionMonoid $ Map.unionWith go f1 f2
where
go b1 b2 = index $ deZIndex b1 + deZIndex b2
instance
( FiniteType a
, FiniteType b
, Monoid a
, Monoid b
, Order a ~ Order b
) => Monoid (SparseFunctionMonoid a b) where
zero = SparseFunctionMonoid $ Map.empty
instance
( FiniteType b
, Abelian b
) => Abelian (SparseFunctionMonoid a b)
instance (FiniteType b, Group b) => Group (SparseFunctionMonoid a b) where
negate (SparseFunctionMonoid f) = SparseFunctionMonoid $ Map.map (index.negate.deZIndex) f
type instance Scalar (SparseFunctionMonoid a b) = Scalar b
instance (FiniteType b, Module b) => Module (SparseFunctionMonoid a b) where
r *. (SparseFunctionMonoid f) = SparseFunctionMonoid $ Map.map (index.(r*.).deZIndex) f
instance (FiniteType b, VectorSpace b) => VectorSpace (SparseFunctionMonoid a b) where
(SparseFunctionMonoid f) ./ r = SparseFunctionMonoid $ Map.map (index.(./r).deZIndex) f
-}
-------------------------------------------------------------------------------
-- | Represents finite functions as a hash table associating input/output value pairs.
data DenseFunction (a :: *) (b :: *) where
DenseFunction ::
( FiniteType a
, FiniteType b
) => VU.Vector Int -> DenseFunction a b
instance Category DenseFunction where
type ValidCategory DenseFunction (a :: *) =
( FiniteType a
)
id :: forall a. ValidCategory DenseFunction a => DenseFunction a a
id = DenseFunction $ VU.generate n id
where
n = fromIntegral $ natVal (Proxy :: Proxy (Order a))
(DenseFunction f).(DenseFunction g) = DenseFunction $ VU.map (f VU.!) g
-- instance SubCategory DenseFunction (->) where
-- embed (DenseFunction f) = \x -> deZIndex $ int2index $ f VU.! (index2int $ index x)
-- | Generates a dense representation of a 'Hask' function.
-- This proof will always succeed; however, if the 'Order' of the finite types
-- are very large, it may take a long time.
-- In that case, a `SparseFunction` is probably the better representation.
proveDenseFunction :: forall a b.
( ValidCategory DenseFunction a
, ValidCategory DenseFunction b
) => (a -> b) -> DenseFunction a b
proveDenseFunction f = DenseFunction $ VU.generate n (index2int . index . f . deZIndex . int2index)
where
n = fromIntegral $ natVal (Proxy :: Proxy (Order a))
---------------------------------------
-- internal functions only
int2index :: Int -> ZIndex a
int2index i = ZIndex $ Mod $ fromIntegral i
index2int :: ZIndex a -> Int
index2int (ZIndex (Mod i)) = fromIntegral i
| abailly/subhask | src/SubHask/Category/Finite.hs | bsd-3-clause | 8,189 | 73 | 10 | 1,964 | 1,499 | 817 | 682 | -1 | -1 |
--
-- Copyright (c) 2012 Citrix Systems, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module OVF.Verify
(
missingLocalFiles
, verifyManifestFile
) where
import Control.Applicative
import Control.Monad
import System.Directory
import System.FilePath
import System.IO
import Text.Printf
import Tools.File
import Core.Types
import OVF.Model
import OVF.Manifest
missingLocalFiles :: FilePath -> [FileRef] -> IO [FileRef]
missingLocalFiles ovfRoot = filterM missing where
missing f = do
case parseURI (fileHref f) of
Nothing -> return False
Just uri -> case uriScheme uri of
"" -> not <$> doesFileExist (ovfRoot </> uriLocation uri)
"file" -> not <$> doesFileExist (uriLocation uri)
_ -> return False
verifyManifestFile :: FilePath -> FilePath -> [FileRef] -> IO ()
verifyManifestFile mfpath root refs = withManifest =<< (parseManifest <$> readFile mfpath) where
withManifest (Left err) = error ("error in manifest file: " ++ show err)
withManifest (Right mf) = mapM_ verifyFileDigest mf
verifyFileDigest (FileDigest fname alg csum) = do
let f = root </> fname
hPutStrLn stderr $ "verification of checksum for " ++ fname
csum' <- case alg of
Sha1 -> fileSha1Sum f
Sha256 -> fileSha256Sum f
when (csum /= csum') $
let showcs c = printf "%0x" c in
error ("mismatched checksum for " ++ show fname ++ " expected " ++ (showcs csum) ++ " have " ++ (showcs csum'))
| jean-edouard/manager | apptool/OVF/Verify.hs | gpl-2.0 | 2,176 | 0 | 19 | 479 | 466 | 239 | 227 | 36 | 4 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns
, CPP
, ExistentialQuantification
, NoImplicitPrelude
, RecordWildCards
, TypeSynonymInstances
, FlexibleInstances
#-}
-- |
-- The event manager supports event notification on fds. Each fd may
-- have multiple callbacks registered, each listening for a different
-- set of events. Registrations may be automatically deactivated after
-- the occurrence of an event ("one-shot mode") or active until
-- explicitly unregistered.
--
-- If an fd has only one-shot registrations then we use one-shot
-- polling if available. Otherwise we use multi-shot polling.
module GHC.Event.Manager
( -- * Types
EventManager
-- * Creation
, new
, newWith
, newDefaultBackend
-- * Running
, finished
, loop
, step
, shutdown
, release
, cleanup
, wakeManager
-- * State
, callbackTableVar
, emControl
-- * Registering interest in I/O events
, Lifetime (..)
, Event
, evtRead
, evtWrite
, IOCallback
, FdKey(keyFd)
, FdData
, registerFd
, unregisterFd_
, unregisterFd
, closeFd
, closeFd_
) where
#include "EventConfig.h"
------------------------------------------------------------------------
-- Imports
import Control.Concurrent.MVar (MVar, newMVar, putMVar,
tryPutMVar, takeMVar, withMVar)
import Control.Exception (onException)
import Data.Bits ((.&.))
import Data.Foldable (forM_)
import Data.Functor (void)
import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef,
writeIORef)
import Data.Maybe (maybe)
import Data.OldList (partition)
import GHC.Arr (Array, (!), listArray)
import GHC.Base
import GHC.Conc.Sync (yield)
import GHC.List (filter, replicate)
import GHC.Num (Num(..))
import GHC.Real (fromIntegral)
import GHC.Show (Show(..))
import GHC.Event.Control
import GHC.Event.IntTable (IntTable)
import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite,
Lifetime(..), EventLifetime, Timeout(..))
import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique)
import System.Posix.Types (Fd)
import qualified GHC.Event.IntTable as IT
import qualified GHC.Event.Internal as I
#if defined(HAVE_KQUEUE)
import qualified GHC.Event.KQueue as KQueue
#elif defined(HAVE_EPOLL)
import qualified GHC.Event.EPoll as EPoll
#elif defined(HAVE_POLL)
import qualified GHC.Event.Poll as Poll
#else
# error not implemented for this operating system
#endif
------------------------------------------------------------------------
-- Types
data FdData = FdData {
fdKey :: {-# UNPACK #-} !FdKey
, fdEvents :: {-# UNPACK #-} !EventLifetime
, _fdCallback :: !IOCallback
}
-- | A file descriptor registration cookie.
data FdKey = FdKey {
keyFd :: {-# UNPACK #-} !Fd
, keyUnique :: {-# UNPACK #-} !Unique
} deriving (Eq, Show)
-- | Callback invoked on I/O events.
type IOCallback = FdKey -> Event -> IO ()
data State = Created
| Running
| Dying
| Releasing
| Finished
deriving (Eq, Show)
-- | The event manager state.
data EventManager = EventManager
{ emBackend :: !Backend
, emFds :: {-# UNPACK #-} !(Array Int (MVar (IntTable [FdData])))
, emState :: {-# UNPACK #-} !(IORef State)
, emUniqueSource :: {-# UNPACK #-} !UniqueSource
, emControl :: {-# UNPACK #-} !Control
, emLock :: {-# UNPACK #-} !(MVar ())
}
-- must be power of 2
callbackArraySize :: Int
callbackArraySize = 32
hashFd :: Fd -> Int
hashFd fd = fromIntegral fd .&. (callbackArraySize - 1)
{-# INLINE hashFd #-}
callbackTableVar :: EventManager -> Fd -> MVar (IntTable [FdData])
callbackTableVar mgr fd = emFds mgr ! hashFd fd
{-# INLINE callbackTableVar #-}
haveOneShot :: Bool
{-# INLINE haveOneShot #-}
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
haveOneShot = False
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
haveOneShot = True
#else
haveOneShot = False
#endif
------------------------------------------------------------------------
-- Creation
handleControlEvent :: EventManager -> Fd -> Event -> IO ()
handleControlEvent mgr fd _evt = do
msg <- readControlMessage (emControl mgr) fd
case msg of
CMsgWakeup -> return ()
CMsgDie -> writeIORef (emState mgr) Finished
_ -> return ()
newDefaultBackend :: IO Backend
#if defined(HAVE_KQUEUE)
newDefaultBackend = KQueue.new
#elif defined(HAVE_EPOLL)
newDefaultBackend = EPoll.new
#elif defined(HAVE_POLL)
newDefaultBackend = Poll.new
#else
newDefaultBackend = error "no back end for this platform"
#endif
-- | Create a new event manager.
new :: IO EventManager
new = newWith =<< newDefaultBackend
-- | Create a new 'EventManager' with the given polling backend.
newWith :: Backend -> IO EventManager
newWith be = do
iofds <- fmap (listArray (0, callbackArraySize-1)) $
replicateM callbackArraySize (newMVar =<< IT.new 8)
ctrl <- newControl False
state <- newIORef Created
us <- newSource
_ <- mkWeakIORef state $ do
st <- atomicModifyIORef' state $ \s -> (Finished, s)
when (st /= Finished) $ do
I.delete be
closeControl ctrl
lockVar <- newMVar ()
let mgr = EventManager { emBackend = be
, emFds = iofds
, emState = state
, emUniqueSource = us
, emControl = ctrl
, emLock = lockVar
}
registerControlFd mgr (controlReadFd ctrl) evtRead
registerControlFd mgr (wakeupReadFd ctrl) evtRead
return mgr
where
replicateM n x = sequence (replicate n x)
failOnInvalidFile :: String -> Fd -> IO Bool -> IO ()
failOnInvalidFile loc fd m = do
ok <- m
when (not ok) $
let msg = "Failed while attempting to modify registration of file " ++
show fd ++ " at location " ++ loc
in error msg
registerControlFd :: EventManager -> Fd -> Event -> IO ()
registerControlFd mgr fd evs =
failOnInvalidFile "registerControlFd" fd $
I.modifyFd (emBackend mgr) fd mempty evs
-- | Asynchronously shuts down the event manager, if running.
shutdown :: EventManager -> IO ()
shutdown mgr = do
state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s)
when (state == Running) $ sendDie (emControl mgr)
-- | Asynchronously tell the thread executing the event
-- manager loop to exit.
release :: EventManager -> IO ()
release EventManager{..} = do
state <- atomicModifyIORef' emState $ \s -> (Releasing, s)
when (state == Running) $ sendWakeup emControl
finished :: EventManager -> IO Bool
finished mgr = (== Finished) `liftM` readIORef (emState mgr)
cleanup :: EventManager -> IO ()
cleanup EventManager{..} = do
writeIORef emState Finished
void $ tryPutMVar emLock ()
I.delete emBackend
closeControl emControl
------------------------------------------------------------------------
-- Event loop
-- | Start handling events. This function loops until told to stop,
-- using 'shutdown'.
--
-- /Note/: This loop can only be run once per 'EventManager', as it
-- closes all of its control resources when it finishes.
loop :: EventManager -> IO ()
loop mgr@EventManager{..} = do
void $ takeMVar emLock
state <- atomicModifyIORef' emState $ \s -> case s of
Created -> (Running, s)
Releasing -> (Running, s)
_ -> (s, s)
case state of
Created -> go `onException` cleanup mgr
Releasing -> go `onException` cleanup mgr
Dying -> cleanup mgr
-- While a poll loop is never forked when the event manager is in the
-- 'Finished' state, its state could read 'Finished' once the new thread
-- actually runs. This is not an error, just an unfortunate race condition
-- in Thread.restartPollLoop. See #8235
Finished -> return ()
_ -> do cleanup mgr
error $ "GHC.Event.Manager.loop: state is already " ++
show state
where
go = do state <- step mgr
case state of
Running -> yield >> go
Releasing -> putMVar emLock ()
_ -> cleanup mgr
-- | To make a step, we first do a non-blocking poll, in case
-- there are already events ready to handle. This improves performance
-- because we can make an unsafe foreign C call, thereby avoiding
-- forcing the current Task to release the Capability and forcing a context switch.
-- If the poll fails to find events, we yield, putting the poll loop thread at
-- end of the Haskell run queue. When it comes back around, we do one more
-- non-blocking poll, in case we get lucky and have ready events.
-- If that also returns no events, then we do a blocking poll.
step :: EventManager -> IO State
step mgr@EventManager{..} = do
waitForIO
state <- readIORef emState
state `seq` return state
where
waitForIO = do
n1 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n1 <= 0) $ do
yield
n2 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n2 <= 0) $ do
_ <- I.poll emBackend (Just Forever) (onFdEvent mgr)
return ()
------------------------------------------------------------------------
-- Registering interest in I/O events
-- | Register interest in the given events, without waking the event
-- manager thread. The 'Bool' return value indicates whether the
-- event manager ought to be woken.
--
-- Note that the event manager is generally implemented in terms of the
-- platform's @select@ or @epoll@ system call, which tend to vary in
-- what sort of fds are permitted. For instance, waiting on regular files
-- is not allowed on many platforms.
registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> Lifetime
-> IO (FdKey, Bool)
registerFd_ mgr@(EventManager{..}) cb fd evs lt = do
u <- newUnique emUniqueSource
let fd' = fromIntegral fd
reg = FdKey fd u
el = I.eventLifetime evs lt
!fdd = FdData reg el cb
(modify,ok) <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
oldFdd <- IT.insertWith (++) fd' [fdd] tbl
let prevEvs :: EventLifetime
prevEvs = maybe mempty eventsOf oldFdd
el' :: EventLifetime
el' = prevEvs `mappend` el
case I.elLifetime el' of
-- All registrations want one-shot semantics and this is supported
OneShot | haveOneShot -> do
ok <- I.modifyFdOnce emBackend fd (I.elEvent el')
if ok
then return (False, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- We don't want or don't support one-shot semantics
_ -> do
let modify = prevEvs /= el'
ok <- if modify
then let newEvs = I.elEvent el'
oldEvs = I.elEvent prevEvs
in I.modifyFd emBackend fd oldEvs newEvs
else return True
if ok
then return (modify, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- this simulates behavior of old IO manager:
-- i.e. just call the callback if the registration fails.
when (not ok) (cb reg evs)
return (reg,modify)
{-# INLINE registerFd_ #-}
-- | @registerFd mgr cb fd evs lt@ registers interest in the events @evs@
-- on the file descriptor @fd@ for lifetime @lt@. @cb@ is called for
-- each event that occurs. Returns a cookie that can be handed to
-- 'unregisterFd'.
registerFd :: EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey
registerFd mgr cb fd evs lt = do
(r, wake) <- registerFd_ mgr cb fd evs lt
when wake $ wakeManager mgr
return r
{-# INLINE registerFd #-}
{-
Building GHC with parallel IO manager on Mac freezes when
compiling the dph libraries in the phase 2. As workaround, we
don't use oneshot and we wake up an IO manager on Mac every time
when we register an event.
For more information, please read:
http://ghc.haskell.org/trac/ghc/ticket/7651
-}
-- | Wake up the event manager.
wakeManager :: EventManager -> IO ()
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
wakeManager mgr = sendWakeup (emControl mgr)
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
wakeManager _ = return ()
#else
wakeManager mgr = sendWakeup (emControl mgr)
#endif
eventsOf :: [FdData] -> EventLifetime
eventsOf [fdd] = fdEvents fdd
eventsOf fdds = mconcat $ map fdEvents fdds
-- | Drop a previous file descriptor registration, without waking the
-- event manager thread. The return value indicates whether the event
-- manager ought to be woken.
unregisterFd_ :: EventManager -> FdKey -> IO Bool
unregisterFd_ mgr@(EventManager{..}) (FdKey fd u) =
withMVar (callbackTableVar mgr fd) $ \tbl -> do
let dropReg = nullToNothing . filter ((/= u) . keyUnique . fdKey)
fd' = fromIntegral fd
pairEvents :: [FdData] -> IO (EventLifetime, EventLifetime)
pairEvents prev = do
r <- maybe mempty eventsOf `fmap` IT.lookup fd' tbl
return (eventsOf prev, r)
(oldEls, newEls) <- IT.updateWith dropReg fd' tbl >>=
maybe (return (mempty, mempty)) pairEvents
let modify = oldEls /= newEls
when modify $ failOnInvalidFile "unregisterFd_" fd $
case I.elLifetime newEls of
OneShot | I.elEvent newEls /= mempty, haveOneShot ->
I.modifyFdOnce emBackend fd (I.elEvent newEls)
_ ->
I.modifyFd emBackend fd (I.elEvent oldEls) (I.elEvent newEls)
return modify
-- | Drop a previous file descriptor registration.
unregisterFd :: EventManager -> FdKey -> IO ()
unregisterFd mgr reg = do
wake <- unregisterFd_ mgr reg
when wake $ wakeManager mgr
-- | Close a file descriptor in a race-safe way.
closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO ()
closeFd mgr close fd = do
fds <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
prev <- IT.delete (fromIntegral fd) tbl
case prev of
Nothing -> close fd >> return []
Just fds -> do
let oldEls = eventsOf fds
when (I.elEvent oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
close fd
return fds
forM_ fds $ \(FdData reg el cb) -> cb reg (I.elEvent el `mappend` evtClose)
-- | Close a file descriptor in a race-safe way.
-- It assumes the caller will update the callback tables and that the caller
-- holds the callback table lock for the fd. It must hold this lock because
-- this command executes a backend command on the fd.
closeFd_ :: EventManager
-> IntTable [FdData]
-> Fd
-> IO (IO ())
closeFd_ mgr tbl fd = do
prev <- IT.delete (fromIntegral fd) tbl
case prev of
Nothing -> return (return ())
Just fds -> do
let oldEls = eventsOf fds
when (oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
return $
forM_ fds $ \(FdData reg el cb) ->
cb reg (I.elEvent el `mappend` evtClose)
------------------------------------------------------------------------
-- Utilities
-- | Call the callbacks corresponding to the given file descriptor.
onFdEvent :: EventManager -> Fd -> Event -> IO ()
onFdEvent mgr fd evs
| fd == controlReadFd (emControl mgr) || fd == wakeupReadFd (emControl mgr) =
handleControlEvent mgr fd evs
| otherwise = do
fdds <- withMVar (callbackTableVar mgr fd) $ \tbl ->
IT.delete (fromIntegral fd) tbl >>= maybe (return []) (selectCallbacks tbl)
forM_ fdds $ \(FdData reg _ cb) -> cb reg evs
where
-- | Here we look through the list of registrations for the fd of interest
-- and sort out which match the events that were triggered. We,
--
-- 1. re-arm the fd as appropriate
-- 2. reinsert registrations that weren't triggered and multishot
-- registrations
-- 3. return a list containing the callbacks that should be invoked.
selectCallbacks :: IntTable [FdData] -> [FdData] -> IO [FdData]
selectCallbacks tbl fdds = do
let -- figure out which registrations have been triggered
matches :: FdData -> Bool
matches fd' = evs `I.eventIs` I.elEvent (fdEvents fd')
(triggered, notTriggered) = partition matches fdds
-- sort out which registrations we need to retain
isMultishot :: FdData -> Bool
isMultishot fd' = I.elLifetime (fdEvents fd') == MultiShot
saved = notTriggered ++ filter isMultishot triggered
savedEls = eventsOf saved
allEls = eventsOf fdds
-- Reinsert multishot registrations.
-- We deleted the table entry for this fd above so we there isn't a preexisting entry
_ <- IT.insertWith (\_ _ -> saved) (fromIntegral fd) saved tbl
case I.elLifetime allEls of
-- we previously armed the fd for multiple shots, no need to rearm
MultiShot | allEls == savedEls ->
return ()
-- either we previously registered for one shot or the
-- events of interest have changed, we must re-arm
_ ->
case I.elLifetime savedEls of
OneShot | haveOneShot ->
-- if there are no saved events and we registered with one-shot
-- semantics then there is no need to re-arm
unless (OneShot == I.elLifetime allEls
&& mempty == I.elEvent savedEls) $ do
void $ I.modifyFdOnce (emBackend mgr) fd (I.elEvent savedEls)
_ ->
-- we need to re-arm with multi-shot semantics
void $ I.modifyFd (emBackend mgr) fd
(I.elEvent allEls) (I.elEvent savedEls)
return triggered
nullToNothing :: [a] -> Maybe [a]
nullToNothing [] = Nothing
nullToNothing xs@(_:_) = Just xs
unless :: Monad m => Bool -> m () -> m ()
unless p = when (not p)
| AlexanderPankiv/ghc | libraries/base/GHC/Event/Manager.hs | bsd-3-clause | 18,170 | 0 | 24 | 4,744 | 4,177 | 2,167 | 2,010 | -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="fa-IR">
<title>Import/Export</title>
<maps>
<homeID>exim</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/exim/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs | apache-2.0 | 959 | 82 | 53 | 155 | 391 | 207 | 184 | -1 | -1 |
module Tree where
import Control.Monad
import Prelude hiding (sequence) -- doesn't work in Hugs.
import Control_Monad_Fix
data Tree a = Empty | Single { theSingle :: a } | Node { theLeft :: Tree a, theRight :: Tree a }
deriving Show
merge Empty t = t
merge t Empty = t
merge t1 t2 = Node t1 t2
fold e s n = f
where f Empty = e
f (Single a) = s a
f (Node l r) = n (f l) (f r)
toList x = fold id (:) (.) x []
assertEmpty t = Empty
assertSingle t = Single (theSingle t)
assertNode t = Node (theLeft t) (theRight t)
instance Functor Tree where
fmap = liftM
instance Monad Tree where
return = Single
Empty >>= f = Empty
Single a >>= f = f a
Node x y >>= f = Node (x >>= f) (y >>= f)
instance MonadPlus Tree where
mzero = Empty
mplus = Node
instance MonadFix Tree where
mfix f = obs result
where result = f (theSingle result)
obs (Node _ _) = Node (mfix (theLeft . f)) (mfix (theRight . f))
obs x = x
-- left to right
sequence :: Monad m => Tree (m a) -> m (Tree a)
sequence = fold (return Empty) (liftM Single) (liftM2 Node)
mapM f = Tree.sequence . fmap f
| kmate/HaRe | old/tools/base/lib/Monads/Tree.hs | bsd-3-clause | 1,417 | 0 | 12 | 592 | 528 | 270 | 258 | 35 | 3 |
module WhereIn5 where
--A definition can be removed if it is not used by other declarations.
--Where a definition is removed, it's type signature should also be removed.
--In this Example: remove defintion 'foo' will fail.
(fac,fib,foo)=(5,8,10)
main :: Int
main = fac+ fib
| kmate/HaRe | old/testing/removeDef/WhereIn5_TokOut.hs | bsd-3-clause | 278 | 0 | 5 | 48 | 45 | 29 | 16 | 4 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module T8566 where
data U (s :: *) = forall v. AA v [U s]
-- AA :: forall (s:*) (v:*). v -> [U s] -> U s
data I (u :: U *) (r :: [*]) :: * where
A :: I (AA t as) r -- Existential k
-- A :: forall (u:U *) (r:[*]) Universal
-- (k:BOX) (t:k) (as:[U *]). Existential
-- (u ~ AA * k t as) =>
-- I u r
-- fs unused, but needs to be present for the bug
class C (u :: U *) (r :: [*]) (fs :: [*]) where
c :: I u r -> I u r
-- c :: forall (u :: U *) (r :: [*]) (fs :: [*]). C u r fs => I u r -> I u r
instance (C (AA (t (I a ps)) as) ps fs) => C (AA t (a ': as)) ps fs where
-- instance C (AA t (a ': as)) ps fs where
c A = c undefined
| lukexi/ghc | testsuite/tests/polykinds/T8566.hs | bsd-3-clause | 975 | 0 | 12 | 296 | 229 | 134 | 95 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Language.Haskell.TH
$( [d| g = 0
h = $( return $ LamE [VarP (mkName "g")] (VarE 'g) ) |] )
-- The 'g should bind to the g=0 definition
-- Should print 0, not 1!
main = print (h 1)
| ezyang/ghc | testsuite/tests/th/T5379.hs | bsd-3-clause | 257 | 0 | 7 | 67 | 38 | 24 | 14 | 6 | 1 |
import Foreign
import Foreign.C
foreign import stdcall "&test" ptest :: FunPtr (CInt -> IO ())
foreign import stdcall "dynamic" ctest :: FunPtr (CInt -> IO ()) -> CInt -> IO ()
main = ctest ptest 3
| ghc-android/ghc | testsuite/tests/ffi/should_run/T2276_ghci.hs | bsd-3-clause | 207 | 0 | 11 | 45 | 86 | 44 | 42 | 5 | 1 |
import PiEstimator
main = let pi = computePi
in print pi | danielqo/PiAlgorithms | haskell/PiEstimatorMain.hs | mit | 64 | 0 | 8 | 18 | 23 | 11 | 12 | 3 | 1 |
{-|
Module : Eve.Internal.Utils.Utilities
Description : The module contains utility functions that could be used anywhere in the library.
Copyright : (c) Alex Gagné, 2017
License : MIT
Stability : experimental
The module contains utility functions that could be used anywhere in the library.
-}
module Eve.Internal.Utils.Utilities (fromJust', textToUTCTime)
where
import Data.Maybe (fromMaybe)
import Data.Text (Text, unpack)
import Data.Time (UTCTime)
import Data.Time.Format (parseTimeOrError, defaultTimeLocale)
-- | 'fromJust'' will extract the value of a maybe or display the error passed in as a String
fromJust' :: Maybe a -> String -> a
fromJust' m err = fromMaybe (error err) m
-- | 'textToUTCTime' will transform a Text into UTCTime
textToUTCTime :: Text -> UTCTime
textToUTCTime dateString = parseTimeOrError True defaultTimeLocale "%Y-%m-%d %H:%M:%S" (unpack dateString) :: UTCTime | AlexGagne/evecalendar | src/Eve/Internal/Utils/Utilities.hs | mit | 933 | 0 | 7 | 163 | 138 | 79 | 59 | 9 | 1 |
module Main where
import qualified LLVM.Module as M
import LLVM.Context
import LLVM.Pretty (ppllvm)
import Control.Monad (filterM)
import Control.Monad.Except
import Data.Functor
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import Text.Show.Pretty (ppShow)
import System.IO
import System.Exit
import System.Directory
import System.FilePath
import System.Environment
-------------------------------------------------------------------------------
-- Harness
-------------------------------------------------------------------------------
readir :: FilePath -> IO ()
readir fname = do
putStrLn $ "Test: " ++ fname
putStrLn $ replicate 80 '='
putStrLn fname
putStrLn $ replicate 80 '='
str <- readFile fname
withContext $ \ctx -> do
res <- runExceptT $ M.withModuleFromLLVMAssembly ctx str $ \mod -> do
ast <- M.moduleAST mod
putStrLn $ ppShow ast
let str = ppllvm ast
T.putStrLn str
T.writeFile ("tests/output" </> takeFileName fname) str
trip <- runExceptT $ M.withModuleFromLLVMAssembly ctx (T.unpack str) (const $ return ())
case trip of
Left err -> do
putStrLn "Error reading output:"
putStrLn err
writeFile ("tests/output" </> takeFileName fname) err
exitFailure
Right ast -> putStrLn "Round Tripped!"
case res of
Left err -> do
putStrLn "Error reading input:"
putStrLn err
writeFile ("tests/output" </> takeFileName fname) err
exitFailure
Right _ -> return ()
main :: IO ()
main = do
files <- getArgs
case files of
[] -> do
let testPath = "tests/input/"
dirFiles <- listDirectory testPath
mapM_ readir (fmap (\x -> testPath </> x) dirFiles)
[fpath] -> readir fpath
_ -> mapM_ readir files
putStrLn "All good."
return ()
| vjoki/llvm-hs-pretty | tests/Main.hs | mit | 1,867 | 0 | 24 | 437 | 565 | 274 | 291 | 56 | 3 |
module Main where
import System.Environment (getArgs)
import System.IO (hFlush, stdout)
import Data.Char (isDigit, digitToInt)
import Control.Monad (when)
import Control.Exception (try, SomeException)
import Sudoku
main = do
arguments <- getArgs
rows <- if null arguments
then do
putStrLn "Please input a puzzle to solve (Ctrl + C to exit):"
inputPuzzle 1 []
else do
contents <- readFile (head arguments)
return $ lines contents
checkFormat rows `seq` return () -- force eval
prettyPrint $ sudoku $ parsePuzzle rows
inputPuzzle :: Int -> [String] -> IO [String]
inputPuzzle 10 base = return base
inputPuzzle i base = do
putStr $ "Row " ++ show i ++ ": "
hFlush stdout
line <- getLine
check <- try $ checkFormatLine line
case check of
Right () -> inputPuzzle (i+1) (base ++ [line])
Left e -> do
putStrLn $ show (e :: SomeException)
inputPuzzle i base
parsePuzzle :: [[ Char ]] -> EmptyPuzzle
parsePuzzle = map parseRow
where parseRow = map (\char -> if isDigit char then Just (digitToInt char) else Nothing)
-- | Check the format of the file
checkFormat :: [String] -> IO ()
checkFormat rows
| len < 9 = error "Invalid format: less than 9 rows found"
| len > 9 = error "Invalid format: more than 9 rows found"
| otherwise = all (\row -> checkFormatLine row `seq` True) rows `seq` return ()
where len = length rows
-- | Check the format for a line
checkFormatLine :: String -> IO ()
checkFormatLine line
| len < 9 = error $ "Invalid format: less than 9 values found: " ++ line
| len > 9 = error $ "Invalid format: more than 9 values found: " ++ line
| otherwise = all (\x -> checkFormatChar x `seq` True) line `seq` return ()
where len = length line
-- | Check the format for a character
checkFormatChar :: Char -> IO ()
checkFormatChar x = if x == '.' || digitToInt x `elem` [1..9]
then return ()
else error $ "Invalid character: " ++ [x]
{-
Pretty prints the solution in the following format:
+-------+-------+-------+
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
+-------+-------+-------+
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
+-------+-------+-------+
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
| 1 2 3 | 1 2 3 | 1 2 3 |
+-------+-------+-------+
-}
prettyPrint :: Puzzle -> IO ()
prettyPrint puzzle = do
puzzle `seq` return () -- force eval of puzzle before doing anything
let (a,b,c) = split3 puzzle
printBorder
printRows a
printBorder
printRows b
printBorder
printRows c
printBorder
where border = "+-------+-------+-------+"
printBorder = putStrLn border
printRows = putStr . unlines . map (unwords . sepRow . (map show))
sep = ["|"]
sepRow row = let (a,b,c) = split3 row
in sep ++ a ++ sep ++ b ++ sep ++ c ++ sep
split3 list = let (a,rest) = splitAt 3 list
(b,c) = splitAt 3 rest
in (a,b,c)
| brandonchinn178/sudoku | src/Main.hs | mit | 3,428 | 0 | 14 | 1,210 | 943 | 474 | 469 | 69 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Test.WebDriver hiding (runWD)
import Test.Hspec.WebDriver
config = useBrowser chrome defaultConfig { wdHost = "selenium", wdPort = 4444}
allBrowsers :: [(Capabilities, String)]
allBrowsers = [(chromeCaps, "Chrome")]
main :: IO ()
main = hspec $
describe "E2E smoke test" $ do
sessionWith config "integration" $ using allBrowsers $ do
it "checks all text in p" $ runWD $ do
openPage "http://web_test/test/files/index.html"
e <- findElem $ ByCSS "p"
e `shouldHaveText` ("Some HTML")
it "checks all text in p strong" $ runWD $ do
openPage "http://web_test/test/files/index.html"
e <- findElem $ ByCSS "p strong"
e `shouldHaveText` ("HTML")
| michalc/hhttpserver | test/Spec.hs | mit | 751 | 0 | 16 | 169 | 208 | 107 | 101 | 18 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Views.BlogIndex
( monthPage
) where
import Data.Monoid((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (TimeZone, TimeOfDay(..), utcToLocalTime, localTimeOfDay, toGregorian, localDay)
import Layout (Page (Page))
import Lucid (Html, toHtml, toHtmlRaw)
import qualified Lucid.Bootstrap as BS
import qualified Lucid.Html5 as H
import Models.BlogIndex
import Models.Events
import Routes
import Text.Printf
import Web.Spock
monthPage :: TimeZone -> Int -> Int -> [BlogIndex] -> Page
monthPage tz year month items =
Page Nothing title $ pageContent tz year month items
where
title = pageTitle year month
pageContent :: TimeZone -> Int -> Int -> [BlogIndex] -> Html ()
pageContent tz year month items =
H.div_ [ H.class_ "col-sm-8" ] $ do
H.h3_ [] (toHtml $ pageTitle year month)
H.div_ [ H.class_ "list-group" ] $ mapM_ (itemContent tz year month) items
itemContent :: TimeZone -> Int -> Int -> BlogIndex -> Html ()
itemContent tz year month ind =
H.a_ [ H.class_ "list-group-item", H.href_ link ] $
H.span_ [] $ do
H.strong_ (toHtml (blogIndexCaption ind))
" "
toHtml (metaInfo tz ind)
where link = routeLinkText $ ShowPath year month (blogIndexTitle ind)
pageTitle :: Int -> Int -> Text
pageTitle year month =
"Beiträge in " <> T.pack (show month) <> "." <> T.pack (show year)
metaInfo :: TimeZone -> BlogIndex -> Text
metaInfo zone ind =
T.pack $ printf "veröffentlicht am %02d. um %02d:%02d" d h m
where publishedAt = utcToLocalTime zone $ blogIndexPublished ind
(TimeOfDay h m _) = localTimeOfDay publishedAt
(_, _, d) = toGregorian $ localDay publishedAt
| CarstenKoenig/MyWebSite | src/Views/BlogIndex.hs | mit | 1,753 | 0 | 12 | 358 | 613 | 322 | 291 | 42 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.