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
main = print "Hello, World!"
charleso/intellij-haskforce
tests/gold/parser/Hello00001.hs
apache-2.0
29
0
5
5
9
4
5
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="it-IT"> <title>Directory List v1.0</title> <maps> <homeID>directorylistv1</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/directorylistv1/src/main/javahelp/help_it_IT/helpset_it_IT.hs
apache-2.0
976
78
66
157
412
209
203
-1
-1
module Type4 where data Data = C1 Int Char | C2 Int | C3 Float errorData field dat function = errorData ("the binding for " ++ field ++ " in a pattern binding involving " ++ dat ++ " has been removed in function " ++ function) f :: Data -> Data -> a f (C1 b c) (C1 b1 b2) = errorData "a1" "C1" "f" f (C2 a) = a f (C3 a) = 42 (C1 b c) = 89
kmate/HaRe
old/testing/removeField/Type4_TokOut.hs
bsd-3-clause
372
0
11
114
151
78
73
-1
-1
module Oops where -- highlight >x +< in f, then select IntroNewDef main = print ((f 1) 2, gaga True) where f x y = x + y gaga h = ("g: " ++) (show h)
SAdams601/HaRe
old/testing/introNewDef/Oops.hs
bsd-3-clause
163
0
9
49
68
36
32
4
1
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-} -- | -- Module : Data.Text.Search -- Copyright : (c) Bryan O'Sullivan 2009 -- -- License : BSD-style -- Maintainer : [email protected], [email protected], -- [email protected] -- Stability : experimental -- Portability : GHC -- -- Fast substring search for 'Text', based on work by Boyer, Moore, -- Horspool, Sunday, and Lundh. -- -- References: -- -- * R. S. Boyer, J. S. Moore: A Fast String Searching Algorithm. -- Communications of the ACM, 20, 10, 762-772 (1977) -- -- * R. N. Horspool: Practical Fast Searching in Strings. Software - -- Practice and Experience 10, 501-506 (1980) -- -- * D. M. Sunday: A Very Fast Substring Search Algorithm. -- Communications of the ACM, 33, 8, 132-142 (1990) -- -- * F. Lundh: The Fast Search Algorithm. -- <http://effbot.org/zone/stringlib.htm> (2006) module Data.Text.Search ( indices --LIQUID , T(..) ) where import qualified Data.Text.Array as A import Data.Word (Word64) import Data.Text.Internal (Text(..)) import Data.Bits ((.|.), (.&.)) import Data.Text.UnsafeShift (shiftL) --LIQUID import Data.Word (Word16) import Language.Haskell.Liquid.Prelude --LIQUID FIXME: we don't currently parse the `:*` syntax used originally data T = {-# UNPACK #-} !Word64 `T` {-# UNPACK #-} !Int {-@ qualif Foo(v:int,x:int): v <= x + 1 @-} {-@ qualif Diff(v:int,l:int,d:int): v = (l - d) + 1 @-} {-@ measure tskip :: T -> Int tskip (T mask skip) = skip @-} -- | /O(n+m)/ Find the offsets of all non-overlapping indices of -- @needle@ within @haystack@. The offsets returned represent -- locations in the low-level array. -- -- In (unlikely) bad cases, this algorithm's complexity degrades -- towards /O(n*m)/. {-@ indices :: needle:Text -> haystack:Text -> [(TValidIN haystack (tlen needle))]<{\ix iy -> (ix+(tlen needle)) <= iy}> @-} indices :: Text -- ^ Substring to search for (@needle@) -> Text -- ^ Text to search in (@haystack@) -> [Int] indices _needle@(Text narr noff nlen) _haystack@(Text harr hoff hlen) --LIQUID switched first two guards, need to consider whether this is problematic.. = if nlen <= 0 || ldiff < 0 then [] else if nlen == 1 then scanOne (index _needle 0) else --LIQUID pushing definitions in to prove safety! {- LIQUID WITNESS -} let scan (d :: Int) !i = if i > ldiff then [] else let nlast = nlen - 1 z = index _needle nlast c = index _haystack (i + nlast) {- LIQUID WITNESS -} candidateMatch (d :: Int) !j = if j >= nlast then True else if index _haystack (i+j) /= index _needle j then False else candidateMatch (d-1) (j+1) delta = if nextInPattern then nlen + 1 else if c == z then skip + 1 else 1 where nextInPattern = mask .&. swizzle (index' _haystack (i+nlen)) == 0 !(mask `T` skip) = buildTable (nlen-1) _needle 0 0 (nlen-2) in if c == z && candidateMatch nlast 0 then i : scan (d-nlen) (i + nlen) else scan (d-delta) (i + delta) in scan (hlen+1) 0 where ldiff = hlen - nlen -- nlast = nlen - 1 -- z = nindex nlast -- nindex k = A.unsafeIndex narr (noff+k) -- hindex k = A.unsafeIndex harr (hoff+k) -- hindex' k | k == hlen = 0 -- | otherwise = A.unsafeIndex harr (hoff+k) -- buildTable !i !msk !skp -- | i >= nlast = (msk .|. swizzle z) :* skp -- | otherwise = buildTable (i+1) (msk .|. swizzle c) skp' -- where c = nindex i -- skp' | c == z = nlen - i - 2 -- | otherwise = skp -- swizzle k = 1 `shiftL` (fromIntegral k .&. 0x3f) -- scan !i -- | i > ldiff = [] -- | c == z && candidateMatch 0 = i : scan (i + nlen) -- | otherwise = scan (i + delta) -- where c = hindex (i + nlast) -- candidateMatch !j -- | j >= nlast = True -- | hindex (i+j) /= nindex j = False -- | otherwise = candidateMatch (j+1) -- delta | nextInPattern = nlen + 1 -- | c == z = skip + 1 -- | otherwise = 1 -- where nextInPattern = mask .&. swizzle (hindex' (i+nlen)) == 0 -- !(mask :* skip) = buildTable 0 0 (nlen-2) scanOne c = loop hlen 0 {- LIQUID WITNESS -} where loop (d :: Int) !i = if i >= hlen then [] else if index _haystack i == c then i : loop (d-1) (i+1) else loop (d-1) (i+1) {- INLINE indices #-} {-@ buildTable :: d:Nat -> pat:{v:Text | (tlen v) > 1} -> i:{v:Nat | ((v < (tlen pat)) && (v = (tlen pat) - 1 - d))} -> Word64 -> skp:{v:Nat | v < (tlen pat)} -> {v:T | (Btwn (tskip v) 0 (tlen pat))} @-} buildTable :: Int -> Text -> Int -> Word64 -> Int -> T buildTable d pat@(Text narr noff nlen) !i !msk !skp = if i >= nlast then (msk .|. swizzle z) `T` skp else let skp' = if c == z then nlen - i - 2 else skp in buildTable (d-1) pat (i+1) (msk .|. swizzle c) skp' where nlast = nlen - 1 z = index pat nlast c = index pat i swizzle k = 1 `shiftL` (fromIntegral k .&. 0x3f) {-@ index :: t:Text -> k:TValidI t -> Word16 @-} index :: Text -> Int -> Word16 index (Text arr off len) k = A.unsafeIndex arr (off+k) {-@ index' :: t:Text -> k:{v:Nat | v <= (tlen t)} -> Word16 @-} index' (Text arr off len) k = if k == len then 0 else A.unsafeIndex arr (off+k)
mightymoose/liquidhaskell
benchmarks/text-0.11.2.3/Data/Text/Search.hs
bsd-3-clause
6,324
0
24
2,392
1,046
600
446
57
11
{-# LANGUAGE OverloadedStrings #-} module Heather where import Data.Text (Text) import Data.Aeson import Control.Applicative import Control.Monad import Control.Exception import Network.HTTP.Conduit import qualified Data.ByteString.Lazy as BS data Weather = Weather { weather :: String, description :: String, temp :: Double, pressure :: Double, humidity :: Double, minTemp :: Double, maxTemp :: Double, wSpeed :: Double, wDeg :: Double } deriving (Show) instance FromJSON Weather where parseJSON (Object v) = Weather <$> ((head <$> v .: "weather") >>= (.: "main")) <*> ((head <$> v .: "weather") >>= (.: "description")) <*> ((v .: "main") >>= (.: "temp")) <*> ((v .: "main") >>= (.: "pressure")) <*> ((v .: "main") >>= (.: "humidity")) <*> ((v .: "main") >>= (.: "temp_min")) <*> ((v .: "main") >>= (.: "temp_max")) <*> ((v .: "wind") >>= (.: "speed")) <*> ((v .: "wind") >>= (.: "deg")) parseJSON _ = mzero getWeather :: String -> IO (Maybe Weather) getWeather s = do r <- try $ simpleHttp $ "http://api.openweathermap.org/data/2.5/weather?units=metric&lang=fi&q=" ++ s case (r :: Either SomeException BS.ByteString) of Left e -> return Nothing Right r -> return $ decode r
anobi/Heather
src/Heather.hs
mit
1,564
0
19
567
449
258
191
38
2
module Eval where import Parse data Store = StoreEmpty | StoreEntry String Parse.Term Store store_get :: Store -> String -> Maybe Parse.Term store_get StoreEmpty _ = Nothing store_get (StoreEntry s t store) query | s == query = Just t | otherwise = store_get store query store_put :: Store -> String -> Parse.Term -> Store store_put store str term = StoreEntry str term store eval :: Parse.Prog -> IO () eval (Parse.Prog list) = do let store = StoreEmpty eval_stmt_list list store eval_stmt_list :: [Parse.Stmt] -> Store -> IO () eval_stmt_list [] _ = do putStrLn "Done" eval_stmt_list (stmt:rest) store = do let (st, io) = eval_stmt stmt store io eval_stmt_list rest st eval_stmt :: Parse.Stmt -> Store -> (Store, IO ()) eval_stmt (Parse.STerm term) store = do let result = eval_term term store case result of Left term -> (store, putStrLn $ show term) Right str -> (store, putStrLn str) eval_stmt (Parse.SAssign string term) store = do let result = eval_term term store case result of Left new_term -> (store_put store string new_term, return ()) Right str -> (store, putStrLn str) eval_term :: Parse.Term -> Store -> Either Parse.Term String eval_term (Parse.Var string) store = do let result = store_get store string case result of Nothing -> Right $ "Lookup of var '" ++ string ++ "' failed" Just term -> eval_term term store eval_term (Parse.Abs string term) store = do -- cannot break down Abs anymore Left (Parse.Abs string term) eval_term (Parse.App (Parse.Abs str body) rterm) store = do -- handle the application let new_store = store_put store str body eval_term rterm new_store eval_term (Parse.App lterm rterm) store = do -- if lterm is not an abstraction, reduce it more let reduced_lterm = eval_term lterm store case reduced_lterm of Left rlterm -> eval_term (Parse.App rlterm rterm) store Right string -> Right string
mkfifo/lambda_calculus
impl/untyped/haskell/eval.hs
mit
1,937
0
13
406
731
352
379
49
3
import Control.Monad (join) import Data.Char (isHexDigit) import Data.List.Split (chunksOf) import Numeric (readHex) myTail :: String -> String myTail "" = "" myTail (_:xs) = xs extractDigits :: String -> String extractDigits = takeWhile isHexDigit . myTail . dropWhile (\c -> c /= 'x') splitHex :: String -> [String] splitHex = chunksOf 2 getAscii :: String -> Char getAscii = toEnum . fst . head . readHex --toChar :: Int -> Char --toChar = toEnum hexStringToString :: [String] -> String hexStringToString = map getAscii convertHexToString :: String -> String convertHexToString = hexStringToString . reverse . splitHex . extractDigits main :: IO () main = do orig <- getContents let ls = reverse $ lines orig chks = map convertHexToString ls ans = join chks putStrLn ans
reubensammut/SLAE32
Scripts/pushprint.hs
mit
812
0
11
163
268
143
125
24
1
{-# LANGUAGE Haskell2010, TemplateHaskell #-} import Control.Monad import NumericalMethods.Simple import Test.QuickCheck import Test.QuickCheck.All import System.Exit mysqrttest m guess = sqrt m main = do success <- $(quickCheckAll) (if success then exitSuccess else exitFailure)
rfdickerson/numerical-methods
quickcheck-tests.hs
mit
296
0
9
49
71
39
32
10
2
module Functions.Math ( collatz, factorial, fib, isMultipleOfAny, quicksort, multiplesOfFactors ) where collatz :: (Integral a) => a -> [a] collatz 1 = [1] collatz n | even n = n:collatz (n `div` 2) | odd n = n:collatz (n*3 + 1) factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n | n > 0 = n * factorial(n - 1) | otherwise = error "Factorial of this argument not supported" fib a b = fibs where fibs = a : b : zipWith (+) fibs (tail fibs) quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = smaller ++ [x] ++ greater where smaller = quicksort (filter (<=x) xs) greater = quicksort (filter (>x) xs) isMultipleOfAny :: (Integral a) => a -> [a] -> Bool x `isMultipleOfAny` factors = any (\f -> x `rem` f == 0) factors multiplesOfFactors :: (Integral a) => [a] -> [a] -> [a] multiplesOfFactors numList factors = filter (`isMultipleOfAny` factors) numList
anshbansal/general
Haskell/Functions/Math.hs
mit
929
0
10
211
448
241
207
29
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes, RecordWildCards #-} module Main where import JSONKit.Base import JSONKit.KeyPath import Data.Aeson import Data.Monoid import qualified Data.Map.Strict as M import Data.Text (Text) import qualified Data.Text.Encoding as T (decodeUtf8) import Data.List (intersperse) import qualified Data.List import qualified Data.Text as T import qualified Data.Text.Lazy.IO as TL import Data.Maybe (catMaybes) import Control.Applicative import Control.Monad (when) import Data.ByteString.Lazy as BL hiding (map, intersperse) import Data.Attoparsec.ByteString.Char8 (endOfLine, sepBy) import qualified Data.Attoparsec.Text as AT import qualified Data.HashMap.Lazy as HM import qualified Data.Vector as V import Data.Scientific import System.Environment (getArgs) import qualified Options.Applicative as O import qualified Text.CSV as CSV import qualified Data.Text.Lazy.Builder as B import qualified Data.Text.Lazy.Builder.Int as B import qualified Data.Text.Lazy.Builder.RealFloat as B data Options = Options { jsonExpr :: String , optArrayDelim :: Text , outputMode :: OutputMode , showHeader :: Bool , nullString :: Text , optTrueString :: Text , optFalseString :: Text , debugKeyPaths :: Bool } deriving Show data OutputMode = TSVOutput { delimiter :: String } | CSVOutput deriving (Show) parseOpts :: O.Parser Options parseOpts = Options <$> O.argument O.str (O.metavar "FIELDS") <*> (T.pack <$> O.strOption (O.metavar "DELIM" <> O.value "," <> O.short 'a' <> O.help "Concatentated array elem delimiter. Defaults to comma.")) <*> (parseCSVMode <|> parseTSVMode) <*> O.flag False True (O.short 'H' <> O.help "Include headers") <*> (T.pack <$> O.strOption (O.value "null" <> O.short 'n' <> O.long "null-string" <> O.metavar "STRING" <> O.help "String to represent null value. Default: 'null'")) <*> (T.pack <$> O.strOption (O.value "t" <> O.short 't' <> O.long "true-string" <> O.metavar "STRING" <> O.help "String to represent boolean true. Default: 't'")) <*> (T.pack <$> O.strOption (O.value "f" <> O.short 'f' <> O.long "false-string" <> O.metavar "STRING" <> O.help "String to represent boolean false. Default: 'f'")) <*> O.switch (O.long "debug" <> O.help "Debug keypaths") parseCSVMode = O.flag' CSVOutput (O.short 'c' <> O.long "csv" <> O.help "Output CSV") parseTSVMode = TSVOutput <$> (O.strOption (O.metavar "DELIM" <> O.value "\t" <> O.short 'd' <> O.help "Output field delimiter. Defaults to tab.")) opts = O.info (O.helper <*> parseOpts) (O.fullDesc <> O.progDesc "Transform JSON objects to TSV. \ \On STDIN provide an input stream of whitespace-separated JSON objects." <> O.header "jsontsv" <> O.footer "See https://github.com/danchoi/jsontsv for more information.") main = do Options{..} <- O.execParser opts x <- BL.getContents let xs :: [Value] xs = decodeStream x ks = parseKeyPath $ T.pack jsonExpr -- keypaths without alias info: ks' = [ks' | KeyPath ks' _ <- ks] when debugKeyPaths $ Prelude.putStrLn $ "key Paths " ++ show ks when showHeader $ do let hs = [case alias of Just alias' -> T.unpack alias' Nothing -> jsonExpr | (KeyPath _ alias, jsonExpr) <- Data.List.zip ks (words jsonExpr)] -- Note `words` introduces a potential bug is quoted aliases are allowed -- See https://github.com/danchoi/jsonxlsx/commit/9aedb4bf97cfa8d5635edc4780bfbf9b79b6f2ec case outputMode of TSVOutput delim -> Prelude.putStrLn . Data.List.intercalate delim $ hs CSVOutput -> Prelude.putStrLn . CSV.printCSV $ [hs] let config = Config { arrayDelim = optArrayDelim , nullValueString = nullString , trueString = optTrueString , falseString = optFalseString} case outputMode of TSVOutput delim -> mapM_ (TL.putStrLn . B.toLazyText . evalToLineBuilder config delim ks') xs CSVOutput -> Prelude.putStrLn . CSV.printCSV $ map (map T.unpack . evalToList config ks') $ xs
danchoi/jsonkit
TSV.hs
mit
4,265
0
20
985
1,173
633
540
93
4
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module TriggerTest where import Control.Exception (Exception) import Control.Monad (void) import Control.Monad.Catch (MonadCatch, MonadThrow, catch, throwM) import Control.Monad.IO.Class (MonadIO(liftIO)) import qualified Data.Text as Text import Data.Typeable (Typeable) import qualified Database.HDBC.PostgreSQL as Postgres import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertEqual, testCase) import qualified Database.Orville.PostgreSQL as O import qualified Database.Orville.PostgreSQL.Trigger as OT import AppManagedEntity.Data.Virus (Virus(..), VirusName(..), bpsVirus) import AppManagedEntity.Schema (schema, virusTable) import qualified TestDB as TestDB #if MIN_VERSION_base(4,11,0) import Control.Monad.Fail (MonadFail) #endif test_trigger :: TestTree test_trigger = TestDB.withOrvilleRun $ \run -> testGroup "Trigger Test" [ testCase "Without Transaction" $ do let oldVirus = bpsVirus newVirus = bpsVirus {virusName = VirusName (Text.pack "New Name")} run $ do TestDB.reset schema runTriggerTest $ do void $ OT.insertTriggered virusTable oldVirus assertTriggersCommitted "Expected Insert Triggers to be fired" [Inserted oldVirus] TriggerTestMonad OT.clearTriggers void $ OT.updateTriggered virusTable oldVirus newVirus assertTriggersCommitted "Expected Update Triggers to be fired" [Updated oldVirus newVirus] TriggerTestMonad OT.clearTriggers void $ OT.deleteTriggered virusTable newVirus assertTriggersCommitted "Expected Delete Triggers to be fired" [Deleted newVirus] , testCase "With Successful Transaction" $ do let oldVirus = bpsVirus newVirus = bpsVirus {virusName = VirusName (Text.pack "New Name")} run $ do TestDB.reset schema runTriggerTest $ do O.withTransaction $ do void $ OT.insertTriggered virusTable oldVirus void $ OT.updateTriggered virusTable oldVirus newVirus void $ OT.deleteTriggered virusTable newVirus assertTriggersCommitted "Expected No Triggers to be fired inside transaction" [] assertTriggersCommitted "Expected All Triggers to be fired update transaction commit" [ Inserted oldVirus , Updated oldVirus newVirus , Deleted newVirus ] , testCase "With Aborted Transaction" $ do let oldVirus = bpsVirus newVirus = bpsVirus {virusName = VirusName (Text.pack "New Name")} run $ do TestDB.reset schema runTriggerTest $ do O.withTransaction (do void $ OT.insertTriggered virusTable oldVirus void $ OT.updateTriggered virusTable oldVirus newVirus void $ OT.deleteTriggered virusTable newVirus throwM AbortTransaction) `catch` (\AbortTransaction -> pure ()) assertTriggersCommitted "Expected No Triggers to be fired update transaction rollback" [] , testCase "With Triggers around Aborted Transaction" $ do let oldVirus = bpsVirus newVirus = bpsVirus {virusName = VirusName (Text.pack "New Name")} run $ do TestDB.reset schema runTriggerTest $ do void $ OT.insertTriggered virusTable oldVirus O.withTransaction (do void $ OT.updateTriggered virusTable oldVirus newVirus throwM AbortTransaction) `catch` (\AbortTransaction -> pure ()) void $ OT.deleteTriggered virusTable newVirus assertTriggersCommitted "Expected triggers from inside transaction to have been rolled back" [Inserted oldVirus, Deleted newVirus] ] data TestTrigger = Inserted Virus | Updated Virus Virus | Deleted Virus deriving (Eq, Show) instance OT.InsertTrigger TestTrigger Virus where insertTriggers virus = [Inserted virus] instance OT.UpdateTrigger TestTrigger Virus Virus where updateTriggers old new = [Updated old new] instance OT.DeleteTrigger TestTrigger Virus where deleteTriggers virus = [Deleted virus] newtype TriggerTestMonad a = TriggerTestMonad { unTriggerTest :: OT.OrvilleTriggerT TestTrigger Postgres.Connection IO a } deriving ( Functor , Applicative , Monad , MonadIO , MonadThrow , MonadCatch , O.HasOrvilleContext Postgres.Connection , O.MonadOrville Postgres.Connection , OT.MonadTrigger TestTrigger #if MIN_VERSION_base(4,11,0) , MonadFail #endif ) -- -- Note that this tosses out the orville env that is in the TestDB.TestMonad instance -- and just steals its conncetion pool to use with runOrvilleTriggerT. This is ok for the -- tests here, but in the real world would result in the TriggerTestMonad using a different -- database connection that the surrounding TestMonad.TestMonad was using. -- runTriggerTest :: TriggerTestMonad () -> TestDB.TestMonad () runTriggerTest (TriggerTestMonad trigger) = do orvilleEnv <- O.getOrvilleEnv void $ liftIO $ OT.runOrvilleTriggerT trigger (O.ormEnvPool orvilleEnv) assertTriggersCommitted :: String -> [TestTrigger] -> TriggerTestMonad () assertTriggersCommitted description expected = do actual <- OT.committedTriggers <$> TriggerTestMonad OT.askTriggers liftIO $ assertEqual description expected actual instance O.MonadOrvilleControl TriggerTestMonad where liftWithConnection = O.defaultLiftWithConnection TriggerTestMonad unTriggerTest liftFinally = O.defaultLiftFinally TriggerTestMonad unTriggerTest data AbortTransaction = AbortTransaction deriving (Eq, Show, Typeable) instance Exception AbortTransaction
flipstone/orville
orville-postgresql/test/TriggerTest.hs
mit
6,332
0
25
1,846
1,270
650
620
-1
-1
module Chat where import Chat.Packet import Chat.Room import Chat.Session import Chat.Types import Network.Wai import Network.HTTP.Types import Network.WebSockets as WS import Network.Wai.Handler.WebSockets import Servant import System.IO.Unsafe import Util type ChatAPI = "chat" :> Capture "alias" String :> Capture "lat" Double :> Capture "lon" Double :> Raw chatApi :: Proxy ChatAPI chatApi = Proxy chatServer :: Server ChatAPI chatServer alias lat lon = websocketsOr ops (chatroomApp alias lat lon) defaultApp where ops = defaultConnectionOptions defaultApp _ resp = resp (responseLBS imATeaPot418 [] "") -- This is pretty unsafe/unsound (Who runs this? When is it run!?) but unless -- we want initialization to bubble up to main, this is how it's gonna be. {-# NOINLINE rootChatroom #-} rootChatroom :: ChatRoom rootChatroom = unsafePerformIO (newChatRoom "root") -- Accepts a pending connection and starts a new session. chatroomApp :: String -> Double -> Double -> WS.PendingConnection -> IO () chatroomApp alias lat lon pcon = do let alias' = sanitizeString alias con <- acceptRequest pcon sess <- newSession (ChatUser alias' lat lon) con rootChatroom waitSession sess
thchittenden/GeoChat
src/Chat.hs
mit
1,214
0
10
208
297
156
141
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-| Module : HSat.Problem.Instances.CNF.Parser.Internal Description : Exports the Internal tests for the CNF Parser Copyright : (c) Andrew Burnett 2014-2015 Maintainer : [email protected] Stability : experimental Portability : Unknown Module containing the Internal 'Parser' tests for the 'CNF' data type -} module Test.Problem.Instances.CNF.Parser.Internal ( tests, -- TestTree ) where import Control.Applicative import Control.Monad (replicateM,foldM) import Control.Monad.Catch import Data.Attoparsec.Text as P hiding (parseTest,take) import Data.Either import Data.Monoid import Data.Text (Text,pack,take) import qualified Data.Text as T hiding (map,replicate,take,foldl) import qualified Data.Vector as V import HSat.Parser hiding (Parser) import HSat.Problem.Instances.CNF.Builder import HSat.Problem.Instances.CNF.Builder.Internal import HSat.Problem.Instances.CNF.Parser.Internal import HSat.Problem.Instances.Common import Prelude hiding (take) import Test.Problem.Instances.CNF.Builder.Internal hiding (tests) import Test.Problem.Instances.CNF.Internal () import Test.Problem.Instances.Common.Clauses hiding (tests) import TestUtils name :: String name = "Internal" tests :: TestTree tests = testGroup name [ testGroup "parseComment" [ parseCommentTest1, parseCommentTest2, parseCommentTest3, parseCommentTest4 ], testGroup "parseComments" [ parseCommentsTest1, parseCommentsTest2 ], testGroup "parseProblemLine" [ parseProblemLineTest1, parseProblemLineTest2, parseProblemLineTest3 ], testGroup "parseNonZeroInteger" [ parseNonZeroIntegerTest1, parseNonZeroIntegerTest2, parseNonZeroIntegerTest3, parseNonZeroIntegerTest4 ], testGroup "parseClause" [ parseClauseTest1, parseClauseTest2, parseClauseTest3, parseClauseTest4, parseClauseTest5 ], testGroup "parseClauses" [ parseClausesTest1, parseClausesTest2, parseClausesTest3 ] ] --General function used to parse all the input given parseTest :: Parser a -> Text -> Either String a parseTest p = parseOnly (p <* endOfInput) parseTest' :: (MonadThrow m) => Parser (m a) -> Text -> m a parseTest' p t = case parseTest p t of Left str -> throwM $ ParseException str Right r -> r {- =================== parseComment Tests =================== -} --General framework for correct Test Cases parseCommentGen :: String -> Text -> Bool -> TestTree parseCommentGen title str True = testCase title $ parseTest parseComment str @=? Right () parseCommentGen title str False = testCase title $ assertBool "Expected failuure. Gotten success" (isLeft $ parseTest parseComment str) parseCommentTest1 :: TestTree parseCommentTest1 = parseCommentGen "parse simple comment" "c hello world" True parseCommentTest2 :: TestTree parseCommentTest2 = parseCommentGen "Parse comment with additional spaces" " c hello world" True parseCommentTest3 :: TestTree parseCommentTest3 = parseCommentGen "Parse Comment that fails" "c hello world\nf" False -- Generate a random comment genComment :: Int -> Gen Text genComment _ = ("c " <>) . T.filter f <$> arbitrary where f :: Char -> Bool f t = t /= '\n' && t/='\r' parseCommentTest4 :: TestTree parseCommentTest4 = testProperty "Parse random comments" $ forAll (sized genComment) (\text -> parseTest parseComment text === Right () ) {- =================== parseComments tests =================== -} parseCommentsTest1 :: TestTree parseCommentsTest1 = testCase "parse valid comments" $ parseTest parseComments testStr @=? Right () where testStr = "c hello world\nc goodbye world\n" parseCommentsTest2 :: TestTree parseCommentsTest2 = testProperty "parseComments randomly generated" $ forAll (sized $ \size -> T.unlines <$> (flip replicateM (genComment size) =<< choose (0,size)) ) (\text -> parseTest parseComments text === Right () ) {- ====================== parseProblemLine tests ====================== -} genProblemLineTest :: String -> Text -> TestTree genProblemLineTest title testStr = testCase title $ case parseTest' parseProblemLine testStr of Right cnf -> cnf @=? cnf' _ -> assertBool "Failure; exception thrown" False where cnf' = CNFBuilder 24 2424 0 emptyClauses emptyClause parseProblemLineTest1 :: TestTree parseProblemLineTest1 = genProblemLineTest "Parse normal problem line" "p cnf 24 2424" parseProblemLineTest2 :: TestTree parseProblemLineTest2 = genProblemLineTest "Parse problem line with spaces" " p cnf 24 \t2424" genSpace' :: Int -> Int -> Gen Text genSpace' offSet size = pack <$> (flip replicateM (oneof . map return $ " \t") =<< (offSet +) <$> choose (0,size)) genSpace :: Int -> Gen Text genSpace = genSpace' 0 parseProblemLineTest3 :: TestTree parseProblemLineTest3 = testProperty "parseProblemLine parses correctly" $ forAll (sized $ \size -> do vars <- arbitrary clauses <- arbitrary let genSpace0 = genSpace' 1 size vars' = return $ pack . show $ vars clauses' = return $ pack . show $ clauses p = return "p" cnf = return "cnf" text <- mconcat <$> sequence [ p,genSpace0,cnf,genSpace0,vars',genSpace0,clauses',genSpace size] return (text,vars,clauses) ) (\(text,v,c) -> let cnf' = CNFBuilder v c 0 emptyClauses emptyClause in case parseTest' parseProblemLine text of Right expected -> counterexample "Not same" $ expected === cnf' _ -> counterexample "Unexpected exception" False ) {- ========================= parseNonZeroInteger tests ========================= -} genParseNonZeroInteger :: String -> Integer -> Bool -> TestTree genParseNonZeroInteger title word True = testCase title $ case parseTest parseNonZeroInteger (pack $ show word) of Right word' -> word' @=? word _ -> assertBool "Unexpected exception" False genParseNonZeroInteger title word False = testCase title $ assertBool "Expected exception" (isLeft $ parseTest parseNonZeroInteger (pack $ show word)) parseNonZeroIntegerTest1 :: TestTree parseNonZeroIntegerTest1 = genParseNonZeroInteger "Parses correct non zero integer" 121 True parseNonZeroIntegerTest2 :: TestTree parseNonZeroIntegerTest2 = genParseNonZeroInteger "Parses correct non zero integer" 2453565 True parseNonZeroIntegerTest3 :: TestTree parseNonZeroIntegerTest3 = genParseNonZeroInteger "Doesn't parse zero" 0 False parseNonZeroIntegerTest4 :: TestTree parseNonZeroIntegerTest4 = testProperty "parseNonZeroInteger successful" $ forAll mkIntegerNonZero (\word -> parseTest parseNonZeroInteger (pack $ show word) === return word ) {- ================= parseClause tests ================= -} genParseClauseTest :: String -> Text -> TestTree genParseClauseTest title testStr = testCase title $ case (parseTest' (parseClause $ return cnf) testStr, finishClause cnf') of (Just gotten, Just exptd) -> gotten @=? exptd _ -> assertBool "Unexpected failure" False where cnf = CNFBuilder 10 10 0 emptyClauses emptyClause cnf' = V.foldl (flip addLiteral') cnf . V.map literalToInteger $ getVectLiteral cl cl = mkClauseFromLits $ map mkLiteralFromInteger [ 1,2,3,-4,-5,6,-7,8,9] parseClauseTest1 :: TestTree parseClauseTest1 = genParseClauseTest "parse good clause" "1 2 3 -4 -5 6 -7 8 9 0" parseClauseTest2 :: TestTree parseClauseTest2 = genParseClauseTest "Parse clause with spaces" "1 2 3 -4 -5 6 -7 8 9 0" parseClauseTest3 :: TestTree parseClauseTest3 = genParseClauseTest "Parse Clause with new lines" "1 2 3 -4 -5 \n 6 -7 8 \n 9 0" parseClauseTest4 :: TestTree parseClauseTest4 = genParseClauseTest "Parse clause with comments in between lines" $ "1 2 \n" <> "c initial\n" <> "3 -4 -5 \n" <> "c hello world\n" <> "6 -7 8 \n" <> "9 0" parseClauseTest5 :: TestTree parseClauseTest5 = testProperty "parse randomly generated clauses" $ forAll (sized $ \size -> do beforeBuilder <- return <$> genCNFBuilderEmptyClause size :: Gen (Maybe CNFBuilder) clause <- arbitrary let lits = clauseToIntegers clause afterBuilder = foldl (\b l -> b >>= addLiteral l) beforeBuilder lits >>= finishClause text <- generateClause size lits return (beforeBuilder,afterBuilder,text) ) (\(before,after,text) -> let gotten = parseTest (parseClause before) text in gotten === return after ) generateClause :: Int -> [Integer] -> Gen Text generateClause size ints = foldM generateClause' T.empty $ ints ++ [0] where generateClause' :: Text -> Integer -> Gen Text generateClause' text int = (text <>) <$> ( oneof . map (\f -> f >>= showNumb int) $ [ empty', empty' >>= ret, empty' >>= addSpace, empty' >>= ret >>= addSpace, empty' >>= addSpace >>= ret, empty' >>= addSpace >>= ret >>= addComs >>= addSpace, empty' >>= addSpace >>= ret >>= addComs, empty' >>= ret >>= addComs >>= addSpace, empty' >>= ret >>= addComs ] ) empty' :: Gen Text empty' = return mempty ret,addSpace,addComs :: Text -> Gen Text ret t = return $ t <> pack "\n" addSpace t = (t <>) <$> genSpace' 1 size addComs t = (t <>) . T.unlines <$> (choose (0,size) >>= flip replicateM (genComment size)) showNumb :: Integer -> Text -> Gen Text showNumb i t = do s <- genSpace' 1 size return $ s <> t <> (pack . show $ i) <> (if i==0 then const "" else take 1) s {- ================== parseClauses tests ================== -} genParseClauses :: String -> Text -> TestTree genParseClauses title testStr = testCase title $ case (parseTest' (parseClauses $ return cnf) testStr,cnf') of (Just gotten, Just expected) -> expected @=? gotten _ -> assertBool "Unexpected error" False where cnf = CNFBuilder 10 10 0 emptyClauses emptyClause cnf' = return $ CNFBuilder 10 10 4 clauses emptyClause clauses = mkClausesFromIntegers [ [1,2,3,-4,-5,-6], [-7,-8,9,10], [-1,-2,-3,-4,-7], [1,1,1,1,1,1] ] parseClausesTest1 :: TestTree parseClausesTest1 = genParseClauses "parse generic clauses" $ "1 2 3 -4 -5 -6 0 " <> "-7 -8 9 10 0 " <> "-1 -2 -3 -4 -7 0 " <> "1 1 1 1 1 1 0" parseClausesTest2 :: TestTree parseClausesTest2 = genParseClauses "parse clauses with comments" $ "c the evil is hardest to find\n" <> "1 2 3 -4 -5 -6 0\n" <> "c when we can find the last one\n" <> "-7 -8 9 10 0\n" <> "c finding the last one is the easiest\n" <> "-1 -2 -3 -4 -7\nc intermitant\n " <> "0 1 1 1 1 1 1 0" parseClausesTest3 :: TestTree parseClausesTest3 = testProperty "parse randomly generated Clauses" $ forAll (sized $ \size -> do clauses <- genClauses maxBound size let setSize = getSizeClauses clauses maxVar = findMaxVar clauses before = return $ CNFBuilder maxVar setSize 0 emptyClauses emptyClause after = return $ CNFBuilder maxVar setSize setSize clauses emptyClause f = round . log :: Double -> Int size' = f $ fromIntegral size text <- genClausesText size' clauses return (before, after, text) ) (\(before,after,text) -> let gotten = parseTest' (parseClauses before) text in case (gotten,after) of (Just gotten',Just after') -> counterexample "Clauses not same: " $ gotten' === after' _ -> counterexample "Unexpected exception" False ) where genClausesText :: Int -> Clauses -> Gen Text genClausesText size clauses = do header <- genComments size middle <- genClausesText' (clausesToIntegers clauses) footer <- genComments size return $ header <> middle <> footer where genClausesText' :: [[Integer]] -> Gen Text genClausesText' [] = return mempty genClausesText' (x:xs) = do header <- genComments size middle <- generateClause size x footer <- genComments size rest <- genClausesText' xs return $ header <> middle <> footer <> rest genComments :: Int -> Gen Text genComments size = do m <- choose (0,size) T.unlines <$> replicateM m (genComment size)
aburnett88/HSat
tests-src/Test/Problem/Instances/CNF/Parser/Internal.hs
mit
13,217
0
20
3,562
3,210
1,686
1,524
298
3
{-# LANGUAGE CPP #-} -- !!! Testing Typeable instances module Main(main) where import Data.Dynamic import Data.Typeable (TyCon, TypeRep, typeOf) import Data.Array import Data.Array.MArray import Data.Array.ST import Data.Array.IO import Data.Array.Unboxed import Data.Complex import Data.Int import Data.Word import Data.IORef import System.IO import Control.Monad.ST import System.Mem.StableName import System.Mem.Weak import Foreign.StablePtr import Control.Exception import Foreign.C.Types main :: IO () main = do print (typeOf (undefined :: [()])) print (typeOf (undefined :: ())) print (typeOf (undefined :: ((),()))) print (typeOf (undefined :: ((),(),()))) print (typeOf (undefined :: ((),(),(),()))) print (typeOf (undefined :: ((),(),(),(),()))) print (typeOf (undefined :: (() -> ()))) print (typeOf (undefined :: (Array () ()))) print (typeOf (undefined :: Bool)) print (typeOf (undefined :: Char)) print (typeOf (undefined :: (Complex ()))) print (typeOf (undefined :: Double)) print (typeOf (undefined :: (Either () ()))) print (typeOf (undefined :: Float)) print (typeOf (undefined :: Handle)) print (typeOf (undefined :: Int)) print (typeOf (undefined :: Integer)) print (typeOf (undefined :: IO ())) print (typeOf (undefined :: (Maybe ()))) print (typeOf (undefined :: Ordering)) print (typeOf (undefined :: Dynamic)) print (typeOf (undefined :: (IORef ()))) print (typeOf (undefined :: Int8)) print (typeOf (undefined :: Int16)) print (typeOf (undefined :: Int32)) print (typeOf (undefined :: Int64)) print (typeOf (undefined :: (ST () ()))) print (typeOf (undefined :: (StableName ()))) print (typeOf (undefined :: (StablePtr ()))) print (typeOf (undefined :: TyCon)) print (typeOf (undefined :: TypeRep)) print (typeOf (undefined :: Word8)) print (typeOf (undefined :: Word16)) print (typeOf (undefined :: Word32)) print (typeOf (undefined :: Word64)) print (typeOf (undefined :: ArithException)) print (typeOf (undefined :: AsyncException)) print (typeOf (undefined :: (IOArray () ()))) print (typeOf (undefined :: (IOUArray () ()))) print (typeOf (undefined :: (STArray () () ()))) print (typeOf (undefined :: (STUArray () () ()))) print (typeOf (undefined :: (StableName ()))) print (typeOf (undefined :: (StablePtr ()))) print (typeOf (undefined :: (UArray () ()))) print (typeOf (undefined :: (Weak ()))) print (typeOf (undefined :: CChar)) print (typeOf (undefined :: CSChar)) print (typeOf (undefined :: CUChar)) print (typeOf (undefined :: CShort)) print (typeOf (undefined :: CUShort)) print (typeOf (undefined :: CInt)) print (typeOf (undefined :: CUInt)) print (typeOf (undefined :: CLong)) print (typeOf (undefined :: CULong)) print (typeOf (undefined :: CLLong)) print (typeOf (undefined :: CULLong)) print (typeOf (undefined :: CFloat)) print (typeOf (undefined :: CDouble)) print (typeOf (undefined :: CPtrdiff)) print (typeOf (undefined :: CSize)) print (typeOf (undefined :: CWchar)) print (typeOf (undefined :: CSigAtomic)) print (typeOf (undefined :: CClock)) print (typeOf (undefined :: CTime))
ghcjs/ghcjs
test/pkg/base/dynamic002.hs
mit
3,233
0
13
606
1,548
799
749
86
1
module Ternary.TestKernel ( qcChain, testChainForSpaceLeak) where import Ternary.Core.Kernel (Kernel, chain) type S = Int fancyKernel :: Int -> Kernel Int Int S fancyKernel n a b = (a*b+n, a+b) qcChain :: Int -> Int -> Int -> S -> S -> Bool qcChain n0 n1 a0 s0 s1 = let (a1,t0) = fancyKernel n0 a0 s0 (a2,t1) = fancyKernel n1 a1 s1 in chain fancyKernel [n0,n1] a0 [s0,s1] == (a2, [t0,t1]) testChainForSpaceLeak n = fst $ chain fancyKernel [1..n] 0 [1..n]
jeroennoels/exact-real
test/Ternary/TestKernel.hs
mit
473
0
9
99
233
127
106
12
1
{-# LANGUAGE OverloadedStrings #-} module System.Authinfo (readAuthinfo, getPassword) where import System.Environment import Data.Attoparsec.Text hiding (take) import Data.List import Control.Applicative import qualified Data.Text as T import qualified Data.Text.IO as T import Control.Monad import Network import Data.Maybe import Data.Char type Line = (T.Text, T.Text, T.Text, Maybe PortNumber) dropBack :: Int -> [a] -> [a] dropBack n l = take (length l - n) l quoted = char '"' *> takeWhile1 (not . (=='"')) <* char '"' lstring s = lexeme $ string s lexeme p = skipSpace *> p <* skipSpace word = takeWhile1 $ not . isSpace attempt p = fmap Just p <|> return Nothing -- a possibly-quoted field field = do p <- peekChar' if p == '"' then quoted else word -- parse line line :: Parser Line line = fmap (\(Just h, Just l, Just p, r) -> (h,l,p,r)) (line' (Nothing,Nothing,Nothing,Nothing)) where line' s@(h,l,p,r) = msum [ char '\n' >> return s , lstring "machine" >> field >>= (\h -> line' (Just h,l,p,r)) , lstring "login" >> field >>= (\l -> line' (h,Just l,p,r)) , lstring "password" >> field >>= (\p -> line' (h,l,Just p,r)) , lstring "port" >> decimal >>= (\r -> line' (h,l,p,Just r)) ] <?> "line" file = many line -- |Parses whole authinfo file readAuthinfo :: IO [Line] readAuthinfo = do home <- getEnv "HOME" Right res <- fmap (parseOnly file) $ T.readFile $ home ++ "/.authinfo" return res -- |Gets the given user info out of AuthInfo getPassword :: T.Text -> T.Text -> IO (Maybe (T.Text, Maybe PortNumber)) getPassword host user = fmap (fmap (\(_,_,pass,port) -> (pass,port)) . find (\(h,u,_,_) -> h == host && u == user)) readAuthinfo
robgssp/authinfo-hs
System/Authinfo.hs
mit
1,818
0
15
449
754
414
340
45
2
module Language.BioPepa.OdesTranslate ( biopepaToOdes ) where {- Standard Library Modules Imported -} {- External Library Modules Imported -} import qualified Horddes.Solve import qualified Horddes.Odes as Odes import Horddes.Odes ( ChangeFunction ( .. ) ) {- Local Modules Imported -} import Language.Pepa.QualifiedName as Qualified import Language.BioPepa.Syntax ( Model ( .. ) , ModelOptions ( .. ) , ComponentDef , Component ( .. ) , ComponentName , PrefixOp ( .. ) , RateIdent , RateExpr ( .. ) ) import qualified Language.Pepa.MainControl as MainControl import Language.Pepa.MainControl ( MainControl ) {- End of Module Imports -} biopepaToOdes :: ModelOptions -> Model -> MainControl (Odes.Odes, Horddes.Solve.Environment) biopepaToOdes modelOptions model = MainControl.valueResult (odes, initEnv) logKey logInfo where logKey = "translated-ode-system" logInfo = Odes.hprintOdes odes odes = map translateComponentDef componentDefs componentDefs = modelCompDefs model rateSpecs = modelRateDefs model initEnv = Horddes.Solve.makeInitialEnvironment $ map makeConcPair modelSpecies makeConcPair :: ComponentName -> (String, Double) makeConcPair n = (Qualified.textual n, getConcentration n) modelSpecies = map fst componentDefs getConcentration :: ComponentName -> Double getConcentration name = maybe 0 fromIntegral $ lookup name initialConcMapping initialConcMapping = modelOptsInitConcs modelOptions translateComponentDef :: ComponentDef -> Odes.Ode translateComponentDef (name, component) = (Qualified.textual name, translateComponent component) translateComponent :: Component -> ChangeFunction translateComponent (Named name) = NameAtT $ Qualified.textual name translateComponent (Choice left right) = Plus (translateComponent left) (translateComponent right) translateComponent (PrefixComp rateIdent _ Reactant _) = -- We assume the component involved is the one being defined. Minus (Number 0) $ translateRateId rateIdent translateComponent (PrefixComp rateIdent _ Product _) = -- We assume the component involved is the one being defined. translateRateId rateIdent translateComponent (PrefixComp _ _ _ _) = error "Apologies, that kind of prefix component not yet supported" translateComponent (Cooperation _ _ _) = error "Sorry, parallel definitions not yet supported" translateComponent (CompConcent _ _ ) = error "Sorry, parallel definitions not yet supported" rateParamMapping = modelOptsRateParams modelOptions translateRateId :: RateIdent -> ChangeFunction translateRateId rateId | Just re <- lookup rateId rateSpecs = translateRate re | otherwise = error "Unbound rate name" translateRate :: RateExpr -> ChangeFunction translateRate (RateName name) | elem name modelSpecies = NameAtT $ Qualified.textual name | otherwise = maybe (Number 0.01) Number $ lookup name rateParamMapping translateRate (RateConstant d) = Number d translateRate (RateAdd left right) = Plus (translateRate left) (translateRate right) translateRate (RateSub left right) = Minus (translateRate left) (translateRate right) translateRate (RateMult left right) = Mult (translateRate left) (translateRate right) translateRate (RateDiv left right) = Divide (translateRate left) (translateRate right) -- Utility function -- pair :: (a -> b) -> a -> (a,b) -- pair f a = (a, f a)
allanderek/ipclib
Language/BioPepa/OdesTranslate.hs
gpl-2.0
3,690
0
11
851
832
437
395
73
12
module Portfolio where import Data.List import GHC.Exts import Text.Printf import Comm import Etran import Types import Utils data Flow = Flow { flName :: String , flFolio :: String , flBefore :: Pennies , flFlow :: Pennies , flProfit :: Pennies , flTo :: Pennies , vflRet :: Percent } deriving Show etran2flow e = Flow { flName = etSym e , flFolio = etFolio e , flBefore = b , flFlow = etFlow e , flProfit = p , flTo = etVcd e , vflRet = r } where b = etVbd e p = etPdp e r = (unPennies p) / (unPennies b) * 100.00 pfRet profitDuring valueBefore = (unPennies profitDuring) / (unPennies valueBefore) * 100.00 -- | Given several flows, reduce them to 1 reduceFlows name fs = Flow { flName = name , flFolio = name , flBefore = b , flFlow = colSum flFlow , flProfit = p , flTo = colSum flTo , vflRet = ret } where colSum func = countPennies $ map func fs p = colSum flProfit b = colSum flBefore ret = pfRet p b filterFlows folioName fs = filter (\fl -> folioName == flFolio fl) fs -- | filter flows by names ffbns folioNames fs = filter (\fl -> elem (flFolio fl) folioNames) fs -- | filter and reduce flows farf folioName fs = reduceFlows folioName $ filterFlows folioName fs baseFlows etrans = newFlows where fs = map etran2flow etrans nubs = nub $ map flFolio fs folioFlow folioName = farf folioName fs newFlows = map folioFlow nubs createPort newName folioNames fs = (subFlows, agg) where subFlows = ffbns folioNames fs agg = reduceFlows newName subFlows createPorts :: [Port] -> [Flow] -> [([Flow], Flow)] -> [([Flow], Flow)] createPorts [] fs acc = acc createPorts (p:ps) fs acc = createPorts ps fs' acc' where Port tgt srcs = p (subFlows, agg) = createPort tgt srcs fs fs' = agg:fs acc' = acc ++ [(subFlows, agg)] showFlow :: Flow -> String showFlow f = concat [n, b, fl, p, t, ret] where n = fmtName $ flFolio f fmt1 func = show $ func f b = fmt1 flBefore fl = fmt1 flFlow p = fmt1 flProfit t = fmt1 flTo ret = fmtRet $ vflRet f showPort :: String -> ([Flow], Flow) -> String showPort acc ([], fEnd) = unlines [acc, pfSpacer1, showFlow fEnd, pfSpacer2, ""] showPort acc (f:fs, fEnd) = showPort acc' (fs, fEnd) where acc' = acc ++ (showFlow f) ++ "\n" fmtName :: String -> String fmtName name = printf "%5s" name fmtRet :: Double -> String fmtRet v = printf "%7.2f" v createIndexLine comms sym = text where --c = findComm comms comm fmtVal v = (printf "%12.2f" v)::String startPrice = commStartPriceOrDie comms sym endPrice = commEndPriceOrDie comms sym profit = endPrice - startPrice retStr = fmtRet (profit/startPrice * 100.0) text = (fmtName sym) ++ (concatMap fmtVal [startPrice, 0.0, profit, endPrice]) ++ retStr createIndices comms = [createIndexLine comms (cmYepic c) | c <- comms, cmType c == "INDX"] pfHdr = "FOLIO VBEFORE VFLOW VPROFIT VTO VRET" pfSpacer1 = "----- ----------- ----------- ----------- ----------- ------" pfSpacer2 = "===== =========== =========== =========== =========== ======" -- | filter etrans on portfolio name, with sorting --feopn :: feopn name cmp etrans = sortWith (\e -> (etSym e, etDstamp e)) $ filter (\e -> name `cmp` etFolio e) etrans myFolio = feopn "ut" (/=) -- FIXME not sure it should be here createPortfolios :: Ledger -> [String] createPortfolios ledger = [pfHdr] ++ ports2 ++ indices where ps = ports ledger ports1 = createPorts ps (baseFlows $ etrans ledger) [] ports2 = map (showPort "") ports1 indices = createIndices $ comms ledger
blippy/sifi
src/Portfolio.hs
gpl-3.0
3,889
0
11
1,112
1,271
688
583
104
1
module Data.NonEmpty (NonEmpty, initNE, updNE, getNE) where -- | A non-empty container for stuff of type a is an item of type a along with a (possibly empty) list of the same type -- -- Is this already defined somewhere ? -- data NonEmpty a = NE -- !a -- ^ Current state -- [a] -- ^ Buffer of previous states -- !Int -- ^ Length of buffer -- deriving (Eq, Show) data NonEmpty a = NE !a [a] !Int deriving (Eq, Show) initNE :: a -> NonEmpty a initNE a = NE a [] 0 -- | Update a 'NonEmpty' record. -- -- updNE :: Int -- ^ Window length (NB : /must/ be positive) -> a -- ^ New state -> NonEmpty a -- ^ Current -> NonEmpty a -- ^ Updated updNE n s (NE sc scs lbuf) | lbuf < n = NE s (sc : scs) (lbuf + 1) | otherwise = NE s (sc : init scs) lbuf -- | Reconstruct the most recent list of states from a 'NonEmpty' record getNE :: Int -> NonEmpty a -> Maybe [a] getNE n (NE sc scs lbuf) | lbuf < n - 1 = Nothing | lbuf == n = Just (sc : scs) | otherwise = Just (sc : init scs) -- | Record-of-functions data NEFun a = NEFun { neFunUpdate :: a -> NonEmpty a -> NonEmpty a , neFunGet :: NonEmpty a -> Maybe [a]} mkNEfun :: Int -> NEFun a mkNEfun n = NEFun (updNE n) (getNE n) -- | Typeclass class NEClass ne where neUpd :: Int -> x -> ne x -> ne x neGet :: Int -> ne x -> Maybe [x] instance NEClass NonEmpty where neUpd = updNE neGet = getNE -- | Tests buf3 :: a -> NonEmpty a -> NonEmpty a buf3 = updNE 3
ocramz/sparse-linear-algebra
src/Data/NonEmpty.hs
gpl-3.0
1,496
0
11
412
486
252
234
34
1
-- Make it more efficient -- Get Grammers checked -- Expr type for the rest -- ask about the evaluator - both for formal as well as for the rest module Parser ( parser ) where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Pos import Syntax import Token -- Begin silly boilerplate type ExprParser a = GenParser Token () a mytoken :: (Token -> Maybe a) -> ExprParser a mytoken test = token showToken posToken testToken where showToken tok = show tok posToken tok = newPos "<stdin>" 0 0 testToken tok = test tok match :: Token -> ExprParser Token match t = mytoken checkEq where checkEq tok = if sametype t tok then Just tok else Nothing -- End silly boilerplate parens :: ExprParser a -> ExprParser a parens p = do match LParen x <- p match RParen return x parser :: [Token] -> Either ParseError Program parser toks = runParser program () "filename" toks -- A = M A' -- A' = + A | - A | epsilon -- M = F M' -- M' = * M | / M | epsilon -- F = num | ( A ) topLvlExpr :: ExprParser Expr topLvlExpr = addExpr <|> listExpr genExpr :: Expr -- LHS Expr -> Token -> ExprParser Expr -- RHS Parser -> (Expr -> Expr -> Expr) -> ExprParser Expr genExpr lhs tok rhs_p cons = do match tok rhs <- rhs_p return (cons lhs rhs) genBExpr :: BExpr -- LHS Expr -> Token -> ExprParser BExpr -- RHS Parser -> (BExpr -> BExpr -> BExpr) -> ExprParser BExpr genBExpr lhs tok rhs_p cons = do match tok rhs <- rhs_p return (cons lhs rhs) genRExpr :: Token -> ExprParser BExpr -- RHS Parser -> (Expr -> Expr -> BExpr) -> ExprParser BExpr genBExpr lhs tok rhs_p cons = do match tok rhs <- rhs_p return (cons lhs rhs) addExpr :: ExprParser Expr addExpr = do lhs <- mulExpr addExpr' lhs addExpr' :: Expr -> ExprParser Expr addExpr' lhs = genExpr lhs Add addExpr AddOp <|> genExpr lhs Sub addExpr SubOp <|> return lhs mulExpr :: ExprParser Expr mulExpr = do lhs <- factorExpr mulExpr' lhs mulExpr' :: Expr -> ExprParser Expr mulExpr' lhs = genExpr lhs Mul addExpr MulOp <|> genExpr lhs Div addExpr DivOp <|> return lhs factorExpr :: ExprParser Expr factorExpr = numFactor <|> parens addExpr <|> indexExpr where numFactor = do (Num x) <- match (Num 0) return (Number x) -- B = A O -- O = or rE | epsilon -- A = A' relE -- A' = or rE | epsilon -- relE = < E | > E | == E | <= E | >= E | != E bExpr :: ExprParser BExpr bExpr = do lhs <- andExpr orExpr lhs orExpr :: BExpr -> ExprParser BExpr orExpr lhs = genBExpr lhs Or bExpr OrOp <|> return lhs andExpr :: ExprParser BExpr andExpr = do lhs <- rExpr andExpr' lhs andExpr' :: BExpr -> ExprParser BExpr andExpr' lhs = genBExpr lhs And bExpr AndOp <|> return lhs rExpr :: BExpr -> ExprParser BExpr rExpr lhs = rExpr' <|> parens bExpr do genRExpr Less addExpr GreaterOp <|> genRExpr Greater addExpr GreaterOp <|> genRExpr Equal addExpr EqualOp <|> genRExpr lhs NEqual addExpr NEqualOp <|> return lhs --indexExpr = ident indexExpr' --indexExpr' = '[' expr ']' | ident | epsilon indexExpr = do (Varname str) <- match (Varname "") indexExpr' (Variable str) where indexExpr' lhs = hasIndex lhs <|> return lhs hasIndex lhs = do match LBracket index <- addExpr match RBracket indexExpr' (Index lhs index) -- O = A O' -- O' = Or O | epsilon -- A = E A' -- A' = And A | epsilon -- E = L E' -- E' = Eq E | NEq E | epsilon -- L = T L' | F -- L' = > L | < L | >= L | <= L | epsilon -- T = Expr | ( O ) -- F = True | False listExpr :: ExprParser Expr listExpr = do match LBracket ls <- sepBy topLvlExpr (match (Comma)) match RBracket return (List ls) onlyIfStmt :: ExprParser IfStmt onlyIfStmt = do match If cond <- addExpr match LCurly ifbl <- many stmt match RCurly return (IfOp cond ifbl) elseStmt :: ExprParser IfStmt elseStmt = do match Else match LCurly elseBl <- many stmt match RCurly return (ElseOp elseBl) elifStmt :: ExprParser IfStmt elifStmt = do match Elif cond <- addExpr match LCurly elifBl <- many stmt match RCurly return (ElifOp cond elifBl) stmt :: ExprParser Stmt stmt = whileStmt <|> assignment where whileStmt = do match While cond <- bExpr match LCurly bl <- many stmt match RCurly return (WhileOp cond bl) assignment = do lhs <- indexExpr match Assign rhs <- topLvlExpr return (AssignmentOp lhs rhs) stmtBlock :: ExprParser StmtBlock stmtBlock = do match Func Funcname fname <- match (Funcname "") match LParen ([Varname args]) <- sepBy (match (Varname "")) (match (Comma)) match RParen match LCurly pg <- many stmt match Return retval <- addExpr match RCurly return (FuncOp [args] pg retval) program :: ExprParser Program program = do retval <- many stmtBlock return (Program retval) --import qualified Data.Map as M
vyasa/satvc
Parser.hs
gpl-3.0
5,856
2
12
2,157
1,588
748
840
-1
-1
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, CPP #-} module Main where import Data.Typeable import Hip.HipSpec import Test.QuickCheck hiding (Prop) import Test.QuickSpec import Prelude hiding ((+),(*),even,odd,pred,sum,id) import qualified Prelude as P data Nat = Z | S Nat deriving (Show,Eq,Ord,Typeable) infixl 6 + infixl 7 * (+) :: Nat -> Nat -> Nat Z + m = m -- S n + m = S (n + m) S n + m = n + S m (*) :: Nat -> Nat -> Nat Z * m = Z S n * m = m + (n * m) -- sigma f Z = Z -- sigma f (S n) = sigma f n + f (S n) -- sum xs = sigma id xs --sum Z = Z --sum (S n) = sum n + S n -- cubes xs = sigma cube xs --cubes Z = Z --cubes (S n) = cubes n + (S n * S n * S n) -- sq x = x * x -- id x = x -- cube x = x * x * x -- two = S (S Z) -- one = S Z prop_comm :: Nat -> Nat -> Prop Nat prop_comm x y = x + y =:= y + x main = hipSpec "Nat2.hs" conf 3 where conf = describe "Nats" [ var "x" natType , var "y" natType , var "z" natType , con "Z" Z , con "S" S , con "+" (+) , con "*" (*) -- , con "id" (id :: Nat -> Nat) -- , con "sum" sum -- , con "cubes" cubes -- , con "sigma" sigma -- , con "sq" sq -- , con "two" two -- , con "one" one -- , con "cube" cube ] where natType = (error "Nat type" :: Nat) -- 4 * sum sq x = sum (sum id) (2 * x) -- sum x + sum x = x * (S x) instance Enum Nat where toEnum 0 = Z toEnum n = S (toEnum (P.pred n)) fromEnum Z = 0 fromEnum (S n) = succ (fromEnum n) instance Arbitrary Nat where arbitrary = sized $ \s -> do x <- choose (0,round (sqrt (toEnum s))) return (toEnum x) instance CoArbitrary Nat where coarbitrary Z = variant 0 coarbitrary (S x) = variant (-1) . coarbitrary x instance Classify Nat where type Value Nat = Nat evaluate = return {- Failed to prove (x*y)*S y = (x+x)*sum S y. Failed to prove sq (sum S x) = cube x+sum cube x. Failed to prove sq x = sum id x+sum S x. Failed to prove x+sq x = sum S x+sum S x. Failed to prove (x*y)*S x = (y+y)*sum S x. Failed to prove (x*y)*S x = sum S x*(y+y). Failed to prove (x*y)*S y = sum S y*(x+x). Failed to prove sum (x+) x = sq x+sum id x. Failed to prove sq x+cube x = (x+x)*sum S x. Failed to prove sum (x+) y = (x*y)+sum id y. Failed to prove sum (x+) y = sum id y+(x*y). Failed to prove sum (y+) x = (x*y)+sum id x. Failed to prove sum (y+) x = sum id x+(x*y). Failed to prove sum (x+) x = sum id x+sq x. Failed to prove sq (sum S x) = sum cube x+cube x. Failed to prove sq x+cube x = sum S x*(x+x). Failed to prove sum cube x = sq (sum id x). Failed to prove sq (sum S x) = sum cube (S x). Failed to prove sq x = sum S x+sum id x. Failed to prove sum cube x = sum id x*sum id x. Failed to prove cube (sum id x) = sum id x*sum cube x. Failed to prove cube (sum id x) = sum cube x*sum id x. Proved: x = x+Z, Z = x*Z, S (x+y) = x+S y, sum S x = sum id (S x), sum (sum S) x = sum (sum id) (S x), x+y = y+x, x+(y+z) = y+(x+z), x*(y+y) = (x+x)*y, (Z*) = sum (Z*), x = x*S Z, x+(x*y) = x*S y, x*y = y*x, y*(x+z) = (x*y)+(y*z), x*(x*y) = y*sq x, y*cube x = sq x*(x*y), x*sum S y = sum (x*) (S y), sum (x*) y = x*sum id y, sum (y*) x = sum id x*y, x*(y*z) = y*(x*z) Unproved: (none) 19/19 17: sum id Z == Z 18: sum id two == one 19: sum id one == Z 20: sum S Z == Z 21: sum S two == S two 22: sum S one == one 23: sum sq Z == Z 24: sum sq two == one 25: sum sq one == Z 26: sum cube Z == Z 27: sum cube two == one 28: sum cube one == Z 29: (x*y)+(x*z) == x*(y+z) 30: cube x*cube y == cube (x*y) 31: sum (x*) (S y) == x*sum S y 32: sum id (S x) == sum S x 33: sum cube (S x) == sq (sum S x) 34: sum (x+) Z == Z 35: sum (x+) two == S (x+x) 36: sum (x+) one == x 37: sum (x*) Z == Z 38: x*sum id y == sum (x*) y 39: sq (sum id x) == sum cube x 40: x+sum id x == sum S x 41: sum (two+) x == x+sum S x 42: sq (S two) == S (cube two) 43: (x*y)+sum id x == sum (y+) x 44: (x+x)*sum S y == (x*y)*S y 45: sum (Z*) (x+y) == Z 46: sum (Z*) (x*y) == Z 47: sq x+sum sq x == sum sq (S x) 48: cube x+sum cube x == sq (sum S x) 49: sum (Z*) (cube x) == Z 50: sum (sum id) (S x) == sum (sum S) x 51: sum S (sq two) == two+cube two 52: sum cube (sq two) == sum S (cube two) 53: sum (sum id) Z == Z 54: sum (sum id) two == Z 55: sum (sum id) one == Z 56: sum (sum S) two == one 57: sum (sum sq) Z == Z 58: sum (sum sq) two == Z 59: sum (sum sq) one == Z 60: sum (sum cube) Z == Z 61: sum (sum cube) two == Z 62: sum (sum cube) one == Z 63: sum id x+sum S x == sq x 64: (x+two)*sum S x == sum (x*) (x+two) 65: sum sq x*sq two == sum (sum id) (x+x) 66: sum (Z*) (sum id x) == Z 67: sum (Z*) (sum S x) == Z 68: sum (Z*) (sum sq x) == Z 69: sum (Z*) (sum cube x) == Z 70: sum (two*) (x+two) == S x*(x+two) 71: sum (two+) (sq two) == sum sq (sq two) 72: sum (sum id) (cube two) == sum (two*) (cube two) 73: sum (sum S) (sq two) == two+cube two 74: sum (sum sq) (S two) == one 75: sum (sum sq) (sq two) == two+sq two 76: sum (sum cube) (S two) == one 77: sum (sum cube) (sq two) == two+cube two Failed to prove sum (x+) (sq x) = two*sum cube x. Failed to prove sum (x*) (S x) = (x+two)*sum id x. Failed to prove sum (sum id) (x+x) = sum sq x*sq two. Failed to prove S (sum cube two) = sum (sum id) (S two). Failed to prove sum sq (sq two) = sum (sum S) (sq two). Failed to prove sum S (sum S two) = sum (sum id) (sq two). Failed to prove sum S (sum S two) = sum (sum sq) (S two). Failed to prove sq (sq two) = sum (sum S) (S two). Failed to prove sum (sum sq) (sq two) = sum (sum S) (sum S two). Failed to prove cube (x*y) = cube x*cube y. Failed to prove cube (x*y) = cube y*cube x. Failed to prove sum cube x = sq (sum id x). Failed to prove cube (x+x) = cube x*cube two. Failed to prove sum (x*) (x+two) = (x+two)*sum S x. Failed to prove sum (x+) (sq x) = sum cube x*two. Failed to prove cube (x+x) = cube two*cube x. Failed to prove sum (x+) (sq x) = sum cube x+sum cube x. Failed to prove sum (x*) (S x) = sum id x*(x+two). Failed to prove sum cube x = sum id x*sum id x. Failed to prove cube (sum id x) = sum id x*sum cube x. Failed to prove sum (x*) (x+two) = sum S x*(x+two). Failed to prove cube (sum id x) = sum cube x*sum id x. Failed to prove sum id x+sum cube x = sum (two*) (sum id x). Failed to prove sum (sum id) (x+x) = sq two*sum sq x. Failed to prove sq (sum S two) = sum (two+) (sum S two). Proved: x = x+Z, S x = x+one, Z = x*Z, x = x*one, x+two = two+x, x+(y+z) = (x+y)+z, x+(y+z) = y+(x+z), x+(y+z) = z+(x+y), x+(x+two) = S x*two, x+x = x*two, x+(x*y) = x*S y, x*y = y*x, x*(y+z) = (x*y)+(x*z), x*(y*z) = y*(x*z), x*(y*z) = z*(x*y), (Z*) = sum (Z*), sum (y*) x = sum id x*y, sum S x = sum id x+x, sum (y+) x = (x*y)+sum id x, x*(x+two) = sum S x+sum id x, x+sq x = sum id x+sum id x Unproved: (none) 21/21 -} (=:=) = undefined type Prop a = a
danr/hipspec
examples/old-examples/quickspec/Nat2.hs
gpl-3.0
7,003
2
17
1,968
591
328
263
46
1
module Amoeba.Middleware.Config.Facade (module X) where import Data.Either.Utils as X (forceEither) import Amoeba.Middleware.Config.Config as X (Configuration(..), getOption, loadConfiguration, intOption, strOption, extract) import Amoeba.Middleware.Config.Extra as X
graninas/The-Amoeba-World
src/Amoeba/Middleware/Config/Facade.hs
gpl-3.0
268
0
6
24
69
49
20
4
0
module Main ( main ) where import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import Data.IORef import Stars_Display import Star_Rec -- | Main method. -- Entry point of the program. main :: IO () main = do (progname,args) <- getArgsAndInitialize initialDisplayMode $= [getBufferMode args, RGBMode, WithDepthBuffer] createWindow "Stars" starFlag <- newIORef NormalStars starList <- newIORef [] initfn starFlag starList reshapeCallback $= Just reshape keyboardMouseCallback $= Just (keyboardMouse starFlag) displayCallback $= display starList visibilityCallback $= Just (visible starFlag starList) mainLoop where getBufferMode ["-sb"] = SingleBuffered getBufferMode _ = DoubleBuffered
rmcmaho/Haskell_OpenGL_Examples
Stars/Stars.hs
gpl-3.0
741
0
10
136
195
97
98
22
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} import Control.Concurrent (ThreadId, forkIO, killThread) import Control.Concurrent.Async (mapConcurrently) import Control.Exception (finally, onException) import Control.Monad (unless) import Control.Monad.Extra (unlessM) import Data.Char (isSpace) import Data.FileEmbed (embedStringFile, makeRelativeToProject) import Data.List (genericLength, genericTake) import Data.Maybe (fromMaybe, isJust) import Data.Monoid ((<>)) import qualified Data.Text as T (filter, lines, strip, unlines, unpack) import qualified Data.Text.Buildable as B (build) import qualified Data.Text.IO as TIO import Data.Traversable (for) import Formatting (build, float, int, sformat, shown, stext, (%)) import qualified Options.Generic as OG import System.Directory (doesFileExist) import System.IO.Temp (withSystemTempDirectory) import qualified Turtle as T import Serokell.Util.Text (listBuilderCSV, listBuilderJSON) import qualified RSCoin.Core as C import Bench.RSCoin.Remote.Config (BankData (..), MintetteData (..), ProfilingType (..), RemoteConfig (..), UserData (..), UsersData (..), readRemoteConfig) import Bench.RSCoin.UserCommons (initializeBank, userThread) import Bench.RSCoin.UserSingle (itemsAndTPS) data RemoteBenchOptions = RemoteBenchOptions { rboConfigFile :: Maybe FilePath , rboBenchSeverity :: Maybe C.Severity } deriving (Show, OG.Generic) instance OG.ParseField C.Severity instance OG.ParseFields C.Severity instance OG.ParseRecord C.Severity instance OG.ParseRecord RemoteBenchOptions rscoinConfigStr :: T.Text rscoinConfigStr = C.rscoinConfigStr data BankParams = BankParams { bpPeriodDelta :: !Word , bpProfiling :: !(Maybe ProfilingType) , bpSeverity :: !(Maybe C.Severity) , bpBranch :: !T.Text } deriving (Show) data UsersParamsSingle = UsersParamsSingle { upsUsersNumber :: !Word , upsMintettesNumber :: !Word , upsTransactionsNumber :: !Word , upsDumpStats :: !Bool , upsConfigStr :: !T.Text , upsSeverity :: !C.Severity , upsBranch :: !T.Text , upsHostName :: !T.Text , upsProfiling :: !(Maybe ProfilingType) } deriving (Show) userName :: T.IsString s => s userName = "ubuntu" defaultBranch :: T.IsString s => s defaultBranch = "master" statsDir :: T.IsString s => s statsDir = "\"$HOME\"/rscoin-stats" sshKeyPath :: T.IsString s => s sshKeyPath = "~/.ssh/rscointest.pem" installCommand :: T.IsString s => s installCommand = $(makeRelativeToProject "bench/install.sh" >>= embedStringFile) cdCommand :: T.Text cdCommand = "cd \"$HOME/rscoin\"" keyGenCommand :: T.Text keyGenCommand = "stack exec -- rscoin-keygen\n" catKeyCommand :: T.Text catKeyCommand = "cat \"$HOME\"/.rscoin/key.pub\n" catAddressCommand :: T.Text -> T.Text catAddressCommand bankHost = T.unlines [ cdCommand , sformat ("stack exec -- rscoin-user dump-address 1 --bank-host " % stext) bankHost] updateRepoCommand :: T.Text -> T.Text updateRepoCommand branchName = T.unlines [ cdCommand , "git checkout . -q" , "git fetch -q" , sformat ("git checkout -q -b " % stext % " " % stext % " 2> /dev/null || git checkout -q " % stext) branchName originBranchName branchName , sformat ("git pull -f -q origin " % stext) branchName] where originBranchName = sformat ("origin/" % stext) branchName updateTimezoneCommand :: T.Text updateTimezoneCommand = "sudo timedatectl set-timezone Europe/Moscow" setupConfigCommand :: T.Text setupConfigCommand = sformat ("echo '" % stext % "' > rscoin.yaml") rscoinConfigStr profilingBuildArgs :: Maybe ProfilingType -> T.Text profilingBuildArgs Nothing = "" profilingBuildArgs (Just _) = " --executable-profiling --library-profiling " profilingRunArgs :: Maybe ProfilingType -> T.Text profilingRunArgs Nothing = "" profilingRunArgs (Just PTStandard) = " +RTS -p -RTS " profilingRunArgs (Just PTDetailed) = " +RTS -P -RTS " profilingRunArgs (Just PTMostDetailed) = " +RTS -pa -RTS " bankSetupCommand :: BankParams -> [T.Text] -> [C.PublicKey] -> T.Text bankSetupCommand BankParams {..} mHosts mKeys = T.unlines [ cdCommand , bankStopCommand , "rm -rf bank-db" , updateRepoCommand bpBranch , setupConfigCommand , mconcat ["stack build rscoin", profilingBuildArgs bpProfiling] , T.unlines $ map (uncurry addMintetteCommand) $ zip mHosts mKeys] where addMintetteCommand = sformat ("stack exec -- rscoin-bank add-mintette --port " % int % " --host " % stext % " --key " % build) (C.defaultPort :: Int) bankRunCommand :: BankParams -> T.Text bankRunCommand BankParams{..} = T.unlines [ cdCommand , sformat ("stack exec -- rscoin-bank serve --log-severity " % shown % " +RTS -qg -RTS --period-delta " % int % stext % " | grep \"Finishing period took\"") (fromMaybe C.Warning bpSeverity) bpPeriodDelta (profilingRunArgs bpProfiling)] bankStopCommand :: T.Text bankStopCommand = "killall -s SIGINT rscoin-bank 2> /dev/null" mintetteSetupCommand :: T.Text -> Maybe ProfilingType -> T.Text mintetteSetupCommand branchName profiling = T.unlines [ cdCommand , mintetteStopCommand , "rm -rf mintette-db" , updateRepoCommand branchName , setupConfigCommand , sformat ("stack build rscoin " % stext) (profilingBuildArgs profiling) , keyGenCommand] mintetteRunCommand :: T.Text -> Maybe ProfilingType -> Maybe C.Severity-> T.Text mintetteRunCommand bankHost profiling severity = T.unlines [ cdCommand , sformat ("stack exec -- rscoin-mintette +RTS -qg -RTS --bank-host " % stext % " " % stext % " " % stext) bankHost (profilingRunArgs profiling) (maybe "" (sformat ("--log-severity " % shown)) severity)] mintetteStopCommand :: T.Text mintetteStopCommand = "killall -s SIGINT rscoin-mintette 2> /dev/null" mkStatsDirCommand :: T.Text mkStatsDirCommand = sformat ("mkdir -p " % stext) statsDir statsTmpFileName :: T.IsString s => s statsTmpFileName = "bench-tmp.txt" csvStatsTmpFileName :: T.IsString s => s csvStatsTmpFileName = "bench-tmp.csv" csvStatsFileName :: (Monoid s, T.IsString s) => s csvStatsFileName = mconcat [statsDir, "/", "stats.csv"] statsId :: (Monoid s, T.IsString s) => s statsId = "`date +\"%m.%d-%H:%M:%S\"`" usersCommandSingle :: UsersParamsSingle -> T.Text usersCommandSingle UsersParamsSingle{..} = T.unlines ([ cdCommand , updateRepoCommand upsBranch , updateTimezoneCommand , setupConfigCommand , mkStatsDirCommand , sformat ("touch " % stext) csvStatsFileName , sformat ("stack bench rscoin:rscoin-bench-only-users " % stext % " --benchmark-arguments \"--users " % int % " --mintettes " % int % " --transactions " % int % " --severity " % shown % " --output " % stext % " --csv " % stext % " --csvPrefix " % stext % stext % " +RTS -qg -RTS\"") (profilingBuildArgs upsProfiling) upsUsersNumber upsMintettesNumber upsTransactionsNumber upsSeverity statsTmpFileName csvStatsTmpFileName csvPrefix (profilingRunArgs upsProfiling)] ++ dealWithStats) where csvPrefix = sformat ("\\\"" % stext % ",`git show-ref --abbrev -s HEAD`,\\\"") statsId dealWithStats | upsDumpStats = [ sformat ("mv " % stext % " " % stext) statsTmpFileName (mconcat [statsDir, "/", statsId, ".stats"]) , sformat ("echo `cat " % stext % "` >> " % stext) csvStatsTmpFileName csvStatsFileName , sformat ("rm -f " % stext) csvStatsTmpFileName , sformat ("echo '" % stext % "' > " % stext) upsConfigStr (mconcat [statsDir, "/", statsId, ".yaml"])] | otherwise = [ sformat ("rm -f " % stext % " " % stext) statsTmpFileName csvStatsTmpFileName] userSetupCommand :: T.Text -> T.Text -> Maybe ProfilingType -> T.Text userSetupCommand bankHost branchName profiling = T.unlines [ cdCommand , "rm -rf wallet-db" , updateRepoCommand branchName , setupConfigCommand , sformat ("stack bench rscoin --no-run-benchmarks " % stext) (profilingBuildArgs profiling) , sformat ("stack exec -- rscoin-user list --addresses-num 1 --bank-host " % stext % " > /dev/null") bankHost] userUpdateCommand :: T.Text -> T.Text userUpdateCommand bankHost = T.unlines [ cdCommand , sformat ("stack exec -- rscoin-user update --bank-host " % stext % " > /dev/null") bankHost] userStatsFileName :: T.IsString s => s userStatsFileName = "user-stats.txt" userRunCommand :: Maybe Word -> T.Text -> Word -> UserData -> T.Text userRunCommand logInterval bankHost txNum UserData{..} = T.unlines [ cdCommand , sformat ("stack bench rscoin:rscoin-bench-single-user --benchmark-arguments \"" % stext % "\"") benchmarkArguments] where benchmarkArguments = sformat ("--walletDb wallet-db --bank " % stext % stext % " --transactions " % int % " --dumpStats " % stext % stext % stext % stext % " +RTS -qg -RTS") bankHost severityArg txNum userStatsFileName printDynamicArg logIntervalArg (profilingRunArgs udProfiling) severityArg = maybe "" (sformat (" --severity " % shown % " ")) udSeverity printDynamicArg = maybe "" (const $ " --printDynamic") udPrintTPS logIntervalArg = maybe "" (sformat (" --logInterval " % int % " ")) logInterval userStopCommand :: T.Text userStopCommand = "killall -s SIGINT rscoin-bench-single-user 2> /dev/null" resultTPSCommand :: T.Text resultTPSCommand = T.unlines [ cdCommand , "cat " <> userStatsFileName ] sshArgs :: T.Text -> [T.Text] sshArgs hostName = [ "-i" , sshKeyPath , "-o" , "StrictHostKeyChecking=no" , mconcat [userName, "@", hostName]] runSsh :: T.Text -> T.Text -> IO () runSsh hostName command = () <$ T.proc "ssh" (sshArgs hostName ++ [command]) mempty runSshStrict :: T.Text -> T.Text -> IO T.Text runSshStrict hostName command = do (T.ExitSuccess,res) <- T.procStrict "ssh" (sshArgs hostName ++ [command]) mempty return res installRSCoin :: T.Text -> IO () installRSCoin = flip runSsh installCommand installRSCoinChecked :: Maybe Bool -> T.Text -> IO () installRSCoinChecked hasRSCoin host = unless (fromMaybe True hasRSCoin) $ installRSCoin host installRSCoinBank :: BankData -> IO () installRSCoinBank BankData{..} = installRSCoinChecked bdHasRSCoin bdHost installRSCoinMintette :: MintetteData -> IO () installRSCoinMintette MintetteData{..} = installRSCoinChecked mdHasRSCoin mdHost installRSCoinUser :: UserData -> IO () installRSCoinUser UserData{..} = installRSCoinChecked udHasRSCoin udHost setupAndRunBank :: BankParams -> T.Text -> [T.Text] -> [C.PublicKey] -> IO ThreadId setupAndRunBank bp@BankParams{..} bankHost mintetteHosts mintetteKeys = do runSsh bankHost $ bankSetupCommand bp mintetteHosts mintetteKeys forkIO $ runSsh bankHost $ bankRunCommand bp stopBank :: T.Text -> IO () stopBank bankHost = runSsh bankHost bankStopCommand genMintetteKey :: T.Text -> MintetteData -> IO C.PublicKey genMintetteKey branchName (MintetteData _ hostName profiling _) = do runSsh hostName $ mintetteSetupCommand branchName profiling fromMaybe (error "FATAL: constructPulicKey failed") . C.constructPublicKey <$> runSshStrict hostName catKeyCommand runMintette :: T.Text -> MintetteData -> IO ThreadId runMintette bankHost (MintetteData _ hostName profiling sev) = forkIO $ runSsh hostName $ mintetteRunCommand bankHost profiling sev stopMintette :: T.Text -> IO () stopMintette host = runSsh host mintetteStopCommand runUsersSingle :: UsersParamsSingle -> IO () runUsersSingle ups@UsersParamsSingle{..} = runSsh upsHostName $ usersCommandSingle ups genUserKey :: T.Text -> T.Text -> UserData -> IO C.PublicKey genUserKey bankHost globalBranch UserData{..} = do runSsh udHost $ userSetupCommand bankHost (fromMaybe globalBranch udBranch) udProfiling fromMaybe (error "FATAL: constructPulicKey failed") . C.constructPublicKey . T.filter (not . isSpace) <$> runSshStrict udHost (catAddressCommand bankHost) sendInitialCoins :: Word -> [C.PublicKey] -> IO () sendInitialCoins txNum (map C.Address -> userAddresses) = do withSystemTempDirectory "tmp" impl where bankId = 0 impl dir = userThread dir (const $ initializeBank txNum userAddresses) bankId updateUser :: T.Text -> UserData -> IO () updateUser bankHost UserData {..} = runSsh udHost $ userUpdateCommand bankHost runUser :: Maybe Word -> T.Text -> Word -> UserData -> IO () runUser logInteval bankHost txNum ud@UserData{..} = runSsh udHost $ userRunCommand logInteval bankHost txNum ud stopUser :: T.Text -> IO () stopUser host = runSsh host userStopCommand writeUserTPSInfo :: SingleRunParams -> Word -> [UserData] -> Double -> IO () writeUserTPSInfo SingleRunParams{..} txNum userDatas totalTPS = do homeStats <- (T.</> "rscoin-stats") <$> T.home T.mktree homeStats (T.ExitSuccess, dateUglyStr) <- T.procStrict "date" ["+\"%m.%d-%H:%M:%S\""] mempty let dateStr = T.filter (/= '"') $ T.strip dateUglyStr let (Right stats) = T.toText homeStats let dateFileName = mconcat [stats, "/", dateStr, ".stats"] let mintettesNum = length srpMintettes let usersNum = length userDatas let dateStatsOutput = T.unlines [ sformat ("total TPS: " % float) totalTPS , sformat ("dynamic TPS: " % stext) "TODO" , sformat ("number of mintettes: " % int) mintettesNum , sformat ("number of users: " % int) usersNum , sformat ("number of transactions: " % int) txNum , sformat ("period length: " % int) srpPeriodLength ] TIO.writeFile (T.unpack dateFileName) dateStatsOutput let statsFile = T.unpack $ mconcat [stats, "/", "stats.csv"] unlessM (doesFileExist statsFile) $ do let statsHeader = "time,TPS,usersNum,mintettesNum,txNum,period\n" TIO.writeFile statsFile statsHeader let builtCsv = listBuilderCSV [ B.build dateStr , B.build totalTPS , B.build usersNum , B.build mintettesNum , B.build txNum , B.build srpPeriodLength ] TIO.appendFile statsFile $ sformat (build % "\n") builtCsv collectUserTPS :: SingleRunParams -> Word -> [UserData] -> IO T.Text collectUserTPS srp txNum userDatas = do resultFiles <- for userDatas $ \ud -> runSshStrict (udHost ud) resultTPSCommand let lastLines = map (last . T.lines) resultFiles let (_, _, totalTPS) = itemsAndTPS lastLines writeUserTPSInfo srp txNum userDatas totalTPS return $ sformat ("Total TPS: " % float) totalTPS data SingleRunParams = SingleRunParams { srpConfigStr :: T.Text , srpGlobalBranch :: Maybe T.Text , srpPeriodLength :: Word , srpUsers :: Maybe UsersData , srpMintettes :: [MintetteData] , srpBank :: BankData , srpUsersNum :: Word , srpTxNum :: Word } deriving (Show) remoteBench :: SingleRunParams -> IO () remoteBench srp@SingleRunParams{..} = do let globalBranch = fromMaybe defaultBranch srpGlobalBranch bp = BankParams { bpPeriodDelta = srpPeriodLength , bpProfiling = bdProfiling srpBank , bpSeverity = bdSeverity srpBank , bpBranch = fromMaybe globalBranch $ bdBranch srpBank } !bankHost = error "Bank host is not defined!" mintettes = srpMintettes userDatas Nothing = [] userDatas (Just (UDSingle{..})) = [udsData] userDatas (Just (UDMultiple{..})) = udmUsers noStats = any isJust (bpProfiling bp : (map udProfiling (userDatas srpUsers) ++ map mdProfiling mintettes)) C.logInfo $ sformat ("Setting up and launching mintettes " % build % "…") $ listBuilderJSON mintettes mintetteKeys <- mapConcurrently (genMintetteKey globalBranch) mintettes mintetteThreads <- mapConcurrently (runMintette bankHost) mintettes C.logInfo "Launched mintettes, waiting…" T.sleep 2 C.logInfo "Launching bank…" bankThread <- setupAndRunBank bp bankHost (map mdHost mintettes) mintetteKeys C.logInfo "Launched bank, waiting…" T.sleep 3 C.logInfo "Running users…" let runUsers :: Maybe UsersData -> IO () runUsers Nothing = do C.logInfo "Running users was disabled in config. I have finished, RSCoin is ready to be used." C.logInfo "Have fun now. I am going to sleep, you can wish me good night." T.sleep 100500 runUsers (Just UDSingle{..}) = runUsersSingle $ UsersParamsSingle { upsUsersNumber = srpUsersNum , upsMintettesNumber = genericLength mintettes , upsTransactionsNumber = srpTxNum , upsDumpStats = not noStats , upsConfigStr = srpConfigStr , upsSeverity = fromMaybe C.Warning $ udSeverity udsData , upsBranch = fromMaybe globalBranch $ udBranch udsData , upsHostName = udHost udsData , upsProfiling = udProfiling udsData } runUsers (Just (UDMultiple{..})) = do let datas = genericTake srpUsersNum udmUsers runUsersMultiple datas srpTxNum udmLogInterval runUsersMultiple datas txNum logInterval = flip finally (TIO.putStrLn =<< collectUserTPS srp txNum datas) $ do let stopUsers = () <$ mapConcurrently (stopUser . udHost) datas pks <- mapConcurrently (genUserKey bankHost globalBranch) datas sendInitialCoins txNum pks () <$ mapConcurrently (updateUser bankHost) datas () <$ mapConcurrently (runUser logInterval bankHost txNum) datas `onException` stopUsers finishMintettesAndBank = do C.logInfo "Ran users" stopBank bankHost C.logInfo "Stopped bank" mapM_ stopMintette $ map mdHost mintettes C.logInfo "Stopped mintettes" killThread bankThread C.logInfo "Killed bank thread" mapM_ killThread mintetteThreads C.logInfo "Killed mintette threads" runUsers srpUsers `finally` finishMintettesAndBank main :: IO () main = do RemoteBenchOptions{..} <- OG.getRecord "rscoin-bench-remote" C.initLogging C.Error flip C.initLoggerByName C.benchLoggerName $ fromMaybe C.Info $ rboBenchSeverity let configPath = fromMaybe "remote.yaml" $ rboConfigFile RemoteConfig{..} <- readRemoteConfig configPath configStr <- TIO.readFile configPath installRSCoinBank rcBank () <$ mapConcurrently installRSCoinMintette rcMintettes () <$ mapConcurrently installRSCoinUser (userDatas rcUsers) let paramsCtor periodDelta mintettesNum usersNum txNum = SingleRunParams { srpConfigStr = configStr , srpGlobalBranch = rcBranch , srpPeriodLength = periodDelta , srpUsers = rcUsers , srpBank = rcBank , srpMintettes = genericTake mintettesNum rcMintettes , srpUsersNum = usersNum , srpTxNum = txNum } mintettesNums = fromMaybe [maxBound] rcMintettesNum sequence_ [remoteBench $ paramsCtor p mNum uNum txNum | p <- rcPeriod , mNum <- mintettesNums , uNum <- usersNums rcUsers , txNum <- txNums rcUsers] where usersNums Nothing = [0] usersNums (Just (UDSingle{..})) = udsNumber usersNums (Just (UDMultiple{..})) = fromMaybe [genericLength udmUsers] udmNumber txNums Nothing = [0] txNums (Just (UDSingle{..})) = udsTransactionsNum txNums (Just (UDMultiple{..})) = udmTransactionsNum userDatas Nothing = [] userDatas (Just UDSingle {..}) = [udsData] userDatas (Just UDMultiple {..}) = udmUsers
input-output-hk/rscoin-haskell
bench/Remote/Wrapper.hs
gpl-3.0
22,780
0
27
7,154
5,418
2,788
2,630
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.ProximityBeacon.Namespaces.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the information about the specified namespace. Only the -- namespace visibility can be updated. -- -- /See:/ <https://developers.google.com/beacons/proximity/ Google Proximity Beacon API Reference> for @proximitybeacon.namespaces.update@. module Network.Google.Resource.ProximityBeacon.Namespaces.Update ( -- * REST Resource NamespacesUpdateResource -- * Creating a Request , namespacesUpdate , NamespacesUpdate -- * Request Lenses , nuXgafv , nuUploadProtocol , nuPp , nuAccessToken , nuUploadType , nuPayload , nuNamespaceName , nuBearerToken , nuProjectId , nuCallback ) where import Network.Google.Prelude import Network.Google.ProximityBeacon.Types -- | A resource alias for @proximitybeacon.namespaces.update@ method which the -- 'NamespacesUpdate' request conforms to. type NamespacesUpdateResource = "v1beta1" :> Capture "namespaceName" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "projectId" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Namespace :> Put '[JSON] Namespace -- | Updates the information about the specified namespace. Only the -- namespace visibility can be updated. -- -- /See:/ 'namespacesUpdate' smart constructor. data NamespacesUpdate = NamespacesUpdate' { _nuXgafv :: !(Maybe Text) , _nuUploadProtocol :: !(Maybe Text) , _nuPp :: !Bool , _nuAccessToken :: !(Maybe Text) , _nuUploadType :: !(Maybe Text) , _nuPayload :: !Namespace , _nuNamespaceName :: !Text , _nuBearerToken :: !(Maybe Text) , _nuProjectId :: !(Maybe Text) , _nuCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'NamespacesUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nuXgafv' -- -- * 'nuUploadProtocol' -- -- * 'nuPp' -- -- * 'nuAccessToken' -- -- * 'nuUploadType' -- -- * 'nuPayload' -- -- * 'nuNamespaceName' -- -- * 'nuBearerToken' -- -- * 'nuProjectId' -- -- * 'nuCallback' namespacesUpdate :: Namespace -- ^ 'nuPayload' -> Text -- ^ 'nuNamespaceName' -> NamespacesUpdate namespacesUpdate pNuPayload_ pNuNamespaceName_ = NamespacesUpdate' { _nuXgafv = Nothing , _nuUploadProtocol = Nothing , _nuPp = True , _nuAccessToken = Nothing , _nuUploadType = Nothing , _nuPayload = pNuPayload_ , _nuNamespaceName = pNuNamespaceName_ , _nuBearerToken = Nothing , _nuProjectId = Nothing , _nuCallback = Nothing } -- | V1 error format. nuXgafv :: Lens' NamespacesUpdate (Maybe Text) nuXgafv = lens _nuXgafv (\ s a -> s{_nuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). nuUploadProtocol :: Lens' NamespacesUpdate (Maybe Text) nuUploadProtocol = lens _nuUploadProtocol (\ s a -> s{_nuUploadProtocol = a}) -- | Pretty-print response. nuPp :: Lens' NamespacesUpdate Bool nuPp = lens _nuPp (\ s a -> s{_nuPp = a}) -- | OAuth access token. nuAccessToken :: Lens' NamespacesUpdate (Maybe Text) nuAccessToken = lens _nuAccessToken (\ s a -> s{_nuAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). nuUploadType :: Lens' NamespacesUpdate (Maybe Text) nuUploadType = lens _nuUploadType (\ s a -> s{_nuUploadType = a}) -- | Multipart request metadata. nuPayload :: Lens' NamespacesUpdate Namespace nuPayload = lens _nuPayload (\ s a -> s{_nuPayload = a}) -- | Resource name of this namespace. Namespaces names have the format: -- namespaces\/namespace. nuNamespaceName :: Lens' NamespacesUpdate Text nuNamespaceName = lens _nuNamespaceName (\ s a -> s{_nuNamespaceName = a}) -- | OAuth bearer token. nuBearerToken :: Lens' NamespacesUpdate (Maybe Text) nuBearerToken = lens _nuBearerToken (\ s a -> s{_nuBearerToken = a}) -- | The project id of the namespace to update. If the project id is not -- specified then the project making the request is used. The project id -- must match the project that owns the beacon. Optional. nuProjectId :: Lens' NamespacesUpdate (Maybe Text) nuProjectId = lens _nuProjectId (\ s a -> s{_nuProjectId = a}) -- | JSONP nuCallback :: Lens' NamespacesUpdate (Maybe Text) nuCallback = lens _nuCallback (\ s a -> s{_nuCallback = a}) instance GoogleRequest NamespacesUpdate where type Rs NamespacesUpdate = Namespace type Scopes NamespacesUpdate = '["https://www.googleapis.com/auth/userlocation.beacon.registry"] requestClient NamespacesUpdate'{..} = go _nuNamespaceName _nuXgafv _nuUploadProtocol (Just _nuPp) _nuAccessToken _nuUploadType _nuBearerToken _nuProjectId _nuCallback (Just AltJSON) _nuPayload proximityBeaconService where go = buildClient (Proxy :: Proxy NamespacesUpdateResource) mempty
rueshyna/gogol
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Namespaces/Update.hs
mpl-2.0
6,245
0
19
1,537
1,013
588
425
141
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.PubSub.Projects.Topics.SetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. -- -- /See:/ <https://cloud.google.com/pubsub/docs Google Cloud Pub/Sub API Reference> for @pubsub.projects.topics.setIamPolicy@. module Network.Google.Resource.PubSub.Projects.Topics.SetIAMPolicy ( -- * REST Resource ProjectsTopicsSetIAMPolicyResource -- * Creating a Request , projectsTopicsSetIAMPolicy , ProjectsTopicsSetIAMPolicy -- * Request Lenses , ptsipXgafv , ptsipUploadProtocol , ptsipPp , ptsipAccessToken , ptsipUploadType , ptsipPayload , ptsipBearerToken , ptsipResource , ptsipCallback ) where import Network.Google.Prelude import Network.Google.PubSub.Types -- | A resource alias for @pubsub.projects.topics.setIamPolicy@ method which the -- 'ProjectsTopicsSetIAMPolicy' request conforms to. type ProjectsTopicsSetIAMPolicyResource = "v1" :> CaptureMode "resource" "setIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetIAMPolicyRequest :> Post '[JSON] Policy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. -- -- /See:/ 'projectsTopicsSetIAMPolicy' smart constructor. data ProjectsTopicsSetIAMPolicy = ProjectsTopicsSetIAMPolicy' { _ptsipXgafv :: !(Maybe Xgafv) , _ptsipUploadProtocol :: !(Maybe Text) , _ptsipPp :: !Bool , _ptsipAccessToken :: !(Maybe Text) , _ptsipUploadType :: !(Maybe Text) , _ptsipPayload :: !SetIAMPolicyRequest , _ptsipBearerToken :: !(Maybe Text) , _ptsipResource :: !Text , _ptsipCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProjectsTopicsSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptsipXgafv' -- -- * 'ptsipUploadProtocol' -- -- * 'ptsipPp' -- -- * 'ptsipAccessToken' -- -- * 'ptsipUploadType' -- -- * 'ptsipPayload' -- -- * 'ptsipBearerToken' -- -- * 'ptsipResource' -- -- * 'ptsipCallback' projectsTopicsSetIAMPolicy :: SetIAMPolicyRequest -- ^ 'ptsipPayload' -> Text -- ^ 'ptsipResource' -> ProjectsTopicsSetIAMPolicy projectsTopicsSetIAMPolicy pPtsipPayload_ pPtsipResource_ = ProjectsTopicsSetIAMPolicy' { _ptsipXgafv = Nothing , _ptsipUploadProtocol = Nothing , _ptsipPp = True , _ptsipAccessToken = Nothing , _ptsipUploadType = Nothing , _ptsipPayload = pPtsipPayload_ , _ptsipBearerToken = Nothing , _ptsipResource = pPtsipResource_ , _ptsipCallback = Nothing } -- | V1 error format. ptsipXgafv :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Xgafv) ptsipXgafv = lens _ptsipXgafv (\ s a -> s{_ptsipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptsipUploadProtocol :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipUploadProtocol = lens _ptsipUploadProtocol (\ s a -> s{_ptsipUploadProtocol = a}) -- | Pretty-print response. ptsipPp :: Lens' ProjectsTopicsSetIAMPolicy Bool ptsipPp = lens _ptsipPp (\ s a -> s{_ptsipPp = a}) -- | OAuth access token. ptsipAccessToken :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipAccessToken = lens _ptsipAccessToken (\ s a -> s{_ptsipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptsipUploadType :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipUploadType = lens _ptsipUploadType (\ s a -> s{_ptsipUploadType = a}) -- | Multipart request metadata. ptsipPayload :: Lens' ProjectsTopicsSetIAMPolicy SetIAMPolicyRequest ptsipPayload = lens _ptsipPayload (\ s a -> s{_ptsipPayload = a}) -- | OAuth bearer token. ptsipBearerToken :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipBearerToken = lens _ptsipBearerToken (\ s a -> s{_ptsipBearerToken = a}) -- | REQUIRED: The resource for which the policy is being specified. -- \`resource\` is usually specified as a path. For example, a Project -- resource is specified as \`projects\/{project}\`. ptsipResource :: Lens' ProjectsTopicsSetIAMPolicy Text ptsipResource = lens _ptsipResource (\ s a -> s{_ptsipResource = a}) -- | JSONP ptsipCallback :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipCallback = lens _ptsipCallback (\ s a -> s{_ptsipCallback = a}) instance GoogleRequest ProjectsTopicsSetIAMPolicy where type Rs ProjectsTopicsSetIAMPolicy = Policy type Scopes ProjectsTopicsSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"] requestClient ProjectsTopicsSetIAMPolicy'{..} = go _ptsipResource _ptsipXgafv _ptsipUploadProtocol (Just _ptsipPp) _ptsipAccessToken _ptsipUploadType _ptsipBearerToken _ptsipCallback (Just AltJSON) _ptsipPayload pubSubService where go = buildClient (Proxy :: Proxy ProjectsTopicsSetIAMPolicyResource) mempty
rueshyna/gogol
gogol-pubsub/gen/Network/Google/Resource/PubSub/Projects/Topics/SetIAMPolicy.hs
mpl-2.0
6,389
0
18
1,486
938
546
392
136
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.KMS.RevokeGrant -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Revokes a grant. You can revoke a grant to actively deny operations that -- depend on it. -- -- <http://docs.aws.amazon.com/kms/latest/APIReference/API_RevokeGrant.html> module Network.AWS.KMS.RevokeGrant ( -- * Request RevokeGrant -- ** Request constructor , revokeGrant -- ** Request lenses , rgGrantId , rgKeyId -- * Response , RevokeGrantResponse -- ** Response constructor , revokeGrantResponse ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.KMS.Types import qualified GHC.Exts data RevokeGrant = RevokeGrant { _rgGrantId :: Text , _rgKeyId :: Text } deriving (Eq, Ord, Read, Show) -- | 'RevokeGrant' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rgGrantId' @::@ 'Text' -- -- * 'rgKeyId' @::@ 'Text' -- revokeGrant :: Text -- ^ 'rgKeyId' -> Text -- ^ 'rgGrantId' -> RevokeGrant revokeGrant p1 p2 = RevokeGrant { _rgKeyId = p1 , _rgGrantId = p2 } -- | Identifier of the grant to be revoked. rgGrantId :: Lens' RevokeGrant Text rgGrantId = lens _rgGrantId (\s a -> s { _rgGrantId = a }) -- | A unique identifier for the customer master key associated with the grant. -- This value can be a globally unique identifier or the fully specified ARN to -- a key. Key ARN Example - -- arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 Globally Unique Key ID Example - 12345678-1234-1234-123456789012 -- rgKeyId :: Lens' RevokeGrant Text rgKeyId = lens _rgKeyId (\s a -> s { _rgKeyId = a }) data RevokeGrantResponse = RevokeGrantResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'RevokeGrantResponse' constructor. revokeGrantResponse :: RevokeGrantResponse revokeGrantResponse = RevokeGrantResponse instance ToPath RevokeGrant where toPath = const "/" instance ToQuery RevokeGrant where toQuery = const mempty instance ToHeaders RevokeGrant instance ToJSON RevokeGrant where toJSON RevokeGrant{..} = object [ "KeyId" .= _rgKeyId , "GrantId" .= _rgGrantId ] instance AWSRequest RevokeGrant where type Sv RevokeGrant = KMS type Rs RevokeGrant = RevokeGrantResponse request = post "RevokeGrant" response = nullResponse RevokeGrantResponse
dysinger/amazonka
amazonka-kms/gen/Network/AWS/KMS/RevokeGrant.hs
mpl-2.0
3,351
0
9
771
414
253
161
54
1
module Lupo.Config where import qualified Data.ByteString as BS import qualified Data.Text as T import Text.XmlHtml import qualified Lupo.Entry as E import Lupo.Import data LupoConfig = LupoConfig { _lcSiteTitle :: T.Text , _lcSqlitePath :: FilePath , _lcLanguage :: T.Text , _lcLocaleFile :: FilePath , _lcDaysPerPage :: Integer , _lcFooterBody :: [Node] , _lcBasePath :: BS.ByteString , _lcSpamFilter :: E.Comment -> Bool , _lcAuthorName :: T.Text , _lcHashedPassword :: T.Text } makeLenses ''LupoConfig class (Monad m, Applicative m, Functor m) => GetLupoConfig m where getLupoConfig :: m LupoConfig refLupoConfig :: GetLupoConfig m => Getter LupoConfig a -> m a refLupoConfig getter = getLupoConfig <&> view getter
keitax/lupo
src/Lupo/Config.hs
lgpl-3.0
748
0
10
133
213
123
90
-1
-1
data RegEx = Eset | Estr | Literal Char | Concat RegEx RegEx | Alter RegEx RegEx | Star RegEx instance Show RegEx where show Eset = "0" show Estr = "$" show (Literal c) = [c] show (Concat r1 r2) = (show r1) ++ (show r2) show (Alter r1 r2) = "(" ++ show r1 ++ "|" ++ show r2 ++ ")" show (Star r) = show r ++ "*" test1 = Concat (Alter (Literal 'a') Estr) (Star (Literal 'b')) exactly "" = Estr exactly (c : cs) = Concat (Literal c) (exactly cs) test2 = exactly "MLR" singular Eset = False singular Estr = True singular (Literal c) = False singular (Concat r1 r2) = singular r1 && singular r2 singular (Alter r1 r2) = singular r1 || singular r2 singular (Star r) = True test3 = singular test1 test4 = singular test2
vedgar/mlr
2016 Kolokvij/Z4.hs
unlicense
767
0
9
199
363
181
182
20
1
module Week2 (specs) where import Test.Hspec import Test.QuickCheck import Week2.LogAnalysis import Week2.Log specs :: SpecWith () specs = ex1 ex1 :: SpecWith () ex1 = do describe "Week 2 - Ex. 1" $ do describe "parseMessage" $ do it "parses info log messages" $ property $ \time msg -> case parseMessage ("I " ++ show (time :: Int) ++ " " ++ msg) of Unknown _ -> False _ -> True it "parses warn log messages" $ property $ \time msg -> case parseMessage ("W " ++ show (time :: Int) ++ " " ++ msg) of Unknown _ -> False _ -> True it "parses error log messages" $ property $ \sev time msg -> let str = ("E " ++ show (sev :: Int) ++ " " ++ show (time :: Int) ++ " " ++ msg) in case parseMessage str of Unknown _ -> False _ -> True describe "Week 2 - Ex. 2" $ do -- TODO: Learn how to autogenerate MessageTree instances with QC and -- how to write props. -- https://github.com/nick8325/quickcheck/blob/master/examples/Set.hs describe "insert" $ do it "ignores Unknown insertions" $ do insert (Unknown "") Leaf `shouldBe` Leaf it "inserts in empty trees" $ do insert (LogMessage Info 1 "") Leaf `shouldBe` Node Leaf (LogMessage Info 1 "") Leaf it "inserts in the correct branch" $ do let m1 = (LogMessage Info 1 "") m2 = (LogMessage Info 2 "") insert m1 (Node Leaf m2 Leaf) `shouldBe` Node (Node Leaf m1 Leaf) m2 Leaf insert m2 (Node Leaf m1 Leaf) `shouldBe` Node Leaf m1 (Node Leaf m2 Leaf) describe "Week 2 - Ex. 5" $ do describe "whatWentWrong" $ do let logs = [ LogMessage Info 1 "Info" , LogMessage Warning 2 "Warn" , LogMessage (Error 10) 0 "Low sev error" , LogMessage (Error 60) 9 "Second high sev error" , LogMessage (Error 50) 5 "First high sev error" ] it "filters log entries by type and size" $ do length (whatWentWrong logs) `shouldBe` 2 it "orders log entries by timestamp" $ do whatWentWrong logs `shouldBe` [ "First high sev error" , "Second high sev error" ]
raphaelnova/cis194
test/Week2.hs
unlicense
2,626
0
26
1,106
693
339
354
51
4
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Network.Haskoin.Transaction.Types ( Tx(..) , txHash , TxIn(..) , TxOut(..) , OutPoint(..) , TxHash(..) , hexToTxHash , txHashToHex , nosigTxHash , nullOutPoint ) where import Control.Applicative ((<|>)) import Control.DeepSeq (NFData, rnf) import Control.Monad (forM_, guard, liftM2, mzero, replicateM, (<=<)) import Data.Aeson (FromJSON, ToJSON, Value (String), parseJSON, toJSON, withText) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Hashable (Hashable) import Data.Maybe (fromMaybe, maybe) import Data.Serialize (Serialize, decode, encode, get, put) import Data.Serialize.Get import Data.Serialize.Put import Data.String (IsString, fromString) import Data.String.Conversions (cs) import Data.Word (Word32, Word64) import Network.Haskoin.Crypto.Hash import Network.Haskoin.Network.Types import Network.Haskoin.Util newtype TxHash = TxHash { getTxHash :: Hash256 } deriving (Eq, Ord, NFData, Hashable, Serialize) instance Show TxHash where show = cs . txHashToHex instance IsString TxHash where fromString s = let e = error "Could not read transaction hash from hex string" in fromMaybe e $ hexToTxHash $ cs s instance FromJSON TxHash where parseJSON = withText "Transaction id" $ \t -> maybe mzero return $ hexToTxHash $ cs t instance ToJSON TxHash where toJSON = String . cs . txHashToHex nosigTxHash :: Tx -> TxHash nosigTxHash tx = TxHash $ doubleSHA256 $ encode tx { txIn = map clearInput $ txIn tx } where clearInput ti = ti { scriptInput = BS.empty } txHashToHex :: TxHash -> ByteString txHashToHex (TxHash h) = encodeHex (BS.reverse (encode h)) hexToTxHash :: ByteString -> Maybe TxHash hexToTxHash hex = do bs <- BS.reverse <$> decodeHex hex h <- either (const Nothing) Just (decode bs) return $ TxHash h type WitnessData = [WitnessStack] type WitnessStack = [WitnessStackItem] type WitnessStackItem = ByteString -- | Data type representing a bitcoin transaction data Tx = Tx { -- | Transaction data format version txVersion :: !Word32 -- | List of transaction inputs , txIn :: ![TxIn] -- | List of transaction outputs , txOut :: ![TxOut] -- | The witness data for the transaction , txWitness :: !WitnessData -- | The block number or timestamp at which this transaction is locked , txLockTime :: !Word32 } deriving (Eq, Ord) txHash :: Tx -> TxHash txHash = TxHash . doubleSHA256 . encode instance Show Tx where show = show . encodeHex . encode instance IsString Tx where fromString = fromMaybe e . (eitherToMaybe . decode <=< decodeHex) . cs where e = error "Could not read transaction from hex string" instance NFData Tx where rnf (Tx v i o w l) = rnf v `seq` rnf i `seq` rnf o `seq` rnf w `seq` rnf l instance Serialize Tx where get = parseWitnessTx <|> parseLegacyTx put tx | null (txWitness tx) = putLegacyTx tx | otherwise = putWitnessTx tx putLegacyTx :: Tx -> Put putLegacyTx (Tx v is os _ l) = do putWord32le v put $ VarInt $ fromIntegral $ length is forM_ is put put $ VarInt $ fromIntegral $ length os forM_ os put putWord32le l putWitnessTx :: Tx -> Put putWitnessTx (Tx v is os w l) = do putWord32le v putWord8 0x00 putWord8 0x01 put $ VarInt $ fromIntegral $ length is forM_ is put put $ VarInt $ fromIntegral $ length os forM_ os put putWitnessData w putWord32le l parseLegacyTx :: Get Tx parseLegacyTx = do v <- getWord32le is <- replicateList =<< get os <- replicateList =<< get l <- getWord32le return Tx {txVersion = v, txIn = is, txOut = os, txWitness = [], txLockTime = l} where replicateList (VarInt c) = replicateM (fromIntegral c) get parseWitnessTx :: Get Tx parseWitnessTx = do v <- getWord32le m <- getWord8 f <- getWord8 guard $ m == 0x00 guard $ f == 0x01 is <- replicateList =<< get os <- replicateList =<< get w <- parseWitnessData $ length is l <- getWord32le return Tx {txVersion = v, txIn = is, txOut = os, txWitness = w, txLockTime = l} where replicateList (VarInt c) = replicateM (fromIntegral c) get parseWitnessData :: Int -> Get WitnessData parseWitnessData n = replicateM n parseWitnessStack where parseWitnessStack = do VarInt i <- get replicateM (fromIntegral i) parseWitnessStackItem parseWitnessStackItem = do VarInt i <- get getByteString $ fromIntegral i putWitnessData :: WitnessData -> Put putWitnessData = mapM_ putWitnessStack where putWitnessStack ws = do put $ VarInt $ fromIntegral $ length ws mapM_ putWitnessStackItem ws putWitnessStackItem bs = do put $ VarInt $ fromIntegral $ BS.length bs putByteString bs instance FromJSON Tx where parseJSON = withText "Tx" $ maybe mzero return . (eitherToMaybe . decode <=< decodeHex) . cs instance ToJSON Tx where toJSON = String . cs . encodeHex . encode -- | Data type representing a transaction input. data TxIn = TxIn { -- | Reference the previous transaction output (hash + position) prevOutput :: !OutPoint -- | Script providing the requirements of the previous transaction -- output to spend those coins. , scriptInput :: !ByteString -- | BIP-68: -- Relative lock-time using consensus-enforced sequence numbers , txInSequence :: !Word32 } deriving (Eq, Show, Ord) instance NFData TxIn where rnf (TxIn p i s) = rnf p `seq` rnf i `seq` rnf s instance Serialize TxIn where get = TxIn <$> get <*> (readBS =<< get) <*> getWord32le where readBS (VarInt len) = getByteString $ fromIntegral len put (TxIn o s q) = do put o put $ VarInt $ fromIntegral $ BS.length s putByteString s putWord32le q -- | Data type representing a transaction output. data TxOut = TxOut { -- | Transaction output value. outValue :: !Word64 -- | Script specifying the conditions to spend this output. , scriptOutput :: !ByteString } deriving (Eq, Show, Ord) instance NFData TxOut where rnf (TxOut v o) = rnf v `seq` rnf o instance Serialize TxOut where get = do val <- getWord64le (VarInt len) <- get TxOut val <$> getByteString (fromIntegral len) put (TxOut o s) = do putWord64le o put $ VarInt $ fromIntegral $ BS.length s putByteString s -- | The OutPoint is used inside a transaction input to reference the previous -- transaction output that it is spending. data OutPoint = OutPoint { -- | The hash of the referenced transaction. outPointHash :: !TxHash -- | The position of the specific output in the transaction. -- The first output position is 0. , outPointIndex :: !Word32 } deriving (Show, Eq, Ord) instance NFData OutPoint where rnf (OutPoint h i) = rnf h `seq` rnf i instance FromJSON OutPoint where parseJSON = withText "OutPoint" $ maybe mzero return . (eitherToMaybe . decode <=< decodeHex) . cs instance ToJSON OutPoint where toJSON = String . cs . encodeHex . encode instance Serialize OutPoint where get = do (h,i) <- liftM2 (,) get getWord32le return $ OutPoint h i put (OutPoint h i) = put h >> putWord32le i -- | Outpoint used in coinbase transactions nullOutPoint :: OutPoint nullOutPoint = OutPoint { outPointHash = "0000000000000000000000000000000000000000000000000000000000000000" , outPointIndex = maxBound }
xenog/haskoin
src/Network/Haskoin/Transaction/Types.hs
unlicense
8,362
0
11
2,554
2,273
1,182
1,091
-1
-1
{- Created : 2014 Mar 16 (Sun) 12:23:18 by Harold Carr. Last Modified : 2014 Mar 16 (Sun) 12:41:23 by Harold Carr. -} {-# LANGUAGE DeriveDataTypeable #-} module Uni2 where import Data.Data import Data.Generics.Uniplate.Data import Data.Typeable data Request = Expand { shortUrl :: [String] , hash :: [String] } | Shorten { longUrl :: String , domain :: String } | LinkEdit { link :: String , title :: Maybe String , note :: Maybe String , private :: Maybe Bool , user_ts :: Maybe Int , archived :: Maybe Bool , edit :: [String] } deriving (Data, Show, Typeable) {- :t typeOf (Shorten "a" "b") => typeOf (Shorten "a" "b") :: TypeRep -} -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/generics/uniplate/src/Uni2.hs
unlicense
862
0
9
329
149
92
57
18
0
#!/usr/bin/env stack {- stack script --resolver lts-12.14 --package directory --package filepath --package unix -} import Control.Monad (foldM) import System.Directory (listDirectory) import System.Environment (getArgs) import System.FilePath ((</>)) import System.Posix.Files (getFileStatus, isDirectory) type Dir = FilePath type File = FilePath data FileTree = Dir :> [Either File FileTree] deriving Show main :: IO () main = do [a] <- getArgs w <- walk a print w walk :: Dir -> IO FileTree walk dir = do paths' <- listDirectory dir let paths = fmap (dir </>) paths' -- need to qualify paths children <- foldM go [] paths pure (dir :> children) where go :: [Either File FileTree] -> FilePath -> IO [Either File FileTree] go acc filePath = do stat <- getFileStatus filePath if isDirectory stat then do tree <- walk filePath pure (Right tree : acc) else pure (Left filePath : acc)
haroldcarr/learn-haskell-coq-ml-etc
haskell/playpen/filewalker.hs
unlicense
1,022
1
13
283
322
163
159
28
2
ans :: Double -> String ans x | x <= 48.0 = "light fly" | x <= 51.0 = "fly" | x <= 54.0 = "bantam" | x <= 57.0 = "feather" | x <= 60.0 = "light" | x <= 64.0 = "light welter" | x <= 69.0 = "welter" | x <= 75.0 = "light middle" | x <= 81.0 = "middle" | x <= 91.0 = "light heavy" | otherwise = "heavy" main = do c <- getContents let i = map read $ lines c :: [Double] o = map ans i mapM_ putStrLn o
a143753/AOJ
0048.hs
apache-2.0
431
10
11
134
212
98
114
18
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PackageImports #-} {- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} -------------------------------------------------------------------------------- -- |The standard set of functions and variables available to all programs. -- -- You may use any of these functions and variables without defining them. module Prelude ( -- $intro -- * Numbers module Internal.Num -- * Text , module Internal.Text -- * General purpose functions , module Internal.Prelude , IO , module Internal.Exports ) where import Internal.Exports import "base" Prelude (IO) import Internal.Num import Internal.Prelude hiding (randomsFrom) import Internal.Text hiding (fromCWText, toCWText) import Internal.CodeWorld import Internal.Color import Internal.Event import Internal.Picture -------------------------------------------------------------------------------- -- $intro -- Welome to CodeWorld! You can define your own pictures, animations, and games -- by defining variables and functions. There are four kinds of CodeWorld -- programs: -- -- * Pictures. To create a picture, you'll define the variable called @program@ -- using 'drawingOf'. The parameter to 'drawingOf' should be a 'Picture'. -- Example: -- -- > program = drawingOf(tree) -- -- * Animations. To create an animation, you'll define the variable called -- @program@ using 'animationOf'. The parameter to 'animationOf' should be a -- function, mapping each time in seconds (a 'Number') to a 'Picture' that is -- shown at that time. Example: -- -- > program = animationOf(spinningWheel) -- -- * Activities. An activity is a program that can interact with the user by -- responding to pointer and keyboard events. It also has a persistent state -- that can be used to remember information about the past. To create an -- activity, you should first decide on the type to describe the state of -- things (called the "world" type). You will then describe the activity with: -- an initial world, a change function that describes how the world changes -- when various things happen, and a picture function that converts the world -- into a picture to display. You will then use 'activityOf' to define -- @program@. Example: -- -- > program = activityOf(initial, change, picture) -- -- * Group activities. Finally, you can build a multi-user activity that others -- can join over the internet. The process is similar to activities, except -- that you'll specify a number of participants, and your change and picture -- functions receive extra arguments describing which participant an event or -- picture applies to. You'll use 'groupActivityOf' to define these. -- Example: -- -- > program = groupActivityOf(n, initial, change, picture)
pranjaltale16/codeworld
codeworld-base/src/Prelude.hs
apache-2.0
3,375
0
5
610
147
112
35
17
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} module HERMIT.Dictionary.Local.Let ( -- * Rewrites on Let Expressions externals -- ** Let Elimination , letNonRecSubstR , letNonRecSubstSafeR , letSubstR , letSubstSafeR , letElimR , letNonRecElimR , letRecElimR , progBindElimR , progBindNonRecElimR , progBindRecElimR -- ** Let Introduction , letIntroR , letNonRecIntroR , progNonRecIntroR , nonRecIntroR , letIntroUnfoldingR -- ** Let Floating Out , letFloatAppR , letFloatArgR , letFloatLetR , letFloatLamR , letFloatCaseR , letFloatCaseAltR , letFloatCastR , letFloatExprR , letFloatTopR -- ** Let Floating In , letFloatInR , letFloatInAppR , letFloatInCaseR , letFloatInLamR -- ** Miscallaneous , reorderNonRecLetsR , letTupleR , letToCaseR ) where import Control.Arrow import Control.Monad (when) -- Needs to have Monad context on GHC 7.8 import Control.Monad.Compat hiding (when) import Control.Monad.IO.Class import Data.List (intersect, partition) import Data.Monoid import HERMIT.Core import HERMIT.Context import HERMIT.Monad import HERMIT.Kure import HERMIT.External import HERMIT.GHC import HERMIT.Name import HERMIT.Utilities import HERMIT.Dictionary.Common import HERMIT.Dictionary.GHC hiding (externals) import HERMIT.Dictionary.Inline hiding (externals) import HERMIT.Dictionary.AlphaConversion hiding (externals) import HERMIT.Dictionary.Local.Bind hiding (externals) import Prelude.Compat hiding ((<$)) ------------------------------------------------------------------------------ -- | Externals relating to 'Let' expressions. externals :: [External] externals = [ external "let-subst" (promoteExprR letSubstR :: RewriteH LCore) [ "Let substitution: (let x = e1 in e2) ==> (e2[e1/x])" , "x must not be free in e1." ] .+ Deep .+ Eval , external "let-subst-safe" (promoteExprR letSubstSafeR :: RewriteH LCore) [ "Safe let substitution" , "let x = e1 in e2, safe to inline without duplicating work ==> e2[e1/x]," , "x must not be free in e1." ] .+ Deep .+ Eval , external "let-nonrec-subst-safe" (promoteExprR letNonRecSubstSafeR :: RewriteH LCore) [ "As let-subst-safe, but does not try to convert a recursive let into a non-recursive let first." ] .+ Deep .+ Eval -- , external "safe-let-subst-plus" (promoteExprR safeLetSubstPlusR :: RewriteH LCore) -- [ "Safe let substitution" -- , "let { x = e1, ... } in e2, " -- , " where safe to inline without duplicating work ==> e2[e1/x,...]," -- , "only matches non-recursive lets" ] .+ Deep .+ Eval , external "let-intro" (promoteExprR . letIntroR :: String -> RewriteH LCore) [ "e => (let v = e in v), name of v is provided" ] .+ Shallow .+ Introduce , external "let-intro-unfolding" (promoteExprR . letIntroUnfoldingR :: HermitName -> RewriteH LCore) [ "e => let f' = defn[f'/f] in e[f'/f], name of f is provided" ] , external "let-elim" (promoteExprR letElimR :: RewriteH LCore) [ "Remove an unused let binding." , "(let v = e1 in e2) ==> e2, if v is not free in e1 or e2." ] .+ Eval .+ Shallow -- , external "let-constructor-reuse" (promoteR $ not_defined "constructor-reuse" :: RewriteH LCore) -- [ "let v = C v1..vn in ... C v1..vn ... ==> let v = C v1..vn in ... v ..., fails otherwise" ] .+ Eval , external "let-float-app" (promoteExprR letFloatAppR :: RewriteH LCore) [ "(let v = ev in e) x ==> let v = ev in e x" ] .+ Commute .+ Shallow , external "let-float-arg" (promoteExprR letFloatArgR :: RewriteH LCore) [ "f (let v = ev in e) ==> let v = ev in f e" ] .+ Commute .+ Shallow , external "let-float-lam" (promoteExprR letFloatLamR :: RewriteH LCore) [ "The Full Laziness Transformation" , "(\\ v1 -> let v2 = e1 in e2) ==> let v2 = e1 in (\\ v1 -> e2), if v1 is not free in e2." , "If v1 = v2 then v1 will be alpha-renamed." ] .+ Commute .+ Shallow , external "let-float-let" (promoteExprR letFloatLetR :: RewriteH LCore) [ "let v = (let w = ew in ev) in e ==> let w = ew in let v = ev in e" ] .+ Commute .+ Shallow , external "let-float-case" (promoteExprR letFloatCaseR :: RewriteH LCore) [ "case (let v = ev in e) of ... ==> let v = ev in case e of ..." ] .+ Commute .+ Shallow .+ Eval , external "let-float-case-alt" (promoteExprR (letFloatCaseAltR Nothing) :: RewriteH LCore) [ "case s of { ... ; p -> let v = ev in e ; ... } " , "==> let v = ev in case s of { ... ; p -> e ; ... } " ] .+ Commute .+ Shallow .+ Eval , external "let-float-case-alt" (promoteExprR . letFloatCaseAltR . Just :: Int -> RewriteH LCore) [ "Float a let binding from specified alternative." , "case s of { ... ; p -> let v = ev in e ; ... } " , "==> let v = ev in case s of { ... ; p -> e ; ... } " ] .+ Commute .+ Shallow .+ Eval , external "let-float-cast" (promoteExprR letFloatCastR :: RewriteH LCore) [ "cast (let bnds in e) co ==> let bnds in cast e co" ] .+ Commute .+ Shallow , external "let-float-top" (promoteProgR letFloatTopR :: RewriteH LCore) [ "v = (let bds in e) : prog ==> bds : v = e : prog" ] .+ Commute .+ Shallow , external "let-float" (promoteProgR letFloatTopR <+ promoteExprR letFloatExprR :: RewriteH LCore) [ "Float a Let whatever the context." ] .+ Commute .+ Shallow -- Don't include in bash, as each sub-rewrite is tagged "Bash" already. , external "let-to-case" (promoteExprR letToCaseR :: RewriteH LCore) [ "let v = ev in e ==> case ev of v -> e" ] .+ Commute .+ Shallow .+ PreCondition -- , external "let-to-case-unbox" (promoteR $ not_defined "let-to-case-unbox" :: RewriteH LCore) -- [ "let v = ev in e ==> case ev of C v1..vn -> let v = C v1..vn in e" ] , external "let-float-in" (promoteExprR letFloatInR >+> anybuR (promoteExprR letElimR) :: RewriteH LCore) [ "Float-in a let if possible." ] .+ Commute .+ Shallow , external "let-float-in-app" ((promoteExprR letFloatInAppR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore) [ "let v = ev in f a ==> (let v = ev in f) (let v = ev in a)" ] .+ Commute .+ Shallow , external "let-float-in-case" ((promoteExprR letFloatInCaseR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore) [ "let v = ev in case s of p -> e ==> case (let v = ev in s) of p -> let v = ev in e" , "if v does not shadow a pattern binder in p" ] .+ Commute .+ Shallow , external "let-float-in-lam" ((promoteExprR letFloatInLamR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore) [ "let v = ev in \\ x -> e ==> \\ x -> let v = ev in e" , "if v does not shadow x" ] .+ Commute .+ Shallow , external "reorder-lets" (promoteExprR . reorderNonRecLetsR :: [String] -> RewriteH LCore) [ "Re-order a sequence of nested non-recursive let bindings." , "The argument list should contain the let-bound variables, in the desired order." ] , external "let-tuple" (promoteExprR . letTupleR :: String -> RewriteH LCore) [ "Combine nested non-recursive lets into case of a tuple." , "E.g. let {v1 = e1 ; v2 = e2 ; v3 = e3} in body ==> case (e1,e2,e3) of {(v1,v2,v3) -> body}" ] .+ Commute , external "prog-bind-elim" (promoteProgR progBindElimR :: RewriteH LCore) [ "Remove unused top-level binding(s)." , "prog-bind-nonrec-elim <+ prog-bind-rec-elim" ] .+ Eval .+ Shallow , external "prog-bind-nonrec-elim" (promoteProgR progBindNonRecElimR :: RewriteH LCore) [ "Remove unused top-level binding(s)." , "v = e : prog ==> prog, if v is not free in prog and not exported." ] .+ Eval .+ Shallow , external "prog-bind-rec-elim" (promoteProgR progBindRecElimR :: RewriteH LCore) [ "Remove unused top-level binding(s)." , "v+ = e+ : prog ==> v* = e* : prog, where v* is a subset of v+ consisting" , "of vs that are free in prog or e+, or exported." ] .+ Eval .+ Shallow ] ------------------------------------------------------------------------------------------- -- | (let x = e1 in e2) ==> (e2[e1/x]), (x must not be free in e1) letSubstR :: (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m) => Rewrite c m CoreExpr letSubstR = letAllR (tryR recToNonrecR) idR >>> letNonRecSubstR -- | As 'letNonRecSubstSafeR', but attempting to convert a singleton recursive binding to a non-recursive binding first. letSubstSafeR :: (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, ReadBindings c, HasEmptyContext c, MonadCatch m) => Rewrite c m CoreExpr letSubstSafeR = letAllR (tryR recToNonrecR) idR >>> letNonRecSubstSafeR -- | @Let (NonRec v e) body@ ==> @body[e/v]@ letNonRecSubstR :: MonadCatch m => Rewrite c m CoreExpr letNonRecSubstR = prefixFailMsg "Let substitution failed: " $ withPatFailMsg (wrongExprForm "Let (NonRec v rhs) body") $ do Let (NonRec v rhs) body <- idR return (substCoreExpr v rhs body) {- TODO: This was written very early in the project by Andy. It was later modified somewhat by Neil, but without reassessing the heurisitc as a whole. It may need revisiting. Safe Subst Heuristic -------------------- Substitution is safe if (A) OR (B) OR (C). (A) The let-bound variable is a type or coercion. (B) The let-bound value is either: (i) a variable; (ii) a lambda; (iii) an application that requires more value arguments before it can perform any computation. (C) In the body, the let-bound variable must NOT occur: (i) more than once; (ii) inside a lambda. -} -- | Currently we always substitute types and coercions, and use a heuristic to decide whether to substitute expressions. -- This may need revisiting. letNonRecSubstSafeR :: forall c m. (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, ReadBindings c, HasEmptyContext c, MonadCatch m) => Rewrite c m CoreExpr letNonRecSubstSafeR = do Let (NonRec v _) _ <- idR when (isId v) $ guardMsgM (safeSubstT v) "safety criteria not met." letNonRecSubstR where safeSubstT :: Id -> Transform c m CoreExpr Bool safeSubstT i = letNonRecT mempty safeBindT (safeOccursT i) (\ () -> (||)) -- what about other Expr constructors, e.g Cast? safeBindT :: Transform c m CoreExpr Bool safeBindT = do c <- contextT arr $ \ e -> case e of Var {} -> True Lam {} -> True App {} -> case collectArgs e of (Var f,args) -> arityOf c f > length (filter (not . isTyCoArg) args) -- Neil: I've changed this to "not . isTyCoArg" rather than "not . isTypeArg". -- This may not be the right thing to do though. (other,args) -> case collectBinders other of (bds,_) -> length bds > length args _ -> False safeOccursT :: Id -> Transform c m CoreExpr Bool safeOccursT i = do depth <- varBindingDepthT i let occursHereT :: Transform c m Core () occursHereT = promoteExprT (exprIsOccurrenceOfT i depth >>> guardT) -- lamOccurrenceT can only fail if the expression is not a Lam -- return either 2 (occurrence) or 0 (no occurrence) lamOccurrenceT :: Transform c m CoreExpr (Sum Int) lamOccurrenceT = lamT mempty (mtryM (Sum 2 <$ extractT (onetdT occursHereT))) mappend occurrencesT :: Transform c m Core (Sum Int) occurrencesT = prunetdT (promoteExprT lamOccurrenceT <+ (Sum 1 <$ occursHereT)) extractT occurrencesT >>^ (getSum >>> (< 2)) (<$) :: Monad m => a -> m b -> m a a <$ mb = mb >> return a ------------------------------------------------------------------------------------------- letElimR :: (ExtendPath c Crumb, AddBindings c, MonadCatch m) => Rewrite c m CoreExpr letElimR = prefixFailMsg "Let elimination failed: " $ withPatFailMsg (wrongExprForm "Let binds expr") $ do Let bg _ <- idR case bg of NonRec{} -> letNonRecElimR Rec{} -> letRecElimR -- | Remove an unused non-recursive let binding. -- @let v = E1 in E2@ ==> @E2@, if @v@ is not free in @E2@ letNonRecElimR :: MonadCatch m => Rewrite c m CoreExpr letNonRecElimR = withPatFailMsg (wrongExprForm "Let (NonRec v e1) e2") $ do Let (NonRec v _) e <- idR guardMsg (v `notElemVarSet` freeVarsExpr e) "let-bound variable appears in the expression." return e -- | Remove all unused recursive let bindings in the current group. letRecElimR :: MonadCatch m => Rewrite c m CoreExpr letRecElimR = withPatFailMsg (wrongExprForm "Let (Rec v e1) e2") $ do Let (Rec bnds) body <- idR let bodyFrees = freeIdsExpr body bsAndFrees = map (second freeIdsExpr) bnds usedIds = chaseDependencies bodyFrees bsAndFrees bs = mkVarSet (map fst bsAndFrees) liveBinders = bs `intersectVarSet` usedIds if isEmptyVarSet liveBinders then return body else if bs `subVarSet` liveBinders then fail "no dead binders to eliminate." else return $ Let (Rec $ filter ((`elemVarSet` liveBinders) . fst) bnds) body progBindElimR :: MonadCatch m => Rewrite c m CoreProg progBindElimR = progBindNonRecElimR <+ progBindRecElimR progBindNonRecElimR :: MonadCatch m => Rewrite c m CoreProg progBindNonRecElimR = withPatFailMsg (wrongExprForm "ProgCons (NonRec v e1) e2") $ do ProgCons (NonRec v _) p <- idR guardMsg (v `notElemVarSet` freeVarsProg p) "variable appears in program body." guardMsg (not (isExportedId v)) "variable is exported." return p -- | Remove all unused bindings at the top level. progBindRecElimR :: MonadCatch m => Rewrite c m CoreProg progBindRecElimR = withPatFailMsg (wrongExprForm "ProgCons (Rec v e1) e2") $ do ProgCons (Rec bnds) p <- idR let pFrees = freeVarsProg p bsAndFrees = map (second freeIdsExpr) bnds usedIds = chaseDependencies pFrees bsAndFrees bs = mkVarSet (map fst bsAndFrees) liveBinders = (bs `intersectVarSet` usedIds) `unionVarSet` (filterVarSet isExportedId bs) if isEmptyVarSet liveBinders then return p else if bs `subVarSet` liveBinders then fail "no dead binders to eliminate." else return $ ProgCons (Rec $ filter ((`elemVarSet` liveBinders) . fst) bnds) p chaseDependencies :: VarSet -> [(Var,VarSet)] -> VarSet chaseDependencies usedIds bsAndFrees = case partition ((`elemVarSet` usedIds) . fst) bsAndFrees of ([],_) -> usedIds (used,unused) -> chaseDependencies (unionVarSets (usedIds : map snd used)) unused ------------------------------------------------------------------------------------------- -- | @let v = ev in e@ ==> @case ev of v -> e@ letToCaseR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, ReadBindings c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letToCaseR = prefixFailMsg "Converting Let to Case failed: " $ withPatFailMsg (wrongExprForm "Let (NonRec v e1) e2") $ do Let (NonRec v ev) _ <- idR guardMsg (not $ isTyCoArg ev) "cannot case on a type or coercion." caseBndr <- extractT (cloneVarAvoidingT v Nothing [v]) letT mempty (replaceVarR v caseBndr) $ \ () e' -> Case ev caseBndr (varType v) [(DEFAULT, [], e')] ------------------------------------------------------------------------------------------- -- | @(let v = ev in e) x@ ==> @let v = ev in e x@ letFloatAppR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatAppR = prefixFailMsg "Let floating from App function failed: " $ withPatFailMsg (wrongExprForm "App (Let bnds body) e") $ do App (Let bnds body) e <- idR let vs = mkVarSet (bindVars bnds) `intersectVarSet` freeVarsExpr e if isEmptyVarSet vs then return $ Let bnds (App body e) else appAllR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatAppR -- | @f (let v = ev in e)@ ==> @let v = ev in f e@ letFloatArgR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatArgR = prefixFailMsg "Let floating from App argument failed: " $ withPatFailMsg (wrongExprForm "App f (Let bnds body)") $ do App f (Let bnds body) <- idR let vs = mkVarSet (bindVars bnds) `intersectVarSet` freeVarsExpr f if isEmptyVarSet vs then return $ Let bnds (App f body) else appAllR idR (alphaLetVarsR $ varSetElems vs) >>> letFloatArgR -- | @let v = (let bds in e1) in e2@ ==> @let bds in let v = e1 in e2@ letFloatLetR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatLetR = prefixFailMsg "Let floating from Let failed: " $ withPatFailMsg (wrongExprForm "Let (NonRec v (Let bds e1)) e2") $ do Let (NonRec v (Let bds e1)) e2 <- idR let vs = mkVarSet (bindVars bds) `intersectVarSet` freeVarsExpr e2 if isEmptyVarSet vs then return $ Let bds (Let (NonRec v e1) e2) else letNonRecAllR idR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatLetR -- | @(\ v -> let binds in e2)@ ==> @let binds in (\ v1 -> e2)@ -- Fails if @v@ occurs in the RHS of @binds@. -- If @v@ is shadowed in binds, then @v@ will be alpha-renamed. letFloatLamR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatLamR = prefixFailMsg "Let floating from Lam failed: " $ withPatFailMsg (wrongExprForm "Lam v1 (Let bds body)") $ do Lam v (Let binds body) <- idR let bs = bindVars binds fvs = freeVarsBind binds guardMsg (v `notElemVarSet` fvs) (unqualifiedName v ++ " occurs in the RHS of the let-bindings.") if v `elem` bs then alphaLamR Nothing >>> letFloatLamR else return $ Let binds (Lam v body) -- | @case (let bnds in e) of bndr alts@ ==> @let bnds in (case e of bndr alts)@ -- Fails if any variables bound in @bnds@ occurs in @alts@. letFloatCaseR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatCaseR = prefixFailMsg "Let floating from Case failed: " $ withPatFailMsg (wrongExprForm "Case (Let bnds e) w ty alts") $ do Case (Let bnds e) w ty alts <- idR let captures = mkVarSet (bindVars bnds) `intersectVarSet` delVarSet (unionVarSets $ map freeVarsAlt alts) w if isEmptyVarSet captures then return $ Let bnds (Case e w ty alts) else caseAllR (alphaLetVarsR $ varSetElems captures) idR idR (const idR) >>> letFloatCaseR -- | case e of w { ... ; p -> let b = rhs in body ; ... } ==> -- let b = rhs in case e of { ... ; p -> body ; ... } -- -- where no variable in `p` or `w` occurs freely in `rhs`, -- and where `b` does not capture a free variable in the overall case, -- and where `w` is not rebound in `b`. letFloatCaseAltR :: MonadCatch m => Maybe Int -> Rewrite c m CoreExpr letFloatCaseAltR maybeN = prefixFailMsg "Let float from case alternative failed: " $ withPatFailMsg (wrongExprForm "Case s w ty alts") $ do -- Perform the first safe let-floating out of a case alternative let letFloatOneAltM :: MonadCatch m => Id -> VarSet -> [CoreAlt] -> m (CoreBind,[CoreAlt]) letFloatOneAltM w fvs = go where go [] = fail "no lets can be safely floated from alternatives." go (alt:rest) = (do (bind,alt') <- letFloatAltM w fvs alt return (bind,alt':rest)) <+ liftM (second (alt :)) (go rest) -- (p -> let bnds in body) ==> (bnds, p -> body) letFloatAltM :: Monad m => Id -> VarSet -> CoreAlt -> m (CoreBind,CoreAlt) letFloatAltM w fvs (con, vs, Let bnds body) = do let bSet = mkVarSet (bindVars bnds) vSet = mkVarSet (w:vs) -- 'w' is not in 'fvs', but if it is rebound by 'b', doing this rewrite -- would cause it to bind things that were previously bound by 'b'. guardMsg (not (w `elemVarSet` bSet)) "floating would allow case binder to capture variables." -- no free vars in 'rhs' are bound by 'p' or 'w' guardMsg (isEmptyVarSet $ vSet `intersectVarSet` freeVarsBind bnds) "floating would cause variables in rhs to become unbound." -- no free vars in overall case are bound by 'b' guardMsg (isEmptyVarSet $ bSet `intersectVarSet` fvs) "floating would cause let binders to capture variables in case expression." return (bnds, (con, vs, body)) letFloatAltM _ _ _ = fail "no let expression on alternative right-hand side." Case e w ty alts <- idR fvs <- arr freeVarsExpr let l = length alts - 1 case maybeN of Just n | n < 0 || n > l -> fail $ "valid alternative indices: 0 to " ++ show l | otherwise -> do let (pre, alt:suf) = splitAt n alts (bnds,alt') <- letFloatAltM w fvs alt return $ Let bnds $ Case e w ty $ pre ++ (alt':suf) Nothing -> do (bnds,alts') <- letFloatOneAltM w fvs alts return $ Let bnds $ Case e w ty alts' -- | @cast (let bnds in e) co@ ==> @let bnds in cast e co@ letFloatCastR :: MonadCatch m => Rewrite c m CoreExpr letFloatCastR = prefixFailMsg "Let floating from Cast failed: " $ withPatFailMsg (wrongExprForm "Cast (Let bnds e) co") $ do Cast (Let bnds e) co <- idR return $ Let bnds (Cast e co) -- | Float a 'Let' through an expression, whatever the context. letFloatExprR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatExprR = setFailMsg "Unsuitable expression for Let floating." $ letFloatArgR <+ letFloatAppR <+ letFloatLetR <+ letFloatLamR <+ letFloatCaseR <+ letFloatCaseAltR Nothing <+ letFloatCastR -- | @'ProgCons' ('NonRec' v ('Let' bds e)) p@ ==> @'ProgCons' bds ('ProgCons' ('NonRec' v e) p)@ letFloatTopR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m) => Rewrite c m CoreProg letFloatTopR = prefixFailMsg "Let floating to top level failed: " $ withPatFailMsg (wrongExprForm "NonRec v (Let bds e) `ProgCons` p") $ do ProgCons (NonRec v (Let bds e)) p <- idR let bs = bindVars bds guardMsg (all isId bs) "type and coercion bindings are not allowed at the top level." let vs = intersectVarSet (mkVarSet bs) (freeVarsProg p) if isEmptyVarSet vs then return $ ProgCons bds (ProgCons (NonRec v e) p) else consNonRecAllR idR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatTopR ------------------------------------------------------------------------------------------- -- | Float in a 'Let' if possible. letFloatInR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatInR = letFloatInCaseR <+ letFloatInAppR <+ letFloatInLamR -- | @let v = ev in case s of p -> e@ ==> @case (let v = ev in s) of p -> let v = ev in e@, -- if @v@ does not shadow a pattern binder in @p@ letFloatInCaseR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatInCaseR = prefixFailMsg "Let floating in to case failed: " $ withPatFailMsg (wrongExprForm "Let bnds (Case s w ty alts)") $ do Let bnds (Case s w ty alts) <- idR let bs = bindVars bnds captured = bs `intersect` (w : concatMap altVars alts) guardMsg (null captured) "let bindings would capture case pattern bindings." let unbound = mkVarSet bs `intersectVarSet` (tyVarsOfType ty `unionVarSet` freeVarsVar w) guardMsg (isEmptyVarSet unbound) "type variables in case signature would become unbound." return (Case (Let bnds s) w ty alts) >>> caseAllR idR idR idR (\_ -> altAllR idR (\_ -> idR) (arr (Let bnds) >>> alphaLetR)) -- | @let v = ev in f a@ ==> @(let v = ev in f) (let v = ev in a)@ letFloatInAppR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m) => Rewrite c m CoreExpr letFloatInAppR = prefixFailMsg "Let floating in to app failed: " $ withPatFailMsg (wrongExprForm "Let bnds (App e1 e2)") $ do Let bnds (App e1 e2) <- idR lhs <- return (Let bnds e1) >>> alphaLetR return $ App lhs (Let bnds e2) -- | @let v = ev in \ x -> e@ ==> @\x -> let v = ev in e@ -- if @v@ does not shadow @x@ letFloatInLamR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, MonadCatch m) => Rewrite c m CoreExpr letFloatInLamR = prefixFailMsg "Let floating in to lambda failed: " $ withPatFailMsg (wrongExprForm "Let bnds (Lam v e)") $ do Let bnds (Lam v e) <- idR safe <- letT (arr bindVars) lamVarT $ flip notElem guardMsg safe "let bindings would capture lambda binding." return $ Lam v $ Let bnds e ------------------------------------------------------------------------------------------- -- | Re-order a sequence of nested non-recursive let bindings. -- The argument list should contain the let-bound variables, in the desired order. reorderNonRecLetsR :: MonadCatch m => [String] -> Rewrite c m CoreExpr reorderNonRecLetsR nms = prefixFailMsg "Reorder lets failed: " $ do guardMsg (notNull nms) "no names given." guardMsg (nodups nms) "duplicate names given." e <- idR (ves,x) <- setFailMsg "insufficient non-recursive lets." $ takeNonRecLets (length nms) e guardMsg (noneFreeIn ves) "some of the bound variables appear in the right-hand-sides." e' <- mkNonRecLets `liftM` mapM (lookupName ves) nms `ap` return x guardMsg (not $ exprSyntaxEq e e') "bindings already in specified order." return e' where takeNonRecLets :: Monad m => Int -> CoreExpr -> m ([(Var,CoreExpr)],CoreExpr) takeNonRecLets 0 x = return ([],x) takeNonRecLets n (Let (NonRec v1 e1) x) = first ((v1,e1):) `liftM` takeNonRecLets (n-1) x takeNonRecLets _ _ = fail "insufficient non-recursive lets." noneFreeIn :: [(Var,CoreExpr)] -> Bool noneFreeIn ves = let (vs,es) = unzip ves in all (`notElemVarSet` unionVarSets (map freeVarsExpr es)) vs lookupName :: Monad m => [(Var,CoreExpr)] -> String -> m (Var,CoreExpr) lookupName ves nm = case filter (cmpString2Var nm . fst) ves of [] -> fail $ "name " ++ nm ++ " not matched." [ve] -> return ve _ -> fail $ "multiple matches for " ++ nm ++ "." mkNonRecLets :: [(Var,CoreExpr)] -> CoreExpr -> CoreExpr mkNonRecLets [] x = x mkNonRecLets ((v,e):ves) x = Let (NonRec v e) (mkNonRecLets ves x) ------------------------------------------------------------------------------------------- -- | Combine nested non-recursive lets into case of a tuple. -- E.g. let {v1 = e1 ; v2 = e2 ; v3 = e3} in body ==> case (e1,e2,e3) of {(v1,v2,v3) -> body} letTupleR :: (MonadCatch m, MonadUnique m) => String -> Rewrite c m CoreExpr letTupleR nm = prefixFailMsg "Let-tuple failed: " $ do (bnds, body) <- arr collectLets let numBnds = length bnds guardMsg (numBnds > 1) "at least two non-recursive let bindings of identifiers required." let (vs, rhss) = unzip bnds -- check if tupling the bindings would cause unbound variables let frees = map freeVarsExpr (drop 1 rhss) used = unionVarSets $ zipWith intersectVarSet (map (mkVarSet . (`take` vs)) [1..]) frees if isEmptyVarSet used then let rhs = mkCoreTup rhss in constT $ do bndr <- newIdH nm (exprType rhs) return $ mkSmallTupleCase vs body bndr rhs else fail $ "the following bound variables are used in subsequent bindings: " ++ showVarSet used where -- we only collect identifiers (not type or coercion vars) because we intend to case on them. collectLets :: CoreExpr -> ([(Id, CoreExpr)],CoreExpr) collectLets (Let (NonRec v e) body) | isId v = first ((v,e):) (collectLets body) collectLets expr = ([],expr) ------------------------------------------------------------------------------------------- -- TODO: come up with a better naming scheme for these -- This code could be factored better. -- | @e@ ==> @let v = e in v@ letIntroR :: (MonadCatch m, MonadUnique m) => String -> Rewrite c m CoreExpr letIntroR nm = do e <- idR Let (NonRec v e') _ <- letNonRecIntroR nm e return $ Let (NonRec v e') (varToCoreExpr v) -- | @body@ ==> @let v = e in body@ letNonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m CoreExpr letNonRecIntroR nm e = prefixFailMsg "Let-introduction failed: " $ contextfreeT $ \ body -> do v <- newVarH nm $ exprKindOrType e return $ Let (NonRec v e) body -- This isn't a "Let", but it's serving the same role. Maybe create a Local/Prog module? -- | @prog@ ==> @'ProgCons' (v = e) prog@ progNonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m CoreProg progNonRecIntroR nm e = prefixFailMsg "Top-level binding introduction failed: " $ do guardMsg (not $ isTyCoArg e) "Top-level type or coercion definitions are prohibited." contextfreeT $ \ prog -> do i <- newIdH nm (exprType e) return $ ProgCons (NonRec i e) prog -- | nonRecIntroR nm e = 'letNonRecIntroR nm e' <+ 'progNonRecIntroR nm e' nonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m Core nonRecIntroR nm e = readerT $ \case ExprCore{} -> promoteExprR (letNonRecIntroR nm e) ProgCore{} -> promoteProgR (progNonRecIntroR nm e) _ -> fail "can only introduce non-recursive bindings at Program or Expression nodes." -- | Introduce a local definition for a (possibly imported) identifier. -- Rewrites occurences of the identifier to point to this new local definiton. letIntroUnfoldingR :: ( BoundVars c, ReadBindings c, HasDynFlags m, HasHermitMEnv m, LiftCoreM m , MonadCatch m, MonadIO m, MonadThings m, MonadUnique m ) => HermitName -> Rewrite c m CoreExpr letIntroUnfoldingR nm = do i <- findIdT nm (rhs,_) <- getUnfoldingT AllBinders <<< return i contextfreeT $ \ body -> do i' <- cloneVarH id i let subst = substCoreExpr i (varToCoreExpr i') bnd = if i `elemUFM` freeVarsExpr rhs then Rec [(i', subst rhs)] else NonRec i' rhs body' = subst body return $ mkCoreLet bnd body' -------------------------------------------------------------------------------------------
beni55/hermit
src/HERMIT/Dictionary/Local/Let.hs
bsd-2-clause
32,721
0
22
9,083
7,348
3,745
3,603
430
6
{- Jacob Albers CMSC 22311 - Functional Systems in Haskell Instructors: Stuart Kurtz & Jakub Tucholski -} {-# OPTIONS_GHC -Wall #-} module TestDB (main) where import Control.Distributed.Process import Control.Distributed.Process.Backend.SimpleLocalnet import Control.Monad import System.Exit (exitSuccess) import DistribUtils import Database main :: IO () main = distribMain masterTest rcdata masterTest :: Backend -> [NodeId] -> Process () masterTest backend peers = do --build database db <- createDB peers --fill database with contents of --the Database.hs file f <- liftIO $ readFile "Database.hs" let ws = words f liftIO $ putStr "Populating Worker Processes...\n" zipWithM_ (set db) ws (tail ws) --test basic GET functionality liftIO $ putStr "GET test - should be 'Database':\n" get db "module" >>= liftIO . print liftIO $ putStr "GET test - should be 'Nothing':\n" get db "xxxx" >>= liftIO . print --test basic SET functionailty liftIO $ putStr "SET test - new value, should be 'shark':\n" set db "xxxx" "shark" get db "xxxx" >>= liftIO . print liftIO $ putStr "SET test - changed value, should be 'changed':\n" set db "module" "changed" get db "module" >>= liftIO . print --test functionality when new file data has been added liftIO $ putStr "ADDFILE test - added DistribUtils, GET 'defaultHost' should be '=':\n" file <- liftIO $ readFile "DistribUtils.hs" let wrds = words file zipWithM_ (set db) wrds (tail wrds) get db "defaultHost" >>= liftIO . print liftIO $ putStr "SET & GET of new file data - should be 'bestHost'\n" set db "defaultHost" "bestHost" get db "defaultHost" >>= liftIO . print --remove a process liftIO $ putStr "Purposefully causing a worker process to end\n" terminateSlave (head peers) --Test if previous data is still present through gets & sets --test new GET functionality liftIO $ putStr "GET test - should be 'DistribUtils':\n" get db "module" >>= liftIO . print liftIO $ putStr "GET test - should be 'shark':\n" get db "xxxx" >>= liftIO . print --test new SET functionailty liftIO $ putStr "SET test - new value, should be 'barracuda':\n" set db "xxxx" "barracuda" get db "xxxx" >>= liftIO . print liftIO $ putStr "SET test - changed value, should be '2changed':\n" set db "module" "2changed" get db "module" >>= liftIO . print --test that quitting successfully closes out the session liftIO $ putStr "QUIT test - closing and terminating remaining workers:\n" terminateAllSlaves backend _ <- liftIO $ exitSuccess return ()
jalberz/distro-db
src/TestDB.hs
bsd-2-clause
2,590
0
10
518
591
271
320
51
1
{-# LANGUAGE Arrows #-} module Data.OpenDataTable.Parser ( parseBindings , parseInput , parseInputInfo , parsePaging , parsePagingNextPage , parsePagingPageSize , parsePagingStart , parsePagingTotal , parseMeta , parseOpenDataTable , parseSelect ) where import Text.Read import Data.Maybe import Text.XML.HXT.Core (arr, deep, constA, isElem, orElse, returnA, isA, listA, getText, none, hasName, getChildren, getAttrValue0, (<<<), (>>>), XmlTree, ArrowXml, ArrowList, ArrowChoice) import Data.OpenDataTable readBoolMaybe :: String -> Maybe Bool readBoolMaybe "true" = Just True readBoolMaybe "false" = Just False readBoolMaybe _ = Nothing atTag :: ArrowXml a => String -> a XmlTree XmlTree atTag tag = deep (isElem >>> hasName tag) atOptionalTag :: ArrowXml a => String -> a XmlTree (Maybe XmlTree) atOptionalTag tag = deep (isElem >>> hasName tag >>> arr Just) `orElse` (constA Nothing) text :: ArrowXml a => a XmlTree String text = getChildren >>> getText textAtTag :: ArrowXml a => String -> a XmlTree String textAtTag tag = atTag tag >>> text getList :: ArrowXml a => String -> a XmlTree c -> a XmlTree [c] getList tag cont = listA ( atTag tag >>> cont) getOptionalList :: (ArrowChoice a, ArrowXml a) => String -> a XmlTree b -> a (Maybe XmlTree) [b] getOptionalList tag cont = proc x -> do case x of Nothing -> returnA -< [] Just xml -> returnA <<< getList tag cont -< xml significant :: String -> Bool significant = not . all (`elem` " \n\r\t") optionalAttr :: ArrowXml a => String -> a XmlTree (Maybe String) optionalAttr attr = (getAttrValue0 attr >>> isA significant >>> arr Just) `orElse` (constA Nothing) optionalTextAtTag :: ArrowXml a => String -> a XmlTree (Maybe String) optionalTextAtTag tag = (textAtTag tag >>> arr Just) `orElse` (constA Nothing) optionalTextAtOptionalTag :: (ArrowChoice a, ArrowXml a) => String -> a (Maybe XmlTree) (Maybe String) optionalTextAtOptionalTag tag = proc mx -> do case mx of Nothing -> returnA -< Nothing Just x -> optionalTextAtTag tag -< x readOptionalAttrVal :: (ArrowChoice a, ArrowList a) => (b -> Maybe c) -> a (Maybe b) (Maybe c) readOptionalAttrVal reader = proc x -> do case x of Nothing -> returnA -< Nothing Just attr -> do let mRead = reader attr case mRead of Nothing -> none -< Nothing Just val -> returnA -< Just val readOptionalAttr :: (ArrowList a, ArrowChoice a, Read c) => a (Maybe String) (Maybe c) readOptionalAttr = readOptionalAttrVal readMaybe readOptionalAttrBool :: (ArrowList a, ArrowChoice a) => a (Maybe String) (Maybe Bool) readOptionalAttrBool = readOptionalAttrVal readBoolMaybe readAttrVal :: (ArrowChoice a, ArrowList a) => (b -> Maybe c) -> a b c readAttrVal reader = proc x -> do let mRead = reader x case mRead of Nothing -> none -< Nothing Just val -> returnA -< val readAttr :: (ArrowChoice a, ArrowList a, Read b) => a String b readAttr = readAttrVal readMaybe readAttrBool :: (ArrowChoice a, ArrowList a) => a String Bool readAttrBool = readAttrVal readBoolMaybe parseOpenDataTable :: (ArrowXml a, ArrowChoice a) => a XmlTree OpenDataTable parseOpenDataTable = proc x -> do mHttps <- optionalAttr "https" -< x https <- readOptionalAttr -< mHttps xmlns <- optionalAttr "xmlns" -< x securityLevel <- readOptionalAttr <<< optionalAttr "securityLevel" -< x meta <- parseMeta -< x mExecute <- optionalAttr "execute" -< x execute <- readOptionalAttr -< mExecute bindings <- parseBindings -< x returnA -< OpenDataTable xmlns securityLevel https meta execute bindings parseMeta :: (ArrowXml a) => a XmlTree Meta parseMeta = proc x -> do meta <- atTag "meta" -< x author <- optionalTextAtTag "author" -< meta apiKeyUrl <- optionalTextAtTag "apiKeyUrl" -< meta description <- optionalTextAtTag "description" -< meta sampleQueries <- getList "sampleQuery" text -< meta documentationUrl <- optionalTextAtTag "documentationURL" -< meta returnA -< Meta author description documentationUrl apiKeyUrl sampleQueries parseBindings :: (ArrowXml a, ArrowChoice a) => a XmlTree [Binding] parseBindings = proc x -> do bindings <- atTag "bindings" -< x selects <- listA (atTag "select" >>> parseSelect) -< bindings returnA -< SelectBinding `fmap` selects parseSelect :: (ArrowXml a, ArrowChoice a) => a XmlTree Select parseSelect = proc x -> do itemPath <- optionalAttr "itemPath" -< x produces <- readOptionalAttr <<< optionalAttr "produces" -< x pollingFrequencySeconds <- readOptionalAttr <<< optionalAttr "pollingFrequencySeconds" -< x url <- optionalTextAtOptionalTag "url" <<< atOptionalTag "urls" -< x inputs <- parseInput -< x execute <- optionalTextAtTag "execute" -< x paging <- (arr Just <<< parsePaging) `orElse` (constA Nothing) -< x returnA -< Select itemPath produces pollingFrequencySeconds url inputs execute paging parseInput :: (ArrowXml a, ArrowChoice a) => a XmlTree [Input] parseInput = proc x -> do inputs <- atOptionalTag "inputs" -< x keys <- getOptionalList "key" parseInputInfo -< inputs returnA -< InputKey `fmap` keys parseInputInfo :: (ArrowXml a, ArrowChoice a) => a XmlTree InputInfo parseInputInfo = proc x -> do id <- getAttrValue0 "id" -< x as <- optionalAttr "as" -< x typ <- readAttr <<< getAttrValue0 "type" -< x paramType <- readAttr <<< getAttrValue0 "paramType" -< x required <- readOptionalAttrBool <<< optionalAttr "required" -< x def <- optionalAttr "default" -< x private <- readOptionalAttrBool <<< optionalAttr "private" -< x const <- readOptionalAttrBool <<< optionalAttr "const" -< x batchable <- readOptionalAttrBool <<< optionalAttr "batchable" -< x maxBatchItems <- readOptionalAttr <<< optionalAttr "maxBatchItems" -< x returnA -< InputInfo id as typ paramType (fromMaybe False required) def private const batchable maxBatchItems parsePaging :: (ArrowXml a, ArrowChoice a) => a XmlTree Paging parsePaging = proc x -> do paging <- atTag "paging" -< x mModel <- optionalAttr "model" -< paging model <- readOptionalAttr -< mModel matrix <- readOptionalAttrBool <<< optionalAttr "matrix" -< paging pageSize <- (arr Just <<< parsePagingPageSize) `orElse` (constA Nothing) -< paging pageStart <- (arr Just <<< parsePagingStart) `orElse` (constA Nothing) -< paging pageTotal <- (arr Just <<< parsePagingTotal) `orElse` (constA Nothing) -< paging nextPage <- (arr Just <<< parsePagingNextPage) `orElse` (constA Nothing) -< paging returnA -< Paging model matrix pageSize pageStart pageTotal nextPage parsePagingPageSize :: ArrowXml a => a XmlTree PagingSize parsePagingPageSize = proc x -> do pageSize <- atTag "pagesize" -< x id <- getAttrValue0 "id" -< pageSize max <- getAttrValue0 "max" -< pageSize returnA -< PagingSize id $ read max parsePagingStart :: ArrowXml a => a XmlTree PagingStart parsePagingStart = proc x -> do pagingStart <- atTag "start" -< x id <- getAttrValue0 "id" -< pagingStart def <- getAttrValue0 "default" -< pagingStart returnA -< PagingStart id $ read def parsePagingTotal :: ArrowXml a => a XmlTree PagingTotal parsePagingTotal = proc x -> do pagingTotal <- atTag "total" -< x def <- getAttrValue0 "default" -< pagingTotal returnA -< PagingTotal $ read def parsePagingNextPage :: ArrowXml a => a XmlTree NextPage parsePagingNextPage = proc x -> do nextPage <- atTag "nextpage" -< x path <- getAttrValue0 "path" -< nextPage returnA -< NextPage path
fabianbergmark/OpenDataTable
Data/OpenDataTable/Parser.hs
bsd-2-clause
9,484
15
17
3,388
2,605
1,266
1,339
237
3
module BoxTest where import Elm.Utils ((|>)) import Test.Tasty import Test.Tasty.HUnit import qualified Data.Text.Lazy as LazyText import qualified Data.Text as Text import Box trim :: String -> String trim text = text |> LazyText.pack |> LazyText.lines |> map LazyText.stripEnd |> LazyText.unlines |> LazyText.unpack assertLineOutput :: String -> Line -> Assertion assertLineOutput expected actual = assertOutput (expected ++ "\n") (line actual) assertOutput :: String -> Box -> Assertion assertOutput expected actual = assertEqual expected expected $ trim $ Text.unpack $ render $ actual word :: String -> Box word = line . identifier block :: String -> Box block text = stack1 [ line $ row [ w, w ] , line $ row [ w, w ] ] where w = identifier text tests :: TestTree tests = testGroup "ElmFormat.Render.BoxTest" [ testCase "keyword" $ assertLineOutput "module" $ keyword "module" , testCase "identifier" $ assertLineOutput "sqrt" $ identifier "sqrt" , testCase "punctuation" $ assertLineOutput "::" $ punc "::" , testCase "row" $ assertLineOutput "ab" $ row [ identifier "a", identifier "b" ] , testCase "space" $ assertLineOutput "a b" $ row [ identifier "a", space, identifier "b" ] , testCase "stack1" $ assertOutput "foo\nbar\n" $ stack1 [ word "foo" , word "bar" ] , testCase "indent" $ assertOutput " a\n b\n" $ indent $ stack1 [ word "a" , word "b" ] , testCase "indent (with leading spaces)" $ assertOutput " a\n" $ prefix space $ indent $ line $ identifier "a" ]
nukisman/elm-format-short
tests/BoxTest.hs
bsd-3-clause
1,840
0
12
606
509
260
249
57
1
module Main where import qualified Data.Text as Text import Lib import System.Environment main :: IO () main = do args <- getArgs case args of [from, to] -> rename (Text.pack from) (Text.pack to) _ -> putStrLn "Usage: pinboard-tag-rename OLD_TAG NEW_TAG"
lmartel-sundry/pinboard-tag-rename
app/Main.hs
bsd-3-clause
269
0
13
54
91
49
42
10
2
{-# LANGUAGE OverloadedStrings #-} module Servant.ChinesePod.API ( api -- * API specification , ChinesePod -- ** Account , Login , Logout , GetUserInfo -- *** Request types , ReqLogin(..) , ReqLogout(..) , ReqGetUserInfo(..) , ReqSignature(..) -- *** Response types , RespLogin(..) , RespGetUserInfo(..) -- ** Lesson , GetLesson -- *** Request types , ReqGetLesson(..) -- ** Library , GetLatestLessons , SearchLessons -- *** Request types , ReqGetLatestLessons(..) , ReqSearchLessons(..) -- * ChinesePod specific datatypes , AccessToken(..) , Example , Expansion(..) , GrammarPoint(..) , GrammarSentence(..) , Lesson(..) , LessonContent(..) , LessonContentType(..) , Level(..) , Sentence(..) , UserId(..) , V3Id(..) , Vocabulary(..) , Word(..) -- * Auxiliary -- ** Types , OK(..) , Undocumented , SearchResults(..) , StrOrInt(..) -- ** Parsing combinators , tryRead , parseFailure ) where import Prelude hiding (Word) import Control.Monad import Crypto.Hash import Data.Aeson.Types hiding ((.:?)) import Data.Bifunctor (bimap) import Data.Binary (Binary) import Data.Data (Data) import Data.Either (rights) import Data.List (sortBy) import Data.Map (Map) import Data.Maybe (catMaybes) import Data.Monoid ((<>)) import Data.Ord (comparing) import Data.Proxy import Data.String (IsString) import Data.Text (Text) import Data.Typeable import GHC.Generics import Servant.API import Text.Show.Pretty (PrettyVal(..)) import Web.FormUrlEncoded import qualified Data.Aeson.Types as Aeson import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as BS.UTF8 import qualified Data.HashMap.Strict as HashMap import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Vector as Vector import Servant.ChinesePod.Util.Orphans.PrettyVal () api :: Proxy ChinesePod api = Proxy {------------------------------------------------------------------------------- API -------------------------------------------------------------------------------} type ChinesePod = "api" :> "0.6" :> Services type Services = "account" :> "login" :> Login :<|> "account" :> "logout" :> Logout :<|> "account" :> "get-user-info" :> GetUserInfo :<|> "lesson" :> "get-lesson" :> GetLesson :<|> "library" :> "get-latest-lessons" :> GetLatestLessons :<|> "library" :> "search-lessons" :> SearchLessons type Login = Request ReqLogin RespLogin type Logout = Request ReqLogout OK type GetUserInfo = Request ReqGetUserInfo RespGetUserInfo type GetLesson = Request ReqGetLesson LessonContent type GetLatestLessons = Request ReqGetLatestLessons (SearchResults Lesson) type SearchLessons = Request ReqSearchLessons (SearchResults Lesson) type Request req resp = ReqBody '[FormUrlEncoded] req :> Post '[JSON] resp {------------------------------------------------------------------------------- Request types -------------------------------------------------------------------------------} data ReqLogin = ReqLogin { reqLoginClientId :: String , reqLoginEmail :: String , reqLoginSignature :: ReqSignature } deriving (Show, Generic, Data) data ReqSignature = ReqSignature { reqSignatureClientSecret :: String , reqSignatureUserPassword :: String } deriving (Show, Generic, Data) data ReqLogout = ReqLogout { reqLogoutAccessToken :: AccessToken , reqLogoutUserId :: UserId } deriving (Show, Generic, Data) data ReqGetUserInfo = ReqGetUserInfo { reqGetUserInfoAccessToken :: AccessToken , reqGetUserInfoUserId :: UserId } deriving (Show, Generic, Data) data ReqGetLesson = ReqGetLesson { reqGetLessonAccessToken :: AccessToken , reqGetLessonUserId :: UserId , reqGetLessonV3Id :: V3Id , reqGetLessonType :: Maybe LessonContentType } deriving (Show, Generic, Data) data ReqSearchLessons = ReqSearchLessons { reqSearchLessonsAccessToken :: AccessToken , reqSearchLessonsUserId :: UserId , reqSearchLessonsSearch :: String , reqSearchLessonsSearchLevel :: Maybe Level , reqSearchLessonsNumResults :: Maybe Int , reqSearchLessonsPage :: Maybe Int } deriving (Show, Generic, Data) data ReqGetLatestLessons = ReqGetLatestLessons { reqGetLatestLessonsAccessToken :: AccessToken , reqGetLatestLessonsUserId :: UserId , reqGetLatestLessonsPage :: Maybe Int , reqGetLatestLessonsCount :: Maybe Int , reqGetLatestLessonsLang :: Maybe String , reqGetLatestLessonsLevelId :: Maybe Level } deriving (Show, Generic, Data) {------------------------------------------------------------------------------- Responses -------------------------------------------------------------------------------} data RespLogin = RespLogin { respLoginAccessToken :: AccessToken , respLoginUserId :: UserId , respLoginUsername :: String , respLoginName :: String , respLoginSelfStudyLessonsTotal :: Int , respLoginAssignedLessonsTotal :: Int , respLoginCoursesCount :: Int , respLoginLang :: String , respLoginBio :: String , respLoginAvatarUrl :: String , respLoginNewLessonNotification :: Bool , respLoginNewShowNotification :: Bool , respLoginNewsletterNotification :: Bool , respLoginGeneralNotification :: Bool , respLoginBookmarkedLessons :: Int , respLoginSubscribedLessons :: Int , respLoginStudiedLessons :: Int } deriving (Show, Generic, Data) data RespGetUserInfo = RespGetUserInfo { respGetUserInfoName :: String , respGetUserInfoUsername :: String , respGetUserInfoAvatarUrl :: String , respGetUserInfoBio :: String , respGetUserInfoUseTraditionalCharacters :: Bool , respGetUserInfoUserId :: UserId , respGetUserInfoNewLessonNotification :: Bool , respGetUserInfoNewShowNotification :: Bool , respGetUserInfoNewsletterNotification :: Bool , respGetUserInfoGeneralNotification :: Bool , respGetUserInfoLevel :: Maybe Level , respGetUserInfoType :: Undocumented String } deriving (Show, Generic, Data) {------------------------------------------------------------------------------- ChinesePod specific datatypes -------------------------------------------------------------------------------} newtype UserId = UserId { userIdString :: String } deriving (Show, Generic, Data, Eq, Ord, FromJSON, ToHttpApiData, FromHttpApiData, IsString) newtype AccessToken = AccessToken { accessTokenString :: String } deriving (Show, Generic, Data, Eq, Ord, FromJSON, ToHttpApiData, FromHttpApiData, IsString) newtype V3Id = V3Id { v3IdString :: String } deriving (Show, Generic, Data, Eq, Ord, FromJSON, ToHttpApiData, FromHttpApiData, IsString) -- | Some ChinesePod requests simply return OK data OK = OK deriving (Show, Generic, Data) -- | User level data Level = LevelNewbie | LevelElementary | LevelIntermediate | LevelUpperIntermediate | LevelAdvanced | LevelMedia | LevelOther String deriving (Show, Generic, Data) data Lesson = Lesson { lessonV3Id :: V3Id , lessonTitle :: String , lessonIntroduction :: String , lessonLevel :: Maybe Level , lessonName :: String , lessonSlug :: String , lessonLessonId :: Maybe String , lessonPublicationTimestamp :: String , lessonImage :: String , lessonBookMarked :: Bool , lessonMarkAsStudied :: Bool , lessonSource :: Maybe String , lessonStatus :: Maybe String , lessonRadioQualityMp3 :: Maybe String , lessonDialogueMp3 :: Maybe String , lessonReviewMp3 :: Maybe String } deriving (Show, Generic, Data) data LessonContentType = LessonContentAll | LessonContentExercise | LessonContentVocabulary | LessonContentDialogue | LessonContentGrammar deriving (Show, Generic, Data) data LessonContent = LessonContent { lessonContentContentId :: String , lessonContentCreatedAt :: String , lessonContentUpdatedAt :: String , lessonContentStatusComments :: String , lessonContentStatusLocked :: String , lessonContentStatusPublished :: String , lessonContentCreatedBy :: String , lessonContentUpdatedBy :: String , lessonContentPopularity :: String , lessonContentRank :: String , lessonContentSlug :: String , lessonContentType :: String , lessonContentSeriesId :: String , lessonContentChannelId :: String , lessonContentMaturity :: String , lessonContentTitle :: String , lessonContentIntroduction :: String , lessonContentTheme :: String , lessonContentChannel :: String , lessonContentLevel :: Maybe Level , lessonContentHosts :: String , lessonContentV3Id :: V3Id , lessonContentHashCode :: String , lessonContentPublicationTimestamp :: String , lessonContentTimeOffset :: String , lessonContentImage :: String , lessonContentText :: String , lessonContentTranscription1 :: String , lessonContentTranscription2 :: String , lessonContentMp3Media :: String , lessonContentMp3Mobile :: String , lessonContentPdf1 :: String , lessonContentPdf2 :: String , lessonContentPdf3 :: String , lessonContentPdf4 :: String , lessonContentPpt :: Maybe String , lessonContentPptSize :: Maybe String , lessonContentVideoFix :: String , lessonContentLinkSource :: String , lessonContentLinkRelated :: String , lessonContentExercisesExercise1 :: String , lessonContentExercisesExercise2 :: String , lessonContentExercisesExercise3 :: String , lessonContentExercisesExercise4 :: String , lessonContentXmlFileName :: String , lessonContentMp3DialogueSize :: Int , lessonContentMp3MediaSize :: Int , lessonContentMp3MobileSize :: Int , lessonContentMp3PublicSize :: Int , lessonContentMp3PrivateSize :: Int , lessonContentMp3ThefixSize :: Int , lessonContentMp3ThefixLength :: String , lessonContentMp3PublicLength :: String , lessonContentMp3PrivateLength :: String , lessonContentMp3MobileLength :: String , lessonContentMp3MediaLength :: String , lessonContentMp3DialogueLength :: String , lessonContentVideoFlv :: String , lessonContentVideoFlvSize :: Int , lessonContentVideoFlvLength :: String , lessonContentVideoMp4 :: String , lessonContentVideoMp4Size :: Int , lessonContentVideoMp4Length :: String , lessonContentVideoM4v :: String , lessonContentVideoM4vSize :: Int , lessonContentVideoM4vLength :: String , lessonContentLastCommentId :: String , lessonContentLastCommentTime :: String , lessonContentIsPrivate :: Bool , lessonContentVideo :: Maybe String , lessonContentLessonPlan :: String , lessonContentLessonAssignment :: String , lessonContentName :: String , lessonContentSeriesName :: String , lessonContentRadioQualityMp3 :: String , lessonContentCdQualityMp3 :: Maybe String , lessonContentDialogueMp3 :: Maybe String , lessonContentReviewMp3 :: Maybe String , lessonContentCommentCount :: Int , lessonContentVideoLesson :: Maybe Bool , lessonContentAccessLevel :: String , lessonContentBookMarked :: Bool , lessonContentMarkAsStudied :: Bool , lessonContentStudentFullname :: String , lessonContentPostDate :: Maybe String , lessonContentStudentComment :: Maybe String , lessonContentFileName :: String , lessonContentFileUrl :: Maybe String , lessonContentTeacherName :: Maybe String , lessonContentTeacherId :: Maybe String , lessonContentReviewDate :: Maybe String , lessonContentTeacherFeedback :: Maybe String , lessonContentTopics :: [String] , lessonContentFunctions :: [String] , lessonContentDialogue :: Maybe [Sentence] , lessonContentGrammar :: Maybe [GrammarPoint] , lessonContentExpansion :: Maybe Expansion , lessonContentVocabulary :: Maybe Vocabulary } deriving (Show, Generic, Data) data Sentence = Sentence { sentenceV3Id :: V3Id , sentenceAudio :: String , sentenceDisplayOrder :: Int , sentenceId :: String , sentencePinyin :: String , sentenceRow3 :: String , sentenceRow4 :: String , sentenceSource :: String , sentenceSourceT :: Maybe String , sentenceSpeaker :: String , sentenceTarget :: String , sentenceVocabulary :: String , sentenceSentenceWords :: [Word] } deriving (Show, Generic, Data) data Word = Word { wordV3Id :: Maybe V3Id , wordAudio :: Maybe String , wordId :: Maybe String , wordPinyin :: String , wordSource :: String , wordSourceT :: String , wordTarget :: String , wordVcid :: Maybe String , wordImage :: Maybe String , wordDisplayOrder :: Maybe Int , wordVocabularyClass :: Maybe String } deriving (Show, Generic, Data) data GrammarPoint = GrammarPoint { grammarPointCreateTime :: String , grammarPointDisplayLayer :: Int , grammarPointDisplaySort :: Int , grammarPointDisplayType :: String , grammarPointGrammarId :: String , grammarPointImage :: String , grammarPointIntroduction :: String , grammarPointLevel :: Maybe Level , grammarPointName :: String , grammarPointParentId :: String , grammarPointPath :: String , grammarPointProductionId :: String , grammarPointRelatedGrammar :: String , grammarPointSentences :: [GrammarSentence] , grammarPointSummary :: String , grammarPointTree :: String , grammarPointUpdateTime :: String } deriving (Show, Generic, Data) data GrammarSentence = GrammarSentence { grammarSentenceAudio :: String , grammarSentenceCreateTime :: Maybe String , grammarSentenceDescription :: String , grammarSentenceDisplaySort :: Maybe Int , grammarSentenceGrammarBlockId :: Maybe String , grammarSentenceGrammarId :: String , grammarSentenceGrammarSentenceId :: Maybe String , grammarSentenceIsCorrect :: Maybe Bool , grammarSentencePinyin :: String , grammarSentenceSource :: String , grammarSentenceSourceAudio :: Maybe String , grammarSentenceSourceT :: String , grammarSentenceSourceTrad :: Maybe String , grammarSentenceSummary :: String , grammarSentenceTarget :: Maybe String , grammarSentenceTargetAnnotate :: Maybe String , grammarSentenceTargetAudio :: Maybe String , grammarSentenceTargetTrad :: Maybe String , grammarSentenceTips :: Maybe String , grammarSentenceUpdateTime :: Maybe String , grammarSentenceWords :: [Word] } deriving (Show, Generic, Data) data Example = Example { exampleAudio :: String , exampleExpansionWord :: [Word] , exampleId :: String , examplePinyin :: String , exampleSource :: String , exampleSourceT :: Maybe String , exampleTarget :: String } deriving (Show, Generic, Data) data Vocabulary = Vocabulary { vocabularyKeyVocab :: [Word] , vocabularySupVocab :: [Word] } deriving (Show, Generic, Data) data Expansion = Expansion { expansion :: Map String [Example] } deriving (Show, Generic, Data) {------------------------------------------------------------------------------- Encoding requests -------------------------------------------------------------------------------} -- | The 'ToText' instance for 'ReqSignature' is the hash instance ToHttpApiData ReqSignature where toQueryParam ReqSignature{..} = toQueryParam . show . sha1 . BS.UTF8.fromString $ concat [ reqSignatureClientSecret , reqSignatureUserPassword ] where sha1 :: BS.ByteString -> Digest SHA1 sha1 = hash instance ToForm ReqLogin where toForm ReqLogin{..} = mkForm [ ( "client_id" , toQueryParam reqLoginClientId ) , ( "email" , toQueryParam reqLoginEmail ) , ( "signature" , toQueryParam reqLoginSignature ) ] instance ToForm ReqLogout where toForm ReqLogout{..} = mkForm [ ( "access_token" , toQueryParam reqLogoutAccessToken ) , ( "user_id" , toQueryParam reqLogoutUserId ) ] instance ToForm ReqGetUserInfo where toForm ReqGetUserInfo{..} = mkForm [ ( "access_token" , toQueryParam reqGetUserInfoAccessToken ) , ( "user_id" , toQueryParam reqGetUserInfoUserId ) ] instance ToForm ReqSearchLessons where toForm ReqSearchLessons{..} = mkForm ([ ( "access_token" , toQueryParam reqSearchLessonsAccessToken ) , ( "user_id" , toQueryParam reqSearchLessonsUserId ) , ( "search" , toQueryParam reqSearchLessonsSearch ) ] ++ catMaybes [ optFormArg "search_level" (toQueryParam . Str) reqSearchLessonsSearchLevel , optFormArg "num_results" (toQueryParam) reqSearchLessonsNumResults , optFormArg "page" (toQueryParam) reqSearchLessonsPage ]) instance ToForm ReqGetLatestLessons where toForm ReqGetLatestLessons{..} = mkForm ([ ( "access_token" , toQueryParam reqGetLatestLessonsAccessToken ) , ( "user_id" , toQueryParam reqGetLatestLessonsUserId ) ] ++ catMaybes [ optFormArg "page" (toQueryParam) reqGetLatestLessonsPage , optFormArg "count" (toQueryParam) reqGetLatestLessonsCount , optFormArg "lang" (toQueryParam) reqGetLatestLessonsLang , optFormArg "level_id" (toQueryParam . Int) reqGetLatestLessonsLevelId ]) instance ToForm ReqGetLesson where toForm ReqGetLesson{..} = mkForm ([ ( "access_token" , toQueryParam reqGetLessonAccessToken ) , ( "user_id" , toQueryParam reqGetLessonUserId ) , ( "v3id" , toQueryParam reqGetLessonV3Id ) ] ++ catMaybes [ optFormArg "type" (toQueryParam) reqGetLessonType ]) {------------------------------------------------------------------------------- Auxiliary: Constructing forms -------------------------------------------------------------------------------} -- | Similar to 'fromEntriesByKey', but allowing only a single value per -- entry and requires the /caller/ to call 'toQueryParam' on the values -- (so that different entries can be of different types). mkForm :: [(Text, Text)] -> Form mkForm = Form . HashMap.fromListWith (<>) . map (bimap toFormKey (:[])) optFormArg :: Text -> (a -> Text) -> Maybe a -> Maybe (Text, Text) optFormArg nm f = fmap $ \a -> (nm, f a) {------------------------------------------------------------------------------- Decoding responses -------------------------------------------------------------------------------} instance FromJSON RespLogin where parseJSON = withObject "RespLogin" $ \obj -> do respLoginAccessToken <- obj .: "access_token" respLoginUserId <- obj .: "user_id" respLoginUsername <- obj .: "username" respLoginName <- obj .: "name" respLoginSelfStudyLessonsTotal <- obj .:~ "self_study_lessons_total" respLoginAssignedLessonsTotal <- obj .: "assigned_lessons_total" respLoginCoursesCount <- obj .:~ "courses_count" respLoginLang <- obj .: "lang" respLoginBio <- obj .: "bio" respLoginAvatarUrl <- obj .: "avatar_url" respLoginNewLessonNotification <- obj .:~ "new_lesson_notification" respLoginNewShowNotification <- obj .:~ "new_show_notification" respLoginNewsletterNotification <- obj .:~ "newsletter_notification" respLoginGeneralNotification <- obj .:~ "general_notification" respLoginBookmarkedLessons <- obj .: "bookmarked_lessons" respLoginSubscribedLessons <- obj .: "subscribed_lessons" respLoginStudiedLessons <- obj .: "studied_lessons" return RespLogin{..} instance FromJSON RespGetUserInfo where parseJSON = withObject "RespGetUserInfo" $ \obj -> do respGetUserInfoName <- obj .: "name" respGetUserInfoUsername <- obj .: "username" respGetUserInfoAvatarUrl <- obj .: "avatar_url" respGetUserInfoBio <- obj .: "bio" respGetUserInfoUseTraditionalCharacters <- obj .:~ "use_traditional_characters" respGetUserInfoUserId <- obj .:~ "user_id" respGetUserInfoNewLessonNotification <- obj .:~ "new_lesson_notification" respGetUserInfoNewShowNotification <- obj .:~ "new_show_notification" respGetUserInfoNewsletterNotification <- obj .:~ "newsletter_notification" respGetUserInfoGeneralNotification <- obj .:~ "general_notification" respGetUserInfoLevel <- obj .:~ "level" respGetUserInfoType <- obj .:? "type" return RespGetUserInfo{..} {------------------------------------------------------------------------------- Encoding/decoding ChinesePod types -------------------------------------------------------------------------------} instance FromJSON OK where parseJSON = withObject "OK" $ \obj -> do result <- obj .: "result" case result :: String of "OK" -> return OK _ -> fail $ "Expected OK" instance FromJSON Lesson where parseJSON = withObject "Lesson" $ \obj -> do lessonV3Id <- obj .: "v3_id" lessonTitle <- obj .: "title" lessonIntroduction <- obj .: "introduction" lessonLevel <- join <$> obj .:?~ "level" lessonName <- obj .:? "name" .!= "" lessonSlug <- obj .: "slug" lessonLessonId <- obj .:? "lesson_id" lessonPublicationTimestamp <- obj .: "publication_timestamp" lessonImage <- obj .: "image" lessonBookMarked <- obj .:~ "book_marked" lessonMarkAsStudied <- obj .:~ "mark_as_studied" lessonSource <- obj .:? "source" lessonStatus <- obj .:? "status" lessonRadioQualityMp3 <- obj .:? "radio_quality_mp3" lessonDialogueMp3 <- obj .:? "dialogue_mp3" lessonReviewMp3 <- obj .:? "review_mp3" return Lesson{..} instance ToHttpApiData LessonContentType where toQueryParam LessonContentAll = "all" toQueryParam LessonContentExercise = "exercise" toQueryParam LessonContentVocabulary = "vocabulary" toQueryParam LessonContentDialogue = "dialogue" toQueryParam LessonContentGrammar = "grammar" instance FromHttpApiData LessonContentType where parseQueryParam "all" = Right $ LessonContentAll parseQueryParam "exercise" = Right $ LessonContentExercise parseQueryParam "vocabulary" = Right $ LessonContentVocabulary parseQueryParam "dialogue" = Right $ LessonContentDialogue parseQueryParam "grammar" = Right $ LessonContentGrammar parseQueryParam typ = Left $ T.pack $ "Invalid lesson content type " ++ show typ instance FromJSON LessonContent where parseJSON = withObject "LessonContent" $ \obj -> do lessonContentContentId <- obj .: "content_id" lessonContentCreatedAt <- obj .: "created_at" lessonContentUpdatedAt <- obj .: "updated_at" lessonContentStatusComments <- obj .: "status_comments" lessonContentStatusLocked <- obj .: "status_locked" lessonContentStatusPublished <- obj .: "status_published" lessonContentCreatedBy <- obj .: "created_by" lessonContentUpdatedBy <- obj .: "updated_by" lessonContentPopularity <- obj .: "popularity" lessonContentRank <- obj .: "rank" lessonContentSlug <- obj .: "slug" lessonContentType <- obj .: "type" lessonContentSeriesId <- obj .: "series_id" lessonContentChannelId <- obj .: "channel_id" lessonContentMaturity <- obj .: "maturity" lessonContentTitle <- obj .: "title" lessonContentIntroduction <- obj .: "introduction" lessonContentTheme <- obj .: "theme" lessonContentChannel <- obj .: "channel" lessonContentLevel <- join <$> obj .:?~ "level" lessonContentHosts <- obj .: "hosts" lessonContentV3Id <- obj .: "v3_id" lessonContentHashCode <- obj .: "hash_code" lessonContentPublicationTimestamp <- obj .: "publication_timestamp" lessonContentTimeOffset <- obj .: "time_offset" lessonContentImage <- obj .: "image" lessonContentText <- obj .: "text" lessonContentTranscription1 <- obj .: "transcription1" lessonContentTranscription2 <- obj .: "transcription2" lessonContentMp3Media <- obj .: "mp3_media" lessonContentMp3Mobile <- obj .: "mp3_mobile" lessonContentPdf1 <- obj .: "pdf1" lessonContentPdf2 <- obj .: "pdf2" lessonContentPdf3 <- obj .: "pdf3" lessonContentPdf4 <- obj .: "pdf4" lessonContentPpt <- obj .:? "ppt" lessonContentPptSize <- obj .:? "ppt_size" lessonContentVideoFix <- obj .: "video_fix" lessonContentLinkSource <- obj .: "link_source" lessonContentLinkRelated <- obj .: "link_related" lessonContentExercisesExercise1 <- obj .: "exercises_exercise1" lessonContentExercisesExercise2 <- obj .: "exercises_exercise2" lessonContentExercisesExercise3 <- obj .: "exercises_exercise3" lessonContentExercisesExercise4 <- obj .: "exercises_exercise4" lessonContentXmlFileName <- obj .: "xml_file_name" lessonContentMp3DialogueSize <- obj .:~ "mp3_dialogue_size" lessonContentMp3MediaSize <- obj .:~ "mp3_media_size" lessonContentMp3MobileSize <- obj .:~ "mp3_mobile_size" lessonContentMp3PublicSize <- obj .:~ "mp3_public_size" lessonContentMp3PrivateSize <- obj .:~ "mp3_private_size" lessonContentMp3ThefixSize <- obj .:~ "mp3_thefix_size" lessonContentMp3ThefixLength <- obj .: "mp3_thefix_length" lessonContentMp3PublicLength <- obj .: "mp3_public_length" lessonContentMp3PrivateLength <- obj .: "mp3_private_length" lessonContentMp3MobileLength <- obj .: "mp3_mobile_length" lessonContentMp3MediaLength <- obj .: "mp3_media_length" lessonContentMp3DialogueLength <- obj .: "mp3_dialogue_length" lessonContentVideoFlv <- obj .: "video_flv" lessonContentVideoFlvSize <- obj .:~ "video_flv_size" lessonContentVideoFlvLength <- obj .: "video_flv_length" lessonContentVideoMp4 <- obj .: "video_mp4" lessonContentVideoMp4Size <- obj .:~ "video_mp4_size" lessonContentVideoMp4Length <- obj .: "video_mp4_length" lessonContentVideoM4v <- obj .: "video_m4v" lessonContentVideoM4vSize <- obj .:~ "video_m4v_size" lessonContentVideoM4vLength <- obj .: "video_m4v_length" lessonContentLastCommentId <- obj .: "last_comment_id" lessonContentLastCommentTime <- obj .: "last_comment_time" lessonContentIsPrivate <- obj .:~ "is_private" lessonContentVideo <- obj .:? "video" lessonContentLessonPlan <- obj .: "lesson_plan" lessonContentLessonAssignment <- obj .: "lesson_assignment" lessonContentName <- obj .: "name" lessonContentSeriesName <- obj .: "series_name" lessonContentRadioQualityMp3 <- obj .: "radio_quality_mp3" lessonContentCdQualityMp3 <- obj .:? "cd_quality_mp3" lessonContentDialogueMp3 <- obj .:? "dialogue_mp3" lessonContentReviewMp3 <- obj .:? "review_mp3" lessonContentCommentCount <- obj .:~ "comment_count" lessonContentVideoLesson <- obj .:? "video_lesson" lessonContentAccessLevel <- obj .: "access_level" lessonContentBookMarked <- obj .:~ "book_marked" lessonContentMarkAsStudied <- obj .:~ "mark_as_studied" lessonContentStudentFullname <- obj .: "student_fullname" lessonContentPostDate <- obj .:? "post_date" lessonContentStudentComment <- obj .:? "student_comment" lessonContentFileName <- obj .: "file_name" lessonContentFileUrl <- obj .:? "file_url" lessonContentTeacherName <- obj .:? "teacher_name" lessonContentTeacherId <- obj .: "teacher_id" lessonContentReviewDate <- obj .:? "review_date" lessonContentTeacherFeedback <- obj .:? "teacher_feedback" lessonContentTopics <- obj .: "topics" lessonContentFunctions <- obj .: "functions" lessonContentDialogue <- obj .:? "dialogue" lessonContentGrammar <- obj .:? "grammar" lessonContentExpansion <- obj .:? "expansion" lessonContentVocabulary <- obj .:? "vocabulary" return LessonContent{..} instance FromJSON Sentence where parseJSON = withObject "Sentence" $ \obj -> do sentenceV3Id <- obj .: "v3_id" sentenceAudio <- obj .: "audio" sentenceDisplayOrder <- obj .:~ "display_order" sentenceId <- obj .: "id" sentencePinyin <- obj .: "pinyin" sentenceRow3 <- obj .: "row_3" sentenceRow4 <- obj .: "row_4" sentenceSource <- obj .: "source" sentenceSourceT <- obj .:? "source_t" sentenceSpeaker <- obj .: "speaker" sentenceTarget <- obj .: "target" sentenceVocabulary <- obj .: "vocabulary" sentenceSentenceWords <- obj .: "sentence_words" return Sentence{..} instance FromJSON Word where parseJSON = withObject "Word" $ \obj -> do wordV3Id <- obj .:? "v3_id" wordAudio <- obj .:? "audio" wordId <- obj .:? "id" wordPinyin <- obj .: "pinyin" wordSource <- obj .: "source" wordSourceT <- obj .: "source_t" wordTarget <- obj .: "target" wordVcid <- obj .:? "vcid" wordImage <- obj .:? "image" wordDisplayOrder <- obj .:?~ "display_order" wordVocabularyClass <- obj .:? "vocabulary_class" return Word{..} instance FromJSON GrammarPoint where parseJSON = withObject "GrammarPoint" $ \obj -> do grammarPointCreateTime <- obj .: "create_time" grammarPointDisplayLayer <- obj .:~ "display_layer" grammarPointDisplaySort <- obj .:~ "display_sort" grammarPointDisplayType <- obj .: "display_type" grammarPointGrammarId <- obj .: "grammar_id" grammarPointImage <- obj .: "image" grammarPointIntroduction <- obj .: "introduction" grammarPointLevel <- join <$> obj .:?~ "level_name" grammarPointName <- obj .: "name" grammarPointParentId <- obj .: "parent_id" grammarPointPath <- obj .: "path" grammarPointProductionId <- obj .: "production_id" grammarPointRelatedGrammar <- obj .: "related_grammar" grammarPointSentences <- obj .: "sentences" grammarPointSummary <- obj .: "summary" grammarPointTree <- obj .: "tree" grammarPointUpdateTime <- obj .: "update_time" return GrammarPoint{..} instance FromJSON GrammarSentence where parseJSON = withObject "GrammarSentence" $ \obj -> do grammarSentenceAudio <- obj .: "audio" grammarSentenceCreateTime <- obj .:? "create_time" grammarSentenceDescription <- obj .: "description" grammarSentenceDisplaySort <- obj .:?~ "display_sort" grammarSentenceGrammarBlockId <- obj .:? "grammar_block_id" grammarSentenceGrammarId <- obj .: "grammar_id" grammarSentenceGrammarSentenceId <- obj .:? "grammar_sentence_id" grammarSentenceIsCorrect <- obj .:?~ "is_correct" grammarSentencePinyin <- obj .: "pinyin" grammarSentenceSource <- obj .: "source" grammarSentenceSourceAudio <- obj .:? "source_audio" grammarSentenceSourceT <- obj .: "source_t" grammarSentenceSourceTrad <- obj .:? "source_trad" grammarSentenceSummary <- obj .: "summary" grammarSentenceTarget <- obj .:? "target" grammarSentenceTargetAnnotate <- obj .:? "target_annotate" grammarSentenceTargetAudio <- obj .:? "target_audio" grammarSentenceTargetTrad <- obj .:? "target_trad" grammarSentenceTips <- obj .:? "tips" grammarSentenceUpdateTime <- obj .:? "update_time" grammarSentenceWords <- obj .: "words" return GrammarSentence{..} instance FromJSON Example where parseJSON = withObject "Example" $ \obj -> do exampleAudio <- obj .: "audio" exampleExpansionWord <- maybeIndexed <$> obj .: "expansion_word" exampleId <- obj .: "id" examplePinyin <- obj .: "pinyin" exampleSource <- obj .: "source" exampleSourceT <- obj .:? "source_t" exampleTarget <- obj .: "target" return Example{..} instance FromJSON Vocabulary where parseJSON = withObject "Vocabulary" $ \obj -> do vocabularyKeyVocab <- obj .: "key_vocab" vocabularySupVocab <- obj .: "sup_vocab" return Vocabulary{..} instance FromJSON Expansion where parseJSON (Object obj) = Expansion . Map.fromList <$> mapM parseFld (HashMap.toList obj) where parseFld :: (Text, Value) -> Parser (String, [Example]) parseFld (word, val) = do examples <- parseJSON val return (T.unpack word, examples) parseJSON (Array arr) = do if Vector.null arr then return Expansion { expansion = Map.empty } else fail $ "Unexpected non-empty array in 'expansion'" parseJSON val = typeMismatch "Expansion" val {------------------------------------------------------------------------------- String/int encoding for specific types -------------------------------------------------------------------------------} instance ToStrOrInt Level where toStr = go where go LevelNewbie = "Newbie" go LevelElementary = "Elementary" go LevelIntermediate = "Intermediate" go LevelUpperIntermediate = "Upper Intermediate" go LevelAdvanced = "Advanced" go LevelMedia = "Media" go (LevelOther other) = T.pack other toInt = go where go LevelNewbie = 1 go LevelElementary = 2 go LevelIntermediate = 3 go LevelUpperIntermediate = 4 go LevelAdvanced = 5 go LevelMedia = 6 go (LevelOther other) = error $ "No numeric value for " ++ other instance FromStrOrInt Int where fromStr = tryRead . T.unpack fromInt = Right instance FromStrOrInt UserId where fromStr = Right . UserId . T.unpack fromInt = Right . UserId . show instance FromStrOrInt Bool where fromStr = go where go "0" = Right False go "1" = Right True go _ = Left "Expected 0 or 1" fromInt = go where go 0 = Right False go 1 = Right True go _ = Left "Expected 0 or 1" instance FromStrOrInt (Maybe Level) where fromStr = go where go "Newbie" = Right $ Just LevelNewbie go "Elementary" = Right $ Just LevelElementary go "Intermediate" = Right $ Just LevelIntermediate go "Upper Intermediate" = Right $ Just LevelUpperIntermediate go "Advanced" = Right $ Just LevelAdvanced go "Media" = Right $ Just LevelMedia go other = Right $ Just (LevelOther $ T.unpack other) fromInt = go where go 0 = Right $ Nothing go 1 = Right $ Just LevelNewbie go 2 = Right $ Just LevelElementary go 3 = Right $ Just LevelIntermediate go 4 = Right $ Just LevelUpperIntermediate go 5 = Right $ Just LevelAdvanced go 6 = Right $ Just LevelMedia go i = Left $ T.pack $ "Invalid Level " ++ show i {------------------------------------------------------------------------------- Values that can be encoded as either strings or as numbers -------------------------------------------------------------------------------} -- | Encode as either a string or a number -- -- The ChinesePod API is not very consistent with what is represented as -- a number, and what as a string. In order not to choke on these, we allow -- them to be represented as either. data StrOrInt a = Str { strOrInt :: a } | Int { strOrInt :: a } class ToStrOrInt a where toStr :: a -> Text toInt :: a -> Int class FromStrOrInt a where fromStr :: Text -> Either Text a fromInt :: Int -> Either Text a instance (Typeable a, FromStrOrInt a) => FromJSON (StrOrInt a) where parseJSON (String s) = case fromStr s of Right level -> return $ Str level Left err -> parseFailure err parseJSON (Number n) = case fromInt (round n) of Right level -> return $ Int level Left err -> parseFailure err parseJSON val = typeMismatch (show (typeOf (undefined :: a))) val instance FromStrOrInt a => FromHttpApiData (StrOrInt a) where parseQueryParam txt = either (\_err -> fmap Str $ fromStr txt) (fmap Int . fromInt) (tryRead $ T.unpack txt) instance ToStrOrInt a => ToHttpApiData (StrOrInt a) where toQueryParam (Str a) = toStr a toQueryParam (Int a) = T.pack $ show (toInt a) {------------------------------------------------------------------------------- Generic search results -------------------------------------------------------------------------------} data SearchResults a = SearchResults { searchResults :: Map Int a , searchResultsTotal :: Int } deriving (Show, Generic, Data) instance FromJSON a => FromJSON (SearchResults a) where parseJSON = withObject "SearchResults" $ \obj -> do let rawResults = rights $ map extractRaw (HashMap.toList obj) searchResults <- Map.fromList <$> mapM parseRaw rawResults searchResultsTotal <- obj .:~ "total" return SearchResults{..} where extractRaw :: (Text, Value) -> Either Text (Int, Value) extractRaw (idx, val) = do idx' <- parseQueryParam idx return (idx', val) parseRaw :: (Int, Value) -> Parser (Int, a) parseRaw (idx, val) = do val' <- parseJSON val return (idx, val') {------------------------------------------------------------------------------- Undocumented fields -------------------------------------------------------------------------------} -- | Some requests return more info than is documented in the API -- -- Since we should not rely on these fields being set, we mark them. type Undocumented = Maybe {------------------------------------------------------------------------------- Parser auxiliary -------------------------------------------------------------------------------} tryRead :: Read a => String -> Either Text a tryRead strA = case filter fullParse (readsPrec 0 strA) of [(a, _)] -> Right a _otherwise -> Left $ T.pack $ "Failed to parse " ++ show strA where fullParse :: (a, String) -> Bool fullParse = null . snd parseFailure :: forall a m. (Typeable a, Monad m) => Text -> m a parseFailure inp = fail $ "Could not parse " ++ show inp ++ " " ++ "as " ++ show (typeOf (undefined :: a)) -- | Variant on '(Aeson..:?)' which regards 'Null' as absent, too. (.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a) obj .:? key = case HashMap.lookup key obj of Just Null -> return Nothing _otherwise -> obj Aeson..:? key -- | "Approximate" accessor that uses StrOrInt (.:~) :: (Typeable a, FromStrOrInt a) => Object -> Text -> Parser a obj .:~ key = strOrInt <$> obj .: key -- | Combination of '(.:?)' and '(.:~)' (.:?~) :: (Typeable a, FromStrOrInt a) => Object -> Text -> Parser (Maybe a) obj .:?~ key = fmap strOrInt <$> obj .:? key -- | A list that is either represented as a JSON list or as a JSON object with -- indices as keys newtype MaybeIndexed a = MaybeIndexed { maybeIndexed :: [a] } instance (Typeable a, FromJSON a) => FromJSON (MaybeIndexed a) where parseJSON (Array arr) = MaybeIndexed <$> mapM parseJSON (Vector.toList arr) parseJSON (Object obj) = do let rawResults = rights $ map extractRaw (HashMap.toList obj) MaybeIndexed <$> mapM parseJSON (sortRaw rawResults) where extractRaw :: (Text, Value) -> Either Text (Int, Value) extractRaw (idx, val) = do idx' <- parseQueryParam idx return (idx', val) sortRaw :: [(Int, Value)] -> [Value] sortRaw = map snd . sortBy (comparing fst) parseJSON val = typeMismatch ("MaybeIndex " ++ show (typeOf (undefined :: a))) val {------------------------------------------------------------------------------- Binary instances -------------------------------------------------------------------------------} instance Binary Example instance Binary Expansion instance Binary GrammarPoint instance Binary GrammarSentence instance Binary Lesson instance Binary LessonContent instance Binary Level instance Binary Sentence instance Binary V3Id instance Binary Vocabulary instance Binary Word instance Binary a => Binary (SearchResults a) {------------------------------------------------------------------------------- PrettyVal instances -------------------------------------------------------------------------------} instance PrettyVal ReqGetLatestLessons instance PrettyVal ReqGetLesson instance PrettyVal ReqGetUserInfo instance PrettyVal ReqLogin instance PrettyVal ReqLogout instance PrettyVal ReqSearchLessons instance PrettyVal ReqSignature instance PrettyVal RespGetUserInfo instance PrettyVal RespLogin instance PrettyVal AccessToken instance PrettyVal Example instance PrettyVal Expansion instance PrettyVal GrammarPoint instance PrettyVal GrammarSentence instance PrettyVal Lesson instance PrettyVal LessonContent instance PrettyVal LessonContentType instance PrettyVal Level instance PrettyVal OK instance PrettyVal Sentence instance PrettyVal UserId instance PrettyVal V3Id instance PrettyVal Vocabulary instance PrettyVal Word instance PrettyVal a => PrettyVal (SearchResults a)
edsko/ChinesePodAPI
src/Servant/ChinesePod/API.hs
bsd-3-clause
45,756
0
21
13,198
9,049
4,794
4,255
-1
-1
-- ------------------------------------------------------ -- -- Copyright © 2012 AlephCloud Systems, Inc. -- ------------------------------------------------------ -- module Aws.Route53.Commands ( -- * Actions on Hosted Zones module Aws.Route53.Commands.CreateHostedZone , module Aws.Route53.Commands.GetHostedZone , module Aws.Route53.Commands.DeleteHostedZone , module Aws.Route53.Commands.ListHostedZones -- * Actions on Resource Record Sets , module Aws.Route53.Commands.ChangeResourceRecordSets , module Aws.Route53.Commands.ListResourceRecordSets , module Aws.Route53.Commands.GetChange -- * Other Commands , module Aws.Route53.Commands.GetDate ) where import Aws.Route53.Commands.CreateHostedZone import Aws.Route53.Commands.GetHostedZone import Aws.Route53.Commands.DeleteHostedZone import Aws.Route53.Commands.ListHostedZones import Aws.Route53.Commands.ChangeResourceRecordSets import Aws.Route53.Commands.ListResourceRecordSets import Aws.Route53.Commands.GetChange import Aws.Route53.Commands.GetDate
memcachier/aws-route53
Aws/Route53/Commands.hs
bsd-3-clause
1,025
0
5
85
135
100
35
18
0
module Main where import Control.Monad import Data.List import System.Environment main = do fmap f getContents >>= putStr f ('$':'|':ls) = '|': f ls f ('|':'$':ls) = '|': f ls f (l:ls) = l : f ls f [] = []
glutamate/tnutils
UnTextBar.hs
bsd-3-clause
218
0
8
52
122
63
59
10
1
-- | Represent do\/don't, is\/isn't, with\/without flags with 'Choice'. -- -- <https://existentialtype.wordpress.com/2011/03/15/boolean-blindness/ Boolean blindness> -- refers to the problem that boolean literals on their own aren't very -- informative. In any given context, what does 'True' mean? What does 'False' -- mean? Instead of passing arguments of type 'Bool' to functions, consider -- using 'Choice'. -- -- 'Choice' is the type of labeled booleans. Use it as follows: -- -- @ -- {-\# LANGUAGE OverloadedLabels \#-} -- -- import Data.Choice (Choice, pattern Do, pattern Don't) -- -- -- Blocking read: block until N bytes available. -- -- Non-blocking: return as many bytes as are available. -- readBytes :: Handle -> Choice "block" -> Int -> IO ByteString -- readBytes = ... -- -- action1 = print =<< readBytes h (Don't #block) 1024 -- @ -- -- For GHC < 8.0, where overloaded labels are not available, substitute -- @(Label :: Label "block")@ for @#block@. -- -- __A comment on labels:__ why use labels? We could as well ask the user to -- define ad hoc constructors. But unlike constructors, labels are guaranteed to -- be singletons. That's exactly what we want: a label doesn't carry any runtime -- information, it's just a type annotation. Better yet, with labels, there is -- no need to ensure that constructor names are unique, nor to pollute the -- precious constructor namespace in a large module with many flags. {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TypeFamilies #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fno-warn-missing-pattern-synonym-signatures #-} #endif module Data.Choice ( Choice -- * Conversion , fromBool , toBool -- * Choice aliases , pattern Do , pattern Don't , pattern Is , pattern Isn't , pattern With , pattern Without , pattern Must , pattern Mustn't , pattern Needn't , pattern Can , pattern Can't -- * Internal -- $label-export , Label(..) ) where #if MIN_VERSION_base(4,9,0) import GHC.OverloadedLabels (IsLabel(..)) #endif import Data.Typeable (Typeable) import GHC.Generics (Generic) import GHC.TypeLits (Symbol) -- $label-export -- -- The 'Label' data type is only exported in full for compatibility with -- versions of GHC older than 8.0. -- | A synonym for 'Data.Proxy.Proxy'. data Label (a :: Symbol) = Label deriving (Eq, Ord, Show) #if MIN_VERSION_base(4,10,0) instance x ~ x' => IsLabel x (Label x') where fromLabel = Label #elif MIN_VERSION_base(4,9,0) instance x ~ x' => IsLabel x (Label x') where fromLabel _ = Label #endif -- | A labeled boolean choice. data Choice (a :: Symbol) = Off {-# UNPACK #-} !(Label a) | On {-# UNPACK #-} !(Label a) deriving (Eq, Ord, Generic, Typeable) instance Show (Choice a) where show x = "fromBool " ++ show (toBool x) instance Enum (Choice a) where toEnum 0 = Off Label toEnum 1 = On Label toEnum _ = error "Prelude.Enum.Choice.toEnum: bad argument" fromEnum (Off _) = 0 fromEnum (On _) = 1 instance Bounded (Choice a) where minBound = Off Label maxBound = On Label -- | Alias for 'True', e.g. @Do #block@. pattern Do x = On x -- | Alias for 'False', e.g. @Don't #block@. pattern Don't x = Off x -- | Alias for 'True', e.g. @Is #ordered@. pattern Is x = On x -- | Alias for 'False', e.g. @Isn't #ordered@. pattern Isn't x = Off x -- | Alias for 'True', e.g. @With #ownDirectory@. pattern With x = On x -- | Alias for 'False', e.g. @Without #ownDirectory@. pattern Without x = Off x -- | Alias for 'True', e.g. @Must #succeed@. pattern Must x = On x -- | Alias for 'False', e.g. @Mustn't #succeed@. pattern Mustn't x = Off x -- | Alias for 'False', e.g. @Needn't #succeed@. pattern Needn't x = Off x -- | Alias for 'True', e.g. @Can #fail@. pattern Can x = On x -- | Alias for 'False', e.g. @Can't #fail@. pattern Can't x = Off x toBool :: Choice a -> Bool toBool (Off _) = False toBool (On _) = True fromBool :: Bool -> Choice a fromBool False = Off Label fromBool True = On Label
mboes/choice
src/Data/Choice.hs
bsd-3-clause
4,193
0
9
790
676
379
297
61
1
module Tests.Frenetic.Slices.TestVerification where import Frenetic.NetCore.Semantics import Test.Framework import Test.Framework.TH import Test.Framework.Providers.QuickCheck2 import Test.HUnit import Test.Framework.Providers.HUnit import Frenetic.Pattern import Frenetic.NetCore import Frenetic.NetCore.Short import Frenetic.Slices.Slice import Frenetic.Slices.Verification import qualified Data.Set as Set import qualified Data.Map as Map sliceVerificationTests = $(testGroupGenerator) s1 = Slice (Set.fromList [ Loc 1 0 , Loc 1 1 , Loc 2 0 , Loc 3 0 , Loc 4 0 , Loc 5 0 ]) (Map.singleton (Loc 6 0) Any) (Map.singleton (Loc 7 0) Any) s2 = Slice (Set.fromList [ Loc 10 0 , Loc 10 1 , Loc 20 0 , Loc 30 0 , Loc 40 0 , Loc 50 0 ]) (Map.singleton (Loc 60 0) Any) (Map.singleton (Loc 70 0) Any) s3 = Slice (Set.singleton (Loc 1 0)) Map.empty Map.empty s4 = Slice Set.empty (Map.singleton (Loc 6 0) Any) Map.empty s5 = Slice Set.empty Map.empty (Map.singleton (Loc 7 0) Any) case_testSeparated = do False @=? separated s1 s1 True @=? separated s1 s2 False @=? separated s1 s3 False @=? separated s1 s4 False @=? separated s1 s5 case_testDisjoint = do False @=? edgeDisjoint s1 s1 True @=? edgeDisjoint s1 s2 False @=? edgeDisjoint s1 s3 True @=? edgeDisjoint s1 s4 True @=? edgeDisjoint s1 s5
frenetic-lang/netcore-1.0
testsuite/Tests/Frenetic/Slices/TestVerification.hs
bsd-3-clause
1,610
0
9
521
535
275
260
-1
-1
import Common.Numbers.Primes (primes') import Common.Numbers.Numbers (powMod) check :: Int -> Int -> Bool check _ 2 = False check _ 5 = False check n p = powMod 10 (gcd n (p-1)) p == 1 && ((sum0 xs) * q `rem` p + sum0 (take r xs)) `rem` p == 0 where get xs = 1 : takeWhile (/= 1) (tail xs) xs = get $ iterate (\x -> x * 10 `rem` p) 1 (q, r) = n `quotRem` length xs sum0 = foldr (\x y -> (x+y) `rem` p) 0 main = print $ sum $ take 40 $ filter (check $ 10^9) primes'
foreverbell/project-euler-solutions
src/132.hs
bsd-3-clause
489
0
13
130
291
157
134
11
1
module Homework1.Solution where --Credit card --Exercise 1 toDigits :: Integer -> [Integer] toDigits 0 = [] toDigits x | x < 0 = [] | otherwise = toDigits (x `div` 10) ++ [x `mod` 10] toDigitsRev :: Integer -> [Integer] toDigitsRev x = reverse $ toDigits x toDigitsRev' :: Integer -> [Integer] toDigitsRev' 0 = [] toDigitsRev' x | x < 0 = [] | otherwise = x `mod` 10 : toDigitsRev' (x `div` 10) --Exercise 2 doubleEveryOther :: [Integer] -> [Integer] doubleEveryOther xs = let double _ [] = [] double True (x:xs) = (x*2) : double False xs double False (x:xs) = x : double True xs in reverse $ double False (reverse xs) --Exercise 3 sumDigits :: [Integer] -> Integer sumDigits [] = 0 sumDigits (x:xs) | check == 2 = div x 10 + mod x 10 + sumDigits xs | otherwise = x + sumDigits xs where check = floor $ log (fromIntegral x) validate :: Integer -> Bool validate = (check . sumDigits . doubleEveryOther . toDigits) where check x = (mod x 10) == 0 --Hanoi tower type Peg = String type Move = (Peg,Peg) --Example: hanoi 2 "a" "b" "c" == [("a","c"), ("a","b"), ("c","b")] hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 0 _ t _ = [] hanoi height a b c = hanoi (height-1) a c b ++ moveDisk a b ++ hanoi (height-1) c b a where moveDisk from to = [(from,to)] --frameStewart :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move] --frameStewart n r = let k = n - round(sqrt(2*n+1)) + 1
gabluc/CIS194-Solutions
src/Homework1/Solution.hs
bsd-3-clause
1,579
0
11
474
600
314
286
35
3
import Data.Byteable (toBytes) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Data.Char (chr) import Data.Maybe (fromMaybe) import Crypto.Hash import Crypto.HKDF import Test.Hspec import Text.Printf hex :: BS.ByteString -> String hex = concatMap (printf "%02x") . BS.unpack convertOctets :: [Int] -> BS.ByteString convertOctets = C8.pack . map chr testCase :: (HashAlgorithm a) => a -> [Int] -- ^ ikm octets -> [Int] -- ^ salt octets -> [Int] -- ^ info octets -> Int -- ^ L -> (BS.ByteString, BS.ByteString) -- ^ (PRK, OKM) testCase alg ikm salt info l = (prk, okm) where prk = toBytes $ hkdfExtract alg (convertOctets salt) (convertOctets ikm) okm = fromMaybe BS.empty $ hkdfExpand alg prk (convertOctets info) l testCase1 :: (BS.ByteString, BS.ByteString) testCase1 = testCase SHA256 (replicate 22 0x0b) [0x00 .. 0x0c] [0xf0 .. 0xf9] 42 testCase2 :: (BS.ByteString, BS.ByteString) testCase2 = testCase SHA256 [0x00 .. 0x4f] [0x60 .. 0xaf] [0xb0 .. 0xff] 82 testCase3 :: (BS.ByteString, BS.ByteString) testCase3 = testCase SHA256 (replicate 22 0x0b) [] [] 42 testCase4 :: (BS.ByteString, BS.ByteString) testCase4 = testCase SHA1 (replicate 11 0x0b) [0x00 .. 0x0c] [0xf0 .. 0xf9] 42 testCase5 :: (BS.ByteString, BS.ByteString) testCase5 = testCase SHA1 [0x00 .. 0x4f] [0x60 .. 0xaf] [0xb0 .. 0xff] 82 testCase6 :: (BS.ByteString, BS.ByteString) testCase6 = testCase SHA1 (replicate 22 0x0b) [] [] 42 testCase7 :: (BS.ByteString, BS.ByteString) testCase7 = testCase SHA1 (replicate 22 0x0c) [] [] 42 main :: IO () main = hspec $ do describe "hkdf-export" $ do it "should work for test case 1" $ hex (fst testCase1) `shouldBe` "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5" it "should work for test case 2" $ hex (fst testCase2) `shouldBe` "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244" it "should work for test case 3" $ hex (fst testCase3) `shouldBe` "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04" it "should work for test case 4" $ hex (fst testCase4) `shouldBe` "9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243" it "should work for test case 5" $ hex (fst testCase5) `shouldBe` "8adae09a2a307059478d309b26c4115a224cfaf6" it "should work for test case 6" $ hex (fst testCase6) `shouldBe` "da8c8a73c7fa77288ec6f5e7c297786aa0d32d01" it "should work for test case 7" $ hex (fst testCase7) `shouldBe` "2adccada18779e7c2077ad2eb19d3f3e731385dd" describe "hkdf-expand" $ do it "should work for test case 1" $ hex (snd testCase1) `shouldBe` "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865" it "should work for test case 2" $ hex (snd testCase2) `shouldBe` "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87" it "should work for test case 3" $ hex (snd testCase3) `shouldBe` "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8" it "should work for test case 4" $ hex (snd testCase4) `shouldBe` "085a01ea1b10f36933068b56efa5ad81a4f14b822f5b091568a9cdd4f155fda2c22e422478d305f3f896" it "should work for test case 5" $ hex (snd testCase5) `shouldBe` "0bd770a74d1160f7c9f12cd5912a06ebff6adcae899d92191fe4305673ba2ffe8fa3f1a4e5ad79f3f334b3b202b2173c486ea37ce3d397ed034c7f9dfeb15c5e927336d0441f4c4300e2cff0d0900b52d3b4" it "should work for test case 6" $ hex (snd testCase6) `shouldBe` "0ac1af7002b3d761d1e55298da9d0506b9ae52057220a306e07b6b87e8df21d0ea00033de03984d34918" it "should work for test case 7" $ hex (snd testCase7) `shouldBe` "2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48"
j1r1k/hkdf
test/Spec.hs
bsd-3-clause
4,419
0
15
1,152
984
521
463
82
1
{-# LANGUAGE CPP #-} module Distribution.Simple.GHCJS ( configure, getInstalledPackages, getPackageDBContents, buildLib, buildExe, replLib, replExe, startInterpreter, installLib, installExe, libAbiHash, hcPkgInfo, registerPackage, componentGhcOptions, getLibDir, isDynamic, getGlobalPackageDB, runCmd ) where import Distribution.Simple.GHC.ImplInfo ( getImplInfo, ghcjsVersionImplInfo ) import qualified Distribution.Simple.GHC.Internal as Internal import Distribution.PackageDescription as PD ( PackageDescription(..), BuildInfo(..), Executable(..) , Library(..), libModules, exeModules , hcOptions, hcProfOptions, hcSharedOptions , allExtensions ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo ( InstalledPackageInfo_(..) ) import Distribution.Package ( LibraryName(..), getHSLibraryName ) import Distribution.Simple.PackageIndex ( InstalledPackageIndex ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), ComponentLocalBuildInfo(..) ) import qualified Distribution.Simple.Hpc as Hpc import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs ) import Distribution.Simple.BuildPaths import Distribution.Simple.Utils import Distribution.Simple.Program ( Program(..), ConfiguredProgram(..), ProgramConfiguration , ProgramSearchPath , rawSystemProgramConf , rawSystemProgramStdout, rawSystemProgramStdoutConf , getProgramInvocationOutput , requireProgramVersion, requireProgram , userMaybeSpecifyPath, programPath , lookupProgram, addKnownPrograms , ghcjsProgram, ghcjsPkgProgram, c2hsProgram, hsc2hsProgram , ldProgram, haddockProgram, stripProgram ) import qualified Distribution.Simple.Program.HcPkg as HcPkg import qualified Distribution.Simple.Program.Ar as Ar import qualified Distribution.Simple.Program.Ld as Ld import qualified Distribution.Simple.Program.Strip as Strip import Distribution.Simple.Program.GHC import Distribution.Simple.Setup ( toFlag, fromFlag, configCoverage, configDistPref ) import qualified Distribution.Simple.Setup as Cabal ( Flag(..) ) import Distribution.Simple.Compiler ( CompilerFlavor(..), CompilerId(..), Compiler(..) , PackageDB(..), PackageDBStack, AbiTag(..) ) import Distribution.Version ( Version(..), anyVersion, orLaterVersion ) import Distribution.System ( Platform(..) ) import Distribution.Verbosity import Distribution.Utils.NubList ( overNubListR, toNubListR ) import Distribution.Text ( display ) import Language.Haskell.Extension ( Extension(..) , KnownExtension(..)) import Control.Monad ( unless, when ) import Data.Char ( isSpace ) import qualified Data.Map as M ( fromList ) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid ( Monoid(..) ) #endif import System.Directory ( doesFileExist ) import System.FilePath ( (</>), (<.>), takeExtension, takeDirectory, replaceExtension, splitExtension ) configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration) configure verbosity hcPath hcPkgPath conf0 = do (ghcjsProg, ghcjsVersion, conf1) <- requireProgramVersion verbosity ghcjsProgram (orLaterVersion (Version [0,1] [])) (userMaybeSpecifyPath "ghcjs" hcPath conf0) Just ghcjsGhcVersion <- findGhcjsGhcVersion verbosity (programPath ghcjsProg) let implInfo = ghcjsVersionImplInfo ghcjsVersion ghcjsGhcVersion -- This is slightly tricky, we have to configure ghcjs first, then we use the -- location of ghcjs to help find ghcjs-pkg in the case that the user did not -- specify the location of ghc-pkg directly: (ghcjsPkgProg, ghcjsPkgVersion, conf2) <- requireProgramVersion verbosity ghcjsPkgProgram { programFindLocation = guessGhcjsPkgFromGhcjsPath ghcjsProg } anyVersion (userMaybeSpecifyPath "ghcjs-pkg" hcPkgPath conf1) Just ghcjsPkgGhcjsVersion <- findGhcjsPkgGhcjsVersion verbosity (programPath ghcjsPkgProg) when (ghcjsVersion /= ghcjsPkgGhcjsVersion) $ die $ "Version mismatch between ghcjs and ghcjs-pkg: " ++ programPath ghcjsProg ++ " is version " ++ display ghcjsVersion ++ " " ++ programPath ghcjsPkgProg ++ " is version " ++ display ghcjsPkgGhcjsVersion when (ghcjsGhcVersion /= ghcjsPkgVersion) $ die $ "Version mismatch between ghcjs and ghcjs-pkg: " ++ programPath ghcjsProg ++ " was built with GHC version " ++ display ghcjsGhcVersion ++ " " ++ programPath ghcjsPkgProg ++ " was built with GHC version " ++ display ghcjsPkgVersion -- be sure to use our versions of hsc2hs, c2hs, haddock and ghc let hsc2hsProgram' = hsc2hsProgram { programFindLocation = guessHsc2hsFromGhcjsPath ghcjsProg } c2hsProgram' = c2hsProgram { programFindLocation = guessC2hsFromGhcjsPath ghcjsProg } haddockProgram' = haddockProgram { programFindLocation = guessHaddockFromGhcjsPath ghcjsProg } conf3 = addKnownPrograms [ hsc2hsProgram', c2hsProgram', haddockProgram' ] conf2 languages <- Internal.getLanguages verbosity implInfo ghcjsProg extensions <- Internal.getExtensions verbosity implInfo ghcjsProg ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcjsProg let ghcInfoMap = M.fromList ghcInfo let comp = Compiler { compilerId = CompilerId GHCJS ghcjsVersion, compilerAbiTag = AbiTag $ "ghc" ++ intercalate "_" (map show . versionBranch $ ghcjsGhcVersion), compilerCompat = [CompilerId GHC ghcjsGhcVersion], compilerLanguages = languages, compilerExtensions = extensions, compilerProperties = ghcInfoMap } compPlatform = Internal.targetPlatform ghcInfo -- configure gcc and ld let conf4 = if ghcjsNativeToo comp then Internal.configureToolchain implInfo ghcjsProg ghcInfoMap conf3 else conf3 return (comp, compPlatform, conf4) ghcjsNativeToo :: Compiler -> Bool ghcjsNativeToo = Internal.ghcLookupProperty "Native Too" guessGhcjsPkgFromGhcjsPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessGhcjsPkgFromGhcjsPath = guessToolFromGhcjsPath ghcjsPkgProgram guessHsc2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessHsc2hsFromGhcjsPath = guessToolFromGhcjsPath hsc2hsProgram guessC2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessC2hsFromGhcjsPath = guessToolFromGhcjsPath c2hsProgram guessHaddockFromGhcjsPath :: ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessHaddockFromGhcjsPath = guessToolFromGhcjsPath haddockProgram guessToolFromGhcjsPath :: Program -> ConfiguredProgram -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath) guessToolFromGhcjsPath tool ghcjsProg verbosity searchpath = do let toolname = programName tool path = programPath ghcjsProg dir = takeDirectory path versionSuffix = takeVersionSuffix (dropExeExtension path) guessNormal = dir </> toolname <.> exeExtension guessGhcjsVersioned = dir </> (toolname ++ "-ghcjs" ++ versionSuffix) <.> exeExtension guessGhcjs = dir </> (toolname ++ "-ghcjs") <.> exeExtension guessVersioned = dir </> (toolname ++ versionSuffix) <.> exeExtension guesses | null versionSuffix = [guessGhcjs, guessNormal] | otherwise = [guessGhcjsVersioned, guessGhcjs, guessVersioned, guessNormal] info verbosity $ "looking for tool " ++ toolname ++ " near compiler in " ++ dir exists <- mapM doesFileExist guesses case [ file | (file, True) <- zip guesses exists ] of -- If we can't find it near ghc, fall back to the usual -- method. [] -> programFindLocation tool verbosity searchpath (fp:_) -> do info verbosity $ "found " ++ toolname ++ " in " ++ fp return (Just fp) where takeVersionSuffix :: FilePath -> String takeVersionSuffix = reverse . takeWhile (`elem ` "0123456789.-") . reverse dropExeExtension :: FilePath -> FilePath dropExeExtension filepath = case splitExtension filepath of (filepath', extension) | extension == exeExtension -> filepath' | otherwise -> filepath -- | Given a single package DB, return all installed packages. getPackageDBContents :: Verbosity -> PackageDB -> ProgramConfiguration -> IO InstalledPackageIndex getPackageDBContents verbosity packagedb conf = do pkgss <- getInstalledPackages' verbosity [packagedb] conf toPackageIndex verbosity pkgss conf -- | Given a package DB stack, return all installed packages. getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO InstalledPackageIndex getInstalledPackages verbosity packagedbs conf = do checkPackageDbEnvVar checkPackageDbStack packagedbs pkgss <- getInstalledPackages' verbosity packagedbs conf index <- toPackageIndex verbosity pkgss conf return $! index toPackageIndex :: Verbosity -> [(PackageDB, [InstalledPackageInfo])] -> ProgramConfiguration -> IO InstalledPackageIndex toPackageIndex verbosity pkgss conf = do -- On Windows, various fields have $topdir/foo rather than full -- paths. We need to substitute the right value in so that when -- we, for example, call gcc, we have proper paths to give it. topDir <- getLibDir' verbosity ghcjsProg let indices = [ PackageIndex.fromList (map (Internal.substTopDir topDir) pkgs) | (_, pkgs) <- pkgss ] return $! (mconcat indices) where Just ghcjsProg = lookupProgram ghcjsProgram conf checkPackageDbEnvVar :: IO () checkPackageDbEnvVar = Internal.checkPackageDbEnvVar "GHCJS" "GHCJS_PACKAGE_PATH" checkPackageDbStack :: PackageDBStack -> IO () checkPackageDbStack (GlobalPackageDB:rest) | GlobalPackageDB `notElem` rest = return () checkPackageDbStack rest | GlobalPackageDB `notElem` rest = die $ "With current ghc versions the global package db is always used " ++ "and must be listed first. This ghc limitation may be lifted in " ++ "future, see http://hackage.haskell.org/trac/ghc/ticket/5977" checkPackageDbStack _ = die $ "If the global package db is specified, it must be " ++ "specified first and cannot be specified multiple times" getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration -> IO [(PackageDB, [InstalledPackageInfo])] getInstalledPackages' verbosity packagedbs conf = sequence [ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb return (packagedb, pkgs) | packagedb <- packagedbs ] getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath getLibDir verbosity lbi = (reverse . dropWhile isSpace . reverse) `fmap` rawSystemProgramStdoutConf verbosity ghcjsProgram (withPrograms lbi) ["--print-libdir"] getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath getLibDir' verbosity ghcjsProg = (reverse . dropWhile isSpace . reverse) `fmap` rawSystemProgramStdout verbosity ghcjsProg ["--print-libdir"] -- | Return the 'FilePath' to the global GHC package database. getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath getGlobalPackageDB verbosity ghcjsProg = (reverse . dropWhile isSpace . reverse) `fmap` rawSystemProgramStdout verbosity ghcjsProg ["--print-global-package-db"] toJSLibName :: String -> String toJSLibName lib | takeExtension lib `elem` [".dll",".dylib",".so"] = replaceExtension lib "js_so" | takeExtension lib == ".a" = replaceExtension lib "js_a" | otherwise = lib <.> "js_a" buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib = buildOrReplLib False replLib = buildOrReplLib True buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildOrReplLib forRepl verbosity numJobs _pkg_descr lbi lib clbi = do let libName@(LibraryName cname) = componentLibraryName clbi libTargetDir = buildDir lbi whenVanillaLib forceVanilla = when (not forRepl && (forceVanilla || withVanillaLib lbi)) whenProfLib = when (not forRepl && withProfLib lbi) whenSharedLib forceShared = when (not forRepl && (forceShared || withSharedLib lbi)) whenGHCiLib = when (not forRepl && withGHCiLib lbi && withVanillaLib lbi) ifReplLib = when forRepl comp = compiler lbi implInfo = getImplInfo comp hole_insts = map (\(k,(p,n)) -> (k,(InstalledPackageInfo.packageKey p,n))) (instantiatedWith lbi) nativeToo = ghcjsNativeToo comp (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi) let runGhcjsProg = runGHC verbosity ghcjsProg comp libBi = libBuildInfo lib isGhcjsDynamic = isDynamic comp dynamicTooSupported = supportsDynamicToo comp doingTH = EnableExtension TemplateHaskell `elem` allExtensions libBi forceVanillaLib = doingTH && not isGhcjsDynamic forceSharedLib = doingTH && isGhcjsDynamic -- TH always needs default libs, even when building for profiling -- Determine if program coverage should be enabled and if so, what -- '-hpcdir' should be. let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi distPref = fromFlag $ configDistPref $ configFlags lbi hpcdir way | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way cname | otherwise = mempty createDirectoryIfMissingVerbose verbosity True libTargetDir -- TODO: do we need to put hs-boot files into place for mutually recursive -- modules? let cObjs = map (`replaceExtension` objExtension) (cSources libBi) jsSrcs = jsSources libBi baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir linkJsLibOpts = mempty { ghcOptExtra = toNubListR $ [ "-link-js-lib" , getHSLibraryName libName , "-js-lib-outputdir", libTargetDir ] ++ concatMap (\x -> ["-js-lib-src",x]) jsSrcs } vanillaOptsNoJsLib = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptNumJobs = numJobs, ghcOptSigOf = hole_insts, ghcOptInputModules = toNubListR $ libModules lib, ghcOptHPCDir = hpcdir Hpc.Vanilla } vanillaOpts = vanillaOptsNoJsLib `mappend` linkJsLibOpts profOpts = adjustExts "p_hi" "p_o" vanillaOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptExtra = toNubListR $ ghcjsProfOptions libBi, ghcOptHPCDir = hpcdir Hpc.Prof } sharedOpts = adjustExts "dyn_hi" "dyn_o" vanillaOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptExtra = toNubListR $ ghcjsSharedOptions libBi, ghcOptHPCDir = hpcdir Hpc.Dyn } linkerOpts = mempty { ghcOptLinkOptions = toNubListR $ PD.ldOptions libBi, ghcOptLinkLibs = toNubListR $ extraLibs libBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi, ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi, ghcOptInputFiles = toNubListR $ [libTargetDir </> x | x <- cObjs] ++ jsSrcs } replOpts = vanillaOptsNoJsLib { ghcOptExtra = overNubListR Internal.filterGhciFlags (ghcOptExtra vanillaOpts), ghcOptNumJobs = mempty } `mappend` linkerOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } vanillaSharedOpts = vanillaOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticAndDynamic, ghcOptDynHiSuffix = toFlag "dyn_hi", ghcOptDynObjSuffix = toFlag "dyn_o", ghcOptHPCDir = hpcdir Hpc.Dyn } unless (forRepl || (null (libModules lib) && null jsSrcs && null cObjs)) $ do let vanilla = whenVanillaLib forceVanillaLib (runGhcjsProg vanillaOpts) shared = whenSharedLib forceSharedLib (runGhcjsProg sharedOpts) useDynToo = dynamicTooSupported && (forceVanillaLib || withVanillaLib lbi) && (forceSharedLib || withSharedLib lbi) && null (ghcjsSharedOptions libBi) if useDynToo then do runGhcjsProg vanillaSharedOpts case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of (Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do -- When the vanilla and shared library builds are done -- in one pass, only one set of HPC module interfaces -- are generated. This set should suffice for both -- static and dynamically linked executables. We copy -- the modules interfaces so they are available under -- both ways. copyDirectoryRecursive verbosity dynDir vanillaDir _ -> return () else if isGhcjsDynamic then do shared; vanilla else do vanilla; shared whenProfLib (runGhcjsProg profOpts) -- build any C sources unless (null (cSources libBi) || not nativeToo) $ do info verbosity "Building C Sources..." sequence_ [ do let vanillaCcOpts = (Internal.componentCcGhcOptions verbosity implInfo lbi libBi clbi libTargetDir filename) profCcOpts = vanillaCcOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptObjSuffix = toFlag "p_o" } sharedCcOpts = vanillaCcOpts `mappend` mempty { ghcOptFPic = toFlag True, ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptObjSuffix = toFlag "dyn_o" } odir = fromFlag (ghcOptObjDir vanillaCcOpts) createDirectoryIfMissingVerbose verbosity True odir runGhcjsProg vanillaCcOpts whenSharedLib forceSharedLib (runGhcjsProg sharedCcOpts) whenProfLib (runGhcjsProg profCcOpts) | filename <- cSources libBi] -- TODO: problem here is we need the .c files built first, so we can load them -- with ghci, but .c files can depend on .h files generated by ghc by ffi -- exports. unless (null (libModules lib)) $ ifReplLib (runGhcjsProg replOpts) -- link: when (nativeToo && not forRepl) $ do info verbosity "Linking..." let cProfObjs = map (`replaceExtension` ("p_" ++ objExtension)) (cSources libBi) cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension)) (cSources libBi) cid = compilerId (compiler lbi) vanillaLibFilePath = libTargetDir </> mkLibName libName profileLibFilePath = libTargetDir </> mkProfLibName libName sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName ghciLibFilePath = libTargetDir </> Internal.mkGHCiLibName libName hObjs <- Internal.getHaskellObjects implInfo lib lbi libTargetDir objExtension True hProfObjs <- if (withProfLib lbi) then Internal.getHaskellObjects implInfo lib lbi libTargetDir ("p_" ++ objExtension) True else return [] hSharedObjs <- if (withSharedLib lbi) then Internal.getHaskellObjects implInfo lib lbi libTargetDir ("dyn_" ++ objExtension) False else return [] unless (null hObjs && null cObjs) $ do let staticObjectFiles = hObjs ++ map (libTargetDir </>) cObjs profObjectFiles = hProfObjs ++ map (libTargetDir </>) cProfObjs ghciObjFiles = hObjs ++ map (libTargetDir </>) cObjs dynamicObjectFiles = hSharedObjs ++ map (libTargetDir </>) cSharedObjs -- After the relocation lib is created we invoke ghc -shared -- with the dependencies spelled out as -package arguments -- and ghc invokes the linker with the proper library paths ghcSharedLinkArgs = mempty { ghcOptShared = toFlag True, ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptInputFiles = toNubListR dynamicObjectFiles, ghcOptOutputFile = toFlag sharedLibFilePath, ghcOptNoAutoLinkPackages = toFlag True, ghcOptPackageDBs = withPackageDB lbi, ghcOptPackages = toNubListR $ Internal.mkGhcOptPackages clbi, ghcOptLinkLibs = toNubListR $ extraLibs libBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi } whenVanillaLib False $ do Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles whenProfLib $ do Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles whenGHCiLib $ do (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi) Ld.combineObjectFiles verbosity ldProg ghciLibFilePath ghciObjFiles whenSharedLib False $ runGhcjsProg ghcSharedLinkArgs -- | Start a REPL without loading any source files. startInterpreter :: Verbosity -> ProgramConfiguration -> Compiler -> PackageDBStack -> IO () startInterpreter verbosity conf comp packageDBs = do let replOpts = mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptPackageDBs = packageDBs } checkPackageDbStack packageDBs (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram conf runGHC verbosity ghcjsProg comp replOpts buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe = buildOrReplExe False replExe = buildOrReplExe True buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildOrReplExe forRepl verbosity numJobs _pkg_descr lbi exe@Executable { exeName = exeName', modulePath = modPath } clbi = do (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi) let comp = compiler lbi implInfo = getImplInfo comp runGhcjsProg = runGHC verbosity ghcjsProg comp exeBi = buildInfo exe -- exeNameReal, the name that GHC really uses (with .exe on Windows) let exeNameReal = exeName' <.> (if takeExtension exeName' /= ('.':exeExtension) then exeExtension else "") let targetDir = (buildDir lbi) </> exeName' let exeDir = targetDir </> (exeName' ++ "-tmp") createDirectoryIfMissingVerbose verbosity True targetDir createDirectoryIfMissingVerbose verbosity True exeDir -- TODO: do we need to put hs-boot files into place for mutually recursive -- modules? FIX: what about exeName.hi-boot? -- Determine if program coverage should be enabled and if so, what -- '-hpcdir' should be. let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi distPref = fromFlag $ configDistPref $ configFlags lbi hpcdir way | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName' | otherwise = mempty -- build executables srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath let isGhcjsDynamic = isDynamic comp dynamicTooSupported = supportsDynamicToo comp buildRunner = case clbi of ExeComponentLocalBuildInfo {} -> False _ -> True isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"] jsSrcs = jsSources exeBi cSrcs = cSources exeBi ++ [srcMainFile | not isHaskellMain] cObjs = map (`replaceExtension` objExtension) cSrcs nativeToo = ghcjsNativeToo comp baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir) `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptInputFiles = toNubListR $ [ srcMainFile | isHaskellMain], ghcOptInputModules = toNubListR $ [ m | not isHaskellMain, m <- exeModules exe], ghcOptExtra = if buildRunner then toNubListR ["-build-runner"] else mempty } staticOpts = baseOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticOnly, ghcOptHPCDir = hpcdir Hpc.Vanilla } profOpts = adjustExts "p_hi" "p_o" baseOpts `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptExtra = toNubListR $ ghcjsProfOptions exeBi, ghcOptHPCDir = hpcdir Hpc.Prof } dynOpts = adjustExts "dyn_hi" "dyn_o" baseOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptExtra = toNubListR $ ghcjsSharedOptions exeBi, ghcOptHPCDir = hpcdir Hpc.Dyn } dynTooOpts = adjustExts "dyn_hi" "dyn_o" staticOpts `mappend` mempty { ghcOptDynLinkMode = toFlag GhcStaticAndDynamic, ghcOptHPCDir = hpcdir Hpc.Dyn } linkerOpts = mempty { ghcOptLinkOptions = toNubListR $ PD.ldOptions exeBi, ghcOptLinkLibs = toNubListR $ extraLibs exeBi, ghcOptLinkLibPath = toNubListR $ extraLibDirs exeBi, ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi, ghcOptInputFiles = toNubListR $ [exeDir </> x | x <- cObjs] ++ jsSrcs } replOpts = baseOpts { ghcOptExtra = overNubListR Internal.filterGhciFlags (ghcOptExtra baseOpts) } -- For a normal compile we do separate invocations of ghc for -- compiling as for linking. But for repl we have to do just -- the one invocation, so that one has to include all the -- linker stuff too, like -l flags and any .o files from C -- files etc. `mappend` linkerOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } commonOpts | withProfExe lbi = profOpts | withDynExe lbi = dynOpts | otherwise = staticOpts compileOpts | useDynToo = dynTooOpts | otherwise = commonOpts withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi) -- For building exe's that use TH with -prof or -dynamic we actually have -- to build twice, once without -prof/-dynamic and then again with -- -prof/-dynamic. This is because the code that TH needs to run at -- compile time needs to be the vanilla ABI so it can be loaded up and run -- by the compiler. -- With dynamic-by-default GHC the TH object files loaded at compile-time -- need to be .dyn_o instead of .o. doingTH = EnableExtension TemplateHaskell `elem` allExtensions exeBi -- Should we use -dynamic-too instead of compiling twice? useDynToo = dynamicTooSupported && isGhcjsDynamic && doingTH && withStaticExe && null (ghcjsSharedOptions exeBi) compileTHOpts | isGhcjsDynamic = dynOpts | otherwise = staticOpts compileForTH | forRepl = False | useDynToo = False | isGhcjsDynamic = doingTH && (withProfExe lbi || withStaticExe) | otherwise = doingTH && (withProfExe lbi || withDynExe lbi) linkOpts = commonOpts `mappend` linkerOpts `mappend` mempty { ghcOptLinkNoHsMain = toFlag (not isHaskellMain) } -- Build static/dynamic object files for TH, if needed. when compileForTH $ runGhcjsProg compileTHOpts { ghcOptNoLink = toFlag True , ghcOptNumJobs = numJobs } unless forRepl $ runGhcjsProg compileOpts { ghcOptNoLink = toFlag True , ghcOptNumJobs = numJobs } -- build any C sources unless (null cSrcs || not nativeToo) $ do info verbosity "Building C Sources..." sequence_ [ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi clbi exeDir filename) `mappend` mempty { ghcOptDynLinkMode = toFlag (if withDynExe lbi then GhcDynamicOnly else GhcStaticOnly), ghcOptProfilingMode = toFlag (withProfExe lbi) } odir = fromFlag (ghcOptObjDir opts) createDirectoryIfMissingVerbose verbosity True odir runGhcjsProg opts | filename <- cSrcs ] -- TODO: problem here is we need the .c files built first, so we can load them -- with ghci, but .c files can depend on .h files generated by ghc by ffi -- exports. when forRepl $ runGhcjsProg replOpts -- link: unless forRepl $ do info verbosity "Linking..." runGhcjsProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) } -- |Install for ghc, .hi, .a and, if --with-ghci given, .o installLib :: Verbosity -> LocalBuildInfo -> FilePath -- ^install location -> FilePath -- ^install location for dynamic libraries -> FilePath -- ^Build location -> PackageDescription -> Library -> ComponentLocalBuildInfo -> IO () installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do whenVanilla $ copyModuleFiles "js_hi" whenProf $ copyModuleFiles "js_p_hi" whenShared $ copyModuleFiles "js_dyn_hi" whenVanilla $ installOrdinary builtDir targetDir $ toJSLibName vanillaLibName whenProf $ installOrdinary builtDir targetDir $ toJSLibName profileLibName whenShared $ installShared builtDir dynlibTargetDir $ toJSLibName sharedLibName when (ghcjsNativeToo $ compiler lbi) $ do -- copy .hi files over: whenVanilla $ copyModuleFiles "hi" whenProf $ copyModuleFiles "p_hi" whenShared $ copyModuleFiles "dyn_hi" -- copy the built library files over: whenVanilla $ installOrdinary builtDir targetDir vanillaLibName whenProf $ installOrdinary builtDir targetDir profileLibName whenGHCi $ installOrdinary builtDir targetDir ghciLibName whenShared $ installShared builtDir dynlibTargetDir sharedLibName where install isShared srcDir dstDir name = do let src = srcDir </> name dst = dstDir </> name createDirectoryIfMissingVerbose verbosity True dstDir if isShared then do when (stripLibs lbi) $ Strip.stripLib verbosity (hostPlatform lbi) (withPrograms lbi) src installExecutableFile verbosity src dst else installOrdinaryFile verbosity src dst installOrdinary = install False installShared = install True copyModuleFiles ext = findModuleFiles [builtDir] [ext] (libModules lib) >>= installOrdinaryFiles verbosity targetDir cid = compilerId (compiler lbi) libName = componentLibraryName clbi vanillaLibName = mkLibName libName profileLibName = mkProfLibName libName ghciLibName = Internal.mkGHCiLibName libName sharedLibName = (mkSharedLibName cid) libName hasLib = not $ null (libModules lib) && null (cSources (libBuildInfo lib)) whenVanilla = when (hasLib && withVanillaLib lbi) whenProf = when (hasLib && withProfLib lbi) whenGHCi = when (hasLib && withGHCiLib lbi) whenShared = when (hasLib && withSharedLib lbi) installExe :: Verbosity -> LocalBuildInfo -> InstallDirs FilePath -- ^Where to copy the files to -> FilePath -- ^Build location -> (FilePath, FilePath) -- ^Executable (prefix,suffix) -> PackageDescription -> Executable -> IO () installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do let binDir = bindir installDirs createDirectoryIfMissingVerbose verbosity True binDir let exeFileName = exeName exe fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix installBinary dest = do rawSystemProgramConf verbosity ghcjsProgram (withPrograms lbi) $ [ "--install-executable" , buildPref </> exeName exe </> exeFileName , "-o", dest ] ++ case (stripExes lbi, lookupProgram stripProgram $ withPrograms lbi) of (True, Just strip) -> ["-strip-program", programPath strip] _ -> [] installBinary (binDir </> fixedExeBaseName) libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO String libAbiHash verbosity _pkg_descr lbi lib clbi = do let libBi = libBuildInfo lib comp = compiler lbi vanillaArgs = (componentGhcOptions verbosity lbi libBi clbi (buildDir lbi)) `mappend` mempty { ghcOptMode = toFlag GhcModeAbiHash, ghcOptInputModules = toNubListR $ exposedModules lib } profArgs = adjustExts "js_p_hi" "js_p_o" vanillaArgs `mappend` mempty { ghcOptProfilingMode = toFlag True, ghcOptExtra = toNubListR (ghcjsProfOptions libBi) } ghcArgs = if withVanillaLib lbi then vanillaArgs else if withProfLib lbi then profArgs else error "libAbiHash: Can't find an enabled library way" -- (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi) getProgramInvocationOutput verbosity (ghcInvocation ghcjsProg comp ghcArgs) adjustExts :: String -> String -> GhcOptions -> GhcOptions adjustExts hiSuf objSuf opts = opts `mappend` mempty { ghcOptHiSuffix = toFlag hiSuf, ghcOptObjSuffix = toFlag objSuf } registerPackage :: Verbosity -> InstalledPackageInfo -> PackageDescription -> LocalBuildInfo -> Bool -> PackageDBStack -> IO () registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs = HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity packageDbs (Right installedPkgInfo) componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions verbosity lbi bi clbi odir = let opts = Internal.componentGhcOptions verbosity lbi bi clbi odir in opts { ghcOptExtra = ghcOptExtra opts `mappend` toNubListR (hcOptions GHCJS bi) } ghcjsProfOptions :: BuildInfo -> [String] ghcjsProfOptions bi = hcProfOptions GHC bi `mappend` hcProfOptions GHCJS bi ghcjsSharedOptions :: BuildInfo -> [String] ghcjsSharedOptions bi = hcSharedOptions GHC bi `mappend` hcSharedOptions GHCJS bi isDynamic :: Compiler -> Bool isDynamic = Internal.ghcLookupProperty "GHC Dynamic" supportsDynamicToo :: Compiler -> Bool supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too" findGhcjsGhcVersion :: Verbosity -> FilePath -> IO (Maybe Version) findGhcjsGhcVersion verbosity pgm = findProgramVersion "--numeric-ghc-version" id verbosity pgm findGhcjsPkgGhcjsVersion :: Verbosity -> FilePath -> IO (Maybe Version) findGhcjsPkgGhcjsVersion verbosity pgm = findProgramVersion "--numeric-ghcjs-version" id verbosity pgm -- ----------------------------------------------------------------------------- -- Registering hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = ghcjsPkgProg , HcPkg.noPkgDbStack = False , HcPkg.noVerboseFlag = False , HcPkg.flagPackageConf = False , HcPkg.useSingleFileDb = v < [7,9] , HcPkg.multInstEnabled = False , HcPkg.supportsView = False } where v = versionBranch ver Just ghcjsPkgProg = lookupProgram ghcjsPkgProgram conf Just ver = programVersion ghcjsPkgProg -- | Get the JavaScript file name and command and arguments to run a -- program compiled by GHCJS -- the exe should be the base program name without exe extension runCmd :: ProgramConfiguration -> FilePath -> (FilePath, FilePath, [String]) runCmd conf exe = ( script , programPath ghcjsProg , programDefaultArgs ghcjsProg ++ programOverrideArgs ghcjsProg ++ ["--run"] ) where script = exe <.> "jsexe" </> "all" <.> "js" Just ghcjsProg = lookupProgram ghcjsProgram conf
fugyk/cabal
Cabal/Distribution/Simple/GHCJS.hs
bsd-3-clause
40,909
0
23
13,168
8,053
4,206
3,847
703
6
import qualified Data.PQueue.Prio.Min as PQ import qualified Data.HashSet as Set import qualified Data.HashMap.Strict as Map import Data.Hashable (Hashable) import Data.List (foldl') import Data.Maybe (fromJust) -- A* search: Finds the shortest path from a start node to a goal node using a heuristic function. astarSearch :: (Eq a, Hashable a) => a -- startNode: the node to start the search from -> (a -> Bool) -- isGoalNode: a function to test if a node is the goal node -> (a -> [(a, Int)]) -- nextNodeFn: a function which calculates the next nodes for a current node -- along with the costs of moving from the current node to the next nodes -> (a -> Int) -- heuristic: a function which calculates the (approximate) cost of moving -- from a node to the nearest goal node -> Maybe (Int, [a]) -- result: Nothing is no path is found else -- Just (path cost, path as a list of nodes) astarSearch startNode isGoalNode nextNodeFn heuristic = astar (PQ.singleton (heuristic startNode) (startNode, 0)) Set.empty (Map.singleton startNode 0) Map.empty where -- pq: open set, seen: closed set, tracks: tracks of states astar pq seen gscore tracks -- If open set is empty then search has failed. Return Nothing | PQ.null pq = Nothing -- If goal node reached then construct the path from the tracks and node | isGoalNode node = Just (gcost, findPath tracks node) -- If node has already been seen then discard it and continue | Set.member node seen = astar pq' seen gscore tracks -- Else expand the node and continue | otherwise = astar pq'' seen' gscore' tracks' where -- Find the node with min f-cost (node, gcost) = snd . PQ.findMin $ pq -- Delete the node from open set pq' = PQ.deleteMin pq -- Add the node to the closed set seen' = Set.insert node seen -- Find the successors (with their g and h costs) of the node -- which have not been seen yet successors = filter (\(s, g, _) -> not (Set.member s seen') && (not (s `Map.member` gscore) || g < (fromJust . Map.lookup s $ gscore))) $ successorsAndCosts node gcost -- Insert the successors in the open set pq'' = foldl' (\q (s, g, h) -> PQ.insert (g + h) (s, g) q) pq' successors gscore' = foldl' (\m (s, g, _) -> Map.insert s g m) gscore successors -- Insert the tracks of the successors tracks' = foldl' (\m (s, _, _) -> Map.insert s node m) tracks successors -- Finds the successors of a given node and their costs successorsAndCosts node gcost = map (\(s, g) -> (s, gcost + g, heuristic s)) . nextNodeFn $ node -- Constructs the path from the tracks and last node findPath tracks node = if Map.member node tracks then findPath tracks (fromJust . Map.lookup node $ tracks) ++ [node] else [node]
trxeste/wrk
haskell/TrabalhoIA/docs/astar_documented.hs
bsd-3-clause
3,086
0
20
919
692
383
309
38
2
module System.Console.Types where data Option a => OptionsList a = OptionList { aboveScreen :: [a] , above :: [a] , current :: a , below :: [a] , belowScreen :: [a] } deriving Eq data Option o => TogglableOption o = TogglableOption { getOption :: o , getState :: Bool } deriving Eq class Eq a => Option a where showOption :: a -> String toggle :: a -> a instance Option String where showOption = id toggle = id instance Option a => Option (TogglableOption a) where showOption togglable = checkBox (getState togglable) ++ showOption (getOption togglable) where checkBox True = " [x] " checkBox False = " [ ] " toggle option = option { getState = not (getState option) } isChosen :: Option o => TogglableOption o -> Bool isChosen (TogglableOption _ True) = True isChosen (TogglableOption _ False) = False toOptionList :: Option option => [option] -> Int -> OptionsList option toOptionList [] _ = undefined -- FIXME: handle this case properly. toOptionList options@(headOption:tailOptions) terminalHeight = OptionList [] [] headOption (take belowLength tailOptions) (drop belowLength tailOptions) where belowLength | length options <= terminalHeight = length options - 1 | otherwise = terminalHeight - 1 fromOptionList :: Option o => OptionsList (TogglableOption o) -> [TogglableOption o] fromOptionList (OptionList aboveScreen above current below belowScreen) = aboveScreen ++ above ++ [current] ++ below ++ belowScreen
shockone/interactive-select
src/System/Console/Types.hs
bsd-3-clause
1,855
0
11
663
500
261
239
32
1
module Repl where import Control.Monad import Eval import Parser import System.IO import Environment flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine evalString :: Env -> String -> IO String evalString env expr = runIOThrows $ fmap show $ liftThrows (readExpr expr) >>= eval env evalAndPrint :: Env -> String -> IO () evalAndPrint env expr = evalString env expr >>= putStrLn until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ pred prompt action = do result <- prompt unless (pred result) $ action result >> until_ pred prompt action runOne :: String -> IO () runOne expr = nullEnv >>= flip evalAndPrint expr runREPL :: IO () runREPL = nullEnv >>= until_ (== "quit") (readPrompt "Scheme> ") . evalAndPrint
juanbono/my-scheme
src/Repl.hs
bsd-3-clause
889
0
12
211
341
168
173
22
1
{-# LANGUAGE TemplateHaskell #-} module QCommon.FileLinkT where import Control.Lens (makeLenses) import qualified Data.ByteString as B import Types makeLenses ''FileLinkT
ksaveljev/hake-2
src/QCommon/FileLinkT.hs
bsd-3-clause
196
0
6
44
36
22
14
6
0
{-# LANGUAGE FlexibleContexts #-} module Util ( values , removeUnicode , lookupWithDefault , shorten , shortenWithEllipsis , addUnique , mergeUnique , normalizePath , removeLeading , removeLeadingSlash , replaceLeading , trimL , trimR , trim , sortByAccessorDesc , shortenFileName , renderAsTree , sumMap , StringTree(STN) ) where import Data.Char import Data.Function import Data.Maybe import Data.Map as Map import Data.List as List import System.FilePath import Text.Regex.Posix values :: Map k v -> [v] values = (List.map snd) . Map.toList lookupWithDefault :: (Ord k) => v -> k -> Map k v -> v lookupWithDefault d key m = fromMaybe d (Map.lookup key m) removeUnicode :: String -> String removeUnicode xs = [ x | x <- xs, x `notElem` "\246" ] shorten :: Int -> String -> String shorten limit s | l > limit = drop (l - limit) s | otherwise = s where l = length s shortenWithEllipsis :: Int -> String -> String shortenWithEllipsis limit s | l > limit = "..." ++ (drop 3 . shorten limit) s | otherwise = s where l = length s slice :: Int -> Int -> String -> String slice start end = take (end - start + 1) . drop start addUnique :: (Eq a) => a -> [a] -> [a] addUnique x xs = if x `elem` xs then xs else x:xs mergeUnique :: (Eq a) => [a] -> [a] -> [a] mergeUnique = Prelude.foldr addUnique normalizePath :: FilePath -> FilePath normalizePath path = joinPath $ List.foldr norm [] paths where paths = splitDirectories path norm p ps = if p =~ "^\\.+$" then drop (length p) ps else p:ps removeLeadingSlash = removeLeading "/" removeLeading :: (Eq a) => [a] -> [a] -> [a] removeLeading x ys = if startsWith x ys then drop (length x) ys else ys startsWith :: (Eq a) => [a] -> [a] -> Bool startsWith x y = x == take (length x) y replaceLeading :: (Eq a) => [a] -> [a] -> [a] -> [a] replaceLeading leading replace str = if startsWith leading str then repl else str where repl = r ++ drop l str r = take l $ concat (replicate l replace) l = length leading trimR :: String -> String trimR = reverse . dropWhile isSpace . reverse trimL :: String -> String trimL = dropWhile isSpace trim :: String -> String trim = trimR . trimL shortenFileName :: Int -> String -> String -> String shortenFileName maxLen rootDir n = shortenWithEllipsis maxLen (dropPrefix n) where dropPrefix = removeLeadingSlash . removeLeading (normalizePath rootDir) sortByAccessorDesc :: (Ord b) => (a -> b) -> [a] -> [a] sortByAccessorDesc f = List.sortBy (check `on` f) where check = flip compare data StringTree = STN (String, [StringTree]) deriving (Show) instance Eq StringTree where x == y = isEqualStringTree x y isEqualStringTree :: StringTree -> StringTree -> Bool isEqualStringTree (STN (p1, cs1)) (STN (p2, cs2)) = p1 == p2 && cs1 == cs2 renderAsTree :: StringTree -> [String] renderAsTree = renderAsTree' id renderAsTree' :: (String -> String) -> StringTree -> [String] renderAsTree' f = normalizePipes . renderAsTreeRec f 0 True renderAsTreeRec :: (String -> String) -> Int -> Bool -> StringTree -> [String] renderAsTreeRec f level isLast (STN (s, cs)) = current:nextLevel where prefix 0 = "" prefix 1 = unwords [sign, ""] prefix l = unwords $ concat [(replicate (l - 1) "│"), [sign, ""]] sign = if isLast then "└" else "├" current = (prefix level) ++ f s nextLevel = concatMap renderNext cs renderNext c = renderAsTreeRec f (level + 1) (c == (last cs)) c normalizePipes :: [String] -> [String] normalizePipes [] = [] normalizePipes (x:[]) = [x] normalizePipes (x:xs) = x:normalizePipes (next:tail xs) where next = normalizePipes' (head xs) x normalizePipes' :: String -> String -> String normalizePipes' a b = List.foldr tryReplace a is where is = elemIndices '│' a tryReplace i x = if isReplaceable i b then replace i " " x else x isReplaceable i x = i < (length x) && ((x!!i) == ' ' || (x!!i) == '└') replace :: Int -> [a] -> [a] -> [a] replace i x xs | i < (length xs) = (take i xs) ++ x ++ (drop (i + 1) xs) | otherwise = xs sumMap :: (a -> Int) -> [a] -> Int sumMap f = sum . List.map f
LFDM/hstats
src/lib/Util.hs
bsd-3-clause
4,128
0
13
878
1,759
936
823
113
4
{-# LANGUAGE NoMonomorphismRestriction #-} module Test.AES (test) where import Test.Util test = standardTest AES modeLine "KEY" modeLine = string "AESVS " *> many anySym *> string " test data for " *> anyVal
GaloisInc/hacrypto
calf/lib/Test/AES.hs
bsd-3-clause
210
0
8
35
55
29
26
5
1
module TestLojysambanLib (lojysambanLib) where import Test.HUnit import Control.Applicative import System.IO.Unsafe import LojysambanLib import Crypto.Hash.MD5 main = maybe (return ()) putStrLn $ ask nonkanynacQ5 nonkanynac lojysambanLib = "test of LojysambanLib" ~: test [ ask pendoQ1 pendo ~?= pendoA1, ask patfuQ1 patfu ~?= patfuA1, (hash . read . show . drop 4) <$> ask skariQ1 skari ~?= skariA1, ask jminaQ1 jmina ~?= Just ".i li 3", -- ask nonkanynacQ2 nonkanynac ~?= Just ".i go'i", ask nonkanynacQ3 nonkanynac ~?= Just ".i nago'i", ask nonkanynacQ4 nonkanynac ~?= Just ".i nago'i", ask zilkancuQ1 zilkancu ~?= zilkancuR1 ] pendo = unsafePerformIO $ readRules <$> readFile "examples/pendo.jbo" pendoQ1 = "la .ualeis. pendo ma" pendoA1 = Just ".i la gromit" patfu = unsafePerformIO $ readRules <$> readFile "examples/patfu.jbo" patfuQ1 = "ma dzena la jon.bois.jr." patfuA1 = Just ".i la jon.bois.sr .a la zeb" skari = unsafePerformIO $ readRules <$> readFile "examples/skari.jbo" skariQ1 = "alabam. bu toldu'o misisip. bu boi joji'as. bu boi " ++ "tenesis. bu boi florid. bu" -- skariA1 = Just $ read "\"\179Gn|a\240\tV\194A;\211\&3q\246\254\"" skariA1 = Just $ read "\"\143\194\159\133X9\170\178\v\238\225\253\\\"\160Z\196\"" cmima = unsafePerformIO $ readRules <$> readFile "examples/cmima.jbo" cmimaQ1 = "ma cmima la .as. ce'o la .yb." jmina = unsafePerformIO $ readRules <$> readFile "examples/jmina.jbo" jminaQ1 = "ma broda" nonkanynac = unsafePerformIO $ readRules <$> readFile "examples/nonkanynac.jbo" nonkanynacQ1 = "xy.papa ce'o xy.pare ce'o lire ce'o licilo'o ce'o " ++ "xy.repa ce'o xy.rere ce'o xy.reci ce'o xy.revo ce'o " ++ "xy.cipa ce'o xy.cire ce'o xy.cici ce'o xy.civo ce'o " ++ "lici ce'o livolo'o ce'o xy.voci ce'o xy.vovo " ++ "nonkanyna'u ma" -- nonkanynacQ2 = "la .iocikun. ce'o la .ituk. ce'o la manam. cu datsi'u" nonkanynacQ3 = "la .iocikun. ce'o la .ituk. ce'o la .iocikun. cu datsi'u" nonkanynacQ4 = "la .ituk. ce'o la .iocikun. ce'o la .iocikun. cu datsi'u" nonkanynacQ5 = "xy.papa ce'o lipa ce'o lire ce'o lici ce'o " ++ "lirelo'o ce'o xy.rere ce'o livo ce'o lipa ce'o " ++ "lipa ce'o lirelo'o ce'o xy.cici ce'o livo ce'o " ++ "lici ce'o livo ce'o lipalo'o ce'o xy.vovo " ++ "nonkanyna'u ma" zilkancu = unsafePerformIO $ readRules <$> readFile "examples/zilkancu.jbo" zilkancuQ1 = "ma zilselna'o lipa ce'o lire ce'o lici" zilkancuR1 = Just ".i li 2"
YoshikuniJujo/lojysamban
tests/TestLojysambanLib.hs
bsd-3-clause
2,465
36
13
436
461
240
221
47
1
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-} module Fuga (fuga, piyo) where import Hoge (hoge) fuga :: String fuga = [hoge| hoge fuga piyo |] piyo :: String piyo = [hoge| hoge fuga piyo |]
CementTheBlock/.vim
vim/bundle/ghcmod-vim/test/data/th/Fuga.hs
mit
192
0
5
35
49
34
15
7
1
{-# LANGUAGE OverloadedStrings #-} {- | Module : Network.MPD.Applicative.Database Copyright : (c) Joachim Fasting 2012 License : MIT Maintainer : [email protected] Stability : stable Portability : unportable The music database. -} module Network.MPD.Applicative.Database where import Control.Applicative import qualified Network.MPD.Commands.Arg as Arg import Network.MPD.Commands.Arg hiding (Command) import Network.MPD.Commands.Parse import Network.MPD.Commands.Query import Network.MPD.Util import Network.MPD.Commands.Types import Network.MPD.Applicative.Internal import Network.MPD.Applicative.Util -- | Get a count of songs and their total playtime that exactly match the -- query. count :: Query -> Command Count count q = Command (liftParser parseCount) ["count" <@> q] -- | Find songs matching the query exactly. find :: Query -> Command [Song] find q = Command p ["find" <@> q] where p :: Parser [Song] p = liftParser takeSongs -- | Like 'find' but adds the results to the current playlist. findAdd :: Query -> Command () findAdd q = Command emptyResponse ["findadd" <@> q] -- | Lists all tags of the specified type. -- -- Note that the optional artist value is only ever used if the -- metadata type is 'Album', and is then taken to mean that the albums -- by that artist be listed. list :: Metadata -> Maybe Artist -> Command [Value] list m q = Command p c where p = map Value . takeValues <$> getResponse c = case m of Album -> ["list Album" <@> q] _ -> ["list" <@> m] -- | List all songs and directories in a database path. listAll :: Path -> Command [Path] listAll path = Command p ["listall" <@> path] where p :: Parser [Path] p = map (Path . snd) . filter ((== "file") . fst) . toAssocList <$> getResponse -- Internal helper lsInfo' :: Arg.Command -> Path -> Command [LsResult] lsInfo' cmd path = Command p [cmd <@> path] where p :: Parser [LsResult] p = liftParser takeEntries -- | Same as 'listAll' but also returns metadata. listAllInfo :: Path -> Command [LsResult] listAllInfo = lsInfo' "listallinfo" -- | List the contents of a database directory. lsInfo :: Path -> Command [LsResult] lsInfo = lsInfo' "lsinfo" -- | Like 'find' but with inexact matching. search :: Query -> Command [Song] search q = Command p ["search" <@> q] where p :: Parser [Song] p = liftParser takeSongs -- | Like 'search' but adds the results to the current playlist. -- -- Since MPD 0.17. searchAdd :: Query -> Command () searchAdd q = Command emptyResponse ["searchadd" <@> q] -- | Like 'searchAdd' but adds results to the named playlist. -- -- Since MPD 0.17. searchAddPl :: PlaylistName -> Query -> Command () searchAddPl pl q = Command emptyResponse ["searchaddpl" <@> pl <++> q] -- | Update the music database. -- If no path is supplied, the entire database is updated. update :: Maybe Path -> Command Integer update = update_ "update" -- | Like 'update' but also rescan unmodified files. rescan :: Maybe Path -> Command Integer rescan = update_ "rescan" -- A helper for 'update' and 'rescan. update_ :: Arg.Command -> Maybe Path -> Command Integer update_ cmd mPath = Command p [cmd <@> mPath] where p :: Parser Integer p = do r <- getResponse case toAssocList r of [("updating_db", id_)] -> maybe (unexpected r) return (parseNum id_) _ -> unexpected r
beni55/libmpd-haskell
src/Network/MPD/Applicative/Database.hs
mit
3,720
0
14
996
818
444
374
60
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} -- @ {-# LANGUAGE TypeApplications #-} -- to bring stuff like (r, c) into scope {-# LANGUAGE ScopedTypeVariables #-} module Symengine.VecBasic ( VecBasic, vecbasic_new, vecbasic_push_back, vecbasic_get, vecbasic_size, vector_to_vecbasic, ) where import Prelude import Foreign.C.Types import Foreign.Ptr import Foreign.C.String import Foreign.Storable import Foreign.Marshal.Array import Foreign.Marshal.Alloc import Foreign.ForeignPtr import Control.Applicative import Control.Monad -- for foldM import System.IO.Unsafe import Control.Monad import GHC.Real import Symengine import GHC.TypeLits -- type level programming import qualified Data.Vector.Sized as V -- sized vectors import Symengine.Internal import Symengine.BasicSym -- |represents a symbol exported by SymEngine. create this using the functions -- 'zero', 'one', 'minus_one', 'e', 'im', 'rational', 'complex', and also by -- constructing a number and converting it to a Symbol -- -- >>> 3.5 :: BasicSym -- 7/2 -- -- >>> rational 2 10 -- 1 /5 -- -- >>> complex 1 2 -- 1 + 2*I -- vectors binding -- | Represents a Vector of BasicSym -- | usually, end-users are not expected to interact directly with VecBasic -- | this should at some point be moved to Symengine.Internal newtype VecBasic = VecBasic (ForeignPtr CVecBasic) instance Wrapped VecBasic CVecBasic where with (VecBasic p) f = withForeignPtr p f -- | push back an element into a vector vecbasic_push_back :: VecBasic -> BasicSym -> IO () vecbasic_push_back vec sym = with2 vec sym (\v p ->vecbasic_push_back_ffi v p) -- | get the i'th element out of a vecbasic vecbasic_get :: VecBasic -> Int -> Either SymengineException BasicSym vecbasic_get vec i = if i >= 0 && i < vecbasic_size vec then unsafePerformIO $ do sym <- basicsym_new exception <- cIntToEnum <$> with2 vec sym (\v s -> vecbasic_get_ffi v i s) case exception of NoException -> return (Right sym) _ -> return (Left exception) else Left RuntimeError -- | Create a new VecBasic vecbasic_new :: IO VecBasic vecbasic_new = do ptr <- vecbasic_new_ffi finalized <- newForeignPtr vecbasic_free_ffi ptr return $ VecBasic (finalized) vector_to_vecbasic :: forall n. KnownNat n => V.Vector n BasicSym -> IO VecBasic vector_to_vecbasic syms = do ptr <- vecbasic_new_ffi forM_ syms (\sym -> with sym (\s -> vecbasic_push_back_ffi ptr s)) finalized <- newForeignPtr vecbasic_free_ffi ptr return $ VecBasic finalized vecbasic_size :: VecBasic -> Int vecbasic_size vec = unsafePerformIO $ fromIntegral <$> with vec vecbasic_size_ffi foreign import ccall "symengine/cwrapper.h vecbasic_new" vecbasic_new_ffi :: IO (Ptr CVecBasic) foreign import ccall "symengine/cwrapper.h vecbasic_push_back" vecbasic_push_back_ffi :: Ptr CVecBasic -> Ptr CBasicSym -> IO () foreign import ccall "symengine/cwrapper.h vecbasic_get" vecbasic_get_ffi :: Ptr CVecBasic -> Int -> Ptr CBasicSym -> IO CInt foreign import ccall "symengine/cwrapper.h vecbasic_size" vecbasic_size_ffi :: Ptr CVecBasic -> IO CSize foreign import ccall "symengine/cwrapper.h &vecbasic_free" vecbasic_free_ffi :: FunPtr (Ptr CVecBasic -> IO ())
bollu/symengine.hs-1
src/Symengine/VecBasic.hs
mit
3,398
0
14
577
701
378
323
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Chorebot.Distributor ( distribute ) where import Data.Time import Data.List import System.Random import Control.Monad.Random import Control.Monad.State import Control.Monad.Identity import Control.Monad.Reader import Control.Monad.Extra import Data.Maybe import Chorebot.Chore import Chorebot.Assignment import Chorebot.Profile import Chorebot.Doer (doerRetired) data PendingChore = PendingChore { _pendingChore :: Chore , _assignedCount :: Int } deriving (Eq) mkPending :: Chore -> PendingChore mkPending chore' = PendingChore chore' (choreCount chore') decPending :: PendingChore -> Maybe PendingChore decPending p | ac > 1 = Just (p { _assignedCount = ac - 1 }) | otherwise = Nothing where ac = _assignedCount p -- The state for our algorithm, which will be updated in -- iterations. As chores are assigned, pending chores move from the -- pending chores list into the new assignments list. In addition a -- sanity check counter is incremented, in cases where chores are not -- able to be assigned and we would loop forever. data CState = CState { pendingChores :: [PendingChore] , newAssignments :: [Assignment] , sanityCheck :: Int , permAssignments :: [(Profile, Int)] } -- Read-only configuration for the algorithm. data CConf = CConf { time :: UTCTime , pastAssignments :: [Assignment] , profiles :: [Profile] , sanityCheckLimit :: Int } -- Helper function to create the config. Make sure that the list of -- assignments is sorted to begin with. mkCConf :: UTCTime -> [Assignment] -> [Profile] -> Int -> CConf mkCConf t a p sc = CConf t a' p sc where a' = let cmpDates a1 a2 = assignmentDate a1 `compare` assignmentDate a2 in reverse $ sortBy cmpDates a -- Our chore assignment monad. We want to capture state (the current -- pending chores to assign and the assignments made so far), -- read-only configuration (a list of profiles, the current time, a -- limit of # of iterations, etc), and a random number generator that -- introduces some randomness into sorting. newtype C a = C { _runC :: RandT StdGen (ReaderT CConf (State CState)) a } deriving (Functor, Applicative, Monad, MonadState CState, MonadReader CConf, MonadRandom) -- Run the C monad. Given an initial config, random generator, and -- state, run an action and return the result along with the new -- generator and updated state. Used to run the overall action, which -- is distribute'. runC :: C a -> CConf -> CState -> StdGen -> ((a, StdGen), CState) runC (C k) conf st gen = runIdentity (runStateT (runReaderT (runRandT k gen) conf) st) -- Public-facing function. Delegate to the C monad to actually run the -- algorithm. Set up our initial reader config and state. distribute :: [Profile] -> [Chore] -> [Assignment] -> UTCTime -> StdGen -> ([Assignment], Bool, StdGen) distribute profs chores assigns now gen = let (((as, hitSc), gen'), _) = runC distribute' conf st gen in (as, hitSc, gen') where st = CState { pendingChores = map mkPending chores , newAssignments = [] , sanityCheck = 0 , permAssignments = [] } conf = mkCConf now assigns profs' sclimit sclimit = (length chores) * (length profs') + 50 profs' = filter (not . doerRetired . profDoer) profs -- The distribution algorithm. distribute' :: C ([Assignment], Bool) distribute' = do removeUneccessaryChores -- step 1 distributePerm -- step 2 sortChores -- step 3 hitLim <- distributeAll -- step 4 st <- get return (newAssignments st, hitLim) -- reader helpers askTime :: C UTCTime askProfiles :: C [Profile] askPastAssignments :: C [Assignment] askSanityCheckLimit :: C Int askTime = liftM time ask askProfiles = liftM profiles ask askPastAssignments = liftM pastAssignments ask askSanityCheckLimit = liftM sanityCheckLimit ask -- Step 1: Remove chores that have been assigned within the required -- chore interval. removeUneccessaryChores :: C () removeUneccessaryChores = do st <- get c' <- filterM choreNeedsAssignment (pendingChores st) let st' = st { pendingChores = c' } put st' return () choreNeedsAssignment :: PendingChore -> C Bool choreNeedsAssignment (PendingChore c _) = do now <- askTime past <- askPastAssignments let prevAssignment = find (\a' -> c == (assignmentChore a')) past case prevAssignment of -- a' is the previous assignment of chore c. -- -- calculate whether the time since last defined is greater -- than the interval. Just a' -> let diff = diffUTCTime now (assignmentDate a') secInDay = 24 * 60 * 60 intervalSeconds = fromIntegral $ (7 * choreInterval c) * secInDay in return $ diff >= intervalSeconds Nothing -> return True assignPerm :: Profile -> PendingChore -> C () assignPerm prof pending = do _ <- assignPending prof pending st <- get let pa = permAssignments st i' = case lookup prof pa of Just i -> i + 1 Nothing -> 1 put $ st { permAssignments = (prof,i'):pa } return () assignPending :: Profile -> PendingChore -> C Assignment assignPending prof pending = do st <- get now <- askTime let doer' = profDoer prof c = _pendingChore pending assignment = assign doer' now c assignments' = assignment : (newAssignments st) chores' = mapMaybe (ifEqDecPending pending) (pendingChores st) put $ st { pendingChores = chores' , newAssignments = assignments' } return assignment where ifEqDecPending p1 p2 | p1 == p2 = decPending p2 | otherwise = Just p2 -- Step 2: distribute permanent chores. distributePerm :: C () distributePerm = do profs <- liftM profiles ask forM_ profs $ \p -> do -- check the current pending chores that are permanently assigned -- to `p`. let doer' = profDoer p cs <- liftM pendingChores get let toAssign = filter (\pc -> doer' `isPermanentlyAssigned` (_pendingChore pc)) cs mapM_ (assignPerm p) toAssign return () -- Helper to generate a sequence of random integers (using an -- arbitrary, "good enough" domain). randomSequence :: Int -> C [Int] randomSequence n = sequence $ replicate n $ getRandomR (1,10000) randomSort :: [a] -> C [a] randomSort as = do rs <- randomSequence (length as) let asW = zip rs as return $ map snd $ sortBy (\a b -> fst a `compare` fst b) asW -- Step 3: Sort the pending chores randomly. sortChores :: C () sortChores = do st <- get let chores = pendingChores st chores' <- randomSort chores put $ st { pendingChores = chores' } -- Step 4: Distribute the remaining pending chores. Returns whether we -- hit the sanity check limit or not. distributeAll :: C Bool distributeAll = do profs <- askProfiles -- Randomize profiles. sortedProfs <- randomSort profs lim <- askSanityCheckLimit let checkIter :: C Bool checkIter = do st <- get let chores = pendingChores st sc = sanityCheck st if sc > lim || (length chores == 0) then return False else return True whileM $ do mapM_ distributeOne sortedProfs checkIter st <- get let hitSanityCheck = if (sanityCheck st) > lim then True else False return hitSanityCheck -- Take one pending chore and make a new assignment. Either remove the -- chore from the pending chores list or decrease its count by 1 if -- greater than 1. it is possible no chore assignment is -- made. increase the sanity check counter by 1. distributeOne :: Profile -> C () distributeOne profile = do lim <- askSanityCheckLimit st <- get let chores = pendingChores st assigns = newAssignments st doer' = profDoer profile sc = sanityCheck st permAssignmentCount = fromMaybe 0 $ lookup profile (permAssignments st) shouldAssign pending = let c = _pendingChore pending in or [ sc >= lim, -- force assignment if sanity check is above limit. not $ or [ (hasVetoed doer' c), (elem c $ map assignmentChore (filter ((== (profDoer profile)) . assignmentDoer) assigns)), (elem c $ latestChores profile) ] ] -- assign the first chore of `pendingChores' that makes sense to the -- doer. newChoreToAssign = find shouldAssign chores case permAssignmentCount of 0 -> do case newChoreToAssign of -- we should assign `c` to `profile` Just pending -> assignPending profile pending >> return () -- chore could not be assigned, noop Nothing -> return () _ -> do -- skip this round and decrease perm assignment count put $ st { permAssignments = (profile,permAssignmentCount - 1):(permAssignments st) } incSc -- ensure sanity check counter is increased return () incSc :: C () incSc = do st <- get let sc = sanityCheck st put $ st { sanityCheck = sc + 1 }
mjhoy/chorebot
src/Chorebot/Distributor.hs
gpl-2.0
9,441
0
26
2,566
2,347
1,213
1,134
188
3
{-# LANGUAGE OverloadedStrings #-} {- | Module: TestMaker.Test Description: Manages the database of questions. Copyright: (c) Chris Godbout License: GPLv3 Maintainer: [email protected] Stability: experimental Portability: portable -} module TestMaker.Database where import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Data.Text as T import TestMaker.Problems import TestMaker.Types type QuestionDB = ((M.Map Int Question), (M.Map T.Text [Int])) getQuestion :: QuestionDB -> Int -> Question getQuestion (db,_) i = (fromMaybe NullQuestion) $ M.lookup i db -- | Finds all questions associated with a given tag. -- | Given a database and a list of integers, it returns a list of questions. getQuestions :: QuestionDB -> [Int] -> [Question] getQuestions qdb ids = filter (/= NullQuestion) $ map (getQuestion qdb) ids getQuestionsByTag :: QuestionDB -> T.Text -> [Question] getQuestionsByTag qdb@(_,db) t = getQuestions qdb $ fromMaybe [] $ M.lookup t db -- | Gets the entire contents of a database. This might work better if it's passed a filename instead. It would have the same effect. getDatabase :: QuestionDB -> [Question] getDatabase (db,_) = M.elems db deleteQuestion :: QuestionDB -> Int -> QuestionDB deleteQuestion (qdb, tdb) i = (qdb', tdb') where qdb' = M.delete i qdb tdb' = M.map (filter (/= i)) tdb smallestMissingID :: QuestionDB -> Int smallestMissingID (qdb,_) = f 1 (M.keys qdb) where f i [] = i f i (x : xs) = if i >= x then f (min (i+1) (x+1)) xs else i insertQuestion :: QuestionDB -> Question -> QuestionDB insertQuestion db NullQuestion = db insertQuestion db q@(Question _ _ _ _ ts i) = (qdb',tdb') where i' = if i < 1 then smallestMissingID db else i (qdb,tdb) = deleteQuestion db i' qdb' = M.insert i' (modQuestion q (QID i')) qdb tdb' = foldl (\acc x -> M.insertWith (++) x [i'] acc) tdb ts insertQuestion db q@(ShortAnswer _ _ _ ts i) = (qdb',tdb') where i' = if i < 1 then smallestMissingID db else i (qdb,tdb) = deleteQuestion db i' qdb' = M.insert i' (modQuestion q (QID i')) qdb tdb' = foldl (\acc x -> M.insertWith (++) x [i'] acc) tdb ts -- | This takes a database name and a problem set file name, parses the problem set, and inserts all of the questions into the database. If the database schema hasn't been created, it creates it. fileToDB :: FilePath -> IO QuestionDB fileToDB fp = do qs <- parseProblemSet fp return $ foldl (\acc x -> insertQuestion acc x) (M.empty,M.empty) qs
mathologist/hTestMaker
testmaker/src/TestMaker/Database.hs
gpl-3.0
2,658
0
12
623
820
444
376
46
3
module Data.Time.Moment.Interval ( -- * Interval Interval (fromInterval) , toInterval ) where import Data.Time.Moment.Private toInterval :: Integer -> Interval toInterval = Interval
hellertime/time-recurrence
src/Data/Time/Moment/Interval.hs
lgpl-3.0
210
0
5
50
42
28
14
9
1
{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE RecordWildCards #-} -- | Dealing with Cabal. module Stack.Package (readPackage ,readPackageBS ,readPackageDescriptionDir ,readDotBuildinfo ,readPackageUnresolved ,readPackageUnresolvedBS ,resolvePackage ,packageFromPackageDescription ,findOrGenerateCabalFile ,hpack ,Package(..) ,GetPackageFiles(..) ,GetPackageOpts(..) ,PackageConfig(..) ,buildLogPath ,PackageException (..) ,resolvePackageDescription ,packageToolDependencies ,packageDependencies ,autogenDir ,checkCabalFileName ,printCabalFileWarning ,cabalFilePackageId) where import Prelude () import Prelude.Compat import Control.Arrow ((&&&)) import Control.Exception hiding (try,catch) import Control.Monad (liftM, liftM2, (<=<), when, forM, forM_) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader,runReaderT,ask,asks) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Data.List.Compat import Data.List.Extra (nubOrd) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Maybe.Extra import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8, decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Version (showVersion) import Distribution.Compiler import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as Cabal import qualified Distribution.Package as D import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier) import qualified Distribution.PackageDescription as D import Distribution.PackageDescription hiding (FlagName) import Distribution.PackageDescription.Parse import qualified Distribution.PackageDescription.Parse as D import Distribution.ParseUtils import Distribution.Simple.Utils import Distribution.System (OS (..), Arch, Platform (..)) import Distribution.Text (display, simpleParse) import qualified Distribution.Verbosity as D import qualified Hpack import qualified Hpack.Config as Hpack import Path as FL import Path.Extra import Path.Find import Path.IO hiding (findFiles) import Safe (headDef, tailSafe) import Stack.Build.Installed import Stack.Constants import Stack.Types.FlagName import Stack.Types.GhcPkgId import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import Stack.Types.Config import Stack.Types.Build import Stack.Types.Package import Stack.Types.Compiler import qualified System.Directory as D import System.FilePath (splitExtensions, replaceExtension) import qualified System.FilePath as FilePath import System.IO.Error -- | Read the raw, unresolved package information. readPackageUnresolved :: (MonadIO m, MonadThrow m) => Path Abs File -> m ([PWarning],GenericPackageDescription) readPackageUnresolved cabalfp = liftIO (BS.readFile (FL.toFilePath cabalfp)) >>= readPackageUnresolvedBS (Just cabalfp) -- | Read the raw, unresolved package information from a ByteString. readPackageUnresolvedBS :: (MonadThrow m) => Maybe (Path Abs File) -> BS.ByteString -> m ([PWarning],GenericPackageDescription) readPackageUnresolvedBS mcabalfp bs = case parsePackageDescription chars of ParseFailed per -> throwM (PackageInvalidCabalFile mcabalfp per) ParseOk warnings gpkg -> return (warnings,gpkg) where chars = T.unpack (dropBOM (decodeUtf8With lenientDecode bs)) -- https://github.com/haskell/hackage-server/issues/351 dropBOM t = fromMaybe t $ T.stripPrefix "\xFEFF" t -- | Reads and exposes the package information readPackage :: (MonadLogger m, MonadIO m, MonadCatch m) => PackageConfig -> Path Abs File -> m ([PWarning],Package) readPackage packageConfig cabalfp = do (warnings,gpkg) <- readPackageUnresolved cabalfp return (warnings,resolvePackage packageConfig gpkg) -- | Reads and exposes the package information, from a ByteString readPackageBS :: (MonadThrow m) => PackageConfig -> BS.ByteString -> m ([PWarning],Package) readPackageBS packageConfig bs = do (warnings,gpkg) <- readPackageUnresolvedBS Nothing bs return (warnings,resolvePackage packageConfig gpkg) -- | Get 'GenericPackageDescription' and 'PackageDescription' reading info -- from given directory. readPackageDescriptionDir :: (MonadLogger m, MonadIO m, MonadCatch m) => PackageConfig -> Path Abs Dir -> m (GenericPackageDescription, PackageDescription) readPackageDescriptionDir config pkgDir = do cabalfp <- findOrGenerateCabalFile pkgDir gdesc <- liftM snd (readPackageUnresolved cabalfp) return (gdesc, resolvePackageDescription config gdesc) -- | Read @<package>.buildinfo@ ancillary files produced by some Setup.hs hooks. -- The file includes Cabal file syntax to be merged into the package description -- derived from the package's .cabal file. -- -- NOTE: not to be confused with BuildInfo, an Stack-internal datatype. readDotBuildinfo :: MonadIO m => Path Abs File -> m HookedBuildInfo readDotBuildinfo buildinfofp = liftIO $ readHookedBuildInfo D.silent (toFilePath buildinfofp) -- | Print cabal file warnings. printCabalFileWarning :: (MonadLogger m) => Path Abs File -> PWarning -> m () printCabalFileWarning cabalfp = \case (PWarning x) -> $logWarn ("Cabal file warning in " <> T.pack (toFilePath cabalfp) <> ": " <> T.pack x) (UTFWarning line msg) -> $logWarn ("Cabal file warning in " <> T.pack (toFilePath cabalfp) <> ":" <> T.pack (show line) <> ": " <> T.pack msg) -- | Check if the given name in the @Package@ matches the name of the .cabal file checkCabalFileName :: MonadThrow m => PackageName -> Path Abs File -> m () checkCabalFileName name cabalfp = do -- Previously, we just use parsePackageNameFromFilePath. However, that can -- lead to confusing error messages. See: -- https://github.com/commercialhaskell/stack/issues/895 let expected = packageNameString name ++ ".cabal" when (expected /= toFilePath (filename cabalfp)) $ throwM $ MismatchedCabalName cabalfp name -- | Resolve a parsed cabal file into a 'Package'. resolvePackage :: PackageConfig -> GenericPackageDescription -> Package resolvePackage packageConfig gpkg = packageFromPackageDescription packageConfig gpkg (resolvePackageDescription packageConfig gpkg) packageFromPackageDescription :: PackageConfig -> GenericPackageDescription -> PackageDescription -> Package packageFromPackageDescription packageConfig gpkg pkg = Package { packageName = name , packageVersion = fromCabalVersion (pkgVersion pkgId) , packageDeps = deps , packageFiles = pkgFiles , packageTools = packageDescTools pkg , packageGhcOptions = packageConfigGhcOptions packageConfig , packageFlags = packageConfigFlags packageConfig , packageDefaultFlags = M.fromList [(fromCabalFlagName (flagName flag), flagDefault flag) | flag <- genPackageFlags gpkg] , packageAllDeps = S.fromList (M.keys deps) , packageHasLibrary = maybe False (buildable . libBuildInfo) (library pkg) , packageTests = M.fromList [(T.pack (testName t), testInterface t) | t <- testSuites pkg , buildable (testBuildInfo t)] , packageBenchmarks = S.fromList [T.pack (benchmarkName biBuildInfo) | biBuildInfo <- benchmarks pkg , buildable (benchmarkBuildInfo biBuildInfo)] , packageExes = S.fromList [T.pack (exeName biBuildInfo) | biBuildInfo <- executables pkg , buildable (buildInfo biBuildInfo)] , packageOpts = GetPackageOpts $ \sourceMap installedMap omitPkgs addPkgs cabalfp -> do (componentsModules,componentFiles,_,_) <- getPackageFiles pkgFiles cabalfp componentsOpts <- generatePkgDescOpts sourceMap installedMap omitPkgs addPkgs cabalfp pkg componentFiles return (componentsModules,componentFiles,componentsOpts) , packageHasExposedModules = maybe False (not . null . exposedModules) (library pkg) , packageSimpleType = buildType pkg == Just Simple } where pkgFiles = GetPackageFiles $ \cabalfp -> do let pkgDir = parent cabalfp distDir <- distDirFromDir pkgDir (componentModules,componentFiles,dataFiles',warnings) <- runReaderT (packageDescModulesAndFiles pkg) (cabalfp, buildDir distDir) setupFiles <- if buildType pkg `elem` [Nothing, Just Custom] then do let setupHsPath = pkgDir </> $(mkRelFile "Setup.hs") setupLhsPath = pkgDir </> $(mkRelFile "Setup.lhs") setupHsExists <- doesFileExist setupHsPath if setupHsExists then return (S.singleton setupHsPath) else do setupLhsExists <- doesFileExist setupLhsPath if setupLhsExists then return (S.singleton setupLhsPath) else return S.empty else return S.empty buildFiles <- liftM (S.insert cabalfp . S.union setupFiles) $ do let hpackPath = pkgDir </> $(mkRelFile Hpack.packageConfig) hpackExists <- doesFileExist hpackPath return $ if hpackExists then S.singleton hpackPath else S.empty return (componentModules, componentFiles, buildFiles <> dataFiles', warnings) pkgId = package pkg name = fromCabalPackageName (pkgName pkgId) deps = M.filterWithKey (const . (/= name)) (packageDependencies pkg) -- | Generate GHC options for the package's components, and a list of -- options which apply generally to the package, not one specific -- component. generatePkgDescOpts :: (HasEnvConfig env, MonadThrow m, MonadReader env m, MonadIO m) => SourceMap -> InstalledMap -> [PackageName] -- ^ Packages to omit from the "-package" / "-package-id" flags -> [PackageName] -- ^ Packages to add to the "-package" flags -> Path Abs File -> PackageDescription -> Map NamedComponent (Set DotCabalPath) -> m (Map NamedComponent BuildInfoOpts) generatePkgDescOpts sourceMap installedMap omitPkgs addPkgs cabalfp pkg componentPaths = do config <- asks getConfig distDir <- distDirFromDir cabalDir let cabalMacros = autogenDir distDir </> $(mkRelFile "cabal_macros.h") exists <- doesFileExist cabalMacros let mcabalMacros = if exists then Just cabalMacros else Nothing let generate namedComponent binfo = ( namedComponent , generateBuildInfoOpts BioInput { biSourceMap = sourceMap , biInstalledMap = installedMap , biCabalMacros = mcabalMacros , biCabalDir = cabalDir , biDistDir = distDir , biOmitPackages = omitPkgs , biAddPackages = addPkgs , biBuildInfo = binfo , biDotCabalPaths = fromMaybe mempty (M.lookup namedComponent componentPaths) , biConfigLibDirs = configExtraLibDirs config , biConfigIncludeDirs = configExtraIncludeDirs config , biComponentName = namedComponent } ) return ( M.fromList (concat [ maybe [] (return . generate CLib . libBuildInfo) (library pkg) , fmap (\exe -> generate (CExe (T.pack (exeName exe))) (buildInfo exe)) (executables pkg) , fmap (\bench -> generate (CBench (T.pack (benchmarkName bench))) (benchmarkBuildInfo bench)) (benchmarks pkg) , fmap (\test -> generate (CTest (T.pack (testName test))) (testBuildInfo test)) (testSuites pkg)])) where cabalDir = parent cabalfp data BioInput = BioInput { biSourceMap :: !SourceMap , biInstalledMap :: !InstalledMap , biCabalMacros :: !(Maybe (Path Abs File)) , biCabalDir :: !(Path Abs Dir) , biDistDir :: !(Path Abs Dir) , biOmitPackages :: ![PackageName] , biAddPackages :: ![PackageName] , biBuildInfo :: !BuildInfo , biDotCabalPaths :: !(Set DotCabalPath) , biConfigLibDirs :: !(Set (Path Abs Dir)) , biConfigIncludeDirs :: !(Set (Path Abs Dir)) , biComponentName :: !NamedComponent } -- | Generate GHC options for the target. generateBuildInfoOpts :: BioInput -> BuildInfoOpts generateBuildInfoOpts BioInput {..} = BuildInfoOpts { bioOpts = ghcOpts ++ cppOptions biBuildInfo -- NOTE for future changes: Due to this use of nubOrd (and other uses -- downstream), these generated options must not rely on multiple -- argument sequences. For example, ["--main-is", "Foo.hs", "--main- -- is", "Bar.hs"] would potentially break due to the duplicate -- "--main-is" being removed. -- -- See https://github.com/commercialhaskell/stack/issues/1255 , bioOneWordOpts = nubOrd $ concat [extOpts, srcOpts, includeOpts, libOpts, fworks, cObjectFiles] , bioPackageFlags = deps , bioCabalMacros = biCabalMacros } where cObjectFiles = mapMaybe (fmap toFilePath . makeObjectFilePathFromC biCabalDir biComponentName biDistDir) cfiles cfiles = mapMaybe dotCabalCFilePath (S.toList biDotCabalPaths) -- Generates: -package=base -package=base16-bytestring-0.1.1.6 ... deps = concat [ case M.lookup name biInstalledMap of Just (_, Stack.Types.Package.Library _ident ipid) -> ["-package-id=" <> ghcPkgIdString ipid] _ -> ["-package=" <> packageNameString name <> maybe "" -- This empty case applies to e.g. base. ((("-" <>) . versionString) . piiVersion) (M.lookup name biSourceMap)] | name <- pkgs] pkgs = biAddPackages ++ [ name | Dependency cname _ <- targetBuildDepends biBuildInfo , let name = fromCabalPackageName cname , name `notElem` biOmitPackages] ghcOpts = concatMap snd . filter (isGhc . fst) $ options biBuildInfo where isGhc GHC = True isGhc _ = False extOpts = map (("-X" ++) . display) (usedExtensions biBuildInfo) srcOpts = map (("-i" <>) . toFilePathNoTrailingSep) ([biCabalDir | null (hsSourceDirs biBuildInfo)] <> mapMaybe toIncludeDir (hsSourceDirs biBuildInfo) <> [autogenDir biDistDir,buildDir biDistDir] <> [makeGenDir (buildDir biDistDir) | Just makeGenDir <- [fileGenDirFromComponentName biComponentName]]) ++ ["-stubdir=" ++ toFilePathNoTrailingSep (buildDir biDistDir)] toIncludeDir "." = Just biCabalDir toIncludeDir x = fmap (biCabalDir </>) (parseRelDir x) includeOpts = map ("-I" <>) (configExtraIncludeDirs <> pkgIncludeOpts) configExtraIncludeDirs = map toFilePathNoTrailingSep (S.toList biConfigIncludeDirs) pkgIncludeOpts = [ toFilePathNoTrailingSep absDir | dir <- includeDirs biBuildInfo , absDir <- handleDir dir ] libOpts = map ("-l" <>) (extraLibs biBuildInfo) <> map ("-L" <>) (configExtraLibDirs <> pkgLibDirs) configExtraLibDirs = map toFilePathNoTrailingSep (S.toList biConfigLibDirs) pkgLibDirs = [ toFilePathNoTrailingSep absDir | dir <- extraLibDirs biBuildInfo , absDir <- handleDir dir ] handleDir dir = case (parseAbsDir dir, parseRelDir dir) of (Just ab, _ ) -> [ab] (_ , Just rel) -> [biCabalDir </> rel] (Nothing, Nothing ) -> [] fworks = map (\fwk -> "-framework=" <> fwk) (frameworks biBuildInfo) -- | Make the .o path from the .c file path for a component. Example: -- -- @ -- executable FOO -- c-sources: cbits/text_search.c -- @ -- -- Produces -- -- <dist-dir>/build/FOO/FOO-tmp/cbits/text_search.o -- -- Example: -- -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- CLib -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/cbits/text_search.o" -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- (CExe "hoogle") -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/hoogle/hoogle-tmp/cbits/text_search.o" -- λ> makeObjectFilePathFromC :: MonadThrow m => Path Abs Dir -- ^ The cabal directory. -> NamedComponent -- ^ The name of the component. -> Path Abs Dir -- ^ Dist directory. -> Path Abs File -- ^ The path to the .c file. -> m (Path Abs File) -- ^ The path to the .o file for the component. makeObjectFilePathFromC cabalDir namedComponent distDir cFilePath = do relCFilePath <- stripDir cabalDir cFilePath relOFilePath <- parseRelFile (replaceExtension (toFilePath relCFilePath) "o") addComponentPrefix <- fileGenDirFromComponentName namedComponent return (addComponentPrefix (buildDir distDir) </> relOFilePath) -- | The directory where generated files are put like .o or .hs (from .x files). fileGenDirFromComponentName :: MonadThrow m => NamedComponent -> m (Path b Dir -> Path b Dir) fileGenDirFromComponentName namedComponent = case namedComponent of CLib -> return id CExe name -> makeTmp name CTest name -> makeTmp name CBench name -> makeTmp name where makeTmp name = do prefix <- parseRelDir (T.unpack name <> "/" <> T.unpack name <> "-tmp") return (</> prefix) -- | Make the autogen dir. autogenDir :: Path Abs Dir -> Path Abs Dir autogenDir distDir = buildDir distDir </> $(mkRelDir "autogen") -- | Make the build dir. buildDir :: Path Abs Dir -> Path Abs Dir buildDir distDir = distDir </> $(mkRelDir "build") -- | Make the component-specific subdirectory of the build directory. getBuildComponentDir :: Maybe String -> Maybe (Path Rel Dir) getBuildComponentDir Nothing = Nothing getBuildComponentDir (Just name) = parseRelDir (name FilePath.</> (name ++ "-tmp")) -- | Get all dependencies of the package (buildable targets only). packageDependencies :: PackageDescription -> Map PackageName VersionRange packageDependencies = M.fromListWith intersectVersionRanges . concatMap (fmap (depName &&& depRange) . targetBuildDepends) . allBuildInfo' -- | Get all build tool dependencies of the package (buildable targets only). packageToolDependencies :: PackageDescription -> Map Text VersionRange packageToolDependencies = M.fromList . concatMap (fmap (packageNameText . depName &&& depRange) . buildTools) . allBuildInfo' -- | Get all dependencies of the package (buildable targets only). packageDescTools :: PackageDescription -> [Dependency] packageDescTools = concatMap buildTools . allBuildInfo' -- | This is a copy-paste from Cabal's @allBuildInfo@ function, but with the -- @buildable@ test removed. The reason is that (surprise) Cabal is broken, -- see: https://github.com/haskell/cabal/issues/1725 allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ bi | Just lib <- [library pkg_descr] , let bi = libBuildInfo lib , True || buildable bi ] ++ [ bi | exe <- executables pkg_descr , let bi = buildInfo exe , True || buildable bi ] ++ [ bi | tst <- testSuites pkg_descr , let bi = testBuildInfo tst , True || buildable bi , testEnabled tst ] ++ [ bi | tst <- benchmarks pkg_descr , let bi = benchmarkBuildInfo tst , True || buildable bi , benchmarkEnabled tst ] -- | Get all files referenced by the package. packageDescModulesAndFiles :: (MonadLogger m, MonadIO m, MonadReader (Path Abs File, Path Abs Dir) m, MonadCatch m) => PackageDescription -> m (Map NamedComponent (Set ModuleName), Map NamedComponent (Set DotCabalPath), Set (Path Abs File), [PackageWarning]) packageDescModulesAndFiles pkg = do (libraryMods,libDotCabalFiles,libWarnings) <- maybe (return (M.empty, M.empty, [])) (asModuleAndFileMap libComponent libraryFiles) (library pkg) (executableMods,exeDotCabalFiles,exeWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap exeComponent executableFiles) (executables pkg)) (testMods,testDotCabalFiles,testWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap testComponent testFiles) (testSuites pkg)) (benchModules,benchDotCabalPaths,benchWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap benchComponent benchmarkFiles) (benchmarks pkg)) (dfiles) <- resolveGlobFiles (extraSrcFiles pkg ++ map (dataDir pkg FilePath.</>) (dataFiles pkg)) let modules = libraryMods <> executableMods <> testMods <> benchModules files = libDotCabalFiles <> exeDotCabalFiles <> testDotCabalFiles <> benchDotCabalPaths warnings = libWarnings <> exeWarnings <> testWarnings <> benchWarnings return (modules, files, dfiles, warnings) where libComponent = const CLib exeComponent = CExe . T.pack . exeName testComponent = CTest . T.pack . testName benchComponent = CBench . T.pack . benchmarkName asModuleAndFileMap label f lib = do (a,b,c) <- f lib return (M.singleton (label lib) a, M.singleton (label lib) b, c) foldTuples = foldl' (<>) (M.empty, M.empty, []) -- | Resolve globbing of files (e.g. data files) to absolute paths. resolveGlobFiles :: (MonadLogger m,MonadIO m,MonadReader (Path Abs File, Path Abs Dir) m,MonadCatch m) => [String] -> m (Set (Path Abs File)) resolveGlobFiles = liftM (S.fromList . catMaybes . concat) . mapM resolve where resolve name = if '*' `elem` name then explode name else liftM return (resolveFileOrWarn name) explode name = do dir <- asks (parent . fst) names <- matchDirFileGlob' (FL.toFilePath dir) name mapM resolveFileOrWarn names matchDirFileGlob' dir glob = catch (matchDirFileGlob_ dir glob) (\(e :: IOException) -> if isUserError e then do $logWarn ("Wildcard does not match any files: " <> T.pack glob <> "\n" <> "in directory: " <> T.pack dir) return [] else throwM e) -- | This is a copy/paste of the Cabal library function, but with -- -- @ext == ext'@ -- -- Changed to -- -- @isSuffixOf ext ext'@ -- -- So that this will work: -- -- @ -- λ> matchDirFileGlob_ "." "test/package-dump/*.txt" -- ["test/package-dump/ghc-7.8.txt","test/package-dump/ghc-7.10.txt"] -- @ -- matchDirFileGlob_ :: (MonadLogger m, MonadIO m) => String -> String -> m [String] matchDirFileGlob_ dir filepath = case parseFileGlob filepath of Nothing -> liftIO $ die $ "invalid file glob '" ++ filepath ++ "'. Wildcards '*' are only allowed in place of the file" ++ " name, not in the directory name or file extension." ++ " If a wildcard is used it must be with an file extension." Just (NoGlob filepath') -> return [filepath'] Just (FileGlob dir' ext) -> do efiles <- liftIO $ try $ D.getDirectoryContents (dir FilePath.</> dir') let matches = case efiles of Left (_ :: IOException) -> [] Right files -> [ dir' FilePath.</> file | file <- files , let (name, ext') = splitExtensions file , not (null name) && isSuffixOf ext ext' ] when (null matches) $ $logWarn $ "WARNING: filepath wildcard '" <> T.pack filepath <> "' does not match any files." return matches -- | Get all files referenced by the benchmark. benchmarkFiles :: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader (Path Abs File, Path Abs Dir) m) => Benchmark -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) benchmarkFiles bench = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ benchmarkName bench) (dirs ++ [dir]) (bnames <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where exposed = case benchmarkInterface bench of BenchmarkExeV10 _ fp -> [DotCabalMain fp] BenchmarkUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = benchmarkBuildInfo bench -- | Get all files referenced by the test. testFiles :: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader (Path Abs File, Path Abs Dir) m) => TestSuite -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) testFiles test = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ testName test) (dirs ++ [dir]) (bnames <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where exposed = case testInterface test of TestSuiteExeV10 _ fp -> [DotCabalMain fp] TestSuiteLibV09 _ mn -> [DotCabalModule mn] TestSuiteUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = testBuildInfo test -- | Get all files referenced by the executable. executableFiles :: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader (Path Abs File, Path Abs Dir) m) => Executable -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) executableFiles exe = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ exeName exe) (dirs ++ [dir]) (map DotCabalModule (otherModules build) ++ [DotCabalMain (modulePath exe)]) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where build = buildInfo exe -- | Get all files referenced by the library. libraryFiles :: (MonadLogger m, MonadIO m, MonadCatch m, MonadReader (Path Abs File, Path Abs Dir) m) => Library -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) libraryFiles lib = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps Nothing (dirs ++ [dir]) (names <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where names = bnames ++ exposed exposed = map DotCabalModule (exposedModules lib) bnames = map DotCabalModule (otherModules build) build = libBuildInfo lib -- | Get all C sources and extra source files in a build. buildOtherSources :: (MonadLogger m,MonadIO m,MonadCatch m,MonadReader (Path Abs File, Path Abs Dir) m) => BuildInfo -> m (Set DotCabalPath) buildOtherSources build = do csources <- liftM (S.map DotCabalCFilePath . S.fromList) (mapMaybeM resolveFileOrWarn (cSources build)) jsources <- liftM (S.map DotCabalFilePath . S.fromList) (mapMaybeM resolveFileOrWarn (targetJsSources build)) return (csources <> jsources) -- | Get the target's JS sources. targetJsSources :: BuildInfo -> [FilePath] #if MIN_VERSION_Cabal(1, 22, 0) targetJsSources = jsSources #else targetJsSources = const [] #endif -- | Get all dependencies of a package, including library, -- executables, tests, benchmarks. resolvePackageDescription :: PackageConfig -> GenericPackageDescription -> PackageDescription resolvePackageDescription packageConfig (GenericPackageDescription desc defaultFlags mlib exes tests benches) = desc {library = fmap (resolveConditions rc updateLibDeps) mlib ,executables = map (\(n, v) -> (resolveConditions rc updateExeDeps v){exeName=n}) exes ,testSuites = map (\(n,v) -> (resolveConditions rc updateTestDeps v){testName=n}) tests ,benchmarks = map (\(n,v) -> (resolveConditions rc updateBenchmarkDeps v){benchmarkName=n}) benches} where flags = M.union (packageConfigFlags packageConfig) (flagMap defaultFlags) rc = mkResolveConditions (packageConfigCompilerVersion packageConfig) (packageConfigPlatform packageConfig) flags updateLibDeps lib deps = lib {libBuildInfo = (libBuildInfo lib) {targetBuildDepends = deps}} updateExeDeps exe deps = exe {buildInfo = (buildInfo exe) {targetBuildDepends = deps}} updateTestDeps test deps = test {testBuildInfo = (testBuildInfo test) {targetBuildDepends = deps} ,testEnabled = packageConfigEnableTests packageConfig} updateBenchmarkDeps benchmark deps = benchmark {benchmarkBuildInfo = (benchmarkBuildInfo benchmark) {targetBuildDepends = deps} ,benchmarkEnabled = packageConfigEnableBenchmarks packageConfig} -- | Make a map from a list of flag specifications. -- -- What is @flagManual@ for? flagMap :: [Flag] -> Map FlagName Bool flagMap = M.fromList . map pair where pair :: Flag -> (FlagName, Bool) pair (MkFlag (fromCabalFlagName -> name) _desc def _manual) = (name,def) data ResolveConditions = ResolveConditions { rcFlags :: Map FlagName Bool , rcCompilerVersion :: CompilerVersion , rcOS :: OS , rcArch :: Arch } -- | Generic a @ResolveConditions@ using sensible defaults. mkResolveConditions :: CompilerVersion -- ^ Compiler version -> Platform -- ^ installation target platform -> Map FlagName Bool -- ^ enabled flags -> ResolveConditions mkResolveConditions compilerVersion (Platform arch os) flags = ResolveConditions { rcFlags = flags , rcCompilerVersion = compilerVersion , rcOS = os , rcArch = arch } -- | Resolve the condition tree for the library. resolveConditions :: (Monoid target,Show target) => ResolveConditions -> (target -> cs -> target) -> CondTree ConfVar cs target -> target resolveConditions rc addDeps (CondNode lib deps cs) = basic <> children where basic = addDeps lib deps children = mconcat (map apply cs) where apply (cond,node,mcs) = if condSatisfied cond then resolveConditions rc addDeps node else maybe mempty (resolveConditions rc addDeps) mcs condSatisfied c = case c of Var v -> varSatisifed v Lit b -> b CNot c' -> not (condSatisfied c') COr cx cy -> condSatisfied cx || condSatisfied cy CAnd cx cy -> condSatisfied cx && condSatisfied cy varSatisifed v = case v of OS os -> os == rcOS rc Arch arch -> arch == rcArch rc Flag flag -> fromMaybe False $ M.lookup (fromCabalFlagName flag) (rcFlags rc) -- NOTE: ^^^^^ This should never happen, as all flags -- which are used must be declared. Defaulting to -- False. Impl flavor range -> case (flavor, rcCompilerVersion rc) of (GHC, GhcVersion vghc) -> vghc `withinRange` range (GHC, GhcjsVersion _ vghc) -> vghc `withinRange` range #if MIN_VERSION_Cabal(1, 22, 0) (GHCJS, GhcjsVersion vghcjs _) -> #else (OtherCompiler "ghcjs", GhcjsVersion vghcjs _) -> #endif vghcjs `withinRange` range _ -> False -- | Get the name of a dependency. depName :: Dependency -> PackageName depName (Dependency n _) = fromCabalPackageName n -- | Get the version range of a dependency. depRange :: Dependency -> VersionRange depRange (Dependency _ r) = r -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions, plus find any of their module and TemplateHaskell -- dependencies. resolveFilesAndDeps :: (MonadIO m, MonadLogger m, MonadCatch m, MonadReader (Path Abs File, Path Abs Dir) m) => Maybe String -- ^ Package component name -> [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> [Text] -- ^ Extensions. -> m (Set ModuleName,Set DotCabalPath,[PackageWarning]) resolveFilesAndDeps component dirs names0 exts = do (dotCabalPaths, foundModules, missingModules) <- loop names0 S.empty warnings <- liftM2 (++) (warnUnlisted foundModules) (warnMissing missingModules) return (foundModules, dotCabalPaths, warnings) where loop [] _ = return (S.empty, S.empty, []) loop names doneModules0 = do resolved <- resolveFiles dirs names exts let foundFiles = mapMaybe snd resolved (foundModules', missingModules') = partition (isJust . snd) resolved foundModules = mapMaybe (dotCabalModule . fst) foundModules' missingModules = mapMaybe (dotCabalModule . fst) missingModules' pairs <- mapM (getDependencies component) foundFiles let doneModules = S.union doneModules0 (S.fromList (mapMaybe dotCabalModule names)) moduleDeps = S.unions (map fst pairs) thDepFiles = concatMap snd pairs modulesRemaining = S.difference moduleDeps doneModules -- Ignore missing modules discovered as dependencies - they may -- have been deleted. (resolvedFiles, resolvedModules, _) <- loop (map DotCabalModule (S.toList modulesRemaining)) doneModules return ( S.union (S.fromList (foundFiles <> map DotCabalFilePath thDepFiles)) resolvedFiles , S.union (S.fromList foundModules) resolvedModules , missingModules) warnUnlisted foundModules = do let unlistedModules = foundModules `S.difference` S.fromList (mapMaybe dotCabalModule names0) cabalfp <- asks fst return $ if S.null unlistedModules then [] else [ UnlistedModulesWarning cabalfp component (S.toList unlistedModules)] warnMissing _missingModules = do return [] {- FIXME: the issue with this is it's noisy for modules like Paths_* cabalfp <- asks fst return $ if null missingModules then [] else [ MissingModulesWarning cabalfp component missingModules] -} -- | Get the dependencies of a Haskell module file. getDependencies :: (MonadReader (Path Abs File, Path Abs Dir) m, MonadIO m, MonadCatch m, MonadLogger m) => Maybe String -> DotCabalPath -> m (Set ModuleName, [Path Abs File]) getDependencies component dotCabalPath = case dotCabalPath of DotCabalModulePath resolvedFile -> readResolvedHi resolvedFile DotCabalMainPath resolvedFile -> readResolvedHi resolvedFile DotCabalFilePath{} -> return (S.empty, []) DotCabalCFilePath{} -> return (S.empty, []) where readResolvedHi resolvedFile = do dumpHIDir <- getDumpHIDir dir <- asks (parent . fst) case stripDir dir resolvedFile of Nothing -> return (S.empty, []) Just fileRel -> do let dumpHIPath = FilePath.replaceExtension (toFilePath (dumpHIDir </> fileRel)) ".dump-hi" dumpHIExists <- liftIO $ D.doesFileExist dumpHIPath if dumpHIExists then parseDumpHI dumpHIPath else return (S.empty, []) getDumpHIDir = do bld <- asks snd return $ maybe bld (bld </>) (getBuildComponentDir component) -- | Parse a .dump-hi file into a set of modules and files. parseDumpHI :: (MonadReader (Path Abs File, void) m, MonadIO m, MonadCatch m, MonadLogger m) => FilePath -> m (Set ModuleName, [Path Abs File]) parseDumpHI dumpHIPath = do dir <- asks (parent . fst) dumpHI <- liftIO $ fmap C8.lines (C8.readFile dumpHIPath) let startModuleDeps = dropWhile (not . ("module dependencies:" `C8.isPrefixOf`)) dumpHI moduleDeps = S.fromList $ mapMaybe (simpleParse . T.unpack . decodeUtf8) $ C8.words $ C8.concat $ C8.dropWhile (/= ' ') (headDef "" startModuleDeps) : takeWhile (" " `C8.isPrefixOf`) (tailSafe startModuleDeps) thDeps = -- The dependent file path is surrounded by quotes but is not escaped. -- It can be an absolute or relative path. mapMaybe ((fmap T.unpack . (T.stripSuffix "\"" <=< T.stripPrefix "\"") . T.dropWhileEnd (== '\r') . decodeUtf8 . C8.dropWhile (/= '"'))) $ filter ("addDependentFile \"" `C8.isPrefixOf`) dumpHI thDepsResolved <- liftM catMaybes $ forM thDeps $ \x -> do mresolved <- forgivingAbsence (resolveFile dir x) >>= rejectMissingFile when (isNothing mresolved) $ $logWarn $ "Warning: qAddDepedency path listed in " <> T.pack dumpHIPath <> " does not exist: " <> T.pack x return mresolved return (moduleDeps, thDepsResolved) -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions. resolveFiles :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> [Text] -- ^ Extensions. -> m [(DotCabalDescriptor, Maybe DotCabalPath)] resolveFiles dirs names exts = forM names (\name -> liftM (name, ) (findCandidate dirs exts name)) -- | Find a candidate for the given module-or-filename from the list -- of directories and given extensions. findCandidate :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => [Path Abs Dir] -> [Text] -> DotCabalDescriptor -> m (Maybe DotCabalPath) findCandidate dirs exts name = do pkg <- asks fst >>= parsePackageNameFromFilePath candidates <- liftIO makeNameCandidates case candidates of [candidate] -> return (Just (cons candidate)) [] -> do case name of DotCabalModule mn | display mn /= paths_pkg pkg -> logPossibilities dirs mn _ -> return () return Nothing (candidate:rest) -> do warnMultiple name candidate rest return (Just (cons candidate)) where cons = case name of DotCabalModule{} -> DotCabalModulePath DotCabalMain{} -> DotCabalMainPath DotCabalFile{} -> DotCabalFilePath DotCabalCFile{} -> DotCabalCFilePath paths_pkg pkg = "Paths_" ++ packageNameString pkg makeNameCandidates = liftM (nubOrd . concat) (mapM makeDirCandidates dirs) makeDirCandidates :: Path Abs Dir -> IO [Path Abs File] makeDirCandidates dir = case name of DotCabalMain fp -> resolveCandidate dir fp DotCabalFile fp -> resolveCandidate dir fp DotCabalCFile fp -> resolveCandidate dir fp DotCabalModule mn -> liftM concat $ mapM ((\ ext -> resolveCandidate dir (Cabal.toFilePath mn ++ "." ++ ext)) . T.unpack) exts resolveCandidate :: (MonadIO m, MonadThrow m) => Path Abs Dir -> FilePath.FilePath -> m [Path Abs File] resolveCandidate x y = do -- The standard canonicalizePath does not work for this case p <- parseCollapsedAbsFile (toFilePath x FilePath.</> y) exists <- doesFileExist p return $ if exists then [p] else [] -- | Warn the user that multiple candidates are available for an -- entry, but that we picked one anyway and continued. warnMultiple :: MonadLogger m => DotCabalDescriptor -> Path b t -> [Path b t] -> m () warnMultiple name candidate rest = $logWarn ("There were multiple candidates for the Cabal entry \"" <> showName name <> "\" (" <> T.intercalate "," (map (T.pack . toFilePath) rest) <> "), picking " <> T.pack (toFilePath candidate)) where showName (DotCabalModule name') = T.pack (display name') showName (DotCabalMain fp) = T.pack fp showName (DotCabalFile fp) = T.pack fp showName (DotCabalCFile fp) = T.pack fp -- | Log that we couldn't find a candidate, but there are -- possibilities for custom preprocessor extensions. -- -- For example: .erb for a Ruby file might exist in one of the -- directories. logPossibilities :: (MonadIO m, MonadThrow m, MonadLogger m) => [Path Abs Dir] -> ModuleName -> m () logPossibilities dirs mn = do possibilities <- liftM concat (makePossibilities mn) case possibilities of [] -> return () _ -> $logWarn ("Unable to find a known candidate for the Cabal entry \"" <> T.pack (display mn) <> "\", but did find: " <> T.intercalate ", " (map (T.pack . toFilePath) possibilities) <> ". If you are using a custom preprocessor for this module " <> "with its own file extension, consider adding the file(s) " <> "to your .cabal under extra-source-files.") where makePossibilities name = mapM (\dir -> do (_,files) <- listDir dir return (map filename (filter (isPrefixOf (display name) . toFilePath . filename) files))) dirs -- | Get the filename for the cabal file in the given directory. -- -- If no .cabal file is present, or more than one is present, an exception is -- thrown via 'throwM'. -- -- If the directory contains a file named package.yaml, hpack is used to -- generate a .cabal file from it. findOrGenerateCabalFile :: forall m. (MonadThrow m, MonadIO m, MonadLogger m) => Path Abs Dir -- ^ package directory -> m (Path Abs File) findOrGenerateCabalFile pkgDir = do hpack pkgDir findCabalFile where findCabalFile :: m (Path Abs File) findCabalFile = findCabalFile' >>= either throwM return findCabalFile' :: m (Either PackageException (Path Abs File)) findCabalFile' = do files <- liftIO $ findFiles pkgDir (flip hasExtension "cabal" . FL.toFilePath) (const False) return $ case files of [] -> Left $ PackageNoCabalFileFound pkgDir [x] -> Right x -- If there are multiple files, ignore files that start with -- ".". On unixlike environments these are hidden, and this -- character is not valid in package names. The main goal is -- to ignore emacs lock files - see -- https://github.com/commercialhaskell/stack/issues/1897. (filter (not . ("." `isPrefixOf`) . toFilePath . filename) -> [x]) -> Right x _:_ -> Left $ PackageMultipleCabalFilesFound pkgDir files where hasExtension fp x = FilePath.takeExtension fp == "." ++ x -- | Generate .cabal file from package.yaml, if necessary. hpack :: (MonadIO m, MonadLogger m) => Path Abs Dir -> m () hpack pkgDir = do let hpackFile = pkgDir </> $(mkRelFile Hpack.packageConfig) exists <- liftIO $ doesFileExist hpackFile when exists $ do let fpt = T.pack (toFilePath hpackFile) $logDebug $ "Running hpack on " <> fpt r <- liftIO $ Hpack.hpackResult (toFilePath pkgDir) forM_ (Hpack.resultWarnings r) $ \w -> $logWarn ("WARNING: " <> T.pack w) let cabalFile = T.pack (Hpack.resultCabalFile r) case Hpack.resultStatus r of Hpack.Generated -> $logDebug $ "hpack generated a modified version of " <> cabalFile Hpack.OutputUnchanged -> $logDebug $ "hpack output unchanged in " <> cabalFile -- NOTE: this is 'logInfo' so it will be outputted to the -- user by default. Hpack.AlreadyGeneratedByNewerHpack -> $logWarn $ "WARNING: " <> cabalFile <> " was generated with a newer version of hpack, please upgrade and try again." -- | Path for the package's build log. buildLogPath :: (MonadReader env m, HasBuildConfig env, MonadThrow m) => Package -> Maybe String -> m (Path Abs File) buildLogPath package' msuffix = do env <- ask let stack = getProjectWorkDir env fp <- parseRelFile $ concat $ packageIdentifierString (packageIdentifier package') : maybe id (\suffix -> ("-" :) . (suffix :)) msuffix [".log"] return $ stack </> $(mkRelDir "logs") </> fp -- Internal helper to define resolveFileOrWarn and resolveDirOrWarn resolveOrWarn :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => Text -> (Path Abs Dir -> String -> m (Maybe a)) -> FilePath.FilePath -> m (Maybe a) resolveOrWarn subject resolver path = do cwd <- getCurrentDir file <- asks fst dir <- asks (parent . fst) result <- resolver dir path when (isNothing result) $ $logWarn ("Warning: " <> subject <> " listed in " <> T.pack (maybe (FL.toFilePath file) FL.toFilePath (stripDir cwd file)) <> " file does not exist: " <> T.pack path) return result -- | Resolve the file, if it can't be resolved, warn for the user -- (purely to be helpful). resolveFileOrWarn :: (MonadCatch m,MonadIO m,MonadLogger m,MonadReader (Path Abs File, Path Abs Dir) m) => FilePath.FilePath -> m (Maybe (Path Abs File)) resolveFileOrWarn = resolveOrWarn "File" f where f p x = forgivingAbsence (resolveFile p x) >>= rejectMissingFile -- | Resolve the directory, if it can't be resolved, warn for the user -- (purely to be helpful). resolveDirOrWarn :: (MonadCatch m,MonadIO m,MonadLogger m,MonadReader (Path Abs File, Path Abs Dir) m) => FilePath.FilePath -> m (Maybe (Path Abs Dir)) resolveDirOrWarn = resolveOrWarn "Directory" f where f p x = forgivingAbsence (resolveDir p x) >>= rejectMissingDir -- | Extract the @PackageIdentifier@ given an exploded haskell package -- path. cabalFilePackageId :: (MonadIO m, MonadThrow m) => Path Abs File -> m PackageIdentifier cabalFilePackageId fp = do pkgDescr <- liftIO (D.readPackageDescription D.silent $ toFilePath fp) (toStackPI . D.package . D.packageDescription) pkgDescr where toStackPI (D.PackageIdentifier (D.PackageName name) ver) = do name' <- parsePackageNameFromString name ver' <- parseVersionFromString (showVersion ver) return (PackageIdentifier name' ver')
AndrewRademacher/stack
src/Stack/Package.hs
bsd-3-clause
51,644
0
22
15,730
12,053
6,233
5,820
-1
-1
module Modal.Formulas where import Control.Applicative hiding ((<|>)) import Control.Arrow ((***)) import Control.Monad (ap) import Data.List import Data.Monoid import Data.Maybe import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import Modal.Display import Modal.Parser hiding (parens, braces, identifier) import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Language import Text.Parsec.Token -- Example usage: -- findGeneralGLFixpoint $ M.fromList [("a",read "~ [] b"), ("b", read "[] (a -> [] ~ b)")] -- Alternatively: -- findGeneralGLFixpoint $ makeEquivs [("a", "~ [] b"), ("b", "[] (a -> [] ~ b)")] -- Modal Logic Formula data structure data ModalFormula v = Val {value :: Bool} | Var {variable :: v} | Neg {contents :: ModalFormula v} | And {left, right :: ModalFormula v} | Or {left, right :: ModalFormula v} | Imp {left, right :: ModalFormula v} | Iff {left, right :: ModalFormula v} | Box {contents :: ModalFormula v} | Dia {contents :: ModalFormula v} deriving (Eq, Ord) instance Monad ModalFormula where return = Var m >>= f = modalEval ModalEvaluator{ handleVal = Val, handleVar = f, handleNeg = Neg, handleAnd = And, handleOr = Or, handleImp = Imp, handleIff = Iff, handleBox = Box, handleDia = Dia } m instance Applicative ModalFormula where pure = return (<*>) = ap instance Functor ModalFormula where fmap f m = m >>= (Var . f) instance Foldable ModalFormula where foldMap acc = modalEval ModalEvaluator{ handleVal = const mempty, handleVar = acc, handleNeg = id, handleAnd = (<>), handleOr = (<>), handleImp = (<>), handleIff = (<>), handleBox = id, handleDia = id } instance Traversable ModalFormula where traverse f = modalEval mevaler where mevaler = ModalEvaluator { handleVal = pure . Val, handleVar = fmap Var . f, handleNeg = fmap Neg, handleAnd = liftA2 And, handleOr = liftA2 Or, handleImp = liftA2 Imp, handleIff = liftA2 Iff, handleBox = fmap Box, handleDia = fmap Dia } -- Syntactic Conveniences: infixr 4 %= (%=) :: ModalFormula v -> ModalFormula v -> ModalFormula v (%=) = Iff infixr 5 %> (%>) :: ModalFormula v -> ModalFormula v -> ModalFormula v (%>) = Imp infixl 6 %| (%|) :: ModalFormula v -> ModalFormula v -> ModalFormula v (%|) = Or infixl 7 %^ (%^) :: ModalFormula v -> ModalFormula v -> ModalFormula v (%^) = And ff :: ModalFormula v ff = Val False tt :: ModalFormula v tt = Val True incon :: Int -> ModalFormula v incon 0 = ff incon n = Box $ incon (n-1) holdsk :: Int -> ModalFormula v -> ModalFormula v holdsk 0 phi = phi holdsk k phi = Neg (incon k) `Imp` phi -- Operator like function that encodes "provable in S+Con^k(S)", where -- "S" is the original system. boxk :: Int -> ModalFormula v -> ModalFormula v boxk k phi = Box (holdsk k phi) diak :: Int -> ModalFormula v -> ModalFormula v diak k phi = Neg $ Box (holdsk k $ Neg phi) -- Data structure to be mapped across a formula. data ModalEvaluator v a = ModalEvaluator { handleVal :: Bool -> a, handleVar :: v -> a, handleNeg :: a -> a, handleAnd :: a -> a -> a, handleOr :: a -> a -> a, handleImp :: a -> a -> a, handleIff :: a -> a -> a, handleBox :: a -> a, handleDia :: a -> a} -- And how to use it to map: modalEval :: ModalEvaluator v a -> ModalFormula v -> a modalEval m = f where f (Val v) = handleVal m v f (Var v) = handleVar m v f (Neg x) = handleNeg m (f x) f (And x y) = handleAnd m (f x) (f y) f (Or x y) = handleOr m (f x) (f y) f (Imp x y) = handleImp m (f x) (f y) f (Iff x y) = handleIff m (f x) (f y) f (Box x) = handleBox m (f x) f (Dia x) = handleDia m (f x) allVars :: ModalFormula v -> [v] allVars = modalEval ModalEvaluator { handleVal = const [], handleVar = pure, handleNeg = id, handleAnd = (++), handleOr = (++), handleImp = (++), handleIff = (++), handleBox = id, handleDia = id } data ShowFormula = ShowFormula { topSymbol :: String, botSymbol :: String, negSymbol :: String, andSymbol :: String, orSymbol :: String, impSymbol :: String, iffSymbol :: String, boxSymbol :: String, diaSymbol :: String } deriving (Eq, Ord, Read, Show) showFormula :: Show v => ShowFormula -> Int -> ModalFormula v -> ShowS showFormula sf = showsFormula where showsFormula p f = case f of Val l -> showString $ if l then topSymbol sf else botSymbol sf Var v -> showString $ show v Neg x -> showParen (p > 8) $ showUnary (negSymbol sf) 8 x And x y -> showParen (p > 7) $ showBinary (andSymbol sf) 7 x 8 y Or x y -> showParen (p > 6) $ showBinary (orSymbol sf) 6 x 7 y Imp x y -> showParen (p > 5) $ showBinary (impSymbol sf) 6 x 5 y Iff x y -> showParen (p > 4) $ showBinary (iffSymbol sf) 5 x 4 y Box x -> showParen (p > 8) $ showUnary (boxSymbol sf) 8 x Dia x -> showParen (p > 8) $ showUnary (diaSymbol sf) 8 x padded o = showString " " . showString o . showString " " showUnary o i x = showString o . showsFormula i x showBinary o l x r y = showsFormula l x . padded o . showsFormula r y instance Show v => Show (ModalFormula v) where showsPrec = showFormula (ShowFormula "⊤" "⊥" "¬" "∧" "∨" "→" "↔" "□" "◇") -------------------------------------------------------------------------------- instance Read v => Parsable (ModalFormula v) where parser = mformulaParser read mformulaParser :: (String -> v) -> Parsec Text s (ModalFormula v) mformulaParser reader = buildExpressionParser table term <?> "ModalFormula" where table = [ [ prefix $ choice [ m_reservedOp "¬" >> return Neg , m_reservedOp "~" >> return Neg , m_reservedOp "□" >> return Box , m_reservedOp "[]" >> return Box , m_reservedOp "[0]" >> return Box , m_reservedOp "[1]" >> return (boxk 1) , m_reservedOp "[2]" >> return (boxk 2) , m_reservedOp "[3]" >> return (boxk 3) , m_reservedOp "[4]" >> return (boxk 4) , m_reservedOp "[5]" >> return (boxk 5) , m_reservedOp "[6]" >> return (boxk 6) , m_reservedOp "[7]" >> return (boxk 7) , m_reservedOp "[8]" >> return (boxk 8) , m_reservedOp "[9]" >> return (boxk 9) , m_reservedOp "◇" >> return Dia , m_reservedOp "<>" >> return Dia , m_reservedOp "<0>" >> return Dia , m_reservedOp "<1>" >> return (diak 1) , m_reservedOp "<2>" >> return (diak 2) , m_reservedOp "<3>" >> return (diak 3) , m_reservedOp "<4>" >> return (diak 4) , m_reservedOp "<5>" >> return (diak 5) , m_reservedOp "<6>" >> return (diak 6) , m_reservedOp "<7>" >> return (diak 7) , m_reservedOp "<8>" >> return (diak 8) , m_reservedOp "<9>" >> return (diak 9) ] ] , [ Infix (m_reservedOp "∧" >> return And) AssocLeft , Infix (m_reservedOp "&&" >> return And) AssocLeft ] , [ Infix (m_reservedOp "∨" >> return Or) AssocLeft , Infix (m_reservedOp "||" >> return Or) AssocLeft ] , [ Infix (m_reservedOp "→" >> return Imp) AssocRight , Infix (m_reservedOp "->" >> return Imp) AssocRight ] , [ Infix (m_reservedOp "↔" >> return Iff) AssocRight , Infix (m_reservedOp "<->" >> return Iff) AssocRight ] ] term = m_parens (mformulaParser reader) <|> m_braces (mformulaParser reader) <|> (m_reserved "⊤" >> return (Val True)) <|> (m_reserved "T" >> return (Val True)) <|> (m_reserved "⊥" >> return (Val False)) <|> (m_reserved "F" >> return (Val False)) <|> fmap (Var . reader) m_identifier -- To work-around Parsec's limitation for prefix operators: prefix p = Prefix . chainl1 p $ return (.) TokenParser { parens = m_parens , braces = m_braces , identifier = m_identifier , reservedOp = m_reservedOp , reserved = m_reserved , semiSep1 = _ , whiteSpace = _ } = makeTokenParser emptyDef { commentStart = "{-" , commentEnd = "-}" , identStart = satisfy isNameFirstChar , identLetter = satisfy isNameChar , opStart = oneOf "~-<[&|¬□◇→↔∨∧" , opLetter = oneOf "->]&|123456789" , reservedOpNames = [ "¬", "∧", "∨", "→", "↔", "□", "◇" , "~", "&&", "||", "->", "<->", "[]", "<>" , "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", "[8]", "[9]" , "<1>", "<2>", "<3>", "<4>", "<5>", "<6>", "<7>", "<8>", "<9>" ] , reservedNames = ["T", "F", "⊤", "⊥"] , caseSensitive = False } instance Read v => Read (ModalFormula v) where readsPrec _ s = case parse (parser <* eof) "reading formula" (T.pack s) of Right result -> [(result,"")] -- We could just return the remaining string, but Parsec gives -- much nicer errors. So we ask it to consume the whole input and -- fail if it fails. Left err -> error $ show err -------------------------------------------------------------------------------- -- Note: Code not dead; just not yet used. isModalized :: ModalFormula v -> Bool isModalized = modalEval ModalEvaluator { handleVar = const False, handleVal = const True, handleNeg = id, handleAnd = (&&), handleOr = (&&), handleImp = (&&), handleIff = (&&), handleBox = const True, handleDia = const True } -- Nesting Depth of Modal Operators maxModalDepthHandler :: ModalEvaluator v Int maxModalDepthHandler = ModalEvaluator { handleVal = const 0, handleVar = const 0, handleNeg = id, handleAnd = max, handleOr = max, handleImp = max, handleIff = max, handleBox = (1+), handleDia = (1+)} maxModalDepth :: ModalFormula v -> Int maxModalDepth = modalEval maxModalDepthHandler -- How to simplify modal formulas: mapFormulaOutput :: (Bool -> Bool) -> ModalFormula v -> ModalFormula v mapFormulaOutput f formula = g (f False) (f True) where g True True = Val True g False False = Val False g False True = formula g True False = Neg formula simplifyBinaryOperator :: (ModalFormula v -> ModalFormula v -> ModalFormula v) -> (Bool -> Bool -> Bool) -> ModalFormula v -> ModalFormula v -> ModalFormula v simplifyBinaryOperator _ behavior (Val a) (Val b) = Val (behavior a b) simplifyBinaryOperator _ behavior (Val a) formula = mapFormulaOutput (behavior a) formula simplifyBinaryOperator _ behavior formula (Val b) = mapFormulaOutput (`behavior` b) formula simplifyBinaryOperator op _ f1 f2 = op f1 f2 simplifyNeg :: ModalFormula v -> ModalFormula v simplifyNeg (Val v) = Val (not v) simplifyNeg (Neg x) = x simplifyNeg x = Neg x simplifyBox :: ModalFormula v -> ModalFormula v simplifyBox t@(Val True) = t simplifyBox x = Box x simplifyDia :: ModalFormula v -> ModalFormula v simplifyDia f@(Val False) = f simplifyDia x = Dia x simplifyHandler :: ModalEvaluator v (ModalFormula v) simplifyHandler = ModalEvaluator { handleVal = Val, handleVar = Var, handleNeg = simplifyNeg, handleAnd = simplifyBinaryOperator And (&&), handleOr = simplifyBinaryOperator Or (||), handleImp = simplifyBinaryOperator Imp (<=), handleIff = simplifyBinaryOperator Iff (==), handleBox = simplifyBox, handleDia = simplifyDia } simplify :: ModalFormula v -> ModalFormula v simplify = modalEval simplifyHandler -- GL Eval in standard model glEvalHandler :: ModalEvaluator v [Bool] glEvalHandler = ModalEvaluator { handleVal = repeat, handleVar = error "Variables are not supported in GLEval", handleNeg = fmap not, handleAnd = zipWith (&&), handleOr = zipWith (||), handleImp = zipWith (<=), handleIff = zipWith (==), handleBox = scanl (&&) True, handleDia = scanl (||) False } -- The reason we don't combine this with the above is because that would induce -- an Ord constraint on v unnecessarily. glEvalHandlerWithVars :: (Show v, Ord v) => Map v [Bool] -> ModalEvaluator v [Bool] glEvalHandlerWithVars m = glEvalHandler{ handleVar = \var -> fromMaybe (unmapped var) (var `M.lookup` m)} where unmapped var = error $ "Unmapped variable in GLEval: " ++ show var glEvalWithVars :: (Show v, Ord v) => Map v [Bool] -> ModalFormula v -> [Bool] glEvalWithVars = modalEval . glEvalHandlerWithVars glEvalWithVarsStandard :: (Show v, Ord v) => Map v [Bool] -> ModalFormula v -> Bool glEvalWithVarsStandard m f = glEvalWithVars m f !! maxModalDepth f glEval :: ModalFormula v -> [Bool] glEval = modalEval glEvalHandler glEvalStandard :: ModalFormula v -> Bool glEvalStandard f = glEval f !! maxModalDepth f simplifiedMaxDepth :: ModalFormula v -> Int simplifiedMaxDepth formula = depth - length (head $ group $ reverse results) + 1 where results = take (depth+1) (glEval formula) depth = maxModalDepth formula fixpointGLEval :: (Show v, Eq v) => v -> ModalFormula v -> [Bool] fixpointGLEval var fi = result where unmapped = error . ("Non-fixpoint-variable used in fixpointGLEval: " ++) . show evalHandler = glEvalHandler{handleVar = \var' -> if var == var' then result else unmapped var'} result = modalEval evalHandler fi generalFixpointGLEval :: (Show v, Ord v) => Map v (ModalFormula v) -> Map v [Bool] generalFixpointGLEval formulaMap = evalMap where unmapped var = error $ "Unmapped variable in generalFixpointGLEval: " ++ show var evalHandler = glEvalHandler{handleVar = \var -> fromMaybe (unmapped var) (M.lookup var evalMap)} evalMap = M.map (modalEval evalHandler) formulaMap -- Finding the fixedpoints -- Check whether the length of a list is at least n without infinite looping. lengthAtLeast :: Int -> [a] -> Bool lengthAtLeast 0 _ = True lengthAtLeast _ [] = False lengthAtLeast n (_:xs) = lengthAtLeast (n-1) xs -- TODO: infinite loop fixpointDepth :: (Eq a) => Int -> [a] -> Int fixpointDepth n xs = 1 + countSkipped 0 (group xs) where countSkipped acc [] = acc countSkipped acc (g:gs) | lengthAtLeast n g = acc | otherwise = countSkipped (acc + length g) gs -- Find the fixpoint of a list, given a length of run after which we should conclude we found it. findFixpoint :: (Eq a) => Int -> [a] -> a findFixpoint n xs = (!!0) $ fromJust $ find (lengthAtLeast n) $ group xs -- Find the Fixpoint for a Modal formula findGLFixpoint :: (Show v, Eq v) => v -> ModalFormula v -> Bool findGLFixpoint var formula = findFixpoint (1 + maxModalDepth formula) (fixpointGLEval var formula) -- Find the Fixpoint for a collection of Modal formulas makeEquivs :: (Ord v, Read v) => [(String, String)] -> Map v (ModalFormula v) makeEquivs = M.fromList . map (read *** read) generalGLEvalSeq :: (Show v, Ord v) => Map v (ModalFormula v)-> [Map v Bool] generalGLEvalSeq formulaMap = map level [0..] where level n = M.map (!!n) result result = generalFixpointGLEval formulaMap findGeneralGLFixpoint :: (Eq v, Show v, Ord v) => Map v (ModalFormula v) -> Map v Bool findGeneralGLFixpoint formulaMap = findFixpoint (1 + maxFormulaDepth) results where results = generalGLEvalSeq formulaMap maxFormulaDepth = maximum $ map maxModalDepth $ M.elems formulaMap -- Display code to help visualize the kripke frames kripkeFrames :: (Eq v, Show v, Ord v) => Map v (ModalFormula v) -> Map v [Bool] kripkeFrames formulaMap = M.map (take (2 + fixPointer)) results where results = generalFixpointGLEval formulaMap mapList = generalGLEvalSeq formulaMap maxFormulaDepth = maximum $ map maxModalDepth $ M.elems formulaMap fixPointer = fixpointDepth (1 + maxFormulaDepth) mapList kripkeTable' :: (Show k, Ord k) => [k] -> Map k (ModalFormula k) -> Table kripkeTable' ks = toTable . kripkeFrames where toTable m = listmapToTable ks $ M.map (map boolify) m boolify = show . (Val :: Bool -> ModalFormula ()) kripkeTable :: (Show k, Ord k) => Map k (ModalFormula k) -> Table kripkeTable m = kripkeTable' (M.keys m) m kripkeTableFiltered :: (Show k, Ord k) => (k -> Bool) -> Map k (ModalFormula k) -> Table kripkeTableFiltered f m = kripkeTable' (filter f $ M.keys m) m displayKripkeFrames :: (Show k, Ord k) => Map k (ModalFormula k) -> IO () displayKripkeFrames = displayTable . kripkeTable
daniel-ziegler/provability
src/Modal/Formulas.hs
bsd-3-clause
16,257
0
16
3,728
5,727
3,031
2,696
337
10
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- {-# LANGUAGE ExistentialQuantification, GADTs #-} module Copilot.Compile.C99.C2A ( c2aExpr , c2aType ) where import qualified Copilot.Compile.C99.Queue as Q import qualified Copilot.Compile.C99.Witness as W import Copilot.Compile.C99.MetaTable import Copilot.Core (Op1 (..), Op2 (..), Op3 (..)) import Copilot.Core.Error (impossible) import qualified Copilot.Core as C import Copilot.Core.Type.Equality ((=~=), coerce, cong) import Data.Map (Map) import qualified Data.Map as M import qualified Language.Atom as A import qualified Prelude as P import Prelude hiding (id) -------------------------------------------------------------------------------- c2aExpr :: MetaTable -> C.Expr a -> A.E a c2aExpr meta e = c2aExpr_ e M.empty meta -------------------------------------------------------------------------------- c2aType :: C.Type a -> A.Type c2aType t = case t of C.Bool -> A.Bool C.Int8 -> A.Int8 ; C.Int16 -> A.Int16 C.Int32 -> A.Int32 ; C.Int64 -> A.Int64 C.Word8 -> A.Word8 ; C.Word16 -> A.Word16 C.Word32 -> A.Word32 ; C.Word64 -> A.Word64 C.Float -> A.Float ; C.Double -> A.Double -------------------------------------------------------------------------------- data Local = forall a . Local { localAtomExpr :: A.E a , localType :: C.Type a } type Env = Map C.Name Local -------------------------------------------------------------------------------- c2aExpr_ :: C.Expr a -> Env -> MetaTable -> A.E a c2aExpr_ e0 env meta = case e0 of ---------------------------------------------------- C.Const _ x -> A.Const x ---------------------------------------------------- C.Drop t i id -> let Just strmInfo = M.lookup id (streamInfoMap meta) in drop1 t strmInfo where drop1 :: C.Type a -> StreamInfo -> A.E a drop1 t1 StreamInfo { streamInfoQueue = que , streamInfoType = t2 } = let Just p = t2 =~= t1 in case W.exprInst t2 of W.ExprInst -> coerce (cong p) (Q.lookahead (fromIntegral i) que) ---------------------------------------------------- C.Local t1 _ name e1 e2 -> let e1' = c2aExpr_ e1 env meta in let env' = M.insert name (Local e1' t1) env in c2aExpr_ e2 env' meta ---------------------------------------------------- C.Var t1 name -> let Just local = M.lookup name env in case local of Local { localAtomExpr = e , localType = t2 } -> let Just p = t2 =~= t1 in case W.exprInst t2 of W.ExprInst -> coerce (cong p) e ---------------------------------------------------- C.ExternVar t name _ -> let Just externInfo = M.lookup name (externInfoMap meta) in externVar1 t externInfo where externVar1 :: C.Type a -> ExternInfo -> A.E a externVar1 t1 ExternInfo { externInfoVar = v , externInfoType = t2 } = let Just p = t2 =~= t1 in coerce (cong p) (A.value v) ---------------------------------------------------- C.ExternFun t name _ _ maybeTag -> let tag = case maybeTag of Nothing -> impossible "c2aExpr_ /ExternFun" "copilot-c99" Just tg -> tg in let Just extFunInfo = M.lookup (name, tag) (externFunInfoMap meta) in externFun1 t extFunInfo where externFun1 t1 ExternFunInfo { externFunInfoVar = var , externFunInfoType = t2 } = let Just p = t2 =~= t1 in case W.exprInst t2 of W.ExprInst -> coerce (cong p) (A.value var) ---------------------------------------------------- C.ExternArray _ t name _ _ _ maybeTag -> let tag = case maybeTag of Nothing -> impossible "c2aExpr_ /ExternArray" "copilot-c99" Just tg -> tg in let Just extArrayInfo = M.lookup (name, tag) (externArrayInfoMap meta) in externArray1 t extArrayInfo where externArray1 t1 ExternArrayInfo { externArrayInfoVar = var , externArrayInfoElemType = t2 } = let Just p = t2 =~= t1 in case W.exprInst t2 of W.ExprInst -> coerce (cong p) (A.value var) ---------------------------------------------------- C.Op1 op e -> c2aOp1 op (c2aExpr_ e env meta) ---------------------------------------------------- C.Op2 op e1 e2 -> c2aOp2 op (c2aExpr_ e1 env meta) (c2aExpr_ e2 env meta) ---------------------------------------------------- C.Op3 op e1 e2 e3 -> c2aOp3 op (c2aExpr_ e1 env meta) (c2aExpr_ e2 env meta) (c2aExpr_ e3 env meta) ---------------------------------------------------- c2aOp1 :: C.Op1 a b -> A.E a -> A.E b c2aOp1 op = case op of Not -> A.not_ Abs t -> case W.numEInst t of W.NumEInst -> abs Sign t -> case W.numEInst t of W.NumEInst -> signum Recip t -> case W.numEInst t of W.NumEInst -> recip Exp t -> case W.floatingEInst t of W.FloatingEInst -> exp Sqrt t -> case W.floatingEInst t of W.FloatingEInst -> sqrt Log t -> case W.floatingEInst t of W.FloatingEInst -> log Sin t -> case W.floatingEInst t of W.FloatingEInst -> sin Tan t -> case W.floatingEInst t of W.FloatingEInst -> tan Cos t -> case W.floatingEInst t of W.FloatingEInst -> cos Asin t -> case W.floatingEInst t of W.FloatingEInst -> asin Atan t -> case W.floatingEInst t of W.FloatingEInst -> atan Acos t -> case W.floatingEInst t of W.FloatingEInst -> acos Sinh t -> case W.floatingEInst t of W.FloatingEInst -> sinh Tanh t -> case W.floatingEInst t of W.FloatingEInst -> tanh Cosh t -> case W.floatingEInst t of W.FloatingEInst -> cosh Asinh t -> case W.floatingEInst t of W.FloatingEInst -> asinh Atanh t -> case W.floatingEInst t of W.FloatingEInst -> atanh Acosh t -> case W.floatingEInst t of W.FloatingEInst -> acosh BwNot t -> case W.bitsEInst t of W.BitsEInst -> (A.complement) Cast C.Bool C.Bool -> P.id Cast C.Bool t -> case W.numEInst t of W.NumEInst -> \e -> A.mux e (A.Const 1) (A.Const 0) Cast t0 t1 -> case W.numEInst t0 of W.NumEInst -> case W.numEInst t1 of W.NumEInst -> A.Cast c2aOp2 :: C.Op2 a b c -> A.E a -> A.E b -> A.E c c2aOp2 op = case op of And -> (A.&&.) Or -> (A.||.) Add t -> case W.numEInst t of W.NumEInst -> (+) Sub t -> case W.numEInst t of W.NumEInst -> (-) Mul t -> case W.numEInst t of W.NumEInst -> (*) Div t -> case W.integralEInst t of W.IntegralEInst -> A.div_ Mod t -> case W.integralEInst t of W.IntegralEInst -> A.mod_ Fdiv t -> case W.numEInst t of W.NumEInst -> (/) Pow t -> case W.floatingEInst t of W.FloatingEInst -> (**) Logb t -> case W.floatingEInst t of W.FloatingEInst -> logBase Eq t -> case W.eqEInst t of W.EqEInst -> (A.==.) Ne t -> case W.eqEInst t of W.EqEInst -> (A./=.) Le t -> case W.ordEInst t of W.OrdEInst -> (A.<=.) Ge t -> case W.ordEInst t of W.OrdEInst -> (A.>=.) Lt t -> case W.ordEInst t of W.OrdEInst -> (A.<.) Gt t -> case W.ordEInst t of W.OrdEInst -> (A.>.) BwAnd t -> case W.bitsEInst t of W.BitsEInst -> (A..&.) BwOr t -> case W.bitsEInst t of W.BitsEInst -> (A..|.) BwXor t -> case W.bitsEInst t of W.BitsEInst -> (A.xor) BwShiftL t t' -> case ( W.bitsEInst t, W.integralEInst t' ) of ( W.BitsEInst, W.IntegralEInst ) -> (A..<<.) BwShiftR t t' -> case ( W.bitsEInst t, W.integralEInst t' ) of ( W.BitsEInst, W.IntegralEInst ) -> (A..>>.) c2aOp3 :: C.Op3 a b c d -> A.E a -> A.E b -> A.E c -> A.E d c2aOp3 op = case op of Mux t -> case W.exprInst t of W.ExprInst -> A.mux
leepike/copilot-c99
src/Copilot/Compile/C99/C2A.hs
bsd-3-clause
8,479
113
26
2,547
2,543
1,347
1,196
165
23
-- | -- Module : Control.Monad.Numeric -- Copyright : (c) 2011 Aleksey Khudyakov -- License : BSD3 -- -- Maintainer : Aleksey Khudyakov <[email protected]> -- Stability : experimental -- Portability : portable -- -- Function useful for writing numeric code which works with mutable -- data. module Control.Monad.Numeric ( forGen , for ) where -- | For function which act much like for loop in the C forGen :: Monad m => a -- ^ Staring index value -> (a -> Bool) -- ^ Condition -> (a -> a) -- ^ Function to modify index -> (a -> m ()) -- ^ Action to perform -> m () forGen n test next a = worker n where worker i | test i = a i >> worker (next i) | otherwise = return () {-# INLINE forGen #-} -- | Specialized for loop. Akin to: -- -- > for( i = 0; i < 10; i++) { ... for :: Monad m => Int -- ^ Starting index -> Int -- ^ Maximal index value not reached -> (Int -> m ()) -- ^ Action to perfor, -> m () for i maxI a = worker i where worker j | j < maxI = a j >> worker (j+1) | otherwise = return () {-# INLINE for #-}
KevinCotrone/numeric-tools
Control/Monad/Numeric.hs
bsd-3-clause
1,243
0
13
438
271
143
128
22
1
{-# LANGUAGE CPP #-} module Eta.TypeCheck.TcInteract ( solveSimpleGivens, -- Solves [EvVar],GivenLoc solveSimpleWanteds, -- Solves Cts solveCallStack, -- for use in TcSimplify ) where import Eta.BasicTypes.BasicTypes () import Eta.HsSyn.HsTypes ( HsIPName(..) ) import Eta.Utils.FastString import qualified Eta.TypeCheck.TcCanonical as TcCanonical import Eta.TypeCheck.TcCanonical import Eta.TypeCheck.TcFlatten import Eta.BasicTypes.VarSet import Eta.Types.Type import qualified Eta.Types.Type as Type import Eta.Types.Kind (isKind, isConstraintKind ) import Eta.Types.Unify import Eta.Types.InstEnv( lookupInstEnv, instanceDFunId ) import Eta.Types.CoAxiom(sfInteractTop, sfInteractInert) import qualified Eta.LanguageExtensions as LangExt import Eta.BasicTypes.Var import Eta.TypeCheck.TcType import Eta.Prelude.PrelNames ( knownNatClassName, knownSymbolClassName, typeableClassName ) import Eta.Prelude.TysWiredIn ( ipClass ) import Eta.BasicTypes.Id( idType ) import Eta.Types.Class import Eta.Types.TyCon import Eta.TypeCheck.FunDeps import Eta.TypeCheck.FamInst import Eta.TypeCheck.Inst( tyVarsOfCt ) import Eta.TypeCheck.TcEvidence import Eta.Utils.Outputable import Eta.TypeCheck.TcRnTypes import Eta.TypeCheck.TcErrors import Eta.TypeCheck.TcSMonad import Eta.Utils.Bag import Data.List( partition, foldl', deleteFirstsBy ) import Eta.BasicTypes.VarEnv import Control.Monad import Eta.Utils.Pair (Pair(..)) import Eta.Main.DynFlags import Eta.Utils.Util #include "HsVersions.h" {- ********************************************************************** * * * Main Interaction Solver * * * ********************************************************************** Note [Basic Simplifier Plan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Pick an element from the WorkList if there exists one with depth less than our context-stack depth. 2. Run it down the 'stage' pipeline. Stages are: - canonicalization - inert reactions - spontaneous reactions - top-level intreactions Each stage returns a StopOrContinue and may have sideffected the inerts or worklist. The threading of the stages is as follows: - If (Stop) is returned by a stage then we start again from Step 1. - If (ContinueWith ct) is returned by a stage, we feed 'ct' on to the next stage in the pipeline. 4. If the element has survived (i.e. ContinueWith x) the last stage then we add him in the inerts and jump back to Step 1. If in Step 1 no such element exists, we have exceeded our context-stack depth and will simply fail. Note [Unflatten after solving the simple wanteds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We unflatten after solving the wc_simples of an implication, and before attempting to float. This means that * The fsk/fmv flatten-skolems only survive during solveSimples. We don't need to worry about then across successive passes over the constraint tree. (E.g. we don't need the old ic_fsk field of an implication. * When floating an equality outwards, we don't need to worry about floating its associated flattening constraints. * Another tricky case becomes easy: Trac #4935 type instance F True a b = a type instance F False a b = b [w] F c a b ~ gamma (c ~ True) => a ~ gamma (c ~ False) => b ~ gamma Obviously this is soluble with gamma := F c a b, and unflattening will do exactly that after solving the simple constraints and before attempting the implications. Before, when we were not unflattening, we had to push Wanted funeqs in as new givens. Yuk! Another example that becomes easy: indexed_types/should_fail/T7786 [W] BuriedUnder sub k Empty ~ fsk [W] Intersect fsk inv ~ s [w] xxx[1] ~ s [W] forall[2] . (xxx[1] ~ Empty) => Intersect (BuriedUnder sub k Empty) inv ~ Empty Note [Running plugins on unflattened wanteds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is an annoying mismatch between solveSimpleGivens and solveSimpleWanteds, because the latter needs to fiddle with the inert set, unflatten and and zonk the wanteds. It passes the zonked wanteds to runTcPluginsWanteds, which produces a replacement set of wanteds, some additional insolubles and a flag indicating whether to go round the loop again. If so, prepareInertsForImplications is used to remove the previous wanteds (which will still be in the inert set). Note that prepareInertsForImplications will discard the insolubles, so we must keep track of them separately. -} solveSimpleGivens :: CtLoc -> [EvVar] -> TcS () solveSimpleGivens loc givens | null givens -- Shortcut for common case = return () | otherwise = go (map mk_given_ct givens) where mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evtm = EvId ev_id , ctev_pred = evVarPred ev_id , ctev_loc = loc }) go givens = do { solveSimples (listToBag givens) ; new_givens <- runTcPluginsGiven ; when (notNull new_givens) (go new_givens) } solveSimpleWanteds :: Cts -> TcS WantedConstraints solveSimpleWanteds = go emptyBag where go insols0 wanteds = do { solveSimples wanteds ; (implics, tv_eqs, fun_eqs, insols, others) <- getUnsolvedInerts ; unflattened_eqs <- unflatten tv_eqs fun_eqs -- See Note [Unflatten after solving the simple wanteds] ; zonked <- zonkSimples (others `andCts` unflattened_eqs) -- Postcondition is that the wl_simples are zonked ; (wanteds', insols', rerun) <- runTcPluginsWanted zonked -- See Note [Running plugins on unflattened wanteds] ; let all_insols = insols0 `unionBags` insols `unionBags` insols' ; if rerun then do { updInertTcS prepareInertsForImplications ; go all_insols wanteds' } else return (WC { wc_simple = wanteds' , wc_insol = all_insols , wc_impl = implics }) } -- The main solver loop implements Note [Basic Simplifier Plan] --------------------------------------------------------------- solveSimples :: Cts -> TcS () -- Returns the final InertSet in TcS -- Has no effect on work-list or residual-iplications -- The constraints are initially examined in left-to-right order solveSimples cts = {-# SCC "solveSimples" #-} do { dyn_flags <- getDynFlags ; updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts) ; solve_loop dyn_flags (maxSubGoalDepth dyn_flags) } where solve_loop dyn_flags max_depth = {-# SCC "solve_loop" #-} do { sel <- selectNextWorkItem max_depth ; case sel of NoWorkRemaining -- Done, successfuly (modulo frozen) -> do dicts <- getUnsolvedInertDicts new_work <- getUniqueInstanceWanteds dyn_flags dicts if null new_work then return () else do updWorkListTcS (extendWorkListCts new_work) solve_loop dyn_flags max_depth MaxDepthExceeded cnt ct -- Failure, depth exceeded -> wrapErrTcS $ solverDepthErrorTcS cnt (ctEvidence ct) NextWorkItem ct -- More work, loop around! -> do { runSolverPipeline thePipeline ct; solve_loop dyn_flags max_depth } } -- | Extract the (inert) givens and invoke the plugins on them. -- Remove solved givens from the inert set and emit insolubles, but -- return new work produced so that 'solveSimpleGivens' can feed it back -- into the main solver. runTcPluginsGiven :: TcS [Ct] runTcPluginsGiven = do (givens,_,_) <- fmap splitInertCans getInertCans if null givens then return [] else do p <- runTcPlugins (givens,[],[]) let (solved_givens, _, _) = pluginSolvedCts p updInertCans (removeInertCts solved_givens) mapM_ emitInsoluble (pluginBadCts p) return (pluginNewCts p) -- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on -- them and produce an updated bag of wanteds (possibly with some new -- work) and a bag of insolubles. The boolean indicates whether -- 'solveSimpleWanteds' should feed the updated wanteds back into the -- main solver. runTcPluginsWanted :: Cts -> TcS (Cts, Cts, Bool) runTcPluginsWanted zonked_wanteds | isEmptyBag zonked_wanteds = return (zonked_wanteds, emptyBag, False) | otherwise = do (given,derived,_) <- fmap splitInertCans getInertCans p <- runTcPlugins (given, derived, bagToList zonked_wanteds) let (solved_givens, solved_deriveds, solved_wanteds) = pluginSolvedCts p (_, _, wanteds) = pluginInputCts p updInertCans (removeInertCts $ solved_givens ++ solved_deriveds) mapM_ setEv solved_wanteds return ( listToBag $ pluginNewCts p ++ wanteds , listToBag $ pluginBadCts p , notNull (pluginNewCts p) ) where setEv :: (EvTerm,Ct) -> TcS () setEv (ev,ct) = case ctEvidence ct of CtWanted {ctev_evar = evar} -> setEvBind evar ev _ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!" -- | A triple of (given, derived, wanted) constraints to pass to plugins type SplitCts = ([Ct], [Ct], [Ct]) -- | A solved triple of constraints, with evidence for wanteds type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)]) -- | Represents collections of constraints generated by typechecker -- plugins data TcPluginProgress = TcPluginProgress { pluginInputCts :: SplitCts -- ^ Original inputs to the plugins with solved/bad constraints -- removed, but otherwise unmodified , pluginSolvedCts :: SolvedCts -- ^ Constraints solved by plugins , pluginBadCts :: [Ct] -- ^ Constraints reported as insoluble by plugins , pluginNewCts :: [Ct] -- ^ New constraints emitted by plugins } -- | Starting from a triple of (given, derived, wanted) constraints, -- invoke each of the typechecker plugins in turn and return -- -- * the remaining unmodified constraints, -- * constraints that have been solved, -- * constraints that are insoluble, and -- * new work. -- -- Note that new work generated by one plugin will not be seen by -- other plugins on this pass (but the main constraint solver will be -- re-invoked and they will see it later). There is no check that new -- work differs from the original constraints supplied to the plugin: -- the plugin itself should perform this check if necessary. runTcPlugins :: SplitCts -> TcS TcPluginProgress runTcPlugins all_cts = do gblEnv <- getGblEnv foldM do_plugin initialProgress (tcg_tc_plugins gblEnv) where do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress do_plugin p solver = do result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p)) return $ progress p result progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress progress p (TcPluginContradiction bad_cts) = p { pluginInputCts = discard bad_cts (pluginInputCts p) , pluginBadCts = bad_cts ++ pluginBadCts p } progress p (TcPluginOk solved_cts new_cts) = p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p) , pluginSolvedCts = add solved_cts (pluginSolvedCts p) , pluginNewCts = new_cts ++ pluginNewCts p } initialProgress = TcPluginProgress all_cts ([], [], []) [] [] discard :: [Ct] -> SplitCts -> SplitCts discard cts (xs, ys, zs) = (xs `without` cts, ys `without` cts, zs `without` cts) without :: [Ct] -> [Ct] -> [Ct] without = deleteFirstsBy eqCt eqCt :: Ct -> Ct -> Bool eqCt c c' = case (ctEvidence c, ctEvidence c') of (CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred' (CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred' (CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred' (_ , _ ) -> False add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts add xs scs = foldl' addOne scs xs addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of CtGiven {} -> (ct:givens, deriveds, wanteds) CtDerived{} -> (givens, ct:deriveds, wanteds) CtWanted {} -> (givens, deriveds, (ev,ct):wanteds) type WorkItem = Ct type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct) data SelectWorkItem = NoWorkRemaining -- No more work left (effectively we're done!) | MaxDepthExceeded SubGoalCounter Ct -- More work left to do but this constraint has exceeded -- the maximum depth for one of the subgoal counters and we -- must stop | NextWorkItem Ct -- More work left, here's the next item to look at selectNextWorkItem :: SubGoalDepth -- Max depth allowed -> TcS SelectWorkItem selectNextWorkItem max_depth = updWorkListTcS_return pick_next where pick_next :: WorkList -> (SelectWorkItem, WorkList) pick_next wl = case selectWorkItem wl of (Nothing,_) -> (NoWorkRemaining,wl) -- No more work (Just ct, new_wl) | Just cnt <- subGoalDepthExceeded max_depth (ctLocDepth (ctLoc ct)) -- Depth exceeded -> (MaxDepthExceeded cnt ct,new_wl) (Just ct, new_wl) -> (NextWorkItem ct, new_wl) -- New workitem and worklist runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline -> WorkItem -- The work item -> TcS () -- Run this item down the pipeline, leaving behind new work and inerts runSolverPipeline pipeline workItem = do { initial_is <- getTcSInerts ; traceTcS "Start solver pipeline {" $ vcat [ ptext (sLit "work item = ") <+> ppr workItem , ptext (sLit "inerts = ") <+> ppr initial_is] ; bumpStepCountTcS -- One step for each constraint processed ; final_res <- run_pipeline pipeline (ContinueWith workItem) ; final_is <- getTcSInerts ; case final_res of Stop ev s -> do { traceFireTcS ev s ; traceTcS "End solver pipeline (discharged) }" (ptext (sLit "inerts =") <+> ppr final_is) ; return () } ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert")) ; traceTcS "End solver pipeline (not discharged) }" $ vcat [ ptext (sLit "final_item =") <+> ppr ct , pprTvBndrs (varSetElems $ tyVarsOfCt ct) , ptext (sLit "inerts =") <+> ppr final_is] ; insertInertItemTcS ct } } where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct -> TcS (StopOrContinue Ct) run_pipeline [] res = return res run_pipeline _ (Stop ev s) = return (Stop ev s) run_pipeline ((stg_name,stg):stgs) (ContinueWith ct) = do { traceTcS ("runStage " ++ stg_name ++ " {") (text "workitem = " <+> ppr ct) ; res <- stg ct ; traceTcS ("end stage " ++ stg_name ++ " }") empty ; run_pipeline stgs res } {- Example 1: Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given) Reagent: a ~ [b] (given) React with (c~d) ==> IR (ContinueWith (a~[b])) True [] React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t] React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True [] Example 2: Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty} Reagent: a ~w [b] React with (c ~w d) ==> IR (ContinueWith (a~[b])) True [] React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!) etc. Example 3: Inert: {a ~ Int, F Int ~ b} (given) Reagent: F a ~ b (wanted) React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True [] React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing -} thePipeline :: [(String,SimplifierStage)] thePipeline = [ ("canonicalization", TcCanonical.canonicalize) , ("interact with inerts", interactWithInertsStage) , ("top-level reactions", topReactionsStage) ] {- ********************************************************************************* * * The interact-with-inert Stage * * ********************************************************************************* Note [The Solver Invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ We always add Givens first. So you might think that the solver has the invariant If the work-item is Given, then the inert item must Given But this isn't quite true. Suppose we have, c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int After processing the first two, we get c1: [G] beta ~ [alpha], c2 : [W] blah Now, c3 does not interact with the the given c1, so when we spontaneously solve c3, we must re-react it with the inert set. So we can attempt a reaction between inert c2 [W] and work-item c3 [G]. It *is* true that [Solver Invariant] If the work-item is Given, AND there is a reaction then the inert item must Given or, equivalently, If the work-item is Given, and the inert item is Wanted/Derived then there is no reaction -} -- Interaction result of WorkItem <~> Ct type StopNowFlag = Bool -- True <=> stop after this interaction interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct) -- Precondition: if the workitem is a CTyEqCan then it will not be able to -- react with anything at this stage. interactWithInertsStage wi = do { inerts <- getTcSInerts ; let ics = inert_cans inerts ; case wi of CTyEqCan {} -> interactTyVarEq ics wi CFunEqCan {} -> interactFunEq ics wi CIrredEvCan {} -> interactIrred ics wi CDictCan {} -> interactDict ics wi _ -> pprPanic "interactWithInerts" (ppr wi) } -- CHoleCan are put straight into inert_frozen, so never get here -- CNonCanonical have been canonicalised data InteractResult = IRKeep | IRReplace | IRDelete instance Outputable InteractResult where ppr IRKeep = ptext (sLit "keep") ppr IRReplace = ptext (sLit "replace") ppr IRDelete = ptext (sLit "delete") solveOneFromTheOther :: CtEvidence -- Inert -> CtEvidence -- WorkItem -> TcS (InteractResult, StopNowFlag) -- Preconditions: -- 1) inert and work item represent evidence for the /same/ predicate -- 2) ip/class/irred evidence (no coercions) only solveOneFromTheOther ev_i ev_w | isDerived ev_w = return (IRKeep, True) | isDerived ev_i -- The inert item is Derived, we can just throw it away, -- The ev_w is inert wrt earlier inert-set items, -- so it's safe to continue on from this point = return (IRDelete, False) | CtWanted { ctev_evar = ev_id } <- ev_w = do { setEvBind ev_id (ctEvTerm ev_i) ; return (IRKeep, True) } | CtWanted { ctev_evar = ev_id } <- ev_i = do { setEvBind ev_id (ctEvTerm ev_w) ; return (IRReplace, True) } | otherwise -- If both are Given, we already have evidence; no need to duplicate -- But the work item *overrides* the inert item (hence IRReplace) -- See Note [Shadowing of Implicit Parameters] = return (IRReplace, True) {- ********************************************************************************* * * interactIrred * * ********************************************************************************* -} -- Two pieces of irreducible evidence: if their types are *exactly identical* -- we can rewrite them. We can never improve using this: -- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not -- mean that (ty1 ~ ty2) interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct) interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w }) | let pred = ctEvPred ev_w (matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred) (inert_irreds inerts) , (ct_i : rest) <- bagToList matching_irreds , let ctev_i = ctEvidence ct_i = ASSERT( null rest ) do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w ; case inert_effect of IRKeep -> return () IRDelete -> updInertIrreds (\_ -> others) IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem) -- These const upd's assume that solveOneFromTheOther -- has no side effects on InertCans ; if stop_now then return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect))) ; else continueWith workItem } | otherwise = continueWith workItem interactIrred _ wi = pprPanic "interactIrred" (ppr wi) {- ********************************************************************************* * * interactDict * * ********************************************************************************* -} interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct) interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys }) | isWanted ev_w , Just ip_name <- isCallStackPred (ctPred workItem) , OccurrenceOf func <- ctLocOrigin (ctEvLoc ev_w) -- If we're given a CallStack constraint that arose from a function -- call, we need to push the current call-site onto the stack instead -- of solving it directly from a given. -- See Note [Overview of implicit CallStacks] = do { let loc = ctEvLoc ev_w -- First we emit a new constraint that will capture the -- given CallStack. ; let new_loc = setCtLocOrigin loc (IPOccOrigin (HsIPName ip_name)) -- We change the origin to IPOccOrigin so -- this rule does not fire again. -- See Note [Overview of implicit CallStacks] ; mb_new <- newWantedEvVar new_loc (ctEvPred ev_w) ; emitWorkNC (freshGoals [mb_new]) -- Then we solve the wanted by pushing the call-site onto the -- newly emitted CallStack. ; let ev_cs = EvCsPushCall func (ctLocSpan loc) (ctEvTerm $ fst mb_new) ; solveCallStack ev_w ev_cs ; stopWith ev_w "Wanted CallStack IP" } | Just ctev_i <- lookupInertDict inerts (ctEvLoc ev_w) cls tys = do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w ; case inert_effect of IRKeep -> return () IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem ; if stop_now then return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect))) else continueWith workItem } | cls == ipClass , isGiven ev_w = interactGivenIP inerts workItem | otherwise = do { mapBagM_ (addFunDepWork workItem) (findDictsByClass (inert_dicts inerts) cls) -- Standard thing: create derived fds and keep on going. Importantly we don't -- throw workitem back in the worklist because this can cause loops (see #5236) ; continueWith workItem } interactDict _ wi = pprPanic "interactDict" (ppr wi) interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- Work item is Given (?x:ty) -- See Note [Shadowing of Implicit Parameters] interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls , cc_tyargs = tys@(ip_str:_) }) = do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem } ; stopWith ev "Given IP" } where dicts = inert_dicts inerts ip_dicts = findDictsByClass dicts cls other_ip_dicts = filterBag (not . is_this_ip) ip_dicts filtered_dicts = addDictsByClass dicts cls other_ip_dicts -- Pick out any Given constraints for the same implicit parameter is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ }) = isGiven ev && ip_str `tcEqType` ip_str' is_this_ip _ = False interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi) addFunDepWork :: Ct -> Ct -> TcS () addFunDepWork work_ct inert_ct = do { let fd_eqns :: [Equation CtLoc] fd_eqns = [ eqn { fd_loc = derived_loc } | eqn <- improveFromAnother inert_pred work_pred ] ; rewriteWithFunDeps fd_eqns -- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok -- NB: We do create FDs for given to report insoluble equations that arise -- from pairs of Givens, and also because of floating when we approximate -- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs -- Also see Note [When improvement happens] } where work_pred = ctPred work_ct inert_pred = ctPred inert_ct work_loc = ctLoc work_ct inert_loc = ctLoc inert_ct derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc inert_pred inert_loc } {- Note [Shadowing of Implicit Parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the following example: f :: (?x :: Char) => Char f = let ?x = 'a' in ?x The "let ?x = ..." generates an implication constraint of the form: ?x :: Char => ?x :: Char Furthermore, the signature for `f` also generates an implication constraint, so we end up with the following nested implication: ?x :: Char => (?x :: Char => ?x :: Char) Note that the wanted (?x :: Char) constraint may be solved in two incompatible ways: either by using the parameter from the signature, or by using the local definition. Our intention is that the local definition should "shadow" the parameter of the signature, and we implement this as follows: when we add a new *given* implicit parameter to the inert set, it replaces any existing givens for the same implicit parameter. This works for the normal cases but it has an odd side effect in some pathological programs like this: -- This is accepted, the second parameter shadows f1 :: (?x :: Int, ?x :: Char) => Char f1 = ?x -- This is rejected, the second parameter shadows f2 :: (?x :: Int, ?x :: Char) => Int f2 = ?x Both of these are actually wrong: when we try to use either one, we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char), which would lead to an error. I can think of two ways to fix this: 1. Simply disallow multiple constratits for the same implicit parameter---this is never useful, and it can be detected completely syntactically. 2. Move the shadowing machinery to the location where we nest implications, and add some code here that will produce an error if we get multiple givens for the same implicit parameter. ********************************************************************************* * * interactFunEq * * ********************************************************************************* -} interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- Try interacting the work item with the inert set interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc , cc_tyargs = args, cc_fsk = fsk }) | Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts = if ev_i `canRewriteOrSame` ev then -- Rewrite work-item using inert do { traceTcS "reactFunEq (discharge work item):" $ vcat [ text "workItem =" <+> ppr workItem , text "inertItem=" <+> ppr ev_i ] ; reactFunEq ev_i fsk_i ev fsk ; stopWith ev "Inert rewrites work item" } else -- Rewrite intert using work-item do { traceTcS "reactFunEq (rewrite inert item):" $ vcat [ text "workItem =" <+> ppr workItem , text "inertItem=" <+> ppr ev_i ] ; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem -- Do the updInertFunEqs before the reactFunEq, so that -- we don't kick out the inertItem as well as consuming it! ; reactFunEq ev fsk ev_i fsk_i ; stopWith ev "Work item rewrites inert" } | Just ops <- isBuiltInSynFamTyCon_maybe tc = do { let matching_funeqs = findFunEqsByTyCon funeqs tc ; let interact = sfInteractInert ops args (lookupFlattenTyVar eqs fsk) do_one (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk, cc_ev = iev }) = mapM_ (unifyDerived (ctEvLoc iev) Nominal) (interact iargs (lookupFlattenTyVar eqs ifsk)) do_one ct = pprPanic "interactFunEq" (ppr ct) ; mapM_ do_one matching_funeqs ; traceTcS "builtInCandidates 1: " $ vcat [ ptext (sLit "Candidates:") <+> ppr matching_funeqs , ptext (sLit "TvEqs:") <+> ppr eqs ] ; return (ContinueWith workItem) } | otherwise = return (ContinueWith workItem) where eqs = inert_eqs inerts funeqs = inert_funeqs inerts matching_inerts = findFunEqs funeqs tc args interactFunEq _ wi = pprPanic "interactFunEq" (ppr wi) lookupFlattenTyVar :: TyVarEnv EqualCtList -> TcTyVar -> TcType -- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs; -- this is used only when dealing with a CFunEqCan lookupFlattenTyVar inert_eqs ftv = case lookupVarEnv inert_eqs ftv of Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq } : _) -> rhs _ -> mkTyVarTy ftv reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1 -> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2 -> TcS () reactFunEq from_this fsk1 (CtGiven { ctev_evtm = tm, ctev_loc = loc }) fsk2 = do { let fsk_eq_co = mkTcSymCo (evTermCoercion tm) `mkTcTransCo` ctEvCoercion from_this -- :: fsk2 ~ fsk1 fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1) ; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co) ; emitWorkNC [new_ev] } reactFunEq from_this fuv1 (CtWanted { ctev_evar = evar }) fuv2 = dischargeFmv evar fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1) reactFunEq _ _ solve_this@(CtDerived {}) _ = pprPanic "reactFunEq" (ppr solve_this) {- Note [Cache-caused loops] ~~~~~~~~~~~~~~~~~~~~~~~~~ It is very dangerous to cache a rewritten wanted family equation as 'solved' in our solved cache (which is the default behaviour or xCtEvidence), because the interaction may not be contributing towards a solution. Here is an example: Initial inert set: [W] g1 : F a ~ beta1 Work item: [W] g2 : F a ~ beta2 The work item will react with the inert yielding the _same_ inert set plus: i) Will set g2 := g1 `cast` g3 ii) Will add to our solved cache that [S] g2 : F a ~ beta2 iii) Will emit [W] g3 : beta1 ~ beta2 Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2 and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it will set g1 := g ; sym g3 and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but remember that we have this in our solved cache, and it is ... g2! In short we created the evidence loop: g2 := g1 ; g3 g3 := refl g1 := g2 ; sym g3 To avoid this situation we do not cache as solved any workitems (or inert) which did not really made a 'step' towards proving some goal. Solved's are just an optimization so we don't lose anything in terms of completeness of solving. Note [Efficient Orientation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we are interacting two FunEqCans with the same LHS: (inert) ci :: (F ty ~ xi_i) (work) cw :: (F ty ~ xi_w) We prefer to keep the inert (else we pass the work item on down the pipeline, which is a bit silly). If we keep the inert, we will (a) discharge 'cw' (b) produce a new equality work-item (xi_w ~ xi_i) Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w): new_work :: xi_w ~ xi_i cw := ci ; sym new_work Why? Consider the simplest case when xi1 is a type variable. If we generate xi1~xi2, porcessing that constraint will kick out 'ci'. If we generate xi2~xi1, there is less chance of that happening. Of course it can and should still happen if xi1=a, xi1=Int, say. But we want to avoid it happening needlessly. Similarly, if we *can't* keep the inert item (because inert is Wanted, and work is Given, say), we prefer to orient the new equality (xi_i ~ xi_w). Note [Carefully solve the right CFunEqCan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ---- OLD COMMENT, NOW NOT NEEDED ---- because we now allow multiple ---- wanted FunEqs with the same head Consider the constraints c1 :: F Int ~ a -- Arising from an application line 5 c2 :: F Int ~ Bool -- Arising from an application line 10 Suppose that 'a' is a unification variable, arising only from flattening. So there is no error on line 5; it's just a flattening variable. But there is (or might be) an error on line 10. Two ways to combine them, leaving either (Plan A) c1 :: F Int ~ a -- Arising from an application line 5 c3 :: a ~ Bool -- Arising from an application line 10 or (Plan B) c2 :: F Int ~ Bool -- Arising from an application line 10 c4 :: a ~ Bool -- Arising from an application line 5 Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error on the *totally innocent* line 5. An example is test SimpleFail16 where the expected/actual message comes out backwards if we use the wrong plan. The second is the right thing to do. Hence the isMetaTyVarTy test when solving pairwise CFunEqCan. ********************************************************************************* * * interactTyVarEq * * ********************************************************************************* -} interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- CTyEqCans are always consumed, so always returns Stop interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv , cc_rhs = rhs , cc_ev = ev , cc_eq_rel = eq_rel }) | (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i } <- findTyEqs inerts tv , ev_i `canRewriteOrSame` ev , rhs_i `tcEqType` rhs ] = -- Inert: a ~ b -- Work item: a ~ b do { when (isWanted ev) $ setEvBind (ctev_evar ev) (ctEvTerm ev_i) ; stopWith ev "Solved from inert" } | Just tv_rhs <- getTyVar_maybe rhs , (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i } <- findTyEqs inerts tv_rhs , ev_i `canRewriteOrSame` ev , rhs_i `tcEqType` mkTyVarTy tv ] = -- Inert: a ~ b -- Work item: b ~ a do { when (isWanted ev) $ setEvBind (ctev_evar ev) (EvCoercion (mkTcSymCo (ctEvCoercion ev_i))) ; stopWith ev "Solved from inert (r)" } | otherwise = do { tclvl <- getTcLevel ; if canSolveByUnification tclvl ev eq_rel tv rhs then do { solveByUnification ev tv rhs ; n_kicked <- kickOutRewritable Given NomEq tv -- Given because the tv := xi is given -- NomEq because only nom. equalities are solved -- by unification ; return (Stop ev (ptext (sLit "Spontaneously solved") <+> ppr_kicked n_kicked)) } else do { traceTcS "Can't solve tyvar equality" (vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv) , ppWhen (isMetaTyVar tv) $ nest 4 (text "TcLevel of" <+> ppr tv <+> text "is" <+> ppr (metaTyVarTcLevel tv)) , text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs) , text "TcLevel =" <+> ppr tclvl ]) ; n_kicked <- kickOutRewritable (ctEvFlavour ev) (ctEvEqRel ev) tv ; updInertCans (\ ics -> addInertCan ics workItem) ; return (Stop ev (ptext (sLit "Kept as inert") <+> ppr_kicked n_kicked)) } } interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi) -- @trySpontaneousSolve wi@ solves equalities where one side is a -- touchable unification variable. -- Returns True <=> spontaneous solve happened canSolveByUnification :: TcLevel -> CtEvidence -> EqRel -> TcTyVar -> Xi -> Bool canSolveByUnification tclvl gw eq_rel tv xi | ReprEq <- eq_rel -- we never solve representational equalities this way. = False | isGiven gw -- See Note [Touchables and givens] = False | isTouchableMetaTyVar tclvl tv = case metaTyVarInfo tv of SigTv -> is_tyvar xi _ -> True | otherwise -- Untouchable = False where is_tyvar xi = case tcGetTyVar_maybe xi of Nothing -> False Just tv -> case tcTyVarDetails tv of MetaTv { mtv_info = info } -> case info of SigTv -> True _ -> False SkolemTv {} -> True FlatSkol {} -> False RuntimeUnk -> True solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS () -- Solve with the identity coercion -- Precondition: kind(xi) is a sub-kind of kind(tv) -- Precondition: CtEvidence is Wanted or Derived -- Precondition: CtEvidence is nominal -- See [New Wanted Superclass Work] to see why solveByUnification -- must work for Derived as well as Wanted -- Returns: workItem where -- workItem = the new Given constraint -- -- NB: No need for an occurs check here, because solveByUnification always -- arises from a CTyEqCan, a *canonical* constraint. Its invariants -- say that in (a ~ xi), the type variable a does not appear in xi. -- See TcRnTypes.Ct invariants. -- -- Post: tv is unified (by side effect) with xi; -- we often write tv := xi solveByUnification wd tv xi = do { let tv_ty = mkTyVarTy tv ; traceTcS "Sneaky unification:" $ vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi, text "Coercion:" <+> pprEq tv_ty xi, text "Left Kind is:" <+> ppr (typeKind tv_ty), text "Right Kind is:" <+> ppr (typeKind xi) ] ; let xi' = defaultKind xi -- We only instantiate kind unification variables -- with simple kinds like *, not OpenKind or ArgKind -- cf TcUnify.uUnboundKVar ; setWantedTyBind tv xi' ; when (isWanted wd) $ setEvBind (ctEvId wd) (EvCoercion (mkTcNomReflCo xi')) } ppr_kicked :: Int -> SDoc ppr_kicked 0 = empty ppr_kicked n = parens (int n <+> ptext (sLit "kicked out")) kickOutRewritable :: CtFlavour -- Flavour of the equality that is -- being added to the inert set -> EqRel -- of the new equality -> TcTyVar -- The new equality is tv ~ ty -> TcS Int kickOutRewritable new_flavour new_eq_rel new_tv | not ((new_flavour, new_eq_rel) `eqCanRewriteFR` (new_flavour, new_eq_rel)) = return 0 -- If new_flavour can't rewrite itself, it can't rewrite -- anything else, so no need to kick out anything -- This is a common case: wanteds can't rewrite wanteds | otherwise = do { ics <- getInertCans ; let (kicked_out, ics') = kick_out new_flavour new_eq_rel new_tv ics ; setInertCans ics' ; updWorkListTcS (appendWorkList kicked_out) ; unless (isEmptyWorkList kicked_out) $ csTraceTcS $ hang (ptext (sLit "Kick out, tv =") <+> ppr new_tv) 2 (vcat [ text "n-kicked =" <+> int (workListSize kicked_out) , text "n-kept fun-eqs =" <+> int (sizeFunEqMap (inert_funeqs ics')) , ppr kicked_out ]) ; return (workListSize kicked_out) } kick_out :: CtFlavour -> EqRel -> TcTyVar -> InertCans -> (WorkList, InertCans) kick_out new_flavour new_eq_rel new_tv (IC { inert_eqs = tv_eqs , inert_dicts = dictmap , inert_funeqs = funeqmap , inert_irreds = irreds , inert_insols = insols }) = (kicked_out, inert_cans_in) where -- NB: Notice that don't rewrite -- inert_solved_dicts, and inert_solved_funeqs -- optimistically. But when we lookup we have to -- take the substitution into account inert_cans_in = IC { inert_eqs = tv_eqs_in , inert_dicts = dicts_in , inert_funeqs = feqs_in , inert_irreds = irs_in , inert_insols = insols_in } kicked_out = WL { wl_eqs = tv_eqs_out , wl_funeqs = feqs_out , wl_rest = bagToList (dicts_out `andCts` irs_out `andCts` insols_out) , wl_implics = emptyBag } (tv_eqs_out, tv_eqs_in) = foldVarEnv kick_out_eqs ([], emptyVarEnv) tv_eqs (feqs_out, feqs_in) = partitionFunEqs kick_out_ct funeqmap (dicts_out, dicts_in) = partitionDicts kick_out_ct dictmap (irs_out, irs_in) = partitionBag kick_out_irred irreds (insols_out, insols_in) = partitionBag kick_out_ct insols -- Kick out even insolubles; see Note [Kick out insolubles] can_rewrite :: CtEvidence -> Bool can_rewrite = ((new_flavour, new_eq_rel) `eqCanRewriteFR`) . ctEvFlavourRole kick_out_ct :: Ct -> Bool kick_out_ct ct = kick_out_ctev (ctEvidence ct) kick_out_ctev :: CtEvidence -> Bool kick_out_ctev ev = can_rewrite ev && new_tv `elemVarSet` tyVarsOfType (ctEvPred ev) -- See Note [Kicking out inert constraints] kick_out_irred :: Ct -> Bool kick_out_irred ct = can_rewrite (cc_ev ct) && new_tv `elemVarSet` closeOverKinds (tyVarsOfCt ct) -- See Note [Kicking out Irreds] kick_out_eqs :: EqualCtList -> ([Ct], TyVarEnv EqualCtList) -> ([Ct], TyVarEnv EqualCtList) kick_out_eqs eqs (acc_out, acc_in) = (eqs_out ++ acc_out, case eqs_in of [] -> acc_in (eq1:_) -> extendVarEnv acc_in (cc_tyvar eq1) eqs_in) where (eqs_in, eqs_out) = partition keep_eq eqs -- implements criteria K1-K3 in Note [The inert equalities] in TcFlatten keep_eq (CTyEqCan { cc_tyvar = tv, cc_rhs = rhs_ty, cc_ev = ev , cc_eq_rel = eq_rel }) | tv == new_tv = not (can_rewrite ev) -- (K1) | otherwise = check_k2 && check_k3 where check_k2 = not (ev `eqCanRewrite` ev) || not (can_rewrite ev) || not (new_tv `elemVarSet` tyVarsOfType rhs_ty) check_k3 | can_rewrite ev = case eq_rel of NomEq -> not (rhs_ty `eqType` mkTyVarTy new_tv) ReprEq -> not (isTyVarExposed new_tv rhs_ty) | otherwise = True keep_eq ct = pprPanic "keep_eq" (ppr ct) {- Note [Kicking out inert constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given a new (a -> ty) inert, we want to kick out an existing inert constraint if a) the new constraint can rewrite the inert one b) 'a' is free in the inert constraint (so that it *will*) rewrite it if we kick it out. For (b) we use tyVarsOfCt, which returns the type variables /and the kind variables/ that are directly visible in the type. Hence we will have exposed all the rewriting we care about to make the most precise kinds visible for matching classes etc. No need to kick out constraints that mention type variables whose kinds contain this variable! (Except see Note [Kicking out Irreds].) Note [Kicking out Irreds] ~~~~~~~~~~~~~~~~~~~~~~~~~ There is an awkward special case for Irreds. When we have a kind-mis-matched equality constraint (a:k1) ~ (ty:k2), we turn it into an Irred (see Note [Equalities with incompatible kinds] in TcCanonical). So in this case the free kind variables of k1 and k2 are not visible. More precisely, the type looks like (~) k1 (a:k1) (ty:k2) because (~) has kind forall k. k -> k -> Constraint. So the constraint itself is ill-kinded. We can "see" k1 but not k2. That's why we use closeOverKinds to make sure we see k2. This is not pretty. Maybe (~) should have kind (~) :: forall k1 k1. k1 -> k2 -> Constraint Note [Kick out insolubles] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have an insoluble alpha ~ [alpha], which is insoluble because an occurs check. And then we unify alpha := [Int]. Then we really want to rewrite the insouluble to [Int] ~ [[Int]]. Now it can be decomposed. Otherwise we end up with a "Can't match [Int] ~ [[Int]]" which is true, but a bit confusing because the outer type constructors match. Note [Avoid double unifications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The spontaneous solver has to return a given which mentions the unified unification variable *on the left* of the equality. Here is what happens if not: Original wanted: (a ~ alpha), (alpha ~ Int) We spontaneously solve the first wanted, without changing the order! given : a ~ alpha [having unified alpha := a] Now the second wanted comes along, but he cannot rewrite the given, so we simply continue. At the end we spontaneously solve that guy, *reunifying* [alpha := Int] We avoid this problem by orienting the resulting given so that the unification variable is on the left. [Note that alternatively we could attempt to enforce this at canonicalization] See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding double unifications is the main reason we disallow touchable unification variables as RHS of type family equations: F xis ~ alpha. Note [Superclasses and recursive dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Overlaps with Note [SUPERCLASS-LOOP 1] Note [SUPERCLASS-LOOP 2] Note [Recursive instances and superclases] ToDo: check overlap and delete redundant stuff Right before adding a given into the inert set, we must produce some more work, that will bring the superclasses of the given into scope. The superclass constraints go into our worklist. When we simplify a wanted constraint, if we first see a matching instance, we may produce new wanted work. To (1) avoid doing this work twice in the future and (2) to handle recursive dictionaries we may ``cache'' this item as given into our inert set WITHOUT adding its superclass constraints, otherwise we'd be in danger of creating a loop [In fact this was the exact reason for doing the isGoodRecEv check in an older version of the type checker]. But now we have added partially solved constraints to the worklist which may interact with other wanteds. Consider the example: Example 1: class Eq b => Foo a b --- 0-th selector instance Eq a => Foo [a] a --- fooDFun and wanted (Foo [t] t). We are first going to see that the instance matches and create an inert set that includes the solved (Foo [t] t) but not its superclasses: d1 :_g Foo [t] t d1 := EvDFunApp fooDFun d3 Our work list is going to contain a new *wanted* goal d3 :_w Eq t Ok, so how do we get recursive dictionaries, at all: Example 2: data D r = ZeroD | SuccD (r (D r)); instance (Eq (r (D r))) => Eq (D r) where ZeroD == ZeroD = True (SuccD a) == (SuccD b) = a == b _ == _ = False; equalDC :: D [] -> D [] -> Bool; equalDC = (==); We need to prove (Eq (D [])). Here's how we go: d1 :_w Eq (D []) by instance decl, holds if d2 :_w Eq [D []] where d1 = dfEqD d2 *BUT* we have an inert set which gives us (no superclasses): d1 :_g Eq (D []) By the instance declaration of Eq we can show the 'd2' goal if d3 :_w Eq (D []) where d2 = dfEqList d3 d1 = dfEqD d2 Now, however this wanted can interact with our inert d1 to set: d3 := d1 and solve the goal. Why was this interaction OK? Because, if we chase the evidence of d1 ~~> dfEqD d2 ~~-> dfEqList d3, so by setting d3 := d1 we are really setting d3 := dfEqD2 (dfEqList d3) which is FINE because the use of d3 is protected by the instance function applications. So, our strategy is to try to put solved wanted dictionaries into the inert set along with their superclasses (when this is meaningful, i.e. when new wanted goals are generated) but solve a wanted dictionary from a given only in the case where the evidence variable of the wanted is mentioned in the evidence of the given (recursively through the evidence binds) in a protected way: more instance function applications than superclass selectors. Here are some more examples from GHC's previous type checker Example 3: This code arises in the context of "Scrap Your Boilerplate with Class" class Sat a class Data ctx a instance Sat (ctx Char) => Data ctx Char -- dfunData1 instance (Sat (ctx [a]), Data ctx a) => Data ctx [a] -- dfunData2 class Data Maybe a => Foo a instance Foo t => Sat (Maybe t) -- dfunSat instance Data Maybe a => Foo a -- dfunFoo1 instance Foo a => Foo [a] -- dfunFoo2 instance Foo [Char] -- dfunFoo3 Consider generating the superclasses of the instance declaration instance Foo a => Foo [a] So our problem is this [G] d0 : Foo t [W] d1 : Data Maybe [t] -- Desired superclass We may add the given in the inert set, along with its superclasses [assuming we don't fail because there is a matching instance, see topReactionsStage, given case ] Inert: [G] d0 : Foo t [G] d01 : Data Maybe t -- Superclass of d0 WorkList [W] d1 : Data Maybe [t] Solve d1 using instance dfunData2; d1 := dfunData2 d2 d3 Inert: [G] d0 : Foo t [G] d01 : Data Maybe t -- Superclass of d0 Solved: d1 : Data Maybe [t] WorkList [W] d2 : Sat (Maybe [t]) [W] d3 : Data Maybe t Now, we may simplify d2 using dfunSat; d2 := dfunSat d4 Inert: [G] d0 : Foo t [G] d01 : Data Maybe t -- Superclass of d0 Solved: d1 : Data Maybe [t] d2 : Sat (Maybe [t]) WorkList: [W] d3 : Data Maybe t [W] d4 : Foo [t] Now, we can just solve d3 from d01; d3 := d01 Inert [G] d0 : Foo t [G] d01 : Data Maybe t -- Superclass of d0 Solved: d1 : Data Maybe [t] d2 : Sat (Maybe [t]) WorkList [W] d4 : Foo [t] Now, solve d4 using dfunFoo2; d4 := dfunFoo2 d5 Inert [G] d0 : Foo t [G] d01 : Data Maybe t -- Superclass of d0 Solved: d1 : Data Maybe [t] d2 : Sat (Maybe [t]) d4 : Foo [t] WorkList: [W] d5 : Foo t Now, d5 can be solved! d5 := d0 Result d1 := dfunData2 d2 d3 d2 := dfunSat d4 d3 := d01 d4 := dfunFoo2 d5 d5 := d0 d0 :_g Foo t d1 :_s Data Maybe [t] d1 := dfunData2 d2 d3 d2 :_g Sat (Maybe [t]) d2 := dfunSat d4 d4 :_g Foo [t] d4 := dfunFoo2 d5 d5 :_g Foo t d5 := dfunFoo1 d7 WorkList: d7 :_w Data Maybe t d6 :_g Data Maybe [t] d8 :_g Data Maybe t d8 := EvDictSuperClass d5 0 d01 :_g Data Maybe t Now, two problems: [1] Suppose we pick d8 and we react him with d01. Which of the two givens should we keep? Well, we *MUST NOT* drop d01 because d8 contains recursive evidence that must not be used (look at case interactInert where both inert and workitem are givens). So we have several options: - Drop the workitem always (this will drop d8) This feels very unsafe -- what if the work item was the "good" one that should be used later to solve another wanted? - Don't drop anyone: the inert set may contain multiple givens! [This is currently implemented] The "don't drop anyone" seems the most safe thing to do, so now we come to problem 2: [2] We have added both d6 and d01 in the inert set, and we are interacting our wanted d7. Now the [isRecDictEv] function in the ineration solver [case inert-given workitem-wanted] will prevent us from interacting d7 := d8 precisely because chasing the evidence of d8 leads us to an unguarded use of d7. So, no interaction happens there. Then we meet d01 and there is no recursion problem there [isRectDictEv] gives us the OK to interact and we do solve d7 := d01! Note [SUPERCLASS-LOOP 1] ~~~~~~~~~~~~~~~~~~~~~~~~ We have to be very, very careful when generating superclasses, lest we accidentally build a loop. Here's an example: class S a class S a => C a where { opc :: a -> a } class S b => D b where { opd :: b -> b } instance C Int where opc = opd instance D Int where opd = opc From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int} Simplifying, we may well get: $dfCInt = :C ds1 (opd dd) dd = $dfDInt ds1 = $p1 dd Notice that we spot that we can extract ds1 from dd. Alas! Alack! We can do the same for (instance D Int): $dfDInt = :D ds2 (opc dc) dc = $dfCInt ds2 = $p1 dc And now we've defined the superclass in terms of itself. Two more nasty cases are in tcrun021 tcrun033 Solution: - Satisfy the superclass context *all by itself* (tcSimplifySuperClasses) - And do so completely; i.e. no left-over constraints to mix with the constraints arising from method declarations Note [SUPERCLASS-LOOP 2] ~~~~~~~~~~~~~~~~~~~~~~~~ We need to be careful when adding "the constaint we are trying to prove". Suppose we are *given* d1:Ord a, and want to deduce (d2:C [a]) where class Ord a => C a where instance Ord [a] => C [a] where ... Then we'll use the instance decl to deduce C [a] from Ord [a], and then add the superclasses of C [a] to avails. But we must not overwrite the binding for Ord [a] (which is obtained from Ord a) with a superclass selection or we'll just build a loop! Here's another variant, immortalised in tcrun020 class Monad m => C1 m class C1 m => C2 m x instance C2 Maybe Bool For the instance decl we need to build (C1 Maybe), and it's no good if we run around and add (C2 Maybe Bool) and its superclasses to the avails before we search for C1 Maybe. Here's another example class Eq b => Foo a b instance Eq a => Foo [a] a If we are reducing (Foo [t] t) we'll first deduce that it holds (via the instance decl). We must not then overwrite the Eq t constraint with a superclass selection! At first I had a gross hack, whereby I simply did not add superclass constraints in addWanted, though I did for addGiven and addIrred. This was sub-optimal, because it lost legitimate superclass sharing, and it still didn't do the job: I found a very obscure program (now tcrun021) in which improvement meant the simplifier got two bites a the cherry... so something seemed to be an Stop first time, but reducible next time. Now we implement the Right Solution, which is to check for loops directly when adding superclasses. It's a bit like the occurs check in unification. Note [Recursive instances and superclases] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this code, which arises in the context of "Scrap Your Boilerplate with Class". class Sat a class Data ctx a instance Sat (ctx Char) => Data ctx Char instance (Sat (ctx [a]), Data ctx a) => Data ctx [a] class Data Maybe a => Foo a instance Foo t => Sat (Maybe t) instance Data Maybe a => Foo a instance Foo a => Foo [a] instance Foo [Char] In the instance for Foo [a], when generating evidence for the superclasses (ie in tcSimplifySuperClasses) we need a superclass (Data Maybe [a]). Using the instance for Data, we therefore need (Sat (Maybe [a], Data Maybe a) But we are given (Foo a), and hence its superclass (Data Maybe a). So that leaves (Sat (Maybe [a])). Using the instance for Sat means we need (Foo [a]). And that is the very dictionary we are bulding an instance for! So we must put that in the "givens". So in this case we have Given: Foo a, Foo [a] Wanted: Data Maybe [a] BUT we must *not not not* put the *superclasses* of (Foo [a]) in the givens, which is what 'addGiven' would normally do. Why? Because (Data Maybe [a]) is the superclass, so we'd "satisfy" the wanted by selecting a superclass from Foo [a], which simply makes a loop. On the other hand we *must* put the superclasses of (Foo a) in the givens, as you can see from the derivation described above. Conclusion: in the very special case of tcSimplifySuperClasses we have one 'given' (namely the "this" dictionary) whose superclasses must not be added to 'givens' by addGiven. There is a complication though. Suppose there are equalities instance (Eq a, a~b) => Num (a,b) Then we normalise the 'givens' wrt the equalities, so the original given "this" dictionary is cast to one of a different type. So it's a bit trickier than before to identify the "special" dictionary whose superclasses must not be added. See test indexed-types/should_run/EqInInstance We need a persistent property of the dictionary to record this special-ness. Current I'm using the InstLocOrigin (a bit of a hack, but cool), which is maintained by dictionary normalisation. Specifically, the InstLocOrigin is NoScOrigin then the no-superclass thing kicks in. WATCH OUT if you fiddle with InstLocOrigin! ************************************************************************ * * * Functional dependencies, instantiation of equations * * ************************************************************************ When we spot an equality arising from a functional dependency, we now use that equality (a "wanted") to rewrite the work-item constraint right away. This avoids two dangers Danger 1: If we send the original constraint on down the pipeline it may react with an instance declaration, and in delicate situations (when a Given overlaps with an instance) that may produce new insoluble goals: see Trac #4952 Danger 2: If we don't rewrite the constraint, it may re-react with the same thing later, and produce the same equality again --> termination worries. To achieve this required some refactoring of FunDeps.lhs (nicer now!). -} rewriteWithFunDeps :: [Equation CtLoc] -> TcS () -- NB: The returned constraints are all Derived -- Post: returns no trivial equalities (identities) and all EvVars returned are fresh rewriteWithFunDeps eqn_pred_locs = mapM_ instFunDepEqn eqn_pred_locs instFunDepEqn :: Equation CtLoc -> TcS () -- Post: Returns the position index as well as the corresponding FunDep equality instFunDepEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc }) = do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution ; mapM_ (do_one subst) eqs } where do_one subst (FDEq { fd_ty_left = ty1, fd_ty_right = ty2 }) = unifyDerived loc Nominal $ Pair (Type.substTy subst ty1) (Type.substTy subst ty2) {- ********************************************************************************* * * The top-reaction Stage * * ********************************************************************************* -} topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct) topReactionsStage wi = do { inerts <- getTcSInerts ; tir <- doTopReact inerts wi ; case tir of ContinueWith wi -> return (ContinueWith wi) Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) } doTopReact :: InertSet -> WorkItem -> TcS (StopOrContinue Ct) -- The work item does not react with the inert set, so try interaction with top-level -- instances. Note: -- -- (a) The place to add superclasses in not here in doTopReact stage. -- Instead superclasses are added in the worklist as part of the -- canonicalization process. See Note [Adding superclasses]. -- -- (b) See Note [Given constraint that matches an instance declaration] -- for some design decisions for given dictionaries. doTopReact inerts work_item = do { traceTcS "doTopReact" (ppr work_item) ; case work_item of CDictCan {} -> doTopReactDict inerts work_item CFunEqCan {} -> doTopReactFunEq work_item _ -> -- Any other work item does not react with any top-level equations return (ContinueWith work_item) } -------------------- doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct) -- Try to use type-class instance declarations to simplify the constraint doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls , cc_tyargs = xis }) | not (isWanted fl) -- Never use instances for Given or Derived constraints = try_fundeps_and_return | Just ev <- lookupSolvedDict inerts loc cls xis -- Cached = do { setEvBind dict_id (ctEvTerm ev); ; stopWith fl "Dict/Top (cached)" } | otherwise -- Not cached = do { lkup_inst_res <- matchClassInst inerts cls xis loc ; case lkup_inst_res of GenInst wtvs ev_term -> do { addSolvedDict fl cls xis ; solve_from_instance wtvs ev_term } NoInstance -> try_fundeps_and_return } where dict_id = ASSERT( isWanted fl ) ctEvId fl pred = mkClassPred cls xis loc = ctEvLoc fl solve_from_instance :: [CtEvidence] -> EvTerm -> TcS (StopOrContinue Ct) -- Precondition: evidence term matches the predicate workItem solve_from_instance evs ev_term | null evs = do { traceTcS "doTopReact/found nullary instance for" $ ppr dict_id ; setEvBind dict_id ev_term ; stopWith fl "Dict/Top (solved, no new work)" } | otherwise = do { traceTcS "doTopReact/found non-nullary instance for" $ ppr dict_id ; setEvBind dict_id ev_term ; let mk_new_wanted ev = mkNonCanonical (ev {ctev_loc = bumpCtLocDepth CountConstraints loc }) ; updWorkListTcS (extendWorkListCts (map mk_new_wanted evs)) ; stopWith fl "Dict/Top (solved, more work)" } -- We didn't solve it; so try functional dependencies with -- the instance environment, and return -- NB: even if there *are* some functional dependencies against the -- instance environment, there might be a unique match, and if -- so we make sure we get on and solve it first. See Note [Weird fundeps] try_fundeps_and_return = do { instEnvs <- getInstEnvs ; let fd_eqns :: [Equation CtLoc] fd_eqns = [ fd { fd_loc = loc { ctl_origin = FunDepOrigin2 pred (ctl_origin loc) inst_pred inst_loc } } | fd@(FDEqn { fd_loc = inst_loc, fd_pred1 = inst_pred }) <- improveFromInstEnv instEnvs pred ] ; rewriteWithFunDeps fd_eqns ; continueWith work_item } doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w) -------------------- doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct) doTopReactFunEq work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc , cc_tyargs = args , cc_fsk = fsk }) = ASSERT(isTypeFamilyTyCon fam_tc) -- No associated data families -- have reached this far ASSERT( not (isDerived old_ev) ) -- CFunEqCan is never Derived -- Look up in top-level instances, or built-in axiom do { match_res <- matchFam fam_tc args -- See Note [MATCHING-SYNONYMS] ; case match_res of { Nothing -> do { try_improvement; continueWith work_item } ; Just (ax_co, rhs_ty) -- Found a top-level instance | Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty , isTypeFamilyTyCon tc , tc_args `lengthIs` tyConArity tc -- Short-cut -> shortCutReduction old_ev fsk ax_co tc tc_args -- Try shortcut; see Note [Short cut for top-level reaction] | isGiven old_ev -- Not shortcut -> do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co -- final_co :: fsk ~ rhs_ty ; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty, EvCoercion final_co) ; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty ; stopWith old_ev "Fun/Top (given)" } | not (fsk `elemVarSet` tyVarsOfType rhs_ty) -> do { dischargeFmv (ctEvId old_ev) fsk ax_co rhs_ty ; traceTcS "doTopReactFunEq" $ vcat [ text "old_ev:" <+> ppr old_ev , nest 2 (text ":=") <+> ppr ax_co ] ; stopWith old_ev "Fun/Top (wanted)" } | otherwise -- We must not assign ufsk := ...ufsk...! -> do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk) ; new_ev <- newWantedEvVarNC loc (mkTcEqPred alpha_ty rhs_ty) ; emitWorkNC [new_ev] -- By emitting this as non-canonical, we deal with all -- flattening, occurs-check, and ufsk := ufsk issues ; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev) -- ax_co :: fam_tc args ~ rhs_ty -- ev :: alpha ~ rhs_ty -- ufsk := alpha -- final_co :: fam_tc args ~ alpha ; dischargeFmv (ctEvId old_ev) fsk final_co alpha_ty ; traceTcS "doTopReactFunEq (occurs)" $ vcat [ text "old_ev:" <+> ppr old_ev , nest 2 (text ":=") <+> ppr final_co , text "new_ev:" <+> ppr new_ev ] ; stopWith old_ev "Fun/Top (wanted)" } } } where loc = ctEvLoc old_ev deeper_loc = bumpCtLocDepth CountTyFunApps loc try_improvement | Just ops <- isBuiltInSynFamTyCon_maybe fam_tc = do { inert_eqs <- getInertEqs ; let eqns = sfInteractTop ops args (lookupFlattenTyVar inert_eqs fsk) ; mapM_ (unifyDerived loc Nominal) eqns } | otherwise = return () doTopReactFunEq w = pprPanic "doTopReactFunEq" (ppr w) shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion -> TyCon -> [TcType] -> TcS (StopOrContinue Ct) shortCutReduction old_ev fsk ax_co fam_tc tc_args | isGiven old_ev = ASSERT( ctEvEqRel old_ev == NomEq ) runFlatten $ do { let fmode = mkFlattenEnv FM_FlattenAll old_ev ; (xis, cos) <- flatten_many fmode (repeat Nominal) tc_args -- ax_co :: F args ~ G tc_args -- cos :: xis ~ tc_args -- old_ev :: F args ~ fsk -- G cos ; sym ax_co ; old_ev :: G xis ~ fsk ; new_ev <- newGivenEvVar deeper_loc ( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk) , EvCoercion (mkTcTyConAppCo Nominal fam_tc cos `mkTcTransCo` mkTcSymCo ax_co `mkTcTransCo` ctEvCoercion old_ev) ) ; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk } ; emitFlatWork new_ct ; stopWith old_ev "Fun/Top (given, shortcut)" } | otherwise = ASSERT( not (isDerived old_ev) ) -- Caller ensures this ASSERT( ctEvEqRel old_ev == NomEq ) runFlatten $ do { let fmode = mkFlattenEnv FM_FlattenAll old_ev ; (xis, cos) <- flatten_many fmode (repeat Nominal) tc_args -- ax_co :: F args ~ G tc_args -- cos :: xis ~ tc_args -- G cos ; sym ax_co ; old_ev :: G xis ~ fsk -- new_ev :: G xis ~ fsk -- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev ; new_ev <- newWantedEvVarNC loc (mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)) ; setEvBind (ctEvId old_ev) (EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos) `mkTcTransCo` ctEvCoercion new_ev)) ; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk } ; emitFlatWork new_ct ; stopWith old_ev "Fun/Top (wanted, shortcut)" } where loc = ctEvLoc old_ev deeper_loc = bumpCtLocDepth CountTyFunApps loc dischargeFmv :: EvVar -> TcTyVar -> TcCoercion -> TcType -> TcS () -- (dischargeFmv x fmv co ty) -- [W] x :: F tys ~ fuv -- co :: F tys ~ ty -- Precondition: fuv is not filled, and fuv `notElem` ty -- -- Then set fuv := ty, -- set x := co -- kick out any inert things that are now rewritable dischargeFmv evar fmv co xi = ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr evar $$ ppr fmv $$ ppr xi ) do { setWantedTyBind fmv xi ; setEvBind evar (EvCoercion co) ; n_kicked <- kickOutRewritable Given NomEq fmv ; traceTcS "dischargeFuv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) } {- Note [Cached solved FunEqs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ When trying to solve, say (FunExpensive big-type ~ ty), it's important to see if we have reduced (FunExpensive big-type) before, lest we simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover we must use `canRewriteOrSame` because both uses might (say) be Wanteds, and we *still* want to save the re-computation. Note [MATCHING-SYNONYMS] ~~~~~~~~~~~~~~~~~~~~~~~~ When trying to match a dictionary (D tau) to a top-level instance, or a type family equation (F taus_1 ~ tau_2) to a top-level family instance, we do *not* need to expand type synonyms because the matcher will do that for us. Note [RHS-FAMILY-SYNONYMS] ~~~~~~~~~~~~~~~~~~~~~~~~~~ The RHS of a family instance is represented as yet another constructor which is like a type synonym for the real RHS the programmer declared. Eg: type instance F (a,a) = [a] Becomes: :R32 a = [a] -- internal type synonym introduced F (a,a) ~ :R32 a -- instance When we react a family instance with a type family equation in the work list we keep the synonym-using RHS without expansion. Note [FunDep and implicit parameter reactions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently, our story of interacting two dictionaries (or a dictionary and top-level instances) for functional dependencies, and implicit paramters, is that we simply produce new Derived equalities. So for example class D a b | a -> b where ... Inert: d1 :g D Int Bool WorkItem: d2 :w D Int alpha We generate the extra work item cv :d alpha ~ Bool where 'cv' is currently unused. However, this new item can perhaps be spontaneously solved to become given and react with d2, discharging it in favour of a new constraint d2' thus: d2' :w D Int Bool d2 := d2' |> D Int cv Now d2' can be discharged from d1 We could be more aggressive and try to *immediately* solve the dictionary using those extra equalities, but that requires those equalities to carry evidence and derived do not carry evidence. If that were the case with the same inert set and work item we might dischard d2 directly: cv :w alpha ~ Bool d2 := d1 |> D Int cv But in general it's a bit painful to figure out the necessary coercion, so we just take the first approach. Here is a better example. Consider: class C a b c | a -> b And: [Given] d1 : C T Int Char [Wanted] d2 : C T beta Int In this case, it's *not even possible* to solve the wanted immediately. So we should simply output the functional dependency and add this guy [but NOT its superclasses] back in the worklist. Even worse: [Given] d1 : C T Int beta [Wanted] d2: C T beta Int Then it is solvable, but its very hard to detect this on the spot. It's exactly the same with implicit parameters, except that the "aggressive" approach would be much easier to implement. Note [When improvement happens] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We fire an improvement rule when * Two constraints match (modulo the fundep) e.g. C t1 t2, C t1 t3 where C a b | a->b The two match because the first arg is identical Note that we *do* fire the improvement if one is Given and one is Derived (e.g. a superclass of a Wanted goal) or if both are Given. Example (tcfail138) class L a b | a -> b class (G a, L a b) => C a b instance C a b' => G (Maybe a) instance C a b => C (Maybe a) a instance L (Maybe a) a When solving the superclasses of the (C (Maybe a) a) instance, we get Given: C a b ... and hance by superclasses, (G a, L a b) Wanted: G (Maybe a) Use the instance decl to get Wanted: C a b' The (C a b') is inert, so we generate its Derived superclasses (L a b'), and now we need improvement between that derived superclass an the Given (L a b) Test typecheck/should_fail/FDsFromGivens also shows why it's a good idea to emit Derived FDs for givens as well. Note [Weird fundeps] ~~~~~~~~~~~~~~~~~~~~ Consider class Het a b | a -> b where het :: m (f c) -> a -> m b class GHet (a :: * -> *) (b :: * -> *) | a -> b instance GHet (K a) (K [a]) instance Het a b => GHet (K a) (K b) The two instances don't actually conflict on their fundeps, although it's pretty strange. So they are both accepted. Now try [W] GHet (K Int) (K Bool) This triggers fudeps from both instance decls; but it also matches a *unique* instance decl, and we should go ahead and pick that one right now. Otherwise, if we don't, it ends up unsolved in the inert set and is reported as an error. Trac #7875 is a case in point. Note [Overriding implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: (?x::a) -> Bool -> a g v = let ?x::Int = 3 in (f v, let ?x::Bool = True in f v) This should probably be well typed, with g :: Bool -> (Int, Bool) So the inner binding for ?x::Bool *overrides* the outer one. Hence a work-item Given overrides an inert-item Given. Note [Given constraint that matches an instance declaration] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What should we do when we discover that one (or more) top-level instances match a given (or solved) class constraint? We have two possibilities: 1. Reject the program. The reason is that there may not be a unique best strategy for the solver. Example, from the OutsideIn(X) paper: instance P x => Q [x] instance (x ~ y) => R [x] y wob :: forall a b. (Q [b], R b a) => a -> Int g :: forall a. Q [a] => [a] -> Int g x = wob x will generate the impliation constraint: Q [a] => (Q [beta], R beta [a]) If we react (Q [beta]) with its top-level axiom, we end up with a (P beta), which we have no way of discharging. On the other hand, if we react R beta [a] with the top-level we get (beta ~ a), which is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is now solvable by the given Q [a]. However, this option is restrictive, for instance [Example 3] from Note [Recursive instances and superclases] will fail to work. 2. Ignore the problem, hoping that the situations where there exist indeed such multiple strategies are rare: Indeed the cause of the previous problem is that (R [x] y) yields the new work (x ~ y) which can be *spontaneously* solved, not using the givens. We are choosing option 2 below but we might consider having a flag as well. Note [New Wanted Superclass Work] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even in the case of wanted constraints, we may add some superclasses as new given work. The reason is: To allow FD-like improvement for type families. Assume that we have a class class C a b | a -> b and we have to solve the implication constraint: C a b => C a beta Then, FD improvement can help us to produce a new wanted (beta ~ b) We want to have the same effect with the type family encoding of functional dependencies. Namely, consider: class (F a ~ b) => C a b Now suppose that we have: given: C a b wanted: C a beta By interacting the given we will get given (F a ~ b) which is not enough by itself to make us discharge (C a beta). However, we may create a new derived equality from the super-class of the wanted constraint (C a beta), namely derived (F a ~ beta). Now we may interact this with given (F a ~ b) to get: derived : beta ~ b But 'beta' is a touchable unification variable, and hence OK to unify it with 'b', replacing the derived evidence with the identity. This requires trySpontaneousSolve to solve *derived* equalities that have a touchable in their RHS, *in addition* to solving wanted equalities. We also need to somehow use the superclasses to quantify over a minimal, constraint see note [Minimize by Superclasses] in TcSimplify. Finally, here is another example where this is useful. Example 1: ---------- class (F a ~ b) => C a b And we are given the wanteds: w1 : C a b w2 : C a c w3 : b ~ c We surely do *not* want to quantify over (b ~ c), since if someone provides dictionaries for (C a b) and (C a c), these dictionaries can provide a proof of (b ~ c), hence no extra evidence is necessary. Here is what will happen: Step 1: We will get new *given* superclass work, provisionally to our solving of w1 and w2 g1: F a ~ b, g2 : F a ~ c, w1 : C a b, w2 : C a c, w3 : b ~ c The evidence for g1 and g2 is a superclass evidence term: g1 := sc w1, g2 := sc w2 Step 2: The givens will solve the wanted w3, so that w3 := sym (sc w1) ; sc w2 Step 3: Now, one may naively assume that then w2 can be solve from w1 after rewriting with the (now solved equality) (b ~ c). But this rewriting is ruled out by the isGoodRectDict! Conclusion, we will (correctly) end up with the unsolved goals (C a b, C a c) NB: The desugarer needs be more clever to deal with equalities that participate in recursive dictionary bindings. -} data LookupInstResult = NoInstance | GenInst [CtEvidence] EvTerm instance Outputable LookupInstResult where ppr NoInstance = text "NoInstance" ppr (GenInst ev t) = text "GenInst" <+> ppr ev <+> ppr t matchClassInst :: InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult matchClassInst _ clas [ ty ] _ | className clas == knownNatClassName , Just n <- isNumLitTy ty = makeDict (EvNum n) | className clas == knownSymbolClassName , Just s <- isStrLitTy ty = makeDict (EvStr s) where {- This adds a coercion that will convert the literal into a dictionary of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit] in TcEvidence. The coercion happens in 2 steps: Integer -> SNat n -- representation of literal to singleton SNat n -> KnownNat n -- singleton to dictionary The process is mirrored for Symbols: String -> SSymbol n SSymbol n -> KnownSymbol n -} makeDict evLit | Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty] -- co_dict :: KnownNat n ~ SNat n , [ meth ] <- classMethods clas , Just tcRep <- tyConAppTyCon_maybe -- SNat $ funResultTy -- SNat n $ dropForAlls -- KnownNat n => SNat n $ idType meth -- forall n. KnownNat n => SNat n , Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty] -- SNat n ~ Integer = return (GenInst [] $ mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep))) | otherwise = panicTcS (text "Unexpected evidence for" <+> ppr (className clas) $$ vcat (map (ppr . idType) (classMethods clas))) matchClassInst _ clas [k,t] loc | className clas == typeableClassName = matchTypeableClass clas k t loc matchClassInst inerts clas tys loc = do { dflags <- getDynFlags ; traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr pred , text "inerts=" <+> ppr inerts ] ; instEnvs <- getInstEnvs ; case lookupInstEnv instEnvs clas tys of ([], _, _) -- Nothing matches -> do { traceTcS "matchClass not matching" $ vcat [ text "dict" <+> ppr pred ] ; return NoInstance } ([(ispec, inst_tys)], [], _) -- A single match | not (xopt LangExt.IncoherentInstances dflags) , not (isEmptyBag unifiable_givens) -> -- See Note [Instance and Given overlap] do { traceTcS "Delaying instance application" $ vcat [ text "Work item=" <+> pprType (mkClassPred clas tys) , text "Relevant given dictionaries=" <+> ppr unifiable_givens ] ; return NoInstance } | otherwise -> do { let dfun_id = instanceDFunId ispec ; traceTcS "matchClass success" $ vcat [text "dict" <+> ppr pred, text "witness" <+> ppr dfun_id <+> ppr (idType dfun_id) ] -- Record that this dfun is needed ; match_one dfun_id inst_tys } (matches, _, _) -- More than one matches -- Defer any reactions of a multitude -- until we learn more about the reagent -> do { traceTcS "matchClass multiple matches, deferring choice" $ vcat [text "dict" <+> ppr pred, text "matches" <+> ppr matches] ; return NoInstance } } where pred = mkClassPred clas tys match_one :: DFunId -> [Maybe TcType] -> TcS LookupInstResult -- See Note [DFunInstType: instantiating types] in InstEnv match_one dfun_id mb_inst_tys = do { checkWellStagedDFun pred dfun_id loc ; (tys, dfun_phi) <- instDFunType dfun_id mb_inst_tys ; let (theta, _) = tcSplitPhiTy dfun_phi ; if null theta then return (GenInst [] (EvDFunApp dfun_id tys [])) else do { evc_vars <- instDFunConstraints loc theta ; let new_ev_vars = freshGoals evc_vars -- new_ev_vars are only the real new variables that can be emitted dfun_app = EvDFunApp dfun_id tys (map (ctEvTerm . fst) evc_vars) ; return $ GenInst new_ev_vars dfun_app } } unifiable_givens :: Cts unifiable_givens = filterBag matchable $ findDictsByClass (inert_dicts $ inert_cans inerts) clas matchable (CDictCan { cc_class = clas_g, cc_tyargs = sys, cc_ev = fl }) | isGiven fl , Just {} <- tcUnifyTys bind_meta_tv tys sys = ASSERT( clas_g == clas ) True | otherwise = False -- No overlap with a solved, already been taken care of -- by the overlap check with the instance environment. matchable ct = pprPanic "Expecting dictionary!" (ppr ct) bind_meta_tv :: TcTyVar -> BindFlag -- Any meta tyvar may be unified later, so we treat it as -- bindable when unifying with givens. That ensures that we -- conservatively assume that a meta tyvar might get unified with -- something that matches the 'given', until demonstrated -- otherwise. bind_meta_tv tv | isMetaTyVar tv = BindMe | otherwise = Skolem {- Note [Instance and Given overlap] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example, from the OutsideIn(X) paper: instance P x => Q [x] instance (x ~ y) => R y [x] wob :: forall a b. (Q [b], R b a) => a -> Int g :: forall a. Q [a] => [a] -> Int g x = wob x This will generate the impliation constraint: Q [a] => (Q [beta], R beta [a]) If we react (Q [beta]) with its top-level axiom, we end up with a (P beta), which we have no way of discharging. On the other hand, if we react R beta [a] with the top-level we get (beta ~ a), which is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is now solvable by the given Q [a]. The solution is that: In matchClassInst (and thus in topReact), we return a matching instance only when there is no Given in the inerts which is unifiable to this particular dictionary. We treat any meta-tyvar as "unifiable" for this purpose, *including* untouchable ones The end effect is that, much as we do for overlapping instances, we delay choosing a class instance if there is a possibility of another instance OR a given to match our constraint later on. This fixes Trac #4981 and #5002. Other notes: * This is arguably not easy to appear in practice due to our aggressive prioritization of equality solving over other constraints, but it is possible. I've added a test case in typecheck/should-compile/GivenOverlapping.hs * Another "live" example is Trac #10195 * We ignore the overlap problem if -XIncoherentInstances is in force: see Trac #6002 for a worked-out example where this makes a difference. * Moreover notice that our goals here are different than the goals of the top-level overlapping checks. There we are interested in validating the following principle: If we inline a function f at a site where the same global instance environment is available as the instance environment at the definition site of f then we should get the same behaviour. But for the Given Overlap check our goal is just related to completeness of constraint solving. -} -- | Assumes that we've checked that this is the 'Typeable' class, -- and it was applied to the correc arugment. matchTypeableClass :: Class -> Kind -> Type -> CtLoc -> TcS LookupInstResult matchTypeableClass clas _k t loc -- See Note [No Typeable for qualified types] | isForAllTy t = return NoInstance -- Is the type of the form `C => t`? | Just (t1,_) <- splitFunTy_maybe t, isConstraintKind (typeKind t1) = return NoInstance | Just (tc, ks) <- splitTyConApp_maybe t , all isKind ks = doTyCon tc ks | Just (f,kt) <- splitAppTy_maybe t = doTyApp f kt | Just _ <- isNumLitTy t = mkSimpEv (EvTypeableTyLit t) | Just _ <- isStrLitTy t = mkSimpEv (EvTypeableTyLit t) | otherwise = return NoInstance where -- Representation for type constructor applied to some kinds doTyCon tc ks = case mapM kindRep ks of Nothing -> return NoInstance Just kReps -> mkSimpEv (EvTypeableTyCon tc kReps) {- Representation for an application of a type to a type-or-kind. This may happen when the type expression starts with a type variable. Example (ignoring kind parameter): Typeable (f Int Char) --> (Typeable (f Int), Typeable Char) --> (Typeable f, Typeable Int, Typeable Char) --> (after some simp. steps) Typeable f -} doTyApp f tk | isKind tk = return NoInstance -- We can't solve until we know the ctr. | otherwise = do ct1 <- subGoal f ct2 <- subGoal tk let realSubs = [ c | (c,Fresh) <- [ct1,ct2] ] return $ GenInst realSubs $ EvTypeable $ EvTypeableTyApp (getEv ct1,f) (getEv ct2,tk) -- Representation for concrete kinds. We just use the kind itself, -- but first check to make sure that it is "simple" (i.e., made entirely -- out of kind constructors). kindRep ki = do (_,ks) <- splitTyConApp_maybe ki mapM_ kindRep ks return ki getEv (ct,_fresh) = ctEvTerm ct -- Emit a `Typeable` constraint for the given type. subGoal ty = do let goal = mkClassPred clas [ typeKind ty, ty ] newWantedEvVar loc goal mkSimpEv ev = return (GenInst [] (EvTypeable ev)) {- Note [No Typeable for polytype or for constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We do not support impredicative typeable, such as Typeable (forall a. a->a) Typeable (Eq a => a -> a) Typeable (() => Int) Typeable (((),()) => Int) See Trac #9858. For forall's the case is clear: we simply don't have a TypeRep for them. For qualified but not polymorphic types, like (Eq a => a -> a), things are murkier. But: * We don't need a TypeRep for these things. TypeReps are for monotypes only. * Perhaps we could treat `=>` as another type constructor for `Typeable` purposes, and thus support things like `Eq Int => Int`, however, at the current state of affairs this would be an odd exception as no other class works with impredicative types. For now we leave it off, until we have a better story for impredicativity. -} solveCallStack :: CtEvidence -> EvCallStack -> TcS () solveCallStack ev ev_cs = do -- We're given ev_cs :: CallStack, but the evidence term should be a -- dictionary, so we have to coerce ev_cs to a dictionary for -- `IP ip CallStack`. See Note [Overview of implicit CallStacks] let ev_tm = mkEvCast (EvCallStack ev_cs) (TcCoercion $ wrapIP (ctEvPred ev)) setWantedEvBind (ctEvId ev) ev_tm
rahulmutt/ghcvm
compiler/Eta/TypeCheck/TcInteract.hs
bsd-3-clause
93,135
109
23
27,454
11,430
6,012
5,418
-1
-1
module Language.Mecha.Primitives ( sphere , cube , cylinder ) where import Language.Mecha.Solid -- | A sphere with radius 1 centered at origin. sphere :: Solid sphere = Solid $ \ (x, y, z) -> sqrt (x ** 2 + y ** 2 + z ** 2) <= 1 -- | A sphere with edge length 2 centered at origin. cube :: Solid cube = Solid $ \ (x, y, z) -> all (\ a -> a <= 1 && a >= (-1)) [x, y, z] -- | A cylinder with radius 1 and height 2 centered at origin. cylinder :: Solid cylinder = Solid $ \ (x, y, z) -> z <= 1 && z >= (-1) && sqrt (x ** 2 + y ** 2) <= 1
tomahawkins/mecha
attic/Primitives.hs
bsd-3-clause
548
0
14
141
223
129
94
11
1
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, Rank2Types #-} -- | -- Module: Data.Aeson.Types.Internal -- Copyright: (c) 2011, 2012 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: Apache -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable -- -- Types for working with JSON data. module Data.Aeson.Types.Internal ( -- * Core JSON types Value(..) , Array , emptyArray, isEmptyArray , Pair , Object , emptyObject -- * Type conversion , Parser , Result(..) , parse , parseEither , parseMaybe , modifyFailure -- * Constructors and accessors , object -- * Generic and TH encoding configuration , Options(..) , SumEncoding(..) , defaultOptions , defaultTaggedObject -- * Used for changing CamelCase names into something else. , camelTo -- * Other types , DotNetTime(..) ) where import Control.Applicative import Control.Monad import Control.DeepSeq (NFData(..)) import Data.Char (toLower, isUpper) import Data.Scientific (Scientific) import Data.Hashable (Hashable(..)) import Data.Data (Data) import Data.HashMap.Strict (HashMap) import Data.Monoid (Monoid(..)) import Data.String (IsString(..)) import Data.Text (Text, pack) import Data.Time (UTCTime) import Data.Time.Format (FormatTime) import Data.Typeable (Typeable) import Data.Vector (Vector) import qualified Data.HashMap.Strict as H import qualified Data.Vector as V -- | The result of running a 'Parser'. data Result a = Error String | Success a deriving (Eq, Show, Typeable) instance (NFData a) => NFData (Result a) where rnf (Success a) = rnf a rnf (Error err) = rnf err instance Functor Result where fmap f (Success a) = Success (f a) fmap _ (Error err) = Error err {-# INLINE fmap #-} instance Monad Result where return = Success {-# INLINE return #-} Success a >>= k = k a Error err >>= _ = Error err {-# INLINE (>>=) #-} instance Applicative Result where pure = return {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance MonadPlus Result where mzero = fail "mzero" {-# INLINE mzero #-} mplus a@(Success _) _ = a mplus _ b = b {-# INLINE mplus #-} instance Alternative Result where empty = mzero {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance Monoid (Result a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} -- | Failure continuation. type Failure f r = String -> f r -- | Success continuation. type Success a f r = a -> f r -- | A continuation-based parser type. newtype Parser a = Parser { runParser :: forall f r. Failure f r -> Success a f r -> f r } instance Monad Parser where m >>= g = Parser $ \kf ks -> let ks' a = runParser (g a) kf ks in runParser m kf ks' {-# INLINE (>>=) #-} return a = Parser $ \_kf ks -> ks a {-# INLINE return #-} fail msg = Parser $ \kf _ks -> kf msg {-# INLINE fail #-} instance Functor Parser where fmap f m = Parser $ \kf ks -> let ks' a = ks (f a) in runParser m kf ks' {-# INLINE fmap #-} instance Applicative Parser where pure = return {-# INLINE pure #-} (<*>) = apP {-# INLINE (<*>) #-} instance Alternative Parser where empty = fail "empty" {-# INLINE empty #-} (<|>) = mplus {-# INLINE (<|>) #-} instance MonadPlus Parser where mzero = fail "mzero" {-# INLINE mzero #-} mplus a b = Parser $ \kf ks -> let kf' _ = runParser b kf ks in runParser a kf' ks {-# INLINE mplus #-} instance Monoid (Parser a) where mempty = fail "mempty" {-# INLINE mempty #-} mappend = mplus {-# INLINE mappend #-} apP :: Parser (a -> b) -> Parser a -> Parser b apP d e = do b <- d a <- e return (b a) {-# INLINE apP #-} -- | A JSON \"object\" (key\/value map). type Object = HashMap Text Value -- | A JSON \"array\" (sequence). type Array = Vector Value -- | A JSON value represented as a Haskell value. data Value = Object !Object | Array !Array | String !Text | Number !Scientific | Bool !Bool | Null deriving (Eq, Show, Typeable, Data) -- | A newtype wrapper for 'UTCTime' that uses the same non-standard -- serialization format as Microsoft .NET, whose @System.DateTime@ -- type is by default serialized to JSON as in the following example: -- -- > /Date(1302547608878)/ -- -- The number represents milliseconds since the Unix epoch. newtype DotNetTime = DotNetTime { fromDotNetTime :: UTCTime } deriving (Eq, Ord, Read, Show, Typeable, FormatTime) instance NFData Value where rnf (Object o) = rnf o rnf (Array a) = V.foldl' (\x y -> rnf y `seq` x) () a rnf (String s) = rnf s rnf (Number n) = rnf n rnf (Bool b) = rnf b rnf Null = () instance IsString Value where fromString = String . pack {-# INLINE fromString #-} hashValue :: Int -> Value -> Int hashValue s (Object o) = H.foldl' hashWithSalt (s `hashWithSalt` (0::Int)) o hashValue s (Array a) = V.foldl' hashWithSalt (s `hashWithSalt` (1::Int)) a hashValue s (String str) = s `hashWithSalt` (2::Int) `hashWithSalt` str hashValue s (Number n) = s `hashWithSalt` (3::Int) `hashWithSalt` n hashValue s (Bool b) = s `hashWithSalt` (4::Int) `hashWithSalt` b hashValue s Null = s `hashWithSalt` (5::Int) instance Hashable Value where hashWithSalt = hashValue -- | The empty array. emptyArray :: Value emptyArray = Array V.empty -- | Determines if the 'Value' is an empty 'Array'. -- Note that: @isEmptyArray 'emptyArray'@. isEmptyArray :: Value -> Bool isEmptyArray (Array arr) = V.null arr isEmptyArray _ = False -- | The empty object. emptyObject :: Value emptyObject = Object H.empty -- | Run a 'Parser'. parse :: (a -> Parser b) -> a -> Result b parse m v = runParser (m v) Error Success {-# INLINE parse #-} -- | Run a 'Parser' with a 'Maybe' result type. parseMaybe :: (a -> Parser b) -> a -> Maybe b parseMaybe m v = runParser (m v) (const Nothing) Just {-# INLINE parseMaybe #-} -- | Run a 'Parser' with an 'Either' result type. parseEither :: (a -> Parser b) -> a -> Either String b parseEither m v = runParser (m v) Left Right {-# INLINE parseEither #-} -- | A key\/value pair for an 'Object'. type Pair = (Text, Value) -- | Create a 'Value' from a list of name\/value 'Pair's. If duplicate -- keys arise, earlier keys and their associated values win. object :: [Pair] -> Value object = Object . H.fromList {-# INLINE object #-} -- | If the inner @Parser@ failed, modify the failure message using the -- provided function. This allows you to create more descriptive error messages. -- For example: -- -- > parseJSON (Object o) = modifyFailure -- > ("Parsing of the Foo value failed: " ++) -- > (Foo <$> o .: "someField") -- -- Since 0.6.2.0 modifyFailure :: (String -> String) -> Parser a -> Parser a modifyFailure f (Parser p) = Parser $ \kf -> p (kf . f) -------------------------------------------------------------------------------- -- Generic and TH encoding configuration -------------------------------------------------------------------------------- -- | Options that specify how to encode\/decode your datatype to\/from JSON. data Options = Options { fieldLabelModifier :: String -> String -- ^ Function applied to field labels. -- Handy for removing common record prefixes for example. , constructorTagModifier :: String -> String -- ^ Function applied to constructor tags which could be handy -- for lower-casing them for example. , allNullaryToStringTag :: Bool -- ^ If 'True' the constructors of a datatype, with /all/ -- nullary constructors, will be encoded to just a string with -- the constructor tag. If 'False' the encoding will always -- follow the `sumEncoding`. , omitNothingFields :: Bool -- ^ If 'True' record fields with a 'Nothing' value will be -- omitted from the resulting object. If 'False' the resulting -- object will include those fields mapping to @null@. , sumEncoding :: SumEncoding -- ^ Specifies how to encode constructors of a sum datatype. } -- | Specifies how to encode constructors of a sum datatype. data SumEncoding = TaggedObject { tagFieldName :: String , contentsFieldName :: String } -- ^ A constructor will be encoded to an object with a field -- 'tagFieldName' which specifies the constructor tag (modified by -- the 'constructorTagModifier'). If the constructor is a record -- the encoded record fields will be unpacked into this object. So -- make sure that your record doesn't have a field with the same -- label as the 'tagFieldName'. Otherwise the tag gets overwritten -- by the encoded value of that field! If the constructor is not a -- record the encoded constructor contents will be stored under -- the 'contentsFieldName' field. | ObjectWithSingleField -- ^ A constructor will be encoded to an object with a single -- field named after the constructor tag (modified by the -- 'constructorTagModifier') which maps to the encoded contents of -- the constructor. | TwoElemArray -- ^ A constructor will be encoded to a 2-element array where the -- first element is the tag of the constructor (modified by the -- 'constructorTagModifier') and the second element the encoded -- contents of the constructor. -- | Default encoding 'Options': -- -- @ -- 'Options' -- { 'fieldLabelModifier' = id -- , 'constructorTagModifier' = id -- , 'allNullaryToStringTag' = True -- , 'omitNothingFields' = False -- , 'sumEncoding' = 'defaultTaggedObject' -- } -- @ defaultOptions :: Options defaultOptions = Options { fieldLabelModifier = id , constructorTagModifier = id , allNullaryToStringTag = True , omitNothingFields = False , sumEncoding = defaultTaggedObject } -- | Default 'TaggedObject' 'SumEncoding' options: -- -- @ -- defaultTaggedObject = 'TaggedObject' -- { 'tagFieldName' = \"tag\" -- , 'contentsFieldName' = \"contents\" -- } -- @ defaultTaggedObject :: SumEncoding defaultTaggedObject = TaggedObject { tagFieldName = "tag" , contentsFieldName = "contents" } -- | Converts from CamelCase to another lower case, interspersing -- the character between all capital letters and their previous -- entries, except those capital letters that appear together, -- like 'API'. -- -- For use by Aeson template haskell calls. -- -- > camelTo '_' 'CamelCaseAPI' == "camel_case_api" camelTo :: Char -> String -> String camelTo c = lastWasCap True where lastWasCap :: Bool -- ^ Previous was a capital letter -> String -- ^ The remaining string -> String lastWasCap _ [] = [] lastWasCap prev (x : xs) = if isUpper x then if prev then toLower x : lastWasCap True xs else c : toLower x : lastWasCap True xs else x : lastWasCap False xs
jprider63/aeson-ios-0.8.0.2
Data/Aeson/Types/Internal.hs
bsd-3-clause
11,828
0
14
3,305
2,228
1,274
954
220
4
module HLearn.Metrics.Mahalanobis.LegoPaper where import Control.Monad import Control.Monad.Random hiding (fromList) import Control.Monad.ST import Data.Array.ST import GHC.Arr import qualified Data.Foldable as F import qualified Data.Vector.Generic as VG import Debug.Trace import Foreign.Storable import Numeric.LinearAlgebra hiding ((<>)) import qualified Numeric.LinearAlgebra as LA import HLearn.Algebra import HLearn.Metrics.Mahalanobis ------------------------------------------------------------------------------- -- data types data LegoPaper dp = LegoPaper { _matrix :: Matrix (Scalar dp) , _xs :: [(Scalar dp,dp)] , _numdp :: Scalar dp } deriving instance (Element (Scalar dp), Show(Scalar dp), Show dp) => Show (LegoPaper dp) type instance Scalar (LegoPaper dp) = Scalar dp instance MahalanobisMetric (LegoPaper dp) where getMatrix (LegoPaper x _ _) = x fromSingleton :: (Element r, Container Vector r, Storable r) => Matrix r -> r fromSingleton m = if rows m /= 1 || cols m /= 1 then error "fromSingleton on not 1x1 matrix" else atIndex m $ minIndex m -- mappend1 :: (Field (Scalar dp)) => LegoPaper dp -> LegoPaper dp -> LegoPaper dp mappend1 m1 m2 = LegoPaper { _matrix = (scale (_numdp m1/totdp) $ _matrix m1) `LA.add` (scale (_numdp m2/totdp) $ _matrix m2) , _numdp = _numdp m1+_numdp m2 , _xs = _xs m1++_xs m2 } where totdp = _numdp m1+_numdp m2 mappend2 eta m1 m2 = mappend1 m1' m2' where m1' = m1 { _matrix = _matrix m1'' } m2' = m1 { _matrix = _matrix m2'' } -- m1'' = F.foldl' (add1dp_LegoPaper eta) m1 $ take 100 xs1' -- m2'' = F.foldl' (add1dp_LegoPaper eta) m2 $ take 100 xs2' m1'' = F.foldl' (add1dp_LegoPaper eta) m1 xs1' m2'' = F.foldl' (add1dp_LegoPaper eta) m2 xs2' xs1' = evalRand (shuffle $ _xs m1) (mkStdGen 10) xs2' = evalRand (shuffle $ _xs m2) (mkStdGen 10) -- train_LegoMonoid :: -- ( F.Foldable container -- , Functor container -- , VG.Vector vec r -- , Container Vector r -- , LA.Product r -- , Floating r -- , r ~ Scalar (vec r) -- , Show r -- , Ord r -- ) => Int -> r -> container (r,vec r) -> LegoPaper (vec r) train_LegoMonoid monoid k1 k2 eta dps = F.foldl1 monoid ms where ms = map (train_LegoPaper 0 eta) dps' dps' = take k2 [takeEvery k1 $ drop j dps | j<-[0..k1-1]] takeEvery n [] = [] takeEvery n xs = head xs : (takeEvery n $ drop n xs) train_LegoPaper :: ( F.Foldable container , Functor container , VG.Vector vec r , Container Vector r , LA.Product r , Floating r , r ~ Scalar (vec r) , Show r , Ord r ) => Int -> r -> container (r,vec r) -> LegoPaper (vec r) train_LegoPaper rep eta dps = F.foldl' (add1dp_LegoPaper eta) reg dps' where -- dps' = evalRand (shuffle $ concat $ replicate rep $ F.toList dps) $ mkStdGen 10 dps' = dps reg = LegoPaper { _matrix = ident $ VG.length $ snd $ head $ F.toList dps , _numdp = 0 -- fromIntegral $ length $ F.toList dps , _xs = [] } shuffle :: RandomGen g => [a] -> Rand g [a] shuffle xs = do let l = length xs rands <- take l `fmap` getRandomRs (0, l-1) let ar = runSTArray $ do ar <- thawSTArray $ listArray (0, l-1) xs forM_ (zip [0..(l-1)] rands) $ \(i, j) -> do vi <- readSTArray ar i vj <- readSTArray ar j writeSTArray ar j vi writeSTArray ar i vj return ar return (elems ar) add1dp_LegoPaper :: ( Storable r , LA.Product r , Floating r , Container Vector r , VG.Vector vec r , r ~ Scalar (vec r) , Show r , Ord r ) => r -> LegoPaper (vec r) -> (r,vec r) -> LegoPaper (vec r) add1dp_LegoPaper eta lp (y,vec) = LegoPaper { _matrix = mat , _numdp = _numdp lp+1 , _xs = (y,vec):(_xs lp) } -- trace ("yhat="++show yhat++"; ybar="++show ybar++"; ybar_det="++show ybar_det++"; y="++show y++"; vec="++show vec++"; a="++show a) $ where a = _matrix lp mat = if yhat<0.00001 then a else a `LA.sub` (scale (eta*(ybar-y)/(1+eta*(ybar-y)*yhat)) $ a LA.<> z LA.<> zT LA.<> a) vec' = VG.convert vec zT = asRow vec' z = asColumn vec' yhat = fromSingleton $ zT LA.<> a LA.<> z ybar = ybar_top / ybar_bot ybar_bot = 2*eta*yhat ybar_top = (eta*y*yhat - 1 + (sqrt ybar_det)) ybar_det = (eta*y*yhat-1)**2 + 4*eta*yhat**2 instance ( VG.Vector vec r , Scalar (vec r) ~ r , LA.Product r ) => MkMahalanobis (LegoPaper (vec r)) where type MetricDatapoint (LegoPaper (vec r)) = vec r mkMahalanobis (LegoPaper a _ _) vec = Mahalanobis { rawdp = vec , moddp = VG.fromList $ toList $ flatten $ a LA.<> asColumn v } where v = fromList $ VG.toList vec
iamkingmaker/HLearn
src/HLearn/Metrics/Mahalanobis/LegoPaper.hs
bsd-3-clause
5,034
0
21
1,491
1,737
913
824
-1
-1
import System.Environment import System.Exit import System.IO import Codec.Text.Detect import qualified Data.ByteString.Lazy as L main :: IO () main = do args <- getArgs bs <- case args of [fp] -> L.readFile fp [] -> L.getContents case detectEncodingName bs of Nothing -> hPutStrLn stderr "Could not detect encoding" >> exitWith (ExitFailure 1) Just encoding -> putStrLn encoding
beni55/charsetdetect
example/Main.hs
lgpl-2.1
432
1
13
108
137
68
69
14
3
{-# LANGUAGE RecordWildCards #-} -- | -- Module : Criterion -- Copyright : (c) 2009-2014 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- Core benchmarking code. module Criterion ( -- * Benchmarkable code Benchmarkable -- * Creating a benchmark suite , Benchmark , env , bench , bgroup -- ** Running a benchmark , nf , whnf , nfIO , whnfIO -- * For interactive use , benchmark , benchmarkWith , benchmark' , benchmarkWith' ) where import Control.Monad (void) import Criterion.IO.Printf (note) import Criterion.Internal (runAndAnalyseOne) import Criterion.Main.Options (defaultConfig) import Criterion.Measurement (initializeTime) import Criterion.Monad (withConfig) import Criterion.Types -- | Run a benchmark interactively, and analyse its performance. benchmark :: Benchmarkable -> IO () benchmark bm = void $ benchmark' bm -- | Run a benchmark interactively, analyse its performance, and -- return the analysis. benchmark' :: Benchmarkable -> IO Report benchmark' = benchmarkWith' defaultConfig -- | Run a benchmark interactively, and analyse its performance. benchmarkWith :: Config -> Benchmarkable -> IO () benchmarkWith cfg bm = void $ benchmarkWith' cfg bm -- | Run a benchmark interactively, analyse its performance, and -- return the analysis. benchmarkWith' :: Config -> Benchmarkable -> IO Report benchmarkWith' cfg bm = do initializeTime withConfig cfg $ do _ <- note "benchmarking...\n" runAndAnalyseOne 0 "function" bm
paulolieuthier/criterion
Criterion.hs
bsd-2-clause
1,628
0
11
333
278
160
118
35
1
module ExportList_C where c = 42
beni55/fay
tests/ExportList_C.hs
bsd-3-clause
34
0
4
7
9
6
3
2
1
{-# LANGUAGE OverloadedStrings, RecordWildCards, TemplateHaskell, TupleSections #-} -- | Extensions to Aeson parsing of objects. module Data.Aeson.Extended ( module Export -- * Extended failure messages , (.:) , (.:?) -- * JSON Parser that emits warnings , WarningParser , JSONWarning (..) , withObjectWarnings , (..:) , (..:?) , (..!=) , jsonSubWarnings , jsonSubWarningsT , jsonSubWarningsMT , logJSONWarnings ) where import Control.Monad.Logger (MonadLogger, logWarn) import Control.Monad.Trans (lift) import Control.Monad.Trans.Writer.Strict (WriterT, mapWriterT, runWriterT, tell) import Data.Aeson as Export hiding ((.:), (.:?)) import qualified Data.Aeson as A import Data.Aeson.Types hiding ((.:), (.:?)) import qualified Data.HashMap.Strict as HashMap import Data.Monoid (Monoid (..), (<>)) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (unpack, Text) import qualified Data.Text as T import Data.Traversable (Traversable) import qualified Data.Traversable as Traversable -- | Extends @.:@ warning to include field name. (.:) :: FromJSON a => Object -> Text -> Parser a (.:) o p = modifyFailure (("failed to parse field '" <> unpack p <> "': ") <>) (o A..: p) {-# INLINE (.:) #-} -- | Extends @.:?@ warning to include field name. (.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a) (.:?) o p = modifyFailure (("failed to parse field '" <> unpack p <> "': ") <>) (o A..:? p) {-# INLINE (.:?) #-} -- | 'WarningParser' version of @.:@. (..:) :: FromJSON a => Object -> Text -> WarningParser a o ..: k = tellField k >> lift (o .: k) -- | 'WarningParser' version of @.:?@. (..:?) :: FromJSON a => Object -> Text -> WarningParser (Maybe a) o ..:? k = tellField k >> lift (o .:? k) -- | 'WarningParser' version of @.!=@. (..!=) :: WarningParser (Maybe a) -> a -> WarningParser a wp ..!= d = flip mapWriterT wp $ \p -> do a <- fmap snd p fmap (, a) (fmap fst p .!= d) -- | Tell warning parser about about an expected field. tellField :: Text -> WarningParser () tellField key = tell (mempty { wpmExpectedFields = Set.singleton key}) -- | 'MonadParser' version of 'withObject'. withObjectWarnings :: String -> (Object -> WarningParser a) -> Value -> Parser (a, [JSONWarning]) withObjectWarnings expected f = withObject expected $ \obj -> do (a,w) <- runWriterT (f obj) let unrecognizedFields = Set.toList (Set.difference (Set.fromList (HashMap.keys obj)) (wpmExpectedFields w)) return ( a , wpmWarnings w ++ case unrecognizedFields of [] -> [] _ -> [JSONUnrecognizedFields expected unrecognizedFields]) -- | Log JSON warnings. logJSONWarnings :: MonadLogger m => FilePath -> [JSONWarning] -> m () logJSONWarnings fp = mapM_ (\w -> $logWarn ("Warning: " <> T.pack fp <> ": " <> T.pack (show w))) -- | Handle warnings in a sub-object. jsonSubWarnings :: WarningParser (a, [JSONWarning]) -> WarningParser a jsonSubWarnings f = do (result,warnings) <- f tell (mempty { wpmWarnings = warnings }) return result -- | Handle warnings in a @Traversable@ of sub-objects. jsonSubWarningsT :: Traversable t => WarningParser (t (a, [JSONWarning])) -> WarningParser (t a) jsonSubWarningsT f = Traversable.mapM (jsonSubWarnings . return) =<< f -- | Handle warnings in a @Maybe Traversable@ of sub-objects. jsonSubWarningsMT :: (Traversable t) => WarningParser (Maybe (t (a, [JSONWarning]))) -> WarningParser (Maybe (t a)) jsonSubWarningsMT f = do ml <- f case ml of Nothing -> return Nothing Just l -> fmap Just (jsonSubWarningsT (return l)) -- | JSON parser that warns about unexpected fields in objects. type WarningParser a = WriterT WarningParserMonoid Parser a -- | Monoid used by 'MonadParser' to track expected fields and warnings. data WarningParserMonoid = WarningParserMonoid { wpmExpectedFields :: !(Set Text) , wpmWarnings :: [JSONWarning] } instance Monoid WarningParserMonoid where mempty = WarningParserMonoid Set.empty [] mappend a b = WarningParserMonoid { wpmExpectedFields = Set.union (wpmExpectedFields a) (wpmExpectedFields b) , wpmWarnings = wpmWarnings a ++ wpmWarnings b } -- | Warning output from 'WarningParser'. data JSONWarning = JSONUnrecognizedFields String [Text] instance Show JSONWarning where show (JSONUnrecognizedFields obj [field]) = "Unrecognized field in " <> obj <> ": " <> T.unpack field show (JSONUnrecognizedFields obj fields) = "Unrecognized fields in " <> obj <> ": " <> T.unpack (T.intercalate ", " fields)
wskplho/stack
src/Data/Aeson/Extended.hs
bsd-3-clause
4,960
0
19
1,263
1,375
754
621
116
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} -- | Names for packages. module Stack.Types.PackageName (PackageName ,PackageNameParseFail(..) ,packageNameParser ,parsePackageName ,parsePackageNameFromString ,packageNameByteString ,packageNameString ,packageNameText ,fromCabalPackageName ,toCabalPackageName ,parsePackageNameFromFilePath ,mkPackageName ,packageNameArgument) where import Control.Applicative import Control.DeepSeq import Control.Monad import Control.Monad.Catch import Data.Aeson.Extended import Data.Attoparsec.ByteString.Char8 import Data.Attoparsec.Combinators import Data.Binary (Binary) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Char (isLetter) import Data.Data import Data.Hashable import Data.Map (Map) import qualified Data.Map as Map import Data.Text (Text) import qualified Data.Text.Encoding as T import qualified Distribution.Package as Cabal import GHC.Generics import Language.Haskell.TH import Language.Haskell.TH.Syntax import Path import qualified Options.Applicative as O -- | A parse fail. data PackageNameParseFail = PackageNameParseFail ByteString | CabalFileNameParseFail FilePath | CabalFileNameInvalidPackageName FilePath deriving (Typeable) instance Exception PackageNameParseFail instance Show PackageNameParseFail where show (PackageNameParseFail bs) = "Invalid package name: " ++ show bs show (CabalFileNameParseFail fp) = "Invalid file path for cabal file, must have a .cabal extension: " ++ fp show (CabalFileNameInvalidPackageName fp) = "cabal file names must use valid package names followed by a .cabal extension, the following is invalid: " ++ fp -- | A package name. newtype PackageName = PackageName ByteString deriving (Eq,Ord,Typeable,Data,Generic,Hashable,Binary,NFData) instance Lift PackageName where lift (PackageName n) = appE (conE 'PackageName) (stringE (S8.unpack n)) instance Show PackageName where show (PackageName n) = S8.unpack n instance ToJSON PackageName where toJSON = toJSON . packageNameText instance FromJSON PackageName where parseJSON j = do s <- parseJSON j case parsePackageNameFromString s of Nothing -> fail ("Couldn't parse package name: " ++ s) Just ver -> return ver -- | Attoparsec parser for a package name from bytestring. packageNameParser :: Parser PackageName packageNameParser = fmap (PackageName . S8.pack) (appending (many1 (satisfy isAlphaNum)) (concating (many (alternating (pured (satisfy isAlphaNum)) (appending (pured (satisfy (== '-'))) (pured (satisfy isLetter))))))) where isAlphaNum c = isLetter c || isDigit c -- | Make a package name. mkPackageName :: String -> Q Exp mkPackageName s = case parsePackageNameFromString s of Nothing -> error ("Invalid package name: " ++ show s) Just pn -> [|pn|] -- | Convenient way to parse a package name from a bytestring. parsePackageName :: MonadThrow m => ByteString -> m PackageName parsePackageName x = go x where go = either (const (throwM (PackageNameParseFail x))) return . parseOnly (packageNameParser <* endOfInput) -- | Migration function. parsePackageNameFromString :: MonadThrow m => String -> m PackageName parsePackageNameFromString = parsePackageName . S8.pack -- | Produce a bytestring representation of a package name. packageNameByteString :: PackageName -> ByteString packageNameByteString (PackageName n) = n -- | Produce a string representation of a package name. packageNameString :: PackageName -> String packageNameString (PackageName n) = S8.unpack n -- | Produce a string representation of a package name. packageNameText :: PackageName -> Text packageNameText (PackageName n) = T.decodeUtf8 n -- | Convert from a Cabal package name. fromCabalPackageName :: Cabal.PackageName -> PackageName fromCabalPackageName (Cabal.PackageName name) = let !x = S8.pack name in PackageName x -- | Convert to a Cabal package name. toCabalPackageName :: PackageName -> Cabal.PackageName toCabalPackageName (PackageName name) = let !x = S8.unpack name in Cabal.PackageName x -- | Parse a package name from a file path. parsePackageNameFromFilePath :: MonadThrow m => Path a File -> m PackageName parsePackageNameFromFilePath fp = do base <- clean $ toFilePath $ filename fp case parsePackageNameFromString base of Nothing -> throwM $ CabalFileNameInvalidPackageName $ toFilePath fp Just x -> return x where clean = liftM reverse . strip . reverse strip ('l':'a':'b':'a':'c':'.':xs) = return xs strip _ = throwM (CabalFileNameParseFail (toFilePath fp)) instance ToJSON a => ToJSON (Map PackageName a) where toJSON = toJSON . Map.mapKeysWith const packageNameText instance FromJSON a => FromJSON (Map PackageName a) where parseJSON val = do m <- parseJSON val fmap Map.fromList $ mapM go $ Map.toList m where go (k, v) = fmap (, v) $ either (fail . show) return $ parsePackageNameFromString k -- | An argument which accepts a template name of the format -- @foo.hsfiles@. packageNameArgument :: O.Mod O.ArgumentFields PackageName -> O.Parser PackageName packageNameArgument = O.argument (do s <- O.str either O.readerError return (p s)) where p s = case parsePackageNameFromString s of Just x -> Right x Nothing -> Left ("Expected valid package name, but got: " ++ s)
akhileshs/stack
src/Stack/Types/PackageName.hs
bsd-3-clause
6,040
0
20
1,382
1,433
748
685
134
3
module Scope3 where f = let square x = x + x in g 55 where g x = square x square x = x * x
kmate/HaRe
old/testing/whereToLet/Scope3_TokOut.hs
bsd-3-clause
133
0
9
69
55
27
28
4
1
{-# LANGUAGE GADTs #-} module ShouldFail2 where data T a where C :: Int -> T Int D :: Bool -> T Bool -- should fail because variable is wobbly foo (C x) = x foo (D b) = b
urbanslug/ghc
testsuite/tests/gadt/gadt-dim2.hs
bsd-3-clause
185
0
7
54
63
35
28
7
1
-- !!! Check the handling of 'qualified' and 'as' clauses module ShouldCompile where import Data.List as L ( intersperse ) x = L.intersperse y = intersperse
wxwxwwxxx/ghc
testsuite/tests/parser/should_compile/read025.hs
bsd-3-clause
162
0
5
31
29
19
10
4
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE StandaloneDeriving, GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Control.OperationalTransformation.Selection.Tests (tests) where import Control.OperationalTransformation import Control.OperationalTransformation.Selection import Control.OperationalTransformation.Text import Data.Aeson.Types hiding (Result) import Data.Monoid import Test.HUnit hiding (Test) import Test.QuickCheck import Test.Tasty import Test.Tasty.HUnit (testCase) import Test.Tasty.QuickCheck (testProperty) instance Arbitrary Range where arbitrary = Range <$> (abs <$> arbitrary) <*> (abs <$> arbitrary) deriving instance Arbitrary Selection prop_json_id :: Selection -> Bool prop_json_id o = parseMaybe parseJSON (toJSON o) == Just o testUpdateRange :: Assertion testUpdateRange = do let range = Range 3 7 Range 8 10 @=? updateCursor (TextOperation [Retain 3, Insert "lorem", Delete 2, Retain 42]) range Range 0 0 @=? updateCursor (TextOperation [Delete 45]) range testUpdateSelection :: Assertion testUpdateSelection = let sel = Selection [Range 2 4, Range 6 8] in Selection [Range 2 6, Range 8 8] @=? updateCursor (TextOperation [Retain 3, Insert "hi", Retain 3, Delete 2]) sel testSize :: Assertion testSize = do size (createCursor 5) @=? 0 size (Selection [Range 5 8, Range 10 20]) @=? 13 prop_sizeNotNegative :: Selection -> Bool prop_sizeNotNegative sel = size sel >= 0 prop_sizeAdditive :: Selection -> Selection -> Bool prop_sizeAdditive sel1 sel2 = size sel1 + size sel2 == size (sel1 <> sel2) prop_sizeZero_notSomethingSelected :: Selection -> Bool prop_sizeZero_notSomethingSelected sel = (size sel /= 0) == (somethingSelected sel) tests :: TestTree tests = testGroup "Control.OperationalTransformation.Selection" [ testProperty "prop_json_id" prop_json_id , testCase "testUpdateRange" testUpdateRange , testCase "testUpdateSelection" testUpdateSelection , testCase "testSize" testSize , testProperty "prop_sizeNotNegative" prop_sizeNotNegative , testProperty "prop_sizeAdditive" prop_sizeAdditive , testProperty "prop_sizeZero_notSomethingSelected" prop_sizeZero_notSomethingSelected ]
thomasjm/ot.hs
test/Control/OperationalTransformation/Selection/Tests.hs
mit
2,203
0
12
307
606
314
292
50
1
import Data.List import Data.Char import Data.Tree hiding (Tree ) data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a deriving (Eq,Ord,Show) data BTree a = BNil | BNode a (BTree a) (BTree a) deriving Show data Move = SM Board Pos Pos | KM | MKM data Fig = W | B | WD | BD | E deriving (Show, Eq) type Board = [[Fig]] type Pos = (Int, Int) charToFig :: Char -> Fig charToFig 'w' = W charToFig 'W' = WD charToFig 'b' = B charToFig 'B' = BD charToFig '.' = E figToChar :: Fig -> Char figToChar W = 'w' figToChar WD = 'W' figToChar B = 'b' figToChar BD = 'B' figToChar E = '.' initialBoardStr = ".b.b.b.b\n\ \b.b.b.b.\n\ \.b.b.b.b\n\ \........\n\ \........\n\ \w.w.w.w.\n\ \.w.w.w.w\n\ \w.w.w.w." szachownica = initBoard initialBoardStr --nieodporne na znak nowej linii fromStr2 :: String -> [Fig] fromStr2 str = map charToFig str fromStr :: String -> [Fig] fromStr str = map charToFig $ concat . lines $ str toStr2 :: [Fig] -> String toStr2 l = intersperse ' ' $ map figToChar l toStr :: [Fig] -> String toStr l = map figToChar l --toStr2 l = foldl1 (\acc x -> if isSpace x then x:acc else acc)intersperse ' ' $ map figToChar l initBoard :: String -> Board initBoard str = map fromStr (lines str) --boardToStr :: Board -> [String] --boardToStr b = map toStr2 [x | x <- b] boardToStr :: Board -> [String] boardToStr b = map toStr2 b addRowNumber num line = (show num) ++ " " ++ line addRowNumbers boardstr = zipWith addRowNumber [0..7] boardstr addColNumbers boardstr = [" 0 1 2 3 4 5 6 7 "] ++ boardstr showBoard :: Board -> String showBoard board = unlines . addColNumbers . addRowNumbers $ boardToStr board showBoard2 :: Board -> IO() showBoard2 b = putStrLn $ unlines (map (\x->fst x ++ snd x) $ zip [show x ++ " "|x<-[1..8]] $ map toStr2 szachownica)++" 1 2 3 4 5 6 7 8" getFig :: Board -> Pos -> Fig getFig board (row, col) = board !! row !! col replaceWithFig :: Fig -> [Fig] -> Int -> [Fig] replaceWithFig fig (h:t) 0 = fig : t replaceWithFig fig (h:t) col = h : replaceWithFig fig t (col - 1) setFig :: Fig -> Board -> Pos -> Board setFig fig (h:t) (0, col) = replaceWithFig fig h col : t setFig fig (h:t) (row, col) = h : setFig fig t ((row - 1), col) countWhiteFigs :: Board -> Int countWhiteFigs [] = 0 countWhiteFigs (h:t) = (countWhiteFigs t) + (length (filter (\f -> f == W || f == WD) h)) countBlackFigs :: Board -> Int countBlackFigs [] = 0 countBlackFigs (h:t) = (countBlackFigs t) + (length (filter (\f -> f == B || f == BD) h)) getRow :: Pos -> Int getRow p = fst p getCol :: Pos -> Int getCol p = snd p isEmpty :: Board -> Pos -> Bool isEmpty b p = (getFig b p) == E isWhite :: Board -> Pos -> Bool isWhite b p = (getFig b p) == W || (getFig b p) == WD isBlack :: Board -> Pos -> Bool isBlack b p = (getFig b p) == B || (getFig b p) == BD isValidPos :: Pos -> Bool isValidPos (row, col) = (row >= 0) && (row <= 7) && (col >= 0) && (col <= 7) countPos :: Pos -> Pos -> Pos countPos (row, col) (neighborRow, neighborCol) = ((countIndex row neighborRow), (countIndex col neighborCol)) where countIndex index neighborIndex = 2 * neighborIndex - index capturedPos :: Pos -> Pos -> Pos capturedPos (r1, c1) (r2, c2) = (quot (r1 + r2) 2, quot (c1 + c2) 2) --setFig :: Fig -> Board -> Pos -> Board --setFig fig (h:t) (0, col) = replaceWithFig fig h col : t --setFig fig (h:t) (row, col) = h : setFig fig t ((row - 1), col) makeCaptureMove :: Board -> Pos -> Pos -> Board makeCaptureMove b from to | isWhite b from = (setFig E (setFig W (setFig E b from) to) (capturedPos from to)) | isBlack b from = (setFig E (setFig B (setFig E b from) to) (capturedPos from to)) --makeSimpleMove :: Move -> Board --makeSimpleMove (SM b from to) --makeSimpleMove b from to makeSimpleMove :: Board -> Pos -> Pos -> Board makeSimpleMove b from to | isWhite b from = setFig W (setFig E b from) to | isBlack b from = setFig B (setFig E b from) to --n is a list of nieghbors --getCaptureMoves :: Board -> Pos -> [Pos] -> [Pos] --getCaptureMoves b p n = [pos | pos <- map (countPos p) n, isValidPos pos, isEmpty b pos] getCaptureMoves :: ((Board, Pos), [Pos]) -> [((Board, Pos), [Pos])] getCaptureMoves ((_, _), []) = [] getCaptureMoves ((b, p), n) = x ++ concat (map getCaptureMoves x) where x = [((makeCaptureMove b p pos, pos), (getNeighbors (makeCaptureMove b p pos) pos)) | pos <- map (countPos p) n, isValidPos pos, isEmpty b pos] getNeighbors :: Board -> Pos -> [Pos] getNeighbors b (row, col) | isWhite b (row, col) = [(x, y) | x <- [(row - 1), (row + 1)], y <- [(col - 1), (col + 1)], isValidPos (x, y), isBlack b (x, y)] | isBlack b (row, col) = [(x, y) | x <- [(row - 1), (row + 1)], y <- [(col - 1), (col + 1)], isValidPos (x, y), isWhite b (x, y)] getComplexMoves :: Board -> Pos -> [(Board, Pos)] getComplexMoves b p = map fst (getCaptureMoves ((b, p), (getNeighbors b p))) getSimpleMoves :: Board -> Pos -> [(Board, Pos)] getSimpleMoves b (row, col) = [(makeSimpleMove b (row, col) (x, y), (x, y)) | x <- [(row - 1)], y <- [(col - 1), (col + 1)], isValidPos (x, y), isEmpty b (x, y)] getMoves :: Board -> Pos -> [(Board, Pos)] getMoves b p | isEmpty b p = [] | otherwise = getSimpleMoves b p ++ getComplexMoves b p b = initBoard ".b.b.b.b\n\ \b.b.b.b.\n\ \...b.b.b\n\ \.b......\n\ \........\n\ \wb..w.w.\n\ \ww.w.w.w\n\ \w.w.w.w." x = showBoard b list = getMoves b (6,0) move = showBoard $ fst $ last list -- minmax algorytm do optymalnego ruchu -- lines Data.Tree -- odciecie drzewa --minmax to ma byc minmax a nie minmax dla konkretnego rozwiazania (tak jest najlepiej) -- funkcja otwarta, sieci petriego -- gęsty graf, multigraf -- neoforj -- moves f board = (genkill f b, genMoves f b) --test quickcheck automatycznie generuje testy --IORef do zmiennych -- import Data.Tree -- drzewo dokłdnie takie jakie potrzebne jest w tej implementacji -- funkcja oceny planszy next time --zip [(x,y)|x<-[1..8],y<-[1..8]] $ fromStr initialBoardStr --zip [(x,y)|x<-[1..8],y<-[1..8]] $ concat b --addRowNumber' :: Int -> String -> String --addRowNumber' num line = (show num) ++ " " ++ line --addRowNumbers' :: [Fig] --addRowNumbers' board = zipWith addRowNumber [1..8] board {- Abstrakcje gier planszowych Generalne: - plansza - pola (rozmieszczenie obok siebie, kolumny, rzedy itd) - figury - rodzaje - reguly ruchu - reguly bicia - reguly zamiany w inne figury - rozmieszczenie poczatkowe Warcabowe: -plansza 8x8 - figury: - rozmieszczenie poczatkowe - pionki albo damki - reguly ruchu dla pionkow i reguly ruchu dla damek - regula bicia dla pionkow i regula bicia dla damek - regula zamiany pionkow w damki -} --infiniteTree :: BTree Int --infiniteTree = go 1 where --go n = BNode (go (2*n)) n (go (2*n+1)) toDataTree (Leaf a) = Node a [] toDataTree (Branch b cs ds) = Node b [toDataTree cs, toDataTree ds] d = Branch "1" (Branch "11" (Leaf "111") (Leaf "112")) (Branch "12" (Leaf "121") (Leaf "122")) e = toDataTree d f = putStrLn $ drawTree e
RAFIRAF/HASKELL
warcaby.hs
mit
7,234
11
15
1,681
2,565
1,371
1,194
111
1
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.HdfsProtos.CryptoProtocolVersionProto (CryptoProtocolVersionProto(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data CryptoProtocolVersionProto = UNKNOWN_PROTOCOL_VERSION | ENCRYPTION_ZONES deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable CryptoProtocolVersionProto instance Prelude'.Bounded CryptoProtocolVersionProto where minBound = UNKNOWN_PROTOCOL_VERSION maxBound = ENCRYPTION_ZONES instance P'.Default CryptoProtocolVersionProto where defaultValue = UNKNOWN_PROTOCOL_VERSION toMaybe'Enum :: Prelude'.Int -> P'.Maybe CryptoProtocolVersionProto toMaybe'Enum 1 = Prelude'.Just UNKNOWN_PROTOCOL_VERSION toMaybe'Enum 2 = Prelude'.Just ENCRYPTION_ZONES toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum CryptoProtocolVersionProto where fromEnum UNKNOWN_PROTOCOL_VERSION = 1 fromEnum ENCRYPTION_ZONES = 2 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.HdfsProtos.CryptoProtocolVersionProto") . toMaybe'Enum succ UNKNOWN_PROTOCOL_VERSION = ENCRYPTION_ZONES succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.HdfsProtos.CryptoProtocolVersionProto" pred ENCRYPTION_ZONES = UNKNOWN_PROTOCOL_VERSION pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.HdfsProtos.CryptoProtocolVersionProto" instance P'.Wire CryptoProtocolVersionProto 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 CryptoProtocolVersionProto instance P'.MessageAPI msg' (msg' -> CryptoProtocolVersionProto) CryptoProtocolVersionProto where getVal m' f' = f' m' instance P'.ReflectEnum CryptoProtocolVersionProto where reflectEnum = [(1, "UNKNOWN_PROTOCOL_VERSION", UNKNOWN_PROTOCOL_VERSION), (2, "ENCRYPTION_ZONES", ENCRYPTION_ZONES)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.hdfs.CryptoProtocolVersionProto") ["Hadoop", "Protos"] ["HdfsProtos"] "CryptoProtocolVersionProto") ["Hadoop", "Protos", "HdfsProtos", "CryptoProtocolVersionProto.hs"] [(1, "UNKNOWN_PROTOCOL_VERSION"), (2, "ENCRYPTION_ZONES")] instance P'.TextType CryptoProtocolVersionProto where tellT = P'.tellShow getT = P'.getRead
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/HdfsProtos/CryptoProtocolVersionProto.hs
mit
2,945
0
11
421
601
327
274
53
1
import Test.Hspec import Test.QuickCheck import Control.Exception (evaluate) import List1 import List2 import List3 import Arithmetic main :: IO () main = hspec $ do describe "lists 1" $ do it "1. Find the last element of a list" $ do myLast [1,2,3,4] `shouldBe` (4 :: Int) myLast ['x','y','z'] `shouldBe` ('z' :: Char) it "2. Find the last but one element of a list" $ do myButLast [1,2,3,4] `shouldBe` (3 :: Int) myButLast ['a'..'z'] `shouldBe` ('y' :: Char) it "8. Eliminate consecutive duplicates of list elements" $ do compress "aaaabccaadeeee" `shouldBe` ("abcade" :: String) compress "abc" `shouldBe` ("abc" :: String) compress [1,2,3,4,4,5] `shouldBe` ([1,2,3,4,5] :: [Int]) it "9. Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists." $ do pack ['a','a','a','a','b','c','c','a','a','d','e','e','e','e'] `shouldBe` (["aaaa","b","cc","aa","d","eeee"]) it "10. Run-length encoding of a list" $ do encode "aaaabccaadeeee" `shouldBe` ([(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')] :: [(Int,Char)]) encode "aabbcde" `shouldBe` ([(2,'a'),(2,'b'),(1,'c'),(1,'d'),(1,'e')] :: [(Int,Char)]) describe "lists 2" $ do it "11. run Run-length with single/multiple elements" $ do encodeModified "aaaabccdeeee" `shouldBe` ([Multiple 4 'a',Single 'b',Multiple 2 'c',Single 'd',Multiple 4 'e'] :: [Element Char]) encodeModified "a" `shouldBe` ([Single 'a'] :: [Element Char]) it "12. Decode a run-length encoded list." $ do decodeModified [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e'] `shouldBe` "aaaabccaadeeee" decodeModified [Multiple 2 'a',Single 'b'] `shouldBe` "aab" it "14. Duplicate the elements of a list." $ do dupli [1, 2, 3] `shouldBe` [1,1,2,2,3,3] dupli' [1, 2, 3] `shouldBe` [1,1,2,2,3,3] it "15. Replicate the elements of a list a given number of times" $ do repli "abc" 3 `shouldBe` "aaabbbccc" repli [1,2] 2 `shouldBe` [1,1,2,2] it "16. Drop every N'th element from a list." $ do dropEvery "abcdefghik" 3 `shouldBe` "abdeghk" dropEvery "" 3 `shouldBe` "" --dropEvery [] 2 `shouldBe` ([]) it "17. Split a list into two parts; the length of the first part is given." $ do split "abcdefghik" 3 `shouldBe` ("abc", "defghik") split "abc" 3 `shouldBe` ("abc", "") split "abc" 5 `shouldBe` ("abc", "") it "18. Extract a slice from a list." $ do slice ['a','b','c','d','e','f','g','h','i','k'] 3 7 `shouldBe` "cdefg" slice ['a','b','c','d','e','f','g','h','i','k'] 3 100 `shouldBe` "cdefghik" slice ['a','b','c','d','e','f','g','h','i','k'] 5 6 `shouldBe` "ef" slice ['a','b'] 3 100 `shouldBe` "" it "19. Rotate a list N places to the left" $ do rotate ['a','b','c','d','e','f','g','h'] 3 `shouldBe` "defghabc" rotate ['a','b','c','d','e','f','g','h'] (-2) `shouldBe` "ghabcdef" it "20. Remove the K'th element from a list" $ do removeAt 2 "abcd" `shouldBe` ('b',"acd") describe "list 3" $ do it "21. Insert an element at a given position into a list." $ do -- insertAt 'X' "abcd" 0 `shouldThrow` anyException insertAt 'X' "abcd" 2 `shouldBe` "aXbcd" it "22. Create a list containing all integers within a given range." $ do range 4 9 `shouldBe` [4,5,6,7,8,9] describe "arithmetic" $ do it "31. Determine whether a given integer number is prime." $ do isPrime 7 `shouldBe` True
matteosister/haskell-exercises
spec.hs
mit
3,481
1
19
647
1,399
779
620
63
1
-- file: ch14/MultiplyTo.hs -- Found at http://book.realworldhaskell.org/read/monads.html module ListMonadExample where multiplyTo :: Int -> [(Int, Int)] multiplyTo n = do x <- [1..n] y <- [x..n] guarded (x * y == n) $ return (x, y) where guarded :: Bool -> [a] -> [a] guarded True xs = xs guarded False _ = []
iduhetonas/haskell-projects
HelloWorld/listMonad.hs
mit
333
0
11
76
129
70
59
9
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Blunt.App.Application where import qualified Blunt.App.Markup as Markup import qualified Blunt.Component as Component import Control.Category ((>>>)) import qualified Control.Exception as Exception import qualified Control.Monad as Monad import qualified Data.Aeson as Aeson import qualified Data.Aeson.Types as Aeson import qualified Data.ByteString.Lazy.Char8 as ByteString import qualified Data.FileEmbed as FileEmbed import Data.Function ((&)) import qualified Data.List as List import qualified Data.Text.Lazy as Text import qualified GHC.Generics as Generics import qualified Lambdabot.Pointful as Pointful import qualified Network.HTTP.Types as HTTP import qualified Network.Wai as Wai import qualified Network.Wai.Handler.WebSockets as WebSockets import qualified Network.WebSockets as WebSockets import qualified Pointfree as Pointfree import qualified System.Timeout as Timeout application :: (Component.Logs, Component.Metrics) -> Wai.Application application (logs,metrics) = WebSockets.websocketsOr WebSockets.defaultConnectionOptions (ws logs metrics) http ws :: Component.Logs -> Component.Metrics -> WebSockets.ServerApp ws logs metrics pending = do connection <- WebSockets.acceptRequest pending WebSockets.forkPingThread connection 30 app connection & Monad.forever where app connection = do Component.metricsCounter metrics "server.convert" 1 Component.metricsTimed metrics "server.convert_duration_s" (do message <- WebSockets.receiveData connection Component.logsInfo logs (Text.unpack message) result <- safeConvert message let json = Aeson.encode result Component.logsDebug logs (ByteString.unpack json) json & WebSockets.sendTextData connection) http :: Wai.Application http request respond = do let response = case (Wai.requestMethod request, Wai.pathInfo request) of ("GET",[]) -> Wai.responseLBS status headers body where status = HTTP.ok200 headers = [("Content-Type", "text/html; charset=utf-8")] body = Markup.markup ("GET",["favicon.ico"]) -> Wai.responseLBS status headers body where status = HTTP.ok200 headers = [("Content-Type", "image/x-icon")] body = ByteString.fromStrict $(FileEmbed.embedFile "static/favicon.ico") _ -> Wai.responseLBS HTTP.notFound404 [] "" respond response safeConvert :: Text.Text -> IO Conversion safeConvert message = do result <- Timeout.timeout 100000 (convert message) case result of Nothing -> return Conversion { conversionPointfree = [] , conversionPointful = [] } Just conversion -> return conversion convert :: Text.Text -> IO Conversion convert message = do let input = Text.unpack message pf <- safePointfree input let pl = safePointful input return Conversion { conversionPointfree = pf , conversionPointful = pl } safePointfree :: String -> IO [String] safePointfree input = input & Pointfree.pointfree & Exception.evaluate & Exception.handle handler handler :: Exception.SomeException -> IO [String] handler _exception = return [] safePointful :: String -> [String] safePointful input = let output = Pointful.pointful input in if any (`List.isPrefixOf` output) ["Error:", "<unknown>.hs:"] then [] else if ";" `List.isSuffixOf` output && not (";" `List.isSuffixOf` input) then [init output] else [output] data Conversion = Conversion { conversionPointfree :: [String] , conversionPointful :: [String] } deriving (Generics.Generic,Read,Show) instance Aeson.ToJSON Conversion where toJSON = Aeson.genericToJSON Aeson.defaultOptions { Aeson.fieldLabelModifier = drop (length ("Conversion" :: String)) >>> Aeson.camelTo2 '_' }
tfausak/blunt
library/Blunt/App/Application.hs
mit
4,412
0
19
1,233
1,062
584
478
106
3
import Control.FRPNow import Control.FRPNow.Vty.Core import Control.FRPNow.Vty.Widgets import Data.Monoid import Graphics.Vty hiding (Event) showImage :: Show a => a -> Image showImage = string defAttr . show sumWidget :: EvStream VEvent -> MakeWidget sumWidget eEv bDis bVis = do sum <- foldEs (+) 0 $ 1 <$ (filterEs (isKey $ KChar 'a') eEv) let img = (mappend (string defAttr "Summing time!") . showImage) <$> sum return $ originWidget [] <$> img <*> bDis <*> bVis timeWidget :: Behavior Double -> MakeWidget timeWidget bT bDis bVis = do bTotalTime <- (integrate bT $ (\b -> if b then 1 else 0) <$> bVis) :: Behavior (Behavior Double) let img = (string defAttr . mappend "Time: " . show) <$> bTotalTime return $ originWidget [] <$> img <*> bDis <*> bVis sizeWidget :: MakeWidget sizeWidget bD bVis = do return $ originWidget [] <$> (showImage <$> bD) <*> bD <*> bVis mainWidget :: EvStream VEvent -> Behavior Double -> Behavior DisplayRegion -> Now (Behavior Widget) mainWidget eV bT bD = sampleNow $ keyToQuit (KChar 'q') eV bD $ vertPane 2 (simpleWidget (string defAttr "Hi" <> string defAttr "==========")) $ tabbingWidget (filterEs (isKey $ KChar 'n') eV) (filterEs (isKey $ KChar 'l') eV) [timeWidget bT, sumWidget eV, sizeWidget ] main = runWidget mainWidget
edwardwas/FRPNow-Vty
src/Example/Main.hs
mit
1,323
1
15
265
525
261
264
26
2
{-# OPTIONS_GHC -O0 #-} {-# LANGUAGE CPP, DeriveGeneric, LambdaCase, MagicHash, StandaloneDeriving #-} {- | Communication between the compiler (GHCJS) and runtime (on node.js) for Template Haskell -} module GHCJS.Prim.TH.Types ( Message(..) , THResultType(..) ) where import Control.Applicative import Data.Binary import Data.ByteString (ByteString) import Data.Word import GHC.Generics import GHC.Exts import GHCJS.Prim.TH.Serialized import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Syntax as TH data THResultType = THExp | THPat | THType | THDec | THAnnWrapper deriving (Enum, Generic) data Message -- | compiler to node requests = RunTH THResultType ByteString (Maybe TH.Loc) | FinishTH -- | node to compiler responses | RunTH' ByteString -- ^ serialized result | FinishTH' -- | node to compiler requests | NewName String | Report Bool String | LookupName Bool String | Reify TH.Name | ReifyInstances TH.Name [TH.Type] | ReifyRoles TH.Name | ReifyAnnotations TH.AnnLookup | ReifyModule TH.Module | AddDependentFile FilePath | AddTopDecls [TH.Dec] -- | compiler to node responses | NewName' TH.Name | Report' | LookupName' (Maybe TH.Name) | Reify' TH.Info | ReifyInstances' [TH.Dec] | ReifyRoles' [TH.Role] | ReifyAnnotations' [ByteString] | ReifyModule' TH.ModuleInfo | AddDependentFile' | AddTopDecls' -- | exit with error status | QFail String | QException String deriving (Generic) instance Binary THResultType instance Binary Message #if MIN_VERSION_template_haskell(2,11,0) #error "unsupported template-haskell version" #elif MIN_VERSION_template_haskell(2,9,0) #if !MIN_VERSION_template_haskell(2,10,0) deriving instance Generic TH.Pred deriving instance Generic TH.Loc deriving instance Generic TH.Name deriving instance Generic TH.ModName deriving instance Generic TH.PkgName deriving instance Generic TH.NameSpace deriving instance Generic TH.Module deriving instance Generic TH.Info deriving instance Generic TH.Type deriving instance Generic TH.TyLit deriving instance Generic TH.TyVarBndr deriving instance Generic TH.Role deriving instance Generic TH.Lit deriving instance Generic TH.Range deriving instance Generic TH.Stmt deriving instance Generic TH.Pat deriving instance Generic TH.Exp deriving instance Generic TH.Dec deriving instance Generic TH.Guard deriving instance Generic TH.Body deriving instance Generic TH.Match deriving instance Generic TH.Fixity deriving instance Generic TH.TySynEqn deriving instance Generic TH.FamFlavour deriving instance Generic TH.FunDep deriving instance Generic TH.AnnTarget deriving instance Generic TH.RuleBndr deriving instance Generic TH.Phases deriving instance Generic TH.RuleMatch deriving instance Generic TH.Inline deriving instance Generic TH.Pragma deriving instance Generic TH.Safety deriving instance Generic TH.Callconv deriving instance Generic TH.Foreign deriving instance Generic TH.Strict deriving instance Generic TH.FixityDirection deriving instance Generic TH.OccName deriving instance Generic TH.Con deriving instance Generic TH.AnnLookup deriving instance Generic TH.ModuleInfo deriving instance Generic TH.Clause #endif #if !MIN_VERSION_template_haskell(2,10,0) instance Binary TH.Pred #endif instance Binary TH.Loc instance Binary TH.Name instance Binary TH.ModName #if MIN_VERSION_template_haskell(2,10,0) instance Binary TH.NameFlavour #else instance Binary TH.NameFlavour where put TH.NameS = putWord8 1 put (TH.NameQ mn) = putWord8 2 >> put mn put (TH.NameU i) = putWord8 3 >> put (I# i) put (TH.NameL i) = putWord8 4 >> put (I# i) put (TH.NameG ns pkg mn) = putWord8 5 >> put ns >> put pkg >> put mn get = getWord8 >>= \case 1 -> return TH.NameS 2 -> TH.NameQ <$> get 3 -> (\(I# i) -> TH.NameU i) <$> get 4 -> (\(I# i) -> TH.NameL i) <$> get 5 -> TH.NameG <$> get <*> get <*> get _ -> error "get Name: invalid tag" #endif instance Binary TH.PkgName instance Binary TH.NameSpace instance Binary TH.Module instance Binary TH.Info instance Binary TH.Type instance Binary TH.TyLit instance Binary TH.TyVarBndr instance Binary TH.Role instance Binary TH.Lit instance Binary TH.Range instance Binary TH.Stmt instance Binary TH.Pat instance Binary TH.Exp instance Binary TH.Dec instance Binary TH.Guard instance Binary TH.Body instance Binary TH.Match instance Binary TH.Fixity instance Binary TH.TySynEqn instance Binary TH.FamFlavour instance Binary TH.FunDep instance Binary TH.AnnTarget instance Binary TH.RuleBndr instance Binary TH.Phases instance Binary TH.RuleMatch instance Binary TH.Inline instance Binary TH.Pragma instance Binary TH.Safety instance Binary TH.Callconv instance Binary TH.Foreign instance Binary TH.Strict instance Binary TH.FixityDirection instance Binary TH.OccName instance Binary TH.Con instance Binary TH.AnnLookup instance Binary TH.ModuleInfo instance Binary TH.Clause #else #error "unsupported template-haskell version" #endif
ghcjs/ghcjs-prim
GHCJS/Prim/TH/Types.hs
mit
5,422
0
9
1,165
723
384
339
-1
-1
{-# LANGUAGE MultiParamTypeClasses, RecordWildCards, GADTs, FlexibleContexts, ExistentialQuantification #-} module SpaceShip.Class.State ( GameObjectClass (..) , GameObject (..) , updatePhysicalMovement , toroidFixedPhysicalPosition , key , render , animateStart , animateEnd , deviceInputs , kind , updateKind , GameObjectKey , StateClass (..) , ObjectKind (..) , isPhantom , isPhysical ) where import Math.Space2D import Graphics.UI.GLUT hiding (position) type GameObjectKey = Int type TimeState = (GLfloat, GLfloat) data ObjectKind = Phantom -- ethereal entity! | Physical { mass :: GLfloat -- kg , position :: Vertexf -- metres , velocity :: Vertexf -- metres / seconds , accforce :: Vertexf -- newtons (accumulated force on each step) , bradius :: GLfloat -- bound radius (for collision purposes) , collided :: Maybe GameObject -- one pending (not processed) collision with some other object , isSmoke :: Bool -- not collidable } isPhantom :: ObjectKind -> Bool isPhantom Phantom = True isPhantom _ = False isPhysical :: ObjectKind -> Bool isPhysical (Physical {..}) = True isPhysical _ = False updatePhysicalMovement :: GLfloat -> ObjectKind -> ObjectKind updatePhysicalMovement dt go@(Physical {..}) = let acceleration = (1.0 / mass) ^* accforce in go { -- simple Euler EDO solver position = position + dt ^* velocity , velocity = velocity + dt ^* acceleration , accforce = zero3f } toroidFixedPhysicalPosition :: StateClass s => s -> ObjectKind -> ObjectKind toroidFixedPhysicalPosition s go@(Physical {..}) = let vws = virtualViewportSize s in go { position = toroidFixedCoordinate ((-0.5) ^* vws) (0.5 ^* vws) position } class GameObjectClass go where key' :: go -> GameObjectKey render' :: go -> IO () render' _ = return () -- default nothing rendered animateStart' :: StateClass s => TimeState -> s -> go -> IO s animateStart' _ s _ = return s -- default not animated animateEnd' :: StateClass s => TimeState -> s -> go -> IO s animateEnd' _ s _ = return s -- default not animated deviceInputs' :: StateClass s => Key -> KeyState -> Modifiers -> Vertexf -> s -> go -> IO s deviceInputs' _ _ _ _ s _ = return s -- default ignore device inputs kind' :: go -> ObjectKind kind' _ = Phantom updateKind' :: go -> ObjectKind -> go data GameObject where GameObject :: GameObjectClass go => go -> GameObject key :: GameObject -> GameObjectKey key (GameObject go) = key' go render :: GameObject -> IO () render (GameObject go) = render' go animateStart :: StateClass s => TimeState -> s -> GameObject -> IO s animateStart t s (GameObject go) = animateStart' t s go animateEnd :: StateClass s => TimeState -> s -> GameObject -> IO s animateEnd t s (GameObject go) = animateEnd' t s go deviceInputs :: StateClass s => Key -> KeyState -> Modifiers -> Vertexf -> s -> GameObject -> IO s deviceInputs k ks m vp s (GameObject go) = deviceInputs' k ks m vp s go kind :: GameObject -> ObjectKind kind (GameObject go) = kind' go updateKind :: GameObject -> ObjectKind -> GameObject updateKind (GameObject go) ok = GameObject $ updateKind' go ok class StateClass o where virtualViewportSize :: o -> Vertexf -- width/height metres (0,0) centered physicalToVirtual :: o -> (Position -> Vertexf) setPhysicalToVirtual :: (Position -> Vertexf) -> o -> o addGameObject :: (GameObjectKey -> GameObject) -> o -> o removeGameObject :: GameObject -> o -> o updateGameObject :: GameObject -> o -> o gameObjects :: o -> [GameObject] getElapsedTime :: o -> IO (TimeState, o)
josejuan/Haskell-Spaceship-Meteorite
SpaceShip/Class/State.hs
mit
4,156
0
14
1,277
1,092
589
503
85
1
module Proteome.Project.Resolve where import qualified Control.Lens as Lens (over, view) import Control.Monad (foldM) import Control.Monad.Extra (firstJustM) import Data.List (nub) import Data.Map.Strict ((!?)) import qualified Data.Map.Strict as Map (toList, union) import Path (Abs, Dir, Path, parent, parseRelDir, toFilePath, (</>)) import Path.IO (doesDirExist) import Ribosome.Config.Setting (setting) import Ribosome.Control.Exception (catchAnyAs) import Ribosome.Data.Foldable (findMapMaybeM) import Ribosome.Data.SettingError (SettingError) import System.FilePath.Glob (globDir1) import qualified System.FilePath.Glob as Glob (compile) import System.FilePattern.Directory (getDirectoryFiles) import Proteome.Config (defaultTypeMarkers) import Proteome.Data.Project (Project(Project)) import Proteome.Data.ProjectConfig (ProjectConfig(ProjectConfig)) import qualified Proteome.Data.ProjectConfig as ProjectConfig (baseDirs, typeMarkers) import Proteome.Data.ProjectLang (ProjectLang(ProjectLang)) import Proteome.Data.ProjectMetadata (ProjectMetadata(DirProject, VirtualProject)) import Proteome.Data.ProjectName (ProjectName(ProjectName)) import Proteome.Data.ProjectRoot (ProjectRoot(ProjectRoot)) import Proteome.Data.ProjectSpec (ProjectSpec(ProjectSpec)) import qualified Proteome.Data.ProjectSpec as PS (ProjectSpec(..)) import Proteome.Data.ProjectType (ProjectType(ProjectType)) import Proteome.Data.ResolveError (ResolveError) import qualified Proteome.Data.ResolveError as ResolveError (ResolveError(..)) import Proteome.Path (parseAbsDirMaybe) import Proteome.Project (pathData) import qualified Proteome.Settings as Settings (projectConfig, projects) projectFromSegments :: ProjectType -> ProjectName -> ProjectRoot -> Project projectFromSegments tpe name root = Project (DirProject name root (Just tpe)) [] Nothing [] projectFromSpec :: ProjectSpec -> Project projectFromSpec (ProjectSpec name root tpe types lang langs) = Project (DirProject name root tpe) types lang langs hasProjectRoot :: ProjectRoot -> ProjectSpec -> Bool hasProjectRoot root spec = root == PS.root spec hasProjectTypeName :: ProjectType -> ProjectName -> ProjectSpec -> Bool hasProjectTypeName tpe' name' (ProjectSpec name _ (Just tpe) _ _ _) = name' == name && tpe' == tpe hasProjectTypeName _ _ _ = False byProjectTypeName :: [ProjectSpec] -> ProjectName -> ProjectType -> Maybe ProjectSpec byProjectTypeName specs name tpe = find (hasProjectTypeName tpe name) specs matchProjectBases :: [Path Abs Dir] -> ProjectRoot -> Bool matchProjectBases baseDirs (ProjectRoot root) = (parent . parent) root `elem` baseDirs byProjectBaseSubpath :: MonadIO m => MonadDeepError e ResolveError m => ProjectName -> ProjectType -> Path Abs Dir -> m (Maybe Project) byProjectBaseSubpath n@(ProjectName name) t@(ProjectType tpe) base = do tpePath <- hoistEitherAs (ResolveError.ParsePath tpe) $ parseRelDir (toString tpe) namePath <- hoistEitherAs (ResolveError.ParsePath name) $ parseRelDir (toString name) let root = base </> tpePath </> namePath exists <- doesDirExist root return $ if exists then Just $ projectFromSegments t n (ProjectRoot root) else Nothing byProjectBasesSubpath :: MonadIO m => MonadDeepError e ResolveError m => [Path Abs Dir] -> ProjectName -> ProjectType -> m (Maybe Project) byProjectBasesSubpath baseDirs name tpe = foldM subpath Nothing baseDirs where subpath (Just p) _ = return (Just p) subpath Nothing a = byProjectBaseSubpath name tpe a virtualProject :: ProjectName -> Project virtualProject name = Project (VirtualProject name) [] Nothing [] resolveByTypeAndPath :: [Path Abs Dir] -> ProjectName -> ProjectType -> ProjectRoot -> Maybe Project resolveByTypeAndPath baseDirs name tpe root = if matchProjectBases baseDirs root then Just (projectFromSegments tpe name root) else Nothing resolveByType :: MonadIO m => MonadDeepError e ResolveError m => [Path Abs Dir] -> [ProjectSpec] -> Maybe ProjectRoot -> ProjectName -> ProjectType -> m (Maybe Project) resolveByType baseDirs explicit root name tpe = do byBaseSubpath <- byProjectBasesSubpath baseDirs name tpe return $ byPath <|> byBaseSubpath <|> fmap projectFromSpec byTypeName where byTypeName = byProjectTypeName explicit name tpe byPath = root >>= resolveByTypeAndPath baseDirs name tpe fromProjectRoot :: Path Abs Dir -> Project fromProjectRoot dir = projectFromSegments tpe name root where (root, name, tpe) = pathData dir projectFromNameIn :: ∀ m . MonadIO m => ProjectName -> Path Abs Dir -> m (Maybe Project) projectFromNameIn (ProjectName name) base = fmap fromProjectRoot <$> join . find isJust <$> matches where matches = fmap (parseAbsDirMaybe . toText) <$> glob glob = liftIO $ globDir1 (Glob.compile ("*/" <> toString name)) (toFilePath base) resolveByName :: MonadIO m => [Path Abs Dir] -> ProjectName -> m (Maybe Project) resolveByName baseDirs name = findMapMaybeM (projectFromNameIn name) baseDirs globDir :: MonadIO m => MonadBaseControl IO m => Path Abs Dir -> [Text] -> m (Maybe FilePath) globDir root patterns = listToMaybe <$> catchAnyAs [] (liftIO $ getDirectoryFiles rootS patternsS) where patternsS = toString <$> patterns rootS = toFilePath root resolveFromDirContents :: MonadIO m => MonadBaseControl IO m => Map ProjectType [Text] -> ProjectName -> ProjectRoot -> m (Maybe Project) resolveFromDirContents typeMarkers name projectRoot@(ProjectRoot root) = fmap cons <$> firstJustM match (Map.toList typeMarkers) where cons projectType = projectFromSegments projectType name projectRoot match (tpe, patterns) = (tpe <$) <$> globDir root patterns resolveByRoot :: MonadIO m => MonadBaseControl IO m => ProjectConfig -> ProjectName -> [ProjectSpec] -> ProjectRoot -> m (Maybe Project) resolveByRoot (ProjectConfig _ _ _ _ typeMarkers _ _) name explicit root = maybe (resolveFromDirContents typeMarkers name root) (return . Just . projectFromSpec) fromExplicit where fromExplicit = find (hasProjectRoot root) explicit augment :: (Eq a, Ord k) => Map k [a] -> k -> [a] -> [a] augment m tpe as = case m !? tpe of Just extra -> nub $ as ++ extra Nothing -> as augmentTypes :: ProjectConfig -> ProjectType -> [ProjectType] -> [ProjectType] augmentTypes (ProjectConfig _ _ _ typeMap _ _ _) = augment typeMap realLang :: ProjectConfig -> ProjectType -> ProjectLang realLang (ProjectConfig _ _ _ _ _ langMap _) t@(ProjectType tpe) = fromMaybe (ProjectLang tpe) (langMap !? t) augmentLangs :: ProjectConfig -> ProjectLang -> [ProjectLang] -> [ProjectLang] augmentLangs (ProjectConfig _ _ _ _ _ _ langsMap) = augment langsMap augmentFromConfig :: ProjectConfig -> Project -> Project augmentFromConfig config (Project meta@(DirProject _ _ (Just tpe)) types lang langs) = Project meta (augmentTypes config tpe types) (Just realLang') (augmentLangs config realLang' langs) where realLang' = fromMaybe (realLang config tpe) lang augmentFromConfig _ project = project resolveProject :: MonadRibo m => MonadBaseControl IO m => MonadDeepError e ResolveError m => [ProjectSpec] -> ProjectConfig -> Maybe ProjectRoot -> ProjectName -> Maybe ProjectType -> m Project resolveProject explicit config root name tpe = do byType <- join <$> traverse (resolveByType baseDirs explicit root name) tpe byName <- if isJust root then return Nothing else resolveByName baseDirs name byRoot <- join <$> traverse (resolveByRoot config name explicit) root let byNameOrVirtual = fromMaybe (virtualProject name) byName let byTypeOrName = fromMaybe byNameOrVirtual byType let project = fromMaybe byTypeOrName byRoot logDebug @Text $ logMsg byType byName byRoot return $ augmentFromConfig config project where baseDirs = Lens.view ProjectConfig.baseDirs config logMsg byType byName byRoot = "resolved project: byType(" <> show byType <> ") byName(" <> show byName <> ") byRoot(" <> show byRoot <> ")" projectConfig :: NvimE e m => MonadRibo m => MonadDeepError e SettingError m => m ProjectConfig projectConfig = Lens.over ProjectConfig.typeMarkers (`Map.union` defaultTypeMarkers) <$> setting Settings.projectConfig resolveProjectFromConfig :: NvimE e m => MonadRibo m => MonadBaseControl IO m => MonadDeepError e SettingError m => MonadDeepError e ResolveError m => Maybe ProjectRoot -> ProjectName -> Maybe ProjectType -> m Project resolveProjectFromConfig root name tpe = do explicit <- setting Settings.projects config <- projectConfig resolveProject explicit config root name tpe
tek/proteome
packages/proteome/lib/Proteome/Project/Resolve.hs
mit
8,708
1
14
1,455
2,779
1,439
1,340
-1
-1
import Control.Concurrent.ParallelIO import Text.HandsomeSoup import Text.XML.HXT.Core textFromUrl url = do doc <- parsePage url print $ (url, length $ clean doc) main = do links <- runX $ fromUrl "http://www.datatau.com" >>> css "td.title a" !"href" parallel_ $ map textFromUrl links stopGlobalPool parsePage :: String -> IO [String] parsePage url = runX $ fromUrl url /> multi getText punctuations = ['!', '"', '#', '$', '%', '(', ')', '.', ',', '?'] removePunctuation = filter (`notElem` punctuations) specialSymbols = ['/', '-'] replaceSpecialSymbols = map $ (\c -> if c `elem` specialSymbols then ' ' else c) clean texts = filter (not.null) $ map clean' texts where clean' = removePunctuation.replaceSpecialSymbols.unwords.words
slon1024/haskell_parallel_io
Scraper.hs
mit
755
0
11
127
269
145
124
18
2
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module Main where import Benchmarks import Criterion.Main sizeSmall :: Int sizeSmall = 10^7 sizeMedium :: Int sizeMedium = 10^8 sizeLarge :: Int sizeLarge = 10^9 main :: IO () main = defaultMain [ bgroup "count1" [ bench "Handler 1 Small" $ whnf benchHandler1 sizeSmall , bench "Transf 1 Small" $ whnf benchTrans1 sizeSmall , bench "Handler 1 Medium" $ whnf benchHandler1 sizeMedium , bench "Transf 1 Medium" $ whnf benchTrans1 sizeMedium , bench "Handler 1 Large" $ whnf benchHandler1 sizeLarge , bench "Transf 1 Large" $ whnf benchTrans1 sizeLarge , bench "Handler 2 Small" $ whnf benchHandler2 sizeSmall , bench "Transf 2 Small" $ whnf benchTrans2 sizeSmall , bench "Handler 2 Medium" $ whnf benchHandler2 sizeMedium , bench "Transf 2 Medium" $ whnf benchTrans2 sizeMedium , bench "Handler 2 Large" $ whnf benchHandler2 sizeLarge , bench "Transf 2 Large" $ whnf benchTrans2 sizeLarge ]]
MichielDeCuyper/Algebraic-Effect-Handlers
src/Main.hs
mit
1,305
0
10
436
264
133
131
27
1
{-| Scry helpers -} module Urbit.King.Scry ( scryNow , module Urbit.Vere.Pier.Types ) where import Urbit.Prelude import Urbit.Vere.Serf.Types import Urbit.Arvo.Common (Desk) import Urbit.Vere.Pier.Types (ScryFunc) scryNow :: forall e n . (HasLogFunc e, FromNoun n) => ScryFunc -> Term -- ^ vane + care as two-letter string -> Desk -- ^ desk in scry path -> [Text] -- ^ resource path to scry for -> RIO e (Maybe n) scryNow scry vare desk path = io (scry Nothing (EachNo $ DemiOnce vare desk (Path $ MkKnot <$> path))) >>= \case Just ("omen", fromNoun @(Path, Term, n) -> Just (_,_,v)) -> pure $ Just v Just (_, fromNoun @n -> Just v) -> pure $ Just v Just (_, n) -> do logError $ displayShow ("uncanny scry result", vare, path, n) pure Nothing Nothing -> pure Nothing
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/King/Scry.hs
mit
876
0
14
243
309
169
140
-1
-1
{-# OPTIONS_GHC -XRank2Types #-} {- Implements a translation between monadic parametric representation of RHS - and Strategy Trees. (Andrej Bauer, Martin Hofmann and Aleksandr Karbyshev. - "On Monadic Parametricity of Second-Order Functionals", FoSSaCS 2013.) -} import Control.Monad import Control.Monad.Cont import Control.Monad.State type V = String type D = Integer type Env = [(V,D)] type Sol = V -> D type RHS = Monad m => (V -> m D) -> ((V,D) -> m ()) -> m D data Tree = Answ D | Read V (D -> Tree) | Write (V,D) Tree data Ops = Wt V | Rd V deriving Show depsFun :: Sol -> RHS -> [Ops] depsFun rho f = reverse $ snd $ runState (f read write) [] where read x = get >>= put . (Rd x:) >> return (rho x) write (x,_) = get >>= put . (Wt x:) evalFun :: Env -> RHS -> D evalFun env f = fst (runState (f read write) env) where read x = get >>= return . find x write x = get >>= put . (x:) fun2tree :: RHS -> Tree fun2tree f = runCont (f read write) Answ where read x = cont (Read x) write x = cont (\k -> Write x (k ())) depsTree :: Sol -> Tree -> [Ops] depsTree rho (Read x c) = Rd x : depsTree rho (c (rho x)) depsTree rho (Write (x,_) c) = Wt x : depsTree rho c depsTree _ (Answ x) = [] evalTree :: Env -> Tree -> D evalTree env (Answ x) = x evalTree env (Read x c) = evalTree env (c (find x env)) evalTree env (Write (x,d) c) = evalTree ((x,d):env) c -- For Testing. f :: RHS f get set = do x <- get "x" if (x > 4) then do forM_ ["x","y","z"] (\x -> set (x, 42)) get "z" else do set ("x",x+1) y <- get "x" return (x+y) test1 = [evalTree testenv (fun2tree f), evalFun testenv f] test2 = [depsTree (mksol testenv) (fun2tree f), depsFun (mksol testenv) f] find x = maybe 0 id . lookup x testenv = [("x",5), ("y",10)] testenv' = [("x",2), ("y",10)] mksol :: Env -> Sol mksol = flip find
vesalvojdani/haskell-fm
nice.hs
gpl-2.0
1,971
1
14
554
941
493
448
46
2
{-| This module is intended to be a pretty printer for pepa models. It should be updated to use 'Text.PrettyPrint.HughesPJ' -} module Language.Pepa.Srmc.Print ( hprintSrmcModel ) where {- Imported Standard Libraries -} {- Imported Local Libraries -} import Language.Pepa.Srmc.Syntax ( SrmcModel ( .. ) , SrmcDef ( .. ) ) import qualified Language.Pepa.Print as Print import Language.Pepa.QualifiedName ( hprintQualifiedName ) import Language.Pepa.Utils ( mkCSlist ) import Language.Hydra.Print ( printCexp ) {- End of Imports -} {-| The main exported function of this model. Prints an srmc model in a human readable format. -} hprintSrmcModel :: SrmcModel -> String hprintSrmcModel (SrmcModel sDefs composition) = unlines $ (map hprintServiceDef sDefs) ++ ("" : [ Print.hprintComponent composition ] ) hprintServiceDef :: SrmcDef -> String hprintServiceDef (ServiceDef ident sDefs) = unlines $ [ (hprintQualifiedName ident) ++ "::{" ] ++ (map hprintServiceDef sDefs) ++ [ "}" ] hprintServiceDef (NameSpaceSet ident names) = unwords [ hprintQualifiedName ident , "=" , "{" , mkCSlist $ map hprintQualifiedName names , "}" , ";" ] hprintServiceDef (VirtualDef ident oneRate) = unwords [ hprintQualifiedName ident , "= [" , printCexp oneRate , "] ;" ] hprintServiceDef (RateSet ident [ oneRate ]) = unwords [ hprintQualifiedName ident , "=" , printCexp oneRate , ";" ] hprintServiceDef (RateSet ident rates) = unwords [ hprintQualifiedName ident , "=" , "{" , mkCSlist $ map printCexp rates , "}" , ";" ] hprintServiceDef (ProcessSet ident [ oneP ] ) = unwords [ hprintQualifiedName ident , "=" , Print.hprintComponent oneP , ";" ] hprintServiceDef (ProcessSet ident comps) = unwords [ hprintQualifiedName ident , "=" , "{" , mkCSlist $ map Print.hprintComponent comps , "}" , ";" ]
allanderek/ipclib
Language/Pepa/Srmc/Print.hs
gpl-2.0
2,229
0
11
721
468
260
208
57
1
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback is free software: you can redistribute it and/or modify it under | | the terms of the GNU General Public License as published by the Free | | Software Foundation, either version 3 of the License, or (at your option) | | any later version. | | | | Fallback is distributed in the hope that it will be useful, but WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | | more details. | | | | You should have received a copy of the GNU General Public License along | | with Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} module Fallback.View.Upgrade (UpgradeState(..), UpgradeAction(..), newUpgradeView) where import Control.Applicative ((<$>)) import Control.Monad (zipWithM) import Fallback.Data.Color import Fallback.Data.Point import qualified Fallback.Data.SparseMap as SM import qualified Fallback.Data.TotalMap as TM (get) import Fallback.Draw import Fallback.Event (Key(..)) import Fallback.Scenario.Abilities (abilityDescription, abilityIconCoords, abilityMinPartyLevel) import Fallback.State.Party import Fallback.State.Resources (FontTag(..), Resources, rsrcAbilityIcon, rsrcFont, rsrcSheetSmallButtons) import Fallback.State.Simple import Fallback.State.Tags (AbilityTag, abilityName, classAbility) import Fallback.View.Base import Fallback.View.Dialog (newDialogBackgroundView) import Fallback.View.Hover import Fallback.View.Widget ------------------------------------------------------------------------------- data UpgradeState = UpgradeState { upsActiveCharacter :: CharacterNumber, upsParty :: Party, upsSpentSkills :: SM.SparseMap (CharacterNumber, AbilityNumber) Int, upsSpentStats :: SM.SparseMap (CharacterNumber, Stat) Int } data UpgradeAction = IncreaseSkill AbilityNumber | DecreaseSkill AbilityNumber | IncreaseStat Stat | DecreaseStat Stat | CancelUpgrades | CommitUpgrades upsGetCharacter :: UpgradeState -> Character upsGetCharacter ups = partyGetCharacter (upsParty ups) (upsActiveCharacter ups) upsStatPointsSpent :: UpgradeState -> Int upsStatPointsSpent ups = sum $ map (\s -> SM.get (upsActiveCharacter ups, s) (upsSpentStats ups)) [minBound .. maxBound] upsSkillPointsSpent :: UpgradeState -> Int upsSkillPointsSpent ups = sum $ map (\n -> SM.get (upsActiveCharacter ups, n) (upsSpentSkills ups)) [minBound .. maxBound] ------------------------------------------------------------------------------- newUpgradeView :: (MonadDraw m) => Resources -> HoverSink Cursor -> m (View UpgradeState UpgradeAction) newUpgradeView resources _cursorSink = do let headingFont = rsrcFont resources FontGeorgiaBold11 let infoFont = rsrcFont resources FontGeorgia11 upgradeRef <- newHoverRef Nothing let upgradeSink = hoverSink upgradeRef let rectFn _ (w, h) = let { w' = 272; h' = 320 } in Rect (half (w - w')) (half (h - h')) w' h' let makeStatWidget stat idx = subView (\_ (w, _) -> Rect (half (w - 140)) (40 + 20 * idx) 150 20) <$> newStatWidget resources upgradeSink stat let statPointsFn ups = "Stat points to spend: " ++ show (chrStatPoints (upsGetCharacter ups) - upsStatPointsSpent ups) let makeAbilityWidget abilNum idx = subView_ (Rect (20 + 48 * (idx `mod` 5)) (140 + 48 * (idx `div` 5)) 40 40) <$> newAbilityWidget resources upgradeSink abilNum let skillPointsFn ups = "Skill points to spend: " ++ show (chrSkillPoints (upsGetCharacter ups) - upsSkillPointsSpent ups) hoverJunction upgradeRef <$> compoundViewM [ (return $ hoverView upgradeSink Nothing nullView), (subView rectFn <$> compoundViewM [ (newDialogBackgroundView), (return $ vmap (("Upgrading " ++) . chrName . upsGetCharacter) $ makeLabel headingFont blackColor $ \(w, _) -> LocMidtop $ Point (w `div` 2) 12), (compoundView <$> zipWithM makeStatWidget [minBound .. maxBound] [0 ..]), (return $ vmap statPointsFn $ makeLabel_ infoFont (Color 64 64 64) $ LocTopleft $ (Point 70 105 :: IPoint)), (compoundView <$> zipWithM makeAbilityWidget [minBound .. maxBound] [0 ..]), (return $ vmap skillPointsFn $ makeLabel_ infoFont (Color 64 64 64) $ LocTopleft $ (Point 70 240 :: IPoint)), (subView (\_ (_, h) -> Rect 20 (h - 44) 80 24) <$> newSimpleTextButton resources "Cancel" [KeyEscape] CancelUpgrades), (subView (\_ (w, h) -> Rect (w - 100) (h - 44) 80 24) <$> newSimpleTextButton resources "Done" [KeyReturn] CommitUpgrades)]), (newStatInfoView resources upgradeRef), (newAbilityInfoView resources upgradeRef)] newStatWidget :: (MonadDraw m) => Resources -> HoverSink (Maybe (Either Stat AbilityNumber)) -> Stat -> m (View UpgradeState UpgradeAction) newStatWidget resources upgradeSink stat = do let infoFont = rsrcFont resources FontGeorgia11 let str = case stat of Strength -> "Strength:" Agility -> "Agility:" Intellect -> "Intellect:" let getStatValue ups = (TM.get stat $ chrBaseStats $ upsGetCharacter ups) + SM.get (upsActiveCharacter ups, stat) (upsSpentStats ups) let plusFn ups = if chrStatPoints (upsGetCharacter ups) > upsStatPointsSpent ups then Just () else Nothing let minusFn ups = if SM.get (upsActiveCharacter ups, stat) (upsSpentStats ups) > 0 then Just () else Nothing hoverView upgradeSink (Just $ Left stat) <$> compoundViewM [ (return $ compoundView [ (vmap (const str) $ makeLabel_ infoFont blackColor $ LocTopright (Point 60 1 :: IPoint)), (vmap (show . getStatValue) $ makeLabel_ infoFont blackColor $ LocTopright (Point 86 1 :: IPoint))]), (newMaybeView minusFn =<< newMinusButton resources (DecreaseStat stat) (LocTopleft $ Point 100 0)), (newMaybeView plusFn =<< newPlusButton resources (IncreaseStat stat) (LocTopleft $ Point 120 0))] newAbilityWidget :: (MonadDraw m) => Resources -> HoverSink (Maybe (Either Stat AbilityNumber)) -> AbilityNumber -> m (View UpgradeState UpgradeAction) newAbilityWidget resources upgradeSink abilNum = do let paintIcon ups = do let party = upsParty ups let char = partyGetCharacter party (upsActiveCharacter ups) let abilTag = classAbility (chrClass char) abilNum let mbRank = TM.get abilNum $ chrAbilities char let available = mbRank /= Just maxBound && partyLevel party >= abilityMinPartyLevel abilTag (nextAbilityRank mbRank) let tint = if available then whiteTint else Tint 255 255 255 64 let icon = rsrcAbilityIcon resources (abilityIconCoords abilTag) center <- rectCenter <$> canvasRect blitLocTinted tint icon (LocCenter center) let plusFn ups = let party = upsParty ups charNum = upsActiveCharacter ups char = partyGetCharacter party charNum abilTag = classAbility (chrClass char) abilNum spentOn n = SM.get (charNum, n) (upsSpentSkills ups) curRank = abilityRankPlus (TM.get abilNum $ chrAbilities char) (spentOn abilNum) in if curRank /= Just maxBound && partyLevel party >= abilityMinPartyLevel abilTag (nextAbilityRank curRank) && chrSkillPoints char > sum (map spentOn [minBound .. maxBound]) then Just () else Nothing let minusFn ups = if SM.get (upsActiveCharacter ups, abilNum) (upsSpentSkills ups) > 0 then Just () else Nothing hoverView upgradeSink (Just $ Right abilNum) <$> compoundViewM [ (return $ inertView paintIcon), (newMaybeView minusFn =<< newMinusButton resources (DecreaseSkill abilNum) (LocBottomleft $ Point 0 40)), (newMaybeView plusFn =<< newPlusButton resources (IncreaseSkill abilNum) (LocBottomright $ Point 40 40))] newStatInfoView :: (MonadDraw m) => Resources -> HoverRef (Maybe (Either Stat AbilityNumber)) -> m (View a b) newStatInfoView resources upgradeRef = do let inputFn _ = do mbUpgrade <- readHoverRef upgradeRef case mbUpgrade of Just (Left stat) -> return $ Just $ statDescription stat _ -> return Nothing let rectFn _ (w, _) = Rect 100 180 (w - 200) 200 tooltip <- newTooltipView resources vmapM inputFn <$> newMaybeView id (subView rectFn tooltip) newAbilityInfoView :: (MonadDraw m) => Resources -> HoverRef (Maybe (Either Stat AbilityNumber)) -> m (View UpgradeState b) newAbilityInfoView resources upgradeRef = do let inputFn ups = do mbUpgrade <- readHoverRef upgradeRef case mbUpgrade of Just (Right abilNum) -> do let charNum = upsActiveCharacter ups let char = upsGetCharacter ups let abilTag = classAbility (chrClass char) abilNum let spentOn n = SM.get (charNum, n) (upsSpentSkills ups) let curRank = abilityRankPlus (TM.get abilNum $ chrAbilities char) (spentOn abilNum) return $ Just $ abilityUpgradeDescription abilTag curRank $ partyLevel $ upsParty ups _ -> return Nothing let rectFn _ (w, _) = Rect 50 0 (w - 100) 300 tooltip <- newTooltipView resources vmapM inputFn <$> newMaybeView id (subView rectFn tooltip) ------------------------------------------------------------------------------- newPlusButton :: (MonadDraw m) => Resources -> b -> LocSpec Int -> m (View a b) newPlusButton = newPlusMinusButton 0 newMinusButton :: (MonadDraw m) => Resources -> b -> LocSpec Int -> m (View a b) newMinusButton = newPlusMinusButton 1 newPlusMinusButton :: (MonadDraw m) => Int -> Resources -> b -> LocSpec Int -> m (View a b) newPlusMinusButton col resources value loc = subView_ (locRect loc (16, 16)) <$> newButton paintFn (const ReadyButton) [] value where paintFn _ buttonState = do let row = case buttonState of ButtonUp -> 0 ButtonHover -> 1 ButtonDown -> 2 ButtonDisabled -> 3 rect <- canvasRect blitStretch ((rsrcSheetSmallButtons resources) ! (row, col)) rect ------------------------------------------------------------------------------- abilityUpgradeDescription :: AbilityTag -> Maybe AbilityRank -> Int -> String abilityUpgradeDescription abilTag abilRank level = "{b}" ++ abilityName abilTag ++ "{_} (" ++ status ++ ")\n" ++ abilityDescription abilTag where status = if abilRank < Just maxBound && level < requiredLevel then "rank " ++ show (abilityRankNumber nextRank) ++ " requires level " ++ show requiredLevel else case abilRank of Nothing -> "not yet learned" Just rank -> "currently at rank " ++ show (abilityRankNumber rank) nextRank = nextAbilityRank abilRank requiredLevel = abilityMinPartyLevel abilTag nextRank -------------------------------------------------------------------------------
mdsteele/fallback
src/Fallback/View/Upgrade.hs
gpl-3.0
12,433
142
19
3,594
3,152
1,669
1,483
215
5
{-# OPTIONS -Wall #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Examples where import GHC.TypeLits import Data.Void import Utils import Generic import Syntaxes ------------------------------------------------------------- -- OPEN TERMS WITH N FREE VARIABLES ------------------------------------------------------------- type family Free (n :: Nat) :: * where Free 0 = Void Free n = Maybe (Free (n - 1)) type OCase n = Case (Free n) type OTerm n = Term (Free n) ------------------------------------------------------------- -- EXAMPLES FOR TmF ------------------------------------------------------------- oTERM :: OTerm 1 oTERM = TmL' $ MkVar $ Just Nothing oTERM' :: OTerm 2 oTERM' = rename oTERM (fmap Just) idTERM :: Term Void idTERM = TmL' $ MkVar Nothing falseTERM :: Term Void falseTERM = subst oTERM $ maybe idTERM absurd . runVariable cutTERM :: Term Void cutTERM = TmA falseTERM falseTERM -- (\ x y -> y) (\ x y -> y) ---->* (\ y -> y) normTERM :: Term Void normTERM = norm cutTERM ------------------------------------------------------------- -- EXAMPLES FOR CsF ------------------------------------------------------------- oCASE :: OCase 1 oCASE = CsCA' (MkVar Nothing) $ Pair (MkVar (Just Nothing), MkVar Nothing) -- Either a (Either a b) -> Either a b oCASE' :: OCase 4 oCASE' = rename oCASE $ fmap (Just . Just . Just) -- Representing natural numbers in Case -- Defining addition by a fix point natToCase :: Integer -> Case a natToCase n | n <= 0 = CsLI CsUN natToCase n = CsRI $ natToCase (n - 1) caseToNat :: Case a -> Integer caseToNat t = case t of CsLI CsUN -> 0 CsRI n -> 1 + caseToNat n _ -> error "Malformed Nat" plus :: Case a plus = CsLA' $ {- m -} CsFX' $ {- m+ -} CsLA' $ {- n -} CsCA' (MkVar Nothing) $ {- case n -} Pair ( MkVar (Just (Just (Just Nothing))) , (CsRI $ MkVar (Just (Just Nothing)) $$ MkVar Nothing) ) five :: Integer five = caseToNat $ norm $ plus $$ natToCase 2 $$ natToCase 3 mult :: Case a mult = CsLA' $ {- m -} CsFX' $ {- m* -} CsLA' $ {- n -} CsCA' (MkVar Nothing) $ {- case n -} Pair ( CsLI CsUN , (plus $$ (MkVar (Just (Just (Just Nothing)))) $$ (MkVar (Just (Just Nothing)) $$ MkVar Nothing)) ) ten :: Integer ten = caseToNat $ norm $ mult $$ natToCase five $$ natToCase 2 ------------------------------------------------------------- -- EXAMPLES FOR CLF ------------------------------------------------------------- ones :: CList Integer ones = CList $ CLCON' 1 $ Var Z ones' :: [Integer] ones' = take 10 $ toStream ones twothrees :: CList Integer twothrees = CList $ CLCON' 2 $ CLCON' 3 $ Var $ S Z twothrees' :: [Integer] twothrees' = take 10 $ toStream twothrees threefours :: CList Integer threefours = fmap (+1) twothrees threefours' :: [Integer] threefours' = take 10 $ toStream threefours
gallais/potpourri
haskell/syntax-with-binding/Examples.hs
gpl-3.0
3,091
3
18
730
824
439
385
75
3
module TestSuites.RenderTextSpec (spec) where import Test.Hspec.Contrib.HUnit(fromHUnitTest) import Test.HUnit import Test.Hspec (hspec) import HsPredictor.Render.Text import HsPredictor.SQL.Queries import HsPredictor.CSV.Load import HelperFuncs (removeIfExists) main = hspec spec spec = fromHUnitTest $ TestList [ TestLabel ">>renderList" test_renderList, TestLabel ">>convertList" test_convertList, TestLabel ">>renderTable" test_renderTable ] stats = [("A", [3, 2 ,1]), ("B", [2, 3, 1])] l = [["A", "1", "2", "3"]] test_renderList = TestCase $ do let t = renderList l 3 t @?= ["| A| 1| 2| 3|", "-----------------"] test_convertList = TestCase $ do let t = convertList stats t @?= [["A", "3", "2", "1"], ["B", "2", "3", "1"]] testFilePath = "tests/tmp/test.csv" testDbPath = "tests/tmp/test.db" setUp = do removeIfExists testDbPath loadCSV testFilePath testDbPath test_renderTable = TestCase $ do setUp t <- renderTable testDbPath 1 t @?= (unlines ["|A|4|2|0|", "---------", "|C|2|3|1|", "---------", "|D|1|3|2|", "---------", "|B|0|2|4|", "---------"])
jacekm-git/HsPredictor
tests/TestSuites/RenderTextSpec.hs
gpl-3.0
1,246
0
11
321
353
201
152
38
1
{-# LANGUAGE ViewPatterns #-} module HipSpec.Heuristics.Associativity where import Test.QuickSpec.Equation import Test.QuickSpec.Term hiding (depth) -- If term is a function applied to two terms, Just return them unbin :: Term -> Maybe (Symbol,Term,Term) unbin (App (App (Const f) x) y) = Just (f,x,y) unbin _ = Nothing -- True if equation is an associativity equation eqIsAssoc :: Equation -> Bool eqIsAssoc ((unbin -> Just (f0,Var x0,unbin -> Just (g0,Var y0,Var z0))) :=: (unbin -> Just (f1,unbin -> Just (g1,Var x1,Var y1),Var z1))) = and [ f0 == f1 , g0 == g1 , f0 == g0 , x0 == x1 , y0 == y1 , z0 == z1 , x0 /= y0 , y0 /= z0 ] eqIsAssoc _ = False
danr/hipspec
src/HipSpec/Heuristics/Associativity.hs
gpl-3.0
689
0
15
156
278
154
124
16
1
module Layout where import Data.Time.Clock data Error = CompileFail | MemoryExceeded | TimeExceeded | WriteFail | NoError deriving (Eq,Show) type Rerror = Either Error (Bool,NominalDiffTime,String,Integer) type Berror = Either Error Bool
prannayk/conj
Judge/Layout.hs
gpl-3.0
239
0
6
32
74
45
29
5
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.AppState.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.AppState.Types ( -- * Service Configuration appStateService -- * OAuth Scopes , appStateScope -- * WriteResult , WriteResult , writeResult , wrCurrentStateVersion , wrKind , wrStateKey -- * ListResponse , ListResponse , listResponse , lrMaximumKeyCount , lrKind , lrItems -- * GetResponse , GetResponse , getResponse , grCurrentStateVersion , grKind , grData , grStateKey -- * UpdateRequest , UpdateRequest , updateRequest , urKind , urData ) where import Network.Google.AppState.Types.Product import Network.Google.AppState.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the Google App State API. This contains the host and root path used as a starting point for constructing service requests. appStateService :: ServiceConfig appStateService = defaultService (ServiceId "appstate:v1") "www.googleapis.com" -- | View and manage your data for this application appStateScope :: Proxy '["https://www.googleapis.com/auth/appstate"] appStateScope = Proxy
brendanhay/gogol
gogol-appstate/gen/Network/Google/AppState/Types.hs
mpl-2.0
1,662
0
7
362
159
110
49
39
1