code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
module KafkaSpec (spec) where
import Control.Applicative ((<$>))
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM)
import Data.IORef (modifyIORef', newIORef, readIORef)
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck
import qualified Data.Set as Set
import Kafka
import Test.Kafka.Arbitrary
-- | Keep running the given generator until a value that satisfies the given
-- predicate is produced.
generateSuchThat :: Gen a -> (a -> IO Bool) -> IO a
generateSuchThat gen f = loop
where
loop = do
a <- generate gen
match <- f a
if match
then return a
else loop
-- | Returns an IO action that will always return unique values from the given
-- generator.
uniqueGenerator :: Ord a => Gen a -> IO (IO a)
uniqueGenerator gen = do
generated <- newIORef Set.empty
let isNew a = Set.notMember a <$> readIORef generated
return $ do
a <- generateSuchThat gen isNew
modifyIORef' generated (Set.insert a)
return a
spec :: Socket -> Spec
spec conn = describe "Kafka" $ do
-- This is hacky but it will ensure that none of the tests run under the
-- same Kafka topic.
getNewTopic <- runIO $ uniqueGenerator arbitrary
prop "returns zero offset for empty topic" $ do
topic <- getNewTopic
let req = Offsets topic 0 OffsetsLatest 10
offsets conn req `shouldReturn` Right [0]
prop "can produce and fetch empty payloads" $ do
topic <- getNewTopic
produce conn [Produce topic 0 [""]]
Right resp <- pollMessages conn $ Fetch topic 0 0 (1024 * 1024)
fetchMessages resp `shouldBe` [""]
prop "can produce and fetch empty lists of payloads" $ do
topic <- getNewTopic
produce conn [Produce topic 0 []]
fetch conn [fetchRequest topic 0]
`shouldReturn` Right [FetchResponse [] 0]
prop "can fetch and produce" $ \(NonEmptyPayloadList messages) -> do
topic <- getNewTopic
produce conn [Produce topic 0 messages]
Right resp <- pollMessages conn (fetchRequest topic 0)
fetchMessages resp `shouldBe` messages
let newOffset = fetchNewOffset resp
offsets conn (Offsets topic 0 OffsetsLatest 10)
`shouldReturn` Right [newOffset, 0]
fetch conn [fetchRequest topic newOffset]
`shouldReturn` Right [FetchResponse [] newOffset]
prop "can multi-fetch and multi-produce" $ \(NonEmpty ps) -> do
topics <- replicateM (length ps) getNewTopic
let messageSets = map getPayloads ps
produceReqs = zipWith
(\t ms -> Produce t 0 ms) topics messageSets
fetchReqs = map (`fetchRequest` 0) topics
receivedAll (Left _) = False
receivedAll (Right responses) = all isSuccess responses
where
isSuccess = not . null . fetchMessages
produce conn produceReqs
responses <- do
result <- retryUntil receivedAll 10 500 (fetch conn fetchReqs)
case result of
Just (Right responses) -> return responses
Just (Left e) -> fail (show e)
Nothing -> fail "Failed to fetch messages."
map fetchMessages responses `shouldBe` messageSets
where
fetchRequest topic offset = Fetch topic 0 offset (1024 * 1024)
-- | Polls the given transport with the given Fetch request until a non-empty
-- list of messages is available.
--
-- Throws an error if a non-empty list of messages is not received after
-- trying for 5 seconds.
pollMessages :: Transport t => t -> Fetch -> IO (Response FetchResponse)
pollMessages t req = do
result <- retryUntil isSuccess 10 500 (fetch t [req])
case result of
Nothing -> fail "Failed to fetch messages."
Just xs -> return $ head <$> xs
where
isSuccess (Left _) = False
isSuccess (Right [resp]) = not . null . fetchMessages $ resp
isSuccess (Right xs) =
error $ "Too many messages in response: " ++ show xs
-- | Retries the given IO operation with the specified delay until the given
-- predicate on the result returns True.
--
-- Return Nothing if the maximum number of attempts was exceeded.
retryUntil :: (a -> Bool) -> Int -> Int -> IO a -> IO (Maybe a)
retryUntil predicate maxAttempts delayMillis m = loop 0
where
loop attempt
| attempt >= maxAttempts = return Nothing
| otherwise = do
a <- m
if predicate a
then return (Just a)
else threadDelay (delayMillis * 1000) >> loop (attempt + 1)
|
abhinav/kafka-client
|
integration-test/KafkaSpec.hs
|
mit
| 4,695 | 0 | 20 | 1,329 | 1,315 | 644 | 671 | 92 | 4 |
{-# LANGUAGE ScopedTypeVariables, TypeOperators, KindSignatures #-}
{-# LANGUAGE TypeFamilies, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}
-- | Utilities for creating selectors for non-record types.
-- In general, you should really use record types for your tables and
-- their record labels (i.e. #label) as selectors using
-- the @OverloadedLabels@ extension instead.
module Database.Selda.MakeSelectors
( Selectors, GSelectors
, selectors, tableWithSelectors
) where
import Control.Monad.State.Strict
import Data.Proxy
import GHC.Generics hiding (Selector, (:*:))
import qualified GHC.Generics as G
import Database.Selda.Generic (Relational)
import Database.Selda.Selectors
import Database.Selda.SqlRow
import Database.Selda.SqlType
import Database.Selda.Table
import Database.Selda.Types
-- | Generate selector functions for the given table.
-- Selectors can be used to access the fields of a query result tuple, avoiding
-- the need to pattern match on the entire tuple.
--
-- > tbl :: Table (Int, Text)
-- > tbl = table "foo" []
-- > (tblBar :*: tblBaz) = selectors tbl
-- >
-- > q :: Query s Text
-- > q = do
-- > row <- select tbl
-- > return (row ! tblBaz)
selectors :: forall a. (Relational a, GSelectors a (Rep a))
=> Table a
-> Selectors a
selectors _ = selectorsFor (Proxy :: Proxy a)
-- | A pair of the table with the given name and columns, and all its selectors.
-- For example:
--
-- > tbl :: Table (Int, Text)
-- > (tbl, tblBar :*: tblBaz)
-- > = tableWithSelectors "foo" []
-- >
-- > q :: Query s Text
-- > q = tblBaz `from` select tbl
tableWithSelectors :: forall a. (Relational a, GSelectors a (Rep a))
=> TableName
-> [Attr a]
-> (Table a, Selectors a)
tableWithSelectors name cs = (t, s)
where
t = table name cs
s = selectors t
-- | Generate selectors for the given type.
selectorsFor :: forall r. GSelectors r (Rep r) => Proxy r -> Selectors r
selectorsFor = flip evalState 0 . mkSel (Proxy :: Proxy (Rep r))
-- | An inductive tuple of selectors for the given relation.
type Selectors r = Sels r (Rep r)
type family Sels t f where
Sels t ((a G.:*: b) G.:*: c) = Sels t (a G.:*: (b G.:*: c))
Sels t (a G.:*: b) = Sels t a :*: Sels t b
Sels t (M1 x y f) = Sels t f
Sels t (K1 i a) = Selector t a
-- | Any table type that can have selectors generated.
class GSelectors t (f :: * -> *) where
mkSel :: Proxy f -> Proxy t -> State Int (Sels t f)
instance (SqlRow t, SqlType a) => GSelectors t (K1 i a) where
mkSel _ _ = unsafeSelector <$> state (\n -> (n, n+1))
instance (GSelectors t f, Sels t f ~ Sels t (M1 x y f)) =>
GSelectors t (M1 x y f) where
mkSel _ = mkSel (Proxy :: Proxy f)
instance GSelectors t (a G.:*: (b G.:*: c)) =>
GSelectors t ((a G.:*: b) G.:*: c) where
mkSel _ = mkSel (Proxy :: Proxy (a G.:*: (b G.:*: c)))
instance {-# OVERLAPPABLE #-}
( GSelectors t a
, GSelectors t b
, Sels t (a G.:*: b) ~ (Sels t a :*: Sels t b)
) => GSelectors t (a G.:*: b) where
mkSel _ p = do
x <- mkSel (Proxy :: Proxy a) p
xs <- mkSel (Proxy :: Proxy b) p
return (x :*: xs)
|
valderman/selda
|
selda/src/Database/Selda/MakeSelectors.hs
|
mit
| 3,266 | 0 | 12 | 786 | 948 | 515 | 433 | 54 | 1 |
module YNABFormat where
import DNBFormat
import Types
import Data.List (intercalate)
import Data.Time.Format (defaultTimeLocale, formatTime)
data YNABFormat = YNABFormat TrxDate Payee Category Explanation Outflow Inflow
instance Show YNABFormat where
show (YNABFormat trxDate payee cat exp outFlow inFlow) =
intercalate separator fields where
separator = ","
fields = [date, payee, cat, exp, show outFlow, show inFlow]
date = formatTime defaultTimeLocale "%d/%m/%Y" trxDate
ynabFromDnb :: DNBFormat -> YNABFormat
ynabFromDnb (DNBFormat trxDate explanation _ outFlow inFlow) =
YNABFormat trxDate noPayee noCategory explanation outFlow inFlow where
noPayee = ""
noCategory = ""
|
lstor/traxform
|
src/YNABFormat.hs
|
mit
| 773 | 0 | 9 | 184 | 194 | 106 | 88 | 17 | 1 |
import Data.List (nub)
-- The oddly named *nub* returns the distinct elements of a list
solution =
length $ nub terms
where terms = [a ** b | a <- [2..100],
b <- [2..100]]
main = print solution
|
drcabana/euler-fp
|
source/hs/P29.hs
|
epl-1.0
| 236 | 0 | 8 | 80 | 73 | 39 | 34 | 6 | 1 |
-- Copyright (c) 2011, bkil.hu
-- This program is free software and can be distributed under the terms of
-- the GNU General Public License v2,
-- see COPYING for detailed licensing terms.
-- created on 2010-07-10 19:58
-- http://www.metnet.hu/?m=fc_race&sub=results
-- I wanted to know who is the most dependable forecaster.
import System.IO(hGetContents,stdin)
import Data.Maybe(catMaybes)
import Data.List(maximumBy)
csv2matrix = map (lines . map tab2nl) . lines where
tab2nl '\t' = '\n'
tab2nl x = x
fixMetnet (a:b:xs) = ab : fixMetnet xs where
(a1,a2) = splitAt 12 a
ab = a1 ++ b ++ a2
fixMetnet xs = xs
maybeRead s =
case reads s of
[(x, "")] -> Just x
_ -> Nothing
process f = r where
table = fixMetnet $ csv2matrix f
eachMin = [
let
strs = take 9 t
-- reverse $ drop 2 $ reverse t
nums = map (maybeRead::String->Maybe Float) strs
in (read id::Int,minimum nums) |
(id:name:t) <- table ]
r = maximumBy (\(_,x)(_,y)->compare x y) eachMin
main = do
hGetContents stdin >>= print . process
|
google-code/bkil-open
|
volatile/calc/maxmin.hs
|
gpl-2.0
| 1,034 | 0 | 15 | 215 | 346 | 185 | 161 | 25 | 2 |
{- |
Module : $Header$
Description : ShATermConvertible instances
Copyright : (c) Christian Maeder, Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports programatica modules)
'ShATermConvertible' instances for TiDecorate data types
-}
module Haskell.TiDecorateATC() where
import ATerm.Lib
import TiDecorate
import Haskell.ATC_Haskell()
import Haskell.TiATC()
import Data.Typeable
{-! for TiDecls derive : Typeable !-}
{-! for TiDecl derive : Typeable !-}
{-! for TiExp derive : Typeable !-}
{-! for TiPat derive : Typeable !-}
{-! for TiDecls derive : ShATermConvertible !-}
{-! for TiDecl derive : ShATermConvertible !-}
{-! for TiExp derive : ShATermConvertible !-}
{-! for TiPat derive : ShATermConvertible !-}
|
nevrenato/Hets_Fork
|
Haskell/TiDecorateATC.der.hs
|
gpl-2.0
| 845 | 0 | 4 | 139 | 47 | 33 | 14 | 6 | 0 |
module Main where
import Control.Applicative
import Control.Exception (IOException, catch)
import Control.Monad
import Data.Char (ord)
import Data.Picture
import qualified Data.PNM as PNM
import Prelude hiding (catch)
import System.Environment
import System.IO (hPutStr, stderr)
printPNM :: FilePath -> IO ()
printPNM path = do
putStrLn "Loading pix"
pix <- PNM.load path
print pix
printFile :: FilePath -> IO ()
printFile path = do
content <- catch (readFile path)
(\e -> do let err = show (e :: IOException)
hPutStr stderr ("Warning: Couldn't open " ++ path ++ ": " ++ err)
return "")
putStrLn content
main1 :: IO ()
main1 = do
(path:_) <- getArgs
putStrLn $ "Reading file " ++ path
printFile path
main2 :: IO ()
main2 = do
(path:_) <- lines `liftM` getContents
putStrLn $ "Reading file " ++ path
printFile path
main3 :: IO ()
main3 = do
(path:_) <- lines `liftM` getContents
print $ map ord path
print $ map ord "essai.pnm"
-- | main entry point
main :: IO ()
main = do
{-
args <- getArgs
path <- getPath args
-}
path <- getArgs >>= getPath
printPNM path
where -- getPath = [String] -> IO String
getPath [] = getFirstContents
getPath (s:_) = return s
-- getFirstContents = IO String
getFirstContents = head `liftM` lines `liftM` getContents
|
bfraikin/netpbm
|
src/Main.hs
|
gpl-2.0
| 1,570 | 0 | 17 | 537 | 464 | 239 | 225 | 44 | 2 |
module Main where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Time.Clock
import Data.Time.Format
import qualified Data.ByteString.Char8 as BS -- for strict readFile :(
import Control.Monad
import System.Environment
import System.Directory
import System.Locale (defaultTimeLocale)
import System.FilePath
data Activity = Activity
{ running :: Bool
, start :: UTCTime
, stored :: [(UTCTime, UTCTime)]
} deriving (Show, Read)
type Activities = Map String Activity
readActivities :: IO (Map String Activity)
readActivities = do
home <- getUserDocumentsDirectory
let path = home </> "activities.txt"
e <- doesFileExist path
if e
then do
p <- getPermissions path
when (not (readable p && writable p)) (do
error ("unable to open " ++ path ++ "for reading and writing"))
read `fmap` BS.unpack `fmap` BS.readFile path
else return Map.empty
writeActivities :: Map String Activity -> IO ()
writeActivities m = do
d <- getUserDocumentsDirectory
writeFile (d </> "activities.txt") (show m)
startActivity :: UTCTime -> Activities -> String -> IO Activities
startActivity now as n = do
putStrLn ("starting: " ++ n)
return $
if n `Map.member` as
then
if running (as Map.! n)
then Map.adjust (\a@(Activity _ _ ss) -> Activity True now ((start a, now):ss)) n as
else Map.adjust (\(Activity _ _ ss) -> Activity True now ss) n as
else Map.insert n (Activity True now []) as
stopActivity :: UTCTime -> Activities -> String -> IO Activities
stopActivity now as n =
if n `Map.member` as && running (as Map.! n)
then do
putStrLn ("stopping: " ++ n)
return $ Map.adjust (\a@(Activity _ t ss) -> Activity False t ((start a, now):ss)) n as
else return as
deleteActivity :: Activities -> String -> IO Activities
deleteActivity as n = do
putStrLn ("deleting: " ++ n)
return $ Map.delete n as
showActivity :: UTCTime -> Activities -> String -> IO Activities
showActivity now as n = do
case Map.lookup n as of
Nothing -> putStrLn ("unknown activity: " ++ n)
Just x -> do
when (running x) (do
putStrLn ("\n*** ongoing since " ++
formatTime defaultTimeLocale "%x %T" (start x) ++ " (" ++ show (round (diffUTCTime now (start x))) ++ "s ago)\n"))
let tab1 = "|---+-------------------+-------------------+------------|"
putStrLn tab1
putStrLn "| n | start | end | diff (sec) |"
putStrLn tab1
forM_ (zip [1..] (stored x)) $ \(i,(s,e)) -> do
let duration = show (round (diffUTCTime e s))
formatS = formatTime defaultTimeLocale "%x %T" s
formatE = formatTime defaultTimeLocale "%x %T" e
putStrLn ("| " ++ show i ++ " | " ++ formatS ++ " | " ++ formatE ++ " | " ++ duration ++ replicate (11 - length duration) ' ' ++ "|")
putStrLn tab1
return as
main :: IO ()
main = do
args <- getArgs
when (length args /= 2)
(error "wrong number of arguments")
let (cmd:n:[]) = args
now <- getCurrentTime
as <- readActivities
new <- case cmd of
"start" -> startActivity now as n
"stop" -> stopActivity now as n
"delete" -> deleteActivity as n
"show" -> showActivity now as n
_ -> error "failed to parse arguments"
writeActivities new
|
dvolk/hsactivity
|
src/Main.hs
|
gpl-3.0
| 3,376 | 0 | 27 | 877 | 1,226 | 614 | 612 | 87 | 5 |
--------------------------------------------------------------------------------
-- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). --
-- --
-- diplomarbeit 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. --
-- --
-- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- Copyright 2012, Johannes Weiß --
--------------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
module Main where
-- # STDLIB
import Control.Monad (when)
import Data.List (partition)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import System.Environment (getArgs)
import qualified Data.Map as M
import qualified Data.Text as T
-- # LOCAL
import Data.Helpers (isOptionArg)
import Functionality.AllInOne (evaluateExpr)
import Functionality.Goliath (readExprFromFile)
import qualified Math.Polynomials as P
import StaticConfiguration
_DEBUG_ :: Bool
_DEBUG_ = False
main :: IO ()
main =
do putStrLn "AllInOne START"
rawArgs <- getArgs
let (optionArgs, args) = partition isOptionArg rawArgs
(filePath, inputArg) =
case args of
f:i:[] -> (f, i)
_ -> error $ "Usage: AllInOne [-h|-m|-q] FILE INPUT-EL"
logMsg =
if "-q" `elem` optionArgs
then (\_ -> return ())
else putStrLn
buildPoly <- if "-m" `elem` optionArgs
then do putStrLn "POLY BUILDING: Monomial"
return P.monomial
else putStrLn "POLY BUILDING: Horner" >> return P.horner
let !inputElement = (read inputArg :: Element)
!varMap = M.fromList [(T.pack "x", inputElement)]
expr <- readExprFromFile (buildPoly _X_) filePath
when _DEBUG_ (print expr)
davidStart <- getCurrentTime
out <- evaluateExpr varMap expr logMsg
davidStop <- getCurrentTime
let sToMs :: Double -> Double
sToMs = (1000 *)
calcDiff e a = (truncate . sToMs . realToFrac) (diffUTCTime e a)
diff :: Integer
diff = calcDiff davidStop davidStart
putStrLn $ "David: Exited (running "++show diff++"ms)"
putStrLn $ "David: DAVID DONE, final result = " ++ show out
putStrLn "AllInOne DONE"
|
weissi/diplomarbeit
|
programs/AllInOne.hs
|
gpl-3.0
| 3,357 | 0 | 15 | 1,214 | 525 | 285 | 240 | 47 | 4 |
{-# LANGUAGE InstanceSigs #-}
module MaybeT where
newtype MaybeT m a =
MaybeT { runMaybeT :: m (Maybe a) }
instance (Functor m) => Functor (MaybeT m) where
fmap f (MaybeT mma) = MaybeT $ (fmap.fmap) f mma
instance (Applicative m) => Applicative (MaybeT m) where
pure a = MaybeT $ pure (Just a)
(MaybeT mmfa) <*> (MaybeT mma) =
MaybeT $ (<*>) <$> mmfa <*> mma
instance (Monad m) => Monad (MaybeT m) where
return = pure
(>>=) :: MaybeT m a -> (a -> MaybeT m b) -> MaybeT m b
(MaybeT mma) >>= f = MaybeT $ do
ma <- mma
case ma of
Nothing -> return Nothing
Just a -> runMaybeT (f a)
|
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
|
MonadTransformers/src/MaybeT.hs
|
gpl-3.0
| 662 | 0 | 14 | 200 | 290 | 149 | 141 | 18 | 0 |
{-# LANGUAGE FlexibleContexts, GADTs, TypeOperators, DataKinds, FlexibleInstances, KindSignatures, ScopedTypeVariables #-}
module Main where
import Servant.Swagger.Test
import Test.Hspec
import Modernator.API
import Modernator.WebsocketsAPI
import Test.QuickCheck.Instances()
import Modernator.RequestBodies()
import Modernator.Types()
import Servant.Aeson.GenericSpecs (apiRoundtripSpecs, apiGoldenSpecs)
import Servant.Aeson.Internal (HasGenericSpecs, MkTypeSpecs, collectRoundtripSpecs, mkTypeSpecs)
import Data.Proxy
import Modernator.QuickCheck()
-- This covers types for the Raw Websocket endpoint
instance MkTypeSpecs a => HasGenericSpecs (Websocket a) where
collectRoundtripSpecs settings _ = mkTypeSpecs settings (Proxy :: Proxy a)
spec :: Spec
spec = describe "Swagger" $ do
context "ToJSON matches ToSchema for non-websockets APIs" $ validateEveryToJSON basicAPI
context "ToJSON matches ToSchema for backup websockets API" $ validateEveryToJSON backupAPI
context "ToJSON . FromJSON $ x = x for non-websockets APIs" $ apiRoundtripSpecs basicAPI
context "ToJSON . FromJSON $ x = x for backup websockets API" $ apiRoundtripSpecs backupAPI
context "JSON hasn't changed for non-websockets APIs" $ apiGoldenSpecs basicAPI
context "JSON hasn't changed for backup websockets API" $ apiGoldenSpecs backupAPI
main = hspec spec
|
mojotech/modernator-haskell
|
src/Spec.hs
|
gpl-3.0
| 1,348 | 0 | 9 | 172 | 247 | 129 | 118 | 24 | 1 |
module Main where
import Language.Atom
import Language.Atom.Unit
import GHC.Word
main :: IO ()
main = do
(sched, _, _, _, _) <- compile "atom_example" atomCfg example
putStrLn $ reportSchedule sched
atomCfg :: Config
atomCfg = defaults { cFuncName = "atom_tick"
, cStateName = "state_example"
, cCode = prePostCode
, hCode = prePostHeader
, cRuleCoverage = False
}
prePostCode :: [Name] -> [Name] -> [(Name, Type)] -> (String, String)
prePostCode _ _ _ =
( unlines [ "// ---- This source is automatically generated by Atom ----"
, "#include <stdlib.h>"
, "#include <stdio.h>"
, "#include <unistd.h>"
, ""
, "bool g_sensor_ready;"
, "uint16_t g_sensor_value;"
, "void sensor_on(void);"
, "void sensor_off(void);"
, "void sensor_trigger(void);"
]
, unlines [ "int main(void) {"
, " while (true) {"
, " atom_tick();"
, " usleep(1000);"
, " }"
, " return 0;"
, "}"
, "void sensor_on(void) {"
, " printf(\"%lu: sensor_on()\\n\", __global_clock);"
, "}"
, ""
, "void sensor_off(void) {"
, " printf(\"%lu: sensor_off()\\n\", __global_clock);"
, "}"
, ""
, "void sensor_trigger(void) {"
, " if (rand() % 4) {"
, " g_sensor_value = rand();"
, " g_sensor_ready = true;"
, " printf(\"%lu: Triggered sensor, value=%u\\n\","
, " __global_clock, g_sensor_value);"
, " }"
, "}"
, ""
, "// ---- End automatically-generated source ----"
])
prePostHeader :: [Name] -> [Name] -> [(Name, Type)] -> (String, String)
prePostHeader _ _ _ =
( unlines [ "// ---- This header is automatically generated by Atom ----"
]
, unlines [ "// ---- End automatically-generated header ----"
])
example :: Atom ()
example = do
clock <- tickSecond
checkSensor 40000 $ do
printStrLn "Sensor value over threshold!"
tickSecond :: Atom (V Word64)
tickSecond = do
clock <- word64 "clock_sec" 0
period 1000 $ exactPhase 0 $ atom "second" $ incr clock
return clock
checkSensor :: Word16 -> Atom () -> Atom ()
checkSensor threshold overThresholdAction = atom "check_sensor" $ do
ready <- return $ bool' "g_sensor_ready"
sensorValue <- return $ word16' "g_sensor_value"
warmup <- timer "warmup"
triggered <- bool "triggered" False
sensorOn <- bool "sensor_on" False
period 2000 $ phase 500 $ atom "powerOn" $ do
call "sensor_on"
triggered <== false
ready <== false
sensorOn <== true
startTimer warmup $ Const 10
atom "trigger" $ do
cond $ timerDone warmup &&. not_ (value triggered) &&. value sensorOn
triggered <== true
call "sensor_trigger"
atom "checkSensorValue" $ do
cond $ value ready
ready <== false
sensorOn <== false
call "sensor_off"
atom "checkThreshold" $ do
cond $ value sensorValue >. Const threshold
overThresholdAction
period 2000 $ phase 550 $ atom "powerOff" $ do
cond $ value sensorOn
ready <== false
printStrLn "Sensor timeout."
call "sensor_off"
|
UBMLtonGroup/survey_sonar
|
Sensor/sensor.hs
|
gpl-3.0
| 3,483 | 0 | 16 | 1,198 | 795 | 399 | 396 | 95 | 1 |
import Test.QuickCheck
import Control.Monad
import Data.Maybe(fromJust)
import Data.Word
import Dep.Algorithms()
import Dep.Algorithms.Sim(emptyCircuit,Circuit,wires,CircuitBuilder,resultingCircuit,addWire,addWires,addNamedWire,Wire(..),makeNandGate,makeNotGate,makeAndGate,sensList,validName,makeClock0,generateDefaultState,renameWire,getWireNames,getWireName)
import qualified Data.Sequence as Sq
import Debug.Trace
arbitraryIncrease :: Num a => [a] -> [a]
arbitraryIncrease = scanl1 (\x -> (x +) . abs)
prop_check_name :: String -> Bool
prop_check_name s = not (validName s) || length s <= 4
_prop_ct_wrs :: Int -> CircuitBuilder ()
_prop_ct_wrs n = do
emptyCircuit
replicateM_ n (addWire False)
prop_ct_wrs :: Int -> Bool
prop_ct_wrs n = n0 == Sq.length (wires $ resultingCircuit $ _prop_ct_wrs n)
where n0 = max 0 n
_prop_nm_wrs :: Int -> Int -> String -> CircuitBuilder ()
_prop_nm_wrs n k nm = do
emptyCircuit
replicateM_ k (addWire False)
addNamedWire nm False
replicateM_ (n-k) (addWire False)
prop_nm_wrs :: Int -> Int -> String -> Bool
prop_nm_wrs m n nm = not (validName nm) || Just nm == wName (Sq.index rs i) && l+1 == Sq.length rs
where am = abs m
an = abs n
l = 1+max am an
i = min am an
rs = wires $ resultingCircuit $ _prop_nm_wrs l i nm
_circ_not_cyc :: CircuitBuilder Wire
_circ_not_cyc = do
emptyCircuit
w0 <- addWire False
Nothing <- getWireName w0
[] <- getWireNames
renameWire w0 "Nt"
Just "Nt" <- getWireName w0
["Nt"] <- getWireNames
makeNotGate w0 w0
_circ_clock_cyc :: CircuitBuilder ()
_circ_clock_cyc = do
emptyCircuit
w1 <- addWire False
w0 <- addWire True
renameWire w0 "Nt"
renameWire w1 "Clk"
makeNotGate w0 w0
makeClock0 5 w1
return ()
prop_agt0_wrs :: Bool
prop_agt0_wrs = 1 == Sq.length sq &&
[0] == sensList (Sq.index sq 0)
where rc = resultingCircuit _circ_not_cyc
sq = wires rc
_circ_latch_clk_wrs :: CircuitBuilder Wire
_circ_latch_clk_wrs = do
emptyCircuit
[w0,w1,w2,w3,w4] <- addWires [True,True,True,False,False]
makeNandGate [w1,w3] w2
makeNandGate [w0,w2] w3
makeClock0 20 w4
prop_agt1_wrs :: Bool
prop_agt1_wrs = 5 == Sq.length sq &&
[] == sensList (Sq.index sq 0) &&
[] == sensList (Sq.index sq 1) &&
[1,3] == sensList (Sq.index sq 2) &&
[4] == sensList (Sq.index sq 4)
where rc = resultingCircuit _circ_latch_clk_wrs
sq = wires rc
_circ_ff :: CircuitBuilder Wire
_circ_ff = do
emptyCircuit
c <- addNamedWire "Clk" False
d <- addNamedWire "D" False
a <- addNamedWire "A" False
s <- addNamedWire "S*" False
r <- addNamedWire "R*" False
b <- addNamedWire "B" False
qn <- addNamedWire "Q*" False
q <- addNamedWire "Q" False
makeNandGate [b,s] a
makeNandGate [a,c] s
makeNandGate [b,c,s] r
makeNandGate [d,r] b
makeNandGate [s,q] qn
makeNandGate [r,qn] q
prop_circ_ff :: Bool
prop_circ_ff = 8 == Sq.length sq
where rc = resultingCircuit _circ_ff
sq = wires rc
main = do
quickCheck prop_check_name
quickCheck prop_ct_wrs
quickCheck prop_nm_wrs
quickCheck prop_agt0_wrs
quickCheck prop_agt1_wrs
quickCheck prop_circ_ff
|
KommuSoft/dep-software
|
Test.Dep.Algorithms.Sim.hs
|
gpl-3.0
| 3,343 | 7 | 15 | 813 | 1,244 | 610 | 634 | 100 | 1 |
{- Copyright (c) 2014-2015, 2017 Chan Beom Park <[email protected]>
This file is part of hs-mt2calculator, which is released under the GNU
General Public License. See file LICENSE in the top directory of this
project or go to <http://www.gnu.org/licenses/> for full license details.
-}
module Main where
import HEP.Kinematics.Variable.MT2
import HEP.Kinematics.Vector.LorentzVector (setXYZT)
import HEP.Kinematics.Vector.TwoVector (setXY)
main :: IO ()
main = do
let visA = setXYZT 410.0 20.0 0.0 422.493
visB = setXYZT (-210.0) (-300.0) 0.0 395.727
ptmiss = setXY (-200.0) 280.0
mInvisible = 100.0
print $ mT2SymmMinuit2 visA visB ptmiss mInvisible
print $ mT2SymmChengHanBisect visA visB ptmiss mInvisible
print $ mT2SymmLesterBisect visA visB ptmiss mInvisible
print $ mT2AsymmLesterBisect visA visB ptmiss mInvisible mInvisible
|
cbpark/hs-mt2calculator
|
test/test_mt2.hs
|
gpl-3.0
| 894 | 0 | 12 | 176 | 179 | 94 | 85 | 14 | 1 |
import qualified Database.QUDB as QUDB
import System.Environment
import System.Directory
import System.IO
import Data.Maybe (isJust)
import Control.Monad (when)
import qualified Control.Exception as E
import qualified Data.ByteString.Char8 as C (hGetContents, writeFile)
main :: IO ()
main = do
args <- getArgs
if length args > 1
then usage
else do
let filename = if null args then Nothing else Just (head args)
db <- prepareDB filename
terminal <- hIsTerminalDevice stdin -- Not portable: GHC/Hugs only!
db' <- if terminal
then repl db
else noninteractive db
when (isJust filename && db /= db') $
let (Just name) = filename in C.writeFile name $ QUDB.dump db'
usage :: IO ()
usage = do
name <- getProgName
putStrLn $ "Usage: " ++ name ++ " [filename]"
prepareDB :: Maybe FilePath -> IO QUDB.DB
prepareDB Nothing = return QUDB.new
prepareDB (Just file) = do
gotFile <- doesFileExist file
if gotFile
then do
handle <- openFile file ReadMode
dump <- C.hGetContents handle
hClose handle
return $ QUDB.load dump
else return QUDB.new
repl :: QUDB.DB -> IO QUDB.DB
repl db = do
putStr "> "
hFlush stdout
eof <- isEOF
if eof
then return db
else do
line <- getLine
db' <- if null line
then return db
else (case QUDB.query db line of
Right (db', res) -> printResults res >> return db'
Left msg -> putStrLn msg >> return db
) `E.catch` handler db
repl db'
where handler :: QUDB.DB -> E.SomeException -> IO QUDB.DB
handler db e = print e >> return db
noninteractive :: QUDB.DB -> IO QUDB.DB
noninteractive db = do
eof <- isEOF
if eof
then return db
else do
line <- getLine
db' <- if null line
then return db
else case QUDB.query db line of
Right (db', res) -> printResults res >> return db'
Left msg -> putStrLn msg >> return db
noninteractive db'
printResults :: [[QUDB.Value]] -> IO ()
printResults = mapM_ (putStrLn . columnify)
where columnify [] = ""
columnify [x] = showValue x
columnify (x:xs) = showValue x ++ "|" ++ columnify xs
showValue (QUDB.IntValue x) = show x
showValue (QUDB.StringValue x) = x
|
jstepien/qudb
|
qudb/qudb.hs
|
lgpl-3.0
| 2,403 | 7 | 18 | 750 | 848 | 412 | 436 | 75 | 4 |
module Main where
import Data
import Evaluator
import PrettyPrinter
import FromTree
import ToTree
main = do
let e1 = Lit 2
let e2 = Lit 3
let e3 = Add e1 e2
let e4 = fromTree $ toTree e3
prettyPrint e4;
putStr "\n";
prettyPrint e3;
putStr " = ";
putStr $ show $ evaluate e3;
putStr "\n";
|
egaburov/funstuff
|
Haskell/tytag/xproblem_src/samples/expressions/Haskell/ClosedDatatype/Main.hs
|
apache-2.0
| 390 | 0 | 11 | 159 | 128 | 61 | 67 | 17 | 1 |
module Database.Neo4j.Internal.PGM (
Id(..),
Label(..),
RelationshipType(..),
Properties,
Node(..),
Relationship(..),
Entity(..),
Direction(..),
Segment(..),
segmentRelationship,
Step,
(<-|),
(|--),
(--|),
(|->),
Path,
singleNodePath,
(<@>),
(<+>),
pathLength,
pathNodes,
pathRelationships,
pathSegment,
pathSegments,
(<++>),
Directed(..),
Invertible(..)
)
where
import qualified Database.Neo4j.Internal.Util.IndexedMap as IM
import Database.Neo4j.Internal.ValueCodec
import Database.Neo4j.Internal.Packstream.Atomic
import Database.Neo4j.Internal.Packstream.Atom
import Database.Neo4j.Internal.Packstream.Signature
import Data.Int
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Vector as V
newtype Id = Id { getId :: Int64 } deriving (Eq, Show, Ord)
instance Atomic Id where
atomize = AInt64 . getId
construct x = Id <$> construct x
instance ValueCodec Id where
type Properties v = Map v
newtype Label = Label { labelName :: T.Text } deriving (Eq, Show, Ord)
instance Atomic Label where
atomize = AText . labelName
construct (AText txt) = Just $ Label txt
construct _ = Nothing
newtype RelationshipType = RelationshipType { relationshipTypeName :: T.Text } deriving (Eq, Show, Ord)
instance Atomic RelationshipType where
atomize = AText . relationshipTypeName
construct (AText txt) = Just $ RelationshipType txt
construct _ = Nothing
data Node v = Node {
nodeId :: Id,
-- TODO
nodeLabels :: V.Vector T.Text,
nodeProperties :: Properties v
}
deriving instance Eq v => Eq (Node v)
deriving instance Ord v => Ord (Node v)
deriving instance Show v => Show (Node v)
instance (Atomic v) => Atomic (Node v) where
atomize n = AStructure _NODE $ V.cons (atomize $ nodeId n)
$ V.cons (atomize $ nodeLabels n)
$ V.singleton (atomize $ nodeProperties n)
construct (AStructure sig args) | sig == _NODE && V.length args == 3 =
do
nId <- args V.!? 0 >>= construct
nLabels <- args V.!? 1 >>= construct
nProperties <- args V.!? 2 >>= construct
return Node { nodeId = nId, nodeLabels = nLabels, nodeProperties = nProperties }
construct _ = Nothing
instance ValueCodec v => ValueCodec (Node v) where
data Relationship v = Relationship {
relationshipId :: Id,
relationshipType :: RelationshipType,
relationshipStartNodeId :: Id,
relationshipEndNodeId :: Id,
relationshipProperties :: Properties v
}
deriving instance Eq v => Eq (Relationship v)
deriving instance Ord v => Ord (Relationship v)
deriving instance Show v => Show (Relationship v)
instance Atomic v => Atomic (Relationship v) where
atomize rel = AStructure _RELATIONSHIP $ V.cons (atomize $ relationshipId rel)
$ V.cons (atomize $ relationshipStartNodeId rel)
$ V.cons (atomize $ relationshipEndNodeId rel)
$ V.cons (atomize $ relationshipTypeName $ relationshipType rel)
$ V.singleton (atomize $ relationshipProperties rel)
construct (AStructure sig args) | sig == _RELATIONSHIP && V.length args == 5 =
do
relId <- args V.!? 0 >>= construct
relStartNodeId <- args V.!? 1 >>= construct
relEndNodeId <- args V.!? 2 >>= construct
relTypeName <- args V.!? 3 >>= construct
relProperties <- args V.!? 4 >>= construct
return Relationship {
relationshipId = relId,
relationshipStartNodeId = relStartNodeId,
relationshipEndNodeId = relEndNodeId,
relationshipType = RelationshipType relTypeName,
relationshipProperties = relProperties
}
construct _ = Nothing
instance ValueCodec v => ValueCodec (Relationship v) where
class Entity a where
type PropertyValue a
entityId :: a -> Id
entityProperties :: a -> Properties (PropertyValue a)
instance Entity (Node v) where
type PropertyValue (Node v) = v
entityId = nodeId
entityProperties = nodeProperties
instance Entity (Relationship v) where
type PropertyValue (Relationship v) = v
entityId = relationshipId
entityProperties = relationshipProperties
data Direction = INCOMING | OUTGOING deriving (Eq, Show, Ord)
class Invertible a where
inverse :: a -> a
instance Invertible a => Invertible (Maybe a) where
inverse = fmap inverse
instance Invertible Direction where
inverse INCOMING = OUTGOING
inverse OUTGOING = INCOMING
data UnboundRelationship v = UnboundRelationship {
unboundRelationshipId :: Id,
unboundRelationshipType :: RelationshipType,
unboundRelationshipProperties :: Properties v
} deriving (Eq, Show, Ord)
unboundRelationship :: Relationship v -> UnboundRelationship v
unboundRelationship rel = UnboundRelationship {
unboundRelationshipId = relationshipId rel,
unboundRelationshipType = relationshipType rel,
unboundRelationshipProperties = relationshipProperties rel
}
instance Atomic v => Atomic (UnboundRelationship v) where
atomize UnboundRelationship {
unboundRelationshipId = relId,
unboundRelationshipType = relType,
unboundRelationshipProperties = relProps
} = AStructure _UNBOUND_RELATIONSHIP
$ V.cons (atomize relId)
$ V.cons (atomize relType)
$ V.singleton (atomize relProps)
construct (AStructure sig elts) | sig == _UNBOUND_RELATIONSHIP && V.length elts == 3 = do
relId <- construct $ elts V.! 0
relType <- construct $ elts V.! 1
relProps <- construct $ elts V.! 2
return UnboundRelationship {
unboundRelationshipId = relId,
unboundRelationshipType = relType,
unboundRelationshipProperties = relProps
}
construct _ = Nothing
data Step v = MkStep {
stepNode :: Node v,
stepUnboundRelationship :: UnboundRelationship v,
stepDirection :: Direction,
stepOtherNodeId :: Id
}
(--|) :: (Eq v) => Node v -> Relationship v -> Maybe (Step v)
(--|) startNode rel =
if nodeId startNode == relationshipStartNodeId rel
then Just MkStep {
stepNode = startNode,
stepUnboundRelationship = unboundRelationship rel,
stepDirection = OUTGOING,
stepOtherNodeId = relationshipEndNodeId rel
}
else Nothing
(|->) :: (Eq v) => Maybe (Step v) -> Node v -> Maybe (Segment v)
(|->) (Just step) endNode | stepDirection step == OUTGOING =
if stepOtherNodeId step == nodeId endNode
then Just Segment {
segmentDirection = if nodeId startNode == nodeId endNode then Nothing else Just OUTGOING,
segmentUnboundRelationship = stepUnboundRelationship step,
segmentStartNode = startNode,
segmentEndNode = endNode
}
else Nothing
where
startNode = stepNode step
(|->) _ _ = Nothing
(<-|) :: (Eq v) => Node v -> Relationship v -> Maybe (Step v)
(<-|) endNode rel =
if nodeId endNode == relationshipEndNodeId rel
then Just MkStep {
stepNode = endNode,
stepUnboundRelationship = unboundRelationship rel,
stepDirection = INCOMING,
stepOtherNodeId = relationshipStartNodeId rel
}
else Nothing
(|--) :: (Eq v) => Maybe (Step v) -> Node v -> Maybe (Segment v)
(|--) (Just step) startNode | stepDirection step == INCOMING =
if stepOtherNodeId step == nodeId startNode
then Just Segment {
segmentDirection = if nodeId startNode == nodeId endNode then Nothing else Just INCOMING,
segmentUnboundRelationship = stepUnboundRelationship step,
segmentStartNode = startNode,
segmentEndNode = endNode
}
else Nothing
where
endNode = stepNode step
(|--) _ _ = Nothing
data Segment v = Segment {
segmentDirection :: Maybe Direction,
segmentUnboundRelationship :: UnboundRelationship v,
segmentStartNode :: Node v,
segmentEndNode :: Node v
}
deriving instance Eq v => Eq (Segment v)
deriving instance Ord v => Ord (Segment v)
deriving instance Show v => Show (Segment v)
instance Invertible (Segment v) where
inverse segment = segment {
segmentStartNode = segmentEndNode segment,
segmentEndNode = segmentStartNode segment,
segmentDirection = inverse $ segmentDirection segment
}
segmentRelationship :: Segment v -> Relationship v
segmentRelationship segment =
if segmentDirection segment == Just INCOMING
then Relationship {
relationshipStartNodeId = nodeId $ segmentEndNode segment,
relationshipEndNodeId = nodeId $ segmentStartNode segment,
relationshipId = unboundRelationshipId rel,
relationshipType = unboundRelationshipType rel,
relationshipProperties = unboundRelationshipProperties rel
}
else Relationship {
relationshipStartNodeId = nodeId $ segmentStartNode segment,
relationshipEndNodeId = nodeId $ segmentEndNode segment,
relationshipId = unboundRelationshipId rel,
relationshipType = unboundRelationshipType rel,
relationshipProperties = unboundRelationshipProperties rel
}
where
rel = segmentUnboundRelationship segment
data Path v = MkPath {
pathNodesMap :: IM.IndexedMap Id (Node v),
pathRelationshipsMap :: IM.IndexedMap Id (UnboundRelationship v),
pathElements :: V.Vector Int
}
deriving instance Eq v => Eq (Path v)
deriving instance Ord v => Ord (Path v)
deriving instance Show v => Show (Path v)
instance Atomic v => Atomic (Path v) where
atomize MkPath {
pathNodesMap = nodesMap,
pathRelationshipsMap = relsMap,
pathElements = elts
} = AStructure _PATH
$ V.cons (atomize $ IM.values nodesMap)
$ V.cons (AVector $ V.map atomize $ IM.values relsMap)
$ V.singleton (atomize elts)
construct (AStructure sig args) | sig == _PATH && V.length args == 3 = do
nodes <- construct $ args V.! 0 :: Maybe (V.Vector (Node v))
unboundRels <- construct $ args V.! 1 :: Maybe (V.Vector (UnboundRelationship v))
elts <- construct $ args V.! 2 :: Maybe (V.Vector Int)
-- TODO Consistency check
return MkPath {
pathNodesMap = IM.extract nodeId nodes,
pathRelationshipsMap = IM.extract unboundRelationshipId unboundRels,
pathElements = elts
}
construct _ = Nothing
instance ValueCodec v => ValueCodec (Path v) where
singleNodePath :: Node v -> Path v
singleNodePath startNode = MkPath {
pathNodesMap = IM.singleton (nodeId startNode) startNode,
pathRelationshipsMap = IM.empty,
pathElements = V.empty
}
(<@>) :: Node v -> Maybe (Path v)
(<@>) = Just . singleNodePath
(<+>) :: (Eq v) => Maybe (Path v) -> Maybe (Segment v) -> Maybe (Path v)
(<+>) (Just path) (Just segment) =
if end path == startNode
then do
newPathNodesMap <- IM.insert startNodeId startNode (pathNodesMap path) >>= IM.insert endNodeId endNode
newPathRelsMap <- IM.insert relId unboundRel $ pathRelationshipsMap path
relIndex <- IM.index relId newPathRelsMap
endNodeIndex <- IM.index endNodeId newPathNodesMap
return $
let relElt = if segmentDirection segment == Just INCOMING then - relIndex else relIndex
in MkPath {
pathNodesMap = newPathNodesMap,
pathRelationshipsMap = newPathRelsMap,
pathElements = V.snoc (V.snoc (pathElements path) relElt) endNodeIndex
}
else Nothing
where
startNodeId = nodeId startNode
startNode = start segment
endNodeId = nodeId endNode
endNode = end segment
unboundRel = segmentUnboundRelationship segment
relId = unboundRelationshipId unboundRel
(<+>) _ _ = Nothing
pathLength :: Path v -> Int
pathLength path = div (V.length $ pathElements path) 2
pathNodes :: Path v -> V.Vector (Node v)
pathNodes path = V.map nodeAtIndex $ V.ifilter nodeIndices $ pathElements path
where
nodeAtIndex idx = pathNodesMap path IM.! idx
nodeIndices idx _ = mod idx 2 == 1
pathRelationships :: (Eq v) => Path v -> V.Vector (Relationship v)
pathRelationships path = V.fromList $ map (segmentRelationship . fromJust) $ pathSegments_ path
pathSegment :: (Eq v) => Int -> Path v -> Maybe (Segment v)
pathSegment segmentId path =
if i >= len
then Nothing
else Just Segment {
segmentDirection =
if startNodeId == endNodeId then Nothing
else Just (if segmentId >= 0 then OUTGOING else INCOMING),
segmentStartNode = startNode,
segmentEndNode = endNode,
segmentUnboundRelationship = rel
}
where
i = abs segmentId
len = pathLength path
idx = i * 2
elts = pathElements path
nodes = pathNodesMap path
startNode = nodes IM.! (if i == 0 then 0 else elts V.! (idx - 1))
startNodeId = nodeId startNode
endNode = nodes IM.! (elts V.! (idx + 1))
endNodeId = nodeId endNode
rels = pathRelationshipsMap path
rel = rels IM.! (elts V.! idx)
pathSegments :: (Eq v) => Path v -> [Segment v]
pathSegments path = map fromJust $ pathSegments_ path
pathSegments_ :: (Eq v) => Path v -> [Maybe (Segment v)]
pathSegments_ path =
if lst == 0
then []
else map segment [0..(lst - 1)]
where
lst = pathLength path
segment i = pathSegment i path
(<++>) :: (Eq v) => Maybe (Path v) -> Maybe (Path v) -> Maybe (Path v)
(<++>) Nothing Nothing = Nothing
(<++>) optPath Nothing = optPath
(<++>) Nothing optPath = optPath
(<++>) optPath (Just path) = foldl (<+>) optPath $ pathSegments_ path
instance (Eq v) => Monoid (Maybe (Path v)) where
mempty = Nothing
mappend = (<++>)
class Directed a where
type Anchor a
start :: a -> Anchor a
end :: a -> Anchor a
instance Directed (Relationship v) where
type Anchor (Relationship v) = Id
start = relationshipStartNodeId
end = relationshipEndNodeId
instance Directed (Segment v) where
type Anchor (Segment v) = Node v
start = segmentStartNode
end = segmentEndNode
instance Directed (Path v) where
type Anchor (Path v) = Node v
start path = pathNodesMap path IM.! 0
end path = pathNodesMap path IM.! (if V.null elts then 0 else V.last elts)
where elts = pathElements path
-- TODO instance invertible Path
|
boggle/neo4j-haskell-driver
|
src/Database/Neo4j/Internal/PGM.hs
|
apache-2.0
| 14,124 | 0 | 17 | 3,317 | 4,495 | 2,361 | 2,134 | -1 | -1 |
import Data.Char
main = do
c <- getContents
let i' = map (map digitToInt) $ lines c
i = takeWhile (/= [0]) i'
o = map sum i
mapM_ print o
|
a143753/AOJ
|
ITP1_8_B.hs
|
apache-2.0
| 159 | 0 | 13 | 52 | 78 | 38 | 40 | 7 | 1 |
module Main where
import qualified LMemLoopbackService_Client as Client
import LMemLoopback_Types
import Thrift
import Thrift.Protocol.Binary
import Thrift.Server
import Thrift.Transport
import Thrift.Transport.Handle
import Control.Exception
import Data.Either
import Data.Int
import Data.List
import Data.Maybe
import Data.Time
import Data.Text.Lazy
import Data.Vector
import Network
import System.Exit
import System.Random
import Text.Printf
getRight :: Either left right -> right
getRight (Right x) = x
lMemLoopbackCPU :: [Int32] -> [Int32] -> [Int32]
lMemLoopbackCPU [] [] = []
lMemLoopbackCPU (a:inA) (b:inB) = (a + b) : (lMemLoopbackCPU (inA) (inB) )
check :: [Int32] -> [Int32] -> Int -> Int -> [Int]
check [] [] start end = []
check (x:outDFE) (y:outCPU) start end
| (x == y) = check outDFE outCPU (start+1) end
| otherwise = (start) : check outDFE outCPU (start+1) end
printErrors :: [Int] -> [Int32] -> [Int32] -> String -> String
printErrors [] xs ys output = output
printErrors (i:is) xs ys output = printErrors is xs ys (output Data.List.++ "Output data @ " Data.List.++ (show i) Data.List.++ " = " Data.List.++ (show (xs!!i)) Data.List.++ " (expected " Data.List.++ (show (ys!!i)) Data.List.++ ")\n")
main = do
startTime <- getCurrentTime
startDFETime <- getCurrentTime
-- Make socket
transport <- hOpen ("localhost", PortNumber 9090)
-- Wrap in a protocol
let protocol = BinaryProtocol transport
-- Create a client to use the protocol encoder
let client = (protocol, protocol)
stopTime <- getCurrentTime
putStrLn ("Creating a client and opening connection:\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Generate input data
startTime <- getCurrentTime
let size = 384
let sizeBytes = size * 4
let inA = [0 .. (size-1)]
let inB = [size - a | a <- inA]
stopTime <- getCurrentTime
putStrLn ("Generating input data:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Initialize maxfile
startTime <- getCurrentTime
e <- try (Client.lMemLoopback_init client) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let maxfile = getRight e
stopTime <- getCurrentTime
putStrLn ("Initializing maxfile:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Load DFE
startTime <- getCurrentTime
e <- try (Client.max_load client maxfile (pack "*")) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let engine = getRight e
stopTime <- getCurrentTime
putStrLn ("Loading DFE:\t\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Allocate and send input streams to server
startTime <- getCurrentTime
e <- try (Client.malloc_int32_t client (fromIntegral size)) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let address_inA = getRight e
e <- try (Client.send_data_int32_t client address_inA (fromList inA)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.malloc_int32_t client (fromIntegral size)) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let address_inB = getRight e
e <- try (Client.send_data_int32_t client address_inB (fromList inB)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("Sending input data:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Allocate memory for output stream on server
startTime <- getCurrentTime
e <- try (Client.malloc_int32_t client (fromIntegral size)) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let address_dataOut = getRight e
stopTime <- getCurrentTime
putStrLn ("Allocating memory for output stream on server:\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Writing to LMem
startTime <- getCurrentTime
e <- try (Client.max_actions_init client maxfile (pack "writeLMem")) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let actionsA = getRight e
e <- try (Client.max_set_param_uint64t client actionsA (pack "address") (fromIntegral 0)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_set_param_uint64t client actionsA (pack "nbytes") (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_queue_input client actionsA (pack "cpu_to_lmem") address_inA (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_run client engine actionsA) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_actions_init client maxfile (pack "writeLMem")) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let actionsB = getRight e
e <- try (Client.max_set_param_uint64t client actionsB (pack "address") (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_set_param_uint64t client actionsB (pack "nbytes") (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_queue_input client actionsB (pack "cpu_to_lmem") address_inB (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_run client engine actionsB) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("Writing to LMem:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Action default
startTime <- getCurrentTime
e <- try (Client.max_actions_init client maxfile (pack "default")) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let actions = getRight e
e <- try (Client.max_set_param_uint64t client actions (pack "N") (fromIntegral size)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_run client engine actions) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("LMemLoopback time:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Reading from LMem
startTime <- getCurrentTime
e <- try (Client.max_actions_init client maxfile (pack "readLMem")) :: IO (Either SomeException Int64)
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
let actionsRead = getRight e
e <- try (Client.max_set_param_uint64t client actionsRead (pack "address") (fromIntegral (2 * sizeBytes))) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_set_param_uint64t client actionsRead (pack "nbytes") (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_queue_output client actionsRead (pack "lmem_to_cpu") address_dataOut (fromIntegral sizeBytes)) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.max_run client engine actionsRead) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("Reading from LMem:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Unload DFE
startTime <- getCurrentTime
e <- try (Client.max_unload client engine) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("Unloading DFE:\t\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Get output stream from server
startTime <- getCurrentTime
dataOutDFE <- Client.receive_data_int32_t client address_dataOut (fromIntegral size)
stopTime <- getCurrentTime
putStrLn ("Getting output stream:\t(size = " Data.List.++ (show (size * 32)) Data.List.++ " bit)\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Free allocated memory for streams on server
startTime <- getCurrentTime
e <- try (Client.free client address_inA) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.free client address_inB) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
e <- try (Client.free client address_dataOut) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
stopTime <- getCurrentTime
putStrLn ("Freeing allocated memory for streams on server:\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Free allocated maxfile data
startTime <- getCurrentTime
e <- try (Client.lMemLoopback_free client) :: IO (Either SomeException ())
case e of
Left ex -> putStrLn $ "Caught exception: " Data.List.++ show ex
Right ex -> return ()
-- Close!
startTime <- getCurrentTime
tClose transport
stopTime <- getCurrentTime
putStrLn ("Closing connection:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
stopTime <- getCurrentTime
putStrLn ("DFE LMemLoopback total time:\t\t\t" Data.List.++ (show (diffUTCTime stopTime startDFETime)))
-- CPU Output
startTime <- getCurrentTime
let dataOutCPU = lMemLoopbackCPU inA inB
stopTime <- getCurrentTime
putStrLn ("CPU LMemLoopback total time::\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
-- Checking results
startTime <- getCurrentTime
let errors = check (toList dataOutDFE) dataOutCPU 0 (fromIntegral size)
stopTime <- getCurrentTime
putStrLn ("Checking results:\t\t\t\t" Data.List.++ (show (diffUTCTime stopTime startTime)))
if ((Data.List.length errors)== 0)
then putStrLn ("Test successful!")
else do putStr (printErrors errors (toList dataOutDFE) dataOutCPU [])
putStrLn ("Test failed " Data.List.++ show (Data.List.length errors) Data.List.++ " times!")
exitWith $ ExitFailure (-1)
|
maxeler/maxskins
|
examples/LMemLoopback/client/hs/Dynamic/LMemLoopbackClient.hs
|
bsd-2-clause
| 12,377 | 6 | 17 | 2,859 | 4,314 | 2,076 | 2,238 | 228 | 32 |
module DivisionIntegralFixed where
data QuotRem a = Result a | DivisionByZero deriving (Show)
fromResult :: QuotRem a -> a
fromResult (Result a) = a
div' :: (Integral a) => a -> a -> QuotRem (a, a)
div' n 0 = DivisionByZero
div' n d = div'' n d 0
where div'' n' d' count
| abs(n') < abs(d') = Result ((s n) * (s d) * count, (s n) * (s d) * n')
| otherwise = Result $ fromResult $ div'' (abs(n') - abs(d')) (abs(d')) (count + 1)
s y =
case y < 0 of
True -> (-1)
False -> 1
|
OCExercise/haskellbook-solutions
|
chapters/chapter08/exercises/division-integral-fixed.hs
|
bsd-2-clause
| 545 | 0 | 13 | 176 | 285 | 147 | 138 | 14 | 2 |
module Obsidian.GCDObsidian.CodeGen.SyncAnalysis (syncAnalysis) where
import Obsidian.GCDObsidian.Kernel
import Obsidian.GCDObsidian.Program
import Obsidian.GCDObsidian.Exp
import Obsidian.GCDObsidian.Globs
import Data.Word
import Data.List
import qualified Data.Map as Map
{-
SyncAnalysis.
Try to decide automatically whether a Sync is needed or not.
*** This will make sence in the CUDA case. For OpenCL generation
use the programmer-placed syncs. (This is why the Synchronize
constructor in the Program datatype now has a boolean parameter.
The method I use to decide if a Sync is needed or not is:
When Array 'arr' is computed, if a thread, t1, that computes
an element uses any element owned by* a thread, t2, such
that (t1 `div` WarpSize /= t2 `div` WarpSize) that has not
yet been synced.
If so, a sync is needed before t1 performs the computation.
*Owned by means having been computed by.
To implement the above method I use two maps and a single pass
over the Program datastructure.
SAMap contains at anytime all the arrays that have not yet been synced
it maps array-names to a TEMap
TEMap is a Index to ThreadId that for every index remembers what
thread computed it.
So when computing location tid in an array, every array and index
that that location depends on is found. The array-names are used
to make lookups into SAMap followed by looking up the in the TEMap
using the index. If the thread obtained is in another warp a sync
is inserted and the SAMap cleared.
The array currently being computed is added to the SAMap and no
sync is inserted following its computation.
Future:
* Once we start to write data-dependent assignment locations (like filters)
The implementation needs an update to work.
One way to take care of this might be to simply say that if the index
cannot be evaluated here it is data-dependent and a sync should be used.
(see eval and evalSource, local functions in analyseForAll)
* The implementation does not understand nested ForAll loops.
If we ever use nested ForAlls this needs to change.
ERROR!!!
My assumptions about when it was safe not to sync are faulty!
This needs more thought!
-}
-- TEMap is an Index->Thread map
-- TODO: Replace with an Array. If that is more efficient.
type TEMap = Map.Map Word32 Word32
-- SAMap is a name->TEMap map
type SAMap = Map.Map Name TEMap
-- TODO: Right now warps are 32 threads.
-- This might change in the future.
warpSize = 32
--syncAnalysis :: Program a -> Program a
--syncAnalysis prg = prg
{-
input program should have unique names for all intermediate arrays
-}
syncAnalysis :: Program a -> Program a
syncAnalysis prg = prg
{-
syncAnalysis :: Program a -> Program a
syncAnalysis prg = snd$ syncAnalysis' prg Map.empty
where
syncAnalysis' :: Program a -> SAMap -> (SAMap,Program a)
syncAnalysis' Skip sam = (sam,Skip)
syncAnalysis' (Synchronize b) sam = (sam,Synchronize False)
syncAnalysis' f@(ForAll _ _) sam = analyseForAll f sam
syncAnalysis' a@(Allocate nom n t e) sam = (sam,a)
syncAnalysis' (ProgramSeq prg1 prg2) sam =
let (sam1,prg1') = syncAnalysis' prg1 sam
(sam2,prg2') = syncAnalysis' prg2 sam1
in (sam2,prg1' `ProgramSeq` prg2')
-- The below case should just take place within a ForAll case.
syncAnalysis' (Assign nom ix a) sam = error "should not happen"
analyseForAll (ForAll g n) sam = (sam'',if sNeeded
then Synchronize True *>* ForAll g n
else ForAll g n )
-- error$ show arrloc -- (sam',prg)
where
threads = [0..(n-1)]
gPrgs = [(g (fromIntegral tid),tid) | tid <- threads]
arrloc'' = concatMap getSourceIndices gPrgs
arrloc' = filter pred arrloc''
arrloc = map evalSource arrloc'
targetMaps = map getTargIndex gPrgs -- (zip gPrgs threads)
(sam',sNeeded) = conflict arrloc sam
sam'' = addMappings targetMaps sam'
eval (Literal a) = a
evalSource (n,(a,ix)) = (n,(a,eval ix))
pred (_,(x,_)) = not ("input" `isPrefixOf` x)
-}
-- TODO: look at the special case below. (Make more beautiful)
getSourceIndices :: (Program a,Word32) -> [(Word32,(Name,Exp Word32))]
getSourceIndices (Assign nom (Literal ix) a,tid) = map (\y -> (tid,y)) (collectArrayIndexPairs a)
-- Special case!
getSourceIndices (Assign nom ix _,tid) =
if isPrefixOf "result" nom ||
isPrefixOf "input" nom then []
else error$ "getSourceIndices: " ++ show ix ++ " is not Literal"
getSourceIndices _ = error "getSourceIndices: Can only handle a very simple case so far"
-- What array are we computing now,
-- create the threadId -> Ix map for that array
getTargIndex ((Assign nom (Literal ix) a),tid) = (nom,(ix,tid))--(nom,(ix,tid))
-- What characterizes a conflict
conflict :: [(Word32,(Name,Word32))] -> SAMap -> (SAMap,Bool)
conflict [] sam = (sam,False)
conflict ((thread,(arr,ix)):xs) sam =
case Map.lookup arr sam of
Nothing -> error$ "this should not be possible" ++ "\n" ++ show ix ++ "\n" ++ show sam -- conflict xs sam
(Just m) -> case Map.lookup ix m of
Nothing -> error$ "this should not be possible" ++ "\n" ++ show ix ++ "\n" ++ show m
(Just j) ->
if (thread `div` 32 /= j `div` 32)
then (Map.empty,True) -- We have a conflict
else conflict xs sam
-- What thread is computing what "now".
-- Add that info to the SAMap
addMappings :: [(Name,(Word32,Word32))] -> SAMap -> SAMap
addMappings [] sam = sam
addMappings ((nom,(ix,thread)):xs) sam =
let sam' = case Map.lookup nom sam of
Nothing -> Map.insert nom (Map.insert ix thread Map.empty) sam
(Just m) -> Map.insert nom (Map.insert ix thread m) sam
in addMappings xs sam'
|
svenssonjoel/GCDObsidian
|
Obsidian/GCDObsidian/CodeGen/SyncAnalysis.hs
|
bsd-3-clause
| 6,323 | 0 | 15 | 1,808 | 719 | 399 | 320 | 39 | 4 |
{-|
Module : Idris.ErrReverse
Description : Utility to make errors readable using transformations.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.ErrReverse(errReverse) where
import Idris.AbsSyntax
import Idris.Core.Evaluate (unfold)
import Idris.Core.TT
import Data.List
-- | For display purposes, apply any 'error reversal' transformations
-- so that errors will be more readable,
-- and any 'error reduce' transformations
errReverse :: IState -> Term -> Term
errReverse ist t = rewrite 5 (do_unfold t) -- (elideLambdas t)
where
do_unfold :: Term -> Term
do_unfold t = let ns = idris_errReduce ist in
if null ns then t
else unfold (tt_ctxt ist) []
(map (\x -> (x, 1000)) (idris_errReduce ist))
t
rewrite 0 t = t
rewrite n t = let t' = foldl applyRule t (reverse (idris_errRev ist)) in
if t == t' then t
else rewrite (n - 1) t'
applyRule :: Term -> (Term, Term) -> Term
applyRule t (l, r) = applyNames [] t l r
-- Assume pattern bindings match in l and r (if they don't just treat
-- the rule as invalid and return t)
applyNames ns t (Bind n (PVar _ ty) scl) (Bind n' (PVar _ ty') scr)
| n == n' = applyNames (n : ns) t (instantiate (P Ref n ty) scl)
(instantiate (P Ref n' ty') scr)
| otherwise = t
applyNames ns t l r = matchTerm ns l r t
matchTerm ns l r t
| Just nmap <- match ns l t = substNames nmap r
matchTerm ns l r (App s f a) = let f' = matchTerm ns l r f
a' = matchTerm ns l r a in
App s f' a'
matchTerm ns l r (Bind n b sc) = let b' = fmap (matchTerm ns l r) b
sc' = matchTerm ns l r sc in
Bind n b' sc'
matchTerm ns l r t = t
match ns l t = do ms <- match' ns l t
combine (nub ms)
-- If any duplicate mappings, it's a failure
combine [] = Just []
combine ((x, t) : xs)
| Just _ <- lookup x xs = Nothing
| otherwise = do xs' <- combine xs
Just ((x, t) : xs')
match' ns (P Ref n _) t | n `elem` ns = Just [(n, t)]
match' ns (App _ f a) (App _ f' a') = do fs <- match' ns f f'
as <- match' ns a a'
Just (fs ++ as)
-- no matching Binds, for now...
match' ns x y = if x == y then Just [] else Nothing
|
uuhan/Idris-dev
|
src/Idris/ErrReverse.hs
|
bsd-3-clause
| 2,734 | 0 | 15 | 1,101 | 902 | 452 | 450 | 46 | 12 |
module Main where
import Control.Monad
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import qualified System.IO as SIO
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TLIO
dictWords :: IO String
dictWords = SIO.readFile "/usr/share/dict/words"
dictWordsT :: IO T.Text
dictWordsT = TIO.readFile "/usr/share/dict/words"
dictWordsTL :: IO TL.Text
dictWordsTL = TLIO.readFile "/usr/share/dict/words"
main :: IO ()
main = do
replicateM_ 10 (dictWords >>= print)
replicateM_ 10 (dictWordsT >>= TIO.putStrLn)
replicateM_ 10 (dictWordsTL >>= TLIO.putStrLn)
|
dmvianna/strict
|
src/text.hs
|
bsd-3-clause
| 613 | 0 | 10 | 89 | 175 | 100 | 75 | 18 | 1 |
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}
import Text.CSL hiding (Citation, Cite(..))
import Text.CSL.Pandoc
import System.Environment
import Text.JSON
import Text.JSON.Generic
import Text.JSON.Types (get_field)
import Text.Pandoc.Definition hiding (Cite)
import qualified Text.Pandoc.Definition as PDD (Inline(Cite))
import Text.Pandoc.Writers.Markdown
import Text.Pandoc.Writers.HTML
import Text.Pandoc.Writers.OpenDocument
import Text.Pandoc.Writers.Org
import Text.Pandoc.Writers.Native
import Text.Pandoc.Options
--import Text.Pandoc.Generic
import Data.Set (empty)
import Data.List (intersperse)
import Control.Monad (unless)
import Control.Applicative ((<$>))
import System.Exit
import System.IO
--
-- INPUT PROCESSING
--
-- represents arrays of citeproc-js citation data JSON objects
data CitationsData = CitationsData [CitationData] deriving (Typeable, Data)
instance JSON CitationsData where
showJSON (CitationsData cds) = JSArray $ map showJSON cds
readJSON (JSArray cds) = Ok $ CitationsData cs
where cs = reverse $ foldl getCitations [] cds
getCitations acc obj = case readJSON obj of
Ok cd@(CitationData _ _) -> cd:acc
_ -> acc -- TODO: error if non-citation in the array?
readJSON x = fromJSON x
-- represents the citeproc-js citation data JSON object
data CitationData = CitationData { citationItems :: [Cite]
, properties :: DataProperties
} deriving (Typeable, Data)
instance JSON CitationData where
showJSON = toJSON
readJSON (JSObject o) = case get_field o "citationItems" of
Just (JSArray cs) -> Ok CitationData { citationItems = cis
, properties = props
}
where getCites acc obj = case readJSON obj of
Ok c@(Cite {}) -> c:acc
_ -> acc -- TODO: error if non-citation in citationItems?
cis = reverse $ foldl getCites [] cs
props = case get_field o "properties" of
Just p -> case readJSON p of
Ok ps@(DataProperties {}) -> ps
_ -> defProps
_ -> defProps
defProps = DataProperties { noteIndex = 0
, commonPrefix = []
, commonSuffix = []
}
_ -> Error "Not a citations data cluster"
readJSON x = fromJSON x
-- convenience accessors for CitationData properties:
getCPrefix :: CitationData -> [Inline]
getCPrefix = commonPrefix . properties
getCSuffix :: CitationData -> [Inline]
getCSuffix = commonSuffix . properties
-- represents properties of a citation data JSON object
data DataProperties = DataProperties { noteIndex :: Int
-- non-standard properties
-- supported here for LaTeX-like
-- multi-cite behavior:
, commonPrefix :: [Inline]
, commonSuffix :: [Inline]
} deriving (Typeable, Data)
instance JSON DataProperties where
showJSON = toJSON
readJSON (JSObject o) = Ok DataProperties { noteIndex = n
, commonPrefix = cpfx
, commonSuffix = csfx
}
where n = 0 -- TODO
asInlines field = case get_field o field of
Just (JSString s) -> [Str $ fromJSString s]
_ -> []
cpfx = asInlines "common-prefix"
csfx = asInlines "common-suffix"
readJSON x = fromJSON x
-- represents an individual work in a citation data JSON object
data Cite = Cite { citeId :: String
, citePrefix :: [Inline]
, citeSuffix :: [Inline]
, citeLabel :: String
, citeLocator :: String
, suppressAuthor :: Bool
, authorInText :: Bool
-- , itemData :: [ItemData] -- TODO
, uris :: [String]
} deriving (Typeable, Data, Show)
instance JSON Cite where
showJSON = toJSON
readJSON (JSObject o) = case get_field o "id" of
Just (JSString citeid) ->
Ok Cite { citeId = fromJSString citeid
, citePrefix = case get_field o "prefix" of
Just (JSString s) -> [Str $ fromJSString s]
_ -> []
, citeSuffix = case get_field o "suffix" of
Just (JSString s) -> [Str $ fromJSString s]
_ -> []
, citeLabel = case get_field o "label" of
Just (JSString x) -> fromJSString x
_ -> ""
, citeLocator = case get_field o "locator" of
Just (JSString x) -> fromJSString x
_ -> ""
, suppressAuthor = case get_field o "suppress-author" of
Just (JSBool True) -> True
_ -> False
, authorInText = case get_field o "author-in-text" of
Just (JSBool True) -> True
_ -> False
, uris = case get_field o "uris" of
Just (JSArray ss) -> us
where us = reverse $ foldl getUris [] ss
getUris acc obj = case readJSON obj of
-- TODO: convert to Links
Ok (JSString s) -> fromJSString s : acc
_ -> acc -- TODO: error if non-strings in field?
_ -> []
-- TODO: itemData
-- See: https://raw.githubusercontent.com/citation-style-language/schema/master/csl-citation.json
-- https://raw.githubusercontent.com/citation-style-language/schema/master/csl-data.json
}
_ -> Error "Not a citation item"
readJSON x = fromJSON x
-- global values needed by several functions
citeSep :: String
citeSep = "////\n" -- TODO: prefer something like "<!-- endCite -->"?
citeSepInline :: Inline
citeSepInline = Str citeSep
citeBibSep :: String
citeBibSep = "====\n" -- TODO: prefer something like "<!-- startBibliography -->"?
citeBibSepInline :: Inline
citeBibSepInline = Str citeBibSep
citeBibSepBlock :: Block
citeBibSepBlock = Plain [citeBibSepInline]
-- functions to transform input into a Pandoc
itemAsCitation :: Cite -> Citation
itemAsCitation i = Citation { citationId = citeId i
, citationPrefix = citePrefix i
, citationSuffix = citeSuffix i
, citationMode = if authorInText i
then AuthorInText
else if suppressAuthor i
then SuppressAuthor
else NormalCitation
, citationNoteNum = 0
, citationHash = 0
}
toPandocCite :: CitationData -> Inline
toPandocCite cd = PDD.Cite citas []
where citas = map itemAsCitation $ citationItems cd
data MultiCite = InTextMulti CitationData
| ParenMulti CitationData
multiCite :: MultiCite -> [Inline]
multiCite (InTextMulti cd) = group
-- in the in-text case, we need to break up the CitationData into
-- multiple individual records, one for each reference, and add the
-- common prefix and suffix in the surrounding text
where items = citationItems cd
props = properties cd
cpfx = case commonPrefix props of
[] -> []
inls -> inls ++ [Space]
csfx = case commonSuffix props of
[] -> []
inls -> sep : inls
asCd i = CitationData { citationItems = [i], properties = props }
citas = map (toPandocCite . asCd) items
sep = Str ", " -- TODO: grab separator from style?
group = cpfx ++ intersperse sep citas ++ csfx
multiCite (ParenMulti cd) = [toPandocCite newCd]
-- in the parenthetical case, we just need to prepend the common
-- prefix to the prefix of the first item, and append the suffix to
-- the suffix of the last item (which might be the same), then treat
-- the resulting CitationData normally, as a single pandoc Citation
where cpfx = case getCPrefix cd of
[] -> []
inls -> inls ++ [Space]
csfx = case getCSuffix cd of
[] -> []
inls -> Str ", " : inls
newItems = case citationItems cd of
[] -> [] -- edge case: common prefix or suffix, but no items
-- (this case is prevented by Org's parser)
[first] -> [first { citePrefix = cpfx ++ citePrefix first
, citeSuffix = citeSuffix first ++ csfx }]
(first:xs) -> [first { citePrefix = cpfx ++ citePrefix first }] ++
init xs ++
[lst { citeSuffix = citeSuffix lst ++ csfx }]
where lst = last xs
newCd = cd { citationItems = newItems }
citationsAsPandoc :: [CitationData] -> Pandoc
citationsAsPandoc cds = Pandoc nullMeta citationBlocks
where citationBlocks = foldr getBlocks [citeBibSepBlock] cds
-- a citation is a `multi-cite' and needs to be handled
-- specially when it has a common prefix or suffix, or when it
-- contains only in-text references (and there are 2+). In
-- these cases, we behave like LaTeX:
atLeastTwo xs = not (null xs) && not (null $ tail xs)
multiInText cd = atLeastTwo (citationItems cd) &&
all authorInText (citationItems cd)
hasCommons cd = not $ null $ getCPrefix cd ++ getCSuffix cd
getBlocks cd acc
| multiInText cd = (Plain $ multiCite (InTextMulti cd) ++ [citeSepInline]) : acc
| hasCommons cd = (Plain $ multiCite (ParenMulti cd) ++ [citeSepInline]) : acc
| otherwise = Plain [toPandocCite cd, citeSepInline] : acc
--
-- OUTPUT PROCESSING
--
-- output format selection
data OutputFormat = Ascii
| Html
| OpenDocument
| Org
| NativeBefore
| NativeAfter
chooseOutputFormat :: String -> OutputFormat
chooseOutputFormat s
| s == "ascii" = Ascii
| s == "html" = Html
| s == "odt" = OpenDocument
| s == "org" = Org
| s == "native-before" = NativeBefore
| s == "native" = NativeAfter
| otherwise = error $ "Unknown output format: " ++ s
chooseRenderer :: OutputFormat -> Pandoc -> String
chooseRenderer fmt = case fmt of
Ascii -> renderPandocPlain
Html -> renderPandocHTML
OpenDocument -> renderPandocODT
Org -> renderPandocOrg
NativeBefore -> renderPandocNativeBefore
NativeAfter -> renderPandocNative
-- rendering functions:
-- plain text:
renderPandocPlain :: Pandoc -> String
renderPandocPlain = writePlain opts
where opts = def { writerStandalone = False
, writerTableOfContents = False
, writerCiteMethod = Citeproc
, writerWrapText = True -- TODO: don't break lines?
, writerColumns = 80 -- TODO: adjustable?
, writerExtensions = empty -- TODO: need any exts?
}
-- HTML:
renderPandocHTML :: Pandoc -> String
renderPandocHTML = writeHtmlString opts
where opts = def { writerStandalone = False
, writerTableOfContents = False
, writerCiteMethod = Citeproc
, writerWrapText = False
, writerSlideVariant = NoSlides
}
-- ODT:
renderPandocODT :: Pandoc -> String
renderPandocODT (Pandoc _ blocks) = concatMap renderBlock blocks
-- special case: we can't just use Pandoc's ODT writer directly here,
-- because it wraps Plain blocks in <text:p> tags. This breaks our
-- extraction mechanism for individual citations and the bibliography
-- on the Org side. We don't want to produce a complete ODT document,
-- but rather identifiable fragments that can be inserted into an ODT
-- document by Org; so here we take care to insert the separators
-- *outside* the ODT XML tags.
where asDoc inlines = Pandoc nullMeta [Plain inlines]
transform i acc = case i of
(PDD.Cite _ inls) -> inls ++ acc
(Str s) -> if s == citeSep
then acc -- remove cite separators inserted earlier
else i : acc
_ -> i : acc
renderInlines inlines = writeOpenDocument opts $ asDoc $
foldr transform [] inlines
renderBlock b = case b of
(Div ("", ["references"], []) _) ->
citeBibSep ++ writeOpenDocument opts (Pandoc nullMeta [b])
(Plain inls) -> if inls == [citeBibSepInline]
then "" -- remove bib separator inserted earlier
else renderInlines inls ++ citeSep
_ -> ""
opts = def { writerStandalone = False
, writerTableOfContents = False
, writerCiteMethod = Citeproc
, writerWrapText = False
}
-- Org:
renderPandocOrg :: Pandoc -> String
renderPandocOrg (Pandoc m blocks) = writeOrg opts cleanDoc
where opts = def { writerStandalone = False
, writerTableOfContents = False
, writerCiteMethod = Citeproc
, writerSectionDivs = False
, writerWrapText = False
}
-- the Org writer converts divs weirdly, wrapping them in
-- BEGIN_HTML/END_HTML blocks...avoid this by extracting the
-- list of bibliography blocks from a Div block
cleanDoc = Pandoc m (foldr unwrapRefsBlock [] blocks)
headline = Plain [Str "* References\n"]
unwrapRefsBlock b acc = case b of
(Div ("", ["references"], []) blks) -> (headline : blks) ++ acc
_ -> b : acc
-- Native:
renderPandocNativeBefore :: Pandoc -> String
renderPandocNativeBefore = writeNative opts
where opts = def { writerStandalone = False }
renderPandocNative :: Pandoc -> String
renderPandocNative = writeNative opts
where opts = def { writerStandalone = False
, writerTableOfContents = False
, writerCiteMethod = Citeproc
}
--
-- MAIN
--
main :: IO ()
main = do
args <- getArgs
progname <- getProgName
unless (length args >= 3) $ do
hPutStrLn stderr $ "Usage: " ++ progname ++ " OUTPUT-FORMAT CSLFILE BIBFILE.."
exitWith (ExitFailure 1)
let (backend : cslfile : bibfiles) = args
sty <- readCSLFile Nothing cslfile
refs <- concat <$> mapM readBiblioFile bibfiles
res <- decode <$> getContents
-- hPutStrLn stderr $ show res
let Ok (CitationsData inputCitations) = res
-- for debugging:
--hPutStrLn stderr $ show inputCitations
let doc = processCites sty refs $ citationsAsPandoc inputCitations
putStrLn $ (chooseRenderer . chooseOutputFormat) backend doc
|
wyleyr/org-citeproc
|
org-citeproc.hs
|
bsd-3-clause
| 15,402 | 29 | 22 | 5,406 | 3,284 | 1,768 | 1,516 | 274 | 7 |
module Main where
import Libs
main = readArgs
|
mike-k-houghton/Builder
|
src/Main.hs
|
bsd-3-clause
| 48 | 0 | 4 | 10 | 12 | 8 | 4 | 3 | 1 |
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Compiler.Frontend.CommandLine.API.Constants where
globalImportList :: [String]
globalImportList = ["Feldspar.Compiler.Compiler"]
warningPrefix :: String
warningPrefix = "[WARNING]: "
errorPrefix :: String
errorPrefix = "[ERROR ]: "
|
emwap/feldspar-compiler
|
src/Feldspar/Compiler/Frontend/CommandLine/API/Constants.hs
|
bsd-3-clause
| 1,854 | 0 | 5 | 326 | 73 | 57 | 16 | 7 | 1 |
{-# LANGUAGE BangPatterns, MultiParamTypeClasses #-}
{-# OPTIONS -fno-warn-orphans #-}
module Data.Digest.JH384 (
jh384,
JH384Digest(..),
JHContext (..),
Hash(..),
hash,
hash',
printAsHex,
printAsHex'
) where
import qualified Data.ByteString.Lazy as L
import Data.Int (Int64)
import Data.List (foldl')
import Control.Monad (liftM)
import Crypto.Classes
import Data.Tagged
import Data.Serialize
import Prelude hiding (truncate)
import Data.Digest.JHInternal
jh384 :: Int64 -> L.ByteString -> L.ByteString
jh384 dataBitLen
| dataBitLen < 0 = error "The data length can not be less than 0"
| otherwise = truncate JH384 . foldl' f8 jh384_h0 . parseMessage dataBitLen
---------------------- Crypto-api instance -------------
instance Hash JHContext JH384Digest where
outputLength = Tagged 384
blockLength = Tagged 512
initialCtx = jhInit JH384 jh384_h0
updateCtx = jhUpdate
finalize ctx = Digest . jhFinalize ctx
data JH384Digest = Digest L.ByteString
deriving (Eq,Ord)
instance Show JH384Digest where
show (Digest h) = printAsHex h
instance Serialize JH384Digest where
put (Digest bs) = put bs
get = liftM Digest get
--------------------- Initial hash value -----------------
jh384_h0 :: Block1024
jh384_h0 = B1024 (B512 0x481e3bc6d813398a6d3b5e894ade879b 0x63faea68d480ad2e332ccb21480f8267
0x98aec84d9082b928d455ea3041114249 0x36f555b2924847ecc7250a93baf43ce1)
(B512 0x569b7f8a27db454c9efcbd496397af0e 0x589fc27d26aa80cd80c08b8c9deb2eda
0x8a7981e8f8d5373af43967adddd17a71 0xa9b4d3bda475d394976c3fba9842737f)
|
hakoja/SHA3
|
Data/Digest/JH384.hs
|
bsd-3-clause
| 1,729 | 0 | 8 | 394 | 361 | 198 | 163 | 42 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.SSH.Messages where
import Network.SSH.Protocol
import Control.Monad ( when )
import Data.ByteString.Short (ShortByteString)
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Lazy ()
import Data.Serialize
( Get, Putter, Put, label, isolate, getBytes, putByteString
, putWord8, getWord8, getWord32be, putWord32be, runPut
, remaining )
import Data.Maybe ( isJust, fromJust )
import Data.Word ( Word32 )
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ( (<$>), (<*>) )
#endif
{-
Transport layer protocol:
1 to 19 Transport layer generic (e.g., disconnect, ignore,
debug, etc.)
20 to 29 Algorithm negotiation
30 to 49 Key exchange method specific (numbers can be reused
for different authentication methods)
User authentication protocol:
50 to 59 User authentication generic
60 to 79 User authentication method specific (numbers can be
reused for different authentication methods)
Connection protocol:
80 to 89 Connection protocol generic
90 to 127 Channel related messages
Reserved for client protocols:
128 to 191 Reserved
Local extensions:
192 to 255 Local extensions
-}
data SshMsgTag = SshMsgTagDisconnect
| SshMsgTagIgnore
| SshMsgTagUnimplemented
| SshMsgTagDebug
| SshMsgTagServiceRequest
| SshMsgTagServiceAccept
| SshMsgTagKexInit
| SshMsgTagNewKeys
| SshMsgTagKexDhInit
| SshMsgTagKexDhReply
| SshMsgTagUserAuthRequest
| SshMsgTagUserAuthFailure
| SshMsgTagUserAuthSuccess
| SshMsgTagUserAuthBanner
| SshMsgTagUserAuthPkOk
| SshMsgTagGlobalRequest
| SshMsgTagRequestSuccess
| SshMsgTagRequestFailure
| SshMsgTagChannelOpen
| SshMsgTagChannelOpenConfirmation
| SshMsgTagChannelOpenFailure
| SshMsgTagChannelWindowAdjust
| SshMsgTagChannelData
| SshMsgTagChannelExtendedData
| SshMsgTagChannelEof
| SshMsgTagChannelClose
| SshMsgTagChannelRequest
| SshMsgTagChannelSuccess
| SshMsgTagChannelFailure
deriving (Show,Eq)
data SshMsg = SshMsgDisconnect SshDiscReason !S.ByteString !S.ByteString
| SshMsgIgnore !S.ByteString
| SshMsgUnimplemented !Word32
| SshMsgDebug Bool !S.ByteString !S.ByteString
| SshMsgServiceRequest SshService
| SshMsgServiceAccept SshService
-- Shared secret establishment and server authentication.
| SshMsgKexInit SshProposal
| SshMsgNewKeys
| SshMsgKexDhInit !S.ByteString
| SshMsgKexDhReply SshPubCert !S.ByteString SshSig
-- Client authentication.
| SshMsgUserAuthRequest !S.ByteString SshService SshAuthMethod
| SshMsgUserAuthFailure
[ShortByteString] -- Supported methods
Bool -- Partial success
| SshMsgUserAuthPkOk
!S.ByteString -- key algorithm
!SshPubCert -- key blob
| SshMsgUserAuthSuccess
| SshMsgUserAuthBanner !S.ByteString !S.ByteString
-- Channel independent global requests and replies.
| SshMsgGlobalRequest !S.ByteString !Bool !S.ByteString
| SshMsgRequestSuccess !S.ByteString
| SshMsgRequestFailure
-- Channel creation requests and replies.
| SshMsgChannelOpen !SshChannelType !Word32 !Word32 !Word32
| SshMsgChannelOpenConfirmation !Word32 !Word32 !Word32 !Word32
| SshMsgChannelOpenFailure !Word32 !SshOpenFailure !S.ByteString !S.ByteString
-- Channel-specific data-related messages.
| SshMsgChannelWindowAdjust !Word32 !Word32
| SshMsgChannelData !Word32 !S.ByteString
| SshMsgChannelExtendedData !Word32 !Word32 !S.ByteString
| SshMsgChannelEof !Word32
| SshMsgChannelClose !Word32
-- Channel-specific requests and replies.
| SshMsgChannelRequest !SshChannelRequest !Word32 !Bool
| SshMsgChannelSuccess !Word32
| SshMsgChannelFailure !Word32
deriving (Show,Eq)
openFailureToCode :: SshOpenFailure -> Word32
openFailureToCode x =
case x of
SshOpenAdministrativelyProhibited -> 1
SshOpenConnectFailed -> 2
SshOpenUnknownChannelType -> 3
SshOpenResourceShortage -> 4
codeToOpenFailure :: Word32 -> Maybe SshOpenFailure
codeToOpenFailure x =
case x of
1 -> Just SshOpenAdministrativelyProhibited
2 -> Just SshOpenConnectFailed
3 -> Just SshOpenUnknownChannelType
4 -> Just SshOpenResourceShortage
_ -> Nothing
data SshOpenFailure
= SshOpenAdministrativelyProhibited
| SshOpenConnectFailed
| SshOpenUnknownChannelType
| SshOpenResourceShortage
deriving (Read, Show, Eq, Ord)
data SshChannelRequestTag
= SshChannelRequestTagPtyReq
| SshChannelRequestTagX11Req
| SshChannelRequestTagEnv
| SshChannelRequestTagShell
| SshChannelRequestTagExec
| SshChannelRequestTagSubsystem
| SshChannelRequestTagWindowChange
| SshChannelRequestTagXonXoff
| SshChannelRequestTagSignal
| SshChannelRequestTagExitStatus
| SshChannelRequestTagExitSignal
deriving (Read,Show,Eq,Ord)
data SshChannelRequest
= SshChannelRequestPtyReq S.ByteString SshWindowSize S.ByteString
| SshChannelRequestEnv !S.ByteString !S.ByteString
| SshChannelRequestShell
| SshChannelRequestExec !S.ByteString
| SshChannelRequestSubsystem !S.ByteString
| SshChannelRequestWindowChange !SshWindowSize
deriving (Read,Show,Eq,Ord)
sshChannelRequestTag :: SshChannelRequest -> SshChannelRequestTag
sshChannelRequestTag request = case request of
SshChannelRequestPtyReq {} -> SshChannelRequestTagPtyReq
SshChannelRequestEnv {} -> SshChannelRequestTagEnv
SshChannelRequestShell {} -> SshChannelRequestTagShell
SshChannelRequestExec {} -> SshChannelRequestTagExec
SshChannelRequestSubsystem {} -> SshChannelRequestTagSubsystem
SshChannelRequestWindowChange {} -> SshChannelRequestTagWindowChange
data SshWindowSize = SshWindowSize
{ sshWsCols, sshWsRows, sshWsX, sshWsY :: !Word32 }
deriving (Read, Show, Ord, Eq)
sshMsgTag :: SshMsg -> SshMsgTag
sshMsgTag msg = case msg of
SshMsgDisconnect {} -> SshMsgTagDisconnect
SshMsgIgnore {} -> SshMsgTagIgnore
SshMsgUnimplemented {} -> SshMsgTagUnimplemented
SshMsgDebug {} -> SshMsgTagDebug
SshMsgServiceRequest {} -> SshMsgTagServiceRequest
SshMsgServiceAccept {} -> SshMsgTagServiceAccept
SshMsgKexInit {} -> SshMsgTagKexInit
SshMsgNewKeys {} -> SshMsgTagNewKeys
SshMsgKexDhInit {} -> SshMsgTagKexDhInit
SshMsgKexDhReply {} -> SshMsgTagKexDhReply
SshMsgUserAuthRequest {} -> SshMsgTagUserAuthRequest
SshMsgUserAuthFailure {} -> SshMsgTagUserAuthFailure
SshMsgUserAuthSuccess {} -> SshMsgTagUserAuthSuccess
SshMsgUserAuthBanner {} -> SshMsgTagUserAuthBanner
SshMsgUserAuthPkOk {} -> SshMsgTagUserAuthPkOk
SshMsgGlobalRequest {} -> SshMsgTagGlobalRequest
SshMsgRequestSuccess {} -> SshMsgTagRequestSuccess
SshMsgRequestFailure {} -> SshMsgTagRequestFailure
SshMsgChannelOpen {} -> SshMsgTagChannelOpen
SshMsgChannelOpenConfirmation {} -> SshMsgTagChannelOpenConfirmation
SshMsgChannelOpenFailure {} -> SshMsgTagChannelOpenFailure
SshMsgChannelWindowAdjust {} -> SshMsgTagChannelWindowAdjust
SshMsgChannelData {} -> SshMsgTagChannelData
SshMsgChannelExtendedData {} -> SshMsgTagChannelExtendedData
SshMsgChannelEof {} -> SshMsgTagChannelEof
SshMsgChannelClose {} -> SshMsgTagChannelClose
SshMsgChannelRequest {} -> SshMsgTagChannelRequest
SshMsgChannelSuccess {} -> SshMsgTagChannelSuccess
SshMsgChannelFailure {} -> SshMsgTagChannelFailure
data SshService = SshUserAuth
| SshConnection
| SshServiceOther !S.ByteString
deriving (Show,Eq)
data SshDiscReason = SshDiscNoReason
| SshDiscHostNotAllowed
| SshDiscProtocolError
| SshDiscKexFailed
| SshDiscReserved
| SshDiscMacError
| SshDiscCompressionError
| SshDiscServiceNotAvailable
| SshDiscProtocolVersionNotSupported
| SshDiscHostKeyNotVerifiable
| SshDiscConnectionLost
| SshDiscByApplication
| SshDiscTooManyConnections
| SshDiscAuthCancelledByUser
| SshDiscNoMoreAuthMethodsAvailable
| SshDiscIllegalUserName
deriving (Show,Eq)
-- | Always 16 bytes of random data.
newtype SshCookie = SshCookie S.ByteString
deriving (Eq,Show,Read)
type NameList = [ShortByteString]
data SshAlgs = SshAlgs
{ sshClientToServer :: NameList
, sshServerToClient :: NameList
} deriving (Eq,Show,Read)
data SshProposal = SshProposal
{ sshProposalCookie :: !SshCookie
, sshKexAlgs :: NameList
, sshServerHostKeyAlgs :: NameList
, sshEncAlgs :: !SshAlgs
, sshMacAlgs :: !SshAlgs
, sshCompAlgs :: !SshAlgs
, sshLanguages :: !SshAlgs
, sshFirstKexFollows :: Bool
} deriving (Eq,Show,Read)
data SshPubCert
= SshPubDss !Integer !Integer !Integer !Integer -- ^ p q g y
| SshPubRsa !Integer !Integer -- ^ e n
| SshPubEcDsaP256 !S.ByteString
| SshPubEcDsaP384 !S.ByteString
| SshPubEcDsaP521 !S.ByteString
| SshPubEd25519 !S.ByteString
| SshPubOther !S.ByteString !S.ByteString
deriving (Eq,Show,Read)
sshPubCertName :: SshPubCert -> S.ByteString
sshPubCertName SshPubDss {} = "ssh-dss"
sshPubCertName SshPubRsa {} = "ssh-rsa"
sshPubCertName SshPubEcDsaP256 {} = "ecdsa-sha2-nistp256"
sshPubCertName SshPubEcDsaP384 {} = "ecdsa-sha2-nistp384"
sshPubCertName SshPubEcDsaP521 {} = "ecdsa-sha2-nistp521"
sshPubCertName SshPubEd25519 {} = "ssh-ed25519"
sshPubCertName (SshPubOther n _) = n
data SshSig
= SshSigDss !Integer !Integer -- ^ r s
| SshSigRsa !S.ByteString
| SshSigEcDsaP256 !S.ByteString
| SshSigEcDsaP384 !S.ByteString
| SshSigEcDsaP521 !S.ByteString
| SshSigEd25519 !S.ByteString
| SshSigOther S.ByteString S.ByteString
deriving (Eq,Show,Read)
newtype SshSessionId = SshSessionId S.ByteString
data SshAuthMethod = SshAuthPublicKey S.ByteString SshPubCert (Maybe SshSig)
| SshAuthPassword !S.ByteString (Maybe S.ByteString) {- ^ optional new password -}
| SshAuthHostBased !S.ByteString !S.ByteString !S.ByteString !S.ByteString !S.ByteString
| SshAuthNone
deriving (Show,Eq)
data SshChannelTypeTag
= SshChannelTypeTagSession
| SshChannelTypeTagX11
| SshChannelTypeTagForwardedTcpIp
| SshChannelTypeTagDirectTcpIp
deriving (Read,Show,Eq,Ord)
data SshChannelType
= SshChannelTypeSession
| SshChannelTypeX11 S.ByteString Word32
| SshChannelTypeForwardedTcpIp S.ByteString Word32 S.ByteString Word32
| SshChannelTypeDirectTcpIp S.ByteString Word32 S.ByteString Word32
deriving (Read,Show,Eq,Ord)
sshChannelTypeTag :: SshChannelType -> SshChannelTypeTag
sshChannelTypeTag tp = case tp of
SshChannelTypeSession -> SshChannelTypeTagSession
SshChannelTypeX11{} -> SshChannelTypeTagX11
SshChannelTypeForwardedTcpIp{} -> SshChannelTypeTagForwardedTcpIp
SshChannelTypeDirectTcpIp{} -> SshChannelTypeTagDirectTcpIp
-- Rendering -------------------------------------------------------------------
putSshMsgTag :: Putter SshMsgTag
putSshMsgTag msg = putWord8 $! case msg of
SshMsgTagDisconnect -> 1
SshMsgTagIgnore -> 2
SshMsgTagUnimplemented -> 3
SshMsgTagDebug -> 4
SshMsgTagServiceRequest -> 5
SshMsgTagServiceAccept -> 6
SshMsgTagKexInit -> 20
SshMsgTagNewKeys -> 21
SshMsgTagKexDhInit -> 30
SshMsgTagKexDhReply -> 31
SshMsgTagUserAuthRequest -> 50
SshMsgTagUserAuthFailure -> 51
SshMsgTagUserAuthSuccess -> 52
SshMsgTagUserAuthBanner -> 53
SshMsgTagUserAuthPkOk -> 60
SshMsgTagGlobalRequest -> 80
SshMsgTagRequestSuccess -> 81
SshMsgTagRequestFailure -> 82
SshMsgTagChannelOpen -> 90
SshMsgTagChannelOpenConfirmation -> 91
SshMsgTagChannelOpenFailure -> 92
SshMsgTagChannelWindowAdjust -> 93
SshMsgTagChannelData -> 94
SshMsgTagChannelExtendedData -> 95
SshMsgTagChannelEof -> 96
SshMsgTagChannelClose -> 97
SshMsgTagChannelRequest -> 98
SshMsgTagChannelSuccess -> 99
SshMsgTagChannelFailure -> 100
putSshMsg :: Putter SshMsg
putSshMsg msg =
do putSshMsgTag (sshMsgTag msg)
case msg of
SshMsgDisconnect r d l -> putDisconnect r d l
SshMsgIgnore bytes -> putString bytes
SshMsgUnimplemented sn -> putWord32be sn
SshMsgDebug d m l -> putDebug d m l
SshMsgServiceRequest svc -> putSshService svc
SshMsgServiceAccept svc -> putSshService svc
SshMsgKexInit proposal -> putSshProposal proposal
SshMsgNewKeys -> return ()
SshMsgKexDhInit n -> putString n
SshMsgKexDhReply c f s -> putDhReply c f s
SshMsgUserAuthRequest user svc m -> putUserAuthRequest user svc m
SshMsgUserAuthFailure ms p -> putUserAuthFailure ms p
SshMsgUserAuthSuccess -> return ()
SshMsgUserAuthBanner txt lang -> putString txt >> putString lang
SshMsgUserAuthPkOk alg key -> putUserAuthPkOk alg key
SshMsgGlobalRequest name reply bytes -> putString name >> putBoolean reply >> putByteString bytes
-- response specific data
SshMsgRequestSuccess bytes -> putByteString bytes -- response specific data
SshMsgRequestFailure -> return ()
SshMsgChannelOpen tp id' win pkt -> putChannelOpen tp id' win pkt
SshMsgChannelOpenConfirmation chan1 chan2 win maxPack -> putWord32be chan1 >> putWord32be chan2 >>
putWord32be win >> putWord32be maxPack
SshMsgChannelOpenFailure c r d l -> putWord32be c >> putWord32be (openFailureToCode r) >>
putString d >> putString l
SshMsgChannelWindowAdjust chan adj -> putWord32be chan >> putWord32be adj
SshMsgChannelData chan bytes -> putWord32be chan >> putString bytes
SshMsgChannelExtendedData chan code bytes -> putWord32be chan >> putWord32be code >> putString bytes
SshMsgChannelEof chan -> putWord32be chan
SshMsgChannelClose chan -> putWord32be chan
SshMsgChannelRequest req id' rep -> putChannelRequest req id' rep
SshMsgChannelSuccess chan -> putWord32be chan
SshMsgChannelFailure chan -> putWord32be chan
putDebug :: Bool -> S.ByteString -> S.ByteString -> Put
putDebug d m l =
do putBoolean d
putString m
putString l
putSshCookie :: Putter SshCookie
putSshCookie (SshCookie bytes) =
putByteString bytes
putSshAlgs :: Putter SshAlgs
putSshAlgs SshAlgs { .. } =
do putNameList sshClientToServer
putNameList sshServerToClient
putSshProposal :: Putter SshProposal
putSshProposal SshProposal{ .. } =
do putSshCookie sshProposalCookie
putNameList sshKexAlgs
putNameList sshServerHostKeyAlgs
putSshAlgs sshEncAlgs
putSshAlgs sshMacAlgs
putSshAlgs sshCompAlgs
putSshAlgs sshLanguages
putBoolean sshFirstKexFollows
-- RESERVED
putWord32be 0
-- TODO(conathan): make @putString . runPut@ part of the definition
-- here, instead of duplicating it everywhere, and confusing me when I
-- forget to add it. And similar for 'putSshSig'.
putSshPubCert :: Putter SshPubCert
putSshPubCert (SshPubDss p q g y) =
do putString "ssh-dss"
putMpInt p
putMpInt q
putMpInt g
putMpInt y
putSshPubCert (SshPubRsa e n) =
do putString "ssh-rsa"
putMpInt e
putMpInt n
putSshPubCert (SshPubEcDsaP256 str) =
do putString "ecdsa-sha2-nistp256"
putString "nistp256"
putString str
putSshPubCert (SshPubEcDsaP384 str) =
do putString "ecdsa-sha2-nistp384"
putString "nistp384"
putString str
putSshPubCert (SshPubEcDsaP521 str) =
do putString "ecdsa-sha2-nistp521"
putString "nistp521"
putString str
putSshPubCert (SshPubEd25519 str) =
do putString "ssh-ed25519"
putString str
putSshPubCert (SshPubOther name bytes) =
do putString name
putByteString bytes
putSshSig :: Putter SshSig
putSshSig (SshSigDss r s) =
do putString "ssh-dss"
putWord32be 40
putUnsigned 20 r
putUnsigned 20 s
putSshSig (SshSigRsa s) =
do putString "ssh-rsa"
putString s
putSshSig (SshSigEcDsaP256 s) =
do putString "ecdsa-sha2-nistp256"
putString s
putSshSig (SshSigEcDsaP384 s) =
do putString "ecdsa-sha2-nistp384"
putString s
putSshSig (SshSigEcDsaP521 s) =
do putString "ecdsa-sha2-nistp521"
putString s
putSshSig (SshSigEd25519 s) =
do putString "ssh-ed25519"
putString s
putSshSig (SshSigOther name bytes) =
do putString name
putByteString bytes
putDhReply :: SshPubCert -> S.ByteString -> SshSig -> Put
putDhReply cert f sig =
do putString (runPut (putSshPubCert cert))
putString f
putString (runPut (putSshSig sig))
getDhReply :: Get SshMsg
getDhReply =
do certLen <- getWord32be
cert <- isolate (fromIntegral certLen) (label "dhreply.cert" getSshPubCert)
pub <- label "dhreply.pub" getString
sigLen <- getWord32be
sig <- isolate (fromIntegral sigLen) (label "dhreply.sig" getSshSig)
return (SshMsgKexDhReply cert pub sig)
putSshDiscReason :: Putter SshDiscReason
putSshDiscReason r = putWord32be $! case r of
SshDiscNoReason -> 0
SshDiscHostNotAllowed -> 1
SshDiscProtocolError -> 2
SshDiscKexFailed -> 3
SshDiscReserved -> 4
SshDiscMacError -> 5
SshDiscCompressionError -> 6
SshDiscServiceNotAvailable -> 7
SshDiscProtocolVersionNotSupported -> 8
SshDiscHostKeyNotVerifiable -> 9
SshDiscConnectionLost -> 10
SshDiscByApplication -> 11
SshDiscTooManyConnections -> 12
SshDiscAuthCancelledByUser -> 13
SshDiscNoMoreAuthMethodsAvailable -> 14
SshDiscIllegalUserName -> 15
putDisconnect :: SshDiscReason -> S.ByteString -> S.ByteString -> Put
putDisconnect r msg lang =
do putSshDiscReason r
putString msg
putString lang
putSshService :: Putter SshService
putSshService SshUserAuth = putString "ssh-userauth"
putSshService SshConnection = putString "ssh-connection"
putSshService (SshServiceOther name) = putString name
putUserAuthRequest :: S.ByteString -> SshService -> SshAuthMethod -> Put
putUserAuthRequest user service method =
do putString user
putSshService service
putAuthMethod method
putAuthMethod :: Putter SshAuthMethod
putAuthMethod (SshAuthPublicKey pubKeyAlg pubKey maybeSig) =
do putString "publickey"
putBoolean (isJust maybeSig)
putString pubKeyAlg
putString (runPut (putSshPubCert pubKey))
when (isJust maybeSig) $
putString (runPut (putSshSig (fromJust maybeSig)))
putAuthMethod (SshAuthPassword oldPw maybeNewPw) =
do putString "password"
putBoolean (isJust maybeNewPw)
putString oldPw
when (isJust maybeNewPw) $
putString (fromJust maybeNewPw)
putAuthMethod (SshAuthHostBased {}) = fail "putAuthMethod: unimplemented"
putAuthMethod (SshAuthNone {}) = putString "none"
putUserAuthFailure :: [ShortByteString] -> Bool -> Put
putUserAuthFailure methods partialSuccess =
do putNameList methods
putBoolean partialSuccess
putUserAuthPkOk :: S.ByteString -> SshPubCert -> Put
putUserAuthPkOk alg key =
do putString alg
putString (runPut (putSshPubCert key))
putSessionId :: Putter SshSessionId
putSessionId (SshSessionId sessionId) = putString sessionId
putChannelOpen :: SshChannelType -> Word32 -> Word32 -> Word32 -> Put
putChannelOpen tp id_us windowSize maxPacket = do
putSshChannelType tp
putWord32be id_us
putWord32be windowSize
putWord32be maxPacket
putSshChannelType :: Putter SshChannelType
putSshChannelType tp = do
putSshChannelTypeTag $ sshChannelTypeTag tp
case tp of
SshChannelTypeSession -> return ()
SshChannelTypeX11 address port -> do
putString address
putWord32be port
SshChannelTypeForwardedTcpIp address1 port1 address2 port2 -> do
putString address1
putWord32be port1
putString address2
putWord32be port2
SshChannelTypeDirectTcpIp address1 port1 address2 port2 -> do
putString address1
putWord32be port1
putString address2
putWord32be port2
putSshChannelTypeTag :: Putter SshChannelTypeTag
putSshChannelTypeTag tag = putString $ case tag of
SshChannelTypeTagSession -> "session"
SshChannelTypeTagX11 -> "x11"
SshChannelTypeTagForwardedTcpIp -> "forwarded-tcpip"
SshChannelTypeTagDirectTcpIp -> "direct-tcpip"
putChannelRequest :: SshChannelRequest -> Word32 -> Bool -> Put
putChannelRequest request channelId_them wantReply = do
putWord32be channelId_them
putChannelRequestTag $ sshChannelRequestTag request
putBoolean wantReply
case request of
SshChannelRequestPtyReq term winsize modes -> do
putString term
putWindowSize winsize
putString modes
SshChannelRequestEnv name value -> do
putString name
putString value
SshChannelRequestShell -> return ()
SshChannelRequestExec cmd ->
putString cmd
SshChannelRequestSubsystem subsystem ->
putString subsystem
SshChannelRequestWindowChange winsize ->
putWindowSize winsize
putWindowSize :: Putter SshWindowSize
putWindowSize (SshWindowSize c r x y) = do
putWord32be c
putWord32be r
putWord32be x
putWord32be y
putChannelRequestTag :: Putter SshChannelRequestTag
putChannelRequestTag tag = putString $ case tag of
SshChannelRequestTagPtyReq -> "pty-req"
SshChannelRequestTagX11Req -> "x11-req"
SshChannelRequestTagEnv -> "env"
SshChannelRequestTagShell -> "shell"
SshChannelRequestTagExec -> "exec"
SshChannelRequestTagSubsystem -> "subsystem"
SshChannelRequestTagWindowChange -> "window-change"
SshChannelRequestTagXonXoff -> "xon-xoff"
SshChannelRequestTagSignal -> "signal"
SshChannelRequestTagExitStatus -> "exit-status"
SshChannelRequestTagExitSignal -> "exit-signal"
-- Parsing ---------------------------------------------------------------------
getSshMsgTag :: Get SshMsgTag
getSshMsgTag = label "SshMsgTag" $
do tag <- getWord8
case tag of
1 -> return SshMsgTagDisconnect
2 -> return SshMsgTagIgnore
3 -> return SshMsgTagUnimplemented
4 -> return SshMsgTagDebug
5 -> return SshMsgTagServiceRequest
6 -> return SshMsgTagServiceAccept
20 -> return SshMsgTagKexInit
21 -> return SshMsgTagNewKeys
30 -> return SshMsgTagKexDhInit
31 -> return SshMsgTagKexDhReply
50 -> return SshMsgTagUserAuthRequest
51 -> return SshMsgTagUserAuthFailure
52 -> return SshMsgTagUserAuthSuccess
53 -> return SshMsgTagUserAuthBanner
60 -> return SshMsgTagUserAuthPkOk
80 -> return SshMsgTagGlobalRequest
81 -> return SshMsgTagRequestSuccess
82 -> return SshMsgTagRequestFailure
90 -> return SshMsgTagChannelOpen
91 -> return SshMsgTagChannelOpenConfirmation
92 -> return SshMsgTagChannelOpenFailure
93 -> return SshMsgTagChannelWindowAdjust
94 -> return SshMsgTagChannelData
95 -> return SshMsgTagChannelExtendedData
96 -> return SshMsgTagChannelEof
97 -> return SshMsgTagChannelClose
98 -> return SshMsgTagChannelRequest
99 -> return SshMsgTagChannelSuccess
100 -> return SshMsgTagChannelFailure
_ -> fail ("Unknown message type: " ++ show tag)
getSshMsg :: Get SshMsg
getSshMsg =
do tag <- getSshMsgTag
label (show tag) $ case tag of
SshMsgTagDisconnect -> getSshDisconnect
SshMsgTagIgnore -> SshMsgIgnore <$> getString
SshMsgTagUnimplemented -> SshMsgUnimplemented <$> getWord32be
SshMsgTagDebug -> getDebug
SshMsgTagServiceRequest -> SshMsgServiceRequest <$> getSshService
SshMsgTagServiceAccept -> SshMsgServiceAccept <$> getSshService
SshMsgTagKexInit -> SshMsgKexInit <$> getSshProposal
SshMsgTagNewKeys -> return SshMsgNewKeys
SshMsgTagKexDhInit -> SshMsgKexDhInit <$> getString
SshMsgTagKexDhReply -> getDhReply
SshMsgTagUserAuthRequest -> getAuthRequest
SshMsgTagUserAuthFailure -> getUserAuthFailure
SshMsgTagUserAuthSuccess -> return SshMsgUserAuthSuccess
SshMsgTagUserAuthBanner -> SshMsgUserAuthBanner <$> getString <*> getString
SshMsgTagUserAuthPkOk -> getUserAuthPkOk
SshMsgTagGlobalRequest -> SshMsgGlobalRequest <$> getString <*> getBoolean <*> getRemaining
SshMsgTagRequestSuccess -> SshMsgRequestSuccess <$> getRemaining
SshMsgTagRequestFailure -> return SshMsgRequestFailure
SshMsgTagChannelOpen -> getChannelOpen
SshMsgTagChannelOpenConfirmation -> SshMsgChannelOpenConfirmation
<$> getWord32be <*> getWord32be
<*> getWord32be <*> getWord32be
SshMsgTagChannelOpenFailure -> SshMsgChannelOpenFailure
<$> getWord32be <*> getOpenFailure
<*> getString <*> getString
SshMsgTagChannelWindowAdjust -> SshMsgChannelWindowAdjust
<$> getWord32be <*> getWord32be
SshMsgTagChannelData -> SshMsgChannelData <$> getWord32be <*> getString
SshMsgTagChannelExtendedData -> SshMsgChannelExtendedData <$> getWord32be <*> getWord32be <*> getString
SshMsgTagChannelEof -> SshMsgChannelEof <$> getWord32be
SshMsgTagChannelClose -> SshMsgChannelClose <$> getWord32be
SshMsgTagChannelRequest -> getChannelRequest
SshMsgTagChannelSuccess -> SshMsgChannelSuccess <$> getWord32be
SshMsgTagChannelFailure -> SshMsgChannelFailure <$> getWord32be
getSshDiscReason :: Get SshDiscReason
getSshDiscReason = label "SshDiscReason" $
do tag <- getWord32be
case tag of
0 -> return SshDiscNoReason
1 -> return SshDiscHostNotAllowed
2 -> return SshDiscProtocolError
3 -> return SshDiscKexFailed
4 -> return SshDiscReserved
5 -> return SshDiscMacError
6 -> return SshDiscCompressionError
7 -> return SshDiscServiceNotAvailable
8 -> return SshDiscProtocolVersionNotSupported
9 -> return SshDiscHostKeyNotVerifiable
10 -> return SshDiscConnectionLost
11 -> return SshDiscByApplication
12 -> return SshDiscTooManyConnections
13 -> return SshDiscAuthCancelledByUser
14 -> return SshDiscNoMoreAuthMethodsAvailable
15 -> return SshDiscIllegalUserName
_ -> fail ("Unknown disconnection reason: " ++ show tag)
getSshDisconnect :: Get SshMsg
getSshDisconnect =
do reason <- getSshDiscReason
desc <- getString
lang <- getString
return (SshMsgDisconnect reason desc lang)
getDebug :: Get SshMsg
getDebug =
do b <- getBoolean
d <- getString
l <- getString
return (SshMsgDebug b d l)
getSshCookie :: Get SshCookie
getSshCookie = SshCookie `fmap` getBytes 16
getSshAlgs :: Get SshAlgs
getSshAlgs =
do sshClientToServer <- getNameList
sshServerToClient <- getNameList
return SshAlgs { .. }
getSshProposal :: Get SshProposal
getSshProposal = label "SshProposal" $
do sshProposalCookie <- label "sshCookie" getSshCookie
sshKexAlgs <- label "sshKexAlgs" getNameList
sshServerHostKeyAlgs <- label "sshServerHostKeyAlgs" getNameList
sshEncAlgs <- label "sshEncAlgs" getSshAlgs
sshMacAlgs <- label "sshMacAlgs" getSshAlgs
sshCompAlgs <- label "sshCompAlgs" getSshAlgs
sshLanguages <- label "sshLanguages" getSshAlgs
sshFirstKexFollows <- label "sshFirstKexFollows" getBoolean
-- RESERVED
0 <- getWord32be
return SshProposal{ .. }
getSshPubCert :: Get SshPubCert
getSshPubCert = label "SshPubCert" $
do name <- getString
case name of
"ssh-dss" ->
do p <- getMpInt
q <- getMpInt
g <- getMpInt
y <- getMpInt
return (SshPubDss p q g y)
"ssh-rsa" ->
do e <- getMpInt
n <- getMpInt
return (SshPubRsa e n)
"ecdsa-sha2-nistp256" ->
do "nistp256" <- getString
str <- getString
return (SshPubEcDsaP256 str)
"ecdsa-sha2-nistp384" ->
do "nistp384" <- getString
str <- getString
return (SshPubEcDsaP384 str)
"ecdsa-sha2-nistp521" ->
do "nistp521" <- getString
str <- getString
return (SshPubEcDsaP521 str)
"ssh-ed25519" ->
do str <- getString
return (SshPubEd25519 str)
_ ->
do bytes <- getBytes =<< remaining
return (SshPubOther name bytes)
getSshSig :: Get SshSig
getSshSig = label "SshSig" $
do name <- getString
case name of
"ssh-dss" ->
do 40 <- getWord32be
r <- getUnsigned (160 `div` 8)
s <- getUnsigned (160 `div` 8)
return (SshSigDss r s)
"ssh-rsa" ->
do s <- getString
return (SshSigRsa s)
"ecdsa-sha2-nistp256" ->
do s <- getString
return (SshSigEcDsaP256 s)
"ecdsa-sha2-nistp384" ->
do s <- getString
return (SshSigEcDsaP384 s)
"ecdsa-sha2-nistp521" ->
do s <- getString
return (SshSigEcDsaP521 s)
"ssh-ed25519" ->
do s <- getString
return (SshSigEd25519 s)
_ ->
do bytes <- getBytes =<< remaining
return (SshSigOther name bytes)
getSshService :: Get SshService
getSshService =
do service <- getString
case service of
"ssh-userauth" -> return SshUserAuth
"ssh-connection" -> return SshConnection
_ -> return (SshServiceOther service)
getAuthRequest :: Get SshMsg
getAuthRequest =
do username <- getString
serviceName <- getSshService
method <- getAuthMethod
return (SshMsgUserAuthRequest username serviceName method)
getAuthMethod :: Get SshAuthMethod
getAuthMethod = label "SshAuthMethod" $
do tag <- getString
case tag of
"publickey" ->
do hasSignature <- getBoolean
pubKeyAlg <- getString
pubKeyLen <- getWord32be
pubKey <- isolate (fromIntegral pubKeyLen) getSshPubCert
sig <- if hasSignature
then do sigLen <- getWord32be
sig <- isolate (fromIntegral sigLen)
getSshSig
return (Just sig)
else return Nothing
return (SshAuthPublicKey pubKeyAlg pubKey sig)
"password" ->
do hasNewPassword <- getBoolean
oldPassword <- getString
newPassword <- if hasNewPassword
then fmap Just getString
else return Nothing
return (SshAuthPassword oldPassword newPassword)
"hostbased" ->
do hostKeyAlg <- getString
hostKey <- getString
hostname <- getString
username <- getString
signature <- getString
return
(SshAuthHostBased hostKeyAlg hostKey hostname username signature)
"none" ->
return SshAuthNone
_ ->
fail ("Unknown auth method: " ++ S.unpack tag)
getUserAuthFailure :: Get SshMsg
getUserAuthFailure =
do methods <- getNameList
partialSuccess <- getBoolean
return (SshMsgUserAuthFailure methods partialSuccess)
getUserAuthPkOk :: Get SshMsg
getUserAuthPkOk =
do keyAlg <- getString
keyLen <- getWord32be
key <- isolate (fromIntegral keyLen) getSshPubCert
return (SshMsgUserAuthPkOk keyAlg key)
getSessionId :: Get SshSessionId
getSessionId = fmap SshSessionId getString
getChannelOpen :: Get SshMsg
getChannelOpen =
do channelTypeTag <- getChannelTypeTag
senderChannel <- getWord32be
initialWindowSize <- getWord32be
maximumPacketSize <- getWord32be
ty <- case channelTypeTag of
SshChannelTypeTagSession ->
return SshChannelTypeSession
SshChannelTypeTagX11 ->
do address <- getString
port <- getWord32be
return (SshChannelTypeX11 address port)
SshChannelTypeTagForwardedTcpIp ->
do address1 <- getString
port1 <- getWord32be
address2 <- getString
port2 <- getWord32be
return (SshChannelTypeForwardedTcpIp address1 port1 address2 port2)
SshChannelTypeTagDirectTcpIp ->
do address1 <- getString
port1 <- getWord32be
address2 <- getString
port2 <- getWord32be
return (SshChannelTypeDirectTcpIp address1 port1 address2 port2)
return (SshMsgChannelOpen ty senderChannel initialWindowSize maximumPacketSize)
getChannelTypeTag :: Get SshChannelTypeTag
getChannelTypeTag =
do t <- getString
case t of
"session" -> return SshChannelTypeTagSession
"x11" -> return SshChannelTypeTagX11
"forwarded-tcpip" -> return SshChannelTypeTagForwardedTcpIp
"direct-tcpip" -> return SshChannelTypeTagDirectTcpIp
_ -> fail ("Unknown channel type: " ++ S.unpack t)
getChannelRequestTag :: Get SshChannelRequestTag
getChannelRequestTag =
do tag <- getString
case tag of
"pty-req" -> return SshChannelRequestTagPtyReq
"x11-req" -> return SshChannelRequestTagX11Req
"env" -> return SshChannelRequestTagEnv
"shell" -> return SshChannelRequestTagShell
"exec" -> return SshChannelRequestTagExec
"subsystem" -> return SshChannelRequestTagSubsystem
"window-change" -> return SshChannelRequestTagWindowChange
"xon-xoff" -> return SshChannelRequestTagXonXoff
"signal" -> return SshChannelRequestTagSignal
"exit-status" -> return SshChannelRequestTagExitStatus
"exit-signal" -> return SshChannelRequestTagExitSignal
_ -> fail ("Unknown request tag: " ++ S.unpack tag)
getWindowSize :: Get SshWindowSize
getWindowSize =
SshWindowSize <$> getWord32be <*> getWord32be <*> getWord32be <*> getWord32be
getChannelRequest :: Get SshMsg
getChannelRequest =
do recipientChannel <- getWord32be
requestTag <- getChannelRequestTag
wantReply <- getBoolean
request <- case requestTag of
SshChannelRequestTagPtyReq ->
SshChannelRequestPtyReq <$> getString <*> getWindowSize <*> getString
SshChannelRequestTagEnv ->
do name <- getString
value <- getString
return (SshChannelRequestEnv name value)
SshChannelRequestTagShell ->
return SshChannelRequestShell
SshChannelRequestTagExec ->
SshChannelRequestExec <$> getString
SshChannelRequestTagSubsystem ->
SshChannelRequestSubsystem <$> getString
SshChannelRequestTagWindowChange ->
SshChannelRequestWindowChange <$> getWindowSize
_ -> fail ("Unsupported request: " ++ show requestTag )
return (SshMsgChannelRequest request recipientChannel wantReply)
getOpenFailure :: Get SshOpenFailure
getOpenFailure =
do code <- getWord32be
case codeToOpenFailure code of
Just tag -> return tag
Nothing -> fail "Unknown Channel Open Failure type"
getRemaining :: Get S.ByteString
getRemaining = getBytes =<< remaining
|
glguy/ssh-hans
|
src/Network/SSH/Messages.hs
|
bsd-3-clause
| 38,360 | 0 | 20 | 11,136 | 7,664 | 3,656 | 4,008 | 1,022 | 30 |
-- Copyright (c) 2016 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-}
-- | This module contains code that converts FlatIR types into LLVM types.
module IR.FlatIR.LLVMGen.Types(
toLLVMType,
genTypeDefs
) where
import Control.Monad.Trans
import Control.Monad.LLVMGen.Metadata.Debug.Class
import Data.Array
import Data.Graph.Inductive.Graph
import IR.Common.Ptr
import IR.FlatIR.Syntax
import qualified Data.ByteString.UTF8 as Strict
import qualified LLVM.AST as LLVM
import qualified LLVM.AST.AddrSpace as LLVM
import qualified LLVM.AST.Type as LLVM
-- | Generate the LLVM type for a given Flat IR type.
toLLVMType :: Graph gr =>
Module tagty typedesc gr
-- ^ The FlatIR module being translated
-> Type tagty
-- ^ The FlatIR type to translate.
-> LLVM.Type
-- ^ The corresponding LLVM type
toLLVMType m FuncType { funcTyRetTy = retty, funcTyArgTys = argtys } =
let
retty' = toLLVMType m retty
argtys' = map (toLLVMType m) argtys
in
LLVM.FunctionType { LLVM.resultType = retty', LLVM.argumentTypes = argtys',
LLVM.isVarArg = False }
toLLVMType _ VariantType {} = error "Variants aren't supported yet"
toLLVMType m StructType { structPacked = packed, structFields = fields } =
let
fieldtys = map (\FieldDef { fieldDefTy = ty } -> toLLVMType m ty)
(elems fields)
in
LLVM.StructureType { LLVM.elementTypes = fieldtys, LLVM.isPacked = packed }
toLLVMType m ArrayType { arrayLen = Just arrlen, arrayElemTy = inner } =
let
inner' = toLLVMType m inner
in
LLVM.ArrayType { LLVM.nArrayElements = fromIntegral arrlen,
LLVM.elementType = inner' }
toLLVMType m ArrayType { arrayLen = Nothing, arrayElemTy = inner } =
let
inner' = toLLVMType m inner
in
LLVM.ArrayType { LLVM.elementType = inner', LLVM.nArrayElements = 0 }
toLLVMType m PtrType { ptrTy = Native { nativeTy = inner } } =
let
inner' = toLLVMType m inner
in
LLVM.PointerType { LLVM.pointerReferent = inner',
LLVM.pointerAddrSpace = LLVM.AddrSpace 0 }
toLLVMType Module { modTypes = types, modTags = tags }
PtrType { ptrTy = Tagged { taggedTag = tagid } } =
let
TagDesc { tagDescTy = tname } = tags ! tagid
innerty' = case types ! tname of
Anon {} -> LLVM.UnName $! fromIntegral $! fromEnum tagid
Name { nameStr = bstr } -> LLVM.Name (Strict.toString bstr)
TypeDef { typeDefStr = bstr } -> LLVM.Name (Strict.toString bstr)
in
LLVM.PointerType { LLVM.pointerReferent = LLVM.NamedTypeReference $!
innerty',
LLVM.pointerAddrSpace = LLVM.AddrSpace 0 }
toLLVMType Module { modTypes = types } IdType { idName = tyid } =
let
tyname = case types ! tyid of
Anon {} -> LLVM.UnName $! fromIntegral $! fromEnum tyid
Name { nameStr = bstr } -> LLVM.Name (Strict.toString bstr)
TypeDef { typeDefStr = bstr } -> LLVM.Name (Strict.toString bstr)
in
LLVM.NamedTypeReference $! tyname
-- Int and float types are a straightaway conversion
toLLVMType _ IntType { intSize = 1 } = LLVM.i1
toLLVMType _ IntType { intSize = 8 } = LLVM.i8
toLLVMType _ IntType { intSize = 16 } = LLVM.i16
toLLVMType _ IntType { intSize = 32 } = LLVM.i32
toLLVMType _ IntType { intSize = 64 } = LLVM.i64
toLLVMType _ IntType { intSize = intsize } =
LLVM.IntegerType { LLVM.typeBits = fromIntegral intsize }
toLLVMType _ FloatType { floatSize = 16 } = LLVM.half
toLLVMType _ FloatType { floatSize = 32 } = LLVM.float
toLLVMType _ FloatType { floatSize = 64 } = LLVM.double
toLLVMType _ FloatType { floatSize = 80 } = LLVM.x86_fp80
toLLVMType _ FloatType { floatSize = 128 } = LLVM.fp128
toLLVMType _ FloatType { floatSize = n } =
error ("Cannot generate floating point type with " ++ show n ++ " bits")
toLLVMType _ UnitType {} = LLVM.StructureType { LLVM.elementTypes = [],
LLVM.isPacked = False }
-- | Generate the LLVM type for a given Flat IR type.
genTypeDefs :: (MonadIO m, MonadDebugMetadata m, Graph gr) =>
Module tagty typedesc gr
-- ^ The FlatIR module being translated
-> m [LLVM.Definition]
-- ^ The corresponding LLVM type
genTypeDefs m @ Module { modTypes = types } =
let
-- Anonymous definitions get a nameless entry
mapfun (tyid, Anon { anonTy = ty }) =
--genTypeDefMD tyid tydef
return $! LLVM.TypeDefinition (LLVM.UnName $! fromIntegral $!
fromEnum tyid)
(Just $! toLLVMType m ty)
-- Name-only definitions get an empty type definition
mapfun (tyid, tydef @ Name { nameStr = bstr }) =
do
genTypeDefMD tyid tydef
return $! LLVM.TypeDefinition (LLVM.Name (Strict.toString bstr)) Nothing
-- Named definitions get both
mapfun (tyid, tydef @ TypeDef { typeDefStr = bstr, typeDefTy = ty }) =
do
genTypeDefMD tyid tydef
return $! LLVM.TypeDefinition (LLVM.Name (Strict.toString bstr))
(Just $! toLLVMType m ty)
in
mapM mapfun (assocs types)
|
emc2/chill
|
src/IR/FlatIR/LLVMGen/Types.hs
|
bsd-3-clause
| 6,777 | 3 | 18 | 1,679 | 1,488 | 807 | 681 | 97 | 5 |
module Main where
import Control.Monad.Trans
import System.Console.Haskeline
import Check
import Eval
import Parser
import Pretty
import Syntax
main :: IO ()
main = runInputT defaultSettings loop
where
loop = do
minput <- getInputLine "Untyped> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just val -> (liftIO $ process val) >> loop
process :: String -> IO ()
process line =
case parseExpr line of
Left err -> print err
Right expr ->
case checkTop [] expr of
Left err -> print err
Right t -> do
putStrLn $ ppexpr t
-- Evaluate the expression
let (v, steps) = runEval expr
--mapM_ showStep steps
putStrLn $ ppexpr v
showStep :: (Int, Expr) -> IO ()
showStep (d, x) = putStrLn $ (replicate d ' ') ++ "=> " ++ ppexpr x
|
zanesterling/haskell-compiler
|
src/Main.hs
|
bsd-3-clause
| 836 | 0 | 16 | 244 | 287 | 143 | 144 | 28 | 3 |
{-# LANGUAGE FlexibleInstances #-}
module Text.CSS.ArbitraryCSS where
import Test.QuickCheck
import Test.QuickCheck.Gen
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.List (intersperse)
import Text.Regex
import Text.Regex.Posix
data CSSString a = CSSString a String
data NewLine = NewLine
-- | A string of one or more space characters.
data Spaces = Spaces
-- | A string of 0 or 1 Spaces.
data WhiteSpace = WhiteSpace
-- | A number like 42, 4.2 or .42
data Number = Number
-- | A comment is any character sequence which start with /* and ends with */
data Comment = Comment
-- | A unicode digit begins with \\ and then contains up to 6 hex
-- digits. If there are less that 6 hex digits then a whitespace
-- character must be added to the end.
data Unicode = Unicode
-- | A nonascii character is a character in the range \o240 - \o4177777
data Nonascii = Nonascii
-- | An escape is either a unicode character or a backslash followed
-- | by anthing but \r, \n, \f or a hex digit.
data Escape = Escape
-- | A name character is a digit, letter, underscore, dash, nonascii
-- | or escape.
data NameChar = NameChar
digitChar = ['0'..'9']
hexChar = digitChar ++ ['a'..'f'] ++ ['A'..'F']
letterChar = ['a'..'z'] ++ ['A'..'Z']
spaceChar = " \t\r\n\f"
anyChar = letterChar ++ digitChar ++ spaceChar ++
"~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/"
newLineChar = [ "\r\n", "\n", "\r", "\f"]
escapeChar = filter (`notElem` ("\r\n\f" ++ hexChar)) anyChar
digits :: Gen String
digits = listOf1 $ elements digitChar
hexDigits :: Gen String
hexDigits = listOf1 $ elements hexChar
instance Show (CSSString a) where
show (CSSString _ x) = x
instance Arbitrary (CSSString NewLine) where
arbitrary = do x <- elements newLineChar
return $ CSSString NewLine x
instance Arbitrary (CSSString Spaces) where
arbitrary = do x <- listOf1 $ elements spaceChar
return $ CSSString Spaces x
-- | Note the difference between this and the above is that here you
-- may have an empty string.
instance Arbitrary (CSSString WhiteSpace) where
arbitrary = do x <- listOf $ elements spaceChar
return $ CSSString WhiteSpace x
instance Arbitrary (CSSString Number) where
arbitrary = do n <- choose (1,3) :: Gen Int
case n of
1 -> do x <- digits
return $ CSSString Number x
2 -> do a <- digits
b <- digits
return $ CSSString Number $ a ++ "." ++ b
3 -> do a <- digits
return $ CSSString Number $ "." ++ a
instance Arbitrary (CSSString Comment) where
arbitrary = do x <- listOf $ elements anyChar
let c = concat $ splitRegex (mkRegex "[*]/") x
return $ CSSString Comment $ ("/*" ++ c ++ "*/")
instance Arbitrary (CSSString Unicode) where
arbitrary = do x <- hexDigits
let x' = take 6 x
if (length x') < 6
then do s <- elements (newLineChar ++ [" "])
return $ CSSString Unicode ("\\" ++ x' ++ s)
else return $ CSSString Unicode ("\\" ++ x')
instance Arbitrary (CSSString Nonascii) where
arbitrary = do x <- elements ['\o240'..'\o4177777']
return $ CSSString Nonascii [x]
instance Arbitrary (CSSString Escape) where
arbitrary = do n <- choose (1,2) :: Gen Int
case n of
1 -> do x <- arbitrary :: Gen (CSSString Unicode)
return $ CSSString Escape $ show x
2 -> do x <- elements escapeChar
return $ CSSString Escape ("\\" ++ [x])
instance Arbitrary (CSSString NameChar) where
arbitrary = do n <- choose (1,3) :: Gen Int
case n of
1 -> do x <- elements (letterChar ++ "_-")
return $ CSSString NameChar [x]
2 -> do x <- arbitrary :: Gen (CSSString Nonascii)
return $ CSSString NameChar $ show x
3 -> do x <- arbitrary :: Gen (CSSString Unicode)
return $ CSSString NameChar $ show x
|
brentonashworth/css-parser
|
test/Text/CSS/ArbitraryCSS.hs
|
bsd-3-clause
| 4,289 | 0 | 17 | 1,363 | 1,149 | 584 | 565 | 81 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Web.RTBBidder.Types.Request.Audio (Audio(..)) where
import qualified Data.Aeson as AESON
import Data.Aeson ((.=), (.:), (.:?), (.!=))
import qualified Data.Text as TX
import Web.RTBBidder.Types.Request.Banner (Banner(..))
data Audio = Audio
{ audioMimes :: [TX.Text]
, audioMinduration :: Maybe Int
, audioMaxduration :: Maybe Int
, audioProtocols :: Maybe Int
, audioStartdelay :: Maybe Int
, audioSequence :: Maybe Int
, audioBattr :: [Int]
, audioMaxextended :: Maybe Int
, audioMinbitrate :: Maybe Int
, audioMaxbitrate :: Maybe Int
, audioDelivery :: [Int]
, audioCompanionad :: [Banner]
, audioApi :: [Int]
, audioCompaniontype :: [Int]
, audioMaxseq :: Maybe Int
, audioFeed :: Maybe Int
, audioStitched :: Maybe Int
, audioNvol :: Maybe Int
, audioExt :: Maybe AESON.Value
} deriving (Show, Eq)
instance AESON.FromJSON Audio where
parseJSON = AESON.withObject "audio" $ \o -> do
audioMimes <- o .: "mimes"
audioMinduration <- o .:? "minduration"
audioMaxduration <- o .:? "maxduration"
audioProtocols <- o .:? "protocols"
audioStartdelay <- o .:? "startdelay"
audioSequence <- o .:? "sequence"
audioBattr <- o .:? "battr" .!= []
audioMaxextended <- o .:? "maxextended"
audioMinbitrate <- o .:? "minbitrate"
audioMaxbitrate <- o .:? "maxbitrate"
audioDelivery <- o .:? "delivery" .!= []
audioCompanionad <- o .:? "companionad" .!= []
audioApi <- o .:? "api" .!= []
audioCompaniontype <- o .:? "companiontype" .!= []
audioMaxseq <- o .:? "maxseq"
audioFeed <- o .:? "feed"
audioStitched <- o .:? "stitched"
audioNvol <- o .:? "nvol"
audioExt <- o .:? "ext"
return Audio{..}
instance AESON.ToJSON Audio where
toJSON Audio{..} = AESON.object
[ "mimes" .= audioMimes
, "minduration" .= audioMinduration
, "maxduration" .= audioMaxduration
, "protocols" .= audioProtocols
, "startdelay" .= audioStartdelay
, "sequence" .= audioSequence
, "battr" .= audioBattr
, "maxextended" .= audioMaxextended
, "minbitrate" .= audioMinbitrate
, "maxbitrate" .= audioMaxbitrate
, "delivery" .= audioDelivery
, "companionad" .= audioCompanionad
, "api" .= audioApi
, "companiontype" .= audioCompaniontype
, "maxseq" .= audioMaxseq
, "feed" .= audioFeed
, "stitched" .= audioStitched
, "nvol" .= audioNvol
, "ext" .= audioExt
]
|
hiratara/hs-rtb-bidder
|
src/Web/RTBBidder/Types/Request/Audio.hs
|
bsd-3-clause
| 2,500 | 0 | 12 | 543 | 716 | 393 | 323 | 71 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Temperature.FR.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Temperature.Helpers
import Duckling.Temperature.Types (TemperatureData (..))
import qualified Duckling.Temperature.Types as TTemperature
import Duckling.Types
ruleLatentTempDegrees :: Rule
ruleLatentTempDegrees = Rule
{ name = "<latent temp> degrees"
, pattern =
[ dimension Temperature
, regex "(deg(r(\x00e9|e|\x00e8))?s?\\.?)|\x00b0"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Degree td
_ -> Nothing
}
ruleTempCelsius :: Rule
ruleTempCelsius = Rule
{ name = "<temp> Celsius"
, pattern =
[ dimension Temperature
, regex "c(el[cs]?(ius)?)?\\.?"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Celsius td
_ -> Nothing
}
ruleTempFahrenheit :: Rule
ruleTempFahrenheit = Rule
{ name = "<temp> Fahrenheit"
, pattern =
[ dimension Temperature
, regex "f(ah?reh?n(h?eit)?)?\\.?"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Fahrenheit td
_ -> Nothing
}
ruleLatentTempEnDessousDeZero :: Rule
ruleLatentTempEnDessousDeZero = Rule
{ name = "<latent temp> en dessous de zero"
, pattern =
[ dimension Temperature
, regex "en dessous de (0|z(\x00e9|e)ro)"
]
, prod = \tokens -> case tokens of
(Token Temperature td@(TemperatureData {TTemperature.value = v}):_) ->
case TTemperature.unit td of
Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $
td {TTemperature.value = - v}
_ -> Just . Token Temperature $ td {TTemperature.value = - v}
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleLatentTempDegrees
, ruleLatentTempEnDessousDeZero
, ruleTempCelsius
, ruleTempFahrenheit
]
|
rfranek/duckling
|
Duckling/Temperature/FR/Rules.hs
|
bsd-3-clause
| 2,393 | 0 | 18 | 528 | 542 | 306 | 236 | 60 | 3 |
module Lib
( module Client
, module Server
) where
import Client
import Server
|
stormont/async-examples
|
ping-pong/src/Lib.hs
|
bsd-3-clause
| 92 | 0 | 4 | 27 | 20 | 14 | 6 | 5 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty as W
import qualified HtmlGen as H
import Lucid.Base as L
import SqlTable (getRandItem)
import qualified SqlTable as S
import Control.Monad.IO.Class
import Database.SQLite.Simple
import Data.Maybe (fromJust)
import Network.Wai.Middleware.Static
import System.Environment
import Control.Monad (liftM)
numItems :: Int
numItems = 3
lucid :: Html () -> ActionM ()
lucid = W.html . L.renderText
main :: IO ()
main = do
port <- liftM read $ getEnv "PORT"
scotty port $ do
middleware $ staticPolicy (noDots >-> addBase "static")
get "/" $ do
conn <- liftIO $ open S.tblname
items <- liftIO $ S.getRandItems conn 3
let contents = fmap (L.toHtml . S.content . fromJust) items
lucid $ H.render contents
get "/color-script.js" $ file "color-script.js"
|
arcticmatt/happy-site
|
src/Main.hs
|
bsd-3-clause
| 857 | 0 | 20 | 166 | 286 | 151 | 135 | 28 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.AmountOfMoney.ZH.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.AmountOfMoney.ZH.Corpus
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "ZH Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/AmountOfMoney/ZH/Tests.hs
|
bsd-3-clause
| 522 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
module GUI.ItemEditor where
import Bucket.EditItem
import Bucket.Types
import Control.Monad
import Data.IORef
import Data.List
import Data.Maybe
import Graphics.UI.Gtk
import GUI.ItemsTreeModel
handleEditButtonClicked itemEditor treeView model tagsText titleText currentBucketRef updateItemList = do
(treePath, _) <- treeViewGetCursor treeView
maybeItem <- getItem treeView model treePath
when (isJust maybeItem) $ do
let item = fromJust maybeItem
entrySetText tagsText (tagsToString (tags item))
entrySetText titleText (title item)
response <- dialogRun itemEditor
when (response == ResponseOk) $ do
currentBucket <- readIORef currentBucketRef
tagsText <- entryGetText tagsText
titleText <- entryGetText titleText
let newItem = setTags (stringToTags tagsText) $
setTitle titleText
item
-- TODO: show error dialog if we can't save item
newBucket <- editItem currentBucket item newItem
writeIORef currentBucketRef newBucket
updateItemList
widgetHide itemEditor
tagsToString :: [String] -> String
tagsToString = intercalate ","
stringToTags :: String -> [String]
stringToTags = getTags
where
getTags "" = []
getTags s = takeWhile notComma s : getTags (drop 1 (dropWhile notComma s))
notComma ',' = False
notComma _ = True
|
rickardlindberg/orgapp
|
src/GUI/ItemEditor.hs
|
bsd-3-clause
| 1,468 | 0 | 19 | 404 | 376 | 181 | 195 | 36 | 3 |
module Data.JSON.Schema
( module Data.JSON.Schema.Generic
, module Data.JSON.Schema.Types
, Proxy (..)
) where
import Data.JSON.Schema.Generic
import Data.JSON.Schema.Types
import Data.Proxy.Compat
|
silkapp/json-schema
|
src/Data/JSON/Schema.hs
|
bsd-3-clause
| 207 | 0 | 5 | 28 | 52 | 37 | 15 | 7 | 0 |
module Main where
import Prelude hiding (length, concat)
import Control.Applicative ((<$>))
import Control.Exception (throwIO)
import Data.ByteString (ByteString, length, unpack, pack, concat)
import Data.Bits ((.|.))
import Data.Map (fromList, empty)
import Data.Char (ord)
import System.Linux.Netlink.Internal
main = do
sock <- makeSocket
let flags = foldr (.|.) 0 [fNLM_F_REQUEST]
header = Header eRTM_GETLINK flags 42 0
message = LinkMsg 0 2 0
attrs = empty
iface <- queryOne sock (Packet header message attrs)
print (packetMessage iface)
let attrs = packetAttributes iface
print $ getLinkAddress attrs
print $ getLinkBroadcast attrs
print $ getLinkName attrs
print $ getLinkMTU attrs
print $ getLinkQDisc attrs
print $ getLinkTXQLen attrs
dumpNumeric :: ByteString -> IO ()
dumpNumeric b = print $ unpack b
|
metachord/netlink-hs
|
bin/Test.hs
|
bsd-3-clause
| 891 | 0 | 11 | 194 | 301 | 157 | 144 | 26 | 1 |
module MutablePairs.Data where
import Control.Monad.Trans.State.Lazy
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
type Try = Either String
type Environment = M.Map String DenotedValue
empty :: Environment
empty = M.empty
initEnvironment :: [(String, DenotedValue)] -> Environment
initEnvironment = M.fromList
extend :: String -> DenotedValue -> Environment -> Environment
extend = M.insert
extendRec :: String -> [String] -> Expression -> Environment
-> StatedTry Environment
extendRec name params body = extendRecMany [(name, params, body)]
extendRecMany :: [(String, [String], Expression)] -> Environment
-> StatedTry Environment
extendRecMany lst env = do
refs <- allocMany (length lst)
let denoVals = fmap DenoRef refs
let names = fmap (\(n, _, _) -> n) lst
let newEnv = extendMany (zip names denoVals) env
extendRecMany' lst refs newEnv
where
extendRecMany' [] [] env = return env
extendRecMany' ((name, params, body):triples) (ref:refs) env = do
setRef ref (ExprProc $ Procedure params body env)
extendRecMany' triples refs env
allocMany 0 = return []
allocMany x = do
ref <- newRef (ExprBool False) -- dummy value false for allocating space
(ref:) <$> allocMany (x - 1)
apply :: Environment -> String -> Maybe DenotedValue
apply = flip M.lookup
extendMany :: [(String, DenotedValue)] -> Environment -> Environment
extendMany = flip (foldl func)
where
func env (var, val) = extend var val env
applyForce :: Environment -> String -> DenotedValue
applyForce env var = fromMaybe
(error $ "Var " `mappend` var `mappend` " is not in environment!")
(apply env var)
newtype Ref = Ref { addr::Integer } deriving(Show, Eq)
newtype Store = Store { refs::[ExpressedValue] } deriving(Show)
type StatedTry = StateT Store (Either String)
throwError :: String -> StatedTry a
throwError msg = StateT (\s -> Left msg)
initStore :: Store
initStore = Store []
newRef :: ExpressedValue -> StatedTry Ref
newRef val = do
store <- get
let refList = refs store
put $ Store (val:refList)
return . Ref . toInteger . length $ refList
deRef :: Ref -> StatedTry ExpressedValue
deRef (Ref r) = do
store <- get
let refList = refs store
findVal r (reverse refList)
where
findVal 0 (x:_) = return x
findVal 0 [] = throwError "Index out of bound when calling deref!"
findVal i (_:xs) = findVal (i - 1) xs
setRef :: Ref -> ExpressedValue -> StatedTry ()
setRef ref val = do
store <- get
let refList = refs store
let i = addr ref
newList <- reverse <$> setRefVal i (reverse refList) val
put $ Store newList
return ()
where
setRefVal _ [] _ = throwError "Index out of bound when calling setref!"
setRefVal 0 (_:xs) val = return (val:xs)
setRefVal i (x:xs) val = (x:) <$> setRefVal (i - 1) xs val
data Program = Prog Expression
deriving (Show, Eq)
data Expression =
ConstExpr ExpressedValue
| VarExpr String
| LetExpr [(String, Expression)] Expression
| BinOpExpr BinOp Expression Expression
| UnaryOpExpr UnaryOp Expression
| CondExpr [(Expression, Expression)]
| ProcExpr [String] Expression
| CallExpr Expression [Expression]
| LetRecExpr [(String, [String], Expression)] Expression
| BeginExpr [Expression]
| AssignExpr String Expression
| SetDynamicExpr String Expression Expression
| NewPairExpr Expression Expression
| GetLeftExpr Expression
| GetRightExpr Expression
| SetLeftExpr Expression Expression
| SetRightExpr Expression Expression
deriving(Show, Eq)
data BinOp =
Add | Sub | Mul | Div | Gt | Le | Eq
deriving(Show, Eq)
data UnaryOp = Minus | IsZero
deriving(Show, Eq)
data Procedure = Procedure [String] Expression Environment
instance Show Procedure where
show _ = "<procedure>"
data ExpressedValue = ExprNum Integer
| ExprBool Bool
| ExprProc Procedure
| ExprPair MutPair
instance Show ExpressedValue where
show (ExprNum i) = show i
show (ExprBool b) = show b
show (ExprPair p) = show p
show (ExprProc p) = show p
instance Eq ExpressedValue where
(ExprNum i1) == (ExprNum i2) = i1 == i2
(ExprBool b1) == (ExprBool b2) = b1 == b2
(ExprPair p1) == (ExprPair p2) = p1 == p2
_ == _ = False
data DenotedValue = DenoRef Ref
instance Show DenotedValue where
show (DenoRef v) = show v
instance Eq DenotedValue where
DenoRef v1 == DenoRef v2 = v1 == v2
data MutPair = MutPair Ref Ref deriving(Show, Eq)
makePair :: ExpressedValue -> ExpressedValue -> StatedTry MutPair
makePair lVal rVal = do
lRef <- newRef lVal
rRef <- newRef rVal
return $ MutPair lRef rRef
getLeft :: MutPair -> StatedTry ExpressedValue
getLeft (MutPair lRef _) = deRef lRef
getRight :: MutPair -> StatedTry ExpressedValue
getRight (MutPair _ rRef) = deRef rRef
setLeft :: MutPair -> ExpressedValue -> StatedTry ()
setLeft (MutPair lRef _) = setRef lRef
setRight :: MutPair -> ExpressedValue -> StatedTry ()
setRight (MutPair _ rRef) = setRef rRef
|
li-zhirui/EoplLangs
|
src/MutablePairs/Data.hs
|
bsd-3-clause
| 5,097 | 0 | 13 | 1,141 | 1,851 | 958 | 893 | 134 | 3 |
{-|
Module : Data.Number.MPFR.Conversion
Description : wrappers for conversion functions
Copyright : (c) Aleš Bizjak
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
Conversion from basic MPFR back to basic Haskell types.
See <http://www.mpfr.org/mpfr-current/mpfr.html#Conversion-Functions> for
documentation on particular functions.
-}
{-# INCLUDE <mpfr.h> #-}
{-# INCLUDE <chsmpfr.h> #-}
module Data.Number.MPFR.Conversion where
import Data.Number.MPFR.Internal
import Data.Number.MPFR.Comparison(isZero)
import Data.Number.MPFR.Misc
import Data.List (isInfixOf)
toDouble :: RoundMode -> MPFR -> Double
toDouble r mp1 = (realToFrac . unsafePerformIO) go
where go = with mp1 $ \p -> mpfr_get_d p ((fromIntegral . fromEnum) r)
toDouble2exp :: RoundMode -> MPFR -> (Double, Int)
toDouble2exp r mp1 = unsafePerformIO go
where go = with mp1 $ \p1 ->
alloca $ \p2 -> do
r1 <- mpfr_get_d_2exp p2 p1 ((fromIntegral . fromEnum) r)
r2 <- peek p2
return (realToFrac r1, fromIntegral r2)
toInt :: RoundMode -> MPFR -> Int
toInt r mp1 = (fromIntegral . unsafePerformIO) go
where go = with mp1 $ \p -> mpfr_get_si p ((fromIntegral . fromEnum) r)
toWord :: RoundMode -> MPFR -> Word
toWord r mp1 = (fromIntegral . unsafePerformIO) go
where go = with mp1 $ \p -> mpfr_get_ui p ((fromIntegral . fromEnum) r)
mpfrToString :: RoundMode
-> Word -- ^ number of decimals
-> Word -- ^ base
-> MPFR -> (String, Exp)
mpfrToString r n b mp1 = unsafePerformIO go
where go = with mp1 $ \p1 ->
alloca $ \p2 -> do
p3 <- mpfr_get_str nullPtr p2 (fromIntegral b) (fromIntegral n) p1 ((fromIntegral . fromEnum) r)
r1 <- peekCString p3
r2 <- peek p2
mpfr_free_str p3
return (r1, r2)
fitsULong :: RoundMode -> MPFR -> Bool
fitsULong r d = withMPFRF d r mpfr_fits_ulong_p /= 0
fitsSLong :: RoundMode -> MPFR -> Bool
fitsSLong r d = withMPFRF d r mpfr_fits_slong_p /= 0
fitsUInt :: RoundMode -> MPFR -> Bool
fitsUInt r d = withMPFRF d r mpfr_fits_uint_p /= 0
fitsSInt :: RoundMode -> MPFR -> Bool
fitsSInt r d = withMPFRF d r mpfr_fits_sint_p /= 0
fitsUShort :: RoundMode -> MPFR -> Bool
fitsUShort r d = withMPFRF d r mpfr_fits_ushort_p /= 0
fitsSShort :: RoundMode -> MPFR -> Bool
fitsSShort r d = withMPFRF d r mpfr_fits_sshort_p /= 0
-- TODO
decompose :: MPFR -> (Integer, Exp)
decompose d@(MP p _ e _) | e == expInf = error "Don't know how to decompose Infinity"
| e == expNaN = error "Don't know how to decompose NaN"
| e == expZero = (0, 0)
| otherwise = (dm, e - sh)
where dm = getMantissa d
sh = fromIntegral (Prelude.ceiling (fromIntegral p / fromIntegral bitsPerMPLimb :: Double) * bitsPerMPLimb)
-- | Output a string in base 10 rounded to Near in exponential form.
toStringExp :: Word -- ^ number of digits
-> MPFR -> String
toStringExp dec d | isInfixOf "NaN" ss = "NaN"
| isInfixOf "Inf" ss = s ++ "Infinity"
| isZero d = "0"
| e > 0 =
s ++ if Prelude.floor prec <= dec
then
take e ss ++
let bt = backtrim (drop e ss)
in if null bt
then ""
else '.' : bt
else head ss : '.' :
let bt = (backtrim . tail) ss
in (if null bt then "0" else bt)
++ "e" ++ show (pred e)
| otherwise =
s ++ (head ss : '.' :
(let bt = (backtrim . tail) ss in
if null bt then "0"
else bt )
++ "e" ++ show (pred e))
where (str, e') = mpfrToString Near n 10 d
e = fromIntegral e'
n = max dec 5
(s, ss) = case head str of
'-' -> ("-", tail str)
_ -> ("" , str)
backtrim = reverse . dropWhile (== '0') . reverse
prec = logBase 10 2 * fromIntegral (getExp d) :: Double
-- | Output a string in base 10 rounded to Near. The difference from @toStringExp@ is that
-- it won't output in exponential form if it is sensible to do so.
toString :: Word -> MPFR -> String
toString dec d | isInfixOf "NaN" ss = "NaN"
| isInfixOf "Inf" ss = s ++ "Infinity"
| otherwise =
s ++ case compare 0 e of
LT -> take e ss ++
(let bt = all (== '0') (drop e ss)
in if bt then "" else '.' : drop e ss)
++ (if fromIntegral n - e < 0
then 'e' : show (e - fromIntegral n)
else "")
GT -> let ee = fromIntegral dec + e in
if ee <= 0 then "0" else
head ss : '.' : (backtrim . tail . take ee) ss
++ "e" ++ show (pred e)
EQ -> "0." ++ let bt = all (== '0') ss
in if bt then "0" else ss
where (str, e') = mpfrToString Near n 10 d
n = max dec 5
e = fromIntegral e'
(s, ss) = case head str of
'-' -> ("-", tail str)
_ -> ("" , str)
backtrim = reverse . dropWhile (== '0') . reverse
instance Show MPFR where
show = toStringExp 16
|
ekmett/hmpfr
|
src/Data/Number/MPFR/Conversion.hs
|
bsd-3-clause
| 6,465 | 0 | 19 | 2,916 | 1,730 | 879 | 851 | 108 | 8 |
module Main where
import Lib
main :: IO ()
main = someFunc
{-99 Haskell Problems-}
{-| Get the last element of a list-}
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
{-| Get the second to last element of a list-}
myButtLast :: [a] -> a
myButtLast [x, _] = x
myButtLast (_:xs) = myButtLast xs
{-| Get the kth element of a list-}
elementAt :: [a] -> Int -> a
elementAt (x:_) 0 = x
elementAt (_:xs) k = elementAt xs (k - 1)
{-| Get the length of a list-}
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + (myLength xs)
{-| Reverse a list-}
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
{-| Checks if list is a palindrome.-}
myPalindrome :: (Eq a) => [a] -> Bool
myPalindrome x
| x == (reverse x) = True
| otherwise = False
{-| Remove dupes in list-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress (x:xs) = [x] ++ compress (clean x xs)
where clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Put duplicates in sublists-}
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack [x] = [[x]]
pack (x:xs) = combine x xs ++ pack (clean x xs)
where
combine _ [] = []
combine x s = [[z | z <- x:s, z == x]]
clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Does stuff-}
encode :: (Eq a) => [a] -> [(Int, a)]
encode [] = []
encode s = map (\(x:xs) -> (length (x:xs), x)) (pack s)
data List a = Single a | Multiple Int a
deriving Show
{-| Similar to before-}
encodeModified :: (Eq a) => [a] -> [List a]
encodeModified s = map f (encode s)
where f (1, x) = Single x
f (n, x) = Multiple n x
decode :: [List a] -> [a]
decode s = foldr (++) [] (map f s)
where f (Single x) = [x]
f (Multiple n x) = replicate n x
encodeDirect :: (Eq a) => [a] -> [List a]
encodeDirect [] = []
encodeDirect (x:xs) = [toList (count x (x:xs)) x] ++
encodeDirect (filter (x /=) xs)
where count x s = length (filter (x==) s)
toList 1 x = Single x
toList n x = Multiple n x
dupl :: [a] -> [a]
dupl [] = []
dupl (x:xs) = [x,x] ++ dupl xs
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = replicate n x ++ repli xs n
dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery s n = foldr (++) [] (map (f n) (zip [1..] s))
where f n (m, x)
| m `mod` n == 0 = []
| otherwise = [x]
spliter :: [a] -> Int -> [[a]]
spliter [] _ = []
spliter s n = [reverse (drop ((length s) - n) (reverse s))] ++ [drop n s]
slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = []
slice s start stop = reverse (drop (((length s)) - stop) (reverse (drop (start - 1) s)))
rotate :: [a] -> Int -> [a]
rotate [] _ = []
rotate s n = slice s ((f n (length s)) + 1) (length s) ++ slice s 1 (f n (length s))
where f n m
| n > m = f (n - m) m
| n < 0 = f (m + n) m
| otherwise = n
removeAt :: [a] -> Int -> (a, [a])
removeAt s n = (elementAt (slice s (n + 1) (n + 2)) 0,
slice s 1 n ++ slice s (n+2) (length s))
insertAt :: [a] -> a -> Int -> [a]
insertAt xs x n = slice xs 1 (n-1) ++ [x] ++ slice xs n (length xs)
range :: Int -> Int -> [Int]
range n1 n2 = [n1..n2]
{-| test this later-}
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = [[]]
combinations n s = f n 1 s (map (\x -> [x]) s)
where f n1 n2 s1 s2
| n1 == n2 = s2
| otherwise = f n1 (n2 + 1) s1 [x ++ [y] |
x <- s2,
y <- s1,
y `notElem` x]
sieveEratosthenes :: Int -> [Int]
sieveEratosthenes n = f n [2..n]
where f n [] = []
f n (x:xs) = [x] ++ f n [y | y <- xs,
y 'notElem'(map (x*) [2..n])]
ads
|
MauriceIsAG/HaskellScratch
|
.stack-work/intero/intero21978WWS.hs
|
bsd-3-clause
| 3,845 | 0 | 14 | 1,191 | 2,223 | 1,171 | 1,052 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, Safe #-}
module Evalso.Cruncher.Language.Java (java) where
import Evalso.Cruncher.Language (Language (..))
java :: Language
java = Language {
_codeFilename = "EvalSO.java"
, _compileCommand = Just ["javac", "EvalSO.java"]
, _compileTimeout = Just 10
, _runCommand = ["java", "EvalSO"]
, _runTimeout = 10
, _codemirror = "java"
, _rpm = "java-devel"
, _displayName = "Java"
}
|
eval-so/cruncher
|
src/Evalso/Cruncher/Language/Java.hs
|
bsd-3-clause
| 428 | 0 | 8 | 77 | 107 | 69 | 38 | 13 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Uninterpreted.Function
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Testsuite for Data.SBV.Examples.Uninterpreted.Function
-----------------------------------------------------------------------------
module TestSuite.Uninterpreted.Function where
import Data.SBV.Examples.Uninterpreted.Function
import SBVTest
-- Test suite
testSuite :: SBVTestSuite
testSuite = mkTestSuite $ \_ -> test [
"aufunc-0" ~: assert =<< isThm thmGood
, "aufunc-1" ~: assert . not =<< isThm thmBad
]
|
Copilot-Language/sbv-for-copilot
|
SBVUnitTest/TestSuite/Uninterpreted/Function.hs
|
bsd-3-clause
| 687 | 0 | 11 | 102 | 83 | 52 | 31 | -1 | -1 |
module Utils
() where
--import Data.Hashable
--(|->) =
|
etu-fkti5301-bgu/alt-exam_automated_theorem_proving
|
src/Utils.hs
|
bsd-3-clause
| 59 | 0 | 3 | 12 | 9 | 7 | 2 | 2 | 0 |
module KnapsackFraction.Central
( KnapsackFraction
, make_fixed
, make_quiz
)
where
import KnapsackFraction.Solve ( packs )
import KnapsackFraction.Param
import Challenger.Partial
import Inter.Types
import Inter.Quiz
import Autolib.ToDoc
import Autolib.Set
import Autolib.FiniteMap
import Autolib.Reporter
import Autolib.Reporter.Set ( eq )
import Autolib.Size ( Size , size )
import Data.Typeable ( Typeable )
import Data.Ratio ( (%) )
import System.Random ( randomRIO )
-------------------------------------------------------------------------------
data KnapsackFraction = KnapsackFraction deriving ( Eq, Typeable, Show, Read )
fm_fun :: FiniteMap Objekt a -> Objekt -> a
fm_fun fm = lookupWithDefaultFM fm (error "data incomplete!?")
count :: (Objekt -> Integer) -> FiniteMap Objekt Rational -> Rational
count f = foldFM ( \ x r v -> v + r * (f x % 1) ) 0
instance OrderScore KnapsackFraction where
scoringOrder _ = None
instance Size Pack where size = const 1
instance Partial KnapsackFraction Inp Pack where
describe KnapsackFraction inp = vcat
[ text "Lösen Sie das Problem Bruchteilrucksack für die Objekte"
, nest 4 $ toDoc $ objekte inp
, text "mit den Gewichten"
, nest 4 $ toDoc $ gewichte inp
, text "und den Werten"
, nest 4 $ toDoc $ werte inp
, text "Der Rucksack hat eine Kapazität von"
, nest 4 $ toDoc $ kapazitaet inp
, text "Sie sollen auch den Gesamtwert Ihrer Packung angeben."
]
initial KnapsackFraction inp =
let packFM = listToFM $ do
(x,i) <- zip (setToList $ objekte inp) [(0::Integer)..]
return ( x , 1 % (max 1 $ mod i 3) )
in Pack (count (fm_fun $ werte inp) packFM) packFM
partial KnapsackFraction inp (Pack value packFM) = do
eq ( text "vorhandene Objekte" , objekte inp )
( text "Objekte in Ihrer Packung" , mkSet $ keysFM packFM )
inform $ text "Sind alle Bruchteile zwischen 0 und 1?"
let badFM = filterFM ( \ _ v -> or [ v < 0 , v > 1 ] ) packFM
when ( sizeFM badFM > 0 ) $ reject $ vcat
[ text "Nein. Diese Bruchteile sind nicht möglich:"
, nest 4 $ toDoc badFM
]
inform $ text "Ja."
inform $ vcat
[ text "Stimmen der von Ihnen berechnete Gesamtwert"
, nest 4 $ toDoc value
, text "und der tatsächliche Gesamtwert Ihrer Packung überein?"
]
let real_value = count (fm_fun $ werte inp) packFM
when ( value /= real_value ) $ reject $ text "Nein."
inform $ text "Ja."
total KnapsackFraction inp (Pack value packFM) = do
let weight = count (fm_fun $ gewichte inp) packFM
inform $ vcat
[ text "Überschreitet das Gesamtgewicht Ihrer Einsendung"
, nest 4 $ toDoc weight
, text "die Kapazität des Rucksacks?"
]
when ( weight > (kapazitaet inp % 1) ) $ reject $ text "Ja."
inform $ text "Nein."
inform $ text "Ist der Gesamtwert maximal?"
when ( value < optimaler_wert inp ) $ reject
$ text "Nein. Es gibt eine Packung mit höherem Wert!"
inform $ text "Ja."
make_fixed :: Make
make_fixed = direct KnapsackFraction inp0
instance Generator KnapsackFraction Param (Inp,Pack) where
generator _ conf _ = do
let os = take (anzahl conf) $ enumFrom A
let rands = sequence . replicate (anzahl conf) . randomRIO
gs <- rands $ gewicht conf
vs <- rands $ wert conf
c <- randomRIO $ kapazitaet0 conf
let gsFM = listToFM $ zip os gs
let vsFM = listToFM $ zip os vs
let ( (opt,p) : _ ) = packs os c (fm_fun gsFM) (fm_fun vsFM)
return ( Inp (mkSet os) opt c gsFM vsFM
, Pack opt (listToFM p)
)
instance Project KnapsackFraction (Inp,Pack) Inp where project _ = fst
make_quiz :: Make
make_quiz = quiz KnapsackFraction p0
|
florianpilz/autotool
|
src/KnapsackFraction/Central.hs
|
gpl-2.0
| 3,858 | 56 | 17 | 1,022 | 1,215 | 625 | 590 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Main (main) where
import Test.Tasty
import Test.AWS.Support
import Test.AWS.Support.Internal
main :: IO ()
main = defaultMain $ testGroup "Support"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
|
olorin/amazonka
|
amazonka-support/test/Main.hs
|
mpl-2.0
| 534 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
{-# LANGUAGE CPP, NondecreasingIndentation #-}
{-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
-----------------------------------------------------------------------------
--
-- GHC Driver program
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module Main (main) where
-- The official GHC API
import qualified GHC
import GHC ( -- DynFlags(..), HscTarget(..),
-- GhcMode(..), GhcLink(..),
Ghc, GhcMonad(..),
LoadHowMuch(..) )
import CmdLineParser
-- Implementations of the various modes (--show-iface, mkdependHS. etc.)
import LoadIface ( showIface )
import HscMain ( newHscEnv )
import DriverPipeline ( oneShot, compileFile )
import DriverMkDepend ( doMkDependHS )
#ifdef GHCI
import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
#endif
-- Various other random stuff that we need
import Config
import Constants
import HscTypes
import Packages ( dumpPackages )
import DriverPhases
import BasicTypes ( failed )
import StaticFlags
import DynFlags
import ErrUtils
import FastString
import Outputable
import SrcLoc
import Util
import Panic
import MonadUtils ( liftIO )
-- Imports for --abi-hash
import LoadIface ( loadUserInterface )
import Module ( mkModuleName )
import Finder ( findImportedModule, cannotFindInterface )
import TcRnMonad ( initIfaceCheck )
import Binary ( openBinMem, put_, fingerprintBinMem )
-- Standard Haskell libraries
import System.IO
import System.Environment
import System.Exit
import System.FilePath
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
-----------------------------------------------------------------------------
-- ToDo:
-- time commands when run with -v
-- user ways
-- Win32 support: proper signal handling
-- reading the package configuration file is too slow
-- -K<size>
-----------------------------------------------------------------------------
-- GHC's command-line interface
main :: IO ()
main = do
initGCStatistics -- See Note [-Bsymbolic and hooks]
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
-- 1. extract the -B flag from the args
argv0 <- getArgs
let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
mbMinusB | null minusB_args = Nothing
| otherwise = Just (drop 2 (last minusB_args))
let argv1' = map (mkGeneralLocated "on the commandline") argv1
(argv2, staticFlagWarnings) <- parseStaticFlags argv1'
-- 2. Parse the "mode" flags (--make, --interactive etc.)
(mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
-- If all we want to do is something like showing the version number
-- then do it now, before we start a GHC session etc. This makes
-- getting basic information much more resilient.
-- In particular, if we wait until later before giving the version
-- number then bootstrapping gets confused, as it tries to find out
-- what version of GHC it's using before package.conf exists, so
-- starting the session fails.
case mode of
Left preStartupMode ->
do case preStartupMode of
ShowSupportedExtensions -> showSupportedExtensions
ShowVersion -> showVersion
ShowNumVersion -> putStrLn cProjectVersion
ShowOptions -> showOptions
Right postStartupMode ->
-- start our GHC session
GHC.runGhc mbMinusB $ do
dflags <- GHC.getSessionDynFlags
case postStartupMode of
Left preLoadMode ->
liftIO $ do
case preLoadMode of
ShowInfo -> showInfo dflags
ShowGhcUsage -> showGhcUsage dflags
ShowGhciUsage -> showGhciUsage dflags
PrintWithDynFlags f -> putStrLn (f dflags)
Right postLoadMode ->
main' postLoadMode dflags argv3 flagWarnings
main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
-> Ghc ()
main' postLoadMode dflags0 args flagWarnings = do
-- set the default GhcMode, HscTarget and GhcLink. The HscTarget
-- can be further adjusted on a module by module basis, using only
-- the -fvia-C and -fasm flags. If the default HscTarget is not
-- HscC or HscAsm, -fvia-C and -fasm have no effect.
let dflt_target = hscTarget dflags0
(mode, lang, link)
= case postLoadMode of
DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
DoMake -> (CompManager, dflt_target, LinkBinary)
DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
DoAbiHash -> (OneShot, dflt_target, LinkBinary)
_ -> (OneShot, dflt_target, LinkBinary)
let dflags1 = case lang of
HscInterpreted ->
let platform = targetPlatform dflags0
dflags0a = updateWays $ dflags0 { ways = interpWays }
dflags0b = foldl gopt_set dflags0a
$ concatMap (wayGeneralFlags platform)
interpWays
dflags0c = foldl gopt_unset dflags0b
$ concatMap (wayUnsetGeneralFlags platform)
interpWays
in dflags0c
_ ->
dflags0
dflags2 = dflags1{ ghcMode = mode,
hscTarget = lang,
ghcLink = link,
verbosity = case postLoadMode of
DoEval _ -> 0
_other -> 1
}
-- turn on -fimplicit-import-qualified for GHCi now, so that it
-- can be overriden from the command-line
-- XXX: this should really be in the interactive DynFlags, but
-- we don't set that until later in interactiveUI
dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled
| DoEval _ <- postLoadMode = imp_qual_enabled
| otherwise = dflags2
where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified
-- The rest of the arguments are "dynamic"
-- Leftover ones are presumably files
(dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args
GHC.prettyPrintGhcErrors dflags4 $ do
let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
liftIO $ handleFlagWarnings dflags4 flagWarnings'
-- make sure we clean up after ourselves
GHC.defaultCleanupHandler dflags4 $ do
liftIO $ showBanner postLoadMode dflags4
let
-- To simplify the handling of filepaths, we normalise all filepaths right
-- away - e.g., for win32 platforms, backslashes are converted
-- into forward slashes.
normal_fileish_paths = map (normalise . unLoc) fileish_args
(srcs, objs) = partition_args normal_fileish_paths [] []
dflags5 = dflags4 { ldInputs = map (FileOption "") objs
++ ldInputs dflags4 }
-- we've finished manipulating the DynFlags, update the session
_ <- GHC.setSessionDynFlags dflags5
dflags6 <- GHC.getSessionDynFlags
hsc_env <- GHC.getSession
---------------- Display configuration -----------
when (verbosity dflags6 >= 4) $
liftIO $ dumpPackages dflags6
when (verbosity dflags6 >= 3) $ do
liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
---------------- Final sanity checking -----------
liftIO $ checkOptions postLoadMode dflags6 srcs objs
---------------- Do the business -----------
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
case postLoadMode of
ShowInterface f -> liftIO $ doShowIface dflags6 f
DoMake -> doMake srcs
DoMkDependHS -> doMkDependHS (map fst srcs)
StopBefore p -> liftIO (oneShot hsc_env p srcs)
DoInteractive -> ghciUI srcs Nothing
DoEval exprs -> ghciUI srcs $ Just $ reverse exprs
DoAbiHash -> abiHash srcs
liftIO $ dumpFinalStats dflags6
ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
#ifndef GHCI
ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use")
#else
ghciUI = interactiveUI defaultGhciSettings
#endif
-- -----------------------------------------------------------------------------
-- Splitting arguments into source files and object files. This is where we
-- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
-- file indicating the phase specified by the -x option in force, if any.
partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
-> ([(String, Maybe Phase)], [String])
partition_args [] srcs objs = (reverse srcs, reverse objs)
partition_args ("-x":suff:args) srcs objs
| "none" <- suff = partition_args args srcs objs
| StopLn <- phase = partition_args args srcs (slurp ++ objs)
| otherwise = partition_args rest (these_srcs ++ srcs) objs
where phase = startPhase suff
(slurp,rest) = break (== "-x") args
these_srcs = zip slurp (repeat (Just phase))
partition_args (arg:args) srcs objs
| looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
| otherwise = partition_args args srcs (arg:objs)
{-
We split out the object files (.o, .dll) and add them
to ldInputs for use by the linker.
The following things should be considered compilation manager inputs:
- haskell source files (strings ending in .hs, .lhs or other
haskellish extension),
- module names (not forgetting hierarchical module names),
- things beginning with '-' are flags that were not recognised by
the flag parser, and we want them to generate errors later in
checkOptions, so we class them as source files (#5921)
- and finally we consider everything not containing a '.' to be
a comp manager input, as shorthand for a .hs or .lhs filename.
Everything else is considered to be a linker object, and passed
straight through to the linker.
-}
looks_like_an_input :: String -> Bool
looks_like_an_input m = isSourceFilename m
|| looksLikeModuleName m
|| "-" `isPrefixOf` m
|| '.' `notElem` m
-- -----------------------------------------------------------------------------
-- Option sanity checks
-- | Ensure sanity of options.
--
-- Throws 'UsageError' or 'CmdLineError' if not.
checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
-- Final sanity checking before kicking off a compilation (pipeline).
checkOptions mode dflags srcs objs = do
-- Complain about any unknown flags
let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
when (notNull (filter wayRTSOnly (ways dflags))
&& isInterpretiveMode mode) $
hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
-- -prof and --interactive are not a good combination
when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
&& isInterpretiveMode mode) $
do throwGhcException (UsageError
"--interactive can't be used with -prof or -unreg.")
-- -ohi sanity check
if (isJust (outputHi dflags) &&
(isCompManagerMode mode || srcs `lengthExceeds` 1))
then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
else do
-- -o sanity checking
if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
&& not (isLinkMode mode))
then throwGhcException (UsageError "can't apply -o to multiple source files")
else do
let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
when (not_linking && not (null objs)) $
hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
-- Check that there are some input files
-- (except in the interactive case)
if null srcs && (null objs || not_linking) && needsInputsMode mode
then throwGhcException (UsageError "no input files")
else do
-- Verify that output files point somewhere sensible.
verifyOutputFiles dflags
-- Compiler output options
-- called to verify that the output files & directories
-- point somewhere valid.
--
-- The assumption is that the directory portion of these output
-- options will have to exist by the time 'verifyOutputFiles'
-- is invoked.
--
verifyOutputFiles :: DynFlags -> IO ()
verifyOutputFiles dflags = do
-- not -odir: we create the directory for -odir if it doesn't exist (#2278).
let ofile = outputFile dflags
when (isJust ofile) $ do
let fn = fromJust ofile
flg <- doesDirNameExist fn
when (not flg) (nonExistentDir "-o" fn)
let ohi = outputHi dflags
when (isJust ohi) $ do
let hi = fromJust ohi
flg <- doesDirNameExist hi
when (not flg) (nonExistentDir "-ohi" hi)
where
nonExistentDir flg dir =
throwGhcException (CmdLineError ("error: directory portion of " ++
show dir ++ " does not exist (used with " ++
show flg ++ " option.)"))
-----------------------------------------------------------------------------
-- GHC modes of operation
type Mode = Either PreStartupMode PostStartupMode
type PostStartupMode = Either PreLoadMode PostLoadMode
data PreStartupMode
= ShowVersion -- ghc -V/--version
| ShowNumVersion -- ghc --numeric-version
| ShowSupportedExtensions -- ghc --supported-extensions
| ShowOptions -- ghc --show-options
showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
showVersionMode = mkPreStartupMode ShowVersion
showNumVersionMode = mkPreStartupMode ShowNumVersion
showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
showOptionsMode = mkPreStartupMode ShowOptions
mkPreStartupMode :: PreStartupMode -> Mode
mkPreStartupMode = Left
isShowVersionMode :: Mode -> Bool
isShowVersionMode (Left ShowVersion) = True
isShowVersionMode _ = False
isShowNumVersionMode :: Mode -> Bool
isShowNumVersionMode (Left ShowNumVersion) = True
isShowNumVersionMode _ = False
data PreLoadMode
= ShowGhcUsage -- ghc -?
| ShowGhciUsage -- ghci -?
| ShowInfo -- ghc --info
| PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
showGhcUsageMode = mkPreLoadMode ShowGhcUsage
showGhciUsageMode = mkPreLoadMode ShowGhciUsage
showInfoMode = mkPreLoadMode ShowInfo
printSetting :: String -> Mode
printSetting k = mkPreLoadMode (PrintWithDynFlags f)
where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
$ lookup k (compilerInfo dflags)
mkPreLoadMode :: PreLoadMode -> Mode
mkPreLoadMode = Right . Left
isShowGhcUsageMode :: Mode -> Bool
isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
isShowGhcUsageMode _ = False
isShowGhciUsageMode :: Mode -> Bool
isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
isShowGhciUsageMode _ = False
data PostLoadMode
= ShowInterface FilePath -- ghc --show-iface
| DoMkDependHS -- ghc -M
| StopBefore Phase -- ghc -E | -C | -S
-- StopBefore StopLn is the default
| DoMake -- ghc --make
| DoInteractive -- ghc --interactive
| DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
| DoAbiHash -- ghc --abi-hash
doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode :: Mode
doMkDependHSMode = mkPostLoadMode DoMkDependHS
doMakeMode = mkPostLoadMode DoMake
doInteractiveMode = mkPostLoadMode DoInteractive
doAbiHashMode = mkPostLoadMode DoAbiHash
showInterfaceMode :: FilePath -> Mode
showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
stopBeforeMode :: Phase -> Mode
stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
doEvalMode :: String -> Mode
doEvalMode str = mkPostLoadMode (DoEval [str])
mkPostLoadMode :: PostLoadMode -> Mode
mkPostLoadMode = Right . Right
isDoInteractiveMode :: Mode -> Bool
isDoInteractiveMode (Right (Right DoInteractive)) = True
isDoInteractiveMode _ = False
isStopLnMode :: Mode -> Bool
isStopLnMode (Right (Right (StopBefore StopLn))) = True
isStopLnMode _ = False
isDoMakeMode :: Mode -> Bool
isDoMakeMode (Right (Right DoMake)) = True
isDoMakeMode _ = False
#ifdef GHCI
isInteractiveMode :: PostLoadMode -> Bool
isInteractiveMode DoInteractive = True
isInteractiveMode _ = False
#endif
-- isInterpretiveMode: byte-code compiler involved
isInterpretiveMode :: PostLoadMode -> Bool
isInterpretiveMode DoInteractive = True
isInterpretiveMode (DoEval _) = True
isInterpretiveMode _ = False
needsInputsMode :: PostLoadMode -> Bool
needsInputsMode DoMkDependHS = True
needsInputsMode (StopBefore _) = True
needsInputsMode DoMake = True
needsInputsMode _ = False
-- True if we are going to attempt to link in this mode.
-- (we might not actually link, depending on the GhcLink flag)
isLinkMode :: PostLoadMode -> Bool
isLinkMode (StopBefore StopLn) = True
isLinkMode DoMake = True
isLinkMode DoInteractive = True
isLinkMode (DoEval _) = True
isLinkMode _ = False
isCompManagerMode :: PostLoadMode -> Bool
isCompManagerMode DoMake = True
isCompManagerMode DoInteractive = True
isCompManagerMode (DoEval _) = True
isCompManagerMode _ = False
-- -----------------------------------------------------------------------------
-- Parsing the mode flag
parseModeFlags :: [Located String]
-> IO (Mode,
[Located String],
[Located String])
parseModeFlags args = do
let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
runCmdLine (processArgs mode_flags args)
(Nothing, [], [])
mode = case mModeFlag of
Nothing -> doMakeMode
Just (m, _) -> m
errs = errs1 ++ map (mkGeneralLocated "on the commandline") errs2
when (not (null errs)) $ throwGhcException $ errorsToGhcException errs
return (mode, flags' ++ leftover, warns)
type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
-- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
-- so we collect the new ones and return them.
mode_flags :: [Flag ModeM]
mode_flags =
[ ------- help / version ----------------------------------------------
Flag "?" (PassFlag (setMode showGhcUsageMode))
, Flag "-help" (PassFlag (setMode showGhcUsageMode))
, Flag "V" (PassFlag (setMode showVersionMode))
, Flag "-version" (PassFlag (setMode showVersionMode))
, Flag "-numeric-version" (PassFlag (setMode showNumVersionMode))
, Flag "-info" (PassFlag (setMode showInfoMode))
, Flag "-show-options" (PassFlag (setMode showOptionsMode))
, Flag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
, Flag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
] ++
[ Flag k' (PassFlag (setMode (printSetting k)))
| k <- ["Project version",
"Booter version",
"Stage",
"Build platform",
"Host platform",
"Target platform",
"Have interpreter",
"Object splitting supported",
"Have native code generator",
"Support SMP",
"Unregisterised",
"Tables next to code",
"RTS ways",
"Leading underscore",
"Debug on",
"LibDir",
"Global Package DB",
"C compiler flags",
"Gcc Linker flags",
"Ld Linker flags"],
let k' = "-print-" ++ map (replaceSpace . toLower) k
replaceSpace ' ' = '-'
replaceSpace c = c
] ++
------- interfaces ----------------------------------------------------
[ Flag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
"--show-iface"))
------- primary modes ------------------------------------------------
, Flag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
addFlag "-no-link" f))
, Flag "M" (PassFlag (setMode doMkDependHSMode))
, Flag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
, Flag "C" (PassFlag (setMode (stopBeforeMode HCc)))
, Flag "S" (PassFlag (setMode (stopBeforeMode (As False))))
, Flag "-make" (PassFlag (setMode doMakeMode))
, Flag "-interactive" (PassFlag (setMode doInteractiveMode))
, Flag "-abi-hash" (PassFlag (setMode doAbiHashMode))
, Flag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
]
setMode :: Mode -> String -> EwM ModeM ()
setMode newMode newFlag = liftEwM $ do
(mModeFlag, errs, flags') <- getCmdLineState
let (modeFlag', errs') =
case mModeFlag of
Nothing -> ((newMode, newFlag), errs)
Just (oldMode, oldFlag) ->
case (oldMode, newMode) of
-- -c/--make are allowed together, and mean --make -no-link
_ | isStopLnMode oldMode && isDoMakeMode newMode
|| isStopLnMode newMode && isDoMakeMode oldMode ->
((doMakeMode, "--make"), [])
-- If we have both --help and --interactive then we
-- want showGhciUsage
_ | isShowGhcUsageMode oldMode &&
isDoInteractiveMode newMode ->
((showGhciUsageMode, oldFlag), [])
| isShowGhcUsageMode newMode &&
isDoInteractiveMode oldMode ->
((showGhciUsageMode, newFlag), [])
-- Otherwise, --help/--version/--numeric-version always win
| isDominantFlag oldMode -> ((oldMode, oldFlag), [])
| isDominantFlag newMode -> ((newMode, newFlag), [])
-- We need to accumulate eval flags like "-e foo -e bar"
(Right (Right (DoEval esOld)),
Right (Right (DoEval [eNew]))) ->
((Right (Right (DoEval (eNew : esOld))), oldFlag),
errs)
-- Saying e.g. --interactive --interactive is OK
_ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
-- Otherwise, complain
_ -> let err = flagMismatchErr oldFlag newFlag
in ((oldMode, oldFlag), err : errs)
putCmdLineState (Just modeFlag', errs', flags')
where isDominantFlag f = isShowGhcUsageMode f ||
isShowGhciUsageMode f ||
isShowVersionMode f ||
isShowNumVersionMode f
flagMismatchErr :: String -> String -> String
flagMismatchErr oldFlag newFlag
= "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
addFlag :: String -> String -> EwM ModeM ()
addFlag s flag = liftEwM $ do
(m, e, flags') <- getCmdLineState
putCmdLineState (m, e, mkGeneralLocated loc s : flags')
where loc = "addFlag by " ++ flag ++ " on the commandline"
-- ----------------------------------------------------------------------------
-- Run --make mode
doMake :: [(String,Maybe Phase)] -> Ghc ()
doMake srcs = do
let (hs_srcs, non_hs_srcs) = partition haskellish srcs
haskellish (f,Nothing) =
looksLikeModuleName f || isHaskellUserSrcFilename f || '.' `notElem` f
haskellish (_,Just phase) =
phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcpp, CmmCpp, Cmm
, StopLn]
hsc_env <- GHC.getSession
-- if we have no haskell sources from which to do a dependency
-- analysis, then just do one-shot compilation and/or linking.
-- This means that "ghc Foo.o Bar.o -o baz" links the program as
-- we expect.
if (null hs_srcs)
then liftIO (oneShot hsc_env StopLn srcs)
else do
o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
non_hs_srcs
dflags <- GHC.getSessionDynFlags
let dflags' = dflags { ldInputs = map (FileOption "") o_files
++ ldInputs dflags }
_ <- GHC.setSessionDynFlags dflags'
targets <- mapM (uncurry GHC.guessTarget) hs_srcs
GHC.setTargets targets
ok_flag <- GHC.load LoadAllTargets
when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
return ()
-- ---------------------------------------------------------------------------
-- --show-iface mode
doShowIface :: DynFlags -> FilePath -> IO ()
doShowIface dflags file = do
hsc_env <- newHscEnv dflags
showIface hsc_env file
-- ---------------------------------------------------------------------------
-- Various banners and verbosity output.
showBanner :: PostLoadMode -> DynFlags -> IO ()
showBanner _postLoadMode dflags = do
let verb = verbosity dflags
#ifdef GHCI
-- Show the GHCi banner
when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
#endif
-- Display details of the configuration in verbose mode
when (verb >= 2) $
do hPutStr stderr "Glasgow Haskell Compiler, Version "
hPutStr stderr cProjectVersion
hPutStr stderr ", stage "
hPutStr stderr cStage
hPutStr stderr " booted by GHC version "
hPutStrLn stderr cBooterVersion
-- We print out a Read-friendly string, but a prettier one than the
-- Show instance gives us
showInfo :: DynFlags -> IO ()
showInfo dflags = do
let sq x = " [" ++ x ++ "\n ]"
putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
showSupportedExtensions :: IO ()
showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
showVersion :: IO ()
showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
showOptions :: IO ()
showOptions = putStr (unlines availableOptions)
where
availableOptions = map ((:) '-') $
getFlagNames mode_flags ++
getFlagNames flagsDynamic ++
(filterUnwantedStatic . getFlagNames $ flagsStatic) ++
flagsStaticNames
getFlagNames opts = map getFlagName opts
getFlagName (Flag name _) = name
-- this is a hack to get rid of two unwanted entries that get listed
-- as static flags. Hopefully this hack will disappear one day together
-- with static flags
filterUnwantedStatic = filter (\x -> not (x `elem` ["f", "fno-"]))
showGhcUsage :: DynFlags -> IO ()
showGhcUsage = showUsage False
showGhciUsage :: DynFlags -> IO ()
showGhciUsage = showUsage True
showUsage :: Bool -> DynFlags -> IO ()
showUsage ghci dflags = do
let usage_path = if ghci then ghciUsagePath dflags
else ghcUsagePath dflags
usage <- readFile usage_path
dump usage
where
dump "" = return ()
dump ('$':'$':s) = putStr progName >> dump s
dump (c:s) = putChar c >> dump s
dumpFinalStats :: DynFlags -> IO ()
dumpFinalStats dflags =
when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
dumpFastStringStats :: DynFlags -> IO ()
dumpFastStringStats dflags = do
buckets <- getFastStringTable
let (entries, longest, has_z) = countFS 0 0 0 buckets
msg = text "FastString stats:" $$
nest 4 (vcat [text "size: " <+> int (length buckets),
text "entries: " <+> int entries,
text "longest chain: " <+> int longest,
text "has z-encoding: " <+> (has_z `pcntOf` entries)
])
-- we usually get more "has z-encoding" than "z-encoded", because
-- when we z-encode a string it might hash to the exact same string,
-- which will is not counted as "z-encoded". Only strings whose
-- Z-encoding is different from the original string are counted in
-- the "z-encoded" total.
putMsg dflags msg
where
x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
countFS entries longest has_z [] = (entries, longest, has_z)
countFS entries longest has_z (b:bs) =
let
len = length b
longest' = max len longest
entries' = entries + len
has_zs = length (filter hasZEncoding b)
in
countFS entries' longest' (has_z + has_zs) bs
-- -----------------------------------------------------------------------------
-- ABI hash support
{-
ghc --abi-hash Data.Foo System.Bar
Generates a combined hash of the ABI for modules Data.Foo and
System.Bar. The modules must already be compiled, and appropriate -i
options may be necessary in order to find the .hi files.
This is used by Cabal for generating the InstalledPackageId for a
package. The InstalledPackageId must change when the visible ABI of
the package chagnes, so during registration Cabal calls ghc --abi-hash
to get a hash of the package's ABI.
-}
abiHash :: [(String, Maybe Phase)] -> Ghc ()
abiHash strs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
let find_it str = do
let modname = mkModuleName str
r <- findImportedModule hsc_env modname Nothing
case r of
Found _ m -> return m
_error -> throwGhcException $ CmdLineError $ showSDoc dflags $
cannotFindInterface dflags modname r
mods <- mapM find_it (map fst strs)
let get_iface modl = loadUserInterface False (text "abiHash") modl
ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
bh <- openBinMem (3*1024) -- just less than a block
put_ bh hiVersion
-- package hashes change when the compiler version changes (for now)
-- see #5328
mapM_ (put_ bh . mi_mod_hash) ifaces
f <- fingerprintBinMem bh
putStrLn (showPpr dflags f)
-- -----------------------------------------------------------------------------
-- Util
unknownFlagsErr :: [String] -> a
unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
where
oneError f =
"unrecognised flag: " ++ f ++ "\n" ++
(case fuzzyMatch f (nub allFlags) of
[] -> ""
suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
{- Note [-Bsymbolic and hooks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Bsymbolic is a flag that prevents the binding of references to global
symbols to symbols outside the shared library being compiled (see `man
ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
package: that is because we want hooks to be overridden by the user,
we don't want to constrain them to the RTS package.
Unfortunately this seems to have broken somehow on OS X: as a result,
defaultHooks (in hschooks.c) is not called, which does not initialize
the GC stats. As a result, this breaks things like `:set +s` in GHCi
(#8754). As a hacky workaround, we instead call 'defaultHooks'
directly to initalize the flags in the RTS.
A byproduct of this, I believe, is that hooks are likely broken on OS
X when dynamically linking. But this probably doesn't affect most
people since we're linking GHC dynamically, but most things themselves
link statically.
-}
foreign import ccall safe "initGCStatistics"
initGCStatistics :: IO ()
|
ryantm/ghc
|
ghc/Main.hs
|
bsd-3-clause
| 33,055 | 0 | 27 | 9,273 | 6,767 | 3,493 | 3,274 | 520 | 14 |
{- |
Module : $Header$
Description : Help functions for all automatic theorem provers.
Copyright : (c) Rainer Grabbe
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : needs POSIX
Data structures, initialising functions for Prover state and configurations.
-}
module THF.ProverState where
import Logic.Prover
import THF.As
import THF.Sign
import THF.Print
import Common.AS_Annotation
{- -----------------------------------------------------------------------------
Todos:
maybe use FreeDefMorphism in the ProverStateTHF
----------------------------------------------------------------------------- -}
data ProverStateTHF = ProverStateTHF
{ axioms :: [Named THFFormula]
, signature :: SignTHF
, freeDefs :: [FreeDefMorphism THFFormula MorphismTHF] }
-- Creates an initial THF prover state.
initialProverStateTHF :: SignTHF -> [Named THFFormula]
-> [FreeDefMorphism THFFormula MorphismTHF]
-> ProverStateTHF
initialProverStateTHF sign oSens freedefs = ProverStateTHF
{ axioms = filter isAxiom oSens
, signature = sign
, freeDefs = freedefs }
-- todo: investigate comment about negated axioms
-- Insert a Named SentenceTHF into the ProverStateTHF
insertSentenceTHF :: ProverStateTHF -> Named THFFormula -> ProverStateTHF
insertSentenceTHF ps ns = ps {axioms = ns : axioms ps}
showProblemTHF :: ProverStateTHF -> Named THFFormula -> [String] -> IO String
showProblemTHF ps goal _ = return $ show $ printProblemTHF (signature ps)
(filter isAxiom (axioms ps)) goal
-- Get all axioms possibly used in a proof.
getAxioms :: ProverStateTHF -> [String]
getAxioms = map senAttr . filter isAxiom . axioms
-- FormulaRoles that are treated like axioms
thfAxioms :: [FormulaRole]
thfAxioms = [Axiom, Definition, Lemma, Theorem]
|
keithodulaigh/Hets
|
THF/ProverState.hs
|
gpl-2.0
| 1,861 | 0 | 10 | 311 | 317 | 176 | 141 | 26 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1993-1998
TcRules: Typechecking transformation rules
-}
{-# LANGUAGE ViewPatterns #-}
module TcRules ( tcRules ) where
import HsSyn
import TcRnMonad
import TcSimplify
import TcMType
import TcType
import TcHsType
import TcExpr
import TcEnv
import TcEvidence
import TcUnify( buildImplicationFor )
import Type
import Id
import Var ( EvVar )
import Name
import BasicTypes ( RuleName )
import SrcLoc
import Outputable
import FastString
import Bag
import Data.List( partition )
{-
Note [Typechecking rules]
~~~~~~~~~~~~~~~~~~~~~~~~~
We *infer* the typ of the LHS, and use that type to *check* the type of
the RHS. That means that higher-rank rules work reasonably well. Here's
an example (test simplCore/should_compile/rule2.hs) produced by Roman:
foo :: (forall m. m a -> m b) -> m a -> m b
foo f = ...
bar :: (forall m. m a -> m a) -> m a -> m a
bar f = ...
{-# RULES "foo/bar" foo = bar #-}
He wanted the rule to typecheck.
-}
tcRules :: [LRuleDecls Name] -> TcM [LRuleDecls TcId]
tcRules decls = mapM (wrapLocM tcRuleDecls) decls
tcRuleDecls :: RuleDecls Name -> TcM (RuleDecls TcId)
tcRuleDecls (HsRules src decls)
= do { tc_decls <- mapM (wrapLocM tcRule) decls
; return (HsRules src tc_decls) }
tcRule :: RuleDecl Name -> TcM (RuleDecl TcId)
tcRule (HsRule name act hs_bndrs lhs fv_lhs rhs fv_rhs)
= addErrCtxt (ruleCtxt $ snd $ unLoc name) $
do { traceTc "---- Rule ------" (pprFullRuleName name)
-- Note [Typechecking rules]
; (vars, bndr_wanted) <- captureConstraints $
tcRuleBndrs hs_bndrs
-- bndr_wanted constraints can include wildcard hole
-- constraints, which we should not forget about.
-- It may mention the skolem type variables bound by
-- the RULE. c.f. Trac #10072
; let (id_bndrs, tv_bndrs) = partition isId vars
; (lhs', lhs_wanted, rhs', rhs_wanted, rule_ty)
<- tcExtendTyVarEnv tv_bndrs $
tcExtendIdEnv id_bndrs $
do { -- See Note [Solve order for RULES]
((lhs', rule_ty), lhs_wanted) <- captureConstraints (tcInferRho lhs)
; (rhs', rhs_wanted) <- captureConstraints $
tcMonoExpr rhs (mkCheckExpType rule_ty)
; return (lhs', lhs_wanted, rhs', rhs_wanted, rule_ty) }
; traceTc "tcRule 1" (vcat [ pprFullRuleName name
, ppr lhs_wanted
, ppr rhs_wanted ])
; let all_lhs_wanted = bndr_wanted `andWC` lhs_wanted
; lhs_evs <- simplifyRule (snd $ unLoc name)
all_lhs_wanted
rhs_wanted
-- Now figure out what to quantify over
-- c.f. TcSimplify.simplifyInfer
-- We quantify over any tyvars free in *either* the rule
-- *or* the bound variables. The latter is important. Consider
-- ss (x,(y,z)) = (x,z)
-- RULE: forall v. fst (ss v) = fst v
-- The type of the rhs of the rule is just a, but v::(a,(b,c))
--
-- We also need to get the completely-uconstrained tyvars of
-- the LHS, lest they otherwise get defaulted to Any; but we do that
-- during zonking (see TcHsSyn.zonkRule)
; let tpl_ids = lhs_evs ++ id_bndrs
; forall_tkvs <- zonkTcTypesAndSplitDepVars $
rule_ty : map idType tpl_ids
; gbls <- tcGetGlobalTyCoVars -- Even though top level, there might be top-level
-- monomorphic bindings from the MR; test tc111
; qtkvs <- quantifyZonkedTyVars gbls forall_tkvs
; traceTc "tcRule" (vcat [ pprFullRuleName name
, ppr forall_tkvs
, ppr qtkvs
, ppr rule_ty
, vcat [ ppr id <+> dcolon <+> ppr (idType id) | id <- tpl_ids ]
])
-- Simplify the RHS constraints
; let skol_info = RuleSkol (snd $ unLoc name)
; (rhs_implic, rhs_binds) <- buildImplicationFor topTcLevel skol_info qtkvs
lhs_evs rhs_wanted
-- For the LHS constraints we must solve the remaining constraints
-- (a) so that we report insoluble ones
-- (b) so that we bind any soluble ones
; (lhs_implic, lhs_binds) <- buildImplicationFor topTcLevel skol_info qtkvs
lhs_evs
(all_lhs_wanted { wc_simple = emptyBag })
-- simplifyRule consumed all simple
-- constraints
; emitImplications (lhs_implic `unionBags` rhs_implic)
; return (HsRule name act
(map (noLoc . RuleBndr . noLoc) (qtkvs ++ tpl_ids))
(mkHsDictLet lhs_binds lhs') fv_lhs
(mkHsDictLet rhs_binds rhs') fv_rhs) }
tcRuleBndrs :: [LRuleBndr Name] -> TcM [Var]
tcRuleBndrs []
= return []
tcRuleBndrs (L _ (RuleBndr (L _ name)) : rule_bndrs)
= do { ty <- newOpenFlexiTyVarTy
; vars <- tcRuleBndrs rule_bndrs
; return (mkLocalId name ty : vars) }
tcRuleBndrs (L _ (RuleBndrSig (L _ name) rn_ty) : rule_bndrs)
-- e.g x :: a->a
-- The tyvar 'a' is brought into scope first, just as if you'd written
-- a::*, x :: a->a
= do { let ctxt = RuleSigCtxt name
; (_ , tvs, id_ty) <- tcHsPatSigType ctxt rn_ty
; let id = mkLocalIdOrCoVar name id_ty
-- See Note [Pattern signature binders] in TcHsType
-- The type variables scope over subsequent bindings; yuk
; vars <- tcExtendTyVarEnv tvs $
tcRuleBndrs rule_bndrs
; return (tvs ++ id : vars) }
ruleCtxt :: FastString -> SDoc
ruleCtxt name = text "When checking the transformation rule" <+>
doubleQuotes (ftext name)
{-
*********************************************************************************
* *
Constraint simplification for rules
* *
***********************************************************************************
Note [Simplifying RULE constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example. Consider the following left-hand side of a rule
f (x == y) (y > z) = ...
If we typecheck this expression we get constraints
d1 :: Ord a, d2 :: Eq a
We do NOT want to "simplify" to the LHS
forall x::a, y::a, z::a, d1::Ord a.
f ((==) (eqFromOrd d1) x y) ((>) d1 y z) = ...
Instead we want
forall x::a, y::a, z::a, d1::Ord a, d2::Eq a.
f ((==) d2 x y) ((>) d1 y z) = ...
Here is another example:
fromIntegral :: (Integral a, Num b) => a -> b
{-# RULES "foo" fromIntegral = id :: Int -> Int #-}
In the rule, a=b=Int, and Num Int is a superclass of Integral Int. But
we *dont* want to get
forall dIntegralInt.
fromIntegral Int Int dIntegralInt (scsel dIntegralInt) = id Int
because the scsel will mess up RULE matching. Instead we want
forall dIntegralInt, dNumInt.
fromIntegral Int Int dIntegralInt dNumInt = id Int
Even if we have
g (x == y) (y == z) = ..
where the two dictionaries are *identical*, we do NOT WANT
forall x::a, y::a, z::a, d1::Eq a
f ((==) d1 x y) ((>) d1 y z) = ...
because that will only match if the dict args are (visibly) equal.
Instead we want to quantify over the dictionaries separately.
In short, simplifyRuleLhs must *only* squash equalities, leaving
all dicts unchanged, with absolutely no sharing.
Also note that we can't solve the LHS constraints in isolation:
Example foo :: Ord a => a -> a
foo_spec :: Int -> Int
{-# RULE "foo" foo = foo_spec #-}
Here, it's the RHS that fixes the type variable
HOWEVER, under a nested implication things are different
Consider
f :: (forall a. Eq a => a->a) -> Bool -> ...
{-# RULES "foo" forall (v::forall b. Eq b => b->b).
f b True = ...
#-}
Here we *must* solve the wanted (Eq a) from the given (Eq a)
resulting from skolemising the agument type of g. So we
revert to SimplCheck when going under an implication.
------------------------ So the plan is this -----------------------
* Step 0: typecheck the LHS and RHS to get constraints from each
* Step 1: Simplify the LHS and RHS constraints all together in one bag
We do this to discover all unification equalities
* Step 2: Zonk the ORIGINAL (unsimplified) lhs constraints, to take
advantage of those unifications, and partition them into the
ones we will quantify over, and the others
See Note [RULE quantification over equalities]
* Step 3: Decide on the type variables to quantify over
* Step 4: Simplify the LHS and RHS constraints separately, using the
quantified constraints as givens
Note [Solve order for RULES]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In step 1 above, we need to be a bit careful about solve order.
Consider
f :: Int -> T Int
type instance T Int = Bool
RULE f 3 = True
From the RULE we get
lhs-constraints: T Int ~ alpha
rhs-constraints: Bool ~ alpha
where 'alpha' is the type that connects the two. If we glom them
all together, and solve the RHS constraint first, we might solve
with alpha := Bool. But then we'd end up with a RULE like
RULE: f 3 |> (co :: T Int ~ Booo) = True
which is terrible. We want
RULE: f 3 = True |> (sym co :: Bool ~ T Int)
So we are careful to solve the LHS constraints first, and *then* the
RHS constraints. Actually much of this is done by the on-the-fly
constraint solving, so the same order must be observed in
tcRule.
Note [RULE quantification over equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Deciding which equalities to quantify over is tricky:
* We do not want to quantify over insoluble equalities (Int ~ Bool)
(a) because we prefer to report a LHS type error
(b) because if such things end up in 'givens' we get a bogus
"inaccessible code" error
* But we do want to quantify over things like (a ~ F b), where
F is a type function.
The difficulty is that it's hard to tell what is insoluble!
So we see whether the simplification step yielded any type errors,
and if so refrain from quantifying over *any* equalities.
Note [Quantifying over coercion holes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Equality constraints from the LHS will emit coercion hole Wanteds.
These don't have a name, so we can't quantify over them directly.
Instead, because we really do want to quantify here, invent a new
EvVar for the coercion, fill the hole with the invented EvVar, and
then quantify over the EvVar. Not too tricky -- just some
impedence matching, really.
Note [Simplify cloned constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At this stage, we're simplifying constraints only for insolubility
and for unification. Note that all the evidence is quickly discarded.
We use a clone of the real constraint. If we don't do this,
then RHS coercion-hole constraints get filled in, only to get filled
in *again* when solving the implications emitted from tcRule. That's
terrible, so we avoid the problem by cloning the constraints.
-}
simplifyRule :: RuleName
-> WantedConstraints -- Constraints from LHS
-> WantedConstraints -- Constraints from RHS
-> TcM [EvVar] -- LHS evidence variables,
-- See Note [Simplifying RULE constraints] in TcRule
-- NB: This consumes all simple constraints on the LHS, but not
-- any LHS implication constraints.
simplifyRule name lhs_wanted rhs_wanted
= do { -- We allow ourselves to unify environment
-- variables: runTcS runs with topTcLevel
; lhs_clone <- cloneWC lhs_wanted
; rhs_clone <- cloneWC rhs_wanted
; insoluble <- runTcSDeriveds $
do { -- First solve the LHS and *then* solve the RHS
-- See Note [Solve order for RULES]
-- See Note [Simplify cloned constraints]
lhs_resid <- solveWanteds lhs_clone
; rhs_resid <- solveWanteds rhs_clone
; return ( insolubleWC lhs_resid ||
insolubleWC rhs_resid ) }
; zonked_lhs_simples <- zonkSimples (wc_simple lhs_wanted)
; ev_ids <- mapMaybeM (quantify_ct insoluble) $
bagToList zonked_lhs_simples
; traceTc "simplifyRule" $
vcat [ text "LHS of rule" <+> doubleQuotes (ftext name)
, text "lhs_wantd" <+> ppr lhs_wanted
, text "rhs_wantd" <+> ppr rhs_wanted
, text "zonked_lhs_simples" <+> ppr zonked_lhs_simples
, text "ev_ids" <+> ppr ev_ids
]
; return ev_ids }
where
quantify_ct insol -- Note [RULE quantification over equalities]
| insol = quantify_insol
| otherwise = quantify_normal
quantify_insol ct
| isEqPred (ctPred ct)
= return Nothing
| otherwise
= return $ Just $ ctEvId $ ctEvidence ct
quantify_normal (ctEvidence -> CtWanted { ctev_dest = dest
, ctev_pred = pred })
= case dest of -- See Note [Quantifying over coercion holes]
HoleDest hole
| EqPred NomEq t1 t2 <- classifyPredType pred
, t1 `tcEqType` t2
-> do { -- These are trivial. Don't quantify. But do fill in
-- the hole.
; fillCoercionHole hole (mkTcNomReflCo t1)
; return Nothing }
| otherwise
-> do { ev_id <- newEvVar pred
; fillCoercionHole hole (mkTcCoVarCo ev_id)
; return (Just ev_id) }
EvVarDest evar -> return (Just evar)
quantify_normal ct = pprPanic "simplifyRule.quantify_normal" (ppr ct)
|
olsner/ghc
|
compiler/typecheck/TcRules.hs
|
bsd-3-clause
| 14,360 | 2 | 17 | 4,451 | 1,645 | 850 | 795 | 135 | 3 |
module Graphics.UI.Gtk.Display.Clone where
import Control.Exception as E
import Control.Monad
import Control.Monad.Trans(liftIO)
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.GC
import Graphics.UI.Gtk.Gdk.Pixbuf
import System.Glib.Types
data Clone = Clone Image
instance WidgetClass Clone
instance ObjectClass Clone
instance GObjectClass Clone where
toGObject (Clone da) = toGObject da
unsafeCastGObject = Clone . unsafeCastGObject
cloneNewOf :: WidgetClass w => w -> IO Clone
cloneNewOf widget = do
(w,h) <- widgetGetSize widget
pb <- pixbufNew ColorspaceRgb False 8 w h
img <- imageNewFromPixbuf pb
widget `after` realize $ redisplay widget img
img `on` exposeEvent $ liftIO (redisplay widget img) >> return False
return $ Clone img
redisplay :: WidgetClass w => w -> Image -> IO ()
redisplay widget img = postGUIAsync $ redisplay' widget img
redisplay' :: WidgetClass w => w -> Image -> IO ()
redisplay' widget img = do
threadsEnter
realizd1 <- widgetGetRealized img
realizd2 <- widgetGetRealized widget
when (realizd1 && realizd2) $ do
displayGetDefault >>= \x -> maybe (return ()) displayFlush x
wgdw <- widgetGetDrawWindow widget
(w',h') <- drawableGetSize wgdw
let r = Rectangle 0 0 w' h'
pb <- pixbufGetFromDrawable wgdw r
maybe (return ()) (imageSetFromPixbuf img) pb
threadsLeave
cloneNewScaledOf :: WidgetClass w => w -> (Int, Int) -> Bool -> IO Clone
cloneNewScaledOf widget sz prop = do
(w,h) <- widgetGetSize widget
pb <- pixbufNew ColorspaceRgb True 8 w h
img <- imageNewFromPixbuf pb
widget `after` realize $ redisplayProp widget img sz prop
-- widget `after` noExposeEvent $ liftIO (redisplayProp widget img sz prop) >> return False
img `on` exposeEvent $ liftIO (redisplayProp widget img sz prop) >> return False
return $ Clone img
redisplayProp :: WidgetClass w => w -> Image -> (Int, Int) -> Bool -> IO ()
redisplayProp widget img sz prop = postGUIAsync $ redisplayProp' widget img sz prop
redisplayProp' :: WidgetClass w => w -> Image -> (Int, Int) -> Bool -> IO ()
redisplayProp' widget img sz@(w,h) prop = do
threadsEnter
sz2@(w2,h2) <- widgetGetSize widget
realizd1 <- widgetGetRealized img
realizd2 <- widgetGetRealized widget
when (realizd1 && realizd2) $ do
wgdw <- widgetGetDrawWindow widget
sz2@(w',h') <- drawableGetSize wgdw
let r = Rectangle 0 0 w' h'
pb <- pixbufGetFromDrawable wgdw r
maybe (return ()) (\pb' -> do
let (dW,dH) = scalingSize sz2 sz prop
pb2 <- pixbufScaleSimple pb' dW dH InterpBilinear
imageSetFromPixbuf img pb2
) pb
return ()
threadsLeave
scalingSize :: (Int,Int) -> (Int,Int) -> Bool -> (Int,Int)
scalingSize s (0 ,_) _ = s
scalingSize s (_ ,0) _ = s
scalingSize (oW,oH) (dW,dH) False = (dW,dH)
scalingSize (oW,oH) (dW,dH) True = (fW,fH)
where fW = round (fromIntegral oW * scale)
fH = round (fromIntegral oH * scale)
scale = min scaleH scaleW
scaleW = fromIntegral dW / fromIntegral oW
scaleH = fromIntegral dH / fromIntegral oH
|
keera-studios/gtk-helpers
|
gtk3/src/Graphics/UI/Gtk/Display/Clone.hs
|
bsd-3-clause
| 3,081 | 0 | 18 | 642 | 1,172 | 585 | 587 | 75 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Copyright : (c) 2010 Simon Meier
--
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Conversion of 'Float's and 'Double's to 'Word32's and 'Word64's.
--
module Data.ByteString.Builder.Prim.Internal.Floating
(
-- coerceFloatToWord32
-- , coerceDoubleToWord64
encodeFloatViaWord32F
, encodeDoubleViaWord64F
) where
import Foreign
import Data.ByteString.Builder.Prim.Internal
{-
We work around ticket http://hackage.haskell.org/trac/ghc/ticket/4092 using the
FFI to store the Float/Double in the buffer and peek it out again from there.
-}
-- | Encode a 'Float' using a 'Word32' encoding.
--
-- PRE: The 'Word32' encoding must have a size of at least 4 bytes.
{-# INLINE encodeFloatViaWord32F #-}
encodeFloatViaWord32F :: FixedPrim Word32 -> FixedPrim Float
encodeFloatViaWord32F w32fe
| size w32fe < sizeOf (undefined :: Float) =
error $ "encodeFloatViaWord32F: encoding not wide enough"
| otherwise = fixedPrim (size w32fe) $ \x op -> do
poke (castPtr op) x
x' <- peek (castPtr op)
runF w32fe x' op
-- | Encode a 'Double' using a 'Word64' encoding.
--
-- PRE: The 'Word64' encoding must have a size of at least 8 bytes.
{-# INLINE encodeDoubleViaWord64F #-}
encodeDoubleViaWord64F :: FixedPrim Word64 -> FixedPrim Double
encodeDoubleViaWord64F w64fe
| size w64fe < sizeOf (undefined :: Float) =
error $ "encodeDoubleViaWord64F: encoding not wide enough"
| otherwise = fixedPrim (size w64fe) $ \x op -> do
poke (castPtr op) x
x' <- peek (castPtr op)
runF w64fe x' op
|
markflorisson/hpack
|
testrepo/bytestring-0.10.4.1/Data/ByteString/Builder/Prim/Internal/Floating.hs
|
bsd-3-clause
| 1,699 | 0 | 13 | 335 | 288 | 152 | 136 | 25 | 1 |
module Application.Helper.View (
-- To use the built in login:
-- module IHP.LoginSupport.Helper.View
) where
-- Here you can add functions which are available in all your views
-- To use the built in login:
-- import IHP.LoginSupport.Helper.View
|
martin-g/FrameworkBenchmarks
|
frameworks/Haskell/ihp/src/Application/Helper/View.hs
|
bsd-3-clause
| 257 | 0 | 3 | 48 | 15 | 12 | 3 | 1 | 0 |
{-# LANGUAGE ConstraintKinds, MultiParamTypeClasses, UndecidableInstances #-}
module TcFail where
class cls (A cls) => A cls c where
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/tcfail216.hs
|
bsd-3-clause
| 134 | 0 | 8 | 19 | 29 | 15 | 14 | -1 | -1 |
module CIS194 (module X) where
import CIS194.Homework01 as X
|
elasticdog/learnhaskell
|
src/CIS194.hs
|
isc
| 62 | 0 | 4 | 10 | 17 | 12 | 5 | 2 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
-- | Perform a restricted form of block+register tiling corresponding to
-- the following pattern:
-- * a redomap is quasi-perfectly nested inside a kernel with at
-- least two parallel dimension (the perfectly nested restriction
-- is relaxed a bit to allow for SGEMM);
-- * all streamed arrays of redomap are one dimensional;
-- * all streamed arrays are variant to exacly one of the two
-- innermost parallel dimensions, and conversely for each of
-- the two innermost parallel dimensions, there is at least
-- one streamed array variant to it;
-- * the stream's result is a tuple of scalar values, which are
-- also the "thread-in-space" return of the kernel.
-- * We have further restrictions that in principle can be relaxed:
-- the redomap has exactly two array input
-- the redomap produces one scalar result
-- the kernel produces one scalar result
module Futhark.Optimise.BlkRegTiling (mmBlkRegTiling, doRegTiling3D) where
import Control.Monad.Reader
import qualified Data.List as L
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Sequence as Seq
import Futhark.IR.GPU
import Futhark.MonadFreshNames
import Futhark.Optimise.TileLoops.Shared
import Futhark.Tools
import Futhark.Transform.Rename
mmBlkRegTiling :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU))
mmBlkRegTiling (Let pat aux (Op (SegOp (SegMap SegThread {} seg_space ts old_kbody))))
| KernelBody () kstms [Returns ResultMaySimplify cs (Var res_nm)] <- old_kbody,
cs == mempty,
-- check kernel has one result of primitive type
[res_tp] <- ts,
primType res_tp,
-- build the variance table, that records, for
-- each variable name, the variables it depends on
initial_variance <- M.map mempty $ scopeOfSegSpace seg_space,
variance <- varianceInStms initial_variance kstms,
-- check that the code fits the pattern having:
-- some `code1`, followed by one Screma SOAC, followed by some `code2`
(code1, Just screma_stmt, code2) <- matchCodeStreamCode kstms,
Let pat_redomap _ (Op _) <- screma_stmt,
-- checks that the Screma SOAC is actually a redomap and normalizes it
Just (common_dim, arrs, (_, red_lam, red_nes, map_lam)) <- isTileableRedomap screma_stmt,
-- check that exactly two 1D arrays are streamed thorugh redomap,
-- and the result of redomap is one scalar
-- !!!I need to rearrange this whole thing!!! including inp_A and inp_B
length arrs == 2 && length red_nes == 1,
[map_t1t, map_t2t] <- map paramDec $ lambdaParams map_lam,
[red_t1, _] <- map paramDec $ lambdaParams red_lam,
primType map_t1t && primType map_t2t && primType red_t1,
map_t1 <- elemType map_t1t,
map_t2 <- elemType map_t2t,
-- checks that the input arrays to redomap are variant to
-- exactly one of the two innermost dimensions of the kernel
Just var_dims <- isInvarTo1of2InnerDims mempty seg_space variance arrs,
-- get the variables on which the first result of redomap depends on
[redomap_orig_res] <- patElems pat_redomap,
Just res_red_var <- M.lookup (patElemName redomap_orig_res) variance, -- variance of the reduce result
-- we furthermore check that code1 is only formed by
-- 1. statements that slice some globally-declared arrays
-- to produce the input for the redomap, and
-- 2. potentially some statements on which the redomap
-- is independent; these are recorded in `code2''`
Just (code2'', tab_inv_stm) <-
foldl
(processIndirections (namesFromList arrs) res_red_var)
(Just (Seq.empty, M.empty))
code1,
-- identify load_A, load_B
tmp_stms <- mapMaybe (`M.lookup` tab_inv_stm) arrs,
length tmp_stms == length arrs,
-- [inp_A, inp_B] <- arrs,
zip_AB <- zip tmp_stms arrs,
[(load_A, inp_A), (load_B, inp_B)] <- if var_dims == [0, 1] then zip_AB else reverse zip_AB,
-- code1' <- stmsFromList $ stmsToList code1 \\ stmsToList code2'',
code2' <- code2'' <> code2,
-- we get the global-thread id for the two inner dimensions,
-- as we are probably going to use it in code generation
(gtid_x, width_B) : (gtid_y, height_A) : rem_outer_dims_rev <- reverse $ unSegSpace seg_space,
rem_outer_dims <- reverse rem_outer_dims_rev,
-- sanity check that the reduce part is not missing
not $ null red_nes = do
let red_ne : _ = red_nes
red_t <- subExpType red_ne
---- in this binder: host code and outer seggroup (ie. the new kernel) ----
(new_kernel, host_stms) <- runBuilder $ do
-- host code
tk_name <- nameFromString . pretty <$> newVName "Tk"
tx_name <- nameFromString . pretty <$> newVName "Tx"
ty_name <- nameFromString . pretty <$> newVName "Ty"
rx_name <- nameFromString . pretty <$> newVName "Rx"
ry_name <- nameFromString . pretty <$> newVName "Ry"
(ty, ry) <- getParTiles ("Ty", "Ry") (ty_name, ry_name) height_A
(tx, rx) <- getParTiles ("Tx", "Rx") (tx_name, rx_name) width_B
tk <- getSeqTile "Tk" tk_name common_dim ty tx
tk_div_tx <- letSubExp "tk_div_tx" =<< ceilDiv tk tx
tk_div_ty <- letSubExp "tk_div_ty" =<< ceilDiv tk ty
tx_rx <- letSubExp "TxRx" =<< toExp (pe64 tx * pe64 rx)
ty_ry <- letSubExp "TyRy" =<< toExp (pe64 ty * pe64 ry)
a_loc_sz <-
letSubExp "a_loc_sz"
=<< toExp (pe64 ty * pe64 ry * pe64 tk)
b_loc_sz <-
letSubExp "b_loc_sz"
=<< toExp (pe64 tk * pe64 tx * pe64 rx)
gridDim_x <- letSubExp "gridDim_x" =<< ceilDiv width_B tx_rx
gridDim_y <- letSubExp "gridDim_y" =<< ceilDiv height_A ty_ry
let gridxy_pexp = pe64 gridDim_y * pe64 gridDim_x
let grid_pexp =
foldl (\x d -> pe64 d * x) gridxy_pexp $
map snd rem_outer_dims_rev
grid_size <- letSubExp "grid_size" =<< toExp grid_pexp
group_size <- letSubExp "group_size" =<< toExp (pe64 ty * pe64 tx)
let segthd_lvl = SegThread (Count grid_size) (Count group_size) SegNoVirtFull
gid_x <- newVName "gid_x"
gid_y <- newVName "gid_y"
gid_flat <- newVName "gid_flat"
---- in this binder: outer seggroup ----
(ret_seggroup, stms_seggroup) <- runBuilder $ do
iii <- letExp "iii" =<< toExp (le64 gid_y * pe64 ty_ry)
jjj <- letExp "jjj" =<< toExp (le64 gid_x * pe64 tx_rx)
-- initialize register mem with neutral elements.
cssss_list <- segMap2D "cssss" segthd_lvl ResultPrivate (ty, tx) $ \_ -> do
css_init <- scratch "css_init" (elemType red_t) [ry, rx]
css <- forLoop ry [css_init] $ \i [css_merge] -> do
css' <- forLoop rx [css_merge] $ \j [css_merge'] -> do
css'' <- update' "css" css_merge' [i, j] red_ne
resultBodyM [Var css'']
resultBodyM [Var css']
return [varRes css]
let [cssss] = cssss_list
a_loc_init <- scratch "A_loc" map_t1 [a_loc_sz]
b_loc_init <- scratch "B_loc" map_t2 [b_loc_sz]
let kkLoopBody kk0 (thd_res_merge, a_loc_init', b_loc_init') epilogue = do
kk <- letExp "kk" =<< toExp (le64 kk0 * pe64 tk)
a_loc <- forLoop ry [a_loc_init'] $ \i0 [a_loc_merge] -> do
loop_a_loc <- forLoop tk_div_tx [a_loc_merge] $ \k0 [a_loc_merge'] -> do
scatter_a_loc <- segScatter2D "A_glb2loc" a_loc_sz a_loc_merge' segthd_lvl (ty, tx) $
\(thd_y, thd_x) -> do
k <- letExp "k" =<< toExp (le64 thd_x + le64 k0 * pe64 tx)
i <- letExp "i" =<< toExp (le64 thd_y + le64 i0 * pe64 ty)
letBindNames [gtid_y] =<< toExp (le64 iii + le64 i)
a_col_idx <- letExp "A_col_idx" =<< toExp (le64 kk + le64 k)
a_elem <-
letSubExp "A_elem"
=<< eIf
( toExp $
le64 gtid_y .<. pe64 height_A
.&&. if epilogue
then le64 a_col_idx .<. pe64 common_dim
else true
)
( do
addStm load_A
res <- index "A_elem" inp_A [a_col_idx]
resultBodyM [Var res]
)
(eBody [eBlank $ Prim map_t1])
a_loc_ind <-
letSubExp "a_loc_ind"
=<< eIf
(toExp $ le64 k .<. pe64 tk)
( toExp (le64 k + le64 i * pe64 tk)
>>= letTupExp' "loc_fi"
>>= resultBodyM
)
(eBody [pure $ BasicOp $ SubExp $ intConst Int64 (-1)])
return (a_elem, a_loc_ind)
resultBodyM $ map Var scatter_a_loc
resultBodyM [Var loop_a_loc]
-- copy B from global to shared memory
b_loc <- forLoop tk_div_ty [b_loc_init'] $ \k0 [b_loc_merge] -> do
loop_b_loc <- forLoop rx [b_loc_merge] $ \j0 [b_loc_merge'] -> do
scatter_b_loc <- segScatter2D
"B_glb2loc"
b_loc_sz
b_loc_merge'
segthd_lvl
(ty, tx)
$ \(thd_y, thd_x) -> do
k <- letExp "k" =<< toExp (le64 thd_y + le64 k0 * pe64 ty)
j <- letExp "j" =<< toExp (le64 thd_x + le64 j0 * pe64 tx)
letBindNames [gtid_x] =<< toExp (le64 jjj + le64 j)
b_row_idx <- letExp "B_row_idx" =<< toExp (le64 kk + le64 k)
b_elem <-
letSubExp "B_elem"
=<< eIf
( toExp $
le64 gtid_x .<. pe64 width_B
.&&. if epilogue
then le64 b_row_idx .<. pe64 common_dim
else true
)
( do
addStm load_B
res <- index "B_elem" inp_B [b_row_idx]
resultBodyM [Var res]
)
(eBody [eBlank $ Prim map_t2])
b_loc_ind <-
letSubExp "b_loc_ind"
=<< eIf
(toExp $ le64 k .<. pe64 tk)
( toExp (le64 j + le64 k * pe64 tx_rx)
>>= letTupExp' "loc_fi"
>>= resultBodyM
)
(eBody [pure $ BasicOp $ SubExp $ intConst Int64 (-1)])
return (b_elem, b_loc_ind)
resultBodyM $ map Var scatter_b_loc
resultBodyM [Var loop_b_loc]
-- inner loop updating this thread's accumulator (loop k in mmm_kernels).
thd_acc <- forLoop tk [thd_res_merge] $ \k [acc_merge] ->
resultBodyM =<< letTupExp' "foo"
=<< eIf
( toExp $
if epilogue
then
le64 kk + le64 k
.<. pe64 common_dim
else true -- if in prologue, always compute redomap.
)
( do
reg_mem <- segMap2D "reg_mem" segthd_lvl ResultPrivate (ty, tx) $
\(ltid_y, ltid_x) -> do
asss_init <- scratch "asss_init" map_t1 [ry]
bsss_init <- scratch "bsss_init" map_t2 [rx]
asss <- forLoop ry [asss_init] $ \i [asss_merge] -> do
a_loc_ind <-
letExp "a_loc_ind"
=<< toExp
( le64 k
+ (le64 ltid_y * pe64 ry + le64 i) * pe64 tk
)
asss <-
index "A_loc_elem" a_loc [a_loc_ind]
>>= update "asss" asss_merge [i]
resultBodyM [Var asss]
bsss <- forLoop rx [bsss_init] $ \j [bsss_merge] -> do
b_loc_ind <-
letExp "b_loc_ind"
=<< toExp
( le64 j
+ le64 k * pe64 tx_rx
+ le64 ltid_x * pe64 rx
)
bsss <-
index "B_loc_elem" b_loc [b_loc_ind]
>>= update "bsss" bsss_merge [j]
resultBodyM [Var bsss]
return $ varsRes [asss, bsss]
let [asss, bsss] = reg_mem
-- the actual redomap.
redomap_res <- segMap2D "redomap_res" segthd_lvl ResultPrivate (ty, tx) $
\(ltid_y, ltid_x) -> do
as <- index "as" asss [ltid_y, ltid_x]
bs <- index "bs" bsss [ltid_y, ltid_x]
css_init <- index "css_init" acc_merge [ltid_y, ltid_x]
css <- forLoop ry [css_init] $ \i [css_merge] -> do
css <- forLoop rx [css_merge] $ \j [css_merge'] ->
resultBodyM =<< letTupExp' "foo"
=<< eIf
( toExp $
le64 iii + le64 i + pe64 ry * le64 ltid_y
.<. pe64 height_A
.&&. le64 jjj + le64 j + pe64 rx * le64 ltid_x
.<. pe64 width_B
)
( do
a <- index "a" as [i]
b <- index "b" bs [j]
c <- index "c" css_merge' [i, j]
map_res <- newVName "map_res"
map_lam' <- renameLambda map_lam
red_lam' <- renameLambda red_lam
-- the inputs to map are supposed to be permutted with the
-- inverted permutation, so as to reach the original position;
-- it just so happens that the inverse of [a,b] is [b,a]
let map_inp_reg = if var_dims == [0, 1] then [a, b] else [b, a]
addStms $
rebindLambda map_lam' map_inp_reg [map_res]
<> rebindLambda red_lam' [c, map_res] [c]
css <- update "css" css_merge' [i, j] c
resultBodyM [Var css]
)
(resultBodyM [Var css_merge'])
resultBodyM [Var css]
return [varRes css]
resultBodyM $ map Var redomap_res
)
(resultBodyM [Var acc_merge])
return [thd_acc, a_loc, b_loc]
-- build prologue.
full_tiles <-
letExp "full_tiles" $
BasicOp $ BinOp (SQuot Int64 Unsafe) common_dim tk
prologue_res_list <-
forLoop' (Var full_tiles) [cssss, a_loc_init, b_loc_init] $
\kk0 [thd_res_merge, a_loc_merge, b_loc_merge] -> do
process_full_tiles <-
kkLoopBody kk0 (thd_res_merge, a_loc_merge, b_loc_merge) False
resultBodyM $ map Var process_full_tiles
let prologue_res : a_loc_reuse : b_loc_reuse : _ = prologue_res_list
-- build epilogue.
epilogue_res_list <- kkLoopBody full_tiles (prologue_res, a_loc_reuse, b_loc_reuse) True
let redomap_res : _ = epilogue_res_list
-- support for non-empty code2'
-- segmap (ltid_y < ty, ltid_x < tx) {
-- for i < ry do
-- for j < rx do
-- res = if (iii+ltid_y*ry+i < height_A && jjj+ltid_x*rx+j < width_B)
-- then code2' else dummy
-- final_res[i,j] = res
epilogue_res <-
if patElemName redomap_orig_res == res_nm
then return redomap_res -- epilogue_res_list
else do
rssss_list <- segMap2D "rssss" segthd_lvl ResultPrivate (ty, tx) $ \(ltid_y, ltid_x) -> do
rss_init <- scratch "rss_init" (elemType res_tp) [ry, rx]
css <- index "redomap_thd" redomap_res [ltid_y, ltid_x]
ii <- letExp "ii" =<< toExp (le64 iii + le64 ltid_y * pe64 ry)
jj <- letExp "jj" =<< toExp (le64 jjj + le64 ltid_x * pe64 rx)
rss <- forLoop ry [rss_init] $ \i [rss_merge] -> do
rss' <- forLoop rx [rss_merge] $ \j [rss_merge'] -> do
c <- index "redomap_elm" css [i, j]
cpy_stm <- mkLetNamesM [patElemName redomap_orig_res] $ BasicOp $ SubExp $ Var c
addStm cpy_stm
letBindNames [gtid_y] =<< toExp (le64 ii + le64 i)
letBindNames [gtid_x] =<< toExp (le64 jj + le64 j)
res_el <-
letSubExp "res_elem"
=<< eIf
( toExp $
le64 gtid_y .<. pe64 height_A
.&&. le64 gtid_x .<. pe64 width_B
)
( do
addStms code2'
resultBodyM [Var res_nm]
)
(eBody [eBlank res_tp])
rss'' <- update' "rss" rss_merge' [i, j] res_el
resultBodyM [Var rss'']
resultBodyM [Var rss']
return [varRes rss]
let rssss : _ = rssss_list
return rssss
let regtile_ret_dims =
map (\(_, sz) -> (sz, se1, se1)) rem_outer_dims
++ [(height_A, ty, ry), (width_B, tx, rx)]
-- Add dummy dimensions to tile to reflect the outer dimensions.
epilogue_res' <-
if null rem_outer_dims
then return epilogue_res
else do
epilogue_t <- lookupType epilogue_res
let (block_dims, rest_dims) = splitAt 2 $ arrayDims epilogue_t
ones = map (const $ intConst Int64 1) rem_outer_dims
new_shape = concat [ones, block_dims, ones, rest_dims]
letExp "res_reshaped" $ BasicOp $ Reshape (map DimNew new_shape) epilogue_res
return [RegTileReturns mempty regtile_ret_dims epilogue_res']
let level' = SegGroup (Count grid_size) (Count group_size) SegNoVirt
space' = SegSpace gid_flat (rem_outer_dims ++ [(gid_y, gridDim_y), (gid_x, gridDim_x)])
kbody' = KernelBody () stms_seggroup ret_seggroup
return $ Let pat aux $ Op $ SegOp $ SegMap level' space' ts kbody'
return $ Just (host_stms, new_kernel)
mmBlkRegTiling _ = return Nothing
ceilDiv :: MonadBuilder m => SubExp -> SubExp -> m (Exp (Rep m))
ceilDiv x y = pure $ BasicOp $ BinOp (SDivUp Int64 Unsafe) x y
scratch :: MonadBuilder m => String -> PrimType -> [SubExp] -> m VName
scratch se_name t shape = letExp se_name $ BasicOp $ Scratch t shape
-- index an array with indices given in outer_indices; any inner
-- dims of arr not indexed by outer_indices are sliced entirely
index :: MonadBuilder m => String -> VName -> [VName] -> m VName
index se_desc arr outer_indices = do
arr_t <- lookupType arr
let shape = arrayShape arr_t
inner_dims = shapeDims $ stripDims (length outer_indices) shape
untouched d = DimSlice (intConst Int64 0) d (intConst Int64 1)
inner_slices = map untouched inner_dims
slice = Slice $ map (DimFix . Var) outer_indices ++ inner_slices
letExp se_desc $ BasicOp $ Index arr slice
update :: MonadBuilder m => String -> VName -> [VName] -> VName -> m VName
update se_desc arr indices new_elem = update' se_desc arr indices (Var new_elem)
update' :: MonadBuilder m => String -> VName -> [VName] -> SubExp -> m VName
update' se_desc arr indices new_elem =
letExp se_desc $ BasicOp $ Update Unsafe arr (Slice $ map (DimFix . Var) indices) new_elem
forLoop' ::
SubExp -> -- loop var
[VName] -> -- loop inits
( VName ->
[VName] -> -- (loop var -> loop inits -> loop body)
Builder GPU (Body GPU)
) ->
Builder GPU [VName]
forLoop' i_bound merge body = do
i <- newVName "i" -- could give this as arg to the function
let loop_form = ForLoop i Int64 i_bound []
merge_ts <- mapM lookupType merge
loop_inits <- mapM (\merge_t -> newParam "merge" $ toDecl merge_t Unique) merge_ts
loop_body <-
runBodyBuilder . inScopeOf loop_form . localScope (scopeOfFParams loop_inits) $
body i $ map paramName loop_inits
letTupExp "loop" $
DoLoop (zip loop_inits $ map Var merge) loop_form loop_body
forLoop ::
SubExp ->
[VName] ->
(VName -> [VName] -> Builder GPU (Body GPU)) ->
Builder GPU VName
forLoop i_bound merge body = do
res_list <- forLoop' i_bound merge body
return $ head res_list
-- given a lambda "lam", a list "new_params" of new
-- parameters which should be applied to the lambda,
-- and a VName "res_name" which the lambda result should
-- be bound to:
-- creates Stms corresponding to binding of new_params,
-- lambda body, and binding of lambda result to res_name.
rebindLambda ::
Lambda GPU ->
[VName] ->
[VName] ->
Stms GPU
rebindLambda lam new_params res_names =
stmsFromList
( zipWith
(\ident new_param -> mkLet [ident] $ BasicOp $ SubExp $ Var new_param)
idents
new_params
)
<> bodyStms lam_body
<> stmsFromList res_cpy_stms
where
(lam_params, lam_body, lam_ret_type : _) =
(lambdaParams lam, lambdaBody lam, lambdaReturnType lam)
idents =
map
(\param -> Ident (paramName param) (paramDec param))
lam_params
res_cpy_stms =
zipWith
( \res_name (SubExpRes cs lam_res) ->
certify cs $ mkLet [Ident res_name lam_ret_type] $ BasicOp $ SubExp lam_res
)
res_names
lam_ress
lam_ress = bodyResult lam_body
-- | Tries to identify the following pattern:
-- code followed by some Screma followed by more code.
matchCodeStreamCode ::
Stms GPU ->
(Stms GPU, Maybe (Stm GPU), Stms GPU)
matchCodeStreamCode kstms =
let (code1, screma, code2) =
foldl
( \acc stmt ->
case (acc, stmt) of
((cd1, Nothing, cd2), Let _ _ (Op (OtherOp Screma {}))) ->
(cd1, Just stmt, cd2)
((cd1, Nothing, cd2), _) ->
(cd1 ++ [stmt], Nothing, cd2)
((cd1, Just strm, cd2), _) ->
(cd1, Just strm, cd2 ++ [stmt])
)
([], Nothing, [])
(stmsToList kstms)
in (stmsFromList code1, screma, stmsFromList code2)
-- | Checks that all streamed arrays are variant to exacly one of
-- the two innermost parallel dimensions, and conversely, for
-- each of the two innermost parallel dimensions, there is at
-- least one streamed array variant to it. The result is the
-- number of the only variant parallel dimension for each array.
isInvarTo1of2InnerDims ::
Names ->
SegSpace ->
VarianceTable ->
[VName] ->
Maybe [Int]
isInvarTo1of2InnerDims branch_variant kspace variance arrs =
let inner_perm0 = map varToOnly1of2InnerDims arrs
inner_perm = catMaybes inner_perm0
ok1 = elem 0 inner_perm && elem 1 inner_perm
ok2 = length inner_perm0 == length inner_perm
in if ok1 && ok2 then Just inner_perm else Nothing
where
varToOnly1of2InnerDims :: VName -> Maybe Int
varToOnly1of2InnerDims arr = do
(j, _) : (i, _) : _ <- Just $ reverse $ unSegSpace kspace
let variant_to = M.findWithDefault mempty arr variance
branch_invariant =
not $ nameIn j branch_variant || nameIn i branch_variant
if not branch_invariant
then Nothing -- if i or j in branch_variant; return nothing
else
if nameIn i variant_to && not (nameIn j variant_to)
then Just 0
else
if nameIn j variant_to && not (nameIn i variant_to)
then Just 1
else Nothing
processIndirections ::
Names -> -- input arrays to redomap
Names -> -- variables on which the result of redomap depends on.
Maybe (Stms GPU, M.Map VName (Stm GPU)) ->
Stm GPU ->
Maybe (Stms GPU, M.Map VName (Stm GPU))
processIndirections arrs _ acc stm@(Let patt _ (BasicOp (Index _ _)))
| Just (ss, tab) <- acc,
[p] <- patElems patt,
p_nm <- patElemName p,
nameIn p_nm arrs =
Just (ss, M.insert p_nm stm tab)
processIndirections _ res_red_var acc stm'@(Let patt _ _)
| Just (ss, tab) <- acc,
ps <- patElems patt,
all (\p -> not (nameIn (patElemName p) res_red_var)) ps =
Just (ss Seq.|> stm', tab)
| otherwise = Nothing
se0 :: SubExp
se0 = intConst Int64 0
se1 :: SubExp
se1 = intConst Int64 1
se2 :: SubExp
se2 = intConst Int64 2
se4 :: SubExp
se4 = intConst Int64 4
se8 :: SubExp
se8 = intConst Int64 8
getParTiles :: (String, String) -> (Name, Name) -> SubExp -> Builder GPU (SubExp, SubExp)
getParTiles (t_str, r_str) (t_name, r_name) len_dim =
case len_dim of
Constant (IntValue (Int64Value 8)) ->
return (se8, se1)
Constant (IntValue (Int64Value 16)) ->
return (se8, se2)
Constant (IntValue (Int64Value 32)) ->
return (se8, se4)
_ -> do
t <- letSubExp t_str $ Op $ SizeOp $ GetSize t_name SizeTile
r <- letSubExp r_str $ Op $ SizeOp $ GetSize r_name SizeRegTile
return (t, r)
getSeqTile :: String -> Name -> SubExp -> SubExp -> SubExp -> Builder GPU SubExp
getSeqTile tk_str tk_name len_dim ty tx =
case (tx, ty) of
(Constant (IntValue (Int64Value v_x)), Constant (IntValue (Int64Value v_y))) ->
letSubExp tk_str . BasicOp . SubExp . constant $
case len_dim of
Constant (IntValue (Int64Value v_d)) -> min v_d $ min v_x v_y
_ -> min v_x v_y
_ ->
letSubExp tk_str $ Op $ SizeOp $ GetSize tk_name SizeTile
----------------------------------------------------------------------------------------------
--- 3D Tiling (RegTiling for the outermost dimension & Block tiling for the innermost two) ---
----------------------------------------------------------------------------------------------
maxRegTile :: Int64
maxRegTile = 30
mkRegTileSe :: Int64 -> SubExp
mkRegTileSe = constant
variantToDim :: VarianceTable -> VName -> VName -> Bool
variantToDim variance gid_outer nm =
gid_outer == nm || nameIn gid_outer (M.findWithDefault mempty nm variance)
-- | Checks that all streamed arrays are variant to exacly one of
-- the two innermost parallel dimensions, and conversely, for
-- each of the two innermost parallel dimensions, there is at
-- least one streamed array variant to it. The result is the
-- number of the only variant parallel dimension for each array.
isInvarTo2of3InnerDims ::
Names ->
SegSpace ->
VarianceTable ->
[VName] ->
Maybe [Int]
isInvarTo2of3InnerDims branch_variant kspace variance arrs =
let inner_perm0 = map varToOnly1of3InnerDims arrs
inner_perm = catMaybes inner_perm0
ok1 = elem 0 inner_perm && elem 1 inner_perm && elem 2 inner_perm
ok2 = length inner_perm0 == length inner_perm
in if ok1 && ok2 then Just inner_perm else Nothing
where
varToOnly1of3InnerDims :: VName -> Maybe Int
varToOnly1of3InnerDims arr = do
(k, _) : (j, _) : (i, _) : _ <- Just $ reverse $ unSegSpace kspace
let variant_to = M.findWithDefault mempty arr variance
branch_invariant =
not $
nameIn k branch_variant
|| nameIn j branch_variant
|| nameIn i branch_variant
if not branch_invariant
then Nothing -- if i or j or k in branch_variant; return nothing
else
if nameIn i variant_to && not (nameIn j variant_to || nameIn k variant_to)
then Just 0
else
if nameIn j variant_to && not (nameIn i variant_to || nameIn k variant_to)
then Just 1
else
if nameIn k variant_to && not (nameIn i variant_to || nameIn j variant_to)
then Just 2
else Nothing
-- | Expects a kernel statement as argument.
-- CONDITIONS for 3D tiling optimization to fire are:
-- 1. a) The kernel body can be broken into
-- scalar-code-1 ++ [Redomap stmt] ++ scalar-code-2.
-- b) The kernels has a per-thread result, and obviously
-- the result is variant to the 3rd dimension
-- (counted from innermost to outermost)
-- 2. For the Redomap:
-- a) the streamed arrays are one dimensional
-- b) each of the array arguments of Redomap are variant
-- to exactly one of the three innermost-parallel dimension
-- of the kernel. This condition can be relaxed by interchanging
-- kernel dimensions whenever possible.
-- 3. For scalar-code-1:
-- a) each of the statements is a slice that produces one of the
-- streamed arrays
--
-- mmBlkRegTiling :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU))
-- mmBlkRegTiling (Let pat aux (Op (SegOp (SegMap SegThread{} seg_space ts old_kbody))))
doRegTiling3D :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU))
doRegTiling3D (Let pat aux (Op (SegOp old_kernel)))
| SegMap SegThread {} space kertp (KernelBody () kstms kres) <- old_kernel,
-- build the variance table, that records, for
-- each variable name, the variables it depends on
initial_variance <- M.map mempty $ scopeOfSegSpace space,
variance <- varianceInStms initial_variance kstms,
-- we get the global-thread id for the two inner dimensions,
-- as we are probably going to use it in code generation
(gtid_x, d_Kx) : (gtid_y, d_Ky) : (gtid_z, d_M) : rem_outer_dims_rev <- reverse $ unSegSpace space,
rem_outer_dims <- reverse rem_outer_dims_rev,
-- check that the code fits the pattern having:
-- some `code1`, followed by one Screma SOAC, followed by some `code2`
(code1, Just screma_stmt, code2) <- matchCodeStreamCode kstms,
Let pat_redomap _ (Op _) <- screma_stmt,
-- checks that the Screma SOAC is actually a redomap and normalize it
Just (common_dim, inp_soac_arrs, (_, red_lam, red_nes, map_lam)) <- isTileableRedomap screma_stmt,
not (null red_nes),
-- assuming we have a budget of maxRegTile registers, we distribute
-- that budget across the result of redomap and the kernel result
num_res <- max (length red_nes) (length kres),
reg_tile <- maxRegTile `quot` fromIntegral num_res,
reg_tile_se <- mkRegTileSe reg_tile,
-- check that the element-type of the map and reduce are scalars:
all (primType . paramDec) $ lambdaParams map_lam,
red_res_tps <- map paramDec $ take (length red_nes) $ lambdaParams red_lam,
all primType red_res_tps,
-- checks that the input arrays to redomap are variant to
-- exactly one of the two innermost dimensions of the kernel
Just _ <- isInvarTo2of3InnerDims mempty space variance inp_soac_arrs,
-- get the free variables on which the result of redomap depends on
redomap_orig_res <- patElems pat_redomap,
res_red_var <- -- variance of the reduce result
mconcat $ mapMaybe ((`M.lookup` variance) . patElemName) redomap_orig_res,
mempty /= res_red_var,
-- we furthermore check that code1 is only formed by
-- 1. statements that slice some globally-declared arrays
-- to produce the input for the redomap, and
-- 2. potentially some statements on which the redomap
-- is independent; these are recorded in `code2''`
Just (code2'', arr_tab0) <-
foldl
(processIndirections (namesFromList inp_soac_arrs) res_red_var)
(Just (Seq.empty, M.empty))
code1,
-- check that code1 contains exacly one slice for each of the input array to redomap
tmp_stms <- mapMaybe (`M.lookup` arr_tab0) inp_soac_arrs,
length tmp_stms == length inp_soac_arrs,
-- code1' <- stmsFromList $ stmsToList code1 \\ stmsToList code2'',
code2' <- code2'' <> code2,
-- we assume the kernel results are variant to the thrid-outer parallel dimension
-- (for sanity sake, they should be)
ker_res_nms <- mapMaybe getResNm kres,
length ker_res_nms == length kres,
all primType kertp,
all (variantToDim variance gtid_z) ker_res_nms = do
-- HERE STARTS THE IMPLEMENTATION:
(new_kernel, host_stms) <- runBuilder $ do
-- host code
-- process the z-variant arrays that need transposition;
-- these "manifest" statements should come before the kernel
(tab_inn, tab_out) <-
foldM
(insertTranspose variance (gtid_z, d_M))
(M.empty, M.empty)
$ M.toList arr_tab0
tx_name <- nameFromString . pretty <$> newVName "Tx"
ty_name <- nameFromString . pretty <$> newVName "Ty"
tx0 <- letSubExp "Tx" $ Op $ SizeOp $ GetSize tx_name SizeTile
ty0 <- letSubExp "Ty" $ Op $ SizeOp $ GetSize ty_name SizeTile
ty <- limitTile "Ty" ty0 d_Ky
tx <- limitTile "Tx" tx0 d_Kx
let rz = reg_tile_se
gridDim_x <- letSubExp "gridDim_x" =<< ceilDiv d_Kx tx
gridDim_y <- letSubExp "gridDim_y" =<< ceilDiv d_Ky ty
gridDim_z <- letSubExp "gridDim_z" =<< ceilDiv d_M rz
let gridxyz_pexp = pe64 gridDim_z * pe64 gridDim_y * pe64 gridDim_x
let grid_pexp = product $ gridxyz_pexp : map (pe64 . snd) rem_outer_dims_rev
grid_size <- letSubExp "grid_size_tile3d" =<< toExp grid_pexp
group_size <- letSubExp "group_size_tile3d" =<< toExp (pe64 ty * pe64 tx)
let segthd_lvl = SegThread (Count grid_size) (Count group_size) SegNoVirtFull
count_shmem <- letSubExp "count_shmem" =<< ceilDiv rz group_size
gid_x <- newVName "gid_x"
gid_y <- newVName "gid_y"
gid_z <- newVName "gid_z"
gid_flat <- newVName "gid_flat"
---- in this binder: outer seggroup ----
(ret_seggroup, stms_seggroup) <- runBuilder $ do
ii <- letExp "ii" =<< toExp (le64 gid_z * pe64 rz)
jj1 <- letExp "jj1" =<< toExp (le64 gid_y * pe64 ty)
jj2 <- letExp "jj2" =<< toExp (le64 gid_x * pe64 tx)
-- initialize the register arrays corresponding to the result of redomap;
reg_arr_nms <- segMap2D "res" segthd_lvl ResultPrivate (ty, tx) $ \_ ->
forM (zip red_nes red_res_tps) $ \(red_ne, red_t) -> do
css_init <- scratch "res_init" (elemType red_t) [rz]
css <- forLoop rz [css_init] $ \i [css_merge] -> do
css' <- update' "css" css_merge [i] red_ne
resultBodyM [Var css']
return $ varRes css
-- scratch the shared-memory arrays corresponding to the arrays that are
-- input to the redomap and are invariant to the outermost parallel dimension.
loc_arr_nms <- forM (M.toList tab_out) $ \(nm, (ptp, _)) ->
scratch (baseString nm ++ "_loc") ptp [rz]
prologue_res_list <-
forLoop' common_dim (reg_arr_nms ++ loc_arr_nms) $
\q var_nms -> do
let reg_arr_merge_nms = take (length red_nes) var_nms
let loc_arr_merge_nms = drop (length red_nes) var_nms
-- collective copy from global to shared memory
loc_arr_nms' <-
forLoop' count_shmem loc_arr_merge_nms $ \tt loc_arr_merge2_nms -> do
loc_arr_merge2_nms' <-
forM (zip loc_arr_merge2_nms (M.toList tab_out)) $ \(loc_Y_nm, (glb_Y_nm, (ptp_Y, load_Y))) -> do
ltid_flat <- newVName "ltid_flat"
ltid <- newVName "ltid"
let segspace = SegSpace ltid_flat [(ltid, group_size)]
((res_v, res_i), stms) <- runBuilder $ do
offs <- letExp "offs" =<< toExp (pe64 group_size * le64 tt)
loc_ind <- letExp "loc_ind" =<< toExp (le64 ltid + le64 offs)
letBindNames [gtid_z] =<< toExp (le64 ii + le64 loc_ind)
let glb_ind = gtid_z
y_elm <-
letSubExp "y_elem"
=<< eIf
(toExp $ le64 glb_ind .<. pe64 d_M)
( do
addStm load_Y
res <- index "Y_elem" glb_Y_nm [q]
resultBodyM [Var res]
)
(eBody [eBlank $ Prim ptp_Y])
y_ind <-
letSubExp "y_loc_ind"
=<< eIf
(toExp $ le64 loc_ind .<. pe64 rz)
(toExp loc_ind >>= letTupExp' "loc_fi" >>= resultBodyM)
(eBody [pure $ BasicOp $ SubExp $ intConst Int64 (-1)])
--y_tp <- subExpType y_elm
return (y_elm, y_ind)
let ret = WriteReturns mempty (Shape [rz]) loc_Y_nm [(Slice [DimFix res_i], res_v)]
let body = KernelBody () stms [ret]
res_nms <-
letTupExp "Y_glb2loc" <=< renameExp $
Op $ SegOp $ SegMap segthd_lvl segspace [Prim ptp_Y] body
let res_nm : _ = res_nms
return res_nm
resultBodyM $ map Var loc_arr_merge2_nms'
redomap_res <-
segMap2D "redomap_res" segthd_lvl ResultPrivate (ty, tx) $
\(ltid_y, ltid_x) -> do
letBindNames [gtid_y] =<< toExp (le64 jj1 + le64 ltid_y)
letBindNames [gtid_x] =<< toExp (le64 jj2 + le64 ltid_x)
reg_arr_merge_nms_slc <- forM reg_arr_merge_nms $ \reg_arr_nm ->
index "res_reg_slc" reg_arr_nm [ltid_y, ltid_x]
fmap subExpsRes . letTupExp' "redomap_guarded"
=<< eIf
(toExp $ le64 gtid_y .<. pe64 d_Ky .&&. le64 gtid_x .<. pe64 d_Kx)
( do
inp_scals_invar_outer <-
forM (M.toList tab_inn) $ \(inp_arr_nm, load_stm) -> do
addStm load_stm
index (baseString inp_arr_nm) inp_arr_nm [q]
-- build the loop of count R whose body is semantically the redomap code
reg_arr_merge_nms' <-
forLoop' rz reg_arr_merge_nms_slc $ \i reg_arr_mm_nms -> do
letBindNames [gtid_z] =<< toExp (le64 ii + le64 i)
resultBodyM =<< letTupExp' "redomap_lam"
=<< eIf
(toExp $ le64 gtid_z .<. pe64 d_M)
( do
-- read from shared memory
ys <- forM loc_arr_nms' $ \loc_arr_nm ->
index "inp_reg_var2z" loc_arr_nm [i]
cs <- forM reg_arr_mm_nms $ \reg_arr_nm ->
index "res_reg_var2z" reg_arr_nm [i]
-- here we need to put in order the scalar inputs to map:
let tab_scals =
M.fromList $
zip (map fst $ M.toList tab_out) ys
++ zip (map fst $ M.toList tab_inn) inp_scals_invar_outer
map_inp_scals <- forM inp_soac_arrs $ \arr_nm ->
case M.lookup arr_nm tab_scals of
Nothing -> error "Impossible case reached in tiling3D\n"
Just nm -> return nm
map_res_scals <- forM (lambdaReturnType map_lam) $ \_ -> newVName "map_res"
map_lam' <- renameLambda map_lam
red_lam' <- renameLambda red_lam
addStms $
rebindLambda map_lam' map_inp_scals map_res_scals
<> rebindLambda red_lam' (cs ++ map_res_scals) cs
css <- forM (zip reg_arr_mm_nms cs) $ \(reg_arr_nm, c) ->
update (baseString reg_arr_nm) reg_arr_nm [i] c
resultBodyM $ map Var css
)
(resultBodyM $ map Var reg_arr_mm_nms)
resultBodyM $ map Var reg_arr_merge_nms'
)
(resultBodyM $ map Var reg_arr_merge_nms_slc)
resultBodyM $ map Var $ redomap_res ++ loc_arr_nms'
-- support for non-empty code2'
-- segmap (ltid_y < ty, ltid_x < tx) {
-- for i < rz do
-- res = if (ii+i < d_M && jj1+ltid_y < d_Ky && jj2 + ltid_x < d_Kx)
-- then code2' else dummy
-- final_res[i] = res
let redomap_res = take (length red_nes) prologue_res_list
epilogue_res <-
if length redomap_orig_res == length ker_res_nms
&& ker_res_nms == map patElemName redomap_orig_res
then -- all (\ (a,b) -> patElemName a == b ) $ zip redomap_orig_res ker_res_nms
segMap3D "rssss" segthd_lvl ResultPrivate (se1, ty, tx) $ \(_ltid_z, ltid_y, ltid_x) ->
forM (zip kertp redomap_res) $ \(res_tp, res) -> do
rss_init <- scratch "rss_init" (elemType res_tp) [rz, se1, se1]
fmap varRes $
forLoop rz [rss_init] $ \i [rss] -> do
let slice = Slice [DimFix $ Var i, DimFix se0, DimFix se0]
thread_res <- index "thread_res" res [ltid_y, ltid_x, i]
rss' <- letSubExp "rss" $ BasicOp $ Update Unsafe rss slice $ Var thread_res
resultBodyM [rss']
else segMap3D "rssss" segthd_lvl ResultPrivate (se1, ty, tx) $ \(_ltid_z, ltid_y, ltid_x) -> do
letBindNames [gtid_y] =<< toExp (le64 jj1 + le64 ltid_y)
letBindNames [gtid_x] =<< toExp (le64 jj2 + le64 ltid_x)
rss_init <- forM kertp $ \res_tp ->
scratch "rss_init" (elemType res_tp) [rz, se1, se1]
rss <- forLoop' rz rss_init $ \i rss_merge -> do
letBindNames [gtid_z] =<< toExp (le64 ii + le64 i)
forM_ (zip redomap_orig_res redomap_res) $ \(o_res, n_res) -> do
c <- index "redomap_thd" n_res [ltid_y, ltid_x, i]
letBindNames [patElemName o_res] =<< toExp (le64 c)
return c
res_els <-
letTupExp' "res_elem"
=<< eIf
( toExp $
le64 gtid_y .<. pe64 d_Ky
.&&. le64 gtid_x .<. pe64 d_Kx
.&&. le64 gtid_z .<. pe64 d_M
)
( do
addStms code2'
resultBodyM $ map Var ker_res_nms
)
(eBody $ map eBlank kertp)
rss' <- forM (zip res_els rss_merge) $ \(res_el, rs_merge) -> do
let slice = Slice [DimFix $ Var i, DimFix se0, DimFix se0]
letSubExp "rss" $ BasicOp $ Update Unsafe rs_merge slice res_el
resultBodyM rss'
return $ varsRes rss
----------------------------------------------------------------
-- Finally, reshape the result arrays for the RegTileReturn ---
----------------------------------------------------------------
let regtile_ret_dims =
map (\(_, sz) -> (sz, se1, se1)) rem_outer_dims
++ [(d_M, se1, rz), (d_Ky, ty, se1), (d_Kx, tx, se1)]
epilogue_res' <- forM epilogue_res $ \res ->
if null rem_outer_dims
then return res
else do
-- Add dummy dimensions to tile to reflect the outer dimensions
res_tp' <- lookupType res
let (block_dims, rest_dims) = splitAt 2 $ arrayDims res_tp'
ones = map (const se1) rem_outer_dims
new_shape = concat [ones, block_dims, ones, rest_dims]
letExp "res_reshaped" $ BasicOp $ Reshape (map DimNew new_shape) res
return $ map (RegTileReturns mempty regtile_ret_dims) epilogue_res'
-- END (ret_seggroup, stms_seggroup) <- runBuilder $ do
let level' = SegGroup (Count grid_size) (Count group_size) SegNoVirt
space' = SegSpace gid_flat (rem_outer_dims ++ [(gid_z, gridDim_z), (gid_y, gridDim_y), (gid_x, gridDim_x)])
kbody' = KernelBody () stms_seggroup ret_seggroup
return $ Let pat aux $ Op $ SegOp $ SegMap level' space' kertp kbody'
-- END (new_kernel, host_stms) <- runBuilder $ do
return $ Just (host_stms, new_kernel)
where
getResNm (Returns ResultMaySimplify _ (Var res_nm)) = Just res_nm
getResNm _ = Nothing
limitTile :: String -> SubExp -> SubExp -> Builder GPU SubExp
limitTile t_str t d_K = letSubExp t_str $ BasicOp $ BinOp (SMin Int64) t d_K
insertTranspose ::
VarianceTable ->
(VName, SubExp) ->
(M.Map VName (Stm GPU), M.Map VName (PrimType, Stm GPU)) ->
(VName, Stm GPU) ->
Builder GPU (M.Map VName (Stm GPU), M.Map VName (PrimType, Stm GPU))
insertTranspose variance (gidz, _) (tab_inn, tab_out) (p_nm, stm@(Let patt yy (BasicOp (Index arr_nm slc))))
| [p] <- patElems patt,
ptp <- elemType $ patElemType p,
p_nm == patElemName p =
case L.findIndices (variantSliceDim variance gidz) (unSlice slc) of
[] -> return (M.insert p_nm stm tab_inn, tab_out)
i : _ -> do
arr_tp <- lookupType arr_nm
let perm = [i + 1 .. arrayRank arr_tp -1] ++ [0 .. i]
let arr_tr_str = baseString arr_nm ++ "_transp"
arr_tr_nm <- letExp arr_tr_str $ BasicOp $ Manifest perm arr_nm
let e_ind' = BasicOp $ Index arr_tr_nm slc
let stm' = Let patt yy e_ind'
return (tab_inn, M.insert p_nm (ptp, stm') tab_out)
insertTranspose _ _ _ _ = error "\nUnreachable case reached in insertTranspose case, doRegTiling3D\n"
variantSliceDim :: VarianceTable -> VName -> DimIndex SubExp -> Bool
variantSliceDim variance gidz (DimFix (Var vnm)) = variantToDim variance gidz vnm
variantSliceDim _ _ _ = False
doRegTiling3D _ = return Nothing
|
HIPERFIT/futhark
|
src/Futhark/Optimise/BlkRegTiling.hs
|
isc
| 48,569 | 0 | 55 | 17,993 | 12,017 | 5,929 | 6,088 | 743 | 8 |
{-# LANGUAGE BangPatterns #-}
module DataStructures (module DataStructures, num) where
import Graphics.Rendering.OpenGL as GL
import Graphics.UI.GLFW as GLFW
import Numeric.Units.Dimensional.Prelude as D
import Numeric.Units.Dimensional.NonSI
import qualified Prelude
import Physics
data Keyboard = Keyboard {
keya :: KeyButtonState,
keyb :: KeyButtonState,
keyc :: KeyButtonState,
keyd :: KeyButtonState,
keye :: KeyButtonState,
keyf :: KeyButtonState,
keyg :: KeyButtonState,
keyh :: KeyButtonState,
keyi :: KeyButtonState,
keyj :: KeyButtonState,
keyk :: KeyButtonState,
keyl :: KeyButtonState,
keym :: KeyButtonState,
keyn :: KeyButtonState,
keyo :: KeyButtonState,
keyp :: KeyButtonState,
keyq :: KeyButtonState,
keyr :: KeyButtonState,
keys :: KeyButtonState,
keyt :: KeyButtonState,
keyu :: KeyButtonState,
keyv :: KeyButtonState,
keyw :: KeyButtonState,
keyx :: KeyButtonState,
keyy :: KeyButtonState,
keyz :: KeyButtonState,
key0 :: KeyButtonState,
key1 :: KeyButtonState,
key2 :: KeyButtonState,
key3 :: KeyButtonState,
key4 :: KeyButtonState,
key5 :: KeyButtonState,
key6 :: KeyButtonState,
key7 :: KeyButtonState,
key8 :: KeyButtonState,
key9 :: KeyButtonState
} deriving (Show)
data Mouse = Mouse {
pos :: Position,
leftButton :: KeyButtonState,
rightButton :: KeyButtonState
} deriving (Show)
type DataMass = D.Mass GLdouble
type DataLength = D.Length GLdouble
type DataVelocity = D.Velocity GLdouble
type DataAcceleration = D.Acceleration GLdouble
type ObjPosition = Vector3 (D.Length GLdouble)
type ObjOrientation = Vector3 (Dimensionless GLdouble)
type ObjVelocity = Vector3 (Velocity GLdouble)
type ObjAcceleration = Vector3 (Acceleration GLdouble)
type ObjMass = Mass GLdouble
type ObjRadius = D.Length GLdouble
type Point = Vector3 GLdouble
au :: Num a => Unit DLength a
au = astronomicalUnit
data Object = Object !ObjPosition !ObjOrientation !ObjVelocity !ObjAcceleration !ObjMass deriving Show
data Sphere = Sphere !Object !ObjRadius deriving Show
standardSphere = (DataStructures.Sphere standardObject ((num 10) * m))
where m = 1 *~ meter
standardObject = (Object (Vector3 m m m) (Vector3 o o o) (Vector3 v v v) (Vector3 a a a) (1 *~ kilo gram))
where m = 1 *~ meter
v = 0 *~ (meter / second)
a = 0 *~ (meter / second / second)
o = 1 *~ one
deMeterize a = a /~ meter
vectorDeMeterize (Vector3 a b c) = (Vector3 (deMeterize a) (deMeterize b) (deMeterize c))
vectorSubstract (Vector3 v1x v1y v1z) (Vector3 v2x v2y v2z) = (Vector3 (v1x-v2x) (v1y-v2y) (v1z-v2z))
vectorAdd (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = (Vector3 (x1+x2) (y1+y2) (z1+z2))
vectorNormalize v = vectorTimesScalar v ((num 1) / (vectorMagnitude v))
vectorTimesScalar (Vector3 x y z) s = (Vector3 (x*s) (y*s) (z*s))
--this function is a problem, in terms of performance
vectorMagnitude (Vector3 vx vy vz) = sqrt (vx * vx + vy * vy + vz * vz)
vectorSqrtMagnitude (Vector3 vx vy vz) = vx * vx + vy * vy + vz * vz
vectorNormalizeDivMagniutde v = vectorTimesScalar v ((num 1) / (vectorSqrtMagnitude v))
getPos (Object p _ _ _ _) = p
deMass a = a /~ (kilo gram)
|
Stratege/NBody-Simulation
|
dataStructures.hs
|
mit
| 3,085 | 5 | 11 | 493 | 1,105 | 618 | 487 | 98 | 1 |
-- | Data.TSTP.AtomicWord module.
-- Adapted from https://github.com/agomezl/tstp2agda.
{-# LANGUAGE UnicodeSyntax #-}
module Data.TSTP.AtomicWord
( AtomicWord ( AtomicWord )
) where
------------------------------------------------------------------------------
import Athena.Utils.PrettyPrint ( Pretty(pretty) )
import Athena.Translation.Utils ( stdName )
------------------------------------------------------------------------------
newtype AtomicWord = AtomicWord String
deriving (Eq, Ord, Read, Show)
instance Pretty AtomicWord where
pretty (AtomicWord "$false") = pretty "⊥"
pretty (AtomicWord a) = pretty . stdName $ a
|
jonaprieto/athena
|
src/Data/TSTP/AtomicWord.hs
|
mit
| 654 | 0 | 8 | 88 | 121 | 71 | 50 | 13 | 0 |
--- import Data.STRef
--- import Control.Monad.ST.Safe
--- import Control.Monad (replicateM_)
--main = (putStrLn . show) stResult
module HigherRank where
--- stResult = runST $ do ref <- newSTRef 0
--- replicateM_ 1000000 $ modifySTRef' ref (+1)
--- readSTRef ref
---
--- Can't be done!
--- v = runST (newSTRef "abc")
foo :: (forall a. a -> a) -> (Char,Bool)
foo f = (f 'c', f True)
bar :: forall a. ((a -> a) -> (Char, Bool))
bar f = ('c', True)
applyTuple :: (forall a. [a] -> Int) -> ([b], [c]) -> (Int, Int)
applyTuple f (bs, cs) = (f(bs), f(cs))
|
nlim/haskell-playground
|
src/HigherRank.hs
|
mit
| 609 | 0 | 9 | 159 | 185 | 112 | 73 | -1 | -1 |
module Main where
import Data.List
import System.Environment
import System.Directory
import Scheme.Printer
import Scheme.Parser
import Scheme.Evaluator
import Scheme.REPL
main :: IO ()
main = do
args <- getArgs
case args of
["-i"] -> lispRepl emptyEnv False
["-i", "-v"] -> lispRepl emptyEnv True
(file:rest) -> do
ok <- doesFileExist file
let verbose =
case rest of
["-v"] -> True
_ -> False
if ok
then interpretFile file verbose
else putStrLn $ "File " ++ file ++ " doesn't exist."
_ -> putStrLn "Usage: lisp ( file [-v] | -i [-v] )\n\n\t-i\tStarts the REPL.\n\t-v\tDisplays evaluation details.\n"
interpretFile :: FilePath -> Bool -> IO ()
interpretFile path verbose = do
content <- readFile path
let evaluated = evalSource emptyEnv $ parseLisp content
if verbose
then print evaluated
else putStrLn $ intercalate "\n" $ map printLisp $ evaluationResult evaluated
|
darthdeus/scheme
|
Main.hs
|
mit
| 985 | 0 | 18 | 253 | 279 | 139 | 140 | 31 | 6 |
{-# LANGUAGE OverloadedLists #-}
module Irg.Lab2.Geometry.Shapes where
import qualified Irg.Lab2.Geometry.Vector as V
import qualified Data.Vector as V2
import Data.Maybe
import Debug.Trace
type Number = Float
myTrace :: Show a => a -> a
myTrace x = if False then traceShowId x else x
polygonFill :: Polygon -> [(Dot, Dot)]
polygonFill p@(Polygon poly)
| polygonOrientation p /= Clockwise = error "The polygon has to be oriented clockwise"
| otherwise = mapMaybe getPolyLineForY ([minimum ys .. maximum ys] :: [Number])
where
edges = myTrace $ polygonEdges p
len = length poly
ys = map ((V2.! 1) . unpackDot) $ V.toList poly
yOfNthVertex n = unpackDot (poly V2.! n) V2.! 1
leftEdges = myTrace $ map fst $ filter (\(_, i) -> yOfNthVertex i < yOfNthVertex ((i+1) `mod` len)) $ zip edges [0..]
rightEdges = filter (`notElem` leftEdges) edges
getXsOfEdgesOnY edgess y = mapMaybe (getXOfIntersection y) edgess
getPolyLineForY y
| null (getXsOfEdgesOnY rightEdges y) || null (getXsOfEdgesOnY leftEdges y) = Nothing
| l < d = Just (Dot [l, y, 1], Dot [d, y, 1])
| otherwise = Nothing
where
l = maximum (myTrace $ getXsOfEdgesOnY leftEdges y)
d = minimum (getXsOfEdgesOnY rightEdges y)
toListWithValid :: Int -> V.Vector Number -> [Number]
toListWithValid n vec
| length vec == n = V.toList vec
| otherwise = error $ "Invalid vector size (" ++ show (length vec) ++ ")"
fromListWithValid :: Int -> [Number] -> V.Vector Number
fromListWithValid n ls
| length ls == n = V.fromList ls
| otherwise = error $ "Invalid list size (" ++ show (length ls) ++ ")"
data Dot = Dot (V.Vector Number) deriving (Eq, Show)
data Line = Line (V.Vector Number) deriving (Eq, Show)
data Polygon = Polygon (V.Vector Dot) deriving (Eq, Show)
data Location = Above | On | Under deriving (Eq, Show)
data InOut = Inside | Outside deriving (Eq, Show)
data Orientation = Clockwise | Counterclockwise | Neither deriving (Eq, Show)
relationDotLine :: Dot -> Line -> Location
relationDotLine dot line
| scalar > 0 = Above
| scalar == 0 = On
| otherwise = Under
where scalar = V.scalarProduct (unpackDot dot) (unpackLine line)
relationDotPolyNthEdge :: Int -> Dot -> Polygon -> Location
relationDotPolyNthEdge n dot poly = relationDotLine dot (polygonEdges poly !! n)
isDotInsidePolygon :: Dot -> Polygon -> Bool
isDotInsidePolygon dot poly = above && (orientation == Counterclockwise) || under && (orientation == Clockwise)
where
under = all ((Above /=) . relationDotLine dot) $ polygonEdges poly
above = all ((Under /=) . relationDotLine dot) $ polygonEdges poly
orientation = polygonOrientation poly
lineFromDots :: Dot -> Dot -> Line
lineFromDots (Dot d1) (Dot d2) = Line $ V.vectorProduct d1 d2
polygonEdges :: Polygon -> [Line]
polygonEdges (Polygon poly) = fmap (\i -> lineFromDots (poly V2.! i) (poly V2.! ((i+1) `mod` len))) lens
where
lens = [0..len-1]
len = length poly
polygonOrientation :: Polygon -> Orientation
polygonOrientation p@(Polygon poly)
| clockwise = Clockwise
| counterclockwise = Counterclockwise
| otherwise = Neither
where
edges = polygonEdges p
len = length poly
lens = [0..len-1] :: [Int]
relationPolyEdgeAndNextVertex i = relationDotLine (poly V2.! ((i + 2) `mod` len)) (edges !! i)
clockwise = all ((Above /=) . relationPolyEdgeAndNextVertex) lens
counterclockwise = all ((Under /=) . relationPolyEdgeAndNextVertex) lens
getXOfIntersection :: Number -> Line -> Maybe Number
getXOfIntersection y (Line edge)
| edge V2.! 0 == 0 = Nothing
| otherwise = Just ((-(edge V2.! 1) * y - (edge V2.! 2)) / (edge V2.! 0))
reversePolygon :: Polygon -> Polygon
reversePolygon = polygonFromLists . reverse . polygonToLists
polygonToClockwise :: Polygon -> Polygon
polygonToClockwise poly
| polygonOrientation poly == Counterclockwise = reversePolygon poly
| polygonOrientation poly == Neither = error "Neither clockwise nor counterclockwise"
| otherwise = poly
unpackDot :: Dot -> V.Vector Number
unpackDot (Dot a) = a
unpackLine :: Line -> V.Vector Number
unpackLine (Line a) = a
unpackPolygon :: Polygon -> V.Vector Dot
unpackPolygon (Polygon a) = a
dotFromList :: [Number] -> Dot
dotFromList = Dot . fromListWithValid 3
dotToList :: Dot -> [Number]
dotToList = toListWithValid 3 . unpackDot
lineFromList :: [Number] -> Line
lineFromList = Line . fromListWithValid 3
lineToList :: Line -> [Number]
lineToList = toListWithValid 3 . unpackLine
polygonFromLists :: [[Number]] -> Polygon
polygonFromLists = Polygon . V.fromList . map dotFromList
polygonToLists :: Polygon -> [[Number]]
polygonToLists = map (V.toList . unpackDot) . V.toList . unpackPolygon
|
DominikDitoIvosevic/Uni
|
IRG/src/Irg/Lab2/Geometry/Shapes.hs
|
mit
| 4,980 | 0 | 17 | 1,164 | 1,804 | 939 | 865 | 99 | 2 |
{-# LANGUAGE FlexibleInstances, IncoherentInstances #-}
------------------------------------------------------------------------------
module Snap.Snaplet.Rest.Resource.Internal
( Resource (..)
, resource
, complete
, PutAction (..)
) where
------------------------------------------------------------------------------
import Control.Applicative
import Data.ByteString (ByteString)
import Data.Maybe
import Network.HTTP.Media (MediaType)
import Snap.Core (Params)
------------------------------------------------------------------------------
import Snap.Snaplet.Rest.FromRequest.Internal (FromRequest (..))
import Snap.Snaplet.Rest.Proxy (Proxy (..))
------------------------------------------------------------------------------
-- | A resource descriptor for the type 'res'. The resource runs in the monad
-- 'm', identifies resources with values of the type 'id', and describes
-- changes with value of the type 'diff'.
data Resource res m id diff = Resource
{ renderers :: [(MediaType, res -> m ByteString)]
, parsers :: [(MediaType, ByteString -> m (Maybe res))]
, diffParsers :: [(MediaType, ByteString -> m (Maybe diff))]
, listRenderers :: [(MediaType, [res] -> m ByteString)]
, listParsers :: [(MediaType, ByteString -> m (Maybe [res]))]
, create :: Maybe (res -> m ())
, retrieve :: Maybe (id -> m [res])
, update :: Maybe (id -> diff -> m Bool)
, toDiff :: Maybe (res -> diff)
, delete :: Maybe (id -> m Bool)
, fromParams :: Maybe (Params -> Maybe id)
, putAction :: Maybe PutAction
, patchEnabled :: Bool
}
------------------------------------------------------------------------------
class Diff a b where
defaultToDiff :: Maybe (a -> b)
isDifferentType :: Proxy (a, b) -> Bool
instance Diff a a where
defaultToDiff = Just id
isDifferentType _ = False
instance Diff a b where
defaultToDiff = Nothing
isDifferentType _ = True
------------------------------------------------------------------------------
-- | The empty resource descriptor, useful as a starting point for building
-- resources.
resource :: Resource res m id diff
resource = Resource [] [] [] [] []
Nothing Nothing Nothing Nothing Nothing Nothing Nothing False
------------------------------------------------------------------------------
complete :: FromRequest id => Resource res m id diff -> Resource res m id diff
complete = complete' Proxy
complete'
:: FromRequest id
=> Proxy (res, diff) -> Resource res m id diff -> Resource res m id diff
complete' p r = r
{ toDiff = toDiff r <|> defaultToDiff
, fromParams = fromParams r <|> defaultFromParams
, putAction = putAction r <|> defaultPutAction
, patchEnabled = isDifferentType p
}
where
hasCreate = isJust $ create r
hasUpdate = isJust $ update r
defaultPutAction
| hasCreate && not hasUpdate = Just Create
| hasUpdate && not hasCreate = Just Update
| otherwise = Nothing
------------------------------------------------------------------------------
-- | Indicates which action that a PUT request should take for a resource.
data PutAction
= Create -- ^ Always create
| Update -- ^ Always update
deriving (Eq, Show)
|
zmthy/snaplet-rest
|
src/Snap/Snaplet/Rest/Resource/Internal.hs
|
mit
| 3,369 | 0 | 15 | 726 | 798 | 444 | 354 | -1 | -1 |
msum :: Integer -> Integer
msum 0 = 0
msum n = n + (msum (n-1))
main = print (msum 500)
|
lucas8/MPSI
|
ipt/recursive/misc/sum.hs
|
mit
| 91 | 0 | 9 | 24 | 57 | 29 | 28 | 4 | 1 |
module Lib where
import Data.List (intercalate)
-- from Chapter 8
digitToWord :: Int -> String
digitToWord 0 = "zero"
digitToWord 1 = "one"
digitToWord 2 = "two"
digitToWord 3 = "three"
digitToWord 4 = "four"
digitToWord 5 = "five"
digitToWord 6 = "six"
digitToWord 7 = "seven"
digitToWord 8 = "eight"
digitToWord 9 = "nine"
-- works - just a little ugly
--digits :: Int -> [Int]
--digits n = map (\c -> (read [c]) :: Int) (show n)
digits :: Int -> [Int]
digits n = go n []
where go n acc
| n < 10 = mod n 10 : acc
| otherwise = go (div n 10) (mod n 10 : acc)
wordNumber :: Int -> String
wordNumber n = intercalate "-" digitsArray
where digitsArray = map digitToWord (digits n)
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter14/WordNumber/src/Lib.hs
|
mit
| 708 | 0 | 11 | 164 | 239 | 122 | 117 | 21 | 1 |
{-# LANGUAGE RecordWildCards, NamedFieldPuns, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Galua.Micro.Type.Eval
( analyze, analyzeFun, Result(..), GlobalBlockName(..), QualifiedBlockName(..)
, valueCasesM
) where
import Control.Monad
import Data.Map ( Map )
import qualified Data.Map as Map
import Data.Set ( Set )
import qualified Data.Set as Set
import qualified Data.ByteString as BS
import Text.PrettyPrint
import Galua.Micro.AST
import Galua.Micro.Type.Value
import Galua.Micro.Type.Pretty()
import Galua.Micro.Type.Monad
import Galua.Pretty
regCasesM :: Reg -> BlockM SingleV
regCasesM reg =
do regVal <- getReg reg
value <- regValCasesM regVal
assign reg (RegVal (fromSingleV value))
return value
exprCasesM :: Expr -> BlockM SingleV
exprCasesM = regValCasesM <=< evalExpr
regValCasesM :: RegVal -> BlockM SingleV
regValCasesM = valueCasesM <=< regValToVal
valueCasesM :: AnalysisM m => Value -> m SingleV
valueCasesM v = options (valueCases v)
data Next = EnterBlock BlockName
| RaiseError Value
| Continue
| ReturnWith (List Value)
-- Does not return bottom
evalExpr :: Expr -> BlockM RegVal
evalExpr expr =
case expr of
EReg r -> getReg r
EUp u -> getUpVal u
ELit l ->
case l of
LNil -> ret (BasicValue Nil)
LBool b -> ret (BooleanValue (NotTop b))
LNum _ -> ret (BasicValue Number)
LInt _ -> ret (BasicValue Number)
LStr b -> ret (StringValue (NotTop b))
where
ret = return . RegVal . fromSingleV
regValToRef :: RegVal -> BlockM (Maybe RefId)
regValToRef rv =
case rv of
RegBottom -> impossible
RegVal _ -> error "[bug] regValToRef got a val, not a ref"
RegRef r -> case r of
Top -> return Nothing
NotTop xs -> Just <$> options (Set.toList xs)
regValToVal :: RegVal -> BlockM Value
regValToVal rv =
case rv of
RegBottom -> impossible
RegVal v -> return v
RegRef _ -> error "[bu] regValToVal got a ref, not a val"
raiseError :: Value -> BlockM Next
raiseError v =
do raisesError v
return (RaiseError v)
evalEndStmt :: BlockStmt EndStmt -> BlockM Next
evalEndStmt stmt =
logTrace ("END STMT: " ++ show (pp stmt)) >>
case stmtCode stmt of
Raise e -> raiseError =<< regValToVal =<< evalExpr e
Goto b -> return (EnterBlock b)
Return -> do vs <- getList ListReg
return (ReturnWith vs)
Case e alts dflts ->
do v <- regValToVal =<< evalExpr e
let inDflt = case dflts of
Nothing -> impossible
Just bn -> upd bn (foldl rmAlt v (map fst alts))
alt (vt,bn) =
let check v' = upd bn (v /\ v')
in case vt of
NumberType -> check (basic Number)
NilType -> check (basic Nil)
UserDataType -> check (basic UserData)
LightUserDataType -> check (basic LightUserData)
ThreadType -> check (basic Thread)
BoolType ->
check bottom { valueBoolean = valueBoolean v }
StringType ->
check bottom { valueString = valueString v }
FunctionType ->
check bottom { valueFunction = valueFunction v }
TableType ->
check bottom { valueTable = valueTable v }
join $ options (inDflt : map alt alts)
where
upd bn v' | v' == bottom = impossible
| otherwise = do case e of
EReg r -> assign r (RegVal v')
ELit _ -> return ()
EUp _ -> error "up index in case"
return (EnterBlock bn)
rmAlt v' ty =
let rmBasic t = v' { valueBasic = Set.delete t (valueBasic v') }
in case ty of
NumberType -> rmBasic Number
NilType -> rmBasic Nil
UserDataType -> rmBasic UserData
LightUserDataType -> rmBasic LightUserData
ThreadType -> rmBasic Thread
BoolType -> v' { valueBoolean = bottom }
StringType -> v' { valueString = bottom }
FunctionType -> v' { valueFunction = bottom }
TableType -> v' { valueTable = bottom }
If (Prop p es) t f ->
do vs <- mapM (regValToVal <=< evalExpr) es
case (p,vs) of
(Equals, [v1,v2]) ->
do let newV = v1 /\ v2
upd e = case e of
EReg r -> assign r (RegVal newV)
ELit _ -> return ()
EUp _ -> error "UpVal in if?"
-- XXX: propagate some -ve info?
-- Currently (/= nil) seems the only possibly interesting one,
-- but maybe tracking some -ve information might be useful.
if newV == bottom
then return (EnterBlock f)
else join
$ options
[ do upd (es !! 0)
upd (es !! 1)
return (EnterBlock t)
, return (EnterBlock f)
]
_ -> options [ EnterBlock t, EnterBlock f ]
TailCall fun ->
do vs <- getList ListReg
FunctionValue fid <- regCasesM fun
next <- callFun fid vs
case next of
Left v -> raiseError v
Right xs -> return (ReturnWith xs)
evalStmt :: BlockStmt Stmt -> BlockM Next
evalStmt stmt =
logTrace ("STMT: " ++ show (pp stmt)) >>
case stmtCode stmt of
Assign r e -> do assign r =<< evalExpr e
return Continue
AssignListReg tgt src -> do setList tgt =<< getList src
return Continue
SetUpVal {} -> error "SetUpVal"
NewTable r ->
do here <- newTableId
assign r (RegVal (newTable here))
return Continue
LookupTable r t i ->
do TableValue l <- regCasesM t
ti <- exprCasesM i
assign r =<< fmap RegVal (getTable l ti)
return Continue
SetTable t i v ->
do val <- regValToVal =<< evalExpr v
TableValue l <- regCasesM t
ti <- regValToVal =<< evalExpr i
setTable l ti val
return Continue
SetTableList t _ ->
do vs <- getList ListReg
let vr = appListAll vs
TableValue tv <- regCasesM t
setTable tv (basic Number) vr
return Continue
GetMeta r e ->
-- Note: XXX: we don't really need to expand function values completely,
-- as they all give the same result.
do v <- exprCasesM e
GlobalState { basicMetas, stringMeta, funMeta, booleanMeta } <- getGlobal
newV <- case v of
TableValue l -> getTableMeta l
BasicValue t -> return (appFun basicMetas t)
StringValue _ -> return stringMeta
BooleanValue{} -> return booleanMeta
FunctionValue _ -> return funMeta
when (newV == bottom) impossible
assign r (RegVal newV)
return Continue
NewClosure r proto fun ->
do let ups = funcUpvalRefExprs fun
upRs' <- mapM (regValToRef <=< evalExpr) ups
let upRs = case sequence upRs' of
Just rs -> rs
Nothing -> error "NewClosure: TOP references?"
fid <- newFunId proto upRs
assign r (RegVal (newFun fid))
return Continue
CloseStack _ -> error "CloseStack"
-- Functions
Call fun ->
do vs <- getList ListReg
FunctionValue fid <- regCasesM fun
next <- callFun fid vs
case next of
Left v -> raiseError v
Right xs -> do setList ListReg xs
return Continue
-- Lists
Append xs es ->
do ves <- mapM (regValToVal <=< evalExpr) es
oldvs <- getList xs
setList xs (listAppend ves oldvs)
return Continue
SetList xs es ->
do ves <- mapM (regValToVal <=< evalExpr) es
let nil = listConst (basic Nil)
setList xs (listAppend ves nil)
return Continue
Drop xs n ->
do vs <- getList xs
setList xs (listDrop n vs)
return Continue
IndexList r xs n ->
do vs <- getList xs
assign r (RegVal (appList vs n))
return Continue
-- Arith
Arith2 r op e1 e2 ->
do ve1 <- regValToVal =<< evalExpr e1
ve2 <- regValToVal =<< evalExpr e2
let vr = case op of
NumberAdd -> basic Number
NumberSub -> basic Number
NumberMul -> basic Number
NumberPow -> basic Number
FMod -> basic Number
IMod -> basic Number
IDiv -> basic Number
NumberDiv -> basic Number
And -> basic Number
Or -> basic Number
Xor -> basic Number
Shl -> basic Number
Shr -> basic Number
Concat ->
case (valueString ve1, valueString ve2) of
(OneValue x, OneValue y) ->
bottom { valueString = OneValue (BS.append x y) }
_ -> anyString
assign r (RegVal vr)
return Continue
Arith1 r op e ->
do ve <- regValToVal =<< evalExpr e
let vr = case op of
ToNumber ->
let veNum = ve /\ basic Number
in joins
[ veNum
, if veNum /= ve then basic Nil else bottom
]
ToInt -> basic Nil \/
(if ve /\ (basic Number \/ anyString) /= bottom
then basic Number else bottom)
ToString ->
let veNum = ve /\ basic Number
veStr = ve /\ anyString
veNumStr = ve /\ (basic Number \/ anyString)
in joins
[ veStr
, if veNumStr /= ve then basic Nil else bottom
, if veNum /= bottom then anyString else bottom
]
IntToDouble -> basic Number
StringLen -> basic Number
TableLen -> basic Number
NumberUnaryMinus -> basic Number
Complement -> basic Number
ToBoolean -> anyBoolean -- TODO: Implement logic
BoolNot -> anyBoolean
assign r (RegVal vr)
return Continue
-- References
NewRef r e ->
do ve <- regValToVal =<< evalExpr e
here <- newRefId ve
assign r (newRef here)
return Continue
ReadRef r e ->
do ref <- regValToRef =<< evalExpr e
vr <- readRefId ref
assign r (RegVal vr)
return Continue
WriteRef r e ->
do ref <- regValToRef =<< evalExpr r
ve <- regValToVal =<< evalExpr e
writeRefId ref ve
return Continue
-- Misc
Comment _ -> return Continue
--------------------------------------------------------------------------------
evalBlock :: AnalysisM m => GlobalBlockName -> State -> m (Next, State)
evalBlock bn s = inBlock bn s go
where
go = do logTrace ("BLOCK: " ++ show (pp bn))
st <- curStmt
next <- case st of
Left norm -> evalStmt norm
Right end -> evalEndStmt end
case next of
Continue -> continue >> go
_ -> return next
callFun :: WithTop ClosureId -> List Value -> BlockM (Either Value (List Value))
callFun mb as = case mb of
Top -> doCall =<< anyFunId
NotTop f -> doCall f
where doCall fid = do (callsite,save) <- getCont
glob <- getGlobal
(next,newG) <- evalFun callsite fid as glob
setGlobal newG
setCont save
return next
-- | Evaluate a call to a lua function
evalFunId :: AnalysisM m =>
CallsiteId {- ^ Location of the call -} ->
FunId {- ^ Lua function being called -} ->
Map UpIx (WithTop (Set RefId)) {- ^ Info about free vars -} ->
List Value {- ^ Info about arguments -} ->
GlobalState {- ^ Info about the global state -} ->
m (Either Value (List Value), GlobalState)
evalFunId caller fid ups as glob =
do (next,s1) <- go EntryBlock State { localState = locals
, globalState = glob }
return (next, globalState s1)
where
locals = LocalState { env = bottom
, argReg = as
, listReg = bottom
, upvals = ups
}
block b = GlobalBlockName caller (QualifiedBlockName fid b)
go b s = do (next,s1) <- evalBlock (block b) s
case next of
Continue -> error "Continue"
EnterBlock b1 -> go b1 s1
RaiseError v -> return (Left v, s1)
ReturnWith xs -> return (Right xs, s1)
evalFun :: AnalysisM m =>
CallsiteId -> ClosureId -> List Value -> GlobalState ->
m (Either Value (List Value), GlobalState)
evalFun caller cid as glob =
case functionFID funV of
NoValue -> impossible
MultipleValues -> error "evalFun: multiple values" -- todo: report intractibility
OneValue (CFunImpl ptr) ->
do mbPrim <- getPrim ptr
case mbPrim of
-- XXX: POTENTIALLY UNSOUND!!!
-- For now we just treat unknown C functions as if they don't
-- throw exceptoins or modify the Lua world in any way.
Nothing -> return (Right (listConst topVal), glob)
Just (PrimImpl prim) -> prim glob as
OneValue (LuaFunImpl fid) ->
evalFunId caller fid (functionUpVals funV) as glob
where
funV = functions glob Map.! cid
data Result = Result
{ resReturns :: List Value
, resRaises :: Value
, resGlobals :: GlobalState
, resStates :: Map GlobalBlockName State
, resBlockRaises :: Map GlobalBlockName Value
} deriving Show
instance Pretty Result where
pp Result { .. } =
vcat [ entry "returns" resReturns
, entry "raises" resRaises
, entry "finals" resGlobals
, entry "all_states" resStates
, entry "raise_states" resBlockRaises
]
where
entry x y
| y == bottom = empty
| otherwise = x <> colon $$ nest 2 (pp y)
{-
analyze ::
Map FunId Function ->
Map CFun PrimImpl ->
ClosureId ->
List Value ->
GlobalState -> Result
analyze funs prims cid args glob =
Result { resReturns = joins [ v | Right v <- nexts ]
, resRaises = joins [ v | Left v <- nexts ]
, resGlobals = joins gs
, resStates = joins states
, resBlockRaises = joins errs
}
where
(nexts,gs) = unzip rss
(rss, states,errs)
= unzip3
$ allPaths funs prims
$ evalFun initialCaller cid args glob
-}
analyze ::
Map FunId MicroFunction ->
Map CFun PrimImpl ->
ClosureId ->
List Value ->
GlobalState -> Result
analyze funs prims cid args glob =
Result { resReturns = joins [ v | Right v <- nexts ]
, resRaises = joins [ v | Left v <- nexts ]
, resGlobals = joins gs
, resStates = states
, resBlockRaises = errs
}
where
(nexts,gs) = unzip rss
(rss, states, errs, logs)
= singlePath funs prims
$ evalFun initialCaller cid args glob
analyzeFun ::
Map FunId MicroFunction ->
Map CFun PrimImpl ->
FunId ->
Map UpIx (WithTop (Set RefId)) ->
List Value ->
GlobalState -> Result
analyzeFun funs prims fid ups args glob =
Result { resReturns = joins [ v | Right v <- nexts ]
, resRaises = joins [ v | Left v <- nexts ]
, resGlobals = joins gs
, resStates = states
, resBlockRaises = errs
}
where
(nexts,gs) = unzip rss
(rss, states, errs, logs)
= singlePath funs prims
$ evalFunId initialCaller fid ups args glob
|
GaloisInc/galua
|
galua-jit/src/Galua/Micro/Type/Eval.hs
|
mit
| 17,324 | 0 | 25 | 7,246 | 4,723 | 2,254 | 2,469 | 390 | 54 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances, DeriveFunctor #-}
module Utils.Gen where
import Control.Applicative
import Control.Error
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
newtype GenT m a = GenT {unGenT :: StateT Integer m a}
deriving(Functor)
instance Monad m => Monad (GenT m) where
return = GenT . return
(GenT m) >>= f = GenT $ m >>= unGenT . f
instance (Functor f, Monad f) => Applicative (GenT f) where
pure = GenT . pure
(GenT f) <*> (GenT a) = GenT $ f <*> a
type Gen = GenT Identity
instance MonadTrans GenT where
lift = GenT . lift
instance MonadReader r m => MonadReader r (GenT m) where
local f = GenT . local f . unGenT
ask = GenT ask
instance MonadState s m => MonadState s (GenT m) where
get = GenT $ lift get
put = GenT . lift . put
instance (MonadWriter w m) => MonadWriter w (GenT m) where
tell m = lift $ tell m
listen = GenT . listen . unGenT
pass = GenT . pass . unGenT
class Monad m => MonadGen m where
gen :: m Integer
instance (Monad m, Functor m) => MonadGen (GenT m) where
gen = GenT $ modify (+1) >> get
instance MonadGen m => MonadGen (StateT s m) where
gen = lift gen
instance MonadGen m => MonadGen (ReaderT s m) where
gen = lift gen
instance (MonadGen m, Monoid s) => MonadGen (WriterT s m) where
gen = lift gen
instance MonadGen (EitherT e Gen) where
gen = lift gen
runGenT :: Monad m => GenT m a -> m a
runGenT = flip evalStateT 0 . unGenT
runGen :: Gen a -> a
runGen = runIdentity . runGenT
|
jozefg/c_of_scheme
|
src/Utils/Gen.hs
|
mit
| 1,637 | 0 | 9 | 377 | 652 | 337 | 315 | 46 | 1 |
-- | Common handler functions.
module Handler.Common where
import Data.FileEmbed (embedFile)
import Import
-- These handlers embed files in the executable at compile time to avoid a
-- runtime dependency, and for efficiency.
getFaviconR :: Handler TypedContent
getFaviconR = return $ TypedContent "image/x-icon"
$ toContent $(embedFile "config/favicon.ico")
getRobotsR :: Handler TypedContent
getRobotsR = return $ TypedContent typePlain
$ toContent $(embedFile "config/robots.txt")
removeAll :: Eq a => a -> [a] -> [a]
removeAll _ [] = []
removeAll x (y:ys)
| x == y = removeAll x ys
| otherwise = y : removeAll x ys
reloadHeader :: MonadWidget m => m ()
reloadHeader = toWidgetHead [hamlet|
<meta http-equiv="refresh" content="2" />
|]
|
nek0/yocage
|
Handler/Common.hs
|
mit
| 793 | 0 | 9 | 166 | 209 | 107 | 102 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE ScopedTypeVariables #-}
module PostgREST.Middleware where
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Text
-- import Data.Pool(withResource, Pool)
import qualified Hasql as H
import qualified Hasql.Postgres as P
import Data.String.Conversions(cs)
import Network.HTTP.Types.Header (hLocation, hAuthorization)
import Network.HTTP.Types (RequestHeaders)
import Network.HTTP.Types.Status (status400, status401, status301)
import Network.Wai (Application, requestHeaders, responseLBS, rawPathInfo,
rawQueryString, isSecure, Request(..), Response)
import Network.URI (URI(..), parseURI)
import PostgREST.Config (AppConfig(..))
import PostgREST.Auth (LoginAttempt(..), signInRole, signInWithJWT, setRole, resetRole, setUserId, resetUserId)
import Codec.Binary.Base64.String (decode)
import Prelude
authenticated :: forall s. AppConfig ->
(Request -> H.Tx P.Postgres s Response) ->
Request -> H.Tx P.Postgres s Response
authenticated conf app req = do
attempt <- httpRequesterRole (requestHeaders req)
case attempt of
MalformedAuth ->
return $ responseLBS status400 [] "Malformed basic auth header"
LoginFailed ->
return $ responseLBS status401 [] "Invalid username or password"
LoginSuccess role uid -> if role /= currentRole then runInRole role uid else app req
NoCredentials -> if anon /= currentRole then runInRole anon "" else app req
where
jwtSecret = cs $ configJwtSecret conf
currentRole = cs $ configDbUser conf
anon = cs $ configAnonRole conf
serverName = cs $ configServerName conf ::Text
httpRequesterRole :: RequestHeaders -> H.Tx P.Postgres s LoginAttempt
httpRequesterRole hdrs = do
let auth = fromMaybe "" $ lookup hAuthorization hdrs
case split (==' ') (cs auth) of
("Basic" : b64 : _) ->
case split (==':') (cs . decode . cs $ b64) of
(u:p:_) -> signInRole serverName u p
_ -> return MalformedAuth
("Bearer" : jwt : _) ->
return $ signInWithJWT jwtSecret jwt
_ -> return NoCredentials
runInRole :: Text -> Text -> H.Tx P.Postgres s Response
runInRole r uid = do
setUserId uid
setRole r
res <- app req
resetRole
resetUserId
return res
redirectInsecure :: Application -> Application
redirectInsecure app req respond = do
let hdrs = requestHeaders req
host = lookup "host" hdrs
uriM = parseURI . cs =<< mconcat [
Just "https://",
host,
Just $ rawPathInfo req,
Just $ rawQueryString req]
isHerokuSecure = lookup "x-forwarded-proto" hdrs == Just "https"
if not (isSecure req || isHerokuSecure)
then case uriM of
Just uri ->
respond $ responseLBS status301 [
(hLocation, cs . show $ uri { uriScheme = "https:" })
] ""
Nothing ->
respond $ responseLBS status400 [] "SSL is required"
else app req respond
|
framp/postgrest
|
src/PostgREST/Middleware.hs
|
mit
| 3,057 | 0 | 17 | 758 | 899 | 476 | 423 | 73 | 9 |
{-# LANGUAGE LambdaCase #-}
-- | @biegunka@ tool options
module Options
( parseArgs
, Command(..)
, _Init
, _Run
, _Json
, _Version
, _Help
, scriptName
, defaultBiegunkaDataDirectory
) where
import Control.Lens
import qualified Data.List as List
import Data.Version (showVersion)
import Prelude hiding (init)
import System.Exit (ExitCode(ExitSuccess, ExitFailure))
import qualified System.IO as IO
import Text.Printf (printf)
import qualified Paths_biegunka as Paths
import qualified Git_biegunka as Git
data Command
= Init FilePath
| Run (Maybe FilePath) [String]
| Json FilePath
| Version String
| Help String IO.Handle ExitCode
deriving (Show, Eq)
parseArgs :: [String] -> Command
parseArgs = \case
["init"] -> Init "."
["init", x] -> Init x
["run"] -> Run Nothing []
("run" : "--" : xs) -> Run Nothing xs
("run" : xs@(('-' : _) : _)) -> Run Nothing xs
("run" : x : "--" : xs) -> Run (Just x) xs
("run" : x : xs) -> Run (Just x) xs
["json"] -> Json defaultBiegunkaDataDirectory
["json", x] -> Json x
["version"] -> Version version
["help"] -> Help help IO.stdout ExitSuccess
_ -> Help help IO.stderr (ExitFailure 1)
where
help = List.intercalate "\n"
[ "biegunka " ++ version
, ""
, "biegunka init [DIR]"
, " put Biegunka.hs template in DIR"
, "biegunka run [SCRIPT | Biegunka.hs] [OPTIONS]"
, " run SCRIPT with OPTIONS"
, "biegunka json [DIRECTORY | ~/.biegunka]"
, " show JSON with Biegunka data in DIR"
, "biegunka version"
, " show version and exit"
, "biegunka help"
, " show this text and exit"
]
version = printf "%s-%s" (showVersion Paths.version) Git.hash
-- | Filename which @biegunka init@ creates by default
scriptName :: FilePath
scriptName = "Biegunka.hs"
-- | @biegunka list@ and @biegunka generate@ default data directory
defaultBiegunkaDataDirectory :: String
defaultBiegunkaDataDirectory = "~/.biegunka"
_Init :: Prism' Command FilePath
_Init = prism' Init (\case Init x -> Just x; _ -> Nothing)
_Run :: Prism' Command (Maybe FilePath, [String])
_Run = prism' (uncurry Run) (\case Run x y -> Just (x, y); _ -> Nothing)
_Json :: Prism' Command FilePath
_Json = prism' Json (\case Json x -> Just x; _ -> Nothing)
_Version :: Prism' Command String
_Version = prism' Version (\case Version x -> Just x; _ -> Nothing)
_Help :: Prism' Command (String, IO.Handle, ExitCode)
_Help = prism' (\(x, y, z) -> Help x y z) (\case Help x y z -> Just (x, y, z); _ -> Nothing)
|
biegunka/biegunka
|
bin/Options.hs
|
mit
| 2,574 | 0 | 14 | 590 | 823 | 457 | 366 | 69 | 12 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html
module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationInputSchema where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationRecordColumn
import Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationRecordFormat
-- | Full data type definition for KinesisAnalyticsV2ApplicationInputSchema.
-- See 'kinesisAnalyticsV2ApplicationInputSchema' for a more convenient
-- constructor.
data KinesisAnalyticsV2ApplicationInputSchema =
KinesisAnalyticsV2ApplicationInputSchema
{ _kinesisAnalyticsV2ApplicationInputSchemaRecordColumns :: [KinesisAnalyticsV2ApplicationRecordColumn]
, _kinesisAnalyticsV2ApplicationInputSchemaRecordEncoding :: Maybe (Val Text)
, _kinesisAnalyticsV2ApplicationInputSchemaRecordFormat :: KinesisAnalyticsV2ApplicationRecordFormat
} deriving (Show, Eq)
instance ToJSON KinesisAnalyticsV2ApplicationInputSchema where
toJSON KinesisAnalyticsV2ApplicationInputSchema{..} =
object $
catMaybes
[ (Just . ("RecordColumns",) . toJSON) _kinesisAnalyticsV2ApplicationInputSchemaRecordColumns
, fmap (("RecordEncoding",) . toJSON) _kinesisAnalyticsV2ApplicationInputSchemaRecordEncoding
, (Just . ("RecordFormat",) . toJSON) _kinesisAnalyticsV2ApplicationInputSchemaRecordFormat
]
-- | Constructor for 'KinesisAnalyticsV2ApplicationInputSchema' containing
-- required fields as arguments.
kinesisAnalyticsV2ApplicationInputSchema
:: [KinesisAnalyticsV2ApplicationRecordColumn] -- ^ 'kavaisRecordColumns'
-> KinesisAnalyticsV2ApplicationRecordFormat -- ^ 'kavaisRecordFormat'
-> KinesisAnalyticsV2ApplicationInputSchema
kinesisAnalyticsV2ApplicationInputSchema recordColumnsarg recordFormatarg =
KinesisAnalyticsV2ApplicationInputSchema
{ _kinesisAnalyticsV2ApplicationInputSchemaRecordColumns = recordColumnsarg
, _kinesisAnalyticsV2ApplicationInputSchemaRecordEncoding = Nothing
, _kinesisAnalyticsV2ApplicationInputSchemaRecordFormat = recordFormatarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordcolumns
kavaisRecordColumns :: Lens' KinesisAnalyticsV2ApplicationInputSchema [KinesisAnalyticsV2ApplicationRecordColumn]
kavaisRecordColumns = lens _kinesisAnalyticsV2ApplicationInputSchemaRecordColumns (\s a -> s { _kinesisAnalyticsV2ApplicationInputSchemaRecordColumns = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordencoding
kavaisRecordEncoding :: Lens' KinesisAnalyticsV2ApplicationInputSchema (Maybe (Val Text))
kavaisRecordEncoding = lens _kinesisAnalyticsV2ApplicationInputSchemaRecordEncoding (\s a -> s { _kinesisAnalyticsV2ApplicationInputSchemaRecordEncoding = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-inputschema.html#cfn-kinesisanalyticsv2-application-inputschema-recordformat
kavaisRecordFormat :: Lens' KinesisAnalyticsV2ApplicationInputSchema KinesisAnalyticsV2ApplicationRecordFormat
kavaisRecordFormat = lens _kinesisAnalyticsV2ApplicationInputSchemaRecordFormat (\s a -> s { _kinesisAnalyticsV2ApplicationInputSchemaRecordFormat = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsV2ApplicationInputSchema.hs
|
mit
| 3,613 | 0 | 13 | 266 | 354 | 207 | 147 | 36 | 1 |
let bubble [] = []; bubble [x] = [x]; bubble (x:y:xs) = if x > y then y:(bubble (x:xs)) else x:(bubble (y:xs))
let length [] = 0; length (x:xs) = 1 + (length xs)
let helper 0 a = a; helper n a = helper (n-1) (bubble a)
let sort l = helper (length l) l
|
mathiasquintero/RandomStuff
|
Haskell/BubbleSort.hs
|
mit
| 252 | 1 | 12 | 56 | 197 | 103 | 94 | -1 | -1 |
-- Thinkful - List Drills: Longest word
-- https://www.codewars.com/kata/58670300f04e7449290000e5
module Kata (longest) where
longest :: [String] -> Int
longest = maximum . map length
|
gafiatulin/codewars
|
src/7 kyu/LengthOfTheLongest.hs
|
mit
| 186 | 0 | 6 | 26 | 35 | 21 | 14 | 3 | 1 |
module Spew where
import Data.Array (listArray, Array)
import qualified Data.Array as A
import System.Random
import Control.Monad.State.Lazy
import Control.Monad.Writer.Lazy
import Control.Applicative
import qualified Data.Vector as V
import Debug.Trace
type PrimFastModel = [(String, FrequencySelector)]
type FastModel = Array Int (String, FrequencySelector)
-- We pay a space cost up front for this, but save ourselves
-- computation later down the line. Given that most state transitions
-- have a frequency of only 1 or 2 (based on a cursory look over
-- sokal.model), it seems likely that the space cost won't be high.
type FrequencySelector = V.Vector Int
toFrequencySelector :: [(Int, Int)] -> FrequencySelector
toFrequencySelector = V.fromList . concatMap stretch
where stretch (fr, idx) = replicate fr idx
deserialize :: String -> PrimFastModel
deserialize = map (makeTrans . read) . lines
where makeTrans (s, is) = (s, toFrequencySelector is)
fromPrim :: PrimFastModel -> FastModel
fromPrim xs = listArray (1, length xs) xs
randomIdx :: FastModel -> StdGen -> (Int, StdGen)
randomIdx m g = randomR (A.bounds m) g
walkModel :: FastModel -> WriterT [String] (State (StdGen, Int)) ()
walkModel model =
do
(g, idx) <- get
let (s, fs) = model A.! idx
let stuck = V.null fs
tell [s ++ if stuck then "." else ""]
let (i, g') = randomR (0, V.length fs - 1) g
let (j, g'') = randomIdx model g
put (g'', if stuck then j else fs V.! i)
runModel :: StdGen -> FastModel -> [String]
runModel g model = (evalState $ execWriterT $ mapM (\_ -> walker) [1..]) (g', idx)
where walker = walkModel model
(idx, g') = randomIdx model g
takeUntil :: (a -> Bool) -> [a] -> [a]
takeUntil f [] = []
takeUntil f [x] = [x]
takeUntil f (x:y:xs)
| f y = [x, y]
| otherwise = x:(takeUntil f (y:xs))
isTerminator :: Char -> Bool
isTerminator '.' = True
isTerminator '?' = True
isTerminator '!' = True
isTerminator _ = False
sentenceFinished :: String -> Bool
sentenceFinished = any isTerminator
takeAtLeast :: Int -> [String] -> [String]
takeAtLeast n ss = body ++ terminator
where (body, rest) = splitAt n ss
terminator = takeUntil sentenceFinished rest
linefill :: Int -> [String] -> String
linefill _ [] = "\n"
linefill n (x:xs) = iter x xs where
iter x (y:ys)
| length x + length y + 1 > n = x ++ "\n" ++ linefill n (y:ys)
| otherwise = iter (x ++ " " ++ y) ys
iter x [] = x ++ "\n"
|
pscollins/cmsc-22311-lab-2
|
Spew.hs
|
gpl-2.0
| 2,515 | 0 | 14 | 565 | 965 | 517 | 448 | 60 | 3 |
-- Joe Jevnik
-- 20.12.2013
-- The benchmarking tests for my brainfuck interpreter implementation
-- interations.
import Criterion.Main
import Criterion.Config
import qualified UnsafeBrainfuck as UBF (main)
import qualified NewArrayTest as NAT (main)
import qualified SafeBrainfuck as SBF (main)
import qualified ByteStringTest as BST (main)
args :: IO [String]
args = return ["../txt/squares"]
cfg :: Config
cfg = defaultConfig { cfgPerformGC = ljust True }
main = defaultMainWith cfg (return ()) [
bgroup "brainfuck" [ bench "unsafe" $ nfIO (UBF.main args)
, bench "newArr" $ nfIO (NAT.main args)
, bench "safe" $ nfIO (SBF.main args)
, bench "bytestr" $ nfIO (BST.main args)
]
]
|
llllllllll/brainfuck
|
prof/src/benchmarking.hs
|
gpl-2.0
| 821 | 0 | 13 | 242 | 220 | 121 | 99 | 15 | 1 |
-- | Linear regression models, as discussed in chapter 3 of Bishop.
module Algorithms.MachineLearning.LinearRegression (
LinearModel, BayesianVarianceModel,
regressLinearModel, regressRegularizedLinearModel, regressBayesianLinearModel,
regressEMBayesianLinearModel, regressFullyDeterminedEMBayesianLinearModel
) where
import Algorithms.MachineLearning.Framework
import Algorithms.MachineLearning.LinearAlgebra
import Algorithms.MachineLearning.Utilities
data LinearModel input target = LinearModel {
lm_basis_fns :: [input -> Double],
lm_weights :: Matrix Weight -- One column per target variable,
-- one row per basis function output
}
instance Show (LinearModel input target) where
show model = "Weights: " ++ show (lm_weights model)
instance (Vectorable input, Vectorable target) => Model (LinearModel input target) input target where
predict model input = fromVector $ (trans $ lm_weights model) <> phi_app_x
where
phi_app_x = applyVector (lm_basis_fns model) input
data BayesianVarianceModel input = BayesianVarianceModel {
bvm_basis_fns :: [input -> Double],
bvm_inv_hessian :: Matrix Weight, -- Equivalent to the weight distribution covariance matrix
bvm_beta :: Precision
}
instance Show (BayesianVarianceModel input) where
show model = "Inverse Hessian: " ++ show (bvm_inv_hessian model) ++ "\n" ++
"Beta: " ++ show (bvm_beta model)
instance (Vectorable input) => Model (BayesianVarianceModel input) input Variance where
predict model input = recip (bvm_beta model) + (phi_app_x <> bvm_inv_hessian model) <.> phi_app_x
where
phi_app_x = applyVector (bvm_basis_fns model) input
regressDesignMatrix :: (Vectorable input) => [input -> Double] -> Matrix Double -> Matrix Double
regressDesignMatrix basis_fns inputs
= applyMatrix (map (. fromVector) basis_fns) inputs -- One row per sample, one column per basis function
-- | Regularized pseudo-inverse of a matrix, with regularization coefficient lambda.
regularizedPinv :: RegularizationCoefficient -> Matrix Double -> Matrix Double
regularizedPinv lambda phi = regularizedPrePinv lambda 1 phi <> trans phi
-- | Just the left portion of the formula for the pseudo-inverse, with coefficients alpha and beta, i.e.:
--
-- > (alpha * _I_ + beta * _phi_ ^ T * _phi_) ^ -1
regularizedPrePinv :: Precision -> Precision -> Matrix Double -> Matrix Double
regularizedPrePinv alpha beta phi = inv $ (alpha .* (ident (cols phi))) + (beta .* (trans phi <> phi))
-- | Regress a basic linear model with no regularization at all onto the given data using the
-- supplied basis functions.
--
-- The resulting model is likely to suffer from overfitting, and may not be well defined in the basis
-- functions are close to colinear.
--
-- However, the model will be the optimal model for the data given the basis in least-squares terms. It
-- is also very quick to find, since there is a closed form solution.
--
-- Equation 3.15 in Bishop.
regressLinearModel
:: (Vectorable input) => [input -> Double] -> DataSet input target -> LinearModel input target
regressLinearModel basis_fns ds = LinearModel { lm_basis_fns = basis_fns, lm_weights = weights }
where
design_matrix = regressDesignMatrix basis_fns (ds_inputs ds)
weights = pinv design_matrix <> ds_targets ds
-- | Regress a basic linear model with a sum-of-squares regularization term. This penalizes models with weight
-- vectors of large magnitudes and hence ameliorates the over-fitting problem of 'regressLinearModel'.
-- The strength of the regularization is controlled by the lambda parameter. If lambda is 0 then this function
-- is equivalent to the unregularized regression.
--
-- The resulting model will be optimal in terms of least-squares penalized by lambda times the sum-of-squares of
-- the weight vector. Like 'regressLinearModel', a closed form solution is used to find the model quickly.
--
-- Equation 3.28 in Bishop.
regressRegularizedLinearModel
:: (Vectorable input) => RegularizationCoefficient -> [input -> Double] -> DataSet input target -> LinearModel input target
regressRegularizedLinearModel lambda basis_fns ds = LinearModel { lm_basis_fns = basis_fns, lm_weights = weights }
where
design_matrix = regressDesignMatrix basis_fns (ds_inputs ds)
weights = regularizedPinv lambda design_matrix <> ds_targets ds
-- | Determine the mean weight and inverse hessian matrix given alpha, beta, the design matrix and the targets.
bayesianPosteriorParameters :: Precision -> Precision -> Matrix Double -> Matrix Double -> (Matrix Double, Matrix Double)
bayesianPosteriorParameters alpha beta design_matrix targets = (weights, inv_hessian)
where
inv_hessian = regularizedPrePinv alpha beta design_matrix
weights = beta .* inv_hessian <> trans design_matrix <> targets
-- | Bayesian linear regression, using an isotropic Gaussian prior for the weights centred at the origin. The precision
-- of the weight prior is controlled by the parameter alpha, and our belief about the inherent noise in the data is
-- controlled by the precision parameter beta.
--
-- Bayesion linear regression with this prior is entirely equivalent to calling 'regressRegularizedLinearModel' with
-- lambda = alpha / beta. However, the twist is that we can use our knowledge of the prior to also make an estimate
-- for the variance of the true value about any input point.
--
-- For the case of multiple target variables, this function makes the naive Bayesian assumption that the probability
-- distributions on output variables are independent, and takes as an error metric the unweighted sum-squared error
-- in all the targets. The variance model is common to all the target variables.
--
-- Equations 3.53, 3.54 and 3.59 in Bishop.
regressBayesianLinearModel
:: (Vectorable input)
=> Precision -- ^ Precision of Gaussian weight prior
-> Precision -- ^ Precision of noise on samples
-> [input -> Double] -> DataSet input target -> (LinearModel input target, BayesianVarianceModel input)
regressBayesianLinearModel alpha beta basis_fns ds
= (LinearModel { lm_basis_fns = basis_fns, lm_weights = weights },
BayesianVarianceModel { bvm_basis_fns = basis_fns, bvm_inv_hessian = inv_hessian, bvm_beta = beta })
where
design_matrix = regressDesignMatrix basis_fns (ds_inputs ds)
(weights, inv_hessian) = bayesianPosteriorParameters alpha beta design_matrix (ds_targets ds)
-- | Evidence-maximising Bayesian linear regression, using an isotropic Gaussian prior for the weights centred at the
-- origin. The precision of the weight prior is controlled by the parameter alpha, and our belief about the inherent
-- noise in the data is controlled by the precision parameter beta.
--
-- This is similar to 'bayesianLinearRegression', but rather than just relying on the supplied values for alpha and beta
-- an iterative procedure is used to try and find values that are best supported by the supplied training data. This is
-- an excellent way of finding a reasonable trade-off between over-fitting of the training set with a complex model and
-- accuracy of the model.
--
-- As a bonus, this function returns gamma, the effective number of parameters used by the regressed model.
--
-- For the case of multiple target variables, this function makes the naive Bayesian assumption that the probability
-- distributions on output variables are independent, and takes as an error metric the unweighted sum-squared error
-- in all the targets. The variance model is common to all the target variables.
--
-- Equations 3.87, 3.92 and 3.95 in Bishop.
regressEMBayesianLinearModel
:: (Vectorable input, Vectorable target, MetricSpace target)
=> Precision -- ^ Initial estimate of Gaussian weight prior
-> Precision -- ^ Initial estimate for precision of noise on samples
-> [input -> Double] -> DataSet input target -> (LinearModel input target, BayesianVarianceModel input, EffectiveNumberOfParameters)
regressEMBayesianLinearModel initial_alpha initial_beta basis_fns ds
= convergeOnEMBayesianLinearModel loopWorker design_matrix initial_alpha initial_beta basis_fns ds
where
n = fromIntegral $ dataSetSize ds
design_matrix = regressDesignMatrix basis_fns (ds_inputs ds)
-- The unscaled eigenvalues will be positive because phi ^ T * phi is positive definite.
(unscaled_eigenvalues, _) = eigSH (trans design_matrix <> design_matrix)
loopWorker alpha beta = (n - gamma, gamma)
where
-- We save computation by calculating eigenvalues once for the design matrix and rescaling each iteration
eigenvalues = beta .* unscaled_eigenvalues
gamma = vectorSum (eigenvalues / (addConstant alpha eigenvalues))
-- | Evidence-maximising Bayesian linear regression, using an isotropic Gaussian prior for the weights centred at the
-- origin. The precision of the weight prior is controlled by the parameter alpha, and our belief about the inherent
-- noise in the data iscontrolled by the precision parameter beta.
--
-- This is similar to 'regressEMBayesianLinearModel', but suitable only for the situation where there is much more
-- training data than there are basis functions you want to assign weights to. Due to the introduction of this
-- constraint, it is much faster than the other function and yet produces results of similar quality.
--
-- Like with 'regressEMBayesianLinearModel', the effective number of parameters, gamma, used by the regressed model
-- is returned. However, because for this function to make sense you need to be sure that there is sufficient data
-- that all the parameters are determined, the returned gamma is always just the number of basis functions (and
-- hence weights).
--
-- For the case of multiple target variables, this function makes the naive Bayesian assumption that the probability
-- distributions on output variables are independent, and takes as an error metric the unweighted sum-squared error
-- in all the targets. The variance model is common to all the target variables.
--
-- Equations 3.98 and 3.99 in Bishop.
regressFullyDeterminedEMBayesianLinearModel
:: (Vectorable input, Vectorable target, MetricSpace target)
=> Precision -- ^ Initial estimate of Gaussian weight prior
-> Precision -- ^ Initial estimate for precision of noise on samples
-> [input -> Double] -> DataSet input target -> (LinearModel input target, BayesianVarianceModel input, EffectiveNumberOfParameters)
regressFullyDeterminedEMBayesianLinearModel initial_alpha initial_beta basis_fns ds
= convergeOnEMBayesianLinearModel loopWorker design_matrix initial_alpha initial_beta basis_fns ds
where
n = fromIntegral $ dataSetSize ds
m = fromIntegral $ length basis_fns
design_matrix = regressDesignMatrix basis_fns (ds_inputs ds)
-- In the limit n >> m, n - gamma = n, so we use that as the beta numerator
-- We assume all paramaters are determined because n >> m, so we return m as gamma
loopWorker _ _ = (n, m)
convergeOnEMBayesianLinearModel
:: (Vectorable input, Vectorable target, MetricSpace target)
=> (Precision -> Precision -> (Double, EffectiveNumberOfParameters)) -- ^ Loop worker: given alpha and beta, return new beta numerator and gamma
-> Matrix Double -- ^ Design matrix
-> Precision -- ^ Initial alpha
-> Precision -- ^ Initial beta
-> [input -> Double] -- ^ Basis functions
-> DataSet input target
-> (LinearModel input target, BayesianVarianceModel input, EffectiveNumberOfParameters)
convergeOnEMBayesianLinearModel loop_worker design_matrix initial_alpha initial_beta basis_fns ds
= loop eps initial_alpha initial_beta False
where
loop threshold alpha beta done
| done = (linear_model, BayesianVarianceModel { bvm_basis_fns = basis_fns, bvm_inv_hessian = inv_hessian, bvm_beta = beta }, gamma)
| otherwise = loop (threshold * 2) alpha' beta' (eqWithin threshold alpha alpha' && eqWithin threshold beta beta')
where
(weights, inv_hessian) = bayesianPosteriorParameters alpha beta design_matrix (ds_targets ds)
linear_model = LinearModel { lm_basis_fns = basis_fns, lm_weights = weights }
(beta_numerator, gamma) = loop_worker alpha beta
-- This alpha computation is not the most efficient way to get the result, but it is idiomatic.
-- This is the modification to the algorithm in Bishop that generalises the result to the case
-- of multiple target variables, but to prove that this is the right thing to do I had to make the
-- naive Bayesian assumption.
--
-- The reason that this is correct because under naive Bayes:
--
-- dE(W) K T T
-- ------- = \Sigma W * W = Tr (W * W)
-- d\alpha k = 1 k k
alpha' = gamma / (matrixTrace $ (trans weights) <> weights)
beta' = beta_numerator / modelSumSquaredError linear_model ds
|
batterseapower/machine-learning
|
Algorithms/MachineLearning/LinearRegression.hs
|
gpl-2.0
| 13,104 | 0 | 14 | 2,501 | 1,799 | 991 | 808 | -1 | -1 |
module Types.Instances where
import Data.Typeable
import Types.Database
import Types.Entry
import Types.Response
import Types.User
deriving instance Typeable Database
deriving instance Typeable UserProfile
deriving instance Typeable User
deriving instance Typeable Error
deriving instance Typeable Entry
deriving instance Eq User
deriving instance Ord User
deriving instance Read User
deriving instance Show User
deriving instance Eq Database
deriving instance Ord Database
deriving instance Read Database
deriving instance Show Database
|
ktvoelker/todo
|
src/Types/Instances.hs
|
gpl-3.0
| 545 | 0 | 5 | 72 | 135 | 71 | 64 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Partition where
import GHC.TypeLits
--
import Control.Applicative
import Control.Monad.ST
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Either (left, runEitherT)
import Data.Array (listArray)
import Data.Array.ST
import qualified Data.Foldable as F
import Data.Maybe
import Data.Sequence (Seq, ViewL(..), viewl, fromList, singleton)
--
import Data.Permute
import Data.SeqZipper
import Data.Fin1
-- |
newtype OrderedPartition n = OP { getPartition :: Seq [Fin1 n] }
deriving Show
mkOrderedPartition :: forall (n :: Nat) . (KnownNat n) => [ [ Fin1 n ] ] -> Either String (OrderedPartition n)
mkOrderedPartition lst = runST action
where nn = order
action :: forall s. ST s (Either String (OrderedPartition n))
action = runEitherT $ do
rarr <- lift (newArray (1,nn) Nothing :: ST s (STArray s (Fin1 n) (Maybe ())))
F.forM_ (concat lst) $ \r -> do
o <- lift (readArray rarr r)
case o of
Just _ -> left "not a partition"
Nothing -> lift (writeArray rarr r (Just ()))
F.forM_ [1..nn] $ \r ->
maybe (left "not a partition") (const (return ())) =<< lift (readArray rarr r)
(return . OP . fromList ) lst
unitPartition :: forall n. (KnownNat n) => OrderedPartition n
unitPartition = OP (singleton interval)
firstNontrivial :: OrderedPartition n -> Maybe (SeqZipper [Fin1 n])
firstNontrivial = listToMaybe . dropWhile ( ( == 1) . length . current ) . zippers
zippers :: OrderedPartition n -> [ SeqZipper [Fin1 n] ]
zippers (OP ptn) = (catMaybes . takeWhile (isJust) . iterate (moveRight =<<)) (pure ptn1)
where ptn1 = case viewl ptn of
EmptyL -> error "impossble" -- guaranteed from OrderedPartition and n >= 1
x :< xs -> fromNonEmptySeq (x,xs)
locateInPartition :: OrderedPartition n -> Fin1 n -> SeqZipper [Fin1 n]
locateInPartition ptn x = head (filter (p x) (zippers ptn)) -- this is guaranteed for ordered partition
where p y z = y `elem` current z
isDiscrete :: OrderedPartition n -> Bool
isDiscrete = all ((== 1) . length) . F.toList . getPartition
discreteToPerm :: (KnownNat n) => OrderedPartition n -> Maybe (Perm n)
discreteToPerm ptn = if isDiscrete ptn
then case (mkPerm . listArray (1,order) . concat . F.toList . getPartition) ptn of
Left err -> error err -- cannot happen. guaranteed by OrderedPartition
Right p -> Just p
else Nothing
|
wavewave/qft
|
old/lib/Data/Partition.hs
|
gpl-3.0
| 3,019 | 0 | 22 | 945 | 923 | 488 | 435 | 56 | 3 |
module Main where
import DutyPlanner
import Test.HUnit
import Data.Time.Calendar
persons = ["ashrub","scripter","iph","kaktus"]
start = (fromGregorian 2014 06 01)
end = (fromGregorian 2014 06 04)
days = [start..end]
duty = [(fromGregorian 2014 06 01,"ashrub"),(fromGregorian 2014 06 02,"scripter"),(fromGregorian 2014 06 03,"iph"),(fromGregorian 2014 06 04,"kaktus")]
description = "Число дежурных равно числу дней, исключений и пожеланий нет"
test1 = TestCase ( assertEqual description duty (planDuty persons days) )
main = runTestTT test1
|
worldmind/dutyplanner
|
test/Main.hs
|
gpl-3.0
| 608 | 0 | 9 | 85 | 183 | 104 | 79 | 12 | 1 |
import Rsa
import System.Environment
import System.IO
import System.IO.Error
import Data.Char
import Data.List
import Data.List.Split
decode :: Int->[Int]
decode x
| x == 0 = []
| otherwise = (decode (x `quot` 1000)) ++ ((x `mod` 1000) : [])
main = do
args <- getArgs
input <- readFile (head args)
keys <- readFile ((args !! 1) ++ "_priv.key")
let key = splitOn ";" keys
blocks = splitOn ";" input
int_blocks = map (\x -> read x :: Integer) (init blocks)
dec_blocks = map fromInteger $ map (\m -> decypher m ((read(key!!0)::Integer),(read(key!!1)::Integer))) int_blocks
dec_txt = map (foldl (\a b->a++((chr b):[])) "") $ map decode dec_blocks
dec_file = foldl (\a b-> a++b) "" dec_txt
writeFile (args !! 2) dec_file
return ()
|
h3nnn4n/rsa-haskell
|
decrypt.hs
|
gpl-3.0
| 811 | 0 | 20 | 203 | 391 | 205 | 186 | 23 | 1 |
module Development.Hake.Tribial (
ghcMake
, updateFile_
) where
import System.IO (openFile, hClose, IOMode(WriteMode), hGetLine,
IOMode(ReadMode), withFile)
import System.IO.Unsafe (unsafeInterleaveIO)
import System.Process (runProcess, waitForProcess)
import System.Exit (ExitCode(ExitSuccess))
import System.Directory (doesFileExist)
import Development.Hake.DirectoryTools (doesNotExistOrOldThan)
import Control.Exception (bracket)
import Control.Monad.Tools (ifM)
import Control.Applicative ((<$>))
ghcMake :: String -> FilePath -> IO ExitCode
ghcMake exe dir = do
let errFile = dir ++ "/" ++ exe ++ ".error"
ret <- bracket (openFile errFile WriteMode) hClose $ \errH ->
runProcess "ghc" [ "--make", exe ] (Just dir)
Nothing Nothing Nothing (Just errH) >>= waitForProcess
case ret of
ExitSuccess -> return ()
_ -> readFile errFile >>= putStr
return ret
updateFile_ :: (String -> Maybe String) -> (FilePath -> String) -> FilePath -> FilePath -> IO Bool
updateFile_ gtSrc hdr src dst
= ifM ( not <$> doesFileExist dst
`orIO`
(/= Just src) . gtSrc <$> withFile dst ReadMode (hGetLine)
`orIO`
doesNotExistOrOldThan dst src )
(readFile src >>= writeFile dst . ( (hdr src ++ "\n") ++ ) >> return True )
( return False)
where
infixr 2 `orIO`
orIO p1 p2 = do { b1 <- p1; b2 <- unsafeInterleaveIO p2; return $ b1 || b2 }
|
YoshikuniJujo/hake_haskell
|
Development/Hake/Tribial.hs
|
gpl-3.0
| 1,595 | 0 | 13 | 472 | 499 | 270 | 229 | 34 | 2 |
import Criterion.Main
import Data.BinTree
tree0 :: BinTree Integer
tree0 = mkTree [0 .. 1000]
tree1 :: BinTree Integer
tree1 = mkTree [0 .. 1000000]
treeE0 :: BinTreeE Integer
treeE0 = mkTreeE [0 .. 1000]
treeE1 :: BinTreeE Integer
treeE1 = mkTreeE [0 .. 1000000]
main :: IO ()
main = defaultMain [
bgroup "leaves" [
bench "catamorphism with standard list/10^3 nodes" (nf leavesCata treeE0)
, bench "catamorphism with standard list/10^6 nodes" (nf leavesCata treeE1)
, bench "lazy state monad/10^3 nodes" (nf leavesS tree0)
, bench "lazy state monad/10^6 nodes" (nf leavesS tree1)
, bench "recursion with standard list/10^3 nodes" (nf leaves tree0)
, bench "recursion with standard list/10^6 nodes" (nf leaves tree1)
, bench "tail recursion with standard list/10^3 nodes" (nf leavesT tree0)
, bench "tail recursion with standard list/10^6 nodes" (nf leavesT tree1)
, bench "recursion with difference list/10^3 nodes" (nf leaves' tree0)
, bench "recursion with difference list/10^6 nodes" (nf leaves' tree1)
]
]
|
capitanbatata/sandbox
|
leaves-of-a-tree/bench/LeavesOfATreeBench.hs
|
gpl-3.0
| 1,086 | 0 | 11 | 231 | 285 | 147 | 138 | 23 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | A monkey is a process which randomly makes changes to the store.
module Ltc.Monkey (
-- * Basic interface
Monkey, start, shutdown,
-- * Configuration
getDelay, setDelay, getActive, setActive
) where
import Control.Concurrent ( forkIO, threadDelay
, MVar, newMVar, readMVar, modifyMVar_ )
import Control.Exception ( Exception )
import Control.Monad ( forever, when )
import Data.String ( fromString )
import Data.Typeable ( Typeable )
import Ltc.Store ( Store(..), Version )
import qualified Control.Exception as CE
import System.Log.Logger ( debugM )
import System.Random ( randomRIO )
import Text.Printf ( printf )
----------------------
-- Debugging
----------------------
-- | Debugging tag for this module
tag :: String
tag = "Monkey"
----------------------
-- Monkey interface
----------------------
data Shutdown = Shutdown
deriving ( Show, Typeable )
instance Exception Shutdown
data Monkey = Monkey
{ getShutdown :: IO ()
, getDelayVar :: MVar (Double, Double)
, getActiveVar :: MVar Bool
}
-- | Start the monkey on the given store.
start :: (Store s) => s -> IO Monkey
start store = do
debugM tag "starting monkey"
delayVar <- newMVar (1.0, 2.0)
activeVar <- newMVar True
tid <- forkIO $
CE.handle (\(_ :: Shutdown) -> return ()) $ do
forever $ do
(minDelay, maxDelay) <- readMVar delayVar
d <- randomRIO (floor (minDelay * 1000000), floor (maxDelay * 1000000))
threadDelay d
isActive <- readMVar activeVar
when isActive accessStoreRandomly
let monkey = Monkey { getShutdown = CE.throwTo tid Shutdown
, getDelayVar = delayVar
, getActiveVar = activeVar
}
return monkey
where
-- FIXME Monkey should use String values as well.
accessStoreRandomly = do
n <- randomRIO (1, 4 :: Int)
if n <= 3 -- 75% chance of read
then readStoreRandomly
else writeStoreRandomly
readStoreRandomly = do
key <- randomKey
(_ :: Maybe (Integer, Version)) <- getLatest store key
return ()
writeStoreRandomly = do
key <- randomKey
v <- randomRIO (1, 4 :: Integer)
_ <- set store key v
return ()
randomKey = do
i <- randomRIO (1, 8 :: Int)
return (fromString (printf "i%03d" i))
-- | Shutdown the given monkey.
shutdown :: Monkey -> IO ()
shutdown monkey = do
debugM tag "shutting monkey down"
getShutdown monkey
-- | Get the current delay range.
getDelay :: Monkey -> IO (Double, Double)
getDelay = readMVar . getDelayVar
-- | Set the delay range. This is the amount of seconds the monkey waits between
-- accesses.
setDelay :: Monkey -> (Double, Double) -> IO ()
setDelay monkey delay = modifyMVar_ (getDelayVar monkey) (const (return delay))
-- | Get the current activation state.
getActive :: Monkey -> IO Bool
getActive = readMVar . getActiveVar
-- | Set the activation state. When inactive, the monkey does not touch the store.
setActive :: Monkey -> Bool -> IO ()
setActive monkey active = modifyMVar_ (getActiveVar monkey) (const (return active))
|
scvalex/ltc
|
src/Ltc/Monkey.hs
|
gpl-3.0
| 3,366 | 0 | 19 | 952 | 858 | 459 | 399 | -1 | -1 |
module Expr where
import Parsing
import Helper
import Lit
-- | These are Expressions used in Command
data Expr = Add Expr Expr -- ^ Addition
| Sub Expr Expr -- ^ Subtration
| Mul Expr Expr -- ^ Multiplication
| Div Expr Expr -- ^ Division
| Val Lit -- ^ Single number
| Ident Name -- ^ Single identifier
| Abs Expr -- ^ Absolute value
| Mod Expr Expr -- ^ Modulo
| Power Expr Expr -- ^ Power
deriving Show
-- | These are the REPL commands
data Command = Set Name Expr -- ^ Setting expression to the variable
| Eval Expr -- ^ Expression evaluation
| Print Expr -- ^ Printing the expression
| Loop Int String -- ^ Looping, the number of times and expression as a string
| FunctionInit Name String -- ^ Initialize the function, function name, expression as a string
| FunctionCall Name -- ^ Calling function
| Simplify Expr -- ^ Simplify an expression
| Load Name -- ^ Load a file and execute its commands
| History Int -- ^ Index into history and execute selected command
| Help -- ^ Display how to use certain commands
| Quit -- ^ Quit the application
deriving Show
-- | Evaluation function evaluates a given expression and produces the result
eval :: Tree (Name, Lit) -- ^ Variable name to value mapping
-> Expr -- ^ Expression to evaluate
-> Either Msg Lit -- ^ Error message or numeric result
-- Basic arithmetic operations for eval
eval _ (Val x) = Right x
eval vars (Add x y) = val add vars x y
eval vars (Sub x y) = val sub vars x y
eval vars (Mul x y) = val mul vars x y
eval vars (Div x y) = do z <- eval vars y
case z of
FLit a -> f a
ILit a -> f a
where f a = if (a == 0) then Left "Divide by 0" else val div' vars x y
-- More complex operations for eval
eval vars (Abs x) = do x <- eval vars x
return $ abs' x
eval vars (Power x y) = do x <- eval vars x
y <- eval vars y
return (pow x y)
eval vars (Ident x) = case getValueFromTree x vars of
Just a -> Right a
Nothing -> Left "Use of undeclared variable"
eval vars (Mod x y) = do x <- eval vars x
y <- eval vars y
return (mod' x y)
-- | Apply an operator to the evaluation of the left and right expressions
val :: (Lit -> Lit -> Lit) -- ^ Operator function
-> Tree (Name, Lit) -- ^ Tree of variables
-> Expr -- ^ Left expression
-> Expr -- ^ Right expression
-> Either Msg Lit -- ^ Error message or numeric result
val op vars x y = do x <- eval vars x
y <- eval vars y
return (op x y)
-- | Parse commands
pCommand :: Parser Command
pCommand = do symbol ":"
do char 'q' -- Quit command
return Quit
||| do char 'l' -- Load command
space
filename <- anything
return (Load filename)
||| do char 's' -- Simplify function
space
e <- pExpr
return (Simplify e)
||| do char 'h'
return (Help)
||| do char '!'
index <- int
return (History index)
||| do l <- identifier -- Variable assignment
symbol "="
e <- pExpr
return (Set l e)
||| do string "print" -- Print statement
space
s <- pExpr
return (Print s)
||| do string "loop" -- Loop construct
n <- natural
s <- anything
return (Loop n s)
||| do string "function" -- Function declaration
n <- identifier -- Function identifier
symbol "():"
e <- anything
return (FunctionInit n e)
||| do n <- identifier -- Function call
symbol "()"
return (FunctionCall n)
||| do e <- pExpr
return (Eval e)
-- | Parse expression
pExpr :: Parser Expr
pExpr = do t <- pTerm
do symbol "+" -- Addition
e <- pExpr
return (Add t e)
||| do symbol "-" -- Subtraction
e <- pExpr
return (Sub t e)
||| return t
-- | Parse factors
pFactor :: Parser Expr
pFactor = do d <- floatIntStr -- Literal
return (Val d)
||| do v <- identifier -- Variable
return (Ident v)
||| do symbol "|" -- Absolute value
e <- pExpr
symbol "|"
return (Abs e)
||| do symbol "(" -- Bracketed expression
e <- pExpr
symbol ")"
return e
-- | Parse terms
pTerm :: Parser Expr
pTerm = do f <- pFactor
do symbol "*" -- Multiplication
t <- pTerm
return (Mul f t)
||| do symbol "/" -- Division
t <- pTerm
return (Div f t)
||| do symbol "^" -- Exponential
e <- pTerm
return (Power f e)
||| do symbol "mod" -- Modulo
e <- pTerm
return (Mod f e)
||| return f
|
MaximKN/Haskell1
|
src/Expr.hs
|
gpl-3.0
| 6,656 | 2 | 21 | 3,490 | 1,426 | 682 | 744 | 133 | 4 |
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
module Abstat.Common.FlatDomainProp where
import Test.Hspec
import Test.QuickCheck
import Abstat.Interface.Poset
import Abstat.Common.FlatDomain
testFlatDomainProperties ::
forall domain .
(Eq domain, Show domain) =>
Gen domain -> Spec
testFlatDomainProperties gen =
describe "FlatDomain properties" $
describe "Poset properties" $ do
it "defines cmp when EQ" $
cmp (Bottom :: FlatDomain domain) Bottom `shouldBe` Just EQ
it "defines cmp when EQ" $
cmp (Top :: FlatDomain domain) Top `shouldBe` Just EQ
it "defines cmp when EQ" $ property $
forAll gen $ \a -> forAll gen $ \b ->
a == b ==> cmp (Val a) (Val a) `shouldBe` Just EQ
it "defines cmp when LT" $
cmp (Bottom :: FlatDomain domain) Top `shouldBe` Just LT
it "defines cmp when LT" $ property $
forAll gen $ \a ->
cmp (Val a) Top `shouldBe` Just LT
it "defines cmp when LT" $ property $
forAll gen $ \a ->
cmp Bottom (Val a) `shouldBe` Just LT
it "defines cmp when GT" $
cmp (Top :: FlatDomain domain) Bottom `shouldBe` Just GT
it "defines cmp when GT" $
forAll gen $ \a ->
cmp Top (Val a) `shouldBe` Just GT
it "defines cmp when GT" $ property $
forAll gen $ \a ->
cmp (Val a) Bottom `shouldBe` Just GT
it "defines cmp when NC" $ property $
forAll gen $ \a -> forAll gen $ \b ->
a /= b ==> cmp (Val a) (Val b) `shouldBe` Nothing
|
fpoli/abstat
|
src/Abstat/Common/FlatDomainProp.hs
|
gpl-3.0
| 1,773 | 0 | 16 | 671 | 537 | 266 | 271 | 39 | 1 |
{-# LANGUAGE RecordWildCards #-}
-- | Render a grammar into a String, which may form the nucleus of a Haskell
-- module.
--
-- Note that the resulting file requires manual additions, such as the module
-- name.
module BioInf.GrammarProducts.Haskell where
import Data.Set (toList)
import Data.Function
import Control.Lens
import Data.List
import Text.Printf
import Data.Char
import BioInf.GrammarProducts.Grammar
renderGrammarHaskell :: [Grammar] -> String
renderGrammarHaskell = concat . intersperse "\n\n" . map rgh
-- render single grammar
rgh :: Grammar -> String
rgh g = concat $ intersperse "\n\n" [renderSignature g, hsGrammar g]
-- Render just the rules as a multi-dim Haskell grammar. Individual memo-tables
-- and their fill functions are placed into an inductive tuple. The
-- @PrimitiveArray@ library has helper functions for filling such tuples of
-- tables.
--
-- TODO explicitly annotate the @""@ terminal symbol as the 'None' terminal
-- parser.
hsGrammar :: Grammar -> String
hsGrammar g = hdr ++ (concat $ inlined 2 $ [ "(Z:.\n" ] ++ intersperse i ts ++ [")" ]) ++ inl where
hdr = printf "g%s s%s {-non-terminals:-} %s {-terminals:-} %s =\n" (g^.gname) (g^.gname) nbs tbs
nbs = concat . intersperse " " . nub
. concatMap (map mkNtSym . (^.lhs)) . toList $ g^.ps -- non-terminal binders
tbs = concat . intersperse " "
. nub . concatMap mkTSym . filter isT
. concatMap (^.rhs) . toList $ g^.ps -- terminal binders
i = ":."
ts = map (mkProdRule (printf "s%s" (g^.gname))) xs
xs = groupBy ((==) `on` (^.lhs)) . toList $ g^.ps
inl = printf "\n{-# INLINE g%s #-}\n" (g^.gname)
mkTSym :: NtT -> [String]
mkTSym nt@Nt{..} = error $ "dying at finding non-terminal symbol in mkTSym: " ++ show nt
mkTSym (T _ ts) = zipWith (\(TSym t) n -> printf "%s_%d" t n) (filter (not . null . (^.tname)) ts) [1 :: Int ..]
mkNtSym :: NtT -> String
mkNtSym t@T{..} = error $ "dying at finding terminal symbol in mkNtSym: " ++ show t
mkNtSym (Nt _ ns) = concatMap f ns
where f (NTSym n 1 _) = printf "%s" (lowerHead n)
f (NTSym n _ i) = printf "%s%d" (lowerHead n) i
mkProdRule :: String -> [PR] -> String
mkProdRule c ps@(p:_)
| any (l/=) ls = error $ "found malformed production rule:" ++ show (p,ps)
| otherwise = "( " ++ concatMap mkNtSym l ++ " , " ++ mkRHS c rs ++ " )\n"
where ls = map (^.lhs) ps
rs = ps
l = p^.lhs
mkRHS :: String -> [PR] -> String
mkRHS c ps = (concat $ intersperse " ||| " $ map (mkRule c) ps) ++ " ... h " ++ c
mkRule :: String -> PR -> String
mkRule c p = mkFunName (p^.fun) ++ " " ++ c ++ " <<< " ++ (concat $ intersperse " % " $ map mkNtT $ p^.rhs)
mkNtT t@T{..} = "(T:!" ++ (concat $ intersperse ":!" $ zipWith mkSingleTSym' [1::Int ..] (t^.symT)) ++ ")"
mkNtT nt = mkNtSym nt
mkSingleTSym' d (TSym t)
| null t = "None"
| otherwise = printf "%s_%d" t d
mkSingleTSym (TSym n)
| null n = "()"
| otherwise = n
lowerHead [] = []
lowerHead (x:xs) = toLower x : xs
inlined k xs = map (replicate k ' ' ++) xs
-- render the signature
renderSignature :: Grammar -> String
renderSignature g = printf "data S%s _m _x _r %s = S%s\n { "
(g^.gname) ts (g^.gname) ++ (concat $ intersperse "\n , " xs) ++ "\n }"
where
xs = (map mkFunType . toList $ g^.ps) ++ ["h :: Stream _m _x -> _m _r"]
ts = concat . intersperse " " . nub
. filter (not . null) . map (^.tname)
. concatMap (^.symT) . filter isT
. concatMap (^.rhs) . toList $ g^.ps
mkFunName = concat . intersperse "_"
mkFunType p = (concat . intersperse "_" $ p^.fun) ++ " :: " ++ as where
as = (concat $ intersperse " -> " $ map trans $ p^.rhs) ++ " -> _x"
-- trans t@T{..} = "(Z:." ++ (concat $ intersperse ":." $ map mkSingleTSym (t^.symT)) ++ ")"
trans t@T{..} = foldl' (\s n -> concat ["(",s,":.",n,")"]) "Z" $ map mkSingleTSym (t^.symT)
trans nt = "_x" -- mkNtSym nt
-- render algebra product
doctorsNote = "\n-- TODO you now need to define the module name, the imports, as well as algebras and table-filling"
|
choener/GrammarProducts
|
old-BioInf/GrammarProducts/Haskell.hs
|
gpl-3.0
| 4,050 | 0 | 17 | 906 | 1,456 | 761 | 695 | 69 | 2 |
module Main where
import System.IO
import System.Environment
import System.Process.Internals
import System.Directory
import Control.Monad
import Control.Exception
import Text.Read
import Text.Regex
import Data.List
import qualified System.Process as P
import qualified Data.ByteString.Lazy as B
import qualified System.Posix.Types as T
import qualified Data.Map as Map
-- type declarations ----------------------
type Options = Map.Map String String
type Config = Map.Map String String
empty :: Options
empty = Map.fromList []
defconf :: Config
defconf = Map.fromList []
-------------------------------------------
main = do
putStrLn "spawn v0.9.10"
args <- getArgs
case args of
["--help"] -> showHelp
(cmd:rest) -> runCommand cmd $ consumeOpts rest
otherwise -> cError
-- function definitions -------------------
runCommand :: String -> Options -> IO ()
runCommand "init" opts = cInit opts
runCommand "start" opts = checkConfig opts cStart
runCommand "stop" opts = checkConfig opts cStop
runCommand "reload" opts = checkConfig opts cReload
runCommand "status" opts = checkConfig opts cStatus
runCommand "clean" opts = checkConfig opts cClean
runCommand c o = cError
consumeOpts' :: Options -> [String] -> Options
consumeOpts' opt [] = opt
consumeOpts' opt [_] = opt
consumeOpts' opt ("-f":v:os) = consumeOpts' (Map.insert "proc" v opt) os
consumeOpts' opt ("-p":v:os) = consumeOpts' (Map.insert "port" v opt) os
consumeOpts' opt ("-d":v:os) = consumeOpts' (Map.insert "dir" v opt) os
consumeOpts' opt ("--onstart":v:os) = consumeOpts' (Map.insert "start" v opt) os
consumeOpts' opt ("--onstop":v:os) = consumeOpts' (Map.insert "stop" v opt) os
consumeOpts' opt (_:_:os) = consumeOpts' opt os
consumeOpts :: [String] -> Options
consumeOpts = consumeOpts' empty
checkConfig :: Options -> (Options -> IO ()) -> IO ()
checkConfig opts continue = do
let dir = getDir $ opts # "dir"
let confPath = (dir ++ "/" ++ ".spawn")
confExists <- doesFileExist confPath
if confExists
then continue opts
else putStrLn $ "not a spawn config" ++ "\nrun spawn init first"
readConfig :: String -> IO (Config)
readConfig dir = do
contents <- fmap lines $ readFile (dir ++ "/" ++ ".spawn")
let keys = ["proc","port","start","stop"]
return (Map.fromList $ zip keys contents)
(#) :: Map.Map String String -> String -> Maybe String
k # m = if value=="$invalid" then Nothing
else Just value
where value = extract $ Map.lookup m k
extract :: Maybe String -> String
extract Nothing = "$invalid"
extract (Just x) = x
-- |fallback to current directory if no -d flag passed
getDir :: Maybe String -> String
getDir Nothing = "."
getDir (Just x) = x
-- |read process id from spawn-fcgi output
getPid :: String -> Maybe String
getPid output = fmap (!! 0) $ matchRegex (mkRegex "spawn-fcgi: child spawned successfully: PID: ([0-9]+)") output
-- |retrieve process id of application
processState :: String -> IO (Maybe String)
processState dir = do
let pidPath = dir ++ "/.pid"
pidfExists <- doesFileExist pidPath
if pidfExists
then do
oPid <- readFile pidPath
procExists <- doesDirectoryExist ("/proc/" ++ oPid)
if procExists
then return (Just oPid)
else do
removeFile pidPath
return Nothing
else return Nothing
-- |initialize a spawn template
cInit :: Options -> IO ()
cInit opts = do
putStr "creating spawn config: "
let proc = opts # "proc"
let port = opts # "port"
if proc == Nothing || port == Nothing
then putStrLn $ "invalid options\n" ++ "usage: spawn init -p <port> -f <process> [--onstart <command>] [--onstop <command>]"
else do
let start = opts # "start"
let stop = opts # "stop"
let config = extract proc ++ "\n" ++ extract port ++ "\n" ++ extract start ++ "\n" ++ extract stop
writeFile ".spawn" config
putStrLn "ok."
cStart :: Options -> IO ()
cStart opts = do
putStr "spawning process: "
let dir = getDir $ opts # "dir"
config <- readConfig dir
let exec = "./" ++ (extract $ config # "proc")
let start = config # "start"
mPid <- processState dir
case mPid of
Just _ -> putStrLn "already running!"
Nothing -> do
ph <- if dir /= "."
then P.readCreateProcess (P.shell $ intercalate " " ["spawn-fcgi -d" , dir, " -f", exec, "-p", (extract $ config # "port")]) ""
else P.readCreateProcess (P.shell $ intercalate " " ["spawn-fcgi -f", exec, "-p", (extract $ config # "port")]) ""
let mPid = getPid ph
case mPid of
Nothing -> putStrLn "error"
Just p -> do
let pidPath = dir ++ "/.pid"
writeFile pidPath p
putStrLn p
if start /= Nothing
then do
P.spawnCommand $ extract start
return ()
else return ()
cStop :: Options -> IO ()
cStop opts = do
let dir = getDir $ opts # "dir"
config <- readConfig dir
putStr "terminating process: "
mPid <- processState dir
case mPid of
Just pid -> do
handle <- mkProcessHandle (T.CPid $ read pid) False
P.terminateProcess handle
P.callCommand $ "sleep 0.5"
let stop = config # "stop"
putStrLn "ok."
if stop /= Nothing
then do
P.spawnCommand $ extract stop
else return ()
Nothing -> putStrLn "cannot attach to process."
let pidPath = dir ++ "/.pid"
pidExists <- doesFileExist pidPath
if pidExists
then removeFile pidPath
else return ()
cReload :: Options -> IO ()
cReload opts = do
(cStop opts)
P.callCommand $ "sleep 2"
(cStart opts)
cStatus :: Options -> IO ()
cStatus opts = do
let dir = getDir $ opts # "dir"
config <- readConfig dir
let onstart = config # "start"
let onstop = config # "stop"
let exec = (extract $ config # "proc")
let port = (extract $ config # "port")
mPid <- processState dir
putStrLn "configuration:"
putStrLn $ "status: " ++ case mPid of Just p -> "running (" ++ p ++ ")"
Nothing -> "stopped"
putStrLn $ "process: " ++ exec
putStrLn $ "port: " ++ port
if onstart/=Nothing
then putStrLn $ "onstart: " ++ extract onstart
else return ()
if onstop/=Nothing
then putStrLn $ "onstop: " ++ extract onstop
else return ()
cClean :: Options -> IO ()
cClean opts = do
spconf <- doesFileExist ".spawn"
if spconf
then do
cStop opts
putStr "removing configuration: "
removeFile ".spawn"
putStrLn "ok."
else putStrLn "error: spawn template not found."
cError :: IO ()
cError = do
putStrLn "unknown command!"
putStrLn "usage: spawn [init|start|stop|reload|status|clean] [options]"
showHelp :: IO ()
showHelp = do
putStrLn "usage: spawn [init|start|stop|reload|status|clean] [options]"
putStrLn $ "init: initialize new spawn template\n" ++
" -f: (required) fcgi application file\n" ++
" -p: (required) port number\n" ++
" --onstart: (optional) command to run after application has started\n" ++
" --onstop: (optional) command to run after application has terminated"
putStrLn $ "start: start the spawn process\n" ++
" -d: (optional) path to spawn directory"
putStrLn $ "stop: terminate the spawn process\n" ++
" -d: (optional) path to spawn directory"
putStrLn $ "reload: restart the spawn process\n" ++
" -d: (optional) path to spawn directory"
putStrLn $ "status: print process status and configuration"
putStrLn $ "clean: stop the process and remove configuration file"
|
hgeg/spawn
|
Main.hs
|
gpl-3.0
| 7,659 | 0 | 21 | 1,883 | 2,337 | 1,136 | 1,201 | 202 | 5 |
{-# LANGUAGE ScopedTypeVariables, NoMonomorphismRestriction, RecordWildCards #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.State
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Traversable as T
import qualified Data.HashMap.Lazy as HM
import Data.Maybe
import Data.Monoid ((<>))
import System.Directory
import System.Environment
import System.FilePath ((</>))
import System.IO
import System.Log.Logger
--
import HEP.Automation.EventChain.Driver
import HEP.Automation.EventChain.File
import HEP.Automation.EventChain.LHEConn
import HEP.Automation.EventChain.Type.MultiProcess
import HEP.Automation.EventChain.Type.Skeleton
import HEP.Automation.EventChain.Type.Spec
import HEP.Automation.EventChain.Type.Process
import HEP.Automation.EventChain.SpecDSL
import HEP.Automation.EventChain.Simulator
import HEP.Automation.EventChain.Process
import HEP.Automation.EventChain.Process.Generator
import HEP.Automation.EventGeneration.Config
import HEP.Automation.EventGeneration.Type
import HEP.Automation.EventGeneration.Work
import HEP.Automation.MadGraph.Model.ADMXQLD111degen
import HEP.Automation.MadGraph.Run
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Type
import HEP.Parser.LHE.Type
import HEP.Parser.LHE.Sanitizer.Type
import HEP.Storage.WebDAV
--
import qualified Paths_madgraph_auto as PMadGraph
import qualified Paths_madgraph_auto_model as PModel
jets = [1,2,3,4,-1,-2,-3,-4,21]
leptons = [11,13,-11,-13]
lepplusneut = [11,12,13,14,-11,-12,-13,-14]
neut = [1000022]
adms = [9000201,-9000201,9000202,-9000202]
squarks = [ 1000001, -1000001 -- sdown_L
, 1000002, -1000002 -- sup_L
, 1000003, -1000003 -- sstrange_L
, 1000004, -1000004 -- scharm_L
, 2000001, -2000001 -- sdown_R
, 2000002, -2000002 -- sup_R
, 2000003, -2000003 -- sstrange_R
, 2000004, -2000004 -- scharm_R
]
p_gluino :: DDecay
p_gluino = d ([1000021], [p_neut, t jets, t jets])
p_neut :: DDecay
p_neut = d (neut, [t lepplusneut, t jets, t jets, t adms])
p_squark :: DDecay
p_squark = d (squarks, [p_neut, t jets])
p_2sg_2l8j2x :: DCross
p_2sg_2l8j2x = x (t proton, t proton, [p_gluino, p_gluino])
map_2sg_2l8j2x :: ProcSpecMap
map_2sg_2l8j2x =
HM.fromList [ (Nothing , MGProc [] [ "p p > go go QED=0" ])
, (Just (3,1000021,[]), MGProc []
[ "go > n1 j j " ] )
, (Just (4,1000021,[]), MGProc []
[ "go > n1 j j " ] )
, (Just (1,1000022,[3]), MGProc [ "define lep = e+ e- mu+ mu- ve ve~ vm vm~ "
, "define sxx = sxxp sxxp~ " ]
[ "n1 > sxx lep j j " ] )
, (Just (1,1000022,[4]), MGProc [ "define lep = e+ e- mu+ mu- ve ve~ vm vm~ "
, "define sxx = sxxp sxxp~ " ]
[ "n1 > sxx lep j j " ] )
]
mprocs = mkMultiProc pdir [ SingleProc "2sg_2l8j2x" p_2sg_2l8j2x map_2sg_2l8j2x mgrunsetup
]
modelparam mgl msq msl mneut = ADMXQLD111degenParam mgl msq msl mneut
-- |
mgrunsetup :: NumOfEv -> SetNum -> RunSetup
mgrunsetup (NumOfEv nev) (SetNum sn) =
RS { numevent = nev
, machine = LHC8 ATLAS
, rgrun = Auto
, rgscale = 200.0
, match = NoMatch
, cut = NoCut
, pythia = RunPYTHIA8
, lhesanitizer = [Replace [(9000201,1000022),(-9000201,1000022)]]
, pgs = RunPGS (AntiKTJet 0.4,NoTau)
, uploadhep = NoUploadHEP
, setnum = sn
}
pdir = ProcDir "Work20130805" "montecarlo/admproject/XQLDdegen/8TeV/neutLOSP_mgmnscan" "scan"
m_neutralino :: Double
m_neutralino = 500.0
worksets :: [ (String, (Double,Double,Double,Double,Int)) ]
worksets = set_2sg
where
makeset str lst =
[ (str,(mg,50000.0,50000.0,mn,10000)) | (mg,mn) <- lst ]
set_2sg = makeset "2sg" massset_2sg
massset_2sg = [ (mg, mn) | mg <- [ 200,250..1500 ], mn <- [ 50,100..mg-50] ]
main :: IO ()
main = do
args <- getArgs
let fp = args !! 0
-- cmd = args !! 1
n1 = read (args !! 1) :: Int
n2 = read (args !! 2) :: Int
updateGlobalLogger "MadGraphAuto" (setLevel DEBUG)
-- print (length worksets)
mapM_ (scanwork fp) (drop (n1-1) . take n2 $ worksets )
scanwork :: FilePath -> (String, (Double,Double,Double,Double,Int)) -> IO ()
scanwork fp (cmd, (mgl,msq,msl,mneut,n)) = do
homedir <- getHomeDirectory
getConfig fp >>=
maybe (return ()) (\ec -> do
let ssetup = evgen_scriptsetup ec
whost = evgen_webdavroot ec
pkey = evgen_privatekeyfile ec
pswd = evgen_passwordstore ec
Just cr <- getCredential pkey pswd
let wdavcfg = WebDAVConfig { webdav_credential = cr
, webdav_baseurl = whost }
param = modelparam mgl msq msl mneut
let mjob = case cmd of
"2sg" -> Just ("2sg_2l8j2x", NumOfEv n, SetNum 1)
_ -> Nothing
print mjob
maybe (return ()) (genMultiProcess ADMXQLD111degen ssetup mprocs param wdavcfg) mjob
)
|
wavewave/lhc-analysis-collection
|
exe/2013-08-05-XQLD.hs
|
gpl-3.0
| 5,620 | 0 | 21 | 1,669 | 1,561 | 923 | 638 | 125 | 2 |
module CSC322a2tester where
import CSC322a2
import CSC322a2TestData
testOne q r = queens q == r
testAll tests = [(i, testOne q r) | (i, q, r) <- tests]
result = testAll tests
score = sum [1 | (i, x) <- result, x == True] * 0.2
passed = [i | (i, x) <- result, x == True]
failed = [i | (i, x) <- result, x == False]
results = (score, passed, failed)
|
cwlmyjm/haskell
|
Learning/400/CSC322a2tester.hs
|
mpl-2.0
| 350 | 0 | 10 | 75 | 185 | 104 | 81 | 10 | 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.DynamoDB.BatchGetItem
-- 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.
-- | The /BatchGetItem/ operation returns the attributes of one or more items from
-- one or more tables. You identify requested items by primary key.
--
-- A single operation can retrieve up to 16 MB of data, which can contain as
-- many as 100 items. /BatchGetItem/ will return a partial result if the response
-- size limit is exceeded, the table's provisioned throughput is exceeded, or an
-- internal processing failure occurs. If a partial result is returned, the
-- operation returns a value for /UnprocessedKeys/. You can use this value to
-- retry the operation starting with the next item to get.
--
-- For example, if you ask to retrieve 100 items, but each individual item is
-- 300 KB in size, the system returns 52 items (so as not to exceed the 16 MB
-- limit). It also returns an appropriate /UnprocessedKeys/ value so you can get
-- the next page of results. If desired, your application can include its own
-- logic to assemble the pages of results into one data set.
--
-- If /none/ of the items can be processed due to insufficient provisioned
-- throughput on all of the tables in the request, then /BatchGetItem/ will return
-- a /ProvisionedThroughputExceededException/. If /at least one/ of the items is
-- successfully processed, then /BatchGetItem/ completes successfully, while
-- returning the keys of the unread items in /UnprocessedKeys/.
--
-- If DynamoDB returns any unprocessed items, you should retry the batch
-- operation on those items. However, /we strongly recommend that you use anexponential backoff algorithm/. If you retry the batch operation immediately,
-- the underlying read or write requests can still fail due to throttling on the
-- individual tables. If you delay the batch operation using exponential
-- backoff, the individual requests in the batch are much more likely to succeed.
--
-- For more information, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#BatchOperations Batch Operations and Error Handling> in the /AmazonDynamoDB Developer Guide/.
--
-- By default, /BatchGetItem/ performs eventually consistent reads on every
-- table in the request. If you want strongly consistent reads instead, you can
-- set /ConsistentRead/ to 'true' for any or all tables.
--
-- In order to minimize response latency, /BatchGetItem/ retrieves items in
-- parallel.
--
-- When designing your application, keep in mind that DynamoDB does not return
-- attributes in any particular order. To help parse the response by item,
-- include the primary key values for the items in your request in the /AttributesToGet/ parameter.
--
-- If a requested item does not exist, it is not returned in the result.
-- Requests for nonexistent items consume the minimum read capacity units
-- according to the type of read. For more information, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#CapacityUnitCalculations Capacity UnitsCalculations> in the /Amazon DynamoDB Developer Guide/.
--
-- <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html>
module Network.AWS.DynamoDB.BatchGetItem
(
-- * Request
BatchGetItem
-- ** Request constructor
, batchGetItem
-- ** Request lenses
, bgiRequestItems
, bgiReturnConsumedCapacity
-- * Response
, BatchGetItemResponse
-- ** Response constructor
, batchGetItemResponse
-- ** Response lenses
, bgirConsumedCapacity
, bgirResponses
, bgirUnprocessedKeys
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DynamoDB.Types
import qualified GHC.Exts
data BatchGetItem = BatchGetItem
{ _bgiRequestItems :: Map Text KeysAndAttributes
, _bgiReturnConsumedCapacity :: Maybe ReturnConsumedCapacity
} deriving (Eq, Read, Show)
-- | 'BatchGetItem' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'bgiRequestItems' @::@ 'HashMap' 'Text' 'KeysAndAttributes'
--
-- * 'bgiReturnConsumedCapacity' @::@ 'Maybe' 'ReturnConsumedCapacity'
--
batchGetItem :: BatchGetItem
batchGetItem = BatchGetItem
{ _bgiRequestItems = mempty
, _bgiReturnConsumedCapacity = Nothing
}
-- | A map of one or more table names and, for each table, a map that describes
-- one or more items to retrieve from that table. Each table name can be used
-- only once per /BatchGetItem/ request.
--
-- Each element in the map of items to retrieve consists of the following:
--
-- /ConsistentRead/ - If 'true', a strongly consistent read is used; if 'false'
-- (the default), an eventually consistent read is used.
--
-- /ExpressionAttributeNames/ - One or more substitution tokens for attribute
-- names in the /ProjectionExpression/ parameter. The following are some use cases
-- for using /ExpressionAttributeNames/:
--
-- To access an attribute whose name conflicts with a DynamoDB reserved word.
--
-- To create a placeholder for repeating occurrences of an attribute name in
-- an expression.
--
-- To prevent special characters in an attribute name from being
-- misinterpreted in an expression.
--
-- Use the # character in an expression to dereference an attribute name. For
-- example, consider the following attribute name:
--
-- 'Percentile'
--
-- The name of this attribute conflicts with a reserved word, so it cannot be
-- used directly in an expression. (For the complete list of reserved words, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html Reserved Words> in the /Amazon DynamoDB Developer Guide/). To work around this,
-- you could specify the following for /ExpressionAttributeNames/:
--
-- '{"#P":"Percentile"}'
--
-- You could then use this substitution in an expression, as in this example:
--
-- '#P = :val'
--
-- Tokens that begin with the : character are /expression attribute values/,
-- which are placeholders for the actual value at runtime.
--
-- For more information on expression attribute names, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing ItemAttributes> in the /Amazon DynamoDB Developer Guide/.
--
-- /Keys/ - An array of primary key attribute values that define specific items
-- in the table. For each primary key, you must provide /all/ of the key
-- attributes. For example, with a hash type primary key, you only need to
-- provide the hash attribute. For a hash-and-range type primary key, you must
-- provide /both/ the hash attribute and the range attribute.
--
-- /ProjectionExpression/ - A string that identifies one or more attributes to
-- retrieve from the table. These attributes can include scalars, sets, or
-- elements of a JSON document. The attributes in the expression must be
-- separated by commas.
--
-- If no attribute names are specified, then all attributes will be returned.
-- If any of the requested attributes are not found, they will not appear in the
-- result.
--
-- For more information, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing Item Attributes> in the /Amazon DynamoDBDeveloper Guide/.
--
-- /AttributesToGet/ -
--
-- This is a legacy parameter, for backward compatibility. New applications
-- should use /ProjectionExpression/ instead. Do not combine legacy parameters and
-- expression parameters in a single API call; otherwise, DynamoDB will return a /ValidationException/ exception.
--
-- This parameter allows you to retrieve attributes of type List or Map;
-- however, it cannot retrieve individual elements within a List or a Map.
--
-- The names of one or more attributes to retrieve. If no attribute names are
-- provided, then all attributes will be returned. If any of the requested
-- attributes are not found, they will not appear in the result.
--
-- Note that /AttributesToGet/ has no effect on provisioned throughput
-- consumption. DynamoDB determines capacity units consumed based on item size,
-- not on the amount of data that is returned to an application.
--
--
bgiRequestItems :: Lens' BatchGetItem (HashMap Text KeysAndAttributes)
bgiRequestItems = lens _bgiRequestItems (\s a -> s { _bgiRequestItems = a }) . _Map
bgiReturnConsumedCapacity :: Lens' BatchGetItem (Maybe ReturnConsumedCapacity)
bgiReturnConsumedCapacity =
lens _bgiReturnConsumedCapacity
(\s a -> s { _bgiReturnConsumedCapacity = a })
data BatchGetItemResponse = BatchGetItemResponse
{ _bgirConsumedCapacity :: List "ConsumedCapacity" ConsumedCapacity
, _bgirResponses :: Map Text (List "Responses" (Map Text AttributeValue))
, _bgirUnprocessedKeys :: Map Text KeysAndAttributes
} deriving (Eq, Read, Show)
-- | 'BatchGetItemResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'bgirConsumedCapacity' @::@ ['ConsumedCapacity']
--
-- * 'bgirResponses' @::@ 'HashMap' 'Text' ['HashMap' 'Text' 'AttributeValue']
--
-- * 'bgirUnprocessedKeys' @::@ 'HashMap' 'Text' 'KeysAndAttributes'
--
batchGetItemResponse :: BatchGetItemResponse
batchGetItemResponse = BatchGetItemResponse
{ _bgirResponses = mempty
, _bgirUnprocessedKeys = mempty
, _bgirConsumedCapacity = mempty
}
-- | The read capacity units consumed by the operation.
--
-- Each element consists of:
--
-- /TableName/ - The table that consumed the provisioned throughput.
--
-- /CapacityUnits/ - The total number of capacity units consumed.
--
--
bgirConsumedCapacity :: Lens' BatchGetItemResponse [ConsumedCapacity]
bgirConsumedCapacity =
lens _bgirConsumedCapacity (\s a -> s { _bgirConsumedCapacity = a })
. _List
-- | A map of table name to a list of items. Each object in /Responses/ consists of
-- a table name, along with a map of attribute data consisting of the data type
-- and attribute value.
bgirResponses :: Lens' BatchGetItemResponse (HashMap Text [HashMap Text AttributeValue])
bgirResponses = lens _bgirResponses (\s a -> s { _bgirResponses = a }) . _Map
-- | A map of tables and their respective keys that were not processed with the
-- current response. The /UnprocessedKeys/ value is in the same form as /RequestItems/, so the value can be provided directly to a subsequent /BatchGetItem/
-- operation. For more information, see /RequestItems/ in the Request Parameters
-- section.
--
-- Each element consists of:
--
-- /Keys/ - An array of primary key attribute values that define specific items
-- in the table.
--
-- /AttributesToGet/ - One or more attributes to be retrieved from the table or
-- index. By default, all attributes are returned. If a requested attribute is
-- not found, it does not appear in the result.
--
-- /ConsistentRead/ - The consistency of a read operation. If set to 'true', then
-- a strongly consistent read is used; otherwise, an eventually consistent read
-- is used.
--
-- If there are no unprocessed keys remaining, the response contains an empty /UnprocessedKeys/ map.
bgirUnprocessedKeys :: Lens' BatchGetItemResponse (HashMap Text KeysAndAttributes)
bgirUnprocessedKeys =
lens _bgirUnprocessedKeys (\s a -> s { _bgirUnprocessedKeys = a })
. _Map
instance ToPath BatchGetItem where
toPath = const "/"
instance ToQuery BatchGetItem where
toQuery = const mempty
instance ToHeaders BatchGetItem
instance ToJSON BatchGetItem where
toJSON BatchGetItem{..} = object
[ "RequestItems" .= _bgiRequestItems
, "ReturnConsumedCapacity" .= _bgiReturnConsumedCapacity
]
instance AWSRequest BatchGetItem where
type Sv BatchGetItem = DynamoDB
type Rs BatchGetItem = BatchGetItemResponse
request = post "BatchGetItem"
response = jsonResponse
instance FromJSON BatchGetItemResponse where
parseJSON = withObject "BatchGetItemResponse" $ \o -> BatchGetItemResponse
<$> o .:? "ConsumedCapacity" .!= mempty
<*> o .:? "Responses" .!= mempty
<*> o .:? "UnprocessedKeys" .!= mempty
|
romanb/amazonka
|
amazonka-dynamodb/gen/Network/AWS/DynamoDB/BatchGetItem.hs
|
mpl-2.0
| 13,049 | 0 | 16 | 2,302 | 868 | 570 | 298 | 79 | 1 |
{-|
Module : Main
-}
module Main where
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.Timeout
import Control.Monad (unless)
import System.IO (hPutStr, stderr)
import Parser
import Text.Parsec.Error (messageString, errorMessages)
import Eval
import Ast (pretty)
import Trans (trans)
import ToData (todata)
-- import Debug.Trace
data Flag = Time Int | From KindD | To KindD deriving Show
data KindD = RCore | RCoreData | RWhile | RWhileWM deriving (Show,Read)
options :: [OptDescr Flag]
options = [ Option ['t'] ["time"] (ReqArg (Time . read) "10") "timeout after N seconds"
, Option [] ["from"] (ReqArg (From . read) "RWhileWM") "transform from"
, Option [] ["to"] (ReqArg (To . read) "RCore") "transform to"
]
processArg :: [Flag] -> (Int,KindD,KindD)
processArg [] = (10,RWhileWM,RCore)
processArg (a:as) = let (time,from,to) = processArg as in
case a of
Time time' -> (time',from,to)
From from' -> (time,from',to)
To to' -> (time,from,to')
main :: IO ()
main = do args <- getArgs
case getOpt Permute options args of
(t,[prog],[]) ->
let (time,from,to) = processArg t in
do prog_str <- loadFile prog
prog <- case parseProgram prog_str of
Left err -> print err >> exitWith (ExitFailure 1)
Right p -> return p
let wellFormed = case from of
RCore -> wellFormedRCore
RWhile -> wellFormedRWhile
RWhileWM -> wellFormedRWhileWM
unless (wellFormed prog) (print "not well formed" >> exitWith (ExitFailure 1))
case (from,to) of
(_, RCoreData) -> print (pretty (todata prog))
(_, RCore) -> print (pretty (trans prog))
(_, RWhileWM) -> print (pretty (trans prog))
(_, _) -> print "not implemented in Main.main"
(t,[prog,val],[]) ->
do res <- let (time,_,_) = processArg t
in timeout (time * 1000000) $ parseAndRun prog val
case res of
Nothing -> exitWith $ ExitFailure 124
_ -> return ()
(_,_,errs) -> hPutStr stderr (concat errs ++ "\n" ++ usageInfo header options) >> exitWith (ExitFailure 1)
where header = "Usage: rw [options] <file>"
loadFile :: String -> IO String
loadFile "-" = getContents
loadFile filename = readFile filename
parseAndRun :: String -> String -> IO ()
parseAndRun prog_file val_file =
do prog_str <- loadFile prog_file
val_str <- loadFile val_file
case Parser.parseProgram prog_str of
Left err -> print err >> exitWith (ExitFailure 1)
Right prog -> case parseVal val_str of
Left err -> mapM_ (hPutStr stderr . messageString) (errorMessages err) >> exitWith (ExitFailure 1)
Right val -> print $ pretty $ execProgram prog val
|
tyoko-dev/rwhile-B-haskell
|
src/Main.hs
|
agpl-3.0
| 3,273 | 0 | 21 | 1,179 | 1,067 | 552 | 515 | 65 | 10 |
module Main where
states = [(tennessee, mississippi, alabama, georgia, florida) |
tennessee <- ["red", "blue", "green"],
mississippi <- ["red", "blue", "green"],
alabama <- ["red", "blue", "green"],
georgia <- ["red", "blue", "green"],
florida <- ["red", "blue", "green"],
tennessee /= mississippi,
tennessee /= alabama,
tennessee /= georgia,
mississippi /= alabama,
alabama /= georgia,
florida /= alabama,
florida /= georgia]
|
Olical/langs
|
haskell/day1/states.hs
|
unlicense
| 527 | 0 | 8 | 157 | 168 | 96 | 72 | 14 | 1 |
module ConstantFusion where
c' :: a -> Char
c' = const 'c'
constantFusion :: (b -> c) -> (a -> b) -> a -> c
constantFusion c f = c . f
c0 :: Char
c0 = constantFusion c' (+1) 45
c0' :: Char
c0' = c' 45
c1 :: Integer
c1 = const 30 . ("foo" ++) $ "bar"
c1' :: Integer
c1' = const 30 3.4
-- End
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/book/2019-Program_Design_by_Calculation-Oliveira/2015-05-LambdaConf/ConstantFusion.hs
|
unlicense
| 298 | 0 | 8 | 77 | 141 | 78 | 63 | 13 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Monad
import Data.Typeable
import Data.Int
import Foreign.Ptr
import Foreign.Storable
import Flow
import Flow.Vector
import Flow.Halide
import System.Posix.Signals
-- Needed for FFI to work
import Data.Vector.HFixed.Class ()
import Flow.Halide.Types ()
-- Data tags
data Vec deriving Typeable
data Sum deriving Typeable
-- Abstract flow signatures
f, g :: Flow Vec
f = flow "f"
g = flow "g"
pp :: Flow Vec -> Flow Vec -> Flow Vec
pp = flow "product"
a :: Flow Vec -> Flow Sum
a = flow "sum"
ddp :: Flow Sum
ddp = a $ pp f g
-- Vector representation
type VecRepr = DynHalideRepr Dim0 Float Vec
vecRepr :: Domain Range -> VecRepr
vecRepr = dynHalideRepr dim0
type SumRepr = HalideRepr Z Float Sum
sumRepr :: SumRepr
sumRepr = halideRepr Z
-- Kernels
fKern :: Domain Range -> Kernel Vec
fKern size = halideKernel0 "f" (vecRepr size) kern_generate_f'''
foreign import ccall unsafe kern_generate_f :: HalideFun '[] VecRepr
kern_generate_f' :: HalideFun '[] VecRepr
kern_generate_f' = case kern_generate_f of
HalideKernel ff -> HalideKernel $ \p -> do
n <- peekByteOff (castPtr p) 48
case n :: Int32 of
0 -> error "Zero arrived!"
_ -> ff p
kern_generate_f'' :: HalideFun '[] VecRepr
kern_generate_f'' = HalideKernel $ error "I crash always!"
kern_generate_f''' :: HalideFun '[] VecRepr
kern_generate_f''' = case kern_generate_f of
HalideKernel ff -> HalideKernel $ \p -> do
n <- peekByteOff (castPtr p) 48
case n :: Int32 of
-- Kill process in most brutal way possible
-- 0 -> raiseSignal sigKILL >> return 0
333333 -> raiseSignal sigKILL >> return 0
_ -> ff p
gKern :: Domain Range -> Kernel Vec
gKern size = halideKernel0 "g" (vecRepr size) kern_generate_g
foreign import ccall unsafe kern_generate_g :: HalideFun '[] VecRepr
ppKern :: Domain Range -> Flow Vec -> Flow Vec -> Kernel Vec
ppKern size = halideKernel1Write "pp" (vecRepr size) (vecRepr size) kern_dotp
foreign import ccall unsafe kern_dotp :: HalideFun '[ VecRepr ] VecRepr
aKern :: Domain Range -> Flow Vec -> Kernel Sum
aKern size = halideKernel1 "a" (vecRepr size) sumRepr kern_sum
foreign import ccall unsafe kern_sum :: HalideFun '[ VecRepr ] SumRepr
-- Dummy recover kernel
recoverKern :: Domain Range -> Kernel Vec
recoverKern size = halideKernel0 "recover" (vecRepr size) kern_recovery
foreign import ccall unsafe kern_recovery :: HalideFun '[] VecRepr
printKern :: Flow Sum -> Kernel Sum
printKern = mergingKernel "print" (sumRepr :. Z) NoRepr $ \case
[(sv,_)]-> \_ -> do
s <- peekVector (castVector sv :: Vector Float) 0
putStrLn $ "Sum: " ++ show s
return nullVector
_other -> fail "printKern: Received wrong number of input buffers!"
-- | Dot product, non-distributed
dpStrat :: Int -> Strategy ()
dpStrat size = do
-- Make vector domain
dom <- makeRangeDomain 0 size
-- Calculate ddp for the whole domain
bind f (fKern dom)
bind g (gKern dom)
recover f (recoverKern dom)
recover g (recoverKern dom)
bindRule pp (ppKern dom)
bindRule a (aKern dom)
calculate ddp
rebind ddp printKern
-- | Dot product, distributed
ddpStrat :: Int -> Strategy ()
ddpStrat size = do
-- Make vector domain
dom <- makeRangeDomain 0 size
-- Calculate ddp for the whole domain
regs <- split dom 3
distribute regs ParSchedule $ do
bind f (fKern regs)
bind g (gKern regs)
bind (pp f g) (ppKern regs f g)
--
recover f (recoverKern regs)
recover g (recoverKern regs)
recover (pp f g) (recoverKern regs)
bindRule a (aKern dom)
calculate ddp
void $ bindNew $ printKern ddp
main :: IO ()
main = do
let size = 1000000
dumpSteps $ ddpStrat size
print "================================================================"
execStrategyDNA False $ ddpStrat size
putStrLn $ "Expected: " ++ show ((size-1)*size`div`20)
|
SKA-ScienceDataProcessor/RC
|
MS6/programs/dotproduct.hs
|
apache-2.0
| 3,991 | 0 | 16 | 794 | 1,311 | 646 | 665 | -1 | -1 |
{-# LANGUAGE TransformListComp #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Html.Decl
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mark Lentczner 2010
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Backends.Xhtml.Decl (
ppDecl,
ppTyName, ppTyFamHeader, ppTypeApp,
tyvarNames
) where
import Haddock.Backends.Xhtml.DocMarkup
import Haddock.Backends.Xhtml.Layout
import Haddock.Backends.Xhtml.Names
import Haddock.Backends.Xhtml.Types
import Haddock.Backends.Xhtml.Utils
import Haddock.GhcUtils
import Haddock.Types
import Haddock.Doc (combineDocumentation)
import Control.Applicative
import Data.List ( intersperse, sort )
import qualified Data.Map as Map
import Data.Maybe
import Text.XHtml hiding ( name, title, p, quote )
import GHC
import GHC.Exts
import Name
import BooleanFormula
ppDecl :: Bool -> LinksInfo -> LHsDecl DocName
-> DocForDecl DocName -> [DocInstance DocName] -> [(DocName, Fixity)]
-> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html
ppDecl summ links (L loc decl) (mbDoc, fnArgsDoc) instances fixities subdocs splice unicode qual = case decl of
TyClD (FamDecl d) -> ppTyFam summ False links instances fixities loc mbDoc d splice unicode qual
TyClD d@(DataDecl {}) -> ppDataDecl summ links instances fixities subdocs loc mbDoc d splice unicode qual
TyClD d@(SynDecl {}) -> ppTySyn summ links fixities loc (mbDoc, fnArgsDoc) d splice unicode qual
TyClD d@(ClassDecl {}) -> ppClassDecl summ links instances fixities loc mbDoc subdocs d splice unicode qual
SigD (TypeSig lnames lty _) -> ppLFunSig summ links loc (mbDoc, fnArgsDoc) lnames lty fixities splice unicode qual
SigD (PatSynSig lname qtvs prov req ty) ->
ppLPatSig summ links loc (mbDoc, fnArgsDoc) lname qtvs prov req ty fixities splice unicode qual
ForD d -> ppFor summ links loc (mbDoc, fnArgsDoc) d fixities splice unicode qual
InstD _ -> noHtml
_ -> error "declaration not supported by ppDecl"
ppLFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
[Located DocName] -> LHsType DocName -> [(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppLFunSig summary links loc doc lnames lty fixities splice unicode qual =
ppFunSig summary links loc doc (map unLoc lnames) (unLoc lty) fixities
splice unicode qual
ppFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
[DocName] -> HsType DocName -> [(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppFunSig summary links loc doc docnames typ fixities splice unicode qual =
ppSigLike summary links loc mempty doc docnames fixities (typ, pp_typ)
splice unicode qual
where
pp_typ = ppType unicode qual typ
ppLPatSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName ->
Located DocName ->
(HsExplicitFlag, LHsTyVarBndrs DocName) ->
LHsContext DocName -> LHsContext DocName ->
LHsType DocName ->
[(DocName, Fixity)] ->
Splice -> Unicode -> Qualification -> Html
ppLPatSig summary links loc (doc, _argDocs) (L _ name) (expl, qtvs) lprov lreq typ fixities splice unicode qual
| summary = pref1
| otherwise = topDeclElem links loc splice [name] (pref1 <+> ppFixities fixities qual)
+++ docSection Nothing qual doc
where
pref1 = hsep [ keyword "pattern"
, ppBinder summary occname
, dcolon unicode
, ppLTyVarBndrs expl qtvs unicode qual
, cxt
, ppLType unicode qual typ
]
cxt = case (ppLContextMaybe lprov unicode qual, ppLContextMaybe lreq unicode qual) of
(Nothing, Nothing) -> noHtml
(Nothing, Just req) -> parens noHtml <+> darr <+> req <+> darr
(Just prov, Nothing) -> prov <+> darr
(Just prov, Just req) -> prov <+> darr <+> req <+> darr
darr = darrow unicode
occname = nameOccName . getName $ name
ppSigLike :: Bool -> LinksInfo -> SrcSpan -> Html -> DocForDecl DocName ->
[DocName] -> [(DocName, Fixity)] -> (HsType DocName, Html) ->
Splice -> Unicode -> Qualification -> Html
ppSigLike summary links loc leader doc docnames fixities (typ, pp_typ)
splice unicode qual =
ppTypeOrFunSig summary links loc docnames typ doc
( addFixities $ leader <+> ppTypeSig summary occnames pp_typ unicode
, addFixities . concatHtml . punctuate comma $ map (ppBinder False) occnames
, dcolon unicode
)
splice unicode qual
where
occnames = map (nameOccName . getName) docnames
addFixities html
| summary = html
| otherwise = html <+> ppFixities fixities qual
ppTypeOrFunSig :: Bool -> LinksInfo -> SrcSpan -> [DocName] -> HsType DocName
-> DocForDecl DocName -> (Html, Html, Html)
-> Splice -> Unicode -> Qualification -> Html
ppTypeOrFunSig summary links loc docnames typ (doc, argDocs) (pref1, pref2, sep) splice unicode qual
| summary = pref1
| Map.null argDocs = topDeclElem links loc splice docnames pref1 +++ docSection curName qual doc
| otherwise = topDeclElem links loc splice docnames pref2 +++
subArguments qual (do_args 0 sep typ) +++ docSection curName qual doc
where
curName = getName <$> listToMaybe docnames
argDoc n = Map.lookup n argDocs
do_largs n leader (L _ t) = do_args n leader t
do_args :: Int -> Html -> HsType DocName -> [SubDecl]
do_args n leader (HsForAllTy _ _ tvs lctxt ltype)
= case unLoc lctxt of
[] -> do_largs n leader' ltype
_ -> (leader' <+> ppLContextNoArrow lctxt unicode qual, Nothing, [])
: do_largs n (darrow unicode) ltype
where leader' = leader <+> ppForAll tvs unicode qual
do_args n leader (HsFunTy lt r)
= (leader <+> ppLFunLhType unicode qual lt, argDoc n, [])
: do_largs (n+1) (arrow unicode) r
do_args n leader t
= [(leader <+> ppType unicode qual t, argDoc n, [])]
ppForAll :: LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html
ppForAll tvs unicode qual =
case [ppKTv n k | L _ (KindedTyVar (L _ n) k) <- hsQTvBndrs tvs] of
[] -> noHtml
ts -> forallSymbol unicode <+> hsep ts +++ dot
where ppKTv n k = parens $
ppTyName (getName n) <+> dcolon unicode <+> ppLKind unicode qual k
ppFixities :: [(DocName, Fixity)] -> Qualification -> Html
ppFixities [] _ = noHtml
ppFixities fs qual = foldr1 (+++) (map ppFix uniq_fs) +++ rightEdge
where
ppFix (ns, p, d) = thespan ! [theclass "fixity"] <<
(toHtml d <+> toHtml (show p) <+> ppNames ns)
ppDir InfixR = "infixr"
ppDir InfixL = "infixl"
ppDir InfixN = "infix"
ppNames = case fs of
_:[] -> const noHtml -- Don't display names for fixities on single names
_ -> concatHtml . intersperse (stringToHtml ", ") . map (ppDocName qual Infix False)
uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs
, let d' = ppDir d
, then group by Down (p,d') using groupWith ]
rightEdge = thespan ! [theclass "rightedge"] << noHtml
ppTyVars :: LHsTyVarBndrs DocName -> [Html]
ppTyVars tvs = map ppTyName (tyvarNames tvs)
tyvarNames :: LHsTyVarBndrs DocName -> [Name]
tyvarNames = map getName . hsLTyVarNames
ppFor :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName
-> ForeignDecl DocName -> [(DocName, Fixity)]
-> Splice -> Unicode -> Qualification -> Html
ppFor summary links loc doc (ForeignImport (L _ name) (L _ typ) _ _) fixities
splice unicode qual
= ppFunSig summary links loc doc [name] typ fixities splice unicode qual
ppFor _ _ _ _ _ _ _ _ _ = error "ppFor"
-- we skip type patterns for now
ppTySyn :: Bool -> LinksInfo -> [(DocName, Fixity)] -> SrcSpan
-> DocForDecl DocName -> TyClDecl DocName
-> Splice -> Unicode -> Qualification -> Html
ppTySyn summary links fixities loc doc (SynDecl { tcdLName = L _ name, tcdTyVars = ltyvars
, tcdRhs = ltype })
splice unicode qual
= ppTypeOrFunSig summary links loc [name] (unLoc ltype) doc
(full <+> fixs, hdr <+> fixs, spaceHtml +++ equals)
splice unicode qual
where
hdr = hsep ([keyword "type", ppBinder summary occ] ++ ppTyVars ltyvars)
full = hdr <+> equals <+> ppLType unicode qual ltype
occ = nameOccName . getName $ name
fixs
| summary = noHtml
| otherwise = ppFixities fixities qual
ppTySyn _ _ _ _ _ _ _ _ _ = error "declaration not supported by ppTySyn"
ppTypeSig :: Bool -> [OccName] -> Html -> Bool -> Html
ppTypeSig summary nms pp_ty unicode =
concatHtml htmlNames <+> dcolon unicode <+> pp_ty
where
htmlNames = intersperse (stringToHtml ", ") $ map (ppBinder summary) nms
ppTyName :: Name -> Html
ppTyName = ppName Prefix
--------------------------------------------------------------------------------
-- * Type families
--------------------------------------------------------------------------------
ppTyFamHeader :: Bool -> Bool -> FamilyDecl DocName
-> Unicode -> Qualification -> Html
ppTyFamHeader summary associated d@(FamilyDecl { fdInfo = info
, fdKindSig = mkind })
unicode qual =
(case info of
OpenTypeFamily
| associated -> keyword "type"
| otherwise -> keyword "type family"
DataFamily
| associated -> keyword "data"
| otherwise -> keyword "data family"
ClosedTypeFamily _
-> keyword "type family"
) <+>
ppFamDeclBinderWithVars summary d <+>
(case mkind of
Just kind -> dcolon unicode <+> ppLKind unicode qual kind
Nothing -> noHtml
)
ppTyFam :: Bool -> Bool -> LinksInfo -> [DocInstance DocName] ->
[(DocName, Fixity)] -> SrcSpan -> Documentation DocName ->
FamilyDecl DocName -> Splice -> Unicode -> Qualification -> Html
ppTyFam summary associated links instances fixities loc doc decl splice unicode qual
| summary = ppTyFamHeader True associated decl unicode qual
| otherwise = header_ +++ docSection Nothing qual doc +++ instancesBit
where
docname = unLoc $ fdLName decl
header_ = topDeclElem links loc splice [docname] $
ppTyFamHeader summary associated decl unicode qual <+> ppFixities fixities qual
instancesBit
| FamilyDecl { fdInfo = ClosedTypeFamily mb_eqns } <- decl
, not summary
= subEquations qual $ map (ppTyFamEqn . unLoc) $ fromMaybe [] mb_eqns
| otherwise
= ppInstances instances docname unicode qual
-- Individual equation of a closed type family
ppTyFamEqn TyFamEqn { tfe_tycon = n, tfe_rhs = rhs
, tfe_pats = HsWB { hswb_cts = ts }}
= ( ppAppNameTypes (unLoc n) [] (map unLoc ts) unicode qual
<+> equals <+> ppType unicode qual (unLoc rhs)
, Nothing, [] )
--------------------------------------------------------------------------------
-- * Associated Types
--------------------------------------------------------------------------------
ppAssocType :: Bool -> LinksInfo -> DocForDecl DocName -> LFamilyDecl DocName
-> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html
ppAssocType summ links doc (L loc decl) fixities splice unicode qual =
ppTyFam summ True links [] fixities loc (fst doc) decl splice unicode qual
--------------------------------------------------------------------------------
-- * TyClDecl helpers
--------------------------------------------------------------------------------
-- | Print a type family and its variables
ppFamDeclBinderWithVars :: Bool -> FamilyDecl DocName -> Html
ppFamDeclBinderWithVars summ (FamilyDecl { fdLName = lname, fdTyVars = tvs }) =
ppAppDocNameNames summ (unLoc lname) (tyvarNames tvs)
-- | Print a newtype / data binder and its variables
ppDataBinderWithVars :: Bool -> TyClDecl DocName -> Html
ppDataBinderWithVars summ decl =
ppAppDocNameNames summ (tcdName decl) (tyvarNames $ tcdTyVars decl)
--------------------------------------------------------------------------------
-- * Type applications
--------------------------------------------------------------------------------
-- | Print an application of a DocName and two lists of HsTypes (kinds, types)
ppAppNameTypes :: DocName -> [HsType DocName] -> [HsType DocName]
-> Unicode -> Qualification -> Html
ppAppNameTypes n ks ts unicode qual =
ppTypeApp n ks ts (\p -> ppDocName qual p True) (ppParendType unicode qual)
-- | Print an application of a DocName and a list of Names
ppAppDocNameNames :: Bool -> DocName -> [Name] -> Html
ppAppDocNameNames summ n ns =
ppTypeApp n [] ns ppDN ppTyName
where
ppDN notation = ppBinderFixity notation summ . nameOccName . getName
ppBinderFixity Infix = ppBinderInfix
ppBinderFixity _ = ppBinder
-- | General printing of type applications
ppTypeApp :: DocName -> [a] -> [a] -> (Notation -> DocName -> Html) -> (a -> Html) -> Html
ppTypeApp n [] (t1:t2:rest) ppDN ppT
| operator, not . null $ rest = parens opApp <+> hsep (map ppT rest)
| operator = opApp
where
operator = isNameSym . getName $ n
opApp = ppT t1 <+> ppDN Infix n <+> ppT t2
ppTypeApp n ks ts ppDN ppT = ppDN Prefix n <+> hsep (map ppT $ ks ++ ts)
-------------------------------------------------------------------------------
-- * Contexts
-------------------------------------------------------------------------------
ppLContext, ppLContextNoArrow :: Located (HsContext DocName) -> Unicode
-> Qualification -> Html
ppLContext = ppContext . unLoc
ppLContextNoArrow = ppContextNoArrow . unLoc
ppLContextMaybe :: Located (HsContext DocName) -> Unicode -> Qualification -> Maybe Html
ppLContextMaybe = ppContextNoLocsMaybe . map unLoc . unLoc
ppContextNoArrow :: HsContext DocName -> Unicode -> Qualification -> Html
ppContextNoArrow cxt unicode qual = fromMaybe noHtml $
ppContextNoLocsMaybe (map unLoc cxt) unicode qual
ppContextNoLocs :: [HsType DocName] -> Unicode -> Qualification -> Html
ppContextNoLocs cxt unicode qual = maybe noHtml (<+> darrow unicode) $
ppContextNoLocsMaybe cxt unicode qual
ppContextNoLocsMaybe :: [HsType DocName] -> Unicode -> Qualification -> Maybe Html
ppContextNoLocsMaybe [] _ _ = Nothing
ppContextNoLocsMaybe cxt unicode qual = Just $ ppHsContext cxt unicode qual
ppContext :: HsContext DocName -> Unicode -> Qualification -> Html
ppContext cxt unicode qual = ppContextNoLocs (map unLoc cxt) unicode qual
ppHsContext :: [HsType DocName] -> Unicode -> Qualification-> Html
ppHsContext [] _ _ = noHtml
ppHsContext [p] unicode qual = ppCtxType unicode qual p
ppHsContext cxt unicode qual = parenList (map (ppType unicode qual) cxt)
-------------------------------------------------------------------------------
-- * Class declarations
-------------------------------------------------------------------------------
ppClassHdr :: Bool -> Located [LHsType DocName] -> DocName
-> LHsTyVarBndrs DocName -> [Located ([Located DocName], [Located DocName])]
-> Unicode -> Qualification -> Html
ppClassHdr summ lctxt n tvs fds unicode qual =
keyword "class"
<+> (if not . null . unLoc $ lctxt then ppLContext lctxt unicode qual else noHtml)
<+> ppAppDocNameNames summ n (tyvarNames tvs)
<+> ppFds fds unicode qual
ppFds :: [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html
ppFds fds unicode qual =
if null fds then noHtml else
char '|' <+> hsep (punctuate comma (map (fundep . unLoc) fds))
where
fundep (vars1,vars2) = ppVars vars1 <+> arrow unicode <+> ppVars vars2
ppVars = hsep . map ((ppDocName qual Prefix True) . unLoc)
ppShortClassDecl :: Bool -> LinksInfo -> TyClDecl DocName -> SrcSpan
-> [(DocName, DocForDecl DocName)]
-> Splice -> Unicode -> Qualification -> Html
ppShortClassDecl summary links (ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = tvs
, tcdFDs = fds, tcdSigs = sigs, tcdATs = ats }) loc
subdocs splice unicode qual =
if not (any isVanillaLSig sigs) && null ats
then (if summary then id else topDeclElem links loc splice [nm]) hdr
else (if summary then id else topDeclElem links loc splice [nm]) (hdr <+> keyword "where")
+++ shortSubDecls False
(
[ ppAssocType summary links doc at [] splice unicode qual | at <- ats
, let doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs ] ++
-- ToDo: add associated type defaults
[ ppFunSig summary links loc doc names typ [] splice unicode qual
| L _ (TypeSig lnames (L _ typ) _) <- sigs
, let doc = lookupAnySubdoc (head names) subdocs
names = map unLoc lnames ]
-- FIXME: is taking just the first name ok? Is it possible that
-- there are different subdocs for different names in a single
-- type signature?
)
where
hdr = ppClassHdr summary lctxt (unLoc lname) tvs fds unicode qual
nm = unLoc lname
ppShortClassDecl _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl"
ppClassDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)]
-> SrcSpan -> Documentation DocName
-> [(DocName, DocForDecl DocName)] -> TyClDecl DocName
-> Splice -> Unicode -> Qualification -> Html
ppClassDecl summary links instances fixities loc d subdocs
decl@(ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = ltyvars
, tcdFDs = lfds, tcdSigs = lsigs, tcdATs = ats })
splice unicode qual
| summary = ppShortClassDecl summary links decl loc subdocs splice unicode qual
| otherwise = classheader +++ docSection Nothing qual d
+++ minimalBit +++ atBit +++ methodBit +++ instancesBit
where
classheader
| any isVanillaLSig lsigs = topDeclElem links loc splice [nm] (hdr unicode qual <+> keyword "where" <+> fixs)
| otherwise = topDeclElem links loc splice [nm] (hdr unicode qual <+> fixs)
-- Only the fixity relevant to the class header
fixs = ppFixities [ f | f@(n,_) <- fixities, n == unLoc lname ] qual
nm = tcdName decl
hdr = ppClassHdr summary lctxt (unLoc lname) ltyvars lfds
-- ToDo: add assocatied typ defaults
atBit = subAssociatedTypes [ ppAssocType summary links doc at subfixs splice unicode qual
| at <- ats
, let n = unL . fdLName $ unL at
doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs
subfixs = [ f | f@(n',_) <- fixities, n == n' ] ]
methodBit = subMethods [ ppFunSig summary links loc doc names typ subfixs splice unicode qual
| L _ (TypeSig lnames (L _ typ) _) <- lsigs
, let doc = lookupAnySubdoc (head names) subdocs
subfixs = [ f | n <- names
, f@(n',_) <- fixities
, n == n' ]
names = map unLoc lnames ]
-- FIXME: is taking just the first name ok? Is it possible that
-- there are different subdocs for different names in a single
-- type signature?
minimalBit = case [ s | L _ (MinimalSig _ s) <- lsigs ] of
-- Miminal complete definition = every shown method
And xs : _ | sort [getName n | Var (L _ n) <- xs] ==
sort [getName n | L _ (TypeSig ns _ _) <- lsigs, L _ n <- ns]
-> noHtml
-- Minimal complete definition = the only shown method
Var (L _ n) : _ | [getName n] ==
[getName n' | L _ (TypeSig ns _ _) <- lsigs, L _ n' <- ns]
-> noHtml
-- Minimal complete definition = nothing
And [] : _ -> subMinimal $ toHtml "Nothing"
m : _ -> subMinimal $ ppMinimal False m
_ -> noHtml
ppMinimal _ (Var (L _ n)) = ppDocName qual Prefix True n
ppMinimal _ (And fs) = foldr1 (\a b -> a+++", "+++b) $ map (ppMinimal True) fs
ppMinimal p (Or fs) = wrap $ foldr1 (\a b -> a+++" | "+++b) $ map (ppMinimal False) fs
where wrap | p = parens | otherwise = id
instancesBit = ppInstances instances nm unicode qual
ppClassDecl _ _ _ _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl"
ppInstances :: [DocInstance DocName] -> DocName -> Unicode -> Qualification -> Html
ppInstances instances baseName unicode qual
= subInstances qual instName (map instDecl instances)
where
instName = getOccString $ getName baseName
instDecl :: DocInstance DocName -> SubDecl
instDecl (inst, maybeDoc) = (instHead inst, maybeDoc, [])
instHead (n, ks, ts, ClassInst cs) = ppContextNoLocs cs unicode qual
<+> ppAppNameTypes n ks ts unicode qual
instHead (n, ks, ts, TypeInst rhs) = keyword "type"
<+> ppAppNameTypes n ks ts unicode qual
<+> maybe noHtml (\t -> equals <+> ppType unicode qual t) rhs
instHead (n, ks, ts, DataInst dd) = keyword "data"
<+> ppAppNameTypes n ks ts unicode qual
<+> ppShortDataDecl False True dd unicode qual
lookupAnySubdoc :: Eq id1 => id1 -> [(id1, DocForDecl id2)] -> DocForDecl id2
lookupAnySubdoc n = fromMaybe noDocForDecl . lookup n
-------------------------------------------------------------------------------
-- * Data & newtype declarations
-------------------------------------------------------------------------------
-- TODO: print contexts
ppShortDataDecl :: Bool -> Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html
ppShortDataDecl summary dataInst dataDecl unicode qual
| [] <- cons = dataHeader
| [lcon] <- cons, ResTyH98 <- resTy,
(cHead,cBody,cFoot) <- ppShortConstrParts summary dataInst (unLoc lcon) unicode qual
= (dataHeader <+> equals <+> cHead) +++ cBody +++ cFoot
| ResTyH98 <- resTy = dataHeader
+++ shortSubDecls dataInst (zipWith doConstr ('=':repeat '|') cons)
| otherwise = (dataHeader <+> keyword "where")
+++ shortSubDecls dataInst (map doGADTConstr cons)
where
dataHeader
| dataInst = noHtml
| otherwise = ppDataHeader summary dataDecl unicode qual
doConstr c con = toHtml [c] <+> ppShortConstr summary (unLoc con) unicode qual
doGADTConstr con = ppShortConstr summary (unLoc con) unicode qual
cons = dd_cons (tcdDataDefn dataDecl)
resTy = (con_res . unLoc . head) cons
ppDataDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] ->
[(DocName, DocForDecl DocName)] ->
SrcSpan -> Documentation DocName -> TyClDecl DocName ->
Splice -> Unicode -> Qualification -> Html
ppDataDecl summary links instances fixities subdocs loc doc dataDecl
splice unicode qual
| summary = ppShortDataDecl summary False dataDecl unicode qual
| otherwise = header_ +++ docSection Nothing qual doc +++ constrBit +++ instancesBit
where
docname = tcdName dataDecl
cons = dd_cons (tcdDataDefn dataDecl)
resTy = (con_res . unLoc . head) cons
header_ = topDeclElem links loc splice [docname] $
ppDataHeader summary dataDecl unicode qual <+> whereBit <+> fix
fix = ppFixities (filter (\(n,_) -> n == docname) fixities) qual
whereBit
| null cons = noHtml
| otherwise = case resTy of
ResTyGADT _ _ -> keyword "where"
_ -> noHtml
constrBit = subConstructors qual
[ ppSideBySideConstr subdocs subfixs unicode qual c
| c <- cons
, let subfixs = filter (\(n,_) -> any (\cn -> cn == n)
(map unLoc (con_names (unLoc c)))) fixities
]
instancesBit = ppInstances instances docname unicode qual
ppShortConstr :: Bool -> ConDecl DocName -> Unicode -> Qualification -> Html
ppShortConstr summary con unicode qual = cHead <+> cBody <+> cFoot
where
(cHead,cBody,cFoot) = ppShortConstrParts summary False con unicode qual
-- returns three pieces: header, body, footer so that header & footer can be
-- incorporated into the declaration
ppShortConstrParts :: Bool -> Bool -> ConDecl DocName -> Unicode -> Qualification -> (Html, Html, Html)
ppShortConstrParts summary dataInst con unicode qual = case con_res con of
ResTyH98 -> case con_details con of
PrefixCon args ->
(header_ unicode qual +++ hsep (ppOcc
: map (ppLParendType unicode qual) args), noHtml, noHtml)
RecCon (L _ fields) ->
(header_ unicode qual +++ ppOcc <+> char '{',
doRecordFields fields,
char '}')
InfixCon arg1 arg2 ->
(header_ unicode qual +++ hsep [ppLParendType unicode qual arg1,
ppOccInfix, ppLParendType unicode qual arg2],
noHtml, noHtml)
ResTyGADT _ resTy -> case con_details con of
-- prefix & infix could use hsConDeclArgTys if it seemed to
-- simplify the code.
PrefixCon args -> (doGADTCon args resTy, noHtml, noHtml)
-- display GADT records with the new syntax,
-- Constr :: (Context) => { field :: a, field2 :: b } -> Ty (a, b)
-- (except each field gets its own line in docs, to match
-- non-GADT records)
RecCon (L _ fields) -> (ppOcc <+> dcolon unicode <+>
ppForAllCon forall_ ltvs lcontext unicode qual <+> char '{',
doRecordFields fields,
char '}' <+> arrow unicode <+> ppLType unicode qual resTy)
InfixCon arg1 arg2 -> (doGADTCon [arg1, arg2] resTy, noHtml, noHtml)
where
doRecordFields fields = shortSubDecls dataInst (map (ppShortField summary unicode qual) (map unLoc fields))
doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [
ppForAllCon forall_ ltvs lcontext unicode qual,
ppLType unicode qual (foldr mkFunTy resTy args) ]
header_ = ppConstrHdr forall_ tyVars context
occ = map (nameOccName . getName . unLoc) $ con_names con
ppOcc = case occ of
[one] -> ppBinder summary one
_ -> hsep (punctuate comma (map (ppBinder summary) occ))
ppOccInfix = case occ of
[one] -> ppBinderInfix summary one
_ -> hsep (punctuate comma (map (ppBinderInfix summary) occ))
ltvs = con_qvars con
tyVars = tyvarNames ltvs
lcontext = con_cxt con
context = unLoc (con_cxt con)
forall_ = con_explicit con
mkFunTy a b = noLoc (HsFunTy a b)
-- ppConstrHdr is for (non-GADT) existentials constructors' syntax
ppConstrHdr :: HsExplicitFlag -> [Name] -> HsContext DocName -> Unicode
-> Qualification -> Html
ppConstrHdr forall_ tvs ctxt unicode qual
= (if null tvs then noHtml else ppForall)
+++
(if null ctxt then noHtml else ppContextNoArrow ctxt unicode qual
<+> darrow unicode +++ toHtml " ")
where
ppForall = case forall_ of
Explicit -> forallSymbol unicode <+> hsep (map (ppName Prefix) tvs) <+> toHtml ". "
Qualified -> noHtml
Implicit -> noHtml
ppSideBySideConstr :: [(DocName, DocForDecl DocName)] -> [(DocName, Fixity)]
-> Unicode -> Qualification -> LConDecl DocName -> SubDecl
ppSideBySideConstr subdocs fixities unicode qual (L _ con) = (decl, mbDoc, fieldPart)
where
decl = case con_res con of
ResTyH98 -> case con_details con of
PrefixCon args ->
hsep ((header_ +++ ppOcc)
: map (ppLParendType unicode qual) args)
<+> fixity
RecCon _ -> header_ +++ ppOcc <+> fixity
InfixCon arg1 arg2 ->
hsep [header_ +++ ppLParendType unicode qual arg1,
ppOccInfix,
ppLParendType unicode qual arg2]
<+> fixity
ResTyGADT _ resTy -> case con_details con of
-- prefix & infix could also use hsConDeclArgTys if it seemed to
-- simplify the code.
PrefixCon args -> doGADTCon args resTy
cd@(RecCon _) -> doGADTCon (hsConDeclArgTys cd) resTy
InfixCon arg1 arg2 -> doGADTCon [arg1, arg2] resTy
fieldPart = case con_details con of
RecCon (L _ fields) -> [doRecordFields fields]
_ -> []
doRecordFields fields = subFields qual
(map (ppSideBySideField subdocs unicode qual) (map unLoc fields))
doGADTCon :: [LHsType DocName] -> Located (HsType DocName) -> Html
doGADTCon args resTy = ppOcc <+> dcolon unicode
<+> hsep [ppForAllCon forall_ ltvs (con_cxt con) unicode qual,
ppLType unicode qual (foldr mkFunTy resTy args) ]
<+> fixity
fixity = ppFixities fixities qual
header_ = ppConstrHdr forall_ tyVars context unicode qual
occ = map (nameOccName . getName . unLoc) $ con_names con
ppOcc = case occ of
[one] -> ppBinder False one
_ -> hsep (punctuate comma (map (ppBinder False) occ))
ppOccInfix = case occ of
[one] -> ppBinderInfix False one
_ -> hsep (punctuate comma (map (ppBinderInfix False) occ))
ltvs = con_qvars con
tyVars = tyvarNames (con_qvars con)
context = unLoc (con_cxt con)
forall_ = con_explicit con
-- don't use "con_doc con", in case it's reconstructed from a .hi file,
-- or also because we want Haddock to do the doc-parsing, not GHC.
mbDoc = lookup (unLoc $ head $ con_names con) subdocs >>=
combineDocumentation . fst
mkFunTy a b = noLoc (HsFunTy a b)
ppSideBySideField :: [(DocName, DocForDecl DocName)] -> Unicode -> Qualification
-> ConDeclField DocName -> SubDecl
ppSideBySideField subdocs unicode qual (ConDeclField names ltype _) =
(hsep (punctuate comma (map ((ppBinder False) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype,
mbDoc,
[])
where
-- don't use cd_fld_doc for same reason we don't use con_doc above
-- Where there is more than one name, they all have the same documentation
mbDoc = lookup (unL $ head names) subdocs >>= combineDocumentation . fst
ppShortField :: Bool -> Unicode -> Qualification -> ConDeclField DocName -> Html
ppShortField summary unicode qual (ConDeclField names ltype _)
= hsep (punctuate comma (map ((ppBinder summary) . nameOccName . getName . unL) names))
<+> dcolon unicode <+> ppLType unicode qual ltype
-- | Print the LHS of a data\/newtype declaration.
-- Currently doesn't handle 'data instance' decls or kind signatures
ppDataHeader :: Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html
ppDataHeader summary decl@(DataDecl { tcdDataDefn =
HsDataDefn { dd_ND = nd
, dd_ctxt = ctxt
, dd_kindSig = ks } })
unicode qual
= -- newtype or data
(case nd of { NewType -> keyword "newtype"; DataType -> keyword "data" })
<+>
-- context
ppLContext ctxt unicode qual <+>
-- T a b c ..., or a :+: b
ppDataBinderWithVars summary decl
<+> case ks of
Nothing -> mempty
Just (L _ x) -> dcolon unicode <+> ppKind unicode qual x
ppDataHeader _ _ _ _ = error "ppDataHeader: illegal argument"
--------------------------------------------------------------------------------
-- * Types and contexts
--------------------------------------------------------------------------------
ppBang :: HsBang -> Html
ppBang HsNoBang = noHtml
ppBang _ = toHtml "!" -- Unpacked args is an implementation detail,
-- so we just show the strictness annotation
tupleParens :: HsTupleSort -> [Html] -> Html
tupleParens HsUnboxedTuple = ubxParenList
tupleParens _ = parenList
--------------------------------------------------------------------------------
-- * Rendering of HsType
--------------------------------------------------------------------------------
pREC_TOP, pREC_CTX, pREC_FUN, pREC_OP, pREC_CON :: Int
pREC_TOP = 0 :: Int -- type in ParseIface.y in GHC
pREC_CTX = 1 :: Int -- Used for single contexts, eg. ctx => type
-- (as opposed to (ctx1, ctx2) => type)
pREC_FUN = 2 :: Int -- btype in ParseIface.y in GHC
-- Used for LH arg of (->)
pREC_OP = 3 :: Int -- Used for arg of any infix operator
-- (we don't keep their fixities around)
pREC_CON = 4 :: Int -- Used for arg of type applicn:
-- always parenthesise unless atomic
maybeParen :: Int -- Precedence of context
-> Int -- Precedence of top-level operator
-> Html -> Html -- Wrap in parens if (ctxt >= op)
maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
| otherwise = p
ppLType, ppLParendType, ppLFunLhType :: Unicode -> Qualification
-> Located (HsType DocName) -> Html
ppLType unicode qual y = ppType unicode qual (unLoc y)
ppLParendType unicode qual y = ppParendType unicode qual (unLoc y)
ppLFunLhType unicode qual y = ppFunLhType unicode qual (unLoc y)
ppType, ppCtxType, ppParendType, ppFunLhType :: Unicode -> Qualification
-> HsType DocName -> Html
ppType unicode qual ty = ppr_mono_ty pREC_TOP ty unicode qual
ppCtxType unicode qual ty = ppr_mono_ty pREC_CTX ty unicode qual
ppParendType unicode qual ty = ppr_mono_ty pREC_CON ty unicode qual
ppFunLhType unicode qual ty = ppr_mono_ty pREC_FUN ty unicode qual
ppLKind :: Unicode -> Qualification -> LHsKind DocName -> Html
ppLKind unicode qual y = ppKind unicode qual (unLoc y)
ppKind :: Unicode -> Qualification -> HsKind DocName -> Html
ppKind unicode qual ki = ppr_mono_ty pREC_TOP ki unicode qual
-- Drop top-level for-all type variables in user style
-- since they are implicit in Haskell
ppForAllCon :: HsExplicitFlag -> LHsTyVarBndrs DocName
-> Located (HsContext DocName) -> Unicode -> Qualification -> Html
ppForAllCon expl tvs cxt unicode qual =
forall_part <+> ppLContext cxt unicode qual
where
forall_part = ppLTyVarBndrs expl tvs unicode qual
ppLTyVarBndrs :: HsExplicitFlag -> LHsTyVarBndrs DocName
-> Unicode -> Qualification
-> Html
ppLTyVarBndrs expl tvs unicode _qual
| show_forall = hsep (forallSymbol unicode : ppTyVars tvs) +++ dot
| otherwise = noHtml
where
show_forall = not (null (hsQTvBndrs tvs)) && is_explicit
is_explicit = case expl of {Explicit -> True; Implicit -> False; Qualified -> False}
ppr_mono_lty :: Int -> LHsType DocName -> Unicode -> Qualification -> Html
ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
ppr_mono_ty :: Int -> HsType DocName -> Unicode -> Qualification -> Html
ppr_mono_ty ctxt_prec (HsForAllTy expl extra tvs ctxt ty) unicode qual
= maybeParen ctxt_prec pREC_FUN $ ppForAllCon expl tvs ctxt' unicode qual
<+> ppr_mono_lty pREC_TOP ty unicode qual
where
anonWC = HsWildCardTy (AnonWildCard PlaceHolder)
ctxt'
| Just loc <- extra = (++ [L loc anonWC]) `fmap` ctxt
| otherwise = ctxt
-- UnicodeSyntax alternatives
ppr_mono_ty _ (HsTyVar name) True _
| getOccString (getName name) == "*" = toHtml "★"
| getOccString (getName name) == "(->)" = toHtml "(→)"
ppr_mono_ty _ (HsBangTy b ty) u q = ppBang b +++ ppLParendType u q ty
ppr_mono_ty _ (HsTyVar name) _ q = ppDocName q Prefix True name
ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) u q = ppr_fun_ty ctxt_prec ty1 ty2 u q
ppr_mono_ty _ (HsTupleTy con tys) u q = tupleParens con (map (ppLType u q) tys)
ppr_mono_ty _ (HsKindSig ty kind) u q =
parens (ppr_mono_lty pREC_TOP ty u q <+> dcolon u <+> ppLKind u q kind)
ppr_mono_ty _ (HsListTy ty) u q = brackets (ppr_mono_lty pREC_TOP ty u q)
ppr_mono_ty _ (HsPArrTy ty) u q = pabrackets (ppr_mono_lty pREC_TOP ty u q)
ppr_mono_ty ctxt_prec (HsIParamTy n ty) u q =
maybeParen ctxt_prec pREC_CTX $ ppIPName n <+> dcolon u <+> ppr_mono_lty pREC_TOP ty u q
ppr_mono_ty _ (HsSpliceTy {}) _ _ = error "ppr_mono_ty HsSpliceTy"
ppr_mono_ty _ (HsRecTy {}) _ _ = error "ppr_mono_ty HsRecTy"
ppr_mono_ty _ (HsCoreTy {}) _ _ = error "ppr_mono_ty HsCoreTy"
ppr_mono_ty _ (HsExplicitListTy _ tys) u q = quote $ brackets $ hsep $ punctuate comma $ map (ppLType u q) tys
ppr_mono_ty _ (HsExplicitTupleTy _ tys) u q = quote $ parenList $ map (ppLType u q) tys
ppr_mono_ty _ (HsWrapTy {}) _ _ = error "ppr_mono_ty HsWrapTy"
ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) unicode qual
= maybeParen ctxt_prec pREC_CTX $
ppr_mono_lty pREC_OP ty1 unicode qual <+> char '~' <+> ppr_mono_lty pREC_OP ty2 unicode qual
ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty) unicode qual
= maybeParen ctxt_prec pREC_CON $
hsep [ppr_mono_lty pREC_FUN fun_ty unicode qual, ppr_mono_lty pREC_CON arg_ty unicode qual]
ppr_mono_ty ctxt_prec (HsOpTy ty1 (_, op) ty2) unicode qual
= maybeParen ctxt_prec pREC_FUN $
ppr_mono_lty pREC_OP ty1 unicode qual <+> ppr_op <+> ppr_mono_lty pREC_OP ty2 unicode qual
where
ppr_op = ppLDocName qual Infix op
ppr_mono_ty ctxt_prec (HsParTy ty) unicode qual
-- = parens (ppr_mono_lty pREC_TOP ty)
= ppr_mono_lty ctxt_prec ty unicode qual
ppr_mono_ty ctxt_prec (HsDocTy ty _) unicode qual
= ppr_mono_lty ctxt_prec ty unicode qual
ppr_mono_ty _ (HsWildCardTy (AnonWildCard _)) _ _ = char '_'
ppr_mono_ty _ (HsWildCardTy (NamedWildCard name)) _ q = ppDocName q Prefix True name
ppr_mono_ty _ (HsTyLit n) _ _ = ppr_tylit n
ppr_tylit :: HsTyLit -> Html
ppr_tylit (HsNumTy _ n) = toHtml (show n)
ppr_tylit (HsStrTy _ s) = toHtml (show s)
ppr_fun_ty :: Int -> LHsType DocName -> LHsType DocName -> Unicode -> Qualification -> Html
ppr_fun_ty ctxt_prec ty1 ty2 unicode qual
= let p1 = ppr_mono_lty pREC_FUN ty1 unicode qual
p2 = ppr_mono_lty pREC_TOP ty2 unicode qual
in
maybeParen ctxt_prec pREC_FUN $
hsep [p1, arrow unicode <+> p2]
|
mrBliss/haddock
|
haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
|
bsd-2-clause
| 39,096 | 0 | 22 | 10,288 | 11,648 | 5,898 | 5,750 | 613 | 9 |
module Data.Kibr.Grammar where
import Preamble
import Data.SafeCopy
data Grammar
= A
| BAhE
| BAI
| BE
| BEhO
| BEI
| BIhE
| BIhI
| BO
| BOI
| BU
| BY1
| BY2
| CAhA
| CAI
| CEhE
| CEI
| CO
| COI
| CU
| CUhE
| DAhO
| DOhU
| DOI
| FA
| FAhA1
| FAhA2
| FAhA3
| FAhA4
| FAhO
| FEhE
| FEhU
| FIhO
| FOI
| FUhA
| FUhE
| FUhO
| GA
| GAhO
| GEhU
| GI
| GIhA
| GOhA
| GOI
| GUhA
| I
| JA
| JAI
| JOhI
| JOI
| KE
| KEhE
| KEI
| KI
| KOhA1
| KOhA2
| KOhA3
| KOhA4
| KOhA5
| KOhA6
| KOhA7
| KOhA8
| KU
| KUhE
| KUhO
| LA
| LAhE
| LAU
| LE
| LEhU
| LI
| LIhU
| LOhO
| LOhU
| LU
| LUhU
| MAhO
| MAI
| ME
| MEhU
| MOhE
| MOhI
| MOI
| NA
| NAhE
| NAhU
| NAI
| NIhE
| NIhO
| NOI
| NU
| NU1
| NUhA
| NUhI
| NUhU
| PA1
| PA2
| PA3
| PA4
| PA5
| PEhE
| PEhO
| PU
| RAhO
| ROI
| SA
| SE
| SEhU
| SEI
| SI
| SOI
| SU
| TAhE
| TEhU
| TEI
| TO
| TOI
| TUhE
| TUhU
| UI1
| UI2
| UI3
| UI3a
| UI3b
| UI3c
| UI4
| UI5
| UI6
| UI7
| VA
| VAU
| VEhA
| VEhO
| VEI
| VIhA
| VUhO
| VUhU0
| VUhU1
| VUhU2
| VUhU3
| VUhU4
| XI
| Y
| ZAhO
| ZEhA
| ZEI
| ZI
| ZIhE
| ZO
| ZOhU
| ZOI
deriving (Eq, Show, Read, Enum, Bounded, Ord, Data, Typeable)
deriveSafeCopy 0 'base ''Grammar
|
dag/kibr
|
src/Data/Kibr/Grammar.hs
|
bsd-2-clause
| 1,450 | 0 | 6 | 632 | 520 | 338 | 182 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
-- Ondřej Súkup xmonad config ...
-- main import
import XMonad
-- xmonad hooks
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.SetWMName
import XMonad.Hooks.UrgencyHook
--xmonad actions
import XMonad.Actions.CycleWS
import XMonad.Actions.GridSelect
import XMonad.Actions.Submap
--xmonad utils
import XMonad.Util.Cursor
import XMonad.Util.EZConfig
import XMonad.Util.NamedWindows
import XMonad.Util.Scratchpad
import XMonad.Util.SpawnOnce (spawnOnce)
import XMonad.Util.Themes
--xmonad layouts
import XMonad.Layout.Fullscreen hiding (fullscreenEventHook)
import XMonad.Layout.LayoutHints
import XMonad.Layout.LayoutModifier
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Tabbed
-- import xmonad promt
import XMonad.Prompt
import XMonad.Prompt.Shell
-- qualified imports of Data and Stack
import qualified XMonad.StackSet as W
import qualified Data.Map as M
-- general import
import Control.Applicative
import Graphics.X11.ExtraTypes.XF86
------------------------------------------------------------------------
promptConfig :: XPConfig
promptConfig =
def {font = "xft:Source Code Pro:pixelsize=14"
,borderColor = "#1e2320"
,height = 18
,position = Top}
------------------------------------------------------------------------
myWorkspaces :: [WorkspaceId]
myWorkspaces =
["con","web","irc","email"] ++ map show [5 .. 9]
------------------------------------------------------------------------
-- add mouse buttons
button8 = 8 :: Button
button9 = 9 :: Button
------------------------------------------------------------------------
-- Layouts:
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myBorders = lessBorders (Combine Union Screen OnlyFloat)
myLayout =
avoidStruts $
myBorders $
layoutHints $
onWorkspace "con"
(tab ||| tiled ||| mtiled) $
onWorkspaces ["web","irc"]
full $
full ||| tab ||| tiled ||| mtiled
where
-- default tiling algorithm partitions the screen into two panes
tiled = Tall nmaster delta ratio
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio =
toRational (2 / (1 + sqrt 5 :: Double))
-- Percent of screen to increment by when resizing panes
delta = 5 / 100
-- tab is tabbed
tab =
tabbed shrinkText (theme smallClean)
-- full is Full
full =
(fullscreenFloat . fullscreenFull) Full
-- mtiled is mirrortiled
mtiled = Mirror tiled
------------------------------------------------------------------------
-- Window rules:
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
--
myManageHook :: ManageHook
myManageHook =
composeAll $
[isDialog --> doFloat] ++
[appName =? r --> doIgnore | r <- myIgnores] ++
[className =? c --> doCenterFloat | c <- myFloats] ++
[appName =? r --> doShift wsp | (r,wsp) <- myWorkspaceMove]
-- fulscreen windows to fullfloating
++
[isFullscreen --> doFullFloat] ++
-- unmanage docks such as gnome-panel and dzen
[fullscreenManageHook
,scratchpadManageHookDefault
,manageDocks]
where
-- windows to operate
myIgnores =
["desktop","kdesktop","desktop_window"]
myFloats =
["Steam","steam","vlc","Vlc","mpv"]
myWorkspaceMove =
[("google-chrome","web")
,("urxvt","con")
,("weechat","irc")
,("Steam","steam")
,("steam","steam")
,("Navigator","web")
,("Weechat","irc")
,("Thunderbird","email")
,("Mail","email")]
------------------------------------------------------------------------
-- Event handling
--
-- * EwmhDesktops users should change this to ewmhDesktopsEventHook
--
-- Defines a custom handler function for X Events. The function should
-- return (All True) if the default handler is to be run afterwards. To
-- combine event hooks use mappend or mconcat from Data.Monoid.
--
myEventHook = fullscreenEventHook <+> hintsEventHook <+> docksEventHook
------------------------------------------------------------------------
-- myStartupHook
myStartupHook :: X ()
myStartupHook =
do setDefaultCursor xC_left_ptr
setWMName "LG3D"
spawnOnce "google-chrome-stable"
spawnOnce "urxvtc-256color"
------------------------------------------------------------------------
-- Urgency Hook:
--
-- Use libnotify notifications when the X11 urgent hint is set
data LibNotifyUrgencyHook =
LibNotifyUrgencyHook
deriving (Read,Show)
instance UrgencyHook LibNotifyUrgencyHook where
urgencyHook LibNotifyUrgencyHook w =
do name <- getName w
wins <- gets windowset
whenJust (W.findTag w wins)
(flash name)
where flash name index = spawn $
"notify-send " ++
"'Workspace " ++
index ++
"' " ++ "'Activity in: " ++ show name ++ "' "
------------------------------------------------------------------------
--
-- |
-- Helper function which provides ToggleStruts keybinding
--
toggleStrutsKey :: XConfig t -> (KeyMask,KeySym)
toggleStrutsKey XConfig{modMask = modm} =
(modm,xK_b)
------------------------------------------------------------------------
-- xmobar from XMonad.Hooks.DynamicLog with scratchpad filter
--
myXmobar
:: LayoutClass l Window
=> XConfig l -> IO (XConfig (ModifiedLayout AvoidStruts l))
myXmobar =
statusBar "xmobar"
xmobarPP {ppSort = (. scratchpadFilterOutWorkspace) Control.Applicative.<$>
ppSort def}
toggleStrutsKey
-----------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
main :: IO ()
main = xmonad =<< myXmobar defaults
------------------------------------------------------------------------
myUrgencyHook =
withUrgencyHook LibNotifyUrgencyHook
defaults =
myUrgencyHook $
ewmh $
def {terminal = "urxvtc-256color" -- unicode rxvt as client for urxvtd started in .xsession file
,borderWidth = 2
,modMask = mod4Mask
,workspaces = myWorkspaces
,layoutHook = myLayout
,manageHook = myManageHook
,handleEventHook = myEventHook
,startupHook = myStartupHook} `additionalKeys`
[((mod4Mask,xK_g),goToSelected def) -- Gridselect
,((mod4Mask,xK_Print),spawn "scrot '%F-%H-%M-%S.png' -e 'mv $f ~/Shot/'") -- screenshot
,((mod4Mask,xK_s),scratchpadSpawnAction defaults) -- scratchpad
,((mod4Mask .|. controlMask,xK_p)
,submap . M.fromList $ -- add submap Ctrl+Win+P,key
[((0,xK_q),spawn "urxvtc-256color -name Weechat -e weechat")
,((0,xK_w),spawn "google-chrome-stable")
,((0,xK_e),spawn "urxvtc-256color -name EDIT -e vim")
,((0,xK_r),spawn "thunderbird")])
,((mod4Mask,xK_p),shellPrompt promptConfig)
,
-- , ((mod4Mask .|. shiftMask , xK_p ), passPrompt promptConfig )
((mod4Mask,xK_l),spawn "i3lock -i wall/lock.png")
,((0,xF86XK_AudioMute),spawn "pulseaudio-ctl mute")
,((0,xF86XK_AudioRaiseVolume),spawn "pulseaudio-ctl up")
,((0,xF86XK_AudioLowerVolume),spawn "pulseaudio-ctl down")
,((0,xF86XK_MonBrightnessUp),spawn "xbacklight +5")
,((0,xF86XK_MonBrightnessDown),spawn "xbacklight -5")
,((mod4Mask,xK_b),sendMessage ToggleStruts)] `additionalMouseBindings`
[((0,button8),const prevWS) -- cycle Workspace up
,((0,button9),const nextWS) -- cycle Workspace down
]
|
mimi1vx/dotfiles
|
ntb/.xmonad/xmonad.hs
|
bsd-2-clause
| 8,572 | 0 | 14 | 1,767 | 1,504 | 907 | 597 | 152 | 1 |
module ImessageSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
|
mitchty/imessage
|
test/ImessageSpec.hs
|
bsd-3-clause
| 205 | 0 | 13 | 49 | 74 | 39 | 35 | 9 | 1 |
module ActiveSync where
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types.Status as Status
import qualified Network.HTTP.Types.Header as HType
import Data.Conduit
import Data.ByteString.Char8 ( pack, unpack )
import Control.Applicative
import Control.Exception ( try, SomeException )
import Control.Monad.IO.Class ( liftIO )
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import Control.Monad.State
import Control.Monad.Error
import Control.Monad.Reader
import Data.CaseInsensitive ( mk )
import qualified Text.XML.Light as X
import qualified System.Log.Logger as Log
data ASConnection = ASConnection { connCredentials :: (String, String),
connUrl :: String,
connMgr :: HTTP.Manager }
login :: String -> String -> IO ( Either String ASConnection )
login username password = runErrorT $ runResourceT $ do
let hostname = getServerName username
[ bsUser, bsPass ] = map pack [ username, password ]
connMan <- liftIO $ HTTP.newManager HTTP.def
adUrl <- autodiscoverUrl hostname bsUser bsPass connMan
req <- HTTP.parseUrl adUrl
let body = HTTP.RequestBodyBS $ pack $ autodiscoverReq username
xmlContent = ( HType.hContentType, pack "text/xml" )
discoverReq = req { HTTP.method = pack "POST",
HTTP.redirectCount = 1,
HTTP.secure = True,
HTTP.requestHeaders = [ xmlContent ],
HTTP.requestBody = body }
authenticatedRequest = HTTP.applyBasicAuth bsUser bsPass discoverReq
res <- liftIO $ tryHttpLbs authenticatedRequest connMan
liftIO $ logHttpResponse res
case res of
Right response | responseCode response == 200 &&
mobileSyncUrl response /= Nothing -> do
let Just svcUrl = mobileSyncUrl response
return $ ASConnection { connCredentials = (username, password),
connUrl = svcUrl,
connMgr = connMan }
Right _ ->
throwError "service is not available"
Left error ->
throwError $ submitError adUrl error
list :: ASConnection -> IO ( ASConnection, [ String ] )
list conn = asRequest conn asListRequest
asRequest conn request = do
let url = connUrl conn
(user, password) = connCredentials conn
[ bsUser, bsPass ] = map pack [ user, password ]
mgr = connMgr conn
req <- HTTP.parseUrl url
let body = HTTP.RequestBodyBS $ wbxmlPack $ request
xmlContent = ( HType.hContentType, pack "text/wbxml" )
httpReq = req { HTTP.method = pack "POST",
HTTP.redirectCount = 0,
HTTP.secure = True,
HTTP.requestHeaders = [ xmlContent ],
HTTP.requestBody = body }
authenticatedRequest = HTTP.applyBasicAuth bsUser bsPass httpReq
res <- liftIO $ tryHttpLbs authenticatedRequest mgr
liftIO $ logHttpResponse res
case res of
Right response | responseCode response == 200 -> do
return $ ( conn, [ "something" ] )
asListRequest = "hallo"
wbxmlPack = pack
logHttpResponse =
either ignore ( ( Log.debugM "yahui.msas" ) . L8.unpack . HTTP.responseBody )
where
ignore = (\_ -> return () )
submitError url error =
"failed to submit autodiscover request to " ++ url ++ show error
getServerName username =
let ( _ : hostname ) = dropWhile (\ c -> c /= '@' ) username in
hostname
autodiscoverUrl hostname user password connManager = do
let connInfo = (user, password, connManager)
evalStateT ( runReaderT pickAutodiscoverTarget connInfo ) $ autodiscoverTargets hostname
autodiscoverTargets hostname =
let suffix = "/autodiscover/autodiscover.xml" in
[ ( "POST", Nothing, "https://autodiscover." ++ hostname ++ suffix ),
( "POST", Nothing, "http://" ++ hostname ++ suffix ),
( "GET", Nothing, "http://autodiscover." ++ hostname ++ suffix ) ]
pickAutodiscoverTarget = do
urls <- get
case urls of
[] ->
throwError "failed to find autodiscover server"
( target : rest ) -> do
put rest
tryAutodiscoverTarget target
tryAutodiscoverTarget ( method, auth, url ) = do
( user, password, connMan ) <- ask
req <- HTTP.parseUrl url
let discoverReq = req { HTTP.method = pack method,
HTTP.redirectCount = 0,
HTTP.checkStatus = \_ _ _ -> Nothing }
res <- liftIO $ tryHttpLbs ( addAuth auth discoverReq ) connMan
case res of
Right httpRes ->
let location = getResponseLocation httpRes in
case (responseCode httpRes, location ) of
( 200, _ ) ->
return url
( 302, Just movedTo ) -> do
targets <- get
put $ ( "POST", Nothing, movedTo ) : targets
pickAutodiscoverTarget
( 401, _ ) | auth == Nothing -> do
targets <- get
put $ ( method, Just (user, password), url ) : targets
pickAutodiscoverTarget
_ ->
pickAutodiscoverTarget
Left _ ->
pickAutodiscoverTarget
-- FIXME: condiser applicative functors
addAuth ( Just (user, password) ) request =
HTTP.applyBasicAuth user password request
addAuth Nothing request =
request
tryHttpLbs req connMan = do
try $ runResourceT $ HTTP.httpLbs req connMan :: IO ( Either SomeException (HTTP.Response L.ByteString) )
getResponseLocation response =
let headerName = mk $ pack "Location" in
unpack <$> ( lookup headerName $ HTTP.responseHeaders response )
responseCode res =
Status.statusCode $ HTTP.responseStatus res
autodiscoverReq email = X.showElement root where
root = X.node ( X.unqual "Autodiscover" ) ( [ nsAttr ], [ request ] )
request = X.node ( X.unqual "Request" ) [ mailAddr, responseSchema ]
mailAddr = strNode "EMailAddress" email
responseSchema = strNode "AcceptableResponseSchema" resNs
nsAttr = X.Attr { X.attrKey = X.unqual "xmlns", X.attrVal = reqNs }
reqNs = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/requestschema/2006"
resNs = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006"
responseNs =
"http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006"
strNode name value =
X.node ( X.unqual name ) ( X.CData { X.cdVerbatim = X.CDataText,
X.cdData = value,
X.cdLine = Nothing } )
mobileSyncUrl response =
let body = HTTP.responseBody response
path = [ "Autodiscover", "Response", "Action",
"Settings", "Server", "Url" ] in
xmlFindPath body path
xmlFindPath xml path = do
root <- X.parseXMLDoc xml
let filter = X.filterElementName . (\ name elName -> X.qName elName == name )
result <- foldl (>>=) ( Just root ) $ map filter path
return $ X.strContent result
|
eazy-f/yahui
|
src/ActiveSync.hs
|
bsd-3-clause
| 7,011 | 0 | 22 | 1,888 | 1,955 | 1,027 | 928 | 155 | 5 |
{-# LANGUAGE
TemplateHaskell
, RankNTypes
, ConstraintKinds
, FlexibleInstances
#-}
-- | This example illustrates the simplest variety of implementing one
-- interface in terms of another - renaming a method.
module Test where
import Classes
import Language.Haskell.InstanceTemplates
$(instantiate
[template Foo_T [t| Foo Int |]
[d|
getFoo = 5
|]
])
main = print (getBar :: Int)
|
mgsloan/instance-templates
|
tests/simple/Test.hs
|
bsd-3-clause
| 410 | 0 | 9 | 88 | 58 | 37 | 21 | 13 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] bg
[@ISO639-2@] bul
[@ISO639-3@] bul
[@Native name@] български език
[@English name@] Bulgarian
-}
module Text.Numeral.Language.BUL.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Integral, (+) )
import "base-unicode-symbols" Prelude.Unicode ( (⋅) )
import "numerals" Text.Numeral.Grammar
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "numerals" Text.Numeral.Misc ( dec )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
http://www.languagesandnumbers.com/how-to-count-in-bulgarian/en/bul/
http://en.wikipedia.org/wiki/Bulgarian_grammar#Numbers
http://bg.wikipedia.org/wiki/Имена_на_числата
-}
cardinals ∷ (Integral i) ⇒ TestData i
cardinals =
[ ( "neuter"
, neuter defaultInflection
, [ (-3, "минус три")
, (0, "нула")
, (1, "едно")
, (2, "две")
, (3, "три")
, (4, "четири")
, (5, "пет")
, (6, "шест")
, (7, "седем")
, (8, "осем")
, (9, "девет")
, (10, "десет")
, (11, "единадесет")
, (12, "дванадесет")
, (13, "тринадесет")
, (14, "четиринадесет")
, (15, "петнадесет")
, (16, "шестнадесет")
, (17, "седемнадесет")
, (18, "осемнадесет")
, (19, "деветнадесет")
, (20, "двадесет")
, (21, "двадесет и едно")
, (22, "двадесет и две")
, (23, "двадесет и три")
, (24, "двадесет и четири")
, (25, "двадесет и пет")
, (26, "двадесет и шест")
, (27, "двадесет и седем")
, (28, "двадесет и осем")
, (29, "двадесет и девет")
, (30, "тридесет")
, (31, "тридесет и едно")
, (32, "тридесет и две")
, (33, "тридесет и три")
, (34, "тридесет и четири")
, (35, "тридесет и пет")
, (36, "тридесет и шест")
, (37, "тридесет и седем")
, (38, "тридесет и осем")
, (39, "тридесет и девет")
, (40, "четиридесет")
, (41, "четиридесет и едно")
, (42, "четиридесет и две")
, (43, "четиридесет и три")
, (44, "четиридесет и четири")
, (45, "четиридесет и пет")
, (46, "четиридесет и шест")
, (47, "четиридесет и седем")
, (48, "четиридесет и осем")
, (49, "четиридесет и девет")
, (50, "петдесет")
, (51, "петдесет и едно")
, (52, "петдесет и две")
, (53, "петдесет и три")
, (54, "петдесет и четири")
, (55, "петдесет и пет")
, (56, "петдесет и шест")
, (57, "петдесет и седем")
, (58, "петдесет и осем")
, (59, "петдесет и девет")
, (60, "шестдесет")
, (61, "шестдесет и едно")
, (62, "шестдесет и две")
, (63, "шестдесет и три")
, (64, "шестдесет и четири")
, (65, "шестдесет и пет")
, (66, "шестдесет и шест")
, (67, "шестдесет и седем")
, (68, "шестдесет и осем")
, (69, "шестдесет и девет")
, (70, "седемдесет")
, (71, "седемдесет и едно")
, (72, "седемдесет и две")
, (73, "седемдесет и три")
, (74, "седемдесет и четири")
, (75, "седемдесет и пет")
, (76, "седемдесет и шест")
, (77, "седемдесет и седем")
, (78, "седемдесет и осем")
, (79, "седемдесет и девет")
, (80, "осемдесет")
, (81, "осемдесет и едно")
, (82, "осемдесет и две")
, (83, "осемдесет и три")
, (84, "осемдесет и четири")
, (85, "осемдесет и пет")
, (86, "осемдесет и шест")
, (87, "осемдесет и седем")
, (88, "осемдесет и осем")
, (89, "осемдесет и девет")
, (90, "деветдесет")
, (91, "деветдесет и едно")
, (92, "деветдесет и две")
, (93, "деветдесет и три")
, (94, "деветдесет и четири")
, (95, "деветдесет и пет")
, (96, "деветдесет и шест")
, (97, "деветдесет и седем")
, (98, "деветдесет и осем")
, (99, "деветдесет и девет")
, (100, "сто")
, (101, "сто и едно")
, (102, "сто и две")
, (110, "сто и десет")
, (115, "сто и петнадесет")
, (120, "сто и двадесет")
, (121, "сто двадесет и едно")
, (130, "сто и тридесет")
, (133, "сто тридесет и три")
, (200, "двеста")
, (202, "двеста и две")
, (216, "двеста и шестнадесет")
, (265, "двеста шестдесет и пет")
, (300, "триста")
, (400, "четиристотин")
, (500, "петстотин")
, (507, "петстотин и седем")
, (600, "шестстотин")
, (700, "седемстотин")
, (800, "осемстотин")
, (900, "деветстотин")
, (1000, "хиляда")
, (1234, "хиляда двеста тридесет и четири")
, (2000, "две хиляди")
, (3000, "три хиляди")
, (5000, "пет хиляди")
, (6000, "шест хиляди")
, (9000, "девет хиляди")
, (16000, "шестнадесет хиляди")
, (21000, "двадесет и едно хиляди")
, (22000, "двадесет и две хиляди")
, (22136, "двадесет и две хиляди сто тридесет и шест")
, (23000, "двадесет и три хиляди")
, (28000, "двадесет и осем хиляди")
, (41000, "четиридесет и едно хиляди")
, (42000, "четиридесет и две хиляди")
, (49000, "четиридесет и девет хиляди")
, (100000, "сто хиляди")
, (200000, "двеста хиляди")
, (255383, "двеста петдесет и пет хиляди триста осемдесет и три")
, (300000, "триста хиляди")
, (300001, "триста хиляди и едно")
, (300020, "триста хиляди и двадесет")
, (300825, "триста хиляди осемстотин двадесет и пет")
, (dec 6, "един милион")
, (1300825, "един милион триста хиляди осемстотин двадесет и пет")
, (1021000, "един милион двадесет и едно хиляди")
, (1001234, "един милион хиляда двеста тридесет и четири")
, (1000216, "един милион двеста и шестнадесет")
, (1000074, "един милион седемдесет и четири")
, (1000004, "един милион и четири")
, (2 ⋅ dec 6, "два милиона")
, (5 ⋅ dec 6, "пет милиона")
, (dec 9, "един милиард")
, (2 ⋅ dec 9, "два милиарда")
, (3 ⋅ dec 12, "три трилиона")
, (dec 15, "един квадрилион")
, (15 ⋅ dec 15 + 41, "петнадесет квадрилиона четиридесет и едно")
, (dec 18, "един квинтилион")
, (dec 21, "един секстилион")
, (dec 24, "един септилион")
, (dec 27, "един октилион")
, (dec 30, "един нонилион")
, (dec 33, "един децилион")
, (dec 36, "един индецилион")
, (dec 39, "един дуодецилион")
, (dec 42, "един тридецилион")
, (dec 45, "един куадродецилион")
, (900 ⋅ dec 45, "деветстотин куадродецилиона")
]
)
, ( "feminine"
, feminine defaultInflection
, [ (1, "една")
, (2, "две")
, (200, "двеста")
, (202, "двеста и две")
]
)
, ( "masculine"
, masculine defaultInflection
, [ (1, "един")
, (2, "два")
, (200, "двеста")
, (202, "двеста и два")
]
)
]
|
telser/numerals
|
src-test/Text/Numeral/Language/BUL/TestData.hs
|
bsd-3-clause
| 9,904 | 0 | 11 | 2,189 | 1,854 | 1,213 | 641 | 198 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.