code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE TypeOperators, TypeFamilies #-} {-# LANGUAGE AllowAmbiguousTypes #-} -- The type of 'empty' is indeed ambiguous module T2544 where data (:|:) a b = Inl a | Inr b class Ix i where type IxMap i :: * -> * empty :: IxMap i [Int] data BiApp a b c = BiApp (a c) (b c) instance (Ix l, Ix r) => Ix (l :|: r) where type IxMap (l :|: r) = BiApp (IxMap l) (IxMap r) empty = BiApp empty empty -- [W] w1: a c ~ IxMap ii1 [Int] (from first 'empty') -- [W] w2: b c ~ IxMap ii2 [Int] (from second 'empty') -- [W] w3: BiApp a b c ~ IxMap (l :|: r) [Int] (from call of BiApp -- ~ BiApp (IxMap l) (IxMap r) [Int] -- If we process w3 first, we'll rewrite it with w1, w2 -- yielding two constraints (Ix io ~ IxMap l, Ix i1 ~ IxMap r) -- both with location of w3. Then we report just one of them, -- because we suppress multiple errors from the same location -- -- But if we process w1,w2 first, we'll get the same constraints -- but this time with different locations.
urbanslug/ghc
testsuite/tests/indexed-types/should_fail/T2544.hs
bsd-3-clause
1,063
0
8
304
168
100
68
11
0
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- {-# LANGUAGE OverloadedStrings #-} import qualified Calculator import Calculator_Iface import Tutorial_Types import SharedService_Iface import Shared_Types import Thrift import Thrift.Protocol.Binary import Thrift.Transport import Thrift.Server import Data.Int import Data.String import Data.Maybe import Text.Printf import Control.Exception (throw) import Control.Concurrent.MVar import qualified Data.Map as M import Data.Map ((!)) import Data.Monoid data CalculatorHandler = CalculatorHandler {mathLog :: MVar (M.Map Int32 SharedStruct)} newCalculatorHandler = do log <- newMVar mempty return $ CalculatorHandler log instance SharedService_Iface CalculatorHandler where getStruct self k = do myLog <- readMVar (mathLog self) return $ (myLog ! k) instance Calculator_Iface CalculatorHandler where ping _ = print "ping()" add _ n1 n2 = do printf "add(%d,%d)\n" n1 n2 return (n1 + n2) calculate self mlogid mwork = do printf "calculate(%d, %s)\n" logid (show work) let val = case op work of ADD -> num1 work + num2 work SUBTRACT -> num1 work - num2 work MULTIPLY -> num1 work * num2 work DIVIDE -> if num2 work == 0 then throw $ InvalidOperation { invalidOperation_whatOp = fromIntegral $ fromEnum $ op work, invalidOperation_why = "Cannot divide by 0" } else num1 work `div` num2 work let logEntry = SharedStruct logid (fromString $ show $ val) modifyMVar_ (mathLog self) $ return .(M.insert logid logEntry) return $! val where -- stupid dynamic languages f'ing it up num1 = work_num1 num2 = work_num2 op = work_op logid = mlogid work = mwork zip _ = print "zip()" main = do handler <- newCalculatorHandler print "Starting the server..." runBasicServer handler Calculator.process 9090 print "done."
jcgruenhage/dendrite
vendor/src/github.com/apache/thrift/tutorial/hs/HaskellServer.hs
apache-2.0
2,972
10
16
848
553
294
259
64
1
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Com.Mysql.Cj.Mysqlx.Protobuf.Open.Condition.ConditionOperation (ConditionOperation(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data ConditionOperation = EXPECT_OP_SET | EXPECT_OP_UNSET deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable ConditionOperation instance Prelude'.Bounded ConditionOperation where minBound = EXPECT_OP_SET maxBound = EXPECT_OP_UNSET instance P'.Default ConditionOperation where defaultValue = EXPECT_OP_SET toMaybe'Enum :: Prelude'.Int -> P'.Maybe ConditionOperation toMaybe'Enum 0 = Prelude'.Just EXPECT_OP_SET toMaybe'Enum 1 = Prelude'.Just EXPECT_OP_UNSET toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum ConditionOperation where fromEnum EXPECT_OP_SET = 0 fromEnum EXPECT_OP_UNSET = 1 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Open.Condition.ConditionOperation") . toMaybe'Enum succ EXPECT_OP_SET = EXPECT_OP_UNSET succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Open.Condition.ConditionOperation" pred EXPECT_OP_UNSET = EXPECT_OP_SET pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.Open.Condition.ConditionOperation" instance P'.Wire ConditionOperation where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB ConditionOperation instance P'.MessageAPI msg' (msg' -> ConditionOperation) ConditionOperation where getVal m' f' = f' m' instance P'.ReflectEnum ConditionOperation where reflectEnum = [(0, "EXPECT_OP_SET", EXPECT_OP_SET), (1, "EXPECT_OP_UNSET", EXPECT_OP_UNSET)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Mysqlx.Expect.Open.Condition.ConditionOperation") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "Open", "Condition"] "ConditionOperation") ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "Open", "Condition", "ConditionOperation.hs"] [(0, "EXPECT_OP_SET"), (1, "EXPECT_OP_UNSET")] instance P'.TextType ConditionOperation where tellT = P'.tellShow getT = P'.getRead
naoto-ogawa/h-xproto-mysql
src/Com/Mysql/Cj/Mysqlx/Protobuf/Open/Condition/ConditionOperation.hs
mit
2,917
0
11
466
645
357
288
59
1
{-# htermination maxFM :: FiniteMap Bool b -> Maybe Bool #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_maxFM_8.hs
mit
78
0
3
13
5
3
2
1
0
module Main where import Control.Monad (unless) import Control.Monad.Error.Class (throwError) {- Abstract syntax =============== τ := α Base type | τ -> τ' Function type e := e :: τ Annotated term | x Variable | e e' Application | λx -> e Lambda abstraction v := n Neutral term | λx -> e Lambda abstraction n := x Variable | n v Application -} data TermI -- Inferable term = Ann TermC Type | Bound Int | Free Name | TermI :@: TermC deriving (Show, Eq) data TermC -- Checkable term = Inf TermI | Lam TermC deriving (Show, Eq) data Name = Global String | Local Int | Quote Int deriving (Show, Eq) data Type = TFree Name | Fun Type Type deriving (Show, Eq) data Value = VLam (Value -> Value) | VNeutral Neutral data Neutral = NFree Name | NApp Neutral Value vfree :: Name -> Value vfree n = VNeutral (NFree n) {- Quotation ========= -} quote0 :: Value -> TermC quote0 = quote 0 quote :: Int -> Value -> TermC quote i (VLam f) = Lam (quote (i + 1) (f (vfree (Quote i)))) quote i (VNeutral n) = Inf (neutralQuote i n) neutralQuote :: Int -> Neutral -> TermI neutralQuote i (NFree x) = boundfree i x neutralQuote i (NApp n v) = neutralQuote i n :@: quote i v boundfree :: Int -> Name -> TermI boundfree i (Quote k) = Bound (i - k - 1) boundfree _ x = Free x instance Show Value where show v = show (quote0 v) instance Eq Value where v == v' = quote0 v == quote0 v' {- Evaluation ========== e => v ----------- e :: τ => v ------ x => x e => λx -> v v[x / e'] -> v' ------------------------------- e e' => v' e => n e' => v' ------------------ e e' => n v' e => v ------------------ λx -> e => λx -> v -} type Env = [Value] evalI :: TermI -> Env -> Value evalI (Ann e _) d = evalC e d evalI (Bound i) d = d !! i evalI (Free x) _ = vfree x evalI (e :@: e') d = vapp (evalI e d) (evalC e' d) vapp :: Value -> Value -> Value vapp (VLam f) v = f v vapp (VNeutral n) v = VNeutral (NApp n v) evalC :: TermC -> Env -> Value evalC (Inf i) d = evalI i d evalC (Lam e) d = VLam (\x -> evalC e (x : d)) {- Contexts ======== Γ := ε Empty context | Γ, α :: * Adding a type identifier | Γ, x :: τ Adding a term identifier -------- valid(ε) valid(Γ) ---------------- valid(Γ, α :: *) valid(Γ) Γ |- τ :: * ----------------------- valid(Γ, x :: τ) Γ(α) = * ----------- (TVAR) Γ |- α :: * Γ |- τ :: * Γ |- τ' :: * --------------------------- (FUN) Γ |- τ -> τ' :: * -} data Kind = Star deriving (Show) data Info = HasKind Kind | HasType Type deriving (Show) type Context = [(Name, Info)] {- Type checking ============= Γ |- τ :: * Γ |- e ::C τ --------------------------- (ANN) Γ |- (e :: τ) ::I τ Γ(x) = τ ------------ (VAR) Γ |- x ::I τ Γ |- e ::I τ -> τ' Γ |- e' ::C τ ----------------------------------- (APP) Γ |- e e' ::I τ' Γ |- e ::I τ ------------ (CHK) Γ |- e ::C τ Γ, x :: τ |- e ::C τ' ------------------------ (LAM) Γ |- λx -> e ::C τ -> τ' -} type Result a = Either String a kindC :: Context -> Type -> Kind -> Result () kindC c (TFree x) Star = case lookup x c of Just (HasKind Star) -> return () Just (HasType _) -> throwError "type/kind mismatch" Nothing -> throwError "unknown identifier" kindC c (Fun k k') Star = do kindC c k Star kindC c k' Star typeI0 :: Context -> TermI -> Result Type typeI0 = typeI 0 typeI :: Int -> Context -> TermI -> Result Type typeI i c (Ann e t) = do kindC c t Star typeC i c e t return t typeI _ _ (Bound _) = throwError "impossible" typeI _ c (Free x) = case lookup x c of Just (HasType t) -> return t Just (HasKind _) -> throwError "type/kind mismatch" Nothing -> throwError "unknown identifier" typeI i c (e :@: e') = do s <- typeI i c e case s of Fun t t' -> do typeC i c e' t return t' _ -> throwError "illegal application" typeC :: Int -> Context -> TermC -> Type -> Result () typeC i c (Inf e) t = do t' <- typeI i c e unless (t == t') (throwError "type mismatch") typeC i c (Lam e) (Fun t t') = typeC (i + 1) ((Local i, HasType t) : c) (substC 0 (Free (Local i)) e) t' typeC _ _ _ _ = throwError "type mismatch" substI :: Int -> TermI -> TermI -> TermI substI i r (Ann e t) = Ann (substC i r e) t substI i r (Bound j) = if i == j then r else Bound j substI _ _ (Free y) = Free y substI i r (e :@: e') = substI i r e :@: substC i r e' substC :: Int -> TermI -> TermC -> TermC substC i r (Inf e) = Inf (substI i r e) substC i r (Lam e) = Lam (substC (i + 1) r e) {- Examples ======== >> assume (α :: *) (y :: α) >> ((λx -> x) :: α -> α) y y :: α >> assume (β :: *) >> ((λx y -> x) :: (β -> β) -> α -> β -> β) (λx -> x) y λx -> x :: β -> β -} id', const' :: TermC id' = Lam (Inf (Bound 0)) const' = Lam (Lam (Inf (Bound 1))) tfree :: String -> Type tfree a = TFree (Global a) free :: String -> TermC free x = Inf (Free (Global x)) env1, env2 :: Context env1 = [(Global "y", HasType (tfree "a")), (Global "a", HasKind Star)] env2 = [(Global "b", HasKind Star)] ++ env1 term1, term2 :: TermI term1 = Ann id' (Fun (tfree "a") (tfree "a")) :@: free "y" term2 = Ann const' (Fun (Fun (tfree "b") (tfree "b")) (Fun (tfree "a") (Fun (tfree "b") (tfree "b")))) :@: id' :@: free "y" main :: IO () main = do print $ evalI term1 [] print $ evalI term2 [] print $ typeI0 env1 term1 print $ typeI0 env2 term2
mietek/lambda-pi
LambdaArrow.hs
mit
6,072
0
15
1,995
2,007
1,011
996
135
4
module Scene ( Scene , Intersection(..) , mkScene , sceneIntersection ) where import Data.List ( minimumBy ) import Data.Maybe ( mapMaybe ) import Data.Ord ( comparing ) import Core ( Ray, Point, at ) import Surface ( Surface, intersection ) data Scene = Scene [Surface] data Intersection = Intersection { rayTested :: Ray , surface :: Surface , rayPosition :: Double , worldPosition :: Point } mkScene :: [Surface] -> Scene mkScene = Scene sceneIntersection :: Scene -> Ray -> Maybe Intersection sceneIntersection (Scene surfaces) ray = minimumBy (comparing rayPosition) <$> maybeIntersections where allIntersections = mapMaybe (renderableIntersection ray) surfaces maybeIntersections = maybeList allIntersections maybeList [] = Nothing maybeList xs@(_:_) = Just xs renderableIntersection :: Ray -> Surface -> Maybe Intersection renderableIntersection ray sfc = toIntersection <$> intersection sfc ray where toIntersection t = Intersection { rayTested = ray , surface = sfc , rayPosition = t , worldPosition = ray `at` t }
stu-smith/rendering-in-haskell
src/experiment01/Scene.hs
mit
1,268
0
10
397
318
181
137
35
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} -------------------------------------------------------------------------------- -- File : Info -- Author : Alejandro Gómez Londoño -- Date : Sun Sep 14 01:56:28 2014 -- Description : Dropbox API info queries -------------------------------------------------------------------------------- -- Change log : -------------------------------------------------------------------------------- module MonadBox.Info where import Control.Lens ((&), (.~), (^.), (?~)) import Data.Text.Encoding (encodeUtf8) import qualified Data.Text.IO as Text import qualified MonadBox.URI as URI import MonadBox.Types (Token,DBAcountInfo(display_name)) import Network.Wreq (auth, defaults, getWith, oauth2Bearer, responseBody) import MonadBox.Util (asJSON) import MonadBox.Exceptions (catchStatus) import Control.Exception (catch) doLogin ∷ Token → IO () doLogin token = (flip catch) catchStatus $ do r ← _DBAcountInfo token putStr "Welcome " >> Text.putStrLn (display_name r) _DBAcountInfo ∷ Token → IO DBAcountInfo _DBAcountInfo token = do let opts = defaults & auth ?~ oauth2Bearer (encodeUtf8 token) r ← asJSON =<< getWith opts URI.info return $ r ^. responseBody
agomezl/MonadBox
src/MonadBox/Info.hs
mit
1,244
0
13
158
281
162
119
21
1
{- The following is a prototype implementation of the plan for overloaded record fields in GHC, described at http://ghc.haskell.org/trac/ghc/wiki/Records/OverloadedRecordFields/Plan This version integrates with lenses, but does not support type-changing update. -} {-# LANGUAGE KindSignatures, DataKinds, MultiParamTypeClasses, TypeFamilies, RankNTypes, FlexibleInstances, UndecidableInstances, PolyKinds, FlexibleContexts, NoMonomorphismRestriction, TypeOperators, GADTs #-} module SimpleRecords where import Control.Applicative import GHC.TypeLits -- These class and type family declarations, the instance declaration -- for SimpleAccessor (->) and the definition of `field` go in base: type family GetResult (r :: *) (f :: Symbol) :: * class t ~ GetResult r f => Has r (f :: Symbol) t where getField :: proxy f -> r -> t setField :: proxy f -> r -> t -> r class SimpleAccessor (p :: * -> * -> *) where simpleAccessor :: (r -> t) -> (r -> t -> r) -> p r t instance SimpleAccessor (->) where simpleAccessor getter setter = getter field :: (Has r f t, SimpleAccessor p) => proxy f -> p r t field z = simpleAccessor (getField z) (setField z) -- Some example datatypes... data R a = MkR { _foo :: a -> a } data S = MkS { _bar :: forall b. b -> b } data T a = MkT { _x :: [a] } data U a = MkU { _foo' :: R a, _bar' :: a } data V k = MkV { _foo'' :: Int, _bar'' :: k Int } data W a where MkW :: (a ~ b, Ord a) => { gaa :: a, gab :: b } -> W (a, b) -- ...lead to automatic generation of the following instances... type instance GetResult (R a) "foo" = a -> a instance t ~ (a -> a) => Has (R a) "foo" t where getField _ (MkR x) = x setField _ (MkR _) x = MkR x type instance GetResult (T a) "x" = [a] instance (b ~ [a]) => Has (T a) "x" b where getField _ (MkT x) = x setField _ (MkT _) y = MkT y type instance GetResult (U a) "foo" = R a instance t ~ R a => Has (U a) "foo" t where getField _ (MkU x _) = x setField _ (MkU _ y) x = MkU x y type instance GetResult (U a) "bar" = a instance t ~ a => Has (U a) "bar" t where getField _ (MkU _ y) = y setField _ (MkU x _) y = MkU x y type instance GetResult (V k) "foo" = Int instance t ~ Int => Has (V k) "foo" t where getField _ (MkV x _) = x setField _ (MkV _ y) x = MkV x y type instance GetResult (V k) "bar" = k Int instance t ~ k Int => Has (V k) "bar" t where getField _ (MkV _ y) = y setField _ (MkV x _) y = MkV x y type instance GetResult (W (a, b)) "gaa" = a instance t ~ a => Has (W (a, b)) "gaa" t where getField _ (MkW gaa _) = gaa setField _ (MkW _ gab) gaa = MkW gaa gab type instance GetResult (W (a, b)) "gab" = b instance (t ~ b, c ~ (a, b)) => Has (W c) "gab" t where getField _ (MkW _ gab) = gab setField _ (MkW gaa _) gab = MkW gaa gab -- Note that there are no instances for bar from S, because it is -- higher rank, so it cannot be overloaded. -- These function declarations approximate how uses of the fields -- would be handled by the typechecker: foo :: (Has r "foo" t, SimpleAccessor p) => p r t foo = field (Proxy :: Proxy "foo") bar :: (Has r "bar" t, SimpleAccessor p) => p r t bar = field (Proxy :: Proxy "bar") x :: (Has r "x" t, SimpleAccessor p) => p r t x = field (Proxy :: Proxy "x") -- We can use fields: t = foo (MkR not) False -- We can compose polymorphic fields: fooBar = foo . bar -- Using a newtype wrapper, we can turn any field into a simple lens -- by applying the `fieldSimpleLens` function. Everything from here -- onwards can go in libraries other than base. type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t newtype SimpleLens r a = MkSimpleLens (Lens r r a a) instance SimpleAccessor SimpleLens where simpleAccessor getter setter = MkSimpleLens (\ w s -> setter s <$> w (getter s)) fieldSimpleLens :: SimpleLens r a -> Lens r r a a fieldSimpleLens (MkSimpleLens l) = l foo_is_a_lens :: Has r "foo" t => Lens r r t t foo_is_a_lens = fieldSimpleLens foo -- data-lens (ish) data DataLens r a = DataLens { getDL :: r -> a , setDL :: r -> a -> r } instance SimpleAccessor DataLens where simpleAccessor = DataLens -- fclabels data Point arr f i o = Point { _get :: f `arr` o , _set :: (i, f) `arr` f } newtype FCLens arr f a = FCLens { unLens :: Point arr f a a } instance SimpleAccessor (FCLens (->)) where simpleAccessor getter setter = FCLens (Point getter (uncurry $ flip setter)) -- data-accessor newtype DataAccessor r a = Cons {decons :: r -> (a, a -> r)} instance SimpleAccessor DataAccessor where simpleAccessor getter setter = Cons (\ r -> (getter r, setter r)) -- Oh, I almost forgot, we need proxy types until explicit type -- application is sorted: data Proxy k = Proxy
adamgundry/records-prototype
2013/SimpleRecords.hs
mit
4,777
2
12
1,135
1,770
951
819
-1
-1
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-} -- | Monitor API. module Web.Mackerel.Api.Monitor ( listMonitors , createMonitor , updateMonitor , deleteMonitor ) where import Data.Aeson (Value) import Data.Aeson.TH (deriveJSON) import qualified Data.ByteString.Char8 as BS import Network.HTTP.Types (StdMethod(..)) import Web.Mackerel.Client import Web.Mackerel.Internal.Api import Web.Mackerel.Internal.TH import Web.Mackerel.Types.Monitor data ListMonitorsResponse = ListMonitorsResponse { responseMonitors :: [Monitor] } $(deriveJSON options ''ListMonitorsResponse) listMonitors :: Client -> IO (Either ApiError [Monitor]) listMonitors client = request client GET "/api/v0/monitors" [] emptyBody (createHandler responseMonitors) createMonitor :: Client -> Monitor -> IO (Either ApiError Monitor) createMonitor client monitor = request client POST "/api/v0/monitors" [] (Just monitor) (createHandler id) updateMonitor :: Client -> Monitor -> IO (Either ApiError Monitor) updateMonitor client monitor = do let Just (MonitorId monitorId') = monitorId monitor request client PUT ("/api/v0/monitors/" <> BS.pack monitorId') [] (Just monitor) (createHandler id) deleteMonitor :: Client -> MonitorId -> IO (Either ApiError Value) deleteMonitor client (MonitorId monitorId') = request client DELETE ("/api/v0/monitors/" <> BS.pack monitorId') [] emptyBody (createHandler id)
itchyny/mackerel-client-hs
src/Web/Mackerel/Api/Monitor.hs
mit
1,402
0
12
184
412
221
191
29
1
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module DataBet ( dataBetTestGroup ) where import Control.Applicative import Control.Lens import Data.Bet import Data.Semigroup import Test.Framework.TH import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck instance (Arbitrary odds, Arbitrary money) => Arbitrary (Bet odds money) where arbitrary = Bet <$> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary BetType where arbitrary = do x <- arbitrary return $ if x then Back else Lay asBetD :: Bet Double Double -> Bet Double Double asBetD = id dataBetTestGroup = $(testGroupGenerator) prop_bettype_pattern (asBetD -> bet) = case bet of BetType Back -> bet^.betType == Back BetType Lay -> bet^.betType == Lay _ -> error "impossible" prop_bet_semigroup (asBetD -> bet) (asBetD -> bet2) = let mbet = bimap Sum Sum bet mbet2 = bimap Sum Sum bet2 bet3 = bimap getSum getSum $ mbet <> mbet2 in bet3^.stake == bet^.stake + bet2^.stake prop_betflipped_semigroup (asBetD -> bet) (asBetD -> bet2) = let mbet = bimap Sum Sum $ BetFlipped bet mbet2 = bimap Sum Sum $ BetFlipped $ bet2 bet3 = getFlipped $ bimap getSum getSum $ mbet <> mbet2 in bet3^.odds == bet^.odds + bet2^.odds prop_back_liability (asBetD -> bet) = bet^.betType == Back ==> bet^.liability == bet^.stake prop_back_set_liability (asBetD -> bet) z = bet^.betType == Back ==> (bet & liability .~ z)^.stake == z prop_lay_liability (asBetD -> bet) = bet^.betType == Lay ==> bet^.liability == bet^.stake * (bet^.odds-1) prop_lay_set_liability (asBetD -> bet) = bet^.betType == Lay ==> abs ((bet & liability .~ (bet^.liability))^.stake - bet^.stake) < 0.001
Noeda/bet
test/DataBet.hs
mit
1,900
0
15
398
637
332
305
-1
-1
{-| Module: Treb.Routes.Helpers Description: Helper functions that return into TrebServerBase. Copyright: Travis Whitaker 2015 License: MIT Maintainer: twhitak@its.jnj.com Stability: Provisional Portability: POSIX -} {-# LANGUAGE DataKinds, PolyKinds, RankNTypes, TypeFamilies, TypeOperators, ScopedTypeVariables, OverloadedStrings, FlexibleContexts, LiberalTypeSynonyms, ImpredicativeTypes #-} module Treb.Routes.Helpers where import qualified Data.ByteString.Lazy as B import qualified Data.Map as M import qualified Database.MySQL.Simple as MySQL import qualified Database.MySQL.Simple.QueryParams as MySQL import qualified Database.MySQL.Simple.QueryResults as MySQL import qualified Hasql as H import qualified Hasql.Postgres as HP import Control.Concurrent.STM import Control.Concurrent.STM.TVar () import Control.Monad.Reader import Control.Monad.Trans.Class () import Control.Monad.Trans.Either import Data.Aeson import Data.List (find) import Data.Maybe import Data.Text (Text) import Data.Text.Encoding import Network.URI import Servant import System.Random import Treb.JSON () import Treb.Routes.Types import Treb.Types import Web.Cookie import Control.Monad.Trans.Except drupalAuth :: TrebServerBase a -> Maybe Text -> TrebServerBase a drupalAuth action cookies = do let sessionCookie = fmap (fmap snd . find ((== "SESS249b7ba79335e5fe3b5934ff07174a20") . fst) . parseCookies . encodeUtf8) cookies conn <- fromJust <$> trebEnvDrupalMySQLConn <$> ask users <- maybe (lift $ throwE $ err403 { errBody = encode $ ClientError CEMissingSessionCookie "Drupal session cookie is not found." }) (liftIO . MySQL.query conn "SELECT atrium_users.uid, atrium_users.name, atrium_realname.realname, atrium_users.mail FROM atrium_users INNER JOIN atrium_sessions ON atrium_users.uid = atrium_sessions.uid INNER JOIN atrium_realname ON atrium_users.uid = atrium_realname.uid WHERE atrium_sessions.sid = ?" . MySQL.Only) sessionCookie case users of [] -> lift $ throwE $ err403 { errBody = encode $ ClientError CEInvalidSessionCookie "Drupal session cookie was given but was not found in Drupal." } [(uid, username, realname, email)] -> local (setTrebEnvCurrentUser $ Just $ User uid username realname email) action _ -> lift $ throwE err500 { errBody = "SQL query invalid. Returned list of usernames has more than one element." } getUserByUsername :: Text -> TrebServerBase User getUserByUsername username = do rs <- queryDrupal (MySQL.Only username) "SELECT atrium_users.uid, atrium_users.name, atrium_realname.realname, atrium_users.mail FROM atrium_users INNER JOIN atrium_realname ON atrium_realname.uid = atrium_users.uid WHERE atrium_users.name = ?" case rs of [(drupalUid, drupalUsername, drupalRealname, drupalEmail)] -> return $ User drupalUid drupalUsername drupalRealname drupalEmail _ -> serverError "Drupal MySQL connection is Nothing in environment." serverError :: B.ByteString -> TrebServerBase a serverError msg = lift $ throwE $ err500 { errBody = msg } clientError :: ClientErrorCode -> Text -> TrebServerBase a clientError ce msg = (\ ret -> lift $ throwE $ ret { errBody = encode $ ClientError ce msg }) $ case ce of CEMissingSessionCookie -> err403 CEInvalidSessionCookie -> err403 CEUserNotFound -> err404 CEInvalidCSV -> err400 queryDrupal :: (MySQL.QueryParams q, MySQL.QueryResults r) => q -> MySQL.Query -> TrebServerBase [r] queryDrupal params query = do conn <- getDrupalMySQLConn liftIO $ MySQL.query conn query params queryPG :: forall r. (forall s. H.Ex HP.Postgres s r) -> H.Stmt HP.Postgres -> TrebServerBase r queryPG ex stmt = do pool <- getPgPool res <- liftIO $ H.session pool (H.tx Nothing (ex stmt :: H.Tx HP.Postgres s r) :: H.Session HP.Postgres IO r) either -- TODO: errBody = B.toStrict $ encodeUtf8 $ pack $ show err (lift . throwE . const err500 { errBody = "Postgres failure." }) return res freshUploadId :: TrebServerBase Int freshUploadId = do user <- getCurrentUser idGen <- reader trebEnvUploadIdGen activeUploadsTVar <- reader trebEnvActiveUploads liftIO $ atomically $ readTVar activeUploadsTVar >>= findNewUploadId idGen user where findNewUploadId idGen user uploads = do uploadId <- nextStdGenSTM idGen if M.member (userName user, uploadId) uploads then findNewUploadId idGen user uploads else return uploadId nextStdGenSTM :: TVar StdGen -> STM Int nextStdGenSTM idGen = do g <- readTVar idGen let (i, g') = next g writeTVar idGen g' return i -- Environment Accessors -- getActiveUploads :: TrebServerBase ActiveUploads getActiveUploads = reader trebEnvActiveUploads >>= liftIO . readTVarIO getRandomUploadId :: TrebServerBase Int getRandomUploadId = reader trebEnvUploadIdGen >>= liftIO . atomically . nextStdGenSTM getCurrentUser :: TrebServerBase User getCurrentUser = do maybeUser <- reader trebEnvCurrentUser maybe (serverError "Current user requested without authentication context.") return maybeUser getBaseURI :: TrebServerBase URI getBaseURI = reader trebEnvBaseURI getDrupalMySQLConn :: TrebServerBase MySQL.Connection getDrupalMySQLConn = do maybeConn <- reader trebEnvDrupalMySQLConn maybe (lift $ throwE $ err500 { errBody = "Drupal MySQL connection is Nothing in environment." }) return maybeConn getPgPool :: TrebServerBase (H.Pool HP.Postgres) getPgPool = reader trebEnvPgPool -- TVar Modifiers -- modifyJobTemplates :: ([JobTemplate] -> [JobTemplate]) -> TrebServerBase () modifyJobTemplates = (reader trebEnvJobTemplates >>=) . tvarModify modifyActiveUploads :: (ActiveUploads -> ActiveUploads) -> TrebServerBase () modifyActiveUploads = (reader trebEnvActiveUploads >>=) . tvarModify modifyUploadIdGen :: (StdGen -> StdGen) -> TrebServerBase () modifyUploadIdGen = (reader trebEnvUploadIdGen >>=) . tvarModify tvarModify :: (a -> a) -> TVar a -> TrebServerBase () tvarModify = (liftIO .) . (atomically .) . flip modifyTVar -- createDataBlock :: DataBlockName -> [DataBlockField] -> TrebServer DataBlock -- createDataBlock name fields =
MadSciGuys/trebuchet
src/Treb/Routes/Helpers.hs
mit
6,372
0
18
1,221
1,451
764
687
121
4
-- Aufgabe 12.16 -- a) -- Note that expo work only on natural numbers (non-negative) -- `expo 0 0`, `expo 0 1`, `expo 2 3` expo :: Int -> Int -> Int expo x 0 = 1 expo 0 y = 0 expo x y | y > 0 = x * (expo x (y-1)) {- Computation example: expo 2 2 = 2 * (expo 2 1) = 2 * 2 * (expo 2 0) = 2 * 2 * 1 = 4 -} -- b) -- `check (Branch (Branch (Leaf 1) (Leaf 2)) (Leaf 6)) k` mit 0<=k<=4 data Tree a = Branch (Tree a) (Tree a) | Leaf a deriving Show check :: Tree a -> Int -> Bool check (Leaf a) k | k == 1 = True | k <= 0 = False | k > 1 = False check (Branch t1 t2) k | (check t1 (k-1)) || (check t2 (k-1)) = True | otherwise = False -- c) -- `test [1,0,2,2]` or `test [1,0,2,3]` test :: [Int] -> Bool test [] = True test (x:xs) | (compare_test x xs) && (test xs) = True | otherwise = False compare_test :: Int -> [Int] -> Bool compare_test x [] = True compare_test x (y:ys) | x /= y && (compare_test x ys) = True | otherwise = False
KaliszAd/programmierung2012
aufgabe12_16.hs
gpl-2.0
959
12
12
255
414
209
205
24
1
{- | Module : $Header$ Description : Navigation through the Development Graph Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : ewaryst.schulz@dfki.de Stability : experimental Portability : non-portable (via imports) Navigation through the Development Graph based on Node and Link predicates using Depth First Search. -} module Static.DGNavigation where import Static.DevGraph import qualified Data.Set as Set import Data.List import Data.Maybe import Data.Graph.Inductive.Graph as Graph import Logic.Grothendieck import Common.Doc import Common.DocUtils import Syntax.AS_Library -- * Navigator Class class DevGraphNavigator a where -- | get all the incoming ledges of the given node incoming :: a -> Node -> [LEdge DGLinkLab] -- | get the label of the given node getLabel :: a -> Node -> DGNodeLab -- | get the local (not referenced) environment of the given node getLocalNode :: a -> Node -> (DGraph, LNode DGNodeLab) getInLibEnv :: a -> (LibEnv -> DGraph -> b) -> b getCurrent :: a -> [LNode DGNodeLab] relocate :: a -> DGraph -> [LNode DGNodeLab] -> a -- | Get all the incoming ledges of the given node and eventually -- cross the border to an other 'DGraph'. The new 'DevGraphNavigator' -- is returned with 'DGraph' set to the new graph and current node to -- the given node. followIncoming :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab, [LEdge DGLinkLab]) followIncoming dgn n = (dgn', lbln, incoming dgn' n') where (dgn', lbln@(n', _)) = followNode dgn n -- | get the local (not referenced) label of the given node getLocalLabel :: DevGraphNavigator a => a -> Node -> DGNodeLab getLocalLabel dgnav = snd . snd . getLocalNode dgnav followNode :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab) followNode dgnav n = (relocate dgnav dg [lbln], lbln) where (dg, lbln) = getLocalNode dgnav n -- | get all the incoming ledges of the current node directInn :: DevGraphNavigator a => a -> [LEdge DGLinkLab] directInn dgnav = concatMap (incoming dgnav . fst) $ getCurrent dgnav -- * Navigator Instance -- | The navigator instance consists of a 'LibEnv' a current 'DGraph' and -- a current 'Node' which is the starting point for navigation through the DG. data DGNav = DGNav { dgnLibEnv :: LibEnv , dgnDG :: DGraph , dgnCurrent :: [LNode DGNodeLab] } deriving Show instance Pretty DGNav where pretty dgn = d1 <> text ":" <+> pretty (map fst $ dgnCurrent dgn) where d1 = case optLibDefn $ dgnDG dgn of Just (Lib_defn ln _ _ _) -> pretty ln Nothing -> text "DG" makeDGNav :: LibEnv -> DGraph -> [LNode DGNodeLab] -> DGNav makeDGNav le dg cnl = DGNav le dg cnl' where cnl' | null cnl = filter f $ labNodesDG dg | otherwise = cnl where f (n, _) = null $ filter isDefLink $ outDG dg n isDefLink :: LEdge DGLinkLab -> Bool isDefLink = isDefEdge . dgl_type . linkLabel instance DevGraphNavigator DGNav where -- we consider only the definition links in a DGraph incoming dgn = filter isDefLink . innDG (dgnDG dgn) getLabel = labDG . dgnDG getLocalNode (DGNav{dgnLibEnv = le, dgnDG = dg}) n = lookupLocalNode le dg n getInLibEnv (DGNav{dgnLibEnv = le, dgnDG = dg}) f = f le dg getCurrent (DGNav{dgnCurrent = lblnl}) = lblnl relocate dgn dg lblnl = dgn { dgnDG = dg, dgnCurrent = lblnl } -- * Basic search functionality -- | DFS based search firstMaybe :: (a -> Maybe b) -> [a] -> Maybe b firstMaybe _ [] = Nothing firstMaybe f (x:l) = case f x of Nothing -> firstMaybe f l y -> y -- | Searches all ancestor nodes of the current node and also the current node -- for a node matching the given predicate searchNode :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Maybe (a, LNode DGNodeLab) searchNode p dgnav = firstMaybe (searchNodeFrom p dgnav . fst) $ getCurrent dgnav searchNodeFrom :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Node -> Maybe (a, LNode DGNodeLab) searchNodeFrom p dgnav n = let (dgnav', lbln, ledgs) = followIncoming dgnav n in if p lbln then Just (dgnav', lbln) else firstMaybe (searchNodeFrom p dgnav') $ map linkSource ledgs searchLink :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Maybe (a, LEdge DGLinkLab) searchLink p dgnav = firstMaybe (searchLinkFrom p dgnav . fst) $ getCurrent dgnav searchLinkFrom :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Node -> Maybe (a, LEdge DGLinkLab) searchLinkFrom p dgnav n = let (dgnav', _, ledgs) = followIncoming dgnav n in case find p ledgs of Nothing -> firstMaybe (searchLinkFrom p dgnav') $ map linkSource ledgs x -> fmap ((,) dgnav') x -- * Predicates to be used with 'searchNode' -- | This predicate is true for nodes with a nodename equal to the given string dgnPredName :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredName n nd@(_, lbl) = if getDGNodeName lbl == n then Just nd else Nothing -- | This predicate is true for nodes which are instantiations of a -- specification with the given name dgnPredParameterized :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredParameterized n nd@(_, DGNodeLab { nodeInfo = DGNode { node_origin = DGInst sid } }) | show sid == n = Just nd | otherwise = Nothing dgnPredParameterized _ _ = Nothing -- * Predicates to be used with 'searchLink' -- | This predicate is true for links which are argument instantiations of a -- parameterized specification with the given name dglPredActualParam :: String -> LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredActualParam n edg@(_, _, DGLink { dgl_origin = DGLinkInstArg sid }) | show sid == n = Just edg | otherwise = Nothing dglPredActualParam _ _ = Nothing -- | This predicate is true for links which are instantiation morphisms dglPredInstance :: LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredInstance edg@(_, _, DGLink { dgl_origin = DGLinkMorph _ }) = Just edg dglPredInstance _ = Nothing -- * Combined Node Queries -- | Search for the given name in an actual parameter link getActualParameterSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getActualParameterSpec n dgnav = -- search first actual param case searchLink (isJust . dglPredActualParam n) dgnav of Nothing -> Nothing Just (dgn', (sn, _, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in an instantiation node getParameterizedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getParameterizedSpec n dgnav = -- search first actual param case searchNode (isJust . dgnPredParameterized n) dgnav of Nothing -> Nothing Just (dgn', (sn, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in any node getNamedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getNamedSpec n dgnav = searchNode (isJust . dgnPredName n) dgnav -- | Combining a search function with an operation on nodes fromSearchResult :: (DevGraphNavigator a) => (a -> Maybe (a, LNode DGNodeLab)) -> (a -> Node -> b) -> a -> Maybe b fromSearchResult sf f dgnav = case sf dgnav of Just (dgn', (n, _)) -> Just $ f dgn' n _ -> Nothing -- * Other utils getLocalSyms :: DevGraphNavigator a => a -> Node -> Set.Set G_symbol getLocalSyms dgnav n = case dgn_origin $ getLocalLabel dgnav n of DGBasicSpec _ _ s -> s _ -> Set.empty linkSource :: LEdge a -> Node linkLabel :: LEdge a -> a linkSource (x,_,_) = x linkLabel (_,_,x) = x
nevrenato/Hets_Fork
Static/DGNavigation.hs
gpl-2.0
8,381
25
14
2,163
2,262
1,185
1,077
128
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Config.Lens -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- Lenses for types exported in Yi.Config. This module serves as a -- convenience module, for easy re-exporting. module Yi.Config.Lens where import Yi.Types (Config(..), UIConfig(..), YiConfigVariable) import Yi.Utils (makeLensesWithSuffix) import Control.Lens import Data.DynamicState (_dyn) import Data.Default makeLensesWithSuffix "A" ''Config makeLensesWithSuffix "A" ''UIConfig configVariable :: YiConfigVariable a => Lens Config Config a a configVariable = configVarsA . _dyn def
atsukotakahashi/wi
src/library/Yi/Config/Lens.hs
gpl-2.0
731
0
6
111
125
74
51
12
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Hkl.Diffabs.IRDRx ( mainIRDRx ) where import Control.Concurrent.Async (mapConcurrently) import Data.Array.Repa (DIM1, ix1) import Data.Char (toUpper) import Numeric.LinearAlgebra (ident) import System.FilePath ((</>)) import Text.Printf (printf) import Prelude hiding (concat, lookup, readFile, writeFile) import Hkl.MyMatrix import Hkl.PyFAI.PoniExt import Hkl.Types import Hkl.XRD import Hkl.XRD.Calibration import Hkl.Detector -- | Samples -- project = "/home/experiences/instrumentation/picca/data/99160066" project :: FilePath project = "/nfs/ruche-diffabs/diffabs-soleil/com-diffabs/" published :: FilePath published = project </> "2016" </> "Run5B" </> "irdrx" beamlineUpper :: Beamline -> String beamlineUpper b = [Data.Char.toUpper x | x <- show b] -- meshSample :: String -- meshSample :: project </> "2016" </> Run5 </> "2016-11-fly" </> "scan5 </> "*" -- h5path nxentry = exptest_01368 -- scan_data, sxpos szpos xpad_image 12x273 x 10 (fichiers) -- delta = -6.2 -- gamma = 0.0 nxs' :: FilePath -> NxEntry -> (NxEntry -> DataFrameH5Path) -> Nxs nxs' f e h = Nxs f e (h e) nxs :: FilePath -> NxEntry -> (NxEntry -> DataFrameH5Path) -> XrdSource nxs f e h = XrdSourceNxs (nxs' f e h) sampleRef :: XRDRef sampleRef = XRDRef "reference" (published </> "calibration") (XrdRefNxs (nxs' (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_39.nxs") "scan_39" h5path') 10 ) h5path' :: NxEntry -> DataFrameH5Path h5path' nxentry = DataFrameH5Path { h5pImage = DataItem (nxentry </> image) StrictDims , h5pGamma = DataItem (nxentry </> beamline </> gamma) ExtendDims , h5pDelta = DataItem (nxentry </> delta) ExtendDims , h5pWavelength = DataItem (nxentry </> beamline </> wavelength) StrictDims } where beamline :: String beamline = beamlineUpper Diffabs image = "scan_data/data_05" gamma = "D13-1-CX1__EX__DIF.1-GAMMA__#1/raw_value" delta = "scan_data/data_03" wavelength = "D13-1-C03__OP__MONO__#1/wavelength" sampleCalibration :: XRDCalibration sampleCalibration = XRDCalibration { xrdCalibrationName = "calibration" , xrdCalibrationOutputDir = published </> "calibration" -- TODO pourquoi ce output , xrdCalibrationEntries = entries } where idxs :: [Int] idxs = [0, 1, 10, 30] entry :: Int -> XRDCalibrationEntry entry idx = XRDCalibrationEntryNxs { xrdCalibrationEntryNxs'Nxs = nxs' (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_39.nxs") "scan_39" h5path' , xrdCalibrationEntryNxs'Idx = idx , xrdCalibrationEntryNxs'NptPath = published </> "calibration" </> printf "scan_39.nxs_%02d.npt" idx } entries :: [XRDCalibrationEntry] entries = [ entry idx | idx <- idxs] bins :: DIM1 bins = ix1 1000 multibins :: DIM1 multibins = ix1 10000 threshold :: Threshold threshold = Threshold 5000 lab6 :: XRDSample lab6 = XRDSample "LaB6" (published </> "LaB6") [ XrdNxs bins multibins threshold n | n <- [ nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_39.nxs") "scan_39" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_40.nxs") "scan_40" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_41.nxs") "scan_41" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_42.nxs") "scan_42" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_43.nxs") "scan_43" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_44.nxs") "scan_44" h5path' , nxs (project </> "2016" </> "Run5" </> "2016-11-09" </> "scan_45.nxs") "scan_45" h5path' ] ] -- | Main mainIRDRx :: IO () mainIRDRx = do let samples = [lab6] p <- getPoniExtRef sampleRef let poniextref = setPose (Hkl.PyFAI.PoniExt.flip p) (MyMatrix HklB (ident 3)) -- full calibration poniextref' <- calibrate sampleCalibration poniextref ImXpadS140 -- integrate each step of the scan _ <- mapConcurrently (integrate poniextref') samples return ()
picca/hkl
contrib/haskell/src/Hkl/Diffabs/IRDRx.hs
gpl-3.0
4,443
0
17
1,106
1,071
586
485
83
1
-- | Define the behaviors of 'Ball' {-# LANGUAGE GADTs , MultiParamTypeClasses #-} module Satter.Ball ( expectedTime ) where import Satter.TwoD import Satter.Types alpha :: Double alpha = 0.99 instance SObject Ball where geometricsOf = _geometrics_b sizeOf _ = ballSize updateIntention _ p@(Ball _ _) = return p updatePhysics _ _ = error "Don't call me!" (<!!) (Ball (Geometrics (x, y) (dx, dy) v) h) t = Ball (Geometrics (x + simulationScale * integral (dx * v) t, y + simulationScale * integral (dy * v) t) (dx, dy) (v * alpha ** t) ) h newPosition :: Ball -> Double -> TwoD newPosition (Ball (Geometrics (x, y) (dx, dy) v) _) t = (x + simulationScale * integral (dx * v) t, y + simulationScale * integral (dy * v) t) expectedTime :: Ball -> TwoD -> Double -> Double expectedTime (Ball (Geometrics pos@(x, y) (dx, dy) vec) _) pos' o | vec == 0 = 0 | 0 < j = log j / (k * simulationScale) | otherwise = d where l1 = dropLength (x, y) (x + dx, y + dy) pos' l' = pos <-> pos' l2 = sqrt $ l' ** 2 - l1 ** 2 d = l2 / simulationScale k = log alpha j = 1 + k * d / vec -- (vec + o / 8) -- | return distance based on the integral of the speed integral :: Double -> Double -> Double integral v t = v / k * (exp (t * k) -1) where k = log alpha defaultBall = Ball (Geometrics (0, 0) (1,1) 1) Nothing
shnarazk/satter
Satter/Ball.hs
gpl-3.0
1,410
0
13
390
608
326
282
40
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.IAM.Projects.Locations.WorkLoadIdentityPools.Providers.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a WorkloadIdentityPoolProvider. Deleting a provider does not -- revoke credentials that have already been issued; they continue to grant -- access. You can undelete a provider for 30 days. After 30 days, deletion -- is permanent. You cannot update deleted providers. However, you can view -- and list them. -- -- /See:/ <https://cloud.google.com/iam/ Identity and Access Management (IAM) API Reference> for @iam.projects.locations.workloadIdentityPools.providers.delete@. module Network.Google.Resource.IAM.Projects.Locations.WorkLoadIdentityPools.Providers.Delete ( -- * REST Resource ProjectsLocationsWorkLoadIdentityPoolsProvidersDeleteResource -- * Creating a Request , projectsLocationsWorkLoadIdentityPoolsProvidersDelete , ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete -- * Request Lenses , plwlippdXgafv , plwlippdUploadProtocol , plwlippdAccessToken , plwlippdUploadType , plwlippdName , plwlippdCallback ) where import Network.Google.IAM.Types import Network.Google.Prelude -- | A resource alias for @iam.projects.locations.workloadIdentityPools.providers.delete@ method which the -- 'ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete' request conforms to. type ProjectsLocationsWorkLoadIdentityPoolsProvidersDeleteResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes a WorkloadIdentityPoolProvider. Deleting a provider does not -- revoke credentials that have already been issued; they continue to grant -- access. You can undelete a provider for 30 days. After 30 days, deletion -- is permanent. You cannot update deleted providers. However, you can view -- and list them. -- -- /See:/ 'projectsLocationsWorkLoadIdentityPoolsProvidersDelete' smart constructor. data ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete = ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete' { _plwlippdXgafv :: !(Maybe Xgafv) , _plwlippdUploadProtocol :: !(Maybe Text) , _plwlippdAccessToken :: !(Maybe Text) , _plwlippdUploadType :: !(Maybe Text) , _plwlippdName :: !Text , _plwlippdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plwlippdXgafv' -- -- * 'plwlippdUploadProtocol' -- -- * 'plwlippdAccessToken' -- -- * 'plwlippdUploadType' -- -- * 'plwlippdName' -- -- * 'plwlippdCallback' projectsLocationsWorkLoadIdentityPoolsProvidersDelete :: Text -- ^ 'plwlippdName' -> ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete projectsLocationsWorkLoadIdentityPoolsProvidersDelete pPlwlippdName_ = ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete' { _plwlippdXgafv = Nothing , _plwlippdUploadProtocol = Nothing , _plwlippdAccessToken = Nothing , _plwlippdUploadType = Nothing , _plwlippdName = pPlwlippdName_ , _plwlippdCallback = Nothing } -- | V1 error format. plwlippdXgafv :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete (Maybe Xgafv) plwlippdXgafv = lens _plwlippdXgafv (\ s a -> s{_plwlippdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plwlippdUploadProtocol :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete (Maybe Text) plwlippdUploadProtocol = lens _plwlippdUploadProtocol (\ s a -> s{_plwlippdUploadProtocol = a}) -- | OAuth access token. plwlippdAccessToken :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete (Maybe Text) plwlippdAccessToken = lens _plwlippdAccessToken (\ s a -> s{_plwlippdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plwlippdUploadType :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete (Maybe Text) plwlippdUploadType = lens _plwlippdUploadType (\ s a -> s{_plwlippdUploadType = a}) -- | Required. The name of the provider to delete. plwlippdName :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete Text plwlippdName = lens _plwlippdName (\ s a -> s{_plwlippdName = a}) -- | JSONP plwlippdCallback :: Lens' ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete (Maybe Text) plwlippdCallback = lens _plwlippdCallback (\ s a -> s{_plwlippdCallback = a}) instance GoogleRequest ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete where type Rs ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete = Operation type Scopes ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsWorkLoadIdentityPoolsProvidersDelete'{..} = go _plwlippdName _plwlippdXgafv _plwlippdUploadProtocol _plwlippdAccessToken _plwlippdUploadType _plwlippdCallback (Just AltJSON) iAMService where go = buildClient (Proxy :: Proxy ProjectsLocationsWorkLoadIdentityPoolsProvidersDeleteResource) mempty
brendanhay/gogol
gogol-iam/gen/Network/Google/Resource/IAM/Projects/Locations/WorkLoadIdentityPools/Providers/Delete.hs
mpl-2.0
6,425
0
15
1,277
705
416
289
112
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdSense.Accounts.AdClients.AdUnits.GetAdcode -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the AdSense code for a given ad unit. -- -- /See:/ <http://code.google.com/apis/adsense/management/ AdSense Management API Reference> for @adsense.accounts.adclients.adunits.getAdcode@. module Network.Google.Resource.AdSense.Accounts.AdClients.AdUnits.GetAdcode ( -- * REST Resource AccountsAdClientsAdUnitsGetAdcodeResource -- * Creating a Request , accountsAdClientsAdUnitsGetAdcode , AccountsAdClientsAdUnitsGetAdcode -- * Request Lenses , aacaugaXgafv , aacaugaUploadProtocol , aacaugaAccessToken , aacaugaUploadType , aacaugaName , aacaugaCallback ) where import Network.Google.AdSense.Types import Network.Google.Prelude -- | A resource alias for @adsense.accounts.adclients.adunits.getAdcode@ method which the -- 'AccountsAdClientsAdUnitsGetAdcode' request conforms to. type AccountsAdClientsAdUnitsGetAdcodeResource = "v2" :> Capture "name" Text :> "adcode" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] AdUnitAdCode -- | Gets the AdSense code for a given ad unit. -- -- /See:/ 'accountsAdClientsAdUnitsGetAdcode' smart constructor. data AccountsAdClientsAdUnitsGetAdcode = AccountsAdClientsAdUnitsGetAdcode' { _aacaugaXgafv :: !(Maybe Xgafv) , _aacaugaUploadProtocol :: !(Maybe Text) , _aacaugaAccessToken :: !(Maybe Text) , _aacaugaUploadType :: !(Maybe Text) , _aacaugaName :: !Text , _aacaugaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsAdClientsAdUnitsGetAdcode' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aacaugaXgafv' -- -- * 'aacaugaUploadProtocol' -- -- * 'aacaugaAccessToken' -- -- * 'aacaugaUploadType' -- -- * 'aacaugaName' -- -- * 'aacaugaCallback' accountsAdClientsAdUnitsGetAdcode :: Text -- ^ 'aacaugaName' -> AccountsAdClientsAdUnitsGetAdcode accountsAdClientsAdUnitsGetAdcode pAacaugaName_ = AccountsAdClientsAdUnitsGetAdcode' { _aacaugaXgafv = Nothing , _aacaugaUploadProtocol = Nothing , _aacaugaAccessToken = Nothing , _aacaugaUploadType = Nothing , _aacaugaName = pAacaugaName_ , _aacaugaCallback = Nothing } -- | V1 error format. aacaugaXgafv :: Lens' AccountsAdClientsAdUnitsGetAdcode (Maybe Xgafv) aacaugaXgafv = lens _aacaugaXgafv (\ s a -> s{_aacaugaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). aacaugaUploadProtocol :: Lens' AccountsAdClientsAdUnitsGetAdcode (Maybe Text) aacaugaUploadProtocol = lens _aacaugaUploadProtocol (\ s a -> s{_aacaugaUploadProtocol = a}) -- | OAuth access token. aacaugaAccessToken :: Lens' AccountsAdClientsAdUnitsGetAdcode (Maybe Text) aacaugaAccessToken = lens _aacaugaAccessToken (\ s a -> s{_aacaugaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). aacaugaUploadType :: Lens' AccountsAdClientsAdUnitsGetAdcode (Maybe Text) aacaugaUploadType = lens _aacaugaUploadType (\ s a -> s{_aacaugaUploadType = a}) -- | Required. Name of the adunit for which to get the adcode. Format: -- accounts\/{account}\/adclients\/{adclient}\/adunits\/{adunit} aacaugaName :: Lens' AccountsAdClientsAdUnitsGetAdcode Text aacaugaName = lens _aacaugaName (\ s a -> s{_aacaugaName = a}) -- | JSONP aacaugaCallback :: Lens' AccountsAdClientsAdUnitsGetAdcode (Maybe Text) aacaugaCallback = lens _aacaugaCallback (\ s a -> s{_aacaugaCallback = a}) instance GoogleRequest AccountsAdClientsAdUnitsGetAdcode where type Rs AccountsAdClientsAdUnitsGetAdcode = AdUnitAdCode type Scopes AccountsAdClientsAdUnitsGetAdcode = '["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"] requestClient AccountsAdClientsAdUnitsGetAdcode'{..} = go _aacaugaName _aacaugaXgafv _aacaugaUploadProtocol _aacaugaAccessToken _aacaugaUploadType _aacaugaCallback (Just AltJSON) adSenseService where go = buildClient (Proxy :: Proxy AccountsAdClientsAdUnitsGetAdcodeResource) mempty
brendanhay/gogol
gogol-adsense/gen/Network/Google/Resource/AdSense/Accounts/AdClients/AdUnits/GetAdcode.hs
mpl-2.0
5,387
0
16
1,159
704
412
292
109
1
{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Monad import Criterion import Criterion.Main import Data.Text ( Text ) import qualified Data.Text as T import Foreign.Marshal.Alloc import Graphics.Text setupEnv :: IO RenderContext setupEnv = do ctx <- newRenderContext setFont ctx "DejaVu Sans 28" return ctx main :: IO () main = defaultMain [ bgroup "meta" [ bench "newRenderContext" $ whnfIO newRenderContext , env setupEnv $ \ctx -> bench "setFont" $ whnfIO $ setFont ctx "Droid Sans 28" ] , env setupEnv $ \ctx -> bgroup "rendering" [ bench (snd fun ++ "[\"" ++ T.unpack str ++ "\"]") $ whnfIO $ (fst fun) ctx str | str <- ["A", "12345", "Hello world!", "宁夏回族自治区"] , fun <- [(renderPlainString, "renderText") ,(renderByteString, "renderByteString") ,(renderVector, "renderVector") ,(plainInkRectangle, "inkRectangle")] ] ] plainInkRectangle :: RenderContext -> Text -> IO () plainInkRectangle ctx txt = do void $ inkRectangle txt Nothing ctx return () renderByteString :: RenderContext -> Text -> IO () renderByteString ctx txt = do PangoRectangle x y w h <- inkRectangle txt Nothing ctx let iw = floor w ih = floor h void $ renderTextByteString txt iw ih FormatARGB32 (V2 (-x) (-y)) (V4 0 0 0 1) ctx renderVector :: RenderContext -> Text -> IO () renderVector ctx txt = do PangoRectangle x y w h <- inkRectangle txt Nothing ctx let iw = floor w ih = floor h void $ renderTextVector txt iw ih FormatARGB32 (V2 (-x) (-y)) (V4 0 0 0 1) ctx renderPlainString :: RenderContext -> Text -> IO () renderPlainString ctx txt = do PangoRectangle x y w h <- inkRectangle txt Nothing ctx let iw = floor w ih = floor h (bytes, stride) = bytesNeededStride iw ih FormatARGB32 allocaBytes bytes $ \ptr -> do renderText txt ptr iw ih stride FormatARGB32 (V2 (-x) (-y)) (V4 0 0 0 1) ctx
Noeda/rendertext
benchmark/Main.hs
lgpl-2.1
2,112
0
18
602
741
373
368
52
1
maximum' :: (Ord a) => [a] -> a maximum' [] = error "maximum of empty list!" maximum' [x] = x maximum' (x:xs) = max x (maximum' xs) -- We use guards instead of patterns because we're testing for a Boolean condition replicate' :: Int -> a -> [a] replicate' n x | n <= 0 = [] | otherwise = x : replicate' (n-1) x take' :: (Num i, Ord i) => i -> [a] -> [a] take' n _ | n <= 0 = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = xs ++ [x] repeat' :: a -> [a] repeat' x = x:repeat' x zip' :: [a] -> [b] -> [(a, b)] zip' _ [] = [] zip' [] _ = [] zip' (x:xs) (y:ys) = (x,y): zip' xs ys elem' :: (Eq a) => a -> [a] -> Bool elem' a [] = False elem' a (x:xs) | a == x = True | otherwise = a `elem'` xs -- We'll take the first element of the list as the pivot quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let smallerOrEqual = [a | a <- xs, a <= x] larger = [a | a <- xs, a > x] in quicksort smallerOrEqual ++ [x] ++ larger
Ketouem/learn-you-a-haskell
src/chapter-4-hello-recursion/recursion.hs
unlicense
1,020
10
11
254
620
325
295
33
1
import Data.List (findIndices, permutations) import Helpers.ListHelpers (cartesianProduct) wreathProductElements k n = [(a, b) | a <- permutations [0..n-1], b <- cartesianProduct n [0..k-1]] isDerangement (perm, prod) = all (\fp -> (prod !! fp) /= 0) fixedPoints where fixedPoints = findIndices (uncurry (==)) $ zip perm [0..]
peterokagey/haskellOEIS
src/Sandbox/Sami/WreathProductDerangements.hs
apache-2.0
332
0
10
51
153
83
70
5
1
{-# LANGUAGE BangPatterns, TemplateHaskell #-} module Collectors.Network where import Control.Applicative ((*>)) import Control.Lens.TH (makeClassy) import Data.Functor ((<$>)) import Data.Text (Text, pack) import Text.Parsec (manyTill, anyChar, digit, endBy, string , many1, char, sepBy, newline, space) import Text.Parsec.String data NetTransmittedMetric = NetTransmittedMetric { _bytesT :: !Int , _packetsT :: !Int , _errsT :: !Int , _dropT :: !Int , _fifoT :: !Int , _collsT :: !Int , _carrierT :: !Int , _compressedT :: !Int } deriving Show $(makeClassy ''NetTransmittedMetric) data NetReceivedMetric = NetReceivedMetric { _bytesR :: !Int , _packetsR :: !Int , _errsR :: !Int , _dropR :: !Int , _fifoR :: !Int , _frameR :: !Int , _compressedR :: !Int , _multicastR :: !Int } deriving Show $(makeClassy ''NetReceivedMetric) data NetDeviceMetric = NetDeviceMetric { _interface :: !Text , _received :: !NetReceivedMetric , _transmitted :: !NetTransmittedMetric } deriving Show $(makeClassy ''NetDeviceMetric) identifier :: Parser Text identifier = pack <$> manyTill anyChar (string ":") toMetric :: [Int] -> (NetReceivedMetric, NetTransmittedMetric) toMetric ms = (recvdMetric, transMetric) where (rList, tList) = splitAt 8 ms (b:p:e:d:fi:fr:c:m:_) = rList (bytes:pkts:errs:drp:fifo:colls:carr:compr:_) = tList recvdMetric = NetReceivedMetric b p e d fi fr c m transMetric = NetTransmittedMetric bytes pkts errs drp fifo colls carr compr metrics :: Parser [Int] metrics = sepBy number (many1 $ char ' ') number :: Parser Int number = read <$> many1 digit deviceLine :: Parser NetDeviceMetric deviceLine = do i <- identifier _ <- many1 space (recvd, transm) <- toMetric <$> metrics return $ NetDeviceMetric i recvd transm parseStat :: Parser [NetDeviceMetric] parseStat = skipLine *> skipLine *> endBy deviceLine newline where skipLine = manyTill anyChar newline
muhbaasu/hmon
src/Collectors/NetDev.hs
apache-2.0
2,863
0
15
1,264
661
359
302
94
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module CoSimCLaSH ( CoSimulator(..) ,coSim ,coSimCleanUp ,coSimDisableStdOut ,coSimEnableStdOut ,coSimSeq ,coSimWithFiles ,verilog ,wordPack ,wordUnpack ,mapAccumLM ) where --------------------------- ---- IMPORTS -------------- --------------------------- -- Haskell import qualified Prelude as P import qualified Data.List as L import Data.Maybe -- CLaSH import CLaSH.Prelude import CLaSH.Signal.Explicit -- FFI import Foreign import Foreign.C -- GC / IO / Monad import System.Mem import System.IO import System.IO.Unsafe import Control.Monad -- Inline import Language.Haskell.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax -------------------------------------- ---- FFI Imports --------------------- -------------------------------------- foreign import ccall "simStart" c_simStart :: Ptr CInt -> CString -> Ptr CString -> IO (Ptr a) foreign import ccall "&simEnd" c_simEnd :: FunPtr (Ptr a -> IO ()) foreign import ccall "simStep" c_simStep :: Ptr a -> IO CInt foreign import ccall "getInputLength" c_inputLength :: Ptr a -> IO CInt foreign import ccall "getOutputLength" c_outputLength :: Ptr a -> IO CInt foreign import ccall "getInputSizes" c_inputSizes :: Ptr a -> IO (Ptr CInt) foreign import ccall "getOutputSizes" c_outputSizes :: Ptr a -> IO (Ptr CInt) foreign import ccall "getInputPtr" c_inputPtr :: Ptr a -> IO (Ptr (Ptr CInt)) foreign import ccall "getOutputPtr" c_outputPtr :: Ptr a -> IO (Ptr (Ptr CInt)) foreign import ccall "writeToFile" c_writeToFile :: CString -> IO CString -------------------------------------- ---- Types --------------------------- -------------------------------------- -- (HDL, Period, ResetFase, Data, Files, Enable StdOut) type CoSimSettings = (Int, Int, Bool, String, [String], Bool) type CoSimSettings' = (CoSimSettings, CoSimulator, String) type CLaSHType a = (BitPack a, KnownNat (BitSize a), KnownNat (BitSize a + 1), KnownNat (BitSize a + 2)) type SignalStream = [[Int32]] data CoSimulator = Icarus | ModelSim deriving (Show, Eq) -------------------------------------- ---- INLINE -------------------------- -------------------------------------- verilog :: QuasiQuoter verilog = createQuasiQuoter' $ inlineCoSim' Icarus inlineCoSim' :: CoSimulator -> String -> Q Exp inlineCoSim' hdl s = liftM TupE $ sequence [q_hdl, q_period, q_reset, q_data, q_list, q_stdOut] where q_hdl = lift (sim2Num hdl :: Int) q_period = lift (20 :: Int) q_reset = lift False q_data = lift s q_list = lift ([] :: [String]) q_stdOut = lift True createQuasiQuoter' :: (String -> Q Exp) -> QuasiQuoter createQuasiQuoter' f = QuasiQuoter {quoteExp = f ,quotePat = undefined ,quoteType = undefined ,quoteDec = undefined} -------------------------------------- ---- Help-Functions ------------------ -------------------------------------- bool2Num False = fromIntegral 0 bool2Num True = fromIntegral 1 sim2Num Icarus = fromIntegral 1 sim2Num ModelSim = fromIntegral 2 transposeList ::(Eq a, Num b, Eq b) => b -> [[a]] -> [[a]] transposeList 0 _ = [] transposeList n xss = ys : transposeList (n-1) yss where ys = P.map P.head xss yss = P.map P.tail xss mapAccumLM :: (acc -> x -> IO (acc, y)) -> acc -> [x] -> IO (acc, [y]) mapAccumLM f s xs = return $ L.mapAccumL (\a xs -> unsafePerformIO $ f a xs) s xs -------------------------------------- ---- Array Marshalling --------------- -------------------------------------- peekArray' :: (Storable a, Integral b) => b -> Ptr a -> IO [a] peekArray' (-1) _ = error "null-pointer" peekArray' size ptr | ptr == nullPtr = error "null-pointer" | otherwise = peekArray (fromIntegral size) ptr pokeArray' :: Storable a => Ptr a -> [a] -> IO () pokeArray' ptr [] = return () pokeArray' ptr xs | ptr == nullPtr = error "null-pointer" | otherwise = pokeArray ptr xs -------------------------------------- ---- Co-Simulation ------------------- -------------------------------------- coSimCleanUp :: IO () coSimCleanUp = performGC coSimEnableStdOut :: CoSimSettings -> CoSimSettings coSimEnableStdOut settings = (a,b,c,d,e,True) where (a,b,c,d,e,_) = settings coSimDisableStdOut :: CoSimSettings -> CoSimSettings coSimDisableStdOut settings = (a,b,c,d,e,False) where (a,b,c,d,e,_) = settings coSimWithFiles :: CoSimSettings -> [String] -> CoSimSettings coSimWithFiles settings fs = (a,b,c,d,(P.++) e fs,f) where (a,b,c,d,e,f) = settings coSimSeq :: CoSimSettings -> (Int,Bool) -> [String] -> CoSimSettings coSimSeq set (p,rst) fs' = (hdl, fromIntegral p, rst, m, (P.++) fs fs', stdOut) where (hdl, _, _, m, fs, stdOut) = set coSim :: (CoSim r) => CoSimSettings -> CoSimulator -> String -> r coSim settings sim top = coSim' (settings, sim, top) False [] -------------------------------------- ---- Co-Simulation MARSHALLING ------- -------------------------------------- coSimMarshall :: CoSimSettings' -> [SignalStream] -> IO (Bool, Ptr CInt, CString, Ptr CString) coSimMarshall settings xs = do -- files c_f <- (newCString m) >>= c_writeToFile c_fs <- mapM newCString d let c_files = c_f : c_fs c_filePtrs <- newArray c_files -- topEntity & settings c_topEntity <- newCString top c_settingsPtr <- newArray $ P.map fromIntegral $ c_settingsf c_files -- return return (c, c_settingsPtr, c_topEntity, c_filePtrs) where (set,sim,top) = settings (a, b, c, m, d, e) = set --(HDL, Period, ResetFase, Data, Files, Enable StdOut) c_settingsf fs = [sim2Num sim, a, b, rst, stdOut, lenf fs, lenf xs] lenf = P.length rst = bool2Num c stdOut = bool2Num e -------------------------------------- ---- Co-Simulation START ------------- -------------------------------------- coSimStart :: CoSimSettings' -> [SignalStream] -> [SignalStream] coSimStart settings xs = unsafePerformIO $ do -- clean up coSimCleanUp -- marshall c-types (rst, c_sPtr, c_topE, c_fPtrs) <- coSimMarshall settings xs -- start simulation c_coSimState' <- c_simStart c_sPtr c_topE c_fPtrs when (c_coSimState' == nullPtr) $ error "Start co-simulation failed" -- add finilizer c_coSimState <- newForeignPtr c_simEnd c_coSimState' -- perform simulation steps c_oLength <- withForeignPtr c_coSimState c_outputLength (_, ys) <- mapAccumLM coSimStep c_coSimState $ f rst xs -- transpose and return return $ transposeList c_oLength ys where f r | r = ([]:) . L.transpose | otherwise = L.transpose -------------------------------------- ---- Co-Simulation STEP -------------- -------------------------------------- coSimStep :: ForeignPtr a -> [[Int32]] -> IO (ForeignPtr a, [[Int32]]) coSimStep state xs = do -- write input coSimInput state xs -- perform simulation step rv <- withForeignPtr state c_simStep when (rv /= 0) $ error "Error in co-simulation step" -- read output ys <- coSimOutput state -- touch state, to keep state alive touchForeignPtr state -- return output return (state, ys) -------------------------------------- ---- Co-Simulation INPUT OUTPUT ------ -------------------------------------- coSimInput :: ForeignPtr a -> [[Int32]] -> IO () coSimInput state xs = do -- check sizes c_iLength <- withForeignPtr state c_inputLength c_iSizes <- withForeignPtr state c_inputSizes >>= peekArray' c_iLength when (f c_iSizes) $ error $ errStr c_iSizes -- write input c_inputPtrs <- withForeignPtr state c_inputPtr >>= peekArray' c_iLength zipWithM_ pokeArray' c_inputPtrs xs' where xs' = P.map (P.map fromIntegral) xs f = not . and . P.zipWith (\x y -> ( x == 0 ) || ( x == y )) iSizes iLength = fromIntegral $ P.length xs iSizes = P.map (fromIntegral . P.length) xs errStr ls = P.concat ["Simulator expects ", show ls, " input words, but ", show iSizes, " given"] coSimOutput :: ForeignPtr a -> IO [[Int32]] coSimOutput state = do -- read output c_oLength <- withForeignPtr state c_outputLength c_oSizes <- withForeignPtr state c_outputSizes >>= peekArray' c_oLength c_outputPtrs <- withForeignPtr state c_outputPtr >>= peekArray' c_oLength ys <- zipWithM peekArray' c_oSizes c_outputPtrs -- convert and return return $ P.map (P.map fromIntegral) ys -------------------------------------- ---- CONVERSION ---------------------- -------------------------------------- wordPack :: (Integral a, Bits a) => a -> [Int32] wordPack x | isJust size = snd $ L.mapAccumR wordPack' x [1 .. wordSize] | otherwise = error "Value does not have a fixed bitsize" where size = bitSizeMaybe x wordSize = 1 + shiftR (fromJust size - 1) 5 wordUnpack :: (Integral a, Bits a) => [Int32] -> a wordUnpack = P.foldl wordUnpack' 0 wordPack' :: (Integral a, Bits a) => a -> b -> (a, Int32) wordPack' x _ = (shiftR x 32, fromIntegral x) wordUnpack' :: (Integral a, Bits a) => a -> Int32 -> a wordUnpack' x y = (shiftL x 32) .|. (4294967295 .&. (fromIntegral y)) -------------------------------------- ---- PARSING ------------------------- -------------------------------------- parseInput :: CoSimType t => [SignalStream] -> t -> [SignalStream] parseInput xs x = toSignalStream x : xs parseOutput :: CoSimType t => ([SignalStream] -> [SignalStream]) -> Bool -> [SignalStream] -> ([SignalStream], t) parseOutput f u xs | qs == [] = error "Simulator expects less output ports" | otherwise = (ys, fromSignalStream y) where (y:ys) = qs qs | u = xs | otherwise = f $ P.reverse xs -------------------------------------- ---- POLYVARIDIC --------------------- -------------------------------------- class CoSim r where -------------------------------------- ---- Func Definitions ---------------- -------------------------------------- coSim' :: CoSimSettings' -> Bool -> [SignalStream] -> r -------------------------------------- ---- Instances Definitions ----------- -------------------------------------- instance {-# OVERLAPPABLE #-} CoSimType t => CoSim t where coSim' s u xs | ys == [] = y' | otherwise = error "Simulator expects more output ports" where (ys, y') = parseOutput (coSimStart s) u xs instance {-# OVERLAPPING #-} (CoSimType t, CoSim r) => CoSim (t, r) where coSim' s u xs = (y', y'') where (ys, y') = parseOutput (coSimStart s) u xs y'' = coSim' s True ys instance {-# OVERLAPPING #-} (CoSimType t, CoSim r) => CoSim (t -> r) where coSim' s u xs = coSim' s u . parseInput xs -------------------------------------- ---- Tupple Definitions -------------- -------------------------------------- instance {-# OVERLAPPING #-} CoSim (a,(b,r)) => CoSim (a,b,r) where coSim' s u = (\(a,(b,r)) -> (a,b,r)) . coSim' s u instance {-# OVERLAPPING #-} CoSim (a,(b,c,r)) => CoSim (a,b,c,r) where coSim' s u = (\(a,(b,c,r)) -> (a,b,c,r)) . coSim' s u instance {-# OVERLAPPING #-} CoSim (a,(b,c,d,r)) => CoSim (a,b,c,d,r) where coSim' s u = (\(a,(b,c,d,r)) -> (a,b,c,d,r)) . coSim' s u -------------------------------------- ---- SUPPORTED TYPES ----------------- -------------------------------------- class CoSimType t where -------------------------------------- ---- Func Definitions ---------------- -------------------------------------- toSignalStream :: t -> SignalStream fromSignalStream :: SignalStream -> t -------------------------------------- ---- Instances Definitions ----------- -------------------------------------- instance {-# OVERLAPPABLE #-} CLaSHType a => CoSimType a where toSignalStream = (:[]) . wordPack . pack fromSignalStream = unpack . wordUnpack . P.head instance {-# OVERLAPPING #-} CLaSHType a => CoSimType (Signal' clk a) where toSignalStream = P.map (wordPack . pack) . sample fromSignalStream = fromList . P.map (unpack . wordUnpack) instance {-# OVERLAPPING #-} (Integral a, Bits a) => CoSimType [a] where toSignalStream = P.map wordPack fromSignalStream = P.map wordUnpack
jgjverheij/clash-cosim
CoSimCLaSH.hs
bsd-2-clause
14,376
0
13
4,352
3,753
2,027
1,726
-1
-1
-- | Program to replace HTML tags by whitespace -- -- This program was originally contributed by Petr Prokhorenkov. -- -- Tested in this benchmark: -- -- * Reading the file -- -- * Replacing text between HTML tags (<>) with whitespace -- -- * Writing back to a handle -- {-# OPTIONS_GHC -fspec-constr-count=5 #-} module Benchmarks.Programs.StripTags ( benchmark ) where import Criterion (Benchmark, bgroup, bench) import Data.List (mapAccumL) import System.IO (Handle, hPutStr) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T benchmark :: FilePath -> Handle -> IO Benchmark benchmark i o = return $ bgroup "StripTags" [ bench "String" $ readFile i >>= hPutStr o . string , bench "ByteString" $ B.readFile i >>= B.hPutStr o . byteString , bench "Text" $ T.readFile i >>= T.hPutStr o . text , bench "TextByteString" $ B.readFile i >>= B.hPutStr o . T.encodeUtf8 . text . T.decodeUtf8 ] string :: String -> String string = snd . mapAccumL step 0 text :: T.Text -> T.Text text = snd . T.mapAccumL step 0 byteString :: B.ByteString -> B.ByteString byteString = snd . BC.mapAccumL step 0 step :: Int -> Char -> (Int, Char) step d c | d > 0 || d' > 0 = (d', ' ') | otherwise = (d', c) where d' = d + depth c depth '>' = 1 depth '<' = -1 depth _ = 0
ekmett/text
benchmarks/haskell/Benchmarks/Programs/StripTags.hs
bsd-2-clause
1,461
0
14
322
449
248
201
32
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} module Haskell.Decode where import Haskell.ArraySig import Data.Array.Base (IArray(..),listArray,amap,elems,MArray) import Data.Array.Base (thaw,unsafeFreeze) import Data.Array.Unboxed ((!),Ix(..)) import Data.Array.ST (STUArray,readArray,writeArray) import Control.Monad.ST (ST,runST) import Control.Monad (when) import Control.Applicative ((<$>)) import Control.Monad.ST.Unsafe (unsafeIOToST) type STM s = STUArray s (Int,Int) type STV s = STUArray s Int updateArray :: (MArray a e m,Ix i) => a i e -> i -> (e -> m e) -> m () updateArray a i f = readArray a i >>= f >>= writeArray a i decoder_mutation :: Int -> M Bool -> V Double -> (Int,V Bool) decoder_mutation maxIterations h lam0 | len /= numCol = error "Haskell.Encode.decoder: bad dimensions" | otherwise = runST $ do lam <- thaw lam0 eta <- thaw (amap (const 0) h) n <- go 0 lam eta -- unsafeFreeze is safe because lam dies (,) n . amap (>0) . trim <$> unsafeFreeze lam where !len = rangeSize lamBounds lamBounds@(lamBase,_) = bounds lam0 !numCol = rangeSize (cBase,cTop) !numRow = rangeSize (rBase,rTop) hBounds@((rBase,cBase),(rTop,cTop)) = bounds h -- numRow is the number of extra parity bits, so drop that many from the -- result vector trim :: V Double -> V Double trim = listArray (1,numCol-numRow) . elems forEta :: Monad m => ((Int,Int) -> m ()) -> m () forEta f = mapM_ (\idx -> when (h!idx) $ f idx) $ range hBounds forEtaRow :: Monad m => (Int -> m ()) -> m () forEtaRow f = mapM_ f $ range (rBase,rTop) forEtaCol :: Monad m => Int -> (Int -> m ()) -> m () forEtaCol row f = mapM_ (\col -> when (h!(row,col)) $ f col) $ range (cBase,cTop) foldlEtaCol :: Monad m => acc -> Int -> (acc -> Int -> m acc) -> m acc foldlEtaCol z row f = go (range (cBase,cTop)) z where go !cols !acc = case cols of [] -> return acc (col:cols) -> (if h!(row,col) then f acc col else return acc) >>= go cols forLamCol :: Monad m => (Int -> m ()) -> m () forLamCol f = mapM_ f (range lamBounds) colEtaToLam :: Int -> Int colEtaToLam col = col-cBase+lamBase {- debug = unsafeIOToST -- switch to the bottom one to enable debugging debug :: IO () -> ST s () debug = const (return ()) rnd :: Double -> Double rnd d = fromIntegral (round (d * 1000.0) :: Int) / 1000.0 putStr7 "" = putStr " " putStr7 s = pad $ let (pre,post) = break (=='.') s in pre ++ if null post then " " else take 4 post where pad t = putStr $ if len < 7 then replicate (7 - len) ' ' ++ t else t where len = length t forEtaCol' :: Monad m => Int -> (Int -> Bool -> m ()) -> m () forEtaCol' row f = mapM_ (\col -> f col (h!(row,col))) $ range (cBase,cTop) dumpEta eta s row = (debug (putStr s >> putStr " ") >>) $ (>> debug (putStrLn "")) $ forEtaCol' row $ \col enabled -> if not enabled then debug $ putStr7 "" >> putStr " " else readArray eta (row,col) >>= \x -> debug $ putStr7 (show (rnd x)) >> putStr " " -} go :: Int -> STV s Double -> STM s Double -> ST s Int go !n !lam !eta | n >= maxIterations = return n | otherwise = do -- unsafeFreeze is safe because lam' doesn't survive this iteration parity <- unsafeFreeze lam >>= \lam' -> do let cHat = amap (>0) lam' let x = multMV "decode" h cHat -- unsafeIOToST $ putStr "cHat " >> showV cHat -- unsafeIOToST $ putStr "x " >> showV x unsafeIOToST $ print $ let es = elems x in (length es,length (filter id es)) return $ not $ or $ elems x -- x is all zeroes if parity then return n else go' n lam eta {-# INLINE go' #-} -- we want a directly recursive go go' :: Int -> STV s Double -> STM s Double -> ST s Int go' !n !lam !eta = do -- unsafeIOToST $ putStr "iteration " >> print n -- eta[r,c] := eta[r,c] - lam[c] forEta $ \idx@(_,col) -> updateArray eta idx $ \e -> (e-) <$> readArray lam (colEtaToLam col) -- lam[c] := lam0[c] -- is there a bulk operation for this? forLamCol $ \col -> writeArray lam col $ lam0!col -- eta[r,c] := min_dagger(eta[r,forall d. d /= c]) -- lam[c] := lam[c] + sum(eta[forall r. r,c]) forEtaRow $ \row -> do -- this is the clever way: take the whole row's min_dagger, then tweak it -- at each element -- collect the minimum and the next-most minimum in the whole row -- NB assumes each row of eta & h has at least two ones (minSign,TwoMD the_min the_2nd_min) <- do let snoc (!sign,!md) !x = (sign * signum x,minMD md $ abs x) foldlEtaCol (1,ZeroMD) row $ \mins col -> snoc mins <$> readArray eta (row,col) forEtaCol row $ \col -> do etav <- readArray eta (row,col) -- sinblingMin is the min_dagger of this element's same-row -- siblings. We recover it from the whole row's TwoMD value by -- "subtracting" this element. let siblingMin = minSign * signum etav * if abs etav == the_min -- dubious use of (==) Double then the_2nd_min else the_min etav' = negate $ 0.75*siblingMin writeArray eta (row,col) etav' {- -- this, on the other hand, is the straight-forward way. (We might -- optimize to add the_mins array as a loop argument) the_mins <- newArray (cBase,cTop) 0 forEtaCol row $ \col -> do the_min <- foldlEtaCol 2 row $ \the_min col2 -> do if col == col2 then return the_min else min_dagger the_min <$> readArray eta (row,col2) writeArray (the_mins `asTypeOf` lam) col the_min forEtaCol row $ \col -> do the_min <- readArray the_mins col let etav' = negate $ 0.75 * the_min writeArray eta (row,col) etav' -} -- add the new eta value to lam updateArray lam (colEtaToLam col) $ return . (+etav') go (n+1) lam eta -- showV = putStrLn . map (\b -> if b then '1' else '0') . elems {-# INLINE min_dagger #-} min_dagger x y = signum x * signum y * min (abs x) (abs y) data MD a = ZeroMD | OneMD a | TwoMD a a {-# INLINE minMD #-} minMD ZeroMD x = OneMD x minMD (OneMD a) x | x < a = TwoMD x a | otherwise = TwoMD a x minMD (TwoMD a b) x | x < a = TwoMD x a | x < b = TwoMD a x | otherwise = TwoMD a b
ku-fpg/ldpc-blob
src/Haskell/Decode.hs
bsd-2-clause
6,316
0
23
1,673
1,794
915
879
87
5
module SpatioTemporalStructure.OrientedMatroid where -- standard modules import Data.List import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe -- local modules import Basics --import Calculus.Dipole import qualified Helpful as H import Interface.LpSolve --import Interface.Clp --import Debug.Trace --type Assignment = Map.Map [Int] Int --data Chirotope = Chirotope (Map.Map [Int] Int) -- Assume that the simpler conditions are already satisfied (e.g. because of -- preprocessing). Only check whether Grassmann-Pluecker can be satisfied. -- Requires that the number of nodes is at least rank + 2 . satisfiesGrassmannPluecker :: Map.Map [Int] Int -> Bool satisfiesGrassmannPluecker m | null keys = True | otherwise = satisfiesGrassmannPluecker_worker missingPermutsWithParities m where keys = Map.keys m rank = length $ head keys sizeOfDomain = length $ nub $ concat keys domain = [0..sizeOfDomain - 1] missingPermutsWithParities = map (H.kPermutationsWithParity rank) (filter (flip Map.notMember m) $ H.kCombinations rank domain) -- This could be done wiser, so we don't have to split the list again -- below! See at function realizable. combis = foldl (\acc x -> (acc ++) $ map (x ++) $ H.kCombinations 4 (domain \\ x) ) [] (H.kCombinations (rank - 2) domain) satisfiesGrassmannPluecker_worker missingPwPs wM | and [ (\y -> (elem (-1) y && elem 1 y) || y == [0,0,0]) [ (Map.!) wM (x ++ [a,b]) * (Map.!) wM (x ++ [c,d]) , (Map.!) wM (x ++ [a,c]) * (Map.!) wM (x ++ [b,d]) * (-1) , (Map.!) wM (x ++ [a,d]) * (Map.!) wM (x ++ [b,c]) ] | xy <- combis , let (x,[a,b,c,d]) = splitAt (rank - 2) xy -- filter the ones in the map. -- fixme: Here we could also drop -- those triples, that have been tested in the last -- backtracking step! , Map.member (x ++ [a,b]) wM , Map.member (x ++ [c,d]) wM , Map.member (x ++ [a,c]) wM , Map.member (x ++ [b,d]) wM , Map.member (x ++ [a,d]) wM , Map.member (x ++ [c,b]) wM ] = if missingPwPs == [] then True else let -- Some optimizations might be helpful at this place. x:pwps = missingPwPs in or $ map (\newSign -> satisfiesGrassmannPluecker_worker pwps (foldl (flip $ uncurry Map.insert) wM [ (y, newSign * z) | (y, z) <- x ] ) ) [(-1), 0, 1] | otherwise = False -- Assume that the simpler conditions (e.g. that m is alternating and not zero) -- are already satisfied. Only check whether the third chirotope axiom can be -- satisfied and whether the chirotope is acyclic. -- TODO: Can we save time by using the fact that the map is alternating? isAcyclicChirotope :: Map.Map [Int] Int ->(Map.Map [Int] Int -> [[Int]] -> Int -> [Int] -> Bool )-> Bool isAcyclicChirotope m f | null keys = True -- | not $ Map.null $ Map.filter (flip notElem [0,1] . abs) m = | (not $ satisfiesThirdAxiom m) || -- /- improve: we should get this from the initial -- /- network instead of reproducing it here. ------------------------------ (not $ isAcyclic (filter H.isSorted $ Map.keys m) m) = False | otherwise = isAcyclicChirotope_worker missingPermutsWithParities [] m nodesInM where keys = Map.keys m rank = length $ head keys domain = Set.toAscList $ Set.fromList $ concat keys nodesInM = nodesIn m -- combis = H.kCombinations (rank + 1) domain missingPermutsWithParities = map (H.kPermutationsWithParity rank) (filter (flip Map.notMember m) $ H.kCombinations rank domain) applyMap k m = -- A triple containing the same node twice has orientation zero. -- TODO: teste ob das unechte triple nicht doch in der Map ist! if H.hasDuplicates k then Just 0 else Map.lookup k m isAcyclicChirotope_worker missingPwPs newTuples wM nodesInwM | satisfiesThirdAxiom wM && isAcyclic (take 1 newTuples) wM = if missingPwPs == [] then -- here we can add a function to run on all full -- chirotopes, e.g. the function "is_realizable" ! -- True f wM keys rank domain else let -- Some optimizations might be helpful at this place. x:stillMissingPwPs = missingPwPs in or $ map (\newSign -> let newConstraints = [ (y, newSign * z) | (y, z) <- x ] in isAcyclicChirotope_worker stillMissingPwPs (map fst newConstraints) (foldr (uncurry Map.insert) wM newConstraints) (foldr Set.insert nodesInwM (intercalate [] $ map fst $ take 1 x)) ) [(-1), 0, 1] | otherwise = False -- here we check whether the chirotope axiom B2' from -- "A. Björner et al: Oriented Matroids, 2nd ed., page 128" -- is fulfilled. Only checking the Grassmann-Pluecker condition is not -- sufficient since we also have to check, that the absolute value of the -- mapping is a matroid. satisfiesThirdAxiom m = let -- improve: can we make use of the newly introduced constraints in -- order to reduce the number of tuples to test in this step? tuplePairs = H.kPermutations 2 $ Map.keys $ Map.filter (/= 0) m in and [ or [ case applyMap (y:tailTuple1) m of Nothing -> True Just 0 -> False Just rel3 -> case applyMap (lefty ++ x:righty) m of Nothing -> True Just 0 -> False Just rel4 -> rel1 * rel2 == rel3 * rel4 | y <- tuple2 , let (lefty, _:righty) = break (== y) tuple2 ] | [tuple1@(x:tailTuple1), tuple2] <- tuplePairs , let rel1 = fromJust $ applyMap tuple1 m , let rel2 = fromJust $ applyMap tuple2 m ] -- See "Ralf Gugish: A Construction of Isomorphism Classes of Oriented -- Matroids, in Algorithmic Algebraic Combinatorics and -- Gröbner Bases, p. 236" isAcyclic newTuples m = {-# SCC "isAcyclic" #-} let positiveCircuitElemsOf z = filter (\x -> maybe True (\y -> (-1)^(fromJust $ elemIndex x z) * y == (-1)) $ Map.lookup (delete x z) m ) z negativeCircuitElemsOf z = filter (\x -> maybe True (\y -> (-1)^(fromJust $ elemIndex x z) * y == 1) $ Map.lookup (delete x z) m ) z combis = [ insert y x | x <- newTuples, y <- domain, not $ elem y x ] circuits = [ (positiveCircuitElemsOf c, negativeCircuitElemsOf c) | c <- combis ] in not $ any (\(x,y) -> ( null y && not (null x) ) --fixme: is it right to include the negative circuits -- here? I did it because the indian tent -- configuration gave either a negative or a -- positive circuit depending on the -- orientation of the tent. || ( null x && not (null y) ) ) circuits -- search for a bi-quadratic final polynomial via translation into a -- Linear Programming Problem. Only works for uniform chirotopes. -- The chirotope axioms are not checked. hasNoBiquadraticFinalPolynomial :: Map.Map [Int] Int -> [[Int]] -> Int -> [Int] -> Bool hasNoBiquadraticFinalPolynomial m keys rank domain = case zeroObjective lpInput of Nothing -> False Just True -> False Just False -> True where lpInput = ("max: s ;\n" ++) $ concatMap (\[a,b,c,d] -> "v_" ++ showBracket a ++ " + v_" ++ showBracket b ++ " - v_" ++ showBracket c ++ " - v_" ++ showBracket d ++ " + s <= 0 ;\n" ) absoluteQuadratics -- lpInput = (++ "END") $ ("MIN\n -s\nST\n" ++) $ concatMap -- (\[a,b,c,d] -> " v_" ++ showBracket a ++ -- " + v_" ++ showBracket b ++ -- " - v_" ++ showBracket c ++ -- " - v_" ++ showBracket d ++ " + s <= 0\n" -- ) absoluteQuadratics showBracket = intercalate "_" . map show absoluteQuadratics = map (\(x, [a,b,c,d]) -> [ sort $ x ++ [a,b] , sort $ x ++ [c,d] , sort $ x ++ [a,c] , sort $ x ++ [b,d] ] ) $ filter (\(x, [a,b,c,d]) -> chi (x ++ [a,b]) * chi (x ++ [c,d]) > 0 && chi (x ++ [a,c]) * chi (x ++ [b,d]) > 0 && chi (x ++ [a,d]) * chi (x ++ [b,c]) > 0 ) $ foldl (\acc x -> (acc ++) $ map (\y -> (x,y)) $ H.kPermutations 4 (domain \\ x) ) [] (H.kCombinations (rank - 2) domain) chi = (Map.!) m -- keys = Map.keys m -- rank = length $ head keys -- domain = nub $ concat keys hasBiquadraticFinalPolynomial :: Map.Map [Int] Int -> [[Int]] -> Int -> [Int] -> Bool hasBiquadraticFinalPolynomial a b c d = not $ hasNoBiquadraticFinalPolynomial a b c d
spatial-reasoning/zeno
src/SpatioTemporalStructure/OrientedMatroid.hs
bsd-2-clause
10,799
0
24
4,579
2,572
1,382
1,190
163
7
-- |Implementation of the gaurantee semantics and forwarding semantics of -- PolicyTrees module HFT ( Action , MatchTable (..) , compileShareTree , emptyTable , unionTable , concatTable , condense ) where import Data.Tree (Tree (..)) import ShareTree (Share (..)) import Base import Data.List (groupBy, find) import qualified Flows as Flows type Action = Maybe (ReqData, Limit) -- ^ (Request, timeout in absolute time) data MatchTable = MatchTable [(Flows.FlowGroup, Action)] deriving (Show, Eq) emptyAction = Nothing activeAt now req = reqStart req <= now && fromInteger now <= reqEnd req -- Strictness is a static restriction on share trees. They are not part of -- HFTs. The Req datatype was designed to be a share-tree element, but we're -- overloading it here to be an HFT. (Same reasoning applies to speakers/ -- principals, but we didn't make that part of the request.) reqToAction (Req _ _ _ end req strict) = Just (req, end) combineMaybe :: (a -> a -> a) -> Maybe (a, Limit) -> Maybe (a, Limit) -> Maybe (a, Limit) combineMaybe _ Nothing Nothing = Nothing combineMaybe _ (Just (a, t)) Nothing = Just (a, t) combineMaybe _ Nothing (Just (b, t)) = Just (b, t) combineMaybe f (Just (a, s)) (Just (b, t)) = Just (f a b, min s t) combineSiblingActions act1 act2 = combineMaybe f act1 act2 where f (ReqResv m) (ReqResv n) = ReqResv (max m n) f (ReqResv m) ReqAllow = ReqResv m f ReqAllow (ReqResv n) = ReqResv n f ReqAllow ReqAllow = ReqAllow f (ReqRlimit m) (ReqRlimit n) = ReqRlimit (min m n) f (ReqRlimit m) ReqAllow = ReqRlimit m f ReqAllow (ReqRlimit n) = ReqRlimit n f _ _ = ReqDeny combineParentChildActions act1 act2 = combineMaybe f act1 act2 where -- f parent child = child overrides parent, with the exceptions below f (ReqResv m) (ReqResv n) = ReqResv (max m n) -- pick max, doesn't hurt f (ReqResv m) ReqAllow = ReqResv m -- give guarantee, doesn't hurt f (ReqRlimit m) (ReqRlimit n) = ReqRlimit (min m n) -- pick min, doesn't hurt f (ReqRlimit m) ReqAllow = ReqRlimit m -- enforce limit , doesn't hurt f _ ch = ch emptyTable :: MatchTable emptyTable = MatchTable [] intersectTable :: (Action -> Action -> Action) -> MatchTable -> MatchTable -> Bool -- Set to true iff used in unionTable -> MatchTable intersectTable cmb (MatchTable tbl1) (MatchTable tbl2) optForUnion = MatchTable tbl' where tbl' = [ (f1 ∩ f2, cmb a1 a2) | (f1, a1) <- tbl1, (f2, a2) <- tbl2, not (Flows.null (f1 ∩ f2)), -- skip unnecessary intersection as an optimization: not (optForUnion && (a1 == a2)) ] (∩) = Flows.intersection -- Note: this is a left-biased union. unionTable :: (Action -> Action -> Action) -> MatchTable -> MatchTable -> MatchTable unionTable cmb mt1@(MatchTable tbl1) mt2@(MatchTable tbl2) = MatchTable (tbl' ++ tbl1 ++ tbl2) where (MatchTable tbl') = intersectTable cmb mt1 mt2 True concatTable mt1@(MatchTable tbl1) mt2@(MatchTable tbl2) = MatchTable (tbl1 ++ tbl2) shareToTable :: Integer -> Share -> MatchTable shareToTable now share = foldl (unionTable combineSiblingActions) emptyTable (map reqToTbl reqs) where reqs = filter (activeAt now) (shareReq share) reqToTbl req = MatchTable [(reqFlows req, reqToAction req)] shareTreeToTable :: Integer -- ^current time -> Tree Share -- ^share tree -> MatchTable shareTreeToTable now (Node share children) = tbl where thisTbl = shareToTable now share childTbls = map (shareTreeToTable now) children cmbChildTbl = foldl (unionTable combineSiblingActions) emptyTable childTbls tbl = unionTable combineParentChildActions thisTbl cmbChildTbl -- Scans MatchTable left to right and drops any rules whose flow is shadowed -- by a flow to the left in the table. condense :: Integer -> MatchTable -> MatchTable condense now (MatchTable tbl) = MatchTable (loop [] tbl') where loop _ [] = [] loop lhs ((f, action):rest) = case any (\leftF -> f `Flows.isSubFlow` leftF) lhs of True -> loop lhs rest False -> (f,action):(loop (f:lhs) rest) tbl' = filter isNotExpired tbl isNotExpired (_, Just (_, expiry)) = expiry >= (fromInteger now) isNotExpired (_, Nothing) = False compileShareTree :: Integer -- ^current time -> Tree Share -- ^share tree -> MatchTable compileShareTree now tree = condense now (shareTreeToTable now tree)
brownsys/pane
src/HFT.hs
bsd-3-clause
4,998
0
14
1,508
1,461
774
687
94
8
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveGeneric #-} module CollabHandlers where import Control.Applicative import Snap.Core import Snap.Snaplet import Snap.Extras.CoreUtils import Snap.Extras.JSON import Snap.Snaplet.PostgresqlSimple import Control.Monad (when) import qualified Data.Aeson as A import Data.Aeson import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.UUID as UUID import GHC.Generics import Snap.Snaplet.Auth import Application import CollabTypes requireMod :: Handler App (AuthManager App) () requireMod = do u <- currentUser mods <- withTop db $ query_ "SELECT * FROM mods;" when (Only (maybe "" userLogin u) `notElem` mods) (badReq "Access denied") getModel :: Handler App (AuthManager App) Model getModel = do thrusts <- getThrusts projects <- getProjects projmems <- withTop db $ query_ "SELECT * FROM projectmember" let members = concatMap _piMembers (concatMap _thrustPIs thrusts) :: [Member] memsOfProj :: Project -> [Member] memsOfProj p = let mIDs = map fst . filter (\pm -> _projectID p == snd pm) $ projmems in filter (\m -> _memberID m `elem` mIDs) members projects' :: [Project] projects' = map (\p -> p {_projectMembers = memsOfProj p}) projects return $ Model thrusts projects' [] Nothing getThrusts :: Handler App (AuthManager App) [Thrust] getThrusts = do thrusts <- withTop db $ query_ "SELECT * FROM thrust;" pis <- getPIs return $ flip map thrusts $ \t@Thrust{..} -> t { _thrustPIs = filter (\PI{..} -> _piThrust == _thrustID) pis} getPIs :: Handler App (AuthManager App) [PI] getPIs = do pis <- withTop db $ query_ "SELECT * FROM pi;" members <- getMembers return $ flip map pis $ \p@PI{..} -> p { _piMembers = filter (\Member{..} -> _memberPI == _piID) members} getMembers :: Handler App (AuthManager App) [Member] getMembers = do withTop db $ query_ "SELECT * FROM member;" getProjects :: Handler App (AuthManager App) [Project] getProjects = withTop db $ query_ "SELECT * FROM project;" handleThrusts :: Handler App (AuthManager App) () handleThrusts = method GET (getThrusts >>= writeJSON) <|> method POST (requireMod >> postThrust) where postThrust = do InsThrust{..} <- reqJSON [Only i] <- withTop db $ query "INSERT INTO thrust(name) VALUES (?)" (Only ithrustName) writeJSON (Thrust i ithrustName []) handleModel :: Handler App (AuthManager App) () handleModel = do getModel >>= writeJSON handleThrust :: Handler App (AuthManager App) () handleThrust = do idBytes <- reqParam "id" tID <- maybe (badReq "No id parse") return (UUID.fromASCIIBytes idBytes) method DELETE (requireMod >> deleteThrust tID) <|> method PUT (requireMod >> putThrust tID) where deleteThrust i = do withTop db $ execute "DELETE FROM thrust WHERE id=(?)" (Only i) writeBS "Ok" putThrust i = do (Thrust i nm pis) <- reqJSON [Only r] <- withTop db $ query "UPDATE thrust WITH name=(?) WHERE id=(?);" (nm, i) writeJSON (Thrust r nm pis) handleProjects :: Handler App (AuthManager App) () handleProjects = method GET (getProjects >>= writeJSON) <|> method POST (requireMod >> postProject) where postProject = do (InsProject nm ws) <- reqJSON [Only r] <- withTop db $ query "INSERT INTO project(name,website) VALUES (?,?) returning id;" (nm, ws) writeJSON (Project r nm ws []) handleProject :: Handler App (AuthManager App) () handleProject = do idBytes <- reqParam "id" pID <- maybe (badReq "No id parse") return (UUID.fromASCIIBytes idBytes) method DELETE (requireMod >> deleteProject pID) <|> method PUT (requireMod >> putProject pID) where deleteProject i = do withTop db $ execute "DELETE FROM project WHERE id=(?);" (Only i) writeBS "Ok." putProject i = do Project{..} <- reqJSON [Only r] <- withTop db $ query "UPDATE project WITH name=(?), site=(?) WHERE id=(?);" (_projectName, _projectSite, i) writeJSON (Project r _projectName _projectSite _projectMembers) handleMembers :: Handler App (AuthManager App) () handleMembers = method GET (getMembers >>= writeJSON) <|> method POST (requireMod >> insertMember) where insertMember = do (InsMember imn imPI iws) <- reqJSON [Only i] <- withTop db $ query "INSERT INTO member(name,pi,website) VALUES (?,?,?) returning id;" (imn, imPI, iws) writeJSON (Member i imn imPI iws) handleMember :: Handler App (AuthManager App) () handleMember = do idBytes <- reqParam "id" mID <- maybe (badReq "No id parse") return (UUID.fromASCIIBytes idBytes) method DELETE (requireMod >> deleteMem mID) <|> method PUT (requireMod >> putMem mID) where deleteMem i = do withTop db $ execute "DELETE FROM member WHERE id=(?)" (Only i) writeBS "Ok." putMem i = do (InsMember nm mPi ws) <- reqJSON [Only r] <- withTop db $ query "UPDATE member SET name=(?),pi=(?),website=(?) WHERE id=(?)" (nm, mPi, ws, i) writeJSON (Member r nm mPi ws) handlePIs :: Handler App (AuthManager App) () handlePIs = method GET (getPIs >>= writeJSON) <|> method POST (requireMod >> insertPI) where insertPI = do (InsPI nm th ws) <- reqJSON [Only i] <- withTop db $ query "INSERT INTO pi(name,thrust,website) VALUES (?,?,?) returning id;" (nm,(th :: UUID.UUID),ws) writeJSON (PI i nm th ws []) handlePI :: Handler App (AuthManager App) () handlePI = do idBytes <- reqParam "id" piID <- maybe (badReq "No parse for id") return (UUID.fromASCIIBytes idBytes) method DELETE (requireMod >> deletePI piID) <|> method PUT (requireMod >> putPI piID) where deletePI i = do withTop db $ execute "DELETE FROM pi WHERE id=(?)" (Only i) writeBS "Ok." putPI i = do PI{..} <- reqJSON [Only r] <- withTop db $ query "UPDATE pi SET name=(?), thrust=(?), site=(?) WHERE id=(?);" (_piName, _piThrust, _piSite, (i :: UUID.UUID)) writeJSON (PI r _piName _piThrust _piSite _piMembers) instance ToRow PI where toRow PI{..} = toRow (_piID, _piName, _piThrust, _piSite) instance FromRow PI where fromRow = PI <$> field <*> field <*> field <*> field <*> pure [] instance FromRow Member where fromRow = Member <$> field <*> field <*> field <*> field instance ToRow Member where toRow Member{..} = toRow (_memberID, _memberName, _memberPI, _memberSite) instance ToRow Project where toRow Project{..} = toRow (_projectID, _projectName, _projectSite) instance FromRow Project where fromRow = Project <$> field <*> field <*> field <*> pure [] instance ToRow Thrust where toRow (Thrust tID tName _) = toRow (tID, tName) instance FromRow Thrust where fromRow = Thrust <$> field <*> field <*> pure []
imalsogreg/collabplot
server/src/CollabHandlers.hs
bsd-3-clause
7,312
0
20
1,881
2,401
1,197
1,204
165
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE ParallelListComp #-} module CRDT.Cv.RGA ( RGA (..) , fromList , toList , edit , RgaString , fromString , toString -- * Packed representation , RgaPacked , pack , unpack ) where import Data.Algorithm.Diff (PolyDiff (Both, First, Second), getGroupedDiffBy) import Data.Empty (AsEmpty (..)) import Data.Function (on) import Data.Semilattice (Semilattice) import Data.Traversable (for) import CRDT.LamportClock (Clock, LamportTime (LamportTime), getTimes) type VertexId = LamportTime -- | TODO(cblp, 2018-02-06) Vector.Unboxed newtype RGA a = RGA [(VertexId, a)] deriving (Eq, Show) type RgaString = RGA Char merge :: (Eq a, AsEmpty a) => RGA a -> RGA a -> RGA a merge (RGA vertices1) (RGA vertices2) = RGA $ mergeVertexLists vertices1 vertices2 where mergeVertexLists [] vs2 = vs2 mergeVertexLists vs1 [] = vs1 mergeVertexLists (v1@(id1, a1):vs1) (v2@(id2, a2):vs2) = case compare id1 id2 of LT -> v2 : mergeVertexLists (v1 : vs1) vs2 GT -> v1 : mergeVertexLists vs1 (v2 : vs2) EQ -> (id1, mergeAtoms a1 a2) : mergeVertexLists vs1 vs2 -- priority of deletion mergeAtoms a1 a2 | isEmpty a1 || isEmpty a2 = empty | a1 == a2 = a1 | otherwise = empty -- error: contradiction instance (Eq a, AsEmpty a) => Semigroup (RGA a) where (<>) = merge instance (Eq a, AsEmpty a) => Semilattice (RGA a) -- Why not? instance (Eq a, AsEmpty a) => Monoid (RGA a) where mempty = RGA [] mappend = (<>) toList :: AsEmpty a => RGA a -> [a] toList (RGA rga) = [ a | (_, a) <- rga, isNotEmpty a ] toString :: RgaString -> String toString = toList fromList :: Clock m => [a] -> m (RGA a) fromList = fmap RGA . fromList' fromList' :: Clock m => [a] -> m [(VertexId, a)] fromList' xs = do LamportTime time0 pid <- getTimes . fromIntegral $ length xs pure [ (LamportTime time pid, x) | time <- [time0..] | x <- xs ] fromString :: Clock m => String -> m RgaString fromString = fromList -- | Replace content with specified, -- applying changed found by the diff algorithm edit :: (Eq a, AsEmpty a, Clock m) => [a] -> RGA a -> m (RGA a) edit newList (RGA oldRga) = fmap (RGA . concat) . for diff $ \case First removed -> pure [ (vid, empty) | (vid, _) <- removed ] Both v _ -> pure v Second added -> fromList' $ map snd added where newList' = [ (undefined, a) | a <- newList ] diff = getGroupedDiffBy ((==) `on` snd) oldRga newList' -- | Compact version of 'RGA'. -- For each 'VertexId', the corresponding sequence of vetices has the same 'Pid' -- and sequentially growing 'LocalTime', starting with the specified one. type RgaPacked a = [(VertexId, [a])] pack :: RGA a -> RgaPacked a pack (RGA [] ) = [] pack (RGA ((first, atom):vs)) = go first [atom] 1 vs where -- TODO(cblp, 2018-02-08) buf :: DList go vid buf _ [] = [(vid, buf)] go vid buf dt ((wid, a):ws) | wid == next dt vid = go vid (buf ++ [a]) (succ dt) ws | otherwise = (vid, buf) : go wid [a] 1 ws next dt (LamportTime t p) = LamportTime (t + dt) p unpack :: RgaPacked a -> RGA a unpack packed = RGA $ do (LamportTime time pid, atoms) <- packed [ (LamportTime (time + i) pid, atom) | i <- [0..] | atom <- atoms ]
cblp/crdt
crdt/lib/CRDT/Cv/RGA.hs
bsd-3-clause
3,516
2
13
1,006
1,334
717
617
75
5
module Main where import Person main :: IO () main = print$firstName$Person "Gabriel" "Ariel" 17 1.90 "3330-7320" "morango"
Hidowga/Projetos
Main.hs
bsd-3-clause
135
0
7
29
43
22
21
4
1
-- ----------------------------------------------------------------------------- -- -- DFA.hs, part of Alex -- -- (c) Chris Dornan 1995-2000, Simon Marlow 2003 -- -- This module generates a DFA from a scanner by first converting it -- to an NFA and then converting the NFA with the subset construction. -- -- See the chapter on `Finite Automata and Lexical Analysis' in the -- dragon book for an excellent overview of the algorithms in this -- module. -- -- ----------------------------------------------------------------------------} module DFA(scanner2dfa) where import AbsSyn import qualified Map import qualified Data.IntMap as IntMap import NFA import Sort ( msort, nub' ) import CharSet import Data.Array ( (!) ) import Data.Maybe ( fromJust ) {- Defined in the Scan Module -- (This section should logically belong to the DFA module but it has been -- placed here to make this module self-contained.) -- -- `DFA' provides an alternative to `Scanner' (described in the RExp module); -- it can be used directly to scan text efficiently. Additionally it has an -- extra place holder for holding action functions for generating -- application-specific tokens. When this place holder is not being used, the -- unit type will be used. -- -- Each state in the automaton consist of a list of `Accept' values, descending -- in priority, and an array mapping characters to new states. As the array -- may only cover a sub-range of the characters, a default state number is -- given in the third field. By convention, all transitions to the -1 state -- represent invalid transitions. -- -- A list of accept states is provided for as the original specification may -- have been ambiguous, in which case the highest priority token should be -- taken (the one appearing earliest in the specification); this can not be -- calculated when the DFA is generated in all cases as some of the tokens may -- be associated with leading or trailing context or start codes. -- -- `scan_token' (see above) can deal with unconditional accept states more -- efficiently than those associated with context; to save it testing each time -- whether the list of accept states contains an unconditional state, the flag -- in the first field of `St' is set to true whenever the list contains an -- unconditional state. -- -- The `Accept' structure contains the priority of the token being accepted -- (lower numbers => higher priorities), the name of the token, a place holder -- that can be used for storing the `action' function for constructing the -- token from the input text and thge scanner's state, a list of start codes -- (listing the start codes that the scanner must be in for the token to be -- accepted; empty => no restriction), the leading and trailing context (both -- `Nothing' if there is none). -- -- The leading context consists simply of a character predicate that will -- return true if the last character read is acceptable. The trailing context -- consists of an alternative starting state within the DFA; if this `sub-dfa' -- turns up any accepting state when applied to the residual input then the -- trailing context is acceptable (see `scan_token' above). type DFA a = Array SNum (State a) type SNum = Int data State a = St Bool [Accept a] SNum (Array Char SNum) data Accept a = Acc Int String a [StartCode] (MB(Char->Bool)) (MB SNum) type StartCode = Int -} -- Scanners are converted to DFAs by converting them to NFAs first. Converting -- an NFA to a DFA works by identifying the states of the DFA with subsets of -- the NFA. The PartDFA is used to construct the DFA; it is essentially a DFA -- in which the states are represented directly by state sets of the NFA. -- `nfa2pdfa' constructs the partial DFA from the NFA by searching for all the -- transitions from a given list of state sets, initially containing the start -- state of the partial DFA, until all possible state sets have been considered -- The final DFA is then constructed with a `mk_dfa'. scanner2dfa:: Encoding -> Scanner -> [StartCode] -> DFA SNum Code scanner2dfa enc scanner scs = nfa2dfa scs (scanner2nfa enc scanner scs) nfa2dfa:: [StartCode] -> NFA -> DFA SNum Code nfa2dfa scs nfa = mk_int_dfa nfa (nfa2pdfa nfa pdfa (dfa_start_states pdfa)) where pdfa = new_pdfa n_starts nfa n_starts = length scs -- number of start states -- `nfa2pdfa' works by taking the next outstanding state set to be considered -- and ignoring it if the state is already in the partial DFA, otherwise -- generating all possible transitions from it, adding the new state to the -- partial DFA and continuing the closure with the extra states. Note the way -- it incorporates the trailing context references into the search (by -- including `rctx_ss' in the search). nfa2pdfa:: NFA -> DFA StateSet Code -> [StateSet] -> DFA StateSet Code nfa2pdfa _ pdfa [] = pdfa nfa2pdfa nfa pdfa (ss:umkd) | ss `in_pdfa` pdfa = nfa2pdfa nfa pdfa umkd | otherwise = nfa2pdfa nfa pdfa' umkd' where pdfa' = add_pdfa ss (State accs (IntMap.fromList ss_outs)) pdfa umkd' = rctx_sss ++ map snd ss_outs ++ umkd -- for each character, the set of states that character would take -- us to from the current set of states in the NFA. ss_outs :: [(Int, StateSet)] ss_outs = [ (fromIntegral ch, mk_ss nfa ss') | ch <- byteSetElems $ setUnions [p | (p,_) <- outs], let ss' = [ s' | (p,s') <- outs, byteSetElem p ch ], not (null ss') ] rctx_sss = [ mk_ss nfa [s] | Acc _ _ _ (RightContextRExp s) <- accs ] outs :: [(ByteSet,SNum)] outs = [ out | s <- ss, out <- nst_outs (nfa!s) ] accs = sort_accs [acc| s<-ss, acc<-nst_accs (nfa!s)] -- `sort_accs' sorts a list of accept values into decending order of priority, -- eliminating any elements that follow an unconditional accept value. sort_accs:: [Accept a] -> [Accept a] sort_accs accs = foldr chk [] (msort le accs) where chk acc@(Acc _ _ Nothing NoRightContext) _ = [acc] chk acc rst = acc:rst le (Acc{accPrio = n}) (Acc{accPrio=n'}) = n<=n' {------------------------------------------------------------------------------ State Sets and Partial DFAs ------------------------------------------------------------------------------} -- A `PartDFA' is a partially constructed DFA in which the states are -- represented by sets of states of the original NFA. It is represented by a -- triple consisting of the start state of the partial DFA, the NFA from which -- it is derived and a map from state sets to states of the partial DFA. The -- state set for a given list of NFA states is calculated by taking the epsilon -- closure of all the states, sorting the result with duplicates eliminated. type StateSet = [SNum] new_pdfa:: Int -> NFA -> DFA StateSet a new_pdfa starts nfa = DFA { dfa_start_states = start_ss, dfa_states = Map.empty } where start_ss = [ msort (<=) (nst_cl(nfa!n)) | n <- [0..(starts-1)]] -- starts is the number of start states -- constructs the epsilon-closure of a set of NFA states mk_ss:: NFA -> [SNum] -> StateSet mk_ss nfa l = nub' (<=) [s'| s<-l, s'<-nst_cl(nfa!s)] add_pdfa:: StateSet -> State StateSet a -> DFA StateSet a -> DFA StateSet a add_pdfa ss pst (DFA st mp) = DFA st (Map.insert ss pst mp) in_pdfa:: StateSet -> DFA StateSet a -> Bool in_pdfa ss (DFA _ mp) = ss `Map.member` mp -- Construct a DFA with numbered states, from a DFA whose states are -- sets of states from the original NFA. mk_int_dfa:: NFA -> DFA StateSet a -> DFA SNum a mk_int_dfa nfa (DFA start_states mp) = DFA [0 .. length start_states-1] (Map.fromList [ (lookup' st, cnv pds) | (st, pds) <- Map.toAscList mp ]) where mp' = Map.fromList (zip (start_states ++ (map fst . Map.toAscList) (foldr Map.delete mp start_states)) [0..]) lookup' = fromJust . flip Map.lookup mp' cnv :: State StateSet a -> State SNum a cnv (State accs as) = State accs' as' where as' = IntMap.mapWithKey (\_ch s -> lookup' s) as accs' = map cnv_acc accs cnv_acc (Acc p a lctx rctx) = Acc p a lctx rctx' where rctx' = case rctx of RightContextRExp s -> RightContextRExp (lookup' (mk_ss nfa [s])) other -> other {- -- `mk_st' constructs a state node from the list of accept values and a list of -- transitions. The transitions list all the valid transitions out of the -- node; all invalid transitions should be represented in the array by state -- -1. `mk_st' has to work out whether the accept states contain an -- unconditional entry, in which case the first field of `St' should be true, -- and which default state to use in constructing the array (the array may span -- a sub-range of the character set, the state number given the third argument -- of `St' being taken as the default if an input character lies outside the -- range). The default values is chosen to minimise the bounds of the array -- and so there are two candidates: the value that 0 maps to (in which case -- some initial segment of the array may be omitted) or the value that 255 maps -- to (in which case a final segment of the array may be omitted), hence the -- calculation of `(df,bds)'. -- -- Note that empty arrays are avoided as they can cause severe problems for -- some popular Haskell compilers. mk_st:: [Accept Code] -> [(Char,Int)] -> State Code mk_st accs as = if null as then St accs (-1) (listArray ('0','0') [-1]) else St accs df (listArray bds [arr!c| c<-range bds]) where bds = if sz==0 then ('0','0') else bds0 (sz,df,bds0) | sz1 < sz2 = (sz1,df1,bds1) | otherwise = (sz2,df2,bds2) (sz1,df1,bds1) = mk_bds(arr!chr 0) (sz2,df2,bds2) = mk_bds(arr!chr 255) mk_bds df = (t-b, df, (chr b, chr (255-t))) where b = length (takeWhile id [arr!c==df| c<-['\0'..'\xff']]) t = length (takeWhile id [arr!c==df| c<-['\xff','\xfe'..'\0']]) arr = listArray ('\0','\xff') (take 256 (repeat (-1))) // as -}
simonmar/alex
src/DFA.hs
bsd-3-clause
10,525
6
19
2,552
1,331
720
611
66
2
{- - Everything here is evil by definition. -} module System.DotFS.Core.Constants where import System.DotFS.Core.Datatypes import System.Fuse import System.Posix.Files -- there is a system call for this. -- but never mind, since we have a read-only file -- system, we don't need that. dotfsGetFileSystemStats :: Conf -> String -> IO (Either Errno FileSystemStats) dotfsGetFileSystemStats dp str = -- use stats from home dp return $ Right FileSystemStats { fsStatBlockSize = 512 , fsStatBlockCount = 1000 , fsStatBlocksFree = 0 , fsStatBlocksAvailable = 0 , fsStatFileCount = 5 -- IS THIS CORRECT? , fsStatFilesFree = 10 -- WHAT IS THIS? , fsStatMaxNameLength = 255 -- SEEMS SMALL? } -- this is dummy data, and turns out to never be -- shown, even when doing `ls -la` dirStat = FileStat { statEntryType = Directory , statFileMode = ownerReadMode , statLinkCount = 5 , statFileOwner = 666 , statFileGroup = 666 , statSpecialDeviceID = 0 , statFileSize = 4096 , statBlocks = 1 , statAccessTime= 0 , statModificationTime = 0 , statStatusChangeTime = 0 }
toothbrush/dotfs
System/DotFS/Core/Constants.hs
bsd-3-clause
1,135
0
9
256
194
125
69
26
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} {-# OPTIONS_GHC -funbox-strict-fields #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Encoding -- Copyright : (c) The University of Glasgow, 2008-2009 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- Text codecs for I/O -- ----------------------------------------------------------------------------- module GHC.IO.Encoding ( BufferCodec(..), TextEncoding(..), TextEncoder, TextDecoder, CodingProgress(..), latin1, latin1_encode, latin1_decode, utf8, utf8_bom, utf16, utf16le, utf16be, utf32, utf32le, utf32be, initLocaleEncoding, getLocaleEncoding, getFileSystemEncoding, getForeignEncoding, setLocaleEncoding, setFileSystemEncoding, setForeignEncoding, char8, mkTextEncoding, ) where import GHC.Base import GHC.IO.Exception import GHC.IO.Buffer import GHC.IO.Encoding.Failure import GHC.IO.Encoding.Types #if !defined(mingw32_HOST_OS) import qualified GHC.IO.Encoding.Iconv as Iconv #else import qualified GHC.IO.Encoding.CodePage as CodePage import Text.Read (reads) #endif import qualified GHC.IO.Encoding.Latin1 as Latin1 import qualified GHC.IO.Encoding.UTF8 as UTF8 import qualified GHC.IO.Encoding.UTF16 as UTF16 import qualified GHC.IO.Encoding.UTF32 as UTF32 import GHC.List import GHC.Word import Data.IORef import Data.Char (toUpper) import System.IO.Unsafe (unsafePerformIO) -- ----------------------------------------------------------------------------- -- | The Latin1 (ISO8859-1) encoding. This encoding maps bytes -- directly to the first 256 Unicode code points, and is thus not a -- complete Unicode encoding. An attempt to write a character greater than -- '\255' to a 'Handle' using the 'latin1' encoding will result in an error. latin1 :: TextEncoding latin1 = Latin1.latin1_checked -- | The UTF-8 Unicode encoding utf8 :: TextEncoding utf8 = UTF8.utf8 -- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte -- sequence 0xEF 0xBB 0xBF). This encoding behaves like 'utf8', -- except that on input, the BOM sequence is ignored at the beginning -- of the stream, and on output, the BOM sequence is prepended. -- -- The byte-order-mark is strictly unnecessary in UTF-8, but is -- sometimes used to identify the encoding of a file. -- utf8_bom :: TextEncoding utf8_bom = UTF8.utf8_bom -- | The UTF-16 Unicode encoding (a byte-order-mark should be used to -- indicate endianness). utf16 :: TextEncoding utf16 = UTF16.utf16 -- | The UTF-16 Unicode encoding (litte-endian) utf16le :: TextEncoding utf16le = UTF16.utf16le -- | The UTF-16 Unicode encoding (big-endian) utf16be :: TextEncoding utf16be = UTF16.utf16be -- | The UTF-32 Unicode encoding (a byte-order-mark should be used to -- indicate endianness). utf32 :: TextEncoding utf32 = UTF32.utf32 -- | The UTF-32 Unicode encoding (litte-endian) utf32le :: TextEncoding utf32le = UTF32.utf32le -- | The UTF-32 Unicode encoding (big-endian) utf32be :: TextEncoding utf32be = UTF32.utf32be -- | The Unicode encoding of the current locale -- -- @since 4.5.0.0 getLocaleEncoding :: IO TextEncoding -- | The Unicode encoding of the current locale, but allowing arbitrary -- undecodable bytes to be round-tripped through it. -- -- This 'TextEncoding' is used to decode and encode command line arguments -- and environment variables on non-Windows platforms. -- -- On Windows, this encoding *should not* be used if possible because -- the use of code pages is deprecated: Strings should be retrieved -- via the "wide" W-family of UTF-16 APIs instead -- -- @since 4.5.0.0 getFileSystemEncoding :: IO TextEncoding -- | The Unicode encoding of the current locale, but where undecodable -- bytes are replaced with their closest visual match. Used for -- the 'CString' marshalling functions in "Foreign.C.String" -- -- @since 4.5.0.0 getForeignEncoding :: IO TextEncoding -- | @since 4.5.0.0 setLocaleEncoding, setFileSystemEncoding, setForeignEncoding :: TextEncoding -> IO () (getLocaleEncoding, setLocaleEncoding) = mkGlobal initLocaleEncoding (getFileSystemEncoding, setFileSystemEncoding) = mkGlobal initFileSystemEncoding (getForeignEncoding, setForeignEncoding) = mkGlobal initForeignEncoding mkGlobal :: a -> (IO a, a -> IO ()) mkGlobal x = unsafePerformIO $ do x_ref <- newIORef x return (readIORef x_ref, writeIORef x_ref) -- | @since 4.5.0.0 initLocaleEncoding, initFileSystemEncoding, initForeignEncoding :: TextEncoding #if !defined(mingw32_HOST_OS) -- It is rather important that we don't just call Iconv.mkIconvEncoding here -- because some iconvs (in particular GNU iconv) will brokenly UTF-8 encode -- lone surrogates without complaint. -- -- By going through our Haskell implementations of those encodings, we are -- guaranteed to catch such errors. -- -- FIXME: this is not a complete solution because if the locale encoding is one -- which we don't have a Haskell-side decoder for, iconv might still ignore the -- lone surrogate in the input. initLocaleEncoding = unsafePerformIO $ mkTextEncoding' ErrorOnCodingFailure Iconv.localeEncodingName initFileSystemEncoding = unsafePerformIO $ mkTextEncoding' RoundtripFailure Iconv.localeEncodingName initForeignEncoding = unsafePerformIO $ mkTextEncoding' IgnoreCodingFailure Iconv.localeEncodingName #else initLocaleEncoding = CodePage.localeEncoding initFileSystemEncoding = CodePage.mkLocaleEncoding RoundtripFailure initForeignEncoding = CodePage.mkLocaleEncoding IgnoreCodingFailure #endif -- | An encoding in which Unicode code points are translated to bytes -- by taking the code point modulo 256. When decoding, bytes are -- translated directly into the equivalent code point. -- -- This encoding never fails in either direction. However, encoding -- discards information, so encode followed by decode is not the -- identity. -- -- @since 4.4.0.0 char8 :: TextEncoding char8 = Latin1.latin1 -- | Look up the named Unicode encoding. May fail with -- -- * 'isDoesNotExistError' if the encoding is unknown -- -- The set of known encodings is system-dependent, but includes at least: -- -- * @UTF-8@ -- -- * @UTF-16@, @UTF-16BE@, @UTF-16LE@ -- -- * @UTF-32@, @UTF-32BE@, @UTF-32LE@ -- -- There is additional notation (borrowed from GNU iconv) for specifying -- how illegal characters are handled: -- -- * a suffix of @\/\/IGNORE@, e.g. @UTF-8\/\/IGNORE@, will cause -- all illegal sequences on input to be ignored, and on output -- will drop all code points that have no representation in the -- target encoding. -- -- * a suffix of @\/\/TRANSLIT@ will choose a replacement character -- for illegal sequences or code points. -- -- * a suffix of @\/\/ROUNDTRIP@ will use a PEP383-style escape mechanism -- to represent any invalid bytes in the input as Unicode codepoints (specifically, -- as lone surrogates, which are normally invalid in UTF-32). -- Upon output, these special codepoints are detected and turned back into the -- corresponding original byte. -- -- In theory, this mechanism allows arbitrary data to be roundtripped via -- a 'String' with no loss of data. In practice, there are two limitations -- to be aware of: -- -- 1. This only stands a chance of working for an encoding which is an ASCII -- superset, as for security reasons we refuse to escape any bytes smaller -- than 128. Many encodings of interest are ASCII supersets (in particular, -- you can assume that the locale encoding is an ASCII superset) but many -- (such as UTF-16) are not. -- -- 2. If the underlying encoding is not itself roundtrippable, this mechanism -- can fail. Roundtrippable encodings are those which have an injective mapping -- into Unicode. Almost all encodings meet this criteria, but some do not. Notably, -- Shift-JIS (CP932) and Big5 contain several different encodings of the same -- Unicode codepoint. -- -- On Windows, you can access supported code pages with the prefix -- @CP@; for example, @\"CP1250\"@. -- mkTextEncoding :: String -> IO TextEncoding mkTextEncoding e = case mb_coding_failure_mode of Nothing -> unknownEncodingErr e Just cfm -> mkTextEncoding' cfm enc where (enc, suffix) = span (/= '/') e mb_coding_failure_mode = case suffix of "" -> Just ErrorOnCodingFailure "//IGNORE" -> Just IgnoreCodingFailure "//TRANSLIT" -> Just TransliterateCodingFailure "//ROUNDTRIP" -> Just RoundtripFailure _ -> Nothing mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding mkTextEncoding' cfm enc = case [toUpper c | c <- enc, c /= '-'] of -- UTF-8 and friends we can handle ourselves "UTF8" -> return $ UTF8.mkUTF8 cfm "UTF16" -> return $ UTF16.mkUTF16 cfm "UTF16LE" -> return $ UTF16.mkUTF16le cfm "UTF16BE" -> return $ UTF16.mkUTF16be cfm "UTF32" -> return $ UTF32.mkUTF32 cfm "UTF32LE" -> return $ UTF32.mkUTF32le cfm "UTF32BE" -> return $ UTF32.mkUTF32be cfm #if defined(mingw32_HOST_OS) 'C':'P':n | [(cp,"")] <- reads n -> return $ CodePage.mkCodePageEncoding cfm cp _ -> unknownEncodingErr (enc ++ codingFailureModeSuffix cfm) #else -- Otherwise, handle other encoding needs via iconv. -- Unfortunately there is no good way to determine whether iconv is actually -- functional without telling it to do something. _ -> do res <- Iconv.mkIconvEncoding cfm enc let isAscii = any (== enc) ansiEncNames case res of Just e -> return e -- At this point we know that we can't count on iconv to work -- (see, for instance, Trac #10298). However, we still want to do -- what we can to work with what we have. For instance, ASCII is -- easy. We match on ASCII encodings directly using several -- possible aliases (specified by RFC 1345 & Co) and for this use -- the 'char8' encoding Nothing | isAscii -> return char8 | otherwise -> unknownEncodingErr (enc ++ codingFailureModeSuffix cfm) where ansiEncNames = -- ASCII aliases [ "ANSI_X3.4-1968", "iso-ir-6", "ANSI_X3.4-1986", "ISO_646.irv:1991" , "US-ASCII", "us", "IBM367", "cp367", "csASCII", "ASCII", "ISO646-US" ] #endif latin1_encode :: CharBuffer -> Buffer Word8 -> IO (CharBuffer, Buffer Word8) latin1_encode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_encode input output -- unchecked, used for char8 --latin1_encode = unsafePerformIO $ do mkTextEncoder Iconv.latin1 >>= return.encode latin1_decode :: Buffer Word8 -> CharBuffer -> IO (Buffer Word8, CharBuffer) latin1_decode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_decode input output --latin1_decode = unsafePerformIO $ do mkTextDecoder Iconv.latin1 >>= return.encode unknownEncodingErr :: String -> IO a unknownEncodingErr e = ioException (IOError Nothing NoSuchThing "mkTextEncoding" ("unknown encoding:" ++ e) Nothing Nothing)
urbanslug/ghc
libraries/base/GHC/IO/Encoding.hs
bsd-3-clause
11,413
0
13
2,220
1,224
737
487
103
9
{- (c) The University of Glasgow, 1992-2006 Here we collect a variety of helper functions that construct or analyse HsSyn. All these functions deal with generic HsSyn; functions which deal with the instantiated versions are located elsewhere: Parameterised by Module ---------------- ------------- RdrName parser/RdrHsSyn Name rename/RnHsSyn Id typecheck/TcHsSyn -} {-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module HsUtils( -- Terms mkHsPar, mkHsApp, mkHsAppType, mkHsAppTypeOut, mkHsConApp, mkSimpleHsAlt, mkSimpleMatch, unguardedGRHSs, unguardedRHS, mkMatchGroup, mkMatchGroupName, mkMatch, mkHsLam, mkHsIf, mkHsWrap, mkLHsWrap, mkHsWrapCo, mkHsWrapCoR, mkLHsWrapCo, mkHsDictLet, mkHsLams, mkHsOpApp, mkHsDo, mkHsComp, mkHsWrapPat, mkHsWrapPatCo, mkLHsPar, mkHsCmdWrap, mkLHsCmdWrap, nlHsTyApp, nlHsTyApps, nlHsVar, nlHsLit, nlHsApp, nlHsApps, nlHsSyntaxApps, nlHsIntLit, nlHsVarApps, nlHsDo, nlHsOpApp, nlHsLam, nlHsPar, nlHsIf, nlHsCase, nlList, mkLHsTupleExpr, mkLHsVarTuple, missingTupArg, toLHsSigWcType, -- * Constructing general big tuples -- $big_tuples mkChunkified, chunkify, -- Bindings mkFunBind, mkVarBind, mkHsVarBind, mk_easy_FunBind, mkTopFunBind, mkPatSynBind, isInfixFunBind, -- Literals mkHsIntegral, mkHsFractional, mkHsIsString, mkHsString, mkHsStringPrimLit, -- Patterns mkNPat, mkNPlusKPat, nlVarPat, nlLitPat, nlConVarPat, nlConVarPatName, nlConPat, nlConPatName, nlInfixConPat, nlNullaryConPat, nlWildConPat, nlWildPat, nlWildPatName, nlWildPatId, nlTuplePat, mkParPat, mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup, -- Types mkHsAppTy, mkHsAppTys, userHsTyVarBndrs, userHsLTyVarBndrs, mkLHsSigType, mkLHsSigWcType, mkClassOpSigs, nlHsAppTy, nlHsTyVar, nlHsFunTy, nlHsTyConApp, -- Stmts mkTransformStmt, mkTransformByStmt, mkBodyStmt, mkBindStmt, mkTcBindStmt, mkLastStmt, emptyTransStmt, mkGroupUsingStmt, mkGroupByUsingStmt, emptyRecStmt, emptyRecStmtName, emptyRecStmtId, mkRecStmt, -- Template Haskell mkHsSpliceTy, mkHsSpliceE, mkHsSpliceTE, mkUntypedSplice, mkHsQuasiQuote, unqualQuasiQuote, -- Flags noRebindableInfo, -- Collecting binders collectLocalBinders, collectHsValBinders, collectHsBindListBinders, collectHsIdBinders, collectHsBindsBinders, collectHsBindBinders, collectMethodBinders, collectPatBinders, collectPatsBinders, collectLStmtsBinders, collectStmtsBinders, collectLStmtBinders, collectStmtBinders, hsLTyClDeclBinders, hsTyClForeignBinders, hsPatSynSelectors, hsForeignDeclsBinders, hsGroupBinders, hsDataFamInstBinders, hsDataDefnBinders, -- Collecting implicit binders lStmtsImplicits, hsValBindsImplicits, lPatImplicits ) where #include "HsVersions.h" import HsDecls import HsBinds import HsExpr import HsPat import HsTypes import HsLit import PlaceHolder import TcEvidence import RdrName import Var import TyCoRep import Type ( filterOutInvisibleTypes ) import TysWiredIn ( unitTy ) import TcType import DataCon import Name import NameSet import BasicTypes import SrcLoc import FastString import Util import Bag import Outputable import Constants import Data.Either import Data.Function import Data.List {- ************************************************************************ * * Some useful helpers for constructing syntax * * ************************************************************************ These functions attempt to construct a not-completely-useless SrcSpan from their components, compared with the nl* functions below which just attach noSrcSpan to everything. -} mkHsPar :: LHsExpr id -> LHsExpr id mkHsPar e = L (getLoc e) (HsPar e) mkSimpleMatch :: [LPat id] -> Located (body id) -> LMatch id (Located (body id)) mkSimpleMatch pats rhs = L loc $ Match NonFunBindMatch pats Nothing (unguardedGRHSs rhs) where loc = case pats of [] -> getLoc rhs (pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs) unguardedGRHSs :: Located (body id) -> GRHSs id (Located (body id)) unguardedGRHSs rhs@(L loc _) = GRHSs (unguardedRHS loc rhs) (noLoc emptyLocalBinds) unguardedRHS :: SrcSpan -> Located (body id) -> [LGRHS id (Located (body id))] unguardedRHS loc rhs = [L loc (GRHS [] rhs)] mkMatchGroup :: Origin -> [LMatch RdrName (Located (body RdrName))] -> MatchGroup RdrName (Located (body RdrName)) mkMatchGroup origin matches = MG { mg_alts = mkLocatedList matches , mg_arg_tys = [] , mg_res_ty = placeHolderType , mg_origin = origin } mkLocatedList :: [Located a] -> Located [Located a] mkLocatedList [] = noLoc [] mkLocatedList ms = L (combineLocs (head ms) (last ms)) ms mkMatchGroupName :: Origin -> [LMatch Name (Located (body Name))] -> MatchGroup Name (Located (body Name)) mkMatchGroupName origin matches = MG { mg_alts = mkLocatedList matches , mg_arg_tys = [] , mg_res_ty = placeHolderType , mg_origin = origin } mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2) mkHsAppType :: LHsExpr name -> LHsWcType name -> LHsExpr name mkHsAppType e t = addCLoc e (hswc_body t) (HsAppType e t) mkHsAppTypeOut :: LHsExpr Id -> LHsWcType Name -> LHsExpr Id mkHsAppTypeOut e t = addCLoc e (hswc_body t) (HsAppTypeOut e t) mkHsLam :: [LPat RdrName] -> LHsExpr RdrName -> LHsExpr RdrName mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches)) where matches = mkMatchGroup Generated [mkSimpleMatch pats body] mkHsLams :: [TyVar] -> [EvVar] -> LHsExpr Id -> LHsExpr Id mkHsLams tyvars dicts expr = mkLHsWrap (mkWpTyLams tyvars <.> mkWpLams dicts) expr mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id -- Used for constructing dictionary terms etc, so no locations mkHsConApp data_con tys args = foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args where mk_app f a = noLoc (HsApp f (noLoc a)) mkSimpleHsAlt :: LPat id -> (Located (body id)) -> LMatch id (Located (body id)) -- A simple lambda with a single pattern, no binds, no guards; pre-typechecking mkSimpleHsAlt pat expr = mkSimpleMatch [pat] expr nlHsTyApp :: name -> [Type] -> LHsExpr name nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar (noLoc fun_id))) nlHsTyApps :: name -> [Type] -> [LHsExpr name] -> LHsExpr name nlHsTyApps fun_id tys xs = foldl nlHsApp (nlHsTyApp fun_id tys) xs --------- Adding parens --------- mkLHsPar :: LHsExpr name -> LHsExpr name -- Wrap in parens if hsExprNeedsParens says it needs them -- So 'f x' becomes '(f x)', but '3' stays as '3' mkLHsPar le@(L loc e) | hsExprNeedsParens e = L loc (HsPar le) | otherwise = le mkParPat :: LPat name -> LPat name mkParPat lp@(L loc p) | hsPatNeedsParens p = L loc (ParPat lp) | otherwise = lp ------------------------------- -- These are the bits of syntax that contain rebindable names -- See RnEnv.lookupSyntaxName mkHsIntegral :: String -> Integer -> PostTc RdrName Type -> HsOverLit RdrName mkHsFractional :: FractionalLit -> PostTc RdrName Type -> HsOverLit RdrName mkHsIsString :: String -> FastString -> PostTc RdrName Type -> HsOverLit RdrName mkHsDo :: HsStmtContext Name -> [ExprLStmt RdrName] -> HsExpr RdrName mkHsComp :: HsStmtContext Name -> [ExprLStmt RdrName] -> LHsExpr RdrName -> HsExpr RdrName mkNPat :: Located (HsOverLit RdrName) -> Maybe (SyntaxExpr RdrName) -> Pat RdrName mkNPlusKPat :: Located RdrName -> Located (HsOverLit RdrName) -> Pat RdrName mkLastStmt :: Located (bodyR idR) -> StmtLR idL idR (Located (bodyR idR)) mkBodyStmt :: Located (bodyR RdrName) -> StmtLR idL RdrName (Located (bodyR RdrName)) mkBindStmt :: (PostTc idR Type ~ PlaceHolder) => LPat idL -> Located (bodyR idR) -> StmtLR idL idR (Located (bodyR idR)) mkTcBindStmt :: LPat Id -> Located (bodyR Id) -> StmtLR Id Id (Located (bodyR Id)) emptyRecStmt :: StmtLR idL RdrName bodyR emptyRecStmtName :: StmtLR Name Name bodyR emptyRecStmtId :: StmtLR Id Id bodyR mkRecStmt :: [LStmtLR idL RdrName bodyR] -> StmtLR idL RdrName bodyR mkHsIntegral src i = OverLit (HsIntegral src i) noRebindableInfo noExpr mkHsFractional f = OverLit (HsFractional f) noRebindableInfo noExpr mkHsIsString src s = OverLit (HsIsString src s) noRebindableInfo noExpr noRebindableInfo :: PlaceHolder noRebindableInfo = PlaceHolder -- Just another placeholder; mkHsDo ctxt stmts = HsDo ctxt (mkLocatedList stmts) placeHolderType mkHsComp ctxt stmts expr = mkHsDo ctxt (stmts ++ [last_stmt]) where last_stmt = L (getLoc expr) $ mkLastStmt expr mkHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> HsExpr id mkHsIf c a b = HsIf (Just noSyntaxExpr) c a b mkNPat lit neg = NPat lit neg noSyntaxExpr placeHolderType mkNPlusKPat id lit = NPlusKPat id lit (unLoc lit) noSyntaxExpr noSyntaxExpr placeHolderType mkTransformStmt :: (PostTc idR Type ~ PlaceHolder) => [ExprLStmt idL] -> LHsExpr idR -> StmtLR idL idR (LHsExpr idL) mkTransformByStmt :: (PostTc idR Type ~ PlaceHolder) => [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR -> StmtLR idL idR (LHsExpr idL) mkGroupUsingStmt :: (PostTc idR Type ~ PlaceHolder) => [ExprLStmt idL] -> LHsExpr idR -> StmtLR idL idR (LHsExpr idL) mkGroupByUsingStmt :: (PostTc idR Type ~ PlaceHolder) => [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR -> StmtLR idL idR (LHsExpr idL) emptyTransStmt :: (PostTc idR Type ~ PlaceHolder) => StmtLR idL idR (LHsExpr idR) emptyTransStmt = TransStmt { trS_form = panic "emptyTransStmt: form" , trS_stmts = [], trS_bndrs = [] , trS_by = Nothing, trS_using = noLoc noExpr , trS_ret = noSyntaxExpr, trS_bind = noSyntaxExpr , trS_bind_arg_ty = PlaceHolder , trS_fmap = noExpr } mkTransformStmt ss u = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u } mkTransformByStmt ss u b = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u, trS_by = Just b } mkGroupUsingStmt ss u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u } mkGroupByUsingStmt ss b u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u, trS_by = Just b } mkLastStmt body = LastStmt body False noSyntaxExpr mkBodyStmt body = BodyStmt body noSyntaxExpr noSyntaxExpr placeHolderType mkBindStmt pat body = BindStmt pat body noSyntaxExpr noSyntaxExpr PlaceHolder mkTcBindStmt pat body = BindStmt pat body noSyntaxExpr noSyntaxExpr unitTy -- don't use placeHolderTypeTc above, because that panics during zonking emptyRecStmt' :: forall idL idR body. PostTc idR Type -> StmtLR idL idR body emptyRecStmt' tyVal = RecStmt { recS_stmts = [], recS_later_ids = [] , recS_rec_ids = [] , recS_ret_fn = noSyntaxExpr , recS_mfix_fn = noSyntaxExpr , recS_bind_fn = noSyntaxExpr, recS_bind_ty = tyVal , recS_later_rets = [] , recS_rec_rets = [], recS_ret_ty = tyVal } emptyRecStmt = emptyRecStmt' placeHolderType emptyRecStmtName = emptyRecStmt' placeHolderType emptyRecStmtId = emptyRecStmt' unitTy -- a panic might trigger during zonking mkRecStmt stmts = emptyRecStmt { recS_stmts = stmts } ------------------------------- --- A useful function for building @OpApps@. The operator is always a -- variable, and we don't know the fixity yet. mkHsOpApp :: LHsExpr id -> id -> LHsExpr id -> HsExpr id mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar (noLoc op))) (error "mkOpApp:fixity") e2 unqualSplice :: RdrName unqualSplice = mkRdrUnqual (mkVarOccFS (fsLit "splice")) mkUntypedSplice :: LHsExpr RdrName -> HsSplice RdrName mkUntypedSplice e = HsUntypedSplice unqualSplice e mkHsSpliceE :: LHsExpr RdrName -> HsExpr RdrName mkHsSpliceE e = HsSpliceE (mkUntypedSplice e) mkHsSpliceTE :: LHsExpr RdrName -> HsExpr RdrName mkHsSpliceTE e = HsSpliceE (HsTypedSplice unqualSplice e) mkHsSpliceTy :: LHsExpr RdrName -> HsType RdrName mkHsSpliceTy e = HsSpliceTy (HsUntypedSplice unqualSplice e) placeHolderKind mkHsQuasiQuote :: RdrName -> SrcSpan -> FastString -> HsSplice RdrName mkHsQuasiQuote quoter span quote = HsQuasiQuote unqualSplice quoter span quote unqualQuasiQuote :: RdrName unqualQuasiQuote = mkRdrUnqual (mkVarOccFS (fsLit "quasiquote")) -- A name (uniquified later) to -- identify the quasi-quote mkHsString :: String -> HsLit mkHsString s = HsString s (mkFastString s) mkHsStringPrimLit :: FastString -> HsLit mkHsStringPrimLit fs = HsStringPrim (unpackFS fs) (fastStringToByteString fs) ------------- userHsLTyVarBndrs :: SrcSpan -> [Located name] -> [LHsTyVarBndr name] -- Caller sets location userHsLTyVarBndrs loc bndrs = [ L loc (UserTyVar v) | v <- bndrs ] userHsTyVarBndrs :: SrcSpan -> [name] -> [LHsTyVarBndr name] -- Caller sets location userHsTyVarBndrs loc bndrs = [ L loc (UserTyVar (L loc v)) | v <- bndrs ] {- ************************************************************************ * * Constructing syntax with no location info * * ************************************************************************ -} nlHsVar :: id -> LHsExpr id nlHsVar n = noLoc (HsVar (noLoc n)) nlHsLit :: HsLit -> LHsExpr id nlHsLit n = noLoc (HsLit n) nlVarPat :: id -> LPat id nlVarPat n = noLoc (VarPat (noLoc n)) nlLitPat :: HsLit -> LPat id nlLitPat l = noLoc (LitPat l) nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id nlHsApp f x = noLoc (HsApp f x) nlHsSyntaxApps :: SyntaxExpr id -> [LHsExpr id] -> LHsExpr id nlHsSyntaxApps (SyntaxExpr { syn_expr = fun , syn_arg_wraps = arg_wraps , syn_res_wrap = res_wrap }) args | [] <- arg_wraps -- in the noSyntaxExpr case = ASSERT( isIdHsWrapper res_wrap ) foldl nlHsApp (noLoc fun) args | otherwise = mkLHsWrap res_wrap (foldl nlHsApp (noLoc fun) (zipWithEqual "nlHsSyntaxApps" mkLHsWrap arg_wraps args)) nlHsIntLit :: Integer -> LHsExpr id nlHsIntLit n = noLoc (HsLit (HsInt (show n) n)) nlHsApps :: id -> [LHsExpr id] -> LHsExpr id nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs nlHsVarApps :: id -> [id] -> LHsExpr id nlHsVarApps f xs = noLoc (foldl mk (HsVar (noLoc f)) (map (HsVar . noLoc) xs)) where mk f a = HsApp (noLoc f) (noLoc a) nlConVarPat :: RdrName -> [RdrName] -> LPat RdrName nlConVarPat con vars = nlConPat con (map nlVarPat vars) nlConVarPatName :: Name -> [Name] -> LPat Name nlConVarPatName con vars = nlConPatName con (map nlVarPat vars) nlInfixConPat :: id -> LPat id -> LPat id -> LPat id nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r)) nlConPat :: RdrName -> [LPat RdrName] -> LPat RdrName nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats)) nlConPatName :: Name -> [LPat Name] -> LPat Name nlConPatName con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats)) nlNullaryConPat :: id -> LPat id nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon [])) nlWildConPat :: DataCon -> LPat RdrName nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con)) (PrefixCon (nOfThem (dataConSourceArity con) nlWildPat))) nlWildPat :: LPat RdrName nlWildPat = noLoc (WildPat placeHolderType ) -- Pre-typechecking nlWildPatName :: LPat Name nlWildPatName = noLoc (WildPat placeHolderType ) -- Pre-typechecking nlWildPatId :: LPat Id nlWildPatId = noLoc (WildPat placeHolderTypeTc ) -- Post-typechecking nlHsDo :: HsStmtContext Name -> [LStmt RdrName (LHsExpr RdrName)] -> LHsExpr RdrName nlHsDo ctxt stmts = noLoc (mkHsDo ctxt stmts) nlHsOpApp :: LHsExpr id -> id -> LHsExpr id -> LHsExpr id nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2) nlHsLam :: LMatch RdrName (LHsExpr RdrName) -> LHsExpr RdrName nlHsPar :: LHsExpr id -> LHsExpr id nlHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> LHsExpr id nlHsCase :: LHsExpr RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> LHsExpr RdrName nlList :: [LHsExpr RdrName] -> LHsExpr RdrName nlHsLam match = noLoc (HsLam (mkMatchGroup Generated [match])) nlHsPar e = noLoc (HsPar e) -- Note [Rebindable nlHsIf] -- nlHsIf should generate if-expressions which are NOT subject to -- RebindableSyntax, so the first field of HsIf is Nothing. (#12080) nlHsIf cond true false = noLoc (HsIf Nothing cond true false) nlHsCase expr matches = noLoc (HsCase expr (mkMatchGroup Generated matches)) nlList exprs = noLoc (ExplicitList placeHolderType Nothing exprs) nlHsAppTy :: LHsType name -> LHsType name -> LHsType name nlHsTyVar :: name -> LHsType name nlHsFunTy :: LHsType name -> LHsType name -> LHsType name nlHsAppTy f t = noLoc (HsAppTy f t) nlHsTyVar x = noLoc (HsTyVar (noLoc x)) nlHsFunTy a b = noLoc (HsFunTy a b) nlHsTyConApp :: name -> [LHsType name] -> LHsType name nlHsTyConApp tycon tys = foldl nlHsAppTy (nlHsTyVar tycon) tys {- Tuples. All these functions are *pre-typechecker* because they lack types on the tuple. -} mkLHsTupleExpr :: [LHsExpr a] -> LHsExpr a -- Makes a pre-typechecker boxed tuple, deals with 1 case mkLHsTupleExpr [e] = e mkLHsTupleExpr es = noLoc $ ExplicitTuple (map (noLoc . Present) es) Boxed mkLHsVarTuple :: [a] -> LHsExpr a mkLHsVarTuple ids = mkLHsTupleExpr (map nlHsVar ids) nlTuplePat :: [LPat id] -> Boxity -> LPat id nlTuplePat pats box = noLoc (TuplePat pats box []) missingTupArg :: HsTupArg RdrName missingTupArg = Missing placeHolderType mkLHsPatTup :: [LPat id] -> LPat id mkLHsPatTup [] = noLoc $ TuplePat [] Boxed [] mkLHsPatTup [lpat] = lpat mkLHsPatTup lpats = L (getLoc (head lpats)) $ TuplePat lpats Boxed [] -- The Big equivalents for the source tuple expressions mkBigLHsVarTup :: [id] -> LHsExpr id mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids) mkBigLHsTup :: [LHsExpr id] -> LHsExpr id mkBigLHsTup = mkChunkified mkLHsTupleExpr -- The Big equivalents for the source tuple patterns mkBigLHsVarPatTup :: [id] -> LPat id mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs) mkBigLHsPatTup :: [LPat id] -> LPat id mkBigLHsPatTup = mkChunkified mkLHsPatTup -- $big_tuples -- #big_tuples# -- -- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but -- we might concievably want to build such a massive tuple as part of the -- output of a desugaring stage (notably that for list comprehensions). -- -- We call tuples above this size \"big tuples\", and emulate them by -- creating and pattern matching on >nested< tuples that are expressible -- by GHC. -- -- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects) -- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any -- construction to be big. -- -- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector' -- and 'mkTupleCase' functions to do all your work with tuples you should be -- fine, and not have to worry about the arity limitation at all. -- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE' -> [a] -- ^ Possible \"big\" list of things to construct from -> a -- ^ Constructed thing made possible by recursive decomposition mkChunkified small_tuple as = mk_big_tuple (chunkify as) where -- Each sub-list is short enough to fit in a tuple mk_big_tuple [as] = small_tuple as mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s)) chunkify :: [a] -> [[a]] -- ^ Split a list into lists that are small enough to have a corresponding -- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE' -- But there may be more than 'mAX_TUPLE_SIZE' sub-lists chunkify xs | n_xs <= mAX_TUPLE_SIZE = [xs] | otherwise = split xs where n_xs = length xs split [] = [] split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs) {- ************************************************************************ * * LHsSigType and LHsSigWcType * * ********************************************************************* -} mkLHsSigType :: LHsType RdrName -> LHsSigType RdrName mkLHsSigType ty = mkHsImplicitBndrs ty mkLHsSigWcType :: LHsType RdrName -> LHsSigWcType RdrName mkLHsSigWcType ty = mkHsImplicitBndrs (mkHsWildCardBndrs ty) mkClassOpSigs :: [LSig RdrName] -> [LSig RdrName] -- Convert TypeSig to ClassOpSig -- The former is what is parsed, but the latter is -- what we need in class/instance declarations mkClassOpSigs sigs = map fiddle sigs where fiddle (L loc (TypeSig nms ty)) = L loc (ClassOpSig False nms (dropWildCards ty)) fiddle sig = sig toLHsSigWcType :: Type -> LHsSigWcType RdrName -- ^ Converting a Type to an HsType RdrName -- This is needed to implement GeneralizedNewtypeDeriving. -- -- Note that we use 'getRdrName' extensively, which -- generates Exact RdrNames rather than strings. toLHsSigWcType ty = mkLHsSigWcType (go ty) where go :: Type -> LHsType RdrName go ty@(ForAllTy (Anon arg) _) | isPredTy arg , (theta, tau) <- tcSplitPhiTy ty = noLoc (HsQualTy { hst_ctxt = noLoc (map go theta) , hst_body = go tau }) go (ForAllTy (Anon arg) res) = nlHsFunTy (go arg) (go res) go ty@(ForAllTy {}) | (tvs, tau) <- tcSplitForAllTys ty = noLoc (HsForAllTy { hst_bndrs = map go_tv tvs , hst_body = go tau }) go (TyVarTy tv) = nlHsTyVar (getRdrName tv) go (AppTy t1 t2) = nlHsAppTy (go t1) (go t2) go (LitTy (NumTyLit n)) = noLoc $ HsTyLit (HsNumTy "" n) go (LitTy (StrTyLit s)) = noLoc $ HsTyLit (HsStrTy "" s) go (TyConApp tc args) = nlHsTyConApp (getRdrName tc) (map go args') where args' = filterOutInvisibleTypes tc args go (CastTy ty _) = go ty go (CoercionTy co) = pprPanic "toLHsSigWcType" (ppr co) -- Source-language types have _invisible_ kind arguments, -- so we must remove them here (Trac #8563) go_tv :: TyVar -> LHsTyVarBndr RdrName go_tv tv = noLoc $ KindedTyVar (noLoc (getRdrName tv)) (go (tyVarKind tv)) {- ********************************************************************* * * --------- HsWrappers: type args, dict args, casts --------- * * ********************************************************************* -} mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e) mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id mkHsWrap co_fn e | isIdHsWrapper co_fn = e | otherwise = HsWrap co_fn e mkHsWrapCo :: TcCoercionN -- A Nominal coercion a ~N b -> HsExpr id -> HsExpr id mkHsWrapCo co e = mkHsWrap (mkWpCastN co) e mkHsWrapCoR :: TcCoercionR -- A Representational coercion a ~R b -> HsExpr id -> HsExpr id mkHsWrapCoR co e = mkHsWrap (mkWpCastR co) e mkLHsWrapCo :: TcCoercionN -> LHsExpr id -> LHsExpr id mkLHsWrapCo co (L loc e) = L loc (mkHsWrapCo co e) mkHsCmdWrap :: HsWrapper -> HsCmd id -> HsCmd id mkHsCmdWrap w cmd | isIdHsWrapper w = cmd | otherwise = HsCmdWrap w cmd mkLHsCmdWrap :: HsWrapper -> LHsCmd id -> LHsCmd id mkLHsCmdWrap w (L loc c) = L loc (mkHsCmdWrap w c) mkHsWrapPat :: HsWrapper -> Pat id -> Type -> Pat id mkHsWrapPat co_fn p ty | isIdHsWrapper co_fn = p | otherwise = CoPat co_fn p ty mkHsWrapPatCo :: TcCoercionN -> Pat id -> Type -> Pat id mkHsWrapPatCo co pat ty | isTcReflCo co = pat | otherwise = CoPat (mkWpCastN co) pat ty mkHsDictLet :: TcEvBinds -> LHsExpr Id -> LHsExpr Id mkHsDictLet ev_binds expr = mkLHsWrap (mkWpLet ev_binds) expr {- l ************************************************************************ * * Bindings; with a location at the top * * ************************************************************************ -} mkFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)] -> HsBind RdrName -- Not infix, with place holders for coercion and free vars mkFunBind fn ms = FunBind { fun_id = fn , fun_matches = mkMatchGroup Generated ms , fun_co_fn = idHsWrapper , bind_fvs = placeHolderNames , fun_tick = [] } mkTopFunBind :: Origin -> Located Name -> [LMatch Name (LHsExpr Name)] -> HsBind Name -- In Name-land, with empty bind_fvs mkTopFunBind origin fn ms = FunBind { fun_id = fn , fun_matches = mkMatchGroupName origin ms , fun_co_fn = idHsWrapper , bind_fvs = emptyNameSet -- NB: closed -- binding , fun_tick = [] } mkHsVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName mkHsVarBind loc var rhs = mk_easy_FunBind loc var [] rhs mkVarBind :: id -> LHsExpr id -> LHsBind id mkVarBind var rhs = L (getLoc rhs) $ VarBind { var_id = var, var_rhs = rhs, var_inline = False } mkPatSynBind :: Located RdrName -> HsPatSynDetails (Located RdrName) -> LPat RdrName -> HsPatSynDir RdrName -> HsBind RdrName mkPatSynBind name details lpat dir = PatSynBind psb where psb = PSB{ psb_id = name , psb_args = details , psb_def = lpat , psb_dir = dir , psb_fvs = placeHolderNames } -- |If any of the matches in the 'FunBind' are infix, the 'FunBind' is -- considered infix. isInfixFunBind :: HsBindLR id1 id2 -> Bool isInfixFunBind (FunBind _ (MG matches _ _ _) _ _ _) = any (isInfixMatch . unLoc) (unLoc matches) isInfixFunBind _ = False ------------ mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName] -> LHsExpr RdrName -> LHsBind RdrName mk_easy_FunBind loc fun pats expr = L loc $ mkFunBind (L loc fun) [mkMatch pats expr (noLoc emptyLocalBinds)] ------------ mkMatch :: [LPat id] -> LHsExpr id -> Located (HsLocalBinds id) -> LMatch id (LHsExpr id) mkMatch pats expr lbinds = noLoc (Match NonFunBindMatch (map paren pats) Nothing (GRHSs (unguardedRHS noSrcSpan expr) lbinds)) where paren lp@(L l p) | hsPatNeedsParens p = L l (ParPat lp) | otherwise = lp {- ************************************************************************ * * Collecting binders * * ************************************************************************ Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg. ... where (x, y) = ... f i j = ... [a, b] = ... it should return [x, y, f, a, b] (remember, order important). Note [Collect binders only after renaming] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These functions should only be used on HsSyn *after* the renamer, to return a [Name] or [Id]. Before renaming the record punning and wild-card mechanism makes it hard to know what is bound. So these functions should not be applied to (HsSyn RdrName) -} ----------------- Bindings -------------------------- collectLocalBinders :: HsLocalBindsLR idL idR -> [idL] collectLocalBinders (HsValBinds binds) = collectHsIdBinders binds -- No pattern synonyms here collectLocalBinders (HsIPBinds _) = [] collectLocalBinders EmptyLocalBinds = [] collectHsIdBinders, collectHsValBinders :: HsValBindsLR idL idR -> [idL] -- Collect Id binders only, or Ids + pattern synonmys, respectively collectHsIdBinders = collect_hs_val_binders True collectHsValBinders = collect_hs_val_binders False collectHsBindBinders :: HsBindLR idL idR -> [idL] -- Collect both Ids and pattern-synonym binders collectHsBindBinders b = collect_bind False b [] collectHsBindsBinders :: LHsBindsLR idL idR -> [idL] collectHsBindsBinders binds = collect_binds False binds [] collectHsBindListBinders :: [LHsBindLR idL idR] -> [idL] -- Same as collectHsBindsBinders, but works over a list of bindings collectHsBindListBinders = foldr (collect_bind False . unLoc) [] collect_hs_val_binders :: Bool -> HsValBindsLR idL idR -> [idL] collect_hs_val_binders ps (ValBindsIn binds _) = collect_binds ps binds [] collect_hs_val_binders ps (ValBindsOut binds _) = collect_out_binds ps binds collect_out_binds :: Bool -> [(RecFlag, LHsBinds id)] -> [id] collect_out_binds ps = foldr (collect_binds ps . snd) [] collect_binds :: Bool -> LHsBindsLR idL idR -> [idL] -> [idL] -- Collect Ids, or Ids + pattern synonyms, depending on boolean flag collect_binds ps binds acc = foldrBag (collect_bind ps . unLoc) acc binds collect_bind :: Bool -> HsBindLR idL idR -> [idL] -> [idL] collect_bind _ (PatBind { pat_lhs = p }) acc = collect_lpat p acc collect_bind _ (FunBind { fun_id = L _ f }) acc = f : acc collect_bind _ (VarBind { var_id = f }) acc = f : acc collect_bind _ (AbsBinds { abs_exports = dbinds }) acc = map abe_poly dbinds ++ acc -- I don't think we want the binders from the abe_binds -- The only time we collect binders from a typechecked -- binding (hence see AbsBinds) is in zonking in TcHsSyn collect_bind _ (AbsBindsSig { abs_sig_export = poly }) acc = poly : acc collect_bind omitPatSyn (PatSynBind (PSB { psb_id = L _ ps })) acc | omitPatSyn = acc | otherwise = ps : acc collectMethodBinders :: LHsBindsLR RdrName idR -> [Located RdrName] -- Used exclusively for the bindings of an instance decl which are all FunBinds collectMethodBinders binds = foldrBag (get . unLoc) [] binds where get (FunBind { fun_id = f }) fs = f : fs get _ fs = fs -- Someone else complains about non-FunBinds ----------------- Statements -------------------------- collectLStmtsBinders :: [LStmtLR idL idR body] -> [idL] collectLStmtsBinders = concatMap collectLStmtBinders collectStmtsBinders :: [StmtLR idL idR body] -> [idL] collectStmtsBinders = concatMap collectStmtBinders collectLStmtBinders :: LStmtLR idL idR body -> [idL] collectLStmtBinders = collectStmtBinders . unLoc collectStmtBinders :: StmtLR idL idR body -> [idL] -- Id Binders for a Stmt... [but what about pattern-sig type vars]? collectStmtBinders (BindStmt pat _ _ _ _)= collectPatBinders pat collectStmtBinders (LetStmt (L _ binds)) = collectLocalBinders binds collectStmtBinders (BodyStmt {}) = [] collectStmtBinders (LastStmt {}) = [] collectStmtBinders (ParStmt xs _ _ _) = collectLStmtsBinders $ [s | ParStmtBlock ss _ _ <- xs, s <- ss] collectStmtBinders (TransStmt { trS_stmts = stmts }) = collectLStmtsBinders stmts collectStmtBinders (RecStmt { recS_stmts = ss }) = collectLStmtsBinders ss collectStmtBinders ApplicativeStmt{} = [] ----------------- Patterns -------------------------- collectPatBinders :: LPat a -> [a] collectPatBinders pat = collect_lpat pat [] collectPatsBinders :: [LPat a] -> [a] collectPatsBinders pats = foldr collect_lpat [] pats ------------- collect_lpat :: LPat name -> [name] -> [name] collect_lpat (L _ pat) bndrs = go pat where go (VarPat (L _ var)) = var : bndrs go (WildPat _) = bndrs go (LazyPat pat) = collect_lpat pat bndrs go (BangPat pat) = collect_lpat pat bndrs go (AsPat (L _ a) pat) = a : collect_lpat pat bndrs go (ViewPat _ pat _) = collect_lpat pat bndrs go (ParPat pat) = collect_lpat pat bndrs go (ListPat pats _ _) = foldr collect_lpat bndrs pats go (PArrPat pats _) = foldr collect_lpat bndrs pats go (TuplePat pats _ _) = foldr collect_lpat bndrs pats go (ConPatIn _ ps) = foldr collect_lpat bndrs (hsConPatArgs ps) go (ConPatOut {pat_args=ps}) = foldr collect_lpat bndrs (hsConPatArgs ps) -- See Note [Dictionary binders in ConPatOut] go (LitPat _) = bndrs go (NPat {}) = bndrs go (NPlusKPat (L _ n) _ _ _ _ _)= n : bndrs go (SigPatIn pat _) = collect_lpat pat bndrs go (SigPatOut pat _) = collect_lpat pat bndrs go (SplicePat _) = bndrs go (CoPat _ pat _) = go pat {- Note [Dictionary binders in ConPatOut] See also same Note in DsArrows ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do *not* gather (a) dictionary and (b) dictionary bindings as binders of a ConPatOut pattern. For most calls it doesn't matter, because it's pre-typechecker and there are no ConPatOuts. But it does matter more in the desugarer; for example, DsUtils.mkSelectorBinds uses collectPatBinders. In a lazy pattern, for example f ~(C x y) = ..., we want to generate bindings for x,y but not for dictionaries bound by C. (The type checker ensures they would not be used.) Desugaring of arrow case expressions needs these bindings (see DsArrows and arrowcase1), but SPJ (Jan 2007) says it's safer for it to use its own pat-binder-collector: Here's the problem. Consider data T a where C :: Num a => a -> Int -> T a f ~(C (n+1) m) = (n,m) Here, the pattern (C (n+1)) binds a hidden dictionary (d::Num a), and *also* uses that dictionary to match the (n+1) pattern. Yet, the variables bound by the lazy pattern are n,m, *not* the dictionary d. So in mkSelectorBinds in DsUtils, we want just m,n as the variables bound. -} hsGroupBinders :: HsGroup Name -> [Name] hsGroupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls, hs_fords = foreign_decls }) = collectHsValBinders val_decls ++ hsTyClForeignBinders tycl_decls foreign_decls hsTyClForeignBinders :: [TyClGroup Name] -> [LForeignDecl Name] -> [Name] -- We need to look at instance declarations too, -- because their associated types may bind data constructors hsTyClForeignBinders tycl_decls foreign_decls = map unLoc (hsForeignDeclsBinders foreign_decls) ++ getSelectorNames (foldMap (foldMap hsLTyClDeclBinders . group_tyclds) tycl_decls `mappend` foldMap (foldMap hsLInstDeclBinders . group_instds) tycl_decls) where getSelectorNames :: ([Located Name], [LFieldOcc Name]) -> [Name] getSelectorNames (ns, fs) = map unLoc ns ++ map (selectorFieldOcc.unLoc) fs ------------------- hsLTyClDeclBinders :: Located (TyClDecl name) -> ([Located name], [LFieldOcc name]) -- ^ Returns all the /binding/ names of the decl. The first one is -- guaranteed to be the name of the decl. The first component -- represents all binding names except record fields; the second -- represents field occurrences. For record fields mentioned in -- multiple constructors, the SrcLoc will be from the first occurrence. -- -- Each returned (Located name) has a SrcSpan for the /whole/ declaration. -- See Note [SrcSpan for binders] hsLTyClDeclBinders (L loc (FamDecl { tcdFam = FamilyDecl { fdLName = L _ name } })) = ([L loc name], []) hsLTyClDeclBinders (L loc (SynDecl { tcdLName = L _ name })) = ([L loc name], []) hsLTyClDeclBinders (L loc (ClassDecl { tcdLName = L _ cls_name , tcdSigs = sigs, tcdATs = ats })) = (L loc cls_name : [ L fam_loc fam_name | L fam_loc (FamilyDecl { fdLName = L _ fam_name }) <- ats ] ++ [ L mem_loc mem_name | L mem_loc (ClassOpSig False ns _) <- sigs, L _ mem_name <- ns ] , []) hsLTyClDeclBinders (L loc (DataDecl { tcdLName = L _ name, tcdDataDefn = defn })) = (\ (xs, ys) -> (L loc name : xs, ys)) $ hsDataDefnBinders defn ------------------- hsForeignDeclsBinders :: [LForeignDecl name] -> [Located name] -- See Note [SrcSpan for binders] hsForeignDeclsBinders foreign_decls = [ L decl_loc n | L decl_loc (ForeignImport { fd_name = L _ n }) <- foreign_decls] ------------------- hsPatSynSelectors :: HsValBinds id -> [id] -- Collects record pattern-synonym selectors only; the pattern synonym -- names are collected by collectHsValBinders. hsPatSynSelectors (ValBindsIn _ _) = panic "hsPatSynSelectors" hsPatSynSelectors (ValBindsOut binds _) = foldrBag addPatSynSelector [] . unionManyBags $ map snd binds addPatSynSelector:: LHsBind id -> [id] -> [id] addPatSynSelector bind sels | L _ (PatSynBind (PSB { psb_args = RecordPatSyn as })) <- bind = map (unLoc . recordPatSynSelectorId) as ++ sels | otherwise = sels ------------------- hsLInstDeclBinders :: LInstDecl name -> ([Located name], [LFieldOcc name]) hsLInstDeclBinders (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = dfis } })) = foldMap (hsDataFamInstBinders . unLoc) dfis hsLInstDeclBinders (L _ (DataFamInstD { dfid_inst = fi })) = hsDataFamInstBinders fi hsLInstDeclBinders (L _ (TyFamInstD {})) = mempty ------------------- -- the SrcLoc returned are for the whole declarations, not just the names hsDataFamInstBinders :: DataFamInstDecl name -> ([Located name], [LFieldOcc name]) hsDataFamInstBinders (DataFamInstDecl { dfid_defn = defn }) = hsDataDefnBinders defn -- There can't be repeated symbols because only data instances have binders ------------------- -- the SrcLoc returned are for the whole declarations, not just the names hsDataDefnBinders :: HsDataDefn name -> ([Located name], [LFieldOcc name]) hsDataDefnBinders (HsDataDefn { dd_cons = cons }) = hsConDeclsBinders cons -- See Note [Binders in family instances] ------------------- hsConDeclsBinders :: [LConDecl name] -> ([Located name], [LFieldOcc name]) -- See hsLTyClDeclBinders for what this does -- The function is boringly complicated because of the records -- And since we only have equality, we have to be a little careful hsConDeclsBinders cons = go id cons where go :: ([LFieldOcc name] -> [LFieldOcc name]) -> [LConDecl name] -> ([Located name], [LFieldOcc name]) go _ [] = ([], []) go remSeen (r:rs) = -- don't re-mangle the location of field names, because we don't -- have a record of the full location of the field declaration anyway case r of -- remove only the first occurrence of any seen field in order to -- avoid circumventing detection of duplicate fields (#9156) L loc (ConDeclGADT { con_names = names , con_type = HsIB { hsib_body = res_ty}}) -> case tau of L _ (HsFunTy (L _ (HsAppsTy [L _ (HsAppPrefix (L _ (HsRecTy flds)))])) _res_ty) -> record_gadt flds L _ (HsFunTy (L _ (HsRecTy flds)) _res_ty) -> record_gadt flds _other -> (map (L loc . unLoc) names ++ ns, fs) where (ns, fs) = go remSeen rs where (_tvs, _cxt, tau) = splitLHsSigmaTy res_ty record_gadt flds = (map (L loc . unLoc) names ++ ns, r' ++ fs) where r' = remSeen (concatMap (cd_fld_names . unLoc) flds) remSeen' = foldr (.) remSeen [deleteBy ((==) `on` unLoc . rdrNameFieldOcc . unLoc) v | v <- r'] (ns, fs) = go remSeen' rs L loc (ConDeclH98 { con_name = name , con_details = RecCon flds }) -> ([L loc (unLoc name)] ++ ns, r' ++ fs) where r' = remSeen (concatMap (cd_fld_names . unLoc) (unLoc flds)) remSeen' = foldr (.) remSeen [deleteBy ((==) `on` unLoc . rdrNameFieldOcc . unLoc) v | v <- r'] (ns, fs) = go remSeen' rs L loc (ConDeclH98 { con_name = name }) -> ([L loc (unLoc name)] ++ ns, fs) where (ns, fs) = go remSeen rs {- Note [SrcSpan for binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ When extracting the (Located RdrNme) for a binder, at least for the main name (the TyCon of a type declaration etc), we want to give it the @SrcSpan@ of the whole /declaration/, not just the name itself (which is how it appears in the syntax tree). This SrcSpan (for the entire declaration) is used as the SrcSpan for the Name that is finally produced, and hence for error messages. (See Trac #8607.) Note [Binders in family instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a type or data family instance declaration, the type constructor is an *occurrence* not a binding site type instance T Int = Int -> Int -- No binders data instance S Bool = S1 | S2 -- Binders are S1,S2 ************************************************************************ * * Collecting binders the user did not write * * ************************************************************************ The job of this family of functions is to run through binding sites and find the set of all Names that were defined "implicitly", without being explicitly written by the user. The main purpose is to find names introduced by record wildcards so that we can avoid warning the user when they don't use those names (#4404) -} lStmtsImplicits :: [LStmtLR Name idR (Located (body idR))] -> NameSet lStmtsImplicits = hs_lstmts where hs_lstmts :: [LStmtLR Name idR (Located (body idR))] -> NameSet hs_lstmts = foldr (\stmt rest -> unionNameSet (hs_stmt (unLoc stmt)) rest) emptyNameSet hs_stmt :: StmtLR Name idR (Located (body idR)) -> NameSet hs_stmt (BindStmt pat _ _ _ _) = lPatImplicits pat hs_stmt (ApplicativeStmt args _ _) = unionNameSets (map do_arg args) where do_arg (_, ApplicativeArgOne pat _) = lPatImplicits pat do_arg (_, ApplicativeArgMany stmts _ _) = hs_lstmts stmts hs_stmt (LetStmt binds) = hs_local_binds (unLoc binds) hs_stmt (BodyStmt {}) = emptyNameSet hs_stmt (LastStmt {}) = emptyNameSet hs_stmt (ParStmt xs _ _ _) = hs_lstmts [s | ParStmtBlock ss _ _ <- xs, s <- ss] hs_stmt (TransStmt { trS_stmts = stmts }) = hs_lstmts stmts hs_stmt (RecStmt { recS_stmts = ss }) = hs_lstmts ss hs_local_binds (HsValBinds val_binds) = hsValBindsImplicits val_binds hs_local_binds (HsIPBinds _) = emptyNameSet hs_local_binds EmptyLocalBinds = emptyNameSet hsValBindsImplicits :: HsValBindsLR Name idR -> NameSet hsValBindsImplicits (ValBindsOut binds _) = foldr (unionNameSet . lhsBindsImplicits . snd) emptyNameSet binds hsValBindsImplicits (ValBindsIn binds _) = lhsBindsImplicits binds lhsBindsImplicits :: LHsBindsLR Name idR -> NameSet lhsBindsImplicits = foldBag unionNameSet (lhs_bind . unLoc) emptyNameSet where lhs_bind (PatBind { pat_lhs = lpat }) = lPatImplicits lpat lhs_bind _ = emptyNameSet lPatImplicits :: LPat Name -> NameSet lPatImplicits = hs_lpat where hs_lpat (L _ pat) = hs_pat pat hs_lpats = foldr (\pat rest -> hs_lpat pat `unionNameSet` rest) emptyNameSet hs_pat (LazyPat pat) = hs_lpat pat hs_pat (BangPat pat) = hs_lpat pat hs_pat (AsPat _ pat) = hs_lpat pat hs_pat (ViewPat _ pat _) = hs_lpat pat hs_pat (ParPat pat) = hs_lpat pat hs_pat (ListPat pats _ _) = hs_lpats pats hs_pat (PArrPat pats _) = hs_lpats pats hs_pat (TuplePat pats _ _) = hs_lpats pats hs_pat (SigPatIn pat _) = hs_lpat pat hs_pat (SigPatOut pat _) = hs_lpat pat hs_pat (CoPat _ pat _) = hs_pat pat hs_pat (ConPatIn _ ps) = details ps hs_pat (ConPatOut {pat_args=ps}) = details ps hs_pat _ = emptyNameSet details (PrefixCon ps) = hs_lpats ps details (RecCon fs) = hs_lpats explicit `unionNameSet` mkNameSet (collectPatsBinders implicit) where (explicit, implicit) = partitionEithers [if pat_explicit then Left pat else Right pat | (i, fld) <- [0..] `zip` rec_flds fs , let pat = hsRecFieldArg (unLoc fld) pat_explicit = maybe True (i<) (rec_dotdot fs)] details (InfixCon p1 p2) = hs_lpat p1 `unionNameSet` hs_lpat p2
vikraman/ghc
compiler/hsSyn/HsUtils.hs
bsd-3-clause
46,472
0
27
12,132
11,948
6,151
5,797
-1
-1
{-# LANGUAGE GADTs #-} module Experiments.Applicative.Introspection where import Control.Applicative data GAplTree a where GAplBranch :: GAplTree (a -> b) -> GAplTree a -> GAplTree b GAplLeaf :: a -> GAplTree a GAplLabel :: String -> GAplTree a -> GAplTree a instance Functor GAplTree where fmap f (GAplLeaf a) = GAplLeaf (f a) fmap f (GAplLabel s tree) = GAplLabel s (fmap f tree) fmap f (GAplBranch l r) = GAplBranch (fmap (f .) l) r -- also works -- doesn't (necessarily) conform to functor laws -- but does mean you don't have to change the functor -- definition as new type constructors are added -- -- fmap f expr = GAplBranch (GAplLeaf f) expr instance Applicative GAplTree where pure v = GAplLeaf v f <*> expr = GAplBranch f expr get :: GAplTree a -> a get (GAplLeaf v) = v get (GAplLabel _ tree) = get tree get (GAplBranch l r) = (get l) (get r) (<?>) :: GAplTree a -> String -> GAplTree a tree <?> label = GAplLabel label tree getLabels :: GAplTree a -> [String] getLabels (GAplLeaf _) = [] getLabels (GAplLabel label tree) = label : (getLabels tree) getLabels (GAplBranch l r) = (getLabels l) ++ (getLabels r) example :: GAplTree Int example = mathFunc <$> ((GAplLeaf 3) <?> "this is 3") <*> ((GAplLeaf 2) <?> "this is 2") <*> ((GAplLeaf 1) <?> "this is 1") where mathFunc a b c = a + b + c
rumblesan/haskell-experiments
src/Experiments/Applicative/Introspection.hs
bsd-3-clause
1,391
0
11
331
506
258
248
29
1
{-# LANGUAGE TemplateHaskell #-} -- | Internal module that handles the caching of Discord resources. -- -- Every object is indexed by its internal discord identifier. module Haskcord.Cache where -- TODO Make a type synonym for ReaderT cache.
swagcod/haskcord
src/Haskcord/Cache.hs
bsd-3-clause
243
0
3
39
11
9
2
2
0
-- A module for changing behavior based on the version of GHC. {-# LANGUAGE CPP #-} module GhcVersion where import Data.Version import Text.ParserCombinators.ReadP ghcVersion :: Version ghcVersion = case readP_to_S (parseVersion <* eof) VERSION_ghc of [(v,"")] -> v _ -> error $ "Unable to parse GHC version " ++ show VERSION_ghc ifGhc88 :: a -> a -> a ifGhc88 x y = if makeVersion [8,8] <= ghcVersion then x else y
google/ghc-source-gen
tests/GhcVersion.hs
bsd-3-clause
459
0
9
114
119
67
52
12
2
import Control.Concurrent (myThreadId, threadDelay) import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering)) import System.Random (randomIO) import Streamly import qualified Streamly.Prelude as S main :: IO () main = do hSetBuffering stdout LineBuffering S.drain $ do x <- S.take 10 $ loop "A" `parallel` loop "B" S.yieldM $ myThreadId >>= putStr . show >> putStr " got " >> print x where -- we can just use -- parallely $ cycle1 $ yieldM (...) loop :: String -> Serial (String, Int) loop name = do S.yieldM $ threadDelay 1000000 rnd <- S.yieldM (randomIO :: IO Int) S.yieldM $ myThreadId >>= putStr . show >> putStr " yielding " >> print rnd return (name, rnd) `parallel` loop name
harendra-kumar/asyncly
test/parallel-loops.hs
bsd-3-clause
833
1
15
252
265
134
131
21
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Fragment.TmApp.Rules.Type.Infer.Common ( TmAppInferTypeConstraint , tmAppInferTypeInput ) where import Data.Proxy (Proxy(..)) import Control.Lens (preview) import Ast.Type import Ast.Term import Fragment.TyArr.Ast.Type import Fragment.TyArr.Rules.Type.Infer.Common import Fragment.TmApp.Ast.Term import Rules.Type.Infer.Common type TmAppInferTypeConstraint e w s r m ki ty pt tm a i = ( BasicInferTypeConstraint e w s r m ki ty pt tm a i , TyArrInferTypeHelper i , TyArrInferTypeHelperConstraint e w s r m ki ty a i , AsTmApp ki ty pt tm , AsTyArr ki ty ) inferTmApp :: TmAppInferTypeConstraint e w s r m ki ty pt tm a i => Proxy (MonadProxy e w s r m) -> Proxy i -> (Term ki ty pt tm a -> InferTypeMonad m ki ty a i (Type ki ty a)) -> Term ki ty pt tm a -> Maybe (InferTypeMonad m ki ty a i (Type ki ty a)) inferTmApp m i inferFn tm = do (tmF, tmX) <- preview _TmApp tm return $ do tyF <- inferFn tmF (tyArg, tyRet) <- expectArr m i tyF tyX <- inferFn tmX expectTypeEq m i tyArg tyX return tyRet tmAppInferTypeInput :: TmAppInferTypeConstraint e w s r m ki ty pt tm a i => Proxy (MonadProxy e w s r m) -> Proxy i -> InferTypeInput e w s r m (InferTypeMonad m ki ty a i) ki ty pt tm a tmAppInferTypeInput m i = InferTypeInput [] [InferTypeRecurse $ inferTmApp m i] []
dalaing/type-systems
src/Fragment/TmApp/Rules/Type/Infer/Common.hs
bsd-3-clause
1,818
0
14
468
556
294
262
46
1
module System.FSWatch.Repr where import Control.Concurrent (MVar, Chan) import System.FSNotify (WatchManager) import System.IO (IO, Handle) import System.Process (ProcessHandle) data WatchProcess = WatchProcess { wPath :: String , wProcessHandle :: ProcessHandle , wStdin :: Handle , wStdout :: Handle , wNotifyMVar :: MVar [PE] , wShutdown :: IO () } type Listener = PE -> IO () data Opts = Opts { oSlave :: Bool , oFixBufferMode :: Int , oDelayedBufferMode :: Int } data State = State { prompt :: MVar String , printFormat :: MVar PrintFormat , buffering :: MVar NotifyBuffering , mode :: MVar Mode } data DBE = DBE { wman :: WatchManager , wfn :: String } type DB = [DBE] type P = (IO (), Chan PE) data PE = Mod String | Add String | Rem String | Prt { fromPrt :: String } deriving (Eq, Show, Read) isPrt :: PE -> Bool isPrt (Prt _) = True isPrt _ = False data PrintFormat = MultiRecord | SingleRecord deriving (Eq, Show) data Mode = CLI | SLAVE deriving (Eq, Show) data NotifyBuffering = NoNotifyBuffer | FixTimeBuffer Int | DelayedBuffer Int deriving (Eq, Show)
kelemzol/watch
src/System/FSWatch/Repr.hs
bsd-3-clause
1,151
0
10
272
392
229
163
49
1
----------------------------------------------------------------------------- -- -- Generating machine code (instruction selection) -- -- (c) The University of Glasgow 1996-2013 -- ----------------------------------------------------------------------------- {-# LANGUAGE GADTs #-} module SPARC.CodeGen ( cmmTopCodeGen, generateJumpTableForInstr, InstrBlock ) where #include "HsVersions.h" #include "nativeGen/NCG.h" #include "../includes/MachDeps.h" -- NCG stuff: import SPARC.Base import SPARC.CodeGen.Sanity import SPARC.CodeGen.Amode import SPARC.CodeGen.CondCode import SPARC.CodeGen.Gen64 import SPARC.CodeGen.Gen32 import SPARC.CodeGen.Base import SPARC.Ppr () import SPARC.Instr import SPARC.Imm import SPARC.AddrMode import SPARC.Regs import SPARC.Stack import Instruction import Size import NCGMonad -- Our intermediate code: import BlockId import Cmm import CmmUtils import Hoopl import PIC import Reg import CLabel import CPrim -- The rest: import BasicTypes import DynFlags import FastString import OrdList import Outputable import Platform import Unique import Control.Monad ( mapAndUnzipM ) -- | Top level code generation cmmTopCodeGen :: RawCmmDecl -> NatM [NatCmmDecl CmmStatics Instr] cmmTopCodeGen (CmmProc info lab live graph) = do let blocks = toBlockListEntryFirst graph (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks let proc = CmmProc info lab live (ListGraph $ concat nat_blocks) let tops = proc : concat statics return tops cmmTopCodeGen (CmmData sec dat) = do return [CmmData sec dat] -- no translation, we just use CmmStatic -- | Do code generation on a single block of CMM code. -- code generation may introduce new basic block boundaries, which -- are indicated by the NEWBLOCK instruction. We must split up the -- instruction stream into basic blocks again. Also, we extract -- LDATAs here too. basicBlockCodeGen :: CmmBlock -> NatM ( [NatBasicBlock Instr] , [NatCmmDecl CmmStatics Instr]) basicBlockCodeGen block = do let (CmmEntry id, nodes, tail) = blockSplit block stmts = blockToList nodes mid_instrs <- stmtsToInstrs stmts tail_instrs <- stmtToInstrs tail let instrs = mid_instrs `appOL` tail_instrs let (top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs mkBlocks (NEWBLOCK id) (instrs,blocks,statics) = ([], BasicBlock id instrs : blocks, statics) mkBlocks (LDATA sec dat) (instrs,blocks,statics) = (instrs, blocks, CmmData sec dat:statics) mkBlocks instr (instrs,blocks,statics) = (instr:instrs, blocks, statics) -- do intra-block sanity checking blocksChecked = map (checkBlock block) $ BasicBlock id top : other_blocks return (blocksChecked, statics) -- | Convert some Cmm statements to SPARC instructions. stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock stmtsToInstrs stmts = do instrss <- mapM stmtToInstrs stmts return (concatOL instrss) stmtToInstrs :: CmmNode e x -> NatM InstrBlock stmtToInstrs stmt = do dflags <- getDynFlags case stmt of CmmComment s -> return (unitOL (COMMENT s)) CmmAssign reg src | isFloatType ty -> assignReg_FltCode size reg src | isWord64 ty -> assignReg_I64Code reg src | otherwise -> assignReg_IntCode size reg src where ty = cmmRegType dflags reg size = cmmTypeSize ty CmmStore addr src | isFloatType ty -> assignMem_FltCode size addr src | isWord64 ty -> assignMem_I64Code addr src | otherwise -> assignMem_IntCode size addr src where ty = cmmExprType dflags src size = cmmTypeSize ty CmmUnsafeForeignCall target result_regs args -> genCCall target result_regs args CmmBranch id -> genBranch id CmmCondBranch arg true false -> do b1 <- genCondJump true arg b2 <- genBranch false return (b1 `appOL` b2) CmmSwitch arg ids -> do dflags <- getDynFlags genSwitch dflags arg ids CmmCall { cml_target = arg } -> genJump arg _ -> panic "stmtToInstrs: statement should have been cps'd away" {- Now, given a tree (the argument to an CmmLoad) that references memory, produce a suitable addressing mode. A Rule of the Game (tm) for Amodes: use of the addr bit must immediately follow use of the code part, since the code part puts values in registers which the addr then refers to. So you can't put anything in between, lest it overwrite some of those registers. If you need to do some other computation between the code part and use of the addr bit, first store the effective address from the amode in a temporary, then do the other computation, and then use the temporary: code LEA amode, tmp ... other computation ... ... (tmp) ... -} -- | Convert a BlockId to some CmmStatic data jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel) where blockLabel = mkAsmTempLabel (getUnique blockid) -- ----------------------------------------------------------------------------- -- Generating assignments -- Assignments are really at the heart of the whole code generation -- business. Almost all top-level nodes of any real importance are -- assignments, which correspond to loads, stores, or register -- transfers. If we're really lucky, some of the register transfers -- will go away, because we can use the destination register to -- complete the code generation for the right hand side. This only -- fails when the right hand side is forced into a fixed register -- (e.g. the result of a call). assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock assignMem_IntCode pk addr src = do (srcReg, code) <- getSomeReg src Amode dstAddr addr_code <- getAmode addr return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock assignReg_IntCode _ reg src = do dflags <- getDynFlags r <- getRegister src let dst = getRegisterReg (targetPlatform dflags) reg return $ case r of Any _ code -> code dst Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg freg) dst -- Floating point assignment to memory assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock assignMem_FltCode pk addr src = do dflags <- getDynFlags Amode dst__2 code1 <- getAmode addr (src__2, code2) <- getSomeReg src tmp1 <- getNewRegNat pk let pk__2 = cmmExprType dflags src code__2 = code1 `appOL` code2 `appOL` if sizeToWidth pk == typeWidth pk__2 then unitOL (ST pk src__2 dst__2) else toOL [ FxTOy (cmmTypeSize pk__2) pk src__2 tmp1 , ST pk tmp1 dst__2] return code__2 -- Floating point assignment to a register/temporary assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock assignReg_FltCode pk dstCmmReg srcCmmExpr = do dflags <- getDynFlags let platform = targetPlatform dflags srcRegister <- getRegister srcCmmExpr let dstReg = getRegisterReg platform dstCmmReg return $ case srcRegister of Any _ code -> code dstReg Fixed _ srcFixedReg srcCode -> srcCode `snocOL` FMOV pk srcFixedReg dstReg genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock genJump (CmmLit (CmmLabel lbl)) = return (toOL [CALL (Left target) 0 True, NOP]) where target = ImmCLbl lbl genJump tree = do (target, code) <- getSomeReg tree return (code `snocOL` JMP (AddrRegReg target g0) `snocOL` NOP) -- ----------------------------------------------------------------------------- -- Unconditional branches genBranch :: BlockId -> NatM InstrBlock genBranch = return . toOL . mkJumpInstr -- ----------------------------------------------------------------------------- -- Conditional jumps {- Conditional jumps are always to local labels, so we can use branch instructions. We peek at the arguments to decide what kind of comparison to do. SPARC: First, we have to ensure that the condition codes are set according to the supplied comparison operation. We generate slightly different code for floating point comparisons, because a floating point operation cannot directly precede a @BF@. We assume the worst and fill that slot with a @NOP@. SPARC: Do not fill the delay slots here; you will confuse the register allocator. -} genCondJump :: BlockId -- the branch target -> CmmExpr -- the condition on which to branch -> NatM InstrBlock genCondJump bid bool = do CondCode is_float cond code <- getCondCode bool return ( code `appOL` toOL ( if is_float then [NOP, BF cond False bid, NOP] else [BI cond False bid, NOP] ) ) -- ----------------------------------------------------------------------------- -- Generating a table-branch genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock genSwitch dflags expr ids | gopt Opt_PIC dflags = error "MachCodeGen: sparc genSwitch PIC not finished\n" | otherwise = do (e_reg, e_code) <- getSomeReg expr base_reg <- getNewRegNat II32 offset_reg <- getNewRegNat II32 dst <- getNewRegNat II32 label <- getNewLabelNat return $ e_code `appOL` toOL [ -- load base of jump table SETHI (HI (ImmCLbl label)) base_reg , OR False base_reg (RIImm $ LO $ ImmCLbl label) base_reg -- the addrs in the table are 32 bits wide.. , SLL e_reg (RIImm $ ImmInt 2) offset_reg -- load and jump to the destination , LD II32 (AddrRegReg base_reg offset_reg) dst , JMP_TBL (AddrRegImm dst (ImmInt 0)) ids label , NOP ] generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl CmmStatics Instr) generateJumpTableForInstr dflags (JMP_TBL _ ids label) = let jumpTable = map (jumpTableEntry dflags) ids in Just (CmmData ReadOnlyData (Statics label jumpTable)) generateJumpTableForInstr _ _ = Nothing -- ----------------------------------------------------------------------------- -- Generating C calls {- Now the biggest nightmare---calls. Most of the nastiness is buried in @get_arg@, which moves the arguments to the correct registers/stack locations. Apart from that, the code is easy. The SPARC calling convention is an absolute nightmare. The first 6x32 bits of arguments are mapped into %o0 through %o5, and the remaining arguments are dumped to the stack, beginning at [%sp+92]. (Note that %o6 == %sp.) If we have to put args on the stack, move %o6==%sp down by the number of words to go on the stack, to ensure there's enough space. According to Fraser and Hanson's lcc book, page 478, fig 17.2, 16 words above the stack pointer is a word for the address of a structure return value. I use this as a temporary location for moving values from float to int regs. Certainly it isn't safe to put anything in the 16 words starting at %sp, since this area can get trashed at any time due to window overflows caused by signal handlers. A final complication (if the above isn't enough) is that we can't blithely calculate the arguments one by one into %o0 .. %o5. Consider the following nested calls: fff a (fff b c) Naive code moves a into %o0, and (fff b c) into %o1. Unfortunately the inner call will itself use %o0, which trashes the value put there in preparation for the outer call. Upshot: we need to calculate the args into temporary regs, and move those to arg regs or onto the stack only immediately prior to the call proper. Sigh. -} genCCall :: ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock -- On SPARC under TSO (Total Store Ordering), writes earlier in the instruction stream -- are guaranteed to take place before writes afterwards (unlike on PowerPC). -- Ref: Section 8.4 of the SPARC V9 Architecture manual. -- -- In the SPARC case we don't need a barrier. -- genCCall (PrimTarget MO_WriteBarrier) _ _ = do return nilOL genCCall target dest_regs args0 = do -- need to remove alignment information let args | PrimTarget mop <- target, (mop == MO_Memcpy || mop == MO_Memset || mop == MO_Memmove) = init args0 | otherwise = args0 -- work out the arguments, and assign them to integer regs argcode_and_vregs <- mapM arg_to_int_vregs args let (argcodes, vregss) = unzip argcode_and_vregs let vregs = concat vregss let n_argRegs = length allArgRegs let n_argRegs_used = min (length vregs) n_argRegs -- deal with static vs dynamic call targets callinsns <- case target of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False)) ForeignTarget expr _ -> do (dyn_c, [dyn_r]) <- arg_to_int_vregs expr return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False) PrimTarget mop -> do res <- outOfLineMachOp mop lblOrMopExpr <- case res of Left lbl -> do return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False)) Right mopExpr -> do (dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False) return lblOrMopExpr let argcode = concatOL argcodes let (move_sp_down, move_sp_up) = let diff = length vregs - n_argRegs nn = if odd diff then diff + 1 else diff -- keep 8-byte alignment in if nn <= 0 then (nilOL, nilOL) else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn))) let transfer_code = toOL (move_final vregs allArgRegs extraStackArgsHere) dflags <- getDynFlags return $ argcode `appOL` move_sp_down `appOL` transfer_code `appOL` callinsns `appOL` unitOL NOP `appOL` move_sp_up `appOL` assign_code (targetPlatform dflags) dest_regs -- | Generate code to calculate an argument, and move it into one -- or two integer vregs. arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg]) arg_to_int_vregs arg = do dflags <- getDynFlags arg_to_int_vregs' dflags arg arg_to_int_vregs' :: DynFlags -> CmmExpr -> NatM (OrdList Instr, [Reg]) arg_to_int_vregs' dflags arg -- If the expr produces a 64 bit int, then we can just use iselExpr64 | isWord64 (cmmExprType dflags arg) = do (ChildCode64 code r_lo) <- iselExpr64 arg let r_hi = getHiVRegFromLo r_lo return (code, [r_hi, r_lo]) | otherwise = do (src, code) <- getSomeReg arg let pk = cmmExprType dflags arg case cmmTypeSize pk of -- Load a 64 bit float return value into two integer regs. FF64 -> do v1 <- getNewRegNat II32 v2 <- getNewRegNat II32 let code2 = code `snocOL` FMOV FF64 src f0 `snocOL` ST FF32 f0 (spRel 16) `snocOL` LD II32 (spRel 16) v1 `snocOL` ST FF32 f1 (spRel 16) `snocOL` LD II32 (spRel 16) v2 return (code2, [v1,v2]) -- Load a 32 bit float return value into an integer reg FF32 -> do v1 <- getNewRegNat II32 let code2 = code `snocOL` ST FF32 src (spRel 16) `snocOL` LD II32 (spRel 16) v1 return (code2, [v1]) -- Move an integer return value into its destination reg. _ -> do v1 <- getNewRegNat II32 let code2 = code `snocOL` OR False g0 (RIReg src) v1 return (code2, [v1]) -- | Move args from the integer vregs into which they have been -- marshalled, into %o0 .. %o5, and the rest onto the stack. -- move_final :: [Reg] -> [Reg] -> Int -> [Instr] -- all args done move_final [] _ _ = [] -- out of aregs; move to stack move_final (v:vs) [] offset = ST II32 v (spRel offset) : move_final vs [] (offset+1) -- move into an arg (%o[0..5]) reg move_final (v:vs) (a:az) offset = OR False g0 (RIReg v) a : move_final vs az offset -- | Assign results returned from the call into their -- destination regs. -- assign_code :: Platform -> [LocalReg] -> OrdList Instr assign_code _ [] = nilOL assign_code platform [dest] = let rep = localRegType dest width = typeWidth rep r_dest = getRegisterReg platform (CmmLocal dest) result | isFloatType rep , W32 <- width = unitOL $ FMOV FF32 (regSingle $ fReg 0) r_dest | isFloatType rep , W64 <- width = unitOL $ FMOV FF64 (regSingle $ fReg 0) r_dest | not $ isFloatType rep , W32 <- width = unitOL $ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest | not $ isFloatType rep , W64 <- width , r_dest_hi <- getHiVRegFromLo r_dest = toOL [ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest_hi , mkRegRegMoveInstr platform (regSingle $ oReg 1) r_dest] | otherwise = panic "SPARC.CodeGen.GenCCall: no match" in result assign_code _ _ = panic "SPARC.CodeGen.GenCCall: no match" -- | Generate a call to implement an out-of-line floating point operation outOfLineMachOp :: CallishMachOp -> NatM (Either CLabel CmmExpr) outOfLineMachOp mop = do let functionName = outOfLineMachOp_table mop dflags <- getDynFlags mopExpr <- cmmMakeDynamicReference dflags CallReference $ mkForeignLabel functionName Nothing ForeignLabelInExternalPackage IsFunction let mopLabelOrExpr = case mopExpr of CmmLit (CmmLabel lbl) -> Left lbl _ -> Right mopExpr return mopLabelOrExpr -- | Decide what C function to use to implement a CallishMachOp -- outOfLineMachOp_table :: CallishMachOp -> FastString outOfLineMachOp_table mop = case mop of MO_F32_Exp -> fsLit "expf" MO_F32_Log -> fsLit "logf" MO_F32_Sqrt -> fsLit "sqrtf" MO_F32_Pwr -> fsLit "powf" MO_F32_Sin -> fsLit "sinf" MO_F32_Cos -> fsLit "cosf" MO_F32_Tan -> fsLit "tanf" MO_F32_Asin -> fsLit "asinf" MO_F32_Acos -> fsLit "acosf" MO_F32_Atan -> fsLit "atanf" MO_F32_Sinh -> fsLit "sinhf" MO_F32_Cosh -> fsLit "coshf" MO_F32_Tanh -> fsLit "tanhf" MO_F64_Exp -> fsLit "exp" MO_F64_Log -> fsLit "log" MO_F64_Sqrt -> fsLit "sqrt" MO_F64_Pwr -> fsLit "pow" MO_F64_Sin -> fsLit "sin" MO_F64_Cos -> fsLit "cos" MO_F64_Tan -> fsLit "tan" MO_F64_Asin -> fsLit "asin" MO_F64_Acos -> fsLit "acos" MO_F64_Atan -> fsLit "atan" MO_F64_Sinh -> fsLit "sinh" MO_F64_Cosh -> fsLit "cosh" MO_F64_Tanh -> fsLit "tanh" MO_UF_Conv w -> fsLit $ word2FloatLabel w MO_Memcpy -> fsLit "memcpy" MO_Memset -> fsLit "memset" MO_Memmove -> fsLit "memmove" MO_BSwap w -> fsLit $ bSwapLabel w MO_PopCnt w -> fsLit $ popCntLabel w MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported MO_Prefetch_Data -> unsupported where unsupported = panic ("outOfLineCmmOp: " ++ show mop ++ " not supported here")
ekmett/ghc
compiler/nativeGen/SPARC/CodeGen.hs
bsd-3-clause
22,234
0
29
7,427
4,465
2,220
2,245
375
40
module Calc.SyntaxTree ( Environment , Expr(..) , evalExpr ) where import Control.Monad (liftM, liftM2) import Control.Monad.State (State, get, modify) import Data.Map (Map, insert, lookup) import Prelude hiding (lookup) type Environment = Map String Expr data Expr = Nil | Val Integer | ID String | Negative Expr | Pow Expr Expr | Mul Expr Expr | Div Expr Expr | Add Expr Expr | Sub Expr Expr | Bind String Expr instance Show Expr where show Nil = "" show (Val i) = show i show (ID s) = s show (Negative e) = '-' : parens e show (Pow e1 e2) = parens e1 ++ "^" ++ parens e2 show (Mul e1 e2) = parens e1 ++ "*" ++ parens e2 show (Div e1 e2) = parens e1 ++ "/" ++ parens e2 show (Add e1 e2) = parens e1 ++ " + " ++ parens e2 show (Sub e1 e2) = parens e1 ++ " - " ++ parens e2 show (Bind s e) = s ++ "=" ++ show e parens Nil = "" parens (Val i) = show i parens (ID s) = s parens e = '(' : show e ++ ")" evalExpr :: Expr -> State Environment Expr evalExpr Nil = return Nil evalExpr e@(Val _) = return e evalExpr e@(ID name) = do m <- get case lookup name m of Nothing -> return e Just exp -> evalExpr exp evalExpr (Negative e) = liftM neg $ evalExpr e where neg (Val i) = Val $ -i neg e = Negative e evalExpr (Pow e1 e2) = liftM2 pow (evalExpr e1) (evalExpr e2) where pow (Val i) (Val j) = Val $ i^j pow e1 e2 = Pow e1 e2 evalExpr (Mul e1 e2) = liftM2 mul (evalExpr e1) (evalExpr e2) where mul (Val i) (Val j) = Val $ i*j mul e1 e2 = Mul e1 e2 evalExpr (Div e1 e2) = liftM2 iDiv (evalExpr e1) (evalExpr e2) where iDiv (Val i) (Val j) = Val $ i `div` j iDiv e1 e2 = Div e1 e2 evalExpr (Add e1 e2) = liftM2 add (evalExpr e1) (evalExpr e2) where add (Val i) (Val j) = Val $ i+j add e1 e2 = Add e1 e2 evalExpr (Sub e1 e2) = liftM2 sub (evalExpr e1) (evalExpr e2) where sub (Val i) (Val j) = Val $ i-j sub e1 e2 = Sub e1 e2 evalExpr (Bind name e) = do expr <- evalExpr e modify $ insert name expr return Nil
qiuhw/calc
src/Calc/SyntaxTree.hs
bsd-3-clause
2,281
0
10
800
1,069
532
537
64
8
{-# LANGUAGE DataKinds, TypeFamilies #-} import Proposte import ProposteInstances import Data.Set hiding (map) import Test.HUnit import Data.Binary ---------------------------------- -- esempi ---------------------- -------------------------------- data instance Prodotto Offerta = PO String Tag data instance Prodotto Domanda = PU Tag pr :: Proposta Int Float Offerta pr = Proposta (Definizione $ fromList [1,2,3]) [Assente, Assente, Vendita (Quantificato 10 2), Vendita (Quantificato 8 2.5), Vendita (Quantificato 10 2), Vendita (Limitato 12)] ri :: Proposta Int Float Domanda ri = Proposta (Filtro $ Includi 1) [Assente, Acquisto Zero (Limitato 3), Acquisto (Limitato 4) (Limitato 3), Acquisto (Obbligatorio 3) (Limitato 5)] t1 x = TestCase $ assertEqual "binary" (decode . encode $ x) x tests = TestList $ map (uncurry TestLabel) [("test1", t1 pr), ("test2", t1 ri)]
paolino/consumattori
Test.hs
bsd-3-clause
889
4
9
139
334
174
160
14
1
module Main where import Lib import HW07 import Testing main :: IO () main = someFunc
ImsungChoi/haskell-test
app/Main.hs
bsd-3-clause
88
0
6
18
28
17
11
6
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE CPP, TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} module Llvm.AsmHirConversion.HirToAsm(hirToAsm) where #define FLC (FileLoc $(srcLoc)) import qualified Compiler.Hoopl as H import qualified Control.Monad as Md import qualified Data.Map as M import qualified Llvm.Asm.Data as A import qualified Llvm.Hir.Data as I import Llvm.Hir.Composer (ptr0) import Llvm.Hir.Cast import Llvm.Util.Monadic (maybeM, pairM) import Llvm.AsmHirConversion.TypeConversion import Control.Monad.Reader import Llvm.AsmHirConversion.Specialization import Llvm.ErrorLoc import Llvm.Hir.DataLayoutMetrics import Llvm.Hir.Target class Conversion l1 l2 | l1 -> l2 where convert :: l1 -> l2 data ReaderData = ReaderData { mp :: (M.Map (I.Gname, H.Label) A.LabelId) , funname :: I.Gname } type Rm = Reader ReaderData withFunName :: I.Gname -> Rm a -> Rm a withFunName g = withReader (\(ReaderData x _) -> ReaderData x g) instance Conversion a (Rm b) => Conversion (Maybe a) (Rm (Maybe b)) where convert (Just x) = Md.liftM Just (convert x) convert Nothing = return Nothing instance (Conversion a (Rm c), Conversion b (Rm c)) => Conversion (Either a b) (Rm c) where convert (Left x) = (convert x) convert (Right x) = (convert x) {- Ir to Ast conversion -} instance Conversion H.Label (Rm A.LabelId) where convert l = do { (ReaderData r fn) <- ask ; case M.lookup (fn,l) r of Just l0 -> return l0 Nothing -> return $ A.LabelDqString $ "_hoopl_label_" ++ show l } convert_to_LabelExt :: I.Gname -> H.Label -> Rm A.LabelId convert_to_LabelExt fn l = do { (ReaderData r _) <- ask ; case M.lookup (fn,l) r of Just l0 -> return l0 Nothing -> errorLoc FLC $ show (fn,l) } convert_to_PercentLabelExt :: I.Gname -> H.Label -> Rm A.PercentLabel convert_to_PercentLabelExt fn l = Md.liftM A.PercentLabel (convert_to_LabelExt fn l) convert_to_PercentLabel :: H.Label -> Rm A.PercentLabel convert_to_PercentLabel l = Md.liftM A.PercentLabel (convert l) convert_to_TargetLabel :: H.Label -> Rm A.TargetLabel convert_to_TargetLabel l = Md.liftM (A.TargetLabel . A.PercentLabel) (convert l) convert_to_BlockLabel :: H.Label -> Rm A.BlockLabel convert_to_BlockLabel l = Md.liftM A.ExplicitBlockLabel (convert l) cnowrap :: Maybe I.NoWrap -> [A.TrapFlag] cnowrap = maybe [] (\x -> case x of I.Nsw -> [A.Nsw] I.Nuw -> [A.Nuw] I.Nsuw -> [A.Nsw, A.Nuw] ) cexact :: Maybe a -> [A.TrapFlag] cexact = maybe [] (\_ -> [A.Exact]) instance Conversion v1 (Rm v2) => Conversion (I.Conversion I.ScalarB v1) (Rm (A.Conversion v2)) where convert x = let (op, t1, u, dt1) = case x of I.Trunc (I.T t0 u0) dt0 -> (A.Trunc, tconvert () t0, u0, tconvert () dt0) I.Zext (I.T t0 u0) dt0 -> (A.Zext, tconvert () t0, u0, tconvert () dt0) I.Sext (I.T t0 u0) dt0 -> (A.Sext, tconvert () t0, u0, tconvert () dt0) I.FpTrunc (I.T t0 u0) dt0 -> (A.FpTrunc, tconvert () t0, u0, tconvert () dt0) I.FpExt (I.T t0 u0) dt0 -> (A.FpExt, tconvert () t0, u0, tconvert () dt0) I.FpToUi (I.T t0 u0) dt0 -> (A.FpToUi, tconvert () t0, u0, tconvert () dt0) I.FpToSi (I.T t0 u0) dt0 -> (A.FpToSi, tconvert () t0, u0, tconvert () dt0) I.UiToFp (I.T t0 u0) dt0 -> (A.UiToFp, tconvert () t0, u0, tconvert () dt0) I.SiToFp (I.T t0 u0) dt0 -> (A.SiToFp, tconvert () t0, u0, tconvert () dt0) I.PtrToInt (I.T t0 u0) dt0 -> (A.PtrToInt, tconvert () t0, u0, tconvert () dt0) I.IntToPtr (I.T t0 u0) dt0 -> (A.IntToPtr, tconvert () t0, u0, tconvert () dt0) I.Bitcast (I.T t0 u0) dt0 -> (A.Bitcast, tconvert () t0, u0, tconvert () dt0) I.AddrSpaceCast (I.T t0 u0) dt0 -> (A.AddrSpaceCast, tconvert () t0, u0, tconvert () dt0) in do { u1 <- convert u ; return $ A.Conversion op (A.Typed t1 u1) dt1 } instance Conversion v1 (Rm v2) => Conversion (I.Conversion I.VectorB v1) (Rm (A.Conversion v2)) where convert x = let (op, t1, u, dt1) = case x of I.Trunc (I.T t0 u0) dt0 -> (A.Trunc, tconvert () t0, u0, tconvert () dt0) I.Zext (I.T t0 u0) dt0 -> (A.Zext, tconvert () t0, u0, tconvert () dt0) I.Sext (I.T t0 u0) dt0 -> (A.Sext, tconvert () t0, u0, tconvert () dt0) I.FpTrunc (I.T t0 u0) dt0 -> (A.FpTrunc, tconvert () t0, u0, tconvert () dt0) I.FpExt (I.T t0 u0) dt0 -> (A.FpExt, tconvert () t0, u0, tconvert () dt0) I.FpToUi (I.T t0 u0) dt0 -> (A.FpToUi, tconvert () t0, u0, tconvert () dt0) I.FpToSi (I.T t0 u0) dt0 -> (A.FpToSi, tconvert () t0, u0, tconvert () dt0) I.UiToFp (I.T t0 u0) dt0 -> (A.UiToFp, tconvert () t0, u0, tconvert () dt0) I.SiToFp (I.T t0 u0) dt0 -> (A.SiToFp, tconvert () t0, u0, tconvert () dt0) I.PtrToInt (I.T t0 u0) dt0 -> (A.PtrToInt, tconvert () t0, u0, tconvert () dt0) I.IntToPtr (I.T t0 u0) dt0 -> (A.IntToPtr, tconvert () t0, u0, tconvert () dt0) I.Bitcast (I.T t0 u0) dt0 -> (A.Bitcast, tconvert () t0, u0, tconvert () dt0) I.AddrSpaceCast (I.T t0 u0) dt0 -> (A.AddrSpaceCast, tconvert () t0, u0, tconvert () dt0) in do { u1 <- convert u ; return $ A.Conversion op (A.Typed t1 u1) dt1 } mkConversion :: (A.ConvertOp, A.Type, I.Const I.Gname, A.Type) -> Rm A.Const mkConversion (op, t1, u, dt1) = do { u1 <- convert u ; return $ A.C_conv $ A.Conversion op (A.Typed t1 u1) dt1 } instance (Conversion v1 (Rm v2), Conversion idx1 (Rm v2)) => Conversion (I.GetElementPtr I.ScalarB v1 idx1) (Rm (A.GetElementPtr v2)) where convert (I.GetElementPtr b u us) = do { ua <- convert u ; usa <- mapM convert us ; return $ A.GetElementPtr b (A.Pointer ua) usa } instance (Conversion v1 (Rm v2), Conversion idx1 (Rm v2)) => Conversion (I.GetElementPtr I.VectorB v1 idx1) (Rm (A.GetElementPtr v2)) where convert (I.GetElementPtr b u us) = do { ua <- convert u ; usa <- mapM convert us ; return $ A.GetElementPtr b (A.Pointer ua) usa } instance Conversion v1 (Rm v2) => Conversion (I.T I.ScalarType v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T I.Dtype v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.ScalarB I.I) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.ScalarB I.F) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.ScalarB I.P) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.VectorB I.I) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.VectorB I.F) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.VectorB I.P) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.RecordB I.D) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.CodeFunB I.X) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.CodeLabelB I.X) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance Conversion v1 (Rm v2) => Conversion (I.T (I.Type I.FirstClassB I.D) v1) (Rm (A.Typed v2)) where convert (I.T t v) = Md.liftM (A.Typed $ tconvert () t) (convert v) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.ScalarB I.I v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.ScalarB I.F v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.ScalarB I.P v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.VectorB I.I v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.VectorB I.F v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance (Conversion v1 (Rm v2)) => Conversion (I.Select I.VectorB I.P v1) (Rm (A.Select v2)) where convert (I.Select u1 u2 u3) = Md.liftM3 A.Select (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.Icmp I.ScalarB v1) (Rm (A.Icmp v2)) where convert (I.Icmp op t u1 u2) = Md.liftM2 (A.Icmp op (tconvert () t)) (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.Icmp I.VectorB v1) (Rm (A.Icmp v2)) where convert (I.Icmp op t u1 u2) = Md.liftM2 (A.Icmp op (tconvert () t)) (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.Fcmp I.ScalarB v1) (Rm (A.Fcmp v2)) where convert (I.Fcmp op t u1 u2) = Md.liftM2 (A.Fcmp op (tconvert () t)) (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.Fcmp I.VectorB v1) (Rm (A.Fcmp v2)) where convert (I.Fcmp op t u1 u2) = Md.liftM2 (A.Fcmp op (tconvert () t)) (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.ShuffleVector I.I v1) (Rm (A.ShuffleVector v2)) where convert (I.ShuffleVector u1 u2 u3) = Md.liftM3 A.ShuffleVector (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.ShuffleVector I.F v1) (Rm (A.ShuffleVector v2)) where convert (I.ShuffleVector u1 u2 u3) = Md.liftM3 A.ShuffleVector (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.ShuffleVector I.P v1) (Rm (A.ShuffleVector v2)) where convert (I.ShuffleVector u1 u2 u3) = Md.liftM3 A.ShuffleVector (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.ExtractValue v1) (Rm (A.ExtractValue v2)) where convert (I.ExtractValue u s) = convert u >>= \u' -> return $ A.ExtractValue u' s instance Conversion v1 (Rm v2) => Conversion (I.InsertValue v1) (Rm (A.InsertValue v2)) where convert (I.InsertValue u1 u2 s) = do { u1' <- convert u1 ; u2' <- convert u2 ; return $ A.InsertValue u1' u2' s } instance Conversion v1 (Rm v2) => Conversion (I.ExtractElement I.I v1) (Rm (A.ExtractElement v2)) where convert (I.ExtractElement u1 u2) = Md.liftM2 A.ExtractElement (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.ExtractElement I.F v1) (Rm (A.ExtractElement v2)) where convert (I.ExtractElement u1 u2) = Md.liftM2 A.ExtractElement (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.ExtractElement I.P v1) (Rm (A.ExtractElement v2)) where convert (I.ExtractElement u1 u2) = Md.liftM2 A.ExtractElement (convert u1) (convert u2) instance Conversion v1 (Rm v2) => Conversion (I.InsertElement I.I v1) (Rm (A.InsertElement v2)) where convert (I.InsertElement u1 u2 u3) = Md.liftM3 A.InsertElement (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.InsertElement I.F v1) (Rm (A.InsertElement v2)) where convert (I.InsertElement u1 u2 u3) = Md.liftM3 A.InsertElement (convert u1) (convert u2) (convert u3) instance Conversion v1 (Rm v2) => Conversion (I.InsertElement I.P v1) (Rm (A.InsertElement v2)) where convert (I.InsertElement u1 u2 u3) = Md.liftM3 A.InsertElement (convert u1) (convert u2) (convert u3) instance Conversion (I.Const I.Gname) (Rm A.Const) where convert x = case x of I.C_int s -> return $ A.C_simple $ A.CpInt s I.C_uhex_int s -> return $ A.C_simple $ A.CpUhexInt s I.C_shex_int s -> return $ A.C_simple $ A.CpShexInt s I.C_float s -> return $ A.C_simple $ A.CpFloat s I.C_null -> return $ A.C_simple $ A.CpNull I.C_undef -> return $ A.C_simple $ A.CpUndef I.C_true -> return $ A.C_simple $ A.CpTrue I.C_false -> return $ A.C_simple $ A.CpFalse I.C_zeroinitializer -> return $ A.C_simple $ A.CpZeroInitializer I.C_globalAddr s -> return $ A.C_simple $ A.CpGlobalAddr (unspecializeGlobalId s) I.C_str s -> return $ A.C_simple $ A.CpStr s I.C_u8 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint8 s I.C_u16 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint16 s I.C_u32 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint32 s I.C_u64 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint64 s I.C_u96 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint96 s I.C_u128 s -> return $ A.C_simple $ A.CpBconst $ A.BconstUint128 s I.C_s8 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt8 s I.C_s16 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt16 s I.C_s32 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt32 s I.C_s64 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt64 s I.C_s96 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt96 s I.C_s128 s -> return $ A.C_simple $ A.CpBconst $ A.BconstInt128 s I.C_struct b fs -> Md.liftM (A.C_complex . (A.Cstruct b)) (mapM convert fs) I.C_vector fs -> Md.liftM (A.C_complex . A.Cvector) (mapM convert fs) I.C_array fs -> Md.liftM (A.C_complex . A.Carray) (mapM convert fs) I.C_vectorN n fs -> do { v <- convert fs ; return (A.C_complex $ A.Cvector $ (fmap (\_ -> v) [1..n])) } I.C_arrayN n fs -> do { v <- convert fs ; return (A.C_complex $ A.Carray $ (fmap (\_ -> v) [1..n])) } I.C_labelId a -> Md.liftM A.C_labelId (convert a) I.C_block g a -> do { a' <- convert_to_PercentLabelExt g a ; return $ A.C_blockAddress (unspecializeGlobalId g) a' } I.C_add nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Add (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_sub nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Sub (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_mul nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Mul (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_udiv nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Udiv (cexact nw) (tconvert () t)) (convert u1) (convert u2)) I.C_sdiv nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Sdiv (cexact nw) (tconvert () t)) (convert u1) (convert u2)) I.C_urem t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Urem [] (tconvert () t)) (convert u1) (convert u2)) I.C_srem t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Srem [] (tconvert () t)) (convert u1) (convert u2)) I.C_shl nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Shl (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_lshr nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Lshr (cexact nw) (tconvert () t)) (convert u1) (convert u2)) I.C_ashr nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Ashr (cexact nw) (tconvert () t)) (convert u1) (convert u2)) I.C_and t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.And [] (tconvert () t)) (convert u1) (convert u2)) I.C_or t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Or [] (tconvert () t)) (convert u1) (convert u2)) I.C_xor t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Xor [] (tconvert () t)) (convert u1) (convert u2)) I.C_add_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Add (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_sub_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Sub (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_mul_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) (Md.liftM2 (A.IbinExpr A.Mul (cnowrap nw) (tconvert () t)) (convert u1) (convert u2)) I.C_udiv_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Udiv (cexact nw) (tconvert () t)) (convert u1) (convert u2) I.C_sdiv_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Sdiv (cexact nw) (tconvert () t)) (convert u1) (convert u2) I.C_urem_V t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Urem [] (tconvert () t)) (convert u1) (convert u2) I.C_srem_V t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Srem [] (tconvert () t)) (convert u1) (convert u2) I.C_shl_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Shl (cnowrap nw) (tconvert () t)) (convert u1) (convert u2) I.C_lshr_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Lshr (cexact nw) (tconvert () t)) (convert u1) (convert u2) I.C_ashr_V nw t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Ashr (cexact nw) (tconvert () t)) (convert u1) (convert u2) I.C_and_V t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.And [] (tconvert () t)) (convert u1) (convert u2) I.C_or_V t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Or [] (tconvert () t)) (convert u1) (convert u2) I.C_xor_V t u1 u2 -> Md.liftM (A.C_binexp . A.Ie) $ Md.liftM2 (A.IbinExpr A.Xor [] (tconvert () t)) (convert u1) (convert u2) I.C_fadd fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fadd fg (tconvert () t)) (convert u1) (convert u2) I.C_fsub fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fsub fg (tconvert () t)) (convert u1) (convert u2) I.C_fmul fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fmul fg (tconvert () t)) (convert u1) (convert u2) I.C_fdiv fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fdiv fg (tconvert () t)) (convert u1) (convert u2) I.C_frem fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Frem fg (tconvert () t)) (convert u1) (convert u2) I.C_fadd_V fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fadd fg (tconvert () t)) (convert u1) (convert u2) I.C_fsub_V fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fsub fg (tconvert () t)) (convert u1) (convert u2) I.C_fmul_V fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fmul fg (tconvert () t)) (convert u1) (convert u2) I.C_fdiv_V fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Fdiv fg (tconvert () t)) (convert u1) (convert u2) I.C_frem_V fg t u1 u2 -> Md.liftM (A.C_binexp . A.Fe) $ Md.liftM2 (A.FbinExpr A.Frem fg (tconvert () t)) (convert u1) (convert u2) I.C_trunc (I.T t0 u0) dt0 -> mkConversion (A.Trunc, tconvert () t0, u0, tconvert () dt0) I.C_zext (I.T t0 u0) dt0 -> mkConversion (A.Zext, tconvert () t0, u0, tconvert () dt0) I.C_sext (I.T t0 u0) dt0 -> mkConversion (A.Sext, tconvert () t0, u0, tconvert () dt0) I.C_fptrunc (I.T t0 u0) dt0 -> mkConversion (A.FpTrunc, tconvert () t0, u0, tconvert () dt0) I.C_fpext (I.T t0 u0) dt0 -> mkConversion (A.FpExt, tconvert () t0, u0, tconvert () dt0) I.C_fptoui (I.T t0 u0) dt0 -> mkConversion (A.FpToUi, tconvert () t0, u0, tconvert () dt0) I.C_fptosi (I.T t0 u0) dt0 -> mkConversion (A.FpToSi, tconvert () t0, u0, tconvert () dt0) I.C_uitofp (I.T t0 u0) dt0 -> mkConversion (A.UiToFp, tconvert () t0, u0, tconvert () dt0) I.C_sitofp (I.T t0 u0) dt0 -> mkConversion (A.SiToFp, tconvert () t0, u0, tconvert () dt0) I.C_ptrtoint (I.T t0 u0) dt0 -> mkConversion (A.PtrToInt, tconvert () t0, u0, tconvert () dt0) I.C_inttoptr (I.T t0 u0) dt0 -> mkConversion (A.IntToPtr, tconvert () t0, u0, tconvert () dt0) I.C_addrspacecast (I.T t0 u0) dt0 -> mkConversion (A.AddrSpaceCast, tconvert () t0, u0, tconvert () dt0) I.C_bitcast (I.T t0 u0) dt0 -> mkConversion (A.Bitcast, tconvert () t0, u0, tconvert () dt0) I.C_trunc_V (I.T t0 u0) dt0 -> mkConversion (A.Trunc, tconvert () t0, u0, tconvert () dt0) I.C_zext_V (I.T t0 u0) dt0 -> mkConversion (A.Zext, tconvert () t0, u0, tconvert () dt0) I.C_sext_V (I.T t0 u0) dt0 -> mkConversion (A.Sext, tconvert () t0, u0, tconvert () dt0) I.C_fptrunc_V (I.T t0 u0) dt0 -> mkConversion (A.FpTrunc, tconvert () t0, u0, tconvert () dt0) I.C_fpext_V (I.T t0 u0) dt0 -> mkConversion (A.FpExt, tconvert () t0, u0, tconvert () dt0) I.C_fptoui_V (I.T t0 u0) dt0 -> mkConversion (A.FpToUi, tconvert () t0, u0, tconvert () dt0) I.C_fptosi_V (I.T t0 u0) dt0 -> mkConversion (A.FpToSi, tconvert () t0, u0, tconvert () dt0) I.C_uitofp_V (I.T t0 u0) dt0 -> mkConversion (A.UiToFp, tconvert () t0, u0, tconvert () dt0) I.C_sitofp_V (I.T t0 u0) dt0 -> mkConversion (A.SiToFp, tconvert () t0, u0, tconvert () dt0) I.C_ptrtoint_V (I.T t0 u0) dt0 -> mkConversion (A.PtrToInt, tconvert () t0, u0, tconvert () dt0) I.C_inttoptr_V (I.T t0 u0) dt0 -> mkConversion (A.IntToPtr, tconvert () t0, u0, tconvert () dt0) I.C_addrspacecast_V (I.T t0 u0) dt0 -> mkConversion (A.AddrSpaceCast, tconvert () t0, u0, tconvert () dt0) I.C_getelementptr b u us -> do { ua <- convert u ; usa <- mapM convert us ; return $ A.C_gep $ A.GetElementPtr b (A.Pointer ua) usa } I.C_getelementptr_V b u us -> do { ua <- convert u ; usa <- mapM convert us ; return $ A.C_gep $ A.GetElementPtr b (A.Pointer ua) usa } I.C_select_I a -> Md.liftM A.C_select (convert a) I.C_select_F a -> Md.liftM A.C_select (convert a) I.C_select_P a -> Md.liftM A.C_select (convert a) I.C_select_First cnd t f -> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.C_select (A.Select cnda ta fa) } I.C_select_VI a -> Md.liftM A.C_select (convert a) I.C_select_VF a -> Md.liftM A.C_select (convert a) I.C_select_VP a -> Md.liftM A.C_select (convert a) I.C_icmp a -> Md.liftM A.C_icmp (convert a) I.C_icmp_V a -> Md.liftM A.C_icmp (convert a) I.C_fcmp a -> Md.liftM A.C_fcmp (convert a) I.C_fcmp_V a -> Md.liftM A.C_fcmp (convert a) I.C_shufflevector_I a -> Md.liftM A.C_shufflevector (convert a) I.C_shufflevector_F a -> Md.liftM A.C_shufflevector (convert a) I.C_shufflevector_P a -> Md.liftM A.C_shufflevector (convert a) I.C_extractvalue a -> Md.liftM A.C_extractvalue (convert a) I.C_insertvalue a -> Md.liftM A.C_insertvalue (convert a) I.C_extractelement_I a -> Md.liftM A.C_extractelement (convert a) I.C_extractelement_F a -> Md.liftM A.C_extractelement (convert a) I.C_extractelement_P a -> Md.liftM A.C_extractelement (convert a) I.C_insertelement_I a -> Md.liftM A.C_insertelement (convert a) I.C_insertelement_F a -> Md.liftM A.C_insertelement (convert a) I.C_insertelement_P a -> Md.liftM A.C_insertelement (convert a) instance Conversion I.MdName (Rm A.MdName) where convert (I.MdName s) = return $ A.MdName s instance Conversion I.MdNode (Rm A.MdNode) where convert (I.MdNode s) = return $ A.MdNode s instance Conversion I.MdRef (Rm A.MdRef) where convert x = case x of I.MdRefName c -> Md.liftM A.MdRefName (convert c) I.MdRefNode c -> Md.liftM A.MdRefNode (convert c) instance Conversion (I.MetaConst I.Gname) (Rm A.MetaConst) where convert (I.McStruct c) = Md.liftM A.McStruct $ mapM convert c convert (I.McString s) = return $ A.McString s convert (I.McMdRef n) = Md.liftM A.McMdRef $ convert n convert (I.McSsa i) = return $ A.McSsa $ unLid i convert (I.McSimple sc) = Md.liftM A.McSimple (convert sc) instance Conversion (I.MetaKindedConst I.Gname) (Rm A.MetaKindedConst) where convert x = case x of (I.MetaKindedConst mk mc) -> Md.liftM (A.MetaKindedConst (tconvert () mk)) (convert mc) I.UnmetaKindedNull -> return A.UnmetaKindedNull instance Conversion (I.Value I.Gname) (Rm A.Value) where convert (I.Val_ssa a) = return $ A.Val_local $ unLid a convert (I.Val_const a) = Md.liftM A.Val_const (convert a) instance Conversion I.CallSiteType (Rm A.Type) where convert t = case t of I.CallSiteTypeRet x -> return $ tconvert () x I.CallSiteTypeFun ft as -> return $ tconvert () (I.Tpointer (ucast ft) as) instance Conversion (I.FunPtr I.Gname) (Rm A.FunName) where convert x = case x of I.Fun_null -> return A.FunName_null I.Fun_undef -> return A.FunName_undef I.FunId g -> return $ A.FunNameGlobal (A.GolG $ unspecializeGlobalId g) I.FunSsa l -> return $ A.FunNameGlobal (A.GolL $ unLid l) I.FunIdBitcast (I.T st c) dt -> do { tv1 <- convert (I.T st c) ; return $ A.FunNameBitcast tv1 (tconvert () dt) } I.FunIdInttoptr (I.T st c) dt -> do { tv1 <- convert (I.T st c) ; return $ A.FunNameInttoptr tv1 (tconvert () dt) } instance Conversion (I.FunPtr I.Gname, I.CallFunInterface I.Gname) (Rm (A.TailCall, A.CallSite)) where convert (fn, I.CallFunInterface { I.cfi_tail = tc, I.cfi_castType = castType , I.cfi_signature = sig, I.cfi_funAttrs = fa}) = do { fna <- convert fn ; (cc, pa, ret, aps) <- convert sig ; let funType = case castType of Just t -> tconvert () t Nothing -> ret ; return (tc, A.CallSiteFun cc pa funType fna aps fa) } instance Conversion (I.FunPtr I.Gname, I.InvokeFunInterface I.Gname) (Rm A.CallSite) where convert (fn, I.InvokeFunInterface { I.ifi_castType = castType, I.ifi_signature = sig, I.ifi_funAttrs = fa}) = do { fna <- convert fn ; (cc, pa, ret, aps) <- convert sig ; let funType = case castType of Just t -> tconvert () t Nothing -> ret ; return (A.CallSiteFun cc pa funType fna aps fa) } instance Conversion (I.Type I.CodeFunB I.X) (Rm (A.Type, [I.RetAttr], Maybe A.VarArgParam)) where convert t@(I.Tfunction (_,retAttrs) pts ma) = return (tconvert () (ptr0 t), retAttrs, ma) getReturnType :: I.Type I.CodeFunB I.X -> Rm (A.Type, [I.RetAttr], Maybe A.VarArgParam) getReturnType t@(I.Tfunction (rt,retAttrs) _ ma) = return (tconvert () rt, retAttrs, ma) instance Conversion (I.AsmCode, I.CallAsmInterface I.Gname) (Rm A.InlineAsmExp) where convert (I.AsmCode dia s1 s2, I.CallAsmInterface t mse mas aps fa) = do { apsa <- mapM convert aps ; (ta,_,_) <- convert t ; return (A.InlineAsmExp ta mse mas dia s1 s2 apsa fa) } instance Conversion (I.Clause I.Gname) (Rm A.Clause) where convert (I.Catch tv) = convert tv >>= \tv' -> return $ A.ClauseCatch tv' convert (I.Filter tc) = convert tc >>= \tc' -> return $ A.ClauseFilter tc' convert (I.CcoS tc) = convert tc >>= return . A.ClauseConversion convert (I.CcoV tc) = convert tc >>= return . A.ClauseConversion instance Conversion I.GlobalOrLocalId (Rm A.GlobalOrLocalId) where convert g = return g instance Conversion (I.Minst I.Gname) (Rm A.ComputingInst) where convert mi = let I.Minst cst fn params = unspecializeMinst mi in do { fna <- convert (I.FunId fn) ; cst0 <- convert cst ; apa <- mapM convert params ; return $ A.ComputingInst Nothing $ A.RhsCall A.TcNon $ A.CallSiteFun Nothing [] cst0 fna apa [] } instance Conversion (I.Cinst I.Gname) (Rm A.ComputingInst) where convert cinst = case unspecializeRegisterIntrinsic cinst of Just (gid, typ, opds, lhs) -> do { opdsa <- mapM convert opds ; let rtTyp = maybe A.Tvoid (\_ -> tconvert () typ) lhs ; return $ A.ComputingInst (fmap unLid lhs) $ A.RhsCall A.TcNon $ A.CallSiteFun Nothing [] rtTyp (A.FunNameGlobal $ A.GolG $ unspecializeGlobalId gid) opdsa [] } Nothing -> case maybe cinst id (unspecializeIntrinsics cinst) of I.I_alloca mar t mtv ma lhs -> do { mtva <- maybeM convert mtv ; return $ A.ComputingInst (Just (unLid lhs)) $ A.RhsMemOp $ A.Alloca mar (tconvert () t) mtva ma } I.I_load atom tv aa nonterm invr nonull lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just (unLid lhs)) $ A.RhsMemOp $ A.Load atom (A.Pointer tva) aa nonterm invr nonull } I.I_loadatomic atom v tv aa lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just (unLid lhs)) $ A.RhsMemOp $ A.LoadAtomic atom v (A.Pointer tva) aa } I.I_store atom tv1 tv2 aa nonterm -> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst Nothing (A.RhsMemOp $ A.Store atom tv1a (A.Pointer tv2a) aa nonterm) } I.I_storeatomic atom v tv1 tv2 aa -> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst Nothing (A.RhsMemOp $ A.StoreAtomic atom v tv1a (A.Pointer tv2a) aa) } I.I_cmpxchg_I wk b1 tv1 tv2 tv3 b2 sord ford lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsMemOp $ A.CmpXchg wk b1 (A.Pointer tv1a) tv2a tv3a b2 sord ford) } I.I_cmpxchg_F wk b1 tv1 tv2 tv3 b2 sord ford lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsMemOp $ A.CmpXchg wk b1 (A.Pointer tv1a) tv2a tv3a b2 sord ford) } I.I_cmpxchg_P wk b1 tv1 tv2 tv3 b2 sord ford lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsMemOp $ A.CmpXchg wk b1 (A.Pointer tv1a) tv2a tv3a b2 sord ford) } I.I_atomicrmw b1 op tv1 tv2 b2 mf lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsMemOp $ A.AtomicRmw b1 op (A.Pointer tv1a) tv2a b2 mf) } I.I_fence b fo -> return $ A.ComputingInst Nothing $ A.RhsMemOp $ A.Fence b fo I.I_va_arg tv t lhs-> do { tv1 <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) $ A.RhsVaArg $ A.VaArg tv1 (tconvert () t) } I.I_landingpad t1 t2 pf b cs lhs-> do { pfa <- convert pf ; csa <- mapM convert cs ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsLandingPad $ A.LandingPad (tconvert () t1) (tconvert () t2) pfa b csa) } I.I_extractelement_I tv1 tv2 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExtractElement $ A.ExtractElement tv1a tv2a) } I.I_extractelement_F tv1 tv2 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExtractElement $ A.ExtractElement tv1a tv2a) } I.I_extractelement_P tv1 tv2 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExtractElement $ A.ExtractElement tv1a tv2a) } I.I_extractvalue tv1 idx lhs-> do { tv1a <- convert tv1 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExtractValue $ A.ExtractValue tv1a idx) } I.I_getelementptr b ptr idx lhs-> do { ptra <- convert ptr ; idxa <- mapM convert idx ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprGetElementPtr $ A.GetElementPtr b (A.Pointer ptra) idxa) } I.I_getelementptr_V b ptr idx lhs -> do { ptra <- convert ptr ; idxa <- mapM convert idx ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprGetElementPtr $ A.GetElementPtr b (A.Pointer ptra) idxa) } I.I_icmp op t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprIcmp $ A.Icmp op (tconvert () t) v1a v2a) } I.I_icmp_V op t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprIcmp $ A.Icmp op (tconvert () t) v1a v2a) } I.I_fcmp op t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprFcmp $ A.Fcmp op (tconvert () t) v1a v2a) } I.I_fcmp_V op t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprFcmp $ A.Fcmp op (tconvert () t) v1a v2a) } I.I_add n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Add (cnowrap n) (tconvert () t) v1a v2a) } I.I_sub n t v1 v2 lhs -> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Sub (cnowrap n) (tconvert () t) v1a v2a) } I.I_mul n t v1 v2 lhs -> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Mul (cnowrap n) (tconvert () t) v1a v2a) } I.I_udiv n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Udiv (cexact n) (tconvert () t) v1a v2a) } I.I_sdiv n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Sdiv (cexact n) (tconvert () t) v1a v2a) } I.I_urem t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Urem [] (tconvert () t) v1a v2a) } I.I_srem t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Srem [] (tconvert () t) v1a v2a) } I.I_shl n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Shl (cnowrap n) (tconvert () t) v1a v2a) } I.I_lshr n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Lshr (cexact n) (tconvert () t) v1a v2a) } I.I_ashr n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Ashr (cexact n) (tconvert () t) v1a v2a) } I.I_and t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.And [] (tconvert () t) v1a v2a) } I.I_or t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Or [] (tconvert () t) v1a v2a) } I.I_xor t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Xor [] (tconvert () t) v1a v2a) } I.I_add_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Add (cnowrap n) (tconvert () t) v1a v2a) } I.I_sub_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Sub (cnowrap n) (tconvert () t) v1a v2a) } I.I_mul_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Mul (cnowrap n) (tconvert () t) v1a v2a) } I.I_udiv_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Udiv (cexact n) (tconvert () t) v1a v2a) } I.I_sdiv_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Sdiv (cexact n) (tconvert () t) v1a v2a) } I.I_urem_V t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Urem [] (tconvert () t) v1a v2a) } I.I_srem_V t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Srem [] (tconvert () t) v1a v2a) } I.I_shl_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Shl (cnowrap n) (tconvert () t) v1a v2a) } I.I_lshr_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Lshr (cexact n) (tconvert () t) v1a v2a) } I.I_ashr_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Ashr (cexact n) (tconvert () t) v1a v2a) } I.I_and_V t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.And [] (tconvert () t) v1a v2a) } I.I_or_V t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Or [] (tconvert () t) v1a v2a) } I.I_xor_V t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Ie $ A.IbinExpr A.Xor [] (tconvert () t) v1a v2a) } I.I_fadd n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fadd n (tconvert () t) v1a v2a) } I.I_fsub n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fsub n (tconvert () t) v1a v2a) } I.I_fmul n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fmul n (tconvert () t) v1a v2a) } I.I_fdiv n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fdiv n (tconvert () t) v1a v2a) } I.I_frem n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Frem n (tconvert () t) v1a v2a) } I.I_fadd_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fadd n (tconvert () t) v1a v2a) } I.I_fsub_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fsub n (tconvert () t) v1a v2a) } I.I_fmul_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fmul n (tconvert () t) v1a v2a) } I.I_fdiv_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Fdiv n (tconvert () t) v1a v2a) } I.I_frem_V n t v1 v2 lhs-> do { v1a <- convert v1 ; v2a <- convert v2 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprBinExpr $ A.Fe $ A.FbinExpr A.Frem n (tconvert () t) v1a v2a) } I.I_trunc tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Trunc tva (tconvert () dt)) } I.I_zext tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Zext tva (tconvert () dt)) } I.I_sext tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Sext tva (tconvert () dt)) } I.I_fptrunc tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpTrunc tva (tconvert () dt)) } I.I_fpext tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpExt tva (tconvert () dt)) } I.I_fptoui tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpToUi tva (tconvert () dt)) } I.I_fptosi tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpToSi tva (tconvert () dt)) } I.I_uitofp tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.UiToFp tva (tconvert () dt)) } I.I_sitofp tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.SiToFp tva (tconvert () dt)) } I.I_ptrtoint tv dt lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.PtrToInt tva (tconvert () dt)) } I.I_inttoptr tv dt lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.IntToPtr tva (tconvert () dt)) } I.I_bitcast tv dt lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Bitcast tva (tconvert () dt)) } I.I_bitcast_D tv dt lhs -> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Bitcast tva (tconvert () dt)) } I.I_addrspacecast tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.AddrSpaceCast tva (tconvert () dt)) } I.I_trunc_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Trunc tva (tconvert () dt)) } I.I_zext_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Zext tva (tconvert () dt)) } I.I_sext_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.Sext tva (tconvert () dt)) } I.I_fptrunc_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpTrunc tva (tconvert () dt)) } I.I_fpext_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpExt tva (tconvert () dt)) } I.I_fptoui_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpToUi tva (tconvert () dt)) } I.I_fptosi_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.FpToSi tva (tconvert () dt)) } I.I_uitofp_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.UiToFp tva (tconvert () dt)) } I.I_sitofp_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.SiToFp tva (tconvert () dt)) } I.I_ptrtoint_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.PtrToInt tva (tconvert () dt)) } I.I_inttoptr_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.IntToPtr tva (tconvert () dt)) } I.I_addrspacecast_V tv dt lhs-> do { tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprConversion $ A.Conversion A.AddrSpaceCast tva (tconvert () dt)) } I.I_select_I cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_F cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_P cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_First cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_VI cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_VF cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_select_VP cnd t f lhs-> do { cnda <- convert cnd ; ta <- convert t ; fa <- convert f ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsExpr $ A.ExprSelect $ A.Select cnda ta fa) } I.I_insertelement_I vtv tv idx lhs-> do { vtva <- convert vtv ; tva <- convert tv ; idxa <- convert idx ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsInsertElement $ A.InsertElement vtva tva idxa) } I.I_insertelement_F vtv tv idx lhs-> do { vtva <- convert vtv ; tva <- convert tv ; idxa <- convert idx ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsInsertElement $ A.InsertElement vtva tva idxa) } I.I_insertelement_P vtv tv idx lhs-> do { vtva <- convert vtv ; tva <- convert tv ; idxa <- convert idx ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsInsertElement $ A.InsertElement vtva tva idxa) } I.I_shufflevector_I tv1 tv2 tv3 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsShuffleVector $ A.ShuffleVector tv1a tv2a tv3a) } I.I_shufflevector_F tv1 tv2 tv3 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsShuffleVector $ A.ShuffleVector tv1a tv2a tv3a) } I.I_shufflevector_P tv1 tv2 tv3 lhs-> do { tv1a <- convert tv1 ; tv2a <- convert tv2 ; tv3a <- convert tv3 ; return $ A.ComputingInst (Just $ unLid lhs) (A.RhsShuffleVector $ A.ShuffleVector tv1a tv2a tv3a) } I.I_insertvalue vtv tv idx lhs-> do { vtva <- convert vtv ; tva <- convert tv ; return $ A.ComputingInst (Just $ unLid lhs) $ A.RhsInsertValue $ A.InsertValue vtva tva idx } I.I_call_fun fn cfi lhs-> do { (tc, csa) <- convert (fn, cfi) ; return $ A.ComputingInst (fmap unLid lhs) $ A.RhsCall tc csa } I.I_call_asm asm cai lhs -> do { csa <- convert (asm, cai) ; return $ A.ComputingInst (fmap unLid lhs) $ A.RhsInlineAsm csa } _ -> errorLoc FLC $ show cinst instance Conversion (I.FunOperand (I.Value I.Gname)) (Rm A.ActualParam) where convert x = case x of I.FunOperandData t pa ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma (fmap unspecializePAttr pa)) va } I.FunOperandByVal t pa ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma (A.PaByVal:(fmap unspecializePAttr pa))) va } I.FunOperandLabel t pa ma (I.Val_const (I.C_labelId v)) -> do { va <- convert_to_PercentLabel v ; return $ A.ActualParamLabel (tconvert () t) (appendAlignment ma (fmap unspecializePAttr pa)) va } I.FunOperandAsRet t pa1 ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma (A.PaSRet:(fmap unspecializePAttr pa1))) va } I.FunOperandExt I.Sign t pa1 ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma (A.PaSignExt:(fmap unspecializePAttr pa1))) va } I.FunOperandExt I.Zero t pa1 ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma (A.PaZeroExt:(fmap unspecializePAttr pa1))) va } instance Conversion (I.MetaOperand I.Gname) (Rm A.ActualParam) where convert x = case x of I.MetaOperandData t pa1 ma v -> do { va <- convert v ; return $ A.ActualParamData (tconvert () t) (appendAlignment ma pa1) va } I.MetaOperandMeta mc -> Md.liftM (A.ActualParamMeta) (convert mc) instance Conversion (I.Aliasee I.Gname) (Rm A.Const) where convert (I.Aliasee v) = return $ A.C_simple $ A.CpGlobalAddr $ unspecializeGlobalId v convert (I.AliaseeConversion a) = Md.liftM A.C_conv (convert a) convert (I.AliaseeGEP a) = Md.liftM A.C_gep (convert a) convertAliasee :: I.Aliasee I.Gname -> Rm A.Aliasee convertAliasee ae = case ae of I.AliaseeTyped t a -> convert a >>= \ax -> return $ A.Aliasee (A.Typed (tconvert () t) ax) I.AliaseeConversion a -> Md.liftM A.AliaseeConversion (convert a) I.AliaseeGEP a -> Md.liftM A.AliaseeGetElementPtr (convert a) instance Conversion (I.Prefix I.Gname) (Rm A.Prefix) where convert (I.Prefix n) = Md.liftM A.Prefix (convert n) instance Conversion (I.Prologue I.Gname) (Rm A.Prologue) where convert (I.Prologue n) = Md.liftM A.Prologue (convert n) instance Conversion (I.TypedConstOrNull I.Gname) (Rm A.TypedConstOrNull) where convert x = case x of I.TypedConst tv -> Md.liftM A.TypedConst (convert tv) I.UntypedNull -> return A.UntypedNull instance Conversion (I.FunOperand ()) (Rm A.FormalParam) where convert x = case x of I.FunOperandData dt pa ma _ -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (fmap unspecializePAttr pa)) (A.FimplicitParam) I.FunOperandByVal dt pa ma _ -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaByVal:(fmap unspecializePAttr pa))) (A.FimplicitParam) I.FunOperandAsRet dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaSRet:(fmap unspecializePAttr pa))) A.FimplicitParam I.FunOperandExt I.Sign dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaSignExt:(fmap unspecializePAttr pa))) A.FimplicitParam I.FunOperandExt I.Zero dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaZeroExt:(fmap unspecializePAttr pa))) A.FimplicitParam instance Conversion (I.FunOperand I.Lname) (Rm A.FormalParam) where convert x = case x of I.FunOperandData dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (fmap unspecializePAttr pa)) (A.FexplicitParam $ unLid fp) I.FunOperandByVal dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaByVal:(fmap unspecializePAttr pa))) (A.FexplicitParam $ unLid fp) I.FunOperandAsRet dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaSRet:(fmap unspecializePAttr pa))) (A.FexplicitParam $ unLid fp) I.FunOperandExt I.Sign dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaSignExt:(fmap unspecializePAttr pa))) (A.FexplicitParam $ unLid fp) I.FunOperandExt I.Zero dt pa ma fp -> return $ A.FormalParamData (tconvert () dt) (appendAlignment ma (A.PaZeroExt:(fmap unspecializePAttr pa))) (A.FexplicitParam $ unLid fp) instance Conversion (I.FunSignature I.Lname) (Rm (Maybe A.CallConv, [A.ParamAttr], A.Type, A.FormalParamList)) where convert I.FunSignature { I.fs_callConv = cc, I.fs_type = typ, I.fs_params = paras } = do { (ret, attrs, mv) <- getReturnType typ ; paras0 <- mapM convert paras -- TODO : check the paramter types match fs_type ; return (Just cc, fmap unspecializeRetAttr attrs, ret, A.FormalParamList paras0 mv) } instance Conversion (I.FunSignature ()) (Rm (Maybe A.CallConv, [A.ParamAttr], A.Type, A.FormalParamList)) where convert I.FunSignature { I.fs_callConv = cc, I.fs_type = typ, I.fs_params = paras } = do { (ret, attrs, mv) <- getReturnType typ ; paras0 <- mapM convert paras ; return (Just cc, fmap unspecializeRetAttr attrs, ret, A.FormalParamList paras0 mv) } instance Conversion (I.FunSignature (I.Value I.Gname)) (Rm (Maybe A.CallConv, [A.ParamAttr], A.Type, [A.ActualParam])) where convert I.FunSignature { I.fs_callConv = cc, I.fs_type = typ, I.fs_params = paras } = do { (ret, attrs, mv) <- convert typ ; paras0 <- mapM convert paras ; return (Just cc, fmap unspecializeRetAttr attrs, ret, paras0) } instance Conversion (I.FunctionInterface I.Gname) (Rm A.FunctionPrototype) where convert (I.FunctionInterface { I.fi_linkage = f0 , I.fi_visibility = f1 , I.fi_dllstorage = f2 , I.fi_signature = f3 , I.fi_fun_name = f6 , I.fi_addr_naming = f8 , I.fi_fun_attrs = f9 , I.fi_section = f10 , I.fi_comdat = f11 , I.fi_alignment = f12 , I.fi_gc = f13 , I.fi_prefix = f14 , I.fi_prologue = f15 }) = do { f15a <- convert f15 ; f14a <- convert f14 ; (f3a, f3b, f3c, f3d) <- convert f3 ; return $ A.FunctionPrototype { A.fp_linkage = f0 , A.fp_visibility = f1 , A.fp_dllstorage = f2 , A.fp_callConv = f3a , A.fp_retAttrs = f3b , A.fp_retType = f3c , A.fp_fun_name = unspecializeGlobalId f6 , A.fp_param_list = f3d , A.fp_addr_naming = f8 , A.fp_fun_attrs = f9 , A.fp_section = f10 , A.fp_comdat = fmap convert_Comdat f11 , A.fp_alignment = f12 , A.fp_gc = f13 , A.fp_prefix = f14a , A.fp_prologue = f15a } } instance Conversion (I.FunctionDeclare I.Gname) (Rm A.FunctionPrototype) where convert x = case x of I.FunctionDeclareData { I.fd_linkage = f0 , I.fd_visibility = f1 , I.fd_dllstorage = f2 , I.fd_signature = f3 , I.fd_fun_name = f6 , I.fd_addr_naming = f8 , I.fd_fun_attrs = f9 , I.fd_section = f10 , I.fd_comdat = f11 , I.fd_alignment = f12 , I.fd_gc = f13 , I.fd_prefix = f14 , I.fd_prologue = f15 } -> do { f15a <- convert f15 ; f14a <- convert f14 ; (f3a, f3b, f3c, f3d) <- convert f3 ; return $ A.FunctionPrototype { A.fp_linkage = f0 , A.fp_visibility = f1 , A.fp_dllstorage = f2 , A.fp_callConv = f3a , A.fp_retAttrs = f3b , A.fp_retType = f3c , A.fp_fun_name = unspecializeGlobalId f6 , A.fp_param_list = f3d , A.fp_addr_naming = f8 , A.fp_fun_attrs = f9 , A.fp_section = f10 , A.fp_comdat = fmap convert_Comdat f11 , A.fp_alignment = f12 , A.fp_gc = f13 , A.fp_prefix = f14a , A.fp_prologue = f15a } } I.FunctionDeclareMeta { I.fd_retType = f5 , I.fd_fun_name = f6 , I.fd_metakinds = f7 , I.fd_fun_attrs = f8 } -> do { let f7a = fmap (\x -> case x of Left m -> A.FormalParamMeta (tconvert () m) A.FimplicitParam Right m -> A.FormalParamData (tconvert () m) [] A.FimplicitParam ) f7 ; return $ A.FunctionPrototype { A.fp_linkage = Nothing , A.fp_visibility = Nothing , A.fp_dllstorage = Nothing , A.fp_callConv = Nothing , A.fp_retAttrs = [] , A.fp_retType = (tconvert () f5) , A.fp_fun_name = unspecializeGlobalId f6 , A.fp_param_list = A.FormalParamList f7a Nothing , A.fp_addr_naming = Nothing , A.fp_fun_attrs = f8 , A.fp_section = Nothing , A.fp_comdat = Nothing , A.fp_alignment = Nothing , A.fp_gc = Nothing , A.fp_prefix = Nothing , A.fp_prologue = Nothing } } instance Conversion (I.Pinst I.Gname) (Rm A.PhiInst) where convert (I.Pinst t branches mg) = Md.liftM (A.PhiInst (Just $ unLid mg) (tconvert () t)) (mapM (pairM convert convert_to_PercentLabel) branches) instance Conversion (I.Tinst I.Gname) (Rm A.TerminatorInst) where convert (I.T_ret_void) = return A.RetVoid convert (I.T_return tvs) = Md.liftM A.Return (mapM convert tvs) convert (I.T_br t) = Md.liftM A.Br (convert_to_TargetLabel t) convert (I.T_cbr cnd t f) = Md.liftM3 A.Cbr (convert cnd) (convert_to_TargetLabel t) (convert_to_TargetLabel f) convert (I.T_indirectbr cnd bs) = Md.liftM2 A.IndirectBr (convert cnd) (mapM convert_to_TargetLabel bs) convert (I.T_switch (cnd,d) cases) = Md.liftM3 A.Switch (convert cnd) (convert_to_TargetLabel d) (mapM (pairM convert convert_to_TargetLabel) cases) convert (I.T_invoke fptr ifi t f mg) = Md.liftM3 (A.Invoke (fmap unLid mg)) (convert (fptr, ifi)) (convert_to_TargetLabel t) (convert_to_TargetLabel f) convert (I.T_invoke_asm asm cai t f lhs) = Md.liftM3 (A.InvokeInlineAsm (fmap unLid lhs)) (convert (asm, cai)) (convert_to_TargetLabel t) (convert_to_TargetLabel f) convert (I.T_resume tv) = Md.liftM A.Resume (convert tv) convert I.T_unreachable = return A.Unreachable convert I.T_unwind = return A.Unwind instance Conversion (I.Dbg I.Gname) (Rm A.Dbg) where convert (I.Dbg mv mc) = Md.liftM2 A.Dbg (convert mv) (convert mc) instance Conversion PhiInstWithDbg (Rm A.PhiInstWithDbg) where convert (PhiInstWithDbg ins dbgs) = Md.liftM2 A.PhiInstWithDbg (convert ins) (mapM convert dbgs) instance Conversion CInstWithDbg (Rm A.ComputingInstWithDbg) where convert (CInstWithDbg ins dbgs) = Md.liftM2 A.ComputingInstWithDbg (convert ins) (mapM convert dbgs) instance Conversion MInstWithDbg (Rm A.ComputingInstWithDbg) where convert (MInstWithDbg ins dbgs) = Md.liftM2 A.ComputingInstWithDbg (convert ins) (mapM convert dbgs) instance Conversion TerminatorInstWithDbg (Rm A.TerminatorInstWithDbg) where convert (TerminatorInstWithDbg term dbgs) = Md.liftM2 A.TerminatorInstWithDbg (convert term) (mapM convert dbgs) instance Conversion (I.TlAlias I.Gname) (Rm A.TlAlias) where convert (I.TlAlias g v dll tlm na l a) = convertAliasee a >>= return . (A.TlAlias (unspecializeGlobalId g) v dll tlm na l) instance Conversion (I.TlUnamedMd I.Gname) (Rm A.TlUnamedMd) where convert x = let (I.TlUnamedMd s tv) = unspecializeUnamedMd x in Md.liftM (A.TlUnamedMd s) (convert tv) instance Conversion I.TlNamedMd (Rm A.TlNamedMd) where convert (I.TlNamedMd m ns) = Md.liftM (A.TlNamedMd m) (mapM convert ns) instance Conversion (I.TlDeclare I.Gname) (Rm A.TlDeclare) where convert (I.TlDeclare f) = convert f >>= return . A.TlDeclare instance Conversion I.TlDeclareIntrinsic (Rm A.TlDeclare) where convert f = convert (unspecializeDeclareIntrinsic f) instance Conversion (I.TlDefine I.Gname ()) (Rm A.TlDefine) where convert (I.TlDefine f elbl g) = withFunName (I.fi_fun_name f) $ do { (bl, bm) <- graphToBlocks g ; fa <- convert f ; elbla <- convert elbl ; let entryblk = case M.lookup elbla bm of Just x -> x Nothing -> error $ "irrefutable: entry block " ++ show elbl ++ " does not exist." ; let bs'' = entryblk:(filter (\x -> x /= entryblk) bl) ; return $ A.TlDefine fa bs'' } -- TODO: this method will NOT emit the new nodes generated by hoopl passes, it should be fixed ASAP. instance Conversion (I.TlIntrinsic I.Gname) (Rm A.TlGlobal) where convert x = convert (unspecializeTlIntrinsics x) instance Conversion (I.TlGlobal I.Gname) (Rm A.TlGlobal) where convert x = case x of (I.TlGlobalDtype a1 a2 a3 a4 a5 a6 a7 a8 a8a a9 a10 a11 a12 a13) -> do { a10a <- maybeM convert a10 ; return $ A.TlGlobal (Just $ unspecializeGlobalId a1) a2 a3 a4 a5 a6 (fmap (tconvert ()) a7) a8 a8a (tconvert () a9) a10a a11 (fmap convert_Comdat a12) a13 } (I.TlGlobalOpaque a1 a2 a3 a4 a5 a6 a7 a8 a8a a9 a10 a11 a12 a13) -> do { a10a <- maybeM convert a10 ; return $ A.TlGlobal (Just $ unspecializeGlobalId a1) a2 a3 a4 a5 a6 (fmap (tconvert ()) a7) a8 a8a (tconvert () a9) a10a a11 (fmap convert_Comdat a12) a13 } convert_Comdat :: I.Comdat I.Gname -> A.Comdat convert_Comdat (I.Comdat n) = A.Comdat (fmap unspecializeDollarId n) instance Conversion I.TlTypeDef (Rm A.TlTypeDef) where convert x = case x of (I.TlFunTypeDef lid t) -> return (A.TlTypeDef (unLid lid) (tconvert () t)) (I.TlDatTypeDef lid t) -> return (A.TlTypeDef (unLid lid) (tconvert () t)) (I.TlOpqTypeDef lid t) -> return (A.TlTypeDef (unLid lid) (tconvert () t)) instance Conversion I.TlDepLibs (Rm A.TlDepLibs) where convert (I.TlDepLibs s) = return (A.TlDepLibs s) instance Conversion I.TlUnamedType (Rm A.TlUnamedType) where convert (I.TlUnamedType i t) = return (A.TlUnamedType i (tconvert () t)) instance Conversion I.TlModuleAsm (Rm A.TlModuleAsm) where convert (I.TlModuleAsm s) = return (A.TlModuleAsm s) instance Conversion I.TlAttribute (Rm A.TlAttribute) where convert (I.TlAttribute n l) = return (A.TlAttribute n l) instance Conversion (I.TlComdat I.Gname) (Rm A.TlComdat) where convert (I.TlComdat l s) = return (A.TlComdat (unspecializeDollarId l) s) instance Conversion I.TlComment (Rm [String]) where convert (I.TlComment a) = return (I.commentize a) type Pblock = (A.BlockLabel, [A.PhiInstWithDbg], [A.ComputingInstWithDbg]) getLabelId :: A.BlockLabel -> A.LabelId getLabelId (A.ImplicitBlockLabel _) = error "ImplicitBlockLabel should be normalized" getLabelId (A.ExplicitBlockLabel l) = l isComment :: A.ComputingInstWithDbg -> Bool isComment x = case x of A.ComputingInstWithComment _ -> True _ -> False data PhiInstWithDbg = PhiInstWithDbg (I.Pinst I.Gname) [I.Dbg I.Gname] deriving (Eq, Ord, Show) data CInstWithDbg = CInstWithDbg (I.Cinst I.Gname) [I.Dbg I.Gname] deriving (Eq, Ord, Show) data MInstWithDbg = MInstWithDbg (I.Minst I.Gname) [I.Dbg I.Gname] deriving (Eq, Ord, Show) data TerminatorInstWithDbg = TerminatorInstWithDbg (I.Tinst I.Gname) [I.Dbg I.Gname] deriving (Eq, Ord, Show) convertNode :: I.Node I.Gname () e x -> Rm ([A.Block], M.Map A.LabelId A.Block, Maybe Pblock) -> Rm ([A.Block], M.Map A.LabelId A.Block, Maybe Pblock) convertNode (I.Lnode a) p = do { (bl, bs, Nothing) <- p ; a' <- convert_to_BlockLabel a ; return (bl, bs, Just (a', [], [])) } convertNode (I.Pnode a dbgs) p = do { (bl, bs, pblk) <- p ; case pblk of Just (pb, phis, l) | all isComment l -> do { a' <- convert (PhiInstWithDbg a dbgs) ; return (bl, bs, Just (pb, a':phis, l)) } _ -> errorLoc FLC $ "irrefutable:unexpected case " ++ show pblk } convertNode (I.Cnode a dbgs) p = do { (bl, bs, Just (pb, phis, cs)) <- p ; a' <- convert (CInstWithDbg a dbgs) ; return (bl, bs, Just (pb, phis, a':cs)) } convertNode (I.Mnode a dbgs) p = do { (bl, bs, Just (pb, phis, cs)) <- p ; a' <- convert (MInstWithDbg a dbgs) ; return (bl, bs, Just (pb, phis, a':cs)) } convertNode (I.Comment a) p = do { (bl, bs, Just (pb, phis, cs)) <- p ; let comments = reverse $ fmap A.ComputingInstWithComment (I.commentize a) ; return (bl, bs, Just (pb, phis, comments ++ cs)) } convertNode (I.Tnode a dbgs) p = do { (bl, bs, pb) <- p ; a' <- convert (TerminatorInstWithDbg a dbgs) ; case pb of Nothing -> error "irrefutable" Just (l, phis, cs) -> let blk = A.Block l (reverse phis) (reverse cs) a' in return (blk:bl, M.insert (getLabelId l) blk bs, Nothing) } convertNode (I.Enode _ _) _ = error "irrefutable:Enode should be converted to LLVM node" graphToBlocks :: H.Graph (I.Node I.Gname ()) H.C H.C -> Rm ([A.Block], M.Map A.LabelId A.Block) graphToBlocks g = do { (bl, bs, Nothing) <- H.foldGraphNodes convertNode g (return ([], M.empty, Nothing)) ; return (reverse bl, bs) } toplevel2Ast :: I.Toplevel I.Gname () -> Rm A.Toplevel toplevel2Ast (I.ToplevelAlias g) = Md.liftM A.ToplevelAlias (convert g) toplevel2Ast (I.ToplevelUnamedMd s) = Md.liftM (A.ToplevelUnamedMd) (convert s) toplevel2Ast (I.ToplevelNamedMd m) = Md.liftM A.ToplevelNamedMd (convert m) toplevel2Ast (I.ToplevelDeclare f) = Md.liftM A.ToplevelDeclare (convert f) toplevel2Ast (I.ToplevelDeclareIntrinsic f) = Md.liftM A.ToplevelDeclare (convert f) toplevel2Ast (I.ToplevelDefine f) = Md.liftM A.ToplevelDefine (convert f) toplevel2Ast (I.ToplevelGlobal s) = Md.liftM A.ToplevelGlobal (convert s) toplevel2Ast (I.ToplevelTypeDef t) = Md.liftM A.ToplevelTypeDef (convert t) toplevel2Ast (I.ToplevelDepLibs qs) = Md.liftM A.ToplevelDepLibs (convert qs) toplevel2Ast (I.ToplevelUnamedType i) = Md.liftM A.ToplevelUnamedType (convert i) toplevel2Ast (I.ToplevelModuleAsm q) = Md.liftM A.ToplevelModuleAsm (convert q) toplevel2Ast (I.ToplevelComdat l) = Md.liftM A.ToplevelComdat (convert l) toplevel2Ast (I.ToplevelAttribute n) = Md.liftM A.ToplevelAttribute (convert n) toplevel2Ast (I.ToplevelIntrinsic n) = Md.liftM A.ToplevelGlobal (convert n) toplevel2Ast (I.ToplevelComment n) = Md.liftM A.ToplevelComment (convert n) hirToAsm :: M.Map (I.Gname, H.Label) A.LabelId -> I.SpecializedModule I.Gname () -> A.Module hirToAsm iLm (I.SpecializedModule (Target dlm) (I.Module ts)) = let (A.Module tl) = runReader (Md.liftM A.Module (mapM toplevel2Ast ts)) (ReaderData iLm (I.Gname (errorLoc FLC $ "<fatal error>"))) ls = toLayoutSpec dlm tt = toTriple dlm in A.Module ((A.ToplevelDataLayout $ A.TlDataLayout $ A.DataLayout ls):(A.ToplevelTriple $ A.TlTriple tt):tl)
mlite/hLLVM
src/Llvm/AsmHirConversion/HirToAsm.hs
bsd-3-clause
79,015
0
23
26,516
32,395
16,080
16,315
1,213
3
module Util where import Data.Time import Options.Applicative import Text.Printf data ClientConfig = ClientConfig { ccHost :: String , ccPort :: Int , ccConn :: Int , ccActive :: Int , ccTotal :: Int } clientConfig :: Parser ClientConfig clientConfig = ClientConfig <$> strOption ( long "host" & short 'h' & metavar "HOSTNAME" & value "localhost" & help "hostname" ) <*> option ( long "port" & short 'p' & metavar "PORT" & value 1234 & help "Port number" ) <*> option ( long "connection" & short 'c' & metavar "CONN" & value 1 & help "Connection number" ) <*> option ( long "active" & short 'a' & metavar "ACTIVE" & value 1 & help "Active request number" ) <*> option ( long "requests" & short 'n' & metavar "REQUESTS" & value 10000 & help "Request number" ) data ServerConfig = ServerConfig { scPort :: Int } serverConfig :: Parser ServerConfig serverConfig = ServerConfig <$> option ( long "port" & short 'p' & metavar "PORT" & value 1234 & help "Port number" ) benchQPS :: Int -> IO () -> IO () benchQPS qnum m = do ela <- measureTime m printf "%d reqs in %.03f sec, %.03f qps\n" qnum ela (fromIntegral qnum / ela) measureTime :: IO () -> IO Double measureTime m = do start <- getCurrentTime _ <- m end <- getCurrentTime return . realToFrac $ end `diffUTCTime` start
tanakh/echo
Util.hs
bsd-3-clause
1,482
0
16
442
473
228
245
52
1
{-# LANGUAGE ScopedTypeVariables #-} module Test.Generalization where import Test.Helper (test2) import Generalization import qualified FreshNames as FN import Syntax import qualified Subst import Control.Monad.State gen1 :: Generalizer gen1 = Subst.empty gen2 :: Generalizer gen2 = Subst.empty gen1' = [] gen2' = [] freshNames :: FN.FreshNames freshNames = FN.FreshNames 10 vars :: [Ts] vars@[x, y, z] = map V [1, 2, 3] c :: [Ts] -> Ts c = C "" inv :: [Ts] -> G S inv = Invoke "" gx = inv [x] gy = inv [y] gz = inv [z] gxx = inv [x, x] gxy = inv [x, y] gxxy = inv [x, x, y] gxyy = inv [x, y, y] unit_generalizeTerm = do let function = test2 (\x y -> runState (generalize gen1 gen2 x y) freshNames) function x x ((x, gen1, gen2), freshNames) function y z (let (n,t) = FN.getFreshName freshNames in ((V n, Subst.fromList $ (n, y) : gen1', Subst.fromList $ (n, z) : gen2'), t)) function (c [x, x]) (c [x, y]) (let (n,t) = FN.getFreshName freshNames in ((c [x, V n], Subst.fromList $ (n, x) : gen1', Subst.fromList $ (n, y) : gen2'), t)) function (c [x, x, y]) (c [x, y, y]) (let (n,t) = FN.getFreshName freshNames in ((c [x, V n, y], Subst.fromList $ (n, x) : gen1', Subst.fromList $ (n, y) : gen2'), t)) function (c [c [], x, y]) (c [x, c [], y]) (let ([n,m],t) = FN.getNames 2 freshNames in ((c [V n, V m, y], Subst.fromList $ (m, x) : (n, c []) : gen1', Subst.fromList $ (m, c []) : (n, x) : gen2'), t)) unit_generalizeGoal = do let function = test2 (\x y -> runState (generalize gen1 gen2 x y) freshNames) function gx gx ((gx, gen1, gen2), freshNames) function gy gz (let (n,t) = FN.getFreshName freshNames in ((inv [V n], Subst.fromList $ (n, y) : gen1', Subst.fromList $ (n, z) : gen2'), t)) function gxx gxy (let (n,t) = FN.getFreshName freshNames in ((inv [x, V n], Subst.fromList $ (n, x) : gen1', Subst.fromList $ (n, y) : gen2'), t)) function gxxy gxyy (let (n,t) = FN.getFreshName freshNames in ((inv [x, V n, y], Subst.fromList $ (n, x) : gen1', Subst.fromList $ (n, y) : gen2'), t)) function (inv [c [], x, y]) (inv [x, c [], y]) (let ([n,m], t) = FN.getNames 2 freshNames in ((inv [V n, V m, y], Subst.fromList $ (m, x) : (n, c []) : gen1', Subst.fromList $ (m, c []) : (n, x) : gen2'), t)) unit_generalizeGoals = do let function = test2 (\x y -> runState (generalize gen1 gen2 x y) freshNames) function [gx, gy] [gx, gy] (([gx, gy], gen1, gen2), freshNames) function [gx, gy] [gy, gx] (let ([n,m], t) = FN.getNames 2 freshNames in (([inv [V n], inv [V m]], Subst.fromList $ (m, y) : (n, x) : gen1', Subst.fromList $ (m, x) : (n, y) : gen2'), t)) function [gxxy, gxyy, gx] [gxyy, gxxy, gy] (let ([n,m,p], t) = FN.getNames 3 freshNames in (( [inv [x, V n, y], inv [x, V m, y], inv [V p]] , Subst.fromList $ [(p, x), (m, y), (n, x)] ++ gen1' , Subst.fromList $ [(p, y), (m, x), (n, y)] ++ gen2') , t )) function [inv [x, c [x, y]], inv [c [z, z], c [x, x]]] [inv [c [x], c [x, z]], inv [c [z, z], y]] (let ([n,m,p], t) = FN.getNames 3 freshNames in (( [inv [V n, c [x, V m]], inv [c [z, z], V p]] , Subst.fromList $ [(p, c [x, x]), (m, y), (n, x)] ++ gen1' , Subst.fromList $ [(p, y), (m, z), (n, c [x])] ++ gen2') , t ))
kajigor/uKanren_transformations
test/auto/Test/Generalization.hs
bsd-3-clause
3,620
0
18
1,098
2,123
1,179
944
75
1
module Language.ImProve.Code.C (codeC) where import Data.List import Text.Printf import Language.ImProve.Code.Common import Language.ImProve.Core import Language.ImProve.Tree hiding (Branch) import qualified Language.ImProve.Tree as T -- | Generate C. codeC :: Name -> Statement -> IO () codeC name stmt = do writeFile (name ++ ".c") $ "/* Generated by ImProve. */\n\n" ++ "#include <assert.h>\n\n" ++ codeVariables True scope ++ "\n" ++ "void " ++ name ++ "(void)\n{\n" ++ indent (codeStmt name [] stmt) ++ "}\n\n" writeFile (name ++ ".h") $ "/* Generated by ImProve. */\n\n" ++ "#ifdef __cplusplus\n" ++ "extern \"C\" {\n" ++ "#endif\n\n" ++ codeVariables False scope ++ "\n" ++ "void " ++ name ++ "(void);\n\n" ++ "#ifdef __cplusplus\n" ++ "}\n" ++ "#endif\n" where scope = case tree (\ (_, path, _) -> path) $ stmtVars stmt of [] -> error "program contains no useful statements" a -> T.Branch (name ++ "_variables") a instance Show Statement where show = codeStmt "none" [] codeStmt :: Name -> [Name] -> Statement -> String codeStmt name path a = case a of Assign a b -> name ++ "_variables." ++ pathName a ++ " = " ++ codeExpr b ++ ";\n" Branch a b Null -> "if (" ++ codeExpr a ++ ") {\n" ++ indent (codeStmt name path b) ++ "}\n" Branch a b c -> "if (" ++ codeExpr a ++ ") {\n" ++ indent (codeStmt name path b) ++ "}\nelse {\n" ++ indent (codeStmt name path c) ++ "}\n" Sequence a b -> codeStmt name path a ++ codeStmt name path b Assert _ _ a -> "assert((" ++ show (pathName path) ++ ", " ++ codeExpr a ++ "));\n" Assume _ a -> "assert((" ++ show (pathName path) ++ ", " ++ codeExpr a ++ "));\n" Label name' a -> "/*" ++ name' ++ "*/\n" ++ indent (codeStmt name (path ++ [name']) a) Null -> "" where codeExpr :: E a -> String codeExpr a = case a of Ref a -> name ++ "_variables." ++ pathName a Const a -> showConst $ const' a Add a b -> group [codeExpr a, "+", codeExpr b] Sub a b -> group [codeExpr a, "-", codeExpr b] Mul a b -> group [codeExpr a, "*", showConst (const' b)] Div a b -> group [codeExpr a, "/", showConst (const' b)] Mod a b -> group [codeExpr a, "%", showConst (const' b)] Not a -> group ["!", codeExpr a] And a b -> group [codeExpr a, "&&", codeExpr b] Or a b -> group [codeExpr a, "||", codeExpr b] Eq a b -> group [codeExpr a, "==", codeExpr b] Lt a b -> group [codeExpr a, "<", codeExpr b] Gt a b -> group [codeExpr a, ">", codeExpr b] Le a b -> group [codeExpr a, "<=", codeExpr b] Ge a b -> group [codeExpr a, ">=", codeExpr b] Mux a b c -> group [codeExpr a, "?", codeExpr b, ":", codeExpr c] where group :: [String] -> String group a = "(" ++ intercalate " " a ++ ")" indent' :: String -> String indent' a = case lines a of [] -> [] (a:b) -> a ++ "\n" ++ indent (unlines b) codeVariables :: Bool -> (Tree Name (Bool, Path, Const)) -> String codeVariables define a = (if define then "" else "extern ") ++ init (init (f1 a)) ++ (if define then " =\n\t" ++ f2 a else "") ++ ";\n" where f1 a = case a of T.Branch name items -> "struct { /* " ++ name ++ " */\n" ++ indent (concatMap f1 items) ++ "} " ++ name ++ ";\n" Leaf name (input, _, init) -> printf "%-5s %-25s;%s\n" (showConstType init) name (if input then " /* input */" else "") f2 a = case a of T.Branch name items -> indent' $ "{ " ++ (intercalate ", " $ map f2 items) ++ "} /* " ++ name ++ " */\n" Leaf name (_, _, init) -> printf "%-15s /* %s */\n" (showConst init) name showConst :: Const -> String showConst a = case a of Bool True -> "1" Bool False -> "0" Int a -> show a Float a -> show a showConstType :: Const -> String showConstType a = case a of Bool _ -> "int" Int _ -> "int" Float _ -> "float"
tomahawkins/improve
Language/ImProve/Code/C.hs
bsd-3-clause
3,907
0
21
1,021
1,651
820
831
83
23
{-# LANGUAGE PostfixOperators, TypeFamilies #-} {-# OPTIONS_HADDOCK show-extensions, prune #-} ---------------------------------------------------------------------- -- | -- Module : ForSyDe.Atom.MoC -- Copyright : (c) George Ungureanu, 2015-2017 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ugeorge@kth.se -- Stability : experimental -- Portability : portable -- -- This module defines the Model of Computation (MoC) layer, and is concerned in -- modeling the timing aspects of CPS. Its formal foundation is the tagged signal -- model <ForSyDe-Atom.html#lee98 [Lee98]>, and it follows it as closely as it is -- permitted by the host language, and with the adaptations required by the atom -- approach. -- -- The MoC layer is defining a similar DSL as the classic -- <https://forsyde.github.io/forsyde-shallow/ ForSyDe> modeling framework, in the -- sense that systems are described in terms of /networks/ of /processes/ operating on -- /signals/, and processes are only allowed to be instantiated using a finite set of -- /process constructors/. Process constructors capture its computational semantics -- accodrding to its respective MoC. MoCs are classes of behaviors dictating the -- semantics of execution and concurrency in a network of processes. -- The MoCs currently implemented in ForSyDe-Atom are shown in the -- <#i:MoC instances section>, and they can be used in designs by -- importing their respective modules: -- -- * "ForSyDe.Atom.MoC.CT" -- * "ForSyDe.Atom.MoC.DE" -- * "ForSyDe.Atom.MoC.SY" -- * "ForSyDe.Atom.MoC.SDF" -- -- __The documentation in this module covers the internals of the MoC layer. While reading through is useful to understand some of the reasoning behind the modeling framework, this API is less likely to be touched by the casual user than the ones exported by each MoC above. For user-friendly modeling APIs consult the respective sub-modules.__ -- -- MoCs are determined by a a signal's tag system. Based on how their tag systems are -- defined ForSyDe identifies MoCs as: -- -- * /timed/ where the tag system is a totally ordered set and, depending on the -- abstraction level, \(t\in T\) might express a notion of physical time -- (e.g. continuous time 'ForSyDe.Atom.MoC.CT.CT', discrete event -- 'ForSyDe.Atom.MoC.DE.DE') to the notion of precedence and causality -- (e.g. synchronous 'ForSyDe.Atom.MoC.SY.SY'); -- -- * untimed, where T is a partially ordered set and \(t\in T\) is expressed in terms -- of constraints on the tags in signals (e.g. dataflow, synchronous data flow -- 'ForSyDe.Atom.MoC.SDF.SDF'). ---------------------------------------------------------------------- module ForSyDe.Atom.MoC( -- * Signals -- | <ForSyDe-Atom.html#lee98 [Lee98]> defines signals as ordered sets of events -- where each event is composed of a tag \(\in T\) and a value \(\in V\), where \(T\) -- defines a total or partial order. In ForSyDe a signal is defined as a sequence of -- events that enables processes to communicate and synchronize. Sequencing might -- infer an implicit total order of events, but more importantly it determines an -- order of evaluation, which is a key piece of a simulation engine. -- -- In ForSyDe, sequencing is achieved using a 'Stream' data type, similar to the one -- described by <ForSyDe-Atom.html#reekie95 [Reekie95]>. In ForSyDe-Atom, signals -- are streams that carry events, where each type of event is identified by a type -- constructor. Hence the pseudo-Haskell definition for a signal would look like -- below, where @e@ is the type of an event which encodes a tag system through its -- type constructor, and is member of the 'MoC' class. Since, according to -- <ForSyDe-Atom.html#lee98 [Lee98]>, MoCs are defined by tag systems, we can state -- that any specific instance of a signal is describing (i.e. is bound to) a MoC. -- -- > type Signal a = exists e . MoC e => Stream (e a) Stream (..), -- | This module re-exports all utilities on streams. These utilities are meant to -- be used with plotters or testbenches, but should never be used in designs under -- tests, as they do not carry formal semantics. module ForSyDe.Atom.MoC.Stream, -- * Atoms -- | These are primitive process constructors capturing an elementary behavior. By -- themselves they are seldom used as-such, but rather as specific compositions of -- atom patterns. For the MoC layer, atoms are defined only as type signatures, and -- are overloaded by each instance of the 'MoC' type class, as follows: MoC(..), -- * Patterns -- | The atom patterns of the MoC layer are the process constructors used in regular -- designs. Notice that these constructors themselves are "hollow" and carry no -- semantics unless the atoms are overloaded with a certain MoC, i.e. are applied on -- signals of a certain MoC. Most MoC sub-modules will provide more user-friendly -- versions of these patterns, thus these ones will seldomly be used as-such. We -- export them mainly for documentation purpose, to show that all MoCs share the -- same structure for their process constructors -- -- __IMPORTANT!!!__ see the <ForSyDe-Atom.html#naming_conv naming convention> rules -- on how to interpret, use and develop your own constructors. -- -- The documentation of each pattern is aided by a mathematical and a graphical -- notation following some conventions for brevity: -- -- * \(\mathcal{S}\) is used to denote a signal type (i.e. stream of events) -- -- * the power notation is used to denote multiple signals, curried if input -- \(s^m=s_1\ s_2\ ...\ s_m\); respectively tupled if output -- \(s^n=(s_1,s_2,...,s_n)\). Currying between outputs and inputs is implicit. -- -- * for improved readability we use the tupled mathematical notation for arguments. -- -- * a single line represents a signal, a double line represents multiple signals. delay, (-&>-), comb11, comb12, comb13, comb14, comb21, comb22, comb23, comb24, comb31, comb32, comb33, comb34, comb41, comb42, comb43, comb44, comb51, comb52, comb53, comb54, comb61, comb62, comb63, comb64, comb71, comb72, comb73, comb74, comb81, comb82, comb83, comb84, reconfig11, reconfig12, reconfig13, reconfig14, reconfig21, reconfig22, reconfig23, reconfig24, reconfig31, reconfig32, reconfig33, reconfig34, reconfig41, reconfig42, reconfig43, reconfig44, reconfig51, reconfig52, reconfig53, reconfig54, reconfig61, reconfig62, reconfig63, reconfig64, reconfig71, reconfig72, reconfig73, reconfig74, reconfig81, reconfig82, reconfig83, reconfig84, state11, state12, state13, state14, state21, state22, state23, state24, state31, state32, state33, state34, state41, state42, state43, state44, stated01, stated02, stated03, stated04, stated11, stated12, stated13, stated14, stated21, stated22, stated23, stated24, stated31, stated32, stated33, stated34, stated41, stated42, stated43, stated44, moore11, moore12, moore13, moore14, moore21, moore22, moore23, moore24, moore31, moore32, moore33, moore34, moore41, moore42, moore43, moore44, mealy11, mealy12, mealy13, mealy14, mealy21, mealy22, mealy23, mealy24, mealy31, mealy32, mealy33, mealy34, mealy41, mealy42, mealy43, mealy44, -- * Utilities ctxt11, ctxt21, ctxt31, ctxt41, ctxt51, ctxt61, ctxt71, ctxt81, ctxt12, ctxt22, ctxt32, ctxt42, ctxt52, ctxt62, ctxt72, ctxt82, ctxt13, ctxt23, ctxt33, ctxt43, ctxt53, ctxt63, ctxt73, ctxt83, ctxt14, ctxt24, ctxt34, ctxt44, ctxt54, ctxt64, ctxt74, ctxt84, warg, wres, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, (-*<), (-*<<), (-*<<<), (-*<<<<), (-*<<<<<), (-*<<<<<<), (-*<<<<<<<), (-*<<<<<<<<), ) where import ForSyDe.Atom.MoC.Stream import ForSyDe.Atom.Utility.Tuple ------------------------------------------------------- -- ATOMS -- ------------------------------------------------------- infixl 5 -.-, -*- infixl 3 -<-, -*, -&- -- | This is a type class defining interfaces for the MoC layer atoms. Each model of -- computation exposes its tag system through a unique event type which is an instance -- of this class, defining \( T \times V \). -- -- #context# To express all possible MoCs which can be described in this layer we need -- to capture the most general form of their atoms. Depending on the execution regime -- of a MoC, its atoms might or might not need additional parameters to determine the -- behavior for evaluating each argument. These additional parameters we call, in -- loose terms, as the /execution context/. -- -- [execution context] Additional information which, paired with a function, -- completely determines the behavior of a MoC atom (i.e. process). -- -- \[ -- \Gamma \vdash \alpha^m \rightarrow \beta^n \simeq \Gamma_{\alpha,1} \times \alpha_1 -- \rightarrow ... \rightarrow \Gamma_{\alpha,m} \times \alpha_m \rightarrow -- (\Gamma_{\beta,1}\times \beta_1) \times ... \times (\Gamma_{\beta,n}\times \beta_n) -- \] -- -- The left-hand side expression above shows the most general notation used to -- describe a function with /m/ inputs of (possibly different) types \(\alpha\) and -- /n/ outputs of (possibly different) types \(\beta\) executed in context -- \(\Gamma\). The right-hand side expression shows that in ForSyDe-Atom context is -- associated with each and every argument in order to enable the applicative -- mechanisms. Depending on the MoC, \(\Gamma_{\alpha,i}\) would translate to e.g.: -- -- \[ -- \Gamma_{\alpha,i} \in \begin{cases} -- \emptyset, & \text{for all timed MoCs (e.g. SY, DE, CT)} \\ -- \mathbb{N}, & \text{for static variants of SDF}\\ -- \mathbb{N}^n, & \text{for CSDF}\\ -- S \times \mathbb{N} \rightarrow \mathbb{N}, & \text{where } S \text{ is a state space,} \\ -- & \text{in the most general case of untimed data flow} -- \end{cases} -- \] -- -- One example of execution context is the consumption and production rates for -- synchronous data flow MoCs (e.g. 'ForSyDe.Atom.MoC.SDF.SDF'). In this case the -- passed functions are defined over /sequences/ or /partitions/ of events, -- i.e. groupings of events with the same partial order in relation to a process -- firing. -- -- Although a more elegant approach of passing execution context would be using -- type-level arithmetics, this is a non-trivial task to implement in Haskell. This is -- why we chose the pragmatic approach of /pairing/ a context parameter per argument, -- similar to the formula above, where: -- -- * any function representing a partition of \(\alpha\) is operating on a recursive -- type, namely a list \([\alpha]\). -- -- * to aid in pairing contexts with each argument in a function, the general purpose -- @ctxt@ utilities are provided (see 'ctxt22'). -- -- * this artifice is masked using the generic type families 'Fun' and 'Ret'. class (Applicative e) => MoC e where -- | This is a type family alias \(^1\) for a context-bound function passed as an -- argument to a MoC atom. It can be regarded as an enhanced @->@ type operator, -- specific to each MoC. -- -- \[ \Gamma_{\alpha,i} \times \alpha_i \rightarrow \beta \] -- -- /\(^1\) While hiding the explicit definition of arguments, this/ /implementation -- choice certainly has its advantages in avoiding/ /unnecessary or redundant type -- constructors (see version 0.1.1 and/ /prior). Aliases are replaced at compile -- time, thus not affecting/ /run-time performance./ type Fun e a b -- | Like 'Fun', this alias hides a context-bound value (e.g. function return). This -- alias is needed for utilities to extract clean context-free types (see '-*'). -- -- \[\Gamma_{\beta,i}\times \beta \] type Ret e b -- | The @func@ atom is mapping a function on values (in the presence of a context) -- to a signal, i.e. stream of tagged events. -- -- <<fig/eqs-moc-atom-dot.png>> (-.-) :: Fun e a b -> Stream (e a) -> Stream (e b) -- | The @sync@ atom synchronizes two signals, one carrying functions on values (in -- the presence of a context), and the other containing values. During the -- synchronization it applies the function(s) carried by the former signal on the -- values carried by the latter. This atom defines a /relation/ between two signals, -- and a process created with it is monotonous, i.e. any new event in any of the -- input signals triggers a reaction at the output. -- -- <<fig/eqs-moc-atom-star.png>> (-*-) :: Stream (e (Fun e a b)) -> Stream (e a) -> Stream (e b) -- | Artificial /utility/ which drops the context and/or partitioning yielding a -- clean signal type. -- -- <<fig/eqs-moc-atom-post.png>> (-*) :: Stream (e (Ret e b)) -> Stream (e b) -- | The @pre@ atom prepends the prefix of the left signal operand (i.e. the first -- event in timed MoCs, or the first /n/ events in untimed MoCs) at the beginning of -- the right signal operand \(^1\). This atom is necessary to ensure /complete -- partial order/ of a signal and assures the /least upper bound/ necessary for -- example in the evaluation of feedback loops <ForSyDe-Atom.html#lee98 [Lee98]>. -- -- <<fig/eqs-moc-atom-pre.png>> -- -- /\(^1\) this atom acts like the @pre@ operator in the synchronous language / -- /Lustre and for timed MoCs it behaves the same. For untimed MoCs though, the / -- /length of the prefix of a signal is assumed to be the length of a signal, / -- /since the API does not provide any other means to pass /n/ as a parameter./ (-<-) :: Stream (e a) -> Stream (e a) -> Stream (e a) -- | The @phi@ atom manipulates the tags in a signal in a restrictive way which -- preserves /monotonicity/ and /continuity/ in a process -- <ForSyDe-Atom.html#lee98 [Lee98]>, namely by “phase-shifting” all tags in a -- signal with the appropriate metric corresponding to each MoC. Thus it preserves -- the characteristic function intact <ForSyDe-Atom.html#sander04 [Sander04]>. -- -- <<fig/eqs-moc-atom-phi.png>> -- -- The metric distance used for phase shifting is inferred from the prefix of the -- left signal operand, while right signal operand is the one being manipulated. (-&-) :: Stream (e a) -> Stream (e a) -> Stream (e a) -------------------------------------------------------- -- PATTERNS -- -------------------------------------------------------- infixl 3 -&>- -- | <<fig/eqs-moc-pattern-delay.png>> -- <<fig/moc-pattern-delay.png>> -- -- The 'delay' process provides both initial token(s) and shifts the -- phase of the signal. In other words, it "delays" a signal with -- one or several events. delay i xs = i -<- (i -&- xs) -- | Infix variant for 'delay'. i -&>- xs = delay i xs -- | #comb22f# /(*) to be read/ @a1 -> a2 -> (b1, b2)@ /where each/ -- /argument may be <#context wrapped along with a context>./ -- -- <<fig/eqs-moc-pattern-comb.png>> -- <<fig/moc-pattern-comb.png>> -- -- The @comb@ processes synchronizes multiple input signals and maps -- combinatorial functions on the values they carry. -- -- This module exports constructors of type @comb[1-8][1-4]@. comb22 :: (MoC e) => (Fun e a1 (Fun e a2 (Ret e b1, Ret e b2))) -- ^ combinational function (<#comb22f *>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e b1), Stream (e b2)) -- ^ two output signals comb11 f s1 = (f -.- s1 -*) comb21 f s1 s2 = (f -.- s1 -*- s2 -*) comb31 f s1 s2 s3 = (f -.- s1 -*- s2 -*- s3 -*) comb41 f s1 s2 s3 s4 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*) comb51 f s1 s2 s3 s4 s5 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*) comb61 f s1 s2 s3 s4 s5 s6 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*) comb71 f s1 s2 s3 s4 s5 s6 s7 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*) comb81 f s1 s2 s3 s4 s5 s6 s7 s8 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*- s8 -*) comb12 f s1 = (f -.- s1 -*<) comb22 f s1 s2 = (f -.- s1 -*- s2 -*<) comb32 f s1 s2 s3 = (f -.- s1 -*- s2 -*- s3 -*<) comb42 f s1 s2 s3 s4 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*<) comb52 f s1 s2 s3 s4 s5 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<) comb62 f s1 s2 s3 s4 s5 s6 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<) comb72 f s1 s2 s3 s4 s5 s6 s7 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<) comb82 f s1 s2 s3 s4 s5 s6 s7 s8 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s5 -*- s8 -*<) comb13 f s1 = (f -.- s1 -*<<) comb23 f s1 s2 = (f -.- s1 -*- s2 -*<<) comb33 f s1 s2 s3 = (f -.- s1 -*- s2 -*- s3 -*<<) comb43 f s1 s2 s3 s4 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*<<) comb53 f s1 s2 s3 s4 s5 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<<) comb63 f s1 s2 s3 s4 s5 s6 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<<) comb73 f s1 s2 s3 s4 s5 s6 s7 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<<) comb83 f s1 s2 s3 s4 s5 s6 s7 s8 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s5 -*- s8 -*<<) comb14 f s1 = (f -.- s1 -*<<<) comb24 f s1 s2 = (f -.- s1 -*- s2 -*<<<) comb34 f s1 s2 s3 = (f -.- s1 -*- s2 -*- s3 -*<<<) comb44 f s1 s2 s3 s4 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*<<<) comb54 f s1 s2 s3 s4 s5 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<<<) comb64 f s1 s2 s3 s4 s5 s6 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<<<) comb74 f s1 s2 s3 s4 s5 s6 s7 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<<<) comb84 f s1 s2 s3 s4 s5 s6 s7 s8 = (f -.- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*- s8 -*<<<) -- | #reconfig22f# /(*) to be read / @a1 -> a2 -> (b1, b2)@ /where each/ -- /argument may be <#context wrapped along with a context>./ -- -- <<fig/eqs-moc-pattern-reconfig.png>> -- <<fig/moc-pattern-reconfig.png>> -- -- The @reconfig@ processes constructs adaptive processes, whose -- functional behavior "changes in time". Its first input is a signal -- carrying functions which is synchronized with all the other input -- signals. The output signal carry the results of mapping those -- functions at each synchronization/firing point. -- -- This library exports constructors of type @reconfig[1-8][1-4]@. reconfig22 :: (MoC e) => Stream (e (Fun e a1 (Fun e a2 (Ret e b1, Ret e b2)))) -- ^ signal carrying functions (<#reconfig22f *>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e b1), Stream (e b2)) -- ^ two output signals reconfig11 sf s1 = (sf -*- s1 -*) reconfig21 sf s1 s2 = (sf -*- s1 -*- s2 -*) reconfig31 sf s1 s2 s3 = (sf -*- s1 -*- s2 -*- s3 -*) reconfig41 sf s1 s2 s3 s4 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*) reconfig51 sf s1 s2 s3 s4 s5 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*) reconfig61 sf s1 s2 s3 s4 s5 s6 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*) reconfig71 sf s1 s2 s3 s4 s5 s6 s7 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*) reconfig81 sf s1 s2 s3 s4 s5 s6 s7 s8 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*- s8 -*) reconfig12 sf s1 = (sf -*- s1 -*<) reconfig22 sf s1 s2 = (sf -*- s1 -*- s2 -*<) reconfig32 sf s1 s2 s3 = (sf -*- s1 -*- s2 -*- s3 -*<) reconfig42 sf s1 s2 s3 s4 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*<) reconfig52 sf s1 s2 s3 s4 s5 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<) reconfig62 sf s1 s2 s3 s4 s5 s6 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<) reconfig72 sf s1 s2 s3 s4 s5 s6 s7 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<) reconfig82 sf s1 s2 s3 s4 s5 s6 s7 s8 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s5 -*- s8 -*<) reconfig13 sf s1 = (sf -*- s1 -*<<) reconfig23 sf s1 s2 = (sf -*- s1 -*- s2 -*<<) reconfig33 sf s1 s2 s3 = (sf -*- s1 -*- s2 -*- s3 -*<<) reconfig43 sf s1 s2 s3 s4 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*<<) reconfig53 sf s1 s2 s3 s4 s5 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<<) reconfig63 sf s1 s2 s3 s4 s5 s6 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<<) reconfig73 sf s1 s2 s3 s4 s5 s6 s7 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<<) reconfig83 sf s1 s2 s3 s4 s5 s6 s7 s8 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s5 -*- s8 -*<<) reconfig14 sf s1 = (sf -*- s1 -*<<<) reconfig24 sf s1 s2 = (sf -*- s1 -*- s2 -*<<<) reconfig34 sf s1 s2 s3 = (sf -*- s1 -*- s2 -*- s3 -*<<<) reconfig44 sf s1 s2 s3 s4 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*<<<) reconfig54 sf s1 s2 s3 s4 s5 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*<<<) reconfig64 sf s1 s2 s3 s4 s5 s6 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*<<<) reconfig74 sf s1 s2 s3 s4 s5 s6 s7 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*<<<) reconfig84 sf s1 s2 s3 s4 s5 s6 s7 s8 = (sf -*- s1 -*- s2 -*- s3 -*- s4 -*- s5 -*- s6 -*- s7 -*- s8 -*<<<) -- | #state22ns# /(*) meaning / @st1 -> st2 -> a1 -> a2 -> (st1,st2)@ -- /where each argument may be <#context wrapped along with a context>./ -- -- #state22i# /(**) inferred from the prefixes of the signals passed/ -- /as arguments. See the documentation for '-<-' for an explanation./ -- -- <<fig/eqs-moc-pattern-state.png>> -- <<fig/moc-pattern-state.png>> -- -- The @state@ processes generate process networks corresponding to a -- simple state machine with "un-latched" outputs like in the graph -- above. In other words, the process starts with a state transition -- and outputs the next state as the first event. -- -- This library exports constructors of type @state[1-4][1-4]@. state22 :: MoC e => Fun e st1 (Fun e st2 (Fun e a1 (Fun e a2 (Ret e st1, Ret e st2)))) -- ^ next state function (<#state22ns *>) -> (Stream (e st1), Stream (e st2)) -- ^ initial state(s) (<#state22i **>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e st1), Stream (e st2)) -- ^ output signals mirroring the next state(s). state11 ns i s1 = comb21 ns st s1 where st = i -&>- comb21 ns st s1 state21 ns i s1 s2 = comb31 ns st s1 s2 where st = i -&>- comb31 ns st s1 s2 state31 ns i s1 s2 s3 = comb41 ns st s1 s2 s3 where st = i -&>- comb41 ns st s1 s2 s3 state41 ns i s1 s2 s3 s4 = comb51 ns st s1 s2 s3 s4 where st = i -&>- comb51 ns st s1 s2 s3 s4 state12 ns (i1,i2) s1 = let (ns1,ns2) = comb32 ns st1 st2 s1 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (ns1,ns2) state22 ns (i1,i2) s1 s2 = let (ns1,ns2) = comb42 ns st1 st2 s1 s2 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (ns1,ns2) state32 ns (i1,i2) s1 s2 s3 = let (ns1,ns2) = comb52 ns st1 st2 s1 s2 s3 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (ns1,ns2) state42 ns (i1,i2) s1 s2 s3 s4 = let (ns1,ns2) = comb62 ns st1 st2 s1 s2 s3 s4 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (ns1,ns2) state13 ns (i1,i2,i3) s1 = let (ns1,ns2,ns3) = comb43 ns st1 st2 st3 s1 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (ns1,ns2,ns3) state23 ns (i1,i2,i3) s1 s2 = let (ns1,ns2,ns3) = comb53 ns st1 st2 st3 s1 s2 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (ns1,ns2,ns3) state33 ns (i1,i2,i3) s1 s2 s3 = let (ns1,ns2,ns3) = comb63 ns st1 st2 st3 s1 s2 s3 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (ns1,ns2,ns3) state43 ns (i1,i2,i3) s1 s2 s3 s4 = let (ns1,ns2,ns3) = comb73 ns st1 st2 st3 s1 s2 s3 s4 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (ns1,ns2,ns3) state14 ns (i1,i2,i3,i4) s1 = let (ns1,ns2,ns3,ns4) = comb54 ns st1 st2 st3 st4 s1 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (ns1,ns2,ns3,ns4) state24 ns (i1,i2,i3,i4) s1 s2 = let (ns1,ns2,ns3,ns4) = comb64 ns st1 st2 st3 st4 s1 s2 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (ns1,ns2,ns3,ns4) state34 ns (i1,i2,i3,i4) s1 s2 s3 = let (ns1,ns2,ns3,ns4) = comb74 ns st1 st2 st3 st4 s1 s2 s3 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (ns1,ns2,ns3,ns4) state44 ns (i1,i2,i3,i4) s1 s2 s3 s4 = let (ns1,ns2,ns3,ns4) = comb84 ns st1 st2 st3 st4 s1 s2 s3 s4 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (ns1,ns2,ns3,ns4) -- | -- #stated22ns# /(*) meaning / @st1 -> st2 -> a1 -> a2 -> (st1,st2)@ -- /where each argument may be <#context wrapped along with a context>./ -- -- #stated22i# /(**) inferred from the prefixes of the signals passed/ -- /as arguments. See the documentation for '-<-' for an explanation./ -- -- <<fig/eqs-moc-pattern-stated.png>> -- <<fig/moc-pattern-stated.png>> -- -- The @stated@ processes generate process networks corresponding to a -- simple state machine with "latched" outputs like in the graph -- above. As compared to 'state22', this process outputs the current -- state, and the state transition is observed from the second -- evaluation onwards. There exists a variant with 0 input signals, in -- which case the process is a signal generator. -- -- This library exports constructors of type @stated[0-4][1-4]@. stated22 :: MoC e => Fun e st1 (Fun e st2 (Fun e a1 (Fun e a2 (Ret e st1, Ret e st2)))) -- ^ next state function (<#stated22ns *>) -> (Stream (e st1), Stream (e st2)) -- ^ initial state(s) (<#stated22i **>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e st1), Stream (e st2)) -- ^ output signals mirroring the next state(s). stated01 ns i = st where st = i -&>- comb11 ns st stated11 ns i s1 = st where st = i -&>- comb21 ns st s1 stated21 ns i s1 s2 = st where st = i -&>- comb31 ns st s1 s2 stated31 ns i s1 s2 s3 = st where st = i -&>- comb41 ns st s1 s2 s3 stated41 ns i s1 s2 s3 s4 = st where st = i -&>- comb51 ns st s1 s2 s3 s4 stated02 ns (i1,i2) = let (ns1,ns2) = comb22 ns st1 st2 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (st1,st2) stated12 ns (i1,i2) s1 = let (ns1,ns2) = comb32 ns st1 st2 s1 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (st1,st2) stated22 ns (i1,i2) s1 s2 = let (ns1,ns2) = comb42 ns st1 st2 s1 s2 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (st1,st2) stated32 ns (i1,i2) s1 s2 s3 = let (ns1,ns2) = comb52 ns st1 st2 s1 s2 s3 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (st1,st2) stated42 ns (i1,i2) s1 s2 s3 s4 = let (ns1,ns2) = comb62 ns st1 st2 s1 s2 s3 s4 (st1,st2) = (i1 -&>- ns1, i2 -&>- ns2) in (st1,st2) stated03 ns (i1,i2,i3) = let (ns1,ns2,ns3) = comb33 ns st1 st2 st3 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (st1,st2,st3) stated13 ns (i1,i2,i3) s1 = let (ns1,ns2,ns3) = comb43 ns st1 st2 st3 s1 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (st1,st2,st3) stated23 ns (i1,i2,i3) s1 s2 = let (ns1,ns2,ns3) = comb53 ns st1 st2 st3 s1 s2 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (st1,st2,st3) stated33 ns (i1,i2,i3) s1 s2 s3 = let (ns1,ns2,ns3) = comb63 ns st1 st2 st3 s1 s2 s3 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (st1,st2,st3) stated43 ns (i1,i2,i3) s1 s2 s3 s4 = let (ns1,ns2,ns3) = comb73 ns st1 st2 st3 s1 s2 s3 s4 (st1,st2,st3) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3) in (st1,st2,st3) stated04 ns (i1,i2,i3,i4) = let (ns1,ns2,ns3,ns4) = comb44 ns st1 st2 st3 st4 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (st1,st2,st3,st4) stated14 ns (i1,i2,i3,i4) s1 = let (ns1,ns2,ns3,ns4) = comb54 ns st1 st2 st3 st4 s1 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (st1,st2,st3,st4) stated24 ns (i1,i2,i3,i4) s1 s2 = let (ns1,ns2,ns3,ns4) = comb64 ns st1 st2 st3 st4 s1 s2 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (st1,st2,st3,st4) stated34 ns (i1,i2,i3,i4) s1 s2 s3 = let (ns1,ns2,ns3,ns4) = comb74 ns st1 st2 st3 st4 s1 s2 s3 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (st1,st2,st3,st4) stated44 ns (i1,i2,i3,i4) s1 s2 s3 s4 = let (ns1,ns2,ns3,ns4) = comb84 ns st1 st2 st3 st4 s1 s2 s3 s4 (st1,st2,st3,st4) = (i1 -&>- ns1, i2 -&>- ns2, i3 -&>- ns3, i4 -&>- ns4) in (st1,st2,st3,st4) -- | #moore22ns# /(*) meaning / @st -> a1 -> a2 -> st @ /where each/ -- /argument may be <#context wrapped along with a context>./ -- -- #moore22od# /(**) meaning / @st -> (b1, b2) @ /where each argument/ -- /may be <#context wrapped along with a context>./ -- -- #moore22i# /(***) inferred from the prefixes of the signals passed/ -- /as arguments. See the documentation for '-<-' for an explanation./ -- -- <<fig/eqs-moc-pattern-moore.png>> -- <<fig/moc-pattern-moore.png>> -- -- The @moore@ processes model Moore state machines. -- -- This library exports constructors of type @moore[1-4][1-4]@. moore22 :: MoC e => Fun e st (Fun e a1 (Fun e a2 (Ret e st))) -- ^ next state function (<#moore22ns *>) -> Fun e st (Ret e b1, Ret e b2) -- ^ output decoder (<#moore22od **>) -> Stream (e st) -- ^ initial state (<#moore22i ***>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e b1), Stream (e b2)) -- ^ output signals moore11 ns od i s1 = comb11 od st where st = i -&>- comb21 ns st s1 moore12 ns od i s1 = comb12 od st where st = i -&>- comb21 ns st s1 moore13 ns od i s1 = comb13 od st where st = i -&>- comb21 ns st s1 moore14 ns od i s1 = comb14 od st where st = i -&>- comb21 ns st s1 moore21 ns od i s1 s2 = comb11 od st where st = i -&>- comb31 ns st s1 s2 moore22 ns od i s1 s2 = comb12 od st where st = i -&>- comb31 ns st s1 s2 moore23 ns od i s1 s2 = comb13 od st where st = i -&>- comb31 ns st s1 s2 moore24 ns od i s1 s2 = comb14 od st where st = i -&>- comb31 ns st s1 s2 moore31 ns od i s1 s2 s3 = comb11 od st where st = i -&>- comb41 ns st s1 s2 s3 moore32 ns od i s1 s2 s3 = comb12 od st where st = i -&>- comb41 ns st s1 s2 s3 moore33 ns od i s1 s2 s3 = comb13 od st where st = i -&>- comb41 ns st s1 s2 s3 moore34 ns od i s1 s2 s3 = comb14 od st where st = i -&>- comb41 ns st s1 s2 s3 moore41 ns od i s1 s2 s3 s4 = comb11 od st where st = i -&>- comb51 ns st s1 s2 s3 s4 moore42 ns od i s1 s2 s3 s4 = comb12 od st where st = i -&>- comb51 ns st s1 s2 s3 s4 moore43 ns od i s1 s2 s3 s4 = comb13 od st where st = i -&>- comb51 ns st s1 s2 s3 s4 moore44 ns od i s1 s2 s3 s4 = comb14 od st where st = i -&>- comb51 ns st s1 s2 s3 s4 -- | #mealy22ns# /(*) meaning / @st -> a1 -> a2 -> st @ /where each/ -- /argument may be <#context wrapped along with a context>./ -- -- #mealy22od# /(**) meaning / @st -> a1 -> a2 -> (b1, b2) @ /where/ -- /each argument may be <#context wrapped along with a context>./ -- -- #mealy22i# /(***) inferred from the prefixes of the signals passed/ -- /as arguments. See the documentation for '-<-' for an explanation./ -- -- <<fig/eqs-moc-pattern-mealy.png>> -- <<fig/moc-pattern-mealy.png>> -- -- The @mealy@ processes model Mealy state machines. -- -- This library exports constructors of type @mealy[1-4][1-4]@. mealy22 :: MoC e => Fun e st (Fun e a1 (Fun e a2 (Ret e st))) -- ^ next state function (<#mealy22ns *>) -> Fun e st (Fun e a1 (Fun e a2 (Ret e b1, Ret e b2))) -- ^ output decoder (<#mealy22od **>) -> Stream (e st) -- ^ initial state (<#mealy22i ***>) -> Stream (e a1) -- ^ first input signal -> Stream (e a2) -- ^ second input signal -> (Stream (e b1), Stream (e b2)) -- ^ output signals mealy11 ns od i s1 = comb21 od st s1 where st = i -&>- comb21 ns st s1 mealy12 ns od i s1 = comb22 od st s1 where st = i -&>- comb21 ns st s1 mealy13 ns od i s1 = comb23 od st s1 where st = i -&>- comb21 ns st s1 mealy14 ns od i s1 = comb24 od st s1 where st = i -&>- comb21 ns st s1 mealy21 ns od i s1 s2 = comb31 od st s1 s2 where st = i -&>- comb31 ns st s1 s2 mealy22 ns od i s1 s2 = comb32 od st s1 s2 where st = i -&>- comb31 ns st s1 s2 mealy23 ns od i s1 s2 = comb33 od st s1 s2 where st = i -&>- comb31 ns st s1 s2 mealy24 ns od i s1 s2 = comb34 od st s1 s2 where st = i -&>- comb31 ns st s1 s2 mealy31 ns od i s1 s2 s3 = comb41 od st s1 s2 s3 where st = i -&>- comb41 ns st s1 s2 s3 mealy32 ns od i s1 s2 s3 = comb42 od st s1 s2 s3 where st = i -&>- comb41 ns st s1 s2 s3 mealy33 ns od i s1 s2 s3 = comb43 od st s1 s2 s3 where st = i -&>- comb41 ns st s1 s2 s3 mealy34 ns od i s1 s2 s3 = comb44 od st s1 s2 s3 where st = i -&>- comb41 ns st s1 s2 s3 mealy41 ns od i s1 s2 s3 s4 = comb51 od st s1 s2 s3 s4 where st = i -&>- comb51 ns st s1 s2 s3 s4 mealy42 ns od i s1 s2 s3 s4 = comb52 od st s1 s2 s3 s4 where st = i -&>- comb51 ns st s1 s2 s3 s4 mealy43 ns od i s1 s2 s3 s4 = comb53 od st s1 s2 s3 s4 where st = i -&>- comb51 ns st s1 s2 s3 s4 mealy44 ns od i s1 s2 s3 s4 = comb54 od st s1 s2 s3 s4 where st = i -&>- comb51 ns st s1 s2 s3 s4 --------------------------------------------------------- -- UTILITIES -- --------------------------------------------------------- -- Attaches a context parameter to a function argument (e.g -- consumption rates in SDF). Used as kernel function in defining -- e.g. 'ctxt22'. warg :: c -> (a -> b) -> (c, a -> b) warg c f = (c, \x -> f x) -- Attaches a context parameter to a function's result (e.g -- production rates in SDF). Used as kernel function in defining -- e.g. 'ctxt22'. wres :: p -> b -> (p, b) wres p x = (p, x) -- | \[ -- \mathtt{ctxt} (\Gamma_{\alpha}, \Gamma_{\beta}, \alpha^m \rightarrow \beta^n) = \Gamma \vdash \alpha^m \rightarrow \beta^n -- \] -- -- Wraps a function with the <#context context> needed by some MoCs for their -- constructors (e.g. rates in SDF). -- -- This library exports wrappers of type @ctxt[1-8][1-4]@. ctxt22 :: (ctxa, ctxa) -- ^ argument contexts (e.g. consumption rates in SDF) -> (ctxb, ctxb) -- ^ result contexts (e.g. production rates in SDF) -> (a1 -> a2 -> (b1, b2)) -- ^ function on values/partitions of values -> (ctxa, a1 -> (ctxa, a2 -> ((ctxb, b1), (ctxb, b2)))) -- ^ context-wrapped form of the previous function ctxt11 (c1) p f = warg c1 $ wres p . f ctxt21 (c1,c2) p f = warg c1 $ ctxt11 c2 p . f ctxt31 (c1,c2,c3) p f = warg c1 $ ctxt21 (c2,c3) p . f ctxt41 (c1,c2,c3,c4) p f = warg c1 $ ctxt31 (c2,c3,c4) p . f ctxt51 (c1,c2,c3,c4,c5) p f = warg c1 $ ctxt41 (c2,c3,c4,c5) p . f ctxt61 (c1,c2,c3,c4,c5,c6) p f = warg c1 $ ctxt51 (c2,c3,c4,c5,c6) p . f ctxt71 (c1,c2,c3,c4,c5,c6,c7) p f = warg c1 $ ctxt61 (c2,c3,c4,c5,c6,c7) p . f ctxt81 (c1,c2,c3,c4,c5,c6,c7,c8) p f = warg c1 $ ctxt71 (c2,c3,c4,c5,c6,c7,c8) p . f ctxt12 (c1) (p1,p2) f = warg c1 $ ($$) (wres p1, wres p2) . f ctxt22 (c1,c2) ps f = warg c1 $ ctxt12 c2 ps . f ctxt32 (c1,c2,c3) ps f = warg c1 $ ctxt22 (c2,c3) ps . f ctxt42 (c1,c2,c3,c4) ps f = warg c1 $ ctxt32 (c2,c3,c4) ps . f ctxt52 (c1,c2,c3,c4,c5) ps f = warg c1 $ ctxt42 (c2,c3,c4,c5) ps . f ctxt62 (c1,c2,c3,c4,c5,c6) ps f = warg c1 $ ctxt52 (c2,c3,c4,c5,c6) ps . f ctxt72 (c1,c2,c3,c4,c5,c6,c7) ps f = warg c1 $ ctxt62 (c2,c3,c4,c5,c6,c7) ps . f ctxt82 (c1,c2,c3,c4,c5,c6,c7,c8) ps f = warg c1 $ ctxt72 (c2,c3,c4,c5,c6,c7,c8) ps . f ctxt13 (c1) (p1,p2,p3) f = warg c1 $ ($$$) (wres p1, wres p2, wres p3) . f ctxt23 (c1,c2) ps f = warg c1 $ ctxt13 c2 ps . f ctxt33 (c1,c2,c3) ps f = warg c1 $ ctxt23 (c2,c3) ps . f ctxt43 (c1,c2,c3,c4) ps f = warg c1 $ ctxt33 (c2,c3,c4) ps . f ctxt53 (c1,c2,c3,c4,c5) ps f = warg c1 $ ctxt43 (c2,c3,c4,c5) ps . f ctxt63 (c1,c2,c3,c4,c5,c6) ps f = warg c1 $ ctxt53 (c2,c3,c4,c5,c6) ps . f ctxt73 (c1,c2,c3,c4,c5,c6,c7) ps f = warg c1 $ ctxt63 (c2,c3,c4,c5,c6,c7) ps . f ctxt83 (c1,c2,c3,c4,c5,c6,c7,c8) ps f = warg c1 $ ctxt73 (c2,c3,c4,c5,c6,c7,c8) ps . f ctxt14 (c1) (p1,p2,p3,p4) f = warg c1 $ ($$$$) (wres p1, wres p2, wres p3, wres p4) . f ctxt24 (c1,c2) ps f = warg c1 $ ctxt14 c2 ps . f ctxt34 (c1,c2,c3) ps f = warg c1 $ ctxt24 (c2,c3) ps . f ctxt44 (c1,c2,c3,c4) ps f = warg c1 $ ctxt34 (c2,c3,c4) ps . f ctxt54 (c1,c2,c3,c4,c5) ps f = warg c1 $ ctxt44 (c2,c3,c4,c5) ps . f ctxt64 (c1,c2,c3,c4,c5,c6) ps f = warg c1 $ ctxt54 (c2,c3,c4,c5,c6) ps . f ctxt74 (c1,c2,c3,c4,c5,c6,c7) ps f = warg c1 $ ctxt64 (c2,c3,c4,c5,c6,c7) ps . f ctxt84 (c1,c2,c3,c4,c5,c6,c7,c8) ps f = warg c1 $ ctxt74 (c2,c3,c4,c5,c6,c7,c8) ps . f arg1 (c1) f = warg c1 $ f arg2 (c1,c2) f = warg c1 $ arg1 c2 . f arg3 (c1,c2,c3) f = warg c1 $ arg2 (c2,c3) . f arg4 (c1,c2,c3,c4) f = warg c1 $ arg3 (c2,c3,c4) . f arg5 (c1,c2,c3,c4,c5) f = warg c1 $ arg4 (c2,c3,c4,c5) . f arg6 (c1,c2,c3,c4,c5,c6) f = warg c1 $ arg5 (c2,c3,c4,c5,c6) . f arg7 (c1,c2,c3,c4,c5,c6,c7) f = warg c1 $ arg6 (c2,c3,c4,c5,c6,c7) . f arg8 (c1,c2,c3,c4,c5,c6,c7,c8) f = warg c1 $ arg7 (c2,c3,c4,c5,c6,c7,c8) . f infixl 3 -*<, -*<<, -*<<<, -*<<<<, -*<<<<<, -*<<<<<<, -*<<<<<<<, -*<<<<<<<< -- | Utilities for extending the '-*' atom for dealing with tupled -- outputs. This library exports operators of form @-*<[1-8]@. (-*<) :: MoC e => Stream (e (Ret e b1, Ret e b2)) -> (Stream (e b1), Stream (e b2)) (-*<) p = ((-*),(-*)) $$ (p ||<) (-*<<) p = ((-*),(-*),(-*)) $$$ (p ||<<) (-*<<<) p = ((-*),(-*),(-*),(-*)) $$$$ (p ||<<<) (-*<<<<) p = ((-*),(-*),(-*),(-*),(-*)) $$$$$ (p ||<<<<) (-*<<<<<) p = ((-*),(-*),(-*),(-*),(-*),(-*)) $$$$$$ (p ||<<<<<) (-*<<<<<<) p = ((-*),(-*),(-*),(-*),(-*),(-*),(-*)) $$$$$$$ (p ||<<<<<<) (-*<<<<<<<) p = ((-*),(-*),(-*),(-*),(-*),(-*),(-*),(-*)) $$$$$$$$ (p ||<<<<<<<) (-*<<<<<<<<) p = ((-*),(-*),(-*),(-*),(-*),(-*),(-*),(-*),(-*)) $$$$$$$$$ (p ||<<<<<<<<)
forsyde/forsyde-atom
src/ForSyDe/Atom/MoC.hs
bsd-3-clause
42,178
0
15
12,798
11,909
6,677
5,232
383
1
{-# LANGUAGE CPP #-} -- | Functions to work with the time value of money module Finance.TimeValue ( -- * Time value of money functions compound , compoundingFactor , discount , futureInterest -- * Utility functions -- TODO: Should they be moved somewhere else? , weightedAverage ) where #if __GLASGOW_HASKELL__ < 710 import Data.Foldable #endif import Data.Monoid -- | Calculate interest rate from spot price, future price and time period. futureInterest :: Floating a => a -> a -> a -> a futureInterest pv fv t = (fv / pv) ** (1 / t) - 1 compoundingFactor :: Floating a => a -> a -> a compoundingFactor r t = (1 + r) ** t compound :: Floating a => a -> a -> a -> a compound r t pv = pv * compoundingFactor r t discount :: Floating a => a -> a -> a -> a discount r t fv = fv / compoundingFactor r t -- | Weighted arithmetic mean with non-normalized weight weightedAverage :: (Floating a, Foldable f) => f (a, a) -> a weightedAverage xs = (getSum $ foldMap (\(w, x) -> Sum (w * x)) xs) / (getSum $ foldMap (\(w, _) -> Sum w) xs)
schernichkin/exchange
src/Finance/TimeValue.hs
bsd-3-clause
1,080
0
13
255
341
185
156
20
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Control.Monad.TreeWriter ( -- * The TreeWriter monad transformer TreeWriter, runTreeWriter, execTreeWriter, printTreeWriter, -- * TreeWriter operations leaf, node, ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Writer import Control.Monad.Trans.Class import Control.Arrow ( second ) import Data.Tree import Data.Monoid -- | @TreeWriter w@ is a specialized version of `WriterT` that outputs a -- @Forest w@. newtype TreeWriter w m a = TreeWriter (WriterT (DList (Tree w)) m a) deriving (Functor, Applicative, Monad, MonadPlus) instance MonadTrans (TreeWriter w) where lift = TreeWriter . lift runTreeWriter :: (Monad m) => TreeWriter w m a -> m (a, Forest w) runTreeWriter (TreeWriter m) = second fromDList `liftM` runWriterT m -- | Construct a `TreeWriter` computation from a @(result, output)@ pair. -- -- This is the inverse of `runTreeWriter`. treeWriter :: (Monad m) => (a, Tree w) -> TreeWriter w m a treeWriter (a, tw) = TreeWriter $ writer (a, single tw) -- | Extract the @Forest w@ output from a @TreeWriter w m a@. execTreeWriter :: (Monad m) => TreeWriter w m a -> m (Forest w) execTreeWriter = liftM snd . runTreeWriter -- | Run a @TreeWriter String m a@ computation, printing the resulting -- @Forest a@ to stdout using `drawForest`. printTreeWriter :: (MonadIO m) => TreeWriter String m a -> m a printTreeWriter m = do (a, w) <- runTreeWriter m liftIO . putStrLn $ drawForest w return a -- | @leaf w@ is a computation that outputs a node with label @w@ and no -- children. leaf :: (Monad m) => w -> TreeWriter w m () leaf w = treeWriter ((), Node w []) -- | @node w m@ is a computation that runs computation @m@ which produces -- the result @a@ and output @t@. It outputs a node with label @w@ and -- children @t@, and returns @a@ as its result. node :: (Monad m) => w -> TreeWriter w m a -> TreeWriter w m a node w (TreeWriter m) = TreeWriter $ censor (single . Node w . fromDList) m ------------------------------------------------------------------------------ -- DList -- | A simple difference list. newtype DList a = DList { runDList :: [a] -> [a] } instance Monoid (DList a) where mempty = toDList [] DList f `mappend` DList g = DList (f . g) -- | Convert a list to a DList. toDList :: [a] -> DList a toDList = DList . (++) -- | Convert a DList to a list. fromDList :: DList a -> [a] fromDList d = runDList d [] -- | A DList consisting of a single item. single :: a -> DList a single = toDList . (:[])
cdxr/tree-writer
Control/Monad/TreeWriter.hs
bsd-3-clause
2,625
0
11
525
709
389
320
46
1
module GibbsSampler (getPosteriorSampling, randomInitializer, zerosInitializer ) where import TNGraph import TNPrimitiveFunctions import System.Random import qualified Data.Map as M import TNTypes import TNParser import Data.Maybe import Debug.Trace -- **** GibbsSampler **** -- This file contains all the functions that utilize TNGraph -- to do image denoising. -- Y is the graph of unobserved, real image pixel values -- X is the graph of observed, noisy pixel values -- **** Types **** -- |In the case of an undirected graph, the Markov Blanket for a vertex -- is the set of all of its neighbors. type MarkovBlanket = ([TNVertexValue], TNVertexValue) -- |Return the Markov Blanket for a given vertex markovBlanket:: TNVertex -> TNGraph -> TNGraph -> MarkovBlanket markovBlanket vId yGraph xGraph = (yNeighborVals, fromJust $ xNeighborVal) where yNeighbors = getNeighbors yGraph vId yNeighborVals = map (\n -> fromJust $ getValue yGraph n) yNeighbors xNeighborVal = getValue xGraph vId -- **** Y graph initializers **** (which represents unobserved, real pixel values) -- Different initializations can ultimately yield different denoised image outputs -- |Return Y, initialized randomly randomInitializer:: TNGraph -> StdGen -> TNGraph randomInitializer xGraph randGen = TNGraph { table = t , graphType = gt, vertexValues = M.fromList newVals} where (TNGraph {table = t, graphType = gt, vertexValues = values}) = xGraph randVals = take (length $ vertices xGraph) (randoms (randGen) :: [Float]) newVals = zip (vertices xGraph) (map (\x -> if x < 0.5 then -1 else 1) randVals) -- |Return Y, a copy of X with all values initialized to zeros zerosInitializer:: TNGraph -> TNGraph zerosInitializer graph = TNGraph { table = t , graphType = gt, vertexValues = M.fromList newVals} where (TNGraph {table = t, graphType = gt, vertexValues = values}) = graph vs = vertices graph newZeroVals = map (\x -> 0) [1.. length(vs)] newVals = zip vs newZeroVals -- **** Sampling **** -- |Returns the probability that the vertex is black, -- givent vertex's Markov Blanket sampleProb:: MarkovBlanket -> Float sampleProb blanket = 1 / denominator where (nu, beta) = (1, 1) (yNeighbors, xNeighbor) = blanket first_sum = nu * (foldl (+) 0 yNeighbors) second_sum = beta * xNeighbor denominator = 1 + exp (-2 * first_sum - 2 * second_sum) -- |Samples the value for a vertex (either 1 or -1). -- It first estimates the probablity that the vertex is black using sample_prob, -- and checks if a randomly drawn decimal (0,1) falls within that probability. sample:: TNVertex -> TNGraph -> TNGraph -> StdGen -> (TNVertexValue, StdGen) sample vId yGraph xGraph randGen = if (randNum < prob) then (1,newRandGen) else (-1, newRandGen) where (yNeighbors, xNeighbor) = markovBlanket vId yGraph xGraph prob = sampleProb (markovBlanket vId yGraph xGraph) (randNum, newRandGen) = (random randGen :: (Float, StdGen)) --if (randNum < prob) then (1,newRandGen) else (-1, newRandGen) -- |Gathers the samples for all vertices in a graph. gatherSamples:: TNGraph -> TNGraph -> StdGen -> [TNVertex] -> [TNVertexValue] -> [TNVertexValue] gatherSamples yGraph xGraph randGen [] currResult = currResult gatherSamples yGraph xGraph randGen vsLeft currResult = gatherSamples yGraph xGraph newRandGen (tail vsLeft) newResult where currVertex = head vsLeft (sampleValue, newRandGen) = sample currVertex yGraph xGraph randGen newResult = currResult ++ [sampleValue] -- |Returns a Gibbs sample, given Y and X. gibbsSample:: TNGraph -> TNGraph -> StdGen -> TNGraph gibbsSample yGraph xGraph randGen = TNGraph {table = t, graphType = gt, vertexValues = sampleVertexVals} where newSampleVals = gatherSamples yGraph xGraph randGen (vertices yGraph) [] TNGraph {table = t, graphType = gt, vertexValues = newVals} = yGraph sampleVertexVals = M.fromList (zip (vertices yGraph) newSampleVals) -- |Adds a value to a graph's vertices addOnesFromSample:: TNGraph -> TVertexValueMap -> TNGraph addOnesFromSample prevCountsGraph newValues = addValuesToGraph prevCountsGraph ones where ones = M.map (\x -> if (x == 1) then 1 else 0) newValues -- |Get posterior probability for all vertices in Y getPosteriorSampling:: TNGraph -> TNGraph -> Int -> Int -> StdGen -> TNGraph getPosteriorSampling xGraph yGraph numSamples numBurns randGen = getPosteriorSamplingRecursive xGraph yGraph numSamples numBurns 0 (zerosInitializer xGraph) randGen -- |Recursive function to calculate Gibbs samples. It's tail recursive. getPosteriorSamplingRecursive:: TNGraph -> TNGraph -> Int -> Int -> Int -> TNGraph -> StdGen -> TNGraph getPosteriorSamplingRecursive xGraph yGraph numSamples numBurns itNum posterior randGen = do if (itNum >= numSamples) then divideGraphValuesBy posterior (fromIntegral numSamples) else getPosteriorSamplingRecursive xGraph newSample numSamples numBurns (itNum + 1) newPosterior newRandGen where (randNum, newRandGen) = (random randGen :: (Float, StdGen)) newSample = gibbsSample xGraph yGraph newRandGen TNGraph {table = samplet, graphType = gtsample, vertexValues = sampleVals} = newSample newPosterior = addOnesFromSample posterior sampleVals -- |Returns the TNVertex that lives at the given coordinates, given some graph dimensions coordinatesToVertexId:: (Int, Int) -> (Int, Int) -> Maybe TNVertex coordinatesToVertexId coordinates graphShape = if ((fst coordinates >= fst graphShape || fst coordinates < 0) || (snd coordinates >= snd graphShape || snd coordinates < 0)) then Nothing else Just $ (fst coordinates) * numVerticesPerLine + (snd coordinates) where numVerticesPerLine = (snd graphShape) -- |Returns the Coordinates for the given TNVertex, given some graph dimensions vertexIdToCoordinates:: TNVertex -> (Int, Int) -> Maybe (Int, Int) vertexIdToCoordinates vId graphShape = if (vId < 0 || vId >= (fst graphShape) * (snd graphShape)) then Nothing else Just $ (numLinesBefore, colNum) where numVerticesPerLine = (snd graphShape) numLinesBefore = div vId numVerticesPerLine numVerticesBefore = numLinesBefore * numVerticesPerLine colNum = vId - numVerticesBefore
astarostap/cs240h_final_project
src/GibbsSampler.hs
bsd-3-clause
6,191
42
13
1,044
1,581
873
708
89
2
module Facebook.Object.Marketing.Utility where import Data.Aeson import Data.Aeson.Types import Data.List import GHC.Generics import Data.ByteString import Data.Char import qualified Data.Aeson.Encode as AE (fromValue) import qualified Data.Text.Lazy as TL import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy.Builder as TLB import qualified Network.HTTP.Conduit as MPFD dropString :: String -> String -> String dropString pre s = case stripPrefix pre s of Nothing -> s Just dropped -> dropped dropOption pre = defaultOptions { fieldLabelModifier = dropString pre , omitNothingFields = True } parseJSONWithPrefix pre = genericParseJSON (dropOption pre) toJSONWithPrefix pre = genericToJSON (dropOption pre) toBS :: Value -> ByteString toBS = TE.encodeUtf8 . TL.toStrict . TLB.toLazyText . AE.fromValue data WithJSON a = WithJSON { withJsonValue :: Value, unWithJson :: a }deriving Show instance FromJSON a => FromJSON (WithJSON a) where parseJSON v = do x <- parseJSON v return $ WithJSON v x
BeautifulDestinations/fb
src/Facebook/Object/Marketing/Utility.hs
bsd-3-clause
1,074
0
9
199
306
174
132
29
2
-------------------------------------------------------------------------------- {-# LANGUAGE DoRec #-} -------------------------------------------------------------------------------- import Control.Applicative (pure, (<$>), (<*>), (<*)) import Control.Concurrent (threadDelay) import Control.Monad (forever, join) import System.Environment (getArgs) import System.Random -------------------------------------------------------------------------------- import FRP.Elerea.Simple import qualified FRP.Elerea.Network as Network -------------------------------------------------------------------------------- update :: Int -> [Int] -> [Int] update d xs | length xs > 5 = drop 1 xs ++ [d] | otherwise = xs ++ [d] -------------------------------------------------------------------------------- server :: IO () server = do gen <- newStdGen sampler <- start $ do deltas <- stateful 0 (+ 1) rec let rsum = update <$> deltas <*> rsum' rsum' <- delay [] rsum ssignals <- join $ execute $ Network.broadcastServer "0.0.0.0" 123456 (fmap const rsum) (fmap const $ fmap Just deltas) return $ (,) <$> rsum <*> ssignals forever $ do x <- sampler putStrLn $ "Server generated sample: " ++ show x threadDelay $ 1000 * 1000 -------------------------------------------------------------------------------- client :: IO () client = do sampler <- start $ join $ execute $ Network.broadcastClient "127.0.0.1" 123456 ([] :: [Int]) update forever $ do x <- sampler putStrLn $ "Client generated sample: " ++ show x threadDelay $ 1000 * 1000 -------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs case args of ("server" : _) -> server ("client" : _) -> client _ -> error "Specify either 'server' or 'client'"
tsurucapital/elerea-network
example.hs
bsd-3-clause
2,092
1
17
558
503
261
242
43
3
module Translations.HealthLog where import Data.Text (Text) import qualified Data.Text as T import I18N import App.HealthLog instance RenderMessage HealthLogError where defaultTranslator = renderHealthLogErrorEn renderHealthLogErrorEn :: HealthLogError -> Text renderHealthLogErrorEn (DatabaseError exc) = T.append "health log database failure: " (T.pack $ show exc) renderHealthLogErrorEn (HealthLogUnknown str) = T.append "Unknown health log error: " str
savannidgerinel/health
src/Translations/HealthLog.hs
bsd-3-clause
465
0
8
60
108
59
49
10
1
{-# LANGUAGE FlexibleContexts #-} module Text.Document.Parser.Wiki where import Control.Applicative hiding ((<|>)) import Data.List (intercalate) import Data.Maybe (isNothing, catMaybes) import Prelude hiding (lines) import Text.ParserCombinators.Parsec hiding (many, optional) import Text.Document.Core.Type import Text.Document.Plugin import Text.Document.PluginRegister import Text.Document.Parser.WikiHelper import Network.Protocol.Uri import Network.Protocol.Uri.Parser (pAbsoluteUri) import Misc.Commons -------[ document parsers ]---------------------------------------------------- pDocTitle = string "###" *> (text <$> pNonEmptyLine) <* many pEmptyLineEol pDocSubtitle = string "####" *> (text <$> pNonEmptyLine) <* many pEmptyLineEol pAbstract = string "**!" *> many pEmptyLineEol *> (snd <$> pParagraph 0) pAnnotate = char '@' *> ((,) <$> pString <*> (snd <$> pInline 0)) pDocument = document <$> pMaybe pDocTitle <*> pMaybe pDocSubtitle <*> many (try pAnnotate) <*> pMaybe (try pAbstract) <*> (maybe [] snd <$> pMaybe (pSections 0 False)) parseDocumentFile file = do f <- readFile file return $ (pDocument @! f) fromWiki :: String -> Either ParseError Document fromWiki t = parse pDocument "" (t ++ "\n") -------[ inline parsers ]------------------------------------------------------ -- TODO: refactor + generalize -- Several links types. pWebLink = (\a -> link (show a) External (text $ show a)) <$> pAbsoluteUri pReference = (\a f -> link a Reference (parseInline (f a))) <$> (string "[#" *> many (noneOf "|]")) <*> href <* char ']' where href = option id (const <$> (char '|' *> many (noneOf "]"))) pInternalLink = (\a f -> link (f a) Internal (text a)) <$> (char '[' *> many (noneOf "|]")) <*> href <* char ']' where href = option id (const <$> (char '|' *> many (noneOf "]"))) pImage = (\a f -> image a (f a)) <$> (char '{' *> many (noneOf "|}")) <*> href <* char '}' where href = option id (const <$> (char '|' *> many (noneOf "}"))) ----- pAbbreviations = choice $ map (\(a, b) -> text b <$ string a) [ (">>", "»") , ("<<", "«") , ("...", "…") , ("--", "―") ] pCustoms = try pWebLink <|> try pReference <|> try pInternalLink <|> try pImage <|> try pAbbreviations inlineTbl = [ ("*", "*", strong) , ("__", "__", footnote) , ("_", "_", emph) , ("==", "==", quote) , ("=", "=", fixed) , ("\0", "\0", id) ] -- tricky helper. explain pFragmentText sym = lines <$> f <$> many (Left <$> pCustoms <|> Right <$> noneOf sym) where f [] = [] f (Left l:xs) = l : f xs f xs = text (map (\(Right x) -> x) a) : f b where (a, b) = span right xs pFragment (s, e, sem) = (sem . lines) <$> (begin *> frags) where begin = try (string s) end = try (string e) sym = head s : map (\(_, b, _) -> head b) inlineTbl normal = pFragmentText sym more = (\a b c -> (text [a] <++> b) : c) <$> oneOf sym <*> normal <*> frags sub = (:) <$> pLines <*> frags frags = normal <**> option pure (pure <$ end <|> (flip(:)) <$> sub <|> (flip(:)) <$> more) pLines = choice $ map pFragment inlineTbl parseInline :: String -> Inline parseInline xs = either (text . show) id $ parse pLines "" ('\0' : xs ++ "\0") pInline :: Int -> GenParser Char st (Int, Inline) pInline n = fmap2 id (parseInline . trimText) <$> pText n -------[ structural parsers ]-------------------------------------------------- pSections :: Int -> Bool -> GenParser Char () (Int, SectionContents) pSections n forceTitle = do -- Based on the `forceTitle' flag we parse or try to parse a title. (n', title) <- (if forceTitle then id else option (n, Nothing)) (try $ pTitle n) -- Try to parse another section on level deeper OR another section on the -- same level, this section MUST have a title of its own (otherwise it is not -- a new section) OR a new block level element. items <- some $ choice [ (Left . snd) <$> pSections (n' + 1) (isNothing title) , (Right . snd) <$> pSections n' True , (Left . (:[]). Right . snd) <$> pBlock n' ] let -- Separate all sub-sections from block elements that are ours (sub, next) = partitionEither items -- Make this section. this = section title (concat sub) return (n', (Left this) : concat next) pTitle n = (,) <$> (pIndent' n <* string "***") <*> (Just . snd <$> pInline 0) -------[ block parsers ]------------------------------------------------------- -- Try to parse a single block level element. -- TODO: These try's should probably be on item indicator level. pBlock n = try (pPlugin n) <|> try (pInclude n) <|> try (pAnchor n) <|> try (pCaption n) <|> try (pMapping n) <|> try (pUnorderedList n) <|> try (pOrderedList n) <|> (pParagraph n) {- Collect all plugins from the global plugin register that claim can parser Wiki fragments. -} pluginParsers = catMaybes $ map (\p -> transformer p Wiki) pluginRegister pPlugin n = (,) n <$> plugin <$> choice (map (\a -> try $ a $ Just (ContextWiki n)) pluginParsers) <* many pEmptyLineEol pAnchor n = do n' <- pIndent' n string "#anchor " l <- pNonEmptyLine (_, b) <- pBlock n' return $ (n', anchor_ l b) pCaption n = do n' <- pIndent' n string "#caption " (_, i) <- pInline 0 (_, b) <- pBlock n' return $ (n', caption i b) pInclude n = do n' <- pIndent' n i <- pInclude' many pEmptyLineEol return $ (n', i) pInclude' = (\a f -> include (f a)) <$> (string "[*" *> many (noneOf "|]")) <*> href <* char ']' where href = option id (const <$> (char '|' *> many (noneOf "]"))) pParagraph n = fmap2 id paragraph <$> pInline n -- List parsers. pMapping = pList mapping (pMapItem "--" "->") pUnorderedList = pList list (pListItem "-") pOrderedList = pList enum (pListItem "+") pList sem item n = do (n', x) <- item n xs <- map snd <$> many (try $ item n') return (n', sem (x:xs)) pListItem c n = do n' <- pIndent' n i <- string c *> ((\a b -> blocks (a : b)) <$> (snd <$> pBlock 0) <*> (map snd <$> many (pBlock (n'+1)))) return (n', i) pMapItem c0 c1 n = do (n', a) <- pListItem c0 n (_, b) <- pListItem c1 n return (n', (a, b))
sebastiaanvisser/orchid-doc
src/Text/Document/Parser/Wiki.hs
bsd-3-clause
6,372
0
17
1,541
2,496
1,295
1,201
147
3
{-# LANGUAGE Safe, TypeOperators, ScopedTypeVariables, PolyKinds, RankNTypes, TypeFamilies, MultiParamTypeClasses #-} module Type.BST.Item ( -- * Item Item(Item, value), type (|>) , With , newkey, item, (|>) ) where import Type.BST.Proxy import Type.BST.Showtype -- | 'Item' used in 'BST'. newtype Item key a = Item {value :: a} -- | When @x@ has a type @T@, -- @('Item' :: 'With' key) x@ works as @'Item' x :: 'Item' key T@. -- -- Using 'With', you can avoid writing @T@. type With key = forall a. a -> Item key a -- | Infix synonym for 'Item'. type (|>) = Item instance (Showtype key, Show a) => Show (Item key a) where showsPrec p (Item x) = showParen (p > 10) $ (\s -> "<" ++ showtype (Proxy :: Proxy key) ++ "> " ++ s) . showsPrec 11 x -- | Give a new key to an 'Item'. newkey :: Item key a -> proxy key' -> Item key' a newkey (Item x) _ = Item x {-# INLINE newkey #-} -- | Make an 'Item' setting a key with @proxy@. item :: proxy key -> a -> Item key a item _ = Item {-# INLINE item #-} -- | Infix synonym for 'item'. (|>) :: proxy key -> a -> Item key a (|>) = item {-# INLINE (|>) #-} infixr 6 |>
Kinokkory/type-level-bst
src/Type/BST/Item.hs
bsd-3-clause
1,192
0
15
311
320
186
134
-1
-1
{-# LANGUAGE OverloadedStrings, FlexibleContexts, DeriveDataTypeable, ScopedTypeVariables #-} module Network.FTP.Commands where {-| Implement all ftp commands in FTP Monad. -} import qualified Prelude as P import BasicPrelude import Control.Monad.Trans.State (get, gets, put, modify) import Control.Exception (throw) import qualified Control.Exception.Lifted as Lifted import qualified Data.ByteString.Char8 as S import qualified Data.CaseInsensitive as CI import Data.Typeable (Typeable) import Data.Maybe (isJust) import Data.Conduit ( ($$) ) import Data.Conduit.Network (Application, sinkSocket, sourceSocket, appSource, appSink) import Data.Conduit.Network.Internal (AppData(..)) import Network.FTP.Monad import qualified Network.FTP.Socket as NS import Network.FTP.Backend (FTPBackend(..)) import Network.FTP.Utils (encode, decode) type Command m = ByteString -> FTP m () data ApplicationQuit = ApplicationQuit deriving (Show, Typeable) instance Exception ApplicationQuit {- - check auth state before run command. -} login_required :: FTPBackend m => Command m -> Command m login_required cmd arg = do b <- isJust <$> FTP (gets ftpUser) if b then cmd arg else reply "530" "Command not possible in non-authenticated state." cmd_user :: FTPBackend m => Command m cmd_user name = do b <- isJust <$> FTP (gets ftpUser) if b then reply "530" "Command not possible in authenticated state." else do reply "331" "User name accepted; send password." pass <- wait (expect "PASS") muser <- lift (authenticate name pass) FTP $ modify $ \st -> st { ftpUser = muser } if isJust muser then reply "230" "login successful." else reply "530" "incorrect password." cmd_cwd, cmd_cdup, cmd_pwd :: FTPBackend m => Command m cmd_cwd dir = do cwd (decode dir) dir' <- pwd reply "250" $ "New directory now " ++ encode dir' cmd_cdup _ = cmd_cwd ".." cmd_pwd _ = do d <- pwd reply "257" $ "\"" ++ encode d ++ "\" is the current working directory." cmd_type :: FTPBackend m => Command m cmd_type tp = do let modType newtp = do st <- FTP get reply "200" $ S.pack $ "Type changed from " ++ P.show (ftpDataType st) ++ " to " ++ P.show newtp FTP $ put st{ ftpDataType = newtp } case tp of "I" -> modType Binary "L 8" -> modType Binary "A" -> modType ASCII "AN" -> modType ASCII "AT" -> modType ASCII _ -> reply "504" $ "Type \"" ++ tp ++ "\" not supported." cmd_pasv :: FTPBackend m => Command m cmd_pasv _ = do local <- FTP (gets ftpLocal) sock <- liftIO $ NS.startPasvServer local FTP $ modify $ \st -> st { ftpChannel = PasvChannel sock } portstr <- liftIO $ NS.getSocketName sock >>= NS.toPortString reply "227" $ S.pack $ "Entering passive mode (" ++ portstr ++ ")" cmd_port :: FTPBackend m => Command m cmd_port port = do local <- FTP (gets ftpLocal) addr <- liftIO $ NS.fromPortString (S.unpack port) case validate local addr of Right _ -> doit addr Left err -> reply "501" err where validate (NS.SockAddrInet _ h1) (NS.SockAddrInet _ h2) = if h1==h2 then Right () else Left "Will only connect to same client as command channel." validate (NS.SockAddrInet _ _) _ = Left "Require IPv4 in specified address" validate _ _ = Left "Require IPv4 on client" doit addr = do FTP $ modify $ \st -> st { ftpChannel = PortChannel addr } reply "200" $ S.pack $ "OK, later I will connect to " ++ P.show addr runTransfer :: FTPBackend m => Application m -> FTP m () runTransfer app = do reply "150" "I'm going to open the data channel now." chan <- FTP (gets ftpChannel) FTP $ modify $ \st -> st{ ftpChannel = NoChannel } case chan of NoChannel -> fail "Can't connect when no data channel exists" PasvChannel sock -> Lifted.finally (do (csock, addr) <- liftIO $ NS.accept sock lift $ Lifted.finally (app AppData { appSource = sourceSocket csock , appSink = sinkSocket csock , appSockAddr = addr , appLocalAddr = Nothing }) (liftIO (NS.sClose csock)) ) (liftIO (NS.sClose sock)) PortChannel addr -> do sock <- liftIO $ do proto <- NS.getProtocolNumber "tcp" sock <- NS.socket NS.AF_INET NS.Stream proto NS.connect sock addr return sock lift $ Lifted.finally (app AppData { appSource = sourceSocket sock , appSink = sinkSocket sock , appSockAddr = addr , appLocalAddr = Nothing }) (liftIO (NS.sClose sock)) reply "226" "Closing data connection; transfer complete." cmd_list :: FTPBackend m => Command m cmd_list dir = do dir' <- ftpAbsolute (decode dir) runTransfer $ \ad -> list dir' $$ (appSink ad) cmd_nlst :: FTPBackend m => Command m cmd_nlst dir = do dir' <- ftpAbsolute (decode dir) runTransfer $ \ad -> nlst dir' $$ (appSink ad) cmd_noop :: FTPBackend m => Command m cmd_noop _ = reply "200" "OK" cmd_dele :: FTPBackend m => Command m cmd_dele "" = reply "501" "Filename required" cmd_dele name = do ftpAbsolute (decode name) >>= lift . dele reply "250" $ "File " ++ name ++ " deleted." cmd_retr :: FTPBackend m => Command m cmd_retr "" = reply "501" "Filename required" cmd_retr name = do name' <- ftpAbsolute (decode name) runTransfer $ \ad -> download name' $$ (appSink ad) cmd_stor :: FTPBackend m => Command m cmd_stor "" = reply "501" "Filename required" cmd_stor name = do name' <- ftpAbsolute (decode name) runTransfer $ \ad -> (appSource ad) $$ upload name' cmd_syst :: FTPBackend m => Command m cmd_syst _ = reply "215" "UNIX Type: L8" cmd_mkd :: FTPBackend m => Command m cmd_mkd "" = reply "501" "Directory name required" cmd_mkd dir = do dir' <- ftpAbsolute (decode dir) lift $ mkd dir' reply "257" $ "\"" ++ encode dir' ++ "\" created." cmd_rnfr, cmd_rnto :: FTPBackend m => Command m cmd_rnfr "" = reply "501" "Filename required" cmd_rnfr name = do FTP $ modify $ \st -> st { ftpRename = Just (decode name) } reply "350" $ "Noted rename from "++name++"; please send RNTO." cmd_rnto "" = reply "501" "Filename required" cmd_rnto name = do mfromname <- FTP (gets ftpRename) case mfromname of Nothing -> reply "503" "RNFR required before RNTO" Just fromname -> do FTP $ modify $ \st -> st { ftpRename = Nothing } fname <- ftpAbsolute fromname tname <- ftpAbsolute (decode name) lift (rename fname tname) reply "250" $ "File "++encode fromname++" renamed to "++name cmd_rmd :: FTPBackend m => Command m cmd_rmd "" = reply "501" "Filename required" cmd_rmd dir = do ftpAbsolute (decode dir) >>= lift . rmd reply "250" $ "Directory " ++ dir ++ " removed." cmd_stat :: FTPBackend m => Command m cmd_stat _ = do st <- FTP get reply "211" $ S.pack $ P.unlines [" *** Sever statistics and information" ," *** Please type HELP for more details" ,"" ,"Server Software : haskell-ftp, https://github.com/yihuang/haskell-ftp" ,"Connected From : ", P.show (ftpRemote st) ,"Connected To : ", P.show (ftpLocal st) ,"Data Transfer Type : ", P.show (ftpDataType st) ,"Auth Status : ", P.show (ftpUser st) ,"End of status." ] cmd_mode, cmd_stru :: FTPBackend m => Command m cmd_mode m = case m of "S" -> reply "200" "Mode is Stream." _ -> reply "504" $ "Mode \"" ++ m ++ "\" not supported." cmd_stru s = case s of "F" -> reply "200" "Structure is File." _ -> reply "504" $ "Structure \"" ++ s ++ "\" not supported." commands :: FTPBackend m => [(CI.CI ByteString, Command m)] commands = [("USER", cmd_user) ,("PASS", const $ reply "530" "Out of sequence PASS command") ,("QUIT", const $ reply "221" "OK, Goodbye." >> throw ApplicationQuit) --,(Command "HELP" (help, help_help)) ,("CWD", login_required cmd_cwd) ,("PWD", login_required cmd_pwd) ,("CDUP", login_required cmd_cdup) ,("PASV", login_required cmd_pasv) ,("PORT", login_required cmd_port) ,("LIST", login_required cmd_list) ,("TYPE", login_required cmd_type) ,("MKD", login_required cmd_mkd) ,("NOOP", login_required cmd_noop) ,("RNFR", login_required cmd_rnfr) ,("RNTO", login_required cmd_rnto) ,("DELE", login_required cmd_dele) ,("RMD", login_required cmd_rmd) ,("RETR", login_required cmd_retr) ,("STOR", login_required cmd_stor) ,("STAT", login_required cmd_stat) ,("SYST", login_required cmd_syst) ,("NLST", login_required cmd_nlst) ,("MODE", login_required cmd_mode) ,("STRU", login_required cmd_stru) ] commandLoop :: FTPBackend m => FTP m () commandLoop = do (cmd, arg) <- wait getCommand lift (ftplog $ CI.original cmd++" "++arg) case lookup cmd commands of Just cmd' -> do continue <- (cmd' arg >> return True) `Lifted.catch` (\(_::ApplicationQuit) -> return False) `Lifted.catch` (\(ex::SomeException) -> do reply "502" (S.pack $ P.show ex) return True ) when continue commandLoop Nothing -> do reply "502" $ "Unrecognized command " ++ CI.original cmd commandLoop
yihuang/haskell-ftp
Network/FTP/Commands.hs
bsd-3-clause
10,197
0
22
3,148
3,082
1,534
1,548
237
6
{-| Module : Util Description : Lib's utils module This is a haddock comment describing your library For more information on how to write Haddock comments check the user guide: <https://www.haskell.org/haddock/doc/html/index.html> -} module Util where import Control.Concurrent.STM import qualified Control.Exception as E import Control.Lens import Control.Monad import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as LBS import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Network.HTTP.Client import Network.Wreq -- import qualified Network.Wreq as W import System.Environment import Types import Web.Slack slackUser :: UserId -> Text slackUser (Id uid) = T.concat ["<@", uid, ">"] slackSimpleQuote :: Text -> Text slackSimpleQuote txt = T.concat ["`", txt, "`"] envFail :: String -> IO String envFail var = envDefault (error var ++ " not set") var envWarn :: String -> IO String envWarn var = do getVar <- lookupEnv var unless (isJust getVar) $ print failureStr pure $ fromMaybe failureStr getVar where failureStr = var ++ " not set" envMaybe :: String -> IO (Maybe String) envMaybe = lookupEnv envGuard :: String -> IO String envGuard var = do getVar <- lookupEnv var guard $ isJust getVar pure $ fromJust getVar envDefault :: String -> String -> IO String envDefault def var = fromMaybe def <$> lookupEnv var safeGetUrl :: Text -> Maybe Text -> Maybe Text -> IO (Either Text (Response LBS.ByteString)) safeGetUrl url (Just login) (Just pass) = do let opts = defaults & auth ?~ basicAuth (BSC.pack $ T.unpack login) (BSC.pack $ T.unpack pass) -- & W.checkStatus .~ (Just $ \_ _ _ -> Nothing) (Right <$> getWith opts (T.unpack url)) `E.catch` handler where handler :: HttpException -> IO (Either Text (Response LBS.ByteString)) handler _ = pure $ Left $ T.pack "Error fetching HTTP data." -- handler (StatusCodeException s _ _) = do -- pure $ Left $ BSC.unpack (s ^. statusMessage) safeGetUrl _ _ _ = pure $ Left $ T.pack "Error: Invalid invocation." slackWriter :: OutputResponse -> OutputMessage -> IO () slackWriter resp msg = atomically $ writeTChan (outputChannel resp) resp { message = msg }
wamaral/slaskellbot
src/Util.hs
bsd-3-clause
2,381
0
15
559
656
341
315
45
1
{-# LANGUAGE OverloadedStrings #-} module Config where import Control.Applicative (empty, (<$>), (<*>)) import qualified Data.Aeson as AE import qualified Data.ByteString.Lazy.Char8 as BL import Data.Default import Data.Text (Text()) import System.Directory (doesFileExist) data AojConf = AojConf { user :: String, pass :: String } deriving (Eq, Show) data Configuration = Configuration { port :: Int, aoj :: AojConf, db :: Text } deriving (Eq, Show) instance Default Configuration where def = Configuration { port = 16384, aoj = AojConf "" "", db = "db.sqlite" } instance AE.ToJSON AojConf where toJSON (AojConf user' pass') = AE.object ["user" AE..= user', "pass" AE..= pass'] instance AE.ToJSON Configuration where toJSON (Configuration port' aoj' db') = AE.object ["port" AE..= port', "aoj" AE..= aoj', "db" AE..= db'] instance AE.FromJSON AojConf where parseJSON (AE.Object v) = AojConf <$> v AE..: "user" <*> v AE..: "pass" parseJSON _ = empty instance AE.FromJSON Configuration where parseJSON (AE.Object v) = Configuration <$> v AE..: "port" <*> v AE..: "aoj" <*> v AE..: "db" parseJSON _ = empty loadConfig :: FilePath -> IO (Maybe Configuration) loadConfig filepath = do existp <- doesFileExist filepath if existp then loadConfig' filepath else return Nothing where loadConfig' fp = do content <- BL.readFile fp return $ AE.decode content
asi1024/WXCS
src/Config.hs
mit
1,579
0
11
431
493
268
225
46
2
{-# LANGUAGE DeriveFunctor, RankNTypes #-} module Control.Lens.Getter where import Control.Monad.State.Class import Control.Monad.Reader.Class import Control.Applicative import Unsafe.Coerce import Data.Monoid import Data.Foldable infixl 8 ^. type Getting r s a = (a -> Accessor r a) -> s -> Accessor r s type Getter s a = forall r. Getting r s a folded :: (Foldable f, Monoid r) => Getting r (f a) a folded ar = unsafeCoerce `asTypeOf` (Accessor .) $ foldMap (unsafeCoerce `asTypeOf` (runAccessor .) $ ar) views :: MonadReader s m => Getting r s a -> (a -> r) -> m r views = asks unsafeCoerce {-# INLINE views #-} view :: MonadReader s m => Getting a s a -> m a view l = views l id {-# INLINE view #-} foldMapOf :: Getting r s a -> (a -> r) -> s -> r foldMapOf = unsafeCoerce {-# INLINE foldMapOf #-} foldOf :: Getting a s a -> s -> a foldOf l = foldMapOf l id {-# INLINE foldOf #-} to :: (s -> a) -> Getter s a to f = \ar -> unsafeCoerce (ar . f) {-# INLINE to #-} (^.) :: s -> Getting a s a -> a (^.) = flip foldOf {-# INLINE (^.) #-} ---- uses :: MonadState s m => Getter s a -> (a -> r) -> m r uses g f = get >>= foldMapOf g (return . f) {-# INLINE uses #-} use :: MonadState s m => Getter s a -> m a use g = uses g id {-# INLINE use #-} ---- newtype Accessor r a = Accessor { runAccessor :: r } deriving (Show, Read, Eq, Ord, Functor) instance Monoid r => Applicative (Accessor r) where pure _ = Accessor mempty {-# INLINE pure #-} Accessor a <*> Accessor b = Accessor (mappend a b) {-# INLINE (<*>) #-}
zerobuzz/reasonable-lens
src/Control/Lens/Getter.hs
mit
1,537
0
10
337
621
333
288
45
1
module Simple where empty [] = 1 emty xs = 0 main = 2 +. 4
roberth/uu-helium
docs/wiki-material/Simple4.hs
gpl-3.0
66
0
6
23
31
17
14
4
1
{-# LANGUAGE CPP #-} -- Copyright (c) 2010, Diego Souza -- 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 <ORGANIZATION> 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. module Test.Yql.UI.CLI.Commands.SetEnv where #define eq assertEqual (__FILE__ ++":"++ show __LINE__) #define ok assertBool (__FILE__ ++":"++ show __LINE__) import Network.OAuth.Consumer import Yql.Core.Backend import Yql.UI.CLI.Command import qualified Yql.UI.CLI.Commands.SetEnv as E import Data.List import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit (assertBool, assertEqual) newtype MyBackend = MyBackend [String] deriving (Eq,Show) instance Yql MyBackend where endpoint = const ("query.yahooapis.com",80) credentials = const $ const $ return () app = const $ Application "iyql" "" OOB setenv (MyBackend es) e = MyBackend (e:es) unsetenv (MyBackend es) e = MyBackend (delete e es) getenv (MyBackend es) = es test0 = testCase "setenv with leading + appends" $ do output <- bin (E.setenv (MyBackend ["foo","bar"])) "" ["+foobar"] eq (Right $ MyBackend ["foobar","foo","bar"]) output test1 = testCase "setenv with leading - deletes" $ do output <- bin (E.setenv (MyBackend ["foobar","foo","bar"])) "" ["-foobar"] eq (Right $ MyBackend ["foo","bar"]) output test2 = testCase "setenv without +/- define" $ do output <- bin (E.setenv (MyBackend ["foo","bar"])) "" ["foobar"] eq (Right $ MyBackend ["foobar"]) output test3 = testCase "setenv without args dump" $ do output <- bin (E.setenv (MyBackend ["foo","bar"])) "" [] eq (Left $ unlines ["foo","bar"]) output suite :: [Test] suite = [ testGroup "Commands/SetEnv.hs" [ test0 , test1 , test2 , test3 ] ]
dgvncsz0f/iyql
src/test/haskell/Test/Yql/UI/CLI/Commands/SetEnv.hs
gpl-3.0
3,377
0
14
782
570
321
249
36
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Program : sliders.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:47 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Main where import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui import Qtc.Enums.Base import Qtc.Enums.Classes.Core import Qtc.Core.Base import Qtc.Enums.Core.Qt import Qtc.Core.QCoreApplication import Qtc.Gui.Base import Qtc.Gui.QApplication import Qtc.Gui.QWidget import Qtc.Gui.QLayout import Qtc.Gui.QBoxLayout import Qtc.Gui.QVBoxLayout import Qtc.Gui.QGridLayout import Qtc.Gui.QPushButton import Qtc.Gui.QFont import Qtc.Enums.Gui.QFont import Qtc.Gui.QAbstractSlider import Qtc.Gui.QSlider import Qtc.Enums.Gui.QLCDNumber import Qtc.Gui.QLCDNumber import Qtc.Enums.Gui.QLCDNumber type MyQWidget = QWidgetSc (CMyQWidget) data CMyQWidget = CMyQWidget myQWidget :: IO (MyQWidget) myQWidget = qSubClass $ qWidget () type LCDRange = QWidgetSc (CLCDRange) data CLCDRange = CLCDRange lCDRange :: IO (LCDRange) lCDRange = qSubClass $ qWidget () data LcdRange_object = LcdR_o LCDRange (QSlider ()) lcdrange :: LcdRange_object -> LCDRange lcdrange (LcdR_o x _) = x slider :: LcdRange_object -> QSlider () slider (LcdR_o _ x) = x main :: IO () main = do app <- qApplication () widget <- myQWidget quit <- qPushButton "Quit" font <- qFont ("Times", 18::Int, qEnum_toInt (eBold::Weight), False) setFont widget font connectSlot quit "clicked()" app "quit()" () grid <- qGridLayout () create_rows grid layout <- qVBoxLayout () addWidget layout quit addLayout layout grid setLayout widget layout setWindowTitle widget "Sliders" qshow widget () ok <- qApplicationExec () return () create_rows g = create_rows_s g 0 Nothing create_rows_s :: QGridLayout () -> Int -> Maybe LcdRange_object -> IO () create_rows_s _ _rc _ | _rc >= 3 = return () create_rows_s _qlt _rc _prev = do prev <- create_columns _qlt _rc 0 _prev create_rows_s _qlt (_rc + 1) prev create_columns :: QGridLayout () -> Int -> Int -> Maybe LcdRange_object -> IO (Maybe LcdRange_object) create_columns _ _ _cc _prev | _cc >= 3 = return _prev create_columns _qlt _rc _cc _prev = do l <- lCDRange s <- qSlider eHorizontal let curr = LcdR_o l s cs = slider curr cl = lcdrange curr lcd <- qLCDNumber (2::Int) setSegmentStyle lcd eFilled setRange cs (0::Int, 99::Int) setValue cs (0::Int) connectSlot cs "valueChanged(int)" lcd "display(int)" () connectSignal cs "valueChanged(int)" cl "valueChanged(int)" layout <- qVBoxLayout () addWidget layout lcd addWidget layout cs setLayout cl layout addWidget _qlt (cl, _rc, _cc) connect_prev _prev curr create_columns _qlt _rc (_cc + 1) (Just curr) connect_prev :: Maybe LcdRange_object -> LcdRange_object -> IO () connect_prev Nothing _ = return () connect_prev (Just prev) curr = connectSlot (lcdrange curr) "valueChanged(int)" (lcdrange prev) "setValue(int)" $ setVal $ slider prev setVal :: QSlider () -> LCDRange -> Int -> IO () setVal _qsl _this _val = do setValue _qsl _val performGC
keera-studios/hsQt
examples/sliders.hs
bsd-2-clause
3,454
0
11
656
1,068
537
531
97
1
module Main where import System.Environment import System.Directory import System.IO import Data.List import Data.Word import Data.Bits import Data.Char import Control.Monad import Control.Exception import Data.List.Split getPrimes :: [Integer] -> [Integer] getPrimes [] = [] getPrimes (p:ps) = p : (getPrimes (filter (\x -> (x `mod` p) /= 0) ps)) main = putStrLn ("Answer: " ++ (show ((getPrimes [2 .. 1000000]) !! 10000) ))
brosnanyuen/Project-Euler-Solutions
73/main.hs
bsd-2-clause
432
0
14
67
176
101
75
15
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 \section[WwLib]{A library for the ``worker\/wrapper'' back-end to the strictness analyser} -} {-# LANGUAGE CPP #-} module Eta.StrAnal.WwLib ( mkWwBodies, mkWWstr, mkWorkerArgs , deepSplitProductType_maybe, findTypeShape ) where #include "HsVersions.h" import Eta.Core.CoreSyn import Eta.Core.CoreUtils ( exprType, mkCast ) import Eta.BasicTypes.Id ( Id, idType, mkSysLocal, idDemandInfo, setIdDemandInfo, setIdUnfolding, setIdInfo, idOneShotInfo, setIdOneShotInfo ) import Eta.BasicTypes.IdInfo ( vanillaIdInfo ) import Eta.BasicTypes.DataCon import Eta.BasicTypes.Demand import Eta.Core.MkCore ( mkRuntimeErrorApp, aBSENT_ERROR_ID ) import Eta.BasicTypes.MkId ( voidArgId, voidPrimId ) import Eta.Prelude.TysPrim ( voidPrimTy ) import Eta.Prelude.TysWiredIn ( tupleCon ) import Eta.Types.Type import Eta.Types.Coercion hiding ( substTy, substTyVarBndr ) import Eta.Types.FamInstEnv import Eta.BasicTypes.BasicTypes ( TupleSort(..), OneShotInfo(..), worstOneShot ) import Eta.BasicTypes.Literal ( absentLiteralOf ) import Eta.Types.TyCon import Eta.BasicTypes.UniqSupply import Eta.BasicTypes.Unique import Eta.Utils.Maybes import Eta.Utils.Util import Eta.Utils.Outputable import Eta.Main.DynFlags import Eta.Utils.FastString {- ************************************************************************ * * \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@} * * ************************************************************************ Here's an example. The original function is: \begin{verbatim} g :: forall a . Int -> [a] -> a g = \/\ a -> \ x ys -> case x of 0 -> head ys _ -> head (tail ys) \end{verbatim} From this, we want to produce: \begin{verbatim} -- wrapper (an unfolding) g :: forall a . Int -> [a] -> a g = \/\ a -> \ x ys -> case x of I# x# -> $wg a x# ys -- call the worker; don't forget the type args! -- worker $wg :: forall a . Int# -> [a] -> a $wg = \/\ a -> \ x# ys -> let x = I# x# in case x of -- note: body of g moved intact 0 -> head ys _ -> head (tail ys) \end{verbatim} Something we have to be careful about: Here's an example: \begin{verbatim} -- "f" strictness: U(P)U(P) f (I# a) (I# b) = a +# b g = f -- "g" strictness same as "f" \end{verbatim} \tr{f} will get a worker all nice and friendly-like; that's good. {\em But we don't want a worker for \tr{g}}, even though it has the same strictness as \tr{f}. Doing so could break laziness, at best. Consequently, we insist that the number of strictness-info items is exactly the same as the number of lambda-bound arguments. (This is probably slightly paranoid, but OK in practice.) If it isn't the same, we ``revise'' the strictness info, so that we won't propagate the unusable strictness-info into the interfaces. ************************************************************************ * * \subsection{The worker wrapper core} * * ************************************************************************ @mkWwBodies@ is called when doing the worker\/wrapper split inside a module. -} mkWwBodies :: DynFlags -> FamInstEnvs -> Type -- Type of original function -> [Demand] -- Strictness of original function -> DmdResult -- Info about function result -> [OneShotInfo] -- One-shot-ness of the function, value args only -> UniqSM (Maybe ([Demand], -- Demands for worker (value) args Id -> CoreExpr, -- Wrapper body, lacking only the worker Id CoreExpr -> CoreExpr)) -- Worker body, lacking the original function rhs -- wrap_fn_args E = \x y -> E -- work_fn_args E = E x y -- wrap_fn_str E = case x of { (a,b) -> -- case a of { (a1,a2) -> -- E a1 a2 b y }} -- work_fn_str E = \a2 a2 b y -> -- let a = (a1,a2) in -- let x = (a,b) in -- E mkWwBodies dflags fam_envs fun_ty demands res_info one_shots = do { let arg_info = demands `zip` (one_shots ++ repeat NoOneShotInfo) all_one_shots = foldr (worstOneShot . snd) OneShotLam arg_info ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs emptyTvSubst fun_ty arg_info ; (useful1, work_args, wrap_fn_str, work_fn_str) <- mkWWstr dflags fam_envs wrap_args -- Do CPR w/w. See Note [Always do CPR w/w] ; (useful2, wrap_fn_cpr, work_fn_cpr, cpr_res_ty) <- mkWWcpr fam_envs res_ty res_info ; let (work_lam_args, work_call_args) = mkWorkerArgs dflags work_args all_one_shots cpr_res_ty worker_args_dmds = [idDemandInfo v | v <- work_call_args, isId v] wrapper_body = wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var worker_body = mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args ; if useful1 && not (only_one_void_argument) || useful2 then return (Just (worker_args_dmds, wrapper_body, worker_body)) else return Nothing } -- We use an INLINE unconditionally, even if the wrapper turns out to be -- something trivial like -- fw = ... -- f = __inline__ (coerce T fw) -- The point is to propagate the coerce to f's call sites, so even though -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent -- fw from being inlined into f's RHS where -- Note [Do not split void functions] only_one_void_argument | [d] <- demands , Just (arg_ty1, _) <- splitFunTy_maybe fun_ty , isAbsDmd d && isVoidTy arg_ty1 = True | otherwise = False {- Note [Always do CPR w/w] ~~~~~~~~~~~~~~~~~~~~~~~~ At one time we refrained from doing CPR w/w for thunks, on the grounds that we might duplicate work. But that is already handled by the demand analyser, which doesn't give the CPR proprety if w/w might waste work: see Note [CPR for thunks] in DmdAnal. And if something *has* been given the CPR property and we don't w/w, it's a disaster, because then the enclosing function might say it has the CPR property, but now doesn't and there a cascade of disaster. A good example is Trac #5920. ************************************************************************ * * \subsection{Making wrapper args} * * ************************************************************************ During worker-wrapper stuff we may end up with an unlifted thing which we want to let-bind without losing laziness. So we add a void argument. E.g. f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z ==> fw = /\ a -> \void -> E f = /\ a -> \x y z -> fw realworld We use the state-token type which generates no code. -} mkWorkerArgs :: DynFlags -> [Var] -> OneShotInfo -- Whether all arguments are one-shot -> Type -- Type of body -> ([Var], -- Lambda bound args [Var]) -- Args at call site mkWorkerArgs dflags args all_one_shot res_ty | any isId args || not needsAValueLambda = (args, args) | otherwise = (args ++ [newArg], args ++ [voidPrimId]) where needsAValueLambda = isUnLiftedType res_ty || not (gopt Opt_FunToThunk dflags) -- see Note [Protecting the last value argument] -- see Note [All One-Shot Arguments of a Worker] newArg = setIdOneShotInfo voidArgId all_one_shot {- Note [Protecting the last value argument] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the user writes (\_ -> E), they might be intentionally disallowing the sharing of E. Since absence analysis and worker-wrapper are keen to remove such unused arguments, we add in a void argument to prevent the function from becoming a thunk. The user can avoid adding the void argument with the -ffun-to-thunk flag. However, this can create sharing, which may be bad in two ways. 1) It can create a space leak. 2) It can prevent inlining *under a lambda*. If w/w removes the last argument from a function f, then f now looks like a thunk, and so f can't be inlined *under a lambda*. Note [All One-Shot Arguments of a Worker] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes, derived join-points are just lambda-lifted thunks, whose only argument is of the unit type and is never used. This might interfere with the absence analysis, basing on which results these never-used arguments are eliminated in the worker. The additional argument `all_one_shot` of `mkWorkerArgs` is to prevent this. Example. Suppose we have foo = \p(one-shot) q(one-shot). y + 3 Then we drop the unused args to give foo = \pq. $wfoo void# $wfoo = \void(one-shot). y + 3 But suppse foo didn't have all one-shot args: foo = \p(not-one-shot) q(one-shot). expensive y + 3 Then we drop the unused args to give foo = \pq. $wfoo void# $wfoo = \void(not-one-shot). y + 3 If we made the void-arg one-shot we might inline an expensive computation for y, which would be terrible! ************************************************************************ * * \subsection{Coercion stuff} * * ************************************************************************ We really want to "look through" coerces. Reason: I've seen this situation: let f = coerce T (\s -> E) in \x -> case x of p -> coerce T' f q -> \s -> E2 r -> coerce T' f If only we w/w'd f, we'd get let f = coerce T (\s -> fw s) fw = \s -> E in ... Now we'll inline f to get let fw = \s -> E in \x -> case x of p -> fw q -> \s -> E2 r -> fw Now we'll see that fw has arity 1, and will arity expand the \x to get what we want. -} -- mkWWargs just does eta expansion -- is driven off the function type and arity. -- It chomps bites off foralls, arrows, newtypes -- and keeps repeating that until it's satisfied the supplied arity mkWWargs :: TvSubst -- Freshening substitution to apply to the type -- See Note [Freshen type variables] -> Type -- The type of the function -> [(Demand,OneShotInfo)] -- Demands and one-shot info for value arguments -> UniqSM ([Var], -- Wrapper args CoreExpr -> CoreExpr, -- Wrapper fn CoreExpr -> CoreExpr, -- Worker fn Type) -- Type of wrapper body mkWWargs subst fun_ty arg_info | null arg_info = return ([], id, id, substTy subst fun_ty) | ((dmd,one_shot):arg_info') <- arg_info , Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty = do { uniq <- getUniqueM ; let arg_ty' = substTy subst arg_ty id = mk_wrap_arg uniq arg_ty' dmd one_shot ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs subst fun_ty' arg_info' ; return (id : wrap_args, Lam id . wrap_fn_args, work_fn_args . (`App` varToCoreExpr id), res_ty) } | Just (tv, fun_ty') <- splitForAllTy_maybe fun_ty = do { let (subst', tv') = substTyVarBndr subst tv -- This substTyVarBndr clones the type variable when necy -- See Note [Freshen type variables] ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs subst' fun_ty' arg_info ; return (tv' : wrap_args, Lam tv' . wrap_fn_args, work_fn_args . (`App` Type (mkTyVarTy tv')), res_ty) } | Just (co, rep_ty) <- topNormaliseNewType_maybe fun_ty -- The newtype case is for when the function has -- a newtype after the arrow (rare) -- -- It's also important when we have a function returning (say) a pair -- wrapped in a newtype, at least if CPR analysis can look -- through such newtypes, which it probably can since they are -- simply coerces. = do { (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs subst rep_ty arg_info ; return (wrap_args, \e -> Cast (wrap_fn_args e) (mkSymCo co), \e -> work_fn_args (Cast e co), res_ty) } | otherwise = WARN( True, ppr fun_ty ) -- Should not happen: if there is a demand return ([], id, id, substTy subst fun_ty) -- then there should be a function arrow applyToVars :: [Var] -> CoreExpr -> CoreExpr applyToVars vars fn = mkVarApps fn vars mk_wrap_arg :: Unique -> Type -> Demand -> OneShotInfo -> Id mk_wrap_arg uniq ty dmd one_shot = mkSysLocal (fsLit "w") uniq ty `setIdDemandInfo` dmd `setIdOneShotInfo` one_shot {- Note [Freshen type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Wen we do a worker/wrapper split, we must not use shadowed names, else we'll get f = /\ a /\a. fw a a which is obviously wrong. Type variables can can in principle shadow, within a type (e.g. forall a. a -> forall a. a->a). But type variables *are* mentioned in <blah>, so we must substitute. That's why we carry the TvSubst through mkWWargs ************************************************************************ * * \subsection{Strictness stuff} * * ************************************************************************ -} mkWWstr :: DynFlags -> FamInstEnvs -> [Var] -- Wrapper args; have their demand info on them -- *Includes type variables* -> UniqSM (Bool, -- Is this useful [Var], -- Worker args CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call -- and without its lambdas -- This fn adds the unboxing CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function, -- and lacking its lambdas. -- This fn does the reboxing mkWWstr _ _ [] = return (False, [], nop_fn, nop_fn) mkWWstr dflags fam_envs (arg : args) = do (useful1, args1, wrap_fn1, work_fn1) <- mkWWstr_one dflags fam_envs arg (useful2, args2, wrap_fn2, work_fn2) <- mkWWstr dflags fam_envs args return (useful1 || useful2, args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2) {- Note [Unpacking arguments with product and polymorphic demands] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The argument is unpacked in a case if it has a product type and has a strict *and* used demand put on it. I.e., arguments, with demands such as the following ones: <S,U(U, L)> <S(L,S),U> will be unpacked, but <S,U> or <B,U> will not, because the pieces aren't used. This is quite important otherwise we end up unpacking massive tuples passed to the bottoming function. Example: f :: ((Int,Int) -> String) -> (Int,Int) -> a f g pr = error (g pr) main = print (f fst (1, error "no")) Does 'main' print "error 1" or "error no"? We don't really want 'f' to unbox its second argument. This actually happened in GHC's onwn source code, in Packages.applyPackageFlag, which ended up un-boxing the enormous DynFlags tuple, and being strict in the as-yet-un-filled-in pkgState files. -} ---------------------- -- mkWWstr_one wrap_arg = (useful, work_args, wrap_fn, work_fn) -- * wrap_fn assumes wrap_arg is in scope, -- brings into scope work_args (via cases) -- * work_fn assumes work_args are in scope, a -- brings into scope wrap_arg (via lets) mkWWstr_one :: DynFlags -> FamInstEnvs -> Var -> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr) mkWWstr_one dflags fam_envs arg | isTyVar arg = return (False, [arg], nop_fn, nop_fn) -- See Note [Worker-wrapper for bottoming functions] | isAbsDmd dmd , Just work_fn <- mk_absent_let dflags arg -- Absent case. We can't always handle absence for arbitrary -- unlifted types, so we need to choose just the cases we can --- (that's what mk_absent_let does) = return (True, [], nop_fn, work_fn) -- See Note [Worthy functions for Worker-Wrapper split] | isSeqDmd dmd -- `seq` demand; evaluate in wrapper in the hope -- of dropping seqs in the worker = let arg_w_unf = arg `setIdUnfolding` evaldUnfolding -- Tell the worker arg that it's sure to be evaluated -- so that internal seqs can be dropped in return (True, [arg_w_unf], mk_seq_case arg, nop_fn) -- Pass the arg, anyway, even if it is in theory discarded -- Consider -- f x y = x `seq` y -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker -- we ABSOLUTELY MUST record that x is evaluated in the wrapper. -- Something like: -- f x y = x `seq` fw y -- fw y = let x{Evald} = error "oops" in (x `seq` y) -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and -- we end up evaluating the absent thunk. -- But the Evald flag is pretty weird, and I worry that it might disappear -- during simplification, so for now I've just nuked this whole case | isStrictDmd dmd , Just cs <- splitProdDmd_maybe dmd -- See Note [Unpacking arguments with product and polymorphic demands] , Just (data_con, inst_tys, inst_con_arg_tys, co) <- deepSplitProductType_maybe fam_envs (idType arg) , cs `equalLength` inst_con_arg_tys -- See Note [mkWWstr and unsafeCoerce] = do { (uniq1:uniqs) <- getUniquesM ; let unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs unbox_fn = mkUnpackCase (Var arg) co uniq1 data_con unpk_args rebox_fn = Let (NonRec arg con_app) con_app = mkConApp2 data_con inst_tys unpk_args `mkCast` mkSymCo co ; (_, worker_args, wrap_fn, work_fn) <- mkWWstr dflags fam_envs unpk_args_w_ds ; return (True, worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) } -- Don't pass the arg, rebox instead | otherwise -- Other cases = return (False, [arg], nop_fn, nop_fn) where dmd = idDemandInfo arg one_shot = idOneShotInfo arg -- If the wrapper argument is a one-shot lambda, then -- so should (all) the corresponding worker arguments be -- This bites when we do w/w on a case join point set_worker_arg_info worker_arg demand = worker_arg `setIdDemandInfo` demand `setIdOneShotInfo` one_shot ---------------------- nop_fn :: CoreExpr -> CoreExpr nop_fn body = body {- Note [mkWWstr and unsafeCoerce] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By using unsafeCoerce, it is possible to make the number of demands fail to match the number of constructor arguments; this happened in Trac #8037. If so, the worker/wrapper split doesn't work right and we get a Core Lint bug. The fix here is simply to decline to do w/w if that happens. ************************************************************************ * * Type scrutiny that is specfic to demand analysis * * ************************************************************************ Note [Do not unpack class dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have f :: Ord a => [a] -> Int -> a {-# INLINABLE f #-} and we worker/wrapper f, we'll get a worker with an INLINALBE pragma (see Note [Worker-wrapper for INLINABLE functions] in WorkWrap), which can still be specialised by the type-class specialiser, something like fw :: Ord a => [a] -> Int# -> a BUT if f is strict in the Ord dictionary, we might unpack it, to get fw :: (a->a->Bool) -> [a] -> Int# -> a and the type-class specialiser can't specialise that. An example is Trac #6056. Moreover, dictinoaries can have a lot of fields, so unpacking them can increase closure sizes. Conclusion: don't unpack dictionaries. -} deepSplitProductType_maybe :: FamInstEnvs -> Type -> Maybe (DataCon, [Type], [Type], Coercion) -- If deepSplitProductType_maybe ty = Just (dc, tys, arg_tys, co) -- then dc @ tys (args::arg_tys) :: rep_ty -- co :: ty ~ rep_ty deepSplitProductType_maybe fam_envs ty | let (co, ty1) = topNormaliseType_maybe fam_envs ty `orElse` (mkReflCo Representational ty, ty) , Just (tc, tc_args) <- splitTyConApp_maybe ty1 , Just con <- isDataProductTyCon_maybe tc , not (isClassTyCon tc) -- See Note [Do not unpack class dictionaries] = Just (con, tc_args, dataConInstArgTys con tc_args, co) deepSplitProductType_maybe _ _ = Nothing deepSplitCprType_maybe :: FamInstEnvs -> ConTag -> Type -> Maybe (DataCon, [Type], [Type], Coercion) -- If deepSplitCprType_maybe n ty = Just (dc, tys, arg_tys, co) -- then dc @ tys (args::arg_tys) :: rep_ty -- co :: ty ~ rep_ty deepSplitCprType_maybe fam_envs con_tag ty | let (co, ty1) = topNormaliseType_maybe fam_envs ty `orElse` (mkReflCo Representational ty, ty) , Just (tc, tc_args) <- splitTyConApp_maybe ty1 , isDataTyCon tc , let cons = tyConDataCons tc , cons `lengthAtLeast` con_tag -- This might not be true if we import the -- type constructor via a .hs-bool file (#8743) , let con = cons !! (con_tag - fIRST_TAG) = Just (con, tc_args, dataConInstArgTys con tc_args, co) deepSplitCprType_maybe _ _ _ = Nothing findTypeShape :: FamInstEnvs -> Type -> TypeShape -- Uncover the arrow and product shape of a type -- The data type TypeShape is defined in Demand -- See Note [Trimming a demand to a type] in Demand findTypeShape fam_envs ty | Just (_, ty') <- splitForAllTy_maybe ty = findTypeShape fam_envs ty' | Just (tc, tc_args) <- splitTyConApp_maybe ty , Just con <- isDataProductTyCon_maybe tc = TsProd (map (findTypeShape fam_envs) $ dataConInstArgTys con tc_args) | Just (_, res) <- splitFunTy_maybe ty = TsFun (findTypeShape fam_envs res) | Just (_, ty') <- topNormaliseType_maybe fam_envs ty = findTypeShape fam_envs ty' | otherwise = TsUnk {- ************************************************************************ * * \subsection{CPR stuff} * * ************************************************************************ @mkWWcpr@ takes the worker/wrapper pair produced from the strictness info and adds in the CPR transformation. The worker returns an unboxed tuple containing non-CPR components. The wrapper takes this tuple and re-produces the correct structured output. The non-CPR results appear ordered in the unboxed tuple as if by a left-to-right traversal of the result structure. -} mkWWcpr :: FamInstEnvs -> Type -- function body type -> DmdResult -- CPR analysis results -> UniqSM (Bool, -- Is w/w'ing useful? CoreExpr -> CoreExpr, -- New wrapper CoreExpr -> CoreExpr, -- New worker Type) -- Type of worker's body mkWWcpr fam_envs body_ty res = case returnsCPR_maybe res of Nothing -> return (False, id, id, body_ty) -- No CPR info Just con_tag | Just stuff <- deepSplitCprType_maybe fam_envs con_tag body_ty -> mkWWcpr_help stuff | otherwise -- See Note [non-algebraic or open body type warning] -> WARN( True, text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty ) return (False, id, id, body_ty) mkWWcpr_help :: (DataCon, [Type], [Type], Coercion) -> UniqSM (Bool, CoreExpr -> CoreExpr, CoreExpr -> CoreExpr, Type) mkWWcpr_help (data_con, inst_tys, arg_tys, co) | [arg_ty1] <- arg_tys , isUnLiftedType arg_ty1 -- Special case when there is a single result of unlifted type -- -- Wrapper: case (..call worker..) of x -> C x -- Worker: case ( ..body.. ) of C x -> x = do { (work_uniq : arg_uniq : _) <- getUniquesM ; let arg = mk_ww_local arg_uniq arg_ty1 con_app = mkConApp2 data_con inst_tys [arg] `mkCast` mkSymCo co ; return ( True , \ wkr_call -> Case wkr_call arg (exprType con_app) [(DEFAULT, [], con_app)] , \ body -> mkUnpackCase body co work_uniq data_con [arg] (Var arg) , arg_ty1 ) } | otherwise -- The general case -- Wrapper: case (..call worker..) of (# a, b #) -> C a b -- Worker: case ( ...body... ) of C a b -> (# a, b #) = do { (work_uniq : uniqs) <- getUniquesM ; let (wrap_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : arg_tys) ubx_tup_con = tupleCon UnboxedTuple (length arg_tys) ubx_tup_ty = exprType ubx_tup_app ubx_tup_app = mkConApp2 ubx_tup_con arg_tys args con_app = mkConApp2 data_con inst_tys args `mkCast` mkSymCo co ; return (True , \ wkr_call -> Case wkr_call wrap_wild (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)] , \ body -> mkUnpackCase body co work_uniq data_con args ubx_tup_app , ubx_tup_ty ) } mkUnpackCase :: CoreExpr -> Coercion -> Unique -> DataCon -> [Id] -> CoreExpr -> CoreExpr -- (mkUnpackCase e co uniq Con args body) -- returns -- case e |> co of bndr { Con args -> body } mkUnpackCase (Tick tickish e) co uniq con args body -- See Note [Profiling and unpacking] = Tick tickish (mkUnpackCase e co uniq con args body) mkUnpackCase scrut co uniq boxing_con unpk_args body = Case casted_scrut bndr (exprType body) [(DataAlt boxing_con, unpk_args, body)] where casted_scrut = scrut `mkCast` co bndr = mk_ww_local uniq (exprType casted_scrut) {- Note [non-algebraic or open body type warning] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are a few cases where the W/W transformation is told that something returns a constructor, but the type at hand doesn't really match this. One real-world example involves unsafeCoerce: foo = IO a foo = unsafeCoerce c_exit foreign import ccall "c_exit" c_exit :: IO () Here CPR will tell you that `foo` returns a () constructor for sure, but trying to create a worker/wrapper for type `a` obviously fails. (This was a real example until ee8e792 in libraries/base.) It does not seem feasible to avoid all such cases already in the analyser (and after all, the analysis is not really wrong), so we simply do nothing here in mkWWcpr. But we still want to emit warning with -DDEBUG, to hopefully catch other cases where something went avoidably wrong. Note [Profiling and unpacking] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the original function looked like f = \ x -> {-# SCC "foo" #-} E then we want the CPR'd worker to look like \ x -> {-# SCC "foo" #-} (case E of I# x -> x) and definitely not \ x -> case ({-# SCC "foo" #-} E) of I# x -> x) This transform doesn't move work or allocation from one cost centre to another. Later [SDM]: presumably this is because we want the simplifier to eliminate the case, and the scc would get in the way? I'm ok with including the case itself in the cost centre, since it is morally part of the function (post transformation) anyway. ************************************************************************ * * \subsection{Utilities} * * ************************************************************************ Note [Absent errors] ~~~~~~~~~~~~~~~~~~~~ We make a new binding for Ids that are marked absent, thus let x = absentError "x :: Int" The idea is that this binding will never be used; but if it buggily is used we'll get a runtime error message. Coping with absence for *unlifted* types is important; see, for example, Trac #4306. For these we find a suitable literal, using Literal.absentLiteralOf. We don't have literals for every primitive type, so the function is partial. [I did try the experiment of using an error thunk for unlifted things too, relying on the simplifier to drop it as dead code, by making absentError (a) *not* be a bottoming Id, (b) be "ok for speculation" But that relies on the simplifier finding that it really is dead code, which is fragile, and indeed failed when profiling is on, which disables various optimisations. So using a literal will do.] -} mk_absent_let :: DynFlags -> Id -> Maybe (CoreExpr -> CoreExpr) mk_absent_let dflags arg | not (isUnLiftedType arg_ty) = Just (Let (NonRec arg abs_rhs)) | Just tc <- tyConAppTyCon_maybe arg_ty , Just lit <- absentLiteralOf tc = Just (Let (NonRec arg (Lit lit))) | arg_ty `eqType` voidPrimTy = Just (Let (NonRec arg (Var voidPrimId))) | otherwise = WARN( True, ptext (sLit "No absent value for") <+> ppr arg_ty ) Nothing where arg_ty = idType arg abs_rhs = mkRuntimeErrorApp aBSENT_ERROR_ID arg_ty msg msg = showSDoc dflags (ppr arg <+> ppr (idType arg)) mk_seq_case :: Id -> CoreExpr -> CoreExpr mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)] sanitiseCaseBndr :: Id -> Id -- The argument we are scrutinising has the right type to be -- a case binder, so it's convenient to re-use it for that purpose. -- But we *must* throw away all its IdInfo. In particular, the argument -- will have demand info on it, and that demand info may be incorrect for -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... } -- Quite likely ww_arg isn't used in '...'. The case may get discarded -- if the case binder says "I'm demanded". This happened in a situation -- like (x+y) `seq` .... sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo mk_ww_local :: Unique -> Type -> Id mk_ww_local uniq ty = mkSysLocal (fsLit "ww") uniq ty
rahulmutt/ghcvm
compiler/Eta/StrAnal/WwLib.hs
bsd-3-clause
32,006
0
15
9,473
3,898
2,135
1,763
264
2
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE FlexibleContexts #-} module Elm.Utils ( (|>), (<|), (>>) , run, unwrappedRun , CommandError(..) ) where import Prelude hiding ((>>)) import Control.Monad.Except (MonadError, MonadIO, liftIO, throwError) import System.Exit (ExitCode(ExitSuccess, ExitFailure)) import System.Process (readProcessWithExitCode) {-| Forward function application `x |> f == f x`. This function is useful for avoiding parenthesis and writing code in a more natural way. -} (|>) :: a -> (a -> b) -> b x |> f = f x {-| Backward function application `f <| x == f x`. This function is useful for avoiding parenthesis. -} (<|) :: (a -> b) -> a -> b f <| x = f x infixr 0 <| infixl 0 |> (>>) :: (a -> b) -> (b -> c) -> (a -> c) f >> g = \x -> f x |> g -- RUN EXECUTABLES data CommandError = MissingExe String | CommandFailed String String {-| Run a command, throw an error if the command is not found or if something goes wrong. -} run :: (MonadError String m, MonadIO m) => String -> [String] -> m String run command args = do result <- liftIO (unwrappedRun command args) case result of Right out -> return out Left err -> throwError (context (message err)) where context msg = "failure when running:" ++ concatMap (' ':) (command:args) ++ "\n" ++ msg message err = case err of CommandFailed stderr stdout -> stdout ++ stderr MissingExe msg -> msg unwrappedRun :: String -> [String] -> IO (Either CommandError String) unwrappedRun command args = do (exitCode, stdout, stderr) <- readProcessWithExitCode command args "" return $ case exitCode of ExitSuccess -> Right stdout ExitFailure code | code == 127 -> Left (missingExe command) -- UNIX | code == 9009 -> Left (missingExe command) -- Windows | otherwise -> Left (CommandFailed stdout stderr) missingExe :: String -> CommandError missingExe command = MissingExe $ "Could not find command `" ++ command ++ "`. Do you have it installed?\n\ \ Can it be run from anywhere? Is it on your PATH?"
rgrempel/frelm.org
vendor/elm-format/parser/src/Elm/Utils.hs
mit
2,199
0
14
588
618
331
287
50
3
{- | Module : $Header$ Description : Tools for CommonLogic static analysis Copyright : (c) Eugen Kuksa, Uni Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : eugenk@informatik.uni-bremen.de Stability : experimental Portability : portable Tools for CommonLogic static analysis -} module CommonLogic.Tools ( freeName -- finds a free discourse name , indvC_text -- retrieves all discourse names from a text , indvC_sen -- retrieves all discourse names from a sentence , indvC_term -- retrieves all discourse names from a term , prd_text -- retrieves all predicates from a text , setUnion_list -- maps function @f@ to the list @ts@ and unifies the results ) where import Data.Char (intToDigit) import Data.Set (Set) import qualified Data.Set as Set import CommonLogic.AS_CommonLogic import Common.Id {- ----------------------------------------------------------------------------- Misc functions -- ----------------------------------------------------------------------------- -} {- | Finds a free discourse name (appends "_" at the end until free name found) given the set of all discourse names -} freeName :: (String, Int) -> Set NAME -> (NAME, Int) freeName (s, i) ns = if Set.member n ns then freeName (s, i + 1) ns else (n, i + 1) where n = mkSimpleId (s ++ "_" ++ [intToDigit i]) {- ----------------------------------------------------------------------------- Functions to compute the set of individual constants (discourse items), -- these work by recursing into all subelements -- ----------------------------------------------------------------------------- -} -- | maps @f@ to @ts@ and unifies the results setUnion_list :: (Ord b) => (a -> Set b) -> [a] -> Set b setUnion_list f = Set.unions . map f -- | retrieves the individual constants from a text indvC_text :: TEXT -> Set NAME indvC_text t = case t of Text ps _ -> setUnion_list indvC_phrase ps Named_text _ txt _ -> indvC_text txt -- | retrieves the individual constants from a phrase indvC_phrase :: PHRASE -> Set NAME indvC_phrase p = case p of Module m -> indvC_module m Sentence s -> indvC_sen s Comment_text _ t _ -> indvC_text t _ -> Set.empty -- | retrieves the individual constants from a module indvC_module :: MODULE -> Set NAME indvC_module m = case m of Mod _ t _ -> indvC_text t Mod_ex _ _ t _ -> indvC_text t -- | retrieves the individual constants from a sentence indvC_sen :: SENTENCE -> Set NAME indvC_sen s = case s of Quant_sent q vs is _ -> indvC_quantsent q vs is Bool_sent b _ -> indvC_boolsent b Atom_sent a _ -> indvC_atomsent a Comment_sent _ c _ -> indvC_sen c Irregular_sent i _ -> indvC_sen i -- | retrieves the individual constants from a quantified sentence indvC_quantsent :: QUANT -> [NAME_OR_SEQMARK] -> SENTENCE -> Set NAME indvC_quantsent _ = quant where quant :: [NAME_OR_SEQMARK] -> SENTENCE -> Set NAME quant nss se = Set.difference (indvC_sen se) $ setUnion_list nameof nss nameof :: NAME_OR_SEQMARK -> Set NAME nameof nsm = case nsm of Name n -> Set.singleton n SeqMark _ -> Set.empty -- see indvC_termSeq -- | retrieves the individual constants from a boolean sentence indvC_boolsent :: BOOL_SENT -> Set NAME indvC_boolsent b = case b of Junction _ ss -> setUnion_list indvC_sen ss Negation s -> indvC_sen s BinOp _ s1 s2 -> setUnion_list indvC_sen [s1, s2] -- | retrieves the individual constants from an atom indvC_atomsent :: ATOM -> Set NAME indvC_atomsent a = case a of Equation t1 t2 -> indvC_term t1 `Set.union` indvC_term t2 Atom t ts -> Set.union (nonToplevelNames t) $ setUnion_list indvC_termSeq ts -- arguments -- | omit predicate names nonToplevelNames :: TERM -> Set NAME nonToplevelNames trm = case trm of Name_term _ -> Set.empty Comment_term t _ _ -> nonToplevelNames t _ -> indvC_term trm -- | retrieves the individual constants from a term indvC_term :: TERM -> Set NAME indvC_term trm = case trm of Name_term n -> Set.singleton n Funct_term t ts _ -> Set.union (indvC_term t) $ setUnion_list indvC_termSeq ts -- arguments Comment_term t _ _ -> indvC_term t That_term s _ -> indvC_sen s -- | retrieves the individual constant from a single argument indvC_termSeq :: TERM_SEQ -> Set NAME indvC_termSeq t = case t of Term_seq txt -> indvC_term txt Seq_marks _ -> Set.empty {- ---------------------------------------------------------------------------- Functions to compute the set of predicates, these work by recursing -- into all subelements -- ---------------------------------------------------------------------------- -} -- | Retrieves all predicates from a text prd_text :: TEXT -> Set.Set NAME prd_text t = case t of Text ps _ -> prd_phrases ps Named_text _ nt _ -> prd_text nt prd_phrases :: [PHRASE] -> Set.Set NAME prd_phrases = setUnion_list prd_phrase prd_phrase :: PHRASE -> Set.Set NAME prd_phrase p = case p of Module m -> prd_module m Sentence s -> prd_sentence s Importation _ -> Set.empty Comment_text _ t _ -> prd_text t prd_module :: MODULE -> Set.Set NAME prd_module m = case m of Mod _ t _ -> prd_text t Mod_ex _ _ t _ -> prd_text t prd_sentence :: SENTENCE -> Set.Set NAME prd_sentence s = case s of Quant_sent q vs is _ -> prd_quantSent q vs is Bool_sent b _ -> prd_boolSent b Atom_sent a _ -> prd_atomSent a Comment_sent _ c _ -> prd_sentence c Irregular_sent i _ -> prd_sentence i prd_quantSent :: QUANT -> [NAME_OR_SEQMARK] -> SENTENCE -> Set.Set NAME prd_quantSent _ _ = prd_sentence {- we do not know if variables are predicates, we assume no, and only check the body -} prd_boolSent :: BOOL_SENT -> Set.Set NAME prd_boolSent b = case b of Junction _ ss -> setUnion_list prd_sentence ss Negation s -> prd_sentence s BinOp _ s1 s2 -> setUnion_list prd_sentence [s1, s2] prd_atomSent :: ATOM -> Set.Set NAME prd_atomSent a = case a of Equation t1 t2 -> setUnion_list prd_term [t1, t2] Atom t tseq -> -- the predicate name is in t Set.unions [prd_termSeqs tseq, prd_term t, prd_add_term t] prd_term :: TERM -> Set.Set NAME prd_term t = case t of Name_term _ -> Set.empty Funct_term ft tseqs _ -> prd_term ft `Set.union` prd_termSeqs tseqs -- the function name is not a predicate Comment_term ct _ _ -> prd_term ct That_term s _ -> prd_sentence s prd_termSeqs :: [TERM_SEQ] -> Set.Set NAME prd_termSeqs = setUnion_list prd_termSeq prd_termSeq :: TERM_SEQ -> Set.Set NAME prd_termSeq tsec = case tsec of Term_seq t -> prd_term t Seq_marks _ -> Set.empty prd_add_term :: TERM -> Set.Set NAME prd_add_term t = case t of Name_term n -> Set.singleton n Comment_term ct _ _ -> prd_add_term ct _ -> Set.empty -- from all other terms we do not extract the predicate name
mariefarrell/Hets
CommonLogic/Tools.hs
gpl-2.0
7,438
0
11
1,984
1,796
882
914
146
5
module Main where import Graphics.UI.WX bugtext = unlines [ "Former bug: these buttons should react when clicked" , "but the boxed one does not" , "" , "Buggy in: MacOS X [now fixed!]" , "Working in: Linux and Windows" ] main = start $ do f <- frame [ text := "program" ] b1 <- button f [ text := "click me" ] b2 <- button f [ text := "click me" ] b3 <- button f [ text := "click me" ] set b1 [ on command := set b1 [ text := "thanks!" ] ] set b2 [ on command := set b2 [ text := "thanks!" ] ] set b3 [ on command := set b3 [ text := "thanks!" ] ] set f [ visible := True , layout := margin 10 $ column 4 [ label bugtext, widget b1, (boxed "" $ column 2 [ (boxed "hey" $ widget b2) , widget b3 ]) ] ]
ekmett/wxHaskell
samples/test/BoxedCombinator.hs
lgpl-2.1
982
0
19
442
292
145
147
19
1
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, MultiParamTypeClasses, DeriveDataTypeable, OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Pane.Errors -- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL -- -- Maintainer : maintainer@leksah.org -- Stability : provisional -- Portability : -- -- | A pane which displays a list of errors -- ----------------------------------------------------------------------------- module IDE.Pane.Errors ( IDEErrors , ErrorsState , fillErrorList , selectError , getErrors ) where import Graphics.UI.Gtk import Data.Typeable (Typeable(..)) import IDE.Core.State import Graphics.UI.Gtk.General.Enums (Click(..), MouseButton(..)) import Graphics.UI.Gtk.Gdk.Events (Event(..)) import IDE.ImportTool (addResolveMenuItems, resolveErrors) import Data.List (elemIndex) import IDE.LogRef (showSourceSpan) import Control.Monad.IO.Class (MonadIO(..)) import IDE.Utils.GUIUtils (treeViewContextMenu, __) import Data.Maybe (isJust) import Control.Monad (when) import Data.Text (Text) import qualified Data.Text as T (unpack) -- | A breakpoints pane description -- data IDEErrors = IDEErrors { scrolledView :: ScrolledWindow , treeView :: TreeView , errorStore :: TreeStore ErrColumn } deriving Typeable data ErrColumn = ErrColumn {logRef :: LogRef, text :: Text, index :: Int} data ErrorsState = ErrorsState { } deriving(Eq,Ord,Read,Show,Typeable) instance Pane IDEErrors IDEM where primPaneName _ = __ "Errors" getTopWidget = castToWidget . scrolledView paneId b = "*Errors" instance RecoverablePane IDEErrors ErrorsState IDEM where saveState p = return (Just ErrorsState) recoverState pp ErrorsState = do nb <- getNotebook pp p <- buildPane pp nb builder fillErrorList return p builder = builder' builder' :: PanePath -> Notebook -> Window -> IDEM (Maybe IDEErrors, Connections) builder' pp nb windows = reifyIDE $ \ ideR -> do errorStore <- treeStoreNew [] treeView <- treeViewNew treeViewSetModel treeView errorStore rendererA <- cellRendererTextNew colA <- treeViewColumnNew treeViewColumnSetTitle colA (__ "Location") treeViewColumnSetSizing colA TreeViewColumnAutosize treeViewColumnSetResizable colA True treeViewColumnSetReorderable colA True treeViewAppendColumn treeView colA cellLayoutPackStart colA rendererA False cellLayoutSetAttributes colA rendererA errorStore $ \row -> [cellText := if index row == 0 then showSourceSpan (logRef row) else "", cellTextForeground := if logRefType (logRef row) == WarningRef then "green" else "red"::Text ] rendererB <- cellRendererTextNew colB <- treeViewColumnNew treeViewColumnSetTitle colB (__ "Description") treeViewColumnSetSizing colB TreeViewColumnAutosize treeViewColumnSetResizable colB True treeViewColumnSetReorderable colB True treeViewAppendColumn treeView colB cellLayoutPackStart colB rendererB False cellLayoutSetAttributes colB rendererB errorStore $ \row -> [ cellText := text row] treeViewSetHeadersVisible treeView True selB <- treeViewGetSelection treeView treeSelectionSetMode selB SelectionSingle scrolledView <- scrolledWindowNew Nothing Nothing scrolledWindowSetShadowType scrolledView ShadowIn containerAdd scrolledView treeView scrolledWindowSetPolicy scrolledView PolicyAutomatic PolicyAutomatic let pane = IDEErrors scrolledView treeView errorStore cid1 <- after treeView focusInEvent $ do liftIO $ reflectIDE (makeActive pane) ideR return True (cid2, cid3) <- treeViewContextMenu treeView $ errorsContextMenu ideR errorStore treeView cid4 <- treeView `on` rowActivated $ errorsSelect ideR errorStore return (Just pane, map ConnectC [cid1, cid2, cid3, cid4]) getErrors :: Maybe PanePath -> IDEM IDEErrors getErrors Nothing = forceGetPane (Right "*Errors") getErrors (Just pp) = forceGetPane (Left pp) fillErrorList :: IDEAction fillErrorList = do mbErrors <- getPane case mbErrors of Nothing -> return () Just pane -> do refs <- readIDE errorRefs liftIO $ do treeStoreClear (errorStore pane) mapM_ (insertError (errorStore pane)) (zip refs [0..length refs]) where insertError treeStore (lr,index) = case {--lines--} [refDescription lr] of [] -> treeStoreInsert treeStore [] index (ErrColumn lr "" 0) h:t -> do treeStoreInsert treeStore [] index (ErrColumn lr h 0) mapM_ (\(line,subind) -> treeStoreInsert treeStore [index] subind (ErrColumn lr line (subind + 1))) (zip t [0..length t]) getSelectedError :: TreeView -> TreeStore ErrColumn -> IO (Maybe LogRef) getSelectedError treeView treeStore = do treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of a:r -> do val <- treeStoreGetValue treeStore a return (Just (logRef val)) _ -> return Nothing selectError :: Maybe LogRef -> IDEAction selectError mbLogRef = do errorRefs' <- readIDE errorRefs errors <- getErrors Nothing liftIO $ do selection <- treeViewGetSelection (treeView errors) case mbLogRef of Nothing -> treeSelectionUnselectAll selection Just lr -> case lr `elemIndex` errorRefs' of Nothing -> return () Just ind -> treeSelectionSelectPath selection [ind] errorsContextMenu :: IDERef -> TreeStore ErrColumn -> TreeView -> Menu -> IO () errorsContextMenu ideR store treeView theMenu = do mbSel <- getSelectedError treeView store item0 <- menuItemNewWithLabel (__ "Resolve Errors") item0 `on` menuItemActivate $ reflectIDE resolveErrors ideR menuShellAppend theMenu item0 case mbSel of Just sel -> addResolveMenuItems ideR theMenu sel Nothing -> return () errorsSelect :: IDERef -> TreeStore ErrColumn -> TreePath -> TreeViewColumn -> IO () errorsSelect ideR store path _ = do ref <- treeStoreGetValue store path reflectIDE (setCurrentError (Just (logRef ref))) ideR
573/leksah
src/IDE/Pane/Errors.hs
gpl-2.0
6,804
1
19
1,804
1,721
856
865
153
3
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Простой пример Дополнения</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/simpleexample/src/main/javahelp/org/zaproxy/addon/simpleexample/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,025
82
52
157
488
253
235
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>Automation Framework</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>
thc202/zap-extensions
addOns/automation/src/main/javahelp/org/zaproxy/addon/automation/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
965
82
52
156
390
206
184
-1
-1
module Generate.JavaScript.Port (inbound, outbound, task) where import qualified Data.List as List import qualified Data.Map as Map import Language.ECMAScript3.Syntax import qualified AST.Type as T import qualified AST.Variable as Var import Generate.JavaScript.Helpers import qualified Reporting.PrettyPrint as P -- TASK task :: String -> Expression () -> T.Port t -> Expression () task name expr portType = case portType of T.Normal _ -> _Task "perform" `call` [ expr ] T.Signal _ _ -> _Task "performSignal" `call` [ string name, expr ] -- HELPERS data JSType = JSNumber | JSBoolean | JSString | JSArray | JSObject [String] typeToString :: JSType -> String typeToString tipe = case tipe of JSNumber -> "a number" JSBoolean -> "a boolean (true or false)" JSString -> "a string" JSArray -> "an array" JSObject fields -> "an object with fields `" ++ List.intercalate "`, `" fields ++ "`" _Array :: String -> Expression () _Array functionName = useLazy ["Elm","Native","Array"] functionName _List :: String -> Expression () _List functionName = useLazy ["Elm","Native","List"] functionName _Maybe :: String -> Expression () _Maybe functionName = useLazy ["Elm","Maybe"] functionName _Port :: String -> Expression () _Port functionName = useLazy ["Elm","Native","Port"] functionName _Task :: String -> Expression () _Task functionName = useLazy ["Elm","Native","Task"] functionName check :: Expression () -> JSType -> Expression () -> Expression () check x jsType continue = CondExpr () (jsFold OpLOr checks x) continue throw where jsFold op checks value = foldl1 (InfixExpr () op) (map ($ value) checks) throw = obj ["_U","badPort"] `call` [ string (typeToString jsType), x ] checks = case jsType of JSNumber -> [typeof "number"] JSBoolean -> [typeof "boolean"] JSString -> [typeof "string", instanceof "String"] JSArray -> [instanceof "Array"] JSObject fields -> [jsFold OpLAnd (typeof "object" : map member fields)] -- INBOUND inbound :: String -> T.Port T.Canonical -> Expression () inbound name portType = case portType of T.Normal tipe -> _Port "inbound" `call` [ string name , string (show (P.pretty Map.empty False tipe)) , toTypeFunction tipe ] T.Signal _root arg -> _Port "inboundSignal" `call` [ string name , string (show (P.pretty Map.empty False arg)) , toTypeFunction arg ] toTypeFunction :: T.Canonical -> Expression () toTypeFunction tipe = ["v"] ==> toType tipe (ref "v") toType :: T.Canonical -> Expression () -> Expression () toType tipe x = case tipe of T.Lambda _ _ -> error "functions should not be allowed through input ports" T.Var _ -> error "type variables should not be allowed through input ports" T.Aliased _ args t -> toType (T.dealias args t) x T.Type (Var.Canonical Var.BuiltIn name) | name == "Int" -> from JSNumber | name == "Float" -> from JSNumber | name == "Bool" -> from JSBoolean | name == "String" -> from JSString where from checks = check x checks x T.Type name | Var.isJson name -> x | Var.isTuple name -> toTuple [] x | otherwise -> error "bad type got to foreign input conversion" T.App f args -> case f : args of T.Type name : [t] | Var.isMaybe name -> CondExpr () (equal x (NullLit ())) (_Maybe "Nothing") (_Maybe "Just" <| toType t x) | Var.isList name -> check x JSArray (_List "fromArray" <| array) | Var.isArray name -> check x JSArray (_Array "fromJSArray" <| array) where array = DotRef () x (var "map") <| toTypeFunction t T.Type name : ts | Var.isTuple name -> toTuple ts x _ -> error "bad ADT got to foreign input conversion" T.Record _ (Just _) -> error "bad record got to foreign input conversion" T.Record fields Nothing -> check x (JSObject (map fst fields)) object where object = ObjectLit () $ (prop "_", ObjectLit () []) : keys keys = map convert fields convert (f,t) = (prop f, toType t (DotRef () x (var f))) toTuple :: [T.Canonical] -> Expression () -> Expression () toTuple types x = check x JSArray (ObjectLit () fields) where fields = (prop "ctor", ctor) : zipWith convert [0..] types ctor = string ("_Tuple" ++ show (length types)) convert n t = ( prop ('_':show n) , toType t (BracketRef () x (IntLit () n)) ) -- OUTBOUND outbound :: String -> Expression () -> T.Port T.Canonical -> Expression () outbound name expr portType = case portType of T.Normal tipe -> _Port "outbound" `call` [ string name, fromTypeFunction tipe, expr ] T.Signal _ arg -> _Port "outboundSignal" `call` [ string name, fromTypeFunction arg, expr ] fromTypeFunction :: T.Canonical -> Expression () fromTypeFunction tipe = ["v"] ==> fromType tipe (ref "v") fromType :: T.Canonical -> Expression () -> Expression () fromType tipe x = case tipe of T.Aliased _ args t -> fromType (T.dealias args t) x T.Lambda _ _ | numArgs > 1 && numArgs < 10 -> func (ref ('A':show numArgs) `call` (x:values)) | otherwise -> func (foldl (<|) x values) where ts = T.collectLambdas tipe numArgs = length ts - 1 args = map (\n -> '_' : show n) [0..] values = zipWith toType (init ts) (map ref args) func body = function (take numArgs args) [ VarDeclStmt () [VarDecl () (var "_r") (Just body)] , ret (fromType (last ts) (ref "_r")) ] T.Var _ -> error "type variables should not be allowed through outputs" T.Type (Var.Canonical Var.BuiltIn name) | name `elem` ["Int","Float","Bool","String"] -> x T.Type name | Var.isJson name -> x | Var.isTuple name -> ArrayLit () [] | otherwise -> error "bad type got to an output" T.App f args -> case f : args of T.Type name : [t] | Var.isMaybe name -> CondExpr () (equal (DotRef () x (var "ctor")) (string "Nothing")) (NullLit ()) (fromType t (DotRef () x (var "_0"))) | Var.isArray name -> DotRef () (_Array "toJSArray" <| x) (var "map") <| fromTypeFunction t | Var.isList name -> DotRef () (_List "toArray" <| x) (var "map") <| fromTypeFunction t T.Type name : ts | Var.isTuple name -> let convert n t = fromType t $ DotRef () x $ var ('_':show n) in ArrayLit () $ zipWith convert [0..] ts _ -> error "bad ADT got to an output" T.Record _ (Just _) -> error "bad record got to an output" T.Record fields Nothing -> ObjectLit () keys where keys = map convert fields convert (f,t) = (PropId () (var f), fromType t (DotRef () x (var f)))
Axure/elm-compiler
src/Generate/JavaScript/Port.hs
bsd-3-clause
7,823
0
20
2,758
2,707
1,336
1,371
193
10
module LiftToToplevel.Where where anotherFun 0 y = sq y where sq x = x^2
RefactoringTools/HaRe
test/testdata/Layout/Where.hs
bsd-3-clause
79
0
7
20
33
17
16
3
1
module A1 where import C1 main xs = case xs of [] -> 0 [(x : xs)] -> (x ^ pow) + (sumSquares1 xs)
kmate/HaRe
old/testing/liftToToplevel/A1AST.hs
bsd-3-clause
129
0
10
55
60
33
27
6
2
{-# Language CPP, GADTs, StandaloneDeriving, DeriveDataTypeable, QuasiQuotes, NoMonomorphismRestriction, TupleSections, OverloadedStrings #-} {- | Optimizer: Basic optimization of the generated JavaScript to reduce file size and improve readability assumptions: - getProperty is pure -} module Gen2.Optimizer where import Control.Applicative import Control.Lens import Control.Monad import Data.Array import Data.Bits import Data.Data import Data.Data.Lens import Data.Default import qualified Data.Foldable as F import qualified Data.IntSet as IS import Data.Int import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.List (foldl') import qualified Data.List as L import qualified Data.Map as M import Data.Maybe import Data.Monoid import qualified Data.Set as S import qualified Data.Text as T import Data.Word import Panic import Compiler.JMacro import Gen2.Base import Gen2.Dataflow import Gen2.Rts import Gen2.RtsTypes optimize :: JStat -> JStat #ifdef DISABLE_OPTIMIZER optimize = id #else optimize = renameLocalVars . removeDeadVars . dataflow #endif renameLocalVars :: JStat -> JStat renameLocalVars = thisFunction . nestedFuns %~ renameLocalsFun newLocals -- traverse all expressions in the statement (no recursion into nested statements) statExprs :: Traversal' JStat JExpr statExprs f (ReturnStat e) = ReturnStat <$> f e statExprs f (IfStat e s1 s2) = IfStat <$> f e <*> pure s1 <*> pure s2 statExprs f (ForInStat b i e s) = ForInStat b i <$> f e <*> pure s statExprs f (SwitchStat e es s) = SwitchStat <$> f e <*> (traverse . _1) f es <*> pure s statExprs f (ApplStat e1 es) = ApplStat <$> f e1 <*> traverse f es statExprs f (UOpStat o e) = UOpStat o <$> f e statExprs f (AssignStat e1 e2) = AssignStat <$> f e1 <*> f e2 statExprs _ s = pure s subStats :: Traversal' JStat JStat subStats f (IfStat e s1 s2) = IfStat e <$> f s1 <*> f s2 subStats f (WhileStat b e s) = WhileStat b e <$> f s subStats f (ForInStat b i e s) = ForInStat b i e <$> f s subStats f (SwitchStat e es s) = SwitchStat e <$> (traverse . _2) f es <*> f s subStats f (TryStat s1 i s2 s3) = TryStat <$> f s1 <*> pure i <*> f s2 <*> f s3 subStats f (BlockStat ss) = BlockStat <$> traverse f ss subStats f (LabelStat l s) = LabelStat l <$> f s subStats _ s = pure s subExprs :: Traversal' JExpr JExpr subExprs f (SelExpr e i) = SelExpr <$> f e <*> pure i subExprs f (IdxExpr e1 e2) = IdxExpr <$> f e1 <*> f e2 subExprs f (InfixExpr o e1 e2) = InfixExpr o <$> f e1 <*> f e2 subExprs f (UOpExpr xs e) = UOpExpr xs <$> f e subExprs f (IfExpr e1 e2 e3) = IfExpr <$> f e1 <*> f e2 <*> f e3 subExprs f (ApplExpr e es) = ApplExpr <$> f e <*> traverse f es subExprs f e = f e -- traverse all 'leaf' statements in this function thisFunction :: Traversal' JStat JStat thisFunction f (IfStat e s1 s2) = IfStat e <$> thisFunction f s1 <*> thisFunction f s2 thisFunction f (WhileStat b e s) = WhileStat b e <$> thisFunction f s thisFunction f (ForInStat b i e s) = ForInStat b i e <$> thisFunction f s thisFunction f (SwitchStat e es s) = SwitchStat e <$> (traverse . _2 . thisFunction) f es <*> thisFunction f s thisFunction f (TryStat s1 i s2 s3) = TryStat <$> thisFunction f s1 <*> pure i <*> thisFunction f s2 <*> thisFunction f s3 thisFunction f (BlockStat ss) = BlockStat <$> template (thisFunction f) ss thisFunction f (LabelStat l s) = LabelStat l <$> thisFunction f s thisFunction f s = f s localVars :: JStat -> [Ident] localVars = universeOf subStats >=> getLocals where getLocals (DeclStat i) = [i] getLocals (ForInStat _ i _ _) = [i] -- remove ident? getLocals (TryStat _ _i _ _) = [] -- is this correct? getLocals _ = [] localIdents :: Traversal' JStat Ident localIdents = template . localFunctionVals . _JVar allIdents :: Traversal' JStat Ident allIdents = template . functionVals . _JVar nestedFuns :: (Applicative f, Data s) => (([Ident], JStat) -> f ([Ident], JStat)) -> s -> f s nestedFuns = template . localFunctionVals . _JFunc -- all idents not in expressions in this function, including in declarations nonExprLocalIdents :: Traversal' JStat Ident nonExprLocalIdents f (IfStat e s1 s2) = IfStat e <$> nonExprLocalIdents f s1 <*> nonExprLocalIdents f s2 nonExprLocalIdents f (DeclStat i) = DeclStat <$> f i nonExprLocalIdents f (WhileStat b e s) = WhileStat b e <$> nonExprLocalIdents f s nonExprLocalIdents f (ForInStat b i e s) = ForInStat b <$> f i <*> pure e <*> nonExprLocalIdents f s nonExprLocalIdents f (SwitchStat e es s) = SwitchStat e <$> (traverse . _2 . nonExprLocalIdents) f es <*> nonExprLocalIdents f s nonExprLocalIdents f (TryStat s1 i s2 s3) = TryStat <$> nonExprLocalIdents f s1 <*> f i <*> nonExprLocalIdents f s2 <*> nonExprLocalIdents f s3 nonExprLocalIdents f (BlockStat ss) = BlockStat <$> (traverse . nonExprLocalIdents) f ss nonExprLocalIdents f (LabelStat l s) = LabelStat l <$> nonExprLocalIdents f s nonExprLocalIdents _ s = pure s functionVals :: Traversal' JVal JVal functionVals f (JList es) = JList <$> template (functionVals f) es functionVals f (JHash m) = JHash <$> tinplate (functionVals f) m functionVals f (JFunc as es) = JFunc as <$> template (functionVals f) es functionVals f v = f v localFunctionVals :: Traversal' JVal JVal localFunctionVals f (JList es) = JList <$> template (localFunctionVals f) es localFunctionVals f (JHash m) = JHash <$> tinplate (localFunctionVals f) m -- lens bug? localFunctionVals f v = f v -- fixme: check that try/catch is handled correctly, with separate local vars for the caught things renameLocalsFun :: [Ident] -> ([Ident], JStat) -> ([Ident], JStat) renameLocalsFun newNames f = ( map renameVar args , s' & localIdents %~ renameVar & nonExprLocalIdents %~ renameVar ) where (_, s') = nestedFuns %~ renameGlobals rename $ (args, s) (args, s) = nestedFuns %~ renameLocalsFun newNames $ f renameVar i = fromMaybe i (M.lookup i rename) rename = M.fromList $ zip locals (filter (`S.notMember` globals) newNames) globals = idents S.\\ (S.fromList locals) idents = S.fromList (s ^.. allIdents ++ args) locals = L.nub $ localVars s -- args ++ s ^.. localVars -- propagate renaming of variables global relative to this function body renameGlobals :: M.Map Ident Ident -> ([Ident],JStat) -> ([Ident],JStat) renameGlobals m f@(args,s) = (args, localIdents %~ renameVar $ s') where (_, s') = nestedFuns %~ renameGlobals m' $ f renameVar i = fromMaybe i (M.lookup i m') locals = L.nub $ args ++ localVars s m' = m M.\\ (M.fromList $ zip locals (repeat (TxtI "_"))) tup :: a -> (a,a) tup x = (x,x) ----------------------------------------------------- -- dead variable elimination: -- a dead var is a local variable that is never read or assigned ----------------------------------------------------- removeDeadVars :: JStat -> JStat removeDeadVars s = s & thisFunction . nestedFuns . _2 %~ removeDeadVars' removeDeadVars' :: JStat -> JStat removeDeadVars' s = transformOf subStats (removeDead dead) s where dead = locals S.\\ nonDead nonDead = S.fromList (universeOf subStats s ^.. traverse . liveVarsS) locals = S.fromList (localVars s) removeDead :: S.Set Ident -> JStat -> JStat removeDead dead (DeclStat i) | i `S.member` dead = mempty removeDead _ s = s liveVarsS :: Traversal' JStat Ident liveVarsS f s = (statExprs . liveVarsE) f s liveVarsE :: Traversal' JExpr Ident liveVarsE f (ValExpr (JVar i)) = ValExpr . JVar <$> f i liveVarsE _ v@(ValExpr (JFunc {})) = pure v liveVarsE f e = template (liveVarsE f) e ---------------------------------------------------------- data Annot = Annot { aIdents :: IdSet -- identifiers in the expression , aSideEffects :: Bool -- can the expression have side effects , aUse :: IntMap Int -- identifiers with number of occurrences } deriving (Data, Typeable, Eq, Show) type Graph' = Graph Annot type Node' = Node Annot type AExpr' = AExpr Annot type SimpleStat' = SimpleStat Annot -- things that we do not want to calculate multiple times for the graph data Cache = Cache { cachedKnownFuns :: IntMap IdSet , cachedKnownPure :: IdSet } cache :: Graph' -> Cache cache g = Cache (knownFuns g) (knownPureFuns g) -- empty annotation to get started, replace this with a proper annotations before rewriting emptyAnnot :: Annot emptyAnnot = Annot (error "emptyAnnot: empty annotation") (error "emptyAnnot: empty annotation") (error "emptyAnnot: empty annotation") annotate :: Cache -> Expr -> AExpr' annotate c e = AExpr (Annot (exprIdents e) (mightHaveSideeffects c e) (exprIdents' e)) e noAnnot :: Graph' -> Expr -> AExpr' noAnnot _ e = AExpr emptyAnnot e normalizeAnnot :: Cache -> Graph' -> Graph' normalizeAnnot c g = g & nodes . traverse %~ normalizeAExprs where normalizeAExprs :: Node' -> Node' normalizeAExprs = rewriteNodeExprs (\isCond -> annotate c . normalize isCond c g . fromA) dataflow :: JStat -> JStat dataflow = thisFunction . nestedFuns %~ f where f d@(args, stat) | noDataflow stat = d | otherwise = ung stat . optimizeSequences c . liveness args' locals . constants args' locals c . liveness args' locals . constants args' locals c . liveness args' locals . constants args' locals c -- . propagateStack args' locals c -- fixme this analysis is buggy and we run into bugs now that we generate branches that don't return $ g1 where g0 = flattenSequences (cfg noAnnot stat) c = cache g0 g1 :: Graph' g1 = normalizeAnnot c g0 args' :: IdSet args' = IS.fromList $ catMaybes (map (lookupId g0) args) locals = localVarsGraph g0 ung _ g = (args, unCfg g) -- ung _ g = (args, [j| if(runOptimized) { `unCfg g` } else { `stat` } |]) -- use this for utils/testOptimizer.hs ----------------------------------------------------------- -- detect some less frequently used constructs that we -- do not support in the dataflow analyzer yet ----------------------------------------------------------- noDataflow :: JStat -> Bool noDataflow stat = any unsupportedExpr (universeOnOf template template stat) where unsupportedExpr (ValExpr (JFunc {})) = True unsupportedExpr _ = False ----------------------------------------------------------- -- liveness: remove unnecessary assignments ----------------------------------------------------------- liveness :: IdSet -> IdSet -> Graph' -> Graph' liveness args locals g = g & nodes %~ IM.mapWithKey updNode where la = args `IS.union` locals lf = livenessFacts g updNode :: NodeId -> Node' -> Node' updNode nid (SimpleNode (AssignS (AExpr _ (ValE (Var i))) e)) | not (live i (lookupFact def nid 0 lf)) && not (mightHaveSideeffects' e) && i `IS.member` la = SequenceNode [] updNode _ n = n live :: Id -> Liveness -> Bool live i (Liveness x y) = i `IM.member` x || i `IM.member` y -- Id -> use data Liveness = Liveness { lUse :: IntMap Use -- normal uses , lExcep :: IntMap Use -- if the statement generates an exception uses } deriving (Eq, Show) instance Default Liveness where def = Liveness IM.empty IM.empty data Use = Once | Multiple deriving (Show, Eq, Bounded, Ord, Enum) -- fixme for trystat probably livenessFacts :: Graph Annot -> Facts Liveness livenessFacts g = {- dumpLive g $ -} foldBackward c f def def g where c :: Liveness -> Liveness -> Liveness c (Liveness x1 y1) (Liveness x2 y2) = Liveness (IM.unionWith lUb x1 x2) (IM.unionWith lUb y1 y2) c' :: IntMap Use -> IntMap Use -> IntMap Use c' = IM.unionWith lUb p :: Liveness -> Liveness -> Liveness p (Liveness x1 y1) (Liveness x2 y2) = Liveness (IM.unionWith lPlus x1 x2) (IM.unionWith lPlus y1 y2) -- p' :: IntMap Use -> IntMap Use -> IntMap Use -- p' = IM.unionWith lUb r :: Id -> Liveness -> Liveness r i (Liveness x y) = Liveness (IM.delete i x) y f :: Backward Annot Liveness f = Backward { bIf = \_ -> cb , bWhile = \_ -> cb , bDoWhile = \_ e x -> x `p` exprL e , bSimple = \_ -> simple , bBreak = \_ -> id , bContinue = \_ -> id , bReturn = \_ e -> exprL e , bTry = \_ _ -> try , bForIn = \_ _ _ -> cb , bSwitch = \_ e x -> x `p` exprL e } cb :: AExpr' -> (Liveness, Liveness) -> Liveness cb e (x1, x2) = (x1 `c` x2) `p` exprL e exprL :: AExpr' -> Liveness exprL e = Liveness (fmap (\x -> if x <= 1 then Once else Multiple) . aUse . getAnnot $ e) IM.empty simple :: SimpleStat' -> Liveness -> Liveness simple (DeclS _) l = l simple (AssignS e1 e2) l | (ValE (Var i)) <- fromA e1 = r i l `p` exprL e2 | otherwise = (l `p` exprL e1) `p` exprL e2 simple (ExprS e) l = l `p` exprL e try :: (Liveness, Liveness, Liveness) -> (Liveness, Liveness) try (bt, bc, bf) = let et = Liveness (lUse bf) (lUse bc `c'` lExcep bc) -- is this correct? bt' = Liveness (lUse bt) (lExcep bf) in (bt', et) lPlus :: Use -> Use -> Use lPlus _ _ = Multiple lUb :: Use -> Use -> Use lUb Once Once = Once lUb _ _ = Multiple ----------------------------------------------------------- -- constants and assignment propagation -- removes unreachable branches and statements ----------------------------------------------------------- data CVals = CUnreached | CReached (IntMap CFact) deriving (Eq, Data, Typeable, Show) newtype CMods = CMods IdSet deriving (Eq, Data, Typeable, Show) -- known value, and whether this value may be used multiple times data CFact = CKnown AExpr' Bool deriving (Eq, Data, Typeable, Show) (%%) :: (IntMap CFact -> IntMap CFact) -> CVals -> CVals _ %% CUnreached = CUnreached f %% CReached m = CReached (f m) constants :: IdSet -> IdSet -> Cache -> Graph' -> Graph' constants args locals c g = g & nodes %~ IM.mapWithKey rewriteNode where fs = constantsFacts lfs c g lfs = livenessFacts g -- fact index 2 is what flows into the expression nodeFact :: NodeId -> CVals nodeFact nid = lookupFact CUnreached nid 2 fs rewriteNode :: NodeId -> Node' -> Node' rewriteNode nid _ | lookupFact CUnreached nid 0 fs == CUnreached = SequenceNode [] -- unreachable code rewriteNode nid (IfNode e s1 s2) | Just True <- c, not s = SequenceNode [s1] -- else branch unreachable | Just False <- c, not s = SequenceNode [s2] -- if branch unreachable where s = mightHaveSideeffects' e' c = exprCond' e' e' = propagateExpr (nodeFact nid) True e rewriteNode nid (WhileNode e _s1) -- loop body unreachable | Just False <- exprCond' e', not (mightHaveSideeffects' e') = SequenceNode [] where e' = propagateExpr (nodeFact nid) True e rewriteNode nid (SimpleNode (AssignS e1 e2)) | (ValE (Var x)) <- fromA e1, (ValE (Var y)) <- fromA e2, x == y = SequenceNode [] | (ValE (Var x)) <- fromA e1, not (live x (lookupFact def nid 0 lfs)) && not (mightHaveSideeffects' e2) && x `IS.member` la = SequenceNode [] | (ValE (Var _)) <- fromA e1 = SimpleNode (AssignS e1 (propagateExpr (nodeFact nid) False e2)) rewriteNode nid n = rewriteNodeExprs (propagateExpr (nodeFact nid)) n la = args `IS.union` locals live :: Id -> Liveness -> Bool live i (Liveness x y) = i `IM.member` x || i `IM.member` y -- apply our facts to an expression propagateExpr :: CVals -> Bool -> AExpr' -> AExpr' propagateExpr CUnreached _isCond ae = ae propagateExpr cv@(CReached{}) isCond ae | not hasKnownDeps = ae | e@(ApplE (ValE _) args) <- fromA ae = annotate c . normalize isCond c g $ propagateExpr' (maybe (CReached IM.empty) (`deleteConstants` cv) (IS.unions <$> mapM (mutated c) args)) e | otherwise = annotate c . normalize isCond c g $ propagateExpr' (maybe (CReached IM.empty) (`deleteConstants` cv) (mutated c (fromA ae))) (fromA ae) where hasKnownDeps = not . IS.null $ exprDeps ae `IS.intersection` knownValues cv propagateExpr' :: CVals -> Expr -> Expr propagateExpr' (CReached cv) e = let e' = transformOf template f e in {- Debug.Trace.trace (p e') -} e' where f :: Expr -> Expr f (ValE (Var i)) | Just (CKnown ae _) <- IM.lookup i cv = fromA ae f x = x --p e' = "propagating:\n" ++ show e ++ "\n" ++ show (e'::Expr) propagateExpr' _ _ = panic "propagateExpr'" -- set of identifiers with known values knownValues :: CVals -> IdSet knownValues (CReached cv) = IS.fromList . (\xs -> [ x | (x, CKnown _ _) <- xs]) . IM.toList $ cv knownValues _ = IS.empty -- constant and variable assignment propagation constantsFacts :: Facts Liveness -> Cache -> Graph' -> Facts CVals constantsFacts lfs c g = {- dumpFacts g $ -} foldForward combineConstants f0 (CReached IM.empty) CUnreached g where f0 :: Forward Annot CVals f0 = def { fIf = removeMutated1t , fWhile = removeMutated1t , fDoWhile = removeMutated1t , fSwitch = switched , fReturn = removeMutated1 , fForIn = \_ _ -> removeMutated1t , fSimple = \nid s m -> simple nid s m , fTry = \_ x -> (x, CReached IM.empty, CReached IM.empty) } usedOnce :: NodeId -> Id -> Bool usedOnce nid i = let (Liveness u excep) = lookupFact def nid 0 lfs in IM.lookup i u == Just Once && isNothing (IM.lookup i excep) switched :: NodeId -> AExpr' -> [AExpr'] -> CVals -> ([CVals], CVals) switched _ e es m = let m' = removeMutated e m in (replicate (length es) m', m') simple :: NodeId -> SimpleStat' -> CVals -> CVals simple _ _ CUnreached = CUnreached simple _ (DeclS{}) m = m simple _ (ExprS e) m = removeMutated e m simple nid (AssignS e1 e2) m | (ValE (Var i)) <- fromA e1, (ValE (IntV _)) <- fromA e2 = IM.insert i (CKnown e2 True) %% dc i m' | (ValE (Var i)) <- fromA e1, (ValE (DoubleV _)) <- fromA e2 = IM.insert i (CKnown e2 True) %% dc i m' -- start experimental | (ValE (Var i)) <- fromA e1, (ValE (Var j)) <- fromA e2, Nothing <- vfact j = IM.insert i (CKnown e2 True) %% dc i m' -- end experimental | (ValE (Var i)) <- fromA e1, (ValE (Var j)) <- fromA e2, Just c@(CKnown _ b) <- vfact j , (usedOnce nid i || b) = IM.insert i c {- (CKnown e2 b) -} %% dc i m' | (ValE (Var i)) <- fromA e1, (ApplE (ValE (Var fun)) args) <- fromA e2, isKnownPureFun c fun && usedOnce nid i && i `IS.notMember` (IS.unions $ map exprDeps' args) = IM.insert i (CKnown e2 False) %% dc i m' | (ValE (Var i)) <- fromA e1, not (mightHaveSideeffects' e2) && usedOnce nid i && i `IS.notMember` exprDeps e2 = IM.insert i (CKnown e2 False) %% dc i m' | (ValE (Var i)) <- fromA e1, (SelE (ValE (Var _)) _field) <- fromA e2, not (mightHaveSideeffects' e2) && usedOnce nid i = IM.insert i (CKnown e1 False) %% dc i m' | (ValE (Var i)) <- fromA e1 = dc i m' -- | (IdxE (ValE (Var i)) _) <- fromA e1 = dc i m' -- | (SelE (ValE (Var i)) _) <- fromA e1 = dc i m' | otherwise = removeMutated e1 m' where m' = removeMutated e2 m vfact v = case m' of CUnreached -> Nothing CReached x -> IM.lookup v x tup x = (x,x) removeMutated1t _ s = tup . removeMutated s removeMutated1 _ = removeMutated removeMutated :: Data a => a -> CVals -> CVals removeMutated s = maybe (const $ CReached IM.empty) deleteConstants mut where mut = IS.unions <$> sequence (Just IS.empty : map (mutated c) (s ^.. template)) dc :: Id -> CVals -> CVals dc i m = deleteConstants (IS.singleton i) m -- propagate constants if we have the same from both branches combineConstants :: CVals -> CVals -> CVals combineConstants (CReached m1) (CReached m2) = CReached (IM.mergeWithKey f (const IM.empty) (const IM.empty) m1 m2) where f _ (CKnown x dx) (CKnown y dy) | x == y = Just (CKnown x (dx || dy)) | otherwise = Nothing combineConstants CUnreached x = x combineConstants x _ = x -- all variables referenced by expression exprDeps :: AExpr' -> IdSet exprDeps = aIdents . getAnnot exprDeps' :: Expr -> IdSet exprDeps' e = exprIdents e deleteConstants :: IdSet -> CVals -> CVals deleteConstants s (CReached m) = CReached (IM.filterWithKey f m) where f :: Id -> CFact -> Bool f k _ | k `IS.member` s = False f _ (CKnown ae _) | not . IS.null $ exprDeps ae `IS.intersection` s = False f _ _ = True deleteConstants _ CUnreached = CUnreached -- returns Nothing if it does things that we aren't sure of mutated :: Cache -> Expr -> Maybe IdSet mutated c expr = foldl' f (Just IS.empty) (universeOf tinplate expr) where f :: Maybe IdSet -> Expr -> Maybe IdSet f Nothing _ = Nothing f s (UOpE op (ValE (Var i))) | op `S.member` uOpMutated = IS.insert i <$> s | otherwise = s f s (ApplE (ValE (Var i)) _) | Just m <- knownMutated i = IS.union m <$> s -- f s (SelE {}) = s -- fixme might not be true with properties -- f s (BOpE{}) = s -- f s (IdxE{}) = s f s (ValE{}) = s f _ _ = Nothing knownMutated i | isKnownPureFun c i = Just IS.empty | Just s <- IM.lookup i (cachedKnownFuns c) = Just s knownMutated _ = Nothing uOpMutated = S.fromList [PreInc, PostInc, PreDec, PostDec] mutated' :: Data a => Cache -> a -> Maybe IdSet mutated' c a = IS.unions <$> (mapM (mutated c) $ a ^.. tinplate) -- common RTS functions that we know touch only a few global variables knownFuns :: Graph a -> IntMap IdSet knownFuns g = IM.fromList . catMaybes . map f $ [ ("h$bh", [ "h$r1" ]) ] ++ map (\n -> ("h$p" <> T.pack (show n), ["h$stack", "h$sp"])) [(1::Int)..32] ++ map (\n -> ("h$pp" <> T.pack (show n), ["h$stack", "h$sp"])) [(1::Int)..255] where f (fun, vals) = fmap (,IS.fromList [x | Just x <- map (lookupId g . TxtI) vals]) (lookupId g (TxtI fun)) -- pure RTS functions that we know we can safely move around or remove knownPureFuns :: Graph a -> IdSet knownPureFuns g = IS.fromList $ catMaybes (map (lookupId g) knownPure) where knownPure = map (TxtI . T.pack . ("h$"++)) $ ("c" : map (('c':).show) [(1::Int)..32]) ++ map (('d':).show) [(1::Int)..32] ++ [ "tagToEnum" , "mulInt32" , "mulWord32", "quotWord32", "remWord32" , "popCnt32", "popCnt64" , "bswap64" , "newByteArray", "newArray" , "hs_eqWord64", "hs_neWord64", "hs_leWord64", "hs_ltWord64", "hs_geWord64", "hs_gtWord64" , "hs_eqInt64", "hs_neInt64", "hs_leInt64", "hs_ltInt64", "hs_geInt64", "hs_gtInt64" , "hs_word64ToWord", "hs_int64ToInt" ] isKnownPureFun :: Cache -> Id -> Bool isKnownPureFun c i = IS.member i (cachedKnownPure c) mightHaveSideeffects' :: AExpr' -> Bool mightHaveSideeffects' = aSideEffects . getAnnot mightHaveSideeffects :: Cache -> Expr -> Bool mightHaveSideeffects c e = any f (universeOf template e) where f (ValE{}) = False f (SelE{}) = False -- might be wrong with defineProperty f (IdxE{}) = False f (BOpE{}) = False f (UOpE op _ ) = op `S.member` sideEffectOps f (CondE{}) = False f (ApplE (ValE (Var i)) _) | isKnownPureFun c i = False f _ = True sideEffectOps = S.fromList [DeleteOp, NewOp, PreInc, PostInc, PreDec, PostDec] -- constant folding and other bottom up rewrites foldExpr :: Cache -> Expr -> Expr foldExpr _c = transformOf template f where f (BOpE LOrOp v1 v2) = lorOp v1 v2 f (BOpE LAndOp v1 v2) = landOp v1 v2 f (BOpE op (ValE (IntV i1)) (ValE (IntV i2))) = intInfixOp op i1 i2 f (BOpE op (ValE (DoubleV d1)) (ValE (DoubleV d2))) = doubleInfixOp op d1 d2 f (BOpE op (ValE (IntV x)) (ValE (DoubleV d))) | abs x < 10000 = doubleInfixOp op (fromIntegral x) d -- conservative estimate to prevent loss of precision? f (BOpE op (ValE (DoubleV d)) (ValE (IntV x))) | abs x < 10000 = doubleInfixOp op d (fromIntegral x) f (BOpE AddOp (ValE (StrV s1)) (ValE (StrV s2))) = ValE (StrV (s1<>s2)) f (BOpE AddOp e (ValE (IntV i))) | i < 0 = BOpE SubOp e (ValE (IntV $ negate i)) f (BOpE SubOp e (ValE (IntV i))) | i < 0 = BOpE AddOp e (ValE (IntV $ negate i)) f (UOpE NegOp (ValE (IntV i))) = ValE (IntV $ negate i) f (UOpE NegOp (ValE (DoubleV i))) = ValE (DoubleV $ negate i) f (UOpE NotOp e) | Just b <- exprCond e = eBool (not b) -- y ? a : b === a -> y == true f (BOpE eqOp (CondE c (ValE (IntV v1)) (ValE (IntV v2))) (ValE (IntV v3))) | isEqOp eqOp = f (constIfEq eqOp c v1 v2 v3) f (BOpE eqOp (ValE (IntV v3)) (CondE c (ValE (IntV v1)) (ValE (IntV v2)))) | isEqOp eqOp = f (constIfEq eqOp c v1 v2 v3) f (BOpE eqOp (BOpE relOp x y) (ValE (BoolV b))) | isEqOp eqOp && isBoolOp relOp = f (boolRelEq eqOp relOp x y b) f (BOpE eqOp (ValE (BoolV b)) (BOpE relOp x y)) | isEqOp eqOp && isBoolOp relOp = f (boolRelEq eqOp relOp x y b) f (UOpE NotOp (BOpE eqOp x y)) | isEqOp eqOp = BOpE (negateEqOp eqOp) x y f e = e -- v3 `op` (c ? v1 : v2) constIfEq :: JOp -> Expr -> Integer -> Integer -> Integer -> Expr constIfEq op c v1 v2 v3 | not (neqOp || eqOp) = error ("constIfEq: not an equality operator: " ++ show op) | v1 == v2 = ValE (BoolV $ eqOp == (v1 == v3)) | v3 == v1 = if eqOp then BOpE EqOp c (ValE (BoolV True)) else UOpE NotOp c | v3 == v2 = if eqOp then UOpE NotOp c else BOpE EqOp c (ValE (BoolV True)) | otherwise = ValE (BoolV False) where neqOp = op == NeqOp || op == StrictNeqOp eqOp = op == EqOp || op == StrictEqOp -- only use if rel always produces a bool result boolRelEq :: JOp -> JOp -> Expr -> Expr -> Bool -> Expr boolRelEq eq rel x y b | eq == EqOp || eq == StrictEqOp = if b then BOpE rel x y else UOpE NotOp (BOpE rel x y) boolRelEq eq rel x y b | eq == NeqOp || eq == StrictNeqOp = if not b then BOpE rel x y else UOpE NotOp (BOpE rel x y) boolRelEq op _ _ _ _ = error ("boolRelEq: not an equality operator: " ++ show op) negateEqOp :: JOp -> JOp negateEqOp EqOp = NeqOp negateEqOp NeqOp = EqOp negateEqOp StrictEqOp = StrictNeqOp negateEqOp StrictNeqOp = StrictEqOp negateEqOp op = error ("negateEqOp: not an equality operator: " ++ show op) -- is expression a numeric or string constant? isConst :: Expr -> Bool isConst (ValE (DoubleV _)) = True isConst (ValE (IntV _)) = True isConst (ValE (StrV _)) = True isConst _ = False isVar :: Expr -> Bool isVar (ValE (Var _)) = True isVar _ = False isConstOrVar :: Expr -> Bool isConstOrVar x = isConst x || isVar x normalize :: Bool -> Cache -> Graph' -> Expr -> Expr normalize True = normalizeCond normalize _ = normalizeReg -- somewhat stronger normalize for expressions in conditions where the -- top level is forced to be bool -- if(x == true) -> if(x) -- if(c ? 1 : 0) -> if(c) normalizeCond :: Cache -> Graph' -> Expr -> Expr normalizeCond c g e = go0 e where go0 e = go (normalizeReg c g e) go e | Just b <- exprCond e = ValE (BoolV b) go (BOpE op (ValE (BoolV b)) e) | (op == EqOp && b) || (op == NeqOp && not b) = go0 e go (BOpE op e (ValE (BoolV b))) | (op == EqOp && b) || (op == NeqOp && not b) = go0 e go (CondE c e1 e2) | Just True <- exprCond e1, Just False <- exprCond e2 = go0 c go e = e normalizeReg :: Cache -> Graph' -> Expr -> Expr normalizeReg cache g = rewriteOf template assoc . rewriteOf template comm . foldExpr cache where comm :: Expr -> Maybe Expr comm e | not (allowed e) = Nothing comm (BOpE op e1 e2) | commutes op && isConst e1 && not (isConst e2) || commutes op && isVar e1 && not (isConstOrVar e2) = f (BOpE op e2 e1) comm (BOpE op1 e1 (BOpE op2 e2 e3)) | op1 == op2 && commutes op1 && isConst e1 && not (isConst e2) || op1 == op2 && commutes op1 && isVar e1 && not (isConstOrVar e2) || commutes2a op1 op2 && isConst e1 && not (isConst e2) || commutes2a op1 op2 && isVar e1 && not (isConstOrVar e2) = f (BOpE op1 e2 (BOpE op2 e1 e3)) comm _ = Nothing assoc :: Expr -> Maybe Expr assoc e | not (allowed e) = Nothing assoc (BOpE op1 (BOpE op2 e1 e2) e3) | op1 == op2 && associates op1 = f (BOpE op1 e1 (cf $ BOpE op1 e2 e3)) | associates2a op1 op2 = f (BOpE op2 e1 (cf $ BOpE op1 e2 e3)) | associates2b op1 op2 = f (BOpE op1 e1 (cf $ BOpE op2 e3 e2)) assoc _ = Nothing commutes op = op `elem` [AddOp] -- ["*", "+"] -- a * b = b * a commutes2a op1 op2 = (op1,op2) `elem` [(AddOp, SubOp)] -- ,("*", "/")] -- a + (b - c) = b + (a - c) associates op = op `elem` [AddOp] -- ["*", "+"] -- (a * b) * cv = a * (b * c) associates2a op1 op2 = (op1,op2) `elem` [(SubOp, AddOp)] -- , ("/", "*")] -- (a + b) - c = a + (b - c) -- (a*b)/c = a*(b/c) associates2b op1 op2 = (op1,op2) `elem` [(AddOp, SubOp)] -- , ("*", "/")] -- (a - b) + c = a + (c - b) cf = rewriteOf template comm . foldExpr cache f = Just . foldExpr cache allowed e | IdxE (ValE (Var st)) e' <- e, Just st == stack = allowed' e' | otherwise = allowed' e where allowed' e = IS.null (exprDeps' e IS.\\ x) && all isSmall (e ^.. tinplate) stack = lookupId g (TxtI "h$stack") sp = lookupId g (TxtI "h$sp") x = IS.fromList $ catMaybes [sp] isSmall (DoubleV (SaneDouble d)) = abs d < 10000 isSmall (IntV x) = abs x < 10000 isSmall (StrV _) = False isSmall _ = True lorOp :: Expr -> Expr -> Expr lorOp e1 e2 | Just b <- exprCond e1 = if b then eBool True else e2 lorOp e1 e2 = BOpE LOrOp e1 e2 landOp :: Expr -> Expr -> Expr landOp e1 e2 | Just b <- exprCond e1 = if b then e2 else eBool False landOp e1 e2 = BOpE LAndOp e1 e2 -- if expression is used in a condition, can we statically determine its result? exprCond :: Expr -> Maybe Bool exprCond (ValE (IntV x)) = Just (x /= 0) exprCond (ValE (DoubleV x)) = Just (x /= 0) exprCond (ValE (StrV xs)) = Just (not $ T.null xs) exprCond (ValE (BoolV b)) = Just b exprCond (ValE NullV) = Just False exprCond (ValE UndefinedV) = Just False exprCond _ = Nothing exprCond' :: AExpr a -> Maybe Bool exprCond' = exprCond . fromA -- constant folding and other bottom up rewrites intInfixOp :: JOp -> Integer -> Integer -> Expr intInfixOp AddOp i1 i2 = ValE (IntV (i1+i2)) intInfixOp SubOp i1 i2 = ValE (IntV (i1-i2)) intInfixOp MulOp i1 i2 = ValE (IntV (i1*i2)) intInfixOp DivOp i1 i2 | i2 /= 0 && d * i2 == i1 = ValE (IntV d) where d = i1 `div` i2 intInfixOp ModOp i1 i2 = ValE (IntV (i1 `mod` i2)) -- not rem? intInfixOp LeftShiftOp i1 i2 = bitwiseInt' shiftL i1 (i2 .&. 31) intInfixOp RightShiftOp i1 i2 = bitwiseInt' shiftR i1 (i2 .&. 31) intInfixOp ZRightShiftOp i1 i2 = bitwiseWord shiftR i1 (i2 .&. 31) intInfixOp BAndOp i1 i2 = bitwiseInt (.&.) i1 i2 intInfixOp BOrOp i1 i2 = bitwiseInt (.|.) i1 i2 intInfixOp BXorOp i1 i2 = bitwiseInt xor i1 i2 intInfixOp GtOp i1 i2 = eBool (i1 > i2) intInfixOp LtOp i1 i2 = eBool (i1 < i2) intInfixOp LeOp i1 i2 = eBool (i1 <= i2) intInfixOp GeOp i1 i2 = eBool (i1 >= i2) intInfixOp StrictEqOp i1 i2 = eBool (i1 == i2) intInfixOp StrictNeqOp i1 i2 = eBool (i1 /= i2) intInfixOp EqOp i1 i2 = eBool (i1 == i2) intInfixOp NeqOp i1 i2 = eBool (i1 /= i2) intInfixOp op i1 i2 = BOpE op (ValE (IntV i1)) (ValE (IntV i2)) doubleInfixOp :: JOp -> SaneDouble -> SaneDouble -> Expr doubleInfixOp AddOp (SaneDouble d1) (SaneDouble d2) = ValE (DoubleV $ SaneDouble (d1+d2)) doubleInfixOp SubOp (SaneDouble d1) (SaneDouble d2) = ValE (DoubleV $ SaneDouble (d1-d2)) doubleInfixOp MulOp (SaneDouble d1) (SaneDouble d2) = ValE (DoubleV $ SaneDouble (d1*d2)) doubleInfixOp DivOp (SaneDouble d1) (SaneDouble d2) = ValE (DoubleV $ SaneDouble (d1/d2)) doubleInfixOp GtOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 > d2) doubleInfixOp LtOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 < d2) doubleInfixOp LeOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 <= d2) doubleInfixOp GeOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 >= d2) doubleInfixOp StrictEqOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 == d2) doubleInfixOp StrictNeqOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 /= d2) doubleInfixOp EqOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 == d2) doubleInfixOp NeqOp (SaneDouble d1) (SaneDouble d2) = eBool (d1 /= d2) doubleInfixOp op d1 d2 = BOpE op (ValE (DoubleV d1)) (ValE (DoubleV d2)) bitwiseInt :: (Int32 -> Int32 -> Int32) -> Integer -> Integer -> Expr bitwiseInt op i1 i2 = let i = fromIntegral i1 `op` fromIntegral i2 in ValE (IntV $ fromIntegral i) bitwiseInt' :: (Int32 -> Int -> Int32) -> Integer -> Integer -> Expr bitwiseInt' op i1 i2 = let i = fromIntegral i1 `op` fromIntegral i2 in ValE (IntV $ fromIntegral i) bitwiseWord :: (Word32 -> Int -> Word32) -> Integer -> Integer -> Expr bitwiseWord op i1 i2 = let i = fromIntegral i1 `op` fromIntegral i2 i' :: Int32 i' = fromIntegral i in ValE (IntV $ fromIntegral i') ----------------------------------------------------------- -- stack and stack pointer magic ----------------------------------------------------------- data StackFacts = SFUnknownB | SFOffset Integer | SFUnknownT deriving (Eq, Ord, Show, Data, Typeable) sfKnown :: StackFacts -> Bool sfKnown (SFOffset _) = True sfKnown _ = False sfUnknown :: StackFacts -> Bool sfUnknown = not . sfKnown propagateStack :: IdSet -> IdSet -> Cache -> Graph' -> Graph' propagateStack _args _locals c g | nrets > 4 || stackAccess < nrets - 1 || stackAccess == 0 = g | otherwise = g' where stackI = fromMaybe (-1) (lookupId g (TxtI "h$stack")) spI = fromMaybe (-2) (lookupId g (TxtI "h$sp")) z = SFOffset 0 allNodes = IM.elems (g ^. nodes) nrets = length [() | (ReturnNode{}) <- allNodes] stackAccess = length $ filter (stackI `IS.member`) (map exprDeps (allNodes ^.. template)) sf = stackFacts c g g' :: Graph' g' = normalizeAnnot c $ foldl' (\g (k,v) -> updNode k v g) g (IM.toList $ g^.nodes) updNode :: NodeId -> Node' -> Graph' -> Graph' updNode nid e@(IfNode _ n1 _) g | known nid && unknown n1 = replace nid e g updNode nid e@(WhileNode _ n1) g | known nid && unknown n1 = replace nid e g updNode nid e@(ForInNode _ _ _ n1) g | known nid && unknown n1 = replace nid e g updNode nid e@(SwitchNode _ _ n1) g | known nid && unknown n1 = replace nid e g updNode nid e@(TryNode _ _ _ _) g | known nid = replace nid e g updNode nid e@(ReturnNode{}) g | known nid = replace nid e g updNode nid e@(SimpleNode{}) g | known nid && sfUnknown (lookupFact SFUnknownB nid 1 sf) = replace nid e g -- fixme is this right? updNode nid (SimpleNode{}) g | SFOffset x <- lookupFact SFUnknownB nid 0 sf, SFOffset y <- lookupFact SFUnknownB nid 1 sf, x /= y = nodes %~ IM.insert nid (SequenceNode []) $ g updNode nid n g = updExprs nid n g updExprs :: NodeId -> Node' -> Graph' -> Graph' updExprs nid n g | SFOffset offset <- lookupFact z nid 2 sf = let n' = (tinplate %~ updExpr offset) n in nodes %~ IM.insert nid n' $ g | otherwise = g updExpr :: Integer -> Expr -> Expr updExpr 0 e = e updExpr n e = transformOf tinplate sp e where sp e@(ValE (Var i)) | i == spI = BOpE AddOp e (ValE (IntV n)) sp e = e known :: NodeId -> Bool known nid = sfKnown (lookupFact SFUnknownB nid 0 sf) unknown :: NodeId -> Bool unknown = not . known replace :: NodeId -> Node' -> Graph' -> Graph' replace nid n g | SFOffset x <- lookupFact SFUnknownB nid 0 sf, x /= 0 = let newId = g^.nodeid sp = ValE (Var spI) newNodes = IM.fromList [ (nid, SequenceNode [newId, newId+1]) , (newId, SimpleNode (AssignS (annotate c sp) (annotate c . normalize False c g $ BOpE AddOp sp (ValE (IntV x))))) , (newId+1, n) ] in (nodeid %~ (+2)) . (nodes %~ IM.union newNodes) $ g | otherwise = g stackFacts :: Cache -> Graph' -> Facts StackFacts stackFacts c g = foldForward combineStack f0 (SFOffset 0) SFUnknownB g where -- stackI = fromMaybe (-1) (lookupId g (TxtI "h$stack")) spI = fromMaybe (-2) (lookupId g (TxtI "h$sp")) f0 = def { fIf = updSfT , fWhile = updSfT , fDoWhile = updSfT , fSwitch = switched , fReturn = updSf1 , fForIn = \_ _ -> updSfT , fSimple = simple , fTry = \_ _ -> (SFUnknownT, SFUnknownT, SFUnknownT) } updSfT _ e sf = tup (updSf e sf) updSf1 _ = updSf updSf :: AExpr' -> StackFacts -> StackFacts updSf _ SFUnknownT = SFUnknownT updSf e sf | Just m <- mutated c (fromA e), spI `IS.notMember` m = sf | otherwise = SFUnknownT updSf' :: SimpleStat' -> StackFacts -> StackFacts updSf' _ SFUnknownT = SFUnknownT updSf' (DeclS {}) sf = sf updSf' (ExprS e) sf | Just s <- mutated c (fromA e), spI `IS.notMember` s = sf updSf' (AssignS e1 e2) sf | Just s1 <- mutated c (fromA e1), Just s2 <- mutated c (fromA e2), spI `IS.notMember` s1 && spI `IS.notMember` s2 = sf updSf' _ _ = SFUnknownT switched :: NodeId -> AExpr' -> [AExpr'] -> StackFacts -> ([StackFacts], StackFacts) switched _ e es sf = let sf' = updSf e sf in (replicate (length es) sf', sf') adjSf :: Integer -> StackFacts -> StackFacts adjSf n (SFOffset x) = SFOffset (x+n) adjSf _ _ = SFUnknownT adjSfE :: AExpr' -> StackFacts -> StackFacts adjSfE e sf | (ValE (Var i)) <- fromA e, i == spI = sf | (BOpE op (ValE (Var i)) (ValE (IntV x))) <- fromA e, i == spI = case op of AddOp -> adjSf x sf SubOp -> adjSf (-x) sf _ -> SFUnknownT | otherwise = SFUnknownT simple :: NodeId -> SimpleStat' -> StackFacts -> StackFacts simple _nid (ExprS (AExpr _ (UOpE op (ValE (Var i))))) | i == spI && op == PreInc = adjSf 1 | i == spI && op == PreDec = adjSf (-1) | i == spI && op == PostInc = adjSf 1 | i == spI && op == PostDec = adjSf (-1) simple _nid (AssignS (AExpr _ (ValE (Var i))) e) | i == spI = adjSfE e simple _nid s = updSf' s combineStack :: StackFacts -> StackFacts -> StackFacts combineStack SFUnknownT _ = SFUnknownT combineStack _ SFUnknownT = SFUnknownT combineStack SFUnknownB x = x combineStack x SFUnknownB = x combineStack ox@(SFOffset x) (SFOffset y) | x == y = ox | otherwise = SFUnknownT -- apply the rewriter to the expressions in this node -- first argument is true when the expression is used in a boolean condition rewriteNodeExprs :: (Bool -> AExpr' -> AExpr') -> Node' -> Node' rewriteNodeExprs f (SimpleNode s) = SimpleNode (rewriteSimpleStatExprs (f False) s) rewriteNodeExprs f (IfNode e s1 s2) = IfNode (f True e) s1 s2 rewriteNodeExprs f (WhileNode e i) = WhileNode (f True e) i rewriteNodeExprs f (DoWhileNode e i) = DoWhileNode (f True e) i rewriteNodeExprs f (ForInNode b i e s ) = ForInNode b i (f False e) s rewriteNodeExprs f (SwitchNode e cs i) = SwitchNode (f False e) (cs & traverse . _1 %~ f False) i rewriteNodeExprs f (ReturnNode e) = ReturnNode (f False e) rewriteNodeExprs _ n = n -- other nodes don't contain expressions rewriteSimpleStatExprs :: (AExpr' -> AExpr') -> SimpleStat' -> SimpleStat' rewriteSimpleStatExprs f (ExprS e) = ExprS (f e) rewriteSimpleStatExprs f (AssignS e1 e2) = AssignS (f e1) (f e2) rewriteSimpleStatExprs _ s = s -- optimize sequences of assignments: -- h$r3 = x -- h$r2 = y -- h$r1 = z -- -> h$l3(x,y,z) -- (only if y,z don't refer to the new value of h$r3) optimizeSequences :: Cache -> Graph' -> Graph' optimizeSequences c g0 = foldl' transformNodes g (IM.elems $ g ^. nodes) where (ls, g1) = addIdents (map (assignRegs'!) [1..32]) g0 g = flattenSequences g1 transformNodes :: Graph' -> Node' -> Graph' transformNodes g' (SequenceNode xs) = let xs' = f (map (\nid -> fromMaybe (error $ "optimizeSequences, invalid node: " ++ show nid) (IM.lookup nid $ g ^. nodes)) xs) in foldr (\(nid,n) -> nodes %~ IM.insert nid n) g' (zip xs xs') transformNodes g' _ = g' regN :: IntMap Int regN = IM.fromList . catMaybes $ map (\r -> (,1 + fromEnum r) <$> lookupId g (registersI!r)) (enumFromTo R1 R32) reg x = IM.lookup x regN regBetween :: Int -> Int -> Int -> Bool regBetween x y r = maybe False (\n -> n >= x && n <= y) (IM.lookup r regN) f :: [Node'] -> [Node'] f (x@(SimpleNode (AssignS (AExpr _ (ValE (Var r))) e)):xs) | Just n <- reg r, n > 1 && not (mightHaveSideeffects' e) = f' (n-1) n [(fromA e,x)] xs f (x:xs) = x : f xs f [] = [] f' :: Int -> Int -> [(Expr, Node')] -> [Node'] -> [Node'] f' 0 start exprs xs = mkAssign exprs : replicate (start-1) (SequenceNode []) ++ f xs f' n start exprs (x@(SimpleNode (AssignS ae@(AExpr _ (ValE (Var r))) e)):xs) | Just k <- reg r, k == n && not (mightHaveSideeffects' e) && not (F.any (regBetween (k+1) start) (IS.toList $ exprDeps ae)) = f' (n-1) start ((fromA e,x):exprs) xs f' _ _start exprs xs = map snd (reverse exprs) ++ f xs mkAssign :: [(Expr, Node')] -> Node' mkAssign xs = SimpleNode (ExprS . annotate c $ ApplE (ValE (Var i)) (reverse $ map fst xs)) where i = ls !! (length xs - 1) flattenSequences :: Graph' -> Graph' flattenSequences g = g & nodes %~ (\n -> foldl' flatten n (IM.toList n)) where flatten :: IntMap Node' -> (NodeId, Node') -> IntMap Node' flatten ns (nid, SequenceNode xs) = case IM.lookup nid ns of Nothing -> ns -- already removed Just _ -> let (xs', ns') = foldl' f ([], ns) xs in IM.insert nid (SequenceNode $ reverse xs') ns' flatten ns _ = ns f :: ([NodeId], IntMap Node') -> NodeId -> ([NodeId], IntMap Node') f (xs, ns) nid | Just (SequenceNode ys) <- IM.lookup nid ns = let (xs', ns') = foldl' f (xs, ns) ys in (xs', IM.delete nid ns') | otherwise = (nid : xs, ns) -------------------------------------------------------------------------- -- some debugging things, remove later or add proper reporting mechanism -------------------------------------------------------------------------- {- dumpLive :: Graph' -> Facts Liveness -> Facts Liveness dumpLive g l@(Facts l0) = Debug.Trace.trace (show g ++ "\n" ++ l') l where l' = concatMap f (M.toList l0) f ((nid,0),v) = show nid ++ " -> " ++ showLive g v ++ "\n" f _ = "" dumpFacts :: Graph' -> Facts CVals -> Facts CVals dumpFacts g c@(Facts c0) = Debug.Trace.trace ({- show g ++ "\n" ++ -} c') c where c' = concatMap f (M.toList c0) f ((nid,0),v) = show nid ++ " -> " ++ showCons g v ++ "\n" f _ = "" showLive :: Graph' -> Liveness -> String showLive gr (Liveness l le) = "live: " ++ f l ++ " excep: " ++ f le where f im = L.intercalate ", " $ map g (IM.toList im) g (i,u) = show i ++ ":" ++ showId gr i ++ ":" ++ show u showId :: Graph' -> Id -> String showId g i = case lookupIdent g i of Nothing -> "<unknown>" Just (TxtI i') -> T.unpack i' showCons :: Graph' -> CVals -> String showCons g CUnreached = "<unreached>" showCons g (CReached imf) = "\n" ++ (L.unlines $ map (\x -> " " ++ f x) (IM.toList imf)) where f (i,v) = showId g i ++ ":" ++ show v -}
beni55/ghcjs
src/Gen2/Optimizer.hs
mit
47,153
0
24
14,258
17,288
8,706
8,582
-1
-1
{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} module T12245 where import Data.Data ( Data ) data Foo f = Foo (f Bool) (f Int) deriving instance Data (Foo []) deriving instance Data (Foo Maybe)
sgillespie/ghc
testsuite/tests/deriving/should_compile/T12245.hs
bsd-3-clause
258
0
8
43
71
40
31
8
0
-- Transformation stress test {-# OPTIONS_GHC -XMonadComprehensions -XTransformListComp #-} module Main where import Data.List(takeWhile) import GHC.Exts(sortWith) employees = [ ("Simon", "MS", 80) , ("Erik", "MS", 100) , ("Phil", "Ed", 40) , ("Gordon", "Ed", 45) , ("Paul", "Yale", 60)] main = putStrLn (show output) where output = [ (dept, salary) | (name, dept, salary) <- employees , then sortWith by salary , then filter by salary > 50 , then take 1 ]
hferreiro/replay
testsuite/tests/deSugar/should_run/mc02.hs
bsd-3-clause
569
0
11
184
173
103
70
15
1
{-# LANGUAGE NamedFieldPuns #-} module NotGate where import Types notGate :: Literal -> Literal notGate (Constant b) = Constant $ not b notGate Input {keys, keyState} = Input keys changed where changed = do a' <- keyState case a' of Producer a0 a1 -> return $ Producer a1 a0 Consumer x -> return $ Consumer x rec@Counter {notCount = n} -> return $ rec{notCount = n + 1}
ur-crypto/sec-lib
library/NotGate.hs
mit
425
0
15
123
151
77
74
13
3
{-# LANGUAGE DeriveGeneric, CPP #-} module Data.KdMap.Dynamic ( -- * Usage -- $usage -- * Reference -- ** Types PointAsListFn , SquaredDistanceFn , KdMap -- ** Dynamic /k/-d map construction , empty , singleton , emptyWithDist , singletonWithDist -- ** Insertion , insert , insertPair , batchInsert -- ** Query , nearest , inRadius , kNearest , inRange , assocs , keys , elems , null , size -- ** Folds , foldrWithKey -- ** Utilities , defaultSqrDist -- ** Internal (for testing) , subtreeSizes ) where import Prelude hiding (null) #if MIN_VERSION_base(4,8,0) #else import Control.Applicative hiding (empty) import Data.Foldable import Data.Traversable #endif import Data.Bits import Data.Function import Data.List as L hiding (insert, null) import qualified Data.List (null) import Control.DeepSeq import Control.DeepSeq.Generics (genericRnf) import GHC.Generics import qualified Data.KdMap.Static as KDM import Data.KdMap.Static (PointAsListFn, SquaredDistanceFn, defaultSqrDist) -- $usage -- -- The 'KdMap' is a variant of -- @Data.KdTree.Dynamic.@'Data.KdTree.Dynamic.KdTree' where each point -- in the tree is associated with some data. It is the dynamic variant -- of @Data.KdMap.Static.@'Data.KdMap.Static.KdMap'. -- -- Here's an example of interleaving point-value insertions and point -- queries using 'KdMap', where points are 3D points and values are -- 'String's: -- -- @ -- >>> let dkdm = 'singleton' point3dAsList ((Point3D 0.0 0.0 0.0), \"First\") -- -- >>> let dkdm' = 'insert' dkdm ((Point3D 1.0 1.0 1.0), \"Second\") -- -- >>> 'nearest' dkdm' (Point3D 0.4 0.4 0.4) -- (Point3D {x = 0.0, y = 0.0, z = 0.0}, \"First\") -- -- >>> let dkdm'' = 'insert' dkdm' ((Point3D 0.5 0.5 0.5), \"Third\") -- -- >>> 'nearest' dkdm'' (Point3D 0.4 0.4 0.4) -- (Point3D {x = 0.5, y = 0.5, z = 0.5}, \"Third\") -- @ -- | A dynamic /k/-d tree structure that stores points of type @p@ -- with axis values of type @a@. Additionally, each point is -- associated with a value of type @v@. data KdMap a p v = KdMap { _trees :: [KDM.KdMap a p v] , _pointAsList :: PointAsListFn a p , _distSqr :: SquaredDistanceFn a p , _numNodes :: Int } deriving Generic instance (NFData a, NFData p, NFData v) => NFData (KdMap a p v) where rnf = genericRnf instance (Show a, Show p, Show v) => Show (KdMap a p v) where show kdm = "KdMap " ++ show (_trees kdm) instance Functor (KdMap a p) where fmap f dkdMap = dkdMap { _trees = map (fmap f) $ _trees dkdMap } -- | Performs a foldr over each point-value pair in the 'KdMap'. foldrWithKey :: ((p, v) -> b -> b) -> b -> KdMap a p v -> b foldrWithKey f z dkdMap = L.foldr (flip $ KDM.foldrWithKey f) z $ _trees dkdMap instance Foldable (KdMap a p) where foldr f = foldrWithKey (f . snd) instance Traversable (KdMap a p) where traverse f (KdMap t p d n) = KdMap <$> traverse (traverse f) t <*> pure p <*> pure d <*> pure n -- | Generates an empty 'KdMap' with a user-specified distance function. emptyWithDist :: PointAsListFn a p -> SquaredDistanceFn a p -> KdMap a p v emptyWithDist p2l d2 = KdMap [] p2l d2 0 -- | Returns whether the 'KdMap' is empty. null :: KdMap a p v -> Bool null (KdMap [] _ _ _) = True null _ = False -- | Generates a 'KdMap' with a single point-value pair using a -- user-specified distance function. singletonWithDist :: Real a => PointAsListFn a p -> SquaredDistanceFn a p -> (p, v) -> KdMap a p v singletonWithDist p2l d2 (k, v) = KdMap [KDM.buildWithDist p2l d2 [(k, v)]] p2l d2 1 -- | Generates an empty 'KdMap' with the default distance function. empty :: Real a => PointAsListFn a p -> KdMap a p v empty p2l = emptyWithDist p2l $ defaultSqrDist p2l -- | Generates a 'KdMap' with a single point-value pair using the -- default distance function. singleton :: Real a => PointAsListFn a p -> (p, v) -> KdMap a p v singleton p2l = singletonWithDist p2l $ defaultSqrDist p2l -- | Adds a given point-value pair to a 'KdMap'. -- -- Average time complexity per insert for /n/ inserts: /O(log^2(n))/. insert :: Real a => KdMap a p v -> p -> v -> KdMap a p v insert (KdMap trees p2l d2 n) k v = let bitList = map ((1 .&.) . (n `shiftR`)) [0..] (onesPairs, theRestPairs) = span ((== 1) . fst) $ zip bitList trees ((_, ones), (_, theRest)) = (unzip onesPairs, unzip theRestPairs) newTree = KDM.buildWithDist p2l d2 $ (k, v) : L.concatMap KDM.assocs ones in KdMap (newTree : theRest) p2l d2 $ n + 1 -- | Same as 'insert', but takes point and value as a pair. insertPair :: Real a => KdMap a p v -> (p, v) -> KdMap a p v insertPair t = uncurry (insert t) -- | Given a 'KdMap' and a query point, returns the point-value pair in -- the 'KdMap' with the point nearest to the query. -- -- Average time complexity: /O(log^2(n))/. nearest :: Real a => KdMap a p v -> p -> (p, v) nearest (KdMap ts _ d2 _) query = let nearests = map (`KDM.nearest` query) ts in if Data.List.null nearests then error "Called nearest on empty KdMap." else L.minimumBy (compare `on` (d2 query . fst)) nearests -- | Given a 'KdMap', a query point, and a number @k@, returns the -- @k@ point-value pairs with the nearest points to the query. -- -- Neighbors are returned in order of increasing distance from query -- point. -- -- Average time complexity: /log(k) * log^2(n)/ for /k/ nearest -- neighbors on a structure with /n/ data points. -- -- Worst case time complexity: /n * log(k)/ for /k/ nearest neighbors -- on a structure with /n/ data points. kNearest :: Real a => KdMap a p v -> Int -> p -> [(p, v)] kNearest (KdMap trees _ d2 _) k query = let neighborSets = map (\t -> KDM.kNearest t k query) trees in take k $ L.foldr merge [] neighborSets where merge [] ys = ys merge xs [] = xs merge xs@(x:xt) ys@(y:yt) | distX <= distY = x : merge xt ys | otherwise = y : merge xs yt where distX = d2 query $ fst x distY = d2 query $ fst y -- | Given a 'KdMap', a query point, and a radius, returns all -- point-value pairs in the 'KdTree' with points within the given -- radius of the query point. -- -- Points are not returned in any particular order. -- -- Worst case time complexity: /O(n)/ for /n/ data points. inRadius :: Real a => KdMap a p v -> a -> p -> [(p, v)] inRadius (KdMap trees _ _ _) radius query = L.concatMap (\t -> KDM.inRadius t radius query) trees -- | Finds all point-value pairs in a 'KdMap' with points within a -- given range, where the range is specified as a set of lower and -- upper bounds. -- -- Points are not returned in any particular order. -- -- Worst case time complexity: /O(n)/ for n data points and a range -- that spans all the points. inRange :: Real a => KdMap a p v -> p -- ^ lower bounds of range -> p -- ^ upper bounds of range -> [(p, v)] -- ^ point-value pairs within given -- range inRange (KdMap trees _ _ _) lowers uppers = L.concatMap (\t -> KDM.inRange t lowers uppers) trees -- | Returns the number of elements in the 'KdMap'. -- -- Time complexity: /O(1)/ size :: KdMap a p v -> Int size (KdMap _ _ _ n) = n -- | Returns a list of all the point-value pairs in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. assocs :: KdMap a p v -> [(p, v)] assocs (KdMap trees _ _ _) = L.concatMap KDM.assocs trees -- | Returns all points in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. keys :: KdMap a p v -> [p] keys = map fst . assocs -- | Returns all values in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. elems :: KdMap a p v -> [v] elems = map snd . assocs -- | Inserts a list of point-value pairs into the 'KdMap'. -- -- TODO: This will be made far more efficient than simply repeatedly -- inserting. batchInsert :: Real a => KdMap a p v -> [(p, v)] -> KdMap a p v batchInsert = L.foldl' insertPair -- | Returns size of each internal /k/-d tree that makes up the -- dynamic structure. For internal testing use. subtreeSizes :: KdMap a p v -> [Int] subtreeSizes (KdMap trees _ _ _) = map KDM.size trees
ScrambledEggsOnToast/kdt
lib-src/Data/KdMap/Dynamic.hs
mit
8,505
0
13
2,164
2,041
1,114
927
118
3
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} #if __GLASGOW_HASKELL__ >= 806 {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeApplications #-} #endif #include "ghc-compat.h" {- This seems to work. But it is a hack! A 10-line patch extending the GHC-API would make that go away -} module HsToCoq.Util.GHC.Deriving (initForDeriving, addDerivedInstances) where import GHC #if __GLASGOW_HASKELL__ >= 808 import GhcPlugins (SourceText(NoSourceText), PromotionFlag(NotPromoted)) #else import GhcPlugins (SourceText(NoSourceText)) #endif import Control.Monad import Outputable import TcRnMonad import TcEnv import InstEnv import Var import TyCoRep import TyCon import Type import TcType import HscTypes import TcInstDcls import Module import SrcLoc import FastString import GHC.IO (throwIO) import DynFlags import qualified GHC.LanguageExtensions as LangExt -- We need to allow IncoherentInstances for the hack in HsToCoq.Util.GHC.Deriving initForDeriving :: GhcMonad m => m () initForDeriving = void $ getSessionDynFlags >>= setSessionDynFlags . (`xopt_set` LangExt.IncoherentInstances) addDerivedInstances :: GhcMonad m => TypecheckedModule -> m TypecheckedModule addDerivedInstances tcm = do let Just (hsgroup, a, b, c) = tm_renamed_source tcm (_gbl_env, inst_infos, _rn_binds) <- initTcHack tcm $ do let tcg_env = fst (tm_internals_ tcm) tcg_env_hack = tcg_env { tcg_mod = fakeDerivingMod, tcg_semantic_mod = fakeDerivingMod } -- Set the module to make it look like we are in GHCi -- so that GHC will allow us to re-typecheck existing instances setGblEnv tcg_env_hack $ #if __GLASGOW_HASKELL__ >= 810 tcInstDeclsDeriv [] (hs_derivds hsgroup) #else tcInstDeclsDeriv [] (hs_tyclds hsgroup >>= group_tyclds) (hs_derivds hsgroup) #endif let inst_decls = map instInfoToDecl $ inst_infos #if __GLASGOW_HASKELL__ >= 806 let mkTyClGroup decls instds = TyClGroup { group_ext = NOEXT , group_tyclds = decls , group_roles = [] #if __GLASGOW_HASKELL__ >= 810 , group_kisigs = [] #endif , group_instds = instds } #endif let hsgroup' = hsgroup { hs_tyclds = mkTyClGroup [] inst_decls : hs_tyclds hsgroup } return $ tcm { tm_renamed_source = Just (hsgroup', a, b, c) } initTcHack :: GhcMonad m => TypecheckedModule -> TcM a -> m a initTcHack tcm action = do hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts (pm_mod_summary (tm_parsed_module tcm)) } let mod = fakeDerivingMod -- let mod = icInteractiveModule (hsc_IC hsc_env) let src_span = realSrcLocSpan (mkRealSrcLoc (fsLit "<deriving>") 1 1) (msgs, mba) <- liftIO $ initTc hsc_env_tmp HsSrcFile False mod src_span action case mba of Just x -> return x Nothing -> liftIO $ throwIO $ mkSrcErr $ snd msgs fakeDerivingMod :: Module fakeDerivingMod = mkModule interactiveUnitId (mkModuleName "Deriving") instInfoToDecl :: InstInfo GhcRn -> LInstDecl GhcRn instInfoToDecl inst_info = noLoc $ ClsInstD NOEXT (ClsInstDecl { cid_binds = ib_binds (iBinds inst_info) , cid_sigs = [] , cid_tyfam_insts = [] , cid_datafam_insts = [] , cid_overlap_mode = Nothing #if __GLASGOW_HASKELL__ >= 808 , cid_poly_ty = HsIB @GhcRn tvars_ (noLoc (HsQualTy NOEXT (noLoc ctxt) inst_head)) #elif __GLASGOW_HASKELL__ == 806 , cid_poly_ty = HsIB @GhcRn (HsIBRn tvars_ True) (noLoc (HsQualTy NOEXT (noLoc ctxt) inst_head)) #else , cid_poly_ty = HsIB tvars_ (noLoc (HsQualTy (noLoc ctxt) inst_head)) True #endif #if __GLASGOW_HASKELL__ >= 806 , cid_ext = NOEXT #endif }) where (tvars, theta, cls, args) = instanceSig (iSpec inst_info) tvars_ :: [Name] tvars_ = map tyVarName tvars ctxt = map typeToLHsType' theta inst_head = foldl lHsAppTy (noLoc (HsTyVar NOEXT NotPromoted (noLoc (getName cls)))) $ map typeToLHsType' args lHsAppTy f x = noLoc (HsAppTy NOEXT f x) -- Taken from HsUtils. We need it to produce a Name, not a RdrName typeToLHsType' :: Type -> LHsType GhcRn typeToLHsType' ty = go ty where go :: Type -> LHsType GhcRn go ty@(FunTy {}) | (arg, res) <- splitFunTy ty = if isPredTy arg then let (theta, tau) = tcSplitPhiTy ty in noLoc (HsQualTy { hst_ctxt = noLoc (map go theta) , hst_body = go tau #if __GLASGOW_HASKELL__ >= 806 , hst_xqual = NOEXT #endif }) else nlHsFunTy (go arg) (go res) go ty@(ForAllTy {}) | (tvs, tau) <- tcSplitForAllTys ty = noLoc (HsForAllTy { hst_bndrs = map go_tv tvs , hst_body = go tau #if __GLASGOW_HASKELL__ >= 806 , hst_xforall = NOEXT #endif #if __GLASGOW_HASKELL__ >= 810 , hst_fvf = ForallInvis #endif }) go (TyVarTy tv) = nlHsTyVar (getName tv) go (AppTy t1 t2) = nlHsAppTy (go t1) (go t2) go (LitTy (NumTyLit n)) = noLoc $ HsTyLit NOEXT (HsNumTy NoSourceText n) go (LitTy (StrTyLit s)) = noLoc $ HsTyLit NOEXT (HsStrTy NoSourceText s) go ty@(TyConApp tc args) | any isInvisibleTyConBinder (tyConBinders tc) -- We must produce an explicit kind signature here to make certain -- programs kind-check. See Note [Kind signatures in typeToLHsType]. = noLoc $ HsKindSig NOEXT lhs_ty (go (Type.typeKind ty)) | otherwise = lhs_ty where lhs_ty = nlHsTyConApp (getName tc) (map go args') args' = filterOutInvisibleTypes tc args go (CastTy ty _) = go ty go (CoercionTy co) = pprPanic "toLHsSigWcType" (ppr co) -- Source-language types have _invisible_ kind arguments, -- so we must remove them here (Trac #8563) go_tv :: TyVar -> LHsTyVarBndr GhcRn go_tv tv = noLoc $ KindedTyVar NOEXT (noLoc (getName tv)) (go (tyVarKind tv))
antalsz/hs-to-coq
src/lib/HsToCoq/Util/GHC/Deriving.hs
mit
5,977
0
17
1,474
1,481
786
695
93
10
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Version where import Language.Haskell.TH (runIO) import Language.Haskell.TH.Syntax (Exp(LitE), Lit(StringL)) import Shellmet import Data.Text -- | Uses Template Haskell to embed a git descriptor of the commit -- which was used to build the executable. gitDescribe :: String gitDescribe = $( fmap (LitE . StringL . unpack) . runIO $ do let formatDate d = " (built on " <> d <> ")" -- Outputs date of current commit; E.g. 2021-08-06 let getDate = "git" $| ["show", "-s", "--format=%cs"] date <- (formatDate <$> getDate) $? pure "" -- Fetches a unique tag-name to represent the current commit. -- Uses human-readable names whenever possible. -- Marks version with a `'` suffix if building on a dirty worktree. let getTag = "git" $| ["describe", "--tags", "--always", "--dirty='"] tag <- getTag $? pure "unknown" pure (tag <> date) )
unisonweb/platform
parser-typechecker/unison/Version.hs
mit
933
0
14
172
205
115
90
15
1
{-# LANGUAGE Rank2Types #-} import Numeric.AD import Control.Applicative import Control.Monad import Data.Foldable as F import Data.Traversable import Control.Applicative import Control.Monad.State import Control.Monad as M import System.IO import Data.Char as C import Data.Vector as V import Data.List as L import Data.Map as Map import Data.Monoid import Data.Reflection import Data.Array.Accelerate.Interpreter as I import Data.Random.Normal import System.Random import Numeric.AD.Internal.Reverse as Reverse import Data.Time.Clock main = time $ test 200 100 {- This function changes frequently and is used to test all the others. Currently it takes in the number of timesteps to iterate over along with the number iterations of gradient descent to use. It then instances a random set of network parameters and optimizes them. It then prints a list of the largest parameters in the neural network at every time step, along with the log likelihoods assigned to the training dataset by the the network before and after the optimisation. -} test iterations dataSize = do biginfo <- getData address let info = L.take dataSize biginfo elems = L.length . Map.toList $ ctiMap (ctiMap,itcMap) = makeConverters info nn = stdGRU elems initMomentum = stdGRU elems llh = testGRU info grad = myGrad (testGRU info) nn --opti = gradientUp (testGRU info) nn iterations 0.01 :: [(GRUParams Float,GRUParams Float)] --opti = momentumGradientAscent (testGRU info) nn initMomentum 0.000001 (0.97) :: [(GRUParams Float, GRUParams Float,Float)] opti = optiGrad (testGRU info) nn initMomentum 0.000001 (0.98) :: [(GRUParams Float, GRUParams Float,Float,Float)] printWith "The size of the network is :" $ getCount nn putStrLn . (\x -> "The initial LLH is: " L.++ show x) $ llh nn putStrLn . show $ (ctiMap,itcMap) putStrLn . show . fmap (\(x,y,z,a) -> (getNorm x,getNorm y,z,a)) $ opti putStrLn . (\x -> "The final LLH is: " L.++ show x) $ llh (L.last . fmap (\(x,_,_,_) -> x) $ opti) return () printWith :: Show a => String -> a -> IO () printWith msg x = putStrLn (msg L.++ show x) time :: IO a -> IO () time x = do t1 <-getCurrentTime x t2 <- getCurrentTime putStrLn . show $ diffUTCTime t2 t1 --Returns a string representation of a file at a given location getData :: String -> IO String getData address = do handle <- openFile address ReadMode hGetContents handle --Hard coded adress of the training data address = "/Users/curtishuebner/Documents/Development/haskell/ghnn/Data/mobyDick.txt" {- Parmeters: An object that can be folded over Returns: the largest numeric value contained within -} getMax :: (Foldable f,Num a,Ord a) => f a -> a getMax= F.foldl (\a b-> if (abs a >abs b) then abs (a) else b) 0 getNorm :: (Foldable f, Floating a) => f a -> a getNorm = sqrt . getSum . F.foldMap (\x -> Sum (x*x)) getCount :: (Num a,Foldable f) => f x -> a getCount = getSum . F.foldMap (\_ -> Sum 1) {- This function produces a stadard set of network parameters when given the input size of the network -} stdGRU :: Floating a => Int -> GRUParams a stdGRU ioSize = initGRU ioSize 500 ioSize (1,2,10) 312 {- Parameters: a string Returns: maps that allow one to freely convert from a list of characters contained in the string to a list of integers and back again -} makeConverters :: String -> (Map.Map Char Int,Map.Map Int Char) makeConverters x = (charToInt x, intToChar x) {- Parameters: A list of integers along with a vector length Returns: a list of vectors initialized to 0 except for the element coresponding to the corresponding integer in the first list -} sparsify :: Num a => [Int] -> Int -> [Vector a] sparsify list length = fmap (\x -> V.replicate length 0 // [(x,1)]) list --returns a sorted list of numbers corresponding to characters in a string values contents = sort . nub $ fmap C.ord contents --unsafely applies a map to the elements of an object conv ::(Functor f,Ord x) => Map.Map x y -> f x -> f y conv map = fmap $ (\(Just x) -> x) . (\y -> Map.lookup y map) {- This function takes a string and creates input output pairs that can be used to train a reccurent neural network along with the maximum size that the values inside the IOpairs can take on -} makeIOPairs :: [Char] -> ([Int],[Int],Int) makeIOPairs charValues = let (ctiMap,_) = makeConverters charValues intValues = conv ctiMap charValues inputs = L.init intValues outputs = L.tail intValues ioWidth = L.length $ values charValues in (inputs,outputs,ioWidth) --Evaluates the preformance of a given neural network given a set of IOPairs and an initial vector evalNN ::(Floating a) => ([Int],[Int],Int) -> ((Vector a,[Vector a]) -> (Vector a,[Vector a])) -> Vector a -> (a,Vector a) evalNN (inputs,outputs,ioWidth) nn initialState = let vectorInputs = sparsify inputs ioWidth (newState,vectorOutputs) = nn (initialState,vectorInputs) targetValuePairs = L.zip vectorOutputs outputs llh = sumSoftMaxLLH targetValuePairs in (llh,newState) --Takes a set of GRU parameters and returns a neural network makeGRU ::Floating a => GRUParams a -> (Vector a,[Vector a]) -> (Vector a,[Vector a]) makeGRU = passOver . gru {- Parameters: training data and a set of network parameters Returns: the log likelyhood assigned by the resulting network to the data (a.k.a the number of bits required to encode the data) I find this function notable as it maps directly from parameters and training data to log likelyhood, and so lends itself to easy optimization -} testGRU :: Floating a => [Char] -> GRUParams a -> a testGRU inputs parameters = let ioPairs = makeIOPairs inputs nn = makeGRU parameters width = stateSize parameters initalVector = V.replicate width 0 in fst $ evalNN ioPairs nn initalVector --Map from possible characters in a string to integers charToInt :: String -> Map.Map Char Int charToInt values = let possibleChars = nub values pairs = L.zip possibleChars [0..] in Map.fromList pairs --Map from integers to characters intToChar :: String -> Map.Map Int Char intToChar values = let possibleChars = nub values pairs = L.zip [0..] possibleChars in Map.fromList pairs {- Applies the log likelyhood funcition to a list and sums the results -} sumLLH :: Floating a => [V.Vector (a,Bool)] -> a sumLLH = L.sum . L.map logLikelyhood {- Parameters: A vector of (float,boolean) pairs This function interprets the pairs as a probability that a given value is true value and a corresponding correct answer. It then computes the product of the probalbilites that had a True value as a pair along with (1-) the probabilities of values that had a False as a pair Returns: the assigned log likelyhood -} logLikelyhood :: Floating a => V.Vector (a,Bool) -> a logLikelyhood = V.sum . V.map (\(x,y) -> if y then log(x) else log(1-x)) {- applies the softMaxLLH function to a vector and sums the results -} sumSoftMaxLLH :: (Floating a) => [(V.Vector a,Int)] -> a sumSoftMaxLLH = L.sum . fmap softMaxLLH {- Applies the soft max function to vector integer pairs and interprets the result as a probability assinged to a given integer. -} softMaxLLH :: (Floating a) => (V.Vector a, Int) -> a softMaxLLH (vector,index) = let logNumerator = vector V.! index logDenominator = log . V.sum . fmap exp $ vector in logNumerator - logDenominator --An experiment in order to understand the type signatue of the graident descent function myGrad ::(Traversable f,Floating b) => (forall a. (Floating a) => f a -> a) -> f b -> f b myGrad a b = grad a b {- An implementation of gradient descent. Parameters: a many to one function, the starting point of the gradient descent, an integer amount of steps, the step size Returns: a list of points in the space of possible inputs with items farther in the list better maximising the function TODO: eliminate recomputation of initVal -} gradientUp :: (Ord a, Floating a ,Traversable f, Applicative f) => (forall x. Floating x => f x -> x) -> f a -> Int -> a -> [(f a,f a)] gradientUp _ initParams 0 _ = [] gradientUp func initParams iterNum alpha= let (initVal,gradient) = grad' func initParams newParams = (+) <$> initParams <*> ((alpha * (1) *) <$> gradient) newVal = func newParams in if (newVal > initVal) then (newParams,gradient) : gradientUp func newParams (iterNum-1) (alpha * 1.05) else (newParams,gradient) : gradientUp func initParams iterNum (alpha / 2) momentumGradientAscent :: (Ord a,Floating a, Traversable f, Applicative f) => (forall x. Floating x => f x -> x) -> f a -> f a -> a -> a -> [(f a,f a,a)] momentumGradientAscent func initParams momentum alpha beta = let (initVal,gradient) = grad' func initParams newMomentum =fmap (*beta) $ (+) <$> momentum <*> ((alpha*) <$> gradient) newParams = (+) <$> momentum <*> initParams theta = acos $ dotProduct momentum gradient / (getNorm momentum * getNorm gradient) in if (getNorm gradient > 0.001) then (newParams,gradient,theta) : momentumGradientAscent func newParams newMomentum alpha beta else [] optiGrad :: (Ord a, Floating a, Traversable f, Applicative f) => (forall x. Floating x => f x -> x) -> f a -> f a -> a -> a -> [(f a,f a,a,a)] optiGrad func initParams momentum alpha beta = let (initVal,gradient) = grad' func initParams truncatedMomentum = if dotProduct momentum gradient > 0 then --momentum momentum `onto` gradient else --planarProj momentum gradient pure 0 newMomentum = fmap (*beta) $ (+) <$> momentum <*> ((alpha*) <$> gradient) newParams = (+) <$> newMomentum <*> initParams theta = acos $ dotProduct momentum gradient / (getNorm momentum * getNorm gradient) in if (getNorm gradient > 1) then (newParams,gradient,theta / pi,initVal) : optiGrad func newParams newMomentum alpha beta else [] {- Parameters: a function from a (state,input) pair to a new (state,output) pair Returns: the same function applied to a list of values with the states chained together TODO: reimplent this using the state monad and the traversable typeclass -} passOver :: ((a,b) -> (a,c)) -> (a,[b]) -> (a,[c]) passOver f (state,inputs@(x:xs)) = let (nextState,nextOutput) = f (state,x) (finalState,otherOutput) = passOver f (nextState,xs) in (finalState,nextOutput:otherOutput) passOver _ (state,[]) = (state,[]) --sparse vector matrix multiplication --TODO: swich the arguments around in acordance with linear algebra conventions (><) :: Num a => V.Vector a -> Matrix a -> V.Vector a vector >< SMatrix matrix = let multiplyElement (factor,index) = vector V.! index * factor multiplyRow = L.sum . fmap multiplyElement in fmap multiplyRow matrix --ElementWise function application for vectors infixl 8 `vecApply` vecApply :: V.Vector (a -> b) -> V.Vector a -> V.Vector b vecApply func a = V.zipWith (\x y -> x y) func a {- An experimental differentiable branching operation between vectors to create turing-complete neural networks -} vectorBranch ::(Ord a, Floating a) => a -> (V.Vector a -> V.Vector a) -> (V.Vector a -> V.Vector a) -> V.Vector a -> V.Vector a vectorBranch x f g args = let function = if x > 0 then f else g transferFunction = 1 / (1 + x**2) newFraction = (*transferFunction) <$> function args oldFraction = ((*) $ 1-transferFunction) <$> args in (vecApply $ fmap (+) newFraction) oldFraction --TODO: Clean this up --Defining Zipvectors newtype ZipVec a = ZipVec (V.Vector a) deriving (Show, Eq, Ord, Read) getZipVec (ZipVec a) = a instance Functor ZipVec where fmap f (ZipVec a) = ZipVec . V.map f $ a instance Applicative ZipVec where pure = ZipVec . V.unfoldr (\x -> Just (x,x)) ZipVec a <*> ZipVec b = ZipVec $ a `vecApply` b instance Foldable ZipVec where foldMap f (ZipVec vec) = F.fold $ fmap f vec foldr f a (ZipVec vec) = V.foldr f a vec instance Traversable ZipVec where sequenceA (ZipVec a)= ZipVec <$> sequenceA a --Defining Sparce and uniform matrices data Matrix a = SMatrix (V.Vector [(a,Int)]) | UMatrix a deriving (Show,Eq) instance Functor Matrix where fmap f (SMatrix matrix) =SMatrix . (V.map . L.map $ (\(a,x) -> (f a,x))) $ matrix instance Applicative Matrix where pure = UMatrix UMatrix f <*> UMatrix a = UMatrix $ f a UMatrix f <*> matrix@(SMatrix a)= fmap f matrix SMatrix f <*> SMatrix a = SMatrix $ V.zipWith applyRow f a where applyRow = L.zipWith (\(f,a) (x,_) -> (f x, a)) instance Foldable Matrix where foldMap = foldMapDefault instance Traversable Matrix where sequenceA (SMatrix a) = SMatrix <$> seqVec a where seqVec = sequenceA . fmap seqRow seqRow = sequenceA . fmap seqVal seqVal (val,index) = (\x -> (x,index)) <$> val {- Parameters: number of columns and rows along with the number of non zero elements Returns: A stateful computation that once run will produce a matrix with the given parameters. -} genSpMtx :: (Num a, Enum a, RandomGen s) => Int -> Int -> Int -> State s (Matrix a) genSpMtx columns rows elemPerRow = newMatrix where newMatrix = matrixGenerator >>= \y -> return . SMatrix $ y matrixGenerator = V.replicateM rows genRow genRow = let vals = [0,0..] indicies = knuthShuffleN range elemPerRow row = indicies >>= \x -> return $ L.zip vals x in row range = (0,columns - 1) :: (Int,Int) --Apply gaussian noise to the numeric values of a given traversable object randPerturb x mean stdDev = M.forM x f where f x = (state $ normal) >>= \y -> return (x + mean + y * stdDev) {- Takes in a range of values and produces a stateful computaton that when run returns the first n elements of a randomly shuffled list containing all the elements in the range -} knuthShuffleN :: (Random a, Enum a, RandomGen g, Num b, Ord b) => (a,a) -> b -> State g [a] knuthShuffleN range n = let initList = (\(a,b) -> [a..b]) range initListLength = L.length initList subShuffle ::(Integral a, Random a, Enum a, Num b, Ord b, RandomGen g) => [t] -> a -> b -> State g [t] subShuffle [] lenght n = return [] subShuffle list lenght n = if (n > 0) then do index <- randomindex lenght let (newList,val) = list -!! index rest <- subShuffle newList (lenght-1) (n-1) let retVal = val:rest return retVal else return [] randomindex :: (Num a,Random a,Enum a,RandomGen g) => a -> State g a randomindex lenght = state $ randomR (0,lenght-1) (-!!) :: Integral b => [a] -> b -> ([a],a) a -!! b = let (x,(y:ys)) = L.genericSplitAt b a in (x L.++ ys,y) in subShuffle initList initListLength n --Instancing the gated reccurent unit dataStructure data GRUParams a = GRUParams { inputToChange :: Matrix a , stateToChange :: Matrix a , inputToGate :: Matrix a , stateToGate :: Matrix a , stateToOutput :: Matrix a , changeBias :: ZipVec a , gateBias :: ZipVec a , outputBias :: ZipVec a , inputSize :: Int , outputSize :: Int , stateSize :: Int }deriving (Show,Eq) instance Functor GRUParams where fmap = fmapDefault instance Foldable GRUParams where foldMap = foldMapDefault {- Note: if traversable is instanced using sequenceA and fmap is implemented with fmapDefault, any calls to traverse will cause a stack overflow. This is because traverse will call fmap which calls fmapDefault which calls traverse again -} instance Traversable GRUParams where traverse f (GRUParams iTC sTC iTG sTG sTO cB gB oB iS oS sS) = GRUParams <$> traverse f iTC <*> traverse f sTC <*> traverse f iTG <*> traverse f sTG <*> traverse f sTO <*> traverse f cB <*> traverse f gB <*> traverse f oB <*> pure iS <*> pure oS <*> pure sS --TODO: instance this properley later instance Applicative GRUParams where pure f = let g = (pure f) h = (pure f) in GRUParams g g g g g h h h undefined undefined undefined GRUParams a1 a2 a3 a4 a5 a6 a7 a8 _ _ _ <*> GRUParams b1 b2 b3 b4 b5 b6 b7 b8 x y z = GRUParams (a1 <*> b1) (a2 <*> b2) (a3 <*> b3) (a4 <*> b4) (a5 <*> b5) (a6 <*> b6) (a7 <*> b7) (a8 <*> b8) x y z {- For the confused: xTY = x to y i = input s = state o = output c = change g = gate B = bias EPR = elements per row Parameters: sizes for the input state and output along with a tuple describing the number of elements per row of each matrix and a seed value Returns: a slightly randomized set of gated reccurent unit parameters -} initGRU ::(Floating a) => Int -> Int -> Int -> (Int,Int,Int) -> Int -> GRUParams a initGRU input state output (iTSEPR,sTSEPR,sTOEPR) seed = let stateGRU = do iTC <- genSpMtx input state iTSEPR sTC <- genSpMtx state state sTSEPR iTG <- genSpMtx input state iTSEPR sTG <- genSpMtx state state sTSEPR sTO <- genSpMtx state output sTOEPR let cB = ZipVec $ V.replicate state 0 gB = ZipVec $ V.replicate state 0 oB = ZipVec $ V.replicate output 0 blankGRU = GRUParams iTC sTC iTG sTG sTO cB gB oB input output state return blankGRU randPerturb blankGRU 0 (1 * 10**(-3)) generator = mkStdGen seed in fmap floatingFromDouble . fst . runState stateGRU $ generator {- Parameters: the parameters to a gated reccurent unit Returns: a funtion that maps between an (input,state) pair of vectors and an (output,newState) pair of vectors -} gru :: (Floating a) => GRUParams a -> (V.Vector a, V.Vector a) -> (V.Vector a, V.Vector a) gru parameters (state,input) = (newState, output) where zipState = ZipVec state gate = (\a b c -> logit $ a + b + c) <$> gateBias parameters <*> ZipVec (input >< inputToGate parameters) <*> ZipVec (state >< stateToGate parameters) change = (\a b c d->cos (a + b + c) * d) <$> changeBias parameters <*> ZipVec (input >< inputToChange parameters) <*> ZipVec (state >< stateToChange parameters) <*> gate newState = getZipVec $ (+) <$> zipState <*> change output = newState >< stateToOutput parameters --Generic transfer functions logit x = 1 / (1 + exp(-x)) quadraticSigmoid x = x/(sqrt(x**2+1)) --Functions for converting from polymorphic floats to doubles and back floatingFromDouble :: Floating n => Double -> n floatingFromDouble i = realToFrac i doubleFromFloating :: (Real n,Floating n) => n -> Double doubleFromFloating i = realToFrac i dotProduct x y = getSum . F.fold . fmap Sum $ ((*) <$> x <*> y) onto x y = fmap (*(dotProduct x y / (getNorm y ^ 2))) y planarProj x y = (-) <$> x <*> (x `onto` y)
CurtisHuebner/ghnn
src/Main.hs
mit
19,897
112
22
5,241
6,019
3,141
2,878
-1
-1
import Database.HDBC.Sqlite3 (connectSqlite3) import Database.HDBC query :: Int -> IO () query maxId = do conn <- connectSqlite3 "test1.db" r <- quickQuery' conn "SELECT id, desc from test where id <= ? ORDER BY id, desc" [toSql maxId] let stringRows = map convRow r mapM_ putStrLn stringRows where convRow :: [SqlValue] -> String convRow [sqlId, sqlDesc] = show intid ++ ": " ++ desc where intid = (fromSql sqlId)::Integer desc = case fromSql sqlDesc of Just x -> x Nothing -> "NULL" convRow x = fail $ "Unexpected result: " ++ show x
zhangjiji/real-world-haskell
ch21/query.hs
mit
636
5
10
193
182
91
91
16
3
--asPatterns.hs module AsPatterns where import Data.Bool import Data.Char import Data.List myChunks :: String -> Char -> [String] myChunks n c | n == "" = [] | otherwise = firstChunk : myChunks (dropWhile (/= c) $ tail n) c where firstChunk = if head n == c then takeWhile (/= c) $ tail n else takeWhile (/= c) n isSubSequenceOf :: (Eq a) => [a] -> [a] -> Bool isSubSequenceOf x y = foldr ((&&).(flip elem) y) True x -- you didnt even use the as-pattern, dingus capitalizeWords :: String -> [(String, String)] capitalizeWords s = map (\s@(c:cs) -> (s, toUpper c : cs)) (words s) capitalizeWord :: String -> String capitalizeWord "" = "" capitalizeWord (' ':xs) = capitalizeWord xs capitalizeWord s@(c:cs) = toUpper c : cs capitalizeParagraph :: String -> String capitalizeParagraph [] = [] capitalizeParagraph p = init.intercalate ". " $ map capSentence (sentences p) where sentences s = map dropInitialSpaces (myChunks s '.') where dropInitialSpaces s | s == [] = [] | otherwise = dropWhile (== ' ') s capSentence [] = [] capSentence s = capitalizeWord (takeWhile (/= ' ') s) ++ drop (length (takeWhile (/= ' ') s)) s
deciduously/Haskell-First-Principles-Exercises
3-Getting serious/11-Algebraic Datatypes/code/asPatterns.hs
mit
1,290
1
13
367
505
264
241
28
2
{-# LANGUAGE DeriveGeneric #-} -- only export the public interface module Users (Users.all, matching, User(..)) where import Data.Aeson import GHC.Generics data User = User {userId :: Int, userName :: String} deriving (Show, Generic, Eq) bob :: User bob = User {userId = 1, userName = "bob"} jenny :: User jenny = User {userId = 2, userName = "jenny"} all :: [User] all = [bob, jenny] matching :: Int -> [User] -> [User] matching id = filter (matchesId id) matchesId :: Int -> User -> Bool matchesId id user = userId user == id -- implement the typeclasses for JSON using Generics instance ToJSON User instance FromJSON User
mikegehard/haskell-api
src/Users.hs
mit
655
0
8
137
217
126
91
17
1
{- Functions for parsing raw file input to [(Person, Birthday)] Scheme: 1. Raw Input -> [Lines] 2. [Lines] -> [Only lines with names and bd] 3. [Only lines with names and bd] -> [(Name, BD)] 4. parseNameAndBD :: [(Name, BD)] -> [(Person, Birthday)] input -> nameAndBirthday (step 2) -> listOfTuples (step 3) -> parseNameAndBD -} module Parsing.ParsingIMDBFile where import Parsing import Data.List (isPrefixOf, elemIndex) import Data.Char (isSpace) import Data.List.Split (splitOn) import Control.Arrow ((***)) import Text.Regex.Posix -- -- Step 1-3 -- | Raw input from file -> ("Lastname, Firstname", "BD, Birthplace") rawInputToTuple :: String -> [(String, String)] rawInputToTuple input = listOfTuples . nameAndBirthday . lines $ input where -- | Step2. Create list of strings: -- ["NM: ...", "DB: ...", "NM: ...", ...] nameAndBirthday = filter (\x -> "NM: " `isPrefixOf` x || "DB: " `isPrefixOf` x) -- | ["NM: ...", "DB: ...", ...] -> [("Raw name string", "Raw bd string")] listOfTuples :: [String] -> [(String, String)] listOfTuples [] = [] listOfTuples (x:xs) | "NM: " `isPrefixOf` x && "DB: " `isPrefixOf` head xs && validBD birthday = (parseName x, birthday) : listOfTuples xs | otherwise = listOfTuples xs where birthday = parseBirthday $ head xs -- | Check birthday string. Only "Day Month Year" validBD :: String -> Bool validBD str = str =~ "^[0-9]+ (January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{4}$" parseName :: String -> String parseName = drop (length "NM: ") -- | Example: "DB: 5 March 1981, Lisbon, Portugal" -> "5 March 1981" parseBirthday :: String -> String parseBirthday string = separateBdFromBp sliced where sliced = drop (length "DB: ") string -- | Example: "5 March 1981, Lisbon, Portugal" -> "5 March 1981" separateBdFromBp :: String -> String separateBdFromBp [] = [] separateBdFromBp string = case isTherePunc of Nothing -> string Just n -> fst $ splitAt n string where isTherePunc = elemIndex ',' string -- -- Step 4 parseNameAndBD :: [(String, String)] -> [(Person, Birthday)] parseNameAndBD = map (parseNameToPerson *** parseDBToBirthday) parseNameToPerson :: String -> Person parseNameToPerson str = if length list == 1 -- True = No lastname; False = fullname then Person { firstName = head list, lastName = "" } else Person { firstName = list !! 1, lastName = head list } where list = splitOn ", " str parseDBToBirthday :: String -> Birthday parseDBToBirthday str = Birthday { day = day', month = month', year = year' } where list = splitOn " " str day' = read d :: Int month' = getMonth (list !! 1) year' = read (list !! 2) :: Int d = stripLeadingWhitespace (head list) stripLeadingWhitespace = dropWhile isSpace getMonth :: String -> Month getMonth mon = case mon of "January" -> January "February" -> February "March" -> March "April" -> April "May" -> May "June" -> June "July" -> July "August" -> August "September" -> September "October" -> October "November" -> November "December" -> December _ -> error "Wrong month" monthToString :: Month -> String monthToString mon = case mon of January -> "January" February -> "February" March -> "March" April -> "April" May -> "May" June -> "June" July -> "July" August -> "August" September -> "September" October -> "October" November -> "November" December -> "December"
liqlvnvn/from-IMDB-to-MongoDB
src/Parsing/ParsingIMDBFile.hs
mit
3,814
0
12
1,036
853
463
390
82
13
module Compiler.JMacro.Symbols where import Prelude import Data.Array import Data.Char (toLower) import qualified Data.Text as T import Compiler.JMacro.Base data Special = Stack | Sp deriving (Show, Eq) instance ToJExpr Special where toJExpr Stack = ValExpr (JVar (TxtI (T.pack "h$stack"))) toJExpr Sp = ValExpr (JVar (TxtI (T.pack "h$sp"))) -- fixme this is getting out of hand... data StgReg = R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15 | R16 | R17 | R18 | R19 | R20 | R21 | R22 | R23 | R24 | R25 | R26 | R27 | R28 | R29 | R30 | R31 | R32 | R33 | R34 | R35 | R36 | R37 | R38 | R39 | R40 | R41 | R42 | R43 | R44 | R45 | R46 | R47 | R48 | R49 | R50 | R51 | R52 | R53 | R54 | R55 | R56 | R57 | R58 | R59 | R60 | R61 | R62 | R63 | R64 | R65 | R66 | R67 | R68 | R69 | R70 | R71 | R72 | R73 | R74 | R75 | R76 | R77 | R78 | R79 | R80 | R81 | R82 | R83 | R84 | R85 | R86 | R87 | R88 | R89 | R90 | R91 | R92 | R93 | R94 | R95 | R96 | R97 | R98 | R99 | R100 | R101 | R102 | R103 | R104 | R105 | R106 | R107 | R108 | R109 | R110 | R111 | R112 | R113 | R114 | R115 | R116 | R117 | R118 | R119 | R120 | R121 | R122 | R123 | R124 | R125 | R126 | R127 | R128 deriving (Eq, Ord, Show, Enum, Bounded, Ix) -- | return registers -- extra results from foreign calls can be stored here (first result is returned) data StgRet = Ret1 | Ret2 | Ret3 | Ret4 | Ret5 | Ret6 | Ret7 | Ret8 | Ret9 | Ret10 deriving (Eq, Ord, Show, Enum, Bounded, Ix) instance ToJExpr StgReg where toJExpr = (registers!) -- only the registers that have a single ident registersI :: Array StgReg Ident registersI = listArray (minBound, R32) (map (ri.(registers!)) $ enumFromTo R1 R32) where ri (ValExpr (JVar i)) = i ri _ = error "registersI: not an ident" registers :: Array StgReg JExpr registers = listArray (minBound, maxBound) (map regN (enumFrom R1)) where regN r | fromEnum r < 32 = ValExpr . JVar . TxtI . T.pack . ("h$"++) . map toLower . show $ r | otherwise = (IdxExpr (ValExpr (JVar (TxtI (T.pack "h$regs"))))) (toJExpr ((fromEnum r) - 32)) -- error "registers" -- [je| h$regs[`fromEnum r-32`] |] instance ToJExpr StgRet where toJExpr r = ValExpr (JVar (rets!r)) rets :: Array StgRet Ident rets = listArray (minBound, maxBound) (map retN (enumFrom Ret1)) where retN = TxtI . T.pack . ("h$"++) . map toLower . show regName :: StgReg -> String regName = map toLower . show regNum :: StgReg -> Int regNum r = fromEnum r + 1 numReg :: Int -> StgReg numReg r = toEnum (r - 1) minReg :: Int minReg = regNum minBound maxReg :: Int maxReg = regNum maxBound -- some shortcuts for convenience r1, r2, r3, r4 :: JExpr r1 = toJExpr R1 r2 = toJExpr R2 r3 = toJExpr R3 r4 = toJExpr R4 ret1, ret2 :: JExpr ret1 = toJExpr Ret1 ret2 = toJExpr Ret2 stack, sp :: JExpr stack = toJExpr Stack sp = toJExpr Sp
ghcjs/ghcjs
src/Compiler/JMacro/Symbols.hs
mit
3,169
1
19
992
1,168
677
491
69
2
{-# LANGUAGE LambdaCase #-} module OptionsSpec (spec) where import Control.Lens import System.Exit.Lens import Test.Hspec.Lens import Options spec :: Spec spec = describe "parser" $ do it "has ’version’ subcommand" $ parseArgs ["version"] `shouldHave` _Version it "has ’help’ subcommand" $ parseArgs ["help"] `shouldHave` _Help._3._ExitSuccess context "‘init’ subcommand" $ do it "takes a filename argument" $ parseArgs ["init", "foo"] `shouldHave` _Init.only "foo" it "filename argument is optional" $ parseArgs ["init"] `shouldHave` _Init.only "." context "‘run’ subcommand" $ do it "takes a filename argument" $ do parseArgs ["run", "Foo.hs"] `shouldHave` _Run.only (Just "Foo.hs", []) parseArgs ["run", "Foo.hs", "--foo"] `shouldHave` _Run.only (Just "Foo.hs", ["--foo"]) parseArgs ["run", "Foo.hs", "--"] `shouldHave` _Run.only (Just "Foo.hs", []) parseArgs ["run", "Foo.hs", "--", "foo", "--bar"] `shouldHave` _Run.only (Just "Foo.hs", ["foo", "--bar"]) it "filename argument is optional" $ do parseArgs ["run"] `shouldHave` _Run.only (Nothing, []) parseArgs ["run", "--foo"] `shouldHave` _Run.only (Nothing, ["--foo"]) parseArgs ["run", "--"] `shouldHave` _Run.only (Nothing, []) parseArgs ["run", "--", "foo", "--bar"] `shouldHave` _Run.only (Nothing, ["foo", "--bar"]) context "‘json’ subcommand" $ do it "takes a filename argument" $ parseArgs ["json", "foo"] `shouldHave` _Json.only "foo" it "filename argument is optional" $ parseArgs ["json"] `shouldHave` _Json.only defaultBiegunkaDataDirectory
biegunka/biegunka
test/spec/OptionsSpec.hs
mit
1,706
0
17
363
547
289
258
-1
-1
-- Example 3 -- Hello event, with an intermediate (2 second) pause import FRP.Yampa as Y import YampaUtils initialise :: IO () initialise = putStrLn "Hello..." output :: Bool -> IO Bool output b = if b then putStrLn "...Event!" >> return True else return False -- twoElapsed generates an event after two seconds twoElapsed :: SF a (Event ()) twoElapsed = time >>> arr (>=2) >>> edge -- waitTwo outputs false, but upon receiving an event from -- twoElapsed, switches to output True waitTwo :: SF () Bool waitTwo = ((constant False) &&& twoElapsed) `switch` (\_ -> constant True) main :: IO () main = yampaMain initialise (return Nothing) output waitTwo
rlupton20/yampaTutorial
src/HelloEvent.hs
cc0-1.0
658
0
9
118
190
102
88
12
2
{- | Module : $Header$ Description : description of undo and redo functions Copyright : uni-bremen and DFKI License : GPLv2 or higher, see LICENSE.txt Maintainer : r.pascanu@jacobs-university.de Stability : provisional Portability : portable CMDL.UnDoRedo contains the implementation of the undo and redo commads -} module CMDL.UndoRedo ( cUndo , cRedo ) where import Interfaces.History (redoOneStep, undoOneStep) import Interfaces.Command (showCmd) import Interfaces.DataTypes import CMDL.DataTypesUtils (genMessage) import CMDL.DataTypes (CmdlState (intState)) -- | Undoes the last command entered cUndo :: CmdlState -> IO CmdlState cUndo = cdo True -- | Redoes the last undo command cRedo :: CmdlState -> IO CmdlState cRedo = cdo False cdo :: Bool -> CmdlState -> IO CmdlState cdo isUndo state = let msg = (if isUndo then "un" else "re") ++ "do" in case (if isUndo then undoList else redoList) . i_hist $ intState state of [] -> return $ genMessage [] ("Nothing to " ++ msg) state action : _ -> do nwIntState <- (if isUndo then undoOneStep else redoOneStep) $ intState state return . genMessage [] ("Action '" ++ showCmd (command action) ++ "' is now " ++ msg ++ "ne") $ state { intState = nwIntState }
nevrenato/Hets_Fork
CMDL/UndoRedo.hs
gpl-2.0
1,336
0
22
324
304
164
140
24
5
module MarXup.Text (Text(..), textual, element, module Data.Monoid, linearize) where import Data.Monoid import Data.Traversable import Data.Foldable import Control.Applicative import Control.Monad import Control.Monad.Fix import Control.Monad.Writer data Text a where Return :: a -> Text a Text :: String -> Text () (:>>=) :: Text a -> (a -> Text b) -> Text b MFix :: (a -> Text a) -> Text a textual = Text element :: Show a => a -> Text () element = Text . show instance MonadFix Text where mfix = MFix instance Monad Text where (>>=) = (:>>=) return = Return instance Applicative Text where (<*>) = ap pure = Return instance Functor Text where fmap = liftM run :: Text a -> Writer [String] a run (Return x) = return x run (Text x) = tell [x] run (k :>>= f) = run k >>= run . f run (MFix f) = mfix (run . f) linearize :: Text a -> [String] linearize t = snd $ runWriter $ run t
jyp/MarXup
MarXup/Text.hs
gpl-2.0
915
0
10
201
395
215
180
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Lamdu.CodeEdit.ExpressionEdit.LiteralEdit(makeInt, makeIntView) where import Control.Lens.Operators import Control.MonadA(MonadA) import Data.Store.Transaction (Transaction) import Graphics.UI.Bottle.Animation (AnimId) import Lamdu.CodeEdit.ExpressionEdit.ExpressionGui (ExpressionGui) import Lamdu.CodeEdit.ExpressionEdit.ExpressionGui.Monad (ExprGuiM) import qualified Data.Char as Char import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.Bottle.Widgets.FocusDelegator as FocusDelegator import qualified Graphics.UI.Bottle.Widgets.TextEdit as TextEdit import qualified Lamdu.BottleWidgets as BWidgets import qualified Lamdu.CodeEdit.ExpressionEdit.ExpressionGui as ExpressionGui import qualified Lamdu.CodeEdit.ExpressionEdit.ExpressionGui.Monad as ExprGuiM import qualified Lamdu.CodeEdit.Sugar as Sugar import qualified Lamdu.Config as Config import qualified Lamdu.WidgetEnvT as WE setColor :: MonadA m => ExprGuiM m a -> ExprGuiM m a setColor action = do config <- ExprGuiM.widgetEnv WE.readConfig ExprGuiM.withFgColor (Config.literalIntColor config) action makeIntView :: MonadA m => AnimId -> Integer -> ExprGuiM m (ExpressionGui m) makeIntView myId integer = fmap ExpressionGui.fromValueWidget . setColor . ExprGuiM.widgetEnv $ BWidgets.makeTextViewWidget (show integer) myId makeIntEdit :: MonadA m => Sugar.LiteralInteger m -> Widget.Id -> ExprGuiM m (ExpressionGui m) makeIntEdit integer myId = case Sugar.liSetValue integer of Nothing -> makeIntView (Widget.toAnimId myId) (Sugar.liValue integer) Just setValue -> makeIntEditI integer myId setValue makeIntEditI :: MonadA m => Sugar.LiteralInteger m -> Widget.Id -> (Integer -> Transaction m ()) -> ExprGuiM m (ExpressionGui m) makeIntEditI integer myId setValue = do cursor <- ExprGuiM.widgetEnv WE.readCursor let suffix = Widget.subId myId cursor isEmpty = Sugar.liValue integer == 0 && suffix == Just emptyZeroCursor (text, textCursor) | isEmpty = ("", TextEdit.makeTextEditCursor myId 0) | otherwise = (show (Sugar.liValue integer), cursor) setter (newText, eventRes) | newText == text = return eventRes | not (all Char.isDigit newText) = return Widget.emptyEventResult | null newText = do _ <- setValue 0 return . Widget.eventResultFromCursor $ Widget.joinId myId emptyZeroCursor | otherwise = do _ <- setValue $ read newText return eventRes style <- ExprGuiM.widgetEnv WE.readTextStyle return $ TextEdit.make (style & TextEdit.sEmptyFocusedString .~ "<0>") textCursor text myId & Widget.wEventMap %~ removeKeys & Widget.atEvents setter & ExpressionGui.fromValueWidget where removeKeys = (E.filterSChars . flip . const) Char.isDigit . foldr (.) id [ E.deleteKey (E.KeyEvent E.Press (E.ModKey E.noMods key)) | key <- [E.KeyEnter, E.KeySpace] ] emptyZeroCursor = ["empty-zero"] literalFDConfig :: FocusDelegator.Config literalFDConfig = FocusDelegator.Config { FocusDelegator.startDelegatingKeys = [E.ModKey E.noMods E.KeyEnter] , FocusDelegator.startDelegatingDoc = E.Doc ["Edit", "Change integer"] , FocusDelegator.stopDelegatingKeys = [E.ModKey E.noMods E.KeyEsc] , FocusDelegator.stopDelegatingDoc = E.Doc ["Edit", "Stop changing integer"] } makeInt :: MonadA m => Sugar.LiteralInteger m -> Widget.Id -> ExprGuiM m (ExpressionGui m) makeInt integer = ExpressionGui.wrapDelegated literalFDConfig FocusDelegator.NotDelegating (setColor . makeIntEdit integer)
Mathnerd314/lamdu
src/Lamdu/CodeEdit/ExpressionEdit/LiteralEdit.hs
gpl-3.0
3,675
0
16
613
1,060
561
499
89
2
module Main where import Data.List import Hash import System.Environment main = do args <- getArgs if(2 == ( length args) ) then runScript $ last args else runInteractive
IvanSindija/Project-Shell-Hash
Main.hs
gpl-3.0
172
0
11
29
60
33
27
7
2
{-# LANGUAGE RecordWildCards #-} module Pusher.Options where import System.Console.GetOpt import System.Info import qualified Config import Data.Version (showVersion) import Paths_pusher (version) import Aws.S3.Core defaultOptions :: Options defaultOptions = Options { optShowVersion = False , optKeyName = "default" , optBucket = Nothing , optPath = Nothing , optFiles = [] , optMime = Nothing , optAcl = Just "AclPublicRead" , optEnc = Nothing , optOperation = Nothing , optIsGzip = False , optKeepDirs = False } options :: [OptDescr (Options -> Options)] options = [ Option "v" ["version"] (NoArg (\opts -> opts{ optShowVersion = True })) "Show version info." , Option "k" ["keyname"] (ReqArg (\s opts -> opts{ optKeyName = s }) "keyname") "AWS credential key name." , Option "b" ["bucket"] (ReqArg (\s opts -> opts{ optBucket = Just s }) "bucket") "Destination bucket." , Option "p" ["path"] (ReqArg (\s opts -> opts{ optPath = Just s }) "path") "Destination path." , Option "" ["mime"] (ReqArg (\s opts -> opts{ optMime = Just s }) "mime") "Destination mime-type." , Option "" ["enc"] (ReqArg (\s opts -> opts{ optMime = Just s }) "enc") "Destination file encoding." , Option "" ["acl"] (ReqArg (\s opts -> opts{ optAcl = Just s }) "acl") "Destination canned ACL." , Option "z" ["gzip"] (NoArg (\opts -> opts{ optIsGzip = True })) $ unwords [ "Uploaded files should maintain their .gz extension" , "and be served from S3 with a content-type of" , "application/x-gzip and will not be served gzip" , "encoded." ] , Option "d" ["dirs"] (NoArg (\opts -> opts{ optKeepDirs = True })) $ unwords [ "Uploaded files should maintain their local directory" , "structures." ] , Option "o" ["op"] (ReqArg (\s opts -> opts{ optOperation = readOperation s }) "op") (unwords $ "Operation command. Valid values are" : vals) ] where vals = map showOperation [ OperationUploadFile ] header :: String header = "Usage: pusher [options] INPUT_FILE1 INPUT_FILE2 INPUT_FILE3 ..." fullVersion :: String fullVersion = concat [ programVersion , " (" , "ghc-", Config.cProjectVersion, "-", arch, "-", os , ")" ] programVersion :: String programVersion = "pusher v" ++ showVersion version data Options = Options { optShowVersion :: Bool , optKeyName :: String , optBucket :: Maybe String , optPath :: Maybe String , optFiles :: [FilePath] , optMime :: Maybe String , optEnc :: Maybe String , optAcl :: Maybe String , optOperation :: Maybe Operation , optIsGzip :: Bool , optKeepDirs :: Bool } deriving (Show, Eq) readAcl :: String -> Maybe CannedAcl readAcl "AclPrivate" = Just AclPrivate readAcl "AclPublicRead" = Just AclPublicRead readAcl "AclPublicReadWrite" = Just AclPublicReadWrite readAcl "AclAuthenticatedRead" = Just AclAuthenticatedRead readAcl "AclBucketOwnerRead" = Just AclBucketOwnerRead readAcl "AclBucketOwnerFullControl" = Just AclBucketOwnerFullControl readAcl "AclLogDeliveryWrite" = Just AclLogDeliveryWrite readAcl _ = Nothing readOperation :: String -> Maybe Operation readOperation "upload-file" = Just OperationUploadFile readOperation _ = Nothing showOperation :: Operation -> String showOperation OperationUploadFile = "upload-file" data Operation = OperationUploadFile deriving (Show, Eq)
schell/pusher
src/Pusher/Options.hs
gpl-3.0
4,399
0
13
1,686
961
539
422
92
1
{-# LANGUAGE RecursiveDo, OverloadedStrings #-} module Estuary.Widgets.TransformedPattern where import Reflex import Reflex.Dom hiding (Subtract,End) import Control.Monad import Data.Map import Data.List import Data.Text (Text) import qualified Data.Text as T import GHC.Real import Data.Maybe (fromJust) import Text.Read import Estuary.Tidal.Types import Estuary.Widgets.Reflex import qualified Estuary.Widgets.SpecificPattern as Sp import Estuary.Utility (lastOrNothing) import Estuary.Types.Hint import Estuary.Widgets.W structureEditor :: MonadWidget t m => Dynamic t TransformedPattern -> W t m (Variable t TransformedPattern) structureEditor x = variableWidget x topLevelTransformedPatternWidget topLevelTransformedPatternWidget :: MonadWidget t m => TransformedPattern -> Event t TransformedPattern -> W t m (Event t TransformedPattern) topLevelTransformedPatternWidget i delta = do let updates = fmap midLevelTransformedPatternWidget delta w <- widgetHold (midLevelTransformedPatternWidget i) updates let edits = switchPromptlyDyn $ fmap fst w hints $ switchPromptlyDyn $ fmap snd w return edits midLevelTransformedPatternWidget:: MonadWidget t m => TransformedPattern -> m (Event t TransformedPattern, Event t [Hint]) midLevelTransformedPatternWidget iTransPat = do tuple <- resettableTransformedPatternWidget iTransPat never let dynVal = fmap (\(x,_,_)->x) tuple -- let editEv = tagPromptlyDyn dynVal $ switchPromptlyDyn $ fmap (\(_,x,_)->x) tuple -- :: EditSignal a let editEv = updated dynVal -- ** BROKEN: in ensemble mode this will lead to infinite request-response cycles in ensembles where nClients > 1 -- structure editor needs to be reworked around Editor monad -- until then, we will just remove it from default views let hs = fmap (:[]) $ switchPromptlyDyn $ fmap (\(_,_,x)->x) tuple return (editEv,hs) popupSpecificPatternWidget :: (MonadWidget t m)=> SpecificPattern -> Event t () -> m (Dynamic t (SpecificPattern, Event t (EditSignal a),Event t Hint)) popupSpecificPatternWidget iValue _ = elClass "div" "patternTransformerWidget-or-popupSpecificPatternWidget" $ mdo let popup = specificPatternPopup [DeleteMe, TransformMe] openEv <- clickableSpanClass showSpecPat "primary-color code-font background" () dynPopup <- liftM switchPromptlyDyn $ flippableWidget (return never) popup False $ updated dynOpen dynOpen <- toggle False $ leftmost [openEv,(() <$ )dynPopup] let changeEvents = fmap ((\x->case x of ChangeValue a->a;otherwise->(S $ Blank Inert)) . fromJust) $ ffilter (\x->case x of Just (ChangeValue a) ->True;otherwise->False) dynPopup let deleteEvent = fmap (\x->case x of Just DeleteMe -> DeleteMe; otherwise->Close) $ ffilter (\x-> case x of Just (DeleteMe)->True;otherwise->False) dynPopup let transformEvent = fmap (\x->case x of Just TransformMe -> TransformMe; otherwise->Close) $ ffilter (\x-> case x of Just (TransformMe)->True; otherwise->False) dynPopup specPatTuple <- liftM join $ widgetHold (Sp.specificContainer iValue never) $ fmap (flip Sp.specificContainer $ never) changeEvents let specPat = fmap (\(x,_,_)->x) specPatTuple let showSpecPat = fmap hack specPat return $ fmap (\(x,y,z)-> (x,leftmost [transformEvent,deleteEvent],z)) specPatTuple where hack (Accelerate _) = " accelerate " hack (Bandf _) = " bandf " hack (Bandq _) = " bandq " -- sorry... hack (Begin _) = " begin " hack (Coarse _) = " coarse " hack (Crush _) = " crush " hack (Estuary.Tidal.Types.Cut _) = " cut " hack (Cutoff _) = " cutoff " hack (Delay _) = " delay " hack (Delaytime _) = " delaytime " hack (Delayfeedback _) = " delayfeedback " hack (End _) = " end " hack (Gain _) = " gain" hack (Hcutoff _) = " hcutoff" hack (Hresonance _) = " hresonance" hack (Loop _) = " loop " hack (N _) = " n " hack (Pan _) = " pan " hack (Resonance _) = " resonance " hack (S _) = " s " hack (Shape _) = " shape " hack (Sound _) = " sound " hack (Speed _) = " speed " hack (Unit _) = " unit " hack (Up _) = " up " hack (Vowel _) = " vowel " specificPatternPopup:: MonadWidget t m => [EditSignal SpecificPattern] -> m (Event t (Maybe (EditSignal SpecificPattern))) specificPatternPopup actionList = elClass "div" "popupMenu" $ do let specMap = fromList $ zip [(0::Int)..] iValueList let ddMap = constDyn $ fromList $ zip [(0::Int)..] ["accelerate", "bandf", "bandq", "begin", "coarse", "crush", "cut", "cutoff", "delay","delayfeedback","delaytime", "end", "gain", "hcutoff", "hresonance", "loop", "n", "pan", "resonance", "s", "shape", "speed", "unit","up", "vowel"] -- Map (Map k func) String dd <- dropdown (-1) ddMap (def & attributes .~ constDyn ("class" =: "code-font background primary-color primary-borders")) let specPatKey = _dropdown_value dd let specChange = fmap (Just . ChangeValue . maybe (S $ Blank Inert) id . (flip Data.Map.lookup) specMap) specPatKey let popupList = fmap (\x->clickableDivClass' (T.pack $ show x) "primary-color code-font background" (Just x)) actionList -- [m (Maybe (EditSignal))] edits <- liftM id $ Control.Monad.sequence popupList closeMenu <- clickableDivClass' "close" "primary-color code-font background" (Nothing) return $ (leftmost $ edits ++[closeMenu,updated specChange]) where iValueList = [ (Accelerate $ Atom 0 Inert Once), (Bandf $ Atom 440 Inert Once), (Bandq $ Atom 10 Inert Once), (Begin $ Atom 0 Inert Once), (Coarse $ Atom 0 Inert Once), (Crush $ Atom 16 Inert Once), (Estuary.Tidal.Types.Cut $ Atom 1 Inert Once), (Cutoff $ Atom 440 Inert Once), (Delay $ Atom 0 Inert Once), (Delayfeedback $ Atom 0 Inert Once), (Delaytime $ Atom 0.5 Inert Once), (End $ Atom 1 Inert Once), (Gain $ Atom 1 Inert Once), (Hcutoff $ Atom 440 Inert Once), (Hresonance $ Atom 20 Inert Once), (Loop $ Atom 0 Inert Once), (N $ Atom 0 Inert Once), (Pan $ Atom 0.5 Inert Once), (Resonance $ Atom 0.5 Inert Once), (S $ Atom "~" Inert Once), (Shape $ Atom 0.5 Inert Once), (Speed $ Atom 1 Inert Once), (Unit $ Atom 'c' Inert Once), (Up $ Atom 0 Inert Once), (Vowel $ Atom 'o' Inert Once)] patternCombinatorDropDown :: MonadWidget t m => PatternCombinator -> Event t () -> m (Dynamic t (PatternCombinator,Event t (EditSignal a))) patternCombinatorDropDown iValue _ = do let ddMapVals = fromList $ zip [(1::Int)..] [Merge,Add,Subtract,Multiply,Divide] let ddMap = constDyn $ fromList $ zip [(1::Int)..] $ fmap (T.pack . show) [Merge,Add,Subtract,Multiply,Divide] dd <- dropdown iIndex ddMap def let choice = _dropdown_value dd let val = fmap (maybe Merge id . (flip Data.Map.lookup) ddMapVals) choice return $ fmap (\x->(x,never)) val where iIndex = case iValue of (Merge) -> 1 (Add) -> 2 (Subtract) -> 3 (Multiply) -> 4 (Divide) -> 5 -- sorry.... patternCombinatorDropDown' :: MonadWidget t m => PatternCombinator -> Event t () -> m (Dynamic t (PatternCombinator,Event t (EditSignal a))) patternCombinatorDropDown' _ _ = do return $ constDyn (Merge,never) resettableTransformedPatternWidget :: MonadWidget t m => TransformedPattern -> Event t (EditSignal a) -> m (Dynamic t(TransformedPattern, Event t (EditSignal a),Event t Hint)) resettableTransformedPatternWidget iTransPat ev = mdo val <- resettableWidget (transformedPat) iTransPat ev resetEvent let tPat = fmap (\(x,_,_)->x) val let e = switchPromptlyDyn $ fmap (\(_,x,_)->x) val let h = switchPromptlyDyn $ fmap (\(_,_,x)->x) val let resetEvent = tagPromptlyDyn tPat $ ffilter (\x-> case x of RebuildMe->True; DeleteMe -> True; otherwise -> False) e return $ fmap (\x->(x,e,h)) tPat transformedPat :: MonadWidget t m => TransformedPattern -> Event t (EditSignal a) -> m (Dynamic t (TransformedPattern, Event t (EditSignal a), Event t Hint)) transformedPat (EmptyTransformedPattern) _ = do x <- liftM (UntransformedPattern (S (Atom "~" Inert Once)) <$) $ dynButton "+" value <- holdDyn EmptyTransformedPattern x let event = (RebuildMe <$) x return $ fmap (\y -> (y,event,never)) value transformedPat (UntransformedPattern specificPattern) _= do sPatTuple <- popupSpecificPatternWidget specificPattern never let sPat = fmap (\(x,_,_)->x) sPatTuple let sEv = switchPromptlyDyn $ fmap (\(_,x,_)->x) sPatTuple let delete = ffilter (\x->case x of DeleteMe->True;otherwise->False) sEv let transform = ffilter (\x->case x of TransformMe->True;otherwise->False) sEv let hint = switchPromptlyDyn $ fmap (\(_,_,h)->h) sPatTuple let tPat = fmap UntransformedPattern sPat combine <- el "div" $ dynButton "+" let delete' = (EmptyTransformedPattern <$) delete let updatedValue = attachPromptlyDynWith (\sp _-> constDyn $ TransformedPattern NoTransformer sp) tPat transform let combineValue = attachPromptlyDynWith (\sp trans-> constDyn $ TransformedPattern (Combine sp Merge) $ UntransformedPattern (Speed $ Atom 1 Inert Once)) sPat combine let updatedValue' = leftmost [updatedValue, combineValue, fmap constDyn delete'] value <- liftM join $ holdDyn tPat updatedValue' let rebuildEvents = leftmost [(DeleteMe <$) delete, (RebuildMe <$) transform, (RebuildMe <$) combine] return $ fmap (\x->(x,rebuildEvents,hint)) value transformedPat (TransformedPattern (Combine iSpecPat iPatComb) EmptyTransformedPattern) _ = transformedPat (UntransformedPattern iSpecPat) never transformedPat (TransformedPattern (Combine iSpecPat iPatComb) iTransPat) _ = do sPatTuple <- popupSpecificPatternWidget iSpecPat never let sPat = fmap (\(x,_,_)->x) sPatTuple let sHint = switchPromptlyDyn $ fmap (\(_,_,h)->h) sPatTuple let sEv = switchPromptlyDyn $ fmap (\(_,x,_)->x) sPatTuple let delete = ffilter (\x->case x of DeleteMe->True;otherwise->False) sEv let transform = ffilter (\x->case x of TransformMe->True;otherwise->False) sEv addAfter <- el "div" $ dynButton "+" (comb,tPatTuple) <- el "div" $ do (c,_) <- liftM splitDynPure $ patternCombinatorDropDown' iPatComb never t <- resettableTransformedPatternWidget iTransPat never -- this one has to have the 'reset' wrapper around it return (c,t) let tPat = fmap (\(x,_,_)->x) tPatTuple addInbetweenVal <- do let x = (\sp c-> TransformedPattern (Combine sp Merge) . TransformedPattern (Combine sp c)) <$> sPat <*> comb return $ (\tp cons->cons tp) <$> tPat <*> x let tEv = switchPromptlyDyn $ fmap (\(_,ev,_)->ev) tPatTuple let tHint = switchPromptlyDyn $ fmap (\(_,_,h)->h) tPatTuple val <- do let x = (\x y -> TransformedPattern (Combine x y)) <$> sPat <*> comb return $ (\t cons -> cons t) <$> tPat <*> x let childDeleteMe = ffilter (\x ->case x of DeleteMe ->True; otherwise-> False) tEv let childIsEmpty = ffilter id $ attachPromptlyDynWith (\x _->case x of EmptyTransformedPattern->True;otherwise->False) tPat childDeleteMe let transVal = fmap (TransformedPattern NoTransformer) val let untransPat = fmap UntransformedPattern sPat let rebuildVal = leftmost [(tPat <$) delete, (untransPat <$) childIsEmpty, (transVal <$) transform, (addInbetweenVal <$) addAfter] val' <- liftM join $ holdDyn val rebuildVal return $ fmap (\x->(x, leftmost [(DeleteMe <$) delete, (RebuildMe <$) transform,(RebuildMe <$) childDeleteMe, (RebuildMe <$) addAfter],leftmost [tHint,sHint])) val' transformedPat (TransformedPattern iPatTrans iTransPat) _ = do (patTrans,deleteTransformer) <- liftM splitDynPure $ patternTransformerWidget iPatTrans never tPatTuple <- el "div" $ resettableTransformedPatternWidget iTransPat never let transPat = fmap (\(x,_,_)->x) tPatTuple let tEv = switchPromptlyDyn $ fmap (\(_,ev,_)->ev) tPatTuple let deleteEvent = ffilter (\x->case x of DeleteMe->True;otherwise->False) tEv let tHint = switchPromptlyDyn $ fmap (\(_,_,x)->x) tPatTuple let rebuildVal = tagPromptlyDyn transPat $ leftmost [switchPromptlyDyn deleteTransformer, deleteEvent] let newTransPat = (\x y-> TransformedPattern x y) <$> patTrans <*> transPat val <- liftM join $ holdDyn newTransPat $ fmap constDyn rebuildVal return $ fmap (\x-> (x,leftmost [deleteEvent, (RebuildMe <$) rebuildVal],tHint)) val paramWidget :: MonadWidget t m => PatternTransformer -> m (Dynamic t PatternTransformer) paramWidget (Jux trans) = do trans' <- parameteredPatternTransformer trans never let val' = fmap (\(next,_)-> Jux next) trans' return val' paramWidget (Every num trans) = do let attrs = fromList $ zip ["type","style"] ["number","width:25px"] input <- textInput $ def & textInputConfig_attributes .~ (constDyn attrs) & textInputConfig_initialValue .~ (T.pack $ show num) let input' = _textInput_value input -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Int)) nextTrans <- parameteredPatternTransformer trans never let val' = (\k (next,_)-> Every k next) <$> val <*> nextTrans return val' paramWidget (Slow i) = do let numer = numerator i let denom = denominator i input <- textInput $ def & textInputConfig_attributes .~ (constDyn (fromList $ zip ["type","style"] ["number","width:25px"])) & textInputConfig_initialValue .~ (T.pack $ show numer) let input' = _textInput_value input -- Dyn string input2 <- textInput $ def & textInputConfig_attributes .~ (constDyn (fromList $ zip ["type","style"] ["number","width:30px"])) & textInputConfig_initialValue .~ (T.pack $ show denom) let input2' = _textInput_value input2 -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Integer)) let val2 = ffor input2' (\x-> maybe 1 id (readMaybe (T.unpack x)::Maybe Integer)) return $ (\x y-> Slow ((x%y)::Rational)) <$> val <*> val2 paramWidget (Density i)= do let numer = numerator i let denom = denominator i input <- textInput $ def & textInputConfig_attributes .~ (constDyn (fromList $ zip ["type","style"] ["number","width:30px"])) & textInputConfig_initialValue .~ (T.pack $ show numer) let input' = _textInput_value input -- Dyn string input2 <- textInput $ def & textInputConfig_attributes .~ (constDyn (fromList $ zip ["type","style"] ["number","width:30px"])) & textInputConfig_initialValue .~ (T.pack $ show denom) let input2' = _textInput_value input2 -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Integer)) let val2 = ffor input2' (\x-> maybe 1 id (readMaybe (T.unpack x)::Maybe Integer)) return $ (\x y-> Density $ (x%y::Rational) ) <$> val <*> val2 paramWidget (DegradeBy i) = do input <- textInput $ def & textInputConfig_attributes .~ (constDyn ("type"=:"number")) & textInputConfig_initialValue .~ (T.pack $ show i) let input' = _textInput_value input -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Double)) let val' = ffor val (\k-> DegradeBy k) return val' paramWidget (Chop i) = do input <- textInput $ def & textInputConfig_attributes .~ (constDyn ("type"=:"number")) & textInputConfig_initialValue .~ (T.pack $ show i) let input' = _textInput_value input -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Int)) let val' = ffor val (\k-> Chop k) return val' paramWidget (Combine iSPat iPatComb) = do sPat <- popupSpecificPatternWidget iSPat never >>= (return . fmap (\(x,_,_)->x)) comb <- patternCombinatorDropDown' iPatComb never >>= (return . fmap fst) return $ Combine <$> sPat <*> comb paramWidget transformer = return $ constDyn transformer parameteredPatternTransformer::MonadWidget t m => PatternTransformer -> Event t () -> m (Dynamic t (PatternTransformer, Event t (EditSignal a))) parameteredPatternTransformer i _ = el "div" $ do let transMap = fromList $ zip [0::Int,1..] [NoTransformer,Rev,Slow 1, Density 1, Brak,Every 1 NoTransformer, Jux NoTransformer, Chop 1,Combine (Speed $ Atom 1 Inert Once) Multiply] let ddMap = constDyn $ fromList $ zip [0::Int,1..] ["NoTransformer","Rev","Slow","Density","Brak","Every","Jux","Chop","Combine"] delete <- liftM (DeleteMe <$) $ button "-" dd <- dropdown (hack i) ddMap def let ddVal = _dropdown_value dd -- Dynamic int let ddWidget = fmap (\k ->case Data.Map.lookup k transMap of Just a->paramWidget a; otherwise -> paramWidget NoTransformer) ddVal --Dynamic (m(dynamic transformer)) let ddWidgetValEv = updated ddWidget -- Event (M (dyn Pattern)) paramValue <- widgetHold (paramWidget i) ddWidgetValEv -- m Dynamic t(m (Dynamic PatternTrans...)) let paramValue' = join paramValue --Dyn PatternTransformer return $ fmap (\k->(k,delete)) paramValue' where hack NoTransformer = 0 hack Rev = 1 hack (Slow _) = 2 -- sorry... hack (Density _) = 3 hack Degrade = 4 hack (DegradeBy _) = 5 hack Brak = 6 hack (Every _ _)= 7 hack (Jux _) = 8 hack (Chop _) = 9 hack (Combine _ _) = 10 hack _ = 0 paramWidget'::MonadWidget t m=>PatternTransformer -> m (Dynamic t PatternTransformer) paramWidget' (Jux trans) = do trans' <- patternTransformerWidget trans never let val' = fmap (\(next,_)-> Jux next) trans' return val' paramWidget' (Every num trans) = do let attrs = fromList $ zip ["type","style"] ["number","width:25px"] input <- textInput $ def & textInputConfig_attributes .~ (constDyn attrs) & textInputConfig_initialValue .~ (T.pack $ show num) let input' = _textInput_value input -- Dyn string let val = ffor input' (\x->maybe 1 id (readMaybe (T.unpack x)::Maybe Int)) nextTrans <- patternTransformerWidget trans never let val' = (\k (next,_)-> Every k next) <$> val <*> nextTrans return val' paramWidget' x = paramWidget x patternTransformerWidget :: (MonadWidget t m)=> PatternTransformer -> Event t () -> m (Dynamic t (PatternTransformer, Event t (EditSignal a))) patternTransformerWidget iValue _ = elClass "div" "patternTransformerWidget-or-popupSpecificPatternWidget" $ mdo let popup = patternTransformerPopup [DeleteMe] openEv <- clickableSpanClass showTransformer' "primary-color code-font background" () dynPopup <- liftM switchPromptlyDyn $ flippableWidget (return never) popup False $ updated dynOpen dynOpen <- toggle False $ leftmost [openEv,(() <$ )dynPopup] let changeEvents = fmap ((\x->case x of ChangeValue a->a;otherwise->NoTransformer) . fromJust) $ ffilter (\x->case x of Just (ChangeValue a) ->True;otherwise->False) dynPopup let deleteEvent = fmap (\x->case x of Just DeleteMe -> DeleteMe; otherwise->Close) $ ffilter (\x-> case x of Just (DeleteMe)->True;otherwise->False) dynPopup transformer <- holdDyn NoTransformer changeEvents let showTransformer = fmap hack transformer showTransformer' <- holdDyn (hack iValue) $ updated showTransformer let widget = fmap paramWidget' transformer paramValue <- liftM join $ widgetHold (paramWidget' iValue) $ updated widget return $ fmap (\x->(x,deleteEvent)) paramValue where hack NoTransformer = " NoTransformer " hack Rev = " Rev " hack (Slow _) = " Slow " -- sorry... hack (Density _) = " Density " hack Degrade = " Degrade " hack (DegradeBy _) = " DegradeBy " hack Brak = " Brak " hack (Every _ _)= " Every " hack (Jux _) = " Jux " hack (Chop _) = " Chop " hack (Combine _ _) = " Combine " patternTransformerPopup:: MonadWidget t m => [EditSignal PatternTransformer] -> m (Event t (Maybe (EditSignal PatternTransformer))) patternTransformerPopup actionList = elClass "div" "popupMenu" $ do let transMap = fromList $ zip [0::Int,1..] [NoTransformer,Rev,Slow 1, Density 1, Brak,Every 1 NoTransformer, Jux NoTransformer, Chop 1,Combine (Speed $ Atom 1 Inert Once) Multiply] let ddMap = constDyn $ fromList $ zip [0::Int,1..] ["NoTransformer","Rev","Slow","Density","Brak","Every","Jux","Chop","Combine"] dd <- dropdown (-1) ddMap def let transformerKey = _dropdown_value dd let transformerChange = fmap (Just . ChangeValue . maybe NoTransformer id . (flip Data.Map.lookup) transMap) transformerKey let popupList = fmap (\x->clickableDivClass' (T.pack $ show x) "primary-color code-font background" (Just x)) actionList -- [m (Maybe (EditSignal))] edits <- liftM id $ Control.Monad.sequence popupList closeMenu <- clickableDivClass' "close" "primary-color code-font background" (Nothing) return $ (leftmost $ edits ++[closeMenu,updated transformerChange])
d0kt0r0/estuary
client/src/Estuary/Widgets/TransformedPattern.hs
gpl-3.0
20,375
0
22
3,597
8,090
4,101
3,989
326
32
module Main where import Helpers main :: IO () main = putStrLn (hello "World !!!!")
dominicusin/gasta
src/Main.hs
gpl-3.0
88
0
7
19
31
17
14
4
1
module Main where import Graphics.UI.Gtk import Graphics.UI.Gtk.Builder import Subgetter.Core main = do initGUI builder <- builderNew builderAddFromFile builder "sublist.glade" window <- builderGetObject builder castToWindow "main" chooser <- builderGetObject builder castToFileChooserDialog "main" results <- builderGetObject builder castToTreeView "results" treeViewSetHeadersVisible results True colLang <- treeViewColumnNew colRelease <- treeViewColumnNew colMovie <- treeViewColumnNew treeViewColumnSetTitle colLang "Language" treeViewColumnSetTitle colRelease "Release name" treeViewColumnSetTitle colMovie "Movie name" treeViewColumnSetResizable colLang True treeViewColumnSetResizable colRelease True treeViewColumnSetResizable colMovie True renderer1 <- cellRendererTextNew renderer2 <- cellRendererTextNew renderer3 <- cellRendererTextNew cellLayoutPackStart colLang renderer1 True cellLayoutPackStart colRelease renderer2 True cellLayoutPackStart colMovie renderer3 True treeViewAppendColumn results colLang treeViewAppendColumn results colRelease treeViewAppendColumn results colMovie onFileActivated chooser $ do Just filename <- fileChooserGetFilename chooser -- dialog <- messageDialogNew (Just window) [DialogDestroyWithParent] MessageInfo ButtonsNone filename -- _ <- dialogRun dialog url <- getSubsUrl filename doc <- openDoc url let subs = getSubs doc model <- listStoreNew subs cellLayoutSetAttributes colLang renderer1 model $ \row -> [ cellText := subtitleLang row ] cellLayoutSetAttributes colRelease renderer2 model $ \row -> [ cellText := releaseName row ] cellLayoutSetAttributes colMovie renderer3 model $ \row -> [ cellText := movieName row ] treeViewSetModel results model manager <- recentManagerGetDefault Just folder <- fileChooserGetCurrentFolder chooser recentManagerAddItem manager $ "file://" ++ folder ++ "/" return () onRowActivated results $ do return () onDestroy window mainQuit widgetShowAll window mainGUI
lisperatu/subgetter
UI.hs
gpl-3.0
2,103
0
14
366
482
208
274
49
1
-- | Load & infer expressions for sugar processing -- (unify with stored ParamLists, recursion support) {-# LANGUAGE TemplateHaskell, TupleSections #-} module Lamdu.Sugar.Convert.Load ( InferOut(..), irVal, irCtx , inferDef , inferDefExpr , makeNominalsMap , readValAndAddProperties , InferFunc, unmemoizedInfer ) where import qualified Control.Lens as Lens import qualified Control.Monad.State as State import qualified Data.Map as Map import Hyper import Hyper.Infer import Hyper.Syntax.Nominal (NominalDecl, nScheme) import Hyper.Syntax.Scheme (sTyp) import Hyper.Type.Functor (_F) import Hyper.Unify (UVar, unify) import Hyper.Unify.Generalize (GTerm(..)) import Hyper.Unify.New (newUnbound) import Lamdu.Calc.Infer (PureInfer, runPureInfer, InferState(..), loadDeps, emptyPureInferState, varGen) import qualified Lamdu.Calc.Lens as ExprLens import qualified Lamdu.Calc.Term as V import qualified Lamdu.Calc.Type as T import qualified Lamdu.Data.Definition as Definition import qualified Lamdu.Debug as Debug import Lamdu.Expr.IRef (HRef) import qualified Lamdu.Expr.IRef as ExprIRef import qualified Lamdu.Expr.Load as ExprLoad import qualified Lamdu.Sugar.Convert.Input as Input import qualified Lamdu.Sugar.Internal.EntityId as EntityId import Lamdu.Sugar.Types import qualified Revision.Deltum.IRef as IRef import Revision.Deltum.Transaction (Transaction) import Lamdu.Prelude type T = Transaction type InferFunc a = Definition.Expr (Ann a # V.Term) -> PureInfer (V.Scope # UVar) (Ann (a :*: InferResult UVar) # V.Term, V.Scope # UVar) unmemoizedInfer :: InferFunc a unmemoizedInfer defExpr = do addDeps <- loadDeps (defExpr ^. Definition.exprFrozenDeps) scope <- Lens.view id <&> addDeps infer (defExpr ^. Definition.expr) & local (const scope) <&> (, scope) preparePayloads :: V.Scope # UVar -> Ann (HRef m :*: InferResult (Pure :*: UVar)) # V.Term -> Ann (Input.Payload m ()) # V.Term preparePayloads topLevelScope inferredVal = inferredVal & hflipped %~ hmap (const f) & Input.preprocess topLevelScope [] where f (valIProp :*: inferRes) = Input.Payload { Input._varRefsOfLambda = [] -- TODO , Input._entityId = eId , Input._localsInScope = [] , Input._stored = valIProp , Input._inferRes = inferRes , Input._inferScope = V.emptyScope -- UGLY: This is initialized by initScopes , Input._userData = () } where eId = valIProp ^. ExprIRef.iref . _F & IRef.uuid & EntityId.EntityId makeNominalsMap :: Monad m => [NominalId] -> T m (Map NominalId (Pure # NominalDecl T.Type)) makeNominalsMap tids = traverse_ loadForTid tids & (`State.execStateT` mempty) <&> Map.mapMaybe id where loadForTid tid = do loaded <- State.get unless (Map.member tid loaded) $ do nom <- ExprLoad.nominal tid & lift Map.insert tid (nom ^? Lens._Right) loaded & State.put nom ^.. Lens._Right . _Pure . nScheme . sTyp . ExprLens.tIds & traverse_ loadForTid readValAndAddProperties :: Monad m => HRef m # V.Term -> T m (Ann (HRef m) # V.Term) readValAndAddProperties prop = ExprIRef.readRecursively (prop ^. ExprIRef.iref) <&> hflipped %~ hmap (const (:*: Const ())) <&> ExprIRef.toHRefs (prop ^. ExprIRef.setIref) <&> hflipped %~ hmap (const (^. _1)) data InferOut m = InferOut { _irVal :: Ann (Input.Payload m [EntityId]) # V.Term , _irCtx :: InferState } Lens.makeLenses ''InferOut runInferResult :: Debug.Monitors -> PureInfer (V.Scope # UVar) (Ann (HRef m :*: InferResult UVar) # V.Term, V.Scope # UVar) -> Either (Pure # T.TypeError) (InferOut m) runInferResult _monitors act = -- TODO: use _monitors case runPureInfer V.emptyScope (InferState emptyPureInferState varGen) act of Left x -> Left x Right ((inferredTerm, topLevelScope), inferState0) -> case inferUVarsApplyBindings inferredTerm & runPureInfer () inferState0 of Left x -> Left x Right (resolvedTerm, _inferState1) -> InferOut ( preparePayloads topLevelScope resolvedTerm & hflipped %~ hmap (const setUserData) ) inferState0 & Right where setUserData pl = pl & Input.userData %~ \() -> [pl ^. Input.entityId] inferDef :: InferFunc (HRef m) -> Debug.Monitors -> Definition.Expr (Ann (HRef m) # V.Term) -> V.Var -> Either (Pure # T.TypeError) (InferOut m) inferDef inferFunc monitors defExpr defVar = do defTv <- newUnbound (inferredVal, scope) <- inferFunc defExpr & local (V.scopeVarTypes . Lens.at defVar ?~ MkHFlip (GMono defTv)) (inferredVal, scope) <$ unify defTv (inferredVal ^. hAnn . _2 . inferResult) & runInferResult monitors inferDefExpr :: InferFunc (HRef m) -> Debug.Monitors -> Definition.Expr (Ann (HRef m) # V.Term) -> Either (Pure # T.TypeError) (InferOut m) inferDefExpr inferFunc monitors defExpr = inferFunc defExpr & runInferResult monitors
Peaker/lamdu
src/Lamdu/Sugar/Convert/Load.hs
gpl-3.0
5,438
0
18
1,456
1,624
877
747
-1
-1
-- | A standard collections of modules covering the most common areas of mathematics/arithmetic. module MathPrelude ( module X ) where import MathPrelude.Prelude.CorePrelude as X import MathPrelude.Prelude.IntegralLists as X import MathPrelude.Classes.Group as X import MathPrelude.Classes.Ring as X import MathPrelude.Classes.EuclideanDomain as X import MathPrelude.Classes.Field as X import MathPrelude.Classes.Integral as X import MathPrelude.Classes.Rational as X import MathPrelude.Classes.Real as X import MathPrelude.Classes.Norm as X import MathPrelude.Classes.VectorSpace as X import MathPrelude.Classes.Approximate as X import MathPrelude.Classes.Transcendental as X import MathPrelude.Constructions.Ratio as X
RossOgilvie/MathPrelude
MathPrelude.hs
gpl-3.0
727
0
4
83
123
92
31
15
0