code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
-- Module : Gen.Types.Help
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
module Gen.Types.Help
( Help
, Desc (..)
, Below (..)
, rawHelpText
) where
import Data.Aeson
import Data.Char (isSpace)
import Data.String
import Data.Text (Text)
import qualified Data.Text as Text
import Text.Pandoc
import Text.Pandoc.Pretty
data Help
= Help [Help]
| Pan Pandoc
| Raw Text
deriving (Eq)
instance Monoid Help where
mempty = Help []
mappend x y =
case (x, y) of
(Help a, Help b) -> Help (a <> b)
(Pan a, Pan b) -> Pan (a <> b)
(Raw a, Raw b) -> Raw (a <> b)
(Help a, b) -> Help (a <> [b])
(a, Help b) -> Help (a : b)
(a, b) -> Help [a, b]
-- | Empty Show instance to avoid verbose debugging output.
instance Show Help where
show = const mempty
instance IsString Help where
fromString = rawHelpText . fromString
rawHelpText :: Text -> Help
rawHelpText = Raw
instance FromJSON Help where
parseJSON = withText "help" $
either (fail . show) pure
. fmap Pan
. readHtml def
. Text.unpack
instance ToJSON Help where
toJSON = toJSON
. mappend "-- |"
. Text.map f
. Text.drop 2
. wrap "-- "
. flatten
where
f '@' = '\''
f x = x
data Desc = Desc !Int Help
instance ToJSON Desc where
toJSON (Desc n h) = toJSON . wrap (replicate n ' ') $ flatten h
data Below = Below !Int Help
instance ToJSON Below where
toJSON (Below n h) = toJSON . wrap (replicate n ' ' <> "-- ") $ flatten h
flatten :: Help -> String
flatten = \case
Help xs -> foldMap flatten xs
Pan d -> writeHaddock def d
Raw t -> Text.unpack t
wrap :: String -> String -> Text
wrap sep =
Text.dropWhileEnd isSpace
. render (Just 76)
. prefixed sep
. fromString
|
rueshyna/gogol
|
gen/src/Gen/Types/Help.hs
|
mpl-2.0
| 2,278
| 0
| 12
| 791
| 706
| 370
| 336
| 71
| 3
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.PlusDomains.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.PlusDomains.Types.Sum where
import Network.Google.Prelude
data MediaInsertCollection
= Cloud
-- ^ @cloud@
-- Upload the media to share on Google+.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable MediaInsertCollection
instance FromHttpApiData MediaInsertCollection where
parseQueryParam = \case
"cloud" -> Right Cloud
x -> Left ("Unable to parse MediaInsertCollection from: " <> x)
instance ToHttpApiData MediaInsertCollection where
toQueryParam = \case
Cloud -> "cloud"
instance FromJSON MediaInsertCollection where
parseJSON = parseJSONText "MediaInsertCollection"
instance ToJSON MediaInsertCollection where
toJSON = toJSONText
-- | The collection of people to list.
data PeopleListByActivityCollection
= Plusoners
-- ^ @plusoners@
-- List all people who have +1\'d this activity.
| Resharers
-- ^ @resharers@
-- List all people who have reshared this activity.
| Sharedto
-- ^ @sharedto@
-- List all people who this activity was shared to.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PeopleListByActivityCollection
instance FromHttpApiData PeopleListByActivityCollection where
parseQueryParam = \case
"plusoners" -> Right Plusoners
"resharers" -> Right Resharers
"sharedto" -> Right Sharedto
x -> Left ("Unable to parse PeopleListByActivityCollection from: " <> x)
instance ToHttpApiData PeopleListByActivityCollection where
toQueryParam = \case
Plusoners -> "plusoners"
Resharers -> "resharers"
Sharedto -> "sharedto"
instance FromJSON PeopleListByActivityCollection where
parseJSON = parseJSONText "PeopleListByActivityCollection"
instance ToJSON PeopleListByActivityCollection where
toJSON = toJSONText
-- | The order to return people in.
data PeopleListOrderBy
= Alphabetical
-- ^ @alphabetical@
-- Order the people by their display name.
| Best
-- ^ @best@
-- Order people based on the relevence to the viewer.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PeopleListOrderBy
instance FromHttpApiData PeopleListOrderBy where
parseQueryParam = \case
"alphabetical" -> Right Alphabetical
"best" -> Right Best
x -> Left ("Unable to parse PeopleListOrderBy from: " <> x)
instance ToHttpApiData PeopleListOrderBy where
toQueryParam = \case
Alphabetical -> "alphabetical"
Best -> "best"
instance FromJSON PeopleListOrderBy where
parseJSON = parseJSONText "PeopleListOrderBy"
instance ToJSON PeopleListOrderBy where
toJSON = toJSONText
-- | The collection of activities to list.
data ActivitiesListCollection
= User
-- ^ @user@
-- All activities created by the specified user that the authenticated user
-- is authorized to view.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ActivitiesListCollection
instance FromHttpApiData ActivitiesListCollection where
parseQueryParam = \case
"user" -> Right User
x -> Left ("Unable to parse ActivitiesListCollection from: " <> x)
instance ToHttpApiData ActivitiesListCollection where
toQueryParam = \case
User -> "user"
instance FromJSON ActivitiesListCollection where
parseJSON = parseJSONText "ActivitiesListCollection"
instance ToJSON ActivitiesListCollection where
toJSON = toJSONText
-- | The collection of people to list.
data PeopleListCollection
= Circled
-- ^ @circled@
-- The list of people who this user has added to one or more circles.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PeopleListCollection
instance FromHttpApiData PeopleListCollection where
parseQueryParam = \case
"circled" -> Right Circled
x -> Left ("Unable to parse PeopleListCollection from: " <> x)
instance ToHttpApiData PeopleListCollection where
toQueryParam = \case
Circled -> "circled"
instance FromJSON PeopleListCollection where
parseJSON = parseJSONText "PeopleListCollection"
instance ToJSON PeopleListCollection where
toJSON = toJSONText
-- | The order in which to sort the list of comments.
data CommentsListSortOrder
= Ascending
-- ^ @ascending@
-- Sort oldest comments first.
| Descending
-- ^ @descending@
-- Sort newest comments first.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommentsListSortOrder
instance FromHttpApiData CommentsListSortOrder where
parseQueryParam = \case
"ascending" -> Right Ascending
"descending" -> Right Descending
x -> Left ("Unable to parse CommentsListSortOrder from: " <> x)
instance ToHttpApiData CommentsListSortOrder where
toQueryParam = \case
Ascending -> "ascending"
Descending -> "descending"
instance FromJSON CommentsListSortOrder where
parseJSON = parseJSONText "CommentsListSortOrder"
instance ToJSON CommentsListSortOrder where
toJSON = toJSONText
|
rueshyna/gogol
|
gogol-plus-domains/gen/Network/Google/PlusDomains/Types/Sum.hs
|
mpl-2.0
| 5,724
| 0
| 11
| 1,235
| 961
| 513
| 448
| 110
| 0
|
module Model where
import Prelude
import Yesod
import Yesod.Markdown (Markdown)
import Data.Text (Text)
import Database.Persist.Quasi
import Data.Typeable (Typeable)
import Data.Time (UTCTime)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlSettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
|
nek0/yacs
|
Model.hs
|
agpl-3.0
| 502
| 0
| 8
| 65
| 89
| 52
| 37
| -1
| -1
|
module ArtfulDodgy where
dodgy x y = x + y * 10
oneIsOne :: (Integer -> Integer)
oneIsOne = dodgy 1 -- returns a function that accepts one parameter and returns an Integer
oneIsTwo :: (Integer -> Integer)
oneIsTwo = (flip dodgy) 2
|
thewoolleyman/haskellbook
|
07/05/maor/artfulDodgy.hs
|
unlicense
| 236
| 0
| 7
| 48
| 69
| 38
| 31
| 6
| 1
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ViewPatterns #-}
{-
Copyright 2020 The CodeWorld Authors. 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.
-}
module CodeWorld.Compile.Requirements.Matcher where
import Control.Monad
import Data.Generics
import Data.Generics.Twins
import Data.List
import Data.Maybe
import "ghc" HsSyn
import "ghc" OccName
import "ghc" RdrName
import "ghc" SrcLoc
class (Data a, Typeable a) => Template a where
toSplice :: a -> Maybe (HsSplice GhcPs)
fromBracket :: (HsBracket GhcPs) -> Maybe a
toParens :: a -> Maybe a
toTuple :: a -> Maybe [a]
toVar :: a -> Maybe a
toCon :: a -> Maybe a
toLit :: a -> Maybe a
toNum :: a -> Maybe a
toChar :: a -> Maybe a
toStr :: a -> Maybe a
instance Template (Pat GhcPs) where
toSplice (SplicePat _ s) = Just s
toSplice _ = Nothing
fromBracket (PatBr _ (L _ p)) = Just p
fromBracket _ = Nothing
toParens (ParPat _ (L _ x)) = Just x
toParens _ = Nothing
toTuple (TuplePat _ ps _) = Just [p | L _ p <- ps]
toTuple _ = Nothing
toVar x@(VarPat _ _) = Just x
toVar _ = Nothing
toCon x@(ConPatIn _ _) = Just x
toCon x@(ConPatOut {}) = Just x
toCon _ = Nothing
toLit x@(LitPat _ _) = Just x
toLit _ = Nothing
toNum x@(LitPat _ (HsInt _ _)) = Just x
toNum x@(LitPat _ (HsInteger _ _ _)) = Just x
toNum x@(LitPat _ (HsRat _ _ _)) = Just x
toNum x@(LitPat _ (HsIntPrim _ _)) = Just x
toNum x@(LitPat _ (HsWordPrim _ _)) = Just x
toNum x@(LitPat _ (HsInt64Prim _ _)) = Just x
toNum x@(LitPat _ (HsWord64Prim _ _)) = Just x
toNum x@(LitPat _ (HsFloatPrim _ _)) = Just x
toNum x@(LitPat _ (HsDoublePrim _ _)) = Just x
toNum _ = Nothing
toChar x@(LitPat _ (HsChar _ _)) = Just x
toChar x@(LitPat _ (HsCharPrim _ _)) = Just x
toChar _ = Nothing
toStr x@(LitPat _ (HsString _ _)) = Just x
toStr x@(LitPat _ (HsStringPrim _ _)) = Just x
toStr _ = Nothing
instance Template (HsExpr GhcPs) where
toSplice (HsSpliceE _ s) = Just s
toSplice _ = Nothing
fromBracket (ExpBr _ (L _ e)) = Just e
fromBracket _ = Nothing
toParens (HsPar _ (L _ x)) = Just x
toParens _ = Nothing
toTuple (ExplicitTuple _ args _) = Just (concat $ tupArgExpr <$> args)
toTuple _ = Nothing
toVar x@(HsVar _ _) = Just x
toVar _ = Nothing
toCon x@(HsConLikeOut _ _) = Just x
toCon _ = Nothing
toLit x@(HsLit _ _) = Just x
toLit x@(NegApp _ (L _ (HsLit _ _)) _) = Just x
toLit _ = Nothing
toNum x@(HsLit _ (HsInt _ _)) = Just x
toNum x@(HsLit _ (HsInteger _ _ _)) = Just x
toNum x@(HsLit _ (HsRat _ _ _)) = Just x
toNum x@(HsLit _ (HsIntPrim _ _)) = Just x
toNum x@(HsLit _ (HsWordPrim _ _)) = Just x
toNum x@(HsLit _ (HsInt64Prim _ _)) = Just x
toNum x@(HsLit _ (HsWord64Prim _ _)) = Just x
toNum x@(HsLit _ (HsFloatPrim _ _)) = Just x
toNum x@(HsLit _ (HsDoublePrim _ _)) = Just x
toNum x@(NegApp _ (L _ (toNum -> Just _)) _) = Just x
toNum _ = Nothing
toChar x@(HsLit _ (HsChar _ _)) = Just x
toChar x@(HsLit _ (HsCharPrim _ _)) = Just x
toChar _ = Nothing
toStr x@(HsLit _ (HsString _ _)) = Just x
toStr x@(HsLit _ (HsStringPrim _ _)) = Just x
toStr _ = Nothing
tupArgExpr :: (LHsTupArg GhcPs) -> [HsExpr GhcPs]
tupArgExpr (L _ (Present _ (L _ x))) = [x]
tupArgExpr _ = []
match :: Data a => a -> a -> Bool
match tmpl val = matchQ tmpl val
matchQ :: GenericQ (GenericQ Bool)
matchQ =
matchesGhcPs
||| (matchesSpecials :: (Pat GhcPs) -> (Pat GhcPs) -> Maybe Bool)
||| (matchesSpecials :: (HsExpr GhcPs) -> (HsExpr GhcPs) -> Maybe Bool)
||| matchesWildcard
||| mismatchedNames
||| structuralEq
matchesGhcPs :: GhcPs -> GhcPs -> Maybe Bool
matchesGhcPs _ _ = Just True
matchesSpecials :: Template a => a -> a -> Maybe Bool
matchesSpecials (toParens -> Just x) y = Just (matchQ x y)
matchesSpecials x (toParens -> Just y) = Just (matchQ x y)
matchesSpecials
( toSplice ->
Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl))))))
)
x =
matchBrackets op tmpl x
matchesSpecials
( toSplice ->
Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (HsBracket _ (fromBracket -> Just tmpl))))))
)
x =
matchBrackets op tmpl x
matchesSpecials
( toSplice ->
Just (HsTypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs))))))
)
x =
matchLogical op xs x
matchesSpecials
( toSplice ->
Just (HsUntypedSplice _ _ _ (L _ (HsApp _ op (L _ (ExplicitList _ _ (sequence . map (\(L _ (HsBracket _ b)) -> fromBracket b) -> Just xs))))))
)
x =
matchLogical op xs x
matchesSpecials
( toSplice ->
Just (HsTypedSplice _ _ _ (L _ (HsVar _ (L _ id))))
)
x =
matchSimple id x
matchesSpecials
( toSplice ->
Just (HsUntypedSplice _ _ _ (L _ (HsVar _ (L _ id))))
)
x =
matchSimple id x
matchesSpecials _ _ = Nothing
matchBrackets :: Template a => LHsExpr GhcPs -> a -> a -> Maybe Bool
matchBrackets op tmpl x = case op of
(L _ (HsVar _ (L _ id))) ->
case idName id of
"tupleOf" -> case toTuple x of Just xs -> Just (all (match tmpl) xs); Nothing -> Just False
"contains" -> Just (everything (||) (mkQ False (match tmpl)) x)
_ -> Nothing
_ -> Nothing
matchLogical :: Template a => LHsExpr GhcPs -> [a] -> a -> Maybe Bool
matchLogical op xs x = case op of
(L _ (HsVar _ (L _ id))) ->
case idName id of
"allOf" -> Just (all (flip match x) xs)
"anyOf" -> Just (any (flip match x) xs)
"noneOf" -> Just (not (any (flip match x) xs))
_ -> Nothing
_ -> Nothing
matchSimple :: Template a => IdP GhcPs -> a -> Maybe Bool
matchSimple id x = case idName id of
"any" -> Just True
"var" -> case toVar x of Just _ -> Just True; Nothing -> Just False
"con" -> case toCon x of Just _ -> Just True; Nothing -> Just False
"lit" -> case toLit x of Just _ -> Just True; Nothing -> Just False
"num" -> case toNum x of Just _ -> Just True; Nothing -> Just False
"char" -> case toChar x of Just _ -> Just True; Nothing -> Just False
"str" -> case toStr x of Just _ -> Just True; Nothing -> Just False
_ -> Nothing
matchesWildcard :: IdP GhcPs -> IdP GhcPs -> Maybe Bool
matchesWildcard id _ | "_" `isPrefixOf` (idName id) && "_" `isSuffixOf` (idName id) = Just True
matchesWildcard _ _ = Nothing
mismatchedNames :: IdP GhcPs -> IdP GhcPs -> Maybe Bool
mismatchedNames x y = if idName x /= idName y then Just False else Nothing
structuralEq :: (Data a, Data b) => a -> b -> Bool
structuralEq x y = toConstr x == toConstr y && and (gzipWithQ matchQ x y)
(|||) ::
(Typeable a, Typeable b, Typeable x) =>
(x -> x -> Maybe Bool) ->
(a -> b -> Bool) ->
(a -> b -> Bool)
f ||| g = \x y -> fromMaybe (g x y) (join (f <$> cast x <*> cast y))
infixr 0 |||
idName :: IdP GhcPs -> String
idName = occNameString . rdrNameOcc
|
google/codeworld
|
codeworld-compiler/src/CodeWorld/Compile/Requirements/Matcher.hs
|
apache-2.0
| 7,455
| 0
| 28
| 1,802
| 3,463
| 1,722
| 1,741
| 182
| 14
|
------------------------------------------------------------------------
-- |
-- Module : TeachingTest
-- Copyright : (c) Amy de Buitléir 2013-2016
-- License : BSD-style
-- Maintainer : amy@nualeargais.ie
-- Stability : experimental
-- Portability : portable
--
-- Verify that a wain can be taught.
--
------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import ALife.Creatur (agentId)
import ALife.Creatur.Wain
import ALife.Creatur.Wain.BrainInternal (classifier, predictor,
makeBrain, decisionQuality)
import ALife.Creatur.Wain.Classifier (buildClassifier)
import ALife.Creatur.Wain.GeneticSOMInternal (LearningParams(..))
import ALife.Creatur.Wain.Audio.Pattern
import qualified ALife.Creatur.Wain.Audio.Wain as AW
import ALife.Creatur.Wain.Audio.Object (Object(..), objectNum, objectId,
objectAppearance)
import ALife.Creatur.Wain.AudioID.Action (Action(..), correct,
correctActions)
import ALife.Creatur.Wain.AudioID.Experiment
import ALife.Creatur.Wain.Muser (makeMuser)
import ALife.Creatur.Wain.PlusMinusOne (doubleToPM1)
import ALife.Creatur.Wain.Predictor (buildPredictor)
import ALife.Creatur.Wain.Response (action, outcomes)
import ALife.Creatur.Wain.SimpleResponseTweaker (ResponseTweaker(..))
import ALife.Creatur.Wain.Statistics (stats)
import ALife.Creatur.Wain.UnitInterval (uiToDouble)
import ALife.Creatur.Wain.Weights (makeWeights)
import ALife.Creatur.Util (shuffle)
import Control.Lens
import Control.Monad (foldM)
import Control.Monad.Random (evalRand, mkStdGen)
import Data.List (sortBy)
import Data.Ord (comparing)
import System.Directory
import System.FilePath.Posix (takeFileName)
reward :: Double
reward = 0.1
runAction
:: Action -> Object Action (ResponseTweaker Action) -> PatternWain
-> PatternWain
runAction a obj w =
if correct a (objectNum obj)
then wCorrect
else wIncorrect
where (wCorrect, _) = adjustEnergy reward w
(wIncorrect, _) = adjustEnergy (-reward) w
testWain :: PatternWain
testWain = w'
where wName = "Fred"
wAppearance = mkAudio $ replicate (172*39) 0
Right wBrain = makeBrain wClassifier wMuser wPredictor wHappinessWeights 1 32 wIos wRds
wDevotion = 0.1
wAgeOfMaturity = 100
wPassionDelta = 0
wBoredomDelta = 0
wClassifier = buildClassifier ec wCSize 0.00021 PatternTweaker
wCSize = 2000
Right wMuser = makeMuser [0, 0, 0, 0] 1
wIos = [doubleToPM1 reward, 0, 0, 0]
wRds = [doubleToPM1 reward, 0, 0, 0]
wPredictor = buildPredictor ep (wCSize*11) 0.1 ResponseTweaker
wHappinessWeights = makeWeights [1, 0, 0, 0]
-- The classifier does most of its learning by round 100.
ec = LearningParams 0.1 0.001 (fromIntegral numImprints)
-- The predictor needs to keep learning longer.
ep = LearningParams 0.1 0.0001 (fromIntegral numImprints)
w = buildWainAndGenerateGenome wName wAppearance wBrain
wDevotion wAgeOfMaturity wPassionDelta wBoredomDelta
(w', _) = adjustEnergy 0.5 w
imprintOne
:: PatternWain -> Object Action (ResponseTweaker Action)
-> IO (PatternWain)
imprintOne w obj = do
let a = correctActions !! (objectNum obj)
putStrLn $ "Teaching " ++ agentId w ++ " that correct action for "
++ objectId obj ++ " is " ++ show a
let (_, _, _, _, w') = imprint [objectAppearance obj] a w
return w'
tryOne
:: PatternWain -> Object Action (ResponseTweaker Action)
-> IO (PatternWain)
tryOne w obj = do
putStrLn $ "-----<br/>"
putStrLn $ "stats=" ++ show (stats w)
let (ldss, _, _, _, r, wainAfterDecision)
= chooseAction [objectAppearance obj] w
putStrLn $ "ldss=" ++ show ldss
let (cBMU, _):(cBMU2, _):_ = sortBy (comparing snd) . head $ ldss
let a = view action r
putStrLn $ "Wain sees " ++ objectId obj ++ ", classifies it as "
++ show cBMU ++ " (alt. " ++ show cBMU2
++ ") and chooses to " ++ show a
++ " predicting the outcomes " ++ show (view outcomes r)
let wainRewarded = runAction a obj wainAfterDecision
let deltaH = uiToDouble (happiness wainRewarded) - uiToDouble (happiness w)
putStrLn $ "Δh=" ++ show deltaH
putStrLn $ "condition before=" ++ show (condition w) ++ " after=" ++ show (condition wainRewarded)
putStrLn $ "happiness before=" ++ show (happiness w) ++ " after=" ++ show (happiness wainRewarded)
putStr $ "Choosing to " ++ show a ++ " in response to " ++ objectId obj
if correct a (objectNum obj)
then putStrLn " was correct"
else putStrLn " was wrong"
let (wainAfterReflection, err) = reflect [objectAppearance obj] r w wainRewarded
putStrLn $ "err=" ++ show err
-- keep the wain's energy constant
let restorationEnergy = uiToDouble (view energy w) - uiToDouble (view energy wainRewarded)
-- keep the wain's boredom constant
let restorationBoredom = uiToDouble (view boredom w) - uiToDouble (view boredom wainRewarded)
let (wainPartiallyRestored, _) = adjustEnergy restorationEnergy wainAfterReflection
let (wainFinal, _) = adjustBoredom restorationBoredom wainPartiallyRestored
putStrLn $ "classifier SQ=" ++ show (schemaQuality . view (brain . classifier) $ w)
putStrLn $ "predictor SQ=" ++ show (schemaQuality . view (brain . predictor) $ w)
putStrLn $ "DQ=" ++ show (decisionQuality . view brain $ w)
return wainFinal
trainingDir :: String
trainingDir = "/home/eamybut/TI46/HTK_MFCC_endpointed/TRAIN-RAW"
testDir :: String
testDir = "/home/eamybut/TI46/HTK_MFCC_endpointed/TEST-RAW"
readDirAndShuffle :: FilePath -> IO [FilePath]
readDirAndShuffle d = do
let g = mkStdGen 263167 -- seed
files <- map (d ++) . drop 2 <$> getDirectoryContents d
return $ evalRand (shuffle files) g
readOneSample :: Int -> FilePath -> IO (Object Action (ResponseTweaker Action))
readOneSample nvec f = do
audio <- readAudio f nvec
return $ PObject audio (takeFileName f)
numImprints :: Int
numImprints = 5
numTests :: Int
numTests = 5
main :: IO ()
main = do
putStrLn $ "numImprints=" ++ show numImprints
putStrLn $ "numTests=" ++ show numTests
putStrLn $ "stats=" ++ show (stats testWain)
imprintFiles <- take numImprints . drop 2 <$> readDirAndShuffle trainingDir
imprintSamples <- mapM (readOneSample 110) imprintFiles
testFiles <- take numTests . drop 2 <$> readDirAndShuffle testDir
testSamples <- mapM (readOneSample 110) testFiles
imprintedWain <- foldM imprintOne testWain imprintSamples
putStrLn "Imprinted prediction models"
mapM_ putStrLn $ AW.describePredictorModels imprintedWain
_ <- foldM tryOne imprintedWain testSamples
putStrLn "test complete"
|
mhwombat/exp-audio-id-wains
|
test/TeachingTest.hs
|
bsd-3-clause
| 6,671
| 0
| 16
| 1,222
| 1,963
| 1,021
| 942
| 137
| 2
|
module Module5.Task10 where
import Data.Char (isDigit)
-- system code
data Token = Number Int | Plus | Minus | LeftBrace | RightBrace
deriving (Eq, Show)
-- solution code
asToken :: String -> Maybe Token
asToken x = case x of
[] -> Nothing
"(" -> Just LeftBrace
")" -> Just RightBrace
"-" -> Just Minus
"+" -> Just Plus
_ | all isDigit x -> Just $ Number $ read x
| otherwise -> Nothing
tokenize :: String -> Maybe [Token]
tokenize = sequence . (map asToken) . words
|
dstarcev/stepic-haskell
|
src/Module5/Task10.hs
|
bsd-3-clause
| 495
| 0
| 11
| 117
| 189
| 97
| 92
| 15
| 6
|
{-# LANGUAGE PatternGuards, ViewPatterns, FlexibleContexts, ScopedTypeVariables, TupleSections #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveFunctor #-}
module GHC.Util.Unify(
Subst(..), fromSubst,
validSubst, removeParens, substitute,
unifyExp
) where
import Control.Applicative
import Control.Monad
import Data.Generics.Uniplate.DataOnly
import Data.Char
import Data.Data
import Data.List.Extra
import Util
import GHC.Hs
import GHC.Types.SrcLoc
import GHC.Utils.Outputable hiding ((<>))
import GHC.Types.Name.Reader
import Language.Haskell.GhclibParserEx.GHC.Hs.Pat
import Language.Haskell.GhclibParserEx.GHC.Hs.Expr
import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable
import Language.Haskell.GhclibParserEx.GHC.Types.Name.Reader
import GHC.Util.HsExpr
import GHC.Util.View
import Data.Maybe
import GHC.Data.FastString
isUnifyVar :: String -> Bool
isUnifyVar [x] = x == '?' || isAlpha x
isUnifyVar [] = False
isUnifyVar xs = all (== '?') xs
---------------------------------------------------------------------
-- SUBSTITUTION DATA TYPE
-- A list of substitutions. A key may be duplicated, you need to call
-- 'check' to ensure the substitution is valid.
newtype Subst a = Subst [(String, a)]
deriving (Semigroup, Monoid, Functor)
-- Unpack the substitution.
fromSubst :: Subst a -> [(String, a)]
fromSubst (Subst xs) = xs
instance Outputable a => Show (Subst a) where
show (Subst xs) = unlines [a ++ " = " ++ unsafePrettyPrint b | (a,b) <- xs]
-- Check the unification is valid and simplify it.
validSubst :: (a -> a -> Bool) -> Subst a -> Maybe (Subst a)
validSubst eq = fmap Subst . mapM f . groupSort . fromSubst
where f (x, y : ys) | all (eq y) ys = Just (x, y)
f _ = Nothing
-- Remove unnecessary brackets from a Subst. The first argument is a list of unification variables
-- for which brackets should be removed from their substitutions.
removeParens :: [String] -> Subst (LHsExpr GhcPs) -> Subst (LHsExpr GhcPs)
removeParens noParens (Subst xs) = Subst $
map (\(x, y) -> if x `elem` noParens then (x, fromParen y) else (x, y)) xs
-- Peform a substition.
-- Returns (suggested replacement, (refactor template, no bracket vars)). It adds/removes brackets
-- for both the suggested replacement and the refactor template appropriately. The "no bracket vars"
-- is a list of substituation variables which, when expanded, should have the brackets stripped.
--
-- Examples:
-- (traverse foo (bar baz), (traverse f (x), []))
-- (zipWith foo bar baz, (f a b, [f]))
substitute :: Subst (LHsExpr GhcPs) -> LHsExpr GhcPs -> (LHsExpr GhcPs, (LHsExpr GhcPs, [String]))
substitute (Subst bind) = transformBracketOld exp . transformBi pat . transformBi typ
where
exp :: LHsExpr GhcPs -> Maybe (LHsExpr GhcPs)
-- Variables.
exp (L _ (HsVar _ x)) = lookup (rdrNameStr x) bind
-- Operator applications.
exp (L loc (OpApp _ lhs (L _ (HsVar _ x)) rhs))
| Just y <- lookup (rdrNameStr x) bind = Just (L loc (OpApp EpAnnNotUsed lhs y rhs))
-- Left sections.
exp (L loc (SectionL _ exp (L _ (HsVar _ x))))
| Just y <- lookup (rdrNameStr x) bind = Just (L loc (SectionL EpAnnNotUsed exp y))
-- Right sections.
exp (L loc (SectionR _ (L _ (HsVar _ x)) exp))
| Just y <- lookup (rdrNameStr x) bind = Just (L loc (SectionR EpAnnNotUsed y exp))
exp _ = Nothing
pat :: LPat GhcPs -> LPat GhcPs
-- Pattern variables.
pat (L _ (VarPat _ x))
| Just y@(L _ HsVar{}) <- lookup (rdrNameStr x) bind = strToPat $ varToStr y
pat x = x :: LPat GhcPs
typ :: LHsType GhcPs -> LHsType GhcPs
-- Type variables.
typ (L _ (HsTyVar _ _ x))
| Just (L _ (HsAppType _ _ (HsWC _ y))) <- lookup (rdrNameStr x) bind = y
typ x = x :: LHsType GhcPs
---------------------------------------------------------------------
-- UNIFICATION
type NameMatch = LocatedN RdrName -> LocatedN RdrName -> Bool
-- | Unification, obeys the property that if @unify a b = s@, then
-- @substitute s a = b@.
unify' :: Data a => NameMatch -> Bool -> a -> a -> Maybe (Subst (LHsExpr GhcPs))
unify' nm root x y
| Just (x, y) <- cast (x, y) = unifyExp' nm root x y
| Just (x, y) <- cast (x, y) = unifyPat' nm x y
| Just (x, y) <- cast (x, y) = unifyType' nm x y
| Just (x, y) <- cast (x, y) = if (x :: FastString) == y then Just mempty else Nothing
-- We need some type magic to reduce this.
| Just (x :: EpAnn AnnsModule) <- cast x = Just mempty
| Just (x :: EpAnn NameAnn) <- cast x = Just mempty
| Just (x :: EpAnn AnnListItem) <- cast x = Just mempty
| Just (x :: EpAnn AnnList) <- cast x = Just mempty
| Just (x :: EpAnn AnnPragma) <- cast x = Just mempty
| Just (x :: EpAnn AnnContext) <- cast x = Just mempty
| Just (x :: EpAnn AnnParen) <- cast x = Just mempty
| Just (x :: EpAnn Anchor) <- cast x = Just mempty
| Just (x :: EpAnn NoEpAnns) <- cast x = Just mempty
| Just (x :: EpAnn GrhsAnn) <- cast x = Just mempty
| Just (x :: EpAnn [AddEpAnn]) <- cast x = Just mempty
| Just (x :: EpAnn EpAnnHsCase) <- cast x = Just mempty
| Just (x :: EpAnn EpAnnUnboundVar) <- cast x = Just mempty
| Just (x :: EpAnn AnnExplicitSum) <- cast x = Just mempty
| Just (x :: EpAnn AnnsLet) <- cast x = Just mempty
| Just (x :: EpAnn AnnProjection) <- cast x = Just mempty
| Just (x :: EpAnn Anchor) <- cast x = Just mempty
| Just (x :: EpAnn EpaLocation) <- cast x = Just mempty
| Just (x :: EpAnn AnnFieldLabel) <- cast x = Just mempty
| Just (x :: EpAnn EpAnnSumPat) <- cast x = Just mempty
| Just (x :: EpAnn AnnSig) <- cast x = Just mempty
| Just (x :: EpAnn HsRuleAnn) <- cast x = Just mempty
| Just (x :: EpAnn EpAnnImportDecl) <- cast x = Just mempty
| Just (x :: EpAnn (AddEpAnn, AddEpAnn)) <- cast x = Just mempty
| Just (y :: SrcSpan) <- cast y = Just mempty
| otherwise = unifyDef' nm x y
unifyDef' :: Data a => NameMatch -> a -> a -> Maybe (Subst (LHsExpr GhcPs))
unifyDef' nm x y =
fmap mconcat . sequence =<< gzip (unify' nm False) x y
unifyComposed' :: NameMatch
-> LHsExpr GhcPs
-> LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
-> Maybe (Subst (LHsExpr GhcPs), Maybe (LHsExpr GhcPs))
unifyComposed' nm x1 y11 dot y12 =
((, Just y11) <$> unifyExp' nm False x1 y12)
<|> case y12 of
(L _ (OpApp _ y121 dot' y122)) | isDot dot' ->
unifyComposed' nm x1 (noLocA (OpApp EpAnnNotUsed y11 dot y121)) dot' y122
_ -> Nothing
-- unifyExp handles the cases where both x and y are HsApp, or y is OpApp. Otherwise,
-- delegate to unifyExp'. These are the cases where we potentially need to call
-- unifyComposed' to handle left composition.
--
-- y is allowed to partially match x (the lhs of the hint), if y is a function application where
-- the function is a composition of functions. In this case the second component of the result is
-- the unmatched part of y, which will be attached to the rhs of the hint after substitution.
--
-- Example:
-- x = head (drop n x)
-- y = foo . bar . baz . head $ drop 2 xs
-- result = (Subst [(n, 2), (x, xs)], Just (foo . bar . baz))
unifyExp :: NameMatch -> Bool -> LHsExpr GhcPs -> LHsExpr GhcPs -> Maybe (Subst (LHsExpr GhcPs), Maybe (LHsExpr GhcPs))
-- Match wildcard operators.
unifyExp nm root (L _ (OpApp _ lhs1 (L _ (HsVar _ (rdrNameStr -> v))) rhs1))
(L _ (OpApp _ lhs2 (L _ (HsVar _ (rdrNameStr -> op2))) rhs2))
| isUnifyVar v =
(, Nothing) . (Subst [(v, strToVar op2)] <>) <$>
liftA2 (<>) (unifyExp' nm False lhs1 lhs2) (unifyExp' nm False rhs1 rhs2)
-- Options: match directly, and expand through '.'
unifyExp nm root x@(L _ (HsApp _ x1 x2)) (L _ (HsApp _ y1 y2)) =
((, Nothing) <$> liftA2 (<>) (unifyExp' nm False x1 y1) (unifyExp' nm False x2 y2)) <|> unifyComposed
where
-- Unify a function application where the function is a composition of functions.
unifyComposed
| (L _ (OpApp _ y11 dot y12)) <- fromParen y1, isDot dot =
if not root then
-- Attempt #1: rewrite '(fun1 . fun2) arg' as 'fun1 (fun2 arg)', and unify it with 'x'.
-- The guard ensures that you don't get duplicate matches because the matching engine
-- auto-generates hints in dot-form.
(, Nothing) <$> unifyExp' nm root x (noLocA (HsApp EpAnnNotUsed y11 (noLocA (HsApp EpAnnNotUsed y12 y2))))
else do
-- Attempt #2: rewrite '(fun1 . fun2 ... funn) arg' as 'fun1 $ (fun2 ... funn) arg',
-- 'fun1 . fun2 $ (fun3 ... funn) arg', 'fun1 . fun2 . fun3 $ (fun4 ... funn) arg',
-- and so on, unify the rhs of '$' with 'x', and store the lhs of '$' into 'extra'.
-- You can only add to extra if you are at the root (otherwise 'extra' has nowhere to go).
rhs <- unifyExp' nm False x2 y2
(lhs, extra) <- unifyComposed' nm x1 y11 dot y12
pure (lhs <> rhs, extra)
| otherwise = Nothing
-- Options: match directly, then expand through '$', then desugar infix.
unifyExp nm root x (L _ (OpApp _ lhs2 op2@(L _ (HsVar _ op2')) rhs2))
| (L _ (OpApp _ lhs1 op1@(L _ (HsVar _ op1')) rhs1)) <- x =
guard (nm op1' op2') >> (, Nothing) <$> liftA2 (<>) (unifyExp' nm False lhs1 lhs2) (unifyExp' nm False rhs1 rhs2)
| isDol op2 = unifyExp nm root x $ noLocA (HsApp EpAnnNotUsed lhs2 rhs2)
| isAmp op2 = unifyExp nm root x $ noLocA (HsApp EpAnnNotUsed rhs2 lhs2)
| otherwise = unifyExp nm root x $ noLocA (HsApp EpAnnNotUsed (noLocA (HsApp EpAnnNotUsed op2 (addPar lhs2))) (addPar rhs2))
where
-- add parens around when desugaring the expression, if necessary
addPar :: LHsExpr GhcPs -> LHsExpr GhcPs
addPar x = if isAtom x then x else addParen x
unifyExp nm root x y = (, Nothing) <$> unifyExp' nm root x y
isAmp :: LHsExpr GhcPs -> Bool
isAmp (L _ (HsVar _ x)) = rdrNameStr x == "&"
isAmp _ = False
-- | If we "throw away" the extra than we have no where to put it, and the substitution is wrong
noExtra :: Maybe (Subst (LHsExpr GhcPs), Maybe (LHsExpr GhcPs)) -> Maybe (Subst (LHsExpr GhcPs))
noExtra (Just (x, Nothing)) = Just x
noExtra _ = Nothing
-- App/InfixApp are analysed specially for performance reasons. If
-- 'root = True', this is the outside of the expr. Do not expand out a
-- dot at the root, since otherwise you get two matches because of
-- 'readRule' (Bug #570).
unifyExp' :: NameMatch -> Bool -> LHsExpr GhcPs -> LHsExpr GhcPs -> Maybe (Subst (LHsExpr GhcPs))
-- Don't subsitute for type apps, since no one writes rules imagining
-- they exist.
unifyExp' nm root (L _ (HsVar _ (rdrNameStr -> v))) y | isUnifyVar v, not $ isTypeApp y = Just $ Subst [(v, y)]
unifyExp' nm root (L _ (HsVar _ x)) (L _ (HsVar _ y)) | nm x y = Just mempty
-- Brackets are not added when expanding '$' in user code, so tolerate
-- them in the match even if they aren't in the user code.
-- Also, allow the user to put in more brackets than they strictly need (e.g. with infix).
unifyExp' nm root x y | not root, isJust x2 || isJust y2 = unifyExp' nm root (fromMaybe x x2) (fromMaybe y y2)
where
-- Make sure we deal with the weird brackets that can't be removed around sections
x2 = remParen x
y2 = remParen y
unifyExp' nm root x@(L _ (OpApp _ lhs1 (L _ (HsVar _ (rdrNameStr -> v))) rhs1))
y@(L _ (OpApp _ lhs2 (L _ (HsVar _ op2)) rhs2)) =
noExtra $ unifyExp nm root x y
unifyExp' nm root (L _ (SectionL _ exp1 (L _ (HsVar _ (rdrNameStr -> v)))))
(L _ (SectionL _ exp2 (L _ (HsVar _ (rdrNameStr -> op2)))))
| isUnifyVar v = (Subst [(v, strToVar op2)] <>) <$> unifyExp' nm False exp1 exp2
unifyExp' nm root (L _ (SectionR _ (L _ (HsVar _ (rdrNameStr -> v))) exp1))
(L _ (SectionR _ (L _ (HsVar _ (rdrNameStr -> op2))) exp2))
| isUnifyVar v = (Subst [(v, strToVar op2)] <>) <$> unifyExp' nm False exp1 exp2
unifyExp' nm root x@(L _ (HsApp _ x1 x2)) y@(L _ (HsApp _ y1 y2)) =
noExtra $ unifyExp nm root x y
unifyExp' nm root x y@(L _ (OpApp _ lhs2 op2@(L _ (HsVar _ op2')) rhs2)) =
noExtra $ unifyExp nm root x y
unifyExp' nm root (L _ (HsBracket _ (VarBr _ b0 (occNameStr . unLoc -> v1))))
(L _ (HsBracket _ (VarBr _ b1 (occNameStr . unLoc -> v2))))
| b0 == b1 && isUnifyVar v1 = Just (Subst [(v1, strToVar v2)])
unifyExp' nm root x y | isOther x, isOther y = unifyDef' nm x y
where
-- Types that are not already handled in unify.
{-# INLINE isOther #-}
isOther :: LHsExpr GhcPs -> Bool
isOther (L _ HsVar{}) = False
isOther (L _ HsApp{}) = False
isOther (L _ OpApp{}) = False
isOther _ = True
unifyExp' _ _ _ _ = Nothing
unifyPat' :: NameMatch -> LPat GhcPs -> LPat GhcPs -> Maybe (Subst (LHsExpr GhcPs))
unifyPat' nm (L _ (VarPat _ x)) (L _ (VarPat _ y)) =
Just $ Subst [(rdrNameStr x, strToVar(rdrNameStr y))]
unifyPat' nm (L _ (VarPat _ x)) (L _ (WildPat _)) =
let s = rdrNameStr x in Just $ Subst [(s, strToVar("_" ++ s))]
unifyPat' nm (L _ (ConPat _ x _)) (L _ (ConPat _ y _)) | rdrNameStr x /= rdrNameStr y =
Nothing
unifyPat' nm x y =
unifyDef' nm x y
unifyType' :: NameMatch -> LHsType GhcPs -> LHsType GhcPs -> Maybe (Subst (LHsExpr GhcPs))
unifyType' nm (L loc (HsTyVar _ _ x)) y =
let wc = HsWC noExtField y :: LHsWcType (NoGhcTc GhcPs)
unused = strToVar "__unused__" :: LHsExpr GhcPs
appType = L loc (HsAppType noSrcSpan unused wc) :: LHsExpr GhcPs
in Just $ Subst [(rdrNameStr x, appType)]
unifyType' nm x y = unifyDef' nm x y
|
ndmitchell/hlint
|
src/GHC/Util/Unify.hs
|
bsd-3-clause
| 13,679
| 0
| 18
| 3,293
| 5,050
| 2,517
| 2,533
| 185
| 7
|
module RotN where
--------------------------------------------------------------
-- P19 Rotate a list N places to the left
--Prelude> rotate ["a", "b", "c", "d", "e", "f", "g", "h"] 3
--["d","e","f","g","h","a","b","c"]
--
--Prelude> rotate ["a", "b", "c", "d", "e", "f", "g", "h"] (-2)
--["g","h","a","b","c","d","e","f"]
---------------------------------------------------------------
rotate :: [a] -> Int -> [a]
rotate xs n
| (n < 0) = (drop (subtract k l) xs) ++ (drop k xs)
| otherwise = (drop k xs) ++ (take k xs)
where k = ((abs n) `mod` l)
l = (length xs)
|
michael-j-clark/hjs99
|
src/11to20/RotN.hs
|
bsd-3-clause
| 582
| 0
| 10
| 103
| 144
| 80
| 64
| 7
| 1
|
module RefacGenFold where
import PFE0
import HsTokens
import TypeCheck
import PrettyPrint
import PosSyntax
import HsName
import HsLexerPass1
import AbstractIO
import Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import List
import RefacUtils hiding (getParams)
import PFE0 (findFile, allFiles, allModules)
import MUtils (( # ))
import RefacLocUtils
import System
import IO
import Relations
import Ents
import Data.Set (toList)
import Data.List
import System.IO.Unsafe
import System.Cmd
import LocalSettings
import RefacSimplify
import StateMT(WithState,withSt,withStS,getSt,setSt,updSt,updSt_)
import qualified Control.Exception as CE (catch)
import EditorCommands
-- | An argument list for a function which of course is a list of paterns.
type FunctionPats = [HsPatP]
-- | A list of declarations used to represent a where or let clause.
type WhereDecls = [HsDeclP]
data PatFun = Mat | Patt | Er deriving (Eq, Show)
genFold args
= do
let fileName = ghead "fileName'" args
beginRow = read (args!!1)::Int
beginCol = read (args!!2)::Int
endRow = read (args!!3)::Int
endCol = read (args!!4)::Int
AbstractIO.putStrLn "genFold"
modName <-fileNameToModName fileName
let modName1 = convertModName modName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
let subExp = locToExp (beginRow, beginCol) (endRow, endCol) tokList mod
let (ty, pnt, pats, wh)
= findDefNameAndExp tokList
(beginRow, beginCol)
(endRow, endCol)
mod
((_,m), (newToks, (newMod, e))) <- applyRefac (addCommentDec pnt) (Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName, m), (newToks, newMod))]
(inscps', exps', mod', tokList') <- parseSourceFile fileName
((_,m'), (newToks', (newMod',parsed))) <- applyRefac (retrieveDecAndRemove pnt e)
(Just (inscps', exps', mod', tokList')) fileName
let pnt' = declToPNT parsed
-- undo the added entry!
undoLatestInHistory
(inscps2, exps2, mod2, tokList2)<-parseSourceFile fileName
((_,m'''), (newToks''', newMod''')) <- applyRefac (changeExpression pnt pnt' parsed subExp)
(Just (inscps2, exps2, mod2, tokList2)) fileName
writeRefactoredFiles False [((fileName, m'''), (newToks''', newMod'''))]
AbstractIO.putStrLn "Completed.\n"
addCommentDec pnt (_,_,t)
= do
tks <- extractComment (pNTtoPN pnt) t
let tksString = concatMap getName tks
let commentDef = dropWhile (==' ') (parseComment (reverse tksString))
if '=' `elem` commentDef
then do
mod <- insertTerm (dropWhile (==' ') (reverse commentDef)) (pNTtoPN pnt) t
return (mod, (dropWhile (==' ') (reverse commentDef)))
else do
error "Please define an equation within a comment above the definition under scrutiny."
retrieveDecAndRemove pnt e (_,_,t)
= do
let parsedDec = retrieveDec pnt e t
-- mod <- removeDec e t
return (t, parsedDec)
retrieveDec pnt exp t
= fromMaybe (error ("Previous record of definition not found! " ++ exp))
(applyTU (once_tdTU (failTU `adhocTU` inDec)) t)
where
inDec d@(Dec (HsPatBind _ _ _ _))
| (render.ppi) d == exp
= Just d
inDec d@(Dec (HsFunBind l matches))
| rendered matches exp
= do
let x = rendered2 matches exp
Just (Dec (HsFunBind l [x]))
inDec d = Nothing
rendered [] _ = False
rendered (m:ms) e
| rmLine ( rmToks ((render.ppi) m)) == rmLine ( rmToks e ) = True
| otherwise = rendered ms e
rendered2 [] _ = error "Error in rendered2"
rendered2 (m:ms) e
| rmLine ( rmToks ((render.ppi) m)) == rmLine ( rmToks e ) = m
| otherwise = rendered2 ms e
rmToks x = (rmRBracket.rmLBracket.rmLine.rmSpace) x
rmSpace x = filter (/=' ') x
rmLine x = filter (/='\n') x
rmLBracket x = filter (/='(') x
rmRBracket x = filter (/=')') x
removeDec exp t
= applyTP (stop_tdTP (idTP `adhocTP` inDec)) t
where
inDec (d::HsDeclP)
| (render.ppi) d == exp
= do
rmDecl (declToPName2 d) True [d]
return d
inDec d = return d
parseComment :: String -> String
parseComment [] = []
parseComment ('}':('-':xs)) = parseComment' xs
parseComment (x:xs) = parseComment xs
parseComment' :: String -> String
parseComment' [] = []
parseComment' ('-':('{':xs)) = ""
parseComment' (x:xs) = x : (parseComment' xs)
getName :: PosToken -> String
getName (_, ((Pos _ _ _), s)) = s
changeExpression pnt pntComment d exp (_,_,t)
= do
mod <- changeExpression' pnt pntComment d exp t
return mod
changeExpression' pnt pntComment d exp t
= applyTP (stop_tdTP (failTP `adhocTP` (inExp d exp))) t
where
inExp (Dec (HsPatBind _ p (HsBody e2) ds)) exp (e::HsExpP)
| sameOccurrence exp e
= do
if rmAllLocs e2 == rmAllLocs e
then do
res <- update e (nameToExp (pNTtoName (patToPNT p))) e
return res
else do
mzero
inExp (dec@(Dec (HsFunBind s matches))::HsDeclP) exp (e::HsExpP)
| sameOccurrence exp e
= do
let match@(HsMatch loc name pats (HsBody e2) ds) = getMatch pntComment matches
let newExp = searchForRHS pnt exp t
let (pred, newParams) = rewriteExp pats newExp e2
if pred
then do
-- let patsConverd = map (render.ppi) newPats
res <- update e (createFunc pntComment (map patToExp newParams)) e
return res
else do
mzero
inExp d exp e = mzero
rewriteExp :: [HsPatP] -> HsExpP -> HsExpP -> (Bool, [HsPatP])
rewriteExp pats (Exp (HsParen e)) e2 = rewriteExp pats e e2
rewriteExp pats e (Exp (HsParen e2)) = rewriteExp pats e e2
rewriteExp pats (Exp (HsLit s x)) (Exp (HsLit s1 x2))
| x == x2 = (True, pats)
rewriteExp pats (Exp (HsId (HsCon x))) (Exp (HsId (HsCon y)))
| x == y = (True, pats)
rewriteExp pats n m@(Exp (HsId (HsVar i2)))
| checkPNTInPat pats i2 = (True, getPatFromPats pats n i2)
rewriteExp pats n@(Exp (HsId (HsVar i1))) (Exp (HsId (HsVar i2)))
| (pNTtoName i1) /= (pNTtoName i2) && checkPNTInPat pats i2 = (True, getPatFromPats pats n i2)
| (pNTtoName i1) == (pNTtoName i2) = (True, pats)
| isLocalPNT i1 && isLocalPNT i2 = (True, pats)
| otherwise = (False, pats)
rewriteExp pats a@(Exp (HsApp e1 e2)) b@(Exp (HsApp e3 e4))
| pred1 == True && pred2 == True = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e3
(pred2, pats2) = rewriteExp pats1 e2 e4
rewriteExp pats a@(Exp (HsInfixApp e1 o1 e2)) b@(Exp (HsInfixApp e3 o2 e4))
| o1 == o2 && (pred1 && pred2) = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e3
(pred2, pats2) = rewriteExp pats1 e2 e4
rewriteExp pats a@(Exp (HsTuple e1)) b@(Exp (HsTuple e2))
| length e1 == length e2 && pred = (True, pats2)
| otherwise = (False, pats)
where
(pred, pats2) = checkList pats e1 e2
rewriteExp pats a@(Exp (HsList e1)) b@(Exp (HsList e2))
| length e1 == length e2 = (True, pats2)
| otherwise = (False, pats)
where
(pred, pats2) = checkList pats e1 e2
rewriteExp pats a@(Exp (HsLeftSection e1 i1)) b@(Exp (HsLeftSection e2 i2))
| i1 == i2 && pred1 = (True, pats1)
where
(pred1, pats1) = rewriteExp pats e1 e2
rewriteExp pats a@(Exp (HsRightSection i1 e1)) b@(Exp (HsRightSection i2 e2))
| i1 == i2 && pred1 = (True, pats1)
where
(pred1, pats1) = rewriteExp pats e1 e2
rewriteExp pats a@(Exp (HsEnumFrom e1)) b@(Exp (HsEnumFrom e2))
| pred1 = (True, pats1)
where
(pred1, pats1) = rewriteExp pats e1 e2
rewriteExp pats a@(Exp (HsEnumFromTo e1 e2)) b@(Exp (HsEnumFromTo e3 e4))
| pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e3
(pred2, pats2) = rewriteExp pats1 e2 e4
rewriteExp pats a@(Exp (HsEnumFromThen e1 e2)) b2@(Exp (HsEnumFromThen e3 e4))
| pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e3
(pred2, pats2) = rewriteExp pats1 e2 e4
rewriteExp pats a@(Exp (HsEnumFromThenTo e1 e2 e3)) b@(Exp (HsEnumFromThenTo e4 e5 e6))
| pred1 && pred2 && pred3 = (True, pats3)
where
(pred1, pats1) = rewriteExp pats e1 e4
(pred2, pats2) = rewriteExp pats1 e2 e5
(pred3, pats3) = rewriteExp pats2 e3 e6
rewriteExp pats a@(Exp (HsIf e1 e2 e3)) b@(Exp (HsIf e4 e5 e6))
| pred1 && pred2 && pred3 = (True, pats3)
where
(pred1, pats1) = rewriteExp pats e1 e4
(pred2, pats2) = rewriteExp pats1 e2 e5
(pred3, pats3) = rewriteExp pats2 e3 e6
rewriteExp pats a@(Exp (HsNegApp s e)) b@(Exp (HsNegApp s2 e2))
| pred = (True, pats1)
where
(pred, pats1) = rewriteExp pats e e2
rewriteExp pats a@(Exp (HsListComp stmts1)) b@(Exp (HsListComp stmts2))
| pred = (True, pats1)
where
(pred, pats1) = rewriteExpStmts pats stmts1 stmts2
rewriteExp pats (Exp (HsDo stmts1)) (Exp (HsDo stmts2))
| pred = (True, pats1)
where
(pred, pats1) = rewriteExpStmts pats stmts1 stmts2
rewriteExp pats a@(Exp (HsLambda ps e1)) b@(Exp (HsLambda ps2 e2))
| wildCardAllPNs ps == wildCardAllPNs ps2 && pred = (True, pats1)
where
(pred, pats1) = rewriteExp pats e1 (localRewriteExp e2 (localRewritePats ps ps2))
localRewritePats [] ps = []
localRewritePats ps [] = []
localRewritePats (p1:p1s) (p2:p2s)
= (rewritePat p2 p1) : (localRewritePats p1s p2s)
localRewriteExp e [] = e
localRewriteExp e (p1:p1s)
= let e1' = rewritePatsInExp p1 e in localRewriteExp e1' p1s
rewriteExp pats a@(Exp (HsRecConstr s i fields1)) b@(Exp (HsRecConstr s2 i2 fields2))
| i == i2 && pred = (True, pats1)
where
(pred, pats1) = rewriteExpFields pats fields1 fields2
rewriteExp pats a@(Exp (HsRecUpdate s1 e1 fields1)) b@(Exp (HsRecUpdate s2 e2 fields2))
| pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpFields pats1 fields1 fields2
rewriteExp pats a@(Exp (HsCase e1 alts1)) b@(Exp (HsCase e2 alts2))
| pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpAlts pats1 alts1 alts2
-- rewriteExp pats e1 e2 = error $ ">" ++ (show (pats, e1, e2))
rewriteExp pats e1 e2 = (False, pats) -- error $ ">" ++ (show (pats, e1, e2))
rewriteExpFields pats [] _ = (True, pats)
rewriteExpFields pats _ [] = (True, pats)
rewriteExpFields pats ((HsField i1 e1):f1) ((HsField i2 e2):f2)
| pred && (i1 == i2 && pred2) = (True, pats2)
| otherwise = (False, pats)
where
(pred, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpFields pats1 f1 f2
rewriteExpAlts pats [] _ = (True, pats)
rewriteExpAlts pats _ [] = (True, pats)
rewriteExpAlts pats ((HsAlt _ p1 (HsBody e1) ds1):alts1) ((HsAlt _ p2 (HsBody e2) ds2):alts2)
| pred && (wildCardAllPNs p1 == wildCardAllPNs p2 && pred2) = (True, pats2)
| otherwise = (False, pats)
where
(pred, pats1) = rewriteExp pats e1 (rewritePatsInExp (rewritePat p2 p1) e2)
(pred2, pats2) = rewriteExpAlts pats1 alts1 alts2
rewriteExpAlts pats ((HsAlt _ p1 (HsGuard gs1) ds1):alts1) ((HsAlt _ p2 (HsGuard gs2) ds2):alts2)
| (wildCardAllPNs p1 == wildCardAllPNs p2 && pred2) = (True, pats2)
| otherwise = (False, pats)
where
-- (pred, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpGuards pats gs1 res
res = (rewritePatsInGuard (rewritePat p2 p1) gs2)
rewriteExpAlts pats _ _ = (False, pats)
rewriteExpGuards pats [] _ = (True, pats)
rewriteExpGuards pats _ [] = (True, pats)
rewriteExpGuards pats ((_ ,e1,e2):gs1) ((_, e3, e4):gs2)
| pred1 && pred2 && pred3 = (True, pats3)
where
(pred1, pats1) = rewriteExp pats e1 e3
(pred2, pats2) = rewriteExp pats1 e2 e4
(pred3, pats3) = rewriteExpGuards pats2 gs1 gs2
rewriteExpStmts pats s1@(HsGenerator _ p1 e1 m1) s2@(HsGenerator _ p2 e2 m2)
| wildCardAllPNs p1 == wildCardAllPNs p2 && pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpStmts pats1 m1 m2
rewriteExpStmts pats (HsLast e1) (HsLast e2)
| wildCardAllPNs e1 == wildCardAllPNs e2 = (True, pats)
-- = error $ show $ rewriteExp pats e1 e2
rewriteExpStmts pats (HsQualifier e1 stmts) (HsQualifier e2 stmts2)
| pred1 && pred2 = (True, pats2)
where
(pred1, pats1) = rewriteExp pats e1 e2
(pred2, pats2) = rewriteExpStmts pats1 stmts stmts2
rewriteExpStmts pats (HsLetStmt ds1 stmts) (HsLetStmt ds2 stmts2)
= rewriteExpStmts pats stmts stmts2
rewriteExpStmts pats s1 s2 = (False, pats)
changeAllNames :: PNT -> PNT -> PNT
changeAllNames pnt t =runIdentity (applyTP (full_buTP (idTP `adhocTP` l)) t)
where
l ((PN (UnQual n) s))
| n /= (pNTtoName pnt) = return ((PN (UnQual (pNTtoName pnt)) s))
| otherwise = return ((PN (UnQual n) s))
rewritePat :: HsPatP -> HsPatP -> HsPatP
rewritePat a@(Pat (HsPId (HsVar x))) b@(Pat (HsPId (HsVar y)))
= (Pat (HsPId (HsVar (changeAllNames y x))))
rewritePat a@(Pat (HsPId (HsCon x))) b@(Pat (HsPId (HsCon y)))
= a
rewritePat a@(Pat (HsPLit _ _)) b@(Pat (HsPLit _ _))
= a
rewritePat a@(Pat (HsPNeg _ _)) b@(Pat (HsPNeg _ _))
= a
rewritePat a@(Pat (HsPSucc _ _ _)) b@(Pat (HsPSucc _ _ _))
= a
rewritePat a@(Pat (HsPInfixApp p1 i p2)) b@(Pat (HsPInfixApp p3 i2 p4))
= (Pat (HsPInfixApp (rewritePat p1 p3) i (rewritePat p2 p4)))
rewritePat a@(Pat (HsPApp i ps)) b@(Pat (HsPApp i2 ps2))
= (Pat (HsPApp i (rewritePat' ps ps2)))
rewritePat a@(Pat (HsPTuple s ps)) b@(Pat (HsPTuple s2 ps2))
= (Pat (HsPTuple s (rewritePat' ps ps2)))
rewritePat a@(Pat (HsPList s ps)) b@(Pat (HsPList s2 ps2))
= (Pat (HsPList s (rewritePat' ps ps2)))
rewritePat a@(Pat (HsPParen p1)) b@(Pat (HsPParen p2))
= (Pat (HsPParen (rewritePat p1 p2)))
rewritePat a@(Pat (HsPAsPat i p1)) b@(Pat (HsPAsPat i2 p2))
= (Pat (HsPAsPat i (rewritePat p1 p2)))
rewritePat a@(Pat (HsPWildCard)) b@(Pat (HsPWildCard))
= a
rewritePat a@(Pat (HsPIrrPat p1)) b@(Pat (HsPIrrPat p2))
= Pat (HsPIrrPat (rewritePat p1 p2))
rewritePat a b = a
rewritePat' :: [HsPatP] -> [HsPatP] -> [HsPatP]
rewritePat' [] _ = []
rewritePat' x [] = x
rewritePat' (x:xs) (y:ys)
= rewritePat x y : rewritePat' xs ys
rewritePatsInExp :: HsPatP -> HsExpP -> HsExpP
rewritePatsInExp p a@(Exp (HsId (HsVar x)))
| isTopLevelPNT x = a
| otherwise
= (Exp (HsId (HsVar newPNT)))
where
newPNT = grabPNT x (hsPNTs p)
rewritePatsInExp p (Exp (HsInfixApp e1 o e2))
= (Exp (HsInfixApp e1' o e2'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
rewritePatsInExp p (Exp (HsApp e1 e2))
= (Exp (HsApp e1' e2'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
rewritePatsInExp p (Exp (HsNegApp s e))
= (Exp (HsNegApp s e'))
where
e' = rewritePatsInExp p e
rewritePatsInExp p (Exp (HsLambda ps e))
= (Exp (HsLambda ps e'))
where
e' = rewritePatsInExp p e
rewritePatsInExp p (Exp (HsLet ds e))
= (Exp (HsLet ds e'))
where
e' = rewritePatsInExp p e
rewritePatsInExp p (Exp (HsIf e1 e2 e3))
= (Exp (HsIf e1' e2' e3'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
e3' = rewritePatsInExp p e3
rewritePatsInExp p (Exp (HsCase e alts))
= (Exp (HsCase e' alts'))
where
e' = rewritePatsInExp p e
alts' = rewritePatsInAlts p alts
rewritePatsInExp p (Exp (HsDo stmts))
= (Exp (HsDo stmts'))
where
stmts' = rewritePatsInStmts p stmts
rewritePatsInExp p (Exp (HsTuple es))
= (Exp (HsTuple es'))
where
es' = map (rewritePatsInExp p) es
rewritePatsInExp p (Exp (HsList es))
= (Exp (HsList es'))
where
es' = map (rewritePatsInExp p) es
rewritePatsInExp p (Exp (HsParen e))
= (Exp (HsParen (rewritePatsInExp p e)))
rewritePatsInExp p (Exp (HsLeftSection e (HsVar x)))
= (Exp (HsLeftSection e' (HsVar newPNT)))
where
e' = rewritePatsInExp p e'
newPNT = grabPNT x (hsPNTs p)
rewritePatsInExp p (Exp (HsRightSection (HsVar x) e))
= (Exp (HsRightSection (HsVar newPNT) e'))
where
e' = rewritePatsInExp p e'
newPNT = grabPNT x (hsPNTs p)
rewritePatsInExp p (Exp (HsRecConstr s i fields))
= (Exp (HsRecConstr s newPNT fields'))
where
newPNT = grabPNT i (hsPNTs p)
fields' = rewritePatsInFields p fields
rewritePatsInExp p (Exp (HsRecUpdate s e fields))
= (Exp (HsRecUpdate s e' fields'))
where
e' = rewritePatsInExp p e
fields' = rewritePatsInFields p fields
rewritePatsInExp p (Exp (HsEnumFrom e))
= (Exp (HsEnumFrom e'))
where
e' = rewritePatsInExp p e
rewritePatsInExp p (Exp (HsEnumFromTo e1 e2))
= (Exp (HsEnumFromTo e1' e2'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
rewritePatsInExp p (Exp (HsEnumFromThen e1 e2))
= (Exp (HsEnumFromThen e1' e2'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
rewritePatsInExp p (Exp (HsEnumFromThenTo e1 e2 e3))
= (Exp (HsEnumFromThenTo e1' e2' e3'))
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
e3' = rewritePatsInExp p e3
rewritePatsInExp p (Exp (HsListComp stmts))
= (Exp (HsListComp stmts'))
where
stmts' = rewritePatsInStmts p stmts
rewritePatsInExp p e = e
rewritePatsInStmts :: HsPatP -> HsStmtP -> HsStmtP
rewritePatsInStmts p (HsGenerator s p2 e stmts)
= (HsGenerator s p2 e' stmts')
where
e' = rewritePatsInExp p e
stmts' = rewritePatsInStmts p stmts
rewritePatsInStmts p (HsQualifier e stmts)
= (HsQualifier e' stmts')
where
e' = rewritePatsInExp p e
stmts' = rewritePatsInStmts p stmts
rewritePatsInStmts p (HsLetStmt ds stmts)
= (HsLetStmt ds stmts')
where
stmts' = rewritePatsInStmts p stmts
rewritePatsInStmts p (HsLast e)
= (HsLast e')
where
e' = rewritePatsInExp p e
rewritePatsInFields :: HsPatP -> [HsFieldP] -> [HsFieldP]
rewritePatsInFields p [] = []
rewritePatsInFields p ((HsField i e):fs)
= (HsField newPNT e') : (rewritePatsInFields p fs)
where
newPNT = grabPNT i (hsPNTs e)
e' = rewritePatsInExp p e
rewritePatsInAlts :: HsPatP -> [HsAltP] -> [HsAltP]
rewritePatsInAlts p [] = []
rewritePatsInAlts p ((HsAlt s p2 (HsBody e) ds):alts)
= (HsAlt s p2 (HsBody e') ds) : (rewritePatsInAlts p alts)
where
e' = rewritePatsInExp p e
rewritePatsInAlts p ((HsAlt s p2 (HsGuard gs) ds):alts)
= (HsAlt s p2 (HsGuard gs') ds) : (rewritePatsInAlts p alts)
where
gs' = rewritePatsInGuard p gs
rewritePatsInGuard :: HsPatP -> [(SrcLoc, HsExpP, HsExpP)] -> [(SrcLoc, HsExpP, HsExpP)]
rewritePatsInGuard p [] = []
rewritePatsInGuard p ((s, e1, e2):gs)
= (s, e1', e2') : (rewritePatsInGuard p gs)
where
e1' = rewritePatsInExp p e1
e2' = rewritePatsInExp p e2
grabPNT :: PNT -> [PNT] -> PNT
grabPNT x [] = x
grabPNT x (y:ys)
| defineLoc x == defineLoc y = y
| otherwise = grabPNT x ys
checkList :: [HsPatP] -> [HsExpP] -> [HsExpP] -> (Bool, [HsPatP])
checkList pats [] [] = (True, pats)
checkList pats [e] [l] = rewriteExp pats e l
checkList pats (e:es) (l:ls)
| pred = checkList pats' es ls
| otherwise = (False, pats')
where
(pred, pats') = rewriteExp pats e l
checkPNTInPat :: [HsPatP] -> PNT -> Bool
checkPNTInPat [] _ = False
checkPNTInPat (p:ps) i
| defineLoc i == (SrcLoc "__unknown__" 0 0 0) = False
| defineLoc i == defineLoc (patToPNT p) = True
| otherwise = checkPNTInPat ps i
getPatFromPats :: [HsPatP] -> HsExpP -> PNT -> [HsPatP]
getPatFromPats [] _ _ = []
getPatFromPats (p:pats) e i2
| defineLoc i2 == (SrcLoc "__unknown__" 0 0 0) = p : (getPatFromPats pats e i2)
| defineLoc i2 == defineLoc (patToPNT p) = (expToPat e) ++ (getPatFromPats pats e i2)
| otherwise = p : (getPatFromPats pats e i2)
patToExp :: HsPatP -> HsExpP
patToExp (Pat (HsPId x)) = (Exp (HsId x))
patToExp (Pat (HsPLit s l)) = (Exp (HsLit s l))
patToExp (Pat (HsPInfixApp p1 i p2)) = (Exp (HsInfixApp (patToExp p1) (HsCon i) (patToExp p2)))
patToExp (Pat (HsPApp pnt p2)) = (Exp (HsApp (nameToExp (pNTtoName pnt)) (cApp p2)))
where
cApp :: [HsPatP] -> HsExpP
cApp [p] = patToExp p
cApp (p:ps) = Exp (HsApp (cApp (init (p:ps))) (patToExp (last ps)))
patToExp (Pat (HsPTuple s ps)) = (Exp (HsTuple (map patToExp ps)))
patToExp (Pat (HsPList s ps)) = (Exp (HsList (map patToExp ps)))
patToExp (Pat (HsPParen p1)) = (Exp (HsParen (patToExp p1)))
patToExp (Pat (HsPAsPat pnt pat)) = (Exp (HsId (HsVar pnt)))
patToExp (Pat (HsPIrrPat p)) = patToExp p
patToExp (Pat (HsPWildCard)) = nameToExp "undefined"
expToPat :: HsExpP -> [HsPatP]
expToPat (Exp (HsId x)) = [Pat (HsPId x)]
expToPat (Exp (HsLit s l)) = [Pat (HsPLit s l)]
expToPat (Exp (HsInfixApp e1 (HsVar i) e2)) = [Pat (HsPInfixApp (ghead "expToPat" $ expToPat e1)
i (ghead "expToPat" $ expToPat e2))]
expToPat (Exp (HsInfixApp e1 (HsCon i) e2)) = [Pat (HsPInfixApp (ghead "expToPat" $ expToPat e1)
i (ghead "expToPat" $ expToPat e2))]
expToPat e@(Exp (HsApp e1 e2)) = [Pat (HsPApp (nameToPNT " ")
(concatMap expToPat exps))]
where
exps = flatternApp e
expToPat (Exp (HsLambda ps e)) = ps
expToPat (Exp (HsTuple es)) = concatMap expToPat es --[Pat (HsPTuple loc0 (concatMap expToPat es))]
expToPat (Exp (HsList es)) = concatMap expToPat es
expToPat (Exp (HsParen e1)) = [Pat (HsPParen (ghead "expToPat" $ expToPat e1))]
expToPat e = []
flatternApp :: HsExpP -> [HsExpP]
flatternApp (Exp (HsApp e1 e2)) = flatternApp e1 ++ flatternApp e2
flatternApp (Exp (HsParen e)) = flatternApp e
flatternApp x = [x]
searchForRHS pnt exp t
= (fromMaybe (error "Could not find the right hand side for the commented definition!"))
(applyTU (once_tdTU (failTU `adhocTU` (inDec exp))) t)
where
inDec e (pat@(Dec (HsPatBind loc1 ps rhs@(HsBody e2) ds))::HsDeclP)
| findEntity e e2
= do
let newExp = symbolicallyTie exp e2 []
Just newExp
inDec e (dec@(Dec (HsFunBind s matches))::HsDeclP)
| findPNT pnt matches
= do
let match@(HsMatch loc name pats rhs ds) = getMatch pnt matches
if findEntity e (extractRHS e rhs)
then do
let newExp = symbolicallyTie exp (extractRHS e rhs) pats
Just newExp
else do
mzero
inDec _ d = mzero
findGuard e [] = error "Cannot find highlight expression!"
findGuard e ((_,_,x):xs)
| findEntity e x = x
| otherwise = findGuard e xs
extractRHS e (HsBody x) = x
extractRHS e (HsGuard gs) = findGuard e gs
symbolicallyTie exp (Exp (HsParen e)) pats = symbolicallyTie exp e pats
symbolicallyTie exp n@(Exp (HsCase e alts)) pats
= symbolicallyTie' alts -- (Exp (HsCase e [symbolicallyTie' alts]))
where
symbolicallyTie' [] = error "Error in symbolic evaluation: expression does not occur on the RHS!"
symbolicallyTie' (a@(HsAlt l p (HsGuard gs) ds):as)
| findEntity exp gs
= zipPatExp e n a' pats
| findEntity exp ds -- selected definition is in where clause of a case alt.
= zipPatExp e n a' pats
where
a' = (HsAlt l p (HsBody exp) ds)
symbolicallyTie' (a@(HsAlt l p (HsBody e2) ds):as)
| findEntity exp e2
= zipPatExp e n a' pats
| findEntity exp ds -- selected definition is in where clause of a case alt.
= zipPatExp e n a' pats
| otherwise = symbolicallyTie' as
where
a' = (HsAlt l p (HsBody exp) ds)
symbolicallyTie exp e pats = exp
-- utility functions
getMatch :: PNT -> [HsMatchP] -> HsMatchP
getMatch _ [] = error "Please select a case in top-level expression scope!"
getMatch pnt (match@(HsMatch loc name pats rhs ds):ms)
| useLoc pnt == useLoc name = match
| otherwise = getMatch pnt ms
convertModName (PlainModule s) = s
convertModName m@(MainModule f) = modNameToStr m
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
findDefNameAndExp :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (PatFun, PNT, FunctionPats, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
findDefNameAndExp toks beginPos endPos t
= fromMaybe (Er, defaultPNT, [], [])
(applyTU (once_buTU (failTU `adhocTU` inMatch `adhocTU` inPat)) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsBody e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, ds)
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsGuard e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, ds)
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= if isSimplePatBind pat
then Just (Patt, patToPNT ps, [], ds)
else Just (Patt, pnt, pats, ds)
where
(_, pnt, pats, ds') = findDefining pat t
findDefining pats t
= fromMaybe (error "Error: the selected entity is a top level complex pattern binding!")
(applyTU (once_buTU (failTU `adhocTU` inMatch')) t)
inMatch' (match@(HsMatch loc1 pnt pats rhs@(HsBody e) ds)::HsMatchP)
| pat `elem` ds = Just (Mat, pnt, pats, ds)
| findEntity pat e = Just (Mat, pnt, pats, ds)
inMatch' (match@(HsMatch loc1 pnt pats rhs@(HsGuard e) ds)::HsMatchP)
| pat `elem` ds = Just (Mat, pnt, pats, ds)
| findEntity pat e = Just (Mat, pnt, pats, ds)
inMatch' _ = Nothing
inPat _ = Nothing
|
forste/haReFork
|
refactorer/RefacGenFold.hs
|
bsd-3-clause
| 28,394
| 0
| 20
| 8,340
| 11,319
| 5,812
| 5,507
| -1
| -1
|
module Tutorial.Examples
( examplesMap
, launchExample
, example1
, example2
, example3
, example4
) where
{-
If you are looking for the example sources, look for the numbered
Example files.
-}
import Tutorial.Example1
import Tutorial.Example2
import Tutorial.Example3
import Tutorial.Example4
import Site
import Snap.Snaplet
import Snap.Http.Server.Config
import Data.Map.Syntax
import Data.Map.Lazy
import Application
allExamples :: [Example]
allExamples =
[ example1Data
, example2Data
, example3Data
, example4Data
]
launchExample :: Example -> IO ()
launchExample ex = serveSnaplet defaultConfig (app ex)
examplesMap :: Map String Example
examplesMap = either (const empty) id $ runMap $
mapM (\ex -> (examplePath ex) ## ex) allExamples
example1 :: IO ()
example1 = launchExample example1Data
example2 :: IO ()
example2 = launchExample example2Data
example3 :: IO ()
example3 = launchExample example3Data
example4 :: IO ()
example4 = launchExample example4Data
|
kaol/heist-tutorial
|
src/Tutorial/Examples.hs
|
bsd-3-clause
| 1,049
| 0
| 11
| 216
| 264
| 147
| 117
| 36
| 1
|
module Main where
import Data.ByteString as BS
import Data.ByteString.Char8 as BS8
import LuaLoader
import Data.Attoparsec.ByteString as PBS
import Data.Bits as Bits
import Data.ByteString as B
import Data.ByteString.Char8 as B8
import Data.Word
import qualified LVM
import qualified Parser
import LuaObjects
import qualified Control.Monad as Monad
import qualified LRT
import qualified Data.Foldable as Foldable
import Control.Monad.ST.Unsafe
import Control.Monad.ST
import System.Environment as Sys
testFile :: FilePath -> IO LVM.LuaState
testFile p = LVM.runLuaCode $ "D:\\Uni\\00_SS2016\\90_AbsMachine\\yalvm\\test\\testFiles\\" ++ p
file :: IO ByteString
file = BS.readFile "luac.out"
luaChunk :: IO Parser.LuaBinaryFile
luaChunk = do
x <- file
let res = PBS.parseOnly Parser.loadLuaChunk x :: Either String Parser.LuaBinaryFile
let luaChunk = either (error "Parse error") id res :: Parser.LuaBinaryFile
return luaChunk
main :: IO ()
main = do
path <- Prelude.head <$> getArgs :: IO String
print $ "Running " ++ path
LVM.runLuaCode path
return ()
{-file <- BS.readFile path
luaChunk <- Main.luaChunk
let luaTopFunction = Parser.getTopFunction luaChunk :: Parser.LuaFunctionHeader
state <- LVM.startExecution luaTopFunction :: IO LVM.LuaState
state <- return $ LRT.setGlobal state "print" $ LOFunction LRT.lrtPrint
result <- LVM.runLuaFunction $ return state-}
--Prelude.putStrLn "\nVM State:"
--print result
--Prelude.putStrLn "\nFinal Stack:"
--LVM.printStack $ return result
--Prelude.putStrLn $ Prelude.replicate 10 '\n'
--print "lalala"
-- BS8.putStrLn x
stackWalk :: LVM.LuaState -> IO ()
stackWalk state =
Monad.unless (1 == (execStop . LVM.stateExecutionThread) state) $ do
stack <- LVM.lGetStateStack state
ss <- stackSize stack
Foldable.traverse_ (fmap print . getElement stack) [0..ss - 1]
print "1-UP"
stackWalk $ LVM.LuaState (execPrevInst . LVM.stateExecutionThread $ state) undefined
|
AndreasPK/yalvm
|
app/Main.hs
|
bsd-3-clause
| 2,158
| 0
| 13
| 500
| 449
| 243
| 206
| 42
| 1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
{-# LANGUAGE StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Exception.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (extended exceptions)
--
-- Extensible exceptions, except for multiple handlers.
--
-----------------------------------------------------------------------------
module Control.Exception.Base (
-- * The Exception type
SomeException(..),
Exception(..),
IOException,
ArithException(..),
ArrayException(..),
AssertionFailed(..),
SomeAsyncException(..), AsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
NonTermination(..),
NestedAtomically(..),
BlockedIndefinitelyOnMVar(..),
FixIOException (..),
BlockedIndefinitelyOnSTM(..),
AllocationLimitExceeded(..),
CompactionFailed(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
TypeError(..), -- #10284, custom error type for deferred type errors
-- * Throwing exceptions
throwIO,
throw,
ioError,
throwTo,
-- * Catching Exceptions
-- ** The @catch@ functions
catch,
catchJust,
-- ** The @handle@ functions
handle,
handleJust,
-- ** The @try@ functions
try,
tryJust,
onException,
-- ** The @evaluate@ function
evaluate,
-- ** The @mapException@ function
mapException,
-- * Asynchronous Exceptions
-- ** Asynchronous exception control
mask,
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
-- * Assertions
assert,
-- * Utilities
bracket,
bracket_,
bracketOnError,
finally,
-- * Calls for GHC runtime
recSelError, recConError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError, absentSumFieldError, typeError,
nonTermination, nestedAtomically,
) where
import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import GHC.Exception
import GHC.Show
-- import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync
import Data.Either
-----------------------------------------------------------------------------
-- Catching exceptions
-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in.
--
-- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- > (readFile f)
-- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- > return "")
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch', 'catchJust', etc.
catchJust
:: Exception e
=> (e -> Maybe b) -- ^ Predicate to select exceptions
-> IO a -- ^ Computation to run
-> (b -> IO a) -- ^ Handler
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throwIO e
Just b -> handler b
-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter. For example:
--
-- > do handle (\NonTermination -> exitWith (ExitFailure 1)) $
-- > ...
handle :: Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
-----------------------------------------------------------------------------
-- 'mapException'
-- | This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".
-- Notice that the usage of 'unsafePerformIO' is safe here.
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throwIO (f x)))
-----------------------------------------------------------------------------
-- 'try' and variations.
-- | Similar to 'catch', but returns an 'Either' result which is
-- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
-- if an exception of type @e@ was raised and its value is @ex@.
-- If any other type of exception is raised then it will be propagated
-- up to the next enclosing exception handler.
--
-- > try a = catch (Right `liftM` a) (return . Left)
try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-- | A variant of 'try' that takes an exception predicate to select
-- which exceptions are caught (c.f. 'catchJust'). If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throwIO e
Just b -> return (Left b)
-- | Like 'finally', but only performs the final action if there was an
-- exception raised by the computation.
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
throwIO (e :: SomeException)
-----------------------------------------------------------------------------
-- Some Useful Functions
-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation. If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- > (openFile "filename" ReadMode)
-- > (hClose)
-- > (\fileHandle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
-- > withFile name mode = bracket (openFile name mode) hClose
--
bracket
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracket before after thing =
mask $ \restore -> do
a <- before
r <- restore (thing a) `onException` after a
_ <- after a
return r
-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
finally :: IO a -- ^ computation to run first
-> IO b -- ^ computation to run afterward (even if an exception
-- was raised)
-> IO a -- returns the value from the first computation
a `finally` sequel =
mask $ \restore -> do
r <- restore a `onException` sequel
_ <- sequel
return r
-- | A variant of 'bracket' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
-- | Like 'bracket', but only performs the final action if there was an
-- exception raised by the in-between computation.
bracketOnError
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError before after thing =
mask $ \restore -> do
a <- before
restore (thing a) `onException` after a
-----
-- |A pattern match failed. The @String@ gives information about the
-- source location of the pattern.
newtype PatternMatchFail = PatternMatchFail String
-- | @since 4.0
instance Show PatternMatchFail where
showsPrec _ (PatternMatchFail err) = showString err
-- | @since 4.0
instance Exception PatternMatchFail
-----
-- |A record selector was applied to a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record selector.
newtype RecSelError = RecSelError String
-- | @since 4.0
instance Show RecSelError where
showsPrec _ (RecSelError err) = showString err
-- | @since 4.0
instance Exception RecSelError
-----
-- |An uninitialised record field was used. The @String@ gives
-- information about the source location where the record was
-- constructed.
newtype RecConError = RecConError String
-- | @since 4.0
instance Show RecConError where
showsPrec _ (RecConError err) = showString err
-- | @since 4.0
instance Exception RecConError
-----
-- |A record update was performed on a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record update.
newtype RecUpdError = RecUpdError String
-- | @since 4.0
instance Show RecUpdError where
showsPrec _ (RecUpdError err) = showString err
-- | @since 4.0
instance Exception RecUpdError
-----
-- |A class method without a definition (neither a default definition,
-- nor a definition in the appropriate instance) was called. The
-- @String@ gives information about which method it was.
newtype NoMethodError = NoMethodError String
-- | @since 4.0
instance Show NoMethodError where
showsPrec _ (NoMethodError err) = showString err
-- | @since 4.0
instance Exception NoMethodError
-----
-- |An expression that didn't typecheck during compile time was called.
-- This is only possible with -fdefer-type-errors. The @String@ gives
-- details about the failed type check.
--
-- @since 4.9.0.0
newtype TypeError = TypeError String
-- | @since 4.9.0.0
instance Show TypeError where
showsPrec _ (TypeError err) = showString err
-- | @since 4.9.0.0
instance Exception TypeError
-----
-- |Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that
-- the runtime system will notice whether any given computation is
-- guaranteed to terminate or not.
data NonTermination = NonTermination
-- | @since 4.0
instance Show NonTermination where
showsPrec _ NonTermination = showString "<<loop>>"
-- | @since 4.0
instance Exception NonTermination
-----
-- |Thrown when the program attempts to call @atomically@, from the @stm@
-- package, inside another call to @atomically@.
data NestedAtomically = NestedAtomically
-- | @since 4.0
instance Show NestedAtomically where
showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
-- | @since 4.0
instance Exception NestedAtomically
-----
recSelError, recConError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError, typeError
:: Addr# -> a -- All take a UTF8-encoded C string
recSelError s = throw (RecSelError ("No match in record selector "
++ unpackCStringUtf8# s)) -- No location info unfortunately
runtimeError s = errorWithoutStackTrace (unpackCStringUtf8# s) -- No location info unfortunately
absentError s = errorWithoutStackTrace ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
recConError s = throw (RecConError (untangle s "Missing field in record construction"))
noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
typeError s = throw (TypeError (unpackCStringUtf8# s))
-- GHC's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination
-- GHC's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically
-- Introduced by unarise for unused unboxed sum fields
absentSumFieldError :: a
absentSumFieldError = absentError " in unboxed sum."#
|
sdiehl/ghc
|
libraries/base/Control/Exception/Base.hs
|
bsd-3-clause
| 13,326
| 0
| 15
| 3,208
| 1,984
| 1,126
| 858
| 173
| 3
|
--------------------------------------------------------------------------------
-- |
-- Module : Language.Verilog.Syntax.Ident
-- Copyright : (c) Signali Corp. 2010
-- License : All rights reserved
--
-- Maintainer : pweaver@signalicorp.com
-- Stability : experimental
-- Portability : ghc
--
-- Definition of Verilog identifiers.
--------------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Language.Verilog.Syntax.Ident
( -- * Identifier
Ident(..)
) where
import Data.Binary ( Binary )
import Data.Generics ( Data, Typeable )
--------------------------------------------------------------------------------
-- TODO check if an identifier is valid; convert to valid identifier
newtype Ident = Ident String
deriving (Eq, Ord, Show, Binary, Data, Typeable)
--------------------------------------------------------------------------------
|
githubkleon/ConvenientHDL
|
src/Language/Verilog/Syntax/Ident.hs
|
bsd-3-clause
| 1,001
| 0
| 6
| 150
| 93
| 63
| 30
| 9
| 0
|
module Chat.C where
world = "world"
|
caasi/trans
|
sample/Chat/C.hs
|
bsd-3-clause
| 37
| 0
| 4
| 7
| 11
| 7
| 4
| 2
| 1
|
module Language.Modelica.Test.ComponentClause (test) where
import qualified Language.Modelica.Parser.ComponentClause as CC
import Language.Modelica.Test.Utility (testFunc)
test :: IO [Bool]
test = do
res1 <- mapM (testFunc CC.condition_attribute) $
"if 7.0 + x" :
"if (7.0 + true)" : []
res2 <- mapM (testFunc CC.component_declaration) $
"x" :
"x[:, :]()" :
"x[:, 4.0](x := 6.0)" :
"x[:, 4.0](x := false .* 8.0) = true" :
"x[:, 4.0](x := 6.0) = f(7.0 == x + 8.0)" :
"x[:, 4.0]() = true if (7.0 == (false))" :
"x[:, 4.0]() = true if if (7.0 == (false)) then true else false" :
"x[:, 4.0]() = true if if if (x + y == (false)) then true else false then true else false" :
"x[:, :]() = 7.9 \"bla\" + \"blub\"" :
[]
res3 <- mapM (testFunc CC.component_list) $
"x" :
"x, y" :
"x[:, 4.0, :](x := 6.0), x[4.0]()" :
"x[:, 4.0, :](x := 6.0), x[false](), y" :
[]
res4 <- mapM (testFunc CC.component_clause) $
"flow parameter bla x" :
"stream constant output bla x, y" :
"stream constant output bla x, y" :
"stream constant output bla[:, 5.0] x, y" :
"Engine engine1(parMaxTorque = 170, engineFile = \"maps/engiääne/base.txt\") annotation(Placement(visible = true, transformation(origin = {-72.9833,-44.9117})))" :
[]
return $ res1 ++ res2 ++ res3 ++ res4
|
xie-dongping/modelicaparser
|
test/Language/Modelica/Test/ComponentClause.hs
|
bsd-3-clause
| 1,361
| 0
| 21
| 324
| 246
| 127
| 119
| 33
| 1
|
{-# language CPP #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
#ifndef ENABLE_INTERNAL_DOCUMENTATION
{-# OPTIONS_HADDOCK hide #-}
#endif
module OpenCV.Internal.Core.Types.Vec.TH
( mkVecType
) where
import "base" Data.List ( intercalate )
import "base" Data.Monoid ( (<>) )
import "base" Foreign.Marshal.Alloc ( alloca )
import "base" Foreign.Storable ( peek )
import "base" System.IO.Unsafe ( unsafePerformIO )
import qualified "inline-c" Language.C.Inline.Unsafe as CU
import "linear" Linear ( V2(..), V3(..), V4(..) )
import "template-haskell" Language.Haskell.TH
import "template-haskell" Language.Haskell.TH.Quote ( quoteExp )
import "this" OpenCV.Internal.C.PlacementNew.TH ( mkPlacementNewInstance )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Core.Types.Vec
import "this" OpenCV.Internal
mkVecType
:: String -- ^ Vec type name, for both Haskell and C
-> Integer -- ^ Vec dimension
-> Name -- ^ Depth type name in Haskell
-> String -- ^ Depth type name in C
-> Q [Dec]
mkVecType vTypeNameStr dim depthTypeName cDepthTypeStr
| dim < 2 || dim > 4 = fail $ "mkVecType: Unsupported dimension: " <> show dim
| otherwise =
fmap concat . sequence $
[ pure <$> vecTySynD
, fromPtrDs
, isVecOpenCVInstanceDs
, isVecHaskellInstanceDs
, mkPlacementNewInstance vTypeName
]
where
vTypeName :: Name
vTypeName = mkName vTypeNameStr
cVecTypeStr :: String
cVecTypeStr = vTypeNameStr
vTypeQ :: Q Type
vTypeQ = conT vTypeName
depthTypeQ :: Q Type
depthTypeQ = conT depthTypeName
dimTypeQ :: Q Type
dimTypeQ = litT (numTyLit dim)
vecTySynD :: Q Dec
vecTySynD =
tySynD vTypeName
[]
([t|Vec|] `appT` dimTypeQ `appT` depthTypeQ)
fromPtrDs :: Q [Dec]
fromPtrDs =
[d|
instance FromPtr $(vTypeQ) where
fromPtr = objFromPtr Vec $ $(finalizerExpQ)
|]
where
finalizerExpQ :: Q Exp
finalizerExpQ = do
ptr <- newName "ptr"
lamE [varP ptr] $
quoteExp CU.exp $
"void { delete $(" <> cVecTypeStr <> " * " <> nameBase ptr <> ") }"
isVecOpenCVInstanceDs :: Q [Dec]
isVecOpenCVInstanceDs =
[d|
instance IsVec (Vec $(dimTypeQ)) $(depthTypeQ) where
toVec = id
toVecIO = pure
fromVec = id
|]
isVecHaskellInstanceDs :: Q [Dec]
isVecHaskellInstanceDs =
let ix = fromInteger dim - 2
in withLinear (linearTypeQs !! ix)
(linearConNames !! ix)
where
linearTypeQs :: [Q Type]
linearTypeQs = map conT [''V2, ''V3, ''V4]
linearConNames :: [Name]
linearConNames = ['V2, 'V3, 'V4]
withLinear :: Q Type -> Name -> Q [Dec]
withLinear lvTypeQ lvConName =
[d|
instance IsVec $(lvTypeQ) $(depthTypeQ) where
toVec = unsafePerformIO . toVecIO
toVecIO = $(toVecIOExpQ)
fromVec = $(fromVecExpQ)
|]
where
toVecIOExpQ :: Q Exp
toVecIOExpQ = do
ns <- mapM newName elemNames
lamE [conP lvConName $ map varP ns]
$ appE [e|fromPtr|]
$ quoteExp CU.exp
$ inlineCStr ns
where
inlineCStr :: [Name] -> String
inlineCStr ns = concat
[ cVecTypeStr
, " * { new cv::Vec<"
, cDepthTypeStr
, ", "
, show dim
, ">(" <> intercalate ", " (map elemQuote ns) <> ")"
, " }"
]
where
elemQuote :: Name -> String
elemQuote n = "$(" <> cDepthTypeStr <> " " <> nameBase n <> ")"
fromVecExpQ :: Q Exp
fromVecExpQ = do
vec <- newName "vec"
vecPtr <- newName "vecPtr"
ptrNames <- mapM (newName . (<> "Ptr")) elemNames
withPtrNames vec vecPtr ptrNames
where
withPtrNames :: Name -> Name -> [Name] -> Q Exp
withPtrNames vec vecPtr ptrNames =
lamE [varP vec]
$ appE [e|unsafePerformIO|]
$ withPtrVarsExpQ ptrNames
where
withPtrVarsExpQ :: [Name] -> Q Exp
withPtrVarsExpQ = foldr (\p -> appE [e|alloca|] . lamE [varP p]) withAllocatedVars
withAllocatedVars :: Q Exp
withAllocatedVars =
appE ([e|withPtr|] `appE` varE vec)
$ lamE [varP vecPtr]
$ doE
[ noBindS $ quoteExp CU.block inlineCStr
, noBindS extractExpQ
]
inlineCStr :: String
inlineCStr = unlines $
concat
[ "void {"
, "const cv::Vec<"
, cDepthTypeStr
, ", " <> show dim <> "> & p = *$("
, cVecTypeStr
, " * "
, nameBase vecPtr
, ");"
]
: map ptrLine (zip [0..] ptrNames)
<> ["}"]
where
ptrLine :: (Int, Name) -> String
ptrLine (ix, ptrName) =
"*$(" <> cDepthTypeStr <> " * " <> nameBase ptrName <> ") = p[" <> show ix <> "];"
-- Applies the constructor to the values that are
-- read from the pointers.
extractExpQ :: Q Exp
extractExpQ = foldl (\acc peekExp -> [e|(<*>)|] `appE` acc `appE` peekExp)
([e|pure|] `appE` conE lvConName)
peekExpQs
where
peekExpQs :: [Q Exp]
peekExpQs = map (\p -> [e|peek|] `appE` varE p) ptrNames
elemNames :: [String]
elemNames = take (fromInteger dim)
["x", "y", "z", "w"]
|
lukexi/haskell-opencv
|
src/OpenCV/Internal/Core/Types/Vec/TH.hs
|
bsd-3-clause
| 6,539
| 0
| 22
| 2,825
| 1,399
| 784
| 615
| -1
| -1
|
module Data.Deciparsec ( module Data.Deciparsec.Combinator
, module Data.Deciparsec.Parser
, module Data.Deciparsec.Prim
, module Data.Deciparsec.Scan
, module Data.Deciparsec.TokenSet
) where
import Data.Deciparsec.Combinator
import Data.Deciparsec.Parser
import Data.Deciparsec.Prim
import Data.Deciparsec.Scan
import Data.Deciparsec.TokenSet
|
d3tucker/deciparsec
|
src/Data/Deciparsec.hs
|
bsd-3-clause
| 462
| 0
| 5
| 146
| 73
| 50
| 23
| 10
| 0
|
{-# LANGUAGE Rank2Types, GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module AbstractSyntaxDump where
{-# LINE 2 "./src-ag/Expression.ag" #-}
import UU.Scanner.Position(Pos)
import HsToken
{-# LINE 10 "dist/build/AbstractSyntaxDump.hs" #-}
{-# LINE 2 "./src-ag/Patterns.ag" #-}
-- Patterns.ag imports
import UU.Scanner.Position(Pos)
import CommonTypes (ConstructorIdent,Identifier)
{-# LINE 17 "dist/build/AbstractSyntaxDump.hs" #-}
{-# LINE 2 "./src-ag/AbstractSyntax.ag" #-}
-- AbstractSyntax.ag imports
import Data.Set(Set)
import Data.Map(Map)
import Patterns (Pattern(..),Patterns)
import Expression (Expression(..))
import Macro --marcos
import CommonTypes
import ErrorMessages
{-# LINE 29 "dist/build/AbstractSyntaxDump.hs" #-}
{-# LINE 6 "./src-ag/AbstractSyntaxDump.ag" #-}
import Data.List
import qualified Data.Map as Map
import Pretty
import PPUtil
import AbstractSyntax
import TokenDef
{-# LINE 41 "dist/build/AbstractSyntaxDump.hs" #-}
import Control.Monad.Identity (Identity)
import qualified Control.Monad.Identity
-- Child -------------------------------------------------------
-- wrapper
data Inh_Child = Inh_Child { }
data Syn_Child = Syn_Child { pp_Syn_Child :: (PP_Doc) }
{-# INLINABLE wrap_Child #-}
wrap_Child :: T_Child -> Inh_Child -> (Syn_Child )
wrap_Child (T_Child act) (Inh_Child ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Child_vIn1
(T_Child_vOut1 _lhsOpp) <- return (inv_Child_s2 sem arg)
return (Syn_Child _lhsOpp)
)
-- cata
{-# INLINE sem_Child #-}
sem_Child :: Child -> T_Child
sem_Child ( Child name_ tp_ kind_ ) = sem_Child_Child name_ tp_ kind_
-- semantic domain
newtype T_Child = T_Child {
attach_T_Child :: Identity (T_Child_s2 )
}
newtype T_Child_s2 = C_Child_s2 {
inv_Child_s2 :: (T_Child_v1 )
}
data T_Child_s3 = C_Child_s3
type T_Child_v1 = (T_Child_vIn1 ) -> (T_Child_vOut1 )
data T_Child_vIn1 = T_Child_vIn1
data T_Child_vOut1 = T_Child_vOut1 (PP_Doc)
{-# NOINLINE sem_Child_Child #-}
sem_Child_Child :: (Identifier) -> (Type) -> (ChildKind) -> T_Child
sem_Child_Child arg_name_ arg_tp_ arg_kind_ = T_Child (return st2) where
{-# NOINLINE st2 #-}
st2 = let
v1 :: T_Child_v1
v1 = \ (T_Child_vIn1 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule0 arg_kind_ arg_name_ arg_tp_
__result_ = T_Child_vOut1 _lhsOpp
in __result_ )
in C_Child_s2 v1
{-# INLINE rule0 #-}
{-# LINE 35 "./src-ag/AbstractSyntaxDump.ag" #-}
rule0 = \ kind_ name_ tp_ ->
{-# LINE 35 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Child","Child"] [pp name_, ppShow tp_] [ppF "kind" $ ppShow kind_] []
{-# LINE 91 "dist/build/AbstractSyntaxDump.hs"#-}
-- Children ----------------------------------------------------
-- wrapper
data Inh_Children = Inh_Children { }
data Syn_Children = Syn_Children { pp_Syn_Children :: (PP_Doc), ppL_Syn_Children :: ([PP_Doc]) }
{-# INLINABLE wrap_Children #-}
wrap_Children :: T_Children -> Inh_Children -> (Syn_Children )
wrap_Children (T_Children act) (Inh_Children ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Children_vIn4
(T_Children_vOut4 _lhsOpp _lhsOppL) <- return (inv_Children_s5 sem arg)
return (Syn_Children _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Children #-}
sem_Children :: Children -> T_Children
sem_Children list = Prelude.foldr sem_Children_Cons sem_Children_Nil (Prelude.map sem_Child list)
-- semantic domain
newtype T_Children = T_Children {
attach_T_Children :: Identity (T_Children_s5 )
}
newtype T_Children_s5 = C_Children_s5 {
inv_Children_s5 :: (T_Children_v4 )
}
data T_Children_s6 = C_Children_s6
type T_Children_v4 = (T_Children_vIn4 ) -> (T_Children_vOut4 )
data T_Children_vIn4 = T_Children_vIn4
data T_Children_vOut4 = T_Children_vOut4 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Children_Cons #-}
sem_Children_Cons :: T_Child -> T_Children -> T_Children
sem_Children_Cons arg_hd_ arg_tl_ = T_Children (return st5) where
{-# NOINLINE st5 #-}
st5 = let
v4 :: T_Children_v4
v4 = \ (T_Children_vIn4 ) -> ( let
_hdX2 = Control.Monad.Identity.runIdentity (attach_T_Child (arg_hd_))
_tlX5 = Control.Monad.Identity.runIdentity (attach_T_Children (arg_tl_))
(T_Child_vOut1 _hdIpp) = inv_Child_s2 _hdX2 (T_Child_vIn1 )
(T_Children_vOut4 _tlIpp _tlIppL) = inv_Children_s5 _tlX5 (T_Children_vIn4 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule1 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule2 _hdIpp _tlIpp
__result_ = T_Children_vOut4 _lhsOpp _lhsOppL
in __result_ )
in C_Children_s5 v4
{-# INLINE rule1 #-}
{-# LINE 67 "./src-ag/AbstractSyntaxDump.ag" #-}
rule1 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 67 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 146 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule2 #-}
rule2 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_Children_Nil #-}
sem_Children_Nil :: T_Children
sem_Children_Nil = T_Children (return st5) where
{-# NOINLINE st5 #-}
st5 = let
v4 :: T_Children_v4
v4 = \ (T_Children_vIn4 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule3 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule4 ()
__result_ = T_Children_vOut4 _lhsOpp _lhsOppL
in __result_ )
in C_Children_s5 v4
{-# INLINE rule3 #-}
{-# LINE 68 "./src-ag/AbstractSyntaxDump.ag" #-}
rule3 = \ (_ :: ()) ->
{-# LINE 68 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 169 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule4 #-}
rule4 = \ (_ :: ()) ->
empty
-- Expression --------------------------------------------------
-- wrapper
data Inh_Expression = Inh_Expression { }
data Syn_Expression = Syn_Expression { pp_Syn_Expression :: (PP_Doc) }
{-# INLINABLE wrap_Expression #-}
wrap_Expression :: T_Expression -> Inh_Expression -> (Syn_Expression )
wrap_Expression (T_Expression act) (Inh_Expression ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Expression_vIn7
(T_Expression_vOut7 _lhsOpp) <- return (inv_Expression_s8 sem arg)
return (Syn_Expression _lhsOpp)
)
-- cata
{-# INLINE sem_Expression #-}
sem_Expression :: Expression -> T_Expression
sem_Expression ( Expression pos_ tks_ ) = sem_Expression_Expression pos_ tks_
-- semantic domain
newtype T_Expression = T_Expression {
attach_T_Expression :: Identity (T_Expression_s8 )
}
newtype T_Expression_s8 = C_Expression_s8 {
inv_Expression_s8 :: (T_Expression_v7 )
}
data T_Expression_s9 = C_Expression_s9
type T_Expression_v7 = (T_Expression_vIn7 ) -> (T_Expression_vOut7 )
data T_Expression_vIn7 = T_Expression_vIn7
data T_Expression_vOut7 = T_Expression_vOut7 (PP_Doc)
{-# NOINLINE sem_Expression_Expression #-}
sem_Expression_Expression :: (Pos) -> ([HsToken]) -> T_Expression
sem_Expression_Expression arg_pos_ arg_tks_ = T_Expression (return st8) where
{-# NOINLINE st8 #-}
st8 = let
v7 :: T_Expression_v7
v7 = \ (T_Expression_vIn7 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule5 arg_pos_ arg_tks_
__result_ = T_Expression_vOut7 _lhsOpp
in __result_ )
in C_Expression_s8 v7
{-# INLINE rule5 #-}
{-# LINE 50 "./src-ag/AbstractSyntaxDump.ag" #-}
rule5 = \ pos_ tks_ ->
{-# LINE 50 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Expression","Expression"] [ppShow pos_] [ppF "txt" $ vlist . showTokens . tokensToStrings $ tks_] []
{-# LINE 221 "dist/build/AbstractSyntaxDump.hs"#-}
-- Grammar -----------------------------------------------------
-- wrapper
data Inh_Grammar = Inh_Grammar { }
data Syn_Grammar = Syn_Grammar { pp_Syn_Grammar :: (PP_Doc) }
{-# INLINABLE wrap_Grammar #-}
wrap_Grammar :: T_Grammar -> Inh_Grammar -> (Syn_Grammar )
wrap_Grammar (T_Grammar act) (Inh_Grammar ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Grammar_vIn10
(T_Grammar_vOut10 _lhsOpp) <- return (inv_Grammar_s11 sem arg)
return (Syn_Grammar _lhsOpp)
)
-- cata
{-# INLINE sem_Grammar #-}
sem_Grammar :: Grammar -> T_Grammar
sem_Grammar ( Grammar typeSyns_ useMap_ derivings_ wrappers_ nonts_ pragmas_ manualAttrOrderMap_ paramMap_ contextMap_ quantMap_ uniqueMap_ augmentsMap_ aroundsMap_ mergeMap_ ) = sem_Grammar_Grammar typeSyns_ useMap_ derivings_ wrappers_ ( sem_Nonterminals nonts_ ) pragmas_ manualAttrOrderMap_ paramMap_ contextMap_ quantMap_ uniqueMap_ augmentsMap_ aroundsMap_ mergeMap_
-- semantic domain
newtype T_Grammar = T_Grammar {
attach_T_Grammar :: Identity (T_Grammar_s11 )
}
newtype T_Grammar_s11 = C_Grammar_s11 {
inv_Grammar_s11 :: (T_Grammar_v10 )
}
data T_Grammar_s12 = C_Grammar_s12
type T_Grammar_v10 = (T_Grammar_vIn10 ) -> (T_Grammar_vOut10 )
data T_Grammar_vIn10 = T_Grammar_vIn10
data T_Grammar_vOut10 = T_Grammar_vOut10 (PP_Doc)
{-# NOINLINE sem_Grammar_Grammar #-}
sem_Grammar_Grammar :: (TypeSyns) -> (UseMap) -> (Derivings) -> (Set NontermIdent) -> T_Nonterminals -> (PragmaMap) -> (AttrOrderMap) -> (ParamMap) -> (ContextMap) -> (QuantMap) -> (UniqueMap) -> (Map NontermIdent (Map ConstructorIdent (Map Identifier [Expression]))) -> (Map NontermIdent (Map ConstructorIdent (Map Identifier [Expression]))) -> (Map NontermIdent (Map ConstructorIdent (Map Identifier (Identifier, [Identifier], Expression)))) -> T_Grammar
sem_Grammar_Grammar arg_typeSyns_ arg_useMap_ arg_derivings_ arg_wrappers_ arg_nonts_ _ _ _ _ _ _ _ _ _ = T_Grammar (return st11) where
{-# NOINLINE st11 #-}
st11 = let
v10 :: T_Grammar_v10
v10 = \ (T_Grammar_vIn10 ) -> ( let
_nontsX17 = Control.Monad.Identity.runIdentity (attach_T_Nonterminals (arg_nonts_))
(T_Nonterminals_vOut16 _nontsIpp _nontsIppL) = inv_Nonterminals_s17 _nontsX17 (T_Nonterminals_vIn16 )
_lhsOpp :: PP_Doc
_lhsOpp = rule6 _nontsIppL arg_derivings_ arg_typeSyns_ arg_useMap_ arg_wrappers_
__result_ = T_Grammar_vOut10 _lhsOpp
in __result_ )
in C_Grammar_s11 v10
{-# INLINE rule6 #-}
{-# LINE 20 "./src-ag/AbstractSyntaxDump.ag" #-}
rule6 = \ ((_nontsIppL) :: [PP_Doc]) derivings_ typeSyns_ useMap_ wrappers_ ->
{-# LINE 20 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Grammar","Grammar"] []
[ ppF "typeSyns" $ ppAssocL typeSyns_
, ppF "useMap" $ ppMap $ Map.map ppMap $ useMap_
, ppF "derivings" $ ppMap $ derivings_
, ppF "wrappers" $ ppShow $ wrappers_
, ppF "nonts" $ ppVList _nontsIppL
] []
{-# LINE 278 "dist/build/AbstractSyntaxDump.hs"#-}
-- Nonterminal -------------------------------------------------
-- wrapper
data Inh_Nonterminal = Inh_Nonterminal { }
data Syn_Nonterminal = Syn_Nonterminal { pp_Syn_Nonterminal :: (PP_Doc) }
{-# INLINABLE wrap_Nonterminal #-}
wrap_Nonterminal :: T_Nonterminal -> Inh_Nonterminal -> (Syn_Nonterminal )
wrap_Nonterminal (T_Nonterminal act) (Inh_Nonterminal ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Nonterminal_vIn13
(T_Nonterminal_vOut13 _lhsOpp) <- return (inv_Nonterminal_s14 sem arg)
return (Syn_Nonterminal _lhsOpp)
)
-- cata
{-# INLINE sem_Nonterminal #-}
sem_Nonterminal :: Nonterminal -> T_Nonterminal
sem_Nonterminal ( Nonterminal nt_ params_ inh_ syn_ prods_ ) = sem_Nonterminal_Nonterminal nt_ params_ inh_ syn_ ( sem_Productions prods_ )
-- semantic domain
newtype T_Nonterminal = T_Nonterminal {
attach_T_Nonterminal :: Identity (T_Nonterminal_s14 )
}
newtype T_Nonterminal_s14 = C_Nonterminal_s14 {
inv_Nonterminal_s14 :: (T_Nonterminal_v13 )
}
data T_Nonterminal_s15 = C_Nonterminal_s15
type T_Nonterminal_v13 = (T_Nonterminal_vIn13 ) -> (T_Nonterminal_vOut13 )
data T_Nonterminal_vIn13 = T_Nonterminal_vIn13
data T_Nonterminal_vOut13 = T_Nonterminal_vOut13 (PP_Doc)
{-# NOINLINE sem_Nonterminal_Nonterminal #-}
sem_Nonterminal_Nonterminal :: (NontermIdent) -> ([Identifier]) -> (Attributes) -> (Attributes) -> T_Productions -> T_Nonterminal
sem_Nonterminal_Nonterminal arg_nt_ arg_params_ arg_inh_ arg_syn_ arg_prods_ = T_Nonterminal (return st14) where
{-# NOINLINE st14 #-}
st14 = let
v13 :: T_Nonterminal_v13
v13 = \ (T_Nonterminal_vIn13 ) -> ( let
_prodsX29 = Control.Monad.Identity.runIdentity (attach_T_Productions (arg_prods_))
(T_Productions_vOut28 _prodsIpp _prodsIppL) = inv_Productions_s29 _prodsX29 (T_Productions_vIn28 )
_lhsOpp :: PP_Doc
_lhsOpp = rule7 _prodsIppL arg_inh_ arg_nt_ arg_params_ arg_syn_
__result_ = T_Nonterminal_vOut13 _lhsOpp
in __result_ )
in C_Nonterminal_s14 v13
{-# INLINE rule7 #-}
{-# LINE 29 "./src-ag/AbstractSyntaxDump.ag" #-}
rule7 = \ ((_prodsIppL) :: [PP_Doc]) inh_ nt_ params_ syn_ ->
{-# LINE 29 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Nonterminal","Nonterminal"] (pp nt_ : map pp params_) [ppF "inh" $ ppMap inh_, ppF "syn" $ ppMap syn_, ppF "prods" $ ppVList _prodsIppL] []
{-# LINE 329 "dist/build/AbstractSyntaxDump.hs"#-}
-- Nonterminals ------------------------------------------------
-- wrapper
data Inh_Nonterminals = Inh_Nonterminals { }
data Syn_Nonterminals = Syn_Nonterminals { pp_Syn_Nonterminals :: (PP_Doc), ppL_Syn_Nonterminals :: ([PP_Doc]) }
{-# INLINABLE wrap_Nonterminals #-}
wrap_Nonterminals :: T_Nonterminals -> Inh_Nonterminals -> (Syn_Nonterminals )
wrap_Nonterminals (T_Nonterminals act) (Inh_Nonterminals ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Nonterminals_vIn16
(T_Nonterminals_vOut16 _lhsOpp _lhsOppL) <- return (inv_Nonterminals_s17 sem arg)
return (Syn_Nonterminals _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Nonterminals #-}
sem_Nonterminals :: Nonterminals -> T_Nonterminals
sem_Nonterminals list = Prelude.foldr sem_Nonterminals_Cons sem_Nonterminals_Nil (Prelude.map sem_Nonterminal list)
-- semantic domain
newtype T_Nonterminals = T_Nonterminals {
attach_T_Nonterminals :: Identity (T_Nonterminals_s17 )
}
newtype T_Nonterminals_s17 = C_Nonterminals_s17 {
inv_Nonterminals_s17 :: (T_Nonterminals_v16 )
}
data T_Nonterminals_s18 = C_Nonterminals_s18
type T_Nonterminals_v16 = (T_Nonterminals_vIn16 ) -> (T_Nonterminals_vOut16 )
data T_Nonterminals_vIn16 = T_Nonterminals_vIn16
data T_Nonterminals_vOut16 = T_Nonterminals_vOut16 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Nonterminals_Cons #-}
sem_Nonterminals_Cons :: T_Nonterminal -> T_Nonterminals -> T_Nonterminals
sem_Nonterminals_Cons arg_hd_ arg_tl_ = T_Nonterminals (return st17) where
{-# NOINLINE st17 #-}
st17 = let
v16 :: T_Nonterminals_v16
v16 = \ (T_Nonterminals_vIn16 ) -> ( let
_hdX14 = Control.Monad.Identity.runIdentity (attach_T_Nonterminal (arg_hd_))
_tlX17 = Control.Monad.Identity.runIdentity (attach_T_Nonterminals (arg_tl_))
(T_Nonterminal_vOut13 _hdIpp) = inv_Nonterminal_s14 _hdX14 (T_Nonterminal_vIn13 )
(T_Nonterminals_vOut16 _tlIpp _tlIppL) = inv_Nonterminals_s17 _tlX17 (T_Nonterminals_vIn16 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule8 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule9 _hdIpp _tlIpp
__result_ = T_Nonterminals_vOut16 _lhsOpp _lhsOppL
in __result_ )
in C_Nonterminals_s17 v16
{-# INLINE rule8 #-}
{-# LINE 75 "./src-ag/AbstractSyntaxDump.ag" #-}
rule8 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 75 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 384 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule9 #-}
rule9 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_Nonterminals_Nil #-}
sem_Nonterminals_Nil :: T_Nonterminals
sem_Nonterminals_Nil = T_Nonterminals (return st17) where
{-# NOINLINE st17 #-}
st17 = let
v16 :: T_Nonterminals_v16
v16 = \ (T_Nonterminals_vIn16 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule10 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule11 ()
__result_ = T_Nonterminals_vOut16 _lhsOpp _lhsOppL
in __result_ )
in C_Nonterminals_s17 v16
{-# INLINE rule10 #-}
{-# LINE 76 "./src-ag/AbstractSyntaxDump.ag" #-}
rule10 = \ (_ :: ()) ->
{-# LINE 76 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 407 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule11 #-}
rule11 = \ (_ :: ()) ->
empty
-- Pattern -----------------------------------------------------
-- wrapper
data Inh_Pattern = Inh_Pattern { }
data Syn_Pattern = Syn_Pattern { copy_Syn_Pattern :: (Pattern), pp_Syn_Pattern :: (PP_Doc) }
{-# INLINABLE wrap_Pattern #-}
wrap_Pattern :: T_Pattern -> Inh_Pattern -> (Syn_Pattern )
wrap_Pattern (T_Pattern act) (Inh_Pattern ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Pattern_vIn19
(T_Pattern_vOut19 _lhsOcopy _lhsOpp) <- return (inv_Pattern_s20 sem arg)
return (Syn_Pattern _lhsOcopy _lhsOpp)
)
-- cata
{-# NOINLINE sem_Pattern #-}
sem_Pattern :: Pattern -> T_Pattern
sem_Pattern ( Constr name_ pats_ ) = sem_Pattern_Constr name_ ( sem_Patterns pats_ )
sem_Pattern ( Product pos_ pats_ ) = sem_Pattern_Product pos_ ( sem_Patterns pats_ )
sem_Pattern ( Alias field_ attr_ pat_ ) = sem_Pattern_Alias field_ attr_ ( sem_Pattern pat_ )
sem_Pattern ( Irrefutable pat_ ) = sem_Pattern_Irrefutable ( sem_Pattern pat_ )
sem_Pattern ( Underscore pos_ ) = sem_Pattern_Underscore pos_
-- semantic domain
newtype T_Pattern = T_Pattern {
attach_T_Pattern :: Identity (T_Pattern_s20 )
}
newtype T_Pattern_s20 = C_Pattern_s20 {
inv_Pattern_s20 :: (T_Pattern_v19 )
}
data T_Pattern_s21 = C_Pattern_s21
type T_Pattern_v19 = (T_Pattern_vIn19 ) -> (T_Pattern_vOut19 )
data T_Pattern_vIn19 = T_Pattern_vIn19
data T_Pattern_vOut19 = T_Pattern_vOut19 (Pattern) (PP_Doc)
{-# NOINLINE sem_Pattern_Constr #-}
sem_Pattern_Constr :: (ConstructorIdent) -> T_Patterns -> T_Pattern
sem_Pattern_Constr arg_name_ arg_pats_ = T_Pattern (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_Pattern_v19
v19 = \ (T_Pattern_vIn19 ) -> ( let
_patsX23 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_pats_))
(T_Patterns_vOut22 _patsIcopy _patsIpp _patsIppL) = inv_Patterns_s23 _patsX23 (T_Patterns_vIn22 )
_lhsOpp :: PP_Doc
_lhsOpp = rule12 _patsIppL arg_name_
_copy = rule13 _patsIcopy arg_name_
_lhsOcopy :: Pattern
_lhsOcopy = rule14 _copy
__result_ = T_Pattern_vOut19 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s20 v19
{-# INLINE rule12 #-}
{-# LINE 44 "./src-ag/AbstractSyntaxDump.ag" #-}
rule12 = \ ((_patsIppL) :: [PP_Doc]) name_ ->
{-# LINE 44 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Constr"] [pp name_] [ppF "pats" $ ppVList _patsIppL] []
{-# LINE 468 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule13 #-}
rule13 = \ ((_patsIcopy) :: Patterns) name_ ->
Constr name_ _patsIcopy
{-# INLINE rule14 #-}
rule14 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Product #-}
sem_Pattern_Product :: (Pos) -> T_Patterns -> T_Pattern
sem_Pattern_Product arg_pos_ arg_pats_ = T_Pattern (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_Pattern_v19
v19 = \ (T_Pattern_vIn19 ) -> ( let
_patsX23 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_pats_))
(T_Patterns_vOut22 _patsIcopy _patsIpp _patsIppL) = inv_Patterns_s23 _patsX23 (T_Patterns_vIn22 )
_lhsOpp :: PP_Doc
_lhsOpp = rule15 _patsIppL arg_pos_
_copy = rule16 _patsIcopy arg_pos_
_lhsOcopy :: Pattern
_lhsOcopy = rule17 _copy
__result_ = T_Pattern_vOut19 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s20 v19
{-# INLINE rule15 #-}
{-# LINE 45 "./src-ag/AbstractSyntaxDump.ag" #-}
rule15 = \ ((_patsIppL) :: [PP_Doc]) pos_ ->
{-# LINE 45 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Product"] [ppShow pos_] [ppF "pats" $ ppVList _patsIppL] []
{-# LINE 497 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule16 #-}
rule16 = \ ((_patsIcopy) :: Patterns) pos_ ->
Product pos_ _patsIcopy
{-# INLINE rule17 #-}
rule17 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Alias #-}
sem_Pattern_Alias :: (Identifier) -> (Identifier) -> T_Pattern -> T_Pattern
sem_Pattern_Alias arg_field_ arg_attr_ arg_pat_ = T_Pattern (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_Pattern_v19
v19 = \ (T_Pattern_vIn19 ) -> ( let
_patX20 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pat_))
(T_Pattern_vOut19 _patIcopy _patIpp) = inv_Pattern_s20 _patX20 (T_Pattern_vIn19 )
_lhsOpp :: PP_Doc
_lhsOpp = rule18 _patIpp arg_attr_ arg_field_
_copy = rule19 _patIcopy arg_attr_ arg_field_
_lhsOcopy :: Pattern
_lhsOcopy = rule20 _copy
__result_ = T_Pattern_vOut19 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s20 v19
{-# INLINE rule18 #-}
{-# LINE 46 "./src-ag/AbstractSyntaxDump.ag" #-}
rule18 = \ ((_patIpp) :: PP_Doc) attr_ field_ ->
{-# LINE 46 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Alias"] [pp field_, pp attr_] [ppF "pat" $ _patIpp] []
{-# LINE 526 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule19 #-}
rule19 = \ ((_patIcopy) :: Pattern) attr_ field_ ->
Alias field_ attr_ _patIcopy
{-# INLINE rule20 #-}
rule20 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Irrefutable #-}
sem_Pattern_Irrefutable :: T_Pattern -> T_Pattern
sem_Pattern_Irrefutable arg_pat_ = T_Pattern (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_Pattern_v19
v19 = \ (T_Pattern_vIn19 ) -> ( let
_patX20 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pat_))
(T_Pattern_vOut19 _patIcopy _patIpp) = inv_Pattern_s20 _patX20 (T_Pattern_vIn19 )
_lhsOpp :: PP_Doc
_lhsOpp = rule21 _patIpp
_copy = rule22 _patIcopy
_lhsOcopy :: Pattern
_lhsOcopy = rule23 _copy
__result_ = T_Pattern_vOut19 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s20 v19
{-# INLINE rule21 #-}
rule21 = \ ((_patIpp) :: PP_Doc) ->
_patIpp
{-# INLINE rule22 #-}
rule22 = \ ((_patIcopy) :: Pattern) ->
Irrefutable _patIcopy
{-# INLINE rule23 #-}
rule23 = \ _copy ->
_copy
{-# NOINLINE sem_Pattern_Underscore #-}
sem_Pattern_Underscore :: (Pos) -> T_Pattern
sem_Pattern_Underscore arg_pos_ = T_Pattern (return st20) where
{-# NOINLINE st20 #-}
st20 = let
v19 :: T_Pattern_v19
v19 = \ (T_Pattern_vIn19 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule24 arg_pos_
_copy = rule25 arg_pos_
_lhsOcopy :: Pattern
_lhsOcopy = rule26 _copy
__result_ = T_Pattern_vOut19 _lhsOcopy _lhsOpp
in __result_ )
in C_Pattern_s20 v19
{-# INLINE rule24 #-}
{-# LINE 47 "./src-ag/AbstractSyntaxDump.ag" #-}
rule24 = \ pos_ ->
{-# LINE 47 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Pattern","Underscore"] [ppShow pos_] [] []
{-# LINE 579 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule25 #-}
rule25 = \ pos_ ->
Underscore pos_
{-# INLINE rule26 #-}
rule26 = \ _copy ->
_copy
-- Patterns ----------------------------------------------------
-- wrapper
data Inh_Patterns = Inh_Patterns { }
data Syn_Patterns = Syn_Patterns { copy_Syn_Patterns :: (Patterns), pp_Syn_Patterns :: (PP_Doc), ppL_Syn_Patterns :: ([PP_Doc]) }
{-# INLINABLE wrap_Patterns #-}
wrap_Patterns :: T_Patterns -> Inh_Patterns -> (Syn_Patterns )
wrap_Patterns (T_Patterns act) (Inh_Patterns ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Patterns_vIn22
(T_Patterns_vOut22 _lhsOcopy _lhsOpp _lhsOppL) <- return (inv_Patterns_s23 sem arg)
return (Syn_Patterns _lhsOcopy _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Patterns #-}
sem_Patterns :: Patterns -> T_Patterns
sem_Patterns list = Prelude.foldr sem_Patterns_Cons sem_Patterns_Nil (Prelude.map sem_Pattern list)
-- semantic domain
newtype T_Patterns = T_Patterns {
attach_T_Patterns :: Identity (T_Patterns_s23 )
}
newtype T_Patterns_s23 = C_Patterns_s23 {
inv_Patterns_s23 :: (T_Patterns_v22 )
}
data T_Patterns_s24 = C_Patterns_s24
type T_Patterns_v22 = (T_Patterns_vIn22 ) -> (T_Patterns_vOut22 )
data T_Patterns_vIn22 = T_Patterns_vIn22
data T_Patterns_vOut22 = T_Patterns_vOut22 (Patterns) (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Patterns_Cons #-}
sem_Patterns_Cons :: T_Pattern -> T_Patterns -> T_Patterns
sem_Patterns_Cons arg_hd_ arg_tl_ = T_Patterns (return st23) where
{-# NOINLINE st23 #-}
st23 = let
v22 :: T_Patterns_v22
v22 = \ (T_Patterns_vIn22 ) -> ( let
_hdX20 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_hd_))
_tlX23 = Control.Monad.Identity.runIdentity (attach_T_Patterns (arg_tl_))
(T_Pattern_vOut19 _hdIcopy _hdIpp) = inv_Pattern_s20 _hdX20 (T_Pattern_vIn19 )
(T_Patterns_vOut22 _tlIcopy _tlIpp _tlIppL) = inv_Patterns_s23 _tlX23 (T_Patterns_vIn22 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule27 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule28 _hdIpp _tlIpp
_copy = rule29 _hdIcopy _tlIcopy
_lhsOcopy :: Patterns
_lhsOcopy = rule30 _copy
__result_ = T_Patterns_vOut22 _lhsOcopy _lhsOpp _lhsOppL
in __result_ )
in C_Patterns_s23 v22
{-# INLINE rule27 #-}
{-# LINE 55 "./src-ag/AbstractSyntaxDump.ag" #-}
rule27 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 55 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 643 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule28 #-}
rule28 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# INLINE rule29 #-}
rule29 = \ ((_hdIcopy) :: Pattern) ((_tlIcopy) :: Patterns) ->
(:) _hdIcopy _tlIcopy
{-# INLINE rule30 #-}
rule30 = \ _copy ->
_copy
{-# NOINLINE sem_Patterns_Nil #-}
sem_Patterns_Nil :: T_Patterns
sem_Patterns_Nil = T_Patterns (return st23) where
{-# NOINLINE st23 #-}
st23 = let
v22 :: T_Patterns_v22
v22 = \ (T_Patterns_vIn22 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule31 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule32 ()
_copy = rule33 ()
_lhsOcopy :: Patterns
_lhsOcopy = rule34 _copy
__result_ = T_Patterns_vOut22 _lhsOcopy _lhsOpp _lhsOppL
in __result_ )
in C_Patterns_s23 v22
{-# INLINE rule31 #-}
{-# LINE 56 "./src-ag/AbstractSyntaxDump.ag" #-}
rule31 = \ (_ :: ()) ->
{-# LINE 56 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 675 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule32 #-}
rule32 = \ (_ :: ()) ->
empty
{-# INLINE rule33 #-}
rule33 = \ (_ :: ()) ->
[]
{-# INLINE rule34 #-}
rule34 = \ _copy ->
_copy
-- Production --------------------------------------------------
-- wrapper
data Inh_Production = Inh_Production { }
data Syn_Production = Syn_Production { pp_Syn_Production :: (PP_Doc) }
{-# INLINABLE wrap_Production #-}
wrap_Production :: T_Production -> Inh_Production -> (Syn_Production )
wrap_Production (T_Production act) (Inh_Production ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Production_vIn25
(T_Production_vOut25 _lhsOpp) <- return (inv_Production_s26 sem arg)
return (Syn_Production _lhsOpp)
)
-- cata
{-# INLINE sem_Production #-}
sem_Production :: Production -> T_Production
sem_Production ( Production con_ params_ constraints_ children_ rules_ typeSigs_ macro_ ) = sem_Production_Production con_ params_ constraints_ ( sem_Children children_ ) ( sem_Rules rules_ ) ( sem_TypeSigs typeSigs_ ) macro_
-- semantic domain
newtype T_Production = T_Production {
attach_T_Production :: Identity (T_Production_s26 )
}
newtype T_Production_s26 = C_Production_s26 {
inv_Production_s26 :: (T_Production_v25 )
}
data T_Production_s27 = C_Production_s27
type T_Production_v25 = (T_Production_vIn25 ) -> (T_Production_vOut25 )
data T_Production_vIn25 = T_Production_vIn25
data T_Production_vOut25 = T_Production_vOut25 (PP_Doc)
{-# NOINLINE sem_Production_Production #-}
sem_Production_Production :: (ConstructorIdent) -> ([Identifier]) -> ([Type]) -> T_Children -> T_Rules -> T_TypeSigs -> (MaybeMacro) -> T_Production
sem_Production_Production arg_con_ _ _ arg_children_ arg_rules_ arg_typeSigs_ _ = T_Production (return st26) where
{-# NOINLINE st26 #-}
st26 = let
v25 :: T_Production_v25
v25 = \ (T_Production_vIn25 ) -> ( let
_childrenX5 = Control.Monad.Identity.runIdentity (attach_T_Children (arg_children_))
_rulesX35 = Control.Monad.Identity.runIdentity (attach_T_Rules (arg_rules_))
_typeSigsX41 = Control.Monad.Identity.runIdentity (attach_T_TypeSigs (arg_typeSigs_))
(T_Children_vOut4 _childrenIpp _childrenIppL) = inv_Children_s5 _childrenX5 (T_Children_vIn4 )
(T_Rules_vOut34 _rulesIpp _rulesIppL) = inv_Rules_s35 _rulesX35 (T_Rules_vIn34 )
(T_TypeSigs_vOut40 _typeSigsIpp _typeSigsIppL) = inv_TypeSigs_s41 _typeSigsX41 (T_TypeSigs_vIn40 )
_lhsOpp :: PP_Doc
_lhsOpp = rule35 _childrenIppL _rulesIppL _typeSigsIppL arg_con_
__result_ = T_Production_vOut25 _lhsOpp
in __result_ )
in C_Production_s26 v25
{-# INLINE rule35 #-}
{-# LINE 32 "./src-ag/AbstractSyntaxDump.ag" #-}
rule35 = \ ((_childrenIppL) :: [PP_Doc]) ((_rulesIppL) :: [PP_Doc]) ((_typeSigsIppL) :: [PP_Doc]) con_ ->
{-# LINE 32 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Production","Production"] [pp con_] [ppF "children" $ ppVList _childrenIppL,ppF "rules" $ ppVList _rulesIppL,ppF "typeSigs" $ ppVList _typeSigsIppL] []
{-# LINE 739 "dist/build/AbstractSyntaxDump.hs"#-}
-- Productions -------------------------------------------------
-- wrapper
data Inh_Productions = Inh_Productions { }
data Syn_Productions = Syn_Productions { pp_Syn_Productions :: (PP_Doc), ppL_Syn_Productions :: ([PP_Doc]) }
{-# INLINABLE wrap_Productions #-}
wrap_Productions :: T_Productions -> Inh_Productions -> (Syn_Productions )
wrap_Productions (T_Productions act) (Inh_Productions ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Productions_vIn28
(T_Productions_vOut28 _lhsOpp _lhsOppL) <- return (inv_Productions_s29 sem arg)
return (Syn_Productions _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Productions #-}
sem_Productions :: Productions -> T_Productions
sem_Productions list = Prelude.foldr sem_Productions_Cons sem_Productions_Nil (Prelude.map sem_Production list)
-- semantic domain
newtype T_Productions = T_Productions {
attach_T_Productions :: Identity (T_Productions_s29 )
}
newtype T_Productions_s29 = C_Productions_s29 {
inv_Productions_s29 :: (T_Productions_v28 )
}
data T_Productions_s30 = C_Productions_s30
type T_Productions_v28 = (T_Productions_vIn28 ) -> (T_Productions_vOut28 )
data T_Productions_vIn28 = T_Productions_vIn28
data T_Productions_vOut28 = T_Productions_vOut28 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Productions_Cons #-}
sem_Productions_Cons :: T_Production -> T_Productions -> T_Productions
sem_Productions_Cons arg_hd_ arg_tl_ = T_Productions (return st29) where
{-# NOINLINE st29 #-}
st29 = let
v28 :: T_Productions_v28
v28 = \ (T_Productions_vIn28 ) -> ( let
_hdX26 = Control.Monad.Identity.runIdentity (attach_T_Production (arg_hd_))
_tlX29 = Control.Monad.Identity.runIdentity (attach_T_Productions (arg_tl_))
(T_Production_vOut25 _hdIpp) = inv_Production_s26 _hdX26 (T_Production_vIn25 )
(T_Productions_vOut28 _tlIpp _tlIppL) = inv_Productions_s29 _tlX29 (T_Productions_vIn28 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule36 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule37 _hdIpp _tlIpp
__result_ = T_Productions_vOut28 _lhsOpp _lhsOppL
in __result_ )
in C_Productions_s29 v28
{-# INLINE rule36 #-}
{-# LINE 71 "./src-ag/AbstractSyntaxDump.ag" #-}
rule36 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 71 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 794 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule37 #-}
rule37 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_Productions_Nil #-}
sem_Productions_Nil :: T_Productions
sem_Productions_Nil = T_Productions (return st29) where
{-# NOINLINE st29 #-}
st29 = let
v28 :: T_Productions_v28
v28 = \ (T_Productions_vIn28 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule38 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule39 ()
__result_ = T_Productions_vOut28 _lhsOpp _lhsOppL
in __result_ )
in C_Productions_s29 v28
{-# INLINE rule38 #-}
{-# LINE 72 "./src-ag/AbstractSyntaxDump.ag" #-}
rule38 = \ (_ :: ()) ->
{-# LINE 72 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 817 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule39 #-}
rule39 = \ (_ :: ()) ->
empty
-- Rule --------------------------------------------------------
-- wrapper
data Inh_Rule = Inh_Rule { }
data Syn_Rule = Syn_Rule { pp_Syn_Rule :: (PP_Doc) }
{-# INLINABLE wrap_Rule #-}
wrap_Rule :: T_Rule -> Inh_Rule -> (Syn_Rule )
wrap_Rule (T_Rule act) (Inh_Rule ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Rule_vIn31
(T_Rule_vOut31 _lhsOpp) <- return (inv_Rule_s32 sem arg)
return (Syn_Rule _lhsOpp)
)
-- cata
{-# INLINE sem_Rule #-}
sem_Rule :: Rule -> T_Rule
sem_Rule ( Rule mbName_ pattern_ rhs_ owrt_ origin_ explicit_ pure_ identity_ mbError_ eager_ ) = sem_Rule_Rule mbName_ ( sem_Pattern pattern_ ) ( sem_Expression rhs_ ) owrt_ origin_ explicit_ pure_ identity_ mbError_ eager_
-- semantic domain
newtype T_Rule = T_Rule {
attach_T_Rule :: Identity (T_Rule_s32 )
}
newtype T_Rule_s32 = C_Rule_s32 {
inv_Rule_s32 :: (T_Rule_v31 )
}
data T_Rule_s33 = C_Rule_s33
type T_Rule_v31 = (T_Rule_vIn31 ) -> (T_Rule_vOut31 )
data T_Rule_vIn31 = T_Rule_vIn31
data T_Rule_vOut31 = T_Rule_vOut31 (PP_Doc)
{-# NOINLINE sem_Rule_Rule #-}
sem_Rule_Rule :: (Maybe Identifier) -> T_Pattern -> T_Expression -> (Bool) -> (String) -> (Bool) -> (Bool) -> (Bool) -> (Maybe Error) -> (Bool) -> T_Rule
sem_Rule_Rule _ arg_pattern_ arg_rhs_ arg_owrt_ arg_origin_ _ _ _ _ _ = T_Rule (return st32) where
{-# NOINLINE st32 #-}
st32 = let
v31 :: T_Rule_v31
v31 = \ (T_Rule_vIn31 ) -> ( let
_patternX20 = Control.Monad.Identity.runIdentity (attach_T_Pattern (arg_pattern_))
_rhsX8 = Control.Monad.Identity.runIdentity (attach_T_Expression (arg_rhs_))
(T_Pattern_vOut19 _patternIcopy _patternIpp) = inv_Pattern_s20 _patternX20 (T_Pattern_vIn19 )
(T_Expression_vOut7 _rhsIpp) = inv_Expression_s8 _rhsX8 (T_Expression_vIn7 )
_lhsOpp :: PP_Doc
_lhsOpp = rule40 _patternIpp _rhsIpp arg_origin_ arg_owrt_
__result_ = T_Rule_vOut31 _lhsOpp
in __result_ )
in C_Rule_s32 v31
{-# INLINE rule40 #-}
{-# LINE 38 "./src-ag/AbstractSyntaxDump.ag" #-}
rule40 = \ ((_patternIpp) :: PP_Doc) ((_rhsIpp) :: PP_Doc) origin_ owrt_ ->
{-# LINE 38 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["Rule","Rule"] [ppShow owrt_, pp origin_] [ppF "pattern" $ _patternIpp, ppF "rhs" $ _rhsIpp] []
{-# LINE 873 "dist/build/AbstractSyntaxDump.hs"#-}
-- Rules -------------------------------------------------------
-- wrapper
data Inh_Rules = Inh_Rules { }
data Syn_Rules = Syn_Rules { pp_Syn_Rules :: (PP_Doc), ppL_Syn_Rules :: ([PP_Doc]) }
{-# INLINABLE wrap_Rules #-}
wrap_Rules :: T_Rules -> Inh_Rules -> (Syn_Rules )
wrap_Rules (T_Rules act) (Inh_Rules ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_Rules_vIn34
(T_Rules_vOut34 _lhsOpp _lhsOppL) <- return (inv_Rules_s35 sem arg)
return (Syn_Rules _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_Rules #-}
sem_Rules :: Rules -> T_Rules
sem_Rules list = Prelude.foldr sem_Rules_Cons sem_Rules_Nil (Prelude.map sem_Rule list)
-- semantic domain
newtype T_Rules = T_Rules {
attach_T_Rules :: Identity (T_Rules_s35 )
}
newtype T_Rules_s35 = C_Rules_s35 {
inv_Rules_s35 :: (T_Rules_v34 )
}
data T_Rules_s36 = C_Rules_s36
type T_Rules_v34 = (T_Rules_vIn34 ) -> (T_Rules_vOut34 )
data T_Rules_vIn34 = T_Rules_vIn34
data T_Rules_vOut34 = T_Rules_vOut34 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_Rules_Cons #-}
sem_Rules_Cons :: T_Rule -> T_Rules -> T_Rules
sem_Rules_Cons arg_hd_ arg_tl_ = T_Rules (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Rules_v34
v34 = \ (T_Rules_vIn34 ) -> ( let
_hdX32 = Control.Monad.Identity.runIdentity (attach_T_Rule (arg_hd_))
_tlX35 = Control.Monad.Identity.runIdentity (attach_T_Rules (arg_tl_))
(T_Rule_vOut31 _hdIpp) = inv_Rule_s32 _hdX32 (T_Rule_vIn31 )
(T_Rules_vOut34 _tlIpp _tlIppL) = inv_Rules_s35 _tlX35 (T_Rules_vIn34 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule41 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule42 _hdIpp _tlIpp
__result_ = T_Rules_vOut34 _lhsOpp _lhsOppL
in __result_ )
in C_Rules_s35 v34
{-# INLINE rule41 #-}
{-# LINE 63 "./src-ag/AbstractSyntaxDump.ag" #-}
rule41 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 63 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 928 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule42 #-}
rule42 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_Rules_Nil #-}
sem_Rules_Nil :: T_Rules
sem_Rules_Nil = T_Rules (return st35) where
{-# NOINLINE st35 #-}
st35 = let
v34 :: T_Rules_v34
v34 = \ (T_Rules_vIn34 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule43 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule44 ()
__result_ = T_Rules_vOut34 _lhsOpp _lhsOppL
in __result_ )
in C_Rules_s35 v34
{-# INLINE rule43 #-}
{-# LINE 64 "./src-ag/AbstractSyntaxDump.ag" #-}
rule43 = \ (_ :: ()) ->
{-# LINE 64 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 951 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule44 #-}
rule44 = \ (_ :: ()) ->
empty
-- TypeSig -----------------------------------------------------
-- wrapper
data Inh_TypeSig = Inh_TypeSig { }
data Syn_TypeSig = Syn_TypeSig { pp_Syn_TypeSig :: (PP_Doc) }
{-# INLINABLE wrap_TypeSig #-}
wrap_TypeSig :: T_TypeSig -> Inh_TypeSig -> (Syn_TypeSig )
wrap_TypeSig (T_TypeSig act) (Inh_TypeSig ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_TypeSig_vIn37
(T_TypeSig_vOut37 _lhsOpp) <- return (inv_TypeSig_s38 sem arg)
return (Syn_TypeSig _lhsOpp)
)
-- cata
{-# INLINE sem_TypeSig #-}
sem_TypeSig :: TypeSig -> T_TypeSig
sem_TypeSig ( TypeSig name_ tp_ ) = sem_TypeSig_TypeSig name_ tp_
-- semantic domain
newtype T_TypeSig = T_TypeSig {
attach_T_TypeSig :: Identity (T_TypeSig_s38 )
}
newtype T_TypeSig_s38 = C_TypeSig_s38 {
inv_TypeSig_s38 :: (T_TypeSig_v37 )
}
data T_TypeSig_s39 = C_TypeSig_s39
type T_TypeSig_v37 = (T_TypeSig_vIn37 ) -> (T_TypeSig_vOut37 )
data T_TypeSig_vIn37 = T_TypeSig_vIn37
data T_TypeSig_vOut37 = T_TypeSig_vOut37 (PP_Doc)
{-# NOINLINE sem_TypeSig_TypeSig #-}
sem_TypeSig_TypeSig :: (Identifier) -> (Type) -> T_TypeSig
sem_TypeSig_TypeSig arg_name_ arg_tp_ = T_TypeSig (return st38) where
{-# NOINLINE st38 #-}
st38 = let
v37 :: T_TypeSig_v37
v37 = \ (T_TypeSig_vIn37 ) -> ( let
_lhsOpp :: PP_Doc
_lhsOpp = rule45 arg_name_ arg_tp_
__result_ = T_TypeSig_vOut37 _lhsOpp
in __result_ )
in C_TypeSig_s38 v37
{-# INLINE rule45 #-}
{-# LINE 41 "./src-ag/AbstractSyntaxDump.ag" #-}
rule45 = \ name_ tp_ ->
{-# LINE 41 "./src-ag/AbstractSyntaxDump.ag" #-}
ppNestInfo ["TypeSig","TypeSig"] [pp name_, ppShow tp_] [] []
{-# LINE 1003 "dist/build/AbstractSyntaxDump.hs"#-}
-- TypeSigs ----------------------------------------------------
-- wrapper
data Inh_TypeSigs = Inh_TypeSigs { }
data Syn_TypeSigs = Syn_TypeSigs { pp_Syn_TypeSigs :: (PP_Doc), ppL_Syn_TypeSigs :: ([PP_Doc]) }
{-# INLINABLE wrap_TypeSigs #-}
wrap_TypeSigs :: T_TypeSigs -> Inh_TypeSigs -> (Syn_TypeSigs )
wrap_TypeSigs (T_TypeSigs act) (Inh_TypeSigs ) =
Control.Monad.Identity.runIdentity (
do sem <- act
let arg = T_TypeSigs_vIn40
(T_TypeSigs_vOut40 _lhsOpp _lhsOppL) <- return (inv_TypeSigs_s41 sem arg)
return (Syn_TypeSigs _lhsOpp _lhsOppL)
)
-- cata
{-# NOINLINE sem_TypeSigs #-}
sem_TypeSigs :: TypeSigs -> T_TypeSigs
sem_TypeSigs list = Prelude.foldr sem_TypeSigs_Cons sem_TypeSigs_Nil (Prelude.map sem_TypeSig list)
-- semantic domain
newtype T_TypeSigs = T_TypeSigs {
attach_T_TypeSigs :: Identity (T_TypeSigs_s41 )
}
newtype T_TypeSigs_s41 = C_TypeSigs_s41 {
inv_TypeSigs_s41 :: (T_TypeSigs_v40 )
}
data T_TypeSigs_s42 = C_TypeSigs_s42
type T_TypeSigs_v40 = (T_TypeSigs_vIn40 ) -> (T_TypeSigs_vOut40 )
data T_TypeSigs_vIn40 = T_TypeSigs_vIn40
data T_TypeSigs_vOut40 = T_TypeSigs_vOut40 (PP_Doc) ([PP_Doc])
{-# NOINLINE sem_TypeSigs_Cons #-}
sem_TypeSigs_Cons :: T_TypeSig -> T_TypeSigs -> T_TypeSigs
sem_TypeSigs_Cons arg_hd_ arg_tl_ = T_TypeSigs (return st41) where
{-# NOINLINE st41 #-}
st41 = let
v40 :: T_TypeSigs_v40
v40 = \ (T_TypeSigs_vIn40 ) -> ( let
_hdX38 = Control.Monad.Identity.runIdentity (attach_T_TypeSig (arg_hd_))
_tlX41 = Control.Monad.Identity.runIdentity (attach_T_TypeSigs (arg_tl_))
(T_TypeSig_vOut37 _hdIpp) = inv_TypeSig_s38 _hdX38 (T_TypeSig_vIn37 )
(T_TypeSigs_vOut40 _tlIpp _tlIppL) = inv_TypeSigs_s41 _tlX41 (T_TypeSigs_vIn40 )
_lhsOppL :: [PP_Doc]
_lhsOppL = rule46 _hdIpp _tlIppL
_lhsOpp :: PP_Doc
_lhsOpp = rule47 _hdIpp _tlIpp
__result_ = T_TypeSigs_vOut40 _lhsOpp _lhsOppL
in __result_ )
in C_TypeSigs_s41 v40
{-# INLINE rule46 #-}
{-# LINE 59 "./src-ag/AbstractSyntaxDump.ag" #-}
rule46 = \ ((_hdIpp) :: PP_Doc) ((_tlIppL) :: [PP_Doc]) ->
{-# LINE 59 "./src-ag/AbstractSyntaxDump.ag" #-}
_hdIpp : _tlIppL
{-# LINE 1058 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule47 #-}
rule47 = \ ((_hdIpp) :: PP_Doc) ((_tlIpp) :: PP_Doc) ->
_hdIpp >-< _tlIpp
{-# NOINLINE sem_TypeSigs_Nil #-}
sem_TypeSigs_Nil :: T_TypeSigs
sem_TypeSigs_Nil = T_TypeSigs (return st41) where
{-# NOINLINE st41 #-}
st41 = let
v40 :: T_TypeSigs_v40
v40 = \ (T_TypeSigs_vIn40 ) -> ( let
_lhsOppL :: [PP_Doc]
_lhsOppL = rule48 ()
_lhsOpp :: PP_Doc
_lhsOpp = rule49 ()
__result_ = T_TypeSigs_vOut40 _lhsOpp _lhsOppL
in __result_ )
in C_TypeSigs_s41 v40
{-# INLINE rule48 #-}
{-# LINE 60 "./src-ag/AbstractSyntaxDump.ag" #-}
rule48 = \ (_ :: ()) ->
{-# LINE 60 "./src-ag/AbstractSyntaxDump.ag" #-}
[]
{-# LINE 1081 "dist/build/AbstractSyntaxDump.hs"#-}
{-# INLINE rule49 #-}
rule49 = \ (_ :: ()) ->
empty
|
norm2782/uuagc
|
src-generated/AbstractSyntaxDump.hs
|
bsd-3-clause
| 50,986
| 14
| 26
| 15,962
| 9,910
| 5,504
| 4,406
| 825
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
import Prelude hiding (fail)
import Control.Concurrent
import qualified Control.Concurrent.Async as Async
import Control.Lens.Operators
import Control.Monad hiding (fail)
import Control.Monad.Catch
import Control.Monad.Fail
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Ref
import Data.Constraint.Extras
import Data.Constraint.Extras.TH
import Data.Dependent.Map (DMap)
import Data.Dependent.Sum (DSum(..), (==>))
import Data.Functor.Identity
import Data.Functor.Misc
import Data.GADT.Compare.TH
import Data.GADT.Show.TH
import Data.IORef (IORef)
import Data.List (sort)
import Data.Maybe
import Data.Proxy
import Data.Text (Text)
import Language.Javascript.JSaddle (syncPoint, liftJSM)
import Language.Javascript.JSaddle.Warp
import Network.HTTP.Types (status200)
import Network.Socket
import Network.Wai
import Network.WebSockets
import Reflex.Dom.Core
import Reflex.Dom.Widget.Input (dropdown)
import Reflex.Patch.DMapWithMove
import System.Directory
import System.Environment
import System.IO (stderr)
import System.IO.Silently
import System.IO.Temp
import System.Process
import System.Which (staticWhich)
import qualified Test.HUnit as HUnit
import qualified Test.Hspec as H
import qualified Test.Hspec.Core.Spec as H
import Test.Hspec (xit)
import Test.Hspec.WebDriver hiding (runWD, click, uploadFile, WD)
import qualified Test.Hspec.WebDriver as WD
import Test.WebDriver (WD(..))
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Dependent.Map as DMap
import qualified Data.IntMap as IntMap
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified GHCJS.DOM.File as File
import qualified Network.Wai.Handler.Warp as Warp
import qualified System.FilePath as FilePath
import qualified Test.WebDriver as WD
import qualified Test.WebDriver.Capabilities as WD
import Test.Util.ChromeFlags
import Test.Util.UnshareNetwork
-- ORPHAN: https://github.com/kallisti-dev/hs-webdriver/pull/167
deriving instance MonadMask WD
chromium :: FilePath
chromium = $(staticWhich "chromium")
seleniumPort, jsaddlePort :: PortNumber
seleniumPort = 8000
jsaddlePort = 8001
-- TODO Remove orphan
instance MonadRef WD where
type Ref WD = Ref IO
newRef = WD . newRef
readRef = WD . readRef
writeRef r = WD . writeRef r
assertEqual :: (MonadIO m, Eq a, Show a) => String -> a -> a -> m ()
assertEqual msg a b = liftIO $ HUnit.assertEqual msg a b
assertFailure :: MonadIO m => String -> m ()
assertFailure = liftIO . HUnit.assertFailure
assertBool :: (MonadIO m) => String -> Bool -> m ()
assertBool msg bool = liftIO $ HUnit.assertBool msg bool
chromeConfig :: Text -> [Text] -> WD.WDConfig
chromeConfig fp flags = WD.useBrowser (WD.chrome { WD.chromeBinary = Just $ T.unpack fp, WD.chromeOptions = T.unpack <$> flags }) WD.defaultConfig
keyMap :: DMap DKey Identity
keyMap = DMap.fromList
[ Key_Int ==> 0
, Key_Char ==> 'A'
]
data DKey a where
Key_Int :: DKey Int
Key_Char :: DKey Char
Key_Bool :: DKey Bool
textKey :: DKey a -> Text
textKey = \case
Key_Int -> "Key_Int"
Key_Char -> "Key_Char"
Key_Bool -> "Key_Bool"
deriveArgDict ''DKey
deriveGEq ''DKey
deriveGCompare ''DKey
deriveGShow ''DKey
deriving instance MonadFail WD
main :: IO ()
main = do
unshareNetwork
isHeadless <- (== Nothing) <$> lookupEnv "NO_HEADLESS"
withSandboxedChromeFlags isHeadless $ \chromeFlags -> do
withSeleniumServer $ \selenium -> do
let browserPath = T.strip $ T.pack chromium
when (T.null browserPath) $ fail "No browser found"
withDebugging <- isNothing <$> lookupEnv "NO_DEBUG"
let wdConfig = WD.defaultConfig { WD.wdPort = fromIntegral $ _selenium_portNumber selenium }
chromeCaps' = WD.getCaps $ chromeConfig browserPath chromeFlags
hspec (tests withDebugging wdConfig [chromeCaps'] selenium) `finally` _selenium_stopServer selenium
tests :: Bool -> WD.WDConfig -> [Capabilities] -> Selenium -> Spec
tests withDebugging wdConfig caps _selenium = do
let putStrLnDebug :: MonadIO m => Text -> m ()
putStrLnDebug m = when withDebugging $ liftIO $ putStrLn $ T.unpack m
session' = sessionWith wdConfig "" . using (map (,"") caps)
runWD m = runWDOptions (WdOptions False) $ do
putStrLnDebug "before"
r <- m
putStrLnDebug "after"
return r
testWidgetStatic :: WD b -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
testWidgetStatic = testWidgetStaticDebug withDebugging
testWidget :: WD () -> WD b -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
testWidget = testWidgetDebug withDebugging
testWidget' :: WD a -> (a -> WD b) -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
testWidget' = testWidgetDebug' withDebugging
describe "text" $ session' $ do
it "works" $ runWD $ do
testWidgetStatic (checkBodyText "hello world") $ do
text "hello world"
it "works with postBuild" $ runWD $ do
testWidgetStatic (checkBodyText "pb") $ do
pb <- getPostBuild
void $ textNode $ TextNodeConfig "" $ Just $ "pb" <$ pb
it "works for adjacent text nodes" $ runWD $ do
testWidgetStatic (checkBodyText "hello world") $ do
text "hello "
text "world"
it "works for empty adjacent text nodes" $ runWD $ do
testWidgetStatic (checkBodyText "hello world") $ do
pb <- getPostBuild
text ""
text ""
_ <- textNode $ TextNodeConfig "" $ Just $ "hello " <$ pb
_ <- textNode $ TextNodeConfig "abc" $ Just $ "" <$ pb
_ <- textNode $ TextNodeConfig "" $ Just $ "world" <$ pb
text ""
it "works when empty text nodes are the only children of an element" $ runWD $ do
testWidgetStatic (checkBodyText "hello world") $ do
el "div" $ do
text ""
text ""
text "hello world"
it "works when an empty text node is the first child before text" $ runWD $ do
testWidgetStatic (checkTextInTag "div" "hello world") $ do
el "div" $ do
text ""
text "hello world"
it "works when an empty text node is the first child before element" $ runWD $ do
testWidgetStatic (checkTextInTag "div" "hello world") $ do
el "div" $ do
text ""
el "span" $ text "hello world"
it "works when an empty text node is the last child" $ runWD $ do
testWidgetStatic (checkTextInTag "div" "hello world") $ do
el "div" $ do
el "span" $ text "hello world"
text ""
-- TODO I think these two tests are broken
-- it "updates after postBuild" $ runWD $ do
-- testWidget (checkBodyText "initial") (checkBodyText "after") $ do
-- after <- delay 0 =<< getPostBuild
-- void $ textNode $ TextNodeConfig "initial" $ Just $ "after" <$ after
-- it "updates immediately after postBuild" $ runWD $ do
-- testWidget (checkBodyText "pb") (checkBodyText "after") $ do
-- pb <- getPostBuild
-- after <- delay 0 pb
-- void $ textNode $ TextNodeConfig "initial" $ Just $ leftmost ["pb" <$ pb, "after" <$ after]
it "updates in immediate mode" $ runWD $ do
let checkUpdated = do
checkBodyText "initial"
WD.click =<< findElemWithRetry (WD.ByTag "button")
checkBodyText "after"
testWidget (pure ()) checkUpdated $ prerender_ (pure ()) $ do
click <- button ""
void $ textNode $ TextNodeConfig "initial" $ Just $ "after" <$ click
describe "element" $ session' $ do
it "works with domEvent Click" $ runWD $ do
clickedRef <- liftIO $ newRef False
testWidget' (findElemWithRetry $ WD.ByTag "div") WD.click $ do
(e, _) <- el' "div" $ text "hello world"
performEvent_ $ liftIO (writeRef clickedRef True) <$ domEvent Click e
readRef clickedRef `shouldBeWithRetryM` True
it "works with eventFlags stopPropagation" $ runWD $ do
firstClickedRef <- newRef False
secondClickedRef <- newRef False
let clickBoth = do
findElemWithRetry (WD.ById "first") >>= WD.click
findElemWithRetry (WD.ById "second") >>= WD.click
testWidget (pure ()) clickBoth $ do
(firstDivEl, _) <- el' "div" $ prerender_ (pure ()) $ do
void $ elAttr "span" ("id" =: "first") $ text "hello world"
performEvent_ $ liftIO (writeRef firstClickedRef True) <$ domEvent Click firstDivEl
(secondDivEl, _) <- el' "div" $ prerender_ (pure ()) $ do
let conf :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace
conf = (def :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace)
& initialAttributes .~ "id" =: "second"
& elementConfig_eventSpec .~ addEventSpecFlags (Proxy :: Proxy GhcjsDomSpace) Click (\_ -> stopPropagation) def
void $ element "span" conf $ text "hello world"
performEvent_ $ liftIO (writeRef secondClickedRef True) <$ domEvent Click secondDivEl
firstClicked <- readRef firstClickedRef
secondClicked <- readRef secondClickedRef
assertEqual "Click propagated when it should have stopped" (True, False) (firstClicked, secondClicked)
it "works with eventFlags preventDefault" $ runWD $ do
let click = do
e <- findElemWithRetry $ WD.ByTag "input"
s0 <- WD.isSelected e
WD.click e
s1 <- WD.isSelected e
pure (s0, s1)
clicked <- testWidget (pure ()) click $ prerender_ (pure ()) $ do
let conf :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace
conf = (def :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace)
& elementConfig_eventSpec .~ addEventSpecFlags (Proxy :: Proxy GhcjsDomSpace) Click (\_ -> preventDefault) def
& initialAttributes .~ "type" =: "checkbox"
void $ element "input" conf $ text "hello world"
assertEqual "Click not prevented" (False, False) clicked
it "can add/update/remove attributes" $ runWD $ do
let checkInitialAttrs = do
e <- findElemWithRetry $ WD.ByTag "div"
assertAttr e "const" (Just "const")
assertAttr e "delete" (Just "delete")
assertAttr e "init" (Just "init")
assertAttr e "click" Nothing
pure e
checkModifyAttrs e = do
WD.click e
withRetry $ do
assertAttr e "const" (Just "const")
assertAttr e "delete" Nothing
assertAttr e "init" (Just "click")
assertAttr e "click" (Just "click")
testWidget' checkInitialAttrs checkModifyAttrs $ mdo
let conf = def
& initialAttributes .~ "const" =: "const" <> "delete" =: "delete" <> "init" =: "init"
& modifyAttributes .~ (("delete" =: Nothing <> "init" =: Just "click" <> "click" =: Just "click") <$ click)
(e, ()) <- element "div" conf $ text "hello world"
let click = domEvent Click e
return ()
describe "inputElement" $ do
describe "hydration" $ session' $ do
it "doesn't wipe user input when switching over" $ runWD $ do
inputRef <- newRef ("" :: Text)
testWidget'
(do
e <- findElemWithRetry $ WD.ByTag "input"
WD.sendKeys "hello world" e
pure e)
(\e -> do
WD.attr e "value" `shouldBeWithRetryM` Just "hello world"
WD.click =<< findElemWithRetry (WD.ByTag "button")
readRef inputRef `shouldBeWithRetryM` "hello world"
) $ do
e <- inputElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "captures user input after switchover" $ runWD $ do
inputRef <- newRef ("" :: Text)
let checkValue = do
WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "input")
WD.click =<< findElemWithRetry (WD.ByTag "button")
readRef inputRef `shouldBeWithRetryM` "hello world"
testWidget (pure ()) checkValue $ do
e <- inputElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "input"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ do
e <- inputElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
it "sets focus when focus occurs before hydration" $ runWD $ do
focusRef <- newRef False
let setup = do
e <- findElemWithRetry $ WD.ByTag "input"
WD.click e
((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
readRef focusRef `shouldBeWithRetryM` False
check = readRef focusRef `shouldBeWithRetryM` True
testWidget setup check $ do
e <- inputElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
it "sets value appropriately" $ runWD $ do
valueByUIRef <- newRef ("" :: Text)
valueRef <- newRef ("" :: Text)
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
readRef valueByUIRef `shouldBeWithRetryM` ""
readRef valueRef `shouldBeWithRetryM` ""
e <- findElemWithRetry $ WD.ByTag "input"
WD.sendKeys "hello" e
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "hello"
liftIO $ writeChan setValueChan "world"
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "world"
testWidget (pure ()) checkValue $ do
update <- triggerEventWithChan setValueChan
e <- inputElement $ def & inputElementConfig_setValue .~ update
performEvent_ $ liftIO . writeRef valueByUIRef <$> _inputElement_input e
performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
it "sets checked appropriately" $ runWD $ do
checkedByUIRef <- newRef False
checkedRef <- newRef False
setCheckedChan <- liftIO newChan
let checkValue = do
readRef checkedByUIRef `shouldBeWithRetryM` False
readRef checkedRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "input"
WD.moveToCenter e
WD.click e
readRef checkedByUIRef `shouldBeWithRetryM` True
readRef checkedRef `shouldBeWithRetryM` True
liftIO $ writeChan setCheckedChan False
readRef checkedByUIRef `shouldBeWithRetryM` True
readRef checkedRef `shouldBeWithRetryM` False
testWidget (pure ()) checkValue $ do
setChecked <- triggerEventWithChan setCheckedChan
e <- inputElement $ def
& initialAttributes .~ "type" =: "checkbox"
& inputElementConfig_setChecked .~ setChecked
performEvent_ $ liftIO . writeRef checkedByUIRef <$> _inputElement_checkedChange e
performEvent_ $ liftIO . writeRef checkedRef <$> updated (_inputElement_checked e)
it "captures file uploads" $ runWD $ do
filesRef :: IORef [Text] <- newRef []
let uploadFile = do
e <- findElemWithRetry $ WD.ByTag "input"
path <- liftIO $ writeSystemTempFile "testFile" "file contents"
WD.sendKeys (T.pack path) e
WD.click =<< findElemWithRetry (WD.ByTag "button")
liftIO $ removeFile path
readRef filesRef `shouldBeWithRetryM` [T.pack $ FilePath.takeFileName path]
testWidget (pure ()) uploadFile $ do
e <- inputElement $ def & initialAttributes .~ "type" =: "file"
click <- button "save"
prerender_ (pure ()) $ performEvent_ $ ffor (tag (current (_inputElement_files e)) click) $ \fs -> do
names <- liftJSM $ traverse File.getName fs
liftIO $ writeRef filesRef names
describe "hydration/immediate" $ session' $ do
it "captures user input after switchover" $ runWD $ do
inputRef :: IORef Text <- newRef ""
let checkValue = do
WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "input")
WD.click =<< findElemWithRetry (WD.ByTag "button")
readRef inputRef `shouldBeWithRetryM` "hello world"
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
e <- inputElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "input"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
e <- inputElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
it "sets value appropriately" $ runWD $ do
valueByUIRef :: IORef Text <- newRef ""
valueRef :: IORef Text <- newRef ""
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
readRef valueByUIRef `shouldBeWithRetryM` ""
readRef valueRef `shouldBeWithRetryM` ""
e <- findElemWithRetry $ WD.ByTag "input"
WD.sendKeys "hello" e
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "hello"
liftIO $ writeChan setValueChan "world"
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "world"
testWidget (pure ()) checkValue $ do
update <- triggerEventWithChan setValueChan
prerender_ (pure ()) $ do
e <- inputElement $ def & inputElementConfig_setValue .~ update
performEvent_ $ liftIO . writeRef valueByUIRef <$> _inputElement_input e
performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
it "sets checked appropriately" $ runWD $ do
checkedByUIRef <- newRef False
checkedRef <- newRef False
setCheckedChan <- liftIO newChan
let checkValue = do
readRef checkedByUIRef `shouldBeWithRetryM` False
readRef checkedRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "input"
WD.moveToCenter e
WD.click e
readRef checkedByUIRef `shouldBeWithRetryM` True
readRef checkedRef `shouldBeWithRetryM` True
liftIO $ writeChan setCheckedChan False
readRef checkedByUIRef `shouldBeWithRetryM` True
readRef checkedRef `shouldBeWithRetryM` False
testWidget (pure ()) checkValue $ do
setChecked <- triggerEventWithChan setCheckedChan
prerender_ (pure ()) $ do
e <- inputElement $ def
& initialAttributes .~ "type" =: "checkbox"
& inputElementConfig_setChecked .~ setChecked
performEvent_ $ liftIO . writeRef checkedByUIRef <$> _inputElement_checkedChange e
performEvent_ $ liftIO . writeRef checkedRef <$> updated (_inputElement_checked e)
it "captures file uploads" $ runWD $ do
filesRef :: IORef [Text] <- newRef []
let uploadFile = do
e <- findElemWithRetry $ WD.ByTag "input"
path <- liftIO $ writeSystemTempFile "testFile" "file contents"
WD.sendKeys (T.pack path) e
WD.click =<< findElemWithRetry (WD.ByTag "button")
liftIO $ removeFile path
readRef filesRef `shouldBeWithRetryM` [T.pack $ FilePath.takeFileName path]
testWidget (pure ()) uploadFile $ prerender_ (pure ()) $ do
e <- inputElement $ def & initialAttributes .~ "type" =: "file"
click <- button "save"
performEvent_ $ ffor (tag (current (_inputElement_files e)) click) $ \fs -> do
names <- liftJSM $ traverse File.getName fs
liftIO $ writeRef filesRef names
describe "textAreaElement" $ do
describe "hydration" $ session' $ do
it "doesn't wipe user input when switching over" $ runWD $ do
inputRef <- newRef ("" :: Text)
testWidget'
(do
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.sendKeys "hello world" e
pure e)
(\e -> do
WD.attr e "value" `shouldBeWithRetryM` Just "hello world"
WD.click <=< findElemWithRetry $ WD.ByTag "button"
readRef inputRef `shouldBeWithRetryM` "hello world"
) $ do
e <- textAreaElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "captures user input after switchover" $ runWD $ do
inputRef <- newRef ("" :: Text)
let checkValue = do
WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "textarea")
WD.click =<< findElemWithRetry (WD.ByTag "button")
readRef inputRef `shouldBeWithRetryM` "hello world"
testWidget (pure ()) checkValue $ do
e <- textAreaElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ do
e <- textAreaElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
it "sets focus when focus occurs before hydration" $ runWD $ do
focusRef <- newRef False
let setup = do
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.click e
((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
readRef focusRef `shouldBeWithRetryM` False
check = readRef focusRef `shouldBeWithRetryM` True
testWidget setup check $ do
e <- textAreaElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
it "sets value appropriately" $ runWD $ do
valueByUIRef <- newRef ("" :: Text)
valueRef <- newRef ("" :: Text)
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
readRef valueByUIRef `shouldBeWithRetryM` ""
readRef valueRef `shouldBeWithRetryM` ""
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.sendKeys "hello" e
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "hello"
liftIO $ writeChan setValueChan "world"
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "world"
testWidget (pure ()) checkValue $ do
setValue' <- triggerEventWithChan setValueChan
e <- textAreaElement $ def { _textAreaElementConfig_setValue = Just setValue' }
performEvent_ $ liftIO . writeRef valueByUIRef <$> _textAreaElement_input e
performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
describe "hydration/immediate" $ session' $ do
it "captures user input after switchover" $ runWD $ do
inputRef :: IORef Text <- newRef ""
let checkValue = do
WD.sendKeys "hello world" <=< findElemWithRetry $ WD.ByTag "textarea"
WD.click <=< findElemWithRetry $ WD.ByTag "button"
readRef inputRef `shouldBeWithRetryM` "hello world"
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
e <- textAreaElement def
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
e <- textAreaElement def
performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
it "sets value appropriately" $ runWD $ do
valueByUIRef :: IORef Text <- newRef ""
valueRef :: IORef Text <- newRef ""
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
readRef valueByUIRef `shouldBeWithRetryM` ""
readRef valueRef `shouldBeWithRetryM` ""
e <- findElemWithRetry $ WD.ByTag "textarea"
WD.sendKeys "hello" e
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "hello"
liftIO $ writeChan setValueChan "world"
readRef valueByUIRef `shouldBeWithRetryM` "hello"
readRef valueRef `shouldBeWithRetryM` "world"
testWidget (pure ()) checkValue $ do
setValue' <- triggerEventWithChan setValueChan
prerender_ (pure ()) $ do
e <- textAreaElement $ def { _textAreaElementConfig_setValue = Just setValue' }
performEvent_ $ liftIO . writeRef valueByUIRef <$> _textAreaElement_input e
performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
describe "selectElement" $ do
let options :: DomBuilder t m => m ()
options = do
elAttr "option" ("value" =: "one" <> "id" =: "one") $ text "one"
elAttr "option" ("value" =: "two" <> "id" =: "two") $ text "two"
elAttr "option" ("value" =: "three" <> "id" =: "three") $ text "three"
describe "hydration" $ session' $ do
it "sets initial value correctly" $ runWD $ do
inputRef <- newRef ("" :: Text)
let setup = do
e <- findElemWithRetry $ WD.ByTag "select"
assertAttr e "value" (Just "three")
WD.click =<< findElemWithRetry (WD.ById "two")
pure e
check e = do
assertAttr e "value" (Just "two")
readRef inputRef `shouldBeWithRetryM` "three"
WD.click =<< findElemWithRetry (WD.ByTag "button")
assertAttr e "value" (Just "two")
readRef inputRef `shouldBeWithRetryM` "two"
testWidget' setup check $ do
(e, ()) <- selectElement (def { _selectElementConfig_initialValue = "three" }) options
click <- button "save"
liftIO . writeRef inputRef <=< sample $ current $ _selectElement_value e
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
it "captures user input after switchover" $ runWD $ do
inputRef <- newRef ("" :: Text)
let checkValue = do
e <- findElemWithRetry $ WD.ByTag "select"
assertAttr e "value" (Just "one")
WD.click =<< findElemWithRetry (WD.ById "two")
assertAttr e "value" (Just "two")
WD.click =<< findElemWithRetry (WD.ByTag "button")
readRef inputRef `shouldBeWithRetryM` "two"
testWidget (pure ()) checkValue $ do
(e, ()) <- selectElement def options
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "select"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ do
(e, ()) <- selectElement def options
performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
it "sets focus when focus occurs before hydration" $ runWD $ do
focusRef <- newRef False
let setup = do
e <- findElemWithRetry $ WD.ByTag "select"
WD.click e
((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
readRef focusRef `shouldBeWithRetryM` False
check = readRef focusRef `shouldBeWithRetryM` True
testWidget setup check $ do
(e, ()) <- selectElement def options
performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
it "sets value appropriately" $ runWD $ do
valueByUIRef <- newRef ("" :: Text)
valueRef <- newRef ("" :: Text)
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
e <- findElemWithRetry $ WD.ByTag "select"
assertAttr e "value" (Just "one")
readRef valueByUIRef `shouldBeWithRetryM` "one"
readRef valueRef `shouldBeWithRetryM` "one"
WD.click <=< findElemWithRetry $ WD.ById "two"
readRef valueByUIRef `shouldBeWithRetryM` "two"
readRef valueRef `shouldBeWithRetryM` "two"
liftIO $ writeChan setValueChan "three"
readRef valueByUIRef `shouldBeWithRetryM` "two"
readRef valueRef `shouldBeWithRetryM` "three"
testWidget (pure ()) checkValue $ do
setValue' <- triggerEventWithChan setValueChan
(e, ()) <- selectElement def { _selectElementConfig_setValue = Just setValue' } options
performEvent_ $ liftIO . writeRef valueByUIRef <$> _selectElement_change e
performEvent_ $ liftIO . writeRef valueRef <$> updated (_selectElement_value e)
describe "hydration/immediate" $ session' $ do
it "captures user input after switchover" $ runWD $ do
inputRef :: IORef Text <- newRef ""
let checkValue = do
WD.click <=< findElemWithRetry $ WD.ById "two"
WD.click <=< findElemWithRetry $ WD.ByTag "button"
readRef inputRef `shouldBeWithRetryM` "two"
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
(e, ()) <- selectElement def options
click <- button "save"
performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
it "sets focus appropriately" $ runWD $ do
focusRef <- newRef False
let checkValue = do
readRef focusRef `shouldBeWithRetryM` False
e <- findElemWithRetry $ WD.ByTag "select"
WD.click e
readRef focusRef `shouldBeWithRetryM` True
testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
(e, ()) <- selectElement def options
performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
it "has correct initial value" $ runWD $ do
valueRef :: IORef Text <- newRef ""
let checkValue = readRef valueRef `shouldBeWithRetryM` "one"
testWidget (pure ()) checkValue $ do
prerender_ (pure ()) $ do
(e, ()) <- selectElement def { _selectElementConfig_initialValue = "one" } options
liftIO . writeRef valueRef <=< sample $ current $ _selectElement_value e
it "sets value appropriately" $ runWD $ do
valueByUIRef :: IORef Text <- newRef ""
valueRef :: IORef Text <- newRef ""
setValueChan :: Chan Text <- liftIO newChan
let checkValue = do
WD.click =<< findElemWithRetry (WD.ById "two")
readRef valueByUIRef `shouldBeWithRetryM` "two"
readRef valueRef `shouldBeWithRetryM` "two"
liftIO $ writeChan setValueChan "three"
readRef valueByUIRef `shouldBeWithRetryM` "two"
readRef valueRef `shouldBeWithRetryM` "three"
testWidget (pure ()) checkValue $ do
setValue' <- triggerEventWithChan setValueChan
prerender_ (pure ()) $ do
(e, ()) <- selectElement def { _selectElementConfig_setValue = Just setValue' } options
performEvent_ $ liftIO . writeRef valueByUIRef <$> _selectElement_change e
performEvent_ $ liftIO . writeRef valueRef <$> updated (_selectElement_value e)
describe "prerender" $ session' $ do
it "works in simple case" $ runWD $ do
testWidget (checkBodyText "One") (checkBodyText "Two") $ do
prerender_ (text "One") (text "Two")
it "removes element correctly" $ runWD $ do
testWidget' (findElemWithRetry $ WD.ByTag "span") elementShouldBeRemoved $ do
prerender_ (el "span" $ text "One") (text "Two")
it "can be nested in server widget" $ runWD $ do
testWidget (checkBodyText "One") (checkBodyText "Three") $ do
prerender_ (prerender_ (text "One") (text "Two")) (text "Three")
it "can be nested in client widget" $ runWD $ do
testWidget (checkBodyText "One") (checkBodyText "Three") $ do
prerender_ (text "One") (prerender_ (text "Two") (text "Three"))
it "works with prerender_ siblings" $ runWD $ do
testWidget
(checkTextInId "a1" "One" >> checkTextInId "b1" "Three" >> checkTextInId "c1" "Five")
(checkTextInId "a2" "Two" >> checkTextInId "b2" "Four" >> checkTextInId "c2" "Six") $ do
prerender_ (divId "a1" $ text "One") (divId "a2" $ text "Two")
prerender_ (divId "b1" $ text "Three") (divId "b2" $ text "Four")
prerender_ (divId "c1" $ text "Five") (divId "c2" $ text "Six")
it "works inside other element" $ runWD $ do
testWidget (checkTextInTag "div" "One") (checkTextInTag "div" "Two") $ do
el "div" $ prerender_ (text "One") (text "Two")
-- TODO re-enable this
-- it "places fences and removes them" $ runWD $ do
-- testWidget'
-- (do
-- scripts <- WD.findElems $ WD.ByTag "script"
-- filterM (\s -> maybe False (\t -> "prerender" `T.isPrefixOf` t) <$> WD.attr s "type") scripts
-- )
-- (traverse_ elementShouldBeRemoved)
-- (el "span" $ prerender_ (text "One") (text "Two"))
it "postBuild works on server side" $ runWD $ do
lock :: MVar () <- liftIO newEmptyMVar
testWidget (liftIO $ takeMVar lock) (pure ()) $ do
prerender_ (do
pb <- getPostBuild
performEvent_ $ liftIO (putMVar lock ()) <$ pb) blank
it "postBuild works on client side" $ runWD $ do
lock :: MVar () <- liftIO newEmptyMVar
testWidget (pure ()) (liftIO $ takeMVar lock) $ do
prerender_ blank $ do
pb <- getPostBuild
performEvent_ $ liftIO (putMVar lock ()) <$ pb
it "result Dynamic is updated *after* switchover" $ runWD $ do
let preSwitchover = checkBodyText "PostBuild"
check = checkBodyText "Client"
testWidget preSwitchover check $ void $ do
d <- prerender (pure "Initial") (pure "Client")
pb <- getPostBuild
initial <- sample $ current d
textNode $ TextNodeConfig initial $ Just $ leftmost [updated d, "PostBuild" <$ pb]
-- This essentially checks that the client IO runs *after* switchover/postBuild,
-- thus can't create conflicting DOM
it "can't exploit IO to break hydration" $ runWD $ do
let preSwitchover = checkBodyText "Initial"
testWidgetStatic preSwitchover $ void $ do
ref <- liftIO $ newRef "Initial"
prerender_ (pure ()) (liftIO $ writeRef ref "Client")
text <=< liftIO $ readRef ref
-- As above, so below
it "can't exploit triggerEvent to break hydration" $ runWD $ do
let preSwitchover = checkBodyText "Initial"
check = checkBodyText "Client"
testWidget preSwitchover check $ void $ do
(e, trigger) <- newTriggerEvent
prerender_ (pure ()) (liftIO $ trigger "Client")
textNode $ TextNodeConfig "Initial" $ Just e
describe "namespaces" $ session' $ do
it "dyn can be nested in namespaced widget" $ runWD $ do
testWidget (pure ()) (checkTextInTag "svg" "one") $ do
let svgRootCfg = def
& (elementConfig_namespace ?~ "http://www.w3.org/2000/svg")
& (elementConfig_initialAttributes .~ ("width" =: "100%" <> "height" =: "100%" <> "viewBox" =: "0 0 1536 2048"))
void $ element "svg" svgRootCfg $ do
dyn_ $ text "one" <$ pure ()
describe "runWithReplace" $ session' $ do
it "works" $ runWD $ do
replaceChan :: Chan Text <- liftIO newChan
let setup = findElemWithRetry $ WD.ByTag "div"
check ssr = do
-- Check that the original element still exists and has the correct text
shouldContainText "two" ssr
liftIO $ writeChan replaceChan "three"
elementShouldBeRemoved ssr
shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
testWidget' setup check $ do
replace <- triggerEventWithChan replaceChan
pb <- getPostBuild
void $ runWithReplace (el "div" $ text "one") $ leftmost
[ el "div" (text "two") <$ pb
, el "span" . text <$> replace
]
it "can be nested in initial widget" $ runWD $ do
replaceChan :: Chan Text <- liftIO newChan
let setup = findElemWithRetry $ WD.ByTag "div"
check ssr = do
-- Check that the original element still exists and has the correct text
shouldContainText "two" ssr
liftIO $ writeChan replaceChan "three"
elementShouldBeRemoved ssr
shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
testWidget' setup check $ void $ flip runWithReplace never $ do
replace <- triggerEventWithChan replaceChan
pb <- getPostBuild
void $ runWithReplace (el "div" $ text "one") $ leftmost
[ el "div" (text "two") <$ pb
, el "span" . text <$> replace
]
it "can be nested in postBuild widget" $ runWD $ do
replaceChan :: Chan Text <- liftIO newChan
let setup = findElemWithRetry $ WD.ByTag "div"
check ssr = do
-- Check that the original element still exists and has the correct text
shouldContainText "two" ssr
liftIO $ writeChan replaceChan "three"
elementShouldBeRemoved ssr
shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
testWidget' setup check $ void $ do
pb <- getPostBuild
runWithReplace (pure ()) $ ffor pb $ \() -> do
replace <- triggerEventWithChan replaceChan
pb' <- getPostBuild
void $ runWithReplace (el "div" $ text "one") $ leftmost
[ el "div" (text "two") <$ pb'
, el "span" . text <$> replace
]
it "postBuild works in replaced widget" $ runWD $ do
replaceChan <- liftIO newChan
pbLock <- liftIO newEmptyMVar
let check = liftIO $ do
writeChan replaceChan ()
takeMVar pbLock
testWidget (pure ()) check $ void $ do
replace <- triggerEventWithChan replaceChan
runWithReplace (pure ()) $ ffor replace $ \() -> do
pb <- getPostBuild
performEvent_ $ liftIO (putMVar pbLock ()) <$ pb
it "can be nested in event widget" $ runWD $ do
replaceChan1 :: Chan Text <- liftIO newChan
replaceChan2 :: Chan Text <- liftIO newChan
lock :: MVar () <- liftIO newEmptyMVar
let check = do
shouldContainText "" =<< findElemWithRetry (WD.ByTag "body")
liftIO $ do
writeChan replaceChan1 "one"
takeMVar lock
one <- findElemWithRetry $ WD.ByTag "div"
shouldContainText "pb" one
liftIO $ writeChan replaceChan2 "two"
elementShouldBeRemoved one
shouldContainText "two" =<< findElemWithRetry (WD.ByTag "span")
testWidget (pure ()) check $ void $ do
replace1 <- triggerEventWithChan replaceChan1
runWithReplace (pure ()) $ ffor replace1 $ \r1 -> do
replace2 <- triggerEventWithChan replaceChan2
pb <- getPostBuild
performEvent_ $ liftIO (putMVar lock ()) <$ pb
void $ runWithReplace (el "div" $ text r1) $ leftmost
[ el "span" . text <$> replace2
, el "div" (text "pb") <$ pb
]
it "prerender works in replaced widget" $ runWD $ do
replaceChan <- liftIO newChan
lock :: MVar () <- liftIO newEmptyMVar
pbLock :: MVar () <- liftIO newEmptyMVar
let check = do
liftIO $ do
writeChan replaceChan ()
takeMVar lock
takeMVar pbLock
testWidget (pure ()) check $ void $ do
replace <- triggerEventWithChan replaceChan
runWithReplace (pure ()) $ ffor replace $ \() -> do
prerender_ (pure ()) $ do
liftIO $ putMVar lock ()
pb <- getPostBuild
performEvent_ $ liftIO (putMVar pbLock ()) <$ pb
it "prerender returns in immediate mode" $ runWD $ do
replaceChan <- liftIO newChan
pbLock <- liftIO newEmptyMVar
let check = liftIO $ do
writeChan replaceChan ()
takeMVar pbLock
testWidget (pure ()) check $ void $ do
replace <- triggerEventWithChan replaceChan
runWithReplace (pure ()) $ ffor replace $ \() -> do
prerender_ (pure ()) (pure ())
liftIO $ putMVar pbLock ()
it "works in immediate mode (RHS of prerender)" $ runWD $ do
replaceChan :: Chan Text <- liftIO newChan
let check = do
checkBodyText "one"
one <- findElemWithRetry $ WD.ByTag "div"
shouldContainText "one" one
liftIO $ writeChan replaceChan "pb"
elementShouldBeRemoved one
shouldContainText "pb" =<< findElemWithRetry (WD.ByTag "span")
testWidget (pure ()) check $ void $ do
replace <- triggerEventWithChan replaceChan
prerender_ blank $ do
void $ runWithReplace (el "div" $ text "one") $ el "span" . text <$> replace
it "works with postBuild in immediate mode (RHS of prerender)" $ runWD $ do
replaceChan :: Chan Text <- liftIO newChan
let check = do
checkBodyText "two"
two <- findElemWithRetry $ WD.ByTag "div"
shouldContainText "two" two
liftIO $ writeChan replaceChan "three"
elementShouldBeRemoved two
shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
testWidget (pure ()) check $ void $ do
replace <- triggerEventWithChan replaceChan
prerender_ blank $ do
pb <- getPostBuild
void $ runWithReplace (el "div" $ text "one") $ leftmost
[ el "div" (text "two") <$ pb
, el "span" . text <$> replace
]
let checkInnerHtml t x = findElemWithRetry (WD.ByTag t) >>= (`attr` "innerHTML") >>= (`shouldBe` Just x)
it "removes bracketing comments" $ runWD $ do
replaceChan :: Chan () <- liftIO newChan
let
preSwitchover = checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0-->|after"
check () = do
liftIO $ writeChan replaceChan () -- trigger creation of p tag
_ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
checkInnerHtml "div" "before|<p>inner2</p>|after"
testWidget' preSwitchover check $ do
replace <- triggerEventWithChan replaceChan
el "div" $ do
text "before|"
_ <- runWithReplace (text "inner1") $ el "p" (text "inner2") <$ replace
text "|after"
it "ignores extra ending bracketing comment" $ runWD $ do
replaceChan :: Chan () <- liftIO newChan
let
preSwitchover = checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0--><!--replace-end-0-->|after"
check () = do
liftIO $ writeChan replaceChan () -- trigger creation of p tag
_ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
checkInnerHtml "div" "before|inner2|after"
testWidget' preSwitchover check $ do
replace <- triggerEventWithChan replaceChan
el "div" $ do
text "before|"
_ <- runWithReplace (text "inner1" *> comment "replace-end-0") $ text "inner2" <$ replace
text "|after"
void $ runWithReplace blank $ el "p" blank <$ replace -- Signal tag for end of test
it "ignores missing ending bracketing comments" $ runWD $ do
replaceChan :: Chan () <- liftIO newChan
let
preSwitchover = do
checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0-->|after"
divEl <- findElemWithRetry (WD.ByTag "div")
let wrongHtml = "<!--replace-start-0-->inner1"
actualHtml :: String <- WD.executeJS
[WD.JSArg divEl, WD.JSArg wrongHtml]
"arguments[0].innerHTML = arguments[1]; return arguments[0].innerHTML"
actualHtml `shouldBe` wrongHtml
check () = do
liftIO $ writeChan replaceChan () -- trigger creation of p tag
_ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
checkInnerHtml "div" "before|<p>inner2</p>|after"
testWidget' preSwitchover check $ do
replace <- triggerEventWithChan replaceChan
el "div" $ do
text "before|"
_ <- runWithReplace (text "inner1") $ el "p" (text "inner2") <$ replace
text "|after"
describe "traverseDMapWithKeyWithAdjust" $ session' $ do
let widget :: DomBuilder t m => DKey a -> Identity a -> m (Identity a)
widget k (Identity v) = elAttr "li" ("id" =: textKey k) $ do
elClass "span" "key" $ text $ textKey k
elClass "span" "value" $ text $ T.pack $ has @Show k $ show v
pure (Identity v)
checkItem :: WD.Element -> Text -> Text -> WD ()
checkItem li k v = do
putStrLnDebug "checkItem"
shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
checkInitialItems dm xs = do
putStrLnDebug "checkInitialItems"
liftIO $ assertEqual "Wrong amount of items in DOM" (DMap.size dm) (length xs)
forM_ (zip xs (DMap.toList dm)) $ \(e, k :=> Identity v) -> checkItem e (textKey k) (T.pack $ has @Show k $ show v)
getAndCheckInitialItems dm = withRetry $ do
putStrLnDebug "getAndCheckInitialItems"
xs <- WD.findElems (WD.ByTag "li")
checkInitialItems dm xs
pure xs
checkRemoval chan k = do
putStrLnDebug "checkRemoval"
e <- findElemWithRetry (WD.ById $ textKey k)
liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe Nothing)
elementShouldBeRemoved e
checkReplace chan k v = do
putStrLnDebug "checkReplace"
e <- findElemWithRetry (WD.ById $ textKey k)
liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe $ Just $ Identity v)
elementShouldBeRemoved e
e' <- findElemWithRetry $ WD.ById $ textKey k
checkItem e' (textKey k) (T.pack $ show v)
checkInsert chan k v = do
putStrLnDebug "checkInsert"
liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe $ Just $ Identity v)
e <- findElemWithRetry (WD.ById $ textKey k)
checkItem e (textKey k) (T.pack $ show v)
postBuildPatch = PatchDMap $ DMap.fromList [Key_Char :=> ComposeMaybe Nothing, Key_Bool :=> ComposeMaybe (Just $ Identity True)]
it "doesn't replace elements at switchover, can delete/update/insert" $ runWD $ do
chan <- liftIO newChan
let preSwitchover :: WD [WD.Element]
preSwitchover = getAndCheckInitialItems keyMap
check :: [WD.Element] -> WD ()
check xs = do
checkInitialItems keyMap xs
checkRemoval chan Key_Int
checkReplace chan Key_Char 'B'
checkInsert chan Key_Bool True
testWidget' preSwitchover check $ do
(dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap =<< triggerEventWithChan chan
liftIO $ dmap `H.shouldBe` keyMap
it "handles postBuild correctly" $ runWD $ do
chan <- liftIO newChan
let preSwitchover = getAndCheckInitialItems $ applyAlways postBuildPatch keyMap
check xs = do
withRetry $ checkInitialItems (applyAlways postBuildPatch keyMap) xs
checkRemoval chan Key_Int
checkInsert chan Key_Char 'B'
checkReplace chan Key_Bool True
testWidget' preSwitchover check $ void $ do
pb <- getPostBuild
replace <- triggerEventWithChan chan
(dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap $ leftmost [postBuildPatch <$ pb, replace]
liftIO $ dmap `H.shouldBe` keyMap
it "can delete/update/insert when built in prerender" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems keyMap
checkRemoval chan Key_Int
checkReplace chan Key_Char 'B'
checkInsert chan Key_Bool True
testWidget (pure ()) check $ do
replace <- triggerEventWithChan chan
prerender_ (pure ()) $ do
(dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap replace
liftIO $ dmap `H.shouldBe` keyMap
it "can delete/update/insert when built in immediate mode" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems keyMap
checkRemoval chan Key_Int
checkReplace chan Key_Char 'B'
checkInsert chan Key_Bool True
testWidget (pure ()) check $ void $ do
pb <- getPostBuild
runWithReplace (pure ()) $ ffor pb $ \() -> void $ do
(dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap =<< triggerEventWithChan chan
liftIO $ dmap `H.shouldBe` keyMap
-- Should be fixed by prerender changes!
it "handles postBuild correctly in prerender" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems $ applyAlways postBuildPatch keyMap
checkRemoval chan Key_Int
checkInsert chan Key_Char 'B'
checkReplace chan Key_Bool True
testWidget (pure ()) check $ do
replace <- triggerEventWithChan chan
prerender_ (pure ()) $ void $ do
pb <- getPostBuild
(dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap $ leftmost [postBuildPatch <$ pb, replace]
liftIO $ dmap `H.shouldBe` keyMap
describe "traverseIntMapWithKeyWithAdjust" $ session' $ do
let textKeyInt k = "key" <> T.pack (show k)
intMap = IntMap.fromList
[ (1, "one")
, (2, "two")
, (3, "three")
]
let widget :: DomBuilder t m => IntMap.Key -> Text -> m Text
widget k v = elAttr "li" ("id" =: textKeyInt k) $ do
elClass "span" "key" $ text $ textKeyInt k
elClass "span" "value" $ text v
pure v
checkItem :: WD.Element -> Text -> Text -> WD ()
checkItem li k v = do
putStrLnDebug "checkItem"
shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
checkInitialItems dm xs = do
putStrLnDebug "checkInitialItems"
liftIO $ assertEqual "Wrong amount of items in DOM" (IntMap.size dm) (length xs)
forM_ (zip xs (IntMap.toList dm)) $ \(e, (k, v)) -> checkItem e (textKeyInt k) v
getAndCheckInitialItems dm = withRetry $ do
putStrLnDebug "getAndCheckInitialItems"
xs <- WD.findElems (WD.ByTag "li")
checkInitialItems dm xs
pure xs
checkRemoval chan k = do
putStrLnDebug "checkRemoval"
e <- findElemWithRetry (WD.ById $ textKeyInt k)
liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k Nothing
elementShouldBeRemoved e
checkReplace chan k v = do
putStrLnDebug "checkReplace"
e <- findElemWithRetry (WD.ById $ textKeyInt k)
liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k $ Just v
elementShouldBeRemoved e
e' <- findElemWithRetry (WD.ById $ textKeyInt k)
withRetry $ checkItem e' (textKeyInt k) v
checkInsert chan k v = do
putStrLnDebug "checkInsert"
liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k $ Just v
e <- findElemWithRetry (WD.ById $ textKeyInt k)
checkItem e (textKeyInt k) v
postBuildPatch = PatchIntMap $ IntMap.fromList [(2, Nothing), (3, Just "trois"), (4, Just "four")]
xit "doesn't replace elements at switchover, can delete/update/insert" $ runWD $ do
chan <- liftIO newChan
let preSwitchover = getAndCheckInitialItems intMap
check xs = do
checkInitialItems intMap xs
checkRemoval chan 1
checkReplace chan 2 "deux"
checkInsert chan 4 "four"
testWidget' preSwitchover check $ void $ do
(im, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap =<< triggerEventWithChan chan
liftIO $ im `H.shouldBe` intMap
xit "handles postBuild correctly" $ runWD $ do
chan <- liftIO newChan
let preSwitchover = getAndCheckInitialItems $ applyAlways postBuildPatch intMap
check xs = do
withRetry $ checkInitialItems (applyAlways postBuildPatch intMap) xs
checkRemoval chan 1
checkInsert chan 2 "deux"
checkReplace chan 3 "trois"
testWidget' preSwitchover check $ void $ do
pb <- getPostBuild
replace <- triggerEventWithChan chan
(dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap $ leftmost [postBuildPatch <$ pb, replace]
liftIO $ dmap `H.shouldBe` intMap
xit "can delete/update/insert when built in prerender" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems intMap
checkRemoval chan 1
checkReplace chan 2 "deux"
checkInsert chan 4 "quatre"
testWidget (pure ()) check $ do
replace <- triggerEventWithChan chan
prerender_ (pure ()) $ do
(dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap replace
liftIO $ dmap `H.shouldBe` intMap
xit "can delete/update/insert when built in immediate mode" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems intMap
checkRemoval chan 1
checkReplace chan 2 "deux"
checkInsert chan 4 "quatre"
testWidget (pure ()) check $ void $ do
pb <- getPostBuild
runWithReplace (pure ()) $ ffor pb $ \() -> void $ do
(dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap =<< triggerEventWithChan chan
liftIO $ dmap `H.shouldBe` intMap
-- Should be fixed by prerender changes!
xit "handles postBuild correctly in prerender" $ runWD $ do
chan <- liftIO newChan
let check = do
_ <- getAndCheckInitialItems $ applyAlways postBuildPatch intMap
checkRemoval chan 1
checkInsert chan 2 "deux"
checkReplace chan 3 "trois"
testWidget (pure ()) check $ do
replace <- triggerEventWithChan chan
prerender_ (pure ()) $ void $ do
pb <- getPostBuild
(dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap $ leftmost [postBuildPatch <$ pb, replace]
liftIO $ dmap `H.shouldBe` intMap
describe "traverseDMapWithKeyWithAdjustWithMove" $ session' $ do
let widget :: DomBuilder t m => Key2 a -> Identity a -> m (Identity a)
widget k (Identity v) = elAttr "li" ("id" =: textKey2 k) $ do
elClass "span" "key" $ text $ textKey2 k
elClass "span" "value" $ text $ T.pack $ has @Show k $ show v
pure (Identity v)
textKey2 :: Key2 a -> Text
textKey2 = \case
Key2_Int i -> "i" <> T.pack (show i)
Key2_Char c -> "c" <> T.pack [c]
checkItem :: WD.Element -> Text -> Text -> WD ()
checkItem li k v = do
shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
checkInitialItems dm xs = do
liftIO $ assertEqual "Wrong amount of items in DOM" (DMap.size dm) (length xs)
forM_ (zip xs (DMap.toList dm)) $ \(e, k :=> Identity v) -> checkItem e (textKey2 k) (T.pack $ has @Show k $ show v)
getAndCheckInitialItems dm = withRetry $ do
xs <- WD.findElems (WD.ByTag "li")
checkInitialItems dm xs
pure xs
moveSpec
:: (DMap Key2 Identity -> (WD.Element -> Chan (PatchDMapWithMove Key2 Identity) -> WD ()) -> WD ())
-> H.SpecM (WdTestSession ()) ()
moveSpec testMove = do
it "can insert an item" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 3 ==> 3]) $ \body chan -> do
shouldContainText (T.strip $ T.unlines ["i11","i33"]) body
liftIO $ writeChan chan (insertDMapKey (Key2_Int 2) 2)
shouldContainText (T.strip $ T.unlines ["i11","i22","i33"]) body
it "can delete an item" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3]) $ \body chan -> do
shouldContainText (T.strip $ T.unlines ["i11","i22","i33"]) body
liftIO $ writeChan chan (deleteDMapKey (Key2_Int 2))
shouldContainText (T.strip $ T.unlines ["i11","i33"]) body
it "can swap items" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3, Key2_Int 4 ==> 4]) $ \body chan -> do
shouldContainText (T.strip $ T.unlines ["i11","i22","i33","i44"]) body
liftIO $ writeChan chan (swapDMapKey (Key2_Int 2) (Key2_Int 3))
shouldContainText (T.strip $ T.unlines ["i11","i33","i22","i44"]) body
-- TODO re-enable this
-- it "can move items" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3, Key2_Int 4 ==> 4]) $ \body chan -> do
-- shouldContainText (T.strip $ T.unlines ["i11","i22","i33", "i44"]) body
-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3))
-- shouldContainText (T.strip $ T.unlines ["i11","i22","i44"]) body
-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3)) -- attempt a move to nonexistent key should delete
-- shouldContainText (T.strip $ T.unlines ["i11","i44"]) body
-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3)) -- this causes a JSException in immediate builder too
-- shouldContainText (T.strip $ T.unlines ["i11","i44"]) body
-- liftIO $ writeChan chan (insertDMapKey (Key2_Int 2) 2) -- this step will fail if the above caused an exception, thus works as a proxy for detecting the exception given we can't catch it
-- shouldContainText (T.strip $ T.unlines ["i11","i22","i44"]) body
describe "hydration" $ moveSpec $ \initMap test -> do
chan <- liftIO newChan
let preSwitchover = getAndCheckInitialItems initMap
check xs = do
checkInitialItems initMap xs
body <- getBody
test body chan
testWidget' preSwitchover check $ void $ do
(dmap, _evt) <- traverseDMapWithKeyWithAdjustWithMove widget initMap =<< triggerEventWithChan chan
liftIO $ assertEqual "DMap" initMap dmap
describe "hydration/immediate" $ moveSpec $ \initMap test -> do
chan <- liftIO newChan
replace <- liftIO newChan
lock :: MVar () <- liftIO newEmptyMVar
let check = do
liftIO $ do
writeChan replace ()
takeMVar lock
xs <- getAndCheckInitialItems initMap
checkInitialItems initMap xs
body <- getBody
test body chan
testWidget (pure ()) check $ void $ do
e <- triggerEventWithChan replace
runWithReplace (pure ()) $ ffor e $ \() -> void $ do
pb <- getPostBuild
performEvent_ $ liftIO (putMVar lock ()) <$ pb
(dmap, _evt) <- traverseDMapWithKeyWithAdjustWithMove widget initMap =<< triggerEventWithChan chan
liftIO $ assertEqual "DMap" initMap dmap
describe "hydrating invalid HTML" $ session' $ do
it "can hydrate list in paragraph" $ runWD $ do
let preSwitchover = do
checkBodyText "before\ninner\nafter"
-- Two <p> tags should be present
(p1, p2) <- WD.findElems (WD.ByTag "p") >>= \case
[p1, p2] -> pure (p1, p2)
_ -> error "Unexpected number of `p` tags (expected 2)"
ol <- findElemWithRetry (WD.ByTag "ol")
shouldContainText "before" p1
shouldContainText "inner" ol
shouldContainText "" p2
pure (p1, ol, p2)
check (p1, ol, p2) = do
checkBodyText "before\ninner\nafter"
shouldContainText "before\ninner\nafter" p1
elementShouldBeRemoved ol
elementShouldBeRemoved p2
testWidget' preSwitchover check $ do
-- This is deliberately invalid HTML, the browser will interpret it as
-- <p>before</p><ol>inner</ol>after<p></p>
el "p" $ do
text "before"
el "ol" $ text "inner"
text "after"
-- TODO: This test presupposes the exact set of labels that "dropdown" places in the "value" fields to distinguish options.
-- This dependence on internal implementation details is undesirable in a test case, but seems fairly tricky to avoid.
-- It seems expedient for the time being to expect this test case to be updated, should those implementation details ever change.
describe "dropdown" $ session' $ do
let doTest expectedOpts (initialValue :: Text) = do
let doCheck = do
es <- findElemsWithRetry $ WD.ByTag "option"
opts <- mapM fetchElement es
assertEqual "missing/extra/incorrect option element(s)" expectedOpts (sort opts)
testWidget doCheck doCheck $ do
void $ dropdown initialValue (constDyn (("aa" :: Text) =: "aaa" <> "bb" =: "bbb")) def
fetchElement e = do
val <- WD.attr e "value"
sel <- WD.attr e "selected"
return (fromMaybe "" val, isJust sel)
-- The "aa" test case is important, but a good test implementation probably needs to avoid selenium, because HTML parsers will insert a "selected" attribute on the first "option" tag if no selected attributes are present; thus as written, this erroneously succeeds on the old implementation (but properly implemented, should fail)
-- Thus, it would appear that we do actually need a HTML5 or maybe XML parser for this test suite.
xit "statically renders initial values (on aa)" $ runWD $ do
doTest [("0",True),("1",False)] "aa"
-- These tests are currently marked "pending" (by using "xit" instead of "it") because this test has a high chance of non-deterministically failing, which is a problem elsewhere in this test suite as well
xit "statically renders initial values (on bb)" $ runWD $ do
doTest [("0",False),("1",True)] "bb"
data Selenium = Selenium
{ _selenium_portNumber :: PortNumber
, _selenium_stopServer :: IO ()
}
startSeleniumServer :: PortNumber -> IO (IO ())
startSeleniumServer port = do
(_,_,_,ph) <- createProcess $ (proc "selenium-server" ["-port", show port])
{ std_in = NoStream
, std_out = NoStream
, std_err = NoStream
}
return $ terminateProcess ph
withSeleniumServer :: (Selenium -> IO ()) -> IO ()
withSeleniumServer f = do
stopServer <- startSeleniumServer seleniumPort
threadDelay $ 1000 * 1000 * 2 -- TODO poll or wait on a a signal to block on
f $ Selenium
{ _selenium_portNumber = seleniumPort
, _selenium_stopServer = stopServer
}
triggerEventWithChan :: (Reflex t, TriggerEvent t m, Prerender js t m) => Chan a -> m (Event t a)
triggerEventWithChan chan = do
(e, trigger) <- newTriggerEvent
-- In prerender because we only want to do this on the client
prerender_ (pure ()) $ void $ liftIO $ forkIO $ forever $ trigger =<< readChan chan
pure e
shouldBeWithRetryM :: (Eq a, Show a) => WD a -> a -> WD ()
shouldBeWithRetryM m expected = withRetry $ do
got <- m
got `shouldBe` expected
assertAttr :: WD.Element -> Text -> Maybe Text -> WD ()
assertAttr e k v = liftIO . assertEqual "Incorrect attribute value" v =<< WD.attr e k
elementShouldBeRemoved :: WD.Element -> WD ()
elementShouldBeRemoved e = withRetry $ do
try (WD.getText e) >>= \case
Left (WD.FailedCommand WD.StaleElementReference _) -> return ()
Left err -> throwM err
Right !_ -> liftIO $ assertFailure "Expected element to be removed, but it still exists"
shouldContainText :: Text -> WD.Element -> WD ()
shouldContainText t = withRetry . shouldContainTextNoRetry t
shouldContainTextNoRetry :: Text -> WD.Element -> WD ()
shouldContainTextNoRetry t = flip shouldBe t <=< WD.getText
checkBodyText :: Text -> WD ()
checkBodyText = checkTextInTag "body"
checkTextInTag :: Text -> Text -> WD ()
checkTextInTag t expected = do
e <- findElemWithRetry (WD.ByTag t)
shouldContainText expected e
checkTextInId :: Text -> Text -> WD ()
checkTextInId i expected = do
e <- findElemWithRetry (WD.ById i)
shouldContainText expected e
findElemWithRetry :: Selector -> WD WD.Element
findElemWithRetry = withRetry . WD.findElem
findElemsWithRetry :: Selector -> WD [WD.Element]
findElemsWithRetry = withRetry . WD.findElems
getBody :: WD WD.Element
getBody = WD.findElem $ WD.ByTag "body"
withRetry :: forall a. WD a -> WD a
withRetry a = wait 300
where wait :: Int -> WD a
wait 0 = a
wait n = try a >>= \case
Left (e :: SomeException) -> do
liftIO $ putStrLn ("(retrying due to " <> show e <> ")") *> threadDelay 100000
wait $ n - 1
Right v -> return v
divId :: DomBuilder t m => Text -> m a -> m a
divId i = elAttr "div" ("id" =: i)
type TestWidget js t m = (DomBuilder t m, MonadHold t m, PostBuild t m, Prerender js t m, PerformEvent t m, TriggerEvent t m, MonadFix m, MonadIO (Performable m), MonadIO m)
testWidgetStaticDebug
:: Bool
-> WD b
-- ^ Webdriver commands to run before JS runs and after hydration switchover
-> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
-- ^ Widget we are testing
-> WD b
testWidgetStaticDebug withDebugging w = testWidgetDebug withDebugging (void w) w
-- | TODO: do something about JSExceptions not causing tests to fail
testWidgetDebug
:: Bool
-> WD ()
-- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
-> WD b
-- ^ Webdriver commands to run after hydration switchover
-> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
-- ^ Widget we are testing
-> WD b
testWidgetDebug withDebugging beforeJS afterSwitchover =
testWidgetDebug' withDebugging beforeJS (const afterSwitchover)
-- | TODO: do something about JSExceptions not causing tests to fail
testWidgetDebug'
:: Bool
-> WD a
-- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
-> (a -> WD b)
-- ^ Webdriver commands to run after hydration switchover
-> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
-- ^ Widget we are testing (contents of body)
-> WD b
testWidgetDebug' withDebugging beforeJS afterSwitchover bodyWidget = do
let putStrLnDebug :: MonadIO m => Text -> m ()
putStrLnDebug m = when withDebugging $ liftIO $ putStrLn $ T.unpack m
staticApp = do
el "head" $ pure ()
el "body" $ do
bodyWidget
el "script" $ text $ TE.decodeUtf8 $ LBS.toStrict $ jsaddleJs False
putStrLnDebug "rendering static"
((), html) <- liftIO $ renderStatic $ runHydratableT staticApp
putStrLnDebug "rendered static"
waitBeforeJS <- liftIO newEmptyMVar -- Empty until JS should be run
waitUntilSwitchover <- liftIO newEmptyMVar -- Empty until switchover
let entryPoint = do
putStrLnDebug "taking waitBeforeJS"
liftIO $ takeMVar waitBeforeJS
let switchOverAction = do
putStrLnDebug "switchover syncPoint"
syncPoint
putStrLnDebug "putting waitUntilSwitchover"
liftIO $ putMVar waitUntilSwitchover ()
putStrLnDebug "put waitUntilSwitchover"
putStrLnDebug "running mainHydrationWidgetWithSwitchoverAction"
mainHydrationWidgetWithSwitchoverAction switchOverAction blank bodyWidget
putStrLnDebug "syncPoint after mainHydrationWidgetWithSwitchoverAction"
syncPoint
application <- liftIO $ jsaddleOr defaultConnectionOptions entryPoint $ \_ sendResponse -> do
putStrLnDebug "sending response"
r <- sendResponse $ responseLBS status200 [] $ "<!doctype html>\n" <> LBS.fromStrict html
putStrLnDebug "sent response"
return r
waitJSaddle <- liftIO newEmptyMVar
let settings = foldr ($) Warp.defaultSettings
[ Warp.setPort $ fromIntegral $ toInteger jsaddlePort
, Warp.setBeforeMainLoop $ do
putStrLnDebug "putting waitJSaddle"
putMVar waitJSaddle ()
putStrLnDebug "put waitJSaddle"
]
-- hSilence to get rid of ConnectionClosed logs
silenceIfDebug = if withDebugging then id else hSilence [stderr]
jsaddleWarp = silenceIfDebug $ Warp.runSettings settings application
withAsync' jsaddleWarp $ do
putStrLnDebug "taking waitJSaddle"
liftIO $ takeMVar waitJSaddle
putStrLnDebug "opening page"
WD.openPage $ "http://localhost:" <> show jsaddlePort
putStrLnDebug "running beforeJS"
a <- beforeJS
putStrLnDebug "putting waitBeforeJS"
liftIO $ putMVar waitBeforeJS ()
putStrLnDebug "taking waitUntilSwitchover"
liftIO $ takeMVar waitUntilSwitchover
putStrLnDebug "running afterSwitchover"
afterSwitchover a
withAsync' :: (MonadIO m, MonadMask m) => IO a -> m b -> m b
withAsync' f g = bracket
(liftIO $ Async.async f)
(liftIO . Async.uninterruptibleCancel)
(const g)
data Key2 a where
Key2_Int :: Int -> Key2 Int
Key2_Char :: Char -> Key2 Char
deriveGEq ''Key2
deriveGCompare ''Key2
deriveGShow ''Key2
deriveArgDict ''Key2
|
ryantrinkle/reflex-dom
|
reflex-dom-core/test/hydration.hs
|
bsd-3-clause
| 72,394
| 0
| 31
| 20,408
| 20,856
| 9,666
| 11,190
| -1
| -1
|
-- Example of using pwmWrite.
-- Run with an LED connected to wiringPi pin 1:
-- https://www.flickr.com/photos/107479024@N04/32201782695/
-- Pulses the LED.
-- Compatible with the hs-wiringPi test board.
-- https://github.com/ppelleti/hs-wiringPi-test-board
import Control.Concurrent
import Control.Monad
import System.Hardware.WiringPi
pwmPin = Wpi 1
main = do
pinMode pwmPin PWM_OUTPUT
forM_ [0, 0.1 ..] $ \x -> do
let y = (sin x + 1) / 2
y' = y ** 2.8 -- gamma correction
analog = y' * 1024
pwmWrite pwmPin $ round analog
threadDelay 50000
|
ppelleti/hs-wiringPi
|
examples/pwm-example.hs
|
bsd-3-clause
| 589
| 0
| 17
| 129
| 127
| 67
| 60
| 12
| 1
|
{-# LANGUAGE DeriveGeneric #-}
module Language.Granule.Checker.Constraints.SymbolicGrades where
{- Provides a symbolic representation of grades (coeffects, effects, indices)
in order for a solver to use.
-}
import Language.Granule.Syntax.Identifiers
import Language.Granule.Syntax.Type
import Language.Granule.Checker.Constraints.SNatX
import Data.Functor.Identity
import Control.Monad.IO.Class
import Control.Monad (liftM2)
-- import System.Exit (die)
import Control.Exception
import qualified Data.Text as T
import GHC.Generics (Generic)
import Data.SBV hiding (kindOf, name, symbolic)
import qualified Data.Set as S
solverError :: MonadIO m => String -> m a
solverError msg = liftIO $ throwIO . ErrorCall $ msg
-- Symbolic grades, for coeffects and indices
data SGrade =
SNat SInteger
| SFloat SFloat
| SLevel SInteger
| SSet (S.Set (Id, Type))
| SExtNat { sExtNat :: SNatX }
| SInterval { sLowerBound :: SGrade, sUpperBound :: SGrade }
-- Single point coeffect (not exposed at the moment)
| SPoint
| SProduct { sfst :: SGrade, ssnd :: SGrade }
-- A kind of embedded uninterpreted sort which can accept some equations
-- Used for doing some limited solving over poly coeffect grades
| SUnknown SynTree
-- but if Nothing then these values are incomparable
deriving (Show, Generic)
data SynTree =
SynPlus SynTree SynTree
| SynTimes SynTree SynTree
| SynMeet SynTree SynTree
| SynJoin SynTree SynTree
| SynLeaf (Maybe SInteger) -- Just 0 and Just 1 can be identified
| SynMerge SBool SynTree SynTree
instance Show SynTree where
show (SynPlus s t) = "(" ++ show s ++ " + " ++ show t ++ ")"
show (SynTimes s t) = show s ++ " * " ++ show t
show (SynJoin s t) = "(" ++ show s ++ " \\/ " ++ show t ++ ")"
show (SynMeet s t) = "(" ++ show s ++ " /\\ " ++ show t ++ ")"
show (SynLeaf Nothing) = "?"
show (SynLeaf (Just n)) = T.unpack $
T.replace (T.pack $ " :: SInteger") (T.pack "") (T.pack $ show n)
show (SynMerge sb s t) = "(if " ++ show sb ++ " (" ++ show s ++ ") (" ++ show t ++ "))"
sEqTree :: SynTree -> SynTree -> Symbolic SBool
sEqTree (SynPlus s s') (SynPlus t t') =
liftM2 (.||) (liftM2 (.&&) (sEqTree s t) (sEqTree s' t'))
-- + is commutative
(liftM2 (.&&) (sEqTree s' t) (sEqTree s t'))
sEqTree (SynTimes s s') (SynTimes t t') = liftM2 (.&&) (sEqTree s t) (sEqTree s' t')
sEqTree (SynMeet s s') (SynMeet t t') =
liftM2 (.||) (liftM2 (.&&) (sEqTree s t) (sEqTree s' t'))
-- /\ is commutative
(liftM2 (.&&) (sEqTree s t') (sEqTree s' t))
sEqTree (SynJoin s s') (SynJoin t t') =
liftM2 (.||) (liftM2 (.&&) (sEqTree s t) (sEqTree s' t'))
-- \/ is commutative
(liftM2 (.&&) (sEqTree s t') (sEqTree s' t))
sEqTree (SynMerge sb s s') (SynMerge sb' t t') =
liftM2 (.||)
(liftM2 (.&&) (liftM2 (.&&) (sEqTree s t) (sEqTree s' t'))
(return $ sb .== sb'))
-- Flipped branching
(liftM2 (.&&) (liftM2 (.&&) (sEqTree s t') (sEqTree s t))
(return $ sb .== sNot sb'))
sEqTree (SynLeaf Nothing) (SynLeaf Nothing) = return $ sFalse
sEqTree (SynLeaf (Just n)) (SynLeaf (Just n')) = return $ n .=== n'
sEqTree _ _ = return $ sFalse
sLtTree :: SynTree -> SynTree -> Symbolic SBool
sLtTree (SynPlus s s') (SynPlus t t') = liftM2 (.&&) (sLtTree s t) (sLtTree s' t')
sLtTree (SynTimes s s') (SynTimes t t') = liftM2 (.&&) (sLtTree s t) (sLtTree s' t')
sLtTree (SynMeet s s') (SynMeet t t') = liftM2 (.&&) (sLtTree s t) (sLtTree s' t')
sLtTree (SynJoin s s') (SynJoin t t') = liftM2 (.&&) (sLtTree s t) (sLtTree s' t')
sLtTree (SynMerge sb s s') (SynMerge sb' t t') =
liftM2 (.&&) (return $ sb .== sb') (liftM2 (.&&) (sLtTree s t) (sLtTree s' t'))
sLtTree (SynLeaf Nothing) (SynLeaf Nothing) = return $ sFalse
sLtTree (SynLeaf (Just n)) (SynLeaf (Just n')) = return $ n .< n'
sLtTree _ _ = return $ sFalse
-- Work out if two symbolic grades are of the same type
match :: SGrade -> SGrade -> Bool
match (SNat _) (SNat _) = True
match (SFloat _) (SFloat _) = True
match (SLevel _) (SLevel _) = True
match (SSet _) (SSet _) = True
match (SExtNat _) (SExtNat _) = True
match (SInterval s1 s2) (SInterval t1 t2) = match s1 t1 && match t1 t2
match SPoint SPoint = True
match (SProduct s1 s2) (SProduct t1 t2) = match s1 t1 && match s2 t2
match (SUnknown _) (SUnknown _) = True
match _ _ = False
isSProduct :: SGrade -> Bool
isSProduct (SProduct _ _) = True
isSProduct _ = False
applyToProducts :: Monad m => (SGrade -> SGrade -> m a)
-> (a -> a -> b)
-> (SGrade -> a)
-> SGrade -> SGrade -> Either String (m b)
applyToProducts f g _ a@(SProduct a1 b1) b@(SProduct a2 b2) =
if (match a1 a2) && (match b1 b2)
then Right $ liftM2 g (f a1 a2) (f b1 b2)
else if (match a1 b2) && (match b1 a2)
then Right $ liftM2 g (f a1 b2) (f b1 a2)
else Left $ "Solver grades " <> show a <> " and " <> show b <> " are incompatible "
applyToProducts f g h a@(SProduct a1 b1) c =
if match a1 c
then Right $ liftM2 g (f a1 c) (return $ h b1)
else if match b1 c
then Right $ liftM2 g (return $ h a1) (f b1 c)
else Left $ "Solver grades " <> show a <> " and " <> show c <> " are incompatible "
applyToProducts f g h c a@(SProduct a1 b1) =
if match c a1
then Right $ liftM2 g (f c a1) (return $ h b1)
else if match c b1
then Right $ liftM2 g (return $ h a1) (f c b1)
else Left $ "Solver grades " <> show a <> " and " <> show c <> " are incompatible "
applyToProducts _ _ _ a b =
Left $ "Solver grades " <> show a <> " and " <> show b <> " are not products"
natLike :: SGrade -> Bool
natLike (SNat _) = True
natLike (SExtNat _) = True
natLike _ = False
instance Mergeable SGrade where
symbolicMerge s sb (SNat n) (SNat n') = SNat (symbolicMerge s sb n n')
symbolicMerge s sb (SFloat n) (SFloat n') = SFloat (symbolicMerge s sb n n')
symbolicMerge s sb (SLevel n) (SLevel n') = SLevel (symbolicMerge s sb n n')
symbolicMerge s sb (SSet n) (SSet n') = error "Can't symbolic merge sets yet"
symbolicMerge s sb (SExtNat n) (SExtNat n') = SExtNat (symbolicMerge s sb n n')
symbolicMerge s sb (SInterval lb1 ub1) (SInterval lb2 ub2) =
SInterval (symbolicMerge s sb lb1 lb2) (symbolicMerge s sb ub1 ub2)
symbolicMerge s sb SPoint SPoint = SPoint
symbolicMerge s sb a b | isSProduct a || isSProduct b =
either error runIdentity (applyToProducts (\a b -> return $ symbolicMerge s sb a b) SProduct id a b)
symbolicMerge s sb (SUnknown (SynLeaf (Just u))) (SUnknown (SynLeaf (Just u'))) =
SUnknown (SynLeaf (Just (symbolicMerge s sb u u')))
symbolicMerge s sb (SUnknown a) (SUnknown b) = SUnknown (SynMerge sb a b)
symbolicMerge _ _ s t = error $ cannotDo "symbolicMerge" s t
symGradeLess :: SGrade -> SGrade -> Symbolic SBool
symGradeLess (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 (.&&) (symGradeLess lb2 lb1) (symGradeLess ub1 ub2)
symGradeLess (SNat n) (SNat n') = return $ n .< n'
symGradeLess (SFloat n) (SFloat n') = return $ n .< n'
symGradeLess (SLevel n) (SLevel n') = return $ n .< n'
symGradeLess (SSet n) (SSet n') = solverError "Can't compare symbolic sets yet"
symGradeLess (SExtNat n) (SExtNat n') = return $ n .< n'
symGradeLess SPoint SPoint = return sTrue
symGradeLess (SUnknown s) (SUnknown t) = sLtTree s t
symGradeLess s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeLess (.&&) (const sTrue) s t)
symGradeLess s t = solverError $ cannotDo ".<" s t
symGradeGreater :: SGrade -> SGrade -> Symbolic SBool
symGradeGreater x y = symGradeLess y x
symGradeLessEq :: SGrade -> SGrade -> Symbolic SBool
symGradeLessEq x y = lazyOrSymbolicM (symGradeEq x y) (symGradeLess x y)
symGradeGreaterEq :: SGrade -> SGrade -> Symbolic SBool
symGradeGreaterEq x y = lazyOrSymbolicM (symGradeEq x y) (symGradeGreater x y)
-- A short-circuiting disjunction for effectful computations that
-- produce symoblic bools (a kind of expanded `iteLazy` for Symbolic monad)
lazyOrSymbolicM :: Symbolic SBool -> Symbolic SBool -> Symbolic SBool
lazyOrSymbolicM m1 m2 = m1 >>= \b1 ->
case unliteral b1 of
Just True -> return sTrue
otherwise -> m2 >>= \b2 -> return $ symbolicMerge False b1 sTrue b2
symGradeEq :: SGrade -> SGrade -> Symbolic SBool
symGradeEq (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 (.&&) (symGradeEq lb2 lb1) (symGradeEq ub1 ub2)
symGradeEq (SNat n) (SNat n') = return $ n .== n'
symGradeEq (SFloat n) (SFloat n') = return $ n .== n'
symGradeEq (SLevel n) (SLevel n') = return $ n .== n'
symGradeEq (SSet n) (SSet n') = solverError "Can't compare symbolic sets yet"
symGradeEq (SExtNat n) (SExtNat n') = return $ n .== n'
symGradeEq SPoint SPoint = return $ sTrue
symGradeEq s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeEq (.&&) (const sTrue) s t)
symGradeEq (SUnknown t) (SUnknown t') = sEqTree t t'
symGradeEq s t = solverError $ cannotDo ".==" s t
-- | Meet operation on symbolic grades
symGradeMeet :: SGrade -> SGrade -> Symbolic SGrade
symGradeMeet (SNat n1) (SNat n2) = return $ SNat $ n1 `smin` n2
symGradeMeet (SSet s) (SSet t) = return $ SSet $ S.intersection s t
symGradeMeet (SLevel s) (SLevel t) = return $ SLevel $ s `smin` t
symGradeMeet (SFloat n1) (SFloat n2) = return $ SFloat $ n1 `smin` n2
symGradeMeet (SExtNat x) (SExtNat y) = return $ SExtNat $
ite (isInf x) y (ite (isInf y) x (SNatX (xVal x `smin` xVal y)))
symGradeMeet (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 SInterval (lb1 `symGradeJoin` lb2) (ub1 `symGradeMeet` ub2)
symGradeMeet SPoint SPoint = return SPoint
symGradeMeet s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeMeet SProduct id s t)
symGradeMeet (SUnknown (SynLeaf (Just n))) (SUnknown (SynLeaf (Just n'))) =
return $ SUnknown (SynLeaf (Just (n `smin` n')))
symGradeMeet (SUnknown t) (SUnknown t') = return $ SUnknown (SynMeet t t')
symGradeMeet s t = solverError $ cannotDo "meet" s t
-- | Join operation on symbolic grades
symGradeJoin :: SGrade -> SGrade -> Symbolic SGrade
symGradeJoin (SNat n1) (SNat n2) = return $ SNat (n1 `smax` n2)
symGradeJoin (SSet s) (SSet t) = return $ SSet $ S.intersection s t
symGradeJoin (SLevel s) (SLevel t) = return $ SLevel $ s `smax` t
symGradeJoin (SFloat n1) (SFloat n2) = return $ SFloat (n1 `smax` n2)
symGradeJoin (SExtNat x) (SExtNat y) = return $ SExtNat $
ite (isInf x .|| isInf y) inf (SNatX (xVal x `smax` xVal y))
symGradeJoin (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 SInterval (lb1 `symGradeMeet` lb2) (ub1 `symGradeJoin` ub2)
symGradeJoin SPoint SPoint = return SPoint
symGradeJoin s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeJoin SProduct id s t)
symGradeJoin (SUnknown (SynLeaf (Just n))) (SUnknown (SynLeaf (Just n'))) =
return $ SUnknown (SynLeaf (Just (n `smax` n')))
symGradeJoin (SUnknown t) (SUnknown t') = return $ SUnknown (SynJoin t t')
symGradeJoin s t = solverError $ cannotDo "join" s t
-- | Plus operation on symbolic grades
symGradePlus :: SGrade -> SGrade -> Symbolic SGrade
symGradePlus (SNat n1) (SNat n2) = return $ SNat (n1 + n2)
symGradePlus (SSet s) (SSet t) = return $ SSet $ S.union s t
symGradePlus (SLevel lev1) (SLevel lev2) = return $ SLevel $ lev1 `smax` lev2
symGradePlus (SFloat n1) (SFloat n2) = return $ SFloat $ n1 + n2
symGradePlus (SExtNat x) (SExtNat y) = return $ SExtNat (x + y)
symGradePlus (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 SInterval (lb1 `symGradePlus` lb2) (ub1 `symGradePlus` ub2)
symGradePlus SPoint SPoint = return $ SPoint
symGradePlus s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradePlus SProduct id s t)
-- Direct encoding of additive unit
symGradePlus (SUnknown t@(SynLeaf (Just u))) (SUnknown t'@(SynLeaf (Just u'))) =
return $ ite (u .== 0) (SUnknown (SynLeaf (Just u')))
(ite (u' .== 0) (SUnknown (SynLeaf (Just u))) (SUnknown (SynPlus t t')))
symGradePlus (SUnknown t@(SynLeaf (Just u))) (SUnknown t') =
return $ ite (u .== 0) (SUnknown t') (SUnknown (SynPlus t t'))
symGradePlus (SUnknown t) (SUnknown t'@(SynLeaf (Just u))) =
return $ ite (u .== 0) (SUnknown t) (SUnknown (SynPlus t t'))
symGradePlus (SUnknown um) (SUnknown un) =
return $ SUnknown (SynPlus um un)
symGradePlus s t = solverError $ cannotDo "plus" s t
-- | Times operation on symbolic grades
symGradeTimes :: SGrade -> SGrade -> Symbolic SGrade
symGradeTimes (SNat n1) (SNat n2) = return $ SNat (n1 * n2)
symGradeTimes (SNat n1) (SExtNat (SNatX n2)) = return $ SExtNat $ SNatX (n1 * n2)
symGradeTimes (SExtNat (SNatX n1)) (SNat n2) = return $ SExtNat $ SNatX (n1 * n2)
symGradeTimes (SSet s) (SSet t) = return $ SSet $ S.union s t
symGradeTimes (SLevel lev1) (SLevel lev2) = return $
ite (lev1 .== literal unusedRepresentation)
(SLevel $ literal unusedRepresentation)
$ ite (lev2 .== literal unusedRepresentation)
(SLevel $ literal unusedRepresentation)
(SLevel $ lev1 `smax` lev2)
symGradeTimes (SFloat n1) (SFloat n2) = return $ SFloat $ n1 * n2
symGradeTimes (SExtNat x) (SExtNat y) = return $ SExtNat (x * y)
symGradeTimes (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 SInterval (comb symGradeMeet) (comb symGradeJoin)
where
comb f = do
lb1lb2 <- lb1 `symGradeTimes` lb2
lb1ub2 <- lb1 `symGradeTimes` ub2
ub1lb2 <- ub1 `symGradeTimes` lb2
ub1ub2 <- ub1 `symGradeTimes` ub2
a <- lb1lb2 `f` lb1ub2
b <- a `f` ub1lb2
b `f` ub1ub2
symGradeTimes SPoint SPoint = return SPoint
symGradeTimes s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeTimes SProduct id s t)
-- units and absorption directly encoded
symGradeTimes (SUnknown t@(SynLeaf (Just u))) (SUnknown t'@(SynLeaf (Just u'))) =
return $
ite (u .== 1) (SUnknown (SynLeaf (Just u')))
(ite (u' .== 1) (SUnknown (SynLeaf (Just u)))
(ite (u .== 0) (SUnknown (SynLeaf (Just 0)))
(ite (u' .== 0) (SUnknown (SynLeaf (Just 0)))
(SUnknown (SynTimes t t')))))
symGradeTimes (SUnknown t@(SynLeaf (Just u))) (SUnknown t') =
return $
ite (u .== 1) (SUnknown t')
(ite (u .== 0) (SUnknown (SynLeaf (Just 0))) (SUnknown (SynTimes t t')))
symGradeTimes (SUnknown t) (SUnknown t'@(SynLeaf (Just u))) =
return $
ite (u .== 1) (SUnknown t)
(ite (u .== 0) (SUnknown (SynLeaf (Just 0))) (SUnknown (SynTimes t t')))
symGradeTimes (SUnknown um) (SUnknown un) =
return $ SUnknown (SynTimes um un)
symGradeTimes s t = solverError $ cannotDo "times" s t
-- | Minus operation on symbolic grades
symGradeMinus :: SGrade -> SGrade -> Symbolic SGrade
symGradeMinus (SNat n1) (SNat n2) = return $ SNat $ ite (n1 .< n2) 0 (n1 - n2)
symGradeMinus (SSet s) (SSet t) = return $ SSet $ s S.\\ t
symGradeMinus (SExtNat x) (SExtNat y) = return $ SExtNat (x - y)
symGradeMinus (SInterval lb1 ub1) (SInterval lb2 ub2) =
liftM2 SInterval (lb1 `symGradeMinus` lb2) (ub1 `symGradeMinus` ub2)
symGradeMinus SPoint SPoint = return $ SPoint
symGradeMinus s t | isSProduct s || isSProduct t =
either solverError id (applyToProducts symGradeMinus SProduct id s t)
symGradeMinus s t = solverError $ cannotDo "minus" s t
cannotDo :: String -> SGrade -> SGrade -> String
cannotDo op (SUnknown s) (SUnknown t) =
"It is unknown whether "
<> show s <> " "
<> op <> " "
<> show t
<> " holds for all resource algebras."
cannotDo op s t =
"Cannot perform symbolic operation `"
<> op <> "` on "
<> show s <> " and "
<> show t
|
dorchard/gram_lang
|
frontend/src/Language/Granule/Checker/Constraints/SymbolicGrades.hs
|
bsd-3-clause
| 15,814
| 0
| 18
| 3,519
| 6,821
| 3,457
| 3,364
| 285
| 7
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Control.Parallel.HsSkel.Exec.Default (
IOEC(..),
IOFuture()
) where
import Control.Parallel.HsSkel.DSL
import Data.Foldable (mapM_, foldlM)
import Data.Maybe (isJust, fromJust)
import Data.Traversable (mapM)
import qualified Data.Sequence as S
import Control.Category ((.))
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, readMVar)
import Control.DeepSeq (NFData, rnf)
import Control.Exception (evaluate)
import Control.Monad (liftM)
import Prelude hiding (id, mapM, mapM_, take, (.))
import Control.Concurrent.Chan.Unagi.Bounded (InChan, OutChan, newChan, readChan, writeChan, tryReadChan, tryRead)
--import Data.Time.Clock (getCurrentTime, diffUTCTime)
{- ================================================================== -}
{- ============================= Types ============================== -}
{- ================================================================== -}
data IOFuture a = Later (MVar a)
readFuture :: IOFuture a -> IO a
readFuture (Later mvar) = readMVar mvar
data IOEC = IOEC { queueLimit :: Int }
instance Exec IO where
type Context IO = IOEC
type Future IO = IOFuture
exec = execIO
data Queue a = Queue {
inChan :: InChan a,
outChan :: OutChan a
}
newQueue :: Int -> IO (Queue a)
newQueue limit = do
(inChan, outChan) <- newChan limit
return $ Queue inChan outChan
readQueue :: Queue a -> IO a
readQueue = readChan . outChan
tryReadQueue :: Queue a -> IO (Maybe a)
tryReadQueue q = do
elem <- tryReadChan $ outChan q
tryRead elem
writeQueue :: Queue a -> a -> IO ()
writeQueue = writeChan . inChan
{- ================================================================== -}
{- =========================== Auxiliary ============================ -}
{- ================================================================== -}
eval :: (NFData a) => a -> IO a
eval a = do
evaluate $ rnf a
return a
data BackMsg = Stop
handleBackMsg :: IO () -> Queue BackMsg -> Queue BackMsg -> IO ()
handleBackMsg continue bqi bqo = do
backMsg <- tryReadQueue bqi
case backMsg of
Nothing -> continue
Just Stop -> writeQueue bqo Stop
{- ================================================================== -}
{- ======================= Stream Execution ========================= -}
{- ================================================================== -}
execStream :: IOEC -> Stream dim IOFuture i -> IO (Queue (Maybe (S.Seq i)), Queue BackMsg)
execStream ec (StUnfoldr dim gen i) = do
qo <- newQueue (queueLimit ec)
bqi <- newQueue (queueLimit ec)
_ <- forkIO $ recc qo bqi i
return (qo, bqi)
where
recc qo bqi i = do
backMsg <- tryReadQueue bqi
case backMsg of
Nothing -> do
(elems, i') <- genElems (dimLinearSize dim) S.empty i
if (not $ S.null elems)
then writeQueue qo (Just elems)
else return ()
if (isJust i')
then recc qo bqi (fromJust i')
else writeQueue qo Nothing
Just Stop -> do
writeQueue qo Nothing
return ()
genElems 0 seq i = return (seq, Just i)
genElems size seq i = do
let res = gen i
case res of
Just (v, i') -> do
_ <- eval v
genElems (size-1) (seq S.|> v) i'
Nothing -> return (seq, Nothing)
execStream ec (StMap _ sk stream) = do
qo <- newQueue (queueLimit ec)
bqi <- newQueue (queueLimit ec)
(qi, bqo) <- execStream ec stream
_ <- forkIO $ recc qi qo bqi bqo
return (qo, bqi)
where
recc qi qo bqi bqo = do
let
continue = do
res <- readQueue qi
case res of
Just vi -> do
vo <- return =<< exec ec (skMap sk) vi
writeQueue qo (Just vo)
recc qi qo bqi bqo
Nothing -> writeQueue qo Nothing
handleBackMsg continue bqi bqo
execStream ec (StChunk dim stream) = do
qo <- newQueue (queueLimit ec)
bqi <- newQueue (queueLimit ec)
(qi, bqo) <- execStream ec stream
let chunkSize = dimLinearSize dim
_ <- forkIO $ recc qi qo bqi bqo S.empty chunkSize
return (qo, bqi)
where
recc qi qo bqi bqo storage chunkSize = do
let
continue = do
i <- readQueue qi
case i of
Just vi -> do
let storage' = storage S.>< vi
if (S.length storage' == chunkSize)
then do
writeQueue qo (Just $ storage')
recc qi qo bqi bqo S.empty chunkSize
else do
recc qi qo bqi bqo storage' chunkSize
Nothing -> do
if (S.length storage > 0)
then writeQueue qo (Just $ storage)
else return ()
writeQueue qo Nothing
handleBackMsg continue bqi bqo
execStream ec (StUnChunk _ stream) = do
let chunk = dimHead . stDim $ stream
qo <- newQueue (queueLimit ec)
bqi <- newQueue (queueLimit ec)
(qi, bqo) <- execStream ec stream
_ <- forkIO $ recc qi qo bqi bqo chunk
return (qo, bqi)
where
recc qi qo bqi bqo chunk = do
let
continue = do
i <- readQueue qi
case i of
Just vsi -> do
let maxChunkIdx = div (S.length vsi) chunk
mapM_ (\c -> writeQueue qo . Just . S.take chunk . S.drop (c * chunk) $ vsi) [0 .. maxChunkIdx]
recc qi qo bqi bqo chunk
Nothing -> do
writeQueue qo Nothing
handleBackMsg continue bqi bqo
execStream ec (StParMap _ sk stream) = do
qo1 <- newQueue (queueLimit ec)
bqi1 <- newQueue (queueLimit ec)
qo2 <- newQueue (queueLimit ec)
bqi2 <- newQueue (queueLimit ec)
(qi, bqo) <- execStream ec stream
_ <- forkIO $ recc1 qi qo1 bqi1 bqo
_ <- forkIO $ recc2 qo1 qo2 bqi2 bqi1
return (qo2, bqi2)
where
recc1 qi qo bqi bqo = do
let
continue = do
res <- readQueue qi
case res of
Just vi -> do
vo <- exec ec (SkFork (SkMap sk)) vi
writeQueue qo (Just vo)
recc1 qi qo bqi bqo
Nothing -> writeQueue qo Nothing
handleBackMsg continue bqi bqo
recc2 qi qo bqi bqo = do
let
continue = do
res <- readQueue qi
case res of
Just vi -> do
vo <- exec ec SkSync vi
writeQueue qo (Just vo)
recc2 qi qo bqi bqo
Nothing -> writeQueue qo Nothing
handleBackMsg continue bqi bqo
execStream ec (StUntil _ skF z skCond stream) = do
qo <- newQueue (queueLimit ec)
bqi <- newQueue (queueLimit ec)
(qi, bqo) <- execStream ec stream
_ <- forkIO $ recc qi qo bqi bqo z
return (qo, bqi)
where
recc qi qo bqi bqo acc = do
let
continue = do
i <- readQueue qi
case i of
Just vi -> do
(acc', pos, stop) <-
foldlM (\(a, p, cond) v ->
do -- esto no esta muy bien ya que recorre todo el arreglo
if cond
then do
return (a, p, cond)
else do
a' <- exec ec skF (a, v)
cond' <- exec ec skCond a'
return (a', p + 1, cond')
) (acc, 0, False) vi
if stop
then do
writeQueue qo (Just $ S.take (pos + 1) vi)
writeQueue bqo Stop
writeQueue qo Nothing
else do
writeQueue qo (Just vi)
recc qi qo bqi bqo acc'
Nothing -> do
writeQueue qo Nothing
handleBackMsg continue bqi bqo
{- ================================================================== -}
{- ======================== Skel Execution ========================== -}
{- ================================================================== -}
execIO :: IOEC -> Skel IOFuture i o -> i -> IO o
execIO _ (SkStrict f) = (eval =<<) . liftM f . return
execIO _ (SkLazy f) = liftM f . return
execIO ec (SkFork sk) = \i -> (do
mVar <- newEmptyMVar
_ <- forkIO (stuff i mVar)
return $ Later mVar)
where
stuff i mVar = do
r <- exec ec sk i
putMVar mVar r
execIO _ (SkSync) = readFuture
execIO ec (SkComp s2 s1) = (exec ec s2 =<<) . exec ec s1
execIO ec (SkPair sk1 sk2) = \(i1, i2) -> do
o1 <- exec ec sk1 i1
o2 <- exec ec sk2 i2
return (o1, o2)
execIO ec (SkMap s) = mapM (exec ec s)
execIO ec (SkChoice sl sr) = \input ->
case input of
Left i -> exec ec sl i >>= return . Left
Right i -> exec ec sr i >>= return . Right
execIO ec (SkApply) = \(sk, i) -> exec ec sk i
execIO ec (SkRed red z) = \stream -> do
(qi, _) <- execStream ec stream
reducer qi z
where
reducer qi z = do
res <- readQueue qi
case res of
Just vi -> do
z' <- foldlM (\r d -> exec ec red (r, d)) z vi
reducer qi z'
Nothing -> do
return z
|
csic-hs-dsl/hs-skel
|
src/Control/Parallel/HsSkel/Exec/Default.hs
|
bsd-3-clause
| 10,740
| 0
| 30
| 4,487
| 3,246
| 1,585
| 1,661
| 246
| 16
|
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE DeriveDataTypeable #-}
----------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TChunkedQueue
-- Copyright : Copyright (c) 2014 Alexander Kondratskiy
-- License : BSD3
-- Maintainer : Alexander Kondratskiy <kholdstare0.0@gmail.com>
-- Portability : non-portable (GHC STM, DeriveDataTypeable)
--
-- A version of "Control.Concurrent.STM.TQueue" that allows complete draining.
-- This makes it possible to chunk items based on a timeout or a settle
-- period. This is useful when items/requests arriving through the queue are
-- too granular and have to be combined, while retaining responsiveness.
--
-- Some capabilities of @TQueue@ are missing (such as unget) due to design
-- tradeoffs.
--
-- /Since: 0.1.0/
------------------------------------------------------------------
module Control.Concurrent.STM.TChunkedQueue (
-- * The TChunkedQueue type
TChunkedQueue,
ChunkedQueue,
consumeQueue,
-- ** Creating TChunkedQueues
newTChunkedQueue,
newTChunkedQueueIO,
-- ** Draining TChunkedQueues
drainTChunkedQueue,
tryDrainTChunkedQueue,
-- ** Writing to TChunkedQueues
writeTChunkedQueue,
writeManyTChunkedQueue,
-- ** Predicates
isEmptyTChunkedQueue,
-- * Chunked operations
drainAndSettleTChunkedQueue,
drainWithTimeoutTChunkedQueue,
) where
import Data.Typeable (Typeable)
import Prelude hiding (reads)
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.STM (STM, retry, atomically)
import Control.Concurrent.STM.TVar
import Control.Concurrent.Async (race)
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM.ChunkedQueue
----------------------------------------------------------------
-- | @TChunkedQueue@ is an abstract type representing a drainable FIFO queue.
data TChunkedQueue a = TChunkedQueue
{-# UNPACK #-} !(TVar (ChunkedQueue a))
deriving Typeable
-- | Build and return a new instance of @TChunkedQueue@
newTChunkedQueue :: STM (TChunkedQueue a)
newTChunkedQueue = TChunkedQueue <$> newTVar (ChunkedQueue [])
-- | @IO@ version of 'newTChunkedQueue'
newTChunkedQueueIO :: IO (TChunkedQueue a)
newTChunkedQueueIO = TChunkedQueue <$> newTVarIO (ChunkedQueue [])
-- | Drain everything contained in the @TChunkedQueue@, but block if it is
-- empty. Corollary: never returns empty queue.
drainTChunkedQueue :: TChunkedQueue a -> STM (ChunkedQueue a)
drainTChunkedQueue (TChunkedQueue tChQueue) = do
chQueue <- readTVar tChQueue
case chQueue of
ChunkedQueue [] -> retry
_ -> do
writeTVar tChQueue (ChunkedQueue [])
return chQueue
-- | Drain everything contained in the @TChunkedQueue@. Doesn't block
tryDrainTChunkedQueue :: TChunkedQueue a -> STM (ChunkedQueue a)
tryDrainTChunkedQueue (TChunkedQueue tChQueue) = do
chQueue <- readTVar tChQueue
case chQueue of
ChunkedQueue [] -> return ()
_ -> writeTVar tChQueue (ChunkedQueue [])
return chQueue
-- | Write many values to a @TChunkedQueue@. More efficient than
-- @writeTChunkedQueue@, so prefer using this variant if several items have to
-- be enqueued
writeManyTChunkedQueue :: TChunkedQueue a -> [a] -> STM ()
writeManyTChunkedQueue (TChunkedQueue tChQueue) xs = do
chQueue <- readTVar tChQueue
writeTVar tChQueue $ enqueueMany chQueue xs
-- | Write a value to a @TChunkedQueue@
writeTChunkedQueue :: TChunkedQueue a -> a -> STM ()
writeTChunkedQueue (TChunkedQueue tChQueue) x = do
chQueue <- readTVar tChQueue
writeTVar tChQueue $ enqueueOne chQueue x
-- | Return @True@ if the supplied @TChunkedQueue@ is empty.
isEmptyTChunkedQueue :: TChunkedQueue a -> STM Bool
isEmptyTChunkedQueue (TChunkedQueue tChQueue) = do
ChunkedQueue chunks <- readTVar tChQueue
return $ null chunks
----------------------------------------------------------------
-- | Keep draining the queue until no more items are seen for at least
-- the given timeout period. Blocks if the queue is empty to begin with,
-- and starts timing after the first value appears in the queue.
drainAndSettleTChunkedQueue :: Int -- ^ settle period in microseconds
-> TChunkedQueue a
-> IO (ChunkedQueue a)
drainAndSettleTChunkedQueue delay queue = do
ChunkedQueue chunks <- atomically $ drainTChunkedQueue queue
-- chunks by definition is non-empty here
go chunks
where
go acc = do
threadDelay delay
ChunkedQueue chunks <- atomically $ tryDrainTChunkedQueue queue
case chunks of
[] -> return $ ChunkedQueue acc
_ -> go (chunks ++ acc)
-- | Keep draining the queue for at least the specified time period. Blocks if
-- the queue is empty to begin with, and starts timing as soon as the first
-- value appears in the queue.
drainWithTimeoutTChunkedQueue :: Int -- ^ timeout in microseconds
-> TChunkedQueue a
-> IO (ChunkedQueue a)
drainWithTimeoutTChunkedQueue delay queue = do
stashedQueue <- newTChunkedQueueIO
let transferItems = atomically $ do
items <- drainTChunkedQueue queue
stashedQueue `writeManyTChunkedQueue` (consumeQueue items)
transferItems -- run transfer once before timing, which blocks on empty queue.
withTimeout delay (forever transferItems)
atomically $ drainTChunkedQueue stashedQueue
where
withTimeout t action = void $ action `race` threadDelay t
----------------------------------------------------------------
|
KholdStare/stm-chunked-queues
|
src/Control/Concurrent/STM/TChunkedQueue.hs
|
bsd-3-clause
| 5,747
| 0
| 15
| 1,189
| 905
| 473
| 432
| -1
| -1
|
{-# LANGUAGE RecursiveDo, RankNTypes, ScopedTypeVariables,
NamedFieldPuns, RecordWildCards #-}
module Distribution.Server.Features.Mirror (
MirrorFeature(..),
MirrorResource(..),
initMirrorFeature
) where
import Distribution.Server.Prelude
import Distribution.Server.Framework
import Distribution.Server.Features.Core
import Distribution.Server.Features.Users
import Distribution.Server.Users.State
import Distribution.Server.Packages.Types
import Distribution.Server.Users.Backup
import Distribution.Server.Users.Types
import Distribution.Server.Users.Users hiding (lookupUserName)
import Distribution.Server.Users.Group (UserGroup(..), GroupDescription(..), nullDescription)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import qualified Distribution.Server.Packages.Unpack as Upload
import Distribution.Server.Framework.BackupDump
import Distribution.Server.Util.Parse (unpackUTF8)
import Distribution.PackageDescription.Parsec (parseGenericPackageDescription, runParseResult)
import Distribution.Parsec.Common (showPError, showPWarning)
import qualified Data.ByteString.Lazy as BS.L
import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (formatTime)
import Data.Time.Locale.Compat (defaultTimeLocale)
import qualified Distribution.Server.Util.GZip as GZip
import Distribution.Package
import Distribution.Text
data MirrorFeature = MirrorFeature {
mirrorFeatureInterface :: HackageFeature,
mirrorResource :: MirrorResource,
mirrorGroup :: UserGroup
}
instance IsHackageFeature MirrorFeature where
getFeatureInterface = mirrorFeatureInterface
data MirrorResource = MirrorResource {
mirrorPackageTarball :: Resource,
mirrorPackageUploadTime :: Resource,
mirrorPackageUploader :: Resource,
mirrorCabalFile :: Resource,
mirrorGroupResource :: GroupResource
}
-------------------------------------------------------------------------
initMirrorFeature :: ServerEnv
-> IO (CoreFeature
-> UserFeature
-> IO MirrorFeature)
initMirrorFeature env@ServerEnv{serverStateDir} = do
-- Canonical state
mirrorersState <- mirrorersStateComponent serverStateDir
return $ \core user@UserFeature{..} -> do
-- Tie the knot with a do-rec
rec let (feature, mirrorersGroupDesc)
= mirrorFeature env core user
mirrorersState mirrorersG mirrorR
(mirrorersG, mirrorR) <- groupResourceAt "/packages/mirrorers" mirrorersGroupDesc
return feature
mirrorersStateComponent :: FilePath -> IO (StateComponent AcidState MirrorClients)
mirrorersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "MirrorClients") initialMirrorClients
return StateComponent {
stateDesc = "Mirror clients"
, stateHandle = st
, getState = query st GetMirrorClients
, putState = update st . ReplaceMirrorClients . mirrorClients
, backupState = \_ (MirrorClients clients) -> [csvToBackup ["clients.csv"] $ groupToCSV clients]
, restoreState = MirrorClients <$> groupBackup ["clients.csv"]
, resetState = mirrorersStateComponent
}
mirrorFeature :: ServerEnv
-> CoreFeature
-> UserFeature
-> StateComponent AcidState MirrorClients
-> UserGroup
-> GroupResource
-> (MirrorFeature, UserGroup)
mirrorFeature ServerEnv{serverBlobStore = store}
CoreFeature{ coreResource = coreResource@CoreResource{
packageInPath
, packageTarballInPath
, lookupPackageId
}
, updateAddPackageRevision
, updateAddPackageTarball
, updateSetPackageUploadTime
, updateSetPackageUploader
}
UserFeature{..}
mirrorersState mirrorGroup mirrorGroupResource
= (MirrorFeature{..}, mirrorersGroupDesc)
where
mirrorFeatureInterface = (emptyHackageFeature "mirror") {
featureDesc = "Support direct (PUT) tarball uploads and overrides"
, featureResources =
map ($ mirrorResource) [
mirrorPackageTarball
, mirrorPackageUploadTime
, mirrorPackageUploader
, mirrorCabalFile
] ++
[ groupResource mirrorGroupResource
, groupUserResource mirrorGroupResource
]
, featureState = [abstractAcidStateComponent mirrorersState]
}
mirrorResource = MirrorResource {
mirrorPackageTarball = (extendResource $ corePackageTarball coreResource) {
resourceDesc = [ (PUT, "Upload or replace a package tarball") ]
, resourcePut = [ ("", tarballPut) ]
}
, mirrorPackageUploadTime = (extendResourcePath "/upload-time" $ corePackagePage coreResource) {
resourceDesc = [ (GET, "Get a package upload time")
, (PUT, "Replace package upload time")
]
, resourceGet = [ ("", uploadTimeGet) ]
, resourcePut = [ ("", uploadTimePut) ]
}
, mirrorPackageUploader = (extendResourcePath "/uploader" $ corePackagePage coreResource) {
resourceDesc = [ (GET, "Get a package uploader (username)")
, (PUT, "Replace a package uploader")
]
, resourceGet = [ ("", uploaderGet) ]
, resourcePut = [ ("", uploaderPut) ]
}
, mirrorCabalFile = (extendResource $ coreCabalFile coreResource) {
resourceDesc = [ (PUT, "Replace a package description" ) ]
, resourcePut = [ ("", cabalPut) ]
}
, mirrorGroupResource
}
mirrorersGroupDesc = UserGroup {
groupDesc = nullDescription { groupTitle = "Mirror clients" },
queryUserGroup = queryState mirrorersState GetMirrorClientsList,
addUserToGroup = updateState mirrorersState . AddMirrorClient,
removeUserFromGroup = updateState mirrorersState . RemoveMirrorClient,
groupsAllowedToDelete = [adminGroup],
groupsAllowedToAdd = [adminGroup]
}
-- result: error from unpacking, bad request error, or warning lines
--
-- curl -u admin:admin \
-- -X PUT \
-- -H "Content-Type: application/x-gzip" \
-- --data-binary @$1 \
-- http://localhost:8080/package/$PACKAGENAME/$PACKAGEID.tar.gz
tarballPut :: DynamicPath -> ServerPartE Response
tarballPut dpath = do
uid <- guardAuthorised [InGroup mirrorGroup]
pkgid <- packageTarballInPath dpath
fileContent <- expectCompressedTarball
time <- liftIO getCurrentTime
let uploadinfo = (time, uid)
res <- liftIO $ BlobStorage.addWith store fileContent $ \fileContent' ->
let filename = display pkgid <.> "tar.gz"
in case Upload.unpackPackageRaw filename fileContent' of
Left err -> return $ Left err
Right x ->
do let decompressedContent = GZip.decompressNamed filename fileContent'
blobIdDecompressed <- BlobStorage.add store decompressedContent
return $ Right (x, blobIdDecompressed)
case res of
Left err -> badRequest (toResponse err)
Right ((((pkg, _pkgStr), warnings), blobIdDecompressed), blobId) -> do
infoGz <- liftIO $ blobInfoFromId store blobId
let tarball = PkgTarball {
pkgTarballGz = infoGz
, pkgTarballNoGz = blobIdDecompressed
}
existed <- updateAddPackageTarball (packageId pkg) tarball uploadinfo
if existed
then return . toResponse $ unlines warnings
else errNotFound "Package not found" []
uploaderGet dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
userdb <- queryGetUserDb
return $ toResponse $ display (userIdToName userdb (pkgLatestUploadUser pkg))
uploaderPut :: DynamicPath -> ServerPartE Response
uploaderPut dpath = do
guardAuthorised_ [InGroup mirrorGroup]
pkgid <- packageInPath dpath
nameContent <- expectTextPlain
let uname = UserName (unpackUTF8 nameContent)
uid <- lookupUserName uname
existed <- updateSetPackageUploader pkgid uid
if existed
then return $ toResponse "Updated uploader OK"
else errNotFound "Package not found" []
uploadTimeGet :: DynamicPath -> ServerPartE Response
uploadTimeGet dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
return $ toResponse $ formatTime defaultTimeLocale "%c"
(pkgLatestUploadTime pkg)
-- curl -H 'Content-Type: text/plain' -u admin:admin -X PUT -d "Tue Oct 18 20:54:28 UTC 2010" http://localhost:8080/package/edit-distance-0.2.1/upload-time
uploadTimePut :: DynamicPath -> ServerPartE Response
uploadTimePut dpath = do
guardAuthorised_ [InGroup mirrorGroup]
pkgid <- packageInPath dpath
timeContent <- expectTextPlain
case parseTimeMaybe "%c" (unpackUTF8 timeContent) of
Nothing -> errBadRequest "Could not parse upload time" []
Just t -> do
existed <- updateSetPackageUploadTime pkgid t
if existed
then return $ toResponse "Updated upload time OK"
else errNotFound "Package not found" []
-- return: error from parsing, bad request error, or warning lines
cabalPut :: DynamicPath -> ServerPartE Response
cabalPut dpath = do
uid <- guardAuthorised [InGroup mirrorGroup]
pkgid :: PackageId <- packageInPath dpath
fileContent <- expectTextPlain
time <- liftIO getCurrentTime
let uploadData = (time, uid)
filename = display pkgid <.> "cabal"
case runParseResult $ parseGenericPackageDescription $ BS.L.toStrict $ fileContent of
(_, Left (_, err:_)) -> badRequest (toResponse $ showPError filename err)
(_, Left (_, [])) -> badRequest (toResponse "failed to parse")
(_, Right pkg) | pkgid /= packageId pkg ->
errBadRequest "Wrong package Id"
[MText $ "Expected " ++ display pkgid
++ " but found " ++ display (packageId pkg)]
(warnings, Right pkg) -> do
updateAddPackageRevision (packageId pkg)
(CabalFileText fileContent) uploadData
return . toResponse $ unlines $ map (showPWarning filename) warnings
|
edsko/hackage-server
|
Distribution/Server/Features/Mirror.hs
|
bsd-3-clause
| 10,994
| 0
| 23
| 3,214
| 2,181
| 1,182
| 999
| 197
| 10
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Vector (Vector)
import qualified Data.Vector as V
import Servant.Common.BaseUrl
import Test.Tasty
import Test.Tasty.HUnit
import qualified Data.Aeson as A
import Network.IPFS
runApiary :: IPFS a -> IO (Either IPFSError a)
runApiary = runIPFS' (BaseUrl Http "private-7fa49-micxjo.apiary-mock.com" 80 "")
assertRequest :: (Eq a, Show a) => IPFS a -> a -> Assertion
assertRequest req expected = do
Right res <- runApiary req
res @?= expected
apiaryTests :: TestTree
apiaryTests = testGroup "Apiary Tests"
[ testCase "getVersion" $
assertRequest getVersion (Version "0.4.0-dev" Nothing "3")
, testCase "getBootstrapList" $
assertRequest getBootstrapList expectedBootstrapList
, testCase "getBlock" $ do
let mh = Multihash "QmT78zSuBmuS4z925WZfrqQ1qHaJ56DQaTfyMUF7F8ff5o"
assertRequest (getBlock mh) "hello world"
, testCase "getBlockStat" $ do
let mh = Multihash "QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ"
assertRequest (getBlockStat mh) BlockStat { _bStatHash = mh
, _bStatSize = 55
}
, testCase "getFileList" $ do
let mh = Multihash "QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ"
assertRequest (getFileList mh) (expectedFileList mh)
, testCase "resolveName" $ do
let name = "QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ"
let path = "/ipfs/QmW2WQi7j6c7UgJTarActp7tDNikE4B2qXtFCfLPdsgaTQ"
assertRequest (resolveName name) (Just path)
, testCase "getConfigValue" $ do
assertRequest (getConfigValue "API.HTTPHeaders") A.Null
]
expectedBootstrapList :: Vector Multiaddr
expectedBootstrapList = V.fromList $ map Multiaddr
[ "/ip4/104.236.176.52/tcp/4001/ipfs/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z"
, "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"
, "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM"
, "/ip4/162.243.248.213/tcp/4001/ipfs/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm"
, "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu"
, "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64"
, "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd"
, "/ip4/178.62.61.185/tcp/4001/ipfs/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3"
, "/ip4/104.236.151.122/tcp/4001/ipfs/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx"
]
expectedFileList :: Multihash -> FileStat
expectedFileList mh = FileStat { _fStatHash = mh
, _fStatSize = 0
, _fStatType = Directory
, _fStatLinks = Just (V.singleton link)
}
where link = FileLink { _fLinkName = "cat.jpg"
, _fLinkHash = Multihash "Qmd286K6pohQcTKYqnS1YhWrCiS4gz7Xi34sdwMe9USZ7u"
, _fLinkSize = 443230
, _fLinkType = File
}
tests :: TestTree
tests = testGroup "ipfs-client" [apiaryTests]
main :: IO ()
main = defaultMain tests
|
micxjo/hs-ipfs-client
|
test/test.hs
|
bsd-3-clause
| 3,280
| 0
| 13
| 766
| 588
| 306
| 282
| 60
| 1
|
{- |
Module : $Header$
Description : Interface to the Isabelle theorem prover.
Copyright : (c) Jonathan von Schroeder, DFKI Bremen 2012
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Jonathan von Schroeder <jonathan.von_schroeder@dfki.de>
Stability : provisional
Portability : non-portable
Isabelle theorem prover for THF0
-}
module THF.ProveIsabelle ( isaProver, nitpickProver,
refuteProver, sledgehammerProver ) where
import THF.SZSProver
import Interfaces.GenericATPState
import Data.List (isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe)
pfun :: String -> ProverFuncs
pfun tool = ProverFuncs {
cfgTimeout = maybe 20 (+ 10) . timeLimit,
proverCommand = \ tout tmpFile _ ->
return ("time", ["isabelle", tool, show (tout - 10), tmpFile]),
getMessage = \ res' pout _ ->
if null res' then concat $ filter (isPrefixOf "*** ") (lines pout)
else res',
getTimeUsed = \ line -> case fromMaybe "" $ stripPrefix "real\t" line of
[] -> Nothing
s -> let sp p str = case dropWhile p str of
"" -> []
s' -> w : sp p s''
where (w, s'') = break p s'
(m : secs : _) = sp (== 'm') s
in Just $ read m * 60 + read secs }
createIsaSZSProver :: String -> String -> ProverFuncs -> ProverType
createIsaSZSProver = createSZSProver "isabelle"
isaProver :: ProverType
isaProver = createIsaSZSProver "Isabelle (automated)"
"Automated Isabelle calling all tools available"
$ pfun "tptp_isabelle_demo"
nitpickProver :: ProverType
nitpickProver = createIsaSZSProver "Isabelle (nitpick)"
"Nitpick for TPTP problems"
$ pfun "tptp_nitpick"
refuteProver :: ProverType
refuteProver = createIsaSZSProver "Isabelle (refute)"
"refute for TPTP problems"
$ pfun "tptp_refute"
sledgehammerProver :: ProverType
sledgehammerProver = createIsaSZSProver "Isabelle (sledgehammer)"
"sledgehammer for TPTP problems"
$ pfun "tptp_sledgehammer"
|
mariefarrell/Hets
|
THF/ProveIsabelle.hs
|
gpl-2.0
| 1,967
| 18
| 16
| 420
| 440
| 235
| 205
| 40
| 4
|
{-# 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.CloudHSM.ListAvailableZones
-- 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.
-- | Lists the Availability Zones that have available AWS CloudHSM capacity.
--
-- <http://docs.aws.amazon.com/cloudhsm/latest/dg/API_ListAvailableZones.html>
module Network.AWS.CloudHSM.ListAvailableZones
(
-- * Request
ListAvailableZones
-- ** Request constructor
, listAvailableZones
-- * Response
, ListAvailableZonesResponse
-- ** Response constructor
, listAvailableZonesResponse
-- ** Response lenses
, lazrAZList
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudHSM.Types
import qualified GHC.Exts
data ListAvailableZones = ListAvailableZones
deriving (Eq, Ord, Read, Show, Generic)
-- | 'ListAvailableZones' constructor.
listAvailableZones :: ListAvailableZones
listAvailableZones = ListAvailableZones
newtype ListAvailableZonesResponse = ListAvailableZonesResponse
{ _lazrAZList :: List "AZList" Text
} deriving (Eq, Ord, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList ListAvailableZonesResponse where
type Item ListAvailableZonesResponse = Text
fromList = ListAvailableZonesResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _lazrAZList
-- | 'ListAvailableZonesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lazrAZList' @::@ ['Text']
--
listAvailableZonesResponse :: ListAvailableZonesResponse
listAvailableZonesResponse = ListAvailableZonesResponse
{ _lazrAZList = mempty
}
-- | The list of Availability Zones that have available AWS CloudHSM capacity.
lazrAZList :: Lens' ListAvailableZonesResponse [Text]
lazrAZList = lens _lazrAZList (\s a -> s { _lazrAZList = a }) . _List
instance ToPath ListAvailableZones where
toPath = const "/"
instance ToQuery ListAvailableZones where
toQuery = const mempty
instance ToHeaders ListAvailableZones
instance ToJSON ListAvailableZones where
toJSON = const (toJSON Empty)
instance AWSRequest ListAvailableZones where
type Sv ListAvailableZones = CloudHSM
type Rs ListAvailableZones = ListAvailableZonesResponse
request = post "ListAvailableZones"
response = jsonResponse
instance FromJSON ListAvailableZonesResponse where
parseJSON = withObject "ListAvailableZonesResponse" $ \o -> ListAvailableZonesResponse
<$> o .:? "AZList" .!= mempty
|
romanb/amazonka
|
amazonka-cloudhsm/gen/Network/AWS/CloudHSM/ListAvailableZones.hs
|
mpl-2.0
| 3,407
| 0
| 10
| 674
| 428
| 257
| 171
| 53
| 1
|
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- Module : Text.XML.Expat.Pickle.Generic
-- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- Berkeley Software Distribution License, v. 3.0.
-- You can obtain it at
-- http://http://opensource.org/licenses/BSD-3-Clause.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Text.XML.Expat.Pickle.Generic
(
-- * Class
IsXML (..)
-- * Functions
, toXML
, toIndentedXML
, fromXML
-- * Data Types
, Node
, XMLPU (..)
-- * Options
, XMLOptions (..)
, defaultXMLOptions
, namespacedXMLOptions
-- * Generics
, XMLGeneric
, genericXMLPickler
-- * Combinators
, xpWrap
, xpList
, xpElemList
, xpElem
, xpSum
, xpEither
, xpPrim
, xpOption
, xpPair
, xpTriple
, xp4Tuple
, xp5Tuple
, xp6Tuple
, xp7Tuple
, xpUnit
, xpLift
, xpEmpty
, xpConst
, xpText
, xpText0
, xpContent
, xpFindMatches
-- * Re-exported Tag Helpers
, module Text.XML.Expat.Internal.Namespaced
, module Text.XML.Expat.Internal.Qualified
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Char (isLower)
import Data.Either
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import Data.Text.Encoding
import GHC.Generics
import Text.XML.Expat.Format
import Text.XML.Expat.Internal.Namespaced
import Text.XML.Expat.Internal.Qualified hiding (fromQualified)
import Text.XML.Expat.Tree hiding (Node, fromQualified)
--
-- Class
--
type Node = NNode ByteString
data XMLPU t a = XMLPU
{ pickleTree :: a -> t
, unpickleTree :: t -> Either String a
, root :: Maybe (NName ByteString)
}
type PU = XMLPU
class IsXML a where
xmlPickler :: PU [Node] a
default xmlPickler :: (Generic a, GIsXML (Rep a)) => PU [Node] a
xmlPickler = genericXMLPickler defaultXMLOptions
--
-- Functions
--
toXML :: IsXML a => a -> ByteString
toXML = toIndentedXML 2
toIndentedXML :: IsXML a => Int -> a -> ByteString
toIndentedXML i = format'
. indent i
. fromQualified
. fromNamespaced
. pickleTree (xpRoot xmlPickler)
fromXML :: IsXML a => ByteString -> Either String a
fromXML = either (Left . show) unpickle . parse' defaultParseOptions
where
unpickle = unpickleTree (xpRoot xmlPickler) . toNamespaced . toQualified
--
-- Options
--
data XMLOptions = XMLOptions
{ xmlCtorModifier :: String -> NName ByteString
-- ^ Function applied to constructor tags.
, xmlFieldModifier :: String -> NName ByteString
-- ^ Function applied to record field labels.
, xmlListElement :: NName ByteString
-- ^ Default element name to wrap list items with.
}
defaultXMLOptions :: XMLOptions
defaultXMLOptions = XMLOptions
{ xmlCtorModifier = mkAnNName . BS.pack
, xmlFieldModifier = mkAnNName . BS.pack . dropWhile isLower
, xmlListElement = mkAnNName "Value"
}
namespacedXMLOptions :: ByteString -> XMLOptions
namespacedXMLOptions ns = XMLOptions
{ xmlCtorModifier = mkNName ns . BS.pack
, xmlFieldModifier = mkNName ns . BS.pack . dropWhile isLower
, xmlListElement = mkNName ns "Value"
}
--
-- Generics
--
type XMLGeneric a = (Generic a, GIsXML (Rep a)) => PU [Node] a
genericXMLPickler opts =
(to, from) `xpWrap` (gXMLPickler opts) (genericXMLPickler opts)
class GIsXML f where
gXMLPickler :: XMLOptions -> PU [Node] a -> PU [Node] (f a)
instance IsXML a => GIsXML (K1 i a) where
gXMLPickler _ _ = (K1, unK1) `xpWrap` xmlPickler
instance (GIsXML a, GIsXML b) => GIsXML (a :+: b) where
gXMLPickler opts f = gXMLPickler opts f `xpSum` gXMLPickler opts f
instance (GIsXML a, GIsXML b) => GIsXML (a :*: b) where
gXMLPickler opts f = xpWrap
(uncurry (:*:), \(a :*: b) -> (a, b))
(gXMLPickler opts f `xpPair` gXMLPickler opts f)
instance (Datatype d, GIsXML a) => GIsXML (D1 d a) where
gXMLPickler opts = xpWrap (M1, unM1) . gXMLPickler opts
instance (Constructor c, GIsXML a) => GIsXML (C1 c a) where
gXMLPickler opts f = (xpWrap (M1, unM1) $ gXMLPickler opts f)
{ root = Just . xmlCtorModifier opts $ conName (undefined :: C1 c a p)
}
instance (Selector s, GIsXML a) => GIsXML (S1 s a) where
gXMLPickler opts f = xpElem
(xmlFieldModifier opts $ selName (undefined :: S1 s a p))
((M1, unM1) `xpWrap` gXMLPickler opts f)
instance (Selector s, IsXML a) => GIsXML (S1 s (K1 i [a])) where
gXMLPickler opts _ = xpDefault
(xmlFieldModifier opts $ selName (undefined :: t s (K1 i [a]) p))
(M1 $ K1 [])
((M1 . K1, unK1 . unM1) `xpWrap` xpList (xpElem key pu))
where
key = fromMaybe (xmlListElement opts) $ root pu
pu = xmlPickler
instance (Selector s, IsXML a) => GIsXML (S1 s (K1 i (Maybe a))) where
gXMLPickler opts _ =
(M1 . K1, unK1 . unM1) `xpWrap` xpOption (xpElem name xmlPickler)
where
name = xmlFieldModifier opts $ selName (undefined :: t s (K1 i (Maybe a)) p)
--
-- Combinators
--
xpRoot :: PU [Node] a -> PU Node a
xpRoot pu = pu
{ pickleTree =
(maybe head (\n -> Element n []) $ root pu) . pickleTree pu
, unpickleTree = \t -> case t of
(Element _ _ cs) -> unpickleTree pu cs
t1 -> unpickleTree pu [t1]
}
xpWrap :: (a -> b, b -> a) -> PU [n] a -> PU [n] b
xpWrap (f, g) pu = pu
{ pickleTree = pickleTree pu . g
, unpickleTree = fmap f . unpickleTree pu
}
xpElemList :: NName ByteString -> PU [Node] a -> PU [Node] [a]
xpElemList name = xpList . xpElem name
xpFindMatches :: PU [Node] a -> PU [Node] [a]
xpFindMatches pu = pu
{ pickleTree = concatMap (pickleTree pu)
, unpickleTree = Right . snd . partitionEithers . unpickle
}
where
unpickle (e@(Element _ _ _):es) = unpickleTree pu [e] : unpickle es
unpickle (_:es) = unpickle es
unpickle [] = []
xpList :: PU [Node] a -> PU [Node] [a]
xpList pu = pu
{ pickleTree = concatMap (pickleTree pu)
, unpickleTree = concatEithers . unpickle
}
where
unpickle (e@(Element _ _ _):es) = unpickleTree pu [e] : unpickle es
unpickle (_:es) = unpickle es
unpickle [] = []
concatEithers xs = case partitionEithers xs of
([], rs) -> Right rs
(l:_, _) -> Left l
xpElem :: NName ByteString -> PU [Node] a -> PU [Node] a
xpElem name pu = XMLPU
{ root = Just name
, pickleTree = \x -> [Element name [] (pickleTree pu x)]
, unpickleTree = \t ->
let children = map matching t
in case catMaybes children of
[] -> Left $ "can't find " ++ tag
(x:_) -> case x of
Left e -> Left $ "in " ++ tag ++ ", " ++ e
r -> r
}
where
matching (Element n _ cs)
| n == name = Just $ unpickleTree pu cs
matching _ = Nothing
tag = "<" ++ show name ++ ">"
xpDefault :: NName ByteString -> a -> PU [Node] a -> PU [Node] a
xpDefault name val pu = XMLPU
{ root = Just name
, pickleTree = \x -> [Element name [] (pickleTree pu x)]
, unpickleTree = \t ->
let children = map matching t
in case catMaybes children of
[] -> Right val
(x:_) -> case x of
Left e -> Left $ "in " ++ tag ++ ", " ++ e
r -> r
}
where
matching (Element n _ cs)
| n == name = Just $ unpickleTree pu cs
matching _ = Nothing
tag = "<" ++ show name ++ ">"
xpSum :: PU [t] (f r) -> PU [t] (g r) -> PU [t] ((f :+: g) r)
xpSum left right = (inp, out) `xpWrap` xpEither left right
where
inp (Left x) = L1 x
inp (Right x) = R1 x
out (L1 x) = Left x
out (R1 x) = Right x
xpEither :: PU [t] a -> PU [t] b -> PU [t] (Either a b)
xpEither pa pb = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb]
, pickleTree = either (pickleTree pa) (pickleTree pb)
, unpickleTree = \t -> case unpickleTree pa t of
Right x -> Right . Left $ x
Left _ -> Right `fmap` unpickleTree pb t
}
xpPrim :: (Read a, Show a) => PU ByteString a
xpPrim = XMLPU
{ root = Nothing
, pickleTree = BS.pack . show
, unpickleTree = \t ->
let s = BS.unpack t
in case reads s of
[(x, "")] -> Right x
_ -> Left $ "failed to read text: " ++ s
}
xpOption :: PU [n] a -> PU [n] (Maybe a)
xpOption pu = pu
{ pickleTree = maybe [] (pickleTree pu)
, unpickleTree = Right . either (const Nothing) Just . unpickleTree pu
}
xpPair :: PU [n] a -> PU [n] b -> PU [n] (a, b)
xpPair pa pb = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb]
, pickleTree = \(a, b) -> concat [pickleTree pa a, pickleTree pb b]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t) of
(Right a, Right b) -> Right (a, b)
(Left e, _) -> Left $ "in 1st of pair, " ++ e
(_, Left e) -> Left $ "in 2nd of pair, " ++ e
}
xpTriple :: PU [n] a -> PU [n] b -> PU [n] c -> PU [n] (a, b, c)
xpTriple pa pb pc = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb, root pc]
, pickleTree = \(a, b, c) ->
concat [pickleTree pa a, pickleTree pb b, pickleTree pc c]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t, unpickleTree pc t) of
(Right a, Right b, Right c) -> Right (a, b, c)
(Left e, _, _) -> Left $ "in 1st of triple, " ++ e
(_, Left e, _) -> Left $ "in 2nd of triple, " ++ e
(_, _, Left e) -> Left $ "in 3rd of triple, " ++ e
}
xp4Tuple :: PU [n] a -> PU [n] b -> PU [n] c -> PU [n] d -> PU [n] (a, b, c, d)
xp4Tuple pa pb pc pd = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb, root pc, root pd]
, pickleTree = \(a, b, c, d) ->
concat [pickleTree pa a, pickleTree pb b, pickleTree pc c, pickleTree pd d]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t, unpickleTree pc t,
unpickleTree pd t) of
(Right a, Right b, Right c, Right d) -> Right (a, b, c, d)
(Left e, _, _, _) -> Left $ "in 1st of 4-tuple, " ++ e
(_, Left e, _, _) -> Left $ "in 2nd of 4-tuple, " ++ e
(_, _, Left e, _) -> Left $ "in 3rd of 4-tuple, " ++ e
(_, _, _, Left e) -> Left $ "in 4th of 4-tuple, " ++ e
}
xp5Tuple :: PU [n] a -> PU [n] b -> PU [n] c -> PU [n] d -> PU [n] e -> PU [n] (a, b, c, d, e)
xp5Tuple pa pb pc pd pe = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb, root pc, root pd, root pe]
, pickleTree = \(a, b, c, d, e) ->
concat [pickleTree pa a, pickleTree pb b, pickleTree pc c, pickleTree pd d, pickleTree pe e]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t, unpickleTree pc t,
unpickleTree pd t, unpickleTree pe t) of
(Right a, Right b, Right c, Right d, Right e) -> Right (a, b, c, d, e)
(Left e, _, _, _, _) -> Left $ "in 1st of 5-tuple, " ++ e
(_, Left e, _, _, _) -> Left $ "in 2nd of 5-tuple, " ++ e
(_, _, Left e, _, _) -> Left $ "in 3rd of 5-tuple, " ++ e
(_, _, _, Left e, _) -> Left $ "in 4th of 5-tuple, " ++ e
(_, _, _, _, Left e) -> Left $ "in 5th of 5-tuple, " ++ e
}
xp6Tuple :: Show n => PU [n] a -> PU [n] b -> PU [n] c -> PU [n] d -> PU [n] e -> PU [n] f -> PU [n] (a, b, c, d, e, f)
xp6Tuple pa pb pc pd pe pf = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb, root pc, root pd, root pe, root pf]
, pickleTree = \(a, b, c, d, e, f) ->
concat [pickleTree pa a, pickleTree pb b, pickleTree pc c, pickleTree pd d, pickleTree pe e, pickleTree pf f]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t, unpickleTree pc t,
unpickleTree pd t, unpickleTree pe t, unpickleTree pf t) of
(Right a, Right b, Right c, Right d, Right e', Right f) -> Right (a, b, c, d, e', f)
(Left e, _, _, _, _, _) -> Left $ "in 1st of 6-tuple, " ++ e
(_, Left e, _, _, _, _) -> Left $ "in 2nd of 6-tuple, " ++ e
(_, _, Left e, _, _, _) -> Left $ "in 3rd of 6-tuple, " ++ e
(_, _, _, Left e, _, _) -> Left $ "in 4th of 6-tuple, " ++ e
(_, _, _, _, Left e, _) -> Left $ "in 5th of 6-tuple, " ++ e
(_, _, _, _, _, Left e) -> Left $ "in 6th of 6-tuple, " ++ e
}
xp7Tuple :: Show n => PU [n] a -> PU [n] b -> PU [n] c -> PU [n] d -> PU [n] e -> PU [n] f -> PU [n] g -> PU [n] (a, b, c, d, e, f, g)
xp7Tuple pa pb pc pd pe pf pg = XMLPU
{ root = listToMaybe $ catMaybes [root pa, root pb, root pc, root pd, root pe, root pf, root pg]
, pickleTree = \(a, b, c, d, e, f, g) ->
concat [pickleTree pa a, pickleTree pb b, pickleTree pc c, pickleTree pd d, pickleTree pe e, pickleTree pf f, pickleTree pg g]
, unpickleTree = \t ->
case (unpickleTree pa t, unpickleTree pb t, unpickleTree pc t,
unpickleTree pd t, unpickleTree pe t, unpickleTree pf t, unpickleTree pg t) of
(Right a, Right b, Right c, Right d, Right e', Right f, Right g) -> Right (a, b, c, d, e', f, g)
(Left e, _, _, _, _, _, _) -> Left $ "in 1st of 7-tuple, " ++ e
(_, Left e, _, _, _, _, _) -> Left $ "in 2nd of 7-tuple, " ++ e
(_, _, Left e, _, _, _, _) -> Left $ "in 3rd of 7-tuple, " ++ e
(_, _, _, Left e, _, _, _) -> Left $ "in 4th of 7-tuple, " ++ e
(_, _, _, _, Left e, _, _) -> Left $ "in 5th of 7-tuple, " ++ e
(_, _, _, _, _, Left e, _) -> Left $ "in 6th of 7-tuple, " ++ e
(_, _, _, _, _, _, Left e) -> Left $ "in 7th of 7-tuple, " ++ e
}
xpUnit :: PU [n] ()
xpUnit = xpLift ()
xpLift :: a -> PU [n] a
xpLift a = XMLPU
{ root = Nothing
, pickleTree = const []
, unpickleTree = const $ Right a
}
xpEmpty :: (Read a, Show a) => Maybe ByteString -> PU [Node] a
xpEmpty mns = XMLPU
{ root = Nothing
, pickleTree = \x -> [Element (name x) [] []]
, unpickleTree = \t -> case t of
[(Element n _ _)] -> let s = BS.unpack $ nnLocalPart n
in case reads s of
[(x, "")] -> Right x
_ -> Left $ "failed to read: " ++ s
l -> Left $ "expected empty element, got: " ++ show l
}
where
name x = maybe (mkAnNName local) (`mkNName` local) mns
where
local = BS.pack $ show x
xpConst :: Show a => ByteString -> a -> XMLPU [Node] a
xpConst ns val = XMLPU
{ root = Just name
, pickleTree = const [Element name [] []]
, unpickleTree = const $ Right val
}
where
name = mkNName ns . BS.pack $ show val
xpText :: PU ByteString ByteString
xpText = XMLPU
{ root = Nothing
, pickleTree = id
, unpickleTree = \t -> if BS.null t then Left "empty text" else Right t
}
xpText0 :: PU ByteString ByteString
xpText0 = XMLPU
{ root = Nothing
, pickleTree = id
, unpickleTree = Right
}
xpContent :: PU ByteString a -> PU [Node] a
xpContent pu = XMLPU
{ root = root pu
, pickleTree = \t ->
let txt = pickleTree pu t
in if gxNullString txt then [] else [Text txt]
, unpickleTree = unpickleTree pu . mconcat . map extract
}
where
extract (Element _ _ cs) = mconcat $ map extract cs
extract (Text txt) = txt
--
-- Instances
--
instance IsXML a => IsXML (Maybe a) where
xmlPickler = xpOption xmlPickler
instance (IsXML a, IsXML b) => IsXML (Either a b) where
xmlPickler = xmlPickler `xpEither` xmlPickler
instance IsXML Int where
xmlPickler = xpContent xpPrim
instance IsXML Integer where
xmlPickler = xpContent xpPrim
instance IsXML Double where
xmlPickler = xpContent xpPrim
instance IsXML Float where
xmlPickler = xpContent xpPrim
instance IsXML ByteString where
xmlPickler = xpContent xpText
instance IsXML Text where
xmlPickler = (decodeUtf8, encodeUtf8) `xpWrap` xmlPickler
--
-- Qualified Prefix Hack
--
fromQualified :: (NodeClass n c, GenericXMLString text)
=> n c (QName text) text
-> n c text text
fromQualified = mapAllTags tag
where
tag (QName Nothing local) = local
tag (QName (Just prefix) local)
| prefix == xmlns = prefix
| otherwise = local
|
brendanhay/amazonka-limited
|
src/Text/XML/Expat/Pickle/Generic.hs
|
mpl-2.0
| 17,804
| 0
| 19
| 5,885
| 6,873
| 3,690
| 3,183
| 361
| 8
|
module Main where
main :: IO ()
main = do
putStrLn $ show $ fibonacci <$> arr
where
arr = [0..10]
fibrecursive 0 presum sum = sum
fibrecursive n presum sum = fibrecursive (n-1) sum (sum+presum)
fibonacci n = fibrecursive n 0 1
|
rahulmutt/ghcvm
|
tests/suite/codegen/run/RecursiveFib2.hs
|
bsd-3-clause
| 259
| 0
| 9
| 75
| 106
| 55
| 51
| 8
| 1
|
module FP.Monads where
import FP.Core
---------------------
-- Monadic Effects --
---------------------
-- ID {{{
newtype ID a = ID { unID :: a }
deriving
( Eq, Ord
, PartialOrder
, Monoid
, Bot
, Top
, Join
, JoinLattice
)
instance Unit ID where unit = ID
instance Functor ID where map f = ID . f . unID
instance FunctorM ID where mapM f = map ID . f . unID
instance Product ID where aM <*> bM = ID $ (unID aM, unID bM)
instance Applicative ID where fM <@> aM = ID $ unID fM $ unID aM
instance Bind ID where aM >>= k = k $ unID aM
instance Monad ID
instance Functorial Bot ID where functorial = W
instance Functorial Top ID where functorial = W
instance Functorial Join ID where functorial = W
instance Functorial JoinLattice ID where functorial = W
instance Functorial Monoid ID where functorial = W
newtype IDT m a = IDT { unIDT :: m a }
-- }}}
-- MaybeT {{{
maybeCommute :: (Functor m) => MaybeT (MaybeT m) ~> MaybeT (MaybeT m)
maybeCommute aMM = MaybeT $ MaybeT $ ff ^$ unMaybeT $ unMaybeT aMM
where
ff Nothing = Just Nothing
ff (Just Nothing) = Nothing
ff (Just (Just a)) = Just (Just a)
instance (Unit m) => Unit (MaybeT m) where unit = MaybeT . unit . Just
instance (Functor m) => Functor (MaybeT m) where map f = MaybeT . f ^^. unMaybeT
instance (Functor m, Product m) => Product (MaybeT m) where
aM1 <*> aM2 = MaybeT $ uncurry ff ^$ unMaybeT aM1 <*> unMaybeT aM2
where
ff Nothing _ = Nothing
ff _ Nothing = Nothing
ff (Just a1) (Just a2) = Just (a1, a2)
instance (Functor m, Applicative m) => Applicative (MaybeT m) where
fM <@> aM = MaybeT $ ff ^@ unMaybeT fM <$> unMaybeT aM
where
ff Nothing _ = Nothing
ff _ Nothing = Nothing
ff (Just f) (Just a) = Just $ f a
instance (Monad m) => Bind (MaybeT m) where
aM >>= k = MaybeT $ do
aM' <- unMaybeT aM
case aM' of
Nothing -> return Nothing
Just a -> unMaybeT $ k a
instance (Monad m) => Monad (MaybeT m)
instance FunctorUnit2 MaybeT where funit2 = MaybeT .^ Just
instance FunctorJoin2 MaybeT where
fjoin2 = MaybeT . ff ^. unMaybeT . unMaybeT
where
ff Nothing = Nothing
ff (Just aM) = aM
instance FunctorFunctor2 MaybeT where
fmap2 :: (Functor m, Functor n) => (m ~> n) -> MaybeT m ~> MaybeT n
fmap2 f = MaybeT . f . unMaybeT
instance (Functor m) => MonadMaybe (MaybeT m) where
maybeI :: MaybeT m ~> MaybeT (MaybeT m)
maybeI = maybeCommute . funit2
maybeE :: MaybeT (MaybeT m) ~> MaybeT m
maybeE = fjoin2 . maybeCommute
-- }}}
-- ErrorT {{{
mapError :: (Functor m) => (e1 -> e2) -> ErrorT e1 m a -> ErrorT e2 m a
mapError f = ErrorT . mapInl f ^. unErrorT
errorCommute :: (Functor m) => ErrorT e (ErrorT e m) ~> ErrorT e (ErrorT e m)
errorCommute = ErrorT . ErrorT . ff ^. unErrorT . unErrorT
where
ff (Inl e) = Inr (Inl e)
ff (Inr (Inl e)) = Inl e
ff (Inr (Inr a)) = Inr $ Inr a
instance (Unit m) => Unit (ErrorT e m) where
unit a = ErrorT $ unit $ Inr a
instance (Functor m) => Functor (ErrorT e m) where
map f aM = ErrorT $ mapInr f ^$ unErrorT aM
instance (Functor m, Product m) => Product (ErrorT e m) where
aM1 <*> aM2 = ErrorT $ ff ^$ unErrorT aM1 <*> unErrorT aM2
where
ff (Inl e, _) = Inl e
ff (_, Inl e) = Inl e
ff (Inr a, Inr b) = Inr (a, b)
instance (Functor m, Applicative m) => Applicative (ErrorT e m) where
fM <@> aM = ErrorT $ ff ^@ unErrorT fM <$> unErrorT aM
where
ff (Inl e) _ = Inl e
ff _ (Inl e) = Inl e
ff (Inr f) (Inr a) = Inr $ f a
instance (Unit m, Functor m, Bind m) => Bind (ErrorT e m) where
aM >>= k = ErrorT $ do
aeM <- unErrorT aM
case aeM of
Inl e -> unit $ Inl e
Inr a -> unErrorT $ k a
instance (Monad m) => Monad (ErrorT e m) where
instance FunctorUnit2 (ErrorT e) where
funit2 :: (Functor m) => m ~> ErrorT e m
funit2 aM = ErrorT $ Inr ^$ aM
instance FunctorJoin2 (ErrorT e) where
fjoin2 :: (Functor m) => ErrorT e (ErrorT e m) ~> ErrorT e m
fjoin2 = ErrorT . ff ^. unErrorT . unErrorT
where
ff (Inl e) = Inl e
ff (Inr ea) = ea
instance FunctorFunctor2 (ErrorT e) where
fmap2 :: (Functor m, Functor n) => m ~> n -> ErrorT e m ~> ErrorT e n
fmap2 f = ErrorT . f . unErrorT
instance (Functor m) => MonadError e (ErrorT e m) where
errorI :: ErrorT e m ~> ErrorT e (ErrorT e m)
errorI = errorCommute . funit2
errorE :: ErrorT e (ErrorT e m) ~> ErrorT e m
errorE = fjoin2 . errorCommute
-- }}}
-- ReaderT {{{
type Reader r = ReaderT r ID
runReader :: r -> Reader r a -> a
runReader r = unID . runReaderT r
readerCommute :: ReaderT r1 (ReaderT r2 m) ~> ReaderT r2 (ReaderT r1 m)
readerCommute aMM = ReaderT $ \ r2 -> ReaderT $ \ r1 -> runReaderT r2 $ runReaderT r1 aMM
instance (Unit m) => Unit (ReaderT r m) where
unit = ReaderT . const . unit
instance (Functor m) => Functor (ReaderT r m) where
map f = ReaderT . f ^^. unReaderT
instance (Product m) => Product (ReaderT r m) where
aM1 <*> aM2 = ReaderT $ \ r ->
runReaderT r aM1 <*> runReaderT r aM2
instance (Applicative m) => Applicative (ReaderT r m) where
fM <@> aM = ReaderT $ \ r ->
runReaderT r fM <@> runReaderT r aM
instance (Bind m) => Bind (ReaderT r m) where
aM >>= k = ReaderT $ \ r -> runReaderT r . k *$ runReaderT r aM
instance (Monad m) => Monad (ReaderT r m) where
instance FunctorUnit2 (ReaderT r) where
funit2 = ReaderT . const
instance FunctorJoin2 (ReaderT r) where
fjoin2 aMM = ReaderT $ \ r -> runReaderT r $ runReaderT r aMM
instance FunctorFunctor2 (ReaderT r) where
fmap2 :: (Functor m, Functor n) => (m ~> n) -> (ReaderT r m ~> ReaderT r n)
fmap2 f aM = ReaderT $ \ r -> f $ runReaderT r aM
instance (Functor m) => MonadReader r (ReaderT r m) where
readerI :: ReaderT r m ~> ReaderT r (ReaderT r m)
readerI = readerCommute . funit2
readerE :: ReaderT r (ReaderT r m) ~> ReaderT r m
readerE = fjoin2 . readerCommute
instance (MonadBot m) => MonadBot (ReaderT r m) where
mbot = ReaderT $ const mbot
instance (MonadAppend m) => MonadAppend (ReaderT r m) where
aM1 <++> aM2 = ReaderT $ \ r -> unReaderT aM1 r <++> unReaderT aM2 r
-- }}}
-- WriterT {{{
execWriterT :: (Functor m) => WriterT o m a -> m o
execWriterT = fst ^. unWriterT
mapOutput :: (Functor m) => (o1 -> o2) -> WriterT o1 m a -> WriterT o2 m a
mapOutput f = WriterT . mapFst f ^. unWriterT
writerCommute :: (Functor m) => WriterT o1 (WriterT o2 m) ~> WriterT o2 (WriterT o1 m)
writerCommute aMM = WriterT $ WriterT $ ff ^$ unWriterT $ unWriterT aMM
where
ff (o2, (o1, a)) = (o1, (o2, a))
instance (Unit m, Monoid o) => Unit (WriterT o m) where unit = WriterT . unit . (null,)
instance (Functor m) => Functor (WriterT o m) where map f = WriterT . mapSnd f ^. unWriterT
instance (Functor m, Product m, Monoid o) => Product (WriterT o m) where
aM1 <*> aM2 = WriterT $ ff ^$ unWriterT aM1 <*> unWriterT aM2
where
ff ((o1, a1), (o2, a2)) = (o1 ++ o2, (a1, a2))
instance (Functor m, Applicative m, Monoid o) => Applicative (WriterT o m) where
fM <@> aM = WriterT $ ff2 ^$ ff1 ^@ unWriterT fM <$> unWriterT aM
where
ff1 (o, f) = mapSnd ((o,) . f)
ff2 (o2, (o1, a)) = (o1 ++ o2, a)
instance (Monad m, Monoid o) => Bind (WriterT o m) where
aM >>= k = WriterT $ do
(o1, a) <- unWriterT aM
(o2, b) <- unWriterT $ k a
return (o1 ++ o2, b)
instance (Monad m, Monoid o) => Monad (WriterT o m) where
instance (Monoid w) => FunctorUnit2 (WriterT w) where
funit2 = WriterT .^ (null,)
instance FunctorJoin2 (WriterT w) where
fjoin2 = snd ^. unWriterT
instance FunctorFunctor2 (WriterT w) where
fmap2 :: (Functor m, Functor n) => (m ~> n) -> (WriterT w m ~> WriterT w n)
fmap2 f aM = WriterT $ f $ unWriterT aM
instance (Functor m, Monoid o) => MonadWriter o (WriterT o m) where
writerI :: WriterT o m ~> WriterT o (WriterT o m)
writerI = writerCommute . funit2
writerE :: WriterT o (WriterT o m) ~> WriterT o m
writerE = fjoin2 . writerCommute
instance (MonadBot m, Monoid o) => MonadBot (WriterT o m) where
mbot = WriterT $ mbot
-- }}}
-- StateT {{{ --
runStateT :: s -> StateT s m a -> m (s, a)
runStateT = flip unStateT
evalStateT :: (Functor m) => s -> StateT s m a -> m a
evalStateT = snd ^.: runStateT
execStateT :: (Functor m) => s -> StateT s m a -> m s
execStateT = fst ^.: runStateT
mapStateT :: (Functor m) => (s1 -> s2) -> (s2 -> s1) -> StateT s1 m a -> StateT s2 m a
mapStateT to from aM = StateT $ \ s2 -> ff ^$ unStateT aM $ from s2
where ff (s1, a) = (to s1, a)
type State s = StateT s ID
runState :: s -> State s a -> (s, a)
runState = unID .: runStateT
evalState :: s -> State s a -> a
evalState = snd .: runState
execState :: s -> State s a -> s
execState = fst .: runState
stateCommute :: (Functor m) => StateT s1 (StateT s2 m) ~> StateT s2 (StateT s1 m)
stateCommute aMM = StateT $ \ s2 -> StateT $ \ s1 -> ff ^$ runStateT s2 $ runStateT s1 aMM
where
ff (s2, (s1, a)) = (s1, (s2, a))
stateLens :: (Functor m) => Lens s1 s2 -> StateT s2 m ~> StateT s1 m
stateLens l aM = StateT $ \ s1 ->
let s2 = access l s1
ff (s2', a) = (set l s2' s1, a)
in ff ^$ unStateT aM s2
stateLensE :: (MonadState s1 m, Monad m) => Lens s1 s2 -> (StateT s2 m ~> m)
stateLensE = stateE .: stateLens
instance (Unit m) => Unit (StateT s m) where unit x = StateT $ \ s -> unit (s, x)
instance (Functor m) => Functor (StateT s m) where map f aM = StateT $ \ s -> mapSnd f ^$ unStateT aM s
instance (Monad m) => Product (StateT s m) where (<*>) = mpair
instance (Monad m) => Applicative (StateT s m) where (<@>) = mapply
instance (Monad m) => Bind (StateT s m) where
aM >>= k = StateT $ \ s -> do
(s', a) <- unStateT aM s
unStateT (k a) s'
instance (Monad m) => Monad (StateT s m) where
instance FunctorUnit2 (StateT s) where funit2 aM = StateT $ \ s -> (s,) ^$ aM
instance FunctorJoin2 (StateT s) where fjoin2 aMM = StateT $ \ s -> runStateT s $ snd ^$ runStateT s aMM
instance FunctorFunctor2 (StateT s) where
fmap2 :: (Functor m, Functor n) => (m ~> n) -> StateT s m ~> StateT s n
fmap2 f aM = StateT $ f . unStateT aM
instance (MonadBot m) => MonadBot (StateT s m) where mbot = StateT $ const mbot
instance (MonadTop m) => MonadTop (StateT s m) where mtop = StateT $ const mtop
instance (MonadPlus m) => MonadPlus (StateT s m) where
aM1 <+> aM2 = StateT $ \ s -> unStateT aM1 s <+> unStateT aM2 s
instance (MonadAppend m) => MonadAppend (StateT s m) where
aM1 <++> aM2 = StateT $ \ s -> unStateT aM1 s <++> unStateT aM2 s
instance (Functorial Monoid m, Monoid s, Monoid a) => Monoid (StateT s m a) where
null =
with (functorial :: W (Monoid (m (s, a)))) $
StateT $ \ _ -> null
aM1 ++ aM2 =
with (functorial :: W (Monoid (m (s, a)))) $
StateT $ \ s -> unStateT aM1 s ++ unStateT aM2 s
instance (Functorial Monoid m, Monoid s) => Functorial Monoid (StateT s m) where
functorial = W
instance (Functorial Bot m, Bot s, Bot a) => Bot (StateT s m a) where
bot :: StateT s m a
bot =
with (functorial :: W (Bot (m (s, a)))) $
StateT $ \ _ -> bot
instance (Functorial Join m, Join s, Join a) => Join (StateT s m a) where
aM1 \/ aM2 =
with (functorial :: W (Join (m (s, a)))) $
StateT $ \ s -> unStateT aM1 s \/ unStateT aM2 s
instance (Functorial Bot m, Functorial Join m, JoinLattice s, JoinLattice a) => JoinLattice (StateT s m a)
instance (Functorial Bot m, Functorial Join m, JoinLattice s) => Functorial JoinLattice (StateT s m) where functorial = W
instance (Functor m) => MonadState s (StateT s m) where
stateI :: StateT s m ~> StateT s (StateT s m)
stateI = stateCommute . funit2
stateE :: StateT s (StateT s m) ~> StateT s m
stateE = fjoin2 . stateCommute
-- }}} --
-- AddStateT {{{
newtype AddStateT s12 s1 m a = AddStateT { runAddStateT :: StateT s1 m a }
deriving
( Unit, Functor, Product, Applicative, Bind, Monad
, MonadBot, MonadPlus, MonadAppend
, MonadReader r
, MonadWriter o
)
mergeState :: (Functor m) => StateT s1 (StateT s2 m) a -> StateT (s1, s2) m a
mergeState aMM = StateT $ \ (s1, s2) -> ff ^$ unStateT (unStateT aMM s1) s2
where
ff (s2, (s1, a)) = ((s1, s2), a)
splitState :: (Functor m) => StateT (s1, s2) m a -> StateT s1 (StateT s2 m) a
splitState aM = StateT $ \ s1 -> StateT $ \ s2 -> ff ^$ unStateT aM (s1, s2)
where
ff ((s1, s2), a) = (s2, (s1, a))
instance (Functor m, MonadState s2 m, Isomorphism s12 (s1, s2)) => MonadState s12 (AddStateT s12 s1 m) where
stateI :: AddStateT s12 s1 m ~> StateT s12 (AddStateT s12 s1 m)
stateI =
fmap2 AddStateT
. mapStateT isofrom isoto
. mergeState
. fmap2 (stateCommute . fmap2 stateI)
. stateI
. runAddStateT
stateE :: StateT s12 (AddStateT s12 s1 m) ~> AddStateT s12 s1 m
stateE =
AddStateT
. stateE
. fmap2 (fmap2 stateE . stateCommute)
. splitState
. mapStateT isoto isofrom
. fmap2 runAddStateT
-- }}}
-- RWST {{{
runRWST :: (Functor m) => r -> s -> RWST r o s m a -> m (s, o, a)
runRWST r0 s0 = ff ^. runStateT s0 . unWriterT . runReaderT r0 . unRWST
where
ff (s, (o, a)) = (s, o, a)
rwsCommute :: (Monad m, Monoid o1, Monoid o2) => RWST r1 o1 s1 (RWST r2 o2 s2 m) ~> RWST r2 o2 s2 (RWST r1 o1 s1 m)
rwsCommute =
RWST
. fmap2 (fmap2 rwsStateCommute . rwsWriterCommute)
. rwsReaderCommute
. mmap2 unRWST
deriving instance (Unit m, Monoid o) => Unit (RWST r o s m)
deriving instance (Functor m) => Functor (RWST r o s m)
deriving instance (Monad m, Monoid o) => Product (RWST r o s m)
deriving instance (Monad m, Monoid o) => Applicative (RWST r o s m)
deriving instance (Monad m, Monoid o) => Bind (RWST r o s m)
deriving instance (Monad m, Monoid o) => Monad (RWST r o s m)
instance (Monoid o) => MonadUnit2 (RWST r o s) where
munit2 = RWST . funit2 . funit2 . funit2
instance (Monoid o) => MonadJoin2 (RWST r o s) where
mjoin2 =
RWST
. fjoin2
. fmap2 (fmap2 fjoin2 . writerReaderCommute)
. fmap2 (fmap2 (fmap2 (fmap2 fjoin2 . stateWriterCommute) . stateReaderCommute))
. unRWST . mmap2 unRWST
instance (Monoid o) => MonadFunctor2 (RWST r o s) where
mmap2 f = RWST . fmap2 (fmap2 (fmap2 f)) . unRWST
deriving instance (Monad m, Monoid o) => MonadReader r (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadWriter o (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadState s (RWST r o s m)
instance (Monad m, Monoid o) => MonadRWS r o s (RWST r o s m) where
rwsI :: RWST r o s m ~> RWST r o s (RWST r o s m)
rwsI = rwsCommute . munit2
rwsE :: RWST r o s (RWST r o s m) ~> RWST r o s m
rwsE = mjoin2 . rwsCommute
deriving instance (MonadBot m, Monoid o) => MonadBot (RWST r o s m)
deriving instance (Functor m, MonadMaybe m, Monoid o) => MonadMaybe (RWST r o s m)
-- }}}
-- ListT {{{
newtype ListT m a = ListT { unListT :: m [a] }
listCommute :: (Functor m) => ListT (ListT m) ~> ListT (ListT m)
listCommute = ListT . ListT . transpose ^. unListT . unListT
instance (Unit m) => Unit (ListT m) where
unit = ListT . unit . single
instance (Functor m) => Functor (ListT m) where
map f = ListT . f ^^. unListT
instance (Monad m, Functorial Monoid m) => Product (ListT m) where
(<*>) = mpair
instance (Monad m, Functorial Monoid m) => Applicative (ListT m) where
(<@>) = mapply
instance (Monad m, Functorial Monoid m) => Bind (ListT m) where
(>>=) :: forall a b. ListT m a -> (a -> ListT m b) -> ListT m b
aM >>= k = ListT $ do
xs <- unListT aM
unListT $ concat $ k ^$ xs
instance (Monad m, Functorial Monoid m) => Monad (ListT m) where
instance FunctorUnit2 ListT where
funit2 = ListT .^ unit
instance FunctorJoin2 ListT where
fjoin2 = ListT . concat ^. unListT . unListT
instance FunctorFunctor2 ListT where
fmap2 f = ListT . f . unListT
instance (Functorial Monoid m) => Monoid (ListT m a) where
null =
with (functorial :: W (Monoid (m [a]))) $
ListT null
xs ++ ys =
with (functorial :: W (Monoid (m [a]))) $
ListT $ unListT xs ++ unListT ys
instance (Functorial Monoid m) => Functorial Monoid (ListT m) where functorial = W
instance (Functorial Monoid m) => MonadBot (ListT m) where
mbot = null
instance (Functorial Monoid m) => MonadAppend (ListT m) where
(<++>) = (++)
maybeToList :: (Functor m) => MaybeT m a -> ListT m a
maybeToList aM = ListT $ ff ^$ unMaybeT aM
where
ff Nothing = []
ff (Just a) = [a]
-- }}}
-- ListSetT {{{
newtype ListSetT m a = ListSetT { unListSetT :: m (ListSet a) }
listSetCommute :: (Functor m) => ListSetT (ListSetT m) ~> ListSetT (ListSetT m)
listSetCommute = ListSetT . ListSetT . listSetTranspose ^. unListSetT . unListSetT
instance (Unit m) => Unit (ListSetT m) where
unit = ListSetT . unit . ListSet . single
instance (Functor m) => Functor (ListSetT m) where
map f = ListSetT . f ^^. unListSetT
instance (Monad m, Functorial JoinLattice m) => Product (ListSetT m) where
(<*>) = mpair
instance (Monad m, Functorial JoinLattice m) => Applicative (ListSetT m) where
(<@>) = mapply
instance (Monad m, Functorial JoinLattice m) => Bind (ListSetT m) where
(>>=) :: forall a b. ListSetT m a -> (a -> ListSetT m b) -> ListSetT m b
aM >>= k = ListSetT $ do
xs <- unListSetT aM
unListSetT $ msum $ k ^$ xs
-- PROOF of: monad laws for (ListSetT m) {{{
--
-- ASSUMPTION 1: returnₘ a <+> returnₘ b = returnₘ (a \/ b)
-- [this comes from m being a lattice functor. (1 x + 1 y) = 1 (x + y)]
--
-- * PROOF of: left unit := return x >>= k = k x {{{
--
-- return x >>= k
-- = [[definition of >>=]]
-- ListSetT $ do { xs <- unListSetT $ return x ; unListSetT $ msums $ map k xs }
-- = [[definition of return]]
-- ListSetT $ do { xs <- unListSetT $ ListSetT $ return [x] ; unListSetT $ msums $ map k xs }
-- = [[ListSetT beta]]
-- ListSetT $ do { xs <- return [x] ; unListSetT $ msums $ map k xs }
-- = [[monad left unit]]
-- ListSetT $ unListSetT $ msums $ map k [x]
-- = [[definition of map]]
-- ListSetT $ unListSetT $ msums $ [k x]
-- = [[definition of msums and <+> unit]]
-- ListSetT $ unListSetT $ k x
-- = [[ListSetT eta]]
-- k x
-- QED }}}
--
-- * PROOF of: right unit := aM >>= return = aM {{{
--
-- aM >>= return
-- = [[definition of >>=]]
-- ListSetT $ { xs <- unListSetT aM ; unListSetT $ msums $ map return xs }
-- = [[induction/expansion on xs]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ msums $ map return [x1,..,xn] }
-- = [[definition of return and map]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ msums $ [ListSetT $ return [x1],..,ListSetT $ return [xn]] }
-- = [[definition of msums]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ ListSetT $ return [x1] <+> .. <+> return [xn] }
-- = [[assumption 1]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ ListSetT $ return [x1,..,xn] }
-- = [[ListSetT beta]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; return [x1,..,xn] }
-- = [[monad right unit]]
-- ListSetT $ unListSetT aM
-- = [[ListSetT eta]]
-- aM
-- QED }}}
--
-- * PROOF of: associativity := (aM >>= k1) >>= k2 = { x <- aM ; k1 x >>= k2 } {{{
--
-- (aM >>= k1) >>= k2
-- = [[definition of >>=]]
-- ListSetT $ { xs <- unListSetT $ ListSetT $ { xs' <- unListSetT aM ; unListSetT $ msums $ map k1 xs' } ; unListSetT $ msums $ map k xs }
-- = [[ListSetT beta]]
-- ListSetT $ { xs <- { xs' <- unListSetT aM ; unListSetT $ msums $ map k1 xs' } ; unListSetT $ msums $ map k xs }
-- = [[monad associativity]]
-- ListSetT $ { xs' <- unListSetT aM ; xs <- unListSetT $ msums $ map k1 xs' ; unListSetT $ msums $ map k xs }
-- =
-- LHS
--
-- { x <- aM ; k1 x >>= k2 }
-- = [[definition of >>=]]
-- ListSetT $ { xs' <- unListSetT aM ; unListSetT $ msums $ map (\ x -> ListSetT $ { xs <- unListSetT (k1 x) ; unListSetT $ msums $ map k2 xs }) xs' }
-- = [[induction/expansion on xs']]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ msums $ map (\ x -> ListSetT $ { xs <- unListSetT (k1 x) ; unListSetT $ msums $ map k2 xs }) [x1,..,xn] }
-- = [[definition of map]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ msums $ [ListSetT $ { xs <- unListSetT (k1 x1) ; unListSetT $ msums $ map k2 xs },..,ListSetT $ { xs <- unListSetT (k1 xn) ; runList $ msums $ map k2 xs}] }
-- = [[definition of msum]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; unListSetT $ ListSetT { xs <- unListSetT (k1 x1) ; unListSetT $ msums $ map k2 xs } <+> .. <+> ListSetT { xs <- unListSetT (k1 xn) ; unListSetT $ msums $ map k2 xs } }
-- = [[ListSetT beta and definition of <+> for ListSetT]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; { xs <- unListSetT (k1 x1) ; unListSetT $ msums $ map k2 xs } <+> .. <+> { xs <- unListSetT (k1 xn) ; unListSetT $ msums $ map k2 xs } }
-- = [[<+> distribute with >>=]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; xs <- (unListSetT (k1 x1) <+> .. <+> unListSetT (k1 xn)) ; unListSetT $ msums $ map k2 xs }
-- = [[definition of msums and map]]
-- ListSetT $ { [x1,..,xn] <- unListSetT aM ; xs <- unListSetT $ msums $ map k1 [x1,..,xn] ; unListSetT $ msums $ map k2 xs }
-- = [[collapsing [x1,..,xn]]]
-- ListSetT $ { xs' <- unListSetT aM ; xs <- unListSetT $ msums $ map k1 xs' ; unListSetT $ msums $ map k xs }
-- =
-- RHS
--
-- LHS = RHS
-- QED }}}
--
-- }}}
instance (Monad m, Functorial JoinLattice m) => Monad (ListSetT m) where
instance FunctorUnit2 ListSetT where
funit2 = ListSetT .^ unit
instance FunctorJoin2 ListSetT where
fjoin2 = ListSetT . concat ^. unListSetT . unListSetT
instance FunctorFunctor2 ListSetT where
fmap2 f = ListSetT . f . unListSetT
instance (Functorial JoinLattice m) => MonadBot (ListSetT m) where
mbot :: forall a. ListSetT m a
mbot =
with (functorial :: W (JoinLattice (m (ListSet a)))) $
ListSetT bot
instance (Functorial JoinLattice m) => MonadPlus (ListSetT m) where
(<+>) :: forall a. ListSetT m a -> ListSetT m a -> ListSetT m a
aM1 <+> aM2 =
with (functorial :: W (JoinLattice (m (ListSet a)))) $
ListSetT $ unListSetT aM1 \/ unListSetT aM2
-- }}}
-- ListSetWithTopT {{{
newtype ListSetWithTopT m a = ListSetWithTopT { unListSetWithTopT :: m (ListSetWithTop a) }
listSetWithTopCommute :: (Functor m) => ListSetWithTopT (ListSetWithTopT m) ~> ListSetWithTopT (ListSetWithTopT m)
listSetWithTopCommute = ListSetWithTopT . ListSetWithTopT . listSetWithTopTranspose ^. unListSetWithTopT . unListSetWithTopT
instance (Unit m) => Unit (ListSetWithTopT m) where unit = ListSetWithTopT . unit . single
instance (Functor m) => Functor (ListSetWithTopT m) where map f = ListSetWithTopT . f ^^. unListSetWithTopT
instance (Monad m, Functorial JoinLattice m, Functorial Top m) => Product (ListSetWithTopT m) where (<*>) = mpair
instance (Monad m, Functorial JoinLattice m, Functorial Top m) => Applicative (ListSetWithTopT m) where (<@>) = mapply
instance (Monad m, Functorial JoinLattice m, Functorial Top m) => Bind (ListSetWithTopT m) where
(>>=) :: forall a b. ListSetWithTopT m a -> (a -> ListSetWithTopT m b) -> ListSetWithTopT m b
aM >>= k = ListSetWithTopT $ do
xs <- unListSetWithTopT aM
unListSetWithTopT $ listSetWithTopElim mtop msum $ k ^$ xs
instance (Monad m, Functorial JoinLattice m, Functorial Top m) => Monad (ListSetWithTopT m) where
instance FunctorUnit2 ListSetWithTopT where
funit2 = ListSetWithTopT .^ unit
instance FunctorJoin2 ListSetWithTopT where
fjoin2 = ListSetWithTopT . listSetWithTopElim ListSetTop concat ^. unListSetWithTopT . unListSetWithTopT
instance FunctorFunctor2 ListSetWithTopT where
fmap2 f = ListSetWithTopT . f . unListSetWithTopT
instance (Functorial JoinLattice m) => MonadBot (ListSetWithTopT m) where
mbot :: forall a. ListSetWithTopT m a
mbot =
with (functorial :: W (JoinLattice (m (ListSetWithTop a)))) $
ListSetWithTopT bot
instance (Functorial Top m) => MonadTop (ListSetWithTopT m) where
mtop :: forall a. ListSetWithTopT m a
mtop =
with (functorial :: W (Top (m (ListSetWithTop a)))) $
ListSetWithTopT top
instance (Functorial JoinLattice m) => MonadPlus (ListSetWithTopT m) where
(<+>) :: forall a. ListSetWithTopT m a -> ListSetWithTopT m a -> ListSetWithTopT m a
aM1 <+> aM2 =
with (functorial :: W (JoinLattice (m (ListSetWithTop a)))) $
ListSetWithTopT $ unListSetWithTopT aM1 \/ unListSetWithTopT aM2
-- }}}
-- SetT {{{
newtype SetT m a = SetT { unSetT :: m (Set a) }
mapSetT :: (m (Set a) -> m (Set b)) -> SetT m a -> SetT m b
mapSetT f = SetT . f . unSetT
setCommute :: (Functor m) => SetT (SetT m) ~> SetT (SetT m)
setCommute = SetT . SetT . setTranspose ^. unSetT . unSetT
instance (Functor m, Product m) => Product (SetT m) where
(<*>) :: forall a b. SetT m a -> SetT m b -> SetT m (a, b)
aM1 <*> aM2 = SetT $ uncurry (<*>) ^$ unSetT aM1 <*> unSetT aM2
instance (Functorial JoinLattice m, Monad m) => Bind (SetT m) where
aM >>= k = SetT $ do
aC <- unSetT aM
unSetT $ msum $ k ^$ toList aC
instance (Functorial JoinLattice m) => MonadBot (SetT m) where
mbot :: forall a. SetT m a
mbot =
with (functorial :: W (JoinLattice (m (Set a)))) $
SetT bot
instance (Functorial JoinLattice m) => MonadPlus (SetT m) where
(<+>) :: forall a. SetT m a -> SetT m a -> SetT m a
aM1 <+> aM2 =
with (functorial :: W (JoinLattice (m (Set a)))) $
SetT $ unSetT aM1 \/ unSetT aM2
-- }}}
-- ContT {{{
evalKonT :: (Unit m) => ContT r m r -> m r
evalKonT aM = unContT aM unit
type Kon r = ContT r ID
runKon :: Kon r a -> (a -> r) -> r
runKon aM f = unID $ unContT aM (ID . f)
evalKon :: Kon r r -> r
evalKon aM = runKon aM id
instance (Unit m) => Unit (ContT r m) where
unit a = ContT $ \ k -> k a
instance (Unit m) => Applicative (ContT r m) where
(<@>) = mapply
instance (Unit m) => Product (ContT r m) where
(<*>) = mpair
instance (Unit m) => Functor (ContT r m) where
map = mmap
instance (Unit m) => Bind (ContT r m) where
(>>=) :: ContT r m a -> (a -> ContT r m b) -> ContT r m b
aM >>= kM = ContT $ \ (k :: b -> m r) -> unContT aM $ \ a -> unContT (kM a) k
instance (Unit m) => Monad (ContT r m) where
instance MonadIsoFunctor2 (ContT r) where
misoMap2 :: (Monad m, Monad n) => (m ~> n, n ~> m) -> (ContT r m ~> ContT r n)
misoMap2 (to, from) aM = ContT $ \ (k :: a -> n r) -> to $ unContT aM $ \ a -> from $ k a
instance (Monad m) => MonadCont r (ContT r m) where
contI :: ContT r m ~> ContT r (ContT r m)
contI aM = ContT $ \ (k1 :: a -> ContT r m r) -> ContT $ \ (k2 :: r -> m r) ->
k2 *$ unContT aM $ \ a -> unContT (k1 a) return
contE :: ContT r (ContT r m) ~> ContT r m
contE aMM = ContT $ \ (k :: a -> m r) ->
let aM :: ContT r m r
aM = unContT aMM $ \ a -> ContT $ \ (k' :: r -> m r) -> k' *$ k a
in unContT aM return
-- }}}
-- OpaqueContT {{{
newtype ContFun r m a = ContFun { unContFun :: a -> m r }
type OpaqueKon k r = OpaqueContT k r ID
runOpaqueKonTWith :: k r m a -> OpaqueContT k r m a -> m r
runOpaqueKonTWith = flip unOpaqueContT
makeMetaKonT :: (Morphism3 (k r) (ContFun r)) => ((a -> m r) -> m r) -> OpaqueContT k r m a
makeMetaKonT nk = OpaqueContT $ \ (k :: k r m a) -> nk $ unContFun $ morph3 k
runMetaKonT :: (Morphism3 (ContFun r) (k r)) => OpaqueContT k r m a -> (a -> m r) -> m r
runMetaKonT aM k = unOpaqueContT aM $ morph3 $ ContFun k
runMetaKonTWith :: (Morphism3 (ContFun r) (k r)) => (a -> m r) -> OpaqueContT k r m a -> m r
runMetaKonTWith = flip runMetaKonT
evalOpaqueKonT :: (Unit m, Morphism3 (ContFun r) (k r)) => OpaqueContT k r m r -> m r
evalOpaqueKonT aM = runMetaKonT aM unit
makeOpaqueKon :: (k r ID a -> r) -> OpaqueKon k r a
makeOpaqueKon nk = OpaqueContT $ ID . nk
makeMetaKon :: (Morphism3 (k r) (ContFun r)) => ((a -> r) -> r) -> OpaqueKon k r a
makeMetaKon nk = makeOpaqueKon $ \ (k :: k r ID a) -> nk $ (.) unID . unContFun $ morph3 k
runOpaqueKon :: OpaqueKon k r a -> k r ID a -> r
runOpaqueKon = unID .: unOpaqueContT
runMetaKon :: (Morphism3 (ContFun r) (k r)) => OpaqueKon k r a -> (a -> r) -> r
runMetaKon aM k = runOpaqueKon aM $ morph3 $ ContFun $ ID . k
evalOpaqueKon :: (Morphism3 (ContFun r) (k r)) => OpaqueKon k r r -> r
evalOpaqueKon aM = runMetaKon aM id
metaKonT :: (Morphism3 (ContFun r) (k r)) => OpaqueContT k r m ~> ContT r m
metaKonT aM = ContT $ \ (k :: a -> m r) -> runMetaKonT aM k
opaqueContT :: (Morphism3 (k r) (ContFun r)) => ContT r m ~> OpaqueContT k r m
opaqueContT aM = makeMetaKonT $ \ (k :: a -> m r) -> unContT aM k
instance (Morphism3 (k r) (ContFun r)) => Unit (OpaqueContT k r m) where
unit :: a -> OpaqueContT k r m a
unit a = OpaqueContT $ \ k -> unContFun (morph3 k) a
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => Functor (OpaqueContT k r m) where map = mmap
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => Applicative (OpaqueContT k r m) where (<@>) = mapply
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => Product (OpaqueContT k r m) where (<*>) = mpair
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => Bind (OpaqueContT k r m) where
(>>=) :: OpaqueContT k r m a -> (a -> OpaqueContT k r m b) -> OpaqueContT k r m b
aM >>= kM = OpaqueContT $ \ (k :: k r m a) -> runMetaKonT aM $ \ a -> unOpaqueContT (kM a) k
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => Monad (OpaqueContT k r m) where
instance (Isomorphism3 (k r) (ContFun r)) => MonadIsoFunctor2 (OpaqueContT k r) where
misoMap2 :: (Monad m, Monad n) => (m ~> n, n ~> m) -> OpaqueContT k r m ~> OpaqueContT k r n
misoMap2 tofrom = opaqueContT . misoMap2 tofrom . metaKonT
class Balloon k r | k -> r where
inflate :: (Monad m) => k r m ~> k r (OpaqueContT k r m)
deflate :: (Monad m) => k r (OpaqueContT k r m) ~> k r m
instance (Monad m, Isomorphism3 (ContFun r) (k r), Balloon k r) => MonadOpaqueCont k r (OpaqueContT k r m) where
opaqueContI :: OpaqueContT k r m a -> OpaqueContT k r (OpaqueContT k r m) a
opaqueContI aM = OpaqueContT $ \ k1 -> makeMetaKonT $ \ (k2 :: r -> m r) -> k2 *$ unOpaqueContT aM $ deflate k1
opaqueContE :: OpaqueContT k r (OpaqueContT k r m) a -> OpaqueContT k r m a
opaqueContE kk = OpaqueContT $ \ (k :: k r m a ) -> runMetaKonTWith return $ unOpaqueContT kk $ inflate k
instance (Monad m, Isomorphism3 (ContFun r) (k r)) => MonadCont r (OpaqueContT k r m) where
contI :: OpaqueContT k r m ~> ContT r (OpaqueContT k r m)
contI aM = ContT $ \ (k1 :: a -> OpaqueContT k r m r) -> makeMetaKonT $ \ (k2 :: r -> m r) ->
k2 *$ runMetaKonT aM $ \ a -> runMetaKonT (k1 a) return
contE :: ContT r (OpaqueContT k r m) ~> OpaqueContT k r m
contE aMM = makeMetaKonT $ \ (k :: a -> m r) ->
runMetaKonTWith return $ unContT aMM $ \ a -> makeMetaKonT $ \ (k' :: r -> m r) -> k' *$ k a
-- }}}
----------------------
-- Monads Commuting --
----------------------
-- Maybe // * --
-- Maybe // Reader // FULL COMMUTE {{{
maybeReaderCommute :: (Functor m) => MaybeT (ReaderT r m) ~> ReaderT r (MaybeT m)
maybeReaderCommute aMRM = ReaderT $ \ r -> MaybeT $ runReaderT r $ unMaybeT aMRM
readerMaybeCommute :: (Functor m) => ReaderT r (MaybeT m) ~> MaybeT (ReaderT r m)
readerMaybeCommute aRMM = MaybeT $ ReaderT $ \ r -> unMaybeT $ runReaderT r aRMM
instance (Functor m, MonadReader r m) => MonadReader r (MaybeT m) where
readerI :: MaybeT m ~> ReaderT r (MaybeT m)
readerI = maybeReaderCommute . fmap2 readerI
readerE :: ReaderT r (MaybeT m) ~> MaybeT m
readerE = fmap2 readerE . readerMaybeCommute
instance (Functor m, MonadMaybe m) => MonadMaybe (ReaderT r m) where
maybeI :: ReaderT r m ~> MaybeT (ReaderT r m)
maybeI = readerMaybeCommute . fmap2 maybeI
maybeE :: MaybeT (ReaderT r m) ~> ReaderT r m
maybeE = fmap2 maybeE . maybeReaderCommute
-- }}}
-- Maybe // Writer {{{
writerMaybeCommute :: (Monoid w, Functor m) => WriterT w (MaybeT m) ~> MaybeT (WriterT w m)
writerMaybeCommute aRMM = MaybeT $ WriterT $ ff ^$ unMaybeT $ unWriterT aRMM
where
ff Nothing = (null, Nothing)
ff (Just (w, a)) = (w, Just a)
maybeWriterCommute :: (Functor m) => MaybeT (WriterT w m) ~> WriterT w (MaybeT m)
maybeWriterCommute aMRM = WriterT $ MaybeT $ ff ^$ unWriterT $ unMaybeT aMRM
where
ff (_, Nothing) = Nothing
ff (w, Just a) = Just (w, a)
instance (Monoid w, Functor m, MonadWriter w m) => MonadWriter w (MaybeT m) where
writerI :: MaybeT m ~> WriterT w (MaybeT m)
writerI = maybeWriterCommute . fmap2 writerI
writerE :: WriterT w (MaybeT m) ~> MaybeT m
writerE = fmap2 writerE . writerMaybeCommute
instance (Monoid w, Functor m, MonadMaybe m) => MonadMaybe (WriterT w m) where
maybeI :: WriterT w m ~> MaybeT (WriterT w m)
maybeI = writerMaybeCommute . fmap2 maybeI
maybeE :: MaybeT (WriterT w m) ~> WriterT w m
maybeE = fmap2 maybeE . maybeWriterCommute
-- }}}
-- Maybe // State {{{
maybeStateCommute :: (Functor m) => MaybeT (StateT s m) ~> StateT s (MaybeT m)
maybeStateCommute aMSM = StateT $ \ s1 -> MaybeT $ ff ^$ runStateT s1 $ unMaybeT aMSM
where
ff (_, Nothing) = Nothing
ff (s2, Just a) = Just (s2, a)
stateMaybeCommute :: (Functor m) => StateT s (MaybeT m) ~> MaybeT (StateT s m)
stateMaybeCommute aSMM = MaybeT $ StateT $ \ s1 -> ff s1 ^$ unMaybeT $ runStateT s1 aSMM
where
ff s1 Nothing = (s1, Nothing)
ff _ (Just (s2, a)) = (s2, Just a)
instance (Functor m, MonadState s m) => MonadState s (MaybeT m) where
stateI :: MaybeT m ~> StateT s (MaybeT m)
stateI = maybeStateCommute . fmap2 stateI
stateE :: StateT s (MaybeT m) ~> MaybeT m
stateE = fmap2 stateE . stateMaybeCommute
instance (Functor m, MonadMaybe m) => MonadMaybe (StateT s m) where
maybeI :: StateT s m ~> MaybeT (StateT s m)
maybeI = stateMaybeCommute . fmap2 maybeI
maybeE :: MaybeT (StateT s m) ~> StateT s m
maybeE = fmap2 maybeE . maybeStateCommute
-- }}}
-- Error // * --
-- Error // Reader {{{
errorReaderCommute :: ErrorT e (ReaderT r m) ~> ReaderT r (ErrorT e m)
errorReaderCommute aMRM = ReaderT $ \ r -> ErrorT $ runReaderT r $ unErrorT aMRM
readerErrorCommute :: ReaderT r (ErrorT e m) ~> ErrorT e (ReaderT r m)
readerErrorCommute aRMM = ErrorT $ ReaderT $ \ r -> unErrorT $ runReaderT r aRMM
instance (Functor m, MonadReader r m) => MonadReader r (ErrorT e m) where
readerI :: ErrorT e m ~> ReaderT r (ErrorT e m)
readerI = errorReaderCommute . fmap2 readerI
readerE :: ReaderT r (ErrorT e m) ~> ErrorT e m
readerE = fmap2 readerE . readerErrorCommute
instance (Functor m, MonadError e m) => MonadError e (ReaderT r m) where
errorI :: ReaderT r m ~> ErrorT e (ReaderT r m)
errorI = readerErrorCommute . fmap2 errorI
errorE :: ErrorT e (ReaderT r m) ~> ReaderT r m
errorE = fmap2 errorE . errorReaderCommute
-- }}}
-- Error // State {{{
errorStateCommute :: (Functor m) => ErrorT e (StateT s m) ~> StateT s (ErrorT e m)
errorStateCommute aMRM = StateT $ \ s -> ErrorT $ ff ^$ runStateT s $ unErrorT aMRM
where
ff (_, Inl e) = Inl e
ff (s, Inr a) = Inr (s, a)
stateErrorCommute :: (Functor m) => StateT s (ErrorT e m) ~> ErrorT e (StateT s m)
stateErrorCommute aRMM = ErrorT $ StateT $ \ s -> ff s ^$ unErrorT $ runStateT s aRMM
where
ff s (Inl e) = (s, Inl e)
ff _ (Inr (s, a)) = (s, Inr a)
instance (Functor m, MonadState s m) => MonadState s (ErrorT e m) where
stateI :: ErrorT e m ~> StateT s (ErrorT e m)
stateI = errorStateCommute . fmap2 stateI
stateE :: StateT s (ErrorT e m) ~> ErrorT e m
stateE = fmap2 stateE . stateErrorCommute
instance (Functor m, MonadError e m) => MonadError e (StateT s m) where
errorI :: StateT s m ~> ErrorT e (StateT s m)
errorI = stateErrorCommute . fmap2 errorI
errorE :: ErrorT e (StateT s m) ~> StateT s m
errorE = fmap2 errorE . errorStateCommute
-- }}}
-- Reader // * --
-- Reader // Writer // FULL COMMUTE {{{
readerWriterCommute :: ReaderT r (WriterT w m) ~> WriterT w (ReaderT r m)
readerWriterCommute aRWM = WriterT $ ReaderT $ \ r -> unWriterT $ runReaderT r aRWM
writerReaderCommute :: WriterT w (ReaderT r m) ~> ReaderT r (WriterT w m)
writerReaderCommute aWRM = ReaderT $ \ r -> WriterT $ runReaderT r $ unWriterT aWRM
instance (Monoid w, Functor m, MonadWriter w m) => MonadWriter w (ReaderT r m) where
writerI :: ReaderT r m ~> WriterT w (ReaderT r m)
writerI = readerWriterCommute . fmap2 writerI
writerE :: WriterT w (ReaderT r m) ~> ReaderT r m
writerE = fmap2 writerE . writerReaderCommute
instance (Monoid w, Functor m, MonadReader r m) => MonadReader r (WriterT w m) where
readerI :: WriterT w m ~> ReaderT r (WriterT w m)
readerI = writerReaderCommute . fmap2 readerI
readerE :: ReaderT r (WriterT w m) ~> WriterT w m
readerE = fmap2 readerE . readerWriterCommute
-- }}}
-- Reader // State // FULL COMMUTE {{{
readerStateCommute :: (Functor m) => ReaderT r (StateT s m) ~> StateT s (ReaderT r m)
readerStateCommute aRSM = StateT $ \ s -> ReaderT $ \ r ->
runStateT s $ runReaderT r aRSM
stateReaderCommute :: (Functor m) => StateT s (ReaderT r m) ~> ReaderT r (StateT s m)
stateReaderCommute aSRM = ReaderT $ \ r -> StateT $ \ s ->
runReaderT r $ runStateT s aSRM
instance (Functor m, MonadState s m) => MonadState s (ReaderT r m) where
stateI :: ReaderT r m ~> StateT s (ReaderT r m)
stateI = readerStateCommute . fmap2 stateI
stateE :: StateT s (ReaderT r m) ~> ReaderT r m
stateE = fmap2 stateE . stateReaderCommute
instance (Functor m, MonadReader r m) => MonadReader r (StateT s m) where
readerI :: StateT s m ~> ReaderT r (StateT s m)
readerI = stateReaderCommute . fmap2 readerI
readerE :: ReaderT r (StateT s m) ~> StateT s m
readerE = fmap2 readerE . readerStateCommute
-- }}}
-- Reader // RWS {{{
readerRWSCommute :: (Monad m, Monoid o) => ReaderT r1 (RWST r2 o s m) ~> RWST r2 o s (ReaderT r1 m)
readerRWSCommute =
RWST
. fmap2
( fmap2 readerStateCommute
. readerWriterCommute
)
. readerCommute
. fmap2 unRWST
rwsReaderCommute :: (Monad m, Monoid o) => RWST r1 o s (ReaderT r2 m) ~> ReaderT r2 (RWST r1 o s m)
rwsReaderCommute =
fmap2 RWST
. readerCommute
. fmap2
( writerReaderCommute
. fmap2 stateReaderCommute
)
. unRWST
-- }}}
-- Writer // * --
-- Writer // State // FULL COMMUTE {{{
writerStateCommute :: (Functor m) => WriterT w (StateT s m) ~> StateT s (WriterT w m)
writerStateCommute aRMM = StateT $ \ s1 -> WriterT $ ff ^$ runStateT s1 $ unWriterT aRMM
where
ff (s, (w, a)) = (w, (s, a))
stateWriterCommute :: (Functor m) => StateT s (WriterT w m) ~> WriterT w (StateT s m)
stateWriterCommute aMRM = WriterT $ StateT $ ff ^. unWriterT . unStateT aMRM
where
ff (w, (s, a)) = (s, (w, a))
instance (Functor m, Monoid w, MonadState s m) => MonadState s (WriterT w m) where
stateI :: WriterT w m ~> StateT s (WriterT w m)
stateI = writerStateCommute . fmap2 stateI
stateE :: StateT s (WriterT w m) ~> WriterT w m
stateE = fmap2 stateE . stateWriterCommute
instance (Monoid w, Functor m, MonadWriter w m) => MonadWriter w (StateT s m) where
writerI :: StateT s m ~> WriterT w (StateT s m)
writerI = stateWriterCommute . fmap2 writerI
writerE :: WriterT w (StateT s m) ~> StateT s m
writerE = fmap2 writerE . writerStateCommute
-- }}}
-- Writer // RWS {{{
writerRWSCommute :: (Monad m, Monoid o1, Monoid o2) => WriterT o1 (RWST r o2 s m) ~> RWST r o2 s (WriterT o1 m)
writerRWSCommute =
RWST
. fmap2
( fmap2 writerStateCommute
. writerCommute
)
. writerReaderCommute
. fmap2 unRWST
rwsWriterCommute :: (Monad m, Monoid o1, Monoid o2) => RWST r o1 s (WriterT o2 m) ~> WriterT o2 (RWST r o1 s m)
rwsWriterCommute =
fmap2 RWST
. readerWriterCommute
. fmap2
( writerCommute
. fmap2 stateWriterCommute
)
. unRWST
-- }}}
-- State // * --
-- State // RWS {{{
stateRWSCommute :: (Monad m, Monoid o) => StateT s1 (RWST r o s2 m) ~> RWST r o s2 (StateT s1 m)
stateRWSCommute =
RWST
. fmap2
( fmap2 stateCommute
. stateWriterCommute
)
. stateReaderCommute
. fmap2 unRWST
rwsStateCommute :: (Monad m, Monoid o) => RWST r o s1 (StateT s2 m) ~> StateT s2 (RWST r o s1 m)
rwsStateCommute =
fmap2 RWST
. readerStateCommute
. fmap2
( writerStateCommute
. fmap2 stateCommute
)
. unRWST
-- }}}
-- State // List {{{
-- (s -> m [a, s]) -> (s -> m ([a], s))
stateListCommute :: (Functor m, Monoid s) => StateT s (ListT m) ~> ListT (StateT s m)
stateListCommute aMM = ListT $ StateT $ \ s -> ff ^$ unListT $ runStateT s aMM
where
ff asL = (concat $ fst ^$ asL, snd ^$ asL)
listStateCommute :: (Functor m) => ListT (StateT s m) ~> StateT s (ListT m)
listStateCommute aMM = StateT $ \ s -> ListT $ ff ^$ runStateT s $ unListT aMM
where
ff (s, xs) = (s,) ^$ xs
instance (Functor m, MonadState s m, Functorial Monoid m, Monoid s) => MonadState s (ListT m) where
stateI :: ListT m ~> StateT s (ListT m)
stateI = listStateCommute . fmap2 stateI
stateE :: StateT s (ListT m) ~> ListT m
stateE = fmap2 stateE . stateListCommute
-- }}}
-- State // ListSet {{{
stateListSetCommute :: (Functor m, JoinLattice s) => StateT s (ListSetT m) ~> ListSetT (StateT s m)
stateListSetCommute aMM = ListSetT $ StateT $ \ s -> ff ^$ unListSetT $ runStateT s aMM
where
ff asL = (joins $ fst ^$ asL, snd ^$ asL)
listSetStateCommute :: (Functor m) => ListSetT (StateT s m) ~> StateT s (ListSetT m)
listSetStateCommute aMM = StateT $ \ s -> ListSetT $ ff ^$ runStateT s $ unListSetT aMM
where
ff (s, xs) = (s,) ^$ xs
instance (Functor m, MonadState s m, Functorial JoinLattice m, JoinLattice s) => MonadState s (ListSetT m) where
stateI :: ListSetT m ~> StateT s (ListSetT m)
stateI = listSetStateCommute . fmap2 stateI
stateE :: StateT s (ListSetT m) ~> ListSetT m
stateE = fmap2 stateE . stateListSetCommute
-- }}}
-- State // Kon {{{
stateKonCommute :: StateT s (ContT (s, r) m) ~> ContT r (StateT s m)
stateKonCommute aSK = ContT $ \ (k :: a -> StateT s m r) -> StateT $ \ s ->
unContT (runStateT s aSK) $ \ (s', a) -> runStateT s' $ k a
konStateCommute :: ContT r (StateT s m) ~> StateT s (ContT (s, r) m)
konStateCommute aKS = StateT $ \ s -> ContT $ \ (k :: (s, a) -> m (s, r)) ->
runStateT s $ unContT aKS $ \ a -> StateT $ \ s' -> k (s',a)
instance (Monad m, MonadState s m) => MonadState s (ContT r m) where
stateI :: ContT r m ~> StateT s (ContT r m)
stateI =
fmap2 (misoMap2 (stateE, stateI))
. fmap2 stateKonCommute
. stateI
. konStateCommute
. misoMap2 (stateI, stateE :: StateT s m ~> m)
stateE :: StateT s (ContT r m) ~> ContT r m
stateE =
misoMap2 (stateE, stateI)
. stateKonCommute
. stateE
. fmap2 konStateCommute
. fmap2 (misoMap2 (stateI, stateE :: StateT s m ~> m))
-- }}}
-- State // OpaqueKon {{{
instance (Monad m, MonadState s m, Isomorphism3 (ContFun r) (k r)) => MonadState s (OpaqueContT k r m) where
stateI :: OpaqueContT k r m ~> StateT s (OpaqueContT k r m)
stateI =
fmap2 opaqueContT
. stateI
. metaKonT
stateE :: StateT s (OpaqueContT k r m) ~> OpaqueContT k r m
stateE =
opaqueContT
. stateE
. fmap2 metaKonT
-- }}}
|
davdar/maam
|
src/FP/Monads.hs
|
bsd-3-clause
| 42,932
| 0
| 19
| 9,956
| 17,878
| 9,158
| 8,720
| -1
| -1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}
module GHC.Event.Thread
( getSystemEventManager
, getSystemTimerManager
, ensureIOManagerIsRunning
, ioManagerCapabilitiesChanged
, threadWaitRead
, threadWaitWrite
, threadWaitReadSTM
, threadWaitWriteSTM
, closeFdWith
, threadDelay
, registerDelay
, blockedOnBadFD -- used by RTS
) where
import Control.Exception (finally, SomeException, toException)
import Data.Foldable (forM_, mapM_, sequence_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Tuple (snd)
import Foreign.C.Error (eBADF, errnoToIOError)
import Foreign.C.Types (CInt(..), CUInt(..))
import Foreign.Ptr (Ptr)
import GHC.Base
import GHC.List (zipWith, zipWith3)
import GHC.Conc.Sync (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
labelThread, modifyMVar_, withMVar, newTVar, sharedCAF,
getNumCapabilities, threadCapability, myThreadId, forkOn,
threadStatus, writeTVar, newTVarIO, readTVar, retry,throwSTM,STM)
import GHC.IO (mask_, onException)
import GHC.IO.Exception (ioError)
import GHC.IOArray (IOArray, newIOArray, readIOArray, writeIOArray,
boundsIOArray)
import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import GHC.Event.Control (controlWriteFd)
import GHC.Event.Internal (eventIs, evtClose)
import GHC.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,
new, registerFd, unregisterFd_)
import qualified GHC.Event.Manager as M
import qualified GHC.Event.TimerManager as TM
import GHC.Num ((-), (+))
import GHC.Real (fromIntegral)
import GHC.Show (showSignedInt)
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types (Fd)
-- | Suspends the current thread for a given number of microseconds
-- (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
threadDelay :: Int -> IO ()
threadDelay usecs = mask_ $ do
mgr <- getSystemTimerManager
m <- newEmptyMVar
reg <- TM.registerTimeout mgr usecs (putMVar m ())
takeMVar m `onException` TM.unregisterTimeout mgr reg
-- | Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs = do
t <- atomically $ newTVar False
mgr <- getSystemTimerManager
_ <- TM.registerTimeout mgr usecs . atomically $ writeTVar t True
return t
-- | Block the current thread until data is available to read from the
-- given file descriptor.
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitRead', use 'closeFdWith'.
threadWaitRead :: Fd -> IO ()
threadWaitRead = threadWait evtRead
{-# INLINE threadWaitRead #-}
-- | Block the current thread until the given file descriptor can
-- accept data to write.
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitWrite', use 'closeFdWith'.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite = threadWait evtWrite
{-# INLINE threadWaitWrite #-}
-- | Close a file descriptor in a concurrency-safe way.
--
-- Any threads that are blocked on the file descriptor via
-- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having
-- IO exceptions thrown.
closeFdWith :: (Fd -> IO ()) -- ^ Action that performs the close.
-> Fd -- ^ File descriptor to close.
-> IO ()
closeFdWith close fd = do
eventManagerArray <- readIORef eventManager
let (low, high) = boundsIOArray eventManagerArray
mgrs <- flip mapM [low..high] $ \i -> do
Just (_,!mgr) <- readIOArray eventManagerArray i
return mgr
mask_ $ do
tables <- flip mapM mgrs $ \mgr -> takeMVar $ M.callbackTableVar mgr fd
cbApps <- zipWithM (\mgr table -> M.closeFd_ mgr table fd) mgrs tables
close fd `finally` sequence_ (zipWith3 finish mgrs tables cbApps)
where
finish mgr table cbApp = putMVar (M.callbackTableVar mgr fd) table >> cbApp
zipWithM f xs ys = sequence (zipWith f xs ys)
threadWait :: Event -> Fd -> IO ()
threadWait evt fd = mask_ $ do
m <- newEmptyMVar
mgr <- getSystemEventManager_
reg <- registerFd mgr (\_ e -> putMVar m e) fd evt
evt' <- takeMVar m `onException` unregisterFd_ mgr reg
if evt' `eventIs` evtClose
then ioError $ errnoToIOError "threadWait" eBADF Nothing Nothing
else return ()
-- used at least by RTS in 'select()' IO manager backend
blockedOnBadFD :: SomeException
blockedOnBadFD = toException $ errnoToIOError "awaitEvent" eBADF Nothing Nothing
threadWaitSTM :: Event -> Fd -> IO (STM (), IO ())
threadWaitSTM evt fd = mask_ $ do
m <- newTVarIO Nothing
mgr <- getSystemEventManager_
reg <- registerFd mgr (\_ e -> atomically (writeTVar m (Just e))) fd evt
let waitAction =
do mevt <- readTVar m
case mevt of
Nothing -> retry
Just evt' ->
if evt' `eventIs` evtClose
then throwSTM $ errnoToIOError "threadWaitSTM" eBADF Nothing Nothing
else return ()
return (waitAction, unregisterFd_ mgr reg >> return ())
-- | Allows a thread to use an STM action to wait for a file descriptor to be readable.
-- The STM action will retry until the file descriptor has data ready.
-- The second element of the return value pair is an IO action that can be used
-- to deregister interest in the file descriptor.
--
-- The STM action will throw an 'IOError' if the file descriptor was closed
-- while the STM action is being executed. To safely close a file descriptor
-- that has been used with 'threadWaitReadSTM', use 'closeFdWith'.
threadWaitReadSTM :: Fd -> IO (STM (), IO ())
threadWaitReadSTM = threadWaitSTM evtRead
{-# INLINE threadWaitReadSTM #-}
-- | Allows a thread to use an STM action to wait until a file descriptor can accept a write.
-- The STM action will retry while the file until the given file descriptor can accept a write.
-- The second element of the return value pair is an IO action that can be used to deregister
-- interest in the file descriptor.
--
-- The STM action will throw an 'IOError' if the file descriptor was closed
-- while the STM action is being executed. To safely close a file descriptor
-- that has been used with 'threadWaitWriteSTM', use 'closeFdWith'.
threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
threadWaitWriteSTM = threadWaitSTM evtWrite
{-# INLINE threadWaitWriteSTM #-}
-- | Retrieve the system event manager for the capability on which the
-- calling thread is running.
--
-- This function always returns 'Just' the current thread's event manager
-- when using the threaded RTS and 'Nothing' otherwise.
getSystemEventManager :: IO (Maybe EventManager)
getSystemEventManager = do
t <- myThreadId
(cap, _) <- threadCapability t
eventManagerArray <- readIORef eventManager
mmgr <- readIOArray eventManagerArray cap
return $ fmap snd mmgr
getSystemEventManager_ :: IO EventManager
getSystemEventManager_ = do
Just mgr <- getSystemEventManager
return mgr
{-# INLINE getSystemEventManager_ #-}
foreign import ccall unsafe "getOrSetSystemEventThreadEventManagerStore"
getOrSetSystemEventThreadEventManagerStore :: Ptr a -> IO (Ptr a)
eventManager :: IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager = unsafePerformIO $ do
numCaps <- getNumCapabilities
eventManagerArray <- newIOArray (0, numCaps - 1) Nothing
em <- newIORef eventManagerArray
sharedCAF em getOrSetSystemEventThreadEventManagerStore
{-# NOINLINE eventManager #-}
numEnabledEventManagers :: IORef Int
numEnabledEventManagers = unsafePerformIO $ do
newIORef 0
{-# NOINLINE numEnabledEventManagers #-}
foreign import ccall unsafe "getOrSetSystemEventThreadIOManagerThreadStore"
getOrSetSystemEventThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)
-- | The ioManagerLock protects the 'eventManager' value:
-- Only one thread at a time can start or shutdown event managers.
{-# NOINLINE ioManagerLock #-}
ioManagerLock :: MVar ()
ioManagerLock = unsafePerformIO $ do
m <- newMVar ()
sharedCAF m getOrSetSystemEventThreadIOManagerThreadStore
getSystemTimerManager :: IO TM.TimerManager
getSystemTimerManager = do
Just mgr <- readIORef timerManager
return mgr
foreign import ccall unsafe "getOrSetSystemTimerThreadEventManagerStore"
getOrSetSystemTimerThreadEventManagerStore :: Ptr a -> IO (Ptr a)
timerManager :: IORef (Maybe TM.TimerManager)
timerManager = unsafePerformIO $ do
em <- newIORef Nothing
sharedCAF em getOrSetSystemTimerThreadEventManagerStore
{-# NOINLINE timerManager #-}
foreign import ccall unsafe "getOrSetSystemTimerThreadIOManagerThreadStore"
getOrSetSystemTimerThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)
{-# NOINLINE timerManagerThreadVar #-}
timerManagerThreadVar :: MVar (Maybe ThreadId)
timerManagerThreadVar = unsafePerformIO $ do
m <- newMVar Nothing
sharedCAF m getOrSetSystemTimerThreadIOManagerThreadStore
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| not threaded = return ()
| otherwise = do
startIOManagerThreads
startTimerManagerThread
startIOManagerThreads :: IO ()
startIOManagerThreads =
withMVar ioManagerLock $ \_ -> do
eventManagerArray <- readIORef eventManager
let (_, high) = boundsIOArray eventManagerArray
mapM_ (startIOManagerThread eventManagerArray) [0..high]
writeIORef numEnabledEventManagers (high+1)
show_int :: Int -> String
show_int i = showSignedInt 0 i ""
restartPollLoop :: EventManager -> Int -> IO ThreadId
restartPollLoop mgr i = do
M.release mgr
!t <- forkOn i $ loop mgr
labelThread t ("IOManager on cap " ++ show_int i)
return t
startIOManagerThread :: IOArray Int (Maybe (ThreadId, EventManager))
-> Int
-> IO ()
startIOManagerThread eventManagerArray i = do
let create = do
!mgr <- new True
!t <- forkOn i $ do
c_setIOManagerControlFd
(fromIntegral i)
(fromIntegral $ controlWriteFd $ M.emControl mgr)
loop mgr
labelThread t ("IOManager on cap " ++ show_int i)
writeIOArray eventManagerArray i (Just (t,mgr))
old <- readIOArray eventManagerArray i
case old of
Nothing -> create
Just (t,em) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> do
-- Sanity check: if the thread has died, there is a chance
-- that event manager is still alive. This could happend during
-- the fork, for example. In this case we should clean up
-- open pipes and everything else related to the event manager.
-- See #4449
c_setIOManagerControlFd (fromIntegral i) (-1)
M.cleanup em
create
_other -> return ()
startTimerManagerThread :: IO ()
startTimerManagerThread = modifyMVar_ timerManagerThreadVar $ \old -> do
let create = do
!mgr <- TM.new
c_setTimerManagerControlFd
(fromIntegral $ controlWriteFd $ TM.emControl mgr)
writeIORef timerManager $ Just mgr
!t <- forkIO $ TM.loop mgr
labelThread t "TimerManager"
return $ Just t
case old of
Nothing -> create
st@(Just t) -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> do
-- Sanity check: if the thread has died, there is a chance
-- that event manager is still alive. This could happend during
-- the fork, for example. In this case we should clean up
-- open pipes and everything else related to the event manager.
-- See #4449
mem <- readIORef timerManager
_ <- case mem of
Nothing -> return ()
Just em -> do c_setTimerManagerControlFd (-1)
TM.cleanup em
create
_other -> return st
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
ioManagerCapabilitiesChanged :: IO ()
ioManagerCapabilitiesChanged = do
withMVar ioManagerLock $ \_ -> do
new_n_caps <- getNumCapabilities
numEnabled <- readIORef numEnabledEventManagers
writeIORef numEnabledEventManagers new_n_caps
eventManagerArray <- readIORef eventManager
let (_, high) = boundsIOArray eventManagerArray
let old_n_caps = high + 1
if new_n_caps > old_n_caps
then do new_eventManagerArray <- newIOArray (0, new_n_caps - 1) Nothing
-- copy the existing values into the new array:
forM_ [0..high] $ \i -> do
Just (tid,mgr) <- readIOArray eventManagerArray i
if i < numEnabled
then writeIOArray new_eventManagerArray i (Just (tid,mgr))
else do tid' <- restartPollLoop mgr i
writeIOArray new_eventManagerArray i (Just (tid',mgr))
-- create new IO managers for the new caps:
forM_ [old_n_caps..new_n_caps-1] $
startIOManagerThread new_eventManagerArray
-- update the event manager array reference:
writeIORef eventManager new_eventManagerArray
else when (new_n_caps > numEnabled) $
forM_ [numEnabled..new_n_caps-1] $ \i -> do
Just (_,mgr) <- readIOArray eventManagerArray i
tid <- restartPollLoop mgr i
writeIOArray eventManagerArray i (Just (tid,mgr))
-- Used to tell the RTS how it can send messages to the I/O manager.
foreign import ccall unsafe "setIOManagerControlFd"
c_setIOManagerControlFd :: CUInt -> CInt -> IO ()
foreign import ccall unsafe "setTimerManagerControlFd"
c_setTimerManagerControlFd :: CInt -> IO ()
|
bitemyapp/ghc
|
libraries/base/GHC/Event/Thread.hs
|
bsd-3-clause
| 14,162
| 0
| 27
| 3,233
| 3,109
| 1,590
| 1,519
| 258
| 5
|
module Generate.JavaScript.Foreign (encode, decode) where
import qualified Data.List as List
import Language.ECMAScript3.Syntax
import qualified AST.Expression.Optimized as Opt
import qualified AST.Literal as Literal
import qualified AST.Type as T
import qualified AST.Variable as Var
import Generate.JavaScript.Helpers ((<|), (==>), function, ref, var)
import qualified Generate.JavaScript.Variable as Var
-- ENCODE
encode :: T.Canonical -> Expression ()
encode tipe =
function ["v"] [ ReturnStmt () (Just (encodeHelp tipe (ref "v"))) ]
encodeHelp :: T.Canonical -> Expression () -> Expression ()
encodeHelp tipe expr =
case tipe of
T.Aliased _ args t ->
encodeHelp (T.dealias args t) expr
T.Lambda _ _ ->
error "encodeHelp: function"
T.Var _ ->
error "encodeHelp: type variable"
T.Type name
| Var.isPrim "Float" name -> expr
| Var.isPrim "Int" name -> expr
| Var.isPrim "Bool" name -> expr
| Var.isPrim "String" name -> expr
| Var.isJson name -> expr
| Var.isTuple name -> NullLit ()
| otherwise -> error "encodeHelp: bad type"
T.App (T.Type name) [arg]
| Var.isMaybe name -> fromMaybe arg expr
| Var.isList name -> fromList arg expr
| Var.isArray name -> fromArray arg expr
| otherwise -> error "encodeHelp: bad union type"
T.App (T.Type name) args
| Var.isTuple name -> fromTuple args expr
T.App _ _ ->
error "encodeHelp: bad union type"
T.Record _ (Just _) ->
error "encodeHelp: bad record"
T.Record fields Nothing ->
let
convert (name, tipe) =
name ==> encodeHelp tipe (DotRef () expr (var name))
in
ObjectLit () (map convert fields)
fromMaybe :: T.Canonical -> Expression () -> Expression ()
fromMaybe tipe expr =
CondExpr ()
(InfixExpr () OpStrictEq (DotRef () expr (var "ctor")) (StringLit () "Nothing"))
(NullLit ())
(encodeHelp tipe (DotRef () expr (var "_0")))
fromList :: T.Canonical -> Expression () -> Expression ()
fromList tipe expr =
let
array =
Var.coreNative "List" "toArray" <| expr
in
DotRef () array (var "map") <| encode tipe
fromArray :: T.Canonical -> Expression () -> Expression ()
fromArray tipe expr =
let
array =
Var.coreNative "Array" "toJSArray" <| expr
in
DotRef () array (var "map") <| encode tipe
fromTuple :: [T.Canonical] -> Expression () -> Expression ()
fromTuple types expr =
let
convert subType n =
encodeHelp subType $ DotRef () expr (var ('_':show n))
in
ArrayLit () (zipWith convert types [0..])
-- SUBSCRIPTIONS
decode :: T.Canonical -> Opt.Expr
decode tipe =
case tipe of
T.Lambda _ _ ->
error "functions should not be allowed through input ports"
T.Var _ ->
error "type variables should not be allowed through input ports"
T.Aliased _ args t ->
decode (T.dealias args t)
T.Type name
| Var.isPrim "Float" name -> to "float"
| Var.isPrim "Int" name -> to "int"
| Var.isPrim "Bool" name -> to "bool"
| Var.isPrim "String" name -> to "string"
| Var.isJson name -> to "value"
| Var.isTuple name -> toTuple0
| otherwise -> error "decode: bad type"
T.App (T.Type name) [arg]
| Var.isMaybe name -> toMaybe arg
| Var.isList name -> to "list" <== [decode arg]
| Var.isArray name -> to "array" <== [decode arg]
| otherwise -> error "decode: bad union type"
T.App (T.Type name) args
| Var.isTuple name -> toTuple args
T.App _ _ ->
error "decode: bad union type"
T.Record _ (Just _) ->
error "decode: bad record"
T.Record fields Nothing ->
toRecord fields
-- DECODE HELPERS
inJsonDecode :: String -> Var.Canonical
inJsonDecode name =
Var.inCore ["Json","Decode"] name
to :: String -> Opt.Expr
to name =
Opt.Var (inJsonDecode name)
(=:) :: String -> Opt.Expr -> Opt.Expr
(=:) name decoder =
Opt.Binop (inJsonDecode ":=") (Opt.Literal (Literal.Str name)) decoder
(<==) :: Opt.Expr -> [Opt.Expr] -> Opt.Expr
(<==) func args =
Opt.Call func args
-- COMPLEX DECODE HELPERS
toMaybe :: T.Canonical -> Opt.Expr
toMaybe tipe =
let
maybe tag =
Opt.Var (Var.inCore ["Maybe"] tag)
in
to "oneOf" <==
[ Opt.ExplicitList
[ to "null" <== [ maybe "Nothing" ]
, to "map" <== [ maybe "Just", decode tipe ]
]
]
toTuple0 :: Opt.Expr
toTuple0 =
to "null" <== [ Opt.Data "_Tuple0" [] ]
toTuple :: [T.Canonical] -> Opt.Expr
toTuple types =
let
size =
length types
args =
map (\n -> 'x' : show n) [ 1 .. size ]
makeTuple =
Opt.Function args (Opt.Data ("_Tuple" ++ show size) (map (Opt.Var . Var.local) args))
in
to ("tuple" ++ show size) <== (makeTuple : map decode types)
toRecord :: [(String, T.Canonical)] -> Opt.Expr
toRecord fields =
let
toFieldExpr (key, _) =
(key, Opt.Var (Var.local key))
finalDecoder =
to "succeed" <== [ Opt.Record (map toFieldExpr fields) ]
andThen (key, tipe) decoder =
to "andThen" <== [ key =: decode tipe, Opt.Function [key] decoder ]
in
List.foldr andThen finalDecoder fields
|
mgold/Elm
|
src/Generate/JavaScript/Foreign.hs
|
bsd-3-clause
| 5,314
| 0
| 17
| 1,447
| 2,014
| 984
| 1,030
| 143
| 9
|
module Arith where
import Data.Char
add::Int->Int->Int
add x y=x+y
addPF :: Int -> Int -> Int
addPF = (+)
addOne :: Int -> Int
addOne = \x->x+1
addOnePF :: Int -> Int
addOnePF = (+1)
main :: IO ()
main = do
print (0 :: Int)
print (add 1 0)
print (addOne 0)
print (addOnePF 0)
print((addOne .addOne)0)
print ((addOnePF . addOne) 0)
print((addOne .addOnePF) 0)
print ((addOnePF . addOnePF) 0)
print (negate (addOne 0))
print ((negate . addOne) 0)
print ((addOne . addOne . addOne . negate . addOne) 0)
g::(a->b)->(a,c)->(b,c)
g f (a,c) = ((f a),c)
myTail:: [t] -> Maybe [t]
myTail [] = Nothing
myTail (_:[]) = Nothing
myTail (_:xs) = Just xs
myHead:: [t] -> Maybe t
myHead [] = Nothing
myHead (x:[]) = Just x
myHead (x:_) = Just x
eftBool :: Bool -> Bool -> [Bool]
eftBool False True = [False, True]
eftBool False False = [False]
eftBool True True = [True]
eftBool True False = []
eftOrd :: Ordering -> Ordering -> [Ordering]
eftOrd x y = case (x > y) of
True -> []
False -> x:(eftOrd (succ x) y)
eftInt :: Int -> Int -> [Int]
eftInt x y = case (x > y) of
True -> []
False -> x:(eftInt (succ x) y)
eftChar :: Char -> Char -> [Char]
eftChar x y = case (x > y) of
True -> []
False -> x:(eftChar (succ x) y)
-- ["p r"] -> ["p","r"]
-- ["pun r"] -> ["pun" "r"]
myWords :: [Char] -> [[Char]]
myWords [] = []
myWords (' ':xs) = myWords xs
myWords xs = f:myWords(r)
where f = takeWhile (/=' ') xs
r = dropWhile (/=' ') xs
mySplit :: Char -> [Char] -> [[Char]]
mySplit _ [] = []
mySplit c xa@(x:xs) = case (x == c) of
True -> mySplit c xs
False -> f:(mySplit c r)
where f = takeWhile (/= c) xa
r = dropWhile (/= c) xa
myWords2 = mySplit ' '
firstSen = "Tyger Tyger, burning bright\n"
secondSen = "In the forests of the night\n"
thirdSen = "What immortal hand or eye\n"
fourthSen = "Could frame thy fearful symmetry?"
sentences = firstSen ++ secondSen ++ thirdSen ++ fourthSen
mySentences = mySplit '\n'
mySqr = [x^2 | x <- [1..5]]
myCube = [y^3 | y <- [1..5]]
myLength :: [a] -> Integer
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
myZip :: [a] -> [b] -> [(a,b)]
myZip [] [] = []
myZip [] ys = []
myZip xs [] = []
myZip (x:xs) (y:ys) = (x,y):(myZip xs ys)
capStr :: [Char] -> [Char]
capStr "woot" = "WOOT"
capStr [] = []
capStr (x:xs) = (toUpper x):xs
capStr2 :: [Char] -> Char
capStr2 = toUpper . head
|
punitrathore/haskell-first-principles
|
src/Arith.hs
|
bsd-3-clause
| 2,376
| 2
| 14
| 536
| 1,337
| 708
| 629
| 86
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Bot.Run where
import Bot.Config
import Bot.Parser.Command
import Bot.Parser.Parser
import Bot.Types
import Bot.Util
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Catch
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Directory
import System.Exit
import System.IO
run :: [String] -> IO ()
run argStrings = do
hSetBuffering stdout NoBuffering
defaultConfigName <- defaultConfiguration
let maybeDefaultConfig = lookup defaultConfigName configsByName
when (null args) $ printHelp maybeDefaultConfig >> exitFailure
execution <- parseExecution defaultConfigName args
(options, (cmd, action)) <- case execution of
ShowHelp ->
printHelp maybeDefaultConfig >> exitSuccess
ShowFullHelp ->
printHelp Nothing >> exitSuccess
RunAction options _ a -> return (options, a)
runAction action options `catch` \(ActionException msg) -> do
if T.null msg
then printf "Command '{}' failed" (Only cmd)
else T.putStrLn msg
exitFailure
where
args = fmap pack argStrings
printHelp maybeConfig = T.putStrLn $ T.intercalate "\n" $
[ "Usage:" ]
++ [ "" ]
++ [ indent 1
$ "bot "
<> "[--help] "
<> "[--config NAME] "
<> "[[--verbose | --show-command-output] | --pipe-commands-to FILENAME] "
<> "COMMAND"
]
++ [ "" ]
++ [ "where" ]
++ [ "" ]
++ configsHelp maybeConfig
configsHelp :: Maybe Configuration -> Help
configsHelp Nothing = allConfigsHelp
configsHelp (Just config) = oneConfigHelp config
allConfigsHelp :: Help
allConfigsHelp = concatMap oneConfigHelp configurations
oneConfigHelp :: Configuration -> Help
oneConfigHelp c = [ "Configuration '{}':" % configName c ]
++ [ "---------------" ]
++ [ "" ]
++ fmap (indent 1) (configHelp c)
++ [ "" ]
data Execution = ShowHelp
| ShowFullHelp
| RunAction Options Configuration (Text, Action)
parseExecution :: Text -> [Text] -> IO Execution
parseExecution defaultConfig args = do
let maybeAction = runParserFully (executionParser defaultConfig) args
case maybeAction of
Left e -> print e >> exitFailure
Right a -> return a
executionParser :: Text -> Parser Execution
executionParser defaultConfig = do
let helpParser = fmap Just (constant "-h" <|> constant "--help") <|> pure Nothing
help <- helpParser
case help of
Just "-h" -> return ShowHelp
Just _ -> return ShowFullHelp
Nothing -> do
config <- configurationParser defaultConfig
let commands = configCommands config
RunAction <$> optionsParser <*> pure config <*> actionParser commands
configurationParser :: Text -> Parser Configuration
configurationParser defaultConfig = do
maybeName <- fmap Just ((,) <$> constant "--config" <*> text) <|> pure Nothing
case maybeName of
Just (_, name) -> lookupConfig name
Nothing -> lookupConfig defaultConfig
where
lookupConfig n = case lookup n configsByName of
Just c -> return c
Nothing -> throwP $ Error [ "Unknown configuration '{}'" % n ]
configsByName :: [(Text, Configuration)]
configsByName = map (configName &&& id) configurations
optionsParser :: Parser Options
optionsParser = Options <$> bashCopyOutputParser
bashCopyOutputParser :: Parser BashCopyOutput
bashCopyOutputParser =
(const ToStdout <$> (constant "--verbose" <|> constant "--show-command-output"))
<|> (const ToFile <$> constant "--pipe-commands-to" <*> path)
<|> pure Off
|
andregr/bot
|
lib/Bot/Run.hs
|
bsd-3-clause
| 3,901
| 0
| 18
| 1,064
| 1,039
| 521
| 518
| 98
| 4
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Bitcoin.BitX.Private
-- Copyright : 2016 Tebello Thejane
-- License : BSD3
--
-- Maintainer : Tebello Thejane <zyxoas+hackage@gmail.com>
-- Stability : Experimental
-- Portability : non-portable (GHC Extensions)
--
-- =The private BitX API.
--
-- Each one of the calls takes at least a 'BitXAuth' containing a previously-created API id and
-- secret (created by visiting
-- <https://bitx.co/settings#/api_keys>), and will return a 'BitXAPIResponse'..
--
-- It would probably be best to create the 'BitXAuth' record using the constructor 'mkBitXAuth' and
-- lens setters:
--
-- @
-- let auth = mkBitXAuth
-- '&' BitX.id '.~' "dude"
-- & BitX.secret .~ "mySecret"
-- let resp = BitX.getBalances auth
-- ...
-- @
--
-- With the OverloadedStrings extension enabled, one may also simply write
-- @
-- let auth = "dude:mySecret" :: BitXAuth
-- @
-- with a colon separating the id from the secret.
--
-- =Permissions
--
-- Each API key is granted a set of permissions when it is created. The key can only be used to call
-- the permitted API functions.
--
-- Here is a list of the possible permissions:
--
-- * @Perm_R_Balance = 1@ (View balance)
-- * @Perm_R_Transactions = 2@ (View transactions)
-- * @Perm_W_Send = 4@ (Send to any address)
-- * @Perm_R_Addresses = 8@ (View addresses)
-- * @Perm_W_Addresses = 16@ (Create addresses)
-- * @Perm_R_Orders = 32@ (View orders)
-- * @Perm_W_Orders = 64@ (Create orders)
-- * @Perm_R_Withdrawals = 128@ (View withdrawals)
-- * @Perm_W_Withdrawals = 256@ (Create withdrawals)
-- * @Perm_R_Merchant = 512@ (View merchant invoices)
-- * @Perm_W_Merchant = 1024@ (Create merchant invoices)
-- * @Perm_W_ClientDebit = 8192@ (Debit accounts)
-- * @Perm_W_ClientCredit = 16384@ (Credit accounts)
-- * @Perm_R_Beneficiaries = 32768@ (View beneficiaries)
-- * @Perm_W_Beneficiaries = 65536@ (Create and delete beneficiaries)
--
-- A set of permissions is represented as the bitwise OR of each permission in the set. For example
-- the set of permissions required to view balances and orders is @Perm_R_Balance | Perm_R_Orders =
-- 33.@
--
-----------------------------------------------------------------------------
module Network.Bitcoin.BitX.Private
(
newAccount,
getBalances,
getFundingAddress,
newFundingAddress,
sendToAddress,
getTransactions,
getPendingTransactions,
module Network.Bitcoin.BitX.Private.Order,
module Network.Bitcoin.BitX.Private.Quote,
--module Network.Bitcoin.BitX.Private.Auth
module Network.Bitcoin.BitX.Private.Withdrawal,
module Network.Bitcoin.BitX.Private.Fees
) where
import Network.Bitcoin.BitX.Internal
import Network.Bitcoin.BitX.Types
import Network.Bitcoin.BitX.Types.Internal
import qualified Data.Text as Txt
import Network.Bitcoin.BitX.Response
import Network.Bitcoin.BitX.Private.Order
--import Network.Bitcoin.BitX.Private.Auth
import Network.Bitcoin.BitX.Private.Quote
import Network.Bitcoin.BitX.Private.Withdrawal
import Network.Bitcoin.BitX.Private.Fees
import Data.Monoid ((<>))
{-# ANN module ("HLint: ignore Use import/export shortcut" :: String) #-}
{- | Create an additional account for the specified currency
Note that the 'id' field of the second parameter can be left blank. The call will return an `Account`
object resembling the parameter, but with the 'id' field filled in with the newly created account's
id.
You must be verified to trade the currency in question in order to be able to create an account.
@Perm_W_Addresses@ permission required. -}
newAccount :: BitXAuth -> Account -> IO (BitXAPIResponse Account)
newAccount auth acc = simpleBitXPOSTAuth_ auth acc "accounts"
{- | Return account balances
@Perm_R_Balance@ permission required. -}
getBalances :: BitXAuth -> IO (BitXAPIResponse [Balance])
getBalances auth = simpleBitXGetAuth_ auth "balance"
{- | Returns the default receive address associated with your account and the amount received via
the address
You can specify an optional address parameter to return information for a non-default receive
address. In the response, total_received is the total confirmed Bitcoin amount received excluding
unconfirmed transactions. total_unconfirmed is the total sum of unconfirmed receive transactions.
@Perm_R_Addresses@ permission is required.
-}
getFundingAddress :: BitXAuth -> Asset -> Maybe Txt.Text -> IO (BitXAPIResponse FundingAddress)
getFundingAddress auth fasset addr = simpleBitXGetAuth_ auth url
where
url = "funding_address?asset=" <> Txt.pack (show fasset) <> case addr of
Nothing -> ""
Just ad -> "&address=" <> ad
{- | Create receive address
Allocates a new receive address to your account. Address creation is rate limited to 1 per hour,
allowing for bursts of up to 10 consecutive calls.
@Perm_R_Addresses@ permission is required.
-}
newFundingAddress :: BitXAuth -> Asset -> IO (BitXAPIResponse FundingAddress)
newFundingAddress auth fasset = simpleBitXPOSTAuth_ auth fasset "funding_address"
{- | Send Bitcoin from your account to a Bitcoin address or email address.
If the email address is not associated with an existing BitX account, an invitation to create an account
and claim the funds will be sent.
__Warning! Bitcoin transactions are irreversible. Please ensure your program has been thoroughly__
__tested before using this call.__
@Perm_W_Send@ permission required. Note that when creating an API key on the BitX site, selecting
"Full access" is not sufficient to add the @Perm_W_Send@ permission. Instead, the permission needs
to be enabled explicitely by selecting "Custom."-}
sendToAddress :: BitXAuth -> BitcoinSendRequest -> IO (BitXAPIResponse RequestSuccess)
sendToAddress auth sreq = simpleBitXPOSTAuth_ auth sreq "send"
{- | Return a list of transaction entries from an account.
Transaction entry rows are numbered sequentially starting from 1, where 1 is the oldest entry. The
range of rows to return are specified with the min_row (inclusive) and max_row (exclusive)
parameters. At most 1000 rows can be requested per call.
If min_row or max_row is nonpositive, the range wraps around the most recent row. For example, to
fetch the 100 most recent rows, use min_row=-100 and max_row=0.
@Perm_R_Transactions@ permission required.
-}
getTransactions
:: BitXAuth
-> AccountID
-> Int -- ^ First row returned, inclusive
-> Int -- ^ Last row returned, exclusive
-> IO (BitXAPIResponse [Transaction])
getTransactions auth accid minr maxr = simpleBitXGetAuth_ auth $
"accounts/" <> accid <> "/transactions?min_row=" <> Txt.pack (show minr) <> "&max_row=" <> Txt.pack (show maxr)
{- | Pending transactions
Return a list of all pending transactions related to the account.
Unlike account entries, pending transactions are not numbered, and may be reordered, deleted or
updated at any time.
@Perm_R_Transactions@ permission required.
-}
getPendingTransactions :: BitXAuth -> AccountID -> IO (BitXAPIResponse [Transaction])
getPendingTransactions auth accid = fmap imebPendingTransactionsToimebTransactions $ simpleBitXGetAuth_ auth $
"accounts/" <> accid <> "/pending"
where
imebPendingTransactionsToimebTransactions (ValidResponse v) = ValidResponse $ pendingTransactionsToTransactions v
imebPendingTransactionsToimebTransactions (ExceptionResponse x) = ExceptionResponse x
imebPendingTransactionsToimebTransactions (ErrorResponse e) = ErrorResponse e
imebPendingTransactionsToimebTransactions (UnparseableResponse a u) = UnparseableResponse a u
|
tebello-thejane/bitx-haskell
|
src/Network/Bitcoin/BitX/Private.hs
|
bsd-3-clause
| 7,690
| 0
| 12
| 1,230
| 701
| 415
| 286
| 53
| 4
|
{-# LANGUAGE RecordWildCards, MultiParamTypeClasses, FlexibleInstances #-}
module Tuura.PetriNet (
Capacity, Weight, Tokens, Marking, PetriNet (..), presetP, postsetP,
readsetP, presetT, postsetT, readsetT, mapP, mapT, mapPT, mapMarking,
enabled, disabled, fire
) where
import Data.Bifunctor
import Data.Set
import Data.Map
type Capacity = Int
type Weight = Int
type Tokens = Int
type Marking p = Map p Tokens
data PetriNet p t = PetriNet
{ places :: Map p Capacity
, transitions :: Set t
, producingArcs :: Map (p, t) Weight
, consumingArcs :: Map (p, t) Weight
, readArcs :: Map (p, t) Weight }
deriving Show
presetP, postsetP, readsetP :: Ord p => PetriNet p t -> p -> Map t Weight
presetP net p = matchFst p $ producingArcs net
postsetP net p = matchFst p $ consumingArcs net
readsetP net p = matchFst p $ readArcs net
presetT, postsetT, readsetT :: Ord t => PetriNet p t -> t -> Map p Weight
presetT net t = matchSnd t $ consumingArcs net
postsetT net t = matchSnd t $ producingArcs net
readsetT net t = matchSnd t $ readArcs net
matchFst :: Eq p => p -> Map (p, t) w -> Map t w
matchFst p = mapKeysMonotonic snd . filterWithKey (\(p', _) _ -> p == p')
matchSnd :: Eq t => t -> Map (p, t) w -> Map p w
matchSnd t = mapKeysMonotonic fst . filterWithKey (\(_, t') _ -> t == t')
mapPT :: (Ord q, Ord u) => (p -> q) -> (t -> u) -> PetriNet p t -> PetriNet q u
mapPT f g PetriNet {..} = PetriNet
(mapKeys f places)
(Data.Set.map g transitions)
(mapKeys (bimap f g) producingArcs)
(mapKeys (bimap f g) consumingArcs)
(mapKeys (bimap f g) readArcs )
mapP :: (Ord q, Ord t) => (p -> q) -> PetriNet p t -> PetriNet q t
mapP f = mapPT f id
mapT :: (Ord p, Ord u) => (t -> u) -> PetriNet p t -> PetriNet p u
mapT = mapPT id
mapMarking :: Ord q => (p -> q) -> Marking p -> Marking q
mapMarking = Data.Map.mapKeys
enabled :: (Ord p, Ord t) => PetriNet p t -> Marking p -> t -> Bool
enabled net m t = foldrWithKey (\p w -> (&& enough p w)) test (presetT net t)
where
test = foldrWithKey (\p w -> (&& enough p w)) True (readsetT net t)
enough p w = findWithDefault 0 p m >= w
disabled :: (Ord p, Ord t) => PetriNet p t -> Marking p -> t -> Bool
disabled net m t = not $ enabled net m t
fire :: (Ord p, Ord t) => PetriNet p t -> t -> Marking p -> Marking p
fire net t m = foldrWithKey (\p w -> adjust (+w) p) m' (postsetT net t)
where
m' = foldrWithKey (\p w -> adjust (subtract w) p) m (presetT net t)
|
tuura/concepts
|
src/Tuura/PetriNet.hs
|
bsd-3-clause
| 2,518
| 0
| 12
| 616
| 1,180
| 617
| 563
| 53
| 1
|
--
-- Copyright (c) 2010 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
import Distribution.Simple
main = defaultMain
|
jean-edouard/idl
|
rpcgen/Setup.hs
|
gpl-2.0
| 815
| 0
| 4
| 148
| 28
| 23
| 5
| 2
| 1
|
#!/usr/bin/env runhaskell --version
import Data.Initial
import Control.Monad
import System.Directory
import System.FilePath
import Base
import Editor.Pickle
import Editor.Pickle.Types
main = do
exists <- doesDirectoryExist dir
when (not exists) $
error (dir ++ " does not exist")
let path = dir </> "empty.nl"
putStrLn ("writing empty level to " ++ show path)
writeSaved path $ pickle $
DiskLevel initial Nothing
dir = "../../data/templateLevels"
|
nikki-and-the-robots/nikki
|
src/scripts/writeEmptyTemplateLevel.hs
|
lgpl-3.0
| 494
| 0
| 10
| 108
| 130
| 65
| 65
| 16
| 1
|
{-# LANGUAGE QuasiQuotes #-}
module TempHask00003 where
str :: String
str = [here|test
test
test test |]
|
charleso/intellij-haskforce
|
tests/gold/parser/TempHask00003.hs
|
apache-2.0
| 106
| 0
| 4
| 18
| 19
| 14
| 5
| 4
| 1
|
{-|
A module exporting only generic functions that choose between compiled and
interpreted mode based on the setting specified in the initializer. This
module is most useful for writitng general snaplets that use Heist and are
meant to be used in applications that might use either interpreted or compiled
templates.
-}
module Snap.Snaplet.Heist.Generic
( Heist
, HasHeist(..)
, SnapletHeist
, SnapletCSplice
-- * Initializer Functions
-- $initializerSection
, addTemplates
, addTemplatesAt
, addConfig
, getHeistState
, modifyHeistState
, withHeistState
-- * Handler Functions
-- $handlerSection
, gRender
, gRenderAs
, gHeistServe
, gHeistServeSingle
, chooseMode
, clearHeistCache
) where
import Snap.Snaplet.Heist
|
sopvop/snap
|
src/Snap/Snaplet/Heist/Generic.hs
|
bsd-3-clause
| 767
| 0
| 5
| 150
| 73
| 51
| 22
| 18
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.C.Data.Name
-- Copyright : (c) 2008 Benedikt Huber
-- License : BSD-style
-- Maintainer : benedikt.huber@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- Unique Names with fast equality (newtype 'Int')
module Language.C.Data.Name (
Name(..),newNameSupply, namesStartingFrom
) where
import Data.Ix
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Generics
-- | Name is a unique identifier
newtype Name = Name { nameId :: Int } deriving (Show, Read, Eq, Ord, Ix, Data, Typeable)
instance Enum Name where
toEnum = Name
fromEnum (Name n) = n
-- | return an infinite stream of 'Name's starting with @nameId@ 0
newNameSupply :: [Name]
newNameSupply = namesStartingFrom 0
-- | get the infinite stream of unique names starting from the given integer
namesStartingFrom :: Int -> [Name]
namesStartingFrom k = [Name k..]
|
wdanilo/haskell-language-c
|
src/Language/C/Data/Name.hs
|
bsd-3-clause
| 1,028
| 0
| 8
| 173
| 178
| 110
| 68
| 15
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti confd types.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Confd.Types
( ConfdClient(..)
, ConfdRequestType(..)
, confdRequestTypeToRaw
, ConfdReqField(..)
, confdReqFieldToRaw
, ConfdReqQ(..)
, ConfdReplyStatus(..)
, confdReplyStatusToRaw
, ConfdNodeRole(..)
, confdNodeRoleToRaw
, ConfdErrorType(..)
, confdErrorTypeToRaw
, ConfdRequest(..)
, newConfdRequest
, ConfdReply(..)
, ConfdQuery(..)
, SignedMessage(..)
) where
import Text.JSON
import qualified Network.Socket as S
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.Hash
import Ganeti.THH
import Ganeti.Utils (newUUID)
$(declareILADT "ConfdRequestType"
[ ("ReqPing", 0)
, ("ReqNodeRoleByName", 1)
, ("ReqNodePipByInstPip", 2)
, ("ReqClusterMaster", 3)
, ("ReqNodePipList", 4)
, ("ReqMcPipList", 5)
, ("ReqInstIpsList", 6)
, ("ReqNodeDrbd", 7)
, ("ReqNodeInstances", 8)
, ("ReqInstanceDisks", 9)
, ("ReqConfigQuery", 10)
, ("ReqDataCollectors", 11)
])
$(makeJSONInstance ''ConfdRequestType)
$(declareILADT "ConfdReqField"
[ ("ReqFieldName", 0)
, ("ReqFieldIp", 1)
, ("ReqFieldMNodePip", 2)
])
$(makeJSONInstance ''ConfdReqField)
-- Confd request query fields. These are used to narrow down queries.
-- These must be strings rather than integers, because json-encoding
-- converts them to strings anyway, as they're used as dict-keys.
$(buildObject "ConfdReqQ" "confdReqQ"
[ renameField "Ip" .
optionalField $
simpleField ConstantUtils.confdReqqIp [t| String |]
, renameField "IpList" .
defaultField [| [] |] $
simpleField ConstantUtils.confdReqqIplist [t| [String] |]
, renameField "Link" .
optionalField $
simpleField ConstantUtils.confdReqqLink [t| String |]
, renameField "Fields" .
defaultField [| [] |] $
simpleField ConstantUtils.confdReqqFields [t| [ConfdReqField] |]
])
-- | Confd query type. This is complex enough that we can't
-- automatically derive it via THH.
data ConfdQuery = EmptyQuery
| PlainQuery String
| DictQuery ConfdReqQ
deriving (Show, Eq)
instance JSON ConfdQuery where
readJSON o = case o of
JSNull -> return EmptyQuery
JSString s -> return . PlainQuery . fromJSString $ s
JSObject _ -> fmap DictQuery (readJSON o::Result ConfdReqQ)
_ -> fail $ "Cannot deserialise into ConfdQuery\
\ the value '" ++ show o ++ "'"
showJSON cq = case cq of
EmptyQuery -> JSNull
PlainQuery s -> showJSON s
DictQuery drq -> showJSON drq
$(declareILADT "ConfdReplyStatus"
[ ("ReplyStatusOk", 0)
, ("ReplyStatusError", 1)
, ("ReplyStatusNotImpl", 2)
])
$(makeJSONInstance ''ConfdReplyStatus)
$(declareILADT "ConfdNodeRole"
[ ("NodeRoleMaster", 0)
, ("NodeRoleCandidate", 1)
, ("NodeRoleOffline", 2)
, ("NodeRoleDrained", 3)
, ("NodeRoleRegular", 4)
])
$(makeJSONInstance ''ConfdNodeRole)
-- Note that the next item is not a frozenset in Python, but we make
-- it a separate type for safety
$(declareILADT "ConfdErrorType"
[ ("ConfdErrorUnknownEntry", 0)
, ("ConfdErrorInternal", 1)
, ("ConfdErrorArgument", 2)
])
$(makeJSONInstance ''ConfdErrorType)
$(buildObject "ConfdRequest" "confdRq"
[ simpleField "protocol" [t| Int |]
, simpleField "type" [t| ConfdRequestType |]
, defaultField [| EmptyQuery |] $ simpleField "query" [t| ConfdQuery |]
, simpleField "rsalt" [t| String |]
])
-- | Client side helper function for creating requests. It automatically fills
-- in some default values.
newConfdRequest :: ConfdRequestType -> ConfdQuery -> IO ConfdRequest
newConfdRequest reqType query = do
rsalt <- newUUID
return $ ConfdRequest ConstantUtils.confdProtocolVersion reqType query rsalt
$(buildObject "ConfdReply" "confdReply"
[ simpleField "protocol" [t| Int |]
, simpleField "status" [t| ConfdReplyStatus |]
, simpleField "answer" [t| JSValue |]
, simpleField "serial" [t| Int |]
])
$(buildObject "SignedMessage" "signedMsg"
[ simpleField "hmac" [t| String |]
, simpleField "msg" [t| String |]
, simpleField "salt" [t| String |]
])
-- | Data type containing information used by the Confd client.
data ConfdClient = ConfdClient
{ hmacKey :: HashKey -- ^ The hmac used for authentication
, peers :: [String] -- ^ The list of nodes to query
, serverPort :: S.PortNumber -- ^ The port where confd server is listening
}
|
grnet/snf-ganeti
|
src/Ganeti/Confd/Types.hs
|
bsd-2-clause
| 6,015
| 0
| 11
| 1,333
| 1,075
| 629
| 446
| 111
| 1
|
module Distribution.Server.Util.ContentType (
parseContentAccept
) where
import Happstack.Server.Types (ContentType(..))
import qualified Text.ParserCombinators.ReadP as Parse
import Control.Monad
import Data.List (find, sortBy)
import Data.Char (isAlphaNum, isDigit)
import Data.Ord (comparing)
-- data VaryFormat = Json | Xml | Html | Plain | Other
-- do some special processing here to fix Webkit's effing issues (and IE's, less so)
-- hackageVaryingAccept :: String -> [VaryFormat]
-- this just returns a list of content-types sorted by quality preference
parseContentAccept :: String -> [ContentType]
parseContentAccept = process . maybe [] fst . find (null . snd) . Parse.readP_to_S parser
where
process :: [(a, Int)] -> [a]
process = map fst . sortBy (flip (comparing snd)) . filter ((/=0) . snd)
parser :: Parse.ReadP [(ContentType, Int)]
parser = flip Parse.sepBy1 (Parse.char ',') $ do
Parse.skipSpaces
-- a more 'accurate' type than (String, String)
-- might be Maybe (String, Maybe String)
typ <- parseMediaType
void $ Parse.char '/'
subTyp <- parseMediaType
quality <- Parse.option 1000 $ do
Parse.skipSpaces >> Parse.string ";q=" >> Parse.skipSpaces
parseQuality
-- TODO: parse other parameters
return (ContentType {ctType = typ, ctSubtype = subTyp, ctParameters = []}, quality)
parseMediaType = (Parse.char '*' >> return []) Parse.<++ Parse.munch1 (\c -> case c of '-' -> True; '.' -> True; '+' -> True; _ -> isAlphaNum c)
-- other characters technically allowed but never found in the wild: !#$%&^_`|~
parseQuality :: Parse.ReadP Int -- returns a quality in fixed point (0.75 -> 750)
parseQuality = (Parse.char '1' >> Parse.optional (Parse.char '.' >> Parse.many (Parse.char '0')) >> return 1000) Parse.<++
(Parse.char '0' >> zeroOption (Parse.char '.' >> zeroOption munch3Digits))
zeroOption :: Parse.ReadP Int -> Parse.ReadP Int
zeroOption p = p Parse.<++ return 0
munch3Digits :: Parse.ReadP Int
munch3Digits = fmap (\s -> read $ take 3 (s++"00") :: Int) (Parse.munch1 isDigit)
--application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
|
mpickering/hackage-server
|
Distribution/Server/Util/ContentType.hs
|
bsd-3-clause
| 2,269
| 0
| 17
| 473
| 620
| 330
| 290
| 30
| 4
|
chain :: (Integral a) => a -> [a]
chain 1 = []
chain n | even n = n : chain (n `div` 2)
| odd n = n : chain (n * 3 + 1)
longChains :: Int
longChains = length (filter isLong [1..100])
where isLong x = (length (chain x)) > 15
longChains' :: Int
longChains' = length (filter isLong (map chain [1..100]))
where isLong x = length x > 15
longChains'' :: Int
longChains'' = length (filter (\x -> length x > 15) (map chain [1..100]))
|
fredmorcos/attic
|
snippets/haskell/Chain.hs
|
isc
| 461
| 0
| 11
| 124
| 247
| 126
| 121
| 12
| 1
|
-- IRC LOG ANALYSER
-- Takes Weechat Logs and does stats on dem
-- Yeh.
import Data.Char
import Data.List
import System.Random
import System.IO
import System.Environment
import Network
import Network.Socket
import Network.HTTP
type Nick = String
type Msg = String
type Time = String
type Entry = (Time,Nick,String)
type Jump = (Nick,Nick)
type Log = [Entry]
type RawLog = [String]
type Blame = [(Nick,Int)]
-- Frontent Features
main = do
theLog <- readLog
swrJSON <- getJSON
putStr $ table $ thin $ swearLeague (jsonToSwears swrJSON) theLog
csvLog = do
theLog <- readLog
putStr $ toCSV $ procLog theLog
-- Do the thing that be what we do
swearLeague :: [(String,Int)] -> RawLog -> Blame
swearLeague swears log = sortScore $ score swears (procLog log) (shrinkBlame (getNickJumps (procLog log)) (buildBlame (procLog log)))
jsonURL :: String
jsonURL = "http://enginger.me/irc-wordlist/wordlist.json"
localSwears :: [(String,Int)]
localSwears = [("cunt",20),
("fuck",10),
("nigger",6),
("vista",6),
("shit",2),
("whore",2),
("asp.net",2),
("vb.net",2),
("slut",1),
("wank",1),
(" windows",1),
("@slap",1),
("bollocks",1),
("tits",1),
("dick",1),
("bastard",1),
("cock",1),
("arse",1),
("emacs",1),
("io monad",1)]
-- Swears with a rank in the tuple - C Bomb is worth money!
-- The more there are, the more computation required
{- Some counterexamples:
Snigger, Vistaed, Shittimwood (so rare I'm allowinf shit infix),
Swanky, Windowsill (Unavoidable (soz)), *asp.net (think of a url),
-}
-- Horrible IO Stuff:
readLog :: IO [String]
readLog = do rlog <- readFile "irc.imaginarynet.#compsoc.weechatlog"
let log = splitByDelim "\n" rlog
return log
getJSON :: IO String
getJSON = do json <- simpleHTTP (getRequest jsonURL) >>= getResponseBody
let swears = json
return swears
jsonToSwears :: String -> [(String,Int)]
jsonToSwears jason = finish ( map (splitByDelim ":") (splitByDelim "," (tail $ init $ init $ init jason)))
where
finish [] = []
finish (stuff:list) = ( (drop 2 $ init $ init stuff!!0) , numerate (stuff!!1) ) : finish list
-- Split a String into a [String] using delimiter 'delim'
splitByDelim :: String -> String -> [String]
splitByDelim delim str = splat delim "" str
where
splat :: String -> String -> String -> [String]
splat [] _ _ = error "Fecking idiot: Delimiter can't be nada"
splat _ _ [] = []
splat delim chop xs
| not ( delim `isInfixOf` xs) = [xs]
| delim `isPrefixOf` xs = chop : splat delim "" (tail xs)
| otherwise = splat delim (chop ++ [head xs]) (tail xs)
-- Process an entry into who said what _OR_ who joined when
procLog :: RawLog -> Log
procLog strs = map splitToEntry strs
-- Parse each line of the log
splitToEntry :: String -> Entry
splitToEntry [] = error "Empty String"
splitToEntry str
| "Day" `isPrefixOf` str = ( drop 15 str ,"$world","/date-change")
| "-->" `isPrefixOf` drop 20 str = ( take 19 str , head (splitByDelim " " (drop 24 str)) , "/joined" )
| "<--" `isPrefixOf` drop 20 str = ( take 19 str , head (splitByDelim " " (drop 24 str)) , "/left" )
| "--" `isPrefixOf` drop 20 str = ( take 19 str , "$notice" , drop 23 str )
| " *" `isPrefixOf` drop 20 str = ( take 19 str , head (splitByDelim " " (head $ tail $ tail (splitByDelim "\t" (drop 19 str)))) , concat $ tail $ tail $ splitByDelim "\t" (drop 19 str) )
| otherwise = ( take 19 str , head $ tail (splitByDelim "\t" (drop 19 str)) , concat $ tail $ tail $ splitByDelim "\t" (drop 19 str) )
-- We use '$' as a special flag in the Nick field because it's invalif for a nick so no-one can ever be $world
-- And we use / as a special flag for content as any client would interpret that as a command and therefore it wouldn't be in the log
-- Ignore date changes
-- The timestamp and tab (YYY-MM-DD HH:MM:SS\t) have length 20
-- Notices begin with -- (For nick changes, topic...)
-- All others should be posts, which are just a tad messy
-- Possible improvement: revert nick changes so stats are complete
-- Kill lurkers!:
lurkKill :: Log -> Log
lurkKill = undefined
-- Maybe not ^^
-- Find Swears:
-- NB: 'swears' is defined at the top of the file
findSwears :: [(String,Int)] -> Entry -> Int
findSwears swears (t,n,str) = find (map toLower str) (map toLower str) swears
where
find :: String -> String -> [(String,Int)] -> Int
find orig [] (swr:swrs) = find orig orig swrs
find _ _ [] = 0
find orig (c:str) (swr:swrs)
| fst swr `isPrefixOf` (c:str) = snd swr + find orig str (swr:swrs)
| otherwise = find orig str (swr:swrs)
-- orig holds the original string and is there because I'm too lazy to do multiple level recursion
-- Filter the list retaining only instances containing:
filterLog :: [String] -> Log -> Log
filterLog [] _ = []
filterLog (this:them) log = find (map toUpper this) log ++ filterLog them log
where
find :: String -> Log -> Log
find _ [] = []
find this ((t,n,c):log)
| this `isInfixOf` (map toUpper c) = (t,n,c) : find this log
| otherwise = find this log
-- Build Blame from Log
buildBlame :: Log -> Blame
buildBlame log = nub (build log)
where
build [] = []
build ((t,n,c):log)
| not( "$" `isInfixOf` n) = ((map toLower n),0) : build log
| otherwise = build log
-- Take all things from the log that match the nick
getNickStuff :: Nick -> Log -> Log
getNickStuff nick log = get (map toUpper nick) log
where
get _ [] = []
get nick ((t,n,c):log)
| nick == (map toUpper n) = (t,n,c) : get nick log
| otherwise = get nick log
-- Strip down a log to joins and leaves
getInOut :: Log -> Log
getInOut [] = []
getInOut ((t,n,c):log)
| c == "/joined" = (t,n,c) : getInOut log
| c == "/left" = (t,n,c) : getInOut log
| otherwise = getInOut log
-- Score nicks on their swearing
score :: [(String,Int)] -> Log -> Blame -> Blame
score _ _ [] = []
score swears log ((nick,val):blame) = ( nick , val + (foldr (+) 0 (map (findSwears swears) (getNickStuff nick log)))) : score swears log blame
-- Apply built in sorting algorithm to Blame
sortScore :: Blame -> Blame
sortScore blame = sortBy compareBlame blame
where
compareBlame a b = snd b `compare` snd a
-- Catch one Nick change
-- A jump looks like ("t2","$notice","nick isnowknown as knack")
-- Jump = (Nick,Nick)
jump :: Entry -> Maybe Jump
jump (t,n,c)
| n == "$notice" && "is now known as" `isInfixOf` c = Just (head $ words c , last $ words c )
| otherwise = Nothing
concatMaybe :: [Maybe a] -> [a]
concatMaybe [] = []
concatMaybe (Nothing:ms) = concatMaybe ms
concatMaybe ((Just a):ms) = a : concatMaybe ms
getNickJumps :: Log -> [Jump]
getNickJumps log = concatMaybe $ map jump log
shrinkBlame :: [Jump] -> Blame -> Blame
shrinkBlame [] blame = nub blame
shrinkBlame (j:js) blame = shrinkBlame js (replace j blame)
where
replace :: Jump -> Blame -> Blame
replace _ [] = []
replace (old,new) ((nick,i):bs)
| nick == old = (new,i) : replace (old,new) bs
| otherwise = (nick,i) : replace (old,new) bs
-- Return the longest nick length
longest :: Blame -> Int
longest blame = count blame 0
where
count [] longest = longest
count ((n,i):blame) longest
| length n > longest = count blame (length n)
| otherwise = count blame longest
-- Remove people who didn't score from the blame
thin :: Blame -> Blame
thin [] = []
thin ((n,i):blame)
| i == 0 = thin blame
| otherwise = (n,i) : thin blame
-- Make the results nice
table :: Blame -> String
table blame = tabulate blame (longest blame)
where
tabulate [] _ = []
tabulate ((n,i):blame) long = n ++ (take (long - (length n)) (repeat ' ')) ++ " -- " ++ (show i) ++ "\n" ++ tabulate blame long
-- Convert the Log to JSON:
toCSV :: Log -> String
toCSV [] = []
toCSV ((t,n,c):log) = "\"" ++ t ++ "\",\"" ++ n ++ "\",\"" ++ c ++ "\"\n" ++ toCSV log
-- Convert a number that's a char to a literal Int
strInt :: Char -> Int
strInt a = (ord a) - 48
-- Convert a string inot a literal Int
numerate :: String -> Int
numerate [] = 0
numerate a@(digit:ds) = ((strInt digit) * 10^(length a -1)) + numerate ds
|
AngusP/NSFWbot
|
irclog.hs
|
mit
| 8,489
| 0
| 17
| 2,102
| 3,113
| 1,656
| 1,457
| 163
| 3
|
-- https://www.hackerrank.com/challenges/fp-hello-world
hello_world = putStr "Hello World"
-- This part relates to Input/Output and can be used as it is. Do not modify this section
main = do
hello_world
|
Seblink/HackerRank
|
functional-programming/introduction/fp-hello-world.hs
|
mit
| 208
| 0
| 6
| 34
| 19
| 10
| 9
| 3
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: Network.SIP.Parser.RequestLine
-- Description: Request line parser.
-- Copyright: Copyright (c) 2015-2016 Jan Sipr
-- License: MIT
module Network.SIP.Parser.RequestLine
( firstLineParser
)
where
import Control.Applicative ((<*))
import Control.Monad (return, fail)
import Data.Attoparsec.ByteString.Char8 (char, takeTill, (<?>))
import Data.Attoparsec.ByteString (Parser)
import Data.Either (Either(Right, Left))
import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Monoid ((<>))
import Data.Text (unpack)
import Network.SIP.Parser.RequestMethod (requestMethodParser)
import Network.SIP.Parser.SipVersion (sipVersionParser)
import Network.SIP.Parser.Uri (parseUri)
import Network.SIP.Type.Message (MessageType(Request))
import Network.SIP.Type.Uri (Uri)
firstLineParser :: Parser MessageType
firstLineParser = do
method <- requestMethodParser <* char ' ' <?> "method parser"
uri <- requestUri
return $ Request method uri
where
requestUri :: Parser Uri
requestUri = do
us <- takeTill (== ' ') <* char ' ' <* sipVersionParser
case parseUri us of
(Left e) -> fail . unpack $ e <> "parseUri method failed"
(Right u) -> return u
|
Siprj/ragnarok
|
src/Network/SIP/Parser/RequestLine.hs
|
mit
| 1,313
| 0
| 14
| 237
| 346
| 207
| 139
| 29
| 2
|
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-}
class TooMany a where
tooMany :: a -> Bool
instance TooMany Int where
tooMany n = n > 42
newtype Goats =
Goats (Int, String) deriving (Eq, Show)
newtype Goats2 =
Goats2 (Int, Int) deriving (Eq, Show)
instance TooMany Goats where
tooMany (Goats (n, _)) = n > 42
instance TooMany Goats2 where
tooMany (Goats2 (n1, n2)) = (n1 + n2) > 42
instance (Num a, TooMany a) => TooMany (a, a) where
tooMany (t1, t2) = tooMany (t1 + t2)
|
candu/haskellbook
|
ch11/tooMany.hs
|
mit
| 506
| 0
| 9
| 106
| 214
| 117
| 97
| 15
| 0
|
import Control.Monad
import Data.List.Extra
import Data.Maybe
import qualified Data.Char as C
import qualified Data.Map as Map
import qualified Data.Set as Set
------
iread :: String -> Int
iread = read
do2 f g x = (f x, g x)
answer :: (Show a) => (String -> a) -> IO ()
answer f = interact $ (++"\n") . show . f
ord0 c = C.ord c - C.ord 'a'
chr0 i = C.chr (i + C.ord 'a')
incletter c i = chr0 ((ord0 c + i) `mod` 26)
splitOn1 a b = fromJust $ stripInfix a b
rsplitOn1 a b = fromJust $ stripInfixEnd a b
-- pull out every part of a String that can be read in
-- for some Read a and ignore the rest
readOut :: Read a => String -> [a]
readOut "" = []
readOut s = case reads s of
[] -> readOut $ tail s
[(x, s')] -> x : readOut s'
_ -> error "ambiguous parse"
ireadOut :: String -> [Int]
ireadOut = readOut
--------
lpair [x, y] = (x, y)
dist (x0, y0) (x1, y1) = abs (x0 - x1) + abs (y0 - y1)
closest pairs loc = if isNothing other then Just k else Nothing
where (v, k) = minimum $ map (\k -> (dist k loc, k)) pairs
other = find (\other -> dist other loc == v && other /= k) pairs
solve pairs = maximum $ counts
where offset = 5
minx = (minimum $ map fst pairs) - offset
maxx = (maximum $ map fst pairs) + offset
miny = (minimum $ map snd pairs) - offset
maxy = (maximum $ map snd pairs) + offset
infinity = [(x, y) | x <- [minx..maxx], y <- [miny, maxy]] ++
[(x, y) | x <- [minx,maxx], y <- [miny..maxy]]
all = [(x, y) | x <- [minx..maxx], y <- [miny..maxy]]
infinite = nub $ map (closest pairs) infinity
all_ds = filter (not . (`elem` infinite)) $ map (closest pairs) all
counts = map length $ group $ sort all_ds
main = answer $ solve . map lpair . map ireadOut . lines
|
msullivan/advent-of-code
|
2018/A6a.hs
|
mit
| 1,792
| 0
| 13
| 478
| 854
| 459
| 395
| 42
| 3
|
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings, ScopedTypeVariables #-}
import Yesod.Core
import Yesod.WebSockets
import qualified Data.Text.Lazy as TL
import Control.Monad (forever)
import Control.Monad.Trans.Reader
import Control.Concurrent (threadDelay)
import Data.Time
import Conduit
import Data.Monoid ((<>))
import Control.Concurrent.STM.Lifted
import Data.Text (Text)
import UnliftIO.Exception (try, SomeException)
data App = App (TChan Text)
instance Yesod App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
chatApp :: WebSocketsT Handler ()
chatApp = do
sendTextData ("Welcome to the chat server, please enter your name." :: Text)
name <- receiveData
sendTextData $ "Welcome, " <> name
App writeChan <- getYesod
readChan <- atomically $ do
writeTChan writeChan $ name <> " has joined the chat"
dupTChan writeChan
(e :: Either SomeException ()) <- try $ race_
(forever $ atomically (readTChan readChan) >>= sendTextData)
(sourceWS $$ mapM_C (\msg ->
atomically $ writeTChan writeChan $ name <> ": " <> msg))
atomically $ case e of
Left _ -> writeTChan writeChan $ name <> " has left the chat"
Right () -> return ()
getHomeR :: Handler Html
getHomeR = do
webSockets chatApp
defaultLayout $ do
[whamlet|
<div #output>
<form #form>
<input #input autofocus>
|]
toWidget [lucius|
\#output {
width: 600px;
height: 400px;
border: 1px solid black;
margin-bottom: 1em;
p {
margin: 0 0 0.5em 0;
padding: 0 0 0.5em 0;
border-bottom: 1px dashed #99aa99;
}
}
\#input {
width: 600px;
display: block;
}
|]
toWidget [julius|
var url = document.URL,
output = document.getElementById("output"),
form = document.getElementById("form"),
input = document.getElementById("input"),
conn;
url = url.replace("http:", "ws:").replace("https:", "wss:");
conn = new WebSocket(url);
conn.onmessage = function(e) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(e.data));
output.appendChild(p);
};
form.addEventListener("submit", function(e){
conn.send(input.value);
input.value = "";
e.preventDefault();
});
|]
main :: IO ()
main = do
chan <- atomically newBroadcastTChan
warp 3000 $ App chan
|
yesodweb/yesod
|
yesod-websockets/chat.hs
|
mit
| 2,806
| 0
| 19
| 966
| 445
| 231
| 214
| 43
| 2
|
module Subsequence where
import Data.Char
import Data.List hiding (isSubsequenceOf)
isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool
isSubsequenceOf [] [] = True
isSubsequenceOf [] _ = True
isSubsequenceOf _ [] = False
isSubsequenceOf ss@(x:xs) (y:ys) =
(x == y && isSubsequenceOf xs ys) || (isSubsequenceOf ss ys)
splitStringBy :: Char -> String -> [String]
splitStringBy c = foldl (\ss s -> if s == c then ss++[""] else (take (length ss - 1) ss) ++ [last ss ++ [s]]) [""]
splitWords :: String -> [String]
splitWords = splitStringBy ' '
capitalizeWords :: String -> [(String, String)]
capitalizeWords = map (\s -> (s, firstToUpper s)) . splitWords
firstToUpper :: String -> String
firstToUpper "" = ""
firstToUpper (x:xs)
| x /= ' ' = (toUpper x) : xs
| otherwise = x : (firstToUpper xs)
capitalizeSentences :: String -> String
capitalizeSentences = concat . intersperse "." . map firstToUpper . splitStringBy '.'
|
JoshuaGross/haskell-learning-log
|
Code/Haskellbook/Subsequence.hs
|
mit
| 948
| 0
| 14
| 187
| 410
| 219
| 191
| 22
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Site
( app
) where
import Api.Core
import Control.Applicative
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Util.FileServe
import Heist
import qualified Heist.Interpreted as I
import Application
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = []
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
api <- nestSnaplet "api" api apiInit
addRoutes routes
return $ App api
|
cackharot/heub
|
app/Site.hs
|
mit
| 852
| 0
| 9
| 230
| 183
| 108
| 75
| 24
| 1
|
module Yobemag.Binary
( Word
, Byte
, highByte
, lowByte
, toWord
) where
import qualified Data.Word as W
import Data.Bits
type Word = W.Word16
type Byte = W.Word8
highByte :: Word -> Byte
highByte = fromIntegral . (`shiftR` 8)
lowByte :: Word -> Byte
lowByte = fromIntegral . (.&. 0xff)
-- arguments in little endian order
toWord :: Byte -> Byte -> Word
toWord l h = shiftL (fromIntegral h) 8 + fromIntegral l
|
nadirs/yobemag
|
src/Yobemag/Binary.hs
|
mit
| 441
| 0
| 8
| 105
| 140
| 83
| 57
| 16
| 1
|
module Qy.Random where
import System.Random
import Data.Char (isAlphaNum)
import qualified Data.Text as T
randomText :: IO T.Text
randomText = do
gen <- newStdGen
let s = T.pack . take 128 $ filter isAlphaNum $ randomRs ('A', 'z') gen
return s
|
realli/chatqy
|
src/Qy/Random.hs
|
mit
| 258
| 0
| 13
| 54
| 97
| 51
| 46
| 9
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html
module Stratosphere.ResourceProperties.KinesisFirehoseDeliveryStreamProcessor where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.KinesisFirehoseDeliveryStreamProcessorParameter
-- | Full data type definition for KinesisFirehoseDeliveryStreamProcessor. See
-- 'kinesisFirehoseDeliveryStreamProcessor' for a more convenient
-- constructor.
data KinesisFirehoseDeliveryStreamProcessor =
KinesisFirehoseDeliveryStreamProcessor
{ _kinesisFirehoseDeliveryStreamProcessorParameters :: [KinesisFirehoseDeliveryStreamProcessorParameter]
, _kinesisFirehoseDeliveryStreamProcessorType :: Val Text
} deriving (Show, Eq)
instance ToJSON KinesisFirehoseDeliveryStreamProcessor where
toJSON KinesisFirehoseDeliveryStreamProcessor{..} =
object $
catMaybes
[ (Just . ("Parameters",) . toJSON) _kinesisFirehoseDeliveryStreamProcessorParameters
, (Just . ("Type",) . toJSON) _kinesisFirehoseDeliveryStreamProcessorType
]
-- | Constructor for 'KinesisFirehoseDeliveryStreamProcessor' containing
-- required fields as arguments.
kinesisFirehoseDeliveryStreamProcessor
:: [KinesisFirehoseDeliveryStreamProcessorParameter] -- ^ 'kfdspParameters'
-> Val Text -- ^ 'kfdspType'
-> KinesisFirehoseDeliveryStreamProcessor
kinesisFirehoseDeliveryStreamProcessor parametersarg typearg =
KinesisFirehoseDeliveryStreamProcessor
{ _kinesisFirehoseDeliveryStreamProcessorParameters = parametersarg
, _kinesisFirehoseDeliveryStreamProcessorType = typearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html#cfn-kinesisfirehose-deliverystream-processor-parameters
kfdspParameters :: Lens' KinesisFirehoseDeliveryStreamProcessor [KinesisFirehoseDeliveryStreamProcessorParameter]
kfdspParameters = lens _kinesisFirehoseDeliveryStreamProcessorParameters (\s a -> s { _kinesisFirehoseDeliveryStreamProcessorParameters = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html#cfn-kinesisfirehose-deliverystream-processor-type
kfdspType :: Lens' KinesisFirehoseDeliveryStreamProcessor (Val Text)
kfdspType = lens _kinesisFirehoseDeliveryStreamProcessorType (\s a -> s { _kinesisFirehoseDeliveryStreamProcessorType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/KinesisFirehoseDeliveryStreamProcessor.hs
|
mit
| 2,572
| 0
| 13
| 219
| 269
| 157
| 112
| 30
| 1
|
{-# LANGUAGE ImplicitParams #-}
{- This file is free to use, distribute, and modify, even commercially. Originally written by John-Michael Reed (who is not legally liable) -}
module Debug.Print.StackTraceDebug where
{- Requires GHC version 7.10.1 (or greater) to compile -}
{- Suggested for use with IntelliJ or EclipseFP -}
import Control.Concurrent -- for myThreadID
import Debug.Trace -- for traceIO
import GHC.Stack
import GHC.SrcLoc -- this is for getting the fine name, line number, etc.
import System.Info -- this is for getting os
import Data.List -- isInfixOf, intercalate
import Data.List.Split -- used for splitting strings
import System.Exit -- for fatal assert
-- | Set to "False" and recompile in order to disable print statements with stack traces.
--
debugMode :: Bool
debugMode = True
-- | Prints message with a one line stack trace (formatted like a Java Exception for IDE usability). Meant to be a substitute for Debug.Trace.traceIO
--
debugTraceIO :: (?loc :: CallStack) => String -> IO ()
debugTraceIO message = do -- Warning: "callStacks <- return(getCallStack (?loc))" cannot be replaced with "let callStacks = getCallStack (?loc)" because doing so would mess up the call stack.
callStacks <- return(getCallStack (?loc)) -- returns [(String, SrcLoc)]
let callStack = Data.List.last callStacks -- returns (String, SrcLoc)
let callOrigin = snd callStack -- returns SrcLoc
let pathToFileName = srcLocModule callOrigin
let fileName = srcLocFile callOrigin
let lineNumber = show(srcLocStartLine callOrigin)
noMonadThreadId <- myThreadId -- myThreadId returns IO(ThreadID)
let threadName = show noMonadThreadId
let threadNameWords = splitOn " " threadName -- break up thread name along spaces
let threadNumberString = Data.List.last threadNameWords -- this isn't working
let fileNameSplit = if (("win" `isInfixOf` os) || ("Win" `isInfixOf` os) || "mingw" `isInfixOf` os)
then splitOn "\\" fileName
else splitOn "/" fileName
let fileNameNoCruff = if (length fileNameSplit > 1)
then last (tail fileNameSplit)
else head fileNameSplit
let lineOne = message ++ " in" ++ " thread" ++ " " ++ "\"" ++ threadNumberString ++ "\"" ++ " :"
let lineTwo = " " ++ "at " ++ pathToFileName ++ ".call" ++ "(" ++ fileNameNoCruff ++ ":" ++ lineNumber ++ ")"
let toPrint = if ((Data.List.isInfixOf "win" os) || (Data.List.isInfixOf "Win" os) || (Data.List.isInfixOf "mingw" os))
then lineOne ++ "\r\n" ++ lineTwo ++ "\r\n"
else lineOne ++ "\n" ++ lineTwo ++ "\n" -- linesOneAndTwo = unlines [lineOne, lineTwo])
if debugMode
then traceIO toPrint
else return()
{- Warning: Reduce duplication. The below code cannot be refactored out into a function because doing so would break the stack trace -}
-- | Kills the application and prints the message with a one line stack trace (formatted like a Java Exception for IDE usability) if assertion is false and "debugMode" is True. Can be used as a substitute for "assert" when used in a Java based IDE or when the killing of the entire application is warranted.
--
fatalAssert :: (?loc :: CallStack) => Bool -> String -> IO ()
fatalAssert assertion message =
if not debugMode
then return()
else if assertion
then return()
else do -- Warning: "callStacks <- return(getCallStack (?loc))" cannot be replaced with "let callStacks = getCallStack (?loc)" because doing so would mess up the call stack.
callStacks <- return(getCallStack (?loc)) -- returns [(String, SrcLoc)]
let callStack = Data.List.last callStacks -- returns (String, SrcLoc)
let callOrigin = snd callStack -- returns SrcLoc
let pathToFileName = srcLocModule callOrigin
let fileName = srcLocFile callOrigin
let lineNumber = show(srcLocStartLine callOrigin)
noMonadThreadId <- myThreadId -- myThreadId returns IO(ThreadID)
let threadName = show noMonadThreadId
let threadNameWords = splitOn " " threadName -- break up thread name along spaces
let threadNumberString = Data.List.last threadNameWords -- this isn't working
let fileNameSplit = if (("win" `isInfixOf` os) || ("Win" `isInfixOf` os) || "mingw" `isInfixOf` os)
then splitOn "\\" fileName
else splitOn "/" fileName
let fileNameNoCruff = if (length fileNameSplit > 1)
then last (tail fileNameSplit)
else head fileNameSplit
let lineOne = message ++ " in" ++ " thread" ++ " " ++ "\"" ++ threadNumberString ++ "\"" ++ " :"
let lineTwo = " " ++ "at " ++ pathToFileName ++ ".call" ++ "(" ++ fileNameNoCruff ++ ":" ++ lineNumber ++ ")"
let toPrint = if ((Data.List.isInfixOf "win" os) || (Data.List.isInfixOf "Win" os) || (Data.List.isInfixOf "mingw" os))
then lineOne ++ "\r\n" ++ lineTwo ++ "\r\n"
else lineOne ++ "\n" ++ lineTwo ++ "\n" -- linesOneAndTwo = unlines [lineOne, lineTwo])
traceIO toPrint
die "This application died due to a fatal assertion."
-- | Shorthand for "debugTraceIO". Prints a message with a formatted stack trace.
--
prt :: (?loc :: CallStack) => String -> IO ()
prt = debugTraceIO
-- | This method tests the "debugTraceIO" function.
--
test :: IO()
test = do
fatalAssert True "Error message"
debugTraceIO "foobarbaz"
debugTraceIO "lalalalaaaaa"
prt "Shorthand for debugTraceIO"
fatalAssert False "premature death in StackTraceDebug.test"
{-
foobarbaz in thread "1" :
at Moc.Print.StackTraceDebug.call(StackTraceDebug.hs:98)
lalalalaaaaa in thread "1" :
at Moc.Print.StackTraceDebug.call(StackTraceDebug.hs:99)
Shorthand for debugTraceIO in thread "1" :
at Moc.Print.StackTraceDebug.call(StackTraceDebug.hs:100)
premature death in StackTraceDebug.test in thread "1" :
at Moc.Print.StackTraceDebug.call(StackTraceDebug.hs:101)
This application died due to a fatal assertion.
-}
|
JohnReedLOL/HaskellPrintDebugger
|
src/Debug/Print/StackTraceDebug.hs
|
cc0-1.0
| 6,413
| 0
| 19
| 1,688
| 1,102
| 570
| 532
| 77
| 6
|
{- |
Module : ./SoftFOL/ProveDarwin.hs
Description : Interface to the TPTP theorem prover via Darwin.
Copyright : (c) Heng Jiang, Uni Bremen 2004-2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : needs POSIX
Interface for the Darwin service, uses GUI.GenericATP.
See <http://spass.mpi-sb.mpg.de/> for details on SPASS, and
<http://combination.cs.uiowa.edu/Darwin/> for Darwin.
-}
module SoftFOL.ProveDarwin
( darwinProver
, darwinCMDLautomaticBatch
, darwinConsChecker
, runDarwinProcess
, ProverBinary (..)
, darwinExe
, proverBinary
, tptpProvers
, eproverOpts
) where
-- preliminary hacks for display of CASL models
import Logic.Prover
import SoftFOL.Sign
import SoftFOL.Translate
import SoftFOL.ProverState
import SoftFOL.EProver
import Common.AS_Annotation as AS_Anno
import qualified Common.Result as Result
import Common.ProofTree
import Common.ProverTools
import Common.SZSOntology
import Common.Utils
import Data.Char (isDigit)
import Data.List
import Data.Maybe
import Data.Time (timeToTimeOfDay)
import Data.Time.Clock (secondsToDiffTime)
import Control.Monad (when)
import qualified Control.Concurrent as Concurrent
import System.Directory
import System.Process (waitForProcess, runInteractiveCommand,
runProcess, terminateProcess)
import System.IO (hGetContents, openFile, hClose, IOMode (WriteMode))
import Control.Exception as Exception
import GUI.GenericATP
import Interfaces.GenericATPState
import Proofs.BatchProcessing
import qualified Data.Map as Map
import qualified Data.Set as Set
-- * Prover implementation
data ProverBinary = Darwin | DarwinFD | EDarwin | EProver | Leo | IProver
deriving (Enum, Bounded)
tptpProvers :: [ProverBinary]
tptpProvers = [minBound .. maxBound]
proverBinary :: ProverBinary -> String
proverBinary b = darwinExe b ++
case b of
Darwin -> "-non-fd"
_ -> ""
darwinExe :: ProverBinary -> String
darwinExe b = case b of
Darwin -> "darwin"
DarwinFD -> "darwin"
EDarwin -> "e-darwin"
EProver -> "eprover"
Leo -> "leo"
IProver -> "iproveropt"
{- | The Prover implementation. First runs the batch prover (with
graphical feedback), then starts the GUI prover. -}
darwinProver
:: ProverBinary -> Prover Sign Sentence SoftFOLMorphism () ProofTree
darwinProver b =
mkAutomaticProver (darwinExe b) (proverBinary b) () (darwinGUI b)
$ darwinCMDLautomaticBatchAux b
darwinConsChecker
:: ProverBinary -> ConsChecker Sign Sentence () SoftFOLMorphism ProofTree
darwinConsChecker b =
(mkUsableConsChecker (darwinExe b) (proverBinary b) () $ consCheck b)
{ ccNeedsTimer = False }
{- |
Record for prover specific functions. This is used by both GUI and command
line interface.
-}
atpFun :: ProverBinary -- ^ the actual binary
-> String -- ^ theory name
-> ATPFunctions Sign Sentence SoftFOLMorphism ProofTree SoftFOLProverState
atpFun b thName = ATPFunctions
{ initialProverState = spassProverState
, atpTransSenName = transSenName
, atpInsertSentence = insertSentenceGen
, goalOutput = showTPTPProblem thName
, proverHelpText = "no help for darwin available"
, batchTimeEnv = "HETS_SPASS_BATCH_TIME_LIMIT"
, fileExtensions = FileExtensions
{ problemOutput = ".tptp"
, proverOutput = ".spass"
, theoryConfiguration = ".spcf" }
, runProver = runDarwin b
, createProverOptions = extraOpts }
-- ** GUI
{- |
Invokes the generic prover GUI. SPASS specific functions are omitted by
data type ATPFunctions.
-}
darwinGUI
:: ProverBinary -- ^ the actual binary
-> String -- ^ theory name
-> Theory Sign Sentence ProofTree
-- ^ theory consisting of a signature and sentences
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO [ProofStatus ProofTree] -- ^ proof status for each goal
darwinGUI b thName th freedefs =
genericATPgui (atpFun b thName) True (proverBinary b) thName th
freedefs emptyProofTree
-- ** command line function
{- |
Implementation of 'Logic.Prover.proveCMDLautomaticBatch' which provides an
automatic command line interface to the Darwin prover.
Darwin specific functions are omitted by data type ATPFunctions.
-}
darwinCMDLautomaticBatch
:: Bool -- ^ True means include proved theorems
-> Bool -- ^ True means save problem file
-> Concurrent.MVar (Result.Result [ProofStatus ProofTree])
-- ^ used to store the result of the batch run
-> String -- ^ theory name
-> TacticScript -- ^ default tactic script
-> Theory Sign Sentence ProofTree
-- ^ theory consisting of a signature and sentences
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO (Concurrent.ThreadId, Concurrent.MVar ())
{- ^ fst: identifier of the batch thread for killing it
snd: MVar to wait for the end of the thread -}
darwinCMDLautomaticBatch = darwinCMDLautomaticBatchAux Darwin
darwinCMDLautomaticBatchAux
:: ProverBinary -- ^ the actual binary
-> Bool -- ^ True means include proved theorems
-> Bool -- ^ True means save problem file
-> Concurrent.MVar (Result.Result [ProofStatus ProofTree])
-- ^ used to store the result of the batch run
-> String -- ^ theory name
-> TacticScript -- ^ default tactic script
-> Theory Sign Sentence ProofTree
-- ^ theory consisting of a signature and sentences
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO (Concurrent.ThreadId, Concurrent.MVar ())
{- ^ fst: identifier of the batch thread for killing it
snd: MVar to wait for the end of the thread -}
darwinCMDLautomaticBatchAux b inclProvedThs saveProblem_batch resultMVar
thName defTS th freedefs =
genericCMDLautomaticBatch (atpFun b thName) inclProvedThs saveProblem_batch
resultMVar (proverBinary b) thName
(parseTacticScript batchTimeLimit [] defTS) th freedefs emptyProofTree
-- * Main prover functions
eproverOpts :: String -> String
eproverOpts verb = "-xAuto -tAuto --tptp3-format " ++ verb
++ " --memory-limit=2048 --soft-cpu-limit="
extras :: ProverBinary -> Bool -> String -> String
extras b cons tl = let
tOut = " -to " ++ tl
darOpt = "-pc false"
fdOpt = darOpt ++ (if cons then " -pmtptp true" else "") ++ " -fd true"
in case b of
EProver -> eproverOpts (if cons then "-s" else "") ++ tl
Leo -> "-t " ++ tl
Darwin -> darOpt ++ tOut
DarwinFD -> fdOpt ++ tOut
EDarwin -> fdOpt ++ " -eq Axioms" ++ tOut
IProver -> "--time_out_real " ++ tl ++ " --sat_mode true"
{- | Runs the Darwin service. The tactic script only contains a string for the
time limit. -}
consCheck
:: ProverBinary
-> String
-> TacticScript
-> TheoryMorphism Sign Sentence SoftFOLMorphism ProofTree
-> [FreeDefMorphism SPTerm SoftFOLMorphism] -- ^ freeness constraints
-> IO (CCStatus ProofTree)
consCheck b thName (TacticScript tl) tm freedefs = case tTarget tm of
Theory sig nSens -> do
let proverStateI = spassProverState sig (toNamedList nSens) freedefs
prob <- showTPTPProblemM thName proverStateI []
(exitCode, out, tUsed) <-
runDarwinProcess (darwinExe b) False (extras b True tl) thName prob
let outState = CCStatus
{ ccResult = Just True
, ccProofTree = ProofTree $ unlines $ exitCode : out
, ccUsedTime = timeToTimeOfDay $ secondsToDiffTime
$ toInteger tUsed }
return $ if szsProved exitCode then outState else
outState
{ ccResult = if szsDisproved exitCode then Just False
else Nothing }
runDarwinProcess
:: String -- ^ binary name
-> Bool -- ^ save problem
-> String -- ^ options
-> String -- ^ filename without extension
-> String -- ^ problem
-> IO (String, [String], Int)
runDarwinProcess bin saveTPTP options tmpFileName prob = do
let tmpFile = basename tmpFileName ++ ".tptp"
when saveTPTP (writeFile tmpFile prob)
noProg <- missingExecutableInPath bin
if noProg then
return (bin ++ " not found. Check your $PATH", [], -1)
else do
timeTmpFile <- getTempFile prob tmpFile
(_, pout, perr) <-
executeProcess bin (words options ++ [timeTmpFile]) ""
let l = lines $ pout ++ perr
(res, _, tUsed) = parseOutput l
removeFile timeTmpFile
return (res, l, tUsed)
mkGraph :: String -> IO ()
mkGraph f = do
fContent <- readFile f
let fLines = lines fContent
let ((p_set, (cs, axs)), res) =
processProof (zipF proofInfo $ zipF conjectures axioms)
(Set.empty, ([], [])) $ reverse fLines
(aliases, _) = processProof alias Map.empty fLines
same_rank = intercalate "; " $ map (\ (_, n) -> 'v' : n) $
filter (\ (_, n) -> Set.member n p_set
&& isNothing (Map.lookup n aliases)) $ cs ++ axs
case res of
Just s -> putStrLn s
_ -> return ()
writeFile "/tmp/graph.dot" $ unlines ["digraph {",
"subgraph { rank = same; " ++ same_rank ++ " }",
(\ (_, _, d, _) -> d) . fst $ processProof (digraph p_set aliases)
(Set.empty, Set.empty, "", Map.empty) fLines, "}"]
runEProverBuffered
:: Bool -- ^ save problem
-> Bool
-> Bool
-> String -- ^ options
-> String -- ^ filename without extension
-> String -- ^ problem
-> IO (String, [String], Int)
runEProverBuffered saveTPTP graph fullgraph options tmpFileName prob = do
s <- supportsProofObject
let tmpFile = basename tmpFileName ++ ".tptp"
useProofObject = s && not fullgraph
bin = if useProofObject then "eprover"
else "eproof"
noProg <- missingExecutableInPath bin
when saveTPTP (writeFile tmpFile prob)
if noProg then return (bin ++ " not found. Check your $PATH", [], -1)
else do
(err, out) <-
do
timeTmpFile <- getTempFile prob tmpFile
(_, out, err, _) <-
if graph || fullgraph || not s then do
bufferFile <- getTempFile "" "eprover-proof-buffer"
buff <- openFile bufferFile WriteMode
h <- runProcess bin (words options ++
["--proof-object" | useProofObject] ++ [timeTmpFile])
Nothing Nothing Nothing (Just buff) (Just buff)
(waitForProcess h >> removeFile timeTmpFile)
`Exception.catch` (\ ThreadKilled -> terminateProcess h)
hClose buff
mkGraph bufferFile
runInteractiveCommand $ unwords ["egrep", "axiom|SZS",
bufferFile, "&&", "rm", "-f", bufferFile]
else runInteractiveCommand $ unwords
[bin, "--proof-object", options, timeTmpFile,
"|", "egrep", "axiom|SZS", "&&", "rm", timeTmpFile]
return (out, err)
perr <- hGetContents err
pout <- hGetContents out
let l = lines $ perr ++ pout
(res, _, tUsed) = parseOutput l
return (res, l, tUsed)
runDarwin
:: ProverBinary
-> SoftFOLProverState
{- ^ logical part containing the input Sign and axioms and possibly
goals that have been proved earlier as additional axioms -}
-> GenericConfig ProofTree -- ^ configuration to use
-> Bool -- ^ True means save TPTP file
-> String -- ^ name of the theory in the DevGraph
-> AS_Anno.Named SPTerm -- ^ goal to prove
-> IO (ATPRetval, GenericConfig ProofTree)
-- ^ (retval, configuration with proof status and complete output)
runDarwin b sps cfg saveTPTP thName nGoal = do
let bin = darwinExe b
(options, graph, fullgraph) = case b of
EProver ->
let w = extraOpts cfg
in (filter (not . (\ e -> elem e ["--graph", "--full-graph"])) w,
elem "--graph" w, elem "--full-graph" w)
_ -> (extraOpts cfg, False, False)
tl = maybe "10" show $ timeLimit cfg
extraOptions = extras b False tl
tmpFileName = thName ++ '_' : AS_Anno.senAttr nGoal
prob <- showTPTPProblem thName sps nGoal
$ options ++ ["Requested prover: " ++ bin]
(exitCode, out, tUsed) <- case b of
EProver -> runEProverBuffered saveTPTP graph fullgraph
extraOptions tmpFileName prob
_ -> runDarwinProcess bin saveTPTP extraOptions tmpFileName prob
axs <- case b of
EProver | szsProved exitCode ||
szsDisproved exitCode ->
case processProof axioms [] out of
(l, Nothing) -> return $ map fst l
(_, Just err) -> do
putStrLn err
return $ getAxioms sps
_ -> return $ getAxioms sps
let ctime = timeToTimeOfDay $ secondsToDiffTime $ toInteger tUsed
(err, retval) = case () of
_ | szsProved exitCode -> (ATPSuccess, provedStatus)
_ | szsDisproved exitCode -> (ATPSuccess, disProvedStatus)
_ | szsTimeout exitCode ->
(ATPTLimitExceeded, defaultProofStatus)
_ | szsStopped exitCode ->
(ATPBatchStopped, defaultProofStatus)
_ -> (ATPError exitCode, defaultProofStatus)
defaultProofStatus =
(openProofStatus
(AS_Anno.senAttr nGoal) bin emptyProofTree)
{ usedTime = ctime
, tacticScript = TacticScript $ show ATPTacticScript
{tsTimeLimit = configTimeLimit cfg,
tsExtraOpts = options} }
disProvedStatus = defaultProofStatus {goalStatus = Disproved}
provedStatus = defaultProofStatus
{ goalName = AS_Anno.senAttr nGoal
, goalStatus = Proved True
, usedAxioms = axs
, usedProver = bin
, usedTime = timeToTimeOfDay $ secondsToDiffTime $ toInteger tUsed
}
return (err, cfg {proofStatus = retval,
resultOutput = case b of
EProver -> reverse out
_ -> out,
timeUsed = ctime })
getSZSStatusWord :: String -> Maybe String
getSZSStatusWord line = case words $ fromMaybe ""
$ stripPrefix "SZS status" $ dropWhile (`elem` "%# ") line of
[] -> Nothing
w : _ -> Just w
parseOutput :: [String] -> (String, Bool, Int)
-- ^ (exit code, status found, used time)
parseOutput = foldl' checkLine ("could not determine SZS status", False, -1)
where checkLine (exCode, stateFound, to) line =
if isPrefixOf "Couldn't find eprover" line
|| isInfixOf "darwin -h for further information" line
-- error by running darwin.
then (line, stateFound, to)
else case getSZSStatusWord line of
Just szsState | not stateFound ->
(szsState, True, to)
_ -> if "CPU Time" `isPrefixOf` line -- get cpu time
then let time = case takeWhile isDigit $ last (words line) of
ds@(_ : _) -> read ds
_ -> to
in (exCode, stateFound, time)
else (exCode, stateFound, to)
|
spechub/Hets
|
SoftFOL/ProveDarwin.hs
|
gpl-2.0
| 15,194
| 0
| 23
| 4,058
| 3,620
| 1,919
| 1,701
| 316
| 10
|
module System.DevUtils.Redis.Helpers.CommandStats (
module A
) where
import System.DevUtils.Redis.Helpers.CommandStats.Include as A
import System.DevUtils.Redis.Helpers.CommandStats.Default as A
import System.DevUtils.Redis.Helpers.CommandStats.Parser as A
import System.DevUtils.Redis.Helpers.CommandStats.Marshall as A
import System.DevUtils.Redis.Helpers.CommandStats.JSON as A
import System.DevUtils.Redis.Helpers.CommandStats.Run as A
|
adarqui/DevUtils-Redis
|
src/System/DevUtils/Redis/Helpers/CommandStats.hs
|
gpl-3.0
| 442
| 0
| 4
| 33
| 81
| 65
| 16
| 8
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Text as T
import System.Console.Haskeline
import Language.Java.Pretty
import Parser
import PrettyPrint
import TypeCheck
main :: IO ()
main = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do
minput <- getInputLine "pts> "
case minput of
Nothing -> return ()
Just "" -> loop
Just ":q" -> return ()
Just cmds -> dispatch cmds
dispatch :: String -> InputT IO ()
dispatch cmds =
let e@(cmd:progm) = words cmds
in case cmd of
-- ":clr" -> do
-- outputStrLn "Environment cleaned up!"
-- loop [] [] -- initalBEnv initalEnv
-- ":env" -> do
-- outputStrLn $ "Typing environment: " ++ show env
-- outputStrLn $ "Binding environment: " ++ show (map fst benv)
-- loop benv env
-- ":add" -> delegate progm "Command parse error - :add name type" $
-- \name xs -> do
-- outputStrLn "Added!"
-- loop benv (extend (name, Logic) (head xs) env)
-- ":let" -> delegate progm "Command parse error - :let name expr" $
-- \name xs -> do
-- outputStrLn "Added new term!"
-- loop ((name, head xs) : benv) env
":e" -> processCMD progm $
\xs -> do
let xs' = eval xs
outputStrLn ("\n--- Evaluation result ---\n\n" ++ (T.unpack . showExpr $ xs') ++ "\n")
loop
":p" -> processCMD progm $
\xs -> do
outputStrLn ("\n--- Pretty printing ---\n\n" ++ (T.unpack . showExpr $ xs) ++ "\n")
loop
_ -> processCMD e $
\xs -> do
case typecheck xs of
Left err -> outputStrLn . T.unpack $ err
Right typ -> outputStrLn ("\n--- Typing result ---\n\n" ++ (T.unpack . showExpr $ typ) ++ "\n")
loop
where
processCMD expr func =
case parseExpr . unwords $ expr of
Left err -> do
outputStrLn . show $ err
loop
Right xs -> func xs
|
xnning/TypeInfer
|
src/Main.hs
|
gpl-3.0
| 2,200
| 0
| 26
| 832
| 463
| 235
| 228
| 43
| 8
|
{-# LANGUAGE RecordWildCards,ViewPatterns,ScopedTypeVariables #-}
{-
Find appropriate translations of QuickSpec strings to core
bindings, data constructors or type constructors.
-}
module HipSpec.Sig.Resolve
( ResolveMap(..)
, lookupSym
, lookupTyCon
, maybeLookupSym
, maybeLookupTyCon
, makeResolveMap
, debugStr
) where
import Test.QuickSpec.Signature
import Test.QuickSpec.Term hiding (Var,symbols,size)
import Test.QuickSpec.Utils.Typed (typeRepTyCons)
import GHC hiding (Sig)
import CoreMonad
import HipSpec.Params
import Control.Monad
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.Typeable as Typeable
import HipSpec.GHC.Utils
import HipSpec.Sig.Scope
import HipSpec.Utils
-- | Mappings for QuickSpec symbols and Typeable Tycons to GHC Core structures
data ResolveMap = ResolveMap
{ sym_map :: Map Symbol Id
, tycon_map :: Map Typeable.TyCon TyCon
}
makeResolveMap :: Params -> Sig -> Ghc ResolveMap
makeResolveMap p@Params{..} sig = do
-- functions and constrctors
syms <- forM (nubSorted (constantSymbols sig)) $ \ symb -> do
things <- lookupString (name symb)
case mapJust thingToId things of
Just i -> return (symb,i)
Nothing -> error $ "Not in scope: " ++ name symb
-- type constructors
tcs <- forM (nubSorted (concatMap (typeRepTyCons . symbolType) (symbols sig))) $ \ tc -> do
things <- lookupString (Typeable.tyConName tc)
let getTc (ATyCon tc') = Just tc'
getTc _ = Nothing
case mapJust getTc things of
Just tc' -> return (tc,tc')
Nothing -> error $ "Type constructor not in scope:" ++ Typeable.tyConName tc
whenFlag p DebugStrConv $ liftIO $ do
putStrLn "Symbol translation"
mapM_ putStrLn
[ " " ++ show s ++ " -> " ++ showOutputable ts
| (s,ts) <- syms
]
putStrLn "Type constructor translation"
mapM_ putStrLn
[ " " ++ show tc ++ " -> " ++ showOutputable ts
| (tc,ts) <- tcs
]
return ResolveMap
{ sym_map = M.fromList syms
, tycon_map = M.fromList tcs
}
maybeLookupSym :: ResolveMap -> Symbol -> Maybe Id
maybeLookupSym sm s = M.lookup s (sym_map sm)
maybeLookupTyCon :: ResolveMap -> Typeable.TyCon -> Maybe TyCon
maybeLookupTyCon sm t = M.lookup t (tycon_map sm)
debugStr :: String
debugStr =
"\nDebug the conversions between QuickSpec signatures and GHC Core " ++
"structures with --debug-str-conv."
lookupSym :: ResolveMap -> Symbol -> Id
lookupSym m s = fromMaybe (error err_str) (maybeLookupSym m s)
where
err_str =
"Cannot translate QuickSpec's " ++ show s ++
" to Core representation! " ++ debugStr
lookupTyCon :: ResolveMap -> Typeable.TyCon -> TyCon
lookupTyCon m s = fromMaybe (error err_str) (maybeLookupTyCon m s)
where
err_str =
"Cannot translate Data.Typeable type constructor " ++ show s ++
" to Core representation! " ++ debugStr
|
danr/hipspec
|
src/HipSpec/Sig/Resolve.hs
|
gpl-3.0
| 3,106
| 0
| 17
| 802
| 817
| 425
| 392
| 70
| 4
|
{-|
Module : Cell
Description : A Cell of a Sudoku
Copyright : (c) Frédéric BISSON 2015
License : GPL-3
Maintainer : zigazou@free.fr
Stability : experimental
Portability : POSIX
This module handles a `Cell` in a Sudoku grid. It keeps track of every possible
`Token` the `Cell` could have.
-}
module Sudoku.Cell
( Cell (Cell, cValue, cPossibles)
, makeCell
, removePossibles
, isSet
)
where
import Data.Set (Set)
import qualified Data.Set as Set
import Sudoku.Token (Token (T1, T9))
{-|
A `Cell` may contain a `Token` or be empty.
-}
data Cell = Cell
{ cValue :: Maybe Token -- ^ The `Token` or `Nothing`
, cPossibles :: Set Token -- ^ Possible `Token`s the `Cell` could contain
}
instance Eq Cell where
(==) c1 c2 = cValue c1 == cValue c2
instance Show Cell where
show (Cell Nothing _) = " "
show (Cell (Just t) _) = show t
{-|
Make a `Cell` given a `Token`. It initializes the `cPossibles` field with
every `Token` possible if the `Cell` is empty. If the `Cell` is not empty, the
`cPossibles` field is initialized with the `Token`.
-}
makeCell :: Maybe Token -> Cell
makeCell mt@(Just t) = Cell mt (Set.singleton t)
makeCell _ = Cell Nothing (Set.fromList [T1 .. T9])
{-|
Given a `Cell`, it removes all the `Token`s from the given `Set` from this
`Cell` possible tokens. If there remains one and only one possible `Token`,
the `Cell` is automatically filled with this `Token`.
-}
removePossibles :: Cell -> Set Token -> Cell
removePossibles (Cell v ps) ts = Cell value possibles
where possibles = Set.difference ps ts
value | Set.size possibles == 1 = Just $ Set.elemAt 0 possibles
| otherwise = v
{-|
Tells if a `Cell` is filled with a `Token` or not.
-}
isSet :: Cell -> Bool
isSet (Cell (Just _) _) = True
isSet _ = False
|
Zigazou/Sudoku
|
src/Sudoku/Cell.hs
|
gpl-3.0
| 1,817
| 0
| 12
| 402
| 376
| 203
| 173
| 29
| 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.Run.Projects.Locations.Services.SetIAMPolicy
-- 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)
--
-- Sets the IAM Access control policy for the specified Service. Overwrites
-- any existing policy.
--
-- /See:/ <https://cloud.google.com/run/ Cloud Run Admin API Reference> for @run.projects.locations.services.setIamPolicy@.
module Network.Google.Resource.Run.Projects.Locations.Services.SetIAMPolicy
(
-- * REST Resource
ProjectsLocationsServicesSetIAMPolicyResource
-- * Creating a Request
, projectsLocationsServicesSetIAMPolicy
, ProjectsLocationsServicesSetIAMPolicy
-- * Request Lenses
, plssipXgafv
, plssipUploadProtocol
, plssipAccessToken
, plssipUploadType
, plssipPayload
, plssipResource
, plssipCallback
) where
import Network.Google.Prelude
import Network.Google.Run.Types
-- | A resource alias for @run.projects.locations.services.setIamPolicy@ method which the
-- 'ProjectsLocationsServicesSetIAMPolicy' request conforms to.
type ProjectsLocationsServicesSetIAMPolicyResource =
"v1" :>
CaptureMode "resource" "setIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SetIAMPolicyRequest :>
Post '[JSON] Policy
-- | Sets the IAM Access control policy for the specified Service. Overwrites
-- any existing policy.
--
-- /See:/ 'projectsLocationsServicesSetIAMPolicy' smart constructor.
data ProjectsLocationsServicesSetIAMPolicy =
ProjectsLocationsServicesSetIAMPolicy'
{ _plssipXgafv :: !(Maybe Xgafv)
, _plssipUploadProtocol :: !(Maybe Text)
, _plssipAccessToken :: !(Maybe Text)
, _plssipUploadType :: !(Maybe Text)
, _plssipPayload :: !SetIAMPolicyRequest
, _plssipResource :: !Text
, _plssipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsServicesSetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plssipXgafv'
--
-- * 'plssipUploadProtocol'
--
-- * 'plssipAccessToken'
--
-- * 'plssipUploadType'
--
-- * 'plssipPayload'
--
-- * 'plssipResource'
--
-- * 'plssipCallback'
projectsLocationsServicesSetIAMPolicy
:: SetIAMPolicyRequest -- ^ 'plssipPayload'
-> Text -- ^ 'plssipResource'
-> ProjectsLocationsServicesSetIAMPolicy
projectsLocationsServicesSetIAMPolicy pPlssipPayload_ pPlssipResource_ =
ProjectsLocationsServicesSetIAMPolicy'
{ _plssipXgafv = Nothing
, _plssipUploadProtocol = Nothing
, _plssipAccessToken = Nothing
, _plssipUploadType = Nothing
, _plssipPayload = pPlssipPayload_
, _plssipResource = pPlssipResource_
, _plssipCallback = Nothing
}
-- | V1 error format.
plssipXgafv :: Lens' ProjectsLocationsServicesSetIAMPolicy (Maybe Xgafv)
plssipXgafv
= lens _plssipXgafv (\ s a -> s{_plssipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plssipUploadProtocol :: Lens' ProjectsLocationsServicesSetIAMPolicy (Maybe Text)
plssipUploadProtocol
= lens _plssipUploadProtocol
(\ s a -> s{_plssipUploadProtocol = a})
-- | OAuth access token.
plssipAccessToken :: Lens' ProjectsLocationsServicesSetIAMPolicy (Maybe Text)
plssipAccessToken
= lens _plssipAccessToken
(\ s a -> s{_plssipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plssipUploadType :: Lens' ProjectsLocationsServicesSetIAMPolicy (Maybe Text)
plssipUploadType
= lens _plssipUploadType
(\ s a -> s{_plssipUploadType = a})
-- | Multipart request metadata.
plssipPayload :: Lens' ProjectsLocationsServicesSetIAMPolicy SetIAMPolicyRequest
plssipPayload
= lens _plssipPayload
(\ s a -> s{_plssipPayload = a})
-- | REQUIRED: The resource for which the policy is being specified. See the
-- operation documentation for the appropriate value for this field.
plssipResource :: Lens' ProjectsLocationsServicesSetIAMPolicy Text
plssipResource
= lens _plssipResource
(\ s a -> s{_plssipResource = a})
-- | JSONP
plssipCallback :: Lens' ProjectsLocationsServicesSetIAMPolicy (Maybe Text)
plssipCallback
= lens _plssipCallback
(\ s a -> s{_plssipCallback = a})
instance GoogleRequest
ProjectsLocationsServicesSetIAMPolicy
where
type Rs ProjectsLocationsServicesSetIAMPolicy =
Policy
type Scopes ProjectsLocationsServicesSetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsServicesSetIAMPolicy'{..}
= go _plssipResource _plssipXgafv
_plssipUploadProtocol
_plssipAccessToken
_plssipUploadType
_plssipCallback
(Just AltJSON)
_plssipPayload
runService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsServicesSetIAMPolicyResource)
mempty
|
brendanhay/gogol
|
gogol-run/gen/Network/Google/Resource/Run/Projects/Locations/Services/SetIAMPolicy.hs
|
mpl-2.0
| 5,994
| 0
| 16
| 1,287
| 781
| 457
| 324
| 122
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.ServiceControl.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.ServiceControl.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | 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
|
brendanhay/gogol
|
gogol-servicecontrol/gen/Network/Google/ServiceControl/Types/Sum.hs
|
mpl-2.0
| 1,231
| 0
| 11
| 292
| 197
| 114
| 83
| 26
| 0
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE OverloadedStrings #-}
module Test.Api where
import Data.Aeson
import Data.Swagger.Build.Api
import Prelude hiding (min, max)
import Test.Tasty
import Test.Tasty.HUnit
import qualified Data.ByteString.Lazy.Char8 as B
tests :: TestTree
tests = testGroup "example declarations"
[ testCase "api" (render apiDecl)
, testCase "model foo" (render foo)
]
where
render :: ToJSON a => a -> IO ()
render = B.putStrLn . encode
apiDecl :: ApiDecl
apiDecl = declare "http://petstore.swagger.wordnik.com/api" "1.2" $ do
apiVersion "1.0.0"
resourcePath "/store"
model foo
model bar
produces "application/json"
produces "text/html"
produces "text/plain"
api "/store/order/{orderId}" $ do
operation "GET" "foo" $ do
summary "give me some foo"
notes "but only the good one"
returns (ref foo)
parameter Header "type" (string $ enum ["bar", "baz"]) $ do
description "specifies the type of foo"
optional
parameter Query "format" (string $ enum ["plain", "html"]) $
description "output format"
parameter Query "size" (int32 $ min 1 . max 100 . def 10) $
description "amount of foo"
produces "application/json"
produces "text/html"
response 200 "OK" (model foo)
response 400 "Bad Request" end
operation "POST" "foo" $ do
summary "something else"
deprecated
foo :: Model
foo = defineModel "Foo" $ do
description "A bottle of foo"
property "rabbit" (array int32') $
description "A foo's rabbit"
property "white" (bool $ def False) $ do
description "a white rabbit?"
optional
property "bar" (ref bar) end
bar :: Model
bar = defineModel "Bar" $
property "foo" (ref foo) end
|
twittner/swagger
|
test/Test/Api.hs
|
mpl-2.0
| 2,094
| 0
| 20
| 601
| 532
| 250
| 282
| 54
| 1
|
{-# LANGUAGE OverloadedStrings, RecordWildCards, TemplateHaskell, QuasiQuotes, DataKinds #-}
module Model.Asset
( module Model.Asset.Types
-- , blankAsset
, assetBacked
, lookupAsset
, lookupOrigAsset
, lookupVolumeAsset
, addAsset
, changeAsset
, assetCreation
, assetRowJSON
, assetJSON
-- , assetJSONRestricted
) where
import Control.Arrow (first)
import Data.Maybe (isNothing, isJust)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Database.PostgreSQL.Typed (pgSQL)
import Database.PostgreSQL.Typed.Query
import Database.PostgreSQL.Typed.Types
import qualified Data.ByteString
import Data.ByteString (ByteString)
import qualified Data.String
import Ops
import Has (view, peek)
import qualified JSON
import Service.DB
import Files
import Store.Types
import Store.Asset
import Model.SQL
import Model.Time
import Model.Audit
import Model.Id
import Model.Identity
import Model.Party
import Model.Volume
import Model.Format
import Model.Asset.Types
import Model.Asset.SQL
mapQuery :: ByteString -> ([PGValue] -> a) -> PGSimpleQuery a
mapQuery qry mkResult =
fmap mkResult (rawPGSimpleQuery qry)
assetBacked :: Asset -> Bool
assetBacked = isJust . assetSHA1 . assetRow
lookupAsset :: (MonadHasIdentity c m, MonadDB c m) => Id Asset -> m (Maybe Asset)
lookupAsset ai = do
ident <- peek
dbQuery1 $(selectQuery (selectAsset 'ident) "$WHERE asset.id = ${ai}")
lookupOrigAsset :: (MonadHasIdentity c m, MonadDB c m) => Id Asset -> m (Maybe Asset)
lookupOrigAsset ai = do
ident <- peek
dbQuery1 $(selectQuery (selectAsset 'ident) "$left join transcode tc on tc.orig = asset.id WHERE asset.id = ${ai}")
lookupVolumeAsset :: (MonadDB c m) => Volume -> Id Asset -> m (Maybe Asset)
lookupVolumeAsset vol ai = do
let _tenv_a87rh = unknownPGTypeEnv
dbQuery1 $ (`Asset` vol) <$> -- .(selectQuery selectAssetRow "WHERE asset.id = ${ai} AND asset.volume = ${volumeId $ volumeRow vol}")
fmap
(\ (vid_a87qZ, vformat_a87r0, vrelease_a87r1, vduration_a87r2,
vname_a87r3, vc_a87r4, vsize_a87r5)
-> makeAssetRow
vid_a87qZ
vformat_a87r0
vrelease_a87r1
vduration_a87r2
vname_a87r3
vc_a87r4
vsize_a87r5)
(mapQuery
((\ _p_a87ri _p_a87rj ->
(Data.ByteString.concat
[Data.String.fromString
"SELECT asset.id,asset.format,asset.release,asset.duration,asset.name,asset.sha1,asset.size FROM asset WHERE asset.id = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87ri,
Data.String.fromString " AND asset.volume = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87rj]))
ai (volumeId $ volumeRow vol))
(\
[_cid_a87rk,
_cformat_a87rl,
_crelease_a87rm,
_cduration_a87rn,
_cname_a87ro,
_csha1_a87rp,
_csize_a87rq]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a87rk,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "smallint")
_cformat_a87rl,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "release")
_crelease_a87rm,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "interval")
_cduration_a87rn,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a87ro,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bytea")
_csha1_a87rp,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a87rh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bigint")
_csize_a87rq)))
addAsset :: (MonadAudit c m, MonadStorage c m) => Asset -> Maybe RawFilePath -> m Asset
addAsset ba fp = do
ident <- getAuditIdentity
ba' <- maybe (return ba) (storeAssetFile ba) fp
let _tenv_a87Hi = unknownPGTypeEnv
dbQuery1' -- .(insertAsset 'ident 'ba')
(fmap
(setAssetId ba')
(mapQuery
((\ _p_a87Hj
_p_a87Hk
_p_a87Hr
_p_a87Hv
_p_a87Hw
_p_a87Hx
_p_a87Hy
_p_a87Hz
_p_a87HB ->
(Data.ByteString.concat
[Data.String.fromString
"WITH audit_row AS (INSERT INTO asset (volume,format,release,duration,name,sha1,size) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87Hj,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "smallint")
_p_a87Hk,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "release")
_p_a87Hr,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "interval")
_p_a87Hv,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a87Hw,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bytea")
_p_a87Hx,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bigint")
_p_a87Hy,
Data.String.fromString
") RETURNING *) INSERT INTO audit.asset SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87Hz,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a87HB,
Data.String.fromString
", 'add'::audit.action, * FROM audit_row RETURNING asset.id"]))
(volumeId $ volumeRow $ assetVolume ba')
(formatId $ assetFormat $ assetRow ba')
(assetRelease $ assetRow ba')
(assetDuration $ assetRow ba')
(assetName $ assetRow ba')
(assetSHA1 $ assetRow ba')
(assetSize $ assetRow ba')
(auditWho ident)
(auditIp ident))
(\ [_cid_a87HC]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a87Hi
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a87HC))))
changeAsset :: (MonadAudit c m, MonadStorage c m) => Asset -> Maybe RawFilePath -> m Asset
changeAsset a fp = do
ident <- getAuditIdentity
a2 <- maybe (return a) (storeAssetFile a) fp
let _tenv_a87Mj = unknownPGTypeEnv
dbExecute1' -- .(updateAsset 'ident 'a2)
(mapQuery
((\ _p_a87Mk
_p_a87Ml
_p_a87Mm
_p_a87Mn
_p_a87Mo
_p_a87Mp
_p_a87Mq
_p_a87Mr
_p_a87Ms
_p_a87Mt ->
(Data.ByteString.concat
[Data.String.fromString
"WITH audit_row AS (UPDATE asset SET volume=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87Mk,
Data.String.fromString ",format=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "smallint")
_p_a87Ml,
Data.String.fromString ",release=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "release")
_p_a87Mm,
Data.String.fromString ",duration=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "interval")
_p_a87Mn,
Data.String.fromString ",name=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a87Mo,
Data.String.fromString ",sha1=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bytea")
_p_a87Mp,
Data.String.fromString ",size=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bigint")
_p_a87Mq,
Data.String.fromString " WHERE id=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87Mr,
Data.String.fromString
" RETURNING *) INSERT INTO audit.asset SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a87Ms,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a87Mj
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a87Mt,
Data.String.fromString
", 'change'::audit.action, * FROM audit_row"]))
(volumeId $ volumeRow $ assetVolume a2)
(formatId $ assetFormat $ assetRow a2)
(assetRelease $ assetRow a2)
(assetDuration $ assetRow a2)
(assetName $ assetRow a2)
(assetSHA1 $ assetRow a2)
(assetSize $ assetRow a2)
(assetId $ assetRow a2)
(auditWho ident)
(auditIp ident))
(\[] -> ()))
return a2
assetCreation :: MonadDB c m => Asset -> m (Maybe Timestamp, Maybe T.Text)
assetCreation a = maybe (Nothing, Nothing) (first Just) <$>
dbQuery1 [pgSQL|$SELECT audit_time, name FROM audit.asset WHERE id = ${assetId $ assetRow a} AND audit_action = 'add' ORDER BY audit_time DESC LIMIT 1|]
assetRowJSON :: JSON.ToObject o => AssetRow -> JSON.Record (Id Asset) o
assetRowJSON AssetRow{..} = JSON.Record assetId $
"format" JSON..= formatId assetFormat
<> "classification" `JSON.kvObjectOrEmpty` assetRelease
<> "duration" `JSON.kvObjectOrEmpty` assetDuration
<> "pending" `JSON.kvObjectOrEmpty` (isNothing assetSize `useWhen` isNothing assetSHA1)
assetJSON :: JSON.ToObject o => Bool -> Asset -> JSON.Record (Id Asset) o
assetJSON _ Asset{..} = assetRowJSON assetRow -- first parameter is publicRestricted
-- assetJSONRestricted :: JSON.ToObject o => Asset -> JSON.Record (Id Asset) o
-- assetJSONRestricted Asset{..} = assetRowJSON assetRow
|
databrary/databrary
|
src/Model/Asset.hs
|
agpl-3.0
| 16,318
| 0
| 22
| 6,357
| 2,634
| 1,520
| 1,114
| 324
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{- |
Utility module dealing with ANSI colors.
-}
--
-- Copyright (c) 2011-2022 Stefan Wehr - http://www.stefanwehr.de
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library 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
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
--
module Test.Framework.Colors (
Color(..), PrimColor(..), ColorString(..), PrimColorString(..)
, firstDiffColor, secondDiffColor, skipDiffColor, diffColor
, warningColor, testStartColor, testOkColor, pendingColor
, emptyColorString, (+++), unlinesColorString, colorStringFind, ensureNewlineColorString
, colorize, colorizeText, colorize', colorizeText'
, noColor, noColorText, noColor', noColorText'
, renderColorString, maxLength
) where
import qualified Data.Text as T
import Data.String
import Data.Maybe
import Control.Monad
firstDiffColor = Color Magenta False
secondDiffColor = Color Blue False
skipDiffColor = Color DarkGray False
diffColor = Color Brown False
warningColor = Color Red True
testStartColor = Color NoColor True
testOkColor = Color Green False
pendingColor = Color Cyan True
data Color = Color PrimColor Bool
deriving (Eq, Show, Read)
data PrimColor = Black | Blue | Green | Cyan | Red | Magenta
| Brown | Gray | DarkGray | LightBlue
| LightGreen | LightCyan | LightRed | LightMagenta
| Yellow | White | NoColor
deriving (Eq, Show, Read)
startColor :: Color -> T.Text
startColor (Color c isBold) =
(case c of
Black -> "\ESC[0;30m"
Blue -> "\ESC[0;34m"
Green -> "\ESC[0;32m"
Cyan -> "\ESC[0;36m"
Red -> "\ESC[0;31m"
Magenta -> "\ESC[0;35m"
Brown -> "\ESC[0;33m"
Gray -> "\ESC[0;37m"
DarkGray -> "\ESC[1;30m"
LightBlue -> "\ESC[1;34m"
LightGreen -> "\ESC[1;32m"
LightCyan -> "\ESC[1;36m"
LightRed -> "\ESC[1;31m"
LightMagenta -> "\ESC[1;35m"
Yellow -> "\ESC[1;33m"
White -> "\ESC[1;37m"
NoColor -> "") `T.append`
(if isBold then "\ESC[1m" else "")
reset :: T.Text
reset = "\ESC[0;0m"
data PrimColorString = PrimColorString Color T.Text (Maybe T.Text) {- no-color fallback -}
deriving (Eq, Show, Read)
newtype ColorString = ColorString { unColorString :: [PrimColorString] }
deriving (Eq, Show, Read)
instance IsString ColorString where
fromString = noColor
emptyColorString :: ColorString
emptyColorString = noColor ""
maxLength :: ColorString -> Int
maxLength (ColorString prims) =
let ml (PrimColorString _ t mt) =
max (T.length t) (fromMaybe 0 (fmap T.length mt))
in sum $ map ml prims
unlinesColorString :: [ColorString] -> ColorString
unlinesColorString l =
concatColorString $
map (\x -> appendPrimColorString x (PrimColorString (Color NoColor False) (T.pack "\n") Nothing)) l
where
appendPrimColorString (ColorString l) x =
ColorString (l ++ [x])
concatColorString :: [ColorString] -> ColorString
concatColorString l =
ColorString $ concatMap (\(ColorString l) -> l) l
colorStringFind :: (Char -> Bool) -> ColorString -> Bool -> Maybe Char
colorStringFind pred (ColorString l) c =
let f = if c then pcolorStringFindColor else pcolorStringFindNoColor
in msum (map f l)
where
pcolorStringFindColor (PrimColorString _ t _) = tfind t
pcolorStringFindNoColor (PrimColorString _ t Nothing) = tfind t
pcolorStringFindNoColor (PrimColorString _ _ (Just t)) = tfind t
tfind t = T.find pred t
ensureNewlineColorString :: ColorString -> ColorString
ensureNewlineColorString cs@(ColorString l) =
let (colors, noColors) = unzip $ map colorsAndNoColors (reverse l)
nlColor = needsNl colors
nlNoColor = needsNl noColors
in if not nlColor && not nlNoColor
then cs
else ColorString (l ++
[PrimColorString (Color NoColor False) (mkNl nlColor)
(Just (mkNl nlNoColor))])
where
mkNl True = "\n"
mkNl False = ""
colorsAndNoColors (PrimColorString _ t1 (Just t2)) = (t1, t2)
colorsAndNoColors (PrimColorString _ t1 Nothing) = (t1, t1)
needsNl [] = False
needsNl (t:ts) =
let t' = T.dropWhileEnd (\c -> c == ' ') t
in if T.null t'
then needsNl ts
else T.last t' /= '\n'
colorize :: Color -> String -> ColorString
colorize c s = colorizeText c (T.pack s)
colorizeText :: Color -> T.Text -> ColorString
colorizeText !c !t = ColorString [PrimColorString c t Nothing]
colorize' :: Color -> String -> String -> ColorString
colorize' c s x = colorizeText' c (T.pack s) (T.pack x)
colorizeText' :: Color -> T.Text -> T.Text -> ColorString
colorizeText' !c !t !x = ColorString [PrimColorString c t (Just x)]
noColor :: String -> ColorString
noColor = colorize (Color NoColor False)
noColorText :: T.Text -> ColorString
noColorText = colorizeText (Color NoColor False)
noColor' :: String -> String -> ColorString
noColor' s1 s2 = colorize' (Color NoColor False) s1 s2
noColorText' :: T.Text -> T.Text -> ColorString
noColorText' t1 t2 = colorizeText' (Color NoColor False) t1 t2
infixr 5 +++
(+++) :: ColorString -> ColorString -> ColorString
cs1 +++ cs2 =
case (cs1, cs2) of
(ColorString [PrimColorString c1 t1 m1], ColorString (PrimColorString c2 t2 m2 : rest))
| c1 == c2 ->
let m3 = case (m1, m2) of
(Nothing, Nothing) -> Nothing
(Just x1, Just x2) -> Just (x1 `T.append` x2)
(Just x1, Nothing) -> Just (x1 `T.append` t2)
(Nothing, Just x2) -> Just (t1 `T.append` x2)
in ColorString (PrimColorString c1 (t1 `T.append` t2) m3 : rest)
(ColorString ps1, ColorString ps2) -> ColorString (ps1 ++ ps2)
renderColorString :: ColorString -> Bool -> T.Text
renderColorString (ColorString l) useColor =
T.concat (map render l)
where
render = if useColor then renderColors else renderNoColors
renderNoColors (PrimColorString _ _ (Just t)) = t
renderNoColors (PrimColorString _ t Nothing) = t
renderColors (PrimColorString c t _) =
T.concat [startColor c, t, reset]
|
skogsbaer/HTF
|
Test/Framework/Colors.hs
|
lgpl-2.1
| 6,940
| 0
| 18
| 1,699
| 1,994
| 1,062
| 932
| 139
| 18
|
-- decodeModified
-- [Multiple 4 'a',Single 'b',Multiple 2 'c',
-- Multiple 2 'a',Single 'd',Multiple 4 'e']
-- "aaaabccaadeeee"
data Tupor a = Single a | Multiple a Int
deriving (Show)
decodeModified :: [Tupor a] -> [a]
decodeModified [] = []
decodeModified xs = h1(head xs) ++ decodeModified(tail xs)
-- decm :: [Tupor a] -> a
-- decm xs = concat(decodeModified xs)
--
h1 :: Tupor a -> [a]
h1 (Single x) = [x]
h1 (Multiple x n) = replicate n x
-- Example: y = decodeModified [Multiple "a" 3, Multiple "b" 4, Single "c"]
-- concat y
|
ekalosak/haskell-practice
|
pr12.hs
|
lgpl-3.0
| 579
| 0
| 8
| 142
| 147
| 80
| 67
| 8
| 1
|
module HW6 where
import Prelude hiding (and,or,not,pred,succ,fst,snd,either)
import DeBruijn
import Church
--
-- * Part 1: Church pair update functions
--
-- | 1. A lambda calculus function that replaces the first element in a
-- Church-encoded pair. The first argument to the function is the original
-- pair, the second is the new first element.
--
-- >>> :{
-- eval (app2 pair true (num 3)) ==
-- eval (app2 setFst (app2 pair (num 2) (num 3)) true)
-- :}
-- True
setFst :: Exp
setFst = abs2 ( app2 pair (Ref 0) (App snd (Ref 1)) )
-- | 2. A lambda calculus function that replaces the second element in a
-- Church-encoded pair. The first argument to the function is the original
-- pair, the second is the new second element.
--
-- >>> :{
-- eval (app2 pair (num 2) true) ==
-- eval (app2 setSnd (app2 pair (num 2) (num 3)) true)
-- :}
-- True
--
setSnd :: Exp
setSnd = abs2 ( app2 pair (App fst (Ref 1)) (Ref 0) )
|
neale/CS-program
|
581-FunctionalProgramming/week6/6.hs
|
unlicense
| 964
| 0
| 11
| 224
| 148
| 93
| 55
| 8
| 1
|
{-# LANGUAGE FlexibleInstances #-}
module PredicateSpec where
import Test.QuickCheck
import Akarui.FOL.Predicate
import TextGen
import TermSpec
import qualified Data.Text as T
genPredicate :: Gen Predicate
genPredicate = do
name <- genPascalString
args <- genTerms
return $ Predicate (T.pack name) args
instance Arbitrary Predicate where
arbitrary = genPredicate
prop_predicate_eq_itself :: Predicate -> Bool
prop_predicate_eq_itself p0 = p0 == p0
prop_predicate_cmp_itself :: Predicate -> Bool
prop_predicate_cmp_itself p0 = p0 `compare` p0 == EQ
-- Make sure Ord and Eq fit together.
prop_predicate_ord :: Predicate -> Predicate -> Bool
prop_predicate_ord p0 p1 = case p0 `compare` p1 of
EQ -> p0 == p1
_ -> p0 /= p1
|
PhDP/Manticore
|
tests/PredicateSpec.hs
|
apache-2.0
| 739
| 0
| 11
| 124
| 192
| 105
| 87
| 22
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.DeploymentDetails where
import GHC.Generics
import Data.Text
import Openshift.V1.DeploymentCause
import qualified Data.Aeson
-- |
data DeploymentDetails = DeploymentDetails
{ message :: Maybe Text -- ^ a user specified change message
, causes :: Maybe [DeploymentCause] -- ^ extended data associated with all the causes for creating a new deployment
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON DeploymentDetails
instance Data.Aeson.ToJSON DeploymentDetails
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/V1/DeploymentDetails.hs
|
apache-2.0
| 680
| 0
| 10
| 99
| 102
| 62
| 40
| 16
| 0
|
import Data.Char
key = ["the", "this", "that"]
f n a =
if a == '.' || a == ' '
then a
else
let i = (ord a) - (ord 'a')
o = (n + i) `mod` 26
in
chr (o + ord 'a')
try w =
filter(\(n,w) -> w=="the" || w=="this" || w=="that") $ map (\n -> (n,map (f n) w)) [0..25]
ans s =
let c = filter (\x->length(x)==3 || length(x)==4 ) s
r = map try c
(n,_) = head $ concat r
in
map (map (f n)) s
spt :: String -> [String]
spt [] = []
spt s@(sh:ss)
| sh == ' ' || sh == '.' = let ss = takeWhile (== sh) s
rr = dropWhile (== sh) s
in
ss:(spt rr)
spt s@(sh:ss) =
let ss = takeWhile (\c -> c /= ' ' && c /= '.') s
rr = dropWhile (\c -> c /= ' ' && c /= '.') s
in
ss:(spt rr)
main = do
c <- getContents
let i = map spt $ lines c
o = map ans i
mapM_ putStrLn $ map concat o
|
a143753/AOJ
|
0017.hs
|
apache-2.0
| 930
| 0
| 16
| 367
| 548
| 282
| 266
| 30
| 2
|
import Data.List
import Text.Printf
split :: String -> [String]
split text =
let i = lookup ',' $ zip text [0..]
in
case i of
Just j -> (take j text):(split $ drop (j+1) text)
Nothing -> [text]
keys :: [[Int]] -> [Int]
keys [] = []
keys ((a:b:_):xs) = a:(keys xs)
find' :: Int -> [[Int]] -> Int
find' _ [] = 0
find' n ((a:b:_):xs) = if n == a
then 1 + (find' n xs)
else find' n xs
ans :: [[Int]] -> [[Int]] -> [(Int,Int)]
ans l1 l2 =
let k1 = nub $ keys l1
k2 = nub $ keys l2
k = sort $ intersect k1 k2
n = map (\i -> (i, find' i (l1++l2) ) ) k
in
n
main = do
c <- getContents
let l = lines c
l1 = map (map read) $ map split $ takeWhile (/= "") l :: [[Int]]
l2 = map (map read) $ map split $ drop 1 $ dropWhile (/= "") l :: [[Int]]
o = ans l1 l2
mapM_ (\(a,b) -> printf "%d %d\n" a b) o
|
a143753/AOJ
|
0065.hs
|
apache-2.0
| 913
| 0
| 15
| 311
| 544
| 286
| 258
| 30
| 2
|
{-# LANGUAGE OverloadedStrings, TypeFamilies, DeriveFunctor, GADTs, TemplateHaskell, FunctionalDependencies, FlexibleInstances, NoMonomorphismRestriction, DeriveGeneric,DeriveDataTypeable, DataKinds #-}
module TF.Types where
import Prelude hiding (Word)
import Control.Lens (Prism,prism, makeWrapped,makePrisms)
import Lens.Simple
import TF.TH
import Data.Data hiding (DataType)
import Control.Monad.Free
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Reader
import GHC.Generics (Generic)
import Lens.Family.Total hiding ((&))
import Control.Monad.RWS
import Data.Tree
import Control.Error as E
import Text.Parsec hiding (runParser, char)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as Te
import TF.ForthTypes
import TF.Errors
import TF.Type.Nodes
import TF.Type.StackEffect
import qualified Data.Tree.Zipper as TreeZ
--------------------------------------
------- STREAM ARGUMENT TYPES --------
--------------------------------------
type SpacesDelimitedParsing = String
_RuntimeProcessed = _Left
_RuntimeNotProcessed = _Right
_UnknownRuntimeSpecification = _Left
_KnownRuntimeSpecification = _Right
type ReferenceDegree = Int
getIndex t = t ^. _typeIndex
data ChangeState = ReferenceDegree Identifier Int
| ResolveUnknown Identifier DataType
deriving (Show,Eq)
makeTraversals ''ChangeState
type Parsed = String
type Name = String
type Description = String
_NoReferenceIndexed :: Prism IndexedStackType IndexedStackType IndexedStackType IndexedStackType
_NoReferenceIndexed = prism id (\s -> case s of
noref@(IndexedStackType (NoReference _) _) -> Right noref
x -> Left x)
data Optional = Sem Semantics | NotSet | Undefined deriving (Show,Eq)
data CompilationSemantics = CompSemDefined (Optional )
| APPEND_EXECUTION
| IMMEDIATE_EXECUTION
deriving (Show,Eq)
data InterpretationSemantics = IntSemDefined Optional
| ADOPT_EXECUTION
deriving (Show, Eq)
newtype ExecutionSemantics = ExecSem (Optional ) deriving (Show, Eq)
newtype RuntimeSemantics = RunSem (Optional ) deriving (Show, Eq)
data ColonDefinitionProcessed = ColonDefinitionProcessed {
_cdefprocColonDefinition :: ColonDefinition
, _cdefprocProcessedEffects :: EffectsByPhase } deriving Show
data Definition = ColDef ColonDefinitionProcessed | CreateDef [StackEffect] deriving Show
type CompExecEffect = (StackEffect, StackEffect)
-- data FullStackEffect = FullStackEffect {
-- _fullstackeffectEffects :: MultiStackEffect
-- , _fullstackeffectIntersection :: Intersections
-- } deriving (Show, Eq)
data CheckEffectsConfig = CheckEffectsConfig {
_checkconfigForthWordOrExpr :: Maybe Node
, _checkconfigIsForcedAssertion :: Bool
, _checkconfigCheckState :: SemState
, _checkconfigTellErrors :: Bool
} deriving (Show)
data Word = Word {
parsedW :: Parsable
, nameW :: String
, runtime :: RuntimeSemantics
, execution :: ExecutionSemantics
, compilation :: CompilationSemantics
, interpretation :: InterpretationSemantics
, isImmediateWord :: Bool
, intersections :: Intersections
} deriving (Show, Eq)
data EffectsByPhase = Forced StackEffectsWI
| Checked StackEffectsWI -- ([StackEffect],Bool)
| NotChecked
| Failed String deriving (Show)
data ColonDefinition = ColonDefinition {
_cdefBody :: [Node]
, _cdefMeta :: ColonDefinitionMeta
} deriving (Show)
data ColonDefinitionMeta = ColonDefinitionMeta {
_cdefinfoName :: String
, _cdefinfoIsImmediate :: Bool
} deriving (Show, Read, Eq)
makeFields ''ColonDefinitionMeta
newtype Trace = Trace {
_traceParsedExpressions :: TreeZ.TreePos TreeZ.Full String
} deriving (Show,Eq)
data ParseState = ParseState {
definedWords' :: M.Map String Definition
, coreWords :: M.Map Parsable Word
, stateVar :: SemState
, currentCompiling :: Bool
, effects :: ForthEffect
, classInterfaces :: M.Map ClassName [(Method, OOMethodSem)]
, classFields :: M.Map ClassName [(Variable, OOFieldSem)]
, subtypeRelation :: S.Set (BasicType, BasicType)
, unresolvedArgsTypes :: M.Map Identifier StackEffect
, inputStreamAssertions :: [StackEffect]
, trace :: Trace
} deriving (Show)
makeLens ''ParseState
data BuildState = BS { _state :: SemanticsState
, _word :: Word
} deriving (Show,Eq)
data ParseEffectResult = ParseEffectResult {
parsedEffects :: [([IndexedStackType], [IndexedStackType])]
, streamArguments :: [DefiningOrNot]
, forcedEffect :: Bool
, isIntersectionPER :: Bool
} deriving (Show,Eq)
data WordDefinition cont = COMPILE_COMING cont
| IMMEDIATE cont
| PARSED_NUM cont
| PARSED_STR Te.Text cont
| NAME String cont
| ENTER SemState cont
| EFFECT String cont
| EFFECT_UNDEFINED cont
| DESCRIPTION String cont
| COMPILATION_START cont
| COMPILATION_END cont
| INTERPRETATION_START cont
| INTERPRETATION_END cont
| RUNTIME_START cont
| RUNTIME_END cont
| END deriving (Functor, Show)
data ParseConfig = ParseConfig {
_configTypeCheck :: Bool
, _configTopLevelEmpty :: Bool
, _configReadFromStream :: Bool
, _configAllowMultipleEffects :: Bool
, _configAllowLocalFailure :: Bool
, _configAllCoreDynamic :: Bool
, _configAllowDynamicInStackComments :: Bool
, _configAllowCasts :: Bool
, _configThirdParty :: [Free WordDefinition ()]
, _configAllowForcedEffects :: Bool
, _configSubtypes :: PrimType -> [PrimType]
, _configAllowOOP :: Bool
} deriving (Typeable)
data SemanticsState = COMPILATION | EXECUTION | INTERPRETATION | RUNTIME deriving (Show,Read,Eq,Data,Typeable)
data ParseStackEffectsConfig = ParseStackEffectsConfig {
_stackeffClassNames :: [ClassName]
, _stackeffOnlyAfter :: Bool
, _stackeffAllowDynamicInStackComments :: Bool
} deriving (Show,Eq)
data CheckFailure = ExecTypeError (Maybe Node) StackEffectsWI StackEffectsWI
| CompTypeError (Maybe Node) StackEffectsWI StackEffectsWI
| CompExecTypeError (Maybe Node) ForthEffect ForthEffect deriving (Show,Eq)
-- data CheckFailure = CheckFailure {
-- currentEffectsCheckFail :: [CompExecEffect],
-- newEffectsCheckFail :: [CompExecEffect]
-- } deriving (Show,Eq)
data AssertFailure = AssertFailure {
currentEffectsAssert :: [CompExecEffect],
newEffectsAssert :: [CompExecEffect]
} deriving (Show,Eq)
type Depth = Int
data Info = Info {
infoFailures :: [CheckFailure]
, assertFailures :: [AssertFailure]
} deriving (Show)
instance Monoid Info where
mempty = Info [] []
mappend (Info fails1 asserts1) (Info fails2 asserts2) = Info (fails1 ++ fails2) (asserts1 ++ asserts2)
data CustomState = CustomState {
checkedExpressions :: TreeZ.TreePos TreeZ.Full String--[Node]
, identifier :: Int
, wordsMap :: M.Map Parsable Word
} deriving (Show,Eq)
makeFields ''Trace
makeWrapped ''Trace
makeLens ''Info
makeFields ''ParseStackEffectsConfig
makeLens ''CustomState
makeFields ''ColonDefinition
makeFields ''ParseConfig
makeFields ''CheckEffectsConfig
makeFields ''ColonDefinitionProcessed
makeLenses ''BuildState
makeLens ''ParseEffectResult
makeFields ''ParseState
makePrisms ''EffectsByPhase
makeLens ''Word
makeTraversals ''Optional
makeTraversals ''CompilationSemantics
makeTraversals ''Definition
makeTraversals ''InterpretationSemantics
makeWrapped ''ExecutionSemantics
makeWrapped ''RuntimeSemantics
data DefOrWord = DefinitionName NameOfDefinition | WordName NameOfWord deriving (Show,Eq)
data Token = UnknownToken Unknown | WordToken Word deriving (Show,Eq)
makeTraversals ''Token
isImmediateColonDefinition = view $ meta.isImmediate
emptyEffect = [StackEffect [] [] []]
type Script' = ReaderT ParseConfig (ExceptT Error' (StateT CustomState (Writer Info)))
type StackEffectM = Script'
type StackEffects = (StackEffect, StackEffect)
type CheckerM = ParsecT [Token] ParseState StackEffectM
type StackRuleM = ExceptT SemState (ReaderT CheckEffectsConfig CheckerM)
type ParseWord = Te.Text -> CheckerM ParsedWord
type IsKnownWord = CheckerM (Maybe (Either ForthWord DefOrWord) )
type ParseStackEffectSemantics = (String -> ParseStackEffectsConfig -> Script' ParseEffectResult) -> CheckerM (Semantics, Bool)
type ParseNode = CheckerM Node
type ParseNodeWithout = [Word] -> CheckerM Node
data ExpressionsEnv = ExpressionEnv {
_exprenvParseWord' :: ParseWord
, _exprenvIsKnownWord' :: IsKnownWord
, _exprenvParseStackEffectSemantics' :: ParseStackEffectSemantics
, _exprenvParseNode' :: ParseNode
, _exprenvParseNodeWithout' :: ParseNodeWithout
} deriving (Typeable)
makeFields ''ExpressionsEnv
type ExpressionsM = ReaderT ExpressionsEnv CheckerM
data ParseStackState = ParseStackState {
parsestateBefore :: [[[IndexedStackType]]]
, parsestateAfter :: [[[IndexedStackType]]]
, parsestateStreamArguments :: [[DefiningOrNot]]
, parsestateForced :: Bool
} deriving (Show, Eq)
makeLens ''ParseStackState
data ParseStacksState = ParseStacksState {
types :: [PrimType]
, currentEffect :: ParseStackState
, previousEffects :: [ParseStackState]
, forced' :: Bool
, isIntersect :: Bool
} deriving (Show, Eq)
makeLens ''ParseStacksState
type ParseStackEffectsM = ParsecT String ParseStacksState (Reader ParseStackEffectsConfig)
instance HasDefault ParseStacksState where
def = ParseStacksState forthTypes def [] False False
instance HasDefault CheckEffectsConfig where
def = CheckEffectsConfig Nothing False INTERPRETSTATE True
instance HasDefault ParseStackState where
def = ParseStackState [] [] [] False
class HasDefault d where
def :: d
instance HasDefault [x] where
def = []
instance HasDefault (CompilationSemantics ) where
def = CompSemDefined NotSet
instance HasDefault (InterpretationSemantics ) where
def = IntSemDefined NotSet
instance HasDefault Optional where
def = NotSet
instance HasDefault ExecutionSemantics where
def = ExecSem $ Sem def
instance HasDefault (RuntimeSemantics ) where
def = RunSem def
instance HasDefault Word where
def = Word (WordIdentifier "") def def def def def def (Intersections False False)
instance HasDefault Semantics where
def = Semantics def def def
instance HasDefault StackEffectsWI where
def = StackEffectsWI def def
instance HasDefault Intersection where
def = Intersection False
instance HasDefault MultiStackEffect where
def = MultiStackEffect []
instance HasDefault Bool where
def = False
instance HasDefault BuildState where
def = BS def def
instance HasDefault SemanticsState where
def = EXECUTION
instance HasDefault (Maybe x) where
def = Nothing
|
sleepomeno/TForth
|
src/TF/Types.hs
|
apache-2.0
| 12,162
| 0
| 15
| 3,251
| 2,634
| 1,489
| 1,145
| 267
| 2
|
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module GUI.Widget.ChildWidget
(
ChildWidget,
makeChildWidget,
) where
import GUI.Widget
data ChildWidget a =
ChildWidget
{
childShape' :: GUIData -> GUIState -> GUIShape,
childBegin' :: GUIData -> GUIState -> IO (ChildWidget a),
childEatInput' :: GUIData -> GUIState -> WidgetInput -> ChildWidget a,
childIterate' :: GUIData -> GUIState -> a -> IO (ChildWidget a, a)
}
instance Widget ChildWidget where
widgetShape = \gd gs w -> childShape' w gd gs
widgetBegin = \gd gs w -> childBegin' w gd gs
widgetEatInput = \gd gs w wi -> childEatInput' w gd gs wi
widgetIterate = \gd gs w a -> childIterate' w gd gs a
--------------------------------------------------------------------------------
-- make
makeChildWidget :: Widget w => GUIData -> w a -> ChildWidget a
makeChildWidget _ w =
ChildWidget
{
childShape' = \gd gs -> widgetShape gd gs w,
childBegin' = \gd gs -> widgetBegin gd gs w >>= \w' ->
return $ makeChildWidget gd w',
childEatInput' = \gd gs wi -> let w' = widgetEatInput gd gs w wi
in makeChildWidget gd w',
childIterate' = \gd gs a -> widgetIterate gd gs w a >>= \(w', a') ->
return (makeChildWidget gd w', a')
}
|
karamellpelle/MEnv
|
source/GUI/Widget/ChildWidget.hs
|
bsd-2-clause
| 2,862
| 0
| 14
| 779
| 434
| 243
| 191
| 26
| 1
|
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
module Cryptol.ModuleSystem.Base where
import Cryptol.ModuleSystem.Env (DynamicEnv(..), deIfaceDecls)
import Cryptol.ModuleSystem.Interface
import Cryptol.ModuleSystem.Monad
import Cryptol.ModuleSystem.Env (lookupModule, LoadedModule(..)
, meCoreLint, CoreLint(..))
import qualified Cryptol.Eval as E
import qualified Cryptol.Eval.Value as E
import qualified Cryptol.ModuleSystem.Renamer as R
import qualified Cryptol.Parser as P
import qualified Cryptol.Parser.Unlit as P
import Cryptol.Parser.AST as P
import Cryptol.Parser.NoPat (RemovePatterns(removePatterns))
import Cryptol.Parser.NoInclude (removeIncludesModule)
import Cryptol.Parser.Position (HasLoc(..), Range, emptyRange)
import qualified Cryptol.TypeCheck as T
import qualified Cryptol.TypeCheck.AST as T
import qualified Cryptol.TypeCheck.Depends as T
import qualified Cryptol.TypeCheck.PP as T
import qualified Cryptol.TypeCheck.Sanity as TcSanity
import Cryptol.Utils.PP (pretty)
import Cryptol.Utils.Panic (panic)
import Cryptol.Prelude (writePreludeContents)
import Cryptol.Transform.MonoValues
import Control.DeepSeq
import qualified Control.Exception as X
import Control.Monad (unless)
import Data.Function (on)
import Data.List (nubBy)
import Data.Maybe (mapMaybe,fromMaybe)
import Data.Monoid ((<>))
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy.IO as T
import System.Directory (doesFileExist)
import System.FilePath ( addExtension
, isAbsolute
, joinPath
, (</>)
, takeDirectory
, takeFileName
)
import qualified System.IO.Error as IOE
import qualified Data.Map as Map
#if __GLASGOW_HASKELL__ < 710
import Data.Foldable (foldMap)
#endif
-- Renaming --------------------------------------------------------------------
rename :: R.Rename a => R.NamingEnv -> a -> ModuleM a
rename env a = do
renamerWarnings ws
case res of
Right r -> return r
Left errs -> renamerErrors errs
where
(res,ws) = R.runRenamer env (R.rename a)
-- | Rename a module in the context of its imported modules.
renameModule :: P.Module -> ModuleM P.Module
renameModule m = do
iface <- importIfaces (map thing (P.mImports m))
let menv = R.namingEnv m
(es,ws) = R.checkNamingEnv menv
renamerWarnings ws
unless (null es) (renamerErrors es)
-- explicitly shadow the imported environment with the local environment
rename (menv `R.shadowing` R.namingEnv iface) m
-- | Rename an expression in the context of the focused module.
renameExpr :: P.Expr -> ModuleM P.Expr
renameExpr e = do
(env,_) <- getFocusedEnv
denv <- getDynEnv
rename (deNames denv `R.shadowing` R.namingEnv env) e
-- | Rename declarations in the context of the focused module.
renameDecls :: (R.Rename d, T.FromDecl d) => [d] -> ModuleM [d]
renameDecls ds = do
(env,_) <- getFocusedEnv
denv <- getDynEnv
rename (deNames denv `R.shadowing` R.namingEnv env) ds
-- NoPat -----------------------------------------------------------------------
-- | Run the noPat pass.
noPat :: RemovePatterns a => a -> ModuleM a
noPat a = do
let (a',errs) = removePatterns a
unless (null errs) (noPatErrors errs)
return a'
-- Parsing ---------------------------------------------------------------------
parseModule :: FilePath -> ModuleM P.Module
parseModule path = do
e <- io $ X.try $ do
bytes <- T.readFile path
return $!! bytes
bytes <- case (e :: Either X.IOException Text) of
Right bytes -> return bytes
Left exn | IOE.isDoesNotExistError exn -> cantFindFile path
| otherwise -> otherIOError path exn
let cfg = P.defaultConfig
{ P.cfgSource = path
, P.cfgPreProc = P.guessPreProc path
}
case P.parseModule cfg bytes of
Right pm -> return pm
Left err -> moduleParseError path err
-- Modules ---------------------------------------------------------------------
-- | Load a module by its path.
loadModuleByPath :: FilePath -> ModuleM T.Module
loadModuleByPath path = withPrependedSearchPath [ takeDirectory path ] $ do
let fileName = takeFileName path
-- path' is the resolved, absolute path
path' <- findFile fileName
pm <- parseModule path'
let n = thing (P.mName pm)
-- Check whether this module name has already been loaded from a different file
env <- getModuleEnv
case lookupModule n env of
Nothing -> loadingModule n (loadModule path' pm)
Just lm
| path' == loaded -> return (lmModule lm)
| otherwise -> duplicateModuleName n path' loaded
where loaded = lmFilePath lm
-- | Load the module specified by an import.
loadImport :: Located P.Import -> ModuleM ()
loadImport li = do
let i = thing li
n = P.iModule i
alreadyLoaded <- isLoaded n
unless alreadyLoaded $
do path <- findModule n
pm <- parseModule path
loadingImport li $ do
-- make sure that this module is the one we expect
unless (n == thing (P.mName pm)) (moduleNameMismatch n (mName pm))
_ <- loadModule path pm
return ()
-- | Load dependencies, typecheck, and add to the eval environment.
loadModule :: FilePath -> P.Module -> ModuleM T.Module
loadModule path pm = do
let pm' = addPrelude pm
loadDeps pm'
-- XXX make it possible to configure output
io (putStrLn ("Loading module " ++ pretty (P.thing (P.mName pm'))))
tcm <- checkModule path pm'
-- extend the eval env
modifyEvalEnv (E.moduleEnv tcm)
loadedModule path tcm
return tcm
-- | Rewrite an import declaration to be of the form:
--
-- > import foo as foo [ [hiding] (a,b,c) ]
fullyQualified :: P.Import -> P.Import
fullyQualified i = i { iAs = Just (iModule i) }
-- | Process the interface specified by an import.
importIface :: P.Import -> ModuleM Iface
importIface i = (fst . interpImport i) `fmap` getIface (T.iModule i)
-- | Load a series of interfaces, merging their public interfaces.
importIfaces :: [P.Import] -> ModuleM IfaceDecls
importIfaces is = foldMap ifPublic `fmap` mapM importIface is
moduleFile :: ModName -> String -> FilePath
moduleFile n = addExtension (joinPath (P.unModName n))
-- | Discover a module.
findModule :: ModName -> ModuleM FilePath
findModule n = do
paths <- getSearchPath
loop (possibleFiles paths)
where
loop paths = case paths of
path:rest -> do
b <- io (doesFileExist path)
if b then return path else loop rest
[] -> handleNotFound
handleNotFound =
case n of
m | m == preludeName -> writePreludeContents
_ -> moduleNotFound n =<< getSearchPath
-- generate all possible search paths
possibleFiles paths = do
path <- paths
ext <- P.knownExts
return (path </> moduleFile n ext)
-- | Discover a file. This is distinct from 'findModule' in that we
-- assume we've already been given a particular file name.
findFile :: FilePath -> ModuleM FilePath
findFile path | isAbsolute path = do
-- No search path checking for absolute paths
b <- io (doesFileExist path)
if b then return path else cantFindFile path
findFile path = do
paths <- getSearchPath
loop (possibleFiles paths)
where
loop paths = case paths of
path':rest -> do
b <- io (doesFileExist path')
if b then return path' else loop rest
[] -> cantFindFile path
possibleFiles paths = map (</> path) paths
preludeName :: P.ModName
preludeName = P.mkModName ["Cryptol"]
-- | Add the prelude to the import list if it's not already mentioned.
addPrelude :: P.Module -> P.Module
addPrelude m
| preludeName == P.thing (P.mName m) = m
| preludeName `elem` importedMods = m
| otherwise = m { mImports = importPrelude : mImports m }
where
importedMods = map (P.iModule . P.thing) (P.mImports m)
importPrelude = P.Located
{ P.srcRange = emptyRange
, P.thing = P.Import
{ iModule = preludeName
, iAs = Nothing
, iSpec = Nothing
}
}
-- | Load the dependencies of a module into the environment.
loadDeps :: Module -> ModuleM ()
loadDeps m
| null needed = return ()
| otherwise = mapM_ load needed
where
needed = nubBy ((==) `on` P.iModule . thing) (P.mImports m)
load mn = loadImport mn
-- Type Checking ---------------------------------------------------------------
-- | Typecheck a single expression.
checkExpr :: P.Expr -> ModuleM (P.Expr,T.Expr,T.Schema)
checkExpr e = do
npe <- noPat e
denv <- getDynEnv
re <- renameExpr npe
env <- getQualifiedEnv
let env' = env <> deIfaceDecls denv
act = TCAction { tcAction = T.tcExpr, tcLinter = exprLinter }
(te,s) <- typecheck act re env'
return (re,te,s)
-- | Typecheck a group of declarations.
checkDecls :: (HasLoc d, R.Rename d, T.FromDecl d) => [d] -> ModuleM [T.DeclGroup]
checkDecls ds = do
-- nopat must already be run
rds <- renameDecls ds
denv <- getDynEnv
env <- getQualifiedEnv
let env' = env <> deIfaceDecls denv
act = TCAction { tcAction = T.tcDecls, tcLinter = declsLinter }
typecheck act rds env'
-- | Typecheck a module.
checkModule :: FilePath -> P.Module -> ModuleM T.Module
checkModule path m = do
-- remove includes first
e <- io (removeIncludesModule path m)
nim <- case e of
Right nim -> return nim
Left ierrs -> noIncludeErrors ierrs
-- remove pattern bindings
npm <- noPat nim
-- rename everything
scm <- renameModule npm
let act = TCAction { tcAction = T.tcModule
, tcLinter = moduleLinter (P.thing (P.mName m)) }
-- typecheck
tcm <- typecheck act scm =<< importIfacesTc (map thing (P.mImports scm))
return (Cryptol.Transform.MonoValues.rewModule tcm)
data TCLinter o = TCLinter
{ lintCheck ::
o -> T.InferInput -> Either TcSanity.Error [TcSanity.ProofObligation]
, lintModule :: Maybe P.ModName
}
exprLinter :: TCLinter (T.Expr, T.Schema)
exprLinter = TCLinter
{ lintCheck = \(e',s) i ->
case TcSanity.tcExpr (T.inpVars i) e' of
Left err -> Left err
Right (s1,os)
| TcSanity.same s s1 -> Right os
| otherwise -> Left (TcSanity.TypeMismatch s s1)
, lintModule = Nothing
}
declsLinter :: TCLinter [ T.DeclGroup ]
declsLinter = TCLinter
{ lintCheck = \ds' i -> case TcSanity.tcDecls (T.inpVars i) ds' of
Left err -> Left err
Right os -> Right os
, lintModule = Nothing
}
moduleLinter :: P.ModName -> TCLinter T.Module
moduleLinter m = TCLinter
{ lintCheck = \m' i -> case TcSanity.tcModule (T.inpVars i) m' of
Left err -> Left err
Right os -> Right os
, lintModule = Just m
}
data TCAction i o = TCAction
{ tcAction :: i -> T.InferInput -> IO (T.InferOutput o)
, tcLinter :: TCLinter o
}
typecheck :: HasLoc i => TCAction i o -> i -> IfaceDecls -> ModuleM o
typecheck act i env = do
let range = fromMaybe emptyRange (getLoc i)
input <- genInferInput range env
out <- io (tcAction act i input)
case out of
T.InferOK warns seeds o ->
do setNameSeeds seeds
typeCheckWarnings warns
menv <- getModuleEnv
case meCoreLint menv of
NoCoreLint -> return ()
CoreLint -> case lintCheck (tcLinter act) o input of
Right as -> io $ mapM_ (print . T.pp) as
Left err -> panic "Core lint failed:" [show err]
return o
T.InferFailed warns errs ->
do typeCheckWarnings warns
typeCheckingFailed errs
-- | Process a list of imports, producing an aggregate interface suitable for use
-- when typechecking.
importIfacesTc :: [P.Import] -> ModuleM IfaceDecls
importIfacesTc is =
mergePublic `fmap` mapM (importIface . fullyQualified) is
where
mergePublic = foldMap ifPublic
-- | Generate input for the typechecker.
genInferInput :: Range -> IfaceDecls -> ModuleM T.InferInput
genInferInput r env = do
seeds <- getNameSeeds
monoBinds <- getMonoBinds
cfg <- getSolverConfig
-- TODO: include the environment needed by the module
return T.InferInput
{ T.inpRange = r
, T.inpVars = Map.map ifDeclSig (filterEnv ifDecls)
, T.inpTSyns = filterEnv ifTySyns
, T.inpNewtypes = filterEnv ifNewtypes
, T.inpNameSeeds = seeds
, T.inpMonoBinds = monoBinds
, T.inpSolverConfig = cfg
}
where
-- at this point, the names used in the aggregate interface should be
-- unique
keepOne :: (QName,[a]) -> Maybe (QName,a)
keepOne (qn,syns) = case syns of
[syn] -> Just (qn,syn)
_ -> Nothing
-- keep symbols without duplicates. the renamer would have caught
-- duplication already, so this is safe.
filterEnv p = Map.fromList (mapMaybe keepOne (Map.toList (p env)))
-- Evaluation ------------------------------------------------------------------
evalExpr :: T.Expr -> ModuleM E.Value
evalExpr e = do
env <- getEvalEnv
denv <- getDynEnv
return (E.evalExpr (env <> deEnv denv) e)
evalDecls :: [T.DeclGroup] -> ModuleM ()
evalDecls dgs = do
env <- getEvalEnv
denv <- getDynEnv
let env' = env <> deEnv denv
denv' = denv { deDecls = deDecls denv ++ dgs
, deEnv = E.evalDecls dgs env'
}
setDynEnv denv'
|
iblumenfeld/cryptol
|
src/Cryptol/ModuleSystem/Base.hs
|
bsd-3-clause
| 13,681
| 0
| 22
| 3,364
| 3,973
| 2,032
| 1,941
| -1
| -1
|
{-# LANGUAGE OverloadedStrings, RankNTypes, RecordWildCards,
ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns -fno-warn-missing-signatures
-fno-warn-unused-binds #-}
module UnitTests (testWith) where
import Control.Arrow (first)
import Control.Applicative ((<$>))
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Exception (Exception, throwIO)
import Control.Lens ((^.), (^?), (.~), (?~), (&), iso, ix, Traversal')
import Control.Monad (unless, void)
import Data.Aeson hiding (Options)
import Data.Aeson.Lens (key, AsValue, _Object)
import Data.ByteString (ByteString)
import Data.Char (toUpper)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import HttpBin.Server (serve)
import Network.HTTP.Client (HttpException(..), HttpExceptionContent(..))
import Network.HTTP.Types.Status (status200, status401)
import Network.HTTP.Types.Version (http11)
import Network.Wreq hiding
(get, post, head_, put, options, delete,
getWith, postWith, headWith, putWith, optionsWith, deleteWith)
import Network.Wreq.Lens
import Network.Wreq.Types (Postable, Putable)
import Snap.Http.Server.Config
import System.IO (hClose, hPutStr)
import System.IO.Temp (withSystemTempFile)
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool, assertEqual, assertFailure)
import qualified Control.Exception as E
import qualified Data.CaseInsensitive as CI
import qualified Data.HashMap.Strict as HMap
import qualified Data.Text as T
import qualified Network.Wreq.Session as Session
import qualified Data.ByteString.Lazy as L
import qualified Network.Wreq as Wreq
data Verb = Verb {
get :: String -> IO (Response L.ByteString)
, getWith :: Options -> String -> IO (Response L.ByteString)
, post :: forall a. Postable a => String -> a -> IO (Response L.ByteString)
, postWith :: forall a. Postable a => Options -> String -> a
-> IO (Response L.ByteString)
, head_ :: String -> IO (Response ())
, headWith :: Options -> String -> IO (Response ())
, put :: forall a. Putable a => String -> a -> IO (Response L.ByteString)
, putWith :: forall a. Putable a => Options -> String -> a -> IO (Response L.ByteString)
, options :: String -> IO (Response ())
, optionsWith :: Options -> String -> IO (Response ())
, delete :: String -> IO (Response L.ByteString)
, deleteWith :: Options -> String -> IO (Response L.ByteString)
}
basic :: Verb
basic = Verb { get = Wreq.get, getWith = Wreq.getWith, post = Wreq.post
, postWith = Wreq.postWith, head_ = Wreq.head_
, headWith = Wreq.headWith, put = Wreq.put
, putWith = Wreq.putWith, options = Wreq.options
, optionsWith = Wreq.optionsWith, delete = Wreq.delete
, deleteWith = Wreq.deleteWith }
session :: Session.Session -> Verb
session s = Verb { get = Session.get s
, getWith = flip Session.getWith s
, post = Session.post s
, postWith = flip Session.postWith s
, head_ = Session.head_ s
, headWith = flip Session.headWith s
, put = Session.put s
, putWith = flip Session.putWith s
, options = Session.options s
, optionsWith = flip Session.optionsWith s
, delete = Session.delete s
, deleteWith = flip Session.deleteWith s }
-- Helper aeson lens for case insensitive keys
-- The test 'snap' server unfortunately lowercases all headers, we have to be case-insensitive
-- when checking the returned header list.
cikey :: AsValue t => T.Text -> Traversal' t Value
cikey i = _Object . toInsensitive . ix (CI.mk i)
where
toInsensitive = iso toCi fromCi
toCi = HMap.fromList . map (first CI.mk) . HMap.toList
fromCi = HMap.fromList . map (first CI.original) . HMap.toList
basicGet Verb{..} site = do
r <- get (site "/get")
assertBool "GET request has User-Agent header" $
isJust (r ^. responseBody ^? key "headers" . cikey "User-Agent")
-- test the various lenses
assertEqual "GET succeeds" status200 (r ^. responseStatus)
assertEqual "GET succeeds 200" 200 (r ^. responseStatus . statusCode)
assertEqual "GET succeeds OK" "OK" (r ^. responseStatus . statusMessage)
assertEqual "GET response has HTTP/1.1 version" http11 (r ^. responseVersion)
assertBool "GET response has Content-Type header" $
isJust (r ^? responseHeader "Content-Type")
assertBool "GET response has Date header" $
isJust (lookup "Date" <$> r ^? responseHeaders)
basicPost Verb{..} site = do
r <- post (site "/post") ("wibble" :: ByteString) >>= asValue
let body = r ^. responseBody
assertEqual "POST succeeds" status200 (r ^. responseStatus)
assertEqual "POST echoes input" (Just "wibble") (body ^? key "data")
assertEqual "POST is binary" (Just "application/octet-stream")
(body ^? key "headers" . cikey "Content-Type")
multipartPost Verb{..} site =
withSystemTempFile "foo.html" $ \name handle -> do
hPutStr handle "<!DOCTYPE html><html></html"
hClose handle
r <- post (site "/post") (partFile "html" name)
assertEqual "POST succeeds" status200 (r ^. responseStatus)
basicHead Verb{..} site = do
r <- head_ (site "/get")
assertEqual "HEAD succeeds" status200 (r ^. responseStatus)
basicPut Verb{..} site = do
r <- put (site "/put") ("wibble" :: ByteString)
assertEqual "PUT succeeds" status200 (r ^. responseStatus)
data SolrAdd = SolrAdd
{ doc :: String
, boost :: Float
, overwrite :: Bool
, commitWithin :: Integer
}
instance ToJSON SolrAdd where
toJSON (SolrAdd doc boost overwrite commitWithin) =
object
[
"add" .= object
[ "doc" .= toJSON doc
, "boost" .= boost
, "overwrite" .= overwrite
, "commitWithin" .= commitWithin
]
]
solrAdd :: SolrAdd
solrAdd = SolrAdd "wibble" 1.0 True 10000
jsonPut Verb{..} site = do
r <- put (site "/put") $ toJSON solrAdd
assertEqual "toJSON PUT request has correct Content-Type header"
(Just "application/json")
(r ^. responseBody ^? key "headers" . cikey "Content-Type")
byteStringPut Verb{..} site = do
let opts = defaults & header "Content-Type" .~ ["application/json"]
r <- putWith opts (site "/put") $ encode solrAdd
assertEqual "ByteString PUT request has correct Content-Type header"
(Just "application/json")
(r ^. responseBody ^? key "headers" . cikey "Content-Type")
basicDelete Verb{..} site = do
r <- delete (site "/delete")
assertEqual "DELETE succeeds" status200 (r ^. responseStatus)
throwsStatusCode Verb{..} site =
assertThrows "404 causes exception to be thrown" inspect $
head_ (site "/status/404")
where inspect (HttpExceptionRequest _ e) = case e of
StatusCodeException _ _ -> return ()
_ -> assertFailure "unexpected exception thrown"
inspect _ = assertFailure "unexpected exception thrown"
getBasicAuth Verb{..} site = do
let opts = defaults & auth ?~ basicAuth "user" "passwd"
r <- getWith opts (site "/basic-auth/user/passwd")
assertEqual "basic auth GET succeeds" status200 (r ^. responseStatus)
let inspect (HttpExceptionRequest _ e) = case e of
StatusCodeException resp _ ->
assertEqual "basic auth failed GET gives 401"
status401 (resp ^. responseStatus)
inspect _ = assertFailure "unexpected exception thrown"
assertThrows "basic auth GET fails if password is bad" inspect $
getWith opts (site "/basic-auth/user/asswd")
getOAuth2 Verb{..} kind ctor site = do
let opts = defaults & auth ?~ ctor "token1234"
r <- getWith opts (site $ "/oauth2/" <> kind <> "/token1234")
assertEqual ("oauth2 " <> kind <> " GET succeeds")
status200 (r ^. responseStatus)
let inspect (HttpExceptionRequest _ e) = case e of
StatusCodeException resp _ ->
assertEqual ("oauth2 " <> kind <> " failed GET gives 401")
status401 (resp ^. responseStatus)
inspect _ = assertFailure "unexpected exception thrown"
assertThrows ("oauth2 " <> kind <> " GET fails if token is bad") inspect $
getWith opts (site $ "/oauth2/" <> kind <> "/token123")
getRedirect Verb{..} site = do
r <- get (site "/redirect/3")
let stripProto = T.dropWhile (/=':')
smap f (String s) = String (f s)
assertEqual "redirect goes to /get"
(Just . String . stripProto . T.pack . site $ "/get")
(smap stripProto <$> (r ^. responseBody ^? key "url"))
getParams Verb{..} site = do
let opts1 = defaults & param "foo" .~ ["bar"]
r1 <- getWith opts1 (site "/get")
assertEqual "params set correctly 1" (Just (object [("foo","bar")]))
(r1 ^. responseBody ^? key "args")
let opts2 = defaults & params .~ [("quux","baz")]
r2 <- getWith opts2 (site "/get")
assertEqual "params set correctly 2" (Just (object [("quux","baz")]))
(r2 ^. responseBody ^? key "args")
r3 <- getWith opts2 (site "/get?whee=wat")
assertEqual "correctly handle mix of params from URI and Options"
(Just (object [("quux","baz"),("whee","wat")]))
(r3 ^. responseBody ^? key "args")
getHeaders Verb{..} site = do
let opts = defaults & header "X-Wibble" .~ ["bar"]
r <- getWith opts (site "/get")
assertEqual "extra header set correctly"
(Just "bar")
(r ^. responseBody ^? key "headers" . cikey "X-Wibble")
getCheckStatus Verb {..} site = do
let opts = defaults & checkResponse .~ Just customRc
r <- getWith opts (site "/status/404")
assertThrows "Non 404 throws error" inspect $
getWith opts (site "/get")
assertEqual "Status 404"
404
(r ^. responseStatus . statusCode)
where
customRc :: ResponseChecker
customRc _ resp
| resp ^. responseStatus . statusCode == 404 = return ()
customRc req resp = throwIO $ HttpExceptionRequest req (StatusCodeException (void resp) "")
inspect (HttpExceptionRequest _ e) = case e of
(StatusCodeException resp _) ->
assertEqual "200 Status Error" (resp ^. responseStatus) status200
inspect _ = assertFailure "unexpected exception thrown"
getGzip Verb{..} site = do
r <- get (site "/gzip")
assertEqual "gzip decoded for us" (Just (Bool True))
(r ^. responseBody ^? key "gzipped")
headRedirect Verb{..} site = do
assertThrows "HEAD of redirect throws exception" inspect $
head_ (site "/redirect/3")
where inspect (HttpExceptionRequest _ e) = case e of
StatusCodeException resp _ ->
let code = resp ^. responseStatus . statusCode
in assertBool "code is redirect"
(code >= 300 && code < 400)
inspect _ = assertFailure "unexpected exception thrown"
redirectOverflow Verb{..} site =
assertThrows "GET with too many redirects throws exception" inspect $
getWith (defaults & redirects .~ 3) (site "/redirect/5")
where inspect (HttpExceptionRequest _ e) = case e of TooManyRedirects _ -> return ()
inspect _ = assertFailure "unexpected exception thrown"
invalidURL Verb{..} _site = do
let noProto (InvalidUrlException _ _) = return ()
assertThrows "exception if no protocol" noProto (get "wheeee")
let noHost (HttpExceptionRequest _ (InvalidDestinationHost _)) = return ()
assertThrows "exception if no host" noHost (get "http://")
funkyScheme Verb{..} site = do
-- schemes are case insensitive, per RFC 3986 section 3.1
let (scheme, rest) = break (==':') $ site "/get"
void . get $ map toUpper scheme <> rest
cookiesSet Verb{..} site = do
r <- get (site "/cookies/set?x=y")
assertEqual "cookies are set correctly" (Just "y")
(r ^? responseCookie "x" . cookieValue)
cookieSession site = do
s <- Session.newSession
r0 <- Session.get s (site "/cookies/set?foo=bar")
assertEqual "after set foo, foo set" (Just "bar")
(r0 ^? responseCookie "foo" . cookieValue)
assertEqual "a different accessor works" (Just "bar")
(r0 ^. responseBody ^? key "cookies" . key "foo")
r1 <- Session.get s (site "/cookies")
assertEqual "long after set foo, foo still set" (Just "bar")
(r1 ^? responseCookie "foo" . cookieValue)
r2 <- Session.get s (site "/cookies/set?baz=quux")
assertEqual "after set baz, foo still set" (Just "bar")
(r2 ^? responseCookie "foo" . cookieValue)
assertEqual "after set baz, baz set" (Just "quux")
(r2 ^? responseCookie "baz" . cookieValue)
r3 <- Session.get s (site "/cookies")
assertEqual "long after set baz, foo still set" (Just "bar")
(r3 ^? responseCookie "foo" . cookieValue)
assertEqual "long after set baz, baz still set" (Just "quux")
(r3 ^? responseCookie "baz" . cookieValue)
r4 <- Session.get s (site "/cookies/delete?foo")
assertEqual "after delete foo, foo deleted" Nothing
(r4 ^? responseCookie "foo" . cookieValue)
assertEqual "after delete foo, baz still set" (Just "quux")
(r4 ^? responseCookie "baz" . cookieValue)
r5 <- Session.get s (site "/cookies")
assertEqual "long after delete foo, foo still deleted" Nothing
(r5 ^? responseCookie "foo" . cookieValue)
assertEqual "long after delete foo, baz still set" (Just "quux")
(r5 ^? responseCookie "baz" . cookieValue)
getWithManager site = withManager $ \opts -> do
void $ Wreq.getWith opts (site "/get?a=b")
void $ Wreq.getWith opts (site "/get?b=c")
assertThrows :: (Show e, Exception e) => String -> (e -> IO ()) -> IO a -> IO ()
assertThrows desc inspect act = do
let myInspect e = inspect e `E.catch` \(ee :: E.PatternMatchFail) ->
assertFailure (desc <> ": unexpected exception (" <>
show e <> "): " <> show ee)
caught <- (act >> return False) `E.catch` \e -> myInspect e >> return True
unless caught (assertFailure desc)
commonTestsWith verb site = [
testGroup "basic" [
testCase "get" $ basicGet verb site
, testCase "post" $ basicPost verb site
, testCase "head" $ basicHead verb site
, testCase "put" $ basicPut verb site
, testCase "delete" $ basicDelete verb site
, testCase "404" $ throwsStatusCode verb site
, testCase "headRedirect" $ headRedirect verb site
, testCase "redirectOverflow" $ redirectOverflow verb site
, testCase "invalidURL" $ invalidURL verb site
, testCase "funkyScheme" $ funkyScheme verb site
]
, testGroup "fancy" [
testCase "basic auth" $ getBasicAuth verb site
, testCase "redirect" $ getRedirect verb site
, testCase "params" $ getParams verb site
, testCase "headers" $ getHeaders verb site
, testCase "gzip" $ getGzip verb site
, testCase "json put" $ jsonPut verb site
, testCase "bytestring put" $ byteStringPut verb site
, testCase "cookiesSet" $ cookiesSet verb site
, testCase "getWithManager" $ getWithManager site
, testCase "cookieSession" $ cookieSession site
, testCase "getCheckStatus" $ getCheckStatus verb site
]
]
-- Snap responds incorrectly to HEAD (by sending a response body),
-- thereby killing http-client's ability to continue a session.
-- https://github.com/snapframework/snap-core/issues/192
snapHeadSessionBug site = do
s <- Session.newSession
basicHead (session s) site
-- will crash with (InvalidStatusLine "0")
basicGet (session s) site
httpbinTestsWith verb site = commonTestsWith verb site <> [
]
-- Tests that our local httpbin clone doesn't yet support.
httpbinTests verb = [testGroup "httpbin" [
testGroup "http" $ httpbinTestsWith verb ("http://httpbin.org" <>)
, testGroup "https" $ httpbinTestsWith verb ("https://httpbin.org" <>)
]]
-- Tests that httpbin.org doesn't support.
localTests verb site = commonTestsWith verb site <> [
testCase "oauth2 Bearer" $ getOAuth2 verb "Bearer" oauth2Bearer site
, testCase "oauth2 token" $ getOAuth2 verb "token" oauth2Token site
]
startServer = do
started <- newEmptyMVar
let go n | n >= 100 = putMVar started Nothing
| otherwise = do
let port = 8000 + n
startedUp p = putMVar started (Just ("http://0.0.0.0:" <> p))
mkCfg = return . setBind ("0.0.0.0") . setPort port .
setVerbose False .
setStartupHook (const (startedUp (show port)))
serve mkCfg `E.catch` \(_::E.IOException) -> go (n+1)
tid <- forkIO $ go 0
(,) tid <$> takeMVar started
testWith :: [Test] -> IO ()
testWith tests = do
(tid, mserv) <- startServer
s <- Session.newSession
flip E.finally (killThread tid) .
defaultMain $ tests <>
[ testGroup "plain" $ httpbinTests basic
, testGroup "session" $ httpbinTests (session s)] <>
case mserv of
Nothing -> []
Just binding -> [
testGroup "localhost" [
testGroup "plain" $ localTests basic (binding <>)
, testGroup "session" $ localTests (session s) (binding <>)
]
]
|
bos/wreq
|
tests/UnitTests.hs
|
bsd-3-clause
| 17,194
| 0
| 23
| 3,982
| 5,377
| 2,697
| 2,680
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
module Snap.Internal.Parsing where
------------------------------------------------------------------------------
import Control.Applicative (Alternative ((<|>)), Applicative (pure, (*>), (<*)), liftA2, (<$>))
import Control.Arrow (first, second)
import Control.Monad (Monad (return), MonadPlus (mzero), liftM, when)
import Data.Attoparsec.ByteString.Char8 (IResult (Done, Fail, Partial), Parser, Result, anyChar, char, choice, decimal, endOfInput, feed, inClass, isDigit, isSpace, letter_ascii, many', match, option, parse, satisfy, skipSpace, skipWhile, string, take, takeTill, takeWhile, sepBy')
import qualified Data.Attoparsec.ByteString.Char8 as AP
import Data.Bits (Bits (unsafeShiftL, (.&.), (.|.)))
import Data.ByteString.Builder (Builder, byteString, char8, toLazyByteString, word8)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Internal (c2w, w2c)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI (mk)
import Data.Char (Char, intToDigit, isAlpha, isAlphaNum, isAscii, isControl, isHexDigit, ord)
import Data.Int (Int64)
import Data.List (concat, intercalate, intersperse)
import Data.Map (Map)
import qualified Data.Map as Map (empty, insertWith, toList)
import Data.Maybe (Maybe (..), maybe)
import Data.Monoid (Monoid (mconcat, mempty), (<>))
import Data.Word (Word8)
import GHC.Exts (Int (I#), uncheckedShiftRL#, word2Int#)
import GHC.Word (Word8 (..))
import Prelude (Bool (..), Either (..), Enum (fromEnum, toEnum), Eq (..), Num (..), Ord (..), String, and, any, concatMap, elem, error, filter, flip, foldr, fst, id, map, not, otherwise, show, snd, ($), ($!), (&&), (++), (.), (||))
import Snap.Internal.Http.Types (Cookie (Cookie))
------------------------------------------------------------------------------
------------------------------------------------------------------------------
{-# INLINE fullyParse #-}
fullyParse :: ByteString -> Parser a -> Either String a
fullyParse = fullyParse' parse feed
{-# INLINE (<?>) #-}
(<?>) :: Parser a -> String -> Parser a
(<?>) a !b = (AP.<?>) a b
infix 0 <?>
------------------------------------------------------------------------------
{-# INLINE fullyParse' #-}
fullyParse' :: (Parser a -> ByteString -> Result a)
-> (Result a -> ByteString -> Result a)
-> ByteString
-> Parser a
-> Either String a
fullyParse' parseFunc feedFunc s p =
case r' of
(Fail _ context e) -> Left $ concat [ "Parsing "
, intercalate "/" context
, ": "
, e
, "."
]
(Partial _) -> Left "parse failed" -- expected to be impossible
(Done _ x) -> Right x
where
r = parseFunc p s
r' = feedFunc r ""
------------------------------------------------------------------------------
-- Parsers for different tokens in an HTTP request.
------------------------------------------------------------------------------
parseNum :: Parser Int64
parseNum = decimal
------------------------------------------------------------------------------
untilEOL :: Parser ByteString
untilEOL = takeWhile notend <?> "untilEOL"
where
notend c = not $ c == '\r' || c == '\n'
------------------------------------------------------------------------------
crlf :: Parser ByteString
crlf = string "\r\n" <?> "crlf"
------------------------------------------------------------------------------
toTableList :: (Char -> Bool) -> [Char]
toTableList f = l
where
g c = c /= '-' && f c
!l1 = filter g $ map w2c [0..255]
!l0 = if f '-' then ['-'] else []
!l = l0 ++ l1
{-# INLINE toTableList #-}
------------------------------------------------------------------------------
toTable :: (Char -> Bool) -> (Char -> Bool)
toTable = inClass . toTableList
{-# INLINE toTable #-}
------------------------------------------------------------------------------
skipFieldChars :: Parser ()
skipFieldChars = skipWhile isFieldChar
------------------------------------------------------------------------------
isFieldChar :: Char -> Bool
isFieldChar = toTable f
where
f c = (isDigit c) || (isAlpha c) || c == '-' || c == '_'
------------------------------------------------------------------------------
-- | Parser for request headers.
pHeaders :: Parser [(ByteString, ByteString)]
pHeaders = many' header <?> "headers"
where
--------------------------------------------------------------------------
slurp p = fst <$> match p
--------------------------------------------------------------------------
header = {-# SCC "pHeaders/header" #-}
liftA2 (,)
fieldName
(char ':' *> skipSpace *> contents)
--------------------------------------------------------------------------
fieldName = {-# SCC "pHeaders/fieldName" #-}
slurp (letter_ascii *> skipFieldChars)
--------------------------------------------------------------------------
contents = {-# SCC "pHeaders/contents" #-}
liftA2 S.append
(untilEOL <* crlf)
(continuation <|> pure S.empty)
--------------------------------------------------------------------------
isLeadingWS w = {-# SCC "pHeaders/isLeadingWS" #-}
w == ' ' || w == '\t'
--------------------------------------------------------------------------
leadingWhiteSpace = {-# SCC "pHeaders/leadingWhiteSpace" #-}
skipWhile1 isLeadingWS
--------------------------------------------------------------------------
continuation = {-# SCC "pHeaders/continuation" #-}
liftA2 S.cons
(leadingWhiteSpace *> pure ' ')
contents
--------------------------------------------------------------------------
skipWhile1 f = satisfy f *> skipWhile f
------------------------------------------------------------------------------
-- unhelpfully, the spec mentions "old-style" cookies that don't have quotes
-- around the value. wonderful.
pWord :: Parser ByteString
pWord = pWord' isRFCText
------------------------------------------------------------------------------
pWord' :: (Char -> Bool) -> Parser ByteString
pWord' charPred = pQuotedString' charPred <|> (takeWhile (/= ';'))
------------------------------------------------------------------------------
pQuotedString :: Parser ByteString
pQuotedString = pQuotedString' isRFCText
------------------------------------------------------------------------------
pQuotedString' :: (Char -> Bool) -> Parser ByteString
pQuotedString' charPred = q *> quotedText <* q
where
quotedText = (S.concat . L.toChunks . toLazyByteString) <$> f mempty
f soFar = do
t <- takeWhile qdtext
let soFar' = soFar <> byteString t
-- RFC says that backslash only escapes for <">
choice [ string "\\\"" *> f (soFar' <> char8 '"')
, pure soFar' ]
q = char '"'
qdtext = matchAll [ charPred, (/= '"'), (/= '\\') ]
------------------------------------------------------------------------------
{-# INLINE isRFCText #-}
isRFCText :: Char -> Bool
isRFCText = not . isControl
------------------------------------------------------------------------------
{-# INLINE matchAll #-}
matchAll :: [ Char -> Bool ] -> Char -> Bool
matchAll x c = and $ map ($ c) x
------------------------------------------------------------------------------
pAvPairs :: Parser [(ByteString, ByteString)]
pAvPairs = do
a <- pAvPair
b <- many' (skipSpace *> char ';' *> skipSpace *> pAvPair)
return $! a:b
------------------------------------------------------------------------------
{-# INLINE pAvPair #-}
pAvPair :: Parser (ByteString, ByteString)
pAvPair = do
key <- pToken <* skipSpace
val <- liftM trim (option "" $ char '=' *> skipSpace *> pWord)
return $! (key, val)
------------------------------------------------------------------------------
pParameter :: Parser (ByteString, ByteString)
pParameter = pParameter' isRFCText
------------------------------------------------------------------------------
pParameter' :: (Char -> Bool) -> Parser (ByteString, ByteString)
pParameter' valueCharPred = parser <?> "pParameter'"
where
parser = do
key <- pToken <* skipSpace
val <- liftM trim (char '=' *> skipSpace *> pWord' valueCharPred)
return $! (trim key, val)
------------------------------------------------------------------------------
{-# INLINE trim #-}
trim :: ByteString -> ByteString
trim = snd . S.span isSpace . fst . S.spanEnd isSpace
------------------------------------------------------------------------------
pValueWithParameters :: Parser (ByteString, [(CI ByteString, ByteString)])
pValueWithParameters = pValueWithParameters' isRFCText
------------------------------------------------------------------------------
pValueWithParameters' :: (Char -> Bool) -> Parser (ByteString, [(CI ByteString, ByteString)])
pValueWithParameters' valueCharPred = parser <?> "pValueWithParameters'"
where
parser = do
value <- liftM trim (skipSpace *> takeWhile (/= ';'))
params <- many' pParam
endOfInput
return (value, map (first CI.mk) params)
pParam = skipSpace *> char ';' *> skipSpace *> pParameter' valueCharPred
------------------------------------------------------------------------------
pContentTypeWithParameters :: Parser ( ByteString
, [(CI ByteString, ByteString)] )
pContentTypeWithParameters = parser <?> "pContentTypeWithParameters"
where
parser = do
value <- liftM trim (skipSpace *> takeWhile (not . isSep))
params <- many' (skipSpace *> satisfy isSep *> skipSpace *> pParameter)
endOfInput
return $! (value, map (first CI.mk) params)
isSep c = c == ';' || c == ','
------------------------------------------------------------------------------
{-# INLINE pToken #-}
pToken :: Parser ByteString
pToken = takeWhile isToken
------------------------------------------------------------------------------
{-# INLINE isToken #-}
isToken :: Char -> Bool
isToken = toTable f
where
f = matchAll [ isAscii
, not . isControl
, not . isSpace
, not . flip elem [ '(', ')', '<', '>', '@', ',', ';'
, ':', '\\', '\"', '/', '[', ']'
, '?', '=', '{', '}' ]
]
------------------------------------------------------------------------------
{-# INLINE pTokens #-}
-- | Used for "#field-name", and field-name = token, so "#token":
-- comma-separated tokens/field-names, like a header field list.
pTokens :: Parser [ByteString]
pTokens = (skipSpace *> pToken <* skipSpace) `sepBy'` char ','
------------------
-- Url encoding --
------------------
------------------------------------------------------------------------------
{-# INLINE parseToCompletion #-}
parseToCompletion :: Parser a -> ByteString -> Maybe a
parseToCompletion p s = toResult $ finish r
where
r = parse p s
toResult (Done _ c) = Just c
toResult _ = Nothing
------------------------------------------------------------------------------
type DList a = [a] -> [a]
pUrlEscaped :: Parser ByteString
pUrlEscaped = do
sq <- nextChunk id
return $! S.concat $ sq []
where
--------------------------------------------------------------------------
nextChunk :: DList ByteString -> Parser (DList ByteString)
nextChunk !s = (endOfInput *> pure s) <|> do
c <- anyChar
case c of
'+' -> plusSpace s
'%' -> percentEncoded s
_ -> unEncoded c s
--------------------------------------------------------------------------
percentEncoded :: DList ByteString -> Parser (DList ByteString)
percentEncoded !l = do
hx <- take 2
when (S.length hx /= 2 || (not $ S.all isHexDigit hx)) $
mzero
let code = w2c ((unsafeFromHex hx) :: Word8)
nextChunk $ l . ((S.singleton code) :)
--------------------------------------------------------------------------
unEncoded :: Char -> DList ByteString -> Parser (DList ByteString)
unEncoded !c !l' = do
let l = l' . ((S.singleton c) :)
bs <- takeTill (flip elem ['%', '+'])
if S.null bs
then nextChunk l
else nextChunk $ l . (bs :)
--------------------------------------------------------------------------
plusSpace :: DList ByteString -> Parser (DList ByteString)
plusSpace l = nextChunk (l . ((S.singleton ' ') :))
------------------------------------------------------------------------------
-- "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'(),"
-- [not including the quotes - ed], and reserved characters used for their
-- reserved purposes may be used unencoded within a URL."
------------------------------------------------------------------------------
-- | Decode an URL-escaped string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>)
--
-- Example:
--
-- @
-- ghci> 'urlDecode' "1+attoparsec+%7e%3d+3+*+10%5e-2+meters"
-- Just "1 attoparsec ~= 3 * 10^-2 meters"
-- @
urlDecode :: ByteString -> Maybe ByteString
urlDecode = parseToCompletion pUrlEscaped
{-# INLINE urlDecode #-}
------------------------------------------------------------------------------
-- | URL-escape a string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>)
--
-- Example:
--
-- @
-- ghci> 'urlEncode' "1 attoparsec ~= 3 * 10^-2 meters"
-- "1+attoparsec+%7e%3d+3+*+10%5e-2+meters"
-- @
urlEncode :: ByteString -> ByteString
urlEncode = S.concat . L.toChunks . toLazyByteString . urlEncodeBuilder
{-# INLINE urlEncode #-}
------------------------------------------------------------------------------
-- | URL-escape a string (see
-- <http://tools.ietf.org/html/rfc2396.html#section-2.4>) into a 'Builder'.
--
-- Example:
--
-- @
-- ghci> import "Data.ByteString.Builder"
-- ghci> 'toLazyByteString' . 'urlEncodeBuilder' $ "1 attoparsec ~= 3 * 10^-2 meters"
-- "1+attoparsec+%7e%3d+3+*+10%5e-2+meters"
-- @
urlEncodeBuilder :: ByteString -> Builder
urlEncodeBuilder = go mempty
where
go !b !s = maybe b' esc (S.uncons y)
where
(x,y) = S.span urlEncodeClean s
b' = b <> byteString x
esc (c,r) = let b'' = if c == ' '
then b' <> char8 '+'
else b' <> hexd c
in go b'' r
------------------------------------------------------------------------------
urlEncodeClean :: Char -> Bool
urlEncodeClean = toTable f
where
f c = any ($ c) [\c' -> isAscii c' && isAlphaNum c'
, flip elem [ '$', '_', '-', '.', '!'
, '*' , '\'', '(', ')', ',' ]]
------------------------------------------------------------------------------
hexd :: Char -> Builder
hexd c0 = char8 '%' <> word8 hi <> word8 low
where
!c = c2w c0
toDigit = c2w . intToDigit
!low = toDigit $ fromEnum $ c .&. 0xf
!hi = toDigit $ (c .&. 0xf0) `shiftr` 4
shiftr (W8# a#) (I# b#) = I# (word2Int# (uncheckedShiftRL# a# b#))
------------------------------------------------------------------------------
finish :: Result a -> Result a
finish (Partial f) = flip feed "" $ f ""
finish x = x
---------------------------------------
-- application/x-www-form-urlencoded --
---------------------------------------
------------------------------------------------------------------------------
-- | Parse a string encoded in @application/x-www-form-urlencoded@ < http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms format>.
--
-- Example:
--
-- @
-- ghci> 'parseUrlEncoded' "Name=John+Doe&Name=Jane+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21"
-- 'Data.Map.fromList' [("Age",["23"]),("Formula",["a + b == 13%!"]),("Name",["John Doe","Jane Doe"])]
-- @
parseUrlEncoded :: ByteString -> Map ByteString [ByteString]
parseUrlEncoded s = foldr ins Map.empty decoded
where
--------------------------------------------------------------------------
ins (!k,v) !m = Map.insertWith (++) k [v] m
--------------------------------------------------------------------------
parts :: [(ByteString,ByteString)]
parts = map breakApart $
S.splitWith (\c -> c == '&' || c == ';') s
--------------------------------------------------------------------------
breakApart = (second (S.drop 1)) . S.break (== '=')
--------------------------------------------------------------------------
urldecode = parseToCompletion pUrlEscaped
--------------------------------------------------------------------------
decodeOne (a,b) = do
!a' <- urldecode a
!b' <- urldecode b
return $! (a',b')
--------------------------------------------------------------------------
decoded = go id parts
where
go !dl [] = dl []
go !dl (x:xs) = maybe (go dl xs)
(\p -> go (dl . (p:)) xs)
(decodeOne x)
------------------------------------------------------------------------------
-- | Like 'printUrlEncoded', but produces a 'Builder' instead of a
-- 'ByteString'. Useful for constructing a large string efficiently in
-- a single step.
--
-- Example:
--
-- @
-- ghci> import "Data.Map"
-- ghci> import "Data.Monoid"
-- ghci> import "Data.ByteString.Builder"
-- ghci> let bldr = 'buildUrlEncoded' ('Data.Map.fromList' [("Name", ["John Doe"]), ("Age", ["23"])])
-- ghci> 'toLazyByteString' $ 'byteString' "http://example.com/script?" <> bldr
-- "http://example.com/script?Age=23&Name=John+Doe"
-- @
buildUrlEncoded :: Map ByteString [ByteString] -> Builder
buildUrlEncoded m = mconcat builders
where
builders = intersperse (char8 '&') $
concatMap encodeVS $ Map.toList m
encodeVS (k,vs) = map (encodeOne k) vs
encodeOne k v = mconcat [ urlEncodeBuilder k
, char8 '='
, urlEncodeBuilder v ]
------------------------------------------------------------------------------
-- | Given a collection of key-value pairs with possibly duplicate
-- keys (represented as a 'Data.Map.Map'), construct a string in
-- @application/x-www-form-urlencoded@ format.
--
-- Example:
--
-- @
-- ghci> 'printUrlEncoded' ('Data.Map.fromList' [("Name", ["John Doe"]), ("Age", ["23"])])
-- "Age=23&Name=John+Doe"
-- @
printUrlEncoded :: Map ByteString [ByteString] -> ByteString
printUrlEncoded = S.concat . L.toChunks . toLazyByteString . buildUrlEncoded
--------------------
-- Cookie parsing --
--------------------
------------------------------------------------------------------------------
-- these definitions try to mirror RFC-2068 (the HTTP/1.1 spec) and RFC-2109
-- (cookie spec): please point out any errors!
------------------------------------------------------------------------------
pCookies :: Parser [Cookie]
pCookies = do
-- grab kvps and turn to strict bytestrings
kvps <- pAvPairs
return $! map toCookie $ filter (not . S.isPrefixOf "$" . fst) kvps
where
toCookie (nm,val) = Cookie nm val Nothing Nothing Nothing False False
------------------------------------------------------------------------------
parseCookie :: ByteString -> Maybe [Cookie]
parseCookie = parseToCompletion pCookies
-----------------------
-- utility functions --
-----------------------
------------------------------------------------------------------------------
unsafeFromHex :: (Enum a, Num a, Bits a) => ByteString -> a
unsafeFromHex = S.foldl' f 0
where
#if MIN_VERSION_base(4,5,0)
sl = unsafeShiftL
#else
sl = shiftL
#endif
f !cnt !i = sl cnt 4 .|. nybble i
nybble c | c >= '0' && c <= '9' = toEnum $! fromEnum c - fromEnum '0'
| c >= 'a' && c <= 'f' = toEnum $! 10 + fromEnum c - fromEnum 'a'
| c >= 'A' && c <= 'F' = toEnum $! 10 + fromEnum c - fromEnum 'A'
| otherwise = error $ "bad hex digit: " ++ show c
{-# INLINE unsafeFromHex #-}
------------------------------------------------------------------------------
-- Note: only works for nonnegative naturals
unsafeFromNat :: (Enum a, Num a, Bits a) => ByteString -> a
unsafeFromNat = S.foldl' f 0
where
zero = ord '0'
f !cnt !i = cnt * 10 + toEnum (digitToInt i)
digitToInt c = if d >= 0 && d <= 9
then d
else error $ "bad digit: '" ++ [c] ++ "'"
where
!d = ord c - zero
{-# INLINE unsafeFromNat #-}
|
23Skidoo/snap-core
|
src/Snap/Internal/Parsing.hs
|
bsd-3-clause
| 22,309
| 0
| 16
| 5,417
| 4,529
| 2,492
| 2,037
| 292
| 4
|
{-# OPTIONS_GHC -cpp #-}
import System.IO
import System.Directory (doesDirectoryExist, getCurrentDirectory)
import System.FilePath
import System.Cmd
import Data.List
import Text.Regex.Posix
parentDirectory :: FilePath -> FilePath
parentDirectory d = joinPath (init (splitDirectories d))
listAncestors :: FilePath -> [FilePath]
listAncestors "" = []
listAncestors path = [path] ++ listAncestors (parentDirectory path)
findGitFolder :: FilePath -> IO (Maybe FilePath)
findGitFolder "" = return Nothing
findGitFolder path = do
let gitPath = joinPath [path, ".git"]
exists <- doesDirectoryExist gitPath
if exists
then return (Just gitPath)
else findGitFolder (parentDirectory path)
githubUrl :: FilePath -> IO (Maybe String)
githubUrl configPath = do
results <- parseConfig configPath
if (length results) > 0
then return (Just ("https://github.com/" ++ ((last (head results)))))
else return Nothing
parseConfig :: FilePath -> IO [[String]]
parseConfig configPath = do
content <- readFile configPath
return (content =~ "github.com[:/]([^.]*)")
launchGithubForPath :: FilePath -> IO ()
launchGithubForPath path = do
gitFolder <- findGitFolder path
case gitFolder of
Just f -> launchBrowser (githubUrl (joinPath [f, "config"]))
Nothing -> putStrLn "Current folder is not inside a git repository"
--TODO .. change this to just take a string
launchBrowser url = do
toOpen <- url
case toOpen of
Just u -> do
#if defined(mingw32_HOST_OS)
--windows
putStrLn "OS: Windows"
system ("start " ++ u)
#elif defined(linux_HOST_OS)
--linux
putStrLn "OS: Linux"
system ("xdg-open " ++ u)
#elif defined(darwin_HOST_OS)
-- hopefully osx?
putStrLn "OS: MacOS"
system ("open " ++ u)
#endif
putStrLn ("Launching " ++ u)
Nothing -> putStrLn "No github remote found"
main = do
currentFolder <- getCurrentDirectory
launchGithubForPath currentFolder
|
rcknight/GitHubHere
|
gh.hs
|
bsd-3-clause
| 1,893
| 12
| 17
| 320
| 539
| 267
| 272
| 45
| 2
|
{-# LANGUAGE CPP, BangPatterns, Rank2Types #-}
#ifdef USE_MONO_PAT_BINDS
{-# LANGUAGE MonoPatBinds #-}
#endif
-- |
-- Module : Blaze.ByteString.Builder.Internal.Buffer
-- Copyright : (c) 2010 Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Stability : experimental
-- Portability : tested on GHC only
--
-- Execution of the 'Put' monad and hence also 'Builder's with respect to
-- buffers.
--
module Blaze.ByteString.Builder.Internal.Buffer (
-- * Buffers
Buffer (..)
-- ** Status information
, freeSize
, sliceSize
, bufferSize
-- ** Creation and modification
, allocBuffer
, reuseBuffer
, nextSlice
, updateEndOfSlice
, execBuildStep
-- ** Conversion to bytestings
, unsafeFreezeBuffer
, unsafeFreezeNonEmptyBuffer
-- * Buffer allocation strategies
, BufferAllocStrategy
, allNewBuffersStrategy
, reuseBufferStrategy
-- * Executing puts respect to some monad
, runPut
) where
#ifdef HAS_FOREIGN_UNSAFE_MODULE
import Foreign (Word8, ForeignPtr, Ptr, plusPtr, minusPtr)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
#else
import Foreign (unsafeForeignPtrToPtr, Word8, ForeignPtr, Ptr, plusPtr, minusPtr)
#endif
import qualified Data.ByteString as S
#ifdef BYTESTRING_IN_BASE
import qualified Data.ByteString.Base as S
#else
import qualified Data.ByteString.Internal as S
#endif
import Blaze.ByteString.Builder.Internal.Types
------------------------------------------------------------------------------
-- Buffers
------------------------------------------------------------------------------
-- | A buffer @Buffer fpbuf p0 op ope@ describes a buffer with the underlying
-- byte array @fpbuf..ope@, the currently written slice @p0..op@ and the free
-- space @op..ope@.
data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8) -- underlying pinned array
{-# UNPACK #-} !(Ptr Word8) -- beginning of slice
{-# UNPACK #-} !(Ptr Word8) -- next free byte
{-# UNPACK #-} !(Ptr Word8) -- first byte after buffer
-- | The size of the free space of the buffer.
freeSize :: Buffer -> Int
freeSize (Buffer _ _ op ope) = ope `minusPtr` op
-- | The size of the written slice in the buffer.
sliceSize :: Buffer -> Int
sliceSize (Buffer _ p0 op _) = op `minusPtr` p0
-- | The size of the whole byte array underlying the buffer.
bufferSize :: Buffer -> Int
bufferSize (Buffer fpbuf _ _ ope) =
ope `minusPtr` unsafeForeignPtrToPtr fpbuf
-- | @allocBuffer size@ allocates a new buffer of size @size@.
{-# INLINE allocBuffer #-}
allocBuffer :: Int -> IO Buffer
allocBuffer size = do
fpbuf <- S.mallocByteString size
let !pbuf = unsafeForeignPtrToPtr fpbuf
return $! Buffer fpbuf pbuf pbuf (pbuf `plusPtr` size)
-- | Resets the beginning of the next slice and the next free byte such that
-- the whole buffer can be filled again.
{-# INLINE reuseBuffer #-}
reuseBuffer :: Buffer -> Buffer
reuseBuffer (Buffer fpbuf _ _ ope) = Buffer fpbuf p0 p0 ope
where
p0 = unsafeForeignPtrToPtr fpbuf
-- | Convert the buffer to a bytestring. This operation is unsafe in the sense
-- that created bytestring shares the underlying byte array with the buffer.
-- Hence, depending on the later use of this buffer (e.g., if it gets reset and
-- filled again) referential transparency may be lost.
{-# INLINE unsafeFreezeBuffer #-}
unsafeFreezeBuffer :: Buffer -> S.ByteString
unsafeFreezeBuffer (Buffer fpbuf p0 op _) =
S.PS fpbuf (p0 `minusPtr` unsafeForeignPtrToPtr fpbuf) (op `minusPtr` p0)
-- | Convert a buffer to a non-empty bytestring. See 'unsafeFreezeBuffer' for
-- the explanation of why this operation may be unsafe.
{-# INLINE unsafeFreezeNonEmptyBuffer #-}
unsafeFreezeNonEmptyBuffer :: Buffer -> Maybe S.ByteString
unsafeFreezeNonEmptyBuffer buf
| sliceSize buf <= 0 = Nothing
| otherwise = Just $ unsafeFreezeBuffer buf
-- | Update the end of slice pointer.
{-# INLINE updateEndOfSlice #-}
updateEndOfSlice :: Buffer -- Old buffer
-> Ptr Word8 -- New end of slice
-> Buffer -- Updated buffer
updateEndOfSlice (Buffer fpbuf p0 _ ope) op' = Buffer fpbuf p0 op' ope
-- | Execute a build step on the given buffer.
{-# INLINE execBuildStep #-}
execBuildStep :: BuildStep a
-> Buffer
-> IO (BuildSignal a)
execBuildStep step (Buffer _ _ op ope) = runBuildStep step (BufRange op ope)
-- | Move the beginning of the slice to the next free byte such that the
-- remaining free space of the buffer can be filled further. This operation
-- is safe and can be used to fill the remaining part of the buffer after a
-- direct insertion of a bytestring or a flush.
{-# INLINE nextSlice #-}
nextSlice :: Int -> Buffer -> Maybe Buffer
nextSlice minSize (Buffer fpbuf _ op ope)
| ope `minusPtr` op <= minSize = Nothing
| otherwise = Just (Buffer fpbuf op op ope)
------------------------------------------------------------------------------
-- Buffer allocation strategies
------------------------------------------------------------------------------
-- | A buffer allocation strategy @(buf0, nextBuf)@ specifies the initial
-- buffer to use and how to compute a new buffer @nextBuf minSize buf@ with at
-- least size @minSize@ from a filled buffer @buf@. The double nesting of the
-- @IO@ monad helps to ensure that the reference to the filled buffer @buf@ is
-- lost as soon as possible, but the new buffer doesn't have to be allocated
-- too early.
type BufferAllocStrategy = (IO Buffer, Int -> Buffer -> IO (IO Buffer))
-- | The simplest buffer allocation strategy: whenever a buffer is requested,
-- allocate a new one that is big enough for the next build step to execute.
--
-- NOTE that this allocation strategy may spill quite some memory upon direct
-- insertion of a bytestring by the builder. Thats no problem for garbage
-- collection, but it may lead to unreasonably high memory consumption in
-- special circumstances.
allNewBuffersStrategy :: Int -- Minimal buffer size.
-> BufferAllocStrategy
allNewBuffersStrategy bufSize =
( allocBuffer bufSize
, \reqSize _ -> return (allocBuffer (max reqSize bufSize)) )
-- | An unsafe, but possibly more efficient buffer allocation strategy:
-- reuse the buffer, if it is big enough for the next build step to execute.
reuseBufferStrategy :: IO Buffer
-> BufferAllocStrategy
reuseBufferStrategy buf0 =
(buf0, tryReuseBuffer)
where
tryReuseBuffer reqSize buf
| bufferSize buf >= reqSize = return $ return (reuseBuffer buf)
| otherwise = return $ allocBuffer reqSize
------------------------------------------------------------------------------
-- Executing puts on a buffer
------------------------------------------------------------------------------
-- | Execute a put on a buffer.
--
-- TODO: Generalize over buffer allocation strategy.
{-# INLINE runPut #-}
runPut :: Monad m
=> (IO (BuildSignal a) -> m (BuildSignal a)) -- lifting of buildsteps
-> (Int -> Buffer -> m Buffer) -- output function for a guaranteedly non-empty buffer, the returned buffer will be filled next
-> (S.ByteString -> m ()) -- output function for guaranteedly non-empty bytestrings, that are inserted directly into the stream
-> Put a -- put to execute
-> Buffer -- initial buffer to be used
-> m (a, Buffer) -- result of put and remaining buffer
runPut liftIO outputBuf outputBS (Put put) =
runStep (put (finalStep))
where
finalStep x = buildStep $ \(BufRange op _) -> return $ Done op x
runStep step buf@(Buffer fpbuf p0 op ope) = do
let !br = BufRange op ope
signal <- liftIO $ runBuildStep step br
case signal of
Done op' x -> -- put completed, buffer partially runSteped
return (x, Buffer fpbuf p0 op' ope)
BufferFull minSize op' nextStep -> do
buf' <- outputBuf minSize (Buffer fpbuf p0 op' ope)
runStep nextStep buf'
InsertByteString op' bs nextStep
| S.null bs -> -- flushing of buffer required
outputBuf 1 (Buffer fpbuf p0 op' ope) >>= runStep nextStep
| p0 == op' -> do -- no bytes written: just insert bytestring
outputBS bs
runStep nextStep buf
| otherwise -> do -- bytes written, insert buffer and bytestring
buf' <- outputBuf 1 (Buffer fpbuf p0 op' ope)
outputBS bs
runStep nextStep buf'
|
meiersi/blaze-builder
|
Blaze/ByteString/Builder/Internal/Buffer.hs
|
bsd-3-clause
| 8,796
| 0
| 18
| 2,059
| 1,376
| 745
| 631
| 109
| 3
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
--
-- Light
--
module Ray.Light (
Light (..)
, generatePhoton
, getDirection
, getRadiance
, initLight
, lemittance
, validPoint
) where
--import System.Random
import Control.DeepSeq
import Control.DeepSeq.Generics (genericRnf)
import Data.Maybe
import Debug.Trace
import GHC.Generics
import NumericPrelude
import System.Random.Mersenne as MT
import Ray.Algebra
import Ray.Geometry
import Ray.Optics
import Ray.Physics
type Flux = Double
{-
Light: 光源型、物体形状と分離して光源の仕様のみとした。
参考光源情報)
Panasonic (https://panasonic.jp/lamp/)
電球型(LDA13(L/N/D)-G/Z100E/S/W, LDA7(L/WW/N/D)-D-G/S/Z6)
電球色 温白色 昼白色 昼光色
2700K 3500K 5000K 6500K
100W 60W 40W
1520lm 810lm 485lm
丸型(FCL30EL28MF2)
電球色 ナチュラル色 クール色
3000K 5200K 6200K
30W 32W 40W
2100lm 2480lm 3230lm
-}
data Light = Light
{ lcolor :: !Color
, flux :: !Flux
, directivity :: !Double
, lshape :: !Shape
, dirflag :: !Bool
-- calcuration when initializing
, cospower :: !Double
, power :: !Double
, emittance0 :: !Radiance
, nsample :: Int
}
deriving (Eq, Show, Generic)
instance NFData Light where
rnf = genericRnf
initLight :: Color -> Flux -> Double -> Shape -> Bool -> Light
initLight col lumen direct shape dirf = Light col flux direct shape dirf cpow pow em nsam
where
flux = lumen / 683.0
(cpow, pow) = densityPower (direct ** 3)
e0 = sr_half * flux / surfaceArea shape
em = (3.0 * e0) *> col <**> radiance1
ns = truncate (1.5 ** (direct * 10))
nsam = if ns < 1 then nSurface shape else ns * nSurface shape
--nsam = if ns < 1 then 1 else ns
lemittance :: Light -> Position3 -> Direction3 -> Direction3 -> Radiance
lemittance (Light _ _ _ _ _ _ pow em _) pos nvec vvec = cos' *> em
where
cos = nvec <.> vvec
cos' = (-cos) ** (0.5 / pow)
generatePhoton :: Light -> IO Photon
generatePhoton (Light c _ _ s flag _ pow _ _) = do
wl <- MT.randomIO :: IO Double
(pos, nvec) <- randomPoint s
let
w = decideWavelength c wl
nvec2 = if flag == True
then nvec
else negate nvec
nvec' <- blurredVector nvec2 pow
return (w, initRay pos nvec')
getDirection :: Light -> Position3 -> Position3 -> Maybe Direction3
getDirection (Light _ _ _ shape _ _ _ _ _) lpos pos
| nvec == Nothing = Nothing
| cos > 0.0 = Nothing
| otherwise = Just lvec
where
nvec = getNormal lpos shape
lvec = lpos - pos
cos = (fromJust nvec) <.> lvec
{-
光源までの距離は二乗された状態で入力される。1/4πd となっているがdは実際はd^2。
-}
getRadiance :: Light -> Direction3 -> Direction3 -> Radiance
getRadiance lgt@(Light (Color r g b) f _ _ _ cpow _ _ _) lnvec lvec
= Radiance (r * decay) (g * decay) (b * decay)
where
cos = lnvec <.> lvec
decay = f * (cos ** cpow) * (cpow + 1.0) / pi2
{-
-}
validPoint :: Light -> Position3 -> Direction3 -> IO (Position3, Direction3)
validPoint lgt pos nvec = do
(lpos, lnvec) <- randomPoint (lshape lgt)
if lnvec <.> nvec >= 0.0
then validPoint lgt pos nvec
else return (lpos, lnvec)
{-
else do
let
ldir = lpos - pos
p <- if ldir <.> nvec < 0.0
then validPoint lgt pos nvec
else return (lpos, lnvec)
return p
-}
|
eijian/raytracer
|
src/Ray/Light.hs
|
bsd-3-clause
| 3,549
| 0
| 11
| 893
| 974
| 523
| 451
| 94
| 2
|
module Parsers.Color
{- ( color
)-} where
import Control.Applicative ((*>), (<*), (<$>), (<*>))
import Data.Char
import Data.List (lookup)
import Data.Monoid ((<>))
import Text.Parsec
import Text.Parsec.String (Parser)
import Types
import Types.Color
import Parsers.Common
color :: Parser Color
color =
(try hexColor) <|> (try rgbColor) <|> (try rgbaColor) <|> (try hslColor) <|> (try hslaColor) <|> (try keyword)
hexColor :: Parser Color
hexColor = do
satisfy (== '#')
x <- many1 hexDigit
case x of
r1:r2:g1:g2:b1:b2:[] -> return $ Color (hex2Int [r1, r2]) (hex2Int [g1, g2]) (hex2Int [b1, b2]) 1
r:g:b:[] -> return $ Color (hex2Int [r, r]) (hex2Int [g, g]) (hex2Int [b, b]) 1
_ -> unexpected "Invalid format for hexadecimal color (eg. #333 or #333333)"
rgbColor :: Parser Color
rgbColor = do
try $ Text.Parsec.string "rgb("
spaces
r <- read <$> many1 digit
g <- read <$> do commaDelimiter *> many1 digit
b <- read <$> do commaDelimiter *> many1 digit
spaces *> satisfy (== ')')
return $ Color r g b 1
rgbaColor :: Parser Color
rgbaColor = do
try $ Text.Parsec.string "rgba("
spaces
r <- read <$> many1 digit
g <- read <$> do commaDelimiter *> many1 digit
b <- read <$> do commaDelimiter *> many1 digit
a <- do commaDelimiter *> decimal
spaces *> satisfy (== ')')
return $ Color r g b (read a)
hslColor :: Parser Color
hslColor = do
Text.Parsec.string "hsl("
spaces
h <- read <$> many1 digit
s <- value <$> do commaDelimiter *> percentage
l <- value <$> do commaDelimiter *> percentage
spaces *> satisfy (== ')')
let
(r, g, b) = hslrgb (h, s, l)
return $ Color r g b 1
hslaColor :: Parser Color
hslaColor = do
Text.Parsec.string "hsla("
spaces
h <- read <$> many1 digit
s <- value <$> do commaDelimiter *> percentage
l <- value <$> do commaDelimiter *> percentage
a <- read <$> do commaDelimiter *> decimal
spaces *> satisfy (== ')')
let
(r, g, b) = hslrgb (h, s, l)
return $ Color r g b a
keyword :: Parser Color
keyword = try $ do
n <- map toLower <$> many1 letter
case n `lookup` keywords of
Just c -> return c
Nothing -> parserZero
|
cimmanon/classi
|
src/Parsers/Color.hs
|
bsd-3-clause
| 2,098
| 2
| 16
| 421
| 967
| 481
| 486
| 69
| 3
|
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.HGL.Key
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Abstract representation of keys.
--
-----------------------------------------------------------------------------
#include "HsHGLConfig.h"
module Graphics.HGL.Key
( Key -- Abstract!
, keyToChar -- :: Key -> Char
, isCharKey -- :: Key -> Bool
, isBackSpaceKey -- :: Key -> Bool
, isTabKey -- :: Key -> Bool
-- , isLineFeedKey -- :: Key -> Bool
, isClearKey -- :: Key -> Bool
, isReturnKey -- :: Key -> Bool
, isEscapeKey -- :: Key -> Bool
, isDeleteKey -- :: Key -> Bool
-- , isMultiKeyKey -- :: Key -> Bool
, isHomeKey -- :: Key -> Bool
, isLeftKey -- :: Key -> Bool
, isUpKey -- :: Key -> Bool
, isRightKey -- :: Key -> Bool
, isDownKey -- :: Key -> Bool
, isPriorKey -- :: Key -> Bool
, isPageUpKey -- :: Key -> Bool
, isNextKey -- :: Key -> Bool
, isPageDownKey -- :: Key -> Bool
, isEndKey -- :: Key -> Bool
-- , isBeginKey -- :: Key -> Bool
, isShiftLKey -- :: Key -> Bool
, isShiftRKey -- :: Key -> Bool
, isControlLKey -- :: Key -> Bool
, isControlRKey -- :: Key -> Bool
-- , isCapsLockKey -- :: Key -> Bool
-- , isShiftLockKey -- :: Key -> Bool
-- , isMetaLKey -- :: Key -> Bool
-- , isMetaRKey -- :: Key -> Bool
-- , isAltLKey -- :: Key -> Bool
-- , isAltRKey -- :: Key -> Bool
) where
import Data.Maybe (isJust)
#if !X_DISPLAY_MISSING
import Graphics.HGL.X11.Types(Key(MkKey))
import Graphics.X11.Xlib
#else
import Graphics.HGL.Win32.Types(Key(MkKey))
import Graphics.Win32
#endif
----------------------------------------------------------------
-- Interface
----------------------------------------------------------------
-- | Converts a character key to a character.
keyToChar :: Key -> Char
isCharKey :: Key -> Bool -- Is it a "real" character?
isBackSpaceKey :: Key -> Bool
isTabKey :: Key -> Bool
--isLineFeedKey :: Key -> Bool
isClearKey :: Key -> Bool
isReturnKey :: Key -> Bool
isEscapeKey :: Key -> Bool
isDeleteKey :: Key -> Bool
--isMultiKeyKey :: Key -> Bool -- Multi-key character compose.
isHomeKey :: Key -> Bool -- Cursor home.
isLeftKey :: Key -> Bool -- Cursor left, left arrow.
isUpKey :: Key -> Bool -- Cursor up, up arrow.
isRightKey :: Key -> Bool -- Cursor right, right arrow.
isDownKey :: Key -> Bool -- Cursor down, down arrow.
isPriorKey :: Key -> Bool -- Prior, previous page. Same as page up.
isPageUpKey :: Key -> Bool -- Page up, previous page. Same as prior.
isNextKey :: Key -> Bool -- Next, next page. Same as page down.
isPageDownKey :: Key -> Bool -- Page down, next page. Same as next.
isEndKey :: Key -> Bool -- End of line.
--isBeginKey :: Key -> Bool -- Beginning of line.
isShiftLKey :: Key -> Bool -- Left shift.
isShiftRKey :: Key -> Bool -- Right shift.
isControlLKey :: Key -> Bool -- Left control.
isControlRKey :: Key -> Bool -- Right control.
--isCapsLockKey :: Key -> Bool -- Caps lock.
--isShiftLockKey :: Key -> Bool -- Shift lock.
--isMetaLKey :: Key -> Bool -- Left meta.
--isMetaRKey :: Key -> Bool -- Right meta.
--isAltLKey :: Key -> Bool -- Left alt.
--isAltRKey :: Key -> Bool -- Right alt.
----------------------------------------------------------------
-- Implementation
----------------------------------------------------------------
keyToChar (MkKey ks) =
case (keySymToChar ks) of
Just c -> c
Nothing -> error "keyToChar: Not a character key!"
isCharKey (MkKey ks) = isJust (keySymToChar ks)
#if !X_DISPLAY_MISSING
-- Converts an X KeySym representing an ISO 8859-1 (Latin 1) character or one
-- of a few control characters to a Char.
-- Note! It is assumed that the KeySym encoding for Latin 1 characters agrees
-- with the Haskell character encoding!
keySymToChar :: KeySym -> Maybe Char
keySymToChar ks
| xK_space <= ks && ks <= xK_ydiaeresis = Just (toEnum (fromIntegral ks))
| ks == xK_BackSpace = Just '\BS'
| ks == xK_Tab = Just '\HT'
| ks == xK_Linefeed = Just '\LF'
| ks == xK_Clear = Just '\FF'
| ks == xK_Return = Just '\CR'
| ks == xK_Escape = Just '\ESC'
| ks == xK_Delete = Just '\DEL'
| otherwise = Nothing
isBackSpaceKey (MkKey ks) = ks == xK_BackSpace
isTabKey (MkKey ks) = ks == xK_Tab
--isLineFeedKey (MkKey ks) = ks == xK_Linefeed
isClearKey (MkKey ks) = ks == xK_Clear
isReturnKey (MkKey ks) = ks == xK_Return
isEscapeKey (MkKey ks) = ks == xK_Escape
isDeleteKey (MkKey ks) = ks == xK_Delete
--isMultiKeyKey (MkKey ks) = ks == xK_Multi_key
isHomeKey (MkKey ks) = ks == xK_Home
isLeftKey (MkKey ks) = ks == xK_Left
isUpKey (MkKey ks) = ks == xK_Up
isRightKey (MkKey ks) = ks == xK_Right
isDownKey (MkKey ks) = ks == xK_Down
isPriorKey (MkKey ks) = ks == xK_Prior
isPageUpKey (MkKey ks) = ks == xK_Page_Up
isNextKey (MkKey ks) = ks == xK_Next
isPageDownKey (MkKey ks) = ks == xK_Page_Down
isEndKey (MkKey ks) = ks == xK_End
--isBeginKey (MkKey ks) = ks == xK_Begin
isShiftLKey (MkKey ks) = ks == xK_Shift_L
isShiftRKey (MkKey ks) = ks == xK_Shift_R
isControlLKey (MkKey ks) = ks == xK_Control_L
isControlRKey (MkKey ks) = ks == xK_Control_R
--isCapsLockKey (MkKey ks) = ks == xK_Caps_Lock
--isShiftLockKey (MkKey ks) = ks == xK_Shift_Lock
--isMetaLKey (MkKey ks) = ks == xK_Meta_L
--isMetaRKey (MkKey ks) = ks == xK_Meta_R
--isAltLKey (MkKey ks) = ks == xK_Alt_L
--isAltRKey (MkKey ks) = ks == xK_Alt_R
#else /* X_DISPLAY_MISSING */
-- Converts a VKey representing an ISO 8859-1 (Latin 1) character or one
-- of a few control characters to a Char.
-- Note! It is assumed that the VKey encoding for Latin 1 characters agrees
-- with the Haskell character encoding!
keySymToChar :: VKey -> Maybe Char
keySymToChar ks
| space <= ks && ks <= ydiaresis = Just (toEnum (fromIntegral ks))
| ks == vK_BACK = Just '\BS'
| ks == vK_TAB = Just '\HT'
-- | ks == vK_LINEFEED = Just '\LF'
| ks == vK_CLEAR = Just '\FF'
| ks == vK_RETURN = Just '\CR'
| ks == vK_ESCAPE = Just '\ESC'
| ks == vK_DELETE = Just '\DEL'
| otherwise = Nothing
where
space, ydiaresis :: VKey
space = fromIntegral (fromEnum ' ')
ydiaresis = fromIntegral 255 -- is this right?
isBackSpaceKey (MkKey ks) = ks == vK_BACK
isTabKey (MkKey ks) = ks == vK_TAB
--isLineFeedKey (MkKey ks) = ks == vK_LINEFEED
isClearKey (MkKey ks) = ks == vK_CLEAR
isReturnKey (MkKey ks) = ks == vK_RETURN
isEscapeKey (MkKey ks) = ks == vK_ESCAPE
isDeleteKey (MkKey ks) = ks == vK_DELETE
--isMultiKeyKey (MkKey ks) = ks == vK_MULTI_KEY
isHomeKey (MkKey ks) = ks == vK_HOME
isLeftKey (MkKey ks) = ks == vK_LEFT
isUpKey (MkKey ks) = ks == vK_UP
isRightKey (MkKey ks) = ks == vK_RIGHT
isDownKey (MkKey ks) = ks == vK_DOWN
isPriorKey (MkKey ks) = ks == vK_PRIOR
isPageUpKey (MkKey ks) = ks == vK_PRIOR -- same as isPriorKey
isNextKey (MkKey ks) = ks == vK_NEXT
isPageDownKey (MkKey ks) = ks == vK_NEXT -- same as isNextKey
isEndKey (MkKey ks) = ks == vK_END
--isBeginKey (MkKey ks) = ks == vK_Begin
isShiftLKey (MkKey ks) = ks == vK_SHIFT -- can't distinguish left and right
isShiftRKey (MkKey ks) = ks == vK_SHIFT
isControlLKey (MkKey ks) = ks == vK_CONTROL -- ambidextrous
isControlRKey (MkKey ks) = ks == vK_CONTROL
--isCapsLockKey (MkKey ks) = ks == vK_Caps_Lock
--isShiftLockKey (MkKey ks) = ks == vK_Shift_Lock
--isMetaLKey (MkKey ks) = ks == vK_Meta_L
--isMetaRKey (MkKey ks) = ks == vK_Meta_R
--isAltLKey (MkKey ks) = ks == vK_Alt_L
--isAltRKey (MkKey ks) = ks == vK_Alt_R
#endif /* X_DISPLAY_MISSING */
----------------------------------------------------------------
-- End
----------------------------------------------------------------
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HGL/Graphics/HGL/Key.hs
|
bsd-3-clause
| 8,550
| 5
| 10
| 2,245
| 1,009
| 573
| 436
| 85
| 2
|
module Haskell99Pointfree.P05
( p05_1,p05_2,p05_3,p05_4,p05_5,p05_6
) where
import Data.Bool.HT
import Control.Monad
import Control.Applicative
import Control.Monad.Extra (ifM)
import Data.List.Extra (snoc, cons)
import Control.Monad.Fix (fix)
p05_1 :: [a] -> [a]
p05_1 = ifM (not . null) (join (( . (flip (:) [] . head )) . (++) . p05_1 . tail) ) (const [])
p05_2 :: [a] -> [a]
p05_2 = liftA3 ifThenElse null (const []) ( flip (flip (++) . take 1) =<< p05_2 . tail )
--variation of p-5_2
p05_3 :: [a] -> [a]
p05_3= join ((. ap (flip (++) . take 1) (p05_3 . tail)) . flip if' [] . null )
p05_4 :: [a] -> [a]
p05_4 = snd . until (null . fst) (liftA2 (,) (tail . fst) (ap ( flip (:) . snd ) (head . fst))) . flip (,) []
--vairation of p05_4
p05_5 :: [a] -> [a]
p05_5 = snd . until (null . fst) (join ((. join ( ( . snd ) . (:) . head . fst) ) . (,) . tail . fst )) . flip (,) []
p05_6 :: [a] -> [a]
p05_6 = join ( (. (p05_6 . tail) ) . flip ifThenElse [] . null ) >>= flip (join ( ( . ( flip (++) . take 1 ) ) . flip ifThenElse (const []) . null ))
p05_7 :: [a] -> [a]
p05_7 = foldr (flip snoc) []
p05_8 :: [a] -> [a]
p05_8 = foldl (flip (:)) []
{-
p05_9 :: [a] -> [a]
p05_9 = fix ()
-}
|
SvenWille/Haskell99Pointfree
|
src/Haskell99Pointfree/P05.hs
|
bsd-3-clause
| 1,229
| 0
| 20
| 296
| 679
| 381
| 298
| 24
| 1
|
-- |
-- Module: Trace.Hpc.Codecov.Util
-- Copyright: (c) 2014 Guillaume Nargeot
-- License: BSD3
-- Maintainer: Guillaume Nargeot <guillaume+hackage@nargeot.com>
-- Stability: experimental
--
-- Utility functions.
module Trace.Hpc.Codecov.Util where
import Data.List
fst3 :: (a, b, c) -> a
fst3 (x, _, _) = x
snd3 :: (a, b, c) -> b
snd3 (_, x, _) = x
trd3 :: (a, b, c) -> c
trd3 (_, _, x) = x
fst4 :: (a, b, c, d) -> a
fst4 (x, _, _, _) = x
toFirstAndRest :: (a, b, c, d) -> (a, (b, c, d))
toFirstAndRest (a, b, c, d) = (a, (b, c, d))
listToMaybe :: [a] -> Maybe [a]
listToMaybe [] = Nothing
listToMaybe xs = Just xs
matchAny :: [String] -> String -> Bool
matchAny patterns fileName = any (`isPrefixOf` fileName) patterns
mapFirst :: (a -> a) -> [a] -> [a]
mapFirst f (x : xs) = f x : xs
mapFirst _ [] = []
mapLast :: (a -> a) -> [a] -> [a]
mapLast f [x] = [f x]
mapLast f (x : xs) = x : mapLast f xs
mapLast _ [] = []
subSeq :: Int -> Int -> [a] -> [a]
subSeq start end = drop start . take end
subSubSeq :: Int -> Int -> [[a]] -> [[a]]
subSubSeq start end = mapFirst (drop start) . mapLast (take end)
groupByIndex :: Int -> [(Int, a)] -> [[a]]
groupByIndex size = take size . flip (++) (repeat []) . groupByIndex' 0 []
where groupByIndex' _ ys [] = [ys]
groupByIndex' i ys xx@((xi, x) : xs) = if xi == i
then groupByIndex' i (x : ys) xs
else ys : groupByIndex' (i + 1) [] xx
|
guillaume-nargeot/codecov-haskell
|
src/Trace/Hpc/Codecov/Util.hs
|
bsd-3-clause
| 1,464
| 0
| 11
| 374
| 729
| 411
| 318
| 34
| 3
|
module Text.ICalendar.Component.VCalendar
( CalScale (..)
, VCalendar (..)
, parseVCalendar
) where
-- haskell platform libraries
import Control.Applicative ((<$>), (<*>))
import Text.Parsec.String
-- foreign libraries
import Text.Parsec.Permutation
-- native libraries
import Text.ICalendar.Component.VEvent
import Text.ICalendar.DataType.Text
import Text.ICalendar.Parser.Validator
data CalScale = Gregorian
| Unsupported String
deriving (Eq, Show)
data VCalendar = VCalendar { productId :: String
, version :: String
, scale :: CalScale
, method :: Maybe String
, events :: [VEvent]
} deriving (Eq, Show)
parseVCalendar :: Parser VCalendar
parseVCalendar = properties >>= components
where
properties = runPermParser $
VCalendar <$> reqProp1 textType "PRODID"
<*> reqProp1 textType "VERSION"
<*> scale1 textType "CALSCALE"
<*> optProp1 textType "METHOD"
components vCalendar = runPermParser $
vCalendar <$> optCompN parseVEvent "VEVENT"
scale1 par key = toCalScale <$> optProp1 par key
-- private functions
toCalScale :: Maybe String -> CalScale
toCalScale (Just "GREGORIAN") = Gregorian
toCalScale (Just other) = Unsupported other
toCalScale _ = Gregorian
|
Jonplussed/iCalendar
|
src/Text/ICalendar/Component/VCalendar.hs
|
bsd-3-clause
| 1,449
| 0
| 11
| 439
| 315
| 180
| 135
| 33
| 1
|
{-# LANGUAGE RecursiveDo, ScopedTypeVariables #-}
module Main where
import LOGL.Application
import LOGL.Camera
import Foreign.Ptr
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL.GL as GL hiding (normalize, position)
import Graphics.GLUtil
import System.FilePath
import Graphics.Rendering.OpenGL.GL.Shaders.ProgramObjects
import Linear.Matrix
import Linear.V3
import Linear.Vector
import Linear.Quaternion
import Linear.Projection
import Linear.Metric
import Reactive.Banana.Frameworks
import Reactive.Banana.Combinators hiding (empty)
import LOGL.FRP
import LOGL.Objects
cubePositions :: [V3 GLfloat]
cubePositions = [
V3 0.0 0.0 0.0,
V3 2.0 5.0 (-15.0),
V3 (-1.5) (-2.2) (-2.5),
V3 (-3.8) (-2.0) (-12.3),
V3 2.4 (-0.4) (-3.5),
V3 (-1.7) 3.0 (-7.5),
V3 1.3 (-2.0) (-2.5),
V3 1.5 2.0 (-2.5),
V3 1.5 0.2 (-1.5),
V3 (-1.3) 1.0 (-1.5)]
main :: IO ()
main = do
GLFW.init
w <- createAppWindow 800 600 "LearnOpenGL"
setCursorInputMode (window w) CursorInputMode'Disabled
depthFunc $= Just Less
lampShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "1_Colors" </> "lamp.vs")
("data" </> "2_Lighting" </> "1_Colors" </> "lamp.frag")
lightingShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "5_Light-casters" </> "point.vs")
("data" </> "2_Lighting" </> "5_Light-casters" </> "point.frag")
diffuseMap <- createTexture ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "container2.png")
specularMap <- createTexture ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "container2_specular.png")
currentProgram $= Just (program lightingShader)
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just diffuseMap
setUniform lightingShader "material.diffuse" (TextureUnit 0)
activeTexture $= TextureUnit 1
textureBinding Texture2D $= Just specularMap
setUniform lightingShader "material.specular" (TextureUnit 1)
cubeVBO <- createCubeVBO
containerVAO <- createContVAO cubeVBO
lightVAO <- createLampVAO cubeVBO
--polygonMode $= (Line, Line)
let networkDescription :: MomentIO ()
networkDescription = mdo
idleE <- idleEvent w
camB <- createAppCamera w (V3 0.0 0.0 3.0)
reactimate $ drawScene lightingShader containerVAO lampShader lightVAO w <$> (camB <@ idleE)
runAppLoopEx w networkDescription
deleteObjectName lightVAO
deleteObjectName containerVAO
deleteObjectName cubeVBO
terminate
drawScene :: ShaderProgram -> VertexArrayObject -> ShaderProgram -> VertexArrayObject -> AppWindow -> Camera GLfloat -> IO ()
drawScene lightingShader contVAO lampShader lightVAO w cam = do
pollEvents
clearColor $= Color4 0.1 0.1 0.1 1.0
clear [ColorBuffer, DepthBuffer]
Just time <- getTime
-- draw the container cube
currentProgram $= Just (program lightingShader)
let lightPos = V3 1.2 1.0 (2.0 :: GLfloat)
setUniform lightingShader "light.position" lightPos
setUniform lightingShader "viewPos" (position cam)
setUniform lightingShader "light.ambient" (V3 (0.2 :: GLfloat) 0.2 0.2)
setUniform lightingShader "light.diffuse" (V3 (0.5 :: GLfloat) 0.5 0.5)
setUniform lightingShader "light.specular" (V3 (1.0 :: GLfloat) 1.0 1.0)
setUniform lightingShader "light.constant" (1.0 :: GLfloat)
setUniform lightingShader "light.linear" (0.09 :: GLfloat)
setUniform lightingShader "light.quadratic" (0.032 :: GLfloat)
setUniform lightingShader "material.shininess" (32.0 :: GLfloat)
let view = viewMatrix cam
projection = perspective (radians (zoom cam)) (800.0 / 600.0) 0.1 (100.0 :: GLfloat)
setUniform lightingShader "view" view
setUniform lightingShader "projection" projection
withVAO contVAO $ mapM_ (drawCube lightingShader) [0..9]
-- draw the lamp
currentProgram $= Just (program lampShader)
setUniform lampShader "view" view
setUniform lampShader "projection" projection
let model = mkTransformationMat (0.2 *!! identity) lightPos
setUniform lampShader "model" model
withVAO lightVAO $ drawArrays Triangles 0 36
swap w
drawCube :: ShaderProgram -> Int -> IO ()
drawCube shader i = do
let angle = pi / 180.0 * 20.0 * fromIntegral i
rot = axisAngle (V3 (1.0 :: GLfloat) 0.3 0.5) (realToFrac angle)
model = mkTransformation rot (cubePositions !! i)
setUniform shader "model" model
drawArrays Triangles 0 36
createCubeVBO :: IO BufferObject
createCubeVBO = makeBuffer ArrayBuffer cubeWithNormalsAndTexture
createContVAO :: BufferObject -> IO VertexArrayObject
createContVAO vbo = do
vao <- genObjectName
bindVertexArrayObject $= Just vao
bindBuffer ArrayBuffer $= Just vbo
vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) offset0)
vertexAttribArray (AttribLocation 0) $= Enabled
vertexAttribPointer (AttribLocation 1) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) (offsetPtr (3*4)))
vertexAttribArray (AttribLocation 1) $= Enabled
vertexAttribPointer (AttribLocation 2) $= (ToFloat, VertexArrayDescriptor 2 Float (8*4) (offsetPtr (6*4)))
vertexAttribArray (AttribLocation 2) $= Enabled
bindVertexArrayObject $= Nothing
return vao
createLampVAO :: BufferObject -> IO VertexArrayObject
createLampVAO vbo = do
vao <- genObjectName
bindVertexArrayObject $= Just vao
bindBuffer ArrayBuffer $= Just vbo
vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) offset0)
vertexAttribArray (AttribLocation 0) $= Enabled
bindVertexArrayObject $= Nothing
return vao
|
atwupack/LearnOpenGL
|
app/2_Lighting/5_Light-casters/Light-casters-point.hs
|
bsd-3-clause
| 5,696
| 0
| 15
| 1,087
| 1,745
| 852
| 893
| 124
| 1
|
module Language.Java.Paragon.Monad.NameRes
(
NameRes(..)
, NameResEnv(..)
, Resolve
, getNameResEnv
, getExpansion
, getCurrentName
, withExpansion
, extendExpansion
) where
import Control.Applicative
import Control.Monad (ap, liftM)
import Language.Java.Paragon.Monad.Base
import Language.Java.Paragon.Monad.PiReader
import Language.Java.Paragon.NameResolution.Expansion
import Language.Java.Paragon.Syntax
data NameResEnv = NameResEnv
{ nrCurrentName :: Name
, nrExpansion :: Expansion
}
newtype NameRes a =
NameRes { runNameRes :: NameResEnv -> PiReader a }
type Resolve ast = ast -> NameRes ast
instance Monad NameRes where
return = liftPR . return
NameRes f >>= k = NameRes $ \env -> do
a <- f env
let NameRes g = k a
in g env
fail = liftPR . fail
instance MonadPR NameRes where
liftPR pr = NameRes $ \_ -> pr
instance MonadBase NameRes where
liftBase = liftPR . liftBase
withErrCtxt erC (NameRes f) = NameRes $ (withErrCtxt erC) . f
tryM (NameRes f) = NameRes $ tryM . f
failE = liftPR . failE
failEC x = liftPR . failEC x
instance MonadIO NameRes where
liftIO = liftPR . liftIO
instance Functor NameRes where
fmap = liftM
instance Applicative NameRes where
pure = return
(<*>) = ap
-- | Access environment
getNameResEnv :: NameRes NameResEnv
getNameResEnv = NameRes $ \s -> return s
-- | Access expansion map
getExpansion :: NameRes Expansion
getExpansion = nrExpansion <$> getNameResEnv
-- | Access name of currently handled syntactical unit
getCurrentName :: NameRes Name
getCurrentName = nrCurrentName <$> getNameResEnv
-- | Set expansion map for given NameRes computation
withExpansion :: Expansion -> NameRes a -> NameRes a
withExpansion e (NameRes f) = NameRes $ \env -> f (env {nrExpansion = e})
-- | Extend expansion map of given computation by given expansion map
extendExpansion :: Expansion -> NameRes a -> NameRes a
extendExpansion e1 nra = do
e2 <- getExpansion
withExpansion (expansionUnion [e1,e2]) nra
|
bvdelft/paragon
|
src/Language/Java/Paragon/Monad/NameRes.hs
|
bsd-3-clause
| 2,175
| 0
| 14
| 547
| 577
| 317
| 260
| 56
| 1
|
import Text.Regex.Posix
import qualified Data.Classifier as C
trainInput :: C.Classifier -> IO C.Classifier
trainInput cls = do
str <- getLine
case str of
[] -> do
putStrLn "\nNow classify some strings:\n"
return cls
_ -> do
case (str =~ "^([^:]+):(.+)$" :: [[String]]) of
(x:xs) -> trainInput $ C.train cls (x !! 1) (x !! 2)
_ -> do
putStrLn "Invalid format, please try again."
trainInput cls
classifyInput :: C.Classifier -> IO C.Classifier
classifyInput cls = do
str <- getLine
case str of
[] -> return cls
_ -> do
putStrLn $ ">> " ++ (show $ C.classify cls str)
classifyInput cls
main :: IO()
main = do
putStrLn "Enter training data (i.e. category:text):\n"
cls <- trainInput C.empty
classifyInput cls
putStrLn "Done."
|
derek-schaefer/haskell-classifier
|
src/Main.hs
|
bsd-3-clause
| 831
| 0
| 18
| 229
| 291
| 139
| 152
| 29
| 3
|
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack53 #-}
module Games.Chaos2010.Database.Action_history_mr where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Action_history_mr =
Record
(HCons (LVPair Id (Expr Int))
(HCons (LVPair History_name (Expr String))
(HCons (LVPair Allegiance (Expr (Maybe String)))
(HCons (LVPair X (Expr (Maybe Int)))
(HCons (LVPair Y (Expr (Maybe Int)))
(HCons (LVPair Tx (Expr (Maybe Int)))
(HCons (LVPair Ty (Expr (Maybe Int)))
(HCons (LVPair Ptype (Expr (Maybe String)))
(HCons (LVPair Tag (Expr (Maybe Int)))
(HCons (LVPair Spell_name (Expr (Maybe String)))
(HCons (LVPair Num_wizards (Expr (Maybe Int)))
(HCons (LVPair Turn_number (Expr (Maybe Int)))
(HCons (LVPair Turn_phase (Expr (Maybe String)))
HNil)))))))))))))
action_history_mr :: Table Action_history_mr
action_history_mr = baseTable "action_history_mr"
|
JakeWheat/Chaos-2010
|
Games/Chaos2010/Database/Action_history_mr.hs
|
bsd-3-clause
| 1,294
| 0
| 37
| 485
| 400
| 206
| 194
| 23
| 1
|
{-# Language OverloadedStrings, RecordWildCards #-}
module Cryptographer.Cmd.Render where
import Text.Blaze.Html5
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as As
import qualified Cryptographer.Common as C
import qualified Data.ByteString as BS
import Data.String
import System.IO
import qualified Pipes.ByteString as Pb
import qualified Pipes as P
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Cryptographer.Util
import Cryptographer.Format
import Data.ByteString.Base64.Lazy as BE
data RenderCTX = RenderCTX {
alljs :: String,
encText :: BS.ByteString
}
encTextName = fromString C.encTextName
keyInputName = fromString C.keyInputName
controlsName = fromString C.controlsName
contentName = fromString C.contentName
decryptButtonName = fromString C.decryptButtonName
warn :: Html
warn = fromString $ "This browser is not supported by Cryptographer. Please change web browser."
++ " If you opened this file in a file previewer, download the file and open"
++ " it in your web browser."
renderEncObject EncInput{..} = do
encText <- readPipes dataSources
return $ H.div $ do
H.input H.! As.type_ "hidden" H.! As.value (unsafeLazyByteStringValue encText) H.! As.id encTextName H.! H.customAttribute "checksum" (unsafeLazyByteStringValue $ BE.encode checksum)
H.input H.! As.type_ "password" H.! As.id keyInputName
H.input H.! As.type_ "submit" H.! As.id decryptButtonName H.! As.value "Decrypt"
renderIO o encText' cs = do
f <- P.liftIO C.allJS
e <- P.liftIO $ renderEncObject $ EncInput [encText'] cs
withFile f ReadMode $ \h -> do
let
out = Pb.toHandle o
js = Pb.fromHandle h
let renderer = do
P.yield "<html><head>"
P.yield "</head><body>"
Pb.fromLazy $ renderHtml e
Pb.fromLazy $ renderHtml $ H.div warn H.! As.id contentName
-- Pb.fromLazy . renderHtml $ render RenderCTX{alljs="", encText=encText'}
P.yield "<script type=\"text/javascript\">"
js
P.yield "</script>"
Pb.fromLazy . renderHtml $ H.script "window.onload = function(){h$main(h$mainZCMainzimain);}" H.! As.type_ "text/javacript"
P.yield "</body></html>"
P.runEffect (renderer P.>-> out)
|
netogallo/Cryptographer
|
src/Cryptographer/Cmd/Render.hs
|
bsd-3-clause
| 2,301
| 0
| 19
| 462
| 603
| 308
| 295
| 51
| 1
|
module EAFIT.CB0081.Data.NFA.Emptyness where
import Data.Set
import EAFIT.CB0081.Data.NFA
-- | 'empty_test' is the start function of the algorithm,
-- it begins the process calling 'reachable_step' with a set
-- only containing the initial state
empty_test :: (Ord a) => NFA a b -- ^ the machine to analyze
-> Bool -- ^ True if is not empty, False if empty
empty_test m = reachable_step m initial_state
where
initial_state = singleton $ startNFA m
-- | 'reachable_step'
reachable_step :: (Ord state) =>
NFA state symbols -- ^ the machine to analyze
-> Set state -- ^ the set of states of the current step
-> Bool -- ^ True if is not empty, False if empty
reachable_step m last_step
| some_is_final next_step = True
| step == last_step = False
| otherwise = reachable_step m step
where
step = union next_step last_step
next_step = unions [delta x y | x <- toList last_step, y <- toList sym]
some_is_final a = intersection a finals /= empty
delta = deltaNFA m
sym = symbolsNFA m
finals = finalsNFA m
|
afl-eafit/2013-2-lab1
|
src/EAFIT/CB0081/Data/NFA/Emptyness.hs
|
bsd-3-clause
| 1,136
| 0
| 11
| 313
| 247
| 128
| 119
| 21
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Arrow (arr)
import Control.Applicative ((<$>))
import Control.Category (id, (.))
import Data.Monoid ((<>))
import Data.Set (fromList)
import Data.Text (Text, pack, unpack)
import System.Environment (getArgs, getProgName)
import System.FilePath ((</>))
import System.Directory (canonicalizePath)
import Prelude hiding (id, (.))
import Scoutess.Core
import Scoutess.DataFlow
import Scoutess.Types
-- TODO: we need a real source of options and better (any) support for command line flags.
main :: IO ()
main = getArgs >>= \args -> case args of
[tName, tVersion, tLocation, sandboxDir, sources]
-> do sandboxAbs <- canonicalizePath sandboxDir
result <- buildScoutess tName tVersion tLocation sandboxAbs sources
putStrLn (ppScoutessResult result)
_ -> printUsage
buildScoutess :: String -> String -> String -> String -> String -> IO (Maybe BuildReport, [ComponentReport])
buildScoutess tName tVersion tLocation sandboxDir sources = do
sourceSpec <- SourceSpec . fromList . map read . lines <$> readFile sources
let targetSpec = makeTargetSpec (pack tName) (pack tVersion) (read tLocation) sandboxDir
runScoutess (standard id id)
(sourceSpec, targetSpec, Nothing)
onlyAllowHackage :: Scoutess SourceSpec SourceSpec
onlyAllowHackage = arr (filterSourceSpec (== Hackage))
printUsage :: IO ()
printUsage = getProgName >>= \progName -> putStrLn . unlines $
[ "Usage: " <> progName <> " tName tVersion tLocation sandboxDir sources\n"
, " tName: name of the target package"
, " tVersion: version of the target package"
, " tLocation: SourceLocation of the target package"
, " sandboxDir: directory to use as a sandbox"
, " sources: a file containing the accessable"
, " SourceLocations seperated by newlines"
, "For details of the SourceLocations, see Scoutess.Core.SourceLocation.\n"
, "Example:"
, " scoutess vector-algorithms 0.5.4 Hackage ./path/to/sandbox ./path/to/sources.txt\n"
, " where sources.txt contains the text \"Hackage\"."
, " would install vector-algorithms-0.5.4 in sandbox fetching the package and its dependencies from Hackage.\n"
, "By default the dependencies can only come from Hackage, to override this behaviour you need to call Scoutess.DataFlow.standard yourself."]
makeTargetSpec :: Text -> Text -> SourceLocation -> FilePath -> TargetSpec
makeTargetSpec name version location sandboxDir = TargetSpec
{ tsName = name
, tsVersion = version
, tsLocation = location
, tsTmpDir = sandboxDir </> "temp"
, tsLocalHackage = LocalHackage (sandboxDir </> "localHackage") (sandboxDir </> "localHackage" </> "temp")
, tsPackageDB = sandboxDir </> "package-cache"
, tsSourceConfig = SourceConfig (sandboxDir </> "srcCacheDir")
, tsCustomCabalArgs = ["--enable-documentation"
,"--docdir=" <> pack (sandboxDir </> "docs" </> "$pkg" </> "$version")]
}
|
cartazio/scoutess
|
Main.hs
|
bsd-3-clause
| 3,190
| 0
| 14
| 748
| 647
| 363
| 284
| 56
| 2
|
import qualified Data.Vector as V
import Test.Hspec.Monadic
import Test.Hspec.HUnit
import Data.Liblinear
main = hspecX $ do
describe "liblinear" $ do
it "correct" $ do
let prob = Problem
{ problemData = V.empty
, problemBias = 0
}
model <- train prob def
return ()
|
tanakh/hs-liblinear
|
test/test.hs
|
bsd-3-clause
| 328
| 0
| 19
| 106
| 100
| 52
| 48
| 12
| 1
|
module Index where
import Data.Bits
import Data.Attoparsec.ByteString.Char8
import qualified Text.PrettyPrint.ANSI.Leijen as T
type Index = Int
type Rank = Int
type File = Int
flattenRF :: Rank -> File -> Index
flattenRF r f = r * 8 + f
unflattenRF :: Index -> (Rank,File)
unflattenRF i = (i `shiftR` 3, i .&. 7)
indexToDoc :: Index -> T.Doc
indexToDoc i = T.char (toEnum (f + 97)) T.<> T.char (toEnum (r + 49))
where (r,f) = unflattenRF i
parseIndex :: Parser Index
parseIndex = parseFileRank combineFR
where combineFR f r = flattenRF (fromEnum r - 49) (fromEnum f - 97)
parseFileRank :: (Char -> Char -> a) -> Parser a
parseFileRank f = f <$> satisfy (\c -> 'a' <= c && c <= 'h') <*>
satisfy (\c -> '1' <= c && c <= '8')
|
mckeankylej/hchess
|
src/Index.hs
|
bsd-3-clause
| 771
| 0
| 12
| 184
| 330
| 180
| 150
| 20
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.BitPrecise.PrefixSum
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- The PrefixSum algorithm over power-lists and proof of
-- the Ladner-Fischer implementation.
-- See <http://dl.acm.org/citation.cfm?id=197356>
-- and <http://www.cs.utexas.edu/~plaxton/c/337/05f/slides/ParallelRecursion-4.pdf>.
-----------------------------------------------------------------------------
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.SBV.Examples.BitPrecise.PrefixSum where
import Data.SBV
----------------------------------------------------------------------
-- * Formalizing power-lists
----------------------------------------------------------------------
-- | A poor man's representation of powerlists and
-- basic operations on them: <http://dl.acm.org/citation.cfm?id=197356>
-- We merely represent power-lists by ordinary lists.
type PowerList a = [a]
-- | The tie operator, concatenation.
tiePL :: PowerList a -> PowerList a -> PowerList a
tiePL = (++)
-- | The zip operator, zips the power-lists of the same size, returns
-- a powerlist of double the size.
zipPL :: PowerList a -> PowerList a -> PowerList a
zipPL [] [] = []
zipPL (x:xs) (y:ys) = x : y : zipPL xs ys
zipPL _ _ = error "zipPL: nonsimilar powerlists received"
-- | Inverse of zipping.
unzipPL :: PowerList a -> (PowerList a, PowerList a)
unzipPL = unzip . chunk2
where chunk2 [] = []
chunk2 (x:y:xs) = (x,y) : chunk2 xs
chunk2 _ = error "unzipPL: malformed powerlist"
----------------------------------------------------------------------
-- * Reference prefix-sum implementation
----------------------------------------------------------------------
-- | Reference prefix sum (@ps@) is simply Haskell's @scanl1@ function.
ps :: (a, a -> a -> a) -> PowerList a -> PowerList a
ps (_, f) = scanl1 f
----------------------------------------------------------------------
-- * The Ladner-Fischer parallel version
----------------------------------------------------------------------
-- | The Ladner-Fischer (@lf@) implementation of prefix-sum. See <http://www.cs.utexas.edu/~plaxton/c/337/05f/slides/ParallelRecursion-4.pdf>
-- or pg. 16 of <http://dl.acm.org/citation.cfm?id=197356>
lf :: (a, a -> a -> a) -> PowerList a -> PowerList a
lf _ [] = error "lf: malformed (empty) powerlist"
lf _ [x] = [x]
lf (zero, f) pl = zipPL (zipWith f (rsh lfpq) p) lfpq
where (p, q) = unzipPL pl
pq = zipWith f p q
lfpq = lf (zero, f) pq
rsh xs = zero : init xs
----------------------------------------------------------------------
-- * Sample proofs for concrete operators
----------------------------------------------------------------------
-- | Correctness theorem, for a powerlist of given size, an associative operator, and its left-unit element.
flIsCorrect :: Int -> (forall a. (OrdSymbolic a, Num a, Bits a) => (a, a -> a -> a)) -> Symbolic SBool
flIsCorrect n zf = do
args :: PowerList SWord32 <- mkForallVars n
return $ ps zf args .== lf zf args
-- | Proves Ladner-Fischer is equivalent to reference specification for addition.
-- @0@ is the left-unit element, and we use a power-list of size @8@. We have:
--
-- >>> thm1
-- Q.E.D.
thm1 :: IO ThmResult
thm1 = prove $ flIsCorrect 8 (0, (+))
-- | Proves Ladner-Fischer is equivalent to reference specification for the function @max@.
-- @0@ is the left-unit element, and we use a power-list of size @16@. We have:
--
-- >>> thm2
-- Q.E.D.
thm2 :: IO ThmResult
thm2 = prove $ flIsCorrect 16 (0, smax)
|
josefs/sbv
|
Data/SBV/Examples/BitPrecise/PrefixSum.hs
|
bsd-3-clause
| 3,782
| 0
| 12
| 655
| 655
| 363
| 292
| 34
| 3
|
module Main where
import Parser.Parser
import Eval.Eval
import System.Environment
import Control.Monad.Except
main :: IO ()
main = do
pro <- readFile "program.txt"
inp <- readFile "input.txt"
res <- runExceptT $ runFromFile pro "program.txt" (words inp)
case res of
Left err -> print err
Right out -> let content = toOutput out in
putStrLn content >> writeFile "output.txt" content
return ()
runFromFile pro file input = do
ast <- getAST file pro
runProgram ast input
toOutput :: [String] -> String
toOutput = unlines . reverse
|
jyh1/mini
|
app/Main.hs
|
bsd-3-clause
| 565
| 0
| 14
| 121
| 199
| 95
| 104
| 20
| 2
|
{-# Language OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
--------------------------------------------------------------------
-- |
-- Module: HTrade.Test.TestConfiguration
--
-- Test verifying the functionality of configuration parsing and loading.
module Main where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (guard, liftM2)
import Control.Monad.Trans (lift, liftIO)
import qualified Data.ByteString.Char8 as B
import Data.Char (isAscii, isAlphaNum)
import qualified System.Directory as D
import System.IO (hClose, hPutStr)
import System.IO.Temp (openTempFile)
import qualified Test.QuickCheck as Q
import qualified Test.QuickCheck.Monadic as Q
import qualified HTrade.Backend.Configuration as C
import qualified HTrade.Backend.Types as T
import HTrade.Test.Utils
-- | Quickcheck instance for bytestrings, limited to alphanum ascii.
instance Q.Arbitrary B.ByteString where
arbitrary = fmap B.pack $ Q.suchThat Q.arbitrary filterTest
where
filterTest s = notElem '\\' s && and (map isAscii s ++ map isAlphaNum s)
-- | Quickcheck instance for market identifiers, only lifts existing.
instance Q.Arbitrary T.MarketIdentifier where
arbitrary = liftM2 T.MarketIdentifier Q.arbitrary Q.arbitrary
-- | Quickcheck instance for market configurations, only lifts existing.
instance Q.Arbitrary T.MarketConfiguration where
arbitrary = T.MarketConfiguration
<$> Q.arbitrary
<*> Q.arbitrary
<*> Q.arbitrary
<*> Q.arbitrary
<*> Q.arbitrary
<*> Q.arbitrary
-- | Generate a configuration, output it to a temporary file,
-- and verify that the parsed results are equal.
verifyConfigurationParser :: IO Bool
verifyConfigurationParser = withQuickCheck $ \genConf -> Q.monadicIO $ do
(path, handle) <- Q.run $ openTempFile "/tmp/" filePattern
Q.run $ hPutStr handle (showConfiguration genConf) >> hClose handle
parsedConf <- Q.run $ C.parseConfigurationFile path
Q.assert $ parsedConf == Just genConf
where
filePattern = "configuration-parser-test.conf"
-- | Verify that the system is capable of:
-- (1) loading a well-defined configuration file
-- (2) Retaining the loaded configuration (consecutive updates)
verifyConfigurationLoader :: IO Bool
verifyConfigurationLoader = withLayers poolSize $ do
-- setup temporary directory with a single configuration for testing
liftIO $ writeTempConf confDir filePattern testConf
-- load the given configuration
liftIO $ putStrLn "[*] Loading test configuration"
loadResult <- lift $ C.withConfiguration $ do
let load = C.loadConfigurations confDir
liftM2 (,) load load
let check output = fmap fst output == Just [T._marketIdentifier testConf]
guard $ check (fst loadResult) && check (snd loadResult)
liftIO $ putStrLn "[*] Test configuration verified"
-- cleanup
liftIO $ D.removeDirectoryRecursive confDir
where
poolSize = 10
confDir = "/tmp/sample_configurations/"
filePattern = "configuration-loader-test.conf"
testConf = T.MarketConfiguration
(T.MarketIdentifier "testMarket" "sek")
"http://localhost"
""
"trades.json"
"orders.json"
1000000
-- | Call tests and indicate success in return code.
main :: IO ()
main = checkTestCases [
("verifyConfigurationParser", verifyConfigurationParser),
("verifyConfigurationLoader", verifyConfigurationLoader)
]
|
davnils/distr-btc
|
src/HTrade/Test/TestConfiguration.hs
|
bsd-3-clause
| 3,613
| 0
| 16
| 791
| 695
| 376
| 319
| 61
| 1
|
{-# LANGUAGE OverloadedStrings, DeriveGeneric, DeriveAnyClass #-}
module Prismic where
import Data.Aeson (Value, Array, Object, FromJSON, ToJSON, Result(..), encode, fromJSON, parseJSON, toJSON)
import Data.Aeson.Types (genericParseJSON, genericToJSON, defaultOptions, fieldLabelModifier)
import Data.ByteString.Lazy (ByteString, toStrict)
import Data.ByteString.Lazy.UTF8 (toString)
import qualified Data.List as L
import Data.Set (Set)
import qualified Data.Set as S (fromList)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import Data.Vector (Vector)
import qualified Data.Vector as V (empty, singleton, concatMap, toList)
import GHC.Generics
import Network.HTTP (urlEncode)
import Network.Wreq (Options, defaults, param)
import Text.Regex.TDFA ((=~), getAllTextMatches)
data Query = Query {
endpoint :: String,
reference :: String,
documentType :: String }
deriving (Show)
queryString :: Query -> String
queryString q = "?" ++ L.intercalate "&" params
where
params = fmap (\(n, v) -> n ++ "=" ++ urlEncode v) [format, pageSize, ref, query]
format = ("format", "json")
pageSize = ("pageSize", "100")
ref = ("ref", reference q)
query = ("q", "[[:d=at(document.type,\"" ++ documentType q ++ "\")]]")
data Res = Res {
page :: Int,
results_per_page :: Int,
results_size :: Int,
total_results_size :: Int,
total_pages :: Int,
next_page :: Maybe String,
prev_page :: Maybe String,
results :: Array,
version :: Text,
license :: Text }
deriving (Show, Generic, FromJSON)
data Document = Document {
_id :: String,
_data :: Object,
_href :: String,
_type :: String,
_slugs :: Value,
_tags :: Value,
_linked_documents :: Value,
_uid :: Value }
deriving (Show, Generic)
instance ToJSON Document where
toJSON = genericToJSON defaultOptions { fieldLabelModifier = drop 1 }
instance FromJSON Document where
parseJSON = genericParseJSON defaultOptions { fieldLabelModifier = drop 1 }
extractDocuments :: Res -> Vector Document
extractDocuments res = V.concatMap parseDocument $ results res
where
parseDocument r = case parseData r of
Nothing -> V.empty
Just d -> V.singleton d
parseData :: Value -> Maybe Document
parseData r = resultToMaybe $ fromJSON r
resultToMaybe :: Result a -> Maybe a
resultToMaybe (Error _) = Nothing
resultToMaybe (Success a) = Just a
serializeDocument :: Document -> Text
serializeDocument = decodeUtf8 . toStrict . encode
analyzeDocuments :: Vector Document -> Set String
analyzeDocuments d = S.fromList $ fmap toString $ concat $ V.toList $ urls
where
urls :: Vector [ByteString]
urls = fmap extractResourceUrls d
extractResourceUrls :: Document -> [ByteString]
extractResourceUrls doc = getAllTextMatches $ str =~ pattern
where
str :: ByteString
str = encode $ _data doc
pattern :: ByteString
pattern = "(https?://[^\"\\?]+/[^\"/\\?]+[.][^\"/.\\?]+)"
|
dsferruzza/prismic-backup
|
src/Prismic.hs
|
bsd-3-clause
| 3,054
| 0
| 11
| 653
| 896
| 514
| 382
| 77
| 2
|
-- | Inhabited dungeon levels and the operations to query and change them
-- as the game progresses.
module Game.LambdaHack.Common.Level
( -- * Dungeon
Dungeon, dungeonBounds, ascendInBranch, whereTo
-- * The @Level@ type and its components
, ItemFloor, BigActorMap, ProjectileMap, TileMap, SmellMap, Level(..)
-- * Component updates
, updateFloor, updateEmbed, updateBigMap, updateProjMap
, updateTile, updateEntry, updateSmell
-- * Level query
, at
, posToBigLvl, occupiedBigLvl, posToProjsLvl, occupiedProjLvl, posToAidsLvl
, findPosTry, findPosTry2, nearbyPassablePoints, nearbyFreePoints
-- * Misc
, sortEmbeds
#ifdef EXPOSE_INTERNAL
-- * Internal operations
, EntryMap
, assertSparseItems, assertSparseProjectiles
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import Game.LambdaHack.Common.Area
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.Kind
import Game.LambdaHack.Common.Point
import qualified Game.LambdaHack.Common.PointArray as PointArray
import qualified Game.LambdaHack.Common.Tile as Tile
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Common.Types
import Game.LambdaHack.Common.Vector
import Game.LambdaHack.Content.CaveKind (CaveKind)
import qualified Game.LambdaHack.Content.ItemKind as IK
import Game.LambdaHack.Content.PlaceKind
import Game.LambdaHack.Content.RuleKind
import Game.LambdaHack.Content.TileKind (TileKind)
import qualified Game.LambdaHack.Core.Dice as Dice
import Game.LambdaHack.Core.Random
import Game.LambdaHack.Definition.Defs
-- | The complete dungeon is a map from level identifiers to levels.
type Dungeon = EM.EnumMap LevelId Level
dungeonBounds :: Dungeon -> (LevelId, LevelId)
dungeonBounds dungeon
| Just ((s, _), _) <- EM.minViewWithKey dungeon
, Just ((e, _), _) <- EM.maxViewWithKey dungeon
= (s, e)
dungeonBounds dungeon = error $ "empty dungeon" `showFailure` dungeon
-- | Levels in the current branch, one level up (or down) from the current.
ascendInBranch :: Dungeon -> Bool -> LevelId -> [LevelId]
ascendInBranch dungeon up lid =
-- Currently there is just one branch, so the computation is simple.
let (minD, maxD) = dungeonBounds dungeon
ln = max minD $ min maxD $ toEnum $ fromEnum lid + if up then 1 else -1
in case EM.lookup ln dungeon of
Just _ | ln /= lid -> [ln]
_ | ln == lid -> []
_ -> ascendInBranch dungeon up ln -- jump over gaps
-- | Compute the level identifier and stair position on the new level,
-- after a level change.
--
-- We assume there is never a staircase up and down at the same position.
whereTo :: LevelId -- ^ level of the stairs
-> Point -- ^ position of the stairs
-> Bool -- ^ optional forced direction
-> Dungeon -- ^ current game dungeon
-> [(LevelId, Point)] -- ^ possible destinations
whereTo lid pos up dungeon =
let lvl = dungeon EM.! lid
li = case elemIndex pos $ fst $ lstair lvl of
Just ifst -> assert up [ifst]
Nothing -> case elemIndex pos $ snd $ lstair lvl of
Just isnd -> assert (not up) [isnd]
Nothing ->
let forcedPoss = (if up then fst else snd) (lstair lvl)
in [0 .. length forcedPoss - 1] -- for ascending via, e.g., spells
in case ascendInBranch dungeon up lid of
[] -> [] -- spell fizzles
ln : _ -> let lvlDest = dungeon EM.! ln
stairsDest = (if up then snd else fst) (lstair lvlDest)
posAtIndex i = case drop i stairsDest of
[] -> error $ "not enough stairs:" `showFailure` (ln, i + 1)
p : _ -> (ln, p)
in map posAtIndex li
-- | Items located on map tiles.
type ItemFloor = EM.EnumMap Point ItemBag
-- | Big actors located on map tiles.
type BigActorMap = EM.EnumMap Point ActorId
-- | Collections of projectiles located on map tiles.
type ProjectileMap = EM.EnumMap Point [ActorId]
-- | Tile kinds on the map.
type TileMap = PointArray.Array (ContentId TileKind)
-- | Current smell on map tiles.
type SmellMap = EM.EnumMap Point Time
-- | Entries of places on the map.
type EntryMap = EM.EnumMap Point PlaceEntry
-- | A view on single, inhabited dungeon level. "Remembered" fields
-- carry a subset of the info in the client copies of levels.
data Level = Level
{ lkind :: ContentId CaveKind
-- ^ the kind of cave the level is an instance of
, ldepth :: Dice.AbsDepth
-- ^ absolute depth of the level
, lfloor :: ItemFloor -- ^ remembered items lying on the floor
, lembed :: ItemFloor -- ^ remembered items embedded in the tile
, lbig :: BigActorMap
-- ^ seen big (non-projectile) actors at positions
-- on the level;
-- could be recomputed at resume, but small enough
, lproj :: ProjectileMap
-- ^ seen projectiles at positions on the level;
-- could be recomputed at resume
, ltile :: TileMap -- ^ remembered level map
, lentry :: EntryMap -- ^ room entrances on the level
, larea :: Area -- ^ area of the level
, lsmell :: SmellMap -- ^ remembered smells on the level
, lstair :: ([Point], [Point])
-- ^ positions of (up, down) stairs
, lescape :: [Point] -- ^ positions of IK.Escape tiles
, lseen :: Int -- ^ currently remembered clear tiles
, lexpl :: Int -- ^ total number of explorable tiles
, ltime :: Time -- ^ local time on the level (possibly frozen)
, lnight :: Bool -- ^ whether the level is covered in darkness
}
deriving (Show, Eq)
assertSparseItems :: ItemFloor -> ItemFloor
assertSparseItems m =
assert (EM.null (EM.filter EM.null m)
`blame` "null floors found" `swith` m) m
hashConsSingle :: ItemFloor -> ItemFloor
hashConsSingle =
EM.map (EM.map (\case
(1, []) -> quantSingle
kit -> kit))
assertSparseProjectiles :: ProjectileMap -> ProjectileMap
assertSparseProjectiles m =
assert (EM.null (EM.filter null m)
`blame` "null projectile lists found" `swith` m) m
updateFloor :: (ItemFloor -> ItemFloor) -> Level -> Level
{-# INLINE updateFloor #-} -- just in case inliner goes hiwire
updateFloor f lvl = lvl {lfloor = f (lfloor lvl)}
updateEmbed :: (ItemFloor -> ItemFloor) -> Level -> Level
updateEmbed f lvl = lvl {lembed = f (lembed lvl)}
updateBigMap :: (BigActorMap -> BigActorMap) -> Level -> Level
updateBigMap f lvl = lvl {lbig = f (lbig lvl)}
updateProjMap :: (ProjectileMap -> ProjectileMap) -> Level -> Level
{-# INLINE updateProjMap #-}
updateProjMap f lvl = lvl {lproj = f (lproj lvl)}
updateTile :: (TileMap -> TileMap) -> Level -> Level
updateTile f lvl = lvl {ltile = f (ltile lvl)}
updateEntry :: (EntryMap -> EntryMap) -> Level -> Level
updateEntry f lvl = lvl {lentry = f (lentry lvl)}
updateSmell :: (SmellMap -> SmellMap) -> Level -> Level
updateSmell f lvl = lvl {lsmell = f (lsmell lvl)}
-- | Query for tile kinds on the map.
at :: Level -> Point -> ContentId TileKind
{-# INLINE at #-}
at Level{ltile} p = ltile PointArray.! p
posToBigLvl :: Point -> Level -> Maybe ActorId
{-# INLINE posToBigLvl #-}
posToBigLvl pos lvl = EM.lookup pos $ lbig lvl
occupiedBigLvl :: Point -> Level -> Bool
{-# INLINE occupiedBigLvl #-}
occupiedBigLvl pos lvl = pos `EM.member` lbig lvl
posToProjsLvl :: Point -> Level -> [ActorId]
{-# INLINE posToProjsLvl #-}
posToProjsLvl pos lvl = EM.findWithDefault [] pos $ lproj lvl
occupiedProjLvl :: Point -> Level -> Bool
{-# INLINE occupiedProjLvl #-}
occupiedProjLvl pos lvl = pos `EM.member` lproj lvl
posToAidsLvl :: Point -> Level -> [ActorId]
{-# INLINE posToAidsLvl #-}
posToAidsLvl pos lvl = maybeToList (posToBigLvl pos lvl)
++ posToProjsLvl pos lvl
-- | Try to find a random position on the map satisfying
-- conjunction of the mandatory and an optional predicate.
-- If the permitted number of attempts is not enough,
-- try again the same number of times without the next optional predicate,
-- and fall back to trying with only the mandatory predicate.
findPosTry :: Int -- ^ the number of tries
-> Level -- ^ look up in this level
-> (Point -> ContentId TileKind -> Bool) -- ^ mandatory predicate
-> [Point -> ContentId TileKind -> Bool] -- ^ optional predicates
-> Rnd (Maybe Point)
{-# INLINE findPosTry #-}
findPosTry numTries lvl m = findPosTry2 numTries lvl m [] undefined
findPosTry2 :: Int -- ^ the number of tries
-> Level -- ^ look up in this level
-> (Point -> ContentId TileKind -> Bool) -- ^ mandatory predicate
-> [Point -> ContentId TileKind -> Bool] -- ^ optional predicates
-> (Point -> ContentId TileKind -> Bool) -- ^ good to have pred.
-> [Point -> ContentId TileKind -> Bool] -- ^ worst case predicates
-> Rnd (Maybe Point)
{-# INLINE findPosTry2 #-}
findPosTry2 numTries Level{ltile, larea} m0 l g r =
assert (numTries > 0) $
let (Point x0 y0, xspan, yspan) = spanArea larea
accomodate :: Rnd (Maybe Point)
-> (Point -> ContentId TileKind -> Bool)
-> [Point -> ContentId TileKind -> Bool]
-> Rnd (Maybe Point)
{-# INLINE accomodate #-}
accomodate fallback m = go
where
go :: [Point -> ContentId TileKind -> Bool]
-> Rnd (Maybe Point)
go [] = fallback
go (hd : tl) = search numTries
where
search 0 = go tl
search !k = do
pxyRelative <- randomR0 (xspan * yspan - 1)
-- Here we can't use @fromEnum@ and/or work with the @Int@
-- representation, because the span is different than @rWidthMax@.
let Point{..} = punindex xspan pxyRelative
pos = Point (x0 + px) (y0 + py)
tile = ltile PointArray.! pos
if m pos tile && hd pos tile
then return $ Just pos
else search (k - 1)
rAndOnceOnlym0 = r ++ [\_ _ -> True]
in accomodate (accomodate (return Nothing) m0 rAndOnceOnlym0)
-- @pos@ and @tile@ not always needed, so not strict;
-- the function arguments determine that thanks to inlining.
(\pos tile -> m0 pos tile && g pos tile)
l
-- | Generate a list of all passable points on (connected component of)
-- the level in the order of path distance from the starting position (BFS).
-- The starting position needn't be passable and is always included.
nearbyPassablePoints :: COps -> Level -> Point -> [Point]
nearbyPassablePoints cops@COps{corule=RuleContent{rWidthMax, rHeightMax}}
lvl start =
let passable p = Tile.isEasyOpen (coTileSpeedup cops) (lvl `at` p)
-- The error is mostly probably caused by place content creating
-- enclosed spaces in conjunction with map edges. To verify,
-- change the error to @l@ and run with the same seed.
semiRandomWrap l = if null l then error "nearbyPassablePoints: blocked"
else let offset = fromEnum start `mod` length l
in drop offset l ++ take offset l
passableVic p = semiRandomWrap $ filter passable
$ vicinityBounded rWidthMax rHeightMax p
siftSingle :: Point
-> (ES.EnumSet Point, [Point])
-> (ES.EnumSet Point, [Point])
siftSingle current (seen, sameDistance) =
if current `ES.member` seen
then (seen, sameDistance)
else (ES.insert current seen, current : sameDistance)
siftVicinity :: Point
-> (ES.EnumSet Point, [Point])
-> (ES.EnumSet Point, [Point])
siftVicinity current seenAndSameDistance =
let vic = passableVic current
in foldr siftSingle seenAndSameDistance vic
siftNearby :: (ES.EnumSet Point, [Point]) -> [Point]
siftNearby (seen, sameDistance) =
sameDistance
++ case foldr siftVicinity (seen, []) sameDistance of
(_, []) -> []
(seen2, sameDistance2) -> siftNearby (seen2, sameDistance2)
in siftNearby (ES.singleton start, [start])
nearbyFreePoints :: COps -> Level -> (ContentId TileKind -> Bool) -> Point
-> [Point]
nearbyFreePoints cops lvl f start =
let good p = f (lvl `at` p)
&& Tile.isWalkable (coTileSpeedup cops) (lvl `at` p)
&& null (posToAidsLvl p lvl)
in filter good $ nearbyPassablePoints cops lvl start
-- We ignore stray embeds, not mentioned in the tile kind.
-- OTOH, some of those mentioned may be used up and so not in the bag
-- and it's OK.
sortEmbeds :: COps -> ContentId TileKind -> [(IK.ItemKind, (ItemId, ItemQuant))]
-> [(ItemId, ItemQuant)]
sortEmbeds COps{cotile} tk embedKindList =
let grpList = Tile.embeddedItems cotile tk
-- Greater or equal 0 to also cover template UNKNOWN items
-- not yet identified by the client.
f grp (itemKind, _) = fromMaybe (-1) (lookup grp $ IK.ifreq itemKind) >= 0
in map snd $ mapMaybe (\grp -> find (f grp) embedKindList) grpList
instance Binary Level where
put Level{..} = do
put lkind
put ldepth
put (assertSparseItems lfloor)
put (assertSparseItems lembed)
put lbig
put (assertSparseProjectiles lproj)
put ltile
put lentry
put larea
put lsmell
put lstair
put lescape
put lseen
put lexpl
put ltime
put lnight
get = do
lkind <- get
ldepth <- get
lfloor <- hashConsSingle <$> get
lembed <- hashConsSingle <$> get
lbig <- get
lproj <- get
ltile <- get
lentry <- get
larea <- get
lsmell <- get
lstair <- get
lescape <- get
lseen <- get
lexpl <- get
ltime <- get
lnight <- get
return $! Level{..}
|
LambdaHack/LambdaHack
|
engine-src/Game/LambdaHack/Common/Level.hs
|
bsd-3-clause
| 14,422
| 0
| 21
| 4,084
| 3,538
| 1,912
| 1,626
| -1
| -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.