code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Types where data Location = Home | FriendYard | Garden | OtherRoom deriving (Eq, Show, Read) -- Where to go using Walk and Go commands data Direction = North | South | West | East deriving (Eq, Show, Read) -- Player's actions data Action = Look | Go Direction | Inventory | Take | Drop | Investigate Object | Quit | Save | Load | New deriving (Eq, Show, Read) data Object = Table | Umbrella | Drawer | Phone | MailBox | FriendKey deriving (Eq, Show, Read)
dskecse/Adv2Game
Types.hs
gpl-3.0
743
0
6
369
158
95
63
29
0
stmt :: Pair String Bool stmt = P "This statement is" False
hmemcpy/milewski-ctfp-pdf
src/content/1.6/code/haskell/snippet10.hs
gpl-3.0
59
1
5
11
24
10
14
2
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.CloudPrivateCatalogProducer.Catalogs.SetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the IAM policy for the specified Catalog. -- -- /See:/ <https://cloud.google.com/private-catalog/ Cloud Private Catalog Producer API Reference> for @cloudprivatecatalogproducer.catalogs.setIamPolicy@. module Network.Google.Resource.CloudPrivateCatalogProducer.Catalogs.SetIAMPolicy ( -- * REST Resource CatalogsSetIAMPolicyResource -- * Creating a Request , catalogsSetIAMPolicy , CatalogsSetIAMPolicy -- * Request Lenses , csipXgafv , csipUploadProtocol , csipAccessToken , csipUploadType , csipPayload , csipResource , csipCallback ) where import Network.Google.CloudPrivateCatalogProducer.Types import Network.Google.Prelude -- | A resource alias for @cloudprivatecatalogproducer.catalogs.setIamPolicy@ method which the -- 'CatalogsSetIAMPolicy' request conforms to. type CatalogsSetIAMPolicyResource = "v1beta1" :> 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] GoogleIAMV1SetIAMPolicyRequest :> Post '[JSON] GoogleIAMV1Policy -- | Sets the IAM policy for the specified Catalog. -- -- /See:/ 'catalogsSetIAMPolicy' smart constructor. data CatalogsSetIAMPolicy = CatalogsSetIAMPolicy' { _csipXgafv :: !(Maybe Xgafv) , _csipUploadProtocol :: !(Maybe Text) , _csipAccessToken :: !(Maybe Text) , _csipUploadType :: !(Maybe Text) , _csipPayload :: !GoogleIAMV1SetIAMPolicyRequest , _csipResource :: !Text , _csipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CatalogsSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csipXgafv' -- -- * 'csipUploadProtocol' -- -- * 'csipAccessToken' -- -- * 'csipUploadType' -- -- * 'csipPayload' -- -- * 'csipResource' -- -- * 'csipCallback' catalogsSetIAMPolicy :: GoogleIAMV1SetIAMPolicyRequest -- ^ 'csipPayload' -> Text -- ^ 'csipResource' -> CatalogsSetIAMPolicy catalogsSetIAMPolicy pCsipPayload_ pCsipResource_ = CatalogsSetIAMPolicy' { _csipXgafv = Nothing , _csipUploadProtocol = Nothing , _csipAccessToken = Nothing , _csipUploadType = Nothing , _csipPayload = pCsipPayload_ , _csipResource = pCsipResource_ , _csipCallback = Nothing } -- | V1 error format. csipXgafv :: Lens' CatalogsSetIAMPolicy (Maybe Xgafv) csipXgafv = lens _csipXgafv (\ s a -> s{_csipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). csipUploadProtocol :: Lens' CatalogsSetIAMPolicy (Maybe Text) csipUploadProtocol = lens _csipUploadProtocol (\ s a -> s{_csipUploadProtocol = a}) -- | OAuth access token. csipAccessToken :: Lens' CatalogsSetIAMPolicy (Maybe Text) csipAccessToken = lens _csipAccessToken (\ s a -> s{_csipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). csipUploadType :: Lens' CatalogsSetIAMPolicy (Maybe Text) csipUploadType = lens _csipUploadType (\ s a -> s{_csipUploadType = a}) -- | Multipart request metadata. csipPayload :: Lens' CatalogsSetIAMPolicy GoogleIAMV1SetIAMPolicyRequest csipPayload = lens _csipPayload (\ s a -> s{_csipPayload = a}) -- | REQUIRED: The resource for which the policy is being specified. See the -- operation documentation for the appropriate value for this field. csipResource :: Lens' CatalogsSetIAMPolicy Text csipResource = lens _csipResource (\ s a -> s{_csipResource = a}) -- | JSONP csipCallback :: Lens' CatalogsSetIAMPolicy (Maybe Text) csipCallback = lens _csipCallback (\ s a -> s{_csipCallback = a}) instance GoogleRequest CatalogsSetIAMPolicy where type Rs CatalogsSetIAMPolicy = GoogleIAMV1Policy type Scopes CatalogsSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform"] requestClient CatalogsSetIAMPolicy'{..} = go _csipResource _csipXgafv _csipUploadProtocol _csipAccessToken _csipUploadType _csipCallback (Just AltJSON) _csipPayload cloudPrivateCatalogProducerService where go = buildClient (Proxy :: Proxy CatalogsSetIAMPolicyResource) mempty
brendanhay/gogol
gogol-cloudprivatecatalogproducer/gen/Network/Google/Resource/CloudPrivateCatalogProducer/Catalogs/SetIAMPolicy.hs
mpl-2.0
5,397
0
16
1,174
777
453
324
114
1
{-# LANGUAGE TemplateHaskell, TypeFamilies, DeriveDataTypeable, OverloadedStrings, DataKinds #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Model.Metric.Types ( MeasureDatum , MeasureType(..) , Metric(..) , ParticipantFieldMapping2(..) , mkParticipantFieldMapping2 , lookupField ) where import Control.Monad (when) import qualified Data.ByteString as BS import Data.Function (on) import qualified Data.List as L import Data.Map (Map) import qualified Data.Map as Map import Data.Ord (comparing) import qualified Data.Text as T import Data.Text (Text) import Instances.TH.Lift () import Language.Haskell.TH.Lift (deriveLiftMany) import qualified Data.Typeable.Internal import qualified GHC.Arr import qualified Database.PostgreSQL.Typed.Types import qualified Database.PostgreSQL.Typed.Dynamic import qualified Database.PostgreSQL.Typed.Enum import qualified Data.Aeson.Types import qualified Data.ByteString.Char8 -- import Has (Has(..)) import Model.Enum import Model.Kind import Model.Release.Types import Model.Id.Types import Model.Category.Types import qualified HTTP.Form.Deform -- makeDBEnum "data_type" "MeasureType" -- TODO: db coherence data MeasureType = MeasureTypeText | MeasureTypeNumeric | MeasureTypeDate | MeasureTypeVoid deriving (Eq, Ord, Enum, GHC.Arr.Ix, Bounded, Data.Typeable.Internal.Typeable) instance Show MeasureType where show MeasureTypeText = "text" show MeasureTypeNumeric = "numeric" show MeasureTypeDate = "date" show MeasureTypeVoid = "void" instance Database.PostgreSQL.Typed.Types.PGType "data_type" instance Database.PostgreSQL.Typed.Types.PGParameter "data_type" MeasureType where pgEncode _ MeasureTypeText = BS.pack [116, 101, 120, 116] pgEncode _ MeasureTypeNumeric = BS.pack [110, 117, 109, 101, 114, 105, 99] pgEncode _ MeasureTypeDate = BS.pack [100, 97, 116, 101] pgEncode _ MeasureTypeVoid = BS.pack [118, 111, 105, 100] instance Database.PostgreSQL.Typed.Types.PGColumn "data_type" MeasureType where pgDecode _ x_a4zCt = case BS.unpack x_a4zCt of [116, 101, 120, 116] -> MeasureTypeText [110, 117, 109, 101, 114, 105, 99] -> MeasureTypeNumeric [100, 97, 116, 101] -> MeasureTypeDate [118, 111, 105, 100] -> MeasureTypeVoid _ -> error ("pgDecode data_type: " ++ Data.ByteString.Char8.unpack x_a4zCt) instance Database.PostgreSQL.Typed.Dynamic.PGRep "data_type" MeasureType instance Database.PostgreSQL.Typed.Enum.PGEnum MeasureType instance Kinded MeasureType where kindOf _ = "data_type" instance DBEnum MeasureType instance Data.Aeson.Types.ToJSON MeasureType where toJSON = Data.Aeson.Types.toJSON . fromEnum instance Data.Aeson.Types.FromJSON MeasureType where parseJSON = parseJSONEnum instance HTTP.Form.Deform.Deform f_a4zCu MeasureType where deform = enumForm type MeasureDatum = BS.ByteString type instance IdType Metric = Int32 data Metric = Metric { metricId :: !(Id Metric) , metricCategory :: !Category , metricName :: !T.Text , metricRelease :: !(Maybe Release) , metricType :: !MeasureType , metricOptions :: ![MeasureDatum] , metricAssumed :: !(Maybe MeasureDatum) , metricDescription :: !(Maybe T.Text) , metricRequired :: !(Maybe Bool) } deriving (Show) instance Kinded Metric where kindOf _ = "metric" instance Eq Metric where (==) = on (==) metricId (/=) = on (/=) metricId instance Ord Metric where compare = comparing metricId deriveLiftMany [''MeasureType, ''Metric] mkParticipantFieldMapping2 :: [(Metric, Text)] -> Either String ParticipantFieldMapping2 mkParticipantFieldMapping2 metricColumn = do let mpng = Map.fromList metricColumn columns = Map.elems mpng when (length (L.nub columns) /= length columns) (Left "columns mapped to are not unique") -- should we enforce minimum required metrics, such as requiring id? (pure . ParticipantFieldMapping2) mpng lookupField :: Metric -> ParticipantFieldMapping2 -> Maybe Text lookupField m (ParticipantFieldMapping2 mp) = Map.lookup m mp newtype ParticipantFieldMapping2 = ParticipantFieldMapping2 { pfmGetMapping :: Map Metric Text } -- deriving (Eq, Show)
databrary/databrary
src/Model/Metric/Types.hs
agpl-3.0
4,258
0
13
742
1,095
636
459
-1
-1
-------------------------------------------------------------------------- -- -- -- Top.hs -- -- -- -- Top level file in the NFA library. -- -- -- -- (c) Simon Thompson, 1995, 2000 -- -- -- -------------------------------------------------------------------------- module Top where import BuildNfa import ImplementNfa import MinimiseDfa import Sets import NfaLib import NfaToDfa import NfaMisc import NfaTypes import RegExp
SonomaStatist/CS454_NFA
haskellDFA/RegExp/Top.hs
unlicense
476
0
3
101
40
30
10
10
0
{- 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. -} {-# LANGUAGE OverloadedStrings #-} -- | -- Functions an types for working with JWT bearer tokens module CodeWorld.Auth.Token ( AccessToken (..), Issuer (..), RefreshToken (..), accessToken, parseAccessToken, parseRefreshToken, refreshToken, renderAccessToken, renderRefreshToken, ) where import CodeWorld.Account (TokenId (..), UserId (..)) import CodeWorld.Auth.Time import Data.Aeson (Value (..)) import Data.Map (Map) import qualified Data.Map as Map (fromList, lookup) import Data.Text (Text) import qualified Data.Text as Text (pack, unpack) import Data.Time.Clock ( NominalDiffTime, UTCTime, addUTCTime, ) import Text.Read (readMaybe) import Web.JWT ( ClaimsMap (..), JWTClaimsSet (..), Signer (..), StringOrURI, claims, decodeAndVerifySignature, encodeSigned, stringOrURI, stringOrURIToText, unClaimsMap, ) import Prelude hiding (exp) newtype Issuer = Issuer Text deriving (Eq, Show) data TokenType = Access | Refresh deriving (Eq, Show) data AccessToken = AccessToken Issuer UTCTime UTCTime UserId data RefreshToken = RefreshToken Issuer UTCTime UTCTime UserId TokenId -- | Access token expiry period: access tokens vended by local auth -- system (via /signIn, /refreshToken) will expire after this time -- period: clients must then request a new access and refresh token -- using the /refreshToken API. accessTokenExpiryPeriod :: NominalDiffTime accessTokenExpiryPeriod = seconds 60 -- | Refresh token expiry period: refresh tokens expire after this -- time period at which the client is required to reauthenticate the -- user via the /signIn API. This is loosely equivalent to a -- traditional "session expiry period". refreshTokenExpiryPeriod :: NominalDiffTime refreshTokenExpiryPeriod = minutes 60 toStringOrURI :: Issuer -> Maybe StringOrURI toStringOrURI (Issuer issuerRaw) = stringOrURI issuerRaw valueText :: Value -> Maybe Text valueText (String s) = Just s valueText _ = Nothing accessToken :: Issuer -> UTCTime -> UserId -> AccessToken accessToken issuer issuedAt userId = let expiresAt = addUTCTime accessTokenExpiryPeriod issuedAt in AccessToken issuer issuedAt expiresAt userId refreshToken :: Issuer -> UTCTime -> UserId -> TokenId -> RefreshToken refreshToken issuer issuedAt userId tokenId = let expiresAt = addUTCTime refreshTokenExpiryPeriod issuedAt in RefreshToken issuer issuedAt expiresAt userId tokenId renderAccessToken :: Signer -> AccessToken -> Maybe Text renderAccessToken signer (AccessToken issuer issuedAt expiresAt userId) = renderHelper signer issuer issuedAt expiresAt userId $ Map.fromList [("token-type", String "access")] renderRefreshToken :: Signer -> RefreshToken -> Maybe Text renderRefreshToken signer (RefreshToken issuer issuedAt expiresAt userId (TokenId tokenId)) = renderHelper signer issuer issuedAt expiresAt userId $ Map.fromList [("token-type", String "refresh"), ("token-id", String $ (Text.pack . show) tokenId)] renderHelper :: Signer -> Issuer -> UTCTime -> UTCTime -> UserId -> Map Text Value -> Maybe Text renderHelper signer issuer issuedAt expiresAt (UserId userIdRaw) extraClaims = do issuedAtNum <- utcTimeToNumericDate issuedAt expiresAtNum <- utcTimeToNumericDate expiresAt let claimsSet = mempty { iss = toStringOrURI issuer, sub = stringOrURI (Text.pack userIdRaw), exp = Just expiresAtNum, iat = Just issuedAtNum, unregisteredClaims = ClaimsMap extraClaims } return $ encodeSigned signer mempty claimsSet parseAccessToken :: Signer -> Text -> Maybe AccessToken parseAccessToken signer j = do (tokenType, issuer, issuedAt, expiresAt, userId, _) <- parseHelper signer j case tokenType of Access -> Just $ AccessToken issuer issuedAt expiresAt userId _ -> Nothing parseRefreshToken :: Signer -> Text -> Maybe RefreshToken parseRefreshToken signer j = do (tokenType, issuer, issuedAt, expiresAt, userId, extraClaims) <- parseHelper signer j case tokenType of Refresh -> do tokenIdValue <- Map.lookup "token-id" extraClaims tokenIdRaw <- valueText tokenIdValue tokenId <- TokenId <$> readMaybe (Text.unpack tokenIdRaw) Just $ RefreshToken issuer issuedAt expiresAt userId tokenId _ -> Nothing parseHelper :: Signer -> Text -> Maybe (TokenType, Issuer, UTCTime, UTCTime, UserId, Map Text Value) parseHelper signer j = do jwt <- decodeAndVerifySignature signer j let c = claims jwt issuer <- (Issuer . stringOrURIToText) <$> iss c issuedAt <- numericDateToUTCTime <$> iat c expiresAt <- numericDateToUTCTime <$> exp c userId <- (UserId . Text.unpack . stringOrURIToText) <$> sub c let extraClaims = unClaimsMap $ unregisteredClaims c tokenTypeValue <- Map.lookup "token-type" extraClaims tokenTypeRaw <- valueText tokenTypeValue tokenType <- parseTokenType tokenTypeRaw return (tokenType, issuer, issuedAt, expiresAt, userId, extraClaims) where parseTokenType s | s == "access" = Just Access | s == "refresh" = Just Refresh | otherwise = Nothing
google/codeworld
codeworld-auth/src/CodeWorld/Auth/Token.hs
apache-2.0
5,737
0
17
1,068
1,351
713
638
109
2
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} import Data.List import Data.Maybe import Data.Char hypotenuse a b = sqrt(a^2 + b^2) --Conditionals -- identifyCamel humps = if humps == 1 then "Dromeday" else "Bactrian" --Recursive Function -- increasing :: (Ord a) => [a] -> Bool increasing xs = if xs == [] then True else if tail xs == [] then True else if head xs <= head(tail xs) then increasing (tail xs) else False --Pattern matching -- incr[] = True incr[x] = True incr(x:y:ys) = x <= y && incr (y:ys) -- incr _ = True --Pattern Matching -- noVowels :: [Char] -> [Char] noVowels "" = "" noVowels (x:xs) = if x `elem` "aeiouAEIOU" then noVowels xs else x : noVowels xs watch :: Int -> [Char] watch 7 = "7 o'clock and ... SHARKNADO!" watch n = show n ++ " " ++ "o'clock and all's well" addOneToSum y z = let x = 1 in x + y + z --Recursion -- sumRange start end acc = if start > end then acc else sumRange (start + 1) end (acc + start) len :: [a] -> Int len [] = 0 len (_:xs) = 1 + len xs summ :: (Num a) => [a] -> a summ [] = 0 summ (x:xs) = x + summ xs --Functional Composition -- add10 value = value + 10 mult5 value = value * 5 mult5AfterAdd10 value = (mult5 . add10) value quote str = "'" ++ str ++ "'" findKeyError key = "Unable to find " ++ " " ++ (quote key) firstOrEmpty :: [[Char]] -> [Char] firstOrEmpty lst = if not(null lst) then head lst else "empty" --ADT-- Defined by two pieces of data -- -- A name for the type that will be used to represent its value -- A set of constructors that are used to create new values. -- These constructors may have arguments that will hold values of the specified types -- 1) Government organizations which are known by their name -- 2) Companies, for which you need to record its name, an identification number, a contact person -- and its position within the company hierachy -- 3) Individual clients, known by their name, surname and whether they want to receive further information -- about offers and discounts data Client = GovOrg String | Company String Integer Person String | Individual Person Bool deriving Show data Person = Person String String Gender deriving Show data Users = Organization String Integer Person String | User Bool deriving Show data Gender = Male | Female | Unknown deriving Show {-Using Records to define Data types-} data PersonR = PersonR {firstName :: String, lastName :: String} deriving Show data ClientR = GovOrgR {clientRName :: String} | CompanyR {clientRName ::String, companyId :: Integer, person :: PersonR, duty :: String} | IndividualR {person ::PersonR } deriving Show hungai = IndividualR {person = PersonR{lastName = "Hungai", firstName="Kevin"}} kevin = PersonR{firstName = "Hungai", lastName="Kevin"} --Functions using pattern matching greet :: ClientR -> String greet IndividualR {person = PersonR{ firstName = fn }} = "Hi," ++ " " ++ fn greet CompanyR { clientRName = c } = "Hello," ++ " " ++ c greet GovOrgR { } = "Welcome" {- Using named record puns -> # LANGUAGE NamedFieldPuns # -} greet2 IndividualR {person = PersonR {firstName}} = "Hi, " ++ " " ++ firstName greet2 CompanyR { clientRName } = "Hello," ++ " " ++ clientRName greet2 GovOrgR { } = "Welcome" {- Using named record puns with Record Wild Cards -> # LANGUAGE RecordWildCards # -} greet3 IndividualR {person=PersonR{..}} = "Hi," ++ " " ++ firstName greet3 CompanyR {..} = "Hello," ++ " " ++ clientRName greet3 GovOrgR { } = "Welcome" {-nameInCapitals :: PersonR -> PersonR nameInCapitals p@(PersonR{firstName = initial:rest}) = let newName = (toUpper initial):rest in p {firstName = newName} nameInCapitals p@(PersonR{firstName = " "}) = p -} clientName :: Client -> String clientName client = case client of GovOrg name -> name Company name _ _ _ -> name Individual person ads -> case person of Person fName lName gender -> fName ++ " " ++ lName companyName :: Client -> Maybe String companyName client = case client of Company name _ _ _ -> Just name _ -> Nothing fibonnaci :: Integer -> Integer fibonnaci n = case n of 0 -> 0 1 -> 1 _ -> fibonnaci (n-1) + fibonnaci (n-2) sorted [] = True sorted [_] = True sorted (x:r@(y:_)) = x < y && sorted r --Card ADT's data Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Eq,Ord,Bounded,Enum,Show,Read) data Suit = Spades | Hearts | Diamonds | Clubs deriving (Eq,Enum,Show,Read) data Card = Card Rank Suit deriving (Eq,Show,Read) type Hand = Card --Returns True if all consucutive pairs satisfy allPairs f [] = True allPairs f [x] = True allPairs f (x:y:ys) = f x y && allPairs f (y:ys) data ConnType = TCP | UDP data UseProxy = NoProxy | Proxy String data TimeOut = NoTimeOut | TimeOut Integer data ConnOptions = ConnOptions { connType :: ConnType ,connSpeed :: Integer ,connProxy :: UseProxy ,connCaching :: Bool ,connKeepAlive :: Bool ,connTimeOut :: TimeOut }
hungaikev/learning-haskell
Hello.hs
apache-2.0
5,386
4
12
1,420
1,639
875
764
113
4
{-# LANGUAGE DeriveGeneric, StandaloneDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main (main) where import Control.Applicative ((<|>)) import Control.Exception (IOException, catch) import Control.Monad (when) import Data.Foldable (traverse_) import Data.List (foldl') import Data.Traversable (for) import GHC.Generics (Generic) import Prelude () import Prelude.Compat import System.Directory (getDirectoryContents) import System.Exit (exitFailure) import System.FilePath import System.IO import Data.TreeDiff import Data.TreeDiff.Golden import qualified Options.Applicative as O import Documentation.Haddock.Types import qualified Documentation.Haddock.Parser as Parse type Doc id = DocH () id data Fixture = Fixture { fixtureName :: FilePath , fixtureOutput :: FilePath } deriving Show data Result = Result { _resultSuccess :: !Int , _resultTotal :: !Int } deriving Show combineResults :: Result -> Result -> Result combineResults (Result s t) (Result s' t') = Result (s + s') (t + t') readFixtures :: IO [Fixture] readFixtures = do let dir = "fixtures/examples" files <- getDirectoryContents dir let inputs = filter (\fp -> takeExtension fp == ".input") files return $ flip map inputs $ \fp -> Fixture { fixtureName = dir </> fp , fixtureOutput = dir </> fp -<.> "parsed" } goldenFixture :: String -> IO Expr -> IO Expr -> (Expr -> Expr -> IO (Maybe String)) -> (Expr -> IO ()) -> IO Result goldenFixture name expect actual cmp wrt = do putStrLn $ "running " ++ name a <- actual e <- expect `catch` handler a mres <- cmp e a case mres of Nothing -> return (Result 1 1) Just str -> do putStrLn str return (Result 0 1) where handler :: Expr -> IOException -> IO Expr handler a exc = do putStrLn $ "Caught " ++ show exc putStrLn "Accepting the test" wrt a return a runFixtures :: [Fixture] -> IO () runFixtures fixtures = do results <- for fixtures $ \(Fixture i o) -> do let name = takeBaseName i let readDoc = do input <- readFile i return (parseString input) ediffGolden goldenFixture name o readDoc case foldl' combineResults (Result 0 0) results of Result s t -> do putStrLn $ "Fixtures: success " ++ show s ++ "; total " ++ show t when (s /= t) exitFailure listFixtures :: [Fixture] -> IO () listFixtures = traverse_ $ \(Fixture i _) -> do let name = takeBaseName i putStrLn name acceptFixtures :: [Fixture] -> IO () acceptFixtures = traverse_ $ \(Fixture i o) -> do input <- readFile i let doc = parseString input let actual = show (prettyExpr $ toExpr doc) ++ "\n" writeFile o actual parseString :: String -> Doc String parseString = Parse.toRegular . _doc . Parse.parseParas Nothing data Cmd = CmdRun | CmdAccept | CmdList main :: IO () main = do hSetBuffering stdout NoBuffering -- For interleaved output when debugging runCmd =<< O.execParser opts where opts = O.info (O.helper <*> cmdParser) O.fullDesc cmdParser :: O.Parser Cmd cmdParser = cmdRun <|> cmdAccept <|> cmdList <|> pure CmdRun cmdRun = O.flag' CmdRun $ mconcat [ O.long "run" , O.help "Run parser fixtures" ] cmdAccept = O.flag' CmdAccept $ mconcat [ O.long "accept" , O.help "Run & accept parser fixtures" ] cmdList = O.flag' CmdList $ mconcat [ O.long "list" , O.help "List fixtures" ] runCmd :: Cmd -> IO () runCmd CmdRun = readFixtures >>= runFixtures runCmd CmdList = readFixtures >>= listFixtures runCmd CmdAccept = readFixtures >>= acceptFixtures ------------------------------------------------------------------------------- -- Orphans ------------------------------------------------------------------------------- deriving instance Generic (DocH mod id) instance (ToExpr mod, ToExpr id) => ToExpr (DocH mod id) deriving instance Generic (Header id) instance ToExpr id => ToExpr (Header id) deriving instance Generic (Hyperlink id) instance ToExpr id => ToExpr (Hyperlink id) deriving instance Generic (ModLink id) instance ToExpr id => ToExpr (ModLink id) deriving instance Generic Picture instance ToExpr Picture deriving instance Generic Example instance ToExpr Example deriving instance Generic (Table id) instance ToExpr id => ToExpr (Table id) deriving instance Generic (TableRow id) instance ToExpr id => ToExpr (TableRow id) deriving instance Generic (TableCell id) instance ToExpr id => ToExpr (TableCell id)
haskell/haddock
haddock-library/fixtures/Fixtures.hs
bsd-2-clause
4,689
0
19
1,122
1,535
770
765
130
2
module NLP.Tools.Convenience (smap) where smap :: (b -> c) -> (a, b) -> (a, c) smap f (a,b) = (a,f b)
RoboNickBot/nlp-tools
src/NLP/Tools/Convenience.hs
bsd-2-clause
103
0
7
22
69
41
28
3
1
{-# LANGUAGE StandaloneDeriving, TemplateHaskell, FlexibleContexts, DeriveTraversable #-} import Data.StructuralTraversal.Class import Data.StructuralTraversal.Instances import Data.StructuralTraversal.TH import Data.StructuralTraversal.Indexing import Data.Traversable import Control.Applicative import Control.Monad.Writer import Test.HUnit hiding (test) data Name a = Name String deriving (Show, Eq) data Lit a = IntLit Integer deriving (Show, Eq) data Expr a = LitExpr (Lit a) | Variable (Name a) | Neg (Ann Expr a) | Plus (Ann Expr a) (Ann Expr a) deriving (Show, Eq) data Instr a = Assign (Ann Expr a) (Ann Expr a) | Sequence (AnnList Instr a) deriving (Show, Eq) data Decl a = Procedure (Ann Name a) (Ann Instr a) deriving (Show, Eq) data Ann elem annot = Ann annot (elem annot) deriving (Show, Eq) instance StructuralTraversable elem => StructuralTraversable (Ann elem) where traverseUp desc asc f (Ann ann e) = flip Ann <$> (desc *> traverseUp desc asc f e <* asc) <*> f ann traverseDown desc asc f (Ann ann e) = Ann <$> f ann <*> (desc *> traverseDown desc asc f e <* asc) newtype AnnList e a = AnnList { fromAnnList :: [Ann e a] } deriving (Show, Eq) instance StructuralTraversable elem => StructuralTraversable (AnnList elem) where traverseUp desc asc f (AnnList ls) = AnnList <$> sequenceA (map (traverseUp desc asc f) ls) traverseDown desc asc f (AnnList ls) = AnnList <$> sequenceA (map (traverseDown desc asc f) ls) input = Ann () (Procedure (Ann () (Name "program1")) (Ann () (Sequence (AnnList [ Ann () (Assign (Ann () (Variable (Name "a"))) (Ann () (LitExpr (IntLit 1)))) , Ann () (Assign (Ann () (Variable (Name "v"))) (Ann () (Plus (Ann () (Variable (Name "b"))) (Ann () (LitExpr (IntLit 2)))))) ])))) expected = Ann [] (Procedure (Ann [0] (Name "program1")) (Ann [1] (Sequence (AnnList [ Ann [0,1] (Assign (Ann [0,0,1] (Variable (Name "a"))) (Ann [1,0,1] (LitExpr (IntLit 1)))) , Ann [1,1] (Assign (Ann [0,1,1] (Variable (Name "v"))) (Ann [1,1,1] (Plus (Ann [0,1,1,1] (Variable (Name "b"))) (Ann [1,1,1,1] (LitExpr (IntLit 2)))))) ])))) topDownRes :: [[Int]] topDownRes = execWriter $ traverseDown (return ()) (return ()) (tell . (:[])) expected topDownExpected :: [[Int]] topDownExpected = [[],[0],[1],[0,1],[0,0,1],[1,0,1],[1,1],[0,1,1],[1,1,1],[0,1,1,1],[1,1,1,1]] bottomUpRes :: [[Int]] bottomUpRes = execWriter $ traverseUp (return ()) (return ()) (tell . (:[])) expected bottomUpExpected :: [[Int]] bottomUpExpected = [[0],[0,0,1],[1,0,1],[0,1],[0,1,1],[0,1,1,1],[1,1,1,1],[1,1,1],[1,1],[1],[]] deriveStructTrav ''Lit deriveStructTrav ''Expr deriveStructTrav ''Instr deriveStructTrav ''Decl deriveStructTrav ''Name main :: IO () main = do assertEqual "The result of the transformation is not as expected" expected (indexedTraverse (\_ i -> i) input) assertEqual "The result of bottom-up traversal is not as expected" bottomUpExpected bottomUpRes assertEqual "The result of top-down traversal is not as expected" topDownExpected topDownRes
nboldi/structural-traversal
test/Example.hs
bsd-3-clause
3,371
0
27
830
1,544
845
699
62
1
{-# LANGUAGE CPP #-} -- | Paths, host bitness and other environmental information about Haste. module Haste.Environment ( hasteSysDir, jsmodSysDir, hasteInstSysDir, pkgSysDir, pkgSysLibDir, jsDir, hasteUserDir, jsmodUserDir, hasteInstUserDir, pkgUserDir, pkgUserLibDir, hostWordSize, ghcLibDir, ghcBinary, ghcPkgBinary, hasteBinary, hastePkgBinary, hasteInstHisBinary, hasteInstBinary, hasteCopyPkgBinary, closureCompiler, portableHaste) where import System.IO.Unsafe import Data.Bits import Foreign.C.Types (CIntPtr) import Control.Shell import System.Environment (getExecutablePath) import System.Directory (findExecutable) import Paths_haste_compiler import GHC.Paths (libdir) import Config (cProjectVersion) import Data.Maybe (catMaybes) #if defined(PORTABLE) portableHaste :: Bool portableHaste = True -- | Haste system directory. Identical to @hasteUserDir@ unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = joinPath . init . init . splitPath $ unsafePerformIO getExecutablePath ghcLibDir :: FilePath ghcLibDir = unsafePerformIO $ do Right out <- shell $ run ghcBinary ["--print-libdir"] "" return $ init out hasteBinDir :: FilePath hasteBinDir = hasteSysDir </> "bin" jsDir :: FilePath jsDir = hasteSysDir </> "js" #else portableHaste :: Bool portableHaste = False -- | Haste system directory. Identical to @hasteUserDir@ unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = hasteUserDir ghcLibDir :: FilePath ghcLibDir = libdir hasteBinDir :: FilePath hasteBinDir = unsafePerformIO $ getBinDir jsDir :: FilePath jsDir = unsafePerformIO $ getDataDir #endif -- | Haste user directory. Usually ~/.haste. hasteUserDir :: FilePath Right hasteUserDir = unsafePerformIO . shell $ withAppDirectory "haste" return -- | Directory where user .jsmod files are stored. jsmodSysDir :: FilePath jsmodSysDir = hasteSysDir </> "jsmods" -- | Base directory for haste-inst; system packages. hasteInstSysDir :: FilePath hasteInstSysDir = hasteSysDir </> "libraries" -- | Base directory for Haste's system libraries. pkgSysLibDir :: FilePath pkgSysLibDir = hasteInstSysDir </> "lib" -- | Directory housing package information. pkgSysDir :: FilePath pkgSysDir = hasteSysDir </> "packages" -- | Directory where user .jsmod files are stored. jsmodUserDir :: FilePath jsmodUserDir = hasteUserDir </> "jsmods" -- | Base directory for haste-inst. hasteInstUserDir :: FilePath hasteInstUserDir = hasteUserDir </> "libraries" -- | Directory containing library information. pkgUserLibDir :: FilePath pkgUserLibDir = hasteInstUserDir </> "lib" -- | Directory housing package information. pkgUserDir :: FilePath pkgUserDir = hasteUserDir </> "packages" -- | Host word size in bits. hostWordSize :: Int #if __GLASGOW_HASKELL__ >= 708 hostWordSize = finiteBitSize (undefined :: CIntPtr) #else hostWordSize = bitSize (undefined :: CIntPtr) #endif -- | Path to the GHC binary. ghcBinary :: FilePath ghcBinary = unsafePerformIO $ do exes <- catMaybes `fmap` mapM findExecutable ["ghc-" ++ cProjectVersion, "ghc"] case exes of (exe:_) -> return exe _ -> error $ "No appropriate GHC executable in search path!\n" ++ "Are you sure you have GHC " ++ cProjectVersion ++ " installed?" -- | Path to the GHC binary. ghcPkgBinary :: FilePath ghcPkgBinary = unsafePerformIO $ do exes <- catMaybes `fmap` mapM findExecutable ["ghc-pkg-" ++ cProjectVersion, "ghc-pkg"] case exes of (exe:_) -> return exe _ -> error $ "No appropriate ghc-pkg executable in search path!\n" ++ "Are you sure you have GHC " ++ cProjectVersion ++ " installed?" -- | The main Haste compiler binary. hasteBinary :: FilePath hasteBinary = hasteBinDir </> "hastec" -- | Binary for haste-pkg. hastePkgBinary :: FilePath hastePkgBinary = hasteBinDir </> "haste-pkg" -- | Binary for haste-copy-pkg. hasteCopyPkgBinary :: FilePath hasteCopyPkgBinary = hasteBinDir </> "haste-copy-pkg" -- | Binary for haste-pkg. hasteInstBinary :: FilePath hasteInstBinary = hasteBinDir </> "haste-inst" -- | Binary for haste-install-his. hasteInstHisBinary :: FilePath hasteInstHisBinary = hasteBinDir </> "haste-install-his" -- | JAR for Closure compiler. closureCompiler :: FilePath closureCompiler = hasteBinDir </> "compiler.jar"
joelburget/haste-compiler
src/Haste/Environment.hs
bsd-3-clause
4,455
0
14
821
711
411
300
78
2
{-# LANGUAGE OverloadedStrings #-} module Fragment ( readFragment, writeFragment, fragmentUpdateHash, TlsIo, evalTlsIo, liftIO, throwError, readCached, randomByteString, Partner(..), setVersion, setClientRandom, setServerRandom, getClientRandom, getServerRandom, getCipherSuite, cacheCipherSuite, flushCipherSuite, encryptRSA, generateKeys, finishedHash, clientVerifySign, updateSequenceNumberSmart, TlsServer, runOpen, tPut, tGetByte, tGetLine, tGet, tGetContent, tClose, debugPrintKeys, getRandomGen, setRandomGen, SecretKey(..), ) where import Prelude hiding (read) import Control.Applicative import qualified Data.ByteString as BS import TlsIo import Basic readFragment :: TlsIo cnt Fragment readFragment = do (ct, v, ebody) <- (,,) <$> readContentType <*> readVersion <*> readLen 2 body <- decryptBody ct v ebody return $ Fragment ct v body decryptBody :: ContentType -> Version -> BS.ByteString -> TlsIo cnt BS.ByteString decryptBody = decryptMessage Server writeFragment :: Fragment -> TlsIo cnt () writeFragment (Fragment ct v bs) = do cs <- isCiphered Client if cs then do eb <- encryptBody ct v bs writeContentType ct >> writeVersion v >> writeLen 2 eb else writeContentType ct >> writeVersion v >> writeLen 2 bs encryptBody :: ContentType -> Version -> BS.ByteString -> TlsIo cnt BS.ByteString encryptBody ct v body = do ret <- encryptMessage Client ct v body updateSequenceNumber Client return ret fragmentUpdateHash :: Fragment -> TlsIo cnt () fragmentUpdateHash (Fragment ContentTypeHandshake _ b) = updateHash b fragmentUpdateHash _ = return ()
YoshikuniJujo/forest
subprojects/tls-analysis/client/Fragment.hs
bsd-3-clause
1,602
26
12
243
513
274
239
41
2
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType17 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get import Protocol.ROC.Float import Protocol.ROC.Utils data PointType17 = PointType17 { pointType17PointTag :: !PointType17PointTag ,pointType17IntFlag :: !PointType17IntFlag ,pointType17Data1 :: !PointType17Data1 ,pointType17Data2 :: !PointType17Data2 ,pointType17Data3 :: !PointType17Data3 ,pointType17Data4 :: !PointType17Data4 ,pointType17Data5 :: !PointType17Data5 ,pointType17Data6 :: !PointType17Data6 ,pointType17Data7 :: !PointType17Data7 ,pointType17Data8 :: !PointType17Data8 ,pointType17Data9 :: !PointType17Data9 ,pointType17Data10 :: !PointType17Data10 ,pointType17Data11 :: !PointType17Data11 ,pointType17Data12 :: !PointType17Data12 ,pointType17Data13 :: !PointType17Data13 ,pointType17Data14 :: !PointType17Data14 ,pointType17Data15 :: !PointType17Data15 ,pointType17Data16 :: !PointType17Data16 ,pointType17Data17 :: !PointType17Data17 ,pointType17Data18 :: !PointType17Data18 ,pointType17Data19 :: !PointType17Data19 ,pointType17Data20 :: !PointType17Data20 ,pointType17EnableSoftPntLog :: !PointType17EnableSoftPntLog } deriving (Read,Eq, Show, Generic) type PointType17PointTag = BS.ByteString type PointType17IntFlag = Word16 type PointType17Data1 = Float type PointType17Data2 = Float type PointType17Data3 = Float type PointType17Data4 = Float type PointType17Data5 = Float type PointType17Data6 = Float type PointType17Data7 = Float type PointType17Data8 = Float type PointType17Data9 = Float type PointType17Data10 = Float type PointType17Data11 = Float type PointType17Data12 = Float type PointType17Data13 = Float type PointType17Data14 = Float type PointType17Data15 = Float type PointType17Data16 = Float type PointType17Data17 = Float type PointType17Data18 = Float type PointType17Data19 = Float type PointType17Data20 = Float type PointType17EnableSoftPntLog = Bool pointType17Parser :: Get PointType17 pointType17Parser = do pointTag <- getByteString 10 intFlag <- getWord16le data1 <- getIeeeFloat32 data2 <- getIeeeFloat32 data3 <- getIeeeFloat32 data4 <- getIeeeFloat32 data5 <- getIeeeFloat32 data6 <- getIeeeFloat32 data7 <- getIeeeFloat32 data8 <- getIeeeFloat32 data9 <- getIeeeFloat32 data10 <- getIeeeFloat32 data11 <- getIeeeFloat32 data12 <- getIeeeFloat32 data13 <- getIeeeFloat32 data14 <- getIeeeFloat32 data15 <- getIeeeFloat32 data16 <- getIeeeFloat32 data17 <- getIeeeFloat32 data18 <- getIeeeFloat32 data19 <- getIeeeFloat32 data20 <- getIeeeFloat32 enableSoftPntLog <- anyButNull return $ PointType17 pointTag intFlag data1 data2 data3 data4 data5 data6 data7 data8 data9 data10 data11 data12 data13 data14 data15 data16 data17 data18 data19 data20 enableSoftPntLog
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType17.hs
bsd-3-clause
3,881
0
9
1,236
610
337
273
130
1
module Metrics.RegexTiming(timingRegex2) where import Metrics.Common import qualified Data.ByteString.Lazy.Char8 as B import Text.Regex.Base.RegexLike (matchAllText, MatchText) import Text.Regex.PCRE.ByteString.Lazy import qualified Data.Map as M import Data.Array as A import Data.List (groupBy) import Data.Function (on) import Data.Attoparsec.ByteString.Lazy import Data.Attoparsec.ByteString.Char8 (double) import qualified Data.Sequence as S select :: Ix i => [i] -> Array i a -> [a] select [] _ = [] select (x:xs) arr = arr A.! x : select xs arr match :: Regex -> B.ByteString -> [MatchText B.ByteString] match = {-# SCC "matchAllText" #-} matchAllText parseDouble :: B.ByteString -> Double parseDouble input = {-# SCC "parseDouble" #-} case parse double input of Done _ r -> r Fail _ _ _ -> 0 duration :: Int -> [MatchText B.ByteString] -> [Double] duration durationGroup matches = {-# SCC "duration" #-} map (parseDouble . fst . (A.! durationGroup)) matches name :: [Int] -> [MatchText B.ByteString] -> [B.ByteString] name nameSuffixes matches = {-# SCC "name" #-} map (B.intercalate (B.pack ".") . map fst . select nameSuffixes) matches pair :: ([b] -> t) -> [(a, b)] -> (a, t) pair _ [] = error "Internal error in timingRegex: pair applied to empty list" pair state durs@((name,_):_) = {-# SCC "pair" #-} (name, state (map snd durs)) durationByName :: [b] -> [B.ByteString] -> [[(B.ByteString, b)]] durationByName durations names = {-# SCC "byname" #-} case durations of [] -> [] _ -> case names of [] -> [zip (repeat B.empty) durations] _ -> groupBy ((==) `on` fst) (zip names durations) timingRegex2 :: Regex -> String -> Int -> [Int] -> B.ByteString -> MetricState timingRegex2 regex nameString durationGroup nameSuffixes input = Timings2 $ M.fromList $ map buildName states where buildName ~(suffix, metricStates) = (metricName, metricStates) where metricName | B.null suffix = nameString ++ "." ++ B.unpack suffix | otherwise = nameString matches = match regex input durations = duration durationGroup matches names = name nameSuffixes matches durationsByName = durationByName durations names states = map (\(k,v) -> (k, S.fromList v)) (map (pair id) durationsByName)
zsol/hlogster
Metrics/RegexTiming.hs
bsd-3-clause
2,336
0
15
478
836
458
378
45
3
module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Async import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Conduit (Sink, Conduit, Source, await, awaitForever, yield) import Data.Conduit.Async import qualified Data.Conduit.Combinators as DCC import Data.Conduit.Filesystem import Data.List import Data.Time.Clock import Foreign.Marshal.Alloc import System.Directory import System.Environment (getArgs) import System.FilePath import System.IO import System.Posix.Files bufSize :: Int bufSize = 464 readContents :: FilePath -> IO () readContents path = allocaBytes bufSize $ \buf -> withFile path ReadMode $ \h -> do hSetBinaryMode h True hSetBuffering h $ BlockBuffering $ Just bufSize _ <- hGetBuf h buf bufSize return () sink :: Sink FilePath IO () sink = awaitForever $ \path -> liftIO $ forkIO $ readContents path mark :: Int mark = 100 timer :: Int -> UTCTime -> Conduit FilePath IO FilePath timer total time = do x' <- await case x' of Just x -> do yield x if total `mod` mark == 0 then do newtime <- liftIO getCurrentTime let diff = diffUTCTime newtime time rate = truncate $ fromIntegral mark / diff :: Integer liftIO $ putStrLn $ show total ++ " total, " ++ show rate ++ " per second" timer (total + 1) newtime else timer (total + 1) time Nothing -> return () source :: FilePath -> Source IO FilePath source path = do contents <- liftIO $ map (path </>) . filter (not . isPrefixOf ".") <$> getDirectoryContents path statted <- liftIO $ zip contents <$> mapConcurrently getFileStatus contents let (dirs', files') = partition (isDirectory . snd) statted dirs = map fst dirs' files = map fst files' DCC.yieldMany files mapM_ source dirs crawl :: FilePath -> IO () crawl path = do --let source = sourceDirectoryDeep False path time <- getCurrentTime source path =$=& timer 1 time $$& sink main :: IO () main = do args <- getArgs case args of [path] -> crawl path _ -> crawl "." return ()
sweeks-imvu/bullshit
src/Main.hs
bsd-3-clause
2,126
0
20
491
730
370
360
65
3
{-# LANGUAGE CPP, NoImplicitPrelude, FlexibleContexts #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Safe #-} #endif ------------------------------------------------------------------------------- -- | -- Module : System.Timeout.Lifted -- Copyright : (c) The University of Glasgow 2007 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- Attach a timeout event to monadic computations -- which are instances of 'MonadBaseControl'. -- ------------------------------------------------------------------------------- module System.Timeout.Lifted ( timeout ) where -- from base: import Prelude ( (.) ) import Data.Int ( Int ) import Data.Maybe ( Maybe(Nothing, Just), maybe ) import Control.Monad ( (>>=), return, liftM ) import System.IO ( IO ) import qualified System.Timeout as T ( timeout ) -- from monad-control: import Control.Monad.Trans.Control ( MonadBaseControl, restoreM, liftBaseWith ) #include "inlinable.h" -- | Generalized version of 'T.timeout'. -- -- Note that when the given computation times out any side effects of @m@ are -- discarded. When the computation completes within the given time the -- side-effects are restored on return. timeout :: MonadBaseControl IO m => Int -> m a -> m (Maybe a) timeout t m = liftBaseWith (\runInIO -> T.timeout t (runInIO m)) >>= maybe (return Nothing) (liftM Just . restoreM) {-# INLINABLE timeout #-}
basvandijk/lifted-base
System/Timeout/Lifted.hs
bsd-3-clause
1,610
0
11
344
230
145
85
12
1
{-# LANGUAGE ConstraintKinds, FlexibleContexts, RankNTypes, OverloadedStrings #-} {-# LANGUAGE UndecidableInstances, ScopedTypeVariables, AllowAmbiguousTypes #-} ----------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- | -- | Module : All functions used to find score -- | Author : Xiao Ling -- | Date : 8/17/2016 -- | --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- module Score ( count -- * todo: this function is easily abused , countp , w1 , w2 , s1 , s2 , p1 , p2 ) where import Control.Monad.State import Control.Monad.Trans.Reader import Data.Conduit import Data.Text (Text, unpack, pack) import Data.Attoparsec.Text hiding (count) import Lib import Core import Query {----------------------------------------------------------------------------- Score ------------------------------------------------------------------------------} w1 :: String -> String -> ReaderT Config IO Output w1 a1 a2 = do p_ws <- pattern weakStrong sumCount $ (\p -> p (S a1) (S a2)) <$> p_ws s1 :: String -> String -> ReaderT Config IO Output s1 a1 a2 = do p_sw <- pattern strongWeak sumCount $ (\p -> p (S a1) (S a2)) <$> p_sw w2 :: String -> String -> ReaderT Config IO Output w2 = flip w1 s2 :: String -> String -> ReaderT Config IO Output s2 = flip s1 p1 :: ReaderT Config IO Output p1 = do p_ws <- pattern weakStrong sumCount $ (\p -> p Star Star) <$> p_ws p2 :: ReaderT Config IO Output p2 = do p_sw <- pattern strongWeak sumCount $ (\p -> p Star Star) <$> p_sw {----------------------------------------------------------------------------- Count ------------------------------------------------------------------------------} -- * sum the results of multiple `count`s -- * and sum their counts, list all results sumCount :: [Parser Text] -> ReaderT Config IO Output sumCount ps = do rrs <- mapM countp ps let ns = fst <$> rrs let rs = snd <$> rrs return (sum ns, concat rs) -- * `count` for occurences of some phrase among ngram files countp :: Parser Text -> ReaderT Config IO Output countp phrase = do con <- ask (n, ts) <- phrase `query` (ngrams con) return (n,ts) -- * `count` occurences of some word `w` -- * in onegram file count :: String -> ReaderT Config IO Output count w = do let word = compile' w con <- ask (n, ts) <- word `query` [onegram con] return (n,ts)
lingxiao/GoodGreatIntensity
src/Score.hs
bsd-3-clause
2,707
0
13
503
651
343
308
56
1
module Graphics where import Prelude import FPPrac.Graphics import System.FilePath (splitPath, dropExtension) data Thickness = Thin | Thick deriving (Eq,Show) alphabet = ['a'..'z'] type Node = (Char,Color,Point) type Edge = (Char,Char,Color,Int) data Graph = Graph { name :: String , directed :: Bool , weighted :: Bool , nodes :: [Node] , edges :: [Edge] } deriving (Eq,Show) data EdgeDrawingData = EdgeDrawingData { edgeStartpunt :: Point -- | (tx,ty): startpunt van edge , edgeEndpunt :: Point -- | (px,py): eindpunt van edge , innerPijlpunt :: Point -- | (qx,qy): binnenhoek van pijlpunt , achterPijlpunt :: Point -- | (sx,sy): achterpunten van pijlpunt , breedtePijlpunt :: Point -- | (wx,wy): breedte pijlputn , edgeDikte :: Point -- | (dx,dy): dikte van de edge , weightAfstand :: Point -- | (ax,ay): afstand gewicht tot pijlpunt , weightMidden :: Point -- | (mx,my): midden van edge } edgeWidthThin = 1 edgeWidthThick = 1.5 nodeRadius = 15 weightDistance = 6 arrowHeight = 20 arrowDepth = 9 arrowWidth = 9 lblBoxW = 20 lblBoxH = 19 lblHshift = 8 lblVshift = -6 bottomLineHeight = 25 bottomTextHeight = 10 allEdgeDrawingData thickness graph (lbl1,lbl2,col,wght) = EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge , weightAfstand = (ax,ay) -- afstand gewicht tot pijlpunt , weightMidden = (mx,my) -- midden van edge } where Graph {directed=directed,nodes=nodes} = graph (x1,y1) = head [ (x,y) | (lbl,_,(x,y)) <- nodes, lbl==lbl1 ] (x2,y2) = head [ (x,y) | (lbl,_,(x,y)) <- nodes, lbl==lbl2 ] rico = (y2-y1) / (x2-x1) alpha | x2 > x1 = atan rico | x2 == x1 && y2 > y1 = pi/2 | x2 < x1 = pi + atan rico | x2 == x1 && y2 <= y1 = 3*pi/2 sina = sin alpha cosa = cos alpha (xr1,yr1) = (nodeRadius * cosa , nodeRadius * sina) (tx ,ty ) = (x1+xr1,y1+yr1) -- start of edge (px ,py ) = (x2-xr1,y2-yr1) -- outer arrow point (xr2,yr2) = (arrowDepth * cosa , arrowDepth * sina) (qx,qy) = (px-xr2,py-yr2) -- inner arrow point (xh ,yh ) = (arrowHeight * cosa , arrowHeight * sina) (sx ,sy ) = (px-xh,py-yh) -- back arrowpoints (wx ,wy ) = (arrowWidth * sina , arrowWidth * cosa) -- width of arrowpoint (dx ,dy ) | thickness == Thick = (edgeWidthThick * sina , edgeWidthThick * cosa) | otherwise = (edgeWidthThin * sina , edgeWidthThin * cosa) -- edge thickness (xwd,ywd) = (weightDistance * cosa , weightDistance * sina) (ax ,ay ) = (px-xwd,py-ywd) -- distance of weight from arrowpoint (mx ,my ) = ((x2+x1)/2,(y2+y1)/2) -- mid of (undirected) edge drawNode :: Node -> Picture drawNode (lbl,col,(x,y)) = Pictures [ Translate x y $ Color col $ circleSolid r , Translate x y $ Color black $ Circle r , Translate (x-lblHshift) (y+lblVshift) $ Color black $ Scale 0.15 0.15 $ Text [lbl] ] where r = nodeRadius drawEdgeTemp :: Color -> (Point,Point) -> Picture drawEdgeTemp col (p1,p2) = Color col $ Line [p1,p2] drawEdge :: Graph -> Edge -> Picture drawEdge graph edge | directed = Pictures [ Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (tx+dx,ty-dy) ] , Color white $ Polygon [ (px+dx,py-dy), (px-dx,py+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (px+dx,py-dy) ] , Color col $ Polygon [ (px,py), (sx-wx,sy+wy), (qx,qy), (sx+wx,sy-wy), (px,py) ] ] | otherwise = Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (px-dx,py+dy), (px+dx,py-dy), (tx+dx,ty-dy) ] where Graph {directed=directed} = graph (_,_,col,_) = edge EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge } = allEdgeDrawingData Thin graph edge drawThickEdge :: Graph -> Edge -> Picture drawThickEdge graph edge | directed = Pictures [ Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (tx+dx,ty-dy) ] , Color white $ Polygon [ (px+dx,py-dy), (px-dx,py+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (px+dx,py-dy) ] , Color col $ Polygon [ (px,py), (sx-wx,sy+wy), (qx,qy), (sx+wx,sy-wy), (px,py) ] ] | otherwise = Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (px-dx,py+dy), (px+dx,py-dy), (tx+dx,ty-dy) ] where Graph {directed=directed} = graph (_,_,col,_) = edge EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge } = allEdgeDrawingData Thick graph edge drawWeight :: Graph -> Edge -> Picture drawWeight graph edge | not weighted = Blank | directed = Pictures [ Translate ax ay $ Color white $ rectangleSolid lblBoxW lblBoxH , Translate (ax-lblHshift) (ay+lblVshift) $ Color black $ Scale 0.11 0.11 $ Text (show wght) ] | otherwise = Pictures [ Translate mx my $ Color white $ rectangleSolid lblBoxW lblBoxH , Translate (mx-lblHshift) (my+lblVshift) $ Color black $ Scale 0.11 0.11 $ Text (show wght) ] where Graph {directed=directed,weighted=weighted}=graph (_,_,_,wght) = edge EdgeDrawingData { weightAfstand = (ax,ay) -- afstand gewicht tot pijlpunt , weightMidden = (mx,my) -- midden van edge } = allEdgeDrawingData Thin graph edge drawGraph :: Graph -> Picture drawGraph graph = Pictures $ Color white (rectangleSolid 800 564) : (map drawNode nodes) ++ (map (drawEdge graph) edges) ++ (map (drawWeight graph) edges) where Graph {name=name,nodes=nodes,edges=edges}=graph drawBottomLine :: Graph -> Picture drawBottomLine graph = Pictures [ Translate 0 (-300 + bottomLineHeight / 2) $ Color white $ rectangleSolid 800 bottomLineHeight , Color black $ Line [(-400,height1),(400,height1)] , Color black $ Line [(-240,height1),(-240,-300)] , Color black $ Line [(100,height1),(100,-300)] , Translate (-392) height2 $ Color black $ Scale 0.11 0.11 $ Text "create:" , Translate (-332) height2 $ Color red $ Scale 0.11 0.11 $ Text $ (case (name graph) of "" -> "" ; xs -> dropExtension $ last $ splitPath xs) , Translate (-235) height2 $ Color black $ Scale 0.11 0.11 $ Text "click: node; drag: edge; double: remove node" , Translate 120 height2 $ Color black $ Scale 0.11 0.11 $ Text "[n]ew; [r]ead; [s]ave; save [a]s; prac[6]" ] where height1 = -300 + bottomLineHeight height2 = -300 + bottomTextHeight
christiaanb/fpprac
examples/Graphics.hs
bsd-3-clause
8,201
0
13
2,677
3,054
1,721
1,333
155
2
module Logging ( logInfo , logDebug , logError ) where import Control.Monad ( when ) import Data.Monoid ( (<>) ) import Data.Time import Lens.Simple ( (^.) ) import qualified Configuration as C getTime :: IO String getTime = formatTime defaultTimeLocale "%F %H:%M:%6Q" <$> getCurrentTime logInfo :: String -> IO () logInfo message = do t <- getTime putStrLn $ t <> " INFO: " <> message logDebug :: C.ImprovizConfig -> String -> IO () logDebug config message = when (config ^. C.debug) $ do t <- getTime putStrLn $ t <> " DEBUG: " <> message logError :: String -> IO () logError message = do t <- getTime putStrLn $ t <> " ERROR: " <> message
rumblesan/proviz
src/Logging.hs
bsd-3-clause
780
0
10
256
238
126
112
23
1
module Sex ( Sex (..) ) where data Sex = M | F deriving (Eq, Show, Ord)
satai/FrozenBeagle
Simulation/Lib/src/Sex.hs
bsd-3-clause
81
0
6
26
38
23
15
3
0
{-# LANGUAGE TypeSynonymInstances #-} -- -- IO.hs -- -- Basic input and output of expressions. -- -- Gregory Wright, 22 April 2011 -- module Math.Symbolic.Wheeler.IO where import Control.Monad.Identity import Text.Parsec import Text.Parsec.Expr as Ex import Text.Parsec.Language import Text.Parsec.String import qualified Text.Parsec.Token as P import Math.Symbolic.Wheeler.Canonicalize --import Math.Symbolic.Wheeler.CanonicalizeDebug import Math.Symbolic.Wheeler.Function import {-# SOURCE #-} Math.Symbolic.Wheeler.Expr import Math.Symbolic.Wheeler.Numeric import Math.Symbolic.Wheeler.Symbol -- -- Read an expression from a string. -- -- Parse an expression. Formerly, certain transformations -- that put subexpressions into canonical form -- were done on the fly. This is no longer the case. The -- string is converted to an unsimplified expression, and -- you must invoke the "canonicalize" function explicitly. readExpr :: String -> Expr readExpr = canonicalize . runLex wheelerDef :: P.LanguageDef st wheelerDef = P.LanguageDef { P.commentStart = "{-" , P.commentEnd = "-}" , P.commentLine = "--" , P.nestedComments = True , P.identStart = letter <|> char '\\' , P.identLetter = letter <|> char '\'' , P.opStart = P.opLetter emptyDef , P.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" , P.reservedOpNames= [] , P.reservedNames = [] , P.caseSensitive = True } lexer :: P.TokenParser () lexer = P.makeTokenParser (wheelerDef { P.reservedOpNames = ["^", "*", "/", "+", "-", "!", "**", "sqrt"] }) whiteSpace :: Parser () whiteSpace = P.whiteSpace lexer lexeme :: Parser a -> Parser a lexeme = P.lexeme lexer symbol :: String -> Parser String symbol = P.symbol lexer integer :: Parser Integer integer = P.integer lexer natural :: Parser Integer natural = P.natural lexer float :: Parser Double float = P.float lexer parens :: Parser a -> Parser a parens = P.parens lexer semi :: Parser String semi = P.semi lexer identifier :: Parser String identifier = P.identifier lexer reserved :: String -> Parser () reserved = P.reserved lexer reservedOp :: String -> Parser () reservedOp = P.reservedOp lexer commaList :: Parser a -> Parser [ a ] commaList = P.commaSep lexer expr :: Parser Expr expr = buildExpressionParser table factor <?> "expression" table :: [[ Operator String () Identity Expr ]] table = [[ inOp "**" (**) AssocRight] ,[ preOp "-" negate, preOp "+" id, preOp "sqrt" sqrt ] ,[ inOp "*" (*) AssocLeft, inOp "/" (/) AssocLeft ] ,[ inOp "+" (+) AssocLeft, inOp "-" (-) AssocLeft ] ] where preOp s f = Ex.Prefix (do { reservedOp s; return f } <?> "prefix operator") inOp s f assoc = Ex.Infix (do { reservedOp s; return f } <?> "infix operator") assoc factor :: Parser Expr factor = try application <|> parens expr <|> numericConst <|> do { x <- identifier; return (Symbol (simpleSymbol x)) } <?> "simple expresion" application :: Parser Expr application = do { f <- reservedFunction ; whiteSpace ; arg <- expr ; return (Applic f arg) } -- Note that the order is important. Function names that are -- prefixes of the other function names must be listed later. reservedFunction :: Parser Function reservedFunction = do { _ <- try $ string "asinh"; return Asinh } <|> do { _ <- try $ string "acosh"; return Acosh } <|> do { _ <- try $ string "atanh"; return Atanh } <|> do { _ <- try $ string "asin"; return Asin } <|> do { _ <- try $ string "acos"; return Acos } <|> do { _ <- try $ string "atan"; return Atan } <|> do { _ <- try $ string "sinh"; return Sinh } <|> do { _ <- try $ string "cosh"; return Cosh } <|> do { _ <- try $ string "tanh"; return Tanh } <|> do { _ <- try $ string "sin"; return Sin } <|> do { _ <- try $ string "cos"; return Cos } <|> do { _ <- try $ string "tan"; return Tan } <|> do { _ <- try $ string "abs"; return Abs } <|> do { _ <- try $ string "signum"; return Signum } <|> do { _ <- try $ string "log"; return Log } <|> do { _ <- try $ string "exp"; return Exp } numericConst :: Parser Expr numericConst = do { x <- integer; return (Const (I x)) } runLex :: String -> Expr runLex input = let result = parse ( do { whiteSpace ; x <- expr ; eof ; return x }) "" input in case result of Right ex -> ex Left err -> error (show err)
gwright83/Wheeler
src/Math/Symbolic/Wheeler/IO.hs
bsd-3-clause
5,099
0
24
1,669
1,483
783
700
106
2
{-# LANGUAGE QuasiQuotes #-} module Main where import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Instances import Data.Aeson as A import qualified Data.Text as T import qualified Data.Bson as B import Text.RawString.QQ import Data.Maybe import Data.Either import Transfuser.Lib import Transfuser.Types import Transfuser.Types.Arbitrary import Transfuser.Sql.Encoder main :: IO () main = hspec $ do describe "MongoDB JSON query language" $ do -- General parsing it "Any query expression will encode to SQL AST" $ property $ \expr -> isRight $ findToSqlText expr it "Any find expression will encode to SQL" $ property $ \expr -> isRight $ queryToSQL expr -- Specific examples it "Example query 1 parses" $ do isJust (decode eg1 :: Maybe QueryExpr) `shouldBe` True it "Example find expression 1 parses" $ do isJust (decode eg2 :: Maybe FindExpr) `shouldBe` True -- Single expression decoding it "encodes default equality" $ property $ \a b -> fromJSON (object [ a .= b ]) == A.Success (ExprConstr $ OpEQ a (B.String b)) it "encodes equality with $eq" $ property $ \a b -> fromJSON (object [ a .= object [ "$eq" .= b ] ]) == A.Success (ExprConstr $ OpEQ a (B.String b)) it "encodes logical and" $ property $ \a b c d -> fromJSON (object [ "$and" .= [object [a .= b], object [c .= d]] ]) == A.Success (ExprAND [ ExprConstr $ OpEQ a (B.String b) , ExprConstr $ OpEQ c (B.String d) ]) ------------------------------------------------------------------------------ eg1 = [r|{"$and": [ {"tracking_id.asic_id": "AAAA"}, {"membrane_summary": {"$exists": true}}, {"$or": [ {"context_tags": {"$exists": false}}, {"$and": [ {"context_tags.department": "qc"}, {"context_tags.experiment_type": "full_pore_insertion"} ]} ]} ]} |] eg2 = [r| { "collection": "col1", "projection": {"a": 1, "b": 1, "c": 1}, "query": {"$or": [ {"context_tags": {"$exists": false}}, {"$and": [ {"context_tags.department": "qc"}, {"context_tags.experiment_type": "full_pore_insertion"} ]} ]} } |]
stephenpascoe/mongo-sql
test/Spec.hs
bsd-3-clause
2,384
0
22
700
517
273
244
37
1
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE ExistentialQuantification #-} module Network.TLS.Crypto ( HashContext , HashCtx , hashInit , hashUpdate , hashUpdateSSL , hashFinal , module Network.TLS.Crypto.DH , module Network.TLS.Crypto.ECDH -- * Hash , hash , Hash(..) , hashName , hashDigestSize , hashBlockSize -- * key exchange generic interface , PubKey(..) , PrivKey(..) , PublicKey , PrivateKey , kxEncrypt , kxDecrypt , kxSign , kxVerify , KxError(..) ) where import qualified Crypto.Hash as H import qualified Data.ByteString as B import qualified Data.ByteArray as B (convert) import Data.ByteString (ByteString) import Crypto.Random import qualified Crypto.PubKey.DSA as DSA import qualified Crypto.PubKey.RSA as RSA import qualified Crypto.PubKey.RSA.PKCS15 as RSA import Data.X509 (PrivKey(..), PubKey(..)) import Network.TLS.Crypto.DH import Network.TLS.Crypto.ECDH import Data.ASN1.Types import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding (DER(..), BER(..)) {-# DEPRECATED PublicKey "use PubKey" #-} type PublicKey = PubKey {-# DEPRECATED PrivateKey "use PrivKey" #-} type PrivateKey = PrivKey data KxError = RSAError RSA.Error | KxUnsupported deriving (Show) -- functions to use the hidden class. hashInit :: Hash -> HashContext hashInit MD5 = HashContext $ ContextSimple (H.hashInit :: H.Context H.MD5) hashInit SHA1 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA1) hashInit SHA224 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA224) hashInit SHA256 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA256) hashInit SHA384 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA384) hashInit SHA512 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA512) hashInit SHA1_MD5 = HashContextSSL H.hashInit H.hashInit hashUpdate :: HashContext -> B.ByteString -> HashCtx hashUpdate (HashContext (ContextSimple h)) b = HashContext $ ContextSimple (H.hashUpdate h b) hashUpdate (HashContextSSL sha1Ctx md5Ctx) b = HashContextSSL (H.hashUpdate sha1Ctx b) (H.hashUpdate md5Ctx b) hashUpdateSSL :: HashCtx -> (B.ByteString,B.ByteString) -- ^ (for the md5 context, for the sha1 context) -> HashCtx hashUpdateSSL (HashContext _) _ = error "internal error: update SSL without a SSL Context" hashUpdateSSL (HashContextSSL sha1Ctx md5Ctx) (b1,b2) = HashContextSSL (H.hashUpdate sha1Ctx b2) (H.hashUpdate md5Ctx b1) hashFinal :: HashCtx -> B.ByteString hashFinal (HashContext (ContextSimple h)) = B.convert $ H.hashFinalize h hashFinal (HashContextSSL sha1Ctx md5Ctx) = B.concat [B.convert (H.hashFinalize md5Ctx), B.convert (H.hashFinalize sha1Ctx)] data Hash = MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 | SHA1_MD5 deriving (Show,Eq) data HashContext = HashContext ContextSimple | HashContextSSL (H.Context H.SHA1) (H.Context H.MD5) instance Show HashContext where show _ = "hash-context" data ContextSimple = forall alg . H.HashAlgorithm alg => ContextSimple (H.Context alg) type HashCtx = HashContext hash :: Hash -> B.ByteString -> B.ByteString hash MD5 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.MD5) $ b hash SHA1 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA1) $ b hash SHA224 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA224) $ b hash SHA256 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA256) $ b hash SHA384 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA384) $ b hash SHA512 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA512) $ b hash SHA1_MD5 b = B.concat [B.convert (md5Hash b), B.convert (sha1Hash b)] where sha1Hash :: B.ByteString -> H.Digest H.SHA1 sha1Hash = H.hash md5Hash :: B.ByteString -> H.Digest H.MD5 md5Hash = H.hash hashName :: Hash -> String hashName = show hashDigestSize :: Hash -> Int hashDigestSize MD5 = 16 hashDigestSize SHA1 = 20 hashDigestSize SHA224 = 28 hashDigestSize SHA256 = 32 hashDigestSize SHA384 = 48 hashDigestSize SHA512 = 64 hashDigestSize SHA1_MD5 = 36 hashBlockSize :: Hash -> Int hashBlockSize MD5 = 64 hashBlockSize SHA1 = 64 hashBlockSize SHA224 = 64 hashBlockSize SHA256 = 64 hashBlockSize SHA384 = 128 hashBlockSize SHA512 = 128 hashBlockSize SHA1_MD5 = 64 {- key exchange methods encrypt and decrypt for each supported algorithm -} generalizeRSAError :: Either RSA.Error a -> Either KxError a generalizeRSAError (Left e) = Left (RSAError e) generalizeRSAError (Right x) = Right x kxEncrypt :: MonadRandom r => PublicKey -> ByteString -> r (Either KxError ByteString) kxEncrypt (PubKeyRSA pk) b = generalizeRSAError `fmap` RSA.encrypt pk b kxEncrypt _ _ = return (Left KxUnsupported) kxDecrypt :: MonadRandom r => PrivateKey -> ByteString -> r (Either KxError ByteString) kxDecrypt (PrivKeyRSA pk) b = generalizeRSAError `fmap` RSA.decryptSafer pk b kxDecrypt _ _ = return (Left KxUnsupported) -- Verify that the signature matches the given message, using the -- public key. -- kxVerify :: PublicKey -> Hash -> ByteString -> ByteString -> Bool kxVerify (PubKeyRSA pk) alg msg sign = rsaVerifyHash alg pk msg sign kxVerify (PubKeyDSA pk) _ msg signBS = case dsaToSignature signBS of Just sig -> DSA.verify H.SHA1 pk sig msg _ -> False where dsaToSignature :: ByteString -> Maybe DSA.Signature dsaToSignature b = case decodeASN1' BER b of Left _ -> Nothing Right asn1 -> case asn1 of Start Sequence:IntVal r:IntVal s:End Sequence:_ -> Just $ DSA.Signature { DSA.sign_r = r, DSA.sign_s = s } _ -> Nothing kxVerify _ _ _ _ = False -- Sign the given message using the private key. -- kxSign :: MonadRandom r => PrivateKey -> Hash -> ByteString -> r (Either KxError ByteString) kxSign (PrivKeyRSA pk) hashAlg msg = generalizeRSAError `fmap` rsaSignHash hashAlg pk msg kxSign (PrivKeyDSA pk) _ msg = do sign <- DSA.sign pk H.SHA1 msg return (Right $ encodeASN1' DER $ dsaSequence sign) where dsaSequence sign = [Start Sequence,IntVal (DSA.sign_r sign),IntVal (DSA.sign_s sign),End Sequence] --kxSign g _ _ _ = -- (Left KxUnsupported, g) rsaSignHash :: MonadRandom m => Hash -> RSA.PrivateKey -> ByteString -> m (Either RSA.Error ByteString) rsaSignHash SHA1_MD5 pk msg = RSA.signSafer noHash pk msg rsaSignHash MD5 pk msg = RSA.signSafer (Just H.MD5) pk msg rsaSignHash SHA1 pk msg = RSA.signSafer (Just H.SHA1) pk msg rsaSignHash SHA224 pk msg = RSA.signSafer (Just H.SHA224) pk msg rsaSignHash SHA256 pk msg = RSA.signSafer (Just H.SHA256) pk msg rsaSignHash SHA384 pk msg = RSA.signSafer (Just H.SHA384) pk msg rsaSignHash SHA512 pk msg = RSA.signSafer (Just H.SHA512) pk msg rsaVerifyHash :: Hash -> RSA.PublicKey -> ByteString -> ByteString -> Bool rsaVerifyHash SHA1_MD5 = RSA.verify noHash rsaVerifyHash MD5 = RSA.verify (Just H.MD5) rsaVerifyHash SHA1 = RSA.verify (Just H.SHA1) rsaVerifyHash SHA224 = RSA.verify (Just H.SHA224) rsaVerifyHash SHA256 = RSA.verify (Just H.SHA256) rsaVerifyHash SHA384 = RSA.verify (Just H.SHA384) rsaVerifyHash SHA512 = RSA.verify (Just H.SHA512) noHash :: Maybe H.MD5 noHash = Nothing
AaronFriel/hs-tls
core/Network/TLS/Crypto.hs
bsd-3-clause
7,539
0
17
1,646
2,450
1,283
1,167
164
4
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE QuasiQuotes #-} -- | Main entry point to hindent. -- -- hindent module Main where import HIndent import HIndent.Types import Control.Applicative import Control.Applicative.QQ.Idiom import Data.List import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as T import qualified Data.Text.Lazy.IO as T import Data.Version (showVersion) import Descriptive import Descriptive.Options import GHC.Tuple import Language.Haskell.Exts.Annotated hiding (Style,style) import Paths_hindent (version) import System.Environment import Text.Read -- | Main entry point. main :: IO () main = do args <- getArgs case consume options (map T.pack args) of Succeeded (style,exts) -> T.interact (either error T.toLazyText . reformat style (Just exts)) Failed (Wrap (Stopped Version) _) -> putStrLn ("hindent " ++ showVersion version) _ -> error (T.unpack (textDescription (describe options []))) -- | Options that stop the argument parser. data Stoppers = Version deriving (Show) -- | Program options. options :: Monad m => Consumer [Text] (Option Stoppers) m (Style,[Extension]) options = ver *> [i|(,) style exts|] where ver = stop (flag "version" "Print the version" Version) style = [i|makeStyle (constant "--style" "Style to print with" () *> foldr1 (<|>) (map (\s -> constant (styleName s) (styleDescription s) s) styles)) lineLen|] exts = fmap getExtensions (many (prefix "X" "Language extension")) lineLen = fmap (>>= (readMaybe . T.unpack)) (optional (arg "line-length" "Desired length of lines")) makeStyle s mlen = case mlen of Nothing -> s Just len -> s {styleDefConfig = (styleDefConfig s) {configMaxColumns = len}} -------------------------------------------------------------------------------- -- Extensions stuff stolen from hlint -- | Consume an extensions list from arguments. getExtensions :: [Text] -> [Extension] getExtensions = foldl f defaultExtensions . map T.unpack where f _ "Haskell98" = [] f a ('N':'o':x) | Just x' <- readExtension x = delete x' a f a x | Just x' <- readExtension x = x' : delete x' a f _ x = error $ "Unknown extension: " ++ x -- | Parse an extension. readExtension :: String -> Maybe Extension readExtension x = case classifyExtension x of UnknownExtension _ -> Nothing x' -> Just x' -- | Default extensions. defaultExtensions :: [Extension] defaultExtensions = [e | e@EnableExtension{} <- knownExtensions] \\ map EnableExtension badExtensions -- | Extensions which steal too much syntax. badExtensions :: [KnownExtension] badExtensions = [Arrows -- steals proc ,TransformListComp -- steals the group keyword ,XmlSyntax, RegularPatterns -- steals a-b ,UnboxedTuples -- breaks (#) lens operator -- ,QuasiQuotes -- breaks [x| ...], making whitespace free list comps break ]
adamse/hindent
src/main/Main.hs
bsd-3-clause
3,616
0
17
1,178
766
423
343
82
4
module Types.Common ( sanitizeUserText , sanitizeUserText' , sanitizeChar ) where import Prelude () import Prelude.MH import qualified Data.Text as T import Network.Mattermost.Types ( UserText, unsafeUserText ) sanitizeUserText :: UserText -> T.Text sanitizeUserText = sanitizeUserText' . unsafeUserText sanitizeUserText' :: T.Text -> T.Text sanitizeUserText' t = T.replace "\ESC" "<ESC>" $ T.replace "\t" " " t sanitizeChar :: Char -> T.Text sanitizeChar '\ESC' = "<ESC>" sanitizeChar '\t' = " " sanitizeChar c = T.singleton c
aisamanra/matterhorn
src/Types/Common.hs
bsd-3-clause
550
0
7
94
151
84
67
18
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoRebindableSyntax #-} module Duckling.Numeral.AR.EG.Rules (rules) where import Data.Maybe import Prelude import qualified Data.HashMap.Strict as HashMap import Duckling.Dimensions.Types import Duckling.Numeral.AR.EG.Helpers ( digitsMap , parseArabicDoubleFromText , parseArabicIntegerFromText ) import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import Duckling.Regex.Types import Duckling.Types import qualified Duckling.Numeral.Types as TNumeral ruleInteger2 :: Rule ruleInteger2 = Rule { name = "integer 2" , pattern = [ regex "[إأا]?تني[ي]?ن" ] , prod = \_ -> integer 2 } ruleInteger3 :: Rule ruleInteger3 = Rule { name = "integer 3" , pattern = [ regex "تلات[هة]?" ] , prod = \_ -> integer 3 } ruleInteger8 :: Rule ruleInteger8 = Rule { name = "integer 8" , pattern = [ regex "تمان(ي[هة])?" ] , prod = \_ -> integer 8 } ruleInteger11 :: Rule ruleInteger11 = Rule { name = "integer 11" , pattern = [ regex "(إأا)?حداشر" ] , prod = \_ -> integer 11 } ruleInteger12 :: Rule ruleInteger12 = Rule { name = "integer 12" , pattern = [ regex "[إأا]?[تط]ناشر" ] , prod = \_ -> integer 12 } ruleInteger13 :: Rule ruleInteger13 = Rule { name = "integer 13" , pattern = [ regex "[تط]ل(ا)?[تط]اشر" ] , prod = \_ -> integer 13 } ruleInteger14 :: Rule ruleInteger14 = Rule { name = "integer 14" , pattern = [ regex "[إأا]ربع[تط]اشر" ] , prod = \_ -> integer 14 } ruleInteger15 :: Rule ruleInteger15 = Rule { name = "integer 15" , pattern = [ regex "خمس[تط]اشر" ] , prod = \_ -> integer 15 } ruleInteger16 :: Rule ruleInteger16 = Rule { name = "integer 16" , pattern = [ regex "س[تط]اشر" ] , prod = \_ -> integer 16 } ruleInteger17 :: Rule ruleInteger17 = Rule { name = "integer 17" , pattern = [ regex "سبع[تط]اشر" ] , prod = \_ -> integer 17 } ruleInteger18 :: Rule ruleInteger18 = Rule { name = "integer 18" , pattern = [ regex "[تط]من[تط]اشر" ] , prod = \_ -> integer 18 } ruleInteger19 :: Rule ruleInteger19 = Rule { name = "integer 19" , pattern = [ regex "تسع[تط]اشر" ] , prod = \_ -> integer 19 } ruleInteger30_80 :: Rule ruleInteger30_80 = Rule { name = "integer (30, 80)" , pattern = [ regex "([تط]لا[تط]|[تط]مان)(ين)" ] , prod = \tokens -> case tokens of Token RegexMatch (GroupMatch (match:_)):_ -> (* 10) <$> HashMap.lookup match digitsMap >>= integer _ -> Nothing } ruleInteger100 :: Rule ruleInteger100 = Rule { name = "integer (100)" , pattern = [ regex "مي[هةت]" ] , prod = const $ integer 100 } ruleInteger200 :: Rule ruleInteger200 = Rule { name = "integer (200)" , pattern = [ regex "م(ي)?تين" ] , prod = const $ integer 200 } ruleInteger300 :: Rule ruleInteger300 = Rule { name = "integer (300)" , pattern = [ regex "([تط]و?لا?[تط]و?)مي[هةت]" ] , prod = const $ integer 300 } ruleInteger400 :: Rule ruleInteger400 = Rule { name = "integer (400)" , pattern = [ regex "(رو?بعو?)مي[هةت]" ] , prod = const $ integer 400 } ruleInteger500 :: Rule ruleInteger500 = Rule { name = "integer (500)" , pattern = [ regex "(خو?مسو?)مي[هةت]" ] , prod = const $ integer 500 } ruleInteger600 :: Rule ruleInteger600 = Rule { name = "integer (600)" , pattern = [ regex "(سو?تو?)مي[هةت]" ] , prod = const $ integer 600 } ruleInteger700 :: Rule ruleInteger700 = Rule { name = "integer (700)" , pattern = [ regex "(سو?بعو?)مي[هةت]" ] , prod = const $ integer 700 } ruleInteger800 :: Rule ruleInteger800 = Rule { name = "integer (800)" , pattern = [ regex "([تط]و?منو?)مي[هةت]" ] , prod = const $ integer 800 } ruleInteger900 :: Rule ruleInteger900 = Rule { name = "integer (900)" , pattern = [ regex "([تط]و?سعو?)مي[هةت]" ] , prod = const $ integer 900 } ruleInteger101_999 :: Rule ruleInteger101_999 = Rule { name = "integer 101..999" , pattern = [ oneOf [100, 200 .. 900] , regex "\\s" , oneOf $ map (+) [10, 20 .. 90] <*> [1..9] ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v1}: _: Token Numeral NumeralData{TNumeral.value = v2}: _) -> double $ v1 + v2 _ -> Nothing } ruleInteger3000 :: Rule ruleInteger3000 = Rule { name = "integer (3000)" , pattern = [ regex "([تط]لا?[تط])( ?[اآ])?لاف" ] , prod = const $ integer 3000 } ruleInteger4000 :: Rule ruleInteger4000 = Rule { name = "integer (4000)" , pattern = [ regex "[أا]ربع(ت| ?[اآ])لاف" ] , prod = const $ integer 4000 } ruleInteger5000 :: Rule ruleInteger5000 = Rule { name = "integer (5000)" , pattern = [ regex "خمس(ت| ?[اآ])لاف" ] , prod = const $ integer 5000 } ruleInteger6000 :: Rule ruleInteger6000 = Rule { name = "integer (6000)" , pattern = [ regex "س(ت| ?[اآ])لاف" ] , prod = const $ integer 6000 } ruleInteger7000 :: Rule ruleInteger7000 = Rule { name = "integer (7000)" , pattern = [ regex "سبع(ت| ?[اآ])لاف" ] , prod = const $ integer 7000 } ruleInteger8000 :: Rule ruleInteger8000 = Rule { name = "integer (8000)" , pattern = [ regex "[تط]م[ا]?ن(ت| ?[اآ])لاف" ] , prod = const $ integer 8000 } ruleInteger9000 :: Rule ruleInteger9000 = Rule { name = "integer (9000)" , pattern = [ regex "([تط]سع)(ت| ?[اآ])لاف" ] , prod = const $ integer 9000 } rules :: [Rule] rules = [ ruleInteger2 , ruleInteger3 , ruleInteger8 , ruleInteger11 , ruleInteger12 , ruleInteger13 , ruleInteger14 , ruleInteger15 , ruleInteger16 , ruleInteger17 , ruleInteger18 , ruleInteger19 , ruleInteger30_80 , ruleInteger100 , ruleInteger200 , ruleInteger300 , ruleInteger400 , ruleInteger500 , ruleInteger600 , ruleInteger700 , ruleInteger800 , ruleInteger900 , ruleInteger101_999 , ruleInteger3000 , ruleInteger4000 , ruleInteger5000 , ruleInteger6000 , ruleInteger7000 , ruleInteger8000 , ruleInteger9000 ]
facebookincubator/duckling
Duckling/Numeral/AR/EG/Rules.hs
bsd-3-clause
6,691
0
18
1,644
1,681
998
683
239
2
{- n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! -} import Data.Char fact :: Integer -> Integer fact n = product [1..n] digit_sum :: Int digit_sum = sum . map digitToInt . show . fact $ 100 main :: IO () main = do putStrLn . show $ digit_sum
bgwines/project-euler
src/solved/problem20.hs
bsd-3-clause
433
0
9
115
87
45
42
8
1
module Bounded where import Base instance Bounded () where minBound = () maxBound = () instance (Bounded a, Bounded b) => Bounded (a,b) where minBound = (minBound, minBound) maxBound = (maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where minBound = (minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where minBound = (minBound, minBound, minBound,minBound) maxBound = (maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e) => Bounded (a,b,c,d,e) where minBound = (minBound, minBound, minBound,minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e, Bounded f) => Bounded (a,b,c,d,e,f) where minBound = (minBound, minBound, minBound,minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e, Bounded f, Bounded g) => Bounded (a,b,c,d,e,f,g) where minBound = (minBound, minBound, minBound,minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
rodrigogribeiro/mptc
src/Libs/Bounded.hs
bsd-3-clause
1,366
0
6
247
562
333
229
23
0
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Concurrent import System.IO import Text.XML.Pipe import Network import HttpPullSv main :: IO () main = do soc <- listenOn $ PortNumber 80 forever $ do (h, _, _) <- accept soc void . forkIO $ testPusher (undefined :: HttpPullSv Handle) (One h) (isPoll, endPoll) isPoll :: XmlNode -> Bool isPoll (XmlNode (_, "poll") _ _ _) = True isPoll _ = False endPoll :: XmlNode endPoll = XmlNode (nullQ "nothing") [] [] []
YoshikuniJujo/forest
subprojects/xml-push/testHttpPullSv.hs
bsd-3-clause
495
2
13
94
199
105
94
19
1
{-# LANGUAGE ForeignFunctionInterface #-} {-# CFILES csrc/gsl_interp.c #-} -- | Cubic-spline interpolation (natural boundary conditions) with the GNU Scientific Library -- -- All @Double@ @Vector@ types are @Unboxed@ - conversion to @Storable@ @CDouble@ is performed internally. -- -- TODO: Possible improvements include wrapping the 'InterpStructPtr' in a -- @ForeignPtr@ and registering the 'interpFree' function as a finalizer. -- For now, I prefer to handle the deallocation explicitly. In addition, leaving -- the 'InterpStructPtr' as a plain @Ptr@ type alias keeps the evaluation -- functions out of the @IO@ Monad (no requirement to use @withForeignPtr@) -- or alternatively from using @unsafeForeignPtrToPtr@ excessively. module Math.GSLInterp ( InterpStruct (..) , InterpStructPtr , interpInit , interpFree , interpEval , interpEvalDeriv , interpEvalSecondDeriv , interpEvalInteg ) where import Foreign.C import Foreign.Ptr import Foreign.ForeignPtr hiding (unsafeForeignPtrToPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified Data.Vector.Storable as S import qualified Data.Vector.Unboxed as V import Control.Monad (unless) import Text.Printf -- | Unit-like type representing foreign interpolant structure data InterpStruct = InterpStruct -- | Convenient type alias for pointer to foreign interpolant structure type InterpStructPtr = Ptr InterpStruct -- FFI interfaces for wrapper code (C) foreign import ccall "gsl_interp_init_wrapper" gslInterpInit :: Ptr CDouble -> Ptr CDouble -> CInt -> CDouble -> IO InterpStructPtr foreign import ccall "gsl_interp_free_wrapper" gslInterpFree :: InterpStructPtr -> IO () foreign import ccall "gsl_interp_eval_wrapper" gslInterpEval :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_deriv_wrapper" gslInterpEvalDeriv :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_deriv2_wrapper" gslInterpEvalSecondDeriv :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_integ_wrapper" gslInterpEvalInteg :: InterpStructPtr -> CDouble -> CDouble -> CDouble -- Helpers used below -- Converts an Unboxed Vector of Doubles to a Storable Vector of CDoubles toStorable :: V.Vector Double -> S.Vector CDouble toStorable = S.map realToFrac . S.convert -- Converts a function of type CDouble -> CDouble to one of Double -> Double wrapDouble :: (CDouble -> CDouble) -> Double -> Double wrapDouble f = realToFrac . f . realToFrac -- Converts a function of type CDouble -> CDouble -> CDouble to one of Double -> Double -> Double wrapDouble3 :: (CDouble -> CDouble -> CDouble) -> Double -> Double -> Double wrapDouble3 f x = wrapDouble $ f (realToFrac x) -- | Initialization of a GSL cubic-spline interpolant -- -- Fails on: (1) memory-allocation failure within the C-based wrapper; or (2) unequal dimension of user-supplied abscissa and ordinate vectors. interpInit :: V.Vector Double -- ^ Unboxed @Vector@ of abscissae -> V.Vector Double -- ^ Unboxed @Vector@ of ordinates -> Double -- ^ Fill-value returned on bounds errors -> IO (Maybe InterpStructPtr) -- ^ @Maybe@ pointer to the resulting interpolant structure (returns @Nothing@ on failure) interpInit xs ys v = do -- convert to S.Vector CDouble, extract ForeignPtrs let (fpx,nx) = S.unsafeToForeignPtr0 . toStorable $ xs (fpy,ny) = S.unsafeToForeignPtr0 . toStorable $ ys -- check for dimension mismatch if nx /= ny then printf "Error [interpInit]: vector dimension mismatch: %i /= %i\n" nx ny >> return Nothing else do -- initialize foreign interpolant state structure interp <- gslInterpInit (unsafeForeignPtrToPtr fpx) (unsafeForeignPtrToPtr fpy) (fromIntegral ny) (realToFrac v) -- ensure the ForeignPtrs live until _after_ call to gslInterpInit touchForeignPtr fpx touchForeignPtr fpy -- check for failure and return if interp == nullPtr then printf "Error [interpInit]: init returned null pointer\n" >> return Nothing else return . Just $ interp -- | Free storage associated with the foreign interpolant structure interpFree :: InterpStructPtr -> IO () interpFree p = unless (p == nullPtr) (gslInterpFree p) -- | Evaluate the cubic spline interpolant associated with the supplied interpolant structure interpEval :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ interpolated y-value interpEval = wrapDouble . gslInterpEval -- | Evaluate the first derivative of the cubic spline interpolant associated with the supplied interpolant structure interpEvalDeriv :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ derivative interpEvalDeriv = wrapDouble . gslInterpEvalDeriv -- | Evaluate the second derivative of the cubic spline interpolant associated with the supplied interpolant structure interpEvalSecondDeriv :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ second derivative interpEvalSecondDeriv = wrapDouble . gslInterpEvalSecondDeriv -- | Evaluate the defintie integral of the cubic spline interpolant associated with the supplied interpolant structure within the specified range interpEvalInteg :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value of lower integration bound -> Double -- ^ x-value of upper integration bound -> Double -- ^ integral interpEvalInteg = wrapDouble3 . gslInterpEvalInteg
swfrench/GSLInterp
src/Math/GSLInterp.hs
bsd-3-clause
5,691
0
13
1,077
772
433
339
103
3
{-#LANGUAGE TemplateHaskell #-} module Parser.Rename (runRename) where import Data.DataType import Control.Lens import qualified Data.Map.Strict as M import Control.Monad.State import Control.Monad.Except data Buffer = Buffer { _counter :: Int , _upper :: M.Map String Int , _current :: M.Map String Int , _vars :: [IntVar] } makeLenses '' Buffer initialBuffer = Buffer 0 M.empty M.empty [] type Rename = StateT Buffer Stage declVar :: LitVar -> Rename IntVar declVar (Var x pos) = do test <- uses current (M.member x) if test then throw (NameCollition x pos) else do now <- use counter counter += 1 current %= M.insert x now let newV = Slot now x pos vars %= (newV :) return newV useVar :: LitVar -> Rename IntVar useVar (Var x pos) = do cur <- use current upp <- use upper let find = M.lookup x case (find cur, find upp) of (Just a, _) -> return (Slot a x pos) (Nothing, Just a) -> return (Slot a x pos) _ -> throw (NotInScope x pos) -- | restore state after exec the action restore :: Rename a -> Rename a restore ac = do old <- get res <- ac newCont <- use counter put (counter .~ newCont $ old) return res descend :: Rename () descend = do cur <- use current upper %= M.union cur current .= M.empty vars .= [] renameExpr :: LitExpr -> Rename RenamedExpr renameExpr (Id var) = fmap Id (useVar var) renameExpr (AppFun fun args) = do newf <- useVar fun newArgs <- mapM renameExpr args return (AppFun newf newArgs) renameExpr (Plus e1 e2) = renameTwo Plus e1 e2 renameExpr (Minus e1 e2) = renameTwo Minus e1 e2 renameExpr (Mult e1 e2) = renameTwo Mult e1 e2 renameExpr (Div e1 e2) = renameTwo Div e1 e2 renameExpr (Num n) = return (Num n) renameTwo f e1 e2 = do newE1 <- renameExpr e1 newE2 <- renameExpr e2 return (f newE1 newE2) renameCommand :: LitCommand -> Rename RenamedCommand renameCommand (Decl vars) = fmap Decl (mapM declVar vars) renameCommand (Value ex) = fmap Value (renameExpr ex) renameCommand (Func f paras pro) = do newF <- declVar f restore $ do descend newParas <- mapM declVar paras newPro <- renameProgram pro freed <- use vars return $ Record newF newParas newPro freed renameCommand (LetBe var ex) = do newVar <- useVar var newEx <- renameExpr ex return (LetBe newVar newEx) renameCommand (RunFun fun args) = do newFun <- useVar fun newArgs <- mapM renameExpr args return (RunFun newFun newArgs) renameCommand (Return ex) = fmap Return (renameExpr ex) renameCommand (Read var) = fmap Read (useVar var) renameCommand (Print ex) = fmap Print (renameExpr ex) renameProgram ::LitProgram -> Rename RenamedProgram renameProgram = mapM renameCommand runRename :: LitProgram -> Stage RenamedProgram runRename pro = evalStateT (renameProgram pro) initialBuffer
jyh1/mini
src/Parser/Rename.hs
bsd-3-clause
2,846
0
13
630
1,174
559
615
90
3
module Watch.Spew where import Data.Foldable import Data.List.NonEmpty import qualified Data.Map as M import System.Console.ANSI import System.FilePath import System.FilePath.Glob import Watch.Types showConcerns :: Refs -> IO () showConcerns cMap = forM_ (M.toList cMap) $ \ (file, d :| ds) -> do setSGR [SetColor Foreground Dull Yellow] putStrLn file setSGR [SetColor Foreground Dull Black] putStr " -> " setSGR [Reset] putStrLn (comp d) forM_ ds $ \ t -> putStrLn $ " " ++ comp t where comp = uncurry (\ a b -> a </> decompile b)
pikajude/src-watch
src/Watch/Spew.hs
bsd-3-clause
601
0
12
155
217
111
106
19
1
{-# LANGUAGE OverloadedStrings #-} module Network.HTTP.Nano( module Network.HTTP.Nano.Types, Network.HTTP.Conduit.Request, tlsManager, mkJSONData, http, http', httpS, httpSJSON, httpJSON, buildReq, addHeaders ) where import Network.HTTP.Nano.Types import Control.Exception (handle) import Control.Lens (review, view) import Control.Monad import Control.Monad.Except (MonadError, throwError) import Control.Monad.Reader (MonadReader) import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad.Trans.Resource (MonadResource) import Data.Aeson (FromJSON, ToJSON (..), eitherDecode, encode) import Data.Bifunctor (bimap) import Data.Conduit (ResumableSource, Conduit, ($=+)) import Data.JsonStream.Parser (value, parseByteString) import Data.String (fromString) import Network.HTTP.Conduit hiding (http) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Conduit.List as CL import qualified Network.HTTP.Conduit as HC -- |Create an HTTP manager tlsManager :: IO Manager tlsManager = newManager tlsManagerSettings -- |Create a JSON request body mkJSONData :: ToJSON d => d -> RequestData mkJSONData = JSONRequestData . toJSON -- |Perform an HTTP request http :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m) => Request -> m BL.ByteString http req = responseBody <$> (view httpManager >>= safeHTTP . httpLbs req) -- |Perform an HTTP request, ignoring the response http' :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m) => Request -> m () http' = void . http httpS :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadResource m) => Request -> m (ResumableSource m B.ByteString) httpS req = responseBody <$> (view httpManager >>= HC.http req) httpSJSON :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadResource m, FromJSON a) => Request -> m (ResumableSource m a) httpSJSON req = do src <- httpS req return $ src $=+ jsonConduit jsonConduit :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadResource m, FromJSON a) => Conduit B.ByteString m a jsonConduit = CL.mapFoldable (parseByteString value) -- |Perform an HTTP request, attempting to parse the response as JSON httpJSON :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m, FromJSON b) => Request -> m b httpJSON req = http req >>= asJSON asJSON :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m, FromJSON b) => BL.ByteString -> m b asJSON bs = case eitherDecode bs of Left err -> throwError (review _ResponseParseError (err ++ "; original data: " ++ BL.unpack bs)) Right b -> return b -- |Build a request buildReq :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m) => HttpMethod -> URL -> RequestData -> m Request buildReq mthd url dta = do breq <- safeHTTP $ parseUrlThrow url return . attachRequestData dta $ breq { method = B.pack $ showHttpMethod mthd } attachRequestData :: RequestData -> Request -> Request attachRequestData NoRequestData req = req attachRequestData (JSONRequestData b) req = req { requestBody = RequestBodyLBS (encode b) } attachRequestData (UrlEncodedRequestData px) req = flip urlEncodedBody req $ fmap (bimap B.pack B.pack) px attachRequestData (RawRequestData bs) req = req { requestBody = RequestBodyLBS bs } -- |Add headers to a request addHeaders :: [(String, String)] -> Request -> Request addHeaders hx req = req { requestHeaders = ehx ++ nhx } where ehx = requestHeaders req nhx = fmap toHeader hx toHeader (n, v) = (fromString n, B.pack v) safeHTTP :: (MonadError e m, MonadReader r m, AsHttpError e, HasHttpCfg r, MonadIO m) => IO a -> m a safeHTTP act = do res <- liftIO $ handle (return . Left) (Right <$> act) case res of Left ex -> throwError $ review _NetworkError ex Right r -> return r
ralphmorton/nano-http
src/Network/HTTP/Nano.hs
bsd-3-clause
3,966
0
14
695
1,349
723
626
73
2
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module is intended to be imported @qualified@, for example: -- -- > import qualified Test.Tasty.Laws.Monad as Monad -- module Test.Tasty.Laws.Monad ( testUnit , test , testExhaustive ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative (Applicative) #endif import Control.Monad.Laws (associativity) import Test.DumbCheck (Series, Serial(series), uncurry3, zipA3) import Test.Tasty (TestTree, testGroup) import Test.Tasty.DumbCheck (testSeriesProperty) import qualified Test.Tasty.Laws.Applicative as Applicative -- | @tasty@ 'TestTree' for 'Monad' laws. The type signature forces the -- parameter to be '()' which, unless you are dealing with non-total -- functions, should be enough to test any 'Monad's. testUnit :: ( Applicative m, Monad m , Eq (m ()) , Show (m ()), Show (m (() -> ())) , Serial (m ()), Serial (m (() -> ())) ) => Series (m ()) -> TestTree testUnit = testExhaustive -- | @tasty@ 'TestTree' for 'Monad' laws. Monomorphic sum 'Series'. test :: forall m a . ( Applicative m, Monad m , Eq a, Eq (m a) , Show a, Show (m a), Show (m (a -> a)) , Serial a, Serial (m a), Serial (m (a -> a)) ) => Series (m a) -> TestTree test ms = testGroup "Monad laws" [ Applicative.test ms , testSeriesProperty "(m >>= f) >>= g ≡ m (f >=> g)" (uncurry3 associativity) $ zip3 ms (series :: Series (a -> m a)) (series :: Series (a -> m a)) ] -- | @tasty@ 'TestTree' for 'Monad' laws. Monomorphic product 'Series'. testExhaustive :: forall m a . ( Applicative m, Monad m , Eq a, Eq (m a) , Show a, Show (m a), Show (m (a -> a)) , Serial a, Serial (m a), Serial (m (a -> a)) ) => Series (m a) -> TestTree testExhaustive ms = testGroup "Monad laws" [ Applicative.testExhaustive ms , testSeriesProperty "(m >>= f) >>= g ≡ m (f >=> g)" (uncurry3 associativity) $ zipA3 ms (series :: Series (a -> m a)) (series :: Series (a -> m a)) ]
jdnavarro/tasty-laws
Test/Tasty/Laws/Monad.hs
bsd-3-clause
2,144
0
13
538
669
364
305
50
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} -- | -- Module : Auth.Register -- Copyright : (C) 2015 Ricky Elrod -- License : MIT (see LICENSE file) -- Maintainer : (C) Ricky Elrod <[email protected]> -- Stability : experimental -- -- Functions and handlers for performing registration. module Auth.Register where import Application #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Lens import Control.Monad.IO.Class import Data.Text.Encoding import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Heist import Text.Digestive.Heist import Text.Digestive.Snap hiding (method) import Auth.Login import Lenses import Forms.Login -- | Handle new user form submit handleNewUser :: Handler App (AuthManager App) () handleNewUser = do (view', result) <- runForm "new_user" loginForm case result of Just user -> do auth' <- createUser (user ^. username) (user ^. password . to encodeUtf8) case auth' of Left e -> liftIO (print e) >> heistLocal (bindDigestiveSplices view') (render "new_user") Right _ -> handleLoginSubmit view' "new_user" user Nothing -> heistLocal (bindDigestiveSplices view') $ render "new_user"
meoblast001/quotum-snap
src/Auth/Register.hs
mit
1,231
0
18
232
269
148
121
-1
-1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DeriveLift #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} module Database.Persist.Types.Base ( module Database.Persist.Types.Base -- * Re-exports , PersistValue(..) , fromPersistValueText , LiteralType(..) ) where import Control.Exception (Exception) import Data.Char (isSpace) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as NEL import Data.Map (Map) import Data.Maybe (isNothing) import Data.Text (Text) import qualified Data.Text as T import Data.Word (Word32) import Language.Haskell.TH.Syntax (Lift(..)) import Web.HttpApiData ( FromHttpApiData(..) , ToHttpApiData(..) , parseBoundedTextData , showTextData ) import Web.PathPieces (PathPiece(..)) -- Bring `Lift (Map k v)` instance into scope, as well as `Lift Text` -- instance on pre-1.2.4 versions of `text` import Instances.TH.Lift () import Database.Persist.Names import Database.Persist.PersistValue -- | A 'Checkmark' should be used as a field type whenever a -- uniqueness constraint should guarantee that a certain kind of -- record may appear at most once, but other kinds of records may -- appear any number of times. -- -- /NOTE:/ You need to mark any @Checkmark@ fields as @nullable@ -- (see the following example). -- -- For example, suppose there's a @Location@ entity that -- represents where a user has lived: -- -- @ -- Location -- user UserId -- name Text -- current Checkmark nullable -- -- UniqueLocation user current -- @ -- -- The @UniqueLocation@ constraint allows any number of -- 'Inactive' @Location@s to be @current@. However, there may be -- at most one @current@ @Location@ per user (i.e., either zero -- or one per user). -- -- This data type works because of the way that SQL treats -- @NULL@able fields within uniqueness constraints. The SQL -- standard says that @NULL@ values should be considered -- different, so we represent 'Inactive' as SQL @NULL@, thus -- allowing any number of 'Inactive' records. On the other hand, -- we represent 'Active' as @TRUE@, so the uniqueness constraint -- will disallow more than one 'Active' record. -- -- /Note:/ There may be DBMSs that do not respect the SQL -- standard's treatment of @NULL@ values on uniqueness -- constraints, please check if this data type works before -- relying on it. -- -- The SQL @BOOLEAN@ type is used because it's the smallest data -- type available. Note that we never use @FALSE@, just @TRUE@ -- and @NULL@. Provides the same behavior @Maybe ()@ would if -- @()@ was a valid 'PersistField'. data Checkmark = Active -- ^ When used on a uniqueness constraint, there -- may be at most one 'Active' record. | Inactive -- ^ When used on a uniqueness constraint, there -- may be any number of 'Inactive' records. deriving (Eq, Ord, Read, Show, Enum, Bounded) instance ToHttpApiData Checkmark where toUrlPiece = showTextData instance FromHttpApiData Checkmark where parseUrlPiece = parseBoundedTextData instance PathPiece Checkmark where toPathPiece Active = "active" toPathPiece Inactive = "inactive" fromPathPiece "active" = Just Active fromPathPiece "inactive" = Just Inactive fromPathPiece _ = Nothing data IsNullable = Nullable !WhyNullable | NotNullable deriving (Eq, Show) fieldAttrsContainsNullable :: [FieldAttr] -> IsNullable fieldAttrsContainsNullable s | FieldAttrMaybe `elem` s = Nullable ByMaybeAttr | FieldAttrNullable `elem` s = Nullable ByNullableAttr | otherwise = NotNullable -- | The reason why a field is 'nullable' is very important. A -- field that is nullable because of a @Maybe@ tag will have its -- type changed from @A@ to @Maybe A@. OTOH, a field that is -- nullable because of a @nullable@ tag will remain with the same -- type. data WhyNullable = ByMaybeAttr | ByNullableAttr deriving (Eq, Show) -- | An 'EntityDef' represents the information that @persistent@ knows -- about an Entity. It uses this information to generate the Haskell -- datatype, the SQL migrations, and other relevant conversions. data EntityDef = EntityDef { entityHaskell :: !EntityNameHS -- ^ The name of the entity as Haskell understands it. , entityDB :: !EntityNameDB -- ^ The name of the database table corresponding to the entity. , entityId :: !EntityIdDef -- ^ The entity's primary key or identifier. , entityAttrs :: ![Attr] -- ^ The @persistent@ entity syntax allows you to add arbitrary 'Attr's -- to an entity using the @!@ operator. Those attributes are stored in -- this list. , entityFields :: ![FieldDef] -- ^ The fields for this entity. Note that the ID field will not be -- present in this list. To get all of the fields for an entity, use -- 'keyAndEntityFields'. , entityUniques :: ![UniqueDef] -- ^ The Uniqueness constraints for this entity. , entityForeigns:: ![ForeignDef] -- ^ The foreign key relationships that this entity has to other -- entities. , entityDerives :: ![Text] -- ^ A list of type classes that have been derived for this entity. , entityExtra :: !(Map Text [ExtraLine]) , entitySum :: !Bool -- ^ Whether or not this entity represents a sum type in the database. , entityComments :: !(Maybe Text) -- ^ Optional comments on the entity. -- -- @since 2.10.0 } deriving (Show, Eq, Read, Ord, Lift) -- | The definition for the entity's primary key ID. -- -- @since 2.13.0.0 data EntityIdDef = EntityIdField !FieldDef -- ^ The entity has a single key column, and it is a surrogate key - that -- is, you can't go from @rec -> Key rec@. -- -- @since 2.13.0.0 | EntityIdNaturalKey !CompositeDef -- ^ The entity has a natural key. This means you can write @rec -> Key rec@ -- because all the key fields are present on the datatype. -- -- A natural key can have one or more columns. -- -- @since 2.13.0.0 deriving (Show, Eq, Read, Ord, Lift) -- | Return the @['FieldDef']@ for the entity keys. entitiesPrimary :: EntityDef -> NonEmpty FieldDef entitiesPrimary t = case entityId t of EntityIdNaturalKey fds -> compositeFields fds EntityIdField fd -> pure fd entityPrimary :: EntityDef -> Maybe CompositeDef entityPrimary t = case entityId t of EntityIdNaturalKey c -> Just c _ -> Nothing entityKeyFields :: EntityDef -> NonEmpty FieldDef entityKeyFields = entitiesPrimary -- | Returns a 'NonEmpty' list of 'FieldDef' that correspond with the key -- columns for an 'EntityDef'. keyAndEntityFields :: EntityDef -> NonEmpty FieldDef keyAndEntityFields ent = case entityId ent of EntityIdField fd -> fd :| fields EntityIdNaturalKey _ -> case NEL.nonEmpty fields of Nothing -> error $ mconcat [ "persistent internal guarantee failed: entity is " , "defined with an entityId = EntityIdNaturalKey, " , "but somehow doesn't have any entity fields." ] Just xs -> xs where fields = filter isHaskellField $ entityFields ent type ExtraLine = [Text] type Attr = Text -- | Attributes that may be attached to fields that can affect migrations -- and serialization in backend-specific ways. -- -- While we endeavor to, we can't forsee all use cases for all backends, -- and so 'FieldAttr' is extensible through its constructor 'FieldAttrOther'. -- -- @since 2.11.0.0 data FieldAttr = FieldAttrMaybe -- ^ The 'Maybe' keyword goes after the type. This indicates that the column -- is nullable, and the generated Haskell code will have a @'Maybe'@ type -- for it. -- -- Example: -- -- @ -- User -- name Text Maybe -- @ | FieldAttrNullable -- ^ This indicates that the column is nullable, but should not have -- a 'Maybe' type. For this to work out, you need to ensure that the -- 'PersistField' instance for the type in question can support -- a 'PersistNull' value. -- -- @ -- data What = NoWhat | Hello Text -- -- instance PersistField What where -- fromPersistValue PersistNull = -- pure NoWhat -- fromPersistValue pv = -- Hello <$> fromPersistValue pv -- -- instance PersistFieldSql What where -- sqlType _ = SqlString -- -- User -- what What nullable -- @ | FieldAttrMigrationOnly -- ^ This tag means that the column will not be present on the Haskell code, -- but will not be removed from the database. Useful to deprecate fields in -- phases. -- -- You should set the column to be nullable in the database. Otherwise, -- inserts won't have values. -- -- @ -- User -- oldName Text MigrationOnly -- newName Text -- @ | FieldAttrSafeToRemove -- ^ A @SafeToRemove@ attribute is not present on the Haskell datatype, and -- the backend migrations should attempt to drop the column without -- triggering any unsafe migration warnings. -- -- Useful after you've used @MigrationOnly@ to remove a column from the -- database in phases. -- -- @ -- User -- oldName Text SafeToRemove -- newName Text -- @ | FieldAttrNoreference -- ^ This attribute indicates that we should create a foreign key reference -- from a column. By default, @persistent@ will try and create a foreign key -- reference for a column if it can determine that the type of the column is -- a @'Key' entity@ or an @EntityId@ and the @Entity@'s name was present in -- 'mkPersist'. -- -- This is useful if you want to use the explicit foreign key syntax. -- -- @ -- Post -- title Text -- -- Comment -- postId PostId noreference -- Foreign Post fk_comment_post postId -- @ | FieldAttrReference Text -- ^ This is set to specify precisely the database table the column refers -- to. -- -- @ -- Post -- title Text -- -- Comment -- postId PostId references="post" -- @ -- -- You should not need this - @persistent@ should be capable of correctly -- determining the target table's name. If you do need this, please file an -- issue describing why. | FieldAttrConstraint Text -- ^ Specify a name for the constraint on the foreign key reference for this -- table. -- -- @ -- Post -- title Text -- -- Comment -- postId PostId constraint="my_cool_constraint_name" -- @ | FieldAttrDefault Text -- ^ Specify the default value for a column. -- -- @ -- User -- createdAt UTCTime default="NOW()" -- @ -- -- Note that a @default=@ attribute does not mean you can omit the value -- while inserting. | FieldAttrSqltype Text -- ^ Specify a custom SQL type for the column. Generally, you should define -- a custom datatype with a custom 'PersistFieldSql' instance instead of -- using this. -- -- @ -- User -- uuid Text sqltype="UUID" -- @ | FieldAttrMaxlen Integer -- ^ Set a maximum length for a column. Useful for VARCHAR and indexes. -- -- @ -- User -- name Text maxlen=200 -- -- UniqueName name -- @ | FieldAttrSql Text -- ^ Specify the database name of the column. -- -- @ -- User -- blarghle Int sql="b_l_a_r_g_h_l_e" -- @ -- -- Useful for performing phased migrations, where one column is renamed to -- another column over time. | FieldAttrOther Text -- ^ A grab bag of random attributes that were unrecognized by the parser. deriving (Show, Eq, Read, Ord, Lift) -- | Parse raw field attributes into structured form. Any unrecognized -- attributes will be preserved, identically as they are encountered, -- as 'FieldAttrOther' values. -- -- @since 2.11.0.0 parseFieldAttrs :: [Text] -> [FieldAttr] parseFieldAttrs = fmap $ \case "Maybe" -> FieldAttrMaybe "nullable" -> FieldAttrNullable "MigrationOnly" -> FieldAttrMigrationOnly "SafeToRemove" -> FieldAttrSafeToRemove "noreference" -> FieldAttrNoreference raw | Just x <- T.stripPrefix "reference=" raw -> FieldAttrReference x | Just x <- T.stripPrefix "constraint=" raw -> FieldAttrConstraint x | Just x <- T.stripPrefix "default=" raw -> FieldAttrDefault x | Just x <- T.stripPrefix "sqltype=" raw -> FieldAttrSqltype x | Just x <- T.stripPrefix "maxlen=" raw -> case reads (T.unpack x) of [(n, s)] | all isSpace s -> FieldAttrMaxlen n _ -> error $ "Could not parse maxlen field with value " <> show raw | Just x <- T.stripPrefix "sql=" raw -> FieldAttrSql x | otherwise -> FieldAttrOther raw -- | A 'FieldType' describes a field parsed from the QuasiQuoter and is -- used to determine the Haskell type in the generated code. -- -- @name Text@ parses into @FTTypeCon Nothing "Text"@ -- -- @name T.Text@ parses into @FTTypeCon (Just "T" "Text")@ -- -- @name (Jsonb User)@ parses into: -- -- @ -- FTApp (FTTypeCon Nothing "Jsonb") (FTTypeCon Nothing "User") -- @ data FieldType = FTTypeCon (Maybe Text) Text -- ^ Optional module and name. | FTTypePromoted Text | FTApp FieldType FieldType | FTList FieldType deriving (Show, Eq, Read, Ord, Lift) isFieldNotGenerated :: FieldDef -> Bool isFieldNotGenerated = isNothing . fieldGenerated -- | There are 3 kinds of references -- 1) composite (to fields that exist in the record) -- 2) single field -- 3) embedded data ReferenceDef = NoReference | ForeignRef !EntityNameHS -- ^ A ForeignRef has a late binding to the EntityDef it references via name -- and has the Haskell type of the foreign key in the form of FieldType | EmbedRef EntityNameHS | CompositeRef CompositeDef | SelfReference -- ^ A SelfReference stops an immediate cycle which causes non-termination at compile-time (issue #311). deriving (Show, Eq, Read, Ord, Lift) -- | An EmbedEntityDef is the same as an EntityDef -- But it is only used for fieldReference -- so it only has data needed for embedding data EmbedEntityDef = EmbedEntityDef { embeddedHaskell :: EntityNameHS , embeddedFields :: [EmbedFieldDef] } deriving (Show, Eq, Read, Ord, Lift) -- | An EmbedFieldDef is the same as a FieldDef -- But it is only used for embeddedFields -- so it only has data needed for embedding data EmbedFieldDef = EmbedFieldDef { emFieldDB :: FieldNameDB , emFieldEmbed :: Maybe (Either SelfEmbed EntityNameHS) } deriving (Show, Eq, Read, Ord, Lift) data SelfEmbed = SelfEmbed deriving (Show, Eq, Read, Ord, Lift) -- | Returns 'True' if the 'FieldDef' does not have a 'MigrationOnly' or -- 'SafeToRemove' flag from the QuasiQuoter. -- -- @since 2.13.0.0 isHaskellField :: FieldDef -> Bool isHaskellField fd = FieldAttrMigrationOnly `notElem` fieldAttrs fd && FieldAttrSafeToRemove `notElem` fieldAttrs fd toEmbedEntityDef :: EntityDef -> EmbedEntityDef toEmbedEntityDef ent = embDef where embDef = EmbedEntityDef { embeddedHaskell = entityHaskell ent , embeddedFields = map toEmbedFieldDef $ filter isHaskellField $ entityFields ent } toEmbedFieldDef :: FieldDef -> EmbedFieldDef toEmbedFieldDef field = EmbedFieldDef { emFieldDB = fieldDB field , emFieldEmbed = case fieldReference field of EmbedRef em -> Just $ Right em SelfReference -> Just $ Left SelfEmbed _ -> Nothing } -- | Type for storing the Uniqueness constraint in the Schema. Assume you have -- the following schema with a uniqueness constraint: -- -- @ -- Person -- name String -- age Int -- UniqueAge age -- @ -- -- This will be represented as: -- -- @ -- UniqueDef -- { uniqueHaskell = ConstraintNameHS (packPTH "UniqueAge") -- , uniqueDBName = ConstraintNameDB (packPTH "unique_age") -- , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))] -- , uniqueAttrs = [] -- } -- @ -- data UniqueDef = UniqueDef { uniqueHaskell :: !ConstraintNameHS , uniqueDBName :: !ConstraintNameDB , uniqueFields :: !(NonEmpty (FieldNameHS, FieldNameDB)) , uniqueAttrs :: ![Attr] } deriving (Show, Eq, Read, Ord, Lift) data CompositeDef = CompositeDef { compositeFields :: !(NonEmpty FieldDef) , compositeAttrs :: ![Attr] } deriving (Show, Eq, Read, Ord, Lift) -- | Used instead of FieldDef -- to generate a smaller amount of code type ForeignFieldDef = (FieldNameHS, FieldNameDB) data ForeignDef = ForeignDef { foreignRefTableHaskell :: !EntityNameHS , foreignRefTableDBName :: !EntityNameDB , foreignConstraintNameHaskell :: !ConstraintNameHS , foreignConstraintNameDBName :: !ConstraintNameDB , foreignFieldCascade :: !FieldCascade -- ^ Determine how the field will cascade on updates and deletions. -- -- @since 2.11.0 , foreignFields :: ![(ForeignFieldDef, ForeignFieldDef)] -- this entity plus the primary entity , foreignAttrs :: ![Attr] , foreignNullable :: Bool , foreignToPrimary :: Bool -- ^ Determines if the reference is towards a Primary Key or not. -- -- @since 2.11.0 } deriving (Show, Eq, Read, Ord, Lift) -- | This datatype describes how a foreign reference field cascades deletes -- or updates. -- -- This type is used in both parsing the model definitions and performing -- migrations. A 'Nothing' in either of the field values means that the -- user has not specified a 'CascadeAction'. An unspecified 'CascadeAction' -- is defaulted to 'Restrict' when doing migrations. -- -- @since 2.11.0 data FieldCascade = FieldCascade { fcOnUpdate :: !(Maybe CascadeAction) , fcOnDelete :: !(Maybe CascadeAction) } deriving (Show, Eq, Read, Ord, Lift) -- | A 'FieldCascade' that does nothing. -- -- @since 2.11.0 noCascade :: FieldCascade noCascade = FieldCascade Nothing Nothing -- | Renders a 'FieldCascade' value such that it can be used in SQL -- migrations. -- -- @since 2.11.0 renderFieldCascade :: FieldCascade -> Text renderFieldCascade (FieldCascade onUpdate onDelete) = T.unwords [ foldMap (mappend " ON DELETE " . renderCascadeAction) onDelete , foldMap (mappend " ON UPDATE " . renderCascadeAction) onUpdate ] -- | An action that might happen on a deletion or update on a foreign key -- change. -- -- @since 2.11.0 data CascadeAction = Cascade | Restrict | SetNull | SetDefault deriving (Show, Eq, Read, Ord, Lift) -- | Render a 'CascadeAction' to 'Text' such that it can be used in a SQL -- command. -- -- @since 2.11.0 renderCascadeAction :: CascadeAction -> Text renderCascadeAction action = case action of Cascade -> "CASCADE" Restrict -> "RESTRICT" SetNull -> "SET NULL" SetDefault -> "SET DEFAULT" data PersistException = PersistError Text -- ^ Generic Exception | PersistMarshalError Text | PersistInvalidField Text | PersistForeignConstraintUnmet Text | PersistMongoDBError Text | PersistMongoDBUnsupported Text deriving Show instance Exception PersistException -- | A SQL data type. Naming attempts to reflect the underlying Haskell -- datatypes, eg SqlString instead of SqlVarchar. Different SQL databases may -- have different translations for these types. data SqlType = SqlString | SqlInt32 | SqlInt64 | SqlReal | SqlNumeric Word32 Word32 | SqlBool | SqlDay | SqlTime | SqlDayTime -- ^ Always uses UTC timezone | SqlBlob | SqlOther T.Text -- ^ a backend-specific name deriving (Show, Read, Eq, Ord, Lift) data PersistFilter = Eq | Ne | Gt | Lt | Ge | Le | In | NotIn | BackendSpecificFilter T.Text deriving (Read, Show, Lift) data UpdateException = KeyNotFound String | UpsertError String instance Show UpdateException where show (KeyNotFound key) = "Key not found during updateGet: " ++ key show (UpsertError msg) = "Error during upsert: " ++ msg instance Exception UpdateException data OnlyUniqueException = OnlyUniqueException String instance Show OnlyUniqueException where show (OnlyUniqueException uniqueMsg) = "Expected only one unique key, got " ++ uniqueMsg instance Exception OnlyUniqueException data PersistUpdate = Assign | Add | Subtract | Multiply | Divide | BackendSpecificUpdate T.Text deriving (Read, Show, Lift) -- | A 'FieldDef' represents the inormation that @persistent@ knows about -- a field of a datatype. This includes information used to parse the field -- out of the database and what the field corresponds to. data FieldDef = FieldDef { fieldHaskell :: !FieldNameHS -- ^ The name of the field. Note that this does not corresponds to the -- record labels generated for the particular entity - record labels -- are generated with the type name prefixed to the field, so -- a 'FieldDef' that contains a @'FieldNameHS' "name"@ for a type -- @User@ will have a record field @userName@. , fieldDB :: !FieldNameDB -- ^ The name of the field in the database. For SQL databases, this -- corresponds to the column name. , fieldType :: !FieldType -- ^ The type of the field in Haskell. , fieldSqlType :: !SqlType -- ^ The type of the field in a SQL database. , fieldAttrs :: ![FieldAttr] -- ^ User annotations for a field. These are provided with the @!@ -- operator. , fieldStrict :: !Bool -- ^ If this is 'True', then the Haskell datatype will have a strict -- record field. The default value for this is 'True'. , fieldReference :: !ReferenceDef , fieldCascade :: !FieldCascade -- ^ Defines how operations on the field cascade on to the referenced -- tables. This doesn't have any meaning if the 'fieldReference' is set -- to 'NoReference' or 'SelfReference'. The cascade option here should -- be the same as the one obtained in the 'fieldReference'. -- -- @since 2.11.0 , fieldComments :: !(Maybe Text) -- ^ Optional comments for a 'Field'. There is not currently a way to -- attach comments to a field in the quasiquoter. -- -- @since 2.10.0 , fieldGenerated :: !(Maybe Text) -- ^ Whether or not the field is a @GENERATED@ column, and additionally -- the expression to use for generation. -- -- @since 2.11.0.0 , fieldIsImplicitIdColumn :: !Bool -- ^ 'True' if the field is an implicit ID column. 'False' otherwise. -- -- @since 2.13.0.0 } deriving (Show, Eq, Read, Ord, Lift)
paul-rouse/persistent
persistent/Database/Persist/Types/Base.hs
mit
23,580
0
16
6,068
2,900
1,733
1,167
363
7
{- | Module : ./CASL/World.hs Description : adding a parameter to ops and preds Copyright : (c) Christian Maeder, DFKI 2012 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable add a parameter like the world sort for Modal CASL -} module CASL.World where import Common.Id import qualified Common.Lib.MapSet as MapSet import CASL.AS_Basic_CASL import CASL.Sign import CASL.Morphism import qualified Data.Map as Map import qualified Data.Set as Set world :: SORT world = genName "World" {- | mixfix identifiers need to be extended by a further place holder. That is, identifiers are renamed, although a wrong number of place holders would allow to use the prefix notation. To avoid a name clashes with existing names the first place holder is preceded by a further place holder and a generated token. -} addPlace :: Id -> Id addPlace i@(Id ts ids ps) | isMixfix i = Id ((\ (x, y) -> x ++ placeTok : genToken "W" : y) (break isPlace ts)) ids ps | otherwise = i -- | the changed mapping addWorld :: Ord a => (a -> a) -> (Id -> Id) -> MapSet.MapSet Id a -> MapSet.MapSet Id a addWorld f ren = MapSet.fromMap . Map.mapKeys ren . MapSet.toMap . MapSet.map f worldOpType :: SORT -> OpType -> OpType worldOpType ws t = t { opArgs = ws : opArgs t} -- | the changed op map addWorldOp :: SORT -> (Id -> Id) -> OpMap -> OpMap addWorldOp = addWorld . worldOpType worldPredType :: SORT -> PredType -> PredType worldPredType ws t = t { predArgs = ws : predArgs t} -- | the changed pred map addWorldPred :: SORT -> (Id -> Id) -> PredMap -> PredMap addWorldPred = addWorld . worldPredType -- | create a predicate name for time, simple and term modalities relOfMod :: Bool -> Bool -> SORT -> Id relOfMod time term m = let s = if time then "T" else "R" in Id [genToken $ if term then s ++ "_t" else s] [m] $ rangeOfId m -- | create a predicate name for simple and term modalities relName :: Bool -> SORT -> Id relName = relOfMod False -- | insert a simple or term modality insertModPred :: SORT -> Bool -> Bool -> Id -> PredMap -> PredMap insertModPred ws time term m = MapSet.insert (relOfMod time term m) $ modPredType ws term m modPredType :: SORT -> Bool -> SORT -> PredType modPredType ws term m = PredType $ (if term then (m :) else id) [ws, ws] -- | the renaming as part of a morphism renMorphism :: Ord a => (Id -> Id) -> MapSet.MapSet Id a -> Map.Map (Id, a) Id renMorphism ren = Map.foldWithKey (\ i s -> let j = ren i in if j == i then id else Map.union . Map.fromAscList . map (\ a -> ((j, a), j)) $ Set.toList s) Map.empty . MapSet.toMap renOpMorphism :: (Id -> Id) -> OpMap -> Op_map renOpMorphism ren = Map.mapWithKey (\ (_, t) i -> (i, opKind t)) . renMorphism ren renPredMorphism :: (Id -> Id) -> PredMap -> Pred_map renPredMorphism = renMorphism
spechub/Hets
CASL/World.hs
gpl-2.0
2,922
0
18
631
866
464
402
48
3
{-| Description : This module converts Verigraph into Partitions structures. Maintainer : Andrei Costa <[email protected]> -} module Data.TypedGraph.Partition.FromVerigraph ( createDisjointUnion, createSatisfyingNacsDisjointUnion ) where import Data.Graphs as G import Data.Graphs.Morphism as GM import Data.TypedGraph as TG import Data.TypedGraph.Morphism as TGM import qualified Data.TypedGraph.Partition.Types as GP -- | The starting integer id for the generated elements. startId :: Int startId = 0 -- | Creates the disjoint union of two verigraph graphs in 'GraphPartition' format createDisjointUnion :: (TypedGraph a b,Bool) -> (TypedGraph a b,Bool) -> GP.Graph createDisjointUnion (g1,inj1) (g2,inj2) = disjointUnionGraphs left right where nodes = fst edges = snd injectiveLeft = if inj1 then (G.nodeIds (GM.domainGraph g1), G.edgeIds (GM.domainGraph g1)) else ([],[]) injectiveRight = if inj2 then (G.nodeIds (GM.domainGraph g2), G.edgeIds (GM.domainGraph g2)) else ([],[]) (left,nextId) = graphMorphismToPartitionGraph injectiveLeft g1 True startId (right,_) = graphMorphismToPartitionGraph injectiveRight g2 False nextId disjointUnionGraphs a b = (nodes a ++ nodes b, edges a ++ edges b) -- | Creates the disjoint union of two verigraph graphs for a right graph and a nac in 'GraphPartition' format createSatisfyingNacsDisjointUnion :: (TypedGraph a b,Bool) -> (TypedGraphMorphism a b,Bool) -> GP.Graph createSatisfyingNacsDisjointUnion (g,injG) (n,injN) = disjointUnionGraphs left right where nodes = fst edges = snd injNodes = filter (\x -> (all (\n' -> TGM.applyNodeIdUnsafe n n' /= x) (TG.nodeIds $ TGM.domainGraph n))) (TG.nodeIds $ TGM.codomainGraph n) injEdges = filter (\x -> (all (\e' -> TGM.applyEdgeIdUnsafe n e' /= x) (TG.edgeIds $ TGM.domainGraph n))) (TG.edgeIds $ TGM.codomainGraph n) injectiveR = if injG then (G.nodeIds (GM.domainGraph g), G.edgeIds (GM.domainGraph g)) else ([],[]) injectiveN = if injN then (TG.nodeIds $ TGM.codomainGraph n, TG.edgeIds $ TGM.codomainGraph n) else (injNodes, injEdges) (left,nextId) = graphMorphismToPartitionGraph injectiveR g True startId (right,_) = graphMorphismToPartitionGraph injectiveN (TGM.codomainGraph n) False nextId disjointUnionGraphs a b = (nodes a ++ nodes b, edges a ++ edges b) graphMorphismToPartitionGraph :: ([NodeId],[EdgeId]) -> GraphMorphism (Maybe a) (Maybe b) -> Bool -> Int -> (GP.Graph,Int) graphMorphismToPartitionGraph inj@(injNodes,_) morfL side id = ((nodes',edges'), nextId) where graphL = GM.domainGraph morfL nodes_ = zip (G.nodeIds graphL) [id..] nodes' = map (nodeToPartitionNode injNodes morfL side) nodes_ edges_ = zip (G.edges graphL) [id..] edges' = map (edgeToPartitionEdge inj morfL side) edges_ nextId = max (length nodes') (length edges') nodeToPartitionNode :: [NodeId] -> TypedGraph a b -> Bool -> (NodeId,Int) -> GP.Node nodeToPartitionNode injNodes tg side (NodeId b,id) = GP.Node n b id flag side where NodeId n = GM.applyNodeIdUnsafe tg (NodeId b) flag = NodeId b `elem` injNodes edgeToPartitionEdge :: ([NodeId],[EdgeId]) -> TypedGraph a b -> Bool -> (Edge (Maybe b),Int) -> GP.Edge edgeToPartitionEdge (injNodes,injEdges) tg side (e,id) = GP.Edge typ edgeNumber id src tgt flag side where EdgeId edgeNumber = edgeId e EdgeId typ = GM.applyEdgeIdUnsafe tg (edgeId e) src = GP.Node n1 src_ (-1) flagSrc side NodeId src_ = sourceId e tgt = GP.Node n2 tgt_ (-1) flagTgt side NodeId tgt_ = targetId e NodeId n1 = GM.applyNodeIdUnsafe tg (NodeId src_) NodeId n2 = GM.applyNodeIdUnsafe tg (NodeId tgt_) flag = edgeId e `elem` injEdges flagSrc = NodeId src_ `elem` injNodes flagTgt = NodeId tgt_ `elem` injNodes
rodrigo-machado/verigraph
src/library/Data/TypedGraph/Partition/FromVerigraph.hs
gpl-3.0
3,912
0
16
791
1,354
725
629
56
3
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE TemplateHaskell #-} module Foreign.CUDA.Cusparse.Types where import Foreign.CUDA.Cublas.THBase $(doIO $ makeTypes "cusparse" cusparseFile)
kathawala/symdiff
cublas/Foreign/CUDA/Cusparse-bak/Types.hs
gpl-3.0
197
0
8
21
33
20
13
5
0
{-# LANGUAGE ExistentialQuantification,DeriveDataTypeable #-} -- | This module provides typed channels, an alternative -- approach to interprocess messaging. Typed channels -- can be used in combination with or instead of the -- the untyped channels available in the "Remote.Process" -- module via 'send'. module Remote.Channel ( -- * Basic typed channels SendPort,ReceivePort,newChannel,sendChannel,receiveChannel, -- * Combined typed channels CombinedChannelAction,combinedChannelAction, combinePortsBiased,combinePortsRR,mergePortsBiased,mergePortsRR, -- * Terminate a channel terminateChannel) where import Remote.Process (ProcessM,send,getMessageType,getMessagePayload,setDaemonic,getProcess,prNodeRef,getNewMessageLocal,localFromPid,isPidLocal,TransmitException(..),TransmitStatus(..),spawnLocalAnd,ProcessId,Node,UnknownMessageException(..)) import Remote.Encoding (Serializable) import Data.List (foldl') import Data.Binary (Binary,get,put) import Data.Typeable (Typeable) import Control.Exception (throw) import Control.Monad (when) import Control.Monad.Trans (liftIO) import Control.Concurrent.MVar (MVar,newEmptyMVar,takeMVar,readMVar,putMVar) import Control.Concurrent.STM (STM,atomically,retry,orElse) import Control.Concurrent.STM.TVar (TVar,newTVarIO,readTVar,writeTVar) ---------------------------------------------- -- * Channels ---------------------------------------------- -- | A channel is a unidirectional communication pipeline -- with two ends: a sending port, and a receiving port. -- This is the sending port. A process holding this -- value can insert messages into the channel. SendPorts -- themselves can also be sent to other processes. -- The other side of the channel is the 'ReceivePort'. newtype SendPort a = SendPort ProcessId deriving (Typeable) -- | A process holding a ReceivePort can extract messages -- from the channel, which we inserted by -- the holder(s) of the corresponding 'SendPort'. -- Critically, ReceivePorts, unlike SendPorts, are not serializable. -- This means that you can only receive messages through a channel -- on the node on which the channel was created. data ReceivePort a = ReceivePortSimple ProcessId (MVar ()) | ReceivePortBiased [Node -> STM a] | ReceivePortRR (TVar [Node -> STM a]) instance Binary (SendPort a) where put (SendPort pid) = put pid get = get >>= return . SendPort -- | Create a new channel, and returns both the 'SendPort' -- and 'ReceivePort' thereof. newChannel :: (Serializable a) => ProcessM (SendPort a, ReceivePort a) newChannel = do mv <- liftIO $ newEmptyMVar pid <- spawnLocalAnd (body mv) setDaemonic return (SendPort pid, ReceivePortSimple pid mv) where body mv = liftIO (takeMVar mv) -- | Inserts a new value into the channel. sendChannel :: (Serializable a) => SendPort a -> a -> ProcessM () sendChannel (SendPort pid) a = send pid a -- | Extract a value from the channel, in FIFO order. receiveChannel :: (Serializable a) => ReceivePort a -> ProcessM a receiveChannel rc = do p <- getProcess channelCheckPids [rc] node <- liftIO $ readMVar (prNodeRef p) liftIO $ atomically $ receiveChannelImpl node rc receiveChannelImpl :: (Serializable a) => Node -> ReceivePort a -> STM a receiveChannelImpl node rc = case rc of ReceivePortBiased l -> foldl' orElse retry (map (\x -> x node) l) ReceivePortRR mv -> do tv <- readTVar mv writeTVar mv (rotate tv) foldl' orElse retry (map (\x -> x node) tv) ReceivePortSimple _ _ -> receiveChannelSimple node rc where rotate [] = [] rotate (h:t) = t ++ [h] data CombinedChannelAction b = forall a. (Serializable a) => CombinedChannelAction (ReceivePort a) (a -> b) -- | Specifies a port and an adapter for combining ports via 'combinePortsBiased' and -- 'combinePortsRR'. combinedChannelAction :: (Serializable a) => ReceivePort a -> (a -> b) -> CombinedChannelAction b combinedChannelAction = CombinedChannelAction -- | This function lets us respond to messages on multiple channels -- by combining several 'ReceivePort's into one. The resulting port -- is the sum of the input ports, and will extract messages from all -- of them in FIFO order. The input ports are specified by -- 'combinedChannelAction', which also gives a converter function. -- After combining the underlying receive ports can still -- be used independently, as well. -- We provide two ways to combine ports, which differ bias -- they demonstrate in returning messages when more than one -- underlying channel is nonempty. combinePortsBiased will -- check ports in the order given by its argument, and so -- if the first channel always was a message waiting, it will. -- starve the other channels. The alternative is 'combinePortsRR'. combinePortsBiased :: Serializable b => [CombinedChannelAction b] -> ProcessM (ReceivePort b) combinePortsBiased chns = do mapM_ (\(CombinedChannelAction chn _ ) -> channelCheckPids [chn]) chns return $ ReceivePortBiased [(\node -> receiveChannelImpl node chn >>= return . fun) | (CombinedChannelAction chn fun) <- chns] -- | See 'combinePortsBiased'. This function differs from that one -- in that the order that the underlying ports are checked is rotated -- with each invocation, guaranteeing that, given enough invocations, -- every channel will have a chance to contribute a message. combinePortsRR :: Serializable b => [CombinedChannelAction b] -> ProcessM (ReceivePort b) combinePortsRR chns = do mapM_ (\(CombinedChannelAction chn _ ) -> channelCheckPids [chn]) chns tv <- liftIO $ newTVarIO [(\node -> receiveChannelImpl node chn >>= return . fun) | (CombinedChannelAction chn fun) <- chns] return $ ReceivePortRR tv -- | Similar to 'combinePortsBiased', with the difference that the -- the underlying ports must be of the same type, and you don't -- have the opportunity to provide an adapter function. mergePortsBiased :: (Serializable a) => [ReceivePort a] -> ProcessM (ReceivePort a) mergePortsBiased chns = do channelCheckPids chns return $ ReceivePortBiased [(\node -> receiveChannelImpl node chn) | chn <- chns] -- | Similar to 'combinePortsRR', with the difference that the -- the underlying ports must be of the same type, and you don't -- have the opportunity to provide an adapter function. mergePortsRR :: (Serializable a) => [ReceivePort a] -> ProcessM (ReceivePort a) mergePortsRR chns = do channelCheckPids chns tv <- liftIO $ newTVarIO [(\node -> receiveChannelImpl node chn) | chn <- chns] return $ ReceivePortRR tv channelCheckPids :: (Serializable a) => [ReceivePort a] -> ProcessM () channelCheckPids chns = mapM_ checkPid chns where checkPid (ReceivePortSimple pid _) = do islocal <- isPidLocal pid when (not islocal) (throw $ TransmitException QteUnknownPid) checkPid _ = return () receiveChannelSimple :: (Serializable a) => Node -> ReceivePort a -> STM a receiveChannelSimple node (ReceivePortSimple chpid _) = do mmsg <- getNewMessageLocal (node) (localFromPid chpid) case mmsg of Nothing -> badPid Just msg -> case getMessagePayload msg of Nothing -> throw $ UnknownMessageException (getMessageType msg) Just q -> return q where badPid = throw $ TransmitException QteUnknownPid -- | Terminate a channel. After calling this function, 'receiveChannel' -- on that port (or on any combined port based on it) will either -- fail or block indefinitely, and 'sendChannel' on the corresponding -- 'SendPort' will fail. Any unread messages remaining in the channel -- will be lost. terminateChannel :: (Serializable a) => ReceivePort a -> ProcessM () terminateChannel (ReceivePortSimple _ term) = liftIO $ putMVar (term) () terminateChannel _ = throw $ TransmitException QteUnknownPid
jepst/CloudHaskell
Remote/Channel.hs
bsd-3-clause
8,558
0
16
2,080
1,680
894
786
82
4
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[Simplify]{The main module of the simplifier} -} {-# LANGUAGE CPP #-} module Eta.SimplCore.Simplify ( simplTopBinds, simplExpr, simplRules ) where #include "HsVersions.h" import Eta.Main.DynFlags import Eta.SimplCore.SimplMonad import Eta.Types.Type hiding ( substTy, extendTvSubst, substTyVar ) import Eta.SimplCore.SimplEnv import Eta.SimplCore.SimplUtils import Eta.Types.FamInstEnv ( FamInstEnv ) import Eta.BasicTypes.Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326 import Eta.BasicTypes.Id import Eta.BasicTypes.MkId ( seqId, voidPrimId ) import Eta.Core.MkCore ( mkImpossibleExpr, castBottomExpr ) import Eta.BasicTypes.IdInfo import Eta.BasicTypes.Name ( Name, mkSystemVarName, isExternalName ) import Eta.Types.Coercion hiding ( substCo, substTy, substCoVar, extendTvSubst ) import Eta.Types.OptCoercion ( optCoercion ) import Eta.Types.FamInstEnv ( topNormaliseType_maybe ) import Eta.BasicTypes.DataCon ( DataCon, dataConWorkId, dataConRepStrictness , isMarkedStrict ) --, dataConTyCon, dataConTag, fIRST_TAG ) --import Eta.Types.TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326 import Eta.SimplCore.CoreMonad ( Tick(..), SimplifierMode(..) ) import Eta.Core.CoreSyn import Eta.BasicTypes.Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd ) import Eta.Core.PprCore ( pprCoreExpr ) import Eta.Core.CoreUnfold import Eta.Core.CoreUtils import Eta.Core.CoreArity --import Eta.Prelude.PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326 import Eta.Specialise.Rules ( mkRuleInfo, lookupRule, getRules ) import Eta.Prelude.TysPrim ( voidPrimTy ) --, intPrimTy ) -- temporalily commented out. See #8326 import Eta.BasicTypes.BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) ) import Eta.Utils.MonadUtils ( foldlM, mapAccumLM, liftIO ) import Eta.Utils.Maybes ( orElse ) --import Eta.BasicTypes.Unique ( hasKey ) -- temporalily commented out. See #8326 import Control.Monad import Eta.Utils.Outputable import Eta.Utils.FastString import Eta.Utils.Pair import Eta.Utils.Util import Eta.Main.ErrUtils {- The guts of the simplifier is in this module, but the driver loop for the simplifier is in SimplCore.lhs. ----------------------------------------- *** IMPORTANT NOTE *** ----------------------------------------- The simplifier used to guarantee that the output had no shadowing, but it does not do so any more. (Actually, it never did!) The reason is documented with simplifyArgs. ----------------------------------------- *** IMPORTANT NOTE *** ----------------------------------------- Many parts of the simplifier return a bunch of "floats" as well as an expression. This is wrapped as a datatype SimplUtils.FloatsWith. All "floats" are let-binds, not case-binds, but some non-rec lets may be unlifted (with RHS ok-for-speculation). ----------------------------------------- ORGANISATION OF FUNCTIONS ----------------------------------------- simplTopBinds - simplify all top-level binders - for NonRec, call simplRecOrTopPair - for Rec, call simplRecBind ------------------------------ simplExpr (applied lambda) ==> simplNonRecBind simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind ------------------------------ simplRecBind [binders already simplfied] - use simplRecOrTopPair on each pair in turn simplRecOrTopPair [binder already simplified] Used for: recursive bindings (top level and nested) top-level non-recursive bindings Returns: - check for PreInlineUnconditionally - simplLazyBind simplNonRecBind Used for: non-top-level non-recursive bindings beta reductions (which amount to the same thing) Because it can deal with strict arts, it takes a "thing-inside" and returns an expression - check for PreInlineUnconditionally - simplify binder, including its IdInfo - if strict binding simplStrictArg mkAtomicArgs completeNonRecX else simplLazyBind addFloats simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder] Used for: binding case-binder and constr args in a known-constructor case - check for PreInLineUnconditionally - simplify binder - completeNonRecX ------------------------------ simplLazyBind: [binder already simplified, RHS not] Used for: recursive bindings (top level and nested) top-level non-recursive bindings non-top-level, but *lazy* non-recursive bindings [must not be strict or unboxed] Returns floats + an augmented environment, not an expression - substituteIdInfo and add result to in-scope [so that rules are available in rec rhs] - simplify rhs - mkAtomicArgs - float if exposes constructor or PAP - completeBind completeNonRecX: [binder and rhs both simplified] - if the the thing needs case binding (unlifted and not ok-for-spec) build a Case else completeBind addFloats completeBind: [given a simplified RHS] [used for both rec and non-rec bindings, top level and not] - try PostInlineUnconditionally - add unfolding [this is the only place we add an unfolding] - add arity Right hand sides and arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In many ways we want to treat (a) the right hand side of a let(rec), and (b) a function argument in the same way. But not always! In particular, we would like to leave these arguments exactly as they are, so they will match a RULE more easily. f (g x, h x) g (+ x) It's harder to make the rule match if we ANF-ise the constructor, or eta-expand the PAP: f (let { a = g x; b = h x } in (a,b)) g (\y. + x y) On the other hand if we see the let-defns p = (g x, h x) q = + x then we *do* want to ANF-ise and eta-expand, so that p and q can be safely inlined. Even floating lets out is a bit dubious. For let RHS's we float lets out if that exposes a value, so that the value can be inlined more vigorously. For example r = let x = e in (x,x) Here, if we float the let out we'll expose a nice constructor. We did experiments that showed this to be a generally good thing. But it was a bad thing to float lets out unconditionally, because that meant they got allocated more often. For function arguments, there's less reason to expose a constructor (it won't get inlined). Just possibly it might make a rule match, but I'm pretty skeptical. So for the moment we don't float lets out of function arguments either. Eta expansion ~~~~~~~~~~~~~~ For eta expansion, we want to catch things like case e of (a,b) -> \x -> case a of (p,q) -> \y -> r If the \x was on the RHS of a let, we'd eta expand to bring the two lambdas together. And in general that's a good thing to do. Perhaps we should eta expand wherever we find a (value) lambda? Then the eta expansion at a let RHS can concentrate solely on the PAP case. ************************************************************************ * * \subsection{Bindings} * * ************************************************************************ -} simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv simplTopBinds env0 binds0 = do { -- Put all the top-level binders into scope at the start -- so that if a transformation rule has unexpectedly brought -- anything into scope, then we don't get a complaint about that. -- It's rather as if the top-level binders were imported. -- See note [Glomming] in OccurAnal. ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0) ; env2 <- simpl_binds env1 binds0 ; freeTick SimplifierDone ; return env2 } where -- We need to track the zapped top-level binders, because -- they should have their fragile IdInfo zapped (notably occurrence info) -- That's why we run down binds and bndrs' simultaneously. -- simpl_binds :: SimplEnv -> [InBind] -> SimplM SimplEnv simpl_binds env [] = return env simpl_binds env (bind:binds) = do { env' <- simpl_bind env bind ; simpl_binds env' binds } simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs simpl_bind env (NonRec b r) = do { (env', b') <- addBndrRules env b (lookupRecBndr env b) ; simplRecOrTopPair env' TopLevel NonRecursive b b' r } {- ************************************************************************ * * \subsection{Lazy bindings} * * ************************************************************************ simplRecBind is used for * recursive bindings only -} simplRecBind :: SimplEnv -> TopLevelFlag -> [(InId, InExpr)] -> SimplM SimplEnv simplRecBind env0 top_lvl pairs0 = do { (env_with_info, triples) <- mapAccumLM add_rules env0 pairs0 ; env1 <- go (zapFloats env_with_info) triples ; return (env0 `addRecFloats` env1) } -- addFloats adds the floats from env1, -- _and_ updates env0 with the in-scope set from env1 where add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr)) -- Add the (substituted) rules to the binder add_rules env (bndr, rhs) = do { (env', bndr') <- addBndrRules env bndr (lookupRecBndr env bndr) ; return (env', (bndr, bndr', rhs)) } go env [] = return env go env ((old_bndr, new_bndr, rhs) : pairs) = do { env' <- simplRecOrTopPair env top_lvl Recursive old_bndr new_bndr rhs ; go env' pairs } {- simplOrTopPair is used for * recursive bindings (whether top level or not) * top-level non-recursive bindings It assumes the binder has already been simplified, but not its IdInfo. -} simplRecOrTopPair :: SimplEnv -> TopLevelFlag -> RecFlag -> InId -> OutBndr -> InExpr -- Binder and rhs -> SimplM SimplEnv -- Returns an env that includes the binding simplRecOrTopPair env top_lvl is_rec old_bndr new_bndr rhs = do { dflags <- getDynFlags ; trace_bind dflags $ if preInlineUnconditionally dflags env top_lvl old_bndr rhs -- Check for unconditional inline then do tick (PreInlineUnconditionally old_bndr) return (extendIdSubst env old_bndr (mkContEx env rhs)) else simplLazyBind env top_lvl is_rec old_bndr new_bndr rhs env } where trace_bind dflags thing_inside | not (dopt Opt_D_verbose_core2core dflags) = thing_inside | otherwise = pprTrace "SimplBind" (ppr old_bndr) thing_inside -- trace_bind emits a trace for each top-level binding, which -- helps to locate the tracing for inlining and rule firing {- simplLazyBind is used for * [simplRecOrTopPair] recursive bindings (whether top level or not) * [simplRecOrTopPair] top-level non-recursive bindings * [simplNonRecE] non-top-level *lazy* non-recursive bindings Nota bene: 1. It assumes that the binder is *already* simplified, and is in scope, and its IdInfo too, except unfolding 2. It assumes that the binder type is lifted. 3. It does not check for pre-inline-unconditionally; that should have been done already. -} simplLazyBind :: SimplEnv -> TopLevelFlag -> RecFlag -> InId -> OutId -- Binder, both pre-and post simpl -- The OutId has IdInfo, except arity, unfolding -> InExpr -> SimplEnv -- The RHS and its environment -> SimplM SimplEnv -- Precondition: rhs obeys the let/app invariant simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $ do { let rhs_env = rhs_se `setInScope` env (tvs, body) = case collectTyBinders rhs of (tvs, body) | not_lam body -> (tvs,body) | otherwise -> ([], rhs) not_lam (Lam _ _) = False not_lam (Tick t e) | not (tickishFloatable t) = not_lam e -- eta-reduction could float not_lam _ = True -- Do not do the "abstract tyyvar" thing if there's -- a lambda inside, because it defeats eta-reduction -- f = /\a. \x. g a x -- should eta-reduce. ; (body_env, tvs') <- simplBinders rhs_env tvs -- See Note [Floating and type abstraction] in SimplUtils -- Simplify the RHS ; let rhs_cont = mkRhsStop (substTy body_env (exprType body)) ; (body_env1, body1) <- simplExprF body_env body rhs_cont -- ANF-ise a constructor or PAP rhs ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1 ; (env', rhs') <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2) then -- No floating, revert to body1 do { rhs' <- mkLam tvs' (wrapFloats body_env1 body1) rhs_cont ; return (env, rhs') } else if null tvs then -- Simple floating do { tick LetFloatFromLet ; return (addFloats env body_env2, body2) } else -- Do type-abstraction first do { tick LetFloatFromLet ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2 ; rhs' <- mkLam tvs' body3 rhs_cont ; env' <- foldlM (addPolyBind top_lvl) env poly_binds ; return (env', rhs') } ; completeBind env' top_lvl bndr bndr1 rhs' } {- A specialised variant of simplNonRec used when the RHS is already simplified, notably in knownCon. It uses case-binding where necessary. -} simplNonRecX :: SimplEnv -> InId -- Old binder -> OutExpr -- Simplified RHS -> SimplM SimplEnv -- Precondition: rhs satisfies the let/app invariant simplNonRecX env bndr new_rhs | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of c { (p,q) -> p } = return env -- Here c is dead, and we avoid creating -- the binding c = (a,b) | Coercion co <- new_rhs = return (extendCvSubst env bndr co) | otherwise = do { (env', bndr') <- simplBinder env bndr ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs } -- simplNonRecX is only used for NotTopLevel things completeNonRecX :: TopLevelFlag -> SimplEnv -> Bool -> InId -- Old binder -> OutId -- New binder -> OutExpr -- Simplified RHS -> SimplM SimplEnv -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs = do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs ; (env2, rhs2) <- if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1 then do { tick LetFloatFromLet ; return (addFloats env env1, rhs1) } -- Add the floats to the main env else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 } {- {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX Doing so risks exponential behaviour, because new_rhs has been simplified once already In the cases described by the folowing commment, postInlineUnconditionally will catch many of the relevant cases. -- This happens; for example, the case_bndr during case of -- known constructor: case (a,b) of x { (p,q) -> ... } -- Here x isn't mentioned in the RHS, so we don't want to -- create the (dead) let-binding let x = (a,b) in ... -- -- Similarly, single occurrences can be inlined vigourously -- e.g. case (f x, g y) of (a,b) -> .... -- If a,b occur once we can avoid constructing the let binding for them. Furthermore in the case-binding case preInlineUnconditionally risks extra thunks -- Consider case I# (quotInt# x y) of -- I# v -> let w = J# v in ... -- If we gaily inline (quotInt# x y) for v, we end up building an -- extra thunk: -- let w = J# (quotInt# x y) in ... -- because quotInt# can fail. | preInlineUnconditionally env NotTopLevel bndr new_rhs = thing_inside (extendIdSubst env bndr (DoneEx new_rhs)) -} ---------------------------------- prepareRhs takes a putative RHS, checks whether it's a PAP or constructor application and, if so, converts it to ANF, so that the resulting thing can be inlined more easily. Thus x = (f a, g b) becomes t1 = f a t2 = g b x = (t1,t2) We also want to deal well cases like this v = (f e1 `cast` co) e2 Here we want to make e1,e2 trivial and get x1 = e1; x2 = e2; v = (f x1 `cast` co) v2 That's what the 'go' loop in prepareRhs does -} prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr) -- Adds new floats to the env iff that allows us to return a good RHS prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions] | Pair ty1 _ty2 <- coercionKind co -- Do *not* do this if rhs has an unlifted type , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)] = do { (env', rhs') <- makeTrivialWithInfo top_lvl env sanitised_info rhs ; return (env', Cast rhs' co) } where sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info `setDemandInfo` demandInfo info info = idInfo id prepareRhs top_lvl env0 _ rhs0 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0 ; return (env1, rhs1) } where go n_val_args env (Cast rhs co) = do { (is_exp, env', rhs') <- go n_val_args env rhs ; return (is_exp, env', Cast rhs' co) } go n_val_args env (App fun (Type ty)) = do { (is_exp, env', rhs') <- go n_val_args env fun ; return (is_exp, env', App rhs' (Type ty)) } go n_val_args env (App fun arg) = do { (is_exp, env', fun') <- go (n_val_args+1) env fun ; case is_exp of True -> do { (env'', arg') <- makeTrivial top_lvl env' arg ; return (True, env'', App fun' arg') } False -> return (False, env, App fun arg) } go n_val_args env (Var fun) = return (is_exp, env, Var fun) where is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP -- See Note [CONLIKE pragma] in BasicTypes -- The definition of is_exp should match that in -- OccurAnal.occAnalApp go n_val_args env (Tick t rhs) -- We want to be able to float bindings past this -- tick. Non-scoping ticks don't care. | tickishScoped t == NoScope = do { (is_exp, env', rhs') <- go n_val_args env rhs ; return (is_exp, env', Tick t rhs') } -- On the other hand, for scoping ticks we need to be able to -- copy them on the floats, which in turn is only allowed if -- we can obtain non-counting ticks. | not (tickishCounts t) || tickishCanSplit t = do { (is_exp, env', rhs') <- go n_val_args (zapFloats env) rhs ; let tickIt (id, expr) = (id, mkTick (mkNoCount t) expr) floats' = seFloats $ env `addFloats` mapFloats env' tickIt ; return (is_exp, env' { seFloats = floats' }, Tick t rhs') } go _ env other = return (False, env, other) {- Note [Float coercions] ~~~~~~~~~~~~~~~~~~~~~~ When we find the binding x = e `cast` co we'd like to transform it to x' = e x = x `cast` co -- A trivial binding There's a chance that e will be a constructor application or function, or something like that, so moving the coerion to the usage site may well cancel the coersions and lead to further optimisation. Example: data family T a :: * data instance T Int = T Int foo :: Int -> Int -> Int foo m n = ... where x = T m go 0 = 0 go n = case x of { T m -> go (n-m) } -- This case should optimise Note [Preserve strictness when floating coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the Note [Float coercions] transformation, keep the strictness info. Eg f = e `cast` co -- f has strictness SSL When we transform to f' = e -- f' also has strictness SSL f = f' `cast` co -- f still has strictness SSL Its not wrong to drop it on the floor, but better to keep it. Note [Float coercions (unlifted)] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BUT don't do [Float coercions] if 'e' has an unlifted type. This *can* happen: foo :: Int = (error (# Int,Int #) "urk") `cast` CoUnsafe (# Int,Int #) Int If do the makeTrivial thing to the error call, we'll get foo = case error (# Int,Int #) "urk" of v -> v `cast` ... But 'v' isn't in scope! These strange casts can happen as a result of case-of-case bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of (# p,q #) -> p+q -} makeTrivialArg :: SimplEnv -> ArgSpec -> SimplM (SimplEnv, ArgSpec) makeTrivialArg env (ValArg e) = do { (env', e') <- makeTrivial NotTopLevel env e ; return (env', ValArg e') } makeTrivialArg env arg = return (env, arg) -- CastBy, TyArg makeTrivial :: TopLevelFlag -> SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr) -- Binds the expression to a variable, if it's not trivial, returning the variable makeTrivial top_lvl env expr = makeTrivialWithInfo top_lvl env vanillaIdInfo expr makeTrivialWithInfo :: TopLevelFlag -> SimplEnv -> IdInfo -> OutExpr -> SimplM (SimplEnv, OutExpr) -- Propagate strictness and demand info to the new binder -- Note [Preserve strictness when floating coercions] -- Returned SimplEnv has same substitution as incoming one makeTrivialWithInfo top_lvl env info expr | exprIsTrivial expr -- Already trivial || not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise -- See Note [Cannot trivialise] = return (env, expr) | otherwise -- See Note [Take care] below = do { uniq <- getUniqueM ; let name = mkSystemVarName uniq (fsLit "a") var = mkLocalIdWithInfo name expr_ty info ; env' <- completeNonRecX top_lvl env False var var expr ; expr' <- simplVar env' var ; return (env', expr') } -- The simplVar is needed becase we're constructing a new binding -- a = rhs -- And if rhs is of form (rhs1 |> co), then we might get -- a1 = rhs1 -- a = a1 |> co -- and now a's RHS is trivial and can be substituted out, and that -- is what completeNonRecX will do -- To put it another way, it's as if we'd simplified -- let var = e in var where expr_ty = exprType expr bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool -- True iff we can have a binding of this expression at this level -- Precondition: the type is the type of the expression bindingOk top_lvl _ expr_ty | isTopLevel top_lvl = not (isUnLiftedType expr_ty) | otherwise = True {- Note [Cannot trivialise] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider tih f :: Int -> Addr# foo :: Bar foo = Bar (f 3) Then we can't ANF-ise foo, even though we'd like to, because we can't make a top-level binding for the Addr# (f 3). And if so we don't want to turn it into foo = let x = f 3 in Bar x because we'll just end up inlining x back, and that makes the simplifier loop. Better not to ANF-ise it at all. A case in point is literal strings (a MachStr is not regarded as trivial): foo = Ptr "blob"# We don't want to ANF-ise this. ************************************************************************ * * \subsection{Completing a lazy binding} * * ************************************************************************ completeBind * deals only with Ids, not TyVars * takes an already-simplified binder and RHS * is used for both recursive and non-recursive bindings * is used for both top-level and non-top-level bindings It does the following: - tries discarding a dead binding - tries PostInlineUnconditionally - add unfolding [this is the only place we add an unfolding] - add arity It does *not* attempt to do let-to-case. Why? Because it is used for - top-level bindings (when let-to-case is impossible) - many situations where the "rhs" is known to be a WHNF (so let-to-case is inappropriate). Nor does it do the atomic-argument thing -} completeBind :: SimplEnv -> TopLevelFlag -- Flag stuck into unfolding -> InId -- Old binder -> OutId -> OutExpr -- New binder and RHS -> SimplM SimplEnv -- completeBind may choose to do its work -- * by extending the substitution (e.g. let x = y in ...) -- * or by adding to the floats in the envt -- -- Precondition: rhs obeys the let/app invariant completeBind env top_lvl old_bndr new_bndr new_rhs | isCoVar old_bndr = case new_rhs of Coercion co -> return (extendCvSubst env old_bndr co) _ -> return (addNonRec env new_bndr new_rhs) | otherwise = ASSERT( isId new_bndr ) do { let old_info = idInfo old_bndr old_unf = unfoldingInfo old_info occ_info = occInfo old_info -- Do eta-expansion on the RHS of the binding -- See Note [Eta-expanding at let bindings] in SimplUtils ; (new_arity, final_rhs) <- tryEtaExpandRhs env new_bndr new_rhs -- Simplify the unfolding ; new_unfolding <- simplLetUnfolding env top_lvl old_bndr final_rhs old_unf ; dflags <- getDynFlags ; if postInlineUnconditionally dflags env top_lvl new_bndr occ_info final_rhs new_unfolding -- Inline and discard the binding then do { tick (PostInlineUnconditionally old_bndr) ; return (extendIdSubst env old_bndr (DoneEx final_rhs)) } -- Use the substitution to make quite, quite sure that the -- substitution will happen, since we are going to discard the binding else do { let info1 = idInfo new_bndr `setArityInfo` new_arity -- Unfolding info: Note [Setting the new unfolding] info2 = info1 `setUnfoldingInfo` new_unfolding -- Demand info: Note [Setting the demand info] -- -- We also have to nuke demand info if for some reason -- eta-expansion *reduces* the arity of the binding to less -- than that of the strictness sig. This can happen: see Note [Arity decrease]. info3 | isEvaldUnfolding new_unfolding || (case strictnessInfo info2 of StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty) = zapDemandInfo info2 `orElse` info2 | otherwise = info2 final_id = new_bndr `setIdInfo` info3 ; -- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $ return (addNonRec env final_id final_rhs) } } -- The addNonRec adds it to the in-scope set too ------------------------------ addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv -- Add a new binding to the environment, complete with its unfolding -- but *do not* do postInlineUnconditionally, because we have already -- processed some of the scope of the binding -- We still want the unfolding though. Consider -- let -- x = /\a. let y = ... in Just y -- in body -- Then we float the y-binding out (via abstractFloats and addPolyBind) -- but 'x' may well then be inlined in 'body' in which case we'd like the -- opportunity to inline 'y' too. -- -- INVARIANT: the arity is correct on the incoming binders addPolyBind top_lvl env (NonRec poly_id rhs) = do { unfolding <- simplLetUnfolding env top_lvl poly_id rhs noUnfolding -- Assumes that poly_id did not have an INLINE prag -- which is perhaps wrong. ToDo: think about this ; let final_id = setIdInfo poly_id $ idInfo poly_id `setUnfoldingInfo` unfolding ; return (addNonRec env final_id rhs) } addPolyBind _ env bind@(Rec _) = return (extendFloats env bind) -- Hack: letrecs are more awkward, so we extend "by steam" -- without adding unfoldings etc. At worst this leads to -- more simplifier iterations {- Note [Arity decrease] ~~~~~~~~~~~~~~~~~~~~~~~~ Generally speaking the arity of a binding should not decrease. But it *can* legitimately happen because of RULES. Eg f = g Int where g has arity 2, will have arity 2. But if there's a rewrite rule g Int --> h where h has arity 1, then f's arity will decrease. Here's a real-life example, which is in the output of Specialise: Rec { $dm {Arity 2} = \d.\x. op d {-# RULES forall d. $dm Int d = $s$dm #-} dInt = MkD .... opInt ... opInt {Arity 1} = $dm dInt $s$dm {Arity 0} = \x. op dInt } Here opInt has arity 1; but when we apply the rule its arity drops to 0. That's why Specialise goes to a little trouble to pin the right arity on specialised functions too. Note [Setting the demand info] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the unfolding is a value, the demand info may go pear-shaped, so we nuke it. Example: let x = (a,b) in case x of (p,q) -> h p q x Here x is certainly demanded. But after we've nuked the case, we'll get just let x = (a,b) in h a b x and now x is not demanded (I'm assuming h is lazy) This really happens. Similarly let f = \x -> e in ...f..f... After inlining f at some of its call sites the original binding may (for example) be no longer strictly demanded. The solution here is a bit ad hoc... ************************************************************************ * * \subsection[Simplify-simplExpr]{The main function: simplExpr} * * ************************************************************************ The reason for this OutExprStuff stuff is that we want to float *after* simplifying a RHS, not before. If we do so naively we get quadratic behaviour as things float out. To see why it's important to do it after, consider this (real) example: let t = f x in fst t ==> let t = let a = e1 b = e2 in (a,b) in fst t ==> let a = e1 b = e2 t = (a,b) in a -- Can't inline a this round, cos it appears twice ==> e1 Each of the ==> steps is a round of simplification. We'd save a whole round if we float first. This can cascade. Consider let f = g d in \x -> ...f... ==> let f = let d1 = ..d.. in \y -> e in \x -> ...f... ==> let d1 = ..d.. in \x -> ...(\y ->e)... Only in this second round can the \y be applied, and it might do the same again. -} simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr simplExpr env expr = simplExprC env expr (mkBoringStop expr_out_ty) where expr_out_ty :: OutType expr_out_ty = substTy env (exprType expr) simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr -- Simplify an expression, given a continuation simplExprC env expr cont = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $ do { (env', expr') <- simplExprF (zapFloats env) expr cont ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $ -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $ -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $ return (wrapFloats env' expr') } -------------------------------------------------- simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM (SimplEnv, OutExpr) simplExprF env e cont = {- pprTrace "simplExprF" (vcat [ ppr e , text "cont =" <+> ppr cont , text "inscope =" <+> ppr (seInScope env) , text "tvsubst =" <+> ppr (seTvSubst env) , text "idsubst =" <+> ppr (seIdSubst env) , text "cvsubst =" <+> ppr (seCvSubst env) {- , ppr (seFloats env) -} ]) $ -} simplExprF1 env e cont simplExprF1 :: SimplEnv -> InExpr -> SimplCont -> SimplM (SimplEnv, OutExpr) simplExprF1 env (Var v) cont = simplIdF env v cont simplExprF1 env (Lit lit) cont = rebuild env (Lit lit) cont simplExprF1 env (Tick t expr) cont = simplTick env t expr cont simplExprF1 env (Cast body co) cont = simplCast env body co cont simplExprF1 env (Coercion co) cont = simplCoercionF env co cont simplExprF1 env (Type ty) cont = ASSERT( contIsRhsOrArg cont ) rebuild env (Type (substTy env ty)) cont simplExprF1 env (App fun arg) cont = simplExprF env fun $ case arg of Type ty -> ApplyToTy { sc_arg_ty = substTy env ty , sc_hole_ty = substTy env (exprType fun) , sc_cont = cont } _ -> ApplyToVal { sc_arg = arg, sc_env = env , sc_dup = NoDup, sc_cont = cont } simplExprF1 env expr@(Lam {}) cont = simplLam env zapped_bndrs body cont -- The main issue here is under-saturated lambdas -- (\x1. \x2. e) arg1 -- Here x1 might have "occurs-once" occ-info, because occ-info -- is computed assuming that a group of lambdas is applied -- all at once. If there are too few args, we must zap the -- occ-info, UNLESS the remaining binders are one-shot where (bndrs, body) = collectBinders expr zapped_bndrs | need_to_zap = map zap bndrs | otherwise = bndrs need_to_zap = any zappable_bndr (drop n_args bndrs) n_args = countArgs cont -- NB: countArgs counts all the args (incl type args) -- and likewise drop counts all binders (incl type lambdas) zappable_bndr b = isId b && not (isOneShotBndr b) zap b | isTyVar b = b | otherwise = zapLamIdInfo b simplExprF1 env (Case scrut bndr _ alts) cont = simplExprF env scrut (Select NoDup bndr alts env cont) simplExprF1 env (Let (Rec pairs) body) cont = do { env' <- simplRecBndrs env (map fst pairs) -- NB: bndrs' don't have unfoldings or rules -- We add them as we go down ; env'' <- simplRecBind env' NotTopLevel pairs ; simplExprF env'' body cont } simplExprF1 env (Let (NonRec bndr rhs) body) cont = simplNonRecE env bndr (rhs, env) ([], body) cont --------------------------------- simplType :: SimplEnv -> InType -> SimplM OutType -- Kept monadic just so we can do the seqType simplType env ty = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $ seqType new_ty `seq` return new_ty where new_ty = substTy env ty --------------------------------- simplCoercionF :: SimplEnv -> InCoercion -> SimplCont -> SimplM (SimplEnv, OutExpr) simplCoercionF env co cont = do { co' <- simplCoercion env co ; rebuild env (Coercion co') cont } simplCoercion :: SimplEnv -> InCoercion -> SimplM OutCoercion simplCoercion env co = let opt_co = optCoercion (getCvSubst env) co in seqCo opt_co `seq` return opt_co ----------------------------------- -- | Push a TickIt context outwards past applications and cases, as -- long as this is a non-scoping tick, to let case and application -- optimisations apply. simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont -> SimplM (SimplEnv, OutExpr) simplTick env tickish expr cont -- A scoped tick turns into a continuation, so that we can spot -- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do -- it this way, then it would take two passes of the simplifier to -- reduce ((scc t (\x . e)) e'). -- NB, don't do this with counting ticks, because if the expr is -- bottom, then rebuildCall will discard the continuation. -- XXX: we cannot do this, because the simplifier assumes that -- the context can be pushed into a case with a single branch. e.g. -- scc<f> case expensive of p -> e -- becomes -- case expensive of p -> scc<f> e -- -- So I'm disabling this for now. It just means we will do more -- simplifier iterations that necessary in some cases. -- | tickishScoped tickish && not (tickishCounts tickish) -- = simplExprF env expr (TickIt tickish cont) -- For unscoped or soft-scoped ticks, we are allowed to float in new -- cost, so we simply push the continuation inside the tick. This -- has the effect of moving the tick to the outside of a case or -- application context, allowing the normal case and application -- optimisations to fire. | tickish `tickishScopesLike` SoftScope = do { (env', expr') <- simplExprF env expr cont ; return (env', mkTick tickish expr') } -- Push tick inside if the context looks like this will allow us to -- do a case-of-case - see Note [case-of-scc-of-case] | Select {} <- cont, Just expr' <- push_tick_inside = simplExprF env expr' cont -- We don't want to move the tick, but we might still want to allow -- floats to pass through with appropriate wrapping (or not, see -- wrap_floats below) --- | not (tickishCounts tickish) || tickishCanSplit tickish -- = wrap_floats | otherwise = no_floating_past_tick where -- Try to push tick inside a case, see Note [case-of-scc-of-case]. push_tick_inside = case expr0 of Case scrut bndr ty alts -> Just $ Case (tickScrut scrut) bndr ty (map tickAlt alts) _other -> Nothing where (ticks, expr0) = stripTicksTop movable (Tick tickish expr) movable t = not (tickishCounts t) || t `tickishScopesLike` NoScope || tickishCanSplit t tickScrut e = foldr mkTick e ticks -- Alternatives get annotated with all ticks that scope in some way, -- but we don't want to count entries. tickAlt (c,bs,e) = (c,bs, foldr mkTick e ts_scope) ts_scope = map mkNoCount $ filter (not . (`tickishScopesLike` NoScope)) ticks no_floating_past_tick = do { let (inc,outc) = splitCont cont ; (env', expr') <- simplExprF (zapFloats env) expr inc ; let tickish' = simplTickish env tickish ; (env'', expr'') <- rebuild (zapFloats env') (wrapFloats env' expr') (TickIt tickish' outc) ; return (addFloats env env'', expr'') } -- Alternative version that wraps outgoing floats with the tick. This -- results in ticks being duplicated, as we don't make any attempt to -- eliminate the tick if we re-inline the binding (because the tick -- semantics allows unrestricted inlining of HNFs), so I'm not doing -- this any more. FloatOut will catch any real opportunities for -- floating. -- -- wrap_floats = -- do { let (inc,outc) = splitCont cont -- ; (env', expr') <- simplExprF (zapFloats env) expr inc -- ; let tickish' = simplTickish env tickish -- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0), -- mkTick (mkNoCount tickish') rhs) -- -- when wrapping a float with mkTick, we better zap the Id's -- -- strictness info and arity, because it might be wrong now. -- ; let env'' = addFloats env (mapFloats env' wrap_float) -- ; rebuild env'' expr' (TickIt tickish' outc) -- } simplTickish env tickish | Breakpoint n ids <- tickish = Breakpoint n (map (getDoneId . substId env) ids) | otherwise = tickish -- Push type application and coercion inside a tick splitCont :: SimplCont -> (SimplCont, SimplCont) splitCont cont@(ApplyToTy { sc_cont = tail }) = (cont { sc_cont = inc }, outc) where (inc,outc) = splitCont tail splitCont (CastIt co c) = (CastIt co inc, outc) where (inc,outc) = splitCont c splitCont other = (mkBoringStop (contHoleType other), other) getDoneId (DoneId id) = id getDoneId (DoneEx e) = getIdFromTrivialExpr e -- Note [substTickish] in CoreSubst getDoneId other = pprPanic "getDoneId" (ppr other) -- Note [case-of-scc-of-case] -- It's pretty important to be able to transform case-of-case when -- there's an SCC in the way. For example, the following comes up -- in nofib/real/compress/Encode.hs: -- -- case scctick<code_string.r1> -- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje -- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) -> -- (ww1_s13f, ww2_s13g, ww3_s13h) -- } -- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) -> -- tick<code_string.f1> -- (ww_s12Y, -- ww1_s12Z, -- PTTrees.PT -- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf) -- } -- -- We really want this case-of-case to fire, because then the 3-tuple -- will go away (indeed, the CPR optimisation is relying on this -- happening). But the scctick is in the way - we need to push it -- inside to expose the case-of-case. So we perform this -- transformation on the inner case: -- -- scctick c (case e of { p1 -> e1; ...; pn -> en }) -- ==> -- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en } -- -- So we've moved a constant amount of work out of the scc to expose -- the case. We only do this when the continuation is interesting: in -- for now, it has to be another Case (maybe generalise this later). {- ************************************************************************ * * \subsection{The main rebuilder} * * ************************************************************************ -} rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr) -- At this point the substitution in the SimplEnv should be irrelevant -- only the in-scope set and floats should matter rebuild env expr cont = case cont of Stop {} -> return (env, expr) TickIt t cont -> rebuild env (mkTick t expr) cont CastIt co cont -> rebuild env (mkCast expr co) cont -- NB: mkCast implements the (Coercion co |> g) optimisation Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont StrictArg info _ cont -> rebuildCall env (info `addValArgTo` expr) cont StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr -- expr satisfies let/app since it started life -- in a call to simplNonRecE ; simplLam env' bs body cont } ApplyToTy { sc_arg_ty = ty, sc_cont = cont} -> rebuild env (App expr (Type ty)) cont ApplyToVal { sc_arg = arg, sc_env = se, sc_dup = dup_flag, sc_cont = cont} -- See Note [Avoid redundant simplification] | isSimplified dup_flag -> rebuild env (App expr arg) cont | otherwise -> do { arg' <- simplExpr (se `setInScope` env) arg ; rebuild env (App expr arg') cont } {- ************************************************************************ * * \subsection{Lambdas} * * ************************************************************************ -} simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont -> SimplM (SimplEnv, OutExpr) simplCast env body co0 cont0 = do { co1 <- simplCoercion env co0 ; cont1 <- addCoerce co1 cont0 ; simplExprF env body cont1 } where addCoerce co cont = add_coerce co (coercionKind co) cont add_coerce _co (Pair s1 k1) cont -- co :: ty~ty | s1 `eqType` k1 = return cont -- is a no-op add_coerce co1 (Pair s1 _k2) (CastIt co2 cont) | (Pair _l1 t1) <- coercionKind co2 -- e |> (g1 :: S1~L) |> (g2 :: L~T1) -- ==> -- e, if S1=T1 -- e |> (g1 . g2 :: S1~T1) otherwise -- -- For example, in the initial form of a worker -- we may find (coerce T (coerce S (\x.e))) y -- and we'd like it to simplify to e[y/x] in one round -- of simplification , s1 `eqType` t1 = return cont -- The coerces cancel out | otherwise = return (CastIt (mkTransCo co1 co2) cont) add_coerce co (Pair s1s2 _t1t2) cont@(ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail }) -- (f |> g) ty ---> (f ty) |> (g @ ty) -- This implements the PushT rule from the paper | Just (tyvar,_) <- splitForAllTy_maybe s1s2 = ASSERT( isTyVar tyvar ) do { cont' <- addCoerce new_cast tail ; return (cont { sc_cont = cont' }) } where new_cast = mkInstCo co arg_ty add_coerce co (Pair s1s2 t1t2) (ApplyToVal { sc_arg = arg, sc_env = arg_se , sc_dup = dup, sc_cont = cont }) | isFunTy s1s2 -- This implements the Push rule from the paper , isFunTy t1t2 -- Check t1t2 to ensure 'arg' is a value arg -- (e |> (g :: s1s2 ~ t1->t2)) f -- ===> -- (e (f |> (arg g :: t1~s1)) -- |> (res g :: s2->t2) -- -- t1t2 must be a function type, t1->t2, because it's applied -- to something but s1s2 might conceivably not be -- -- When we build the ApplyTo we can't mix the out-types -- with the InExpr in the argument, so we simply substitute -- to make it all consistent. It's a bit messy. -- But it isn't a common case. -- -- Example of use: Trac #995 = do { let arg' = substExpr arg_se arg -- It's important that this is lazy, because this argument -- may be disarded if turns out to be the argument of -- (\_ -> e) This can make a huge difference; -- see Trac #10527 ; cont' <- addCoerce co2 cont ; return (ApplyToVal { sc_arg = mkCast arg' (mkSymCo co1) , sc_env = zapSubstEnv arg_se , sc_dup = dup , sc_cont = cont' }) } where -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and -- t2 ~ s2 with left and right on the curried form: -- (->) t1 t2 ~ (->) s1 s2 [co1, co2] = decomposeCo 2 co add_coerce co _ cont = return (CastIt co cont) simplArg :: SimplEnv -> DupFlag -> StaticEnv -> CoreExpr -> SimplM (DupFlag, StaticEnv, OutExpr) simplArg env dup_flag arg_env arg | isSimplified dup_flag = return (dup_flag, arg_env, arg) | otherwise = do { arg' <- simplExpr (arg_env `setInScope` env) arg ; return (Simplified, zapSubstEnv arg_env, arg') } {- ************************************************************************ * * \subsection{Lambdas} * * ************************************************************************ Note [Zap unfolding when beta-reducing] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Lambda-bound variables can have stable unfoldings, such as $j = \x. \b{Unf=Just x}. e See Note [Case binders and join points] below; the unfolding for lets us optimise e better. However when we beta-reduce it we want to revert to using the actual value, otherwise we can end up in the stupid situation of let x = blah in let b{Unf=Just x} = y in ...b... Here it'd be far better to drop the unfolding and use the actual RHS. -} simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont -> SimplM (SimplEnv, OutExpr) simplLam env [] body cont = simplExprF env body cont -- Beta reduction simplLam env (bndr:bndrs) body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont }) = do { tick (BetaReduction bndr) ; simplLam (extendTvSubst env bndr arg_ty) bndrs body cont } simplLam env (bndr:bndrs) body (ApplyToVal { sc_arg = arg, sc_env = arg_se , sc_cont = cont }) = do { tick (BetaReduction bndr) ; simplNonRecE env (zap_unfolding bndr) (arg, arg_se) (bndrs, body) cont } where zap_unfolding bndr -- See Note [Zap unfolding when beta-reducing] | isId bndr, isStableUnfolding (realIdUnfolding bndr) = setIdUnfolding bndr NoUnfolding | otherwise = bndr -- discard a non-counting tick on a lambda. This may change the -- cost attribution slightly (moving the allocation of the -- lambda elsewhere), but we don't care: optimisation changes -- cost attribution all the time. simplLam env bndrs body (TickIt tickish cont) | not (tickishCounts tickish) = simplLam env bndrs body cont -- Not enough args, so there are real lambdas left to put in the result simplLam env bndrs body cont = do { (env', bndrs') <- simplLamBndrs env bndrs ; body' <- simplExpr env' body ; new_lam <- mkLam bndrs' body' cont ; rebuild env' new_lam cont } simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr]) simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs ------------- simplLamBndr :: SimplEnv -> Var -> SimplM (SimplEnv, Var) -- Used for lambda binders. These sometimes have unfoldings added by -- the worker/wrapper pass that must be preserved, because they can't -- be reconstructed from context. For example: -- f x = case x of (a,b) -> fw a b x -- fw a b x{=(a,b)} = ... -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise. simplLamBndr env bndr | isId bndr && hasSomeUnfolding old_unf -- Special case = do { (env1, bndr1) <- simplBinder env bndr ; unf' <- simplUnfolding env1 NotTopLevel bndr old_unf ; let bndr2 = bndr1 `setIdUnfolding` unf' ; return (modifyInScope env1 bndr2, bndr2) } | otherwise = simplBinder env bndr -- Normal case where old_unf = idUnfolding bndr ------------------ simplNonRecE :: SimplEnv -> InBndr -- The binder -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda) -> ([InBndr], InExpr) -- Body of the let/lambda -- \xs.e -> SimplCont -> SimplM (SimplEnv, OutExpr) -- simplNonRecE is used for -- * non-top-level non-recursive lets in expressions -- * beta reduction -- -- It deals with strict bindings, via the StrictBind continuation, -- which may abort the whole process -- -- Precondition: rhs satisfies the let/app invariant -- Note [CoreSyn let/app invariant] in CoreSyn -- -- The "body" of the binding comes as a pair of ([InId],InExpr) -- representing a lambda; so we recurse back to simplLam -- Why? Because of the binder-occ-info-zapping done before -- the call to simplLam in simplExprF (Lam ...) -- First deal with type applications and type lets -- (/\a. e) (Type ty) and (let a = Type ty in e) simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont = ASSERT( isTyVar bndr ) do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont } simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont = do dflags <- getDynFlags case () of _ | preInlineUnconditionally dflags env NotTopLevel bndr rhs -> do { tick (PreInlineUnconditionally bndr) ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $ simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont } | isStrictId bndr -- Includes coercions -> simplExprF (rhs_se `setFloats` env) rhs (StrictBind bndr bndrs body env cont) | otherwise -> ASSERT( not (isTyVar bndr) ) do { (env1, bndr1) <- simplNonRecBndr env bndr ; (env2, bndr2) <- addBndrRules env1 bndr bndr1 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se ; simplLam env3 bndrs body cont } {- ************************************************************************ * * Variables * * ************************************************************************ -} simplVar :: SimplEnv -> InVar -> SimplM OutExpr -- Look up an InVar in the environment simplVar env var | isTyVar var = return (Type (substTyVar env var)) | isCoVar var = return (Coercion (substCoVar env var)) | otherwise = case substId env var of DoneId var1 -> return (Var var1) DoneEx e -> return e ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr) simplIdF env var cont = case substId env var of DoneEx e -> simplExprF (zapSubstEnv env) e cont ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont DoneId var1 -> completeCall env var1 cont -- Note [zapSubstEnv] -- The template is already simplified, so don't re-substitute. -- This is VITAL. Consider -- let x = e in -- let y = \z -> ...x... in -- \ x -> ...y... -- We'll clone the inner \x, adding x->x' in the id_subst -- Then when we inline y, we must *not* replace x by x' in -- the inlined copy!! --------------------------------------------------------- -- Dealing with a call site completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr) completeCall env var cont = do { ------------- Try inlining ---------------- dflags <- getDynFlags ; let (lone_variable, arg_infos, call_cont) = contArgs cont n_val_args = length arg_infos interesting_cont = interestingCallContext call_cont unfolding = activeUnfolding env var maybe_inline = callSiteInline dflags var unfolding lone_variable arg_infos interesting_cont ; case maybe_inline of { Just expr -- There is an inlining! -> do { checkedTick (UnfoldingDone var) ; dump_inline dflags expr cont ; simplExprF (zapSubstEnv env) expr cont } ; Nothing -> do -- No inlining! { rule_base <- getSimplRules ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont ; rebuildCall env info cont }}} where dump_inline dflags unfolding cont | not (dopt Opt_D_dump_inlinings dflags) = return () | not (dopt Opt_D_verbose_core2core dflags) = when (isExternalName (idName var)) $ liftIO $ printInfoForUser dflags alwaysQualify $ sep [text "Inlining done:", nest 4 (ppr var)] | otherwise = liftIO $ printInfoForUser dflags alwaysQualify $ sep [text "Inlining done: " <> ppr var, nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding), text "Cont: " <+> ppr cont])] rebuildCall :: SimplEnv -> ArgInfo -> SimplCont -> SimplM (SimplEnv, OutExpr) rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont -- When we run out of strictness args, it means -- that the call is definitely bottom; see SimplUtils.mkArgInfo -- Then we want to discard the entire strict continuation. E.g. -- * case (error "hello") of { ... } -- * (error "Hello") arg -- * f (error "Hello") where f is strict -- etc -- Then, especially in the first of these cases, we'd like to discard -- the continuation, leaving just the bottoming expression. But the -- type might not be right, so we may have to add a coerce. | not (contIsTrivial cont) -- Only do this if there is a non-trivial = return (env, castBottomExpr res cont_ty) -- contination to discard, else we do it where -- again and again! res = argInfoExpr fun rev_args cont_ty = contResultType cont rebuildCall env info (CastIt co cont) = rebuildCall env (addCastTo info co) cont rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont }) = rebuildCall env (info `addTyArgTo` arg_ty) cont rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty , ai_strs = str:strs, ai_discs = disc:discs }) (ApplyToVal { sc_arg = arg, sc_env = arg_se , sc_dup = dup_flag, sc_cont = cont }) | isSimplified dup_flag -- See Note [Avoid redundant simplification] = rebuildCall env (addValArgTo info' arg) cont | str -- Strict argument = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $ simplExprF (arg_se `setFloats` env) arg (StrictArg info' cci cont) -- Note [Shadowing] | otherwise -- Lazy argument -- DO NOT float anything outside, hence simplExprC -- There is no benefit (unlike in a let-binding), and we'd -- have to be very careful about bogus strictness through -- floating a demanded let. = do { arg' <- simplExprC (arg_se `setInScope` env) arg (mkLazyArgStop (funArgTy fun_ty) cci) ; rebuildCall env (addValArgTo info' arg') cont } where info' = info { ai_strs = strs, ai_discs = discs } cci | encl_rules = RuleArgCtxt | disc > 0 = DiscArgCtxt -- Be keener here | otherwise = BoringCtxt -- Nothing interesting rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont | null rules = rebuild env (argInfoExpr fun rev_args) cont -- No rules, common case | otherwise = do { -- We've accumulated a simplified call in <fun,rev_args> -- so try rewrite rules; see Note [RULEs apply to simplified arguments] -- See also Note [Rules for recursive functions] ; let env' = zapSubstEnv env -- See Note [zapSubstEnv]; -- and NB that 'rev_args' are all fully simplified ; mb_rule <- tryRules env' rules fun (reverse rev_args) cont ; case mb_rule of { Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont' -- Rules don't match ; Nothing -> rebuild env (argInfoExpr fun rev_args) cont -- No rules } } {- Note [RULES apply to simplified arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's very desirable to try RULES once the arguments have been simplified, because doing so ensures that rule cascades work in one pass. Consider {-# RULES g (h x) = k x f (k x) = x #-} ...f (g (h x))... Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If we match f's rules against the un-simplified RHS, it won't match. This makes a particularly big difference when superclass selectors are involved: op ($p1 ($p2 (df d))) We want all this to unravel in one sweeep. Note [Avoid redundant simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because RULES apply to simplified arguments, there's a danger of repeatedly simplifying already-simplified arguments. An important example is that of (>>=) d e1 e2 Here e1, e2 are simplified before the rule is applied, but don't really participate in the rule firing. So we mark them as Simplified to avoid re-simplifying them. Note [Shadowing] ~~~~~~~~~~~~~~~~ This part of the simplifier may break the no-shadowing invariant Consider f (...(\a -> e)...) (case y of (a,b) -> e') where f is strict in its second arg If we simplify the innermost one first we get (...(\a -> e)...) Simplifying the second arg makes us float the case out, so we end up with case y of (a,b) -> f (...(\a -> e)...) e' So the output does not have the no-shadowing invariant. However, there is no danger of getting name-capture, because when the first arg was simplified we used an in-scope set that at least mentioned all the variables free in its static environment, and that is enough. We can't just do innermost first, or we'd end up with a dual problem: case x of (a,b) -> f e (...(\a -> e')...) I spent hours trying to recover the no-shadowing invariant, but I just could not think of an elegant way to do it. The simplifier is already knee-deep in continuations. We have to keep the right in-scope set around; AND we have to get the effect that finding (error "foo") in a strict arg position will discard the entire application and replace it with (error "foo"). Getting all this at once is TOO HARD! ************************************************************************ * * Rewrite rules * * ************************************************************************ -} tryRules :: SimplEnv -> [CoreRule] -> Id -> [ArgSpec] -> SimplCont -> SimplM (Maybe (CoreExpr, SimplCont)) -- The SimplEnv already has zapSubstEnv applied to it tryRules env rules fn args call_cont | null rules = return Nothing {- Disabled until we fix #8326 | fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#] , [_type_arg, val_arg] <- args , Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont , isDeadBinder bndr = do { dflags <- getDynFlags ; let enum_to_tag :: CoreAlt -> CoreAlt -- Takes K -> e into tagK# -> e -- where tagK# is the tag of constructor K enum_to_tag (DataAlt con, [], rhs) = ASSERT( isEnumerationTyCon (dataConTyCon con) ) (LitAlt tag, [], rhs) where tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG)) enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt) new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts new_bndr = setIdType bndr intPrimTy -- The binder is dead, but should have the right type ; return (Just (val_arg, Select dup new_bndr new_alts se cont)) } -} | otherwise = do { dflags <- getDynFlags ; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env) fn (argInfoAppArgs args) rules of { Nothing -> return Nothing ; -- No rule matches Just (rule, rule_rhs) -> do { checkedTick (RuleFired (ru_name rule)) ; let cont' = pushSimplifiedArgs env (drop (ruleArity rule) args) call_cont -- (ruleArity rule) says how many args the rule consumed ; dump dflags rule rule_rhs ; return (Just (rule_rhs, cont')) }}} where dump dflags rule rule_rhs | dopt Opt_D_dump_rule_rewrites dflags = log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat [ text "Rule:" <+> ftext (ru_name rule) , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args)) , text "After: " <+> pprCoreExpr rule_rhs , text "Cont: " <+> ppr call_cont ] | dopt Opt_D_dump_rule_firings dflags = log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $ ftext (ru_name rule) | otherwise = return () log_rule dflags flag hdr details = liftIO . dumpSDoc dflags alwaysQualify flag "" $ sep [text hdr, nest 4 details] {- Note [Optimising tagToEnum#] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have an enumeration data type: data Foo = A | B | C Then we want to transform case tagToEnum# x of ==> case x of A -> e1 DEFAULT -> e1 B -> e2 1# -> e2 C -> e3 2# -> e3 thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT alternative we retain it (remember it comes first). If not the case must be exhaustive, and we reflect that in the transformed version by adding a DEFAULT. Otherwise Lint complains that the new case is not exhaustive. See #8317. Note [Rules for recursive functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You might think that we shouldn't apply rules for a loop breaker: doing so might give rise to an infinite loop, because a RULE is rather like an extra equation for the function: RULE: f (g x) y = x+y Eqn: f a y = a-y But it's too drastic to disable rules for loop breakers. Even the foldr/build rule would be disabled, because foldr is recursive, and hence a loop breaker: foldr k z (build g) = g k z So it's up to the programmer: rules can cause divergence ************************************************************************ * * Rebuilding a case expression * * ************************************************************************ Note [Case elimination] ~~~~~~~~~~~~~~~~~~~~~~~ The case-elimination transformation discards redundant case expressions. Start with a simple situation: case x# of ===> let y# = x# in e y# -> e (when x#, y# are of primitive type, of course). We can't (in general) do this for algebraic cases, because we might turn bottom into non-bottom! The code in SimplUtils.prepareAlts has the effect of generalise this idea to look for a case where we're scrutinising a variable, and we know that only the default case can match. For example: case x of 0# -> ... DEFAULT -> ...(case x of 0# -> ... DEFAULT -> ...) ... Here the inner case is first trimmed to have only one alternative, the DEFAULT, after which it's an instance of the previous case. This really only shows up in eliminating error-checking code. Note that SimplUtils.mkCase combines identical RHSs. So case e of ===> case e of DEFAULT -> r True -> r False -> r Now again the case may be elminated by the CaseElim transformation. This includes things like (==# a# b#)::Bool so that we simplify case ==# a# b# of { True -> x; False -> x } to just x This particular example shows up in default methods for comparison operations (e.g. in (>=) for Int.Int32) Note [Case elimination: lifted case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a case over a lifted type has a single alternative, and is being used as a strict 'let' (all isDeadBinder bndrs), we may want to do this transformation: case e of r ===> let r = e in ...r... _ -> ...r... (a) 'e' is already evaluated (it may so if e is a variable) Specifically we check (exprIsHNF e). In this case we can just allocate the WHNF directly with a let. or (b) 'x' is not used at all and e is ok-for-speculation The ok-for-spec bit checks that we don't lose any exceptions or divergence. NB: it'd be *sound* to switch from case to let if the scrutinee was not yet WHNF but was guaranteed to converge; but sticking with case means we won't build a thunk or (c) 'x' is used strictly in the body, and 'e' is a variable Then we can just substitute 'e' for 'x' in the body. See Note [Eliminating redundant seqs] For (b), the "not used at all" test is important. Consider case (case a ># b of { True -> (p,q); False -> (q,p) }) of r -> blah The scrutinee is ok-for-speculation (it looks inside cases), but we do not want to transform to let r = case a ># b of { True -> (p,q); False -> (q,p) } in blah because that builds an unnecessary thunk. Note [Eliminating redundant seqs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have this: case x of r { _ -> ..r.. } where 'r' is used strictly in (..r..), the case is effectively a 'seq' on 'x', but since 'r' is used strictly anyway, we can safely transform to (...x...) Note that this can change the error behaviour. For example, we might transform case x of { _ -> error "bad" } --> error "bad" which is might be puzzling if 'x' currently lambda-bound, but later gets let-bound to (error "good"). Nevertheless, the paper "A semantics for imprecise exceptions" allows this transformation. If you want to fix the evaluation order, use 'pseq'. See Trac #8900 for an example where the loss of this transformation bit us in practice. See also Note [Empty case alternatives] in CoreSyn. Just for reference, the original code (added Jan 13) looked like this: || case_bndr_evald_next rhs case_bndr_evald_next :: CoreExpr -> Bool -- See Note [Case binder next] case_bndr_evald_next (Var v) = v == case_bndr case_bndr_evald_next (Cast e _) = case_bndr_evald_next e case_bndr_evald_next (App e _) = case_bndr_evald_next e case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e case_bndr_evald_next _ = False (This came up when fixing Trac #7542. See also Note [Eta reduction of an eval'd function] in CoreUtils.) Note [Case elimination: unlifted case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider case a +# b of r -> ...r... Then we do case-elimination (to make a let) followed by inlining, to get .....(a +# b).... If we have case indexArray# a i of r -> ...r... we might like to do the same, and inline the (indexArray# a i). But indexArray# is not okForSpeculation, so we don't build a let in rebuildCase (lest it get floated *out*), so the inlining doesn't happen either. This really isn't a big deal I think. The let can be Further notes about case elimination ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider: test :: Integer -> IO () test = print Turns out that this compiles to: Print.test = \ eta :: Integer eta1 :: Void# -> case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT -> case hPutStr stdout (PrelNum.jtos eta ($w[] @ Char)) eta1 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }} Notice the strange '<' which has no effect at all. This is a funny one. It started like this: f x y = if x < 0 then jtos x else if y==0 then "" else jtos x At a particular call site we have (f v 1). So we inline to get if v < 0 then jtos x else if 1==0 then "" else jtos x Now simplify the 1==0 conditional: if v<0 then jtos v else jtos v Now common-up the two branches of the case: case (v<0) of DEFAULT -> jtos v Why don't we drop the case? Because it's strict in v. It's technically wrong to drop even unnecessary evaluations, and in practice they may be a result of 'seq' so we *definitely* don't want to drop those. I don't really know how to improve this situation. -} --------------------------------------------------------- -- Eliminate the case if possible rebuildCase, reallyRebuildCase :: SimplEnv -> OutExpr -- Scrutinee -> InId -- Case binder -> [InAlt] -- Alternatives (inceasing order) -> SimplCont -> SimplM (SimplEnv, OutExpr) -------------------------------------------------- -- 1. Eliminate the case if there's a known constructor -------------------------------------------------- rebuildCase env scrut case_bndr alts cont | Lit lit <- scrut -- No need for same treatment as constructors -- because literals are inlined more vigorously , not (litIsLifted lit) = do { tick (KnownBranch case_bndr) ; case findAlt (LitAlt lit) alts of Nothing -> missingAlt env case_bndr alts cont Just (_, bs, rhs) -> simple_rhs bs rhs } | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut -- Works when the scrutinee is a variable with a known unfolding -- as well as when it's an explicit constructor application = do { tick (KnownBranch case_bndr) ; case findAlt (DataAlt con) alts of Nothing -> missingAlt env case_bndr alts cont Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args case_bndr bs rhs cont } where simple_rhs bs rhs = ASSERT( null bs ) do { env' <- simplNonRecX env case_bndr scrut -- scrut is a constructor application, -- hence satisfies let/app invariant ; simplExprF env' rhs cont } -------------------------------------------------- -- 2. Eliminate the case if scrutinee is evaluated -------------------------------------------------- rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont -- See if we can get rid of the case altogether -- See Note [Case elimination] -- mkCase made sure that if all the alternatives are equal, -- then there is now only one (DEFAULT) rhs -- 2a. Dropping the case altogether, if -- a) it binds nothing (so it's really just a 'seq') -- b) evaluating the scrutinee has no side effects | is_plain_seq , exprOkForSideEffects scrut -- The entire case is dead, so we can drop it -- if the scrutinee converges without having imperative -- side effects or raising a Haskell exception -- See Note [PrimOp can_fail and has_side_effects] in PrimOp = simplExprF env rhs cont -- 2b. Turn the case into a let, if -- a) it binds only the case-binder -- b) unlifted case: the scrutinee is ok-for-speculation -- lifted case: the scrutinee is in HNF (or will later be demanded) | all_dead_bndrs , if is_unlifted then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case] else exprIsHNF scrut -- See Note [Case elimination: lifted case] || scrut_is_demanded_var scrut = do { tick (CaseElim case_bndr) ; env' <- simplNonRecX env case_bndr scrut ; simplExprF env' rhs cont } -- 2c. Try the seq rules if -- a) it binds only the case binder -- b) a rule for seq applies -- See Note [User-defined RULES for seq] in MkId | is_plain_seq = do { let scrut_ty = exprType scrut rhs_ty = substTy env (exprType rhs) out_args = [ TyArg { as_arg_ty = scrut_ty , as_hole_ty = seq_id_ty } , TyArg { as_arg_ty = rhs_ty , as_hole_ty = applyTy seq_id_ty scrut_ty } , ValArg scrut] rule_cont = ApplyToVal { sc_dup = NoDup, sc_arg = rhs , sc_env = env, sc_cont = cont } env' = zapSubstEnv env -- Lazily evaluated, so we don't do most of this ; rule_base <- getSimplRules ; mb_rule <- tryRules env' (getRules rule_base seqId) seqId out_args rule_cont ; case mb_rule of Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont' Nothing -> reallyRebuildCase env scrut case_bndr alts cont } where is_unlifted = isUnLiftedType (idType case_bndr) all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId] is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect seq_id_ty = idType seqId scrut_is_demanded_var :: CoreExpr -> Bool -- See Note [Eliminating redundant seqs] scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr) scrut_is_demanded_var _ = False rebuildCase env scrut case_bndr alts cont = reallyRebuildCase env scrut case_bndr alts cont -------------------------------------------------- -- 3. Catch-all case -------------------------------------------------- reallyRebuildCase env scrut case_bndr alts cont = do { -- Prepare the continuation; -- The new subst_env is in place (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont -- Simplify the alternatives ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont ; dflags <- getDynFlags ; let alts_ty' = contResultType dup_cont ; case_expr <- mkCase dflags scrut' case_bndr' alts_ty' alts' -- Notice that rebuild gets the in-scope set from env', not alt_env -- (which in any case is only build in simplAlts) -- The case binder *not* scope over the whole returned case-expression ; rebuild env' case_expr nodup_cont } {- simplCaseBinder checks whether the scrutinee is a variable, v. If so, try to eliminate uses of v in the RHSs in favour of case_bndr; that way, there's a chance that v will now only be used once, and hence inlined. Historical note: we use to do the "case binder swap" in the Simplifier so there were additional complications if the scrutinee was a variable. Now the binder-swap stuff is done in the occurrence analyer; see OccurAnal Note [Binder swap]. Note [knownCon occ info] ~~~~~~~~~~~~~~~~~~~~~~~~ If the case binder is not dead, then neither are the pattern bound variables: case <any> of x { (a,b) -> case x of { (p,q) -> p } } Here (a,b) both look dead, but come alive after the inner case is eliminated. The point is that we bring into the envt a binding let x = (a,b) after the outer case, and that makes (a,b) alive. At least we do unless the case binder is guaranteed dead. Note [Case alternative occ info] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we are simply reconstructing a case (the common case), we always zap the occurrence info on the binders in the alternatives. Even if the case binder is dead, the scrutinee is usually a variable, and *that* can bring the case-alternative binders back to life. See Note [Add unfolding for scrutinee] Note [Improving seq] ~~~~~~~~~~~~~~~~~~~ Consider type family F :: * -> * type instance F Int = Int ... case e of x { DEFAULT -> rhs } ... where x::F Int. Then we'd like to rewrite (F Int) to Int, getting case e `cast` co of x'::Int I# x# -> let x = x' `cast` sym co in rhs so that 'rhs' can take advantage of the form of x'. Notice that Note [Case of cast] (in OccurAnal) may then apply to the result. Nota Bene: We only do the [Improving seq] transformation if the case binder 'x' is actually used in the rhs; that is, if the case is *not* a *pure* seq. a) There is no point in adding the cast to a pure seq. b) There is a good reason not to: doing so would interfere with seq rules (Note [Built-in RULES for seq] in MkId). In particular, this [Improving seq] thing *adds* a cast while [Built-in RULES for seq] *removes* one, so they just flip-flop. You might worry about case v of x { __DEFAULT -> ... case (v `cast` co) of y { I# -> ... }} This is a pure seq (since x is unused), so [Improving seq] won't happen. But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get case v of x { __DEFAULT -> ... case (x `cast` co) of y { I# -> ... }} Now the outer case is not a pure seq, so [Improving seq] will happen, and then the inner case will disappear. The need for [Improving seq] showed up in Roman's experiments. Example: foo :: F Int -> Int -> Int foo t n = t `seq` bar n where bar 0 = 0 bar n = bar (n - case t of TI i -> i) Here we'd like to avoid repeated evaluating t inside the loop, by taking advantage of the `seq`. At one point I did transformation in LiberateCase, but it's more robust here. (Otherwise, there's a danger that we'll simply drop the 'seq' altogether, before LiberateCase gets to see it.) -} simplAlts :: SimplEnv -> OutExpr -> InId -- Case binder -> [InAlt] -- Non-empty -> SimplCont -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation -- Like simplExpr, this just returns the simplified alternatives; -- it does not return an environment -- The returned alternatives can be empty, none are possible simplAlts env scrut case_bndr alts cont' = do { let env0 = zapFloats env ; (env1, case_bndr1) <- simplBinder env0 case_bndr ; fam_envs <- getFamEnvs ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut case_bndr case_bndr1 alts ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts -- NB: it's possible that the returned in_alts is empty: this is handled -- by the caller (rebuildCase) in the missingAlt function ; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts ; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $ return (scrut', case_bndr', alts') } ------------------------------------ improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv -> OutExpr -> InId -> OutId -> [InAlt] -> SimplM (SimplEnv, OutExpr, OutId) -- Note [Improving seq] improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)] | not (isDeadBinder case_bndr) -- Not a pure seq! See Note [Improving seq] , Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1) = do { case_bndr2 <- newId (fsLit "nt") ty2 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co) env2 = extendIdSubst env case_bndr rhs ; return (env2, scrut `Cast` co, case_bndr2) } improveSeq _ env scrut _ case_bndr1 _ = return (env, scrut, case_bndr1) ------------------------------------ simplAlt :: SimplEnv -> Maybe OutExpr -- The scrutinee -> [AltCon] -- These constructors can't be present when -- matching the DEFAULT alternative -> OutId -- The case binder -> SimplCont -> InAlt -> SimplM OutAlt simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs) = ASSERT( null bndrs ) do { let env' = addBinderUnfolding env case_bndr' (mkOtherCon imposs_deflt_cons) -- Record the constructors that the case-binder *can't* be. ; rhs' <- simplExprC env' rhs cont' ; return (DEFAULT, [], rhs') } simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs) = ASSERT( null bndrs ) do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit) ; rhs' <- simplExprC env' rhs cont' ; return (LitAlt lit, [], rhs') } simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs) = do { -- Deal with the pattern-bound variables -- Mark the ones that are in ! positions in the -- data constructor as certainly-evaluated. -- NB: simplLamBinders preserves this eval info ; let vs_with_evals = add_evals (dataConRepStrictness con) ; (env', vs') <- simplLamBndrs env vs_with_evals -- Bind the case-binder to (con args) ; let inst_tys' = tyConAppArgs (idType case_bndr') con_app :: OutExpr con_app = mkConApp2 con inst_tys' vs' ; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app ; rhs' <- simplExprC env'' rhs cont' ; return (DataAlt con, vs', rhs') } where -- add_evals records the evaluated-ness of the bound variables of -- a case pattern. This is *important*. Consider -- data T = T !Int !Int -- -- case x of { T a b -> T (a+1) b } -- -- We really must record that b is already evaluated so that we don't -- go and re-evaluate it when constructing the result. -- See Note [Data-con worker strictness] in MkId.lhs add_evals the_strs = go vs the_strs where go [] [] = [] go (v:vs') strs | isTyVar v = v : go vs' strs go (v:vs') (str:strs) | isMarkedStrict str = evald_v : go vs' strs | otherwise = zapped_v : go vs' strs where zapped_v = zapIdOccInfo v -- See Note [Case alternative occ info] evald_v = zapped_v `setIdUnfolding` evaldUnfolding go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs) addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv addAltUnfoldings env scrut case_bndr con_app = do { dflags <- getDynFlags ; let con_app_unf = mkSimpleUnfolding dflags con_app env1 = addBinderUnfolding env case_bndr con_app_unf -- See Note [Add unfolding for scrutinee] env2 = case scrut of Just (Var v) -> addBinderUnfolding env1 v con_app_unf Just (Cast (Var v) co) -> addBinderUnfolding env1 v $ mkSimpleUnfolding dflags (Cast con_app (mkSymCo co)) _ -> env1 ; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app]) ; return env2 } addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv addBinderUnfolding env bndr unf | debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf = WARN( not (eqType (idType bndr) (exprType tmpl)), ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) ) modifyInScope env (bndr `setIdUnfolding` unf) | otherwise = modifyInScope env (bndr `setIdUnfolding` unf) zapBndrOccInfo :: Bool -> Id -> Id -- Consider case e of b { (a,b) -> ... } -- Then if we bind b to (a,b) in "...", and b is not dead, -- then we must zap the deadness info on a,b zapBndrOccInfo keep_occ_info pat_id | keep_occ_info = pat_id | otherwise = zapIdOccInfo pat_id {- Note [Add unfolding for scrutinee] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In general it's unlikely that a variable scrutinee will appear in the case alternatives case x of { ...x unlikely to appear... } because the binder-swap in OccAnal has got rid of all such occcurrences See Note [Binder swap] in OccAnal. BUT it is still VERY IMPORTANT to add a suitable unfolding for a variable scrutinee, in simplAlt. Here's why case x of y (a,b) -> case b of c I# v -> ...(f y)... There is no occurrence of 'b' in the (...(f y)...). But y gets the unfolding (a,b), and *that* mentions b. If f has a RULE RULE f (p, I# q) = ... we want that rule to match, so we must extend the in-scope env with a suitable unfolding for 'y'. It's *essential* for rule matching; but it's also good for case-elimintation -- suppose that 'f' was inlined and did multi-level case analysis, then we'd solve it in one simplifier sweep instead of two. Exactly the same issue arises in SpecConstr; see Note [Add scrutinee to ValueEnv too] in SpecConstr HOWEVER, given case x of y { Just a -> r1; Nothing -> r2 } we do not want to add the unfolding x -> y to 'x', which might seem cool, since 'y' itself has different unfoldings in r1 and r2. Reason: if we did that, we'd have to zap y's deadness info and that is a very useful piece of information. So instead we add the unfolding x -> Just a, and x -> Nothing in the respective RHSs. ************************************************************************ * * \subsection{Known constructor} * * ************************************************************************ We are a bit careful with occurrence info. Here's an example (\x* -> case x of (a*, b) -> f a) (h v, e) where the * means "occurs once". This effectively becomes case (h v, e) of (a*, b) -> f a) and then let a* = h v; b = e in f a and then f (h v) All this should happen in one sweep. -} knownCon :: SimplEnv -> OutExpr -- The scrutinee -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces) -> InId -> [InBndr] -> InExpr -- The alternative -> SimplCont -> SimplM (SimplEnv, OutExpr) knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont = do { env' <- bind_args env bs dc_args ; env'' <- bind_case_bndr env' ; simplExprF env'' rhs cont } where zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId -- Ugh! bind_args env' [] _ = return env' bind_args env' (b:bs') (Type ty : args) = ASSERT( isTyVar b ) bind_args (extendTvSubst env' b ty) bs' args bind_args env' (b:bs') (arg : args) = ASSERT( isId b ) do { let b' = zap_occ b -- Note that the binder might be "dead", because it doesn't -- occur in the RHS; and simplNonRecX may therefore discard -- it via postInlineUnconditionally. -- Nevertheless we must keep it if the case-binder is alive, -- because it may be used in the con_app. See Note [knownCon occ info] ; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant ; bind_args env'' bs' args } bind_args _ _ _ = pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$ text "scrut:" <+> ppr scrut -- It's useful to bind bndr to scrut, rather than to a fresh -- binding x = Con arg1 .. argn -- because very often the scrut is a variable, so we avoid -- creating, and then subsequently eliminating, a let-binding -- BUT, if scrut is a not a variable, we must be careful -- about duplicating the arg redexes; in that case, make -- a new con-app from the args bind_case_bndr env | isDeadBinder bndr = return env | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut)) | otherwise = do { dc_args <- mapM (simplVar env) bs -- dc_ty_args are aready OutTypes, -- but bs are InBndrs ; let con_app = Var (dataConWorkId dc) `mkTyApps` dc_ty_args `mkApps` dc_args ; simplNonRecX env bndr con_app } ------------------- missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr) -- This isn't strictly an error, although it is unusual. -- It's possible that the simplifer might "see" that -- an inner case has no accessible alternatives before -- it "sees" that the entire branch of an outer case is -- inaccessible. So we simply put an error case here instead. missingAlt env case_bndr _ cont = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr ) return (env, mkImpossibleExpr (contResultType cont)) {- ************************************************************************ * * \subsection{Duplicating continuations} * * ************************************************************************ -} prepareCaseCont :: SimplEnv -> [InAlt] -> SimplCont -> SimplM (SimplEnv, SimplCont, -- Dupable part SimplCont) -- Non-dupable part -- We are considering -- K[case _ of { p1 -> r1; ...; pn -> rn }] -- where K is some enclosing continuation for the case -- Goal: split K into two pieces Kdup,Knodup so that -- a) Kdup can be duplicated -- b) Knodup[Kdup[e]] = K[e] -- The idea is that we'll transform thus: -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] } -- -- We may also return some extra bindings in SimplEnv (that scope over -- the entire continuation) -- -- When case-of-case is off, just make the entire continuation non-dupable prepareCaseCont env alts cont | not (sm_case_case (getMode env)) = return (env, mkBoringStop (contHoleType cont), cont) | not (many_alts alts) = return (env, cont, mkBoringStop (contResultType cont)) | otherwise = mkDupableCont env cont where many_alts :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative many_alts [] = False -- See Note [Bottom alternatives] many_alts [_] = False many_alts (alt:alts) | is_bot_alt alt = many_alts alts | otherwise = not (all is_bot_alt alts) is_bot_alt (_,_,rhs) = exprIsBottom rhs {- Note [Bottom alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~ When we have case (case x of { A -> error .. ; B -> e; C -> error ..) of alts then we can just duplicate those alts because the A and C cases will disappear immediately. This is more direct than creating join points and inlining them away; and in some cases we would not even create the join points (see Note [Single-alternative case]) and we would keep the case-of-case which is silly. See Trac #4930. -} mkDupableCont :: SimplEnv -> SimplCont -> SimplM (SimplEnv, SimplCont, SimplCont) mkDupableCont env cont | contIsDupable cont = return (env, cont, mkBoringStop (contResultType cont)) mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn mkDupableCont env (CastIt ty cont) = do { (env', dup, nodup) <- mkDupableCont env cont ; return (env', CastIt ty dup, nodup) } -- Duplicating ticks for now, not sure if this is good or not mkDupableCont env cont@(TickIt{}) = return (env, mkBoringStop (contHoleType cont), cont) mkDupableCont env cont@(StrictBind {}) = return (env, mkBoringStop (contHoleType cont), cont) -- See Note [Duplicating StrictBind] mkDupableCont env (StrictArg info cci cont) -- See Note [Duplicating StrictArg] = do { (env', dup, nodup) <- mkDupableCont env cont ; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info) ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) } mkDupableCont env cont@(ApplyToTy { sc_cont = tail }) = do { (env', dup_cont, nodup_cont) <- mkDupableCont env tail ; return (env', cont { sc_cont = dup_cont }, nodup_cont ) } mkDupableCont env (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_env = se, sc_cont = cont }) = -- e.g. [...hole...] (...arg...) -- ==> -- let a = ...arg... -- in [...hole...] a do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont ; (_, se', arg') <- simplArg env' dup se arg ; (env'', arg'') <- makeTrivial NotTopLevel env' arg' ; let app_cont = ApplyToVal { sc_arg = arg'', sc_env = se' , sc_dup = OkToDup, sc_cont = dup_cont } ; return (env'', app_cont, nodup_cont) } mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _) -- See Note [Single-alternative case] -- | not (exprIsDupable rhs && contIsDupable case_cont) -- | not (isDeadBinder case_bndr) | all isDeadBinder bs -- InIds && not (isUnLiftedType (idType case_bndr)) -- Note [Single-alternative-unlifted] = return (env, mkBoringStop (contHoleType cont), cont) mkDupableCont env (Select _ case_bndr alts se cont) = -- e.g. (case [...hole...] of { pi -> ei }) -- ===> -- let ji = \xij -> ei -- in case [...hole...] of { pi -> ji xij } do { tick (CaseOfCase case_bndr) ; (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont -- NB: We call prepareCaseCont here. If there is only one -- alternative, then dup_cont may be big, but that's ok -- because we push it into the single alternative, and then -- use mkDupableAlt to turn that simplified alternative into -- a join point if it's too big to duplicate. -- And this is important: see Note [Fusing case continuations] ; let alt_env = se `setInScope` env' ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts -- Safe to say that there are no handled-cons for the DEFAULT case -- NB: simplBinder does not zap deadness occ-info, so -- a dead case_bndr' will still advertise its deadness -- This is really important because in -- case e of b { (# p,q #) -> ... } -- b is always dead, and indeed we are not allowed to bind b to (# p,q #), -- which might happen if e was an explicit unboxed pair and b wasn't marked dead. -- In the new alts we build, we have the new case binder, so it must retain -- its deadness. -- NB: we don't use alt_env further; it has the substEnv for -- the alternatives, and we don't want that ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts' ; return (env'', -- Note [Duplicated env] Select OkToDup case_bndr' alts'' (zapSubstEnv env'') (mkBoringStop (contHoleType nodup_cont)), nodup_cont) } mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplM (SimplEnv, [InAlt]) -- Absorbs the continuation into the new alternatives mkDupableAlts env case_bndr' the_alts = go env the_alts where go env0 [] = return (env0, []) go env0 (alt:alts) = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt ; (env2, alts') <- go env1 alts ; return (env2, alt' : alts' ) } mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr) -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr)) mkDupableAlt env case_bndr (con, bndrs', rhs') = do dflags <- getDynFlags if exprIsDupable dflags rhs' -- Note [Small alternative rhs] then return (env, (con, bndrs', rhs')) else do { let rhs_ty' = exprType rhs' scrut_ty = idType case_bndr case_bndr_w_unf = case con of DEFAULT -> case_bndr DataAlt dc -> setIdUnfolding case_bndr unf where -- See Note [Case binders and join points] unf = mkInlineUnfolding Nothing rhs rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs' LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt") <+> ppr case_bndr <+> ppr con ) case_bndr -- The case binder is alive but trivial, so why has -- it not been substituted away? used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs' | otherwise = bndrs' ++ [case_bndr_w_unf] abstract_over bndr | isTyVar bndr = True -- Abstract over all type variables just in case | otherwise = not (isDeadBinder bndr) -- The deadness info on the new Ids is preserved by simplBinders ; (final_bndrs', final_args) -- Note [Join point abstraction] <- if (any isId used_bndrs') then return (used_bndrs', varsToCoreExprs used_bndrs') else do { rw_id <- newId (fsLit "w") voidPrimTy ; return ([setOneShotLambda rw_id], [Var voidPrimId]) } ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty') -- Note [Funky mkPiTypes] ; let -- We make the lambdas into one-shot-lambdas. The -- join point is sure to be applied at most once, and doing so -- prevents the body of the join point being floated out by -- the full laziness pass really_final_bndrs = map one_shot final_bndrs' one_shot v | isId v = setOneShotLambda v | otherwise = v join_rhs = mkLams really_final_bndrs rhs' join_arity = exprArity join_rhs join_call = mkApps (Var join_bndr) final_args ; env' <- addPolyBind NotTopLevel env (NonRec (join_bndr `setIdArity` join_arity) join_rhs) ; return (env', (con, bndrs', join_call)) } -- See Note [Duplicated env] {- Note [Fusing case continuations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's important to fuse two successive case continuations when the first has one alternative. That's why we call prepareCaseCont here. Consider this, which arises from thunk splitting (see Note [Thunk splitting] in WorkWrap): let x* = case (case v of {pn -> rn}) of I# a -> I# a in body The simplifier will find (Var v) with continuation Select (pn -> rn) ( Select [I# a -> I# a] ( StrictBind body Stop So we'll call mkDupableCont on Select [I# a -> I# a] (StrictBind body Stop) There is just one alternative in the first Select, so we want to simplify the rhs (I# a) with continuation (StricgtBind body Stop) Supposing that body is big, we end up with let $j a = <let x = I# a in body> in case v of { pn -> case rn of I# a -> $j a } This is just what we want because the rn produces a box that the case rn cancels with. See Trac #4957 a fuller example. Note [Case binders and join points] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this case (case .. ) of c { I# c# -> ....c.... If we make a join point with c but not c# we get $j = \c -> ....c.... But if later inlining scrutines the c, thus $j = \c -> ... case c of { I# y -> ... } ... we won't see that 'c' has already been scrutinised. This actually happens in the 'tabulate' function in wave4main, and makes a significant difference to allocation. An alternative plan is this: $j = \c# -> let c = I# c# in ...c.... but that is bad if 'c' is *not* later scrutinised. So instead we do both: we pass 'c' and 'c#' , and record in c's inlining (a stable unfolding) that it's really I# c#, thus $j = \c# -> \c[=I# c#] -> ...c.... Absence analysis may later discard 'c'. NB: take great care when doing strictness analysis; see Note [Lamba-bound unfoldings] in DmdAnal. Also note that we can still end up passing stuff that isn't used. Before strictness analysis we have let $j x y c{=(x,y)} = (h c, ...) in ... After strictness analysis we see that h is strict, we end up with let $j x y c{=(x,y)} = ($wh x y, ...) and c is unused. Note [Duplicated env] ~~~~~~~~~~~~~~~~~~~~~ Some of the alternatives are simplified, but have not been turned into a join point So they *must* have an zapped subst-env. So we can't use completeNonRecX to bind the join point, because it might to do PostInlineUnconditionally, and we'd lose that when zapping the subst-env. We could have a per-alt subst-env, but zapping it (as we do in mkDupableCont, the Select case) is safe, and at worst delays the join-point inlining. Note [Small alternative rhs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is worth checking for a small RHS because otherwise we get extra let bindings that may cause an extra iteration of the simplifier to inline back in place. Quite often the rhs is just a variable or constructor. The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra iterations because the version with the let bindings looked big, and so wasn't inlined, but after the join points had been inlined it looked smaller, and so was inlined. NB: we have to check the size of rhs', not rhs. Duplicating a small InAlt might invalidate occurrence information However, if it *is* dupable, we return the *un* simplified alternative, because otherwise we'd need to pair it up with an empty subst-env.... but we only have one env shared between all the alts. (Remember we must zap the subst-env before re-simplifying something). Rather than do this we simply agree to re-simplify the original (small) thing later. Note [Funky mkPiTypes] ~~~~~~~~~~~~~~~~~~~~~~ Notice the funky mkPiTypes. If the contructor has existentials it's possible that the join point will be abstracted over type variables as well as term variables. Example: Suppose we have data T = forall t. C [t] Then faced with case (case e of ...) of C t xs::[t] -> rhs We get the join point let j :: forall t. [t] -> ... j = /\t \xs::[t] -> rhs in case (case e of ...) of C t xs::[t] -> j t xs Note [Join point abstraction] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Join points always have at least one value argument, for several reasons * If we try to lift a primitive-typed something out for let-binding-purposes, we will *caseify* it (!), with potentially-disastrous strictness results. So instead we turn it into a function: \v -> e where v::Void#. The value passed to this function is void, which generates (almost) no code. * CPR. We used to say "&& isUnLiftedType rhs_ty'" here, but now we make the join point into a function whenever used_bndrs' is empty. This makes the join-point more CPR friendly. Consider: let j = if .. then I# 3 else I# 4 in case .. of { A -> j; B -> j; C -> ... } Now CPR doesn't w/w j because it's a thunk, so that means that the enclosing function can't w/w either, which is a lose. Here's the example that happened in practice: kgmod :: Int -> Int -> Int kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0 then 78 else 5 * Let-no-escape. We want a join point to turn into a let-no-escape so that it is implemented as a jump, and one of the conditions for LNE is that it's not updatable. In CoreToStg, see Note [What is a non-escaping let] * Floating. Since a join point will be entered once, no sharing is gained by floating out, but something might be lost by doing so because it might be allocated. I have seen a case alternative like this: True -> \v -> ... It's a bit silly to add the realWorld dummy arg in this case, making $j = \s v -> ... True -> $j s (the \v alone is enough to make CPR happy) but I think it's rare There's a slight infelicity here: we pass the overall case_bndr to all the join points if it's used in *any* RHS, because we don't know its usage in each RHS separately Note [Duplicating StrictArg] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The original plan had (where E is a big argument) e.g. f E [..hole..] ==> let $j = \a -> f E a in $j [..hole..] But this is terrible! Here's an example: && E (case x of { T -> F; F -> T }) Now, && is strict so we end up simplifying the case with an ArgOf continuation. If we let-bind it, we get let $j = \v -> && E v in simplExpr (case x of { T -> F; F -> T }) (ArgOf (\r -> $j r) And after simplifying more we get let $j = \v -> && E v in case x of { T -> $j F; F -> $j T } Which is a Very Bad Thing What we do now is this f E [..hole..] ==> let a = E in f a [..hole..] Now if the thing in the hole is a case expression (which is when we'll call mkDupableCont), we'll push the function call into the branches, which is what we want. Now RULES for f may fire, and call-pattern specialisation. Here's an example from Trac #3116 go (n+1) (case l of 1 -> bs' _ -> Chunk p fpc (o+1) (l-1) bs') If we can push the call for 'go' inside the case, we get call-pattern specialisation for 'go', which is *crucial* for this program. Here is the (&&) example: && E (case x of { T -> F; F -> T }) ==> let a = E in case x of { T -> && a F; F -> && a T } Much better! Notice that * Arguments to f *after* the strict one are handled by the ApplyToVal case of mkDupableCont. Eg f [..hole..] E * We can only do the let-binding of E because the function part of a StrictArg continuation is an explicit syntax tree. In earlier versions we represented it as a function (CoreExpr -> CoreEpxr) which we couldn't take apart. Do *not* duplicate StrictBind and StritArg continuations. We gain nothing by propagating them into the expressions, and we do lose a lot. The desire not to duplicate is the entire reason that mkDupableCont returns a pair of continuations. Note [Duplicating StrictBind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unlike StrictArg, there doesn't seem anything to gain from duplicating a StrictBind continuation, so we don't. Note [Single-alternative cases] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This case is just like the ArgOf case. Here's an example: data T a = MkT !a ...(MkT (abs x))... Then we get case (case x of I# x' -> case x' <# 0# of True -> I# (negate# x') False -> I# x') of y { DEFAULT -> MkT y Because the (case x) has only one alternative, we'll transform to case x of I# x' -> case (case x' <# 0# of True -> I# (negate# x') False -> I# x') of y { DEFAULT -> MkT y But now we do *NOT* want to make a join point etc, giving case x of I# x' -> let $j = \y -> MkT y in case x' <# 0# of True -> $j (I# (negate# x')) False -> $j (I# x') In this case the $j will inline again, but suppose there was a big strict computation enclosing the orginal call to MkT. Then, it won't "see" the MkT any more, because it's big and won't get duplicated. And, what is worse, nothing was gained by the case-of-case transform. So, in circumstances like these, we don't want to build join points and push the outer case into the branches of the inner one. Instead, don't duplicate the continuation. When should we use this strategy? We should not use it on *every* single-alternative case: e.g. case (case ....) of (a,b) -> (# a,b #) Here we must push the outer case into the inner one! Other choices: * Match [(DEFAULT,_,_)], but in the common case of Int, the alternative-filling-in code turned the outer case into case (...) of y { I# _ -> MkT y } * Match on single alternative plus (not (isDeadBinder case_bndr)) Rationale: pushing the case inwards won't eliminate the construction. But there's a risk of case (...) of y { (a,b) -> let z=(a,b) in ... } Now y looks dead, but it'll come alive again. Still, this seems like the best option at the moment. * Match on single alternative plus (all (isDeadBinder bndrs)) Rationale: this is essentially seq. * Match when the rhs is *not* duplicable, and hence would lead to a join point. This catches the disaster-case above. We can test the *un-simplified* rhs, which is fine. It might get bigger or smaller after simplification; if it gets smaller, this case might fire next time round. NB also that we must test contIsDupable case_cont *too, because case_cont might be big! HOWEVER: I found that this version doesn't work well, because we can get let x = case (...) of { small } in ...case x... When x is inlined into its full context, we find that it was a bad idea to have pushed the outer case inside the (...) case. Note [Single-alternative-unlifted] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here's another single-alternative where we really want to do case-of-case: data Mk1 = Mk1 Int# | Mk2 Int# M1.f = \r [x_s74 y_s6X] case case y_s6X of tpl_s7m { M1.Mk1 ipv_s70 -> ipv_s70; M1.Mk2 ipv_s72 -> ipv_s72; } of wild_s7c { __DEFAULT -> case case x_s74 of tpl_s7n { M1.Mk1 ipv_s77 -> ipv_s77; M1.Mk2 ipv_s79 -> ipv_s79; } of wild1_s7b { __DEFAULT -> ==# [wild1_s7b wild_s7c]; }; }; So the outer case is doing *nothing at all*, other than serving as a join-point. In this case we really want to do case-of-case and decide whether to use a real join point or just duplicate the continuation: let $j s7c = case x of Mk1 ipv77 -> (==) s7c ipv77 Mk1 ipv79 -> (==) s7c ipv79 in case y of Mk1 ipv70 -> $j ipv70 Mk2 ipv72 -> $j ipv72 Hence: check whether the case binder's type is unlifted, because then the outer case is *not* a seq. ************************************************************************ * * Unfoldings * * ************************************************************************ -} simplLetUnfolding :: SimplEnv-> TopLevelFlag -> InId -> OutExpr -> Unfolding -> SimplM Unfolding simplLetUnfolding env top_lvl id new_rhs unf | isStableUnfolding unf = simplUnfolding env top_lvl id unf | otherwise = bottoming `seq` -- See Note [Force bottoming field] do { dflags <- getDynFlags ; return (mkUnfolding dflags InlineRhs (isTopLevel top_lvl) bottoming new_rhs) } -- We make an unfolding *even for loop-breakers*. -- Reason: (a) It might be useful to know that they are WHNF -- (b) In TidyPgm we currently assume that, if we want to -- expose the unfolding then indeed we *have* an unfolding -- to expose. (We could instead use the RHS, but currently -- we don't.) The simple thing is always to have one. where bottoming = isBottomingId id simplUnfolding :: SimplEnv-> TopLevelFlag -> InId -> Unfolding -> SimplM Unfolding -- Note [Setting the new unfolding] simplUnfolding env top_lvl id unf = case unf of NoUnfolding -> return unf OtherCon {} -> return unf DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args } -> do { (env', bndrs') <- simplBinders rule_env bndrs ; args' <- mapM (simplExpr env') args ; return (mkDFunUnfolding bndrs' con args') } CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide } | isStableSource src -> do { expr' <- simplExpr rule_env expr ; case guide of UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things -> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok , ug_boring_ok = inlineBoringOk expr' } -- Refresh the boring-ok flag, in case expr' -- has got small. This happens, notably in the inlinings -- for dfuns for single-method classes; see -- Note [Single-method classes] in TcInstDcls. -- A test case is Trac #4138 in return (mkCoreUnfolding src is_top_lvl expr' guide') -- See Note [Top-level flag on inline rules] in CoreUnfold _other -- Happens for INLINABLE things -> bottoming `seq` -- See Note [Force bottoming field] do { dflags <- getDynFlags ; return (mkUnfolding dflags src is_top_lvl bottoming expr') } } -- If the guidance is UnfIfGoodArgs, this is an INLINABLE -- unfolding, and we need to make sure the guidance is kept up -- to date with respect to any changes in the unfolding. | otherwise -> return noUnfolding -- Discard unstable unfoldings where bottoming = isBottomingId id is_top_lvl = isTopLevel top_lvl act = idInlineActivation id rule_env = updMode (updModeForStableUnfoldings act) env -- See Note [Simplifying inside stable unfoldings] in SimplUtils {- Note [Force bottoming field] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to force bottoming, or the new unfolding holds on to the old unfolding (which is part of the id). Note [Setting the new unfolding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * If there's an INLINE pragma, we simplify the RHS gently. Maybe we should do nothing at all, but simplifying gently might get rid of more crap. * If not, we make an unfolding from the new RHS. But *only* for non-loop-breakers. Making loop breakers not have an unfolding at all means that we can avoid tests in exprIsConApp, for example. This is important: if exprIsConApp says 'yes' for a recursive thing, then we can get into an infinite loop If there's an stable unfolding on a loop breaker (which happens for INLINEABLE), we hang on to the inlining. It's pretty dodgy, but the user did say 'INLINE'. May need to revisit this choice. ************************************************************************ * * Rules * * ************************************************************************ Note [Rules in a letrec] ~~~~~~~~~~~~~~~~~~~~~~~~ After creating fresh binders for the binders of a letrec, we substitute the RULES and add them back onto the binders; this is done *before* processing any of the RHSs. This is important. Manuel found cases where he really, really wanted a RULE for a recursive function to apply in that function's own right-hand side. See Note [Loop breaking and RULES] in OccAnal. -} addBndrRules :: SimplEnv -> InBndr -> OutBndr -> SimplM (SimplEnv, OutBndr) -- Rules are added back into the bin addBndrRules env in_id out_id | null old_rules = return (env, out_id) | otherwise = do { new_rules <- simplRules env (Just (idName out_id)) old_rules ; let final_id = out_id `setIdSpecialisation` mkRuleInfo new_rules ; return (modifyInScope env final_id, final_id) } where old_rules = ruleInfoRules (idSpecialisation in_id) simplRules :: SimplEnv -> Maybe Name -> [CoreRule] -> SimplM [CoreRule] simplRules env mb_new_nm rules = mapM simpl_rule rules where simpl_rule rule@(BuiltinRule {}) = return rule simpl_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args , ru_fn = fn_name, ru_rhs = rhs }) = do { (env', bndrs') <- simplBinders env bndrs ; let rule_env = updMode updModeForRules env' ; args' <- mapM (simplExpr rule_env) args ; rhs' <- simplExpr rule_env rhs ; return (rule { ru_bndrs = bndrs' , ru_fn = mb_new_nm `orElse` fn_name , ru_args = args' , ru_rhs = rhs' }) }
rahulmutt/ghcvm
compiler/Eta/SimplCore/Simplify.hs
bsd-3-clause
123,358
20
25
37,632
15,229
8,069
7,160
-1
-1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- -- | Main import module for the front-end lanugage. {-# LANGUAGE Safe #-} module Copilot ( module Copilot.Language ) where import Copilot.Language --------------------------------------------------------------------------------
niswegmann/copilot-language
src/Copilot.hs
bsd-3-clause
467
0
5
45
23
17
6
4
0
{-| Module : Main Copyright : (c) Henry J. Wylde, 2015 License : BSD3 Maintainer : [email protected] -} module Main ( main ) where import Control.Monad import Qux.Test.Integration import Qux.Test.Steps import System.Directory import System.FilePath import Test.Tasty import Test.Tasty.Golden main :: IO () main = defaultMain =<< tests tests :: IO TestTree tests = do testsDir <- getCurrentDirectory >>= \dir -> return $ dir </> "test" </> "build" </> "tests" testDirs <- filter ((/= '.') . head) <$> getDirectoryContents testsDir testTrees <- mapM test =<< filterM (\testDir -> not <$> doesFileExist (testDir </> "pending")) (map (combine testsDir) testDirs) return $ testGroup "Tests" testTrees test :: String -> IO TestTree test dir = do let name = takeFileName dir clean dir return $ goldenVsFile name (expectedOutputFilePath dir) (actualOutputFilePath dir) (withCurrentDirectory dir $ build ".")
qux-lang/qux
test/build/app/Main.hs
bsd-3-clause
1,004
0
15
236
286
146
140
27
1
{-# LANGUAGE ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances, OverlappingInstances, IncoherentInstances #-} -- | Pretty printing utils. -- Taken from BuildBox 2.1.0.1: -- http://hackage.haskell.org/packages/archive/buildbox/2.1.0.1/doc/html/BuildBox-Pretty.html module Pretty ( module Text.PrettyPrint , Pretty(..) , padRc, padR , padLc, padL , blank , pprEngDouble , pprEngInteger , pprTimestampAbs , pprTimestampEng , pprValidate , pprMap , renderLong , padLines , chunks' , chunks , trunc) where import Text.PrettyPrint import Text.Printf import Control.Monad import GHC.RTS.Events (Timestamp) import qualified Data.Map as M import Data.Maybe (fromMaybe) -- Things that can be pretty printed class Pretty a where ppr :: a -> Doc -- Basic instances instance Pretty Doc where ppr = id instance Pretty Float where ppr = text . show instance Pretty Int where ppr = int instance Pretty Integer where ppr = text . show {- instance Pretty UTCTime where ppr = text . show -} instance Pretty Timestamp where ppr = text . show instance Pretty a => Pretty [a] where ppr xx = lbrack <> (hcat $ punctuate (text ", ") (map ppr xx)) <> rbrack instance Pretty String where ppr = text -- | Right justify a doc, padding with a given character. padRc :: Int -> Char -> Doc -> Doc padRc n c str = (text $ replicate (n - length (render str)) c) <> str -- | Right justify a string with spaces. padR :: Int -> Doc -> Doc padR n str = padRc n ' ' str -- | Left justify a string, padding with a given character. padLc :: Int -> Char -> Doc -> Doc padLc n c str = str <> (text $ replicate (n - length (render str)) c) -- | Left justify a string with spaces. padL :: Int -> Doc -> Doc padL n str = padLc n ' ' str -- | Blank text. This is different different from `empty` because it comes out a a newline when used in a `vcat`. blank :: Doc blank = ppr "" -- | Like `pprEngDouble` but don't display fractional part when the value is < 1000. -- Good for units where fractional values might not make sense (like bytes). pprEngInteger :: String -> Integer -> Maybe Doc pprEngInteger unit k | k < 0 = liftM (text "-" <>) $ pprEngInteger unit (-k) | k > 1000 = pprEngDouble unit (fromRational $ toRational k) | otherwise = Just $ text $ printf "%5d%s " k unit -- | Pretty print an engineering value, to 4 significant figures. -- Valid range is 10^(-24) (y\/yocto) to 10^(+24) (Y\/Yotta). -- Out of range values yield Nothing. -- -- examples: -- -- @ -- liftM render $ pprEngDouble \"J\" 102400 ==> Just \"1.024MJ\" -- liftM render $ pprEngDouble \"s\" 0.0000123 ==> Just \"12.30us\" -- @ -- pprEngDouble :: String -> Double -> Maybe Doc pprEngDouble unit k | k < 0 = liftM (text "-" <>) $ pprEngDouble unit (-k) | k >= 1e+27 = Nothing | k >= 1e+24 = Just $ (k*1e-24) `with` ("Y" ++ unit) | k >= 1e+21 = Just $ (k*1e-21) `with` ("Z" ++ unit) | k >= 1e+18 = Just $ (k*1e-18) `with` ("E" ++ unit) | k >= 1e+15 = Just $ (k*1e-15) `with` ("P" ++ unit) | k >= 1e+12 = Just $ (k*1e-12) `with` ("T" ++ unit) | k >= 1e+9 = Just $ (k*1e-9) `with` ("G" ++ unit) | k >= 1e+6 = Just $ (k*1e-6) `with` ("M" ++ unit) | k >= 1e+3 = Just $ (k*1e-3) `with` ("k" ++ unit) | k >= 1 = Just $ k `with` (unit ++ " ") | k >= 1e-3 = Just $ (k*1e+3) `with` ("m" ++ unit) | k >= 1e-6 = Just $ (k*1e+6) `with` ("u" ++ unit) | k >= 1e-9 = Just $ (k*1e+9) `with` ("n" ++ unit) | k >= 1e-12 = Just $ (k*1e+12) `with` ("p" ++ unit) | k >= 1e-15 = Just $ (k*1e+15) `with` ("f" ++ unit) | k >= 1e-18 = Just $ (k*1e+18) `with` ("a" ++ unit) | k >= 1e-21 = Just $ (k*1e+21) `with` ("z" ++ unit) | k >= 1e-24 = Just $ (k*1e+24) `with` ("y" ++ unit) | k >= 1e-27 = Nothing | otherwise = Just $ text $ printf "%5.0f%s " k unit where with (t :: Double) (u :: String) | t >= 1e3 = text $ printf "%.0f%s" t u | t >= 1e2 = text $ printf "%.1f%s" t u | t >= 1e1 = text $ printf "%.2f%s" t u | otherwise = text $ printf "%.3f%s" t u -- | print an absolute time, in the format used by threadscope pprTimestampAbs :: Timestamp -> Doc pprTimestampAbs v = text (printf "%.9fs" v') where v' = fromIntegral v / 1e+9 :: Double pprTimestampEng :: Timestamp -> Doc pprTimestampEng v = fromMaybe (text "-") (pprEngDouble "s" v') where v' = fromIntegral v / 1e+9 pprValidate :: (s -> Doc) -> (i -> Doc) -> Either (s, i) s -> Doc pprValidate pprState pprInput (Left (state, input)) = vcat [ text "Invalid eventlog:" , text "State:" , pprState state , text "Input:" , pprInput input ] pprValidate pprState _ (Right state) = vcat [ text "Valid eventlog: ", pprState state ] pprMap :: Ord k => (k -> Doc) -> (a -> Doc) -> M.Map k a -> Doc pprMap pprKey pprValue m = vcat $ zipWith (<>) (map pprKey . M.keys $ m) (map (pprValue . (M.!) m) . M.keys $ m) renderLong :: Doc -> String renderLong = renderStyle (style { lineLength = 200 }) padLines :: Doc -> String -> Doc padLines left right = let (x:xs) = chunks' trunc_len right pad' = text $ replicate (length (render left)) ' ' in vcat $ (left <> text x) : map (\s -> pad' <> text s) xs trunc_len :: Int trunc_len = 100 trunc :: String -> String trunc l | length l > trunc_len = take (trunc_len-4) l ++ " ..." | otherwise = l chunks' :: Int -> String -> [String] chunks' len str = case chunks len str of (x:xs) -> (x:xs) [] -> [""] chunks :: Int -> String -> [String] chunks len [] = [] chunks len str = let (f,r) = splitAt len str in f : chunks len r
mainland/dph
dph-event-seer/src/Pretty.hs
bsd-3-clause
5,727
29
14
1,449
2,133
1,135
998
136
2
{-# LANGUAGE TypeFamilies, DataKinds, UndecidableInstances #-} module T6018failclosed1 where -- Id is injective... type family IdClosed a = result | result -> a where IdClosed a = a -- ...but despite that we disallow a call to Id type family IdProxyClosed a = r | r -> a where IdProxyClosed a = IdClosed a
acowley/ghc
testsuite/tests/typecheck/should_fail/T6018failclosed1.hs
bsd-3-clause
317
0
6
65
56
37
19
6
0
{-| Module : Data.OrgMode.Parse.Types Copyright : © 2014 Parnell Springmeyer License : All Rights Reserved Maintainer : Parnell Springmeyer <[email protected]> Stability : experimental Types and utility functions. -} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Data.OrgMode.Parse.Types ( Document (..) , Section (..) , Level (..) , Heading (..) , Priority (..) , Plannings (..) , StateKeyword (..) , Duration , PlanningKeyword (..) , Properties , Timestamp (..) , DateTime (..) , Stats (..) , Tag , TimeUnit (..) , RepeaterType (..) , Repeater (..) , DelayType (..) , Delay (..) , LevelDepth (..) , TitleMeta (..) , YearMonthDay(..) , YearMonthDay'(..) ) where import Control.Applicative import Control.Monad (mzero) import Data.Aeson ((.:), (.=)) import qualified Data.Aeson as A import Data.Hashable (Hashable (..)) import Data.HashMap.Strict (HashMap, fromList, keys, toList) import Data.Text (Text, pack) import Data.Thyme.Calendar (YearMonthDay (..)) import Data.Thyme.LocalTime (Hour, Minute) import Data.Traversable import GHC.Generics data Document = Document { documentText :: Text -- ^ Text occurring before any Org headlines , documentHeadings :: [Heading] -- ^ Toplevel Org headlines } deriving (Show, Eq, Generic) instance A.ToJSON Document where instance A.FromJSON Document where newtype LevelDepth = LevelDepth Int deriving (Eq, Show, Num) data TitleMeta = TitleMeta Text (Maybe Stats) (Maybe [Tag]) deriving (Eq, Show) data Heading = Heading { level :: Level -- ^ Org headline nesting level (1 is at the top) , keyword :: Maybe StateKeyword -- ^ State of the headline (e.g. TODO, DONE) , priority :: Maybe Priority -- , title :: Text -- properties , stats :: Maybe Stats -- , tags :: [Tag] -- , section :: Section -- Next-line , subHeadings :: [Heading] -- elements } deriving (Show, Eq, Generic) newtype Level = Level Int deriving (Eq, Show, Num, Generic) type Properties = HashMap Text Text type Clock = (Maybe Timestamp, Maybe Duration) data Section = Section { sectionPlannings :: Plannings , sectionClocks :: [Clock] , sectionProperties :: Properties , sectionParagraph :: Text } deriving (Show, Eq, Generic) data Timestamp = Timestamp { tsTime :: DateTime , tsActive :: Bool , tsEndTime :: Maybe DateTime } deriving (Show, Eq, Generic) instance A.ToJSON Timestamp where instance A.FromJSON Timestamp where newtype YearMonthDay' = YMD' YearMonthDay deriving (Show, Eq, Generic) instance A.ToJSON YearMonthDay' where toJSON (YMD' (YearMonthDay y m d)) = A.object ["ymdYear" .= y ,"ymdMonth" .= m ,"ymdDay" .= d] instance A.FromJSON YearMonthDay' where parseJSON (A.Object v) = do y <- v .: "ymdYear" m <- v .: "ymdMonth" d <- v .: "ymdDay" return (YMD' (YearMonthDay y m d)) parseJSON _ = mzero data DateTime = DateTime { yearMonthDay :: YearMonthDay' , dayName :: Maybe Text , hourMinute :: Maybe (Hour,Minute) , repeater :: Maybe Repeater , delay :: Maybe Delay } deriving (Show, Eq, Generic) instance A.ToJSON DateTime where instance A.FromJSON DateTime where data RepeaterType = RepeatCumulate | RepeatCatchUp | RepeatRestart deriving (Show, Eq, Generic) instance A.ToJSON RepeaterType instance A.FromJSON RepeaterType data Repeater = Repeater { repeaterType :: RepeaterType , repeaterValue :: Int , repeaterUnit :: TimeUnit } deriving (Show, Eq, Generic) instance A.ToJSON Repeater where instance A.FromJSON Repeater where data DelayType = DelayAll | DelayFirst deriving (Show, Eq, Generic) instance A.ToJSON DelayType where instance A.FromJSON DelayType where data Delay = Delay { delayType :: DelayType , delayValue :: Int , delayUnit :: TimeUnit } deriving (Show, Eq, Generic) instance A.ToJSON Delay where instance A.FromJSON Delay where data TimeUnit = UnitYear | UnitWeek | UnitMonth | UnitDay | UnitHour deriving (Show, Eq, Generic) instance A.ToJSON TimeUnit where instance A.FromJSON TimeUnit where --------------------------------------------------------------------------- --instance A.ToJSON Document where --instance A.FromJSON Document where instance A.ToJSON Level where instance A.FromJSON Level where newtype StateKeyword = StateKeyword {unStateKeyword :: Text} deriving (Show, Eq, Generic) instance A.ToJSON StateKeyword where instance A.FromJSON StateKeyword where data PlanningKeyword = SCHEDULED | DEADLINE | CLOSED deriving (Show, Eq, Enum, Ord, Generic) instance A.ToJSON PlanningKeyword where instance A.FromJSON PlanningKeyword where --instance (A.ToJSON k, A.ToJSON v) => A.ToJSON (HashMap k v) where -- toJSON hm = A.object hm newtype Plannings = Plns (HashMap PlanningKeyword Timestamp) deriving (Show, Eq, Generic) instance A.ToJSON Plannings where toJSON (Plns hm) = A.object $ map jPair (toList hm) where jPair (k, v) = pack (show k) .= A.toJSON v instance A.FromJSON Plannings where parseJSON (A.Object v) = Plns . fromList <$> (traverse jPair (keys v)) where jPair k = v .: k parseJSON _ = mzero instance A.ToJSON Section where instance A.FromJSON Section where instance A.ToJSON Heading where instance A.FromJSON Heading where data Priority = A | B | C deriving (Show, Read, Eq, Ord, Generic) instance A.ToJSON Priority where instance A.FromJSON Priority where type Tag = Text data Stats = StatsPct Int | StatsOf Int Int deriving (Show, Eq, Generic) instance A.ToJSON Stats where instance A.FromJSON Stats where type Duration = (Hour,Minute) instance Hashable PlanningKeyword where hashWithSalt salt k = hashWithSalt salt (fromEnum k) -- -- This might be the form to use if we were supporting <diary> timestamps -- data Timestamp = Dairy Text -- | Time TimestampTime -- deriving (Show, Eq, Generic)
imalsogreg/orgmode-parse
src/Data/OrgMode/Parse/Types.hs
bsd-3-clause
6,430
0
12
1,617
1,715
979
736
163
0
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} module Int where import Language.VHDL (Mode(..)) import Language.Embedded.Hardware import Control.Monad.Identity import Control.Monad.Operational.Higher import Data.ALaCarte import Data.Int import Data.Word import Text.PrettyPrint import Prelude hiding (and, or, not) -------------------------------------------------------------------------------- -- * Example of a program that performs type casting. -------------------------------------------------------------------------------- -- | Command set used for our programs. type CMD = SignalCMD :+: VariableCMD :+: ArrayCMD :+: VArrayCMD :+: LoopCMD :+: ConditionalCMD :+: ComponentCMD :+: ProcessCMD :+: VHDLCMD type HProg = Program CMD (Param2 HExp HType) type HSig = Sig CMD HExp HType Identity -------------------------------------------------------------------------------- integers :: HProg () integers = do arr :: VArray Word8 <- initVArray [0..10] ref :: Variable Word8 <- initVariable 10 setVArray arr 0 20 for 0 10 $ \i -> do v <- getVArray arr (10 - i) setVArray arr i v v0 <- getVArray arr 0 v1 <- getVArray arr 1 iff (v0 `lte` 5) (setVArray arr 0 5) (iff (v1 `lte` 5) (setVArray arr 1 5) (setVArray arr 1 10)) -------------------------------------------------------------------------------- test = icompile integers --------------------------------------------------------------------------------
markus-git/imperative-edsl-vhdl
examples/Int.hs
bsd-3-clause
1,630
0
14
319
365
196
169
42
1
{-# LINE 1 "Database/MySQL/Base/C.hsc" #-} {-# LANGUAGE CPP, EmptyDataDecls, ForeignFunctionInterface #-} {-# LINE 2 "Database/MySQL/Base/C.hsc" #-} -- | -- Module: Database.MySQL.Base.C -- Copyright: (c) 2011 MailRank, Inc. -- License: BSD3 -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable -- -- Direct bindings to the C @mysqlclient@ API. module Database.MySQL.Base.C ( -- * Connection management mysql_init , mysql_options , mysql_ssl_set , mysql_real_connect , mysql_close , mysql_ping , mysql_autocommit , mysql_change_user , mysql_select_db , mysql_set_character_set -- ** Connection information , mysql_thread_id , mysql_get_server_info , mysql_get_host_info , mysql_get_proto_info , mysql_character_set_name , mysql_get_ssl_cipher , mysql_stat -- * Querying , mysql_real_query , mysql_insert_id -- ** Escaping , mysql_real_escape_string -- ** Results , mysql_field_count , mysql_affected_rows , mysql_store_result , mysql_use_result , mysql_fetch_lengths , mysql_fetch_lengths_nonblock , mysql_fetch_row , mysql_fetch_row_nonblock -- * Working with results , mysql_free_result , mysql_free_result_nonblock , mysql_fetch_fields , mysql_fetch_fields_nonblock , mysql_data_seek , mysql_row_seek , mysql_row_tell -- ** Multiple results , mysql_next_result -- * Transactions , mysql_commit , mysql_rollback -- * General information , mysql_get_client_info , mysql_get_client_version -- * Error handling , mysql_errno , mysql_error ) where {-# LINE 69 "Database/MySQL/Base/C.hsc" #-} {-# LINE 70 "Database/MySQL/Base/C.hsc" #-} import Data.ByteString.Unsafe (unsafeUseAsCString) import Database.MySQL.Base.Types import Foreign.C.String (CString, withCString) #if __GLASGOW_HASKELL__ >= 704 import Foreign.C.Types (CChar(..), CInt(..), CUInt(..), CULLong(..), CULong(..)) #else import Foreign.C.Types (CInt, CUInt, CULLong, CULong) #endif import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, nullPtr) foreign import ccall safe mysql_init :: Ptr MYSQL -- ^ should usually be 'nullPtr' -> IO (Ptr MYSQL) mysql_options :: Ptr MYSQL -> Option -> IO CInt mysql_options ptr opt = case opt of ConnectTimeout secs -> withIntegral secs $ go (0) {-# LINE 91 "Database/MySQL/Base/C.hsc" #-} Compress -> go (1) nullPtr {-# LINE 93 "Database/MySQL/Base/C.hsc" #-} NamedPipe -> go (2) nullPtr {-# LINE 95 "Database/MySQL/Base/C.hsc" #-} InitCommand cmd -> unsafeUseAsCString cmd $ go (3) {-# LINE 97 "Database/MySQL/Base/C.hsc" #-} ReadDefaultFile path -> withCString path $ go (4) {-# LINE 99 "Database/MySQL/Base/C.hsc" #-} ReadDefaultGroup group -> unsafeUseAsCString group $ go (5) {-# LINE 101 "Database/MySQL/Base/C.hsc" #-} CharsetDir path -> withCString path $ go (6) {-# LINE 103 "Database/MySQL/Base/C.hsc" #-} CharsetName cs -> withCString cs $ go (7) {-# LINE 105 "Database/MySQL/Base/C.hsc" #-} LocalInFile b -> withBool b $ go (8) {-# LINE 107 "Database/MySQL/Base/C.hsc" #-} Protocol proto -> withIntegral (fromEnum proto) $ go (9) {-# LINE 109 "Database/MySQL/Base/C.hsc" #-} SharedMemoryBaseName name -> unsafeUseAsCString name $ go (10) {-# LINE 111 "Database/MySQL/Base/C.hsc" #-} ReadTimeout secs -> withIntegral secs $ go (11) {-# LINE 113 "Database/MySQL/Base/C.hsc" #-} WriteTimeout secs -> withIntegral secs $ go (12) {-# LINE 115 "Database/MySQL/Base/C.hsc" #-} UseRemoteConnection -> go (14) nullPtr {-# LINE 117 "Database/MySQL/Base/C.hsc" #-} UseEmbeddedConnection -> go (15) nullPtr {-# LINE 119 "Database/MySQL/Base/C.hsc" #-} GuessConnection -> go (16) nullPtr {-# LINE 121 "Database/MySQL/Base/C.hsc" #-} ClientIP ip -> unsafeUseAsCString ip $ go (17) {-# LINE 123 "Database/MySQL/Base/C.hsc" #-} SecureAuth b -> withBool b $ go (18) {-# LINE 125 "Database/MySQL/Base/C.hsc" #-} ReportDataTruncation b -> withBool b $ go (19) {-# LINE 127 "Database/MySQL/Base/C.hsc" #-} Reconnect b -> withBool b $ go (20) {-# LINE 129 "Database/MySQL/Base/C.hsc" #-} SSLVerifyServerCert b -> withBool b $ go (21) {-# LINE 131 "Database/MySQL/Base/C.hsc" #-} -- Other options are accepted by mysql_real_connect, so ignore them. _ -> return 0 where go = mysql_options_ ptr withBool b = with (if b then 1 else 0 :: CUInt) withIntegral i = with (fromIntegral i :: CUInt) foreign import ccall safe "mysql.h mysql_options" mysql_options_ :: Ptr MYSQL -> CInt -> Ptr a -> IO CInt foreign import ccall unsafe "mysql_signals.h _hs_mysql_real_connect" mysql_real_connect :: Ptr MYSQL -- ^ Context (from 'mysql_init'). -> CString -- ^ Host name. -> CString -- ^ User name. -> CString -- ^ Password. -> CString -- ^ Database. -> CInt -- ^ Port. -> CString -- ^ Unix socket. -> CULong -- ^ Flags. -> IO (Ptr MYSQL) foreign import ccall safe mysql_ssl_set :: Ptr MYSQL -> CString -- ^ Key. -> CString -- ^ Cert. -> CString -- ^ CA. -> CString -- ^ CA path. -> CString -- ^ Ciphers. -> IO MyBool foreign import ccall unsafe "mysql_signals.h _hs_mysql_close" mysql_close :: Ptr MYSQL -> IO () foreign import ccall unsafe "mysql_signals.h _hs_mysql_ping" mysql_ping :: Ptr MYSQL -> IO CInt foreign import ccall safe mysql_thread_id :: Ptr MYSQL -> IO CULong foreign import ccall unsafe "mysql_signals.h _hs_mysql_autocommit" mysql_autocommit :: Ptr MYSQL -> MyBool -> IO MyBool foreign import ccall unsafe "mysql_signals.h _hs_mysql_change_user" mysql_change_user :: Ptr MYSQL -> CString -- ^ user -> CString -- ^ password -> CString -- ^ database -> IO MyBool foreign import ccall unsafe "mysql_signals.h _hs_mysql_select_db" mysql_select_db :: Ptr MYSQL -> CString -> IO CInt foreign import ccall safe mysql_get_server_info :: Ptr MYSQL -> IO CString foreign import ccall safe mysql_get_host_info :: Ptr MYSQL -> IO CString foreign import ccall safe mysql_get_proto_info :: Ptr MYSQL -> IO CUInt foreign import ccall safe mysql_character_set_name :: Ptr MYSQL -> IO CString foreign import ccall safe mysql_set_character_set :: Ptr MYSQL -> CString -> IO CInt foreign import ccall safe mysql_get_ssl_cipher :: Ptr MYSQL -> IO CString foreign import ccall unsafe "mysql_signals.h _hs_mysql_stat" mysql_stat :: Ptr MYSQL -> IO CString foreign import ccall unsafe "mysql_signals.h _hs_mysql_real_query" mysql_real_query :: Ptr MYSQL -> CString -> CULong -> IO CInt foreign import ccall safe mysql_insert_id :: Ptr MYSQL -> IO CULLong foreign import ccall safe mysql_field_count :: Ptr MYSQL -> IO CUInt foreign import ccall safe mysql_affected_rows :: Ptr MYSQL -> IO CULLong foreign import ccall unsafe "mysql_signals.h _hs_mysql_store_result" mysql_store_result :: Ptr MYSQL -> IO (Ptr MYSQL_RES) foreign import ccall unsafe "mysql_signals.h _hs_mysql_use_result" mysql_use_result :: Ptr MYSQL -> IO (Ptr MYSQL_RES) foreign import ccall unsafe "mysql_signals.h _hs_mysql_free_result" mysql_free_result :: Ptr MYSQL_RES -> IO () foreign import ccall safe "mysql.h mysql_free_result" mysql_free_result_nonblock :: Ptr MYSQL_RES -> IO () foreign import ccall safe mysql_fetch_fields :: Ptr MYSQL_RES -> IO (Ptr Field) foreign import ccall safe "mysql.h mysql_fetch_fields" mysql_fetch_fields_nonblock :: Ptr MYSQL_RES -> IO (Ptr Field) foreign import ccall safe mysql_data_seek :: Ptr MYSQL_RES -> CULLong -> IO () foreign import ccall safe mysql_row_seek :: Ptr MYSQL_RES -> MYSQL_ROW_OFFSET -> IO MYSQL_ROW_OFFSET foreign import ccall safe mysql_row_tell :: Ptr MYSQL_RES -> IO MYSQL_ROW_OFFSET foreign import ccall unsafe "mysql_signals.h _hs_mysql_next_result" mysql_next_result :: Ptr MYSQL -> IO CInt foreign import ccall unsafe "mysql_signals.h _hs_mysql_commit" mysql_commit :: Ptr MYSQL -> IO MyBool foreign import ccall unsafe "mysql_signals.h _hs_mysql_rollback" mysql_rollback :: Ptr MYSQL -> IO MyBool foreign import ccall unsafe "mysql_signals.h _hs_mysql_fetch_row" mysql_fetch_row :: Ptr MYSQL_RES -> IO MYSQL_ROW foreign import ccall safe "mysql.h mysql_fetch_row" mysql_fetch_row_nonblock :: Ptr MYSQL_RES -> IO MYSQL_ROW foreign import ccall safe mysql_fetch_lengths :: Ptr MYSQL_RES -> IO (Ptr CULong) foreign import ccall safe "mysql.h mysql_fetch_lengths" mysql_fetch_lengths_nonblock :: Ptr MYSQL_RES -> IO (Ptr CULong) foreign import ccall safe mysql_real_escape_string :: Ptr MYSQL -> CString -> CString -> CULong -> IO CULong foreign import ccall safe mysql_get_client_info :: CString foreign import ccall safe mysql_get_client_version :: CULong foreign import ccall safe mysql_errno :: Ptr MYSQL -> IO CInt foreign import ccall safe mysql_error :: Ptr MYSQL -> IO CString
lhuang7/mysql
dist/dist-sandbox-bd9d9ce/build/Database/MySQL/Base/C.hs
bsd-3-clause
9,473
123
10
2,177
1,848
1,012
836
204
23
module Data.Graph.Inductive.Query.Monad (mapFst, mapSnd, (><), orP, GT(..), apply, apply', applyWith, applyWith', runGT, condMGT', recMGT', condMGT, recMGT, getNode, getContext, getNodes', getNodes, sucGT, sucM, graphRec, graphRec', graphUFold, graphNodesM0, graphNodesM, graphNodes, graphFilterM, graphFilter, dfsGT, dfsM, dfsM', dffM, graphDff, graphDff') where { import Data.Tree; import Data.Graph.Inductive.Graph; import Data.Graph.Inductive.Monad; mapFst :: (a -> b) -> (a, c) -> (b, c); mapFst f (x, y) = (f x, y); mapSnd :: (a -> b) -> (c, a) -> (c, b); mapSnd f (x, y) = (x, f y); infixr 8 ><; (><) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d); (f >< g) (x, y) = (f x, g y); orP :: (a -> Bool) -> (b -> Bool) -> (a, b) -> Bool; orP p q (x, y) = p x || q y; data GT m g a = MGT (m g -> m (a, g)); apply :: GT m g a -> m g -> m (a, g); apply (MGT f) mg = f mg; apply' :: (Monad m) => GT m g a -> g -> m (a, g); apply' gt = apply gt . return; applyWith :: (Monad m) => (a -> b) -> GT m g a -> m g -> m (b, g); applyWith h (MGT f) gm = do { (x, g) <- f gm; return (h x, g)}; applyWith' :: (Monad m) => (a -> b) -> GT m g a -> g -> m (b, g); applyWith' h gt = applyWith h gt . return; runGT :: (Monad m) => GT m g a -> m g -> m a; runGT gt mg = do { (x, _) <- apply gt mg; return x}; instance (Monad m) => Monad (GT m g) where { return x = MGT (\ mg -> do { g <- mg; return (x, g)}); f >>= h = MGT (\ mg -> do { (x, g) <- apply f mg; apply' (h x) g})}; condMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> GT m s a -> GT m s a; condMGT' p f g = MGT (\ mg -> do { h <- mg; if p h then apply f mg else apply g mg}); recMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b; recMGT' p mg f u = condMGT' p (return u) (do { x <- mg; y <- recMGT' p mg f u; return (f x y)}); condMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> GT m s a -> GT m s a; condMGT p f g = MGT (\ mg -> do { b <- p mg; if b then apply f mg else apply g mg}); recMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b; recMGT p mg f u = condMGT p (return u) (do { x <- mg; y <- recMGT p mg f u; return (f x y)}); getNode :: (GraphM m gr) => GT m (gr a b) Node; getNode = MGT (\ mg -> do { ((_, v, _, _), g) <- matchAnyM mg; return (v, g)}); getContext :: (GraphM m gr) => GT m (gr a b) (Context a b); getContext = MGT matchAnyM; getNodes' :: (Graph gr, GraphM m gr) => GT m (gr a b) [Node]; getNodes' = condMGT' isEmpty (return []) (do { v <- getNode; vs <- getNodes; return (v : vs)}); getNodes :: (GraphM m gr) => GT m (gr a b) [Node]; getNodes = condMGT isEmptyM (return []) (do { v <- getNode; vs <- getNodes; return (v : vs)}); sucGT :: (GraphM m gr) => Node -> GT m (gr a b) (Maybe [Node]); sucGT v = MGT (\ mg -> do { (c, g) <- matchM v mg; case c of { Just (_, _, _, s) -> return (Just (map snd s), g); Nothing -> return (Nothing, g)}}); sucM :: (GraphM m gr) => Node -> m (gr a b) -> m (Maybe [Node]); sucM v = runGT (sucGT v); graphRec :: (GraphM m gr) => GT m (gr a b) c -> (c -> d -> d) -> d -> GT m (gr a b) d; graphRec = recMGT isEmptyM; graphRec' :: (Graph gr, GraphM m gr) => GT m (gr a b) c -> (c -> d -> d) -> d -> GT m (gr a b) d; graphRec' = recMGT' isEmpty; graphUFold :: (GraphM m gr) => (Context a b -> c -> c) -> c -> GT m (gr a b) c; graphUFold = graphRec getContext; graphNodesM0 :: (GraphM m gr) => GT m (gr a b) [Node]; graphNodesM0 = graphRec getNode (:) []; graphNodesM :: (GraphM m gr) => GT m (gr a b) [Node]; graphNodesM = graphUFold (\ (_, v, _, _) -> (v :)) []; graphNodes :: (GraphM m gr) => m (gr a b) -> m [Node]; graphNodes = runGT graphNodesM; graphFilterM :: (GraphM m gr) => (Context a b -> Bool) -> GT m (gr a b) [Context a b]; graphFilterM p = graphUFold (\ c cs -> if p c then c : cs else cs) []; graphFilter :: (GraphM m gr) => (Context a b -> Bool) -> m (gr a b) -> m [Context a b]; graphFilter p = runGT (graphFilterM p); dfsGT :: (GraphM m gr) => [Node] -> GT m (gr a b) [Node]; dfsGT [] = return []; dfsGT (v : vs) = MGT (\ mg -> do { (mc, g') <- matchM v mg; case mc of { Just (_, _, _, s) -> applyWith' (v :) (dfsGT (map snd s ++ vs)) g'; Nothing -> apply' (dfsGT vs) g'}}); dfsM :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Node]; dfsM vs = runGT (dfsGT vs); dfsM' :: (GraphM m gr) => m (gr a b) -> m [Node]; dfsM' mg = do { vs <- nodesM mg; runGT (dfsGT vs) mg}; dffM :: (GraphM m gr) => [Node] -> GT m (gr a b) [Tree Node]; dffM vs = MGT (\ mg -> do { g <- mg; b <- isEmptyM mg; if b || null vs then return ([], g) else let { (v : vs') = vs} in do { (mc, g1) <- matchM v mg; case mc of { Nothing -> apply (dffM vs') (return g1); Just c -> do { (ts, g2) <- apply (dffM (suc' c)) (return g1); (ts', g3) <- apply (dffM vs') (return g2); return (Node (node' c) ts : ts', g3)}}}}); graphDff :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Tree Node]; graphDff vs = runGT (dffM vs); graphDff' :: (GraphM m gr) => m (gr a b) -> m [Tree Node]; graphDff' mg = do { vs <- nodesM mg; runGT (dffM vs) mg}}
ckaestne/CIDE
other/CaseStudies/fgl/CIDEfgl/Data/Graph/Inductive/Query/Monad.hs
gpl-3.0
6,497
1
25
2,709
3,318
1,785
1,533
167
3
module FBHasTooMany2 where f :: Int f x y = x + y
roberth/uu-helium
test/typeerrors/Heuristics/FBHasTooMany2.hs
gpl-3.0
52
0
5
15
23
13
10
3
1
module Import00003 where #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 708 import Data.Typeable (Typeable) #else import Data.Typeable (Typeable,Typeable1,mkTyCon3,mkTyConApp,typeOf) #endif
charleso/intellij-haskforce
tests/gold/parser/Import00003.hs
apache-2.0
203
0
5
18
17
12
5
2
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>Core Language Files | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/coreLang/src/main/javahelp/org/zaproxy/zap/extension/coreLang/resources/help_si_LK/helpset_si_LK.hs
apache-2.0
980
83
52
160
398
210
188
-1
-1
module TupleIn1 where f :: (a, ([Int], c)) -> ([Int], c) f (x, y@([], m)) = case y of y@(b_1, b_2) -> y f (x, y@([], m)) = y
kmate/HaRe
old/testing/introCase/TupleIn1AST.hs
bsd-3-clause
146
0
9
50
106
65
41
6
1
{-# LANGUAGE CPP #-} #ifndef NO_NEWTYPE_DERIVING {-# LANGUAGE GeneralizedNewtypeDeriving #-} #endif -- | Types to help with testing polymorphic properties. -- -- Types 'A', 'B' and 'C' are @newtype@ wrappers around 'Integer' that -- implement 'Eq', 'Show', 'Arbitrary' and 'CoArbitrary'. Types -- 'OrdA', 'OrdB' and 'OrdC' also implement 'Ord' and 'Num'. -- -- See also "Test.QuickCheck.All" for an automatic way of testing -- polymorphic properties. module Test.QuickCheck.Poly ( A(..), B(..), C(..) , OrdA(..), OrdB(..), OrdC(..) ) where -------------------------------------------------------------------------- -- imports import Test.QuickCheck.Arbitrary -------------------------------------------------------------------------- -- polymorphic A, B, C (in Eq) -- A newtype A = A{ unA :: Integer } deriving ( Eq ) instance Show A where showsPrec n (A x) = showsPrec n x instance Arbitrary A where arbitrary = (A . (+1) . abs) `fmap` arbitrary shrink (A x) = [ A x' | x' <- shrink x, x' > 0 ] instance CoArbitrary A where coarbitrary = coarbitrary . unA -- B newtype B = B{ unB :: Integer } deriving ( Eq ) instance Show B where showsPrec n (B x) = showsPrec n x instance Arbitrary B where arbitrary = (B . (+1) . abs) `fmap` arbitrary shrink (B x) = [ B x' | x' <- shrink x, x' > 0 ] instance CoArbitrary B where coarbitrary = coarbitrary . unB -- C newtype C = C{ unC :: Integer } deriving ( Eq ) instance Show C where showsPrec n (C x) = showsPrec n x instance Arbitrary C where arbitrary = (C . (+1) . abs) `fmap` arbitrary shrink (C x) = [ C x' | x' <- shrink x, x' > 0 ] instance CoArbitrary C where coarbitrary = coarbitrary . unC -------------------------------------------------------------------------- -- polymorphic OrdA, OrdB, OrdC (in Eq, Ord) -- OrdA newtype OrdA = OrdA{ unOrdA :: Integer } deriving ( Eq, Ord #ifndef NO_NEWTYPE_DERIVING , Num #endif ) instance Show OrdA where showsPrec n (OrdA x) = showsPrec n x instance Arbitrary OrdA where arbitrary = (OrdA . (+1) . abs) `fmap` arbitrary shrink (OrdA x) = [ OrdA x' | x' <- shrink x, x' > 0 ] instance CoArbitrary OrdA where coarbitrary = coarbitrary . unOrdA -- OrdB newtype OrdB = OrdB{ unOrdB :: Integer } deriving ( Eq, Ord #ifndef NO_NEWTYPE_DERIVING , Num #endif ) instance Show OrdB where showsPrec n (OrdB x) = showsPrec n x instance Arbitrary OrdB where arbitrary = (OrdB . (+1) . abs) `fmap` arbitrary shrink (OrdB x) = [ OrdB x' | x' <- shrink x, x' > 0 ] instance CoArbitrary OrdB where coarbitrary = coarbitrary . unOrdB -- OrdC newtype OrdC = OrdC{ unOrdC :: Integer } deriving ( Eq, Ord #ifndef NO_NEWTYPE_DERIVING , Num #endif ) instance Show OrdC where showsPrec n (OrdC x) = showsPrec n x instance Arbitrary OrdC where arbitrary = (OrdC . (+1) . abs) `fmap` arbitrary shrink (OrdC x) = [ OrdC x' | x' <- shrink x, x' > 0 ] instance CoArbitrary OrdC where coarbitrary = coarbitrary . unOrdC -------------------------------------------------------------------------- -- the end.
beni55/quickcheck
Test/QuickCheck/Poly.hs
bsd-3-clause
3,165
0
10
700
947
534
413
63
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} module T11732a where import GHC.Generics data Proxy k (a :: k) deriving Generic1 data family ProxyFam (a :: y) (b :: z) data instance ProxyFam k (a :: k) deriving Generic1
ezyang/ghc
testsuite/tests/deriving/should_compile/T11732a.hs
bsd-3-clause
264
1
5
46
62
43
19
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module T5371 where import Language.Haskell.TH f :: a -> Name f (x :: a) = ''a
urbanslug/ghc
testsuite/tests/quotes/T5721.hs
bsd-3-clause
117
0
7
22
37
22
15
-1
-1
----------------------------------------------------------------------------- -- -- Module : PhysicalQuantities.Definitions -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- {-# LANGUAGE MultiParamTypeClasses , FlexibleContexts , ConstraintKinds , UndecidableInstances , FlexibleInstances #-} module PhysicalQuantities.Definitions ( Dimensions (Scalar, Vector, Dimensionless) , PhysicalQuantity(..), Abs(..) , QuantityDecomposition, BaseQuantity, DerivedQuantity , CmpQ, EqQ , Unit(..), Vec(..) , UnitDecomposition, BaseUnit, DerivedUnit , CmpU, EqU , UnitSystem(..), UnitPrefix(..) , (:*)(..), (:/)(..), (:^)(..) ) where import PhysicalQuantities.Combinations import PhysicalQuantities.Decomposition ( TBase(..), TDerived(..) , Decomposition(..), DecompositionType , CmpD ) import TypeNum.Rational hiding (Abs) import GHC.TypeLits (symbolVal) import Data.Maybe (fromMaybe) import Data.Type.Bool (If) import Data.Type.Equality ----------------------------------------------------------------------------- data Dimensions = Dimensionless | Scalar | Vector deriving (Show, Eq, Ord) instance TypesEq (a :: Dimensions) (b :: Dimensions) where type a ~=~ b = CompareDimensions a b == EQ instance TypesOrd (a :: Dimensions) (b :: Dimensions) where type Cmp a b = CompareDimensions a b type instance (a :: Dimensions) == (b :: Dimensions) = a ~=~ b type family CompareDimensions (a :: Dimensions) (b :: Dimensions) :: Ordering where CompareDimensions Dimensionless Dimensionless = EQ CompareDimensions Dimensionless Scalar = LT CompareDimensions Dimensionless Vector = LT CompareDimensions Scalar Dimensionless = GT CompareDimensions Vector Dimensionless = GT CompareDimensions Scalar Scalar = EQ CompareDimensions Scalar Vector = LT CompareDimensions Vector Scalar = GT CompareDimensions Vector Vector = EQ ----------------------------------------------------------------------------- class PhysicalQuantity q where type QuantityDimensions q :: Dimensions quantityDimensions :: q -> Dimensions quantityName :: q -> String quantityInstance :: q type BaseQuantity q = (PhysicalQuantity q, TBase q) type DerivedQuantity q = (PhysicalQuantity q, TDerived q) type QuantityDecomposition q = (PhysicalQuantity q, Decomposition q) ----------------------------------------------------------------------------- parenth s = "(" ++ s ++ ")" instance ( PhysicalQuantity a, PhysicalQuantity b ) => PhysicalQuantity (a :* b) where type QuantityDimensions (a :* b) = ResultingDimensions' a b quantityDimensions (a :* b) = resultingDimensions' a b quantityName (a :* b) = parenth $ quantityName' " * " a b quantityInstance = quantityInstance :* quantityInstance instance ( PhysicalQuantity a, PhysicalQuantity b ) => PhysicalQuantity (a :/ b) where type QuantityDimensions (a :/ b) = ResultingDimensions' a b quantityDimensions (a :/ b) = resultingDimensions' a b quantityName (a :/ b) = parenth $ quantityName' " / " a b quantityInstance = quantityInstance :/ quantityInstance instance ( PhysicalQuantity a, MaybeRational p, KnownRatio (AsRational p) ) => PhysicalQuantity (a :^ (p :: k)) where type QuantityDimensions (a :^ p) = QuantityDimensions a quantityDimensions (a :^ p) = quantityDimensions a quantityName (a :^ p) = quantityName a ++ "^" ++ show p quantityInstance = quantityInstance :^ Ratio' type family ResultingDimensions (a :: Dimensions) (b ::Dimensions) :: Dimensions where ResultingDimensions a Dimensionless = a ResultingDimensions Dimensionless b = b ResultingDimensions Scalar Scalar = Scalar ResultingDimensions a b = Vector type ResultingDimensions' a b = ResultingDimensions (QuantityDimensions a) (QuantityDimensions b) quantityName' op a b = quantityName a ++ op ++ quantityName b resultingDimensions a Dimensionless = a resultingDimensions Dimensionless b = b resultingDimensions Scalar Scalar = Scalar resultingDimensions _ _ = Vector resultingDimensions' a b = resultingDimensions (quantityDimensions a) (quantityDimensions b) ----------------------------------------------------------------------------- -- | Scalar container for vector quantities. newtype Abs q = Abs q instance (PhysicalQuantity a, QuantityDimensions a ~ Vector) => PhysicalQuantity (Abs a) where type QuantityDimensions (Abs a) = Scalar quantityDimensions _ = Scalar quantityName (Abs a) = "|" ++ quantityName a ++ "|" quantityInstance = Abs quantityInstance type instance DecompositionType (Abs a) = DecompositionType a instance (BaseQuantity a) => TBase (Abs a) where type TSymbol (Abs a) = TSymbol a tFromSymbol = Abs . tFromSymbol instance (DerivedQuantity a) => TDerived (Abs a) where type TStructure (Abs a) = TStructure a ----------------------------------------------------------------------------- -- | Represents a unit as a symbol (combination of symbols); measures no -- specific 'PhysicalQuantity' outside of a 'UnitSystem'. class Unit u where type UnitDimensions u :: Dimensions unitDimensions :: u -> Dimensions unitName :: u -> String unitInstance :: u type BaseUnit u = (Unit u, TBase u) type DerivedUnit u = (Unit u, TDerived u) type UnitDecomposition u = (Unit u, Decomposition u) -- | Vector container for scalar units. newtype Vec u = Vec u -- | Vector container wraps any scalar unit and turns it into vector. instance (Unit u, UnitDimensions u ~ Scalar) => Unit (Vec u) where type UnitDimensions (Vec u) = Vector unitDimensions _ = Vector unitName u = "Vec[" ++ unitName u ++ "]" unitInstance = Vec unitInstance ----------------------------------------------------------------------------- instance ( Unit a, Unit b ) => Unit (a :* b) where type UnitDimensions (a :* b) = ResultingDimensions (UnitDimensions a) (UnitDimensions b) unitDimensions (a :* b) = resultingDimensions (unitDimensions a) (unitDimensions b) unitName (a :* b) = parenth $ unitName' " * " a b unitInstance = unitInstance :* unitInstance instance ( Unit a, Unit b ) => Unit (a :/ b) where type UnitDimensions (a :/ b) = ResultingDimensions (UnitDimensions a) (UnitDimensions b) unitDimensions (a :/ b) = resultingDimensions (unitDimensions a) (unitDimensions b) unitName (a :/ b) = parenth $ unitName' " / " a b unitInstance = unitInstance :/ unitInstance instance ( Unit a, MaybeRational p, KnownRatio (AsRational p) ) => Unit (a :^ (p :: k)) where type UnitDimensions (a :^ p) = UnitDimensions a unitDimensions (a :^ _) = unitDimensions a unitName (a :^ p) = unitName a ++ "^" ++ show p unitInstance = unitInstance :^ Ratio' unitName' op a b = unitName a ++ op ++ unitName b ----------------------------------------------------------------------------- -- | Establishes units for the physical quantities within the system. class (UnitPrefix (Prefix sys)) => UnitSystem sys where unitSystemName :: sys -> String type Prefix sys :: * -> * type UnitFor sys phq :: * unitFor :: (Unit (UnitFor sys phq)) => sys -> phq -> UnitFor sys phq unitFor _ _ = unitInstance class UnitPrefix p where prefixGroup :: p v -> String prefixName :: p v -> String prefixValue :: (Num v, Eq v) => p v -> v prefixFromValue :: (Num v, Eq v) => v -> Maybe (p v) convertPrefix :: p v -> p w ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- eq and compare for quantities and units, using decompositions. class ( QuantityDecomposition q1, QuantityDecomposition q2 ) => CompareQuantities q1 q2 where type CmpQ q1 q2 :: Ordering type EqQ q1 q2 :: Bool type EqQ q1 q2 = CmpQ q1 q2 == EQ -- | Compare physical quantities by dimensions and decomposition. instance ( QuantityDecomposition q1, QuantityDecomposition q2 ) => CompareQuantities q1 q2 where type CmpQ q1 q2 = If (QuantityDimensions q1 == QuantityDimensions q2) (CmpD (TDecomposition q1) (TDecomposition q2)) (Cmp (QuantityDimensions q1) (QuantityDimensions q2)) ----------------------------------------------------------------------------- class ( UnitDecomposition u1, UnitDecomposition u2 ) => CompareUnits u1 u2 where type CmpU u1 u2 :: Ordering type EqU u1 u2 :: Bool type EqU u1 u2 = CmpU u1 u2 == EQ instance ( UnitDecomposition u1, UnitDecomposition u2 ) => CompareUnits u1 u2 where type CmpU u1 u2 = If (UnitDimensions u1 == UnitDimensions u2) (CmpD (TDecomposition u1) (TDecomposition u2)) (Cmp (UnitDimensions u1) (UnitDimensions u2)) -----------------------------------------------------------------------------
fehu/PhysicalQuantities
src/PhysicalQuantities/Definitions.hs
mit
9,889
2
11
2,666
2,447
1,338
1,109
-1
-1
module GHCJS.DOM.RequestAnimationFrameCallback ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/RequestAnimationFrameCallback.hs
mit
59
0
3
7
10
7
3
1
0
{-# LANGUAGE TypeFamilies #-} module Agent.PingPong.Role.SendResult where import AgentSystem.Generic import Agent.PingPong import qualified Agent.PingPong.Simple.SendResult as SendRes import Data.IORef -------------------------------------------------------------------------------- data PingRole = PingRole data PongRole = PongRole -------------------------------------------------------------------------------- instance RoleName PingRole where roleName _ = "Ping" instance AgentRole PingRole where type RoleState PingRole = (IORef Integer, IORef SomeAgentRef, IORef Bool) type RoleResult PingRole = () type RoleSysArgs PingRole = () type RoleArgs PingRole = (Integer, IORef SomeAgentRef) instance RoleName PongRole where roleName _ = "Pong" instance AgentRole PongRole where type RoleState PongRole = (IORef Integer, IORef SomeAgentRef) type RoleResult PongRole = Integer type RoleSysArgs PongRole = () type RoleArgs PongRole = IORef SomeAgentRef -------------------------------------------------------------------------------- pingRoleDescriptor = genericRoleDescriptor PingRole (const $ return . uncurry SendRes.pingDescriptor) pongRoleDescriptor = genericRoleDescriptor PongRole (const $ return . SendRes.pongDescriptor) -------------------------------------------------------------------------------- runPingPong nPings = do pingRef <- newIORef undefined pongRef <- newIORef undefined putStrLn "<< CreateAgentOfRole >> " let pingC = CreateAgentOfRole pingRoleDescriptor (return ()) $ return (nPings, pongRef) pongC = CreateAgentOfRole pongRoleDescriptor (return ()) $ return pingRef ping <- createAgentRef pingC pong <- createAgentRef pongC pingRef `writeIORef` someAgentRef ping pongRef `writeIORef` someAgentRef pong putStrLn "Starting PING" agentStart ping putStrLn "Starting PONG" agentStart pong putStrLn "Waiting PING termination" agentWaitTermination ping putStrLn "Waiting PONG result" res <- agentWaitResult pong putStrLn $ "PONG result: " ++ show res putStrLn "Waiting PONG termination" agentWaitTermination pong putStrLn "Finished"
fehu/h-agents
test/Agent/PingPong/Role/SendResult.hs
mit
2,684
0
14
851
491
242
249
47
1
module Language.MSH.MethodTable where import qualified Data.Map as M import Language.Haskell.TH import Language.Haskell.TH.Syntax {- Methods -} data MethodTable = MkMethodTable { methodSigs :: M.Map String Dec, methodDefs :: M.Map String Dec } deriving Show emptyMethodTable :: MethodTable emptyMethodTable = MkMethodTable M.empty M.empty addMethodSig :: Name -> Dec -> MethodTable -> MethodTable addMethodSig name dec tbl = tbl { methodSigs = M.insert (nameBase name) dec (methodSigs tbl) } addMethodDef :: Name -> Dec -> MethodTable -> MethodTable addMethodDef name dec tbl = tbl { methodDefs = M.insert (nameBase name) dec (methodDefs tbl) } isImplemented :: Name -> MethodTable -> Bool isImplemented n tbl = M.member (nameBase n) (methodDefs tbl) -- | `preProcessMethods ds' builds a value of type `MethodTable' from a list -- of top-level declarations. preProcessMethods :: [Dec] -> MethodTable preProcessMethods ds = go emptyMethodTable ds where go tbl [] = tbl go tbl (d@(SigD name ty) : ds) = go (addMethodSig name d tbl) ds go tbl (d@(FunD name cs) : ds) = go (addMethodDef name d tbl) ds go tbl (d@(ValD (VarP name) body wh) : ds) = go (addMethodDef name d tbl) ds go tbl (d : ds) = go tbl ds
mbg/monadic-state-hierarchies
Language/MSH/MethodTable.hs
mit
1,371
0
14
362
444
236
208
25
5
-- From http://decipheringmusictheory.com/?page_id=46 module Other.Harmonisation where import Mezzo v1 = start $ melody :| d :| g :| fs :< g :| a :^ bf :| a :| a :| a :| d' :| c' :| bf :| a :>> g v2 = start $ melody :| d :| ef :| d :| d :| d :| d :| cs :| d :| d :| ef :| d :| d :>> bf_ v3 = start $ melody :| bf_ :| g_ :| a_ :< g_ :| fs_ :^ g_ :| a_ :| a_ :| fs_ :| g_ :| g_ :| g_ :| fs_ :>> g_ v4 = start $ melody :| g__ :| c_ :| c_ :< bf__ :| a__ :^ g__ :| f__ :| a__ :| d__ :| bf__ :| c_ :| d_ :| d_ :>> g__ -- ^ The above tutorial used 'd_' which gave a concealed octave sco = score setKeySig g_min setRuleSet strict withMusic (v1 :-: v2 :-: v3 :-: v4) main = renderScore "rendered/Harmonisation.mid" "4-voice chorale" sco
DimaSamoz/mezzo
examples/src/Other/Harmonisation.hs
mit
922
0
19
365
312
161
151
12
1
module MedicineSpec (main, spec) where import Test.Hspec import Medicine import Medicine.ParserSpec (parsedMedicine) import Text.ParserCombinators.Parsec (parse) sampleBuild = unlines [ "e => H" , "e => O" , "H => HO" , "H => OH" , "O => HH" , "" , "HOH" ] parsedBuild = case parse pMedicine "" sampleBuild of Left err -> error (show err) Right p -> p main :: IO () main = hspec spec spec :: Spec spec = do describe "getDistinctMolecules" $ do it "should return 4 for HOH" $ getDistinctMolecules parsedMedicine `shouldBe` 4 it "should return 7 for HOHOHO" $ do let med = parsedMedicine { molecule = ["H", "O", "H", "O", "H", "O"]} getDistinctMolecules med `shouldBe` 7 describe "search" $ do it "should take 3 steps to make HOH" $ search parsedBuild `shouldBe` Just 3 it "should take 6 steps to make HOHOHO" $ do let build = parsedBuild { molecule = ["H", "O", "H", "O", "H", "O"] } search build `shouldBe` Just 6
corajr/adventofcode2015
19/test/MedicineSpec.hs
mit
1,051
0
18
299
319
169
150
32
2
module YourProject where my_func = "This is my package!"
Azabuhs/YourProject
src/YourProject.hs
mit
57
0
4
9
9
6
3
2
1
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.EdgeFlag -- Copyright : (c) Sven Panne 2002-2009 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- This is a purely internal module for (un-)marshaling EdgeFlag. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.EdgeFlag ( EdgeFlag(..), marshalEdgeFlag, unmarshalEdgeFlag ) where import Graphics.Rendering.OpenGL.Raw.Core31 import Graphics.Rendering.OpenGL.GL.GLboolean -------------------------------------------------------------------------------- -- | A vertex can begin an edge which lies in the interior of its polygon or on -- the polygon\'s boundary. data EdgeFlag = BeginsInteriorEdge | BeginsBoundaryEdge deriving ( Eq, Ord, Show ) marshalEdgeFlag :: EdgeFlag -> GLboolean marshalEdgeFlag = marshalGLboolean . (BeginsBoundaryEdge ==) unmarshalEdgeFlag :: GLboolean -> EdgeFlag unmarshalEdgeFlag f = if unmarshalGLboolean f then BeginsBoundaryEdge else BeginsBoundaryEdge
ducis/haAni
hs/common/Graphics/Rendering/OpenGL/GL/EdgeFlag.hs
gpl-2.0
1,231
0
6
160
132
88
44
11
2
module Insult where {- Inspired by http://lost-in-space.soup.io/post/356758305/Butterface-crotch-waffle -} import Control.Concurrent (threadDelay) import Control.Monad import System.Random as Random w1,w2,w3 :: [String] w1 = ["Lazy","Stupid","Insecure","Idiotic","Slimy","Slutty","Smelly","Pompous","Communist","Dicknose","Pie-eating","Racist","Elitist","White trash","Drug-loving","Butterface","Tone deaf","Ugly","Creepy"] w2 = ["douche","ass","turd","rectum","butt","cock","shit","crotch","bitch","turd","prick","slut","taint","fuck","dick","boner","shart","nut","sphincter"] w3 = ["pilot","canoe","captain","pirate","hammer","knob","box","jockey","nazi","waffle","goblin","blossom","biscuit","clown","socket","monster","hound","dragon","balloon"] ws = [w1,w2,w3] lengths :: [Int] lengths = cycle $ map length ws walk :: [String] -> [String] walk xs = let y = unwords $ take 3 xs ys = walk $ drop 3 xs in y:ys main :: IO () main = do rs <- liftM randoms newStdGen let ixs = zipWith mod rs lengths ws' = zipWith (!!) (cycle ws) ixs slp = const $ threadDelay 1000000 mapM_ (slp <=< putStrLn) $ walk ws'
runjak/snippets
playground/Insult.hs
gpl-2.0
1,157
0
12
162
417
248
169
22
1
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback is free software: you can redistribute it and/or modify it under | | the terms of the GNU General Public License as published by the Free | | Software Foundation, either version 3 of the License, or (at your option) | | any later version. | | | | Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} module Fallback.Scenario.Triggers.PerilousRoad (compilePerilousRoad) where import Control.Applicative ((<$>)) import Control.Monad (forM, when) import Data.Maybe (isNothing) import Fallback.Constants (framesPerRound) import Fallback.Data.Color (Tint(Tint)) import qualified Fallback.Data.Grid as Grid import Fallback.Data.Point import Fallback.Scenario.Compile import Fallback.Scenario.Script import Fallback.Scenario.Triggers.Globals import Fallback.Scenario.Triggers.Script import Fallback.State.Area import Fallback.State.Creature import Fallback.State.Resources (SoundTag(..), StripTag(IceBoom)) import Fallback.State.Simple import Fallback.State.Status import Fallback.State.Tags (AreaTag(..), MonsterTag(..)) import Fallback.State.Terrain (positionCenter) import Fallback.State.Tileset (TileTag(..)) ------------------------------------------------------------------------------- compilePerilousRoad :: Globals -> CompileScenario () compilePerilousRoad globals = compileArea PerilousRoad Nothing $ do makeExit Holmgare ["ToHolmgare1", "ToHolmgare2"] "FromHolmgare" makeExit StoneBridge ["ToStoneBridge"] "FromStoneBridge" makeExit IcyConfluence ["ToIcyConfluence"] "FromIcyConfluence" onStartDaily 184809 $ do addUnlockedDoors globals mapM_ (addRemains Bones) =<< lookupTerrainMark "Bones" once 480298 (walkIn "JustInside1" `orP` walkIn "JustInside2") $ do narrate "FIXME" simpleEnemy_ 879920 "ZomA1" Zombie MindlessAI simpleEnemy_ 297279 "ZomA2" Zombie MindlessAI simpleEnemy_ 400982 "ZomA3" Zombie MindlessAI simpleEnemy_ 178721 "GhoulA" Ghoul MindlessAI simpleEnemy_ 338940 "WraithA1" Wraith MindlessAI simpleEnemy_ 612041 "WraithA2" Wraith MindlessAI simpleEnemy_ 740821 "ZomB1" Zombie MindlessAI simpleEnemy_ 300100 "ZomB2" Zombie MindlessAI simpleEnemy_ 428302 "ZomB3" Zombie MindlessAI simpleEnemy_ 485082 "GhoulB1" Ghoul MindlessAI simpleEnemy_ 585092 "GhoulB2" Ghoul MindlessAI simpleEnemy_ 500192 "WraithB" Wraith MindlessAI simpleEnemy_ 984113 "ZomC1" Zombie MindlessAI simpleEnemy_ 448020 "ZomC2" Zombie MindlessAI simpleEnemy_ 397299 "SkelC1" Skeleton MindlessAI simpleEnemy_ 321353 "SkelC2" Skeleton MindlessAI simpleEnemy_ 575792 "WraithC" Wraith MindlessAI simpleEnemy_ 477201 "GhastD1" Ghast MindlessAI simpleEnemy_ 313516 "GhastD2" Ghast MindlessAI simpleEnemy_ 297987 "WraithD" Wraith MindlessAI uniqueDevice 572098 "RoadSign" signRadius $ \_ _ -> do narrate "There's a weather-beaten signpost along the road here. It\ \ says:\n\n\ \ {c}City of Tragorda: 8 mi. S{_}\n\ \ {c}Sabina Confluence: 4 mi. E{_}\n\ \ {c}Village of Holmgare: 4 mi. NW{_}" (bonemasterKey, bonemasterDead) <- scriptedMonster 841042 "Bonemaster" Bonemaster False ImmobileAI crystalCounter <- newPersistentVar 672092 (0 :: Int) bossBattle <- newScriptedBattle 568009 "BossRoom" $ do trigger 575022 periodicP $ do (crystalMark, blockMark, columnMark) <- do idx <- (`mod` 3) . (1 +) <$> readVar crystalCounter writeVar crystalCounter idx case idx of 0 -> return ("CrystalW", "BlockW", "ColumnW") 1 -> return ("CrystalNE", "BlockNE", "ColumnNE") 2 -> return ("CrystalSE", "BlockSE", "ColumnSE") _ -> fail "bad crystal counter" unlessP (walkOn blockMark) $ do crystalPos <- demandOneTerrainMark crystalMark columnPos <- demandOneTerrainMark columnMark addLightningDoodad (Tint 0 128 255 192) crystalPos columnPos runePos <- demandOneTerrainMark "Rune" mbOccupant <- areaGet (arsOccupant runePos) case mbOccupant of Nothing -> do key <- readVar bonemasterKey degradeMonstersSummonedBy (Right key) tag <- getRandomElem [Zombie, Skeleton, Ghoul, Wraith] let lifetime = framesPerRound * 16 playSound SndSummon mbEntry <- trySummonMonsterNear runePos (Right key) tag lifetime True when (isNothing mbEntry) $ fail "Couldn't place monster on rune" Just (Right entry) | not (monstIsAlly $ Grid.geValue entry) -> do let hitTarget = HitMonster (Grid.geKey entry) playSound SndHeal healDamage . (:[]) . (,) hitTarget =<< getRandomR 90 110 playSound SndBlessing playSound SndHaste alterStatus hitTarget $ (seApplyHaste $ Beneficial 12) . (seApplyBlessing $ Beneficial 15) . sePurgeAllBadEffects Just _ -> do playSound SndFreeze hits <- forM (prectPositions $ expandPosition runePos) $ \pos -> do damage <- getRandomR 50 70 return (HitPosition pos, ColdDamage, damage) forkScript $ doExplosionDoodad IceBoom (positionCenter runePos) wait 5 >> dealDamage hits wait 16 once 492011 (walkIn "BossRoom") $ do setTerrain BasaltGateClosedTile =<< lookupTerrainMark "BossGate" narrate "TODO Fight!" startScriptedBattle bossBattle trigger 490194 (varTrue bonemasterDead) $ do setAreaCleared PerilousRoad True setTerrain BasaltGateOpenTile =<< lookupTerrainMark "BossGate" setTerrain BasaltGateOpenTile =<< lookupTerrainMark "ExitGate" -------------------------------------------------------------------------------
mdsteele/fallback
src/Fallback/Scenario/Triggers/PerilousRoad.hs
gpl-3.0
6,754
0
30
1,728
1,364
658
706
-1
-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.ToolResults.Projects.Histories.Executions.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates an Execution. The returned Execution will have the id set. May -- return any of the following canonical error codes: - PERMISSION_DENIED - -- if the user is not authorized to write to project - INVALID_ARGUMENT - -- if the request is malformed - NOT_FOUND - if the containing History does -- not exist -- -- /See:/ <https://firebase.google.com/docs/test-lab/ Cloud Tool Results API Reference> for @toolresults.projects.histories.executions.create@. module Network.Google.Resource.ToolResults.Projects.Histories.Executions.Create ( -- * REST Resource ProjectsHistoriesExecutionsCreateResource -- * Creating a Request , projectsHistoriesExecutionsCreate , ProjectsHistoriesExecutionsCreate -- * Request Lenses , phecRequestId , phecPayload , phecHistoryId , phecProjectId ) where import Network.Google.Prelude import Network.Google.ToolResults.Types -- | A resource alias for @toolresults.projects.histories.executions.create@ method which the -- 'ProjectsHistoriesExecutionsCreate' request conforms to. type ProjectsHistoriesExecutionsCreateResource = "toolresults" :> "v1beta3" :> "projects" :> Capture "projectId" Text :> "histories" :> Capture "historyId" Text :> "executions" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Execution :> Post '[JSON] Execution -- | Creates an Execution. The returned Execution will have the id set. May -- return any of the following canonical error codes: - PERMISSION_DENIED - -- if the user is not authorized to write to project - INVALID_ARGUMENT - -- if the request is malformed - NOT_FOUND - if the containing History does -- not exist -- -- /See:/ 'projectsHistoriesExecutionsCreate' smart constructor. data ProjectsHistoriesExecutionsCreate = ProjectsHistoriesExecutionsCreate' { _phecRequestId :: !(Maybe Text) , _phecPayload :: !Execution , _phecHistoryId :: !Text , _phecProjectId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsHistoriesExecutionsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'phecRequestId' -- -- * 'phecPayload' -- -- * 'phecHistoryId' -- -- * 'phecProjectId' projectsHistoriesExecutionsCreate :: Execution -- ^ 'phecPayload' -> Text -- ^ 'phecHistoryId' -> Text -- ^ 'phecProjectId' -> ProjectsHistoriesExecutionsCreate projectsHistoriesExecutionsCreate pPhecPayload_ pPhecHistoryId_ pPhecProjectId_ = ProjectsHistoriesExecutionsCreate' { _phecRequestId = Nothing , _phecPayload = pPhecPayload_ , _phecHistoryId = pPhecHistoryId_ , _phecProjectId = pPhecProjectId_ } -- | A unique request ID for server to detect duplicated requests. For -- example, a UUID. Optional, but strongly recommended. phecRequestId :: Lens' ProjectsHistoriesExecutionsCreate (Maybe Text) phecRequestId = lens _phecRequestId (\ s a -> s{_phecRequestId = a}) -- | Multipart request metadata. phecPayload :: Lens' ProjectsHistoriesExecutionsCreate Execution phecPayload = lens _phecPayload (\ s a -> s{_phecPayload = a}) -- | A History id. Required. phecHistoryId :: Lens' ProjectsHistoriesExecutionsCreate Text phecHistoryId = lens _phecHistoryId (\ s a -> s{_phecHistoryId = a}) -- | A Project id. Required. phecProjectId :: Lens' ProjectsHistoriesExecutionsCreate Text phecProjectId = lens _phecProjectId (\ s a -> s{_phecProjectId = a}) instance GoogleRequest ProjectsHistoriesExecutionsCreate where type Rs ProjectsHistoriesExecutionsCreate = Execution type Scopes ProjectsHistoriesExecutionsCreate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsHistoriesExecutionsCreate'{..} = go _phecProjectId _phecHistoryId _phecRequestId (Just AltJSON) _phecPayload toolResultsService where go = buildClient (Proxy :: Proxy ProjectsHistoriesExecutionsCreateResource) mempty
brendanhay/gogol
gogol-toolresults/gen/Network/Google/Resource/ToolResults/Projects/Histories/Executions/Create.hs
mpl-2.0
5,128
0
17
1,128
556
333
223
90
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.YouTube.Comments.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates an existing resource. -- -- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.comments.update@. module Network.Google.Resource.YouTube.Comments.Update ( -- * REST Resource CommentsUpdateResource -- * Creating a Request , commentsUpdate , CommentsUpdate -- * Request Lenses , cuXgafv , cuPart , cuUploadProtocol , cuAccessToken , cuUploadType , cuPayload , cuCallback ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.comments.update@ method which the -- 'CommentsUpdate' request conforms to. type CommentsUpdateResource = "youtube" :> "v3" :> "comments" :> QueryParams "part" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Comment :> Put '[JSON] Comment -- | Updates an existing resource. -- -- /See:/ 'commentsUpdate' smart constructor. data CommentsUpdate = CommentsUpdate' { _cuXgafv :: !(Maybe Xgafv) , _cuPart :: ![Text] , _cuUploadProtocol :: !(Maybe Text) , _cuAccessToken :: !(Maybe Text) , _cuUploadType :: !(Maybe Text) , _cuPayload :: !Comment , _cuCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CommentsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cuXgafv' -- -- * 'cuPart' -- -- * 'cuUploadProtocol' -- -- * 'cuAccessToken' -- -- * 'cuUploadType' -- -- * 'cuPayload' -- -- * 'cuCallback' commentsUpdate :: [Text] -- ^ 'cuPart' -> Comment -- ^ 'cuPayload' -> CommentsUpdate commentsUpdate pCuPart_ pCuPayload_ = CommentsUpdate' { _cuXgafv = Nothing , _cuPart = _Coerce # pCuPart_ , _cuUploadProtocol = Nothing , _cuAccessToken = Nothing , _cuUploadType = Nothing , _cuPayload = pCuPayload_ , _cuCallback = Nothing } -- | V1 error format. cuXgafv :: Lens' CommentsUpdate (Maybe Xgafv) cuXgafv = lens _cuXgafv (\ s a -> s{_cuXgafv = a}) -- | The *part* parameter identifies the properties that the API response -- will include. You must at least include the snippet part in the -- parameter value since that part contains all of the properties that the -- API request can update. cuPart :: Lens' CommentsUpdate [Text] cuPart = lens _cuPart (\ s a -> s{_cuPart = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). cuUploadProtocol :: Lens' CommentsUpdate (Maybe Text) cuUploadProtocol = lens _cuUploadProtocol (\ s a -> s{_cuUploadProtocol = a}) -- | OAuth access token. cuAccessToken :: Lens' CommentsUpdate (Maybe Text) cuAccessToken = lens _cuAccessToken (\ s a -> s{_cuAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). cuUploadType :: Lens' CommentsUpdate (Maybe Text) cuUploadType = lens _cuUploadType (\ s a -> s{_cuUploadType = a}) -- | Multipart request metadata. cuPayload :: Lens' CommentsUpdate Comment cuPayload = lens _cuPayload (\ s a -> s{_cuPayload = a}) -- | JSONP cuCallback :: Lens' CommentsUpdate (Maybe Text) cuCallback = lens _cuCallback (\ s a -> s{_cuCallback = a}) instance GoogleRequest CommentsUpdate where type Rs CommentsUpdate = Comment type Scopes CommentsUpdate = '["https://www.googleapis.com/auth/youtube.force-ssl"] requestClient CommentsUpdate'{..} = go _cuPart _cuXgafv _cuUploadProtocol _cuAccessToken _cuUploadType _cuCallback (Just AltJSON) _cuPayload youTubeService where go = buildClient (Proxy :: Proxy CommentsUpdateResource) mempty
brendanhay/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/Comments/Update.hs
mpl-2.0
4,876
0
18
1,186
802
468
334
112
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.Compute.NodeGroups.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the specified NodeGroup. Get a list of available NodeGroups by -- making a list() request. Note: the \"nodes\" field should not be used. -- Use nodeGroups.listNodes instead. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.nodeGroups.get@. module Network.Google.Resource.Compute.NodeGroups.Get ( -- * REST Resource NodeGroupsGetResource -- * Creating a Request , nodeGroupsGet , NodeGroupsGet -- * Request Lenses , nggNodeGroup , nggProject , nggZone ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.nodeGroups.get@ method which the -- 'NodeGroupsGet' request conforms to. type NodeGroupsGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "nodeGroups" :> Capture "nodeGroup" Text :> QueryParam "alt" AltJSON :> Get '[JSON] NodeGroup -- | Returns the specified NodeGroup. Get a list of available NodeGroups by -- making a list() request. Note: the \"nodes\" field should not be used. -- Use nodeGroups.listNodes instead. -- -- /See:/ 'nodeGroupsGet' smart constructor. data NodeGroupsGet = NodeGroupsGet' { _nggNodeGroup :: !Text , _nggProject :: !Text , _nggZone :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NodeGroupsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nggNodeGroup' -- -- * 'nggProject' -- -- * 'nggZone' nodeGroupsGet :: Text -- ^ 'nggNodeGroup' -> Text -- ^ 'nggProject' -> Text -- ^ 'nggZone' -> NodeGroupsGet nodeGroupsGet pNggNodeGroup_ pNggProject_ pNggZone_ = NodeGroupsGet' { _nggNodeGroup = pNggNodeGroup_ , _nggProject = pNggProject_ , _nggZone = pNggZone_ } -- | Name of the node group to return. nggNodeGroup :: Lens' NodeGroupsGet Text nggNodeGroup = lens _nggNodeGroup (\ s a -> s{_nggNodeGroup = a}) -- | Project ID for this request. nggProject :: Lens' NodeGroupsGet Text nggProject = lens _nggProject (\ s a -> s{_nggProject = a}) -- | The name of the zone for this request. nggZone :: Lens' NodeGroupsGet Text nggZone = lens _nggZone (\ s a -> s{_nggZone = a}) instance GoogleRequest NodeGroupsGet where type Rs NodeGroupsGet = NodeGroup type Scopes NodeGroupsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient NodeGroupsGet'{..} = go _nggProject _nggZone _nggNodeGroup (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy NodeGroupsGetResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/NodeGroups/Get.hs
mpl-2.0
3,798
0
16
895
470
282
188
75
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.Monitoring -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Manages your Cloud Monitoring data and configurations. Most projects -- must be associated with a Workspace, with a few exceptions as noted on -- the individual method pages. The table entries below are presented in -- alphabetical order, not in order of common use. For explanations of the -- concepts found in the table entries, read the Cloud Monitoring -- documentation (https:\/\/cloud.google.com\/monitoring\/docs). -- -- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> module Network.Google.Monitoring ( -- * Service Configuration monitoringService -- * OAuth Scopes , monitoringReadScope , cloudPlatformScope , monitoringScope , monitoringWriteScope -- * API Declaration , MonitoringAPI -- * Resources -- ** monitoring.folders.timeSeries.list , module Network.Google.Resource.Monitoring.Folders.TimeSeries.List -- ** monitoring.organizations.timeSeries.list , module Network.Google.Resource.Monitoring.Organizations.TimeSeries.List -- ** monitoring.projects.alertPolicies.create , module Network.Google.Resource.Monitoring.Projects.AlertPolicies.Create -- ** monitoring.projects.alertPolicies.delete , module Network.Google.Resource.Monitoring.Projects.AlertPolicies.Delete -- ** monitoring.projects.alertPolicies.get , module Network.Google.Resource.Monitoring.Projects.AlertPolicies.Get -- ** monitoring.projects.alertPolicies.list , module Network.Google.Resource.Monitoring.Projects.AlertPolicies.List -- ** monitoring.projects.alertPolicies.patch , module Network.Google.Resource.Monitoring.Projects.AlertPolicies.Patch -- ** monitoring.projects.collectdTimeSeries.create , module Network.Google.Resource.Monitoring.Projects.CollectdTimeSeries.Create -- ** monitoring.projects.groups.create , module Network.Google.Resource.Monitoring.Projects.Groups.Create -- ** monitoring.projects.groups.delete , module Network.Google.Resource.Monitoring.Projects.Groups.Delete -- ** monitoring.projects.groups.get , module Network.Google.Resource.Monitoring.Projects.Groups.Get -- ** monitoring.projects.groups.list , module Network.Google.Resource.Monitoring.Projects.Groups.List -- ** monitoring.projects.groups.members.list , module Network.Google.Resource.Monitoring.Projects.Groups.Members.List -- ** monitoring.projects.groups.update , module Network.Google.Resource.Monitoring.Projects.Groups.Update -- ** monitoring.projects.metricDescriptors.create , module Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Create -- ** monitoring.projects.metricDescriptors.delete , module Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Delete -- ** monitoring.projects.metricDescriptors.get , module Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Get -- ** monitoring.projects.metricDescriptors.list , module Network.Google.Resource.Monitoring.Projects.MetricDescriptors.List -- ** monitoring.projects.monitoredResourceDescriptors.get , module Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.Get -- ** monitoring.projects.monitoredResourceDescriptors.list , module Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.List -- ** monitoring.projects.notificationChannelDescriptors.get , module Network.Google.Resource.Monitoring.Projects.NotificationChannelDescriptors.Get -- ** monitoring.projects.notificationChannelDescriptors.list , module Network.Google.Resource.Monitoring.Projects.NotificationChannelDescriptors.List -- ** monitoring.projects.notificationChannels.create , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Create -- ** monitoring.projects.notificationChannels.delete , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Delete -- ** monitoring.projects.notificationChannels.get , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Get -- ** monitoring.projects.notificationChannels.getVerificationCode , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.GetVerificationCode -- ** monitoring.projects.notificationChannels.list , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.List -- ** monitoring.projects.notificationChannels.patch , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Patch -- ** monitoring.projects.notificationChannels.sendVerificationCode , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.SendVerificationCode -- ** monitoring.projects.notificationChannels.verify , module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Verify -- ** monitoring.projects.timeSeries.create , module Network.Google.Resource.Monitoring.Projects.TimeSeries.Create -- ** monitoring.projects.timeSeries.list , module Network.Google.Resource.Monitoring.Projects.TimeSeries.List -- ** monitoring.projects.timeSeries.query , module Network.Google.Resource.Monitoring.Projects.TimeSeries.Query -- ** monitoring.projects.uptimeCheckConfigs.create , module Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Create -- ** monitoring.projects.uptimeCheckConfigs.delete , module Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Delete -- ** monitoring.projects.uptimeCheckConfigs.get , module Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Get -- ** monitoring.projects.uptimeCheckConfigs.list , module Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.List -- ** monitoring.projects.uptimeCheckConfigs.patch , module Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Patch -- ** monitoring.services.create , module Network.Google.Resource.Monitoring.Services.Create -- ** monitoring.services.delete , module Network.Google.Resource.Monitoring.Services.Delete -- ** monitoring.services.get , module Network.Google.Resource.Monitoring.Services.Get -- ** monitoring.services.list , module Network.Google.Resource.Monitoring.Services.List -- ** monitoring.services.patch , module Network.Google.Resource.Monitoring.Services.Patch -- ** monitoring.services.serviceLevelObjectives.create , module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Create -- ** monitoring.services.serviceLevelObjectives.delete , module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Delete -- ** monitoring.services.serviceLevelObjectives.get , module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Get -- ** monitoring.services.serviceLevelObjectives.list , module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.List -- ** monitoring.services.serviceLevelObjectives.patch , module Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Patch -- ** monitoring.uptimeCheckIps.list , module Network.Google.Resource.Monitoring.UptimeCheckIPs.List -- * Types -- ** MetricDescriptorValueType , MetricDescriptorValueType (..) -- ** NotificationChannelDescriptorLaunchStage , NotificationChannelDescriptorLaunchStage (..) -- ** MonitoredResourceDescriptor , MonitoredResourceDescriptor , monitoredResourceDescriptor , mrdName , mrdDisplayName , mrdLabels , mrdType , mrdDescription , mrdLaunchStage -- ** BasicSli , BasicSli , basicSli , bsLocation , bsLatency , bsAvailability , bsMethod , bsVersion -- ** CollectdValueDataSourceType , CollectdValueDataSourceType (..) -- ** Status , Status , status , sDetails , sCode , sMessage -- ** ValueDescriptorMetricKind , ValueDescriptorMetricKind (..) -- ** ServiceLevelObjective , ServiceLevelObjective , serviceLevelObjective , sloUserLabels , sloName , sloCalendarPeriod , sloServiceLevelIndicator , sloGoal , sloDisplayName , sloRollingPeriod -- ** ListNotificationChannelsResponse , ListNotificationChannelsResponse , listNotificationChannelsResponse , lncrNextPageToken , lncrNotificationChannels , lncrTotalSize -- ** ListTimeSeriesResponse , ListTimeSeriesResponse , listTimeSeriesResponse , ltsrNextPageToken , ltsrExecutionErrors , ltsrUnit , ltsrTimeSeries -- ** GetNotificationChannelVerificationCodeResponse , GetNotificationChannelVerificationCodeResponse , getNotificationChannelVerificationCodeResponse , gncvcrCode , gncvcrExpireTime -- ** Telemetry , Telemetry , telemetry , tResourceName -- ** MonitoringQueryLanguageCondition , MonitoringQueryLanguageCondition , monitoringQueryLanguageCondition , mqlcQuery , mqlcTrigger , mqlcDuration -- ** ListServicesResponse , ListServicesResponse , listServicesResponse , lsrNextPageToken , lsrServices -- ** ListNotificationChannelDescriptorsResponse , ListNotificationChannelDescriptorsResponse , listNotificationChannelDescriptorsResponse , lncdrNextPageToken , lncdrChannelDescriptors -- ** TimeSeriesRatio , TimeSeriesRatio , timeSeriesRatio , tsrTotalServiceFilter , tsrGoodServiceFilter , tsrBadServiceFilter -- ** UptimeCheckIPRegion , UptimeCheckIPRegion (..) -- ** MetricDescriptor , MetricDescriptor , metricDescriptor , mdMonitoredResourceTypes , mdMetricKind , mdName , mdMetadata , mdDisplayName , mdLabels , mdType , mdValueType , mdDescription , mdUnit , mdLaunchStage -- ** GoogleMonitoringV3Range , GoogleMonitoringV3Range , googleMonitoringV3Range , gmvrMax , gmvrMin -- ** Group , Group , group' , gName , gDisplayName , gFilter , gIsCluster , gParentName -- ** TypedValue , TypedValue , typedValue , tvBoolValue , tvDoubleValue , tvStringValue , tvDistributionValue , tvInt64Value -- ** MonitoredResourceLabels , MonitoredResourceLabels , monitoredResourceLabels , mrlAddtional -- ** MonitoredResourceMetadata , MonitoredResourceMetadata , monitoredResourceMetadata , mrmUserLabels , mrmSystemLabels -- ** NotificationChannelUserLabels , NotificationChannelUserLabels , notificationChannelUserLabels , nculAddtional -- ** ServicesServiceLevelObjectivesGetView , ServicesServiceLevelObjectivesGetView (..) -- ** SourceContext , SourceContext , sourceContext , scFileName -- ** BasicAuthentication , BasicAuthentication , basicAuthentication , baUsername , baPassword -- ** Distribution , Distribution , distribution , dSumOfSquaredDeviation , dMean , dCount , dBucketCounts , dExemplars , dRange , dBucketOptions -- ** MetricThresholdComparison , MetricThresholdComparison (..) -- ** ProjectsTimeSeriesListSecondaryAggregationPerSeriesAligner , ProjectsTimeSeriesListSecondaryAggregationPerSeriesAligner (..) -- ** AggregationPerSeriesAligner , AggregationPerSeriesAligner (..) -- ** Field , Field , field , fKind , fOneofIndex , fName , fJSONName , fCardinality , fOptions , fPacked , fDefaultValue , fNumber , fTypeURL -- ** FieldKind , FieldKind (..) -- ** ExemplarAttachmentsItem , ExemplarAttachmentsItem , exemplarAttachmentsItem , eaiAddtional -- ** Service , Service , service , sTelemetry , sCustom , sUserLabels , sIstioCanonicalService , sName , sAppEngine , sClusterIstio , sDisplayName , sMeshIstio , sCloudEndpoints -- ** QueryTimeSeriesRequest , QueryTimeSeriesRequest , queryTimeSeriesRequest , qtsrQuery , qtsrPageToken , qtsrPageSize -- ** NotificationChannelDescriptor , NotificationChannelDescriptor , notificationChannelDescriptor , ncdName , ncdDisplayName , ncdLabels , ncdType , ncdDescription , ncdLaunchStage -- ** LabelValue , LabelValue , labelValue , lvBoolValue , lvStringValue , lvInt64Value -- ** Empty , Empty , empty -- ** ListGroupsResponse , ListGroupsResponse , listGroupsResponse , lgrNextPageToken , lgrGroup -- ** ListMetricDescriptorsResponse , ListMetricDescriptorsResponse , listMetricDescriptorsResponse , lmdrMetricDescriptors , lmdrNextPageToken -- ** WindowsBasedSli , WindowsBasedSli , windowsBasedSli , wbsMetricSumInRange , wbsWindowPeriod , wbsGoodTotalRatioThreshold , wbsGoodBadMetricFilter , wbsMetricMeanInRange -- ** FoldersTimeSeriesListSecondaryAggregationCrossSeriesReducer , FoldersTimeSeriesListSecondaryAggregationCrossSeriesReducer (..) -- ** HTTPCheckRequestMethod , HTTPCheckRequestMethod (..) -- ** Error' , Error' , error' , eStatus , ePointCount -- ** VerifyNotificationChannelRequest , VerifyNotificationChannelRequest , verifyNotificationChannelRequest , vncrCode -- ** OptionValue , OptionValue , optionValue , ovAddtional -- ** DistributionCut , DistributionCut , distributionCut , dcRange , dcDistributionFilter -- ** ProjectsTimeSeriesListAggregationPerSeriesAligner , ProjectsTimeSeriesListAggregationPerSeriesAligner (..) -- ** MetricRange , MetricRange , metricRange , mrRange , mrTimeSeries -- ** AggregationCrossSeriesReducer , AggregationCrossSeriesReducer (..) -- ** NotificationChannelLabels , NotificationChannelLabels , notificationChannelLabels , nclAddtional -- ** MetricDescriptorMetadataLaunchStage , MetricDescriptorMetadataLaunchStage (..) -- ** CreateTimeSeriesRequest , CreateTimeSeriesRequest , createTimeSeriesRequest , ctsrTimeSeries -- ** Custom , Custom , custom -- ** DroppedLabelsLabel , DroppedLabelsLabel , droppedLabelsLabel , dllAddtional -- ** MetricThreshold , MetricThreshold , metricThreshold , mtThresholdValue , mtAggregations , mtDenominatorAggregations , mtComparison , mtDenominatorFilter , mtFilter , mtTrigger , mtDuration -- ** SpanContext , SpanContext , spanContext , scSpanName -- ** StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- ** ProjectsTimeSeriesListSecondaryAggregationCrossSeriesReducer , ProjectsTimeSeriesListSecondaryAggregationCrossSeriesReducer (..) -- ** ValueDescriptorValueType , ValueDescriptorValueType (..) -- ** NotificationChannelVerificationStatus , NotificationChannelVerificationStatus (..) -- ** CreateTimeSeriesSummary , CreateTimeSeriesSummary , createTimeSeriesSummary , ctssTotalPointCount , ctssSuccessPointCount , ctssErrors -- ** MonitoredResourceMetadataUserLabels , MonitoredResourceMetadataUserLabels , monitoredResourceMetadataUserLabels , mrmulAddtional -- ** InternalChecker , InternalChecker , internalChecker , icState , icNetwork , icName , icPeerProjectId , icGcpZone , icDisplayName -- ** NotificationChannel , NotificationChannel , notificationChannel , ncMutationRecords , ncEnabled , ncCreationRecord , ncUserLabels , ncName , ncDisplayName , ncVerificationStatus , ncLabels , ncType , ncDescription -- ** OrganizationsTimeSeriesListAggregationPerSeriesAligner , OrganizationsTimeSeriesListAggregationPerSeriesAligner (..) -- ** ListServiceLevelObjectivesResponse , ListServiceLevelObjectivesResponse , listServiceLevelObjectivesResponse , lslorNextPageToken , lslorServiceLevelObjectives -- ** ListMonitoredResourceDescriptorsResponse , ListMonitoredResourceDescriptorsResponse , listMonitoredResourceDescriptorsResponse , lmrdrNextPageToken , lmrdrResourceDescriptors -- ** LabelDescriptorValueType , LabelDescriptorValueType (..) -- ** Explicit , Explicit , explicit , eBounds -- ** MetricLabels , MetricLabels , metricLabels , mlAddtional -- ** CollectdPayloadMetadata , CollectdPayloadMetadata , collectdPayloadMetadata , cpmAddtional -- ** ContentMatcherMatcher , ContentMatcherMatcher (..) -- ** CollectdValue , CollectdValue , collectdValue , cvDataSourceName , cvDataSourceType , cvValue -- ** CreateCollectdTimeSeriesRequest , CreateCollectdTimeSeriesRequest , createCollectdTimeSeriesRequest , cctsrCollectdPayloads , cctsrResource , cctsrCollectdVersion -- ** TypeSyntax , TypeSyntax (..) -- ** FoldersTimeSeriesListSecondaryAggregationPerSeriesAligner , FoldersTimeSeriesListSecondaryAggregationPerSeriesAligner (..) -- ** OrganizationsTimeSeriesListView , OrganizationsTimeSeriesListView (..) -- ** ProjectsTimeSeriesListAggregationCrossSeriesReducer , ProjectsTimeSeriesListAggregationCrossSeriesReducer (..) -- ** PointData , PointData , pointData , pdValues , pdTimeInterval -- ** OrganizationsTimeSeriesListSecondaryAggregationPerSeriesAligner , OrganizationsTimeSeriesListSecondaryAggregationPerSeriesAligner (..) -- ** Aggregation , Aggregation , aggregation , aPerSeriesAligner , aCrossSeriesReducer , aAlignmentPeriod , aGroupByFields -- ** UptimeCheckConfig , UptimeCheckConfig , uptimeCheckConfig , uccInternalCheckers , uccPeriod , uccContentMatchers , uccName , uccMonitoredResource , uccSelectedRegions , uccIsInternal , uccDisplayName , uccResourceGroup , uccTimeout , uccHTTPCheck , uccTCPCheck -- ** Point , Point , point , pValue , pInterval -- ** FoldersTimeSeriesListView , FoldersTimeSeriesListView (..) -- ** CollectdPayload , CollectdPayload , collectdPayload , cpStartTime , cpPluginInstance , cpValues , cpTypeInstance , cpEndTime , cpMetadata , cpType , cpPlugin -- ** MutationRecord , MutationRecord , mutationRecord , mrMutatedBy , mrMutateTime -- ** Metric , Metric , metric , mLabels , mType -- ** CollectdPayloadError , CollectdPayloadError , collectdPayloadError , cpeError , cpeValueErrors , cpeIndex -- ** ProjectsTimeSeriesListView , ProjectsTimeSeriesListView (..) -- ** OperationMetadataState , OperationMetadataState (..) -- ** SendNotificationChannelVerificationCodeRequest , SendNotificationChannelVerificationCodeRequest , sendNotificationChannelVerificationCodeRequest -- ** Exponential , Exponential , exponential , eGrowthFactor , eScale , eNumFiniteBuckets -- ** PerformanceThreshold , PerformanceThreshold , performanceThreshold , ptBasicSliPerformance , ptPerformance , ptThreshold -- ** LogMatch , LogMatch , logMatch , lmLabelExtractors , lmFilter -- ** HTTPCheckContentType , HTTPCheckContentType (..) -- ** ResourceGroupResourceType , ResourceGroupResourceType (..) -- ** Range , Range , range , rMax , rMin -- ** IstioCanonicalService , IstioCanonicalService , istioCanonicalService , icsCanonicalService , icsMeshUid , icsCanonicalServiceNamespace -- ** AppEngine , AppEngine , appEngine , aeModuleId -- ** QueryTimeSeriesResponse , QueryTimeSeriesResponse , queryTimeSeriesResponse , qtsrNextPageToken , qtsrPartialErrors , qtsrTimeSeriesDescriptor , qtsrTimeSeriesData -- ** OrganizationsTimeSeriesListAggregationCrossSeriesReducer , OrganizationsTimeSeriesListAggregationCrossSeriesReducer (..) -- ** MonitoredResource , MonitoredResource , monitoredResource , mrLabels , mrType -- ** UptimeCheckIP , UptimeCheckIP , uptimeCheckIP , uciIPAddress , uciLocation , uciRegion -- ** ClusterIstio , ClusterIstio , clusterIstio , ciLocation , ciServiceNamespace , ciServiceName , ciClusterName -- ** AlertPolicyUserLabels , AlertPolicyUserLabels , alertPolicyUserLabels , apulAddtional -- ** Documentation , Documentation , documentation , dContent , dMimeType -- ** Xgafv , Xgafv (..) -- ** LogMatchLabelExtractors , LogMatchLabelExtractors , logMatchLabelExtractors , lmleAddtional -- ** AvailabilityCriteria , AvailabilityCriteria , availabilityCriteria -- ** Exemplar , Exemplar , exemplar , eAttachments , eValue , eTimestamp -- ** NotificationRateLimit , NotificationRateLimit , notificationRateLimit , nrlPeriod -- ** FoldersTimeSeriesListAggregationCrossSeriesReducer , FoldersTimeSeriesListAggregationCrossSeriesReducer (..) -- ** MetricDescriptorMetadata , MetricDescriptorMetadata , metricDescriptorMetadata , mdmSamplePeriod , mdmIngestDelay , mdmLaunchStage -- ** ServiceLevelIndicator , ServiceLevelIndicator , serviceLevelIndicator , sliBasicSli , sliRequestBased , sliWindowsBased -- ** TimeInterval , TimeInterval , timeInterval , tiStartTime , tiEndTime -- ** HTTPCheckHeaders , HTTPCheckHeaders , hTTPCheckHeaders , httpchAddtional -- ** TimeSeriesMetricKind , TimeSeriesMetricKind (..) -- ** MonitoredResourceMetadataSystemLabels , MonitoredResourceMetadataSystemLabels , monitoredResourceMetadataSystemLabels , mrmslAddtional -- ** ContentMatcher , ContentMatcher , contentMatcher , cmMatcher , cmContent -- ** ListGroupMembersResponse , ListGroupMembersResponse , listGroupMembersResponse , lgmrNextPageToken , lgmrMembers , lgmrTotalSize -- ** AlertStrategy , AlertStrategy , alertStrategy , asNotificationRateLimit -- ** LabelDescriptor , LabelDescriptor , labelDescriptor , ldKey , ldValueType , ldDescription -- ** TimeSeriesValueType , TimeSeriesValueType (..) -- ** Linear , Linear , linear , lOffSet , lWidth , lNumFiniteBuckets -- ** MonitoredResourceDescriptorLaunchStage , MonitoredResourceDescriptorLaunchStage (..) -- ** AlertPolicyCombiner , AlertPolicyCombiner (..) -- ** ListUptimeCheckIPsResponse , ListUptimeCheckIPsResponse , listUptimeCheckIPsResponse , lucirNextPageToken , lucirUptimeCheckIPs -- ** GetNotificationChannelVerificationCodeRequest , GetNotificationChannelVerificationCodeRequest , getNotificationChannelVerificationCodeRequest , gExpireTime -- ** ResourceGroup , ResourceGroup , resourceGroup , rgResourceType , rgGroupId -- ** DroppedLabels , DroppedLabels , droppedLabels , dlLabel -- ** TimeSeriesDescriptor , TimeSeriesDescriptor , timeSeriesDescriptor , tsdPointDescriptors , tsdLabelDescriptors -- ** OrganizationsTimeSeriesListSecondaryAggregationCrossSeriesReducer , OrganizationsTimeSeriesListSecondaryAggregationCrossSeriesReducer (..) -- ** FieldCardinality , FieldCardinality (..) -- ** Trigger , Trigger , trigger , tPercent , tCount -- ** ServiceLevelObjectiveUserLabels , ServiceLevelObjectiveUserLabels , serviceLevelObjectiveUserLabels , sloulAddtional -- ** ValueDescriptor , ValueDescriptor , valueDescriptor , vdMetricKind , vdKey , vdValueType , vdUnit -- ** Type , Type , type' , tSourceContext , tOneofs , tName , tOptions , tFields , tSyntax -- ** OperationMetadata , OperationMetadata , operationMetadata , omState , omUpdateTime , omCreateTime -- ** UptimeCheckConfigSelectedRegionsItem , UptimeCheckConfigSelectedRegionsItem (..) -- ** MetricDescriptorMetricKind , MetricDescriptorMetricKind (..) -- ** CreateCollectdTimeSeriesResponse , CreateCollectdTimeSeriesResponse , createCollectdTimeSeriesResponse , cctsrSummary , cctsrPayloadErrors -- ** LatencyCriteria , LatencyCriteria , latencyCriteria , lcThreshold -- ** MeshIstio , MeshIstio , meshIstio , miMeshUid , miServiceNamespace , miServiceName -- ** Option , Option , option , oValue , oName -- ** ServiceLevelObjectiveCalendarPeriod , ServiceLevelObjectiveCalendarPeriod (..) -- ** FoldersTimeSeriesListAggregationPerSeriesAligner , FoldersTimeSeriesListAggregationPerSeriesAligner (..) -- ** Condition , Condition , condition , cConditionAbsent , cConditionThreshold , cName , cConditionMonitoringQueryLanguage , cConditionMatchedLog , cDisplayName -- ** TimeSeriesData , TimeSeriesData , timeSeriesData , tsdPointData , tsdLabelValues -- ** ServicesServiceLevelObjectivesListView , ServicesServiceLevelObjectivesListView (..) -- ** BucketOptions , BucketOptions , bucketOptions , boExponentialBuckets , boLinearBuckets , boExplicitBuckets -- ** ListUptimeCheckConfigsResponse , ListUptimeCheckConfigsResponse , listUptimeCheckConfigsResponse , luccrUptimeCheckConfigs , luccrNextPageToken , luccrTotalSize -- ** HTTPCheck , HTTPCheck , hTTPCheck , httpcUseSSL , httpcPath , httpcBody , httpcMaskHeaders , httpcHeaders , httpcValidateSSL , httpcRequestMethod , httpcAuthInfo , httpcContentType , httpcPort -- ** TimeSeries , TimeSeries , timeSeries , tsPoints , tsMetricKind , tsMetric , tsResource , tsMetadata , tsValueType , tsUnit -- ** MetricDescriptorLaunchStage , MetricDescriptorLaunchStage (..) -- ** AlertPolicy , AlertPolicy , alertPolicy , apEnabled , apNotificationChannels , apMutationRecord , apCreationRecord , apUserLabels , apName , apDocumentation , apValidity , apDisplayName , apAlertStrategy , apConditions , apCombiner -- ** RequestBasedSli , RequestBasedSli , requestBasedSli , rbsGoodTotalRatio , rbsDistributionCut -- ** CloudEndpoints , CloudEndpoints , cloudEndpoints , ceService -- ** ListAlertPoliciesResponse , ListAlertPoliciesResponse , listAlertPoliciesResponse , laprNextPageToken , laprTotalSize , laprAlertPolicies -- ** TCPCheck , TCPCheck , tcpCheck , tcPort -- ** InternalCheckerState , InternalCheckerState (..) -- ** ServiceUserLabels , ServiceUserLabels , serviceUserLabels , sulAddtional -- ** MetricAbsence , MetricAbsence , metricAbsence , maAggregations , maFilter , maTrigger , maDuration -- ** CollectdValueError , CollectdValueError , collectdValueError , cveError , cveIndex ) where import Network.Google.Prelude import Network.Google.Monitoring.Types import Network.Google.Resource.Monitoring.Folders.TimeSeries.List import Network.Google.Resource.Monitoring.Organizations.TimeSeries.List import Network.Google.Resource.Monitoring.Projects.AlertPolicies.Create import Network.Google.Resource.Monitoring.Projects.AlertPolicies.Delete import Network.Google.Resource.Monitoring.Projects.AlertPolicies.Get import Network.Google.Resource.Monitoring.Projects.AlertPolicies.List import Network.Google.Resource.Monitoring.Projects.AlertPolicies.Patch import Network.Google.Resource.Monitoring.Projects.CollectdTimeSeries.Create import Network.Google.Resource.Monitoring.Projects.Groups.Create import Network.Google.Resource.Monitoring.Projects.Groups.Delete import Network.Google.Resource.Monitoring.Projects.Groups.Get import Network.Google.Resource.Monitoring.Projects.Groups.List import Network.Google.Resource.Monitoring.Projects.Groups.Members.List import Network.Google.Resource.Monitoring.Projects.Groups.Update import Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Create import Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Delete import Network.Google.Resource.Monitoring.Projects.MetricDescriptors.Get import Network.Google.Resource.Monitoring.Projects.MetricDescriptors.List import Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.Get import Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.List import Network.Google.Resource.Monitoring.Projects.NotificationChannelDescriptors.Get import Network.Google.Resource.Monitoring.Projects.NotificationChannelDescriptors.List import Network.Google.Resource.Monitoring.Projects.NotificationChannels.Create import Network.Google.Resource.Monitoring.Projects.NotificationChannels.Delete import Network.Google.Resource.Monitoring.Projects.NotificationChannels.Get import Network.Google.Resource.Monitoring.Projects.NotificationChannels.GetVerificationCode import Network.Google.Resource.Monitoring.Projects.NotificationChannels.List import Network.Google.Resource.Monitoring.Projects.NotificationChannels.Patch import Network.Google.Resource.Monitoring.Projects.NotificationChannels.SendVerificationCode import Network.Google.Resource.Monitoring.Projects.NotificationChannels.Verify import Network.Google.Resource.Monitoring.Projects.TimeSeries.Create import Network.Google.Resource.Monitoring.Projects.TimeSeries.List import Network.Google.Resource.Monitoring.Projects.TimeSeries.Query import Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Create import Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Delete import Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Get import Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.List import Network.Google.Resource.Monitoring.Projects.UptimeCheckConfigs.Patch import Network.Google.Resource.Monitoring.Services.Create import Network.Google.Resource.Monitoring.Services.Delete import Network.Google.Resource.Monitoring.Services.Get import Network.Google.Resource.Monitoring.Services.List import Network.Google.Resource.Monitoring.Services.Patch import Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Create import Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Delete import Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Get import Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.List import Network.Google.Resource.Monitoring.Services.ServiceLevelObjectives.Patch import Network.Google.Resource.Monitoring.UptimeCheckIPs.List {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Cloud Monitoring API service. type MonitoringAPI = FoldersTimeSeriesListResource :<|> UptimeCheckIPsListResource :<|> OrganizationsTimeSeriesListResource :<|> ProjectsMetricDescriptorsListResource :<|> ProjectsMetricDescriptorsGetResource :<|> ProjectsMetricDescriptorsCreateResource :<|> ProjectsMetricDescriptorsDeleteResource :<|> ProjectsGroupsMembersListResource :<|> ProjectsGroupsListResource :<|> ProjectsGroupsGetResource :<|> ProjectsGroupsCreateResource :<|> ProjectsGroupsDeleteResource :<|> ProjectsGroupsUpdateResource :<|> ProjectsCollectdTimeSeriesCreateResource :<|> ProjectsUptimeCheckConfigsListResource :<|> ProjectsUptimeCheckConfigsPatchResource :<|> ProjectsUptimeCheckConfigsGetResource :<|> ProjectsUptimeCheckConfigsCreateResource :<|> ProjectsUptimeCheckConfigsDeleteResource :<|> ProjectsNotificationChannelsVerifyResource :<|> ProjectsNotificationChannelsListResource :<|> ProjectsNotificationChannelsPatchResource :<|> ProjectsNotificationChannelsGetResource :<|> ProjectsNotificationChannelsCreateResource :<|> ProjectsNotificationChannelsGetVerificationCodeResource :<|> ProjectsNotificationChannelsSendVerificationCodeResource :<|> ProjectsNotificationChannelsDeleteResource :<|> ProjectsMonitoredResourceDescriptorsListResource :<|> ProjectsMonitoredResourceDescriptorsGetResource :<|> ProjectsAlertPoliciesListResource :<|> ProjectsAlertPoliciesPatchResource :<|> ProjectsAlertPoliciesGetResource :<|> ProjectsAlertPoliciesCreateResource :<|> ProjectsAlertPoliciesDeleteResource :<|> ProjectsNotificationChannelDescriptorsListResource :<|> ProjectsNotificationChannelDescriptorsGetResource :<|> ProjectsTimeSeriesListResource :<|> ProjectsTimeSeriesCreateResource :<|> ProjectsTimeSeriesQueryResource :<|> ServicesServiceLevelObjectivesListResource :<|> ServicesServiceLevelObjectivesPatchResource :<|> ServicesServiceLevelObjectivesGetResource :<|> ServicesServiceLevelObjectivesCreateResource :<|> ServicesServiceLevelObjectivesDeleteResource :<|> ServicesListResource :<|> ServicesPatchResource :<|> ServicesGetResource :<|> ServicesCreateResource :<|> ServicesDeleteResource
brendanhay/gogol
gogol-monitoring/gen/Network/Google/Monitoring.hs
mpl-2.0
34,481
0
52
6,777
3,601
2,609
992
805
0
{- Habit of Fate, a game to incentivize habit formation. Copyright (C) 2019 Gregory Crosswhite This program is free software: you can redistribute it and/or modify it under version 3 of the terms of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE UnicodeSyntax #-} module HabitOfFate.Data.QuestState where import HabitOfFate.Prelude import Control.Monad.Catch (MonadThrow(throwM), Exception) import Control.Monad.Logic (LogicT, observeAllT) import Control.Monad.Random.Class (MonadRandom, uniform) import Data.Aeson ( FromJSON(..) , ToJSON(..) , (.:) , withObject ) import Data.List (head,permutations) import System.Random.Shuffle (shuffleM) import HabitOfFate.Data.Markdown import HabitOfFate.Data.Outcomes import HabitOfFate.JSON import HabitOfFate.Quest import HabitOfFate.Story import HabitOfFate.Substitution data Content content = EventContent (Outcomes content) | NarrativeContent content | RandomStoriesContent [content] | StatusContent content | FamesContent [content] deriving (Eq,Foldable,Functor,Ord,Read,Show,Traversable) instance ToJSON content ⇒ ToJSON (Content content) where toJSON content = runJSONBuilder $ case content of EventContent c → writeContent "event" c NarrativeContent c → writeContent "narrative" c RandomStoriesContent c → writeContent "random stories" c StatusContent c → writeContent "status" c FamesContent c → writeContent "fames" c where writeContent ∷ ToJSON c ⇒ Text → c → JSONBuilder () writeContent name c = do writeField "kind" name writeField "content" c instance FromJSON content ⇒ FromJSON (Content content) where parseJSON = withObject "account must be object-shaped" $ \o → do kind ∷ Text ← o .: "kind" case kind of "event" → EventContent <$> (o .: "content") "narrative" → NarrativeContent <$> (o .: "content") "random stories" → RandomStoriesContent <$> (o .: "content") "status" → StatusContent <$> (o .: "content") "fames" → FamesContent <$> (o .: "content") _ → fail [i|Content kind must be event, narrative, ransoms, or fames, not #{kind}|] data QuestState content = QuestState { _quest_state_name_ ∷ Text , _quest_state_fames_ ∷ [content] , _quest_state_remaining_content_ ∷ [Content content] , _quest_state_random_stories_ ∷ [content] , _quest_state_status_ ∷ content } deriving (Eq,Foldable,Functor,Ord,Read,Show,Traversable) makeLenses ''QuestState instance ToJSON content ⇒ ToJSON (QuestState content) where toJSON QuestState{..} = runJSONBuilder $ do writeField "name" _quest_state_name_ writeField "fames" _quest_state_fames_ writeField "content" _quest_state_remaining_content_ writeField "stories" _quest_state_random_stories_ writeField "status" _quest_state_status_ instance FromJSON content ⇒ FromJSON (QuestState content) where parseJSON = withObject "quest state must be object-shaped" $ \o → QuestState <$> (o .: "name") <*> (o .: "fames") <*> (o .: "content") <*> (o .: "stories") <*> (o .: "status") data FolderState content = FolderState { _name_ ∷ Text , _remaining_content_ ∷ Seq (Content content) , _maybe_fames_ ∷ Maybe [content] , _has_random_stories_ ∷ Bool , _substitutions_ ∷ Substitutions } makeLenses ''FolderState data FamesError = DuplicateFames Text | EmptyFames Text | NoFames deriving (Eq,Show) instance Exception FamesError where data RandomStoriesError = EmptyRandomStories Text | NoRandomStoriesForEvent Text deriving (Eq,Show) instance Exception RandomStoriesError where generateQuestState ∷ ∀ m. MonadThrow m ⇒ (∀ α. [α] → m α) → (∀ α. [α] → m α) → (∀ α. [α] → m [α]) → Quest → m (Text, QuestState Markdown) generateQuestState select selectName shuffle Quest{..} = do initial_substitutions ← randomSubstitutionsFor selectName quest_substitutions let initial_folder_state = FolderState { _name_ = quest_name , _remaining_content_ = mempty , _maybe_fames_ = Nothing , _has_random_stories_ = False , _substitutions_ = initial_substitutions } FolderState{..} ← foldlM folder initial_folder_state [quest_entry] fames ← maybe (throwM NoFames) pure _maybe_fames_ let pre_substitution_quest_state = QuestState quest_name fames (toList _remaining_content_) [] "You are between quests." quest_state ← traverse (substitute _substitutions_) pre_substitution_quest_state pure (_name_, quest_state) where folder folder_state entry = case entry of EventEntry{..} | folder_state ^. has_random_stories_ → pure ( folder_state & name_ ⊕~ ("/" ⊕ event_name) & remaining_content_ %~ (`snoc` EventContent event_outcomes)) | otherwise → throwM $ NoRandomStoriesForEvent name NarrativeEntry{..} → pure ( folder_state & name_ ⊕~ ("/" ⊕ narrative_name) & remaining_content_ %~ (`snoc` NarrativeContent (narrative_content & content))) LineEntry{..} → ( case line_shuffle_mode of NoShuffle → pure Shuffle → shuffle $ line_contents ) >>= foldlM folder (folder_state & name_ ⊕~ ("/" ⊕ line_name)) SplitEntry{..} → select split_branches >>= (\Branch{..} → do new_substitutions ← randomSubstitutionsFor selectName branch_substitutions folder (folder_state & substitutions_ %~ (⊕ new_substitutions)) branch_entry ) FamesEntry{..} → case folder_state ^. maybe_fames_ of Nothing | null fames_content → throwM $ EmptyFames quest_name | otherwise → pure (folder_state & maybe_fames_ .~ Just fames_content) Just _ → throwM $ DuplicateFames name RandomStoriesEntry{..} | null random_stories_content → throwM $ EmptyRandomStories name | otherwise → pure ( folder_state & remaining_content_ %~ (`snoc` RandomStoriesContent random_stories_content) & has_random_stories_ .~ True) StatusEntry{..} → pure ( folder_state & remaining_content_ %~ (`snoc` StatusContent status_content)) where name = folder_state ^. name_ instance MonadThrow m ⇒ MonadThrow (LogicT m) where throwM = throwM >>> lift allQuestStates ∷ MonadThrow m ⇒ Quest → m [(Text, QuestState Markdown)] allQuestStates = generateQuestState (map pure >>> asum) (head >>> pure) (permutations >>> map pure >>> asum) >>> observeAllT randomQuestStateFor ∷ (MonadRandom m, MonadThrow m) ⇒ Quest → m (QuestState Markdown) randomQuestStateFor quest = generateQuestState uniform uniform shuffleM quest <&> snd
gcross/habit-of-fate
sources/library/HabitOfFate/Data/QuestState.hs
agpl-3.0
7,636
0
18
1,548
1,859
975
884
174
9
{-# LANGUAGE OverloadedStrings #-} module Commands.Distrowatch ( distrowatch ) where import qualified Data.Response as R import Control.Monad.IO.Class import Network.HTTP.Client import Data.ByteString.Char8 (ByteString, unpack) import qualified Data.ByteString.Lazy as B import Data.Monoid import Data.Maybe import Network.IRC import Text.HTML.TagSoup data Distro = Distro { distroURL :: ByteString , distroName :: ByteString } deriving (Show, Eq) randomDistro :: MonadIO m => Manager -> m Distro randomDistro manager = liftIO $ do req1 <- parseRequest "http://distrowatch.com/random" rsp1 <- withResponseHistory req1 manager $ pure . hrFinalRequest let url = "http://distrowatch.com" <> path rsp1 <> queryString rsp1 req2 <- parseRequest $ unpack url rsp2 <- responseBody <$> httpLbs req2 manager let name = case head . drop 5 . parseTags $ rsp2 of TagText x | "DistroWatch" `B.isPrefixOf` x -> B.drop 17 x _ -> "<unknown>" pure $ Distro url (B.toStrict name) distrowatch :: MonadIO m => Manager -> R.Response m distrowatch manager = R.simpleCmd ":distro" $ \_ c -> do distro <- randomDistro manager let resp = distroName distro <> " - " <> distroURL distro pure $ privmsg (fromMaybe "" c) resp
tsahyt/lmrbot
src/Commands/Distrowatch.hs
agpl-3.0
1,331
0
17
312
405
206
199
34
2
import Data.Monoid import Test.QuickCheck -- Exercise: Optional Monoid data Optional a = Nada | Only a deriving (Eq, Show) instance (Arbitrary a) => Arbitrary (Optional a) where arbitrary = do a <- arbitrary oneof [ return Nada , return $ Only a ] instance Monoid a => Monoid (Optional a) where mempty = Nada mappend (Only a) (Only b) = Only (a <> b) mappend Nada a = a mappend a Nada = a monoidAssoc :: (Eq m, Monoid m) => m -> m -> m -> Bool monoidAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c) monoidLeftIdentity :: (Eq m, Monoid m) => m -> Bool monoidLeftIdentity a = (mempty <> a) == a monoidRightIdentity :: (Eq m, Monoid m) => m -> Bool monoidRightIdentity a = (a <> mempty) == a -- Exercise: Maybe Another Monoid newtype First' a = First' { getFirst' :: Optional a } deriving (Eq, Show) instance (Arbitrary a) => Arbitrary (First' a) where arbitrary = do a <- arbitrary return $ First' a instance Monoid (First' a) where mempty = First' Nada mappend (First' Nada) a = a mappend a (First' Nada) = a mappend a _ = a firstMappend :: First' a -> First' a -> First' a firstMappend = mappend type FirstMappend = First' String -> First' String -> First' String -> Bool type FstId = First' String -> Bool main :: IO () main = do quickCheck (monoidAssoc :: FirstMappend) quickCheck (monoidLeftIdentity :: FstId) quickCheck (monoidRightIdentity :: FstId)
dmp1ce/Haskell-Programming-Exercises
Chapter 15/Exercise: Optional Monoid.hs
unlicense
1,490
1
10
390
590
306
284
42
1
{-# LANGUAGE CPP #-} {- Math.hs - Point of switching between MathDirect and MathHmatrix - - Timothy A. Chagnon - CS 636 - Spring 2009 -} module Math ( #ifdef USING_HMATRIX module MathHmatrix, #else module MathDirect, #endif module MatInv ) where #ifdef USING_HMATRIX import MathHmatrix #else import MathDirect #endif import MatInv
tchagnon/cs636-raytracer
a1/Math.hs
apache-2.0
356
0
4
76
28
22
6
6
0
module Text.Pandoc.RPC where import Text.Pandoc import Text.Pandoc.Rpc.Protocol import Text.Pandoc.Rpc.Protocol.PandocRequest import Text.ProtocolBuffers.Basic import Text.ProtocolBuffers.WireMessage import qualified Text.Pandoc.Rpc.Protocol.PandocResponse as R import Data.ByteString.Lazy.Char8 hiding (putStrLn) import qualified Data.ByteString.Lazy as L import System.ZMQ3 import Control.Concurrent (forkIO) import Control.Monad (forever, forM_) pipeline :: String -> String -> Either String (ReaderOptions -> String -> IO Pandoc, Writer) pipeline inputFmt outputFmt = case getReader inputFmt of Left error -> Left error Right reader@_ -> writer reader where writer reader = case getWriter outputFmt of Left error -> Left error Right writer@_ -> Right (reader, writer) write :: Writer -> Pandoc -> IO String write writer native = case writer of PureStringWriter writer' -> return $ writer' def native IOStringWriter writer' -> writer' def native IOByteStringWriter writer' -> do out <- writer' def native return $ unpack out transform :: (ReaderOptions -> String -> IO Pandoc) -> Writer -> String -> IO String transform reader writer input = do native <- reader def input write writer native pandoc :: String -> String -> String -> IO (Either String String) pandoc inputFmt outputFmt input = do case pipeline inputFmt outputFmt of Left error -> return $ Left error Right (reader, writer) -> do out <- transform reader writer input return $ Right out pandoc' :: PandocRequest -> IO R.PandocResponse pandoc' req = do resp <- pandoc (uToString $ inputFmt req) (uToString $ outputFmt req) (uToString $ input req) return $ case resp of Left error -> R.PandocResponse { R.error = Just $ uFromString error, R.output = Nothing } Right output -> R.PandocResponse { R.error = Nothing, R.output = Just $ uFromString output } worker :: (Receiver a, Sender a) => Socket a -> IO () worker socket = do msg <- receive socket resp <- case messageGet $ fromStrict msg of Left error -> return $ R.PandocResponse { R.error = Just $ uFromString error, R.output = Nothing } Right (msg, _) -> pandoc' msg send socket [] $ toStrict $ messagePut resp workers :: Int -> Context -> IO () workers workerCount context = forM_ [0..workerCount] $ \_ -> forkIO $ do withSocket context Rep $ \responder -> do connect responder "inproc://pandoc" forever $ worker responder main :: String -> Int -> IO () main endpoint workerCount = do withContext $ \context -> do withSocket context Router $ \frontend -> do bind frontend endpoint withSocket context Dealer $ \backend -> do bind backend "inproc://pandoc" workers workerCount context proxy frontend backend Nothing
aolshevskiy/pandoc-rpc
Text/Pandoc/RPC.hs
apache-2.0
2,897
0
19
666
983
489
494
70
3
{-# LANGUAGE QuasiQuotes #-} ----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.GUI.Menu -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Application.HXournal.GUI.Menu where import Application.HXournal.Util.Verbatim import Application.HXournal.Coroutine.Callback import Application.HXournal.Type import Application.HXournal.Type.Clipboard import Application.HXournal.Accessor import Control.Monad.Coroutine.SuspensionFunctors import Data.IORef import Data.Maybe import Control.Category import Data.Label import Prelude hiding ((.),id) import Graphics.UI.Gtk hiding (set,get) import qualified Graphics.UI.Gtk as Gtk (set) import System.FilePath import Data.Xournal.Predefined import Paths_hxournal -- | justMenu :: MenuEvent -> Maybe MyEvent justMenu = Just . Menu -- | uiDeclTest :: String uiDeclTest = [verbatim|<ui> <menubar> <menu action="VMA"> <menuitem action="CONTA" /> <menuitem action="ONEPAGEA" /> <separator /> <menuitem action="FSCRA" /> <separator /> </menu> </menubar> </ui>|] -- | uiDecl :: String uiDecl = [verbatim|<ui> <menubar> <menu action="FMA"> <menuitem action="NEWA" /> <menuitem action="ANNPDFA" /> <menuitem action="OPENA" /> <menuitem action="SAVEA" /> <menuitem action="SAVEASA" /> <separator /> <menuitem action="RECENTA" /> <separator /> <menuitem action="PRINTA" /> <menuitem action="EXPORTA" /> <separator /> <menuitem action="QUITA" /> </menu> <menu action="EMA"> <menuitem action="UNDOA" /> <menuitem action="REDOA" /> <separator /> <menuitem action="CUTA" /> <menuitem action="COPYA" /> <menuitem action="PASTEA" /> <menuitem action="DELETEA" /> <separator /> <menuitem action="NETCOPYA" /> <menuitem action="NETPASTEA" /> </menu> <menu action="VMA"> <menuitem action="CONTA" /> <menuitem action="ONEPAGEA" /> <separator /> <menuitem action="FSCRA" /> <separator /> <menu action="ZOOMA" > <menuitem action="ZMINA" /> <menuitem action="ZMOUTA" /> <menuitem action="NRMSIZEA" /> <menuitem action="PGWDTHA" /> <menuitem action="PGHEIGHTA" /> <menuitem action="SETZMA" /> </menu> <separator /> <menuitem action="FSTPAGEA" /> <menuitem action="PRVPAGEA" /> <menuitem action="NXTPAGEA" /> <menuitem action="LSTPAGEA" /> <separator /> <menuitem action="SHWLAYERA" /> <menuitem action="HIDLAYERA" /> <separator /> <menuitem action="HSPLITA" /> <menuitem action="VSPLITA" /> <menuitem action="DELCVSA" /> </menu> <menu action="JMA"> <menuitem action="NEWPGBA" /> <menuitem action="NEWPGAA" /> <menuitem action="NEWPGEA" /> <menuitem action="DELPGA" /> <separator /> <menuitem action="NEWLYRA" /> <menuitem action="NEXTLAYERA" /> <menuitem action="PREVLAYERA" /> <menuitem action="GOTOLAYERA" /> <menuitem action="DELLYRA" /> <separator /> <menuitem action="PPSIZEA" /> <menuitem action="PPCLRA" /> <menuitem action="PPSTYA" /> <menuitem action="APALLPGA" /> <separator /> <menuitem action="LDBKGA" /> <menuitem action="BKGSCRSHTA" /> <separator /> <menuitem action="DEFPPA" /> <menuitem action="SETDEFPPA" /> </menu> <menu action="TMA"> <menuitem action="PENA" /> <menuitem action="ERASERA" /> <menuitem action="HIGHLTA" /> <menuitem action="TEXTA" /> <separator /> <menuitem action="SHPRECA" /> <menuitem action="RULERA" /> <separator /> <menuitem action="SELREGNA" /> <menuitem action="SELRECTA" /> <menuitem action="VERTSPA" /> <menuitem action="HANDA" /> <separator /> <menu action="CLRA"> <menuitem action="BLACKA" /> <menuitem action="BLUEA" /> <menuitem action="REDA" /> <menuitem action="GREENA" /> <menuitem action="GRAYA" /> <menuitem action="LIGHTBLUEA" /> <menuitem action="LIGHTGREENA" /> <menuitem action="MAGENTAA" /> <menuitem action="ORANGEA" /> <menuitem action="YELLOWA" /> <menuitem action="WHITEA" /> </menu> <menu action="PENOPTA"> <menuitem action="PENVERYFINEA" /> <menuitem action="PENFINEA" /> <menuitem action="PENMEDIUMA" /> <menuitem action="PENTHICKA" /> <menuitem action="PENVERYTHICKA" /> <menuitem action="PENULTRATHICKA" /> </menu> <menuitem action="ERASROPTA" /> <menuitem action="HILTROPTA" /> <menuitem action="TXTFNTA" /> <separator /> <menuitem action="DEFPENA" /> <menuitem action="DEFERSRA" /> <menuitem action="DEFHILTRA" /> <menuitem action="DEFTXTA" /> <menuitem action="SETDEFOPTA" /> </menu> <menu action="OMA"> <menuitem action="UXINPUTA" /> <menuitem action="DCRDCOREA" /> <menuitem action="ERSRTIPA" /> <menuitem action="PRESSRSENSA" /> <menuitem action="PGHILTA" /> <menuitem action="MLTPGVWA" /> <menuitem action="MLTPGA" /> <menuitem action="BTN2MAPA" /> <menuitem action="BTN3MAPA" /> <separator /> <menuitem action="ANTIALIASBMPA" /> <menuitem action="PRGRSBKGA" /> <menuitem action="PRNTPPRULEA" /> <menuitem action="LFTHNDSCRBRA" /> <menuitem action="SHRTNMENUA" /> <separator /> <menuitem action="AUTOSAVEPREFA" /> <menuitem action="SAVEPREFA" /> <menuitem action="RELAUNCHA" /> </menu> <menu action="HMA"> <menuitem action="ABOUTA" /> </menu> </menubar> <toolbar name="toolbar1" > <toolitem action="SAVEA" /> <toolitem action="NEWA" /> <toolitem action="OPENA" /> <separator /> <toolitem action="CUTA" /> <toolitem action="COPYA" /> <toolitem action="PASTEA" /> <separator /> <toolitem action="UNDOA" /> <toolitem action="REDOA" /> <separator /> <toolitem action="FSTPAGEA" /> <toolitem action="PRVPAGEA" /> <toolitem action="NXTPAGEA" /> <toolitem action="LSTPAGEA" /> <separator /> <toolitem action="ZMOUTA" /> <toolitem action="NRMSIZEA" /> <toolitem action="ZMINA" /> <toolitem action="PGWDTHA" /> <toolitem action="SETZMA" /> <toolitem action="FSCRA" /> </toolbar> <toolbar name="toolbar2" > <toolitem action="PENA" /> <toolitem action="ERASERA" /> <toolitem action="HIGHLTA" /> <toolitem action="TEXTA" /> <separator /> <toolitem action="DEFAULTA" /> <toolitem action="DEFPENA" /> <toolitem action="SHPRECA" /> <toolitem action="RULERA" /> <separator /> <toolitem action="SELREGNA" /> <toolitem action="SELRECTA" /> <toolitem action="VERTSPA" /> <toolitem action="HANDA" /> <separator /> <toolitem action="PENFINEA" /> <toolitem action="PENMEDIUMA" /> <toolitem action="PENTHICKA" /> <separator /> <toolitem action="BLACKA" /> <toolitem action="BLUEA" /> <toolitem action="REDA" /> <toolitem action="GREENA" /> <toolitem action="GRAYA" /> <toolitem action="LIGHTBLUEA" /> <toolitem action="LIGHTGREENA" /> <toolitem action="MAGENTAA" /> <toolitem action="ORANGEA" /> <toolitem action="YELLOWA" /> <toolitem action="WHITEA" /> </toolbar> </ui> |] iconList :: [ (String,String) ] iconList = [ ("fullscreen.png" , "myfullscreen") , ("pencil.png" , "mypen") , ("eraser.png" , "myeraser") , ("highlighter.png", "myhighlighter") , ("text-tool.png" , "mytext") , ("shapes.png" , "myshapes") , ("ruler.png" , "myruler") , ("lasso.png" , "mylasso") , ("rect-select.png", "myrectselect") , ("stretch.png" , "mystretch") , ("hand.png" , "myhand") , ("recycled.png" , "mydefault") , ("default-pen.png", "mydefaultpen") , ("thin.png" , "mythin") , ("medium.png" , "mymedium") , ("thick.png" , "mythick") , ("black.png" , "myblack") , ("blue.png" , "myblue") , ("red.png" , "myred") , ("green.png" , "mygreen") , ("gray.png" , "mygray") , ("lightblue.png" , "mylightblue") , ("lightgreen.png" , "mylightgreen") , ("magenta.png" , "mymagenta") , ("orange.png" , "myorange") , ("yellow.png" , "myyellow") , ("white.png" , "mywhite") ] -- | viewmods :: [RadioActionEntry] viewmods = [ RadioActionEntry "CONTA" "Continuous" Nothing Nothing Nothing 0 , RadioActionEntry "ONEPAGEA" "One Page" Nothing Nothing Nothing 1 ] -- | pointmods :: [RadioActionEntry] pointmods = [ RadioActionEntry "PENVERYFINEA" "Very fine" Nothing Nothing Nothing 0 , RadioActionEntry "PENFINEA" "Fine" (Just "mythin") Nothing Nothing 1 , RadioActionEntry "PENTHICKA" "Thick" (Just "mythick") Nothing Nothing 3 , RadioActionEntry "PENVERYTHICKA" "Very Thick" Nothing Nothing Nothing 4 , RadioActionEntry "PENULTRATHICKA" "Ultra Thick" Nothing Nothing Nothing 5 , RadioActionEntry "PENMEDIUMA" "Medium" (Just "mymedium") Nothing Nothing 2 ] -- | penmods :: [RadioActionEntry] penmods = [ RadioActionEntry "PENA" "Pen" (Just "mypen") Nothing Nothing 0 , RadioActionEntry "ERASERA" "Eraser" (Just "myeraser") Nothing Nothing 1 , RadioActionEntry "HIGHLTA" "Highlighter" (Just "myhighlighter") Nothing Nothing 2 , RadioActionEntry "TEXTA" "Text" (Just "mytext") Nothing Nothing 3 , RadioActionEntry "SELREGNA" "Select Region" (Just "mylasso") Nothing Nothing 4 , RadioActionEntry "SELRECTA" "Select Rectangle" (Just "myrectselect") Nothing Nothing 5 , RadioActionEntry "VERTSPA" "Vertical Space" (Just "mystretch") Nothing Nothing 6 , RadioActionEntry "HANDA" "Hand Tool" (Just "myhand") Nothing Nothing 7 ] -- | colormods :: [RadioActionEntry] colormods = [ RadioActionEntry "BLUEA" "Blue" (Just "myblue") Nothing Nothing 1 , RadioActionEntry "REDA" "Red" (Just "myred") Nothing Nothing 2 , RadioActionEntry "GREENA" "Green" (Just "mygreen") Nothing Nothing 3 , RadioActionEntry "GRAYA" "Gray" (Just "mygray") Nothing Nothing 4 , RadioActionEntry "LIGHTBLUEA" "Lightblue" (Just "mylightblue") Nothing Nothing 5 , RadioActionEntry "LIGHTGREENA" "Lightgreen" (Just "mylightgreen") Nothing Nothing 6 , RadioActionEntry "MAGENTAA" "Magenta" (Just "mymagenta") Nothing Nothing 7 , RadioActionEntry "ORANGEA" "Orange" (Just "myorange") Nothing Nothing 8 , RadioActionEntry "YELLOWA" "Yellow" (Just "myyellow") Nothing Nothing 9 , RadioActionEntry "WHITEA" "White" (Just "mywhite") Nothing Nothing 10 , RadioActionEntry "BLACKA" "Black" (Just "myblack") Nothing Nothing 0 ] -- | iconResourceAdd :: IconFactory -> FilePath -> (FilePath, StockId) -> IO () iconResourceAdd iconfac resdir (fp,stid) = do myIconSource <- iconSourceNew iconSourceSetFilename myIconSource (resdir </> fp) iconSourceSetSize myIconSource IconSizeLargeToolbar myIconSourceSmall <- iconSourceNew iconSourceSetFilename myIconSourceSmall (resdir </> fp) iconSourceSetSize myIconSource IconSizeMenu myIconSet <- iconSetNew iconSetAddSource myIconSet myIconSource iconSetAddSource myIconSet myIconSourceSmall iconFactoryAdd iconfac stid myIconSet -- | actionNewAndRegisterRef :: IORef (Await MyEvent (Iteratee MyEvent XournalStateIO ())) -> IORef HXournalState -> String -> String -> Maybe String -> Maybe StockId -> Maybe MyEvent -> IO Action actionNewAndRegisterRef tref sref name label tooltip stockId myevent = do a <- actionNew name label tooltip stockId case myevent of Nothing -> return a Just ev -> do a `on` actionActivated $ do bouncecallback tref sref ev return a -- | getMenuUI :: IORef (Await MyEvent (Iteratee MyEvent XournalStateIO ())) -> IORef HXournalState -> IO UIManager getMenuUI tref sref = do let actionNewAndRegister = actionNewAndRegisterRef tref sref -- icons myiconfac <- iconFactoryNew iconFactoryAddDefault myiconfac resDir <- getDataDir >>= return . (</> "resource") mapM_ (iconResourceAdd myiconfac resDir) iconList fma <- actionNewAndRegister "FMA" "File" Nothing Nothing Nothing ema <- actionNewAndRegister "EMA" "Edit" Nothing Nothing Nothing vma <- actionNewAndRegister "VMA" "View" Nothing Nothing Nothing jma <- actionNewAndRegister "JMA" "Journal" Nothing Nothing Nothing tma <- actionNewAndRegister "TMA" "Tools" Nothing Nothing Nothing oma <- actionNewAndRegister "OMA" "Options" Nothing Nothing Nothing hma <- actionNewAndRegister "HMA" "Help" Nothing Nothing Nothing -- file menu newa <- actionNewAndRegister "NEWA" "New" (Just "Just a Stub") (Just stockNew) (justMenu MenuNew) annpdfa <- actionNewAndRegister "ANNPDFA" "Annotate PDF" (Just "Just a Stub") Nothing (justMenu MenuAnnotatePDF) opena <- actionNewAndRegister "OPENA" "Open" (Just "Just a Stub") (Just stockOpen) (justMenu MenuOpen) savea <- actionNewAndRegister "SAVEA" "Save" (Just "Just a Stub") (Just stockSave) (justMenu MenuSave) saveasa <- actionNewAndRegister "SAVEASA" "Save As" (Just "Just a Stub") (Just stockSaveAs) (justMenu MenuSaveAs) recenta <- actionNewAndRegister "RECENTA" "Recent Document" (Just "Just a Stub") Nothing (justMenu MenuRecentDocument) printa <- actionNewAndRegister "PRINTA" "Print" (Just "Just a Stub") Nothing (justMenu MenuPrint) exporta <- actionNewAndRegister "EXPORTA" "Export" (Just "Just a Stub") Nothing (justMenu MenuExport) quita <- actionNewAndRegister "QUITA" "Quit" (Just "Just a Stub") (Just stockQuit) (justMenu MenuQuit) -- edit menu undoa <- actionNewAndRegister "UNDOA" "Undo" (Just "Just a Stub") (Just stockUndo) (justMenu MenuUndo) redoa <- actionNewAndRegister "REDOA" "Redo" (Just "Just a Stub") (Just stockRedo) (justMenu MenuRedo) cuta <- actionNewAndRegister "CUTA" "Cut" (Just "Just a Stub") (Just stockCut) (justMenu MenuCut) copya <- actionNewAndRegister "COPYA" "Copy" (Just "Just a Stub") (Just stockCopy) (justMenu MenuCopy) pastea <- actionNewAndRegister "PASTEA" "Paste" (Just "Just a Stub") (Just stockPaste) (justMenu MenuPaste) deletea <- actionNewAndRegister "DELETEA" "Delete" (Just "Just a Stub") (Just stockDelete) (justMenu MenuDelete) -- netcopya <- actionNewAndRegister "NETCOPYA" "Copy to NetworkClipboard" (Just "Just a Stub") Nothing (justMenu MenuNetCopy) -- netpastea <- actionNewAndRegister "NETPASTEA" "Paste from NetworkClipboard" (Just "Just a Stub") Nothing (justMenu MenuNetPaste) -- view menu fscra <- actionNewAndRegister "FSCRA" "Full Screen" (Just "Just a Stub") (Just "myfullscreen") (justMenu MenuFullScreen) zooma <- actionNewAndRegister "ZOOMA" "Zoom" (Just "Just a Stub") Nothing Nothing -- (justMenu MenuZoom) zmina <- actionNewAndRegister "ZMINA" "Zoom In" (Just "Zoom In") (Just stockZoomIn) (justMenu MenuZoomIn) zmouta <- actionNewAndRegister "ZMOUTA" "Zoom Out" (Just "Zoom Out") (Just stockZoomOut) (justMenu MenuZoomOut) nrmsizea <- actionNewAndRegister "NRMSIZEA" "Normal Size" (Just "Normal Size") (Just stockZoom100) (justMenu MenuNormalSize) pgwdtha <- actionNewAndRegister "PGWDTHA" "Page Width" (Just "Page Width") (Just stockZoomFit) (justMenu MenuPageWidth) pgheighta <- actionNewAndRegister "PGHEIGHTA" "Page Height" (Just "Page Height") Nothing (justMenu MenuPageHeight) setzma <- actionNewAndRegister "SETZMA" "Set Zoom" (Just "Set Zoom") (Just stockFind) (justMenu MenuSetZoom) fstpagea <- actionNewAndRegister "FSTPAGEA" "First Page" (Just "Just a Stub") (Just stockGotoFirst) (justMenu MenuFirstPage) prvpagea <- actionNewAndRegister "PRVPAGEA" "Previous Page" (Just "Just a Stub") (Just stockGoBack) (justMenu MenuPreviousPage) nxtpagea <- actionNewAndRegister "NXTPAGEA" "Next Page" (Just "Just a Stub") (Just stockGoForward) (justMenu MenuNextPage) lstpagea <- actionNewAndRegister "LSTPAGEA" "Last Page" (Just "Just a Stub") (Just stockGotoLast) (justMenu MenuLastPage) shwlayera <- actionNewAndRegister "SHWLAYERA" "Show Layer" (Just "Just a Stub") Nothing (justMenu MenuShowLayer) hidlayera <- actionNewAndRegister "HIDLAYERA" "Hide Layer" (Just "Just a Stub") Nothing (justMenu MenuHideLayer) hsplita <- actionNewAndRegister "HSPLITA" "Horizontal Split" (Just "horizontal split") Nothing (justMenu MenuHSplit) vsplita <- actionNewAndRegister "VSPLITA" "Vertical Split" (Just "vertical split") Nothing (justMenu MenuVSplit) delcvsa <- actionNewAndRegister "DELCVSA" "Delete Current Canvas" (Just "delete current canvas") Nothing (justMenu MenuDelCanvas) -- journal menu newpgba <- actionNewAndRegister "NEWPGBA" "New Page Before" (Just "Just a Stub") Nothing (justMenu MenuNewPageBefore) newpgaa <- actionNewAndRegister "NEWPGAA" "New Page After" (Just "Just a Stub") Nothing (justMenu MenuNewPageAfter) newpgea <- actionNewAndRegister "NEWPGEA" "New Page At End" (Just "Just a Stub") Nothing (justMenu MenuNewPageAtEnd) delpga <- actionNewAndRegister "DELPGA" "Delete Page" (Just "Just a Stub") Nothing (justMenu MenuDeletePage) newlyra <- actionNewAndRegister "NEWLYRA" "New Layer" (Just "Just a Stub") Nothing (justMenu MenuNewLayer) nextlayera <- actionNewAndRegister "NEXTLAYERA" "Next Layer" (Just "Just a Stub") Nothing (justMenu MenuNextLayer) prevlayera <- actionNewAndRegister "PREVLAYERA" "Prev Layer" (Just "Just a Stub") Nothing (justMenu MenuPrevLayer) gotolayera <- actionNewAndRegister "GOTOLAYERA" "Goto Layer" (Just "Just a Stub") Nothing (justMenu MenuGotoLayer) dellyra <- actionNewAndRegister "DELLYRA" "Delete Layer" (Just "Just a Stub") Nothing (justMenu MenuDeleteLayer) ppsizea <- actionNewAndRegister "PPSIZEA" "Paper Size" (Just "Just a Stub") Nothing (justMenu MenuPaperSize) ppclra <- actionNewAndRegister "PPCLRA" "Paper Color" (Just "Just a Stub") Nothing (justMenu MenuPaperColor) ppstya <- actionNewAndRegister "PPSTYA" "Paper Style" (Just "Just a Stub") Nothing (justMenu MenuPaperStyle) apallpga<- actionNewAndRegister "APALLPGA" "Apply To All Pages" (Just "Just a Stub") Nothing (justMenu MenuApplyToAllPages) ldbkga <- actionNewAndRegister "LDBKGA" "Load Background" (Just "Just a Stub") Nothing (justMenu MenuLoadBackground) bkgscrshta <- actionNewAndRegister "BKGSCRSHTA" "Background Screenshot" (Just "Just a Stub") Nothing (justMenu MenuBackgroundScreenshot) defppa <- actionNewAndRegister "DEFPPA" "Default Paper" (Just "Just a Stub") Nothing (justMenu MenuDefaultPaper) setdefppa <- actionNewAndRegister "SETDEFPPA" "Set As Default" (Just "Just a Stub") Nothing (justMenu MenuSetAsDefaultPaper) -- tools menu shpreca <- actionNewAndRegister "SHPRECA" "Shape Recognizer" (Just "Just a Stub") (Just "myshapes") (justMenu MenuShapeRecognizer) rulera <- actionNewAndRegister "RULERA" "Ruler" (Just "Just a Stub") (Just "myruler") (justMenu MenuRuler) -- selregna <- actionNewAndRegister "SELREGNA" "Select Region" (Just "Just a Stub") (Just "mylasso") (justMenu MenuSelectRegion) -- selrecta <- actionNewAndRegister "SELRECTA" "Select Rectangle" (Just "Just a Stub") (Just "myrectselect") (justMenu MenuSelectRectangle) -- vertspa <- actionNewAndRegister "VERTSPA" "Vertical Space" (Just "Just a Stub") (Just "mystretch") (justMenu MenuVerticalSpace) -- handa <- actionNewAndRegister "HANDA" "Hand Tool" (Just "Just a Stub") (Just "myhand") (justMenu MenuHandTool) clra <- actionNewAndRegister "CLRA" "Color" (Just "Just a Stub") Nothing Nothing penopta <- actionNewAndRegister "PENOPTA" "Pen Options" (Just "Just a Stub") Nothing (justMenu MenuPenOptions) erasropta <- actionNewAndRegister "ERASROPTA" "Eraser Options" (Just "Just a Stub") Nothing (justMenu MenuEraserOptions) hiltropta <- actionNewAndRegister "HILTROPTA" "Highlighter Options" (Just "Just a Stub") Nothing (justMenu MenuHighlighterOptions) txtfnta <- actionNewAndRegister "TXTFNTA" "Text Font" (Just "Just a Stub") Nothing (justMenu MenuTextFont) defpena <- actionNewAndRegister "DEFPENA" "Default Pen" (Just "Just a Stub") (Just "mydefaultpen") (justMenu MenuDefaultPen) defersra <- actionNewAndRegister "DEFERSRA" "Default Eraser" (Just "Just a Stub") Nothing (justMenu MenuDefaultEraser) defhiltra <- actionNewAndRegister "DEFHILTRA" "Default Highlighter" (Just "Just a Stub") Nothing (justMenu MenuDefaultHighlighter) deftxta <- actionNewAndRegister "DEFTXTA" "Default Text" (Just "Just a Stub") Nothing (justMenu MenuDefaultText) setdefopta <- actionNewAndRegister "SETDEFOPTA" "Set As Default" (Just "Just a Stub") Nothing (justMenu MenuSetAsDefaultOption) relauncha <- actionNewAndRegister "RELAUNCHA" "Relaunch Application" (Just "Just a Stub") Nothing (justMenu MenuRelaunch) -- options menu uxinputa <- toggleActionNew "UXINPUTA" "Use XInput" (Just "Just a Stub") Nothing uxinputa `on` actionToggled $ do bouncecallback tref sref (Menu MenuUseXInput) -- AndRegister "UXINPUTA" "Use XInput" (Just "Just a Stub") Nothing (justMenu MenuUseXInput) dcrdcorea <- actionNewAndRegister "DCRDCOREA" "Discard Core Events" (Just "Just a Stub") Nothing (justMenu MenuDiscardCoreEvents) ersrtipa <- actionNewAndRegister "ERSRTIPA" "Eraser Tip" (Just "Just a Stub") Nothing (justMenu MenuEraserTip) pressrsensa <- toggleActionNew "PRESSRSENSA" "Pressure Sensitivity" (Just "Just a Stub") Nothing pressrsensa `on` actionToggled $ do bouncecallback tref sref (Menu MenuPressureSensitivity) -- AndRegister "UXINPUTA" "Use XInput" (Just "Just a Stub") Nothing (justMenu MenuUseXInput) pghilta <- actionNewAndRegister "PGHILTA" "Page Highlight" (Just "Just a Stub") Nothing (justMenu MenuPageHighlight) mltpgvwa <- actionNewAndRegister "MLTPGVWA" "Multiple Page View" (Just "Just a Stub") Nothing (justMenu MenuMultiplePageView) mltpga <- actionNewAndRegister "MLTPGA" "Multiple Pages" (Just "Just a Stub") Nothing (justMenu MenuMultiplePages) btn2mapa <- actionNewAndRegister "BTN2MAPA" "Button 2 Mapping" (Just "Just a Stub") Nothing (justMenu MenuButton2Mapping) btn3mapa <- actionNewAndRegister "BTN3MAPA" "Button 3 Mapping" (Just "Just a Stub") Nothing (justMenu MenuButton3Mapping) antialiasbmpa <- actionNewAndRegister "ANTIALIASBMPA" "Antialiased Bitmaps" (Just "Just a Stub") Nothing (justMenu MenuAntialiasedBitmaps) prgrsbkga <- actionNewAndRegister "PRGRSBKGA" "Progressive Backgrounds" (Just "Just a Stub") Nothing (justMenu MenuProgressiveBackgrounds) prntpprulea <- actionNewAndRegister "PRNTPPRULEA" "Print Paper Ruling" (Just "Just a Stub") Nothing (justMenu MenuPrintPaperRuling) lfthndscrbra <- actionNewAndRegister "LFTHNDSCRBRA" "Left-Handed Scrollbar" (Just "Just a Stub") Nothing (justMenu MenuLeftHandedScrollbar) shrtnmenua <- actionNewAndRegister "SHRTNMENUA" "Shorten Menus" (Just "Just a Stub") Nothing (justMenu MenuShortenMenus) autosaveprefa <- actionNewAndRegister "AUTOSAVEPREFA" "Auto-Save Preferences" (Just "Just a Stub") Nothing (justMenu MenuAutoSavePreferences) saveprefa <- actionNewAndRegister "SAVEPREFA" "Save Preferences" (Just "Just a Stub") Nothing (justMenu MenuSavePreferences) -- help menu abouta <- actionNewAndRegister "ABOUTA" "About" (Just "Just a Stub") Nothing (justMenu MenuAbout) -- others defaulta <- actionNewAndRegister "DEFAULTA" "Default" (Just "Default") (Just "mydefault") (justMenu MenuDefault) agr <- actionGroupNew "AGR" mapM_ (actionGroupAddAction agr) [fma,ema,vma,jma,tma,oma,hma] mapM_ (actionGroupAddAction agr) [ undoa, redoa, cuta, copya, pastea, deletea ] -- actionGroupAddActionWithAccel agr undoa (Just "<control>z") mapM_ (\act -> actionGroupAddActionWithAccel agr act Nothing) [ newa, annpdfa, opena, savea, saveasa, recenta, printa, exporta, quita {- , netcopya, netpastea -} , fscra, zooma, zmina, zmouta, nrmsizea, pgwdtha, pgheighta, setzma , fstpagea, prvpagea, nxtpagea, lstpagea, shwlayera, hidlayera , hsplita, vsplita, delcvsa , newpgba, newpgaa, newpgea, delpga, newlyra, nextlayera, prevlayera, gotolayera, dellyra, ppsizea, ppclra , ppstya, apallpga, ldbkga, bkgscrshta, defppa, setdefppa , shpreca, rulera, clra, penopta , erasropta, hiltropta, txtfnta, defpena, defersra, defhiltra, deftxta , setdefopta, relauncha , dcrdcorea, ersrtipa, pghilta, mltpgvwa , mltpga, btn2mapa, btn3mapa, antialiasbmpa, prgrsbkga, prntpprulea , lfthndscrbra, shrtnmenua, autosaveprefa, saveprefa , abouta , defaulta ] actionGroupAddAction agr uxinputa actionGroupAddAction agr pressrsensa -- actionGroupAddRadioActions agr viewmods 0 (assignViewMode tref sref) actionGroupAddRadioActions agr viewmods 0 (const (return ())) actionGroupAddRadioActions agr pointmods 0 (assignPoint sref) actionGroupAddRadioActions agr penmods 0 (assignPenMode tref sref) actionGroupAddRadioActions agr colormods 0 (assignColor sref) let disabledActions = [ recenta, printa, exporta , cuta, copya, pastea, deletea , fscra, setzma , shwlayera, hidlayera , newpgea, {- delpga, -} ppsizea, ppclra , ppstya, apallpga, ldbkga, bkgscrshta, defppa, setdefppa , shpreca, rulera , erasropta, hiltropta, txtfnta, defpena, defersra, defhiltra, deftxta , setdefopta , dcrdcorea, ersrtipa, pghilta, mltpgvwa , mltpga, btn2mapa, btn3mapa, antialiasbmpa, prgrsbkga, prntpprulea , lfthndscrbra, shrtnmenua, autosaveprefa, saveprefa , abouta , defaulta ] enabledActions = [ opena, savea, saveasa, quita, fstpagea, prvpagea, nxtpagea, lstpagea , clra, penopta, zooma, nrmsizea, pgwdtha ] -- mapM_ (\x->actionSetSensitive x True) enabledActions mapM_ (\x->actionSetSensitive x False) disabledActions -- -- -- radio actions -- ui <- uiManagerNew uiManagerAddUiFromString ui uiDecl uiManagerInsertActionGroup ui agr 0 -- Just ra1 <- actionGroupGetAction agr "ONEPAGEA" -- Gtk.set (castToRadioAction ra1) [radioActionCurrentValue := 1] Just ra2 <- actionGroupGetAction agr "PENFINEA" Gtk.set (castToRadioAction ra2) [radioActionCurrentValue := 2] Just ra3 <- actionGroupGetAction agr "SELREGNA" actionSetSensitive ra3 True Just ra4 <- actionGroupGetAction agr "VERTSPA" actionSetSensitive ra4 False Just ra5 <- actionGroupGetAction agr "HANDA" actionSetSensitive ra5 False Just ra6 <- actionGroupGetAction agr "CONTA" actionSetSensitive ra6 True Just toolbar1 <- uiManagerGetWidget ui "/ui/toolbar1" toolbarSetStyle (castToToolbar toolbar1) ToolbarIcons Just toolbar2 <- uiManagerGetWidget ui "/ui/toolbar2" toolbarSetStyle (castToToolbar toolbar2) ToolbarIcons return ui -- | assignViewMode :: IORef (Await MyEvent (Iteratee MyEvent XournalStateIO ())) -> IORef HXournalState -> RadioAction -> IO () assignViewMode tref sref a = do st <- readIORef sref putStrLn "in assignmViewMode" printCanvasMode (getCurrentCanvasId st) (get currentCanvasInfo st) putStrLn "still in assignViewMode" viewModeToMyEvent a >>= bouncecallback tref sref -- | assignPenMode :: IORef (Await MyEvent (Iteratee MyEvent XournalStateIO ())) -> IORef HXournalState -> RadioAction -> IO () assignPenMode tref sref a = do v <- radioActionGetCurrentValue a let t = int2PenType v st <- readIORef sref case t of Left pm -> do let stNew = set (penType.penInfo) pm st writeIORef sref stNew bouncecallback tref sref ToViewAppendMode Right sm -> do let stNew = set (selectType.selectInfo) sm st writeIORef sref stNew bouncecallback tref sref ToSelectMode -- | assignColor :: IORef HXournalState -> RadioAction -> IO () assignColor sref a = do v <- radioActionGetCurrentValue a let c = int2Color v st <- readIORef sref let callback = get callBack st let stNew = set (penColor.currentTool.penInfo) c st writeIORef sref stNew callback (PenColorChanged c) -- | assignPoint :: IORef HXournalState -> RadioAction -> IO () assignPoint sref a = do v <- radioActionGetCurrentValue a st <- readIORef sref let ptype = get (penType.penInfo) st let w = int2Point ptype v let stNew = set (penWidth.currentTool.penInfo) w st let callback = get callBack st writeIORef sref stNew callback (PenWidthChanged w) -- | int2PenType :: Int -> Either PenType SelectType int2PenType 0 = Left PenWork int2PenType 1 = Left EraserWork int2PenType 2 = Left HighlighterWork int2PenType 3 = Left TextWork int2PenType 4 = Right SelectRegionWork int2PenType 5 = Right SelectRectangleWork int2PenType 6 = Right SelectVerticalSpaceWork int2PenType 7 = Right SelectHandToolWork int2PenType _ = error "No such pentype" -- | int2Point :: PenType -> Int -> Double int2Point PenWork 0 = predefined_veryfine int2Point PenWork 1 = predefined_fine int2Point PenWork 2 = predefined_medium int2Point PenWork 3 = predefined_thick int2Point PenWork 4 = predefined_verythick int2Point PenWork 5 = predefined_ultrathick int2Point HighlighterWork 0 = predefined_highlighter_veryfine int2Point HighlighterWork 1 = predefined_highlighter_fine int2Point HighlighterWork 2 = predefined_highlighter_medium int2Point HighlighterWork 3 = predefined_highlighter_thick int2Point HighlighterWork 4 = predefined_highlighter_verythick int2Point HighlighterWork 5 = predefined_highlighter_ultrathick int2Point EraserWork 0 = predefined_eraser_veryfine int2Point EraserWork 1 = predefined_eraser_fine int2Point EraserWork 2 = predefined_eraser_medium int2Point EraserWork 3 = predefined_eraser_thick int2Point EraserWork 4 = predefined_eraser_verythick int2Point EraserWork 5 = predefined_eraser_ultrathick int2Point TextWork 0 = predefined_veryfine int2Point TextWork 1 = predefined_fine int2Point TextWork 2 = predefined_medium int2Point TextWork 3 = predefined_thick int2Point TextWork 4 = predefined_verythick int2Point TextWork 5 = predefined_ultrathick int2Point _ _ = error "No such point" -- | int2Color :: Int -> PenColor int2Color 0 = ColorBlack int2Color 1 = ColorBlue int2Color 2 = ColorRed int2Color 3 = ColorGreen int2Color 4 = ColorGray int2Color 5 = ColorLightBlue int2Color 6 = ColorLightGreen int2Color 7 = ColorMagenta int2Color 8 = ColorOrange int2Color 9 = ColorYellow int2Color 10 = ColorWhite int2Color _ = error "No such color"
wavewave/hxournal
lib/Application/HXournal/GUI/Menu.hs
bsd-2-clause
34,087
0
17
8,944
6,158
3,087
3,071
365
2
{-# LANGUAGE PackageImports #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PolyKinds #-} module Propellor.Property ( -- * Property combinators requires , before , onChange , onChangeFlagOnFail , flagFile , flagFile' , check , fallback , revert -- * Property descriptions , describe , (==>) -- * Constructing properties , Propellor , property , property' , OuterMetaTypesWitness , ensureProperty , pickOS , withOS , unsupportedOS , unsupportedOS' , makeChange , noChange , doNothing , endAction -- * Property result checking , UncheckedProperty , unchecked , changesFile , changesFileContent , isNewerThan , checkResult , Checkable , assume ) where import System.FilePath import Control.Monad import Data.Monoid import Control.Monad.IfElse import "mtl" Control.Monad.RWS.Strict import System.Posix.Files import qualified Data.Hash.MD5 as MD5 import Data.List import Control.Applicative import Prelude import Propellor.Types import Propellor.Types.Core import Propellor.Types.ResultCheck import Propellor.Types.MetaTypes import Propellor.Types.Singletons import Propellor.Info import Propellor.EnsureProperty import Utility.Exception import Utility.Monad import Utility.Misc import Utility.Directory -- | Makes a perhaps non-idempotent Property be idempotent by using a flag -- file to indicate whether it has run before. -- Use with caution. flagFile :: Property i -> FilePath -> Property i flagFile p = flagFile' p . return flagFile' :: Property i -> IO FilePath -> Property i flagFile' p getflagfile = adjustPropertySatisfy p $ \satisfy -> do flagfile <- liftIO getflagfile go satisfy flagfile =<< liftIO (doesFileExist flagfile) where go _ _ True = return NoChange go satisfy flagfile False = do r <- satisfy when (r == MadeChange) $ liftIO $ unlessM (doesFileExist flagfile) $ do createDirectoryIfMissing True (takeDirectory flagfile) writeFile flagfile "" return r -- | Indicates that the first property depends on the second, -- so before the first is ensured, the second must be ensured. -- -- The combined property uses the description of the first property. requires :: Combines x y => x -> y -> CombinedType x y requires = combineWith -- Run action of y, then x (flip (<>)) -- When reverting, run in reverse order. (<>) -- | Combines together two properties, resulting in one property -- that ensures the first, and if the first succeeds, ensures the second. -- -- The combined property uses the description of the first property. before :: Combines x y => x -> y -> CombinedType x y before = combineWith -- Run action of x, then y (<>) -- When reverting, run in reverse order. (flip (<>)) -- | Whenever a change has to be made for a Property, causes a hook -- Property to also be run, but not otherwise. onChange :: (Combines x y) => x -> y -> CombinedType x y onChange = combineWith combiner revertcombiner where combiner (Just p) (Just hook) = Just $ do r <- p case r of MadeChange -> do r' <- hook return $ r <> r' _ -> return r combiner (Just p) Nothing = Just p combiner Nothing _ = Nothing revertcombiner = (<>) -- | Same as `onChange` except that if property y fails, a flag file -- is generated. On next run, if the flag file is present, property y -- is executed even if property x doesn't change. -- -- With `onChange`, if y fails, the property x `onChange` y returns -- `FailedChange`. But if this property is applied again, it returns -- `NoChange`. This behavior can cause trouble... onChangeFlagOnFail :: (Combines x y) => FilePath -> x -> y -> CombinedType x y onChangeFlagOnFail flagfile = combineWith combiner revertcombiner where combiner (Just s1) s2 = Just $ do r1 <- s1 case r1 of MadeChange -> flagFailed s2 _ -> ifM (liftIO $ doesFileExist flagfile) ( flagFailed s2 , return r1 ) combiner Nothing _ = Nothing revertcombiner = (<>) flagFailed (Just s) = do r <- s liftIO $ case r of FailedChange -> createFlagFile _ -> removeFlagFile return r flagFailed Nothing = return NoChange createFlagFile = unlessM (doesFileExist flagfile) $ do createDirectoryIfMissing True (takeDirectory flagfile) writeFile flagfile "" removeFlagFile = whenM (doesFileExist flagfile) $ removeFile flagfile -- | Changes the description of a property. describe :: IsProp p => p -> Desc -> p describe = setDesc -- | Alias for @flip describe@ (==>) :: IsProp (Property i) => Desc -> Property i -> Property i (==>) = flip describe infixl 1 ==> -- | Tries the first property, but if it fails to work, instead uses -- the second. fallback :: (Combines p1 p2) => p1 -> p2 -> CombinedType p1 p2 fallback = combineWith combiner revertcombiner where combiner (Just a1) (Just a2) = Just $ do r <- a1 if r == FailedChange then a2 else return r combiner (Just a1) Nothing = Just a1 combiner Nothing _ = Nothing revertcombiner = (<>) -- | Indicates that a Property may change a particular file. When the file -- is modified in any way (including changing its permissions or mtime), -- the property will return MadeChange instead of NoChange. changesFile :: Checkable p i => p i -> FilePath -> Property i changesFile p f = checkResult getstat comparestat p where getstat = catchMaybeIO $ getSymbolicLinkStatus f comparestat oldstat = do newstat <- getstat return $ if samestat oldstat newstat then NoChange else MadeChange samestat Nothing Nothing = True samestat (Just a) (Just b) = and -- everything except for atime [ deviceID a == deviceID b , fileID a == fileID b , fileMode a == fileMode b , fileOwner a == fileOwner b , fileGroup a == fileGroup b , specialDeviceID a == specialDeviceID b , fileSize a == fileSize b , modificationTimeHiRes a == modificationTimeHiRes b , isBlockDevice a == isBlockDevice b , isCharacterDevice a == isCharacterDevice b , isNamedPipe a == isNamedPipe b , isRegularFile a == isRegularFile b , isDirectory a == isDirectory b , isSymbolicLink a == isSymbolicLink b , isSocket a == isSocket b ] samestat _ _ = False -- | Like `changesFile`, but compares the content of the file. -- Changes to mtime etc that do not change file content are treated as -- NoChange. changesFileContent :: Checkable p i => p i -> FilePath -> Property i changesFileContent p f = checkResult getmd5 comparemd5 p where getmd5 = catchMaybeIO $ MD5.md5 . MD5.Str <$> readFileStrict f comparemd5 oldmd5 = do newmd5 <- getmd5 return $ if oldmd5 == newmd5 then NoChange else MadeChange -- | Determines if the first file is newer than the second file. -- -- This can be used with `check` to only run a command when a file -- has changed. -- -- > check ("/etc/aliases" `isNewerThan` "/etc/aliases.db") -- > (cmdProperty "newaliases" [] `assume` MadeChange) -- updates aliases.db -- -- Or it can be used with `checkResult` to test if a command made a change. -- -- > checkResult (return ()) -- > (\_ -> "/etc/aliases.db" `isNewerThan` "/etc/aliases") -- > (cmdProperty "newaliases" []) -- -- (If one of the files does not exist, the file that does exist is -- considered to be the newer of the two.) isNewerThan :: FilePath -> FilePath -> IO Bool isNewerThan x y = do mx <- mtime x my <- mtime y return (mx > my) where mtime f = catchMaybeIO $ modificationTimeHiRes <$> getFileStatus f -- | Picks one of the two input properties to use, -- depending on the targeted OS. -- -- If both input properties support the targeted OS, then the -- first will be used. -- -- The resulting property will use the description of the first property -- no matter which property is used in the end. So, it's often a good -- idea to change the description to something clearer. -- -- For example: -- -- > upgraded :: Property (DebianLike + FreeBSD) -- > upgraded = (Apt.upgraded `pickOS` Pkg.upgraded) -- > `describe` "OS upgraded" -- -- If neither input property supports the targeted OS, calls -- `unsupportedOS`. Using the example above on a Fedora system would -- fail that way. pickOS :: ( SingKind ('KProxy :: KProxy ka) , SingKind ('KProxy :: KProxy kb) , DemoteRep ('KProxy :: KProxy ka) ~ [MetaType] , DemoteRep ('KProxy :: KProxy kb) ~ [MetaType] , SingI c -- Would be nice to have this constraint, but -- union will not generate metatypes lists with the same -- order of OS's as is used everywhere else. So, -- would need a type-level sort. --, Union a b ~ c ) => Property (MetaTypes (a :: ka)) -> Property (MetaTypes (b :: kb)) -> Property (MetaTypes c) pickOS a b = c `addChildren` [toChildProperty a, toChildProperty b] where -- This use of getSatisfy is safe, because both a and b -- are added as children, so their info will propigate. c = withOS (getDesc a) $ \_ o -> if matching o a then maybe (pure NoChange) id (getSatisfy a) else if matching o b then maybe (pure NoChange) id (getSatisfy b) else unsupportedOS' matching Nothing _ = False matching (Just o) p = Targeting (systemToTargetOS o) `elem` fromSing (proptype p) proptype (Property t _ _ _ _) = t -- | Makes a property that is satisfied differently depending on specifics -- of the host's operating system. -- -- > myproperty :: Property Debian -- > myproperty = withOS "foo installed" $ \w o -> case o of -- > (Just (System (Debian kernel (Stable release)) arch)) -> ensureProperty w ... -- > (Just (System (Debian kernel suite) arch)) -> ensureProperty w ... -- > _ -> unsupportedOS' -- -- Note that the operating system specifics may not be declared for all hosts, -- which is where Nothing comes in. withOS :: (SingI metatypes) => Desc -> (OuterMetaTypesWitness '[] -> Maybe System -> Propellor Result) -> Property (MetaTypes metatypes) withOS desc a = property desc $ a dummyoutermetatypes =<< getOS where -- Using this dummy value allows ensureProperty to be used -- even though the inner property probably doesn't target everything -- that the outer withOS property targets. dummyoutermetatypes :: OuterMetaTypesWitness ('[]) dummyoutermetatypes = OuterMetaTypesWitness sing -- | A property that always fails with an unsupported OS error. unsupportedOS :: Property UnixLike unsupportedOS = property "unsupportedOS" unsupportedOS' -- | Throws an error, for use in `withOS` when a property is lacking -- support for an OS. unsupportedOS' :: Propellor Result unsupportedOS' = go =<< getOS where go Nothing = error "Unknown host OS is not supported by this property." go (Just o) = error $ "This property is not implemented for " ++ show o -- | Undoes the effect of a RevertableProperty. revert :: RevertableProperty setup undo -> RevertableProperty undo setup revert (RevertableProperty p1 p2) = RevertableProperty p2 p1 makeChange :: IO () -> Propellor Result makeChange a = liftIO a >> return MadeChange noChange :: Propellor Result noChange = return NoChange -- | A no-op property. -- -- This is the same as `mempty` from the `Monoid` instance. doNothing :: SingI t => Property (MetaTypes t) doNothing = mempty -- | Registers an action that should be run at the very end, after -- propellor has checks all the properties of a host. endAction :: Desc -> (Result -> Propellor Result) -> Propellor () endAction desc a = tell [EndAction desc a]
ArchiveTeam/glowing-computing-machine
src/Propellor/Property.hs
bsd-2-clause
11,367
91
16
2,230
2,517
1,329
1,188
222
5
{-# LANGUAGE ScopedTypeVariables #-} {-| Module: HaskHOL.Lib.Meson Copyright: (c) Evan Austin 2015 LICENSE: BSD3 Maintainer: [email protected] Stability: unstable Portability: unknown -} module HaskHOL.Lib.Meson ( tacGEN_MESON , tacASM_MESON , tacASM_MESON_NIL , tacMESON , tacMESON_NIL , ruleMESON , ruleMESON_NIL ) where import HaskHOL.Core import qualified HaskHOL.Core.Kernel as K (typeOf) import HaskHOL.Lib.Bool import HaskHOL.Lib.Canon import HaskHOL.Lib.Classic import HaskHOL.Lib.Equal import HaskHOL.Lib.Theorems import HaskHOL.Lib.Simp import HaskHOL.Lib.DRule import HaskHOL.Lib.Tactics import HaskHOL.Lib.Trivia -- AST for negation normal form terms data FOLTerm = FVar Int | FNApp Int [FOLTerm] deriving (Eq, Ord) type FOLAtom = (Int, [FOLTerm]) -- Type of a MESON proof tree data FOLGoal = Subgoal FOLAtom [FOLGoal] (Int, HOLThm) Int [(FOLTerm, Int)] deriving Eq type FOLTermEnv = [(FOLTerm, Int)] type Tup = (FOLTermEnv, Int, Int) type Rule = (Int, [(([FOLAtom], FOLAtom), (Int, HOLThm))]) type State = ((FOLAtom, [Rule]), Tup) data MesonErr = Fail | Cut deriving (Show, Typeable) instance Exception MesonErr -- Cacheable continuations. type ContMem1 cls thry = (FOLGoal, Tup) -> HOL cls thry (FOLGoal, Tup) type ContMemMany cls thry = ([FOLGoal], Tup) -> HOL cls thry (FOLGoal, Tup) data DeCont1 = Return1 | Base DeCont | Goals11 DeCont [Rule] Int [(FOLAtom, [Rule])] | Cache1 DeCont1 deriving Eq data DeCont = TopRec FOLTermEnv Int FOLTermEnv FOLAtom (Int, HOLThm) DeCont1 Int | Goals1 DeCont [Rule] Int [(FOLAtom, [Rule])] Int | Goals2 DeCont [FOLGoal] | Goals3 Int Int DeCont [Rule] Int [(FOLAtom, [Rule])] | Goals4 Int Int Int DeCont [FOLGoal] | Goals5 DeCont FOLGoal | CacheMany DeCont deriving Eq cachecont :: DeCont1 -> DeCont1 cachecont = Cache1 cacheconts :: DeCont -> DeCont cacheconts = CacheMany -- local MESON state type MesonState = HOLRef MesonRefs data MesonRefs = MesonRefs { infs :: !Int , cutIn :: !Int , vstore :: ![(HOLTerm, Int)] , gstore :: ![(HOLTerm, Int)] , vcounter :: !Int , cstore :: ![(HOLTerm, Int)] , ccounter :: !Int , memory :: ![((Int, HOLTerm), HOLThm)] , cont1 :: ![(DeCont1, [(FOLGoal, Tup)])] , cont2 :: ![(DeCont, [([FOLGoal], Tup)])] } initializeMeson :: TriviaCtxt thry => HOL cls thry MesonRefs initializeMeson = do falseTm <- serve [trivia| F |] return $! MesonRefs 0 1 [] [] 0 [(falseTm, 1)] 2 [] [] [] -- meson settings mesonOffInc, mesonSkew, mesonSplitLimit :: Int mesonOffInc = 10000 mesonSkew = 3 mesonSplitLimit = 8 -- partitioning utility qpartition :: forall a. Eq a => (a -> Bool) -> [a] -> [a] -> ([a], [a]) qpartition p m l = tryd ([], l) $ partRec l where partRec :: [a] -> Catch ([a], [a]) partRec [] = fail' "partRec" partRec lst@(h:t) | lst == m = fail' "partRec" | p h = (do (yes, no) <- partRec t return (h:yes, no)) <|> return ([h], t) | otherwise = (do (yes, no) <- partRec t return (yes, h:no)) <?> "partRec" -- nnf substitution functions folSubst :: [(FOLTerm, Int)] -> FOLTerm -> FOLTerm folSubst theta tm@(FVar v) = revAssocd v theta tm folSubst theta (FNApp f args) = FNApp f $ map (folSubst theta) args folInst :: [(FOLTerm, Int)] -> FOLAtom -> FOLAtom folInst theta (p, args) = (p, map (folSubst theta) args) folSubstBump :: Int -> [(FOLTerm, Int)] -> FOLTerm -> FOLTerm folSubstBump offset theta tm@(FVar v) | v < mesonOffInc = let v' = v + offset in revAssocd v' theta $ FVar v' | otherwise = revAssocd v theta tm folSubstBump offset theta (FNApp f args) = FNApp f $! map (folSubstBump offset theta) args folInstBump :: Int -> [(FOLTerm, Int)] -> FOLAtom -> FOLAtom folInstBump offset theta (p, args) = let args' = map (folSubstBump offset theta) args in (p, args') -- main nnf unification functions isTriv :: MonadThrow m => [(FOLTerm, Int)] -> Int -> FOLTerm -> m Bool isTriv env x (FVar y) | y == x = return True | otherwise = case runCatch $ revAssoc y env of Left{} -> return False Right t' -> isTriv env x t' isTriv env x (FNApp _ args) = do conds <- mapM (isTriv env x) args if or conds then fail' "isTriv: cyclic" else return False folUnify :: (MonadCatch m, MonadThrow m) => Int -> FOLTerm -> FOLTerm -> [(FOLTerm, Int)] -> m [(FOLTerm, Int)] folUnify offset (FNApp f fargs) (FNApp g gargs) sofar | f /= g = fail' "folUnify" | otherwise = foldr2M (folUnify offset) sofar fargs gargs folUnify offset tm1 (FVar x) sofar = case runCatch $ revAssoc x' sofar of Right tm2' -> folUnify 0 tm1 tm2' sofar Left{} -> do cond <- isTriv sofar x' tm1 <?> "folUnify: cyclic" return $! if cond then sofar else (tm1, x'):sofar where x' = x + offset folUnify offset (FVar x) tm2 sofar = case runCatch $ revAssoc x sofar of Right tm1' -> folUnify offset tm1' tm2 sofar Left{} -> do cond <- isTriv sofar x tm2' <?> "folUnify: cyclic" return $! if cond then sofar else (tm2', x):sofar where tm2' = folSubstBump offset [] tm2 -- test for nnf equality folEq :: [(FOLTerm, Int)] -> FOLTerm -> FOLTerm -> Bool folEq insts tm1 tm2 | tm1 == tm2 = True | otherwise = case (tm1, tm2) of (FNApp f fargs, FNApp g gargs) -> let conds = zipWith (folEq insts) fargs gargs in f == g && and conds (_, FVar x) -> case runCatch $ revAssoc x insts of Right tm2' -> folEq insts tm1 tm2' Left{} -> tryd False $ isTriv insts x tm1 (FVar x, _) -> case runCatch $ revAssoc x insts of Right tm1' -> folEq insts tm1' tm2 Left{} -> tryd False $ isTriv insts x tm2 folAtomEq :: [(FOLTerm, Int)] -> FOLAtom -> FOLAtom -> Bool folAtomEq insts (p1, args1) (p2, args2) | p1 /= p2 = False | otherwise = and $ zipWith (folEq insts) args1 args2 -- check ancestor list for repetition checkan :: MonadThrow m => FOLTermEnv -> FOLAtom -> [Rule] -> m [Rule] checkan insts (p, a) ancestors = let p' = negate p t' = (p', a) in case runCatch $ assoc p' ancestors of Left{} -> return ancestors Right ours -> if or $ map (folAtomEq insts t' . snd . fst) ours then fail' "checkan: loop" else return ancestors -- insert new goal's negation in ancestor clause, given refinement insertan :: BoolCtxt thry => FOLTermEnv -> FOLAtom -> [Rule] -> HOL cls thry [Rule] insertan insts (p, a) ancestors = let p' = negate p t' = (p', a) (ourancp, otheranc) = tryd ((p', []), ancestors) $ remove (\ (pr, _) -> pr == p') ancestors ouranc = snd ourancp in if or $ map (folAtomEq insts t' . snd . fst) ouranc then fail "insertan: loop" else do th <- thmTRUTH return ((p', (([], t'), (0, th)):ouranc):otheranc) -- apply a multi-level "graph" instantiation folSubstPartial :: [(FOLTerm, Int)] -> FOLTerm -> FOLTerm folSubstPartial insts tm@(FVar v) = case runCatch $ revAssoc v insts of Left{} -> tm Right t -> folSubstPartial insts t folSubstPartial insts (FNApp f args) = FNApp f $ map (folSubstPartial insts) args -- tease apart local and global instantiations. separateInsts2 :: Int -> FOLTermEnv -> FOLTermEnv -> (FOLTermEnv, FOLTermEnv) separateInsts2 offset old new = let (loc, glob) = qpartition (\ (_, v) -> offset <= v) old new in if glob == old then (map (first (folSubstPartial new)) loc, old) else (map (first (folSubstPartial new)) loc, map (first (folSubstPartial new)) glob) mkNegated :: FOLAtom -> FOLAtom mkNegated (p, a) = (negate p, a) mkContraposes :: Int -> HOLThm -> [FOLAtom] -> [FOLAtom] -> [(([FOLAtom], FOLAtom), (Int, HOLThm))] -> [(([FOLAtom], FOLAtom), (Int, HOLThm))] mkContraposes _ _ _ [] sofar = sofar mkContraposes n th used (h:t) sofar = let nw = ((map mkNegated (used ++ t), h), (n, th)) in mkContraposes (n + 1) th (used ++ [h]) t (nw:sofar) -- optimize set of clausesa optimizeRules :: [Rule] -> [Rule] optimizeRules = map (second optimizeClauseOrder) where optimizeClauseOrder = sort (\ ((l1, _), _) ((l2, _), _) -> length l1 <= length l2) convDISJ_AC :: TheoremsCtxt thry => Conversion cls thry convDISJ_AC = convAC thmDISJ_ACI convImp :: TriviaCtxt thry => Conversion cls thry convImp = convREWR convImp_pth where convImp_pth :: TriviaCtxt thry => HOL cls thry HOLThm convImp_pth = cacheProof "convImp_pth" ctxtTrivia $ ruleTAUT [txt| a \/ b <=> ~b ==> a |] convPush :: TriviaCtxt thry => Conversion cls thry convPush = convGEN_REWRITE convTOP_SWEEP [convPush_pth1, convPush_pth2] where convPush_pth1 :: TriviaCtxt thry => HOL cls thry HOLThm convPush_pth1 = cacheProof "convPush_pth1" ctxtTrivia $ ruleTAUT [txt| ~(a \/ b) <=> ~a /\ ~b |] convPush_pth2 :: TriviaCtxt thry => HOL cls thry HOLThm convPush_pth2 = cacheProof "convPush_pth2" ctxtTrivia $ ruleTAUT [txt| ~(~a) <=> a |] convPull :: TriviaCtxt thry => Conversion cls thry convPull = convGEN_REWRITE convDEPTH [convPull_pth] where convPull_pth :: TriviaCtxt thry => HOL cls thry HOLThm convPull_pth = cacheProof "convPull_pth" ctxtTrivia $ ruleTAUT [txt| ~a \/ ~b <=> ~(a /\ b) |] convImf :: TriviaCtxt thry => Conversion cls thry convImf = convREWR convImf_pth where convImf_pth :: TriviaCtxt thry => HOL cls thry HOLThm convImf_pth = cacheProof "convImf_pth" ctxtTrivia $ ruleTAUT [txt| ~p <=> p ==> F |] -- translate saved proof back to HOL holNegate :: HOLTerm -> HOL cls thry HOLTerm holNegate tm = (destNeg tm <|> mkNeg tm) <?> "holNegate" mergeInst :: (FOLTerm, Int) -> [(FOLTerm, Int)] -> [(FOLTerm, Int)] mergeInst (t, x) current = let t' = folSubst current t in (t', x) : current finishRule :: TriviaCtxt thry => HOLThm -> HOL cls thry HOLThm finishRule = ruleGEN_REWRITE id [finishRule_pth1, finishRule_pth2] where finishRule_pth1 :: TriviaCtxt thry => HOL cls thry HOLThm finishRule_pth1 = cacheProof "finishRule_pth1" ctxtTrivia $ ruleTAUT [txt| (~p ==> p) <=> p |] finishRule_pth2 :: TriviaCtxt thry => HOL cls thry HOLThm finishRule_pth2 = cacheProof "finishRule_pth2" ctxtTrivia $ ruleTAUT [txt| (p ==> ~p) <=> ~p |] -- create equality axioms convImpElim :: TriviaCtxt thry => Conversion cls thry convImpElim = convREWR convImpElim_pth where convImpElim_pth :: TriviaCtxt thry => HOL cls thry HOLThm convImpElim_pth = cacheProof "convImpElim_pth" ctxtTrivia $ ruleTAUT [txt| (a ==> b) <=> ~a \/ b |] ruleEqElim :: TriviaCtxt thry => HOLThm -> HOL cls thry HOLThm ruleEqElim = ruleMATCH_MP ruleEqElim_pth where ruleEqElim_pth :: TriviaCtxt thry => HOL cls thry HOLThm ruleEqElim_pth = cacheProof "ruleEqElim_pth" ctxtTrivia $ ruleTAUT [txt| (a <=> b) ==> b \/ ~a |] createEquivalenceAxioms :: TriviaCtxt thry => (HOLTerm, Int) -> HOL cls thry [HOLThm] createEquivalenceAxioms (eq, _) = (do ths@(th:_) <- sequence eqThms veqTm <- rator $ rator (concl th) tyins <- typeMatch_NIL (typeOf veqTm) (typeOf eq) mapM (primINST_TYPE_FULL tyins) ths) <?> "createEquivalenceAxioms" where eqThms :: TriviaCtxt thry => [HOL cls thry HOLThm] eqThms = cacheProofs ["eqThms1", "eqThms2"] ctxtTrivia . ruleCONJUNCTS $ prove [txt| (x:A = x) /\ (~(x:A = y) \/ ~(x = z) \/ (y = z)) |] (tacREWRITE_NIL `_THEN` tacASM_CASES [txt| x:A = y |] `_THEN` tacASM_REWRITE_NIL `_THEN` tacCONV (Conv ruleTAUT)) tmConsts :: HOLTerm -> [(HOLTerm, Int)] -> [(HOLTerm, Int)] tmConsts tm acc = let (fn, args) = stripComb tm in if null args then acc else foldr tmConsts (insert (fn, length args) acc) args fmConsts :: HOLTerm -> ([(HOLTerm, Int)], [(HOLTerm, Int)]) -> ([(HOLTerm, Int)], [(HOLTerm, Int)]) fmConsts (Forall _ x) acc = fmConsts x acc fmConsts (Exists _ x) acc = fmConsts x acc fmConsts (l :/\ r) acc = fmConsts l $ fmConsts r acc fmConsts (l :\/ r) acc = fmConsts l $ fmConsts r acc fmConsts (l :==> r) acc = fmConsts l $ fmConsts r acc fmConsts (Neg x) acc = fmConsts x acc fmConsts tm@(l := r) acc | K.typeOf l == tyBool = fmConsts r $ fmConsts l acc | otherwise = fmConstsBad tm acc fmConsts tm acc = fmConstsBad tm acc fmConstsBad :: HOLTerm -> ([(HOLTerm, Int)], [(HOLTerm, Int)]) -> ([(HOLTerm, Int)], [(HOLTerm, Int)]) fmConstsBad tm acc@(preds, funs) = let (p, args) = stripComb tm in if null args then acc else (insert (p, length args) preds, foldr tmConsts funs args) createCongruenceAxiom :: TriviaCtxt thry => Bool -> (HOLTerm, Int) -> HOL cls thry HOLThm createCongruenceAxiom pflag (tm, len) = (do (atys, _) <- splitListM destFunTy =<< typeOf tm (ctys, _) <- trySplitAt len atys largs <- mapM genVar ctys rargs <- mapM genVar ctys th1 <- primREFL tm ths <- mapM (primASSUME <=< uncurry mkEq) $ zip largs rargs th2 <- foldlM primMK_COMB th1 ths th3@(Thm asl _) <- if pflag then ruleEqElim th2 else return th2 foldrM (\ e th -> ruleCONV convImpElim $ ruleDISCH e th) th3 asl) <?> "createCongruenceAxiom" createEqualityAxioms :: TriviaCtxt thry => [HOLTerm] -> HOL cls thry [HOLThm] createEqualityAxioms tms = note "createEqualityAxioms" $ let (preds, funs) = foldr fmConsts ([], []) tms (eqs0, noneqs) = partition eqPred preds in if null eqs0 then return [] else do pcongs <- mapM (createCongruenceAxiom True) noneqs fcongs <- mapM (createCongruenceAxiom False) funs let (preds1, _) = foldr fmConsts ([], []) $ map concl (pcongs ++ fcongs) eqs1 = filter eqPred preds1 eqs = eqs0 `union` eqs1 equivs <- foldrM (\ x ys -> do xs <- createEquivalenceAxioms x return $ union xs ys) [] eqs return $! equivs ++ pcongs ++ fcongs where eqPred :: (HOLTerm, Int) -> Bool eqPred (Const "=" _, _) = True eqPred _ = False -- polymorph tactic grabConstants :: HOLTerm -> [HOLTerm] -> [HOLTerm] grabConstants (Forall _ bod) acc = grabConstants bod acc grabConstants (Exists _ bod) acc = grabConstants bod acc grabConstants (l :<=> r) acc = grabConstants r $ grabConstants l acc grabConstants (l :==> r) acc = grabConstants r $ grabConstants l acc grabConstants (l :/\ r) acc = grabConstants r $ grabConstants l acc grabConstants (l :\/ r) acc = grabConstants r $ grabConstants l acc grabConstants (Neg t) acc = grabConstants t acc grabConstants tm acc = findTerms isConst tm `union` acc matchConsts :: (HOLTerm, HOLTerm) -> HOL cls thry SubstTrip matchConsts (Const s1 ty1, Const s2 ty2) | s1 == s2 = typeMatch_NIL ty1 ty2 | otherwise = fail' "matchConsts: consts of different name" matchConsts _ = fail' "matchConsts" polymorph :: [HOLTerm] -> HOLThm -> HOL cls thry [HOLThm] polymorph mconsts th = let tvs = typeVarsInTerm (concl th) \\ (unions . map typeVarsInTerm $ hyp th) in if null tvs then return [th] else let pconsts = grabConstants (concl th) [] in do tyins <- mapFilterM matchConsts $ allpairs (,) pconsts mconsts tyins' <- mapM (`primINST_TYPE_FULL` th) tyins let ths' = setify' ((<=) `on` destThm) (==) tyins' if null ths' then printDebug "No useful-looking instantiation of lemma" $ return [th] else return ths' polymorphAll :: [HOLTerm] -> [HOLThm] -> [HOLThm] -> HOL cls thry [HOLThm] polymorphAll _ [] acc = return acc polymorphAll mconsts (th:ths) acc = do ths' <- polymorph mconsts th let mconsts' = foldr (grabConstants . concl) mconsts ths' polymorphAll mconsts' ths (union' (==) ths' acc) tacPOLY_ASSUME :: BoolCtxt thry => [HOLThm] -> Tactic cls thry tacPOLY_ASSUME ths gl@(Goal asl _) = let mconsts = foldr (grabConstants . concl . snd) [] asl in do ths' <- polymorphAll mconsts ths [] _MAP_EVERY tacASSUME ths' gl tacCONJUNCTS_THEN' :: BoolCtxt thry => ThmTactic HOLThm cls thry -> ThmTactic HOLThm cls thry tacCONJUNCTS_THEN' ttac cth gl = do cthl <- ruleCONJUNCT1 cth cthr <- ruleCONJUNCT2 cth (ttac cthl `_THEN` ttac cthr) gl tacPURE_MESON :: TriviaCtxt thry => MesonState -> Int -> Int -> Int -> Tactic cls thry tacPURE_MESON ref minVal maxVal inc goal = do resetVars resetConsts flushCaches (_FIRST_ASSUM tacCONTR `_ORELSE` (\ g@(Goal asl _) -> do th <- simpleMesonRefute $ map snd asl tacACCEPT th g)) goal where simpleMesonRefute :: TriviaCtxt thry => [HOLThm] -> HOL cls thry HOLThm simpleMesonRefute ths = do dcutin <- liftM cutIn $ readHOLRef ref clearContraposCache modifyHOLRef ref $ \ st -> st { infs = 0 } ths' <- liftM (ths ++) . createEqualityAxioms $ map concl ths rules <- liftM optimizeRules $ folOfHOLClauses ths' (proof, (insts, _, _)) <- solveGoal rules inc (1, []) modifyHOLRef ref $ \ st -> st { cutIn = dcutin } mesonToHOL insts proof solveGoal :: BoolCtxt thry => [Rule] -> Int -> FOLAtom -> HOL cls thry (FOLGoal, Tup) solveGoal rules incsize g = solve minVal (g,[]) where solve :: BoolCtxt thry => Int -> (FOLAtom, [Rule]) -> HOL cls thry (FOLGoal, Tup) solve n gl | n > maxVal = fail "solveGoal: too deep" | otherwise = (do is <- liftM infs $ readHOLRef ref printDebug (show is ++ "..") $ return () gi <- expandGoal rules gl 100000 n Return1 is' <- liftM infs $ readHOLRef ref printDebug ("solved at " ++ show is') $ return () return gi) <|> solve (n + incsize) gl expandGoal :: BoolCtxt thry => [Rule] -> (FOLAtom, [Rule]) -> Int -> Int -> DeCont1 -> HOL cls thry (FOLGoal, Tup) expandGoal rules g maxdep maxinf = expandGoalRec rules maxdep (g, ([], 2 * mesonOffInc, maxinf)) expandGoalRec :: BoolCtxt thry => [Rule] -> Int -> State -> DeCont1 -> HOL cls thry (FOLGoal, Tup) expandGoalRec rules depth state@((g, _), (insts, offset, size)) cont | depth < 0 = fail "expandGoal: too deep" | otherwise = mesonExpand rules state (\ apprule newstate@(_, (pinsts, _, _)) -> let cont' = cacheconts $ TopRec insts offset pinsts g apprule cont size in expandGoals rules (depth - 1) newstate cont') expandGoals :: BoolCtxt thry => [Rule] -> Int -> ([(FOLAtom, [Rule])], Tup) -> DeCont -> HOL cls thry (FOLGoal, Tup) expandGoals _ _ ([], tup) cont = deCont cont ([], tup) expandGoals rules depth ([g], tup) cont = expandGoalRec rules depth (g, tup) $ Base cont expandGoals rules depth (gl@(g:gs), tup@(insts, offset, size)) cont = do dcutin <- liftM cutIn $ readHOLRef ref if size >= dcutin then let lsize = size `div` mesonSkew rsize = size - lsize in do (lgoals, rgoals) <- trySplitAt (length gl `div` 2) gl (let cont' = cacheconts $ Goals1 cont rules depth rgoals rsize in expandGoals rules depth (lgoals, (insts, offset, lsize)) cont') <|> (let cont' = cacheconts $ Goals3 rsize lsize cont rules depth lgoals in expandGoals rules depth (rgoals, (insts, offset, lsize)) cont') else let cont' = cachecont $ Goals11 cont rules depth gs in expandGoalRec rules depth (g, tup) cont' mesonExpand :: forall cls thry. BoolCtxt thry => [Rule] -> State -> ((Int, HOLThm) -> ([(FOLAtom, [Rule])], Tup) -> HOL cls thry (FOLGoal, Tup)) -> HOL cls thry (FOLGoal, Tup) mesonExpand rules ((g, ancestors), tup@(insts, offset, size)) cont = let pr = fst g in do newancestors <- insertan insts g ancestors let newstate = ((g, newancestors), tup) (if pr > 0 then throwM Fail else case lookup pr ancestors of Nothing -> throwM Fail Just arules -> mesonExpandCont 0 arules newstate cont) `catch` errCase pr newstate where errCase :: Int -> State -> MesonErr -> HOL cls thry (FOLGoal, Tup) errCase _ _ Cut = fail "mesonExpand" errCase pr newstate Fail = do prule <- assoc pr rules let crules = filter (\ ((h, _), _) -> length h <= size) prule mesonExpandCont offset crules newstate cont mesonExpandCont :: Int -> [(([FOLAtom], FOLAtom), b)] -> State -> (b -> ([(FOLAtom, [Rule])], Tup) -> HOL cls thry (FOLGoal, Tup)) -> HOL cls thry (FOLGoal, Tup) mesonExpandCont loffset rules state cont = tryFind (\ r -> cont (snd r) =<< mesonSingleExpand loffset r state) rules <|> throwM Fail mesonSingleExpand :: Int -> (([FOLAtom], FOLAtom), b) -> State -> HOL cls thry ([(FOLAtom, [Rule])], Tup) mesonSingleExpand loffset rule (((_, ftms), ancestors), (insts, offset, size)) = let ((hyps, conc), _) = rule in do allEnv <- foldl2M (\ c a b -> folUnify loffset a b c) insts ftms $ snd conc let (loc, glob) = separateInsts2 offset insts allEnv mkIHyp h = let h' = folInstBump offset loc h in do an <- checkan insts h' ancestors return (h', an) newhyps <- mapM mkIHyp hyps modifyHOLRef ref $ \ st -> st { infs = 1 + infs st } return (newhyps, (glob, offset + mesonOffInc, size-length hyps)) flushCaches :: HOL cls thry () flushCaches = modifyHOLRef ref $ \ st -> st { cont1 = [], cont2 = [] } replaceMem1 :: DeCont1 -> [(FOLGoal, Tup)] -> HOL cls thry () replaceMem1 f m = modifyHOLRef ref $ \ st -> st { cont1 = replaceMemRec $ cont1 st } where replaceMemRec [] = [(f, m)] replaceMemRec (x:xs) | fst x == f = (f, m) : xs | otherwise = x : replaceMemRec xs replaceMem :: DeCont -> [([FOLGoal], Tup)] -> HOL cls thry () replaceMem f m = modifyHOLRef ref $ \ st -> st { cont2 = replaceMemRec $ cont2 st } where replaceMemRec [] = [(f, m)] replaceMemRec (x:xs) | fst x == f = (f, m) : xs | otherwise = x : replaceMemRec xs deCont1 :: BoolCtxt thry => DeCont1 -> ContMem1 cls thry deCont1 Return1 x = return x deCont1 (Base cont) (g', stup) = deCont cont ([g'], stup) deCont1 (Goals11 cont rules depth gs) (g', stup) = let cont' = cacheconts $ Goals5 cont g' in expandGoals rules depth (gs, stup) cont' deCont1 (Cache1 cont) input@(_, (insts, _, size)) = do cache <- liftM cont1 $ readHOLRef ref case lookup cont cache of Nothing -> do modifyHOLRef ref $ \ st -> st { cont1 = [(cont, [input])] } deCont1 cont input Just m -> if any (\ (_, (insts', _, size')) -> insts == insts' && (size <= size')) m then fail "cacheconts" else do replaceMem1 cont m deCont1 cont input deCont :: BoolCtxt thry => DeCont -> ContMemMany cls thry deCont (TopRec insts offset pinsts g apprule cont size) (gs, (newinsts, newoffset, newsize)) = let (locin, globin) = separateInsts2 offset pinsts newinsts g' = Subgoal g gs apprule offset locin in if globin == insts && null gs then deCont1 cont (g', (globin, newoffset, size)) <|> throwM Cut else deCont1 cont (g', (globin, newoffset, newsize)) <|> throwM Fail deCont (Goals1 cont rules depth rgoals rsize) (lg', (i, off, n)) = let cont' = cacheconts $ Goals2 cont lg' in expandGoals rules depth (rgoals, (i, off, n + rsize)) cont' deCont (Goals2 cont lg') (rg', ztup) = deCont cont (lg' ++ rg', ztup) deCont (Goals3 rsize lsize cont rules depth lgoals) (rg', (i, off, n)) = let cont' = cacheconts $ Goals4 n rsize lsize cont rg' in expandGoals rules depth (lgoals, (i, off, n + rsize)) cont' deCont (Goals4 n rsize lsize cont rg') (lg', ztup@(_, _, fsize)) = if n + rsize <= lsize + fsize then fail "repetition of demigoal pair" else deCont cont (lg' ++ rg', ztup) deCont (Goals5 cont g') (gs', ftup) = deCont cont (g':gs', ftup) deCont (CacheMany cont) input@(_, (insts, _, size)) = do cache <- liftM cont2 $ readHOLRef ref case lookup cont cache of Nothing -> do modifyHOLRef ref $ \ st -> st { cont2 = [(cont, [input])] } deCont cont input Just m -> if any (\ (_, (insts', _, size')) -> insts == insts' && (size <= size')) m then fail "cacheconts" else do replaceMem cont m deCont cont input clearContraposCache :: HOL cls thry () clearContraposCache = modifyHOLRef ref $ \ st -> st { memory = [] } makeHOLContrapos :: TriviaCtxt thry => Int -> HOLThm -> HOL cls thry HOLThm makeHOLContrapos n th = let tm = concl th key = (n, tm) in do m <- liftM memory $ readHOLRef ref (assoc key m) <|> (if n < 0 then ruleCONV (convPull `_THEN` convImf) th else let djs = disjuncts tm in do acth <- if n == 0 then return th else do (ldjs, rdj:rdjs) <- trySplitAt n djs let ndjs = rdj : (ldjs ++ rdjs) th1 <- runConv convDISJ_AC . mkEq tm $ listMkDisj ndjs primEQ_MP th1 th fth <- if length djs == 1 then return acth else ruleCONV (convImp `_THEN` convPush) acth modifyHOLRef ref $ \ st -> st { memory = (key, fth) : m } return fth) resetVars :: HOL cls thry () resetVars = modifyHOLRef ref $ \ st -> st { vstore = [], gstore = [], vcounter = 0 } resetConsts :: TriviaCtxt thry => HOL cls thry () resetConsts = do falseTm <- serve [trivia| F |] modifyHOLRef ref $ \ st -> st { cstore = [(falseTm, 1)], ccounter = 2 } incVCounter :: HOL cls thry Int incVCounter = do n <- liftM vcounter $ readHOLRef ref let m = n + 1 if m >= mesonOffInc then fail "incVCounter: too many variables" else do modifyHOLRef ref $ \ st -> st { vcounter = m } return n mesonToHOL :: TriviaCtxt thry => [(FOLTerm, Int)] -> FOLGoal -> HOL cls thry HOLThm mesonToHOL insts (Subgoal g gs (n, th) _ locin) = let newInsts = foldr mergeInst insts locin g' = folInst newInsts g in do holG <- holOfLiteral g' ths <- mapM (mesonToHOL newInsts) gs truthTh <- thmTRUTH hth <- if th == truthTh then primASSUME holG else do cth <- makeHOLContrapos n th if null ths then return cth else ruleMATCH_MP cth $ foldr1M ruleCONJ ths ith <- rulePART_MATCH return hth holG tm <- holNegate $ concl ith finishRule =<< ruleDISCH tm ith folOfHOLClause :: HOLThm -> HOL cls thry [(([FOLAtom], FOLAtom), (Int, HOLThm))] folOfHOLClause th = let lconsts = catFrees $ hyp th tm = concl th hlits = disjuncts tm in do flits <- mapM (folOfLiteral [] lconsts) hlits let basics = mkContraposes 0 th [] flits [] return $ if all (\ (p, _) -> p < 0) flits then ((map mkNegated flits, (1, [])), (-1, th)):basics else basics folOfHOLClauses :: [HOLThm] -> HOL cls thry [Rule] folOfHOLClauses thms = do rawrules <- foldrM (\ x ys -> do xs <- folOfHOLClause x return $! union xs ys) [] thms let prs = setify $ map (fst . snd . fst) rawrules prules = map (\ t -> (t, filter ((== t) . fst . snd . fst) rawrules)) prs srules = sort (\ (p, _) (q, _) -> abs p <= abs q) prules return srules holOfTerm :: FOLTerm -> HOL cls thry HOLTerm holOfTerm (FVar v) = holOfVar v holOfTerm (FNApp f args) = do f' <- holOfConst f args' <- mapM holOfTerm args listMkComb f' args' folOfTerm :: [HOLTerm] -> [HOLTerm] -> HOLTerm -> HOL cls thry FOLTerm folOfTerm env consts tm = if isVar tm && (tm `notElem` consts) then liftM FVar $ folOfVar tm else let (f, args) = stripComb tm in if f `elem` env then fail "folOfTerm: higher order" else do ff <- folOfConst f args' <- mapM (folOfTerm env consts) args return $! FNApp ff args' holOfAtom :: FOLAtom -> HOL cls thry HOLTerm holOfAtom (p, args) = do p' <- holOfConst p args' <- mapM holOfTerm args listMkComb p' args' folOfAtom :: [HOLTerm] -> [HOLTerm] -> HOLTerm -> HOL cls thry FOLAtom folOfAtom env consts tm = let (f, args) = stripComb tm in if f `elem` env then fail "folOfAtom: higher order" else do ff <- folOfConst f args' <- mapM (folOfTerm env consts) args return (ff, args') holOfLiteral :: FOLAtom -> HOL cls thry HOLTerm holOfLiteral fa@(p, args) | p < 0 = mkNeg $ holOfAtom (negate p, args) | otherwise = holOfAtom fa folOfLiteral :: [HOLTerm] -> [HOLTerm] -> HOLTerm -> HOL cls thry FOLAtom folOfLiteral env consts (Neg tm') = do (p, a) <- folOfAtom env consts tm' return (negate p, a) folOfLiteral env consts tm = folOfAtom env consts tm holOfConst :: Int -> HOL cls thry HOLTerm holOfConst c = note "holOfConst" $ do cs <- liftM cstore $ readHOLRef ref revAssoc c cs folOfConst :: HOLTerm -> HOL cls thry Int folOfConst c = note "folOfConst" $ do currentconsts <- liftM cstore $ readHOLRef ref (assoc c currentconsts) <|> (do n <- liftM ccounter $ readHOLRef ref modifyHOLRef ref $ \ st -> st { ccounter = n + 1, cstore = (c, n):currentconsts } return n) holOfVar :: Int -> HOL cls thry HOLTerm holOfVar v = holOfVar' v <|> let v' = v `mod` mesonOffInc in do hv' <- holOfVar' v' gv <- genVar $ typeOf hv' modifyHOLRef ref $ \ st -> st { gstore = (gv, v) : gstore st } return gv holOfVar' :: Int -> HOL cls thry HOLTerm holOfVar' v = note "holOfVar" $ do vs <- liftM vstore $ readHOLRef ref (revAssoc v vs) <|> (do gs <- liftM gstore $ readHOLRef ref revAssoc v gs) folOfVar :: HOLTerm -> HOL cls thry Int folOfVar v = do currentvars <- liftM vstore $ readHOLRef ref case lookup v currentvars of Just x -> return x Nothing -> do n <- incVCounter modifyHOLRef ref $ \ st -> st { vstore = (v, n) : currentvars } return n convQUANT_BOOL :: ClassicCtxt thry => Conversion cls thry convQUANT_BOOL = convPURE_REWRITE [ thmFORALL_BOOL, thmEXISTS_BOOL, thmCOND_CLAUSES , thmNOT_CLAUSES, thmIMP_CLAUSES, thmAND_CLAUSES , thmOR_CLAUSES, thmEQ_CLAUSES, thmFORALL_SIMP , thmEXISTS_SIMP ] tacSPLIT :: BoolCtxt thry => Int -> Tactic cls thry tacSPLIT n = (_FIRST_X_ASSUM (tacCONJUNCTS_THEN' tacASSUME) `_THEN` tacSPLIT n) `_ORELSE` (if n > 0 then _FIRST_X_ASSUM tacDISJ_CASES `_THEN` tacSPLIT (n-1) else _NO) `_ORELSE` _ALL tacGEN_MESON :: (TriviaCtxt thry, HOLThmRep thm cls thry) => Int -> Int -> Int -> [thm] -> Tactic cls thry tacGEN_MESON minVal maxVal step ths gl = do val <- initializeMeson ref <- newHOLRef val ths' <- mapM ruleGEN_ALL ths (tacREFUTE_THEN tacASSUME `_THEN` tacPOLY_ASSUME ths' `_THEN` (\ g@(Goal asl _) -> _MAP_EVERY (tacUNDISCH . concl . snd) asl g) `_THEN` tacSELECT_ELIM `_THEN` (\ g@(Goal _ w) -> _MAP_EVERY (\ v -> tacSPEC (v,v)) (frees w) g) `_THEN` tacCONV (convPRESIMP `_THEN` convTOP_DEPTH convBETA `_THEN` convLAMBDA_ELIM `_THEN` convCONDS_CELIM `_THEN` convQUANT_BOOL) `_THEN` _REPEAT (tacGEN `_ORELSE` tacDISCH) `_THEN` tacREFUTE_THEN tacASSUME `_THEN` tacRULE_ASSUM (ruleCONV (convNNF `_THEN` convSKOLEM)) `_THEN` _REPEAT (_FIRST_X_ASSUM tacCHOOSE) `_THEN` tacASM_FOL `_THEN` tacSPLIT mesonSplitLimit `_THEN` tacRULE_ASSUM (ruleCONV (convPRENEX `_THEN` convWEAK_CNF)) `_THEN` tacRULE_ASSUM (repeatM (\ th@(Thm _ (Forall x _)) -> do tm <- genVar $ typeOf x ruleSPEC tm th)) `_THEN` _REPEAT (_FIRST_X_ASSUM (tacCONJUNCTS_THEN' tacASSUME)) `_THEN` tacRULE_ASSUM (ruleCONV (convASSOC thmDISJ_ASSOC)) `_THEN` _REPEAT (_FIRST_X_ASSUM tacSUBST_VAR) `_THEN` tacPURE_MESON ref minVal maxVal step) gl -- common meson tactics tacASM_MESON :: (TriviaCtxt thry, HOLThmRep thm cls thry) => [thm] -> Tactic cls thry tacASM_MESON = tacGEN_MESON 0 50 1 tacASM_MESON_NIL :: TriviaCtxt thry => Tactic cls thry tacASM_MESON_NIL = tacASM_MESON ([] :: [HOLThm]) tacMESON :: (TriviaCtxt thry, HOLThmRep thm cls thry) => [thm] -> Tactic cls thry tacMESON ths = _POP_ASSUM_LIST (const _ALL) `_THEN` tacASM_MESON ths tacMESON_NIL :: TriviaCtxt thry => Tactic cls thry tacMESON_NIL = tacMESON ([] :: [HOLThm]) ruleMESON :: (TriviaCtxt thry, HOLThmRep thm cls thry, HOLTermRep tm cls thry) => [thm] -> tm -> HOL cls thry HOLThm ruleMESON ths tm = prove tm $ tacMESON ths ruleMESON_NIL :: (TriviaCtxt thry, HOLTermRep tm cls thry) => tm -> HOL cls thry HOLThm ruleMESON_NIL tm = prove tm tacMESON_NIL
ecaustin/haskhol-deductive
src/HaskHOL/Lib/Meson.hs
bsd-2-clause
37,384
0
30
12,987
12,961
6,736
6,225
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Propellor.Property.Ssh ( installed, restarted, PubKeyText, SshKeyType(..), -- * Daemon configuration sshdConfig, ConfigKeyword, setSshdConfigBool, setSshdConfig, RootLogin(..), permitRootLogin, passwordAuthentication, noPasswords, listenPort, -- * Host keys randomHostKeys, hostKeys, hostKey, hostPubKey, getHostPubKey, -- * User keys and configuration userKeys, userKeyAt, knownHost, unknownHost, authorizedKeysFrom, unauthorizedKeysFrom, authorizedKeys, authorizedKey, unauthorizedKey, hasAuthorizedKeys, getUserPubKeys, ) where import Propellor.Base import qualified Propellor.Property.File as File import qualified Propellor.Property.Service as Service import qualified Propellor.Property.Apt as Apt import Propellor.Property.User import Propellor.Types.Info import Utility.FileMode import System.PosixCompat import qualified Data.Map as M import qualified Data.Set as S import Data.List installed :: Property NoInfo installed = Apt.installed ["ssh"] restarted :: Property NoInfo restarted = Service.restarted "ssh" sshBool :: Bool -> String sshBool True = "yes" sshBool False = "no" sshdConfig :: FilePath sshdConfig = "/etc/ssh/sshd_config" type ConfigKeyword = String setSshdConfigBool :: ConfigKeyword -> Bool -> Property NoInfo setSshdConfigBool setting allowed = setSshdConfig setting (sshBool allowed) setSshdConfig :: ConfigKeyword -> String -> Property NoInfo setSshdConfig setting val = File.fileProperty desc f sshdConfig `onChange` restarted where desc = unwords [ "ssh config:", setting, val ] cfgline = setting ++ " " ++ val wantedline s | s == cfgline = True | (setting ++ " ") `isPrefixOf` s = False | otherwise = True f ls | cfgline `elem` ls = filter wantedline ls | otherwise = filter wantedline ls ++ [cfgline] data RootLogin = RootLogin Bool -- ^ allow or prevent root login | WithoutPassword -- ^ disable password authentication for root, while allowing other authentication methods | ForcedCommandsOnly -- ^ allow root login with public-key authentication, but only if a forced command has been specified for the public key permitRootLogin :: RootLogin -> Property NoInfo permitRootLogin (RootLogin b) = setSshdConfigBool "PermitRootLogin" b permitRootLogin WithoutPassword = setSshdConfig "PermitRootLogin" "without-password" permitRootLogin ForcedCommandsOnly = setSshdConfig "PermitRootLogin" "forced-commands-only" passwordAuthentication :: Bool -> Property NoInfo passwordAuthentication = setSshdConfigBool "PasswordAuthentication" -- | Configure ssh to not allow password logins. -- -- To prevent lock-out, this is done only once root's -- authorized_keys is in place. noPasswords :: Property NoInfo noPasswords = check (hasAuthorizedKeys (User "root")) $ passwordAuthentication False dotDir :: User -> IO FilePath dotDir user = do h <- homedir user return $ h </> ".ssh" dotFile :: FilePath -> User -> IO FilePath dotFile f user = do d <- dotDir user return $ d </> f -- | Makes the ssh server listen on a given port, in addition to any other -- ports it is configured to listen on. -- -- Revert to prevent it listening on a particular port. listenPort :: Int -> RevertableProperty NoInfo listenPort port = enable <!> disable where portline = "Port " ++ show port enable = sshdConfig `File.containsLine` portline `describe` ("ssh listening on " ++ portline) `onChange` restarted disable = sshdConfig `File.lacksLine` portline `describe` ("ssh not listening on " ++ portline) `onChange` restarted hasAuthorizedKeys :: User -> IO Bool hasAuthorizedKeys = go <=< dotFile "authorized_keys" where go f = not . null <$> catchDefaultIO "" (readFile f) -- | Blows away existing host keys and make new ones. -- Useful for systems installed from an image that might reuse host keys. -- A flag file is used to only ever do this once. randomHostKeys :: Property NoInfo randomHostKeys = flagFile prop "/etc/ssh/.unique_host_keys" `onChange` restarted where prop = property "ssh random host keys" $ do void $ liftIO $ boolSystem "sh" [ Param "-c" , Param "rm -f /etc/ssh/ssh_host_*" ] ensureProperty $ scriptProperty [ "DPKG_MAINTSCRIPT_NAME=postinst DPKG_MAINTSCRIPT_PACKAGE=openssh-server /var/lib/dpkg/info/openssh-server.postinst configure" ] -- | The text of a ssh public key, for example, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB3BJ2GqZiTR2LEoDXyYFgh/BduWefjdKXAsAtzS9zeI" type PubKeyText = String -- | Installs the specified list of ssh host keys. -- -- The corresponding private keys come from the privdata. -- -- Any host keys that are not in the list are removed from the host. hostKeys :: IsContext c => c -> [(SshKeyType, PubKeyText)] -> Property HasInfo hostKeys ctx l = propertyList desc $ catMaybes $ map (\(t, pub) -> Just $ hostKey ctx t pub) l ++ [cleanup] where desc = "ssh host keys configured " ++ typelist (map fst l) typelist tl = "(" ++ unwords (map fromKeyType tl) ++ ")" alltypes = [minBound..maxBound] staletypes = let have = map fst l in filter (`notElem` have) alltypes removestale b = map (File.notPresent . flip keyFile b) staletypes cleanup | null staletypes || null l = Nothing | otherwise = Just $ toProp $ property ("any other ssh host keys removed " ++ typelist staletypes) $ ensureProperty $ combineProperties desc (removestale True ++ removestale False) `onChange` restarted -- | Installs a single ssh host key of a particular type. -- -- The public key is provided to this function; -- the private key comes from the privdata; hostKey :: IsContext c => c -> SshKeyType -> PubKeyText -> Property HasInfo hostKey context keytype pub = combineProperties desc [ hostPubKey keytype pub , toProp $ property desc $ install File.hasContent True (lines pub) , withPrivData (keysrc "" (SshPrivKey keytype "")) context $ \getkey -> property desc $ getkey $ install File.hasContentProtected False . privDataLines ] `onChange` restarted where desc = "ssh host key configured (" ++ fromKeyType keytype ++ ")" install writer ispub keylines = do let f = keyFile keytype ispub ensureProperty $ writer f (keyFileContent keylines) keysrc ext field = PrivDataSourceFileFromCommand field ("sshkey"++ext) ("ssh-keygen -t " ++ sshKeyTypeParam keytype ++ " -f sshkey") -- Make sure that there is a newline at the end; -- ssh requires this for some types of private keys. keyFileContent :: [String] -> [File.Line] keyFileContent keylines = keylines ++ [""] keyFile :: SshKeyType -> Bool -> FilePath keyFile keytype ispub = "/etc/ssh/ssh_host_" ++ fromKeyType keytype ++ "_key" ++ ext where ext = if ispub then ".pub" else "" -- | Indicates the host key that is used by a Host, but does not actually -- configure the host to use it. Normally this does not need to be used; -- use 'hostKey' instead. hostPubKey :: SshKeyType -> PubKeyText -> Property HasInfo hostPubKey t = pureInfoProperty "ssh pubkey known" . HostKeyInfo . M.singleton t getHostPubKey :: Propellor (M.Map SshKeyType PubKeyText) getHostPubKey = fromHostKeyInfo <$> askInfo newtype HostKeyInfo = HostKeyInfo { fromHostKeyInfo :: M.Map SshKeyType PubKeyText } deriving (Eq, Ord, Typeable, Show) instance IsInfo HostKeyInfo where propagateInfo _ = False instance Monoid HostKeyInfo where mempty = HostKeyInfo M.empty mappend (HostKeyInfo old) (HostKeyInfo new) = -- new first because union prefers values from the first -- parameter when there is a duplicate key HostKeyInfo (new `M.union` old) userPubKeys :: User -> [(SshKeyType, PubKeyText)] -> Property HasInfo userPubKeys u@(User n) l = pureInfoProperty ("ssh pubkey for " ++ n) $ UserKeyInfo (M.singleton u (S.fromList l)) getUserPubKeys :: User -> Propellor [(SshKeyType, PubKeyText)] getUserPubKeys u = maybe [] S.toList . M.lookup u . fromUserKeyInfo <$> askInfo newtype UserKeyInfo = UserKeyInfo { fromUserKeyInfo :: M.Map User (S.Set (SshKeyType, PubKeyText)) } deriving (Eq, Ord, Typeable, Show) instance IsInfo UserKeyInfo where propagateInfo _ = False instance Monoid UserKeyInfo where mempty = UserKeyInfo M.empty mappend (UserKeyInfo old) (UserKeyInfo new) = UserKeyInfo (M.unionWith S.union old new) -- | Sets up a user with the specified public keys, and the corresponding -- private keys from the privdata. -- -- The public keys are added to the Info, so other properties like -- `authorizedKeysFrom` can use them. userKeys :: IsContext c => User -> c -> [(SshKeyType, PubKeyText)] -> Property HasInfo userKeys user@(User name) context ks = combineProperties desc $ userPubKeys user ks : map (userKeyAt Nothing user context) ks where desc = unwords [ name , "has ssh key" , "(" ++ unwords (map (fromKeyType . fst) ks) ++ ")" ] -- | Sets up a user with the specified pubic key, and a private -- key from the privdata. -- -- A file can be specified to write the key to somewhere other than -- the default locations. Allows a user to have multiple keys for -- different roles. userKeyAt :: IsContext c => Maybe FilePath -> User -> c -> (SshKeyType, PubKeyText) -> Property HasInfo userKeyAt dest user@(User u) context (keytype, pubkeytext) = combineProperties desc $ props & pubkey & privkey where desc = unwords $ catMaybes [ Just u , Just "has ssh key" , dest , Just $ "(" ++ fromKeyType keytype ++ ")" ] pubkey = property desc $ install File.hasContent ".pub" [pubkeytext] privkey = withPrivData (SshPrivKey keytype u) context $ \getkey -> property desc $ getkey $ install File.hasContentProtected "" . privDataLines install writer ext key = do f <- liftIO $ keyfile ext ensureProperty $ combineProperties desc [ writer f (keyFileContent key) , File.ownerGroup f user (userGroup user) , File.ownerGroup (takeDirectory f) user (userGroup user) ] keyfile ext = case dest of Nothing -> do home <- homeDirectory <$> getUserEntryForName u return $ home </> ".ssh" </> "id_" ++ fromKeyType keytype ++ ext Just f -> return $ f ++ ext fromKeyType :: SshKeyType -> String fromKeyType SshRsa = "rsa" fromKeyType SshDsa = "dsa" fromKeyType SshEcdsa = "ecdsa" fromKeyType SshEd25519 = "ed25519" -- | Puts some host's ssh public key(s), as set using `hostPubKey` -- or `hostKey` into the known_hosts file for a user. knownHost :: [Host] -> HostName -> User -> Property NoInfo knownHost hosts hn user@(User u) = property desc $ go =<< knownHostLines hosts hn where desc = u ++ " knows ssh key for " ++ hn go [] = do warningMessage $ "no configured ssh host keys for " ++ hn return FailedChange go ls = do f <- liftIO $ dotFile "known_hosts" user modKnownHost user f $ f `File.containsLines` ls `requires` File.dirExists (takeDirectory f) -- | Reverts `knownHost` unknownHost :: [Host] -> HostName -> User -> Property NoInfo unknownHost hosts hn user@(User u) = property desc $ go =<< knownHostLines hosts hn where desc = u ++ " does not know ssh key for " ++ hn go [] = return NoChange go ls = do f <- liftIO $ dotFile "known_hosts" user ifM (liftIO $ doesFileExist f) ( modKnownHost user f $ f `File.lacksLines` ls , return NoChange ) knownHostLines :: [Host] -> HostName -> Propellor [File.Line] knownHostLines hosts hn = keylines <$> fromHost hosts hn getHostPubKey where keylines (Just m) = map (\k -> hn ++ " " ++ k) (M.elems m) keylines Nothing = [] modKnownHost :: User -> FilePath -> Property NoInfo -> Propellor Result modKnownHost user f p = ensureProperty $ p `requires` File.ownerGroup f user (userGroup user) `requires` File.ownerGroup (takeDirectory f) user (userGroup user) -- | Ensures that a local user's authorized_keys contains lines allowing -- logins from a remote user on the specified Host. -- -- The ssh keys of the remote user can be set using `keysImported` -- -- Any other lines in the authorized_keys file are preserved as-is. authorizedKeysFrom :: User -> (User, Host) -> Property NoInfo localuser@(User ln) `authorizedKeysFrom` (remoteuser@(User rn), remotehost) = property desc (go =<< authorizedKeyLines remoteuser remotehost) where remote = rn ++ "@" ++ hostName remotehost desc = ln ++ " authorized_keys from " ++ remote go [] = do warningMessage $ "no configured ssh user keys for " ++ remote return FailedChange go ls = ensureProperty $ combineProperties desc $ map (authorizedKey localuser) ls -- | Reverts `authorizedKeysFrom` unauthorizedKeysFrom :: User -> (User, Host) -> Property NoInfo localuser@(User ln) `unauthorizedKeysFrom` (remoteuser@(User rn), remotehost) = property desc (go =<< authorizedKeyLines remoteuser remotehost) where remote = rn ++ "@" ++ hostName remotehost desc = ln ++ " unauthorized_keys from " ++ remote go [] = return NoChange go ls = ensureProperty $ combineProperties desc $ map (unauthorizedKey localuser) ls authorizedKeyLines :: User -> Host -> Propellor [File.Line] authorizedKeyLines remoteuser remotehost = map snd <$> fromHost' remotehost (getUserPubKeys remoteuser) -- | Makes a user have authorized_keys from the PrivData -- -- This removes any other lines from the file. authorizedKeys :: IsContext c => User -> c -> Property HasInfo authorizedKeys user@(User u) context = withPrivData (SshAuthorizedKeys u) context $ \get -> property desc $ get $ \v -> do f <- liftIO $ dotFile "authorized_keys" user ensureProperty $ combineProperties desc [ File.hasContentProtected f (keyFileContent (privDataLines v)) , File.ownerGroup f user (userGroup user) , File.ownerGroup (takeDirectory f) user (userGroup user) ] where desc = u ++ " has authorized_keys" -- | Ensures that a user's authorized_keys contains a line. -- Any other lines in the file are preserved as-is. authorizedKey :: User -> String -> Property NoInfo authorizedKey user@(User u) l = property desc $ do f <- liftIO $ dotFile "authorized_keys" user modAuthorizedKey f user $ f `File.containsLine` l `requires` File.dirExists (takeDirectory f) where desc = u ++ " has authorized_keys" -- | Reverts `authorizedKey` unauthorizedKey :: User -> String -> Property NoInfo unauthorizedKey user@(User u) l = property desc $ do f <- liftIO $ dotFile "authorized_keys" user ifM (liftIO $ doesFileExist f) ( modAuthorizedKey f user $ f `File.lacksLine` l , return NoChange ) where desc = u ++ " lacks authorized_keys" modAuthorizedKey :: FilePath -> User -> Property NoInfo -> Propellor Result modAuthorizedKey f user p = ensureProperty $ p `requires` File.mode f (combineModes [ownerWriteMode, ownerReadMode]) `requires` File.ownerGroup f user (userGroup user) `requires` File.ownerGroup (takeDirectory f) user (userGroup user)
np/propellor
src/Propellor/Property/Ssh.hs
bsd-2-clause
14,661
184
18
2,582
4,148
2,156
1,992
286
2
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} module PromotedTypes where data RevList a = RNil | RevList a :> a data Pattern :: [*] -> * where Nil :: Pattern '[] Cons :: Maybe h -> Pattern t -> Pattern (h ': t) -- Unlike (:), (:>) does not have to be quoted on type level. data RevPattern :: RevList * -> * where RevNil :: RevPattern RNil RevCons :: Maybe h -> RevPattern t -> RevPattern (t :> h) data Tuple :: (*, *) -> * where Tuple :: a -> b -> Tuple '(a, b)
haskell/haddock
html-test/src/PromotedTypes.hs
bsd-2-clause
584
0
10
136
177
99
78
15
0
{-# LANGUAGE GADTs, TypeFamilies #-} module JS.Types where import Data.Monoid ((<>)) import Data.Text.Lazy.Builder (Builder, fromText) import Yesod.Core (GWidget, Route) import Data.Text (Text) import Control.Monad.Trans.RWS (RWST) import Data.Aeson (ToJSON) -- Javascript representation, tagged via phantom types. newtype JSVarName = JSVarName Text type RenderUrl url = url -> [(Text, Text)] -> Text type JS master = RWST (RenderUrl (Route master)) () Int (GWidget master master) data JSBody result where JSStmtNoBind :: JSExp a -> JSBody result -> JSBody result JSStmtBind :: JSExp a -> (JSExp a -> JSBody result) -> JSBody result JSStmtExp :: JSExp a -> JSBody a data JSExp a where JSLambda :: Args a => (a -> JSBody b) -> JSExp (ArgsType a -> b) JSText :: Text -> JSExp Text JSValue :: ToJSON value => value -> JSExp value JSVarE :: JSVarName -> JSExp a JSAppE :: Args a => JSExp (ArgsType a -> b) -> a -> JSExp b JSObject :: [JSPair] -> JSExp a JSProperty :: JSExp a -> Text -> JSExp b class Args a where type ArgsType a showArgs :: a -> JS master [Builder] showLambda :: (a -> JSBody b) -> JS master Builder data Arg a = Arg { unArg :: JSExp a } data JSPair where JSPair :: JSExp Text -> JSExp a -> JSPair
snoyberg/yesod-js
samples/ajax/JS/Types.hs
bsd-2-clause
1,277
0
10
279
477
257
220
30
0
module Haddock.Interface.Rn ( rnDoc, rnHaddockModInfo ) where import Haddock.Types import RnEnv ( dataTcOccs ) import RdrName ( RdrName, gre_name, GlobalRdrEnv, lookupGRE_RdrName ) import Name ( Name ) import Outputable ( ppr, defaultUserStyle ) rnHaddockModInfo :: GlobalRdrEnv -> HaddockModInfo RdrName -> HaddockModInfo Name rnHaddockModInfo gre (HaddockModInfo desc port stab maint) = HaddockModInfo (fmap (rnDoc gre) desc) port stab maint ids2string :: [RdrName] -> String ids2string [] = [] ids2string (x:_) = show $ ppr x defaultUserStyle data Id x = Id {unId::x} instance Monad Id where (Id v)>>=f = f v; return = Id rnDoc :: GlobalRdrEnv -> Doc RdrName -> Doc Name rnDoc gre = unId . do_rn where do_rn doc_to_rn = case doc_to_rn of DocEmpty -> return DocEmpty DocAppend a b -> do a' <- do_rn a b' <- do_rn b return (DocAppend a' b') DocString str -> return (DocString str) DocParagraph doc -> do doc' <- do_rn doc return (DocParagraph doc') DocIdentifier ids -> do let choices = concatMap dataTcOccs ids let gres = concatMap (\rdrName -> map gre_name (lookupGRE_RdrName rdrName gre)) choices case gres of [] -> return (DocMonospaced (DocString (ids2string ids))) ids' -> return (DocIdentifier ids') DocModule str -> return (DocModule str) DocEmphasis doc -> do doc' <- do_rn doc return (DocEmphasis doc') DocMonospaced doc -> do doc' <- do_rn doc return (DocMonospaced doc') DocUnorderedList docs -> do docs' <- mapM do_rn docs return (DocUnorderedList docs') DocOrderedList docs -> do docs' <- mapM do_rn docs return (DocOrderedList docs') DocDefList list -> do list' <- mapM (\(a,b) -> do a' <- do_rn a b' <- do_rn b return (a', b')) list return (DocDefList list') DocCodeBlock doc -> do doc' <- do_rn doc return (DocCodeBlock doc') DocURL str -> return (DocURL str) DocPic str -> return (DocPic str) DocAName str -> return (DocAName str) DocExamples e -> return (DocExamples e)
nominolo/haddock2
src/Haddock/Interface/Rn.hs
bsd-2-clause
2,106
0
21
518
811
385
426
59
17
{- Data/Singletons/TypeRepStar.hs (c) Richard Eisenberg 2012 [email protected] This file contains the definitions for considering TypeRep to be the demotion of *. This is still highly experimental, so expect unusual results! -} {-# LANGUAGE RankNTypes, TypeFamilies, KindSignatures, FlexibleInstances, GADTs, UndecidableInstances, ScopedTypeVariables #-} module Data.Singletons.TypeRepStar where import Data.Singletons import Data.Typeable data instance Sing (a :: *) where STypeRep :: Typeable a => Sing a sTypeRep :: forall (a :: *). Typeable a => Sing a sTypeRep = STypeRep instance Typeable a => SingI (a :: *) where sing = STypeRep instance SingE (a :: *) where type Demote a = TypeRep fromSing STypeRep = typeOf (undefined :: a) instance SingKind (Any :: *) where singInstance STypeRep = SingInstance
jonsterling/singletons
Data/Singletons/TypeRepStar.hs
bsd-3-clause
839
1
7
148
170
94
76
16
1
-- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE MagicHash #-} module Bind.Marshal.Action.Base where import Bind.Marshal.Prelude import qualified Prelude import Bind.Marshal.DataModel import Control.DeepSeq import Foreign.Ptr import GHC.Prim -- | All actions have a buffering requirement. In the case of an action with a static data model the -- buffer requirement is the memory required by the marshaled data. -- XXX: All actions? Maybe easier to just have a StaticBufferReq that is only defined for static -- buffer actions. type family BufferReq action -- | All static memory actions act on a buffer region. -- -- The tag type variable differentiates buffers being serialized to versus deserialized from. data BufferRegion tag = BufferRegion { buffer_region_start :: {-# UNPACK #-} !BytePtr , buffer_region_size :: {-# UNPACK #-} !Size } -- | returns the pointer to the end of the BufferRegion buffer_region_end :: BufferRegion tag -> BytePtr buffer_region_end (BufferRegion start size) = start `plusPtr` size {-# INLINE buffer_region_end #-} -- | Produces a new buffer region that skips the given number of bytes of the given buffer. -- -- XXX: Really should be named drop_bytes instead of pop_bytes pop_bytes :: BufferRegion tag -> Size -> BufferRegion tag pop_bytes (BufferRegion start size) !to_pop = BufferRegion (start `plusPtr` to_pop) (size - to_pop) {-# INLINE pop_bytes #-} instance NFData (BufferRegion tag) where rnf (BufferRegion !start !size) = () type Iter = Ptr Word8
coreyoconnor/bind-marshal
src/Bind/Marshal/Action/Base.hs
bsd-3-clause
1,639
0
9
311
224
132
92
-1
-1
{-# LANGUAGE TemplateHaskell #-} module TH where import Data.Type.Equality import Language.Haskell.TH import Type triangle :: Int -> Int -> Int -> Q Exp triangle a b c = [|Refl :: Triangle $(intToNat a) $(intToNat b) $(intToNat c)|] where intToNat :: Int -> Q Type intToNat 0 = [t|Zero|] intToNat n = [t|Succ $(intToNat $ pred n)|]
nkaretnikov/triangle-inequality
src/TH.hs
bsd-3-clause
352
0
8
76
93
56
37
11
2
module Language.Brainfuck.Internals.GenericParser where import Prelude hiding (print, read) import Data.Maybe (catMaybes) import Text.ParserCombinators.Parsec import Language.Brainfuck.Internals.Instructions -- | Encapsulate a parser type GenericParser = Parser [Instr] -- | Record type containing symbols of Brainfuck language data Symbols = Symbols { incr :: String, -- Symbol for + decr :: String, -- Symbol for - right :: String, -- Symbol for > left :: String, -- Symbol for < read :: String, -- Symbol for , print :: String, -- Symbol for . openl :: String, -- Symbol for [ closel :: String, -- Symbol for ] reserved :: String -- None of this is a comment } -- | Used to generate a parser for a Brainfuck's dialect genparser :: Symbols -> GenericParser genparser sym = fmap catMaybes $ many $ try instr <|> try loop <|> comment where comment = noneOf (reserved sym) >> return Nothing instr = choice [ parseInstr incr (Incr 1), parseInstr decr (Decr 1), parseInstr right (MoveRight 1), parseInstr left (MoveLeft 1), parseInstr read Read, parseInstr print Print] loop = between (string $ openl sym) -- Open loop (string $ closel sym) -- Close loop (Just . Loop <$> genparser sym) -- Body parseInstr fun inst = try $ do _ <- string $ fun sym return $ Just inst
remusao/Hodor
src/Language/Brainfuck/Internals/GenericParser.hs
bsd-3-clause
1,523
0
12
473
362
203
159
33
1
module PivotalTrackerApi.Iteration ( Iteration , number , project_id , PivotalTrackerApi.Iteration.length , team_strength , stories , start , finish , velocity , kind ) where import PivotalTrackerApi.Base import PivotalTrackerApi.Story (Story) data Iteration = Iteration { _number :: Int , _project_id :: Int , _length :: Int , _team_strength :: Double , _stories :: [Story] , _start :: Text , _finish :: Text , _velocity :: Maybe Double , _kind :: Text } deriving (Show, Generic) makeLenses ''Iteration instance FromJSON Iteration where parseJSON = genericParseJSON defaultOptions{fieldLabelModifier = drop 1}
diogob/pivotal-tracker-api
src/PivotalTrackerApi/Iteration.hs
bsd-3-clause
791
0
9
267
171
103
68
-1
-1
{-# OPTIONS_HADDOCK show-extensions #-} {-| Module : $Header$ Copyright : (c) 2015 Swinburne Software Innovation Lab License : BSD3 Maintainer : Rhys Adams <[email protected]> Stability : unstable Portability : portable Functions for Eclogues API instance election. -} module Eclogues.APIElection ( LeadershipError (..), ManagedZK, ZKURI, whileLeader, advertisedData ) where import Eclogues.API (zkNode) import Control.Monad.Except (ExceptT, throwError, catchError) import Control.Monad.Trans.Control (liftBaseOp) import Data.Aeson (encode) import Data.ByteString (ByteString) import Data.ByteString.Lazy (toStrict) import Data.Word (Word16) import Database.Zookeeper.Election (LeadershipError (..), whenLeader) import Database.Zookeeper.ManagedEvents (ManagedZK, ZKURI, withZookeeper) -- | Contest Zookeeper election with the provided data, and perform some -- action while elected. If leadership is lost, wait until re-elected and -- perform the action again. -- -- This function will never throw 'LeadershipLost'. whileLeader :: ZKURI -> String -- ^ API host -> Word16 -- ^ API port -> (ManagedZK -> IO a) -> ExceptT LeadershipError IO a whileLeader zkUri host port act = liftBaseOp (withZookeeper zkUri) go where go zk = catchError (whenLeader zk zkNode zkData $ act zk) $ \case LeadershipLost -> go zk e -> throwError e zkData = advertisedData host port -- | Create encoded (host, port) to advertise via Zookeeper. advertisedData :: String -> Word16 -> ByteString advertisedData host port = toStrict $ encode (host, port)
futufeld/eclogues
eclogues-impl/app/api/Eclogues/APIElection.hs
bsd-3-clause
1,654
0
11
329
315
181
134
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module HipBot.AbsoluteURI where import Blaze.ByteString.Builder (toLazyByteString) import Control.Monad import qualified Data.Aeson as A import qualified Data.ByteString.Lazy.UTF8 as LB import Data.List (isSuffixOf) import Data.Maybe import Data.Monoid import Data.String import Data.Text (Text) import qualified Data.Text as T import Data.Typeable import Network.HTTP.Types import Network.URI (URI) import qualified Network.URI as URI import Prelude newtype AbsoluteURI = AbsoluteURI URI deriving (Eq, Typeable) parseAbsoluteURI :: String -> Maybe AbsoluteURI parseAbsoluteURI = fmap AbsoluteURI . URI.parseAbsoluteURI appendPath :: AbsoluteURI -> [Text] -> AbsoluteURI appendPath (AbsoluteURI uri) xs = AbsoluteURI uri' where uri' = uri { URI.uriPath = URI.uriPath uri <> dropSlash (relPath xs) } dropSlash s = if "/" `isSuffixOf` URI.uriPath uri then tail s else s relPath :: [Text] -> String relPath = LB.toString . toLazyByteString . encodePathSegments relativeTo :: [Text] -> AbsoluteURI -> AbsoluteURI relativeTo xs (AbsoluteURI uri) = AbsoluteURI (URI.relativeTo rel uri) where rel = fromJust . URI.parseURIReference . drop 1 . relPath $ xs instance Show AbsoluteURI where show (AbsoluteURI u) = show u instance IsString AbsoluteURI where fromString s = fromMaybe (error $ "Not an absolute URI: " <> s) (parseAbsoluteURI s) instance A.ToJSON AbsoluteURI where toJSON = A.toJSON . show instance A.FromJSON AbsoluteURI where parseJSON = A.withText "String" $ \t -> maybe mzero return . parseAbsoluteURI . T.unpack $ t
purefn/hipbot
src/HipBot/AbsoluteURI.hs
bsd-3-clause
1,604
0
12
257
493
271
222
42
2
module HipChat.Types.Rooms.GetAllRoomsResponse ( GetAllRoomsResponse(..) ) where data GetAllRoomsResponse = GetAllRoomsResponse
oswynb/hipchat-hs
lib/HipChat/Types/Rooms/GetAllRoomsResponse.hs
bsd-3-clause
133
0
5
15
24
16
8
3
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} -- | Versions for packages. module Stack.Types.Version (Version ,Cabal.VersionRange -- TODO in the future should have a newtype wrapper ,MajorVersion (..) ,getMajorVersion ,fromMajorVersion ,parseMajorVersionFromString ,versionParser ,parseVersion ,parseVersionFromString ,versionString ,versionText ,toCabalVersion ,fromCabalVersion ,mkVersion ,versionRangeText ,withinRange) where import Control.Applicative import Control.DeepSeq import Control.Monad.Catch import Data.Aeson import Data.Attoparsec.ByteString.Char8 import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Data import Data.Hashable import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Text (Text) import qualified Data.Text as T import Data.Vector.Binary () import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import Data.Word import Distribution.Text (disp) import qualified Distribution.Version as Cabal import GHC.Generics import Language.Haskell.TH import Language.Haskell.TH.Syntax import Prelude -- Fix warning: Word in Prelude from base-4.8. import Text.PrettyPrint (render) -- | A parse fail. data VersionParseFail = VersionParseFail ByteString | NotAMajorVersion Version deriving (Typeable) instance Exception VersionParseFail instance Show VersionParseFail where show (VersionParseFail bs) = "Invalid version: " ++ show bs show (NotAMajorVersion v) = concat [ "Not a major version: " , versionString v , ", expecting exactly two numbers (e.g. 7.10)" ] -- | A package version. newtype Version = Version {unVersion :: Vector Word} deriving (Eq,Ord,Typeable,Data,Generic,Binary,NFData) -- | The first two components of a version. data MajorVersion = MajorVersion !Word !Word deriving (Typeable, Eq, Ord) instance Show MajorVersion where show (MajorVersion x y) = concat [show x, ".", show y] instance ToJSON MajorVersion where toJSON = toJSON . fromMajorVersion -- | Parse major version from @String@ parseMajorVersionFromString :: MonadThrow m => String -> m MajorVersion parseMajorVersionFromString s = do Version v <- parseVersionFromString s if V.length v == 2 then return $ getMajorVersion (Version v) else throwM $ NotAMajorVersion (Version v) instance FromJSON MajorVersion where parseJSON = withText "MajorVersion" $ either (fail . show) return . parseMajorVersionFromString . T.unpack instance FromJSON a => FromJSON (Map MajorVersion a) where parseJSON val = do m <- parseJSON val fmap Map.fromList $ mapM go $ Map.toList m where go (k, v) = do k' <- either (fail . show) return $ parseMajorVersionFromString k return (k', v) -- | Returns the first two components, defaulting to 0 if not present getMajorVersion :: Version -> MajorVersion getMajorVersion (Version v) = case V.length v of 0 -> MajorVersion 0 0 1 -> MajorVersion (V.head v) 0 _ -> MajorVersion (V.head v) (v V.! 1) -- | Convert a two-component version into a @Version@ fromMajorVersion :: MajorVersion -> Version fromMajorVersion (MajorVersion x y) = Version $ V.fromList [x, y] instance Hashable Version where hashWithSalt i = hashWithSalt i . V.toList . unVersion instance Lift Version where lift (Version n) = appE (conE 'Version) (appE (varE 'V.fromList) (listE (map (litE . IntegerL . fromIntegral) (V.toList n)))) instance Show Version where show (Version v) = intercalate "." (map show (V.toList v)) instance ToJSON Version where toJSON = toJSON . versionText instance FromJSON Version where parseJSON j = do s <- parseJSON j case parseVersionFromString s of Nothing -> fail ("Couldn't parse package version: " ++ s) Just ver -> return ver -- | Attoparsec parser for a package version from bytestring. versionParser :: Parser Version versionParser = do ls <- ((:) <$> num <*> many num') let !v = V.fromList ls return (Version v) where num = decimal num' = point *> num point = satisfy (== '.') -- | Convenient way to parse a package version from a bytestring. parseVersion :: MonadThrow m => ByteString -> m Version parseVersion x = go x where go = either (const (throwM (VersionParseFail x))) return . parseOnly (versionParser <* endOfInput) -- | Migration function. parseVersionFromString :: MonadThrow m => String -> m Version parseVersionFromString = parseVersion . S8.pack -- | Get a string representation of a package version. versionString :: Version -> String versionString (Version v) = intercalate "." (map show (V.toList v)) -- | Get a string representation of a package version. versionText :: Version -> Text versionText (Version v) = T.intercalate "." (map (T.pack . show) (V.toList v)) -- | Convert to a Cabal version. toCabalVersion :: Version -> Cabal.Version toCabalVersion (Version v) = Cabal.Version (map fromIntegral (V.toList v)) [] -- | Convert from a Cabal version. fromCabalVersion :: Cabal.Version -> Version fromCabalVersion (Cabal.Version vs _) = let !v = V.fromList (map fromIntegral vs) in Version v -- | Make a package version. mkVersion :: String -> Q Exp mkVersion s = case parseVersionFromString s of Nothing -> error ("Invalid package version: " ++ show s) Just pn -> [|pn|] -- | Display a version range versionRangeText :: Cabal.VersionRange -> Text versionRangeText = T.pack . render . disp -- | Check if a version is within a version range. withinRange :: Version -> Cabal.VersionRange -> Bool withinRange v r = toCabalVersion v `Cabal.withinRange` r
mietek/stack
src/Stack/Types/Version.hs
bsd-3-clause
6,328
0
15
1,521
1,637
866
771
163
3
----------------------------------------------------------------------------------------- -- A Haskell port of GNU's getopt library -- -- Sven Panne <[email protected]> Oct. 1996 (small changes Dec. 1997) -- -- Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't -- already know it, you probably don't want to hear about it...) and the recognition of -- long options with a single dash (e.g. '-help' is recognised as '--help', as long as -- there is no short option 'h'). -- -- Other differences between GNU's getopt and this implementation: -- * To enforce a coherent description of options and arguments, there are explanation -- fields in the option/argument descriptor. -- * Error messages are now more informative, but no longer POSIX compliant... :-( -- -- And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, -- we need only 195 here, including a 46 line example! :-) ----------------------------------------------------------------------------------------- module Text.CTK.GetOpt (ArgOrder(..), OptDescr(..), ArgDescr(..), usageInfo, getOpt) where import Data.List (isPrefixOf) data ArgOrder a -- what to do with options following non-options: = RequireOrder -- no option processing after first non-option | Permute -- freely intersperse options and non-options | ReturnInOrder (String -> a) -- wrap non-options into options data OptDescr a = -- description of a single options: Option [Char] -- list of short option characters [String] -- list of long option strings (without "--") (ArgDescr a) -- argument descriptor String -- explanation of option for user data ArgDescr a -- description of an argument option: = NoArg a -- no argument expected | ReqArg (String -> a) String -- option requires argument | OptArg (Maybe String -> a) String -- optional argument data OptKind a -- kind of cmd line arg (internal use only): = Opt a -- an option | NonOpt String -- a non-option | EndOfOpts -- end-of-options marker (i.e. "--") | OptErr String -- something went wrong... usageInfo :: String -- header -> [OptDescr a] -- option descriptors -> String -- nicely formatted decription of optionsL usageInfo header optDescr = unlines (header:table) where (ss,ls,ds) = (unzip3 . map fmtOpt) optDescr table = zipWith3 paste (sameLen ss) (sameLen ls) (sameLen ds) paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z sameLen xs = flushLeft ((maximum . map length) xs) xs flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ] fmtOpt :: OptDescr a -> (String,String,String) fmtOpt (Option sos los ad descr) = (sepBy ", " (map (fmtShort ad) sos), sepBy ", " (map (fmtLong ad) los), descr) where sepBy sep [] = "" sepBy sep [x] = x sepBy sep (x:xs) = x ++ sep ++ sepBy sep xs fmtShort :: ArgDescr a -> Char -> String fmtShort (NoArg _ ) so = "-" ++ [so] fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]" fmtLong :: ArgDescr a -> String -> String fmtLong (NoArg _ ) lo = "--" ++ lo fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]" getOpt :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the commandline arguments -> ([a],[String],[String]) -- (options,non-options,error messages) getOpt _ _ [] = ([],[],[]) getOpt ordering optDescr (arg:args) = procNextOpt opt ordering where procNextOpt (Opt o) _ = (o:os,xs,es) procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[]) procNextOpt (NonOpt x) Permute = (os,x:xs,es) procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es) procNextOpt EndOfOpts RequireOrder = ([],rest,[]) procNextOpt EndOfOpts Permute = ([],rest,[]) procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[]) procNextOpt (OptErr e) _ = (os,xs,e:es) (opt,rest) = getNext arg args optDescr (os,xs,es) = getOpt ordering optDescr rest -- take a look at the next cmd line arg and decide what to do with it getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) getNext "--" rest _ = (EndOfOpts,rest) getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr getNext ('-':x:xs) rest optDescr = shortOpt x xs rest optDescr getNext a rest _ = (NonOpt a,rest) -- handle long option longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) longOpt xs rest optDescr = long ads arg rest where (opt,arg) = break (=='=') xs options = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `isPrefixOf` l ] ads = [ ad | Option _ _ ad _ <- options ] optStr = ("--"++opt) long (_:_:_) _ rest = (errAmbig options optStr,rest) long [NoArg a ] [] rest = (Opt a,rest) long [NoArg a ] ('=':xs) rest = (errNoArg optStr,rest) long [ReqArg f d] [] [] = (errReq d optStr,[]) long [ReqArg f _] [] (r:rest) = (Opt (f r),rest) long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest) long [OptArg f _] [] rest = (Opt (f Nothing),rest) long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest) long _ _ rest = (errUnrec optStr,rest) -- handle short option shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String]) shortOpt x xs rest optDescr = short ads xs rest where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ] ads = [ ad | Option _ _ ad _ <- options ] optStr = '-':[x] short (_:_:_) _ rest = (errAmbig options optStr,rest) short (NoArg a :_) [] rest = (Opt a,rest) short (NoArg a :_) xs rest = (Opt a,('-':xs):rest) short (ReqArg f d:_) [] [] = (errReq d optStr,[]) short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest) short (ReqArg f _:_) xs rest = (Opt (f xs),rest) short (OptArg f _:_) [] rest = (Opt (f Nothing),rest) short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest) short [] [] rest = (errUnrec optStr,rest) short [] xs rest = (errUnrec optStr,('-':xs):rest) -- miscellaneous error formatting errAmbig :: [OptDescr a] -> String -> OptKind a errAmbig ods optStr = OptErr (usageInfo header ods) where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:" errReq :: String -> String -> OptKind a errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n") errUnrec :: String -> OptKind a errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n") errNoArg :: String -> OptKind a errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n") {- ----------------------------------------------------------------------------------------- -- and here a small and hopefully enlightening example: data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options :: [OptDescr Flag] options = [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files", Option ['V','?'] ["version","release"] (NoArg Version) "show version info", Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump", Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"] out :: Maybe String -> Flag out Nothing = Output "stdout" out (Just o) = Output o test :: ArgOrder Flag -> [String] -> String test order cmdline = case getOpt order options cmdline of (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n" (_,_,errs) -> concat errs ++ usageInfo header options where header = "Usage: foobar [OPTION...] files..." -- example runs: -- putStr (test RequireOrder ["foo","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["foo","-v"]) -- ==> options=[Verbose] args=["foo"] -- putStr (test (ReturnInOrder Arg) ["foo","-v"]) -- ==> options=[Arg "foo", Verbose] args=[] -- putStr (test Permute ["foo","--","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["-?o","--name","bar","--na=baz"]) -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[] -- putStr (test Permute ["--ver","foo"]) -- ==> option `--ver' is ambiguous; could be one of: -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- Usage: foobar [OPTION...] files... -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- -o[FILE] --output[=FILE] use FILE for dump -- -n USER --name=USER only dump USER's files ----------------------------------------------------------------------------------------- -}
mwotton/ctkl
src/Text/CTK/GetOpt.hs
bsd-3-clause
9,896
0
12
3,066
2,478
1,332
1,146
104
10
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Model where import qualified Data.ByteString.Lazy as B import GHC.Generics (Generic) import Control.Lens import Data.Aeson import Data.Aeson.TH import Common -- -- Model -- type Model = [Step] data Step = Step { _nInputPlane :: Int , _nOutputPlane :: Int , _weight :: [[Kernel]] -- ^ nOutputPlane * nInputPlane * (kW*kH) , _bias :: [Bias] -- ^ nOutputPlane , _kW :: Int , _kH :: Int } deriving (Show, Generic) type Kernel = [[Float]] type Bias = Float deriveJSON defaultOptions{fieldLabelModifier = drop 1} ''Step makeLenses ''Step readModel :: FilePath -> IO Model readModel path = do json_bytes <- B.readFile path let (Just model) = decode' json_bytes return model dumpModel :: Model -> IO () dumpModel model = do dump "model steps" (length model) mapM_ dumpStep model dumpStep :: Step -> IO () dumpStep step = do dumpTitle "Step" dump "nInputPlane" (step ^. nInputPlane) dump "nOutputPlane" (step ^. nOutputPlane) dump "kW, kH" (step ^. kW, step ^. kH)
notae/haskell-exercise
graphics/Model.hs
bsd-3-clause
1,133
0
11
270
351
190
161
38
1
module Lev3 where import Data.Array import qualified Number.Peano.Inf as P mft :: String -> String -> Array (Int, Int) P.Nat mft f t = m where m = array bounds [ ((i, j), lev i j) | (i,j) <- range bounds ] bounds = ((0, 0), (length t, length f)) lev 0 0 = 0 lev 0 j = succ $ m ! (0 , pred j) lev i 0 = succ $ m ! (pred i, 0 ) lev i j | (f!! p j) == (t !! p i) = m!(p i,p j) | otherwise = 1 + minimum [ m!(p i,j), m!(i,p j), m!(p i,p j) ] score :: String -> String -> Int score f t = let m = mft f t in fromIntegral $ m ! snd (bounds m) p = pred
sordina/mfug_levenshtein_difference_2016_07_07-
src/Lev3.hs
bsd-3-clause
588
0
13
181
380
201
179
15
4
{-# LINE 1 "fptools\libraries\base\System\CPUTime.hsc" #-} ----------------------------------------------------------------------------- {-# LINE 2 "fptools\libraries\base\System\CPUTime.hsc" #-} -- | -- Module : System.CPUTime -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/core/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- The standard CPUTime library. -- ----------------------------------------------------------------------------- module System.CPUTime ( getCPUTime, -- :: IO Integer cpuTimePrecision -- :: Integer ) where import Prelude import Data.Ratio {-# LINE 26 "fptools\libraries\base\System\CPUTime.hsc" #-} import Hugs.Time ( getCPUTime, clockTicks ) {-# LINE 28 "fptools\libraries\base\System\CPUTime.hsc" #-} {-# LINE 35 "fptools\libraries\base\System\CPUTime.hsc" #-} {-# LINE 123 "fptools\libraries\base\System\CPUTime.hsc" #-} -- |The 'cpuTimePrecision' constant is the smallest measurable difference -- in CPU time that the implementation can record, and is given as an -- integral number of picoseconds. cpuTimePrecision :: Integer cpuTimePrecision = round ((1000000000000::Integer) % fromIntegral (clockTicks)) {-# LINE 141 "fptools\libraries\base\System\CPUTime.hsc" #-}
OS2World/DEV-UTIL-HUGS
libraries/System/CPUTime.hs
bsd-3-clause
1,371
4
9
205
96
67
29
9
1
{-| Module : Idris.Imports Description : Code to handle import declarations. Copyright : License : BSD3 Maintainer : The Idris Community. -} module Idris.Imports( IFileType(..), findImport, findInPath, findPkgIndex , ibcPathNoFallback, installedPackages, pkgIndex ) where import Control.Applicative ((<$>)) import Data.List (isSuffixOf) import Idris.AbsSyntax import Idris.Error import Idris.Core.TT import IRTS.System (getIdrisLibDir) import System.FilePath import System.Directory import Control.Monad.State.Strict data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType deriving (Show, Eq) -- | Get the index file name for a package name pkgIndex :: String -> FilePath pkgIndex s = "00" ++ s ++ "-idx.ibc" srcPath :: FilePath -> FilePath srcPath fp = let (n, ext) = splitExtension fp in case ext of ".idr" -> fp _ -> fp ++ ".idr" lsrcPath :: FilePath -> FilePath lsrcPath fp = let (n, ext) = splitExtension fp in case ext of ".lidr" -> fp _ -> fp ++ ".lidr" -- Get name of byte compiled version of an import ibcPath :: FilePath -> Bool -> FilePath -> FilePath ibcPath ibcsd use_ibcsd fp = let (d_fp, n_fp) = splitFileName fp d = if (not use_ibcsd) || ibcsd == "" then d_fp else ibcsd </> d_fp n = dropExtension n_fp in d </> n <.> "ibc" ibcPathWithFallback :: FilePath -> FilePath -> IO FilePath ibcPathWithFallback ibcsd fp = do let ibcp = ibcPath ibcsd True fp ibc <- doesFileExist' ibcp return (if ibc then ibcp else ibcPath ibcsd False fp) ibcPathNoFallback :: FilePath -> FilePath -> FilePath ibcPathNoFallback ibcsd fp = ibcPath ibcsd True fp findImport :: [FilePath] -> FilePath -> FilePath -> Idris IFileType findImport [] ibcsd fp = ierror . Msg $ "Can't find import " ++ fp findImport (d:ds) ibcsd fp = do let fp_full = d </> fp ibcp <- runIO $ ibcPathWithFallback ibcsd fp_full let idrp = srcPath fp_full let lidrp = lsrcPath fp_full ibc <- runIO $ doesFileExist' ibcp idr <- runIO $ doesFileExist' idrp lidr <- runIO $ doesFileExist' lidrp let isrc = if lidr then LIDR lidrp else IDR idrp if ibc then return (IBC ibcp isrc) else if (idr || lidr) then return isrc else findImport ds ibcsd fp -- find a specific filename somewhere in a path findInPath :: [FilePath] -> FilePath -> IO FilePath findInPath [] fp = fail $ "Can't find file " ++ fp findInPath (d:ds) fp = do let p = d </> fp e <- doesFileExist' p if e then return p else findInPath ds fp findPkgIndex :: String -> Idris FilePath findPkgIndex p = do let idx = pkgIndex p ids <- allImportDirs runIO $ findInPath ids idx installedPackages :: IO [String] installedPackages = do idir <- getIdrisLibDir filterM (goodDir idir) =<< dirContents idir where allFilesInDir base fp = do let fullpath = base </> fp isDir <- doesDirectoryExist' fullpath if isDir then fmap concat (mapM (allFilesInDir fullpath) =<< dirContents fullpath) else return [fp] dirContents = fmap (filter (not . (`elem` [".", ".."]))) . getDirectoryContents goodDir idir d = any (".ibc" `isSuffixOf`) <$> allFilesInDir idir d -- | Case sensitive file existence check for Mac OS X. doesFileExist' :: FilePath -> IO Bool doesFileExist' = caseSensitive doesFileExist -- | Case sensitive directory existence check for Mac OS X. doesDirectoryExist' :: FilePath -> IO Bool doesDirectoryExist' = caseSensitive doesDirectoryExist caseSensitive :: (FilePath -> IO Bool) -> FilePath -> IO Bool caseSensitive existsCheck name = do exists <- existsCheck name if exists then do contents <- getDirectoryContents (takeDirectory name) return $ (takeFileName name) `elem` contents else return False
enolan/Idris-dev
src/Idris/Imports.hs
bsd-3-clause
4,677
0
15
1,721
1,180
600
580
90
4
module Eval where import System.IO.Unsafe import Data.Either import Data.List (nub) import qualified Data.Map as Map import Foreign.Ptr (FunPtr, castFunPtr) import Control.Monad.Except import qualified LLVM.General.AST as AST import qualified LLVM.General.AST.Type as T import LLVM.General.Analysis import LLVM.General.Context import qualified LLVM.General.ExecutionEngine as EE import LLVM.General.Module as Mod import LLVM.General.PassManager import Codegen import Curry import Emit import Environment import Infer import Lift import Parser import Pretty () import Substitute import Syntax import Type foreign import ccall "dynamic" haskFun :: FunPtr (IO Int) -> IO Int run :: FunPtr a -> IO Int run fn = haskFun (castFunPtr fn :: FunPtr (IO Int)) jit :: Context -> (EE.MCJIT -> IO a) -> IO a jit c = EE.withMCJIT c optlevel model ptrelim fastins where optlevel = Just 2 model = Nothing ptrelim = Nothing fastins = Nothing passes :: PassSetSpec passes = defaultCuratedPassSetSpec {optLevel = Just 3} runJIT :: AST.Module -> Either String Int runJIT mod' = do res <- unsafePerformIO $ withContext $ \context -> jit context $ \executionEngine -> runExceptT $ withModuleFromAST context mod' $ \m -> withPassManager passes $ \pm -> do _ <- runPassManager pm m EE.withModuleInEngine executionEngine m $ \ee -> do mainfn <- EE.getFunction ee (AST.Name "main") case mainfn of Just fn -> do res <- run fn return $ Right res Nothing -> return $ Left "could not find `main` function" case res of Left err -> Left err Right res' -> Right res' codegen :: AST.Module -> Program Typed -> [Type] -> IO AST.Module codegen m fns tys = withContext $ \context -> liftError $ withModuleFromAST context newast $ \m' -> do liftError $ verify m' return newast where modn = do Codegen.declare (T.ptr T.i8) "malloc" [(T.i32, AST.Name "size")] mapM (codegenTop tys (Map.fromList $ definitions' fns)) fns newast = runLLVM m modn eval :: String -> IO (Either String Int) eval source = case parseModule "<string>" source of Left err -> return $ Left $ show err Right prog -> do let defs = definitions prog let subbed = substitute (Map.fromList defs) prog let curried = map curryTop subbed let defs' = definitions curried case inferTop Environment.empty defs' of Left err -> return $ Left $ show err Right env -> do let core = constraintsTop env curried let corel = lefts core let corer = rights core if not (null corel) then return $ Left $ concatMap show corel else do let undef = filterDefinitions corer let (lifted, _) = lambdaLiftProgram 0 [] undef mod' <- Eval.codegen (AST.defaultModule {AST.moduleName = "test"}) lifted typeSymbols return $ runJIT mod'
jjingram/satori
src/Eval.hs
bsd-3-clause
3,126
0
28
914
1,014
511
503
93
4
import App.Models.Comments as CommentsModel import Turbinado.Controller create :: Controller () create = do id' <-getSetting_u "id" :: Controller String body_ <- getParam_u "body" author_ <- getParam_u "author" let pId = (Prelude.read id')::Integer CommentsModel.insert Comments{author = author_ ,body = body_ ,comment_id =Nothing,post_id = pId} False redirectTo $ "/Posts/Show/"++id'
abuiles/turbinado-blog
App/Controllers/Comments.hs
bsd-3-clause
448
0
12
110
132
68
64
9
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Exception import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (LoggingT, runStderrLoggingT) import Data.Conduit (Source, transPipe, ($$), (=$=)) import Database.Persist (insert) import Database.Persist.Sql (ConnectionPool, SqlPersistM, runMigration, runSqlPersistMPool) import Database.Persist.Sqlite (withSqlitePool) import Handlers import Model import Network.Wai.Middleware.RequestLogger (logStdoutDev) import System.Directory import System.Environment (getEnv) import System.IO.Error import Text.Blaze.Html (Html) import Text.Blaze.Html.Renderer.Text (renderHtml) import Web.Scotty (ActionM, ScottyM, get, html, middleware, param, scotty) main :: IO () main = do removeIfExists "my.db" runStderrLoggingT . withSqlPool $ \pool -> liftIO $ do runSql pool $ do runMigration migrateModel _ <- insert $ Person "John Doe" 35 _ <- insert $ Person "Jane Doe" 32 _ <- insert $ Person "The Dude" 38 _ <- insert $ Person "Me" 34 return () port <- getPort scotty port $ do middleware logStdoutDev router pool router :: ConnectionPool -> ScottyM () router pool = do get "/people/:personId" $ do personId <- param "personId" blazeSql pool $ getPerson personId get "/people" $ blazeSql pool getPeople get "/test/people" $ -- broken liftIO (runSqlSource pool selectAllPeople $$ peopleToHtml =$= foldSink) >>= blaze get "/" $ blazeSql pool getPeople get "/:word" $ do beam <- param "word" blaze $ getWord beam withSqlPool :: (ConnectionPool -> LoggingT IO ()) -> LoggingT IO () withSqlPool = withSqlitePool "my.db" 10 getPort :: IO Int getPort = fmap read $ getEnv "PORT" blaze :: Html -> ActionM () blaze = html . renderHtml blazeSql :: ConnectionPool -> SqlPersistM Html -> ActionM () blazeSql pool sql = liftIO (runSql pool sql) >>= blaze runSql :: ConnectionPool -> SqlPersistM a -> IO a runSql = flip runSqlPersistMPool removeIfExists :: FilePath -> IO () removeIfExists fileName = removeFile fileName `catch` handleExists where handleExists e | isDoesNotExistError e = return () | otherwise = throwIO e runSqlSource :: ConnectionPool -> Source SqlPersistM a -> Source IO a runSqlSource pool = transPipe $ runSql pool
derekjw/scotty-playground
src/Main.hs
bsd-3-clause
3,156
0
17
1,271
762
384
378
71
1
module Network.HaskellNet.SSL ( Settings (..) , defaultSettingsWithPort ) where import Network.Socket.Internal (PortNumber) data Settings = Settings { sslPort :: PortNumber , sslMaxLineLength :: Int , sslLogToConsole :: Bool , sslDisableCertificateValidation :: Bool } deriving(Eq, Ord, Show) defaultSettingsWithPort :: PortNumber -> Settings defaultSettingsWithPort p = Settings { sslPort = p , sslMaxLineLength = 10000 , sslLogToConsole = False , sslDisableCertificateValidation = False }
lemol/HaskellNet-SSL
src/Network/HaskellNet/SSL.hs
bsd-3-clause
632
0
8
203
121
75
46
16
1