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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
import Debug.Trace
-- import Control.Arrow
import Control.Applicative ((<$>))
import Control.Monad (when)
--import Control.Monad.ST
--import Data.Array.ST
import Data.Array.IO
import Data.Array.MArray
import qualified Data.Set as Set
import Data.List ((\\))
-- import Data.Set (fromAscList,Set (..),singleton, (\\))
type Point = (Int,Int)
type CC = [Point] --CC stands for connected component
main :: IO ()
main = do [imax,jmax] <- map read . words <$> getLine ::IO [Int]
list <- filter (/='\n')<$> getContents
arr <- newListArray ((1,1),(imax,jmax)) list :: IO (IOArray Point Char)
loop arr (imax,jmax) (1,1) (1,1)
cc <- length . filter (=='1') <$> getElems arr
print cc
return ()
loop :: IOArray Point Char -> (Int, Int) -> Point -> Point -> IO ()
loop arr bd src p = do i <- readArray arr p
let src' = next src bd
if i == '1'
then do writeArray arr p '0'
let nbs = nb p bd
if null nbs
then do writeArray arr src '1' -- we have a singleton or
if src == p && p /= bd
then loop arr bd src' src'
else loop arr bd src src
else mapM_ (loop arr bd src) nbs
else when (src == p && p /= bd) $ loop arr bd src' src'
next (x,y) (bx,by) | x+1 > bx && y+1 > by = (bx,by)
| x+1 > bx && y+1 < by = (1,y+1)
| otherwise = (x+1,y)
nb :: Point -> (Int, Int) -> [Point]
nb = nb2
nb1 :: Point -> (Int, Int) -> [Point]
nb1 (i,j) (i',j') = let imin = max 1 (i-1)
jmin = max 1 (j-1)
imax = min i' (i+1)
jmax = min j'(j+1)
in range ((imin,jmin),(imax,jmax)) \\ [(i,j)]
nb2 :: Point -> (Int, Int) -> [Point] -- |0 0 0
nb2 (x,y) (imax,jmax)= let inRange (i,j) = 1 <= min i j && i <= imax && j <= jmax-- |0 X 1
in filter inRange [(x+1,y),(x-1,y+1),(x,y+1),(x+1,y+1)] -- |1 1 1
| epsilonhalbe/Sammelsurium | ConnectedComponent/Array/CC.hs | bsd-3-clause | 2,298 | 0 | 16 | 966 | 941 | 508 | 433 | 44 | 4 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Data.Monoid (mappend)
import Hakyll
import qualified Text.Highlighting.Kate as K
--------------------------------------------------------------------------------
main :: IO ()
main = hakyll $ do
match "images/*" $ do
route idRoute
compile copyFileCompiler
create ["css/highlight.css"] $ do
route idRoute
compile $ makeItem (compressCss $ K.styleToCss K.pygments)
match "css/*" $ do
route idRoute
compile compressCssCompiler
match (fromList ["about.rst", "contact.markdown"]) $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
tags <- buildTags "posts/*" (fromCapture "tags/*.html")
match "posts/*" $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" (postCtx tags)
>>= saveSnapshot "content"
>>= loadAndApplyTemplate "templates/default.html" (postCtx tags)
>>= relativizeUrls
archive <- buildPaginateWith
(sortRecentFirst >=> return . paginateEvery 5)
"posts/*"
(\n -> if n == 1
then fromFilePath "archive.html"
else fromFilePath $ "archive/" ++ show n ++ ".html")
paginateRules archive $ \pageNum pattern -> do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll pattern
let archiveCtx =
constField "title" "Archives" `mappend`
listField "posts" (postCtx tags) (return posts) `mappend`
paginateContext archive pageNum `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/archive.html" archiveCtx
>>= loadAndApplyTemplate "templates/default.html" archiveCtx
>>= relativizeUrls
tagsRules tags $ \tag pattern -> do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll pattern
let tagCtx =
constField "title" ("Posts tagged " ++ tag) `mappend`
listField "posts" (postCtx tags) (return posts) `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/tag.html" tagCtx
>>= loadAndApplyTemplate "templates/default.html" tagCtx
>>= relativizeUrls
match "index.html" $ do
route idRoute
compile $ do
posts <- fmap (take 3) . recentFirst =<< loadAll "posts/*"
tagCloud <- renderTagCloud 80.0 120.0 tags
let indexCtx =
listField "posts" (postCtx tags) (return posts) `mappend`
constField "title" "Home" `mappend`
constField "tagcloud" tagCloud `mappend`
defaultContext
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
create ["atom.xml"] $ do
route idRoute
compile $ do
let feedCtx =
postCtx tags `mappend`
bodyField "description"
posts <- fmap (take 10) . recentFirst =<< loadAllSnapshots "posts/*" "content"
renderAtom myFeedConfiguration feedCtx posts
match "templates/*" $ compile templateCompiler
--------------------------------------------------------------------------------
postCtx :: Tags -> Context String
postCtx tags =
dateField "date" "%B %e, %Y" `mappend`
teaserField "teaser" "content" `mappend`
tagsField "tags" tags `mappend`
defaultContext
myFeedConfiguration :: FeedConfiguration
myFeedConfiguration = FeedConfiguration
{ feedTitle = "My Hakyll Blog"
, feedDescription = "Hakyllでブログを作る"
, feedAuthorName = "username"
, feedAuthorEmail = "test@example.com"
, feedRoot = "http://user.github.io"
}
| IMOKURI/hakyll-blog-example | site.hs | bsd-3-clause | 4,430 | 0 | 23 | 1,478 | 931 | 444 | 487 | -1 | -1 |
module Main where
import Haste
main :: IO ()
main = do
ul <- elemsByQS document "ul#demo-list"
case ul of
(el:_) -> mapQS_ document "#demo-list li" (handleRemove el)
_ -> error "Element 'ul#demo-list' not found"
handleRemove :: Elem -> Elem -> IO Bool
handleRemove ul li = do
onEvent li OnClick $ \_ _ -> removeChild li ul
| joelburget/haste-compiler | examples/list/list.hs | bsd-3-clause | 344 | 0 | 12 | 79 | 126 | 62 | 64 | 11 | 2 |
{-# LANGUAGE RecordWildCards #-}
-- | Tests for 'VssCertData': certificates with TTL.
module Test.Pos.Ssc.VssCertDataSpec
( spec
) where
import Universum hiding (id)
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Data.List.Extra (nubOrdOn)
import qualified Data.Set as S
import Data.Tuple (swap)
import Test.Hspec (Spec, describe, runIO)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (Arbitrary (..), Gen, Property, choose,
conjoin, counterexample, generate, suchThat, vectorOf,
(.&&.), (==>))
import Pos.Chain.Ssc (SscGlobalState (..), VssCertData (..),
VssCertificate (..), expiryEoS, getCertId,
getVssCertificatesMap, mkVssCertificate, rollbackSsc,
runPureToss, setLastKnownSlot, sgsVssCertificates)
import qualified Pos.Chain.Ssc as Ssc
import Pos.Core (EpochIndex (..), EpochOrSlot (..), SlotId (..))
import Pos.Core.Chrono (NewestFirst (..))
import Pos.Core.Slotting (flattenEpochOrSlot, unflattenSlotId)
import Pos.Crypto (ProtocolMagic (..), RequiresNetworkMagic (..))
import Test.Pos.Chain.Genesis.Dummy (dummyEpochSlots,
dummySlotSecurityParam)
import Test.Pos.Core.Arbitrary ()
import Test.Pos.Infra.Arbitrary.Ssc ()
import Test.Pos.Util.QuickCheck.Property (qcIsJust)
spec :: Spec
spec = do
runWithMagic RequiresNoMagic
runWithMagic RequiresMagic
runWithMagic :: RequiresNetworkMagic -> Spec
runWithMagic rnm = do
pm <- (\ident -> ProtocolMagic ident rnm) <$> runIO (generate arbitrary)
describe ("(requiresNetworkMagic=" ++ show rnm ++ ")") $
specBody pm
specBody :: ProtocolMagic -> Spec
specBody _pm = describe "Ssc.VssCertData" $ do
describe "verifyInsertVssCertData" $
prop description_verifyInsertVssCertData verifyInsertVssCertData
describe "verifyDeleteVssCertData" $
prop description_verifyDeleteVssCertData verifyDeleteVssCertData
describe "verifyCorrectVssCertDataIsConsistent" $
prop description_verifyCorrectVssCertDataIsConsistent isConsistent
describe "verifySetLastKnownSlot" $
prop description_verifySetLastKnownSlot verifySetLastKnownSlot
describe "verifyDeleteAndFilter" $
prop description_verifyDeleteAndFilter verifyDeleteAndFilter
describe "verifyRollback" $
prop description_verifyRollback verifyRollback
where
description_verifyInsertVssCertData =
"successfully verifies if certificate is in certificate data\
\ after insertion this certificate in data"
description_verifyDeleteVssCertData =
"successfully verifies if certificate is not in certificate data\
\ after deletion of this certificate from data"
description_verifyCorrectVssCertDataIsConsistent =
"successfully verifies if inserts create consistent VssCertData"
description_verifySetLastKnownSlot =
"successfully verifies if new last known slot is set properly"
description_verifyDeleteAndFilter =
"successfully verifies if filter saves consistency"
description_verifyRollback =
"successfully rollsback certificates older than slot to which state was rolled\
\ back to"
----------------------------------------------------------------------------
-- Utility functions not present in VssCertData
----------------------------------------------------------------------------
expiresAfter :: VssCertificate -> EpochOrSlot -> Bool
expiresAfter certificate expirySlot = expiryEoS certificate > expirySlot
canBeIn :: VssCertificate -> VssCertData -> Bool
canBeIn certificate certData = certificate `expiresAfter` lastKnownEoS certData
----------------------------------------------------------------------------
-- Wrapper around VssCertData which Arbitrary instance should be consistent
----------------------------------------------------------------------------
newtype CorrectVssCertData = CorrectVssCertData
{ getVssCertData :: VssCertData
} deriving (Show)
instance Arbitrary CorrectVssCertData where
arbitrary = (CorrectVssCertData <$>) $ do
certificatesToAdd <- choose (0, 100)
lkeos <- arbitrary :: Gen EpochOrSlot
let notExpiredGen = arbitrary `suchThat` (`expiresAfter` lkeos)
vssCertificates <- vectorOf @VssCertificate certificatesToAdd notExpiredGen
let dataUpdaters = map Ssc.insert vssCertificates
pure $ foldl' (&) (Ssc.empty {lastKnownEoS = lkeos}) dataUpdaters
----------------------------------------------------------------------------
-- Properties for VssCertData
----------------------------------------------------------------------------
verifyInsertVssCertData :: VssCertificate -> VssCertData -> Property
verifyInsertVssCertData certificate certData =
certificate `canBeIn` certData ==>
counterexample
("expected " <> show shid <> " to be in certdata")
(shid `Ssc.member` Ssc.insert certificate certData)
where
shid = getCertId certificate
verifyDeleteVssCertData :: VssCertificate -> VssCertData -> Property
verifyDeleteVssCertData certificate certData =
let shid = getCertId certificate
certWithShid = Ssc.insert certificate certData
certWithoutShid = Ssc.delete shid certWithShid
in counterexample
("expected " <> show shid <> " not to be in certdata")
(not (shid `Ssc.member` certWithoutShid))
-- | This function checks all imaginable properties for correctly created 'VssCertData'.
-- TODO: some checks are not assimptotically efficient but nobody cares untill time is reasonable
isConsistent :: CorrectVssCertData -> Bool
isConsistent (getVssCertData -> VssCertData{..}) =
-- (1) all certificates inserted not later than lastknownslot
all (<= lastKnownEoS) insertedSlots
-- (2) all expiredslots greater than lastKnownSlot
&& all (> lastKnownEoS) expiredSlots
-- (3) @certs@ keys and @certsIns@ keys are equal
&& certsStakeholders == certsInsStakeholders
-- (4) @insSlotset@ equals to hashmap of @certsInts@
&& slotsFromCertsIns == whenInsSet
-- (5) there is expiry slot for every inserted certificate
&& insSlotSetStakeholders == expirySlotSetStakeholders
-- (*) every expire slot strictly greater than corresponding inserted slot
-- consequence of (1) && (2) && (5)
-- && all (\(expireSlot, shid) -> certsIns ! shid < expireSlot) expirySlotPairs
-- (6) intersection of expired certificates and not expired is empty
&& null (notExpiredCertificates `S.intersection` expiredCertificates)
-- (7) all expired certificates are stored for no longer than +epochSlots from lks
&& all (<= addEpoch lastKnownEoS) expiredCertificatesSlots
where
insSlotSetPairs = S.toList whenInsSet
expirySlotSetPairs = S.toList whenExpire
insertedSlots = map fst insSlotSetPairs
expiredSlots = map fst expirySlotSetPairs
certsStakeholders = S.fromList $ HM.keys $ getVssCertificatesMap certs
certsInsStakeholders = S.fromList $ HM.keys whenInsMap
slotsFromCertsIns = S.fromList $ map swap $ HM.toList whenInsMap
insSlotSetStakeholders = S.fromList $ map snd insSlotSetPairs
expirySlotSetStakeholders = S.fromList $ map snd expirySlotSetPairs
notExpiredCertificates = S.fromList $ toList certs
expiredCertificatesData = S.toList expiredCerts
expiredCertificatesSlots = map fst expiredCertificatesData
expiredCertificates = S.fromList $ map (view _3 . snd) expiredCertificatesData
addEpoch :: EpochOrSlot -> EpochOrSlot
addEpoch (EpochOrSlot (Left (EpochIndex epoch))) =
EpochOrSlot $ Left $ EpochIndex $ epoch + 1
addEpoch (EpochOrSlot (Right (SlotId ep sl))) =
EpochOrSlot $ Right $ SlotId (ep + 1) sl
verifySetLastKnownSlot :: SlotId -> CorrectVssCertData -> Bool
verifySetLastKnownSlot newLks (CorrectVssCertData vssCertData) =
isConsistent $ CorrectVssCertData $ setLastKnownSlot newLks vssCertData
-- | Verifies that filter (and 'delete' as consequences) save consintency.
-- TODO: add more checks here?
verifyDeleteAndFilter :: CorrectVssCertData -> Bool
verifyDeleteAndFilter (getVssCertData -> vcd@VssCertData{..}) =
let certificatesHolders = Ssc.keys vcd
holdersLength = length certificatesHolders
halfOfHolders = take (holdersLength `div` 2) certificatesHolders
setFromHalf = HS.fromList halfOfHolders
resultVcd = Ssc.filter (`HS.member` setFromHalf) vcd
resultCorrectVcd = CorrectVssCertData resultVcd
in isConsistent resultCorrectVcd
data RollbackData = Rollback SscGlobalState EpochOrSlot [VssCertificate]
deriving (Show, Eq)
instance Arbitrary RollbackData where
arbitrary = do
goodVssCertData@(VssCertData {..}) <- getVssCertData <$> arbitrary
certsToRollbackN <- choose (0, 100) >>= choose . (0,)
slotsToRollback <- choose (1, dummySlotSecurityParam)
let lastKEoSWord = flattenEpochOrSlot dummyEpochSlots lastKnownEoS
rollbackFrom = fromIntegral slotsToRollback + lastKEoSWord
rollbackGen = do
sk <- arbitrary
binVssPK <- arbitrary
thisEpoch <-
siEpoch . unflattenSlotId dummyEpochSlots <$>
choose (succ lastKEoSWord, rollbackFrom)
pm <- arbitrary
return $ mkVssCertificate pm sk binVssPK thisEpoch
certsToRollback <- nubOrdOn vcVssKey <$>
vectorOf @VssCertificate certsToRollbackN rollbackGen
return $ Rollback (SscGlobalState mempty mempty mempty goodVssCertData)
lastKnownEoS
certsToRollback
verifyRollback :: RollbackData -> Gen Property
verifyRollback (Rollback oldSscGlobalState rollbackEoS vssCerts) = do
let certAdder vcd = foldl' (flip Ssc.insert) vcd vssCerts
newSscGlobalState@(SscGlobalState _ _ _ newVssCertData) =
oldSscGlobalState & sgsVssCertificates %~ certAdder
(_, SscGlobalState _ _ _ rolledVssCertData, _) <-
runPureToss newSscGlobalState $
rollbackSsc dummyEpochSlots rollbackEoS (NewestFirst [])
pure $ conjoin $ vssCerts <&> \cert ->
let id = getCertId cert in
counterexample ("haven't found cert with id " <>
show id <> " in newVssCertData")
(qcIsJust (Ssc.lookup id newVssCertData))
.&&.
counterexample ("expected a " <> show (Just cert) <>
", got " <> show (Ssc.lookup id rolledVssCertData) <>
" in rolledVssCertData")
((/= Just cert) (Ssc.lookup id rolledVssCertData))
| input-output-hk/pos-haskell-prototype | lib/test/Test/Pos/Ssc/VssCertDataSpec.hs | mit | 11,020 | 0 | 20 | 2,519 | 2,084 | 1,116 | 968 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, StandaloneDeriving, ScopedTypeVariables #-}
module TwitterOAuth
( loginWithTwitterHandler
, twitterAccessTokenHandler) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad (liftM)
import Snap.Core
import Network.OAuth.Consumer
import Network.OAuth.Http.Request
import Network.OAuth.Http.Response
import Network.OAuth.Http.CurlHttpClient
import Network.OAuth.Http.PercentEncoding
import Data.Maybe (fromJust)
import Control.Monad.Error (runErrorT)
import qualified Data.ByteString.Char8 as B
deriving instance Show Application
deriving instance Show Token
deriving instance Read Application
deriving instance Read OAuthCallback
reqUrl = fromJust . parseURL $ "https://api.twitter.com/oauth/request_token"
accUrl = fromJust . parseURL $ "https://api.twitter.com/oauth/access_token"
serviceUrl = fromJust . parseURL $ "http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=danchoi"
twitterApp :: IO Application
twitterApp = do
(key:secret:callback:_) <- liftM lines $ readFile "twitter.cfg"
return $ Application { consKey = key, consSec = secret, callback = (URL callback) }
loginWithTwitterHandler :: Snap ()
loginWithTwitterHandler = do
-- writeLBS $ "login with Twitter"
tapp <- liftIO twitterApp
liftIO $ putStrLn $ "Using config " ++ (show tapp)
reqToken :: Token <- runOAuthM (fromApplication tapp) $ do
s1 <- signRq2 HMACSHA1 Nothing reqUrl
oauthRequest CurlClient s1
token <- getToken
return token
liftIO $ putStrLn $ "Received reqToken: " ++ (show reqToken)
liftIO $ putStrLn $ "Token oauth params: " ++ (show $ oauthParams reqToken)
-- TODO save the oauth creds in session
let oauthToken = head $ find ((==) "oauth_token") $ oauthParams reqToken
let authUrl = "https://api.twitter.com/oauth/authenticate?oauth_token=" ++ oauthToken
redirect $ B.pack authUrl
twitterAccessTokenHandler :: Snap ()
twitterAccessTokenHandler = do
writeLBS "twitter access verified "
-- TODO step 3 https://dev.twitter.com/docs/auth/implementing-sign-twitter
-- accessToken <- (signRq2 HMACSHA1 Nothing accUrl >>= oauthRequest CurlClient)
-- liftIO $ putStrLn $ show (oauthParams accessToken)
| danchoi/geochat | src/TwitterOAuth.hs | mit | 2,259 | 0 | 14 | 368 | 486 | 258 | 228 | 43 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Yesod
data HelloWorld = HelloWorld
mkYesod "HelloWorld" [parseRoutes|
/ HomeR GET
|]
instance Yesod HelloWorld
getHomeR :: Handler Html
getHomeR = defaultLayout [whamlet|Hello, World!|]
main :: IO ()
main = warp 3000 HelloWorld | brodyberg/LearnHaskell | Web/sqlitetest/HelloWorld.hs | mit | 366 | 0 | 6 | 54 | 74 | 42 | 32 | 12 | 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="tr-TR">
<title>Sunucu-Gönderim Etkinlikleri | ZAP Uzantısı</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>İçerikler</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Dizin</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Arama</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoriler</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 994 | 80 | 67 | 160 | 428 | 216 | 212 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
module QuasiQuote where
import T7918A
ex1 = [qq|e1|]
ex2 = [qq|e2|]
ex3 = [qq|e3|]
ex4 = [qq|e4|]
tx1 = undefined :: [qq|t1|]
tx2 = undefined :: [qq|t2|]
tx3 = undefined :: [qq|t3|]
tx4 = undefined :: [qq|t4|]
px1 [qq|p1|] = undefined
px2 [qq|p2|] = undefined
px3 [qq|p3|] = undefined
px4 [qq|p4|] = undefined
{-# LANGUAGE QuasiQuotes #-}
testComplex = assertBool "" ([istr|
ok
#{Foo 4 "Great!" : [Foo 3 "Scott!"]}
then
|] == ("\n" ++
" ok\n" ++
"[Foo 4 \"Great!\",Foo 3 \"Scott!\"]\n" ++
" then\n"))
| mpickering/ghc-exactprint | tests/examples/ghc710/QuasiQuote.hs | bsd-3-clause | 582 | 0 | 11 | 142 | 177 | 124 | 53 | -1 | -1 |
{-# LANGUAGE StaticPointers #-}
module Tests.StaticPtr where
import GHC.StaticPtr
runTest :: IO ()
runTest = do
print (staticKey (static staticPtrKeys))
print (staticKey (static runTest))
| nyson/haste-compiler | Tests/StaticPtr.hs | bsd-3-clause | 193 | 0 | 11 | 29 | 63 | 32 | 31 | 7 | 1 |
-- | When there aren't enough registers to hold all the vregs we have to spill
-- some of those vregs to slots on the stack. This module is used modify the
-- code to use those slots.
module RegAlloc.Graph.Spill (
regSpill,
SpillStats(..),
accSpillSL
) where
import RegAlloc.Liveness
import Instruction
import Reg
import Cmm hiding (RegSet)
import BlockId
import MonadUtils
import State
import Unique
import UniqFM
import UniqSet
import UniqSupply
import Outputable
import Platform
import Data.List
import Data.Maybe
import Data.Map (Map)
import Data.Set (Set)
import qualified Data.Map as Map
import qualified Data.Set as Set
-- | Spill all these virtual regs to stack slots.
--
-- TODO: See if we can split some of the live ranges instead of just globally
-- spilling the virtual reg. This might make the spill cleaner's job easier.
--
-- TODO: On CISCy x86 and x86_64 we don't nessesarally have to add a mov instruction
-- when making spills. If an instr is using a spilled virtual we may be able to
-- address the spill slot directly.
--
regSpill
:: Instruction instr
=> Platform
-> [LiveCmmDecl statics instr] -- ^ the code
-> UniqSet Int -- ^ available stack slots
-> UniqSet VirtualReg -- ^ the regs to spill
-> UniqSM
([LiveCmmDecl statics instr]
-- code with SPILL and RELOAD meta instructions added.
, UniqSet Int -- left over slots
, SpillStats ) -- stats about what happened during spilling
regSpill platform code slotsFree regs
-- Not enough slots to spill these regs.
| sizeUniqSet slotsFree < sizeUniqSet regs
= pprPanic "regSpill: out of spill slots!"
( text " regs to spill = " <> ppr (sizeUniqSet regs)
$$ text " slots left = " <> ppr (sizeUniqSet slotsFree))
| otherwise
= do
-- Allocate a slot for each of the spilled regs.
let slots = take (sizeUniqSet regs) $ nonDetEltsUFM slotsFree
let regSlotMap = listToUFM
$ zip (nonDetEltsUFM regs) slots
-- This is non-deterministic but we do not
-- currently support deterministic code-generation.
-- See Note [Unique Determinism and code generation]
-- Grab the unique supply from the monad.
us <- getUniqueSupplyM
-- Run the spiller on all the blocks.
let (code', state') =
runState (mapM (regSpill_top platform regSlotMap) code)
(initSpillS us)
return ( code'
, minusUniqSet slotsFree (mkUniqSet slots)
, makeSpillStats state')
-- | Spill some registers to stack slots in a top-level thing.
regSpill_top
:: Instruction instr
=> Platform
-> RegMap Int
-- ^ map of vregs to slots they're being spilled to.
-> LiveCmmDecl statics instr
-- ^ the top level thing.
-> SpillM (LiveCmmDecl statics instr)
regSpill_top platform regSlotMap cmm
= case cmm of
CmmData{}
-> return cmm
CmmProc info label live sccs
| LiveInfo static firstId mLiveVRegsOnEntry liveSlotsOnEntry <- info
-> do
-- We should only passed Cmms with the liveness maps filled in,
-- but we'll create empty ones if they're not there just in case.
let liveVRegsOnEntry = fromMaybe mapEmpty mLiveVRegsOnEntry
-- The liveVRegsOnEntry contains the set of vregs that are live
-- on entry to each basic block. If we spill one of those vregs
-- we remove it from that set and add the corresponding slot
-- number to the liveSlotsOnEntry set. The spill cleaner needs
-- this information to erase unneeded spill and reload instructions
-- after we've done a successful allocation.
let liveSlotsOnEntry' :: Map BlockId (Set Int)
liveSlotsOnEntry'
= mapFoldWithKey patchLiveSlot
liveSlotsOnEntry liveVRegsOnEntry
let info'
= LiveInfo static firstId
(Just liveVRegsOnEntry)
liveSlotsOnEntry'
-- Apply the spiller to all the basic blocks in the CmmProc.
sccs' <- mapM (mapSCCM (regSpill_block platform regSlotMap)) sccs
return $ CmmProc info' label live sccs'
where -- Given a BlockId and the set of registers live in it,
-- if registers in this block are being spilled to stack slots,
-- then record the fact that these slots are now live in those blocks
-- in the given slotmap.
patchLiveSlot
:: BlockId -> RegSet
-> Map BlockId (Set Int) -> Map BlockId (Set Int)
patchLiveSlot blockId regsLive slotMap
= let
-- Slots that are already recorded as being live.
curSlotsLive = fromMaybe Set.empty
$ Map.lookup blockId slotMap
moreSlotsLive = Set.fromList
$ catMaybes
$ map (lookupUFM regSlotMap)
$ nonDetEltsUFM regsLive
-- See Note [Unique Determinism and code generation]
slotMap'
= Map.insert blockId (Set.union curSlotsLive moreSlotsLive)
slotMap
in slotMap'
-- | Spill some registers to stack slots in a basic block.
regSpill_block
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveBasicBlock instr
-> SpillM (LiveBasicBlock instr)
regSpill_block platform regSlotMap (BasicBlock i instrs)
= do instrss' <- mapM (regSpill_instr platform regSlotMap) instrs
return $ BasicBlock i (concat instrss')
-- | Spill some registers to stack slots in a single instruction.
-- If the instruction uses registers that need to be spilled, then it is
-- prefixed (or postfixed) with the appropriate RELOAD or SPILL meta
-- instructions.
regSpill_instr
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveInstr instr
-> SpillM [LiveInstr instr]
regSpill_instr _ _ li@(LiveInstr _ Nothing)
= do return [li]
regSpill_instr platform regSlotMap
(LiveInstr instr (Just _))
= do
-- work out which regs are read and written in this instr
let RU rlRead rlWritten = regUsageOfInstr platform instr
-- sometimes a register is listed as being read more than once,
-- nub this so we don't end up inserting two lots of spill code.
let rsRead_ = nub rlRead
let rsWritten_ = nub rlWritten
-- if a reg is modified, it appears in both lists, want to undo this..
let rsRead = rsRead_ \\ rsWritten_
let rsWritten = rsWritten_ \\ rsRead_
let rsModify = intersect rsRead_ rsWritten_
-- work out if any of the regs being used are currently being spilled.
let rsSpillRead = filter (\r -> elemUFM r regSlotMap) rsRead
let rsSpillWritten = filter (\r -> elemUFM r regSlotMap) rsWritten
let rsSpillModify = filter (\r -> elemUFM r regSlotMap) rsModify
-- rewrite the instr and work out spill code.
(instr1, prepost1) <- mapAccumLM (spillRead regSlotMap) instr rsSpillRead
(instr2, prepost2) <- mapAccumLM (spillWrite regSlotMap) instr1 rsSpillWritten
(instr3, prepost3) <- mapAccumLM (spillModify regSlotMap) instr2 rsSpillModify
let (mPrefixes, mPostfixes) = unzip (prepost1 ++ prepost2 ++ prepost3)
let prefixes = concat mPrefixes
let postfixes = concat mPostfixes
-- final code
let instrs' = prefixes
++ [LiveInstr instr3 Nothing]
++ postfixes
return $ instrs'
-- | Add a RELOAD met a instruction to load a value for an instruction that
-- writes to a vreg that is being spilled.
spillRead
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillRead regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 0, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, []) )
| otherwise = panic "RegSpill.spillRead: no slot defined for spilled reg"
-- | Add a SPILL meta instruction to store a value for an instruction that
-- writes to a vreg that is being spilled.
spillWrite
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillWrite regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 0) }
return ( instr'
, ( []
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillWrite: no slot defined for spilled reg"
-- | Add both RELOAD and SPILL meta instructions for an instruction that
-- both reads and writes to a vreg that is being spilled.
spillModify
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillModify regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillModify: no slot defined for spilled reg"
-- | Rewrite uses of this virtual reg in an instr to use a different
-- virtual reg.
patchInstr
:: Instruction instr
=> Reg -> instr -> SpillM (instr, Reg)
patchInstr reg instr
= do nUnique <- newUnique
-- The register we're rewriting is suppoed to be virtual.
-- If it's not then something has gone horribly wrong.
let nReg
= case reg of
RegVirtual vr
-> RegVirtual (renameVirtualReg nUnique vr)
RegReal{}
-> panic "RegAlloc.Graph.Spill.patchIntr: not patching real reg"
let instr' = patchReg1 reg nReg instr
return (instr', nReg)
patchReg1
:: Instruction instr
=> Reg -> Reg -> instr -> instr
patchReg1 old new instr
= let patchF r
| r == old = new
| otherwise = r
in patchRegsOfInstr instr patchF
-- Spiller monad --------------------------------------------------------------
-- | State monad for the spill code generator.
type SpillM a
= State SpillS a
-- | Spill code generator state.
data SpillS
= SpillS
{ -- | Unique supply for generating fresh vregs.
stateUS :: UniqSupply
-- | Spilled vreg vs the number of times it was loaded, stored.
, stateSpillSL :: UniqFM (Reg, Int, Int) }
-- | Create a new spiller state.
initSpillS :: UniqSupply -> SpillS
initSpillS uniqueSupply
= SpillS
{ stateUS = uniqueSupply
, stateSpillSL = emptyUFM }
-- | Allocate a new unique in the spiller monad.
newUnique :: SpillM Unique
newUnique
= do us <- gets stateUS
case takeUniqFromSupply us of
(uniq, us')
-> do modify $ \s -> s { stateUS = us' }
return uniq
-- | Add a spill/reload count to a stats record for a register.
accSpillSL :: (Reg, Int, Int) -> (Reg, Int, Int) -> (Reg, Int, Int)
accSpillSL (r1, s1, l1) (_, s2, l2)
= (r1, s1 + s2, l1 + l2)
-- Spiller stats --------------------------------------------------------------
-- | Spiller statistics.
-- Tells us what registers were spilled.
data SpillStats
= SpillStats
{ spillStoreLoad :: UniqFM (Reg, Int, Int) }
-- | Extract spiller statistics from the spiller state.
makeSpillStats :: SpillS -> SpillStats
makeSpillStats s
= SpillStats
{ spillStoreLoad = stateSpillSL s }
instance Outputable SpillStats where
ppr stats
= pprUFM (spillStoreLoad stats)
(vcat . map (\(r, s, l) -> ppr r <+> int s <+> int l))
| vTurbine/ghc | compiler/nativeGen/RegAlloc/Graph/Spill.hs | bsd-3-clause | 13,496 | 0 | 16 | 4,715 | 2,494 | 1,286 | 1,208 | 226 | 2 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
module Network.Wai.Handler.Warp.HTTP2.HPACK (
hpackEncodeHeader
, hpackEncodeHeaderLoop
, hpackDecodeHeader
, just
) where
import qualified Control.Exception as E
import Control.Monad (unless)
import Data.ByteString (ByteString)
import Network.HPACK hiding (Buffer)
import Network.HPACK.Token
import qualified Network.HTTP.Types as H
import Network.HTTP2
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.PackInt
import qualified Network.Wai.Handler.Warp.Settings as S
import Network.Wai.Handler.Warp.Types
-- $setup
-- >>> :set -XOverloadedStrings
strategy :: EncodeStrategy
strategy = EncodeStrategy { compressionAlgo = Linear, useHuffman = False }
-- Set-Cookie: contains only one cookie value.
-- So, we don't need to split it.
hpackEncodeHeader :: Context -> Buffer -> BufSize
-> InternalInfo -> S.Settings
-> H.Status -> (TokenHeaderList,ValueTable)
-> IO (TokenHeaderList, Int)
hpackEncodeHeader Context{..} buf siz ii settings s (ths0,tbl) = do
let !defServer = S.settingsServerName settings
!ths1 = addHeader tokenServer defServer tbl ths0
date <- getDate ii
let !ths2 = addHeader tokenDate date tbl ths1
!status = packStatus s
!ths3 = (tokenStatus, status) : ths2
encodeTokenHeader buf siz strategy True encodeDynamicTable ths3
{-# INLINE addHeader #-}
addHeader :: Token -> ByteString -> ValueTable -> TokenHeaderList -> TokenHeaderList
addHeader t v tbl ths = case getHeaderValue t tbl of
Nothing -> (t,v) : ths
Just _ -> ths
hpackEncodeHeaderLoop :: Context -> Buffer -> BufSize -> TokenHeaderList
-> IO (TokenHeaderList, Int)
hpackEncodeHeaderLoop Context{..} buf siz hs =
encodeTokenHeader buf siz strategy False encodeDynamicTable hs
----------------------------------------------------------------
hpackDecodeHeader :: HeaderBlockFragment -> Context -> IO (TokenHeaderList, ValueTable)
hpackDecodeHeader hdrblk Context{..} = do
tbl@(_,vt) <- decodeTokenHeader decodeDynamicTable hdrblk `E.catch` handl
unless (checkRequestHeader vt) $
E.throwIO $ ConnectionError ProtocolError "the header key is illegal"
return tbl
where
handl IllegalHeaderName =
E.throwIO $ ConnectionError ProtocolError "the header key is illegal"
handl _ =
E.throwIO $ ConnectionError CompressionError "cannot decompress the header"
{-# INLINE checkRequestHeader #-}
checkRequestHeader :: ValueTable -> Bool
checkRequestHeader reqvt
| getHeaderValue tokenStatus reqvt /= Nothing = False
| getHeaderValue tokenPath reqvt == Nothing = False
| getHeaderValue tokenMethod reqvt == Nothing = False
| getHeaderValue tokenAuthority reqvt == Nothing = False
| getHeaderValue tokenConnection reqvt /= Nothing = False
| just (getHeaderValue tokenTE reqvt) (/= "trailers") = False
| otherwise = True
{-# INLINE just #-}
just :: Maybe a -> (a -> Bool) -> Bool
just Nothing _ = False
just (Just x) p
| p x = True
| otherwise = False
| erikd/wai | warp/Network/Wai/Handler/Warp/HTTP2/HPACK.hs | mit | 3,245 | 0 | 13 | 693 | 820 | 431 | 389 | 67 | 2 |
import Graphics.UI.WX
import Graphics.UI.WXCore
calltiptext = "I can write whatever I want here"
main = start $ do
f <- frame [text := "Scintilla Test"]
p <- panel f []
textlog <- textCtrl p [clientSize := sz 500 200]
textCtrlMakeLogActiveTarget textlog
logMessage "logging enabled"
s <- styledTextCtrl p []
set s [on stcEvent := handler s]
styledTextCtrlSetMouseDwellTime s 2000
set f [ layout := container p $
column 5 $ [ fill $ widget s
, hfill $ widget textlog
]
, clientSize := sz 500 500
]
handler :: StyledTextCtrl a -> EventSTC -> IO ()
handler _ STCUpdateUI = return ()
handler _ STCStyleNeeded = return ()
handler _ STCPainted = return ()
handler stc e = do logMessage $ show e
case e of
(STCDwellStart xy) -> do
pos <- styledTextCtrlPositionFromPoint stc xy
styledTextCtrlCallTipShow stc pos calltiptext
(STCDwellEnd xy) -> do
active <- styledTextCtrlCallTipActive stc
when active $ styledTextCtrlCallTipCancel stc
_ -> return ()
| ekmett/wxHaskell | samples/test/STCEvent.hs | lgpl-2.1 | 1,327 | 0 | 13 | 542 | 371 | 170 | 201 | 29 | 3 |
{-# LANGUAGE CPP #-}
module Distribution.Client.Dependency.Modular.Builder (buildTree) where
-- Building the search tree.
--
-- In this phase, we build a search tree that is too large, i.e, it contains
-- invalid solutions. We keep track of the open goals at each point. We
-- nondeterministically pick an open goal (via a goal choice node), create
-- subtrees according to the index and the available solutions, and extend the
-- set of open goals by superficially looking at the dependencies recorded in
-- the index.
--
-- For each goal, we keep track of all the *reasons* why it is being
-- introduced. These are for debugging and error messages, mainly. A little bit
-- of care has to be taken due to the way we treat flags. If a package has
-- flag-guarded dependencies, we cannot introduce them immediately. Instead, we
-- store the entire dependency.
import Data.List as L
import Data.Map as M
import Prelude hiding (sequence, mapM)
import Distribution.Client.Dependency.Modular.Dependency
import Distribution.Client.Dependency.Modular.Flag
import Distribution.Client.Dependency.Modular.Index
import Distribution.Client.Dependency.Modular.Package
import Distribution.Client.Dependency.Modular.PSQ (PSQ)
import qualified Distribution.Client.Dependency.Modular.PSQ as P
import Distribution.Client.Dependency.Modular.Tree
import Distribution.Client.ComponentDeps (Component)
-- | The state needed during the build phase of the search tree.
data BuildState = BS {
index :: Index, -- ^ information about packages and their dependencies
rdeps :: RevDepMap, -- ^ set of all package goals, completed and open, with reverse dependencies
open :: PSQ (OpenGoal ()) (), -- ^ set of still open goals (flag and package goals)
next :: BuildType, -- ^ kind of node to generate next
qualifyOptions :: QualifyOptions -- ^ qualification options
}
-- | Extend the set of open goals with the new goals listed.
--
-- We also adjust the map of overall goals, and keep track of the
-- reverse dependencies of each of the goals.
extendOpen :: QPN -> [OpenGoal Component] -> BuildState -> BuildState
extendOpen qpn' gs s@(BS { rdeps = gs', open = o' }) = go gs' o' gs
where
go :: RevDepMap -> PSQ (OpenGoal ()) () -> [OpenGoal Component] -> BuildState
go g o [] = s { rdeps = g, open = o }
go g o (ng@(OpenGoal (Flagged _ _ _ _) _gr) : ngs) = go g (cons' ng () o) ngs
-- Note: for 'Flagged' goals, we always insert, so later additions win.
-- This is important, because in general, if a goal is inserted twice,
-- the later addition will have better dependency information.
go g o (ng@(OpenGoal (Stanza _ _ ) _gr) : ngs) = go g (cons' ng () o) ngs
go g o (ng@(OpenGoal (Simple (Dep qpn _) c) _gr) : ngs)
| qpn == qpn' = go g o ngs
-- we ignore self-dependencies at this point; TODO: more care may be needed
| qpn `M.member` g = go (M.adjust ((c, qpn'):) qpn g) o ngs
| otherwise = go (M.insert qpn [(c, qpn')] g) (cons' ng () o) ngs
-- code above is correct; insert/adjust have different arg order
go g o ( (OpenGoal (Simple (Ext _ext ) _) _gr) : ngs) = go g o ngs
go g o ( (OpenGoal (Simple (Lang _lang)_) _gr) : ngs) = go g o ngs
cons' = P.cons . forgetCompOpenGoal
-- | Given the current scope, qualify all the package names in the given set of
-- dependencies and then extend the set of open goals accordingly.
scopedExtendOpen :: QPN -> I -> QGoalReasonChain -> FlaggedDeps Component PN -> FlagInfo ->
BuildState -> BuildState
scopedExtendOpen qpn i gr fdeps fdefs s = extendOpen qpn gs s
where
-- Qualify all package names
qfdeps = qualifyDeps (qualifyOptions s) qpn fdeps
-- Introduce all package flags
qfdefs = L.map (\ (fn, b) -> Flagged (FN (PI qpn i) fn) b [] []) $ M.toList fdefs
-- Combine new package and flag goals
gs = L.map (flip OpenGoal gr) (qfdefs ++ qfdeps)
-- NOTE:
--
-- In the expression @qfdefs ++ qfdeps@ above, flags occur potentially
-- multiple times, both via the flag declaration and via dependencies.
-- The order is potentially important, because the occurrences via
-- dependencies may record flag-dependency information. After a number
-- of bugs involving computing this information incorrectly, however,
-- we're currently not using carefully computed inter-flag dependencies
-- anymore, but instead use 'simplifyVar' when computing conflict sets
-- to map all flags of one package to a single flag for conflict set
-- purposes, thereby treating them all as interdependent.
--
-- If we ever move to a more clever algorithm again, then the line above
-- needs to be looked at very carefully, and probably be replaced by
-- more systematically computed flag dependency information.
-- | Datatype that encodes what to build next
data BuildType =
Goals -- ^ build a goal choice node
| OneGoal (OpenGoal ()) -- ^ build a node for this goal
| Instance QPN I PInfo QGoalReasonChain -- ^ build a tree for a concrete instance
deriving Show
build :: BuildState -> Tree QGoalReasonChain
build = ana go
where
go :: BuildState -> TreeF QGoalReasonChain BuildState
-- If we have a choice between many goals, we just record the choice in
-- the tree. We select each open goal in turn, and before we descend, remove
-- it from the queue of open goals.
go bs@(BS { rdeps = rds, open = gs, next = Goals })
| P.null gs = DoneF rds
| otherwise = GoalChoiceF (P.mapWithKey (\ g (_sc, gs') -> bs { next = OneGoal g, open = gs' })
(P.splits gs))
-- If we have already picked a goal, then the choice depends on the kind
-- of goal.
--
-- For a package, we look up the instances available in the global info,
-- and then handle each instance in turn.
go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Ext _ ) _) _ ) }) =
error "Distribution.Client.Dependency.Modular.Builder: build.go called with Ext goal"
go (BS { index = _ , next = OneGoal (OpenGoal (Simple (Lang _ ) _) _ ) }) =
error "Distribution.Client.Dependency.Modular.Builder: build.go called with Lang goal"
go bs@(BS { index = idx, next = OneGoal (OpenGoal (Simple (Dep qpn@(Q _ pn) _) _) gr) }) =
case M.lookup pn idx of
Nothing -> FailF (toConflictSet (Goal (P qpn) gr)) (BuildFailureNotInIndex pn)
Just pis -> PChoiceF qpn gr (P.fromList (L.map (\ (i, info) ->
(POption i Nothing, bs { next = Instance qpn i info gr }))
(M.toList pis)))
-- TODO: data structure conversion is rather ugly here
-- For a flag, we create only two subtrees, and we create them in the order
-- that is indicated by the flag default.
--
-- TODO: Should we include the flag default in the tree?
go bs@(BS { next = OneGoal (OpenGoal (Flagged qfn@(FN (PI qpn _) _) (FInfo b m w) t f) gr) }) =
FChoiceF qfn gr (w || trivial) m (P.fromList (reorder b
[(True, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn True : gr)) t) bs) { next = Goals }),
(False, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn False : gr)) f) bs) { next = Goals })]))
where
reorder True = id
reorder False = reverse
trivial = L.null t && L.null f
go bs@(BS { next = OneGoal (OpenGoal (Stanza qsn@(SN (PI qpn _) _) t) gr) }) =
SChoiceF qsn gr trivial (P.fromList
[(False, bs { next = Goals }),
(True, (extendOpen qpn (L.map (flip OpenGoal (SDependency qsn : gr)) t) bs) { next = Goals })])
where
trivial = L.null t
-- For a particular instance, we change the state: we update the scope,
-- and furthermore we update the set of goals.
--
-- TODO: We could inline this above.
go bs@(BS { next = Instance qpn i (PInfo fdeps fdefs _) gr }) =
go ((scopedExtendOpen qpn i (PDependency (PI qpn i) : gr) fdeps fdefs bs)
{ next = Goals })
-- | Interface to the tree builder. Just takes an index and a list of package names,
-- and computes the initial state and then the tree from there.
buildTree :: Index -> Bool -> [PN] -> Tree QGoalReasonChain
buildTree idx ind igs =
build BS {
index = idx
, rdeps = M.fromList (L.map (\ qpn -> (qpn, [])) qpns)
, open = P.fromList (L.map (\ qpn -> (topLevelGoal qpn, ())) qpns)
, next = Goals
, qualifyOptions = defaultQualifyOptions idx
}
where
topLevelGoal qpn = OpenGoal (Simple (Dep qpn (Constrained [])) ()) [UserGoal]
qpns | ind = makeIndependent igs
| otherwise = L.map (Q None) igs
| randen/cabal | cabal-install/Distribution/Client/Dependency/Modular/Builder.hs | bsd-3-clause | 9,115 | 0 | 23 | 2,502 | 2,143 | 1,178 | 965 | 86 | 9 |
<?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="ru-RU">
<title>Code Dx | ZAP Расширение</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 1,011 | 78 | 66 | 159 | 487 | 244 | 243 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="es-ES">
<title>TreeTools</title>
<maps>
<homeID>treetools</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/treetools/src/main/javahelp/help_es_ES/helpset_es_ES.hs | apache-2.0 | 960 | 77 | 66 | 155 | 404 | 205 | 199 | -1 | -1 |
module LetIn2 where
--A definition can be lifted from a where or let into the surronding binding group.
--Lifting a definition widens the scope of the definition.
--In this example, lift 'sq' in 'sumSquares'
--This example aims to test lifting a definition from a let clause to a where clause,
--adding parameters and the keyword 'where'.
sumSquares x y = let
pow=2
in (sq pow) x + (sq pow) y
where
sq pow 0=0
sq pow z=z^pow
anotherFun 0 y = sq y
where sq x = x^2
| kmate/HaRe | old/testing/liftOneLevel/LetIn2_TokOut.hs | bsd-3-clause | 554 | 0 | 10 | 178 | 105 | 54 | 51 | 8 | 2 |
{-# OPTIONS_GHC -fwarn-incomplete-patterns -fglasgow-exts #-}
-- Test for trac #366
-- The C2 case is impossible due to the types
module ShouldCompile where
data T a where
C1 :: T Char
C2 :: T Float
exhaustive :: T Char -> Char
exhaustive C1 = ' '
| hvr/jhc | regress/tests/1_typecheck/2_pass/ghc/uncat/tc215.hs | mit | 261 | 0 | 6 | 59 | 48 | 28 | 20 | -1 | -1 |
module UnitTests.Distribution.Client.Targets (
tests
) where
import Distribution.Client.Targets (UserConstraint (..), readUserConstraint)
import Distribution.Compat.ReadP (ReadP, readP_to_S)
import Distribution.Package (PackageName (..))
import Distribution.ParseUtils (parseCommaList)
import Distribution.Text (parse)
import Test.Framework as TF (Test)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, assertEqual)
import Data.Char (isSpace)
tests :: [TF.Test]
tests = [ testCase "readUserConstraint" readUserConstraintTest
, testCase "parseUserConstraint" parseUserConstraintTest
, testCase "readUserConstraints" readUserConstraintsTest
]
readUserConstraintTest :: Assertion
readUserConstraintTest =
assertEqual ("Couldn't read constraint: '" ++ constr ++ "'") expected actual
where
pkgName = "template-haskell"
constr = pkgName ++ " installed"
expected = UserConstraintInstalled (PackageName pkgName)
actual = let (Right r) = readUserConstraint constr in r
parseUserConstraintTest :: Assertion
parseUserConstraintTest =
assertEqual ("Couldn't parse constraint: '" ++ constr ++ "'") expected actual
where
pkgName = "template-haskell"
constr = pkgName ++ " installed"
expected = [UserConstraintInstalled (PackageName pkgName)]
actual = [ x | (x, ys) <- readP_to_S parseUserConstraint constr
, all isSpace ys]
parseUserConstraint :: ReadP r UserConstraint
parseUserConstraint = parse
readUserConstraintsTest :: Assertion
readUserConstraintsTest =
assertEqual ("Couldn't read constraints: '" ++ constr ++ "'") expected actual
where
pkgName = "template-haskell"
constr = pkgName ++ " installed"
expected = [[UserConstraintInstalled (PackageName pkgName)]]
actual = [ x | (x, ys) <- readP_to_S parseUserConstraints constr
, all isSpace ys]
parseUserConstraints :: ReadP r [UserConstraint]
parseUserConstraints = parseCommaList parse
| DavidAlphaFox/ghc | libraries/Cabal/cabal-install/tests/UnitTests/Distribution/Client/Targets.hs | bsd-3-clause | 2,133 | 0 | 12 | 481 | 482 | 270 | 212 | 42 | 1 |
module Vec0 () where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding (map, concat, zipWith, filter, foldl, foldr, (++))
prop = prop0 && prop1 && prop2 && prop3 && prop4
where
xs = [1,2,3,4] :: [Int]
vs = fromList xs
x = Prelude.head xs
n = Prelude.length xs
prop0 = liquidAssertB (x >= 0)
prop1 = liquidAssertB (n > 0)
prop2 = liquidAssertB (Data.Vector.length vs > 0)
prop3 = liquidAssertB (Data.Vector.length vs > 3)
prop4 = liquidAssertB ((vs ! 0 + vs ! 1 + vs ! 2 + vs ! 3) > 0)
| mightymoose/liquidhaskell | tests/pos/vector0.hs | bsd-3-clause | 556 | 0 | 17 | 147 | 237 | 134 | 103 | 13 | 1 |
module Arsec
(
Comment
, comment
, semi
, showC
, unichar
, unichars
, module Control.Applicative
, module Control.Monad
, module Data.Char
, module Text.ParserCombinators.Parsec.Char
, module Text.ParserCombinators.Parsec.Combinator
, module Text.ParserCombinators.Parsec.Error
, module Text.ParserCombinators.Parsec.Prim
) where
import Control.Monad
import Control.Applicative
import Data.Char
import Numeric
import Text.ParserCombinators.Parsec.Char hiding (lower, upper)
import Text.ParserCombinators.Parsec.Combinator hiding (optional)
import Text.ParserCombinators.Parsec.Error
import Text.ParserCombinators.Parsec.Prim hiding ((<|>), many)
type Comment = String
unichar :: Parser Char
unichar = chr . fst . head . readHex <$> many1 hexDigit
unichars :: Parser [Char]
unichars = manyTill (unichar <* spaces) semi
semi :: Parser ()
semi = char ';' *> spaces *> pure ()
comment :: Parser Comment
comment = (char '#' *> manyTill anyToken (char '\n')) <|> string "\n"
showC :: Char -> String
showC c = "'\\x" ++ d ++ "'"
where h = showHex (ord c) ""
d = replicate (4 - length h) '0' ++ h
| bgamari/text | scripts/Arsec.hs | bsd-2-clause | 1,173 | 0 | 11 | 234 | 351 | 205 | 146 | 36 | 1 |
{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
$(do
invalidDecl <- valD (varP (mkName "emptyDo")) (normalB (doE [])) []
addTopDecls [invalidDecl]
return [])
| sdiehl/ghc | testsuite/tests/th/TH_invalid_add_top_decl.hs | bsd-3-clause | 211 | 0 | 15 | 30 | 81 | 40 | 41 | 7 | 0 |
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Utils where
import Idris.AbsSyntax
import Idris.Error
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Typecheck
import Control.Applicative hiding (Const)
import Control.Monad.State
import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.Traversable as Traversable
import Debug.Trace
import qualified Data.Map as Map
recheckC = recheckC_borrowing False True []
recheckC_borrowing uniq_check addConstrs bs fc mkerr env t
= do -- t' <- applyOpts (forget t) (doesn't work, or speed things up...)
ctxt <- getContext
t' <- case safeForget t of
Just ft -> return ft
Nothing -> tclift $ tfail $ mkerr (At fc (IncompleteTerm t))
(tm, ty, cs) <- tclift $ case recheck_borrowing uniq_check bs ctxt env t' t of
Error e -> tfail (At fc (mkerr e))
OK x -> return x
logLvl 6 $ "CONSTRAINTS ADDED: " ++ show (tm, ty, cs)
when addConstrs $ addConstraints fc cs
return (tm, ty)
iderr :: Name -> Err -> Err
iderr _ e = e
checkDef :: FC -> (Name -> Err -> Err) -> [(Name, (Int, Maybe Name, Type, [Name]))]
-> Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkDef fc mkerr ns = checkAddDef False True fc mkerr ns
checkAddDef :: Bool -> Bool -> FC -> (Name -> Err -> Err)
-> [(Name, (Int, Maybe Name, Type, [Name]))]
-> Idris [(Name, (Int, Maybe Name, Type, [Name]))]
checkAddDef add toplvl fc mkerr [] = return []
checkAddDef add toplvl fc mkerr ((n, (i, top, t, psns)) : ns)
= do ctxt <- getContext
(t', _) <- recheckC fc (mkerr n) [] t
when add $ do addDeferred [(n, (i, top, t, psns, toplvl))]
addIBC (IBCDef n)
ns' <- checkAddDef add toplvl fc mkerr ns
return ((n, (i, top, t', psns)) : ns')
-- | Get the list of (index, name) of inaccessible arguments from an elaborated
-- type
inaccessibleImps :: Int -> Type -> [Bool] -> [(Int, Name)]
inaccessibleImps i (Bind n (Pi _ t _) sc) (inacc : ins)
| inacc = (i, n) : inaccessibleImps (i + 1) sc ins
| otherwise = inaccessibleImps (i + 1) sc ins
inaccessibleImps _ _ _ = []
-- | Get the list of (index, name) of inaccessible arguments from the type.
inaccessibleArgs :: Int -> PTerm -> [(Int, Name)]
inaccessibleArgs i (PPi plicity n _ ty t)
| InaccessibleArg `elem` pargopts plicity
= (i,n) : inaccessibleArgs (i+1) t -- an .{erased : Implicit}
| otherwise
= inaccessibleArgs (i+1) t -- a {regular : Implicit}
inaccessibleArgs _ _ = []
elabCaseBlock :: ElabInfo -> FnOpts -> PDecl -> Idris ()
elabCaseBlock info opts d@(PClauses f o n ps)
= do addIBC (IBCDef n)
logLvl 5 $ "CASE BLOCK: " ++ show (n, d)
let opts' = nub (o ++ opts)
-- propagate totality assertion to the new definitions
when (AssertTotal `elem` opts) $ setFlags n [AssertTotal]
rec_elabDecl info EAll info (PClauses f opts' n ps )
-- | Check that the result of type checking matches what the programmer wrote
-- (i.e. - if we inferred any arguments that the user provided, make sure
-- they are the same!)
checkInferred :: FC -> PTerm -> PTerm -> Idris ()
checkInferred fc inf user =
do logLvl 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n\nFROM\n\n" ++
showTmImpls user
logLvl 10 $ "Checking match"
i <- getIState
tclift $ case matchClause' True i user inf of
_ -> return ()
-- Left (x, y) -> tfail $ At fc
-- (Msg $ "The type-checked term and given term do not match: "
-- ++ show x ++ " and " ++ show y)
logLvl 10 $ "Checked match"
-- ++ "\n" ++ showImp True inf ++ "\n" ++ showImp True user)
-- | Return whether inferred term is different from given term
-- (as above, but return a Bool)
inferredDiff :: FC -> PTerm -> PTerm -> Idris Bool
inferredDiff fc inf user =
do i <- getIState
logLvl 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n" ++
showTmImpls user
tclift $ case matchClause' True i user inf of
Right vs -> return False
Left (x, y) -> return True
-- | Check a PTerm against documentation and ensure that every documented
-- argument actually exists. This must be run _after_ implicits have been
-- found, or it will give spurious errors.
checkDocs :: FC -> [(Name, Docstring a)] -> PTerm -> Idris ()
checkDocs fc args tm = cd (Map.fromList args) tm
where cd as (PPi _ n _ _ sc) = cd (Map.delete n as) sc
cd as _ | Map.null as = return ()
| otherwise = ierror . At fc . Msg $
"There is documentation for argument(s) "
++ (concat . intersperse ", " . map show . Map.keys) as
++ " but they were not found."
decorateid decorate (PTy doc argdocs s f o n nfc t) = PTy doc argdocs s f o (decorate n) nfc t
decorateid decorate (PClauses f o n cs)
= PClauses f o (decorate n) (map dc cs)
where dc (PClause fc n t as w ds) = PClause fc (decorate n) (dappname t) as w ds
dc (PWith fc n t as w pn ds)
= PWith fc (decorate n) (dappname t) as w pn
(map (decorateid decorate) ds)
dappname (PApp fc (PRef fc' hl n) as) = PApp fc (PRef fc' hl (decorate n)) as
dappname t = t
-- if 't' is a type class application, assume its arguments are injective
pbinds :: IState -> Term -> ElabD ()
pbinds i (Bind n (PVar t) sc)
= do attack; patbind n
env <- get_env
case unApply (normalise (tt_ctxt i) env t) of
(P _ c _, args) -> case lookupCtxt c (idris_classes i) of
[] -> return ()
_ -> -- type class, set as injective
mapM_ setinjArg args
_ -> return ()
pbinds i sc
where setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
pbinds i tm = return ()
pbty (Bind n (PVar t) sc) tm = Bind n (PVTy t) (pbty sc tm)
pbty _ tm = tm
getPBtys (Bind n (PVar t) sc) = (n, t) : getPBtys sc
getPBtys (Bind n (PVTy t) sc) = (n, t) : getPBtys sc
getPBtys _ = []
psolve (Bind n (PVar t) sc) = do solve; psolve sc
psolve tm = return ()
pvars ist (Bind n (PVar t) sc) = (n, delab ist t) : pvars ist sc
pvars ist _ = []
getFixedInType i env (PExp _ _ _ _ : is) (Bind n (Pi _ t _) sc)
= nub $ getFixedInType i env [] t ++
getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
++ case unApply t of
(P _ n _, _) -> if n `elem` env then [n] else []
_ -> []
getFixedInType i env (_ : is) (Bind n (Pi _ t _) sc)
= getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
getFixedInType i env is tm@(App _ f a)
| (P _ tn _, args) <- unApply tm
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env (param_pos t) ++
getFixedInType i env is f ++
getFixedInType i env is a
Nothing -> nub $ getFixedInType i env is f ++
getFixedInType i env is a
| otherwise = nub $ getFixedInType i env is f ++
getFixedInType i env is a
getFixedInType i _ _ _ = []
getFlexInType i env ps (Bind n (Pi _ t _) sc)
= nub $ (if (not (n `elem` ps)) then getFlexInType i env ps t else []) ++
getFlexInType i (n : env) ps (instantiate (P Bound n t) sc)
getFlexInType i env ps tm@(App _ f a)
| (P nt tn _, args) <- unApply tm, nt /= Bound
= case lookupCtxtExact tn (idris_datatypes i) of
Just t -> nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` param_pos t)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
Nothing -> let ppos = case lookupCtxtExact tn (idris_fninfo i) of
Just fi -> fn_params fi
Nothing -> []
in nub $ paramNames args env [x | x <- [0..length args],
not (x `elem` ppos)]
++ getFlexInType i env ps f ++
getFlexInType i env ps a
| otherwise = nub $ getFlexInType i env ps f ++
getFlexInType i env ps a
getFlexInType i _ _ _ = []
-- | Treat a name as a parameter if it appears in parameter positions in
-- types, and never in a non-parameter position in a (non-param) argument type.
getParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getParamsInType i env ps t = let fix = getFixedInType i env ps t
flex = getFlexInType i env fix t in
[x | x <- fix, not (x `elem` flex)]
getTCinj i (Bind n (Pi _ t _) sc)
= getTCinj i t ++ getTCinj i (instantiate (P Bound n t) sc)
getTCinj i ap@(App _ f a)
| (P _ n _, args) <- unApply ap,
isTCName n = mapMaybe getInjName args
| otherwise = []
where
isTCName n = case lookupCtxtExact n (idris_classes i) of
Just _ -> True
_ -> False
getInjName t | (P _ x _, _) <- unApply t = Just x
| otherwise = Nothing
getTCinj _ _ = []
getTCParamsInType :: IState -> [Name] -> [PArg] -> Type -> [Name]
getTCParamsInType i env ps t = let params = getParamsInType i env ps t
tcs = nub $ getTCinj i t in
filter (flip elem tcs) params
paramNames args env [] = []
paramNames args env (p : ps)
| length args > p = case args!!p of
P _ n _ -> if n `elem` env
then n : paramNames args env ps
else paramNames args env ps
_ -> paramNames args env ps
| otherwise = paramNames args env ps
getUniqueUsed :: Context -> Term -> [Name]
getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []
where
getUniq :: Env -> [(Name, Bool)] -> Term -> State [Name] ()
getUniq env us (Bind n b sc)
= let uniq = case check ctxt env (forgetEnv (map fst env) (binderTy b)) of
OK (_, UType UniqueType) -> True
OK (_, UType NullType) -> True
OK (_, UType AllTypes) -> True
_ -> False in
do getUniqB env us b
getUniq ((n,b):env) ((n, uniq):us) sc
getUniq env us (App _ f a) = do getUniq env us f; getUniq env us a
getUniq env us (V i)
| i < length us = if snd (us!!i) then use (fst (us!!i)) else return ()
getUniq env us (P _ n _)
| Just u <- lookup n us = if u then use n else return ()
getUniq env us _ = return ()
use n = do ns <- get; put (n : ns)
getUniqB env us (Let t v) = getUniq env us v
getUniqB env us (Guess t v) = getUniq env us v
-- getUniqB env us (Pi t v) = do getUniq env us t; getUniq env us v
getUniqB env us (NLet t v) = getUniq env us v
getUniqB env us b = return () -- getUniq env us (binderTy b)
-- In a functional application, return the names which are used
-- directly in a static position
getStaticNames :: IState -> Term -> [Name]
getStaticNames ist (Bind n (PVar _) sc)
= getStaticNames ist (instantiate (P Bound n Erased) sc)
getStaticNames ist tm
| (P _ fn _, args) <- unApply tm
= case lookupCtxtExact fn (idris_statics ist) of
Just stpos -> getStatics args stpos
_ -> []
where
getStatics (P _ n _ : as) (True : ss) = n : getStatics as ss
getStatics (_ : as) (_ : ss) = getStatics as ss
getStatics _ _ = []
getStaticNames _ _ = []
getStatics :: [Name] -> Term -> [Bool]
getStatics ns (Bind n (Pi _ _ _) t)
| n `elem` ns = True : getStatics ns t
| otherwise = False : getStatics ns t
getStatics _ _ = []
mkStatic :: [Name] -> PDecl -> PDecl
mkStatic ns (PTy doc argdocs syn fc o n nfc ty)
= PTy doc argdocs syn fc o n nfc (mkStaticTy ns ty)
mkStatic ns t = t
mkStaticTy :: [Name] -> PTerm -> PTerm
mkStaticTy ns (PPi p n fc ty sc)
| n `elem` ns = PPi (p { pstatic = Static }) n fc ty (mkStaticTy ns sc)
| otherwise = PPi p n fc ty (mkStaticTy ns sc)
mkStaticTy ns t = t
| osa1/Idris-dev | src/Idris/Elab/Utils.hs | bsd-3-clause | 12,955 | 4 | 20 | 4,557 | 4,901 | 2,463 | 2,438 | 239 | 13 |
{-# LANGUAGE DataKinds, PolyKinds, TypeFamilies #-}
module T10815 where
import Data.Proxy
type family Any :: k
class kproxy ~ 'KProxy => C (kproxy :: KProxy k) where
type F (a :: k)
type G a :: k
instance C ('KProxy :: KProxy Bool) where
type F a = Int
type G a = Any
| ezyang/ghc | testsuite/tests/indexed-types/should_compile/T10815.hs | bsd-3-clause | 281 | 1 | 8 | 67 | 102 | 58 | 44 | 10 | 0 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE Safe #-}
-- | Basic test to see if Safe flags compiles
module SafeFlags11 where
f :: Int
f = 1
| wxwxwwxxx/ghc | testsuite/tests/safeHaskell/flags/SafeFlags11.hs | bsd-3-clause | 133 | 0 | 4 | 30 | 17 | 12 | 5 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.PlantUML.Filter.TypesSpec where
import Test.Hspec
import Text.Pandoc.PlantUML.Filter.Types
spec :: Spec
spec = do
describe "Text.Pandoc.PlantUML.Filter.Types" $ do
it "can show an image filename correctly" $ do
(show (ImageFileName "base" "eps")) `shouldBe` "base.eps"
main :: IO ()
main = hspec spec
| thriqon/pandoc-plantuml-diagrams | test/Text/Pandoc/PlantUML/Filter/TypesSpec.hs | isc | 372 | 0 | 17 | 61 | 94 | 52 | 42 | 11 | 1 |
module Graphics.Pylon.Binding.Pango.Font where
import Graphics.Pylon.Foreign.Pango.Font
import Graphics.Pylon.Foreign.GLib
import qualified Data.ByteString as S
import qualified Data.ByteString.Unsafe as S
import Foreign.Marshal
import Foreign.Storable
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.C.String
fontDescriptionNew :: IO FontDescription
fontDescriptionNew = fmap FontDescription $
pango_font_description_new >>=
newForeignPtr p'pango_font_description_free
fontDescriptionCopy :: FontDescription -> IO FontDescription
fontDescriptionCopy (FontDescription f'fd) = fmap FontDescription $
withForeignPtr f'fd $ \fd ->
pango_font_description_copy fd >>=
newForeignPtr p'pango_font_description_free
fontDescriptionEqual :: FontDescription -> FontDescription -> IO Bool
fontDescriptionEqual (FontDescription f'a) (FontDescription f'b) =
withForeignPtr f'a $ \a -> withForeignPtr f'b $ \b ->
fmap toBool $ pango_font_description_equal a b
fontDescriptionSetFamily :: S.ByteString -> FontDescription -> IO ()
fontDescriptionSetFamily fam (FontDescription f'fd) =
S.useAsCString fam $ \f -> withForeignPtr f'fd $ \fd ->
pango_font_description_set_family fd f
fontDescriptionGetFamily :: FontDescription -> IO (Maybe S.ByteString)
fontDescriptionGetFamily (FontDescription f'fd) =
withForeignPtr f'fd $ \fd -> do
p <- pango_font_description_get_family fd
if p == nullPtr
then return Nothing
else Just `fmap` S.unsafePackCString p
fontDescriptionSetStyle :: Style -> FontDescription -> IO ()
fontDescriptionSetStyle sty (FontDescription f'fd) =
withForeignPtr f'fd $ \fd -> pango_font_description_set_style fd sty
fontDescriptionGetStyle :: FontDescription -> IO Style
fontDescriptionGetStyle (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_style fd
fontDescriptionSetVariant :: Variant -> FontDescription -> IO ()
fontDescriptionSetVariant var (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_variant fd var
fontDescriptionGetVariant :: FontDescription -> IO Variant
fontDescriptionGetVariant (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_variant fd
fontDescriptionSetWeight :: Weight -> FontDescription -> IO ()
fontDescriptionSetWeight w (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_weight fd w
fontDescriptionGetWeight :: FontDescription -> IO Weight
fontDescriptionGetWeight (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_weight fd
fontDescriptionSetStretch :: Stretch -> FontDescription -> IO ()
fontDescriptionSetStretch s (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_stretch fd s
fontDescriptionGetStretch :: FontDescription -> IO Stretch
fontDescriptionGetStretch (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_stretch fd
fontDescriptionSetSize :: Int -> FontDescription -> IO ()
fontDescriptionSetSize s (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_size fd (fromIntegral s)
fontDescriptionGetSize :: FontDescription -> IO Int
fontDescriptionGetSize (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
fromIntegral `fmap` pango_font_description_get_size fd
fontDescriptionSetAbsoluteSize :: Int -> FontDescription -> IO ()
fontDescriptionSetAbsoluteSize s (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_absolute_size fd (fromIntegral s)
fontDescriptionGetSizeIsAbsolute :: FontDescription -> IO Bool
fontDescriptionGetSizeIsAbsolute (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
toBool `fmap` pango_font_description_get_size_is_absolute fd
fontDescriptionSetGravity :: Gravity -> FontDescription -> IO ()
fontDescriptionSetGravity g (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_set_gravity fd g
fontDescriptionGetGravity :: FontDescription -> IO Gravity
fontDescriptionGetGravity (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_gravity fd
fontDescriptionGetSetFields :: FontDescription -> IO FontMask
fontDescriptionGetSetFields (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_get_set_fields fd
fontDescriptionUnsetFields :: FontMask -> FontDescription -> IO ()
fontDescriptionUnsetFields mask (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_unset_fields fd mask
fontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()
fontDescriptionMerge (FontDescription f'to) (FontDescription f'from) rep =
withForeignPtr f'to $ \to -> withForeignPtr f'from $ \from ->
pango_font_description_merge to from (fromBool rep)
fontDescriptionFromString :: S.ByteString -> IO FontDescription
fontDescriptionFromString s =
S.unsafeUseAsCString s $ \str ->
pango_font_description_from_string str >>= \p ->
fmap FontDescription $
newForeignPtr p'pango_font_description_free p
fontDescriptionToString :: FontDescription -> IO S.ByteString
fontDescriptionToString (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_to_string fd >>= \p -> do
r <- S.packCString p
g_free p
return r
fontDescriptionToFilename :: FontDescription -> IO FilePath
fontDescriptionToFilename (FontDescription f'fd) =
withForeignPtr f'fd $ \fd ->
pango_font_description_to_filename fd >>= \p -> do
f <- peekCString p
g_free p
return f
fontMapListFamilies :: FontMap -> IO [FontFamily]
fontMapListFamilies (FontMap f'fm) =
withForeignPtr f'fm $ \fm ->
alloca $ \pfams -> alloca $ \nfam -> do
pango_font_map_list_families fm pfams nfam
n <- peek nfam
fams <- peek pfams
fs <- peekArray (fromIntegral n) fams
g_free fams
mapM (\p -> FontFamily `fmap` newForeignPtr_ p) fs
fontFamilyGetName :: FontFamily -> IO S.ByteString
fontFamilyGetName (FontFamily fam) = withForeignPtr fam $ \p ->
pango_font_family_get_name p >>= S.unsafePackCString
fontFamilyIsMonospace :: FontFamily -> IO Bool
fontFamilyIsMonospace (FontFamily fam) = withForeignPtr fam $ \p ->
toBool `fmap` pango_font_family_is_monospace p
fontFamilyListFaces :: FontFamily -> IO [FontFace]
fontFamilyListFaces (FontFamily f'fam) = withForeignPtr f'fam $ \fam ->
alloca $ \pfaces -> alloca $ \pnfaces -> do
pango_font_family_list_faces fam pfaces pnfaces
nfaces <- peek pnfaces
faces <- peek pfaces
fs <- peekArray (fromIntegral nfaces) faces
g_free faces
mapM (\p -> FontFace `fmap` newForeignPtr_ p) fs
fontFaceGetFaceName :: FontFace -> IO S.ByteString
fontFaceGetFaceName (FontFace f) = withForeignPtr f $ \p ->
pango_font_face_get_face_name p >>= S.unsafePackCString
fontFaceListSizes :: FontFace -> IO [Int]
fontFaceListSizes (FontFace f'face) = withForeignPtr f'face $ \face ->
alloca $ \psizes -> alloca $ \pnsizes -> do
pango_font_face_list_sizes face psizes pnsizes
nsizes <- peek pnsizes
sizes <- peek psizes
ss <- peekArray (fromIntegral nsizes) sizes
g_free sizes
return $ map fromIntegral ss
fontFaceDescribe :: FontFace -> IO FontDescription
fontFaceDescribe (FontFace f) = withForeignPtr f $ \p ->
pango_font_face_describe p >>= newForeignPtr_ >>= return . FontDescription
fontFaceIsSynthesized :: FontFace -> IO Bool
fontFaceIsSynthesized (FontFace f) = withForeignPtr f $ \p ->
toBool `fmap` pango_font_face_is_synthesized p
| philopon/pylon | Graphics/Pylon/Binding/Pango/Font.hs | mit | 7,796 | 0 | 17 | 1,363 | 2,072 | 1,021 | 1,051 | 164 | 2 |
-- Main function of the Haskell program.
module Root.Src.Main where
import Root.Src.Finder
main = do
putStrLn "Hello Haskell World!"
let x = maxFunction [5, 4, 33, 2, 1]
print x
| codeboardio/kali | test/src_examples/haskell/template_project/Root/Src/Main.hs | mit | 206 | 0 | 11 | 58 | 58 | 32 | 26 | 6 | 1 |
{-# htermination (unzip3 :: (List (Tup3 b a c)) -> Tup3 (List b) (List a) (List c)) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup3 a b c = Tup3 a b c ;
foldr :: (b -> a -> a) -> a -> (List b) -> a;
foldr f z Nil = z;
foldr f z (Cons x xs) = f x (foldr f z xs);
unzip300 (Tup3 as bs cs) = as;
unzip301 (Tup3 as bs cs) = bs;
unzip302 (Tup3 as bs cs) = cs;
unzip30 (Tup3 a b c) vv = Tup3 (Cons a (unzip300 vv)) (Cons b (unzip301 vv)) (Cons c (unzip302 vv));
unzip3 :: (List (Tup3 c a b)) -> Tup3 (List c) (List a) (List b);
unzip3 = foldr unzip30 (Tup3 Nil Nil Nil);
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/unzip3_1.hs | mit | 648 | 3 | 9 | 170 | 372 | 181 | 191 | 13 | 1 |
primeFactors :: Int -> [Int]
primeFactors x = fn x [2..x]
where
fn x' [] = []
fn x' (y:ys)
| x' `mod` y == 0 = y : fn (x' `div` y) [2..x']
| otherwise = fn x' ys
-- primeFactors 13195 == [5,7,13,29]
maxPrimeFactor :: Int -> Int
maxPrimeFactor x = maximum $ primeFactors x
-- maxPrimeFactor 600851475143 == 6857
| samidarko/euler | problem003.hs | mit | 339 | 2 | 9 | 90 | 151 | 75 | 76 | 8 | 2 |
-- | Descriptive position in C code
module Centrinel.Data.CodePosition where
import qualified Language.C.Data.Node as C
import qualified Language.C.Analysis.SemRep as C
import Language.C.Analysis.Debug () -- instance PP.Pretty Type
import qualified Centrinel.PrettyPrint as PP
import Centrinel.PrettyPrint ((<+>))
-- | Trace of an error position
data NPEPosn = NPEArg !Int !C.VarName !C.NodeInfo !NPEPosn -- ^ function argument j
| NPERet !NPEPosn -- ^ function return value
| NPEDecl !C.VarName -- ^ a declaration
| NPETypeDefRef !C.NodeInfo !NPEPosn -- ^ a typedef occurrence
| NPETypeDefDef !C.NodeInfo !NPEPosn -- ^ the typedef declaration
| NPEDefn !C.VarName -- ^ a (function) definition
| NPEStmt !C.NodeInfo !NPEPosn -- ^ a statement in a function
| NPETypeOfExpr !C.NodeInfo !NPEPosn -- ^ in the type of the expression
instance PP.Pretty NPEPosn where
pretty p0 = PP.vcat $ case p0 of
NPEDecl ident -> [PP.text "in function declaration" <+> PP.quotes (PP.pretty ident)]
NPEArg j ident ni p -> [PP.text "in" <+> prettyOrdinal j <+> PP.text "argument" <+> PP.quotes (PP.pretty ident)
<+> PP.text "at" <+> PP.prettyPos ni, PP.pretty p]
NPERet p -> [PP.text "in return type", PP.pretty p]
NPETypeDefRef ni p -> [PP.text "at" <+> PP.prettyPos ni, PP.pretty p]
NPETypeDefDef ni p -> [PP.text "in type defined at" <+> PP.prettyPos ni, PP.pretty p]
NPEDefn ident -> [PP.text "in the definition of " <+> PP.quotes (PP.pretty ident)]
NPEStmt ni p -> [PP.text "in statement at " <+> PP.prettyPos ni, PP.pretty p]
NPETypeOfExpr ni p -> [PP.text "in the type of the expression at " <+> PP.prettyPos ni, PP.pretty p]
prettyOrdinal :: Integral n => n -> PP.Doc
prettyOrdinal n = PP.integer (toInteger n) PP.<> suf
where
r = n `mod` 10
suf = case r of
1 | h /= 11 -> PP.text "st"
2 | h /= 12 -> PP.text "nd"
3 | h /= 13 -> PP.text "rd"
_ -> PP.text "th"
h = n `mod` 100
| lambdageek/use-c | src/Centrinel/Data/CodePosition.hs | mit | 2,008 | 0 | 17 | 452 | 654 | 331 | 323 | 64 | 4 |
import Graphics.Gloss
import System.Environment
data BinaryTree = Branch Float BinaryTree BinaryTree
| Leaf
deriving (Show, Ord, Eq)
maxwidth = 1200
maxheight = 600
node = Color (dark green) (ThickCircle 1.5 3.0)
niceline coords = Color (light chartreuse) (Line coords)
main = do
fn:rest <- getArgs
file <- readFile fn
let tree = mktree [read x :: Float | x <- words file] (Branch 0 Leaf Leaf)
simulate (InWindow
"BTree Demo" -- Title
(truncate maxwidth, truncate maxheight) -- Dimensions
(10, 10)) -- Position
black -- Background
2 -- Steps per second
tree -- Initial state
gentree -- Picture representation of state
elongate -- Alter state
size :: BinaryTree -> Integer
size Leaf = 0
size (Branch v l r) = 1 + (size l) + (size r)
iheight :: BinaryTree -> Float
iheight (Leaf) = 0
iheight (Branch v l r) = v + max (iheight l) (iheight r)
insertTree :: Float -> BinaryTree -> BinaryTree
insertTree n (Branch v l r)
| size l < size r = Branch v (insertTree n l) r
| otherwise = Branch v l (insertTree n r)
insertTree n Leaf = Branch n Leaf Leaf
mktree :: [Float] -> BinaryTree -> BinaryTree
mktree (x:xs) tree = mktree xs (insertTree x tree)
mktree [] tree = tree
height x total = x * (maxheight / 2) / total
tree :: Float -> Float -> BinaryTree -> Picture
tree total n Leaf = Blank
tree total n (Branch i l r) = Pictures [niceline [(0,0), (n, h)],
Translate n h (tree total (-n/2) l),
Translate n h (tree total (n/2) r),
Translate n h node]
where h = -(height i total)
addval :: Float -> BinaryTree -> BinaryTree
addval i (Branch v l r) = Branch (v+i) l r
addval _ Leaf = Leaf
treelongate :: Float -> BinaryTree -> BinaryTree
treelongate n Leaf = Leaf
treelongate n (Branch v l r)
| n > 0 = Branch v (treelongate (n-1) l) (treelongate (n-1) r)
| lh > rh = Branch v l (addval (lh - rh) r)
| lh < rh = Branch v (addval (rh - lh) l) r
| otherwise = Branch v l r
where
lh = iheight l
rh = iheight r
elongate _ time tree@(Branch v l r) = treelongate v (addval 1 tree)
gentree (Branch _ l r) = Translate 0 (maxheight / 3)
(Pictures [tree t (-maxwidth / 5) l,
tree t (maxwidth / 5) r,
node])
where t = max (iheight l) (iheight r) | tetrapus/Tree-Extension-Visualisation | vis.hs | mit | 2,884 | 9 | 14 | 1,178 | 1,137 | 555 | 582 | 62 | 1 |
module Rebase.Data.Bifunctor.Tannen
(
module Data.Bifunctor.Tannen
)
where
import Data.Bifunctor.Tannen
| nikita-volkov/rebase | library/Rebase/Data/Bifunctor/Tannen.hs | mit | 107 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
module Shexkell.Semantic.Neighbourhood
( arcsOut
, arcsIn
, predicatesOut
, predicatesIn
, neigh
, predicates
) where
import Data.RDF (Node, Rdf, RDF, Triples, query, predicateOf)
import qualified Data.Set as Set
arcsOut :: Rdf g =>
RDF g
-> Node
-> Triples
arcsOut graph node = query graph (Just node) Nothing Nothing
predicatesOut :: Rdf g =>
RDF g
-> Node
-> [Node]
predicatesOut graph = map predicateOf . arcsOut graph
arcsIn :: Rdf g =>
RDF g
-> Node
-> Triples
arcsIn graph node = query graph Nothing Nothing (Just node)
predicatesIn :: Rdf g =>
RDF g
-> Node
-> [Node]
predicatesIn graph = map predicateOf . arcsIn graph
neigh :: Rdf g =>
RDF g
-> Node
-> Triples
neigh = unionOf arcsIn arcsOut
predicates :: Rdf g =>
RDF g
-> Node
-> [Node]
predicates = unionOf predicatesIn predicatesOut
unionOf :: (Rdf g, Ord a) =>
(RDF g -> Node -> [a])
-> (RDF g -> Node -> [a])
-> RDF g
-> Node
-> [a]
unionOf f g graph node = let
left = Set.fromList $ f graph node
right = Set.fromList $ g graph node
in Set.toList $ left `Set.union` right
| weso/shexkell | src/Shexkell/Semantic/Neighbourhood.hs | mit | 1,134 | 0 | 11 | 291 | 455 | 235 | 220 | 49 | 1 |
-- | Functionality for inspecting and debugging Selda queries.
module Database.Selda.Debug
( OnError (..), defPPConfig
, compile
, compileCreateTable, compileDropTable
, compileInsert, compileUpdate
) where
import Database.Selda.Backend
import Database.Selda.Compile
import Database.Selda.Table.Compile
| valderman/selda | selda/src/Database/Selda/Debug.hs | mit | 313 | 0 | 5 | 41 | 54 | 37 | 17 | 8 | 0 |
-- Find the K'th Element of a List
-- http://www.codewars.com/kata/5416356b1b28a5e297000bc7/
module Kth where
import Prelude hiding ((!!))
elementAt :: [a] -> Int -> a
elementAt (x:_) 1 = x
elementAt (x: xs) n = elementAt xs (n-1)
| gafiatulin/codewars | src/7 kyu/Kth.hs | mit | 235 | 0 | 7 | 41 | 79 | 46 | 33 | 5 | 1 |
-- sum
module Summer where
summer :: (Eq a, Num a) => a -> a
summer 0 = 0
summer x = x + summer(x - 1)
| Lyapunov/haskell-programming-from-first-principles | chapter_8/sum.hs | mit | 104 | 0 | 8 | 28 | 59 | 32 | 27 | 4 | 1 |
module Debug.Trace.Err
(trace)
where
import Data.Text (Text)
import qualified Data.Text.IO as TIO
import System.IO.Unsafe
import System.IO (stderr)
trace :: Text -> a -> a
trace msg x = unsafePerformIO $ do
TIO.hPutStrLn stderr msg
return x
| cgag/selecth | src/Debug/Trace/Err.hs | mit | 251 | 0 | 9 | 46 | 90 | 51 | 39 | 10 | 1 |
import Data.Char
-- Devuelve un set de notas dependiendo de su resto modulo 12, determinando si es bemol, sostenido o becuadro
notas :: Int -> [[Char]]
notas x = [ n !! caso | n <- todas ]
where todas = [["Do","Do"],["Do#","Reb"],["Re","Re"],["Re#","Mib"],["Mi","Mi"],["Fa","Fa"],["Fa#","Solb"],["Sol","Sol"],["Sol#","Lab"],["La","La"],["La#","Sib"],["Si","Dob"]]
caso
| elem (mod x 12) [0,2,4,7,9,11] = 0
| otherwise = 1
-- Mapea cada nota con su equivalente numerico
nota :: [Char] -> Int
nota n
| x ["do","si#"] = 0
| x ["do#","reb"] = 1
| x ["re"] = 2
| x ["re#","mib"] = 3
| x ["mi","fab"] = 4
| x ["fa","mi#"] = 5
| x ["fa#","solb"] = 6
| x ["sol"] = 7
| x ["sol#","lab"] = 8
| x ["la"] = 9
| x ["la#","sib"] = 10
| x ["si","dob"] = 11
| otherwise = 12
where x = elem $ map toLower n
-- Calcula la estructura basica del modo jonico
escala :: [Int]
escala = scanl (+) 0 [tono, tono, semitono, tono, tono, tono]
where semitono = 1
tono = 2
-- Devuelve un set de notas dependiendo del centro tonal, modificando el caso particular de Solb para que no repita nombres de notas
tonalidad :: Int -> [[Char]]
tonalidad x = [ cycle (notas x) !! ((caso n) + x) | n <- escala ]
where caso n
| x == 6 && n == 5 = 6
| otherwise = n
-- Se corre una tonalidad hasta colocar el centro tonal en $b
-- el modo "a" debe correr la tonalidad tantas posiciones como valor haya en el indice $a de $escala
modo :: Int -> [Char] -> [[Char]]
modo a b = [ cycle corrimiento !! (n + a) | n <- [0..6] ]
where corrimiento = tonalidad $ c + 12 - (escala !! a)
c = nota b
jonico = modo 0
dorico = modo 1
frigio = modo 2
lidio = modo 3
mixolidio = modo 4
eolico = modo 5
locrio = modo 6
mayor = jonico
menor = eolico
estructura :: Int -> [Int]
estructura n = take n [0,2..]
-- Construye los acordes basicos de una escala dada
acordes x = [ triada e | e <- [0..6] ]
where triada e = [ cycle x !! (n+e) | n <- estructura 3 ]
| martriay/amadeus | main.hs | mit | 2,067 | 23 | 10 | 555 | 922 | 482 | 440 | 49 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.AutocompleteErrorEvent
(newAutocompleteErrorEvent, getReason, AutocompleteErrorEvent(..),
gTypeAutocompleteErrorEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AutocompleteErrorEvent Mozilla AutocompleteErrorEvent documentation>
newAutocompleteErrorEvent ::
(MonadDOM m, ToJSString type') =>
type' ->
Maybe AutocompleteErrorEventInit -> m AutocompleteErrorEvent
newAutocompleteErrorEvent type' eventInitDict
= liftDOM
(AutocompleteErrorEvent <$>
new (jsg "AutocompleteErrorEvent")
[toJSVal type', toJSVal eventInitDict])
-- | <https://developer.mozilla.org/en-US/docs/Web/API/AutocompleteErrorEvent.reason Mozilla AutocompleteErrorEvent.reason documentation>
getReason ::
(MonadDOM m, FromJSString result) =>
AutocompleteErrorEvent -> m result
getReason self
= liftDOM ((self ^. js "reason") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/AutocompleteErrorEvent.hs | mit | 1,935 | 0 | 10 | 326 | 432 | 268 | 164 | 33 | 1 |
{-# LANGUAGE DeriveDataTypeable, QuasiQuotes, TemplateHaskell #-}
{-|
Module : Calculational.Quasiquoter
Description : Expressions parser
Copyright : (c) Francisco J Cháves, 2012
License : MIT
Maintainer : pachopepe@gmail.com
Stability : experimental
A expression parser for Dijkstra-Sholten style like expressions.
-}
module Calculational.QuasiQuoter (
calc
)
where
import Data.Generics
import qualified Language.Haskell.TH as TH
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Quote
import Text.Parsec.Pos (newPos)
import Calculational.Parser (parseExpr)
import Calculational.MonoidExt
-- | The calculational quasiquoter function
calc :: QuasiQuoter
calc = QuasiQuoter quoteExprExp undefined undefined undefined
quoteExprExp :: String -> TH.ExpQ
quoteExprExp s = do loc <- TH.location
let pos = newPos (TH.loc_filename loc)
(fst $ TH.loc_start loc)
(snd $ TH.loc_start loc)
qExpr <- parseExpr pos s
expr <- qExpr
return expr
| pachopepe/Calculational | src/Calculational/QuasiQuoter.hs | mit | 1,163 | 0 | 14 | 338 | 188 | 103 | 85 | 20 | 1 |
module Tamien.GM.EvalTest where
import Tamien.GM
import Test.HUnit
assertProgEq x prog
= assertEqual prog x (run prog)
testId = assertProgEq 3 "main = I 3"
testId2 = assertProgEq 3 "main = S K K 3"
testId3 = assertProgEq 3 "main = twice (I I I) 3"
testLet = assertProgEq 3 "main = let id = I I I in id 3"
testLetRec = assertProgEq 4
"pair x y f = f x y; \
\fst p = p K; \
\snd p = p K1; \
\f x y = letrec \
\ a = pair x b; \
\ b = pair y a \
\ in fst (snd (snd (snd a))); \
\main = f 3 4"
testNegate = assertProgEq (-3) "main = negate 3"
testNegateIndir = assertProgEq (-3) "main = negate (I 3)"
testNegateTwice = assertProgEq 3 "main = twice negate 3"
testAdd = assertProgEq 9 "main = + 6 3"
testSub = assertProgEq 3 "main = - 6 3"
testMul = assertProgEq 18 "main = * 6 3"
testDiv = assertProgEq 2 "main = / 6 3"
testDivTruncation = assertProgEq 2 "main = / 7 3"
testPrimArithIndir = assertProgEq 26 "main = + (* 6 3) 8"
testPrimArithIndir2 = assertProgEq 26 "main = + 8 (* 6 3)"
testPrimArithIndir3 = assertProgEq 26 "main = + (* 6 3) (I 8)"
testEq1 = assertProgEq 1 "main = (== 5 5)"
testEq2 = assertProgEq 0 "main = (== 5 4)"
testNe1 = assertProgEq 0 "main = (/= 5 5)"
testNe2 = assertProgEq 1 "main = (/= 5 4)"
testGt1 = assertProgEq 1 "main = (> 5 4)"
testGt2 = assertProgEq 0 "main = (> 4 5)"
testGt3 = assertProgEq 0 "main = (> 5 5)"
testGte1 = assertProgEq 1 "main = (>= 5 4)"
testGte2 = assertProgEq 0 "main = (>= 4 5)"
testGte3 = assertProgEq 1 "main = (>= 5 5)"
testLt1 = assertProgEq 0 "main = (< 5 4)"
testLt2 = assertProgEq 1 "main = (< 4 5)"
testLt3 = assertProgEq 0 "main = (< 5 5)"
testLte1 = assertProgEq 0 "main = (<= 5 4)"
testLte2 = assertProgEq 1 "main = (<= 4 5)"
testLte3 = assertProgEq 1 "main = (<= 5 5)"
testFac = assertProgEq 120 "fac n = if (== n 0) 1 (* n (fac (- n 1))); main = fac 5"
testFib = assertProgEq 8 "fib n = if (== n 0) 0 (if (== n 1) 1 (+ (fib (- n 1)) (fib (- n 2)))); main = fib 6"
tests = TestList $
map TestCase
[ testId
, testId2
, testId3
, testLet
, testLetRec
, testNegate
, testNegateIndir
, testNegateTwice
, testAdd
, testSub
, testMul
, testDiv
, testDivTruncation
, testPrimArithIndir
, testPrimArithIndir2
, testPrimArithIndir3
, testEq1
, testEq2
, testNe1
, testNe2
, testGt1
, testGt2
, testGt3
, testGte1
, testGte2
, testGte3
, testLt1
, testLt2
, testLt3
, testLte1
, testLte2
, testLte3
, testFac
, testFib
]
main = runTestTT tests
| cpettitt/tamien | Tamien/GM/EvalTest.hs | mit | 3,212 | 0 | 7 | 1,313 | 514 | 277 | 237 | 77 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# OPTIONS_HADDOCK hide #-}
module System.Console.Docopt.ApplicativeParsec
(
module Control.Applicative
, module Text.ParserCombinators.Parsec
) where
import Control.Applicative hiding (optional, (<|>))
import Text.ParserCombinators.Parsec hiding (many)
| docopt/docopt.hs | System/Console/Docopt/ApplicativeParsec.hs | mit | 332 | 0 | 5 | 48 | 53 | 37 | 16 | 8 | 0 |
{- This module was generated from data in the Kate syntax
highlighting file html.xml, version 2.1, by Wilbert Berendsen (wilbert@kde.nl) -}
module Text.Highlighting.Kate.Syntax.Html
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import qualified Text.Highlighting.Kate.Syntax.Alert
import qualified Text.Highlighting.Kate.Syntax.Css
import qualified Text.Highlighting.Kate.Syntax.Javascript
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
-- | Full name of language.
syntaxName :: String
syntaxName = "HTML"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.htm;*.html;*.shtml;*.shtm"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("HTML","Start")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("HTML","Start") -> return ()
("HTML","FindHTML") -> return ()
("HTML","FindEntityRefs") -> return ()
("HTML","FindPEntityRefs") -> return ()
("HTML","FindAttributes") -> return ()
("HTML","FindDTDRules") -> return ()
("HTML","Comment") -> return ()
("HTML","CDATA") -> return ()
("HTML","PI") -> return ()
("HTML","Doctype") -> return ()
("HTML","Doctype Internal Subset") -> return ()
("HTML","Doctype Markupdecl") -> return ()
("HTML","Doctype Markupdecl DQ") -> return ()
("HTML","Doctype Markupdecl SQ") -> return ()
("HTML","El Open") -> return ()
("HTML","El Close") -> return ()
("HTML","El Close 2") -> return ()
("HTML","El Close 3") -> return ()
("HTML","CSS") -> return ()
("HTML","CSS content") -> return ()
("HTML","JS") -> return ()
("HTML","JS content") -> return ()
("HTML","JS comment close") -> (popContext) >> pEndLine
("HTML","Value") -> return ()
("HTML","Value NQ") -> (popContext >> popContext) >> pEndLine
("HTML","Value DQ") -> return ()
("HTML","Value SQ") -> return ()
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
regex_'3c'21DOCTYPE'5cs'2b = compileRegex True "<!DOCTYPE\\s+"
regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a = compileRegex True "<\\?[\\w:-]*"
regex_'3cstyle'5cb = compileRegex True "<style\\b"
regex_'3cscript'5cb = compileRegex True "<script\\b"
regex_'3cpre'5cb = compileRegex True "<pre\\b"
regex_'3cdiv'5cb = compileRegex True "<div\\b"
regex_'3ctable'5cb = compileRegex True "<table\\b"
regex_'3cul'5cb = compileRegex True "<ul\\b"
regex_'3col'5cb = compileRegex True "<ol\\b"
regex_'3cdl'5cb = compileRegex True "<dl\\b"
regex_'3carticle'5cb = compileRegex True "<article\\b"
regex_'3caside'5cb = compileRegex True "<aside\\b"
regex_'3cdetails'5cb = compileRegex True "<details\\b"
regex_'3cfigure'5cb = compileRegex True "<figure\\b"
regex_'3cfooter'5cb = compileRegex True "<footer\\b"
regex_'3cheader'5cb = compileRegex True "<header\\b"
regex_'3cmain'5cb = compileRegex True "<main\\b"
regex_'3cnav'5cb = compileRegex True "<nav\\b"
regex_'3csection'5cb = compileRegex True "<section\\b"
regex_'3c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "<[A-Za-z_:][\\w.:_-]*"
regex_'3c'2fpre'5cb = compileRegex True "</pre\\b"
regex_'3c'2fdiv'5cb = compileRegex True "</div\\b"
regex_'3c'2ftable'5cb = compileRegex True "</table\\b"
regex_'3c'2ful'5cb = compileRegex True "</ul\\b"
regex_'3c'2fol'5cb = compileRegex True "</ol\\b"
regex_'3c'2fdl'5cb = compileRegex True "</dl\\b"
regex_'3c'2farticle'5cb = compileRegex True "</article\\b"
regex_'3c'2faside'5cb = compileRegex True "</aside\\b"
regex_'3c'2fdetails'5cb = compileRegex True "</details\\b"
regex_'3c'2ffigure'5cb = compileRegex True "</figure\\b"
regex_'3c'2ffooter'5cb = compileRegex True "</footer\\b"
regex_'3c'2fheader'5cb = compileRegex True "</header\\b"
regex_'3c'2fmain'5cb = compileRegex True "</main\\b"
regex_'3c'2fnav'5cb = compileRegex True "</nav\\b"
regex_'3c'2fsection'5cb = compileRegex True "</section\\b"
regex_'3c'2f'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "</[A-Za-z_:][\\w.:_-]*"
regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b = compileRegex True "&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z_:][\\w.:_-]*);"
regex_'25'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'3b = compileRegex True "%[A-Za-z_:][\\w.:_-]*;"
regex_'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "[A-Za-z_:][\\w.:_-]*"
regex_'5cs'2b'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "\\s+[A-Za-z_:][\\w.:_-]*"
regex_'3c'21'28ELEMENT'7cENTITY'7cATTLIST'7cNOTATION'29'5cb = compileRegex True "<!(ELEMENT|ENTITY|ATTLIST|NOTATION)\\b"
regex_'2d'28'2d'28'3f'21'2d'3e'29'29'2b = compileRegex True "-(-(?!->))+"
regex_'5cS = compileRegex True "\\S"
regex_'3c'2fstyle'5cb = compileRegex True "</style\\b"
regex_'3c'2fscript'5cb = compileRegex True "</script\\b"
regex_'2f'2f'28'3f'3d'2e'2a'3c'2fscript'5cb'29 = compileRegex True "//(?=.*</script\\b)"
regex_'2f'28'3f'21'3e'29 = compileRegex True "/(?!>)"
regex_'5b'5e'2f'3e'3c'22'27'5cs'5d = compileRegex True "[^/><\"'\\s]"
parseRules ("HTML","Start") =
(((parseRules ("HTML","FindHTML")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Start")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","FindHTML") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pDetectIdentifier >>= withAttribute NormalTok))
<|>
((pString False "<!--" >>= withAttribute CommentTok) >>~ pushContext ("HTML","Comment"))
<|>
((pString False "<![CDATA[" >>= withAttribute BaseNTok) >>~ pushContext ("HTML","CDATA"))
<|>
((pRegExpr regex_'3c'21DOCTYPE'5cs'2b >>= withAttribute DataTypeTok) >>~ pushContext ("HTML","Doctype"))
<|>
((pRegExpr regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("HTML","PI"))
<|>
((pRegExpr regex_'3cstyle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","CSS"))
<|>
((pRegExpr regex_'3cscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","JS"))
<|>
((pRegExpr regex_'3cpre'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cdiv'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3ctable'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cul'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3col'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cdl'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3carticle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3caside'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cdetails'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cfigure'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cfooter'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cheader'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cmain'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3cnav'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3csection'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Open"))
<|>
((pRegExpr regex_'3c'2fpre'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fdiv'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2ftable'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2ful'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fol'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fdl'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2farticle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2faside'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fdetails'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2ffigure'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2ffooter'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fheader'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fmain'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fnav'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2fsection'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((pRegExpr regex_'3c'2f'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close"))
<|>
((parseRules ("HTML","FindDTDRules")))
<|>
((parseRules ("HTML","FindEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","FindHTML")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","FindEntityRefs") =
(((pRegExpr regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b >>= withAttribute DecValTok))
<|>
((pAnyChar "&<" >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","FindEntityRefs")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","FindPEntityRefs") =
(((pRegExpr regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b >>= withAttribute DecValTok))
<|>
((pRegExpr regex_'25'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'3b >>= withAttribute DecValTok))
<|>
((pAnyChar "&%" >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","FindPEntityRefs")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","FindAttributes") =
(((pColumn 0 >> pRegExpr regex_'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute OtherTok))
<|>
((pRegExpr regex_'5cs'2b'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute OtherTok))
<|>
((pDetectChar False '=' >>= withAttribute OtherTok) >>~ pushContext ("HTML","Value"))
<|>
(currentContext >>= \x -> guard (x == ("HTML","FindAttributes")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","FindDTDRules") =
(((pRegExpr regex_'3c'21'28ELEMENT'7cENTITY'7cATTLIST'7cNOTATION'29'5cb >>= withAttribute DataTypeTok) >>~ pushContext ("HTML","Doctype Markupdecl"))
<|>
(currentContext >>= \x -> guard (x == ("HTML","FindDTDRules")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","Comment") =
(((pDetectSpaces >>= withAttribute CommentTok))
<|>
((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd)))
<|>
((pDetectIdentifier >>= withAttribute CommentTok))
<|>
((pString False "-->" >>= withAttribute CommentTok) >>~ (popContext))
<|>
((pRegExpr regex_'2d'28'2d'28'3f'21'2d'3e'29'29'2b >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Comment")) >> pDefault >>= withAttribute CommentTok))
parseRules ("HTML","CDATA") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pDetectIdentifier >>= withAttribute NormalTok))
<|>
((pString False "]]>" >>= withAttribute BaseNTok) >>~ (popContext))
<|>
((pString False "]]>" >>= withAttribute DecValTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","CDATA")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","PI") =
(((pDetect2Chars False '?' '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("HTML","PI")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","Doctype") =
(((pDetectChar False '>' >>= withAttribute DataTypeTok) >>~ (popContext))
<|>
((pDetectChar False '[' >>= withAttribute DataTypeTok) >>~ pushContext ("HTML","Doctype Internal Subset"))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Doctype")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","Doctype Internal Subset") =
(((pDetectChar False ']' >>= withAttribute DataTypeTok) >>~ (popContext))
<|>
((parseRules ("HTML","FindDTDRules")))
<|>
((pString False "<!--" >>= withAttribute CommentTok) >>~ pushContext ("HTML","Comment"))
<|>
((pRegExpr regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("HTML","PI"))
<|>
((parseRules ("HTML","FindPEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Doctype Internal Subset")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","Doctype Markupdecl") =
(((pDetectChar False '>' >>= withAttribute DataTypeTok) >>~ (popContext))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("HTML","Doctype Markupdecl DQ"))
<|>
((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("HTML","Doctype Markupdecl SQ"))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Doctype Markupdecl")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","Doctype Markupdecl DQ") =
(((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
((parseRules ("HTML","FindPEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Doctype Markupdecl DQ")) >> pDefault >>= withAttribute StringTok))
parseRules ("HTML","Doctype Markupdecl SQ") =
(((pDetectChar False '\'' >>= withAttribute StringTok) >>~ (popContext))
<|>
((parseRules ("HTML","FindPEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Doctype Markupdecl SQ")) >> pDefault >>= withAttribute StringTok))
parseRules ("HTML","El Open") =
(((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((parseRules ("HTML","FindAttributes")))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","El Open")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","El Close") =
(((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","El Close")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","El Close 2") =
(((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext >> popContext >> popContext))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","El Close 2")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","El Close 3") =
(((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext >> popContext >> popContext >> popContext))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","El Close 3")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","CSS") =
(((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ pushContext ("HTML","CSS content"))
<|>
((parseRules ("HTML","FindAttributes")))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","CSS")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","CSS content") =
(((pRegExpr regex_'3c'2fstyle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close 2"))
<|>
((Text.Highlighting.Kate.Syntax.Css.parseExpression (Just ("CSS",""))))
<|>
(currentContext >>= \x -> guard (x == ("HTML","CSS content")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","JS") =
(((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext))
<|>
((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ pushContext ("HTML","JS content"))
<|>
((parseRules ("HTML","FindAttributes")))
<|>
((pRegExpr regex_'5cS >>= withAttribute ErrorTok))
<|>
(currentContext >>= \x -> guard (x == ("HTML","JS")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","JS content") =
(((pRegExpr regex_'3c'2fscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close 2"))
<|>
((pRegExpr regex_'2f'2f'28'3f'3d'2e'2a'3c'2fscript'5cb'29 >>= withAttribute CommentTok) >>~ pushContext ("HTML","JS comment close"))
<|>
((Text.Highlighting.Kate.Syntax.Javascript.parseExpression (Just ("JavaScript","Normal"))))
<|>
(currentContext >>= \x -> guard (x == ("HTML","JS content")) >> pDefault >>= withAttribute NormalTok))
parseRules ("HTML","JS comment close") =
(((pRegExpr regex_'3c'2fscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("HTML","El Close 3"))
<|>
((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd)))
<|>
(currentContext >>= \x -> guard (x == ("HTML","JS comment close")) >> pDefault >>= withAttribute CommentTok))
parseRules ("HTML","Value") =
(((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("HTML","Value DQ"))
<|>
((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("HTML","Value SQ"))
<|>
((pDetectSpaces >>= withAttribute NormalTok))
<|>
(pushContext ("HTML","Value NQ") >> currentContext >>= parseRules))
parseRules ("HTML","Value NQ") =
(((parseRules ("HTML","FindEntityRefs")))
<|>
((pRegExpr regex_'2f'28'3f'21'3e'29 >>= withAttribute StringTok))
<|>
((pRegExpr regex_'5b'5e'2f'3e'3c'22'27'5cs'5d >>= withAttribute StringTok))
<|>
((popContext >> popContext) >> currentContext >>= parseRules))
parseRules ("HTML","Value DQ") =
(((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext >> popContext))
<|>
((parseRules ("HTML","FindEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Value DQ")) >> pDefault >>= withAttribute StringTok))
parseRules ("HTML","Value SQ") =
(((pDetectChar False '\'' >>= withAttribute StringTok) >>~ (popContext >> popContext))
<|>
((parseRules ("HTML","FindEntityRefs")))
<|>
(currentContext >>= \x -> guard (x == ("HTML","Value SQ")) >> pDefault >>= withAttribute StringTok))
parseRules ("Alerts", _) = Text.Highlighting.Kate.Syntax.Alert.parseExpression Nothing
parseRules ("CSS", _) = Text.Highlighting.Kate.Syntax.Css.parseExpression Nothing
parseRules ("JavaScript", _) = Text.Highlighting.Kate.Syntax.Javascript.parseExpression Nothing
parseRules x = parseRules ("HTML","Start") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Html.hs | gpl-2.0 | 21,010 | 0 | 51 | 3,105 | 6,258 | 3,336 | 2,922 | 398 | 30 |
---------------------------------------------------------
--
-- Module : LoanCalendars
-- Copyright : Bartosz Wójcik (2007)
-- License : Private
--
-- Maintainer : bartek@sudety.it
-- Stability : Unstable
-- Portability : portable
--
-- Bank calendar of ELCA.
---------------------------------------------------------
module LoanCalendars
where
--import System.Time
data Month
= January | February | March | April
| May | June | July | August
| September | October | November | December
deriving (Eq, Ord, Enum, Bounded, Read, Show)
-- ---------------------------------
-- Own date type
-- ---------------------------------
data LoanCalendar = LoanCalendar {
lcYear :: Int,
lcMonth :: Month,
lcDay :: Int
}
deriving (Eq, Ord)
data CalendarType = Y360 -- year has 360 days, each month 30 days (SICLID version, where diff 15.05 31.01 = 14 [not 15 as expected!])
| RealCalendar -- each month has real number of days
deriving (Eq, Ord, Show, Read)
-- Day is in range [0..30] where 0 means "not set" but also "last day of previous month"
-- m <- [1..12] whilst Month is in range from Time module
-- Year is range [0..]
setLC :: Int -> Int -> Int -> LoanCalendar
setLC y m d = LoanCalendar {lcYear = y + ((m+(d `div` 31)-1) `div` 12),
lcMonth = toEnum ((m+(d `div` 31)-1) `mod` 12),
lcDay = d `mod` 31
}
instance Show LoanCalendar where
show lc = show (lcYear lc) ++ "-" ++ show (lcMonth lc) ++ "-" ++ show (lcDay lc)
diffLoanCalendar :: LoanCalendar -> LoanCalendar -> CalendarType -> Int
diffLoanCalendar d1 d2 Y360 = 360 * (lcYear d1 - lcYear d2) +
30 * (fromEnum (lcMonth d1) - fromEnum (lcMonth d2)) +
lcDay d1 - lcDay d2
diffLoanCalendar d1 d2 cal = error $ "Calendar " ++ show cal ++ " is not yet defined"
addYearLC lc y = setLC (lcYear lc + y) ((fromEnum . lcMonth) lc + 1) (lcDay lc)
addMonthLC lc m = setLC (lcYear lc) ((fromEnum . lcMonth) lc + m + 1) (lcDay lc)
addDayLC lc d = setLC (lcYear lc) ((fromEnum . lcMonth) lc + 1) (lcDay lc + d)
| bartoszw/elca | LoanCalendars.hs | gpl-2.0 | 2,480 | 0 | 14 | 873 | 608 | 335 | 273 | 28 | 1 |
{-
Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
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 Config where
import Data.List
import Types
startingAddresses :: [GAddress]
startingAddresses =
[GAddress {host="home.jumpjet.info",port= 70,dtype= '1',path= "1/Gopher_Jewels_2"}]
excludeServers = [] --["gopher.quux.org", "quux.org"]
baseDir = "/home/jgoerzen/tree/gopher-arch"
numThreads = 15
| jgoerzen/gopherbot | Config.hs | gpl-2.0 | 1,050 | 0 | 7 | 166 | 73 | 47 | 26 | 9 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
------------------------------------------------------------------------
-- |
-- Module : Text.Pandoc.Definition.Lens
-- Copyright : (C) 2015 Christopher Chalmers
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Christopher Chalmers <c.chalmers@me.com>
-- Stability : experimental
-- Portability : non-portable
--
-- 'Prism's, 'Lens'es and 'Traversal's for and orphan instances 'Pandoc'
-- types.
------------------------------------------------------------------------
module Text.Pandoc.Definition.Lens
( -- $orphans
-- * Documents
body
, meta
-- * Generics traversals
-- | These traversals are simply 'template'.
, attributes
, inlines
, blocks
, citations
, formats
, targets
-- * Block prisms
, _Plain
, _Para
, _CodeBlock
, _RawBlock
, _BlockQuote
, _OrderedList
, _BulletList
, _DefinitionList
, _Header
, _HorizontalRule
, _Table
, _Div
, _Null
-- ** Inline prisms
, _Str
, _Emph
, _Strong
, _Strikeout
, _Superscript
, _Subscript
, _SmallCaps
, _Quoted
, _Cite
, _Code
, _Space
, _LineBreak
, _Math
, _RawInline
, _Link
, _Image
, _Note
, _Span
-- ** Meta prisms
, _MetaMap
, _MetaList
, _MetaBool
, _MetaString
, _MetaInlines
, _MetaBlocks
-- ** Citation lenses
, citeId
, citePrefix
, citeSuffix
, citeMode
, citeNoteNum
, citeHash
, module Text.Pandoc.Definition
) where
import Control.Applicative
import Control.Lens
import Data.Data (Data)
import Data.Data.Lens
import Data.Semigroup
import Text.Pandoc.Builder
import Text.Pandoc.Definition
-- | The 'Block's of a 'Pandoc'.
body :: Lens' Pandoc [Block]
body f (Pandoc m bs) = f bs <&> \bs' -> Pandoc m bs'
{-# INLINE body #-}
-- | The 'Meta' of a 'Pandoc'.
meta :: Lens' Pandoc Meta
meta f (Pandoc m bs) = f m <&> \m' -> Pandoc m' bs
{-# INLINE meta #-}
-- Generics
-- | Traversal over all 'Attr's of a structure (usually 'Pandoc',
-- 'Block' or 'Inline').
attributes :: Data a => Traversal' a Attr
attributes = template
-- | Traversal over all 'Block's of a structure that are not contained
-- in another 'Block'. (usually @a@ is 'Pandoc', 'Block' or 'Inline').
blocks :: Data a => Traversal' a Block
blocks = template
-- | Traversal over all 'Inline's of a structure that are not contained
-- in another 'Inline'. (usually @a@ is 'Pandoc', 'Block' or 'Inline').
inlines :: Data a => Traversal' a Inline
inlines = template
-- | Traversal over all 'Citation's of a structure (usually @a@ is 'Pandoc',
-- 'Block' or 'Inline').
citations :: Data a => Traversal' a Citation
citations = template
-- | Traversal over all 'Target's of a structure (usually @a@ is 'Pandoc',
-- 'Block' or 'Inline').
targets :: Data a => Traversal' a Target
targets = template
-- | Traversal over all 'Format's of a structure (usually @a@ is 'Pandoc',
-- 'Block' or 'Inline').
formats :: Data a => Traversal' a Format
formats = template
-- Template haskell
makeWrapped ''Meta
makeWrapped ''Format
makeWrapped ''Many
makePrisms ''Block
makePrisms ''Inline
makePrisms ''MetaValue
makeLensesFor
[ ("citationId" , "citeId")
, ("citationPrefix" , "citePrefix")
, ("citationSuffix" , "citeSuffix")
, ("citationMode" , "citeMode")
, ("citationNoteNum", "citeNoteNum")
, ("citationHash" , "citeHash")
] ''Citation
-- $orphans
-- The following orphan instances are provided:
-- * 'Plated': 'Block', 'Inline'
-- * 'Wrapped': 'Meta', 'Format', 'Many'
-- * 'At' and 'Ixed': Meta
-- * 'Semigroup': 'Pandoc', 'Meta', 'Inlines', 'Blocks'
-- * 'Each': 'Meta', 'Many'
instance Plated Inline
instance Plated Block
type instance IxValue Meta = MetaValue
type instance Index Meta = String
instance Ixed Meta where
ix = ixAt
instance At Meta where
at i = _Wrapped . at i
instance Each Meta Meta MetaValue MetaValue where
each = _Wrapped . each
instance Each (Many a) (Many b) a b where
each = _Wrapped . each
instance Semigroup Meta
instance Semigroup Pandoc
-- not sure why Pandoc doesn't have Monoid (Many a) instance
instance Semigroup (Many Inline)
instance Semigroup (Many Block)
-- Potential 'Many' instances: Snoc Cons Ixed
class HasAttr a where
-- | Traversal over the top level attributes of an object.
attr :: Traversal' a Attr
instance HasAttr Block where
attr f (CodeBlock a s) = f a <&> \a' -> CodeBlock a' s
attr f (Header n a s) = f a <&> \a' -> Header n a' s
attr f (Div a s) = f a <&> \a' -> Div a' s
attr _ x = pure x
instance HasAttr Inline where
attr f (Code a s) = f a <&> \a' -> Code a' s
attr f (Span a s) = f a <&> \a' -> Span a' s
attr _ x = pure x
-- attrKeysAt :: String -> Lens Attr String
-- attrKeysAt s = _3 . _Unwrapping M.fromList . at s
-- attrKeysIx :: String -> Traversal' Attr String
-- attrKeysIx s = _3 . _Unwrapping M.fromList . ix s
| cchalmers/pandoc-types-lens | src/Text/Pandoc/Definition/Lens.hs | gpl-3.0 | 5,128 | 0 | 8 | 1,115 | 1,016 | 569 | 447 | 126 | 1 |
module Util.HttpTester where
import Snap.Http.Server.Config
import Test.HUnit
import Control.Concurrent(forkIO, threadDelay, killThread)
import qualified Util.HttpClient as HTTP
import Text.Regex.XMLSchema.String(match)
import Control.Exception(finally)
import Util.RegexEscape(escape)
import Util.TestWrapper
data ExpectedResult = Matching String | Exactly String | ReturnCode Int | All [ExpectedResult]
post desc root path request expected =
httpTest desc (HTTP.post (root ++ path) request) expected
get desc root path expected =
httpTest desc (HTTP.get (root ++ path)) expected
httpTest :: String -> IO (Int, String) -> ExpectedResult -> Test
httpTest desc request expected = TestLabel desc $ TestCase $ do
(code, body) <- request
verify (code, body) expected
where
verify (code, body) expected = case expected of
Matching pattern -> assertBool desc (match pattern (body))
Exactly str -> assertEqual desc str body
ReturnCode c -> assertEqual desc c code
All checks -> mapM_ (verify (code, body)) checks
withForkedServer :: IO() -> Wrapper
withForkedServer server task = do
serverThread <- forkIO server
threadDelay $ toMicros 1000
task `finally` (killThread serverThread)
toMicros = (*1000)
| raimohanska/rump | src/Util/HttpTester.hs | gpl-3.0 | 1,268 | 0 | 13 | 234 | 431 | 229 | 202 | 29 | 4 |
<?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">
<!-- title -->
<title>Logisim - Help</title>
<!-- maps -->
<maps>
<homeID>top</homeID>
<mapref location="map_pt.jhm" />
</maps>
<!-- views -->
<view xml:lang="pt" mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Table Of Contents</label>
<type>javax.help.TOCView</type>
<data>pt/contents.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">search_lookup_pt</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
<!-- presentation windows -->
<!-- This window is the default one for the helpset.
* It is a tri-paned window because displayviews, not
* defined, defaults to true and because a toolbar is defined.
* The toolbar has a back arrow, a forward arrow, and
* a home button that has a user-defined image.
-->
<presentation default=true>
<name>main window</name>
<size width="900" height="700" />
<location x="200" y="10" />
<toolbar>
<helpaction>javax.help.BackAction</helpaction>
<helpaction>javax.help.ForwardAction</helpaction>
<helpaction image="homeicon">javax.help.HomeAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.FavoritesAction</helpaction>
</toolbar>
</presentation>
<!-- implementation section -->
<impl>
<helpsetregistry helpbrokerclass="javax.help.DefaultHelpBroker" />
<viewerregistry viewertype="text/html"
viewerclass="com.sun.java.help.impl.CustomKit" />
<viewerregistry viewertype="text/xml"
viewerclass="com.sun.java.help.impl.CustomXMLKit" />
</impl>
</helpset>
| LogisimIt/Logisim | Logisim-Fork/doc/doc_pt.hs | gpl-3.0 | 2,125 | 146 | 27 | 441 | 589 | 334 | 255 | -1 | -1 |
{-#LANGUAGE BangPatterns #-}
{-
Enumerate all closed Knight's Tours in an
arbitrarity sized chessboard. Multi-threaded version.
Usage:
KnightTours m n +RTS -N
Compile with:
ghc -O3 -threaded -rtsopts -fllvm --make KnightTours
Examples:
A small example is the 3x12 board
Author: Jyotirmoy Bhattacharya (jyotirmoy@jyotirmoy.net)
This program has been put into the public domain
by the author.
-}
module Main (main) where
import Control.Parallel.Strategies
import Control.Parallel
import Data.Char (chr,ord)
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Control.Monad
import System.Environment (getArgs)
main::IO ()
main = do
[p,q] <- (map read) <$> getArgs
unless (p>0 && q>0) $ error "Invalid arguments"
let chessG = mkChessGraph p q
let cycles = enumHamCycle chessG
n <- countAndPrint 0 chessG cycles
putStrLn $ "Total cycles = "++(show n)
where
countAndPrint::Int->Graph->[[Int]]->IO Int
countAndPrint !accum g [] = return accum
countAndPrint !accum g (c:cs) = do
putStrLn $ prettyPath g c
countAndPrint (accum+1) g cs
data Graph = Graph{
gNVerts::Int,
gNames::M.Map Int String,
gNeighs::M.Map Int [Int]
} deriving Show
-- Enumerate all Hamiltonian cycles in the given graph
enumHamCycle::Graph->[[Int]]
enumHamCycle g
= completeHamCycle g 1 (n - 1)
[0] (S.singleton 0)
where
n = gNVerts g
-- Try to complete a path into a Hamiltonian cycle
-- (parallel version)
completeHamCycle::Graph->Int->Int
->[Int]->(S.Set Int)
->[[Int]]
completeHamCycle g !depth !remain !path !visited
| remain == 0 =
if 0 `elem` choices then [path] else []
| otherwise =
concat $ withStrategy (evalList strat)
[completeHamCycle g (depth+1) (remain-1)
(c:path)
(c `S.insert` visited)
| c <- choices,
c `S.notMember` visited
]
where
last = head path
choices = (gNeighs g) M.! last
strat = if depth>6 then rseq else rpar
-- Make the graph corresponding to
-- a knight's moves on a mxn chessboard
mkChessGraph::Int->Int->Graph
mkChessGraph m n
= Graph {gNVerts = nv,
gNames = M.fromList [(k,genName k)|k<-[0..nv-1]],
gNeighs = M.fromList [(k,genNeighs k)|k<-[0..nv-1]]
}
where
nv = m*n
deidx k = k `divMod` n
idx i j = i*n+j
genName k = let (i,j) = deidx k in
chr (ord 'A'+i):(show j)
genNeighs k = let (i,j) = deidx k in
[idx p q|
(x,y)<-[(1,2),(1,-2),(-1,2),(-1,-2),
(2,1),(2,-1),(-2,1),(-2,-1)],
let p = i+x,
let q = j+y,
p>=0 && p<m && q>=0 && q<n]
-- Pretty print path in a graph
prettyPath::Graph->[Int]->String
prettyPath g = concat . map ((gNames g) M.!)
| jmoy/knights_tours | slowHaskell/KnightTours.hs | gpl-3.0 | 2,861 | 0 | 17 | 773 | 1,073 | 578 | 495 | 67 | 3 |
-- generate balanced trees
-- with n nodes
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq)
p55 :: Int -> [Tree Char]
p55 0 = [Empty]
p55 n = let (q,r) = quotRem (n-1) 2
in [ (Branch 'x' l r) | i <- [q..q+r],
l <- p55 i,
r <- p55 (n-i-1) ]
| yalpul/CENG242 | H99/54-60/p55.hs | gpl-3.0 | 334 | 3 | 13 | 135 | 177 | 88 | 89 | 7 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a forwarding address. If ownership verification is required, a
-- message will be sent to the recipient and the resource\'s verification
-- status will be set to pending; otherwise, the resource will be created
-- with verification status set to accepted.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.forwardingAddresses.create@.
module Network.Google.Resource.Gmail.Users.Settings.ForwardingAddresses.Create
(
-- * REST Resource
UsersSettingsForwardingAddressesCreateResource
-- * Creating a Request
, usersSettingsForwardingAddressesCreate
, UsersSettingsForwardingAddressesCreate
-- * Request Lenses
, usfacPayload
, usfacUserId
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.settings.forwardingAddresses.create@ method which the
-- 'UsersSettingsForwardingAddressesCreate' request conforms to.
type UsersSettingsForwardingAddressesCreateResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"settings" :>
"forwardingAddresses" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ForwardingAddress :>
Post '[JSON] ForwardingAddress
-- | Creates a forwarding address. If ownership verification is required, a
-- message will be sent to the recipient and the resource\'s verification
-- status will be set to pending; otherwise, the resource will be created
-- with verification status set to accepted.
--
-- /See:/ 'usersSettingsForwardingAddressesCreate' smart constructor.
data UsersSettingsForwardingAddressesCreate = UsersSettingsForwardingAddressesCreate'
{ _usfacPayload :: !ForwardingAddress
, _usfacUserId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersSettingsForwardingAddressesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usfacPayload'
--
-- * 'usfacUserId'
usersSettingsForwardingAddressesCreate
:: ForwardingAddress -- ^ 'usfacPayload'
-> UsersSettingsForwardingAddressesCreate
usersSettingsForwardingAddressesCreate pUsfacPayload_ =
UsersSettingsForwardingAddressesCreate'
{ _usfacPayload = pUsfacPayload_
, _usfacUserId = "me"
}
-- | Multipart request metadata.
usfacPayload :: Lens' UsersSettingsForwardingAddressesCreate ForwardingAddress
usfacPayload
= lens _usfacPayload (\ s a -> s{_usfacPayload = a})
-- | User\'s email address. The special value \"me\" can be used to indicate
-- the authenticated user.
usfacUserId :: Lens' UsersSettingsForwardingAddressesCreate Text
usfacUserId
= lens _usfacUserId (\ s a -> s{_usfacUserId = a})
instance GoogleRequest
UsersSettingsForwardingAddressesCreate where
type Rs UsersSettingsForwardingAddressesCreate =
ForwardingAddress
type Scopes UsersSettingsForwardingAddressesCreate =
'["https://www.googleapis.com/auth/gmail.settings.sharing"]
requestClient
UsersSettingsForwardingAddressesCreate'{..}
= go _usfacUserId (Just AltJSON) _usfacPayload
gmailService
where go
= buildClient
(Proxy ::
Proxy UsersSettingsForwardingAddressesCreateResource)
mempty
| rueshyna/gogol | gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/ForwardingAddresses/Create.hs | mpl-2.0 | 4,299 | 0 | 15 | 897 | 392 | 239 | 153 | 67 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Games.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Games.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Collection of players being retrieved
data PlayersListCollection
= PlayedWith
-- ^ @played_with@
-- Retrieve a list of players you have played a multiplayer game (realtime
-- or turn-based) with recently.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayersListCollection
instance FromHttpApiData PlayersListCollection where
parseQueryParam = \case
"played_with" -> Right PlayedWith
x -> Left ("Unable to parse PlayersListCollection from: " <> x)
instance ToHttpApiData PlayersListCollection where
toQueryParam = \case
PlayedWith -> "played_with"
instance FromJSON PlayersListCollection where
parseJSON = parseJSONText "PlayersListCollection"
instance ToJSON PlayersListCollection where
toJSON = toJSONText
-- | The time span of this high score.
data LeaderboardEntryTimeSpan
= ScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| AllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| Weekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| Daily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LeaderboardEntryTimeSpan
instance FromHttpApiData LeaderboardEntryTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right ScoreTimeSpanUnspecified
"ALL_TIME" -> Right AllTime
"WEEKLY" -> Right Weekly
"DAILY" -> Right Daily
x -> Left ("Unable to parse LeaderboardEntryTimeSpan from: " <> x)
instance ToHttpApiData LeaderboardEntryTimeSpan where
toQueryParam = \case
ScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
AllTime -> "ALL_TIME"
Weekly -> "WEEKLY"
Daily -> "DAILY"
instance FromJSON LeaderboardEntryTimeSpan where
parseJSON = parseJSONText "LeaderboardEntryTimeSpan"
instance ToJSON LeaderboardEntryTimeSpan where
toJSON = toJSONText
-- | The cause for the update failure.
data EventBatchRecordFailureFailureCause
= EventFailureCauseUnspecified
-- ^ @EVENT_FAILURE_CAUSE_UNSPECIFIED@
-- Default value. Should not be used.
| TooLarge
-- ^ @TOO_LARGE@
-- A batch request was issued with more events than are allowed in a single
-- batch.
| TimePeriodExpired
-- ^ @TIME_PERIOD_EXPIRED@
-- A batch was sent with data too far in the past to record.
| TimePeriodShort
-- ^ @TIME_PERIOD_SHORT@
-- A batch was sent with a time range that was too short.
| TimePeriodLong
-- ^ @TIME_PERIOD_LONG@
-- A batch was sent with a time range that was too long.
| AlreadyUpdated
-- ^ @ALREADY_UPDATED@
-- An attempt was made to record a batch of data which was already seen.
| RecordRateHigh
-- ^ @RECORD_RATE_HIGH@
-- An attempt was made to record data faster than the server will apply
-- updates.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EventBatchRecordFailureFailureCause
instance FromHttpApiData EventBatchRecordFailureFailureCause where
parseQueryParam = \case
"EVENT_FAILURE_CAUSE_UNSPECIFIED" -> Right EventFailureCauseUnspecified
"TOO_LARGE" -> Right TooLarge
"TIME_PERIOD_EXPIRED" -> Right TimePeriodExpired
"TIME_PERIOD_SHORT" -> Right TimePeriodShort
"TIME_PERIOD_LONG" -> Right TimePeriodLong
"ALREADY_UPDATED" -> Right AlreadyUpdated
"RECORD_RATE_HIGH" -> Right RecordRateHigh
x -> Left ("Unable to parse EventBatchRecordFailureFailureCause from: " <> x)
instance ToHttpApiData EventBatchRecordFailureFailureCause where
toQueryParam = \case
EventFailureCauseUnspecified -> "EVENT_FAILURE_CAUSE_UNSPECIFIED"
TooLarge -> "TOO_LARGE"
TimePeriodExpired -> "TIME_PERIOD_EXPIRED"
TimePeriodShort -> "TIME_PERIOD_SHORT"
TimePeriodLong -> "TIME_PERIOD_LONG"
AlreadyUpdated -> "ALREADY_UPDATED"
RecordRateHigh -> "RECORD_RATE_HIGH"
instance FromJSON EventBatchRecordFailureFailureCause where
parseJSON = parseJSONText "EventBatchRecordFailureFailureCause"
instance ToJSON EventBatchRecordFailureFailureCause where
toJSON = toJSONText
-- | The collection of scores you\'re requesting.
data ScoresListCollection
= ScoreCollectionUnspecified
-- ^ @SCORE_COLLECTION_UNSPECIFIED@
-- Default value. This value is unused.
| Public
-- ^ @PUBLIC@
-- List all scores in the public leaderboard.
| Social
-- ^ @SOCIAL@
-- (Obsolete) Legacy G+ social scores.
| Friends
-- ^ @FRIENDS@
-- List only scores of friends.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresListCollection
instance FromHttpApiData ScoresListCollection where
parseQueryParam = \case
"SCORE_COLLECTION_UNSPECIFIED" -> Right ScoreCollectionUnspecified
"PUBLIC" -> Right Public
"SOCIAL" -> Right Social
"FRIENDS" -> Right Friends
x -> Left ("Unable to parse ScoresListCollection from: " <> x)
instance ToHttpApiData ScoresListCollection where
toQueryParam = \case
ScoreCollectionUnspecified -> "SCORE_COLLECTION_UNSPECIFIED"
Public -> "PUBLIC"
Social -> "SOCIAL"
Friends -> "FRIENDS"
instance FromJSON ScoresListCollection where
parseJSON = parseJSONText "ScoresListCollection"
instance ToJSON ScoresListCollection where
toJSON = toJSONText
-- | Type of endpoint being requested.
data ApplicationsGetEndPointEndPointType
= AGEPEPTEndPointTypeUnspecified
-- ^ @END_POINT_TYPE_UNSPECIFIED@
-- Default value. This value is unused.
| AGEPEPTProFileCreation
-- ^ @PROFILE_CREATION@
-- Request a URL to create a new profile.
| AGEPEPTProFileSettings
-- ^ @PROFILE_SETTINGS@
-- Request a URL for the Settings view.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ApplicationsGetEndPointEndPointType
instance FromHttpApiData ApplicationsGetEndPointEndPointType where
parseQueryParam = \case
"END_POINT_TYPE_UNSPECIFIED" -> Right AGEPEPTEndPointTypeUnspecified
"PROFILE_CREATION" -> Right AGEPEPTProFileCreation
"PROFILE_SETTINGS" -> Right AGEPEPTProFileSettings
x -> Left ("Unable to parse ApplicationsGetEndPointEndPointType from: " <> x)
instance ToHttpApiData ApplicationsGetEndPointEndPointType where
toQueryParam = \case
AGEPEPTEndPointTypeUnspecified -> "END_POINT_TYPE_UNSPECIFIED"
AGEPEPTProFileCreation -> "PROFILE_CREATION"
AGEPEPTProFileSettings -> "PROFILE_SETTINGS"
instance FromJSON ApplicationsGetEndPointEndPointType where
parseJSON = parseJSONText "ApplicationsGetEndPointEndPointType"
instance ToJSON ApplicationsGetEndPointEndPointType where
toJSON = toJSONText
-- | The time span for this player score.
data PlayerScoreTimeSpan
= PSTSScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| PSTSAllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| PSTSWeekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| PSTSDaily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayerScoreTimeSpan
instance FromHttpApiData PlayerScoreTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right PSTSScoreTimeSpanUnspecified
"ALL_TIME" -> Right PSTSAllTime
"WEEKLY" -> Right PSTSWeekly
"DAILY" -> Right PSTSDaily
x -> Left ("Unable to parse PlayerScoreTimeSpan from: " <> x)
instance ToHttpApiData PlayerScoreTimeSpan where
toQueryParam = \case
PSTSScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
PSTSAllTime -> "ALL_TIME"
PSTSWeekly -> "WEEKLY"
PSTSDaily -> "DAILY"
instance FromJSON PlayerScoreTimeSpan where
parseJSON = parseJSONText "PlayerScoreTimeSpan"
instance ToJSON PlayerScoreTimeSpan where
toJSON = toJSONText
data ApplicationEnabledFeaturesItem
= ApplicationFeatureUnspecified
-- ^ @APPLICATION_FEATURE_UNSPECIFIED@
-- Safe default, don\'t use.
| Snapshots
-- ^ @SNAPSHOTS@
-- Saved Games (snapshots).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ApplicationEnabledFeaturesItem
instance FromHttpApiData ApplicationEnabledFeaturesItem where
parseQueryParam = \case
"APPLICATION_FEATURE_UNSPECIFIED" -> Right ApplicationFeatureUnspecified
"SNAPSHOTS" -> Right Snapshots
x -> Left ("Unable to parse ApplicationEnabledFeaturesItem from: " <> x)
instance ToHttpApiData ApplicationEnabledFeaturesItem where
toQueryParam = \case
ApplicationFeatureUnspecified -> "APPLICATION_FEATURE_UNSPECIFIED"
Snapshots -> "SNAPSHOTS"
instance FromJSON ApplicationEnabledFeaturesItem where
parseJSON = parseJSONText "ApplicationEnabledFeaturesItem"
instance ToJSON ApplicationEnabledFeaturesItem where
toJSON = toJSONText
-- | Restrict application details returned to the specific platform.
data ApplicationsGetPlatformType
= PlatformTypeUnspecified
-- ^ @PLATFORM_TYPE_UNSPECIFIED@
-- Default value, don\'t use.
| Android
-- ^ @ANDROID@
-- Retrieve applications that can be played on Android.
| Ios
-- ^ @IOS@
-- Retrieve applications that can be played on iOS.
| WebApp
-- ^ @WEB_APP@
-- Retrieve applications that can be played on desktop web.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ApplicationsGetPlatformType
instance FromHttpApiData ApplicationsGetPlatformType where
parseQueryParam = \case
"PLATFORM_TYPE_UNSPECIFIED" -> Right PlatformTypeUnspecified
"ANDROID" -> Right Android
"IOS" -> Right Ios
"WEB_APP" -> Right WebApp
x -> Left ("Unable to parse ApplicationsGetPlatformType from: " <> x)
instance ToHttpApiData ApplicationsGetPlatformType where
toQueryParam = \case
PlatformTypeUnspecified -> "PLATFORM_TYPE_UNSPECIFIED"
Android -> "ANDROID"
Ios -> "IOS"
WebApp -> "WEB_APP"
instance FromJSON ApplicationsGetPlatformType where
parseJSON = parseJSONText "ApplicationsGetPlatformType"
instance ToJSON ApplicationsGetPlatformType where
toJSON = toJSONText
-- | The cause for the update failure.
data EventRecordFailureFailureCause
= EventUpdateFailureCauseUnspecified
-- ^ @EVENT_UPDATE_FAILURE_CAUSE_UNSPECIFIED@
-- Default value. Should not use.
| NotFound
-- ^ @NOT_FOUND@
-- An attempt was made to set an event that was not defined.
| InvalidUpdateValue
-- ^ @INVALID_UPDATE_VALUE@
-- An attempt was made to increment an event by a non-positive value.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EventRecordFailureFailureCause
instance FromHttpApiData EventRecordFailureFailureCause where
parseQueryParam = \case
"EVENT_UPDATE_FAILURE_CAUSE_UNSPECIFIED" -> Right EventUpdateFailureCauseUnspecified
"NOT_FOUND" -> Right NotFound
"INVALID_UPDATE_VALUE" -> Right InvalidUpdateValue
x -> Left ("Unable to parse EventRecordFailureFailureCause from: " <> x)
instance ToHttpApiData EventRecordFailureFailureCause where
toQueryParam = \case
EventUpdateFailureCauseUnspecified -> "EVENT_UPDATE_FAILURE_CAUSE_UNSPECIFIED"
NotFound -> "NOT_FOUND"
InvalidUpdateValue -> "INVALID_UPDATE_VALUE"
instance FromJSON EventRecordFailureFailureCause where
parseJSON = parseJSONText "EventRecordFailureFailureCause"
instance ToJSON EventRecordFailureFailureCause where
toJSON = toJSONText
-- | The time span of this score.
data PlayerLeaderboardScoreTimeSpan
= PLSTSScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| PLSTSAllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| PLSTSWeekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| PLSTSDaily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayerLeaderboardScoreTimeSpan
instance FromHttpApiData PlayerLeaderboardScoreTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right PLSTSScoreTimeSpanUnspecified
"ALL_TIME" -> Right PLSTSAllTime
"WEEKLY" -> Right PLSTSWeekly
"DAILY" -> Right PLSTSDaily
x -> Left ("Unable to parse PlayerLeaderboardScoreTimeSpan from: " <> x)
instance ToHttpApiData PlayerLeaderboardScoreTimeSpan where
toQueryParam = \case
PLSTSScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
PLSTSAllTime -> "ALL_TIME"
PLSTSWeekly -> "WEEKLY"
PLSTSDaily -> "DAILY"
instance FromJSON PlayerLeaderboardScoreTimeSpan where
parseJSON = parseJSONText "PlayerLeaderboardScoreTimeSpan"
instance ToJSON PlayerLeaderboardScoreTimeSpan where
toJSON = toJSONText
-- | The current state of the achievement for which a reveal was attempted.
-- This might be \`UNLOCKED\` if the achievement was already unlocked.
data AchievementRevealResponseCurrentState
= RevealAchievementStateUnspecified
-- ^ @REVEAL_ACHIEVEMENT_STATE_UNSPECIFIED@
-- Safe default, don\'t use.
| Revealed
-- ^ @REVEALED@
-- Achievement is revealed.
| Unlocked
-- ^ @UNLOCKED@
-- Achievement is unlocked.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementRevealResponseCurrentState
instance FromHttpApiData AchievementRevealResponseCurrentState where
parseQueryParam = \case
"REVEAL_ACHIEVEMENT_STATE_UNSPECIFIED" -> Right RevealAchievementStateUnspecified
"REVEALED" -> Right Revealed
"UNLOCKED" -> Right Unlocked
x -> Left ("Unable to parse AchievementRevealResponseCurrentState from: " <> x)
instance ToHttpApiData AchievementRevealResponseCurrentState where
toQueryParam = \case
RevealAchievementStateUnspecified -> "REVEAL_ACHIEVEMENT_STATE_UNSPECIFIED"
Revealed -> "REVEALED"
Unlocked -> "UNLOCKED"
instance FromJSON AchievementRevealResponseCurrentState where
parseJSON = parseJSONText "AchievementRevealResponseCurrentState"
instance ToJSON AchievementRevealResponseCurrentState where
toJSON = toJSONText
data ProFileSettingsFriendsListVisibility
= FriendsListVisibilityUnspecified
-- ^ @FRIENDS_LIST_VISIBILITY_UNSPECIFIED@
-- Unused.
| Visible
-- ^ @VISIBLE@
-- The friends list is currently visible to the game.
| RequestRequired
-- ^ @REQUEST_REQUIRED@
-- The developer does not have access to the friends list, but can call the
-- Android API to show a consent dialog.
| Unavailable
-- ^ @UNAVAILABLE@
-- The friends list is currently unavailable for this user, and it is not
-- possible to request access at this time, either because the user has
-- permanently declined or the friends feature is not available to them. In
-- this state, any attempts to request access to the friends list will be
-- unsuccessful.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProFileSettingsFriendsListVisibility
instance FromHttpApiData ProFileSettingsFriendsListVisibility where
parseQueryParam = \case
"FRIENDS_LIST_VISIBILITY_UNSPECIFIED" -> Right FriendsListVisibilityUnspecified
"VISIBLE" -> Right Visible
"REQUEST_REQUIRED" -> Right RequestRequired
"UNAVAILABLE" -> Right Unavailable
x -> Left ("Unable to parse ProFileSettingsFriendsListVisibility from: " <> x)
instance ToHttpApiData ProFileSettingsFriendsListVisibility where
toQueryParam = \case
FriendsListVisibilityUnspecified -> "FRIENDS_LIST_VISIBILITY_UNSPECIFIED"
Visible -> "VISIBLE"
RequestRequired -> "REQUEST_REQUIRED"
Unavailable -> "UNAVAILABLE"
instance FromJSON ProFileSettingsFriendsListVisibility where
parseJSON = parseJSONText "ProFileSettingsFriendsListVisibility"
instance ToJSON ProFileSettingsFriendsListVisibility where
toJSON = toJSONText
-- | The collection of scores you\'re requesting.
data ScoresListWindowCollection
= SLWCScoreCollectionUnspecified
-- ^ @SCORE_COLLECTION_UNSPECIFIED@
-- Default value. This value is unused.
| SLWCPublic
-- ^ @PUBLIC@
-- List all scores in the public leaderboard.
| SLWCSocial
-- ^ @SOCIAL@
-- (Obsolete) Legacy G+ social scores.
| SLWCFriends
-- ^ @FRIENDS@
-- List only scores of friends.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresListWindowCollection
instance FromHttpApiData ScoresListWindowCollection where
parseQueryParam = \case
"SCORE_COLLECTION_UNSPECIFIED" -> Right SLWCScoreCollectionUnspecified
"PUBLIC" -> Right SLWCPublic
"SOCIAL" -> Right SLWCSocial
"FRIENDS" -> Right SLWCFriends
x -> Left ("Unable to parse ScoresListWindowCollection from: " <> x)
instance ToHttpApiData ScoresListWindowCollection where
toQueryParam = \case
SLWCScoreCollectionUnspecified -> "SCORE_COLLECTION_UNSPECIFIED"
SLWCPublic -> "PUBLIC"
SLWCSocial -> "SOCIAL"
SLWCFriends -> "FRIENDS"
instance FromJSON ScoresListWindowCollection where
parseJSON = parseJSONText "ScoresListWindowCollection"
instance ToJSON ScoresListWindowCollection where
toJSON = toJSONText
-- | The type of update being applied.
data AchievementUpdateRequestUpdateType
= AchievementUpdateTypeUnspecified
-- ^ @ACHIEVEMENT_UPDATE_TYPE_UNSPECIFIED@
-- Safe default, don\'t use.
| Reveal
-- ^ @REVEAL@
-- Achievement is revealed.
| Unlock
-- ^ @UNLOCK@
-- Achievement is unlocked.
| Increment
-- ^ @INCREMENT@
-- Achievement is incremented.
| SetStepsAtLeast
-- ^ @SET_STEPS_AT_LEAST@
-- Achievement progress is set to at least the passed value.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementUpdateRequestUpdateType
instance FromHttpApiData AchievementUpdateRequestUpdateType where
parseQueryParam = \case
"ACHIEVEMENT_UPDATE_TYPE_UNSPECIFIED" -> Right AchievementUpdateTypeUnspecified
"REVEAL" -> Right Reveal
"UNLOCK" -> Right Unlock
"INCREMENT" -> Right Increment
"SET_STEPS_AT_LEAST" -> Right SetStepsAtLeast
x -> Left ("Unable to parse AchievementUpdateRequestUpdateType from: " <> x)
instance ToHttpApiData AchievementUpdateRequestUpdateType where
toQueryParam = \case
AchievementUpdateTypeUnspecified -> "ACHIEVEMENT_UPDATE_TYPE_UNSPECIFIED"
Reveal -> "REVEAL"
Unlock -> "UNLOCK"
Increment -> "INCREMENT"
SetStepsAtLeast -> "SET_STEPS_AT_LEAST"
instance FromJSON AchievementUpdateRequestUpdateType where
parseJSON = parseJSONText "AchievementUpdateRequestUpdateType"
instance ToJSON AchievementUpdateRequestUpdateType where
toJSON = toJSONText
-- | The result of the revision check.
data RevisionCheckResponseRevisionStatus
= RevisionStatusUnspecified
-- ^ @REVISION_STATUS_UNSPECIFIED@
-- Default value. This value is unused.
| OK
-- ^ @OK@
-- The revision being used is current.
| Deprecated
-- ^ @DEPRECATED@
-- There is currently a newer version available, but the revision being
-- used still works.
| Invalid
-- ^ @INVALID@
-- The revision being used is not supported in any released version.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RevisionCheckResponseRevisionStatus
instance FromHttpApiData RevisionCheckResponseRevisionStatus where
parseQueryParam = \case
"REVISION_STATUS_UNSPECIFIED" -> Right RevisionStatusUnspecified
"OK" -> Right OK
"DEPRECATED" -> Right Deprecated
"INVALID" -> Right Invalid
x -> Left ("Unable to parse RevisionCheckResponseRevisionStatus from: " <> x)
instance ToHttpApiData RevisionCheckResponseRevisionStatus where
toQueryParam = \case
RevisionStatusUnspecified -> "REVISION_STATUS_UNSPECIFIED"
OK -> "OK"
Deprecated -> "DEPRECATED"
Invalid -> "INVALID"
instance FromJSON RevisionCheckResponseRevisionStatus where
parseJSON = parseJSONText "RevisionCheckResponseRevisionStatus"
instance ToJSON RevisionCheckResponseRevisionStatus where
toJSON = toJSONText
-- | The type of this snapshot.
data SnapshotType
= SnapshotTypeUnspecified
-- ^ @SNAPSHOT_TYPE_UNSPECIFIED@
-- Default value. This value is unused.
| SaveGame
-- ^ @SAVE_GAME@
-- A snapshot representing a save game.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SnapshotType
instance FromHttpApiData SnapshotType where
parseQueryParam = \case
"SNAPSHOT_TYPE_UNSPECIFIED" -> Right SnapshotTypeUnspecified
"SAVE_GAME" -> Right SaveGame
x -> Left ("Unable to parse SnapshotType from: " <> x)
instance ToHttpApiData SnapshotType where
toQueryParam = \case
SnapshotTypeUnspecified -> "SNAPSHOT_TYPE_UNSPECIFIED"
SaveGame -> "SAVE_GAME"
instance FromJSON SnapshotType where
parseJSON = parseJSONText "SnapshotType"
instance ToJSON SnapshotType where
toJSON = toJSONText
-- | The time span for the scores and ranks you\'re requesting.
data ScoresListWindowTimeSpan
= SLWTSScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| SLWTSAllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| SLWTSWeekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| SLWTSDaily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresListWindowTimeSpan
instance FromHttpApiData ScoresListWindowTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right SLWTSScoreTimeSpanUnspecified
"ALL_TIME" -> Right SLWTSAllTime
"WEEKLY" -> Right SLWTSWeekly
"DAILY" -> Right SLWTSDaily
x -> Left ("Unable to parse ScoresListWindowTimeSpan from: " <> x)
instance ToHttpApiData ScoresListWindowTimeSpan where
toQueryParam = \case
SLWTSScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
SLWTSAllTime -> "ALL_TIME"
SLWTSWeekly -> "WEEKLY"
SLWTSDaily -> "DAILY"
instance FromJSON ScoresListWindowTimeSpan where
parseJSON = parseJSONText "ScoresListWindowTimeSpan"
instance ToJSON ScoresListWindowTimeSpan where
toJSON = toJSONText
-- | The state of the achievement.
data PlayerAchievementAchievementState
= PAASStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Default value. This value is unused.
| PAASHidden
-- ^ @HIDDEN@
-- Achievement is hidden.
| PAASRevealed
-- ^ @REVEALED@
-- Achievement is revealed.
| PAASUnlocked
-- ^ @UNLOCKED@
-- Achievement is unlocked.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayerAchievementAchievementState
instance FromHttpApiData PlayerAchievementAchievementState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right PAASStateUnspecified
"HIDDEN" -> Right PAASHidden
"REVEALED" -> Right PAASRevealed
"UNLOCKED" -> Right PAASUnlocked
x -> Left ("Unable to parse PlayerAchievementAchievementState from: " <> x)
instance ToHttpApiData PlayerAchievementAchievementState where
toQueryParam = \case
PAASStateUnspecified -> "STATE_UNSPECIFIED"
PAASHidden -> "HIDDEN"
PAASRevealed -> "REVEALED"
PAASUnlocked -> "UNLOCKED"
instance FromJSON PlayerAchievementAchievementState where
parseJSON = parseJSONText "PlayerAchievementAchievementState"
instance ToJSON PlayerAchievementAchievementState where
toJSON = toJSONText
-- | The time span for the scores and ranks you\'re requesting.
data ScoresGetTimeSpan
= SGTSScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| SGTSAll
-- ^ @ALL@
-- Get the high scores for all time spans. If this is used, maxResults
-- values will be ignored.
| SGTSAllTime
-- ^ @ALL_TIME@
-- Get the all time high score.
| SGTSWeekly
-- ^ @WEEKLY@
-- List the top scores for the current day.
| SGTSDaily
-- ^ @DAILY@
-- List the top scores for the current week.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresGetTimeSpan
instance FromHttpApiData ScoresGetTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right SGTSScoreTimeSpanUnspecified
"ALL" -> Right SGTSAll
"ALL_TIME" -> Right SGTSAllTime
"WEEKLY" -> Right SGTSWeekly
"DAILY" -> Right SGTSDaily
x -> Left ("Unable to parse ScoresGetTimeSpan from: " <> x)
instance ToHttpApiData ScoresGetTimeSpan where
toQueryParam = \case
SGTSScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
SGTSAll -> "ALL"
SGTSAllTime -> "ALL_TIME"
SGTSWeekly -> "WEEKLY"
SGTSDaily -> "DAILY"
instance FromJSON ScoresGetTimeSpan where
parseJSON = parseJSONText "ScoresGetTimeSpan"
instance ToJSON ScoresGetTimeSpan where
toJSON = toJSONText
-- | The visibility of event being tracked in this definition.
data EventDefinitionVisibility
= EDVEventVisibilityUnspecified
-- ^ @EVENT_VISIBILITY_UNSPECIFIED@
-- Default value. Should not be used.
| EDVRevealed
-- ^ @REVEALED@
-- This event should be visible to all users.
| EDVHidden
-- ^ @HIDDEN@
-- This event should only be shown to users that have recorded this event
-- at least once.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EventDefinitionVisibility
instance FromHttpApiData EventDefinitionVisibility where
parseQueryParam = \case
"EVENT_VISIBILITY_UNSPECIFIED" -> Right EDVEventVisibilityUnspecified
"REVEALED" -> Right EDVRevealed
"HIDDEN" -> Right EDVHidden
x -> Left ("Unable to parse EventDefinitionVisibility from: " <> x)
instance ToHttpApiData EventDefinitionVisibility where
toQueryParam = \case
EDVEventVisibilityUnspecified -> "EVENT_VISIBILITY_UNSPECIFIED"
EDVRevealed -> "REVEALED"
EDVHidden -> "HIDDEN"
instance FromJSON EventDefinitionVisibility where
parseJSON = parseJSONText "EventDefinitionVisibility"
instance ToJSON EventDefinitionVisibility where
toJSON = toJSONText
-- | How scores are ordered.
data LeaderboardOrder
= ScoreOrderUnspecified
-- ^ @SCORE_ORDER_UNSPECIFIED@
-- Default value. This value is unused.
| LargerIsBetter
-- ^ @LARGER_IS_BETTER@
-- Larger values are better; scores are sorted in descending order
| SmallerIsBetter
-- ^ @SMALLER_IS_BETTER@
-- Smaller values are better; scores are sorted in ascending order
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LeaderboardOrder
instance FromHttpApiData LeaderboardOrder where
parseQueryParam = \case
"SCORE_ORDER_UNSPECIFIED" -> Right ScoreOrderUnspecified
"LARGER_IS_BETTER" -> Right LargerIsBetter
"SMALLER_IS_BETTER" -> Right SmallerIsBetter
x -> Left ("Unable to parse LeaderboardOrder from: " <> x)
instance ToHttpApiData LeaderboardOrder where
toQueryParam = \case
ScoreOrderUnspecified -> "SCORE_ORDER_UNSPECIFIED"
LargerIsBetter -> "LARGER_IS_BETTER"
SmallerIsBetter -> "SMALLER_IS_BETTER"
instance FromJSON LeaderboardOrder where
parseJSON = parseJSONText "LeaderboardOrder"
instance ToJSON LeaderboardOrder where
toJSON = toJSONText
-- | The types of ranks to return. If the parameter is omitted, no ranks will
-- be returned.
data ScoresGetIncludeRankType
= SGIRTIncludeRankTypeUnspecified
-- ^ @INCLUDE_RANK_TYPE_UNSPECIFIED@
-- Default value. Should be unused.
| SGIRTAll
-- ^ @ALL@
-- Retrieve all supported ranks. In HTTP, this parameter value can also be
-- specified as \`ALL\`.
| SGIRTPublic
-- ^ @PUBLIC@
-- Retrieve public ranks, if the player is sharing their gameplay activity
-- publicly.
| SGIRTSocial
-- ^ @SOCIAL@
-- (Obsolete) Retrieve the social rank.
| SGIRTFriends
-- ^ @FRIENDS@
-- Retrieve the rank on the friends collection.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresGetIncludeRankType
instance FromHttpApiData ScoresGetIncludeRankType where
parseQueryParam = \case
"INCLUDE_RANK_TYPE_UNSPECIFIED" -> Right SGIRTIncludeRankTypeUnspecified
"ALL" -> Right SGIRTAll
"PUBLIC" -> Right SGIRTPublic
"SOCIAL" -> Right SGIRTSocial
"FRIENDS" -> Right SGIRTFriends
x -> Left ("Unable to parse ScoresGetIncludeRankType from: " <> x)
instance ToHttpApiData ScoresGetIncludeRankType where
toQueryParam = \case
SGIRTIncludeRankTypeUnspecified -> "INCLUDE_RANK_TYPE_UNSPECIFIED"
SGIRTAll -> "ALL"
SGIRTPublic -> "PUBLIC"
SGIRTSocial -> "SOCIAL"
SGIRTFriends -> "FRIENDS"
instance FromJSON ScoresGetIncludeRankType where
parseJSON = parseJSONText "ScoresGetIncludeRankType"
instance ToJSON ScoresGetIncludeRankType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The type of the achievement.
data AchievementDefinitionAchievementType
= AchievementTypeUnspecified
-- ^ @ACHIEVEMENT_TYPE_UNSPECIFIED@
-- Safe default, don\'t use.
| Standard
-- ^ @STANDARD@
-- Achievement is either locked or unlocked.
| Incremental
-- ^ @INCREMENTAL@
-- Achievement is incremental.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementDefinitionAchievementType
instance FromHttpApiData AchievementDefinitionAchievementType where
parseQueryParam = \case
"ACHIEVEMENT_TYPE_UNSPECIFIED" -> Right AchievementTypeUnspecified
"STANDARD" -> Right Standard
"INCREMENTAL" -> Right Incremental
x -> Left ("Unable to parse AchievementDefinitionAchievementType from: " <> x)
instance ToHttpApiData AchievementDefinitionAchievementType where
toQueryParam = \case
AchievementTypeUnspecified -> "ACHIEVEMENT_TYPE_UNSPECIFIED"
Standard -> "STANDARD"
Incremental -> "INCREMENTAL"
instance FromJSON AchievementDefinitionAchievementType where
parseJSON = parseJSONText "AchievementDefinitionAchievementType"
instance ToJSON AchievementDefinitionAchievementType where
toJSON = toJSONText
-- | The friend status of the given player, relative to the requester. This
-- is unset if the player is not sharing their friends list with the game.
data PlayerFriendStatus
= FriendStatusUnspecified
-- ^ @FRIEND_STATUS_UNSPECIFIED@
-- Default value. This value is unused.
| NoRelationship
-- ^ @NO_RELATIONSHIP@
-- There is no relationship between the players.
| Friend
-- ^ @FRIEND@
-- The player and requester are friends.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayerFriendStatus
instance FromHttpApiData PlayerFriendStatus where
parseQueryParam = \case
"FRIEND_STATUS_UNSPECIFIED" -> Right FriendStatusUnspecified
"NO_RELATIONSHIP" -> Right NoRelationship
"FRIEND" -> Right Friend
x -> Left ("Unable to parse PlayerFriendStatus from: " <> x)
instance ToHttpApiData PlayerFriendStatus where
toQueryParam = \case
FriendStatusUnspecified -> "FRIEND_STATUS_UNSPECIFIED"
NoRelationship -> "NO_RELATIONSHIP"
Friend -> "FRIEND"
instance FromJSON PlayerFriendStatus where
parseJSON = parseJSONText "PlayerFriendStatus"
instance ToJSON PlayerFriendStatus where
toJSON = toJSONText
-- | The time span for the scores and ranks you\'re requesting.
data ScoresListTimeSpan
= SLTSScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| SLTSAllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| SLTSWeekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| SLTSDaily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ScoresListTimeSpan
instance FromHttpApiData ScoresListTimeSpan where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right SLTSScoreTimeSpanUnspecified
"ALL_TIME" -> Right SLTSAllTime
"WEEKLY" -> Right SLTSWeekly
"DAILY" -> Right SLTSDaily
x -> Left ("Unable to parse ScoresListTimeSpan from: " <> x)
instance ToHttpApiData ScoresListTimeSpan where
toQueryParam = \case
SLTSScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
SLTSAllTime -> "ALL_TIME"
SLTSWeekly -> "WEEKLY"
SLTSDaily -> "DAILY"
instance FromJSON ScoresListTimeSpan where
parseJSON = parseJSONText "ScoresListTimeSpan"
instance ToJSON ScoresListTimeSpan where
toJSON = toJSONText
-- | The current state of the achievement.
data AchievementUpdateResponseCurrentState
= AURCSUpdatedAchievementStateUnspecified
-- ^ @UPDATED_ACHIEVEMENT_STATE_UNSPECIFIED@
-- Safe default, don\'t use.
| AURCSHidden
-- ^ @HIDDEN@
-- Achievement is hidden.
| AURCSRevealed
-- ^ @REVEALED@
-- Achievement is revealed.
| AURCSUnlocked
-- ^ @UNLOCKED@
-- Achievement is unlocked.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementUpdateResponseCurrentState
instance FromHttpApiData AchievementUpdateResponseCurrentState where
parseQueryParam = \case
"UPDATED_ACHIEVEMENT_STATE_UNSPECIFIED" -> Right AURCSUpdatedAchievementStateUnspecified
"HIDDEN" -> Right AURCSHidden
"REVEALED" -> Right AURCSRevealed
"UNLOCKED" -> Right AURCSUnlocked
x -> Left ("Unable to parse AchievementUpdateResponseCurrentState from: " <> x)
instance ToHttpApiData AchievementUpdateResponseCurrentState where
toQueryParam = \case
AURCSUpdatedAchievementStateUnspecified -> "UPDATED_ACHIEVEMENT_STATE_UNSPECIFIED"
AURCSHidden -> "HIDDEN"
AURCSRevealed -> "REVEALED"
AURCSUnlocked -> "UNLOCKED"
instance FromJSON AchievementUpdateResponseCurrentState where
parseJSON = parseJSONText "AchievementUpdateResponseCurrentState"
instance ToJSON AchievementUpdateResponseCurrentState where
toJSON = toJSONText
-- | The initial state of the achievement.
data AchievementDefinitionInitialState
= ADISInitialAchievementStateUnspecified
-- ^ @INITIAL_ACHIEVEMENT_STATE_UNSPECIFIED@
-- Safe default, don\'t use.
| ADISHidden
-- ^ @HIDDEN@
-- Achievement is hidden.
| ADISRevealed
-- ^ @REVEALED@
-- Achievement is revealed.
| ADISUnlocked
-- ^ @UNLOCKED@
-- Achievement is unlocked.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementDefinitionInitialState
instance FromHttpApiData AchievementDefinitionInitialState where
parseQueryParam = \case
"INITIAL_ACHIEVEMENT_STATE_UNSPECIFIED" -> Right ADISInitialAchievementStateUnspecified
"HIDDEN" -> Right ADISHidden
"REVEALED" -> Right ADISRevealed
"UNLOCKED" -> Right ADISUnlocked
x -> Left ("Unable to parse AchievementDefinitionInitialState from: " <> x)
instance ToHttpApiData AchievementDefinitionInitialState where
toQueryParam = \case
ADISInitialAchievementStateUnspecified -> "INITIAL_ACHIEVEMENT_STATE_UNSPECIFIED"
ADISHidden -> "HIDDEN"
ADISRevealed -> "REVEALED"
ADISUnlocked -> "UNLOCKED"
instance FromJSON AchievementDefinitionInitialState where
parseJSON = parseJSONText "AchievementDefinitionInitialState"
instance ToJSON AchievementDefinitionInitialState where
toJSON = toJSONText
data PlayerScoreResponseBeatenScoreTimeSpansItem
= PSRBSTSIScoreTimeSpanUnspecified
-- ^ @SCORE_TIME_SPAN_UNSPECIFIED@
-- Default value. This value is unused.
| PSRBSTSIAllTime
-- ^ @ALL_TIME@
-- The score is an all-time score.
| PSRBSTSIWeekly
-- ^ @WEEKLY@
-- The score is a weekly score.
| PSRBSTSIDaily
-- ^ @DAILY@
-- The score is a daily score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PlayerScoreResponseBeatenScoreTimeSpansItem
instance FromHttpApiData PlayerScoreResponseBeatenScoreTimeSpansItem where
parseQueryParam = \case
"SCORE_TIME_SPAN_UNSPECIFIED" -> Right PSRBSTSIScoreTimeSpanUnspecified
"ALL_TIME" -> Right PSRBSTSIAllTime
"WEEKLY" -> Right PSRBSTSIWeekly
"DAILY" -> Right PSRBSTSIDaily
x -> Left ("Unable to parse PlayerScoreResponseBeatenScoreTimeSpansItem from: " <> x)
instance ToHttpApiData PlayerScoreResponseBeatenScoreTimeSpansItem where
toQueryParam = \case
PSRBSTSIScoreTimeSpanUnspecified -> "SCORE_TIME_SPAN_UNSPECIFIED"
PSRBSTSIAllTime -> "ALL_TIME"
PSRBSTSIWeekly -> "WEEKLY"
PSRBSTSIDaily -> "DAILY"
instance FromJSON PlayerScoreResponseBeatenScoreTimeSpansItem where
parseJSON = parseJSONText "PlayerScoreResponseBeatenScoreTimeSpansItem"
instance ToJSON PlayerScoreResponseBeatenScoreTimeSpansItem where
toJSON = toJSONText
-- | The platform type.
data InstancePlatformType
= IPTPlatformTypeUnspecified
-- ^ @PLATFORM_TYPE_UNSPECIFIED@
-- Default value. Should be unused.
| IPTAndroid
-- ^ @ANDROID@
-- Instance is for Android.
| IPTIos
-- ^ @IOS@
-- Instance is for iOS.
| IPTWebApp
-- ^ @WEB_APP@
-- Instance is for Web App.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable InstancePlatformType
instance FromHttpApiData InstancePlatformType where
parseQueryParam = \case
"PLATFORM_TYPE_UNSPECIFIED" -> Right IPTPlatformTypeUnspecified
"ANDROID" -> Right IPTAndroid
"IOS" -> Right IPTIos
"WEB_APP" -> Right IPTWebApp
x -> Left ("Unable to parse InstancePlatformType from: " <> x)
instance ToHttpApiData InstancePlatformType where
toQueryParam = \case
IPTPlatformTypeUnspecified -> "PLATFORM_TYPE_UNSPECIFIED"
IPTAndroid -> "ANDROID"
IPTIos -> "IOS"
IPTWebApp -> "WEB_APP"
instance FromJSON InstancePlatformType where
parseJSON = parseJSONText "InstancePlatformType"
instance ToJSON InstancePlatformType where
toJSON = toJSONText
-- | The collection of categories for which data will be returned.
data MetagameListCategoriesByPlayerCollection
= CollectionUnspecified
-- ^ @COLLECTION_UNSPECIFIED@
-- Default value. This value is unused.
| All
-- ^ @ALL@
-- Retrieve data for all categories. This is the default.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable MetagameListCategoriesByPlayerCollection
instance FromHttpApiData MetagameListCategoriesByPlayerCollection where
parseQueryParam = \case
"COLLECTION_UNSPECIFIED" -> Right CollectionUnspecified
"ALL" -> Right All
x -> Left ("Unable to parse MetagameListCategoriesByPlayerCollection from: " <> x)
instance ToHttpApiData MetagameListCategoriesByPlayerCollection where
toQueryParam = \case
CollectionUnspecified -> "COLLECTION_UNSPECIFIED"
All -> "ALL"
instance FromJSON MetagameListCategoriesByPlayerCollection where
parseJSON = parseJSONText "MetagameListCategoriesByPlayerCollection"
instance ToJSON MetagameListCategoriesByPlayerCollection where
toJSON = toJSONText
-- | Tells the server to return only achievements with the specified state.
-- If this parameter isn\'t specified, all achievements are returned.
data AchievementsListState
= ALSAll
-- ^ @ALL@
-- List all achievements. This is the default.
| ALSHidden
-- ^ @HIDDEN@
-- List only hidden achievements.
| ALSRevealed
-- ^ @REVEALED@
-- List only revealed achievements.
| ALSUnlocked
-- ^ @UNLOCKED@
-- List only unlocked achievements.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AchievementsListState
instance FromHttpApiData AchievementsListState where
parseQueryParam = \case
"ALL" -> Right ALSAll
"HIDDEN" -> Right ALSHidden
"REVEALED" -> Right ALSRevealed
"UNLOCKED" -> Right ALSUnlocked
x -> Left ("Unable to parse AchievementsListState from: " <> x)
instance ToHttpApiData AchievementsListState where
toQueryParam = \case
ALSAll -> "ALL"
ALSHidden -> "HIDDEN"
ALSRevealed -> "REVEALED"
ALSUnlocked -> "UNLOCKED"
instance FromJSON AchievementsListState where
parseJSON = parseJSONText "AchievementsListState"
instance ToJSON AchievementsListState where
toJSON = toJSONText
| brendanhay/gogol | gogol-games/gen/Network/Google/Games/Types/Sum.hs | mpl-2.0 | 43,252 | 0 | 11 | 9,416 | 6,273 | 3,335 | 2,938 | 740 | 0 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2019 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Quests.DarkLord (quest) where
import HabitOfFate.Prelude
import HabitOfFate.Quest
import qualified HabitOfFate.Quests.DarkLord.Part1 as Part1
import qualified HabitOfFate.Quests.DarkLord.Part2 as Part2
import HabitOfFate.Story
part_selection = Narrative
{ title = "Choose What to Follow"
, content = "This quest has two parts."
}
quest ∷ Quest
quest = Quest
"darklord"
"An entreatment from someone seeking to defeat the Dark Lord."
mempty
( SplitEntry "part" part_selection "Which do you choose to follow first?"
[ Part1.branch
, Part2.branch
]
)
| gcross/habit-of-fate | sources/library/HabitOfFate/Quests/DarkLord.hs | agpl-3.0 | 1,434 | 0 | 9 | 274 | 113 | 73 | 40 | 22 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Project where
import Import
import Data.Filter
import Data.Order
import Data.Time.Format
import Handler.Comment as Com
import Handler.Discussion
import Handler.Utils
import Model.Application
import Model.Comment
import Model.Comment.ActionPermissions
import Model.Comment.HandlerInfo
import Model.Comment.Mods
import Model.Comment.Sql
import Model.Currency
import Model.Discussion
import Model.Issue
import Model.Markdown.Diff
import Model.Project
import Model.Role
import Model.Shares
import Model.SnowdriftEvent
import Model.User
import Model.Wiki
import System.Locale (defaultTimeLocale)
import View.Comment
import View.Project
import View.SnowdriftEvent
import Widgets.Preview
import Widgets.Time
import Data.Default (def)
import qualified Data.Foldable as F
import Data.List (sortBy)
import qualified Data.Map as M
import Data.Maybe (maybeToList)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Tree (Forest, Tree)
import qualified Data.Tree as Tree
import System.Random (randomIO)
import Text.Cassius (cassiusFile)
import Text.Printf
import Yesod.AtomFeed
import Yesod.RssFeed
--------------------------------------------------------------------------------
-- Utility functions
lookupGetParamDefault :: Read a => Text -> a -> Handler a
lookupGetParamDefault name def_val = do
maybe_value <- lookupGetParam name
return (fromMaybe def_val (maybe_value >>= readMaybe . T.unpack))
-- | Require any of the given Roles, failing with permissionDenied if none are satisfied.
requireRolesAny :: [Role] -> Text -> Text -> Handler (UserId, Entity Project)
requireRolesAny roles project_handle err_msg = do
user_id <- requireAuthId
(project, ok) <- runYDB $ do
project@(Entity project_id _) <- getBy404 (UniqueProjectHandle project_handle)
ok <- userHasRolesAnyDB roles user_id project_id
return (project, ok)
unless ok $
permissionDenied err_msg
return (user_id, project)
-- | Sanity check for Project Comment pages. Redirects if the comment was rethreaded.
-- 404's if the comment doesn't exist. 403 if permission denied.
checkComment :: Text -> CommentId -> Handler (Maybe (Entity User), Entity Project, Comment)
checkComment project_handle comment_id = do
muser <- maybeAuth
(project, comment) <- checkComment' (entityKey <$> muser) project_handle comment_id
return (muser, project, comment)
-- | Like checkComment, but authentication is required.
checkCommentRequireAuth :: Text -> CommentId -> Handler (Entity User, Entity Project, Comment)
checkCommentRequireAuth project_handle comment_id = do
user@(Entity user_id _) <- requireAuth
(project, comment) <- checkComment' (Just user_id) project_handle comment_id
return (user, project, comment)
-- | Abstract checkComment and checkCommentRequireAuth. You shouldn't use this function directly.
checkComment' :: Maybe UserId -> Text -> CommentId -> Handler (Entity Project, Comment)
checkComment' muser_id project_handle comment_id = do
redirectIfRethreaded comment_id
(project, ecomment) <- runYDB $ do
project@(Entity project_id _) <- getBy404 (UniqueProjectHandle project_handle)
let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id)
ecomment <- fetchCommentDB comment_id has_permission
return (project, ecomment)
case ecomment of
Left CommentNotFound -> notFound
Left CommentPermissionDenied -> permissionDenied "You don't have permission to view this comment."
Right comment ->
if commentDiscussion comment /= projectDiscussion (entityVal project)
then notFound
else return (project, comment)
checkProjectCommentActionPermission
:: (CommentActionPermissions -> Bool)
-> Entity User
-> Text
-> Entity Comment
-> Handler ()
checkProjectCommentActionPermission
can_perform_action
user
project_handle
comment@(Entity comment_id _) = do
action_permissions <-
lookupErr "checkProjectCommentActionPermission: comment id not found in map" comment_id
<$> makeProjectCommentActionPermissionsMap (Just user) project_handle def [comment]
unless (can_perform_action action_permissions)
(permissionDenied "You don't have permission to perform this action.")
makeProjectCommentForestWidget
:: Maybe (Entity User)
-> ProjectId
-> Text
-> [Entity Comment]
-> CommentMods
-> Handler MaxDepth
-> Bool
-> Widget
-> Handler (Widget, Forest (Entity Comment))
makeProjectCommentForestWidget
muser
project_id
project_handle
comments =
makeCommentForestWidget
(projectCommentHandlerInfo muser project_id project_handle)
comments
muser
makeProjectCommentTreeWidget
:: Maybe (Entity User)
-> ProjectId
-> Text
-> Entity Comment
-> CommentMods
-> Handler MaxDepth
-> Bool
-> Widget
-> Handler (Widget, Tree (Entity Comment))
makeProjectCommentTreeWidget a b c d e f g h = do
(widget, [tree]) <- makeProjectCommentForestWidget a b c [d] e f g h
return (widget, tree)
makeProjectCommentActionWidget
:: MakeCommentActionWidget
-> Text
-> CommentId
-> CommentMods
-> Handler MaxDepth
-> Handler (Widget, Tree (Entity Comment))
makeProjectCommentActionWidget make_comment_action_widget project_handle comment_id mods get_max_depth = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
let handler_info = projectCommentHandlerInfo (Just user) project_id project_handle
make_comment_action_widget (Entity comment_id comment) user handler_info mods get_max_depth False
projectDiscussionPage :: Text -> Widget -> Widget
projectDiscussionPage project_handle widget = do
$(widgetFile "project_discussion_wrapper")
toWidget $(cassiusFile "templates/comment.cassius")
-------------------------------------------------------------------------------
--
getProjectsR :: Handler Html
getProjectsR = do
project_summaries <- runDB $ do
projects <- fetchPublicProjectsDB
forM projects $ \project -> do
pledges <- fetchProjectPledgesDB $ entityKey project
discussions <- fetchProjectDiscussionsDB $ entityKey project
tickets <- fetchProjectOpenTicketsDB (entityKey project) Nothing
let summary = summarizeProject project pledges discussions tickets
return (project, summary)
let discussionsCount = getCount . summaryDiscussionCount
let ticketsCount = getCount . summaryTicketCount
defaultLayout $ do
snowdriftTitle "Projects"
$(widgetFile "projects")
--------------------------------------------------------------------------------
-- /
getProjectR :: Text -> Handler Html
getProjectR project_handle = do
mviewer_id <- maybeAuthId
(project_id, project, is_watching, pledges, pledge) <- runYDB $ do
Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle
pledges <- fetchProjectSharesDB project_id
(pledge, is_watching) <- case mviewer_id of
Nothing -> return (Nothing, False)
Just viewer_id -> (,)
<$> getBy (UniquePledge viewer_id project_id)
<*> userIsWatchingProjectDB viewer_id project_id
return (project_id, project, is_watching, pledges, pledge)
defaultLayout $ do
snowdriftTitle $ projectName project
renderProject (Just project_id) project mviewer_id is_watching pledges pledge
postProjectR :: Text -> Handler Html
postProjectR project_handle = do
(viewer_id, Entity project_id project) <-
requireRolesAny [Admin] project_handle "You do not have permission to edit this project."
((result, _), _) <- runFormPost $ editProjectForm Nothing
now <- liftIO getCurrentTime
case result of
FormSuccess (UpdateProject
name
blurb
description
tags
github_repo
logo) ->
lookupPostMode >>= \case
Just PostMode -> do
runDB $ do
when (projectBlurb project /= blurb) $ do
project_update <- insert $
ProjectUpdate now
project_id
viewer_id
blurb
(diffMarkdown
(projectDescription project)
description)
last_update <- getBy $ UniqueProjectLastUpdate project_id
case last_update of
Just (Entity k _) -> repsert k $ ProjectLastUpdate project_id project_update
Nothing -> void $ insert $ ProjectLastUpdate project_id project_update
update $ \p -> do
set p [ ProjectName =. val name
, ProjectBlurb =. val blurb
, ProjectDescription =. val description
, ProjectGithubRepo =. val github_repo
, ProjectLogo =. val logo
]
where_ (p ^. ProjectId ==. val project_id)
tag_ids <- forM tags $ \tag_name -> do
tag_entity_list <- select $ from $ \tag -> do
where_ (tag ^. TagName ==. val tag_name)
return tag
case tag_entity_list of
[] -> insert $ Tag tag_name
Entity tag_id _ : _ -> return tag_id
delete $
from $ \pt ->
where_ (pt ^. ProjectTagProject ==. val project_id)
forM_ tag_ids $ \tag_id -> insert (ProjectTag project_id tag_id)
alertSuccess "project updated"
redirect $ ProjectR project_handle
_ -> do
let
preview_project = project
{ projectName = name
, projectBlurb = blurb
, projectDescription = description
, projectGithubRepo = github_repo
, projectLogo = logo
}
(form, _) <- generateFormPost $ editProjectForm (Just (preview_project, tags))
defaultLayout $ previewWidget form "update" $ renderProject (Just project_id) preview_project Nothing False [] Nothing
x -> do
alertDanger $ T.pack $ show x
redirect $ ProjectR project_handle
--------------------------------------------------------------------------------
-- /applications (List of submitted applications)
getApplicationsR :: Text -> Handler Html
getApplicationsR project_handle = do
viewer_id <- requireAuthId
(project, applications) <- runYDB $ do
Entity project_id project <- getBy404 (UniqueProjectHandle project_handle)
ok <- userIsAffiliatedWithProjectDB viewer_id project_id
unless ok $
lift (permissionDenied "You don't have permission to view this page.")
applications <- fetchProjectVolunteerApplicationsDB project_id
userReadVolunteerApplicationsDB viewer_id
return (project, applications)
defaultLayout $ do
snowdriftTitle $ projectName project <> " Volunteer Applications"
$(widgetFile "applications")
--------------------------------------------------------------------------------
-- /application (Form for new application)
getApplicationR :: Text -> VolunteerApplicationId -> Handler Html
getApplicationR project_handle application_id = do
viewer_id <- requireAuthId
(project, user, application, interests, num_interests) <- runYDB $ do
Entity project_id project <- getBy404 (UniqueProjectHandle project_handle)
ok <- userIsAffiliatedWithProjectDB viewer_id project_id
unless ok $
lift (permissionDenied "You don't have permission to view this page.")
application <- get404 application_id
let user_id = volunteerApplicationUser application
user <- get404 user_id
(interests, num_interests) <- (T.intercalate ", " &&& length) <$> fetchApplicationVolunteerInterestsDB application_id
return (project, Entity user_id user, application, interests, num_interests)
defaultLayout $ do
snowdriftDashTitle
(projectName project <> " Volunteer Application")
(userDisplayName user)
$(widgetFile "application")
--------------------------------------------------------------------------------
-- /edit
getEditProjectR :: Text -> Handler Html
getEditProjectR project_handle = do
(_, Entity project_id project) <-
requireRolesAny [Admin] project_handle "You do not have permission to edit this project."
tags <- runDB $
select $
from $ \(p_t `InnerJoin` tag) -> do
on_ (p_t ^. ProjectTagTag ==. tag ^. TagId)
where_ (p_t ^. ProjectTagProject ==. val project_id)
return tag
(project_form, _) <- generateFormPost $ editProjectForm (Just (project, map (tagName . entityVal) tags))
defaultLayout $ do
snowdriftTitle $ projectName project
$(widgetFile "edit_project")
--------------------------------------------------------------------------------
-- /feed
-- | This function is responsible for hitting every relevant event table. Nothing
-- statically guarantees that.
getProjectFeedR :: Text -> Handler TypedContent
getProjectFeedR project_handle = do
let lim = 26 -- limit 'lim' from each table, then take 'lim - 1'
languages <- getLanguages
muser <- maybeAuth
let muser_id = entityKey <$> muser
before <- lookupGetUTCTimeDefaultNow "before"
(
project_id, project,
is_watching,
comment_events, rethread_events, closing_events, claiming_events, unclaiming_events,
wiki_page_events, wiki_edit_events, blog_post_events, new_pledge_events,
updated_pledge_events, deleted_pledge_events,
discussion_map, wiki_target_map, user_map, earlier_closures_map, earlier_retracts_map,
closure_map, retract_map, ticket_map, claim_map, flag_map
) <- runYDB $ do
Entity project_id project <- getBy404 (UniqueProjectHandle project_handle)
is_watching <- maybe (pure False) (flip userIsWatchingProjectDB project_id) muser_id
comment_events <- fetchProjectCommentPostedEventsIncludingRethreadedBeforeDB project_id muser_id before lim
rethread_events <- fetchProjectCommentRethreadEventsBeforeDB project_id muser_id before lim
closing_events <- fetchProjectCommentClosingEventsBeforeDB project_id muser_id before lim
claiming_events <- fetchProjectTicketClaimingEventsBeforeDB project_id before lim
unclaiming_events <- fetchProjectTicketUnclaimingEventsBeforeDB project_id before lim
wiki_page_events <- fetchProjectWikiPageEventsWithTargetsBeforeDB languages project_id before lim
blog_post_events <- fetchProjectBlogPostEventsBeforeDB project_id before lim
wiki_edit_events <- fetchProjectWikiEditEventsWithTargetsBeforeDB languages project_id before lim
new_pledge_events <- fetchProjectNewPledgeEventsBeforeDB project_id before lim
updated_pledge_events <- fetchProjectUpdatedPledgeEventsBeforeDB project_id before lim
deleted_pledge_events <- fetchProjectDeletedPledgeEventsBeforeDB project_id before lim
-- Suplementary maps for displaying the data. If something above requires extra
-- data to display the project feed row, it MUST be used to fetch the data below!
let (comment_ids, comment_users) = F.foldMap (\(_, Entity comment_id comment) -> ([comment_id], [commentUser comment])) comment_events
(wiki_edit_users, wiki_edit_pages) = F.foldMap (\(_, Entity _ e, _) -> ([wikiEditUser e], [wikiEditPage e])) wiki_edit_events
(blog_post_users) = F.foldMap (\(_, Entity _ e) -> [blogPostUser e]) blog_post_events
shares_pledged = map (entityVal . snd) new_pledge_events <> map (\(_, _, x) -> entityVal x) updated_pledge_events
closing_users = map (commentClosingClosedBy . entityVal . snd) closing_events
rethreading_users = map (rethreadModerator . entityVal . snd) rethread_events
ticket_claiming_users = map (either (ticketClaimingUser . entityVal) (ticketOldClaimingUser . entityVal) . snd) claiming_events
ticket_unclaiming_users = map (ticketOldClaimingUser . entityVal . snd) unclaiming_events
pledging_users = map sharesPledgedUser shares_pledged
unpledging_users = map (eventDeletedPledgeUser . snd) deleted_pledge_events
-- All users: comment posters, wiki page creators, etc.
user_ids = S.toList $ mconcat
[ S.fromList comment_users
, S.fromList closing_users
, S.fromList rethreading_users
, S.fromList wiki_edit_users
, S.fromList blog_post_users
, S.fromList ticket_claiming_users
, S.fromList ticket_unclaiming_users
, S.fromList pledging_users
, S.fromList unpledging_users
]
discussion_map <- fetchProjectDiscussionsDB project_id >>= fetchDiscussionsDB languages
let claimed_comment_ids = map (either (ticketClaimingTicket . entityVal) (ticketOldClaimingTicket . entityVal) . snd) claiming_events
unclaimed_comment_ids = map (ticketOldClaimingTicket . entityVal . snd) unclaiming_events
closed_comment_ids = map (commentClosingComment . entityVal . snd) closing_events
ticket_map <- fetchCommentTicketsDB $ mconcat
[ S.fromList comment_ids
, S.fromList claimed_comment_ids
, S.fromList unclaimed_comment_ids
, S.fromList closed_comment_ids
]
-- WikiPages keyed by their own IDs (contained in a WikiEdit)
wiki_targets <- pickTargetsByLanguage languages <$> fetchWikiPageTargetsInDB wiki_edit_pages
let wiki_target_map = M.fromList $ map ((wikiTargetPage &&& id) . entityVal) wiki_targets
user_map <- entitiesMap <$> fetchUsersInDB user_ids
earlier_closures_map <- fetchCommentsAncestorClosuresDB comment_ids
earlier_retracts_map <- fetchCommentsAncestorRetractsDB comment_ids
closure_map <- makeCommentClosingMapDB comment_ids
retract_map <- makeCommentRetractingMapDB comment_ids
claim_map <- makeClaimedTicketMapDB comment_ids
flag_map <- makeFlagMapDB comment_ids
return
(
project_id, project,
is_watching,
comment_events, rethread_events, closing_events, claiming_events, unclaiming_events, wiki_page_events,
wiki_edit_events, blog_post_events, new_pledge_events, updated_pledge_events, deleted_pledge_events,
discussion_map, wiki_target_map, user_map, earlier_closures_map, earlier_retracts_map,
closure_map, retract_map, ticket_map, claim_map, flag_map
)
action_permissions_map <- makeProjectCommentActionPermissionsMap muser project_handle def (map snd comment_events)
let all_unsorted_events :: [(Route App, SnowdriftEvent)]
all_unsorted_events = mconcat
[ map (EventCommentPostedR *** onEntity ECommentPosted) comment_events
, map (EventCommentRethreadedR *** onEntity ECommentRethreaded) rethread_events
, map (EventCommentClosingR *** onEntity ECommentClosed) closing_events
, map (EventTicketClaimedR *** ETicketClaimed . (onEntity (,) +++ onEntity (,))) claiming_events
, map (EventTicketUnclaimedR *** onEntity ETicketUnclaimed) unclaiming_events
, map (\(eid, Entity wpid wp, wt)
-> (EventWikiPageR eid, EWikiPage wpid wp wt)) wiki_page_events
, map (\(eid, Entity weid we, wt)
-> (EventWikiEditR eid, EWikiEdit weid we wt)) wiki_edit_events
, map (EventBlogPostR *** onEntity EBlogPost) blog_post_events
, map (EventNewPledgeR *** onEntity ENewPledge) new_pledge_events
, map (\(eid, shares, pledge)
-> (EventUpdatedPledgeR eid, eup2se shares pledge)) updated_pledge_events
, map (EventDeletedPledgeR *** edp2se) deleted_pledge_events
]
(events, more_events) = splitAt (lim-1) (sortBy (snowdriftEventNewestToOldest `on` snd) all_unsorted_events)
-- For pagination: Nothing means no more pages, Just time means set the 'before'
-- GET param to that time. Note that this means 'before' should be a <= relation,
-- rather than a <.
mnext_before :: Maybe Text
mnext_before = case more_events of
[] -> Nothing
((_, next_event):_) -> (Just . T.pack . show . snowdriftEventTime) next_event
now <- liftIO getCurrentTime
Just route <- getCurrentRoute
render <- getUrlRender
let feed = Feed "project feed" route HomeR "Snowdrift Community" "" "en" now $
mapMaybe (uncurry $ snowdriftEventToFeedEntry
render
project_handle
user_map
discussion_map
wiki_target_map
ticket_map) events
selectRep $ do
provideRep $ atomFeed feed
provideRep $ rssFeed feed
provideRep $ defaultLayout $ do
snowdriftDashTitle (projectName project) "Feed"
$(widgetFile "project_feed")
toWidget $(cassiusFile "templates/comment.cassius")
where
-- "event updated pledge to snowdrift event"
eup2se :: Int64 -> Entity SharesPledged -> SnowdriftEvent
eup2se old_shares (Entity shares_pledged_id shares_pledged) = EUpdatedPledge old_shares shares_pledged_id shares_pledged
-- "event deleted pledge to snowdrift event"
edp2se :: EventDeletedPledge -> SnowdriftEvent
edp2se (EventDeletedPledge a b c d) = EDeletedPledge a b c d
--------------------------------------------------------------------------------
-- /invite
getInviteR :: Text -> Handler Html
getInviteR project_handle = do
(_, Entity _ project) <- requireRolesAny [Admin] project_handle "You must be a project admin to invite."
now <- liftIO getCurrentTime
maybe_invite_code <- lookupSession "InviteCode"
maybe_invite_role <- fmap (read . T.unpack) <$> lookupSession "InviteRole"
deleteSession "InviteCode"
deleteSession "InviteRole"
let maybe_link = InvitationR project_handle <$> maybe_invite_code
(invite_form, _) <- generateFormPost inviteForm
outstanding_invites <- runDB $
select $
from $ \invite -> do
where_ ( invite ^. InviteRedeemed ==. val False )
orderBy [ desc (invite ^. InviteCreatedTs) ]
return invite
redeemed_invites <- runDB $
select $
from $ \invite -> do
where_ ( invite ^. InviteRedeemed ==. val True )
orderBy [ desc (invite ^. InviteCreatedTs) ]
limit 20
return invite
let redeemed_users = S.fromList $ mapMaybe (inviteRedeemedBy . entityVal) redeemed_invites
redeemed_inviters = S.fromList $ map (inviteUser . entityVal) redeemed_invites
outstanding_inviters = S.fromList $ map (inviteUser . entityVal) outstanding_invites
user_ids = S.toList $ redeemed_users `S.union` redeemed_inviters `S.union` outstanding_inviters
user_entities <- runDB $ selectList [ UserId <-. user_ids ] []
let users = M.fromList $ map (entityKey &&& id) user_entities
let format_user Nothing = "NULL"
format_user (Just user_id) =
let Entity _ user = fromMaybe (error "getInviteR: user_id not found in users map")
(M.lookup user_id users)
in fromMaybe (userIdent user) $ userName user
format_inviter user_id =
userDisplayName $ fromMaybe (error "getInviteR(#2): user_id not found in users map")
(M.lookup user_id users)
defaultLayout $ do
snowdriftDashTitle (projectName project) "Send Invite"
$(widgetFile "invite")
postInviteR :: Text -> Handler Html
postInviteR project_handle = do
(user_id, Entity project_id _) <- requireRolesAny [Admin] project_handle "You must be a project admin to invite."
now <- liftIO getCurrentTime
invite <- liftIO randomIO
((result, _), _) <- runFormPost inviteForm
case result of
FormSuccess (tag, role) -> do
let invite_code = T.pack $ printf "%016x" (invite :: Int64)
_ <- runDB $ insert $ Invite now project_id invite_code user_id role tag False Nothing Nothing
setSession "InviteCode" invite_code
setSession "InviteRole" (T.pack $ show role)
_ -> alertDanger "Error in submitting form."
redirect $ InviteR project_handle
--------------------------------------------------------------------------------
-- /patrons
getProjectPatronsR :: Text -> Handler Html
getProjectPatronsR project_handle = do
_ <- requireAuthId
page <- lookupGetParamDefault "page" 0
per_page <- lookupGetParamDefault "count" 20
(project, pledges, user_payouts_map) <- runYDB $ do
Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle
pledges <- select $ from $ \(pledge `InnerJoin` user) -> do
on_ $ pledge ^. PledgeUser ==. user ^. UserId
where_ $ pledge ^. PledgeProject ==. val project_id
&&. pledge ^. PledgeFundedShares >. val 0
orderBy [ desc (pledge ^. PledgeFundedShares), asc (user ^. UserName), asc (user ^. UserId)]
offset page
limit per_page
return (pledge, user)
last_paydays <- case projectLastPayday project of
Nothing -> return []
Just last_payday -> select $ from $ \payday -> do
where_ $ payday ^. PaydayId <=. val last_payday
orderBy [ desc $ payday ^. PaydayId ]
limit 2
return payday
user_payouts <- select $ from $ \(transaction `InnerJoin` user) -> do
where_ $ transaction ^. TransactionPayday `in_` valList (map (Just . entityKey) last_paydays)
on_ $ transaction ^. TransactionDebit ==. just (user ^. UserAccount)
groupBy $ user ^. UserId
return (user ^. UserId, count $ transaction ^. TransactionId)
return (project, pledges, M.fromList $ map ((\(Value x :: Value UserId) -> x) *** (\(Value x :: Value Int) -> x)) user_payouts)
defaultLayout $ do
snowdriftTitle $ projectName project <> " Patrons"
$(widgetFile "project_patrons")
--------------------------------------------------------------------------------
-- /pledge
getUpdatePledgeR :: Text -> Handler Html
getUpdatePledgeR project_handle = do
_ <- requireAuthId
Entity project_id project <- runYDB $ getBy404 $ UniqueProjectHandle project_handle
((result, _), _) <- runFormGet $ pledgeForm project_id
let dangerRedirect msg = do
alertDanger msg
redirect $ ProjectR project_handle
case result of
FormSuccess (SharesPurchaseOrder new_user_shares) -> do
user_id <- requireAuthId
(confirm_form, _) <- generateFormPost $ projectConfirmPledgeForm (Just new_user_shares)
(mpledge, other_shares) <- runDB $ do
mpledge <- getBy $ UniquePledge user_id project_id
other_shares <- fmap unwrapValues $ select $ from $ \p -> do
where_ $ p ^. PledgeProject ==. val project_id
&&. p ^. PledgeUser !=. val user_id
return $ p ^. PledgeShares
return (mpledge, other_shares)
case mpledge of
Just (Entity _ pledge) | pledgeShares pledge == new_user_shares -> do
alertWarning $ T.unwords
[ "Your pledge was already at"
, T.pack (show new_user_shares)
, plural new_user_shares "share" "shares" <> "."
, "Thank you for your support!"
]
redirect (ProjectR project_handle)
_ -> do
let old_user_shares = maybe 0 (pledgeShares . entityVal) mpledge
new_project_shares = filter (>0) [new_user_shares] ++ other_shares
old_project_shares = filter (>0) [old_user_shares] ++ other_shares
new_share_value = projectComputeShareValue new_project_shares
old_share_value = projectComputeShareValue old_project_shares
new_user_amount = new_share_value $* fromIntegral new_user_shares
old_user_amount = old_share_value $* fromIntegral old_user_shares
new_project_amount = new_share_value $* fromIntegral (sum new_project_shares)
old_project_amount = old_share_value $* fromIntegral (sum old_project_shares)
user_decrease = old_user_amount - new_user_amount
project_decrease = old_project_amount - new_project_amount
project_increase = new_project_amount - old_project_amount
donations_drop = project_decrease - user_decrease
matched_extra = project_increase - new_user_amount
defaultLayout $ do
snowdriftDashTitle
(projectName project)
"update pledge"
$(widgetFile "update_pledge")
FormMissing -> dangerRedirect "Form missing."
FormFailure errors ->
dangerRedirect $ T.snoc (T.intercalate "; " errors) '.'
postUpdatePledgeR :: Text -> Handler Html
postUpdatePledgeR project_handle = do
((result, _), _) <- runFormPost $ projectConfirmPledgeForm Nothing
isConfirmed <- maybe False (T.isPrefixOf "yes") <$> lookupPostParam "confirm"
case result of
FormSuccess (SharesPurchaseOrder shares) -> do
when isConfirmed $ updateUserPledge project_handle shares
redirect (ProjectR project_handle)
_ -> do
alertDanger "error occurred in form submission"
redirect (UpdatePledgeR project_handle)
--------------------------------------------------------------------------------
-- /t
getTicketsR :: Text -> Handler Html
getTicketsR project_handle = do
muser_id <- maybeAuthId
(project, tagged_tickets) <- runYDB $ do
Entity project_id project <- getBy404 (UniqueProjectHandle project_handle)
tagged_tickets <- fetchProjectOpenTicketsDB project_id muser_id
return (project, tagged_tickets)
((result, formWidget), encType) <- runFormGet viewForm
let (filter_expression, order_expression) = case result of
FormSuccess x -> x
_ -> (defaultFilter, defaultOrder)
github_issues <- getGithubIssues project
let issues = sortBy (flip compare `on` order_expression . issueOrderable) $
filter (filter_expression . issueFilterable) $
map mkSomeIssue tagged_tickets ++ map mkSomeIssue github_issues
defaultLayout $ do
snowdriftTitle $ projectName project <> " Tickets"
$(widgetFile "tickets")
--------------------------------------------------------------------------------
-- /t/#TicketId
getTicketR :: Text -> TicketId -> Handler ()
getTicketR project_handle ticket_id = do
Ticket{..} <- runYDB $ do
void $ getBy404 $ UniqueProjectHandle project_handle
get404 ticket_id
-- TODO - check that the comment is associated with the correct project
redirect $ CommentDirectLinkR ticketComment
--------------------------------------------------------------------------------
-- /transactions
getProjectTransactionsR :: Text -> Handler Html
getProjectTransactionsR project_handle = do
(project, account, account_map, transaction_groups) <- runYDB $ do
Entity _ project :: Entity Project <- getBy404 $ UniqueProjectHandle project_handle
account <- get404 $ projectAccount project
transactions <- select $ from $ \t -> do
where_ $ t ^. TransactionCredit ==. val (Just $ projectAccount project)
||. t ^. TransactionDebit ==. val (Just $ projectAccount project)
orderBy [ desc $ t ^. TransactionTs ]
return t
let accounts = S.toList $ S.fromList $ concatMap (\(Entity _ t) -> maybeToList (transactionCredit t) <> maybeToList (transactionDebit t)) transactions
users_by_account <- fmap (M.fromList . map (userAccount . entityVal &&& Right)) $ select $ from $ \u -> do
where_ $ u ^. UserAccount `in_` valList accounts
return u
projects_by_account <- fmap (M.fromList . map (projectAccount . entityVal &&& Left)) $ select $ from $ \p -> do
where_ $ p ^. ProjectAccount `in_` valList accounts
return p
let account_map = projects_by_account `M.union` users_by_account
payday_map <- fmap (M.fromList . map (entityKey &&& id)) $ select $ from $ \pd -> do
where_ $ pd ^. PaydayId `in_` valList (S.toList $ S.fromList $ mapMaybe (transactionPayday . entityVal) transactions)
return pd
return (project, account, account_map, process payday_map transactions)
let getOtherAccount transaction
| transactionCredit transaction == Just (projectAccount project) = transactionDebit transaction
| transactionDebit transaction == Just (projectAccount project) = transactionCredit transaction
| otherwise = Nothing
defaultLayout $ do
snowdriftTitle $ projectName project <> " Transactions"
$(widgetFile "project_transactions")
where
process payday_map =
let process' [] [] = []
process' (t':ts') [] = [(fmap (payday_map M.!) $ transactionPayday $ entityVal t', reverse (t':ts'))]
process' [] (t:ts) = process' [t] ts
process' (t':ts') (t:ts)
| transactionPayday (entityVal t') == transactionPayday (entityVal t)
= process' (t:t':ts') ts
| otherwise
= (fmap (payday_map M.!) $ transactionPayday $ entityVal t', reverse (t':ts')) : process' [t] ts
in process' []
--------------------------------------------------------------------------------
-- /w
getWikiPagesR :: Text -> Handler Html
getWikiPagesR project_handle = do
void maybeAuthId
languages <- getLanguages
(project, wiki_targets) <- runYDB $ do
Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle
wiki_targets <- getProjectWikiPages languages project_id
return (project, wiki_targets)
defaultLayout $ do
snowdriftTitle $ projectName project <> " Wiki"
$(widgetFile "wiki_pages")
--------------------------------------------------------------------------------
-- /watch, /unwatch
postWatchProjectR, postUnwatchProjectR :: ProjectId -> Handler ()
postWatchProjectR = watchOrUnwatchProject userWatchProjectDB "Watching "
postUnwatchProjectR = watchOrUnwatchProject userUnwatchProjectDB "No longer watching "
watchOrUnwatchProject :: (UserId -> ProjectId -> DB ()) -> Text -> ProjectId -> Handler ()
watchOrUnwatchProject action msg project_id = do
user_id <- requireAuthId
project <- runYDB $ do
action user_id project_id
get404 project_id
alertSuccess (msg <> projectName project <> ".")
redirect $ ProjectR $ projectHandle project
--------------------------------------------------------------------------------
-- /c/#CommentId
getProjectCommentR :: Text -> CommentId -> Handler Html
getProjectCommentR project_handle comment_id = do
(muser, Entity project_id _, comment) <- checkComment project_handle comment_id
(widget, comment_tree) <-
makeProjectCommentTreeWidget
muser
project_id
project_handle
(Entity comment_id comment)
def
getMaxDepth
False
mempty
case muser of
Nothing -> return ()
Just (Entity user_id _) ->
runDB (userMaybeViewProjectCommentsDB user_id project_id (map entityKey (Tree.flatten comment_tree)))
defaultLayout (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/approve
getApproveProjectCommentR :: Text -> CommentId -> Handler Html
getApproveProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeApproveCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postApproveProjectCommentR :: Text -> CommentId -> Handler Html
postApproveProjectCommentR project_handle comment_id = do
(user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_approve user project_handle (Entity comment_id comment)
postApproveComment user_id comment_id comment
redirect (ProjectCommentR project_handle comment_id)
--------------------------------------------------------------------------------
-- /c/#CommentId/claim
getClaimProjectCommentR :: Text -> CommentId -> Handler Html
getClaimProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeClaimCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postClaimProjectCommentR :: Text -> CommentId -> Handler Html
postClaimProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_claim user project_handle (Entity comment_id comment)
postClaimComment
user
comment_id
comment
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectCommentR project_handle comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "claim" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/close
getCloseProjectCommentR :: Text -> CommentId -> Handler Html
getCloseProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeCloseCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postCloseProjectCommentR :: Text -> CommentId -> Handler Html
postCloseProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_close user project_handle (Entity comment_id comment)
postCloseComment
user
comment_id
comment
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectCommentR project_handle comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "close" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/delete
getDeleteProjectCommentR :: Text -> CommentId -> Handler Html
getDeleteProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeDeleteCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postDeleteProjectCommentR :: Text -> CommentId -> Handler Html
postDeleteProjectCommentR project_handle comment_id = do
(user, _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_delete user project_handle (Entity comment_id comment)
was_deleted <- postDeleteComment comment_id
if was_deleted
then redirect (ProjectDiscussionR project_handle)
else redirect (ProjectCommentR project_handle comment_id)
--------------------------------------------------------------------------------
-- /c/#CommentId/edit
getEditProjectCommentR :: Text -> CommentId -> Handler Html
getEditProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeEditCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postEditProjectCommentR :: Text -> CommentId -> Handler Html
postEditProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_edit user project_handle (Entity comment_id comment)
postEditComment
user
(Entity comment_id comment)
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectCommentR project_handle comment_id) -- Edit made.
Just (widget, form) -> defaultLayout $ previewWidget form "post" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/flag
getFlagProjectCommentR :: Text -> CommentId -> Handler Html
getFlagProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeFlagCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postFlagProjectCommentR :: Text -> CommentId -> Handler Html
postFlagProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_flag user project_handle (Entity comment_id comment)
postFlagComment
user
(Entity comment_id comment)
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectDiscussionR project_handle)
Just (widget, form) -> defaultLayout $ previewWidget form "flag" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/reply
getReplyProjectCommentR :: Text -> CommentId -> Handler Html
getReplyProjectCommentR project_handle parent_id = do
(widget, _) <- makeProjectCommentActionWidget makeReplyCommentWidget project_handle parent_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postReplyProjectCommentR :: Text -> CommentId -> Handler Html
postReplyProjectCommentR project_handle parent_id = do
(user, Entity _ project, parent) <- checkCommentRequireAuth project_handle parent_id
checkProjectCommentActionPermission can_reply user project_handle (Entity parent_id parent)
postNewComment
(Just parent_id)
user
(projectDiscussion project)
(makeProjectCommentActionPermissionsMap (Just user) project_handle def)
>>= \case
ConfirmedPost (Left err) -> do
alertDanger err
redirect $ ReplyProjectCommentR project_handle parent_id
ConfirmedPost (Right _) ->
redirect $ ProjectCommentR project_handle parent_id
Com.Preview (widget, form) ->
defaultLayout $ previewWidget form "post" $
projectDiscussionPage project_handle widget
--------------------------------------------------------------------------------
-- /c/#CommentId/rethread
getRethreadProjectCommentR :: Text -> CommentId -> Handler Html
getRethreadProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeRethreadCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postRethreadProjectCommentR :: Text -> CommentId -> Handler Html
postRethreadProjectCommentR project_handle comment_id = do
(user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_rethread user project_handle (Entity comment_id comment)
postRethreadComment user_id comment_id comment
--------------------------------------------------------------------------------
-- /c/#CommentId/retract
getRetractProjectCommentR :: Text -> CommentId -> Handler Html
getRetractProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeRetractCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postRetractProjectCommentR :: Text -> CommentId -> Handler Html
postRetractProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_retract user project_handle (Entity comment_id comment)
postRetractComment
user
comment_id
comment
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectCommentR project_handle comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "retract" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/tags
getProjectCommentTagsR :: Text -> CommentId -> Handler Html
getProjectCommentTagsR _ = getCommentTags
--------------------------------------------------------------------------------
-- /c/#CommentId/tag/#TagId
getProjectCommentTagR :: Text -> CommentId -> TagId -> Handler Html
getProjectCommentTagR _ = getCommentTagR
postProjectCommentTagR :: Text -> CommentId -> TagId -> Handler ()
postProjectCommentTagR _ = postCommentTagR
--------------------------------------------------------------------------------
-- /c/#CommentId/tag/apply, /c/#CommentId/tag/create
postProjectCommentApplyTagR, postProjectCommentCreateTagR:: Text -> CommentId -> Handler Html
postProjectCommentApplyTagR = applyOrCreate postCommentApplyTag
postProjectCommentCreateTagR = applyOrCreate postCommentCreateTag
applyOrCreate :: (CommentId -> Handler ()) -> Text -> CommentId -> Handler Html
applyOrCreate action project_handle comment_id = do
action comment_id
redirect (ProjectCommentR project_handle comment_id)
--------------------------------------------------------------------------------
-- /c/#CommentId/tag/new
getProjectCommentAddTagR :: Text -> CommentId -> Handler Html
getProjectCommentAddTagR project_handle comment_id = do
(user@(Entity user_id _), Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_add_tag user project_handle (Entity comment_id comment)
getProjectCommentAddTag comment_id project_id user_id
--------------------------------------------------------------------------------
-- /c/#CommentId/unclaim
getUnclaimProjectCommentR :: Text -> CommentId -> Handler Html
getUnclaimProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeUnclaimCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postUnclaimProjectCommentR :: Text -> CommentId -> Handler Html
postUnclaimProjectCommentR project_handle comment_id = do
(user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_unclaim user project_handle (Entity comment_id comment)
postUnclaimComment
user
comment_id
comment
(projectCommentHandlerInfo (Just user) project_id project_handle)
>>= \case
Nothing -> redirect (ProjectCommentR project_handle comment_id)
Just (widget, form) -> defaultLayout $ previewWidget form "unclaim" (projectDiscussionPage project_handle widget)
--------------------------------------------------------------------------------
-- /c/#CommentId/watch
getWatchProjectCommentR :: Text -> CommentId -> Handler Html
getWatchProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeWatchCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postWatchProjectCommentR ::Text -> CommentId -> Handler Html
postWatchProjectCommentR project_handle comment_id = do
(viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_watch viewer project_handle (Entity comment_id comment)
postWatchComment viewer_id comment_id
redirect (ProjectCommentR project_handle comment_id)
--------------------------------------------------------------------------------
-- /c/#CommentId/unwatch
getUnwatchProjectCommentR :: Text -> CommentId -> Handler Html
getUnwatchProjectCommentR project_handle comment_id = do
(widget, _) <- makeProjectCommentActionWidget makeUnwatchCommentWidget project_handle comment_id def getMaxDepth
defaultLayout (projectDiscussionPage project_handle widget)
postUnwatchProjectCommentR ::Text -> CommentId -> Handler Html
postUnwatchProjectCommentR project_handle comment_id = do
(viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id
checkProjectCommentActionPermission can_watch viewer project_handle (Entity comment_id comment)
postUnwatchComment viewer_id comment_id
redirect (ProjectCommentR project_handle comment_id)
--------------------------------------------------------------------------------
-- /contact
-- ProjectContactR stuff posts a private new topic to project discussion
getProjectContactR :: Text -> Handler Html
getProjectContactR project_handle = do
(project_contact_form, _) <- generateFormPost projectContactForm
Entity _ project <- runYDB $ getBy404 (UniqueProjectHandle project_handle)
defaultLayout $ do
snowdriftTitle $ "Contact " <> projectName project
$(widgetFile "project_contact")
postProjectContactR :: Text -> Handler Html
postProjectContactR project_handle = do
maybe_user_id <- maybeAuthId
((result, _), _) <- runFormPost projectContactForm
Entity _ project <- runYDB $ getBy404 (UniqueProjectHandle project_handle)
case result of
FormSuccess (content, language) -> do
_ <- runSDB (postApprovedCommentDB (fromMaybe anonymousUser maybe_user_id) Nothing (projectDiscussion project) content VisPrivate language)
alertSuccess "Comment submitted. Thank you for your input!"
_ -> alertDanger "Error occurred when submitting form."
redirect $ ProjectContactR project_handle
--------------------------------------------------------------------------------
-- /d
getProjectDiscussionR :: Text -> Handler Html
getProjectDiscussionR = getDiscussion . getProjectDiscussion
getProjectDiscussion :: Text -> (DiscussionId -> ExprCommentCond -> DB [Entity Comment]) -> Handler Html
getProjectDiscussion project_handle get_root_comments = do
muser <- maybeAuth
let muser_id = entityKey <$> muser
(Entity project_id project, root_comments) <- runYDB $ do
p@(Entity project_id project) <- getBy404 (UniqueProjectHandle project_handle)
let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id)
root_comments <- get_root_comments (projectDiscussion project) has_permission
return (p, root_comments)
(comment_forest_no_css, _) <-
makeProjectCommentForestWidget
muser
project_id
project_handle
root_comments
def
getMaxDepth
False
mempty
let has_comments = not (null root_comments)
comment_forest = do
comment_forest_no_css
toWidget $(cassiusFile "templates/comment.cassius")
(comment_form, _) <- generateFormPost commentNewTopicForm
defaultLayout $ do
snowdriftTitle $ projectName project <> " Discussion"
$(widgetFile "project_discuss")
--------------------------------------------------------------------------------
-- /d/new
getNewProjectDiscussionR :: Text -> Handler Html
getNewProjectDiscussionR project_handle = do
void requireAuth
let widget = commentNewTopicFormWidget
defaultLayout (projectDiscussionPage project_handle widget)
postNewProjectDiscussionR :: Text -> Handler Html
postNewProjectDiscussionR project_handle = do
user <- requireAuth
Entity _ Project{..} <- runYDB (getBy404 (UniqueProjectHandle project_handle))
postNewComment
Nothing
user
projectDiscussion
(makeProjectCommentActionPermissionsMap (Just user) project_handle def)
>>= \case
ConfirmedPost (Left err) -> do
alertDanger err
redirect $ NewProjectDiscussionR project_handle
ConfirmedPost (Right comment_id) ->
redirect $ ProjectCommentR project_handle comment_id
Com.Preview (widget, form) ->
defaultLayout $ previewWidget form "post" $
projectDiscussionPage project_handle widget
| chreekat/snowdrift | Handler/Project.hs | agpl-3.0 | 55,605 | 0 | 32 | 13,866 | 12,288 | 6,022 | 6,266 | -1 | -1 |
{- ORMOLU_DISABLE -}
-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)
-- Copyright 2015 2016, Mike MacHenry (mike.machenry@gmail.com)
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)
-- Released under the GNU AGPLV3+, see LICENSE
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Graphics.Implicit.ObjectUtil.GetImplicitShared (getImplicitShared, normalize) where
import {-# SOURCE #-} Graphics.Implicit.Primitives (Object(getImplicit'))
import Prelude (flip, (-), (*), (>), (<), (&&), (/), product, abs, (**), fmap, (.), negate, ($), const)
import Graphics.Implicit.Definitions
( objectRounding, ObjectContext, SharedObj(Empty, Full, Complement, UnionR, IntersectR, DifferenceR, Translate, Scale, Mirror, Shell, Outset, EmbedBoxedObj, WithRounding), ComponentWiseMultable((⋯/)), ℝ, minℝ )
import Graphics.Implicit.MathUtil (infty, rmax, rmaximum, rminimum, reflect)
-- Use getImplicit2 for handling extrusion of 2D shapes to 3D.
import Graphics.Implicit.ObjectUtil.GetBoxShared (VectorStuff(elements, uniformV))
import Linear (Metric(dot))
------------------------------------------------------------------------------
-- | Normalize a dimensionality-polymorphic vector.
normalize
:: forall f
. (VectorStuff (f ℝ), Metric f)
=> f ℝ
-> ℝ
normalize v =
let all1s = uniformV @(f ℝ) 1
in abs (product (elements v)) ** (1 / (all1s `dot` all1s))
-- Get a function that describes the surface of the object.
getImplicitShared
:: forall obj f
. ( Object obj (f ℝ)
, VectorStuff (f ℝ)
, ComponentWiseMultable (f ℝ)
, Metric f
)
=> ObjectContext
-> SharedObj obj (f ℝ)
-> f ℝ
-> ℝ
getImplicitShared _ Empty = const infty
getImplicitShared _ Full = const $ -infty
getImplicitShared ctx (Complement symbObj) =
negate . getImplicit' ctx symbObj
getImplicitShared ctx (UnionR _ []) =
getImplicitShared @obj ctx Empty
getImplicitShared ctx (UnionR r symbObjs) = \p ->
rminimum r $ fmap (flip (getImplicit' ctx) p) symbObjs
getImplicitShared ctx (IntersectR _ []) =
getImplicitShared @obj ctx Full
getImplicitShared ctx (IntersectR r symbObjs) = \p ->
rmaximum r $ fmap (flip (getImplicit' ctx) p) symbObjs
getImplicitShared ctx (DifferenceR _ symbObj []) =
getImplicit' ctx symbObj
getImplicitShared ctx (DifferenceR r symbObj symbObjs) =
let headObj = getImplicit' ctx symbObj
in
\p -> do
let
maxTail = rmaximum r
$ fmap (flip (getImplicitShared ctx) p . Complement) symbObjs
if maxTail > -minℝ && maxTail < minℝ
then rmax r (headObj p) minℝ
else rmax r (headObj p) maxTail
-- Simple transforms
getImplicitShared ctx (Translate v symbObj) = \p ->
getImplicit' ctx symbObj (p - v)
getImplicitShared ctx (Scale s symbObj) = \p ->
normalize s * getImplicit' ctx symbObj (p ⋯/ s)
getImplicitShared ctx (Mirror v symbObj) =
getImplicit' ctx symbObj . reflect v
-- Boundary mods
getImplicitShared ctx (Shell w symbObj) = \p ->
abs (getImplicit' ctx symbObj p) - w/2
getImplicitShared ctx (Outset d symbObj) = \p ->
getImplicit' ctx symbObj p - d
-- Misc
getImplicitShared _ (EmbedBoxedObj (obj,_)) = obj
getImplicitShared ctx (WithRounding r obj) = getImplicit' (ctx { objectRounding = r }) obj
| colah/ImplicitCAD | Graphics/Implicit/ObjectUtil/GetImplicitShared.hs | agpl-3.0 | 3,445 | 5 | 19 | 664 | 1,038 | 577 | 461 | 65 | 2 |
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
| Trickness/pl_learning | Haskell/function/sum.hs | unlicense | 71 | 0 | 9 | 24 | 60 | 29 | 31 | 3 | 1 |
lastButOne xs = if null xs || (length xs) < 2
then undefined
else
if (length xs) == 2
then head xs
else lastButOne (tail xs)
| RobertFischer/real-world-haskell | ch02/LastButOne.hs | unlicense | 211 | 0 | 9 | 112 | 64 | 32 | 32 | 5 | 3 |
module Problem035 where
import Data.List
main =
print $ length $ filter isCircular [2 .. 1000000]
isCircular = all isPrime . rotate
rotate x = take n $ map ((read :: String -> Int) . take n) $ tails $ take (2 * n) $ cycle s
where s = show x
n = length s
isPrime x = isPrime' primes x
where isPrime' (p:ps) x
| p * p > x = True
| x `rem` p == 0 = False
| otherwise = isPrime' ps x
primes = 2 : 3 : filter (f primes) [5, 7 ..]
where f (p:ps) x = p * p > x || x `rem` p /= 0 && f ps x
| vasily-kartashov/playground | euler/problem-035.hs | apache-2.0 | 543 | 0 | 13 | 181 | 286 | 146 | 140 | 15 | 1 |
module Util where
import Control.DeepSeq (NFData, force)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Debug.Trace as Trace
import Numeric (showFFloat)
import Text.ParserCombinators.Parsec (parse)
import Imports
eol :: Parser String
eol = try (string "\n\r")
<|> try (string "\r\n")
<|> string "\n"
<|> string "\r"
decimal :: Read a => Parser a
decimal = read <$> many1 digit
pad :: Parser String
pad = many $ char ' '
padded :: Parser a -> Parser a
padded = between pad pad
-- a :: String
-- a = parseOrDie eol "\n\n"
parseOrDie :: Parser a -> String -> a
parseOrDie p s = either
(error . show)
id
(parse p "parseOrDie" s)
replaceAll :: Eq a => [a] -> [a] -> [a] -> [a]
replaceAll from to = intercalate to . splitOn from
-- Examples:
-- s <- readInput "Y15.D01"
-- Y15.D14.solve1 <$> readInput "Y15.D14"
readInput :: String -> IO String
readInput name = readFile $ "res/" ++ replaceAll "." "/" (take 7 name) ++ ".txt"
-- trace
tr :: Show a => String -> a -> a
tr s x = trace (s <> ": " <> show x) x
trace :: String -> a -> a
trace = Trace.trace
traceShow :: Show a => a -> b -> b
traceShow = Trace.traceShow
traceShowId :: Show a => a -> a
traceShowId = Trace.traceShowId
timeOf :: NFData a => IO a -> IO (a, Integer)
timeOf ioa = do
start <- timeInMillis
a <- force <$> ioa
void $ evaluate a
end <- timeInMillis
pure (a, end - start)
where
timeInMillis = ceiling . (1000 *) <$> getPOSIXTime
size2humanSize :: Integer -> String
size2humanSize i =
flip fix (fromIntegral i::Float, "BKMGTPEZY") $ \l (n, u:units) ->
if n <= 999.9 || null units
then showFFloat (Just $ if u == 'B' then 0 else 1) n [u]
else l (n / 1024, units)
| oshyshko/adventofcode | src/Util.hs | bsd-3-clause | 1,865 | 0 | 12 | 536 | 680 | 356 | 324 | 49 | 3 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Numeral.MY.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.MY.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "MY Tests"
[ makeCorpusTest [This Numeral] corpus
]
| rfranek/duckling | tests/Duckling/Numeral/MY/Tests.hs | bsd-3-clause | 600 | 0 | 9 | 96 | 80 | 51 | 29 | 11 | 1 |
module Dixi.PatchUtils where
import Data.Foldable
import Data.Monoid
import Data.Patch (Patch)
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Patch as P
import qualified Data.Text as T
type PatchSummary = (Int, Int, Int)
patchSummary :: Patch a -> PatchSummary
patchSummary p | (Sum a, Sum b, Sum c) <- mconcat (map toCounts $ P.toList p) = (a,b,c)
where toCounts (P.Insert {}) = (Sum 1, Sum 0, Sum 0)
toCounts (P.Delete {}) = (Sum 0, Sum 1, Sum 0)
toCounts (P.Replace {}) = (Sum 0, Sum 0, Sum 1)
patchToText :: Patch Char -> Text
patchToText = T.pack . toList . patchToVector
patchToVector :: Patch Char -> Vector Char
patchToVector = flip P.apply mempty
| liamoc/dixi | Dixi/PatchUtils.hs | bsd-3-clause | 713 | 0 | 13 | 142 | 313 | 169 | 144 | 18 | 3 |
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface,
TypeOperators #-}
-- |
-- Module: Data.BloomFilter.Hash
-- Copyright: Bryan O'Sullivan
-- License: BSD3
--
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: unstable
-- Portability: portable
--
-- Fast hashing of Haskell values. The hash functions used are Bob
-- Jenkins's public domain functions, which combine high performance
-- with excellent mixing properties. For more details, see
-- <http://burtleburtle.net/bob/hash/>.
--
-- In addition to the usual "one input, one output" hash functions,
-- this module provides multi-output hash functions, suitable for use
-- in applications that need multiple hashes, such as Bloom filtering.
module Data.BloomFilter.Hash
(
-- * Basic hash functionality
Hashable(..)
, hash32
, hash64
, hashSalt32
, hashSalt64
-- * Compute a family of hash values
, hashes
, cheapHashes
-- * Hash functions for 'Storable' instances
, hashOne32
, hashOne64
, hashList32
, hashList64
) where
import Control.Monad (foldM)
import Data.Bits ((.&.), (.|.), xor)
import Data.BloomFilter.Util (FastShift(..))
import Data.List (unfoldr)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Word (Word8, Word16, Word32, Word64)
import Foreign.C.String (CString)
import Foreign.C.Types (CInt, CSize)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Array (allocaArray, withArrayLen)
import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)
import Foreign.Storable (Storable, peek, poke, sizeOf)
import System.IO.Unsafe (unsafePerformIO)
import Data.ByteString.Internal (ByteString(..))
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy.Internal as LB
import qualified Data.ByteString.Lazy as LB
#include "HsBaseConfig.h"
-- Make sure we're not performing any expensive arithmetic operations.
-- import Prelude hiding ((/), (*), div, divMod, mod, rem)
foreign import ccall unsafe "lookup3.h _jenkins_hashword" hashWord
:: Ptr Word32 -> CSize -> Word32 -> IO Word32
foreign import ccall unsafe "lookup3.h _jenkins_hashword2" hashWord2
:: Ptr Word32 -> CSize -> Ptr Word32 -> Ptr Word32 -> IO ()
foreign import ccall unsafe "lookup3.h _jenkins_hashlittle" hashLittle
:: Ptr a -> CSize -> Word32 -> IO Word32
foreign import ccall unsafe "lookup3.h _jenkins_hashlittle2" hashLittle2
:: Ptr a -> CSize -> Ptr Word32 -> Ptr Word32 -> IO ()
class Hashable a where
-- | Compute a 32-bit hash of a value. The salt value perturbs
-- the result.
hashIO32 :: a -- ^ value to hash
-> Word32 -- ^ salt
-> IO Word32
-- | Compute a 64-bit hash of a value. The first salt value
-- perturbs the first element of the result, and the second salt
-- perturbs the second.
hashIO64 :: a -- ^ value to hash
-> Word64 -- ^ salt
-> IO Word64
hashIO64 v salt = do
let s1 = fromIntegral (salt `shiftR` 32) .&. maxBound
s2 = fromIntegral salt
h1 <- hashIO32 v s1
h2 <- hashIO32 v s2
return $ (fromIntegral h1 `shiftL` 32) .|. fromIntegral h2
-- | Compute a 32-bit hash.
hash32 :: Hashable a => a -> Word32
hash32 = hashSalt32 0x106fc397
hash64 :: Hashable a => a -> Word64
hash64 = hashSalt64 0x106fc397cf62f64d3
-- | Compute a salted 32-bit hash.
hashSalt32 :: Hashable a => Word32 -- ^ salt
-> a -- ^ value to hash
-> Word32
{-# INLINE hashSalt32 #-}
hashSalt32 salt k = unsafePerformIO $ hashIO32 k salt
-- | Compute a salted 64-bit hash.
hashSalt64 :: Hashable a => Word64 -- ^ salt
-> a -- ^ value to hash
-> Word64
{-# INLINE hashSalt64 #-}
hashSalt64 salt k = unsafePerformIO $ hashIO64 k salt
-- | Compute a list of 32-bit hashes. The value to hash may be
-- inspected as many times as there are hashes requested.
hashes :: Hashable a => Int -- ^ number of hashes to compute
-> a -- ^ value to hash
-> [Word32]
hashes n v = unfoldr go (n,0x3f56da2d3ddbb9f6)
where go (k,s) | k <= 0 = Nothing
| otherwise = let s' = hashSalt32 s v
in Just (s', (k-1,s'))
-- | Compute a list of 32-bit hashes relatively cheaply. The value to
-- hash is inspected at most twice, regardless of the number of hashes
-- requested.
--
-- We use a variant of Kirsch and Mitzenmacher's technique from \"Less
-- Hashing, Same Performance: Building a Better Bloom Filter\",
-- <http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf>.
--
-- Where Kirsch and Mitzenmacher multiply the second hash by a
-- coefficient, we shift right by the coefficient. This offers better
-- performance (as a shift is much cheaper than a multiply), and the
-- low order bits of the final hash stay well mixed.
cheapHashes :: Hashable a => Int -- ^ number of hashes to compute
-> a -- ^ value to hash
-> [Word32]
{-# SPECIALIZE cheapHashes :: Int -> SB.ByteString -> [Word32] #-}
{-# SPECIALIZE cheapHashes :: Int -> LB.ByteString -> [Word32] #-}
{-# SPECIALIZE cheapHashes :: Int -> String -> [Word32] #-}
cheapHashes k v = go 0
where go i | i == j = []
| otherwise = hash : go (i + 1)
where !hash = h1 + (h2 `shiftR` i)
h1 = fromIntegral (h `shiftR` 32)
h2 = fromIntegral h
h = hashSalt64 0x9150a946c4a8966e v
j = fromIntegral k
instance Hashable () where
hashIO32 _ salt = return salt
instance Hashable Integer where
hashIO32 k salt | k < 0 = hashIO32 (unfoldr go (-k))
(salt `xor` 0x3ece731e9c1c64f8)
| otherwise = hashIO32 (unfoldr go k) salt
where go 0 = Nothing
go i = Just (fromIntegral i :: Word32, i `shiftR` 32)
instance Hashable Bool where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Ordering where
hashIO32 = hashIO32 . fromEnum
hashIO64 = hashIO64 . fromEnum
instance Hashable Char where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Int where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Float where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Double where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Int8 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Int16 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Int32 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Int64 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Word8 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Word16 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Word32 where
hashIO32 = hashOne32
hashIO64 = hashOne64
instance Hashable Word64 where
hashIO32 = hashOne32
hashIO64 = hashOne64
-- | A fast unchecked shift. Nasty, but otherwise GHC 6.8.2 does a
-- test and branch on every shift.
div4 :: CSize -> CSize
div4 k = fromIntegral ((fromIntegral k :: HTYPE_SIZE_T) `shiftR` 2)
alignedHash :: Ptr a -> CSize -> Word32 -> IO Word32
alignedHash ptr bytes salt
| bytes .&. 3 == 0 = hashWord (castPtr ptr) (div4 bytes) salt'
| otherwise = hashLittle ptr bytes salt'
where salt' = fromIntegral salt
-- Inlined from Foreign.Marshal.Utils, for performance reasons.
with :: Storable a => a -> (Ptr a -> IO b) -> IO b
with val f =
alloca $ \ptr -> do
poke ptr val
f ptr
alignedHash2 :: Ptr a -> CSize -> Word64 -> IO Word64
alignedHash2 ptr bytes salt =
with (fromIntegral salt) $ \sp -> do
let p1 = castPtr sp
p2 = castPtr sp `plusPtr` 4
doubleHash ptr bytes p1 p2
peek sp
doubleHash :: Ptr a -> CSize -> Ptr Word32 -> Ptr Word32 -> IO ()
doubleHash ptr bytes p1 p2
| bytes .&. 3 == 0 = hashWord2 (castPtr ptr) (div4 bytes) p1 p2
| otherwise = hashLittle2 ptr bytes p1 p2
instance Hashable SB.ByteString where
hashIO32 bs salt = unsafeUseAsCStringLen bs $ \ptr len ->
alignedHash ptr (fromIntegral len) salt
{-# INLINE hashIO64 #-}
hashIO64 bs salt = unsafeUseAsCStringLen bs $ \ptr len ->
alignedHash2 ptr (fromIntegral len) salt
rechunk :: LB.ByteString -> [SB.ByteString]
rechunk s | LB.null s = []
| otherwise = let (pre,suf) = LB.splitAt chunkSize s
in repack pre : rechunk suf
where repack = SB.concat . LB.toChunks
chunkSize = fromIntegral LB.defaultChunkSize
instance Hashable LB.ByteString where
hashIO32 bs salt = foldM (flip hashIO32) salt (rechunk bs)
{-# INLINE hashIO64 #-}
hashIO64 = hashChunks
instance Hashable a => Hashable (Maybe a) where
hashIO32 Nothing salt = return salt
hashIO32 (Just k) salt = hashIO32 k salt
hashIO64 Nothing salt = return salt
hashIO64 (Just k) salt = hashIO64 k salt
instance (Hashable a, Hashable b) => Hashable (Either a b) where
hashIO32 (Left a) salt = hashIO32 a salt
hashIO32 (Right b) salt = hashIO32 b (salt + 1)
hashIO64 (Left a) salt = hashIO64 a salt
hashIO64 (Right b) salt = hashIO64 b (salt + 1)
instance (Hashable a, Hashable b) => Hashable (a, b) where
hashIO32 (a,b) salt = hashIO32 a salt >>= hashIO32 b
hashIO64 (a,b) salt = hashIO64 a salt >>= hashIO64 b
instance (Hashable a, Hashable b, Hashable c) => Hashable (a, b, c) where
hashIO32 (a,b,c) salt = hashIO32 a salt >>= hashIO32 b >>= hashIO32 c
instance (Hashable a, Hashable b, Hashable c, Hashable d) =>
Hashable (a, b, c, d) where
hashIO32 (a,b,c,d) salt =
hashIO32 a salt >>= hashIO32 b >>= hashIO32 c >>= hashIO32 d
instance (Hashable a, Hashable b, Hashable c, Hashable d, Hashable e) =>
Hashable (a, b, c, d, e) where
hashIO32 (a,b,c,d,e) salt =
hashIO32 a salt >>= hashIO32 b >>= hashIO32 c >>= hashIO32 d >>= hashIO32 e
instance Storable a => Hashable [a] where
hashIO32 = hashList32
{-# INLINE hashIO64 #-}
hashIO64 = hashList64
-- | Compute a 32-bit hash of a 'Storable' instance.
hashOne32 :: Storable a => a -> Word32 -> IO Word32
hashOne32 k salt = with k $ \ptr ->
alignedHash ptr (fromIntegral (sizeOf k)) salt
-- | Compute a 64-bit hash of a 'Storable' instance.
hashOne64 :: Storable a => a -> Word64 -> IO Word64
hashOne64 k salt = with k $ \ptr ->
alignedHash2 ptr (fromIntegral (sizeOf k)) salt
-- | Compute a 32-bit hash of a list of 'Storable' instances.
hashList32 :: Storable a => [a] -> Word32 -> IO Word32
hashList32 xs salt =
withArrayLen xs $ \len ptr ->
alignedHash ptr (fromIntegral (len * sizeOf (head xs))) salt
-- | Compute a 64-bit hash of a list of 'Storable' instances.
hashList64 :: Storable a => [a] -> Word64 -> IO Word64
hashList64 xs salt =
withArrayLen xs $ \len ptr ->
alignedHash2 ptr (fromIntegral (len * sizeOf (head xs))) salt
unsafeUseAsCStringLen :: SB.ByteString -> (CString -> Int -> IO a) -> IO a
unsafeUseAsCStringLen (PS fp o l) action =
withForeignPtr fp $ \p -> action (p `plusPtr` o) l
type HashState = Ptr Word32
foreign import ccall unsafe "lookup3.h _jenkins_little2_begin" c_begin
:: Ptr Word32 -> Ptr Word32 -> HashState -> IO ()
foreign import ccall unsafe "lookup3.h _jenkins_little2_frag" c_frag
:: Ptr a -> CSize -> HashState -> CSize -> IO CSize
foreign import ccall unsafe "lookup3.h _jenkins_little2_step" c_step
:: Ptr a -> CSize -> HashState -> IO CSize
foreign import ccall unsafe "lookup3.h _jenkins_little2_end" c_end
:: CInt -> Ptr Word32 -> Ptr Word32 -> HashState -> IO ()
unsafeAdjustCStringLen :: SB.ByteString -> Int -> (CString -> Int -> IO a)
-> IO a
unsafeAdjustCStringLen (PS fp o l) d action
| d > l = action nullPtr 0
| otherwise = withForeignPtr fp $ \p -> action (p `plusPtr` (o + d)) (l - d)
hashChunks :: LB.ByteString -> Word64 -> IO Word64
hashChunks s salt = do
with (fromIntegral salt) $ \sp -> do
let p1 = castPtr sp
p2 = castPtr sp `plusPtr` 4
allocaArray 3 $ \st -> do
let step :: LB.ByteString -> Int -> IO Int
step (LB.Chunk x xs) off = do
unread <- unsafeAdjustCStringLen x off $ \ptr len ->
c_step ptr (fromIntegral len) st
if unread > 0
then frag xs unread
else step xs 0
step _ _ = return 0
frag :: LB.ByteString -> CSize -> IO Int
frag c@(LB.Chunk x xs) stoff = do
nstoff <- unsafeUseAsCStringLen x $ \ptr len -> do
c_frag ptr (fromIntegral len) st stoff
if nstoff == 12
then step c (fromIntegral (nstoff - stoff))
else frag xs nstoff
frag LB.Empty stoff = return (fromIntegral (12 - stoff))
c_begin p1 p2 st
unread <- step s 0
c_end (fromIntegral unread) p1 p2 st
peek sp
| jsa/hs-bloomfilter | Data/BloomFilter/Hash.hs | bsd-3-clause | 13,337 | 0 | 27 | 3,571 | 3,723 | 1,938 | 1,785 | 262 | 5 |
{-# LANGUAGE RecordWildCards #-}
module EditKit.Buffer
( Buffer(..)
, Cursor(..)
, fromFile
, isValidCursor
) where
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
data Buffer = Buffer
{ lines :: {-# UNPACK #-} !(Vector Text)
, cursor :: {-# UNPACK #-} !Cursor
} deriving (Show)
data Cursor = Cursor
{ cursorLine :: {-# UNPACK #-} !Int
, cursorColumn :: {-# UNPACK #-} !Int
} deriving (Eq, Ord)
instance Show Cursor where
show Cursor{..} = show cursorLine ++ ":" ++ show cursorColumn
fromFile :: FilePath -> IO Buffer
fromFile file = Buffer . V.fromList . T.lines <$> T.readFile file <*> pure (Cursor 0 0)
isValidCursor :: Buffer -> Cursor -> Bool
isValidCursor Buffer{..} Cursor{..} =
cursorLine >= 0 &&
cursorLine < V.length lines &&
cursorColumn >= 0 &&
cursorColumn <= T.length (lines V.! cursorLine)
| rasendubi/edit-kit | edit-kit/EditKit/Buffer.hs | bsd-3-clause | 962 | 0 | 11 | 199 | 322 | 179 | 143 | 29 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE FlexibleContexts #-}
-- |
-- Module : Streamly.Memory.Internal.Unicode.Array
-- Copyright : (c) 2018 Composewell Technologies
--
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Stability : experimental
-- Portability : GHC
--
module Streamly.Internal.Memory.Unicode.Array
(
-- * Streams of Strings
lines
, words
, unlines
, unwords
)
where
import Control.Monad.IO.Class (MonadIO)
import Streamly (IsStream, MonadAsync)
import Prelude hiding (String, lines, words, unlines, unwords)
import Streamly.Memory.Array (Array)
import qualified Streamly.Internal.Data.Unicode.Stream as S
import qualified Streamly.Memory.Array as A
-- | Break a string up into a stream of strings at newline characters.
-- The resulting strings do not contain newlines.
--
-- > lines = S.lines A.write
--
-- >>> S.toList $ lines $ S.fromList "lines\nthis\nstring\n\n\n"
-- ["lines","this","string","",""]
--
{-# INLINE lines #-}
lines :: (MonadIO m, IsStream t) => t m Char -> t m (Array Char)
lines = S.lines A.write
-- | Break a string up into a stream of strings, which were delimited
-- by characters representing white space.
--
-- > words = S.words A.write
--
-- >>> S.toList $ words $ S.fromList "A newline\nis considered white space?"
-- ["A", "newline", "is", "considered", "white", "space?"]
--
{-# INLINE words #-}
words :: (MonadIO m, IsStream t) => t m Char -> t m (Array Char)
words = S.words A.write
-- | Flattens the stream of @Array Char@, after appending a terminating
-- newline to each string.
--
-- 'unlines' is an inverse operation to 'lines'.
--
-- >>> S.toList $ unlines $ S.fromList ["lines", "this", "string"]
-- "lines\nthis\nstring\n"
--
-- > unlines = S.unlines A.read
--
-- Note that, in general
--
-- > unlines . lines /= id
{-# INLINE unlines #-}
unlines :: (MonadIO m, IsStream t) => t m (Array Char) -> t m Char
unlines = S.unlines A.read
-- | Flattens the stream of @Array Char@, after appending a separating
-- space to each string.
--
-- 'unwords' is an inverse operation to 'words'.
--
-- >>> S.toList $ unwords $ S.fromList ["unwords", "this", "string"]
-- "unwords this string"
--
-- > unwords = S.unwords A.read
--
-- Note that, in general
--
-- > unwords . words /= id
{-# INLINE unwords #-}
unwords :: (MonadAsync m, IsStream t) => t m (Array Char) -> t m Char
unwords = S.unwords A.read
| harendra-kumar/asyncly | src/Streamly/Internal/Memory/Unicode/Array.hs | bsd-3-clause | 2,418 | 0 | 9 | 444 | 364 | 230 | 134 | 26 | 1 |
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_GLASGOW_HASKELL
#define MIN_VERSION_GLASGOW_HASKELL(a,b,c,d) 0
#endif
-- MIN_VERSION_GLASGOW_HASKELL was introduced in GHC 7.10
#if MIN_VERSION_GLASGOW_HASKELL(7,10,0,0)
#else
{-# LANGUAGE OverlappingInstances #-}
#endif
-- | This module provides a generalized implementation of data types à la carte
-- [1]. It supports (higher-order) functors with 0 or more functorial parameters
-- and additional non-functorial parameters, all with a uniform interface.
--
-- \[1\] W. Swierstra. Data Types à la Carte.
-- /Journal of Functional Programming/, 18(4):423-436, 2008,
-- <http://dx.doi.org/10.1017/S0956796808006758>.
--
-- (This module is preferably used with the GHC extensions @DataKinds@ and
-- @PolyKinds@.)
--
-- = Usage
--
-- Compared to traditional data types à la carte, an extra poly-kinded parameter
-- has been added to ':+:' and to the parameters of ':<:'. Standard data types à
-- la carte is obtained by setting this parameter to @()@. That gives us the
-- following type for 'Inl':
--
-- @`Inl` :: h1 () a -> (h1 `:+:` h2) () a@
--
-- Here, @h1 ()@ and @(h1 `:+:` h2) ()@ are functors.
--
-- By setting the extra parameter to a functor @f :: * -> *@, we obtain this
-- type:
--
-- @`Inl` :: h1 f a -> (h1 `:+:` h2) f a@
--
-- This makes @h1@ and @(h1 `:+:` h2)@ higher-order functors.
--
-- Finally, by setting the parameter to a type-level pair of functors
-- @'(f,g) :: (* -> *, * -> *)@, we obtain this type:
--
-- @`Inl` :: h1 '(f,g) a -> (h1 `:+:` h2) '(f,g) a@
--
-- This makes @h1@ and @(h1 `:+:` h2)@ higher-order bi-functors.
--
-- Alternatively, we can represent all three cases above using heterogeneous
-- lists of functors constructed using @'(,)@ and terminated by @()@:
--
-- @
-- `Inl` :: h1 () a -> (h1 `:+:` h2) () a -- functor
-- `Inl` :: h1 '(f,()) a -> (h1 `:+:` h2) '(f,()) a -- higher-order functor
-- `Inl` :: h1 '(f,'(g,())) a -> (h1 `:+:` h2) '(f,'(g,())) a -- higher-order bi-functor
-- @
--
-- This view is taken by the classes 'HFunctor' and 'HBifunctor'. An 'HFunctor'
-- takes a parameter of kind @(* -> *, k)@; i.e. it has /at least/ one
-- functorial parameter. A 'HBiFunctor' takes a parameter of kind
-- @(* -> *, (* -> *, k))@; i.e. it has /at least/ two functorial parameters.
--
-- = Aliases for parameter lists
--
-- To avoid ugly types such as @'(f,'(g,()))@, this module exports the synonyms
-- 'Param0', 'Param1', 'Param2', etc. for parameter lists up to size 4. These
-- synonyms allow the module to be used without the @DataKinds@ extension.
--
-- = Extra type parameters
--
-- Recall that an 'HFunctor' takes a parameter of kind @(* -> *, k)@, and an
-- 'HBifunctor' takes a parameter of kind @(* -> *, (* -> *, k))@. Since @k@ is
-- polymorphic, it means that it is possible to add extra parameters in place of
-- @k@.
--
-- For example, a user can define the following type representing addition in
-- some language:
--
-- @
-- data Add fs a where
-- Add :: (`Num` a, pred a) => f a -> f a -> Add (`Param2` f pred) a
--
-- instance `HFunctor` Add where
-- `hfmap` f (Add a b) = Add (f a) (f b)
-- @
--
-- Here, @Add@ has a functorial parameter @f@, and an extra non-functorial
-- parameter @pred@ that provides a constraint for the type @a@.
--
-- An obvious alternative would have been to just make @pred@ a separate
-- parameter to @Add@:
--
-- @
-- data Add pred fs a where
-- Add :: (`Num` a, pred a) => f a -> f a -> Add pred (`Param1` f) a
--
-- instance `HFunctor` (Add pred) where
-- `hfmap` f (Add a b) = Add (f a) (f b)
-- @
--
-- However, this has the disadvantage of being hard to use together with the
-- ':<:' class. For example, we might want to define the following \"smart
-- constructor\" for @Add@:
--
-- @
-- mkAdd :: (`Num` a, pred a, Add pred `:<:` h) => f a -> f a -> h (`Param1` f) a
-- mkAdd a b = `inj` (Add a b)
-- @
--
-- Unfortunately, the above type is ambiguous, because @pred@ is completely
-- free. Assuming that @h@ is a type of the form @(... `:+:` Add `Show` `:+:` ...)@,
-- we would like to infer @(pred ~ `Show`)@, but this would require extra
-- machinery, such as a type family that computes @pred@ from @h@.
--
-- By putting @pred@ in the parameter list, we avoid the above problem. We also
-- get the advantage that the same @pred@ parameter is distributed to all types
-- in a sum constructed using ':+:'. This makes it easier to, for example,
-- change the @pred@ parameter uniformly throughout an expression.
module Data.ALaCarte where
-- | Coproducts
data (h1 :+: h2) fs a
= Inl (h1 fs a)
| Inr (h2 fs a)
#if __GLASGOW_HASKELL__>=708
deriving (Functor)
#endif
infixr :+:
-- | A constraint @f `:<:` g@ expresses that the signature @f@ is subsumed by
-- @g@, i.e. @f@ can be used to construct elements in @g@.
class sub :<: sup
where
inj :: sub fs a -> sup fs a
prj :: sup fs a -> Maybe (sub fs a)
instance {-# OVERLAPPING #-} (f :<: f)
where
inj = id
prj = Just
instance {-# OVERLAPPING #-} (f :<: (f :+: g))
where
inj = Inl
prj (Inl f) = Just f
prj _ = Nothing
instance {-# OVERLAPPING #-} (f :<: h) => (f :<: (g :+: h))
where
inj = Inr . inj
prj (Inr h) = prj h
prj _ = Nothing
-- | Higher-order functors
class HFunctor h
where
-- | Higher-order 'fmap'
hfmap :: (forall b . f b -> g b) -> h '(f,fs) a -> h '(g,fs) a
instance (HFunctor h1, HFunctor h2) => HFunctor (h1 :+: h2)
where
hfmap f (Inl i) = Inl (hfmap f i)
hfmap f (Inr i) = Inr (hfmap f i)
-- | Higher-order bi-functors
class HFunctor h => HBifunctor h
where
-- | Higher-order \"bimap\"
hbimap :: (Functor f, Functor g)
=> (forall b . f b -> g b)
-> (forall b . i b -> j b)
-> h '(f,'(i,fs)) a
-> h '(g,'(j,fs)) a
instance (HBifunctor h1, HBifunctor h2) => HBifunctor (h1 :+: h2)
where
hbimap f g (Inl i) = Inl (hbimap f g i)
hbimap f g (Inr i) = Inr (hbimap f g i)
--------------------------------------------------------------------------------
-- * Parameter lists
--------------------------------------------------------------------------------
-- | Empty parameter list
type Param0 = ()
-- | Singleton parameter list
type Param1 a = '(a,Param0)
-- | Two-element parameter list
type Param2 a b = '(a, Param1 b)
-- | Three-element parameter list
type Param3 a b c = '(a, Param2 b c)
-- | Four-element parameter list
type Param4 a b c d = '(a, Param3 b c d)
| emilaxelsson/operational-alacarte | src/Data/ALaCarte.hs | bsd-3-clause | 6,497 | 8 | 15 | 1,410 | 818 | 501 | 317 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Graphomania.Shumov.Internal
( ShumovBinary (..)
, ShumovEdge (..)
, ShumovVertexBinary (..)
, readShumov
, writeShumov
, unsafeConvertShumov
) where
import Control.DeepSeq
import Control.Monad
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Int
import Data.MonoTraversable
import Data.Proxy
import Data.Tagged
import GHC.Generics (Generic)
import Graphomania.Utils.Binary
import System.Endian
data ShumovEdge = ShumovEdge
{ _edgeTag :: !Int16
, _nodeId :: !Int64
} deriving ( Show, Eq, Ord )
instance (EndiannessAware e) => Binary (Tagged e ShumovEdge) where
get = do
edgeTag <- untag <$> (get :: Get (Tagged e Int16))
nodeId <- untag <$> (get :: Get (Tagged e Int64))
return $ Tagged $ ShumovEdge
{ _edgeTag = edgeTag
, _nodeId = nodeId
}
put (Tagged ShumovEdge {..}) = do
put (Tagged _edgeTag :: Tagged e Int16)
put (Tagged _nodeId :: Tagged e Int64)
data ShumovVertexHeader = ShumovVertexHeader
{ _externalId :: !ByteString
, _edgeCount :: !Int32
} deriving ( Show, Eq, Ord )
instance (EndiannessAware e) => Binary (Tagged e ShumovVertexHeader) where
get = do
idSize <- untag <$> (get :: Get (Tagged e Int16))
externalId <- getByteString (fromIntegral idSize)
edgeCount <- untag <$> (get :: Get (Tagged e Int32))
return $ Tagged $ ShumovVertexHeader
{ _externalId = externalId
, _edgeCount = edgeCount
}
put (Tagged ShumovVertexHeader {..}) = do
put (Tagged (fromIntegral $ BS.length _externalId) :: Tagged e Int16)
putByteString _externalId
put (Tagged _edgeCount :: Tagged e Int32)
data ShumovVertexBinary e = ShumovVertexBinary
{ _vertexHeader :: !ShumovVertexHeader
, _edges :: !ByteString
} deriving ( Show, Eq, Ord ) -- TODO: redefine Show, Eq, Ord classes.
instance (EndiannessAware e) => Binary (ShumovVertexBinary e) where
get = do
vertexHeader <- untag <$> (get :: Get (Tagged e ShumovVertexHeader))
edges <- getByteString (fromIntegral $ _edgeCount vertexHeader * 10)
return ShumovVertexBinary
{ _vertexHeader = vertexHeader
, _edges = edges
}
put ShumovVertexBinary {..} = do
put (Tagged _vertexHeader :: Tagged e ShumovVertexHeader)
putByteString _edges
newtype ShumovBinary e = ShumovBinary { unShumov :: ByteString } deriving (Generic)
instance NFData (ShumovBinary e)
type instance Element (ShumovBinary e) = ShumovVertexBinary e
instance (EndiannessAware e) => MonoFoldable (ShumovBinary e) where
ofoldr f z = go z . unShumov
where
go z s | BS.null s = z
| otherwise = let (x, xs) = runGetStrict get s
in f x (go z xs)
ofoldMap = error "Data.Graph.Shumov.ofoldMap"
ofoldr1Ex = error "Data.Graph.Shumov.ofoldr1Ex"
ofoldl1Ex' = error "Data.Graph.Shumov.ofoldl1Ex'"
ofoldl' f v = go v . unShumov
where
go !a !s | BS.null s = a
| otherwise = let (x, xs) = runGetStrict get s
in go (f a x) xs
ofoldlM f v = go v . unShumov
where
go !a !s | BS.null s = pure a
| otherwise = let (x, xs) = runGetStrict get s
in f a x >>= flip go xs
readShumov :: (EndiannessAware e) => FilePath -> IO (ShumovBinary e)
readShumov = fmap ShumovBinary . BS.readFile
writeShumov :: (EndiannessAware e) => FilePath -> (ShumovBinary e) -> IO ()
writeShumov path = BS.writeFile path . unShumov
--TODO: consider streaming instead of inplace conversion
-- | Inplace edge encoding conversion
-- This function will rewrite source buffer and return unused part.
unsafeConverEdge :: forall from to . (EndiannessAware from, EndiannessAware to)
=> Proxy from -> Proxy to -> ByteString -> IO ByteString
unsafeConverEdge _ _ bs = do
let edge = untag $ fst $ runGetStrict (get :: Get (Tagged from ShumovEdge)) bs
unsafePutStrict (put (Tagged edge :: (Tagged to ShumovEdge))) bs
unsafeConverVertex :: forall from to . (EndiannessAware from, EndiannessAware to)
=> Proxy from -> Proxy to -> ByteString -> IO ByteString
unsafeConverVertex from to bs = do
let vertexHeader = untag $ fst $ runGetStrict (get :: Get (Tagged from ShumovVertexHeader)) bs
edgesS <- unsafePutStrict (put (Tagged vertexHeader :: (Tagged to ShumovVertexHeader))) bs
foldM (const . unsafeConverEdge from to) edgesS [1 .. _edgeCount vertexHeader]
unsafeConvertShumov :: forall from to . (EndiannessAware from, EndiannessAware to)
=> ShumovBinary from -> IO (ShumovBinary to)
unsafeConvertShumov ShumovBinary {..} = go unShumov
where
go s | BS.null s = return $ ShumovBinary unShumov
| otherwise = unsafeConverVertex (Proxy :: Proxy from) (Proxy :: Proxy to) s >>= go
| schernichkin/BSPM | graphomania/src/Graphomania/Shumov/Internal.hs | bsd-3-clause | 5,453 | 0 | 15 | 1,428 | 1,642 | 839 | 803 | 126 | 1 |
module Singletons.T29 where
import Data.Singletons.TH
import Prelude.Singletons
$(singletons [d|
foo :: Bool -> Bool
foo x = not $ x
-- test that $ works with function composition
bar :: Bool -> Bool
bar x = not . not . not $ x
baz :: Bool -> Bool
baz x = not $! x
-- test that $! works with function composition
ban :: Bool -> Bool
ban x = not . not . not $! x
|])
foo1a :: Proxy (Foo True)
foo1a = Proxy
foo1b :: Proxy False
foo1b = foo1b
bar1a :: Proxy (Bar True)
bar1a = Proxy
bar1b :: Proxy False
bar1b = bar1b
baz1a :: Proxy (Baz True)
baz1a = Proxy
baz1b :: Proxy False
baz1b = baz1b
ban1a :: Proxy (Ban True)
ban1a = Proxy
ban1b :: Proxy False
ban1b = ban1b
| goldfirere/singletons | singletons-base/tests/compile-and-dump/Singletons/T29.hs | bsd-3-clause | 701 | 0 | 7 | 173 | 159 | 87 | 72 | -1 | -1 |
module Render
( getAspectRatio
, getRenderFunctions
, setViewport
) where
import Control.Monad
import Data.Array
import Data.Char
import Data.IORef
import Foreign.Marshal
import Graphics.UI.GLFW
import Graphics.Rendering.OpenGL hiding (position)
import Actor as A
import Game
import GraphUtils
import Level
import Text
import Vector
hudHeight = 0.2
solid :: GLfloat
solid = 1
fullLevelSize = addBorder . levelSize
where addBorder (w,h) = (w+2,h+2)
getAspectRatio level = fromIntegral lh / fromIntegral lw + hudHeight
where (lw,lh) = fullLevelSize level
setViewport ref size@(Size w h) = do
lr <- readIORef ref
let r = (fromIntegral h/fromIntegral w)
r' = recip r
lr' = recip lr
s = 2*min (max 1 (min lr' r')) (max (r/lr) lr')
viewport $= (Position 0 0,size)
matrixMode $= Projection
loadIdentity
scale (s*min 1 r) (s*min 1 r') (1 :: GLfloat)
translate $ Vector3 (-0.5) (-0.5*lr) (0 :: GLfloat)
matrixMode $= Modelview 0
setAspectRatio ref val = do
writeIORef ref val
setViewport ref =<< get windowSize
getRenderFunctions aspectRatio charset = do
let displayText = uncurry displayString charset
rgbOverlay <- createTexture 24 24 True $ flip pokeArray $
concat [if b then [95,95,95,255] else c | y <- [0..23], x <- [0..23],
let c = case x `div` 4 `mod` 3 of
0 -> [255,191,191,255]
1 -> [191,255,191,255]
2 -> [191,191,255,255]
b = x `mod` 4 == 0 || x < 12 && y `mod` 12 == 0 || x >= 12 && y `mod` 12 == 6
]
return (renderGame aspectRatio displayText rgbOverlay
,renderMenu aspectRatio displayText rgbOverlay
)
renderMenu aspectRatio displayText rgbOverlay score items item = do
let charSize = 0.006
textCol = Color4 1 0 0 solid
activeCol = Color4 0.93 0.79 0 solid
menu = "DUNGEONS OF WOR":"":"":items++["","","HIGH SCORE "++show score]
setAspectRatio aspectRatio 1
clear [ColorBuffer]
loadIdentity
texture Texture2D $= Enabled
forM_ (zip menu [-3..]) $ \(text,i) -> do
color $ if i == item then activeCol else textCol
displayText (0.5-(fromIntegral (length text)*4*charSize))
(0.5+charSize*(7*fromIntegral (length items-1-2*i)))
charSize text
renderOverlay rgbOverlay
flush
swapBuffers
renderGame aspectRatio displayText rgbOverlay levelState levelCount scores lives = do
let curLevel = level levelState
(lw,lh) = fullLevelSize curLevel
height = fromIntegral lh / fromIntegral lw
magn = 1 / fromIntegral lw
setAspectRatio aspectRatio (getAspectRatio curLevel)
clear [ColorBuffer]
loadIdentity
renderHud displayText height scores lives (actors levelState) levelCount curLevel
preservingMatrix $ do
translate $ Vector3 0 hudHeight (0 :: GLfloat)
scale magn magn (1 :: GLfloat)
renderLevel curLevel
renderBullets (bullets levelState)
renderActors (actors levelState)
renderOverlay rgbOverlay
flush
swapBuffers
renderOverlay rgbOverlay = do
texture Texture2D $= Enabled
textureBinding Texture2D $= Just rgbOverlay
blendFunc $= (Zero,SrcColor)
color $ Color4 1 1 1 solid
let pscale = 100
renderPrimitive Quads $ do
texCoord2 0 0
vertex3 0 0 0
texCoord2 pscale 0
vertex3 1 0 0
texCoord2 pscale pscale
vertex3 1 1 0
texCoord2 0 pscale
vertex3 0 1 0
blendFunc $= (SrcAlpha,OneMinusSrcAlpha)
renderLevel level = do
let (lw,lh) = fullLevelSize level
height = fromIntegral lh / fromIntegral lw
entries = [((y,x),[]) | (_,y,x) <- entrances level]
texture Texture2D $= Disabled
color $ Color4 0.2 0.5 1 solid
forM_ (entries ++ assocs (legalMoves level)) $ \((y,x),ms) -> do
let xc = fromIntegral (x+1)
yc = fromIntegral (lh-y-2)
unless (North `elem` ms) $ drawRectangle xc (yc+0.95) 1 0.05
unless (South `elem` ms) $ drawRectangle xc yc 1 0.05
unless (East `elem` ms) $ drawRectangle (xc+0.95) yc 0.05 1
unless (West `elem` ms) $ drawRectangle xc yc 0.05 1
renderActors as = do
let players = filter ((`elem` [BlueWorrior,YellowWorrior]) . actorType) as
texture Texture2D $= Enabled
color $ Color4 1 1 1 solid
forM_ as $ \a -> do
let V x y = A.position a
x' = fromIntegral x / fromIntegral fieldSize
y' = fromIntegral y / fromIntegral fieldSize
dist = case actorType a of
Garwor -> 2*fieldSize
Thorwor -> fieldSize
_ -> maxBound
visible = any ((\(V px py) -> abs (x-px) < dist || abs (y-py) < dist) . A.position) players
when (visible && (not . null . animation) a) $
drawSprite (head (animation a)) (1.1+x') (1.1+y') 0.8 0.8 (facing a)
renderBullets bs = do
texture Texture2D $= Disabled
color $ Color4 1 0.3 0.1 solid
forM_ bs $ \(_,V x y) -> do
let x' = fromIntegral x / fromIntegral fieldSize
y' = fromIntegral y / fromIntegral fieldSize
drawRectangle (1.45+x') (1.45+y') 0.1 0.1
renderHud displayText height scores lives actors levelCount level = do
let r = Color4 1 0 0 solid
b = Color4 0.25 0.63 1 solid
y = Color4 0.93 0.79 0 solid
d = Color4 0 0 0 solid
charSize = 0.0028
radarTitle = if levelCount == 1 then "RADAR" else
case levelName level of
"pit" -> "THE PIT"
"arena" -> "THE ARENA"
_ -> "DUNGEON " ++ show levelCount
(levelW,levelH) = levelSize level
scoreB = hudHeight / 4
scoreW = 0.3
scoreH = scoreB*3
radarB = charSize
radarW = radarF*fromIntegral levelW
radarH = hudHeight-radarB*4-charSize*10
radarF = radarH/fromIntegral levelH
snum1 = show (scores !! 0)
snum2 = show (scores !! 1)
lnum1 = show (lives !! 0)
lnum2 = show (lives !! 1)
numPlayers = length lives
texture Texture2D $= Disabled
color b
drawRectangle 0 0 scoreW scoreH
drawRectangle (0.5-radarW/2-radarB) 0 (radarW+radarB*2) (radarH+radarB*2)
color y
drawRectangle (1-scoreW) 0 scoreW scoreH
color d
drawRectangle scoreB scoreB (scoreW-2*scoreB) (scoreH-2*scoreB)
drawRectangle (1-scoreW+scoreB) scoreB (scoreW-2*scoreB) (scoreH-2*scoreB)
drawRectangle (0.5-radarW/2) radarB radarW radarH
forM_ actors $ \actor -> do
let (fx,fy) = fieldPos (position actor)
rx = 0.5-radarW/2+radarF*fromIntegral fx
ry = radarB+radarF*fromIntegral fy
case actorType actor of
Burwor -> color b >> drawRectangle rx ry radarF radarF
Garwor -> color y >> drawRectangle rx ry radarF radarF
Thorwor -> color r >> drawRectangle rx ry radarF radarF
_ -> return ()
texture Texture2D $= Enabled
color y
displayText (1-scoreB-(fromIntegral (length snum1)*8*charSize)) (scoreB+scoreH/2-scoreB-5*charSize) charSize snum1
displayText (1-scoreW-3*radarB-(fromIntegral (length lnum1)*8*charSize)) (scoreB+scoreH/2-scoreB-5*charSize) charSize lnum1
when (numPlayers > 1) $ do
color b
displayText (scoreW-scoreB-(fromIntegral (length snum2)*8*charSize)) (scoreB+scoreH/2-scoreB-5*charSize) charSize snum2
displayText (scoreW+3*radarB) (scoreB+scoreH/2-scoreB-5*charSize) charSize lnum2
color r
displayText (0.5-(fromIntegral (length radarTitle)*4*charSize)) (radarH+radarB*3) charSize radarTitle
drawRectangle :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()
drawRectangle x y sx sy = renderPrimitive Quads $ mapM_ vertex
[Vertex3 x y 0, Vertex3 (x+sx) y 0, Vertex3 (x+sx) (y+sy) 0, Vertex3 x (y+sy) 0]
drawSprite :: TextureObject -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> Direction -> IO ()
drawSprite tid x y sx sy dir = do
let (u1,v1,u2,v2,u3,v3,u4,v4) = case dir of
North -> (1,1,1,0,0,0,0,1)
East -> (1,1,0,1,0,0,1,0)
South -> (0,1,0,0,1,0,1,1)
West -> (0,1,1,1,1,0,0,0)
textureBinding Texture2D $= Just tid
renderPrimitive Quads $ do
texCoord2 u1 v1
vertex3 x y 0
texCoord2 u2 v2
vertex3 (x+sx) y 0
texCoord2 u3 v3
vertex3 (x+sx) (y+sy) 0
texCoord2 u4 v4
vertex3 x (y+sy) 0
| cobbpg/dow | src/Render.hs | bsd-3-clause | 8,252 | 0 | 26 | 2,127 | 3,545 | 1,771 | 1,774 | 209 | 7 |
{-|
Module : DeepControl.Arrow
Description : Deepened the usual Control.Arrow module.
Copyright : (c) Ross Paterson 2002,
(c) 2015 KONISHI Yohsuke
License : BSD-style (see the LICENSE file in the distribution)
Maintainer : ocean0yohsuke@gmail.com
Stability : experimental
Portability : ---
-}
module DeepControl.Arrow (
module Control.Arrow,
Kleisli2(..),
Kleisli3(..),
Kleisli4(..),
Kleisli5(..),
) where
import DeepControl.Applicative
import DeepControl.Traversable
import DeepControl.Monad
import Control.Arrow
import Prelude hiding (id, (.))
import Control.Category
----------------------------------------------------------------------
-- Kleisli2
newtype Kleisli2 m1 m2 a b = Kleisli2 { runKleisli2 :: a -> m1 (m2 b) }
instance (Monad m1, Monad m2, Traversable m2) => Category (Kleisli2 m1 m2) where
id = Kleisli2 $ (.**)
(Kleisli2 g) . (Kleisli2 f) = Kleisli2 $ f >>=> g
instance (Monad m1, Monad m2, Traversable m2) => Arrow (Kleisli2 m1 m2) where
arr f = Kleisli2 $ (.**) . f
first (Kleisli2 f) = Kleisli2 $ \ ~(b,d) -> f b >>== \c -> (.**) (c,d)
second (Kleisli2 f) = Kleisli2 $ \ ~(d,b) -> f b >>== \c -> (.**) (d,c)
----------------------------------------------------------------------
-- Kleisli3
newtype Kleisli3 m1 m2 m3 a b = Kleisli3 { runKleisli3 :: a -> m1 (m2 (m3 b)) }
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3) => Category (Kleisli3 m1 m2 m3) where
id = Kleisli3 $ (.***)
(Kleisli3 g) . (Kleisli3 f) = Kleisli3 $ f >>>=> g
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3) => Arrow (Kleisli3 m1 m2 m3) where
arr f = Kleisli3 $ (.***) . f
first (Kleisli3 f) = Kleisli3 $ \ ~(b,d) -> f b >>>= \c -> (.***) (c,d)
second (Kleisli3 f) = Kleisli3 $ \ ~(d,b) -> f b >>>= \c -> (.***) (d,c)
----------------------------------------------------------------------
-- Kleisli4
newtype Kleisli4 m1 m2 m3 m4 a b = Kleisli4 { runKleisli4 :: a -> m1 (m2 (m3 (m4 b))) }
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3, Monad m4, Traversable m4) => Category (Kleisli4 m1 m2 m3 m4) where
id = Kleisli4 $ (.****)
(Kleisli4 g) . (Kleisli4 f) = Kleisli4 $ f >>>>=> g
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3, Monad m4, Traversable m4) => Arrow (Kleisli4 m1 m2 m3 m4) where
arr f = Kleisli4 $ (.****) . f
first (Kleisli4 f) = Kleisli4 $ \ ~(b,d) -> f b >>>>= \c -> (.****) (c,d)
second (Kleisli4 f) = Kleisli4 $ \ ~(d,b) -> f b >>>>= \c -> (.****) (d,c)
----------------------------------------------------------------------
-- Kleisli5
newtype Kleisli5 m1 m2 m3 m4 m5 a b = Kleisli5 { runKleisli5 :: a -> m1 (m2 (m3 (m4 (m5 b)))) }
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3, Monad m4, Traversable m4, Monad m5, Traversable m5) => Category (Kleisli5 m1 m2 m3 m4 m5) where
id = Kleisli5 $ (.*****)
(Kleisli5 g) . (Kleisli5 f) = Kleisli5 $ f >>>>>=> g
instance (Monad m1, Monad m2, Traversable m2, Monad m3, Traversable m3, Monad m4, Traversable m4, Monad m5, Traversable m5) => Arrow (Kleisli5 m1 m2 m3 m4 m5) where
arr f = Kleisli5 $ (.*****) . f
first (Kleisli5 f) = Kleisli5 $ \ ~(b,d) -> f b >>>>>= \c -> (.*****) (c,d)
second (Kleisli5 f) = Kleisli5 $ \ ~(d,b) -> f b >>>>>= \c -> (.*****) (d,c)
| ocean0yohsuke/deepcontrol | DeepControl/Arrow.hs | bsd-3-clause | 3,396 | 0 | 16 | 709 | 1,381 | 760 | 621 | 44 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runStderrLoggingT)
import Database.Persist
import Database.Persist.Postgresql
import Database.Persist.TH
import DB.Schema
--Needs to fetch real login info from ENV later
connectionString ="host=localhost user=postgres dbname=catsandbox password=scalasandboxserver port=5432"
main :: IO ()
main = runStderrLoggingT $ withPostgresqlPool connectionString 10 $ \pool ->
liftIO $
flip runSqlPersistMPool pool $ do
runMigration migrateAll
liftIO $ print "Migrate Complete"
| AlexaDeWit/haskellsandboxserver | app/Migrate.hs | bsd-3-clause | 800 | 0 | 11 | 166 | 122 | 70 | 52 | 19 | 1 |
-- | Build instance tycons for the PData and PDatas type families.
--
-- TODO: the PData and PDatas cases are very similar.
-- We should be able to factor out the common parts.
module Vectorise.Generic.PData
( buildPDataTyCon
, buildPDatasTyCon )
where
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Utils
import BasicTypes
import BuildTyCl
import DataCon
import TyCon
import Type
import FamInstEnv
import Name
import Util
import MonadUtils
import Control.Monad
-- buildPDataTyCon ------------------------------------------------------------
-- | Build the PData instance tycon for a given type constructor.
buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDataTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDataTyConOcc orig_name
rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr
pdata <- builtin pdataTyCon
buildDataFamInst name' pdata vect_tc rhs
where
orig_name = tyConName orig_tc
buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst
buildDataFamInst name' fam_tc vect_tc rhs
= do { axiom_name <- mkDerivedName mkInstTyCoOcc name'
; let fam_inst = mkDataFamInst axiom_name tyvars fam_tc pat_tys rep_tc
ax = famInstAxiom fam_inst
pat_tys = [mkTyConApp vect_tc (mkTyVarTys tyvars)]
rep_tc = buildAlgTyCon name'
tyvars
Nothing
[] -- no stupid theta
rhs
rec_flag -- FIXME: is this ok?
False -- not GADT syntax
(FamInstTyCon ax fam_tc pat_tys)
; return fam_inst }
where
tyvars = tyConTyVars vect_tc
rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDataTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDataDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDataDataConOcc orig_name
comp_tys <- mkSumTys repr_sel_ty mkPDataType repr
liftDs $ buildDataCon dc_name
False -- not infix
(map (const HsNoBang) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
-- buildPDatasTyCon -----------------------------------------------------------
-- | Build the PDatas instance tycon for a given type constructor.
buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDatasTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDatasTyConOcc orig_name
rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr
pdatas <- builtin pdatasTyCon
buildDataFamInst name' pdatas vect_tc rhs
where
orig_name = tyConName orig_tc
buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDatasTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDatasDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name
comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr
liftDs $ buildDataCon dc_name
False -- not infix
(map (const HsNoBang) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
-- Utils ----------------------------------------------------------------------
-- | Flatten a SumRepr into a list of data constructor types.
mkSumTys
:: (SumRepr -> Type)
-> (Type -> VM Type)
-> SumRepr
-> VM [Type]
mkSumTys repr_selX_ty mkTc repr
= sum_tys repr
where
sum_tys EmptySum = return []
sum_tys (UnarySum r) = con_tys r
sum_tys d@(Sum { repr_cons = cons })
= liftM (repr_selX_ty d :) (concatMapM con_tys cons)
con_tys (ConRepr _ r) = prod_tys r
prod_tys EmptyProd = return []
prod_tys (UnaryProd r) = liftM singleton (comp_ty r)
prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps
comp_ty r = mkTc (compOrigType r)
{-
mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
mk_fam_inst fam_tc arg_tc
= (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
-}
| nomeata/ghc | compiler/vectorise/Vectorise/Generic/PData.hs | bsd-3-clause | 5,726 | 0 | 13 | 1,938 | 1,152 | 582 | 570 | 108 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty
import Data.Monoid (mconcat)
main = scotty 80 $ do
get "/:word" $ do
beam <- param "word"
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"] | dimarwix/titso | app/Main.hs | bsd-3-clause | 228 | 0 | 13 | 48 | 71 | 37 | 34 | 8 | 1 |
module Norm.AllNormalizations where
import CoreS.AST
import NormalizationStrategies
import Norm.NormFor
import Norm.CompAssignment
import AlphaR
import Norm.VarDecl
import Norm.ElimRedundant
import Norm.ElimDead
import Norm.IfElseEmpty
import Norm.DoWToWhile
import Norm.FloatToDouble
import Norm.SumsOfProducts
import Norm.ForIndex
import Norm.StepOp
import Norm.ForIndexConstLessThanEq
normalizations :: Normalizer CompilationUnit
normalizations = [ alphaRenaming, normForIndex, normForToWhile, normCompAss
, normMoveForTVD, normSingleTVDs, normVDIArrLeft
, normSplitInit, normVDTop ,normSortT
, normFlattenBlock, normEmptyBlock, normFilterEmpty
, normSingleton, normDeadIf, normDeadDo
, normDeadWhile, normDeadFor, normDoWToWhile
, normIESiEmpty, normIESeEmpty, normIEBothEmpty
, normStepFor, normStepSExpr, normStepExpr
, normFloatToDoubleVars, normFloatToDoubleRet, normSOP
, normForIndexCLTE
]
| DATX02-17-26/DATX02-17-26 | libsrc/Norm/AllNormalizations.hs | gpl-2.0 | 1,072 | 0 | 5 | 251 | 177 | 112 | 65 | 27 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.AttachInternetGateway
-- 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)
--
-- Attaches an Internet gateway to a VPC, enabling connectivity between the
-- Internet and the VPC. For more information about your VPC and Internet
-- gateway, see the
-- <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/ Amazon Virtual Private Cloud User Guide>.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachInternetGateway.html AWS API Reference> for AttachInternetGateway.
module Network.AWS.EC2.AttachInternetGateway
(
-- * Creating a Request
attachInternetGateway
, AttachInternetGateway
-- * Request Lenses
, aigDryRun
, aigInternetGatewayId
, aigVPCId
-- * Destructuring the Response
, attachInternetGatewayResponse
, AttachInternetGatewayResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'attachInternetGateway' smart constructor.
data AttachInternetGateway = AttachInternetGateway'
{ _aigDryRun :: !(Maybe Bool)
, _aigInternetGatewayId :: !Text
, _aigVPCId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AttachInternetGateway' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aigDryRun'
--
-- * 'aigInternetGatewayId'
--
-- * 'aigVPCId'
attachInternetGateway
:: Text -- ^ 'aigInternetGatewayId'
-> Text -- ^ 'aigVPCId'
-> AttachInternetGateway
attachInternetGateway pInternetGatewayId_ pVPCId_ =
AttachInternetGateway'
{ _aigDryRun = Nothing
, _aigInternetGatewayId = pInternetGatewayId_
, _aigVPCId = pVPCId_
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
aigDryRun :: Lens' AttachInternetGateway (Maybe Bool)
aigDryRun = lens _aigDryRun (\ s a -> s{_aigDryRun = a});
-- | The ID of the Internet gateway.
aigInternetGatewayId :: Lens' AttachInternetGateway Text
aigInternetGatewayId = lens _aigInternetGatewayId (\ s a -> s{_aigInternetGatewayId = a});
-- | The ID of the VPC.
aigVPCId :: Lens' AttachInternetGateway Text
aigVPCId = lens _aigVPCId (\ s a -> s{_aigVPCId = a});
instance AWSRequest AttachInternetGateway where
type Rs AttachInternetGateway =
AttachInternetGatewayResponse
request = postQuery eC2
response = receiveNull AttachInternetGatewayResponse'
instance ToHeaders AttachInternetGateway where
toHeaders = const mempty
instance ToPath AttachInternetGateway where
toPath = const "/"
instance ToQuery AttachInternetGateway where
toQuery AttachInternetGateway'{..}
= mconcat
["Action" =: ("AttachInternetGateway" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"DryRun" =: _aigDryRun,
"InternetGatewayId" =: _aigInternetGatewayId,
"VpcId" =: _aigVPCId]
-- | /See:/ 'attachInternetGatewayResponse' smart constructor.
data AttachInternetGatewayResponse =
AttachInternetGatewayResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AttachInternetGatewayResponse' with the minimum fields required to make a request.
--
attachInternetGatewayResponse
:: AttachInternetGatewayResponse
attachInternetGatewayResponse = AttachInternetGatewayResponse'
| fmapfmapfmap/amazonka | amazonka-ec2/gen/Network/AWS/EC2/AttachInternetGateway.hs | mpl-2.0 | 4,346 | 0 | 11 | 841 | 521 | 316 | 205 | 71 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SWF.RegisterActivityType
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Registers a new /activity type/ along with its configuration settings in the
-- specified domain.
--
-- A 'TypeAlreadyExists' fault is returned if the type already exists in the
-- domain. You cannot change any configuration settings of the type after its
-- registration, and it must be registered as a new version. Access Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys. 'defaultTaskList.name': String constraint. The key
-- is 'swf:defaultTaskList.name'. 'name': String constraint. The key is 'swf:name'. 'version': String constraint. The key is 'swf:version'. If the caller does not have
-- sufficient permissions to invoke the action, or the parameter values fall
-- outside the specified constraints, the action fails. The associated event
-- attribute's cause parameter will be set to OPERATION_NOT_PERMITTED. For
-- details and example IAM policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to AmazonSWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_RegisterActivityType.html>
module Network.AWS.SWF.RegisterActivityType
(
-- * Request
RegisterActivityType
-- ** Request constructor
, registerActivityType
-- ** Request lenses
, ratDefaultTaskHeartbeatTimeout
, ratDefaultTaskList
, ratDefaultTaskPriority
, ratDefaultTaskScheduleToCloseTimeout
, ratDefaultTaskScheduleToStartTimeout
, ratDefaultTaskStartToCloseTimeout
, ratDescription
, ratDomain
, ratName
, ratVersion
-- * Response
, RegisterActivityTypeResponse
-- ** Response constructor
, registerActivityTypeResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data RegisterActivityType = RegisterActivityType
{ _ratDefaultTaskHeartbeatTimeout :: Maybe Text
, _ratDefaultTaskList :: Maybe TaskList
, _ratDefaultTaskPriority :: Maybe Text
, _ratDefaultTaskScheduleToCloseTimeout :: Maybe Text
, _ratDefaultTaskScheduleToStartTimeout :: Maybe Text
, _ratDefaultTaskStartToCloseTimeout :: Maybe Text
, _ratDescription :: Maybe Text
, _ratDomain :: Text
, _ratName :: Text
, _ratVersion :: Text
} deriving (Eq, Read, Show)
-- | 'RegisterActivityType' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ratDefaultTaskHeartbeatTimeout' @::@ 'Maybe' 'Text'
--
-- * 'ratDefaultTaskList' @::@ 'Maybe' 'TaskList'
--
-- * 'ratDefaultTaskPriority' @::@ 'Maybe' 'Text'
--
-- * 'ratDefaultTaskScheduleToCloseTimeout' @::@ 'Maybe' 'Text'
--
-- * 'ratDefaultTaskScheduleToStartTimeout' @::@ 'Maybe' 'Text'
--
-- * 'ratDefaultTaskStartToCloseTimeout' @::@ 'Maybe' 'Text'
--
-- * 'ratDescription' @::@ 'Maybe' 'Text'
--
-- * 'ratDomain' @::@ 'Text'
--
-- * 'ratName' @::@ 'Text'
--
-- * 'ratVersion' @::@ 'Text'
--
registerActivityType :: Text -- ^ 'ratDomain'
-> Text -- ^ 'ratName'
-> Text -- ^ 'ratVersion'
-> RegisterActivityType
registerActivityType p1 p2 p3 = RegisterActivityType
{ _ratDomain = p1
, _ratName = p2
, _ratVersion = p3
, _ratDescription = Nothing
, _ratDefaultTaskStartToCloseTimeout = Nothing
, _ratDefaultTaskHeartbeatTimeout = Nothing
, _ratDefaultTaskList = Nothing
, _ratDefaultTaskPriority = Nothing
, _ratDefaultTaskScheduleToStartTimeout = Nothing
, _ratDefaultTaskScheduleToCloseTimeout = Nothing
}
-- | If set, specifies the default maximum time before which a worker processing a
-- task of this type must report progress by calling 'RecordActivityTaskHeartbeat'. If the timeout is exceeded, the activity task is automatically timed out. This default can be overridden when scheduling an activity task using the
-- 'ScheduleActivityTask' 'Decision'. If the activity worker subsequently attempts
-- to record a heartbeat or returns a result, the activity worker receives an 'UnknownResource' fault. In this case, Amazon SWF no longer considers the activity task to be
-- valid; the activity worker should clean up the activity task.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- The value "NONE" can be used to specify unlimited duration.
ratDefaultTaskHeartbeatTimeout :: Lens' RegisterActivityType (Maybe Text)
ratDefaultTaskHeartbeatTimeout =
lens _ratDefaultTaskHeartbeatTimeout
(\s a -> s { _ratDefaultTaskHeartbeatTimeout = a })
-- | If set, specifies the default task list to use for scheduling tasks of this
-- activity type. This default task list is used if a task list is not provided
-- when a task is scheduled through the 'ScheduleActivityTask' 'Decision'.
ratDefaultTaskList :: Lens' RegisterActivityType (Maybe TaskList)
ratDefaultTaskList =
lens _ratDefaultTaskList (\s a -> s { _ratDefaultTaskList = a })
-- | The default task priority to assign to the activity type. If not assigned,
-- then "0" will be used. Valid values are integers that range from Java's 'Integer.MIN_VALUE' (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers indicate
-- higher priority.
--
-- For more information about setting task priority, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
ratDefaultTaskPriority :: Lens' RegisterActivityType (Maybe Text)
ratDefaultTaskPriority =
lens _ratDefaultTaskPriority (\s a -> s { _ratDefaultTaskPriority = a })
-- | If set, specifies the default maximum duration for a task of this activity
-- type. This default can be overridden when scheduling an activity task using
-- the 'ScheduleActivityTask' 'Decision'.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- The value "NONE" can be used to specify unlimited duration.
ratDefaultTaskScheduleToCloseTimeout :: Lens' RegisterActivityType (Maybe Text)
ratDefaultTaskScheduleToCloseTimeout =
lens _ratDefaultTaskScheduleToCloseTimeout
(\s a -> s { _ratDefaultTaskScheduleToCloseTimeout = a })
-- | If set, specifies the default maximum duration that a task of this activity
-- type can wait before being assigned to a worker. This default can be
-- overridden when scheduling an activity task using the 'ScheduleActivityTask' 'Decision'.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- The value "NONE" can be used to specify unlimited duration.
ratDefaultTaskScheduleToStartTimeout :: Lens' RegisterActivityType (Maybe Text)
ratDefaultTaskScheduleToStartTimeout =
lens _ratDefaultTaskScheduleToStartTimeout
(\s a -> s { _ratDefaultTaskScheduleToStartTimeout = a })
-- | If set, specifies the default maximum duration that a worker can take to
-- process tasks of this activity type. This default can be overridden when
-- scheduling an activity task using the 'ScheduleActivityTask' 'Decision'.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- The value "NONE" can be used to specify unlimited duration.
ratDefaultTaskStartToCloseTimeout :: Lens' RegisterActivityType (Maybe Text)
ratDefaultTaskStartToCloseTimeout =
lens _ratDefaultTaskStartToCloseTimeout
(\s a -> s { _ratDefaultTaskStartToCloseTimeout = a })
-- | A textual description of the activity type.
ratDescription :: Lens' RegisterActivityType (Maybe Text)
ratDescription = lens _ratDescription (\s a -> s { _ratDescription = a })
-- | The name of the domain in which this activity is to be registered.
ratDomain :: Lens' RegisterActivityType Text
ratDomain = lens _ratDomain (\s a -> s { _ratDomain = a })
-- | The name of the activity type within the domain.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '/' (slash), '|' (vertical bar), or any control characters
-- (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal
-- string quotarnquot.
ratName :: Lens' RegisterActivityType Text
ratName = lens _ratName (\s a -> s { _ratName = a })
-- | The version of the activity type.
--
-- The activity type consists of the name and version, the combination of which
-- must be unique within the domain. The specified string must not start or end
-- with whitespace. It must not contain a ':' (colon), '/' (slash), '|' (vertical
-- bar), or any control characters (\u0000-\u001f | \u007f - \u009f). Also, it
-- must not contain the literal string quotarnquot.
ratVersion :: Lens' RegisterActivityType Text
ratVersion = lens _ratVersion (\s a -> s { _ratVersion = a })
data RegisterActivityTypeResponse = RegisterActivityTypeResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'RegisterActivityTypeResponse' constructor.
registerActivityTypeResponse :: RegisterActivityTypeResponse
registerActivityTypeResponse = RegisterActivityTypeResponse
instance ToPath RegisterActivityType where
toPath = const "/"
instance ToQuery RegisterActivityType where
toQuery = const mempty
instance ToHeaders RegisterActivityType
instance ToJSON RegisterActivityType where
toJSON RegisterActivityType{..} = object
[ "domain" .= _ratDomain
, "name" .= _ratName
, "version" .= _ratVersion
, "description" .= _ratDescription
, "defaultTaskStartToCloseTimeout" .= _ratDefaultTaskStartToCloseTimeout
, "defaultTaskHeartbeatTimeout" .= _ratDefaultTaskHeartbeatTimeout
, "defaultTaskList" .= _ratDefaultTaskList
, "defaultTaskPriority" .= _ratDefaultTaskPriority
, "defaultTaskScheduleToStartTimeout" .= _ratDefaultTaskScheduleToStartTimeout
, "defaultTaskScheduleToCloseTimeout" .= _ratDefaultTaskScheduleToCloseTimeout
]
instance AWSRequest RegisterActivityType where
type Sv RegisterActivityType = SWF
type Rs RegisterActivityType = RegisterActivityTypeResponse
request = post "RegisterActivityType"
response = nullResponse RegisterActivityTypeResponse
| kim/amazonka | amazonka-swf/gen/Network/AWS/SWF/RegisterActivityType.hs | mpl-2.0 | 11,914 | 0 | 9 | 2,501 | 1,048 | 647 | 401 | 114 | 1 |
module Tests.Language.Interpreter
( interpreterTests
)
where
import Test.Framework ( Test
, testGroup
)
import Tests.Language.Interpreter.Blocks
( interpreterBlockTests )
import Tests.Language.Interpreter.Expressions
( interpreterExpressionTests )
import Tests.Language.Interpreter.Functions
( interpreterFunctionTests )
import Tests.Language.Interpreter.If ( interpreterIfTests )
import Tests.Language.Interpreter.Lists
( interpreterListTests )
import Tests.Language.Interpreter.Loops
( interpreterLoopTests )
import Tests.Language.Interpreter.Operators
( interpreterOperatorTests )
import Tests.Language.Interpreter.Scoping
( interpreterScopingTests )
interpreterTests :: Test
interpreterTests = testGroup
"Interpreter Tests"
[ interpreterBlockTests
, interpreterExpressionTests
, interpreterFunctionTests
, interpreterIfTests
, interpreterListTests
, interpreterLoopTests
, interpreterOperatorTests
, interpreterScopingTests
]
| rumblesan/improviz | test/Tests/Language/Interpreter.hs | bsd-3-clause | 1,496 | 0 | 6 | 644 | 160 | 104 | 56 | 30 | 1 |
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, MagicHash,
UnboxedTuples #-}
module Main (main) where
import Control.Monad.ST
import Criterion.Main
import Data.Hashable
import Data.Hashable.SipHash
import Data.Int
import Foreign.ForeignPtr
import GHC.Exts
import GHC.ST (ST(..))
import Data.Word
import Foreign.C.Types (CInt(..), CLong(..), CSize(..))
import Foreign.Ptr
import Data.ByteString.Internal
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Crypto.MAC.SipHash as HS
import qualified Data.ByteString.Char8 as B8
-- Benchmark English words (5 and 8), base64 encoded integers (11),
-- SHA1 hashes as hex (40), and large blobs (1 Mb).
main :: IO ()
main = do
-- We do not actually care about the contents of these pointers.
fp5 <- mallocForeignPtrBytes 5
fp8 <- mallocForeignPtrBytes 8
fp11 <- mallocForeignPtrBytes 11
fp40 <- mallocForeignPtrBytes 40
fp128 <- mallocForeignPtrBytes 128
fp512 <- mallocForeignPtrBytes 512
let !mb = 2^(20 :: Int) -- 1 Mb
fp1Mb <- mallocForeignPtrBytes mb
-- We don't care about the contents of these either.
let !ba5 = new 5; !ba8 = new 8; !ba11 = new 11; !ba40 = new 40
!ba128 = new 128; !ba512 = new 512; !ba1Mb = new mb
s5 = ['\0'..'\4']; s8 = ['\0'..'\7']; s11 = ['\0'..'\10']
s40 = ['\0'..'\39']; s128 = ['\0'..'\127']; s512 = ['\0'..'\511']
s1Mb = ['\0'..'\999999']
!bs5 = B8.pack s5; !bs8 = B8.pack s8; !bs11 = B8.pack s11
!bs40 = B8.pack s40; !bs128 = B8.pack s128; !bs512 = B8.pack s512
!bs1Mb = B8.pack s1Mb
blmeg = BL.take (fromIntegral mb) . BL.fromChunks . repeat
bl5 = BL.fromChunks [bs5]; bl8 = BL.fromChunks [bs8]
bl11 = BL.fromChunks [bs11]; bl40 = BL.fromChunks [bs40]
bl128 = BL.fromChunks [bs128]; bl512 = BL.fromChunks [bs512]
bl1Mb_40 = blmeg bs40; bl1Mb_128 = blmeg bs128
bl1Mb_64k = blmeg (B8.take 65536 bs1Mb)
!t5 = T.pack s5; !t8 = T.pack s8; !t11 = T.pack s11
!t40 = T.pack s40; !t128 = T.pack s128; !t512 = T.pack s512
!t1Mb = T.pack s1Mb
tlmeg = TL.take (fromIntegral mb) . TL.fromChunks . repeat
tl5 = TL.fromStrict t5; tl8 = TL.fromStrict t8
tl11 = TL.fromStrict t11; tl40 = TL.fromStrict t40
tl128 = TL.fromStrict t128; tl512 = TL.fromChunks (replicate 4 t128)
tl1Mb_40 = tlmeg t40; tl1Mb_128 = tlmeg t128
tl1Mb_64k = tlmeg (T.take 65536 t1Mb)
let k0 = 0x4a7330fae70f52e8
k1 = 0x919ea5953a9a1ec9
sipHash = hashByteString 2 4 k0 k1
hsSipHash = HS.hash (HS.SipKey k0 k1)
cSipHash (PS fp off len) =
inlinePerformIO . withForeignPtr fp $ \ptr ->
return $! c_siphash 2 4 k0 k1 (ptr `plusPtr` off) (fromIntegral len)
cSipHash24 (PS fp off len) =
inlinePerformIO . withForeignPtr fp $ \ptr ->
return $! c_siphash24 k0 k1 (ptr `plusPtr` off) (fromIntegral len)
fnvHash (PS fp off len) =
inlinePerformIO . withForeignPtr fp $ \ptr ->
return $! fnv_hash (ptr `plusPtr` off) (fromIntegral len) 2166136261
#ifdef HAVE_SSE2
sse2SipHash (PS fp off len) =
inlinePerformIO . withForeignPtr fp $ \ptr ->
return $! sse2_siphash k0 k1 (ptr `plusPtr` off) (fromIntegral len)
#endif
#ifdef HAVE_SSE41
sse41SipHash (PS fp off len) =
inlinePerformIO . withForeignPtr fp $ \ptr ->
return $! sse41_siphash k0 k1 (ptr `plusPtr` off) (fromIntegral len)
#endif
withForeignPtr fp5 $ \ p5 ->
withForeignPtr fp8 $ \ p8 ->
withForeignPtr fp11 $ \ p11 ->
withForeignPtr fp40 $ \ p40 ->
withForeignPtr fp128 $ \ p128 ->
withForeignPtr fp512 $ \ p512 ->
withForeignPtr fp1Mb $ \ p1Mb ->
defaultMain
[ bgroup "hashPtr"
[ bench "5" $ whnfIO $ hashPtr p5 5
, bench "8" $ whnfIO $ hashPtr p8 8
, bench "11" $ whnfIO $ hashPtr p11 11
, bench "40" $ whnfIO $ hashPtr p40 40
, bench "128" $ whnfIO $ hashPtr p128 128
, bench "512" $ whnfIO $ hashPtr p512 512
, bench "2^20" $ whnfIO $ hashPtr p1Mb mb
]
, bgroup "hashByteArray"
[ bench "5" $ whnf (hashByteArray ba5 0) 5
, bench "8" $ whnf (hashByteArray ba8 0) 8
, bench "11" $ whnf (hashByteArray ba11 0) 11
, bench "40" $ whnf (hashByteArray ba40 0) 40
, bench "128" $ whnf (hashByteArray ba128 0) 128
, bench "512" $ whnf (hashByteArray ba512 0) 512
, bench "2^20" $ whnf (hashByteArray ba1Mb 0) mb
]
, bgroup "hash"
[ bgroup "ByteString"
[ bgroup "strict"
[ bench "5" $ whnf hash bs5
, bench "8" $ whnf hash bs8
, bench "11" $ whnf hash bs11
, bench "40" $ whnf hash bs40
, bench "128" $ whnf hash bs128
, bench "512" $ whnf hash bs512
, bench "2^20" $ whnf hash bs1Mb
]
, bgroup "lazy"
[ bench "5" $ whnf hash bl5
, bench "8" $ whnf hash bl8
, bench "11" $ whnf hash bl11
, bench "40" $ whnf hash bl40
, bench "128" $ whnf hash bl128
, bench "512" $ whnf hash bl512
, bench "2^20_40" $ whnf hash bl1Mb_40
, bench "2^20_128" $ whnf hash bl1Mb_128
, bench "2^20_64k" $ whnf hash bl1Mb_64k
]
]
, bgroup "String"
[ bench "5" $ whnf hash s5
, bench "8" $ whnf hash s8
, bench "11" $ whnf hash s11
, bench "40" $ whnf hash s40
, bench "128" $ whnf hash s128
, bench "512" $ whnf hash s512
, bench "2^20" $ whnf hash s1Mb
]
, bgroup "Text"
[ bgroup "strict"
[ bench "5" $ whnf hash t5
, bench "8" $ whnf hash t8
, bench "11" $ whnf hash t11
, bench "40" $ whnf hash t40
, bench "128" $ whnf hash t128
, bench "512" $ whnf hash t512
, bench "2^20" $ whnf hash t1Mb
]
, bgroup "lazy"
[ bench "5" $ whnf hash tl5
, bench "8" $ whnf hash tl8
, bench "11" $ whnf hash tl11
, bench "40" $ whnf hash tl40
, bench "128" $ whnf hash tl128
, bench "512" $ whnf hash tl512
, bench "2^20_40" $ whnf hash tl1Mb_40
, bench "2^20_128" $ whnf hash tl1Mb_128
, bench "2^20_64k" $ whnf hash tl1Mb_64k
]
]
, bench "Int8" $ whnf hash (0xef :: Int8)
, bench "Int16" $ whnf hash (0x7eef :: Int16)
, bench "Int32" $ whnf hash (0x7eadbeef :: Int32)
, bench "Int" $ whnf hash (0x7eadbeefdeadbeef :: Int)
, bench "Int64" $ whnf hash (0x7eadbeefdeadbeef :: Int64)
, bench "Double" $ whnf hash (0.3780675796601578 :: Double)
]
, bgroup "sipHash"
[ bench "5" $ whnf sipHash bs5
, bench "8" $ whnf sipHash bs8
, bench "11" $ whnf sipHash bs11
, bench "40" $ whnf sipHash bs40
, bench "128" $ whnf sipHash bs128
, bench "512" $ whnf sipHash bs512
, bench "2^20" $ whnf sipHash bs1Mb
]
, bgroup "cSipHash"
[ bench "5" $ whnf cSipHash bs5
, bench "8" $ whnf cSipHash bs8
, bench "11" $ whnf cSipHash bs11
, bench "40" $ whnf cSipHash bs40
, bench "128" $ whnf cSipHash bs128
, bench "512" $ whnf cSipHash bs512
, bench "2^20" $ whnf cSipHash bs1Mb
]
, bgroup "cSipHash24"
[ bench "5" $ whnf cSipHash24 bs5
, bench "8" $ whnf cSipHash24 bs8
, bench "11" $ whnf cSipHash24 bs11
, bench "40" $ whnf cSipHash24 bs40
, bench "128" $ whnf cSipHash24 bs128
, bench "512" $ whnf cSipHash24 bs512
, bench "2^20" $ whnf cSipHash24 bs1Mb
]
#ifdef HAVE_SSE2
, bgroup "sse2SipHash"
[ bench "5" $ whnf sse2SipHash bs5
, bench "8" $ whnf sse2SipHash bs8
, bench "11" $ whnf sse2SipHash bs11
, bench "40" $ whnf sse2SipHash bs40
, bench "128" $ whnf sse2SipHash bs128
, bench "512" $ whnf sse2SipHash bs512
, bench "2^20" $ whnf sse2SipHash bs1Mb
]
#endif
#ifdef HAVE_SSE41
, bgroup "sse41SipHash"
[ bench "5" $ whnf sse41SipHash bs5
, bench "8" $ whnf sse41SipHash bs8
, bench "11" $ whnf sse41SipHash bs11
, bench "40" $ whnf sse41SipHash bs40
, bench "128" $ whnf sse41SipHash bs128
, bench "512" $ whnf sse41SipHash bs512
, bench "2^20" $ whnf sse41SipHash bs1Mb
]
#endif
, bgroup "pkgSipHash"
[ bench "5" $ whnf hsSipHash bs5
, bench "8" $ whnf hsSipHash bs8
, bench "11" $ whnf hsSipHash bs11
, bench "40" $ whnf hsSipHash bs40
, bench "128" $ whnf hsSipHash bs128
, bench "512" $ whnf hsSipHash bs512
, bench "2^20" $ whnf hsSipHash bs1Mb
]
, bgroup "fnv"
[ bench "5" $ whnf fnvHash bs5
, bench "8" $ whnf fnvHash bs8
, bench "11" $ whnf fnvHash bs11
, bench "40" $ whnf fnvHash bs40
, bench "128" $ whnf fnvHash bs128
, bench "512" $ whnf fnvHash bs512
, bench "2^20" $ whnf fnvHash bs1Mb
]
, bgroup "Int"
[ bench "id32" $ whnf id (0x7eadbeef :: Int32)
, bench "id64" $ whnf id (0x7eadbeefdeadbeef :: Int64)
, bench "wang32" $ whnf hash_wang_32 0xdeadbeef
, bench "wang64" $ whnf hash_wang_64 0xdeadbeefdeadbeef
, bench "jenkins32a" $ whnf hash_jenkins_32a 0xdeadbeef
, bench "jenkins32b" $ whnf hash_jenkins_32b 0xdeadbeef
]
]
data ByteArray = BA { unBA :: !ByteArray# }
new :: Int -> ByteArray#
new (I# n#) = unBA (runST $ ST $ \s1 ->
case newByteArray# n# s1 of
(# s2, ary #) -> case unsafeFreezeByteArray# ary s2 of
(# s3, ba #) -> (# s3, BA ba #))
foreign import ccall unsafe "hashable_siphash" c_siphash
:: CInt -> CInt -> Word64 -> Word64 -> Ptr Word8 -> CSize -> Word64
foreign import ccall unsafe "hashable_siphash24" c_siphash24
:: Word64 -> Word64 -> Ptr Word8 -> CSize -> Word64
#ifdef HAVE_SSE2
foreign import ccall unsafe "hashable_siphash24_sse2" sse2_siphash
:: Word64 -> Word64 -> Ptr Word8 -> CSize -> Word64
#endif
#ifdef HAVE_SSE41
foreign import ccall unsafe "hashable_siphash24_sse41" sse41_siphash
:: Word64 -> Word64 -> Ptr Word8 -> CSize -> Word64
#endif
foreign import ccall unsafe "hashable_fnv_hash" fnv_hash
:: Ptr Word8 -> CLong -> CLong -> CLong
foreign import ccall unsafe "hashable_wang_32" hash_wang_32
:: Word32 -> Word32
foreign import ccall unsafe "hashable_wang_64" hash_wang_64
:: Word64 -> Word64
foreign import ccall unsafe "hash_jenkins_32a" hash_jenkins_32a
:: Word32 -> Word32
foreign import ccall unsafe "hash_jenkins_32b" hash_jenkins_32b
:: Word32 -> Word32
| ekmett/hashable | benchmarks/Benchmarks.hs | bsd-3-clause | 11,538 | 0 | 30 | 3,947 | 3,645 | 1,816 | 1,829 | 212 | 1 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.Ptr (module M) where
import "base" GHC.Ptr as M
| xwysp/codeworld | codeworld-base/src/GHC/Ptr.hs | apache-2.0 | 729 | 0 | 4 | 136 | 23 | 17 | 6 | 4 | 0 |
module MonadOnlyInstances where
import Control.Monad ()
main :: IO ()
main = pure ()
| serokell/importify | test/test-data/base@basic/18-MonadOnlyInstances.hs | mit | 87 | 0 | 6 | 16 | 32 | 18 | 14 | 4 | 1 |
-- !!! Tests garbage collection in the branch of a case
-- !!! alternative where the constructor is returned in the heap.
{- This is also a rather stressful test for another reason.
The mutual recursion between munch and f causes lots of
closures to be built, of the form (munch n s), for some n and s.
Now, all of these closures are entered and each has as its value
the result delivered by the next; so the result is that there is
a massive chain of identical updates.
As it turns out, they are mostly garbage, so the GC could eliminate
them (though this isn't implemented at present), but that isn't
necessarily the case.
The only correct solution is to spot that the updates are all
updating with the same value (update frames stacked on top of each
other), and update all but one with indirections to the last
remaining one. This could be done by GC, or at the moment the
frame is pushed.
Incidentally, hbc won't have this particular problem, because it
updates immediately.
NOTE: [March 97] Now that stack squeezing happens when GC happens,
the stack is squished at GC. So this program uses a small stack
in a small heap (eg 4m heap 2m stack), but in a big heap (no GC)
it needs a much bigger stack (10m)! It would be better to try GC/stack
squeezing on stack oflo.
-}
module Main where
main = munch 100000 (inf 3)
data Stream a
= MkStream a a a a a a a a a (Stream a)
| Empty
inf :: Int -> Stream Int
inf n = MkStream n n n n n n n n n (inf n)
munch :: Int -> Stream a -> IO ()
munch n Empty = return () -- error "this never happens!\n"
-- this first equation mks it non-strict in "n"
-- (NB: call the "error" makes it strict)
munch 0 _ = putStr "I succeeded!\n"
munch n s = case (f n s) of
(True, rest) -> rest
(False, _) -> error "this never happens either\n"
--f :: Int -> Stream a -> (Bool, [Request])
f n (MkStream _ _ _ _ _ _ _ _ _ rest)
= -- garbage collection *HERE*, please!
-- (forced by the closure for n-1)
(True, munch (n - 1) rest)
-- munch and f are mutually recursive, just to be nasty
| sdiehl/ghc | testsuite/tests/codeGen/should_run/cgrun021.hs | bsd-3-clause | 2,141 | 0 | 8 | 534 | 264 | 140 | 124 | 16 | 2 |
module Prop2SVC(prop2SVC) where
import Syntax
import SCC
import PrettyPrint
import HOLOps
prop2SVC :: HsModuleR -> Doc
prop2SVC = module2HOL
module2HOL :: HsModuleR -> Doc
module2HOL (HsModule m Nothing imports infixes decls)
= fsep [ vcat $ map import2HOL imports,
vcat $ map infix2HOL infixes,
vcat $ map hsDecl2HOL decls ]
-- where (dss, _) = bindingGroups decls
module2HOL (HsModule m (Just exports) imports infixes decls)
= fsep [ vcat $ map export2HOL exports,
vcat $ map import2HOL imports,
vcat $ map infix2HOL infixes,
vcat $ map hsDecl2HOL decls ]
-- where (dss, _) = bindingGroups decls
export2HOL _ = notsupported0 "export declaration"
import2HOL _ = notsupported0 "import declaration"
infix2HOL (HsInfixDecl loc fixity ops) = notsupported loc "infix declaration"
decls2HOL :: [HsDecl] -> Doc
decls2HOL [] = empty
decls2HOL ds =
vcat $ (text "let" <+> dhol :
map (\dhol -> text "and" <+> dhol) dhols)
where (dhol:dhols) = map hsDecl2HOL ds
hsDecl2HOL :: HsDecl -> Doc
hsDecl2HOL (Dec (HsTypeDecl loc ((Typ (HsTyCon con)):params) t))
-- notsupported loc "type synonym declaration"
= blankline $ from loc
$$ (text "Hol_datatype" <+>
(backQuotes $
ppi con <+> equals <+> hsType2HOL [con] t))
$$ handleThm (text "Type synonym" <+> ppi con)
hsDecl2HOL (Dec (HsNewTypeDecl loc c ((Typ (HsTyCon con)):params) t ders))
-- notsupported loc "newtype declaration"
= blankline $ from loc
$$ (text "Hol_datatype" <+>
(backQuotes $
ppi con <+> equals <+> hsConDecl2HOL [con] t))
$$ handleThm (text "Newtype" <+> ppi con)
hsDecl2HOL (Dec (HsDataDecl loc c ((Typ (HsTyCon con)):params) summands ders))
= blankline $ from loc
$$ (text "Hol_datatype" <+>
(backQuotes $
ppi con <+> equals <+>
foldr1 (\d d' -> d $$ char '|' <+> d')
(map (hsConDecl2HOL [con]) summands)))
$$ handleThm (text "Datatype" <+> ppi con)
hsDecl2HOL (Dec (HsTypeSig loc nms c t))
= notsupported loc "type signature declaration"
hsDecl2HOL (Dec (HsFunBind loc ms))
= blankline $ from loc
$$ (text "val" <+> ppi fun <> text "_def" <+> equals <+>
text "Define" <+>
(backQuotes $
foldr1 (\d d' -> parens d <+> text "/\\"
$$ d')
(map hsMatch2HOL ms)))
$$ handleThm (text "Function" <+> ppi fun)
where (HsMatch _ fun _ _ _):_ = ms
hsDecl2HOL (Dec (HsPatBind loc (Pat (HsPId (HsVar v))) rhs ds))
= blankline $ from loc
$$ (text "val" <+> ppi v <> text "_def" <+> equals <+>
text "Define" <+>
(backQuotes $
funRhs2HOL loc (ppi v) rhs ds))
$$ handleThm (text "CAF" <+> ppi v)
hsDecl2HOL (Dec (HsPatBind loc p rhs ds))
= notsupported loc "pattern binding"
hsDecl2HOL (Dec (HsClassDecl loc c tp ds))
= notsupported loc "class declaration"
hsDecl2HOL (Dec (HsInstDecl loc c tp ds))
= notsupported loc "instance declaration"
hsDecl2HOL (Dec (HsDefaultDecl loc t))
= notsupported loc "default declaration"
hsDecl2HOL (Dec (HsPrimitiveTypeDecl loc cntxt nm))
= notsupported loc "Hugs-style primitive type declaration"
hsDecl2HOL (Dec (HsPrimitiveBind loc nm t))
= notsupported loc "Hugs-style primitive type declaration"
hsDecl2HOL (PropDec (HsProperty loc (ns @ (prop:_)) e))
= blankline $ from loc
$$ (holComment $ text "Property:" <+> pns)
$$ fsep [ {-text "val prop_" <> pprop <+> equals,-}
letNest $ {- parens $ backQuotes $ backQuotes $-} hsExp2HOL e ]
{- $$ handleTerm (text "Property" <+> pprop) -}
where pns = sep $ map ppi ns
pprop = ppi prop
hsConDecl2HOL :: [HsName] -> HsConDecl HsType -> Doc
hsConDecl2HOL excl (HsConDecl loc con params)
= hsName2HOL con <+> ps
where ps = case params of
[] -> empty
xs -> text "of" <+>
(hsep $ punctuate (text " =>") $
map (hsType2HOL excl . hsBangType2Type) xs)
hsConDecl2HOL excl (HsRecDecl loc _ _)
= notsupported loc "record declaration"
hsMatch2HOL (HsMatch loc fun ps rhs ds)
= funRhs2HOL loc (wrap fun <+> (fsep $ map wrap ps)) rhs ds
funRhs2HOL loc lhs (HsBody e) ds =
fsep [ lhs <+> equals,
funNest $
hsLet2HOL ds e ]
funRhs2HOL loc lhs (HsGuard gs) ds =
-- should convert guards to ifs, but need to factor in other function
-- branches, since a missing "otherwise" or "True" leaves us without an
-- else branch. This involves some of the patterm match compilation
-- machinery. This may be needed anyway, since it's not clear how complex
-- case expressions can be.
notsupported loc "guarded function/CAF definiton"
hsLet2HOL [] e = hsExp2HOL e
hsLet2HOL (d:ds) e = fsep [ text "let" <+> hsLetDecl2HOL d,
text "in" $$
(letNest $ hsLet2HOL ds e) ]
hsLetDecl2HOL (Dec (HsFunBind loc [m])) =
hsMatch2HOL m
hsLetDecl2HOL (Dec (HsFunBind loc ms)) =
notsupported loc "function definitions with many cases in lets"
hsLetDecl2HOL (Dec (HsPatBind loc p rhs ds)) =
funRhs2HOL loc (wrap p) rhs ds
hsLetDecl2HOL _ =
notsupported0 "non-function/pattern definitions in lets"
hsExp2HOL (Exp (HsId n)) = hsIdent2HOL n
hsExp2HOL (Exp (HsLit l)) = ppi l
hsExp2HOL (Exp (HsInfixApp x (HsVar (UnQual "$")) y)) =
fsep [ hsExp2HOL x, letNest $ parens $ hsExp2HOL y ]
hsExp2HOL (Exp (HsInfixApp x op y)) = hsInfixOp2SVC
(hsOp2SVC op)
(hsExp2HOL x)
(letNest $ hsExp2HOL y)
hsExp2HOL (Exp (HsApp x y)) =
(parens . fsep) [ hsExp2HOL x, letNest $ hsExp2HOL y ]
hsExp2HOL (Exp (HsNegApp x)) = char '-' <> hsExp2HOL x
hsExp2HOL (Exp (HsIf x y z)) = text "(ite" <+> hsExp2HOL x
$$ (letNest $ hsExp2HOL y)
$$ (letNest $ hsExp2HOL z) <+> text ")"
--- Above are definitely important, below maybe not.
hsExp2HOL (Exp (HsLambda ps e)) = fsep
[ char '\\' <+>
sep (map (hsPat2HOL wrap) ps) <+>
char '.',
letNest $ hsExp2HOL e ]
hsExp2HOL (Exp (HsLet ds e)) = hsLet2HOL ds e
hsExp2HOL (Exp (HsCase e alts)) =
text "case" <+> hsExp2HOL e <+> text "of"
$$ (vcat $ (nest 2 halt) : map (char '|' <+>) talt)
where (halt:talt) = map hsAlt2HOL alts
hsExp2HOL (Exp (HsDo stmts)) =
notsupported0 "do notation"
hsExp2HOL (Exp (HsTuple xs)) = ppiFTuple xs
hsExp2HOL (Exp (HsList xs)) = ppiList xs
hsExp2HOL (Exp (HsParen e)) = parens $ hsExp2HOL e
hsExp2HOL (Exp (HsLeftSection x op)) =
parens $
fsep [ char '\\' <+> ppi y <+> char '.',
hsInfixOp2HOL (hsOp2HOL op) (hsExp2HOL x) (ppi y) ]
where y = hsEVar $ UnQual "_y" -- Must be replaced by unique name
hsExp2HOL (Exp (HsRightSection op y)) =
parens $
fsep [ char '\\' <+> ppi x <+> char '.',
hsInfixOp2HOL (hsOp2HOL op) (ppi x) (hsExp2HOL y) ]
where x = hsEVar $ UnQual "_x" -- Must be replaced by unique name
hsExp2HOL (Exp (HsRecConstr n [])) =
notsupported0 "record construction"
hsExp2HOL (Exp (HsRecConstr n upds)) =
notsupported0 "record construction"
hsExp2HOL (Exp (HsRecUpdate e [])) =
notsupported0 "record update"
hsExp2HOL (Exp (HsRecUpdate e upds)) =
notsupported0 "record update"
hsExp2HOL (Exp (HsEnumFrom x)) =
notsupported0 "numeric enumeration"
hsExp2HOL (Exp (HsEnumFromTo x y)) =
notsupported0 "numeric enumeration"
hsExp2HOL (Exp (HsEnumFromThen x y)) =
notsupported0 "numeric enumeration"
hsExp2HOL (Exp (HsEnumFromThenTo x y z)) =
notsupported0 "numeric enumeration"
hsExp2HOL (Exp (HsListComp stmts)) =
notsupported0 "list comprehension"
hsExp2HOL (Exp (HsExpTypeSig s e t)) =
notsupported0 "type signature"
hsExp2HOL (Exp (HsAsPat n p)) =
error "hsExp2HOL: pattern exp in expression"
hsExp2HOL (Exp (HsWildCard)) =
error "hsExp2HOL: pattern exp in expression"
hsExp2HOL (Exp (HsIrrPat p)) =
error "hsExp2HOL: pattern exp in expression"
hsExp2HOL (PropExp (HsQuant q ps e)) =
fsep [ hsQuantifier2HOL q <+>
sep (map (hsPat2HOL wrap) ps) <+>
char '.',
letNest $ hsExp2HOL e ]
hsAlt2HOL (HsAlt loc p rhs ds) =
fsep [ hsPat2HOL wrap p, text "=>", caseRhs2HOL loc rhs ds ]
caseRhs2HOL loc (HsBody e) ds =
hsLet2HOL ds e
caseRhs2HOL loc (HsGuard gs) ds =
-- should convert guards to ifs, but need to factor in other function
-- branches, since a missing "otherwise" or "True" leaves us without an
-- else branch. This involves some of the patterm match compilation
-- machinery. This may be needed anyway, since it's not clear how complex
-- case expressions can be.
notsupported loc "guarded pattern in case expression"
hsQuantifier2HOL HsPropForall = char '!'
hsQuantifier2HOL HsPropExists = char '?'
hsQuantifier2HOL HsPropForallDefined = char '!' <+>
(holComment $ text "defined")
hsQuantifier2HOL HsPropExistsUnique = text "?!"
hsPat2HOL :: (HsPat -> Doc) -> HsPat -> Doc
hsPat2HOL ppf (Pat (HsPId id)) = ppi id
hsPat2HOL ppf (Pat (HsPLit lit)) = ppi lit
hsPat2HOL ppf (Pat (HsPNeg p)) = notsupported0 "negation pattern"
hsPat2HOL ppf (Pat (HsPInfixApp p1 op p2)) = fsep [ ppi op, ppf p1, ppf p2 ]
hsPat2HOL ppf (Pat (HsPApp id ps)) = fsep (ppi id : map ppf ps)
hsPat2HOL ppf (Pat (HsPTuple ps)) = ppiTuple ps
hsPat2HOL ppf (Pat (HsPList ps)) = ppiList ps
hsPat2HOL ppf (Pat (HsPParen p)) = parens $ ppi p
hsPat2HOL ppf (Pat (HsPRec _ _)) = notsupported0 "record pattern"
hsPat2HOL ppf (Pat (HsPRecUpdate _ _)) = notsupported0 "record pattern"
hsPat2HOL ppf (Pat (HsPAsPat id p)) = parens $
ppi id <+> text "as" <+> ppf p
hsPat2HOL ppf (Pat (HsPWildCard)) = text "_dummy"
hsPat2HOL ppf (Pat (HsPIrrPat p)) = ppf p
hsPat2HOL ppf (PropPat (HsPatTypeSig p t)) = ppf p
hsType2HOL :: [HsName] -> HsType -> Doc
hsType2HOL excl (Typ typ)
= case typ of
HsTyVar v -> quote <> hsName2HOL v
HsTyCon c -> hsTyCon2HOL c
HsTyApp (t1@(Typ (HsTyCon c))) t2
| c `elem` excl -> hsType2HOL excl t1
HsTyApp t1 t2 -> parens (hsType2HOL excl t2) <+> hsType2HOL excl t1
HsTyTuple ts -> hsep $ punctuate (text " #")
$ map (hsType2HOL excl) ts
HsTyFun t1 t2 ->
hsType2HOL excl t1 <+> text "->" <+> hsType2HOL excl t2
hsBangType2Type (HsBangedType t) = t
hsBangType2Type (HsUnBangedType t) = t -- ignore strictness annotations
hsIdent2HOL :: HsIdent -> Doc
hsIdent2HOL = snd . hsOp2HOL
hsInfixOp2HOL (inf, op) x y | inf = parens (fsep [ x, op, y ])
| otherwise = curlies (fsep [ op, x, y ])
hsInfixOp2SVC (int, op) x y | int = curlies (fsep [ op, x, y ])
| otherwise = parens (fsep [ op, x, y ])
hsOp2SVC (HsCon (id @ (Qual _ n))) =
case getSVCOp n of
Just (int, holop) -> (int, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2SVC (HsCon (id @ (UnQual n))) =
case getSVCOp n of
Just (int, holop) -> (int, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2SVC (HsVar (id @ (Qual _ n))) =
case getSVCOp n of
Just (int, holop) -> (int, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2SVC (HsVar (id @ (UnQual n))) =
case getSVCOp n of
Just (int, holop) -> (int, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2HOL (HsCon (id @ (Qual _ n))) =
case getSVCOp n of
Just (inf, holop) -> (inf, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2HOL (HsCon (id @ (UnQual n))) =
case getSVCOp n of
Just (inf, holop) -> (inf, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2HOL (HsVar (id @ (Qual _ n))) =
case getSVCOp n of
Just (inf, holop) -> (inf, text holop)
Nothing -> (False, hsName2HOL id)
hsOp2HOL (HsVar (id @ (UnQual n))) =
case getSVCOp n of
Just (inf, holop) -> (inf, text holop)
Nothing -> (False, hsName2HOL id)
hsTyCon2HOL (id @ (Qual _ n)) =
case getHOLTyCon n of
Just holtycon -> text holtycon
Nothing -> hsName2HOL id
hsTyCon2HOL (id @ (UnQual n)) =
case getHOLTyCon n of
Just holtycon -> text holtycon
Nothing -> hsName2HOL id
hsName2HOL :: HsName -> Doc
hsName2HOL (UnQual n) = text n
hsName2HOL (id @ (Qual _ n)) = text n <+> (holComment $ ppi id)
holComment d = text "(*" <+> d <+> text "*)"
from loc = holComment $ text "From" <+> ppi loc <+> char ':'
notsupported loc msg
= holComment $
text "Not supported:" <+> text msg <+> text "from" <+> ppi loc
notsupported0 msg
= holComment $ text "Not supported:" <+> text msg
handle failed backup =
text "handle e =>" <+>
(parens $
(vcat [ text "print" <+>
(doubleQuotes $ (failed <+> text "failed with exception"))
<> semi,
text "Exception.print_HOL_ERR e" <> semi,
backup
])
)
$$
semi
handleThm failed = handle failed (text "dummyThm")
handleTerm failed = handle failed (text "dummyTerm")
| forste/haReFork | tools/pg2hol/Prop2SVC.hs | bsd-3-clause | 13,939 | 22 | 18 | 4,248 | 4,897 | 2,403 | 2,494 | 294 | 6 |
{-# LANGUAGE UnicodeSyntax, MagicHash, TypeInType, TypeFamilies #-}
-- from Conal Elliott
-- Actually, this *should* work. But I want to put it in the testsuite
-- as a succeeding "compile_fail" test to make sure that we don't panic.
module RepRep where
import GHC.Exts
type family RepRep a ∷ RuntimeRep
class HasRep a where
type Rep a ∷ TYPE (RepRep a)
repr ∷ a → Rep a
abst ∷ Rep a → a
type instance RepRep Int = IntRep
instance HasRep Int where
type Rep Int = Int#
abst n = I# n
repr (I# n) = n
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T13105.hs | bsd-3-clause | 529 | 0 | 9 | 116 | 123 | 68 | 55 | -1 | -1 |
import System.IO
import Foreign
import Foreign.C
import Control.Monad
main = do test True; test False
test blocking = do
h <- openBinaryFile "hGetBuf003.hs" ReadMode
let sz = 42
loop = do
-- mix ordinary char buffering with hGetBuf
eof <- hIsEOF h
when (not eof) $ hGetChar h >>= putChar
b <- allocaBytes sz $ \ptr -> do
r <- (if blocking then hGetBuf else hGetBufNonBlocking) h ptr sz
if (r == 0)
then return True
else do s <- peekCStringLen (ptr,r)
putStr s
return False
if b then return () else loop -- tail call
loop
| beni55/ghcjs | test/pkg/base/hGetBuf003.hs | mit | 619 | 8 | 18 | 195 | 223 | 107 | 116 | 20 | 4 |
module Parser where
import Index
import Extras
data ParserStage = PersonSection | ShopSection | YearSection | MonthSection
| ExpenseSection
data ParserState = ParserState { psText :: String
, psLine :: Int
, psCol :: Int
, psTok :: String
, psToks :: [String]
, psIndex :: Index
, psStage :: ParserStage
}
data ParserErrorCode = Undefined
| Unknown { character :: Char }
| UnexpectedChar { character :: Char }
| EndOfFile
data ParserError = ParserError { peLine :: Int
, peCol :: Int
, peTok :: String
, peStage :: ParserStage
, peError :: ParserErrorCode
}
instance Show ParserStage where
show PersonSection = "Persons"
show ShopSection = "Shops"
show YearSection = "Year"
show MonthSection = "Month"
show ExpenseSection = "Expense"
instance Show ParserErrorCode where
show Undefined = "Undefined error"
show (Unknown c) = "Unknown error at character: " ++ [c]
show (UnexpectedChar c) = "Unexpected character: " ++ [c]
show EndOfFile = "End of file"
instance Show ParserError where
show ParserError { peLine = line
, peCol = col
, peTok = tok
, peStage = stage
, peError = err
} = unlines ["Line " ++ show line ++ ", Column " ++ show col ++
", Token " ++ tok ++ ", Stage " ++ show stage,
" -> " ++ show err]
errorFromState :: ParserState -> ParserError
errorFromState state = ParserError { peLine = psLine state
, peCol = psCol state
, peTok = psTok state
, peStage = psStage state
, peError = Undefined
}
consume :: Bool -> (Char -> Bool) -> ParserState -> Either ParserError ParserState
consume discard predicate state =
if not $ null t
then if predicate c
then Right state
{ psText = cs
, psTok = if discard then psTok state else psTok state ++ [c]
, psCol = psCol state + 1
, psLine = if isNewline c then psLine state + 1 else psLine state
}
else Left $ (errorFromState state) { peError = UnexpectedChar c }
else Left $ (errorFromState state) { peError = EndOfFile }
where t@(c:cs) = psText state
--(<~>) :: Either ParserError ParserState -> Either ParserError ParserState
--(<~>) (Left e) = e
| fredmorcos/attic | projects/pet/archive/pet_haskell_early/archive/Parser.hs | isc | 2,932 | 0 | 15 | 1,292 | 638 | 356 | 282 | 59 | 5 |
main :: IO ()
main = do
let a = "hell"
b = "yeah!"
putStrLn $ a ++ " " ++ b
| timtian090/Playground | Haskell/LearnYouAHaskellForGreatGood/lets.hs | mit | 86 | 0 | 9 | 32 | 50 | 23 | 27 | 5 | 1 |
module Main where
import Data.Char
-- A recursive datatype
{-
data Expr = Const Int
| Add Expr Expr
| Mul Expr Expr
-}
-- Same definition rewritten with Type Fixpoint
newtype Fix f = Fx (f (Fix f ) )
data ExprF a = Const Int | Add a a | Mul a a
type Expr = Fix ExprF
-- a test
testExpr = Fx $ (Fx $ (Fx $ Const 2 ) `Add` (Fx $ Const 3))
`Mul` (Fx $ Const 4)
-- an algebra is built on top of a functor.
-- ExprF is a functor:
instance Functor ExprF where
fmap eval (Const i) = Const i
fmap eval (Add x y) = Add (eval x) (eval y)
fmap eval (Mul x y) = Mul (eval x) (eval y)
-- Having a functor we can try different 'algebras'
-- Note we are talking about ExprF now.
-- We expect to be able to 'evaluate' children of Expr
alg':: ExprF Int -> Int
alg' (Const i) = i
alg' (Add x y) = x + y
alg' (Mul x y) = x * y
alg:: ExprF String -> String
alg (Const i) = [ chr (ord 'a' + i)]
alg (Add x y) = x ++ y
alg (Mul x y) = concat [[a,b] | a <- x, b <- y]
-- Algebra = (C, F, A, m)
-- + Category C = Hask, points are types of Haskell
-- + Endofunctor F (maps Hask points into other Hask points)
-- + Point A of category C. It's called carrier.
-- + Function m:: (F A) -> A
-- Hence our definition:
type Algebra f a = f a -> a
-- C is implied (Hask), F and A are type-level, the rest is m, the function
-- There are infinitely many algebras based on same functor
-- One is particular -- Initial algebra,
-- Practice: does not 'forget' anything, preserves all information about input
-- Theory: there exists a homomorphism from initial algebra to any other algebra
type ExprInitAlgebra = Algebra ExprF (Fix ExprF)
ex_init_alg :: ExprF (Fix ExprF) -> Fix ExprF
ex_init_alg = Fx
-- Now let's show we can build anything from it. Functor 'f' is fixed.
-- Let 'a' be a carrier object for a new algebra.
-- Carrier Evaluator
-- Initial algebra: Fix f Fx
-- Constructed one: a `alg`
--
-- Fx :: f (Fix f) -> Fix f
-- alg:: f a -> a
--
-- we want to get:
-- g:: Fix f -> a
-- Thanks to the fact that f is a functor, fmap is at our disposal:
-- fmap g :: f (Fix f) -> f a
{- Before:
f( Fix f ) ---- fmap g ---> f a
| |
| |
Fx alg
| |
| |
V V
Fix f -------g--------> a
-}
-- VERY CRUCIAL:: Fx is lossess SO it can be inverted:
{- Before:
f( Fix f ) ---- fmap g ---> f a
^ |
| |
Unfix alg
| |
| |
| V
Fix f -------g--------> a
-}
unFix:: Fix f -> f (Fix f)
unFix (Fx x) = x
-- Finally: let s build g:
g = alg. (fmap g) . unFix
--g alg = alg. (fmap (g alg)) . unFix
-- And even better:
cata :: Functor f => (f a -> a) -> (Fix f -> a)
cata alg = alg . fmap (cata alg) . unFix
-- *Main> :t cata alg
-- cata alg :: Fix ExprF -> String
-- Now lists
data ListF a b = Nil | Cons a b
type List a = Fix (ListF a)
instance Functor (ListF a) where
fmap f Nil = Nil
fmap f (Cons e x) = Cons e (f x)
algSum :: ListF Int Int -> Int
algSum Nil = 0
algSum (Cons e acc) = e + acc
lst :: List Int
lst = Fx $ Cons 2 (Fx $ Cons 3 (Fx $ Cons 4 (Fx Nil)))
{- Fx and unFix together -}
{- Fx is In (into F), unfix is out (out of F) -}
newtype Mu f = In {out :: f (Mu f)}
type CoAlgebra f a = a -> f a
catam :: Functor f => Algebra f a -> (Mu f -> a)
catam alg = alg . fmap (catam alg) . out
anam :: Functor f => CoAlgebra f a -> (a -> Mu f)
anam coalg = In. fmap (anam coalg) . coalg
data ListF' a b = Nil' | Cons' a b deriving Show
type List' a = Mu (ListF' a)
instance Functor (ListF' a) where
fmap f Nil' = Nil'
fmap f (Cons' e x) = Cons' e (f x)
coalg :: CoAlgebra (ListF' Int) Int -- Int --Int -> List' Int
coalg 0 = Nil'
coalg x = Cons' x (x-1)
showF :: (Show a) => List' a -> String
showF (In Nil') = "NIL"
showF (In (Cons' x xs)) = (show x) ++ ";" ++ (showF xs)
mu f = f (mu f)
cata_fix :: Functor f => Algebra f a -> (Mu f -> a)
cata_fix = mu (\f alg-> alg . fmap (f alg) . out)
anam_fix :: Functor f => CoAlgebra f a -> (a -> Mu f)
anam_fix = mu (\f coalg-> In. fmap (f coalg) . coalg )
-- Actually, even in Haskell recursion is not completely first class because the compiler does a terrible job of optimizing recursive code. This is why F-algebras and F-coalgebras are pervasive in high-performance Haskell libraries like vector, because they transform recursive code to non-recursive code, and the compiler does an amazing job of optimizing non-recursive code.
main = do
print $ (cata algSum) lst
print $ foldr (\e acc -> e + acc) 0 [2, 3, 4]
print $ showF $ anam coalg 10
| sayon/fp-cata-presentation | listings/algebra.hs | mit | 4,882 | 0 | 14 | 1,527 | 1,370 | 725 | 645 | 64 | 1 |
{-# htermination truncate :: RealFrac a => a -> Int #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_truncate_1.hs | mit | 56 | 0 | 2 | 11 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Dataset
( Dataset
, Point(..)
, push
, removeEnd
, toList
, xbounds
, ybounds
) where
import Dataset.Internal.Types
-- | Pushes a single point into the dataset.
push :: p -> Dataset p -> Dataset p
push p Dataset{..} =
Dataset _insert
_removeEnd
(_insert p _dataset)
_toList
_xbounds
_ybounds
-- | Removes a single point from the end of the dataset.
removeEnd :: Dataset p -> Dataset p
removeEnd Dataset{..} =
Dataset _insert
_removeEnd
(_removeEnd _dataset)
_toList
_xbounds
_ybounds
-- | Converts a dataset to a list.
toList :: Dataset p -> [p]
toList Dataset{..} = _toList _dataset
-- | Computes bounds for the dataset, if they can be calculated.
xbounds, ybounds :: Dataset p -> Maybe (Double, Double)
xbounds Dataset{..} = _xbounds _dataset
ybounds Dataset{..} = _ybounds _dataset
| SilverSylvester/cplot | src/Dataset.hs | mit | 962 | 0 | 7 | 272 | 235 | 125 | 110 | 31 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Model.Transfer(
Transfer(..),
TransferState(..),
TranferRejectionReason(..),
Fund(..),
Timeline(..),
TransferResponse(..),
toEntity,
fromEntity,
toFundEntity,
FundType(..)
) where
import GHC.Generics
--import Data.Aeson
import Data.Time.Clock (UTCTime)
import Data.Aeson.Types
import Data.Char
import Data.Maybe
import Data.Text (Text, unpack, pack)
import Data.Text.Encoding
import qualified Data.ByteString.Lazy as BL
import Control.Monad
import DB.Common as C
import qualified DB.Schema as S
import Model.Common
import Arith
import Data.Aeson hiding (encode) -- Workaround
import Workaround (encodeWithWorkaround)
encode :: ToJSON a => a -> BL.ByteString
encode = encodeWithWorkaround
instance FromJSON TransferState where
parseJSON (String "proposed") = return Proposed
parseJSON (String "prepared") = return Prepared
parseJSON (String "executed") = return Executed
parseJSON (String "rejected") = return Rejected
parseJSON _ = fail "could not parse TransferState"
instance ToJSON TransferState where
toJSON s = case s of
Proposed -> String "proposed"
Prepared -> String "prepared"
Executed -> String "executed"
Rejected -> String "rejected"
instance FromJSON TranferRejectionReason where
parseJSON (String "cancelled") = return Cancelled
parseJSON (String "expired") = return Expired
parseJSON _ = fail "could not parse TranferRejectionReason"
instance ToJSON TranferRejectionReason where
toJSON Cancelled = String "cancelled"
toJSON Expired = String "expired"
instance FromJSON FundType where
parseJSON (String "credit") = return Credit
parseJSON (String "debit") = return Debit
parseJSON _ = fail "could not parse FundType"
type Condition = Text
data AdditionalInfo = AdditionalInfo {
cases :: Maybe [Text]
} deriving (Show, Generic)
instance FromJSON AdditionalInfo
instance ToJSON AdditionalInfo
data Fund = Fund {
account :: Maybe Text,
amount :: Text,
memo :: Maybe Value,
invoice :: Maybe Text,
authorized :: Maybe Bool
} deriving (Show, Generic)
instance FromJSON Fund
instance ToJSON Fund
-- Bug in Aeson 0.12.x, omitNothingFields doesn't work ;(
--instance ToJSON Fund where
-- toEncoding = genericToEncoding $ defaultOptions { omitNothingFields = True }
toFundEntity :: Int -> S.Key S.Transfer -> Maybe (S.Key S.Account)
-> FundType -> Fund -> S.Fund
toFundEntity scale transferId mAccountId type_ f =
S.Fund transferId
type_
mAccountId
(fromText scale $ amount f)
(authorized f)
-- fromFundEntity :: Int -> S.Fund -> Fund
-- fromFundEntity scale f =
-- Fund (S.fundAccount f)
-- (toText scale $ S.fundAmount f)
-- Nothing
-- Nothing
-- (S.fundIsAuthorized f)
data Timeline = Timeline {
proposed_at :: Maybe Text,
prepared_at :: Maybe Text,
executed_at :: Maybe Text,
rejected_at :: Maybe Text
} deriving (Show, Generic)
instance FromJSON Timeline
instance ToJSON Timeline
defaultTimeline = Timeline Nothing Nothing Nothing Nothing
data Transfer = Transfer {
id :: Uuid,
ledger :: Text,
state :: Maybe TransferState,
rejection_reason :: Maybe TranferRejectionReason,
execution_condition :: Maybe Condition,
cancellation_condition :: Maybe Condition,
expiry_duration :: Maybe Text,
credits :: [Fund],
debits :: [Fund],
additional_info :: Maybe AdditionalInfo,
timeline :: Maybe Timeline
} deriving (Show, Generic)
instance FromJSON Transfer
instance ToJSON Transfer
-- Bug in Aeson 0.12.x, omitNothingFields doesn't work ;(
--instance ToJSON Transfer where
-- toEncoding = genericToEncoding $ defaultOptions { omitNothingFields = True }
data TransferResponse = TransferResponse {
transfer :: Transfer,
existed :: Bool
} deriving (Show, Generic)
instance ToJSON TransferResponse
justOr def (Just v) = v
justOr def _ = def
toEntity :: Transfer -> S.Transfer
toEntity t =
S.Transfer (uuidToText $ Model.Transfer.id t)
(ledger t)
(justOr Proposed $ state t)
(rejection_reason t)
Nothing
Nothing
Nothing
Nothing
Nothing
(liftM (decodeUtf8 . BL.toStrict . encode) $
additional_info t)
(execution_condition t)
(cancellation_condition t)
(liftM (read . unpack) $ expiry_duration t)
(decodeUtf8 . BL.toStrict . encode $ credits t)
(decodeUtf8 . BL.toStrict . encode $ debits t)
Nothing
fromEntity :: S.Transfer -> Transfer
fromEntity t =
Transfer (Uuid $ S.transferUuid t)
(S.transferLedger t)
(Just $ S.transferState t)
(S.transferRejectionReason t)
(S.transferExecutionCondition t)
(S.transferCancellationCondition t)
(liftM (pack . show) $ S.transferExpiryDuration t)
(fromJust $ decode . BL.fromStrict . encodeUtf8 $ S.transferCredits t)
(fromJust $ decode . BL.fromStrict . encodeUtf8 $ S.transferDebits t)
(S.transferAdditionalInfo t >>= decode . BL.fromStrict . encodeUtf8)
(Just timeline)
where
show' :: Maybe UTCTime -> Maybe Text
show' = liftM (pack . show)
timeline =
Timeline (show' $ S.transferProposedAt t)
(show' $ S.transferPreparedAt t)
(show' $ S.transferExecutedAt t)
(show' $ S.transferRejectedAt t)
| gip/cinq-cloches-ledger | src/Model/Transfer.hs | mit | 5,501 | 0 | 12 | 1,258 | 1,478 | 786 | 692 | 146 | 1 |
module ProjectEuler.Problem44
( problem
) where
import Control.Monad
import qualified Data.IntSet as IS
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 44 Solved result
{-
P(n) = n*(3n-1) / 2
=> P(n) - P(n-1) = 3n-2
let P'(n) = 3n-2
=> P'(n) - P'(n-1) = 3
-}
pentagonals :: [Int]
pentagonals = tail $ scanl (+) 0 $ iterate (+ 3) 1
result :: Int
result = head possibleDiffs
where
possibleDiffs :: [Int]
possibleDiffs = do
(n, pN) <- zip [1..] pentagonals
let space = IS.fromDistinctAscList $ take (n-1) pentagonals
p2 <- IS.toList space
-- p2 + p1 = pN
let p1 = pN - p2
guard $ p1 <= p2
guard $ IS.member p1 space
let pDiff = p2 - p1
guard $ IS.member pDiff space
pure pDiff
| Javran/Project-Euler | src/ProjectEuler/Problem44.hs | mit | 782 | 0 | 15 | 218 | 244 | 127 | 117 | 22 | 1 |
module Main where
import Prelude hiding (readFile)
import Data.List (partition, (\\))
import Control.Monad (forM, liftM, liftM2, join)
import System.FilePath (addExtension, takeExtension, dropExtension, (</>))
import System.Directory (getHomeDirectory, getDirectoryContents)
import System.Environment (getArgs)
import System.IO.Error (tryIOError, isDoesNotExistError)
import System.IO.Strict (readFile) -- Needed because we read and write to the same file
-- which is "not?" possible lazily
main :: IO ()
main = do
args <- getArgs
home <- getHomeDirectory
existing <- getGitignoreFileContents
templates <- listAvailableTemplates
chosen <- return $ join (liftM (listChosenTemplates args) templates)
allRules <- case chosen of
Left e -> return $ Left e
Right files -> getTemplatesContent $ getFullPathTemplates home files
toAdd <- return $ liftM2 rulesToAdd existing allRules
added <- case toAdd of
Left e -> return $ Left e
Right rules -> addRules rules
putStrLn $ formatMessage $ getMessage added toAdd
where
getMessage added' toAdd' = case added' of
Left e -> Left e
Right _ -> liftM getSummary toAdd'
type Rule = String
templatesDir :: FilePath
templatesDir = ".gitignore"
gitignoreFile :: FilePath
gitignoreFile = ".gitignore"
extension :: String
extension = "gitignore"
listChosenTemplates :: [String] -> [FilePath] -> Either String [FilePath]
listChosenTemplates [] _ = Left "No template names provided"
listChosenTemplates names templates =
if someTemplatesMissing
then Left ("Templates missing for " ++ unwords missing)
else Right (addExtensions present)
where namesOnly = fmap dropExtension
addExtensions = fmap (flip addExtension extension)
someTemplatesMissing = not (null missing)
group desired existing = partition (flip elem existing) desired
(present, missing) = group names (namesOnly templates)
listAvailableTemplates :: IO (Either String [FilePath])
listAvailableTemplates = do
home <- getHomeDirectory
result <- tryIOError (getDirectoryContents $ home </> templatesDir)
case result of
Left _ -> return $ Left "Problem getting files from templates directory"
Right files -> return $ Right $ filter isTemplate files
where isTemplate :: FilePath -> Bool
isTemplate p = takeExtension p == '.' : extension
getFullPathTemplate :: FilePath -> FilePath -> FilePath
getFullPathTemplate home file = home </> templatesDir </> file
getFullPathTemplates :: FilePath -> [FilePath] -> [FilePath]
getFullPathTemplates home = map (getFullPathTemplate home)
getTemplatesContent :: [FilePath] -> IO (Either String [Rule])
getTemplatesContent paths = do
result <- tryIOError (forM paths readFile)
case result of
Left _ -> return $ Left "Problem loading templates"
Right contents -> return $ Right $ lines $ foldr (++) "" contents
getGitignoreFileContents :: IO (Either String [Rule])
getGitignoreFileContents = do
result <- tryIOError (readFile gitignoreFile)
case result of
Left e -> if isDoesNotExistError e
then return $ Right []
else return $ Left "Problem loading .gitignore"
Right content -> return $ Right $ lines content
rulesToAdd :: [Rule] -> [Rule] -> [Rule]
rulesToAdd existing new = new \\ existing
addRules :: [Rule] -> IO (Either String ())
addRules toAdd = do
result <- tryIOError (appendFile gitignoreFile $ unlines toAdd)
case result of
Left _ -> return $ Left "Problem writing to .gitignore file"
Right _ -> return $ Right ()
getSummary :: [Rule] -> String
getSummary rules = if null rules
then "Nothing to add to the .gitignore file"
else "Added " ++ (show $ length rules) ++ " rules to the .gitignore file"
formatMessage :: (Either String String) -> String
formatMessage (Left m) = "Error: " ++ m
formatMessage (Right m) = "Success: " ++ m
| toonketels/gitignore | src/Main.hs | mit | 4,362 | 0 | 14 | 1,235 | 1,190 | 602 | 588 | 87 | 4 |
{-# LANGUAGE TypeOperators #-}
module Main where
import Data.Either
import Test.Tasty
import Test.Tasty.HUnit
import PigmentPrelude
import qualified TacticParse as Parse
import qualified Operators
import qualified AlphaConversions
import qualified Mangler
import qualified Records
import qualified Data
import qualified OTT
canTyBasics :: Assertion
canTyBasics = do
-- let's start with the basics
assertRight "Set"
Set
(canTy ev (Set :>: Set))
-- -- Can ((TY :>: VAL) :=>: VAL)
-- let s = (SET :>: SET) :=>: SET
-- assertRight "Pi"
-- (Pi s s)
-- -- (do
-- -- s' <- ev (SET :>: s)
-- -- return (Pi (SET :>: s) ((ARR s' SET) :>: t))
-- -- )
-- (canTy ev (Set :>: Pi s s))
-- check :: (TY :>: INTM) -> Check INTM (INTM :=>: VAL)
checkBasics :: Assertion
checkBasics = do
-- some trivial checks
assertChecks (SET :>: SET) SET
assertChecks (SET :>: PROP) PROP
assertChecks (SET :>: PROB) PROB
assertChecks (SET :>: RSIG) RSIG
assertChecks (RSIG :>: REMPTY) REMPTY
assertChecks (UNIT :>: VOID) VOID
assertChecks (SET :>: UID) UID
-- assertChecks (PI SET (L (K SET)) :>: L ("s" :. SET)) (L (K SET))
assertChecks (PI SET (L (K SET)) :>: L (K SET)) (L (K SET))
-- infer :: EXTM -> Check INTM (VAL :<: TY)
inferBasics :: Assertion
inferBasics = do
-- trivial checks - we infer the ascripted type
assertInfers (UNIT ?? SET) (UNIT :<: SET)
assertInfers (VOID ?? UNIT) (VOID :<: UNIT)
assertInfers (ARR UNIT UNIT ?? SET)
(ARR UNIT UNIT :<: SET)
assertInfers (LK VOID ?? ARR UNIT UNIT)
(LK VOID :<: ARR UNIT UNIT)
-- this SIGMA and TIMES are really the same thing
assertInfers (PAIR UNIT UNIT ?? SIGMA SET (LK SET))
(PAIR UNIT UNIT :<: TIMES SET SET)
-- this ARR and PI are really the same thing
assertInfers (LAV "x" (NV 0) ?? ARR SET SET)
(LAV "x" (NV 0) :<: PI SET (LK SET))
-- elimination
-- assertInfers
-- ((constUnit :? constUnitTy) :$ (A UNIT))
-- (UNIT :<: SET)
equalBasics :: Assertion
equalBasics = do
let pair = PAIR UNIT UNIT
result = pair $$ Fst
assertTrue $ equal (SET :>: (result, UNIT)) fakeNameSupply
checkTests :: TestTree
checkTests = testGroup "Type Checking Tests"
[ testCase "canTy basics" canTyBasics
, testCase "check basics" checkBasics
, testCase "infer basics" inferBasics
, testCase "equal basics" equalBasics
-- , testCase "tactics" testTactics
]
tests :: TestTree
tests = testGroup "Tests"
[ checkTests
, Parse.tests
, Operators.tests
, AlphaConversion.tests
, Mangler.tests
, Records.tests
, Data.tests
, OTT.tests
]
main :: IO ()
main = defaultMain tests
| kwangkim/pigment | tests/Main.hs | mit | 2,830 | 0 | 14 | 780 | 687 | 363 | 324 | 63 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Spec where
import Test.Hspec
import Test.Hspec.QuickCheck
import Data.MonoTraversable
import Data.Text (Text)
import qualified Data.ByteString.Lazy as L
import Data.Sequences
import Prelude (Bool (..), ($), IO, min, abs, Eq (..), (&&), fromIntegral, Ord (..), String, mod, Int)
main :: IO ()
main = hspec $ do
describe "cnull" $ do
it "empty list" $ onull [] `shouldBe` True
it "non-empty list" $ onull [()] `shouldBe` False
it "empty text" $ onull ("" :: Text) `shouldBe` True
it "non-empty text" $ onull ("foo" :: Text) `shouldBe` False
describe "clength" $ do
prop "list" $ \i' ->
let x = replicate i () :: [()]
i = min 500 $ abs i'
in olength x == i
prop "text" $ \i' ->
let x = replicate i 'a' :: Text
i = min 500 $ abs i'
in olength x == i
prop "lazy bytestring" $ \i' ->
let x = replicate i 6 :: L.ByteString
i = min 500 $ abs i'
in olength64 x == i
describe "ccompareLength" $ do
prop "list" $ \i' j ->
let i = min 500 $ abs i'
x = replicate i () :: [()]
in ocompareLength x j == compare i j
describe "groupAll" $ do
it "list" $ groupAll ("abcabcabc" :: String) == ["aaa", "bbb", "ccc"]
it "Text" $ groupAll ("abcabcabc" :: Text) == ["aaa", "bbb", "ccc"]
describe "groupAllOn" $ do
it "list" $ groupAllOn (`mod` 3) ([1..9] :: [Int]) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
| moonKimura/mono-traversable-0.1.0.0 | test/Spec.hs | mit | 1,594 | 0 | 18 | 525 | 654 | 345 | 309 | 39 | 1 |
module Type (TypeInfo (..), Type (..), TypedName, Error (..), checkTypes, typeOf, ValidationError (..), validateTypes) where
import MyPrelude
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Pretty as P
import qualified AST
import AST (AST)
import qualified Name
import Name (Name, NameWith (NameWith), ResolvedName)
------------------------------------------------------------------------ types
data TypeInfo
= IsType Type -- stored for names of types in type annotations
| HasType Type -- stored for value-level names
deriving (Generic, Eq, Show)
data Type
= Int
| Bool
| Text
| Unit
| Function [Type] Type
deriving (Generic, Eq, Show)
type TypedName = NameWith TypeInfo
typeOf :: AST.Expression metadata TypedName -> Type
typeOf = \case
AST.Named name ->
case Name.info name of
HasType ty -> ty
IsType _ -> bug "Expression which IsType in typed AST"
AST.NumberLiteral _ ->
Int
AST.TextLiteral _ ->
Text
AST.UnaryOperator op _ ->
case op of
Not -> Bool
Negate -> Int
AST.BinaryOperator _ op _ ->
case op of
ArithmeticOperator _ -> Int
ComparisonOperator _ -> Bool
LogicalOperator _ -> Bool
AST.Call fn _ ->
case typeOf (nodeWithout fn) of
Function _ returnType -> returnType
_ -> bug "Call of non-function in typed AST"
------------------------------------------------------------------------ pretty-printing
instance P.Render TypeInfo where
listSeparator = ", "
render ty = P.note (P.Identifier (P.IdentInfo (typeText ty) P.Use P.Type True)) (P.pretty (typeText ty)) where
typeText = \case
HasType (Function argumentTypes returnType) ->
"function(" ++ Text.intercalate ", " (map (typeText . HasType) argumentTypes) ++ ")" ++ case returnType of
Unit -> ""
otherType -> " returns " ++ typeText (HasType otherType)
HasType otherType -> showText otherType
IsType _ -> "Type"
instance P.Render Type where
listSeparator = ", "
render = P.render . HasType
instance AST.RenderName TypedName where
renderName defOrUse (NameWith name ty) = maybeAppendTypeAnnotation (fmap setTypeInNote (AST.renderName defOrUse name))
where maybeAppendTypeAnnotation binding = binding ++ (if defOrUse == P.Definition then (P.colon ++ " " ++ P.render ty) else "")
setTypeInNote = \case
P.Identifier info -> P.Identifier (info { P.identType })
_ -> bug "Pretty-printing annotation on ResolvedName was not Identifier"
identType = case ty of
IsType _ -> P.Type
HasType hasType -> case hasType of
Int -> P.Int
Bool -> P.Bool
Text -> P.Text
Unit -> P.Unit
Function _ _ -> P.Function
------------------------------------------------------------------------ typechecker frontend
-- TODO more info in here?
data Error
= TypeMismatch Expected TypeInfo
| WrongNumberOfArguments -- (can we move this into Expected?)
| FunctionWithoutReturn
| AssignToLet
| LiteralOutOfRange
deriving (Generic, Show)
data Expected
= Expected Type
| ExpectedFunction
| ExpectedExpression
| ExpectedType
deriving (Generic, Show)
class (forall metadata. Monad (m metadata)) => TypeCheckM m where
recordType :: Type -> ResolvedName -> m metadata () -- records `HasType`; for now, the only things which are `IsType` are builtins
lookupType :: ResolvedName -> m metadata TypeInfo
reportError :: Error -> m metadata a
enterMetadata :: metadata -> m metadata a -> m metadata a
-- TODO deduplicate?
enterMetadataOf :: TypeCheckM m => NodeWith node metadata name -> m metadata a -> m metadata a
enterMetadataOf = enterMetadata . nodeMetadata
class CheckTypeOf node where
inferType :: TypeCheckM m => node metadata ResolvedName -> m metadata TypeInfo
checkUnit :: TypeCheckM m => node metadata ResolvedName -> m metadata ()
inferType node = do
checkUnit node
return (HasType Unit)
checkUnit = checkType Unit
checkType :: (TypeCheckM m, CheckTypeOf node) => Type -> node metadata ResolvedName -> m metadata ()
checkType expected node = do
actual <- inferType node
when (actual != HasType expected) do
reportError (TypeMismatch (Expected expected) actual)
instance CheckTypeOf AST.Expression where
inferType = \case
AST.Named name -> do
nameType <- lookupType name
case nameType of
HasType _ -> return nameType
IsType _ -> reportError (TypeMismatch ExpectedExpression nameType)
AST.NumberLiteral int -> do
when (int > fromIntegral (maxBound :: Int64) || int < fromIntegral (minBound :: Int64)) do
reportError LiteralOutOfRange
return (HasType Int)
AST.TextLiteral _ -> do
return (HasType Text)
AST.UnaryOperator op expr -> do
let type' = case op of
Not -> Bool
Negate -> Int
checkType type' expr
return (HasType type')
AST.BinaryOperator expr1 op expr2 -> do
let (inType, outType) = case op of
ArithmeticOperator _ -> (Int, Int)
ComparisonOperator _ -> (Int, Bool)
LogicalOperator _ -> (Bool, Bool)
checkType inType expr1
checkType inType expr2
return (HasType outType)
AST.Call function arguments -> do
functionType <- inferType function
case functionType of
HasType (Function argumentTypes returnType) -> do
when (length argumentTypes != length arguments) do
reportError WrongNumberOfArguments
zipWithM checkType argumentTypes arguments
return (HasType returnType)
_ -> do
reportError (TypeMismatch ExpectedFunction functionType)
instance CheckTypeOf AST.Statement where
checkUnit = \case
AST.Binding _ name expr -> do
inferred <- inferType expr
case inferred of
HasType hasType -> recordType hasType name
IsType _ -> reportError (TypeMismatch ExpectedExpression inferred)
AST.Assign name expr -> do
when (Name.info name != AST.Var) do
reportError AssignToLet
nameType <- lookupType name
case nameType of
HasType hasType -> checkType hasType expr
IsType _ -> reportError (TypeMismatch ExpectedExpression nameType)
AST.IfThen expr block -> do
checkType Bool expr
checkUnit block
AST.IfThenElse expr block1 block2 -> do
checkType Bool expr
checkUnit block1
checkUnit block2
AST.Forever block -> do
checkBlock Unit block
AST.While expr block -> do
checkType Bool expr
checkBlock Unit block
AST.Return target maybeExpr -> do
returnType <- lookupType target
mapM_ (checkType (assert (match @"HasType" returnType))) maybeExpr
when (maybeExpr == Nothing) do
checkType Unit (AST.Named target) -- HACK?
AST.Break target -> do
breakType <- lookupType target
assertEqM breakType (HasType Unit)
AST.Expression expr -> do
unused (inferType expr)
instance CheckTypeOf AST.Block where
checkUnit AST.Block { AST.statements } = do
mapM_ checkUnit statements
checkBlock :: TypeCheckM m => Type -> NodeWith AST.Block metadata ResolvedName -> m metadata ()
checkBlock exitTargetType block = do
recordType exitTargetType (assert (AST.exitTarget (nodeWithout block)))
checkUnit block
resolveAsType :: TypeCheckM m => NodeWith AST.Type metadata ResolvedName -> m metadata Type
resolveAsType typeNode = enterMetadataOf typeNode do
resolved <- inferType (nodeWithout typeNode)
return (msgAssert "type annotation resolved to a non-type" (match @"IsType" resolved))
instance CheckTypeOf AST.Function where
checkUnit AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do
argumentTypes <- forM arguments \argument -> do
enterMetadataOf argument do
let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument
resolvedType <- resolveAsType argumentType
recordType resolvedType argumentName
return resolvedType
maybeReturnType <- mapM resolveAsType returns
let returnType = fromMaybe Unit maybeReturnType
recordType (Function argumentTypes returnType) functionName
checkBlock returnType body
when (returnType != Unit && not (definitelyReturns (controlFlow body))) do
reportError FunctionWithoutReturn
instance CheckTypeOf AST.Type where
inferType = \case
AST.NamedType name -> do
nameType <- lookupType name
case nameType of
IsType _ -> return nameType
HasType _ -> reportError (TypeMismatch ExpectedType nameType)
AST.FunctionType parameters returns -> do
resolvedParameters <- mapM resolveAsType parameters
resolvedReturns <- resolveAsType returns
return (IsType (Function resolvedParameters resolvedReturns))
instance CheckTypeOf node => CheckTypeOf (NodeWith node) where
inferType node = do
enterMetadataOf node do
inferType (nodeWithout node)
data ControlFlow = ControlFlow {
definitelyReturns :: Bool, -- guaranteed divergence also counts as "returning"
potentiallyBreaks :: Bool
}
instance Semigroup ControlFlow where
prev <> next = ControlFlow returns breaks where
returns = definitelyReturns prev || (not (potentiallyBreaks prev) && definitelyReturns next)
breaks = potentiallyBreaks prev || (not (definitelyReturns prev) && potentiallyBreaks next)
instance Monoid ControlFlow where
mempty = ControlFlow False False
class CheckControlFlow node where
controlFlow :: Eq name => node metadata name -> ControlFlow
instance CheckControlFlow AST.Block where
controlFlow = mconcat . map controlFlow . AST.statements
instance CheckControlFlow AST.Statement where
controlFlow = \case
AST.Return {} ->
ControlFlow True False
AST.Break {} ->
ControlFlow False True
AST.Binding {} ->
ControlFlow False False
AST.Assign {} ->
ControlFlow False False
AST.Expression {} ->
ControlFlow False False
AST.While {} ->
ControlFlow False False -- loops can't currently break out of the /outer/ context
AST.IfThen _ block ->
ControlFlow False (potentiallyBreaks (controlFlow block))
AST.IfThenElse _ block1 block2 ->
ControlFlow (returns1 && returns2) (breaks1 || breaks2) where
ControlFlow returns1 breaks1 = controlFlow block1
ControlFlow returns2 breaks2 = controlFlow block2
AST.Forever blockWith ->
ControlFlow (noBreaks || doesReturn) False where
-- we can check whether there is a `break` by whether the `exitTarget` is ever referred to
-- (we make use of the Foldable instances for the AST)
-- we have to make sure to leave out the `exitTarget` itself!
noBreaks = not (any (== (assert (AST.exitTarget block))) (block { AST.exitTarget = Nothing }))
doesReturn = definitelyReturns (controlFlow block)
block = nodeWithout blockWith
instance CheckControlFlow node => CheckControlFlow (NodeWith node) where
controlFlow = controlFlow . nodeWithout
------------------------------------------------------------------------ typechecker backend
newtype TypeCheck metadata a = TypeCheck {
runTypeCheck :: (ExceptT Error) (State (TypeCheckState metadata)) a
} deriving (Functor, Applicative, Monad, MonadState (TypeCheckState metadata), MonadError Error)
data TypeCheckState metadata = TypeCheckState {
types :: Map Name TypeInfo,
metadata :: [metadata]
} deriving (Generic, Show)
checkTypes :: AST metadata ResolvedName -> Either (With metadata Error) (AST metadata TypedName)
checkTypes ast = pipeline ast where
pipeline = constructResult . runState initialState . runExceptT . runTypeCheck . mapM_ checkUnit
initialState = TypeCheckState (Map.fromList builtinNames) []
builtinNames = map (\builtinName -> (Name.BuiltinName builtinName, inferBuiltin builtinName)) (enumerate @Name.BuiltinName)
constructResult = \case
(Right (), TypeCheckState { types }) -> Right (map (fmap (makeNameTyped types)) ast)
(Left error, TypeCheckState { metadata }) -> Left (With (assert (head metadata)) error)
makeNameTyped types (NameWith name _) = NameWith name (assert (Map.lookup name types))
instance TypeCheckM TypeCheck where
recordType typeOfName name = do
doModifyM (field @"types") \typeMap -> do
assertM (not (Map.member (Name.name name) typeMap))
return (Map.insert (Name.name name) (HasType typeOfName) typeMap)
return ()
lookupType name = do
typeMap <- getM (field @"types")
return (msgAssert "Name not found in types map!" (Map.lookup (Name.name name) typeMap))
reportError err = do
throwError err
enterMetadata metadata action = do -- TODO maybe deduplicate this from here and `Name`?
modifyM (field @"metadata") (prepend metadata)
result <- action
modifyM (field @"metadata") (assert . tail)
return result
inferBuiltin :: Name.BuiltinName -> TypeInfo
inferBuiltin = \case
Name.Builtin_Int -> IsType Int
Name.Builtin_Bool -> IsType Bool
Name.Builtin_Text -> IsType Text
Name.Builtin_Unit -> IsType Unit
Name.Builtin_true -> HasType Bool
Name.Builtin_false -> HasType Bool
Name.Builtin_ask -> HasType (Function [Text] Int)
Name.Builtin_say -> HasType (Function [Text] Unit)
Name.Builtin_write -> HasType (Function [Int] Unit)
------------------------------------------------------------------------ validation
-- TODO check presence/absence of exit targets (or in Name.validate??)
data ValidationError metadata
= BadType Expected (AST.Expression metadata TypedName)
| BadAnnotation Type (AST.Type metadata TypedName)
| BadArgumentCount Int (AST.Expression metadata TypedName)
deriving (Generic, Show)
type ValidateM metadata a = Except (ValidationError metadata) a
class Validate node where
validate :: node metadata TypedName -> ValidateM metadata ()
-- This checks that:
-- * The AST is locally well-typed at each point, based on the types stored within `Name`s.
-- * The explicitly-written type annotations in the AST are accurate.
-- This does NOT check that:
-- * Names are actually in scope, and the info stored in `Name`s is consistent. Use `Name.validate` for that!
-- * Literals are within range, and assignments match their binding types.
validateTypes :: AST metadata TypedName -> Either (ValidationError metadata) ()
validateTypes = runExcept . mapM_ validate
validateAnnotation :: Type -> AST.Type metadata TypedName -> ValidateM metadata ()
validateAnnotation = curry \case
(expected@(Function expectedParams expectedReturns), annotated@(AST.FunctionType annotatedParams annotatedReturns)) -> do
when (length expectedParams != length annotatedParams) do
throwError (BadAnnotation expected annotated)
zipWithM_ validateAnnotation expectedParams (map nodeWithout annotatedParams)
validateAnnotation expectedReturns (nodeWithout annotatedReturns)
(expectedType, AST.NamedType namedType) | Name.info namedType == IsType expectedType -> do
return ()
(expectedType, annotation) -> do
throwError (BadAnnotation expectedType annotation)
instance Validate AST.Function where
validate AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do
argumentTypes <- forM arguments \argument -> do
let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument
case Name.info argumentName of
HasType ty -> do
validateAnnotation ty (nodeWithout argumentType)
return ty
IsType _ -> do
throwError (BadType ExpectedExpression (AST.Named argumentName))
case Name.info functionName of
HasType infoType@(Function infoParams infoReturns) -> do
mapM_ (validateAnnotation infoReturns . nodeWithout) returns
when (infoParams != argumentTypes) do
throwError (BadType (Expected infoType) (AST.Named functionName)) -- ehhhhhh
mapM_ (validateName infoReturns) ((AST.exitTarget . nodeWithout) body) -- TODO check that it's Just!
HasType _ -> do
throwError (BadType ExpectedFunction (AST.Named functionName))
IsType _ -> do
throwError (BadType ExpectedExpression (AST.Named functionName))
validate body
instance Validate AST.Block where
validate = mapM_ validate . AST.statements
instance Validate AST.Statement where
validate = \case
AST.Binding _ name@(NameWith _ info) expr -> do
case info of
HasType ty -> validateExpr ty expr
IsType _ -> throwError (BadType ExpectedExpression (AST.Named name))
AST.Assign name@(NameWith _ info) expr -> do
case info of
HasType ty -> validateExpr ty expr
IsType _ -> throwError (BadType ExpectedExpression (AST.Named name))
AST.IfThen expr body -> do
validateExpr Bool expr
validate body
AST.IfThenElse expr body1 body2 -> do
validateExpr Bool expr
mapM_ validate [body1, body2]
AST.Forever body -> do
validate body
AST.While expr body -> do
validateExpr Bool expr
validate body
AST.Return target maybeExpr -> do
mapM_ (validateExpr (typeOf (AST.Named target))) maybeExpr
when (maybeExpr == Nothing) do
validateName Unit target
AST.Break target -> do
validateName Unit target
AST.Expression expr -> do
validate expr
instance Validate AST.Expression where
validate = \case
AST.UnaryOperator op expr -> do
validateExpr opExpectsType expr where
opExpectsType = case op of
Not -> Bool
Negate -> Int
AST.BinaryOperator expr1 op expr2 -> do
mapM_ (validateExpr opExpectsType) [expr1, expr2] where
opExpectsType = case op of
ArithmeticOperator _ -> Int
ComparisonOperator _ -> Int
LogicalOperator _ -> Bool
AST.Named _ -> do
return ()
AST.NumberLiteral _ -> do
return ()
AST.TextLiteral _ -> do
return ()
AST.Call function args -> do
case typeOf (nodeWithout function) of
Function argTypes _ -> do
when (length args != length argTypes) do
throwError (BadArgumentCount (length argTypes) (AST.Call function args))
zipWithM_ validateExpr argTypes args
_ -> do
throwError (BadType ExpectedFunction (nodeWithout function))
instance Validate node => Validate (NodeWith node) where
validate = validate . nodeWithout
validateName :: Type -> TypedName -> ValidateM metadata ()
validateName ty = validateExprImpl ty . AST.Named
validateExpr :: Type -> NodeWith AST.Expression metadata TypedName -> ValidateM metadata ()
validateExpr ty = validateExprImpl ty . nodeWithout
validateExprImpl :: Type -> AST.Expression metadata TypedName -> ValidateM metadata ()
validateExprImpl expectedType expr = do
when (typeOf expr != expectedType) do -- FIXME maybe `validate` shouldn't panic if it sees a `Type` in the wrong place, as `typeOf` does!!
throwError (BadType (Expected expectedType) expr)
validate expr
| glaebhoerl/stageless | src/Type.hs | mit | 21,010 | 0 | 24 | 6,117 | 5,649 | 2,718 | 2,931 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import System.IO
import ReadArgs
import CombinatoryCalculator
import ImageGenerator
main :: IO ()
main = do
(command:: String, x:xs :: [String]) <-readArgs
let f x = (putStrLn . show) x
g (x:y:rest) = (read x, read y)
g _ = (512, 512)
h (x:y:z:rest) = (read x, read y, read z)
h _ = (512, 512, 512)
in case command of
"-p" -> f $ Parse $ fromString x
"-d" -> f $ Decorate $ fromString x
"-f" -> f $ FindRedexes $ fromString x
"-a" -> f $ Analyze $ fromString x
"-s" -> f $ Step $ fromString x
"-n" -> f $ StepN (read x) $ fromString $ head xs
"-t" -> f $ TraceN (read x) $ fromString $ head xs
"-o" -> f $ TraceNPolish (read x) $ fromString $ head xs
"-r" -> f $ Reduce $ fromString x
"-v" -> visualize x $ g xs
"-w" -> visualize2 x $ g xs
-- "-x" -> visualizeRandom $ h (x:xs)
-- "-y" -> visualizeRandom2 $ h (x:xs)
_ -> f $ "Unknown command \"" ++ command ++ "\".\n" ++
(show Help)
-- TODO: Implement visualization for -v and -w flags with a randomly
-- generated expression, from an integer seed.
| jllang/CombinatoryCalculator | src/Main.hs | mit | 1,604 | 0 | 17 | 761 | 452 | 227 | 225 | 28 | 14 |
module Main where
import Control.Arrow ((&&&))
import Control.Monad ((<=<))
import Data.Bool (bool)
import Data.Foldable (find)
import Data.List (inits)
import Data.Map.Strict (empty, insertWith)
import Data.Monoid (Sum (..))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
part1 :: [Text] -> Int
part1 = getSum . uncurry (*) . foldMap ((has 2 &&& has 3) . counts)
where
has n = Sum . bool 0 1 . elem n
counts = T.foldl' (\m c -> insertWith (+) c (1 :: Word) m) empty
part2 :: [Text] -> Maybe Text
part2 ts = search . zip ts $ inits ts
where
search = find isProperLen <=< (find (any isProperLen) . fmap commons)
commons (x, xs) = fmap (commonChars x) xs
commonChars a b =
T.filter (/= ' ') $ T.zipWith (\x y -> bool ' ' x (x == y)) a b
isProperLen = (== (T.length (head ts) - 1)) . T.length
main :: IO ()
main = do
ids <- T.lines <$> T.readFile "input"
print . part1 $ ids
print . part2 $ ids
| genos/online_problems | advent_of_code_2018/day02/src/Main.hs | mit | 1,081 | 0 | 13 | 321 | 470 | 256 | 214 | 27 | 1 |
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE RecordWildCards #-}
module Problem04 (partA, partB) where
import Data.List
import Text.Megaparsec hiding (State)
import Text.Megaparsec.String
import qualified Data.Map as M
import qualified Text.Megaparsec.Lexer as L
partA = readFile inputLocation >>= print . partAString
partB = readFile inputLocation >>= print . partBString
inputLocation = "input/input4.txt"
data RoomID = RoomID {
name :: String
, sectorId :: Integer
, checksum :: String
}
deriving (Eq,Show)
parseRoomID :: Parser RoomID
parseRoomID = do
name <- concat <$> many ((++) <$> (many lowerChar) <*> string "-")
sectorID <- L.integer
char '['
checksum <- manyTill lowerChar $ char ']'
return $ RoomID name sectorID checksum
mostCommon :: (Ord a) => Int -> [a] -> [a]
mostCommon n = map fst . take n . reverse . sortBy sortHelper . M.toList .
foldr (M.unionWith (+)) M.empty . map (\c -> M.singleton c (1 :: Int))
where sortHelper (c1,n1) (c2,n2)
| n1 == n2 = compare c2 c1
| otherwise = compare n1 n2
validRoomID :: RoomID -> Bool
validRoomID RoomID{..} = checksum == mostCommon 5 (filter (/= '-') name)
partAString :: String -> Either (ParseError Char Dec) Integer
partAString = fmap (sum . map sectorId . filter validRoomID) .
parse (many $ parseRoomID <* space) ""
applyShift :: Int -> String -> String
applyShift n = head . drop n . iterate (map helper)
where helper '-' = '_'
helper 'z' = 'a'
helper x = succ x
partBString :: String -> Either (ParseError Char Dec) Integer
partBString = fmap (sectorId . head . filter (isInfixOf "pol" . name)
. map (\r -> r { name = applyShift (fromIntegral $ sectorId r) (name r)})
. filter validRoomID) .
parse (many $ parseRoomID <* space) ""
| edwardwas/adventOfCodeTwo | src/Problem04.hs | mit | 1,868 | 0 | 18 | 450 | 694 | 360 | 334 | 44 | 3 |
{- |
Module : $Header$
Description : A Parser for the TPTP-THF Syntax
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Alexis.Tsogias@dfki.de
Stability : provisional
Portability : portable
A Parser for the TPTP-THF Input Syntax v5.1.0.2 taken from
<http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html>
-}
module THF.ParseTHF (parseTHF) where
import THF.As
import Text.ParserCombinators.Parsec
import Common.Parsec
import Data.Char
import Data.Maybe
--------------------------------------------------------------------------------
-- Parser for the THF Syntax
-- Most methods match those of As.hs
--------------------------------------------------------------------------------
parseTHF :: CharParser st [TPTP_THF]
parseTHF = do
h <- optionMaybe header
thf <- many ((systemComment <|> definedComment <|> comment <|>
include <|> thfAnnotatedFormula) << skipSpaces)
return $ if isJust h then fromJust h : thf else thf
header :: CharParser st TPTP_THF
header = try (do
s <- headerSE
c <- myManyTill (try (commentLine << skipSpaces)) (try headerSE)
return $ TPTP_Header (s : c))
headerSE :: CharParser st Comment
headerSE = do
try (char '%' >> notFollowedBy (char '$'))
c <- many1 $ char '-' << notFollowedBy printableChar
skipSpaces
return $ Comment_Line c
commentLine :: CharParser st Comment
commentLine = do
try (char '%' >> notFollowedBy (char '$'))
c <- many printableChar
return $ Comment_Line c
comment :: CharParser st TPTP_THF
comment = fmap TPTP_Comment commentLine
<|> do
try (string "/*" >> notFollowedBy (char '$'))
c <- many (noneOf "*/")
skipMany1 (char '*'); char '/'
return $ TPTP_Comment (Comment_Block (lines c))
definedComment :: CharParser st TPTP_THF
definedComment = do
try (string "%$" >> notFollowedBy (char '$'))
c <- many printableChar
return $ TPTP_Defined_Comment (Defined_Comment_Line c)
<|> do
try (string "/*$" >> notFollowedBy (char '$'))
c <- many (noneOf "*/")
skipMany1 (char '*'); char '/'
return $ TPTP_Defined_Comment (Defined_Comment_Block (lines c))
systemComment :: CharParser st TPTP_THF
systemComment = do
tryString "%$$"
c <- many printableChar
return $ TPTP_System_Comment (System_Comment_Line c)
<|> do
tryString "/*$$"
c <- many (noneOf "*/")
skipMany1 (char '*'); char '/'
return $ TPTP_System_Comment (System_Comment_Block (lines c))
include :: CharParser st TPTP_THF
include = do
key $ tryString "include"
oParentheses
fn <- fileName
fs <- formulaSelection
cParentheses; char '.'
return $ TPTP_Include (I_Include fn fs)
thfAnnotatedFormula :: CharParser st TPTP_THF
thfAnnotatedFormula = do
key $ tryString "thf"
oParentheses
n <- name; comma
fr <- formulaRole; comma
tf <- thfFormula
a <- annotations
cParentheses; char '.'
return $ TPTP_THF_Annotated_Formula n fr tf a
annotations :: CharParser st Annotations
annotations = do
comma
s <- source
oi <- optionalInfo
return $ Annotations s oi
<|> do
notFollowedBy (char ',');
return Null
formulaRole :: CharParser st FormulaRole
formulaRole = do
r <- lowerWord
case r of
"axiom" -> return Axiom
"hypothesis" -> return Hypothesis
"definition" -> return Definition
"assumption" -> return Assumption
"lemma" -> return Lemma
"theorem" -> return Theorem
"conjecture" -> return Conjecture
"negated_conjecture" -> return Negated_Conjecture
"plain" -> return Plain
"fi_domain" -> return Fi_Domain
"fi_functors" -> return Fi_Functors
"fi_predicates" -> return Fi_Predicates
"type" -> return Type
"unknown" -> return Unknown
_ -> fail ("No such Role: " ++ r)
thfFormula :: CharParser st THFFormula
thfFormula = fmap TF_THF_Logic_Formula thfLogicFormula
<|> fmap TF_THF_Sequent thfSequent
thfLogicFormula :: CharParser st THFLogicFormula
thfLogicFormula = fmap TLF_THF_Binary_Formula thfBinaryFormula
<|> fmap TLF_THF_Type_Formula thfTypeFormula
<|> fmap TLF_THF_Sub_Type thfSubType
<|> fmap TLF_THF_Unitary_Formula thfUnitaryFormula
thfBinaryFormula :: CharParser st THFBinaryFormula
thfBinaryFormula = fmap TBF_THF_Binary_Type thfBinaryType
<|> fmap TBF_THF_Binary_Tuple thfBinaryTuple
<|> do
(uff, pc) <- try $ do
uff1 <- thfUnitaryFormula
pc1 <- thfPairConnective
return (uff1, pc1)
ufb <- thfUnitaryFormula
return $ TBF_THF_Binary_Pair uff pc ufb
thfBinaryTuple :: CharParser st THFBinaryTuple
thfBinaryTuple = do -- or
uff <- try (thfUnitaryFormula << vLine)
ufb <- sepBy1 thfUnitaryFormula vLine
return $ TBT_THF_Or_Formula (uff : ufb)
<|> do -- and
uff <- try (thfUnitaryFormula << ampersand)
ufb <- sepBy1 thfUnitaryFormula ampersand
return $ TBT_THF_And_Formula (uff : ufb)
<|> do -- apply
uff <- try (thfUnitaryFormula << at)
ufb <- sepBy1 thfUnitaryFormula at
return $ TBT_THF_Apply_Formula (uff : ufb)
thfUnitaryFormula :: CharParser st THFUnitaryFormula
thfUnitaryFormula = fmap TUF_THF_Logic_Formula_Par (parentheses thfLogicFormula)
<|> fmap TUF_THF_Quantified_Formula thfQuantifiedFormula
<|> thfUnaryFormula
<|> fmap TUF_THF_Atom thfAtom
<|> fmap TUF_THF_Tuple thfTuple
<|> do
key $ tryString ":="
ll <- brackets (sepBy1 thfDefinedVar comma); colon
uf <- thfUnitaryFormula
return $ TUF_THF_Let ll uf
<|> do
key $ tryString "$itef"; oParentheses
lf1 <- thfLogicFormula; comma
lf2 <- thfLogicFormula; comma
lf3 <- thfLogicFormula; cParentheses
return $ TUF_THF_Conditional lf1 lf2 lf3
thfQuantifiedFormula :: CharParser st THFQuantifiedFormula
thfQuantifiedFormula = do
q <- thfQuantifier
vl <- brackets thfVariableList; colon
uf <- thfUnitaryFormula
return $ TQF_THF_Quantified_Formula q vl uf
thfVariableList :: CharParser st THFVariableList
thfVariableList = sepBy1 thfVariable comma
thfVariable :: CharParser st THFVariable
thfVariable = do
v <- try (variable << colon)
tlt <- thfTopLevelType
return $ TV_THF_Typed_Variable v tlt
<|> fmap TV_Variable variable
thfUnaryFormula :: CharParser st THFUnitaryFormula
thfUnaryFormula = do
uc <- thfUnaryConnective
lf <- parentheses thfLogicFormula
return $ TUF_THF_Unary_Formula uc lf
thfTypeFormula :: CharParser st THFTypeFormula
thfTypeFormula = do
tp <- try (thfTypeableFormula << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Type_Formula tp tlt
<|> do
c <- try (constant << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Typed_Const c tlt
thfTypeableFormula :: CharParser st THFTypeableFormula
thfTypeableFormula = fmap TTyF_THF_Atom thfAtom
<|> fmap TTyF_THF_Tuple thfTuple
<|> fmap TTyF_THF_Logic_Formula (parentheses thfLogicFormula)
thfSubType :: CharParser st THFSubType
thfSubType = do
cf <- try (constant << key (string "<<"))
cb <- constant
return $ TST_THF_Sub_Type cf cb
thfTopLevelType :: CharParser st THFTopLevelType
thfTopLevelType = fmap TTLT_THF_Logic_Formula thfLogicFormula
thfUnitaryType :: CharParser st THFUnitaryType
thfUnitaryType = fmap TUT_THF_Unitary_Formula thfUnitaryFormula
thfBinaryType :: CharParser st THFBinaryType
thfBinaryType = do -- mappingType
utf <- try (thfUnitaryType << arrow)
utb <- sepBy1 thfUnitaryType arrow
return $ TBT_THF_Mapping_Type (utf : utb)
<|> do -- xprodType
utf <- try (thfUnitaryType << star)
utb <- sepBy1 thfUnitaryType star
return $ TBT_THF_Xprod_Type (utf : utb)
<|> do -- unionType
utf <- try (thfUnitaryType << plus)
utb <- sepBy1 thfUnitaryType plus
return $ TBT_THF_Union_Type (utf : utb)
thfAtom :: CharParser st THFAtom
thfAtom = fmap TA_Defined_Type definedType
<|> fmap TA_Defined_Plain_Formula definedPlainFormula
<|> fmap TA_System_Type systemType
<|> fmap TA_System_Atomic_Formula systemTerm
<|> fmap TA_Term term
<|> fmap TA_THF_Conn_Term thfConnTerm
thfTuple :: CharParser st THFTuple
thfTuple = try ((oBracket >> cBracket) >> return [])
<|> brackets (sepBy1 thfUnitaryFormula comma)
thfDefinedVar :: CharParser st THFDefinedVar
thfDefinedVar = fmap TDV_THF_Defined_Var_Par (parentheses thfDefinedVar)
<|> do
v <- try (thfVariable << key ( string ":="))
lf <- thfLogicFormula
return $ TDV_THF_Defined_Var v lf
thfSequent :: CharParser st THFSequent
thfSequent = fmap TS_THF_Sequent_Par (parentheses thfSequent)
<|> do
tf <- try (thfTuple << gentzenArrow)
tb <- thfTuple
return $ TS_THF_Sequent tf tb
thfConnTerm :: CharParser st THFConnTerm
thfConnTerm = fmap TCT_THF_Pair_Connective thfPairConnective
<|> fmap TCT_Assoc_Connective assocConnective
<|> fmap TCT_THF_Unary_Connective thfUnaryConnective
thfQuantifier :: CharParser st THFQuantifier
thfQuantifier = (keyChar '!' >> return TQ_ForAll)
<|> (keyChar '?' >> return TQ_Exists)
<|> (keyChar '^' >> return TQ_Lambda_Binder)
<|> (key (tryString "!>") >> return TQ_Dependent_Product)
<|> (key (tryString "?*") >> return TQ_Dependent_Sum)
<|> (key (tryString "@+") >> return TQ_Indefinite_Description)
<|> (key (tryString "@-") >> return TQ_Definite_Description)
<?> "quantifier"
thfPairConnective :: CharParser st THFPairConnective
thfPairConnective = (key (tryString "!=") >> return Infix_Inequality)
<|> (key (tryString "<=>") >> return Equivalent)
<|> (key (tryString "=>") >> return Implication)
<|> (key (tryString "<=") >> return IF)
<|> (key (tryString "<~>") >> return XOR)
<|> (key (tryString "~|") >> return NOR)
<|> (key (tryString "~&") >> return NAND)
<|> (keyChar '=' >> return Infix_Equality)
<?> "pairConnective"
thfUnaryConnective :: CharParser st THFUnaryConnective
thfUnaryConnective = (keyChar '~' >> return Negation)
<|> (key (tryString "!!") >> return PiForAll)
<|> (key (tryString "??") >> return SigmaExists)
assocConnective :: CharParser st AssocConnective
assocConnective = (keyChar '|' >> return OR)
<|> (keyChar '&' >> return AND)
definedType :: CharParser st DefinedType
definedType = do
adw <- atomicDefinedWord
case adw of
"oType" -> return DT_oType
"o" -> return DT_o
"iType" -> return DT_iType
"i" -> return DT_i
"tType" -> return DT_tType
"real" -> return DT_real
"rat" -> return DT_rat
"int" -> return DT_int
_ -> fail ("No such definedType: " ++ adw)
systemType :: CharParser st SystemType
systemType = atomicSystemWord
definedPlainFormula :: CharParser st DefinedPlainFormula
definedPlainFormula = fmap DPF_Defined_Prop definedProp
<|> do
dp <- definedPred
a <- parentheses arguments
return $ DPF_Defined_Formula dp a
definedProp :: CharParser st DefinedProp
definedProp = do
adw <- atomicDefinedWord
case adw of
"true" -> return DP_True
"false" -> return DP_False
_ -> fail ("No such definedProp: " ++ adw)
definedPred :: CharParser st DefinedPred
definedPred = do
adw <- atomicDefinedWord
case adw of
"equal" -> return Equal
"distinct" -> return Disrinct
"itef" -> return Itef
"less" -> return Less
"lesseq" -> return Lesseq
"greater" -> return Greater
"greatereq" -> return Greatereq
"evaleq" -> return Evaleq
"is_int" -> return Is_int
"is_rat" -> return Is_rat
_ -> fail ("No such definedPred: " ++ adw)
term :: CharParser st Term
term = fmap T_Function_Term functionTerm
<|> fmap T_Variable variable
functionTerm :: CharParser st FunctionTerm
functionTerm = fmap FT_System_Term systemTerm
<|> fmap FT_Defined_Term definedTerm
<|> fmap FT_Plain_Term plainTerm
plainTerm :: CharParser st PlainTerm
plainTerm = try (do
f <- tptpFunctor
a <- parentheses arguments
return $ PT_Plain_Term f a)
<|> fmap PT_Constant constant
constant :: CharParser st Constant
constant = tptpFunctor
tptpFunctor :: CharParser st TPTPFunctor
tptpFunctor = atomicWord
definedTerm :: CharParser st DefinedTerm
definedTerm = fmap DT_Defined_Atomic_Term definedPlainTerm
<|> fmap DT_Defined_Atom definedAtom
definedAtom :: CharParser st DefinedAtom
definedAtom = fmap DA_Number number
<|> fmap DA_Distinct_Object distinctObject
definedPlainTerm :: CharParser st DefinedPlainTerm
definedPlainTerm = try (do
df <- definedFunctor
a <- parentheses arguments
return $ DPT_Defined_Function df a)
<|> fmap DPT_Defined_Constant definedFunctor
definedFunctor :: CharParser st DefinedFunctor
definedFunctor = do
adw <- atomicDefinedWord
case adw of
"itett" -> return Itett
"uminus" -> return Uminus
"sum" -> return Sum
"difference" -> return Difference
"product" -> return Product
"to_int" -> return To_int
"to_rat" -> return To_rat
"to_real" -> return To_real
_ -> fail ("No such definedFunctor: " ++ adw)
systemTerm :: CharParser st SystemTerm
systemTerm = try (do
sf <- systemFunctor
a <- parentheses arguments
return $ ST_System_Term sf a)
<|> fmap ST_System_Constant systemFunctor
systemFunctor :: CharParser st SystemFunctor
systemFunctor = atomicSystemWord
variable :: CharParser st Variable
variable = do
u <- upper
an <- many alphaNum
skipAll
return (u : an)
<?> "Variable"
arguments :: CharParser st Arguments
arguments = sepBy1 term comma
principalSymbol :: CharParser st PrincipalSymbol
principalSymbol = fmap PS_Functor tptpFunctor
<|> fmap PS_Variable variable
source :: CharParser st Source
source = (key (tryString "unknown") >> return S_Unknown)
<|> fmap S_Dag_Source dagSource
<|> fmap S_External_Source externalSource
<|> fmap S_Sources (sepBy1 source comma)
<|> do -- internal_source
key $ tryString "introduced"; oParentheses
it <- introType
oi <- optionalInfo; cParentheses
return $ S_Internal_Source it oi
dagSource :: CharParser st DagSource
dagSource = do
key (tryString "inference"); oParentheses
ir <- atomicWord; comma
ui <- usefulInfo; comma
pl <- brackets (sepBy1 parentInfo comma)
cParentheses
return (DS_Inference_Record ir ui pl)
<|> fmap DS_Name name
parentInfo :: CharParser st ParentInfo
parentInfo = do
s <- source
pd <- parentDetails
return $ PI_Parent_Info s pd
parentDetails :: CharParser st (Maybe GeneralList)
parentDetails = fmap Just (colon >> generalList)
<|> (notFollowedBy (char ':') >> return Nothing)
introType :: CharParser st IntroType
introType = (key (tryString "definition") >> return IT_definition)
<|> (key (tryString "axiom_of_choice") >> return IT_axiom_of_choice)
<|> (key (tryString "tautology") >> return IT_tautology)
<|> (key (tryString "assumption") >> return IT_assumption)
externalSource :: CharParser st ExternalSource
externalSource = fmap ES_File_Source fileSource
<|> do
key $ tryString "theory"; oParentheses
tn <- theoryName
oi <- optionalInfo; cParentheses
return $ ES_Theory tn oi
<|> do
key $ tryString "creator"; oParentheses
cn <- atomicWord
oi <- optionalInfo; cParentheses
return $ ES_Creator_Source cn oi
fileSource :: CharParser st FileSource
fileSource = do
key $ tryString "file"; oParentheses
fn <- fileName
fi <- fileInfo; cParentheses
return $ FS_File fn fi
fileInfo :: CharParser st (Maybe Name)
fileInfo = fmap Just (comma >> name)
<|> (notFollowedBy (char ',') >> return Nothing)
theoryName :: CharParser st TheoryName
theoryName = (key (tryString "equality") >> return Equality)
<|> (key (tryString "ac") >> return Ac)
optionalInfo :: CharParser st OptionalInfo
optionalInfo = fmap Just (comma >> usefulInfo)
<|> (notFollowedBy (char ',') >> return Nothing)
usefulInfo :: CharParser st UsefulInfo
usefulInfo = (oBracket >> cBracket >> return [])
<|> brackets (sepBy1 infoItem comma)
infoItem :: CharParser st InfoItem
infoItem = fmap II_Formula_Item formulaItem
<|> fmap II_Inference_Item inferenceItem
<|> fmap II_General_Function generalFunction
formulaItem :: CharParser st FormulaItem
formulaItem = do
key $ tryString "description"
fmap FI_Description_Item (parentheses atomicWord)
<|> do
key $ tryString "iquote"
fmap FI_Iquote_Item (parentheses atomicWord)
inferenceItem :: CharParser st InferenceItem
inferenceItem = fmap II_Inference_Status inferenceStatus
<|> do
key $ tryString "assumptions"
fmap II_Assumptions_Record (parentheses (brackets nameList))
<|> do
key $ tryString "new_symbols"; oParentheses
aw <- atomicWord; comma
nsl <- brackets (sepBy1 principalSymbol comma); cParentheses
return $ II_New_Symbol_Record aw nsl
<|> do
key $ tryString "refutation"
fmap II_Refutation (parentheses fileSource)
inferenceStatus :: CharParser st InferenceStatus
inferenceStatus = do
key $ tryString "status"
fmap IS_Status (parentheses statusValue)
<|> do
ir <- try (atomicWord << oParentheses)
aw <- atomicWord; comma
gl <- generalList; cParentheses
return $ IS_Inference_Info ir aw gl
statusValue :: CharParser st StatusValue
statusValue = choice $ map (\ r -> key (tryString $ showStatusValue r)
>> return r) allStatusValues
allStatusValues :: [StatusValue]
allStatusValues =
[Suc, Unp, Sap, Esa, Sat, Fsa, Thm, Eqv, Tac,
Wec, Eth, Tau, Wtc, Wth, Cax, Sca, Tca, Wca,
Cup, Csp, Ecs, Csa, Cth, Ceq, Unc, Wcc, Ect,
Fun, Uns, Wuc, Wct, Scc, Uca, Noc]
showStatusValue :: StatusValue -> String
showStatusValue = map toLower . show
formulaSelection :: CharParser st (Maybe NameList)
formulaSelection = fmap Just (comma >> brackets nameList)
<|> (notFollowedBy (char ',') >> return Nothing)
nameList :: CharParser st NameList
nameList = sepBy1 name comma
generalTerm :: CharParser st GeneralTerm
generalTerm = do
gd <- try (generalData << notFollowedBy (char ':'))
return $ GT_General_Data gd
<|> do
gd <- try (generalData << colon)
gt <- generalTerm
return $ GT_General_Data_Term gd gt
<|> fmap GT_General_List generalList
generalData :: CharParser st GeneralData
generalData = fmap GD_Variable variable
<|> fmap GD_Number number
<|> fmap GD_Distinct_Object distinctObject
<|> do
key $ tryString "bind"; oParentheses
v <- variable; comma
fd <- formulaData; cParentheses
return (GD_Bind v fd)
<|> fmap GD_General_Function generalFunction
<|> fmap GD_Atomic_Word atomicWord
<|> fmap GD_Formula_Data formulaData
generalFunction :: CharParser st GeneralFunction
generalFunction = do
aw <- atomicWord
gts <- parentheses generalTerms
return $ GF_General_Function aw gts
formulaData :: CharParser st FormulaData
formulaData = fmap THF_Formula thfFormula
generalList :: CharParser st GeneralList
generalList = (try (oBracket >> cBracket) >> return [])
<|> brackets generalTerms
generalTerms :: CharParser st [GeneralTerm]
generalTerms = sepBy1 generalTerm comma
name :: CharParser st Name
name = fmap N_Integer (integer << skipAll)
<|> fmap N_Atomic_Word atomicWord
atomicWord :: CharParser st AtomicWord
atomicWord = fmap A_Lower_Word lowerWord
<|> fmap A_Single_Quoted singleQuoted
<?> "lowerWord or singleQuoted"
atomicDefinedWord :: CharParser st String
atomicDefinedWord = char '$' >> lowerWord
atomicSystemWord :: CharParser st AtomicSystemWord
atomicSystemWord = tryString "$$" >> lowerWord
number :: CharParser st Number
number = fmap Num_Real (real << skipAll)
<|> fmap Num_Rational (rational << skipAll)
<|> fmap Num_Integer (integer << skipAll)
fileName :: CharParser st FileName
fileName = singleQuoted
singleQuoted :: CharParser st SingleQuoted
singleQuoted = do
char '\''
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\'"
<|> tryString "\\\'"
<|> single ( satisfy (\ c -> printable c && notElem c ['\'', '\\'])))
keyChar '\''
return s
distinctObject :: CharParser st DistinctObject
distinctObject = do
char '\"'
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\\""
<|> single ( satisfy (\ c -> printable c && notElem c ['\'', '\\'])))
keyChar '\"'
return s
lowerWord :: CharParser st LowerWord
lowerWord = do
l <- lower
an <- many (alphaNum <|> char '_'); skipAll
return (l : an)
<?> "alphanumeric word with leading lowercase letter"
printableChar :: CharParser st Char
printableChar = satisfy printable
printable :: Char -> Bool
printable c = ord c >= 32 && ord c <= 126
-- Numbers
real :: CharParser st String
real = try (do
s <- oneOf "-+"
ur <- unsignedReal
return (s : ur))
<|> unsignedReal
<?> "(signed) real"
unsignedReal :: CharParser st String
unsignedReal = do
de <- try (do
d <- decimalFractional <|> decimal
e <- oneOf "Ee"
return (d ++ [e]))
ex <- decimal
return (de ++ ex)
<|> decimalFractional
<?> "unsigned real"
rational :: CharParser st String
rational = try (do
s <- oneOf "-+"
ur <- unsignedRational
return (s : ur))
<|> unsignedRational
<?> "(signed) rational"
unsignedRational :: CharParser st String
unsignedRational = do
d1 <- try (decimal << char '/')
d2 <- positiveDecimal
return (d1 ++ "/" ++ d2)
integer :: CharParser st String
integer = try (do
s <- oneOf "-+"
ui <- unsignedInteger
return (s : ui))
<|> unsignedInteger
<?> "(signed) integer"
unsignedInteger :: CharParser st String
unsignedInteger = try ( decimal << notFollowedBy (oneOf "eE/."))
decimal :: CharParser st String
decimal = do
char '0'
notFollowedBy digit
return "0"
<|> positiveDecimal
<?> "single zero or digits"
positiveDecimal :: CharParser st String
positiveDecimal = do
nz <- satisfy (\ c -> isDigit c && c /= '0')
d <- many digit
return (nz : d)
<?> "positiv decimal"
decimalFractional :: CharParser st String
decimalFractional = do
dec <- try (decimal << char '.')
n <- many1 digit
return (dec ++ "." ++ n)
<?> "decimal fractional"
--------------------------------------------------------------------------------
-- Some helper functions
--------------------------------------------------------------------------------
skipAll :: CharParser st ()
skipAll = skipMany (skipMany1 space <|>
((comment <|> definedComment <|>
systemComment) >> return ()))
skipSpaces :: CharParser st ()
skipSpaces = skipMany space
key :: CharParser st a -> CharParser st ()
key = (>> skipAll)
keyChar :: Char -> CharParser st ()
keyChar = key . char
myManyTill :: CharParser st a -> CharParser st a -> CharParser st [a]
myManyTill p end = do
e <- end ; return [e]
<|> do
x <- p; xs <- myManyTill p end; return (x : xs)
--------------------------------------------------------------------------------
-- Different simple symbols
--------------------------------------------------------------------------------
vLine :: CharParser st ()
vLine = keyChar '|'
star :: CharParser st ()
star = keyChar '*'
plus :: CharParser st ()
plus = keyChar '+'
arrow :: CharParser st ()
arrow = keyChar '>'
comma :: CharParser st ()
comma = keyChar ','
colon :: CharParser st ()
colon = keyChar ':'
oParentheses :: CharParser st ()
oParentheses = keyChar '('
cParentheses :: CharParser st ()
cParentheses = keyChar ')'
parentheses :: CharParser st a -> CharParser st a
parentheses p = do
r <- try (oParentheses >> p)
cParentheses
return r
oBracket :: CharParser st ()
oBracket = keyChar '['
cBracket :: CharParser st ()
cBracket = keyChar ']'
brackets :: CharParser st a -> CharParser st a
brackets p = do
r <- try (oBracket >> p)
cBracket
return r
ampersand :: CharParser st ()
ampersand = keyChar '&'
at :: CharParser st ()
at = keyChar '@'
gentzenArrow :: CharParser st ()
gentzenArrow = key $ string "-->"
| nevrenato/Hets_Fork | THF/ParseTHF.hs | gpl-2.0 | 24,546 | 0 | 19 | 5,514 | 7,339 | 3,494 | 3,845 | 654 | 15 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-
Copyright (C) 2010 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
-}
{- | Functions for parsing LaTeX macro definitions and applying macros
to LateX expressions.
-}
module Text.TeXMath.Readers.TeX.Macros
( Macro
, parseMacroDefinitions
, pMacroDefinition
, applyMacros
)
where
import Data.Char (isDigit, isLetter)
import qualified Data.Text as T
import Control.Monad
import Text.Parsec
data Macro = Macro { macroDefinition :: T.Text
, macroParser :: forall st m s . Stream s m Char =>
ParsecT s st m T.Text }
instance Show Macro where
show m = "Macro " ++ show (macroDefinition m)
-- | Parses a string for a list of macro definitions, optionally
-- separated and ended by spaces and TeX comments. Returns
-- the list of macros (which may be empty) and the unparsed
-- portion of the input string.
parseMacroDefinitions :: T.Text -> ([Macro], T.Text)
parseMacroDefinitions s =
case parse pMacroDefinitions "input" s of
Left _ -> ([], s)
Right res -> res
-- | Parses one or more macro definitions separated by comments & space.
-- Return list of macros parsed + remainder of string.
pMacroDefinitions :: (Monad m, Stream s m Char)
=> ParsecT s st m ([Macro], s)
pMacroDefinitions = do
pSkipSpaceComments
defs <- sepEndBy pMacroDefinition pSkipSpaceComments
rest <- getInput
return (reverse defs, rest) -- reversed so later macros shadow earlier
-- | Parses a @\\newcommand@ or @\\renewcommand@ macro definition and
-- returns a 'Macro'.
pMacroDefinition :: (Monad m, Stream s m Char)
=> ParsecT s st m Macro
pMacroDefinition = newcommand <|> declareMathOperator <|> newenvironment
-- | Skip whitespace and comments.
pSkipSpaceComments :: (Monad m, Stream s m Char)
=> ParsecT s st m ()
pSkipSpaceComments = spaces >> skipMany (comment >> spaces)
-- | Applies a list of macros to a string recursively until a fixed
-- point is reached. If there are several macros in the list with the
-- same name, earlier ones will shadow later ones.
applyMacros :: [Macro] -> T.Text -> T.Text
applyMacros [] s = s
applyMacros ms s =
maybe s id $ iterateToFixedPoint ((2 * length ms) + 1)
(applyMacrosOnce ms) s
------------------------------------------------------------------------------
iterateToFixedPoint :: Eq a => Int -> (a -> Maybe a) -> a -> Maybe a
iterateToFixedPoint 0 _ _ = Nothing
-- Macro application did not terminate in a reasonable time, possibly
-- because of a loop in the macro.
iterateToFixedPoint limit f x =
case f x of
Nothing -> Nothing
Just y
| y == x -> Just y
| otherwise -> iterateToFixedPoint (limit - 1) f y
applyMacrosOnce :: [Macro] -> T.Text -> Maybe T.Text
applyMacrosOnce ms s =
case parse (many tok) "input" s of
Right r -> Just $ T.concat r
Left _ -> Nothing
where tok = try $ do
skipComment
choice [ choice (map (\m -> macroParser m) ms)
, T.pack <$> ctrlseq
, T.pack <$> count 1 anyChar ]
ctrlseq :: (Monad m, Stream s m Char)
=> ParsecT s st m String
ctrlseq = do
char '\\'
res <- many1 letter <|> count 1 anyChar
return $ '\\' : res
newcommand :: (Monad m, Stream s m Char)
=> ParsecT s st m Macro
newcommand = try $ do
char '\\'
-- we ignore differences between these so far:
try (string "newcommand")
<|> try (string "renewcommand")
<|> string "providecommand"
optional (char '*')
pSkipSpaceComments
name <- inbraces <|> ctrlseq
guard (take 1 name == "\\")
let name' = drop 1 name
numargs <- numArgs
pSkipSpaceComments
optarg <- if numargs > 0
then optArg
else return Nothing
let numargs' = case optarg of
Just _ -> numargs - 1
Nothing -> numargs
pSkipSpaceComments
body <- inbraces <|> ctrlseq
let defn = "\\newcommand{" ++ name ++ "}" ++
(if numargs > 0 then ("[" ++ show numargs ++ "]") else "") ++
case optarg of { Nothing -> ""; Just x -> "[" ++ x ++ "]"} ++
"{" ++ body ++ "}"
return $ Macro (T.pack defn) $ fmap T.pack $ try $ do
char '\\'
string name'
when (all isLetter name') $
notFollowedBy letter
pSkipSpaceComments
opt <- case optarg of
Nothing -> return Nothing
Just _ -> liftM (`mplus` optarg) optArg
args <- count numargs' (pSkipSpaceComments >>
(inbraces <|> ctrlseq <|> count 1 anyChar))
let args' = case opt of
Just x -> x : args
Nothing -> args
return $ apply args' $ "{" ++ body ++ "}"
newenvironment :: (Monad m, Stream s m Char)
=> ParsecT s st m Macro
newenvironment = try $ do
char '\\'
-- we ignore differences between these so far:
optional (string "re")
string "newenvironment"
optional (char '*')
pSkipSpaceComments
name <- inbraces <|> ctrlseq
numargs <- numArgs
pSkipSpaceComments
optarg <- if numargs > 0
then optArg <* pSkipSpaceComments
else return Nothing
let numargs' = case optarg of
Just _ -> numargs - 1
Nothing -> numargs
opener <- inbraces <|> ctrlseq
pSkipSpaceComments
closer <- inbraces <|> ctrlseq
let defn = "\\newenvironment{" ++ name ++ "}" ++
(if numargs > 0 then ("[" ++ show numargs ++ "]") else "") ++
case optarg of { Nothing -> ""; Just x -> "[" ++ x ++ "]"} ++
"%\n{" ++ opener ++ "}%\n" ++ "{" ++ closer ++ "}"
return $ Macro (T.pack defn) $ fmap T.pack $ try $ do
string "\\begin"
pSkipSpaceComments
char '{'
string name
pSkipSpaceComments
char '}'
opt <- case optarg of
Nothing -> return Nothing
Just _ -> liftM (`mplus` optarg) optArg
args <- count numargs' (pSkipSpaceComments >>
(inbraces <|> ctrlseq <|> count 1 anyChar))
let args' = case opt of
Just x -> x : args
Nothing -> args
let ender = try $ do
string "\\end"
pSkipSpaceComments
char '{'
string name
char '}'
body <- manyTill anyChar ender
return $ apply args'
$ opener ++ body ++ closer
-- | Parser for \DeclareMathOperator(*) command.
declareMathOperator :: (Monad m, Stream s m Char)
=> ParsecT s st m Macro
declareMathOperator = try $ do
string "\\DeclareMathOperator"
pSkipSpaceComments
star <- option "" (string "*")
pSkipSpaceComments
name <- inbraces <|> ctrlseq
guard (take 1 name == "\\")
let name' = drop 1 name
pSkipSpaceComments
body <- inbraces <|> ctrlseq
let defn = "\\DeclareMathOperator" ++ star ++ "{" ++ name ++ "}" ++
"{" ++ body ++ "}"
return $ Macro (T.pack defn) $ fmap T.pack $ try $ do
char '\\'
string name'
when (all isLetter name') $
notFollowedBy letter
pSkipSpaceComments
return $ "\\operatorname" ++ star ++ "{" ++ body ++ "}"
apply :: [String] -> String -> String
apply args ('#':d:xs) | isDigit d, d /= '0' =
let argnum = read [d]
in if length args >= argnum
then args !! (argnum - 1) ++ apply args xs
else '#' : d : apply args xs
apply args ('\\':'#':xs) = '\\':'#' : apply args xs
apply args (x:xs) = x : apply args xs
apply _ "" = ""
skipComment :: (Monad m, Stream s m Char)
=> ParsecT s st m ()
skipComment = skipMany comment
comment :: (Monad m, Stream s m Char)
=> ParsecT s st m ()
comment = do
char '%'
skipMany (notFollowedBy newline >> anyChar)
newline
return ()
numArgs :: (Monad m, Stream s m Char)
=> ParsecT s st m Int
numArgs = option 0 $ try $ do
pSkipSpaceComments
char '['
pSkipSpaceComments
n <- digit
pSkipSpaceComments
char ']'
return $ read [n]
optArg :: (Monad m, Stream s m Char)
=> ParsecT s st m (Maybe String)
optArg = option Nothing $ (liftM Just $ inBrackets)
escaped :: (Monad m, Stream s m Char)
=> String -> ParsecT s st m String
escaped xs = try $ char '\\' >> oneOf xs >>= \x -> return ['\\',x]
inBrackets :: (Monad m, Stream s m Char)
=> ParsecT s st m String
inBrackets = try $ do
char '['
pSkipSpaceComments
res <- manyTill (skipComment >> (escaped "[]" <|> count 1 anyChar))
(try $ pSkipSpaceComments >> char ']')
return $ concat res
inbraces :: (Monad m, Stream s m Char)
=> ParsecT s st m String
inbraces = try $ do
char '{'
res <- manyTill (skipComment >>
(inbraces' <|> count 1 anyChar <|> escaped "{}"))
(try $ skipComment >> char '}')
return $ concat res
inbraces' :: (Monad m, Stream s m Char)
=> ParsecT s st m String
inbraces' = do
res <- inbraces
return $ '{' : (res ++ "}")
| jgm/texmath | src/Text/TeXMath/Readers/TeX/Macros.hs | gpl-2.0 | 9,899 | 0 | 24 | 2,975 | 2,946 | 1,436 | 1,510 | 229 | 7 |
{- |
Module : $Header$
Description : Implementation of functions necessary to instantiate
Logic.hs for object logics defined in LF
Copyright : (c) Kristina Sojakova, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : k.sojakova@jacobs-university.de
Stability : experimental
Portability : portable
-}
module LF.ImplOL
( basicAnalysisOL
, inducedFromToMorphismOL
) where
import LF.AS
import LF.Sign
import LF.Morphism
import LF.Analysis
import LF.Twelf2GR
import LF.Framework
import Common.ExtSign
import Common.GlobalAnnotations
import Common.AS_Annotation
import Common.Result
import Common.Doc
import Common.DocUtils
import System.IO.Unsafe
import qualified Data.Map as Map
-- basic analysis for object logics of LF
basicAnalysisOL :: Morphism -> (BASIC_SPEC, Sign, GlobalAnnos) ->
Result (BASIC_SPEC, ExtSign Sign Symbol, [Named EXP])
basicAnalysisOL ltruth (bs@(Basic_spec items), initsig, _) = do
let (sig,sens) = unsafePerformIO $ makeSigSenOL ltruth initsig items
let syms = getSymbols sig
let fs = makeNamedForms sens $ map r_annos $ getSenItems items
return (bs, ExtSign sig syms, fs)
-- constructs the signatures and sentences
makeSigSenOL :: Morphism -> Sign -> [Annoted BASIC_ITEM] ->
IO (Sign,[(NAME,Sentence)])
makeSigSenOL ltruth sig items = do
-- make a Twelf file
let sen_type = case mapSymbol sen_type_symbol ltruth of
Nothing -> error $ badSenTypeError
Just t -> show $ pretty t
let lSyn = target ltruth
file <- mkImport lSyn
let imp = mkRead file
let cont1 = if sig == lSyn then "" else printLocalDefs sig
let cont2 = printSigItems $ getSigItems items
let cont3 = printSenItems sen_type $ getSenItems items
let s1 = mkSig gen_sig1 $ mkIncl (sigModule lSyn) ++ cont1 ++ cont2
let s2 = mkSig gen_sig2 $ mkIncl gen_sig1 ++ cont3
let contents = imp ++ "\n" ++ s1 ++ "\n" ++ s2
writeFile gen_file contents
-- run Twelf on the created file
libs <- twelf2SigMor HETS gen_file
-- construct the signature and sentences
sig1 <- getSigFromLibs gen_sig1 libs
sig2 <- getSigFromLibs gen_sig2 libs
let sens = getSens sig2
return (sig1,sens)
mkImport :: Sign -> IO String
mkImport lSyn = do
file <- fromLibName LATIN $ sigBase lSyn
toRelativeURI file
printLocalDefs :: Sign -> String
printLocalDefs sig =
if (null $ getLocalDefs sig) then "" else
(show $ vcat $ map pretty $ getLocalDefs sig) ++ "\n"
-----------------------------------------------------------------
-----------------------------------------------------------------
-- induced_from_to_morphism for object logics
inducedFromToMorphismOL :: Morphism -> Map.Map RAW_SYM RAW_SYM ->
ExtSign Sign Symbol -> ExtSign Sign Symbol ->
Result Morphism
inducedFromToMorphismOL ltruth m (ExtSign sig1 _) (ExtSign sig2 _) =
inducedFromToMorphism (translMapAnalysisOL ltruth m sig1 sig2) sig1 sig2
{- converts a mapping of raw symbols to a mapping of symbols to expressions
annotated with their type -}
translMapAnalysisOL :: Morphism -> Map.Map RAW_SYM RAW_SYM -> Sign ->
Sign -> Map.Map Symbol (EXP,EXP)
translMapAnalysisOL ltruth m sig1 sig2 =
let syms = getUnknownSyms (Map.keys m) sig1
in if not (null syms) then error $ badSymsError syms else
unsafePerformIO $ codAnalysisOL ltruth m sig2
codAnalysisOL :: Morphism -> Map.Map RAW_SYM RAW_SYM -> Sign ->
IO (Map.Map Symbol (EXP,EXP))
codAnalysisOL ltruth m sig2 = do
-- make a Twelf file
let lSyn = target ltruth
file <- mkImport lSyn
let imp = mkRead file
let cont1 = if sig2 == lSyn then "" else printLocalDefs sig2
let cont2 = concat $ map (\ (k,v) -> (genPref k) ++ " = " ++ v ++ ".\n") $
Map.toList m
let s1 = mkSig gen_sig1 $ mkIncl (sigModule lSyn) ++ cont1
let s2 = mkSig gen_sig2 $ mkIncl gen_sig1 ++ cont2
let contents = imp ++ "\n" ++ s1 ++ "\n" ++ s2
writeFile gen_file contents
-- run Twelf on the created file
libs <- twelf2SigMor HETS gen_file
-- construct the mapping
sig' <- getSigFromLibs gen_sig2 libs
return $ getMap sig'
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- ERROR MESSAGES
badSenTypeError :: String
badSenTypeError = "Sentence type cannot be constructed."
| nevrenato/Hets_Fork | LF/ImplOL.hs | gpl-2.0 | 4,493 | 0 | 19 | 976 | 1,207 | 597 | 610 | 82 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.