code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE RecursiveDo #-} -- needed for Earley module AST (Type (..), Expression (..), BindingType (..), Statement (..), Block (..), Argument (..), Function (..), AST, Error (..), parse, RenderName (..)) where import MyPrelude import qualified Text.Earley as E import qualified Pretty as P import qualified Token as T import Pretty (Render, render) ----------------------------------------------------------------------------- types data Type metadata name = NamedType name | FunctionType [NodeWith Type metadata name] (NodeWith Type metadata name) deriving (Generic, Eq, Show, Functor, Foldable, Traversable) data Expression metadata name = Named name | Call (NodeWith Expression metadata name) [NodeWith Expression metadata name] | NumberLiteral Integer | TextLiteral Text | UnaryOperator UnaryOperator (NodeWith Expression metadata name) | BinaryOperator (NodeWith Expression metadata name) BinaryOperator (NodeWith Expression metadata name) deriving (Generic, Eq, Show, Functor, Foldable, Traversable) data BindingType = Let | Var deriving (Generic, Eq, Show) data Statement metadata name = Expression (NodeWith Expression metadata name) | Binding BindingType name (NodeWith Expression metadata name) | Assign name (NodeWith Expression metadata name) | IfThen (NodeWith Expression metadata name) (NodeWith Block metadata name) | IfThenElse (NodeWith Expression metadata name) (NodeWith Block metadata name) (NodeWith Block metadata name) | Forever (NodeWith Block metadata name) | While (NodeWith Expression metadata name) (NodeWith Block metadata name) | Return name -- return and break refer to the `exitTarget` in `Block`; these are "phantom names", not present in the source code (Maybe (NodeWith Expression metadata name)) | Break name -- see above deriving (Generic, Eq, Show, Functor, Foldable, Traversable) data Block metadata name = Block { exitTarget :: Maybe name, -- "phantom", see above statements :: [NodeWith Statement metadata name] } deriving (Generic, Eq, Show, Functor, Foldable, Traversable) data Argument metadata name = Argument { argumentName :: name, argumentType :: NodeWith Type metadata name } deriving (Generic, Eq, Show, Functor, Foldable, Traversable) data Function metadata name = Function { functionName :: name, arguments :: [NodeWith Argument metadata name], returns :: Maybe (NodeWith Type metadata name), body :: NodeWith Block metadata name } deriving (Generic, Eq, Show, Functor, Foldable, Traversable) ----------------------------------------------------------------------------- parsing type Expected = Text type Prod r = Compose (E.Prod r Expected (With Loc T.Token)) (With Loc) type Grammar r node = E.Grammar r (Prod r (node Loc Text)) token :: T.Token -> Prod r () token = unused . Compose . E.token . pure keyword :: T.Keyword -> Prod r () keyword = token . T.Keyword terminal :: (T.Token -> Maybe a) -> Prod r a terminal f = Compose (E.terminal (\(With loc a) -> fmap (With loc) (f a))) tokenConstructor :: forall name inner r. AsConstructor' name T.Token inner => Prod r inner tokenConstructor = terminal (match @name) bracketed :: T.BracketKind -> Prod r output -> Prod r output bracketed kind inner = do token (T.Bracket' (T.Bracket kind T.Open)) output <- inner token (T.Bracket' (T.Bracket kind T.Close)) return output separatedBy :: T.Token -> Prod r output -> Prod r [output] separatedBy t element = oneOf [pure [], liftA2 prepend element (zeroOrMore (token t `followedBy` element))] followedBy :: Prod r a -> Prod r b -> Prod r b followedBy = (*>) -- This may seem somewhat surprising -- why do we need to /duplicate/ the location info? Doesn't the Applicative instance handle this for us? -- The explanation is that Applicative only handles combining the sublocations into the location of the final result -- -- but we don't just want the location of the whole tree, we also want the locations of all the sub-nodes! -- So this takes a snapshot of the location for the subnode, and also lets `Applicative` go on combining it into the location of the parent node. located :: Prod r (node Loc Text) -> Prod r (NodeWith node Loc Text) located = Compose . fmap dupLocated . getCompose where dupLocated node = With (getMetadata node) (NodeWith node) nodeRule :: Prod r (node Loc Text) -> Grammar r node nodeRule = fmap Compose . E.rule . getCompose locatedNode :: Prod r (node Loc Text) -> Grammar r (NodeWith node) locatedNode = nodeRule . located -- from tightest to loosest; operators within a group have equal precedence precedenceGroups :: [[BinaryOperator]] precedenceGroups = assert (justIf isWellFormed listOfGroups) where isWellFormed = all exactly1 (enumerate :: [BinaryOperator]) && not (any null listOfGroups) exactly1 op = length (filter (== op) (concat listOfGroups)) == 1 listOfGroups = [map ArithmeticOperator [Mul, Div, Mod], map ArithmeticOperator [Add, Sub], map ComparisonOperator [Less, LessEqual, Greater, GreaterEqual], map ComparisonOperator [Equal, NotEqual], map LogicalOperator [And], map LogicalOperator [Or]] data BinaryOperationList metadata name = SingleExpression (NodeWith Expression metadata name) | BinaryOperation (NodeWith Expression metadata name) BinaryOperator (BinaryOperationList metadata name) deriving Show resolvePrecedences :: BinaryOperationList Loc Text -> NodeWith Expression Loc Text resolvePrecedences binaryOperationList = finalResult where finalResult = case allPrecedencesResolved of SingleExpression expr -> expr list -> bug ("Unresolved binary operator precedence: " ++ prettyShow list) allPrecedencesResolved = foldl' resolveOnePrecedenceLevel binaryOperationList precedenceGroups resolveOnePrecedenceLevel binOpList precedenceGroup = case binOpList of BinaryOperation expr1 op1 (BinaryOperation expr2 op2 rest) | elem op1 precedenceGroup -> resolveOnePrecedenceLevel (BinaryOperation (locatedBinaryOperator expr1 op1 expr2) op2 rest) precedenceGroup | otherwise -> BinaryOperation expr1 op1 (resolveOnePrecedenceLevel (BinaryOperation expr2 op2 rest) precedenceGroup) BinaryOperation expr1 op (SingleExpression expr2) | elem op precedenceGroup -> SingleExpression (locatedBinaryOperator expr1 op expr2) other -> other locatedBinaryOperator expr1 op expr2 = NodeWith (With combinedLoc (BinaryOperator expr1 op expr2)) where combinedLoc = mconcat (map nodeMetadata [expr1, expr2]) expressionGrammar :: Grammar r (NodeWith Expression) expressionGrammar = mdo atom <- (locatedNode . oneOf) [ liftA1 Named (tokenConstructor @"Name"), liftA1 NumberLiteral (tokenConstructor @"Number"), liftA1 TextLiteral (tokenConstructor @"Text"), liftA1 nodeWithout (bracketed T.Round expression) ] call <- (locatedNode . oneOf) [ liftA2 Call call (bracketed T.Round (separatedBy T.Comma expression)), liftA1 nodeWithout atom ] unary <- (locatedNode . oneOf) [ liftA2 UnaryOperator (tokenConstructor @"UnaryOperator") unary, liftA1 nodeWithout call ] binaries <- (nodeRule . oneOf) [ liftA3 BinaryOperation unary (tokenConstructor @"BinaryOperator") binaries, liftA1 SingleExpression unary ] let expression = liftA1 resolvePrecedences binaries return expression blockGrammar :: Grammar r (NodeWith Block) blockGrammar = mdo expression <- expressionGrammar ----------------------------------------------------------- binding <- locatedNode do letvar <- terminal (\case T.Keyword T.K_let -> Just Let; T.Keyword T.K_var -> Just Var; _ -> Nothing) -- TODO prism? name <- tokenConstructor @"Name" token T.EqualsSign rhs <- expression token T.Semicolon return (Binding letvar name rhs) assign <- locatedNode do lhs <- tokenConstructor @"Name" token T.EqualsSign rhs <- expression token T.Semicolon return (Assign lhs rhs) ifthen <- locatedNode do keyword T.K_if cond <- expression body <- block return (IfThen cond body) ifthenelse <- locatedNode do keyword T.K_if cond <- expression body1 <- block keyword T.K_else body2 <- block return (IfThenElse cond body1 body2) forever <- locatedNode do keyword T.K_forever body <- block return (Forever (mapNode (set (field @"exitTarget") (Just "break")) body)) while <- locatedNode do keyword T.K_while cond <- expression body <- block return (While cond (mapNode (set (field @"exitTarget") (Just "break")) body)) ret <- locatedNode do keyword T.K_return arg <- liftA1 head (zeroOrOne expression) token T.Semicolon return (Return "return" arg) break <- locatedNode do keyword T.K_break token T.Semicolon return (Break "break") exprStatement <- locatedNode do expr <- expression token T.Semicolon return (Expression expr) ----------------------------------------------------- statement <- nodeRule (oneOf [binding, assign, ifthen, ifthenelse, forever, while, ret, break, exprStatement]) block <- locatedNode do statements <- bracketed T.Curly (oneOrMore statement) return Block { exitTarget = Nothing, statements } return block typeGrammar :: Grammar r (NodeWith Type) typeGrammar = mdo functionType <- nodeRule do keyword T.K_function parameters <- bracketed T.Round (separatedBy T.Comma type') keyword T.K_returns returns <- type' return (FunctionType parameters returns) type' <- locatedNode (oneOf [liftA1 NamedType (tokenConstructor @"Name"), functionType]) return type' functionGrammar :: Grammar r (NodeWith Function) functionGrammar = do block <- blockGrammar type' <- typeGrammar argument <- locatedNode do argumentName <- tokenConstructor @"Name" token T.Colon argumentType <- type' return Argument { argumentName, argumentType } locatedNode do keyword T.K_function functionName <- tokenConstructor @"Name" arguments <- bracketed T.Round (separatedBy T.Comma argument) returns <- liftA1 head (zeroOrOne (keyword T.K_returns `followedBy` type')) body <- block return Function { functionName, arguments, returns, body = mapNode (set (field @"exitTarget") (Just "return")) body } type AST metadata name = [NodeWith Function metadata name] data Error = Invalid Int [Expected] [With Loc T.Token] | Ambiguous [AST Loc Text] deriving (Generic, Show) parse :: [With Loc T.Token] -> Either Error (AST Loc Text) parse = checkResult . E.fullParses parser where parser = E.parser (liftM oneOrMore (fmap (fmap unWith . getCompose) functionGrammar)) checkResult = \case ([], E.Report a b c) -> Left (Invalid a b c) ([one], _) -> Right one (more, _) -> Left (Ambiguous more) ----------------------------------------------------------------------------- pretty-printing renderBlock :: RenderName name => NodeWith Block metadata name -> P.Document renderBlock block = P.braces (P.nest 4 (P.hardline ++ render block) ++ P.hardline) class RenderName name where renderName :: P.DefinitionOrUse -> name -> P.Document instance RenderName Text where renderName defOrUse name = P.note (P.Identifier (P.IdentInfo name defOrUse P.Unknown False)) (P.pretty name) instance RenderName name => Render (Type metadata name) where listSeparator = ", " render = \case NamedType name -> renderName P.Use name FunctionType parameters returns -> P.keyword "function" ++ P.parens (render parameters) ++ " " ++ P.keyword "returns" ++ " " ++ render returns instance RenderName name => Render (Expression metadata name) where listSeparator = ", " render = \case Named name -> renderName P.Use name Call fn args -> render fn ++ P.parens (render args) NumberLiteral number-> P.number number TextLiteral text -> P.string text UnaryOperator op expr-> P.unaryOperator op ++ render expr BinaryOperator expr1 op expr2 -> render expr1 ++ " " ++ P.binaryOperator op ++ " " ++ render expr2 instance Render BindingType where render = P.keyword . \case Let -> "let" Var -> "var" instance RenderName name => Render (Statement metadata name) where render = \case Binding btype name expr -> render btype ++ " " ++ renderName P.Definition name ++ " " ++ P.defineEquals ++ " " ++ render expr ++ P.semicolon Assign name expr -> renderName P.Use name ++ " " ++ P.assignEquals ++ " " ++ render expr ++ P.semicolon IfThen expr block -> P.keyword "if" ++ " " ++ render expr ++ " " ++ renderBlock block IfThenElse expr block1 block2 -> render (IfThen expr block1) ++ " " ++ P.keyword "else" ++ " " ++ renderBlock block2 Forever block -> P.keyword "forever" ++ " " ++ renderBlock block While expr block -> P.keyword "while" ++ " " ++ render expr ++ " " ++ renderBlock block Return _ maybeExpr -> P.keyword "return" ++ (maybe "" (\expr -> " " ++ render expr) maybeExpr) ++ P.semicolon Break _ -> P.keyword "break" ++ P.semicolon Expression expr -> render expr ++ P.semicolon instance RenderName name => Render (Block metadata name) where render Block { statements } = render statements instance RenderName name => Render (Argument metadata name) where listSeparator = ", " render Argument { argumentName, argumentType } = renderName P.Definition argumentName ++ P.colon ++ " " ++ render argumentType instance RenderName name => Render (Function metadata name) where render Function { functionName, arguments, returns, body } = renderedHead ++ renderedArguments ++ renderedReturns ++ renderedBody where renderedHead = P.keyword "function" ++ " " ++ renderName P.Definition functionName renderedArguments = P.parens (render arguments) renderedReturns = maybe "" (\returnType -> " " ++ P.keyword "returns" ++ " " ++ render returnType) returns renderedBody = P.hardline ++ renderBlock body
glaebhoerl/stageless
src/AST.hs
Haskell
mit
15,229
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} module DBTypes where import Data.Aeson import Data.Aeson.TH import Data.Text import Data.Time.Clock import GHC.Generics import Control.Lens import Types import Price import Models import Database.Persist import Database.Persist.Sql import Data.Serialize import GHC.TypeLits type Tenant = DBTenant type TenantOutput = DBTenant type TenantId = Key DBTenant type UserId = Key DBUser type ProductId = Key DBProduct type UserActivationId = Key DBUserActivation type TenantActivationId = Key DBTenantActivation data Product = Product { getProduct :: Entity DBProduct , getVariants :: [Entity DBVariant]} -- Dummy instance instance ToJSON Product where toJSON = undefined data ProductInput = ProductI { piName :: Text , piDescription :: Text , piCurrency :: Text , piType :: ProductType , piVariants :: [VariantInput] , piProperties :: AppJSON , piCostPrice :: Maybe Price , piComparisonPrice :: Maybe Price , piAdvertisedPrice :: Maybe Price , piURLSlug :: Maybe Text } data VariantInput = VariantI { viName :: Text , viSKU :: Text , viWeightInGrams :: Maybe Double , viWeightDisplayUnit :: Maybe Text , viPrice :: Price } instance Serialize UserId where get = DBUserKey . SqlBackendKey <$> Data.Serialize.get put x = put (unSqlBackendKey $ unDBUserKey x) instance Serialize UTCTime where get = read <$> Data.Serialize.get put x = put (show x) data Session = Session { sessionUserID :: UserId , startTime :: UTCTime } deriving (Show, Generic, Serialize, FromJSON , ToJSON) data DBError = TenantNotFound TenantId | UserNotFound UserId | ProductNotFound ProductId | RoleNotFound (Either RoleId Text) | ViolatesTenantUniqueness (Unique Tenant) | UserAlreadyActive UserId deriving (Eq, Show) data UserCreationError = UserExists Text | TenantDoesn'tExist Text deriving (Eq, Show) data ActivationError = ActivationError data TenantInput = TenantI { _name :: Text , _backofficeDomain :: Text } deriving (Generic) instance FromJSON TenantInput where parseJSON = genericParseJSON (defaultOptions { fieldLabelModifier = Prelude.drop 1}) instance ToJSON TenantInput where toEncoding = genericToEncoding (defaultOptions { fieldLabelModifier = Prelude.drop 1}) toJSON = genericToJSON (defaultOptions { fieldLabelModifier = Prelude.drop 1}) instance HasName TenantInput where name = lens _name (\ti n -> ti { _name = n } ) instance HasBackofficeDomain TenantInput where backofficeDomain = lens _backofficeDomain (\ti bd -> ti { _backofficeDomain = bd } ) data UserType = Input | Regular type family Omittable (state :: UserType) (s :: Symbol) a where Omittable Input "password" a = a Omittable Input _ a = () Omittable Regular "password" a = () Omittable Regular _ a = a class HasTenantID s where tenantID :: Lens' s TenantId class HasUserID s where userID :: Lens' s UserId instance HasTenantID DBUser where tenantID = dBUserTenantID data UserBase (userType :: UserType)= UserB { _userFirstName :: Text , _userLastName :: Text , _userEmail :: Text , _userPhone :: Text , _userUsername :: Text , _userTenantID :: TenantId , _userPassword :: Omittable userType "password" Text , _userStatus :: Omittable userType "status" UserStatus , _userRole :: Omittable userType "role" Role , _userUserID :: Omittable userType "userID" UserId } deriving (Generic) makeLenses ''UserBase instance HasHumanName (UserBase a) where firstName = userFirstName lastName = userLastName instance HasContactDetails (UserBase a) where email = userEmail phone = userPhone instance HasUsername (UserBase a) where username = userUsername instance HasPassword (UserBase Input) where password = userPassword instance HasTenantID (UserBase a) where tenantID = userTenantID instance HasUserID (UserBase Regular) where userID = userUserID deriving instance (Show (Omittable a "password" Text), Show (Omittable a "status" UserStatus), Show (Omittable a "role" Role), Show (Omittable a "userID" UserId)) => Show (UserBase a) type UserInput = UserBase Input type User = UserBase Regular
wz1000/haskell-webapps
ServantPersistent/src/DBTypes.hs
Haskell
mit
4,951
{-| Module : TTN.Model.Translation Description : Model code for Translation. Author : Sam van Herwaarden <samvherwaarden@protonmail.com> -} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module TTN.Model.Translation where import TTN.Model.Article import TTN.Model.Language import TTN.Model.User import Data.Text ( Text ) import Data.Time.Clock ( UTCTime ) import Database.Persist import Database.Persist.Postgresql import Database.Persist.TH import qualified Data.Text as T -- * Translation share [mkPersist sqlSettings, mkMigrate "migrateTranslation"] [persistLowerCase| Translation sql=translations artId ArticleId sql=article_id contrId UserId sql=contributor_id lang Language sql=trans_lang title Text sql=title summary Text Maybe sql=summary body ArticleBody default='[]' sql=body_new created UTCTime default=CURRENT_TIMESTAMP sql=created bodyOld String sql=body Id sql=id deriving Read Show |] entTranslation :: Entity Translation -> Translation entTranslation (Entity _ t) = t getArticlesTranslatedToLang :: Language -> SqlPersistM [Entity Article] getArticlesTranslatedToLang lang = rawSql query [toPersistValue lang] where query = T.unwords [ "SELECT DISTINCT ?? FROM translations" , "INNER JOIN articles" , "ON translations.article_id = articles.id" , "WHERE translations.trans_lang = ?" ] getTranslationsInLangs :: [Language] -> SqlPersistM [Entity Translation] getTranslationsInLangs langs = rawSql query $ map toPersistValue langs where holes = T.intercalate "," . take (length langs) $ repeat "?" query = T.unwords [ "SELECT ??" , "FROM ( SELECT DISTINCT ON (a.id)" , "a.created AS a_created, t.* " , "FROM translations AS t" , "INNER JOIN articles AS a" , "ON t.article_id = a.id" , "WHERE t.trans_lang IN (" , holes , ")" , "ORDER BY a.id, t.created DESC) translations" , "ORDER BY translations.a_created DESC" ]
samvher/translatethenews
app/TTN/Model/Translation.hs
Haskell
mit
2,816
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2018.M04.D04.Solution where {-- So you have the data from the last two day's exercises, let's start storing those data into a PostgreSQL database. Today's exercise is to store just the authors. But there's a catch: you have to consider you're doing this as a daily upload. So: are there authors already stored? If so we don't store them, if not, we DO store them and get back the unique ID associated with those authors (for eventual storage in an article_author join table. First, fetch all the authors already stored (with, of course their unique ids) --} import Control.Monad.State import Data.Aeson import qualified Data.Map as Map import qualified Data.Set as Set import Data.Tuple (swap) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.ToRow -- we will use previous techniques for memoizing tables: -- below imports available via 1HaskellADay git repository import Data.LookupTable import Data.MemoizingTable (MemoizingS, MemoizingTable(MT)) import qualified Data.MemoizingTable as MT import Store.SQL.Util.Indexed import Store.SQL.Util.LookupTable import Y2018.M04.D02.Solution hiding (idx) import Y2018.M04.D03.Solution import Y2018.M04.D05.Solution -- looking forward in time, m'kay -- 1. fetch the authors into a LookupTable then convert that into a memoizing -- table state {-- >>> json <- readJSON arts >>> (Success arties) = (fromJSON json) :: Result [Article] >>> ci <- connectInfo "WPJ" >>> conn <- connect ci --} authorTableName :: String authorTableName = "author" lookupAuthors :: Connection -> IO LookupTable lookupAuthors = flip lookupTable authorTableName {-- >>> auths <- lookupAuthors conn fromList [] --} type MemoizedAuthors m = MemoizingS m Integer Author () lk2MS :: Monad m => LookupTable -> MemoizedAuthors m lk2MS table = put (MT.start (map swap $ Map.toList table), Map.empty) -- 2. from yesterday's exercise, triage the authors into the memoizing table addNewAuthors :: Monad m => [Author] -> MemoizedAuthors m addNewAuthors = MT.triageM 5 -- because '5' is a nice number -- 3. store the new memoizing table values into the author table authorStmt :: Query authorStmt = [sql|INSERT INTO author (author) VALUES (?) returning id|] data AuthorVal = AV Author instance ToRow AuthorVal where toRow (AV x) = [toField x] insertAuthors :: Connection -> MemoizedAuthors IO insertAuthors conn = get >>= \(mt@(MT _ _ news), _) -> let authors = Set.toList news auths = map AV authors in if null auths then return () else lift ((returning conn authorStmt auths) :: IO [Index]) >>= \idxen -> put (MT.update (zip (map idx idxen) authors) mt, Map.empty) {-- >>> execStateT (addNewAuthors (Map.elems $ authors arties) >> insertAuthors conn) (MT.start (map swap $ Map.toList auths), Map.empty) (MT {fromTable = fromList [(1,"Ahmed H. Adam"),(2,"Jonathan Cristol")], readIndex = fromList [("Ahmed H. Adam",1),("Jonathan Cristol",2)], newValues = fromList []},fromList []) >>> close conn $ select * from author; id author -------------- 1 Ahmed H. Adam 2 Jonathan Cristol --} -- and there we go for today! Have at it!
geophf/1HaskellADay
exercises/HAD/Y2018/M04/D04/Solution.hs
Haskell
mit
3,329
module Tiling.A295229Spec (main, spec) where import Test.Hspec import Tiling.A295229 (a295229) main :: IO () main = hspec spec spec :: Spec spec = describe "A295229" $ it "correctly computes the first 10 elements" $ take 10 (map a295229 [1..]) `shouldBe` expectedValue where expectedValue = [1, 6, 84, 8548, 4203520, 8590557312, 70368815480832, 2305843028004192256, 302231454912728264605696, 158456325028538104598816096256]
peterokagey/haskellOEIS
test/Tiling/A295229Spec.hs
Haskell
apache-2.0
438
module Permutations.A330858 (a330858, a330858T) where import Permutations.A068424 (a068424T) import Data.MemoCombinators (memo2, integral) a330858T :: Integer -> Integer -> Integer a330858T = memo2 integral integral a330858T' where a330858T' n k | n == 0 = 1 | n <= k = product [1..n] | otherwise = n * a330858T (n-1) k - a068424T (n-1) k * a330858T (n-k-1) k a330858_row :: Integer -> [Integer] a330858_row n = map (a330858T n) [1..n] a330858_list :: [Integer] a330858_list = concatMap a330858_row [1..] a330858 :: Int -> Integer a330858 n = a330858_list !! (n - 1)
peterokagey/haskellOEIS
src/Permutations/A330858.hs
Haskell
apache-2.0
591
-- logging feature implemented with do syntax import Control.Monad.Writer -- be careful: the code does not compile correctly logNumber :: Int -> Writer [String] Int logNumber x = Writer (x, ["Got number: " ++ show x]) multWithLog :: Writer [String] Int multWithLog = do a <- logNumber 3 b <- logNumber 5 return (a*b)
Oscarzhao/haskell
learnyouahaskell/monads/log_with_do.hs
Haskell
apache-2.0
323
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {----------------------------------------------------------------- This files provides functions to convert parsed JSON responses of type Jvalue to other Haskell Types that we use. All functions in this module are pure. So, all error reporting is done using (Either MercadoException a). No synchronous (imprecise) exception should ever be thrown from within this module. This is a tighter match than a naïve Aeson implementation. I have found a few bugs in their API through this tighter coupling: - Order of parameters is not important - For safety, these lists will be sorted (even if they already are): - asks are sorted by increasing price - bids are sorted by decreasing price I don't know what will happen to the trading algorithms if they are not! So, we must ensure that. - We also ensure that prices and volumes are non-negative numbers ------------------------------------------------------------------} module Mercado.Internals ( module Mercado.Internals , parse ) where import Text.Read (readMaybe) import Data.List import Data.Word import Data.Function import qualified Data.HashMap.Strict as Map import Razao.Util import JsonParser import Mercado.Types data MercadoAPIType = GetInfo | GetOrder | OrderList | CancelOrder | WithdrawCoin | PlaceSellOrder | PlaceBuyOrder | MercadoListBook instance Show MercadoAPIType where -- v3 show PlaceSellOrder = "place_sell_order" show PlaceBuyOrder = "place_buy_order" show MercadoListBook = "list_orderbook" show CancelOrder = "cancel_order" show OrderList = "list_orders" show GetInfo = "get_account_info" show GetOrder = "get_order" show WithdrawCoin = "withdraw_coin" {- little reminder: data Jvalue = Jobject (Map.HashMap String Jvalue) | Jarray [Jvalue] | Jstring String -- terminals | Jnumber Double | Jbool Bool | Jnull deriving Show parse :: String -> Jvalue -} ------------------------------------------------ getMercadoResponseTime :: Jvalue -> Maybe Timestamp getMercadoResponseTime (Jobject dict) = Map.lookup "server_unix_timestamp" dict >>= getString >>= readMaybe >>= maybePositive getMercadoResponseTime _ = Nothing ------------------------------------------------ type MercadoDataParser a = Timestamp -> Jvalue -> Either MercadoException a convertMercadoResponse :: MercadoDataParser a -> Jvalue -> (Either MercadoException a) convertMercadoResponse parser resp@(Jobject dict) = let mRespStatus = Map.lookup "status_code" dict mResponseData = Map.lookup "response_data" dict mTime = getMercadoResponseTime resp in case (mRespStatus, mTime, mResponseData) of (Just (Jnumber 100), Just t , Just jResponseData) -> parser t jResponseData (Just (Jnumber 100), Just _ , Nothing ) -> Left (BadResponseStructure $ "Missing response data: " ++ show resp) (Just (Jnumber 100), Nothing, _ ) -> Left (BadResponseStructure $ "Bad or missing server_unix_timestamp: " ++ show resp) (Nothing , _ , _ ) -> Left (BadResponseStructure $ "Missing status code: " ++ show resp) (Just (Jnumber 200), _ , _ ) -> Left (OtherError $ show resp) (Just (Jnumber 201), _ , _ ) -> Left (Invalid_TAPI_ID $ show resp) (Just (Jnumber 202), _ , _ ) -> Left (Invalid_TAPI_MAC $ show resp) (Just (Jnumber 203), _ , _ ) -> Left (Invalid_Tonce $ show resp) (Just (Jnumber 204), _ , _ ) -> Left (Invalid_TAPI_Method $ show resp) (Just (Jnumber 205), _ , _ ) -> Left (InvalidCoinPair $ show resp) (Just (Jnumber 206), _ , _ ) -> Left (InvalidParameter $ show resp) (Just (Jnumber 207), _ , _ ) -> Left (InsufficientFunds $ show resp) (Just (Jnumber 208), _ , _ ) -> Left (InvalidOrder $ show resp) (Just (Jnumber 209), _ , _ ) -> Left (UntrustedWalletAddress $ show resp) (Just (Jnumber 210), _ , _ ) -> Left (BRLWithdrawalFailure $ show resp) (Just (Jnumber 211), _ , _ ) -> Left (InvalidForReadOnlyKey $ show resp) (Just (Jnumber 212), _ , _ ) -> Left (OrderAlreadyDone $ show resp) (Just (Jnumber 213), _ , _ ) -> Left (UntrustedBankAccount $ show resp) (Just (Jnumber 214), _ , _ ) -> Left (OtherError $ show resp) (Just (Jnumber 215), _ , _ ) -> Left (NotEnoughBitcoins $ show resp) (Just (Jnumber 216), _ , _ ) -> Left (NotEnoughLitecoins $ show resp) (Just (Jnumber 217), _ , _ ) -> Left (BRLWithdrawalLimitReached $ show resp) (Just (Jnumber 218), _ , _ ) -> Left (BTCWithdrawalLimitReached $ show resp) (Just (Jnumber 219), _ , _ ) -> Left (OtherError $ show resp) (Just (Jnumber 220), _ , _ ) -> Left (BTCWithdrawalTooSmall $ show resp) (Just (Jnumber 221), _ , _ ) -> Left (LTCWithdrawalTooSmall $ show resp) (Just (Jnumber 222), _ , _ ) -> Left (BTCVolumeTooSmall $ show resp) (Just (Jnumber 223), _ , _ ) -> Left (LTCVolumeTooSmall $ show resp) (Just (Jnumber 224), _ , _ ) -> Left (BelowMiminumPrice $ show resp) (Just (Jnumber 225), _ , _ ) -> Left (OtherError $ show resp) (Just (Jnumber 226), _ , _ ) -> Left (OtherError $ show resp) (Just (Jnumber 227), _ , _ ) -> Left (TooMuchPrecision $ show resp) (Just (Jnumber 429), _ , _ ) -> Left (MaxRequestRateExceeded $ show resp) (Just (Jnumber 500), _ , _ ) -> Left (InternalServerError $ show resp) (Just (Jnumber _ ), _ , _ ) -> Left (OtherError $ "Unknown status code: " ++ show resp) (Just _ , _ , _ ) -> Left (BadResponseStructure $ "Bad status code: " ++ show resp) -- Finally, we have an error if response is not a dictionary convertMercadoResponse _parser resp = Left (BadResponseStructure $ "Response: " ++ show resp) badFormatWrapper :: (Timestamp -> Jvalue -> Maybe a) -> Timestamp -> Jvalue -> Either MercadoException a badFormatWrapper parser time jval = case parser time jval of Nothing -> Left $ BadResponseStructure (show jval) Just x -> Right $ x ------------------------------------------------ -- functions to convert orderbooks convertMercadoBook :: (Ord p, Fractional p, Fractional v) => Timestamp -> Jvalue -> Maybe (MercadoBook p v) convertMercadoBook _ (Jobject dict) = do jBook <- Map.lookup "orderbook" dict case jBook of Jobject book -> do Jarray jasks <- Map.lookup "asks" book Jarray jbids <- Map.lookup "bids" book jLatestOid <- Map.lookup "latest_order_id" book oid' <- getNumber jLatestOid -- FIX ME! This fails due to lack of precision in 'Double' if OID > 2^52 oid <- maybePositive oid' as <- mapM makeMercadoAsk jasks bs <- mapM makeMercadoBid jbids return (QuoteBook { bids = sortBy (flip (compare `on` price)) bs --flip inverts order , asks = sortBy (compare `on` price) as , counter = OID 0 (round oid :: Word64) }) _ -> Nothing convertMercadoBook _ _ = Nothing ------------------------------------------------ type QuoteMaker p v = Jvalue -> Maybe (MercadoQuote p v) makeMercadoAsk :: (Fractional p, Fractional v) => QuoteMaker p v makeMercadoAsk = makeMercadoQuote toAsk makeMercadoBid :: (Fractional p, Fractional v) => QuoteMaker p v makeMercadoBid = makeMercadoQuote toBid type ToBidOrAsk p v = Double -> Double -> OrderID -> Bool -> MercadoQuote p v toBid :: (Fractional p, Fractional v) => Double -> Double -> OrderID -> Bool -> MercadoQuote p v toBid p v oid flag = Quote {side = Bid, price = realToFrac p, volume = realToFrac v, qtail=(oid, flag)} toAsk :: (Fractional p, Fractional v) => Double -> Double -> OrderID -> Bool -> MercadoQuote p v toAsk p v oid flag = Quote {side = Ask, price = realToFrac p, volume = realToFrac v, qtail=(oid, flag)} makeMercadoQuote :: ToBidOrAsk p v -> QuoteMaker p v makeMercadoQuote bidask (Jobject dict) = do jOid <- Map.lookup "order_id" dict oid' <- getNumber jOid -- FIX ME! This fails due to lack of precision in 'Double' if OID > 2^52 oid <- maybePositive oid' jPrice <- Map.lookup "limit_price" dict p' <- jStringToNumber jPrice p <- maybePositive p' jVol <- Map.lookup "quantity" dict v' <- jStringToNumber jVol v <- maybePositive v' jIsMine <- Map.lookup "is_owner" dict isMine <- getBool jIsMine return (bidask p v (OID 0 (round oid :: Word64)) isMine ) makeMercadoQuote _ _ = Nothing ------------------------------------------------------------------------------ convertLimitOrderResp :: (Fractional v, Fractional p) => Timestamp -> Jvalue -> Maybe (Order p v (Confirmation p v), [Fill p v]) convertLimitOrderResp _ (Jobject dict) = do jOrder <- Map.lookup "order" dict convertMercadoLimitOrder jOrder convertLimitOrderResp _ _ = Nothing ------------------------------------------------------------------------------ convertGetOrderResp :: (Fractional v, Fractional p) => Timestamp -> Jvalue -> Maybe [(Order p v (Confirmation p v), [Fill p v])] convertGetOrderResp _ (Jobject dict) = do jOrders <- Map.lookup "orders" dict case jOrders of Jarray jOrds -> mapM convertMercadoLimitOrder jOrds _ -> Nothing convertGetOrderResp _ _ = Nothing ------------------------------------------------------------------------------ -- | This functions converts the Jvalue representing a single Order. convertMercadoLimitOrder :: (Fractional v, Fractional p) => Jvalue -> Maybe (Order p v (Confirmation p v), [Fill p v]) convertMercadoLimitOrder (Jobject dict) = do jOid <- Map.lookup "order_id" dict jPair <- Map.lookup "coin_pair" dict jSide <- Map.lookup "order_type" dict jStatus <- Map.lookup "status" dict jHasFill<- Map.lookup "has_fills" dict jPrice <- Map.lookup "limit_price" dict jVolume <- Map.lookup "quantity" dict jExePri <- Map.lookup "executed_price_avg" dict jExeVol <- Map.lookup "executed_quantity" dict jFee <- Map.lookup "fee" dict jTime <- Map.lookup "created_timestamp" dict jUpdated<- Map.lookup "updated_timestamp" dict jFills <- Map.lookup "operations" dict case (jOid, jPair, jSide, jStatus, jHasFill, jPrice, jVolume, jExePri, jExeVol, jFee, jTime, jUpdated, jFills) of ( Jnumber orderID' , Jstring _coinPair , Jnumber nSide , Jnumber nStatus , Jbool hasFills , Jstring sPrice , Jstring sVolume , Jstring sExePri , Jstring sExeVol , Jstring _sFee -- ignored for now , Jstring sTime , Jstring _sUpdated -- ignored for now , Jarray jOps ) -> do let mStatus = case nStatus of 2 -> case hasFills of {False -> Just Active; True -> Just ActivePartiallyExecuted} 3 -> Just Inactive 4 -> Just Inactive _ -> Nothing price' <- (readMaybe sPrice :: Maybe Double) volume' <- (readMaybe sVolume :: Maybe Double) exePrice' <- (readMaybe sExePri :: Maybe Double) exeVolume' <- (readMaybe sExeVol :: Maybe Double) time' <- (readMaybe sTime :: Maybe Double) -- must be non-negative otherwise abort lOrderID <- maybePositive orderID' let oid = (OID 0 $ truncate lOrderID) price <- maybePositive price' volume <- maybePositive volume' exePrice <- maybePositive exePrice' exeVolume <- maybePositive exeVolume' time <- maybePositive time' fills <- mapM (convertMercadoOperation oid) jOps let requestedVolume = realToFrac volume executedVolume = realToFrac exeVolume mSide = case nSide of { 1 -> Just Bid; 2 -> Just Ask; _ -> Nothing } case (mSide,mStatus) of (_ , Nothing) -> Nothing -- invalid status field in response (Nothing , _) -> Nothing -- invalid order_type field in response (Just side, Just status) -> return ( LimitOrder { oSide = side , limitPrice = realToFrac price , limitVolume = requestedVolume , aConfirmation = Conf{ orderID = oid , mTimestamp = Just (truncate time) -- FIX ME! This should really be "updated_timestamp" (but this has other ramifications) , mOrderStatus = Just status , mExecuted = Just (realToFrac exePrice, executedVolume)} }, fills) _ -> Nothing convertMercadoLimitOrder _ = Nothing ------------------------------------------------------------------------------- -- | This functions converts the Jvalue representing a single Operation. convertMercadoOperation :: (Fractional p, Fractional v) => OrderID -> Jvalue -> Maybe (Fill p v) convertMercadoOperation oid (Jobject dict) = do jFID <- Map.lookup "operation_id" dict jPrice <- Map.lookup "price" dict jVol <- Map.lookup "quantity" dict jFeeRate <- Map.lookup "fee_rate" dict jTime <- Map.lookup "executed_timestamp" dict case (jFID,jPrice,jVol,jFeeRate,jTime) of (Jnumber fid', Jstring sPrice, Jstring sVol, Jstring sRate, Jstring sTime) -> do price' <- (readMaybe sPrice :: Maybe Double) vol' <- (readMaybe sVol :: Maybe Double) rate' <- (readMaybe sRate :: Maybe Double) time' <- (readMaybe sTime :: Maybe Double) price <- maybePositive price' vol <- maybePositive vol' rate <- maybePositive rate' time <- maybePositive time' return Fill { fillID = truncate fid' , fillPrice = realToFrac price , fillVolume = realToFrac vol , fillFee = realToFrac (0.01 * rate * price * vol) , mFillTime = Just (round time) , orderId = oid } _ -> Nothing convertMercadoOperation _ _ = Nothing ------------------------------------------------------------------------------ convertMercadoGetInfoResp :: Timestamp -> Jvalue -> Maybe (CurrencyVol BRL, Vol BTC, Vol LTC, Timestamp) convertMercadoGetInfoResp t (Jobject dict) = do jBalance <- Map.lookup "balance" dict jLimits <- Map.lookup "withdrawal_limits" dict case (jBalance,jLimits) of (Jobject balDict, Jobject _) -> do jReais <- Map.lookup "brl" balDict jBitcoins <- Map.lookup "btc" balDict jLTCs <- Map.lookup "ltc" balDict case (jReais, jBitcoins, jLTCs) of (Jobject realDict, Jobject btcDict, Jobject ltcDict) -> do jReaisAvail <- Map.lookup "available" realDict jBTCsAvail <- Map.lookup "available" btcDict jLTCsAvail <- Map.lookup "available" ltcDict case (jReaisAvail, jBTCsAvail, jLTCsAvail) of (Jstring sBRL, Jstring sBTC, Jstring sLTC) -> do brlFunds' <- (readMaybe sBRL :: Maybe Double) btcFunds' <- (readMaybe sBTC :: Maybe Double) ltcFunds' <- (readMaybe sLTC :: Maybe Double) brlFunds <- maybePositive brlFunds' -- must be non-negative btcFunds <- maybePositive btcFunds' -- otherwise abort ltcFunds <- maybePositive ltcFunds' -- otherwise abort return (realToFrac brlFunds, realToFrac btcFunds, realToFrac ltcFunds, t) _ -> Nothing _ -> Nothing _ -> Nothing convertMercadoGetInfoResp _ _ = Nothing ------------------------------------------------------------------------------ convertMercadoWithdrawalResponse :: (Fractional vol) => Timestamp -> Jvalue -> Maybe (MercadoTransfer vol) convertMercadoWithdrawalResponse _ (Jobject wDict) = do jWithdrawal <- Map.lookup "withdrawal" wDict case jWithdrawal of Jobject dict -> do jSt <- Map.lookup "status" dict jCoin <- Map.lookup "coin" dict jVol <- Map.lookup "quantity" dict jFee <- Map.lookup "fee" dict jWallet <- Map.lookup "address" dict jTime <- Map.lookup "created_timestamp" dict jId <- Map.lookup "id" dict _ <- Map.lookup "tx" dict _ <- Map.lookup "updated_timestamp" dict _ <- Map.lookup "description" dict case (jSt,jCoin,jVol,jFee,jWallet,jTime,jId) of (Jnumber st, Jstring _, Jstring sVol, Jstring sFee, Jstring sWallet, Jstring sTime, Jnumber tid') -> do if st /= 1 && st /= 2 then Nothing else do vol' <- (readMaybe sVol :: Maybe Double) vol <- maybePositive vol' fee' <- (readMaybe sFee :: Maybe Double) fee <- maybePositive fee' time'<- (readMaybe sTime :: Maybe Double) time <- maybePositive time' _ <- maybePositive tid' -- Mercado id not the bitcoin transaction id, not recording it. return MercadoTransfer { transfTime = truncate time , transfVol = realToFrac vol -- fee NOT included , transfFee = realToFrac fee -- this is also debited from account , toWallet = Wallet sWallet , mTransferID = Nothing } _ -> Nothing _ -> Nothing convertMercadoWithdrawalResponse _ _ = Nothing ------------------------------------------------------------------------------ convertMercadoTrades :: (Fractional p, Fractional v) => Jvalue -> Maybe [MercadoTrade p v] convertMercadoTrades (Jarray trades) = mapM convertMercadoTrade trades convertMercadoTrades _ = Nothing convertMercadoTrade :: (Fractional p, Fractional v) => Jvalue -> Maybe (MercadoTrade p v) convertMercadoTrade (Jobject dict) = do jTime <- Map.lookup "date" dict jPrice <- Map.lookup "price" dict jVol <- Map.lookup "amount" dict jTid <- Map.lookup "tid" dict jSide <- Map.lookup "type" dict case (jTime, jPrice, jVol, jTid, jSide) of (Jnumber time', Jnumber price', Jnumber vol', Jnumber tid', Jstring sSide) -> do time <- maybePositive time' price <- maybePositive price' vol <- maybePositive vol' tid <- maybePositive tid' side <- case sSide of "buy" -> Just Bid "sell" -> Just Ask _ -> Nothing return $ MT { tradeTime = truncate time , tradeSide = side , tradePrice = realToFrac price , tradeVolume = realToFrac vol , tradeId = truncate tid } _ -> Nothing convertMercadoTrade _ = Nothing
dimitri-xyz/mercado-bitcoin
src/Mercado/Internals.hs
Haskell
bsd-3-clause
20,014
module Experiments.MonadT.ErrorIO where import Control.Monad.Except import System.Random getRandomNumber :: IO Int getRandomNumber = randomRIO (0, 20) data RandError = RandError Int String deriving (Show) type ErrorIO a = ExceptT RandError IO a errIfOdd :: ErrorIO Int errIfOdd = do n <- lift getRandomNumber if (n `mod` 2) == 1 then throwError $ RandError n "odd number error" else return n errIfOver :: Int -> ErrorIO Int errIfOver lim = do n <- lift getRandomNumber if n > lim then throwError $ RandError n "over limit" else return n errIfUnder :: Int -> ErrorIO Int errIfUnder lim = do n <- lift getRandomNumber if n < lim then throwError $ RandError n "under limit" else return n getSomeNumbers :: ErrorIO [Int] getSomeNumbers = do n1 <- errIfOdd n2 <- errIfOver 10 n3 <- errIfUnder 10 return [n1, n2, n3] getSomeNumbersEither :: IO (Either RandError [Int]) getSomeNumbersEither = runExceptT getSomeNumbers alwaysPass :: ErrorIO [Int] alwaysPass = do n1 <- errIfOver 30 n2 <- errIfUnder 0 n3 <- errIfOver 30 return [n1, n2, n3] alwaysPassEither :: IO (Either RandError [Int]) alwaysPassEither = runExceptT alwaysPass alwaysFail :: ErrorIO [Int] alwaysFail = do n1 <- errIfOver 30 n2 <- errIfUnder 0 n3 <- errIfOver 0 return [n1, n2, n3] alwaysFailEither :: IO (Either RandError [Int]) alwaysFailEither = runExceptT alwaysFail
rumblesan/haskell-experiments
src/Experiments/MonadT/ErrorIO.hs
Haskell
bsd-3-clause
1,440
module Exercises109 where fibs :: Num a => [a] fibs = 1 : scanl (+) 1 fibs fibsN :: Num a => Int -> a fibsN x = fibs !! x -- 1. fibs20 = take 20 fibs -- 2. fibsUnder100 = takeWhile (< 100) fibs -- 3. fact :: (Num a, Enum a) => [a] fact = scanl (*) 1 [1..] factN x = fact !! x
pdmurray/haskell-book-ex
src/ch10/Exercises10.9.hs
Haskell
bsd-3-clause
282
{-# LANGUAGE OverloadedStrings #-} module Security ( tokens , credential ) where import Web.Twitter.Conduit import Web.Authenticate.OAuth tokens :: OAuth tokens = twitterOAuth { oauthConsumerKey = "YOUR CONSUMER KEY" , oauthConsumerSecret = "YOUR CONSUMER SECRET" } credential :: Credential credential = Credential [ ("oauth_token", "YOUR ACCESS TOKEN") , ("oauth_token_secret", "YOUR ACCESS TOKEN SECRET") ]
jmct/PubBot
Security.hs
Haskell
bsd-3-clause
458
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS -ddump-splices #-} import Language.Haskell.TH.ExpandSyns import Language.Haskell.TH import Language.Haskell.TH.Syntax import Util import Types main = do putStrLn "Basic test..." $(mkTest [t| forall a. Show a => a -> ForAll [] -> (Int,ApplyToInteger []) |] -- GHC 7.8 always seems to consider the body of 'ForallT' to have a 'PlainTV', -- whereas it always has a 'KindedTV' with GHC 7.10 (in both cases, it doesn't appear -- to matter whether the definition of 'ForAll' is actually written with a kind signature). #if MIN_VERSION_template_haskell(2,10,0) [t| forall a. Show a => a -> (forall (x :: *). [] x) -> (Int,[] Integer) |] #else [t| forall a. Show a => a -> (forall x. [] x) -> (Int,[] Integer) |] #endif ) putStrLn "Variable capture avoidance test..." $(let -- See comment about 'PlainTV'/'KindedTV' above #if MIN_VERSION_template_haskell(2,10,0) y_0 = KindedTV (mkName "y_0") StarT #else y_0 = PlainTV (mkName "y_0") #endif expectedExpansion = forallT [y_0] (cxt []) (conT ''Either `appT` varT' "y" `appT` varT' "y_0" --> conT ''Int) -- the naive (and wrong) result would be: -- forall y. (forall y. Either y y -> Int) in mkTest (forallT'' ["y"] (conT' "E" `appT` varT' "y")) (forallT'' ["y"] expectedExpansion)) putStrLn "Testing that it doesn't crash on type families (expanding them is not supported yet)" $(let t = [t| (DF1 Int, TF1 Int, AT1 Int) |] in mkTest t t) putStrLn "Testing that the args of type family applications are handled" $(mkTest [t| (DF1 Int', TF1 Int', AT1 Int') |] [t| (DF1 Int, TF1 Int, AT1 Int) |]) putStrLn "Higher-kinded synonym" $(mkTest [t| Either' (ListOf Int') (ListOf Char) |] [t| Either [Int] [Char] |]) putStrLn "Nested" $(mkTest [t| Int'' |] [t| Int |])
seereason/th-expand-syns
testing/Main.hs
Haskell
bsd-3-clause
2,189
module Spec.Constant where import Data.Word(Word32, Word64) data Constant = Constant { cName :: String , cValueString :: String , cValue :: ConstantValue , cComment :: Maybe String } deriving (Show) data ConstantValue = -- | An integral value with no specific size IntegralValue Integer | -- | A value ending in 'f' FloatValue Float | -- A value sized with 'U' Word32Value Word32 | -- A value sized with 'ULL' Word64Value Word64 deriving (Show)
oldmanmike/vulkan
generate/src/Spec/Constant.hs
Haskell
bsd-3-clause
693
-- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- {-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} -- | Module that translates from the UntypedFeld program from the middleend to -- the module format in the backend. module Feldspar.Compiler.Imperative.FromCore ( fromCore , fromCoreM , fromCoreExp , getCore' ) where import qualified Data.Map as Map import Data.Char (toLower) import Data.List (nub, find, isPrefixOf) import Data.Maybe (isJust, fromJust, mapMaybe) import Control.Monad.RWS import Control.Monad.State import Control.Applicative import Feldspar.Core.Types import Feldspar.Core.UntypedRepresentation ( Term(..), Lit(..), collectLetBinders, collectBinders , UntypedFeldF(App, LetFun), Fork(..) ) import qualified Feldspar.Core.UntypedRepresentation as Ut import Feldspar.Core.Middleend.FromTyped import Feldspar.Compiler.Backend.C.Platforms (extend, c99) import Feldspar.Core.Constructs (SyntacticFeld) import Feldspar.Core.Frontend (reifyFeldM) import qualified Feldspar.Compiler.Imperative.Representation as Rep (Variable(..), Type(..), ScalarType(..)) import Feldspar.Compiler.Imperative.Representation ( ActualParameter(..), Block(..), Declaration(..), Entity(..) , Expression(..), Module(..), Program(..), Pattern(..), ParType(..) , Constant(..), typeof, fv ) import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation import Feldspar.Compiler.Backend.C.Options (Options(..)) import Feldspar.Compiler.Backend.C.MachineLowering {- Fast returns ------------ Fast returns really means single return value and that value fits in a register--thus they are platform dependent. This is why we have to compileTypeRep since that can make configuration specific choices about data layout. The user is free to ask for fast returns, but we might not be able to comply. For those cases we flip the option before generating code. -} -- | Get the generated core for a program with a specified output name. fromCore :: SyntacticFeld a => Options -> String -> a -> Module () fromCore opt funname prog = flip evalState 0 $ fromCoreM opt funname prog -- | Get the generated core for a program with a specified output name. fromCoreM :: (MonadState Integer m) => SyntacticFeld a => Options -> String -> a -> m (Module ()) fromCoreM opt funname prog = do s <- get let (ast, s') = flip runState (fromInteger s) $ reifyFeldM (frontendOpts opt) N32 prog uast = untype (frontendOpts opt) ast let opt' | useNativeReturns opt , not $ canFastReturn $ compileTypeRep opt (typeof uast) = opt { useNativeReturns = False } -- Note [Fast returns] | otherwise = opt fastRet = useNativeReturns opt' let (outParam,States s'',results) = runRWS (compileProgTop opt' uast) (initReader opt) $ States $ toInteger s' put s'' let decls = decl results ins = params results post = epilogue results ++ returns Block ds p = block results outDecl = Declaration outParam Nothing paramTypes = getTypes $ outDecl:map (`Declaration` Nothing) ins defs = nub (def results ++ paramTypes) ++ topProc (outs, ds', returns) | fastRet = ( Right outParam, outDecl:ds ++ decls , [call "return" [ValueParameter $ varToExpr outParam]]) | otherwise = ( Left [outParam], ds ++ decls, []) topProc = [Proc funname False ins outs $ Just (Block ds' (Sequence mainProg))] mainProg | Just _ <- find isTask $ def results = call "taskpool_init" [four,four,four] : p : call "taskpool_shutdown" [] : post | otherwise = p:post isTask (Proc{..}) = isPrefixOf "task_core" procName isTask _ = False four = ValueParameter $ ConstExpr $ IntConst 4 $ Rep.NumType Ut.Unsigned Ut.S32 return $ Module defs -- | Get the generated core for a program and an expression that contains the output. The components -- of the result are as follows, in order: -- -- * A list of extra entities needed by the program -- * A list of declarations needed by the program -- * The actual program -- * An expression that contains the result -- * A list of epilogue programs, for freeing memory, etc. fromCoreExp :: (MonadState Integer m) => SyntacticFeld a => Options -> Map.Map Integer String -> a -> m ([Entity ()], [Declaration ()], Program (), Expression (), [Program ()]) fromCoreExp opt aliases prog = do s <- get let (ast, s') = flip runState (fromInteger s) $ reifyFeldM (frontendOpts opt) N32 prog uast = untype (frontendOpts opt) ast mkAlias (Ut.Var i t) = do n <- Map.lookup (toInteger i) aliases return (i, varToExpr $ Rep.Variable (compileTypeRep opt t) n) as = mapMaybe mkAlias $ Ut.fv uast let (expr,States s'',results) = runRWS (compileExpr (CEnv opt False) uast) (Readers as opt) $ States $ toInteger s' put s'' unless (null (params results)) $ error "fromCoreExp: unexpected params" let x = getPlatformRenames opt Block ls p = block results return ( renameEnt opt x <$> def results , renameDecl x <$> (ls ++ decl results) , renameProg opt x p , renameExp x expr , renameProg opt x <$> epilogue results ) -- | Get the generated core for a program. getCore' :: SyntacticFeld a => Options -> a -> Module () getCore' opts = fromCore opts "test" compileProgTop :: Options -> Ut.UntypedFeld -> CodeWriter (Rep.Variable ()) compileProgTop opt (In (Ut.Lambda (Ut.Var v ta) body)) = do let typ = compileTypeRep opt ta (arg,arge) | Rep.StructType{} <- typ = (mkPointer typ v, Deref $ varToExpr arg) | otherwise = (mkVariable typ v, varToExpr arg) tell $ mempty {params=[arg]} withAlias v arge $ compileProgTop opt body compileProgTop opt (In (Ut.App Ut.Let _ [In (Ut.Literal l), In (Ut.Lambda (Ut.Var v _) body)])) | representableType l = do tellDef [ValueDef var c] withAlias v (varToExpr var) $ compileProgTop opt body where var = mkVariable (typeof c) v -- Note [Precise size information] c = literalConst opt l compileProgTop opt a = do let outType' = compileTypeRep opt (typeof a) (outType, outLoc) | useNativeReturns opt = (outType', varToExpr outParam) | otherwise = (Rep.MachineVector 1 (Rep.Pointer outType'), Deref $ varToExpr outParam) outParam = Rep.Variable outType "out" compileProg (cenv0 opt) (Just outLoc) a return outParam {- Precise size information ------------------------ Tight size bounds for a given literal is easy to compute. Precise bounds are particularly important for array literals since they are often copied in the deepCopy function near the CodeGen in the backend. Deepcopy will appear to hang when generating the copy code for insanely large array literals, so don't do that. -} data CompileEnv = CEnv { opts :: Options , inTask :: Bool } -- | Initial environment for compile. cenv0 :: Options -> CompileEnv cenv0 opts = CEnv opts False -- | Compiles code and assigns the expression to the given location. compileExprLoc :: CompileEnv -> Location -> Ut.UntypedFeld -> CodeWriter () compileExprLoc env loc e = do expr <- compileExpr env e assign loc expr -- | Compiles code into a fresh variable. compileProgFresh :: CompileEnv -> Ut.UntypedFeld -> CodeWriter (Expression ()) compileProgFresh env e = do loc <- freshVar (opts env) "e" (typeof e) compileProg env (Just loc) e return loc -- | Compile an expression and make sure that the result is stored in a variable compileExprVar :: CompileEnv -> Ut.UntypedFeld -> CodeWriter (Expression ()) compileExprVar env e = do e' <- compileExpr env e case e' of _ | isNearlyVar e' -> return e' _ -> do varId <- freshId let loc = varToExpr $ mkNamedVar "e" (typeof e') varId declare loc assign (Just loc) e' return loc where isNearlyVar VarExpr{} = True isNearlyVar (Deref a) = isNearlyVar a isNearlyVar (AddrOf a) = isNearlyVar a isNearlyVar _ = False -- | Compile a function bound by a LetFun. compileFunction :: CompileEnv -> Expression () -> (String, Fork, Ut.UntypedFeld) -> CodeWriter () compileFunction env loc (coreName, kind, e) | (bs, e') <- collectBinders e = do es' <- mapM (compileExpr env) (map (In . Ut.Variable) bs) let args = nub $ map exprToVar es' ++ fv loc -- Task core: ((_, ws), Block ds bl) <- confiscateBigBlock $ case kind of Future -> do p' <- compileExprVar env {inTask = True } e' tellProg [iVarPut loc p'] Par -> compileProg env {inTask = True} (Just loc) e' Loop | (_:_) <- es' , Ut.ElementsType{} <- typeof e' -> compileProg env (Just loc) e' | (ix:_) <- es' -> compileProg env (Just $ ArrayElem loc ix) e' None -> compileProg env (Just loc) e' tellDef [Proc coreName (kind == Loop) args (Left []) $ Just $ Block (decl ws ++ ds) bl] -- Task: let taskName = "task" ++ drop 9 coreName runTask = Just $ toBlock $ run coreName args outs = [mkNamedRef "params" Rep.VoidType (-1)] case kind of _ | kind `elem` [None, Loop] -> return () _ -> tellDef [Proc taskName False [] (Left outs) runTask] -- | Create a variable of the right type for storing a length. mkLength :: CompileEnv -> Ut.UntypedFeld -> Ut.Type -> CodeWriter (Expression ()) mkLength env a t | isVariableOrLiteral a = compileExpr env a | otherwise = do lenvar <- freshVar (opts env) "len" t compileProg env (Just lenvar) a return lenvar mkBranch :: CompileEnv -> Location -> Ut.UntypedFeld -> Ut.UntypedFeld -> Maybe Ut.UntypedFeld -> CodeWriter () mkBranch env loc c th el = do ce <- compileExpr env c (_, tb) <- confiscateBlock $ compileProg env loc th (_, eb) <- if isJust el then confiscateBlock $ compileProg env loc (fromJust el) else return (undefined, toBlock Empty) tellProg [Switch ce [(Pat (litB True), tb), (Pat (litB False), eb)]] compileProg :: CompileEnv -> Location -> Ut.UntypedFeld -> CodeWriter () -- Array compileProg env (Just loc) (In (App Ut.Parallel _ [len, In (Ut.Lambda (Ut.Var v ta) ixf)])) = do let ix = mkVar (compileTypeRep (opts env) ta) v len' <- mkLength env len ta (ptyp, b) <- case ixf of In (App (Ut.Call Loop n) _ vs) -> do vs' <- mapM (compileExpr env) vs let mkV w = Rep.Variable (typeof w) (lName w) args = map (ValueParameter . varToExpr) $ nub $ map mkV vs' ++ fv loc return $ (TaskParallel, toBlock $ ProcedureCall n args) _ -> do b' <- confiscateBlock $ compileProg env (Just $ ArrayElem loc ix) ixf return (Parallel, snd b') tellProg [initArray (Just loc) len'] tellProg [for ptyp (lName ix) (litI32 0) len' (litI32 1) b] compileProg env loc (In (App Ut.Sequential _ [len, init', In (Ut.Lambda (Ut.Var v tix) ixf1)])) | In (Ut.Lambda (Ut.Var s tst) l) <- ixf1 , (bs, In (Ut.App Ut.Tup2 _ [In (Ut.Variable t1), In (Ut.Variable t2)])) <- collectLetBinders l , not $ null bs , (e, step) <- last bs , t1 == e , t2 == e = do blocks <- mapM (confiscateBlock . compileBind env) (init bs) let (dss, lets) = unzip $ map (\(_, Block ds (Sequence body)) -> (ds, body)) blocks let ix = mkVar (compileTypeRep (opts env) tix) v len' <- mkLength env len tix st1 <- freshVar (opts env) "st" tst let st = mkRef (compileTypeRep (opts env) tst) s st_val = Deref st declareAlias st (_, Block ds (Sequence body)) <- confiscateBlock $ withAlias s st_val $ compileProg env (ArrayElem <$> loc <*> pure ix) step withAlias s st_val $ compileProg env (Just st1) init' tellProg [ Assign (Just st) (AddrOf st1) , initArray loc len'] tellProg [toProg $ Block (concat dss ++ ds) $ for Sequential (lName ix) (litI32 0) len' (litI32 1) $ toBlock $ Sequence (concat lets ++ body ++ maybe [] (\arr -> [Assign (Just st) $ AddrOf (ArrayElem arr ix)]) loc)] compileProg env loc (In (App Ut.Sequential _ [len, st, In (Ut.Lambda (Ut.Var v t) (In (Ut.Lambda (Ut.Var s _) step)))])) = do let tr' = typeof step let ix = mkVar (compileTypeRep (opts env) t) v len' <- mkLength env len t tmp <- freshVar (opts env) "seq" tr' (_, Block ds (Sequence body)) <- confiscateBlock $ withAlias s (StructField tmp "member2") $ compileProg env (Just tmp) step tellProg [initArray loc len'] compileProg env (Just $ StructField tmp "member2") st tellProg [toProg $ Block ds $ for Sequential (lName ix) (litI32 0) len' (litI32 1) $ toBlock $ Sequence $ body ++ [copyProg (ArrayElem <$> loc <*> pure ix) [StructField tmp "member1"] ]] compileProg env loc (In (App Ut.Append _ [a, b])) = do a' <- compileExpr env a b' <- compileExpr env b tellProg [copyProg loc [a', b']] compileProg env loc (In (App Ut.SetIx _ [arr, i, a])) = do compileProg env loc arr i' <- compileExpr env i compileProg env (ArrayElem <$> loc <*> pure i') a compileProg env (Just loc) (In (App Ut.GetIx _ [arr, i])) = do a' <- compileExpr env arr i' <- compileExpr env i let el = ArrayElem a' i' tellProg $ if isArray $ typeof el then [Assign (Just loc) el] else [copyProg (Just loc) [el]] compileProg env loc (In (App Ut.SetLength _ [len, arr])) = do len' <- compileExpr env len compileProg env loc arr tellProg [setLength loc len'] -- Binding compileProg _ _ e@(In Ut.Lambda{}) = error ("Can only compile top-level lambda: " ++ show e) compileProg env loc (In (Ut.App Ut.Let _ [a, In (Ut.Lambda (Ut.Var v ta) body)])) = do e <- compileLet env a ta v withAlias v e $ compileProg env loc body -- Bits -- Complex -- Condition compileProg env loc (In (App Ut.Condition _ [cond, tHEN, eLSE])) = mkBranch env loc cond tHEN $ Just eLSE compileProg env loc (In (App Ut.ConditionM _ [cond, tHEN, eLSE])) = mkBranch env loc cond tHEN $ Just eLSE -- Conversion -- Elements compileProg env loc (In (App Ut.EMaterialize _ [len, arr])) = do len' <- mkLength env len (Ut.typeof len) tellProg [initArray loc len'] compileProg env loc arr compileProg env (Just loc) (In (App Ut.EWrite _ [ix, e])) = do dst <- compileExpr env ix compileProg env (Just $ ArrayElem loc dst) e compileProg _ _ (In (App Ut.ESkip _ _)) = return () compileProg env loc (In (App Ut.EPar _ [p1, p2])) = do (_, Block ds1 b1) <- confiscateBlock $ compileProg env loc p1 (_, Block ds2 b2) <- confiscateBlock $ compileProg env loc p2 tellProg [toProg $ Block (ds1 ++ ds2) (Sequence [b1,b2])] compileProg env (Just loc) (In (App Ut.EparFor _ [len, In (Ut.Lambda (Ut.Var v ta) ixf)])) = do let ix = mkVar (compileTypeRep (opts env) ta) v len' <- mkLength env len ta (ptyp, b) <- case ixf of In (App (Ut.Call Loop n) _ vs) -> do vs' <- mapM (compileExpr env) vs let mkV w = Rep.Variable (typeof w) (lName w) args = map (ValueParameter . varToExpr) $ nub $ map mkV vs' ++ fv loc return $ (TaskParallel, toBlock $ ProcedureCall n args) _ -> do b' <- confiscateBlock $ compileProg env (Just loc) ixf return (Parallel, snd b') tellProg [for ptyp (lName ix) (litI32 0) len' (litI32 1) b] -- Error compileProg _ _ (In (App Ut.Undefined _ _)) = return () compileProg env loc (In (App (Ut.Assert msg) _ [cond, a])) = do compileAssert env cond msg compileProg env loc a -- Future compileProg _ _ e@(In (App Ut.MkFuture _ _)) = error ("Unexpected MkFuture:" ++ show e) compileProg env (Just loc) (In (LetFun f e)) = do compileFunction env loc f compileProg env (Just loc) e compileProg env loc (In (App Ut.Await _ [a])) = do fut <- compileExprVar env a tellProg [iVarGet (inTask env) l fut | Just l <- [loc]] -- Literal compileProg env loc (In (Ut.Literal a)) = case loc of Just l -> literalLoc (opts env) l a Nothing -> return () -- Logic -- Loop compileProg env (Just loc) (In (App Ut.ForLoop _ [len, init', In (Ut.Lambda (Ut.Var ix ta) (In (Ut.Lambda (Ut.Var st _) ixf)))])) = do let ix' = mkVar (compileTypeRep (opts env) ta) ix len' <- mkLength env len ta (lstate, stvar) <- mkDoubleBufferState loc st compileProg env (Just lstate) init' (_, Block ds body) <- withAlias st lstate $ confiscateBlock $ compileProg env (Just stvar) ixf >> shallowCopyWithRefSwap lstate stvar tellProg [toProg $ Block ds (for Sequential (lName ix') (litI32 0) len' (litI32 1) (toBlock body))] shallowAssign (Just loc) lstate compileProg env (Just loc) (In (App Ut.WhileLoop _ [init', In (Ut.Lambda (Ut.Var cv _) cond), In (Ut.Lambda (Ut.Var bv _) body)])) = do let condv = mkVar (compileTypeRep (opts env) (typeof cond)) cv (lstate,stvar) <- mkDoubleBufferState loc bv compileProg env (Just lstate) init' (_, cond') <- confiscateBlock $ withAlias cv lstate $ compileProg env (Just condv) cond (_, body') <- withAlias bv lstate $ confiscateBlock $ compileProg env (Just stvar) body >> shallowCopyWithRefSwap lstate stvar declare condv tellProg [while cond' condv body'] shallowAssign (Just loc) lstate -- LoopM compileProg env loc (In (App Ut.While _ [cond,step])) = do condv <- freshVar (opts env) "cond" (typeof cond) (_, cond') <- confiscateBlock $ compileProg env (Just condv) cond (_, step') <- confiscateBlock $ compileProg env loc step tellProg [while cond' condv step'] compileProg env loc (In (App Ut.For _ [len, In (Ut.Lambda (Ut.Var v ta) ixf)])) = do let ix = mkVar (compileTypeRep (opts env) ta) v len' <- mkLength env len ta (_, Block ds body) <- confiscateBlock $ compileProg env loc ixf tellProg [toProg $ Block ds (for Sequential (lName ix) (litI32 0) len' (litI32 1) (toBlock body))] -- Mutable compileProg env loc (In (App Ut.Run _ [ma])) = compileProg env loc ma compileProg env loc (In (App Ut.Return t [a])) | Ut.MutType Ut.UnitType <- t = return () | Ut.ParType Ut.UnitType <- t = return () | otherwise = compileProg env loc a compileProg env loc (In (App Ut.Bind _ [ma, In (Ut.Lambda (Ut.Var v ta) body)])) | (In (App Ut.ParNew _ _)) <- ma = do let var = mkVar (compileTypeRep (opts env) ta) v declare var tellProg [iVarInit (AddrOf var)] compileProg env loc body | otherwise = do let var = mkVar (compileTypeRep (opts env) ta) v declare var compileProg env (Just var) ma compileProg env loc body compileProg env loc (In (App Ut.Then _ [ma, mb])) = do compileProg env Nothing ma compileProg env loc mb compileProg env loc (In (App Ut.When _ [c, action])) = mkBranch env loc c action Nothing -- MutableArray compileProg env loc (In (App Ut.NewArr _ [len, a])) = do nId <- freshId let var = mkNamedVar "i" (Rep.MachineVector 1 (Rep.NumType Ut.Unsigned Ut.S32)) nId ix = varToExpr var a' <- compileExpr env a l <- compileExpr env len tellProg [initArray loc l] tellProg [for Sequential (Rep.varName var) (litI32 0) l (litI32 1) $ toBlock (Sequence [copyProg (ArrayElem <$> loc <*> pure ix) [a']])] compileProg env loc (In (App Ut.NewArr_ _ [len])) = do l <- compileExpr env len tellProg [initArray loc l] compileProg env loc (In (App Ut.GetArr _ [arr, i])) = do arr' <- compileExpr env arr i' <- compileExpr env i assign loc (ArrayElem arr' i') compileProg env _ (In (App Ut.SetArr _ [arr, i, a])) = do arr' <- compileExpr env arr i' <- compileExpr env i a' <- compileExpr env a assign (Just $ ArrayElem arr' i') a' -- MutableReference compileProg env loc (In (App Ut.NewRef _ [a])) = compileProg env loc a compileProg env loc (In (App Ut.GetRef _ [r])) = compileProg env loc r compileProg env _ (In (App Ut.SetRef _ [r, a])) = do var <- compileExpr env r compileProg env (Just var) a compileProg env _ (In (App Ut.ModRef _ [r, In (Ut.Lambda (Ut.Var v _) body)])) = do var <- compileExpr env r withAlias v var $ compileProg env (Just var) body -- Since the modifier function is pure it is safe to alias -- v with var here -- MutableToPure compileProg env (Just loc) (In (App Ut.RunMutableArray _ [marr])) | (In (App Ut.Bind _ [In (App Ut.NewArr_ _ [l]), In (Ut.Lambda (Ut.Var v _) body)])) <- marr , (In (App Ut.Return _ [In (Ut.Variable (Ut.Var r _))])) <- chaseBind body , v == r = do len <- compileExpr env l tellProg [setLength (Just loc) len] withAlias v loc $ compileProg env (Just loc) body compileProg env loc (In (App Ut.RunMutableArray _ [marr])) = compileProg env loc marr compileProg env loc (In (App Ut.WithArray _ [marr@(In Ut.Variable{}), In (Ut.Lambda (Ut.Var v _) body)])) = do e <- compileExpr env marr withAlias v e $ do b <- compileExpr env body tellProg [copyProg loc [b]] compileProg env loc (In (App Ut.WithArray _ [marr, In (Ut.Lambda (Ut.Var v ta) body)])) = do let var = mkVar (compileTypeRep (opts env) ta) v declare var compileProg env (Just var) marr e <- compileExpr env body tellProg [copyProg loc [e]] -- Noinline compileProg _ (Just _) (In (App Ut.NoInline _ [e])) = error ("Unexpected NoInline:" ++ show e) -- Par compileProg env loc (In (App Ut.ParRun _ [p])) = compileProg env loc p compileProg _ _ (In (App Ut.ParNew _ _)) = return () compileProg env loc (In (App Ut.ParGet _ [r])) = do iv <- compileExpr env r tellProg [iVarGet (inTask env) l iv | Just l <- [loc]] compileProg env _ (In (App Ut.ParPut _ [r, a])) = do iv <- compileExpr env r val <- compileExpr env a i <- freshId let var = varToExpr $ mkNamedVar "msg" (typeof val) i declare var assign (Just var) val tellProg [iVarPut iv var] compileProg _ _ (In (App Ut.ParFork _ [e])) = error ("Unexpected ParFork:" ++ show e) compileProg _ _ (In (App Ut.ParYield _ _)) = return () -- SizeProp compileProg env loc (In (App Ut.PropSize _ [e])) = compileProg env loc e -- SourceInfo compileProg env loc (In (App (Ut.SourceInfo info) _ [a])) = do tellProg [Comment True info] compileProg env loc a -- Switch compileProg env loc (In (App Ut.Switch _ [tree@(In (App Ut.Condition _ [In (App Ut.Equal _ [_, s]), _, _]))])) = do scrutinee <- compileExpr env s alts <- chaseTree env loc s tree tellProg [Switch{..}] compileProg env loc (In (App Ut.Switch _ [tree])) = compileProg env loc tree -- Tuple compileProg env loc (In (App Ut.Tup2 _ [m1, m2])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env loc (In (App Ut.Tup3 _ [m1, m2, m3])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env loc (In (App Ut.Tup4 _ [m1, m2, m3, m4])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env loc (In (App Ut.Tup5 _ [m1, m2, m3, m4, m5])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env loc (In (App Ut.Tup6 _ [m1, m2, m3, m4, m5, m6])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env loc (In (App Ut.Tup7 _ [m1, m2, m3, m4, m5, m6, m7])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env loc (In (App Ut.Tup8 _ [m1, m2, m3, m4, m5, m6, m7, m8])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env loc (In (App Ut.Tup9 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env loc (In (App Ut.Tup10 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env loc (In (App Ut.Tup11 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env (StructField <$> loc <*> pure "member11") m11 compileProg env loc (In (App Ut.Tup12 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env (StructField <$> loc <*> pure "member11") m11 compileProg env (StructField <$> loc <*> pure "member12") m12 compileProg env loc (In (App Ut.Tup13 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env (StructField <$> loc <*> pure "member11") m11 compileProg env (StructField <$> loc <*> pure "member12") m12 compileProg env (StructField <$> loc <*> pure "member13") m13 compileProg env loc (In (App Ut.Tup14 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env (StructField <$> loc <*> pure "member11") m11 compileProg env (StructField <$> loc <*> pure "member12") m12 compileProg env (StructField <$> loc <*> pure "member13") m13 compileProg env (StructField <$> loc <*> pure "member14") m14 compileProg env loc (In (App Ut.Tup15 _ [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15])) = do compileProg env (StructField <$> loc <*> pure "member1") m1 compileProg env (StructField <$> loc <*> pure "member2") m2 compileProg env (StructField <$> loc <*> pure "member3") m3 compileProg env (StructField <$> loc <*> pure "member4") m4 compileProg env (StructField <$> loc <*> pure "member5") m5 compileProg env (StructField <$> loc <*> pure "member6") m6 compileProg env (StructField <$> loc <*> pure "member7") m7 compileProg env (StructField <$> loc <*> pure "member8") m8 compileProg env (StructField <$> loc <*> pure "member9") m9 compileProg env (StructField <$> loc <*> pure "member10") m10 compileProg env (StructField <$> loc <*> pure "member11") m11 compileProg env (StructField <$> loc <*> pure "member12") m12 compileProg env (StructField <$> loc <*> pure "member13") m13 compileProg env (StructField <$> loc <*> pure "member14") m14 compileProg env (StructField <$> loc <*> pure "member15") m15 -- Special case foreign imports since they can be of void type and just have effects. compileProg env loc (In (App p@Ut.ForeignImport{} t es)) = do es' <- mapM (compileExpr env) es tellProg [Assign loc $ fun' (compileTypeRep (opts env) t) (compileOp p) es'] -- Common nodes compileProg env (Just loc) (In (App (Ut.Call f name) _ es)) = do es' <- mapM (compileExpr env) es let args = nub $ map exprToVar es' ++ fv loc tellProg [iVarInitCond f (AddrOf loc)] tellProg [spawn f name args] compileProg env loc e = compileExprLoc env loc e compileExpr :: CompileEnv -> Ut.UntypedFeld -> CodeWriter (Expression ()) -- Array compileExpr env (In (App Ut.GetLength _ [a])) = do aExpr <- compileExpr env a return $ arrayLength aExpr compileExpr env (In (App Ut.GetIx _ [arr, i])) = do a' <- compileExpr env arr i' <- compileExpr env i return $ ArrayElem a' i' -- Bits compileExpr env (In (App Ut.Bit t [arr])) = do a' <- compileExpr env arr let t' = compileTypeRep (opts env) t return $ binop t' "<<" (litI t' 1) a' -- Binding compileExpr env (In (Ut.Variable (Ut.Var v t))) = do env' <- ask case lookup v (alias env') of Nothing -> return $ mkVar (compileTypeRep (opts env) t) v Just e -> return e compileExpr env (In (Ut.App Ut.Let _ [a, In (Ut.Lambda (Ut.Var v ta) body)])) = do e <- compileLet env a ta v withAlias v e $ compileExpr env body -- Bits -- Condition -- Conversion compileExpr env (In (App Ut.F2I t es)) = do es' <- mapM (compileExpr env) es let f' = fun (Rep.MachineVector 1 Rep.FloatType) "truncf" es' return $ Cast (compileTypeRep (opts env) t) f' compileExpr env (In (App Ut.I2N t1 [e])) | (Rep.MachineVector 1 (Rep.ComplexType t)) <- t' = do e' <- compileExpr env e let args = [Cast t e', litF 0] return $ fun t' (extend c99 "complex" t) args | otherwise = do e' <- compileExpr env e return $ Cast t' e' where t' = compileTypeRep (opts env) t1 compileExpr env (In (App Ut.B2I t [e])) = do e' <- compileExpr env e return $ Cast (compileTypeRep (opts env) t) e' compileExpr env (In (App Ut.Round t es)) = do es' <- mapM (compileExpr env) es let f' = fun (Rep.MachineVector 1 Rep.FloatType) "roundf" es' return $ Cast (compileTypeRep (opts env) t) f' compileExpr env (In (App Ut.Ceiling t es)) = do es' <- mapM (compileExpr env) es let f' = fun (Rep.MachineVector 1 Rep.FloatType) "ceilf" es' return $ Cast (compileTypeRep (opts env) t) f' compileExpr env (In (App Ut.Floor t es)) = do es' <- mapM (compileExpr env) es let f' = fun (Rep.MachineVector 1 Rep.FloatType) "floorf" es' return $ Cast (compileTypeRep (opts env) t) f' -- Error compileExpr env (In (App (Ut.Assert msg) _ [cond, a])) = do compileAssert env cond msg compileExpr env a -- Eq -- FFI -- Floating compileExpr _ (In (App Ut.Pi _ [])) = error "No pi ready" -- Fractional -- Future -- Literal compileExpr env (In (Ut.Literal l)) = literal (opts env) l -- Loop -- Logic -- Mutable compileExpr env (In (App Ut.Run _ [ma])) = compileExpr env ma -- MutableArray compileExpr env (In (App Ut.ArrLength _ [arr])) = do a' <- compileExpr env arr return $ arrayLength a' -- MutableReference compileExpr env (In (App Ut.GetRef _ [r])) = compileExpr env r -- NoInline -- Num -- Ord -- SizeProp compileExpr env (In (App Ut.PropSize _ [e])) = compileExpr env e -- SourceInfo compileExpr env (In (App (Ut.SourceInfo info) _ [a])) = do tellProg [Comment True info] compileExpr env a -- Tuple compileExpr env (In (App p _ [tup])) | p `elem` [ Ut.Sel1, Ut.Sel2, Ut.Sel3, Ut.Sel4, Ut.Sel5, Ut.Sel6, Ut.Sel7 , Ut.Sel8, Ut.Sel9, Ut.Sel10, Ut.Sel11, Ut.Sel12, Ut.Sel13 , Ut.Sel14, Ut.Sel15] = do tupExpr <- compileExpr env tup return $ StructField tupExpr ("member" ++ drop 3 (show p)) compileExpr env e@(In (App p _ _)) | p `elem` [ Ut.Parallel, Ut.SetLength, Ut.Sequential, Ut.Condition, Ut.ConditionM , Ut.MkFuture, Ut.Await, Ut.Bind, Ut.Then, Ut.Return, Ut.While, Ut.For, Ut.SetArr, Ut.EMaterialize , Ut.WhileLoop, Ut.ForLoop, Ut.RunMutableArray, Ut.NoInline , Ut.Switch, Ut.WithArray, Ut.Tup2, Ut.Tup3, Ut.Tup4, Ut.Tup5 , Ut.Tup6, Ut.Tup7, Ut.Tup8, Ut.Tup9, Ut.Tup10, Ut.Tup11, Ut.Tup11 , Ut.Tup12, Ut.Tup13, Ut.Tup14, Ut.Tup15] = compileProgFresh env e compileExpr env (In (App p t es)) = do es' <- mapM (compileExpr env) es return $ fun' (compileTypeRep (opts env) t) (compileOp p) es' compileExpr env e = compileProgFresh env e compileLet :: CompileEnv -> Ut.UntypedFeld -> Ut.Type -> Integer -> CodeWriter (Expression ()) compileLet env a ta v = do let var = mkVar (compileTypeRep (opts env) ta) v declare var compileProg env (Just var) a return var compileAssert :: CompileEnv -> Ut.UntypedFeld -> String -> CodeWriter () compileAssert env cond msg = do condExpr <- compileExpr env cond tellProg [call "assert" [ValueParameter condExpr]] unless (null msg) $ tellProg [Comment False $ "{" ++ msg ++ "}"] literal :: Options -> Ut.Lit -> CodeWriter (Expression ()) literal opt t@LUnit = return (ConstExpr $ literalConst opt t) literal opt t@LBool{} = return (ConstExpr $ literalConst opt t) literal opt t@LInt{} = return (ConstExpr $ literalConst opt t) literal opt t@LFloat{} = return (ConstExpr $ literalConst opt t) literal opt t@LDouble{} = return (ConstExpr $ literalConst opt t) literal opt t@LComplex{} = return (ConstExpr $ literalConst opt t) literal opt t@LArray{} = return (ConstExpr $ literalConst opt t) literal opt t = do loc <- freshVar opt "x" (typeof t) literalLoc opt loc t return loc -- | Returns true if we can represent the literal in Program. representableType :: Ut.Lit -> Bool representableType l | Ut.ArrayType{} <- t = True -- Simple types. | Ut.IntType{} <- t = True | Ut.ComplexType{} <- t = True | otherwise = t `elem` [Ut.UnitType, Ut.DoubleType, Ut.FloatType, Ut.BoolType] where t = typeof l literalConst :: Options -> Ut.Lit -> Constant () literalConst _ LUnit = IntConst 0 (Rep.NumType Ut.Unsigned Ut.S32) literalConst _ (LBool a) = BoolConst a literalConst _ (LInt s sz a) = IntConst (toInteger a) (Rep.NumType s sz) literalConst _ (LFloat a) = FloatConst a literalConst _ (LDouble a) = DoubleConst a literalConst opt (LArray t es) = ArrayConst (map (literalConst opt) es) $ compileTypeRep opt t literalConst opt (LComplex r i) = ComplexConst (literalConst opt r) (literalConst opt i) literalLoc :: Options -> Expression () -> Ut.Lit -> CodeWriter () literalLoc opt loc arr@Ut.LArray{} = tellProg [copyProg (Just loc) [ConstExpr $ literalConst opt arr]] literalLoc env loc (Ut.LTup2 ta tb) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env loc (Ut.LTup3 ta tb tc) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env loc (Ut.LTup4 ta tb tc td) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env loc (Ut.LTup5 ta tb tc td te) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env loc (Ut.LTup6 ta tb tc td te tf) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env loc (Ut.LTup7 ta tb tc td te tf tg) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env loc (Ut.LTup8 ta tb tc td te tf tg th) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env loc (Ut.LTup9 ta tb tc td te tf tg th ti) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env loc (Ut.LTup10 ta tb tc td te tf tg th ti tj) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env loc (Ut.LTup11 ta tb tc td te tf tg th ti tj tk) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env (StructField loc "member11") tk literalLoc env loc (Ut.LTup12 ta tb tc td te tf tg th ti tj tk tl) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env (StructField loc "member11") tk literalLoc env (StructField loc "member12") tl literalLoc env loc (Ut.LTup13 ta tb tc td te tf tg th ti tj tk tl tm) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env (StructField loc "member11") tk literalLoc env (StructField loc "member12") tl literalLoc env (StructField loc "member13") tm literalLoc env loc (Ut.LTup14 ta tb tc td te tf tg th ti tj tk tl tm tn) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env (StructField loc "member11") tk literalLoc env (StructField loc "member12") tl literalLoc env (StructField loc "member13") tm literalLoc env (StructField loc "member14") tn literalLoc env loc (Ut.LTup15 ta tb tc td te tf tg th ti tj tk tl tm tn to) = do literalLoc env (StructField loc "member1") ta literalLoc env (StructField loc "member2") tb literalLoc env (StructField loc "member3") tc literalLoc env (StructField loc "member4") td literalLoc env (StructField loc "member5") te literalLoc env (StructField loc "member6") tf literalLoc env (StructField loc "member7") tg literalLoc env (StructField loc "member8") th literalLoc env (StructField loc "member9") ti literalLoc env (StructField loc "member10") tj literalLoc env (StructField loc "member11") tk literalLoc env (StructField loc "member12") tl literalLoc env (StructField loc "member13") tm literalLoc env (StructField loc "member14") tn literalLoc env (StructField loc "member15") to literalLoc env loc t = do rhs <- literal env t assign (Just loc) rhs chaseTree :: CompileEnv -> Location -> Ut.UntypedFeld -> Ut.UntypedFeld -> CodeWriter [(Pattern (), Block ())] chaseTree env loc _s (In (App Ut.Condition _ [In (App Ut.Equal _ [c, _]), t, f])) -- , alphaEq s a -- TODO check that the scrutinees are equal = do e <- compileExpr env c (_,body) <- confiscateBlock $ compileProg env loc t cases <- chaseTree env loc _s f return $ (Pat e, body) : cases chaseTree env loc _ a = do (_,body) <- confiscateBlock $ compileProg env loc a return [(PatDefault, body)] -- | Chase down the right-spine of `Bind` and `Then` constructs and return -- the last term chaseBind :: Ut.UntypedFeld -> Ut.UntypedFeld chaseBind (In (App Ut.Bind _ [_, In (Ut.Lambda _ body)])) = chaseBind body chaseBind (In (App Ut.Then _ [_, body])) = chaseBind body chaseBind a = a {- NOTES: The trick of doing a copy at the end, i.e. `tellProg [copyProg loc e]`, when compiling WithArray is important. It allows us to safely return the pure array that is passed in as input. This is nice because it allows us to implement `freezeArray` in terms of `withArray`. In most cases I expect `withArray` to return a scalar as its final result and then the copyProg is harmless. -} compileBind :: CompileEnv -> (Ut.Var, Ut.UntypedFeld) -> CodeWriter () compileBind env (Ut.Var v t, e) = do let var = mkVar (compileTypeRep (opts env) t) v declare var compileProg env (Just var) e -- | Translates Op names to strings. compileOp :: Ut.Op -> String -- Bits compileOp Ut.BAnd = "&" compileOp Ut.BOr = "|" compileOp Ut.BXor = "^" -- Complex compileOp Ut.RealPart = "creal" compileOp Ut.ImagPart = "cimag" compileOp Ut.Sign = "signum" -- Eq compileOp Ut.Equal = "==" compileOp Ut.NotEqual = "/=" -- FFI compileOp (Ut.ForeignImport s) = s -- Floating compileOp Ut.Exp = "exp" -- Fractional compileOp Ut.DivFrac = "/" -- Integral compileOp Ut.IExp = "pow" -- Logic compileOp Ut.And = "&&" compileOp Ut.Or = "||" -- Num compileOp Ut.Add = "+" compileOp Ut.Sub = "-" compileOp Ut.Mul = "*" -- Ord compileOp Ut.LTH = "<" compileOp Ut.GTH = ">" compileOp Ut.LTE = "<=" compileOp Ut.GTE = ">=" compileOp p = toLower h:t where (h:t) = show p
emwap/feldspar-compiler
lib/Feldspar/Compiler/Imperative/FromCore.hs
Haskell
bsd-3-clause
50,193
module Main where import System.Exit import System.Environment import System.Console.GetOpt import Control.Monad (forM_, when, unless) import Control.Monad.Trans import Control.Applicative ((<$>)) import Tools.Quarry import Data.Word import Data.List import Data.Maybe import System.IO import System.Process data SubCommand = Init | Import | Set | Get | Find | Tags | Cats | Info | Exist | View deriving (Show,Eq) data InitOpt = InitHelp deriving (Show,Eq) data ImportOpt = ImportHelp | ImportTy ImportType | ImportDate String | ImportTag String | ImportFilename String deriving (Show,Eq) data FindOpt = FindHelp deriving (Show,Eq) data TagOpt = TagHelp | TagCategory String deriving (Show,Eq) data CatsOpt = CatsHelp deriving (Show,Eq) data ExistOpt = ExistHelp | ExistMissing | ExistAlready deriving (Show,Eq) data ViewOpt = ViewHelp deriving (Show,Eq) usage Init = error "usage: quarry init <repository-path>" usage Import = error "usage: quarry import <repository-path> <file>" usage Set = error "usage: quarry set <repository-path> <digest> [+/-tag]" usage Get = error "usage: quarry get <repository-path> <digest>" usage Find = error "usage: quarry find <repository-path> <query>" usage Tags = error "usage: quarry tags [--category <category>] <repository-path> <tag prefix> ..." usage Cats = error "usage: quarry cats <add|list> <repository-path> <cat prefix> ..." usage Exist = error "usage: quarry exists <repository-path> <file> ..." usage Info = error "usage: quarry info <repository-path>" usage View = error "usage: quarry view <repository-path> <digest>" reportOptError errOpts | null errOpts = return () | otherwise = mapM_ (putStrLn . ("parseError: " ++)) errOpts >> exitFailure fromTagArg :: String -> Either TagName Tag fromTagArg s = case break (== ':') s of (_,"") -> Left s (_ ,[':']) -> error "empty tag, expecting 'category:tag', got 'category:'" (cat,':':t) -> Right $ Tag { tagName = t, tagCat = cat } _ -> error "impossible with break" tag s = maybe (error $ "cannot resolve " ++ s) id <$> resolveTag (fromTagArg s) -- create a tag object, automatically filling category to personal if cannot be found. resolveAddTag s = do let t = fromTagArg s r <- resolveTag t case r of Just _ -> return r Nothing -> case t of Left _ -> return $ Just $ Tag { tagName = s, tagCat = "personal" } _ -> return r cmdInit args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (InitHelp `elem` optArgs) $ do usage Init >> exitSuccess reportOptError errOpts case nonOpts of [path] -> initialize True path >> return () _ -> usage Init where options = [ Option ['h'] ["help"] (NoArg InitHelp) "show help" ] -- | import a file cmdImport args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (ImportHelp `elem` optArgs) $ do usage Import >> exitSuccess reportOptError errOpts case nonOpts of [path,file] -> doImport optArgs path file _ -> usage Import where options = [ Option ['h'] ["help"] (NoArg ImportHelp) "show help" , Option ['s'] ["symlink"] (NoArg (ImportTy ImportSymlink)) "use a symlink to import into the hashfs" , Option [] ["hardlink"] (NoArg (ImportTy ImportHardlink)) "use a hardlink to import into the hashfs" , Option ['d'] ["date"] (ReqArg ImportDate "date") "add a date in posix seconds" , Option ['t'] ["tag"] (ReqArg ImportTag "tag") "add a tag" , Option ['f'] ["filename"] (ReqArg ImportFilename "filename") "override the filename" ] hardcodedDataCat = CategoryPersonal doImport optArgs path file = do let (date,tags,mFilename,ity) = foldl (\acc@(d,accTags,accFile,t) f -> case f of ImportTy ty -> (d,accTags,accFile,ty) ImportDate da -> (read da,accTags,accFile,t) ImportTag ta -> (d,ta:accTags,accFile,t) ImportFilename fi -> (d,accTags,Just fi,t) _ -> acc) (0 :: Word64, [], Nothing, ImportCopy) optArgs let mDate = case date of 0 -> Nothing _ -> Just $ fromIntegral date conf <- initialize False path (digest,isNew) <- runQuarry conf $ do addTags <- catMaybes <$> mapM resolveAddTag tags importFile ity hardcodedDataCat mDate (("/old/" ++) `fmap` mFilename) addTags file if isNew then putStrLn (show digest) else hPutStrLn stderr (show digest ++ " already existing ") cmdSet args = case args of path:digest:tagPatches -> doSet path (maybe (error "not a valid digest") id $ readDigest digest) tagPatches _ -> usage Import where doSet path digest tagPatches = do let (addTagArgs, delTagArgs) = foldl readPatch ([], []) tagPatches conf <- initialize False path runQuarry conf $ do --tag s = maybe (error $ "cannot resolve " ++ s) id <$> resolveTag (fromTagArg s) addTags <- catMaybes <$> mapM resolveAddTag addTagArgs delTags <- catMaybes <$> mapM (resolveTag . fromTagArg) delTagArgs liftIO $ putStrLn ("deleting tags: " ++ show delTags) liftIO $ putStrLn ("adding tags: " ++ show addTags) updateDigest digest addTags delTags readPatch (a,d) s = case s of '+':toAdd -> (toAdd:a, d) '-':toRem -> (a, toRem:d) _ -> (a,d) cmdGet _ = error ("get not implemented") cmdFind args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (FindHelp `elem` optArgs) $ do usage Find >> exitSuccess reportOptError errOpts case nonOpts of path:tags -> doFind path tags _ -> usage Find where options = [ Option ['h'] ["help"] (NoArg FindHelp) "show help" ] doFind path tagArgs = do conf <- initialize False path runQuarry conf $ do tags <- mapM tag tagArgs digests <- findDigestWithTags tags liftIO $ mapM_ (putStrLn . show) digests cmdTags args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (TagHelp `elem` optArgs) $ do usage Tags >> exitSuccess reportOptError errOpts case nonOpts of [] -> usage Tags path:l -> doTags optArgs path l where options = [ Option ['h'] ["help"] (NoArg TagHelp) "show help" , Option ['c'] ["category"] (ReqArg TagCategory "category") "restrict tag search to a specific category" ] doTags optArgs path l = do let cat = foldl (\acc f -> case f of TagCategory c -> Just c _ -> acc) Nothing optArgs conf <- initialize False path runQuarry conf $ forM_ l $ \s -> do tags <- findTags (Just s) cat mapM_ (liftIO . putStrLn . show) tags cmdExist args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (ExistHelp `elem` optArgs) $ do usage Exist >> exitSuccess when (ExistMissing `elem` optArgs && ExistAlready `elem` optArgs) $ putStrLn "cannot specify missing and exist at the same time" >> exitFailure reportOptError errOpts case nonOpts of path:f1:fs -> doExist optArgs path (f1:fs) _ -> usage Exist where options = [ Option ['h'] ["help"] (NoArg ExistHelp) "show help" , Option ['m'] ["missing"] (NoArg ExistMissing) "show only missing file from the store" , Option ['e'] ["exist"] (NoArg ExistAlready) "show only already existing file in the store" ] doExist optArgs path filenames = do conf <- initialize False path runQuarry conf $ mapM_ (check optArgs) filenames check optArgs filename = do d <- computeDigest filename x <- exist d liftIO $ do case (ExistAlready `elem` optArgs, ExistMissing `elem` optArgs) of (True, True) -> error "impossible" (False, True) -> when x $ putStrLn filename (True, False) -> unless x $ putStrLn filename (False, False) -> if x then putStrLn (filename ++ " " ++ show d) else putStrLn (filename ++ " MISSING") cmdCats args = do let (optArgs, nonOpts, errOpts) = getOpt Permute options args when (CatsHelp `elem` optArgs) $ do usage Cats >> exitSuccess reportOptError errOpts case nonOpts of [] -> usage Cats "add":path:name:[] -> doCatAdd optArgs path name "list":path:_ -> doCats optArgs path _:_ -> error ("error unknown sub command " ++ show nonOpts ++ " in cats: expected list or add") where options = [ Option ['h'] ["help"] (NoArg CatsHelp) "show help" ] doCatAdd _ path name = do conf <- initialize False path runQuarry conf $ addCategory name doCats _ path = do conf <- initialize False path runQuarry conf $ do cats <- getCategoryTable mapM_ (\(_,(c,a)) -> liftIO $ putStrLn (c ++ " (abstract=" ++ show a ++ ")")) cats cmdInfo args = do case args of path:[] -> doInfo path _ -> usage Import where doInfo path = do conf <- initialize False path info <- runQuarry conf $ getInfo putStrLn ("files : " ++ show (infoNFile info)) putStrLn ("tags : " ++ show (infoNTag info)) putStrLn ("categories : " ++ show (infoNCategory info)) cmdView args = do case args of path:digests -> doView path digests _ -> usage View where doView path digests_ = do let digests = catMaybes $ map readDigest digests_ conf <- initialize False path l <- runQuarry conf $ mapM getPathAndType $ digests forM_ l $ \(p, ty) -> do case ty of QuarryTypeImage -> do ec <- rawSystem "eog" [p] unless (ec == ExitSuccess) $ exitWith ec _ -> putStrLn (show ty ++ " " ++ show p) getPathAndType digest = do path <- getDigestPath digest ty <- getQuarryFileType path return (path, ty) commands = [ ("init" , (cmdInit, "initialize a repository")) , ("import", (cmdImport, "import a file into quarry")) , ("set" , (cmdSet, "set some metadata")) , ("tags" , (cmdTags, "list tags")) , ("cats" , (cmdCats, "list categories")) , ("get" , (cmdGet, "get some metadata")) , ("find" , (cmdFind, "find contents by query")) , ("exist" , (cmdExist, "check if some file already exist")) , ("info" , (cmdInfo, "get quarry general state information")) , ("view" , (cmdView, "use a viewer on digest")) ] main = do args <- getArgs case args of [] -> error ("expecting one subcommand of: " ++ intercalate ", " (map fst commands)) cmd:subArgs -> case lookup cmd commands of Nothing -> error ("unrecognized command: " ++ cmd) Just (fCommand, _) -> fCommand subArgs
vincenthz/quarry
src/Quarry.hs
Haskell
bsd-3-clause
12,085
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Jana.Types ( Array, Stack, Value(..), nil, performOperation, performModOperation, showValueType, typesMatch, truthy, Store, printVdecl, showStore, emptyStore, storeFromList, getRef, getVar, getRefValue, bindVar, unbindVar, setVar, EvalEnv(..), EvalOptions(..), defaultOptions, ProcEnv, emptyProcEnv, procEnvFromList, getProc, Eval, runEval, (<!!>) ) where import Prelude hiding (GT, LT, EQ) import Data.Bits import Data.List (intercalate) import Data.IORef import Control.Monad.State import Control.Monad.Reader import Control.Monad.Except import Text.Printf (printf) import qualified Data.Maybe as Maybe import qualified Data.Map as Map import Text.Parsec.Pos import Jana.Aliases import Jana.Ast import Jana.Error import Jana.ErrorMessages type Array = [Integer] type Stack = [Integer] -- Types of values an expression can evaluate to. data Value = JInt Integer | JBool Bool | JArray Array | JStack Stack deriving (Eq) instance Show Value where show (JInt x) = show x show (JArray xs) = "{" ++ intercalate ", " (map show xs) ++ "}" show (JStack []) = "nil" show (JStack xs) = "<" ++ intercalate ", " (map show xs) ++ "]" showValueType :: Value -> String showValueType (JInt _) = "int" showValueType (JStack _) = "stack" showValueType (JArray _) = "array" showValueType (JBool _) = "bool" typesMatch :: Value -> Value -> Bool typesMatch (JInt _) (JInt _) = True typesMatch (JArray _) (JArray _) = True typesMatch (JStack _) (JStack _) = True typesMatch (JBool _) (JBool _) = True typesMatch _ _ = False nil = JStack [] truthy :: Value -> Bool truthy (JInt 0) = False truthy (JStack []) = False truthy _ = True boolToInt :: Num a => (a -> a -> Bool) -> a -> a -> a boolToInt f x y = if f x y then 1 else 0 wrap :: (a -> Value) -> (Integer -> Integer -> a) -> Integer -> Integer -> Value wrap m f x y = m $ f x y opFunc :: BinOp -> Integer -> Integer -> Value opFunc Add = wrap JInt (+) opFunc Sub = wrap JInt (-) opFunc Mul = wrap JInt (*) opFunc Div = wrap JInt div opFunc Mod = wrap JInt mod opFunc And = wrap JInt (.&.) opFunc Or = wrap JInt (.|.) opFunc Xor = wrap JInt xor opFunc LAnd = undefined -- handled by evalExpr opFunc LOr = undefined -- handled by evalExpr opFunc GT = wrap JBool (>) opFunc LT = wrap JBool (<) opFunc EQ = wrap JBool (==) opFunc NEQ = wrap JBool (/=) opFunc GE = wrap JBool (>=) opFunc LE = wrap JBool (<=) performOperation :: BinOp -> Value -> Value -> SourcePos -> SourcePos -> Eval Value performOperation Div (JInt _) (JInt 0) _ pos = pos <!!> divisionByZero performOperation op (JInt x) (JInt y) _ _ = return $ opFunc op x y performOperation _ (JInt _) val _ pos = pos <!!> typeMismatch ["int"] (showValueType val) performOperation _ val _ pos _ = pos <!!> typeMismatch ["int"] (showValueType val) performModOperation :: ModOp -> Value -> Value -> SourcePos -> SourcePos -> Eval Value performModOperation modOp = performOperation $ modOpToBinOp modOp where modOpToBinOp AddEq = Add modOpToBinOp SubEq = Sub modOpToBinOp XorEq = Xor -- -- Environment -- type Store = Map.Map String (IORef Value) printVdecl :: String -> Value -> String printVdecl name val@(JArray xs) = printf "%s[%d] = %s" name (length xs) (show val) printVdecl name val = printf "%s = %s" name (show val) showStore :: Store -> IO String showStore store = liftM (intercalate "\n") (mapM (\(name, ref) -> liftM (printVdecl name) (readIORef ref)) (Map.toList store)) emptyStore = Map.empty storeFromList :: [(String, IORef Value)] -> Store storeFromList = Map.fromList getRef :: Ident -> Eval (IORef Value) getRef (Ident name pos) = do storeEnv <- get case Map.lookup name storeEnv of Just ref -> return ref Nothing -> pos <!!> unboundVar name getVar :: Ident -> Eval Value getVar id = getRef id >>= liftIO . readIORef getRefValue :: IORef Value -> Eval Value getRefValue = liftIO . readIORef -- Bind a variable name to a new reference bindVar :: Ident -> Value -> Eval () bindVar (Ident name pos) val = do storeEnv <- get ref <- liftIO $ newIORef val case Map.lookup name storeEnv of Nothing -> put $ Map.insert name ref storeEnv Just _ -> pos <!!> alreadyBound name unbindVar :: Ident -> Eval () unbindVar = modify . Map.delete . ident -- Set the value of a variable (modifying the reference) setVar :: Ident -> Value -> Eval () setVar id val = do ref <- getRef id liftIO $ writeIORef ref val data EvalEnv = EE { evalOptions :: EvalOptions , procEnv :: ProcEnv , aliases :: AliasSet } data EvalOptions = EvalOptions { modInt :: Bool, runReverse :: Bool } defaultOptions = EvalOptions { modInt = False, runReverse = False } type ProcEnv = Map.Map String Proc emptyProcEnv = Map.empty procEnvFromList :: [Proc] -> Either JanaError ProcEnv procEnvFromList = foldM insertProc emptyProcEnv where insertProc env p = if Map.notMember (ident p) env then if checkDuplicateArgs (makeIdentList p) then Right (Map.insert (ident p) p env) else Left $ newErrorMessage (ppos p) (procDuplicateArgs p) else Left $ newErrorMessage (ppos p) (procDefined p) ppos Proc { procname = (Ident _ pos) } = pos makeIdentList :: Proc -> [Ident] makeIdentList (Proc {params = params}) = map getVdeclIdent params where getVdeclIdent (Scalar _ id _) = id getVdeclIdent (Array id _ _) = id checkDuplicateArgs :: [Ident] -> Bool checkDuplicateArgs [] = True checkDuplicateArgs ([arg]) = True checkDuplicateArgs (arg:args) = arg `notElem` args && checkDuplicateArgs args getProc :: Ident -> Eval Proc getProc (Ident funName pos) = do when (funName == "main") $ pos <!!> callingMainError procEnv <- asks procEnv case Map.lookup funName procEnv of Just proc -> return proc Nothing -> pos <!!> undefProc funName -- -- Evaluation -- instance Functor Eval where fmap = liftM instance Applicative Eval where pure = return (<*>) = ap -- defined in Control.Monad newtype Eval a = E { runE :: StateT Store (ReaderT EvalEnv (ExceptT JanaError IO)) a } deriving (Monad, MonadIO, MonadError JanaError, MonadReader EvalEnv, MonadState Store) runEval :: Eval a -> Store -> EvalEnv -> IO (Either JanaError (a, Store)) runEval eval store procs = runExceptT (runReaderT (runStateT (runE eval) store) procs) throwJanaError :: SourcePos -> Message -> Eval a throwJanaError pos msg = throwError $ newErrorMessage pos msg infixr 1 <!!> pos <!!> msg = throwJanaError pos msg
tyoko-dev/jana
src/Jana/Types.hs
Haskell
bsd-3-clause
6,785
{- % (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcGenDeriv: Generating derived instance declarations This module is nominally ``subordinate'' to @TcDeriv@, which is the ``official'' interface to deriving-related things. This is where we do all the grimy bindings' generation. -} {-# LANGUAGE CPP, ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module TcGenDeriv ( BagDerivStuff, DerivStuff(..), hasBuiltinDeriving, FFoldType(..), functorLikeTraverse, deepSubtypesContaining, foldDataConArgs, mkCoerceClassMethEqn, gen_Newtype_binds, genAuxBinds, ordOpTbl, boxConTbl, litConTbl, mkRdrFunBind ) where #include "HsVersions.h" import LoadIface( loadInterfaceForName ) import HscTypes( lookupFixity, mi_fix ) import TcRnMonad import HsSyn import RdrName import BasicTypes import Module( getModule ) import DataCon import Name import Fingerprint import Encoding import DynFlags import PrelInfo import FamInstEnv( FamInst ) import PrelNames import THNames import Module ( moduleName, moduleNameString , moduleUnitId, unitIdString ) import MkId ( coerceId ) import PrimOp import SrcLoc import TyCon import TcType import TysPrim import TysWiredIn import Type import Class import TyCoRep import VarSet import VarEnv import State import Util import Var import Outputable import Lexeme import FastString import Pair import Bag import TcEnv (InstInfo) import StaticFlags( opt_PprStyle_Debug ) import ListSetOps ( assocMaybe ) import Data.List ( partition, intersperse ) import Data.Maybe ( catMaybes, isJust ) type BagDerivStuff = Bag DerivStuff data AuxBindSpec = DerivCon2Tag TyCon -- The con2Tag for given TyCon | DerivTag2Con TyCon -- ...ditto tag2Con | DerivMaxTag TyCon -- ...and maxTag deriving( Eq ) -- All these generate ZERO-BASED tag operations -- I.e first constructor has tag 0 data DerivStuff -- Please add this auxiliary stuff = DerivAuxBind AuxBindSpec -- Generics | DerivFamInst FamInst -- New type family instances -- New top-level auxiliary bindings | DerivHsBind (LHsBind RdrName, LSig RdrName) -- Also used for SYB | DerivInst (InstInfo RdrName) -- New, auxiliary instances {- ************************************************************************ * * Class deriving diagnostics * * ************************************************************************ Only certain blessed classes can be used in a deriving clause. These classes are listed below in the definition of hasBuiltinDeriving (with the exception of Generic and Generic1, which are handled separately in TcGenGenerics). A class might be able to be used in a deriving clause if it -XDeriveAnyClass is willing to support it. The canDeriveAnyClass function checks if this is the case. -} hasBuiltinDeriving :: Class -> Maybe (SrcSpan -> TyCon -> TcM (LHsBinds RdrName, BagDerivStuff)) hasBuiltinDeriving clas = assocMaybe gen_list (getUnique clas) where gen_list :: [(Unique, SrcSpan -> TyCon -> TcM (LHsBinds RdrName, BagDerivStuff))] gen_list = [ (eqClassKey, simple gen_Eq_binds) , (ordClassKey, simple gen_Ord_binds) , (enumClassKey, simple gen_Enum_binds) , (boundedClassKey, simple gen_Bounded_binds) , (ixClassKey, simple gen_Ix_binds) , (showClassKey, with_fix_env gen_Show_binds) , (readClassKey, with_fix_env gen_Read_binds) , (dataClassKey, gen_Data_binds) , (functorClassKey, simple gen_Functor_binds) , (foldableClassKey, simple gen_Foldable_binds) , (traversableClassKey, simple gen_Traversable_binds) , (liftClassKey, simple gen_Lift_binds) ] simple gen_fn loc tc = return (gen_fn loc tc) with_fix_env gen_fn loc tc = do { fix_env <- getDataConFixityFun tc ; return (gen_fn fix_env loc tc) } getDataConFixityFun :: TyCon -> TcM (Name -> Fixity) -- If the TyCon is locally defined, we want the local fixity env; -- but if it is imported (which happens for standalone deriving) -- we need to get the fixity env from the interface file -- c.f. RnEnv.lookupFixity, and Trac #9830 getDataConFixityFun tc = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod name then do { fix_env <- getFixityEnv ; return (lookupFixity fix_env) } else do { iface <- loadInterfaceForName doc name -- Should already be loaded! ; return (mi_fix iface . nameOccName) } } where name = tyConName tc doc = text "Data con fixities for" <+> ppr name {- ************************************************************************ * * Eq instances * * ************************************************************************ Here are the heuristics for the code we generate for @Eq@. Let's assume we have a data type with some (possibly zero) nullary data constructors and some ordinary, non-nullary ones (the rest, also possibly zero of them). Here's an example, with both \tr{N}ullary and \tr{O}rdinary data cons. data Foo ... = N1 | N2 ... | Nn | O1 a b | O2 Int | O3 Double b b | ... * For the ordinary constructors (if any), we emit clauses to do The Usual Thing, e.g.,: (==) (O1 a1 b1) (O1 a2 b2) = a1 == a2 && b1 == b2 (==) (O2 a1) (O2 a2) = a1 == a2 (==) (O3 a1 b1 c1) (O3 a2 b2 c2) = a1 == a2 && b1 == b2 && c1 == c2 Note: if we're comparing unlifted things, e.g., if 'a1' and 'a2' are Float#s, then we have to generate case (a1 `eqFloat#` a2) of r -> r for that particular test. * If there are a lot of (more than en) nullary constructors, we emit a catch-all clause of the form: (==) a b = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> case (a# ==# b#) of { r -> r }}} If con2tag gets inlined this leads to join point stuff, so it's better to use regular pattern matching if there aren't too many nullary constructors. "Ten" is arbitrary, of course * If there aren't any nullary constructors, we emit a simpler catch-all: (==) a b = False * For the @(/=)@ method, we normally just use the default method. If the type is an enumeration type, we could/may/should? generate special code that calls @con2tag_Foo@, much like for @(==)@ shown above. We thought about doing this: If we're also deriving 'Ord' for this tycon, we generate: instance ... Eq (Foo ...) where (==) a b = case (compare a b) of { _LT -> False; _EQ -> True ; _GT -> False} (/=) a b = case (compare a b) of { _LT -> True ; _EQ -> False; _GT -> True } However, that requires that (Ord <whatever>) was put in the context for the instance decl, which it probably wasn't, so the decls produced don't get through the typechecker. -} gen_Eq_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Eq_binds loc tycon = (method_binds, aux_binds) where all_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon all_cons -- If there are ten or more (arbitrary number) nullary constructors, -- use the con2tag stuff. For small types it's better to use -- ordinary pattern matching. (tag_match_cons, pat_match_cons) | nullary_cons `lengthExceeds` 10 = (nullary_cons, non_nullary_cons) | otherwise = ([], all_cons) no_tag_match_cons = null tag_match_cons fall_through_eqn | no_tag_match_cons -- All constructors have arguments = case pat_match_cons of [] -> [] -- No constructors; no fall-though case [_] -> [] -- One constructor; no fall-though case _ -> -- Two or more constructors; add fall-through of -- (==) _ _ = False [([nlWildPat, nlWildPat], false_Expr)] | otherwise -- One or more tag_match cons; add fall-through of -- extract tags compare for equality = [([a_Pat, b_Pat], untag_Expr tycon [(a_RDR,ah_RDR), (b_RDR,bh_RDR)] (genPrimOpApp (nlHsVar ah_RDR) eqInt_RDR (nlHsVar bh_RDR)))] aux_binds | no_tag_match_cons = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon method_binds = listToBag [eq_bind, ne_bind] eq_bind = mk_FunBind loc eq_RDR (map pats_etc pat_match_cons ++ fall_through_eqn) ne_bind = mk_easy_FunBind loc ne_RDR [a_Pat, b_Pat] ( nlHsApp (nlHsVar not_RDR) (nlHsPar (nlHsVarApps eq_RDR [a_RDR, b_RDR]))) ------------------------------------------------------------------ pats_etc data_con = let con1_pat = nlConVarPat data_con_RDR as_needed con2_pat = nlConVarPat data_con_RDR bs_needed data_con_RDR = getRdrName data_con con_arity = length tys_needed as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs tys_needed = dataConOrigArgTys data_con in ([con1_pat, con2_pat], nested_eq_expr tys_needed as_needed bs_needed) where nested_eq_expr [] [] [] = true_Expr nested_eq_expr tys as bs = foldl1 and_Expr (zipWith3Equal "nested_eq" nested_eq tys as bs) where nested_eq ty a b = nlHsPar (eq_Expr tycon ty (nlHsVar a) (nlHsVar b)) {- ************************************************************************ * * Ord instances * * ************************************************************************ Note [Generating Ord instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose constructors are K1..Kn, and some are nullary. The general form we generate is: * Do case on first argument case a of K1 ... -> rhs_1 K2 ... -> rhs_2 ... Kn ... -> rhs_n _ -> nullary_rhs * To make rhs_i If i = 1, 2, n-1, n, generate a single case. rhs_2 case b of K1 {} -> LT K2 ... -> ...eq_rhs(K2)... _ -> GT Otherwise do a tag compare against the bigger range (because this is the one most likely to succeed) rhs_3 case tag b of tb -> if 3 <# tg then GT else case b of K3 ... -> ...eq_rhs(K3).... _ -> LT * To make eq_rhs(K), which knows that a = K a1 .. av b = K b1 .. bv we just want to compare (a1,b1) then (a2,b2) etc. Take care on the last field to tail-call into comparing av,bv * To make nullary_rhs generate this case con2tag a of a# -> case con2tag b of -> a# `compare` b# Several special cases: * Two or fewer nullary constructors: don't generate nullary_rhs * Be careful about unlifted comparisons. When comparing unboxed values we can't call the overloaded functions. See function unliftedOrdOp Note [Do not rely on compare] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's a bad idea to define only 'compare', and build the other binary comparisons on top of it; see Trac #2130, #4019. Reason: we don't want to laboriously make a three-way comparison, only to extract a binary result, something like this: (>) (I# x) (I# y) = case <# x y of True -> False False -> case ==# x y of True -> False False -> True So for sufficiently small types (few constructors, or all nullary) we generate all methods; for large ones we just use 'compare'. -} data OrdOp = OrdCompare | OrdLT | OrdLE | OrdGE | OrdGT ------------ ordMethRdr :: OrdOp -> RdrName ordMethRdr op = case op of OrdCompare -> compare_RDR OrdLT -> lt_RDR OrdLE -> le_RDR OrdGE -> ge_RDR OrdGT -> gt_RDR ------------ ltResult :: OrdOp -> LHsExpr RdrName -- Knowing a<b, what is the result for a `op` b? ltResult OrdCompare = ltTag_Expr ltResult OrdLT = true_Expr ltResult OrdLE = true_Expr ltResult OrdGE = false_Expr ltResult OrdGT = false_Expr ------------ eqResult :: OrdOp -> LHsExpr RdrName -- Knowing a=b, what is the result for a `op` b? eqResult OrdCompare = eqTag_Expr eqResult OrdLT = false_Expr eqResult OrdLE = true_Expr eqResult OrdGE = true_Expr eqResult OrdGT = false_Expr ------------ gtResult :: OrdOp -> LHsExpr RdrName -- Knowing a>b, what is the result for a `op` b? gtResult OrdCompare = gtTag_Expr gtResult OrdLT = false_Expr gtResult OrdLE = false_Expr gtResult OrdGE = true_Expr gtResult OrdGT = true_Expr ------------ gen_Ord_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ord_binds loc tycon | null tycon_data_cons -- No data-cons => invoke bale-out case = (unitBag $ mk_FunBind loc compare_RDR [], emptyBag) | otherwise = (unitBag (mkOrdOp OrdCompare) `unionBags` other_ops, aux_binds) where aux_binds | single_con_type = emptyBag | otherwise = unitBag $ DerivAuxBind $ DerivCon2Tag tycon -- Note [Do not rely on compare] other_ops | (last_tag - first_tag) <= 2 -- 1-3 constructors || null non_nullary_cons -- Or it's an enumeration = listToBag (map mkOrdOp [OrdLT,OrdLE,OrdGE,OrdGT]) | otherwise = emptyBag get_tag con = dataConTag con - fIRST_TAG -- We want *zero-based* tags, because that's what -- con2Tag returns (generated by untag_Expr)! tycon_data_cons = tyConDataCons tycon single_con_type = isSingleton tycon_data_cons (first_con : _) = tycon_data_cons (last_con : _) = reverse tycon_data_cons first_tag = get_tag first_con last_tag = get_tag last_con (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon tycon_data_cons mkOrdOp :: OrdOp -> LHsBind RdrName -- Returns a binding op a b = ... compares a and b according to op .... mkOrdOp op = mk_easy_FunBind loc (ordMethRdr op) [a_Pat, b_Pat] (mkOrdOpRhs op) mkOrdOpRhs :: OrdOp -> LHsExpr RdrName mkOrdOpRhs op -- RHS for comparing 'a' and 'b' according to op | length nullary_cons <= 2 -- Two nullary or fewer, so use cases = nlHsCase (nlHsVar a_RDR) $ map (mkOrdOpAlt op) tycon_data_cons -- i.e. case a of { C1 x y -> case b of C1 x y -> ....compare x,y... -- C2 x -> case b of C2 x -> ....comopare x.... } | null non_nullary_cons -- All nullary, so go straight to comparing tags = mkTagCmp op | otherwise -- Mixed nullary and non-nullary = nlHsCase (nlHsVar a_RDR) $ (map (mkOrdOpAlt op) non_nullary_cons ++ [mkHsCaseAlt nlWildPat (mkTagCmp op)]) mkOrdOpAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- Make the alternative (Ki a1 a2 .. av -> mkOrdOpAlt op data_con = mkHsCaseAlt (nlConVarPat data_con_RDR as_needed) (mkInnerRhs op data_con) where as_needed = take (dataConSourceArity data_con) as_RDRs data_con_RDR = getRdrName data_con mkInnerRhs op data_con | single_con_type = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con ] | tag == first_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (ltResult op) ] | tag == last_tag = nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (gtResult op) ] | tag == first_tag + 1 = nlHsCase (nlHsVar b_RDR) [ mkHsCaseAlt (nlConWildPat first_con) (gtResult op) , mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (ltResult op) ] | tag == last_tag - 1 = nlHsCase (nlHsVar b_RDR) [ mkHsCaseAlt (nlConWildPat last_con) (ltResult op) , mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (gtResult op) ] | tag > last_tag `div` 2 -- lower range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) ltInt_RDR tag_lit) (gtResult op) $ -- Definitely GT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (ltResult op) ] | otherwise -- upper range is larger = untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsIf (genPrimOpApp (nlHsVar bh_RDR) gtInt_RDR tag_lit) (ltResult op) $ -- Definitely LT nlHsCase (nlHsVar b_RDR) [ mkInnerEqAlt op data_con , mkHsCaseAlt nlWildPat (gtResult op) ] where tag = get_tag data_con tag_lit = noLoc (HsLit (HsIntPrim "" (toInteger tag))) mkInnerEqAlt :: OrdOp -> DataCon -> LMatch RdrName (LHsExpr RdrName) -- First argument 'a' known to be built with K -- Returns a case alternative Ki b1 b2 ... bv -> compare (a1,a2,...) with (b1,b2,...) mkInnerEqAlt op data_con = mkHsCaseAlt (nlConVarPat data_con_RDR bs_needed) $ mkCompareFields tycon op (dataConOrigArgTys data_con) where data_con_RDR = getRdrName data_con bs_needed = take (dataConSourceArity data_con) bs_RDRs mkTagCmp :: OrdOp -> LHsExpr RdrName -- Both constructors known to be nullary -- genreates (case data2Tag a of a# -> case data2Tag b of b# -> a# `op` b# mkTagCmp op = untag_Expr tycon [(a_RDR, ah_RDR),(b_RDR, bh_RDR)] $ unliftedOrdOp tycon intPrimTy op ah_RDR bh_RDR mkCompareFields :: TyCon -> OrdOp -> [Type] -> LHsExpr RdrName -- Generates nested comparisons for (a1,a2...) against (b1,b2,...) -- where the ai,bi have the given types mkCompareFields tycon op tys = go tys as_RDRs bs_RDRs where go [] _ _ = eqResult op go [ty] (a:_) (b:_) | isUnliftedType ty = unliftedOrdOp tycon ty op a b | otherwise = genOpApp (nlHsVar a) (ordMethRdr op) (nlHsVar b) go (ty:tys) (a:as) (b:bs) = mk_compare ty a b (ltResult op) (go tys as bs) (gtResult op) go _ _ _ = panic "mkCompareFields" -- (mk_compare ty a b) generates -- (case (compare a b) of { LT -> <lt>; EQ -> <eq>; GT -> <bt> }) -- but with suitable special cases for mk_compare ty a b lt eq gt | isUnliftedType ty = unliftedCompare lt_op eq_op a_expr b_expr lt eq gt | otherwise = nlHsCase (nlHsPar (nlHsApp (nlHsApp (nlHsVar compare_RDR) a_expr) b_expr)) [mkHsCaseAlt (nlNullaryConPat ltTag_RDR) lt, mkHsCaseAlt (nlNullaryConPat eqTag_RDR) eq, mkHsCaseAlt (nlNullaryConPat gtTag_RDR) gt] where a_expr = nlHsVar a b_expr = nlHsVar b (lt_op, _, eq_op, _, _) = primOrdOps "Ord" tycon ty unliftedOrdOp :: TyCon -> Type -> OrdOp -> RdrName -> RdrName -> LHsExpr RdrName unliftedOrdOp tycon ty op a b = case op of OrdCompare -> unliftedCompare lt_op eq_op a_expr b_expr ltTag_Expr eqTag_Expr gtTag_Expr OrdLT -> wrap lt_op OrdLE -> wrap le_op OrdGE -> wrap ge_op OrdGT -> wrap gt_op where (lt_op, le_op, eq_op, ge_op, gt_op) = primOrdOps "Ord" tycon ty wrap prim_op = genPrimOpApp a_expr prim_op b_expr a_expr = nlHsVar a b_expr = nlHsVar b unliftedCompare :: RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- What to cmpare -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -- Three results -> LHsExpr RdrName -- Return (if a < b then lt else if a == b then eq else gt) unliftedCompare lt_op eq_op a_expr b_expr lt eq gt = nlHsIf (ascribeBool $ genPrimOpApp a_expr lt_op b_expr) lt $ -- Test (<) first, not (==), because the latter -- is true less often, so putting it first would -- mean more tests (dynamically) nlHsIf (ascribeBool $ genPrimOpApp a_expr eq_op b_expr) eq gt where ascribeBool e = nlExprWithTySig e (toLHsSigWcType boolTy) nlConWildPat :: DataCon -> LPat RdrName -- The pattern (K {}) nlConWildPat con = noLoc (ConPatIn (noLoc (getRdrName con)) (RecCon (HsRecFields { rec_flds = [] , rec_dotdot = Nothing }))) {- ************************************************************************ * * Enum instances * * ************************************************************************ @Enum@ can only be derived for enumeration types. For a type \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} we use both @con2tag_Foo@ and @tag2con_Foo@ functions, as well as a @maxtag_Foo@ variable (all generated by @gen_tag_n_con_binds@). \begin{verbatim} instance ... Enum (Foo ...) where succ x = toEnum (1 + fromEnum x) pred x = toEnum (fromEnum x - 1) toEnum i = tag2con_Foo i enumFrom a = map tag2con_Foo [con2tag_Foo a .. maxtag_Foo] -- or, really... enumFrom a = case con2tag_Foo a of a# -> map tag2con_Foo (enumFromTo (I# a#) maxtag_Foo) enumFromThen a b = map tag2con_Foo [con2tag_Foo a, con2tag_Foo b .. maxtag_Foo] -- or, really... enumFromThen a b = case con2tag_Foo a of { a# -> case con2tag_Foo b of { b# -> map tag2con_Foo (enumFromThenTo (I# a#) (I# b#) maxtag_Foo) }} \end{verbatim} For @enumFromTo@ and @enumFromThenTo@, we use the default methods. -} gen_Enum_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Enum_binds loc tycon = (method_binds, aux_binds) where method_binds = listToBag [ succ_enum, pred_enum, to_enum, enum_from, enum_from_then, from_enum ] aux_binds = listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon] occ_nm = getOccString tycon succ_enum = mk_easy_FunBind loc succ_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsVar (maxtag_RDR tycon), nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "succ" occ_nm "tried to take `succ' of last tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsIntLit 1])) pred_enum = mk_easy_FunBind loc pred_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsIf (nlHsApps eq_RDR [nlHsIntLit 0, nlHsVarApps intDataCon_RDR [ah_RDR]]) (illegal_Expr "pred" occ_nm "tried to take `pred' of first tag in enumeration") (nlHsApp (nlHsVar (tag2con_RDR tycon)) (nlHsApps plus_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsLit (HsInt "-1" (-1))])) to_enum = mk_easy_FunBind loc toEnum_RDR [a_Pat] $ nlHsIf (nlHsApps and_RDR [nlHsApps ge_RDR [nlHsVar a_RDR, nlHsIntLit 0], nlHsApps le_RDR [nlHsVar a_RDR, nlHsVar (maxtag_RDR tycon)]]) (nlHsVarApps (tag2con_RDR tycon) [a_RDR]) (illegal_toEnum_tag occ_nm (maxtag_RDR tycon)) enum_from = mk_easy_FunBind loc enumFrom_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ nlHsApps map_RDR [nlHsVar (tag2con_RDR tycon), nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVar (maxtag_RDR tycon)))] enum_from_then = mk_easy_FunBind loc enumFromThen_RDR [a_Pat, b_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR), (b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_then_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR]) (nlHsIf (nlHsApps gt_RDR [nlHsVarApps intDataCon_RDR [ah_RDR], nlHsVarApps intDataCon_RDR [bh_RDR]]) (nlHsIntLit 0) (nlHsVar (maxtag_RDR tycon)) )) from_enum = mk_easy_FunBind loc fromEnum_RDR [a_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ (nlHsVarApps intDataCon_RDR [ah_RDR]) {- ************************************************************************ * * Bounded instances * * ************************************************************************ -} gen_Bounded_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Bounded_binds loc tycon | isEnumerationTyCon tycon = (listToBag [ min_bound_enum, max_bound_enum ], emptyBag) | otherwise = ASSERT(isSingleton data_cons) (listToBag [ min_bound_1con, max_bound_1con ], emptyBag) where data_cons = tyConDataCons tycon ----- enum-flavored: --------------------------- min_bound_enum = mkHsVarBind loc minBound_RDR (nlHsVar data_con_1_RDR) max_bound_enum = mkHsVarBind loc maxBound_RDR (nlHsVar data_con_N_RDR) data_con_1 = head data_cons data_con_N = last data_cons data_con_1_RDR = getRdrName data_con_1 data_con_N_RDR = getRdrName data_con_N ----- single-constructor-flavored: ------------- arity = dataConSourceArity data_con_1 min_bound_1con = mkHsVarBind loc minBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity minBound_RDR) max_bound_1con = mkHsVarBind loc maxBound_RDR $ nlHsVarApps data_con_1_RDR (nOfThem arity maxBound_RDR) {- ************************************************************************ * * Ix instances * * ************************************************************************ Deriving @Ix@ is only possible for enumeration types and single-constructor types. We deal with them in turn. For an enumeration type, e.g., \begin{verbatim} data Foo ... = N1 | N2 | ... | Nn \end{verbatim} things go not too differently from @Enum@: \begin{verbatim} instance ... Ix (Foo ...) where range (a, b) = map tag2con_Foo [con2tag_Foo a .. con2tag_Foo b] -- or, really... range (a, b) = case (con2tag_Foo a) of { a# -> case (con2tag_Foo b) of { b# -> map tag2con_Foo (enumFromTo (I# a#) (I# b#)) }} -- Generate code for unsafeIndex, because using index leads -- to lots of redundant range tests unsafeIndex c@(a, b) d = case (con2tag_Foo d -# con2tag_Foo a) of r# -> I# r# inRange (a, b) c = let p_tag = con2tag_Foo c in p_tag >= con2tag_Foo a && p_tag <= con2tag_Foo b -- or, really... inRange (a, b) c = case (con2tag_Foo a) of { a_tag -> case (con2tag_Foo b) of { b_tag -> case (con2tag_Foo c) of { c_tag -> if (c_tag >=# a_tag) then c_tag <=# b_tag else False }}} \end{verbatim} (modulo suitable case-ification to handle the unlifted tags) For a single-constructor type (NB: this includes all tuples), e.g., \begin{verbatim} data Foo ... = MkFoo a b Int Double c c \end{verbatim} we follow the scheme given in Figure~19 of the Haskell~1.2 report (p.~147). -} gen_Ix_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Ix_binds loc tycon | isEnumerationTyCon tycon = ( enum_ixes , listToBag $ map DerivAuxBind [DerivCon2Tag tycon, DerivTag2Con tycon, DerivMaxTag tycon]) | otherwise = (single_con_ixes, unitBag (DerivAuxBind (DerivCon2Tag tycon))) where -------------------------------------------------------------- enum_ixes = listToBag [ enum_range, enum_index, enum_inRange ] enum_range = mk_easy_FunBind loc range_RDR [nlTuplePat [a_Pat, b_Pat] Boxed] $ untag_Expr tycon [(a_RDR, ah_RDR)] $ untag_Expr tycon [(b_RDR, bh_RDR)] $ nlHsApp (nlHsVarApps map_RDR [tag2con_RDR tycon]) $ nlHsPar (enum_from_to_Expr (nlHsVarApps intDataCon_RDR [ah_RDR]) (nlHsVarApps intDataCon_RDR [bh_RDR])) enum_index = mk_easy_FunBind loc unsafeIndex_RDR [noLoc (AsPat (noLoc c_RDR) (nlTuplePat [a_Pat, nlWildPat] Boxed)), d_Pat] ( untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(d_RDR, dh_RDR)] ( let rhs = nlHsVarApps intDataCon_RDR [c_RDR] in nlHsCase (genOpApp (nlHsVar dh_RDR) minusInt_RDR (nlHsVar ah_RDR)) [mkHsCaseAlt (nlVarPat c_RDR) rhs] )) ) -- This produces something like `(ch >= ah) && (ch <= bh)` enum_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [a_Pat, b_Pat] Boxed, c_Pat] $ untag_Expr tycon [(a_RDR, ah_RDR)] ( untag_Expr tycon [(b_RDR, bh_RDR)] ( untag_Expr tycon [(c_RDR, ch_RDR)] ( -- This used to use `if`, which interacts badly with RebindableSyntax. -- See #11396. nlHsApps and_RDR [ genPrimOpApp (nlHsVar ch_RDR) geInt_RDR (nlHsVar ah_RDR) , genPrimOpApp (nlHsVar ch_RDR) leInt_RDR (nlHsVar bh_RDR) ] ))) -------------------------------------------------------------- single_con_ixes = listToBag [single_con_range, single_con_index, single_con_inRange] data_con = case tyConSingleDataCon_maybe tycon of -- just checking... Nothing -> panic "get_Ix_binds" Just dc -> dc con_arity = dataConSourceArity data_con data_con_RDR = getRdrName data_con as_needed = take con_arity as_RDRs bs_needed = take con_arity bs_RDRs cs_needed = take con_arity cs_RDRs con_pat xs = nlConVarPat data_con_RDR xs con_expr = nlHsVarApps data_con_RDR cs_needed -------------------------------------------------------------- single_con_range = mk_easy_FunBind loc range_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed] $ noLoc (mkHsComp ListComp stmts con_expr) where stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed mk_qual a b c = noLoc $ mkBindStmt (nlVarPat c) (nlHsApp (nlHsVar range_RDR) (mkLHsVarTuple [a,b])) ---------------- single_con_index = mk_easy_FunBind loc unsafeIndex_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] -- We need to reverse the order we consider the components in -- so that -- range (l,u) !! index (l,u) i == i -- when i is in range -- (from http://haskell.org/onlinereport/ix.html) holds. (mk_index (reverse $ zip3 as_needed bs_needed cs_needed)) where -- index (l1,u1) i1 + rangeSize (l1,u1) * (index (l2,u2) i2 + ...) mk_index [] = nlHsIntLit 0 mk_index [(l,u,i)] = mk_one l u i mk_index ((l,u,i) : rest) = genOpApp ( mk_one l u i ) plus_RDR ( genOpApp ( (nlHsApp (nlHsVar unsafeRangeSize_RDR) (mkLHsVarTuple [l,u])) ) times_RDR (mk_index rest) ) mk_one l u i = nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u], nlHsVar i] ------------------ single_con_inRange = mk_easy_FunBind loc inRange_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed, con_pat cs_needed] $ foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed) where in_range a b c = nlHsApps inRange_RDR [mkLHsVarTuple [a,b], nlHsVar c] {- ************************************************************************ * * Read instances * * ************************************************************************ Example infix 4 %% data T = Int %% Int | T1 { f1 :: Int } | T2 T instance Read T where readPrec = parens ( prec 4 ( do x <- ReadP.step Read.readPrec expectP (Symbol "%%") y <- ReadP.step Read.readPrec return (x %% y)) +++ prec (appPrec+1) ( -- Note the "+1" part; "T2 T1 {f1=3}" should parse ok -- Record construction binds even more tightly than application do expectP (Ident "T1") expectP (Punc '{') expectP (Ident "f1") expectP (Punc '=') x <- ReadP.reset Read.readPrec expectP (Punc '}') return (T1 { f1 = x })) +++ prec appPrec ( do expectP (Ident "T2") x <- ReadP.step Read.readPrec return (T2 x)) ) readListPrec = readListPrecDefault readList = readListDefault Note [Use expectP] ~~~~~~~~~~~~~~~~~~ Note that we use expectP (Ident "T1") rather than Ident "T1" <- lexP The latter desugares to inline code for matching the Ident and the string, and this can be very voluminous. The former is much more compact. Cf Trac #7258, although that also concerned non-linearity in the occurrence analyser, a separate issue. Note [Read for empty data types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What should we get for this? (Trac #7931) data Emp deriving( Read ) -- No data constructors Here we want read "[]" :: [Emp] to succeed, returning [] So we do NOT want instance Read Emp where readPrec = error "urk" Rather we want instance Read Emp where readPred = pfail -- Same as choose [] Because 'pfail' allows the parser to backtrack, but 'error' doesn't. These instances are also useful for Read (Either Int Emp), where we want to be able to parse (Left 3) just fine. -} gen_Read_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Read_binds get_fixity loc tycon = (listToBag [read_prec, default_readlist, default_readlistprec], emptyBag) where ----------------------------------------------------------------------- default_readlist = mkHsVarBind loc readList_RDR (nlHsVar readListDefault_RDR) default_readlistprec = mkHsVarBind loc readListPrec_RDR (nlHsVar readListPrecDefault_RDR) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon (nullary_cons, non_nullary_cons) = partition isNullarySrcDataCon data_cons read_prec = mkHsVarBind loc readPrec_RDR (nlHsApp (nlHsVar parens_RDR) read_cons) read_cons | null data_cons = nlHsVar pfail_RDR -- See Note [Read for empty data types] | otherwise = foldr1 mk_alt (read_nullary_cons ++ read_non_nullary_cons) read_non_nullary_cons = map read_non_nullary_con non_nullary_cons read_nullary_cons = case nullary_cons of [] -> [] [con] -> [nlHsDo DoExpr (match_con con ++ [noLoc $ mkLastStmt (result_expr con [])])] _ -> [nlHsApp (nlHsVar choose_RDR) (nlList (map mk_pair nullary_cons))] -- NB For operators the parens around (:=:) are matched by the -- enclosing "parens" call, so here we must match the naked -- data_con_str con match_con con | isSym con_str = [symbol_pat con_str] | otherwise = ident_h_pat con_str where con_str = data_con_str con -- For nullary constructors we must match Ident s for normal constrs -- and Symbol s for operators mk_pair con = mkLHsTupleExpr [nlHsLit (mkHsString (data_con_str con)), result_expr con []] read_non_nullary_con data_con | is_infix = mk_parser infix_prec infix_stmts body | is_record = mk_parser record_prec record_stmts body -- Using these two lines instead allows the derived -- read for infix and record bindings to read the prefix form -- | is_infix = mk_alt prefix_parser (mk_parser infix_prec infix_stmts body) -- | is_record = mk_alt prefix_parser (mk_parser record_prec record_stmts body) | otherwise = prefix_parser where body = result_expr data_con as_needed con_str = data_con_str data_con prefix_parser = mk_parser prefix_prec prefix_stmts body read_prefix_con | isSym con_str = [read_punc "(", symbol_pat con_str, read_punc ")"] | otherwise = ident_h_pat con_str read_infix_con | isSym con_str = [symbol_pat con_str] | otherwise = [read_punc "`"] ++ ident_h_pat con_str ++ [read_punc "`"] prefix_stmts -- T a b c = read_prefix_con ++ read_args infix_stmts -- a %% b, or a `T` b = [read_a1] ++ read_infix_con ++ [read_a2] record_stmts -- T { f1 = a, f2 = b } = read_prefix_con ++ [read_punc "{"] ++ concat (intersperse [read_punc ","] field_stmts) ++ [read_punc "}"] field_stmts = zipWithEqual "lbl_stmts" read_field labels as_needed con_arity = dataConSourceArity data_con labels = map flLabel $ dataConFieldLabels data_con dc_nm = getName data_con is_infix = dataConIsInfix data_con is_record = length labels > 0 as_needed = take con_arity as_RDRs read_args = zipWithEqual "gen_Read_binds" read_arg as_needed (dataConOrigArgTys data_con) (read_a1:read_a2:_) = read_args prefix_prec = appPrecedence infix_prec = getPrecedence get_fixity dc_nm record_prec = appPrecedence + 1 -- Record construction binds even more tightly -- than application; e.g. T2 T1 {x=2} means T2 (T1 {x=2}) ------------------------------------------------------------------------ -- Helpers ------------------------------------------------------------------------ mk_alt e1 e2 = genOpApp e1 alt_RDR e2 -- e1 +++ e2 mk_parser p ss b = nlHsApps prec_RDR [nlHsIntLit p -- prec p (do { ss ; b }) , nlHsDo DoExpr (ss ++ [noLoc $ mkLastStmt b])] con_app con as = nlHsVarApps (getRdrName con) as -- con as result_expr con as = nlHsApp (nlHsVar returnM_RDR) (con_app con as) -- return (con as) -- For constructors and field labels ending in '#', we hackily -- let the lexer generate two tokens, and look for both in sequence -- Thus [Ident "I"; Symbol "#"]. See Trac #5041 ident_h_pat s | Just (ss, '#') <- snocView s = [ ident_pat ss, symbol_pat "#" ] | otherwise = [ ident_pat s ] bindLex pat = noLoc (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p -- See Note [Use expectP] ident_pat s = bindLex $ nlHsApps ident_RDR [nlHsLit (mkHsString s)] -- expectP (Ident "foo") symbol_pat s = bindLex $ nlHsApps symbol_RDR [nlHsLit (mkHsString s)] -- expectP (Symbol ">>") read_punc c = bindLex $ nlHsApps punc_RDR [nlHsLit (mkHsString c)] -- expectP (Punc "<") data_con_str con = occNameString (getOccName con) read_arg a ty = ASSERT( not (isUnliftedType ty) ) noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR])) read_field lbl a = read_lbl lbl ++ [read_punc "=", noLoc (mkBindStmt (nlVarPat a) (nlHsVarApps reset_RDR [readPrec_RDR]))] -- When reading field labels we might encounter -- a = 3 -- _a = 3 -- or (#) = 4 -- Note the parens! read_lbl lbl | isSym lbl_str = [read_punc "(", symbol_pat lbl_str, read_punc ")"] | otherwise = ident_h_pat lbl_str where lbl_str = unpackFS lbl {- ************************************************************************ * * Show instances * * ************************************************************************ Example infixr 5 :^: data Tree a = Leaf a | Tree a :^: Tree a instance (Show a) => Show (Tree a) where showsPrec d (Leaf m) = showParen (d > app_prec) showStr where showStr = showString "Leaf " . showsPrec (app_prec+1) m showsPrec d (u :^: v) = showParen (d > up_prec) showStr where showStr = showsPrec (up_prec+1) u . showString " :^: " . showsPrec (up_prec+1) v -- Note: right-associativity of :^: ignored up_prec = 5 -- Precedence of :^: app_prec = 10 -- Application has precedence one more than -- the most tightly-binding operator -} gen_Show_binds :: (Name -> Fixity) -> SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Show_binds get_fixity loc tycon = (listToBag [shows_prec, show_list], emptyBag) where ----------------------------------------------------------------------- show_list = mkHsVarBind loc showList_RDR (nlHsApp (nlHsVar showList___RDR) (nlHsPar (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)))) ----------------------------------------------------------------------- data_cons = tyConDataCons tycon shows_prec = mk_FunBind loc showsPrec_RDR (map pats_etc data_cons) pats_etc data_con | nullary_con = -- skip the showParen junk... ASSERT(null bs_needed) ([nlWildPat, con_pat], mk_showString_app op_con_str) | otherwise = ([a_Pat, con_pat], showParen_Expr (genOpApp a_Expr ge_RDR (nlHsLit (HsInt "" con_prec_plus_one))) (nlHsPar (nested_compose_Expr show_thingies))) where data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con bs_needed = take con_arity bs_RDRs arg_tys = dataConOrigArgTys data_con -- Correspond 1-1 with bs_needed con_pat = nlConVarPat data_con_RDR bs_needed nullary_con = con_arity == 0 labels = map flLabel $ dataConFieldLabels data_con lab_fields = length labels record_syntax = lab_fields > 0 dc_nm = getName data_con dc_occ_nm = getOccName data_con con_str = occNameString dc_occ_nm op_con_str = wrapOpParens con_str backquote_str = wrapOpBackquotes con_str show_thingies | is_infix = [show_arg1, mk_showString_app (" " ++ backquote_str ++ " "), show_arg2] | record_syntax = mk_showString_app (op_con_str ++ " {") : show_record_args ++ [mk_showString_app "}"] | otherwise = mk_showString_app (op_con_str ++ " ") : show_prefix_args show_label l = mk_showString_app (nm ++ " = ") -- Note the spaces around the "=" sign. If we -- don't have them then we get Foo { x=-1 } and -- the "=-" parses as a single lexeme. Only the -- space after the '=' is necessary, but it -- seems tidier to have them both sides. where nm = wrapOpParens (unpackFS l) show_args = zipWith show_arg bs_needed arg_tys (show_arg1:show_arg2:_) = show_args show_prefix_args = intersperse (nlHsVar showSpace_RDR) show_args -- Assumption for record syntax: no of fields == no of -- labelled fields (and in same order) show_record_args = concat $ intersperse [mk_showString_app ", "] $ [ [show_label lbl, arg] | (lbl,arg) <- zipEqual "gen_Show_binds" labels show_args ] show_arg :: RdrName -> Type -> LHsExpr RdrName show_arg b arg_ty | isUnliftedType arg_ty -- See Note [Deriving and unboxed types] in TcDeriv = nlHsApps compose_RDR [mk_shows_app boxed_arg, mk_showString_app postfixMod] | otherwise = mk_showsPrec_app arg_prec arg where arg = nlHsVar b boxed_arg = box "Show" tycon arg arg_ty postfixMod = assoc_ty_id "Show" tycon postfixModTbl arg_ty -- Fixity stuff is_infix = dataConIsInfix data_con con_prec_plus_one = 1 + getPrec is_infix get_fixity dc_nm arg_prec | record_syntax = 0 -- Record fields don't need parens | otherwise = con_prec_plus_one wrapOpParens :: String -> String wrapOpParens s | isSym s = '(' : s ++ ")" | otherwise = s wrapOpBackquotes :: String -> String wrapOpBackquotes s | isSym s = s | otherwise = '`' : s ++ "`" isSym :: String -> Bool isSym "" = False isSym (c : _) = startsVarSym c || startsConSym c -- | showString :: String -> ShowS mk_showString_app :: String -> LHsExpr RdrName mk_showString_app str = nlHsApp (nlHsVar showString_RDR) (nlHsLit (mkHsString str)) -- | showsPrec :: Show a => Int -> a -> ShowS mk_showsPrec_app :: Integer -> LHsExpr RdrName -> LHsExpr RdrName mk_showsPrec_app p x = nlHsApps showsPrec_RDR [nlHsLit (HsInt "" p), x] -- | shows :: Show a => a -> ShowS mk_shows_app :: LHsExpr RdrName -> LHsExpr RdrName mk_shows_app x = nlHsApp (nlHsVar shows_RDR) x getPrec :: Bool -> (Name -> Fixity) -> Name -> Integer getPrec is_infix get_fixity nm | not is_infix = appPrecedence | otherwise = getPrecedence get_fixity nm appPrecedence :: Integer appPrecedence = fromIntegral maxPrecedence + 1 -- One more than the precedence of the most -- tightly-binding operator getPrecedence :: (Name -> Fixity) -> Name -> Integer getPrecedence get_fixity nm = case get_fixity nm of Fixity _ x _assoc -> fromIntegral x -- NB: the Report says that associativity is not taken -- into account for either Read or Show; hence we -- ignore associativity here {- ************************************************************************ * * Data instances * * ************************************************************************ From the data type data T a b = T1 a b | T2 we generate $cT1 = mkDataCon $dT "T1" Prefix $cT2 = mkDataCon $dT "T2" Prefix $dT = mkDataType "Module.T" [] [$con_T1, $con_T2] -- the [] is for field labels. instance (Data a, Data b) => Data (T a b) where gfoldl k z (T1 a b) = z T `k` a `k` b gfoldl k z T2 = z T2 -- ToDo: add gmapT,Q,M, gfoldr gunfold k z c = case conIndex c of I# 1# -> k (k (z T1)) I# 2# -> z T2 toConstr (T1 _ _) = $cT1 toConstr T2 = $cT2 dataTypeOf _ = $dT dataCast1 = gcast1 -- If T :: * -> * dataCast2 = gcast2 -- if T :: * -> * -> * -} gen_Data_binds :: SrcSpan -> TyCon -- For data families, this is the -- *representation* TyCon -> TcM (LHsBinds RdrName, -- The method bindings BagDerivStuff) -- Auxiliary bindings gen_Data_binds loc rep_tc = do { dflags <- getDynFlags -- Make unique names for the data type and constructor -- auxiliary bindings. Start with the name of the TyCon/DataCon -- but that might not be unique: see Trac #12245. ; dt_occ <- chooseUniqueOccTc (mkDataTOcc (getOccName rep_tc)) ; dc_occs <- mapM (chooseUniqueOccTc . mkDataCOcc . getOccName) (tyConDataCons rep_tc) ; let dt_rdr = mkRdrUnqual dt_occ dc_rdrs = map mkRdrUnqual dc_occs -- OK, now do the work ; return (gen_data dflags dt_rdr dc_rdrs loc rep_tc) } gen_data :: DynFlags -> RdrName -> [RdrName] -> SrcSpan -> TyCon -> (LHsBinds RdrName, -- The method bindings BagDerivStuff) -- Auxiliary bindings gen_data dflags data_type_name constr_names loc rep_tc = (listToBag [gfoldl_bind, gunfold_bind, toCon_bind, dataTypeOf_bind] `unionBags` gcast_binds, -- Auxiliary definitions: the data type and constructors listToBag ( genDataTyCon : zipWith genDataDataCon data_cons constr_names ) ) where data_cons = tyConDataCons rep_tc n_cons = length data_cons one_constr = n_cons == 1 genDataTyCon :: DerivStuff genDataTyCon -- $dT = DerivHsBind (mkHsVarBind loc data_type_name rhs, L loc (TypeSig [L loc data_type_name] sig_ty)) sig_ty = mkLHsSigWcType (nlHsTyVar dataType_RDR) rhs = nlHsVar mkDataType_RDR `nlHsApp` nlHsLit (mkHsString (showSDocOneLine dflags (ppr rep_tc))) `nlHsApp` nlList (map nlHsVar constr_names) genDataDataCon :: DataCon -> RdrName -> DerivStuff genDataDataCon dc constr_name -- $cT1 etc = DerivHsBind (mkHsVarBind loc constr_name rhs, L loc (TypeSig [L loc constr_name] sig_ty)) where sig_ty = mkLHsSigWcType (nlHsTyVar constr_RDR) rhs = nlHsApps mkConstr_RDR constr_args constr_args = [ -- nlHsIntLit (toInteger (dataConTag dc)), -- Tag nlHsVar (data_type_name) -- DataType , nlHsLit (mkHsString (occNameString dc_occ)) -- String name , nlList labels -- Field labels , nlHsVar fixity ] -- Fixity labels = map (nlHsLit . mkHsString . unpackFS . flLabel) (dataConFieldLabels dc) dc_occ = getOccName dc is_infix = isDataSymOcc dc_occ fixity | is_infix = infix_RDR | otherwise = prefix_RDR ------------ gfoldl gfoldl_bind = mk_HRFunBind 2 loc gfoldl_RDR (map gfoldl_eqn data_cons) gfoldl_eqn con = ([nlVarPat k_RDR, nlVarPat z_RDR, nlConVarPat con_name as_needed], foldl mk_k_app (nlHsVar z_RDR `nlHsApp` nlHsVar con_name) as_needed) where con_name :: RdrName con_name = getRdrName con as_needed = take (dataConSourceArity con) as_RDRs mk_k_app e v = nlHsPar (nlHsOpApp e k_RDR (nlHsVar v)) ------------ gunfold gunfold_bind = mk_HRFunBind 2 loc gunfold_RDR [([k_Pat, z_Pat, if one_constr then nlWildPat else c_Pat], gunfold_rhs)] gunfold_rhs | one_constr = mk_unfold_rhs (head data_cons) -- No need for case | otherwise = nlHsCase (nlHsVar conIndex_RDR `nlHsApp` c_Expr) (map gunfold_alt data_cons) gunfold_alt dc = mkHsCaseAlt (mk_unfold_pat dc) (mk_unfold_rhs dc) mk_unfold_rhs dc = foldr nlHsApp (nlHsVar z_RDR `nlHsApp` nlHsVar (getRdrName dc)) (replicate (dataConSourceArity dc) (nlHsVar k_RDR)) mk_unfold_pat dc -- Last one is a wild-pat, to avoid -- redundant test, and annoying warning | tag-fIRST_TAG == n_cons-1 = nlWildPat -- Last constructor | otherwise = nlConPat intDataCon_RDR [nlLitPat (HsIntPrim "" (toInteger tag))] where tag = dataConTag dc ------------ toConstr toCon_bind = mk_FunBind loc toConstr_RDR (zipWith to_con_eqn data_cons constr_names) to_con_eqn dc con_name = ([nlWildConPat dc], nlHsVar con_name) ------------ dataTypeOf dataTypeOf_bind = mk_easy_FunBind loc dataTypeOf_RDR [nlWildPat] (nlHsVar data_type_name) ------------ gcast1/2 -- Make the binding dataCast1 x = gcast1 x -- if T :: * -> * -- or dataCast2 x = gcast2 s -- if T :: * -> * -> * -- (or nothing if T has neither of these two types) -- But care is needed for data families: -- If we have data family D a -- data instance D (a,b,c) = A | B deriving( Data ) -- and we want instance ... => Data (D [(a,b,c)]) where ... -- then we need dataCast1 x = gcast1 x -- because D :: * -> * -- even though rep_tc has kind * -> * -> * -> * -- Hence looking for the kind of fam_tc not rep_tc -- See Trac #4896 tycon_kind = case tyConFamInst_maybe rep_tc of Just (fam_tc, _) -> tyConKind fam_tc Nothing -> tyConKind rep_tc gcast_binds | tycon_kind `tcEqKind` kind1 = mk_gcast dataCast1_RDR gcast1_RDR | tycon_kind `tcEqKind` kind2 = mk_gcast dataCast2_RDR gcast2_RDR | otherwise = emptyBag mk_gcast dataCast_RDR gcast_RDR = unitBag (mk_easy_FunBind loc dataCast_RDR [nlVarPat f_RDR] (nlHsVar gcast_RDR `nlHsApp` nlHsVar f_RDR)) kind1, kind2 :: Kind kind1 = liftedTypeKind `mkFunTy` liftedTypeKind kind2 = liftedTypeKind `mkFunTy` kind1 gfoldl_RDR, gunfold_RDR, toConstr_RDR, dataTypeOf_RDR, mkConstr_RDR, mkDataType_RDR, conIndex_RDR, prefix_RDR, infix_RDR, dataCast1_RDR, dataCast2_RDR, gcast1_RDR, gcast2_RDR, constr_RDR, dataType_RDR, eqChar_RDR , ltChar_RDR , geChar_RDR , gtChar_RDR , leChar_RDR , eqInt_RDR , ltInt_RDR , geInt_RDR , gtInt_RDR , leInt_RDR , eqWord_RDR , ltWord_RDR , geWord_RDR , gtWord_RDR , leWord_RDR , eqAddr_RDR , ltAddr_RDR , geAddr_RDR , gtAddr_RDR , leAddr_RDR , eqFloat_RDR , ltFloat_RDR , geFloat_RDR , gtFloat_RDR , leFloat_RDR , eqDouble_RDR, ltDouble_RDR, geDouble_RDR, gtDouble_RDR, leDouble_RDR :: RdrName gfoldl_RDR = varQual_RDR gENERICS (fsLit "gfoldl") gunfold_RDR = varQual_RDR gENERICS (fsLit "gunfold") toConstr_RDR = varQual_RDR gENERICS (fsLit "toConstr") dataTypeOf_RDR = varQual_RDR gENERICS (fsLit "dataTypeOf") dataCast1_RDR = varQual_RDR gENERICS (fsLit "dataCast1") dataCast2_RDR = varQual_RDR gENERICS (fsLit "dataCast2") gcast1_RDR = varQual_RDR tYPEABLE (fsLit "gcast1") gcast2_RDR = varQual_RDR tYPEABLE (fsLit "gcast2") mkConstr_RDR = varQual_RDR gENERICS (fsLit "mkConstr") constr_RDR = tcQual_RDR gENERICS (fsLit "Constr") mkDataType_RDR = varQual_RDR gENERICS (fsLit "mkDataType") dataType_RDR = tcQual_RDR gENERICS (fsLit "DataType") conIndex_RDR = varQual_RDR gENERICS (fsLit "constrIndex") prefix_RDR = dataQual_RDR gENERICS (fsLit "Prefix") infix_RDR = dataQual_RDR gENERICS (fsLit "Infix") eqChar_RDR = varQual_RDR gHC_PRIM (fsLit "eqChar#") ltChar_RDR = varQual_RDR gHC_PRIM (fsLit "ltChar#") leChar_RDR = varQual_RDR gHC_PRIM (fsLit "leChar#") gtChar_RDR = varQual_RDR gHC_PRIM (fsLit "gtChar#") geChar_RDR = varQual_RDR gHC_PRIM (fsLit "geChar#") eqInt_RDR = varQual_RDR gHC_PRIM (fsLit "==#") ltInt_RDR = varQual_RDR gHC_PRIM (fsLit "<#" ) leInt_RDR = varQual_RDR gHC_PRIM (fsLit "<=#") gtInt_RDR = varQual_RDR gHC_PRIM (fsLit ">#" ) geInt_RDR = varQual_RDR gHC_PRIM (fsLit ">=#") eqWord_RDR = varQual_RDR gHC_PRIM (fsLit "eqWord#") ltWord_RDR = varQual_RDR gHC_PRIM (fsLit "ltWord#") leWord_RDR = varQual_RDR gHC_PRIM (fsLit "leWord#") gtWord_RDR = varQual_RDR gHC_PRIM (fsLit "gtWord#") geWord_RDR = varQual_RDR gHC_PRIM (fsLit "geWord#") eqAddr_RDR = varQual_RDR gHC_PRIM (fsLit "eqAddr#") ltAddr_RDR = varQual_RDR gHC_PRIM (fsLit "ltAddr#") leAddr_RDR = varQual_RDR gHC_PRIM (fsLit "leAddr#") gtAddr_RDR = varQual_RDR gHC_PRIM (fsLit "gtAddr#") geAddr_RDR = varQual_RDR gHC_PRIM (fsLit "geAddr#") eqFloat_RDR = varQual_RDR gHC_PRIM (fsLit "eqFloat#") ltFloat_RDR = varQual_RDR gHC_PRIM (fsLit "ltFloat#") leFloat_RDR = varQual_RDR gHC_PRIM (fsLit "leFloat#") gtFloat_RDR = varQual_RDR gHC_PRIM (fsLit "gtFloat#") geFloat_RDR = varQual_RDR gHC_PRIM (fsLit "geFloat#") eqDouble_RDR = varQual_RDR gHC_PRIM (fsLit "==##") ltDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<##" ) leDouble_RDR = varQual_RDR gHC_PRIM (fsLit "<=##") gtDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">##" ) geDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">=##") {- ************************************************************************ * * Functor instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ For the data type: data T a = T1 Int a | T2 (T a) We generate the instance: instance Functor T where fmap f (T1 b1 a) = T1 b1 (f a) fmap f (T2 ta) = T2 (fmap f ta) Notice that we don't simply apply 'fmap' to the constructor arguments. Rather - Do nothing to an argument whose type doesn't mention 'a' - Apply 'f' to an argument of type 'a' - Apply 'fmap f' to other arguments That's why we have to recurse deeply into the constructor argument types, rather than just one level, as we typically do. What about types with more than one type parameter? In general, we only derive Functor for the last position: data S a b = S1 [b] | S2 (a, T a b) instance Functor (S a) where fmap f (S1 bs) = S1 (fmap f bs) fmap f (S2 (p,q)) = S2 (a, fmap f q) However, we have special cases for - tuples - functions More formally, we write the derivation of fmap code over type variable 'a for type 'b as ($fmap 'a 'b). In this general notation the derived instance for T is: instance Functor T where fmap f (T1 x1 x2) = T1 ($(fmap 'a 'b1) x1) ($(fmap 'a 'a) x2) fmap f (T2 x1) = T2 ($(fmap 'a '(T a)) x1) $(fmap 'a 'b) = \x -> x -- when b does not contain a $(fmap 'a 'a) = f $(fmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(fmap 'a 'b1) x1, $(fmap 'a 'b2) x2) $(fmap 'a '(T b1 b2)) = fmap $(fmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(fmap 'a '(b -> c)) = \x b -> $(fmap 'a' 'c) (x ($(cofmap 'a 'b) b)) For functions, the type parameter 'a can occur in a contravariant position, which means we need to derive a function like: cofmap :: (a -> b) -> (f b -> f a) This is pretty much the same as $fmap, only without the $(cofmap 'a 'a) case: $(cofmap 'a 'b) = \x -> x -- when b does not contain a $(cofmap 'a 'a) = error "type variable in contravariant position" $(cofmap 'a '(b1,b2)) = \x -> case x of (x1,x2) -> ($(cofmap 'a 'b1) x1, $(cofmap 'a 'b2) x2) $(cofmap 'a '[b]) = map $(cofmap 'a 'b) $(cofmap 'a '(T b1 b2)) = fmap $(cofmap 'a 'b2) -- when a only occurs in the last parameter, b2 $(cofmap 'a '(b -> c)) = \x b -> $(cofmap 'a' 'c) (x ($(fmap 'a 'c) b)) Note that the code produced by $(fmap _ _) is always a higher order function, with type `(a -> b) -> (g a -> g b)` for some g. When we need to do pattern matching on the type, this means create a lambda function (see the (,) case above). The resulting code for fmap can look a bit weird, for example: data X a = X (a,Int) -- generated instance instance Functor X where fmap f (X x) = (\y -> case y of (x1,x2) -> X (f x1, (\z -> z) x2)) x The optimizer should be able to simplify this code by simple inlining. An older version of the deriving code tried to avoid these applied lambda functions by producing a meta level function. But the function to be mapped, `f`, is a function on the code level, not on the meta level, so it was eta expanded to `\x -> [| f $x |]`. This resulted in too much eta expansion. It is better to produce too many lambdas than to eta expand, see ticket #7436. -} gen_Functor_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Functor_binds loc tycon = (unitBag fmap_bind, emptyBag) where data_cons = tyConDataCons tycon fun_name = L loc fmap_RDR fmap_bind = mkRdrFunBind fun_name eqns fmap_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_fmap con eqns | null data_cons = [mkSimpleMatch (FunRhs fun_name Prefix) [nlWildPat, nlWildPat] (error_Expr "Void fmap")] | otherwise = map fmap_eqn data_cons ft_fmap :: FFoldType (State [RdrName] (LHsExpr RdrName)) ft_fmap = FT { ft_triv = mkSimpleLam $ \x -> return x -- fmap f = \x -> x , ft_var = return f_Expr -- fmap f = f , ft_fun = \g h -> do gg <- g hh <- h mkSimpleLam2 $ \x b -> return $ nlHsApp hh (nlHsApp x (nlHsApp gg b)) -- fmap f = \x b -> h (x (g b)) , ft_tup = \t gs -> do gg <- sequence gs mkSimpleLam $ mkSimpleTupleCase match_for_con t gg -- fmap f = \x -> case x of (a1,a2,..) -> (g1 a1,g2 a2,..) , ft_ty_app = \_ g -> nlHsApp fmap_Expr <$> g -- fmap f = fmap g , ft_forall = \_ g -> g , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" } -- Con a1 a2 ... -> Con (f1 a1) (f2 a2) ... match_for_con :: [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_for_con = mkSimpleConMatch CaseAlt $ \con_name xs -> return $ nlHsApps con_name xs -- Con x1 x2 .. {- Utility functions related to Functor deriving. Since several things use the same pattern of traversal, this is abstracted into functorLikeTraverse. This function works like a fold: it makes a value of type 'a' in a bottom up way. -} -- Generic traversal for Functor deriving -- See Note [FFoldType and functorLikeTraverse] data FFoldType a -- Describes how to fold over a Type in a functor like way = FT { ft_triv :: a -- ^ Does not contain variable , ft_var :: a -- ^ The variable itself , ft_co_var :: a -- ^ The variable itself, contravariantly , ft_fun :: a -> a -> a -- ^ Function type , ft_tup :: TyCon -> [a] -> a -- ^ Tuple type , ft_ty_app :: Type -> a -> a -- ^ Type app, variable only in last argument , ft_bad_app :: a -- ^ Type app, variable other than in last argument , ft_forall :: TcTyVar -> a -> a -- ^ Forall type } functorLikeTraverse :: forall a. TyVar -- ^ Variable to look for -> FFoldType a -- ^ How to fold -> Type -- ^ Type to process -> a functorLikeTraverse var (FT { ft_triv = caseTrivial, ft_var = caseVar , ft_co_var = caseCoVar, ft_fun = caseFun , ft_tup = caseTuple, ft_ty_app = caseTyApp , ft_bad_app = caseWrongArg, ft_forall = caseForAll }) ty = fst (go False ty) where go :: Bool -- Covariant or contravariant context -> Type -> (a, Bool) -- (result of type a, does type contain var) go co ty | Just ty' <- coreView ty = go co ty' go co (TyVarTy v) | v == var = (if co then caseCoVar else caseVar,True) go co (FunTy x y) | isPredTy x = go co y | xc || yc = (caseFun xr yr,True) where (xr,xc) = go (not co) x (yr,yc) = go co y go co (AppTy x y) | xc = (caseWrongArg, True) | yc = (caseTyApp x yr, True) where (_, xc) = go co x (yr,yc) = go co y go co ty@(TyConApp con args) | not (or xcs) = (caseTrivial, False) -- Variable does not occur -- At this point we know that xrs, xcs is not empty, -- and at least one xr is True | isTupleTyCon con = (caseTuple con xrs, True) | or (init xcs) = (caseWrongArg, True) -- T (..var..) ty | Just (fun_ty, _) <- splitAppTy_maybe ty -- T (..no var..) ty = (caseTyApp fun_ty (last xrs), True) | otherwise = (caseWrongArg, True) -- Non-decomposable (eg type function) where (xrs,xcs) = unzip (map (go co) args) go co (ForAllTy (TvBndr v vis) x) | isVisibleArgFlag vis = panic "unexpected visible binder" | v /= var && xc = (caseForAll v xr,True) where (xr,xc) = go co x go _ _ = (caseTrivial,False) -- Return all syntactic subterms of ty that contain var somewhere -- These are the things that should appear in instance constraints deepSubtypesContaining :: TyVar -> Type -> [TcType] deepSubtypesContaining tv = functorLikeTraverse tv (FT { ft_triv = [] , ft_var = [] , ft_fun = (++) , ft_tup = \_ xs -> concat xs , ft_ty_app = (:) , ft_bad_app = panic "in other argument" , ft_co_var = panic "contravariant" , ft_forall = \v xs -> filterOut ((v `elemVarSet`) . tyCoVarsOfType) xs }) foldDataConArgs :: FFoldType a -> DataCon -> [a] -- Fold over the arguments of the datacon foldDataConArgs ft con = map foldArg (dataConOrigArgTys con) where foldArg = case getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con))) of Just tv -> functorLikeTraverse tv ft Nothing -> const (ft_triv ft) -- If we are deriving Foldable for a GADT, there is a chance that the last -- type variable in the data type isn't actually a type variable at all. -- (for example, this can happen if the last type variable is refined to -- be a concrete type such as Int). If the last type variable is refined -- to be a specific type, then getTyVar_maybe will return Nothing. -- See Note [DeriveFoldable with ExistentialQuantification] -- -- The kind checks have ensured the last type parameter is of kind *. -- Make a HsLam using a fresh variable from a State monad mkSimpleLam :: (LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) -- (mkSimpleLam fn) returns (\x. fn(x)) mkSimpleLam lam = do (n:names) <- get put names body <- lam (nlHsVar n) return (mkHsLam [nlVarPat n] body) mkSimpleLam2 :: (LHsExpr RdrName -> LHsExpr RdrName -> State [RdrName] (LHsExpr RdrName)) -> State [RdrName] (LHsExpr RdrName) mkSimpleLam2 lam = do (n1:n2:names) <- get put names body <- lam (nlHsVar n1) (nlHsVar n2) return (mkHsLam [nlVarPat n1,nlVarPat n2] body) -- "Con a1 a2 a3 -> fold [x1 a1, x2 a2, x3 a3]" -- -- @mkSimpleConMatch fold extra_pats con insides@ produces a match clause in -- which the LHS pattern-matches on @extra_pats@, followed by a match on the -- constructor @con@ and its arguments. The RHS folds (with @fold@) over @con@ -- and its arguments, applying an expression (from @insides@) to each of the -- respective arguments of @con@. mkSimpleConMatch :: Monad m => HsMatchContext RdrName -> (RdrName -> [LHsExpr RdrName] -> m (LHsExpr RdrName)) -> [LPat RdrName] -> DataCon -> [LHsExpr RdrName] -> m (LMatch RdrName (LHsExpr RdrName)) mkSimpleConMatch ctxt fold extra_pats con insides = do let con_name = getRdrName con let vars_needed = takeList insides as_RDRs let pat = nlConVarPat con_name vars_needed rhs <- fold con_name (zipWith nlHsApp insides (map nlHsVar vars_needed)) return $ mkMatch ctxt (extra_pats ++ [pat]) rhs (noLoc emptyLocalBinds) -- "Con a1 a2 a3 -> fmap (\b2 -> Con a1 b2 a3) (traverse f a2)" -- -- @mkSimpleConMatch2 fold extra_pats con insides@ behaves very similarly to -- 'mkSimpleConMatch', with two key differences: -- -- 1. @insides@ is a @[Maybe (LHsExpr RdrName)]@ instead of a -- @[LHsExpr RdrName]@. This is because it filters out the expressions -- corresponding to arguments whose types do not mention the last type -- variable in a derived 'Foldable' or 'Traversable' instance (i.e., the -- 'Nothing' elements of @insides@). -- -- 2. @fold@ takes an expression as its first argument instead of a -- constructor name. This is because it uses a specialized -- constructor function expression that only takes as many parameters as -- there are argument types that mention the last type variable. -- -- See Note [Generated code for DeriveFoldable and DeriveTraversable] mkSimpleConMatch2 :: Monad m => HsMatchContext RdrName -> (LHsExpr RdrName -> [LHsExpr RdrName] -> m (LHsExpr RdrName)) -> [LPat RdrName] -> DataCon -> [Maybe (LHsExpr RdrName)] -> m (LMatch RdrName (LHsExpr RdrName)) mkSimpleConMatch2 ctxt fold extra_pats con insides = do let con_name = getRdrName con vars_needed = takeList insides as_RDRs pat = nlConVarPat con_name vars_needed -- Make sure to zip BEFORE invoking catMaybes. We want the variable -- indicies in each expression to match up with the argument indices -- in con_expr (defined below). exps = catMaybes $ zipWith (\i v -> (`nlHsApp` v) <$> i) insides (map nlHsVar vars_needed) -- An element of argTysTyVarInfo is True if the constructor argument -- with the same index has a type which mentions the last type -- variable. argTysTyVarInfo = map isJust insides (asWithTyVar, asWithoutTyVar) = partitionByList argTysTyVarInfo as_RDRs con_expr | null asWithTyVar = nlHsApps con_name $ map nlHsVar asWithoutTyVar | otherwise = let bs = filterByList argTysTyVarInfo bs_RDRs vars = filterByLists argTysTyVarInfo (map nlHsVar bs_RDRs) (map nlHsVar as_RDRs) in mkHsLam (map nlVarPat bs) (nlHsApps con_name vars) rhs <- fold con_expr exps return $ mkMatch ctxt (extra_pats ++ [pat]) rhs (noLoc emptyLocalBinds) -- "case x of (a1,a2,a3) -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleTupleCase :: Monad m => ([LPat RdrName] -> DataCon -> [a] -> m (LMatch RdrName (LHsExpr RdrName))) -> TyCon -> [a] -> LHsExpr RdrName -> m (LHsExpr RdrName) mkSimpleTupleCase match_for_con tc insides x = do { let data_con = tyConSingleDataCon tc ; match <- match_for_con [] data_con insides ; return $ nlHsCase x [match] } {- ************************************************************************ * * Foldable instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ Deriving Foldable instances works the same way as Functor instances, only Foldable instances are not possible for function types at all. Given (data T a = T a a (T a) deriving Foldable), we get: instance Foldable T where foldr f z (T x1 x2 x3) = $(foldr 'a 'a) x1 ( $(foldr 'a 'a) x2 ( $(foldr 'a '(T a)) x3 z ) ) -XDeriveFoldable is different from -XDeriveFunctor in that it filters out arguments to the constructor that would produce useless code in a Foldable instance. For example, the following datatype: data Foo a = Foo Int a Int deriving Foldable would have the following generated Foldable instance: instance Foldable Foo where foldr f z (Foo x1 x2 x3) = $(foldr 'a 'a) x2 since neither of the two Int arguments are folded over. The cases are: $(foldr 'a 'a) = f $(foldr 'a '(b1,b2)) = \x z -> case x of (x1,x2) -> $(foldr 'a 'b1) x1 ( $(foldr 'a 'b2) x2 z ) $(foldr 'a '(T b1 b2)) = \x z -> foldr $(foldr 'a 'b2) z x -- when a only occurs in the last parameter, b2 Note that the arguments to the real foldr function are the wrong way around, since (f :: a -> b -> b), while (foldr f :: b -> t a -> b). One can envision a case for types that don't contain the last type variable: $(foldr 'a 'b) = \x z -> z -- when b does not contain a But this case will never materialize, since the aforementioned filtering removes all such types from consideration. See Note [Generated code for DeriveFoldable and DeriveTraversable]. Foldable instances differ from Functor and Traversable instances in that Foldable instances can be derived for data types in which the last type variable is existentially quantified. In particular, if the last type variable is refined to a more specific type in a GADT: data GADT a where G :: a ~ Int => a -> G Int then the deriving machinery does not attempt to check that the type a contains Int, since it is not syntactically equal to a type variable. That is, the derived Foldable instance for GADT is: instance Foldable GADT where foldr _ z (GADT _) = z See Note [DeriveFoldable with ExistentialQuantification]. -} gen_Foldable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Foldable_binds loc tycon = (listToBag [foldr_bind, foldMap_bind], emptyBag) where data_cons = tyConDataCons tycon foldr_bind = mkRdrFunBind (L loc foldable_foldr_RDR) eqns eqns = map foldr_eqn data_cons foldr_eqn con = evalState (match_foldr z_Expr [f_Pat,z_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldr con foldMap_bind = mkRdrFunBind (L loc foldMap_RDR) (map foldMap_eqn data_cons) foldMap_eqn con = evalState (match_foldMap [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldMap con -- Yields 'Just' an expression if we're folding over a type that mentions -- the last type parameter of the datatype. Otherwise, yields 'Nothing'. -- See Note [FFoldType and functorLikeTraverse] ft_foldr :: FFoldType (State [RdrName] (Maybe (LHsExpr RdrName))) ft_foldr = FT { ft_triv = return Nothing -- foldr f = \x z -> z , ft_var = return $ Just f_Expr -- foldr f = f , ft_tup = \t g -> do gg <- sequence g lam <- mkSimpleLam2 $ \x z -> mkSimpleTupleCase (match_foldr z) t gg x return (Just lam) -- foldr f = (\x z -> case x of ...) , ft_ty_app = \_ g -> do gg <- g mapM (\gg' -> mkSimpleLam2 $ \x z -> return $ nlHsApps foldable_foldr_RDR [gg',z,x]) gg -- foldr f = (\x z -> foldr g z x) , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldr :: LHsExpr RdrName -> [LPat RdrName] -> DataCon -> [Maybe (LHsExpr RdrName)] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_foldr z = mkSimpleConMatch2 LambdaExpr $ \_ xs -> return (mkFoldr xs) where -- g1 v1 (g2 v2 (.. z)) mkFoldr :: [LHsExpr RdrName] -> LHsExpr RdrName mkFoldr = foldr nlHsApp z -- See Note [FFoldType and functorLikeTraverse] ft_foldMap :: FFoldType (State [RdrName] (Maybe (LHsExpr RdrName))) ft_foldMap = FT { ft_triv = return Nothing -- foldMap f = \x -> mempty , ft_var = return (Just f_Expr) -- foldMap f = f , ft_tup = \t g -> do gg <- sequence g lam <- mkSimpleLam $ mkSimpleTupleCase match_foldMap t gg return (Just lam) -- foldMap f = \x -> case x of (..,) , ft_ty_app = \_ g -> fmap (nlHsApp foldMap_Expr) <$> g -- foldMap f = foldMap g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } match_foldMap :: [LPat RdrName] -> DataCon -> [Maybe (LHsExpr RdrName)] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_foldMap = mkSimpleConMatch2 CaseAlt $ \_ xs -> return (mkFoldMap xs) where -- mappend v1 (mappend v2 ..) mkFoldMap :: [LHsExpr RdrName] -> LHsExpr RdrName mkFoldMap [] = mempty_Expr mkFoldMap xs = foldr1 (\x y -> nlHsApps mappend_RDR [x,y]) xs {- ************************************************************************ * * Traversable instances see http://www.mail-archive.com/haskell-prime@haskell.org/msg02116.html * * ************************************************************************ Again, Traversable is much like Functor and Foldable. The cases are: $(traverse 'a 'a) = f $(traverse 'a '(b1,b2)) = \x -> case x of (x1,x2) -> (,) <$> $(traverse 'a 'b1) x1 <*> $(traverse 'a 'b2) x2 $(traverse 'a '(T b1 b2)) = traverse $(traverse 'a 'b2) -- when a only occurs in the last parameter, b2 Like -XDeriveFoldable, -XDeriveTraversable filters out arguments whose types do not mention the last type parameter. Therefore, the following datatype: data Foo a = Foo Int a Int would have the following derived Traversable instance: instance Traversable Foo where traverse f (Foo x1 x2 x3) = fmap (\b2 -> Foo x1 b2 x3) ( $(traverse 'a 'a) x2 ) since the two Int arguments do not produce any effects in a traversal. One can envision a case for types that do not mention the last type parameter: $(traverse 'a 'b) = pure -- when b does not contain a But this case will never materialize, since the aforementioned filtering removes all such types from consideration. See Note [Generated code for DeriveFoldable and DeriveTraversable]. -} gen_Traversable_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Traversable_binds loc tycon = (unitBag traverse_bind, emptyBag) where data_cons = tyConDataCons tycon traverse_bind = mkRdrFunBind (L loc traverse_RDR) eqns eqns = map traverse_eqn data_cons traverse_eqn con = evalState (match_for_con [f_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_trav con -- Yields 'Just' an expression if we're folding over a type that mentions -- the last type parameter of the datatype. Otherwise, yields 'Nothing'. -- See Note [FFoldType and functorLikeTraverse] ft_trav :: FFoldType (State [RdrName] (Maybe (LHsExpr RdrName))) ft_trav = FT { ft_triv = return Nothing -- traverse f = pure x , ft_var = return (Just f_Expr) -- traverse f = f x , ft_tup = \t gs -> do gg <- sequence gs lam <- mkSimpleLam $ mkSimpleTupleCase match_for_con t gg return (Just lam) -- traverse f = \x -> case x of (a1,a2,..) -> -- (,,) <$> g1 a1 <*> g2 a2 <*> .. , ft_ty_app = \_ g -> fmap (nlHsApp traverse_Expr) <$> g -- traverse f = traverse g , ft_forall = \_ g -> g , ft_co_var = panic "contravariant" , ft_fun = panic "function" , ft_bad_app = panic "in other argument" } -- Con a1 a2 ... -> fmap (\b1 b2 ... -> Con b1 b2 ...) (g1 a1) -- <*> g2 a2 <*> ... match_for_con :: [LPat RdrName] -> DataCon -> [Maybe (LHsExpr RdrName)] -> State [RdrName] (LMatch RdrName (LHsExpr RdrName)) match_for_con = mkSimpleConMatch2 CaseAlt $ \con xs -> return (mkApCon con xs) where -- fmap (\b1 b2 ... -> Con b1 b2 ...) x1 <*> x2 <*> .. mkApCon :: LHsExpr RdrName -> [LHsExpr RdrName] -> LHsExpr RdrName mkApCon con [] = nlHsApps pure_RDR [con] mkApCon con (x:xs) = foldl appAp (nlHsApps fmap_RDR [con,x]) xs where appAp x y = nlHsApps ap_RDR [x,y] {- ************************************************************************ * * Lift instances * * ************************************************************************ Example: data Foo a = Foo a | a :^: a deriving Lift ==> instance (Lift a) => Lift (Foo a) where lift (Foo a) = appE (conE (mkNameG_d "package-name" "ModuleName" "Foo")) (lift a) lift (u :^: v) = infixApp (lift u) (conE (mkNameG_d "package-name" "ModuleName" ":^:")) (lift v) Note that (mkNameG_d "package-name" "ModuleName" "Foo") is equivalent to what 'Foo would be when using the -XTemplateHaskell extension. To make sure that -XDeriveLift can be used on stage-1 compilers, however, we expliticly invoke makeG_d. -} gen_Lift_binds :: SrcSpan -> TyCon -> (LHsBinds RdrName, BagDerivStuff) gen_Lift_binds loc tycon | null data_cons = (unitBag (L loc $ mkFunBind (L loc lift_RDR) [mkMatch (FunRhs (L loc lift_RDR) Prefix) [nlWildPat] errorMsg_Expr (noLoc emptyLocalBinds)]) , emptyBag) | otherwise = (unitBag lift_bind, emptyBag) where errorMsg_Expr = nlHsVar error_RDR `nlHsApp` nlHsLit (mkHsString $ "Can't lift value of empty datatype " ++ tycon_str) lift_bind = mk_FunBind loc lift_RDR (map pats_etc data_cons) data_cons = tyConDataCons tycon tycon_str = occNameString . nameOccName . tyConName $ tycon pats_etc data_con = ([con_pat], lift_Expr) where con_pat = nlConVarPat data_con_RDR as_needed data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con as_needed = take con_arity as_RDRs lifted_as = zipWithEqual "mk_lift_app" mk_lift_app tys_needed as_needed tycon_name = tyConName tycon is_infix = dataConIsInfix data_con tys_needed = dataConOrigArgTys data_con mk_lift_app ty a | not (isUnliftedType ty) = nlHsApp (nlHsVar lift_RDR) (nlHsVar a) | otherwise = nlHsApp (nlHsVar litE_RDR) (primLitOp (mkBoxExp (nlHsVar a))) where (primLitOp, mkBoxExp) = primLitOps "Lift" tycon ty pkg_name = unitIdString . moduleUnitId . nameModule $ tycon_name mod_name = moduleNameString . moduleName . nameModule $ tycon_name con_name = occNameString . nameOccName . dataConName $ data_con conE_Expr = nlHsApp (nlHsVar conE_RDR) (nlHsApps mkNameG_dRDR (map (nlHsLit . mkHsString) [pkg_name, mod_name, con_name])) lift_Expr | is_infix = nlHsApps infixApp_RDR [a1, conE_Expr, a2] | otherwise = foldl mk_appE_app conE_Expr lifted_as (a1:a2:_) = lifted_as mk_appE_app :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName mk_appE_app a b = nlHsApps appE_RDR [a, b] {- ************************************************************************ * * Newtype-deriving instances * * ************************************************************************ Note [Newtype-deriving instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We take every method in the original instance and `coerce` it to fit into the derived instance. We need a type annotation on the argument to `coerce` to make it obvious what instantiation of the method we're coercing from. So from, say, class C a b where op :: a -> [b] -> Int newtype T x = MkT <rep-ty> instance C a <rep-ty> => C a (T x) where op = (coerce (op :: a -> [<rep-ty>] -> Int) ) :: a -> [T x] -> Int Notice that we give the 'coerce' call two type signatures: one to fix the of the inner call, and one for the expected type. The outer type signature ought to be redundant, but may improve error messages. The inner one is essential to fix the type at which 'op' is called. See #8503 for more discussion. Here's a wrinkle. Supppose 'op' is locally overloaded: class C2 b where op2 :: forall a. Eq a => a -> [b] -> Int Then we could do exactly as above, but it's a bit redundant to instantiate op, then re-generalise with the inner signature. (The inner sig is only there to fix the type at which 'op' is called.) So we just instantiate the signature, and add instance C2 <rep-ty> => C2 (T x) where op2 = (coerce (op2 :: a -> [<rep-ty>] -> Int) ) :: forall a. Eq a => a -> [T x] -> Int -} gen_Newtype_binds :: SrcSpan -> Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> LHsBinds RdrName -- See Note [Newtype-deriving instances] gen_Newtype_binds loc cls inst_tvs cls_tys rhs_ty = listToBag $ map mk_bind (classMethods cls) where coerce_RDR = getRdrName coerceId mk_bind :: Id -> LHsBind RdrName mk_bind meth_id = mkRdrFunBind (L loc meth_RDR) [mkSimpleMatch (FunRhs (L loc meth_RDR) Prefix) [] rhs_expr] where Pair from_ty to_ty = mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty meth_id -- See "wrinkle" in Note [Newtype-deriving instances] (_, _, from_ty') = tcSplitSigmaTy from_ty meth_RDR = getRdrName meth_id rhs_expr = ( nlHsVar coerce_RDR `nlHsApp` (nlHsVar meth_RDR `nlExprWithTySig` toLHsSigWcType from_ty')) `nlExprWithTySig` toLHsSigWcType to_ty nlExprWithTySig :: LHsExpr RdrName -> LHsSigWcType RdrName -> LHsExpr RdrName nlExprWithTySig e s = noLoc (ExprWithTySig e s) mkCoerceClassMethEqn :: Class -- the class being derived -> [TyVar] -- the tvs in the instance head -> [Type] -- instance head parameters (incl. newtype) -> Type -- the representation type (already eta-reduced) -> Id -- the method to look at -> Pair Type -- See Note [Newtype-deriving instances] -- The pair is the (from_type, to_type), where to_type is -- the type of the method we are tyrying to get mkCoerceClassMethEqn cls inst_tvs cls_tys rhs_ty id = Pair (substTy rhs_subst user_meth_ty) (substTy lhs_subst user_meth_ty) where cls_tvs = classTyVars cls in_scope = mkInScopeSet $ mkVarSet inst_tvs lhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs cls_tys) rhs_subst = mkTvSubst in_scope (zipTyEnv cls_tvs (changeLast cls_tys rhs_ty)) (_class_tvs, _class_constraint, user_meth_ty) = tcSplitMethodTy (varType id) changeLast :: [a] -> a -> [a] changeLast [] _ = panic "changeLast" changeLast [_] x = [x] changeLast (x:xs) x' = x : changeLast xs x' {- ************************************************************************ * * \subsection{Generating extra binds (@con2tag@ and @tag2con@)} * * ************************************************************************ \begin{verbatim} data Foo ... = ... con2tag_Foo :: Foo ... -> Int# tag2con_Foo :: Int -> Foo ... -- easier if Int, not Int# maxtag_Foo :: Int -- ditto (NB: not unlifted) \end{verbatim} The `tags' here start at zero, hence the @fIRST_TAG@ (currently one) fiddling around. -} genAuxBindSpec :: SrcSpan -> AuxBindSpec -> (LHsBind RdrName, LSig RdrName) genAuxBindSpec loc (DerivCon2Tag tycon) = (mk_FunBind loc rdr_name eqns, L loc (TypeSig [L loc rdr_name] sig_ty)) where rdr_name = con2tag_RDR tycon sig_ty = mkLHsSigWcType $ L loc $ HsCoreTy $ mkSpecSigmaTy (tyConTyVars tycon) (tyConStupidTheta tycon) $ mkParentType tycon `mkFunTy` intPrimTy lots_of_constructors = tyConFamilySize tycon > 8 -- was: mAX_FAMILY_SIZE_FOR_VEC_RETURNS -- but we don't do vectored returns any more. eqns | lots_of_constructors = [get_tag_eqn] | otherwise = map mk_eqn (tyConDataCons tycon) get_tag_eqn = ([nlVarPat a_RDR], nlHsApp (nlHsVar getTag_RDR) a_Expr) mk_eqn :: DataCon -> ([LPat RdrName], LHsExpr RdrName) mk_eqn con = ([nlWildConPat con], nlHsLit (HsIntPrim "" (toInteger ((dataConTag con) - fIRST_TAG)))) genAuxBindSpec loc (DerivTag2Con tycon) = (mk_FunBind loc rdr_name [([nlConVarPat intDataCon_RDR [a_RDR]], nlHsApp (nlHsVar tagToEnum_RDR) a_Expr)], L loc (TypeSig [L loc rdr_name] sig_ty)) where sig_ty = mkLHsSigWcType $ L loc $ HsCoreTy $ mkSpecForAllTys (tyConTyVars tycon) $ intTy `mkFunTy` mkParentType tycon rdr_name = tag2con_RDR tycon genAuxBindSpec loc (DerivMaxTag tycon) = (mkHsVarBind loc rdr_name rhs, L loc (TypeSig [L loc rdr_name] sig_ty)) where rdr_name = maxtag_RDR tycon sig_ty = mkLHsSigWcType (L loc (HsCoreTy intTy)) rhs = nlHsApp (nlHsVar intDataCon_RDR) (nlHsLit (HsIntPrim "" max_tag)) max_tag = case (tyConDataCons tycon) of data_cons -> toInteger ((length data_cons) - fIRST_TAG) type SeparateBagsDerivStuff = -- AuxBinds and SYB bindings ( Bag (LHsBind RdrName, LSig RdrName) -- Extra bindings (used by Generic only) , Bag (FamInst) -- Extra family instances , Bag (InstInfo RdrName)) -- Extra instances genAuxBinds :: SrcSpan -> BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds loc b = genAuxBinds' b2 where (b1,b2) = partitionBagWith splitDerivAuxBind b splitDerivAuxBind (DerivAuxBind x) = Left x splitDerivAuxBind x = Right x rm_dups = foldrBag dup_check emptyBag dup_check a b = if anyBag (== a) b then b else consBag a b genAuxBinds' :: BagDerivStuff -> SeparateBagsDerivStuff genAuxBinds' = foldrBag f ( mapBag (genAuxBindSpec loc) (rm_dups b1) , emptyBag, emptyBag) f :: DerivStuff -> SeparateBagsDerivStuff -> SeparateBagsDerivStuff f (DerivAuxBind _) = panic "genAuxBinds'" -- We have removed these before f (DerivHsBind b) = add1 b f (DerivFamInst t) = add2 t f (DerivInst i) = add3 i add1 x (a,b,c) = (x `consBag` a,b,c) add2 x (a,b,c) = (a,x `consBag` b,c) add3 x (a,b,c) = (a,b,x `consBag` c) mkParentType :: TyCon -> Type -- Turn the representation tycon of a family into -- a use of its family constructor mkParentType tc = case tyConFamInst_maybe tc of Nothing -> mkTyConApp tc (mkTyVarTys (tyConTyVars tc)) Just (fam_tc,tys) -> mkTyConApp fam_tc tys {- ************************************************************************ * * \subsection{Utility bits for generating bindings} * * ************************************************************************ -} mk_FunBind :: SrcSpan -> RdrName -> [([LPat RdrName], LHsExpr RdrName)] -> LHsBind RdrName mk_FunBind = mk_HRFunBind 0 -- by using mk_FunBind and not mk_HRFunBind, -- the caller says that the Void case needs no -- patterns -- | This variant of 'mk_FunBind' puts an 'Arity' number of wildcards before -- the "=" in the empty-data-decl case. This is necessary if the function -- has a higher-rank type, like foldl. (See deriving/should_compile/T4302) mk_HRFunBind :: Arity -> SrcSpan -> RdrName -> [([LPat RdrName], LHsExpr RdrName)] -> LHsBind RdrName mk_HRFunBind arity loc fun pats_and_exprs = mkHRRdrFunBind arity (L loc fun) matches where matches = [mkMatch (FunRhs (L loc fun) Prefix) p e (noLoc emptyLocalBinds) | (p,e) <-pats_and_exprs] mkRdrFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> LHsBind RdrName mkRdrFunBind = mkHRRdrFunBind 0 mkHRRdrFunBind :: Arity -> Located RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> LHsBind RdrName mkHRRdrFunBind arity fun@(L loc fun_rdr) matches = L loc (mkFunBind fun matches') where -- Catch-all eqn looks like -- fmap = error "Void fmap" -- It's needed if there no data cons at all, -- which can happen with -XEmptyDataDecls -- See Trac #4302 matches' = if null matches then [mkMatch (FunRhs fun Prefix) (replicate arity nlWildPat) (error_Expr str) (noLoc emptyLocalBinds)] else matches str = "Void " ++ occNameString (rdrNameOcc fun_rdr) box :: String -- The class involved -> TyCon -- The tycon involved -> LHsExpr RdrName -- The argument -> Type -- The argument type -> LHsExpr RdrName -- Boxed version of the arg -- See Note [Deriving and unboxed types] in TcDeriv box cls_str tycon arg arg_ty = nlHsApp (nlHsVar box_con) arg where box_con = assoc_ty_id cls_str tycon boxConTbl arg_ty --------------------- primOrdOps :: String -- The class involved -> TyCon -- The tycon involved -> Type -- The type -> (RdrName, RdrName, RdrName, RdrName, RdrName) -- (lt,le,eq,ge,gt) -- See Note [Deriving and unboxed types] in TcDeriv primOrdOps str tycon ty = assoc_ty_id str tycon ordOpTbl ty primLitOps :: String -- The class involved -> TyCon -- The tycon involved -> Type -- The type -> ( LHsExpr RdrName -> LHsExpr RdrName -- Constructs a Q Exp value , LHsExpr RdrName -> LHsExpr RdrName -- Constructs a boxed value ) primLitOps str tycon ty = ( assoc_ty_id str tycon litConTbl ty , \v -> nlHsVar boxRDR `nlHsApp` v ) where boxRDR | ty `eqType` addrPrimTy = unpackCString_RDR | otherwise = assoc_ty_id str tycon boxConTbl ty ordOpTbl :: [(Type, (RdrName, RdrName, RdrName, RdrName, RdrName))] ordOpTbl = [(charPrimTy , (ltChar_RDR , leChar_RDR , eqChar_RDR , geChar_RDR , gtChar_RDR )) ,(intPrimTy , (ltInt_RDR , leInt_RDR , eqInt_RDR , geInt_RDR , gtInt_RDR )) ,(wordPrimTy , (ltWord_RDR , leWord_RDR , eqWord_RDR , geWord_RDR , gtWord_RDR )) ,(addrPrimTy , (ltAddr_RDR , leAddr_RDR , eqAddr_RDR , geAddr_RDR , gtAddr_RDR )) ,(floatPrimTy , (ltFloat_RDR , leFloat_RDR , eqFloat_RDR , geFloat_RDR , gtFloat_RDR )) ,(doublePrimTy, (ltDouble_RDR, leDouble_RDR, eqDouble_RDR, geDouble_RDR, gtDouble_RDR)) ] boxConTbl :: [(Type, RdrName)] boxConTbl = [(charPrimTy , getRdrName charDataCon ) ,(intPrimTy , getRdrName intDataCon ) ,(wordPrimTy , getRdrName wordDataCon ) ,(floatPrimTy , getRdrName floatDataCon ) ,(doublePrimTy, getRdrName doubleDataCon) ] -- | A table of postfix modifiers for unboxed values. postfixModTbl :: [(Type, String)] postfixModTbl = [(charPrimTy , "#" ) ,(intPrimTy , "#" ) ,(wordPrimTy , "##") ,(floatPrimTy , "#" ) ,(doublePrimTy, "##") ] litConTbl :: [(Type, LHsExpr RdrName -> LHsExpr RdrName)] litConTbl = [(charPrimTy , nlHsApp (nlHsVar charPrimL_RDR)) ,(intPrimTy , nlHsApp (nlHsVar intPrimL_RDR) . nlHsApp (nlHsVar toInteger_RDR)) ,(wordPrimTy , nlHsApp (nlHsVar wordPrimL_RDR) . nlHsApp (nlHsVar toInteger_RDR)) ,(addrPrimTy , nlHsApp (nlHsVar stringPrimL_RDR) . nlHsApp (nlHsApp (nlHsVar map_RDR) (compose_RDR `nlHsApps` [ nlHsVar fromIntegral_RDR , nlHsVar fromEnum_RDR ]))) ,(floatPrimTy , nlHsApp (nlHsVar floatPrimL_RDR) . nlHsApp (nlHsVar toRational_RDR)) ,(doublePrimTy, nlHsApp (nlHsVar doublePrimL_RDR) . nlHsApp (nlHsVar toRational_RDR)) ] -- | Lookup `Type` in an association list. assoc_ty_id :: String -- The class involved -> TyCon -- The tycon involved -> [(Type,a)] -- The table -> Type -- The type -> a -- The result of the lookup assoc_ty_id cls_str _ tbl ty | null res = pprPanic "Error in deriving:" (text "Can't derive" <+> text cls_str <+> text "for primitive type" <+> ppr ty) | otherwise = head res where res = [id | (ty',id) <- tbl, ty `eqType` ty'] ----------------------------------------------------------------------- and_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName and_Expr a b = genOpApp a and_RDR b ----------------------------------------------------------------------- eq_Expr :: TyCon -> Type -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName eq_Expr tycon ty a b | not (isUnliftedType ty) = genOpApp a eq_RDR b | otherwise = genPrimOpApp a prim_eq b where (_, _, prim_eq, _, _) = primOrdOps "Eq" tycon ty untag_Expr :: TyCon -> [( RdrName, RdrName)] -> LHsExpr RdrName -> LHsExpr RdrName untag_Expr _ [] expr = expr untag_Expr tycon ((untag_this, put_tag_here) : more) expr = nlHsCase (nlHsPar (nlHsVarApps (con2tag_RDR tycon) [untag_this])) {-of-} [mkHsCaseAlt (nlVarPat put_tag_here) (untag_Expr tycon more expr)] enum_from_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_then_to_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName enum_from_to_Expr f t2 = nlHsApp (nlHsApp (nlHsVar enumFromTo_RDR) f) t2 enum_from_then_to_Expr f t t2 = nlHsApp (nlHsApp (nlHsApp (nlHsVar enumFromThenTo_RDR) f) t) t2 showParen_Expr :: LHsExpr RdrName -> LHsExpr RdrName -> LHsExpr RdrName showParen_Expr e1 e2 = nlHsApp (nlHsApp (nlHsVar showParen_RDR) e1) e2 nested_compose_Expr :: [LHsExpr RdrName] -> LHsExpr RdrName nested_compose_Expr [] = panic "nested_compose_expr" -- Arg is always non-empty nested_compose_Expr [e] = parenify e nested_compose_Expr (e:es) = nlHsApp (nlHsApp (nlHsVar compose_RDR) (parenify e)) (nested_compose_Expr es) -- impossible_Expr is used in case RHSs that should never happen. -- We generate these to keep the desugarer from complaining that they *might* happen! error_Expr :: String -> LHsExpr RdrName error_Expr string = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString string)) -- illegal_Expr is used when signalling error conditions in the RHS of a derived -- method. It is currently only used by Enum.{succ,pred} illegal_Expr :: String -> String -> String -> LHsExpr RdrName illegal_Expr meth tp msg = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString (meth ++ '{':tp ++ "}: " ++ msg))) -- illegal_toEnum_tag is an extended version of illegal_Expr, which also allows you -- to include the value of a_RDR in the error string. illegal_toEnum_tag :: String -> RdrName -> LHsExpr RdrName illegal_toEnum_tag tp maxtag = nlHsApp (nlHsVar error_RDR) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ("toEnum{" ++ tp ++ "}: tag (")))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar a_RDR)) (nlHsApp (nlHsApp (nlHsVar append_RDR) (nlHsLit (mkHsString ") is outside of enumeration's range (0,"))) (nlHsApp (nlHsApp (nlHsApp (nlHsVar showsPrec_RDR) (nlHsIntLit 0)) (nlHsVar maxtag)) (nlHsLit (mkHsString ")")))))) parenify :: LHsExpr RdrName -> LHsExpr RdrName parenify e@(L _ (HsVar _)) = e parenify e = mkHsPar e -- genOpApp wraps brackets round the operator application, so that the -- renamer won't subsequently try to re-associate it. genOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genOpApp e1 op e2 = nlHsPar (nlHsOpApp e1 op e2) genPrimOpApp :: LHsExpr RdrName -> RdrName -> LHsExpr RdrName -> LHsExpr RdrName genPrimOpApp e1 op e2 = nlHsPar (nlHsApp (nlHsVar tagToEnum_RDR) (nlHsOpApp e1 op e2)) a_RDR, b_RDR, c_RDR, d_RDR, f_RDR, k_RDR, z_RDR, ah_RDR, bh_RDR, ch_RDR, dh_RDR :: RdrName a_RDR = mkVarUnqual (fsLit "a") b_RDR = mkVarUnqual (fsLit "b") c_RDR = mkVarUnqual (fsLit "c") d_RDR = mkVarUnqual (fsLit "d") f_RDR = mkVarUnqual (fsLit "f") k_RDR = mkVarUnqual (fsLit "k") z_RDR = mkVarUnqual (fsLit "z") ah_RDR = mkVarUnqual (fsLit "a#") bh_RDR = mkVarUnqual (fsLit "b#") ch_RDR = mkVarUnqual (fsLit "c#") dh_RDR = mkVarUnqual (fsLit "d#") as_RDRs, bs_RDRs, cs_RDRs :: [RdrName] as_RDRs = [ mkVarUnqual (mkFastString ("a"++show i)) | i <- [(1::Int) .. ] ] bs_RDRs = [ mkVarUnqual (mkFastString ("b"++show i)) | i <- [(1::Int) .. ] ] cs_RDRs = [ mkVarUnqual (mkFastString ("c"++show i)) | i <- [(1::Int) .. ] ] a_Expr, c_Expr, f_Expr, z_Expr, ltTag_Expr, eqTag_Expr, gtTag_Expr, false_Expr, true_Expr, fmap_Expr, mempty_Expr, foldMap_Expr, traverse_Expr :: LHsExpr RdrName a_Expr = nlHsVar a_RDR -- b_Expr = nlHsVar b_RDR c_Expr = nlHsVar c_RDR f_Expr = nlHsVar f_RDR z_Expr = nlHsVar z_RDR ltTag_Expr = nlHsVar ltTag_RDR eqTag_Expr = nlHsVar eqTag_RDR gtTag_Expr = nlHsVar gtTag_RDR false_Expr = nlHsVar false_RDR true_Expr = nlHsVar true_RDR fmap_Expr = nlHsVar fmap_RDR -- pure_Expr = nlHsVar pure_RDR mempty_Expr = nlHsVar mempty_RDR foldMap_Expr = nlHsVar foldMap_RDR traverse_Expr = nlHsVar traverse_RDR a_Pat, b_Pat, c_Pat, d_Pat, f_Pat, k_Pat, z_Pat :: LPat RdrName a_Pat = nlVarPat a_RDR b_Pat = nlVarPat b_RDR c_Pat = nlVarPat c_RDR d_Pat = nlVarPat d_RDR f_Pat = nlVarPat f_RDR k_Pat = nlVarPat k_RDR z_Pat = nlVarPat z_RDR minusInt_RDR, tagToEnum_RDR :: RdrName minusInt_RDR = getRdrName (primOpId IntSubOp ) tagToEnum_RDR = getRdrName (primOpId TagToEnumOp) con2tag_RDR, tag2con_RDR, maxtag_RDR :: TyCon -> RdrName -- Generates Orig s RdrName, for the binding positions con2tag_RDR tycon = mk_tc_deriv_name tycon mkCon2TagOcc tag2con_RDR tycon = mk_tc_deriv_name tycon mkTag2ConOcc maxtag_RDR tycon = mk_tc_deriv_name tycon mkMaxTagOcc mk_tc_deriv_name :: TyCon -> (OccName -> OccName) -> RdrName mk_tc_deriv_name tycon occ_fun = mkAuxBinderName (tyConName tycon) occ_fun mkAuxBinderName :: Name -> (OccName -> OccName) -> RdrName -- ^ Make a top-level binder name for an auxiliary binding for a parent name -- See Note [Auxiliary binders] mkAuxBinderName parent occ_fun = mkRdrUnqual (occ_fun stable_parent_occ) where stable_parent_occ = mkOccName (occNameSpace parent_occ) stable_string stable_string | opt_PprStyle_Debug = parent_stable | otherwise = parent_stable_hash parent_stable = nameStableString parent parent_stable_hash = let Fingerprint high low = fingerprintString parent_stable in toBase62 high ++ toBase62Padded low -- See Note [Base 62 encoding 128-bit integers] parent_occ = nameOccName parent {- Note [Auxiliary binders] ~~~~~~~~~~~~~~~~~~~~~~~~ We often want to make a top-level auxiliary binding. E.g. for comparison we haev instance Ord T where compare a b = $con2tag a `compare` $con2tag b $con2tag :: T -> Int $con2tag = ...code.... Of course these top-level bindings should all have distinct name, and we are generating RdrNames here. We can't just use the TyCon or DataCon to distinguish because with standalone deriving two imported TyCons might both be called T! (See Trac #7947.) So we use package name, module name and the name of the parent (T in this example) as part of the OccName we generate for the new binding. To make the symbol names short we take a base62 hash of the full name. In the past we used the *unique* from the parent, but that's not stable across recompilations as uniques are nondeterministic. Note [DeriveFoldable with ExistentialQuantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Functor and Traversable instances can only be derived for data types whose last type parameter is truly universally polymorphic. For example: data T a b where T1 :: b -> T a b -- YES, b is unconstrained T2 :: Ord b => b -> T a b -- NO, b is constrained by (Ord b) T3 :: b ~ Int => b -> T a b -- NO, b is constrained by (b ~ Int) T4 :: Int -> T a Int -- NO, this is just like T3 T5 :: Ord a => a -> b -> T a b -- YES, b is unconstrained, even -- though a is existential T6 :: Int -> T Int b -- YES, b is unconstrained For Foldable instances, however, we can completely lift the constraint that the last type parameter be truly universally polymorphic. This means that T (as defined above) can have a derived Foldable instance: instance Foldable (T a) where foldr f z (T1 b) = f b z foldr f z (T2 b) = f b z foldr f z (T3 b) = f b z foldr f z (T4 b) = z foldr f z (T5 a b) = f b z foldr f z (T6 a) = z foldMap f (T1 b) = f b foldMap f (T2 b) = f b foldMap f (T3 b) = f b foldMap f (T4 b) = mempty foldMap f (T5 a b) = f b foldMap f (T6 a) = mempty In a Foldable instance, it is safe to fold over an occurrence of the last type parameter that is not truly universally polymorphic. However, there is a bit of subtlety in determining what is actually an occurrence of a type parameter. T3 and T4, as defined above, provide one example: data T a b where ... T3 :: b ~ Int => b -> T a b T4 :: Int -> T a Int ... instance Foldable (T a) where ... foldr f z (T3 b) = f b z foldr f z (T4 b) = z ... foldMap f (T3 b) = f b foldMap f (T4 b) = mempty ... Notice that the argument of T3 is folded over, whereas the argument of T4 is not. This is because we only fold over constructor arguments that syntactically mention the universally quantified type parameter of that particular data constructor. See foldDataConArgs for how this is implemented. As another example, consider the following data type. The argument of each constructor has the same type as the last type parameter: data E a where E1 :: (a ~ Int) => a -> E a E2 :: Int -> E Int E3 :: (a ~ Int) => a -> E Int E4 :: (a ~ Int) => Int -> E a Only E1's argument is an occurrence of a universally quantified type variable that is syntactically equivalent to the last type parameter, so only E1's argument will be be folded over in a derived Foldable instance. See Trac #10447 for the original discussion on this feature. Also see https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/DeriveFunctor for a more in-depth explanation. Note [FFoldType and functorLikeTraverse] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Deriving Functor, Foldable, and Traversable all require generating expressions which perform an operation on each argument of a data constructor depending on the argument's type. In particular, a generated operation can be different depending on whether the type mentions the last type variable of the datatype (e.g., if you have data T a = MkT a Int, then a generated foldr expresion would fold over the first argument of MkT, but not the second). This pattern is abstracted with the FFoldType datatype, which provides hooks for the user to specify how a constructor argument should be folded when it has a type with a particular "shape". The shapes are as follows (assume that a is the last type variable in a given datatype): * ft_triv: The type does not mention the last type variable at all. Examples: Int, b * ft_var: The type is syntactically equal to the last type variable. Moreover, the type appears in a covariant position (see the Deriving Functor instances section of the users' guide for an in-depth explanation of covariance vs. contravariance). Example: a (covariantly) * ft_co_var: The type is syntactically equal to the last type variable. Moreover, the type appears in a contravariant position. Example: a (contravariantly) * ft_fun: A function type which mentions the last type variable in the argument position, result position or both. Examples: a -> Int, Int -> a, Maybe a -> [a] * ft_tup: A tuple type which mentions the last type variable in at least one of its fields. The TyCon argument of ft_tup represents the particular tuple's type constructor. Examples: (a, Int), (Maybe a, [a], Either a Int) * ft_ty_app: A type is being applied to the last type parameter, where the applied type does not mention the last type parameter (if it did, it would fall under ft_bad_app). The Type argument to ft_ty_app represents the applied type. Note that functions, tuples, and foralls are distinct cases and take precedence of ft_ty_app. (For example, (Int -> a) would fall under (ft_fun Int a), not (ft_ty_app ((->) Int) a). Examples: Maybe a, Either b a * ft_bad_app: A type application uses the last type parameter in a position other than the last argument. This case is singled out because Functor, Foldable, and Traversable instances cannot be derived for datatypes containing arguments with such types. Examples: Either a Int, Const a b * ft_forall: A forall'd type mentions the last type parameter on its right- hand side (and is not quantified on the left-hand side). This case is present mostly for plumbing purposes. Example: forall b. Either b a If FFoldType describes a strategy for folding subcomponents of a Type, then functorLikeTraverse is the function that applies that strategy to the entirety of a Type, returning the final folded-up result. foldDataConArgs applies functorLikeTraverse to every argument type of a constructor, returning a list of the fold results. This makes foldDataConArgs a natural way to generate the subexpressions in a generated fmap, foldr, foldMap, or traverse definition (the subexpressions must then be combined in a method-specific fashion to form the final generated expression). Deriving Generic1 also does validity checking by looking for the last type variable in certain positions of a constructor's argument types, so it also uses foldDataConArgs. See Note [degenerate use of FFoldType] in TcGenGenerics. Note [Generated code for DeriveFoldable and DeriveTraversable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We adapt the algorithms for -XDeriveFoldable and -XDeriveTraversable based on that of -XDeriveFunctor. However, there an important difference between deriving the former two typeclasses and the latter one, which is best illustrated by the following scenario: data WithInt a = WithInt a Int# deriving (Functor, Foldable, Traversable) The generated code for the Functor instance is straightforward: instance Functor WithInt where fmap f (WithInt a i) = WithInt (f a) i But if we use too similar of a strategy for deriving the Foldable and Traversable instances, we end up with this code: instance Foldable WithInt where foldMap f (WithInt a i) = f a <> mempty instance Traversable WithInt where traverse f (WithInt a i) = fmap WithInt (f a) <*> pure i This is unsatisfying for two reasons: 1. The Traversable instance doesn't typecheck! Int# is of kind #, but pure expects an argument whose type is of kind *. This effectively prevents Traversable from being derived for any datatype with an unlifted argument type (Trac #11174). 2. The generated code contains superfluous expressions. By the Monoid laws, we can reduce (f a <> mempty) to (f a), and by the Applicative laws, we can reduce (fmap WithInt (f a) <*> pure i) to (fmap (\b -> WithInt b i) (f a)). We can fix both of these issues by incorporating a slight twist to the usual algorithm that we use for -XDeriveFunctor. The differences can be summarized as follows: 1. In the generated expression, we only fold over arguments whose types mention the last type parameter. Any other argument types will simply produce useless 'mempty's or 'pure's, so they can be safely ignored. 2. In the case of -XDeriveTraversable, instead of applying ConName, we apply (\b_i ... b_k -> ConName a_1 ... a_n), where * ConName has n arguments * {b_i, ..., b_k} is a subset of {a_1, ..., a_n} whose indices correspond to the arguments whose types mention the last type parameter. As a consequence, taking the difference of {a_1, ..., a_n} and {b_i, ..., b_k} yields the all the argument values of ConName whose types do not mention the last type parameter. Note that [i, ..., k] is a strictly increasing—but not necessarily consecutive—integer sequence. For example, the datatype data Foo a = Foo Int a Int a would generate the following Traversable instance: instance Traversable Foo where traverse f (Foo a1 a2 a3 a4) = fmap (\b2 b4 -> Foo a1 b2 a3 b4) (f a2) <*> f a4 Technically, this approach would also work for -XDeriveFunctor as well, but we decide not to do so because: 1. There's not much benefit to generating, e.g., ((\b -> WithInt b i) (f a)) instead of (WithInt (f a) i). 2. There would be certain datatypes for which the above strategy would generate Functor code that would fail to typecheck. For example: data Bar f a = Bar (forall f. Functor f => f a) deriving Functor With the conventional algorithm, it would generate something like: fmap f (Bar a) = Bar (fmap f a) which typechecks. But with the strategy mentioned above, it would generate: fmap f (Bar a) = (\b -> Bar b) (fmap f a) which does not typecheck, since GHC cannot unify the rank-2 type variables in the types of b and (fmap f a). -}
vTurbine/ghc
compiler/typecheck/TcGenDeriv.hs
Haskell
bsd-3-clause
119,963
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.UI.GLUT.QueryUtils -- Copyright : (c) Sven Panne 2003 -- License : BSD-style (see the file libraries/GLUT/LICENSE) -- -- Maintainer : sven_panne@yahoo.com -- Stability : provisional -- Portability : portable -- -- This is a purely internal module with utilities to query GLUT state. -- -------------------------------------------------------------------------------- module Graphics.UI.GLUT.QueryUtils ( Getter, simpleGet, layerGet, deviceGet ) where import Control.Monad ( liftM ) import Foreign.C.Types ( CInt ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum ) -------------------------------------------------------------------------------- type PrimGetter = GLenum -> IO CInt type Getter a = (CInt -> a) -> GLenum -> IO a makeGetter :: PrimGetter -> Getter a makeGetter g f = liftM f . g simpleGet, layerGet, deviceGet :: Getter a simpleGet = makeGetter glutGet layerGet = makeGetter glutLayerGet deviceGet = makeGetter glutDeviceGet foreign import stdcall unsafe "HsGLUT.h glutGet" glutGet :: PrimGetter foreign import stdcall unsafe "HsGLUT.h glutLayerGet" glutLayerGet :: PrimGetter foreign import stdcall unsafe "HsGLUT.h glutDeviceGet" glutDeviceGet :: PrimGetter
OS2World/DEV-UTIL-HUGS
libraries/Graphics/UI/GLUT/QueryUtils.hs
Haskell
bsd-3-clause
1,360
----------------------------------------------------------------------------- -- | -- Module : Data.Metrology.Parser -- Copyright : (C) 2014 Richard Eisenberg -- License : BSD-style (see LICENSE) -- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu) -- Stability : experimental -- Portability : non-portable -- -- This module exports functions allowing users to create their own unit -- quasiquoters to make for compact unit expressions. -- -- A typical use case is this: -- -- > $(makeQuasiQuoter "unit" [''Kilo, ''Milli] [''Meter, ''Second]) -- -- and then, /in a separate module/ (due to GHC's staging constraints) -- -- > x = 3 % [unit| m/s^2 ] -- -- The unit expressions can refer to the prefixes and units specified in -- the call to 'makeQuasiQuoter'. The spellings of the prefixes and units -- are taken from their @Show@ instances. -- -- The syntax for these expressions is like -- F#'s. There are four arithmetic operators (@*@, @/@, @^@, and juxtaposition). -- Exponentiation binds the tightest, and it allows an integer to its right -- (possibly with minus signs and parentheses). Next tightest is juxtaposition, -- which indicates multiplication. Because juxtaposition binds tighter than division, -- the expressions @m/s^2@ and @m/s s@ are equivalent. Multiplication and -- division bind the loosest and are left-associative, meaning that @m/s*s@ -- is equivalent to @(m/s)*s@, probably not what you meant. Parentheses in -- unit expressions are allowed, of course. -- -- Within a unit string (that is, a unit with an optional prefix), there may -- be ambiguity. If a unit string can be interpreted as a unit without a -- prefix, that parsing is preferred. Thus, @min@ would be minutes, not -- milli-inches (assuming appropriate prefixes and units available.) There still -- may be ambiguity between unit strings, even interpreting the string as a prefix -- and a base unit. If a unit string is amiguous in this way, it is rejected. -- For example, if we have prefixes @da@ and @d@ and units @m@ and @am@, then -- @dam@ is ambiguous like this. ----------------------------------------------------------------------------- {-# LANGUAGE TemplateHaskell, CPP #-} {-# OPTIONS_HADDOCK prune #-} module Data.Metrology.Parser ( -- * Quasiquoting interface makeQuasiQuoter, allUnits, allPrefixes, -- * Direct interface -- | The definitions below allow users to access the unit parser directly. -- The parser produces 'UnitExp's which can then be further processed as -- necessary. parseUnit, UnitExp(..), SymbolTable, mkSymbolTable, -- for internal use only parseUnitExp, parseUnitType ) where import Prelude hiding ( exp ) import Language.Haskell.TH hiding ( Pred ) import Language.Haskell.TH.Quote import Language.Haskell.TH.Desugar.Lift () -- get the Lift Name instance import Data.Maybe import Control.Monad import Text.Parse.Units import Data.Metrology import Data.Metrology.TH ---------------------------------------------------------------------- -- TH conversions ---------------------------------------------------------------------- parseUnitExp :: SymbolTable Name Name -> String -> Either String Exp parseUnitExp tab s = to_exp `liftM` parseUnit tab s -- the Either monad where to_exp Unity = ConE 'Number to_exp (Unit (Just pre) unit) = ConE '(:@) `AppE` of_type pre `AppE` of_type unit to_exp (Unit Nothing unit) = of_type unit to_exp (Mult e1 e2) = ConE '(:*) `AppE` to_exp e1 `AppE` to_exp e2 to_exp (Div e1 e2) = ConE '(:/) `AppE` to_exp e1 `AppE` to_exp e2 to_exp (Pow e i) = ConE '(:^) `AppE` to_exp e `AppE` mk_sing i of_type :: Name -> Exp of_type n = (VarE 'undefined) `SigE` (ConT n) mk_sing :: Integer -> Exp mk_sing n | n < 0 = VarE 'sPred `AppE` mk_sing (n + 1) | n > 0 = VarE 'sSucc `AppE` mk_sing (n - 1) | otherwise = VarE 'sZero parseUnitType :: SymbolTable Name Name -> String -> Either String Type parseUnitType tab s = to_type `liftM` parseUnit tab s -- the Either monad where to_type Unity = ConT ''Number to_type (Unit (Just pre) unit) = ConT ''(:@) `AppT` ConT pre `AppT` ConT unit to_type (Unit Nothing unit) = ConT unit to_type (Mult e1 e2) = ConT ''(:*) `AppT` to_type e1 `AppT` to_type e2 to_type (Div e1 e2) = ConT ''(:/) `AppT` to_type e1 `AppT` to_type e2 to_type (Pow e i) = ConT ''(:^) `AppT` to_type e `AppT` mk_z i mk_z :: Integer -> Type mk_z n | n < 0 = ConT ''Pred `AppT` mk_z (n + 1) | n > 0 = ConT ''Succ `AppT` mk_z (n - 1) | otherwise = ConT 'Zero -- single quote as it's a data constructor! ---------------------------------------------------------------------- -- QuasiQuoters ---------------------------------------------------------------------- emptyQQ :: QuasiQuoter emptyQQ = QuasiQuoter { quoteExp = \_ -> fail "No quasi-quoter for expressions" , quotePat = \_ -> fail "No quasi-quoter for patterns" , quoteType = \_ -> fail "No quasi-quoter for types" , quoteDec = \_ -> fail "No quasi-quoter for declarations" } errorQQ :: String -> QuasiQuoter errorQQ msg = QuasiQuoter { quoteExp = \_ -> fail msg , quotePat = \_ -> fail msg , quoteType = \_ -> fail msg , quoteDec = \_ -> fail msg } -- | @makeQuasiQuoter "qq" prefixes units@ makes a quasi-quoter named @qq@ -- that considers the prefixes and units provided. These are provided via -- names of the /type/ constructors, /not/ the data constructors. See the -- module documentation for more info and an example. makeQuasiQuoter :: String -> [Name] -> [Name] -> Q [Dec] makeQuasiQuoter qq_name_str prefix_names unit_names = do mapM_ checkIsType prefix_names mapM_ checkIsType unit_names qq <- [| case $sym_tab of Left err -> errorQQ err Right computed_sym_tab -> emptyQQ { quoteExp = \unit_exp -> case parseUnitExp computed_sym_tab unit_exp of Left err2 -> fail err2 Right exp -> return exp , quoteType = \unit_exp -> case parseUnitType computed_sym_tab unit_exp of Left err2 -> fail err2 Right typ -> return typ } |] return [ SigD qq_name (ConT ''QuasiQuoter) , ValD (VarP qq_name) (NormalB qq) []] where qq_name = mkName qq_name_str mk_pair :: Name -> Q Exp -- Exp is of type (String, Name) mk_pair n = [| (show (undefined :: $( return $ ConT n )), n) |] sym_tab :: Q Exp -- Exp is of type (Either String SymbolTable) sym_tab = do prefix_pairs <- mapM mk_pair prefix_names unit_pairs <- mapM mk_pair unit_names [| mkSymbolTable $( return $ ListE prefix_pairs ) $( return $ ListE unit_pairs ) |] ---------------------------------------------------------------------- -- Getting instances ---------------------------------------------------------------------- getInstanceNames :: Name -> Q [Name] getInstanceNames class_name = do ClassI _ insts <- reify class_name m_names <- forM insts $ \inst -> case inst of InstanceD #if __GLASGOW_HASKELL__ >= 711 _ #endif _ ((ConT class_name') `AppT` (ConT unit_name)) [] | class_name == class_name' -> do show_insts <- reifyInstances ''Show [ConT unit_name] case show_insts of [_show_inst] -> return $ Just unit_name _ -> return Nothing _ -> return Nothing return $ catMaybes m_names #if __GLASGOW_HASKELL__ < 709 {-# WARNING allUnits, allPrefixes "Retrieving the list of all units and prefixes in scope does not work under GHC 7.8.*. Please upgrade GHC to use these functions." #-} #endif -- | Gets a list of the names of all units with @Show@ instances in scope. -- Example usage: -- -- > $( do units <- allUnits -- > makeQuasiQuoter "unit" [] units ) -- allUnits :: Q [Name] allUnits = getInstanceNames ''Unit -- | Gets a list of the names of all unit prefixes with @Show@ instances in -- scope. Example usage: -- -- > $( do units <- allUnits -- > prefixes <- allPrefixes -- > makeQuasiQuoter "unit" prefixes units ) -- allPrefixes :: Q [Name] allPrefixes = getInstanceNames ''UnitPrefix
goldfirere/units
units/Data/Metrology/Parser.hs
Haskell
bsd-3-clause
8,556
{-# LANGUAGE PackageImports #-} import Control.Applicative import "monads-tf" Control.Monad.Trans import Control.Concurrent (threadDelay) import Control.Concurrent.STM import Control.Exception import Data.Maybe import Data.Pipe import System.IO import Network import Data.Char main :: IO () main = do h <- connectTo "localhost" $ PortNumber 54492 vh <- atomically $ newTVar h fromJust <$> runPipe (input vh =$= process =$= output vh) input :: TVar Handle -> Pipe () String IO () input vh = do h <- liftIO . atomically $ readTVar vh maybe (return ()) yield =<< liftIO ((`catch` reconnect vh Nothing) . (Just <$>) $ hGetLine h) input vh output :: TVar Handle -> Pipe String () IO () output vh = do h <- liftIO . atomically $ readTVar vh await >>= \mx -> case mx of Just x -> do liftIO . (`catch` reconnect vh (Just x)) $ do hPutStrLn h x return Nothing output vh _ -> return () reconnect :: TVar Handle -> Maybe String -> IOException -> IO (Maybe String) reconnect vh x _ = do h <- connectTo "localhost" $ PortNumber 54492 maybe (return ()) (hPutStrLn h) x atomically $ writeTVar vh h return Nothing process :: Monad m => Pipe String String m () process = await >>= \mx -> case mx of Just x -> yield (map toUpper x) >> process _ -> return ()
YoshikuniJujo/xmpipe
test/s2s_model_io/s2s_cl.hs
Haskell
bsd-3-clause
1,281
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- Some code in this file was originally from wai-1.3.0.3, made -- available under the following terms (MIT): -- -- Copyright (c) 2012 Michael Snoyman, http://www.yesodweb.com/ -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ module Seldom.Internal.Request ( Request(..) , RequestMeta(..) ) where import Data.Typeable (Typeable) import qualified Network.Socket as NS import qualified Data.ByteString.Char8 as B import qualified Network.HTTP.Types as H -------------------------------------------------------------------------------- data Request = Request { reqMethod :: !H.StdMethod , reqUri :: !B.ByteString , reqHttpVersion :: !H.HttpVersion , reqHeaders :: !H.RequestHeaders } deriving (Eq, Ord, Show, Typeable) data RequestMeta = RequestMeta { -- | The request message data. reqmReq :: !Request -- | Generally the host requested by the user via the Host request header. -- Backends are free to provide alternative values as necessary. This value -- should not be used to construct URLs. , reqmServerName :: !B.ByteString -- | The listening port that the server received this request on. It is -- possible for a server to listen on a non-numeric port (i.e., Unix named -- socket), in which case this value will be arbitrary. Like 'serverName', -- this value should not be used in URL construction. -- | If no query string was specified, this should be empty. This value -- /won't/ include the leading question mark. , reqQueryString :: !B.ByteString , reqmServerPort :: !B.ByteString -- | Was this request made over an SSL/TLS connection? , reqmIsSecure :: !Bool -- | The client\'s host information. , reqmRemoteHost :: !NS.SockAddr } deriving (Eq, Show, Typeable)
k0001/seldom
src/Seldom/Internal/Request.hs
Haskell
bsd-3-clause
3,068
{-# LANGUAGE TupleSections #-} module Matterhorn.FilePaths ( historyFilePath , historyFileName , lastRunStateFilePath , lastRunStateFileName , configFileName , xdgName , locateConfig , xdgSyntaxDir , syntaxDirName , userEmojiJsonPath , bundledEmojiJsonPath , emojiJsonFilename , Script(..) , locateScriptPath , getAllScripts ) where import Prelude () import Matterhorn.Prelude import qualified Paths_matterhorn as Paths import Data.Text ( unpack ) import System.Directory ( doesFileExist , doesDirectoryExist , getDirectoryContents , getPermissions , executable ) import System.Environment ( getExecutablePath ) import System.Environment.XDG.BaseDir ( getUserConfigFile , getAllConfigFiles , getUserConfigDir ) import System.FilePath ( (</>), takeBaseName, takeDirectory, splitPath, joinPath ) xdgName :: String xdgName = "matterhorn" historyFileName :: FilePath historyFileName = "history.txt" lastRunStateFileName :: Text -> FilePath lastRunStateFileName teamId = "last_run_state_" ++ unpack teamId ++ ".json" configFileName :: FilePath configFileName = "config.ini" historyFilePath :: IO FilePath historyFilePath = getUserConfigFile xdgName historyFileName lastRunStateFilePath :: Text -> IO FilePath lastRunStateFilePath teamId = getUserConfigFile xdgName (lastRunStateFileName teamId) -- | Get the XDG path to the user-specific syntax definition directory. -- The path does not necessarily exist. xdgSyntaxDir :: IO FilePath xdgSyntaxDir = (</> syntaxDirName) <$> getUserConfigDir xdgName -- | Get the XDG path to the user-specific emoji JSON file. The path -- does not necessarily exist. userEmojiJsonPath :: IO FilePath userEmojiJsonPath = (</> emojiJsonFilename) <$> getUserConfigDir xdgName -- | Get the emoji JSON path relative to the development binary location -- or the release binary location. bundledEmojiJsonPath :: IO FilePath bundledEmojiJsonPath = do selfPath <- getExecutablePath let distDir = "dist-newstyle/" pathBits = splitPath selfPath adjacentEmojiJsonPath <- do let path = takeDirectory selfPath </> emojiDirName </> emojiJsonFilename exists <- doesFileExist path return $ if exists then Just path else Nothing cabalEmojiJsonPath <- Paths.getDataFileName $ emojiDirName </> emojiJsonFilename return $ if distDir `elem` pathBits then -- We're in development, so use the development -- executable path to locate the emoji path in the -- development tree. (joinPath $ takeWhile (/= distDir) pathBits) </> emojiDirName </> emojiJsonFilename else -- In this case we assume the binary is being run from -- a release, in which case the syntax directory is a -- sibling of the executable path. If it does not exist -- we fall back to the cabal data files path discovered -- via Paths.getDataFileName. fromMaybe cabalEmojiJsonPath adjacentEmojiJsonPath emojiJsonFilename :: FilePath emojiJsonFilename = "emoji.json" emojiDirName :: FilePath emojiDirName = "emoji" syntaxDirName :: FilePath syntaxDirName = "syntax" -- | Find a specified configuration file by looking in all of the -- supported locations. locateConfig :: FilePath -> IO (Maybe FilePath) locateConfig filename = do xdgLocations <- getAllConfigFiles xdgName filename let confLocations = ["./" <> filename] ++ xdgLocations ++ ["/etc/matterhorn/" <> filename] results <- forM confLocations $ \fp -> (fp,) <$> doesFileExist fp return $ listToMaybe $ fst <$> filter snd results scriptDirName :: FilePath scriptDirName = "scripts" data Script = ScriptPath FilePath | NonexecScriptPath FilePath | ScriptNotFound deriving (Eq, Read, Show) toScript :: FilePath -> IO (Script) toScript fp = do perm <- getPermissions fp return $ if executable perm then ScriptPath fp else NonexecScriptPath fp isExecutable :: FilePath -> IO Bool isExecutable fp = do perm <- getPermissions fp return (executable perm) locateScriptPath :: FilePath -> IO Script locateScriptPath name | head name == '.' = return ScriptNotFound | otherwise = do xdgLocations <- getAllConfigFiles xdgName scriptDirName let cmdLocations = [ xdgLoc ++ "/" ++ name | xdgLoc <- xdgLocations ] ++ [ "/etc/matterhorn/scripts/" <> name ] existingFiles <- filterM doesFileExist cmdLocations executables <- mapM toScript existingFiles return $ case executables of (path:_) -> path _ -> ScriptNotFound -- | This returns a list of valid scripts, and a list of non-executable -- scripts. getAllScripts :: IO ([FilePath], [FilePath]) getAllScripts = do xdgLocations <- getAllConfigFiles xdgName scriptDirName let cmdLocations = xdgLocations ++ ["/etc/matterhorn/scripts"] let getCommands dir = do exists <- doesDirectoryExist dir if exists then map ((dir ++ "/") ++) `fmap` getDirectoryContents dir else return [] let isNotHidden f = case f of ('.':_) -> False [] -> False _ -> True allScripts <- concat `fmap` mapM getCommands cmdLocations execs <- filterM isExecutable allScripts nonexecs <- filterM (fmap not . isExecutable) allScripts return ( filter isNotHidden $ map takeBaseName execs , filter isNotHidden $ map takeBaseName nonexecs )
matterhorn-chat/matterhorn
src/Matterhorn/FilePaths.hs
Haskell
bsd-3-clause
5,779
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module TrieMap( CoreMap, emptyCoreMap, extendCoreMap, lookupCoreMap, foldCoreMap, TypeMap, emptyTypeMap, extendTypeMap, lookupTypeMap, foldTypeMap, LooseTypeMap, MaybeMap, ListMap, TrieMap(..), insertTM, deleteTM ) where import CoreSyn import Coercion import Literal import Name import Type import TyCoRep import Var import UniqDFM import Unique( Unique ) import FastString(FastString) import qualified Data.Map as Map import qualified Data.IntMap as IntMap import VarEnv import NameEnv import Outputable import Control.Monad( (>=>) ) {- This module implements TrieMaps, which are finite mappings whose key is a structured value like a CoreExpr or Type. The code is very regular and boilerplate-like, but there is some neat handling of *binders*. In effect they are deBruijn numbered on the fly. The regular pattern for handling TrieMaps on data structures was first described (to my knowledge) in Connelly and Morris's 1995 paper "A generalization of the Trie Data Structure"; there is also an accessible description of the idea in Okasaki's book "Purely Functional Data Structures", Section 10.3.2 ************************************************************************ * * The TrieMap class * * ************************************************************************ -} type XT a = Maybe a -> Maybe a -- How to alter a non-existent elt (Nothing) -- or an existing elt (Just) class TrieMap m where type Key m :: * emptyTM :: m a lookupTM :: forall b. Key m -> m b -> Maybe b alterTM :: forall b. Key m -> XT b -> m b -> m b mapTM :: (a->b) -> m a -> m b foldTM :: (a -> b -> b) -> m a -> b -> b -- The unusual argument order here makes -- it easy to compose calls to foldTM; -- see for example fdE below insertTM :: TrieMap m => Key m -> a -> m a -> m a insertTM k v m = alterTM k (\_ -> Just v) m deleteTM :: TrieMap m => Key m -> m a -> m a deleteTM k m = alterTM k (\_ -> Nothing) m ---------------------- -- Recall that -- Control.Monad.(>=>) :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c (>.>) :: (a -> b) -> (b -> c) -> a -> c -- Reverse function composition (do f first, then g) infixr 1 >.> (f >.> g) x = g (f x) infixr 1 |>, |>> (|>) :: a -> (a->b) -> b -- Reverse application x |> f = f x ---------------------- (|>>) :: TrieMap m2 => (XT (m2 a) -> m1 (m2 a) -> m1 (m2 a)) -> (m2 a -> m2 a) -> m1 (m2 a) -> m1 (m2 a) (|>>) f g = f (Just . g . deMaybe) deMaybe :: TrieMap m => Maybe (m a) -> m a deMaybe Nothing = emptyTM deMaybe (Just m) = m {- ************************************************************************ * * IntMaps * * ************************************************************************ -} instance TrieMap IntMap.IntMap where type Key IntMap.IntMap = Int emptyTM = IntMap.empty lookupTM k m = IntMap.lookup k m alterTM = xtInt foldTM k m z = IntMap.fold k z m mapTM f m = IntMap.map f m xtInt :: Int -> XT a -> IntMap.IntMap a -> IntMap.IntMap a xtInt k f m = IntMap.alter f k m instance Ord k => TrieMap (Map.Map k) where type Key (Map.Map k) = k emptyTM = Map.empty lookupTM = Map.lookup alterTM k f m = Map.alter f k m foldTM k m z = Map.fold k z m mapTM f m = Map.map f m {- Note [foldTM determinism] ~~~~~~~~~~~~~~~~~~~~~~~~~ We want foldTM to be deterministic, which is why we have an instance of TrieMap for UniqDFM, but not for UniqFM. Here's an example of some things that go wrong if foldTM is nondeterministic. Consider: f a b = return (a <> b) Depending on the order that the typechecker generates constraints you get either: f :: (Monad m, Monoid a) => a -> a -> m a or: f :: (Monoid a, Monad m) => a -> a -> m a The generated code will be different after desugaring as the dictionaries will be bound in different orders, leading to potential ABI incompatibility. One way to solve this would be to notice that the typeclasses could be sorted alphabetically. Unfortunately that doesn't quite work with this example: f a b = let x = a <> a; y = b <> b in x where you infer: f :: (Monoid m, Monoid m1) => m1 -> m -> m1 or: f :: (Monoid m1, Monoid m) => m1 -> m -> m1 Here you could decide to take the order of the type variables in the type according to depth first traversal and use it to order the constraints. The real trouble starts when the user enables incoherent instances and the compiler has to make an arbitrary choice. Consider: class T a b where go :: a -> b -> String instance (Show b) => T Int b where go a b = show a ++ show b instance (Show a) => T a Bool where go a b = show a ++ show b f = go 10 True GHC is free to choose either dictionary to implement f, but for the sake of determinism we'd like it to be consistent when compiling the same sources with the same flags. inert_dicts :: DictMap is implemented with a TrieMap. In getUnsolvedInerts it gets converted to a bag of (Wanted) Cts using a fold. Then in solve_simple_wanteds it's merged with other WantedConstraints. We want the conversion to a bag to be deterministic. For that purpose we use UniqDFM instead of UniqFM to implement the TrieMap. See Note [Deterministic UniqFM] in UniqDFM for more details on how it's made deterministic. -} instance TrieMap UniqDFM where type Key UniqDFM = Unique emptyTM = emptyUDFM lookupTM k m = lookupUDFM m k alterTM k f m = alterUDFM f m k foldTM k m z = foldUDFM k z m mapTM f m = mapUDFM f m {- ************************************************************************ * * Maybes * * ************************************************************************ If m is a map from k -> val then (MaybeMap m) is a map from (Maybe k) -> val -} data MaybeMap m a = MM { mm_nothing :: Maybe a, mm_just :: m a } instance TrieMap m => TrieMap (MaybeMap m) where type Key (MaybeMap m) = Maybe (Key m) emptyTM = MM { mm_nothing = Nothing, mm_just = emptyTM } lookupTM = lkMaybe lookupTM alterTM = xtMaybe alterTM foldTM = fdMaybe mapTM = mapMb mapMb :: TrieMap m => (a->b) -> MaybeMap m a -> MaybeMap m b mapMb f (MM { mm_nothing = mn, mm_just = mj }) = MM { mm_nothing = fmap f mn, mm_just = mapTM f mj } lkMaybe :: (forall b. k -> m b -> Maybe b) -> Maybe k -> MaybeMap m a -> Maybe a lkMaybe _ Nothing = mm_nothing lkMaybe lk (Just x) = mm_just >.> lk x xtMaybe :: (forall b. k -> XT b -> m b -> m b) -> Maybe k -> XT a -> MaybeMap m a -> MaybeMap m a xtMaybe _ Nothing f m = m { mm_nothing = f (mm_nothing m) } xtMaybe tr (Just x) f m = m { mm_just = mm_just m |> tr x f } fdMaybe :: TrieMap m => (a -> b -> b) -> MaybeMap m a -> b -> b fdMaybe k m = foldMaybe k (mm_nothing m) . foldTM k (mm_just m) {- ************************************************************************ * * Lists * * ************************************************************************ -} data ListMap m a = LM { lm_nil :: Maybe a , lm_cons :: m (ListMap m a) } instance TrieMap m => TrieMap (ListMap m) where type Key (ListMap m) = [Key m] emptyTM = LM { lm_nil = Nothing, lm_cons = emptyTM } lookupTM = lkList lookupTM alterTM = xtList alterTM foldTM = fdList mapTM = mapList mapList :: TrieMap m => (a->b) -> ListMap m a -> ListMap m b mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons } lkList :: TrieMap m => (forall b. k -> m b -> Maybe b) -> [k] -> ListMap m a -> Maybe a lkList _ [] = lm_nil lkList lk (x:xs) = lm_cons >.> lk x >=> lkList lk xs xtList :: TrieMap m => (forall b. k -> XT b -> m b -> m b) -> [k] -> XT a -> ListMap m a -> ListMap m a xtList _ [] f m = m { lm_nil = f (lm_nil m) } xtList tr (x:xs) f m = m { lm_cons = lm_cons m |> tr x |>> xtList tr xs f } fdList :: forall m a b. TrieMap m => (a -> b -> b) -> ListMap m a -> b -> b fdList k m = foldMaybe k (lm_nil m) . foldTM (fdList k) (lm_cons m) foldMaybe :: (a -> b -> b) -> Maybe a -> b -> b foldMaybe _ Nothing b = b foldMaybe k (Just a) b = k a b {- ************************************************************************ * * Basic maps * * ************************************************************************ -} lkDNamed :: NamedThing n => n -> DNameEnv a -> Maybe a lkDNamed n env = lookupDNameEnv env (getName n) xtDNamed :: NamedThing n => n -> XT a -> DNameEnv a -> DNameEnv a xtDNamed tc f m = alterDNameEnv f m (getName tc) ------------------------ type LiteralMap a = Map.Map Literal a emptyLiteralMap :: LiteralMap a emptyLiteralMap = emptyTM lkLit :: Literal -> LiteralMap a -> Maybe a lkLit = lookupTM xtLit :: Literal -> XT a -> LiteralMap a -> LiteralMap a xtLit = alterTM {- ************************************************************************ * * GenMap * * ************************************************************************ Note [Compressed TrieMap] ~~~~~~~~~~~~~~~~~~~~~~~~~ The GenMap constructor augments TrieMaps with leaf compression. This helps solve the performance problem detailed in #9960: suppose we have a handful H of entries in a TrieMap, each with a very large key, size K. If you fold over such a TrieMap you'd expect time O(H). That would certainly be true of an association list! But with TrieMap we actually have to navigate down a long singleton structure to get to the elements, so it takes time O(K*H). This can really hurt on many type-level computation benchmarks: see for example T9872d. The point of a TrieMap is that you need to navigate to the point where only one key remains, and then things should be fast. So the point of a SingletonMap is that, once we are down to a single (key,value) pair, we stop and just use SingletonMap. 'EmptyMap' provides an even more basic (but essential) optimization: if there is nothing in the map, don't bother building out the (possibly infinite) recursive TrieMap structure! -} data GenMap m a = EmptyMap | SingletonMap (Key m) a | MultiMap (m a) instance (Outputable a, Outputable (m a)) => Outputable (GenMap m a) where ppr EmptyMap = text "Empty map" ppr (SingletonMap _ v) = text "Singleton map" <+> ppr v ppr (MultiMap m) = ppr m -- TODO undecidable instance instance (Eq (Key m), TrieMap m) => TrieMap (GenMap m) where type Key (GenMap m) = Key m emptyTM = EmptyMap lookupTM = lkG alterTM = xtG foldTM = fdG mapTM = mapG -- NB: Be careful about RULES and type families (#5821). So we should make sure -- to specify @Key TypeMapX@ (and not @DeBruijn Type@, the reduced form) {-# SPECIALIZE lkG :: Key TypeMapX -> TypeMapG a -> Maybe a #-} {-# SPECIALIZE lkG :: Key CoercionMapX -> CoercionMapG a -> Maybe a #-} {-# SPECIALIZE lkG :: Key CoreMapX -> CoreMapG a -> Maybe a #-} lkG :: (Eq (Key m), TrieMap m) => Key m -> GenMap m a -> Maybe a lkG _ EmptyMap = Nothing lkG k (SingletonMap k' v') | k == k' = Just v' | otherwise = Nothing lkG k (MultiMap m) = lookupTM k m {-# SPECIALIZE xtG :: Key TypeMapX -> XT a -> TypeMapG a -> TypeMapG a #-} {-# SPECIALIZE xtG :: Key CoercionMapX -> XT a -> CoercionMapG a -> CoercionMapG a #-} {-# SPECIALIZE xtG :: Key CoreMapX -> XT a -> CoreMapG a -> CoreMapG a #-} xtG :: (Eq (Key m), TrieMap m) => Key m -> XT a -> GenMap m a -> GenMap m a xtG k f EmptyMap = case f Nothing of Just v -> SingletonMap k v Nothing -> EmptyMap xtG k f m@(SingletonMap k' v') | k' == k -- The new key matches the (single) key already in the tree. Hence, -- apply @f@ to @Just v'@ and build a singleton or empty map depending -- on the 'Just'/'Nothing' response respectively. = case f (Just v') of Just v'' -> SingletonMap k' v'' Nothing -> EmptyMap | otherwise -- We've hit a singleton tree for a different key than the one we are -- searching for. Hence apply @f@ to @Nothing@. If result is @Nothing@ then -- we can just return the old map. If not, we need a map with *two* -- entries. The easiest way to do that is to insert two items into an empty -- map of type @m a@. = case f Nothing of Nothing -> m Just v -> emptyTM |> alterTM k' (const (Just v')) >.> alterTM k (const (Just v)) >.> MultiMap xtG k f (MultiMap m) = MultiMap (alterTM k f m) {-# SPECIALIZE mapG :: (a -> b) -> TypeMapG a -> TypeMapG b #-} {-# SPECIALIZE mapG :: (a -> b) -> CoercionMapG a -> CoercionMapG b #-} {-# SPECIALIZE mapG :: (a -> b) -> CoreMapG a -> CoreMapG b #-} mapG :: TrieMap m => (a -> b) -> GenMap m a -> GenMap m b mapG _ EmptyMap = EmptyMap mapG f (SingletonMap k v) = SingletonMap k (f v) mapG f (MultiMap m) = MultiMap (mapTM f m) {-# SPECIALIZE fdG :: (a -> b -> b) -> TypeMapG a -> b -> b #-} {-# SPECIALIZE fdG :: (a -> b -> b) -> CoercionMapG a -> b -> b #-} {-# SPECIALIZE fdG :: (a -> b -> b) -> CoreMapG a -> b -> b #-} fdG :: TrieMap m => (a -> b -> b) -> GenMap m a -> b -> b fdG _ EmptyMap = \z -> z fdG k (SingletonMap _ v) = \z -> k v z fdG k (MultiMap m) = foldTM k m {- ************************************************************************ * * CoreMap * * ************************************************************************ Note [Binders] ~~~~~~~~~~~~~~ * In general we check binders as late as possible because types are less likely to differ than expression structure. That's why cm_lam :: CoreMapG (TypeMapG a) rather than cm_lam :: TypeMapG (CoreMapG a) * We don't need to look at the type of some binders, notalby - the case binder in (Case _ b _ _) - the binders in an alternative because they are totally fixed by the context Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * For a key (Case e b ty (alt:alts)) we don't need to look the return type 'ty', because every alternative has that type. * For a key (Case e b ty []) we MUST look at the return type 'ty', because otherwise (Case (error () "urk") _ Int []) would compare equal to (Case (error () "urk") _ Bool []) which is utterly wrong (Trac #6097) We could compare the return type regardless, but the wildly common case is that it's unnecessary, so we have two fields (cm_case and cm_ecase) for the two possibilities. Only cm_ecase looks at the type. See also Note [Empty case alternatives] in CoreSyn. -} -- | @CoreMap a@ is a map from 'CoreExpr' to @a@. If you are a client, this -- is the type you want. newtype CoreMap a = CoreMap (CoreMapG a) instance TrieMap CoreMap where type Key CoreMap = CoreExpr emptyTM = CoreMap emptyTM lookupTM k (CoreMap m) = lookupTM (deBruijnize k) m alterTM k f (CoreMap m) = CoreMap (alterTM (deBruijnize k) f m) foldTM k (CoreMap m) = foldTM k m mapTM f (CoreMap m) = CoreMap (mapTM f m) -- | @CoreMapG a@ is a map from @DeBruijn CoreExpr@ to @a@. The extended -- key makes it suitable for recursive traversal, since it can track binders, -- but it is strictly internal to this module. If you are including a 'CoreMap' -- inside another 'TrieMap', this is the type you want. type CoreMapG = GenMap CoreMapX -- | @CoreMapX a@ is the base map from @DeBruijn CoreExpr@ to @a@, but without -- the 'GenMap' optimization. data CoreMapX a = CM { cm_var :: VarMap a , cm_lit :: LiteralMap a , cm_co :: CoercionMapG a , cm_type :: TypeMapG a , cm_cast :: CoreMapG (CoercionMapG a) , cm_tick :: CoreMapG (TickishMap a) , cm_app :: CoreMapG (CoreMapG a) , cm_lam :: CoreMapG (BndrMap a) -- Note [Binders] , cm_letn :: CoreMapG (CoreMapG (BndrMap a)) , cm_letr :: ListMap CoreMapG (CoreMapG (ListMap BndrMap a)) , cm_case :: CoreMapG (ListMap AltMap a) , cm_ecase :: CoreMapG (TypeMapG a) -- Note [Empty case alternatives] } instance Eq (DeBruijn CoreExpr) where D env1 e1 == D env2 e2 = go e1 e2 where go (Var v1) (Var v2) = case (lookupCME env1 v1, lookupCME env2 v2) of (Just b1, Just b2) -> b1 == b2 (Nothing, Nothing) -> v1 == v2 _ -> False go (Lit lit1) (Lit lit2) = lit1 == lit2 go (Type t1) (Type t2) = D env1 t1 == D env2 t2 go (Coercion co1) (Coercion co2) = D env1 co1 == D env2 co2 go (Cast e1 co1) (Cast e2 co2) = D env1 co1 == D env2 co2 && go e1 e2 go (App f1 a1) (App f2 a2) = go f1 f2 && go a1 a2 -- This seems a bit dodgy, see 'eqTickish' go (Tick n1 e1) (Tick n2 e2) = n1 == n2 && go e1 e2 go (Lam b1 e1) (Lam b2 e2) = D env1 (varType b1) == D env2 (varType b2) && D (extendCME env1 b1) e1 == D (extendCME env2 b2) e2 go (Let (NonRec v1 r1) e1) (Let (NonRec v2 r2) e2) = go r1 r2 && D (extendCME env1 v1) e1 == D (extendCME env2 v2) e2 go (Let (Rec ps1) e1) (Let (Rec ps2) e2) = length ps1 == length ps2 && D env1' rs1 == D env2' rs2 && D env1' e1 == D env2' e2 where (bs1,rs1) = unzip ps1 (bs2,rs2) = unzip ps2 env1' = extendCMEs env1 bs1 env2' = extendCMEs env2 bs2 go (Case e1 b1 t1 a1) (Case e2 b2 t2 a2) | null a1 -- See Note [Empty case alternatives] = null a2 && go e1 e2 && D env1 t1 == D env2 t2 | otherwise = go e1 e2 && D (extendCME env1 b1) a1 == D (extendCME env2 b2) a2 go _ _ = False emptyE :: CoreMapX a emptyE = CM { cm_var = emptyTM, cm_lit = emptyLiteralMap , cm_co = emptyTM, cm_type = emptyTM , cm_cast = emptyTM, cm_app = emptyTM , cm_lam = emptyTM, cm_letn = emptyTM , cm_letr = emptyTM, cm_case = emptyTM , cm_ecase = emptyTM, cm_tick = emptyTM } instance TrieMap CoreMapX where type Key CoreMapX = DeBruijn CoreExpr emptyTM = emptyE lookupTM = lkE alterTM = xtE foldTM = fdE mapTM = mapE -------------------------- mapE :: (a->b) -> CoreMapX a -> CoreMapX b mapE f (CM { cm_var = cvar, cm_lit = clit , cm_co = cco, cm_type = ctype , cm_cast = ccast , cm_app = capp , cm_lam = clam, cm_letn = cletn , cm_letr = cletr, cm_case = ccase , cm_ecase = cecase, cm_tick = ctick }) = CM { cm_var = mapTM f cvar, cm_lit = mapTM f clit , cm_co = mapTM f cco, cm_type = mapTM f ctype , cm_cast = mapTM (mapTM f) ccast, cm_app = mapTM (mapTM f) capp , cm_lam = mapTM (mapTM f) clam, cm_letn = mapTM (mapTM (mapTM f)) cletn , cm_letr = mapTM (mapTM (mapTM f)) cletr, cm_case = mapTM (mapTM f) ccase , cm_ecase = mapTM (mapTM f) cecase, cm_tick = mapTM (mapTM f) ctick } -------------------------- lookupCoreMap :: CoreMap a -> CoreExpr -> Maybe a lookupCoreMap cm e = lookupTM e cm extendCoreMap :: CoreMap a -> CoreExpr -> a -> CoreMap a extendCoreMap m e v = alterTM e (\_ -> Just v) m foldCoreMap :: (a -> b -> b) -> b -> CoreMap a -> b foldCoreMap k z m = foldTM k m z emptyCoreMap :: CoreMap a emptyCoreMap = emptyTM instance Outputable a => Outputable (CoreMap a) where ppr m = text "CoreMap elts" <+> ppr (foldTM (:) m []) ------------------------- fdE :: (a -> b -> b) -> CoreMapX a -> b -> b fdE k m = foldTM k (cm_var m) . foldTM k (cm_lit m) . foldTM k (cm_co m) . foldTM k (cm_type m) . foldTM (foldTM k) (cm_cast m) . foldTM (foldTM k) (cm_tick m) . foldTM (foldTM k) (cm_app m) . foldTM (foldTM k) (cm_lam m) . foldTM (foldTM (foldTM k)) (cm_letn m) . foldTM (foldTM (foldTM k)) (cm_letr m) . foldTM (foldTM k) (cm_case m) . foldTM (foldTM k) (cm_ecase m) -- lkE: lookup in trie for expressions lkE :: DeBruijn CoreExpr -> CoreMapX a -> Maybe a lkE (D env expr) cm = go expr cm where go (Var v) = cm_var >.> lkVar env v go (Lit l) = cm_lit >.> lkLit l go (Type t) = cm_type >.> lkG (D env t) go (Coercion c) = cm_co >.> lkG (D env c) go (Cast e c) = cm_cast >.> lkG (D env e) >=> lkG (D env c) go (Tick tickish e) = cm_tick >.> lkG (D env e) >=> lkTickish tickish go (App e1 e2) = cm_app >.> lkG (D env e2) >=> lkG (D env e1) go (Lam v e) = cm_lam >.> lkG (D (extendCME env v) e) >=> lkBndr env v go (Let (NonRec b r) e) = cm_letn >.> lkG (D env r) >=> lkG (D (extendCME env b) e) >=> lkBndr env b go (Let (Rec prs) e) = let (bndrs,rhss) = unzip prs env1 = extendCMEs env bndrs in cm_letr >.> lkList (lkG . D env1) rhss >=> lkG (D env1 e) >=> lkList (lkBndr env1) bndrs go (Case e b ty as) -- See Note [Empty case alternatives] | null as = cm_ecase >.> lkG (D env e) >=> lkG (D env ty) | otherwise = cm_case >.> lkG (D env e) >=> lkList (lkA (extendCME env b)) as xtE :: DeBruijn CoreExpr -> XT a -> CoreMapX a -> CoreMapX a xtE (D env (Var v)) f m = m { cm_var = cm_var m |> xtVar env v f } xtE (D env (Type t)) f m = m { cm_type = cm_type m |> xtG (D env t) f } xtE (D env (Coercion c)) f m = m { cm_co = cm_co m |> xtG (D env c) f } xtE (D _ (Lit l)) f m = m { cm_lit = cm_lit m |> xtLit l f } xtE (D env (Cast e c)) f m = m { cm_cast = cm_cast m |> xtG (D env e) |>> xtG (D env c) f } xtE (D env (Tick t e)) f m = m { cm_tick = cm_tick m |> xtG (D env e) |>> xtTickish t f } xtE (D env (App e1 e2)) f m = m { cm_app = cm_app m |> xtG (D env e2) |>> xtG (D env e1) f } xtE (D env (Lam v e)) f m = m { cm_lam = cm_lam m |> xtG (D (extendCME env v) e) |>> xtBndr env v f } xtE (D env (Let (NonRec b r) e)) f m = m { cm_letn = cm_letn m |> xtG (D (extendCME env b) e) |>> xtG (D env r) |>> xtBndr env b f } xtE (D env (Let (Rec prs) e)) f m = m { cm_letr = let (bndrs,rhss) = unzip prs env1 = extendCMEs env bndrs in cm_letr m |> xtList (xtG . D env1) rhss |>> xtG (D env1 e) |>> xtList (xtBndr env1) bndrs f } xtE (D env (Case e b ty as)) f m | null as = m { cm_ecase = cm_ecase m |> xtG (D env e) |>> xtG (D env ty) f } | otherwise = m { cm_case = cm_case m |> xtG (D env e) |>> let env1 = extendCME env b in xtList (xtA env1) as f } -- TODO: this seems a bit dodgy, see 'eqTickish' type TickishMap a = Map.Map (Tickish Id) a lkTickish :: Tickish Id -> TickishMap a -> Maybe a lkTickish = lookupTM xtTickish :: Tickish Id -> XT a -> TickishMap a -> TickishMap a xtTickish = alterTM ------------------------ data AltMap a -- A single alternative = AM { am_deflt :: CoreMapG a , am_data :: DNameEnv (CoreMapG a) , am_lit :: LiteralMap (CoreMapG a) } instance TrieMap AltMap where type Key AltMap = CoreAlt emptyTM = AM { am_deflt = emptyTM , am_data = emptyDNameEnv , am_lit = emptyLiteralMap } lookupTM = lkA emptyCME alterTM = xtA emptyCME foldTM = fdA mapTM = mapA instance Eq (DeBruijn CoreAlt) where D env1 a1 == D env2 a2 = go a1 a2 where go (DEFAULT, _, rhs1) (DEFAULT, _, rhs2) = D env1 rhs1 == D env2 rhs2 go (LitAlt lit1, _, rhs1) (LitAlt lit2, _, rhs2) = lit1 == lit2 && D env1 rhs1 == D env2 rhs2 go (DataAlt dc1, bs1, rhs1) (DataAlt dc2, bs2, rhs2) = dc1 == dc2 && D (extendCMEs env1 bs1) rhs1 == D (extendCMEs env2 bs2) rhs2 go _ _ = False mapA :: (a->b) -> AltMap a -> AltMap b mapA f (AM { am_deflt = adeflt, am_data = adata, am_lit = alit }) = AM { am_deflt = mapTM f adeflt , am_data = mapTM (mapTM f) adata , am_lit = mapTM (mapTM f) alit } lkA :: CmEnv -> CoreAlt -> AltMap a -> Maybe a lkA env (DEFAULT, _, rhs) = am_deflt >.> lkG (D env rhs) lkA env (LitAlt lit, _, rhs) = am_lit >.> lkLit lit >=> lkG (D env rhs) lkA env (DataAlt dc, bs, rhs) = am_data >.> lkDNamed dc >=> lkG (D (extendCMEs env bs) rhs) xtA :: CmEnv -> CoreAlt -> XT a -> AltMap a -> AltMap a xtA env (DEFAULT, _, rhs) f m = m { am_deflt = am_deflt m |> xtG (D env rhs) f } xtA env (LitAlt l, _, rhs) f m = m { am_lit = am_lit m |> xtLit l |>> xtG (D env rhs) f } xtA env (DataAlt d, bs, rhs) f m = m { am_data = am_data m |> xtDNamed d |>> xtG (D (extendCMEs env bs) rhs) f } fdA :: (a -> b -> b) -> AltMap a -> b -> b fdA k m = foldTM k (am_deflt m) . foldTM (foldTM k) (am_data m) . foldTM (foldTM k) (am_lit m) {- ************************************************************************ * * Coercions * * ************************************************************************ -} -- We should really never care about the contents of a coercion. Instead, -- just look up the coercion's type. newtype CoercionMap a = CoercionMap (CoercionMapG a) instance TrieMap CoercionMap where type Key CoercionMap = Coercion emptyTM = CoercionMap emptyTM lookupTM k (CoercionMap m) = lookupTM (deBruijnize k) m alterTM k f (CoercionMap m) = CoercionMap (alterTM (deBruijnize k) f m) foldTM k (CoercionMap m) = foldTM k m mapTM f (CoercionMap m) = CoercionMap (mapTM f m) type CoercionMapG = GenMap CoercionMapX newtype CoercionMapX a = CoercionMapX (TypeMapX a) instance TrieMap CoercionMapX where type Key CoercionMapX = DeBruijn Coercion emptyTM = CoercionMapX emptyTM lookupTM = lkC alterTM = xtC foldTM f (CoercionMapX core_tm) = foldTM f core_tm mapTM f (CoercionMapX core_tm) = CoercionMapX (mapTM f core_tm) instance Eq (DeBruijn Coercion) where D env1 co1 == D env2 co2 = D env1 (coercionType co1) == D env2 (coercionType co2) lkC :: DeBruijn Coercion -> CoercionMapX a -> Maybe a lkC (D env co) (CoercionMapX core_tm) = lkT (D env $ coercionType co) core_tm xtC :: DeBruijn Coercion -> XT a -> CoercionMapX a -> CoercionMapX a xtC (D env co) f (CoercionMapX m) = CoercionMapX (xtT (D env $ coercionType co) f m) {- ************************************************************************ * * Types * * ************************************************************************ -} -- | @TypeMapG a@ is a map from @DeBruijn Type@ to @a@. The extended -- key makes it suitable for recursive traversal, since it can track binders, -- but it is strictly internal to this module. If you are including a 'TypeMap' -- inside another 'TrieMap', this is the type you want. Note that this -- lookup does not do a kind-check. Thus, all keys in this map must have -- the same kind. type TypeMapG = GenMap TypeMapX -- | @TypeMapX a@ is the base map from @DeBruijn Type@ to @a@, but without the -- 'GenMap' optimization. data TypeMapX a = TM { tm_var :: VarMap a , tm_app :: TypeMapG (TypeMapG a) , tm_tycon :: DNameEnv a , tm_forall :: TypeMapG (BndrMap a) -- See Note [Binders] , tm_tylit :: TyLitMap a , tm_coerce :: Maybe a } -- Note that there is no tyconapp case; see Note [Equality on AppTys] in Type -- | squeeze out any synonyms, convert Constraint to *, and change TyConApps -- to nested AppTys. Why the last one? See Note [Equality on AppTys] in Type trieMapView :: Type -> Maybe Type trieMapView ty | Just ty' <- coreViewOneStarKind ty = Just ty' trieMapView (TyConApp tc tys@(_:_)) = Just $ foldl AppTy (TyConApp tc []) tys trieMapView (ForAllTy (Anon arg) res) = Just ((TyConApp funTyCon [] `AppTy` arg) `AppTy` res) trieMapView _ = Nothing instance TrieMap TypeMapX where type Key TypeMapX = DeBruijn Type emptyTM = emptyT lookupTM = lkT alterTM = xtT foldTM = fdT mapTM = mapT instance Eq (DeBruijn Type) where env_t@(D env t) == env_t'@(D env' t') | Just new_t <- coreViewOneStarKind t = D env new_t == env_t' | Just new_t' <- coreViewOneStarKind t' = env_t == D env' new_t' | otherwise = case (t, t') of (CastTy t1 _, _) -> D env t1 == D env t' (_, CastTy t1' _) -> D env t == D env t1' (TyVarTy v, TyVarTy v') -> case (lookupCME env v, lookupCME env' v') of (Just bv, Just bv') -> bv == bv' (Nothing, Nothing) -> v == v' _ -> False -- See Note [Equality on AppTys] in Type (AppTy t1 t2, s) | Just (t1', t2') <- repSplitAppTy_maybe s -> D env t1 == D env' t1' && D env t2 == D env' t2' (s, AppTy t1' t2') | Just (t1, t2) <- repSplitAppTy_maybe s -> D env t1 == D env' t1' && D env t2 == D env' t2' (ForAllTy (Anon t1) t2, ForAllTy (Anon t1') t2') -> D env t1 == D env' t1' && D env t2 == D env' t2' (TyConApp tc tys, TyConApp tc' tys') -> tc == tc' && D env tys == D env' tys' (LitTy l, LitTy l') -> l == l' (ForAllTy (Named tv _) ty, ForAllTy (Named tv' _) ty') -> D env (tyVarKind tv) == D env' (tyVarKind tv') && D (extendCME env tv) ty == D (extendCME env' tv') ty' (CoercionTy {}, CoercionTy {}) -> True _ -> False instance Outputable a => Outputable (TypeMapG a) where ppr m = text "TypeMap elts" <+> ppr (foldTM (:) m []) emptyT :: TypeMapX a emptyT = TM { tm_var = emptyTM , tm_app = EmptyMap , tm_tycon = emptyDNameEnv , tm_forall = EmptyMap , tm_tylit = emptyTyLitMap , tm_coerce = Nothing } mapT :: (a->b) -> TypeMapX a -> TypeMapX b mapT f (TM { tm_var = tvar, tm_app = tapp, tm_tycon = ttycon , tm_forall = tforall, tm_tylit = tlit , tm_coerce = tcoerce }) = TM { tm_var = mapTM f tvar , tm_app = mapTM (mapTM f) tapp , tm_tycon = mapTM f ttycon , tm_forall = mapTM (mapTM f) tforall , tm_tylit = mapTM f tlit , tm_coerce = fmap f tcoerce } ----------------- lkT :: DeBruijn Type -> TypeMapX a -> Maybe a lkT (D env ty) m = go ty m where go ty | Just ty' <- trieMapView ty = go ty' go (TyVarTy v) = tm_var >.> lkVar env v go (AppTy t1 t2) = tm_app >.> lkG (D env t1) >=> lkG (D env t2) go (TyConApp tc []) = tm_tycon >.> lkDNamed tc go ty@(TyConApp _ (_:_)) = pprPanic "lkT TyConApp" (ppr ty) go (LitTy l) = tm_tylit >.> lkTyLit l go (ForAllTy (Named tv _) ty) = tm_forall >.> lkG (D (extendCME env tv) ty) >=> lkBndr env tv go ty@(ForAllTy (Anon _) _) = pprPanic "lkT FunTy" (ppr ty) go (CastTy t _) = go t go (CoercionTy {}) = tm_coerce ----------------- xtT :: DeBruijn Type -> XT a -> TypeMapX a -> TypeMapX a xtT (D env ty) f m | Just ty' <- trieMapView ty = xtT (D env ty') f m xtT (D env (TyVarTy v)) f m = m { tm_var = tm_var m |> xtVar env v f } xtT (D env (AppTy t1 t2)) f m = m { tm_app = tm_app m |> xtG (D env t1) |>> xtG (D env t2) f } xtT (D _ (TyConApp tc [])) f m = m { tm_tycon = tm_tycon m |> xtDNamed tc f } xtT (D _ (LitTy l)) f m = m { tm_tylit = tm_tylit m |> xtTyLit l f } xtT (D env (CastTy t _)) f m = xtT (D env t) f m xtT (D _ (CoercionTy {})) f m = m { tm_coerce = tm_coerce m |> f } xtT (D env (ForAllTy (Named tv _) ty)) f m = m { tm_forall = tm_forall m |> xtG (D (extendCME env tv) ty) |>> xtBndr env tv f } xtT (D _ ty@(TyConApp _ (_:_))) _ _ = pprPanic "xtT TyConApp" (ppr ty) xtT (D _ ty@(ForAllTy (Anon _) _)) _ _ = pprPanic "xtT FunTy" (ppr ty) fdT :: (a -> b -> b) -> TypeMapX a -> b -> b fdT k m = foldTM k (tm_var m) . foldTM (foldTM k) (tm_app m) . foldTM k (tm_tycon m) . foldTM (foldTM k) (tm_forall m) . foldTyLit k (tm_tylit m) . foldMaybe k (tm_coerce m) ------------------------ data TyLitMap a = TLM { tlm_number :: Map.Map Integer a , tlm_string :: Map.Map FastString a } instance TrieMap TyLitMap where type Key TyLitMap = TyLit emptyTM = emptyTyLitMap lookupTM = lkTyLit alterTM = xtTyLit foldTM = foldTyLit mapTM = mapTyLit emptyTyLitMap :: TyLitMap a emptyTyLitMap = TLM { tlm_number = Map.empty, tlm_string = Map.empty } mapTyLit :: (a->b) -> TyLitMap a -> TyLitMap b mapTyLit f (TLM { tlm_number = tn, tlm_string = ts }) = TLM { tlm_number = Map.map f tn, tlm_string = Map.map f ts } lkTyLit :: TyLit -> TyLitMap a -> Maybe a lkTyLit l = case l of NumTyLit n -> tlm_number >.> Map.lookup n StrTyLit n -> tlm_string >.> Map.lookup n xtTyLit :: TyLit -> XT a -> TyLitMap a -> TyLitMap a xtTyLit l f m = case l of NumTyLit n -> m { tlm_number = tlm_number m |> Map.alter f n } StrTyLit n -> m { tlm_string = tlm_string m |> Map.alter f n } foldTyLit :: (a -> b -> b) -> TyLitMap a -> b -> b foldTyLit l m = flip (Map.fold l) (tlm_string m) . flip (Map.fold l) (tlm_number m) ------------------------------------------------- -- | @TypeMap a@ is a map from 'Type' to @a@. If you are a client, this -- is the type you want. The keys in this map may have different kinds. newtype TypeMap a = TypeMap (TypeMapG (TypeMapG a)) lkTT :: DeBruijn Type -> TypeMap a -> Maybe a lkTT (D env ty) (TypeMap m) = lkG (D env $ typeKind ty) m >>= lkG (D env ty) xtTT :: DeBruijn Type -> XT a -> TypeMap a -> TypeMap a xtTT (D env ty) f (TypeMap m) = TypeMap (m |> xtG (D env $ typeKind ty) |>> xtG (D env ty) f) -- Below are some client-oriented functions which operate on 'TypeMap'. instance TrieMap TypeMap where type Key TypeMap = Type emptyTM = TypeMap emptyTM lookupTM k m = lkTT (deBruijnize k) m alterTM k f m = xtTT (deBruijnize k) f m foldTM k (TypeMap m) = foldTM (foldTM k) m mapTM f (TypeMap m) = TypeMap (mapTM (mapTM f) m) foldTypeMap :: (a -> b -> b) -> b -> TypeMap a -> b foldTypeMap k z m = foldTM k m z emptyTypeMap :: TypeMap a emptyTypeMap = emptyTM lookupTypeMap :: TypeMap a -> Type -> Maybe a lookupTypeMap cm t = lookupTM t cm extendTypeMap :: TypeMap a -> Type -> a -> TypeMap a extendTypeMap m t v = alterTM t (const (Just v)) m -- | A 'LooseTypeMap' doesn't do a kind-check. Thus, when lookup up (t |> g), -- you'll find entries inserted under (t), even if (g) is non-reflexive. newtype LooseTypeMap a = LooseTypeMap (TypeMapG a) instance TrieMap LooseTypeMap where type Key LooseTypeMap = Type emptyTM = LooseTypeMap emptyTM lookupTM k (LooseTypeMap m) = lookupTM (deBruijnize k) m alterTM k f (LooseTypeMap m) = LooseTypeMap (alterTM (deBruijnize k) f m) foldTM f (LooseTypeMap m) = foldTM f m mapTM f (LooseTypeMap m) = LooseTypeMap (mapTM f m) {- ************************************************************************ * * Variables * * ************************************************************************ -} type BoundVar = Int -- Bound variables are deBruijn numbered type BoundVarMap a = IntMap.IntMap a data CmEnv = CME { cme_next :: BoundVar , cme_env :: VarEnv BoundVar } emptyCME :: CmEnv emptyCME = CME { cme_next = 0, cme_env = emptyVarEnv } extendCME :: CmEnv -> Var -> CmEnv extendCME (CME { cme_next = bv, cme_env = env }) v = CME { cme_next = bv+1, cme_env = extendVarEnv env v bv } extendCMEs :: CmEnv -> [Var] -> CmEnv extendCMEs env vs = foldl extendCME env vs lookupCME :: CmEnv -> Var -> Maybe BoundVar lookupCME (CME { cme_env = env }) v = lookupVarEnv env v -- | @DeBruijn a@ represents @a@ modulo alpha-renaming. This is achieved -- by equipping the value with a 'CmEnv', which tracks an on-the-fly deBruijn -- numbering. This allows us to define an 'Eq' instance for @DeBruijn a@, even -- if this was not (easily) possible for @a@. Note: we purposely don't -- export the constructor. Make a helper function if you find yourself -- needing it. data DeBruijn a = D CmEnv a -- | Synthesizes a @DeBruijn a@ from an @a@, by assuming that there are no -- bound binders (an empty 'CmEnv'). This is usually what you want if there -- isn't already a 'CmEnv' in scope. deBruijnize :: a -> DeBruijn a deBruijnize = D emptyCME instance Eq (DeBruijn a) => Eq (DeBruijn [a]) where D _ [] == D _ [] = True D env (x:xs) == D env' (x':xs') = D env x == D env' x' && D env xs == D env' xs' _ == _ = False --------- Variable binders ------------- -- | A 'BndrMap' is a 'TypeMapG' which allows us to distinguish between -- binding forms whose binders have different types. For example, -- if we are doing a 'TrieMap' lookup on @\(x :: Int) -> ()@, we should -- not pick up an entry in the 'TrieMap' for @\(x :: Bool) -> ()@: -- we can disambiguate this by matching on the type (or kind, if this -- a binder in a type) of the binder. type BndrMap = TypeMapG -- Note [Binders] -- ~~~~~~~~~~~~~~ -- We need to use 'BndrMap' for 'Coercion', 'CoreExpr' AND 'Type', since all -- of these data types have binding forms. lkBndr :: CmEnv -> Var -> BndrMap a -> Maybe a lkBndr env v m = lkG (D env (varType v)) m xtBndr :: CmEnv -> Var -> XT a -> BndrMap a -> BndrMap a xtBndr env v f = xtG (D env (varType v)) f --------- Variable occurrence ------------- data VarMap a = VM { vm_bvar :: BoundVarMap a -- Bound variable , vm_fvar :: DVarEnv a } -- Free variable instance TrieMap VarMap where type Key VarMap = Var emptyTM = VM { vm_bvar = IntMap.empty, vm_fvar = emptyDVarEnv } lookupTM = lkVar emptyCME alterTM = xtVar emptyCME foldTM = fdVar mapTM = mapVar mapVar :: (a->b) -> VarMap a -> VarMap b mapVar f (VM { vm_bvar = bv, vm_fvar = fv }) = VM { vm_bvar = mapTM f bv, vm_fvar = mapTM f fv } lkVar :: CmEnv -> Var -> VarMap a -> Maybe a lkVar env v | Just bv <- lookupCME env v = vm_bvar >.> lookupTM bv | otherwise = vm_fvar >.> lkDFreeVar v xtVar :: CmEnv -> Var -> XT a -> VarMap a -> VarMap a xtVar env v f m | Just bv <- lookupCME env v = m { vm_bvar = vm_bvar m |> alterTM bv f } | otherwise = m { vm_fvar = vm_fvar m |> xtDFreeVar v f } fdVar :: (a -> b -> b) -> VarMap a -> b -> b fdVar k m = foldTM k (vm_bvar m) . foldTM k (vm_fvar m) lkDFreeVar :: Var -> DVarEnv a -> Maybe a lkDFreeVar var env = lookupDVarEnv env var xtDFreeVar :: Var -> XT a -> DVarEnv a -> DVarEnv a xtDFreeVar v f m = alterDVarEnv f m v
vikraman/ghc
compiler/coreSyn/TrieMap.hs
Haskell
bsd-3-clause
41,908
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} -- | Main stack tool entry point. module Main (main) where import Control.Exception import qualified Control.Exception.Lifted as EL import Control.Monad hiding (mapM, forM) import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (ask, asks, runReaderT) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Either (EitherT) import Control.Monad.Trans.Writer (Writer) import Data.Attoparsec.Args (getInterpreterArgs, parseArgs, EscapingMode (Escaping)) import qualified Data.ByteString.Lazy as L import Data.IORef import Data.List import qualified Data.Map as Map import qualified Data.Map.Strict as M import Data.Maybe import Data.Maybe.Extra (mapMaybeA) import Data.Monoid import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Traversable import Data.Typeable (Typeable) import Data.Version (showVersion) #ifdef USE_GIT_INFO import Development.GitRev (gitCommitCount, gitHash) #endif import Distribution.System (buildArch, buildPlatform) import Distribution.Text (display) import GHC.IO.Encoding (mkTextEncoding, textEncodingName) import Network.HTTP.Client import Options.Applicative import Options.Applicative.Args import Options.Applicative.Help(footerHelp,stringChunk) import Options.Applicative.Builder.Extra import Options.Applicative.Complicated #ifdef USE_GIT_INFO import Options.Applicative.Simple (simpleVersion) #endif import Options.Applicative.Types (readerAsk, ParserHelp) import Path import Path.Extra (toFilePathNoTrailingSep) import Path.IO import qualified Paths_stack as Meta import Prelude hiding (pi, mapM) import Stack.Build import Stack.Clean (CleanOpts, clean) import Stack.Config import Stack.ConfigCmd as ConfigCmd import Stack.Constants import Stack.Coverage import qualified Stack.Docker as Docker import Stack.Dot import Stack.Exec import qualified Stack.Nix as Nix import Stack.Fetch import Stack.FileWatch import Stack.GhcPkg (getGlobalDB, mkGhcPackagePath) import Stack.Ghci import Stack.Ide import qualified Stack.Image as Image import Stack.Init import Stack.New import Stack.Options import Stack.Package (getCabalFileName) import qualified Stack.PackageIndex import Stack.SDist (getSDistTarball, checkSDistTarball, checkSDistTarball') import Stack.Setup import qualified Stack.Sig as Sig import Stack.Solver (solveExtraDeps) import Stack.Types import Stack.Types.Internal import Stack.Types.StackT import Stack.Upgrade import qualified Stack.Upload as Upload import System.Directory (canonicalizePath, doesFileExist, doesDirectoryExist, createDirectoryIfMissing) import qualified System.Directory as Directory (findExecutable) import System.Environment (getEnvironment, getProgName, getArgs, withArgs) import System.Exit import System.FileLock (lockFile, tryLockFile, unlockFile, SharedExclusive(Exclusive), FileLock) import System.FilePath (searchPathSeparator) import System.IO (hIsTerminalDevice, stderr, stdin, stdout, hSetBuffering, BufferMode(..), hPutStrLn, Handle, hGetEncoding, hSetEncoding) import System.Process.Read -- | Change the character encoding of the given Handle to transliterate -- on unsupported characters instead of throwing an exception hSetTranslit :: Handle -> IO () hSetTranslit h = do menc <- hGetEncoding h case fmap textEncodingName menc of Just name | '/' `notElem` name -> do enc' <- mkTextEncoding $ name ++ "//TRANSLIT" hSetEncoding h enc' _ -> return () versionString' :: String #ifdef USE_GIT_INFO versionString' = concat $ concat [ [$(simpleVersion Meta.version)] -- Leave out number of commits for --depth=1 clone -- See https://github.com/commercialhaskell/stack/issues/792 , [" (" ++ commitCount ++ " commits)" | commitCount /= ("1"::String) && commitCount /= ("UNKNOWN" :: String)] , [" ", display buildArch] ] where commitCount = $gitCommitCount #else versionString' = showVersion Meta.version ++ ' ' : display buildArch #endif main :: IO () main = do -- Line buffer the output by default, particularly for non-terminal runs. -- See https://github.com/commercialhaskell/stack/pull/360 hSetBuffering stdout LineBuffering hSetBuffering stdin LineBuffering hSetBuffering stderr LineBuffering hSetTranslit stdout hSetTranslit stderr args <- getArgs progName <- getProgName isTerminal <- hIsTerminalDevice stdout execExtraHelp args Docker.dockerHelpOptName (dockerOptsParser False) ("Only showing --" ++ Docker.dockerCmdName ++ "* options.") execExtraHelp args Nix.nixHelpOptName (nixOptsParser False) ("Only showing --" ++ Nix.nixCmdName ++ "* options.") eGlobalRun <- try $ commandLineHandler progName False case eGlobalRun of Left (exitCode :: ExitCode) -> do throwIO exitCode Right (globalMonoid,run) -> do let global = globalOptsFromMonoid isTerminal globalMonoid when (globalLogLevel global == LevelDebug) $ hPutStrLn stderr versionString' case globalReExecVersion global of Just expectVersion | expectVersion /= showVersion Meta.version -> throwIO $ InvalidReExecVersion expectVersion (showVersion Meta.version) _ -> return () run global `catch` \e -> -- This special handler stops "stack: " from being printed before the -- exception case fromException e of Just ec -> exitWith ec Nothing -> do printExceptionStderr e exitFailure commandLineHandler :: String -> Bool -> IO (GlobalOptsMonoid, GlobalOpts -> IO ()) commandLineHandler progName isInterpreter = complicatedOptions Meta.version (Just versionString') "stack - The Haskell Tool Stack" "" (globalOpts False) (Just failureCallback) (addCommands (globalOpts True) isInterpreter) where failureCallback f args = case stripPrefix "Invalid argument" (fst (renderFailure f "")) of Just _ -> if isInterpreter then handleParseResult (Failure f) else secondaryCommandHandler args >>= maybe (interpreterHandler f args) id Nothing -> handleParseResult (Failure f) globalOpts hide = extraHelpOption hide progName (Docker.dockerCmdName ++ "*") Docker.dockerHelpOptName <*> extraHelpOption hide progName (Nix.nixCmdName ++ "*") Nix.nixHelpOptName <*> globalOptsParser hide (if isInterpreter then Just $ LevelOther "silent" else Nothing) globalFooter :: String globalFooter = "Run 'stack --help' for global options that apply to all subcommands." addCommands :: Monoid c => Parser c -> Bool -> EitherT (GlobalOpts -> IO ()) (Writer (Mod CommandFields (GlobalOpts -> IO (), c))) () addCommands globalOpts isInterpreter = do when (not isInterpreter) (do addCommand' "build" "Build the package(s) in this directory/configuration" buildCmd (buildOptsParser Build) addCommand' "install" "Shortcut for 'build --copy-bins'" buildCmd (buildOptsParser Install) addCommand' "uninstall" "DEPRECATED: This command performs no actions, and is present for documentation only" uninstallCmd (many $ strArgument $ metavar "IGNORED") addCommand' "test" "Shortcut for 'build --test'" buildCmd (buildOptsParser Test) addCommand' "bench" "Shortcut for 'build --bench'" buildCmd (buildOptsParser Bench) addCommand' "haddock" "Shortcut for 'build --haddock'" buildCmd (buildOptsParser Haddock) addCommand' "new" "Create a new project from a template. Run `stack templates' to see available templates." newCmd newOptsParser addCommand' "templates" "List the templates available for `stack new'." templatesCmd (pure ()) addCommand' "init" "Initialize a stack project based on one or more cabal packages" initCmd initOptsParser addCommand' "solver" "Use a dependency solver to try and determine missing extra-deps" solverCmd solverOptsParser addCommand' "setup" "Get the appropriate GHC for your project" setupCmd setupParser addCommand' "path" "Print out handy path information" pathCmd (mapMaybeA (\(desc,name,_) -> flag Nothing (Just name) (long (T.unpack name) <> help desc)) paths) addCommand' "unpack" "Unpack one or more packages locally" unpackCmd (some $ strArgument $ metavar "PACKAGE") addCommand' "update" "Update the package index" updateCmd (pure ()) addCommand' "upgrade" "Upgrade to the latest stack (experimental)" upgradeCmd ((,) <$> switch ( long "git" <> help "Clone from Git instead of downloading from Hackage (more dangerous)" ) <*> strOption ( long "git-repo" <> help "Clone from specified git repository" <> value "https://github.com/commercialhaskell/stack" <> showDefault )) addCommand' "upload" "Upload a package to Hackage" uploadCmd ((,,,) <$> many (strArgument $ metavar "TARBALL/DIR") <*> optional pvpBoundsOption <*> ignoreCheckSwitch <*> flag False True (long "sign" <> help "GPG sign & submit signature")) addCommand' "sdist" "Create source distribution tarballs" sdistCmd ((,,) <$> many (strArgument $ metavar "DIR") <*> optional pvpBoundsOption <*> ignoreCheckSwitch) addCommand' "dot" "Visualize your project's dependency graph using Graphviz dot" dotCmd dotOptsParser addCommand' "exec" "Execute a command" execCmd (execOptsParser Nothing) addCommand' "ghc" "Run ghc" execCmd (execOptsParser $ Just ExecGhc) addCommand' "ghci" "Run ghci in the context of package(s) (experimental)" ghciCmd ghciOptsParser addCommand' "repl" "Run ghci in the context of package(s) (experimental) (alias for 'ghci')" ghciCmd ghciOptsParser ) -- These two are the only commands allowed in interpreter mode as well addCommand' "runghc" "Run runghc" execCmd (execOptsParser $ Just ExecRunGhc) addCommand' "runhaskell" "Run runghc (alias for 'runghc')" execCmd (execOptsParser $ Just ExecRunGhc) when (not isInterpreter) (do addCommand' "eval" "Evaluate some haskell code inline. Shortcut for 'stack exec ghc -- -e CODE'" evalCmd (evalOptsParser "CODE") addCommand' "clean" "Clean the local packages" cleanCmd cleanOptsParser addCommand' "list-dependencies" "List the dependencies" listDependenciesCmd (textOption (long "separator" <> metavar "SEP" <> help ("Separator between package name " <> "and package version.") <> value " " <> showDefault)) addCommand' "query" "Query general build information (experimental)" queryCmd (many $ strArgument $ metavar "SELECTOR...") addSubCommands' "ide" "IDE-specific commands" (do addCommand' "start" "Start the ide-backend service" ideCmd ((,) <$> many (textArgument (metavar "TARGET" <> help ("If none specified, use all " <> "packages defined in current directory"))) <*> argsOption (long "ghc-options" <> metavar "OPTION" <> help "Additional options passed to GHCi" <> value [])) addCommand' "packages" "List all available local loadable packages" packagesCmd (pure ()) addCommand' "load-targets" "List all load targets for a package target" targetsCmd (textArgument (metavar "TARGET"))) addSubCommands' Docker.dockerCmdName "Subcommands specific to Docker use" (do addCommand' Docker.dockerPullCmdName "Pull latest version of Docker image from registry" dockerPullCmd (pure ()) addCommand' "reset" "Reset the Docker sandbox" dockerResetCmd (switch (long "keep-home" <> help "Do not delete sandbox's home directory")) addCommand' Docker.dockerCleanupCmdName "Clean up Docker images and containers" dockerCleanupCmd dockerCleanupOptsParser) addSubCommands' ConfigCmd.cfgCmdName "Subcommands specific to modifying stack.yaml files" (addCommand' ConfigCmd.cfgCmdSetName "Sets a field in the project's stack.yaml to value" cfgSetCmd configCmdSetParser) addSubCommands' Image.imgCmdName "Subcommands specific to imaging (EXPERIMENTAL)" (addCommand' Image.imgDockerCmdName "Build a Docker image for the project" imgDockerCmd (boolFlags True "build" "building the project before creating the container" idm)) addSubCommands' "hpc" "Subcommands specific to Haskell Program Coverage" (addCommand' "report" "Generate HPC report a combined HPC report" hpcReportCmd hpcReportOptsParser) addSubCommands' Sig.sigCmdName "Subcommands specific to package signatures (EXPERIMENTAL)" (addSubCommands' Sig.sigSignCmdName "Sign a a single package or all your packages" (addCommand' Sig.sigSignSdistCmdName "Sign a single sdist package file" sigSignSdistCmd Sig.sigSignSdistOpts)) ) where ignoreCheckSwitch = switch (long "ignore-check" <> help "Do not check package for common mistakes") -- addCommand hiding global options addCommand' cmd title constr = addCommand cmd title globalFooter constr globalOpts addSubCommands' cmd title = addSubCommands cmd title globalFooter globalOpts secondaryCommandHandler :: (MonadIO m, MonadThrow m, MonadBaseControl IO m) => [String] -> IO (Maybe (m a)) -- fall-through to external executables in `git` style if they exist -- (i.e. `stack something` looks for `stack-something` before -- failing with "Invalid argument `something'") secondaryCommandHandler args = do -- FIXME this is broken when any options are specified before the command -- e.g. stack --verbosity silent cmd mExternalExec <- Directory.findExecutable ("stack-" ++ head args) case mExternalExec of Just ex -> do menv <- getEnvOverride buildPlatform return (Just $ runNoLoggingT (exec menv ex (tail args))) Nothing -> return Nothing interpreterHandler :: Monoid t => ParserFailure ParserHelp -> [String] -> IO (GlobalOptsMonoid, (GlobalOpts -> IO (), t)) interpreterHandler f args = do val <- getInterpreterArgs args stackProgName case val of Nothing -> do let hlp = footerHelp $ stringChunk $ concat [ "\nIf you are trying to use " , stackProgName , " as a script interpreter, a\n'-- " , stackProgName , " [options] runghc [options]' comment is required." , "\nSee https://github.com/commercialhaskell/stack/blob/release/doc/GUIDE.md#ghcrunghc" ] handleParseResult (overFailure (mappend hlp) (Failure f)) Just iargs -> do progName <- getProgName let cmdlineParse = commandLineHandler progName True (a,b) <- withArgs (iargs ++ "--" : args) cmdlineParse return (a,(b,mempty)) -- | Print out useful path information in a human-readable format (and -- support others later). pathCmd :: [Text] -> GlobalOpts -> IO () pathCmd keys go = withBuildConfig go (do env <- ask let cfg = envConfig env bc = envConfigBuildConfig cfg -- This is the modified 'bin-path', -- including the local GHC or MSYS if not configured to operate on -- global GHC. -- It was set up in 'withBuildConfigAndLock -> withBuildConfigExt -> setupEnv'. -- So it's not the *minimal* override path. menv <- getMinimalEnvOverride snap <- packageDatabaseDeps local <- packageDatabaseLocal extra <- packageDatabaseExtra global <- getGlobalDB menv =<< getWhichCompiler snaproot <- installationRootDeps localroot <- installationRootLocal distDir <- distRelativeDir hpcDir <- hpcReportDir forM_ -- filter the chosen paths in flags (keys), -- or show all of them if no specific paths chosen. (filter (\(_,key,_) -> null keys || elem key keys) paths) (\(_,key,path) -> liftIO $ T.putStrLn -- If a single path type is requested, output it directly. -- Otherwise, name all the paths. ((if length keys == 1 then "" else key <> ": ") <> path (PathInfo bc menv snap local global snaproot localroot distDir hpcDir extra)))) -- | Passed to all the path printers as a source of info. data PathInfo = PathInfo { piBuildConfig :: BuildConfig , piEnvOverride :: EnvOverride , piSnapDb :: Path Abs Dir , piLocalDb :: Path Abs Dir , piGlobalDb :: Path Abs Dir , piSnapRoot :: Path Abs Dir , piLocalRoot :: Path Abs Dir , piDistDir :: Path Rel Dir , piHpcDir :: Path Abs Dir , piExtraDbs :: [Path Abs Dir] } -- | The paths of interest to a user. The first tuple string is used -- for a description that the optparse flag uses, and the second -- string as a machine-readable key and also for @--foo@ flags. The user -- can choose a specific path to list like @--global-stack-root@. But -- really it's mainly for the documentation aspect. -- -- When printing output we generate @PathInfo@ and pass it to the -- function to generate an appropriate string. Trailing slashes are -- removed, see #506 paths :: [(String, Text, PathInfo -> Text)] paths = [ ( "Global stack root directory" , "global-stack-root" , T.pack . toFilePathNoTrailingSep . configStackRoot . bcConfig . piBuildConfig ) , ( "Project root (derived from stack.yaml file)" , "project-root" , T.pack . toFilePathNoTrailingSep . bcRoot . piBuildConfig ) , ( "Configuration location (where the stack.yaml file is)" , "config-location" , T.pack . toFilePath . bcStackYaml . piBuildConfig ) , ( "PATH environment variable" , "bin-path" , T.pack . intercalate [searchPathSeparator] . eoPath . piEnvOverride ) , ( "Installed GHCs (unpacked and archives)" , "ghc-paths" , T.pack . toFilePathNoTrailingSep . configLocalPrograms . bcConfig . piBuildConfig ) , ( "Local bin path where stack installs executables" , "local-bin-path" , T.pack . toFilePathNoTrailingSep . configLocalBin . bcConfig . piBuildConfig ) , ( "Extra include directories" , "extra-include-dirs" , T.intercalate ", " . Set.elems . configExtraIncludeDirs . bcConfig . piBuildConfig ) , ( "Extra library directories" , "extra-library-dirs" , T.intercalate ", " . Set.elems . configExtraLibDirs . bcConfig . piBuildConfig ) , ( "Snapshot package database" , "snapshot-pkg-db" , T.pack . toFilePathNoTrailingSep . piSnapDb ) , ( "Local project package database" , "local-pkg-db" , T.pack . toFilePathNoTrailingSep . piLocalDb ) , ( "Global package database" , "global-pkg-db" , T.pack . toFilePathNoTrailingSep . piGlobalDb ) , ( "GHC_PACKAGE_PATH environment variable" , "ghc-package-path" , \pi -> mkGhcPackagePath True (piLocalDb pi) (piSnapDb pi) (piExtraDbs pi) (piGlobalDb pi)) , ( "Snapshot installation root" , "snapshot-install-root" , T.pack . toFilePathNoTrailingSep . piSnapRoot ) , ( "Local project installation root" , "local-install-root" , T.pack . toFilePathNoTrailingSep . piLocalRoot ) , ( "Snapshot documentation root" , "snapshot-doc-root" , \pi -> T.pack (toFilePathNoTrailingSep (piSnapRoot pi </> docDirSuffix))) , ( "Local project documentation root" , "local-doc-root" , \pi -> T.pack (toFilePathNoTrailingSep (piLocalRoot pi </> docDirSuffix))) , ( "Dist work directory" , "dist-dir" , T.pack . toFilePathNoTrailingSep . piDistDir ) , ( "Where HPC reports and tix files are stored" , "local-hpc-root" , T.pack . toFilePathNoTrailingSep . piHpcDir ) ] data SetupCmdOpts = SetupCmdOpts { scoCompilerVersion :: !(Maybe CompilerVersion) , scoForceReinstall :: !Bool , scoUpgradeCabal :: !Bool , scoStackSetupYaml :: !String , scoGHCBindistURL :: !(Maybe String) } setupParser :: Parser SetupCmdOpts setupParser = SetupCmdOpts <$> optional (argument readVersion (metavar "GHC_VERSION" <> help ("Version of GHC to install, e.g. 7.10.2. " ++ "The default is to install the version implied by the resolver."))) <*> boolFlags False "reinstall" "reinstalling GHC, even if available (implies no-system-ghc)" idm <*> boolFlags False "upgrade-cabal" "installing the newest version of the Cabal library globally" idm <*> strOption ( long "stack-setup-yaml" <> help "Location of the main stack-setup.yaml file" <> value defaultStackSetupYaml <> showDefault ) <*> optional (strOption (long "ghc-bindist" <> metavar "URL" <> help "Alternate GHC binary distribution (requires custom --ghc-variant)")) where readVersion = do s <- readerAsk case parseCompilerVersion ("ghc-" <> T.pack s) of Nothing -> case parseCompilerVersion (T.pack s) of Nothing -> readerError $ "Invalid version: " ++ s Just x -> return x Just x -> return x setupCmd :: SetupCmdOpts -> GlobalOpts -> IO () setupCmd SetupCmdOpts{..} go@GlobalOpts{..} = do (manager,lc) <- loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) Nothing (runStackTGlobal manager (lcConfig lc) go $ Nix.reexecWithOptionalShell $ runStackLoggingTGlobal manager go $ do (wantedCompiler, compilerCheck, mstack) <- case scoCompilerVersion of Just v -> return (v, MatchMinor, Nothing) Nothing -> do bc <- lcLoadBuildConfig lc globalCompiler return ( bcWantedCompiler bc , configCompilerCheck (lcConfig lc) , Just $ bcStackYaml bc ) miniConfig <- loadMiniConfig (lcConfig lc) mpaths <- runStackTGlobal manager miniConfig go $ ensureCompiler SetupOpts { soptsInstallIfMissing = True , soptsUseSystem = configSystemGHC (lcConfig lc) && not scoForceReinstall , soptsWantedCompiler = wantedCompiler , soptsCompilerCheck = compilerCheck , soptsStackYaml = mstack , soptsForceReinstall = scoForceReinstall , soptsSanityCheck = True , soptsSkipGhcCheck = False , soptsSkipMsys = configSkipMsys $ lcConfig lc , soptsUpgradeCabal = scoUpgradeCabal , soptsResolveMissingGHC = Nothing , soptsStackSetupYaml = scoStackSetupYaml , soptsGHCBindistURL = scoGHCBindistURL } let compiler = case wantedCompiler of GhcVersion _ -> "GHC" GhcjsVersion {} -> "GHCJS" case mpaths of Nothing -> $logInfo $ "stack will use the " <> compiler <> " on your PATH" Just _ -> $logInfo $ "stack will use a locally installed " <> compiler $logInfo "For more information on paths, see 'stack path' and 'stack exec env'" $logInfo $ "To use this " <> compiler <> " and packages outside of a project, consider using:" $logInfo "stack ghc, stack ghci, stack runghc, or stack exec" ) Nothing (Just $ munlockFile lk) -- | Unlock a lock file, if the value is Just munlockFile :: MonadIO m => Maybe FileLock -> m () munlockFile Nothing = return () munlockFile (Just lk) = liftIO $ unlockFile lk -- | Enforce mutual exclusion of every action running via this -- function, on this path, on this users account. -- -- A lock file is created inside the given directory. Currently, -- stack uses locks per-snapshot. In the future, stack may refine -- this to an even more fine-grain locking approach. -- withUserFileLock :: (MonadBaseControl IO m, MonadIO m) => GlobalOpts -> Path Abs Dir -> (Maybe FileLock -> m a) -> m a withUserFileLock go@GlobalOpts{} dir act = do env <- liftIO getEnvironment let toLock = lookup "STACK_LOCK" env == Just "true" if toLock then do let lockfile = $(mkRelFile "lockfile") let pth = dir </> lockfile liftIO $ createDirectoryIfMissing True (toFilePath dir) -- Just in case of asynchronous exceptions, we need to be careful -- when using tryLockFile here: EL.bracket (liftIO $ tryLockFile (toFilePath pth) Exclusive) (maybe (return ()) (liftIO . unlockFile)) (\fstTry -> case fstTry of Just lk -> EL.finally (act $ Just lk) (liftIO $ unlockFile lk) Nothing -> do let chatter = globalLogLevel go /= LevelOther "silent" when chatter $ liftIO $ hPutStrLn stderr $ "Failed to grab lock ("++show pth++ "); other stack instance running. Waiting..." EL.bracket (liftIO $ lockFile (toFilePath pth) Exclusive) (liftIO . unlockFile) (\lk -> do when chatter $ liftIO $ hPutStrLn stderr "Lock acquired, proceeding." act $ Just lk)) else act Nothing withConfigAndLock :: GlobalOpts -> StackT Config IO () -> IO () withConfigAndLock go@GlobalOpts{..} inner = do (manager, lc) <- loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) Nothing (runStackTGlobal manager (lcConfig lc) go inner) Nothing (Just $ munlockFile lk) -- For now the non-locking version just unlocks immediately. -- That is, there's still a serialization point. withBuildConfig :: GlobalOpts -> StackT EnvConfig IO () -> IO () withBuildConfig go inner = withBuildConfigAndLock go (\lk -> do munlockFile lk inner) withBuildConfigAndLock :: GlobalOpts -> (Maybe FileLock -> StackT EnvConfig IO ()) -> IO () withBuildConfigAndLock go inner = withBuildConfigExt go Nothing inner Nothing withBuildConfigExt :: GlobalOpts -> Maybe (StackT Config IO ()) -- ^ Action to perform after before build. This will be run on the host -- OS even if Docker is enabled for builds. The build config is not -- available in this action, since that would require build tools to be -- installed on the host OS. -> (Maybe FileLock -> StackT EnvConfig IO ()) -- ^ Action that uses the build config. If Docker is enabled for builds, -- this will be run in a Docker container. -> Maybe (StackT Config IO ()) -- ^ Action to perform after the build. This will be run on the host -- OS even if Docker is enabled for builds. The build config is not -- available in this action, since that would require build tools to be -- installed on the host OS. -> IO () withBuildConfigExt go@GlobalOpts{..} mbefore inner mafter = do (manager, lc) <- loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk0 -> do -- A local bit of state for communication between callbacks: curLk <- newIORef lk0 let inner' lk = -- Locking policy: This is only used for build commands, which -- only need to lock the snapshot, not the global lock. We -- trade in the lock here. do dir <- installationRootDeps -- Hand-over-hand locking: withUserFileLock go dir $ \lk2 -> do liftIO $ writeIORef curLk lk2 liftIO $ munlockFile lk inner lk2 let inner'' lk = do bconfig <- runStackLoggingTGlobal manager go $ lcLoadBuildConfig lc globalCompiler envConfig <- runStackTGlobal manager bconfig go (setupEnv Nothing) runStackTGlobal manager envConfig go (inner' lk) runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) mbefore (runStackTGlobal manager (lcConfig lc) go $ Nix.reexecWithOptionalShell (inner'' lk0)) mafter (Just $ liftIO $ do lk' <- readIORef curLk munlockFile lk') cleanCmd :: CleanOpts -> GlobalOpts -> IO () cleanCmd opts go = withBuildConfigAndLock go (const (clean opts)) -- | Helper for build and install commands buildCmd :: BuildOpts -> GlobalOpts -> IO () buildCmd opts go = do when (any (("-prof" `elem`) . either (const []) id . parseArgs Escaping) (boptsGhcOptions opts)) $ do hPutStrLn stderr "When building with stack, you should not use the -prof GHC option" hPutStrLn stderr "Instead, please use --library-profiling and --executable-profiling" hPutStrLn stderr "See: https://github.com/commercialhaskell/stack/issues/1015" error "-prof GHC option submitted" case boptsFileWatch opts of FileWatchPoll -> fileWatchPoll inner FileWatch -> fileWatch inner NoFileWatch -> inner $ const $ return () where inner setLocalFiles = withBuildConfigAndLock go $ \lk -> Stack.Build.build setLocalFiles lk opts uninstallCmd :: [String] -> GlobalOpts -> IO () uninstallCmd _ go = withConfigAndLock go $ do $logError "stack does not manage installations in global locations" $logError "The only global mutation stack performs is executable copying" $logError "For the default executable destination, please run 'stack path --local-bin-path'" -- | Unpack packages to the filesystem unpackCmd :: [String] -> GlobalOpts -> IO () unpackCmd names go = withConfigAndLock go $ do menv <- getMinimalEnvOverride Stack.Fetch.unpackPackages menv "." names -- | Update the package index updateCmd :: () -> GlobalOpts -> IO () updateCmd () go = withConfigAndLock go $ getMinimalEnvOverride >>= Stack.PackageIndex.updateAllIndices upgradeCmd :: (Bool, String) -> GlobalOpts -> IO () upgradeCmd (fromGit, repo) go = withConfigAndLock go $ upgrade (if fromGit then Just repo else Nothing) (globalResolver go) #ifdef USE_GIT_INFO (find (/= "UNKNOWN") [$gitHash]) #else Nothing #endif -- | Upload to Hackage uploadCmd :: ([String], Maybe PvpBounds, Bool, Bool) -> GlobalOpts -> IO () uploadCmd ([], _, _, _) _ = error "To upload the current package, please run 'stack upload .'" uploadCmd (args, mpvpBounds, ignoreCheck, shouldSign) go = do let partitionM _ [] = return ([], []) partitionM f (x:xs) = do r <- f x (as, bs) <- partitionM f xs return $ if r then (x:as, bs) else (as, x:bs) (files, nonFiles) <- partitionM doesFileExist args (dirs, invalid) <- partitionM doesDirectoryExist nonFiles unless (null invalid) $ error $ "stack upload expects a list sdist tarballs or cabal directories. Can't find " ++ show invalid (_,lc) <- liftIO $ loadConfigWithOpts go let getUploader :: (HasStackRoot config, HasPlatform config, HasConfig config) => StackT config IO Upload.Uploader getUploader = do config <- asks getConfig manager <- asks envManager let uploadSettings = Upload.setGetManager (return manager) Upload.defaultUploadSettings liftIO $ Upload.mkUploader config uploadSettings sigServiceUrl = "https://sig.commercialhaskell.org/" withBuildConfigAndLock go $ \_ -> do uploader <- getUploader unless ignoreCheck $ mapM_ (parseRelAsAbsFile >=> checkSDistTarball) files forM_ files (\file -> do tarFile <- parseRelAsAbsFile file liftIO (Upload.upload uploader (toFilePath tarFile)) when shouldSign (Sig.sign (lcProjectRoot lc) sigServiceUrl tarFile)) unless (null dirs) $ forM_ dirs $ \dir -> do pkgDir <- parseRelAsAbsDir dir (tarName, tarBytes) <- getSDistTarball mpvpBounds pkgDir unless ignoreCheck $ checkSDistTarball' tarName tarBytes liftIO $ Upload.uploadBytes uploader tarName tarBytes tarPath <- parseRelFile tarName when shouldSign (Sig.signTarBytes (lcProjectRoot lc) sigServiceUrl tarPath tarBytes) sdistCmd :: ([String], Maybe PvpBounds, Bool) -> GlobalOpts -> IO () sdistCmd (dirs, mpvpBounds, ignoreCheck) go = withBuildConfig go $ do -- No locking needed. -- If no directories are specified, build all sdist tarballs. dirs' <- if null dirs then asks (Map.keys . envConfigPackages . getEnvConfig) else mapM (parseAbsDir <=< liftIO . canonicalizePath) dirs forM_ dirs' $ \dir -> do (tarName, tarBytes) <- getSDistTarball mpvpBounds dir distDir <- distDirFromDir dir tarPath <- (distDir </>) <$> parseRelFile tarName liftIO $ createTree $ parent tarPath liftIO $ L.writeFile (toFilePath tarPath) tarBytes unless ignoreCheck (checkSDistTarball tarPath) $logInfo $ "Wrote sdist tarball to " <> T.pack (toFilePath tarPath) -- | Execute a command. execCmd :: ExecOpts -> GlobalOpts -> IO () execCmd ExecOpts {..} go@GlobalOpts{..} = case eoExtra of ExecOptsPlain -> do (cmd, args) <- case (eoCmd, eoArgs) of (ExecCmd cmd, args) -> return (cmd, args) (ExecGhc, args) -> return ("ghc", args) (ExecRunGhc, args) -> return ("runghc", args) (manager,lc) <- liftIO $ loadConfigWithOpts go withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk -> runStackTGlobal manager (lcConfig lc) go $ Docker.reexecWithOptionalContainer (lcProjectRoot lc) -- Unlock before transferring control away, whether using docker or not: (Just $ munlockFile lk) (runStackTGlobal manager (lcConfig lc) go $ do config <- asks getConfig menv <- liftIO $ configEnvOverride config plainEnvSettings Nix.reexecWithOptionalShell (runStackTGlobal manager (lcConfig lc) go $ exec menv cmd args)) Nothing Nothing -- Unlocked already above. ExecOptsEmbellished {..} -> withBuildConfigAndLock go $ \lk -> do config <- asks getConfig (cmd, args) <- case (eoCmd, eoArgs) of (ExecCmd cmd, args) -> return (cmd, args) (ExecGhc, args) -> execCompiler "" args -- NOTE: this won't currently work for GHCJS, because it doesn't have -- a runghcjs binary. It probably will someday, though. (ExecRunGhc, args) -> execCompiler "run" args let targets = concatMap words eoPackages unless (null targets) $ Stack.Build.build (const $ return ()) lk defaultBuildOpts { boptsTargets = map T.pack targets } munlockFile lk -- Unlock before transferring control away. menv <- liftIO $ configEnvOverride config eoEnvSettings exec menv cmd args where execCompiler cmdPrefix args = do wc <- getWhichCompiler let cmd = cmdPrefix ++ compilerExeName wc return (cmd, args) -- | Evaluate some haskell code inline. evalCmd :: EvalOpts -> GlobalOpts -> IO () evalCmd EvalOpts {..} go@GlobalOpts {..} = execCmd execOpts go where execOpts = ExecOpts { eoCmd = ExecGhc , eoArgs = ["-e", evalArg] , eoExtra = evalExtra } -- | Run GHCi in the context of a project. ghciCmd :: GhciOpts -> GlobalOpts -> IO () ghciCmd ghciOpts go@GlobalOpts{..} = withBuildConfigAndLock go $ \lk -> do let packageTargets = concatMap words (ghciAdditionalPackages ghciOpts) unless (null packageTargets) $ Stack.Build.build (const $ return ()) lk defaultBuildOpts { boptsTargets = map T.pack packageTargets } munlockFile lk -- Don't hold the lock while in the GHCI. ghci ghciOpts -- | Run ide-backend in the context of a project. ideCmd :: ([Text], [String]) -> GlobalOpts -> IO () ideCmd (targets,args) go@GlobalOpts{..} = withBuildConfig go $ -- No locking needed. ide targets args -- | List packages in the project. packagesCmd :: () -> GlobalOpts -> IO () packagesCmd () go@GlobalOpts{..} = withBuildConfig go $ do econfig <- asks getEnvConfig locals <- forM (M.toList (envConfigPackages econfig)) $ \(dir,_) -> do cabalfp <- getCabalFileName dir parsePackageNameFromFilePath cabalfp forM_ locals (liftIO . putStrLn . packageNameString) -- | List load targets for a package target. targetsCmd :: Text -> GlobalOpts -> IO () targetsCmd target go@GlobalOpts{..} = withBuildConfig go $ do let bopts = defaultBuildOpts { boptsTargets = [target] } (_realTargets,_,pkgs) <- ghciSetup bopts False False Nothing pwd <- getWorkingDir targets <- fmap (concat . snd . unzip) (mapM (getPackageOptsAndTargetFiles pwd) pkgs) forM_ targets (liftIO . putStrLn) -- | Pull the current Docker image. dockerPullCmd :: () -> GlobalOpts -> IO () dockerPullCmd _ go@GlobalOpts{..} = do (manager,lc) <- liftIO $ loadConfigWithOpts go -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal manager (lcConfig lc) go $ Docker.preventInContainer Docker.pull -- | Reset the Docker sandbox. dockerResetCmd :: Bool -> GlobalOpts -> IO () dockerResetCmd keepHome go@GlobalOpts{..} = do (manager,lc) <- liftIO (loadConfigWithOpts go) -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal manager (lcConfig lc) go $ Docker.preventInContainer $ Docker.reset (lcProjectRoot lc) keepHome -- | Cleanup Docker images and containers. dockerCleanupCmd :: Docker.CleanupOpts -> GlobalOpts -> IO () dockerCleanupCmd cleanupOpts go@GlobalOpts{..} = do (manager,lc) <- liftIO $ loadConfigWithOpts go -- TODO: can we eliminate this lock if it doesn't touch ~/.stack/? withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ -> runStackTGlobal manager (lcConfig lc) go $ Docker.preventInContainer $ Docker.cleanup cleanupOpts cfgSetCmd :: ConfigCmd.ConfigCmdSet -> GlobalOpts -> IO () cfgSetCmd co go@GlobalOpts{..} = withBuildConfigAndLock go (\_ -> do env <- ask runReaderT (cfgCmdSet co) env) imgDockerCmd :: Bool -> GlobalOpts -> IO () imgDockerCmd rebuild go@GlobalOpts{..} = withBuildConfigExt go Nothing (\lk -> do when rebuild $ Stack.Build.build (const (return ())) lk defaultBuildOpts Image.stageContainerImageArtifacts) (Just Image.createContainerImageFromStage) sigSignSdistCmd :: (String, String) -> GlobalOpts -> IO () sigSignSdistCmd (url,path) go = withConfigAndLock go (do (manager,lc) <- liftIO (loadConfigWithOpts go) tarBall <- parseRelAsAbsFile path runStackTGlobal manager (lcConfig lc) go (Sig.sign (lcProjectRoot lc) url tarBall)) -- | Load the configuration with a manager. Convenience function used -- throughout this module. loadConfigWithOpts :: GlobalOpts -> IO (Manager,LoadConfig (StackLoggingT IO)) loadConfigWithOpts go@GlobalOpts{..} = do manager <- newTLSManager mstackYaml <- case globalStackYaml of Nothing -> return Nothing Just fp -> do path <- canonicalizePath fp >>= parseAbsFile return $ Just path lc <- runStackLoggingTGlobal manager go $ do lc <- loadConfig globalConfigMonoid mstackYaml globalResolver -- If we have been relaunched in a Docker container, perform in-container initialization -- (switch UID, etc.). We do this after first loading the configuration since it must -- happen ASAP but needs a configuration. case globalDockerEntrypoint of Just de -> Docker.entrypoint (lcConfig lc) de Nothing -> return () return lc return (manager,lc) -- | Project initialization initCmd :: InitOpts -> GlobalOpts -> IO () initCmd initOpts go = withConfigAndLock go $ do pwd <- getWorkingDir config <- asks getConfig miniConfig <- loadMiniConfig config runReaderT (initProject pwd initOpts) miniConfig -- | Create a project directory structure and initialize the stack config. newCmd :: (NewOpts,InitOpts) -> GlobalOpts -> IO () newCmd (newOpts,initOpts) go@GlobalOpts{..} = withConfigAndLock go $ do dir <- new newOpts config <- asks getConfig miniConfig <- loadMiniConfig config runReaderT (initProject dir initOpts) miniConfig -- | List the available templates. templatesCmd :: () -> GlobalOpts -> IO () templatesCmd _ go@GlobalOpts{..} = withConfigAndLock go listTemplates -- | Fix up extra-deps for a project solverCmd :: Bool -- ^ modify stack.yaml automatically? -> GlobalOpts -> IO () solverCmd fixStackYaml go = withBuildConfigAndLock go (\_ -> solveExtraDeps fixStackYaml) -- | Visualize dependencies dotCmd :: DotOpts -> GlobalOpts -> IO () dotCmd dotOpts go = withBuildConfigAndLock go (\_ -> dot dotOpts) -- | List the dependencies listDependenciesCmd :: Text -> GlobalOpts -> IO () listDependenciesCmd sep go = withBuildConfig go (listDependencies sep') where sep' = T.replace "\\t" "\t" (T.replace "\\n" "\n" sep) -- | Query build information queryCmd :: [String] -> GlobalOpts -> IO () queryCmd selectors go = withBuildConfig go $ queryBuildInfo $ map T.pack selectors -- | Generate a combined HPC report hpcReportCmd :: HpcReportOpts -> GlobalOpts -> IO () hpcReportCmd hropts go = withBuildConfig go $ generateHpcReportForTargets hropts data MainException = InvalidReExecVersion String String deriving (Typeable) instance Exception MainException instance Show MainException where show (InvalidReExecVersion expected actual) = concat [ "When re-executing '" , stackProgName , "' in a container, the incorrect version was found\nExpected: " , expected , "; found: " , actual]
rubik/stack
src/main/Main.hs
Haskell
bsd-3-clause
49,174
{-# LANGUAGE TemplateHaskell #-} module Lopc.Enums where import Database.Persist.TH data LopcClassification = MajorLopc | MinorLopc | OtherLopc deriving (Show, Read, Eq, Ord) derivePersistField "LopcClassification"
hectorhon/autotrace2
app/Lopc/Enums.hs
Haskell
bsd-3-clause
266
-- -- GPIOF4.hs --- GPIO peripheral for F4 series & compatible -- -- Copyright (C) 2014, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32.Peripheral.GPIOF4 ( module Ivory.BSP.STM32.Peripheral.GPIOF4.Peripheral , module Ivory.BSP.STM32.Peripheral.GPIOF4.Regs , module Ivory.BSP.STM32.Peripheral.GPIOF4.RegTypes ) where import Ivory.BSP.STM32.Peripheral.GPIOF4.Peripheral import Ivory.BSP.STM32.Peripheral.GPIOF4.Regs import Ivory.BSP.STM32.Peripheral.GPIOF4.RegTypes
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/GPIOF4.hs
Haskell
bsd-3-clause
491
-- -*- mode: haskell; -*- -- -- generate anagrams based on dictionary and repeated user input -- import Data.Char (toLower) import Data.List (sort) import System.Environment (getArgs) import System.IO (stdout, hFlush) import qualified Data.Map as M (Map, empty, lookup, alter) -- map of canonical representation to all anagrams that exist type AnagramMap = M.Map String [String] dictionaryFilename :: IO String dictionaryFilename = do arg <- getArgs if null arg then (return "/usr/share/dict/words") else (return $ head arg) readDictionary :: String -> IO [String] readDictionary fileName = do fmap lines $ readFile fileName canonicalWord :: String -> String canonicalWord = sort . (map toLower) canonicalDictionary :: [String] -> AnagramMap canonicalDictionary ws = foldr go M.empty ws where go word acc = M.alter (updateWord word) (canonicalWord word) acc updateWord w m = Just [w] `mappend` m generateAnagrams :: AnagramMap -> String -> String generateAnagrams h w = maybe failureMessage formatResponse anagrams where anagrams = M.lookup (canonicalWord w) h formatResponse ws = "\nAnagrams for '" ++ w ++ "':\n" ++ (formatAnagrams ws) ++ "\nEnter a word to find anagrams for: " formatAnagrams arr = unlines $ map (\str -> "\t - '" ++ str ++ "'") arr failureMessage = "\nNo anagrams for '" ++ w ++ "'\nEnter a word to find anagrams for: " printAnagrams :: AnagramMap -> String -> String printAnagrams dictionary input = unlines $ map (generateAnagrams dictionary) (lines input) main :: IO () main = do dict <- fmap canonicalDictionary $ dictionaryFilename >>= readDictionary putStr "Enter a word to find anagrams for: " >> hFlush stdout interact $ printAnagrams dict
wiggly/workshop
app/Anagram.hs
Haskell
bsd-3-clause
1,810
-- | Internal module containing the store definitions. {-# LANGUAGE AllowAmbiguousTypes, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} module React.Flux.Store ( ReactStoreRef(..) , StoreData(..) -- * Old Stores , SomeStoreAction(..) , executeAction -- * New Stores , NewReactStoreHS(..) , someStoreAction , registerInitialStore , transformStore , readStoreData -- * Util , typeJsKey ) where import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, readMVar) import Control.DeepSeq import Data.Typeable import GHC.Generics (Generic) import React.Flux.Internal (unsafeDerefExport) import Data.Monoid ((<>)) import GHCJS.Foreign.Export import GHCJS.Types (JSVal, IsJSVal, JSString) import GHC.Fingerprint.Type import qualified Data.JSString.Int as JSString (decimal) import qualified Data.JSString as JSString import Data.Word (Word64) -- | See https://github.com/ghcjs/ghcjs/issues/570 for details. decimal_workaround_570 :: Word64 -> JSString decimal_workaround_570 w = dropleadingzeros . mconcat $ showpadded <$> chunks where n :: Integer -> Integer n i = 10^(5 * i) chunks :: [Integer] chunks = [ (fromIntegral w `div` (n 3)) `mod` n 1 , (fromIntegral w `div` (n 2)) `mod` n 1 , (fromIntegral w `div` (n 1)) `mod` n 1 , fromIntegral w `mod` n 1 ] showpadded :: Integer -> JSString showpadded i = JSString.reverse . JSString.take 5 . JSString.reverse $ JSString.pack "00000" <> JSString.decimal i dropleadingzeros :: JSString -> JSString dropleadingzeros = JSString.dropWhile (== '0') -- | A store contains application state, receives actions from the dispatcher, and notifies -- controller-views to re-render themselves. You can have multiple stores; it should be the case -- that all of the state required to render the page is contained in the stores. A store keeps a -- global reference to a value of type @storeData@, which must be an instance of 'StoreData'. -- -- Stores also work when compiled with GHC instead of GHCJS. When compiled with GHC, the store is -- just an MVar containing the store data and there are no controller views. 'alterStore' can still -- be used, but it just 'transform's the store and does not notify any controller-views since there -- are none. Compiling with GHC instead of GHCJS can be helpful for unit testing, although GHCJS -- plus node can also be used for unit testing. -- -- >data Todo = Todo { -- > todoText :: Text -- > , todoComplete :: Bool -- > , todoIsEditing :: Bool -- >} deriving (Show, Typeable) -- > -- >newtype TodoState = TodoState { -- > todoList :: [(Int, Todo)] -- >} deriving (Show, Typeable) -- > -- >data TodoAction = TodoCreate Text -- > | TodoDelete Int -- > | TodoEdit Int -- > | UpdateText Int Text -- > | ToggleAllComplete -- > | TodoSetComplete Int Bool -- > | ClearCompletedTodos -- > deriving (Show, Typeable, Generic, NFData) -- > -- >instance StoreData TodoState where -- > type StoreAction TodoState = TodoAction -- > transform action (TodoState todos) = ... -- > -- >initTodoStore :: IO () -- >initTodoStore = registerInitialStore $ TodoState -- > [ (0, Todo "Learn react" True False) -- > , (1, Todo "Learn react-flux" False False) -- > ] class Typeable storeData => StoreData storeData where -- | The actions that this store accepts type StoreAction storeData -- | Transform the store data according to the action. This is the only place in your app where -- @IO@ should occur. The transform function should complete quickly, since the UI will not be -- re-rendered until the transform is complete. Therefore, if you need to perform some longer -- action, you should fork a thread from inside 'transform'. The thread can then call 'alterStore' -- with another action with the result of its computation. This is very common to communicate with -- the backend using AJAX. Indeed, the 'React.Flux.Combinators.jsonAjax' utility function -- implements exactly this strategy since it is so common. -- -- Note that if the transform throws an exception, the transform will be aborted and the old -- store data will be kept unchanged. The exception will then be thrown from 'alterStore'. -- -- For the best performance, care should be taken in only modifying the part of the store data -- that changed (see below for more information on performance). transform :: StoreAction storeData -> storeData -> IO storeData -- | An existential type for some store action. It is used as the output of the dispatcher. -- The 'NFData' instance is important for performance, for details see below. data SomeStoreAction = forall storeData. (StoreData storeData, NFData (StoreAction storeData)) => SomeNewStoreAction (Proxy storeData) (StoreAction storeData) instance NFData SomeStoreAction where rnf (SomeNewStoreAction _ action) = action `deepseq` () -- | Create some store action. You must use a type-argument to specify the storeData type (because technically, the same -- store action type could be used for different stores). I strongly suggest you keep a one-to-one correspondence between -- stores and store actions, but GHC does not know that. For example, -- -- >todoAction :: TodoAction -> SomeStoreAction -- >todoAction a = someStoreAction @TodoStore a someStoreAction :: forall storeData. (StoreData storeData, NFData (StoreAction storeData)) => StoreAction storeData -> SomeStoreAction someStoreAction = SomeNewStoreAction (Proxy :: Proxy storeData) -- | Call 'alterStore' on the store and action. executeAction :: SomeStoreAction -> IO () executeAction (SomeNewStoreAction p a) = transformStore p a -------------------------------------------------------------------------------- -- Old Version Store Definition -------------------------------------------------------------------------------- -- | This type is used to represent the foreign javascript object part of the store. newtype ReactStoreRef storeData = ReactStoreRef JSVal deriving (Generic) instance IsJSVal (ReactStoreRef storeData) data NewReactStoreHS = NewReactStoreHS { newStoreLock :: MVar () } deriving Typeable ---------------------------------------------------------------------------------------------------- -- Store operations ---------------------------------------------------------------------------------------------------- -- | The new type of stores, introduced in version 1.3, keep the data in a javascript dictionary indexed -- by the fingerprint of the type. This allows any code to lookup the store by knowing the type. newtype NewReactStore storeData = NewReactStore JSVal instance IsJSVal (NewReactStore storeData) -- | New stores are kept in a javascript dictionary by type. This computes the key into this dictionary. -- -- FIXME: make the return value of this a newtype StoreKey, make typeJsKey private, and make -- Views.stateForView use StoreKey as hashmap keys. storeJsKey :: Typeable ty => Proxy ty -> JSString storeJsKey p = typeJsKey (typeRep p) typeJsKey :: TypeRep -> JSString typeJsKey t = decimal_workaround_570 f1 <> "-" <> decimal_workaround_570 f2 where Fingerprint f1 f2 = typeRepFingerprint t -- | Register the initial store data. This function must be called exactly once from your main function before -- the initial rendering occurs. Store data is global and so there can be only one store data value for each -- store type. -- -- FIXME: why not @storeE <- export =<< newMVar initial@? i think the reason to keep the lock -- separately in 'NewReactStoreHS' is just due to the fact that too much code is on the javascript -- side. The MVar should contain the entirety of @{ sdata: ..., views: ..., hs: <lock> }@, which -- would eliminate the need fo the lock. (medium-sized refactoring if we're lucky.) registerInitialStore :: forall storeData. (Typeable storeData, StoreData storeData) => storeData -> IO () registerInitialStore initial = do sdataE <- export initial storeE <- export . NewReactStoreHS =<< newMVar () js_createNewStore (storeJsKey (Proxy :: Proxy storeData)) sdataE storeE -- | First, 'transform' the store data according to the given action and then notify all registered -- controller-views to re-render themselves. -- -- Only a single thread can be transforming the store at any one time, so this function will block -- on an 'MVar' waiting for a previous transform to complete if one is in process. -- -- This function will 'error' if 'registerInitialStore' has not been called. transformStore :: forall storeData. StoreData storeData => Proxy storeData -> StoreAction storeData -> IO () transformStore _ action = do store :: NewReactStore storeData <- js_getNewStore (storeJsKey (Proxy :: Proxy storeData)) storeHS <- getNewStoreHS store modifyMVar_ (newStoreLock storeHS) $ \() -> do oldData :: storeData <- js_getNewStoreData store >>= unsafeDerefExport "transformStore" newData :: storeData <- transform action oldData js_updateNewStore store =<< export newData -- | Obtain the store data from a store. Note that the store data is stored in an MVar, so -- 'readStoreData' can block since it uses 'readMVar'. The 'MVar' is empty exactly when the store is -- being transformed, so there is a possiblity of deadlock if two stores try and access each other's -- data during transformation. -- -- This function will 'error' if 'registerInitialStore' has not been called. readStoreData :: forall storeData. (Typeable storeData, StoreData storeData) => IO storeData readStoreData = do store :: NewReactStore storeData <- js_getNewStore (storeJsKey (Proxy :: Proxy storeData)) js_getNewStoreData store >>= unsafeDerefExport "readStoreData" foreign import javascript unsafe "hsreact$storedata[$1]" js_getNewStore :: JSString -> IO (NewReactStore storeData) foreign import javascript unsafe "$1.hs" js_getNewStoreHS :: NewReactStore storeData -> IO (Export NewReactStoreHS) getNewStoreHS :: NewReactStore storeData -> IO NewReactStoreHS getNewStoreHS s = js_getNewStoreHS s >>= unsafeDerefExport "getNewStoreHS" {-# NOINLINE getNewStoreHS #-} foreign import javascript unsafe "$1.sdata" js_getNewStoreData :: NewReactStore storeData -> IO (Export storeData) foreign import javascript unsafe "hsreact$storedata[$1] = {sdata: $2, views: {}, hs: $3}" js_createNewStore :: JSString -> Export storeData -> Export NewReactStoreHS -> IO () -- | Perform the update, swapping the old export and the new export and then notifying the component views. foreign import javascript unsafe "hsreact$transform_new_store($1, $2)" js_updateNewStore :: NewReactStore storeData -> Export storeData -> IO ()
liqula/react-flux
src/React/Flux/Store.hs
Haskell
bsd-3-clause
10,832
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} module HMenu.Command ( Command(..), execute, commandLine ) where import ClassyPrelude import Control.DeepSeq import Data.Binary import GHC.Generics (Generic) import System.Directory import System.Environment import System.FilePath import System.Posix.Process data Command = ShellCommand Text | GraphicalCommand Text deriving (Show, Eq, Ord, Generic) instance NFData Command instance Binary Command instance Hashable Command commandLine :: Command -> Text commandLine (ShellCommand c) = c commandLine (GraphicalCommand c) = c execute :: Command -> IO () execute c = do (cmd, args) <- toGraphical c executeFile (unpack cmd) True (map unpack args) Nothing toGraphical :: Command -> IO (Text, [Text]) toGraphical (ShellCommand c) = do t <- findTerminal case t of Nothing -> error "Cannot find a terminal emulator" Just t' -> return (t', ["-e", c]) toGraphical (GraphicalCommand c) = do s <- findShell return (s, ["-c", c]) findShell :: IO Text findShell = do s <- lookupEnv "SHELL" case s of Just s' -> return $ pack s' Nothing -> error "Empty $SHELL !" findTerminal :: IO (Maybe Text) findTerminal = do t <- lookupEnv "TERMINAL" firstExec $ case t of Just t' -> pack t' : defaultTerminals Nothing -> defaultTerminals where firstExec :: [Text] -> IO (Maybe Text) firstExec [] = return Nothing firstExec (f:fs) = do ex <- findExecutable $ unpack f case ex of Nothing -> firstExec fs Just f' -> return $ Just (pack f') defaultTerminals :: [Text] defaultTerminals = [ "x-terminal-emulator" , "urxvt" , "rxvt" , "termit" , "terminator" , "Eterm" , "aterm" , "xterm" , "gnome-terminal" , "roxterm" , "xfce4-terminal" , "termite" , "lxterminal" , "mate-terminal" , "terminology" , "st" , "qterminal" ]
Adirelle/hmenu
src/HMenu/Command.hs
Haskell
bsd-3-clause
2,397
{-# LANGUAGE DeriveDataTypeable #-} module Main ( main ) where import System.IO import Data.List (sort) import qualified Data.ByteString.Lazy.Char8 as C import System.Console.CmdArgs import System.Directory (doesFileExist) data Options = Options { noSort :: Bool, file :: FilePath } deriving (Show,Data,Typeable) opts = Options { noSort = def &= help "Assume given line numbers is sorted.", file = def &= argPos 0 &= typFile } &= summary "getlines v0.1, (C) Naren Sundar 2010" &= program "getlines" &= details ["EXAMPLE: get lines 37 and 43 from file.", "$ echo \"37 43\" | getlines file","","", "http://github.com/nanonaren/getlines"] main = do options <- cmdArgs opts --check file exists exists <- doesFileExist (file options) if not exists then fail "Cannot open input file" else return () -- read lines lns <- C.lines `fmap` C.readFile (file options) lineNos <- fmap (map read.words) $ hGetContents stdin -- filter lines mapM_ C.putStrLn $ filterLines (if (noSort options) then lineNos else sort lineNos) lns filterLines ns ls = filterLines' ns (zip [1..] ls) filterLines' (n:ns) lns@((i,l):ls) | i > n = filterLines' ns lns | i == n = l : filterLines' ns ls | otherwise = filterLines' (n:ns) ls filterLines' [] _ = [] filterLines' _ [] = []
nanonaren/getlines
src/Main.hs
Haskell
bsd-3-clause
1,416
module Text.HTML.Truncate(truncateHtml,truncateHtml',truncateStringLike) where import qualified Text.HTML.TagSoup as TS import qualified Text.StringLike as SL import Data.Char(isSpace) import Data.List(dropWhileEnd) {- Roughly, the algorithm works like this: 1. Parse the HTML to a list of tags 2. Walk through those tags. If a tag with actual text content is encountered, truncate it. If the text was not long enough to result in actually anything being truncated, keep going and truncate less the in the next tag that is encountered. Otherwise, just close all open tags and remove all remaining text in them. 3. Remove trailing empty tags -} -- | Truncate HTML, and ensure that tags are closed; Remove trailing empty tags truncateHtml :: SL.StringLike str => Int -> str -> str truncateHtml n txt = snd $ truncateHtml' n txt truncateHtml' :: SL.StringLike str => Int -> str -> (Int,str) truncateHtml' n txt = fmap (TS.renderTags . removeTrailingEmptyTags) $ go n 0 (TS.parseTags txt) where removeTrailingEmptyTags = removeTrailingEmptyTags' [] . reverse removeTrailingEmptyTags' accm (t@(TS.TagClose _) : ts) = removeTrailingEmptyTags' (t : accm) ts removeTrailingEmptyTags' accm (t@(TS.TagOpen _ _) : ts) = removeTrailingEmptyTags' (delCloseTag accm) ts removeTrailingEmptyTags' accm (t@(TS.TagText _) : ts) = reverse (t : ts) ++ accm removeTrailingEmptyTags' accm (t : ts) = removeTrailingEmptyTags' (t : accm) ts removeTrailingEmptyTags' accm [] = accm delCloseTag (t@(TS.TagClose _) : ts) = ts delCloseTag (t : ts) = t : delCloseTag ts delCloseTag [] = [] go :: (SL.StringLike str) => Int -- ^The number of remaining characters to truncate -> Int -- ^The number of open tags -> [TS.Tag str] -- ^The remaining tags to walk through -> (Int,[TS.Tag str]) go c openTags _ | c <= 0 && openTags <= 0 = (0,[]) -- we're done. Nothing to truncate, nothing to close go i _ [] = (i,[]) go 0 openTags (t@(TS.TagOpen _ _) : ts) = go 0 (openTags + 1) ts go c openTags (t@(TS.TagOpen _ _) : ts) = fmap (t :) (go c (openTags + 1) ts) go 0 openTags (t@(TS.TagClose _) : ts) = go 0 (openTags - 1) ts go c openTags (t@(TS.TagClose _) : ts) = fmap (t :) (go c (openTags - 1) ts) go 0 openTags ((TS.TagText str) : ts) = go 0 openTags ts go c openTags (t@(TS.TagText str) : ts) = case truncateStringLike c str of (c', str') -> fmap ((TS.TagText str') :) (go (max 0 c') openTags ts) go c openTags (t : ts) = fmap (t :) (go c openTags ts) -- | Truncate to full words. If actual truncation occured, remove the last (usually cut-off) word, then remove trailing whitespace. -- | Returns the truncated string and the number of characters that remain to be truncated truncateStringLike :: SL.StringLike str => Int -> str -> (Int, str) truncateStringLike c t = case truncateStringLike' c t of (0, t') -> (0, dropWhileEndSL isSpace $ dropWhileEndSL (not . isSpace) $ t') other -> other truncateStringLike' :: SL.StringLike str => Int -> str -> (Int, str) truncateStringLike' 0 t = (0, SL.empty) truncateStringLike' c t = case SL.uncons t of Nothing -> (c, t) Just (char, rest) -> fmap (SL.cons char) (truncateStringLike (c - 1) rest) -- note: could be optimized for double applications of this. dropWhileEndSL :: SL.StringLike a => (Char -> Bool) -> a -> a dropWhileEndSL p = SL.fromString . (dropWhileEnd p) . SL.toString
mruegenberg/html-truncate
Text/HTML/Truncate.hs
Haskell
bsd-3-clause
3,618
{-# LANGUAGE OverloadedStrings #-} module Hrpg.Game.Resources.Zones.UpperCape ( upperCape ) where import Hrpg.Game.Resources.Mobs.SpawnTables (commonSpawns) import Hrpg.Framework.Zones.Zone upperCape = Zone (ZoneId 1000) "Upper Cape" "Woods on the bay" [] commonSpawns
cwmunn/hrpg
src/Hrpg/Game/Resources/Zones/UpperCape.hs
Haskell
bsd-3-clause
285
-- This file contains utility functions not provided by the Haskell -- standard library. Most mirror functions in Harrison's lib.ml -- * Signature module Util.Lib ( time , timeIO , pow , funpow , decreasing -- Strings , substringIndex -- Map , (↦) , (⟾) ) where -- * Imports import Prelude import qualified Control.Exception as Exn import qualified Data.Map as Map import Data.Map (Map) import qualified System.CPUTime as Time import qualified Text.Printf as Printf -- * Misc timeIO :: IO a -> IO a timeIO a = do start <- Time.getCPUTime v <- a end <- Time.getCPUTime let diff :: Double = (fromIntegral (end - start)) / (1E12) _ <- Printf.printf "Computation time: %0.4f sec\n" diff return v time :: (a -> b) -> a -> IO b time f x = do start <- Time.getCPUTime y <- Exn.evaluate $ f x end <- Time.getCPUTime let diff :: Double = (fromIntegral (end - start)) / (1E12) _ <- Printf.printf "Computation time: %0.4f sec\n" diff return y pow' :: Int -> Int -> Int -> Int pow' _ 0 acc = acc pow' x n acc = pow' x (n-1) (x*acc) pow :: Int -> Int -> Int pow x y = if y >= 0 then pow' x y 1 else error "negative power" funpow :: Int -> (a -> a) -> a -> a funpow n f x = iterate f x !! n -- For use with sort decreasing :: Ord b => (a -> b) -> a -> a -> Ordering decreasing f x y = compare (f y) (f x) -- * Strings substringIndex :: String -> String -> Maybe Int substringIndex s1 s2 = let ind _ [] = Nothing ind n s = if take n s == s1 then Just n else ind (n+1) (tail s) in ind 0 s2 -- * Substitutions (↦) :: Ord a => a -> b -> Map a b -> Map a b (↦) = Map.insert (⟾) :: a -> b -> Map a b (⟾) = Map.singleton
etu-fkti5301-bgu/alt-exam_automated_theorem_proving
src/Util/Lib.hs
Haskell
bsd-3-clause
1,698
module TypeDiff ( typeDiff -- exported for testing , sigMap , typeEq , alphaNormalize , normalizeConstrainNames ) where import Data.Char import Data.Maybe import Data.List import Data.Map as Map (Map) import qualified Data.Map as Map import Language.Haskell.Exts.Syntax import Language.Haskell.Exts.Parser import Data.Generics.Uniplate.Data typeDiff :: String -> String -> String typeDiff input1 input2 = unlines (missing ++ extra ++ wrongSigs) where sigs1 = sigMap input1 sigs2 = sigMap input2 names1 = Map.keys sigs1 names2 = Map.keys sigs2 missing = map format (names1 \\ names2) where format :: String -> String format = ("missing " ++) extra = map format (names2 \\ names1) where format :: String -> String format = ("extra " ++) wrongSigs :: [String] wrongSigs | null mismatches = [] | otherwise = "wrong types:" : mismatches where mismatches :: [String] mismatches = (catMaybes . map checkType . Map.toList) sigs1 checkType :: (String, String) -> Maybe String checkType (name, t1) = case Map.lookup name sigs2 of Just t2 | not (parseType_ t1 `typeEq` parseType_ t2) -> Just (format name t1 ++ "\n" ++ format name t2) _ -> Nothing format :: String -> String -> String format name type_ = " " ++ name ++ " :: " ++ type_ parseType_ :: String -> Type parseType_ type_ = case parseType type_ of ParseOk t -> t _ -> error ("can not parse type " ++ show type_) sigMap :: String -> Map String String sigMap = Map.fromList . map splitType . lines where splitType :: String -> (String, String) splitType = fmap stripSigMark . span (not . isSpace) stripSigMark :: String -> String stripSigMark = dropWhile isSpace . dropWhile (== ':') . dropWhile isSpace typeEq :: Type -> Type -> Bool typeEq t1 t2 = normalize t1 == normalize t2 where normalize = alphaNormalize . normalizeConstrainNames . normalizeConstrains . sortConstrains sortConstrains :: Type -> Type sortConstrains x = case x of TyForall a1 constrains a2 -> TyForall a1 (sort constrains) a2 _ -> x normalizeConstrains :: Type -> Type normalizeConstrains t = case t of TyForall a1 [ParenA a2] a3 -> TyForall a1 [a2] a3 _ -> t alphaNormalize :: Type -> Type alphaNormalize t = transformBi f t where f :: Name -> Name f name = fromMaybe name $ lookup name mapping names :: [Name] names = (nub . filter isTyVar . universeBi) t isTyVar :: Name -> Bool isTyVar x = case x of Ident n -> null (takeWhile isUpper n) _ -> False mapping :: [(Name, Name)] mapping = zip names vars vars :: [Name] vars = map (Ident . ('t' :) . show) [0 :: Integer ..] normalizeConstrainNames :: Type -> Type normalizeConstrainNames t = transformBi f t where f :: QName -> QName f name = case name of Qual (ModuleName "GHC.Base") (Ident "Applicative") -> Qual (ModuleName "Control.Applicative") (Ident "Applicative") Qual (ModuleName "GHC.Base") (Ident "Alternative") -> Qual (ModuleName "Control.Applicative") (Ident "Alternative") Qual (ModuleName "GHC.Base") (Ident "MonadPlus") -> Qual (ModuleName "Control.Monad") (Ident "MonadPlus") Qual (ModuleName "GHC.Base") (Ident "Maybe") -> Qual (ModuleName "Data.Maybe") (Ident "Maybe") Qual (ModuleName "GHC.Base") (Ident "Monoid") -> Qual (ModuleName "Data.Monoid") (Ident "Monoid") Qual (ModuleName "GHC.Types") (Ident "Bool") -> Qual (ModuleName "GHC.Bool") (Ident "Bool") Qual (ModuleName "GHC.Types") (Ident "Ordering") -> Qual (ModuleName "GHC.Ordering") (Ident "Ordering") _ -> name
beni55/base-compat
typediff/src/TypeDiff.hs
Haskell
mit
3,765
{-| Module : Util.DynamicLinker Description : Platform-specific dynamic linking support. Add new platforms to this file through conditional compilation. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE ExistentialQuantification, CPP, ScopedTypeVariables #-} module Util.DynamicLinker ( ForeignFun(..) , DynamicLib(..) , tryLoadLib , tryLoadFn ) where #ifdef IDRIS_FFI import Foreign.LibFFI import Foreign.Ptr (Ptr(), nullPtr, FunPtr, nullFunPtr, castPtrToFunPtr) import System.Directory #ifndef mingw32_HOST_OS import Control.Exception (try, IOException, throwIO) import Data.Array (Array, inRange, bounds, (!)) import Data.Functor ((<$>)) import Data.Maybe (catMaybes) import System.Posix.DynamicLinker import System.FilePath.Posix ((</>)) import Text.Regex.TDFA #else import qualified Control.Exception as Exception (catch, IOException) import System.Win32.DLL import System.Win32.Types import System.FilePath.Windows ((</>)) type DL = HMODULE #endif hostDynamicLibExt :: String #if defined(linux_HOST_OS) || defined(freebsd_HOST_OS) \ || defined(dragonfly_HOST_OS) || defined(openbsd_HOST_OS) \ || defined(netbsd_HOST_OS) hostDynamicLibExt = "so" #elif defined(darwin_HOST_OS) hostDynamicLibExt = "dylib" #elif defined(mingw32_HOST_OS) hostDynamicLibExt = "dll" #else hostDynamicLibExt = error $ unwords [ "Undefined file extension for dynamic libraries" , "in Idris' Util.DynamicLinker." ] #endif data ForeignFun = forall a. Fun { fun_name :: String , fun_handle :: FunPtr a } data DynamicLib = Lib { lib_name :: String , lib_handle :: DL } instance Eq DynamicLib where (Lib a _) == (Lib b _) = a == b firstExisting :: [FilePath] -> IO (Maybe FilePath) firstExisting [] = return Nothing firstExisting (f:fs) = do exists <- doesFileExist f if exists then return (Just f) else firstExisting fs libFileName :: [FilePath] -> String -> IO String libFileName dirs lib = do let names = [lib, lib ++ "." ++ hostDynamicLibExt] cwd <- getCurrentDirectory found <- firstExisting $ map ("."</>) names ++ [d </> f | d <- cwd:dirs, f <- names] return $ maybe (lib ++ "." ++ hostDynamicLibExt) id found #ifndef mingw32_HOST_OS -- Load a dynamic library on POSIX systems. -- In the simple case, we just find the appropriate filename and call dlopen(). -- In the complicated case our "foo.so" isn't actually a library. Some of the -- .so files on modern Linux systems are linker scripts instead. dlopen() -- doesn't know anything about those. We need to look inside the script for the -- actual library path and load that. This is a horrible hack, the correct -- method would be to actually parse the scripts and execute them. The approach -- below is what GHC does. tryLoadLib :: [FilePath] -> String -> IO (Maybe DynamicLib) tryLoadLib dirs lib = do filename <- libFileName dirs lib res :: Either IOException DL <- try $ dlopen filename [RTLD_NOW, RTLD_GLOBAL] mbDL <- case res of Right handle -> return $ Just handle #ifdef linux_HOST_OS Left ex -> -- dlopen failed, run a regex to see if the error message looks like it -- could be a linker script. case matchAllText invalidLibRegex (show ex) of (x:_) -> do if inRange (bounds x) 1 then do -- filename above may be a relative path. Get the full path out of -- the error message. let realPath = fst $ x ! 1 fileLines <- lines <$> readFile realPath -- Go down the linker script line by line looking for .so -- filenames and try each one. let matches = catMaybes $ map (getLastMatch . matchAllText linkerScriptRegex) fileLines mapMFirst (\f -> dlopen f [RTLD_NOW, RTLD_GLOBAL]) matches else return Nothing [] -> return Nothing #else Left ex -> throwIO ex #endif case mbDL of Just handle -> if undl handle == nullPtr then return Nothing else return . Just $ Lib lib handle Nothing -> return Nothing getLastMatch :: [MatchText String] -> Maybe String getLastMatch [] = Nothing getLastMatch (x:_) = case bounds x of (low, high) -> if low > high then Nothing else Just $ fst $ x ! high mapMFirst :: (a -> IO b) -> [a] -> IO (Maybe b) mapMFirst f [] = return Nothing mapMFirst f (a:as) = do res <- try (f a) case res of Left (ex :: IOException) -> mapMFirst f as Right res -> return $ Just res -- Both regexes copyright 2009-2011 Howard B. Golden, CJ van den Berg and Ian -- Lynagh. From the Glasgow Haskell Compiler. BSD licensed. invalidLibRegex :: Regex invalidLibRegex = makeRegex "(([^ \t()])+\\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short)" linkerScriptRegex :: Regex linkerScriptRegex = makeRegex "(GROUP|INPUT) *\\( *([^ )]+)" tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun) tryLoadFn fn (Lib _ h) = do cFn <- dlsym h fn if cFn == nullFunPtr then return Nothing else return . Just $ Fun fn cFn #else tryLoadLib :: [FilePath] -> String -> IO (Maybe DynamicLib) tryLoadLib dirs lib = do filename <- libFileName dirs lib handle <- Exception.catch (loadLibrary filename) nullPtrOnException if handle == nullPtr then return Nothing else return . Just $ Lib lib handle where nullPtrOnException :: Exception.IOException -> IO DL nullPtrOnException e = return nullPtr -- `show e` will however give broken error message tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun) tryLoadFn fn (Lib _ h) = do cFn <- getProcAddress h fn if cFn == nullPtr then return Nothing else return . Just $ Fun fn (castPtrToFunPtr cFn) #endif #else -- no libffi, just add stubbs. data DynamicLib = Lib { lib_name :: String , lib_handle :: () } deriving Eq data ForeignFun = forall a. Fun { fun_name :: String , fun_handle :: () } tryLoadLib :: [FilePath] -> String -> IO (Maybe DynamicLib) tryLoadLib fps lib = do putStrLn $ "WARNING: Cannot load '" ++ lib ++ "' at compile time because Idris was compiled without libffi support." return Nothing tryLoadFn :: String -> DynamicLib -> IO (Maybe ForeignFun) tryLoadFn fn lib = do putStrLn $ "WARNING: Cannot load '" ++ fn ++ "' at compile time because Idris was compiled without libffi support." return Nothing #endif
ozgurakgun/Idris-dev
src/Util/DynamicLinker.hs
Haskell
bsd-3-clause
7,268
-- Copyright (c) 2015 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. module Tests.Language.Salt.Surface(tests) where import Test.HUnitPlus.Base tests :: Test tests = "Surface" ~: ([] :: [Test])
emc2/saltlang
test/library/Tests/Language/Salt/Surface.hs
Haskell
bsd-3-clause
1,684
module Turbinado.Environment.Files( getFile, getFile_u, getFileContent, getFileDecode ) where import qualified Data.ByteString as BS import qualified Data.Map as M import Data.Maybe import Network.HTTP import Network.HTTP.Headers import Network.URI import Codec.MIME.Type import Codec.MIME.Decode import Turbinado.Environment.Params import Turbinado.Environment.Types import Turbinado.Utility.Data -- | Attempt to get a File from the POST getFile :: (HasEnvironment m) => String -> m (Maybe MIMEValue) getFile f = do populateParamsAndFiles e <- getEnvironment let Files fs = fromJust' "Turbinado.Environment.Files.getFile: Files is Nothing" $ getFiles e return $ M.lookup f fs -- | An unsafe version of getFile. Errors if the key does not exist. getFile_u :: (HasEnvironment m) => String -> m MIMEValue getFile_u f = do r <- getFile f maybe (error $ "getFile_u : key does not exist - \"" ++ f ++ "\"") return r getFileContent :: MIMEValue -> String getFileContent mv = case (mime_val_content mv) of Single c -> c _ -> error "Turbinado.Environment.Params.getContent: called with a Multi Content" getFileDecode :: MIMEValue -> String getFileDecode mv = case (mime_val_content mv) of --Single c -> decodeBody "base64" c Single c -> decodeWords c _ -> error "Turbinado.Environment.Params.getContent: called with a Multi Content"
alsonkemp/turbinado-website
Turbinado/Environment/Files.hs
Haskell
bsd-3-clause
1,530
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeSynonymInstances #-} -- | The internal FFI module. module Fay.FFI (Fay ,Nullable (..) ,Defined (..) ,Ptr ,Automatic ,ffi) where import Data.String (IsString) import Fay.Types import Prelude (error) -- | Values that may be null -- Nullable x decodes to x, Null decodes to null. data Nullable a = Nullable a | Null -- | Values that may be undefined -- Defined x encodes to x, Undefined decodes to undefined. -- An undefined property in a record will be removed when encoding. data Defined a = Defined a | Undefined -- | Do not serialize the specified type. This is useful for, e.g. -- -- > foo :: String -> String -- > foo = ffi "%1" -- -- This would normally serialize and unserialize the string, for no -- reason, in this case. Instead: -- -- > foo :: Ptr String -> Ptr String -- -- Will just give an identity function. type Ptr a = a -- | The opposite of "Ptr". Serialize the specified polymorphic type. -- -- > foo :: Automatic a -> String -- type Automatic a = a -- | Declare a foreign action. ffi :: IsString s => s -- ^ The foreign value. -> a -- ^ Bottom. ffi = error "Fay.FFI.ffi: Used foreign function outside a JS engine context."
beni55/fay
src/Fay/FFI.hs
Haskell
bsd-3-clause
1,284
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Stack.Upgrade (upgrade) where import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control import Data.Foldable (forM_) import qualified Data.Map as Map import qualified Data.Set as Set import Network.HTTP.Client.Conduit (HasHttpManager, getHttpManager) import Path import qualified Paths_stack as Paths import Stack.Build import Stack.Build.Types import Stack.Config import Stack.Fetch import Stack.PackageIndex import Stack.Setup import Stack.Types import Stack.Types.Internal import Stack.Types.StackT import System.IO.Temp (withSystemTempDirectory) import System.Process.Run upgrade :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, MonadLogger m, HasTerminal env, HasLogLevel env, MonadBaseControl IO m) => Bool -- ^ use Git? -> Maybe Resolver -> m () upgrade fromGit mresolver = withSystemTempDirectory "stack-upgrade" $ \tmp' -> do menv <- getMinimalEnvOverride tmp <- parseAbsDir tmp' mdir <- if fromGit then do $logInfo "Cloning stack" runIn tmp "git" menv [ "clone" , "https://github.com/commercialhaskell/stack" -- TODO allow to be configured , "stack" , "--depth" , "1" ] Nothing return $ Just $ tmp </> $(mkRelDir "stack") else do updateAllIndices menv caches <- getPackageCaches menv let latest = Map.fromListWith max $ map toTuple $ Map.keys -- Mistaken upload to Hackage, just ignore it $ Map.delete (PackageIdentifier $(mkPackageName "stack") $(mkVersion "9.9.9")) caches case Map.lookup $(mkPackageName "stack") latest of Nothing -> error "No stack found in package indices" Just version | version <= fromCabalVersion Paths.version -> do $logInfo "Already at latest version, no upgrade required" return Nothing Just version -> do let ident = PackageIdentifier $(mkPackageName "stack") version paths <- unpackPackageIdents menv tmp Nothing $ Set.singleton ident case Map.lookup ident paths of Nothing -> error "Stack.Upgrade.upgrade: invariant violated, unpacked directory not found" Just path -> return $ Just path manager <- asks getHttpManager logLevel <- asks getLogLevel terminal <- asks getTerminal configMonoid <- asks $ configConfigMonoid . getConfig forM_ mdir $ \dir -> liftIO $ do bconfig <- runStackLoggingT manager logLevel terminal $ do lc <- loadConfig configMonoid (Just $ dir </> $(mkRelFile "stack.yaml")) lcLoadBuildConfig lc mresolver ThrowException envConfig1 <- runStackT manager logLevel bconfig terminal setupEnv runStackT manager logLevel envConfig1 terminal $ build (const $ return ()) defaultBuildOpts { boptsTargets = ["stack"] , boptsInstallExes = True }
GaloisInc/stack
src/Stack/Upgrade.hs
Haskell
bsd-3-clause
3,964
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, MagicHash #-} {-# OPTIONS_HADDOCK hide #-} module GHC.List ( mylen ) where import GHC.Base hiding (assert) {-# INLINE mfoldr #-} mfoldr :: (a -> b -> b) -> b -> [a] -> b mfoldr k z = go where go [] = z go (y:ys) = y `k` go ys {-@ assert mylen :: xs: [a] -> {v: Int | v = len(xs)} @-} mylen :: [a] -> Int mylen = mfoldr (\_ -> (1 +)) 0 --{-# INLINE mmap #-} --mmap f = go -- where go [] = [] -- go (x:xs) = (f x) : (go xs) -- --myadd :: [Int] -> [Int] --myadd = mmap (1 +)
mightymoose/liquidhaskell
benchmarks/ghc-7.4.1/List-mini.hs
Haskell
bsd-3-clause
567
<?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="ko-KR"> <title>SOAP Support Add-on</title> <maps> <homeID>soap</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/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_ko_KR/helpset_ko_KR.hs
Haskell
apache-2.0
965
module Test1 where f = e2 where e2 = 1 - 2
kmate/HaRe
old/testing/refacSlicing/Test1AST.hs
Haskell
bsd-3-clause
44
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[Simplify]{The main module of the simplifier} -} {-# LANGUAGE CPP #-} module Simplify ( simplTopBinds, simplExpr, simplRules ) where #include "HsVersions.h" import DynFlags import SimplMonad import Type hiding ( substTy, extendTvSubst, substTyVar ) import SimplEnv import SimplUtils import FamInstEnv ( FamInstEnv ) import Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326 import Id import MkId ( seqId, voidPrimId ) import MkCore ( mkImpossibleExpr, castBottomExpr ) import IdInfo import Name ( Name, mkSystemVarName, isExternalName ) import Coercion hiding ( substCo, substTy, substCoVar, extendTvSubst ) import OptCoercion ( optCoercion ) import FamInstEnv ( topNormaliseType_maybe ) import DataCon ( DataCon, dataConWorkId, dataConRepStrictness , isMarkedStrict ) --, dataConTyCon, dataConTag, fIRST_TAG ) --import TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326 import CoreMonad ( Tick(..), SimplifierMode(..) ) import CoreSyn import Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd ) import PprCore ( pprCoreExpr ) import CoreUnfold import CoreUtils import CoreArity --import PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326 import Rules ( mkSpecInfo, lookupRule, getRules ) import TysPrim ( voidPrimTy ) --, intPrimTy ) -- temporalily commented out. See #8326 import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) ) import MonadUtils ( foldlM, mapAccumLM, liftIO ) import Maybes ( orElse ) --import Unique ( hasKey ) -- temporalily commented out. See #8326 import Control.Monad import Outputable import FastString import Pair import Util import ErrUtils {- The guts of the simplifier is in this module, but the driver loop for the simplifier is in SimplCore.hs. ----------------------------------------- *** 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 coercion to the usage site may well cancel the coercions 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 { sc_dup = NoDup, sc_bndr = bndr , sc_alts = alts , sc_env = env, sc_cont = 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 { sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = 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 { (dup', arg_se', arg') <- simplArg env dup arg_se arg ; cont' <- addCoerce co2 cont ; return (ApplyToVal { sc_arg = mkCast arg' (mkSymCo co1) , sc_env = 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 $ printOutputForUser dflags alwaysQualify $ sep [text "Inlining done:", nest 4 (ppr var)] | otherwise = liftIO $ printOutputForUser 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.hs 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 { sc_bndr = case_bndr, sc_alts = [(_, 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 { sc_bndr = case_bndr, sc_alts = alts , sc_env = se, sc_cont = 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 { sc_dup = OkToDup , sc_bndr = case_bndr', sc_alts = alts'' , sc_env = zapSubstEnv env'' , sc_cont = 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.hs, 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. There is a cost to not doing case-of-case; see Trac #10626. 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` mkSpecInfo new_rules ; return (modifyInScope env final_id, final_id) } where old_rules = specInfoRules (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 , ru_act = act }) = do { (env, bndrs') <- simplBinders env bndrs ; let lhs_env = updMode updModeForRuleLHS env rhs_env = updMode (updModeForStableUnfoldings act) env ; args' <- mapM (simplExpr lhs_env) args ; rhs' <- simplExpr rhs_env rhs ; return (rule { ru_bndrs = bndrs' , ru_fn = mb_new_nm `orElse` fn_name , ru_args = args' , ru_rhs = rhs' }) }
acowley/ghc
compiler/simplCore/Simplify.hs
Haskell
bsd-3-clause
123,147
{-# LANGUAGE TemplateHaskell, TypeFamilies, PolyKinds #-} module T8884 where import Language.Haskell.TH import System.IO type family Foo a = r | r -> a where Foo x = x type family Baz (a :: k) = (r :: k) | r -> a type instance Baz x = x $( do FamilyI foo@(ClosedTypeFamilyD _ tvbs1 res1 m_kind1 eqns1) [] <- reify ''Foo FamilyI baz@(OpenTypeFamilyD _ tvbs2 res2 m_kind2) [inst@(TySynInstD _ eqn2)] <- reify ''Baz runIO $ putStrLn $ pprint foo runIO $ putStrLn $ pprint baz runIO $ putStrLn $ pprint inst runIO $ hFlush stdout return [ ClosedTypeFamilyD (mkName "Foo'") tvbs1 res1 m_kind1 eqns1 , OpenTypeFamilyD (mkName "Baz'") tvbs2 res2 m_kind2 , TySynInstD (mkName "Baz'") eqn2 ] )
ghc-android/ghc
testsuite/tests/th/T8884.hs
Haskell
bsd-3-clause
784
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ScopedTypeVariables #-} module Controllers.Sessions where import Lucid import Lucid.Html5 import Control.Monad import Data.HVect import Web.Spock.Safe import Models import Config import Views.Sessions as Views new :: (ContainsGuest n xs, NotAuthenticated xs) => Action (HVect xs) a new = render $ Views.new [] create :: (ContainsGuest n xs, NotAuthenticated xs) => Action (HVect xs) a create = do uName <- param' "email" uPass <- param' "password" loginRes <- runSQL $ loginUser uName uPass case loginRes of Just userId -> do sid <- runSQL $ createSession userId writeSession (Just sid) redirect "/" Nothing -> do render $ Views.new ["Wrong username or password"] destroy :: Authenticated n xs => Action (HVect xs) a destroy = do (userId, _ :: User) <- liftM findFirst getContext runSQL $ killSessions userId writeSession Nothing redirect "/"
folsen/haskell-startapp
src/Controllers/Sessions.hs
Haskell
mit
1,070
module Demos ( mainDemo ) where import Draw import Centres import Shape import Constructions -------------------------------------------------------------------------------- type Demo = Triangle -> IO () mainDemo :: Demo mainDemo = demoNapoleonTriangle True -------------------------------------------------------------------------------- demoCentroid :: Demo demoCentroid t@(Triangle a b c) = let c' = centroid t in do draw white t draw red $ t `ceviansThrough` c' draw red c' demoSymmedian :: Demo demoSymmedian t@(Triangle a b c) = let c' = symmedianpoint t in do draw white t draw red $ t `ceviansThrough` c' draw red c' demoOrthocentre :: Demo demoOrthocentre t@(Triangle a b c) = let c' = orthocentre t in do draw white t draw red $ t `ceviansThrough` c' draw red c' demoMittenpunkt :: Demo demoMittenpunkt t@(Triangle a b c) = let mp = mittenpunkt t in do draw white t draw green $ outcircles t draw green $ outcentres t draw cyan $ rays mp (outcentres t) draw cyan $ mp demoIncircle :: Demo demoIncircle t@(Triangle a b c) = let ic@(Circle c r) = incircle t in do draw white t draw yellow $ rays c (corners t) draw yellow $ c draw yellow $ ic demoCircumcircle :: Demo demoCircumcircle t@(Triangle a b c) = let cc@(Circle c r) = circumcircle t in do draw white t draw cyan $ rays c (sidemidpoints t) draw green $ c draw green $ cc demoNinePointCircle :: Demo demoNinePointCircle t@(Triangle a b c) = let o = orthocentre t heights = t `ceviansThrough` o hs = map (\(Line a b) -> b) heights npc@(Circle c r) = ninepointcircle t in do draw white $ t draw cyan $ heights draw blue $ raysMidpoints o (corners t) draw red $ sidemidpoints t draw yellow $ c draw yellow $ npc draw cyan $ hs demoOuterNapoleonTriangle :: Demo demoOuterNapoleonTriangle t = let ots = outerEquilateralTriangles t in do draw red $ ots draw green $ outerNapoleonTriangle t draw white $ t -- isouter is True if you're using outer equilateral triangles, False for inner. demoNapoleonTriangle :: Bool -> Demo demoNapoleonTriangle isouter t = let ets = sideEquilateralTriangles isouter t nt = napoleonTriangle isouter t in do draw red $ ets draw green $ nt draw white $ t demoNagel :: Demo demoNagel t@(Triangle a b c) = let n = nagelpoint t in do draw white $ t draw cyan $ n draw cyan $ t `ceviansThrough` n demoEulerLine :: Demo demoEulerLine t@(Triangle a b c) = let o = orthocentre t hs = cevianIntersects t o cd = centroid t ms = cevianIntersects t cd cc@(Circle ccc ccr) = circumcircle t ex = exeterpoint t npc@(Circle npcc npcr) = ninepointcircle t in do draw (faded white) $ zipWith Line hs ms draw white $ t draw cyan $ t `ceviansThrough` o draw cyan $ rays o (corners t) draw cyan $ o draw green $ t `ceviansThrough` cd draw green $ cd draw blue $ ccc draw blue $ cc draw magenta $ ex draw yellow $ Line o ex draw yellow $ Line ccc ex draw yellow $ npcc draw yellow $ npc --------------------------------------------------------------------------------
clauderichard/Euclaude
Demos.hs
Haskell
mit
3,906
-------------------------------------------------------------------------------- -- | -- Module : Control.Workflow -- Copyright : (c) 2015-2019 Kai Zhang -- License : MIT -- Maintainer : kai@kzhang.org -- Stability : experimental -- Portability : portable -- -- DSL for building computational workflows. Example: -- -- > {-# LANGUAGE TemplateHaskell #-} -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Control.Monad.Reader -- > import Control.Concurrent (threadDelay) -- > import Control.Lens -- > import System.Environment -- > import qualified Data.HashMap.Strict as M -- > import Network.Transport.TCP -- > import Data.Proxy (Proxy(..)) -- > -- > import Control.Workflow -- > import Control.Workflow.Coordinator.Local -- > import Control.Workflow.Coordinator.Drmaa -- > -- > s0 :: () -> ReaderT Int IO [Int] -- > s0 = return . const [1..10] -- > -- > s1 :: Int -> ReaderT Int IO Int -- >s1 i = (i*) <$> ask -- > -- > s2 = return . (!!1) -- > s3 = return . (!!2) -- > s4 = return . (!!3) -- > s5 = return . (!!4) -- > s6 (a,b,c,d) = liftIO $ threadDelay 10000000 >> print [a,b,c,d] -- > -- > build "wf" [t| SciFlow Int |] $ do -- > node "S0" 's0 $ return () -- > nodePar "S1" 's1 $ return () -- > ["S0"] ~> "S1" -- > -- > node "S2" 's2 $ memory .= 30 -- > node "S3" 's3 $ memory .= 30 -- > node "S4" 's4 $ nCore .= 4 -- > node "S5" 's5 $ queue .= Just "gpu" -- > ["S0"] ~> "S2" -- > ["S0"] ~> "S3" -- > ["S0"] ~> "S4" -- > ["S0"] ~> "S5" -- > -- > node "S6" 's6 $ return () -- > ["S2", "S3", "S4", "S5"] ~> "S6" -- > main :: IO () -- > main = do -- > let serverAddr = "192.168.0.1" -- > port = 8888 -- > storePath = "sciflow.db" -- > resources = ResourceConfig $ M.fromList -- > [("S6", Resource (Just 2) Nothing Nothing)] -- > [mode] <- getArgs -- > case mode of -- > -- Run on local machine -- > "local" -> withCoordinator (LocalConfig 5) $ \coord -> do -- > Right transport <- createTransport (defaultTCPAddr serverAddr $ show port) -- > defaultTCPParameters -- > withStore storePath $ \store -> -- > runSciFlow coord transport store (ResourceConfig M.empty) 2 wf -- > -- Using the DRMAA backend -- > "drmaa" -> do -- > config <- getDefaultDrmaaConfig ["slave"] -- > withCoordinator config $ \coord -> do -- > Right transport <- createTransport (defaultTCPAddr serverAddr $ show port) -- > defaultTCPParameters -- > withStore storePath $ \store -> -- > runSciFlow coord transport store resources 2 wf -- > -- DRMAA workers -- > "slave" -> startClient (Proxy :: Proxy Drmaa) -- > (mkNodeId serverAddr port) $ _function_table wf -------------------------------------------------------------------------------- module Control.Workflow ( -- * Workflow types SciFlow(..) , ResourceConfig(..) , Resource(..) -- * Construct workflow , Builder , node , nodePar , uNode , doc , nCore , memory , queue , (~>) , path , namespace , build -- * Run workflow , withCoordinator , withStore , startClient , runSciFlow , mkNodeId ) where import Control.Workflow.Types import Control.Workflow.Language import Control.Workflow.Language.TH import Control.Workflow.Interpreter.Exec import Control.Workflow.DataStore import Control.Workflow.Coordinator import Control.Workflow.Utils
kaizhang/SciFlow
SciFlow/src/Control/Workflow.hs
Haskell
mit
3,631
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} -- | This module provides abstractions for parallel job processing. module Control.TimeWarp.Manager.Job ( -- * Job data types InterruptType (..) , JobCurator (..) -- * 'JobsState' lenses , jcCounter , jcIsClosed , jcJobs -- * Manager utilities , addManagerAsJob , addSafeThreadJob , addThreadJob , interruptAllJobs , isInterrupted , mkJobCurator , stopAllJobs , unlessInterrupted ) where import Control.Concurrent (forkIO) import Control.Concurrent.STM (atomically, check) import Control.Concurrent.STM.TVar (TVar, newTVarIO, readTVar, readTVarIO, writeTVar) import Control.Lens (at, makeLenses, use, view, (&), (.=), (.~), (<<+=), (<<.=), (?=), (^.)) import Control.Monad (mapM_, unless, void) import Control.Monad.Catch (MonadMask (mask), finally) import Control.Monad.Extra ((&&^)) import Control.Monad.Trans (MonadIO (liftIO)) import Control.Monad.Trans.Control (MonadBaseControl (..)) import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM hiding (HashMap) import Serokell.Util.Base (inCurrentContext) import Serokell.Util.Concurrent (modifyTVarS, threadDelay) import System.Wlog (CanLog) import Control.TimeWarp.Timed (Microsecond, MonadTimed, fork_, killThread, myThreadId) -- | Unique identifier of job. newtype JobId = JobId Word deriving (Show, Eq, Num, Hashable) -- | Job killer. newtype JobInterrupter = JobInterrupter { runJobInterrupter :: IO () } -- | Action to mark job as finished newtype MarkJobFinished = MarkJobFinished { runMarker :: IO () } data JobCuratorState = JobCuratorState { -- | @True@ if interrupt had been invoked. Also, when @True@, no job could be added _jcIsClosed :: !Bool -- | 'Map' with currently active jobs , _jcJobs :: !(HashMap JobId JobInterrupter) -- | Total number of allocated jobs ever , _jcCounter :: !JobId } makeLenses ''JobCuratorState -- | Keeps set of jobs. Allows to stop jobs and wait till all of them finish. newtype JobCurator = JobCurator { getJobCurator :: TVar JobCuratorState } -- | Defines way to interrupt all jobs in curator. data InterruptType = Plain -- ^ Just interrupt all jobs | Force -- ^ Interrupt all jobs, and treat them all as completed | WithTimeout !Microsecond !(IO ()) -- ^ Interrupt all jobs in `Plain` was, but if some jobs fail to complete in time, -- interrupt `Force`ly and execute given action. mkJobCurator :: MonadIO m => m JobCurator mkJobCurator = JobCurator <$> (liftIO $ newTVarIO JobCuratorState { _jcIsClosed = False , _jcJobs = mempty , _jcCounter = 0 }) -- | Remembers and starts given action. -- Once `interruptAllJobs` called on this manager, if job is not completed yet, -- `JobInterrupter` is invoked. -- -- Given job *must* invoke given `MarkJobFinished` upon finishing, even if it was -- interrupted. -- -- If curator is already interrupted, action would not start, and `JobInterrupter` -- would be invoked. addJob :: MonadIO m => JobCurator -> JobInterrupter -> (MarkJobFinished -> m ()) -> m () addJob (getJobCurator -> curator) ji@(runJobInterrupter -> interrupter) action = do jidm <- liftIO . atomically $ do st <- readTVar curator let closed = st ^. jcIsClosed if closed then return Nothing else modifyTVarS curator $ do no <- jcCounter <<+= 1 jcJobs . at no ?= ji return $ Just no maybe (liftIO interrupter) (action . markReady) jidm where markReady jid = MarkJobFinished $ atomically $ do st <- readTVar curator writeTVar curator $ st & jcJobs . at jid .~ Nothing -- | Invokes `JobInterrupter`s for all incompleted jobs. -- Has no effect on second call. interruptAllJobs :: MonadIO m => JobCurator -> InterruptType -> m () interruptAllJobs (getJobCurator -> curator) Plain = do jobs <- liftIO . atomically $ modifyTVarS curator $ do wasClosed <- jcIsClosed <<.= True if wasClosed then return mempty else use jcJobs liftIO $ mapM_ runJobInterrupter jobs interruptAllJobs c@(getJobCurator -> curator) Force = do interruptAllJobs c Plain liftIO . atomically $ modifyTVarS curator $ jcJobs .= mempty interruptAllJobs c@(getJobCurator -> curator) (WithTimeout delay onTimeout) = do interruptAllJobs c Plain void $ liftIO . forkIO $ do threadDelay delay done <- HM.null . view jcJobs <$> readTVarIO curator unless done $ liftIO onTimeout >> interruptAllJobs c Force -- | Waits for this manager to get closed and all registered jobs to invoke -- `MaskForJobFinished`. awaitAllJobs :: MonadIO m => JobCurator -> m () awaitAllJobs (getJobCurator -> jc) = liftIO . atomically $ check =<< (view jcIsClosed &&^ (HM.null . view jcJobs)) <$> readTVar jc -- | Interrupts and then awaits for all jobs to complete. stopAllJobs :: MonadIO m => JobCurator -> m () stopAllJobs c = interruptAllJobs c Plain >> awaitAllJobs c -- | Add second manager as a job to first manager. addManagerAsJob :: (MonadIO m, MonadTimed m, MonadBaseControl IO m) => JobCurator -> InterruptType -> JobCurator -> m () addManagerAsJob curator intType managerJob = do interrupter <- inCurrentContext $ interruptAllJobs managerJob intType addJob curator (JobInterrupter interrupter) $ \(runMarker -> ready) -> fork_ $ awaitAllJobs managerJob >> liftIO ready -- | Adds job executing in another thread, where interrupting kills the thread. addThreadJob :: (CanLog m, MonadIO m, MonadMask m, MonadTimed m, MonadBaseControl IO m) => JobCurator -> m () -> m () addThreadJob curator action = mask $ \unmask -> fork_ $ do tid <- myThreadId killer <- inCurrentContext $ killThread tid addJob curator (JobInterrupter killer) $ \(runMarker -> markReady) -> unmask action `finally` liftIO markReady -- | Adds job executing in another thread, interrupting does nothing. -- Usefull then work stops itself on interrupt, and we just need to wait till it fully -- stops. addSafeThreadJob :: (MonadIO m, MonadMask m, MonadTimed m) => JobCurator -> m () -> m () addSafeThreadJob curator action = mask $ \unmask -> fork_ $ addJob curator (JobInterrupter $ return ()) $ \(runMarker -> markReady) -> unmask action `finally` liftIO markReady isInterrupted :: MonadIO m => JobCurator -> m Bool isInterrupted = liftIO . atomically . fmap (view jcIsClosed) . readTVar . getJobCurator unlessInterrupted :: MonadIO m => JobCurator -> m () -> m () unlessInterrupted c a = isInterrupted c >>= flip unless a
serokell/time-warp
src/Control/TimeWarp/Manager/Job.hs
Haskell
mit
7,469
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGPathSegArcAbs (js_setX, setX, js_getX, getX, js_setY, setY, js_getY, getY, js_setR1, setR1, js_getR1, getR1, js_setR2, setR2, js_getR2, getR2, js_setAngle, setAngle, js_getAngle, getAngle, js_setLargeArcFlag, setLargeArcFlag, js_getLargeArcFlag, getLargeArcFlag, js_setSweepFlag, setSweepFlag, js_getSweepFlag, getSweepFlag, SVGPathSegArcAbs, castToSVGPathSegArcAbs, gTypeSVGPathSegArcAbs) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"x\"] = $2;" js_setX :: SVGPathSegArcAbs -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.x Mozilla SVGPathSegArcAbs.x documentation> setX :: (MonadIO m) => SVGPathSegArcAbs -> Float -> m () setX self val = liftIO (js_setX (self) val) foreign import javascript unsafe "$1[\"x\"]" js_getX :: SVGPathSegArcAbs -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.x Mozilla SVGPathSegArcAbs.x documentation> getX :: (MonadIO m) => SVGPathSegArcAbs -> m Float getX self = liftIO (js_getX (self)) foreign import javascript unsafe "$1[\"y\"] = $2;" js_setY :: SVGPathSegArcAbs -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.y Mozilla SVGPathSegArcAbs.y documentation> setY :: (MonadIO m) => SVGPathSegArcAbs -> Float -> m () setY self val = liftIO (js_setY (self) val) foreign import javascript unsafe "$1[\"y\"]" js_getY :: SVGPathSegArcAbs -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.y Mozilla SVGPathSegArcAbs.y documentation> getY :: (MonadIO m) => SVGPathSegArcAbs -> m Float getY self = liftIO (js_getY (self)) foreign import javascript unsafe "$1[\"r1\"] = $2;" js_setR1 :: SVGPathSegArcAbs -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.r1 Mozilla SVGPathSegArcAbs.r1 documentation> setR1 :: (MonadIO m) => SVGPathSegArcAbs -> Float -> m () setR1 self val = liftIO (js_setR1 (self) val) foreign import javascript unsafe "$1[\"r1\"]" js_getR1 :: SVGPathSegArcAbs -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.r1 Mozilla SVGPathSegArcAbs.r1 documentation> getR1 :: (MonadIO m) => SVGPathSegArcAbs -> m Float getR1 self = liftIO (js_getR1 (self)) foreign import javascript unsafe "$1[\"r2\"] = $2;" js_setR2 :: SVGPathSegArcAbs -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.r2 Mozilla SVGPathSegArcAbs.r2 documentation> setR2 :: (MonadIO m) => SVGPathSegArcAbs -> Float -> m () setR2 self val = liftIO (js_setR2 (self) val) foreign import javascript unsafe "$1[\"r2\"]" js_getR2 :: SVGPathSegArcAbs -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.r2 Mozilla SVGPathSegArcAbs.r2 documentation> getR2 :: (MonadIO m) => SVGPathSegArcAbs -> m Float getR2 self = liftIO (js_getR2 (self)) foreign import javascript unsafe "$1[\"angle\"] = $2;" js_setAngle :: SVGPathSegArcAbs -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.angle Mozilla SVGPathSegArcAbs.angle documentation> setAngle :: (MonadIO m) => SVGPathSegArcAbs -> Float -> m () setAngle self val = liftIO (js_setAngle (self) val) foreign import javascript unsafe "$1[\"angle\"]" js_getAngle :: SVGPathSegArcAbs -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.angle Mozilla SVGPathSegArcAbs.angle documentation> getAngle :: (MonadIO m) => SVGPathSegArcAbs -> m Float getAngle self = liftIO (js_getAngle (self)) foreign import javascript unsafe "$1[\"largeArcFlag\"] = $2;" js_setLargeArcFlag :: SVGPathSegArcAbs -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.largeArcFlag Mozilla SVGPathSegArcAbs.largeArcFlag documentation> setLargeArcFlag :: (MonadIO m) => SVGPathSegArcAbs -> Bool -> m () setLargeArcFlag self val = liftIO (js_setLargeArcFlag (self) val) foreign import javascript unsafe "($1[\"largeArcFlag\"] ? 1 : 0)" js_getLargeArcFlag :: SVGPathSegArcAbs -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.largeArcFlag Mozilla SVGPathSegArcAbs.largeArcFlag documentation> getLargeArcFlag :: (MonadIO m) => SVGPathSegArcAbs -> m Bool getLargeArcFlag self = liftIO (js_getLargeArcFlag (self)) foreign import javascript unsafe "$1[\"sweepFlag\"] = $2;" js_setSweepFlag :: SVGPathSegArcAbs -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.sweepFlag Mozilla SVGPathSegArcAbs.sweepFlag documentation> setSweepFlag :: (MonadIO m) => SVGPathSegArcAbs -> Bool -> m () setSweepFlag self val = liftIO (js_setSweepFlag (self) val) foreign import javascript unsafe "($1[\"sweepFlag\"] ? 1 : 0)" js_getSweepFlag :: SVGPathSegArcAbs -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegArcAbs.sweepFlag Mozilla SVGPathSegArcAbs.sweepFlag documentation> getSweepFlag :: (MonadIO m) => SVGPathSegArcAbs -> m Bool getSweepFlag self = liftIO (js_getSweepFlag (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGPathSegArcAbs.hs
Haskell
mit
6,051
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE FlexibleContexts #-} -- | -- -- Module : EventProbability.NaiveBayes.Weka -- Description : NaiveBayes for Weka data. -- License : MIT -- -- NaiveBayes learing and classification for Weka data. -- module EventProbability.NaiveBayes.Weka ( -- * Prepare wekaEntry2Event -- * Execute , buildCaches , classifyWekaData , ClassifyResult -- * Test , learnAndTest , Filename , runWekaLearnAndTest ) where import Cache import EventProbability import EventProbability.Cache import EventProbability.NaiveBayes import WekaData import qualified Data.Set as Set import Data.Maybe ( fromMaybe, maybeToList ) import Data.List ( find ) import Data.Typeable import Control.Arrow ( (&&&) ) import Control.Monad ( when ) ----------------------------------------------------------------------------- instance AtomicEvent WekaVal where eventName (WVal attr _) = EventName $ wekaAttributeName attr eventDomain (WVal attr@(WekaAttrNom _ dom) _) = Set.fromList $ map (uncurry WVal . (const attr &&& id)) dom ----------------------------------------------------------------------------- -- | Build an 'Event' from a 'WekaEntry'. wekaEntry2Event :: (Show WekaVal) => WekaEntry -> Event wekaEntry2Event (WEntry vals) = compositeEvent vals ----------------------------------------------------------------------------- -- | Create initial 'EventCaches' and update counts of the 'EventCountCache'. buildCaches :: (Show WekaVal) => RawWekaData -> IO (EventCaches IO) buildCaches rawData = do cc <- newIOCache pc <- newIOCache cpc <- newIOCache updateCountCache cc events return $ EvCaches cc pc cpc where events = map wekaEntry2Event $ wekaData2Sparse rawData ----------------------------------------------------------------------------- -- | Classification result of an 'Event'. type ClassifyResult = (Event, Maybe (EvAtom, Prob)) -- | Classifies given 'RawWekaData' by given attribute name using 'EventCaches'. classifyWekaData :: (Show WekaVal, NaiveBayesCondProb (EventCaches IO) IO) => EventCaches IO -> RawWekaData -- ^ data to classify. -> String -- ^ attribute to clasify. -> IO [ClassifyResult] classifyWekaData caches rawData className = sequence $ do ev <- events return $ do c <- classifyEvent caches cAtom ev return (ev, c) where classifyBy = fromMaybe (error $ errStr ++ show className) $ find ((==) className . wekaAttributeName) $ rwdAttrs rawData errStr = "couldn't find an attribute with name " cAtom = EvAtom $ WVal classifyBy undefined events = map wekaEntry2Event $ wekaData2Sparse rawData ----------------------------------------------------------------------------- -- | Teaches a /Naive Bayes/ classifier (updates the caches) with the -- /learn/ data and tests the classification quality with the /test/ data. learnAndTest :: ( Show WekaVal, Show WekaEntry , NaiveBayesCondProb (EventCaches IO) IO) => RawWekaData -- ^ /learn/ data. -> RawWekaData -- ^ /test/ data. -> String -- ^ attribute to classify. -> Bool -- ^ show test results. -> IO (EventCaches IO, [ClassifyResult]) learnAndTest learnData testData className showRes = do caches <- buildCaches learnData testClassify <- classifyWekaData caches testData className -- for showRes let err = "class '" ++ className ++ "' not found in " let getClass e@(WEntry set) = find (\(WVal a _)-> className == wekaAttributeName a) $ Set.toList set let expectedRes = map getClass $ wekaData2Sparse testData let notClassified ev exp = do putStrLn $ "\n[?]" ++ show ev ++ " wasn't classified, expected " ++ show exp return False let compareClassified ev exp (EvAtom c, p) = case cast exp of Just exp' | exp' == c -> do putStrLn strOk return True _ -> do putStrLn strFail return False where strOk = "\n[+]\t" ++ show ev ++ " was classified correcly (" ++ show c ++ ") with probability " ++ show p strFail = "\n[-]\t" ++ show ev ++ " was classified incorrecly: expected " ++ show exp ++ ", got " ++ show c ++ "(with probability " ++ show p ++ ")" when showRes $ do results <- sequence $ do ((ev, mbClass), mbExp) <- zip testClassify expectedRes let compare exp = maybe (notClassified ev exp) (compareClassified ev exp) mbClass maybe [] (return . compare) mbExp let ok = length $ filter id results putStrLn $ replicate 30 '=' putStrLn $ show ok ++ "\t classified correctly" putStrLn $ show (length results - ok) ++ "\t classified incorrectly" return (caches, testClassify) ----------------------------------------------------------------------------- type Filename = String -- | Calls 'learnAndTest' after extracting 'RawWekaData' from the given files. runWekaLearnAndTest :: ( Show WekaVal, Show WekaEntry , NaiveBayesCondProb (EventCaches IO) IO) => Filename -- ^ path to a weka data file with /learn/ data. -> Filename -- ^ path to a weka data file with /test/ data. -> String -- ^ attribute to classify. -> Bool -- ^ show test results. -> IO (EventCaches IO, [ClassifyResult]) runWekaLearnAndTest learnFile testFile className showRes = do learnData <- readWekaData learnFile testData <- readWekaData testFile learnAndTest learnData testData className showRes -----------------------------------------------------------------------------
fehu/min-dat--naive-bayes
src/EventProbability/NaiveBayes/Weka.hs
Haskell
mit
6,125
{-# LANGUAGE DeriveGeneric #-} module U.Codebase.Kind where import U.Util.Hashable (Hashable) import qualified U.Util.Hashable as Hashable import GHC.Generics (Generic) data Kind = Star | Arrow Kind Kind deriving (Eq,Ord,Read,Show,Generic) instance Hashable Kind where tokens k = case k of Star -> [Hashable.Tag 0] Arrow k1 k2 -> (Hashable.Tag 1 : Hashable.tokens k1) ++ Hashable.tokens k2
unisonweb/platform
codebase2/codebase/U/Codebase/Kind.hs
Haskell
mit
404
-- Disguised sequences (II) -- https://www.codewars.com/kata/56fe17fcc25bf3e19a000292 module Codewars.G964.Disguised2 where u1 :: Integer -> Integer -> Integer u1 n p = p * succ n v1 :: Integer -> Integer -> Integer v1 n p = p * succ (2 * n) uEff :: Integer -> Integer -> Integer uEff = u1 vEff :: Integer -> Integer -> Integer vEff = v1
gafiatulin/codewars
src/6 kyu/Disguised2.hs
Haskell
mit
343
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveGeneric #-} module Network.OnDemandSSHTunnel ( SSHTunnel(..), Config(..), prettyConfig, setupConfiguration, setupOnDemandTunnel ) where import System.Process import Control.Monad import Control.Concurrent import Control.Exception import qualified Control.Exception as CE import Network.Socket import System.Random import System.IO import qualified Data.ByteString as BS import Text.Printf (printf) import System.Mem import Text.PrettyPrint.GenericPretty data SSHTunnel = SSHTunnel Int String [String] deriving (Show, Read, Generic) newtype Config = Config [SSHTunnel] deriving (Show, Read, Generic) instance Out SSHTunnel instance Out Config prettyConfig :: Config -> String prettyConfig = pretty setupConfiguration :: Config -> IO () setupConfiguration (Config tuns) = forM_ tuns $ forkIO . setupOnDemandTunnel setupOnDemandTunnel :: SSHTunnel -> IO () setupOnDemandTunnel (SSHTunnel listenPort targetHostPort sshArgs) = do sock <- socket AF_INET Stream defaultProtocol setSocketOption sock ReuseAddr 1 addr <- inet_addr "127.0.0.1" bindSocket sock $ SockAddrInet (fromIntegral listenPort) addr listen sock 5 putStrLn $ "listening for connections on port " ++ show listenPort forever $ do (conn, connaddr) <- accept sock hConn <- socketToHandle conn ReadWriteMode putStrLn $ "connection accepted: " ++ show connaddr forkIO $ do tunnelPort :: Int <- randomRIO (50000, 55000) handleConnection hConn tunnelPort targetHostPort sshArgs handleConnection :: Handle -> Int -> String -> [String] -> IO () handleConnection hConn tunnelPort targetHostPort sshArgs = do (_, _, _, p) <- createProcess (proc "ssh" $ ["-v"] ++ [ "-L" ++ show tunnelPort ++ ":" ++ targetHostPort, "-n"] ++ sshArgs) finally forwardToTunnel $ do putStrLn "terminating ssh" terminateProcess p _ <- waitForProcess p putStrLn "ssh exited" performGC -- a good moment to finalize handles where forwardToTunnel = do hTunn <- tryTunnelConnection tunnelPort 15 _ <- forkIO $ forward "hTunn->hConn" hTunn hConn forward "hConn->hTunn" hConn hTunn forward desc h1 h2 = forever $ do bs <- BS.hGetSome h1 4096 putStrLn $ printf "%s %d bytes" desc (BS.length bs) if BS.null bs then error "no more data to tunnel" else do BS.hPut h2 bs hFlush h2 tryTunnelConnection :: Int -> Int -> IO Handle tryTunnelConnection _ 0 = error "can't connect to tunnel" tryTunnelConnection port attempts = do threadDelay (1*1000*1000) tunn <- socket AF_INET Stream defaultProtocol addr <- inet_addr "127.0.0.1" CE.catch (do connect tunn $ SockAddrInet (fromIntegral port) addr hTunn <- socketToHandle tunn ReadWriteMode putStrLn "got hTunn" return hTunn) (\(_::SomeException) -> do sClose tunn tryTunnelConnection port (attempts-1))
crackleware/on-demand-ssh-tunnel
src/Network/OnDemandSSHTunnel.hs
Haskell
mit
3,125
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html module Stratosphere.ResourceProperties.RedshiftClusterLoggingProperties where import Stratosphere.ResourceImports -- | Full data type definition for RedshiftClusterLoggingProperties. See -- 'redshiftClusterLoggingProperties' for a more convenient constructor. data RedshiftClusterLoggingProperties = RedshiftClusterLoggingProperties { _redshiftClusterLoggingPropertiesBucketName :: Val Text , _redshiftClusterLoggingPropertiesS3KeyPrefix :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON RedshiftClusterLoggingProperties where toJSON RedshiftClusterLoggingProperties{..} = object $ catMaybes [ (Just . ("BucketName",) . toJSON) _redshiftClusterLoggingPropertiesBucketName , fmap (("S3KeyPrefix",) . toJSON) _redshiftClusterLoggingPropertiesS3KeyPrefix ] -- | Constructor for 'RedshiftClusterLoggingProperties' containing required -- fields as arguments. redshiftClusterLoggingProperties :: Val Text -- ^ 'rclpBucketName' -> RedshiftClusterLoggingProperties redshiftClusterLoggingProperties bucketNamearg = RedshiftClusterLoggingProperties { _redshiftClusterLoggingPropertiesBucketName = bucketNamearg , _redshiftClusterLoggingPropertiesS3KeyPrefix = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-bucketname rclpBucketName :: Lens' RedshiftClusterLoggingProperties (Val Text) rclpBucketName = lens _redshiftClusterLoggingPropertiesBucketName (\s a -> s { _redshiftClusterLoggingPropertiesBucketName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-s3keyprefix rclpS3KeyPrefix :: Lens' RedshiftClusterLoggingProperties (Maybe (Val Text)) rclpS3KeyPrefix = lens _redshiftClusterLoggingPropertiesS3KeyPrefix (\s a -> s { _redshiftClusterLoggingPropertiesS3KeyPrefix = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/RedshiftClusterLoggingProperties.hs
Haskell
mit
2,221
{-# LANGUAGE OverloadedStrings #-} module Network.API.Mandrill.Messages where import Network.API.Mandrill.Utils import Network.API.Mandrill.Response import Network.API.Mandrill.Types -- | Send a new transactional message through Mandrill send :: (MonadIO m) => Message -> MessageConfig -> MandrillT m (Either ApiError [DeliveryStatus]) send m c = performRequest "/messages/send.json" $ [ "message" .= m , "ip_pool" .= _conf_ip_pool c , "async" .= _conf_async c , "send_at" .= _conf_send_at c ] -- | Send a new transactional message through Mandrill using a template sendTmpl :: (MonadIO m) => Message -> MessageConfig -> Name -> [Content] -> MandrillT m (Either ApiError [DeliveryStatus]) sendTmpl m c t tc = performRequest "/messages/send-template.json" $ [ "template_name" .= t , "template_content" .= tc , "message" .= m , "ip_pool" .= _conf_ip_pool c , "async" .= _conf_async c , "send_at" .= _conf_send_at c ] -- | Search recently sent messages and optionally narrow by date -- range, tags, senders, and API keys. If no date range is specified, -- results within the last 7 days are returned. This method may be called -- up to 20 times per minute. If you need the data more often, -- you can use /messages/info.json to get the information for a single message, -- or webhooks to push activity to your own application for querying. search :: (MonadIO m) => Query -> From -> Thru -> [Tag] -> [Email] -> [ApiKey] -> Count -> MandrillT m (Either ApiError [SearchResult]) search q f t ts es ks c = performRequest "/messages/search.json" $ [ "query" .= q , "date_from" .= f , "date_to" .= t , "tags" .= ts , "senders" .= es , "api_keys" .= ks , "limit" .= c ] -- | Search the content of recently sent messages and return the aggregated -- hourly stats for matching messages searchTimeSeries :: (MonadIO m ) => Query -> From -> Thru -> [Tag] -> [Email] -> MandrillT m (Either ApiError [Stat]) searchTimeSeries q f t ts es = performRequest "/messages/search-time-series.json" $ [ "query" .= q , "date_from" .= f , "date_to" .= t , "tags" .= ts , "senders" .= es ] -- | Get the information for a single recently sent message info :: (MonadIO m) => MessageId -> MandrillT m (Either ApiError SearchResult) info mid = performRequest "/messages/info.json" ["id" .= mid] -- | Get the full content of a recently sent message content :: (MonadIO m ) => MessageId -> MandrillT m (Either ApiError Message) content mid = performRequest "/messages/content.json" ["id" .= mid] -- | Parse the full MIME document for an email message, returning the content -- of the message broken into its constituent pieces parse :: (MonadIO m) => RawMessage -> MandrillT m (Either ApiError Message) parse raw = performRequest "/messages/parse.json" ["raw_message" .= raw] -- | Take a raw MIME document for a message, and send it exactly as if it -- were sent through Mandrill's SMTP servers sendRaw :: (MonadIO m) => RawMessage -> Email -> Name -> [Recipient] -> MessageConfig -> MandrillT m (Either ApiError [DeliveryStatus]) sendRaw raw e n to c = performRequest "/messages/send-raw.json" $ [ "raw_message" .= raw , "from_email" .= e , "from_name" .= n , "to" .= to , "async" .= _conf_async c , "ip_pool" .= _conf_ip_pool c , "send_at" .= _conf_send_at c ] -- | Queries your scheduled emails by sender or recipient, or both. listScheduled :: (MonadIO m) => Email -> MandrillT m (Either ApiError [Scheduled]) listScheduled e = performRequest "/messages/list-scheduled.json" ["to" .= e] -- | Cancels a scheduled email. cancelScheduled :: (MonadIO m) => ScheduledId -> MandrillT m (Either ApiError Scheduled) cancelScheduled i = performRequest "/messages/cancel-scheduled.json" ["id" .= i] -- | Reschedules a scheduled email. reschedule :: (MonadIO m) => ScheduledId -> TimeStamp -> MandrillT m (Either ApiError Scheduled) reschedule i s = performRequest "/messages/reschedule.json" $ [ "id" .= i , "send_at" .= s ]
krgn/hamdrill
src/Network/API/Mandrill/Messages.hs
Haskell
mit
4,831
-- Making our own types and typeclasses module Shapes ( Point(..) , Shape(..) , surface , nudge , baseCircle , baseRect ) where data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b)) baseCircle :: Float -> Shape baseCircle r = Circle (Point 0 0) r baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) -- record syntax, fields get functions that get the field data Person = Person { firstName :: String , lastName :: String , age :: Int , height :: Float , phoneNumber :: String , flavor :: String } deriving (Show) data Car = Car { company :: String , model :: String , year :: Int } deriving (Show) -- its a very strong convention in haskell to never add typeclass -- constraints in data declarations.
autocorr/lyah
chap8.hs
Haskell
mit
1,237
-- ------------------------------------------------------------------------------------- -- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. -- For email, run on linux (perl v5.8.5): -- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' -- ------------------------------------------------------------------------------------- import Data.List import Data.Ord minDiffFrom :: Int -> [Int] -> Int minDiffFrom fromme = minimum . map ((abs) . (\x -> fromme - x)) solveProblem :: Int -> Int -> [Int] -> Int solveProblem p q ns = let ns' = sort ns pcand = minDiffFrom p ns' qcand = minDiffFrom q ns' mids = filter (\(x, dx)-> (x >= p) && (x <= q)) . reverse . snd . foldl' (\a@(ln, ls) nn -> (nn, ((ln+nn) `div` 2, (nn-ln) `div` 2):ls)) (head ns', []) $ tail ns' allCands = (p, pcand):(q, qcand):mids maxdelta = maximum . map snd $ allCands chosen = head . sort . map fst . filter ((== maxdelta) . snd) $ allCands in chosen main :: IO () main = do _ <- getLine nsstr <- getLine pqstr <- getLine let ns = map read . words $ nsstr [p, q] = map read . words $ pqstr ans = solveProblem p q ns putStrLn $ show ans
cbrghostrider/Hacking
HackerRank/Algorithms/Greedy/minimax.hs
Haskell
mit
1,287
module Compiling where import Control.Monad.Writer import System.Process import System.Exit import Text.Printf import Data.List.Split data GC = JGC | Stub data TDir = NoTDir | TDirAt FilePath data CompilerFlags = CF { tdir :: TDir , entryPoint :: Maybe String , cCompiler :: String , extraCFlags :: [String] , includes :: [String] , hsCompiler :: String , ignoreCache :: Bool , debug :: Bool , extraHaskellFlags :: [String] , toC :: Bool , cPreprocessor :: [(PreprocessorFlag, Maybe String)] , hsPreprocessor :: Maybe [(PreprocessorFlag, Maybe String)] , gc :: GC } type PreprocessorFlag = String preprocessorFlags :: [(PreprocessorFlag, Maybe String)] -> [String] preprocessorFlags = map $ \pair -> case pair of (flag, Nothing) -> "-D"++flag (flag, Just val) -> "-D"++flag++"="++val whenJust :: (Monad m) => Maybe a -> (a -> m ()) -> m () whenJust Nothing _ = return () whenJust (Just a) f = f a fileToModuleName :: String -> String fileToModuleName = takeWhile (/= '.') compilerFlagsToHaskell :: FilePath -> Maybe FilePath -> CompilerFlags -> [String] compilerFlagsToHaskell input output flags = snd $ runWriter $ do case gc flags of JGC -> return () Stub -> tell ["-fjgc-stub"] whenJust (entryPoint flags) $ \main -> tell ["--main=" ++ fileToModuleName input ++ "." ++ main] when (ignoreCache flags) $ tell ["--ignore-cache"] whenJust (hsPreprocessor flags) $ \ppFlags -> do tell ["-fcpp"] tell $ preprocessorFlags ppFlags tell $ extraHaskellFlags flags case tdir flags of NoTDir -> return () TDirAt dir -> tell ["--tdir=" ++ dir] --TDirRandom -> return () -- TODO implement this at some point when (toC flags) (tell ["-C"]) whenJust output (\filename -> tell ["--output=" ++ filename]) tell [input] includeDirectives :: [String] -> [String] includeDirectives = map ("-I" ++) compilerFlagsToC :: [FilePath] -> Maybe FilePath -> CompilerFlags -> [String] compilerFlagsToC inputs output flags = snd $ runWriter $ do case gc flags of JGC -> tell ["-D_JHC_GC=_JHC_GC_JGC"] Stub -> tell ["-D_JHC_GC=_JHC_GC_JGC", "-D_JHC_GC_JGC_STUB"] tell $ includeDirectives $ includes flags tell $ extraCFlags flags when (debug flags) $ tell ["-g"] tell $ preprocessorFlags $ cPreprocessor flags whenJust output (\filename -> tell ["-o " ++ filename]) tell inputs runHaskellCompiler :: FilePath -> Maybe FilePath -> CompilerFlags -> IO(ExitCode,String,String) runHaskellCompiler input output flags = do printf "Command: %s %s\n" compiler (unwords haskellFlags) readProcessWithExitCode compiler haskellFlags "" where compiler = hsCompiler flags haskellFlags = compilerFlagsToHaskell input output flags runCCompiler :: [FilePath] -> Maybe FilePath -> CompilerFlags -> IO (ExitCode, String, String) runCCompiler inputs output flags = do printf "Command: %s %s\n" compiler (unwords cFlags) readProcessWithExitCode compiler cFlags "" where compiler = cCompiler flags cFlags = compilerFlagsToC inputs output flags report :: ExitCode -> String -> String -> String -> IO ExitCode report exitCode input out err = do case exitCode of ExitFailure i -> do printf "Error compiling inputs %s\n" input printf "Error code %d\n" i printf "STDOUT:\n%s\n" out printf "STDERR:\n%s\n" err ExitSuccess -> return () return exitCode compileHs :: FilePath -> Maybe FilePath -> CompilerFlags -> IO ExitCode compileHs input output flags = do (exitCode, out, err) <- runHaskellCompiler input output flags report exitCode input out err runLinker :: [FilePath] -> Maybe FilePath -> IO (ExitCode, String, String) runLinker files output = readProcessWithExitCode "llvm-link" (files ++ out) "" where out = case output of Nothing -> [] Just file -> ["-o=" ++ file] replaceExtension :: String -> String replaceExtension path = takeWhile (/= '.') (last $ splitOn "/" path) ++ ".o" compileC :: [FilePath] -> Maybe FilePath -> CompilerFlags -> IO ExitCode compileC inputs output flags = do (exitCode, out, err) <- runCCompiler inputs Nothing flags _ <- report exitCode (show inputs) out err case exitCode of ExitFailure _ -> return exitCode ExitSuccess -> do (exitCode', out', err') <- runLinker (map replaceExtension inputs) output _ <- report exitCode' (show $ map replaceExtension inputs) out' err' _ <- system "rm -rf *.o" return exitCode'
m-alvarez/scher-run
Compiling.hs
Haskell
mit
4,836
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE NamedFieldPuns #-} -- A simple structure for a pool of resources. -- Each managed resource has an integer index that identifies the 'slot' for the given resource; -- when the resource is idle, this slot holds a Nothing; when it's currently used it holds the -- content of the resource module Data.Pool ( Pool , Id -- * Accessors , busy , idles , slots -- * Query , null , size -- * Creation , empty , idling , fromBusy -- * Modification , takeSlot , takeSlot_ , takeSlots , takeSlots_ , releaseSlot , reserve , growBy ) where import Prelude hiding (null) import Data.Tuple (swap) import Data.List (mapAccumL) import qualified Data.IntMap.Strict as IM import qualified Data.IntSet as IS type Id = Int -- elems hold the elements in use -- idles contains the currently unoccupied ids (but issued in the past) -- nexts contains the lazy list of all the future ids to issue -- therefore, keysSet elems \cap idles = \0 data Pool a = Pool (IM.IntMap a) -- the busy / occupied cells IS.IntSet -- the idle cells Id -- the base of the remaining id deriving (Show, Eq, Ord) -- TODO: Show instance, Eq instance..? busy :: Pool a -> IM.IntMap a busy (Pool busy _ _) = busy idles :: Pool a -> IS.IntSet idles (Pool _ idles _) = idles -- all the slots in the pool, those busy contain a 'Just a'; whereas the idle ones have a Nothing slots :: Pool a -> IM.IntMap (Maybe a) slots (Pool busy idles _) = IM.union (Just <$> busy) (IM.fromSet (const Nothing) idles) null :: Pool a -> Bool null = (&&) <$> IM.null . busy <*> IS.null . idles size :: Pool a -> Int size = (+) <$> IM.size . busy <*> IS.size . idles empty :: Pool a empty = Pool IM.empty IS.empty 0 idling :: Int -> Pool a idling c = Pool IM.empty (IS.fromList [0..c-1]) c -- | call takeSlots on the elements with an empty starting pool fromBusy :: [a] -> Pool a fromBusy = flip takeSlots_ empty takeSlot_ :: a -> Pool a -> Pool a takeSlot_ a = snd . takeSlot a takeSlot :: a -> Pool a -> (Id, Pool a) takeSlot a (Pool busy idles next) | IS.null idles = (next, Pool (IM.insert next a busy) idles (next+1)) | otherwise = let (k, idles') = IS.deleteFindMin idles in (k, Pool (IM.insert k a busy) idles' next) -- insert all elements into the pool, starting from the left takeSlots :: [a] -> Pool a -> ([Id], Pool a) takeSlots l p = swap $ mapAccumL (\p a -> let (k, p') = takeSlot a p in (p', k)) p l takeSlots_ :: [a] -> Pool a -> Pool a takeSlots_ l = snd . takeSlots l -- | reserve a certain minimum size reserve :: Int -> Pool a -> Pool a reserve c p | left > 0 = growBy left p | otherwise = p where left = c - size p growBy :: Int -> Pool a -> Pool a growBy s (Pool busy idles next) = Pool busy (foldr IS.insert idles $ take s [next..]) (next+s) releaseSlot :: Id -> Pool a -> Pool a releaseSlot k p@(Pool busy idles next) | IM.member k busy = Pool (IM.delete k busy) (IS.insert k idles) next | otherwise = p
lynnard/reflex-cocos2d
src/Data/Pool.hs
Haskell
mit
3,086
module Filter.Hyperref (hyperref) where import Text.Pandoc.Definition import Text.Pandoc.Walk (walk) tex :: String -> Inline tex = RawInline (Format "tex") f :: Inline -> Inline f x@(Link attr is (('#':id), title)) = Span nullAttr $ [ tex $ "\\hyperref[" ++ id ++ "]{" ] ++ is ++ [ tex "}" ] f x = x hyperref :: Pandoc -> Pandoc hyperref = walk f
Thhethssmuz/ppp
src/Filter/Hyperref.hs
Haskell
mit
353
#!/usr/bin/env runhaskell {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} import Data.Foldable (foldMap) import Data.Maybe (fromMaybe) import Data.Monoid import Control.Lens import qualified Data.Aeson.Lens as L import Network.StackExchange main ∷ IO () main = ask >>= print . foldMap count ask ∷ IO [SE Badge] ask = askSE $ badgesOnUsers [972985] <> site "stackoverflow" <> key "Lhg6xe5d5BvNK*C0S8jijA((" count ∷ SE Badge → (Sum Int, Sum Int, Sum Int) count (view (from se) → x) = (\l → set l (x ^. L.key "award_count" . to (Sum . fromMaybe 0)) mempty) $ case x ^. L.key "rank" . L.asText of Just "bronze" → _1 Just "silver" → _2 Just "gold" → _3 _ → error "badge rank isn't bronze/silver/gold"
supki/libstackexchange
examples/badges-watcher.hs
Haskell
mit
870
-- -- -- ------------------ -- Exercise 12.41. ------------------ -- -- -- module E'12'41 where
pascal-knodel/haskell-craft
_/links/E'12'41.hs
Haskell
mit
106
module DDF.Meta.Dual where newtype Dual l r = Dual {runDual :: (l, r)} instance Eq l => Eq (Dual l r) where (Dual (l, _)) == (Dual (r, _)) = l == r instance Ord l => Ord (Dual l r) where (Dual (l, _)) `compare` (Dual (r, _)) = l `compare` r dualOrig (Dual (l, _)) = l dualDiff (Dual (_, r)) = r mkDual l r = Dual (l, r)
ThoughtWorksInc/DeepDarkFantasy
DDF/Meta/Dual.hs
Haskell
apache-2.0
329
<?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="en-GB"> <title>Context Alert Filters | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
0xkasun/security-tools
src/org/zaproxy/zap/extension/alertFilters/resources/help/helpset.hs
Haskell
apache-2.0
995
{-# LANGUAGE CPP, OverloadedStrings, PackageImports, ScopedTypeVariables #-} -- | In which Hawk's command-line arguments are structured into a `HawkSpec`. module System.Console.Hawk.Args.Parse (parseArgs) where import Prelude hiding (fail) #if MIN_VERSION_base(4,12,0) import Control.Monad.Fail (fail) #else import Prelude (fail) #endif import Data.Char (isSpace) import Data.Maybe import "mtl" Control.Monad.Trans import Control.Monad.Trans.OptionParser import Control.Monad.Trans.Uncertain import qualified System.Console.Hawk.Args.Option as Option import System.Console.Hawk.Args.Option (HawkOption, options) import System.Console.Hawk.Args.Spec import System.Console.Hawk.Context.Dir -- $setup -- >>> let testP parser = runUncertainIO . runOptionParserT options parser -- | (record processor, field processor) type CommonProcessors = (Processor, Processor) -- | Extract '-D' and '-d'. We perform this step separately because those two -- delimiters are used by both the input and output specs. -- -- >>> let test = testP commonProcessors -- -- >>> test [] -- (SeparateOn (Delimiter "\n"),SeparateOn Whitespace) -- -- >>> test ["-D\\n", "-d\\t"] -- (SeparateOn (Delimiter "\n"),SeparateOn (Delimiter "\t")) -- -- >>> test ["-D|", "-d,"] -- (SeparateOn (Delimiter "|"),SeparateOn (Delimiter ",")) -- -- >>> test ["-D", "-d"] -- (DoNotSeparate,DoNotSeparate) commonProcessors :: forall m. (Functor m, Monad m) => OptionParserT HawkOption m CommonProcessors commonProcessors = do r <- consumeProcessor Option.RecordDelimiter defaultRecordSeparator f <- consumeProcessor Option.FieldDelimiter defaultFieldSeparator return (r, f) where consumeProcessor :: HawkOption -> Separator -> OptionParserT HawkOption m Processor consumeProcessor opt def = fromMaybe (SeparateOn def) <$> consumeLast opt (Option.processorConsumer) -- | The input delimiters have already been parsed, but we still need to -- interpret them and to determine the input source. -- -- >>> :{ -- let test = testP $ do { c <- commonProcessors -- ; _ <- consumeExtra stringConsumer -- skip expr -- ; i <- inputSpec c -- ; lift $ print $ inputSource i -- ; lift $ print $ inputFormat i -- } -- :} -- -- >>> test [] -- UseStdin -- Records (Delimiter "\n") (Fields Whitespace) -- -- >>> test ["-d", "-a", "L.reverse"] -- UseStdin -- Records (Delimiter "\n") RawRecord -- -- >>> test ["-D", "-a", "B.reverse"] -- UseStdin -- RawStream -- -- >>> test ["-d:", "-m", "L.head", "/etc/passwd"] -- InputFile "/etc/passwd" -- Records (Delimiter "\n") (Fields (Delimiter ":")) inputSpec :: (Functor m, Monad m) => CommonProcessors -> OptionParserT HawkOption m InputSpec inputSpec (rProc, fProc) = InputSpec <$> source <*> format where source = do r <- consumeExtra stringConsumer return $ case r of Nothing -> UseStdin Just f -> InputFile f format = return streamFormat streamFormat = case rProc of DoNotSeparate -> RawStream SeparateOn rSep -> Records rSep recordFormat recordFormat = case fProc of DoNotSeparate -> RawRecord SeparateOn fSep -> Fields fSep -- | The output delimiters take priority over the input delimiters, regardless -- of the order in which they appear. -- -- >>> :{ -- let test = testP $ do { c <- commonProcessors -- ; o <- outputSpec c -- ; let OutputFormat r f = outputFormat o -- ; lift $ print $ outputSink o -- ; lift $ print (r, f) -- } -- :} -- -- >>> test [] -- UseStdout -- ("\n"," ") -- -- >>> test ["-D;", "-d", "-a", "L.reverse"] -- UseStdout -- (";"," ") -- -- >>> test ["-o\t", "-d,", "-O|"] -- UseStdout -- ("|","\t") outputSpec :: forall m. (Functor m, Monad m) => CommonProcessors -> OptionParserT HawkOption m OutputSpec outputSpec (r, f) = OutputSpec <$> sink <*> format where sink :: OptionParserT HawkOption m OutputSink sink = return UseStdout format :: OptionParserT HawkOption m OutputFormat format = OutputFormat <$> record <*> field record, field :: OptionParserT HawkOption m Delimiter record = fmap (fromMaybe r') $ consumeLast Option.OutputRecordDelimiter $ fromMaybe "" <$> optionalConsumer Option.delimiterConsumer field = fmap (fromMaybe f') $ consumeLast Option.OutputFieldDelimiter $ fromMaybe "" <$> optionalConsumer Option.delimiterConsumer r', f' :: Delimiter r' = fromProcessor defaultRecordDelimiter r f' = fromProcessor defaultFieldDelimiter f -- | The information we need in order to evaluate a user expression: -- the expression itself, and the context in which it should be evaluated. -- In Hawk, that context is the user prelude. -- -- >>> :{ -- let test = testP $ do { e <- exprSpec -- ; lift $ print $ untypedExpr e -- ; lift $ print $ userContextDirectory (contextSpec e) -- } -- :} -- -- >>> test [] -- error: missing user expression -- *** Exception: ExitFailure 1 -- -- >>> test [""] -- error: user expression cannot be empty -- *** Exception: ExitFailure 1 -- -- >>> test ["-D;", "-d", "-a", "L.reverse","-c","somedir"] -- "L.reverse" -- "somedir" exprSpec :: (Functor m, MonadIO m) => OptionParserT HawkOption m ExprSpec exprSpec = ExprSpec <$> (ContextSpec <$> contextDir) <*> expr where contextDir = do maybeDir <- consumeLast Option.ContextDirectory stringConsumer case maybeDir of Nothing -> liftIO findContextFromCurrDirOrDefault Just dir -> return dir expr = do r <- consumeExtra stringConsumer case r of Just e -> if all isSpace e then fail "user expression cannot be empty" else return e Nothing -> fail "missing user expression" -- | Parse command-line arguments to construct a `HawkSpec`. -- -- TODO: complain if some arguments are unused (except perhaps "-d" and "-D"). -- -- >>> :{ -- let test args = do { spec <- runUncertainIO $ parseArgs args -- ; case spec of -- Help -> putStrLn "Help" -- Version -> putStrLn "Version" -- Eval e o -> putStrLn "Eval" >> print (untypedExpr e) >> print (recordDelimiter (outputFormat o), fieldDelimiter (outputFormat o)) -- Apply e i o -> putStrLn "Apply" >> print (untypedExpr e, inputSource i) >> print (inputFormat i) >> print (recordDelimiter (outputFormat o), fieldDelimiter (outputFormat o)) -- Map e i o -> putStrLn "Map" >> print (untypedExpr e, inputSource i) >> print (inputFormat i) >> print (recordDelimiter (outputFormat o), fieldDelimiter (outputFormat o)) -- } -- :} -- -- >>> test [] -- Help -- -- >>> test ["--help"] -- Help -- -- >>> test ["--version"] -- Version -- -- >>> test ["-d\\t", "L.head"] -- Eval -- "L.head" -- ("\n","\t") -- -- >>> test ["-D\r\n", "-d\\t", "-m", "L.head"] -- Map -- ("L.head",UseStdin) -- Records (Delimiter "\r\n") (Fields (Delimiter "\t")) -- ("\r\n","\t") -- -- >>> test ["-D", "-O\n", "-m", "L.head", "file.in"] -- Map -- ("L.head",InputFile "file.in") -- RawStream -- ("\n"," ") parseArgs :: (Functor m,MonadIO m) => [String] -> UncertainT m HawkSpec parseArgs [] = return Help parseArgs args = runOptionParserT options parser args where parser = do lift $ return () -- silence a warning cmd <- fromMaybe eval <$> consumeExclusive assoc c <- commonProcessors cmd c assoc = [ (Option.Help, help) , (Option.Version, version) , (Option.Apply, apply) , (Option.Map, map') ] help, version, eval, apply, map' :: (Functor m,MonadIO m) => CommonProcessors -> OptionParserT HawkOption m HawkSpec help _ = return Help version _ = return Version eval c = Eval <$> exprSpec <*> outputSpec c apply c = Apply <$> exprSpec <*> inputSpec c <*> outputSpec c map' c = Map <$> exprSpec <*> inputSpec c <*> outputSpec c
gelisam/hawk
src/System/Console/Hawk/Args/Parse.hs
Haskell
apache-2.0
8,499
module Main where primes = filter prime [2..] where prime x = null [d | d <- [2..x-1], rem x d == 0] primes' = filterPrimes [2..] where filterPrimes (p:xs) = p : filterPrimes [x | x <- xs, rem x p /= 0]
frankiesardo/seven-languages-in-seven-weeks
src/main/haskell/day2/primes.hs
Haskell
apache-2.0
253
module Main where import qualified Language.P4 as P4 import CodeGen import Options.Applicative parseAndFixup :: FilePath -> String -> Either String P4.Program parseAndFixup fileName input = do ast <- P4.parseProgram fileName input P4.fixupSEMAs ast astDump :: FilePath -> IO () astDump file = do contents <- readFile file case parseAndFixup file contents of Left err -> print err Right ast -> print ast compile :: FilePath -> IO () compile file = do contents <- readFile file case parseAndFixup file contents of Left err -> print err Right ast -> writeFile "softswitch.c" (ppCgen ast) data Cmd = AstDump FilePath | Compile FilePath deriving (Show) cmd :: Parser Cmd cmd = subparser ( command "ast-dump" (info cmdAstDump (progDesc "Parse and dump AST.")) <> command "compile" (info cmdCompile (progDesc "Compile P4 program.")) ) cmdAstDump :: Parser Cmd cmdAstDump = AstDump <$> argument str (metavar "PROGRAM") cmdCompile :: Parser Cmd cmdCompile = Compile <$> argument str (metavar "PROGRAM") run :: Cmd -> IO () run (AstDump file) = astDump file run (Compile file) = compile file main :: IO () main = execParser opts >>= run where opts = info (cmd <**> helper) idm
brooksbp/P4
src/compiler/Main.hs
Haskell
apache-2.0
1,243
module Notification where import DBus.Notify import DBus.Client (connectSession) giveYourEeysABreak :: IO () giveYourEeysABreak = do client <- connectSession do let startNote = appNote { summary="Mike Says" , body=(Just $ Text "Give your eyes a break") } notification <- notify client startNote putStrLn "Done" where appNote = blankNote { appName="Mike" }
akalyaev/mike-on-linux
src/Notification.hs
Haskell
apache-2.0
408
{-# LANGUAGE TemplateHaskell, OverloadedStrings, TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.QcIntegrated where import Data.Integrated hiding (tests) import Test.QuickCheck import Test.QuickCheck.All import Test.QuickCheck.Monadic import Test.QuickCheck.Property.Comb import qualified Data.Property as P import qualified Data.Suite.Ops as O import Control.Lens hiding (lens, mapping) import Control.Applicative import Data.Integrated.Partition import Data.Integrated.TestModule import Control.Monad.State import Util.Invariants import Data.String.Builder import Data.ModulePath hiding (toPath) import Data.Path import Arbitrary.Properties import Arbitrary.TestModule (toGenerated) import Arbitrary.FS import qualified Data.Set as S import qualified Data.Map as M import qualified Filesystem.Path.CurrentOS as FS import qualified Data.List as L import Prelude hiding (FilePath) import System.Directory import Env main :: IO () main = void $quickCheckAll prop_toPartition :: Diff -> Property prop_toPartition diff = runInvariants (diff, toPartition diff) inv_toPartition where -- TODO/FIXME cleanup remove diff type inv_toPartition :: Invariants (Diff, Partition) inv_toPartition = do satcomp (\t -> (incoming . fst $ t, snd t)) $ eqCoverageInv "union of [equal, displacing, added] form improper subset of incoming" [equal, displacing, added] satcomp (fromPart . snd) disjointSetsInv satcomp (\t -> (fst t, added . snd $ t)) addedInv satcomp (\t -> (incoming . fst $ t, displacing . snd $ t)) displacingInv satcomp (\t -> (fst t, equal . snd $ t)) equalInv where fromPart p = toSets p [ ("equal", S.fromList . M.keys . equal), ("displacing", S.fromList . M.keys . displacing), ("added", S.fromList . M.keys . added) ] eqCoverageInv :: String -> [Partition -> Map] -> Invariants (Map, Partition) eqCoverageInv msg fs = sat $ do (s, p) <- cause doc $ msg ++ "\n\n" doc $ show p return $ (M.unions . map ($ p)) fs == s addedInv :: Invariants (Diff, Map) addedInv = sat $ do d <- fst <$> cause doc "added are the modulepath-set difference of incoming minus original" (==) (M.difference (incoming d) (original d)) . snd <$> cause -- TODO members of displacing either differ by property content, -- by file-path, or both displacingInv :: Invariants (Map, Map) displacingInv = sat $ do incoming_map <- fst <$> cause doc "displacing is a submap of incoming" (`M.isSubmapOf` incoming_map) . snd <$> cause equalInv :: Invariants (Diff, Map) equalInv = sat $ do (d, equal_map) <- cause doc "equal is a submap of original and incoming" doc $ "equal: " ++ show equal_map return $ (equal_map `M.isSubmapOf` incoming d) && (equal_map `M.isSubmapOf` original d) instance Arbitrary Diff where arbitrary = fromOriginal =<< fromMask M.empty =<< choose (0, 4) where -- | Produce a list of added sets, or sets that don't intersect on -- modulepath with any in the original set. fromMask :: Map -> Int -> Gen Map fromMask mask 0 = return mask fromMask mask n = do (p, satisfying_tm) <- maskSatisfying fromMask (M.insert (view modpath satisfying_tm) (p, view properties satisfying_tm) mask ) (n-1) where -- Note the suthThat predicate relies upon comparison of -- test module path, and this isn't very clear from -- appearances maskSatisfying :: Gen (FS.FilePath, TestModule) maskSatisfying = suchThat (toGenerated (choose ('a','z')) (M.keysSet mask)) -- =<< toModulePath (choose ('a', 'z'))) (\(_, tm) -> not . S.member (view modpath tm) $ M.keysSet mask) fromOriginal :: Map -> Gen Diff fromOriginal m = do intersecting <- choose (0, M.size m) equivalent <- choose (0, intersecting) changed <- choose (0, intersecting - equivalent) Diff m <$> toIncoming (M.toList m) equivalent changed where toIncoming :: [(ModulePath, (FS.FilePath, [P.Property]))] -> Int -> Int -> Gen Map toIncoming original_list equivalent changed = -- Partition the original into equivalent and changed and -- exclude the rest let equivalent_map = M.fromList . take equivalent $ original_list in do added_total <- choose (0,2) changed_map <- genChangedMap M.unions . (:[equivalent_map, changed_map]) <$> fromMask (equivalent_map `M.union` changed_map) added_total where genChangedMap = let subseq = take changed . drop equivalent $ original_list in do fs <- vectorOf (L.length subseq) mutation return . M.fromList $ zipWith (\f p -> over _2 f p) fs subseq -- Note, I could have used QuickCheck.Function here, but -- that is really overkill mutation :: Gen ((FS.FilePath, [P.Property]) -> (FS.FilePath, [P.Property])) mutation = oneof $ map return [over _1 pathMutation, over _2 propMutation] where pathMutation :: FS.FilePath -> FS.FilePath pathMutation p = FS.decodeString $ FS.encodeString "z/" ++ FS.encodeString p propMutation :: [P.Property] -> [P.Property] propMutation [] = [toProperty 0] propMutation (_:rest) = rest data Input_fromPartition = Input_fromPartition { masking :: Bool, original_map :: Map, partition :: Partition } deriving Show instance Arbitrary Input_fromPartition where arbitrary = do bool <- arbitrary :: Gen Bool diff <- suchThat (arbitrary :: Gen Diff) (not . M.null . original) return $ Input_fromPartition bool (original diff) (toPartition diff) -- TODO/FIXME cleanup/remove input type prop_fromPartition :: Input_fromPartition -> Property prop_fromPartition input = let result = runState (fromPartition (masking input) (partition input)) (original_map input) in runInvariants (result, input) inv_fromPartition where -- Note by precondition, -- all invariants on the Partition are held (disjoint, relations with -- imported etc). inv_fromPartition :: Invariants ((O.Ops, Map), Input_fromPartition) inv_fromPartition = do ops_invariants satcomp (\((_, ss), i) -> (ss,i)) suite_invariants where ops_invariants :: Invariants ((O.Ops, Map), Input_fromPartition) ops_invariants = let fromOpsLens lens t = set (_1 . _1) (view (_1 . _1 . lens) t) t addedRelations t = ((view (_1 . _1 . O.added) t, view (_1 . _2) t), partition . snd $ t ) removedRelations t = ((view (_1 . _1 . O.removed) t, view (_1 . _2) t), snd t) in do satcomp (toLabelled . fst . fst) disjointSetsInv satcomp addedRelations ops_added satcomp removedRelations ops_removed satcomp (fromOpsLens O.modified) ops_modified satcomp (fromOpsLens O.unmodified) ops_unmodified ops_added :: Invariants ((Map, Map), Partition) ops_added = do satcomp (\t -> (fst . fst $ t, added . snd $ t)) . sat $ do doc "added is equivalent to added in partition" uncurry (==) <$> cause satcomp fst . sat $ do doc "added is a submap of the suite mapping" uncurry M.isSubmapOf <$> cause toLabelled :: O.Ops -> [LabelledSet ModulePath] toLabelled ops = toSets ops [ ("added", S.fromList . M.keys . O._added) ,("removed", S.fromList . M.keys . O._removed) ,("modified", S.fromList . M.keys . O._modified) ,("unmodified", S.fromList . M.keys . O._unmodified) ] ops_removed :: Invariants ((Map, Map), Input_fromPartition) ops_removed = do sat $ do doc "removed is a subset of the original suite set" ((removed_map, _), i) <- cause return $ M.isSubmapOf removed_map (original_map i) satcomp fst . sat $ do doc "non-empty removed is not a subset of the final suite set" (removed_map, final_suite_map) <- cause return . (if M.null removed_map then id else not) $ M.isSubmapOf removed_map final_suite_map sat $ do ((removed_map, _), i) <- cause if masking i then do doc . build $ do "masking => removed is the difference: " " original - (equal of partition U displaced) " return $ (==) removed_map (M.difference (original_map i) (displaced `M.union` (equal . partition $ i)) ) else do doc "not masking => removed empty" return . M.null $ removed_map where displaced = M.intersection (original_map input) (displacing . partition $ input) ops_modified :: Invariants ((Map, Map), Input_fromPartition) ops_modified = do sat $ do doc "modified is a submap of original" ((modified_map, _), i) <- cause return $ M.isSubmapOf modified_map (original_map i) sat $ do doc . build $ do "modified is domain-equivalent to displacing of partition," "and for every equal relation (d1,d2) in a domain pairing," "s.t d1 -> v1 and d2 -> v2, v1 neq v2" ((modified_map, _), i) <- cause let displacing_map = displacing . partition $ i domain_eq = M.null $ M.difference modified_map displacing_map return . (&&) domain_eq . and . zipWith (/=) (M.elems modified_map) $ M.elems displacing_map ops_unmodified :: Invariants ((Map, Map), Input_fromPartition) ops_unmodified = do sat $ do doc "unmodified is a submap of original" ((unmodified_map, _), i) <- cause return $ M.isSubmapOf unmodified_map (original_map i) sat $ do ((unmodified_map, _), i) <- cause if masking i then do doc "masking => unmodified is only the equal set" return $ unmodified_map == (equal . partition $ i) else do doc "not masking => original - displaced-mapped of partition" return $ unmodified_map == M.difference (original_map i) ( M.intersection (original_map i) (displacing . partition $ i) ) suite_invariants :: Invariants (Map, Input_fromPartition) suite_invariants = sat $ do (final_suite, _) <- cause if masking input then do doc "the final suite is (equal U added U displacing)" return $ final_suite == minimum_expected else do doc . build $ do "the final suite is latent U (equal U added U displacing)" " where latent = original_set - displaced" " where displaced = domain mapped via displacing" return $ final_suite == M.union latent minimum_expected where latent = M.difference (original_map input) displaced displaced = M.intersection (original_map input) (displacing . partition $ input) minimum_expected = M.unions $ map ($ partition input) [equal, displacing, added] test_isomorphism :: Invariants (Tests, Tests) test_isomorphism = sat $ do doc "parsed tests are equal to those on filesystem" (written, parsed) <- cause if parsed /= written then do doc (msg parsed written) doc $ "\n written tests: \n" ++ (show . M.toList $ written) doc $ "\n parsed tests: \n" ++ (show . M.toList $ parsed) return False else return True where msg parsed written = if M.size parsed > M.size written then fromDifference "\n excessive parsed:\n " parsed written else fromDifference "\n unparsed:\n " written parsed fromDifference des l r = des ++ (show . M.toList $ M.difference l r) errors_isomorphism :: Invariants (Errors, Errors) errors_isomorphism = sat $ do doc "parsed errors are equal to those on filesystem" (written, parsed) <- cause if parsed /= written then do doc (msg parsed written) doc $ "\n written: \n" ++ (show . S.toList $ written) doc $ "\n parsed: \n" ++ (show . S.toList $ parsed) return False else return True where msg parsed written = if S.size parsed > S.size written then fromDifference "\n excessive parsed:\n " parsed written else fromDifference "\n unparsed:\n " written parsed fromDifference des l r = des ++ (show . S.toList $ S.difference l r) type Tests = M.Map ModulePath [String] type Errors = S.Set FS.FilePath -- FS is a Set of file-path(s), so it is sufficient to check for -- isomorphisms on the two path-disjoint sets forming its union, -- test files and non-sense files fromTestpathInv :: FS.FilePath -> Invariants (FS, (Map, [Error])) fromTestpathInv sandbox = do satcomp (uncurry to_test_isomorphism) test_isomorphism satcomp (uncurry to_errors_isomorphism) errors_isomorphism where to_test_isomorphism :: FS -> (Map, [Error]) -> (Tests, Tests) to_test_isomorphism fs (parsed_tests, _) = (,) (M.fromList . L.map (\tm -> (view modpath tm, map P.func $ view properties tm)) . M.elems . fst . M.mapEither id $ mapping fs) -- Written (M.map (map P.func . snd) parsed_tests) to_errors_isomorphism :: FS -> (Map, [Error]) -> (Errors, Errors) to_errors_isomorphism fs (_, parsed_errors) = (,) (S.map (FS.append sandbox) . M.keysSet . snd . M.mapEither id $ mapping fs) -- Given (S.fromList . map filepath $ parsed_errors) -- parsed -- FIXME/TODO still need to populate the directory with tests env :: String -> FS -> Env FS.FilePath env sandbox fs = Env { setup = do -- TODO add deleted state after completed createDirectory sandbox writeFS decoded_path fs return decoded_path , teardown = do removeDirectoryRecursive sandbox return () } where decoded_path = FS.decodeString sandbox filterIndicatives :: FS -> FS filterIndicatives = FS . M.filterWithKey (\k _ -> legalModSubpath . FS.encodeString $ k) . mapping prop_fromTestpath_isomorphism :: FS -> Property prop_fromTestpath_isomorphism fs = let sandbox = "./tmp/" in monadicIO $ do isomorphic <- run $ runEnv (env sandbox fs) toIsomorphic stop $ runInvariants (filterIndicatives fs, isomorphic) (fromTestpathInv $ FS.decodeString sandbox) where toIsomorphic :: FS.FilePath -> IO (Map, [Error]) toIsomorphic fp = do path <- toPath $ FS.encodeString fp runStateT (fromTestpath path) []
jfeltz/tasty-integrate
tests/Data/QcIntegrated.hs
Haskell
bsd-2-clause
16,375
{-# LANGUAGE OverloadedStrings, GADTs #-} module View.Class where import Control.Applicative import Data.Monoid import Data.String import Model.Class import Model.Home import Model.Page import Web.Thermopolis.Clause import Types import View.Page import Web.Thermopolis.PageIdentity classPageClause :: (PageIdentity p f, p ~ Path, ContentReader f) => Page ClassContent -> f Clause classPageClause page = pageClause $ (\ ClassContent -> "... HA! HA HA...") <$> page
andygill/thermopolis
src/View/Class.hs
Haskell
bsd-2-clause
572
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGL.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Opengl.QGL ( FormatOption, FormatOptions, eDoubleBuffer, fDoubleBuffer, eDepthBuffer, fDepthBuffer, eRgba, fRgba, eAlphaChannel, fAlphaChannel, eAccumBuffer, fAccumBuffer, eStencilBuffer, fStencilBuffer, eStereoBuffers, fStereoBuffers, eDirectRendering, fDirectRendering, eHasOverlay, fHasOverlay, eSampleBuffers, fSampleBuffers, eSingleBuffer, fSingleBuffer, eNoDepthBuffer, fNoDepthBuffer, eColorIndex, fColorIndex, eNoAlphaChannel, fNoAlphaChannel, eNoAccumBuffer, fNoAccumBuffer, eNoStencilBuffer, fNoStencilBuffer, eNoStereoBuffers, fNoStereoBuffers, eIndirectRendering, fIndirectRendering, eNoOverlay, fNoOverlay, eNoSampleBuffers, fNoSampleBuffers ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CFormatOption a = CFormatOption a type FormatOption = QEnum(CFormatOption Int) ieFormatOption :: Int -> FormatOption ieFormatOption x = QEnum (CFormatOption x) instance QEnumC (CFormatOption Int) where qEnum_toInt (QEnum (CFormatOption x)) = x qEnum_fromInt x = QEnum (CFormatOption x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> FormatOption -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () data CFormatOptions a = CFormatOptions a type FormatOptions = QFlags(CFormatOptions Int) ifFormatOptions :: Int -> FormatOptions ifFormatOptions x = QFlags (CFormatOptions x) instance QFlagsC (CFormatOptions Int) where qFlags_toInt (QFlags (CFormatOptions x)) = x qFlags_fromInt x = QFlags (CFormatOptions x) withQFlagsResult x = do ti <- x return $ qFlags_fromInt $ fromIntegral ti withQFlagsListResult x = do til <- x return $ map qFlags_fromInt til instance Qcs (QObject c -> FormatOptions -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qFlags_fromInt hint) return () eDoubleBuffer :: FormatOption eDoubleBuffer = ieFormatOption $ 1 eDepthBuffer :: FormatOption eDepthBuffer = ieFormatOption $ 2 eRgba :: FormatOption eRgba = ieFormatOption $ 4 eAlphaChannel :: FormatOption eAlphaChannel = ieFormatOption $ 8 eAccumBuffer :: FormatOption eAccumBuffer = ieFormatOption $ 16 eStencilBuffer :: FormatOption eStencilBuffer = ieFormatOption $ 32 eStereoBuffers :: FormatOption eStereoBuffers = ieFormatOption $ 64 eDirectRendering :: FormatOption eDirectRendering = ieFormatOption $ 128 eHasOverlay :: FormatOption eHasOverlay = ieFormatOption $ 256 eSampleBuffers :: FormatOption eSampleBuffers = ieFormatOption $ 512 eSingleBuffer :: FormatOption eSingleBuffer = ieFormatOption $ 65536 eNoDepthBuffer :: FormatOption eNoDepthBuffer = ieFormatOption $ 131072 eColorIndex :: FormatOption eColorIndex = ieFormatOption $ 262144 eNoAlphaChannel :: FormatOption eNoAlphaChannel = ieFormatOption $ 524288 eNoAccumBuffer :: FormatOption eNoAccumBuffer = ieFormatOption $ 1048576 eNoStencilBuffer :: FormatOption eNoStencilBuffer = ieFormatOption $ 2097152 eNoStereoBuffers :: FormatOption eNoStereoBuffers = ieFormatOption $ 4194304 eIndirectRendering :: FormatOption eIndirectRendering = ieFormatOption $ 8388608 eNoOverlay :: FormatOption eNoOverlay = ieFormatOption $ 16777216 eNoSampleBuffers :: FormatOption eNoSampleBuffers = ieFormatOption $ 33554432 fDoubleBuffer :: FormatOptions fDoubleBuffer = ifFormatOptions $ 1 fDepthBuffer :: FormatOptions fDepthBuffer = ifFormatOptions $ 2 fRgba :: FormatOptions fRgba = ifFormatOptions $ 4 fAlphaChannel :: FormatOptions fAlphaChannel = ifFormatOptions $ 8 fAccumBuffer :: FormatOptions fAccumBuffer = ifFormatOptions $ 16 fStencilBuffer :: FormatOptions fStencilBuffer = ifFormatOptions $ 32 fStereoBuffers :: FormatOptions fStereoBuffers = ifFormatOptions $ 64 fDirectRendering :: FormatOptions fDirectRendering = ifFormatOptions $ 128 fHasOverlay :: FormatOptions fHasOverlay = ifFormatOptions $ 256 fSampleBuffers :: FormatOptions fSampleBuffers = ifFormatOptions $ 512 fSingleBuffer :: FormatOptions fSingleBuffer = ifFormatOptions $ 65536 fNoDepthBuffer :: FormatOptions fNoDepthBuffer = ifFormatOptions $ 131072 fColorIndex :: FormatOptions fColorIndex = ifFormatOptions $ 262144 fNoAlphaChannel :: FormatOptions fNoAlphaChannel = ifFormatOptions $ 524288 fNoAccumBuffer :: FormatOptions fNoAccumBuffer = ifFormatOptions $ 1048576 fNoStencilBuffer :: FormatOptions fNoStencilBuffer = ifFormatOptions $ 2097152 fNoStereoBuffers :: FormatOptions fNoStereoBuffers = ifFormatOptions $ 4194304 fIndirectRendering :: FormatOptions fIndirectRendering = ifFormatOptions $ 8388608 fNoOverlay :: FormatOptions fNoOverlay = ifFormatOptions $ 16777216 fNoSampleBuffers :: FormatOptions fNoSampleBuffers = ifFormatOptions $ 33554432
uduki/hsQt
Qtc/Enums/Opengl/QGL.hs
Haskell
bsd-2-clause
7,292
{-#LANGUAGE DeriveGeneric #-} {-| Module : Name Description : Yaml parsing Copyright : License : GPL-2 Maintainer : theNerd247 Stability : experimental Portability : POSIX -} module Data.Serialization.Yaml ( readYamlFile ,writeYamlFile ) where import YabCommon import Data.Budget import Data.Serialization.Errors import qualified Data.Yaml as YAML import qualified Data.Aeson.Types as DAT data BadYAMLReadException = BadYAMLReadException FilePath deriving (Generic,Typeable,Read,Eq,Ord) instance Show BadYAMLReadException where show (BadYAMLReadException fpath) = show $ "Could not read YAML data from: " ++ fpath instance Exception BadYAMLReadException -- | Reads data from a yaml file. If no data could be read or an error occurs then the system exits. readYamlFile :: (YAML.FromJSON a, MonadIO m, MonadCatch m) => FilePath -> m a readYamlFile fpath = do r <- liftIO $ YAML.decodeFile fpath maybe (throwM $ BadYAMLReadException fpath) return $ r `catchAll` printEAndExit -- | write data to a yaml file. If an error occurs then the system exits writeYamlFile :: (YAML.ToJSON a, MonadIO m, MonadCatch m) => FilePath -> a -> m () writeYamlFile f = handleAll printEAndExit . liftIO . YAML.encodeFile f -- | TODO: add a way to support percentages of the income in the yaml files instance YAML.FromJSON Budget -- TODO: fix this quick hack as per issue #290 on github.com/bos/aeson instance YAML.ToJSON Budget instance YAML.ToJSON Account where toJSON = YAML.toJSON . accountAmount instance YAML.FromJSON Account where parseJSON v = do a <- YAML.parseJSON v return $ Account {accountAmount = a, accountEntries = []}
theNerd247/yab
src/Data/Serialization/Yaml.hs
Haskell
bsd-3-clause
1,674
{-#LANGUAGE RankNTypes, CPP, Trustworthy #-} module Streaming ( -- * An iterable streaming monad transformer -- $stream Stream, -- * Constructing a 'Stream' on a given functor yields, effect, wrap, replicates, repeats, repeatsM, unfold, never, untilJust, streamBuild, delays, -- * Transforming streams maps, mapsM, mapped, distribute, groups, -- * Inspecting a stream inspect, -- * Splitting and joining 'Stream's splitsAt, takes, chunksOf, concats, intercalates, cutoff, -- period, -- periods, -- * Zipping, unzipping, separating and unseparating streams zipsWith, zips, unzips, interleaves, separate, unseparate, decompose, -- * Eliminating a 'Stream' mapsM_, run, streamFold, iterTM, iterT, destroy, -- * Base functor for streams of individual items Of (..), lazily, strictly, -- * ResourceT help bracketStream, -- * re-exports MFunctor(..), MMonad(..), MonadTrans(..), MonadIO(..), Compose(..), Sum(..), Identity(..), Alternative((<|>)), MonadThrow(..), MonadResource(..), MonadBase(..), ResourceT(..), runResourceT, #if MIN_VERSION_base(4,8,0) Bifunctor(..), #endif join, liftM, liftM2, liftA2, liftA3, void, (<>) ) where import Streaming.Internal import Streaming.Prelude import Control.Monad.Morph import Control.Monad import Data.Monoid ((<>)) import Control.Applicative import Control.Monad.Trans import Data.Functor.Compose import Data.Functor.Sum import Data.Functor.Identity import Data.Functor.Of import Control.Monad.Base import Control.Monad.Trans.Resource #if MIN_VERSION_base(4,8,0) import Data.Bifunctor #endif {- $stream The 'Stream' data type can be used to represent any effectful succession of steps arising in some monad. The form of the steps is specified by the first (\"functor\") parameter in @Stream f m r@. The monad of the underlying effects is expressed by the second parameter. This module exports combinators that pertain to that general case. Some of these are quite abstract and pervade any use of the library, e.g. > maps :: (forall x . f x -> g x) -> Stream f m r -> Stream g m r > mapped :: (forall x . f x -> m (g x)) -> Stream f m r -> Stream g m r > hoist :: (forall x . m x -> n x) -> Stream f m r -> Stream f n r -- from the MFunctor instance > concats :: Stream (Stream f m) m r -> Stream f m r (assuming here and thoughout that @m@ or @n@ satisfies a @Monad@ constraint, and @f@ or @g@ a @Functor@ constraint.) Others are surprisingly determinate in content: > chunksOf :: Int -> Stream f m r -> Stream (Stream f m) m r > splitsAt :: Int -> Stream f m r -> Stream f m (Stream f m r) > zipsWith :: (forall x y. f x -> g y -> h (x, y)) -> Stream f m r -> Stream g m r -> Stream h m r > intercalates :: Stream f m () -> Stream (Stream f m) m r -> Stream f m r > unzips :: Stream (Compose f g) m r -> Stream f (Stream g m) r > separate :: Stream (Sum f g) m r -> Stream f (Stream g) m r -- cp. partitionEithers > unseparate :: Stream f (Stream g) m r -> Stream (Sum f g) m r > groups :: Stream (Sum f g) m r -> Stream (Sum (Stream f m) (Stream g m)) m r One way to see that /any/ streaming library needs some such general type is that it is required to represent the segmentation of a stream, and to express the equivalents of @Prelude/Data.List@ combinators that involve 'lists of lists' and the like. See for example this <http://www.haskellforall.com/2013/09/perfect-streaming-using-pipes-bytestring.html post> on the correct expression of a streaming \'lines\' function. The module @Streaming.Prelude@ exports combinators relating to > Stream (Of a) m r where @Of a r = !a :> r@ is a left-strict pair. This expresses the concept of a 'Producer' or 'Source' or 'Generator' and easily inter-operates with types with such names in e.g. 'conduit', 'iostreams' and 'pipes'. -} {-| Map a stream to its church encoding; compare @Data.List.foldr@ This is the @safe_destroy@ exported by the @Internal@ module. Typical @FreeT@ operators can be defined in terms of @destroy@ e.g. > iterT :: (Functor f, Monad m) => (f (m a) -> m a) -> Stream f m a -> m a > iterT out stream = destroy stream out join return > iterTM :: (Functor f, Monad m, MonadTrans t, Monad (t m)) => (f (t m a) -> t m a) -> Stream f m a -> t m a > iterTM out stream = destroy stream out (join . lift) return > concats :: (Monad m, MonadTrans t, Monad (t m)) => Stream (t m) m a -> t m a > concats stream = destroy stream join (join . lift) return -}
michaelt/streaming
src/Streaming.hs
Haskell
bsd-3-clause
4,789
import Control.Applicative boop = (*2) doop = (+10) -- function composition bip :: Integer -> Integer bip = boop . doop -- context is Functor bloop :: Integer -> Integer bloop = fmap boop doop -- context is Applicative bbop :: Integer -> Integer bbop = (+) <$> boop <*> doop duwop :: Integer -> Integer duwop = liftA2 (+) boop doop -- context is Monad boopDoop :: Integer -> Integer boopDoop = do a <- boop b <- doop return (a + b)
chengzh2008/hpffp
src/ch22-Reader/start.hs
Haskell
bsd-3-clause
444
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances #-} module Language.Mojito.Syntax.Types where import Prelude hiding ((<>)) import Data.List (intersperse) import Text.PrettyPrint.HughesPJClass -- Simple Types -- t = C t1 .. tn | a t1 .. tn data Simple = TyCon String | TyVar String | TyApp Simple Simple -- Or Simple [Simple], which would give an arity ? deriving (Show, Eq) instance Pretty Simple where pPrint (TyCon c) = text c pPrint (TyVar v) = text v pPrint (TyApp t1 t2) = text "(" <> pPrint t1 <+> pPrint t2 <> text ")" showSimple :: Simple -> String showSimple (TyCon a) = a showSimple (TyVar a) = a showSimple (TyApp t1 t2) = "(" ++ showSimple t1 ++ " " ++ showSimple t2 ++ ")" tc :: Simple -> [String] -- TODO nub the result, or use union instead of ++ -- tc is also Substitution.vars tc (TyCon s) = [s] tc (TyVar _) = [] tc (TyApp t1 t2) = tc t1 ++ tc t2 -- Occur check: tests if a type variable appears in a given -- type. occurs :: String -> Simple -> Bool occurs a (TyVar b) = a == b occurs _ (TyCon _) = False occurs a (TyApp t1 t2) = occurs a t1 || occurs a t2 -- Is it faster ? -- Occur check: tests if a type variable appears in a given -- type. -- occurs :: String -> Simple -> Bool -- occurs a t = a `elem` tv t tc' :: [Simple] -> [String] tc' = concatMap tc args :: Simple -> [Simple] args (TyCon _) = [] args (TyVar _) = [] args (TyApp t1 t2) = args t1 ++ [t2] nargs :: Simple -> Int nargs = length . args -- t == let (c,as) = cargs t -- in foldl TyApp c as cargs :: Simple -> (Simple,[Simple]) cargs t = cargs' t [] cargs' :: Simple -> [Simple] -> (Simple,[Simple]) cargs' t as = case t of TyCon _ -> (t,as) TyVar _ -> (t,as) TyApp t1 t2 -> cargs' t1 (t2 : as) -- fargs (-> a b c) = [a,b,c] fargs :: Simple -> [Simple] fargs (TyCon "->" `TyApp` a `TyApp` b) = a : fargs b fargs t = [t] -- Constrained types -- d = {oi : ti}.t data Constrained = Constrained [Constraint] Simple deriving (Show, Eq) showConstrained :: Constrained -> String showConstrained (Constrained [] t) = showSimple t showConstrained (Constrained cs t) = showConstraints cs ++ "." ++ showSimple t -- Constraint {o : t} where o is a term variable. data Constraint = Constraint String Simple deriving (Show, Eq) showConstraint :: Constraint -> String showConstraint (Constraint o t) = o ++ " : " ++ showSimple t showConstraints :: [Constraint] -> String showConstraints cs = "{" ++ concat (intersperse ", " $ map showConstraint cs) ++ "}" -- Quantified type. -- s = forall ai . d data Type = Type [String] Constrained deriving (Show, Eq) showType :: Type -> String showType (Type [] c) = showConstrained c showType (Type as c) = "forall " ++ concat (intersperse ", " as) ++ " . " ++ showConstrained c simple :: Type -> Simple simple (Type _ (Constrained _ t)) = t smpl :: Constrained -> Simple smpl (Constrained _ t) = t cstr :: Constrained -> [Constraint] cstr (Constrained c _) = c typed :: Simple -> Type typed t = Type [] $ Constrained [] t isSimple :: Type -> Bool isSimple (Type [] (Constrained [] _)) = True isSimple _ = False
noteed/mojito
Language/Mojito/Syntax/Types.hs
Haskell
bsd-3-clause
3,139
{-# LANGUAGE OverloadedStrings #-} module RegexPattern where import Data.Text import Types -- ideally use regular expressions to create an item -- input: priority:description:MM/DD/YYYY regexPattern :: String regexPattern = "[0-9]+(:)[A-Za-z0-9 .!\"#$%()]+(:)[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}" -- Used to read Items from file/stdin -- DOES NO PATTERN CHECKING - Left to regex. -- Assumes input is of proper format patternToItem :: String -> Item patternToItem itemString = Item (read p :: Int) desc date where list = Prelude.map unpack $ splitOn ":" (pack itemString) p = list !! 0 desc = list !! 1 date = list !! 2 -- Used to write Items to a file. itemToPattern :: Item -> String itemToPattern (Item p desc date) = (show p) ++ ":" ++ desc ++ ":" ++ date
frankhucek/Todo
app/RegexPattern.hs
Haskell
bsd-3-clause
790
module Data.Params.ModInt where import Data.Params ------------------------------------------------------------------------------- -- general data family ModIntegral (modulus :: Param Nat) i type ModInt modulus = ModIntegral modulus Int type ModInteger modulus = ModIntegral modulus Integer ------------------------------------------------------------------------------- -- Static newtype instance ModIntegral (Static n) i = ModIntegral_Static i deriving (Read,Show,Eq,Ord) instance (KnownNat n, Integral i) => Num (ModIntegral (Static n) i) where (ModIntegral_Static a)+(ModIntegral_Static b) = ModIntegral_Static $ (a+b) `mod` n where n = fromIntegral $ natVal (Proxy::Proxy n) (ModIntegral_Static a)*(ModIntegral_Static b) = ModIntegral_Static $ (a*b) `mod` n where n = fromIntegral $ natVal (Proxy::Proxy n) abs = id signum = id fromInteger a = ModIntegral_Static $ (fromIntegral $ a `mod` n) where n = fromIntegral $ natVal (Proxy::Proxy n) negate (ModIntegral_Static a) = ModIntegral_Static $ (a-n) `mod` n where n = fromIntegral $ natVal (Proxy::Proxy n) ------------------------------------------------------------------------------- -- RunTime newtype instance ModIntegral RunTime i = ModIntegral_RunTime i deriving (Read,Show,Eq,Ord) mkParams ''ModIntegral instance ( Param_modulus (ModIntegral RunTime i) , Integral i ) => Num (ModIntegral RunTime i) where (ModIntegral_RunTime a)+(ModIntegral_RunTime b) = ModIntegral_RunTime $ (a+b) `mod` n where n = fromIntegral $ param_modulus (undefined:: (ModIntegral RunTime i)) (ModIntegral_RunTime a)*(ModIntegral_RunTime b) = ModIntegral_RunTime $ (a*b) `mod` n where n = fromIntegral $ param_modulus (undefined:: (ModIntegral RunTime i)) abs = id signum = id fromInteger a = ModIntegral_RunTime $ (fromIntegral $ a `mod` n) where n = fromIntegral $ param_modulus (undefined:: (ModIntegral RunTime i)) negate (ModIntegral_RunTime a) = ModIntegral_RunTime $ a-n `mod` n where n = fromIntegral $ param_modulus (undefined:: (ModIntegral RunTime i))
mikeizbicki/typeparams
src/Data/Params/ModInt.hs
Haskell
bsd-3-clause
2,196
{-# LANGUAGE RecordWildCards #-} module Network.RMV.Post (sendRequest) where import Network.RMV.Types import Network.RMV.Output import Data.Char import Data.List import Data.Maybe import Network.Browser import Network.HTTP import Network.URI import System.Time rmvURI = URI { uriScheme = "http:" , uriAuthority = Just URIAuth { uriUserInfo = "" , uriRegName = "www.rmv.de" , uriPort = ":80" } , uriPath = "/auskunft/bin/jp/query.exe/dn" , uriQuery = "?L=vs_rmv&" , uriFragment = "" } reqBody :: Options -> IO String reqBody opts = do time <- getClockTime >>= toCalendarTime let curDate = intercalate "." . map (pad . show . ($time)) $ [ ctDay, (+1) . fromEnum . ctMonth, ctYear] curTime = ppTime (ctHour time * 60 + ctMin time) pad xs = replicate (2 - length xs) '0' ++ xs return $ intercalate "&" [ "queryPageDisplayed=yes" , "REQ0JourneyStopsN=-1" , "REQ0HafasNumCons1=1" , "REQ0HafasNumCons0=4" , "REQ0JourneyStopsS0A=255" , "REQ0JourneyStopsS0G=" ++ urlEncode (opStartPoint opts) , "REQ0JourneyStopsS0ID=" , "REQ0JourneyStopsZ0A=255" , "REQ0JourneyStopsZ0G=" ++ urlEncode (opEndPoint opts) , "REQ0JourneyStopsZ0ID=" , "existUnsharpSearch=yes" , "iER=no" , "REQ0HafasOptimize1=1" , "REQ0JourneyDate=" ++ urlEncode (fromMaybe curDate $ opDate opts) , "wDayExt0=Mo%7CDi%7CMi%7CDo%7CFr%7CSa%7CSo" , "REQ0JourneyTime=" ++ urlEncode (fromMaybe curTime $ opTime opts) , "REQ0HafasSearchForw=1" , "REQ0JourneyProductMask=1%3A11111111111111111" , "start=Verbindungen+suchen" ] userAgentMimicIE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)" expandAliases :: Options -> Options expandAliases opts@(Options{..}) = opts { opStartPoint = expand opStartPoint , opEndPoint = expand opEndPoint } where expand s = maybe s snd $ find ((~=s) . fst) aliases a ~= b = map toLower a == map toLower b -- | Sends a request with the specified options sendRequest :: Options -> IO String sendRequest opts = do req <- reqBody $ expandAliases opts rsp <- Network.Browser.browse $ do setAllowRedirects True setOutHandler $ const (return ()) request Request { rqURI = rmvURI , rqMethod = POST , rqHeaders = [ Header HdrContentLength $ show (length req) , Header HdrUserAgent userAgentMimicIE ] , rqBody = req } return . rspBody . snd $ rsp testOpts = defaultOptions { opStartPoint = "kopernikusplatz" , opEndPoint = "darmstadt, schloß" , opCount = Just 3 }
dschoepe/rmv-query
Network/RMV/Post.hs
Haskell
bsd-3-clause
3,094
module Part1.Problem3 where -- -- The prime factors of 13195 are 5, 7, 13 and 29. -- -- What is the largest prime factor of the number 600851475143 ? -- https://stackoverflow.com/a/27464965/248948 squareRoot :: Integral t => t -> t squareRoot n | n > 0 = babylon n | n == 0 = 0 | n < 0 = error "Negative input" where babylon a | a > b = babylon b | otherwise = a where b = quot (a + quot n a) 2 primeSieve :: Int -> [Int] primeSieve n = filter (`notElem` sieve) [2..n] where sieve = [ i*i + j*i | i <- [2..squareRoot n] , j <- [0..((n - i*i) `div` i)] ] altPrimeSieve :: Integral t => t -> [t] altPrimeSieve n = filter isPrime [2..n] where isPrime p = all (\x -> p `mod` x /= 0) [2..(squareRoot p)] ceilSquareRoot :: Int -> Int ceilSquareRoot n = if s2 < n then s + 1 else s where s = squareRoot n s2 = s * s isSquare :: Int -> Bool isSquare n = s * s == n where s = squareRoot n fermatFactor :: Int -> Int fermatFactor n = factor' b2 a where a = ceilSquareRoot n b2 = a * a - n factor' b2 a = if not (isSquare b2) then let a' = a + 1 b2' = (a' * a') + n in factor' b2' a' else a - squareRoot b2 -- def trial_division(n): -- """Return a list of the prime factors for a natural number.""" -- if n < 2: -- return [] -- prime_factors = [] -- for p in prime_sieve(int(n**0.5)): -- if p*p > n: break -- while n % p == 0: -- prime_factors.append(p) -- n //= p -- if n > 1: -- prime_factors.append(n) -- return prime_factors trialDivision :: Integral t => t -> [t] trialDivision n | n < 2 = [] trialDivision n = trialDivision' n primes where primes = altPrimeSieve (squareRoot n) trialDivision' n [] | n > 1 = [n] | otherwise = [] trialDivision' n (p:ps) | p*p > n = trialDivision' n [] | otherwise = case factor n p of (x:xs) -> xs ++ trialDivision' x ps factor :: Integral t => t -> t -> [t] factor x p = if x `mod` p == 0 then factor (x `div` p) p ++ [p] else [x] largestPrimeFactor :: Int -> Int largestPrimeFactor p = maximum $ trialDivision p problem3 :: Int problem3 = largestPrimeFactor 600851475143
c0deaddict/project-euler
src/Part1/Problem3.hs
Haskell
bsd-3-clause
2,277
{-#LANGUAGE ScopedTypeVariables, TypeOperators, FlexibleContexts #-} module Main where import Bindings.DC1394.Camera import Bindings.DC1394.Types import Canny import System.Environment import qualified Data.Array.Accelerate as A import Data.Array.Accelerate hiding (fromIntegral,fst,(++)) import qualified Data.Array.Accelerate.CUDA as CUDA import qualified Data.Array.Accelerate.IO as A import qualified Data.Array.Accelerate.IO.Firewire as A import Data.Array.Accelerate.Interpreter import qualified Data.Array.Repa as Repa import qualified Data.Array.Repa.IO.BMP as Repa import Data.Enumerator (run_) import Data.Maybe main :: IO () main = do numFrames <- (read . head) <$> getArgs withFirewireCamera ISO_400 Mode_640x480_RGB8 Rate_30 4 defaultFlags $ \camera -> do -- computation on one frame Right frame <- A.getFrame camera 640 480 let rgbaImg = (A.map A.packRGBA32 . A.flatten3dTo2d 480 640 . use) frame computation = (A.map A.rgba32OfLuminance .fst . canny 0.3 0.5) rgbaImg newImg = CUDA.run computation A.writeImageToBMP "out_accel.bmp" newImg -- computation on frame sequence let computation :: A.RGBImageDIM3 -> Acc (Array DIM2 A.RGBA32) computation = A.map A.rgba32OfLuminance -- convert graycale to RGB image . fst -- get the resulting grayscale image . canny 0.7 0.9 -- compute Canny edge detection . A.map A.packRGBA32 -- convert to 2D RGB (R,G,B) triple . A.flipV -- flip it in preparation for BMP file output . A.flatten3dTo2d 480 640 -- flatten 3D (Word8) image to 2D (Word8,Word8,Word8) image . use -- makes frame available for processing run_ $ A.withFrames camera 640 480 numFrames $ \frame frameCount -> do A.writeImageToBMP (show frameCount ++ "_out.bmp") (CUDA.run (computation frame)) -- run on the GPU
robstewart57/firewire-image-io
examples/accelerate.hs
Haskell
bsd-3-clause
2,075
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module TestCodecovHaskellUtil where import Test.HUnit import Trace.Hpc.Codecov.Util testMapFirst = "mapFirst" ~: [ mapFirst (+ 1) [] @?= [], mapFirst (+ 1) [2] @?= [3], mapFirst (+ 1) [2, 3] @?= [3, 3], mapFirst (+ 1) [2, 3, 5] @?= [3, 3, 5]] testMapLast = "mapLast" ~: [ mapLast (+ 1) [] @?= [], mapLast (+ 1) [2] @?= [3], mapLast (+ 1) [2, 3] @?= [2, 4], mapLast (+ 1) [2, 3, 5] @?= [2, 3, 6]] testSubSeq = "subSeq" ~: [ subSeq 0 0 [] @?= ([] :: [Int]), subSeq 0 0 [2] @?= [], subSeq 0 1 [2] @?= [2], subSeq 0 2 [2] @?= [2], subSeq 1 1 [2] @?= [], subSeq 1 2 [2] @?= [], subSeq 0 0 [2, 3] @?= [], subSeq 0 1 [2, 3] @?= [2], subSeq 0 2 [2, 3] @?= [2, 3], subSeq 0 3 [2, 3] @?= [2, 3], subSeq 1 1 [2, 3] @?= [], subSeq 1 2 [2, 3] @?= [3], subSeq 1 3 [2, 3] @?= [3], subSeq 0 2 [2, 3] @?= [2, 3], subSeq 1 3 [2, 3, 5] @?= [3, 5], subSeq 0 3 [2, 3, 5] @?= [2, 3, 5]] testSubSubSeq = "subSubSeq" ~: [ subSubSeq 0 0 [[]] @?= ([[]] :: [[Int]]), subSubSeq 0 0 [[2]] @?= [[]], subSubSeq 0 1 [[2]] @?= [[2]], subSubSeq 0 0 [[2, 3]] @?= [[]], subSubSeq 0 1 [[2, 3]] @?= [[2]], subSubSeq 0 2 [[2, 3]] @?= [[2, 3]], subSubSeq 1 1 [[2, 3]] @?= [[]], subSubSeq 1 2 [[2, 3]] @?= [[3]], subSubSeq 1 3 [[2, 3]] @?= [[3]], subSubSeq 0 2 [[2, 3]] @?= [[2, 3]], subSubSeq 1 3 [[2, 3, 5]] @?= [[3, 5]], subSubSeq 0 3 [[2, 3, 5]] @?= [[2, 3, 5]], subSubSeq 0 0 [[2, 3], [5, 7]] @?= [[2, 3], []], subSubSeq 0 1 [[2, 3], [5, 7]] @?= [[2, 3], [5]], subSubSeq 0 2 [[2, 3], [5, 7]] @?= [[2, 3], [5, 7]], subSubSeq 1 0 [[2, 3], [5, 7]] @?= [[3], []], subSubSeq 1 1 [[2, 3], [5, 7]] @?= [[3], [5]], subSubSeq 1 2 [[2, 3], [5, 7]] @?= [[3], [5, 7]], subSubSeq 2 0 [[2, 3], [5, 7]] @?= [[], []], subSubSeq 2 1 [[2, 3], [5, 7]] @?= [[], [5]], subSubSeq 2 2 [[2, 3], [5, 7]] @?= [[], [5, 7]]] testGroupByIndex = "groupByIndex" ~: [ groupByIndex 0 [(0, 2)] @?= [], groupByIndex 1 [(0, 2)] @?= [[2]], groupByIndex 2 [(0, 2)] @?= [[2], []], groupByIndex 0 [(1, 2)] @?= [], groupByIndex 1 [(1, 2)] @?= [[]], groupByIndex 2 [(1, 2)] @?= [[], [2]], groupByIndex 3 [(1, 2)] @?= [[], [2], []], groupByIndex 0 [(0, 2), (0, 3)] @?= [], groupByIndex 1 [(0, 2), (0, 3)] @?= [[3, 2]], groupByIndex 1 [(0, 2), (1, 3)] @?= [[2]], groupByIndex 1 [(1, 2), (1, 3)] @?= [[]], groupByIndex 2 [(0, 2), (0, 3)] @?= [[3, 2], []], groupByIndex 2 [(0, 2), (1, 3)] @?= [[2], [3]], groupByIndex 2 [(1, 2), (1, 3)] @?= [[], [3, 2]], groupByIndex 3 [(0, 2), (0, 3)] @?= [[3, 2], [], []], groupByIndex 3 [(0, 2), (1, 3)] @?= [[2], [3], []], groupByIndex 3 [(1, 2), (1, 3)] @?= [[], [3, 2], []], groupByIndex 5 [(0, 2), (2, 5), (2, 3), (4, 13), (4, 11), (4, 7)] @?= [[2], [], [3, 5], [], [7, 11, 13]]] testUtil = "Util" ~: [ testMapFirst, testMapLast, testSubSeq, testSubSubSeq, testGroupByIndex]
guillaume-nargeot/codecov-haskell
test/TestCodecovHaskellUtil.hs
Haskell
bsd-3-clause
3,108
module View.Talk where import Data.Aeson.Text (encodeToLazyText) import qualified Data.Text.Lazy as LT import Database.Persist import Lucid import Lucid.Base (makeAttribute) import Models.Talk (getTalkBySlug) import RIO import Types import View.Bundle import View.Error import View.Layout (layout) getTalkH :: Text -> AppM (Html ()) getTalkH slug = do mTalk <- lift $ getTalkBySlug slug case mTalk of Nothing -> get404H Just entity@(Entity _ talk) -> do bundle <- includeBundle TalkBundle layout ( do title_ $ toHtml $ talkName talk meta_ [ makeAttribute "property" "og:description" , name_ "description" , content_ $ talkDescription talk ] meta_ [ makeAttribute "property" "og:url" , content_ $ "https://ted2srt.org/talks/" <> talkSlug talk ] meta_ [ makeAttribute "property" "og:title" , content_ $ talkName talk ] meta_ [ makeAttribute "property" "og:type" , content_ "article" ] meta_ [ makeAttribute "property" "og:image" , content_ $ talkImage talk ] script_ $ LT.toStrict $ "window.TALK = " <> encodeToLazyText (entityIdToJSON entity) ) bundle
rnons/ted2srt
backend/src/View/Talk.hs
Haskell
bsd-3-clause
1,496
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Test.Mismi.Amazonka ( sendMultipart , withMultipart , newMultipart ) where import Control.Monad.Catch import Control.Monad.Reader (ask) import Control.Monad.Trans.Resource import Data.Text as T import Data.Text.Encoding (encodeUtf8) import Mismi.S3 import qualified Mismi.S3.Amazonka as A import Mismi.S3.Internal import P import Test.Mismi.S3 import Test.QuickCheck import Test.QuickCheck.Instances () import X.Control.Monad.Trans.Either sendMultipart :: Text -> Address -> Int -> Text -> AWS () sendMultipart t a i ui = do let req = f' A.uploadPart a i ui (A.toBody $ encodeUtf8 t) void $ A.send req withMultipart :: Testable a => (Address -> Text -> AWS a) -> Property withMultipart f = testAWS $ do a <- newAddress awsBracket (createMultipartUpload a) (abortMultipart' a) (f a) newMultipart :: AWS (Address, Text) newMultipart = do a <- newAddress r <- createMultipartUpload a e <- ask void $ register (eitherT throwM pure . runAWS e $ abortMultipart' a r) void $ register (eitherT throwM pure . runAWS e $ listRecursively a >>= mapM_ delete >> delete a) pure $ (a, r)
ambiata/mismi
mismi-s3/test/Test/Mismi/Amazonka.hs
Haskell
bsd-3-clause
1,315
{- TestVersion.hs (adapted from test_version.c in freealut) Copyright (c) Sven Panne 2005 <sven.panne@aedion.de> This file is part of the ALUT package & distributed under a BSD-style license See the file libraries/ALUT/LICENSE -} import Control.Monad ( unless ) import Sound.ALUT import System.Exit ( exitFailure ) import System.IO ( hPutStrLn, stderr ) -- This program checks that the version of OpenAL in the library agrees with the -- header file we're compiled against. main :: IO () main = withProgNameAndArgs runALUT $ \_progName _args -> do av <- get alutVersion unless (av == alutAPIVersion) $ do hPutStrLn stderr ("WARNING: The ALUT library is version " ++ av ++ ".x but the ALUT binding says it's " ++ alutAPIVersion ++ ".x!") exitFailure hPutStrLn stderr ("The ALUT library is at version " ++ av ++ ".x")
FranklinChen/hugs98-plus-Sep2006
packages/ALUT/examples/TestSuite/TestVersion.hs
Haskell
bsd-3-clause
870
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.ZH.Rules ( rules ) where import qualified Data.HashMap.Strict as HashMap import Data.Maybe import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import Duckling.Types ruleInteger5 :: Rule ruleInteger5 = Rule { name = "integer (0..10)" , pattern = [ regex "(\x3007|\x96f6|\x4e00|\x4e8c|\x4e24|\x5169|\x4e09|\x56db|\x4e94|\x516d|\x4e03|\x516b|\x4e5d|\x5341)(\x4e2a|\x500b)?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup match integerMap >>= integer _ -> Nothing } integerMap :: HashMap.HashMap Text.Text Integer integerMap = HashMap.fromList [ ( "\x3007", 0 ) , ( "\x96f6", 0 ) , ( "\x4e00", 1 ) , ( "\x5169", 2 ) , ( "\x4e24", 2 ) , ( "\x4e8c", 2 ) , ( "\x4e09", 3 ) , ( "\x56db", 4 ) , ( "\x4e94", 5 ) , ( "\x516d", 6 ) , ( "\x4e03", 7 ) , ( "\x516b", 8 ) , ( "\x4e5d", 9 ) , ( "\x5341", 10 ) ] ruleNumeralsPrefixWithNegativeOrMinus :: Rule ruleNumeralsPrefixWithNegativeOrMinus = Rule { name = "numbers prefix with -, negative or minus" , pattern = [ regex "-|\x8d1f\\s?|\x8ca0\\s?" , dimension Numeral ] , prod = \tokens -> case tokens of (_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1)) _ -> Nothing } ruleIntegerNumeric :: Rule ruleIntegerNumeric = Rule { name = "integer (numeric)" , pattern = [ regex "(\\d{1,18})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do v <- parseInt match integer $ toInteger v _ -> Nothing } ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [ regex "(\\d+(,\\d\\d\\d)+\\.\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDouble (Text.replace (Text.singleton ',') Text.empty match) >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number" , pattern = [ regex "(\\d*\\.\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal True match _ -> Nothing } ruleNumeral :: Rule ruleNumeral = Rule { name = "<number>个" , pattern = [ dimension Numeral , regex "\x4e2a" ] , prod = \tokens -> case tokens of (token:_) -> Just token _ -> Nothing } ruleInteger3 :: Rule ruleInteger3 = Rule { name = "integer (20..90)" , pattern = [ numberBetween 2 10 , regex "\x5341" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ v * 10 _ -> Nothing } ruleNumeralsSuffixesKMG :: Rule ruleNumeralsSuffixesKMG = Rule { name = "numbers suffixes (K, M, G)" , pattern = [ dimension Numeral , regex "([kmg])" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}): Token RegexMatch (GroupMatch (match:_)): _) -> case Text.toLower match of "k" -> double $ v * 1e3 "m" -> double $ v * 1e6 "g" -> double $ v * 1e9 _ -> Nothing _ -> Nothing } ruleInteger4 :: Rule ruleInteger4 = Rule { name = "integer 21..99" , pattern = [ oneOf [70, 20, 60, 50, 40, 90, 30, 80] , numberBetween 1 10 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + v2 _ -> Nothing } ruleInteger2 :: Rule ruleInteger2 = Rule { name = "integer (11..19)" , pattern = [ regex "\x5341" , numberBetween 1 10 ] , prod = \tokens -> case tokens of (_:Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ 10 + v _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ," , pattern = [ regex "(\\d{1,3}(,\\d\\d\\d){1,5})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)): _) -> let fmt = Text.replace (Text.singleton ',') Text.empty match in parseDouble fmt >>= double _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleInteger2 , ruleInteger3 , ruleInteger4 , ruleInteger5 , ruleIntegerNumeric , ruleIntegerWithThousandsSeparator , ruleNumeral , ruleNumeralsPrefixWithNegativeOrMinus , ruleNumeralsSuffixesKMG ]
rfranek/duckling
Duckling/Numeral/ZH/Rules.hs
Haskell
bsd-3-clause
5,188
{-# LANGUAGE NamedFieldPuns #-} module RFB.CommandLoop (commandLoop) where import System.IO import qualified Data.ByteString.Lazy as BS import Data.Char import Data.Binary.Get import Data.Binary.Put import Data.Word import qualified RFB.ClientToServer as RFBClient import qualified RFB.Encoding as Encoding import qualified RFB.State as RFBState import Control.Monad.State type MyState a = StateT RFBState.RFBState IO a commandLoop :: Handle -> Int -> Int -> IO () commandLoop h width height= do runStateT (commandLoop1 h) (RFBState.initialState width height) return () commandLoop1 :: Handle -> MyState () commandLoop1 handle = do commandByte <- liftIO$ BS.hGet handle 1 let command = RFBClient.word8ToCommand $ runGet (do {x<-getWord8;return(x);}) commandByte byteStream <- liftIO $ BS.hGet handle (RFBClient.bytesToRead command) let commandData = RFBClient.getCommandData byteStream command --let commandData = RFBClient.parseCommandByteString byteStream command liftIO $ putStrLn $ "Client said -> " ++ (show command) liftIO $ putStrLn (show commandData) case command of RFBClient.SetPixelFormat -> processSetPixelFormat commandData RFBClient.SetEncodings -> liftIO $ processSetEncodings handle commandData RFBClient.FramebufferUpdate -> processFrameBufferUpdateRequest handle commandData RFBClient.PointerEvent -> processPointerEvent handle commandData RFBClient.ClientCutText -> processClientCutTextEvent handle commandData RFBClient.KeyEvent -> processKeyEvent handle commandData RFBClient.BadCommand -> liftIO $ putStrLn (show command) commandLoop1 handle processClientCutTextEvent handle (RFBClient.ClientCutTextData length) = do x <- liftIO $ BS.hGet handle length liftIO $ putStrLn (show x) processKeyEvent handle commandData = do return () processPointerEvent handle (RFBClient.PointerEventData buttonMask x y)= do state@(RFBState.RFBState d i p pend u) <- get let newState=if buttonMask == 1 then Encoding.putPixel state (x,y) else state put newState if pend && ((length u) > 0) then do liftIO $ putStrLn $ "Updating -> " ++ (show u) liftIO $ BS.hPutStr handle (updateRectangles state) liftIO $ hFlush handle put (RFBState.RFBState d i p False []) return () else return () processSetPixelFormat (RFBClient.SetPixelFormatData bitsPerPixel depth bigEndian trueColor redMax greenMax blueMax redShift greenShift blueShift) = do state <- get let newState=RFBState.setPixelFormat state bitsPerPixel bigEndian redMax greenMax blueMax redShift greenShift blueShift put newState return () processSetEncodings handle (RFBClient.SetEncodingsData count) = do x <- BS.hGet handle (4*count) let e = runGet (do {x<-getWord32le; return x}) x putStrLn (show e) return () fullScreen :: Int -> Int -> Int -> Int -> RFBState.RFBState -> BS.ByteString fullScreen x y width height state = runPut $ do putWord8 0 putWord8 0 putWord16be 1 putWord16be (fromIntegral x) putWord16be (fromIntegral y) putWord16be (fromIntegral width) putWord16be (fromIntegral height) putWord32be 0 Encoding.getImageByteString state x y width height return () updateRectangles state@(RFBState.RFBState _ _ (RFBState.PixelFormat bpp _ _ _ _ _ _ _) pend updateList) = runPut $ do putWord8 0 putWord8 0 putWord16be (fromIntegral (length updateList)) Encoding.encodeRectagles bpp updateList return () empty = runPut $ return () processFrameBufferUpdateRequest handle (RFBClient.FramebufferUpdateData incremental x y width height) = do -- this produces black state@(RFBState.RFBState d i p pend u) <- get let byteString=if incremental == 0 then fullScreen x y width height state else (if (length u > 0) then updateRectangles state else empty) --let newState = if incremental == 0 then state else RFBState.RFBState d i p pend [] let newState = if incremental == 0 then RFBState.RFBState d i p False [] else RFBState.RFBState d i p (if (length u > 0) then False else True) [] put newState (RFBState.RFBState _ _ _ newPend _) <- get liftIO $ putStrLn (show pend) liftIO $ putStrLn (show newPend) --liftIO $ putStrLn (show state) --liftIO $ putStrLn (show newState) liftIO $ BS.hPutStr handle byteString liftIO $ hFlush handle
ckkashyap/Chitra
RFB/CommandLoop.hs
Haskell
bsd-3-clause
4,219
{-# LANGUAGE TypeFamilies, ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Program.View.WiredGeometryView -- Copyright : (c) Artem Chirkin -- License : MIT -- -- Maintainer : Artem Chirkin <chirkin@arch.ethz.ch> -- Stability : experimental -- -- -- ----------------------------------------------------------------------------- module Program.View.WiredGeometryView ( WiredGeometryView (..) )where import JsHs.TypedArray import JsHs.TypedArray.IO as JsHs import Data.Coerce (coerce) import JsHs.WebGL import SmallGL.Shader import Data.Geometry import Program.Model.WiredGeometry import Program.View data WiredGeometryView = WGView !WebGLBuffer !ShaderProgram !GLsizei instance Drawable WiredGeometry where type View WiredGeometry = WiredGeometryView createView gl (WiredGeometry _ _ size arr) = do buf <- createBuffer gl bindBuffer gl gl_ARRAY_BUFFER buf bufferData gl gl_ARRAY_BUFFER arr gl_STATIC_DRAW shProgram <- initShaders gl [(gl_FRAGMENT_SHADER, fragStaticMesh) ,(gl_VERTEX_SHADER, vertStaticMesh)] [] return $ WGView buf shProgram size drawInCurrContext vc@ViewContext{glctx = gl, curState = cs} (WiredGeometry _ (unpackV4 -> (r,g,b,a)) _ _) (WGView buf prog size) | size <= 1 = return () | otherwise = do enableVertexAttribArray gl ploc useProgram gl . programId $ prog bindBuffer gl gl_ARRAY_BUFFER buf uniformMatrix4fv gl (unifLoc prog "uProjM") False (projectArr vc) setIndex 0 (vView cs) (coerce $ modelViewArr vc) uniformMatrix4fv gl (unifLoc prog "uModelViewM") False (modelViewArr vc) uniform4f gl (unifLoc prog "uColor") (r*a) (g*a) (b*a) a vertexAttribPointer gl ploc 3 gl_FLOAT False 12 0 drawArrays gl gl_LINES 0 size disableVertexAttribArray gl ploc where ploc = attrLoc prog "aVertexPosition" updateView gl (WiredGeometry _ _ s arr) (WGView buf p _) = do bindBuffer gl gl_ARRAY_BUFFER buf bufferData gl gl_ARRAY_BUFFER arr gl_STATIC_DRAW return (WGView buf p s) deleteView gl _ (WGView buf _ _) = deleteBuffer gl buf fragStaticMesh :: String fragStaticMesh = unlines [ "precision mediump float;", "uniform vec4 uColor;", "varying vec3 vDist;", "void main(void) {", " gl_FragColor = clamp(3.0 - dot(vDist,vDist), 0.0, 1.0) * uColor;", "}"] vertStaticMesh :: String vertStaticMesh = unlines [ "precision mediump float;", "attribute vec3 aVertexPosition;", "uniform mat4 uModelViewM;", "uniform mat4 uProjM;", "varying vec3 vDist;", "void main(void) {", " vec4 globalPos = uModelViewM * vec4(aVertexPosition, 1.0);", " gl_Position = uProjM * globalPos;", " vDist = globalPos.xyz/(globalPos.w*200.0);", "}"]
achirkin/ghcjs-modeler
src/Program/View/WiredGeometryView.hs
Haskell
bsd-3-clause
3,078
module PL0.SymbolTable ( SymEntry(..) , SymbolTable , emptySymbolTable ) where import PL0.Internal
LightAndLight/pl0-haskell
src/PL0/SymbolTable.hs
Haskell
bsd-3-clause
116
{-# LANGUAGE TemplateHaskell #-} module Game.ClientRespawnT where import Control.Lens (makeLenses) import Linear (V3(..)) import Game.ClientPersistantT import Types makeLenses ''ClientRespawnT newClientRespawnT :: ClientRespawnT newClientRespawnT = ClientRespawnT { _crCoopRespawn = newClientPersistantT , _crEnterFrame = 0 , _crScore = 0 , _crCmdAngles = V3 0 0 0 , _crSpectator = False }
ksaveljev/hake-2
src/Game/ClientRespawnT.hs
Haskell
bsd-3-clause
475
-- For everything {-# LANGUAGE GADTs #-} -- For type level flags, lists, strings {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} -- For Vinyl and universe polymorphism {-# LANGUAGE PolyKinds #-} -- For type-level lists {-# LANGUAGE TypeOperators #-} -- For unpacking existentials {-# LANGUAGE RankNTypes #-} -- For functions to apply to records {-# LANGUAGE TypeFamilies #-} -- For Aeson serialization {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Master.Template ( -- * Data Kinds TemplateLevel(..) , Normalization(..) -- * Templating , Template(..) , TemplatesFor , TemplateFix(..) , unFixLevel , TemplateBox() , weakenTemplate , compileTemplateBox , compileTemplate , checkTemplate , checkTemplates -- * Lenses and prisms , templateFixNormalized , templateBox , templateFixBox , fixAnyLevelIso , Fixable (..) , _Or , _And , _Gt , _Lt , _Not , _Eq , _In ) where import Data.Aeson import Data.Aeson.Types import Control.Monad import Control.Applicative ((<$>), (<|>)) import qualified Control.Lens as L import Data.Vinyl.Core import Data.Vinyl.Functor import GHC.TypeLits -- | Take apart an or unOr :: Template Normalized Disjunction a -> [TemplateFix Normalized Conjunction a] unOr (Or fixes) = fixes -- | Take apart the existential 'FixAny' that permits violation of normalization constraints unFixAny :: (forall level' . Template Unnormalized level' a -> k) -> TemplateFix Unnormalized level a -> k unFixAny existentialKont (FixAny constraint) = existentialKont constraint -- | Take apart the 'FixLevel that prevents violation of normalization constraints unFixLevel :: TemplateFix Normalized level a -> Template Normalized level a unFixLevel (FixLevel c) = c -- | Functor transformer for template records type TemplatesFor norm level (f :: u -> *) = Compose (Template norm level) f -- | Check the templates for a record -- TODO: Have a real validation type checkTemplates :: Rec (TemplatesFor norm level f) fields -> Rec f fields -> Rec (Const Bool) fields checkTemplates constraintRec xRec = rmap (\(Compose constraint) -> Lift $ \x -> Const $ checkTemplate x constraint) constraintRec `rapply` xRec -- | Check whether a constraint is fulfilled checkTemplate :: a -> Template norm level a -> Bool checkTemplate _ Meh = True checkTemplate x (Not (FixAny template)) = not $ checkTemplate x template checkTemplate x (Not (FixLevel template)) = not $ checkTemplate x template checkTemplate x (Eq y) = x == y checkTemplate x (Lt y) = x < y checkTemplate x (Gt y) = x > y checkTemplate x (In y) = x `elem` y checkTemplate x (And []) = True checkTemplate x (And conjs@(FixAny _ : _)) = and $ map (unFixAny $ checkTemplate x) conjs checkTemplate x (And conjs@(FixLevel _ : _)) = and $ map (checkTemplate x . unFixLevel) conjs checkTemplate x (Or []) = False checkTemplate x (Or disjs@(FixAny _ : _)) = or $ map (unFixAny $ checkTemplate x) disjs checkTemplate x (Or disjs@(FixLevel _ : _)) = or $ map (checkTemplate x . unFixLevel) disjs -- | A constraint compiled by normalizing to horn clauses type CompiledTemplate = Template Normalized Disjunction -- | For enforcing normal form data TemplateLevel = Atom | Conjunction | Disjunction -- Flag for whether a type is normalized or not data Normalization = Unnormalized | Normalized -- When recurring, do we enforce normalization or not? data TemplateFix (norm :: Normalization) (level :: TemplateLevel) (a :: *) where FixAny :: Template Unnormalized level' a -> TemplateFix Unnormalized level a FixLevel :: Template Normalized level a -> TemplateFix Normalized level a -- | Isomorphism between a Normalized fix and the contained template templateFixNormalized :: L.Iso' (TemplateFix Normalized level a) (Template Normalized level a) templateFixNormalized = L.iso unFixLevel FixLevel instance (Eq a) => Eq (TemplateFix norm level a) where (==) = eqFixHelper eqFixHelper :: (Eq a) => TemplateFix norm level a -> TemplateFix norm level' a -> Bool eqFixHelper (FixAny a) (FixAny b) = eqHelper a b eqFixHelper (FixLevel a) (FixLevel b) = eqHelper a b eqFixHelper _ _ = False eqHelper :: (Eq a) => Template norm level' a -> Template norm level a -> Bool eqHelper Meh Meh = True eqHelper (Not a) (Not b) = a == b eqHelper (Eq a) (Eq b) = a == b eqHelper (Lt a) (Lt b) = a == b eqHelper (Gt a) (Gt b) = a == b eqHelper (In a) (In b) = a == b eqHelper (And a) (And b) = a == b eqHelper (Or a) (Or b) = a == b eqHelper _ _ = False -- | Templates data Template (norm :: Normalization) (level :: TemplateLevel) (a :: *) where Meh :: Template norm level a Not :: TemplateFix norm Atom a -> Template norm Atom a Eq :: (Eq a) => a -> Template norm Atom a Lt :: (Ord a) => a -> Template norm Atom a Gt :: (Ord a) => a -> Template norm Atom a In :: (Eq a) => [a] -> Template norm Atom a And :: [TemplateFix norm Atom a] -> Template norm Conjunction a Or :: [TemplateFix norm Conjunction a] -> Template norm Disjunction a instance (Eq a) => Eq (Template norm level a) where (==) = eqHelper -- | Convert a constraint from unnormalized form to normal form compileTemplate :: Template Unnormalized level a -> Template Normalized Disjunction a compileTemplate Meh = Meh compileTemplate (Not (FixAny Meh)) = Or [FixLevel $ And [FixLevel $ Not $ FixLevel $ Meh]] compileTemplate (Not (FixAny (Eq x))) = Or [FixLevel $ And [FixLevel $ Not $ FixLevel $ Eq x]] compileTemplate (Not (FixAny (Lt x))) = Or [FixLevel $ And [FixLevel $ Not $ FixLevel $ Lt x]] compileTemplate (Not (FixAny (Gt x))) = Or [FixLevel $ And [FixLevel $ Not $ FixLevel $ Gt x]] compileTemplate (Not (FixAny (In x))) = Or [FixLevel $ And [FixLevel $ Not $ FixLevel $ In x]] compileTemplate (Not (FixAny c)) = pushDownNots compileTemplate c compileTemplate (Eq x) = Or [FixLevel $ And [FixLevel $ Eq x]] compileTemplate (Lt x) = Or [FixLevel $ And [FixLevel $ Lt x]] compileTemplate (Gt x) = Or [FixLevel $ And [FixLevel $ Gt x]] compileTemplate (In x) = Or [FixLevel $ And [FixLevel $ In x]] compileTemplate (And fixes) = foldr distributeOrsAnd (Or [FixLevel $ And [FixLevel Meh]]) $ map (unFixAny compileTemplate) fixes compileTemplate (Or fixes) = Or $ concatMap (unFixAny $ unOr . compileTemplate) fixes -- | Push 'Nots' out to leaves pushDownNots :: (forall level' . Template Unnormalized level' a -> k) -> Template Unnormalized level a -> k pushDownNots k Meh = k $ Not $ FixAny Meh pushDownNots k (Not (FixAny c)) = k c pushDownNots k (Eq x) = k $ Not $ FixAny $ Eq x pushDownNots k (Lt x) = k $ Not $ FixAny $ Lt x pushDownNots k (Gt x) = k $ Not $ FixAny $ Gt x pushDownNots k (In x) = k $ Not $ FixAny $ In x pushDownNots k (And fixes) = k $ Or $ map (unFixAny $ pushDownNots FixAny) fixes pushDownNots k (Or fixes) = k $ And $ map (unFixAny $ pushDownNots FixAny) fixes -- | Distribute a conjunction of disjunctions of conjunctions to obtain a disjunction of conjunctions distributeOrsAnd :: Template Normalized Disjunction a -> Template Normalized Disjunction a -> Template Normalized Disjunction a distributeOrsAnd (Or andsLeft) (Or andsRight) = Or [FixLevel $ andAnds andLeft andRight | (FixLevel andLeft) <- andsLeft, (FixLevel andRight) <- andsRight] distributeOrsAnd Meh (Or andsRight) = Or andsRight distributeOrsAnd (Or andsLeft) Meh = Or andsLeft distributeOrsAnd Meh Meh = Meh andAnds :: Template Normalized Conjunction a -> Template Normalized Conjunction a -> Template Normalized Conjunction a andAnds (And leftFixes) (And rightFixes) = And $ leftFixes ++ rightFixes andAnds Meh (And rightFixes) = And rightFixes andAnds (And leftFixes) Meh = And leftFixes andAnds Meh Meh = Meh weakenTemplate :: Template norm level a -> TemplateBox a weakenTemplate Meh = TemplateBox Meh weakenTemplate (Eq x) = TemplateBox $ Eq x weakenTemplate (Not (FixAny t)) = case weakenTemplate t of TemplateBox t -> TemplateBox $ Not $ FixAny t weakenTemplate (Lt x) = TemplateBox $ Lt x weakenTemplate (Gt x) = TemplateBox $ Gt x weakenTemplate (In xs) = TemplateBox $ In xs weakenTemplate (And []) = TemplateBox $ And [] weakenTemplate (And ts@(FixAny _ : _)) = TemplateBox $ And $ ripTemplates (map (unFixAny weakenTemplate) ts) FixAny weakenTemplate (And ts@(FixLevel _ : _)) = TemplateBox $ And $ ripTemplates (map (weakenTemplate . unFixLevel) ts) FixAny weakenTemplate (Or []) = TemplateBox $ Or [] weakenTemplate (Or ts@(FixAny _ : _)) = TemplateBox $ Or $ ripTemplates (map (unFixAny weakenTemplate) ts) FixAny weakenTemplate (Or ts@(FixLevel _ : _)) = TemplateBox $ Or $ ripTemplates (map (weakenTemplate . unFixLevel) ts) FixAny compileTemplateBox :: TemplateBox a -> Template Normalized Disjunction a compileTemplateBox (TemplateBox t) = compileTemplate t instance (ToJSON a) => ToJSON (Template Normalized Disjunction a) where toJSON = toJSON . weakenTemplate instance (FromJSON a, Eq a, Ord a) => FromJSON (Template Normalized Disjunction a) where parseJSON = (compileTemplateBox <$>) . parseJSON data TemplateBox a = forall level. TemplateBox { _templateBox :: Template Unnormalized level a } -- | Isomorphism between a TemplateBox (used for encoding) and a TemplateFix Unnormalized (which can be deconstructed with prisms) templateBox :: L.Iso' (TemplateBox a) (TemplateFix Unnormalized level a) templateBox = L.iso (\(TemplateBox template) -> FixAny template) (\(FixAny template) -> TemplateBox template) data TemplateFixBox a = forall level. TemplateFixBox { _templateFixBox :: TemplateFix Unnormalized level a} templateFixBox :: L.Iso' (TemplateFixBox a) (TemplateFix Unnormalized level a) templateFixBox = L.iso (\(TemplateFixBox (FixAny template)) -> FixAny template) TemplateFixBox instance (ToJSON a) => ToJSON (TemplateFixBox a) where toJSON (TemplateFixBox (FixAny template)) = toJSON $ TemplateBox template instance (ToJSON a) => ToJSON (TemplateBox a) where toJSON (TemplateBox Meh) = object ["Meh" .= ()] toJSON (TemplateBox (Eq val)) = object ["Eq" .= val] toJSON (TemplateBox (Not t)) = object ["Not" .= TemplateFixBox t] toJSON (TemplateBox (Lt val)) = object ["Lt" .= val] toJSON (TemplateBox (Gt val)) = object ["Gt" .= val] toJSON (TemplateBox (In xs)) = object ["In" .= xs] toJSON (TemplateBox (And ts)) = object ["And" .= fmap TemplateFixBox ts] toJSON (TemplateBox (Or ts)) = object ["Or" .= fmap TemplateFixBox ts] instance (FromJSON a, Eq a, Ord a) => FromJSON (TemplateBox a) where parseJSON o = parseEq o <|> parseNot o <|> parseLt o <|> parseGt o <|> parseIn o <|> parseAnd o <|> parseOr o <|> parseMeh o parseEq, parseNot, parseLt, parseGt, parseIn, parseAnd, parseOr, parseMeh :: (FromJSON a, Ord a, Eq a) => Value -> Parser (TemplateBox a) parseEq (Object o) = do value <- (o .: "Eq") return $ TemplateBox $ Eq value parseEq _ = mzero parseNot (Object o) = do (TemplateBox template) <- o .: "Not" return $ TemplateBox $ Not $ FixAny $ template parseNot _ = mzero parseLt (Object o) = do value <- o .: "Lt" return $ TemplateBox $ Lt value parseLt _ = mzero parseGt (Object o) = do value <- o .: "Gt" return $ TemplateBox $ Gt value parseGt _ = mzero parseIn (Object o) = do xs <- o .: "In" return $ TemplateBox $ In xs parseIn _ = mzero parseAnd (Object o) = do xs <- o .: "And" return $ TemplateBox $ And $ ripTemplates xs FixAny parseAnd _ = mzero parseOr (Object o) = do xs <- o .: "Or" return $ TemplateBox $ Or $ ripTemplates xs FixAny parseOr _ = mzero parseMeh (Object o) = do () <- o .: "Meh" return $ TemplateBox $ Meh parseMeh _ = mzero ripTemplates :: [TemplateBox a] -> (forall level. Template Unnormalized level a -> k) -> [k] ripTemplates [] _ = [] ripTemplates ((TemplateBox t):ts) f = (f t):(ripTemplates ts f) -- | Necessary for the reconstruction side of prisms into TemplateBox. -- Simply propagate this constraint when using the prisms parametrically in the normalization variable. -- Instances are given for both cases. class Fixable (normalization :: Normalization) where fixFunction :: Template normalization level a -> TemplateFix normalization level a instance Fixable Normalized where fixFunction = FixLevel instance Fixable Unnormalized where fixFunction = FixAny -- | Isomorphism between TemplateFix unnormalized at differing levels. Use when applying a prism to Unnormalized boxes. fixAnyLevelIso :: L.Iso' (TemplateFix Unnormalized level1 a) (TemplateFix Unnormalized level2 a) fixAnyLevelIso = L.iso castFixAny castFixAny where castFixAny :: TemplateFix Unnormalized level1 a -> TemplateFix Unnormalized level2 a castFixAny (FixAny template) = FixAny template -- | Prism for getting/setting disjunctive constraints _Or :: (Fixable normalization) => L.Prism' (TemplateFix normalization Disjunction a) [TemplateFix normalization Conjunction a] _Or = L.prism' (fixFunction . Or) ripOr where ripOr :: TemplateFix normalization level a -> Maybe [TemplateFix normalization Conjunction a] ripOr (FixAny (Or xs)) = Just xs ripOr (FixLevel (Or xs)) = Just xs ripOr _ = Nothing -- | Prism for getting/setting conjunctive constraints _And :: (Fixable normalization) => L.Prism' (TemplateFix normalization Conjunction a) [TemplateFix normalization Atom a] _And = L.prism' (fixFunction . And) ripAnd where ripAnd :: TemplateFix normalization level a -> Maybe [TemplateFix normalization Atom a] ripAnd (FixAny (And xs)) = Just xs ripAnd (FixLevel (And xs)) = Just xs ripAnd _ = Nothing -- | Prism for getting/setting inverted constraints _Not :: (Fixable normalization) => L.Prism' (TemplateFix normalization Atom a) (TemplateFix normalization Atom a) _Not = L.prism' (fixFunction . Not) ripNot where ripNot :: (TemplateFix normalization level a) -> Maybe (TemplateFix normalization Atom a) ripNot (FixAny (Not t)) = Just t ripNot (FixLevel (Not t)) = Just t ripNot _ = Nothing -- | Prism for getting/setting equality constraints _Eq :: (Fixable normalization, Eq a) => L.Prism' (TemplateFix normalization Atom a) a _Eq = L.prism' (fixFunction . Eq) ripEq where ripEq :: (TemplateFix normalization level a) -> Maybe a ripEq (FixAny (Eq v)) = Just v ripEq (FixLevel (Eq v)) = Just v ripEq _ = Nothing -- | Prism for getting/setting less-than constraints _Lt :: (Fixable normalization, Ord a) => L.Prism' (TemplateFix normalization Atom a) a _Lt = L.prism' (fixFunction . Lt) ripLt where ripLt :: (TemplateFix normalization level a) -> Maybe a ripLt (FixAny (Lt v)) = Just v ripLt (FixLevel (Lt v)) = Just v ripLt _ = Nothing -- | Prism for getting/setting greater-than constraints _Gt :: (Fixable normalization, Ord a) => L.Prism' (TemplateFix normalization Atom a) a _Gt = L.prism' (fixFunction . Lt) ripGt where ripGt :: (TemplateFix normalization level a) -> Maybe a ripGt (FixAny (Gt v)) = Just v ripGt (FixLevel (Gt v)) = Just v ripGt _ = Nothing -- | Prism for getting/setting set membership constraints _In :: (Fixable normalization, Eq a) => L.Prism' (TemplateFix normalization Atom a) [a] _In = L.prism' (fixFunction . In) ripIn where ripIn :: (TemplateFix normalization level a) -> Maybe [a] ripIn (FixAny (In xs)) = Just xs ripIn (FixLevel (In xs)) = Just xs ripIn _ = Nothing
plow-technologies/template-service
master/src/Data/Master/Template.hs
Haskell
bsd-3-clause
15,771
{-# LINE 1 "Data.Either.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, TypeOperators, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Either -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- The Either type, and associated operations. -- ----------------------------------------------------------------------------- module Data.Either ( Either(..), either, lefts, rights, isLeft, isRight, partitionEithers, ) where import GHC.Base import GHC.Show import GHC.Read import Data.Type.Equality -- $setup -- Allow the use of some Prelude functions in doctests. -- >>> import Prelude ( (+), (*), length, putStrLn ) {- -- just for testing import Test.QuickCheck -} {-| The 'Either' type represents values with two possibilities: a value of type @'Either' a b@ is either @'Left' a@ or @'Right' b@. The 'Either' type is sometimes used to represent a value which is either correct or an error; by convention, the 'Left' constructor is used to hold an error value and the 'Right' constructor is used to hold a correct value (mnemonic: \"right\" also means \"correct\"). ==== __Examples__ The type @'Either' 'String' 'Int'@ is the type of values which can be either a 'String' or an 'Int'. The 'Left' constructor can be used only on 'String's, and the 'Right' constructor can be used only on 'Int's: >>> let s = Left "foo" :: Either String Int >>> s Left "foo" >>> let n = Right 3 :: Either String Int >>> n Right 3 >>> :type s s :: Either String Int >>> :type n n :: Either String Int The 'fmap' from our 'Functor' instance will ignore 'Left' values, but will apply the supplied function to values contained in a 'Right': >>> let s = Left "foo" :: Either String Int >>> let n = Right 3 :: Either String Int >>> fmap (*2) s Left "foo" >>> fmap (*2) n Right 6 The 'Monad' instance for 'Either' allows us to chain together multiple actions which may fail, and fail overall if any of the individual steps failed. First we'll write a function that can either parse an 'Int' from a 'Char', or fail. >>> import Data.Char ( digitToInt, isDigit ) >>> :{ let parseEither :: Char -> Either String Int parseEither c | isDigit c = Right (digitToInt c) | otherwise = Left "parse error" >>> :} The following should work, since both @\'1\'@ and @\'2\'@ can be parsed as 'Int's. >>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither '1' y <- parseEither '2' return (x + y) >>> :} >>> parseMultiple Right 3 But the following should fail overall, since the first operation where we attempt to parse @\'m\'@ as an 'Int' will fail: >>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither 'm' y <- parseEither '2' return (x + y) >>> :} >>> parseMultiple Left "parse error" -} data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show) instance Functor (Either a) where fmap _ (Left x) = Left x fmap f (Right y) = Right (f y) instance Applicative (Either e) where pure = Right Left e <*> _ = Left e Right f <*> r = fmap f r instance Monad (Either e) where Left l >>= _ = Left l Right r >>= k = k r -- | Case analysis for the 'Either' type. -- If the value is @'Left' a@, apply the first function to @a@; -- if it is @'Right' b@, apply the second function to @b@. -- -- ==== __Examples__ -- -- We create two values of type @'Either' 'String' 'Int'@, one using the -- 'Left' constructor and another using the 'Right' constructor. Then -- we apply \"either\" the 'length' function (if we have a 'String') -- or the \"times-two\" function (if we have an 'Int'): -- -- >>> let s = Left "foo" :: Either String Int -- >>> let n = Right 3 :: Either String Int -- >>> either length (*2) s -- 3 -- >>> either length (*2) n -- 6 -- either :: (a -> c) -> (b -> c) -> Either a b -> c either f _ (Left x) = f x either _ g (Right y) = g y -- | Extracts from a list of 'Either' all the 'Left' elements. -- All the 'Left' elements are extracted in order. -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- >>> lefts list -- ["foo","bar","baz"] -- lefts :: [Either a b] -> [a] lefts x = [a | Left a <- x] -- | Extracts from a list of 'Either' all the 'Right' elements. -- All the 'Right' elements are extracted in order. -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- >>> rights list -- [3,7] -- rights :: [Either a b] -> [b] rights x = [a | Right a <- x] -- | Partitions a list of 'Either' into two lists. -- All the 'Left' elements are extracted, in order, to the first -- component of the output. Similarly the 'Right' elements are extracted -- to the second component of the output. -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- >>> partitionEithers list -- (["foo","bar","baz"],[3,7]) -- -- The pair returned by @'partitionEithers' x@ should be the same -- pair as @('lefts' x, 'rights' x)@: -- -- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ] -- >>> partitionEithers list == (lefts list, rights list) -- True -- partitionEithers :: [Either a b] -> ([a],[b]) partitionEithers = foldr (either left right) ([],[]) where left a ~(l, r) = (a:l, r) right a ~(l, r) = (l, a:r) -- | Return `True` if the given value is a `Left`-value, `False` otherwise. -- -- @since 4.7.0.0 -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isLeft (Left "foo") -- True -- >>> isLeft (Right 3) -- False -- -- Assuming a 'Left' value signifies some sort of error, we can use -- 'isLeft' to write a very simple error-reporting function that does -- absolutely nothing in the case of success, and outputs \"ERROR\" if -- any error occurred. -- -- This example shows how 'isLeft' might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- -- >>> import Control.Monad ( when ) -- >>> let report e = when (isLeft e) $ putStrLn "ERROR" -- >>> report (Right 1) -- >>> report (Left "parse error") -- ERROR -- isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft (Right _) = False -- | Return `True` if the given value is a `Right`-value, `False` otherwise. -- -- @since 4.7.0.0 -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isRight (Left "foo") -- False -- >>> isRight (Right 3) -- True -- -- Assuming a 'Left' value signifies some sort of error, we can use -- 'isRight' to write a very simple reporting function that only -- outputs \"SUCCESS\" when a computation has succeeded. -- -- This example shows how 'isRight' might be used to avoid pattern -- matching when one does not care about the value contained in the -- constructor: -- -- >>> import Control.Monad ( when ) -- >>> let report e = when (isRight e) $ putStrLn "SUCCESS" -- >>> report (Left "parse error") -- >>> report (Right 1) -- SUCCESS -- isRight :: Either a b -> Bool isRight (Left _) = False isRight (Right _) = True -- instance for the == Boolean type-level equality operator type family EqEither a b where EqEither ('Left x) ('Left y) = x == y EqEither ('Right x) ('Right y) = x == y EqEither a b = 'False type instance a == b = EqEither a b {- {-------------------------------------------------------------------- Testing --------------------------------------------------------------------} prop_partitionEithers :: [Either Int Int] -> Bool prop_partitionEithers x = partitionEithers x == (lefts x, rights x) -}
phischu/fragnix
builtins/base/Data.Either.hs
Haskell
bsd-3-clause
8,051
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell {-@ LIQUID "--no-termination "@-} import Language.Haskell.Liquid.Prelude mmax x y | x < y = y | otherwise = x for lo hi acc f | lo < hi = for (lo + 1) hi (f lo acc) f | otherwise = acc sumRange i j = for i j 0 (+) prop = liquidAssertB (m >= 0) where m = sumRange 0 k k = choose 0 prop2 = liquidAssertB (z >= x && z >= y) where x = choose 0 y = choose 1 z = mmax x y
spinda/liquidhaskell
tests/gsoc15/unknown/pos/forloop.hs
Haskell
bsd-3-clause
471
{-# LANGUAGE DataKinds #-} module Ivory.Tower.Monitor ( handler , state , stateInit , monitorModuleDef , Handler() , Monitor() ) where import Ivory.Tower.Types.Unique import Ivory.Tower.Monad.Handler import Ivory.Tower.Monad.Monitor import Ivory.Tower.Monad.Base import Ivory.Language state :: (IvoryArea a, IvoryZero a) => String -> Monitor e (Ref 'Global a) state n = state' n Nothing stateInit :: (IvoryArea a, IvoryZero a) => String -> Init a -> Monitor e (Ref 'Global a) stateInit n i = state' n (Just i) state' :: (IvoryArea a, IvoryZero a) => String -> Maybe (Init a) -> Monitor e (Ref 'Global a) state' n i = do f <- freshname n let a = area (showUnique f) i monitorModuleDef $ defMemArea a return (addrOf a)
GaloisInc/tower
tower/src/Ivory/Tower/Monitor.hs
Haskell
bsd-3-clause
782
{-# language CPP #-} -- | = Name -- -- VK_EXT_sample_locations - device extension -- -- == VK_EXT_sample_locations -- -- [__Name String__] -- @VK_EXT_sample_locations@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 144 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ -- -- [__Contact__] -- -- - Daniel Rakos -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_sample_locations] @drakos-amd%0A<<Here describe the issue or question you have about the VK_EXT_sample_locations extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2017-08-02 -- -- [__Contributors__] -- -- - Mais Alnasser, AMD -- -- - Matthaeus G. Chajdas, AMD -- -- - Maciej Jesionowski, AMD -- -- - Daniel Rakos, AMD -- -- - Slawomir Grajewski, Intel -- -- - Jeff Bolz, NVIDIA -- -- - Bill Licea-Kane, Qualcomm -- -- == Description -- -- This extension allows an application to modify the locations of samples -- within a pixel used in rasterization. Additionally, it allows -- applications to specify different sample locations for each pixel in a -- group of adjacent pixels, which /can/ increase antialiasing quality -- (particularly if a custom resolve shader is used that takes advantage of -- these different locations). -- -- It is common for implementations to optimize the storage of depth values -- by storing values that /can/ be used to reconstruct depth at each sample -- location, rather than storing separate depth values for each sample. For -- example, the depth values from a single triangle /may/ be represented -- using plane equations. When the depth value for a sample is needed, it -- is automatically evaluated at the sample location. Modifying the sample -- locations causes the reconstruction to no longer evaluate the same depth -- values as when the samples were originally generated, thus the depth -- aspect of a depth\/stencil attachment /must/ be cleared before rendering -- to it using different sample locations. -- -- Some implementations /may/ need to evaluate depth image values while -- performing image layout transitions. To accommodate this, instances of -- the 'SampleLocationsInfoEXT' structure /can/ be specified for each -- situation where an explicit or automatic layout transition has to take -- place. 'SampleLocationsInfoEXT' /can/ be chained from -- 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier' structures to provide -- sample locations for layout transitions performed by -- 'Vulkan.Core10.CommandBufferBuilding.cmdWaitEvents' and -- 'Vulkan.Core10.CommandBufferBuilding.cmdPipelineBarrier' calls, and -- 'RenderPassSampleLocationsBeginInfoEXT' /can/ be chained from -- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo' to provide -- sample locations for layout transitions performed implicitly by a render -- pass instance. -- -- == New Commands -- -- - 'cmdSetSampleLocationsEXT' -- -- - 'getPhysicalDeviceMultisamplePropertiesEXT' -- -- == New Structures -- -- - 'AttachmentSampleLocationsEXT' -- -- - 'MultisamplePropertiesEXT' -- -- - 'SampleLocationEXT' -- -- - 'SubpassSampleLocationsEXT' -- -- - Extending 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier', -- 'Vulkan.Core13.Promoted_From_VK_KHR_synchronization2.ImageMemoryBarrier2': -- -- - 'SampleLocationsInfoEXT' -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2': -- -- - 'PhysicalDeviceSampleLocationsPropertiesEXT' -- -- - Extending -- 'Vulkan.Core10.Pipeline.PipelineMultisampleStateCreateInfo': -- -- - 'PipelineSampleLocationsStateCreateInfoEXT' -- -- - Extending 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo': -- -- - 'RenderPassSampleLocationsBeginInfoEXT' -- -- == New Enum Constants -- -- - 'EXT_SAMPLE_LOCATIONS_EXTENSION_NAME' -- -- - 'EXT_SAMPLE_LOCATIONS_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.DynamicState.DynamicState': -- -- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT' -- -- - Extending -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.ImageCreateFlagBits': -- -- - 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT' -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT' -- -- == Version History -- -- - Revision 1, 2017-08-02 (Daniel Rakos) -- -- - Internal revisions -- -- == See Also -- -- 'AttachmentSampleLocationsEXT', 'MultisamplePropertiesEXT', -- 'PhysicalDeviceSampleLocationsPropertiesEXT', -- 'PipelineSampleLocationsStateCreateInfoEXT', -- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationEXT', -- 'SampleLocationsInfoEXT', 'SubpassSampleLocationsEXT', -- 'cmdSetSampleLocationsEXT', 'getPhysicalDeviceMultisamplePropertiesEXT' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_sample_locations Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_sample_locations ( cmdSetSampleLocationsEXT , getPhysicalDeviceMultisamplePropertiesEXT , SampleLocationEXT(..) , SampleLocationsInfoEXT(..) , AttachmentSampleLocationsEXT(..) , SubpassSampleLocationsEXT(..) , RenderPassSampleLocationsBeginInfoEXT(..) , PipelineSampleLocationsStateCreateInfoEXT(..) , PhysicalDeviceSampleLocationsPropertiesEXT(..) , MultisamplePropertiesEXT(..) , EXT_SAMPLE_LOCATIONS_SPEC_VERSION , pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION , EXT_SAMPLE_LOCATIONS_EXTENSION_NAME , pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME ) where import Vulkan.CStruct.Utils (FixedArray) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Data.Coerce (coerce) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.C.Types (CFloat) import Foreign.C.Types (CFloat(..)) import Foreign.C.Types (CFloat(CFloat)) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.CStruct.Utils (lowerArrayPtr) import Vulkan.NamedType ((:::)) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Handles (CommandBuffer) import Vulkan.Core10.Handles (CommandBuffer(..)) import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer)) import Vulkan.Core10.Handles (CommandBuffer_T) import Vulkan.Dynamic (DeviceCmds(pVkCmdSetSampleLocationsEXT)) import Vulkan.Core10.FundamentalTypes (Extent2D) import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDeviceMultisamplePropertiesEXT)) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits) import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits(..)) import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlags) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdSetSampleLocationsEXT :: FunPtr (Ptr CommandBuffer_T -> Ptr SampleLocationsInfoEXT -> IO ()) -> Ptr CommandBuffer_T -> Ptr SampleLocationsInfoEXT -> IO () -- | vkCmdSetSampleLocationsEXT - Set sample locations dynamically for a -- command buffer -- -- = Description -- -- This command sets the custom sample locations for subsequent drawing -- commands when the graphics pipeline is created with -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT' -- set in -- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@, -- and when the -- 'PipelineSampleLocationsStateCreateInfoEXT'::@sampleLocationsEnable@ -- property of the bound graphics pipeline is -- 'Vulkan.Core10.FundamentalTypes.TRUE'. Otherwise, this state is -- specified by the -- 'PipelineSampleLocationsStateCreateInfoEXT'::@sampleLocationsInfo@ -- values used to create the currently active pipeline. -- -- == Valid Usage -- -- - #VUID-vkCmdSetSampleLocationsEXT-sampleLocationsPerPixel-01529# The -- @sampleLocationsPerPixel@ member of @pSampleLocationsInfo@ /must/ -- equal the @rasterizationSamples@ member of the -- 'Vulkan.Core10.Pipeline.PipelineMultisampleStateCreateInfo' -- structure the bound graphics pipeline has been created with -- -- - #VUID-vkCmdSetSampleLocationsEXT-variableSampleLocations-01530# If -- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE' then the current render -- pass /must/ have been begun by specifying a -- 'RenderPassSampleLocationsBeginInfoEXT' structure whose -- @pPostSubpassSampleLocations@ member contains an element with a -- @subpassIndex@ matching the current subpass index and the -- @sampleLocationsInfo@ member of that element /must/ match the sample -- locations state pointed to by @pSampleLocationsInfo@ -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-parameter# -- @commandBuffer@ /must/ be a valid -- 'Vulkan.Core10.Handles.CommandBuffer' handle -- -- - #VUID-vkCmdSetSampleLocationsEXT-pSampleLocationsInfo-parameter# -- @pSampleLocationsInfo@ /must/ be a valid pointer to a valid -- 'SampleLocationsInfoEXT' structure -- -- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-recording# -- @commandBuffer@ /must/ be in the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-cmdpool# The -- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was -- allocated from /must/ support graphics operations -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- -- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that -- @commandBuffer@ was allocated from /must/ be externally synchronized -- -- == Command Properties -- -- \' -- -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> | -- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+ -- | Primary | Both | Graphics | -- | Secondary | | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'Vulkan.Core10.Handles.CommandBuffer', 'SampleLocationsInfoEXT' cmdSetSampleLocationsEXT :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer into which the command will be -- recorded. CommandBuffer -> -- | @pSampleLocationsInfo@ is the sample locations state to set. SampleLocationsInfoEXT -> io () cmdSetSampleLocationsEXT commandBuffer sampleLocationsInfo = liftIO . evalContT $ do let vkCmdSetSampleLocationsEXTPtr = pVkCmdSetSampleLocationsEXT (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) lift $ unless (vkCmdSetSampleLocationsEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetSampleLocationsEXT is null" Nothing Nothing let vkCmdSetSampleLocationsEXT' = mkVkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXTPtr pSampleLocationsInfo <- ContT $ withCStruct (sampleLocationsInfo) lift $ traceAroundEvent "vkCmdSetSampleLocationsEXT" (vkCmdSetSampleLocationsEXT' (commandBufferHandle (commandBuffer)) pSampleLocationsInfo) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetPhysicalDeviceMultisamplePropertiesEXT :: FunPtr (Ptr PhysicalDevice_T -> SampleCountFlagBits -> Ptr MultisamplePropertiesEXT -> IO ()) -> Ptr PhysicalDevice_T -> SampleCountFlagBits -> Ptr MultisamplePropertiesEXT -> IO () -- | vkGetPhysicalDeviceMultisamplePropertiesEXT - Report sample count -- specific multisampling capabilities of a physical device -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'MultisamplePropertiesEXT', 'Vulkan.Core10.Handles.PhysicalDevice', -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' getPhysicalDeviceMultisamplePropertiesEXT :: forall io . (MonadIO io) => -- | @physicalDevice@ is the physical device from which to query the -- additional multisampling capabilities. -- -- #VUID-vkGetPhysicalDeviceMultisamplePropertiesEXT-physicalDevice-parameter# -- @physicalDevice@ /must/ be a valid -- 'Vulkan.Core10.Handles.PhysicalDevice' handle PhysicalDevice -> -- | @samples@ is a -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value -- specifying the sample count to query capabilities for. -- -- #VUID-vkGetPhysicalDeviceMultisamplePropertiesEXT-samples-parameter# -- @samples@ /must/ be a valid -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value ("samples" ::: SampleCountFlagBits) -> io (MultisamplePropertiesEXT) getPhysicalDeviceMultisamplePropertiesEXT physicalDevice samples = liftIO . evalContT $ do let vkGetPhysicalDeviceMultisamplePropertiesEXTPtr = pVkGetPhysicalDeviceMultisamplePropertiesEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetPhysicalDeviceMultisamplePropertiesEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDeviceMultisamplePropertiesEXT is null" Nothing Nothing let vkGetPhysicalDeviceMultisamplePropertiesEXT' = mkVkGetPhysicalDeviceMultisamplePropertiesEXT vkGetPhysicalDeviceMultisamplePropertiesEXTPtr pPMultisampleProperties <- ContT (withZeroCStruct @MultisamplePropertiesEXT) lift $ traceAroundEvent "vkGetPhysicalDeviceMultisamplePropertiesEXT" (vkGetPhysicalDeviceMultisamplePropertiesEXT' (physicalDeviceHandle (physicalDevice)) (samples) (pPMultisampleProperties)) pMultisampleProperties <- lift $ peekCStruct @MultisamplePropertiesEXT pPMultisampleProperties pure $ (pMultisampleProperties) -- | VkSampleLocationEXT - Structure specifying the coordinates of a sample -- location -- -- = Description -- -- The domain space of the sample location coordinates has an upper-left -- origin within the pixel in framebuffer space. -- -- The values specified in a 'SampleLocationEXT' structure are always -- clamped to the implementation-dependent sample location coordinate range -- [@sampleLocationCoordinateRange@[0],@sampleLocationCoordinateRange@[1]] -- that /can/ be queried using -- 'PhysicalDeviceSampleLocationsPropertiesEXT'. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'SampleLocationsInfoEXT' data SampleLocationEXT = SampleLocationEXT { -- | @x@ is the horizontal coordinate of the sample’s location. x :: Float , -- | @y@ is the vertical coordinate of the sample’s location. y :: Float } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (SampleLocationEXT) #endif deriving instance Show SampleLocationEXT instance ToCStruct SampleLocationEXT where withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p) pokeCStruct p SampleLocationEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (x)) poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (y)) f cStructSize = 8 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (zero)) poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (zero)) f instance FromCStruct SampleLocationEXT where peekCStruct p = do x <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat)) y <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat)) pure $ SampleLocationEXT (coerce @CFloat @Float x) (coerce @CFloat @Float y) instance Storable SampleLocationEXT where sizeOf ~_ = 8 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero SampleLocationEXT where zero = SampleLocationEXT zero zero -- | VkSampleLocationsInfoEXT - Structure specifying a set of sample -- locations -- -- = Description -- -- This structure /can/ be used either to specify the sample locations to -- be used for rendering or to specify the set of sample locations an image -- subresource has been last rendered with for the purposes of layout -- transitions of depth\/stencil images created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT'. -- -- The sample locations in @pSampleLocations@ specify -- @sampleLocationsPerPixel@ number of sample locations for each pixel in -- the grid of the size specified in @sampleLocationGridSize@. The sample -- location for sample i at the pixel grid location (x,y) is taken from -- @pSampleLocations@[(x + y × @sampleLocationGridSize.width@) × -- @sampleLocationsPerPixel@ + i]. -- -- If the render pass has a fragment density map, the implementation will -- choose the sample locations for the fragment and the contents of -- @pSampleLocations@ /may/ be ignored. -- -- == Valid Usage -- -- - #VUID-VkSampleLocationsInfoEXT-sampleLocationsPerPixel-01526# -- @sampleLocationsPerPixel@ /must/ be a bit value that is set in -- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@sampleLocationSampleCounts@ -- -- - #VUID-VkSampleLocationsInfoEXT-sampleLocationsCount-01527# -- @sampleLocationsCount@ /must/ equal @sampleLocationsPerPixel@ × -- @sampleLocationGridSize.width@ × @sampleLocationGridSize.height@ -- -- == Valid Usage (Implicit) -- -- - #VUID-VkSampleLocationsInfoEXT-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT' -- -- - #VUID-VkSampleLocationsInfoEXT-pSampleLocations-parameter# If -- @sampleLocationsCount@ is not @0@, @pSampleLocations@ /must/ be a -- valid pointer to an array of @sampleLocationsCount@ -- 'SampleLocationEXT' structures -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'AttachmentSampleLocationsEXT', -- 'Vulkan.Core10.FundamentalTypes.Extent2D', -- 'PipelineSampleLocationsStateCreateInfoEXT', -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits', -- 'SampleLocationEXT', 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'SubpassSampleLocationsEXT', 'cmdSetSampleLocationsEXT' data SampleLocationsInfoEXT = SampleLocationsInfoEXT { -- | @sampleLocationsPerPixel@ is a -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value -- specifying the number of sample locations per pixel. sampleLocationsPerPixel :: SampleCountFlagBits , -- | @sampleLocationGridSize@ is the size of the sample location grid to -- select custom sample locations for. sampleLocationGridSize :: Extent2D , -- | @pSampleLocations@ is a pointer to an array of @sampleLocationsCount@ -- 'SampleLocationEXT' structures. sampleLocations :: Vector SampleLocationEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (SampleLocationsInfoEXT) #endif deriving instance Show SampleLocationsInfoEXT instance ToCStruct SampleLocationsInfoEXT where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p SampleLocationsInfoEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr SampleCountFlagBits)) (sampleLocationsPerPixel) lift $ poke ((p `plusPtr` 20 :: Ptr Extent2D)) (sampleLocationGridSize) lift $ poke ((p `plusPtr` 28 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (sampleLocations)) :: Word32)) pPSampleLocations' <- ContT $ allocaBytes @SampleLocationEXT ((Data.Vector.length (sampleLocations)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPSampleLocations' `plusPtr` (8 * (i)) :: Ptr SampleLocationEXT) (e)) (sampleLocations) lift $ poke ((p `plusPtr` 32 :: Ptr (Ptr SampleLocationEXT))) (pPSampleLocations') lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SampleCountFlagBits)) (zero) poke ((p `plusPtr` 20 :: Ptr Extent2D)) (zero) f instance FromCStruct SampleLocationsInfoEXT where peekCStruct p = do sampleLocationsPerPixel <- peek @SampleCountFlagBits ((p `plusPtr` 16 :: Ptr SampleCountFlagBits)) sampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 20 :: Ptr Extent2D)) sampleLocationsCount <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32)) pSampleLocations <- peek @(Ptr SampleLocationEXT) ((p `plusPtr` 32 :: Ptr (Ptr SampleLocationEXT))) pSampleLocations' <- generateM (fromIntegral sampleLocationsCount) (\i -> peekCStruct @SampleLocationEXT ((pSampleLocations `advancePtrBytes` (8 * (i)) :: Ptr SampleLocationEXT))) pure $ SampleLocationsInfoEXT sampleLocationsPerPixel sampleLocationGridSize pSampleLocations' instance Zero SampleLocationsInfoEXT where zero = SampleLocationsInfoEXT zero zero mempty -- | VkAttachmentSampleLocationsEXT - Structure specifying the sample -- locations state to use in the initial layout transition of attachments -- -- = Description -- -- If the image referenced by the framebuffer attachment at index -- @attachmentIndex@ was not created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT' -- then the values specified in @sampleLocationsInfo@ are ignored. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationsInfoEXT' data AttachmentSampleLocationsEXT = AttachmentSampleLocationsEXT { -- | @attachmentIndex@ is the index of the attachment for which the sample -- locations state is provided. -- -- #VUID-VkAttachmentSampleLocationsEXT-attachmentIndex-01531# -- @attachmentIndex@ /must/ be less than the @attachmentCount@ specified in -- 'Vulkan.Core10.Pass.RenderPassCreateInfo' the render pass specified by -- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo'::@renderPass@ -- was created with attachmentIndex :: Word32 , -- | @sampleLocationsInfo@ is the sample locations state to use for the -- layout transition of the given attachment from the initial layout of the -- attachment to the image layout specified for the attachment in the first -- subpass using it. -- -- #VUID-VkAttachmentSampleLocationsEXT-sampleLocationsInfo-parameter# -- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT' -- structure sampleLocationsInfo :: SampleLocationsInfoEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (AttachmentSampleLocationsEXT) #endif deriving instance Show AttachmentSampleLocationsEXT instance ToCStruct AttachmentSampleLocationsEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p AttachmentSampleLocationsEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (attachmentIndex) ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ()) lift $ f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (zero) ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ()) lift $ f instance FromCStruct AttachmentSampleLocationsEXT where peekCStruct p = do attachmentIndex <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32)) sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) pure $ AttachmentSampleLocationsEXT attachmentIndex sampleLocationsInfo instance Zero AttachmentSampleLocationsEXT where zero = AttachmentSampleLocationsEXT zero zero -- | VkSubpassSampleLocationsEXT - Structure specifying the sample locations -- state to use for layout transitions of attachments performed after a -- given subpass -- -- = Description -- -- If the image referenced by the depth\/stencil attachment used in the -- subpass identified by @subpassIndex@ was not created with -- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT' -- or if the subpass does not use a depth\/stencil attachment, and -- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@ -- is 'Vulkan.Core10.FundamentalTypes.TRUE' then the values specified in -- @sampleLocationsInfo@ are ignored. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationsInfoEXT' data SubpassSampleLocationsEXT = SubpassSampleLocationsEXT { -- | @subpassIndex@ is the index of the subpass for which the sample -- locations state is provided. -- -- #VUID-VkSubpassSampleLocationsEXT-subpassIndex-01532# @subpassIndex@ -- /must/ be less than the @subpassCount@ specified in -- 'Vulkan.Core10.Pass.RenderPassCreateInfo' the render pass specified by -- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo'::@renderPass@ -- was created with subpassIndex :: Word32 , -- | @sampleLocationsInfo@ is the sample locations state to use for the -- layout transition of the depth\/stencil attachment away from the image -- layout the attachment is used with in the subpass specified in -- @subpassIndex@. -- -- #VUID-VkSubpassSampleLocationsEXT-sampleLocationsInfo-parameter# -- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT' -- structure sampleLocationsInfo :: SampleLocationsInfoEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (SubpassSampleLocationsEXT) #endif deriving instance Show SubpassSampleLocationsEXT instance ToCStruct SubpassSampleLocationsEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p SubpassSampleLocationsEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (subpassIndex) ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ()) lift $ f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (zero) ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ()) lift $ f instance FromCStruct SubpassSampleLocationsEXT where peekCStruct p = do subpassIndex <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32)) sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) pure $ SubpassSampleLocationsEXT subpassIndex sampleLocationsInfo instance Zero SubpassSampleLocationsEXT where zero = SubpassSampleLocationsEXT zero zero -- | VkRenderPassSampleLocationsBeginInfoEXT - Structure specifying sample -- locations to use for the layout transition of custom sample locations -- compatible depth\/stencil attachments -- -- == Valid Usage (Implicit) -- -- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-sType-sType# @sType@ -- /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT' -- -- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-pAttachmentInitialSampleLocations-parameter# -- If @attachmentInitialSampleLocationsCount@ is not @0@, -- @pAttachmentInitialSampleLocations@ /must/ be a valid pointer to an -- array of @attachmentInitialSampleLocationsCount@ valid -- 'AttachmentSampleLocationsEXT' structures -- -- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-pPostSubpassSampleLocations-parameter# -- If @postSubpassSampleLocationsCount@ is not @0@, -- @pPostSubpassSampleLocations@ /must/ be a valid pointer to an array -- of @postSubpassSampleLocationsCount@ valid -- 'SubpassSampleLocationsEXT' structures -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'AttachmentSampleLocationsEXT', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'SubpassSampleLocationsEXT' data RenderPassSampleLocationsBeginInfoEXT = RenderPassSampleLocationsBeginInfoEXT { -- | @pAttachmentInitialSampleLocations@ is a pointer to an array of -- @attachmentInitialSampleLocationsCount@ 'AttachmentSampleLocationsEXT' -- structures specifying the attachment indices and their corresponding -- sample location state. Each element of -- @pAttachmentInitialSampleLocations@ /can/ specify the sample location -- state to use in the automatic layout transition performed to transition -- a depth\/stencil attachment from the initial layout of the attachment to -- the image layout specified for the attachment in the first subpass using -- it. attachmentInitialSampleLocations :: Vector AttachmentSampleLocationsEXT , -- | @pPostSubpassSampleLocations@ is a pointer to an array of -- @postSubpassSampleLocationsCount@ 'SubpassSampleLocationsEXT' structures -- specifying the subpass indices and their corresponding sample location -- state. Each element of @pPostSubpassSampleLocations@ /can/ specify the -- sample location state to use in the automatic layout transition -- performed to transition the depth\/stencil attachment used by the -- specified subpass to the image layout specified in a dependent subpass -- or to the final layout of the attachment in case the specified subpass -- is the last subpass using that attachment. In addition, if -- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@ -- is 'Vulkan.Core10.FundamentalTypes.FALSE', each element of -- @pPostSubpassSampleLocations@ /must/ specify the sample location state -- that matches the sample locations used by all pipelines that will be -- bound to a command buffer during the specified subpass. If -- @variableSampleLocations@ is 'Vulkan.Core10.FundamentalTypes.TRUE', the -- sample locations used for rasterization do not depend on -- @pPostSubpassSampleLocations@. postSubpassSampleLocations :: Vector SubpassSampleLocationsEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (RenderPassSampleLocationsBeginInfoEXT) #endif deriving instance Show RenderPassSampleLocationsBeginInfoEXT instance ToCStruct RenderPassSampleLocationsBeginInfoEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p RenderPassSampleLocationsBeginInfoEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (attachmentInitialSampleLocations)) :: Word32)) pPAttachmentInitialSampleLocations' <- ContT $ allocaBytes @AttachmentSampleLocationsEXT ((Data.Vector.length (attachmentInitialSampleLocations)) * 48) Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPAttachmentInitialSampleLocations' `plusPtr` (48 * (i)) :: Ptr AttachmentSampleLocationsEXT) (e) . ($ ())) (attachmentInitialSampleLocations) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr AttachmentSampleLocationsEXT))) (pPAttachmentInitialSampleLocations') lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (postSubpassSampleLocations)) :: Word32)) pPPostSubpassSampleLocations' <- ContT $ allocaBytes @SubpassSampleLocationsEXT ((Data.Vector.length (postSubpassSampleLocations)) * 48) Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPPostSubpassSampleLocations' `plusPtr` (48 * (i)) :: Ptr SubpassSampleLocationsEXT) (e) . ($ ())) (postSubpassSampleLocations) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr SubpassSampleLocationsEXT))) (pPPostSubpassSampleLocations') lift $ f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct RenderPassSampleLocationsBeginInfoEXT where peekCStruct p = do attachmentInitialSampleLocationsCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pAttachmentInitialSampleLocations <- peek @(Ptr AttachmentSampleLocationsEXT) ((p `plusPtr` 24 :: Ptr (Ptr AttachmentSampleLocationsEXT))) pAttachmentInitialSampleLocations' <- generateM (fromIntegral attachmentInitialSampleLocationsCount) (\i -> peekCStruct @AttachmentSampleLocationsEXT ((pAttachmentInitialSampleLocations `advancePtrBytes` (48 * (i)) :: Ptr AttachmentSampleLocationsEXT))) postSubpassSampleLocationsCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pPostSubpassSampleLocations <- peek @(Ptr SubpassSampleLocationsEXT) ((p `plusPtr` 40 :: Ptr (Ptr SubpassSampleLocationsEXT))) pPostSubpassSampleLocations' <- generateM (fromIntegral postSubpassSampleLocationsCount) (\i -> peekCStruct @SubpassSampleLocationsEXT ((pPostSubpassSampleLocations `advancePtrBytes` (48 * (i)) :: Ptr SubpassSampleLocationsEXT))) pure $ RenderPassSampleLocationsBeginInfoEXT pAttachmentInitialSampleLocations' pPostSubpassSampleLocations' instance Zero RenderPassSampleLocationsBeginInfoEXT where zero = RenderPassSampleLocationsBeginInfoEXT mempty mempty -- | VkPipelineSampleLocationsStateCreateInfoEXT - Structure specifying -- sample locations for a pipeline -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', 'SampleLocationsInfoEXT', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PipelineSampleLocationsStateCreateInfoEXT = PipelineSampleLocationsStateCreateInfoEXT { -- | @sampleLocationsEnable@ controls whether custom sample locations are -- used. If @sampleLocationsEnable@ is -- 'Vulkan.Core10.FundamentalTypes.FALSE', the default sample locations are -- used and the values specified in @sampleLocationsInfo@ are ignored. sampleLocationsEnable :: Bool , -- | @sampleLocationsInfo@ is the sample locations to use during -- rasterization if @sampleLocationsEnable@ is -- 'Vulkan.Core10.FundamentalTypes.TRUE' and the graphics pipeline is not -- created with -- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT'. -- -- #VUID-VkPipelineSampleLocationsStateCreateInfoEXT-sampleLocationsInfo-parameter# -- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT' -- structure sampleLocationsInfo :: SampleLocationsInfoEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PipelineSampleLocationsStateCreateInfoEXT) #endif deriving instance Show PipelineSampleLocationsStateCreateInfoEXT instance ToCStruct PipelineSampleLocationsStateCreateInfoEXT where withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p) pokeCStruct p PipelineSampleLocationsStateCreateInfoEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (sampleLocationsEnable)) ContT $ pokeCStruct ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ()) lift $ f cStructSize = 64 cStructAlignment = 8 pokeZeroCStruct p f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) ContT $ pokeCStruct ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ()) lift $ f instance FromCStruct PipelineSampleLocationsStateCreateInfoEXT where peekCStruct p = do sampleLocationsEnable <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT)) pure $ PipelineSampleLocationsStateCreateInfoEXT (bool32ToBool sampleLocationsEnable) sampleLocationsInfo instance Zero PipelineSampleLocationsStateCreateInfoEXT where zero = PipelineSampleLocationsStateCreateInfoEXT zero zero -- | VkPhysicalDeviceSampleLocationsPropertiesEXT - Structure describing -- sample location limits that can be supported by an implementation -- -- = Description -- -- If the 'PhysicalDeviceSampleLocationsPropertiesEXT' structure is -- included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2', -- it is filled in with each corresponding implementation-dependent -- property. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.FundamentalTypes.Extent2D', -- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlags', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceSampleLocationsPropertiesEXT = PhysicalDeviceSampleLocationsPropertiesEXT { -- | #limits-sampleLocationSampleCounts# @sampleLocationSampleCounts@ is a -- bitmask of 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' -- indicating the sample counts supporting custom sample locations. sampleLocationSampleCounts :: SampleCountFlags , -- | #limits-maxSampleLocationGridSize# @maxSampleLocationGridSize@ is the -- maximum size of the pixel grid in which sample locations /can/ vary that -- is supported for all sample counts in @sampleLocationSampleCounts@. maxSampleLocationGridSize :: Extent2D , -- | #limits-sampleLocationCoordinateRange# -- @sampleLocationCoordinateRange@[2] is the range of supported sample -- location coordinates. sampleLocationCoordinateRange :: (Float, Float) , -- | #limits-sampleLocationSubPixelBits# @sampleLocationSubPixelBits@ is the -- number of bits of subpixel precision for sample locations. sampleLocationSubPixelBits :: Word32 , -- | #limits-variableSampleLocations# @variableSampleLocations@ specifies -- whether the sample locations used by all pipelines that will be bound to -- a command buffer during a subpass /must/ match. If set to -- 'Vulkan.Core10.FundamentalTypes.TRUE', the implementation supports -- variable sample locations in a subpass. If set to -- 'Vulkan.Core10.FundamentalTypes.FALSE', then the sample locations /must/ -- stay constant in each subpass. variableSampleLocations :: Bool } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceSampleLocationsPropertiesEXT) #endif deriving instance Show PhysicalDeviceSampleLocationsPropertiesEXT instance ToCStruct PhysicalDeviceSampleLocationsPropertiesEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceSampleLocationsPropertiesEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SampleCountFlags)) (sampleLocationSampleCounts) poke ((p `plusPtr` 20 :: Ptr Extent2D)) (maxSampleLocationGridSize) let pSampleLocationCoordinateRange' = lowerArrayPtr ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat))) case (sampleLocationCoordinateRange) of (e0, e1) -> do poke (pSampleLocationCoordinateRange' :: Ptr CFloat) (CFloat (e0)) poke (pSampleLocationCoordinateRange' `plusPtr` 4 :: Ptr CFloat) (CFloat (e1)) poke ((p `plusPtr` 36 :: Ptr Word32)) (sampleLocationSubPixelBits) poke ((p `plusPtr` 40 :: Ptr Bool32)) (boolToBool32 (variableSampleLocations)) f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr SampleCountFlags)) (zero) poke ((p `plusPtr` 20 :: Ptr Extent2D)) (zero) let pSampleLocationCoordinateRange' = lowerArrayPtr ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat))) case ((zero, zero)) of (e0, e1) -> do poke (pSampleLocationCoordinateRange' :: Ptr CFloat) (CFloat (e0)) poke (pSampleLocationCoordinateRange' `plusPtr` 4 :: Ptr CFloat) (CFloat (e1)) poke ((p `plusPtr` 36 :: Ptr Word32)) (zero) poke ((p `plusPtr` 40 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceSampleLocationsPropertiesEXT where peekCStruct p = do sampleLocationSampleCounts <- peek @SampleCountFlags ((p `plusPtr` 16 :: Ptr SampleCountFlags)) maxSampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 20 :: Ptr Extent2D)) let psampleLocationCoordinateRange = lowerArrayPtr @CFloat ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat))) sampleLocationCoordinateRange0 <- peek @CFloat ((psampleLocationCoordinateRange `advancePtrBytes` 0 :: Ptr CFloat)) sampleLocationCoordinateRange1 <- peek @CFloat ((psampleLocationCoordinateRange `advancePtrBytes` 4 :: Ptr CFloat)) sampleLocationSubPixelBits <- peek @Word32 ((p `plusPtr` 36 :: Ptr Word32)) variableSampleLocations <- peek @Bool32 ((p `plusPtr` 40 :: Ptr Bool32)) pure $ PhysicalDeviceSampleLocationsPropertiesEXT sampleLocationSampleCounts maxSampleLocationGridSize (((coerce @CFloat @Float sampleLocationCoordinateRange0), (coerce @CFloat @Float sampleLocationCoordinateRange1))) sampleLocationSubPixelBits (bool32ToBool variableSampleLocations) instance Storable PhysicalDeviceSampleLocationsPropertiesEXT where sizeOf ~_ = 48 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceSampleLocationsPropertiesEXT where zero = PhysicalDeviceSampleLocationsPropertiesEXT zero zero (zero, zero) zero zero -- | VkMultisamplePropertiesEXT - Structure returning information about -- sample count specific additional multisampling capabilities -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>, -- 'Vulkan.Core10.FundamentalTypes.Extent2D', -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'getPhysicalDeviceMultisamplePropertiesEXT' data MultisamplePropertiesEXT = MultisamplePropertiesEXT { -- | @maxSampleLocationGridSize@ is the maximum size of the pixel grid in -- which sample locations /can/ vary. maxSampleLocationGridSize :: Extent2D } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (MultisamplePropertiesEXT) #endif deriving instance Show MultisamplePropertiesEXT instance ToCStruct MultisamplePropertiesEXT where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p MultisamplePropertiesEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Extent2D)) (maxSampleLocationGridSize) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Extent2D)) (zero) f instance FromCStruct MultisamplePropertiesEXT where peekCStruct p = do maxSampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 16 :: Ptr Extent2D)) pure $ MultisamplePropertiesEXT maxSampleLocationGridSize instance Storable MultisamplePropertiesEXT where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero MultisamplePropertiesEXT where zero = MultisamplePropertiesEXT zero type EXT_SAMPLE_LOCATIONS_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_EXT_SAMPLE_LOCATIONS_SPEC_VERSION" pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION :: forall a . Integral a => a pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION = 1 type EXT_SAMPLE_LOCATIONS_EXTENSION_NAME = "VK_EXT_sample_locations" -- No documentation found for TopLevel "VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME" pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME = "VK_EXT_sample_locations"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_sample_locations.hs
Haskell
bsd-3-clause
52,025
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Main where import Lib import Resources import Authentication import Control.Applicative (Applicative) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (runNoLoggingT, runStdoutLoggingT) import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT) import Control.Monad.Trans.Class (MonadTrans, lift) import Data.Aeson (Value (Null), (.=), object) import Data.Default (def) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy (Text, unpack) import qualified Database.Persist as DB import qualified Database.Persist.Postgresql as DB import Network.Wai import Network.Wai.Handler.Warp (Settings, defaultSettings, setFdCacheDuration, setPort) import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import System.Environment (lookupEnv) import System.Directory (createDirectory) import Web.Heroku (parseDatabaseUrl) import Web.Scotty.Trans import Codec.MIME.Base64 (decodeToString) import Network.Wai.Middleware.Cors (simpleCors) import Data.CaseInsensitive (CI) import Data.ByteString as B import Web.ClientSession main :: IO () main = do c <- getConfig migrateSchema c runApplication c migrateSchema :: Config -> IO () migrateSchema c = liftIO $ flip DB.runSqlPersistMPool (pool c) $ DB.runMigration migrateAll getConfig :: IO Config getConfig = do e <- getEnvironment p <- getPool e key <- getDefaultKey return Config { environment = e , pool = p , key = key } getEnvironment :: IO Environment getEnvironment = fmap (maybe Development read) (lookupEnv "SCOTTY_ENV") getPool :: Environment -> IO DB.ConnectionPool getPool e = do s <- getConnectionString e let n = getConnectionSize e case e of Development -> runStdoutLoggingT (DB.createPostgresqlPool s n) Production -> runStdoutLoggingT (DB.createPostgresqlPool s n) Test -> runNoLoggingT (DB.createPostgresqlPool s n) getConnectionString :: Environment -> IO DB.ConnectionString getConnectionString e = do m <- lookupEnv "DATABASE_URL" let s = case m of Nothing -> getDefaultConnectionString e Just u -> createConnectionString (parseDatabaseUrl u) return s getDefaultConnectionString :: Environment -> DB.ConnectionString getDefaultConnectionString e = let n = case e of Development -> "lift_development" Production -> "lift_production" Test -> "lift_test" in createConnectionString [ ("host", "localhost") , ("port", "5432") , ("user", "postgres") , ("dbname", n) ] createConnectionString :: [(T.Text, T.Text)] -> DB.ConnectionString createConnectionString l = let f (k, v) = T.concat [k, "=", v] in encodeUtf8 (T.unwords (Prelude.map f l)) getConnectionSize :: Environment -> Int getConnectionSize Development = 1 getConnectionSize Production = 8 getConnectionSize Test = 1 runApplication :: Config -> IO () runApplication c = do o <- getOptions (environment c) let r m = runReaderT (runConfigM m) c app = application c scottyOptsT o r app getOptions :: Environment -> IO Options getOptions e = do s <- getSettings e return def { settings = s , verbose = case e of Development -> 1 Production -> 0 Test -> 0 } getSettings :: Environment -> IO Settings getSettings e = do let s = defaultSettings s' = case e of Development -> setFdCacheDuration 0 s Production -> s Test -> s m <- getPort let s'' = case m of Nothing -> s' Just p -> setPort p s' return s'' getPort :: IO (Maybe Int) getPort = (fmap . fmap) read (lookupEnv "SCOTTY_PORT") application :: Config -> ScottyT Error ConfigM () application c = do let e = environment c middleware (loggingM e) let headerName = "Access-Control-Allow-Headers" middleware $ modifyResponse $ mapResponseHeaders (\headers -> headers ++ [(headerName, "Content-Type, authorization"), ("Access-Control-Allow-Methods", "GET, POST, OPTIONS"), ("Access-Control-Allow-Origin", "*")]) defaultHandler (defaultH e) get "/" home post "/signin" $ authenticate >>= signinA get "/logout" logoutA get "/lifts" $ authenticate >>= getLiftsA post "/lifts" $ authenticate >>= postLiftsA post "/users" postUsersA options "/users" optionsA options (regex "/lifts") optionsA notFound notFoundA loggingM :: Environment -> Middleware loggingM Development = logStdoutDev loggingM Production = logStdout loggingM Test = id toKey :: DB.ToBackendKey DB.SqlBackend a => Integer -> DB.Key a toKey i = DB.toSqlKey (fromIntegral (i :: Integer))
clample/lift-tracker
app/Main.hs
Haskell
bsd-3-clause
4,681
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances, OverlappingInstances #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE CPP #-} module Narradar.Types.DPIdentifiers (module Narradar.Types.DPIdentifiers, ArityId(..), StringId ) where import Control.Applicative import Control.Arrow (first) import Control.DeepSeq import Data.Foldable (Foldable(..)) import Data.Hashable import Data.Traversable (Traversable(..)) import Data.Typeable import Prelude import Narradar.Types.Term import Narradar.Framework.Ppr #ifdef HOOD import Debug.Hood.Observe #endif type Id = DPIdentifier StringId type DP a = RuleN (DPIdentifier a) -- ----------------------- -- Concrete DP Identifiers -- ----------------------- data DPIdentifier a = IdFunction a | IdDP a | AnyIdentifier deriving (Ord, Typeable, Functor, Foldable, Traversable) instance Eq a => Eq (DPIdentifier a) where IdFunction f1 == IdFunction f2 = f1 == f2 IdDP f1 == IdDP f2 = f1 == f2 AnyIdentifier == _ = True _ == AnyIdentifier = True _ == _ = False instance HasArity a => HasArity (DPIdentifier a) where getIdArity (IdFunction f) = getIdArity f getIdArity (IdDP f) = getIdArity f getIdArity AnyIdentifier = 0 instance Pretty (DPIdentifier a) => Show (DPIdentifier a) where show = show . pPrint instance Pretty (DPIdentifier String) where pPrint (IdFunction f) = text f pPrint (IdDP n) = text n <> text "#" instance Pretty a => Pretty (DPIdentifier a) where pPrint (IdFunction f) = pPrint f pPrint (IdDP n) = pPrint n <> text "#" instance NFData a => NFData (DPIdentifier a) where rnf (IdFunction f) = rnf f rnf (IdDP f) = rnf f rnf AnyIdentifier = () instance Hashable a => Hashable (DPIdentifier a) where hash (IdFunction f) = hash f hash (IdDP f) = combine 1 (hash f) #ifdef HOOD instance Observable id => Observable (DPIdentifier id) where observer (IdFunction a) = send "IdFunction" (return IdFunction << a) observer (IdDP a) = send "IdDP" (return IdDP << a) #endif -- ------------ -- DP Symbols -- ------------ class DPSymbol s where markDPSymbol, unmarkDPSymbol :: s -> s isDPSymbol :: s -> Bool instance DPSymbol (DPIdentifier id) where markDPSymbol (IdFunction f) = IdDP f markDPSymbol f = f unmarkDPSymbol (IdDP n) = IdFunction n unmarkDPSymbol n = n isDPSymbol (IdDP _ ) = True isDPSymbol _ = False functionSymbol = IdFunction; dpSymbol = IdDP symbol (IdFunction f) = f; symbol(IdDP f) = f --markDP, unmarkDP :: (MapId t, Functor (t id), DPSymbol id) => Term (t id) v -> Term (t id) v markDP = evalTerm return (Impure . mapId markDPSymbol) unmarkDP = evalTerm return (Impure . mapId unmarkDPSymbol) returnDP = foldTerm return (Impure . mapId IdFunction) --unmarkDPRule, markDPRule :: Rule t v -> Rule t v markDPRule = fmap markDP unmarkDPRule = fmap unmarkDP
pepeiborra/narradar
src/Narradar/Types/DPIdentifiers.hs
Haskell
bsd-3-clause
3,373
module Lambda.Evaluator.Debug where import DeepControl.Applicative import DeepControl.Monad import DeepControl.MonadTrans import Lambda.Evaluator.Eval import Lambda.Compiler import Lambda.Parser (readSExpr) import Lambda.Action import Lambda.Convertor import Lambda.Debug import Lambda.DataType import Lambda.DataType.Error.Eval (EvalError) import qualified Lambda.DataType.Error.Eval as EErr import qualified Lambda.DataType.PatternMatch as PM -- for debug import Debug.Trace ---------------------------------------------------------------------- -- unittest ---------------------------------------------------------------------- evalUnitTest :: Term -> Lambda ReturnT evalUnitTest name = (*:) $ RETURN $ META ("(evalUnitTest "++ show name ++")") $ f (show name) where f :: Name -> Term -> Lambda ReturnT f name unit@(LIST g msp) = localMSPBy msp $ do let xs = toList g str <- rec (length xs, 0, 0, 0, "") $ xs <$| \(TPL (TUPLE [expr, answer]) msp) -> (expr, answer, msp) liftIO $ putStrLn str (*:) VOID where rec :: (Int, Int, Int, Int, String) -> [(Term, Term, MSP)] -> Lambda String rec (cases, tried, 0, 0, "") [] = (*:) $ "unittest ["++ name ++"] - "++ "Cases: "++ show cases ++" "++ "Tried: "++ show tried ++" "++ "Errors: 0 "++ "Failures: 0" rec (cases, tried, errors, failures, mes) [] = (*:) $ "////////////////////////////////////////////////////////////////////"++"\n"++ "/// - unittest ["++ name ++"]"++"\n"++ mes++ "/// - "++ "Cases: "++ show cases ++" "++ "Tried: "++ show tried ++" "++ "Errors: "++ show errors ++" "++ "Failures: "++ show failures ++"\n"++ "/// - unittest ["++ name ++"]"++"\n"++ "////////////////////////////////////////////////////////////////////" rec (cases, tried, errors, failures, mes) ((term, answer, msp):xs) = localMSPBy msp $ catch $ do expr <- restore term v <- thisEval_ term if show v /= show answer then do answer <- restore answer v <- restore v let str1 = "/// ### failured in: "++ name ++": at "++ showMSP msp ++"\n" str2 = "/// tried: "++ show expr ++"\n"++ "/// expected: "++ show answer ++"\n"++ "/// but got: "++ show v ++"\n" rec (cases, tried+1, errors, failures+1, mes ++ str1 ++ str2) xs else do rec (cases, tried+1, errors, failures, mes) xs where catch x = x `catchError` \e -> do let str = "/// ### errored in: "++ name ++": at "++ showMSP msp ++"\n" ++ (show e >- lines >- foldr (\line acc -> "/// "++ line ++"\n"++ acc) "") ++"/// \n" rec (cases, tried+1, errors+1, failures, mes ++ str) xs showMSP :: MSP -> String showMSP Nothing = "---" showMSP (Just sp) = show sp --------------------------------------------------------------------------------------- -- show --------------------------------------------------------------------------------------- evalShowSExpr :: Term -> Lambda ReturnT evalShowSExpr t = do case readSExpr (show t) of Left err -> liftIO $ putStrLn $ "evalDesugar: "++ show err Right (s, []) -> liftIO $ putStrLn $ show (convert s :: SExpr_) Right (s, rest) -> liftIO $ putStrLn $ "evalDesugar: rest: "++ rest (*:) VOID evalShowExpr :: Term -> Lambda ReturnT evalShowExpr t = do case readSExpr (show t) of Left err -> liftIO $ putStrLn $ "evalDesugar: "++ show err Right (s, []) -> do e <- s >- desugarSExpr liftIO $ putStrLn $ show (convert e :: Expr_) Right (s, rest) -> liftIO $ putStrLn $ "evalDesugar: rest: "++ rest (*:) VOID --------------------------------------------------------------------------------------- -- misc --------------------------------------------------------------------------------------- evalShowContext :: Lambda ReturnT evalShowContext = do showContext "---" (*:) VOID evalShowDef :: Lambda ReturnT evalShowDef = do showDef "---" (*:) VOID evalShowDef_ :: Lambda ReturnT evalShowDef_ = do showDef_ "---" (*:) VOID
ocean0yohsuke/Simply-Typed-Lambda
src/Lambda/Evaluator/Debug.hs
Haskell
bsd-3-clause
4,535
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE FunctionalDependencies #-} -- data declarations that are empty {-# LANGUAGE EmptyDataDecls #-} module Symengine.Internal ( cIntToEnum, cIntFromEnum, mkForeignPtr, Wrapped(..), with2, with3, with4, CBasicSym, CVecBasic, SymengineException(NoException, RuntimeError, DivByZero, NotImplemented, DomainError, ParseError), forceException, throwOnSymIntException ) where import Prelude import Foreign.C.Types import Foreign.Ptr import Foreign.C.String import Foreign.Storable import Foreign.Marshal.Array import Foreign.Marshal.Alloc import Foreign.ForeignPtr import Control.Applicative import Control.Monad -- for foldM import System.IO.Unsafe import Control.Monad import GHC.Real import Control.Exception import Data.Typeable data SymengineException = NoException | RuntimeError | DivByZero | NotImplemented | DomainError | ParseError deriving (Show, Enum, Eq, Typeable) instance Exception SymengineException -- interpret the CInt as a SymengineException, and -- throw if it is actually an error throwOnSymIntException :: CInt -> IO () throwOnSymIntException i = forceException . cIntToEnum $ i forceException :: SymengineException -> IO () forceException exception = case exception of NoException -> return () error @ _ -> throwIO error cIntToEnum :: Enum a => CInt -> a cIntToEnum = toEnum . fromIntegral cIntFromEnum :: Enum a => a -> CInt cIntFromEnum = fromIntegral . fromEnum -- |given a raw pointer IO (Ptr a) and a destructor function pointer, make a -- foreign pointer mkForeignPtr :: (IO (Ptr a)) -> FunPtr (Ptr a -> IO ()) -> IO (ForeignPtr a) mkForeignPtr cons des = do rawptr <- cons finalized <- newForeignPtr des rawptr return finalized class Wrapped o i | o -> i where with :: o -> (Ptr i -> IO a) -> IO a with2 :: Wrapped o1 i1 => Wrapped o2 i2 => o1 -> o2 -> (Ptr i1 -> Ptr i2 -> IO a) -> IO a with2 o1 o2 f = with o1 (\p1 -> with o2 (\p2 -> f p1 p2)) with3 :: Wrapped o1 i1 => Wrapped o2 i2 => Wrapped o3 i3 => o1 -> o2 -> o3 -> (Ptr i1 -> Ptr i2 -> Ptr i3 -> IO a) -> IO a with3 o1 o2 o3 f = with2 o1 o2 (\p1 p2 -> with o3 (\p3 -> f p1 p2 p3)) with4:: Wrapped o1 i1 => Wrapped o2 i2 => Wrapped o3 i3 => Wrapped o4 i4 => o1 -> o2 -> o3 -> o4 -> (Ptr i1 -> Ptr i2 -> Ptr i3 -> Ptr i4 -> IO a) -> IO a with4 o1 o2 o3 o4 f = with o1 (\p1 -> with3 o2 o3 o4 (\p2 p3 p4 -> f p1 p2 p3 p4)) -- BasicSym data CBasicSym -- VecBasic data CVecBasic -- CDenseMatrix
bollu/symengine.hs-1
src/Symengine/Internal.hs
Haskell
mit
2,666
-- HACKERRANK: String-o-Permute -- https://www.hackerrank.com/challenges/string-o-permute module Main where import qualified Control.Monad as M solve :: String -> String solve [] = [] solve (x1:x2:xs) = x2:x1:(solve xs) main :: IO () main = getLine >>= \tStr -> M.replicateM_ ((read::String->Int) tStr) (getLine >>= \l -> putStrLn (solve l))
everyevery/programming_study
hackerrank/functional/string-o-permute/string-o-permute.hs
Haskell
mit
348
------------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- Chapter 1 -- -- The Pictures example code is given in the file Pitures.hs. -- This file can be used by importing it; more details are given in -- Chapter 2. -- ------------------------------------------------------------------------- module Chapter1 where import Craft.Pictures hiding (rotate) -- A first definition, of the integer value, size. size :: Integer size = 12+13 -- Some definitions using Pictures. -- Inverting the colour of the horse picture, ... blackHorse :: Picture blackHorse = invertColour horse -- ... rotating the horse picture, ... rotateHorse :: Picture rotateHorse = flipH (flipV horse) -- Some function definitions. -- To square an integer, ... square :: Integer -> Integer square n = n*n -- ... to double an integer, and ... double :: Integer -> Integer double n = 2*n -- ... to rotate a picture we can perform the two reflections, -- and so we define rotate :: Picture -> Picture rotate pic = flipH (flipV pic) -- A different definition of rotateHorse can use rotate rotateHorse1 :: Picture rotateHorse1 = rotate horse -- where the new definition is of a different name: you can't change a definition -- in a script. -- Defining rotate a different way, as a composition of functions; see the -- diagram in the book for a picture of what's going on. rotate1 :: Picture -> Picture rotate1 = flipH . flipV -- Pictures -- The definitions of the functions modelling pictures are in the file -- Pictures.hs. -- Tests and properties -- The functions test_rotate, prop_rotate etc are in the Pictures.hs module
Numberartificial/workflow
snipets/src/craft/Chapter1.hs
Haskell
mit
1,751