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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- https://www.hackerrank.com/challenges/grading/problem
-- Constants
threshold = 3
lowerLimit = 38
toInt :: String -> Int
toInt string = read string :: Int
calculateNextMultipleOfFive :: Int -> Int
calculateNextMultipleOfFive grade = grade + 5 - (grade `mod` 5)
gradeStudent :: Int -> Int
gradeStudent grade
| grade < lowerLimit = grade
| otherwise = if difference < threshold then nextMultiple else grade
where
nextMultiple = calculateNextMultipleOfFive grade
difference = nextMultiple - grade
readGrades :: String -> [String]
readGrades = tail . lines
main :: IO ()
main =
interact $ unlines . map (show . gradeStudent . toInt) . readGrades
| julianespinel/training | hackerrank/Grading.hs | mit | 667 | 0 | 10 | 122 | 199 | 106 | 93 | 17 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Server (
server, authServerContext, AuthMap
) where
import Servant
import API
import Config
import Server.Main
import Server.Login
import Server.Swagger
import Server.Static
server :: AuthMap -> Config -> Server API
server m cfg = convertServer cfg (mainServer :<|> loginServer m)
:<|> swaggerServer
:<|> staticServer cfg
| lierdakil/markco | server/src/Server.hs | mit | 378 | 0 | 10 | 64 | 97 | 54 | 43 | 14 | 1 |
module FRP.Jalapeno.Sample where
-------------
-- Imports --
import Control.Concurrent
import Data.Time.Clock
import FRP.Jalapeno.Behavior
----------
-- Code --
{--- | Sampling a @'Behavior'@ in real time at a maximum number of times per-}
{--- second.-}
{-intermittentSample :: (Monad m, Show a) => Behavior m a -> Int -> IO ()-}
{-intermittentSample b rate = do-}
{-ct <- getCurrentTime-}
{-intermittentSample' ct 0 b rate-}
{-where intermittentSample' :: (Monad m, Show a) => UTCTime -> Double -> Behavior m a -> Int -> IO ()-}
{-intermittentSample' lt t b rate = do-}
{-runBehavior t b >>= print-}
{--- Non-reactive delay. Could fix later to make sure that if it's-}
{--- running slowly it doesn't apply the delay.-}
{-threadDelay $ 1000000 `div` rate-}
{-ct <- getCurrentTime-}
{-intermittentSample' ct-}
{-(t + (fromRational $ toRational $ diffUTCTime ct lt))-}
{-b-}
{-rate-}
{--- | Sampling a @'Behavior'@ at around 100 samples per second.-}
{-sample :: (Monad m, Show a) => Behavior m a -> IO ()-}
{-sample b = intermittentSample b 60-}
| crockeo/jalapeno | src/lib/FRP/Jalapeno/Sample.hs | mit | 1,219 | 0 | 4 | 338 | 48 | 40 | 8 | 4 | 0 |
module U.Codebase.Sqlite.Branch.Format where
import Data.Vector (Vector)
import U.Codebase.Sqlite.Branch.Diff (LocalDiff)
import U.Codebase.Sqlite.Branch.Full (LocalBranch)
import U.Codebase.Sqlite.DbId (CausalHashId, BranchObjectId, ObjectId, PatchObjectId, TextId)
import Data.ByteString (ByteString)
-- |you can use the exact same `BranchLocalIds` when converting between `Full` and `Diff`
data BranchFormat
= Full BranchLocalIds LocalBranch
| Diff BranchObjectId BranchLocalIds LocalDiff
deriving Show
data BranchLocalIds = LocalIds
{ branchTextLookup :: Vector TextId,
branchDefnLookup :: Vector ObjectId,
branchPatchLookup :: Vector PatchObjectId,
branchChildLookup :: Vector (BranchObjectId, CausalHashId)
}
deriving Show
data SyncBranchFormat
= SyncFull BranchLocalIds ByteString
| SyncDiff BranchObjectId BranchLocalIds ByteString
| unisonweb/platform | codebase2/codebase-sqlite/U/Codebase/Sqlite/Branch/Format.hs | mit | 872 | 0 | 10 | 117 | 177 | 109 | 68 | 19 | 0 |
module Problem0012 where
import Data.List
--http://www.mathsisfun.com/algebra/triangular-numbers.html
nthTriangleNumber nth =
round
$(nth * ( nth + 1)) / 2
infiniteListOfTriangleNumbers = [nthTriangleNumber x | x <- [1..]]
--http://rosettacode.org/wiki/Factors_of_an_integer#Haskell
factors n = lows ++ (reverse $ map (div n) lows)
where lows = filter ((== 0) . mod n) [1..truncate . sqrt $ fromIntegral n]
firstTriangleNumberWithMoreThanHowManyFactors n =
head $ filter (\x -> (length $ factors x) > n) infiniteListOfTriangleNumbers
| Sobieck00/practice | pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0012.hs | mit | 570 | 0 | 12 | 104 | 174 | 92 | 82 | 10 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.List (sort)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Prelude hiding (null)
import CustomSet
( delete
, difference
, fromList
, insert
, isDisjointFrom
, isSubsetOf
, intersection
, member
, null
, size
, toList
, union
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
describe "standard tests" $ do
describe "null" $ do
it "sets with no elements are empty" $
null (fromList ([] :: [Integer])) `shouldBe` True
it "sets with elements are not empty" $
null (fromList [1]) `shouldBe` False
describe "member" $ do
it "nothing is contained in an empty set" $
1 `member` fromList [] `shouldBe` False
it "when the element is in the set" $
1 `member` fromList [1, 2, 3] `shouldBe` True
it "when the element is not in the set" $
4 `member` fromList [1, 2, 3] `shouldBe` False
describe "isSubsetOf" $ do
it "empty set is a subset of another empty set" $
fromList ([] :: [Integer]) `isSubsetOf` fromList [] `shouldBe` True
it "empty set is a subset of non-empty set" $
fromList [] `isSubsetOf` fromList [1] `shouldBe` True
it "non-empty set is not a subset of empty set" $
fromList [1] `isSubsetOf` fromList [] `shouldBe` False
it "set is a subset of set with exact same elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [1, 2, 3] `shouldBe` True
it "set is a subset of larger set with same elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [4, 1, 2, 3] `shouldBe` True
it "set is not a subset of set that does not contain its elements" $
fromList [1, 2, 3] `isSubsetOf` fromList [4, 1, 3] `shouldBe` False
describe "isDisjointFrom" $ do
it "the empty set is disjoint with itself" $
fromList ([] :: [Integer]) `isDisjointFrom` fromList [] `shouldBe` True
it "empty set is disjoint with non-empty set" $
fromList [] `isDisjointFrom` fromList [1] `shouldBe` True
it "non-empty set is disjoint with empty set" $
fromList [1] `isDisjointFrom` fromList [] `shouldBe` True
it "sets are not disjoint if they share an element" $
fromList [1, 2] `isDisjointFrom` fromList [2, 3] `shouldBe` False
it "sets are disjoint if they share no elements" $
fromList [1, 2] `isDisjointFrom` fromList [3, 4] `shouldBe` True
describe "Eq" $ do
it "empty sets are equal" $
(fromList ([] :: [Integer]) == fromList []) `shouldBe` True
it "empty set is not equal to non-empty set" $
(fromList [] == fromList [1, 2, 3]) `shouldBe` False
it "non-empty set is not equal to empty set" $
(fromList [1, 2, 3] == fromList []) `shouldBe` False
it "sets with the same elements are equal" $
(fromList [1, 2] == fromList [2, 1]) `shouldBe` True
it "sets with different elements are not equal" $
(fromList [1, 2, 3] == fromList [1, 2, 4]) `shouldBe` False
it "set is not equal to larger set with same elements" $
(fromList [1, 2, 3] == fromList [1, 2, 3, 4]) `shouldBe` False
describe "insert" $ do
it "add to empty set" $
insert 3 (fromList []) `shouldBe` fromList [3]
it "add to non-empty set" $
insert 3 (fromList [1, 2, 4]) `shouldBe` fromList [1, 2, 3, 4]
it "adding an existing element does not change the set" $
insert 3 (fromList [1, 2, 3]) `shouldBe` fromList [1, 2, 3]
describe "intersection" $ do
it "intersection of two empty sets is an empty set" $
fromList ([] :: [Integer]) `intersection` fromList [] `shouldBe` fromList []
it "intersection of an empty set and non-empty set is an empty set" $
fromList [] `intersection` fromList [3, 2, 5] `shouldBe` fromList []
it "intersection of a non-empty set and an empty set is an empty set" $
fromList [1, 2, 3, 4] `intersection` fromList [] `shouldBe` fromList []
it "intersection of two sets with no shared elements is an empty set" $
fromList [1, 2, 3] `intersection` fromList [4, 5, 6] `shouldBe` fromList []
it "intersection of two sets with shared elements is a set of the shared elements" $
fromList [1, 2, 3, 4] `intersection` fromList [3, 2, 5] `shouldBe` fromList [2, 3]
describe "difference" $ do
it "difference of two empty sets is an empty set" $
fromList ([] :: [Integer]) `difference` fromList [] `shouldBe` fromList []
it "difference of empty set and non-empty set is an empty set" $
fromList [] `difference` fromList [3, 2, 5] `shouldBe` fromList []
it "difference of a non-empty set and an empty set is the non-empty set" $
fromList [1, 2, 3, 4] `difference` fromList [] `shouldBe` fromList [1, 2, 3, 4]
it "difference of two non-empty sets is a set of elements that are only in the first set" $
fromList [3, 2, 1] `difference` fromList [2, 4] `shouldBe` fromList [1, 3]
describe "union" $ do
it "union of empty sets is an empty set" $
fromList ([] :: [Integer]) `union` fromList [] `shouldBe` fromList []
it "union of an empty set and non-empty set is the non-empty set" $
fromList [] `union` fromList [2] `shouldBe` fromList [2]
it "union of a non-empty set and empty set is the non-empty set" $
fromList [1, 3] `union` fromList [] `shouldBe` fromList [1, 3]
it "union of non-empty sets contains all unique elements" $
fromList [1, 3] `union` fromList [2, 3] `shouldBe` fromList [3, 2, 1]
describe "track-specific tests" $ do
-- Track-specific test cases.
describe "delete" $
it "delete existing element" $
delete 2 (fromList [1, 2, 3]) `shouldBe` fromList [1, 3]
describe "size" $ do
it "size of an empty set is zero" $
size (fromList ([] :: [Integer])) `shouldBe` 0
it "size is the number of elements" $
size (fromList [1, 2, 3]) `shouldBe` 3
it "size doesn't count repetition in `fromList`" $
size (fromList [1, 2, 3, 2]) `shouldBe` 3
it "size does count inserted element" $
size (insert 3 (fromList [1, 2])) `shouldBe` 3
it "size doesn't count element removed by `delete`" $
size (delete 3 (fromList [1, 2, 3, 4])) `shouldBe` 3
describe "toList" $ do
it "an empty set has an empty list of elements" $
(sort . toList . fromList) ([] :: [Integer]) `shouldBe `[]
it "a set has the list of its elements" $
(sort . toList . fromList) [3, 1, 2] `shouldBe `[1, 2, 3]
it "a set doesn't keep repeated elements" $
(sort . toList . fromList) [3, 1, 2, 1] `shouldBe `[1, 2, 3]
-- 54d64bc5e2ff20c76b6c16138ed8ce97cf6f9981
| exercism/xhaskell | exercises/practice/custom-set/test/Tests.hs | mit | 7,179 | 0 | 23 | 2,113 | 2,269 | 1,215 | 1,054 | 130 | 1 |
main = do cs <- getContents
putStr $ numbering cs
numbering :: String -> String
numbering cs = unlines $ map format $ zipLineNumber $ lines cs
zipLineNumber :: [String] -> [(String, String)]
zipLineNumber xs = zip (map show [1..]) xs
format (s1, s2) = s1++" "++s2
| kazuya030/haskell-test | old/catn.hs | mit | 280 | 0 | 8 | 63 | 125 | 64 | 61 | 7 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLHeadingElement
(js_setAlign, setAlign, js_getAlign, getAlign, HTMLHeadingElement,
castToHTMLHeadingElement, gTypeHTMLHeadingElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: HTMLHeadingElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLHeadingElement -> val -> m ()
setAlign self val = liftIO (js_setAlign (self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
HTMLHeadingElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLHeadingElement -> m result
getAlign self = liftIO (fromJSString <$> (js_getAlign (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLHeadingElement.hs | mit | 1,809 | 14 | 10 | 226 | 463 | 284 | 179 | 28 | 1 |
module GHCJS.DOM.OESStandardDerivatives (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/OESStandardDerivatives.hs | mit | 52 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies, FlexibleContexts, ConstraintKinds #-}
module Database.Persist.Class.PersistUnique
(PersistUniqueRead(..)
,PersistUniqueWrite(..)
,getByValue
,insertBy
,insertUniqueEntity
,replaceUnique
,checkUnique
,onlyUnique)
where
import Database.Persist.Types
import Control.Exception (throwIO)
import Control.Monad (liftM)
import Control.Monad.IO.Class (liftIO, MonadIO)
import Data.List ((\\))
import Control.Monad.Trans.Reader (ReaderT)
import Database.Persist.Class.PersistStore
import Database.Persist.Class.PersistEntity
import Data.Monoid (mappend)
import Data.Text (unpack, Text)
-- | Queries against 'Unique' keys (other than the id 'Key').
--
-- Please read the general Persistent documentation to learn how to create
-- 'Unique' keys.
--
-- Using this with an Entity without a Unique key leads to undefined
-- behavior. A few of these functions require a /single/ 'Unique', so using
-- an Entity with multiple 'Unique's is also undefined. In these cases
-- persistent's goal is to throw an exception as soon as possible, but
-- persistent is still transitioning to that.
--
-- SQL backends automatically create uniqueness constraints, but for MongoDB
-- you must manually place a unique index on a field to have a uniqueness
-- constraint.
--
class (PersistCore backend, PersistStoreRead backend) =>
PersistUniqueRead backend where
-- | Get a record by unique key, if available. Returns also the identifier.
getBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -> ReaderT backend m (Maybe (Entity record))
-- | Some functions in this module ('insertUnique', 'insertBy', and
-- 'replaceUnique') first query the unique indexes to check for
-- conflicts. You could instead optimistically attempt to perform the
-- operation (e.g. 'replace' instead of 'replaceUnique'). However,
--
-- * there is some fragility to trying to catch the correct exception and
-- determing the column of failure;
--
-- * an exception will automatically abort the current SQL transaction.
class (PersistUniqueRead backend, PersistStoreWrite backend) =>
PersistUniqueWrite backend where
-- | Delete a specific record by unique key. Does nothing if no record
-- matches.
deleteBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -> ReaderT backend m ()
-- | Like 'insert', but returns 'Nothing' when the record
-- couldn't be inserted because of a uniqueness constraint.
insertUnique
:: (MonadIO m, PersistRecordBackend record backend)
=> record -> ReaderT backend m (Maybe (Key record))
insertUnique datum = do
conflict <- checkUnique datum
case conflict of
Nothing -> Just `liftM` insert datum
Just _ -> return Nothing
-- | Update based on a uniqueness constraint or insert:
--
-- * insert the new record if it does not exist;
-- * If the record exists (matched via it's uniqueness constraint), then update the existing record with the parameters which is passed on as list to the function.
--
-- Throws an exception if there is more than 1 uniqueness contraint.
upsert
:: (MonadIO m, PersistRecordBackend record backend)
=> record -- ^ new record to insert
-> [Update record] -- ^ updates to perform if the record already exists (leaving
-- this empty is the equivalent of performing a 'repsert' on a
-- unique key)
-> ReaderT backend m (Entity record) -- ^ the record in the database after the operation
upsert record updates = do
uniqueKey <- onlyUnique record
upsertBy uniqueKey record updates
-- | Update based on a given uniqueness constraint or insert:
--
-- * insert the new record if it does not exist;
-- * update the existing record that matches the given uniqueness contraint.
upsertBy
:: (MonadIO m, PersistRecordBackend record backend)
=> Unique record -- ^ uniqueness constraint to find by
-> record -- ^ new record to insert
-> [Update record] -- ^ updates to perform if the record already exists (leaving
-- this empty is the equivalent of performing a 'repsert' on a
-- unique key)
-> ReaderT backend m (Entity record) -- ^ the record in the database after the operation
upsertBy uniqueKey record updates = do
mrecord <- getBy uniqueKey
maybe (insertEntity record) (`updateGetEntity` updates) mrecord
where
updateGetEntity (Entity k _) upds =
(Entity k) `liftM` (updateGet k upds)
-- | Insert a value, checking for conflicts with any unique constraints. If a
-- duplicate exists in the database, it is returned as 'Left'. Otherwise, the
-- new 'Key is returned as 'Right'.
insertBy
:: (MonadIO m
,PersistUniqueWrite backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Either (Entity record) (Key record))
insertBy val = do
res <- getByValue val
case res of
Nothing -> Right `liftM` insert val
Just z -> return $ Left z
-- | Insert a value, checking for conflicts with any unique constraints. If a
-- duplicate exists in the database, it is left untouched. The key of the
-- existing or new entry is returned
_insertOrGet :: (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend)
=> record -> ReaderT backend m (Key record)
_insertOrGet val = do
res <- getByValue val
case res of
Nothing -> insert val
Just (Entity key _) -> return key
-- | Like 'insertEntity', but returns 'Nothing' when the record
-- couldn't be inserted because of a uniqueness constraint.
--
-- @since 2.7.1
insertUniqueEntity
:: (MonadIO m
,PersistRecordBackend record backend
,PersistUniqueWrite backend)
=> record -> ReaderT backend m (Maybe (Entity record))
insertUniqueEntity datum =
fmap (\key -> Entity key datum) `liftM` insertUnique datum
-- | Return the single unique key for a record.
onlyUnique
:: (MonadIO m
,PersistUniqueWrite backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Unique record)
onlyUnique record =
case onlyUniqueEither record of
Right u -> return u
Left us ->
requireUniques record us >>=
liftIO . throwIO . OnlyUniqueException . show . length
onlyUniqueEither
:: (PersistEntity record)
=> record -> Either [Unique record] (Unique record)
onlyUniqueEither record =
case persistUniqueKeys record of
[u] -> Right u
us -> Left us
-- | A modification of 'getBy', which takes the 'PersistEntity' itself instead
-- of a 'Unique' record. Returns a record matching /one/ of the unique keys. This
-- function makes the most sense on entities with a single 'Unique'
-- constructor.
getByValue
:: (MonadIO m
,PersistUniqueRead backend
,PersistRecordBackend record backend)
=> record -> ReaderT backend m (Maybe (Entity record))
getByValue record =
checkUniques =<< requireUniques record (persistUniqueKeys record)
where
checkUniques [] = return Nothing
checkUniques (x:xs) = do
y <- getBy x
case y of
Nothing -> checkUniques xs
Just z -> return $ Just z
requireUniques
:: (MonadIO m, PersistEntity record)
=> record -> [Unique record] -> m [Unique record]
requireUniques record [] = liftIO $ throwIO $ userError errorMsg
where
errorMsg = "getByValue: " `Data.Monoid.mappend` unpack (recordName record) `mappend` " does not have any Unique"
requireUniques _ xs = return xs
-- TODO: expose this to users
recordName
:: (PersistEntity record)
=> record -> Text
recordName = unHaskellName . entityHaskell . entityDef . Just
-- | Attempt to replace the record of the given key with the given new record.
-- First query the unique fields to make sure the replacement maintains
-- uniqueness constraints.
--
-- Return 'Nothing' if the replacement was made.
-- If uniqueness is violated, return a 'Just' with the 'Unique' violation
--
-- @since 1.2.2.0
replaceUnique
:: (MonadIO m
,Eq record
,Eq (Unique record)
,PersistRecordBackend record backend
,PersistUniqueWrite backend)
=> Key record -> record -> ReaderT backend m (Maybe (Unique record))
replaceUnique key datumNew = getJust key >>= replaceOriginal
where
uniqueKeysNew = persistUniqueKeys datumNew
replaceOriginal original = do
conflict <- checkUniqueKeys changedKeys
case conflict of
Nothing -> replace key datumNew >> return Nothing
(Just conflictingKey) -> return $ Just conflictingKey
where
changedKeys = uniqueKeysNew \\ uniqueKeysOriginal
uniqueKeysOriginal = persistUniqueKeys original
-- | Check whether there are any conflicts for unique keys with this entity and
-- existing entities in the database.
--
-- Returns 'Nothing' if the entity would be unique, and could thus safely be inserted.
-- on a conflict returns the conflicting key
checkUnique
:: (MonadIO m
,PersistRecordBackend record backend
,PersistUniqueRead backend)
=> record -> ReaderT backend m (Maybe (Unique record))
checkUnique = checkUniqueKeys . persistUniqueKeys
checkUniqueKeys
:: (MonadIO m
,PersistEntity record
,PersistUniqueRead backend
,PersistRecordBackend record backend)
=> [Unique record] -> ReaderT backend m (Maybe (Unique record))
checkUniqueKeys [] = return Nothing
checkUniqueKeys (x:xs) = do
y <- getBy x
case y of
Nothing -> checkUniqueKeys xs
Just _ -> return (Just x)
| psibi/persistent | persistent/Database/Persist/Class/PersistUnique.hs | mit | 9,836 | 0 | 13 | 2,317 | 1,820 | 962 | 858 | 157 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
module Config (
asks
, ConfigHandler(..)
, Config(..)
, readConfigFromEnv
, convertServer
) where
import System.Environment
import qualified Data.Map as M
import Data.Maybe
import Control.Monad.Reader
import Control.Monad.Except
import Servant
import Servant.Utils.Enter
newtype ConfigHandler a = ConfigHandler {
runConfigHandler :: ReaderT Config (ExceptT ServantErr IO) a
} deriving ( Functor, Applicative, Monad, MonadReader Config,
MonadError ServantErr, MonadIO)
data Config = Config {
configDataDir :: !FilePath
, configStaticDir :: !FilePath
, configDataUri :: !String
, configPort :: !Int
, configOrigins :: !(Maybe [String])
, configUserFile :: !(Maybe FilePath)
, configNewCmdFile :: !(Maybe FilePath)
}
convertHandler :: Config -> ConfigHandler :~> Handler
convertHandler cfg = NT (Handler . flip runReaderT cfg . runConfigHandler)
convertServer :: Enter (Entered Handler ConfigHandler t) ConfigHandler Handler t
=> Config -> Entered Handler ConfigHandler t -> t
convertServer cfg = enter (convertHandler cfg)
readConfigFromEnv :: IO Config
readConfigFromEnv = do
env <- M.fromList <$> getEnvironment
return Config {
configDataDir = fromMaybe "data" $ M.lookup "MARKCO_DATA_DIR" env
, configStaticDir = fromMaybe "../client/dist" $ M.lookup "MARKCO_STATIC_DIR" env
, configDataUri = fromMaybe "/data" $ M.lookup "MARKCO_DATA_URI" env
, configPort = fromMaybe 8081 (read <$> M.lookup "MARKCO_PORT" env)
, configOrigins = words <$> M.lookup "MARKCO_ORIGINS" env
, configUserFile = M.lookup "MARKCO_USER_FILE" env
, configNewCmdFile = M.lookup "MARKCO_NEWCOMMANDS" env
}
| lierdakil/markco | server/src/Config.hs | mit | 1,820 | 0 | 14 | 351 | 472 | 257 | 215 | 58 | 1 |
module Graphics.Urho3D.UI.Internal.Menu(
Menu
, menuCntx
, sharedMenuPtrCntx
, SharedMenu
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import Graphics.Urho3D.Container.Ptr
import qualified Data.Map as Map
data Menu
menuCntx :: C.Context
menuCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "Menu", [t| Menu |])
]
}
sharedPtrImpl "Menu"
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/UI/Internal/Menu.hs | mit | 471 | 0 | 11 | 88 | 120 | 80 | 40 | -1 | -1 |
{-# Language BangPatterns #-}
module Main where
import System.IO
import System.Environment
import System.Console.Haskeline
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Error
import Control.Monad.State
import Control.DeepSeq
import Data.Either
import Types
import Parser
import Interpreter
import Builtins
import Environment
processExpr :: LispVal -> Environment -> (LispVal, Environment, LispVal)
processExpr !expr !env = result
where
(!expr', !env') = expandInterpreter (expr, env)
!tco = tailCallOptimize env' expr'
(!ret, !env'') = evalInterpreter (tco, env')
!result = (ret, env'', tco)
processRepl :: String -> Environment -> IO Environment
processRepl line env = do
let expr = parseForm "<stdin>" $ C.pack line
let (ret, env'', tco) = processExpr expr env
print ret
return env''
runRepl :: Environment -> IO ()
runRepl env = runInputT defaultSettings (loop env)
where
loop env = do
minput <- getInputLine "hl> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just input -> do
env' <- liftIO $ processRepl input env
loop env'
processFile :: Bool -> [LispVal] -> Environment -> IO Environment
processFile verbose !exprs !env = loop exprs env
where
loop ![] !env = return env
loop (expr:exprs) !env = do
let (ret, env'', tco) = processExpr expr env
if isLispError ret
then do
print "Error: "
print ret
return env''
else do
when verbose $ case tco of
(Definition _ _) -> return ()
_ -> print ret
loop exprs env''
runFile :: String -> Bool -> Environment -> IO Environment
runFile fname verbose !env = do
!source <- B.readFile fname
let !res = parseTopLevel fname source
case res of
Left err -> do
print err
return env
Right !exprs -> result where !result = processFile verbose exprs env
main :: IO ()
main = do
args <- getArgs
env <- liftM force runFile "stdlib.hl" False makeBuiltinEnvironment
let !env' = makeChildEnvironment env
case args of
[] -> runRepl env'
[fname] -> void $ runFile fname True env'
| mhlakhani/hlisp | src/Main.hs | mit | 2,229 | 0 | 17 | 528 | 772 | 373 | 399 | 71 | 4 |
module Hasql.Postgres.Session.Execution where
import Hasql.Postgres.Prelude
import qualified Data.HashTable.IO as Hashtables
import qualified Database.PostgreSQL.LibPQ as PQ
import qualified Hasql.Postgres.Statement as Statement
import qualified Hasql.Postgres.TemplateConverter as TemplateConverter
import qualified Hasql.Postgres.Session.ResultProcessing as ResultProcessing
-- * Environment
-------------------------
type Env =
(PQ.Connection, IORef Word16, Hashtables.BasicHashTable LocalKey RemoteKey)
newEnv :: PQ.Connection -> IO Env
newEnv c =
(,,) <$> pure c <*> newIORef 0 <*> Hashtables.new
-- |
-- Local statement key.
data LocalKey =
LocalKey !ByteString ![Word32]
deriving (Show, Eq)
instance Hashable LocalKey where
hashWithSalt salt (LocalKey template types) =
hashWithSalt salt template
localKey :: ByteString -> [PQ.Oid] -> LocalKey
localKey t ol =
LocalKey t (map oidMapper ol)
where
oidMapper (PQ.Oid x) = fromIntegral x
-- |
-- Remote statement key.
type RemoteKey =
ByteString
data Error =
UnexpectedResult Text |
ErroneousResult Text |
UnparsableTemplate ByteString Text |
TransactionConflict
-- * Monad
-------------------------
newtype M r =
M (ReaderT Env (EitherT Error IO) r)
deriving (Functor, Applicative, Monad, MonadIO)
run :: Env -> M r -> IO (Either Error r)
run e (M m) =
runEitherT $ runReaderT m e
throwError :: Error -> M a
throwError = M . lift . left
prepare :: ByteString -> [PQ.Oid] -> M RemoteKey
prepare s tl =
do
(c, counter, table) <- M $ ask
let lk = localKey s tl
rk <- liftIO $ Hashtables.lookup table lk
($ rk) $ ($ return) $ maybe $ do
w <- liftIO $ readIORef counter
let rk = fromString $ show w
unitResult =<< do liftIO $ PQ.prepare c rk s (partial (not . null) tl)
liftIO $ Hashtables.insert table lk rk
liftIO $ writeIORef counter (succ w)
return rk
statement :: Statement.Statement -> M (Maybe PQ.Result)
statement s =
do
(c, _, _) <- M $ ask
let (template, params, preparable) = s
convertedTemplate <-
either (throwError . UnparsableTemplate template) return $
TemplateConverter.convert template
case preparable of
True -> do
let (tl, vl) = unzip params
key <- prepare convertedTemplate tl
liftIO $ PQ.execPrepared c key vl PQ.Binary
False -> do
let params' = map (\(t, v) -> (\(vb, vf) -> (t, vb, vf)) <$> v) params
liftIO $ PQ.execParams c convertedTemplate params' PQ.Binary
liftResultProcessing :: ResultProcessing.M a -> M a
liftResultProcessing m =
M $ ReaderT $ \(c, _, _) ->
EitherT $ fmap (either (Left . mapError) Right) $ ResultProcessing.run c m
where
mapError =
\case
ResultProcessing.UnexpectedResult t -> UnexpectedResult t
ResultProcessing.ErroneousResult t -> ErroneousResult t
ResultProcessing.TransactionConflict -> TransactionConflict
{-# INLINE unitResult #-}
unitResult :: Maybe PQ.Result -> M ()
unitResult =
liftResultProcessing . (ResultProcessing.unit <=< ResultProcessing.just)
{-# INLINE vectorResult #-}
vectorResult :: Maybe PQ.Result -> M (Vector (Vector (Maybe ByteString)))
vectorResult =
liftResultProcessing . (ResultProcessing.vector <=< ResultProcessing.just)
{-# INLINE countResult #-}
countResult :: Maybe PQ.Result -> M Word64
countResult =
liftResultProcessing . (ResultProcessing.count <=< ResultProcessing.just)
| begriffs/hasql-postgres | library/Hasql/Postgres/Session/Execution.hs | mit | 3,467 | 0 | 21 | 717 | 1,134 | 591 | 543 | -1 | -1 |
module PureScript.Ide.Watcher where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM
import Control.Monad (forever, when)
import qualified Data.Map as M
import Data.Maybe (isJust)
import PureScript.Ide.Externs
import PureScript.Ide.Types
import System.FilePath
import System.FSNotify
reloadFile :: TVar PscState -> FilePath -> IO ()
reloadFile stateVar fp = do
Right (name, decls) <- readExternFile fp
reloaded <- atomically $ do
st <- readTVar stateVar
if isLoaded name st
then
loadModule name decls *> pure True
else
pure False
when reloaded $ putStrLn $ "Reloaded File at: " ++ fp
where
isLoaded name st = isJust (M.lookup name (pscStateModules st))
loadModule name decls = modifyTVar stateVar $ \x ->
x { pscStateModules = M.insert name decls (pscStateModules x)}
watcher :: TVar PscState -> FilePath -> IO ()
watcher stateVar fp = withManager $ \mgr -> do
_ <- watchTree mgr fp
(\ev -> takeFileName (eventPath ev) == "externs.json")
(reloadFile stateVar . eventPath)
forever (threadDelay 10000)
| nwolverson/psc-ide | src/PureScript/Ide/Watcher.hs | mit | 1,218 | 0 | 16 | 344 | 371 | 190 | 181 | 28 | 2 |
import qualified Problem01 as P01
import qualified Problem02 as P02
import qualified Problem03 as P03
import qualified Problem04 as P04
import qualified Problem05 as P05
import qualified Problem06 as P06
import qualified Problem07 as P07
import qualified Problem08 as P08
import qualified Problem14 as P14
cine = False :: Bool
main = P14.partB
--main = do
-- putStrLn "Day 1:"
-- putStr "\tPart A: "
-- P01.partA
-- putStr "\tPart B: "
-- P01.partB
--
-- putStrLn "Day 2:"
-- putStr "\tPart A: "
-- P02.partA
-- putStr "\tPart B: "
-- P02.partB
--
-- putStrLn "Day 3:"
-- putStr "\tPart A: "
-- P03.partA
-- putStr "\tPart B: "
-- P03.partB
--
-- putStrLn "Day 4:"
-- putStr "\tPart A: "
-- P04.partA
-- putStr "\tPart B: "
-- P04.partB
--
-- putStrLn "Day 5:"
-- putStr "\tPart A: "
-- P05.partA
-- putStr "\tPart B: "
-- if cine then P05.partBCine else P05.partB
--
-- putStrLn "Day 6:"
-- putStr "\tPart A: "
-- P06.partA
-- putStr "\tPart B: "
-- P06.partB
--
-- putStrLn "Day 7:"
-- putStr "\tPart A: "
-- P07.partA
-- putStr "\tPart B: "
-- P07.partB
--
-- putStrLn "Day 8:"
-- putStr "\tPart A: "
-- P08.partA
-- putStrLn "\tPart B: "
-- P08.partB
| edwardwas/adventOfCodeTwo | src/Main.hs | mit | 1,278 | 0 | 5 | 335 | 118 | 102 | 16 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.BufferMode
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.BufferMode where
import Prelude hiding(getLine)
import IDE.Core.State
import Data.List (isPrefixOf, elemIndices, isInfixOf, isSuffixOf)
import IDE.TextEditor
(getOffset, startsLine, getIterAtMark, EditorView(..),
getSelectionBoundMark, getInsertMark, getBuffer,
delete, getText, forwardCharsC, insert, getIterAtLine,
getLine, TextEditor(..), EditorBuffer(..),
EditorIter(..))
import Data.IORef (IORef)
import System.Time (ClockTime)
import Data.Typeable (cast, Typeable)
import IDE.SourceCandy
(getCandylessText, keystrokeCandy, transformFromCandy,
transformToCandy)
import IDE.Utils.GUIUtils (getCandyState)
import Control.Monad (when)
import Data.Maybe (mapMaybe, catMaybes)
import IDE.Utils.FileUtils
import Graphics.UI.Gtk
(Notebook, castToWidget, notebookPageNum, ScrolledWindow)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Time (UTCTime)
import Data.Text (Text)
import Data.Monoid ((<>))
import qualified Data.Text as T
(isPrefixOf, lines, unlines, count, isInfixOf)
-- * Buffer Basics
--
-- | A text editor pane description
--
data IDEBuffer = forall editor. TextEditor editor => IDEBuffer {
fileName :: Maybe FilePath
, bufferName :: Text
, addedIndex :: Int
, sourceView :: EditorView editor
, scrolledWindow :: ScrolledWindow
, modTime :: IORef (Maybe UTCTime)
, mode :: Mode
} deriving (Typeable)
instance Pane IDEBuffer IDEM
where
primPaneName = bufferName
getAddedIndex = addedIndex
getTopWidget = castToWidget . scrolledWindow
paneId b = ""
data BufferState = BufferState FilePath Int
| BufferStateTrans Text Text Int
deriving(Eq,Ord,Read,Show,Typeable)
maybeActiveBuf :: IDEM (Maybe IDEBuffer)
maybeActiveBuf = do
mbActivePane <- getActivePane
mbPane <- lastActiveBufferPane
case (mbPane,mbActivePane) of
(Just paneName1, Just (paneName2,_)) | paneName1 == paneName2 -> do
(PaneC pane) <- paneFromName paneName1
let mbActbuf = cast pane
return mbActbuf
_ -> return Nothing
lastActiveBufferPane :: IDEM (Maybe PaneName)
lastActiveBufferPane = do
rs <- recentSourceBuffers
case rs of
(hd : _) -> return (Just hd)
_ -> return Nothing
recentSourceBuffers :: IDEM [PaneName]
recentSourceBuffers = do
recentPanes' <- readIDE recentPanes
mbBufs <- mapM mbPaneFromName recentPanes'
return $ map paneName (mapMaybe (\ (PaneC p) -> cast p) (catMaybes mbBufs) :: [IDEBuffer])
getStartAndEndLineOfSelection :: TextEditor editor => EditorBuffer editor -> IDEM (Int,Int)
getStartAndEndLineOfSelection ebuf = do
startMark <- getInsertMark ebuf
endMark <- getSelectionBoundMark ebuf
startIter <- getIterAtMark ebuf startMark
endIter <- getIterAtMark ebuf endMark
startLine <- getLine startIter
endLine <- getLine endIter
let (startLine',endLine',endIter') = if endLine >= startLine
then (startLine,endLine,endIter)
else (endLine,startLine,startIter)
b <- startsLine endIter'
let endLineReal = if b && endLine /= startLine then endLine' - 1 else endLine'
return (startLine',endLineReal)
inBufContext :: MonadIDE m => alpha -> IDEBuffer -> (forall editor. TextEditor editor => Notebook -> EditorView editor -> EditorBuffer editor -> IDEBuffer -> Int -> m alpha) -> m alpha
inBufContext def (ideBuf@IDEBuffer{sourceView = v}) f = do
(pane,_) <- liftIDE $ guiPropertiesFromName (paneName ideBuf)
nb <- liftIDE $ getNotebook pane
mbI <- liftIO $ notebookPageNum nb (scrolledWindow ideBuf)
case mbI of
Nothing -> liftIO $ do
sysMessage Normal $ bufferName ideBuf <> " notebook page not found: unexpected"
return def
Just i -> do
ebuf <- liftIDE $ getBuffer v
f nb v ebuf ideBuf i
inActiveBufContext :: alpha -> (forall editor. TextEditor editor => Notebook -> EditorView editor -> EditorBuffer editor -> IDEBuffer -> Int -> IDEM alpha) -> IDEM alpha
inActiveBufContext def f = do
mbBuf <- maybeActiveBuf
case mbBuf of
Nothing -> return def
Just ideBuf ->
inBufContext def ideBuf f
doForSelectedLines :: [a] -> (forall editor. TextEditor editor => EditorBuffer editor -> Int -> IDEM a) -> IDEM [a]
doForSelectedLines d f = inActiveBufContext d $ \_ _ ebuf currentBuffer _ -> do
(start,end) <- getStartAndEndLineOfSelection ebuf
beginUserAction ebuf
result <- mapM (f ebuf) [start .. end]
endUserAction ebuf
return result
-- * Buffer Modes
data Mode = Mode {
modeName :: Text,
modeEditComment :: IDEAction,
modeEditUncomment :: IDEAction,
modeSelectedModuleName :: IDEM (Maybe Text),
modeEditToCandy :: (Text -> Bool) -> IDEAction,
modeTransformToCandy :: forall editor . TextEditor editor => (Text -> Bool) -> EditorBuffer editor -> IDEAction,
modeEditFromCandy :: IDEAction,
modeEditKeystrokeCandy :: Maybe Char -> (Text -> Bool) -> IDEAction,
modeEditInsertCode :: forall editor . TextEditor editor => Text -> EditorIter editor -> EditorBuffer editor -> IDEAction,
modeEditInCommentOrString :: Text -> Bool
}
-- | Assumes
modFromFileName :: Maybe FilePath -> Mode
modFromFileName Nothing = haskellMode
modFromFileName (Just fn) | ".hs" `isSuffixOf` fn = haskellMode
| ".lhs" `isSuffixOf` fn = literalHaskellMode
| ".cabal" `isSuffixOf` fn = cabalMode
| otherwise = otherMode
haskellMode = Mode {
modeName = "Haskell",
modeEditComment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
insert ebuf sol "--"
return (),
modeEditUncomment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol 2
str <- getText ebuf sol sol2 True
when (str == "--") $ delete ebuf sol sol2
return (),
modeSelectedModuleName =
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ ->
case fileName currentBuffer of
Just filePath -> liftIO $ moduleNameFromFilePath filePath
Nothing -> return Nothing,
modeTransformToCandy = \ inCommentOrString ebuf -> do
ct <- readIDE candy
transformToCandy ct ebuf inCommentOrString,
modeEditToCandy = \ inCommentOrString -> do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
transformToCandy ct ebuf inCommentOrString,
modeEditFromCandy = do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
transformFromCandy ct ebuf,
modeEditKeystrokeCandy = \c inCommentOrString -> do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
keystrokeCandy ct c ebuf inCommentOrString,
modeEditInsertCode = \ str iter buf ->
insert buf iter str,
modeEditInCommentOrString = \ line -> ("--" `T.isInfixOf` line)
|| odd (T.count "\"" line)
}
literalHaskellMode = Mode {
modeName = "Literal Haskell",
modeEditComment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol 1
str <- getText ebuf sol sol2 True
when (str == ">")
(delete ebuf sol sol2)
return (),
modeEditUncomment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol 1
str <- getText ebuf sol sol2 True
when (str /= ">")
(insert ebuf sol ">")
return (),
modeSelectedModuleName =
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ ->
case fileName currentBuffer of
Just filePath -> liftIO $ moduleNameFromFilePath filePath
Nothing -> return Nothing,
modeTransformToCandy = \ inCommentOrString ebuf -> do
ct <- readIDE candy
transformToCandy ct ebuf inCommentOrString,
modeEditToCandy = \ inCommentOrString -> do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
transformToCandy ct ebuf inCommentOrString,
modeEditFromCandy = do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
transformFromCandy ct ebuf,
modeEditKeystrokeCandy = \c inCommentOrString -> do
ct <- readIDE candy
inActiveBufContext () $ \_ _ ebuf _ _ ->
keystrokeCandy ct c ebuf inCommentOrString,
modeEditInsertCode = \ str iter buf ->
insert buf iter (T.unlines $ map (\ s -> "> " <> s) $ T.lines str),
modeEditInCommentOrString = \ line -> not (T.isPrefixOf ">" line)
|| odd (T.count "\"" line)
}
cabalMode = Mode {
modeName = "Cabal",
modeEditComment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
insert ebuf sol "--"
return (),
modeEditUncomment = do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol 2
str <- getText ebuf sol sol2 True
when (str == "--") $ delete ebuf sol sol2
return (),
modeSelectedModuleName = return Nothing,
modeTransformToCandy = \ _ _ -> return (),
modeEditToCandy = \ _ -> return (),
modeEditFromCandy = return (),
modeEditKeystrokeCandy = \ _ _ -> return (),
modeEditInsertCode = \ str iter buf -> insert buf iter str,
modeEditInCommentOrString = T.isPrefixOf "--"
}
otherMode = Mode {
modeName = "Unknown",
modeEditComment = return (),
modeEditUncomment = return (),
modeSelectedModuleName = return Nothing,
modeTransformToCandy = \ _ _ -> return (),
modeEditToCandy = \ _ -> return (),
modeEditFromCandy = return (),
modeEditKeystrokeCandy = \_ _ -> return (),
modeEditInsertCode = \str iter buf -> insert buf iter str,
modeEditInCommentOrString = const False
}
isHaskellMode mode = modeName mode == "Haskell" || modeName mode == "Literal Haskell"
withCurrentMode :: alpha -> (Mode -> IDEM alpha) -> IDEM alpha
withCurrentMode def act = do
mbBuf <- maybeActiveBuf
case mbBuf of
Nothing -> return def
Just ideBuf -> act (mode ideBuf)
editComment :: IDEAction
editComment = withCurrentMode () modeEditComment
editUncomment :: IDEAction
editUncomment = withCurrentMode () modeEditUncomment
selectedModuleName :: IDEM (Maybe Text)
selectedModuleName = withCurrentMode Nothing modeSelectedModuleName
editToCandy :: IDEAction
editToCandy = withCurrentMode () (\m -> modeEditToCandy m (modeEditInCommentOrString m))
editFromCandy :: IDEAction
editFromCandy = withCurrentMode () modeEditFromCandy
editKeystrokeCandy :: Maybe Char -> IDEAction
editKeystrokeCandy c = withCurrentMode () (\m -> modeEditKeystrokeCandy m c
(modeEditInCommentOrString m))
editInsertCode :: TextEditor editor => EditorBuffer editor -> EditorIter editor -> Text -> IDEAction
editInsertCode buffer iter str = withCurrentMode ()
(\ m -> modeEditInsertCode m str iter buffer)
| cocreature/leksah | src/IDE/BufferMode.hs | gpl-2.0 | 12,571 | 0 | 17 | 3,533 | 3,475 | 1,785 | 1,690 | 266 | 3 |
{- Chapter 15 :: Lazy evaluation -}
inc :: Int -> Int
inc n = n + 1
mult :: (Int,Int) -> Int
mult (x,y) = x * y
{-
> mult(1+2,2+3)
15
-}
mult' :: Int -> Int -> Int
mult' x = \y -> x * y
{-
> mult' (1+2) (2+3)
15
-}
inf :: Int
inf = 1 + inf
{-
> fst (0, inf)
0
-}
square :: Int -> Int
square n = n * n
ones :: [Int]
ones = 1 : ones
{-
> head ones
1
> take 3 ones
[1,1,1]
from standard prelude:
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
replicate :: Int -> a -> [a]
replicate 0 _ = []
replicate n x = x : replicate (n-1) x
> filter (<= 5) [1..]
[1,2,3,4,5.. (will loop endlessly)
> takeWhile (<= 5) [1..]
[1,2,3,4,5]
-}
primes :: [Int]
primes = sieve [2..]
sieve :: [Int] -> [Int]
sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
{-
> take 10 primes
[2,3,5,7,11,13,17,19,23,29]
> takeWhile (< 10) primes
[2,3,5,7]
------------------ Strict Application ---------------
> square (1+2)
9
> square $! (1+2)
9
square $! (1+2)
= square $! 3
= square 3
= 3 * 3
= 9
-}
sumwith :: Int -> [Int] -> Int
sumwith v [] = v
sumwith v (x:xs) = sumwith (v+x) xs
{-
sumwith 0 [1,2,3]
= sumwith (0+1) [2,3]
= sumwith ((0+1)+2) [3]
= sumwith (((0+1)+2)+3) []
= sumwith (((0+1)+2)+3) []
= ((0+1)+2)+3
= (1+2) + 3
= 3 + 3
= 6
-}
sumwith' :: Int -> [Int] -> Int
sumwith' v [] = v
sumwith' v (x:xs) = (sumwith' $! (v+x)) xs
{-
sumwith' 0 [1,2,3]
= (sumwith' $! (0+1)) [2,3]
= (sumwith' $! 1) [2,3]
= sumwith' 1 [2,3]
= (sumwith' $! (1,2)) [3]
= (sumwith' $! 3) [3]
= sumwith' 3 [3]
= (sumwith' $! (3+3)) []
= (sumwith' $! 6) []
= sumwith' 6 []
= 6
-}
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f v [] = v
foldl' f v (x:xs) = ((foldl' f) $! (f v x)) xs
sumwith'' :: Int -> [Int] -> Int
sumwith'' = foldl' (+)
{-
> sumwith'' 0 [1,2,3]
6
-}
| rad1al/hutton_exercises | notes_ch15.hs | gpl-2.0 | 1,823 | 0 | 10 | 459 | 460 | 253 | 207 | 27 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.GUI.Widget.MaxWidget
(
MaxWidget,
makeMaxWidget,
) where
import MyPrelude
import Game.GUI.Widget
import Game.GUI.Widget.ChildWidget
import Game.GUI.Widget.Helpers
import Game.GUI.Widget.Output
-- | MaxWidget has shape max(maxMaxShape, childShape)
data MaxWidget a =
MaxWidget
{
maxChild :: !(ChildWidget a),
maxMaxShape :: !GUIShape
}
--------------------------------------------------------------------------------
-- Widget structure
instance Widget MaxWidget where
widgetShape = maxShape
widgetBegin = maxBegin
widgetEatInput = maxEatInput
widgetIterate = maxIterate
maxShape :: GUIData -> GUIState -> MaxWidget a -> GUIShape
maxShape gd gs max =
let GUIShape wth hth = maxMaxShape max
GUIShape wth' hth' = widgetShape gd gs $ maxChild max
in GUIShape (Prelude.max wth wth') (Prelude.max hth hth')
maxBegin :: GUIData -> GUIState -> MaxWidget a -> IO (MaxWidget a)
maxBegin gd gs max = do
child' <- widgetBegin gd gs (maxChild max)
return $ max { maxChild = child' }
maxEatInput :: GUIData -> GUIState -> MaxWidget a -> WidgetInput -> MaxWidget a
maxEatInput gd gs max wi =
let shape@(GUIShape wth hth) = widgetShape gd gs $ maxChild max
GUIShape wth' hth' = maxMaxShape max
x = 0.5 * (Prelude.max wth wth' - wth)
y = 0.5 * (Prelude.max hth hth' - hth)
child' = ifInputInsideThenElse gd gs (GUIPos x y) shape wi
(\gs' wi' -> widgetEatInput gd gs' (maxChild max) wi')
(maxChild max)
in max { maxChild = child' }
maxIterate :: GUIData -> GUIState -> MaxWidget a -> a -> IO (MaxWidget a, a)
maxIterate gd gs max a = do
let GUIShape wth hth = widgetShape gd gs $ maxChild max
GUIShape wth' hth' = maxMaxShape max
x = 0.5 * (Prelude.max wth wth' - wth)
y = 0.5 * (Prelude.max hth hth' - hth)
-- iterate child
gs' <- plusPos gd gs $ GUIPos x y
(child', a') <- widgetIterate gd gs' (maxChild max) a
return (max { maxChild = child' }, a')
--------------------------------------------------------------------------------
-- make
makeMaxWidget :: Widget w => GUIData -> GUIShape -> w a -> MaxWidget a
makeMaxWidget gd shape w =
MaxWidget
{
maxChild = makeChildWidget gd w,
maxMaxShape = shape
}
| karamellpelle/grid | source/Game/GUI/Widget/MaxWidget.hs | gpl-3.0 | 3,114 | 0 | 14 | 733 | 775 | 405 | 370 | 55 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Memory.Output.Fancy.State
(
stateSetBeginShow,
) where
import MyPrelude
import Game
import Game.Memory
import Game.Memory.MemoryWorld.OutputState
import Game.Run.RunWorld
import System.Random
stateSetBeginShow :: MemoryWorld -> RunWorld -> IO (MemoryWorld, RunWorld)
stateSetBeginShow mem run = do
mem' <- modifyIO mem $ \state -> do
plus <- randomRIO (0, valueColorMapSize - 2)
let ix1 = (ostateColorIx1 state + plus) `mod` valueColorMapSize
return state
{
ostateColorIx0 = ostateColorIx1 state,
ostateColorIx1 = ix1
}
return (mem', run)
modifyIO :: MemoryWorld -> (OutputState -> IO OutputState) -> IO MemoryWorld
modifyIO mem f = do
state' <- f $ memoryOutputState mem
return mem { memoryOutputState = state' }
| karamellpelle/grid | source/Game/Memory/Output/Fancy/State.hs | gpl-3.0 | 1,636 | 0 | 18 | 396 | 257 | 146 | 111 | 22 | 1 |
{- This file is part of "settleDyn" software.
Copyright (C) 2009, 2010, 2011
Helmholtz Centre Potsdam, GFZ German Research Centre for Geosciences.
(C) 2011, 2012
Dmitrij Yu. Naumov
"settleDyn" 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.
"settleDyn" 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
"settleDyn". If not, see <http://www.gnu.org/licenses/>.
Author: Dmitrij Yu. Naumov
-}
module Config (
freezeTimeSteps
, generateGrainsOffset
, grainsGenerationBox
, grainsSizeMean
, grainsSizeMin
, grainsSizeSlope
, grainsSizeGenerator
, maxGrainsHeight
, maxMovingGrains
, maxNumberGrains
, maxSimulationSteps
, movingThreshold
, outputDirectory
, prototypeFiles
, verbose
, showHelp
, exportEveryStep
, exportLastStep
, setOptions, getOptions
, Options(..)
) where
import Data.IORef
import System.IO.Unsafe
data Options = Options {
_freezeTimeSteps :: Int
, _generateGrainsOffset :: Double
, _grainsGenerationBox :: Double -- for random x,z position
, _grainsSizeMean :: Double
, _grainsSizeMin :: Double
, _grainsSizeSlope :: Double
, _grainsSizeGenerator :: String
, _maxGrainsHeight :: Double
, _maxMovingGrains :: Int
, _maxNumberGrains :: Int
, _maxSimulationSteps :: Int
, _movingThreshold :: Double
, _outputDirectory :: String
, _prototypeFiles :: [FilePath]
, _verbose :: Bool
, _showHelp :: Bool
, _exportEveryStep :: Bool
, _exportLastStep :: Bool
} deriving Show
getOptions :: IO Options
getOptions = readIORef options
setOptions :: Options -> IO ()
setOptions = writeIORef options
{-# NOINLINE options #-}
options :: IORef Options
options = unsafePerformIO $ newIORef defaultOptions
defaultOptions = Options {
_freezeTimeSteps = 10000
, _generateGrainsOffset = 4
, _grainsGenerationBox = 5
, _grainsSizeMean = 2
, _grainsSizeMin = 1
, _grainsSizeSlope = 3
, _grainsSizeGenerator = "univariate"
, _maxGrainsHeight = 10
, _maxMovingGrains = 100
, _maxNumberGrains = 16000 -- limited by bullet's broadphase algorithm
, _maxSimulationSteps = 1000000
, _movingThreshold = 1e-4
, _outputDirectory = "out"
, _prototypeFiles = []
, _verbose = False
, _showHelp = False
, _exportEveryStep = False
, _exportLastStep = False
}
freezeTimeSteps = _freezeTimeSteps $ unsafePerformIO getOptions
generateGrainsOffset = _generateGrainsOffset $ unsafePerformIO getOptions
grainsGenerationBox = _grainsGenerationBox $ unsafePerformIO getOptions
grainsSizeMean = _grainsSizeMean $ unsafePerformIO getOptions
grainsSizeMin = _grainsSizeMin $ unsafePerformIO getOptions
grainsSizeSlope = _grainsSizeSlope $ unsafePerformIO getOptions
grainsSizeGenerator = _grainsSizeGenerator $ unsafePerformIO getOptions
maxGrainsHeight = _maxGrainsHeight $ unsafePerformIO getOptions
maxMovingGrains = _maxMovingGrains $ unsafePerformIO getOptions
maxNumberGrains = _maxNumberGrains $ unsafePerformIO getOptions
maxSimulationSteps = _maxSimulationSteps $ unsafePerformIO getOptions
movingThreshold = _movingThreshold $ unsafePerformIO getOptions
outputDirectory = _outputDirectory $ unsafePerformIO getOptions
prototypeFiles = _prototypeFiles $ unsafePerformIO getOptions
verbose = _verbose $ unsafePerformIO getOptions
showHelp = _showHelp $ unsafePerformIO getOptions
exportEveryStep = _exportEveryStep $ unsafePerformIO getOptions
exportLastStep = _exportLastStep $ unsafePerformIO getOptions
| endJunction/settleDyn | src/Config.hs | gpl-3.0 | 3,997 | 0 | 9 | 776 | 602 | 355 | 247 | 87 | 1 |
{-
ñïîëüçóß unfoldr, ðåàëèçóéòå ôóíêöèþ, êîòîðàß âîçâðàùàåò â îáðàòíîì àëôàâèòíîì ïîðßäêå ñïèñîê ñèìâîëîâ, ïîïàäàþùèõ â çàäàííûé ïàðîé äèàïàçîí. îïàäàíèå ñèìâîëà x â äèàïàçîí ïàðû (a,b) îçíà÷àåò, ÷òî x >= a è x <= b.
revRange :: (Char,Char) -> [Char]
revRange = unfoldr g
where g = undefined
GHCi> revRange ('a','z')
"zyxwvutsrqponmlkjihgfedcba"
-}
module Demo where
import Data.List
revRange :: (Char,Char) -> [Char]
revRange (a,b) = if (a <= b) then unfoldr g b else ""
where g = (\x -> if x==(pred a) then Nothing else Just (x,pred x)) | devtype-blogspot-com/Haskell-Examples | RevRange/Demo.hs | gpl-3.0 | 556 | 0 | 12 | 104 | 107 | 62 | 45 | 5 | 3 |
{-# LANGUAGE DeriveFunctor, GADTs, KindSignatures, ScopedTypeVariables #-}
module Chamber.Data.Boolean where
import qualified Data.Map as M
import Debug.Trace
import Data.Maybe
import Data.Monoid
import Data.List hiding (concat, foldr)
import Prelude hiding (concat, foldr)
import Data.Foldable
import Control.Monad.State
import Control.Monad.ST
import Data.STRef
import Chamber.Data.NC
import qualified Chamber.Data.Formula as F
--------------------------------------------------------------------------------
type Variable = Int -- Should be (strictly) positive.
type Literal = Int
type CNF = [[Literal]]
-- Functions for constructing formulae
evalCNF :: (Variable -> Bool) -> CNF -> Bool
eq :: NC a -> NC a -> NC a
xor :: NC a -> NC a -> NC a
ite :: NC a -> NC a -> NC a -> NC a
land :: [NC a] -> NC a
lor :: [NC a] -> NC a
-- Conversion to NC.
toNC :: F.Formula a -> NC a
-- Functions for transforming formulae
-- Transform a formula of 3 args. into a boolean function.
-- TODO: Generalize this via Template Haskell
ftf3 :: (Eq a) => a -> a -> a -> F.Formula a -> Bool -> Bool -> Bool -> Bool
-- [litify] transform a formula on a comparable (via ==) types to formula only
-- on integers, returning an list specifying the variable assignment.
litify :: Ord a => NC a -> (NC Variable, M.Map a Variable, Int)
-- [cnf] performs the simple (worst-case exponential time) conversion of an
-- arbitrary formula to one in which all NOT gates directly preceed variables
-- and every AND gate appears above every OR gate.
cnf :: NC a -> NC a
-- [convert] wraps [cnf] and translates the result it into a CNF type.
convert :: NC Variable -> CNF
-- [cnfPoly] performs polynomial time expansion of the formula, which may add
-- additional variables. The State monad is used to keep track of how many
-- variables are used in the formula. [cnfPoly] returns (within the monad) a
-- variable representing the result current expression as well as additional
-- clauses that make it happen.
cnfPoly :: NC Variable -> State (Variable, CNF) Variable
convertPoly :: NC Variable -> (CNF, Int)
convertPolyST :: NC Variable -> Int -> (CNF, Int)
-- print a CNF in DIMCAS format
dimacs :: Int -> CNF -> String
-- parse a solution in DIMCAS format; solution is expected to be an actual
-- solution, not "s UNSATISIFIABLE"
undimacs :: String -> M.Map Int Bool
--------------------------------------------------------------------------------
ftf3 v1 v2 v3 f v1b v2b v3b = F.eval varmap f
where varmap x =
if x == v1 then v1b else
if x == v2 then v2b else
if x == v3 then v3b else undefined
evl a x = if x < 0 then not $ a (abs x) else a x
evalCNF a c = foldr (&&) True $ map ((foldr (||) False).(map $ evl a)) c
eq f g = Or (And f g) (And (Not f) (Not g))
xor f g = Or (And (Not f) g) (And f (Not g))
ite f g h = Or (And f g) (And (Not f) h)
land [] = undefined
land [x] = x
land (x:xs) = And x (land xs)
lor [] = undefined
lor [x] = x
lor (x:xs) = Or x (lor xs)
toNC (F.Var v) = Var v
toNC (F.Not f) = Not (toNC f)
toNC (F.And fs) = case fs of
[x] -> toNC x
(x:xs) -> And (toNC x) $ toNC (F.And xs)
toNC (F.Or fs) = case fs of
[x] -> toNC x
(x:xs) -> Or (toNC x) $ toNC (F.Or xs)
toNC (F.Xor fs) = case fs of
[x] -> toNC x
(x:xs) -> xor (toNC x) $ toNC (F.Xor xs)
toNC (F.Eql fs) = case fs of
[x, y] -> eq (toNC x) (toNC y)
(x:y:xs) -> And (eq (toNC x) (toNC y)) (toNC $ F.Eql (y:xs))
toNC (F.Dec x y z) = ite (toNC x) (toNC y) (toNC z)
-- Convert to CNF ([And]s above [Or]s)
distributeLeft x (And e f) = And (distributeLeft x e) (distributeLeft x f)
distributeLeft x y = Or x y
distributeOr (And e f) y = And (distributeOr e y) (distributeOr f y)
distributeOr x y = distributeLeft x y
cnf (Var v) = Var v
cnf (Not (Var v)) = Not (Var v)
cnf (Not (Not f)) = f
cnf (Not (And e f)) = cnf $ Or (Not e) (Not f)
cnf (Not (Or e f)) = cnf $ And (Not e) (Not f)
cnf (And e f) = And (cnf e) (cnf f)
cnf (Or e f) = distributeOr (cnf e) (cnf f)
clausify (Var v) = [v] -- Clausify should only be called
clausify (Not (Var v)) = [-v] -- on formula with only `Or' nodes
clausify (Or e f) = clausify e ++ clausify f -- and `Not' nodes in which all the
clausify (And _ _) = undefined -- `Not' nodes appear directly
clausify (Not _) = undefined -- above variables.
listify (And e f) = convert e ++ convert f
listify x = [clausify x]
convert = listify.cnf
new = do (var, cs) <- get; put (var + 1, cs); return var
shed cs = do (x, cs') <- get
put (x, cs ++ cs')
cnfPoly (Var v) = return v
cnfPoly (Not f) = do v <- cnfPoly f
n <- new
shed [[v,n], [-v,-n]]
return n
cnfPoly (Or f g) = do fv <- cnfPoly f
gv <- cnfPoly g
n <- new
shed [[n,-fv], [n,-gv], [-n,fv,gv]]
return n
cnfPoly (And f g) = do fv <- cnfPoly f
gv <- cnfPoly g
n <- new
shed [[-n,fv], [-n,gv], [n,-fv,-gv]]
return n
cnfPolyST :: STRef s Int -> STRef s CNF -> NC Variable -> ST s (Variable)
cnfPolyST nref lref f = case f of
(Var v) -> return v
(Not f) -> do v <- cnfPolyST nref lref f
n <- readSTRef nref
modifySTRef nref (+1)
modifySTRef lref ([[v,n], [-v,-n]]++)
seq n $ return n
(Or f g) -> do fv <- cnfPolyST nref lref f
gv <- cnfPolyST nref lref g
n <- readSTRef nref
modifySTRef nref (+1)
modifySTRef lref ([[n,-fv], [n,-gv], [-n,fv,gv]]++)
seq n $ return n
(And f g) -> do fv <- cnfPolyST nref lref f
gv <- cnfPolyST nref lref g
n <- readSTRef nref
modifySTRef nref (+1)
modifySTRef lref ([[-n,fv], [-n,gv], [n,-fv,-gv]]++)
seq n $ return n
convertPoly f = ([v]:clauses, v)
where (v, clauses) = execState (cnfPoly f)
$ (1 + (length $ nub $ foldr (:) [] f), [])
convertPolyST f vn = runST $ do
n <- newSTRef $ 1 + vn
cnf <- newSTRef []
v <- cnfPolyST n cnf f
cnf' <- readSTRef cnf
n' <- readSTRef n
return $ ([v]:cnf', v)
litify f = (fmap (m M.!) f, m, n)
where list = nub $ foldr (:) [] f
(n, m) = foldr (\v (k, m) -> (k + 1, M.insert v k m)) (1, M.empty) list
dimacs varnum cnf = "p cnf " ++ show varnum ++ " " ++ (show $ length cnf) ++ "\n" ++ cs
where cs = concat $ intersperse "\n" $ map formatClause cnf
-- varnum = length $ nub $ map abs $ concat cnf
formatClause c = (concat $ intersperse " " $ map show c) ++ " 0"
undimacs s = foldr (\i m -> if i > 0 then M.insert i True m
else M.insert (-i) False m) M.empty
$ map read $ words $ filter (\x -> (x /= '\n') && (x /= 'v'))
$ concat $ filter (\l -> ((head l) /= 'c') && ((head l) /= 's'))
$ lines s
| sjindel/Chamber | Chamber/Data/Boolean.hs | gpl-3.0 | 7,152 | 1 | 17 | 2,144 | 3,064 | 1,572 | 1,492 | 142 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.URI.Text
-- Copyright : (c) 2004, Graham Klyne
-- License : BSD-style (see end of this file)
--
-- Maintainer : Graham Klyne <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- This is a Text-oriented version. Everything deprecated and not GHC related
-- has been removed.
--
-- This module defines functions for handling URIs. It presents substantially
-- the same interface as the older GHC Network.URI module, but is implemented
-- using Parsec rather than a Regex library that is not available with Hugs.
-- The internal representation of URI has been changed so that URI strings are
-- more completely preserved when round-tripping to a URI value and back.
--
-- In addition, four methods are provided for parsing different
-- kinds of URI string (as noted in RFC3986):
-- 'parseURI',
-- 'parseURIReference',
-- 'parseRelativeReference' and
-- 'parseAbsoluteURI'.
--
-- Further, four methods are provided for classifying different
-- kinds of URI string (as noted in RFC3986):
-- 'isURI',
-- 'isURIReference',
-- 'isRelativeReference' and
-- 'isAbsoluteURI'.
--
-- The long-standing official reference for URI handling was RFC2396 [1],
-- as updated by RFC 2732 [2], but this was replaced by a new specification,
-- RFC3986 [3] in January 2005. This latter specification has been used
-- as the primary reference for constructing the URI parser implemented
-- here, and it is intended that there is a direct relationship between
-- the syntax definition in that document and this parser implementation.
--
-- RFC 1808 [4] contains a number of test cases for relative URI handling.
-- Dan Connolly's Python module @uripath.py@ [5] also contains useful details
-- and test cases.
--
-- Some of the code has been copied from the previous GHC implementation,
-- but the parser is replaced with one that performs more complete
-- syntax checking of the URI itself, according to RFC3986 [3].
--
-- References
--
-- (1) <http://www.ietf.org/rfc/rfc2396.txt>
--
-- (2) <http://www.ietf.org/rfc/rfc2732.txt>
--
-- (3) <http://www.ietf.org/rfc/rfc3986.txt>
--
-- (4) <http://www.ietf.org/rfc/rfc1808.txt>
--
-- (5) <http://www.w3.org/2000/10/swap/uripath.py>
--
--------------------------------------------------------------------------------
module Network.URI.Text
( -- * The URI type
URI(..)
, URIAuth(..)
, nullURI
-- * Parsing
, parseURI -- :: Text -> Maybe URI
, parseURIReference -- :: Text -> Maybe URI
, parseRelativeReference -- :: Text -> Maybe URI
, parseAbsoluteURI -- :: Text -> Maybe URI
-- * Test for strings containing various kinds of URI
, isURI
, isURIReference
, isRelativeReference
, isAbsoluteURI
, isIPv6address
, isIPv4address
-- * Relative URIs
, relativeTo -- :: URI -> URI -> Maybe URI
, nonStrictRelativeTo -- :: URI -> URI -> Maybe URI
, relativeFrom -- :: URI -> URI -> URI
-- * Operations on URI strings
-- | Support for putting strings into URI-friendly
-- escaped format and getting them back again.
-- This can't be done transparently in all cases, because certain
-- characters have different meanings in different kinds of URI.
-- The URI spec [3], section 2.4, indicates that all URI components
-- should be escaped before they are assembled as a URI:
-- \"Once produced, a URI is always in its percent-encoded form\"
, uriToString -- :: URI -> ShowS
, isReserved, isUnreserved -- :: Char -> Bool
, isAllowedInURI, isUnescapedInURI -- :: Char -> Bool
, escapeURIChar -- :: (Char->Bool) -> Char -> Text
, escapeURIString -- :: (Char->Bool) -> Text -> Text
, unEscapeString -- :: Text -> Text
-- * URI Normalization functions
, normalizeCase -- :: Text -> Text
, normalizeEscape -- :: Text -> Text
, normalizePathSegments -- :: Text -> Text
)
where
import Data.Text ( Text )
import qualified Data.Text as T
import Text.Parsec
( ParseError
, parse, (<|>), (<?>), try
, option, many, many1, count, notFollowedBy
, char, satisfy, oneOf, string, eof
, unexpected
)
import Text.Parsec.Text ( GenParser )
import Data.Char( ord, chr, isHexDigit, toLower, toUpper, digitToInt )
import Numeric( showIntAtBase )
import Data.Typeable ( Typeable )
import Data.Data ( Data )
------------------------------------------------------------
-- The URI datatype
------------------------------------------------------------
-- |Represents a general universal resource identifier using
-- its component parts.
--
-- For example, for the URI
--
-- > foo://[email protected]:42/ghc?query#frag
--
-- the components are:
--
data URI = URI
{ uriScheme :: Text -- ^ @foo:@
, uriAuthority :: Maybe URIAuth -- ^ @\/\/anonymous\@www.haskell.org:42@
, uriPath :: Text -- ^ @\/ghc@
, uriQuery :: Text -- ^ @?query@
, uriFragment :: Text -- ^ @#frag@
} deriving (Eq, Typeable, Data)
-- |Type for authority value within a URI
data URIAuth = URIAuth
{ uriUserInfo :: Text -- ^ @anonymous\@@
, uriRegName :: Text -- ^ @www.haskell.org@
, uriPort :: Text -- ^ @:42@
} deriving (Eq, Typeable, Data, Show)
-- |Blank URI
nullURI :: URI
nullURI = URI
{ uriScheme = T.empty
, uriAuthority = Nothing
, uriPath = T.empty
, uriQuery = T.empty
, uriFragment = T.empty
}
-- URI as instance of Show. Note that for security reasons, the default
-- behaviour is to suppress any userinfo field (see RFC3986, section 7.5).
-- This can be overridden by using uriToText directly with first
-- argument @id@ (noting that this returns a ShowS value rather than a string).
--
-- [[[Another design would be to embed the userinfo mapping function in
-- the URIAuth value, with the default value suppressing userinfo formatting,
-- but providing a function to return a new URI value with userinfo
-- data exposed by show.]]]
--
instance Show URI where
showsPrec _ aUri = uriToString defaultUserInfoMap aUri
defaultUserInfoMap :: Text -> Text
defaultUserInfoMap uinf = T.append user newpass
where
(user, pass) = T.break (== ':') uinf
newpass = if T.null pass || (pass == "@") || (pass == ":@")
then pass
else ":...@"
------------------------------------------------------------
-- Parse a URI
------------------------------------------------------------
-- |Turn a string containing a URI into a 'URI'.
-- Returns 'Nothing' if the string is not a valid URI;
-- (an absolute URI with optional fragment identifier).
--
-- NOTE: this is different from the previous network.URI,
-- whose @parseURI@ function works like 'parseURIReference'
-- in this module.
--
parseURI :: Text -> Maybe URI
parseURI = parseURIAny uri
-- |Parse a URI reference to a 'URI' value.
-- Returns 'Nothing' if the string is not a valid URI reference.
-- (an absolute or relative URI with optional fragment identifier).
--
parseURIReference :: Text -> Maybe URI
parseURIReference = parseURIAny uriReference
-- |Parse a relative URI to a 'URI' value.
-- Returns 'Nothing' if the string is not a valid relative URI.
-- (a relative URI with optional fragment identifier).
--
parseRelativeReference :: Text -> Maybe URI
parseRelativeReference = parseURIAny relativeRef
-- |Parse an absolute URI to a 'URI' value.
-- Returns 'Nothing' if the string is not a valid absolute URI.
-- (an absolute URI without a fragment identifier).
--
parseAbsoluteURI :: Text -> Maybe URI
parseAbsoluteURI = parseURIAny absoluteURI
-- |Test if string contains a valid URI
-- (an absolute URI with optional fragment identifier).
--
isURI :: Text -> Bool
isURI = isValidParse uri
-- |Test if string contains a valid URI reference
-- (an absolute or relative URI with optional fragment identifier).
--
isURIReference :: Text -> Bool
isURIReference = isValidParse uriReference
-- |Test if string contains a valid relative URI
-- (a relative URI with optional fragment identifier).
--
isRelativeReference :: Text -> Bool
isRelativeReference = isValidParse relativeRef
-- |Test if string contains a valid absolute URI
-- (an absolute URI without a fragment identifier).
--
isAbsoluteURI :: Text -> Bool
isAbsoluteURI = isValidParse absoluteURI
-- |Test if string contains a valid IPv6 address
--
isIPv6address :: Text -> Bool
isIPv6address = isValidParse ipv6address
-- |Test if string contains a valid IPv4 address
--
isIPv4address :: Text -> Bool
isIPv4address = isValidParse ipv4address
-- Helper function for turning a string into a URI
--
parseURIAny :: URIParser URI -> Text -> Maybe URI
parseURIAny parser uristr = case parseAll parser "" uristr of
Left _ -> Nothing
Right u -> Just u
-- Helper function to test a string match to a parser
--
isValidParse :: URIParser a -> Text -> Bool
isValidParse parser uristr = case parseAll parser "" uristr of
Left _ -> False
Right _ -> True
parseAll :: URIParser a -> String -> Text -> Either ParseError a
parseAll parser filename uristr = parse newparser filename uristr
where newparser = do
res <- parser
eof
return res
------------------------------------------------------------
-- URI parser body based on Parsec elements and combinators
------------------------------------------------------------
-- Parser parser type.
-- Currently
type URIParser a = GenParser () a
-- RFC3986, section 2.1
--
-- Parse and return a 'pct-encoded' sequence
--
escaped :: URIParser Text
escaped = do
_ <- char '%'
h1 <- hexDigitChar
h2 <- hexDigitChar
return $ T.cons '%' (T.append h1 h2)
-- RFC3986, section 2.2
--
-- |Returns 'True' if the character is a \"reserved\" character in a
-- URI. To include a literal instance of one of these characters in a
-- component of a URI, it must be escaped.
--
isReserved :: Char -> Bool
isReserved c = isGenDelims c || isSubDelims c
isGenDelims :: Char -> Bool
isGenDelims c = c `telem` ":/?#[]@"
isSubDelims :: Char -> Bool
isSubDelims c = c `telem` "!$&'()*+,;="
subDelims :: URIParser Text
subDelims = T.singleton <$> satisfy isSubDelims
telem :: Char -> Text -> Bool
telem needle haystack = T.findIndex (== needle) haystack /= Nothing
-- RFC3986, section 2.3
--
-- |Returns 'True' if the character is an \"unreserved\" character in
-- a URI. These characters do not need to be escaped in a URI. The
-- only characters allowed in a URI are either \"reserved\",
-- \"unreserved\", or an escape sequence (@%@ followed by two hex digits).
--
isUnreserved :: Char -> Bool
isUnreserved c = isAlphaNumChar c || (c `telem` "-_.~")
unreservedChar :: URIParser Text
unreservedChar = T.singleton <$> satisfy isUnreserved
-- RFC3986, section 3
--
-- URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
--
-- hier-part = "//" authority path-abempty
-- / path-abs
-- / path-rootless
-- / path-empty
uri :: URIParser URI
uri = do
us <- try uscheme
(ua,up) <- hierPart
uq <- option "" ( char '?' >> uquery )
uf <- option "" ( char '#' >> ufragment )
return $ URI
{ uriScheme = us
, uriAuthority = ua
, uriPath = up
, uriQuery = uq
, uriFragment = uf
}
hierPart :: URIParser ((Maybe URIAuth), Text)
hierPart = withAuthority <|> absoluteWOAuth <|> rootLessWOAuth <|> nothingAtAll
where
withAuthority = do
_ <- try (string "//")
ua <- uauthority
up <- pathAbEmpty
return (ua, up)
absoluteWOAuth = (Nothing ,) <$> pathAbs
rootLessWOAuth = (Nothing ,) <$> pathRootLess
nothingAtAll = return (Nothing, "")
-- RFC3986, section 3.1
uscheme :: URIParser Text
uscheme = do
s <- oneThenMany alphaChar schemeChar
_ <- char ':'
return $ T.snoc s ':'
-- RFC3986, section 3.2
uauthority :: URIParser (Maybe URIAuth)
uauthority = do
uu <- option "" (try userinfo)
uh <- host
up <- option "" port
return $ Just $ URIAuth
{ uriUserInfo = uu
, uriRegName = uh
, uriPort = up
}
-- RFC3986, section 3.2.1
userinfo :: URIParser Text
userinfo = do
uu <- many (uchar ";:&=+$,")
_ <- char '@'
return (T.snoc (T.concat uu) '@')
-- RFC3986, section 3.2.2
host :: URIParser Text
host = ipLiteral <|> try ipv4address <|> regName
ipLiteral :: URIParser Text
ipLiteral = parseIpLiteral <?> "IP address literal"
where parseIpLiteral = do
_ <- char '['
ua <- ( ipv6address <|> ipvFuture )
_ <- char ']'
return $ T.concat [ "[", ua, "]" ]
ipvFuture :: URIParser Text
ipvFuture = do
_ <- char 'v'
h <- hexDigitChar
_ <- char '.'
a <- many1 (satisfy isIpvFutureChar)
return $ T.concat [ "c", h, ".", T.pack a ]
isIpvFutureChar :: Char -> Bool
isIpvFutureChar c = isUnreserved c || isSubDelims c || (c == ';')
ipv6address :: URIParser Text
ipv6address = try case1 <|> try case2 <|> try case3 <|> try case4
<|> try case5 <|> try case6 <|> try case7 <|> try case8
<|> try case9 <?> "IPv6 address"
where
case1 = do
a2 <- count 6 h4c
a3 <- ls32
return $ T.append (T.concat a2) a3
case2 = do
_ <- string "::"
a2 <- count 5 h4c
a3 <- ls32
return $ T.concat [ "::", T.concat a2, a3 ]
case3 = do
a1 <- opt_n_h4c_h4 0
_ <- string "::"
a2 <- count 4 h4c
a3 <- ls32
return $ T.concat [ a1, "::", T.concat a2, a3 ]
case4 = do
a1 <- opt_n_h4c_h4 1
_ <- string "::"
a2 <- count 3 h4c
a3 <- ls32
return $ T.concat [ a1, "::", T.concat a2, a3 ]
case5 = do
a1 <- opt_n_h4c_h4 2
_ <- string "::"
a2 <- count 2 h4c
a3 <- ls32
return $ T.concat [ a1, "::", T.concat a2, a3 ]
case6 = do
a1 <- opt_n_h4c_h4 3
_ <- string "::"
a2 <- h4c
a3 <- ls32
return $ T.concat [ a1, "::", a2, a3 ]
case7 = do
a1 <- opt_n_h4c_h4 4
_ <- string "::"
a3 <- ls32
return $ T.concat [ a1, "::", a3 ]
case8 = do
a1 <- opt_n_h4c_h4 5
_ <- string "::"
a3 <- h4
return $ T.concat [ a1, "::", a3 ]
case9 = do
a1 <- opt_n_h4c_h4 6
_ <- string "::"
return $ T.append a1 "::"
opt_n_h4c_h4 :: Int -> URIParser Text
opt_n_h4c_h4 n = option "" $ do
a1 <- countMinMax 0 n h4c
a2 <- h4
return $ T.append a1 a2
ls32 :: URIParser Text
ls32 = try parseLs32 <|> ipv4address
where parseLs32 = h4c >>= \a1 -> h4 >>= \a2 -> return (T.append a1 a2)
h4c :: URIParser Text
h4c = try $ do
a1 <- h4
_ <- char ':'
notFollowedBy (char ':')
return $ T.snoc a1 ':'
h4 :: URIParser Text
h4 = countMinMax 1 4 hexDigitChar
ipv4address :: URIParser Text
ipv4address = do
a1 <- decOctet
_ <- char '.'
a2 <- decOctet
_ <- char '.'
a3 <- decOctet
_ <- char '.'
a4 <- decOctet
return $ T.concat [ a1, ".", a2, ".", a3, ".", a4 ]
decOctet :: URIParser Text
decOctet = do
a1 <- countMinMax 1 3 digitChar
if read (T.unpack a1) > (255 :: Integer)
then fail "Decimal octet value too large"
else return a1
regName :: URIParser Text
regName = countMinMax 0 255 ( unreservedChar <|> escaped <|> subDelims )
<?> "Registered name"
-- RFC3986, section 3.2.3
port :: URIParser Text
port = do
_ <- char ':'
p <- many digitChar
return (T.cons ':' (T.concat p))
--
-- RFC3986, section 3.3
--
-- path = path-abempty ; begins with "/" or is empty
-- / path-abs ; begins with "/" but not "//"
-- / path-noscheme ; begins with a non-colon segment
-- / path-rootless ; begins with a segment
-- / path-empty ; zero characters
--
-- path-abempty = *( "/" segment )
-- path-abs = "/" [ segment-nz *( "/" segment ) ]
-- path-noscheme = segment-nzc *( "/" segment )
-- path-rootless = segment-nz *( "/" segment )
-- path-empty = 0<pchar>
--
-- segment = *pchar
-- segment-nz = 1*pchar
-- segment-nzc = 1*( unreserved / pct-encoded / sub-delims / "@" )
--
-- pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
{-
upath :: URIParser Text
upath = pathAbEmpty
<|> pathAbs
<|> pathNoScheme
<|> pathRootLess
<|> pathEmpty
-}
pathAbEmpty :: URIParser Text
pathAbEmpty = T.concat <$> many slashSegment
pathAbs :: URIParser Text
pathAbs = char '/' >> T.cons '/' <$> option "" pathRootLess
pathNoScheme :: URIParser Text
pathNoScheme = do
s1 <- segmentNzc
ss <- many slashSegment
return $ T.append s1 (T.concat ss)
pathRootLess :: URIParser Text
pathRootLess = do
s1 <- segmentNz
ss <- many slashSegment
return $ T.append s1 (T.concat ss)
slashSegment :: URIParser Text
slashSegment = char '/' >> T.cons '/' <$> segment
segment :: URIParser Text
segment = T.concat <$> many pchar
segmentNz :: URIParser Text
segmentNz = T.concat <$> many1 pchar
segmentNzc :: URIParser Text
segmentNzc = T.concat <$> many1 (uchar "@")
pchar :: URIParser Text
pchar = uchar ":@"
-- helper function for pchar and friends
uchar :: String -> URIParser Text
uchar extras = unreservedChar <|> escaped <|> subDelims <|> oneOfExtras
where oneOfExtras = T.singleton <$> oneOf extras
-- RFC3986, section 3.4
uquery :: URIParser Text
uquery = do
ss <- many $ uchar (":@" ++ "/?")
return $ T.cons '?' (T.concat ss)
-- RFC3986, section 3.5
ufragment :: URIParser Text
ufragment = do
ss <- many $ uchar (":@" ++ "/?")
return $ T.cons '#' (T.concat ss)
-- Reference, Relative and Absolute URI forms
--
-- RFC3986, section 4.1
uriReference :: URIParser URI
uriReference = uri <|> relativeRef
-- RFC3986, section 4.2
--
-- relative-URI = relative-part [ "?" query ] [ "#" fragment ]
--
-- relative-part = "//" authority path-abempty
-- / path-abs
-- / path-noscheme
-- / path-empty
relativeRef :: URIParser URI
relativeRef = do
notMatching uscheme
(ua,up) <- relativePart
uq <- option "" ( char '?' >> uquery )
uf <- option "" ( char '#' >> ufragment )
return $ URI
{ uriScheme = T.empty
, uriAuthority = ua
, uriPath = up
, uriQuery = uq
, uriFragment = uf
}
relativePart :: URIParser ((Maybe URIAuth), Text)
relativePart = withAuthority
<|> (Nothing, ) <$> pathAbs
<|> (Nothing, ) <$> pathNoScheme
<|> return (Nothing, "")
where withAuthority = do
_ <- try (string "//")
ua <- uauthority
up <- pathAbEmpty
return (ua, up)
-- RFC3986, section 4.3
absoluteURI :: URIParser URI
absoluteURI = do
us <- uscheme
(ua, up) <- hierPart
uq <- option "" ( char '?' >> uquery )
return $ URI
{ uriScheme = us
, uriAuthority = ua
, uriPath = up
, uriQuery = uq
, uriFragment = T.empty
}
-- Imports from RFC 2234
-- NOTE: can't use isAlphaNum etc. because these deal with ISO 8859
-- (and possibly Unicode!) chars.
-- [[[Above was a comment originally in GHC Network/URI.hs:
-- when IRIs are introduced then most codepoints above 128(?) should
-- be treated as unreserved, and higher codepoints for letters should
-- certainly be allowed.
-- ]]]
isAlphaChar :: Char -> Bool
isAlphaChar c = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
isDigitChar :: Char -> Bool
isDigitChar c = (c >= '0' && c <= '9')
isAlphaNumChar :: Char -> Bool
isAlphaNumChar c = isAlphaChar c || isDigitChar c
isHexDigitChar :: Char -> Bool
isHexDigitChar c = isHexDigit c
isSchemeChar :: Char -> Bool
isSchemeChar c = (isAlphaNumChar c) || (c `telem` "+-.")
alphaChar :: URIParser Text
alphaChar = T.singleton <$> satisfy isAlphaChar
digitChar :: URIParser Text
digitChar = T.singleton <$> satisfy isDigitChar
hexDigitChar :: URIParser Text
hexDigitChar = T.singleton <$> satisfy isHexDigitChar
schemeChar :: URIParser Text
schemeChar = T.singleton <$> satisfy isSchemeChar
-- Additional parser combinators for common patterns
oneThenMany :: GenParser t Text -> GenParser t Text -> GenParser t Text
oneThenMany p1 pr = do
a1 <- p1
ar <- many pr
return $ T.append a1 (T.concat ar)
countMinMax :: Int -> Int -> GenParser t Text -> GenParser t Text
countMinMax m n parser | m > 0 = do
a1 <- parser
ar <- countMinMax (m - 1) (n - 1) parser
return (T.append a1 ar)
countMinMax _ n _ | n <= 0 = return T.empty
countMinMax _ n parser = option T.empty $ do
a1 <- parser
ar <- countMinMax 0 (n-1) parser
return (T.append a1 ar)
notMatching :: Show a => GenParser tok a -> GenParser tok ()
notMatching p = do { a <- try p ; unexpected (show a) } <|> return ()
------------------------------------------------------------
-- Reconstruct a URI string
------------------------------------------------------------
--
-- |Turn a 'URI' into a string.
--
-- Uses a supplied function to map the userinfo part of the URI.
--
-- The Show instance for URI uses a mapping that hides any password
-- that may be present in the URI. Use this function with argument @id@
-- to preserve the password in the formatted output.
--
uriToString :: (Text->Text) -> URI -> ShowS
uriToString userinfomap URI { uriScheme=scheme
, uriAuthority=authority
, uriPath=path
, uriQuery=query
, uriFragment=fragment
} = (T.unpack scheme ++)
. uriAuthToString userinfomap authority
. (T.unpack path ++)
. (T.unpack query ++)
. (T.unpack fragment ++)
uriAuthToString :: (Text->Text) -> (Maybe URIAuth) -> ShowS
uriAuthToString _ Nothing = id -- shows ""
uriAuthToString userinfomap
(Just URIAuth { uriUserInfo = uinfo
, uriRegName = regname
, uriPort = portNumber
} ) = ("//" ++)
. (if T.null uinfo
then id
else ((T.unpack $ userinfomap uinfo)++)
)
. (T.unpack regname ++)
. (T.unpack portNumber ++)
------------------------------------------------------------
-- Character classes
------------------------------------------------------------
-- | Returns 'True' if the character is allowed in a URI.
--
isAllowedInURI :: Char -> Bool
isAllowedInURI c = isReserved c || isUnreserved c || c == '%' -- escape char
-- | Returns 'True' if the character is allowed unescaped in a URI.
--
isUnescapedInURI :: Char -> Bool
isUnescapedInURI c = isReserved c || isUnreserved c
------------------------------------------------------------
-- Escape sequence handling
------------------------------------------------------------
-- |Escape character if supplied predicate is not satisfied,
-- otherwise return character as singleton string.
--
escapeURIChar :: (Char -> Bool) -> Char -> Text
escapeURIChar p c
| p c = T.singleton c
| otherwise = T.cons '%' (T.pack (myShowHex (ord c) ""))
where
myShowHex :: Int -> ShowS
myShowHex n r = case showIntAtBase 16 (toChrHex) n r of
[] -> "00"
[aDigit] -> ['0', aDigit]
digits -> digits
toChrHex d
| d < 10 = chr (ord '0' + fromIntegral d)
| otherwise = chr (ord 'A' + fromIntegral (d - 10))
-- |Can be used to make a string valid for use in a URI.
--
escapeURIString
:: (Char->Bool) -- ^ a predicate which returns 'False'
-- if the character should be escaped
-> Text -- ^ the string to process
-> Text -- ^ the resulting URI string
escapeURIString p s = T.concatMap (escapeURIChar p) s
-- |Turns all instances of escaped characters in the string back
-- into literal characters.
--
infixr 5 :<
pattern b :< bs <- (T.uncons -> Just (b, bs))
pattern Empty <- (T.uncons -> Nothing)
unEscapeString :: Text -> Text
unEscapeString Empty = T.empty
unEscapeString ('%' :< x1 :< x2 :< s) | isHexDigit x1 && isHexDigit x2 =
T.cons (chr (digitToInt x1 * 16 + digitToInt x2))
(unEscapeString s)
unEscapeString (c :< s) = T.cons c (unEscapeString s)
unEscapeString _ = T.empty
------------------------------------------------------------
-- Resolving a relative URI relative to a base URI
------------------------------------------------------------
-- |Returns a new 'URI' which represents the value of the
-- first 'URI' interpreted as relative to the second 'URI'.
-- For example:
--
-- > "foo" `relativeTo` "http://bar.org/" = "http://bar.org/foo"
-- > "http:foo" `nonStrictRelativeTo` "http://bar.org/" = "http://bar.org/foo"
--
-- Algorithm from RFC3986 [3], section 5.2.2
--
nonStrictRelativeTo :: URI -> URI -> Maybe URI
nonStrictRelativeTo ref base = relativeTo ref' base
where
ref' = if uriScheme ref == uriScheme base
then ref { uriScheme="" }
else ref
mergePaths :: [Text] -> Text
mergePaths [] = T.empty
mergePaths [a] = T.dropWhile (== '/') a
mergePaths (a:b:cs) = T.concat
[ T.dropWhileEnd (== '/') a
, "/"
, mergePaths (b:cs)
]
-- |Compute an absolute 'URI' for a supplied URI
-- relative to a given base.
relativeTo :: URI -> URI -> Maybe URI
relativeTo ref base
| uriScheme ref /= "" =
just_segments ref
| uriAuthority ref /= Nothing =
just_segments ref { uriScheme = uriScheme base }
| uriPath ref /= "" =
if (T.head (uriPath ref) == '/') then
just_segments ref
{ uriScheme = uriScheme base
, uriAuthority = uriAuthority base
}
else
just_segments ref
{ uriScheme = uriScheme base
, uriAuthority = uriAuthority base
, uriPath = mergeURIsToPath base ref
}
| uriQuery ref /= "" =
just_segments ref
{ uriScheme = uriScheme base
, uriAuthority = uriAuthority base
, uriPath = uriPath base
}
| otherwise =
just_segments ref
{ uriScheme = uriScheme base
, uriAuthority = uriAuthority base
, uriPath = uriPath base
, uriQuery = uriQuery base
}
where
just_segments u = Just $ u { uriPath = removeDotSegments (uriPath u) }
mergeURIsToPath b r
| uriAuthority b /= Nothing && T.null pb = mergePaths ["", pr]
| otherwise = mergePaths [pb, pr]
where
(pb, pr) = (uriPath b, uriPath r)
-- Remove dot segments, but protect leading '/' character
removeDotSegments :: Text -> Text
removeDotSegments ('/' :< ps) = T.cons '/' (elimDots ps [])
removeDotSegments ps = elimDots ps []
-- Second arg accumulates segments processed so far in reverse order
elimDots :: Text -> [Text] -> Text
elimDots Empty [] = ""
elimDots Empty rs = T.concat (reverse rs)
elimDots ('.' :< '/' :< ps) rs = elimDots ps rs
elimDots ('.' :< Empty) rs = elimDots T.empty rs
elimDots ('.' :< '.' :< '/' :< ps) rs = elimDots ps (dropHead rs)
elimDots ('.' :< '.' :< Empty) rs = elimDots T.empty (dropHead rs)
elimDots ps rs = elimDots ps1 (r:rs)
where
(r,ps1) = nextSegment ps
-- Return tail of non-null list, otherwise return null list
dropHead :: [a] -> [a]
dropHead [] = []
dropHead (_:rs) = rs
-- Returns the next segment and the rest of the path from a path string.
-- Each segment ends with the next '/' or the end of string.
--
nextSegment :: Text -> (Text, Text)
nextSegment ps =
case T.breakOn "/" ps of
(r, '/' :< ps1) -> (T.snoc r '/', ps1)
(r, _) -> (r, T.empty)
-- Split last (name) segment from path, returning (path,name)
splitLast :: Text -> (Text, Text)
splitLast = T.breakOnEnd "/"
------------------------------------------------------------
-- Finding a URI relative to a base URI
------------------------------------------------------------
-- |Returns a new 'URI' which represents the relative location of
-- the first 'URI' with respect to the second 'URI'. Thus, the
-- values supplied are expected to be absolute URIs, and the result
-- returned may be a relative URI.
--
-- Example:
--
-- > "http://example.com/Root/sub1/name2#frag"
-- > `relativeFrom` "http://example.com/Root/sub2/name2#frag"
-- > == "../sub1/name2#frag"
--
-- There is no single correct implementation of this function,
-- but any acceptable implementation must satisfy the following:
--
-- > (uabs `relativeFrom` ubase) `relativeTo` ubase == uabs
--
-- For any valid absolute URI.
-- (cf. <http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html>
-- <http://lists.w3.org/Archives/Public/uri/2003Jan/0005.html>)
--
relativeFrom :: URI -> URI -> URI
relativeFrom uabs base
| diff uriScheme uabs base = uabs
| diff uriAuthority uabs base = uabs { uriScheme = "" }
| diff uriPath uabs base = uabs
{ uriScheme = T.empty
, uriAuthority = Nothing
, uriPath = relPathFrom (removeBodyDotSegments $ uriPath uabs)
(removeBodyDotSegments $ uriPath base)
}
| diff uriQuery uabs base = uabs
{ uriScheme = T.empty
, uriAuthority = Nothing
, uriPath = T.empty
}
| otherwise = uabs -- Always carry fragment from uabs
{ uriScheme = T.empty
, uriAuthority = Nothing
, uriPath = T.empty
, uriQuery = T.empty
}
where
diff :: Eq b => (a -> b) -> a -> a -> Bool
diff sel u1 u2 = sel u1 /= sel u2
-- Remove dot segments except the final segment
removeBodyDotSegments p = T.append (removeDotSegments p1) p2
where (p1,p2) = splitLast p
relPathFrom :: Text -> Text -> Text
relPathFrom Empty _ = "/"
relPathFrom pabs Empty = pabs
relPathFrom pabs base = -- Construct a relative path segments
if sa1 == sb1 -- if the paths share a leading segment
then if (sa1 == "/") -- other than a leading '/'
then if (sa2 == sb2)
then relPathFrom1 ra2 rb2
else pabs
else relPathFrom1 ra1 rb1
else pabs
where
(sa1, ra1) = nextSegment pabs
(sb1, rb1) = nextSegment base
(sa2, ra2) = nextSegment ra1
(sb2, rb2) = nextSegment rb1
-- relPathFrom1 strips off trailing names from the supplied paths,
-- and calls difPathFrom to find the relative path from base to
-- target
relPathFrom1 :: Text -> Text -> Text
relPathFrom1 pabs base = relName
where
(sa, na) = splitLast pabs
(sb, nb) = splitLast base
rp = relSegsFrom sa sb
relName = if T.null rp then
if (na == nb) then ""
else if protect na then T.append "./" na
else na
else
T.append rp na
-- Precede name with some path if it is null or contains a ':'
protect name = T.null name || T.findIndex (== ':') name /= Nothing
-- relSegsFrom discards any common leading segments from both paths,
-- then invokes difSegsFrom to calculate a relative path from the end
-- of the base path to the end of the target path.
-- The final name is handled separately, so this deals only with
-- "directory" segtments.
--
relSegsFrom :: Text -> Text -> Text
relSegsFrom Empty Empty = "" -- paths are identical
relSegsFrom sabs base =
if sa1 == sb1
then relSegsFrom ra1 rb1
else difSegsFrom sabs base
where
(sa1,ra1) = nextSegment sabs
(sb1,rb1) = nextSegment base
-- difSegsFrom calculates a path difference from base to target,
-- not including the final name at the end of the path
-- (i.e. results always ends with '/')
--
-- This function operates under the invariant that the supplied
-- value of sabs is the desired path relative to the beginning of
-- base. Thus, when base is empty, the desired path has been found.
--
difSegsFrom :: Text -> Text -> Text
difSegsFrom sabs Empty = sabs
difSegsFrom sabs base = difSegsFrom (T.append "../" sabs)
(snd $ nextSegment base)
------------------------------------------------------------
-- Other normalization functions
------------------------------------------------------------
-- |Case normalization; cf. RFC3986 section 6.2.2.1
-- NOTE: authority case normalization is not performed
--
normalizeCase :: Text -> Text
normalizeCase uristr = ncScheme uristr
where
ncScheme (':' :< cs) = T.cons ':' (ncEscape cs)
ncScheme (c :< cs) | isSchemeChar c = T.cons (toLower c) (ncScheme cs)
ncScheme _ = ncEscape uristr -- no scheme present
ncEscape ('%' :< h1 :< h2 :< cs) = T.concat [ "%"
, T.singleton $ toUpper h1
, T.singleton $ toUpper h2
, ncEscape cs
]
ncEscape (c :< cs) = T.cons c (ncEscape cs)
ncEscape _ = T.empty
-- |Encoding normalization; cf. RFC3986 section 6.2.2.2
--
normalizeEscape :: Text -> Text
normalizeEscape ('%' :< h1 :< h2 :< cs)
| isHexDigit h1 && isHexDigit h2 && isUnreserved escval =
T.cons escval (normalizeEscape cs)
where escval = chr (digitToInt h1 * 16 + digitToInt h2)
normalizeEscape (c :< cs) = T.cons c (normalizeEscape cs)
normalizeEscape _ = T.empty
-- |Path segment normalization; cf. RFC3986 section 6.2.2.4
--
normalizePathSegments :: Text -> Text
normalizePathSegments uristr = normstr juri
where
juri = parseURI uristr
normstr Nothing = uristr
normstr (Just u) = T.pack $ show (normuri u)
normuri u = u { uriPath = removeDotSegments (uriPath u) }
--------------------------------------------------------------------------------
--
-- Copyright (c) 2004, G. KLYNE. All rights reserved.
-- Distributed as free software under the following license.
--
-- 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 name of the copyright holders 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 THE 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
-- HOLDERS OR THE 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.
--
--------------------------------------------------------------------------------
| Zigazou/deadlink | src/Network/URI/Text.hs | gpl-3.0 | 37,321 | 0 | 14 | 10,379 | 7,550 | 4,029 | 3,521 | 586 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidPublisher.Edits.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new edit for an app.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Android Developer API Reference> for @androidpublisher.edits.insert@.
module Network.Google.Resource.AndroidPublisher.Edits.Insert
(
-- * REST Resource
EditsInsertResource
-- * Creating a Request
, editsInsert
, EditsInsert
-- * Request Lenses
, eiXgafv
, eiUploadProtocol
, eiPackageName
, eiAccessToken
, eiUploadType
, eiPayload
, eiCallback
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.edits.insert@ method which the
-- 'EditsInsert' request conforms to.
type EditsInsertResource =
"androidpublisher" :>
"v3" :>
"applications" :>
Capture "packageName" Text :>
"edits" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AppEdit :> Post '[JSON] AppEdit
-- | Creates a new edit for an app.
--
-- /See:/ 'editsInsert' smart constructor.
data EditsInsert =
EditsInsert'
{ _eiXgafv :: !(Maybe Xgafv)
, _eiUploadProtocol :: !(Maybe Text)
, _eiPackageName :: !Text
, _eiAccessToken :: !(Maybe Text)
, _eiUploadType :: !(Maybe Text)
, _eiPayload :: !AppEdit
, _eiCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EditsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eiXgafv'
--
-- * 'eiUploadProtocol'
--
-- * 'eiPackageName'
--
-- * 'eiAccessToken'
--
-- * 'eiUploadType'
--
-- * 'eiPayload'
--
-- * 'eiCallback'
editsInsert
:: Text -- ^ 'eiPackageName'
-> AppEdit -- ^ 'eiPayload'
-> EditsInsert
editsInsert pEiPackageName_ pEiPayload_ =
EditsInsert'
{ _eiXgafv = Nothing
, _eiUploadProtocol = Nothing
, _eiPackageName = pEiPackageName_
, _eiAccessToken = Nothing
, _eiUploadType = Nothing
, _eiPayload = pEiPayload_
, _eiCallback = Nothing
}
-- | V1 error format.
eiXgafv :: Lens' EditsInsert (Maybe Xgafv)
eiXgafv = lens _eiXgafv (\ s a -> s{_eiXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
eiUploadProtocol :: Lens' EditsInsert (Maybe Text)
eiUploadProtocol
= lens _eiUploadProtocol
(\ s a -> s{_eiUploadProtocol = a})
-- | Package name of the app.
eiPackageName :: Lens' EditsInsert Text
eiPackageName
= lens _eiPackageName
(\ s a -> s{_eiPackageName = a})
-- | OAuth access token.
eiAccessToken :: Lens' EditsInsert (Maybe Text)
eiAccessToken
= lens _eiAccessToken
(\ s a -> s{_eiAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
eiUploadType :: Lens' EditsInsert (Maybe Text)
eiUploadType
= lens _eiUploadType (\ s a -> s{_eiUploadType = a})
-- | Multipart request metadata.
eiPayload :: Lens' EditsInsert AppEdit
eiPayload
= lens _eiPayload (\ s a -> s{_eiPayload = a})
-- | JSONP
eiCallback :: Lens' EditsInsert (Maybe Text)
eiCallback
= lens _eiCallback (\ s a -> s{_eiCallback = a})
instance GoogleRequest EditsInsert where
type Rs EditsInsert = AppEdit
type Scopes EditsInsert =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient EditsInsert'{..}
= go _eiPackageName _eiXgafv _eiUploadProtocol
_eiAccessToken
_eiUploadType
_eiCallback
(Just AltJSON)
_eiPayload
androidPublisherService
where go
= buildClient (Proxy :: Proxy EditsInsertResource)
mempty
| brendanhay/gogol | gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/Insert.hs | mpl-2.0 | 4,773 | 0 | 19 | 1,188 | 786 | 457 | 329 | 114 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Content.Accounts.AuthInfo
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns information about the authenticated user.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.accounts.authinfo@.
module Network.Google.Resource.Content.Accounts.AuthInfo
(
-- * REST Resource
AccountsAuthInfoResource
-- * Creating a Request
, accountsAuthInfo
, AccountsAuthInfo
-- * Request Lenses
, aaiXgafv
, aaiUploadProtocol
, aaiAccessToken
, aaiUploadType
, aaiCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.accounts.authinfo@ method which the
-- 'AccountsAuthInfo' request conforms to.
type AccountsAuthInfoResource =
"content" :>
"v2.1" :>
"accounts" :>
"authinfo" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] AccountsAuthInfoResponse
-- | Returns information about the authenticated user.
--
-- /See:/ 'accountsAuthInfo' smart constructor.
data AccountsAuthInfo =
AccountsAuthInfo'
{ _aaiXgafv :: !(Maybe Xgafv)
, _aaiUploadProtocol :: !(Maybe Text)
, _aaiAccessToken :: !(Maybe Text)
, _aaiUploadType :: !(Maybe Text)
, _aaiCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsAuthInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aaiXgafv'
--
-- * 'aaiUploadProtocol'
--
-- * 'aaiAccessToken'
--
-- * 'aaiUploadType'
--
-- * 'aaiCallback'
accountsAuthInfo
:: AccountsAuthInfo
accountsAuthInfo =
AccountsAuthInfo'
{ _aaiXgafv = Nothing
, _aaiUploadProtocol = Nothing
, _aaiAccessToken = Nothing
, _aaiUploadType = Nothing
, _aaiCallback = Nothing
}
-- | V1 error format.
aaiXgafv :: Lens' AccountsAuthInfo (Maybe Xgafv)
aaiXgafv = lens _aaiXgafv (\ s a -> s{_aaiXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aaiUploadProtocol :: Lens' AccountsAuthInfo (Maybe Text)
aaiUploadProtocol
= lens _aaiUploadProtocol
(\ s a -> s{_aaiUploadProtocol = a})
-- | OAuth access token.
aaiAccessToken :: Lens' AccountsAuthInfo (Maybe Text)
aaiAccessToken
= lens _aaiAccessToken
(\ s a -> s{_aaiAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aaiUploadType :: Lens' AccountsAuthInfo (Maybe Text)
aaiUploadType
= lens _aaiUploadType
(\ s a -> s{_aaiUploadType = a})
-- | JSONP
aaiCallback :: Lens' AccountsAuthInfo (Maybe Text)
aaiCallback
= lens _aaiCallback (\ s a -> s{_aaiCallback = a})
instance GoogleRequest AccountsAuthInfo where
type Rs AccountsAuthInfo = AccountsAuthInfoResponse
type Scopes AccountsAuthInfo =
'["https://www.googleapis.com/auth/content"]
requestClient AccountsAuthInfo'{..}
= go _aaiXgafv _aaiUploadProtocol _aaiAccessToken
_aaiUploadType
_aaiCallback
(Just AltJSON)
shoppingContentService
where go
= buildClient
(Proxy :: Proxy AccountsAuthInfoResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Accounts/AuthInfo.hs | mpl-2.0 | 4,271 | 0 | 17 | 1,020 | 630 | 368 | 262 | 94 | 1 |
module ProjectM36.TypeConstructorDef where
import ProjectM36.Base
name :: TypeConstructorDef -> TypeConstructorName
name (ADTypeConstructorDef nam _) = nam
name (PrimitiveTypeConstructorDef nam _) = nam
typeVars :: TypeConstructorDef -> [TypeVarName]
typeVars (PrimitiveTypeConstructorDef _ _) = []
typeVars (ADTypeConstructorDef _ args) = args
| agentm/project-m36 | src/lib/ProjectM36/TypeConstructorDef.hs | unlicense | 372 | 0 | 7 | 66 | 98 | 52 | 46 | 8 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Brainfuck.Cell
( Cell
, Math (..)
, stepCell
) where
import ClassyPrelude
import Data.Monoid (Sum)
type Cell = Sum Word8
data Math = Inc | Dec
deriving Show
stepCell :: Math -> (Cell -> Cell)
stepCell Inc = fmap $ \case
255 -> 0
s -> s + 1
stepCell Dec = fmap $ \case
0 -> 255
s -> s - 1
| expede/brainfucker | src/Brainfuck/Cell.hs | apache-2.0 | 412 | 0 | 9 | 126 | 134 | 76 | 58 | 18 | 3 |
cnt' n ('O':'I':xs) = cnt' (n+1) xs
cnt' n x = n
cnt [] = []
cnt ('I':xs) =
let n = cnt' 0 xs
r = drop (2*n) xs
in
n:(cnt r)
cnt ('O':xs) = cnt xs
ans ("0":_) = []
ans (n:_:s:xs) =
let n' = read n :: Int
r = cnt s
a = sum $ map (\x -> if x >= n' then (x-n'+1) else 0) r
in
a:(ans xs)
main = do
c <- getContents
let i = lines c
o = ans i
mapM_ print o
| a143753/AOJ | 0538.hs | apache-2.0 | 405 | 0 | 16 | 147 | 292 | 147 | 145 | 19 | 2 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Messages.Type (Type(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Type = GET
| PUT
| REMOVE
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable Type
instance Prelude'.Bounded Type where
minBound = GET
maxBound = REMOVE
instance P'.Default Type where
defaultValue = GET
toMaybe'Enum :: Prelude'.Int -> P'.Maybe Type
toMaybe'Enum 1 = Prelude'.Just GET
toMaybe'Enum 2 = Prelude'.Just PUT
toMaybe'Enum 3 = Prelude'.Just REMOVE
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum Type where
fromEnum GET = 1
fromEnum PUT = 2
fromEnum REMOVE = 3
toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Messages.Type") . toMaybe'Enum
succ GET = PUT
succ PUT = REMOVE
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Messages.Type"
pred PUT = GET
pred REMOVE = PUT
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Messages.Type"
instance P'.Wire Type where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB Type
instance P'.MessageAPI msg' (msg' -> Type) Type where
getVal m' f' = f' m'
instance P'.ReflectEnum Type where
reflectEnum = [(1, "GET", GET), (2, "PUT", PUT), (3, "REMOVE", REMOVE)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".messages.Type") [] ["Messages"] "Type") ["Messages", "Type.hs"]
[(1, "GET"), (2, "PUT"), (3, "REMOVE")]
instance P'.TextType Type where
tellT = P'.tellShow
getT = P'.getRead | JDrit/MemDB | client.hs/src/Messages/Type.hs | apache-2.0 | 2,139 | 0 | 11 | 378 | 650 | 352 | 298 | 52 | 1 |
module Tables.A268057Spec (main, spec) where
import Test.Hspec
import Tables.A268057 (a268057)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A268057" $
it "correctly computes the first 20 elements" $
take 20 (map a268057 [1..]) `shouldBe` expectedValue where
expectedValue = [1,1,1,1,2,1,1,1,2,1,1,2,3,2,1,1,1,1,2,2]
| peterokagey/haskellOEIS | test/Tables/A268057Spec.hs | apache-2.0 | 347 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QResizeEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QResizeEvent (
QqqResizeEvent(..), QqResizeEvent(..)
,QqqResizeEvent_nf(..), QqResizeEvent_nf(..)
,qoldSize, oldSize
,qResizeEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqqResizeEvent x1 where
qqResizeEvent :: x1 -> IO (QResizeEvent ())
class QqResizeEvent x1 where
qResizeEvent :: x1 -> IO (QResizeEvent ())
instance QqResizeEvent ((QResizeEvent t1)) where
qResizeEvent (x1)
= withQResizeEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QResizeEvent cobj_x1
foreign import ccall "qtc_QResizeEvent" qtc_QResizeEvent :: Ptr (TQResizeEvent t1) -> IO (Ptr (TQResizeEvent ()))
instance QqqResizeEvent ((QSize t1, QSize t2)) where
qqResizeEvent (x1, x2)
= withQResizeEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QResizeEvent1 cobj_x1 cobj_x2
foreign import ccall "qtc_QResizeEvent1" qtc_QResizeEvent1 :: Ptr (TQSize t1) -> Ptr (TQSize t2) -> IO (Ptr (TQResizeEvent ()))
instance QqResizeEvent ((Size, Size)) where
qResizeEvent (x1, x2)
= withQResizeEventResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
withCSize x2 $ \csize_x2_w csize_x2_h ->
qtc_QResizeEvent2 csize_x1_w csize_x1_h csize_x2_w csize_x2_h
foreign import ccall "qtc_QResizeEvent2" qtc_QResizeEvent2 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQResizeEvent ()))
class QqqResizeEvent_nf x1 where
qqResizeEvent_nf :: x1 -> IO (QResizeEvent ())
class QqResizeEvent_nf x1 where
qResizeEvent_nf :: x1 -> IO (QResizeEvent ())
instance QqResizeEvent_nf ((QResizeEvent t1)) where
qResizeEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QResizeEvent cobj_x1
instance QqqResizeEvent_nf ((QSize t1, QSize t2)) where
qqResizeEvent_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QResizeEvent1 cobj_x1 cobj_x2
instance QqResizeEvent_nf ((Size, Size)) where
qResizeEvent_nf (x1, x2)
= withObjectRefResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
withCSize x2 $ \csize_x2_w csize_x2_h ->
qtc_QResizeEvent2 csize_x1_w csize_x1_h csize_x2_w csize_x2_h
qoldSize :: QResizeEvent a -> (()) -> IO (QSize ())
qoldSize x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_oldSize cobj_x0
foreign import ccall "qtc_QResizeEvent_oldSize" qtc_QResizeEvent_oldSize :: Ptr (TQResizeEvent a) -> IO (Ptr (TQSize ()))
oldSize :: QResizeEvent a -> (()) -> IO (Size)
oldSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_oldSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QResizeEvent_oldSize_qth" qtc_QResizeEvent_oldSize_qth :: Ptr (TQResizeEvent a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqqsize (QResizeEvent a) (()) (IO (QSize ())) where
qqsize x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_size cobj_x0
foreign import ccall "qtc_QResizeEvent_size" qtc_QResizeEvent_size :: Ptr (TQResizeEvent a) -> IO (Ptr (TQSize ()))
instance Qqsize (QResizeEvent a) (()) (IO (Size)) where
qsize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_size_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QResizeEvent_size_qth" qtc_QResizeEvent_size_qth :: Ptr (TQResizeEvent a) -> Ptr CInt -> Ptr CInt -> IO ()
qResizeEvent_delete :: QResizeEvent a -> IO ()
qResizeEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QResizeEvent_delete cobj_x0
foreign import ccall "qtc_QResizeEvent_delete" qtc_QResizeEvent_delete :: Ptr (TQResizeEvent a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QResizeEvent.hs | bsd-2-clause | 4,324 | 0 | 15 | 717 | 1,262 | 655 | 607 | -1 | -1 |
{-| Implementation of the Ganeti Query2 export queries.
-}
{-
Copyright (C) 2013 Google Inc.
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.
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 Ganeti.Query.Export
( Runtime
, fieldsMap
, collectLiveData
) where
import Control.Monad (liftM)
import qualified Data.Map as Map
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Query.Language
import Ganeti.Query.Common
import Ganeti.Query.Types
-- | The parsed result of the ExportList. This is a bit tricky, in
-- that we already do parsing of the results in the RPC calls, so the
-- runtime type is a plain 'ResultEntry', as we have just one type.
type Runtime = ResultEntry
-- | Small helper for rpc to rs.
rpcErrToRs :: RpcError -> ResultEntry
rpcErrToRs err = ResultEntry (rpcErrorToStatus err) Nothing
-- | Helper for extracting fields from RPC result.
rpcExtractor :: Node -> Either RpcError RpcResultExportList
-> [(Node, ResultEntry)]
rpcExtractor node (Right res) =
[(node, rsNormal path) | path <- rpcResExportListExports res]
rpcExtractor node (Left err) = [(node, rpcErrToRs err)]
-- | List of all node fields.
exportFields :: FieldList Node Runtime
exportFields =
[ (FieldDefinition "node" "Node" QFTText "Node name",
FieldRuntime (\_ n -> rsNormal $ nodeName n), QffHostname)
, (FieldDefinition "export" "Export" QFTText "Export name",
FieldRuntime (curry fst), QffNormal)
]
-- | The node fields map.
fieldsMap :: FieldMap Node Runtime
fieldsMap =
Map.fromList $ map (\v@(f, _, _) -> (fdefName f, v)) exportFields
-- | Collect live data from RPC query if enabled.
--
-- Note that this function is \"funny\": the returned rows will not be
-- 1:1 with the input, as nodes without exports will be pruned,
-- whereas nodes with multiple exports will be listed multiple times.
collectLiveData:: Bool -> ConfigData -> [Node] -> IO [(Node, Runtime)]
collectLiveData False _ nodes =
return [(n, rpcErrToRs $ RpcResultError "Live data disabled") | n <- nodes]
collectLiveData True _ nodes =
concatMap (uncurry rpcExtractor) `liftM`
executeRpcCall nodes RpcCallExportList
| apyrgio/snf-ganeti | src/Ganeti/Query/Export.hs | bsd-2-clause | 3,309 | 0 | 11 | 558 | 450 | 255 | 195 | 34 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
-- | A module collecting the toy grammars used for testing and
-- unit test examples themselves.
module NLP.TAG.Vanilla.Tests
( Test (..)
, TestRes (..)
, mkGram1
, gram1Tests
, mkGram2
, gram2Tests
, mkGram3
, gram3Tests
, mkGram4
, gram4Tests
-- Temporary
, mkGram5
, mkGramAcidRains
, mkGramSetPoints
, Gram
, WeightedGram
, testTree
) where
import Control.Applicative ((<$>), (<*>))
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Test.Tasty (TestTree, testGroup, withResource)
import Test.HUnit (Assertion, (@?=))
import Test.Tasty.HUnit (testCase)
import NLP.TAG.Vanilla.Core (Cost)
import NLP.TAG.Vanilla.Tree (Tree (..), AuxTree (..))
import NLP.TAG.Vanilla.Rule (Rule)
import qualified NLP.TAG.Vanilla.Rule as R
import qualified NLP.TAG.Vanilla.WRule as W
import NLP.TAG.Vanilla.SubtreeSharing (compile)
---------------------------------------------------------------------
-- Prerequisites
---------------------------------------------------------------------
type Tr = Tree String String
type AuxTr = AuxTree String String
type Rl = Rule String String
type WRl = W.Rule String String
-- | A compiled grammar.
type Gram = S.Set Rl
-- | A compiled grammar with weights.
type WeightedTree = (Tr, Cost)
type WeightedAux = (AuxTr, Cost)
type WeightedGram = S.Set WRl
---------------------------------------------------------------------
-- Tests
---------------------------------------------------------------------
-- | A single test case.
data Test = Test {
-- | Starting symbol
startSym :: String
-- | The sentence to parse (list of words)
, testSent :: [String]
-- | The expected recognition result
, testRes :: TestRes
} deriving (Show, Eq, Ord)
-- | The expected test result. The set of parsed trees can be optionally
-- specified.
data TestRes
= No
-- ^ No parse
| Yes
-- ^ Parse
| Trees (S.Set Tr)
-- ^ Parsing results
| WeightedTrees (M.Map Tr Cost)
-- ^ Parsing results with weights
deriving (Show, Eq, Ord)
---------------------------------------------------------------------
-- Grammar1
---------------------------------------------------------------------
tom :: Tr
tom = INode "NP"
[ INode "N"
[FNode "Tom"]
]
sleeps :: Tr
sleeps = INode "S"
[ INode "NP" []
, INode "VP"
[INode "V" [FNode "sleeps"]]
]
caught :: Tr
caught = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V" [FNode "caught"]
, INode "NP" [] ]
]
almost :: AuxTr
almost = AuxTree (INode "V"
[ INode "Ad" [FNode "almost"]
, INode "V" []
]) [1]
quickly :: AuxTr
quickly = AuxTree (INode "V"
[ INode "Ad" [FNode "quickly"]
, INode "V" []
]) [1]
a :: Tr
a = INode "D" [FNode "a"]
mouse :: Tr
mouse = INode "NP"
[ INode "D" []
, INode "N"
[FNode "mouse"]
]
-- | Compile the first grammar.
mkGram1 :: IO Gram
mkGram1 = compile $
map Left [tom, sleeps, caught, a, mouse] ++
map Right [almost, quickly]
---------------------------------------------------------------------
-- Grammar1 Tests
---------------------------------------------------------------------
gram1Tests :: [Test]
gram1Tests =
-- group 1
[ Test "S" ["Tom", "sleeps"] . Trees . S.singleton $
INode "S"
[ INode "NP"
[ INode "N"
[FNode "Tom"]
]
, INode "VP"
[INode "V" [FNode "sleeps"]]
]
, Test "S" ["Tom"] No
, Test "NP" ["Tom"] Yes
-- group 2
, Test "S" ["Tom", "almost", "caught", "a", "mouse"] . Trees . S.singleton $
INode "S"
[ INode "NP"
[ INode "N"
[ FNode "Tom" ] ]
, INode "VP"
[ INode "V"
[ INode "Ad"
[FNode "almost"]
, INode "V"
[FNode "caught"]
]
, INode "NP"
[ INode "D"
[FNode "a"]
, INode "N"
[FNode "mouse"]
]
]
]
, Test "S" ["Tom", "caught", "almost", "a", "mouse"] No
, Test "S" ["Tom", "quickly", "almost", "caught", "Tom"] Yes
, Test "S" ["Tom", "caught", "a", "mouse"] Yes
, Test "S" ["Tom", "caught", "Tom"] Yes
, Test "S" ["Tom", "caught", "a", "Tom"] No
, Test "S" ["Tom", "caught"] No
, Test "S" ["caught", "a", "mouse"] No ]
---------------------------------------------------------------------
-- Grammar2
---------------------------------------------------------------------
alpha :: Tr
alpha = INode "S"
[ INode "X"
[FNode "e"] ]
beta1 :: AuxTr
beta1 = AuxTree (INode "X"
[ FNode "a"
, INode "X"
[ INode "X" []
, FNode "a" ] ]
) [1,0]
beta2 :: AuxTr
beta2 = AuxTree (INode "X"
[ FNode "b"
, INode "X"
[ INode "X" []
, FNode "b" ] ]
) [1,0]
mkGram2 :: IO Gram
mkGram2 = compile $
map Left [alpha] ++
map Right [beta1, beta2]
---------------------------------------------------------------------
-- Grammar2 Tests
---------------------------------------------------------------------
-- | What we test is not really a copy language but rather a
-- language in which there is always the same number of `a`s and
-- `b`s on the left and on the right of the empty `e` symbol.
-- To model the real copy language with a TAG we would need to
-- use either adjunction constraints or feature structures.
gram2Tests :: [Test]
gram2Tests =
[ Test "S" (words "a b e a b") Yes
, Test "S" (words "a b e a a") No
, Test "S" (words "a b a b a b a b e a b a b a b a b") Yes
, Test "S" (words "a b a b a b a b e a b a b a b a ") No
, Test "S" (words "a b e b a") Yes
, Test "S" (words "b e a") No
, Test "S" (words "a b a b") No ]
---------------------------------------------------------------------
-- Grammar 3
---------------------------------------------------------------------
mkGram3 :: IO Gram
mkGram3 = compile $
map Left [sent] ++
map Right [xtree]
where
sent = INode "S"
[ FNode "p"
, INode "X"
[FNode "e"]
, FNode "b" ]
xtree = AuxTree (INode "X"
[ FNode "a"
, INode "X" []
, FNode "b" ]
) [1]
-- | Here we check that the auxiliary tree must be fully
-- recognized before it can be adjoined.
gram3Tests :: [Test]
gram3Tests =
[ Test "S" (words "p a e b b") Yes
, Test "S" (words "p a e b") No ]
---------------------------------------------------------------------
-- Grammar 4 (make a cat drink)
---------------------------------------------------------------------
make1 :: WeightedTree
make1 = ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP" [] ]
], 1)
make2 :: WeightedTree
make2 = ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP" []
, INode "VP" [] ]
], 1)
a' :: WeightedTree
a' = (INode "D" [FNode "a"], 1)
cat :: WeightedTree
cat = ( INode "NP"
[ INode "D" []
, INode "N"
[FNode "cat"]
], 1)
drink :: WeightedTree
drink = ( INode "VP"
[ INode "V"
[FNode "drink"]
], 1)
catDrink :: WeightedTree
catDrink = ( INode "NP"
[ INode "D" []
, INode "N"
[FNode "cat"]
, INode "N"
[FNode "drink"]
], 0)
almostW :: WeightedAux
almostW = ( AuxTree (INode "V"
[ INode "Ad" [FNode "almost"]
, INode "V" []
]) [1], 1)
-- | Compile the first grammar.
mkGram4 :: IO WeightedGram
mkGram4 = W.compileWeights $
map Left
[ make1, make2, a', cat
, drink, catDrink ] ++
map Right [almostW]
-- | Here we check that the auxiliary tree must be fully
-- recognized before it can be adjoined.
gram4Tests :: [Test]
gram4Tests =
[ Test "S" ["make", "a", "cat", "drink"] . WeightedTrees $ M.fromList
[ ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "cat"] ]
, INode "VP"
[ INode "V" [FNode "drink"] ]
]
], 4)
, ( INode "S"
[ INode "VP"
[ INode "V" [FNode "make"]
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "cat"]
, INode "N" [FNode "drink"] ]
]
], 2)
]
]
---------------------------------------------------------------------
-- Grammar 5 (give a lift)
---------------------------------------------------------------------
-- | Compile the first grammar.
mkGram5 :: IO WeightedGram
mkGram5 = W.compileWeights $
map Left trees ++ map Right auxTrees
where
trees = concat
[ det "a", det "my", det "your" , det "the" , noun "lift"
, noun "car", noun "house", pron "me"
, give1, give2 , give_a_lift_to, give_a_lift
, train_station, noun "train", noun "station" ]
auxTrees = concat
[ ppVPMod "with", ppVPMod "to"
, ppNPMod "with", ppNPMod "to"
, adj "main", adj "nearest" ]
det x = single (INode "D" [FNode x], 1)
noun x =
[ ( INode "NP"
[ INode "D" []
, INode "N"
[FNode x]
], 1 )
, ( INode "NP"
[ INode "D" []
, INode "N"
[ FNode x
, INode "N" [] ]
], 1 )
, (INode "N" [FNode x], 1) ]
pron x = single ( INode "NP"
[ INode "Pron"
[FNode x]
], 1)
give1 = single ( INode "VP"
[ INode "V" [FNode "give"]
, INode "NP" []
, INode "NP" []
], 1)
give2 = single ( INode "VP"
[ INode "V" [FNode "give"]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode "to"]
, INode "NP" [] ]
], 1)
give_a_lift_to = single ( INode "VP"
[ INode "V-MWE" [FNode "give"]
, INode "NP" []
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "lift"] ]
, INode "PP"
[ INode "P" [FNode "to"]
, INode "NP" [] ]
], 1)
give_a_lift = single ( INode "VP"
[ INode "V-MWE" [FNode "give"]
, INode "NP" []
, INode "NP"
[ INode "D" [FNode "a"]
, INode "N" [FNode "lift"] ]
], 1)
ppVPMod x = single ( AuxTree (INode "VP"
[ INode "VP" []
, INode "PP"
[ INode "P" [FNode x]
, INode "NP" [] ]
]) [0], 1)
ppNPMod x = single ( AuxTree (INode "NP"
[ INode "NP" []
, INode "PP"
[ INode "P" [FNode x]
, INode "NP" [] ]
]) [0], 1)
train_station = single ( INode "NP"
[ INode "D" []
, INode "N"
[ FNode "train"
, FNode "station" ]
], 1)
adj x = single ( AuxTree (INode "N"
[ INode "Adj" [FNode x]
, INode "N" []
]) [1], 1)
-- Utils
single x = [x]
---------------------------------------------------------------------
-- Misc Grammars
---------------------------------------------------------------------
-- | Compile the first grammar and return two results: a simple factorized
-- grammar (fst) and factorized grammar with subtree sharing (snd).
mkGramAcidRains :: IO (Gram, Gram)
mkGramAcidRains = do
gramPlain <- R.compile trees
gramShare <- compile trees
return (gramPlain, gramShare)
where
trees =
-- map Left [rainsN, rainsV, acid_rains, ghana] ++
-- map Right [ppMod "in" "S", ppMod "in" "NP"]
map Left [rainsN, rainsV, acidNP, acid_rains] ++
map Right [nounM "acid" "A", nounM "acid" "N"]
rainsN = INode "NP"
[ INode "N"
[FNode "rains"]
]
rainsV = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode "rains"]
]
]
acidNP = INode "NP"
[ INode "N"
[FNode "acid"]
]
acid_rains = INode "NP"
[ INode "N" [FNode "acid"]
, INode "N" [FNode "rains"]
]
nounM x cat = AuxTree (INode "N"
[ INode cat [FNode x]
, INode "N" []
]) [1]
-- ghana = INode "NP"
-- [ INode "N"
-- [FNode "Ghana"]
-- ]
-- ppMod x cat = AuxTree (INode cat
-- [ INode cat []
-- , INode "PP"
-- [ INode "P" [FNode x]
-- , INode "NP" [] ]
-- ]) [0]
-- | Compile the first grammar and return two results: a simple factorized
-- grammar (fst) and factorized grammar with subtree sharing (snd).
mkGramSetPoints :: IO Gram
mkGramSetPoints = do
-- gramPlain <- R.compile trees
gramShare <- compile trees
-- return (gramPlain, gramShare)
return gramShare
where
trees =
( map Left
-- [ nounNoDet "set"
[ nounNoDet "points"
, imperVerbNPprepNP "set" "in"
-- , transVerb "set"
-- , inTransVerb "lunches"
-- , verbNPatNP "points"
, nounNounComp "set" "points" ] ) ++
( map Right
[ nounLeftMod "set" "Adj"
, nounLeftMod "set" "N"
, nounLeftMod "set" "Ppart" ] )
nounNoDet x = INode "NP"
[ INode "N"
[FNode x]
]
transVerb x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
]
]
inTransVerb x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
]
]
transVerbImper x = INode "S"
[ INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
]
]
imperVerbNPprepNP v p = INode "S"
[ INode "VP"
[ INode "V"
[FNode v]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode p]
, INode "NP" [] ]
]
]
verbNPatNP x = INode "S"
[ INode "NP" []
, INode "VP"
[ INode "V"
[FNode x]
, INode "NP" []
, INode "PP"
[ INode "P" [FNode "at"]
, INode "NP" [] ]
]
]
nounLeftMod x cat = AuxTree (INode "N"
[ INode cat [FNode x]
, INode "N" []
]) [1]
nounNounComp x y = INode "NP"
[ INode "N" [FNode x]
, INode "N" [FNode y]
]
adjNounComp x y = INode "NP"
[ INode "Adj" [FNode x]
, INode "N" [FNode y]
]
---------------------------------------------------------------------
-- Resources
---------------------------------------------------------------------
-- | Compiled grammars.
data Res = Res
{ gram1 :: Gram
, gram2 :: Gram
, gram3 :: Gram
, gram4 :: WeightedGram }
-- | Construct the shared resource (i.e. the grammars) used in
-- tests.
mkGrams :: IO Res
mkGrams = Res <$> mkGram1 <*> mkGram2 <*> mkGram3 <*> mkGram4
---------------------------------------------------------------------
-- Test Tree
---------------------------------------------------------------------
-- | All the tests of the parsing algorithm.
testTree
:: String
-- ^ Name of the tested module
-> (Gram -> String -> [String] -> IO Bool)
-- ^ Recognition function
-> Maybe (Gram -> String -> [String] -> IO (S.Set Tr))
-- ^ Parsing function (optional)
-> Maybe (WeightedGram -> String -> [String] -> IO (M.Map Tr Cost))
-- ^ Parsing with weights (optional)
-> TestTree
testTree modName reco parse parseW = withResource mkGrams (const $ return ()) $
\resIO -> testGroup modName $
map (testIt resIO gram1) gram1Tests ++
map (testIt resIO gram2) gram2Tests ++
map (testIt resIO gram3) gram3Tests ++
map (testWe resIO gram4) gram4Tests
where
testIt resIO getGram test = testCase (show test) $ do
gram <- getGram <$> resIO
doTest gram test
testWe resIO getGram test = testCase (show test) $ do
gram <- getGram <$> resIO
doTestW gram test
doTest gram test@Test{..} = case (parse, testRes) of
(Nothing, _) ->
reco gram startSym testSent @@?= simplify testRes
(Just pa, Trees ts) ->
pa gram startSym testSent @@?= ts
_ ->
reco gram startSym testSent @@?= simplify testRes
doTestW gram test@Test{..} = case (parseW, parse, testRes) of
-- (Nothing, Nothing, _) ->
-- reco gram startSym testSent @@?= simplify testRes
(_, Just pa, Trees ts) ->
pa (unWeighGram gram) startSym testSent @@?= ts
(Just pa, _, WeightedTrees ts) ->
fmap smoothOut (pa gram startSym testSent) @@?= ts
(Nothing, Just pa, WeightedTrees ts) ->
pa (unWeighGram gram) startSym testSent @@?= remWeights ts
_ ->
reco (unWeighGram gram) startSym testSent @@?= simplify testRes
smoothOut = fmap $ roundWeight 5
roundWeight n x = fromInteger (round $ x * (10^n)) / (10.0^^n)
remWeights = M.keysSet
unWeighGram
= S.fromList
. map W.unWeighRule
. S.toList
simplify No = False
simplify Yes = True
simplify (Trees _) = True
simplify (WeightedTrees _)
= True
---------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------
(@@?=) :: (Show a, Eq a) => IO a -> a -> Assertion
mx @@?= y = do
x <- mx
x @?= y
| kawu/tag-vanilla | src/NLP/TAG/Vanilla/Tests.hs | bsd-2-clause | 18,182 | 0 | 18 | 6,194 | 4,979 | 2,658 | 2,321 | 459 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
module NLP.Albemarle.Cooccur
( -- * Sliding Window
geometricSkips,
harmonicSkips,
packIDs,
unpackIDs,
cooccurify,
wordSlice,
frequency,
wordFrequency,
probability,
predict
) where
import Lens.Micro
import Lens.Micro.TH
import qualified Data.IntMap.Strict as IntMap
import Data.Bits
import Data.Maybe
import Debug.Trace
type Cooccur = IntMap.IntMap Double
-- | Windowing function for skip-grams
geometricSkips :: Double -- ^ Exponential decay with distance
-> Int -- ^ Window radius (actual size is 2*radius + 1)
-> [a] -- ^ Document
-> [(a, a, Double)] -- ^ (Source, target, weight) triple
geometricSkips dropoff radius [] = []
geometricSkips dropoff radius (s:ss) =
-- Tack on source and get two tuples each, because it is symmetric
(concatMap (\(t, w) -> [(s, t, w), (t, s, w)])
$ zip ss -- Pair the weights with the upcoming words
$ take radius -- Limit to a horizon
$ iterate (dropoff*) 1) -- The decaying weights
++ geometricSkips dropoff radius ss -- Repeat for the next word
-- | Windowing function for skip-grams
harmonicSkips :: Int -- ^ Window radius (actual size is 2*radius + 1)
-> [a] -- ^ Document
-> [(a, a, Double)] -- ^ (Source, target, weight) triple
harmonicSkips radius [] = []
harmonicSkips radius (s:ss) =
(concatMap (\(t, w) -> [(s, t, w), (t, s, w)])
$ zip ss
$ fmap (1/) [1..fromIntegral radius])
++ harmonicSkips radius ss
-- | This is dangerous but great for Intmaps: convert two 32 bit integers into
-- a single packed 64 bit integer. But Intmaps can't guarantee 64 bits, so
-- this will not work on 32-bit machines. Be warned!
packIDs :: Int -> Int -> Int
packIDs a b = (a `shiftL` 32) .|. b
-- | This is dangerous but great for Intmaps: convert one 64 bit integer into
-- two 32 bit integers. But Intmaps can't guarantee 64 bits, so
-- this will not work on 32-bit machines. Be warned!
unpackIDs :: Int -> (Int, Int)
unpackIDs a = (a `shiftR` 32, a .&. 0x00000000FFFFFFFF)
-- | Make a word-word cooccurance matrix out of a series of weighted
-- cooccurances (like harmonicSkips will make for you)
cooccurify :: [(Int, Int, Double)] -> Cooccur
cooccurify = IntMap.fromListWith (+)
. fmap (\(s, t, w) -> (packIDs s t, w))
-- | Get all of the frequencies associated with a source word
wordSlice :: Int -> Cooccur -> Cooccur
wordSlice a = let
start = packIDs a 0 -- Will be inclusive
end = packIDs (a+1) 0 -- Will be exclusive
split target c = let
(left, mayv, right) = IntMap.splitLookup target c
in (maybe left (\v -> IntMap.insert target v left) mayv, right)
in snd . split start -- after the beginning
. fst . split end -- before the end
-- | Get the frequency of a specific word pair.
frequency :: Int -> Int -> Cooccur -> Double
frequency a b = fromMaybe 0 . IntMap.lookup (packIDs a b)
wordFrequency :: Int -> Cooccur -> Double
wordFrequency wd = sum . fmap snd . IntMap.toList . wordSlice wd
probability :: Int -> Int -> Cooccur -> Double
probability a b cooccur = let
denom = wordFrequency a cooccur
in if denom == 0 then 0 else frequency a b cooccur / denom
predict :: Int -> Cooccur -> [(Int, Double)]
predict wd cooccur = let
normalize = wordFrequency wd cooccur
in fmap (\(p, f) -> (snd $ unpackIDs p, f/normalize))
$ IntMap.toList $ wordSlice wd cooccur
| SeanTater/albemarle | src/NLP/Albemarle/Cooccur.hs | bsd-3-clause | 3,483 | 0 | 16 | 738 | 943 | 531 | 412 | 72 | 2 |
module TriangleKata.Day1 (triangle, TriangleType(..)) where
data TriangleType = Illegal | Equilateral | Isosceles | Scalene
deriving (Show, Eq)
type Triangle = (Int, Int, Int)
triangle :: Triangle -> TriangleType
triangle (0, 0, 0) = Illegal
triangle (a, b, c)
| a + b < c
|| b + c < a
|| c + a < b = Illegal
| a == b
&& b == c = Equilateral
| a == b
|| b == c
|| c == a = Isosceles
| otherwise = Scalene
| Alex-Diez/haskell-tdd-kata | old-katas/src/TriangleKata/Day1.hs | bsd-3-clause | 552 | 0 | 15 | 234 | 200 | 109 | 91 | 16 | 1 |
module Config
( scPre
) where
import Data.Monoid
import Common
genDefaultNav galNav = N { navTitle = "Home"
, navPath = Just ""
, subs =
[ galNav
, N { navTitle = "Webdesign"
, navPath = Just "webdesign.html"
, subs = []}
, N { navTitle = "Kontakt"
, navPath = Just "kontakt.html"
, subs =
[ N { navTitle = "gpg-pubkey"
, navPath = Just "gpg-pubkey.html"
, subs = []}
, N { navTitle = "GitHub"
, navPath = Just
"https://github.com/maxhbr"
, subs = []}
, N { navTitle = "Impress"
, navPath = Just "impress.html"
, subs = []}]}]}
scPre galNav = SC { statics = ["css","galerie","images","scripts"
,"gpg-pubkey.asc","favicon.ico"
,"qr.jpg","qr_large.jpg"]
, url = "https://maximilian-huber.de"
, outPath = "_site"
, defaultP = P { pPath = []
, pTitle = Nothing
, pStyle = TextStyle
, pCtn = mempty
, pNav = genDefaultNav galNav
, pLine = Nothing
, pSocial = Nothing}
, indexP = Just "galerie/index.html"}
| maximilianhuber/maximilian-huber.de | src/Config.hs | bsd-3-clause | 1,929 | 0 | 13 | 1,186 | 305 | 188 | 117 | 37 | 1 |
#!/usr/bin/env runhaskell
import Distribution.Simple (defaultMainWithHooks, simpleUserHooks,
UserHooks(..), Args)
{-
-- The test-related options have been disabled due to incompitibilities
-- in various Cabal release versions. In particular, the type expected for
-- runTests has changed, and joinPaths was not exported in Cabal 1.1.6
import Distribution.PackageDescription (PackageDescription)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo)
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Utils (rawSystemVerbose)
import Distribution.Compat.FilePath (joinPaths)
import System.Exit(ExitCode(..))
-}
main :: IO ()
main = defaultMainWithHooks (simpleUserHooks)
-- main = defaultMainWithHooks (defaultUserHooks{runTests = tests})
{-
-- Definition of tests for Cabal 1.1.3
tests :: Args -> Bool -> LocalBuildInfo -> IO ExitCode
tests args _ lbi =
let testCmd = foldl1 joinPaths [LBI.buildDir lbi, "ListMergeTest", "ListMergeTest"]
in rawSystemVerbose 1 testCmd
("+RTS" : "-M32m" : "-c30" : "-RTS" : args)
-}
{-
-- Definition of tests for Cabal 1.1.7
tests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO ExitCode
tests args _ _ lbi =
let testCmd = foldl1 joinPaths [LBI.buildDir lbi, "ListMergeTest", "ListMergeTest"]
in rawSystemVerbose 1 testCmd
("+RTS" : "-M32m" : "-c30" : "-RTS" : args)
-}
| kfish/hogg | Setup.hs | bsd-3-clause | 1,463 | 0 | 6 | 281 | 50 | 31 | 19 | 4 | 1 |
-- Copyright (c) 2011, Mark Wright. All rights reserved.
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
module Main (main) where
import Control.Exception as E
import qualified Data.List as L
import Data.Char (toLower)
import Distribution.Compiler
import Distribution.ModuleName (components, ModuleName)
import Distribution.Package
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.System (buildPlatform)
import Distribution.Verbosity
import Distribution.Version
import System.Console.CmdArgs.Implicit
import System.IO
import System.Process (readProcess)
import Data.String.Utils
import Text.Regex.TDFA
deriving instance Data CompilerFlavor
deriving instance Data Version
deriving instance Typeable CompilerFlavor
instance Default CompilerFlavor where
def = buildCompilerFlavor
data VersionInfo = NotDisplayed
| Displayed
| DisplayedInSquareBrackets
deriving (Data, Enum, Typeable, Show)
data ModuleInfo = ExposedAndNonExposed
| Exposed
| NonExposed
deriving (Data, Enum, Typeable, Show)
data CmdOpts = Depends
{ delim :: String
, prefix :: String
, compilerFlavor :: CompilerFlavor
, compilerVersion :: Version
, versionInfo :: VersionInfo
, cabalFilePath :: FilePath
}
| Modules
{ delim :: String
, prefix :: String
, compilerFlavor :: CompilerFlavor
, compilerVersion :: Version
, moduleInfo :: ModuleInfo
, cabalFilePath :: FilePath
} deriving (Data, Typeable, Show)
lowercase :: String -> String
lowercase = map toLower
depends_ :: CmdOpts
depends_ = Depends { delim = " "
, prefix = ""
, compilerFlavor = enum [ GHC &= help "ghc"
, NHC &= help "nhc"
, YHC &= help "yhc"
, Hugs &= help "hugs"
, HBC &= help "hbc"
, Helium &= help "helium"
, JHC &= help "jhc"
, LHC &= help "lhc"
, UHC &= help "uhc"
, OtherCompiler "" &= help ""
]
, compilerVersion = Version { versionBranch = []
, versionTags = [] }
, versionInfo = enum [ NotDisplayed &= help "Version info not displayed"
, Displayed &= help "Version info displayed"
, DisplayedInSquareBrackets &= help "Version info displayed in square brackets"
]
, cabalFilePath = "" &= typFile &= args
} &= help "List dependencies"
modules :: CmdOpts
modules = Modules { delim = " "
, prefix = ""
, compilerFlavor = enum [ GHC &= help "ghc"
, NHC &= help "nhc"
, YHC &= help "yhc"
, Hugs &= help "hugs"
, HBC &= help "hbc"
, Helium &= help "helium"
, JHC &= help "jhc"
, LHC &= help "lhc"
, UHC &= help "uhc"
, OtherCompiler "" &= help ""
]
, compilerVersion = Version { versionBranch = []
, versionTags = []
}
, moduleInfo = enum [ ExposedAndNonExposed &= help "Both exposed and non-exposed modules"
, Exposed &= help "Exposed modules"
, NonExposed &= help "Non-exposed modules"
]
, cabalFilePath = "" &= typFile &= args
} &= help "List modules"
-- | display dependency and optionally version information
depVerStr :: VersionInfo -> -- ^ controls the optional display of dependency version information
Dependency -> -- ^ the dependency
String -- ^ output dependency string and optionally dependency version information
depVerStr vi (Dependency (PackageName pn) vr) = case vi of
NotDisplayed -> pn
Displayed -> pn ++ " " ++ show vr
DisplayedInSquareBrackets -> pn ++ "[" ++ show vr ++ "]"
-- | list dependencies in the cabal file
lsdeps :: VersionInfo -> -- ^ optionally list dependency version information
String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
IO () -- ^ return nothing
lsdeps vi d p l =
let ds = (map (depVerStr vi) . targetBuildDepends . libBuildInfo) l
prefixedDeps = map (p ++) ds
deps = L.intercalate d prefixedDeps
in
do
putStrLn deps
return ()
nonExposedModules :: Library ->
[ModuleName]
nonExposedModules = otherModules . libBuildInfo
mods :: String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
(Library -> [ModuleName]) -> -- ^ function to obtain list of modules from Library
IO () -- ^ return nothing
mods d p l f =
let ds = map (L.intercalate "." . components) (f l)
prefixedMods = map (p ++) ds
ms = L.intercalate d prefixedMods
in
putStrLn ms
-- | list modules in the cabal file
lsmods :: ModuleInfo -> -- ^ optionally list exposed and/or non-exposed modules
String -> -- ^ delimiter string between dependencies
String -> -- ^ optional prefix string before each dependency
Library -> -- ^ library
IO () -- ^ return nothing
lsmods mi d p l =
case mi of
ExposedAndNonExposed ->
do
mods d p l exposedModules
mods d p l nonExposedModules
return ()
Exposed -> mods d p l exposedModules
NonExposed -> mods d p l nonExposedModules
-- | Replace all occurrances of escaped line feed, carriage return and
-- tab characters.
escapeReplace :: String -> -- ^ input string
String -- ^ output string with escaped characters replaced with corresponding characters
escapeReplace = replace "\\n" "\n" . replace "\\r" "\r" . replace "\\t" "\t"
compVer :: CompilerFlavor ->
Version ->
IO CompilerId
compVer c v@(Version [] []) =
do
let comp = (lowercase . show) c
eitherH <- (E.try :: IO String -> IO (Either SomeException String)) $ readProcess comp ["--version"] []
case eitherH of
Left err ->
do
putStrLn $ "Failed to obtain " ++ (lowercase . show) c ++ " version: " ++ show err
return $ CompilerId c v
Right vs ->
do
let vw = words (vs =~ "[Vv]ersion [0-9]+([.][0-9])+" :: String)
let ns = if length vw == 2
then (words . replace "." " " . last) vw
else []
eitherR <- (E.try :: IO [Int] -> IO (Either SomeException [Int])) $ return $ map (read :: String -> Int) ns
case eitherR of
Left _ ->
return $ CompilerId c Version { versionBranch = []
, versionTags = ns
}
Right is ->
return $ CompilerId c Version { versionBranch = is
, versionTags = ns
}
compVer c v@Version {} =
return $ CompilerId c v
-- | Process command line options
processOpts :: CmdOpts -> -- ^ command line options
IO Int -- ^ return 0 on success, 1 on failure
processOpts cmdOpts =
do
let inputFilePath = cabalFilePath cmdOpts
cv <- compVer (compilerFlavor cmdOpts) (compilerVersion cmdOpts)
eitherH <- E.try $ readPackageDescription verbose inputFilePath
case eitherH of
Left err ->
putStrLn "Failed to open output file " >> ioError err >> return 1
Right genericPackageDescription ->
let eitherP = finalizePackageDescription
[ (FlagName "small_base", True)
]
(\_ -> True)
buildPlatform
cv
[]
genericPackageDescription
in
case eitherP of
Left ds ->
let missingDeps = (L.unwords . map show) ds
in
do
putStrLn $ "Missing deps: " ++ missingDeps
return 1
Right (pd, _) ->
case cmdOpts of
Depends {} ->
do
let
d = escapeReplace $ delim cmdOpts
p = escapeReplace $ prefix cmdOpts
vi = versionInfo cmdOpts
withLib pd (lsdeps vi d p)
return 0
Modules {} ->
do
let
d = escapeReplace $ delim cmdOpts
p = escapeReplace $ prefix cmdOpts
mi = moduleInfo cmdOpts
withLib pd (lsmods mi d p)
return 0
main :: IO Int
main = do
cmdOpts <- cmdArgs $ modes [ depends_
, modules
]
&= program "cquery"
&= summary "cquery"
processOpts cmdOpts
| markwright/cquery | Main.hs | bsd-3-clause | 10,420 | 7 | 22 | 4,532 | 2,114 | 1,111 | 1,003 | 215 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Language.Brainfuck.Internals.CCodeGen where
import Data.Int
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as TIO
import qualified Data.Text.Lazy.Builder as TB
import Data.Text.Format
import Control.Monad.State
import Language.Brainfuck.Internals.Instructions
data CProgram = CProgram
{ statements :: TB.Builder
, indent :: Int64 }
type Compiler = State CProgram ()
addLine :: T.Text -> CProgram -> CProgram
addLine l p = p { statements = statements p
`mappend` (TB.fromLazyText (T.replicate (indent p) " ")
`mappend` (TB.fromLazyText l
`mappend` TB.singleton '\n')) }
incrIndent :: CProgram -> CProgram
incrIndent p = p { indent=indent p + 1 }
decrIndent :: CProgram -> CProgram
decrIndent p = p { indent=indent p - 1 }
emptyProgram :: CProgram
emptyProgram = CProgram
{ statements=TB.fromLazyText ""
, indent=1 }
gen :: Instr -> Compiler
gen (Incr i) = modify' . addLine . format "mem[ptr] += {};" $ Only i
gen (Decr i) = modify' . addLine . format "mem[ptr] -= {};" $ Only i
gen (Set i) = modify' . addLine . format "mem[ptr] = {};" $ Only i
gen (Mul x 1) = modify' . addLine . format "mem[ptr + {}] += mem[ptr];" $ Only x
gen (Mul x y) = modify' . addLine . format "mem[ptr + {}] += mem[ptr] * {};" $ (x, y)
gen (Copy n) = modify' . addLine . format "mem[ptr + {}] = mem[ptr]" $ Only n
gen (MoveRight n) = modify' . addLine . format "ptr += {};" $ Only n
gen (MoveLeft n) = modify' . addLine . format "ptr -= {};" $ Only n
gen Read = modify' (addLine "mem[ptr] = getchar();")
gen Print = modify' (addLine "putchar(mem[ptr]);")
gen (Loop body) = do
modify' (addLine "while (mem[ptr]) {")
modify' incrIndent
mapM_ gen body
modify' decrIndent
modify' (addLine "}")
gen _ = return ()
genCode :: Program -> T.Text
genCode prog = TB.toLazyText . statements . execState (mapM_ gen prog) $ emptyProgram
wrapCode :: T.Text -> T.Text
wrapCode program = T.unlines
[ "#include <stdio.h>"
, ""
, "int main() {"
, " char mem[30000] = {0};"
, " int ptr = 0;"
, program
, "}"
]
compile :: Program -> FilePath -> IO ()
compile [] _ = putStrLn "Empty program would result in empty file. No file created."
compile prog path = TIO.writeFile path . wrapCode . genCode $ prog
| remusao/Hodor | src/Language/Brainfuck/Internals/CCodeGen.hs | bsd-3-clause | 2,368 | 0 | 14 | 527 | 810 | 421 | 389 | 58 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving
, MultiParamTypeClasses
, TypeSynonymInstances
, FlexibleContexts
, FlexibleInstances
, StandaloneDeriving
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Spiro
-- Copyright : (c) 2011 diagrams-lib team (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
--
-- Generic functionality for constructing cubic splines
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Spiro
( spiro
, SpiroPoint(..)
, SpiroConstraint(..)
) where
import System.IO.Unsafe(unsafePerformIO)
import Graphics.Spiro.Raw
import Diagrams.Prelude
import Diagrams.TwoD.Spiro.PathContext (PathContext,toDiagram,zeroPathContext)
import qualified Diagrams.TwoD.Spiro.PathContext as P
import Data.Monoid
import Data.NumInstances
import Control.Monad.IO.Class
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Newtype
newtype PathPostscriptT s m a = PathPostscriptT { runPathPostscriptT :: StateT (PathContext s) m a }
deriving (Functor,Applicative,Monad,MonadIO,MonadTrans)
deriving instance Monad m => MonadState (PathContext s) (PathPostscriptT s m)
instance Newtype (PathPostscriptT s m a) (StateT (PathContext s) m a) where
pack = PathPostscriptT
unpack = runPathPostscriptT
instance MonadIO m => PostscriptLike (PathPostscriptT R2 m) where
moveTo' x y b = modify $ P.moveTo' (x,y) b
moveTo x y = modify $ P.moveTo (x,y)
lineTo x y = modify $ P.lineTo (x,y)
quadTo x y x' y' = modify $ P.quadTo (x,y) (x',y')
curveTo x y x' y' x'' y'' = modify $ P.curveTo (x,y) (x',y') (x'',y'')
markKnot _ = return ()
-- | Computes a diagram from the given spiro control points.
spiro :: Renderable (Path R2) b
=> Bool -- ^ 'True' for a closed path.
-> [SpiroPoint] -- ^ Set of control points with their constrints.
-> Diagram b R2
spiro closed ps = unsafePerformIO $ do
let p = runPathPostscriptT $ spiroToBezier closed ps
execStateT p zeroPathContext >>= return . toDiagram
| fryguybob/diagrams-spiro | src/Diagrams/TwoD/Spiro.hs | bsd-3-clause | 2,294 | 0 | 12 | 482 | 542 | 304 | 238 | 42 | 1 |
-- SG library
-- Copyright (c) 2009, Neil Brown.
-- 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.
-- * The author's name may not 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 OWNER 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.
-- | Some types that are very basic vectors. Most of the use that can be made
-- of the vectors is in their type-class instances, which support a powerful set
-- of operations. For example:
--
-- > fmap (*3) v -- Scales vector v by 3
-- > pure 0 -- Creates a vector filled with zeroes
-- > v + w -- Adds two vectors (there is a 'Num' instance, basically)
--
-- Plus all the instances for the classes in "Data.SG.Vector", which allows you
-- to use 'getX' and so on.
--
-- You will probably want to create more friendly type synonyms, such as:
--
-- > type Vector2 = Pair Double
-- > type Vector3 = Triple Double
-- > type Line2 = LinePair Double
-- > type Line3 = LineTriple Double
module Data.SG.Vector.Basic where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.SG.Vector
-- | A pair, which acts as a 2D vector.
newtype Pair a = Pair (a, a)
deriving (Eq, Ord, Show, Read)
-- | A triple, which acts as a 3D vector.
newtype Triple a = Triple (a, a, a)
deriving (Eq, Ord, Show, Read)
-- | A quad, which acts as a 4D vector.
newtype Quad a = Quad (a, a, a, a)
deriving (Eq, Ord, Show, Read)
-- | A pair of (position vector, direction vector) to be used as a 2D line.
newtype LinePair a = LinePair (Pair a, Pair a)
deriving (Eq, Ord, Show, Read)
-- | A pair of (position vector, direction vector) to be used as a 3D line.
newtype LineTriple a = LineTriple (Triple a, Triple a)
deriving (Eq, Ord, Show, Read)
instance VectorNum Pair where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance VectorNum Triple where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance VectorNum Quad where
fmapNum1 = fmap
fmapNum1inv = fmap
fmapNum2 = liftA2
simpleVec = pure
instance (Show a, Eq a, Num a) => Num (Pair a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance (Show a, Eq a, Num a) => Num (Triple a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance (Show a, Eq a, Num a) => Num (Quad a) where
(+) = fmapNum2 (+)
(-) = fmapNum2 (-)
(*) = fmapNum2 (*)
abs = fmapNum1inv abs
signum = fmapNum1 signum
negate = fmapNum1inv negate
fromInteger = simpleVec . fromInteger
instance Applicative Pair where
pure a = Pair (a, a)
(<*>) (Pair (fa, fb)) (Pair (a, b)) = Pair (fa a, fb b)
instance Foldable Pair where
foldr f t (Pair (x, y)) = x `f` (y `f` t)
instance Traversable Pair where
traverse f (Pair (x, y)) = Pair <$> liftA2 (,) (f x) (f y)
instance Applicative Triple where
pure a = Triple (a, a, a)
(<*>) (Triple (fa, fb, fc)) (Triple (a, b, c)) = Triple (fa a, fb b, fc c)
instance Foldable Triple where
foldr f t (Triple (x, y, z)) = x `f` (y `f` (z `f` t))
instance Traversable Triple where
traverse f (Triple (x, y, z)) = Triple <$> liftA3 (,,) (f x) (f y) (f z)
instance Applicative Quad where
pure a = Quad (a, a, a, a)
(<*>) (Quad (fa, fb, fc, fd)) (Quad (a, b, c, d))
= Quad (fa a, fb b, fc c, fd d)
instance Foldable Quad where
foldr f t (Quad (x, y, z, a)) = x `f` (y `f` (z `f` (a `f` t)))
instance Traversable Quad where
traverse f (Quad (x, y, z, a)) = Quad <$> ((,,,) <$> f x <*> f y <*> f z <*> f a)
instance Functor Pair where
fmap = fmapDefault
instance Functor Triple where
fmap = fmapDefault
instance Functor Quad where
fmap = fmapDefault
instance Coord Pair where
getComponents (Pair (a, b)) = [a, b]
fromComponents (a:b:_) = Pair (a, b)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Pair where
getX (Pair (a, _)) = a
getY (Pair (_, b)) = b
instance Coord Triple where
getComponents (Triple (a, b, c)) = [a, b, c]
fromComponents (a:b:c:_) = Triple (a, b, c)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Triple where
getX (Triple (a, _, _)) = a
getY (Triple (_, b, _)) = b
instance Coord3 Triple where
getZ (Triple (_, _, c)) = c
instance Coord Quad where
getComponents (Quad (a, b, c, d)) = [a, b, c, d]
fromComponents (a:b:c:d:_) = Quad (a, b, c, d)
fromComponents xs = fromComponents $ xs ++ repeat 0
instance Coord2 Quad where
getX (Quad (a, _, _, _)) = a
getY (Quad (_, b, _, _)) = b
instance Coord3 Quad where
getZ (Quad (_, _, c, _)) = c
| eigengrau/haskell-sg | Data/SG/Vector/Basic.hs | bsd-3-clause | 6,065 | 0 | 12 | 1,283 | 1,863 | 1,063 | 800 | 107 | 0 |
-- To run, package aivika-experiment-cairo must be installed.
import Simulation.Aivika.Experiment
import Simulation.Aivika.Experiment.Chart
import Simulation.Aivika.Experiment.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Backend.Cairo
import Model
import Experiment
main = do
-- run the ordinary simulation
putStrLn "*** The simulation with default parameters..."
runExperiment
singleExperiment singleGenerators
(WebPageRenderer (CairoRenderer PNG) experimentFilePath) (model defaultParams)
putStrLn ""
-- run the Monte-Carlo simulation
putStrLn "*** The Monte-Carlo simulation..."
randomParams >>= runExperimentParallel
monteCarloExperiment monteCarloGenerators
(WebPageRenderer (CairoRenderer PNG) experimentFilePath) . model
| dsorokin/aivika-experiment-chart | examples/Financial/MainUsingCairo.hs | bsd-3-clause | 774 | 0 | 13 | 105 | 127 | 68 | 59 | 16 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, BangPatterns #-}
module Valkyria.Type where
import Air.Data.Default
import Air.TH
import Air.Env
import Prelude ()
import Air.Data.Record.SimpleLabel
import Control.Concurrent.STM
import Data.ByteString.Char8 (ByteString)
import Data.Map (Map)
import Data.StateVar
import Text.JSON.Generic
data Code = Code
{
path :: String
, parent :: String
, depth :: Integer
, filesize :: Integer
, content :: String
, is_directory :: Integer
}
deriving (Show, Eq)
mkDefault ''Code
data UnpackStatus =
Unpacking
| UnpackComplete
deriving (Show, Eq, Data, Typeable)
data DBJobStatus =
DBInit
| DBAnalysing
| DBImporting Int
| DBIndexing
| DBComplete
deriving (Show, Eq, Data, Typeable)
data JobError =
FailedToFetchRepo
| Exception String
deriving (Show, Eq, Data, Typeable)
data JobStatus =
Initialized
| UnpackStage UnpackStatus
| DBStage DBJobStatus
| Bouncing
| Cleanup
| Completed Project
| Failed JobError
deriving (Show, Eq, Data, Typeable)
instance Default JobStatus where
def = Initialized
data FetchStatus =
FetchInQueue Integer
| Fetching JobStatus
| FetchFailed String
type StatusCallback = JobStatus -> IO ()
type FetchCallback = FetchStatus -> IO ()
type FetchMonitorCallback = IO () -> IO ()
data Repo = Git | Darcs | SVN | Hg | Archive | Raw
deriving (Show, Eq, Data, Typeable, Read)
instance Default Repo where
def = Git
data Project = Project
{
project_id :: Integer
, project_name :: String
, repo :: Repo
, project_url :: String
}
deriving (Show, Eq, Data, Typeable)
mkDefault ''Project
data RepoState = RepoState
{
states_map :: Map Integer (TVar JobStatus)
}
instance Default RepoState where
def = RepoState
{
states_map = def
}
-- Datatypes
data JobQueryResponse =
JobQueryFailed String
| JobQuerySuccess JobStatus
deriving (Eq, Show, Data, Typeable)
data JobCreateResponse =
JobCreateFailed String
| JobCreateSuccess Integer
deriving (Eq, Show, Data, Typeable)
instance HasGetter TVar where
get = atomically < readTVar
instance HasSetter TVar where
($=) x = atomically < writeTVar x
data SourceCode = SourceCode
{
project_ref :: Project
, fetch_status :: FetchStatus
}
data ClientState = ClientState
{
source_codes :: [SourceCode]
}
data LocalRepoStatus =
LocalInQueue
| LocalUnpacking
| LocalAnalysing
| LocalImporting Double
| LocalBouncing
| LocalDownloading Double
| LocalDone
| LocalError String
| LocalRefreshReachMaximumNumber
deriving (Show, Eq, Data, Typeable)
instance Default LocalRepoStatus where
def = LocalInQueue
data RepoControlHandle = RepoControlHandle
{
set_ui_repo_status :: Integer -> LocalRepoStatus -> IO ()
, set_global_error :: String -> IO ()
}
data RepoControlInput = RepoControlInput
{
create_repo :: TaskID -> Repo -> String-> IO ()
}
{-
instance Default (Event a) where
def = NoEvent
-}
type TaskID = Int
type CallbackMap = Map Int RepoControlHandle
data FetchTask =
CreateRepo !Repo !ByteString
| MonitorRepo !Integer !Integer
| DownloadRepo !Integer
| NoTask
deriving (Show, Eq)
instance Default FetchTask where
def = NoTask
data ReactInput = ReactInput
{
input_id :: !TaskID
, fetch_task :: !FetchTask
}
deriving (Show, Eq)
mkDefault ''ReactInput
data FetchUpdate =
PerformCreateRepo !Repo !ByteString
| PerformMonitorRepo !Integer !Integer
| PerformDownloadRepo !Integer
| SetRepoInQueue
| NoUpdate
deriving (Show, Eq)
instance Default FetchUpdate where
def = NoUpdate
data ReactState = ReactState
{
update_id :: !TaskID
, fetch_update :: !FetchUpdate
}
deriving (Show, Eq)
mkDefault ''ReactState
data LocalRepo = LocalRepo
{
repo_id :: Integer
, repo_url :: String
, repo_type :: Repo
, repo_name :: String
, repo_status :: LocalRepoStatus
}
deriving (Show, Eq, Data, Typeable)
mkDefault ''LocalRepo
type LocalRepoIndex = Integer
{-}
type FetchIn = Event ReactInput
type FetchOut = Event ReactState
type SenseRef = TVar [ReactInput]
type TaskRef = TVar CallbackMap
type LocalState = Map LocalRepoIndex LocalRepo
type LocalStateRef = TVar LocalState
-}
mkLabels
[
''RepoState
]
| nfjinjing/source-code-server | src/Valkyria/Type.hs | bsd-3-clause | 4,315 | 0 | 13 | 916 | 1,128 | 633 | 495 | 174 | 0 |
-- | Refreshes the shared simulation state. The new state will be calculated:
--
-- * Regularly, according to the speed selected by the user
--
-- * Every time there's a change in the status (running, paused, stopped, etc).
module Controller.Conditions.ShowState
( installHandlers )
where
-- External imports
import Control.Monad
import Control.Monad.IfElse
import Hails.MVC.Model.ProtectedModel.Reactive
-- Local imports
import Data.History
import CombinedEnvironment
import Graphics.UI.Gtk.Display.SoOSiMState
import Model.Model
import Model.SystemStatus
-- | Updates the simulation regularly and when there are changes
-- in the simulation status. There's an initial 1-second delay.
installHandlers :: CEnv -> IO()
installHandlers cenv = void $
onEvent (model cenv) SimStateChanged $ condition cenv
condition :: CEnv -> IO ()
condition cenv = onViewAsync $ do
stateM <- getter simStateField (model cenv)
awhen stateM $ \state -> do
let systemSt = simGLSystemStatus state
simstate = simGLSimState state
sel = selection $ systemSt
mcs = present $ multiCoreStatus systemSt
soosimSetSimState soosim $ Just simstate
soosimSetMCS soosim $ Just mcs
soosimSetSelection soosim $ Just sel
where soosim = soosimView (view cenv)
| ivanperez-keera/SoOSiM-ui | src/Controller/Conditions/ShowState.hs | bsd-3-clause | 1,289 | 0 | 16 | 240 | 265 | 139 | 126 | 25 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Spec.ExecuteF where
import Spec.Decode
import Spec.Machine
import Utility.Utility
import Spec.VirtualMemory
import qualified Spec.CSRField as Field
import Data.Bits
import Data.Word
import Data.Int
import SoftFloat
import Prelude hiding (isNaN)
canonicalNaN = 0x7fc00000 :: Int32
negativeZero = 0x80000000 :: Int32
positiveZero = 0x00000000 :: Int32
negativeInfinity = 0xff800000 :: Int32
positiveInfinity = 0x7f800000 :: Int32
intToRoundingMode :: MachineInt -> Maybe RoundingMode
intToRoundingMode 0 = Just RoundNearEven
intToRoundingMode 1 = Just RoundMinMag
intToRoundingMode 2 = Just RoundMin
intToRoundingMode 3 = Just RoundMax
intToRoundingMode 4 = Just RoundNearMaxMag
intToRoundingMode _ = Nothing
isNaN :: (Integral t) => t -> Bool
isNaN x = not notNaN
where Result notNaN _ = f32Eq (fromIntegral x :: Word32) (fromIntegral x :: Word32)
getRoundMode :: (RiscvMachine p t) => MachineInt -> p RoundingMode
getRoundMode rm = do
frm <- (if rm == 7 then
getCSRField Field.FRM
else
return rm)
case intToRoundingMode frm of
Just roundMode -> return roundMode
Nothing -> raiseException 0 2
boolBit :: (Bits t) => Int -> Bool -> t
boolBit i b = if b then bit i else zeroBits
updateFFlags :: (RiscvMachine p t) => ExceptionFlags -> p ()
updateFFlags (ExceptionFlags inexact underflow overflow infinite invalid) = do
flags <- getCSRField Field.FFlags
let flags' = flags .|. boolBit 0 inexact .|. boolBit 1 underflow .|.
boolBit 2 overflow .|. boolBit 3 infinite .|. boolBit 4 invalid
setCSRField Field.FFlags flags'
runFPUnary :: (RiscvMachine p t) => (RoundingMode -> Word32 -> F32Result) -> RoundingMode -> Int32 -> p Int32
runFPUnary f roundMode x = do
let Result y flags = f roundMode (fromIntegral x)
updateFFlags flags
if (invalid flags) then
return canonicalNaN
else
return (fromIntegral y)
runFPBinary :: (RiscvMachine p t) => (RoundingMode -> Word32 -> Word32 -> F32Result) -> RoundingMode -> Int32 -> Int32 -> p Int32
runFPBinary f roundMode x y = do
let Result z flags = f roundMode (fromIntegral x) (fromIntegral y)
updateFFlags flags
if (invalid flags) then
return canonicalNaN
else
return (fromIntegral z)
execute :: forall p t. (RiscvMachine p t) => InstructionF -> p ()
execute (Flw rd rs1 oimm12) = do
a <- getRegister rs1
addr <- translate Load 4 (a + fromImm oimm12)
x <- loadWord Execute addr
setFPRegister rd x
execute (Fsw rs1 rs2 simm12) = do
a <- getRegister rs1
addr <- translate Store 4 (a + fromImm simm12)
x <- getFPRegister rs2
storeWord Execute addr x
execute (Fmadd_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Add roundMode y x
setFPRegister rd z
execute (Fmsub_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode y x
setFPRegister rd z
execute (Fnmsub_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode x y
setFPRegister rd z
execute (Fnmadd_s rd rs1 rs2 rs3 rm) = do
roundMode <- getRoundMode rm
v <- getFPRegister rs1
w <- getFPRegister rs2
x <- getFPRegister rs3
y <- runFPBinary f32Mul roundMode v w
z <- runFPBinary f32Sub roundMode (xor y (bit 31)) x
setFPRegister rd z
execute (Fadd_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Add roundMode x y
setFPRegister rd z
execute (Fsub_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Sub roundMode x y
setFPRegister rd z
execute (Fmul_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Mul roundMode x y
setFPRegister rd z
execute (Fdiv_s rd rs1 rs2 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- getFPRegister rs2
z <- runFPBinary f32Div roundMode x y
setFPRegister rd z
execute (Fsqrt_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
y <- runFPUnary f32Sqrt roundMode x
setFPRegister rd y
execute (Fsgnj_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (bitSlice x 0 31 .|. (y .&. bit 31))
execute (Fsgnjn_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (bitSlice x 0 31 .|. (complement y .&. bit 31))
execute (Fsgnjx_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
setFPRegister rd (x `xor` (y .&. bit 31))
execute (Fmin_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32LtQuiet (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
-- Special cases and other sheNaNigans. Current behavior (v2.3-draft) differs
-- from v2.2 of spec.
let result | x == negativeZero && y == positiveZero = x
| isNaN x && isNaN y = canonicalNaN
| isNaN y = x
| isNaN x = y
| z = x
| otherwise = y
setFPRegister rd result
execute (Fmax_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32LtQuiet (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
-- Special cases and other sheNaNigans. Current behavior (v2.3-draft) differs
-- from v2.2 of spec.
let result | x == negativeZero && y == positiveZero = y
| isNaN x && isNaN y = canonicalNaN
| isNaN y = x
| isNaN x = y
| z = y
| otherwise = x
setFPRegister rd result
execute (Fcvt_w_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
let Result y flags = f32ToI32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
-- Special case for the softfloat library.
let result | isNaN x || (y == 2^31 && not (testBit x 31)) = 2^31 - 1
| otherwise = y
setRegister rd (fromIntegral result)
execute (Fcvt_wu_s rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getFPRegister rs1
let Result y flags = f32ToUi32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
-- Another special case for the softfloat library.
let result | not (isNaN x) && testBit x 31 = 0
| otherwise = y
setRegister rd (fromIntegral (fromIntegral result :: Int32))
execute (Fmv_x_w rd rs1) = do
x <- getFPRegister rs1
setRegister rd (fromIntegral x)
execute (Feq_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Eq (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Flt_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Lt (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Fle_s rd rs1 rs2) = do
x <- getFPRegister rs1
y <- getFPRegister rs2
let Result z flags = f32Le (fromIntegral x :: Word32) (fromIntegral y :: Word32)
updateFFlags flags
let result = fromIntegral (fromEnum z)
setRegister rd result
execute (Fclass_s rd rs1) = do
x <- getFPRegister rs1
let special = bitSlice x 23 31 == 2^8 - 1
let result | x == negativeInfinity = bit 0
| x == negativeZero = bit 3
| x == positiveZero = bit 4
| x == positiveInfinity = bit 7
| testBit x 22 && special = bit 9 -- quiet NaN
| special = bit 8 -- signaling NaN
| testBit x 22 && testBit x 31 = bit 2 -- negative subnormal
| testBit x 22 = bit 5 -- positive subnormal
| testBit x 31 = bit 1 -- negative normal
| otherwise = bit 6 -- positive normal
setRegister rd result
execute (Fcvt_s_w rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getRegister rs1
let Result y flags = i32ToF32 roundMode (fromIntegral x :: Int32)
updateFFlags flags
setFPRegister rd (fromIntegral y)
execute (Fcvt_s_wu rd rs1 rm) = do
roundMode <- getRoundMode rm
x <- getRegister rs1
let Result y flags = ui32ToF32 roundMode (fromIntegral x :: Word32)
updateFFlags flags
setFPRegister rd (fromIntegral y)
execute (Fmv_w_x rd rs1) = do
x <- getRegister rs1
setFPRegister rd (fromIntegral x)
execute inst = error $ "dispatch bug: " ++ show inst
| mit-plv/riscv-semantics | src/Spec/ExecuteF.hs | bsd-3-clause | 8,803 | 3 | 18 | 2,073 | 3,407 | 1,555 | 1,852 | 235 | 3 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1996-1998
TcTyClsDecls: Typecheck type and class declarations
-}
{-# LANGUAGE TupleSections #-}
module ETA.TypeCheck.TcTyClsDecls (
tcTyAndClassDecls, tcAddImplicits,
-- Functions used by TcInstDcls to check
-- data/type family instance declarations
kcDataDefn, tcConDecls, dataDeclChecks, checkValidTyCon,
tcFamTyPats, tcTyFamInstEqn, famTyConShape,
tcAddTyFamInstCtxt, tcAddDataFamInstCtxt,
wrongKindOfFamily, dataConCtxt, badDataConTyCon
) where
import ETA.HsSyn.HsSyn
import ETA.Main.HscTypes
import ETA.Iface.BuildTyCl
import ETA.TypeCheck.TcRnMonad
import ETA.TypeCheck.TcEnv
import ETA.TypeCheck.TcValidity
import ETA.TypeCheck.TcHsSyn
import ETA.TypeCheck.TcSimplify( growThetaTyVars )
import ETA.TypeCheck.TcBinds( tcRecSelBinds )
import ETA.TypeCheck.TcTyDecls
import ETA.TypeCheck.TcClassDcl
import ETA.TypeCheck.TcHsType
import ETA.TypeCheck.TcMType
import ETA.TypeCheck.TcType
import ETA.Prelude.TysWiredIn( unitTy )
import ETA.TypeCheck.FamInst
import ETA.Types.FamInstEnv( isDominatedBy, mkCoAxBranch, mkBranchedCoAxiom )
import ETA.Types.Coercion( pprCoAxBranch, ltRole )
import ETA.Types.Type
import ETA.Types.TypeRep -- for checkValidRoles
import ETA.Types.Kind
import ETA.Types.Class
import ETA.Types.CoAxiom
import ETA.Types.TyCon
import ETA.BasicTypes.DataCon
import ETA.BasicTypes.Id
import ETA.Core.MkCore ( rEC_SEL_ERROR_ID )
import ETA.BasicTypes.IdInfo
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.Module
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.NameEnv
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.Maybes
import ETA.Types.Unify
import ETA.Utils.Util
import ETA.BasicTypes.SrcLoc
import ETA.Utils.ListSetOps
import ETA.Utils.Digraph
import ETA.Main.DynFlags
import ETA.Utils.FastString
import ETA.BasicTypes.Unique ( mkBuiltinUnique )
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Bag
import Control.Monad
import Data.List
{-
************************************************************************
* *
\subsection{Type checking for type and class declarations}
* *
************************************************************************
Note [Grouping of type and class declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tcTyAndClassDecls is called on a list of `TyClGroup`s. Each group is a strongly
connected component of mutually dependent types and classes. We kind check and
type check each group separately to enhance kind polymorphism. Take the
following example:
type Id a = a
data X = X (Id Int)
If we were to kind check the two declarations together, we would give Id the
kind * -> *, since we apply it to an Int in the definition of X. But we can do
better than that, since Id really is kind polymorphic, and should get kind
forall (k::BOX). k -> k. Since it does not depend on anything else, it can be
kind-checked by itself, hence getting the most general kind. We then kind check
X, which works fine because we then know the polymorphic kind of Id, and simply
instantiate k to *.
Note [Check role annotations in a second pass]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Role inference potentially depends on the types of all of the datacons declared
in a mutually recursive group. The validity of a role annotation, in turn,
depends on the result of role inference. Because the types of datacons might
be ill-formed (see #7175 and Note [Checking GADT return types]) we must check
*all* the tycons in a group for validity before checking *any* of the roles.
Thus, we take two passes over the resulting tycons, first checking for general
validity and then checking for valid role annotations.
-}
tcTyAndClassDecls :: ModDetails
-> [TyClGroup Name] -- Mutually-recursive groups in dependency order
-> TcM TcGblEnv -- Input env extended by types and classes
-- and their implicit Ids,DataCons
-- Fails if there are any errors
tcTyAndClassDecls boot_details tyclds_s
= checkNoErrs $ -- The code recovers internally, but if anything gave rise to
-- an error we'd better stop now, to avoid a cascade
fold_env tyclds_s -- Type check each group in dependency order folding the global env
where
fold_env :: [TyClGroup Name] -> TcM TcGblEnv
fold_env [] = getGblEnv
fold_env (tyclds:tyclds_s)
= do { tcg_env <- tcTyClGroup boot_details tyclds
; setGblEnv tcg_env $ fold_env tyclds_s }
-- remaining groups are typecheck in the extended global env
tcTyClGroup :: ModDetails -> TyClGroup Name -> TcM TcGblEnv
-- Typecheck one strongly-connected component of type and class decls
tcTyClGroup boot_details tyclds
= do { -- Step 1: kind-check this group and returns the final
-- (possibly-polymorphic) kind of each TyCon and Class
-- See Note [Kind checking for type and class decls]
names_w_poly_kinds <- kcTyClGroup tyclds
; traceTc "tcTyAndCl generalized kinds" (ppr names_w_poly_kinds)
-- Step 2: type-check all groups together, returning
-- the final TyCons and Classes
; let role_annots = extractRoleAnnots tyclds
decls = group_tyclds tyclds
; tyclss <- fixM $ \ rec_tyclss -> do
{ is_boot <- tcIsHsBootOrSig
; let rec_flags = calcRecFlags boot_details is_boot
role_annots rec_tyclss
-- Populate environment with knot-tied ATyCon for TyCons
-- NB: if the decls mention any ill-staged data cons
-- (see Note [Recusion and promoting data constructors]
-- we will have failed already in kcTyClGroup, so no worries here
; tcExtendRecEnv (zipRecTyClss names_w_poly_kinds rec_tyclss) $
-- Also extend the local type envt with bindings giving
-- the (polymorphic) kind of each knot-tied TyCon or Class
-- See Note [Type checking recursive type and class declarations]
tcExtendKindEnv names_w_poly_kinds $
-- Kind and type check declarations for this group
concatMapM (tcTyClDecl rec_flags) decls }
-- Step 3: Perform the validity check
-- We can do this now because we are done with the recursive knot
-- Do it before Step 4 (adding implicit things) because the latter
-- expects well-formed TyCons
; tcExtendGlobalEnv tyclss $ do
{ traceTc "Starting validity check" (ppr tyclss)
; checkNoErrs $
mapM_ (recoverM (return ()) . checkValidTyCl) tyclss
-- We recover, which allows us to report multiple validity errors
-- the checkNoErrs is necessary to fix #7175.
; mapM_ (recoverM (return ()) . checkValidRoleAnnots role_annots) tyclss
-- See Note [Check role annotations in a second pass]
-- Step 4: Add the implicit things;
-- we want them in the environment because
-- they may be mentioned in interface files
; tcExtendGlobalValEnv (mkDefaultMethodIds tyclss) $
tcAddImplicits tyclss } }
tcAddImplicits :: [TyThing] -> TcM TcGblEnv
tcAddImplicits tyclss
= tcExtendGlobalEnvImplicit implicit_things $
tcRecSelBinds rec_sel_binds
where
implicit_things = concatMap implicitTyThings tyclss
rec_sel_binds = mkRecSelBinds tyclss
zipRecTyClss :: [(Name, Kind)]
-> [TyThing] -- Knot-tied
-> [(Name,TyThing)]
-- Build a name-TyThing mapping for the things bound by decls
-- being careful not to look at the [TyThing]
-- The TyThings in the result list must have a visible ATyCon,
-- because typechecking types (in, say, tcTyClDecl) looks at this outer constructor
zipRecTyClss kind_pairs rec_things
= [ (name, ATyCon (get name)) | (name, _kind) <- kind_pairs ]
where
rec_type_env :: TypeEnv
rec_type_env = mkTypeEnv rec_things
get name = case lookupTypeEnv rec_type_env name of
Just (ATyCon tc) -> tc
other -> pprPanic "zipRecTyClss" (ppr name <+> ppr other)
{-
************************************************************************
* *
Kind checking
* *
************************************************************************
Note [Kind checking for type and class decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kind checking is done thus:
1. Make up a kind variable for each parameter of the *data* type, class,
and closed type family decls, and extend the kind environment (which is
in the TcLclEnv)
2. Dependency-analyse the type *synonyms* (which must be non-recursive),
and kind-check them in dependency order. Extend the kind envt.
3. Kind check the data type and class decls
Synonyms are treated differently to data type and classes,
because a type synonym can be an unboxed type
type Foo = Int#
and a kind variable can't unify with UnboxedTypeKind
So we infer their kinds in dependency order
We need to kind check all types in the mutually recursive group
before we know the kind of the type variables. For example:
class C a where
op :: D b => a -> b -> b
class D c where
bop :: (Monad c) => ...
Here, the kind of the locally-polymorphic type variable "b"
depends on *all the uses of class D*. For example, the use of
Monad c in bop's type signature means that D must have kind Type->Type.
However type synonyms work differently. They can have kinds which don't
just involve (->) and *:
type R = Int# -- Kind #
type S a = Array# a -- Kind * -> #
type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
So we must infer their kinds from their right-hand sides *first* and then
use them, whereas for the mutually recursive data types D we bring into
scope kind bindings D -> k, where k is a kind variable, and do inference.
Open type families
~~~~~~~~~~~~~~~~~~
This treatment of type synonyms only applies to Haskell 98-style synonyms.
General type functions can be recursive, and hence, appear in `alg_decls'.
The kind of an open type family is solely determinded by its kind signature;
hence, only kind signatures participate in the construction of the initial
kind environment (as constructed by `getInitialKind'). In fact, we ignore
instances of families altogether in the following. However, we need to include
the kinds of *associated* families into the construction of the initial kind
environment. (This is handled by `allDecls').
-}
kcTyClGroup :: TyClGroup Name -> TcM [(Name,Kind)]
-- Kind check this group, kind generalize, and return the resulting local env
-- This bindds the TyCons and Classes of the group, but not the DataCons
-- See Note [Kind checking for type and class decls]
kcTyClGroup (TyClGroup { group_tyclds = decls })
= do { mod <- getModule
; traceTc "kcTyClGroup" (ptext (sLit "module") <+> ppr mod $$ vcat (map ppr decls))
-- Kind checking;
-- 1. Bind kind variables for non-synonyms
-- 2. Kind-check synonyms, and bind kinds of those synonyms
-- 3. Kind-check non-synonyms
-- 4. Generalise the inferred kinds
-- See Note [Kind checking for type and class decls]
-- Step 1: Bind kind variables for non-synonyms
; let (syn_decls, non_syn_decls) = partition (isSynDecl . unLoc) decls
; initial_kinds <- getInitialKinds non_syn_decls
; traceTc "kcTyClGroup: initial kinds" (ppr initial_kinds)
-- Step 2: Set initial envt, kind-check the synonyms
; lcl_env <- tcExtendKindEnv2 initial_kinds $
kcSynDecls (calcSynCycles syn_decls)
-- Step 3: Set extended envt, kind-check the non-synonyms
; setLclEnv lcl_env $
mapM_ kcLTyClDecl non_syn_decls
-- Step 4: generalisation
-- Kind checking done for this group
-- Now we have to kind generalize the flexis
; res <- concatMapM (generaliseTCD (tcl_env lcl_env)) decls
; traceTc "kcTyClGroup result" (ppr res)
; return res }
where
generalise :: TcTypeEnv -> Name -> TcM (Name, Kind)
-- For polymorphic things this is a no-op
generalise kind_env name
= do { let kc_kind = case lookupNameEnv kind_env name of
Just (AThing k) -> k
_ -> pprPanic "kcTyClGroup" (ppr name $$ ppr kind_env)
; kvs <- kindGeneralize (tyVarsOfType kc_kind)
; kc_kind' <- zonkTcKind kc_kind -- Make sure kc_kind' has the final,
-- skolemised kind variables
; traceTc "Generalise kind" (vcat [ ppr name, ppr kc_kind, ppr kvs, ppr kc_kind' ])
; return (name, mkForAllTys kvs kc_kind') }
generaliseTCD :: TcTypeEnv -> LTyClDecl Name -> TcM [(Name, Kind)]
generaliseTCD kind_env (L _ decl)
| ClassDecl { tcdLName = (L _ name), tcdATs = ats } <- decl
= do { first <- generalise kind_env name
; rest <- mapM ((generaliseFamDecl kind_env) . unLoc) ats
; return (first : rest) }
| FamDecl { tcdFam = fam } <- decl
= do { res <- generaliseFamDecl kind_env fam
; return [res] }
| otherwise
= do { res <- generalise kind_env (tcdName decl)
; return [res] }
generaliseFamDecl :: TcTypeEnv -> FamilyDecl Name -> TcM (Name, Kind)
generaliseFamDecl kind_env (FamilyDecl { fdLName = L _ name })
= generalise kind_env name
mk_thing_env :: [LTyClDecl Name] -> [(Name, TcTyThing)]
mk_thing_env [] = []
mk_thing_env (decl : decls)
| L _ (ClassDecl { tcdLName = L _ nm, tcdATs = ats }) <- decl
= (nm, APromotionErr ClassPE) :
(map (, APromotionErr TyConPE) $ map (unLoc . fdLName . unLoc) ats) ++
(mk_thing_env decls)
| otherwise
= (tcdName (unLoc decl), APromotionErr TyConPE) :
(mk_thing_env decls)
getInitialKinds :: [LTyClDecl Name] -> TcM [(Name, TcTyThing)]
getInitialKinds decls
= tcExtendKindEnv2 (mk_thing_env decls) $
do { pairss <- mapM (addLocM getInitialKind) decls
; return (concat pairss) }
getInitialKind :: TyClDecl Name -> TcM [(Name, TcTyThing)]
-- Allocate a fresh kind variable for each TyCon and Class
-- For each tycon, return (tc, AThing k)
-- where k is the kind of tc, derived from the LHS
-- of the definition (and probably including
-- kind unification variables)
-- Example: data T a b = ...
-- return (T, kv1 -> kv2 -> kv3)
--
-- This pass deals with (ie incorporates into the kind it produces)
-- * The kind signatures on type-variable binders
-- * The result kinds signature on a TyClDecl
--
-- ALSO for each datacon, return (dc, APromotionErr RecDataConPE)
-- Note [ARecDataCon: Recursion and promoting data constructors]
--
-- No family instances are passed to getInitialKinds
getInitialKind decl@(ClassDecl { tcdLName = L _ name, tcdTyVars = ktvs, tcdATs = ats })
= do { (cl_kind, inner_prs) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) ktvs $
do { inner_prs <- getFamDeclInitialKinds ats
; return (constraintKind, inner_prs) }
; let main_pr = (name, AThing cl_kind)
; return (main_pr : inner_prs) }
getInitialKind decl@(DataDecl { tcdLName = L _ name
, tcdTyVars = ktvs
, tcdDataDefn = HsDataDefn { dd_kindSig = m_sig
, dd_cons = cons' } })
= let cons = cons' -- AZ list monad coming
in
do { (decl_kind, _) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) ktvs $
do { res_k <- case m_sig of
Just ksig -> tcLHsKind ksig
Nothing -> return liftedTypeKind
; return (res_k, ()) }
; let main_pr = (name, AThing decl_kind)
inner_prs = [ (unLoc con, APromotionErr RecDataConPE)
| L _ con' <- cons, con <- con_names con' ]
; return (main_pr : inner_prs) }
getInitialKind (FamDecl { tcdFam = decl })
= getFamDeclInitialKind decl
getInitialKind decl@(SynDecl {})
= pprPanic "getInitialKind" (ppr decl)
---------------------------------
getFamDeclInitialKinds :: [LFamilyDecl Name] -> TcM [(Name, TcTyThing)]
getFamDeclInitialKinds decls
= tcExtendKindEnv2 [ (n, APromotionErr TyConPE)
| L _ (FamilyDecl { fdLName = L _ n }) <- decls] $
concatMapM (addLocM getFamDeclInitialKind) decls
getFamDeclInitialKind :: FamilyDecl Name
-> TcM [(Name, TcTyThing)]
getFamDeclInitialKind decl@(FamilyDecl { fdLName = L _ name
, fdTyVars = ktvs
, fdKindSig = ksig })
= do { (fam_kind, _) <-
kcHsTyVarBndrs (famDeclHasCusk decl) ktvs $
do { res_k <- case ksig of
Just k -> tcLHsKind k
Nothing
| famDeclHasCusk decl -> return liftedTypeKind
| otherwise -> newMetaKindVar
; return (res_k, ()) }
; return [ (name, AThing fam_kind) ] }
----------------
kcSynDecls :: [SCC (LTyClDecl Name)]
-> TcM TcLclEnv -- Kind bindings
kcSynDecls [] = getLclEnv
kcSynDecls (group : groups)
= do { (n,k) <- kcSynDecl1 group
; lcl_env <- tcExtendKindEnv [(n,k)] (kcSynDecls groups)
; return lcl_env }
kcSynDecl1 :: SCC (LTyClDecl Name)
-> TcM (Name,TcKind) -- Kind bindings
kcSynDecl1 (AcyclicSCC (L _ decl)) = kcSynDecl decl
kcSynDecl1 (CyclicSCC decls) = do { recSynErr decls; failM }
-- Fail here to avoid error cascade
-- of out-of-scope tycons
kcSynDecl :: TyClDecl Name -> TcM (Name, TcKind)
kcSynDecl decl@(SynDecl { tcdTyVars = hs_tvs, tcdLName = L _ name
, tcdRhs = rhs })
-- Returns a possibly-unzonked kind
= tcAddDeclCtxt decl $
do { (syn_kind, _) <-
kcHsTyVarBndrs (hsDeclHasCusk decl) hs_tvs $
do { traceTc "kcd1" (ppr name <+> brackets (ppr hs_tvs))
; (_, rhs_kind) <- tcLHsType rhs
; traceTc "kcd2" (ppr name)
; return (rhs_kind, ()) }
; return (name, syn_kind) }
kcSynDecl decl = pprPanic "kcSynDecl" (ppr decl)
------------------------------------------------------------------------
kcLTyClDecl :: LTyClDecl Name -> TcM ()
-- See Note [Kind checking for type and class decls]
kcLTyClDecl (L loc decl)
= setSrcSpan loc $ tcAddDeclCtxt decl $ kcTyClDecl decl
kcTyClDecl :: TyClDecl Name -> TcM ()
-- This function is used solely for its side effect on kind variables
-- NB kind signatures on the type variables and
-- result kind signature have aready been dealt with
-- by getInitialKind, so we can ignore them here.
kcTyClDecl (DataDecl { tcdLName = L _ name, tcdTyVars = hs_tvs, tcdDataDefn = defn })
| HsDataDefn { dd_cons = cons, dd_kindSig = Just _ } <- defn
= mapM_ (wrapLocM kcConDecl) cons
-- hs_tvs and dd_kindSig already dealt with in getInitialKind
-- If dd_kindSig is Just, this must be a GADT-style decl,
-- (see invariants of DataDefn declaration)
-- so (a) we don't need to bring the hs_tvs into scope, because the
-- ConDecls bind all their own variables
-- (b) dd_ctxt is not allowed for GADT-style decls, so we can ignore it
| HsDataDefn { dd_ctxt = ctxt, dd_cons = cons } <- defn
= kcTyClTyVars name hs_tvs $
do { _ <- tcHsContext ctxt
; mapM_ (wrapLocM kcConDecl) cons }
kcTyClDecl decl@(SynDecl {}) = pprPanic "kcTyClDecl" (ppr decl)
kcTyClDecl (ClassDecl { tcdLName = L _ name, tcdTyVars = hs_tvs
, tcdCtxt = ctxt, tcdSigs = sigs })
= kcTyClTyVars name hs_tvs $
do { _ <- tcHsContext ctxt
; mapM_ (wrapLocM kc_sig) sigs }
where
kc_sig (TypeSig _ op_ty _) = discardResult (tcHsLiftedType op_ty)
kc_sig (GenericSig _ op_ty) = discardResult (tcHsLiftedType op_ty)
kc_sig _ = return ()
-- closed type families look at their equations, but other families don't
-- do anything here
kcTyClDecl (FamDecl (FamilyDecl { fdLName = L _ fam_tc_name
, fdTyVars = hs_tvs
, fdInfo = ClosedTypeFamily eqns }))
= do { tc_kind <- kcLookupKind fam_tc_name
; let fam_tc_shape = ( fam_tc_name, length (hsQTvBndrs hs_tvs), tc_kind)
; mapM_ (kcTyFamInstEqn fam_tc_shape) eqns }
kcTyClDecl (FamDecl {}) = return ()
-------------------
kcConDecl :: ConDecl Name -> TcM ()
kcConDecl (ConDecl { con_names = names, con_qvars = ex_tvs
, con_cxt = ex_ctxt, con_details = details
, con_res = res })
= addErrCtxt (dataConCtxtName names) $
-- the 'False' says that the existentials don't have a CUSK, as the
-- concept doesn't really apply here. We just need to bring the variables
-- into scope!
do { _ <- kcHsTyVarBndrs False ex_tvs $
do { _ <- tcHsContext ex_ctxt
; mapM_ (tcHsOpenType . getBangType) (hsConDeclArgTys details)
; _ <- tcConRes res
; return (panic "kcConDecl", ()) }
; return () }
{-
Note [Recursion and promoting data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't want to allow promotion in a strongly connected component
when kind checking.
Consider:
data T f = K (f (K Any))
When kind checking the `data T' declaration the local env contains the
mappings:
T -> AThing <some initial kind>
K -> ARecDataCon
ANothing is only used for DataCons, and only used during type checking
in tcTyClGroup.
************************************************************************
* *
\subsection{Type checking}
* *
************************************************************************
Note [Type checking recursive type and class declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At this point we have completed *kind-checking* of a mutually
recursive group of type/class decls (done in kcTyClGroup). However,
we discarded the kind-checked types (eg RHSs of data type decls);
note that kcTyClDecl returns (). There are two reasons:
* It's convenient, because we don't have to rebuild a
kinded HsDecl (a fairly elaborate type)
* It's necessary, because after kind-generalisation, the
TyCons/Classes may now be kind-polymorphic, and hence need
to be given kind arguments.
Example:
data T f a = MkT (f a) (T f a)
During kind-checking, we give T the kind T :: k1 -> k2 -> *
and figure out constraints on k1, k2 etc. Then we generalise
to get T :: forall k. (k->*) -> k -> *
So now the (T f a) in the RHS must be elaborated to (T k f a).
However, during tcTyClDecl of T (above) we will be in a recursive
"knot". So we aren't allowed to look at the TyCon T itself; we are only
allowed to put it (lazily) in the returned structures. But when
kind-checking the RHS of T's decl, we *do* need to know T's kind (so
that we can correctly elaboarate (T k f a). How can we get T's kind
without looking at T? Delicate answer: during tcTyClDecl, we extend
*Global* env with T -> ATyCon (the (not yet built) TyCon for T)
*Local* env with T -> AThing (polymorphic kind of T)
Then:
* During TcHsType.kcTyVar we look in the *local* env, to get the
known kind for T.
* But in TcHsType.ds_type (and ds_var_app in particular) we look in
the *global* env to get the TyCon. But we must be careful not to
force the TyCon or we'll get a loop.
This fancy footwork (with two bindings for T) is only necesary for the
TyCons or Classes of this recursive group. Earlier, finished groups,
live in the global env only.
-}
tcTyClDecl :: RecTyInfo -> LTyClDecl Name -> TcM [TyThing]
tcTyClDecl rec_info (L loc decl)
= setSrcSpan loc $ tcAddDeclCtxt decl $
traceTc "tcTyAndCl-x" (ppr decl) >>
tcTyClDecl1 NoParentTyCon rec_info decl
-- "type family" declarations
tcTyClDecl1 :: TyConParent -> RecTyInfo -> TyClDecl Name -> TcM [TyThing]
tcTyClDecl1 parent _rec_info (FamDecl { tcdFam = fd })
= tcFamDecl1 parent fd
-- "type" synonym declaration
tcTyClDecl1 _parent rec_info
(SynDecl { tcdLName = L _ tc_name, tcdTyVars = tvs, tcdRhs = rhs })
= --ASSERT( isNoParent _parent )
tcTyClTyVars tc_name tvs $ \ tvs' kind ->
tcTySynRhs rec_info tc_name tvs' kind rhs
-- "data/newtype" declaration
tcTyClDecl1 _parent rec_info
(DataDecl { tcdLName = L _ tc_name, tcdTyVars = tvs, tcdDataDefn = defn })
= --ASSERT( isNoParent _parent )
tcTyClTyVars tc_name tvs $ \ tvs' kind ->
tcDataDefn rec_info tc_name tvs' kind defn
tcTyClDecl1 _parent rec_info
(ClassDecl { tcdLName = L _ class_name, tcdTyVars = tvs
, tcdCtxt = ctxt, tcdMeths = meths
, tcdFDs = fundeps, tcdSigs = sigs
, tcdATs = ats, tcdATDefs = at_defs })
= --ASSERT( isNoParent _parent )
do { (clas, tvs', gen_dm_env) <- fixM $ \ ~(clas,_,_) ->
tcTyClTyVars class_name tvs $ \ tvs' kind ->
do { --MASSERT( isConstraintKind kind )
-- This little knot is just so we can get
-- hold of the name of the class TyCon, which we
-- need to look up its recursiveness
; let tycon_name = tyConName (classTyCon clas)
tc_isrec = rti_is_rec rec_info tycon_name
roles = rti_roles rec_info tycon_name
; ctxt' <- tcHsContext ctxt
; ctxt' <- zonkTcTypeToTypes emptyZonkEnv ctxt'
-- Squeeze out any kind unification variables
; fds' <- mapM (addLocM tc_fundep) fundeps
; (sig_stuff, gen_dm_env) <- tcClassSigs class_name sigs meths
; at_stuff <- tcClassATs class_name (AssocFamilyTyCon clas) ats at_defs
; mindef <- tcClassMinimalDef class_name sigs sig_stuff
; clas <- buildClass
class_name tvs' roles ctxt' fds' at_stuff
sig_stuff mindef tc_isrec
; traceTc "tcClassDecl" (ppr fundeps $$ ppr tvs' $$ ppr fds')
; return (clas, tvs', gen_dm_env) }
; let { gen_dm_ids = [ AnId (mkExportedLocalId VanillaId gen_dm_name gen_dm_ty)
| (sel_id, GenDefMeth gen_dm_name) <- classOpItems clas
, let gen_dm_tau = expectJust "tcTyClDecl1" $
lookupNameEnv gen_dm_env (idName sel_id)
, let gen_dm_ty = mkSigmaTy tvs'
[mkClassPred clas (mkTyVarTys tvs')]
gen_dm_tau
]
; class_ats = map ATyCon (classATs clas) }
; return (ATyCon (classTyCon clas) : gen_dm_ids ++ class_ats ) }
-- NB: Order is important due to the call to `mkGlobalThings' when
-- tying the the type and class declaration type checking knot.
where
tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM (tc_fd_tyvar . unLoc) tvs1 ;
; tvs2' <- mapM (tc_fd_tyvar . unLoc) tvs2 ;
; return (tvs1', tvs2') }
tc_fd_tyvar name -- Scoped kind variables are bound to unification variables
-- which are now fixed, so we can zonk
= do { tv <- tcLookupTyVar name
; ty <- zonkTyVarOcc emptyZonkEnv tv
-- Squeeze out any kind unification variables
; case getTyVar_maybe ty of
Just tv' -> return tv'
Nothing -> pprPanic "tc_fd_tyvar" (ppr name $$ ppr tv $$ ppr ty) }
tcFamDecl1 :: TyConParent -> FamilyDecl Name -> TcM [TyThing]
tcFamDecl1 parent
(FamilyDecl {fdInfo = OpenTypeFamily, fdLName = L _ tc_name, fdTyVars = tvs})
= tcTyClTyVars tc_name tvs $ \ tvs' kind -> do
{ traceTc "open type family:" (ppr tc_name)
; checkFamFlag tc_name
; tycon <- buildFamilyTyCon tc_name tvs' OpenSynFamilyTyCon kind parent
; return [ATyCon tycon] }
tcFamDecl1 parent
(FamilyDecl { fdInfo = ClosedTypeFamily eqns
, fdLName = lname@(L _ tc_name), fdTyVars = tvs })
-- Closed type families are a little tricky, because they contain the definition
-- of both the type family and the equations for a CoAxiom.
-- Note: eqns might be empty, in a hs-boot file!
= do { traceTc "closed type family:" (ppr tc_name)
-- the variables in the header have no scope:
; (tvs', kind) <- tcTyClTyVars tc_name tvs $ \ tvs' kind ->
return (tvs', kind)
; checkFamFlag tc_name -- make sure we have -XTypeFamilies
-- Process the equations, creating CoAxBranches
; tc_kind <- kcLookupKind tc_name
; let fam_tc_shape = (tc_name, length (hsQTvBndrs tvs), tc_kind)
; branches <- mapM (tcTyFamInstEqn fam_tc_shape) eqns
-- we need the tycon that we will be creating, but it's in scope.
-- just look it up.
; fam_tc <- tcLookupLocatedTyCon lname
-- create a CoAxiom, with the correct src location. It is Vitally
-- Important that we do not pass the branches into
-- newFamInstAxiomName. They have types that have been zonked inside
-- the knot and we will die if we look at them. This is OK here
-- because there will only be one axiom, so we don't need to
-- differentiate names.
-- See [Zonking inside the knot] in TcHsType
; loc <- getSrcSpanM
; co_ax_name <- newFamInstAxiomName loc tc_name []
-- mkBranchedCoAxiom will fail on an empty list of branches, but
-- we'll never look at co_ax in this case
; let co_ax = mkBranchedCoAxiom co_ax_name fam_tc branches
-- now, finally, build the TyCon
; let syn_rhs = if null eqns
then AbstractClosedSynFamilyTyCon
else ClosedSynFamilyTyCon co_ax
; tycon <- buildFamilyTyCon tc_name tvs' syn_rhs kind parent
; let result = if null eqns
then [ATyCon tycon]
else [ATyCon tycon, ACoAxiom co_ax]
; return result }
-- We check for instance validity later, when doing validity checking for
-- the tycon
tcFamDecl1 parent
(FamilyDecl {fdInfo = DataFamily, fdLName = L _ tc_name, fdTyVars = tvs})
= tcTyClTyVars tc_name tvs $ \ tvs' kind -> do
{ traceTc "data family:" (ppr tc_name)
; checkFamFlag tc_name
; extra_tvs <- tcDataKindSig kind
; let final_tvs = tvs' ++ extra_tvs -- we may not need these
roles = map (const Nominal) final_tvs
tycon = buildAlgTyCon tc_name final_tvs roles Nothing []
DataFamilyTyCon Recursive
False -- Not promotable to the kind level
True -- GADT syntax
parent
; return [ATyCon tycon] }
tcTySynRhs :: RecTyInfo
-> Name
-> [TyVar] -> Kind
-> LHsType Name -> TcM [TyThing]
tcTySynRhs rec_info tc_name tvs kind hs_ty
= do { env <- getLclEnv
; traceTc "tc-syn" (ppr tc_name $$ ppr (tcl_env env))
; rhs_ty <- tcCheckLHsType hs_ty kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; let roles = rti_roles rec_info tc_name
; tycon <- buildSynonymTyCon tc_name tvs roles rhs_ty kind
; return [ATyCon tycon] }
tcDataDefn :: RecTyInfo -> Name
-> [TyVar] -> Kind
-> HsDataDefn Name -> TcM [TyThing]
-- NB: not used for newtype/data instances (whether associated or not)
tcDataDefn rec_info tc_name tvs kind
(HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = ctxt, dd_kindSig = mb_ksig
, dd_cons = cons' })
= let cons = cons' -- AZ List monad coming
in do { extra_tvs <- tcDataKindSig kind
; let final_tvs = tvs ++ extra_tvs
roles = rti_roles rec_info tc_name
; stupid_tc_theta <- tcHsContext ctxt
; stupid_theta <- zonkTcTypeToTypes emptyZonkEnv stupid_tc_theta
; kind_signatures <- xoptM Opt_KindSignatures
; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
-- Check that we don't use kind signatures without Glasgow extensions
; case mb_ksig of
Nothing -> return ()
Just hs_k -> do { checkTc (kind_signatures) (badSigTyDecl tc_name)
; tc_kind <- tcLHsKind hs_k
; checkKind kind tc_kind
; return () }
; gadt_syntax <- dataDeclChecks tc_name new_or_data stupid_theta cons
; tycon <- fixM $ \ tycon -> do
{ let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
; data_cons <- tcConDecls new_or_data tycon (final_tvs, res_ty) cons
; tc_rhs <-
if null cons && is_boot -- In a hs-boot file, empty cons means
then return totallyAbstractTyConRhs -- "don't know"; hence totally Abstract
else case new_or_data of
DataType -> return (mkDataTyConRhs data_cons)
NewType -> --ASSERT( not (null data_cons) )
mkNewTyConRhs tc_name tycon (head data_cons)
; return (buildAlgTyCon tc_name final_tvs roles (fmap unLoc cType)
stupid_theta tc_rhs
(rti_is_rec rec_info tc_name)
(rti_promotable rec_info)
gadt_syntax NoParentTyCon) }
; return [ATyCon tycon] }
{-
************************************************************************
* *
Typechecking associated types (in class decls)
(including the associated-type defaults)
* *
************************************************************************
Note [Associated type defaults]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following is an example of associated type defaults:
class C a where
data D a
type F a b :: *
type F a Z = [a] -- Default
type F a (S n) = F a n -- Default
Note that:
- We can have more than one default definition for a single associated type,
as long as they do not overlap (same rules as for instances)
- We can get default definitions only for type families, not data families
-}
tcClassATs :: Name -- The class name (not knot-tied)
-> TyConParent -- The class parent of this associated type
-> [LFamilyDecl Name] -- Associated types.
-> [LTyFamDefltEqn Name] -- Associated type defaults.
-> TcM [ClassATItem]
tcClassATs class_name parent ats at_defs
= do { -- Complain about associated type defaults for non associated-types
sequence_ [ failWithTc (badATErr class_name n)
| n <- map at_def_tycon at_defs
, not (n `elemNameSet` at_names) ]
; mapM tc_at ats }
where
at_def_tycon :: LTyFamDefltEqn Name -> Name
at_def_tycon (L _ eqn) = unLoc (tfe_tycon eqn)
at_fam_name :: LFamilyDecl Name -> Name
at_fam_name (L _ decl) = unLoc (fdLName decl)
at_names = mkNameSet (map at_fam_name ats)
at_defs_map :: NameEnv [LTyFamDefltEqn Name]
-- Maps an AT in 'ats' to a list of all its default defs in 'at_defs'
at_defs_map = foldr (\at_def nenv -> extendNameEnv_C (++) nenv
(at_def_tycon at_def) [at_def])
emptyNameEnv at_defs
tc_at at = do { [ATyCon fam_tc] <- addLocM (tcFamDecl1 parent) at
; let at_defs = lookupNameEnv at_defs_map (at_fam_name at)
`orElse` []
; atd <- tcDefaultAssocDecl fam_tc at_defs
; return (ATI fam_tc atd) }
-------------------------
tcDefaultAssocDecl :: TyCon -- ^ Family TyCon
-> [LTyFamDefltEqn Name] -- ^ Defaults
-> TcM (Maybe (Type, SrcSpan)) -- ^ Type checked RHS
tcDefaultAssocDecl _ []
= return Nothing -- No default declaration
tcDefaultAssocDecl _ (d1:_:_)
= failWithTc (ptext (sLit "More than one default declaration for")
<+> ppr (tfe_tycon (unLoc d1)))
tcDefaultAssocDecl fam_tc [L loc (TyFamEqn { tfe_tycon = L _ tc_name
, tfe_pats = hs_tvs
, tfe_rhs = rhs })]
= setSrcSpan loc $
tcAddFamInstCtxt (ptext (sLit "default type instance")) tc_name $
tcTyClTyVars tc_name hs_tvs $ \ tvs rhs_kind ->
do { traceTc "tcDefaultAssocDecl" (ppr tc_name)
; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
; let (fam_name, fam_pat_arity, _) = famTyConShape fam_tc
; --ASSERT( fam_name == tc_name )
checkTc (length (hsQTvBndrs hs_tvs) == fam_pat_arity)
(wrongNumberOfParmsErr fam_pat_arity)
; rhs_ty <- tcCheckLHsType rhs rhs_kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; let fam_tc_tvs = tyConTyVars fam_tc
subst = zipTopTvSubst tvs (mkTyVarTys fam_tc_tvs)
; return ( --ASSERT( equalLength fam_tc_tvs tvs )
Just (substTy subst rhs_ty, loc) ) }
-- We check for well-formedness and validity later, in checkValidClass
-------------------------
kcTyFamInstEqn :: FamTyConShape -> LTyFamInstEqn Name -> TcM ()
kcTyFamInstEqn fam_tc_shape
(L loc (TyFamEqn { tfe_pats = pats, tfe_rhs = hs_ty }))
= setSrcSpan loc $
discardResult $
tc_fam_ty_pats fam_tc_shape pats (discardResult . (tcCheckLHsType hs_ty))
tcTyFamInstEqn :: FamTyConShape -> LTyFamInstEqn Name -> TcM CoAxBranch
-- Needs to be here, not in TcInstDcls, because closed families
-- (typechecked here) have TyFamInstEqns
tcTyFamInstEqn fam_tc_shape@(fam_tc_name,_,_)
(L loc (TyFamEqn { tfe_tycon = L _ eqn_tc_name
, tfe_pats = pats
, tfe_rhs = hs_ty }))
= setSrcSpan loc $
tcFamTyPats fam_tc_shape pats (discardResult . (tcCheckLHsType hs_ty)) $
\tvs' pats' res_kind ->
do { checkTc (fam_tc_name == eqn_tc_name)
(wrongTyFamName fam_tc_name eqn_tc_name)
; rhs_ty <- tcCheckLHsType hs_ty res_kind
; rhs_ty <- zonkTcTypeToType emptyZonkEnv rhs_ty
; traceTc "tcTyFamInstEqn" (ppr fam_tc_name <+> ppr tvs')
-- don't print out the pats here, as they might be zonked inside the knot
; return (mkCoAxBranch tvs' pats' rhs_ty loc) }
kcDataDefn :: HsDataDefn Name -> TcKind -> TcM ()
-- Used for 'data instance' only
-- Ordinary 'data' is handled by kcTyClDec
kcDataDefn (HsDataDefn { dd_ctxt = ctxt, dd_cons = cons, dd_kindSig = mb_kind }) res_k
= do { _ <- tcHsContext ctxt
; checkNoErrs $ mapM_ (wrapLocM kcConDecl) cons
-- See Note [Failing early in kcDataDefn]
; kcResultKind mb_kind res_k }
------------------
kcResultKind :: Maybe (LHsKind Name) -> Kind -> TcM ()
kcResultKind Nothing res_k
= checkKind res_k liftedTypeKind
-- type family F a
-- defaults to type family F a :: *
kcResultKind (Just k) res_k
= do { k' <- tcLHsKind k
; checkKind k' res_k }
{-
Kind check type patterns and kind annotate the embedded type variables.
type instance F [a] = rhs
* Here we check that a type instance matches its kind signature, but we do
not check whether there is a pattern for each type index; the latter
check is only required for type synonym instances.
Note [tc_fam_ty_pats vs tcFamTyPats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tc_fam_ty_pats does the type checking of the patterns, but it doesn't
zonk or generate any desugaring. It is used when kind-checking closed
type families.
tcFamTyPats type checks the patterns, zonks, and then calls thing_inside
to generate a desugaring. It is used during type-checking (not kind-checking).
Note [Type-checking type patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When typechecking the patterns of a family instance declaration, we can't
rely on using the family TyCon, because this is sometimes called
from within a type-checking knot. (Specifically for closed type families.)
The type FamTyConShape gives just enough information to do the job.
The "arity" field of FamTyConShape is the *visible* arity of the family
type constructor, i.e. what the users sees and writes, not including kind
arguments.
See also Note [tc_fam_ty_pats vs tcFamTyPats]
Note [Failing early in kcDataDefn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to use checkNoErrs when calling kcConDecl. This is because kcConDecl
calls tcConDecl, which checks that the return type of a GADT-like constructor
is actually an instance of the type head. Without the checkNoErrs, potentially
two bad things could happen:
1) Duplicate error messages, because tcConDecl will be called again during
*type* checking (as opposed to kind checking)
2) If we just keep blindly forging forward after both kind checking and type
checking, we can get a panic in rejigConRes. See Trac #8368.
-}
-----------------
type FamTyConShape = (Name, Arity, Kind) -- See Note [Type-checking type patterns]
famTyConShape :: TyCon -> FamTyConShape
famTyConShape fam_tc
= ( tyConName fam_tc
, length (filterOut isKindVar (tyConTyVars fam_tc))
, tyConKind fam_tc )
tc_fam_ty_pats :: FamTyConShape
-> HsWithBndrs Name [LHsType Name] -- Patterns
-> (TcKind -> TcM ()) -- Kind checker for RHS
-- result is ignored
-> TcM ([Kind], [Type], Kind)
-- Check the type patterns of a type or data family instance
-- type instance F <pat1> <pat2> = <type>
-- The 'tyvars' are the free type variables of pats
--
-- NB: The family instance declaration may be an associated one,
-- nested inside an instance decl, thus
-- instance C [a] where
-- type F [a] = ...
-- In that case, the type variable 'a' will *already be in scope*
-- (and, if C is poly-kinded, so will its kind parameter).
tc_fam_ty_pats (name, arity, kind)
(HsWB { hswb_cts = arg_pats, hswb_kvs = kvars, hswb_tvs = tvars })
kind_checker
= do { let (fam_kvs, fam_body) = splitForAllTys kind
-- We wish to check that the pattern has the right number of arguments
-- in checkValidFamPats (in TcValidity), so we can do the check *after*
-- we're done with the knot. But, the splitKindFunTysN below will panic
-- if there are *too many* patterns. So, we do a preliminary check here.
-- Note that we don't have enough information at hand to do a full check,
-- as that requires the full declared arity of the family, which isn't
-- nearby.
; checkTc (length arg_pats == arity) $
wrongNumberOfParmsErr arity
-- Instantiate with meta kind vars
; fam_arg_kinds <- mapM (const newMetaKindVar) fam_kvs
; loc <- getSrcSpanM
; let (arg_kinds, res_kind)
= splitKindFunTysN (length arg_pats) $
substKiWith fam_kvs fam_arg_kinds fam_body
hs_tvs = HsQTvs { hsq_kvs = kvars
, hsq_tvs = userHsTyVarBndrs loc tvars }
-- Kind-check and quantify
-- See Note [Quantifying over family patterns]
; typats <- tcHsTyVarBndrs hs_tvs $ \ _ ->
do { kind_checker res_kind
; tcHsArgTys (quotes (ppr name)) arg_pats arg_kinds }
; return (fam_arg_kinds, typats, res_kind) }
-- See Note [tc_fam_ty_pats vs tcFamTyPats]
tcFamTyPats :: FamTyConShape
-> HsWithBndrs Name [LHsType Name] -- patterns
-> (TcKind -> TcM ()) -- kind-checker for RHS
-> ([TKVar] -- Kind and type variables
-> [TcType] -- Kind and type arguments
-> Kind -> TcM a)
-> TcM a
tcFamTyPats fam_shape@(name,_,_) pats kind_checker thing_inside
= do { (fam_arg_kinds, typats, res_kind)
<- tc_fam_ty_pats fam_shape pats kind_checker
; let all_args = fam_arg_kinds ++ typats
-- Find free variables (after zonking) and turn
-- them into skolems, so that we don't subsequently
-- replace a meta kind var with AnyK
-- Very like kindGeneralize
; qtkvs <- quantifyTyVars emptyVarSet (tyVarsOfTypes all_args)
-- Zonk the patterns etc into the Type world
; (ze, qtkvs') <- zonkTyBndrsX emptyZonkEnv qtkvs
; all_args' <- zonkTcTypeToTypes ze all_args
; res_kind' <- zonkTcTypeToType ze res_kind
; traceTc "tcFamTyPats" (ppr name)
-- don't print out too much, as we might be in the knot
; tcExtendTyVarEnv qtkvs' $
thing_inside qtkvs' all_args' res_kind' }
{-
Note [Quantifying over family patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to quantify over two different lots of kind variables:
First, the ones that come from the kinds of the tyvar args of
tcTyVarBndrsKindGen, as usual
data family Dist a
-- Proxy :: forall k. k -> *
data instance Dist (Proxy a) = DP
-- Generates data DistProxy = DP
-- ax8 k (a::k) :: Dist * (Proxy k a) ~ DistProxy k a
-- The 'k' comes from the tcTyVarBndrsKindGen (a::k)
Second, the ones that come from the kind argument of the type family
which we pick up using the (tyVarsOfTypes typats) in the result of
the thing_inside of tcHsTyvarBndrsGen.
-- Any :: forall k. k
data instance Dist Any = DA
-- Generates data DistAny k = DA
-- ax7 k :: Dist k (Any k) ~ DistAny k
-- The 'k' comes from kindGeneralizeKinds (Any k)
Note [Quantified kind variables of a family pattern]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider type family KindFam (p :: k1) (q :: k1)
data T :: Maybe k1 -> k2 -> *
type instance KindFam (a :: Maybe k) b = T a b -> Int
The HsBSig for the family patterns will be ([k], [a])
Then in the family instance we want to
* Bring into scope [ "k" -> k:BOX, "a" -> a:k ]
* Kind-check the RHS
* Quantify the type instance over k and k', as well as a,b, thus
type instance [k, k', a:Maybe k, b:k']
KindFam (Maybe k) k' a b = T k k' a b -> Int
Notice that in the third step we quantify over all the visibly-mentioned
type variables (a,b), but also over the implicitly mentioned kind variables
(k, k'). In this case one is bound explicitly but often there will be
none. The role of the kind signature (a :: Maybe k) is to add a constraint
that 'a' must have that kind, and to bring 'k' into scope.
************************************************************************
* *
Data types
* *
************************************************************************
-}
dataDeclChecks :: Name -> NewOrData -> ThetaType -> [LConDecl Name] -> TcM Bool
dataDeclChecks tc_name new_or_data stupid_theta cons
= do { -- Check that we don't use GADT syntax in H98 world
gadtSyntax_ok <- xoptM Opt_GADTSyntax
; let gadt_syntax = consUseGadtSyntax cons
; checkTc (gadtSyntax_ok || not gadt_syntax) (badGadtDecl tc_name)
-- Check that the stupid theta is empty for a GADT-style declaration
; checkTc (null stupid_theta || not gadt_syntax) (badStupidTheta tc_name)
-- Check that a newtype has exactly one constructor
-- Do this before checking for empty data decls, so that
-- we don't suggest -XEmptyDataDecls for newtypes
; checkTc (new_or_data == DataType || isSingleton cons)
(newtypeConError tc_name (length cons))
-- Check that there's at least one condecl,
-- or else we're reading an hs-boot file, or -XEmptyDataDecls
; empty_data_decls <- xoptM Opt_EmptyDataDecls
; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
; checkTc (not (null cons) || empty_data_decls || is_boot)
(emptyConDeclsErr tc_name)
; return gadt_syntax }
-----------------------------------
consUseGadtSyntax :: [LConDecl a] -> Bool
consUseGadtSyntax (L _ (ConDecl { con_res = ResTyGADT _ _ }) : _) = True
consUseGadtSyntax _ = False
-- All constructors have same shape
-----------------------------------
tcConDecls :: NewOrData -> TyCon -> ([TyVar], Type)
-> [LConDecl Name] -> TcM [DataCon]
tcConDecls new_or_data rep_tycon (tmpl_tvs, res_tmpl) cons
= concatMapM (addLocM $ tcConDecl new_or_data rep_tycon tmpl_tvs res_tmpl)
cons
tcConDecl :: NewOrData
-> TyCon -- Representation tycon
-> [TyVar] -> Type -- Return type template (with its template tyvars)
-- (tvs, T tys), where T is the family TyCon
-> ConDecl Name
-> TcM [DataCon]
tcConDecl new_or_data rep_tycon tmpl_tvs res_tmpl -- Data types
(ConDecl { con_names = names
, con_qvars = hs_tvs, con_cxt = hs_ctxt
, con_details = hs_details, con_res = hs_res_ty })
= addErrCtxt (dataConCtxtName names) $
do { traceTc "tcConDecl 1" (ppr names)
; (ctxt, arg_tys, res_ty, field_lbls, stricts)
<- tcHsTyVarBndrs hs_tvs $ \ _ ->
do { ctxt <- tcHsContext hs_ctxt
; details <- tcConArgs new_or_data hs_details
; res_ty <- tcConRes hs_res_ty
; let (field_lbls, btys) = details
(arg_tys, stricts) = unzip btys
; return (ctxt, arg_tys, res_ty, field_lbls, stricts)
}
-- Generalise the kind variables (returning quantified TcKindVars)
-- and quantify the type variables (substituting their kinds)
-- REMEMBER: 'tkvs' are:
-- ResTyH98: the *existential* type variables only
-- ResTyGADT: *all* the quantified type variables
-- c.f. the comment on con_qvars in HsDecls
; tkvs <- case res_ty of
ResTyH98 -> quantifyTyVars (mkVarSet tmpl_tvs)
(tyVarsOfTypes (ctxt++arg_tys))
ResTyGADT _ res_ty -> quantifyTyVars emptyVarSet
(tyVarsOfTypes (res_ty:ctxt++arg_tys))
-- Zonk to Types
; (ze, qtkvs) <- zonkTyBndrsX emptyZonkEnv tkvs
; arg_tys <- zonkTcTypeToTypes ze arg_tys
; ctxt <- zonkTcTypeToTypes ze ctxt
; res_ty <- case res_ty of
ResTyH98 -> return ResTyH98
ResTyGADT ls ty -> ResTyGADT ls <$> zonkTcTypeToType ze ty
; let (univ_tvs, ex_tvs, eq_preds, res_ty') = rejigConRes tmpl_tvs res_tmpl qtkvs res_ty
; fam_envs <- tcGetFamInstEnvs
; let
buildOneDataCon (L _ name) = do
{ is_infix <- tcConIsInfix name hs_details res_ty
; buildDataCon fam_envs name is_infix
stricts field_lbls
univ_tvs ex_tvs eq_preds ctxt arg_tys
res_ty' rep_tycon
-- NB: we put data_tc, the type constructor gotten from the
-- constructor type signature into the data constructor;
-- that way checkValidDataCon can complain if it's wrong.
}
; mapM buildOneDataCon names
}
tcConIsInfix :: Name
-> HsConDetails (LHsType Name) (Located [LConDeclField Name])
-> ResType Type
-> TcM Bool
tcConIsInfix _ details ResTyH98
= case details of
InfixCon {} -> return True
_ -> return False
tcConIsInfix con details (ResTyGADT _ _)
= case details of
InfixCon {} -> return True
RecCon {} -> return False
PrefixCon arg_tys -- See Note [Infix GADT cons]
| isSymOcc (getOccName con)
, [_ty1,_ty2] <- arg_tys
-> do { fix_env <- getFixityEnv
; return (con `elemNameEnv` fix_env) }
| otherwise -> return False
tcConArgs :: NewOrData -> HsConDeclDetails Name
-> TcM ([Name], [(TcType, HsSrcBang)])
tcConArgs new_or_data (PrefixCon btys)
= do { btys' <- mapM (tcConArg new_or_data) btys
; return ([], btys') }
tcConArgs new_or_data (InfixCon bty1 bty2)
= do { bty1' <- tcConArg new_or_data bty1
; bty2' <- tcConArg new_or_data bty2
; return ([], [bty1', bty2']) }
tcConArgs new_or_data (RecCon fields)
= do { btys' <- mapM (tcConArg new_or_data) btys
; return (field_names, btys') }
where
-- We need a one-to-one mapping from field_names to btys
combined = map (\(L _ f) -> (cd_fld_names f,cd_fld_type f)) (unLoc fields)
explode (ns,ty) = zip (map unLoc ns) (repeat ty)
exploded = concatMap explode combined
(field_names,btys) = unzip exploded
tcConArg :: NewOrData -> LHsType Name -> TcM (TcType, HsSrcBang)
tcConArg new_or_data bty
= do { traceTc "tcConArg 1" (ppr bty)
; arg_ty <- tcHsConArgType new_or_data bty
; traceTc "tcConArg 2" (ppr bty)
; return (arg_ty, getBangStrictness bty) }
tcConRes :: ResType (LHsType Name) -> TcM (ResType Type)
tcConRes ResTyH98 = return ResTyH98
tcConRes (ResTyGADT ls res_ty) = do { res_ty' <- tcHsLiftedType res_ty
; return (ResTyGADT ls res_ty') }
{-
Note [Infix GADT constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do not currently have syntax to declare an infix constructor in GADT syntax,
but it makes a (small) difference to the Show instance. So as a slightly
ad-hoc solution, we regard a GADT data constructor as infix if
a) it is an operator symbol
b) it has two arguments
c) there is a fixity declaration for it
For example:
infix 6 (:--:)
data T a where
(:--:) :: t1 -> t2 -> T Int
Note [Checking GADT return types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a delicacy around checking the return types of a datacon. The
central problem is dealing with a declaration like
data T a where
MkT :: a -> Q a
Note that the return type of MkT is totally bogus. When creating the T
tycon, we also need to create the MkT datacon, which must have a "rejigged"
return type. That is, the MkT datacon's type must be transformed to have
a uniform return type with explicit coercions for GADT-like type parameters.
This rejigging is what rejigConRes does. The problem is, though, that checking
that the return type is appropriate is much easier when done over *Type*,
not *HsType*.
So, we want to make rejigConRes lazy and then check the validity of the return
type in checkValidDataCon. But, if the return type is bogus, rejigConRes can't
work -- it will have a failed pattern match. Luckily, if we run
checkValidDataCon before ever looking at the rejigged return type
(checkValidDataCon checks the dataConUserType, which is not rejigged!), we
catch the error before forcing the rejigged type and panicking.
-}
-- Example
-- data instance T (b,c) where
-- TI :: forall e. e -> T (e,e)
--
-- The representation tycon looks like this:
-- data :R7T b c where
-- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
-- In this case orig_res_ty = T (e,e)
rejigConRes :: [TyVar] -> Type -- Template for result type; e.g.
-- data instance T [a] b c = ...
-- gives template ([a,b,c], T [a] b c)
-> [TyVar] -- where MkT :: forall x y z. ...
-> ResType Type
-> ([TyVar], -- Universal
[TyVar], -- Existential (distinct OccNames from univs)
[(TyVar,Type)], -- Equality predicates
Type) -- Typechecked return type
-- We don't check that the TyCon given in the ResTy is
-- the same as the parent tycon, because checkValidDataCon will do it
rejigConRes tmpl_tvs res_ty dc_tvs ResTyH98
= (tmpl_tvs, dc_tvs, [], res_ty)
-- In H98 syntax the dc_tvs are the existential ones
-- data T a b c = forall d e. MkT ...
-- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
rejigConRes tmpl_tvs res_tmpl dc_tvs (ResTyGADT _ res_ty)
-- E.g. data T [a] b c where
-- MkT :: forall x y z. T [(x,y)] z z
-- Then we generate
-- Univ tyvars Eq-spec
-- a a~(x,y)
-- b b~z
-- z
-- Existentials are the leftover type vars: [x,y]
-- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
= (univ_tvs, ex_tvs, eq_spec, res_ty)
where
Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty
-- This 'Just' pattern is sure to match, because if not
-- checkValidDataCon will complain first.
-- See Note [Checking GADT return types]
-- /Lazily/ figure out the univ_tvs etc
-- Each univ_tv is either a dc_tv or a tmpl_tv
(univ_tvs, eq_spec) = foldr choose ([], []) tmpl_tvs
choose tmpl (univs, eqs)
| Just ty <- lookupTyVar subst tmpl
= case tcGetTyVar_maybe ty of
Just tv | not (tv `elem` univs)
-> (tv:univs, eqs)
_other -> (new_tmpl:univs, (new_tmpl,ty):eqs)
where -- see Note [Substitution in template variables kinds]
new_tmpl = updateTyVarKind (substTy subst) tmpl
| otherwise = pprPanic "tcResultType" (ppr res_ty)
ex_tvs = dc_tvs `minusList` univ_tvs
{-
Note [Substitution in template variables kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data List a = Nil | Cons a (List a)
data SList s as where
SNil :: SList s Nil
We call tcResultType with
tmpl_tvs = [(k :: BOX), (s :: k -> *), (as :: List k)]
res_tmpl = SList k s as
res_ty = ResTyGADT (SList k1 (s1 :: k1 -> *) (Nil k1))
We get subst:
k -> k1
s -> s1
as -> Nil k1
Now we want to find out the universal variables and the equivalences
between some of them and types (GADT).
In this example, k and s are mapped to exactly variables which are not
already present in the universal set, so we just add them without any
coercion.
But 'as' is mapped to 'Nil k1', so we add 'as' to the universal set,
and add the equivalence with 'Nil k1' in 'eqs'.
The problem is that with kind polymorphism, as's kind may now contain
kind variables, and we have to apply the template substitution to it,
which is why we create new_tmpl.
The template substitution only maps kind variables to kind variables,
since GADTs are not kind indexed.
************************************************************************
* *
Validity checking
* *
************************************************************************
Validity checking is done once the mutually-recursive knot has been
tied, so we can look at things freely.
-}
checkClassCycleErrs :: Class -> TcM ()
checkClassCycleErrs cls = mapM_ recClsErr (calcClassCycles cls)
checkValidTyCl :: TyThing -> TcM ()
checkValidTyCl thing
= setSrcSpan (getSrcSpan thing) $
addTyThingCtxt thing $
case thing of
ATyCon tc -> checkValidTyCon tc
AnId _ -> return () -- Generic default methods are checked
-- with their parent class
ACoAxiom _ -> return () -- Axioms checked with their parent
-- closed family tycon
_ -> pprTrace "checkValidTyCl" (ppr thing) $ return ()
-------------------------
-- For data types declared with record syntax, we require
-- that each constructor that has a field 'f'
-- (a) has the same result type
-- (b) has the same type for 'f'
-- modulo alpha conversion of the quantified type variables
-- of the constructor.
--
-- Note that we allow existentials to match because the
-- fields can never meet. E.g
-- data T where
-- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
-- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
-- Here we do not complain about f1,f2 because they are existential
checkValidTyCon :: TyCon -> TcM ()
checkValidTyCon tc
| Just cl <- tyConClass_maybe tc
= checkValidClass cl
| Just syn_rhs <- synTyConRhs_maybe tc
= checkValidType syn_ctxt syn_rhs
| Just fam_flav <- famTyConFlav_maybe tc
= case fam_flav of
{ ClosedSynFamilyTyCon ax -> checkValidClosedCoAxiom ax
; AbstractClosedSynFamilyTyCon ->
do { hsBoot <- tcIsHsBootOrSig
; checkTc hsBoot $
ptext (sLit "You may omit the equations in a closed type family") $$
ptext (sLit "only in a .hs-boot file") }
; OpenSynFamilyTyCon -> return ()
; BuiltInSynFamTyCon _ -> return () }
| otherwise
= do { -- Check the context on the data decl
traceTc "cvtc1" (ppr tc)
; checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
; traceTc "cvtc2" (ppr tc)
; dflags <- getDynFlags
; existential_ok <- xoptM Opt_ExistentialQuantification
; gadt_ok <- xoptM Opt_GADTs
; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
; mapM_ (checkValidDataCon dflags ex_ok tc) data_cons
-- Check that fields with the same name share a type
; mapM_ check_fields groups }
where
syn_ctxt = TySynCtxt name
name = tyConName tc
data_cons = tyConDataCons tc
groups = equivClasses cmp_fld (concatMap get_fields data_cons)
cmp_fld (f1,_) (f2,_) = f1 `compare` f2
get_fields con = dataConFieldLabels con `zip` repeat con
-- dataConFieldLabels may return the empty list, which is fine
-- See Note [GADT record selectors] in MkId.lhs
-- We must check (a) that the named field has the same
-- type in each constructor
-- (b) that those constructors have the same result type
--
-- However, the constructors may have differently named type variable
-- and (worse) we don't know how the correspond to each other. E.g.
-- C1 :: forall a b. { f :: a, g :: b } -> T a b
-- C2 :: forall d c. { f :: c, g :: c } -> T c d
--
-- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
-- result type against other candidates' types BOTH WAYS ROUND.
-- If they magically agrees, take the substitution and
-- apply them to the latter ones, and see if they match perfectly.
check_fields ((label, con1) : other_fields)
-- These fields all have the same name, but are from
-- different constructors in the data type
= recoverM (return ()) $ mapM_ checkOne other_fields
-- Check that all the fields in the group have the same type
-- NB: this check assumes that all the constructors of a given
-- data type use the same type variables
where
(tvs1, _, _, res1) = dataConSig con1
ts1 = mkVarSet tvs1
fty1 = dataConFieldType con1 label
checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
= do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
where
(tvs2, _, _, res2) = dataConSig con2
ts2 = mkVarSet tvs2
fty2 = dataConFieldType con2 label
check_fields [] = panic "checkValidTyCon/check_fields []"
checkValidClosedCoAxiom :: CoAxiom Branched -> TcM ()
checkValidClosedCoAxiom (CoAxiom { co_ax_branches = branches, co_ax_tc = tc })
= tcAddClosedTypeFamilyDeclCtxt tc $
do { brListFoldlM_ check_accessibility [] branches
; void $ brListMapM (checkValidTyFamInst Nothing tc) branches }
where
check_accessibility :: [CoAxBranch] -- prev branches (in reverse order)
-> CoAxBranch -- cur branch
-> TcM [CoAxBranch] -- cur : prev
-- Check whether the branch is dominated by earlier
-- ones and hence is inaccessible
check_accessibility prev_branches cur_branch
= do { when (cur_branch `isDominatedBy` prev_branches) $
addWarnAt (coAxBranchSpan cur_branch) $
inaccessibleCoAxBranch tc cur_branch
; return (cur_branch : prev_branches) }
checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
-> Type -> Type -> Type -> Type -> TcM ()
checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
= do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
where
mb_subst1 = tcMatchTy tvs1 res1 res2
mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
-------------------------------
checkValidDataCon :: DynFlags -> Bool -> TyCon -> DataCon -> TcM ()
checkValidDataCon dflags existential_ok tc con
= setSrcSpan (srcLocSpan (getSrcLoc con)) $
addErrCtxt (dataConCtxt con) $
do { -- Check that the return type of the data constructor
-- matches the type constructor; eg reject this:
-- data T a where { MkT :: Bogus a }
-- c.f. Note [Check role annotations in a second pass]
-- and Note [Checking GADT return types]
let tc_tvs = tyConTyVars tc
res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
orig_res_ty = dataConOrigResTy con
; traceTc "checkValidDataCon" (vcat
[ ppr con, ppr tc, ppr tc_tvs
, ppr res_ty_tmpl <+> dcolon <+> ppr (typeKind res_ty_tmpl)
, ppr orig_res_ty <+> dcolon <+> ppr (typeKind orig_res_ty)])
; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
res_ty_tmpl
orig_res_ty))
(badDataConTyCon con res_ty_tmpl orig_res_ty)
-- Check that the result type is a *monotype*
-- e.g. reject this: MkT :: T (forall a. a->a)
-- Reason: it's really the argument of an equality constraint
; checkValidMonoType orig_res_ty
-- Check all argument types for validity
; checkValidType ctxt (dataConUserType con)
-- Extra checks for newtype data constructors
; when (isNewTyCon tc) (checkNewDataCon con)
-- Check that UNPACK pragmas and bangs work out
-- E.g. reject data T = MkT {-# UNPACK #-} Int -- No "!"
-- data T = MkT {-# UNPACK #-} !a -- Can't unpack
; mapM_ check_bang (zip3 (dataConSrcBangs con) (dataConImplBangs con) [1..])
-- Check that existentials are allowed if they are used
; checkTc (existential_ok || isVanillaDataCon con)
(badExistential con)
-- Check that we aren't doing GADT type refinement on kind variables
-- e.g reject data T (a::k) where
-- T1 :: T Int
-- T2 :: T Maybe
; checkTc (not (any (isKindVar . fst) (dataConEqSpec con)))
(badGadtKindCon con)
; traceTc "Done validity of data con" (ppr con <+> ppr (dataConRepType con))
}
where
ctxt = ConArgCtxt (dataConName con)
check_bang (HsSrcBang _ (Just want_unpack) has_bang, rep_bang, n)
| want_unpack, not has_bang
= addWarnTc (bad_bang n (ptext (sLit "UNPACK pragma lacks '!'")))
| want_unpack
, case rep_bang of { HsUnpack {} -> False; _ -> True }
, not (gopt Opt_OmitInterfacePragmas dflags)
-- If not optimising, se don't unpack, so don't complain!
-- See MkId.dataConArgRep, the (HsBang True) case
= addWarnTc (bad_bang n (ptext (sLit "Ignoring unusable UNPACK pragma")))
check_bang _
= return ()
bad_bang n herald
= hang herald 2 (ptext (sLit "on the") <+> speakNth n
<+> ptext (sLit "argument of") <+> quotes (ppr con))
-------------------------------
checkNewDataCon :: DataCon -> TcM ()
-- Further checks for the data constructor of a newtype
checkNewDataCon con
= do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
-- One argument
; check_con (null eq_spec) $
ptext (sLit "A newtype constructor must have a return type of form T a1 ... an")
-- Return type is (T a b c)
; check_con (null theta) $
ptext (sLit "A newtype constructor cannot have a context in its type")
; check_con (null ex_tvs) $
ptext (sLit "A newtype constructor cannot have existential type variables")
-- No existentials
; checkTc (not (any isBanged (dataConSrcBangs con)))
(newtypeStrictError con)
-- No strictness
}
where
(_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig con
check_con what msg
= checkTc what (msg $$ ppr con <+> dcolon <+> ppr (dataConUserType con))
-------------------------------
checkValidClass :: Class -> TcM ()
checkValidClass cls
= do { constrained_class_methods <- xoptM Opt_ConstrainedClassMethods
; multi_param_type_classes <- xoptM Opt_MultiParamTypeClasses
; nullary_type_classes <- xoptM Opt_NullaryTypeClasses
; fundep_classes <- xoptM Opt_FunctionalDependencies
-- Check that the class is unary, unless multiparameter type classes
-- are enabled; also recognize deprecated nullary type classes
-- extension (subsumed by multiparameter type classes, Trac #8993)
; checkTc (multi_param_type_classes || cls_arity == 1 ||
(nullary_type_classes && cls_arity == 0))
(classArityErr cls_arity cls)
; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
-- Check the super-classes
; checkValidTheta (ClassSCCtxt (className cls)) theta
-- Now check for cyclic superclasses
-- If there are superclass cycles, checkClassCycleErrs bails.
; checkClassCycleErrs cls
-- Check the class operations.
-- But only if there have been no earlier errors
-- See Note [Abort when superclass cycle is detected]
; whenNoErrs $
mapM_ (check_op constrained_class_methods) op_stuff
-- Check the associated type defaults are well-formed and instantiated
; mapM_ check_at_defs at_stuff }
where
(tyvars, fundeps, theta, _, at_stuff, op_stuff) = classExtraBigSig cls
cls_arity = count isTypeVar tyvars -- Ignore kind variables
cls_tv_set = mkVarSet tyvars
mini_env = zipVarEnv tyvars (mkTyVarTys tyvars)
check_op constrained_class_methods (sel_id, dm)
= addErrCtxt (classOpCtxt sel_id tau) $ do
{ checkValidTheta ctxt (tail theta)
-- The 'tail' removes the initial (C a) from the
-- class itself, leaving just the method type
; traceTc "class op type" (ppr op_ty <+> ppr tau)
; checkValidType ctxt tau
-- Check that the method type mentions a class variable
-- But actually check that the variables *reachable from*
-- the method type include a class variable.
-- Example: tc223
-- class Error e => Game b mv e | b -> mv e where
-- newBoard :: MonadState b m => m ()
-- Here, MonadState has a fundep m->b, so newBoard is fine
; check_mentions (growThetaTyVars theta (tyVarsOfType tau))
(ptext (sLit "class method") <+> quotes (ppr sel_id))
; case dm of
GenDefMeth dm_name -> do { dm_id <- tcLookupId dm_name
; checkValidType (FunSigCtxt op_name) (idType dm_id) }
_ -> return ()
}
where
ctxt = FunSigCtxt op_name
op_name = idName sel_id
op_ty = idType sel_id
(_,theta1,tau1) = tcSplitSigmaTy op_ty
(_,theta2,tau2) = tcSplitSigmaTy tau1
(theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
| otherwise = (theta1, mkPhiTy (tail theta1) tau1)
-- Ugh! The function might have a type like
-- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
-- With -XConstrainedClassMethods, we want to allow this, even though the inner
-- forall has an (Eq a) constraint. Whereas in general, each constraint
-- in the context of a for-all must mention at least one quantified
-- type variable. What a mess!
check_at_defs (ATI fam_tc m_dflt_rhs)
= do { check_mentions (mkVarSet fam_tvs) $
ptext (sLit "associated type") <+> quotes (ppr fam_tc)
; whenIsJust m_dflt_rhs $ \ (rhs, loc) ->
checkValidTyFamEqn (Just (cls, mini_env)) fam_tc
fam_tvs (mkTyVarTys fam_tvs) rhs loc }
where
fam_tvs = tyConTyVars fam_tc
check_mentions :: TyVarSet -> SDoc -> TcM ()
-- Check that the thing (method or associated type) mentions at least
-- one of the class type variables
-- The check is disabled for nullary type classes,
-- since there is no possible ambiguity (Trac #10020)
check_mentions thing_tvs thing_doc
= checkTc (cls_arity == 0 || thing_tvs `intersectsVarSet` cls_tv_set)
(noClassTyVarErr cls thing_doc)
checkFamFlag :: Name -> TcM ()
-- Check that we don't use families without -XTypeFamilies
-- The parser won't even parse them, but I suppose a GHC API
-- client might have a go!
checkFamFlag tc_name
= do { idx_tys <- xoptM Opt_TypeFamilies
; checkTc idx_tys err_msg }
where
err_msg = hang (ptext (sLit "Illegal family declaration for") <+> quotes (ppr tc_name))
2 (ptext (sLit "Use TypeFamilies to allow indexed type families"))
{-
Note [Abort when superclass cycle is detected]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must avoid doing the ambiguity check for the methods (in
checkValidClass.check_op) when there are already errors accumulated.
This is because one of the errors may be a superclass cycle, and
superclass cycles cause canonicalization to loop. Here is a
representative example:
class D a => C a where
meth :: D a => ()
class C a => D a
This fixes Trac #9415, #9739
************************************************************************
* *
Checking role validity
* *
************************************************************************
-}
checkValidRoleAnnots :: RoleAnnots -> TyThing -> TcM ()
checkValidRoleAnnots role_annots thing
= case thing of
{ ATyCon tc
| isTypeSynonymTyCon tc -> check_no_roles
| isFamilyTyCon tc -> check_no_roles
| isAlgTyCon tc -> check_roles
where
name = tyConName tc
-- Role annotations are given only on *type* variables, but a tycon stores
-- roles for all variables. So, we drop the kind roles (which are all
-- Nominal, anyway).
tyvars = tyConTyVars tc
roles = tyConRoles tc
(kind_vars, type_vars) = span isKindVar tyvars
type_roles = dropList kind_vars roles
role_annot_decl_maybe = lookupRoleAnnots role_annots name
check_roles
= whenIsJust role_annot_decl_maybe $
\decl@(L loc (RoleAnnotDecl _ the_role_annots)) ->
addRoleAnnotCtxt name $
setSrcSpan loc $ do
{ role_annots_ok <- xoptM Opt_RoleAnnotations
; checkTc role_annots_ok $ needXRoleAnnotations tc
; checkTc (type_vars `equalLength` the_role_annots)
(wrongNumberOfRoles type_vars decl)
; _ <- zipWith3M checkRoleAnnot type_vars the_role_annots type_roles
-- Representational or phantom roles for class parameters
-- quickly lead to incoherence. So, we require
-- IncoherentInstances to have them. See #8773.
; incoherent_roles_ok <- xoptM Opt_IncoherentInstances
; checkTc ( incoherent_roles_ok
|| (not $ isClassTyCon tc)
|| (all (== Nominal) type_roles))
incoherentRoles
; lint <- goptM Opt_DoCoreLinting
; when lint $ checkValidRoles tc }
check_no_roles
= whenIsJust role_annot_decl_maybe illegalRoleAnnotDecl
; _ -> return () }
checkRoleAnnot :: TyVar -> Located (Maybe Role) -> Role -> TcM ()
checkRoleAnnot _ (L _ Nothing) _ = return ()
checkRoleAnnot tv (L _ (Just r1)) r2
= when (r1 /= r2) $
addErrTc $ badRoleAnnot (tyVarName tv) r1 r2
-- This is a double-check on the role inference algorithm. It is only run when
-- -dcore-lint is enabled. See Note [Role inference] in TcTyDecls
checkValidRoles :: TyCon -> TcM ()
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in CoreLint
checkValidRoles tc
| isAlgTyCon tc
-- tyConDataCons returns an empty list for data families
= mapM_ check_dc_roles (tyConDataCons tc)
| Just rhs <- synTyConRhs_maybe tc
= check_ty_roles (zipVarEnv (tyConTyVars tc) (tyConRoles tc)) Representational rhs
| otherwise
= return ()
where
check_dc_roles datacon
= do { traceTc "check_dc_roles" (ppr datacon <+> ppr (tyConRoles tc))
; mapM_ (check_ty_roles role_env Representational) $
eqSpecPreds eq_spec ++ theta ++ arg_tys }
-- See Note [Role-checking data constructor arguments] in TcTyDecls
where
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig datacon
univ_roles = zipVarEnv univ_tvs (tyConRoles tc)
-- zipVarEnv uses zipEqual, but we don't want that for ex_tvs
ex_roles = mkVarEnv (zip ex_tvs (repeat Nominal))
role_env = univ_roles `plusVarEnv` ex_roles
check_ty_roles env role (TyVarTy tv)
= case lookupVarEnv env tv of
Just role' -> unless (role' `ltRole` role || role' == role) $
report_error $ ptext (sLit "type variable") <+> quotes (ppr tv) <+>
ptext (sLit "cannot have role") <+> ppr role <+>
ptext (sLit "because it was assigned role") <+> ppr role'
Nothing -> report_error $ ptext (sLit "type variable") <+> quotes (ppr tv) <+>
ptext (sLit "missing in environment")
check_ty_roles env Representational (TyConApp tc tys)
= let roles' = tyConRoles tc in
zipWithM_ (maybe_check_ty_roles env) roles' tys
check_ty_roles env Nominal (TyConApp _ tys)
= mapM_ (check_ty_roles env Nominal) tys
check_ty_roles _ Phantom ty@(TyConApp {})
= pprPanic "check_ty_roles" (ppr ty)
check_ty_roles env role (AppTy ty1 ty2)
= check_ty_roles env role ty1
>> check_ty_roles env Nominal ty2
check_ty_roles env role (FunTy ty1 ty2)
= check_ty_roles env role ty1
>> check_ty_roles env role ty2
check_ty_roles env role (ForAllTy tv ty)
= check_ty_roles (extendVarEnv env tv Nominal) role ty
check_ty_roles _ _ (LitTy {}) = return ()
maybe_check_ty_roles env role ty
= when (role == Nominal || role == Representational) $
check_ty_roles env role ty
report_error doc
= addErrTc $ vcat [ptext (sLit "Internal error in role inference:"),
doc,
ptext (sLit "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug")]
{-
************************************************************************
* *
Building record selectors
* *
************************************************************************
-}
mkDefaultMethodIds :: [TyThing] -> [Id]
-- See Note [Default method Ids and Template Haskell]
mkDefaultMethodIds things
= [ mkExportedLocalId VanillaId dm_name (idType sel_id)
| ATyCon tc <- things
, Just cls <- [tyConClass_maybe tc]
, (sel_id, DefMeth dm_name) <- classOpItems cls ]
{-
Note [Default method Ids and Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (Trac #4169):
class Numeric a where
fromIntegerNum :: a
fromIntegerNum = ...
ast :: Q [Dec]
ast = [d| instance Numeric Int |]
When we typecheck 'ast' we have done the first pass over the class decl
(in tcTyClDecls), but we have not yet typechecked the default-method
declarations (because they can mention value declarations). So we
must bring the default method Ids into scope first (so they can be seen
when typechecking the [d| .. |] quote, and typecheck them later.
-}
mkRecSelBinds :: [TyThing] -> HsValBinds Name
-- NB We produce *un-typechecked* bindings, rather like 'deriving'
-- This makes life easier, because the later type checking will add
-- all necessary type abstractions and applications
mkRecSelBinds tycons
= ValBindsOut [(NonRecursive, b) | b <- binds] sigs
where
(sigs, binds) = unzip rec_sels
rec_sels = map mkRecSelBind [ (tc,fld)
| ATyCon tc <- tycons
, fld <- tyConFields tc ]
mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
mkRecSelBind (tycon, sel_name)
= (L loc (IdSig sel_id), unitBag (L loc sel_bind))
where
loc = getSrcSpan sel_name
sel_id = mkExportedLocalId rec_details sel_name sel_ty
rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
-- Find a representative constructor, con1
all_cons = tyConDataCons tycon
cons_w_field = [ con | con <- all_cons
, sel_name `elem` dataConFieldLabels con ]
con1 = {-ASSERT( not (null cons_w_field) )-} head cons_w_field
-- Selector type; Note [Polymorphic selectors]
field_ty = dataConFieldType con1 sel_name
data_ty = dataConOrigResTy con1
data_tvs = tyVarsOfType data_ty
is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
(field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
sel_ty | is_naughty = unitTy -- See Note [Naughty record selectors]
| otherwise = mkForAllTys (varSetElemsKvsFirst $
data_tvs `extendVarSetList` field_tvs) $
mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
mkPhiTy field_theta $ -- Urgh!
mkFunTy data_ty field_tau
-- Make the binding: sel (C2 { fld = x }) = x
-- sel (C7 { fld = x }) = x
-- where cons_w_field = [C2,C7]
sel_bind = mkTopFunBind Generated sel_lname alts
where
alts | is_naughty = [mkSimpleMatch [] unit_rhs]
| otherwise = map mk_match cons_w_field ++ deflt
mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
(L loc (HsVar field_var))
mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
rec_field = noLoc (HsRecField { hsRecFieldId = sel_lname
, hsRecFieldArg = L loc (VarPat field_var)
, hsRecPun = False })
sel_lname = L loc sel_name
field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
-- Add catch-all default case unless the case is exhaustive
-- We do this explicitly so that we get a nice error message that
-- mentions this particular record selector
deflt | all dealt_with all_cons = []
| otherwise = [mkSimpleMatch [L loc (WildPat placeHolderType)]
(mkHsApp (L loc (HsVar (getName rEC_SEL_ERROR_ID)))
(L loc (HsLit msg_lit)))]
-- Do not add a default case unless there are unmatched
-- constructors. We must take account of GADTs, else we
-- get overlap warning messages from the pattern-match checker
-- NB: we need to pass type args for the *representation* TyCon
-- to dataConCannotMatch, hence the calculation of inst_tys
-- This matters in data families
-- data instance T Int a where
-- A :: { fld :: Int } -> T Int Bool
-- B :: { fld :: Int } -> T Int Char
dealt_with con = con `elem` cons_w_field || dataConCannotMatch inst_tys con
inst_tys = substTyVars (mkTopTvSubst (dataConEqSpec con1)) (dataConUnivTyVars con1)
unit_rhs = mkLHsTupleExpr []
msg_lit = HsStringPrim "" $ unsafeMkByteString $
occNameString (getOccName sel_name)
---------------
tyConFields :: TyCon -> [FieldLabel]
tyConFields tc
| isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
| otherwise = []
{-
Note [Polymorphic selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a record has a polymorphic field, we pull the foralls out to the front.
data T = MkT { f :: forall a. [a] -> a }
Then f :: forall a. T -> [a] -> a
NOT f :: T -> forall a. [a] -> a
This is horrid. It's only needed in deeply obscure cases, which I hate.
The only case I know is test tc163, which is worth looking at. It's far
from clear that this test should succeed at all!
Note [Naughty record selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "naughty" field is one for which we can't define a record
selector, because an existential type variable would escape. For example:
data T = forall a. MkT { x,y::a }
We obviously can't define
x (MkT v _) = v
Nevertheless we *do* put a RecSelId into the type environment
so that if the user tries to use 'x' as a selector we can bleat
helpfully, rather than saying unhelpfully that 'x' is not in scope.
Hence the sel_naughty flag, to identify record selectors that don't really exist.
In general, a field is "naughty" if its type mentions a type variable that
isn't in the result type of the constructor. Note that this *allows*
GADT record selectors (Note [GADT record selectors]) whose types may look
like sel :: T [a] -> a
For naughty selectors we make a dummy binding
sel = ()
for naughty selectors, so that the later type-check will add them to the
environment, and they'll be exported. The function is never called, because
the tyepchecker spots the sel_naughty field.
Note [GADT record selectors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For GADTs, we require that all constructors with a common field 'f' have the same
result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
E.g.
data T where
T1 { f :: Maybe a } :: T [a]
T2 { f :: Maybe a, y :: b } :: T [a]
T3 :: T Int
and now the selector takes that result type as its argument:
f :: forall a. T [a] -> Maybe a
Details: the "real" types of T1,T2 are:
T1 :: forall r a. (r~[a]) => a -> T r
T2 :: forall r a b. (r~[a]) => a -> b -> T r
So the selector loooks like this:
f :: forall a. T [a] -> Maybe a
f (a:*) (t:T [a])
= case t of
T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
T3 -> error "T3 does not have field f"
Note the forall'd tyvars of the selector are just the free tyvars
of the result type; there may be other tyvars in the constructor's
type (e.g. 'b' in T2).
Note the need for casts in the result!
Note [Selector running example]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's OK to combine GADTs and type families. Here's a running example:
data instance T [a] where
T1 { fld :: b } :: T [Maybe b]
The representation type looks like this
data :R7T a where
T1 { fld :: b } :: :R7T (Maybe b)
and there's coercion from the family type to the representation type
:CoR7T a :: T [a] ~ :R7T a
The selector we want for fld looks like this:
fld :: forall b. T [Maybe b] -> b
fld = /\b. \(d::T [Maybe b]).
case d `cast` :CoR7T (Maybe b) of
T1 (x::b) -> x
The scrutinee of the case has type :R7T (Maybe b), which can be
gotten by appying the eq_spec to the univ_tvs of the data con.
************************************************************************
* *
Error messages
* *
************************************************************************
-}
tcAddTyFamInstCtxt :: TyFamInstDecl Name -> TcM a -> TcM a
tcAddTyFamInstCtxt decl
= tcAddFamInstCtxt (ptext (sLit "type instance")) (tyFamInstDeclName decl)
tcAddDataFamInstCtxt :: DataFamInstDecl Name -> TcM a -> TcM a
tcAddDataFamInstCtxt decl
= tcAddFamInstCtxt (pprDataFamInstFlavour decl <+> ptext (sLit "instance"))
(unLoc (dfid_tycon decl))
tcAddFamInstCtxt :: SDoc -> Name -> TcM a -> TcM a
tcAddFamInstCtxt flavour tycon thing_inside
= addErrCtxt ctxt thing_inside
where
ctxt = hsep [ptext (sLit "In the") <+> flavour
<+> ptext (sLit "declaration for"),
quotes (ppr tycon)]
tcAddClosedTypeFamilyDeclCtxt :: TyCon -> TcM a -> TcM a
tcAddClosedTypeFamilyDeclCtxt tc
= addErrCtxt ctxt
where
ctxt = ptext (sLit "In the equations for closed type family") <+>
quotes (ppr tc)
resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
resultTypeMisMatch field_name con1 con2
= vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
nest 2 $ ptext (sLit "but have different result types")]
fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
fieldTypeMisMatch field_name con1 con2
= sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
ptext (sLit "give different types for field"), quotes (ppr field_name)]
dataConCtxtName :: [Located Name] -> SDoc
dataConCtxtName [con]
= ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
dataConCtxtName con
= ptext (sLit "In the definition of data constructors") <+> interpp'SP con
dataConCtxt :: Outputable a => a -> SDoc
dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
classOpCtxt :: Var -> Type -> SDoc
classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
nest 2 (pprPrefixOcc sel_id <+> dcolon <+> ppr tau)]
classArityErr :: Int -> Class -> SDoc
classArityErr n cls
| n == 0 = mkErr "No" "no-parameter"
| otherwise = mkErr "Too many" "multi-parameter"
where
mkErr howMany allowWhat =
vcat [ptext (sLit $ howMany ++ " parameters for class") <+> quotes (ppr cls),
parens (ptext (sLit $ "Use MultiParamTypeClasses to allow "
++ allowWhat ++ " classes"))]
classFunDepsErr :: Class -> SDoc
classFunDepsErr cls
= vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
parens (ptext (sLit "Use FunctionalDependencies to allow fundeps"))]
noClassTyVarErr :: Class -> SDoc -> SDoc
noClassTyVarErr clas what
= sep [ptext (sLit "The") <+> what,
ptext (sLit "mentions none of the type or kind variables of the class") <+>
quotes (ppr clas <+> hsep (map ppr (classTyVars clas)))]
recSynErr :: [LTyClDecl Name] -> TcRn ()
recSynErr syn_decls
= setSrcSpan (getLoc (head sorted_decls)) $
addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
nest 2 (vcat (map ppr_decl sorted_decls))])
where
sorted_decls = sortLocated syn_decls
ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
recClsErr :: [TyCon] -> TcRn ()
recClsErr cycles
= addErr (sep [ptext (sLit "Cycle in class declaration (via superclasses):"),
nest 2 (hsep (intersperse (text "->") (map ppr cycles)))])
badDataConTyCon :: DataCon -> Type -> Type -> SDoc
badDataConTyCon data_con res_ty_tmpl actual_res_ty
= hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
badGadtKindCon :: DataCon -> SDoc
badGadtKindCon data_con
= hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con)
<+> ptext (sLit "cannot be GADT-like in its *kind* arguments"))
2 (ppr data_con <+> dcolon <+> ppr (dataConUserType data_con))
badGadtDecl :: Name -> SDoc
badGadtDecl tc_name
= vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
, nest 2 (parens $ ptext (sLit "Use GADTs to allow GADTs")) ]
badExistential :: DataCon -> SDoc
badExistential con
= hang (ptext (sLit "Data constructor") <+> quotes (ppr con) <+>
ptext (sLit "has existential type variables, a context, or a specialised result type"))
2 (vcat [ ppr con <+> dcolon <+> ppr (dataConUserType con)
, parens $ ptext (sLit "Use ExistentialQuantification or GADTs to allow this") ])
badStupidTheta :: Name -> SDoc
badStupidTheta tc_name
= ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
newtypeConError :: Name -> Int -> SDoc
newtypeConError tycon n
= sep [ptext (sLit "A newtype must have exactly one constructor,"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
newtypeStrictError :: DataCon -> SDoc
newtypeStrictError con
= sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
newtypeFieldErr :: DataCon -> Int -> SDoc
newtypeFieldErr con_name n_flds
= sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
badSigTyDecl :: Name -> SDoc
badSigTyDecl tc_name
= vcat [ ptext (sLit "Illegal kind signature") <+>
quotes (ppr tc_name)
, nest 2 (parens $ ptext (sLit "Use KindSignatures to allow kind signatures")) ]
emptyConDeclsErr :: Name -> SDoc
emptyConDeclsErr tycon
= sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
nest 2 $ ptext (sLit "(EmptyDataDecls permits this)")]
wrongKindOfFamily :: TyCon -> SDoc
wrongKindOfFamily family
= ptext (sLit "Wrong category of family instance; declaration was for a")
<+> kindOfFamily
where
kindOfFamily | isTypeFamilyTyCon family = text "type family"
| isDataFamilyTyCon family = text "data family"
| otherwise = pprPanic "wrongKindOfFamily" (ppr family)
wrongNumberOfParmsErr :: Arity -> SDoc
wrongNumberOfParmsErr max_args
= ptext (sLit "Number of parameters must match family declaration; expected")
<+> ppr max_args
wrongTyFamName :: Name -> Name -> SDoc
wrongTyFamName fam_tc_name eqn_tc_name
= hang (ptext (sLit "Mismatched type name in type family instance."))
2 (vcat [ ptext (sLit "Expected:") <+> ppr fam_tc_name
, ptext (sLit " Actual:") <+> ppr eqn_tc_name ])
inaccessibleCoAxBranch :: TyCon -> CoAxBranch -> SDoc
inaccessibleCoAxBranch tc fi
= ptext (sLit "Overlapped type family instance equation:") $$
(pprCoAxBranch tc fi)
badRoleAnnot :: Name -> Role -> Role -> SDoc
badRoleAnnot var annot inferred
= hang (ptext (sLit "Role mismatch on variable") <+> ppr var <> colon)
2 (sep [ ptext (sLit "Annotation says"), ppr annot
, ptext (sLit "but role"), ppr inferred
, ptext (sLit "is required") ])
wrongNumberOfRoles :: [a] -> LRoleAnnotDecl Name -> SDoc
wrongNumberOfRoles tyvars d@(L _ (RoleAnnotDecl _ annots))
= hang (ptext (sLit "Wrong number of roles listed in role annotation;") $$
ptext (sLit "Expected") <+> (ppr $ length tyvars) <> comma <+>
ptext (sLit "got") <+> (ppr $ length annots) <> colon)
2 (ppr d)
illegalRoleAnnotDecl :: LRoleAnnotDecl Name -> TcM ()
illegalRoleAnnotDecl (L loc (RoleAnnotDecl tycon _))
= setErrCtxt [] $
setSrcSpan loc $
addErrTc (ptext (sLit "Illegal role annotation for") <+> ppr tycon <> char ';' $$
ptext (sLit "they are allowed only for datatypes and classes."))
needXRoleAnnotations :: TyCon -> SDoc
needXRoleAnnotations tc
= ptext (sLit "Illegal role annotation for") <+> ppr tc <> char ';' $$
ptext (sLit "did you intend to use RoleAnnotations?")
incoherentRoles :: SDoc
incoherentRoles = (text "Roles other than" <+> quotes (text "nominal") <+>
text "for class parameters can lead to incoherence.") $$
(text "Use IncoherentInstances to allow this; bad role found")
addTyThingCtxt :: TyThing -> TcM a -> TcM a
addTyThingCtxt thing
= addErrCtxt ctxt
where
name = getName thing
flav = case thing of
ATyCon tc
| isClassTyCon tc -> ptext (sLit "class")
| isTypeFamilyTyCon tc -> ptext (sLit "type family")
| isDataFamilyTyCon tc -> ptext (sLit "data family")
| isTypeSynonymTyCon tc -> ptext (sLit "type")
| isNewTyCon tc -> ptext (sLit "newtype")
| isDataTyCon tc -> ptext (sLit "data")
_ -> pprTrace "addTyThingCtxt strange" (ppr thing)
Outputable.empty
ctxt = hsep [ ptext (sLit "In the"), flav
, ptext (sLit "declaration for"), quotes (ppr name) ]
addRoleAnnotCtxt :: Name -> TcM a -> TcM a
addRoleAnnotCtxt name
= addErrCtxt $
text "while checking a role annotation for" <+> quotes (ppr name)
| alexander-at-github/eta | compiler/ETA/TypeCheck/TcTyClsDecls.hs | bsd-3-clause | 100,819 | 879 | 25 | 29,639 | 17,793 | 9,820 | 7,973 | 1,173 | 9 |
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Storage
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-}
module Kubernetes.OpenAPI.API.Storage where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Storage
-- *** getAPIGroup
-- | @GET \/apis\/storage.k8s.io\/@
--
-- get information of a group
--
-- AuthMethod: 'AuthApiKeyBearerToken'
--
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/storage.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
| denibertovic/haskell | kubernetes/lib/Kubernetes/OpenAPI/API/Storage.hs | bsd-3-clause | 2,717 | 0 | 8 | 331 | 484 | 333 | 151 | -1 | -1 |
module ScrapYourImports where
data Exports = Exports
{ greet :: IO ()
}
makeExports :: String -> Exports
makeExports str = Exports
{ greet = putStrLn str
}
| sleexyz/haskell-fun | ScrapYourImports.hs | bsd-3-clause | 168 | 0 | 10 | 40 | 52 | 29 | 23 | 6 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Text.Syntax.Parser.Attoparsec.Text (
runAsAttoparsec', runAsAttoparsec,
runAsIAttoparsec'
) where
import Data.Attoparsec.Types (Parser)
import Text.Syntax.Parser.Instances ()
import Text.Syntax.Poly (RunAsIParser,
RunAsParser, Syntax (..), TryAlternative (try, (<|>)),
(<||>))
import qualified Data.Attoparsec.Text as A (anyChar, parse, try)
import qualified Data.Attoparsec.Text.Lazy as L
import Data.Text (Text)
import qualified Data.Text.Lazy as L (Text)
import Text.Syntax.Parser.Attoparsec.RunResult (runIResult, runResult)
instance TryAlternative (Parser Text) where
try = A.try
p <|> q = try p <||> q
instance Syntax Char (Parser Text) where
token = A.anyChar
runAsAttoparsec' :: RunAsParser Char Text a ([String], String)
runAsAttoparsec' parser tks = runResult $ A.parse parser tks where
runAsAttoparsec :: RunAsParser Char L.Text a ([String], String)
runAsAttoparsec parser tks =
case L.parse parser tks of
L.Fail _ estack msg -> Left (estack, msg)
L.Done _ r -> Right r
runAsIAttoparsec' :: RunAsIParser Char Text a ([String], String)
runAsIAttoparsec' parser tks = runIResult $ A.parse parser tks
| schernichkin/haskell-invertible-syntax-attoparsec | Text/Syntax/Parser/Attoparsec/Text.hs | bsd-3-clause | 1,550 | 0 | 9 | 475 | 388 | 228 | 160 | 30 | 2 |
{- Data/Singletons/Syntax.hs
(c) Richard Eisenberg 2014
[email protected]
Converts a list of DLetDecs into a LetDecEnv for easier processing,
and contains various other AST definitions.
-}
{-# LANGUAGE DataKinds, TypeFamilies, PolyKinds, DeriveDataTypeable,
StandaloneDeriving, FlexibleInstances #-}
module Data.Singletons.Syntax where
import Prelude hiding ( exp )
import Data.Monoid
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Desugar
import Data.Map.Strict ( Map )
import qualified Data.Map.Strict as Map
type VarPromotions = [(Name, Name)] -- from term-level name to type-level name
-- the relevant part of declarations
data DataDecl = DataDecl NewOrData Name [DTyVarBndr] [DCon] [DPred]
data ClassDecl ann = ClassDecl { cd_cxt :: DCxt
, cd_name :: Name
, cd_tvbs :: [DTyVarBndr]
, cd_fds :: [FunDep]
, cd_lde :: LetDecEnv ann }
data InstDecl ann = InstDecl { id_cxt :: DCxt
, id_name :: Name
, id_arg_tys :: [DType]
, id_meths :: [(Name, LetDecRHS ann)] }
type UClassDecl = ClassDecl Unannotated
type UInstDecl = InstDecl Unannotated
type AClassDecl = ClassDecl Annotated
type AInstDecl = InstDecl Annotated
{-
We see below several datatypes beginning with "A". These are annotated structures,
necessary for Promote to communicate key things to Single. In particular, promotion
of expressions is *not* deterministic, due to the necessity to create unique names
for lets, cases, and lambdas. So, we put these promotions into an annotated AST
so that Single can use the right promotions.
-}
-- A DExp with let and lambda nodes annotated with their type-level equivalents
data ADExp = ADVarE Name
| ADConE Name
| ADLitE Lit
| ADAppE ADExp ADExp
| ADLamE VarPromotions -- bind these type variables to these term vars
DType -- the promoted lambda
[Name] ADExp
| ADCaseE ADExp DType [ADMatch] DType
-- the first type is the promoted scrutinee;
-- the second type is the return type
| ADLetE ALetDecEnv ADExp
| ADSigE ADExp DType
-- unlike in other places, the DType in an ADMatch (the promoted "case" statement)
-- should be used with DAppT, *not* apply! (Case statements are not defunctionalized.)
data ADMatch = ADMatch VarPromotions DType DPat ADExp
data ADClause = ADClause VarPromotions
[DPat] ADExp
data AnnotationFlag = Annotated | Unannotated
-- These are used at the type-level exclusively
type Annotated = 'Annotated
type Unannotated = 'Unannotated
type family IfAnn (ann :: AnnotationFlag) (yes :: k) (no :: k) :: k
type instance IfAnn Annotated yes no = yes
type instance IfAnn Unannotated yes no = no
data family LetDecRHS (ann :: AnnotationFlag)
data instance LetDecRHS Annotated
= AFunction DType -- promote function (unapplied)
Int -- number of arrows in type
[ADClause]
| AValue DType -- promoted exp
Int -- number of arrows in type
ADExp
data instance LetDecRHS Unannotated = UFunction [DClause]
| UValue DExp
type ALetDecRHS = LetDecRHS Annotated
type ULetDecRHS = LetDecRHS Unannotated
data LetDecEnv ann = LetDecEnv
{ lde_defns :: Map Name (LetDecRHS ann)
, lde_types :: Map Name DType -- type signatures
, lde_infix :: [(Fixity, Name)] -- infix declarations
, lde_proms :: IfAnn ann (Map Name DType) () -- possibly, promotions
}
type ALetDecEnv = LetDecEnv Annotated
type ULetDecEnv = LetDecEnv Unannotated
instance Monoid ULetDecEnv where
mempty = LetDecEnv Map.empty Map.empty [] ()
mappend (LetDecEnv defns1 types1 infx1 _) (LetDecEnv defns2 types2 infx2 _) =
LetDecEnv (defns1 <> defns2) (types1 <> types2) (infx1 <> infx2) ()
valueBinding :: Name -> ULetDecRHS -> ULetDecEnv
valueBinding n v = emptyLetDecEnv { lde_defns = Map.singleton n v }
typeBinding :: Name -> DType -> ULetDecEnv
typeBinding n t = emptyLetDecEnv { lde_types = Map.singleton n t }
infixDecl :: Fixity -> Name -> ULetDecEnv
infixDecl f n = emptyLetDecEnv { lde_infix = [(f,n)] }
emptyLetDecEnv :: ULetDecEnv
emptyLetDecEnv = mempty
buildLetDecEnv :: Quasi q => [DLetDec] -> q ULetDecEnv
buildLetDecEnv = go emptyLetDecEnv
where
go acc [] = return acc
go acc (DFunD name clauses : rest) =
go (valueBinding name (UFunction clauses) <> acc) rest
go acc (DValD (DVarPa name) exp : rest) =
go (valueBinding name (UValue exp) <> acc) rest
go acc (dec@(DValD {}) : rest) = do
flattened <- flattenDValD dec
go acc (flattened ++ rest)
go acc (DSigD name ty : rest) =
go (typeBinding name ty <> acc) rest
go acc (DInfixD f n : rest) =
go (infixDecl f n <> acc) rest
| int-index/singletons | src/Data/Singletons/Syntax.hs | bsd-3-clause | 5,063 | 0 | 12 | 1,388 | 1,102 | 624 | 478 | 88 | 6 |
module Arion.Utilities (
associate,
dependencies,
findHaskellFiles
) where
import Arion.Types
import Control.Applicative ((<*>))
import Data.List (nub, sort, union, isInfixOf)
import Data.Map (Map, fromList)
import System.FilePath.Find (always, extension, find, (==?),
(||?))
associate :: [SourceFile] -> [TestFile] -> Map FilePath [TestFile]
associate sourceFiles testFiles = let sourcesAndDependencies = dependencies sourceFiles
in fromList $ map (\(source, dependencies) ->
let testFilesFor source = filter (\testFile -> moduleName source `elem` imports testFile) testFiles
testFilesForSource = testFilesFor source
testFilesForDependencies = concatMap testFilesFor dependencies
in (sourceFilePath source, testFilesForSource ++ testFilesForDependencies)
) sourcesAndDependencies
dependencies :: [SourceFile] -> [(SourceFile, [SourceFile])]
dependencies sourceFiles = map (\file -> let dependencies = transitiveDependencies sourceFiles [] file
in (file, nub $ (filter ((/=) file) dependencies))
) sourceFiles
transitiveDependencies :: [SourceFile] -> [SourceFile] -> SourceFile -> [SourceFile]
transitiveDependencies allSourceFiles sourcesThatIHaveSeenSoFar theSourceFile =
let sourcesThatImportMe = sourcesThatImport allSourceFiles (moduleName theSourceFile)
in case any (\source -> source `elem` sourcesThatIHaveSeenSoFar) sourcesThatImportMe of
True -> sourcesThatImportMe
False -> let soFar = sourcesThatIHaveSeenSoFar ++ [theSourceFile]
in sourcesThatImportMe ++ concatMap (transitiveDependencies allSourceFiles soFar) sourcesThatImportMe
findSourcesByModule :: [SourceFile] -> String -> [SourceFile]
findSourcesByModule sourceFiles theModuleName = filter (\file -> moduleName file == theModuleName) sourceFiles
sourcesThatImport :: [SourceFile] -> String -> [SourceFile]
sourcesThatImport sourceFiles theModuleName = filter (\file -> theModuleName `elem` (importedModules file)) sourceFiles
findHaskellFiles :: String -> IO [String]
findHaskellFiles path = do
files <- find always (extension ==? ".hs" ||? extension ==? ".lhs") path
return $ filter (not . isInfixOf ".#") files
| saturday06/arion | src/Arion/Utilities.hs | mit | 2,916 | 0 | 19 | 1,063 | 635 | 344 | 291 | 37 | 2 |
--main = do
-- contents <- getContents
-- putStr (shortLinesOnly contents)
main = interact shortLinesOnly
shortLinesOnly :: String -> String
shortLinesOnly input =
let allLines = lines input
shortLines = filter (\line -> length line < 10) allLines
result = unlines shortLines
in result
--main = interact $ unlines . filter ((<10) . length) . lines
| leichunfeng/learnyouahaskell | shortlinesonly.hs | mit | 382 | 0 | 13 | 90 | 77 | 40 | 37 | 7 | 1 |
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-}
{-
Copyright (C) 2006-2015 John MacFarlane <[email protected]>
This program 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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.LaTeX
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of LaTeX to 'Pandoc' document.
-}
module Text.Pandoc.Readers.LaTeX ( readLaTeX,
rawLaTeXInline,
rawLaTeXBlock,
inlineCommand,
handleIncludes
) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Shared
import Text.Pandoc.Options
import Text.Pandoc.Parsing hiding ((<|>), many, optional, space,
mathDisplay, mathInline)
import qualified Text.Pandoc.UTF8 as UTF8
import Data.Char ( chr, ord, isLetter, isAlphaNum )
import Control.Monad.Trans (lift)
import Control.Monad
import Text.Pandoc.Builder
import Control.Applicative
import Data.Monoid
import Data.Maybe (fromMaybe, maybeToList)
import System.Environment (getEnv)
import System.FilePath (replaceExtension, (</>), takeExtension, addExtension)
import Data.List (intercalate)
import qualified Data.Map as M
import qualified Control.Exception as E
import Text.Pandoc.Highlighting (fromListingsLanguage)
import Text.Pandoc.Error
-- | Parse LaTeX from string and return 'Pandoc' document.
readLaTeX :: ReaderOptions -- ^ Reader options
-> String -- ^ String to parse (assumes @'\n'@ line endings)
-> Either PandocError Pandoc
readLaTeX opts = readWith parseLaTeX def{ stateOptions = opts }
parseLaTeX :: LP Pandoc
parseLaTeX = do
bs <- blocks
eof
st <- getState
let meta = stateMeta st
let (Pandoc _ bs') = doc bs
return $ Pandoc meta bs'
type LP = Parser String ParserState
anyControlSeq :: LP String
anyControlSeq = do
char '\\'
next <- option '\n' anyChar
case next of
'\n' -> return ""
c | isLetter c -> (c:) <$> (many letter <* optional sp)
| otherwise -> return [c]
controlSeq :: String -> LP String
controlSeq name = try $ do
char '\\'
case name of
"" -> mzero
[c] | not (isLetter c) -> string [c]
cs -> string cs <* notFollowedBy letter <* optional sp
return name
dimenarg :: LP String
dimenarg = try $ do
ch <- option "" $ string "="
num <- many1 digit
dim <- oneOfStrings ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
return $ ch ++ num ++ dim
sp :: LP ()
sp = skipMany1 $ satisfy (\c -> c == ' ' || c == '\t')
<|> try (newline <* lookAhead anyChar <* notFollowedBy blankline)
isLowerHex :: Char -> Bool
isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
tildeEscape :: LP Char
tildeEscape = try $ do
string "^^"
c <- satisfy (\x -> x >= '\0' && x <= '\128')
d <- if isLowerHex c
then option "" $ count 1 (satisfy isLowerHex)
else return ""
if null d
then case ord c of
x | x >= 64 && x <= 127 -> return $ chr (x - 64)
| otherwise -> return $ chr (x + 64)
else return $ chr $ read ('0':'x':c:d)
comment :: LP ()
comment = do
char '%'
skipMany (satisfy (/='\n'))
optional newline
return ()
bgroup :: LP ()
bgroup = () <$ char '{'
<|> () <$ controlSeq "bgroup"
<|> () <$ controlSeq "begingroup"
egroup :: LP ()
egroup = () <$ char '}'
<|> () <$ controlSeq "egroup"
<|> () <$ controlSeq "endgroup"
grouped :: Monoid a => LP a -> LP a
grouped parser = try $ bgroup *> (mconcat <$> manyTill parser egroup)
braced :: LP String
braced = bgroup *> (concat <$> manyTill
( many1 (satisfy (\c -> c /= '\\' && c /= '}' && c /= '{'))
<|> try (string "\\}")
<|> try (string "\\{")
<|> try (string "\\\\")
<|> ((\x -> "{" ++ x ++ "}") <$> braced)
<|> count 1 anyChar
) egroup)
bracketed :: Monoid a => LP a -> LP a
bracketed parser = try $ char '[' *> (mconcat <$> manyTill parser (char ']'))
mathDisplay :: LP String -> LP Inlines
mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
mathInline :: LP String -> LP Inlines
mathInline p = math <$> (try p >>= applyMacros')
mathChars :: LP String
mathChars = (concat <$>) $
many $
many1 (satisfy (\c -> c /= '$' && c /='\\'))
<|> (\c -> ['\\',c]) <$> try (char '\\' *> anyChar)
quoted' :: (Inlines -> Inlines) -> LP String -> LP () -> LP Inlines
quoted' f starter ender = do
startchs <- starter
try ((f . mconcat) <$> manyTill inline ender) <|> lit startchs
doubleQuote :: LP Inlines
doubleQuote =
quoted' doubleQuoted (try $ string "``") (void $ try $ string "''")
<|> quoted' doubleQuoted (string "“") (void $ char '”')
-- the following is used by babel for localized quotes:
<|> quoted' doubleQuoted (try $ string "\"`") (void $ try $ string "\"'")
<|> quoted' doubleQuoted (string "\"") (void $ char '"')
singleQuote :: LP Inlines
singleQuote =
quoted' singleQuoted (string "`") (try $ char '\'' >> notFollowedBy letter)
<|> quoted' singleQuoted (string "‘") (try $ char '’' >> notFollowedBy letter)
inline :: LP Inlines
inline = (mempty <$ comment)
<|> (space <$ sp)
<|> inlineText
<|> inlineCommand
<|> inlineEnvironment
<|> inlineGroup
<|> (char '-' *> option (str "-")
(char '-' *> option (str "–") (str "—" <$ char '-')))
<|> doubleQuote
<|> singleQuote
<|> (str "”" <$ try (string "''"))
<|> (str "”" <$ char '”')
<|> (str "’" <$ char '\'')
<|> (str "’" <$ char '’')
<|> (str "\160" <$ char '~')
<|> mathDisplay (string "$$" *> mathChars <* string "$$")
<|> mathInline (char '$' *> mathChars <* char '$')
<|> try (superscript <$> (char '^' *> tok))
<|> (subscript <$> (char '_' *> tok))
<|> (guardEnabled Ext_literate_haskell *> char '|' *> doLHSverb)
<|> (str . (:[]) <$> tildeEscape)
<|> (str . (:[]) <$> oneOf "[]")
<|> (str . (:[]) <$> oneOf "#&") -- TODO print warning?
-- <|> (str <$> count 1 (satisfy (\c -> c /= '\\' && c /='\n' && c /='}' && c /='{'))) -- eat random leftover characters
inlines :: LP Inlines
inlines = mconcat <$> many (notFollowedBy (char '}') *> inline)
inlineGroup :: LP Inlines
inlineGroup = do
ils <- grouped inline
if isNull ils
then return mempty
else return $ spanWith nullAttr ils
-- we need the span so we can detitlecase bibtex entries;
-- we need to know when something is {C}apitalized
block :: LP Blocks
block = (mempty <$ comment)
<|> (mempty <$ ((spaceChar <|> newline) *> spaces))
<|> environment
<|> macro
<|> blockCommand
<|> paragraph
<|> grouped block
<|> (mempty <$ char '&') -- loose & in table environment
blocks :: LP Blocks
blocks = mconcat <$> many block
getRawCommand :: String -> LP String
getRawCommand name' = do
rawargs <- withRaw (skipopts *> option "" dimenarg *> many braced)
return $ '\\' : name' ++ snd rawargs
lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
lookupListDefault d = (fromMaybe d .) . lookupList
where
lookupList l m = msum $ map (`M.lookup` m) l
blockCommand :: LP Blocks
blockCommand = try $ do
name <- anyControlSeq
guard $ name /= "begin" && name /= "end"
star <- option "" (string "*" <* optional sp)
let name' = name ++ star
let raw = do
rawcommand <- getRawCommand name'
transformed <- applyMacros' rawcommand
guard $ transformed /= rawcommand
notFollowedBy $ parseFromString inlines transformed
parseFromString blocks transformed
lookupListDefault raw [name',name] blockCommands
inBrackets :: Inlines -> Inlines
inBrackets x = str "[" <> x <> str "]"
-- eat an optional argument and one or more arguments in braces
ignoreInlines :: String -> (String, LP Inlines)
ignoreInlines name = (name, doraw <|> (mempty <$ optargs))
where optargs = skipopts *> skipMany (try $ optional sp *> braced)
contseq = '\\':name
doraw = (rawInline "latex" . (contseq ++) . snd) <$>
(getOption readerParseRaw >>= guard >> withRaw optargs)
ignoreBlocks :: String -> (String, LP Blocks)
ignoreBlocks name = (name, doraw <|> (mempty <$ optargs))
where optargs = skipopts *> skipMany (try $ optional sp *> braced)
contseq = '\\':name
doraw = (rawBlock "latex" . (contseq ++) . snd) <$>
(getOption readerParseRaw >>= guard >> withRaw optargs)
blockCommands :: M.Map String (LP Blocks)
blockCommands = M.fromList $
[ ("par", mempty <$ skipopts)
, ("title", mempty <$ (skipopts *>
(grouped inline >>= addMeta "title")
<|> (grouped block >>= addMeta "title")))
, ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
, ("author", mempty <$ (skipopts *> authors))
-- -- in letter class, temp. store address & sig as title, author
, ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
, ("signature", mempty <$ (skipopts *> authors))
, ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
-- sectioning
, ("chapter", updateState (\s -> s{ stateHasChapters = True })
*> section nullAttr 0)
, ("chapter*", updateState (\s -> s{ stateHasChapters = True })
*> section ("",["unnumbered"],[]) 0)
, ("section", section nullAttr 1)
, ("section*", section ("",["unnumbered"],[]) 1)
, ("subsection", section nullAttr 2)
, ("subsection*", section ("",["unnumbered"],[]) 2)
, ("subsubsection", section nullAttr 3)
, ("subsubsection*", section ("",["unnumbered"],[]) 3)
, ("paragraph", section nullAttr 4)
, ("paragraph*", section ("",["unnumbered"],[]) 4)
, ("subparagraph", section nullAttr 5)
, ("subparagraph*", section ("",["unnumbered"],[]) 5)
-- beamer slides
, ("frametitle", section nullAttr 3)
, ("framesubtitle", section nullAttr 4)
-- letters
, ("opening", (para . trimInlines) <$> (skipopts *> tok))
, ("closing", skipopts *> closing)
--
, ("hrule", pure horizontalRule)
, ("rule", skipopts *> tok *> tok *> pure horizontalRule)
, ("item", skipopts *> looseItem)
, ("documentclass", skipopts *> braced *> preamble)
, ("centerline", (para . trimInlines) <$> (skipopts *> tok))
, ("caption", skipopts *> setCaption)
, ("PandocStartInclude", startInclude)
, ("PandocEndInclude", endInclude)
, ("bibliography", mempty <$ (skipopts *> braced >>=
addMeta "bibliography" . splitBibs))
, ("addbibresource", mempty <$ (skipopts *> braced >>=
addMeta "bibliography" . splitBibs))
] ++ map ignoreBlocks
-- these commands will be ignored unless --parse-raw is specified,
-- in which case they will appear as raw latex blocks
[ "newcommand", "renewcommand", "newenvironment", "renewenvironment"
-- newcommand, etc. should be parsed by macro, but we need this
-- here so these aren't parsed as inline commands to ignore
, "special", "pdfannot", "pdfstringdef"
, "bibliographystyle"
, "maketitle", "makeindex", "makeglossary"
, "addcontentsline", "addtocontents", "addtocounter"
-- \ignore{} is used conventionally in literate haskell for definitions
-- that are to be processed by the compiler but not printed.
, "ignore"
, "hyperdef"
, "markboth", "markright", "markleft"
, "hspace", "vspace"
, "newpage"
]
addMeta :: ToMetaValue a => String -> a -> LP ()
addMeta field val = updateState $ \st ->
st{ stateMeta = addMetaField field val $ stateMeta st }
splitBibs :: String -> [Inlines]
splitBibs = map (str . flip replaceExtension "bib" . trim) . splitBy (==',')
setCaption :: LP Blocks
setCaption = do
ils <- tok
mblabel <- option Nothing $
try $ spaces' >> controlSeq "label" >> (Just <$> tok)
let ils' = case mblabel of
Just lab -> ils <> spanWith
("",[],[("data-label", stringify lab)]) mempty
Nothing -> ils
updateState $ \st -> st{ stateCaption = Just ils' }
return mempty
resetCaption :: LP ()
resetCaption = updateState $ \st -> st{ stateCaption = Nothing }
authors :: LP ()
authors = try $ do
char '{'
let oneAuthor = mconcat <$>
many1 (notFollowedBy' (controlSeq "and") >>
(inline <|> mempty <$ blockCommand))
-- skip e.g. \vspace{10pt}
auths <- sepBy oneAuthor (controlSeq "and")
char '}'
addMeta "author" (map trimInlines auths)
section :: Attr -> Int -> LP Blocks
section (ident, classes, kvs) lvl = do
hasChapters <- stateHasChapters `fmap` getState
let lvl' = if hasChapters then lvl + 1 else lvl
skipopts
contents <- grouped inline
lab <- option ident $ try (spaces' >> controlSeq "label" >> spaces' >> braced)
attr' <- registerHeader (lab, classes, kvs) contents
return $ headerWith attr' lvl' contents
inlineCommand :: LP Inlines
inlineCommand = try $ do
name <- anyControlSeq
guard $ name /= "begin" && name /= "end"
guard $ not $ isBlockCommand name
parseRaw <- getOption readerParseRaw
star <- option "" (string "*")
let name' = name ++ star
let raw = do
rawcommand <- getRawCommand name'
transformed <- applyMacros' rawcommand
if transformed /= rawcommand
then parseFromString inlines transformed
else if parseRaw
then return $ rawInline "latex" rawcommand
else return mempty
lookupListDefault mzero [name',name] inlineCommands
<|> raw
unlessParseRaw :: LP ()
unlessParseRaw = getOption readerParseRaw >>= guard . not
isBlockCommand :: String -> Bool
isBlockCommand s = s `M.member` blockCommands
inlineEnvironments :: M.Map String (LP Inlines)
inlineEnvironments = M.fromList
[ ("displaymath", mathEnv id Nothing "displaymath")
, ("equation", mathEnv id Nothing "equation")
, ("equation*", mathEnv id Nothing "equation*")
, ("gather", mathEnv id (Just "gathered") "gather")
, ("gather*", mathEnv id (Just "gathered") "gather*")
, ("multline", mathEnv id (Just "gathered") "multline")
, ("multline*", mathEnv id (Just "gathered") "multline*")
, ("eqnarray", mathEnv id (Just "aligned") "eqnarray")
, ("eqnarray*", mathEnv id (Just "aligned") "eqnarray*")
, ("align", mathEnv id (Just "aligned") "align")
, ("align*", mathEnv id (Just "aligned") "align*")
, ("alignat", mathEnv id (Just "aligned") "alignat")
, ("alignat*", mathEnv id (Just "aligned") "alignat*")
]
inlineCommands :: M.Map String (LP Inlines)
inlineCommands = M.fromList $
[ ("emph", extractSpaces emph <$> tok)
, ("textit", extractSpaces emph <$> tok)
, ("textsl", extractSpaces emph <$> tok)
, ("textsc", extractSpaces smallcaps <$> tok)
, ("sout", extractSpaces strikeout <$> tok)
, ("textsuperscript", extractSpaces superscript <$> tok)
, ("textsubscript", extractSpaces subscript <$> tok)
, ("textbackslash", lit "\\")
, ("backslash", lit "\\")
, ("slash", lit "/")
, ("textbf", extractSpaces strong <$> tok)
, ("textnormal", extractSpaces (spanWith ("",["nodecor"],[])) <$> tok)
, ("ldots", lit "…")
, ("dots", lit "…")
, ("mdots", lit "…")
, ("sim", lit "~")
, ("label", unlessParseRaw >> (inBrackets <$> tok))
, ("ref", unlessParseRaw >> (inBrackets <$> tok))
, ("noindent", unlessParseRaw >> return mempty)
, ("textgreek", tok)
, ("sep", lit ",")
, ("cref", unlessParseRaw >> (inBrackets <$> tok)) -- from cleveref.sty
, ("(", mathInline $ manyTill anyChar (try $ string "\\)"))
, ("[", mathDisplay $ manyTill anyChar (try $ string "\\]"))
, ("ensuremath", mathInline braced)
, ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)
, ("P", lit "¶")
, ("S", lit "§")
, ("$", lit "$")
, ("%", lit "%")
, ("&", lit "&")
, ("#", lit "#")
, ("_", lit "_")
, ("{", lit "{")
, ("}", lit "}")
-- old TeX commands
, ("em", extractSpaces emph <$> inlines)
, ("it", extractSpaces emph <$> inlines)
, ("sl", extractSpaces emph <$> inlines)
, ("bf", extractSpaces strong <$> inlines)
, ("rm", inlines)
, ("itshape", extractSpaces emph <$> inlines)
, ("slshape", extractSpaces emph <$> inlines)
, ("scshape", extractSpaces smallcaps <$> inlines)
, ("bfseries", extractSpaces strong <$> inlines)
, ("/", pure mempty) -- italic correction
, ("aa", lit "å")
, ("AA", lit "Å")
, ("ss", lit "ß")
, ("o", lit "ø")
, ("O", lit "Ø")
, ("L", lit "Ł")
, ("l", lit "ł")
, ("ae", lit "æ")
, ("AE", lit "Æ")
, ("oe", lit "œ")
, ("OE", lit "Œ")
, ("pounds", lit "£")
, ("euro", lit "€")
, ("copyright", lit "©")
, ("textasciicircum", lit "^")
, ("textasciitilde", lit "~")
, ("`", option (str "`") $ try $ tok >>= accent grave)
, ("'", option (str "'") $ try $ tok >>= accent acute)
, ("^", option (str "^") $ try $ tok >>= accent circ)
, ("~", option (str "~") $ try $ tok >>= accent tilde)
, ("\"", option (str "\"") $ try $ tok >>= accent umlaut)
, (".", option (str ".") $ try $ tok >>= accent dot)
, ("=", option (str "=") $ try $ tok >>= accent macron)
, ("c", option (str "c") $ try $ tok >>= accent cedilla)
, ("v", option (str "v") $ try $ tok >>= accent hacek)
, ("u", option (str "u") $ try $ tok >>= accent breve)
, ("i", lit "i")
, ("\\", linebreak <$ (optional (bracketed inline) *> spaces'))
, (",", pure mempty)
, ("@", pure mempty)
, (" ", lit "\160")
, ("ps", pure $ str "PS." <> space)
, ("TeX", lit "TeX")
, ("LaTeX", lit "LaTeX")
, ("bar", lit "|")
, ("textless", lit "<")
, ("textgreater", lit ">")
, ("thanks", (note . mconcat) <$> (char '{' *> manyTill block (char '}')))
, ("footnote", (note . mconcat) <$> (char '{' *> manyTill block (char '}')))
, ("verb", doverb)
, ("lstinline", skipopts *> doverb)
, ("Verb", doverb)
, ("texttt", (code . stringify . toList) <$> tok)
, ("url", (unescapeURL <$> braced) >>= \url ->
pure (link url "" (str url)))
, ("href", (unescapeURL <$> braced <* optional sp) >>= \url ->
tok >>= \lab ->
pure (link url "" lab))
, ("includegraphics", skipopts *> (unescapeURL <$> braced) >>= mkImage)
, ("enquote", enquote)
, ("cite", citation "cite" AuthorInText False)
, ("citep", citation "citep" NormalCitation False)
, ("citep*", citation "citep*" NormalCitation False)
, ("citeal", citation "citeal" NormalCitation False)
, ("citealp", citation "citealp" NormalCitation False)
, ("citealp*", citation "citealp*" NormalCitation False)
, ("autocite", citation "autocite" NormalCitation False)
, ("smartcite", citation "smartcite" NormalCitation False)
, ("footcite", inNote <$> citation "footcite" NormalCitation False)
, ("parencite", citation "parencite" NormalCitation False)
, ("supercite", citation "supercite" NormalCitation False)
, ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
, ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
, ("citeyear", citation "citeyear" SuppressAuthor False)
, ("autocite*", citation "autocite*" SuppressAuthor False)
, ("cite*", citation "cite*" SuppressAuthor False)
, ("parencite*", citation "parencite*" SuppressAuthor False)
, ("textcite", citation "textcite" AuthorInText False)
, ("citet", citation "citet" AuthorInText False)
, ("citet*", citation "citet*" AuthorInText False)
, ("citealt", citation "citealt" AuthorInText False)
, ("citealt*", citation "citealt*" AuthorInText False)
, ("textcites", citation "textcites" AuthorInText True)
, ("cites", citation "cites" NormalCitation True)
, ("autocites", citation "autocites" NormalCitation True)
, ("footcites", inNote <$> citation "footcites" NormalCitation True)
, ("parencites", citation "parencites" NormalCitation True)
, ("supercites", citation "supercites" NormalCitation True)
, ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
, ("Autocite", citation "Autocite" NormalCitation False)
, ("Smartcite", citation "Smartcite" NormalCitation False)
, ("Footcite", citation "Footcite" NormalCitation False)
, ("Parencite", citation "Parencite" NormalCitation False)
, ("Supercite", citation "Supercite" NormalCitation False)
, ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
, ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
, ("Citeyear", citation "Citeyear" SuppressAuthor False)
, ("Autocite*", citation "Autocite*" SuppressAuthor False)
, ("Cite*", citation "Cite*" SuppressAuthor False)
, ("Parencite*", citation "Parencite*" SuppressAuthor False)
, ("Textcite", citation "Textcite" AuthorInText False)
, ("Textcites", citation "Textcites" AuthorInText True)
, ("Cites", citation "Cites" NormalCitation True)
, ("Autocites", citation "Autocites" NormalCitation True)
, ("Footcites", citation "Footcites" NormalCitation True)
, ("Parencites", citation "Parencites" NormalCitation True)
, ("Supercites", citation "Supercites" NormalCitation True)
, ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
, ("citetext", complexNatbibCitation NormalCitation)
, ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
complexNatbibCitation AuthorInText)
<|> citation "citeauthor" AuthorInText False)
, ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
addMeta "nocite"))
] ++ map ignoreInlines
-- these commands will be ignored unless --parse-raw is specified,
-- in which case they will appear as raw latex blocks:
[ "index" ]
mkImage :: String -> LP Inlines
mkImage src = do
let alt = str "image"
case takeExtension src of
"" -> do
defaultExt <- getOption readerDefaultImageExtension
return $ image (addExtension src defaultExt) "" alt
_ -> return $ image src "" alt
inNote :: Inlines -> Inlines
inNote ils =
note $ para $ ils <> str "."
unescapeURL :: String -> String
unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
where isEscapable c = c `elem` ("#$%&~_^\\{}" :: String)
unescapeURL (x:xs) = x:unescapeURL xs
unescapeURL [] = ""
enquote :: LP Inlines
enquote = do
skipopts
context <- stateQuoteContext <$> getState
if context == InDoubleQuote
then singleQuoted <$> withQuoteContext InSingleQuote tok
else doubleQuoted <$> withQuoteContext InDoubleQuote tok
doverb :: LP Inlines
doverb = do
marker <- anyChar
code <$> manyTill (satisfy (/='\n')) (char marker)
doLHSverb :: LP Inlines
doLHSverb = codeWith ("",["haskell"],[]) <$> manyTill (satisfy (/='\n')) (char '|')
lit :: String -> LP Inlines
lit = pure . str
accent :: (Char -> String) -> Inlines -> LP Inlines
accent f ils =
case toList ils of
(Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
[] -> mzero
_ -> return ils
grave :: Char -> String
grave 'A' = "À"
grave 'E' = "È"
grave 'I' = "Ì"
grave 'O' = "Ò"
grave 'U' = "Ù"
grave 'a' = "à"
grave 'e' = "è"
grave 'i' = "ì"
grave 'o' = "ò"
grave 'u' = "ù"
grave c = [c]
acute :: Char -> String
acute 'A' = "Á"
acute 'E' = "É"
acute 'I' = "Í"
acute 'O' = "Ó"
acute 'U' = "Ú"
acute 'Y' = "Ý"
acute 'a' = "á"
acute 'e' = "é"
acute 'i' = "í"
acute 'o' = "ó"
acute 'u' = "ú"
acute 'y' = "ý"
acute 'C' = "Ć"
acute 'c' = "ć"
acute 'L' = "Ĺ"
acute 'l' = "ĺ"
acute 'N' = "Ń"
acute 'n' = "ń"
acute 'R' = "Ŕ"
acute 'r' = "ŕ"
acute 'S' = "Ś"
acute 's' = "ś"
acute 'Z' = "Ź"
acute 'z' = "ź"
acute c = [c]
circ :: Char -> String
circ 'A' = "Â"
circ 'E' = "Ê"
circ 'I' = "Î"
circ 'O' = "Ô"
circ 'U' = "Û"
circ 'a' = "â"
circ 'e' = "ê"
circ 'i' = "î"
circ 'o' = "ô"
circ 'u' = "û"
circ 'C' = "Ĉ"
circ 'c' = "ĉ"
circ 'G' = "Ĝ"
circ 'g' = "ĝ"
circ 'H' = "Ĥ"
circ 'h' = "ĥ"
circ 'J' = "Ĵ"
circ 'j' = "ĵ"
circ 'S' = "Ŝ"
circ 's' = "ŝ"
circ 'W' = "Ŵ"
circ 'w' = "ŵ"
circ 'Y' = "Ŷ"
circ 'y' = "ŷ"
circ c = [c]
tilde :: Char -> String
tilde 'A' = "Ã"
tilde 'a' = "ã"
tilde 'O' = "Õ"
tilde 'o' = "õ"
tilde 'I' = "Ĩ"
tilde 'i' = "ĩ"
tilde 'U' = "Ũ"
tilde 'u' = "ũ"
tilde 'N' = "Ñ"
tilde 'n' = "ñ"
tilde c = [c]
umlaut :: Char -> String
umlaut 'A' = "Ä"
umlaut 'E' = "Ë"
umlaut 'I' = "Ï"
umlaut 'O' = "Ö"
umlaut 'U' = "Ü"
umlaut 'a' = "ä"
umlaut 'e' = "ë"
umlaut 'i' = "ï"
umlaut 'o' = "ö"
umlaut 'u' = "ü"
umlaut c = [c]
dot :: Char -> String
dot 'C' = "Ċ"
dot 'c' = "ċ"
dot 'E' = "Ė"
dot 'e' = "ė"
dot 'G' = "Ġ"
dot 'g' = "ġ"
dot 'I' = "İ"
dot 'Z' = "Ż"
dot 'z' = "ż"
dot c = [c]
macron :: Char -> String
macron 'A' = "Ā"
macron 'E' = "Ē"
macron 'I' = "Ī"
macron 'O' = "Ō"
macron 'U' = "Ū"
macron 'a' = "ā"
macron 'e' = "ē"
macron 'i' = "ī"
macron 'o' = "ō"
macron 'u' = "ū"
macron c = [c]
cedilla :: Char -> String
cedilla 'c' = "ç"
cedilla 'C' = "Ç"
cedilla 's' = "ş"
cedilla 'S' = "Ş"
cedilla 't' = "ţ"
cedilla 'T' = "Ţ"
cedilla 'e' = "ȩ"
cedilla 'E' = "Ȩ"
cedilla 'h' = "ḩ"
cedilla 'H' = "Ḩ"
cedilla 'o' = "o̧"
cedilla 'O' = "O̧"
cedilla c = [c]
hacek :: Char -> String
hacek 'A' = "Ǎ"
hacek 'a' = "ǎ"
hacek 'C' = "Č"
hacek 'c' = "č"
hacek 'D' = "Ď"
hacek 'd' = "ď"
hacek 'E' = "Ě"
hacek 'e' = "ě"
hacek 'G' = "Ǧ"
hacek 'g' = "ǧ"
hacek 'H' = "Ȟ"
hacek 'h' = "ȟ"
hacek 'I' = "Ǐ"
hacek 'i' = "ǐ"
hacek 'j' = "ǰ"
hacek 'K' = "Ǩ"
hacek 'k' = "ǩ"
hacek 'L' = "Ľ"
hacek 'l' = "ľ"
hacek 'N' = "Ň"
hacek 'n' = "ň"
hacek 'O' = "Ǒ"
hacek 'o' = "ǒ"
hacek 'R' = "Ř"
hacek 'r' = "ř"
hacek 'S' = "Š"
hacek 's' = "š"
hacek 'T' = "Ť"
hacek 't' = "ť"
hacek 'U' = "Ǔ"
hacek 'u' = "ǔ"
hacek 'Z' = "Ž"
hacek 'z' = "ž"
hacek c = [c]
breve :: Char -> String
breve 'A' = "Ă"
breve 'a' = "ă"
breve 'E' = "Ĕ"
breve 'e' = "ĕ"
breve 'G' = "Ğ"
breve 'g' = "ğ"
breve 'I' = "Ĭ"
breve 'i' = "ĭ"
breve 'O' = "Ŏ"
breve 'o' = "ŏ"
breve 'U' = "Ŭ"
breve 'u' = "ŭ"
breve c = [c]
tok :: LP Inlines
tok = try $ grouped inline <|> inlineCommand <|> str <$> count 1 inlineChar
opt :: LP Inlines
opt = bracketed inline <* optional sp
skipopts :: LP ()
skipopts = skipMany opt
inlineText :: LP Inlines
inlineText = str <$> many1 inlineChar
inlineChar :: LP Char
inlineChar = noneOf "\\$%^_&~#{}^'`\"‘’“”-[] \t\n"
environment :: LP Blocks
environment = do
controlSeq "begin"
name <- braced
M.findWithDefault mzero name environments
<|> rawEnv name
inlineEnvironment :: LP Inlines
inlineEnvironment = try $ do
controlSeq "begin"
name <- braced
M.findWithDefault mzero name inlineEnvironments
rawEnv :: String -> LP Blocks
rawEnv name = do
let addBegin x = "\\begin{" ++ name ++ "}" ++ x
parseRaw <- getOption readerParseRaw
if parseRaw
then (rawBlock "latex" . addBegin) <$>
(withRaw (env name blocks) >>= applyMacros' . snd)
else env name blocks
----
type IncludeParser = ParserT String [String] IO String
-- | Replace "include" commands with file contents.
handleIncludes :: String -> IO (Either PandocError String)
handleIncludes s = mapLeft (ParsecError s) <$> runParserT includeParser' [] "input" s
includeParser' :: IncludeParser
includeParser' =
concat <$> many (comment' <|> escaped' <|> blob' <|> include'
<|> startMarker' <|> endMarker'
<|> verbCmd' <|> verbatimEnv' <|> backslash')
comment' :: IncludeParser
comment' = do
char '%'
xs <- manyTill anyChar newline
return ('%':xs ++ "\n")
escaped' :: IncludeParser
escaped' = try $ string "\\%" <|> string "\\\\"
verbCmd' :: IncludeParser
verbCmd' = fmap snd <$>
withRaw $ try $ do
string "\\verb"
c <- anyChar
manyTill anyChar (char c)
verbatimEnv' :: IncludeParser
verbatimEnv' = fmap snd <$>
withRaw $ try $ do
string "\\begin"
name <- braced'
guard $ name `elem` ["verbatim", "Verbatim", "lstlisting",
"minted", "alltt"]
manyTill anyChar (try $ string $ "\\end{" ++ name ++ "}")
blob' :: IncludeParser
blob' = try $ many1 (noneOf "\\%")
backslash' :: IncludeParser
backslash' = string "\\"
braced' :: IncludeParser
braced' = try $ char '{' *> manyTill (satisfy (/='}')) (char '}')
maybeAddExtension :: String -> FilePath -> FilePath
maybeAddExtension ext fp =
if null (takeExtension fp)
then addExtension fp ext
else fp
include' :: IncludeParser
include' = do
fs' <- try $ do
char '\\'
name <- try (string "include")
<|> try (string "input")
<|> string "usepackage"
-- skip options
skipMany $ try $ char '[' *> manyTill anyChar (char ']')
fs <- (map trim . splitBy (==',')) <$> braced'
return $ if name == "usepackage"
then map (maybeAddExtension ".sty") fs
else map (maybeAddExtension ".tex") fs
pos <- getPosition
containers <- getState
let fn = case containers of
(f':_) -> f'
[] -> "input"
-- now process each include file in order...
rest <- getInput
results' <- forM fs' (\f -> do
when (f `elem` containers) $
fail "Include file loop!"
contents <- lift $ readTeXFile f
return $ "\\PandocStartInclude{" ++ f ++ "}" ++
contents ++ "\\PandocEndInclude{" ++
fn ++ "}{" ++ show (sourceLine pos) ++ "}{"
++ show (sourceColumn pos) ++ "}")
setInput $ concat results' ++ rest
return ""
startMarker' :: IncludeParser
startMarker' = try $ do
string "\\PandocStartInclude"
fn <- braced'
updateState (fn:)
setPosition $ newPos fn 1 1
return $ "\\PandocStartInclude{" ++ fn ++ "}"
endMarker' :: IncludeParser
endMarker' = try $ do
string "\\PandocEndInclude"
fn <- braced'
ln <- braced'
co <- braced'
updateState tail
setPosition $ newPos fn (fromMaybe 1 $ safeRead ln) (fromMaybe 1 $ safeRead co)
return $ "\\PandocEndInclude{" ++ fn ++ "}{" ++ ln ++ "}{" ++
co ++ "}"
readTeXFile :: FilePath -> IO String
readTeXFile f = do
texinputs <- E.catch (getEnv "TEXINPUTS") $ \(_ :: E.SomeException) ->
return "."
let ds = splitBy (==':') texinputs
readFileFromDirs ds f
readFileFromDirs :: [FilePath] -> FilePath -> IO String
readFileFromDirs [] _ = return ""
readFileFromDirs (d:ds) f =
E.catch (UTF8.readFile $ d </> f) $ \(_ :: E.SomeException) ->
readFileFromDirs ds f
----
keyval :: LP (String, String)
keyval = try $ do
key <- many1 alphaNum
val <- option "" $ char '=' >> many1 alphaNum
skipMany spaceChar
optional (char ',')
skipMany spaceChar
return (key, val)
keyvals :: LP [(String, String)]
keyvals = try $ char '[' *> manyTill keyval (char ']')
alltt :: String -> LP Blocks
alltt t = walk strToCode <$> parseFromString blocks
(substitute " " "\\ " $ substitute "%" "\\%" $
intercalate "\\\\\n" $ lines t)
where strToCode (Str s) = Code nullAttr s
strToCode x = x
rawLaTeXBlock :: LP String
rawLaTeXBlock = snd <$> try (withRaw (environment <|> blockCommand))
rawLaTeXInline :: LP Inline
rawLaTeXInline = do
raw <- (snd <$> withRaw inlineCommand) <|> (snd <$> withRaw blockCommand)
RawInline "latex" <$> applyMacros' raw
addImageCaption :: Blocks -> LP Blocks
addImageCaption = walkM go
where go (Image alt (src,tit)) = do
mbcapt <- stateCaption <$> getState
return $ case mbcapt of
Just ils -> Image (toList ils) (src, "fig:")
Nothing -> Image alt (src,tit)
go x = return x
addTableCaption :: Blocks -> LP Blocks
addTableCaption = walkM go
where go (Table c als ws hs rs) = do
mbcapt <- stateCaption <$> getState
return $ case mbcapt of
Just ils -> Table (toList ils) als ws hs rs
Nothing -> Table c als ws hs rs
go x = return x
environments :: M.Map String (LP Blocks)
environments = M.fromList
[ ("document", env "document" blocks <* skipMany anyChar)
, ("letter", env "letter" letterContents)
, ("figure", env "figure" $
resetCaption *> skipopts *> blocks >>= addImageCaption)
, ("center", env "center" blocks)
, ("table", env "table" $
resetCaption *> skipopts *> blocks >>= addTableCaption)
, ("tabular*", env "tabular" $ simpTable True)
, ("tabular", env "tabular" $ simpTable False)
, ("quote", blockQuote <$> env "quote" blocks)
, ("quotation", blockQuote <$> env "quotation" blocks)
, ("verse", blockQuote <$> env "verse" blocks)
, ("itemize", bulletList <$> listenv "itemize" (many item))
, ("description", definitionList <$> listenv "description" (many descItem))
, ("enumerate", orderedList')
, ("alltt", alltt =<< verbEnv "alltt")
, ("code", guardEnabled Ext_literate_haskell *>
(codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
verbEnv "code"))
, ("verbatim", codeBlock <$> verbEnv "verbatim")
, ("Verbatim", do options <- option [] keyvals
let kvs = [ (if k == "firstnumber"
then "startFrom"
else k, v) | (k,v) <- options ]
let classes = [ "numberLines" |
lookup "numbers" options == Just "left" ]
let attr = ("",classes,kvs)
codeBlockWith attr <$> verbEnv "Verbatim")
, ("lstlisting", do options <- option [] keyvals
let kvs = [ (if k == "firstnumber"
then "startFrom"
else k, v) | (k,v) <- options ]
let classes = [ "numberLines" |
lookup "numbers" options == Just "left" ]
++ maybeToList (lookup "language" options
>>= fromListingsLanguage)
let attr = (fromMaybe "" (lookup "label" options),classes,kvs)
codeBlockWith attr <$> verbEnv "lstlisting")
, ("minted", do options <- option [] keyvals
lang <- grouped (many1 $ satisfy (/='}'))
let kvs = [ (if k == "firstnumber"
then "startFrom"
else k, v) | (k,v) <- options ]
let classes = [ lang | not (null lang) ] ++
[ "numberLines" |
lookup "linenos" options == Just "true" ]
let attr = ("",classes,kvs)
codeBlockWith attr <$> verbEnv "minted")
, ("obeylines", parseFromString
(para . trimInlines . mconcat <$> many inline) =<<
intercalate "\\\\\n" . lines <$> verbEnv "obeylines")
, ("displaymath", mathEnv para Nothing "displaymath")
, ("equation", mathEnv para Nothing "equation")
, ("equation*", mathEnv para Nothing "equation*")
, ("gather", mathEnv para (Just "gathered") "gather")
, ("gather*", mathEnv para (Just "gathered") "gather*")
, ("multline", mathEnv para (Just "gathered") "multline")
, ("multline*", mathEnv para (Just "gathered") "multline*")
, ("eqnarray", mathEnv para (Just "aligned") "eqnarray")
, ("eqnarray*", mathEnv para (Just "aligned") "eqnarray*")
, ("align", mathEnv para (Just "aligned") "align")
, ("align*", mathEnv para (Just "aligned") "align*")
, ("alignat", mathEnv para (Just "aligned") "alignat")
, ("alignat*", mathEnv para (Just "aligned") "alignat*")
]
letterContents :: LP Blocks
letterContents = do
bs <- blocks
st <- getState
-- add signature (author) and address (title)
let addr = case lookupMeta "address" (stateMeta st) of
Just (MetaBlocks [Plain xs]) ->
para $ trimInlines $ fromList xs
_ -> mempty
return $ addr <> bs -- sig added by \closing
closing :: LP Blocks
closing = do
contents <- tok
st <- getState
let extractInlines (MetaBlocks [Plain ys]) = ys
extractInlines (MetaBlocks [Para ys ]) = ys
extractInlines _ = []
let sigs = case lookupMeta "author" (stateMeta st) of
Just (MetaList xs) ->
para $ trimInlines $ fromList $
intercalate [LineBreak] $ map extractInlines xs
_ -> mempty
return $ para (trimInlines contents) <> sigs
item :: LP Blocks
item = blocks *> controlSeq "item" *> skipopts *> blocks
looseItem :: LP Blocks
looseItem = do
ctx <- stateParserContext `fmap` getState
if ctx == ListItemState
then mzero
else return mempty
descItem :: LP (Inlines, [Blocks])
descItem = do
blocks -- skip blocks before item
controlSeq "item"
optional sp
ils <- opt
bs <- blocks
return (ils, [bs])
env :: String -> LP a -> LP a
env name p = p <*
(try (controlSeq "end" *> braced >>= guard . (== name))
<?> ("\\end{" ++ name ++ "}"))
listenv :: String -> LP a -> LP a
listenv name p = try $ do
oldCtx <- stateParserContext `fmap` getState
updateState $ \st -> st{ stateParserContext = ListItemState }
res <- env name p
updateState $ \st -> st{ stateParserContext = oldCtx }
return res
mathEnv :: (Inlines -> a) -> Maybe String -> String -> LP a
mathEnv f innerEnv name = f <$> mathDisplay (inner <$> verbEnv name)
where inner x = case innerEnv of
Nothing -> x
Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
"\\end{" ++ y ++ "}"
verbEnv :: String -> LP String
verbEnv name = do
skipopts
optional blankline
let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
res <- manyTill anyChar endEnv
return $ stripTrailingNewlines res
orderedList' :: LP Blocks
orderedList' = do
optional sp
(_, style, delim) <- option (1, DefaultStyle, DefaultDelim) $
try $ char '[' *> anyOrderedListMarker <* char ']'
spaces
optional $ try $ controlSeq "setlength" *> grouped (controlSeq "itemindent") *> braced
spaces
start <- option 1 $ try $ do controlSeq "setcounter"
grouped (string "enum" *> many1 (oneOf "iv"))
optional sp
num <- grouped (many1 digit)
spaces
return (read num + 1 :: Int)
bs <- listenv "enumerate" (many item)
return $ orderedListWith (start, style, delim) bs
paragraph :: LP Blocks
paragraph = do
x <- trimInlines . mconcat <$> many1 inline
if x == mempty
then return mempty
else return $ para x
preamble :: LP Blocks
preamble = mempty <$> manyTill preambleBlock beginDoc
where beginDoc = lookAhead $ try $ controlSeq "begin" *> string "{document}"
preambleBlock = void comment
<|> void sp
<|> void blanklines
<|> void macro
<|> void blockCommand
<|> void anyControlSeq
<|> void braced
<|> void anyChar
-------
-- citations
addPrefix :: [Inline] -> [Citation] -> [Citation]
addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
addPrefix _ _ = []
addSuffix :: [Inline] -> [Citation] -> [Citation]
addSuffix s ks@(_:_) =
let k = last ks
in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
addSuffix _ _ = []
simpleCiteArgs :: LP [Citation]
simpleCiteArgs = try $ do
first <- optionMaybe $ toList <$> opt
second <- optionMaybe $ toList <$> opt
char '{'
optional sp
keys <- manyTill citationLabel (char '}')
let (pre, suf) = case (first , second ) of
(Just s , Nothing) -> (mempty, s )
(Just s , Just t ) -> (s , t )
_ -> (mempty, mempty)
conv k = Citation { citationId = k
, citationPrefix = []
, citationSuffix = []
, citationMode = NormalCitation
, citationHash = 0
, citationNoteNum = 0
}
return $ addPrefix pre $ addSuffix suf $ map conv keys
citationLabel :: LP String
citationLabel = optional sp *>
(many1 (satisfy isBibtexKeyChar)
<* optional sp
<* optional (char ',')
<* optional sp)
where isBibtexKeyChar c = isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]*" :: String)
cites :: CitationMode -> Bool -> LP [Citation]
cites mode multi = try $ do
cits <- if multi
then many1 simpleCiteArgs
else count 1 simpleCiteArgs
let cs = concat cits
return $ case mode of
AuthorInText -> case cs of
(c:rest) -> c {citationMode = mode} : rest
[] -> []
_ -> map (\a -> a {citationMode = mode}) cs
citation :: String -> CitationMode -> Bool -> LP Inlines
citation name mode multi = do
(c,raw) <- withRaw $ cites mode multi
return $ cite c (rawInline "latex" $ "\\" ++ name ++ raw)
complexNatbibCitation :: CitationMode -> LP Inlines
complexNatbibCitation mode = try $ do
let ils = (toList . trimInlines . mconcat) <$>
many (notFollowedBy (oneOf "\\};") >> inline)
let parseOne = try $ do
skipSpaces
pref <- ils
cit' <- inline -- expect a citation
let citlist = toList cit'
cits' <- case citlist of
[Cite cs _] -> return cs
_ -> mzero
suff <- ils
skipSpaces
optional $ char ';'
return $ addPrefix pref $ addSuffix suff cits'
(c:cits, raw) <- withRaw $ grouped parseOne
return $ cite (c{ citationMode = mode }:cits)
(rawInline "latex" $ "\\citetext" ++ raw)
-- tables
parseAligns :: LP [Alignment]
parseAligns = try $ do
char '{'
let maybeBar = skipMany $ sp <|> () <$ char '|' <|> () <$ (char '@' >> braced)
maybeBar
let cAlign = AlignCenter <$ char 'c'
let lAlign = AlignLeft <$ char 'l'
let rAlign = AlignRight <$ char 'r'
let parAlign = AlignLeft <$ (char 'p' >> braced)
let alignChar = cAlign <|> lAlign <|> rAlign <|> parAlign
aligns' <- sepEndBy alignChar maybeBar
spaces
char '}'
spaces
return aligns'
hline :: LP ()
hline = () <$ try (spaces' *> controlSeq "hline" <* spaces')
lbreak :: LP ()
lbreak = () <$ try (spaces' *> controlSeq "\\" <* spaces')
amp :: LP ()
amp = () <$ try (spaces' *> char '&')
parseTableRow :: Int -- ^ number of columns
-> LP [Blocks]
parseTableRow cols = try $ do
let tableCellInline = notFollowedBy (amp <|> lbreak) >> inline
let tableCell = (plain . trimInlines . mconcat) <$> many tableCellInline
cells' <- sepBy1 tableCell amp
let numcells = length cells'
guard $ numcells <= cols && numcells >= 1
guard $ cells' /= [mempty]
-- note: a & b in a three-column table leaves an empty 3rd cell:
let cells'' = cells' ++ replicate (cols - numcells) mempty
spaces'
return cells''
spaces' :: LP ()
spaces' = spaces *> skipMany (comment *> spaces)
simpTable :: Bool -> LP Blocks
simpTable hasWidthParameter = try $ do
when hasWidthParameter $ () <$ (spaces' >> tok)
skipopts
aligns <- parseAligns
let cols = length aligns
optional hline
header' <- option [] $ try (parseTableRow cols <* lbreak <* hline)
rows <- sepEndBy (parseTableRow cols) (lbreak <* optional hline)
spaces'
let header'' = if null header'
then replicate cols mempty
else header'
lookAhead $ controlSeq "end" -- make sure we're at end
return $ table mempty (zip aligns (repeat 0)) header'' rows
startInclude :: LP Blocks
startInclude = do
fn <- braced
setPosition $ newPos fn 1 1
return mempty
endInclude :: LP Blocks
endInclude = do
fn <- braced
ln <- braced
co <- braced
setPosition $ newPos fn (fromMaybe 1 $ safeRead ln) (fromMaybe 1 $ safeRead co)
return mempty
| csrhodes/pandoc | src/Text/Pandoc/Readers/LaTeX.hs | gpl-2.0 | 45,144 | 0 | 29 | 11,883 | 15,632 | 8,039 | 7,593 | 1,148 | 4 |
-- Body of the HTML page for a package
{-# LANGUAGE PatternGuards, RecordWildCards #-}
module Distribution.Server.Pages.Package (
packagePage,
renderDependencies,
renderVersion,
renderFields,
renderDownloads
) where
import Distribution.Server.Features.PreferredVersions
import Distribution.Server.Pages.Template (hackagePageWith)
import Distribution.Server.Pages.Package.HaddockParse (parseHaddockParagraphs)
import Distribution.Server.Pages.Package.HaddockLex (tokenise)
import Distribution.Server.Pages.Package.HaddockHtml
import Distribution.Server.Packages.ModuleForest
import Distribution.Server.Packages.Render
import Distribution.Server.Users.Types (userStatus, userName, isActiveAccount)
import Distribution.Package
import Distribution.PackageDescription as P
import Distribution.Simple.Utils ( cabalVersion )
import Distribution.Version
import Distribution.Text (display)
import Text.XHtml.Strict hiding (p, name, title, content)
import Data.Monoid (Monoid(..))
import Data.Maybe (maybeToList)
import Data.List (intersperse, intercalate)
import System.FilePath.Posix ((</>), (<.>))
import System.Locale (defaultTimeLocale)
import Data.Time.Format (formatTime)
packagePage :: PackageRender -> [Html] -> [Html] -> [(String, Html)] -> [(String, Html)] -> Maybe URL -> Bool -> Html
packagePage render headLinks top sections bottom docURL isCandidate =
hackagePageWith [] docTitle docSubtitle docBody [docFooter]
where
pkgid = rendPkgId render
docTitle = display (packageName pkgid)
++ case synopsis (rendOther render) of
"" -> ""
short -> ": " ++ short
docSubtitle = toHtml docTitle
docBody = h1 << bodyTitle
: concat [
renderHeads,
top,
pkgBody render sections,
moduleSection render docURL,
packageFlags render,
downloadSection render,
maintainerSection pkgid isCandidate,
map pair bottom
]
bodyTitle = "The " ++ display (pkgName pkgid) ++ " package"
renderHeads = case headLinks of
[] -> []
items -> [thediv ! [thestyle "font-size: small"] <<
(map (\item -> "[" +++ item +++ "] ") items)]
docFooter = thediv ! [identifier "footer"]
<< paragraph
<< [ toHtml "Produced by "
, anchor ! [href "/"] << "hackage"
, toHtml " and "
, anchor ! [href cabalHomeURL] << "Cabal"
, toHtml (" " ++ display cabalVersion) ]
pair (title, content) =
toHtml [ h2 << title, content ]
-- | Body of the package page
pkgBody :: PackageRender -> [(String, Html)] -> [Html]
pkgBody render sections =
descriptionSection render
++ propertySection sections
descriptionSection :: PackageRender -> [Html]
descriptionSection PackageRender{..} =
prologue (description rendOther)
++ [ hr
, ulist << li << changelogLink]
where
changelogLink
| rendHasChangeLog = anchor ! [href changeLogURL] << "Changelog"
| otherwise = toHtml << "No changelog available"
changeLogURL = rendPkgUri </> "changelog"
prologue :: String -> [Html]
prologue [] = []
prologue desc = case tokenise desc >>= parseHaddockParagraphs of
Nothing -> [paragraph << p | p <- paragraphs desc]
Just doc -> [markup htmlMarkup doc]
-- Break text into paragraphs (separated by blank lines)
paragraphs :: String -> [String]
paragraphs = map unlines . paras . lines
where paras xs = case dropWhile null xs of
[] -> []
xs' -> case break null xs' of
(para, xs'') -> para : paras xs''
downloadSection :: PackageRender -> [Html]
downloadSection PackageRender{..} =
[ h2 << "Downloads"
, ulist << map (li <<) downloadItems
]
where
downloadItems =
[ if rendHasTarball
then [ anchor ! [href downloadURL] << tarGzFileName
, toHtml << " ["
, anchor ! [href srcURL] << "browse"
, toHtml << "]"
, toHtml << " (Cabal source package)"
]
else [ toHtml << "Package tarball not uploaded" ]
, [ anchor ! [href cabalURL] << "Package description"
, toHtml $ if rendHasTarball then " (included in the package)" else ""
]
]
downloadURL = rendPkgUri </> display rendPkgId <.> "tar.gz"
cabalURL = rendPkgUri </> display (packageName rendPkgId) <.> "cabal"
srcURL = rendPkgUri </> "src/"
tarGzFileName = display rendPkgId ++ ".tar.gz"
maintainerSection :: PackageId -> Bool -> [Html]
maintainerSection pkgid isCandidate =
[ h4 << "Maintainers' corner"
, paragraph << "For package maintainers and hackage trustees"
, ulist << li << anchor ! [href maintainURL]
<< "edit package information"
]
where
maintainURL | isCandidate = "candidate/maintain"
| otherwise = display (packageName pkgid) </> "maintain"
-- | Render a table of the package's flags and along side it a tip
-- indicating how to enable/disable flags with Cabal.
packageFlags :: PackageRender -> [Html]
packageFlags render =
case rendFlags render of
[] -> mempty
flags ->
[h2 << "Flags"
,flagsTable flags
,tip]
where tip =
paragraph ! [theclass "tip"] <<
[thespan << "Use "
,code "-f <flag>"
,thespan << " to enable a flag, or "
,code "-f -<flag>"
,thespan << " to disable that flag. "
,anchor ! [href tipLink] << "More info"
]
tipLink = "http://www.haskell.org/cabal/users-guide/installing-packages.html#controlling-flag-assignments"
flagsTable flags =
table ! [theclass "flags-table"] <<
[thead << flagsHeadings
,tbody << map flagRow flags]
flagsHeadings = [th << "Name"
,th << "Description"
,th << "Default"]
flagRow flag =
tr << [td ! [theclass "flag-name"] << code (case flagName flag of FlagName name -> name)
,td ! [theclass "flag-desc"] << flagDescription flag
,td ! [theclass (if flagDefault flag then "flag-enabled" else "flag-disabled")] <<
if flagDefault flag then "Enabled" else "Disabled"]
code = (thespan ! [theclass "code"] <<)
moduleSection :: PackageRender -> Maybe URL -> [Html]
moduleSection render docURL = maybeToList $ fmap msect (rendModules render)
where msect lib = toHtml
[ h2 << "Modules"
, renderModuleForest docURL lib
, renderDocIndexLink docURL
]
renderDocIndexLink = maybe mempty $ \docURL' ->
let docIndexURL = docURL' </> "doc-index.html"
in paragraph ! [thestyle "font-size: small"]
<< ("[" +++ anchor ! [href docIndexURL] << "Index" +++ "]")
propertySection :: [(String, Html)] -> [Html]
propertySection sections =
[ h2 << "Properties"
, tabulate $ filter (not . isNoHtml . snd) sections
]
tabulate :: [(String, Html)] -> Html
tabulate items = table ! [theclass "properties"] <<
[tr << [th << t, td << d] | (t, d) <- items]
renderDependencies :: PackageRender -> (String, Html)
renderDependencies render = ("Dependencies", case htmlDepsList of
[] -> toHtml "None"
_ -> foldr (+++) noHtml htmlDepsList)
where htmlDepsList =
intersperse (toHtml " " +++ bold (toHtml "or") +++ br) $
map showDependencies (rendDepends render)
showDependencies :: [Dependency] -> Html
showDependencies deps = commaList (map showDependency deps)
showDependency :: Dependency -> Html
showDependency (Dependency (PackageName pname) vs) = showPkg +++ vsHtml
where vsHtml = if vs == anyVersion then noHtml
else toHtml (" (" ++ display vs ++ ")")
-- mb_vers links to latest version in range. This is a bit computationally
-- expensive, not cache-friendly, and perhaps unexpected in some cases
{-mb_vers = maybeLast $ filter (`withinRange` vs) $ map packageVersion $
PackageIndex.lookupPackageName vmap (PackageName pname)-}
-- nonetheless, we should ensure that the package exists /before/
-- passing along the PackageRender, which is not the case here
showPkg = anchor ! [href . packageURL $ PackageIdentifier (PackageName pname) (Version [] [])] << pname
renderVersion :: PackageId -> [(Version, VersionStatus)] -> Maybe String -> (String, Html)
renderVersion (PackageIdentifier pname pversion) allVersions info =
(if null earlierVersions && null laterVersions then "Version" else "Versions", versionList +++ infoHtml)
where (earlierVersions, laterVersionsInc) = span ((<pversion) . fst) allVersions
(mThisVersion, laterVersions) = case laterVersionsInc of
(v:later) | fst v == pversion -> (Just v, later)
later -> (Nothing, later)
versionList = commaList $ map versionedLink earlierVersions
++ (case pversion of
Version [] [] -> []
_ -> [strong ! (maybe [] (status . snd) mThisVersion) << display pversion]
)
++ map versionedLink laterVersions
versionedLink (v, s) = anchor ! (status s ++ [href $ packageURL $ PackageIdentifier pname v]) << display v
status st = case st of
NormalVersion -> []
DeprecatedVersion -> [theclass "deprecated"]
UnpreferredVersion -> [theclass "unpreferred"]
infoHtml = case info of Nothing -> noHtml; Just str -> " (" +++ (anchor ! [href str] << "info") +++ ")"
-- We don't keep currently per-version downloads in memory; if we decide that
-- it is important to show this all the time, we can reenable
renderDownloads :: Int -> Int -> {- Int -> Version -> -} (String, Html)
renderDownloads totalDown recentDown {- versionDown version -} =
("Downloads", toHtml $ {- show versionDown ++ " for " ++ display version ++
" and " ++ -} show totalDown ++ " total (" ++
show recentDown ++ " in last 30 days)")
renderFields :: PackageRender -> [(String, Html)]
renderFields render = [
-- Cabal-Version
("License", toHtml $ rendLicenseName render),
("Copyright", toHtml $ P.copyright desc),
("Author", toHtml $ author desc),
("Maintainer", maintainField $ rendMaintainer render),
("Stability", toHtml $ stability desc),
("Category", commaList . map categoryField $ rendCategory render),
("Home page", linkField $ homepage desc),
("Bug tracker", linkField $ bugReports desc),
("Source repository", vList $ map sourceRepositoryField $ sourceRepos desc),
("Executables", commaList . map toHtml $ rendExecNames render),
("Uploaded", uncurry renderUploadInfo (rendUploadInfo render))
]
++ [ ("Updated", renderUpdateInfo revisionNo utime uinfo)
| (revisionNo, utime, uinfo) <- maybeToList (rendUpdateInfo render) ]
where
desc = rendOther render
renderUploadInfo utime uinfo =
formatTime defaultTimeLocale "%c" utime +++ " by " +++ user
where
uname = maybe "Unknown" (display . userName) uinfo
uactive = maybe False (isActiveAccount . userStatus) uinfo
user | uactive = anchor ! [href $ "/user/" ++ uname] << uname
| otherwise = toHtml uname
renderUpdateInfo revisionNo utime uinfo =
renderUploadInfo utime uinfo +++ " to " +++
anchor ! [href revisionsURL] << ("revision " +++ show revisionNo)
where
revisionsURL = display (rendPkgId render) </> "revisions/"
linkField url = case url of
[] -> noHtml
_ -> anchor ! [href url] << url
categoryField cat = anchor ! [href $ "/packages/#cat:" ++ cat] << cat
maintainField mnt = case mnt of
Nothing -> strong ! [theclass "warning"] << toHtml "none"
Just n -> toHtml n
sourceRepositoryField sr = sourceRepositoryToHtml sr
sourceRepositoryToHtml :: SourceRepo -> Html
sourceRepositoryToHtml sr
= toHtml (display (repoKind sr) ++ ": ")
+++ case repoType sr of
Just Darcs
| (Just url, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr) ->
concatHtml [toHtml "darcs get ",
anchor ! [href url] << toHtml url,
case repoTag sr of
Just tag' -> toHtml (" --tag " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml " ("
+++ (anchor ! [href (url </> sd)]
<< toHtml sd)
+++ toHtml ")"
Nothing -> noHtml]
Just Git
| (Just url, Nothing) <-
(repoLocation sr, repoModule sr) ->
concatHtml [toHtml "git clone ",
anchor ! [href url] << toHtml url,
case repoBranch sr of
Just branch -> toHtml (" -b " ++ branch)
Nothing -> noHtml,
case repoTag sr of
Just tag' -> toHtml ("(tag " ++ tag' ++ ")")
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just SVN
| (Just url, Nothing, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr, repoTag sr) ->
concatHtml [toHtml "svn checkout ",
anchor ! [href url] << toHtml url,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just CVS
| (Just url, Just m, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr, repoTag sr) ->
concatHtml [toHtml "cvs -d ",
anchor ! [href url] << toHtml url,
toHtml (" " ++ m),
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just Mercurial
| (Just url, Nothing) <-
(repoLocation sr, repoModule sr) ->
concatHtml [toHtml "hg clone ",
anchor ! [href url] << toHtml url,
case repoBranch sr of
Just branch -> toHtml (" -b " ++ branch)
Nothing -> noHtml,
case repoTag sr of
Just tag' -> toHtml (" -u " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
Just Bazaar
| (Just url, Nothing, Nothing) <-
(repoLocation sr, repoModule sr, repoBranch sr) ->
concatHtml [toHtml "bzr branch ",
anchor ! [href url] << toHtml url,
case repoTag sr of
Just tag' -> toHtml (" -r " ++ tag')
Nothing -> noHtml,
case repoSubdir sr of
Just sd -> toHtml ("(" ++ sd ++ ")")
Nothing -> noHtml]
_ ->
-- We don't know how to show this SourceRepo.
-- This is a kludge so that we at least show all the info.
toHtml (show sr)
commaList :: [Html] -> Html
commaList = concatHtml . intersperse (toHtml ", ")
vList :: [Html] -> Html
vList = concatHtml . intersperse br
-----------------------------------------------------------------------------
renderModuleForest :: Maybe URL -> ModuleForest -> Html
renderModuleForest mb_url forest =
thediv ! [identifier "module-list"] << renderForest [] forest
where
renderForest _ [] = noHtml
renderForest pathRev ts = myUnordList $ map renderTree ts
where
renderTree (Node s isModule subs) =
( if isModule then moduleEntry newPath else italics << s )
+++ renderForest newPathRev subs
where
newPathRev = s:pathRev
newPath = reverse newPathRev
moduleEntry path =
thespan ! [theclass "module"] << maybe modName linkedName mb_url path
modName path = toHtml (intercalate "." path)
linkedName url path = anchor ! [href modUrl] << modName path
where
modUrl = url ++ "/" ++ intercalate "-" path ++ ".html"
myUnordList :: HTML a => [a] -> Html
myUnordList = unordList ! [theclass "modules"]
------------------------------------------------------------------------------
-- TODO: most of these should be available from the CoreFeature
-- so pass it in to this module
-- | URL describing a package.
packageURL :: PackageIdentifier -> URL
packageURL pkgId = "/package" </> display pkgId
--cabalLogoURL :: URL
--cabalLogoURL = "/built-with-cabal.png"
-- global URLs
cabalHomeURL :: URL
cabalHomeURL = "http://haskell.org/cabal/"
| haskell-infra/hackage-server | Distribution/Server/Pages/Package.hs | bsd-3-clause | 17,668 | 0 | 23 | 5,762 | 4,659 | 2,440 | 2,219 | 329 | 19 |
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Reddit
( handler
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Control.Monad.Trans (liftIO)
import Data.Aeson (FromJSON (..), Object, Value (..), (.:))
import qualified Data.HashMap.Lazy as HM
import Data.Text (Text)
import qualified Data.Text as T
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Util
import NumberSix.Util.BitLy
import NumberSix.Util.Error
import NumberSix.Util.Http
--------------------------------------------------------------------------------
data Reddit = Reddit [Link] deriving (Show)
--------------------------------------------------------------------------------
instance FromJSON Reddit where
parseJSON (Object o) = let o' = unData o in Reddit <$> o' .: "children"
parseJSON _ = mzero
--------------------------------------------------------------------------------
data Link = Link Text Text deriving (Show)
--------------------------------------------------------------------------------
instance FromJSON Link where
parseJSON (Object o) =
let o' = unData o in Link <$> o' .: "title" <*> o' .: "url"
parseJSON _ = mzero
--------------------------------------------------------------------------------
-- | Fetch the data attribute from an object. Reddit's ugly json...
unData :: Object -> Object
unData o = case HM.lookup "data" o of Just (Object o') -> o'; _ -> HM.empty
--------------------------------------------------------------------------------
reddit :: Text -> IO Text
reddit query = http url id >>= \bs -> case parseJsonEither bs of
Left _ -> randomError
Right (Reddit ls) -> do
Link t u <- case idx of
Nothing -> randomElement ls
Just i -> return $ ls !! (i - 1)
textAndUrl t u
where
url = "http://reddit.com/r/" <> subreddit <> ".json"
(subreddit, idx) = case T.words query of
[s, i] -> (s, readText i)
[s] -> case readText s of
Just i -> ("all", Just i)
Nothing -> (s, Nothing)
_ -> ("all", Nothing)
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "Reddit" ["!reddit"] $ liftIO . reddit
| itkovian/number-six | src/NumberSix/Handlers/Reddit.hs | bsd-3-clause | 2,660 | 0 | 18 | 627 | 614 | 338 | 276 | 44 | 6 |
-- Copyright (c) 1998 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module CollectionUtils
{-# DEPRECATED "This module is unmaintained, and will disappear soon" #-}
where
import Prelude hiding (map,null,foldr,foldl,foldr1,foldl1,lookup,filter)
import Collection
map :: (Coll cin a, CollX cout b) => (a -> b) -> (cin a -> cout b)
map f xs = fold (\x ys -> insert (f x) ys) empty xs
mapPartial :: (Coll cin a, CollX cout b) => (a -> Maybe b) -> (cin a -> cout b)
mapPartial f xs = fold (\ x ys -> case f x of
Just y -> insert y ys
Nothing -> ys)
empty xs
unsafeMapMonotonic :: (OrdColl cin a, OrdCollX cout b) => (a -> b) -> (cin a -> cout b)
unsafeMapMonotonic f xs = foldr (unsafeInsertMin . f) empty xs
unionMap :: (Coll cin a, CollX cout b) => (a -> cout b) -> (cin a -> cout b)
unionMap f xs = fold (\x ys -> union (f x) ys) empty xs
| alekar/hugs | fptools/hslibs/data/edison/Coll/CollectionUtils.hs | bsd-3-clause | 959 | 3 | 11 | 275 | 397 | 208 | 189 | 15 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Std_msgs.UInt16 where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import qualified Data.Word as Word
import Foreign.Storable (Storable(..))
import qualified Ros.Internal.Util.StorableMonad as SM
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data UInt16 = UInt16 { __data :: Word.Word16
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''UInt16)
instance RosBinary UInt16 where
put obj' = put (__data obj')
get = UInt16 <$> get
instance Storable UInt16 where
sizeOf _ = sizeOf (P.undefined::Word.Word16)
alignment _ = 8
peek = SM.runStorable (UInt16 <$> SM.peek)
poke ptr' obj' = SM.runStorable store' ptr'
where store' = SM.poke (__data obj')
instance MsgInfo UInt16 where
sourceMD5 _ = "1df79edf208b629fe6b81923a544552d"
msgTypeName _ = "std_msgs/UInt16"
instance D.Default UInt16
| acowley/roshask | msgs/Std_msgs/Ros/Std_msgs/UInt16.hs | bsd-3-clause | 1,237 | 1 | 10 | 197 | 356 | 209 | 147 | 34 | 0 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Attoparsec/Text.hs" #-}
{-# LANGUAGE BangPatterns, CPP, FlexibleInstances, TypeSynonymInstances #-}
{-# LANGUAGE Trustworthy #-} -- Imports internal modules
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
-- |
-- Module : Data.Attoparsec.Text
-- Copyright : Bryan O'Sullivan 2007-2015
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
-- Simple, efficient combinator parsing for 'Text' strings,
-- loosely based on the Parsec library.
module Data.Attoparsec.Text
(
-- * Differences from Parsec
-- $parsec
-- * Incremental input
-- $incremental
-- * Performance considerations
-- $performance
-- * Parser types
Parser
, Result
, T.IResult(..)
, I.compareResults
-- * Running parsers
, parse
, feed
, I.parseOnly
, parseWith
, parseTest
-- ** Result conversion
, maybeResult
, eitherResult
-- * Parsing individual characters
, I.char
, I.anyChar
, I.notChar
, I.satisfy
, I.satisfyWith
, I.skip
-- ** Lookahead
, I.peekChar
, I.peekChar'
-- ** Special character parsers
, digit
, letter
, space
-- ** Character classes
, I.inClass
, I.notInClass
-- * Efficient string handling
, I.string
, I.stringCI
, I.asciiCI
, skipSpace
, I.skipWhile
, I.scan
, I.runScanner
, I.take
, I.takeWhile
, I.takeWhile1
, I.takeTill
-- ** String combinators
-- $specalt
, (.*>)
, (<*.)
-- ** Consume all remaining input
, I.takeText
, I.takeLazyText
-- * Text parsing
, I.endOfLine
, isEndOfLine
, isHorizontalSpace
-- * Numeric parsers
, decimal
, hexadecimal
, signed
, double
, Number(..)
, number
, rational
, scientific
-- * Combinators
, try
, (<?>)
, choice
, count
, option
, many'
, many1
, many1'
, manyTill
, manyTill'
, sepBy
, sepBy'
, sepBy1
, sepBy1'
, skipMany
, skipMany1
, eitherP
, I.match
-- * State observation and manipulation functions
, I.endOfInput
, I.atEnd
) where
import Control.Applicative ((<|>))
import Data.Attoparsec.Combinator
import Data.Attoparsec.Number (Number(..))
import Data.Scientific (Scientific)
import qualified Data.Scientific as Sci
import Data.Attoparsec.Text.Internal (Parser, Result, parse, takeWhile1)
import Data.Bits (Bits, (.|.), shiftL)
import Data.Char (isAlpha, isDigit, isSpace, ord)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intercalate)
import Data.Text (Text)
import Data.Word (Word8, Word16, Word32, Word64)
import qualified Data.Attoparsec.Internal as I
import qualified Data.Attoparsec.Internal.Types as T
import qualified Data.Attoparsec.Text.Internal as I
import qualified Data.Text as T
-- $parsec
--
-- Compared to Parsec 3, attoparsec makes several tradeoffs. It is
-- not intended for, or ideal for, all possible uses.
--
-- * While attoparsec can consume input incrementally, Parsec cannot.
-- Incremental input is a huge deal for efficient and secure network
-- and system programming, since it gives much more control to users
-- of the library over matters such as resource usage and the I/O
-- model to use.
--
-- * Much of the performance advantage of attoparsec is gained via
-- high-performance parsers such as 'I.takeWhile' and 'I.string'.
-- If you use complicated combinators that return lists of
-- characters, there is less performance difference between the two
-- libraries.
--
-- * Unlike Parsec 3, attoparsec does not support being used as a
-- monad transformer.
--
-- * attoparsec is specialised to deal only with strict 'Text'
-- input. Efficiency concerns rule out both lists and lazy text.
-- The usual use for lazy text would be to allow consumption of very
-- large input without a large footprint. For this need,
-- attoparsec's incremental input provides an excellent substitute,
-- with much more control over when input takes place. If you must
-- use lazy text, see the 'Lazy' module, which feeds lazy chunks to
-- a regular parser.
--
-- * Parsec parsers can produce more helpful error messages than
-- attoparsec parsers. This is a matter of focus: attoparsec avoids
-- the extra book-keeping in favour of higher performance.
-- $incremental
--
-- attoparsec supports incremental input, meaning that you can feed it
-- a 'Text' that represents only part of the expected total amount
-- of data to parse. If your parser reaches the end of a fragment of
-- input and could consume more input, it will suspend parsing and
-- return a 'T.Partial' continuation.
--
-- Supplying the 'T.Partial' continuation with another string will
-- resume parsing at the point where it was suspended, with the string
-- you supplied used as new input at the end of the existing
-- input. You must be prepared for the result of the resumed parse to
-- be another 'Partial' continuation.
--
-- To indicate that you have no more input, supply the 'Partial'
-- continuation with an 'T.empty' 'Text'.
--
-- Remember that some parsing combinators will not return a result
-- until they reach the end of input. They may thus cause 'T.Partial'
-- results to be returned.
--
-- If you do not need support for incremental input, consider using
-- the 'I.parseOnly' function to run your parser. It will never
-- prompt for more input.
--
-- /Note/: incremental input does /not/ imply that attoparsec will
-- release portions of its internal state for garbage collection as it
-- proceeds. Its internal representation is equivalent to a single
-- 'Text': if you feed incremental input to an a parser, it will
-- require memory proportional to the amount of input you supply.
-- (This is necessary to support arbitrary backtracking.)
-- $performance
--
-- If you write an attoparsec-based parser carefully, it can be
-- realistic to expect it to perform similarly to a hand-rolled C
-- parser (measuring megabytes parsed per second).
--
-- To actually achieve high performance, there are a few guidelines
-- that it is useful to follow.
--
-- Use the 'Text'-oriented parsers whenever possible,
-- e.g. 'I.takeWhile1' instead of 'many1' 'I.anyChar'. There is
-- about a factor of 100 difference in performance between the two
-- kinds of parser.
--
-- For very simple character-testing predicates, write them by hand
-- instead of using 'I.inClass' or 'I.notInClass'. For instance, both
-- of these predicates test for an end-of-line character, but the
-- first is much faster than the second:
--
-- >endOfLine_fast c = c == '\r' || c == '\n'
-- >endOfLine_slow = inClass "\r\n"
--
-- Make active use of benchmarking and profiling tools to measure,
-- find the problems with, and improve the performance of your parser.
-- | Run a parser and print its result to standard output.
parseTest :: (Show a) => I.Parser a -> Text -> IO ()
parseTest p s = print (parse p s)
-- | Run a parser with an initial input string, and a monadic action
-- that can supply more input if needed.
parseWith :: Monad m =>
(m Text)
-- ^ An action that will be executed to provide the parser
-- with more input, if necessary. The action must return an
-- 'T.empty' string when there is no more input available.
-> I.Parser a
-> Text
-- ^ Initial input for the parser.
-> m (Result a)
parseWith refill p s = step $ parse p s
where step (T.Partial k) = (step . k) =<< refill
step r = return r
{-# INLINE parseWith #-}
-- | Convert a 'Result' value to a 'Maybe' value. A 'Partial' result
-- is treated as failure.
maybeResult :: Result r -> Maybe r
maybeResult (T.Done _ r) = Just r
maybeResult _ = Nothing
-- | Convert a 'Result' value to an 'Either' value. A 'Partial' result
-- is treated as failure.
eitherResult :: Result r -> Either String r
eitherResult (T.Done _ r) = Right r
eitherResult (T.Fail _ [] msg) = Left msg
eitherResult (T.Fail _ ctxs msg) = Left (intercalate " > " ctxs ++ ": " ++ msg)
eitherResult _ = Left "Result: incomplete input"
-- | A predicate that matches either a carriage return @\'\\r\'@ or
-- newline @\'\\n\'@ character.
isEndOfLine :: Char -> Bool
isEndOfLine c = c == '\n' || c == '\r'
{-# INLINE isEndOfLine #-}
-- | A predicate that matches either a space @\' \'@ or horizontal tab
-- @\'\\t\'@ character.
isHorizontalSpace :: Char -> Bool
isHorizontalSpace c = c == ' ' || c == '\t'
{-# INLINE isHorizontalSpace #-}
-- | Parse and decode an unsigned hexadecimal number. The hex digits
-- @\'a\'@ through @\'f\'@ may be upper or lower case.
--
-- This parser does not accept a leading @\"0x\"@ string.
hexadecimal :: (Integral a, Bits a) => Parser a
hexadecimal = T.foldl' step 0 `fmap` takeWhile1 isHexDigit
where
isHexDigit c = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
step a c | w >= 48 && w <= 57 = (a `shiftL` 4) .|. fromIntegral (w - 48)
| w >= 97 = (a `shiftL` 4) .|. fromIntegral (w - 87)
| otherwise = (a `shiftL` 4) .|. fromIntegral (w - 55)
where w = ord c
{-# SPECIALISE hexadecimal :: Parser Int #-}
{-# SPECIALISE hexadecimal :: Parser Int8 #-}
{-# SPECIALISE hexadecimal :: Parser Int16 #-}
{-# SPECIALISE hexadecimal :: Parser Int32 #-}
{-# SPECIALISE hexadecimal :: Parser Int64 #-}
{-# SPECIALISE hexadecimal :: Parser Integer #-}
{-# SPECIALISE hexadecimal :: Parser Word #-}
{-# SPECIALISE hexadecimal :: Parser Word8 #-}
{-# SPECIALISE hexadecimal :: Parser Word16 #-}
{-# SPECIALISE hexadecimal :: Parser Word32 #-}
{-# SPECIALISE hexadecimal :: Parser Word64 #-}
-- | Parse and decode an unsigned decimal number.
decimal :: Integral a => Parser a
decimal = T.foldl' step 0 `fmap` takeWhile1 isDecimal
where step a c = a * 10 + fromIntegral (ord c - 48)
{-# SPECIALISE decimal :: Parser Int #-}
{-# SPECIALISE decimal :: Parser Int8 #-}
{-# SPECIALISE decimal :: Parser Int16 #-}
{-# SPECIALISE decimal :: Parser Int32 #-}
{-# SPECIALISE decimal :: Parser Int64 #-}
{-# SPECIALISE decimal :: Parser Integer #-}
{-# SPECIALISE decimal :: Parser Word #-}
{-# SPECIALISE decimal :: Parser Word8 #-}
{-# SPECIALISE decimal :: Parser Word16 #-}
{-# SPECIALISE decimal :: Parser Word32 #-}
{-# SPECIALISE decimal :: Parser Word64 #-}
isDecimal :: Char -> Bool
isDecimal c = c >= '0' && c <= '9'
{-# INLINE isDecimal #-}
-- | Parse a number with an optional leading @\'+\'@ or @\'-\'@ sign
-- character.
signed :: Num a => Parser a -> Parser a
{-# SPECIALISE signed :: Parser Int -> Parser Int #-}
{-# SPECIALISE signed :: Parser Int8 -> Parser Int8 #-}
{-# SPECIALISE signed :: Parser Int16 -> Parser Int16 #-}
{-# SPECIALISE signed :: Parser Int32 -> Parser Int32 #-}
{-# SPECIALISE signed :: Parser Int64 -> Parser Int64 #-}
{-# SPECIALISE signed :: Parser Integer -> Parser Integer #-}
signed p = (negate <$> (I.char '-' *> p))
<|> (I.char '+' *> p)
<|> p
-- | Parse a rational number.
--
-- The syntax accepted by this parser is the same as for 'double'.
--
-- /Note/: this parser is not safe for use with inputs from untrusted
-- sources. An input with a suitably large exponent such as
-- @"1e1000000000"@ will cause a huge 'Integer' to be allocated,
-- resulting in what is effectively a denial-of-service attack.
--
-- In most cases, it is better to use 'double' or 'scientific'
-- instead.
rational :: Fractional a => Parser a
{-# SPECIALIZE rational :: Parser Double #-}
{-# SPECIALIZE rational :: Parser Float #-}
{-# SPECIALIZE rational :: Parser Rational #-}
{-# SPECIALIZE rational :: Parser Scientific #-}
rational = scientifically realToFrac
-- | Parse a rational number.
--
-- This parser accepts an optional leading sign character, followed by
-- at least one decimal digit. The syntax similar to that accepted by
-- the 'read' function, with the exception that a trailing @\'.\'@ or
-- @\'e\'@ /not/ followed by a number is not consumed.
--
-- Examples with behaviour identical to 'read', if you feed an empty
-- continuation to the first result:
--
-- >rational "3" == Done 3.0 ""
-- >rational "3.1" == Done 3.1 ""
-- >rational "3e4" == Done 30000.0 ""
-- >rational "3.1e4" == Done 31000.0, ""
--
-- Examples with behaviour identical to 'read':
--
-- >rational ".3" == Fail "input does not start with a digit"
-- >rational "e3" == Fail "input does not start with a digit"
--
-- Examples of differences from 'read':
--
-- >rational "3.foo" == Done 3.0 ".foo"
-- >rational "3e" == Done 3.0 "e"
--
-- This function does not accept string representations of \"NaN\" or
-- \"Infinity\".
double :: Parser Double
double = scientifically Sci.toRealFloat
-- | Parse a number, attempting to preserve both speed and precision.
--
-- The syntax accepted by this parser is the same as for 'double'.
--
-- This function does not accept string representations of \"NaN\" or
-- \"Infinity\".
number :: Parser Number
number = scientifically $ \s ->
let e = Sci.base10Exponent s
c = Sci.coefficient s
in if e >= 0
then I (c * 10 ^ e)
else D (Sci.toRealFloat s)
{-# DEPRECATED number "Use 'scientific' instead." #-}
-- | Parse a scientific number.
--
-- The syntax accepted by this parser is the same as for 'double'.
scientific :: Parser Scientific
scientific = scientifically id
-- A strict pair
data SP = SP !Integer {-# UNPACK #-}!Int
{-# INLINE scientifically #-}
scientifically :: (Scientific -> a) -> Parser a
scientifically h = do
!positive <- ((== '+') <$> I.satisfy (\c -> c == '-' || c == '+')) <|>
pure True
n <- decimal
let f fracDigits = SP (T.foldl' step n fracDigits)
(negate $ T.length fracDigits)
step a c = a * 10 + fromIntegral (ord c - 48)
SP c e <- (I.satisfy (=='.') *> (f <$> I.takeWhile isDigit)) <|>
pure (SP n 0)
let !signedCoeff | positive = c
| otherwise = -c
(I.satisfy (\w -> w == 'e' || w == 'E') *>
fmap (h . Sci.scientific signedCoeff . (e +)) (signed decimal)) <|>
return (h $ Sci.scientific signedCoeff e)
-- | Parse a single digit, as recognised by 'isDigit'.
digit :: Parser Char
digit = I.satisfy isDigit <?> "digit"
{-# INLINE digit #-}
-- | Parse a letter, as recognised by 'isAlpha'.
letter :: Parser Char
letter = I.satisfy isAlpha <?> "letter"
{-# INLINE letter #-}
-- | Parse a space character, as recognised by 'isSpace'.
space :: Parser Char
space = I.satisfy isSpace <?> "space"
{-# INLINE space #-}
-- | Skip over white space.
skipSpace :: Parser ()
skipSpace = I.skipWhile isSpace
{-# INLINE skipSpace #-}
-- $specalt
--
-- If you enable the @OverloadedStrings@ language extension, you can
-- use the '*>' and '<*' combinators to simplify the common task of
-- matching a statically known string, then immediately parsing
-- something else.
--
-- Instead of writing something like this:
--
-- @
--'I.string' \"foo\" '*>' wibble
-- @
--
-- Using @OverloadedStrings@, you can omit the explicit use of
-- 'I.string', and write a more compact version:
--
-- @
-- \"foo\" '*>' wibble
-- @
--
-- (Note: the '.*>' and '<*.' combinators that were originally
-- provided for this purpose are obsolete and unnecessary, and will be
-- removed in the next major version.)
-- | /Obsolete/. A type-specialized version of '*>' for 'Text'. Use
-- '*>' instead.
(.*>) :: Text -> Parser a -> Parser a
s .*> f = I.string s *> f
{-# DEPRECATED (.*>) "This is no longer necessary, and will be removed. Use '*>' instead." #-}
-- | /Obsolete/. A type-specialized version of '<*' for 'Text'. Use
-- '*>' instead.
(<*.) :: Parser a -> Text -> Parser a
f <*. s = f <* I.string s
{-# DEPRECATED (<*.) "This is no longer necessary, and will be removed. Use '<*' instead." #-}
| phischu/fragnix | tests/packages/scotty/Data.Attoparsec.Text.hs | bsd-3-clause | 16,149 | 0 | 16 | 3,639 | 2,192 | 1,302 | 890 | 220 | 2 |
module Turing.Laufzeit.Type where
-- $Id$
import Turing.Type (TM)
import Informed
import ToDoc
import Reader
data Laufzeit =
Laufzeit { fun :: Int -> Int -- laufzeit-funktion (kein Read)
, fun_info :: Doc -- funktions-name/-erklärung
, args :: [ Int ] -- argumente zum testen
}
instance Informed Laufzeit where
info = fun_info
instance ToDoc Laufzeit where
toDoc = info
instance Show Laufzeit where
show = render . toDoc
instance Reader Laufzeit where
reader = error "Laufzeit.Type.reader"
instance Read Laufzeit where
readsPrec p = error "Laufzeit.Type.readsPrec" | florianpilz/autotool | src/Turing/Laufzeit/Type.hs | gpl-2.0 | 642 | 2 | 9 | 161 | 144 | 83 | 61 | 19 | 0 |
{-# LANGUAGE PolyKinds #-}
module T16326_Fail7 where
import Data.Kind
-- Make sure that this doesn't parse as something goofy like
-- forall (forall :: Type -> Type) (k :: Type). forall k -> k -> Type
data Foo :: forall k -> k -> Type
| sdiehl/ghc | testsuite/tests/dependent/should_fail/T16326_Fail7.hs | bsd-3-clause | 238 | 0 | 6 | 48 | 27 | 18 | 9 | -1 | -1 |
{-# LANGUAGE CPP #-}
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Map.Strict
-- Copyright : (c) Daan Leijen 2002
-- (c) Andriy Palamarchuk 2008
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of ordered maps from keys to values
-- (dictionaries).
--
-- API of this module is strict in both the keys and the values.
-- If you need value-lazy maps, use "Data.Map.Lazy" instead.
-- The 'Map' type is shared between the lazy and strict modules,
-- meaning that the same 'Map' value can be passed to functions in
-- both modules (although that is rarely needed).
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- > import qualified Data.Map.Strict as Map
--
-- The implementation of 'Map' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'.
--
-- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of
-- this condition is not detected and if the size limit is exceeded, its
-- behaviour is undefined.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
--
-- Be aware that the 'Functor', 'Traversable' and 'Data' instances
-- are the same as for the "Data.Map.Lazy" module, so if they are used
-- on strict maps, the resulting maps will be lazy.
-----------------------------------------------------------------------------
-- See the notes at the beginning of Data.Map.Base.
module Data.Map.Strict
(
-- * Strictness properties
-- $strictness
-- * Map type
#if !defined(TESTING)
Map -- instance Eq,Show,Read
#else
Map(..) -- instance Eq,Show,Read
#endif
-- * Operators
, (!), (\\)
-- * Query
, null
, size
, member
, notMember
, lookup
, findWithDefault
, lookupLT
, lookupGT
, lookupLE
, lookupGE
-- * Construction
, empty
, singleton
-- ** Insertion
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
-- ** Delete\/Update
, delete
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
-- * Combine
-- ** Union
, union
, unionWith
, unionWithKey
, unions
, unionsWith
-- ** Difference
, difference
, differenceWith
, differenceWithKey
-- ** Intersection
, intersection
, intersectionWith
, intersectionWithKey
-- ** Universal combining function
, mergeWithKey
-- * Traversal
-- ** Map
, map
, mapWithKey
, traverseWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeys
, mapKeysWith
, mapKeysMonotonic
-- * Folds
, foldr
, foldl
, foldrWithKey
, foldlWithKey
, foldMapWithKey
-- ** Strict folds
, foldr'
, foldl'
, foldrWithKey'
, foldlWithKey'
-- * Conversion
, elems
, keys
, assocs
, keysSet
, fromSet
-- ** Lists
, toList
, fromList
, fromListWith
, fromListWithKey
-- ** Ordered lists
, toAscList
, toDescList
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
-- * Filter
, filter
, filterWithKey
, partition
, partitionWithKey
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, split
, splitLookup
, splitRoot
-- * Submap
, isSubmapOf, isSubmapOfBy
, isProperSubmapOf, isProperSubmapOfBy
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, updateAt
, deleteAt
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
, minView
, maxView
, minViewWithKey
, maxViewWithKey
-- * Debugging
, showTree
, showTreeWith
, valid
#if defined(TESTING)
-- * Internals
, bin
, balanced
, link
, merge
#endif
) where
import Prelude hiding (lookup,map,filter,foldr,foldl,null)
import Data.Map.Base hiding
( findWithDefault
, singleton
, insert
, insertWith
, insertWithKey
, insertLookupWithKey
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
, unionWith
, unionWithKey
, unionsWith
, differenceWith
, differenceWithKey
, intersectionWith
, intersectionWithKey
, mergeWithKey
, map
, mapWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
, mapKeysWith
, fromSet
, fromList
, fromListWith
, fromListWithKey
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey
, updateAt
, updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
)
import qualified Data.Set.Base as Set
import Data.Utils.StrictFold
import Data.Utils.StrictPair
import Data.Bits (shiftL, shiftR)
#if __GLASGOW_HASKELL__ >= 709
import Data.Coerce
#endif
-- $strictness
--
-- This module satisfies the following strictness properties:
--
-- 1. Key arguments are evaluated to WHNF;
--
-- 2. Keys and values are evaluated to WHNF before they are stored in
-- the map.
--
-- Here's an example illustrating the first property:
--
-- > delete undefined m == undefined
--
-- Here are some examples that illustrate the second property:
--
-- > map (\ v -> undefined) m == undefined -- m is not empty
-- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
-- the value at key @k@ or returns default value @def@
-- when the key is not in the map.
--
-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
-- See Map.Base.Note: Local 'go' functions and capturing
findWithDefault :: Ord k => a -> k -> Map k a -> a
findWithDefault def k = k `seq` go
where
go Tip = def
go (Bin _ kx x l r) = case compare k kx of
LT -> go l
GT -> go r
EQ -> x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findWithDefault #-}
#else
{-# INLINE findWithDefault #-}
#endif
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. A map with a single element.
--
-- > singleton 1 'a' == fromList [(1, 'a')]
-- > size (singleton 1 'a') == 1
singleton :: k -> a -> Map k a
singleton k x = x `seq` Bin 1 k x Tip Tip
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insertion
--------------------------------------------------------------------}
-- | /O(log n)/. Insert a new key and value in the map.
-- If the key is already present in the map, the associated value is
-- replaced with the supplied value. 'insert' is equivalent to
-- @'insertWith' 'const'@.
--
-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
-- > insert 5 'x' empty == singleton 5 'x'
-- See Map.Base.Note: Type of local 'go' function
insert :: Ord k => k -> a -> Map k a -> Map k a
insert = go
where
go :: Ord k => k -> a -> Map k a -> Map k a
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go kx x Tip = singleton kx x
go kx x (Bin sz ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go kx x l) r
GT -> balanceR ky y l (go kx x r)
EQ -> Bin sz kx x l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insert #-}
#else
{-# INLINE insert #-}
#endif
-- | /O(log n)/. Insert with a function, combining new value and old value.
-- @'insertWith' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key, f new_value old_value)@.
--
-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith f = insertWithKey (\_ x' y' -> f x' y')
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWith #-}
#else
{-# INLINE insertWith #-}
#endif
-- | /O(log n)/. Insert with a function, combining key, new value and old value.
-- @'insertWithKey' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key,f key new_value old_value)@.
-- Note that the key passed to f is the same key passed to 'insertWithKey'.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
-- See Map.Base.Note: Type of local 'go' function
insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWithKey = go
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
STRICT_2_OF_4(go)
go _ kx x Tip = singleton kx x
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> balanceL ky y (go f kx x l) r
GT -> balanceR ky y l (go f kx x r)
EQ -> let x' = f kx x y
in x' `seq` Bin sy kx x' l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertWithKey #-}
#else
{-# INLINE insertWithKey #-}
#endif
-- | /O(log n)/. Combines insert operation with old value retrieval.
-- The expression (@'insertLookupWithKey' f k x map@)
-- is a pair where the first element is equal to (@'lookup' k map@)
-- and the second element equal to (@'insertWithKey' f k x map@).
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
-- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
--
-- This is how to define @insertLookup@ using @insertLookupWithKey@:
--
-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
-- See Map.Base.Note: Type of local 'go' function
insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
-> (Maybe a, Map k a)
insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0
where
go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a)
STRICT_2_OF_4(go)
go _ kx x Tip = Nothing :*: singleton kx x
go f kx x (Bin sy ky y l r) =
case compare kx ky of
LT -> let (found :*: l') = go f kx x l
in found :*: balanceL ky y l' r
GT -> let (found :*: r') = go f kx x r
in found :*: balanceR ky y l r'
EQ -> let x' = f kx x y
in x' `seq` (Just y :*: Bin sy kx x' l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertLookupWithKey #-}
#else
{-# INLINE insertLookupWithKey #-}
#endif
{--------------------------------------------------------------------
Deletion
--------------------------------------------------------------------}
-- | /O(log n)/. Update a value at a specific key with the result of the provided function.
-- When the key is not
-- a member of the map, the original map is returned.
--
-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjust ("new " ++) 7 empty == empty
adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
adjust f = adjustWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjust #-}
#else
{-# INLINE adjust #-}
#endif
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > let f key x = (show key) ++ ":new " ++ x
-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjustWithKey f 7 empty == empty
adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE adjustWithKey #-}
#else
{-# INLINE adjustWithKey #-}
#endif
-- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
update f = updateWithKey (\_ x -> f x)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE update #-}
#else
{-# INLINE update #-}
#endif
-- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
-- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
-- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
-- to the new value @y@.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- See Map.Base.Note: Type of local 'go' function
updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
updateWithKey = go
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go _ _ Tip = Tip
go f k(Bin sx kx x l r) =
case compare k kx of
LT -> balanceR kx x (go f k l) r
GT -> balanceL kx x l (go f k r)
EQ -> case f kx x of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateWithKey #-}
#else
{-# INLINE updateWithKey #-}
#endif
-- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
-- The function returns changed value, if it is updated.
-- Returns the original key value if the map entry is deleted.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
-- See Map.Base.Note: Type of local 'go' function
updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0
where
go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
STRICT_2_OF_3(go)
go _ _ Tip = (Nothing :*: Tip)
go f k (Bin sx kx x l r) =
case compare k kx of
LT -> let (found :*: l') = go f k l
in found :*: balanceR kx x l' r
GT -> let (found :*: r') = go f k r
in found :*: balanceL kx x l r'
EQ -> case f kx x of
Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
Nothing -> (Just x :*: glue l r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE updateLookupWithKey #-}
#else
{-# INLINE updateLookupWithKey #-}
#endif
-- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
-- 'alter' can be used to insert, delete, or update a value in a 'Map'.
-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
--
-- > let f _ = Nothing
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- >
-- > let f _ = Just "c"
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
-- See Map.Base.Note: Type of local 'go' function
alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
alter = go
where
go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
STRICT_2_OF_3(go)
go f k Tip = case f Nothing of
Nothing -> Tip
Just x -> singleton k x
go f k (Bin sx kx x l r) = case compare k kx of
LT -> balance kx x (go f k l) r
GT -> balance kx x l (go f k r)
EQ -> case f (Just x) of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE alter #-}
#else
{-# INLINE alter #-}
#endif
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Update the element at /index/. Calls 'error' when an
-- invalid index is used.
--
-- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
-- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
-- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
-- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
-- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
updateAt f i t = i `seq`
case t of
Tip -> error "Map.updateAt: index out of range"
Bin sx kx x l r -> case compare i sizeL of
LT -> balanceR kx x (updateAt f i l) r
GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
EQ -> case f kx x of
Just x' -> x' `seq` Bin sx kx x' l r
Nothing -> glue l r
where
sizeL = size l
{--------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
-- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMin :: (a -> Maybe a) -> Map k a -> Map k a
updateMin f m
= updateMinWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
-- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMax :: (a -> Maybe a) -> Map k a -> Map k a
updateMax f m
= updateMaxWithKey (\_ x -> f x) m
-- | /O(log n)/. Update the value at the minimal key.
--
-- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
-- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMinWithKey _ Tip = Tip
updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
Nothing -> r
Just x' -> x' `seq` Bin sx kx x' Tip r
updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
-- | /O(log n)/. Update the value at the maximal key.
--
-- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
-- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
updateMaxWithKey _ Tip = Tip
updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
Nothing -> l
Just x' -> x' `seq` Bin sx kx x' l Tip
updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of maps, with a combining operation:
-- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
--
-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
unionsWith f ts
= foldlStrict (unionWith f) empty ts
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionsWith #-}
#endif
{--------------------------------------------------------------------
Union with a combining function
--------------------------------------------------------------------}
-- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith f m1 m2
= unionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWith #-}
#endif
-- | /O(n+m)/.
-- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
--
-- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unionWithKey #-}
#endif
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference with a combining function.
-- When two equal keys are
-- encountered, the combining function is applied to the values of these keys.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
-- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
-- > == singleton 3 "b:B"
differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWith f m1 m2
= differenceWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWith #-}
#endif
-- | /O(n+m)/. Difference with a combining function. When two equal keys are
-- encountered, the combining function is applied to the key and both values.
-- If it returns 'Nothing', the element is discarded (proper set difference). If
-- it returns (@'Just' y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
-- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
-- > == singleton 3 "3:b|B"
differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE differenceWithKey #-}
#endif
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWith f m1 m2
= intersectionWithKey (\_ x y -> f x y) m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWith #-}
#endif
-- | /O(n+m)/. Intersection with a combining function. The implementation uses
-- an efficient /hedge/ algorithm comparable with /hedge-union/.
--
-- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
-- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersectionWithKey #-}
#endif
{--------------------------------------------------------------------
MergeWithKey
--------------------------------------------------------------------}
-- | /O(n+m)/. A high-performance universal combining function. This function
-- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
-- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
-- used to define other custom combine functions.
--
-- Please make sure you know what is going on when using 'mergeWithKey',
-- otherwise you can be surprised by unexpected code growth or even
-- corruption of the data structure.
--
-- When 'mergeWithKey' is given three arguments, it is inlined to the call
-- site. You should therefore use 'mergeWithKey' only to define your custom
-- combining functions. For example, you could define 'unionWithKey',
-- 'differenceWithKey' and 'intersectionWithKey' as
--
-- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
-- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
-- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
--
-- When calling @'mergeWithKey' combine only1 only2@, a function combining two
-- 'IntMap's is created, such that
--
-- * if a key is present in both maps, it is passed with both corresponding
-- values to the @combine@ function. Depending on the result, the key is either
-- present in the result with specified value, or is left out;
--
-- * a nonempty subtree present only in the first map is passed to @only1@ and
-- the output is added to the result;
--
-- * a nonempty subtree present only in the second map is passed to @only2@ and
-- the output is added to the result.
--
-- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
-- The values can be modified arbitrarily. Most common variants of @only1@ and
-- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
-- @'filterWithKey' f@ could be used for any @f@.
mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
-> Map k a -> Map k b -> Map k c
mergeWithKey f g1 g2 = go
where
go Tip t2 = g2 t2
go t1 Tip = g1 t1
go t1 t2 = hedgeMerge NothingS NothingS t1 t2
hedgeMerge _ _ t1 Tip = g1 t1
hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
(found, trim_t2) = trimLookupLo kx bhi t2
r' = hedgeMerge bmi bhi r trim_t2
in case found of
Nothing -> case g1 (singleton kx x) of
Tip -> merge l' r'
(Bin _ _ x' Tip Tip) -> link kx x' l' r'
_ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
Just x2 -> case f kx x x2 of
Nothing -> merge l' r'
Just x' -> x' `seq` link kx x' l' r'
where bmi = JustS kx
{-# INLINE mergeWithKey #-}
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Map values and collect the 'Just' results.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
mapMaybe f = mapMaybeWithKey (\_ x -> f x)
-- | /O(n)/. Map keys\/values and collect the 'Just' results.
--
-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
-- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
mapMaybeWithKey _ Tip = Tip
mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
--
-- > let f a = if a < "c" then Left a else Right a
-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
-- >
-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEither f m
= mapEitherWithKey (\_ x -> f x) m
-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
--
-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
-- >
-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEitherWithKey f0 t0 = toPair $ go f0 t0
where
go _ Tip = (Tip :*: Tip)
go f (Bin _ kx x l r) = case f kx x of
Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
where
(l1 :*: l2) = go f l
(r1 :*: r2) = go f r
{--------------------------------------------------------------------
Mapping
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all values in the map.
--
-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
map :: (a -> b) -> Map k a -> Map k b
map _ Tip = Tip
map f (Bin sx kx x l r) = let x' = f x in x' `seq` Bin sx kx x' (map f l) (map f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] map #-}
{-# RULES
"map/map" forall f g xs . map f (map g xs) = map (f . g) xs
#-}
#endif
#if __GLASGOW_HASKELL__ >= 709
-- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
{-# RULES
"mapSeq/coerce" map coerce = coerce
#-}
#endif
-- | /O(n)/. Map a function over all values in the map.
--
-- > let f key x = (show key) ++ ":" ++ x
-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
mapWithKey _ Tip = Tip
mapWithKey f (Bin sx kx x l r) =
let x' = f kx x
in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] mapWithKey #-}
{-# RULES
"mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
mapWithKey (\k a -> f k (g k a)) xs
"mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
mapWithKey (\k a -> f k (g a)) xs
"map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
mapWithKey (\k a -> f (g k a)) xs
#-}
#endif
-- | /O(n)/. The function 'mapAccum' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a b = (a ++ b, b ++ "X")
-- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccum f a m
= mapAccumWithKey (\a' _ x' -> f a' x') a m
-- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
-- argument through the map in ascending order of keys.
--
-- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
-- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumWithKey f a t
= mapAccumL f a t
-- | /O(n)/. The function 'mapAccumL' threads an accumulating
-- argument through the map in ascending order of keys.
mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumL _ a Tip = (a,Tip)
mapAccumL f a (Bin sx kx x l r) =
let (a1,l') = mapAccumL f a l
(a2,x') = f a1 kx x
(a3,r') = mapAccumL f a2 r
in x' `seq` (a3,Bin sx kx x' l' r')
-- | /O(n)/. The function 'mapAccumR' threads an accumulating
-- argument through the map in descending order of keys.
mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
mapAccumRWithKey _ a Tip = (a,Tip)
mapAccumRWithKey f a (Bin sx kx x l r) =
let (a1,r') = mapAccumRWithKey f a r
(a2,x') = f a1 kx x
(a3,l') = mapAccumRWithKey f a2 l
in x' `seq` (a3,Bin sx kx x' l' r')
-- | /O(n*log n)/.
-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the associated values will be
-- combined using @c@.
--
-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE mapKeysWith #-}
#endif
{--------------------------------------------------------------------
Conversions
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from a set of keys and a function which for each key
-- computes its value.
--
-- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
-- > fromSet undefined Data.Set.empty == empty
fromSet :: (k -> a) -> Set.Set k -> Map k a
fromSet _ Set.Tip = Tip
fromSet f (Set.Bin sz x l r) = case f x of v -> v `seq` Bin sz x v (fromSet f l) (fromSet f r)
{--------------------------------------------------------------------
Lists
use [foldlStrict] to reduce demand on the control-stack
--------------------------------------------------------------------}
-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
-- If the list contains more than one value for the same key, the last value
-- for the key is retained.
--
-- If the keys of the list are ordered, linear-time implementation is used,
-- with the performance equal to 'fromDistinctAscList'.
--
-- > fromList [] == empty
-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
-- For some reason, when 'singleton' is used in fromList or in
-- create, it is not inlined, so we inline it manually.
fromList :: Ord k => [(k,a)] -> Map k a
fromList [] = Tip
fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
| otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
not_ordered _ [] = False
not_ordered kx ((ky,_) : _) = kx >= ky
{-# INLINE not_ordered #-}
fromList' t0 xs = foldlStrict ins t0 xs
where ins t (k,x) = insert k x t
STRICT_1_OF_3(go)
go _ t [] = t
go _ t [(kx, x)] = x `seq` insertMax kx x t
go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
| otherwise = case create s xss of
(r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
(r, _, ys) -> x `seq` fromList' (link kx x l r) ys
-- The create is returning a triple (tree, xs, ys). Both xs and ys
-- represent not yet processed elements and only one of them can be nonempty.
-- If ys is nonempty, the keys in ys are not ordered with respect to tree
-- and must be inserted using fromList'. Otherwise the keys have been
-- ordered so far.
STRICT_1_OF_2(create)
create _ [] = (Tip, [], [])
create s xs@(xp : xss)
| s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
| otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
| otherwise = case create (s `shiftR` 1) xs of
res@(_, [], _) -> res
(l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
(l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
| otherwise -> case create (s `shiftR` 1) yss of
(r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromList #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
--
-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
-- > fromListWith (++) [] == empty
fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
fromListWith f xs
= fromListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWith #-}
#endif
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
--
-- > let f k a1 a2 = (show k) ++ a1 ++ a2
-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
-- > fromListWithKey f [] == empty
fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromListWithKey f xs
= foldlStrict ins empty xs
where
ins t (k,x) = insertWithKey f k x t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromListWithKey #-}
#endif
{--------------------------------------------------------------------
Building trees from ascending/descending lists can be done in linear time.
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
fromAscListWith f xs == fromListWith f xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
-- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscList :: Eq k => [(k,a)] -> Map k a
fromAscList xs
= fromAscListWithKey (\_ x _ -> x) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscList #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
-- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWith f xs
= fromAscListWithKey (\_ x y -> f x y) xs
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWith #-}
#endif
-- | /O(n)/. Build a map from an ascending list in linear time with a
-- combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
-- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
-- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWithKey f xs
= fromDistinctAscList (combineEq f xs)
where
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
combineEq _ xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z@(kz,zz) (x@(kx,xx):xs')
| kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
| otherwise = z:combineEq' x xs'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscListWithKey #-}
#endif
-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
-- /The precondition is not checked./
--
-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
-- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
-- For some reason, when 'singleton' is used in fromDistinctAscList or in
-- create, it is not inlined, so we inline it manually.
fromDistinctAscList :: [(k,a)] -> Map k a
fromDistinctAscList [] = Tip
fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
where
STRICT_1_OF_3(go)
go _ t [] = t
go s l ((kx, x) : xs) = case create s xs of
(r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
STRICT_1_OF_2(create)
create _ [] = (Tip, [])
create s xs@(x' : xs')
| s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
| otherwise = case create (s `shiftR` 1) xs of
res@(_, []) -> res
(l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
(r, zs) -> y `seq` (link ky y l r, zs)
| shockkolate/containers | Data/Map/Strict.hs | bsd-3-clause | 45,518 | 0 | 17 | 11,392 | 8,305 | 4,539 | 3,766 | -1 | -1 |
-- Stacks: using restricted type synonyms
module Stack where
type Stack a = [a] in emptyStack, push, pop, topOf, isEmpty
emptyStack :: Stack a
emptyStack = []
push :: a -> Stack a -> Stack a
push = (:)
pop :: Stack a -> Stack a
pop [] = error "pop: empty stack"
pop (_:xs) = xs
topOf :: Stack a -> a
topOf [] = error "topOf: empty stack"
topOf (x:_) = x
isEmpty :: Stack a -> Bool
isEmpty = null
instance Eq a => Eq (Stack a) where
s1 == s2 | isEmpty s1 = isEmpty s2
| isEmpty s2 = isEmpty s1
| otherwise = topOf s1 == topOf s2 && pop s1 == pop s2
-- A slightly different presentation:
type Stack' a = [a] in
emptyStack' :: Stack' a,
push' :: a -> Stack' a -> Stack' a,
pop' :: Stack' a -> Stack' a,
topOf' :: Stack' a -> a,
isEmpty' :: Stack' a -> Bool
emptyStack' = []
push' = (:)
pop' [] = error "pop': empty stack"
pop' (_:xs) = xs
topOf' [] = error "topOf': empty stack"
topOf' (x:_) = x
isEmpty' = null
instance Eq a => Eq (Stack' a) where
s1 == s2 | isEmpty' s1 = isEmpty' s2
| isEmpty' s2 = isEmpty' s1
| otherwise = topOf' s1 == topOf' s2 && pop' s1 == pop' s2
| FranklinChen/Hugs | demos/Stack.hs | bsd-3-clause | 1,249 | 8 | 11 | 410 | 475 | 241 | 234 | -1 | -1 |
{-# LANGUAGE LambdaCase, MultiWayIf #-}
module Unification
( Equality
, Bindings
, Unifiable
, unifyLiberally
, applyBinding
, applyBinding'
, applyBindingM
, UnificationResult(..)
) where
import qualified Data.Map as M
import Control.Monad
import Control.Applicative
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Writer
--import Debug.Trace
import Data.List
import Propositions
import Unbound.LocallyNameless
import Unbound.LocallyNameless.Fresh
type Equality = (Term, Term)
-- Invariant: If (v1, Var v2), then v1 <= v2
type Bindings = M.Map Var Term
type Unifiable = [Var]
emptyBinding :: Bindings
emptyBinding = M.empty
data UnificationResult = Solved | Failed | Dunno
deriving Show
unifyLiberally :: Unifiable -> [(a,Equality)] -> (Bindings, [(a,UnificationResult)])
unifyLiberally uvs eqns = flip contFreshM highest $
iter (uvs, emptyBinding) $ map (\(n,e) -> (n,Dunno,e)) eqns
where
highest = firstFree (uvs, map snd eqns)
-- Repeatedly go through the list of equalities until we can solve no more
iter :: Fresh m => (Unifiable, Bindings) -> [(a, UnificationResult, Equality)] -> m (Bindings, [(a, UnificationResult)])
iter (uvs, bind) eqns = do
((uvs', bind'), eqns') <- runWriterT $ go (uvs,bind) eqns
if M.size bind' > M.size bind
then iter (uvs', bind') eqns'
else return (bind', map (\(n,r,_) -> (n,r)) eqns')
-- we learned something, so retry
go :: Fresh m => (Unifiable, Bindings) -> [(a,UnificationResult, Equality)] -> WriterT [(a,UnificationResult, Equality)] m (Unifiable, Bindings)
go uvs_bind [] = return uvs_bind
go uvs_bind ((n,Dunno,x):xs) = do
maybe_uvs_bind' <- lift $ runMaybeT (uncurry unif uvs_bind x)
case maybe_uvs_bind' of
Just (uvs',bind') -> do
solved <- x `solvedBy` bind'
if solved
then tell [(n,Solved, x)] >> go (uvs',bind') xs
-- Discard the results of this dunno,
-- potentially less complete, but makes the output easier to understand
else tell [(n,Dunno, x)] >> go uvs_bind xs
Nothing ->
tell [(n, Failed, x)] >> go uvs_bind xs
-- Do not look at solved or failed equations again
go uvs_bind ((n,r,x):xs) = tell [(n,r,x)] >> go uvs_bind xs
-- Code taken from http://www21.in.tum.de/~nipkow/pubs/lics93.html
{-
fun unif (S,(s,t)) = case (devar S s,devar S t) of
(x\s,y\t) => unif (S,(s,if x=y then t else subst x y t))
| (x\s,t) => unif (S,(s,t$(B x)))
| (s,x\t) => unif (S,(s$(B x),t))
| (s,t) => cases S (s,t)
-}
unif :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> (Term, Term) -> m ([Var], Bindings)
unif uvs binds (s,t) = do
s' <- devar binds s
t' <- devar binds t
case (s',t') of
(Lam b1, Lam b2)
-> lunbind2' b1 b2 $ \(Just (_,s,_,t)) -> unif uvs binds (s,t)
(s,t) -> cases uvs binds (s,t)
{-
and cases S (s,t) = case (strip s,strip t) of
((V F,ym),(V G,zn)) => flexflex(F,ym,G,zn,S)
| ((V F,ym),_) => flexrigid(F,ym,t,S)
| (_,(V F,ym)) => flexrigid(F,ym,s,S)
| ((a,sm),(b,tn)) => rigidrigid(a,sm,b,tn,S)
-}
cases :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> (Term, Term) -> m ([Var], Bindings)
cases uvs binds (s,t) = do
case (strip s, strip t) of
((V f, ym), (V g, zn))
| f `elem` uvs && g `elem` uvs -> flexflex uvs binds f ym g zn
((V f, ym), _)
| f `elem` uvs -> flexrigid uvs binds f ym t
(_, (V g, zn))
| g `elem` uvs -> flexrigid uvs binds g zn s
((a, sm), (b, tn))
-> rigidrigid uvs binds a sm b tn
{-
fun flexflex1(F,ym,zn,S) =
if ym=zn then S else (F, hnf(ym, newV(), eqs ym zn)) :: S;
fun flexflex2(F,ym,G,zn,S) =
if ym subset zn then (G, hnf(zn,V F,ym)) :: S else
if zn subset ym then (F, hnf(ym,V G,zn)) :: S
else let val xk = ym /\ zn and H = newV()
in (F, hnf(ym,H,xk)) :: (G, hnf(zn,H,xk)) :: S end;
fun flexflex(F,ym,G,zn,S) = if F=G then flexflex1(F,ym,zn,S)
else flexflex2(F,ym,G,zn,S);
-}
flexflex :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Var -> [Term] -> Var -> [Term] -> m ([Var], Bindings)
flexflex uvs binds f ym g zn
| f == g && ym == zn = return (uvs, binds)
| f == g
, Just ym' <- allBoundVar uvs ym
= do
newName <- fresh (string2Name "uni")
let rhs = absTerm ym' (App (V newName) (intersect ym zn))
binds' = M.insert f rhs binds
return (newName:uvs, binds')
| f == g = return (uvs, binds) -- non-pattern: Just ignore
| Just ym' <- allBoundVar uvs ym
, Just zn' <- allBoundVar uvs zn
= if | all (`elem` zn') ym' -> do
let rhs = absTerm zn' (App (V f) ym)
binds' = M.insert g rhs binds
return (uvs, binds')
| all (`elem` ym') zn' -> do
let rhs = absTerm ym' (App (V g) zn)
binds' = M.insert f rhs binds
return (uvs, binds')
| otherwise -> do
newName <- fresh (string2Name "uni")
let rhs1 = absTerm ym' (App (V newName) (intersect ym zn))
rhs2 = absTerm zn' (App (V newName) (intersect ym zn))
binds' = M.insert f rhs1 $ M.insert g rhs2 binds
return (newName:uvs, binds')
| otherwise = return (uvs, binds) -- non-pattern: Just ignore
{-
fun occ F S (V G) = (F=G) orelse
(case assoc G S of Some(s) => occ F S s | None => false)
| occ F S (s$t) = occ F S s orelse occ F S t
| occ F S (_\s) = occ F S s
| occ F S (_) = false;
-}
occ :: Alpha b => Bindings -> Name Term -> b -> Bool
occ binds v t = v `elem` vars || any (maybe False (occ binds v) . (`M.lookup` binds)) vars
where vars = fv t::[Var]
{-
fun flexrigid(F,ym,t,S) = if occ F S t then raise Unif
else proj (map B1 ym) (((F,abs(ym,t))::S),t);
-}
flexrigid :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Var -> [Term] -> Term -> m ([Var], Bindings)
flexrigid uvs binds f ym t
| occ binds f t
= mzero
| Just vs <- allBoundVar uvs ym
= let binds' = M.insert f (absTerm vs t) binds
in proj vs uvs binds' t
| otherwise
= return (uvs, binds) -- not a pattern, ignoring here
{-
fun proj W (S,s) = case strip(devar S s) of
(x\t,_) => proj (x::W) (S,t)
| (C _,ss) => foldl (proj W) (S,ss)
| (B x,ss) => if x mem W then foldl (proj W) (S,ss) else raise Unif
| (V F,ss) => if (map B1 ss) subset W then S
else (F, hnf(ss, newV(), ss /\ (map B W))) :: S;
-}
proj :: (MonadPlus m, Fresh m) => [Var] -> [Var] -> Bindings -> Term -> m ([Var], Bindings)
proj w uvs binds s = do
s' <- devar binds s
case strip s' of
(Lam b, _)
-> lunbind' b $ \(x,t) -> proj (x:w) uvs binds t
(V v, ss) | v `elem` uvs
-> case allBoundVar uvs ss of
Just vs | all (`elem` w) vs -> return (uvs, binds)
Just vs -> do
newName <- fresh (string2Name "uni")
let rhs = absTerm vs (App (V newName) (ss ++ map V w))
let binds' = M.insert v rhs binds
return (newName:uvs, binds')
-- Found a non-pattern use of a free variable, so recurse into the arguments
-- (The correctness of this is a guess by Joachim)
Nothing -> recurse ss
| v `elem` w -> recurse ss
| otherwise -> mzero
(C _, ss) -> recurse ss
(App _ _, _) -> error "Unreachable"
where
recurse = foldM (uncurry (proj w)) (uvs, binds)
allBoundVar :: Unifiable -> [Term] -> Maybe [Var]
allBoundVar _ [] = return []
allBoundVar uvs (V x:xs) | x `notElem` uvs = (x:) <$> allBoundVar uvs xs
allBoundVar _ _ = Nothing
{-
and rigidrigid(a,ss,b,ts,S) = if a <> b then raise Unif
else foldl unif (S,zip ss ts);
-}
rigidrigid :: (MonadPlus m, Fresh m) => [Var] -> Bindings -> Term -> [Term] -> Term -> [Term] -> m ([Var], Bindings)
rigidrigid uvs binds a sm b tn
| a `aeq` b && length sm == length tn
= foldM (uncurry unif) (uvs, binds) (zip sm tn)
| otherwise
= mzero
{-
fun devar S t = case strip t of
(V F,ys) => (case assoc F S of
Some(t) => devar S (red t ys)
| None => t)
| _ => t;
-}
devar :: Fresh m => Bindings -> Term -> m Term
devar binds t = case strip t of
(V v,ys)
| Just t <- M.lookup v binds
-> redsTerm t ys >>= devar binds
_ -> return t
redsTerm :: Fresh m => Term -> [Term] -> m Term
redsTerm t [] = return t
redsTerm (Lam b) (x:xs) = lunbind' b $ \(v,body) -> redsTerm (subst v x body) xs
redsTerm t xs = return $ App t xs
strip :: Term -> (Term, [Term])
strip t = go t []
where go (App t args) args' = go t (args++args')
go t args' = (t, args')
solvedBy :: Fresh m => Equality -> Bindings -> m Bool
solvedBy (t1,t2) b = liftM2 aeq (applyBindingM b t1) (applyBindingM b t2)
-- | This is slow. If possible, use 'applyBinding'' or 'applyBindingM'
applyBinding :: Bindings -> Term -> Term
applyBinding bindings t = applyBinding' (firstFree (M.toList bindings,t)) bindings t
applyBinding' :: Integer -> Bindings -> Term -> Term
applyBinding' free bindings t = flip contFreshM free $ applyBindingM bindings t
applyBindingM :: Fresh m => Bindings -> Term -> m Term
applyBindingM bindings t = go [] t
where
go args (V v) | Just t <- M.lookup v bindings
= go args t
go [] (V v) = return $ V v
go args (V v) = App (V v) <$> mapM (go []) args
go [] (C v) = return $ C v
go args (C v) = App (C v) <$> mapM (go []) args
go args (App t args') = go (args' ++ args) t
go [] (Lam b) = lunbind' b $ \(v,body) -> Lam . bind v <$> go [] body
go (x:xs) (Lam b) = lunbind' b $ \(v,body) -> go xs (subst v x body)
-- This can be dropped once we only support GHC-7.10
infixl 4 <$>
(<$>) = liftM
lunbind' :: (Fresh m, Alpha p, Alpha t) => Bind p t -> ((p, t) -> m c) -> m c
lunbind' b c = unbind b >>= c
lunbind2' :: (Fresh m, Alpha p1, Alpha p2, Alpha t1, Alpha t2) => Bind p1 t1 -> Bind p2 t2 -> (Maybe (p1, t1, p2, t2) -> m r) -> m r
lunbind2' b1 b2 c = unbind2 b1 b2 >>= c
| psibi/incredible | logic/Unification.hs | mit | 10,729 | 5 | 24 | 3,422 | 3,643 | 1,920 | 1,723 | 176 | 8 |
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE PolyKinds, DataKinds, RankNTypes, TypeFamilies,
TypeApplications, TypeOperators, GADTs #-}
module SAKS_030 where
import Data.Kind
import Data.Type.Equality
type T1 :: forall k (a :: k). Bool
type T2 :: k -> Bool
type family T1 where
T1 @Bool @True = False
T1 @Bool @False = True
type family T2 a where
T2 True = False
T2 False = True
type SBool :: Bool -> Type
data SBool b where
STrue :: SBool True
SFalse :: SBool False
proof_t1_eq_t2 :: SBool b -> T1 @Bool @b :~: T2 b
proof_t1_eq_t2 STrue = Refl
proof_t1_eq_t2 SFalse = Refl
| sdiehl/ghc | testsuite/tests/saks/should_compile/saks030.hs | bsd-3-clause | 619 | 11 | 8 | 135 | 173 | 100 | 73 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ar-SA">
<title>دليل البدء</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>محتوى</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>الفهرس</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>بحث</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>المفضلة</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/gettingStarted/src/main/javahelp/org/zaproxy/zap/extension/gettingStarted/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 978 | 87 | 61 | 156 | 394 | 200 | 194 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ur-PK">
<title>Passive Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_ur_PK/helpset_ur_PK.hs | apache-2.0 | 979 | 78 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE RankNTypes, NamedWildCards #-}
-- See #11098
module NamedWildcardExplicitForall where
foo :: forall _a . _a -> _a -- _a is a type variable
foo = not
bar :: _a -> _a -- _a is a named wildcard
bar = not
baz :: forall _a . _a -> _b -> (_a, _b) -- _a is a variable, _b is a wildcard
baz x y = (not x, not y)
qux :: _a -> (forall _a . _a -> _a) -> _a -- the _a bound by forall is a tyvar
qux x f = let _ = f 7 in not x -- the other _a are wildcards
| sdiehl/ghc | testsuite/tests/partial-sigs/should_fail/NamedWildcardExplicitForall.hs | bsd-3-clause | 521 | 0 | 9 | 173 | 143 | 80 | 63 | 10 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Ros.Internal.Log where
import qualified Prelude as P
import Prelude ((.))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import Ros.Internal.Msg.HeaderSupport
import qualified Data.Word as Word
import qualified Ros.Internal.Header as Header
data Log = Log { header :: Header.Header
, level :: Word.Word8
, name :: P.String
, msg :: P.String
, file :: P.String
, function :: P.String
, line :: Word.Word32
, topics :: [P.String]
} deriving (P.Show, P.Eq, P.Ord, T.Typeable)
instance RosBinary Log where
put obj' = put (header obj') *> put (level obj') *> put (name obj') *> put (msg obj') *> put (file obj') *> put (function obj') *> put (line obj') *> putList (topics obj')
get = Log <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> getList
putMsg = putStampedMsg
instance HasHeader Log where
getSequence = Header.seq . header
getFrame = Header.frame_id . header
getStamp = Header.stamp . header
setSequence seq x' = x' { header = (header x') { Header.seq = seq } }
instance MsgInfo Log where
sourceMD5 _ = "acffd30cd6b6de30f120938c17c593fb"
msgTypeName _ = "rosgraph_msgs/Log"
dEBUG :: Word.Word8
dEBUG = 1
iNFO :: Word.Word8
iNFO = 2
wARN :: Word.Word8
wARN = 4
eRROR :: Word.Word8
eRROR = 8
fATAL :: Word.Word8
fATAL = 16
| bitemyapp/roshask | src/Ros/Internal/Log.hs | bsd-3-clause | 1,547 | 0 | 15 | 389 | 494 | 279 | 215 | 42 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Provide ability to upload tarballs to Hackage.
module Stack.Upload
( -- * Upload
nopUploader
, mkUploader
, Uploader
, upload
, uploadBytes
, UploadSettings
, defaultUploadSettings
, setUploadUrl
, setGetManager
, setCredsSource
, setSaveCreds
-- * Credentials
, HackageCreds
, loadCreds
, saveCreds
, FromFile
-- ** Credentials source
, HackageCredsSource
, fromAnywhere
, fromPrompt
, fromFile
, fromMemory
) where
import Control.Applicative
import Control.Exception (bracket)
import qualified Control.Exception as E
import Control.Monad (when, unless)
import Data.Aeson (FromJSON (..),
ToJSON (..),
eitherDecode', encode,
object, withObject,
(.:), (.=))
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy as L
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Typeable (Typeable)
import Network.HTTP.Client (BodyReader, Manager,
Response,
RequestBody(RequestBodyLBS),
applyBasicAuth, brRead,
checkStatus, newManager,
parseUrl,
requestHeaders,
responseBody,
responseStatus,
withResponse)
import Network.HTTP.Client.MultipartFormData (formDataBody, partFileRequestBody)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types (statusCode)
import Path (toFilePath)
import Prelude -- Fix redundant import warnings
import Stack.Types
import System.Directory (createDirectoryIfMissing,
removeFile)
import System.FilePath ((</>), takeFileName)
import System.IO (hFlush, hGetEcho, hSetEcho,
stdin, stdout)
-- | Username and password to log into Hackage.
--
-- Since 0.1.0.0
data HackageCreds = HackageCreds
{ hcUsername :: !Text
, hcPassword :: !Text
}
deriving Show
instance ToJSON HackageCreds where
toJSON (HackageCreds u p) = object
[ "username" .= u
, "password" .= p
]
instance FromJSON HackageCreds where
parseJSON = withObject "HackageCreds" $ \o -> HackageCreds
<$> o .: "username"
<*> o .: "password"
-- | A source for getting Hackage credentials.
--
-- Since 0.1.0.0
newtype HackageCredsSource = HackageCredsSource
{ getCreds :: IO (HackageCreds, FromFile)
}
-- | Whether the Hackage credentials were loaded from a file.
--
-- This information is useful since, typically, you only want to save the
-- credentials to a file if it wasn't already loaded from there.
--
-- Since 0.1.0.0
type FromFile = Bool
-- | Load Hackage credentials from the given source.
--
-- Since 0.1.0.0
loadCreds :: HackageCredsSource -> IO (HackageCreds, FromFile)
loadCreds = getCreds
-- | Save the given credentials to the credentials file.
--
-- Since 0.1.0.0
saveCreds :: Config -> HackageCreds -> IO ()
saveCreds config creds = do
fp <- credsFile config
L.writeFile fp $ encode creds
-- | Load the Hackage credentials from the prompt, asking the user to type them
-- in.
--
-- Since 0.1.0.0
fromPrompt :: HackageCredsSource
fromPrompt = HackageCredsSource $ do
putStr "Hackage username: "
hFlush stdout
username <- TIO.getLine
password <- promptPassword
return (HackageCreds
{ hcUsername = username
, hcPassword = password
}, False)
credsFile :: Config -> IO FilePath
credsFile config = do
let dir = toFilePath (configStackRoot config) </> "upload"
createDirectoryIfMissing True dir
return $ dir </> "credentials.json"
-- | Load the Hackage credentials from the JSON config file.
--
-- Since 0.1.0.0
fromFile :: Config -> HackageCredsSource
fromFile config = HackageCredsSource $ do
fp <- credsFile config
lbs <- L.readFile fp
case eitherDecode' lbs of
Left e -> E.throwIO $ Couldn'tParseJSON fp e
Right creds -> return (creds, True)
-- | Load the Hackage credentials from the given arguments.
--
-- Since 0.1.0.0
fromMemory :: Text -> Text -> HackageCredsSource
fromMemory u p = HackageCredsSource $ return (HackageCreds
{ hcUsername = u
, hcPassword = p
}, False)
data HackageCredsExceptions = Couldn'tParseJSON FilePath String
deriving (Show, Typeable)
instance E.Exception HackageCredsExceptions
-- | Try to load the credentials from the config file. If that fails, ask the
-- user to enter them.
--
-- Since 0.1.0.0
fromAnywhere :: Config -> HackageCredsSource
fromAnywhere config = HackageCredsSource $
getCreds (fromFile config) `E.catches`
[ E.Handler $ \(_ :: E.IOException) -> getCreds fromPrompt
, E.Handler $ \(_ :: HackageCredsExceptions) -> getCreds fromPrompt
]
-- | Lifted from cabal-install, Distribution.Client.Upload
promptPassword :: IO Text
promptPassword = do
putStr "Hackage password: "
hFlush stdout
-- save/restore the terminal echoing status
passwd <- bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do
hSetEcho stdin False -- no echoing for entering the password
fmap T.pack getLine
putStrLn ""
return passwd
nopUploader :: Config -> UploadSettings -> IO Uploader
nopUploader _ _ = return (Uploader nop)
where nop :: String -> L.ByteString -> IO ()
nop _ _ = return ()
-- | Turn the given settings into an @Uploader@.
--
-- Since 0.1.0.0
mkUploader :: Config -> UploadSettings -> IO Uploader
mkUploader config us = do
manager <- usGetManager us
(creds, fromFile') <- loadCreds $ usCredsSource us config
when (not fromFile' && usSaveCreds us) $ saveCreds config creds
req0 <- parseUrl $ usUploadUrl us
let req1 = req0
{ requestHeaders = [("Accept", "text/plain")]
, checkStatus = \_ _ _ -> Nothing
}
return Uploader
{ upload_ = \tarName bytes -> do
let formData = [partFileRequestBody "package" tarName (RequestBodyLBS bytes)]
req2 <- formDataBody formData req1
let req3 = applyBasicAuth
(encodeUtf8 $ hcUsername creds)
(encodeUtf8 $ hcPassword creds)
req2
putStr $ "Uploading " ++ tarName ++ "... "
hFlush stdout
withResponse req3 manager $ \res ->
case statusCode $ responseStatus res of
200 -> putStrLn "done!"
401 -> do
putStrLn "authentication failure"
cfp <- credsFile config
handleIO (const $ return ()) (removeFile cfp)
error "Authentication failure uploading to server"
403 -> do
putStrLn "forbidden upload"
putStrLn "Usually means: you've already uploaded this package/version combination"
putStrLn "Ignoring error and continuing, full message from Hackage below:\n"
printBody res
503 -> do
putStrLn "service unavailable"
putStrLn "This error some times gets sent even though the upload succeeded"
putStrLn "Check on Hackage to see if your pacakge is present"
printBody res
code -> do
putStrLn $ "unhandled status code: " ++ show code
printBody res
error $ "Upload failed on " ++ tarName
}
printBody :: Response BodyReader -> IO ()
printBody res =
loop
where
loop = do
bs <- brRead $ responseBody res
unless (S.null bs) $ do
S.hPut stdout bs
loop
-- | The computed value from a @UploadSettings@.
--
-- Typically, you want to use this with 'upload'.
--
-- Since 0.1.0.0
data Uploader = Uploader
{ upload_ :: !(String -> L.ByteString -> IO ())
}
-- | Upload a single tarball with the given @Uploader@.
--
-- Since 0.1.0.0
upload :: Uploader -> FilePath -> IO ()
upload uploader fp = upload_ uploader (takeFileName fp) =<< L.readFile fp
-- | Upload a single tarball with the given @Uploader@. Instead of
-- sending a file like 'upload', this sends a lazy bytestring.
--
-- Since 0.1.2.1
uploadBytes :: Uploader -> String -> L.ByteString -> IO ()
uploadBytes = upload_
-- | Settings for creating an @Uploader@.
--
-- Since 0.1.0.0
data UploadSettings = UploadSettings
{ usUploadUrl :: !String
, usGetManager :: !(IO Manager)
, usCredsSource :: !(Config -> HackageCredsSource)
, usSaveCreds :: !Bool
}
-- | Default value for @UploadSettings@.
--
-- Use setter functions to change defaults.
--
-- Since 0.1.0.0
defaultUploadSettings :: UploadSettings
defaultUploadSettings = UploadSettings
{ usUploadUrl = "https://hackage.haskell.org/packages/"
, usGetManager = newManager tlsManagerSettings
, usCredsSource = fromAnywhere
, usSaveCreds = True
}
-- | Change the upload URL.
--
-- Default: "https://hackage.haskell.org/packages/"
--
-- Since 0.1.0.0
setUploadUrl :: String -> UploadSettings -> UploadSettings
setUploadUrl x us = us { usUploadUrl = x }
-- | How to get an HTTP connection manager.
--
-- Default: @newManager tlsManagerSettings@
--
-- Since 0.1.0.0
setGetManager :: IO Manager -> UploadSettings -> UploadSettings
setGetManager x us = us { usGetManager = x }
-- | How to get the Hackage credentials.
--
-- Default: @fromAnywhere@
--
-- Since 0.1.0.0
setCredsSource :: (Config -> HackageCredsSource) -> UploadSettings -> UploadSettings
setCredsSource x us = us { usCredsSource = x }
-- | Save new credentials to the config file.
--
-- Default: @True@
--
-- Since 0.1.0.0
setSaveCreds :: Bool -> UploadSettings -> UploadSettings
setSaveCreds x us = us { usSaveCreds = x }
handleIO :: (E.IOException -> IO a) -> IO a -> IO a
handleIO = E.handle
| phadej/stack | src/Stack/Upload.hs | bsd-3-clause | 11,305 | 0 | 24 | 3,876 | 2,108 | 1,148 | 960 | 221 | 5 |
-- | a module for caching a monadic action based on its return type
--
-- The cache is a HashMap where the key uses the TypeReP from Typeable.
-- The value stored is toDyn from Dynamic to support arbitrary value types in the same Map.
--
-- un-exported newtype wrappers should be used to maintain unique keys in the cache.
-- Note that a TypeRep is unique to a module in a package, so types from different modules will not conflict if they have the same name.
--
-- used in 'Yesod.Core.Handler.cached' and 'Yesod.Core.Handler.cachedBy'
module Yesod.Core.TypeCache (cached, cachedBy, TypeMap, KeyedTypeMap) where
import Prelude hiding (lookup)
import Data.Typeable (Typeable, TypeRep, typeOf)
import Data.HashMap.Strict
import Data.ByteString (ByteString)
import Data.Dynamic (Dynamic, toDyn, fromDynamic)
type TypeMap = HashMap TypeRep Dynamic
type KeyedTypeMap = HashMap (TypeRep, ByteString) Dynamic
-- | avoid performing the same action multiple times.
-- Values are stored by their TypeRep from Typeable.
-- Therefore, you should use un-exported newtype wrappers for each cache.
--
-- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth.
-- This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
--
-- In Yesod, this is used for a request-local cache that is cleared at the end of every request.
-- See the original announcement: <http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals>
--
-- Since 1.4.0
cached :: (Monad m, Typeable a)
=> TypeMap
-> m a -- ^ cache the result of this action
-> m (Either (TypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cached cache action = case clookup cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cinsert val cache, val)
where
clookup :: Typeable a => TypeMap -> Maybe a
clookup c =
res
where
res = lookup (typeOf $ fromJust res) c >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
cinsert :: Typeable a => a -> TypeMap -> TypeMap
cinsert v = insert (typeOf v) (toDyn v)
-- | similar to 'cached'.
-- 'cached' can only cache a single value per type.
-- 'cachedBy' stores multiple values per type by indexing on a ByteString key
--
-- 'cached' is ideal to cache an action that has only one value of a type, such as the session's current user
-- 'cachedBy' is required if the action has parameters and can return multiple values per type.
-- You can turn those parameters into a ByteString cache key.
-- For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
--
-- Since 1.4.0
cachedBy :: (Monad m, Typeable a)
=> KeyedTypeMap
-> ByteString -- ^ a cache key
-> m a -- ^ cache the result of this action
-> m (Either (KeyedTypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cachedBy cache k action = case clookup k cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cinsert k val cache, val)
where
clookup :: Typeable a => ByteString -> KeyedTypeMap -> Maybe a
clookup key c =
res
where
res = lookup (typeOf $ fromJust res, key) c >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
cinsert :: Typeable a => ByteString -> a -> KeyedTypeMap -> KeyedTypeMap
cinsert key v = insert (typeOf v, key) (toDyn v)
| ygale/yesod | yesod-core/Yesod/Core/TypeCache.hs | mit | 3,896 | 0 | 13 | 1,009 | 639 | 346 | 293 | 43 | 2 |
{-# LANGUAGE OverloadedLists, TypeFamilies #-}
import qualified Data.Set as S
import GHC.Exts
main = do print ([] :: (S.Set Int))
print (['a','b','c'] :: (S.Set Char))
print (['a','c'..'g'] :: (S.Set Char))
instance Ord a => IsList (S.Set a) where
type (Item (S.Set a)) = a
fromList = S.fromList
toList = S.toList
| lukexi/ghc-7.8-arm64 | testsuite/tests/overloadedlists/should_run/overloadedlistsrun02.hs | bsd-3-clause | 350 | 0 | 11 | 86 | 157 | 85 | 72 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-- Test for sane reporting on TH code giving up.
module ShouldCompile where
$( fail "Code not written yet..." )
| urbanslug/ghc | testsuite/tests/th/TH_fail.hs | bsd-3-clause | 148 | 0 | 7 | 27 | 16 | 9 | 7 | 3 | 0 |
area r = pi * r ^ 2 | fredmorcos/attic | snippets/haskell/varfun.hs | isc | 19 | 0 | 6 | 7 | 17 | 8 | 9 | 1 | 1 |
{-# LANGUAGE DeriveGeneric, RecordWildCards, TypeSynonymInstances, FlexibleInstances #-}
module Game.World(
World(..)
, WorldId(..)
, worldInfoMsg
, WorldFindPlayer(..)
) where
import Control.DeepSeq
import Data.Hashable
import Data.HashMap.Strict (HashMap)
import Data.Text (Text)
import Game.Player
import GHC.Generics (Generic)
import Network.Protocol.Message
import qualified Data.HashMap.Strict as M
-- | World are completly isolated environments
data World = World {
worldId :: !WorldId
, worldName :: !Text
, worldPlayers :: !(HashMap PlayerId Player)
, worldPlayersByName :: !(HashMap Text Player)
} deriving (Generic)
instance NFData World
newtype WorldId = WorldId { unWorldId :: Int } deriving (Eq, Show, Generic)
instance NFData WorldId
instance Hashable WorldId
worldInfoMsg :: World -> NetworkMessage
worldInfoMsg (World{..}) = PlayerWorld (unWorldId worldId) worldName
class WorldFindPlayer k where
-- | Finds player by specific key
worldFindPlayer :: World -> k -> Maybe Player
-- | You can search players by name
instance WorldFindPlayer Text where
worldFindPlayer w = (`M.lookup` worldPlayersByName w)
-- | And you can search players by theirs ids
instance WorldFindPlayer PlayerId where
worldFindPlayer w = (`M.lookup` worldPlayers w) | NCrashed/sinister | src/shared/Game/World.hs | mit | 1,296 | 0 | 11 | 207 | 323 | 186 | 137 | 40 | 1 |
{-# LANGUAGE TemplateHaskell #-}
import TemplateHaskell
data MyData = MyData
{ foo :: String
, bar :: Int
}
listFields ''MyData
main = print $ MyData { foo = "what", bar = 1 }
| limdauto/learning-haskell | snippets/TemplateHaskellTests.hs | mit | 192 | 0 | 8 | 50 | 57 | 33 | 24 | 7 | 1 |
module System.AtomicWrite.Writer.ByteStringSpec (spec) where
import Test.Hspec (it, describe, shouldBe, Spec)
import System.AtomicWrite.Writer.ByteString (atomicWriteFile)
import System.IO.Temp (withSystemTempDirectory)
import System.FilePath.Posix (joinPath)
import Data.ByteString.Char8 (pack)
spec :: Spec
spec = describe "atomicWriteFile" $
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFile path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
| bitemyapp/atomic-write | spec/System/AtomicWrite/Writer/ByteStringSpec.hs | mit | 625 | 0 | 13 | 103 | 163 | 91 | 72 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Parser for what seems to be DCPU16 assembly.
--
-- There is some ambiguity between sources: the specification uses uppercase a
-- lot (which I'd rather put in as an option later, with the strict
-- implementation being default).
--
-- A screenshot also shows indirect mode being done with [] instead of (). Go
-- figure.
module DCPU16.Assembly.Parser
( parseFile
, defaults
, Options(..)
) where
import Text.Trifecta hiding (Pop,Push)
import Control.Applicative hiding (Const)
import DCPU16.Instructions
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Vector (Vector)
import Data.Word (Word16)
import qualified Data.Vector as V
import Data.Char (toUpper)
import Control.Monad (void,unless,when)
import Text.Printf
-- | Default parsing options.
defaults :: Options
defaults = Options False
-- | Parsing options, if you want to override the defaults.
data Options = Options
{ roundedBrackets :: Bool
-- ^ Indirect mode via \(\) instead of \[\]. Default: off.
--
-- Weird, but showed up in a screenshot.
} deriving (Read,Show,Eq)
-- | Parser state.
--
-- Should factor this into a RWS monad wrapper, but don't understand Trifecta
-- well enough to do so. Monads, how do they work?
data Opt = Opt
{ optSymbols :: Vector ByteString
, options :: Options
} deriving (Read,Show,Eq)
-- | Parse a file.
--
-- Detailed errors with line and column numbers (as well as expected values)
-- will be printed to console if parsing fails.
parseFile opt f = do
ss <- parseFromFile symbolDefs f
case ss of
(Just syms) -> parseFromFile (asm (Opt syms opt)) f
Nothing -> return Nothing
symbolDefs :: Parser String (Vector ByteString)
-- | Label definition only parser.
--
-- Meant to be run as the first pass, to extract a table to check label uses
-- against in a future pass.
symbolDefs = process `fmap` (spaces >> ls <* end) where
-- labels appear at the start of lines:
-- if something un-label-like seen, skip to next line
ls = many . lexeme . choice $ [label,nextLine]
nextLine = Data (Const 0) <$ skipSome (satisfy notMark)
notMark c = c/='\n'
process = V.fromList . map (\(Label s)->s) . filter isLabel
isLabel (Label _) = True
isLabel _ = False
-- | Instruction, comment, and label parser.
--
-- Relies on a symbol table parsed in a previous pass to check for label
-- existance.
asm :: Opt -> Parser String (Vector Instruction)
asm o = V.fromList `fmap` (spaces >> instructs <* end) where
instructs = many . lexeme . choice $ [instruction o, label, comment, dat o]
end = eof <?> "comment, end of file, or valid instruction"
-- | For now, data only handles one word.
--
-- Will figure out good syntax sugar (and refactor "asm" to handle multi-word)
-- later.
dat o = Data <$ symbol "dat" <*> word o
label = do
char ':'
l<-labelName
when (isRegName (B.unpack l)) $
err [] $ "label definition "++show l++" clashes with register name"
spaces
return $ Label l
where
isRegName :: String -> Bool
isRegName s = map toUpper s `elem` regs
regs = ["A","B","C","X","Y","Z","I","J"
,"POP","PEEK","PUSH","PC","O"
]
labelName = B.pack `fmap` some labelChars
labelChars = alphaNum <|> char '_' <|> char '.'
comment = do
char ';'
l <- line
Comment (B.head l == ';') <$> manyTill anyChar eofOrNewline
where
eofOrNewline = void (try newline) <|> eof
instruction :: Opt -> Parser String Instruction
instruction o = choice
[ Basic <$> basicOp o <*> operand o <* comma <*> operand o
, NonBasic <$> sym o JSR "jsr" <*> operand o
]
operand :: Opt -> Parser String Operand
operand o = choice
[ sym o Pop "pop"
, sym o Peek "peek"
, sym o Push "push"
, sym o SP "sp"
, sym o PC "pc"
, sym o O "o"
, Direct <$> register o
, DirectLiteral <$> word o
, brace o (indirect o)
]
where
indirect o = choice
[ try $ Offset <$> word o <* symbol "+" <*> register o
, try $ flip Offset <$> register o <* symbol "+" <*> word o
, try $ Indirect <$> register o
, IndirectLiteral <$> word o
]
-- This code is based on the Haskell parser, and thus strips a lot more
-- whitespace than desired. [\na+2] probably shouldn't be valid assembly.
brace o = if roundedBrackets $ options o
then nesting . between (symbolic '(') (symbolic ')')
else brackets
word :: Opt -> Parser String Word
word o = lexeme $ choice
[ Const <$> int
, definedLabel
]
where
definedLabel = do
s <- labelName
unless (s `V.elem` optSymbols o) $
err [] $ "label "++show s++" not defined"
return $ LabelAddr s
int :: Parser String Word16
int = fromInteger <$> (num >>= checkSize)
where
num = choice
[ try $ (char '0' <?> "\"0x\"") >> hexadecimal
, decimal
]
checkSize :: Integer -> Parser String Integer
checkSize n = if n>0xffff
then do
err [] (printf fmt n)
return (mod n 0xffff)
else return n
fmt = "literal 0x%x is wider than 16 bits"
sym o i tok = try $ i <$ token <* notFollowedBy labelChars <* spaces
where
token = string tok <|> string (map toUpper tok)
register o = try $ choice
[ sym o A "a", sym o B "b", sym o C "c"
, sym o X "x", sym o Y "y", sym o Z "z"
, sym o I "i", sym o J "j"
]
basicOp o = choice
[ sym o SET "set", sym o ADD "add", sym o SUB "sub"
, sym o MUL "mul", sym o DIV "div", sym o MOD "mod", sym o SHL "shl"
, sym o SHR "shr", sym o AND "and", sym o BOR "bor", sym o XOR "xor"
, sym o IFE "ife", sym o IFN "ifn", sym o IFG "ifg", sym o IFB "ifb"
]
| amtal/soyuz | DCPU16/Assembly/Parser.hs | mit | 5,788 | 0 | 16 | 1,496 | 1,728 | 904 | 824 | 116 | 2 |
{-# OPTIONS_GHC -Wall #-}
module Todo.Predicates ( minDate
, maxDate
, minPriority
, maxPriority
, isComplete
) where
import Todo.Data
minDate :: Date -> Task -> Bool
minDate d = maybe False (d >=) . maybeDate
maxDate :: Date -> Task -> Bool
maxDate d = maybe True (d >=) . maybeDate
minPriority :: Priority -> Task -> Bool
minPriority p = maybe False (>= p) . priority
maxPriority :: Priority -> Task -> Bool
maxPriority p = maybe True (<= p) . priority
isComplete :: Task -> Bool
isComplete t = case status t of
Done _ -> True
_ -> False
| nadirs/todohs | src/lib/Todo/Predicates.hs | mit | 669 | 0 | 8 | 232 | 204 | 110 | 94 | 19 | 2 |
-- https://projecteuler.net/problem=29
-- Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
-- 22=4, 23=8, 24=16, 25=32
-- 32=9, 33=27, 34=81, 35=243
-- 42=16, 43=64, 44=256, 45=1024
-- 52=25, 53=125, 54=625, 55=3125
-- If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
-- 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
-- How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
import Data.Set
import qualified Data.Set as Set
import Data.List
cartProd xs ys = [x^y | x <- xs, y <- ys]
countPowers n = size (fromList (cartProd [2..n] [2..n]))
countPowers2 n = length (nub [x^y | x <- [2..n], y <- [2..n]]) | kirhgoff/haskell-sandbox | euler29/countPowers.hs | mit | 774 | 0 | 11 | 150 | 146 | 82 | 64 | 6 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module HsPredictor.LoadCSV where
-- standard
import Control.Exception (bracket, catch, throwIO)
import Control.Monad (when)
import Control.Monad.Error (liftIO)
import Data.Text (pack)
import Prelude hiding (catch)
import System.IO (IOMode (ReadMode), hClose,
hGetContents, openFile)
import System.IO.Error
-- 3rd party
import Database.Persist.Sql (Entity (..), Filter, Key (..),
SelectOpt (LimitTo), SqlBackend,
SqlPersistM, deleteWhere, entityKey,
get, getBy, insert, insertBy,
runMigration, runMigrationSilent,
selectList, selectList, toSqlKey,
update, (+=.), (=.), (==.), (>.))
import Database.Persist.Sqlite (runSqlite)
-- own
import HsPredictor.HashCSV (checkHash, genHash)
import HsPredictor.Models
import HsPredictor.ParserCSV (readMatches)
import HsPredictor.Queries
import HsPredictor.Types (Field (..), Match (..), Result (..))
-- | Inserts match to database
insertMatch :: Match -> SqlPersistM ()
insertMatch (Match {dateM=d,homeM=ht,awayM=at,ghM=gh,gaM=ga,
odds1M=o1,oddsxM=ox,odds2M=o2}) = do
idHome <- getKeyTeams ht
idAway <- getKeyTeams at
insert $ Results d idHome idAway gh ga o1 ox o2
updateTable idHome $ getResult Home gh ga
updateTable idAway $ getResult Away gh ga
-- | Return sql key for a given team name
getKeyTeams :: String -> SqlPersistM (Key Teams)
getKeyTeams team = do
eitherKey <- insertBy $ Teams team
return $ keyFromEither eitherKey
-- | Return result of match
getResult :: Field -> Int -> Int -> Result
getResult Home rh ra
| rh == (-1) = Upcoming
| rh == ra = Draw
| rh > ra = Win
| otherwise = Loss
getResult Away rh ra
| rh == (-1) = Upcoming
| rh == ra = Draw
| rh > ra = Loss
| otherwise = Win
-- | Update team statistics
updateTable :: Key Teams -> Result -> SqlPersistM ()
updateTable team result = do
eitherKey <- insertBy $ StatsTable team 0 0 0
let teamId = keyFromEither eitherKey
case result of
Win -> update teamId [StatsTableWin +=. 1]
Draw -> update teamId [StatsTableDraw +=. 1]
Loss -> update teamId [StatsTableLoss +=. 1]
Upcoming -> return ()
-- | Return sql key form Either
keyFromEither :: Either (Entity record) (Key record) -> Key record
keyFromEither (Left ent) = entityKey ent
keyFromEither (Right key) = key
-- | Insert matches into database. Only if csv was updated.
-- | checkHash prevents from processing the same file twice.
bulkInsert :: [Match] -> String -> String -> SqlPersistM ()
bulkInsert xs hashF hashDB =
when (checkHash hashF hashDB) $ do
deleteWhere ([] :: [Filter Results])
deleteWhere ([] :: [Filter StatsTable])
deleteWhere ([] :: [Filter Teams])
mapM_ insertMatch xs
-- | Main function for processing matches and inserting into database.
action :: [Match] -- ^ list of matches
-> String -- ^ hash of csv file
-> String -- ^ path to database
-> IO ()
action xs hashF dbname = runSqlite (pack dbname) $ do
runMigrationSilent migrateAll
isHashDB <- get (toSqlKey 1 :: MD5Id)
case isHashDB of
Nothing -> do
insertBy $ MD5 hashF
bulkInsert xs hashF ""
Just h -> do
update (toSqlKey 1 :: MD5Id) [MD5Hash =. hashF]
bulkInsert xs hashF $ mD5Hash h
return ()
-- | Return file contents
getFileContents :: String -> IO String
getFileContents fname = readF `catch` handleExists
where
readF = do
csvH <- openFile fname ReadMode
!full <- hGetContents csvH
hClose csvH
return full
handleExists e
| isDoesNotExistError e = return ""
| otherwise = throwIO e
-- | Load csv into database
loadCSV :: String -> String -> IO ()
loadCSV fname dbname = do
full <- getFileContents fname
hash <- genHash full
let matches = readMatches $ lines full
action matches hash dbname
| Taketrung/HsPredictor | library/HsPredictor/LoadCSV.hs | mit | 4,364 | 0 | 15 | 1,305 | 1,274 | 662 | 612 | 98 | 4 |
module ECL.ClassicChecker where
import ECL.DataTypes
-- | Type Synonyms for pattern
-- * representation
-- *
-- * Basic representations of cases
type Case = [Binder]
type Cases = [Case]
-- * Result
type Result = Cases
-- * Pattern Matching definition
type DefPm = Cases
-- | unmatched: returns the list
-- * of `_` for the first uncovered set
unmatched :: Case -> Cases
unmatched c = [unmatched' c]
unmatched' :: Case -> Case
unmatched' = foldr op []
where
op :: Binder -> Case -> Case
op _ c = NullBinder:c
-- | check: given a pattern matching definition
-- * we check whether or not it is exhaustive
-- * giving the resultant non-covered cases
ccheck :: DefPm -> Result
ccheck [] = []
ccheck pmdef@(pm:_) =
check_uncovers unm pmdef
where
unm = unmatched pm
-- | uncover: single binder uncovering
-- * this returns the difference between
-- * two single binders
uncover :: Binder -> Binder -> Case
uncover Zero Zero = []
uncover _ NullBinder = []
uncover NullBinder b =
concat $ map (\cp -> uncover cp b) all_pat
where
all_pat = [Zero, Succ NullBinder]
uncover (Succ n) (Succ m) =
map Succ ucs
where
ucs = uncover n m
uncover b _ = [b]
-- | uncovers: given an uncovered case and a clause
-- * of a pattern match definition,
-- * returns the uncovered cases
uncovers :: Case -> Case -> Cases
-- empty case
uncovers [] [] = []
-- any-var
uncovers (u:us) (NullBinder:ps) =
map (u:) (uncovers us ps)
-- zero-zero
uncovers (Zero:us) (Zero:ps) =
map (Zero:) (uncovers us ps)
-- succ-zero
uncovers ucs@((Succ _):_) (Zero:_) =
[ucs]
-- zero-succ
uncovers ucs@(Zero:_) ((Succ _):_) =
[ucs]
-- succ-succ
uncovers ((Succ n):us) ((Succ m):ps) =
let ucs = uncovers (n:us) (m:ps)
in map (zip_con Succ) ucs
where
-- This *must* be generalized for all constructors
zip_con :: (Binder -> Binder) -> Case -> Case
zip_con _ [] = []
zip_con b xs = (b hps):rest
where
(hps, rest) = (head xs, tail xs)
-- var-nat
uncovers (NullBinder:us) pats@(_:_) =
-- This must be something that traverse all constructors of a type
let all_pat = [Zero, Succ NullBinder]
uncovered = map (\cp -> uncovers (cp:us) pats) all_pat
in concat uncovered
-- I guess other cases must fail inside a monad
uncovers _ _ = []
-- | uncovering: returns the cases
-- * that are not covered by a single clause
uncovering :: Cases -> Case -> Cases
uncovering unc clause =
concat $ map (\u -> uncovers u clause) unc
-- | check_uncovers: Given an uncovered set and a full pm definition
-- * this calculates the cases that are not covered by
-- * the pattern matching definition
check_uncovers :: Cases -> Cases -> Cases
check_uncovers ucs [] = ucs
check_uncovers ucs (c:cs) =
let ucs' = uncovering ucs c
in check_uncovers ucs' cs
-- | is_exhaustive: returns whether or not
-- * the given definition is exhaustive
is_exhaustive :: DefPm -> Bool
is_exhaustive = null . ccheck
| nicodelpiano/stlcnat-exhaustivity-checker | src/ECL/ClassicChecker.hs | mit | 2,949 | 0 | 14 | 643 | 899 | 490 | 409 | 59 | 2 |
module Routes.TH
( module Routes.TH.Types
-- * Functions
, module Routes.TH.RenderRoute
, module Routes.TH.ParseRoute
, module Routes.TH.RouteAttrs
-- ** Dispatch
, module Routes.TH.Dispatch
) where
import Routes.TH.Types
import Routes.TH.RenderRoute
import Routes.TH.ParseRoute
import Routes.TH.RouteAttrs
import Routes.TH.Dispatch
| ajnsit/wai-routes | src/Routes/TH.hs | mit | 370 | 0 | 5 | 72 | 75 | 52 | 23 | 11 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Main where
--import Data.ByteString.Char8 (ByteString)
import HlAdif
import HlLog
import HlOptions
import Options.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Semigroup ((<>))
import System.IO
import Text.Regex.TDFA.ByteString
data Options = Options
{ flexps :: [FlExp]
, getInputHandle :: IO Handle
}
optionsParserInfo :: ParserInfo Options
optionsParserInfo = info (helper <*> (
Options
<$> filterOptions
<*> inputHandleArgument
)) (
fullDesc
<> progDesc "Filter ADIF records according to filter expressions"
)
tagMatches :: FlExp -> Tag -> Bool
tagMatches expr (CTag (tname, mbtval)) =
case expr of
FlEx ftname -> ftname == tname
otherexpr ->
case mbtval of
Nothing -> False
Just (tvalue, _) ->
case otherexpr of
FlGte ftname fvalue -> ftname == tname && tvalue >= fvalue
FlGt ftname fvalue -> ftname == tname && tvalue > fvalue
FlLte ftname fvalue -> ftname == tname && tvalue <= fvalue
FlLt ftname fvalue -> ftname == tname && tvalue < fvalue
FlReg ftname fregex -> ftname == tname &&
case execute fregex tvalue of
Right (Just _) -> True
_ -> False
FlEq ftname fvalue -> ftname == tname && tvalue == fvalue
FlNeq ftname fvalue -> ftname == tname && tvalue /= fvalue
_ -> False
recordMatches :: FlExp -> Record -> Bool
recordMatches expr (CRecord ts) = any (tagMatches expr) ts
filterLog :: [FlExp] -> Log -> Log
filterLog flexps Log{..} = Log logHeaderTxt logHeaderTags $ filter (\rec -> any (flip recordMatches rec) flexps) logRecords
doFilterLog :: Options -> IO ()
doFilterLog opt = do
parseResult <- adifLogParser <$> (getInputHandle opt >>= B.hGetContents)
case parseResult of
Left errorMsg -> putStrLn errorMsg
Right l -> B.putStr $ writeLog $ filterLog (flexps opt) l
return ()
main :: IO ()
main = execParser optionsParserInfo >>= doFilterLog
| netom/hamloghs | app/hl-filter.hs | mit | 2,313 | 0 | 20 | 782 | 637 | 326 | 311 | 54 | 11 |
-- Problems/Problem063Spec.hs
module Problems.Problem063Spec (main, spec) where
import Test.Hspec
import Problems.Problem063
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 63" $
it "Should evaluate to 49" $
p63 `shouldBe` 49
| Sgoettschkes/learning | haskell/ProjectEuler/tests/Problems/Problem063Spec.hs | mit | 262 | 0 | 8 | 51 | 73 | 41 | 32 | 9 | 1 |
data Quantum =
Yes
| No
| Both deriving (Eq, Show)
convert :: Quantum -> Bool
convert Yes = False
convert No = False
convert Both = False
convert2 Yes = False
convert2 No = False
convert2 Both = True
convert3 Yes = False
convert3 No = True
convert3 Both = True
convert4 Yes = True
convert4 No = True
convert4 Both = True
convert5 Yes = True
convert5 No = True
convert5 Both = False
convert6 Yes = True
convert6 No = False
convert6 Both = False
convert7 Yes = True
convert7 No = False
convert7 Both = True
convert8 Yes = False
convert8 No = True
convert8 Both = False
data Quad =
One
| Two
| Three
| Four
-- eQuad :: Either Quad Quad
-- 4 + 4 = 8
-- prodQuad :: (Quad, Quad)
-- 4 * 4 = 16
-- funcQuad :: Quad -> Quad
-- 4 ^ 4 = 256
-- prodTBool :: (Bool, Bool, Bool)
-- 2 * 2 * 2
-- gTwo :: Bool -> Bool -> Bool
-- 2 ^ 2 ^ 2 = 16
-- fTwo :: Bool -> Quad -> Quad
-- 4 ^ 4 ^ 2 = 65535
-- (2 ^ 4) ^ 4 = 65535
| JustinUnger/haskell-book | ch11/exp.hs | mit | 946 | 0 | 6 | 250 | 255 | 138 | 117 | 34 | 1 |
{- |
- Implementation of the IDA* search algorithm
-}
{-# LANGUAGE ScopedTypeVariables, MultiParamTypeClasses,
FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}
module Rubik.IDA where
import qualified Data.Set as S
-- | Type of outgoing edges, labelled and weighted.
data Succ label length node = Succ {
eLabel :: label,
eCost :: length,
eSucc :: node
}
data Search f a l node = Search {
goal :: node -> Bool,
estm :: node -> a,
edges :: node -> f (Succ l a node)
}
type Result a l = Maybe [l]
data SearchResult a l = Next !a | Found [l] | Stop
instance Ord a => Monoid (SearchResult a l) where
{-# INLINE mempty #-}
mempty = Stop
{-# INLINE mappend #-}
mappend f@(Found _) _ = f
mappend _ f@(Found _) = f
mappend (Next a) (Next b) = Next (min a b)
mappend Stop x = x
mappend x Stop = x
-- | Depth-first search up to depth @bound@,
-- and reduce results from the leaves.
dfSearch
:: (Foldable f, Num a, Ord a)
=> Search f a l node
-> node -> a -> [l] -> a -> SearchResult a l
{-# INLINE dfSearch #-}
dfSearch (Search goal estm edges) n g ls bound
= dfs n g ls bound
where
dfs n g ls bound
| g == bound && g == f && goal n = Found (reverse ls)
| f > bound = Next f
| otherwise
= foldMap searchSucc $ edges n
where
isGoal = goal n
f = g + estm n
searchSucc (Succ eLabel eCost eSucc)
= dfs eSucc (g + eCost) (eLabel : ls) bound
-- | IDA* search
--
-- All paths to goal(s) are returned, grouped by length.
--
-- Only searches as deep as necessary thanks to lazy evaluation.
--
-- TODO: Possible memory leak, solving hard cubes eats a lot of memory.
search
:: forall f a l node . (Foldable f, Num a, Ord a)
=> Search f a l node
-> node {- ^ root -} -> Maybe [l]
{-# INLINE search #-}
search s root = rootSearch (estm s root)
where
-- Search from the root up to a distance @d@
-- for increasing values of @d@.
rootSearch :: a -> Maybe [l]
rootSearch d =
case dfSearch s root 0 [] d of
Stop -> Nothing
Found ls -> Just ls
Next d' -> rootSearch d'
data SelfAvoid node = SelfAvoid (S.Set node) node
selfAvoid (Search goal estm edges) = Search {
goal = goal . node,
estm = estm . node,
edges = edges'
}
where
node (SelfAvoid _ n) = n
edges' (SelfAvoid trace n)
= [ Succ l c (SelfAvoid (S.insert s trace) s)
| Succ l c s <- edges n, S.notMember s trace ]
selfAvoidRoot root = (root, S.singleton root)
| Lysxia/twentyseven | src/Rubik/IDA.hs | mit | 2,548 | 0 | 13 | 713 | 847 | 450 | 397 | 63 | 3 |
import Control.Monad.Writer
import Control.Monad ((<=<), (>=>))
deeldoorTwee :: (Integral a, Show a) => a -> Maybe String
deeldoorTwee x = if even x
then Just (show x++" is deelbaar door 2." )
else Just (show x++" is niet deelbaar door 2!" )
half :: (Integral a) => a -> Maybe a
half x = if even x
then Just (x `div` 2)
else Nothing
halveer :: Int -> Maybe Int
halveer x = do
if even x
then Just (x `div` 2)
else Nothing
halveer' :: Int -> Maybe Int
halveer' x | even x = Just (x `div` 2)
| otherwise = Nothing
plus2 :: Int -> Maybe Int
plus2 x = Just (x+2)
plus2enhalveer :: Int -> Maybe Int
plus2enhalveer = plus2 >=> halveer
halveerEnplus2 :: Int -> Maybe Int
halveerEnplus2 = plus2 <=< halveer
draaiom :: String -> Maybe String
draaiom s = Just (reverse s)
main =
getLine >>= \x ->
putStrLn x >>= \_ ->
return ()
main1 =
getLine >>= \x ->
putStrLn (x++"hoi") >>= \_ ->
return ()
main2 =
getLine >>= \x ->
putStrLn x >>= \_ ->
return ()
main4 =
getLine >>= \x -> putStrLn (x++"hoi") >>= \_ -> return ()
theodds = do
x <- [1..10]
if odd x
then [x * 2]
else []
theodds' = [x*2 | x <-[1..10], odd x]
f :: Float -> Float
f = \x -> x^2
addWorld :: String -> IO String
addWorld s = return (s++" world")
| iambernie/tryhaskell | useful.hs | mit | 1,399 | 0 | 10 | 445 | 608 | 317 | 291 | 50 | 2 |
module Assembler(assemble) where
import Datatypes
import Opcodes
import Text.Printf
assemble :: [IR] -> [String]
assemble instructions =
map (printf "0x%08x") hex
where hex = map assembleInstruction instructions
assembleInstruction :: IR -> Int
assembleInstruction LoadIR = (hexOpcode Lw)
assembleInstruction StoreIR = (hexOpcode Sw)
assembleInstruction (TwoIR (R reg) (I immediate) masked) =
(hexMask masked) + (hexOpcode Addi) + (hexRt reg) + (immediate `mod` 2 ^ 16)
assembleInstruction (TwoIR (R reg) (C address) masked) =
(hexMask masked) + (hexOpcode Ldc) + (hexRt reg) + (address `mod` 2 ^ 16)
assembleInstruction (ThreeIR operator (R rd) (R rs) (R rt) masked) =
(hexMask masked) + (hexOpcode opcode) + (hexRd rd) + (hexRs rs) + (hexRt rt) + (hexAlufunction opcode)
where opcode = case operator of
BitwiseAnd -> And
BitwiseOr -> Or
BitwiseXor -> Xor
Plus -> Add
Minus -> Sub
Multiply -> Mul
LessThan -> Slt
EqualTo -> Seq
assembleInstruction (ThreeIR op rd (I rs) (R rt) masked)
| op == Plus = assembleInstruction (ThreeIR op rd (R rt) (I rs) masked)
assembleInstruction (ThreeIR operator (R rd) (R rs) (I sh) masked) =
(hexMask masked) + (hexOpcode opcode) + (hexRd rd) + (hexRs rs) + sh
where opcode = case operator of
Plus -> Addi
ShiftLeft -> Sll
ShiftRight -> Srl
ShiftRightArithmetic -> Sra
| aleksanb/hdc | src/Assembler.hs | mit | 1,524 | 0 | 11 | 429 | 592 | 303 | 289 | 35 | 11 |
module Import
( module Import
) where
import Foundation as Import
import Import.NoFoundation as Import
-- vim:set expandtab:
| tmcl/katalogo | backend/sqlite/Import.hs | gpl-3.0 | 147 | 0 | 4 | 40 | 23 | 17 | 6 | 4 | 0 |
module Data.XDR.PPUtils
( ppConstExpr
) where
import Data.XDR.AST
import Text.PrettyPrint.Leijen as PP hiding (braces, indent)
ppConstExpr :: ConstExpr -> Doc
ppConstExpr (ConstLit n) = text . show $ n
ppConstExpr (ConstRef (ConstantDef n _)) = text n
ppConstExpr (ConstBinExpr op c1 c2) = ppBinOp op (ppConstExpr c1) (ppConstExpr c2)
ppConstExpr (ConstUnExpr NEG c) = parens $ text "-" <> ppConstExpr c
ppConstExpr (ConstUnExpr NOT c) = parens $ text "~" <> ppConstExpr c
ppBinOp :: BinOp -> Doc -> Doc -> Doc
ppBinOp op d1 d2 = parens $ parens d1 </> (text . symbol $ op) <+> parens d2
where
symbol MUL = "*"
symbol DIV = "/"
symbol MOD = "%"
symbol ADD = "+"
symbol SUB = "-"
symbol SHR = ">>"
symbol SHL = "<<"
symbol AND = "&"
symbol XOR = "^"
symbol OR = "|"
| jthornber/xdrgen | Data/XDR/PPUtils.hs | gpl-3.0 | 891 | 0 | 9 | 267 | 328 | 168 | 160 | 22 | 10 |
module Support where
import Data.List
import Data.Char
import Network.Curl
import Control.Monad
import qualified Utilities as T
type App = String
support :: App -> App -> IO Float
support lhs rhs = do
lhs `T.shouldHaveType` T.app
rhs `T.shouldHaveType` T.app
let lhs' = map toLower . T.remove $ lhs
let rhs' = map toLower . T.remove $ rhs
let url = "http://localhost:5000/support"
++"?lhs="++lhs'
++"&rhs="++rhs'
(code, str) <- curlGetString url []
if "Error:" `isPrefixOf` str
then fail "arguments"
else return $ read str
| bogwonch/SecPAL | functions/Support.hs | gpl-3.0 | 575 | 0 | 13 | 133 | 204 | 107 | 97 | 20 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.RemoteBuildExecution
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Supplies a Remote Execution API service for tools such as bazel.
--
-- /See:/ <https://cloud.google.com/remote-build-execution/docs/ Remote Build Execution API Reference>
module Network.Google.RemoteBuildExecution
(
-- * Service Configuration
remoteBuildExecutionService
-- * OAuth Scopes
, cloudPlatformScope
-- * API Declaration
, RemoteBuildExecutionAPI
-- * Resources
-- ** remotebuildexecution.actionResults.get
, module Network.Google.Resource.RemoteBuildExecution.ActionResults.Get
-- ** remotebuildexecution.actionResults.update
, module Network.Google.Resource.RemoteBuildExecution.ActionResults.Update
-- ** remotebuildexecution.actions.execute
, module Network.Google.Resource.RemoteBuildExecution.Actions.Execute
-- ** remotebuildexecution.blobs.batchRead
, module Network.Google.Resource.RemoteBuildExecution.Blobs.BatchRead
-- ** remotebuildexecution.blobs.batchUpdate
, module Network.Google.Resource.RemoteBuildExecution.Blobs.BatchUpdate
-- ** remotebuildexecution.blobs.findMissing
, module Network.Google.Resource.RemoteBuildExecution.Blobs.FindMissing
-- ** remotebuildexecution.blobs.getTree
, module Network.Google.Resource.RemoteBuildExecution.Blobs.GetTree
-- ** remotebuildexecution.getCapabilities
, module Network.Google.Resource.RemoteBuildExecution.GetCapabilities
-- ** remotebuildexecution.operations.waitExecution
, module Network.Google.Resource.RemoteBuildExecution.Operations.WaitExecution
-- * Types
-- ** BuildBazelRemoteExecutionV2Digest
, BuildBazelRemoteExecutionV2Digest
, buildBazelRemoteExecutionV2Digest
, bbrevdSizeBytes
, bbrevdHash
-- ** GoogleRpcStatus
, GoogleRpcStatus
, googleRpcStatus
, grsDetails
, grsCode
, grsMessage
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaGetWorkerPoolRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaGetWorkerPoolRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaGetWorkerPoolRequest
, gdravgwprName
-- ** BuildBazelRemoteExecutionV2OutputSymlink
, BuildBazelRemoteExecutionV2OutputSymlink
, buildBazelRemoteExecutionV2OutputSymlink
, bbrevosPath
, bbrevosNodeProperties
, bbrevosTarget
-- ** GoogleDevtoolsRemoteworkersV1test2FileMetadata
, GoogleDevtoolsRemoteworkersV1test2FileMetadata
, googleDevtoolsRemoteworkersV1test2FileMetadata
, gdrvfmContents
, gdrvfmPath
, gdrvfmIsExecutable
, gdrvfmDigest
-- ** GoogleLongrunningOperationMetadata
, GoogleLongrunningOperationMetadata
, googleLongrunningOperationMetadata
, glomAddtional
-- ** BuildBazelRemoteExecutionV2ExecuteOperationMetadataStage
, BuildBazelRemoteExecutionV2ExecuteOperationMetadataStage (..)
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaInstanceState
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaInstanceState (..)
-- ** GoogleDevtoolsRemoteworkersV1test2Digest
, GoogleDevtoolsRemoteworkersV1test2Digest
, googleDevtoolsRemoteworkersV1test2Digest
, gdrvdSizeBytes
, gdrvdHash
-- ** BuildBazelRemoteExecutionV2ServerCapabilities
, BuildBazelRemoteExecutionV2ServerCapabilities
, buildBazelRemoteExecutionV2ServerCapabilities
, bbrevscHighAPIVersion
, bbrevscExecutionCapabilities
, bbrevscCacheCapabilities
, bbrevscDeprecatedAPIVersion
, bbrevscLowAPIVersion
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyLinuxIsolation
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyLinuxIsolation (..)
-- ** BuildBazelRemoteExecutionV2Action
, BuildBazelRemoteExecutionV2Action
, buildBazelRemoteExecutionV2Action
, bbrevaPlatform
, bbrevaDoNotCache
, bbrevaCommandDigest
, bbrevaSalt
, bbrevaInputRootDigest
, bbrevaTimeout
-- ** BuildBazelRemoteExecutionV2OutputDirectory
, BuildBazelRemoteExecutionV2OutputDirectory
, buildBazelRemoteExecutionV2OutputDirectory
, bbrevodPath
, bbrevodTreeDigest
-- ** BuildBazelRemoteExecutionV2Tree
, BuildBazelRemoteExecutionV2Tree
, buildBazelRemoteExecutionV2Tree
, bbrevtChildren
, bbrevtRoot
-- ** BuildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange
, BuildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange
, buildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange
, bbrevpcprMinPriority
, bbrevpcprMaxPriority
-- ** BuildBazelRemoteExecutionV2OutputFile
, BuildBazelRemoteExecutionV2OutputFile
, buildBazelRemoteExecutionV2OutputFile
, bbrevofContents
, bbrevofPath
, bbrevofIsExecutable
, bbrevofDigest
, bbrevofNodeProperties
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaCreateInstanceRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaCreateInstanceRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaCreateInstanceRequest
, gdravcirParent
, gdravcirInstanceId
, gdravcirInstance
-- ** BuildBazelRemoteExecutionV2Directory
, BuildBazelRemoteExecutionV2Directory
, buildBazelRemoteExecutionV2Directory
, bbrevdDirectories
, bbrevdSymlinks
, bbrevdFiles
, bbrevdNodeProperties
-- ** BuildBazelRemoteExecutionV2DirectoryNode
, BuildBazelRemoteExecutionV2DirectoryNode
, buildBazelRemoteExecutionV2DirectoryNode
, bbrevdnName
, bbrevdnDigest
-- ** BuildBazelRemoteExecutionV2NodeProperties
, BuildBazelRemoteExecutionV2NodeProperties
, buildBazelRemoteExecutionV2NodeProperties
, bbrevnpMtime
, bbrevnpUnixMode
, bbrevnpProperties
-- ** GoogleDevtoolsRemoteworkersV1test2CommandTaskTimeouts
, GoogleDevtoolsRemoteworkersV1test2CommandTaskTimeouts
, googleDevtoolsRemoteworkersV1test2CommandTaskTimeouts
, gdrvcttIdle
, gdrvcttShutdown
, gdrvcttExecution
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaInstance
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaInstance
, googleDevtoolsRemotebuildexecutionAdminV1alphaInstance
, gdraviState
, gdraviLocation
, gdraviFeaturePolicy
, gdraviName
, gdraviLoggingEnabled
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfigLabels
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfigLabels
, googleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfigLabels
, gdravwclAddtional
-- ** GoogleDevtoolsRemotebuildbotCommandStatusCode
, GoogleDevtoolsRemotebuildbotCommandStatusCode (..)
-- ** BuildBazelRemoteExecutionV2ExecutionCapabilities
, BuildBazelRemoteExecutionV2ExecutionCapabilities
, buildBazelRemoteExecutionV2ExecutionCapabilities
, bbrevecSupportedNodeProperties
, bbrevecExecutionPriorityCapabilities
, bbrevecExecEnabled
, bbrevecDigestFunction
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaUpdateWorkerPoolRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaUpdateWorkerPoolRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaUpdateWorkerPoolRequest
, gdravuwprUpdateMask
, gdravuwprWorkerPool
-- ** BuildBazelRemoteExecutionV2BatchReadBlobsRequest
, BuildBazelRemoteExecutionV2BatchReadBlobsRequest
, buildBazelRemoteExecutionV2BatchReadBlobsRequest
, bbrevbrbrDigests
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerPool
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerPool
, googleDevtoolsRemotebuildexecutionAdminV1alphaWorkerPool
, gdravwpWorkerConfig
, gdravwpState
, gdravwpWorkerCount
, gdravwpChannel
, gdravwpName
, gdravwpAutoscale
-- ** BuildBazelRemoteExecutionV2SymlinkNode
, BuildBazelRemoteExecutionV2SymlinkNode
, buildBazelRemoteExecutionV2SymlinkNode
, bbrevsnName
, bbrevsnNodeProperties
, bbrevsnTarget
-- ** GoogleRpcStatusDetailsItem
, GoogleRpcStatusDetailsItem
, googleRpcStatusDetailsItem
, grsdiAddtional
-- ** GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata
, GoogleDevtoolsRemoteworkersV1test2DirectoryMetadata
, googleDevtoolsRemoteworkersV1test2DirectoryMetadata
, gdrvdmPath
, gdrvdmDigest
-- ** BuildBazelRemoteExecutionV2ActionResult
, BuildBazelRemoteExecutionV2ActionResult
, buildBazelRemoteExecutionV2ActionResult
, bbrevarExecutionMetadata
, bbrevarOutputDirectorySymlinks
, bbrevarOutputFileSymlinks
, bbrevarOutputDirectories
, bbrevarOutputSymlinks
, bbrevarOutputFiles
, bbrevarStderrRaw
, bbrevarExitCode
, bbrevarStdoutDigest
, bbrevarStderrDigest
, bbrevarStdoutRaw
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteWorkerPoolRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteWorkerPoolRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaDeleteWorkerPoolRequest
, gdravdwprName
-- ** GoogleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable
, GoogleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable
, googleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable
, gdrvctievValue
, gdrvctievName
-- ** GoogleDevtoolsRemotebuildbotResourceUsageStat
, GoogleDevtoolsRemotebuildbotResourceUsageStat
, googleDevtoolsRemotebuildbotResourceUsageStat
, gdrrusUsed
, gdrrusTotal
-- ** BuildBazelSemverSemVer
, BuildBazelSemverSemVer
, buildBazelSemverSemVer
, bbssvMinor
, bbssvMajor
, bbssvPatch
, bbssvPrerelease
-- ** GoogleDevtoolsRemoteworkersV1test2CommandOverhead
, GoogleDevtoolsRemoteworkersV1test2CommandOverhead
, googleDevtoolsRemoteworkersV1test2CommandOverhead
, gdrvcoOverhead
, gdrvcoDuration
-- ** BuildBazelRemoteExecutionV2LogFile
, BuildBazelRemoteExecutionV2LogFile
, buildBazelRemoteExecutionV2LogFile
, bbrevlfHumanReadable
, bbrevlfDigest
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaAutoscale
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaAutoscale
, googleDevtoolsRemotebuildexecutionAdminV1alphaAutoscale
, gdravaMaxSize
, gdravaMinSize
-- ** GoogleDevtoolsRemotebuildbotResourceUsageIOStats
, GoogleDevtoolsRemotebuildbotResourceUsageIOStats
, googleDevtoolsRemotebuildbotResourceUsageIOStats
, gdrruioWriteBytesCount
, gdrruioReadBytesCount
, gdrruioWriteCount
, gdrruioReadTimeMs
, gdrruioReadCount
, gdrruioWriteTimeMs
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaCreateWorkerPoolRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaCreateWorkerPoolRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaCreateWorkerPoolRequest
, gdravcwprParent
, gdravcwprPoolId
, gdravcwprWorkerPool
-- ** BuildBazelRemoteExecutionV2FindMissingBlobsResponse
, BuildBazelRemoteExecutionV2FindMissingBlobsResponse
, buildBazelRemoteExecutionV2FindMissingBlobsResponse
, bbrevfmbrMissingBlobDigests
-- ** GoogleDevtoolsRemoteworkersV1test2Directory
, GoogleDevtoolsRemoteworkersV1test2Directory
, googleDevtoolsRemoteworkersV1test2Directory
, gdrvdDirectories
, gdrvdFiles
-- ** BuildBazelRemoteExecutionV2ExecutionPolicy
, BuildBazelRemoteExecutionV2ExecutionPolicy
, buildBazelRemoteExecutionV2ExecutionPolicy
, bbrevepPriority
-- ** BuildBazelRemoteExecutionV2ActionCacheUpdateCapabilities
, BuildBazelRemoteExecutionV2ActionCacheUpdateCapabilities
, buildBazelRemoteExecutionV2ActionCacheUpdateCapabilities
, bbrevacucUpdateEnabled
-- ** BuildBazelRemoteExecutionV2CacheCapabilitiesDigestFunctionItem
, BuildBazelRemoteExecutionV2CacheCapabilitiesDigestFunctionItem (..)
-- ** GoogleDevtoolsRemoteworkersV1test2CommandResultMetadataItem
, GoogleDevtoolsRemoteworkersV1test2CommandResultMetadataItem
, googleDevtoolsRemoteworkersV1test2CommandResultMetadataItem
, gdrvcrmiAddtional
-- ** BuildBazelRemoteExecutionV2BatchUpdateBlobsRequestRequest
, BuildBazelRemoteExecutionV2BatchUpdateBlobsRequestRequest
, buildBazelRemoteExecutionV2BatchUpdateBlobsRequestRequest
, bbrevbubrrData
, bbrevbubrrDigest
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsResponse
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsResponse
, googleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsResponse
, gdravlwprWorkerPools
-- ** GoogleDevtoolsRemoteworkersV1test2CommandResult
, GoogleDevtoolsRemoteworkersV1test2CommandResult
, googleDevtoolsRemoteworkersV1test2CommandResult
, gdrvcrStatus
, gdrvcrOverhead
, gdrvcrOutputs
, gdrvcrExitCode
, gdrvcrMetadata
, gdrvcrDuration
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyFeature
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyFeature
, googleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyFeature
, gdravfpfPolicy
, gdravfpfAllowedValues
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig
, googleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig
, gdravacAcceleratorCount
, gdravacAcceleratorType
-- ** GoogleDevtoolsRemoteworkersV1test2AdminTemp
, GoogleDevtoolsRemoteworkersV1test2AdminTemp
, googleDevtoolsRemoteworkersV1test2AdminTemp
, gdrvatCommand
, gdrvatArg
-- ** GoogleDevtoolsRemotebuildbotCommandEventsOutputLocation
, GoogleDevtoolsRemotebuildbotCommandEventsOutputLocation (..)
-- ** GoogleDevtoolsRemotebuildbotCommandDurations
, GoogleDevtoolsRemotebuildbotCommandDurations
, googleDevtoolsRemotebuildbotCommandDurations
, gdrcdStdout
, gdrcdCasRelease
, gdrcdDockerPrep
, gdrcdDockerPrepStartTime
, gdrcdExecStartTime
, gdrcdDownload
, gdrcdOverall
, gdrcdExecution
, gdrcdIsoPrepDone
, gdrcdCmWaitForAssignment
, gdrcdUpload
, gdrcdUploadStartTime
, gdrcdDownloadStartTime
-- ** BuildBazelRemoteExecutionV2PlatformProperty
, BuildBazelRemoteExecutionV2PlatformProperty
, buildBazelRemoteExecutionV2PlatformProperty
, bbrevppValue
, bbrevppName
-- ** BuildBazelRemoteExecutionV2WaitExecutionRequest
, BuildBazelRemoteExecutionV2WaitExecutionRequest
, buildBazelRemoteExecutionV2WaitExecutionRequest
-- ** GoogleDevtoolsRemoteworkersV1test2CommandOutputs
, GoogleDevtoolsRemoteworkersV1test2CommandOutputs
, googleDevtoolsRemoteworkersV1test2CommandOutputs
, gdrvcoOutputs
, gdrvcoExitCode
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerPoolState
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerPoolState (..)
-- ** BuildBazelRemoteExecutionV2ExecutedActionMetadata
, BuildBazelRemoteExecutionV2ExecutedActionMetadata
, buildBazelRemoteExecutionV2ExecutedActionMetadata
, bbreveamOutputUploadCompletedTimestamp
, bbreveamAuxiliaryMetadata
, bbreveamOutputUploadStartTimestamp
, bbreveamWorkerCompletedTimestamp
, bbreveamWorkerStartTimestamp
, bbreveamExecutionStartTimestamp
, bbreveamInputFetchStartTimestamp
, bbreveamQueuedTimestamp
, bbreveamWorker
, bbreveamExecutionCompletedTimestamp
, bbreveamInputFetchCompletedTimestamp
-- ** GoogleDevtoolsRemoteworkersV1test2Blob
, GoogleDevtoolsRemoteworkersV1test2Blob
, googleDevtoolsRemoteworkersV1test2Blob
, gdrvbContents
, gdrvbDigest
-- ** BuildBazelRemoteExecutionV2FindMissingBlobsRequest
, BuildBazelRemoteExecutionV2FindMissingBlobsRequest
, buildBazelRemoteExecutionV2FindMissingBlobsRequest
, bbrevfmbrBlobDigests
-- ** BuildBazelRemoteExecutionV2GetTreeResponse
, BuildBazelRemoteExecutionV2GetTreeResponse
, buildBazelRemoteExecutionV2GetTreeResponse
, bbrevgtrDirectories
, bbrevgtrNextPageToken
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaGetInstanceRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaGetInstanceRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaGetInstanceRequest
, gdravgirName
-- ** BuildBazelRemoteExecutionV2ResultsCachePolicy
, BuildBazelRemoteExecutionV2ResultsCachePolicy
, buildBazelRemoteExecutionV2ResultsCachePolicy
, bbrevrcpPriority
-- ** BuildBazelRemoteExecutionV2BatchReadBlobsResponseResponse
, BuildBazelRemoteExecutionV2BatchReadBlobsResponseResponse
, buildBazelRemoteExecutionV2BatchReadBlobsResponseResponse
, bbrevbrbrrStatus
, bbrevbrbrrData
, bbrevbrbrrDigest
-- ** Xgafv
, Xgafv (..)
-- ** BuildBazelRemoteExecutionV2ExecuteRequest
, BuildBazelRemoteExecutionV2ExecuteRequest
, buildBazelRemoteExecutionV2ExecuteRequest
, bbreverExecutionPolicy
, bbreverSkipCacheLookup
, bbreverResultsCachePolicy
, bbreverActionDigest
-- ** BuildBazelRemoteExecutionV2BatchUpdateBlobsResponse
, BuildBazelRemoteExecutionV2BatchUpdateBlobsResponse
, buildBazelRemoteExecutionV2BatchUpdateBlobsResponse
, bbrevbubrResponses
-- ** BuildBazelRemoteExecutionV2ExecuteResponseServerLogs
, BuildBazelRemoteExecutionV2ExecuteResponseServerLogs
, buildBazelRemoteExecutionV2ExecuteResponseServerLogs
, bbreverslAddtional
-- ** BuildBazelRemoteExecutionV2ExecutionCapabilitiesDigestFunction
, BuildBazelRemoteExecutionV2ExecutionCapabilitiesDigestFunction (..)
-- ** GoogleLongrunningOperationResponse
, GoogleLongrunningOperationResponse
, googleLongrunningOperationResponse
, glorAddtional
-- ** BuildBazelRemoteExecutionV2FileNode
, BuildBazelRemoteExecutionV2FileNode
, buildBazelRemoteExecutionV2FileNode
, bbrevfnName
, bbrevfnIsExecutable
, bbrevfnDigest
, bbrevfnNodeProperties
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesResponse
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesResponse
, googleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesResponse
, gdravlirInstances
-- ** GoogleDevtoolsRemoteworkersV1test2CommandTask
, GoogleDevtoolsRemoteworkersV1test2CommandTask
, googleDevtoolsRemoteworkersV1test2CommandTask
, gdrvctInputs
, gdrvctExpectedOutputs
, gdrvctTimeouts
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicy
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicy
, googleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicy
, gdravfpDockerSiblingContainers
, gdravfpDockerNetwork
, gdravfpContainerImageSources
, gdravfpDockerRunAsRoot
, gdravfpDockerChrootPath
, gdravfpDockerPrivileged
, gdravfpLinuxIsolation
, gdravfpDockerRuntime
, gdravfpDockerAddCapabilities
-- ** GoogleDevtoolsRemotebuildbotCommandEventsCmUsage
, GoogleDevtoolsRemotebuildbotCommandEventsCmUsage (..)
-- ** GoogleDevtoolsRemotebuildbotCommandStatus
, GoogleDevtoolsRemotebuildbotCommandStatus
, googleDevtoolsRemotebuildbotCommandStatus
, gdrcsCode
, gdrcsMessage
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig
, googleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig
, gdravwcDiskSizeGb
, gdravwcSoleTenantNodeType
, gdravwcReserved
, gdravwcVMImage
, gdravwcAccelerator
, gdravwcMaxConcurrentActions
, gdravwcNetworkAccess
, gdravwcMachineType
, gdravwcDiskType
, gdravwcLabels
, gdravwcMinCPUPlatform
-- ** BuildBazelRemoteExecutionV2ExecuteResponse
, BuildBazelRemoteExecutionV2ExecuteResponse
, buildBazelRemoteExecutionV2ExecuteResponse
, bbreverStatus
, bbreverServerLogs
, bbreverResult
, bbreverCachedResult
, bbreverMessage
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaUpdateInstanceRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaUpdateInstanceRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaUpdateInstanceRequest
, gdravuirUpdateMask
, gdravuirName
, gdravuirLoggingEnabled
, gdravuirInstance
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest
, gdravdirName
-- ** BuildBazelRemoteExecutionV2CacheCapabilitiesSymlinkAbsolutePathStrategy
, BuildBazelRemoteExecutionV2CacheCapabilitiesSymlinkAbsolutePathStrategy (..)
-- ** GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs
, GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs
, googleDevtoolsRemoteworkersV1test2CommandTaskInputs
, gdrvctiWorkingDirectory
, gdrvctiArguments
, gdrvctiFiles
, gdrvctiEnvironmentVariables
, gdrvctiInlineBlobs
-- ** BuildBazelRemoteExecutionV2CommandEnvironmentVariable
, BuildBazelRemoteExecutionV2CommandEnvironmentVariable
, buildBazelRemoteExecutionV2CommandEnvironmentVariable
, bbrevcevValue
, bbrevcevName
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaListInstancesRequest
, gdravlirParent
-- ** BuildBazelRemoteExecutionV2PriorityCapabilities
, BuildBazelRemoteExecutionV2PriorityCapabilities
, buildBazelRemoteExecutionV2PriorityCapabilities
, bbrevpcPriorities
-- ** BuildBazelRemoteExecutionV2BatchUpdateBlobsRequest
, BuildBazelRemoteExecutionV2BatchUpdateBlobsRequest
, buildBazelRemoteExecutionV2BatchUpdateBlobsRequest
, bbrevbubrRequests
-- ** BuildBazelRemoteExecutionV2RequestMetadata
, BuildBazelRemoteExecutionV2RequestMetadata
, buildBazelRemoteExecutionV2RequestMetadata
, bbrevrmTargetId
, bbrevrmCorrelatedInvocationsId
, bbrevrmConfigurationId
, bbrevrmToolInvocationId
, bbrevrmActionId
, bbrevrmActionMnemonic
, bbrevrmToolDetails
-- ** BuildBazelRemoteExecutionV2Platform
, BuildBazelRemoteExecutionV2Platform
, buildBazelRemoteExecutionV2Platform
, bbrevpProperties
-- ** GoogleDevtoolsRemoteworkersV1test2AdminTempCommand
, GoogleDevtoolsRemoteworkersV1test2AdminTempCommand (..)
-- ** BuildBazelRemoteExecutionV2ExecuteOperationMetadata
, BuildBazelRemoteExecutionV2ExecuteOperationMetadata
, buildBazelRemoteExecutionV2ExecuteOperationMetadata
, bbreveomStage
, bbreveomStderrStreamName
, bbreveomStdoutStreamName
, bbreveomActionDigest
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsRequest
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsRequest
, googleDevtoolsRemotebuildexecutionAdminV1alphaListWorkerPoolsRequest
, gdravlwprParent
, gdravlwprFilter
-- ** BuildBazelRemoteExecutionV2Command
, BuildBazelRemoteExecutionV2Command
, buildBazelRemoteExecutionV2Command
, bbrevcPlatform
, bbrevcOutputDirectories
, bbrevcWorkingDirectory
, bbrevcArguments
, bbrevcOutputPaths
, bbrevcOutputFiles
, bbrevcEnvironmentVariables
, bbrevcOutputNodeProperties
-- ** BuildBazelRemoteExecutionV2NodeProperty
, BuildBazelRemoteExecutionV2NodeProperty
, buildBazelRemoteExecutionV2NodeProperty
, bbrevnpValue
, bbrevnpName
-- ** BuildBazelRemoteExecutionV2CacheCapabilitiesSupportedCompressorItem
, BuildBazelRemoteExecutionV2CacheCapabilitiesSupportedCompressorItem (..)
-- ** BuildBazelRemoteExecutionV2ToolDetails
, BuildBazelRemoteExecutionV2ToolDetails
, buildBazelRemoteExecutionV2ToolDetails
, bbrevtdToolName
, bbrevtdToolVersion
-- ** BuildBazelRemoteExecutionV2ExecutedActionMetadataAuxiliaryMetadataItem
, BuildBazelRemoteExecutionV2ExecutedActionMetadataAuxiliaryMetadataItem
, buildBazelRemoteExecutionV2ExecutedActionMetadataAuxiliaryMetadataItem
, bbreveamamiAddtional
-- ** BuildBazelRemoteExecutionV2CacheCapabilities
, BuildBazelRemoteExecutionV2CacheCapabilities
, buildBazelRemoteExecutionV2CacheCapabilities
, bbrevccSymlinkAbsolutePathStrategy
, bbrevccMaxBatchTotalSizeBytes
, bbrevccDigestFunction
, bbrevccSupportedCompressor
, bbrevccActionCacheUpdateCapabilities
, bbrevccCachePriorityCapabilities
-- ** GoogleDevtoolsRemotebuildbotCommandEvents
, GoogleDevtoolsRemotebuildbotCommandEvents
, googleDevtoolsRemotebuildbotCommandEvents
, gdrceDockerImageName
, gdrceDockerCacheHit
, gdrceNumErrors
, gdrceInputCacheMiss
, gdrceNumWarnings
, gdrceOutputLocation
, gdrceCmUsage
, gdrceUsedAsyncContainer
-- ** GoogleDevtoolsRemoteworkersV1test2CommandTaskOutputs
, GoogleDevtoolsRemoteworkersV1test2CommandTaskOutputs
, googleDevtoolsRemoteworkersV1test2CommandTaskOutputs
, gdrvctoDirectories
, gdrvctoStderrDestination
, gdrvctoFiles
, gdrvctoStdoutDestination
-- ** GoogleLongrunningOperation
, GoogleLongrunningOperation
, googleLongrunningOperation
, gloDone
, gloError
, gloResponse
, gloName
, gloMetadata
-- ** GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyFeaturePolicy
, GoogleDevtoolsRemotebuildexecutionAdminV1alphaFeaturePolicyFeaturePolicy (..)
-- ** BuildBazelRemoteExecutionV2BatchUpdateBlobsResponseResponse
, BuildBazelRemoteExecutionV2BatchUpdateBlobsResponseResponse
, buildBazelRemoteExecutionV2BatchUpdateBlobsResponseResponse
, bStatus
, bDigest
-- ** BuildBazelRemoteExecutionV2BatchReadBlobsResponse
, BuildBazelRemoteExecutionV2BatchReadBlobsResponse
, buildBazelRemoteExecutionV2BatchReadBlobsResponse
, bbrevbrbrResponses
-- ** GoogleDevtoolsRemotebuildbotResourceUsage
, GoogleDevtoolsRemotebuildbotResourceUsage
, googleDevtoolsRemotebuildbotResourceUsage
, gdrruMemoryUsage
, gdrruDiskUsage
, gdrruCPUUsedPercent
, gdrruTotalDiskIoStats
) where
import Network.Google.Prelude
import Network.Google.RemoteBuildExecution.Types
import Network.Google.Resource.RemoteBuildExecution.ActionResults.Get
import Network.Google.Resource.RemoteBuildExecution.ActionResults.Update
import Network.Google.Resource.RemoteBuildExecution.Actions.Execute
import Network.Google.Resource.RemoteBuildExecution.Blobs.BatchRead
import Network.Google.Resource.RemoteBuildExecution.Blobs.BatchUpdate
import Network.Google.Resource.RemoteBuildExecution.Blobs.FindMissing
import Network.Google.Resource.RemoteBuildExecution.Blobs.GetTree
import Network.Google.Resource.RemoteBuildExecution.GetCapabilities
import Network.Google.Resource.RemoteBuildExecution.Operations.WaitExecution
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Remote Build Execution API service.
type RemoteBuildExecutionAPI =
ActionsExecuteResource :<|> BlobsGetTreeResource :<|>
BlobsBatchUpdateResource
:<|> BlobsBatchReadResource
:<|> BlobsFindMissingResource
:<|> GetCapabilitiesResource
:<|> ActionResultsGetResource
:<|> ActionResultsUpdateResource
:<|> OperationsWaitExecutionResource
| brendanhay/gogol | gogol-remotebuildexecution/gen/Network/Google/RemoteBuildExecution.hs | mpl-2.0 | 27,892 | 0 | 12 | 4,206 | 1,884 | 1,322 | 562 | 523 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Analytics.Management.AccountSummaries.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists account summaries (lightweight tree comprised of
-- accounts\/properties\/profiles) to which the user has access.
--
-- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.accountSummaries.list@.
module Network.Google.Resource.Analytics.Management.AccountSummaries.List
(
-- * REST Resource
ManagementAccountSummariesListResource
-- * Creating a Request
, managementAccountSummariesList
, ManagementAccountSummariesList
-- * Request Lenses
, maslStartIndex
, maslMaxResults
) where
import Network.Google.Analytics.Types
import Network.Google.Prelude
-- | A resource alias for @analytics.management.accountSummaries.list@ method which the
-- 'ManagementAccountSummariesList' request conforms to.
type ManagementAccountSummariesListResource =
"analytics" :>
"v3" :>
"management" :>
"accountSummaries" :>
QueryParam "start-index" (Textual Int32) :>
QueryParam "max-results" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] AccountSummaries
-- | Lists account summaries (lightweight tree comprised of
-- accounts\/properties\/profiles) to which the user has access.
--
-- /See:/ 'managementAccountSummariesList' smart constructor.
data ManagementAccountSummariesList = ManagementAccountSummariesList'
{ _maslStartIndex :: !(Maybe (Textual Int32))
, _maslMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ManagementAccountSummariesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'maslStartIndex'
--
-- * 'maslMaxResults'
managementAccountSummariesList
:: ManagementAccountSummariesList
managementAccountSummariesList =
ManagementAccountSummariesList'
{ _maslStartIndex = Nothing
, _maslMaxResults = Nothing
}
-- | An index of the first entity to retrieve. Use this parameter as a
-- pagination mechanism along with the max-results parameter.
maslStartIndex :: Lens' ManagementAccountSummariesList (Maybe Int32)
maslStartIndex
= lens _maslStartIndex
(\ s a -> s{_maslStartIndex = a})
. mapping _Coerce
-- | The maximum number of account summaries to include in this response,
-- where the largest acceptable value is 1000.
maslMaxResults :: Lens' ManagementAccountSummariesList (Maybe Int32)
maslMaxResults
= lens _maslMaxResults
(\ s a -> s{_maslMaxResults = a})
. mapping _Coerce
instance GoogleRequest ManagementAccountSummariesList
where
type Rs ManagementAccountSummariesList =
AccountSummaries
type Scopes ManagementAccountSummariesList =
'["https://www.googleapis.com/auth/analytics.edit",
"https://www.googleapis.com/auth/analytics.readonly"]
requestClient ManagementAccountSummariesList'{..}
= go _maslStartIndex _maslMaxResults (Just AltJSON)
analyticsService
where go
= buildClient
(Proxy ::
Proxy ManagementAccountSummariesListResource)
mempty
| rueshyna/gogol | gogol-analytics/gen/Network/Google/Resource/Analytics/Management/AccountSummaries/List.hs | mpl-2.0 | 4,082 | 0 | 14 | 875 | 436 | 258 | 178 | 68 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Common.Database (userDatabaseName)
import Common.Onedrive (getOnedriveClientSecret)
import Common.OnedriveInfo (onedriveInfoId, defaultOnedriveInfo, token, refreshToken)
import Common.ServerEnvironmentInfo (ServerEnvironmentInfo(..), getServerEnvironment)
import Control.Concurrent (forkIO)
import Control.Lens ((^.), set)
import Control.Monad (when, void)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Except (runExceptT)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (runMaybeT, MaybeT(MaybeT))
import CouchDB.Requests (getObject, putObject)
import CouchDB.Types.Auth (Auth(NoAuth, BasicAuth))
import Data.ByteString.Char8 (ByteString, pack)
import Data.Maybe (fromJust, fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T (Text, concat, empty)
import qualified Data.Text.Encoding as T (decodeUtf8)
import qualified Data.Text.Lazy as TL
import Network.HTTP.Types.Status (unauthorized401)
import Network.Wai (queryString)
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Network.Wai.Middleware.Static (staticPolicy, addBase)
import Onedrive.Auth (requestToken)
import Onedrive.Items (content)
import Onedrive.Session (newSessionWithToken)
import Onedrive.Types.OauthTokenRequest (OauthTokenRequest(OauthTokenRequest))
import qualified Onedrive.Types.OauthTokenResponse as Resp (OauthTokenResponse, refreshToken, accessToken)
import Onedrive.Types.UserInfo (id_)
import Onedrive.User (me)
import System.Directory (getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath ((</>))
import qualified Text.Blaze.Html.Renderer.Text as H (renderHtml)
import qualified Text.Blaze.Html5 as H (Html,
textComment,
docTypeHtml,
head,
meta,
title,
(!),
body,
p,
text,
strong,
a,
script,
div,
toValue)
import qualified Text.Blaze.Html5.Attributes as HA
import Web.Routing.Combinators (wildcard)
import Web.Spock.Core (runSpock,
spockT,
get,
middleware,
redirect,
html,
request,
setCookie,
cookie,
defaultCookieSettings,
json,
hookAny,
setHeader,
setStatus,
bytes,
var,
(<//>),
StdMethod(GET))
import Web.ViewEpub (loadEpubItem, itemBytes, contentType, firstPagePath)
main :: IO ()
main = do
port <- getPort
onedriveClientSecret <- getOnedriveClientSecret
serverEnvironment <- getServerEnvironment
runSpock port $ spockT id $ do
middleware logStdoutDev
currentDirectory <- liftIO getCurrentDirectory
middleware $ staticPolicy (addBase (currentDirectory </> "public"))
get "onedrive-redirect" $ do
qs <- queryString <$> request
let c = pa "code" qs
let req =
OauthTokenRequest (_onedriveClientId serverEnvironment) (_appBaseUrl serverEnvironment <> "/onedrive-redirect") onedriveClientSecret
resp <- lift $ requestToken req $ T.decodeUtf8 $ fromJust c
void $ liftIO $ forkIO $ updateOnedriveInfoSync (_couchdbServer serverEnvironment) resp
setCookie "onedriveToken" (resp ^. Resp.accessToken) defaultCookieSettings
redirect "/"
get "server-environment" $
json serverEnvironment
get ("view-epub" <//> var <//> wildcard) $ \itemId path -> do
liftIO $ print itemId
liftIO $ print path
mbAccessToken <- cookie "onedriveToken"
case mbAccessToken of
Nothing ->
setStatus unauthorized401
Just accessToken -> do
session <- liftIO $ newSessionWithToken accessToken
bs <- liftIO $ content session itemId
if path == T.empty
then do
result <- liftIO $ runExceptT $ firstPagePath bs
case result of
Right indexPath ->
redirect $ "/view-epub/" <> itemId <> "/" <> indexPath
Left err ->
fail $ "Error getting EPUB index item: " ++ err
else do
result <- liftIO $ runExceptT $ loadEpubItem bs path
case result of
Right res -> do
setHeader "Content-Type" $ res ^. contentType
bytes $ res ^. itemBytes
Left err ->
fail $ "Error getting EPUB item: " ++ err
hookAny GET $ \_ ->
html $ renderHtml appPage
where
pa _ [] = Nothing
pa par ((p, v) : qs)
| p == par = v
| otherwise = pa par qs
renderHtml :: H.Html -> T.Text
renderHtml =
TL.toStrict . H.renderHtml
appPage :: H.Html
appPage =
withMaster "/app.bundle.js" $ H.div H.! HA.class_ "application container" $ ""
withMaster :: T.Text -> H.Html -> H.Html
withMaster mainScript childrenMarkup = H.docTypeHtml $ do
H.head $ do
H.meta H.! HA.charset "UTF-8"
H.title "My Books"
H.body $ do
ie10comment $ H.p H.! HA.class_ "browserupgrade" $ do
H.text "You are using an "
H.strong "outdated"
H.text " browser. Please "
H.a H.! HA.href "http://browserhappy.com/" $ "upgrade your browser"
H.text " to improve your experience."
childrenMarkup
H.script H.! HA.src (H.toValue mainScript) $ ""
ie10comment :: H.Html -> H.Html
ie10comment htmlContent = H.textComment $ T.concat ["[if lt IE 10]>", renderedContent, "<![endif]"]
where renderedContent = renderHtml htmlContent
getPort :: IO Int
getPort =
maybe 8000 read <$> lookupEnv "PORT"
updateOnedriveInfoSync :: T.Text -> Resp.OauthTokenResponse -> IO ()
updateOnedriveInfoSync couchdbUrl resp = do
let
tok = resp ^. Resp.accessToken
session <- newSessionWithToken tok
user <- me session
updateOnedriveInfoIfNeeded couchdbUrl (user ^. id_) resp
updateOnedriveInfoIfNeeded :: (MonadThrow m, MonadIO m) => T.Text -> T.Text -> Resp.OauthTokenResponse -> m ()
updateOnedriveInfoIfNeeded couchdbUrl userId tokenResp = do
auth <- getAuth
let
databaseId = userDatabaseName userId
newToken = tokenResp ^. Resp.accessToken
newRefreshToken = tokenResp ^. Resp.refreshToken
currentInfo <- fromMaybe defaultOnedriveInfo <$> getObject couchdbUrl databaseId auth onedriveInfoId
when ((currentInfo ^. token) /= newToken || (currentInfo ^. Common.OnedriveInfo.refreshToken) /= newRefreshToken) $ do
let
newInfo = set Common.OnedriveInfo.refreshToken newRefreshToken $ set token newToken currentInfo
putObject couchdbUrl databaseId auth onedriveInfoId newInfo
getAuth :: MonadIO m => m Auth
getAuth =
maybe NoAuth auth <$> tryGetAdminAuth
where
auth (username, password) =
BasicAuth username password
tryGetAdminAuth :: MonadIO m => m (Maybe (ByteString, ByteString))
tryGetAdminAuth = runMaybeT $ do
username <- MaybeT $ liftIO $ lookupEnv "COUCHDB_ADMIN_USERNAME"
password <- MaybeT $ liftIO $ lookupEnv "COUCHDB_ADMIN_PASSWORD"
return (pack username, pack password)
| asvyazin/my-books.purs | server/my-books/Web/Main.hs | mpl-2.0 | 8,427 | 0 | 29 | 2,929 | 1,991 | 1,055 | 936 | 181 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module View.VolumeAccess
( volumeAccessTitle
, volumeAccessPresetTitle
-- , htmlVolumeAccessForm
) where
import qualified Data.ByteString.Char8 as BSC
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Store.Config as C
import Service.Messages
-- import Action
-- import Model.Party
import Model.Permission
-- import Model.Volume
-- import Model.VolumeAccess
-- import Controller.Paths
-- import View.Form
-- import {-# SOURCE #-} Controller.VolumeAccess
volumeAccessTitle :: Permission -> Messages -> T.Text
volumeAccessTitle perm = getMessage $ C.Path ["access", "edit", BSC.pack (show perm), "title"]
volumeAccessPresetTitle :: Bool -> Messages -> T.Text
volumeAccessPresetTitle shared = getMessage $ C.Path ["access", "preset", "title" <> BSC.pack (show (fromEnum shared))]
{-
htmlVolumeAccessForm :: VolumeAccess -> RequestContext -> FormHtml f
htmlVolumeAccessForm a@VolumeAccess{ volumeAccessVolume = vol, volumeAccessParty = p } = htmlForm
("Access to " <> volumeName (volumeRow vol) <> " for " <> partyName (partyRow p))
postVolumeAccess (HTML, (volumeId $ volumeRow vol, VolumeAccessTarget $ partyId $ partyRow p))
(do
field "individual" $ inputEnum True $ Just $ volumeAccessIndividual a
field "children" $ inputEnum True $ Just $ volumeAccessChildren a
field "delete" $ inputCheckbox False)
(const mempty)
-}
| databrary/databrary | src/View/VolumeAccess.hs | agpl-3.0 | 1,414 | 0 | 13 | 211 | 188 | 113 | 75 | 14 | 1 |
-- ch 3.8, Building Functions, exercise 5
module ReturnThird where
main :: IO()
main = do
putStrLn rvrs
rvrs :: String
rvrs =
let
string = "Curry is awesome"
in
drop 9 string ++ drop 5 (take 9 string ) ++ take 5 string
| thewoolleyman/haskellbook | 03/08/chad/Rvrs.hs | unlicense | 235 | 0 | 11 | 60 | 78 | 39 | 39 | 9 | 1 |
module AlecSequences.A280172Spec (main, spec) where
import Test.Hspec
import AlecSequences.A280172 (a280172)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A280172" $
it "correctly computes the first 20 elements" $
take 20 (map a280172 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,2,3,1,3,4,4,4,4,5,3,1,3,5,6,6,2,2,6]
| peterokagey/haskellOEIS | test/AlecSequences/A280172Spec.hs | apache-2.0 | 361 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{- |
Module : Data.Time.Zones.Internal
Copyright : (C) 2014 Mihaly Barasz
License : Apache-2.0, see LICENSE
Maintainer : Mihaly Barasz <[email protected]>
Stability : experimental
-}
{-# LANGUAGE CPP #-}
#ifdef TZ_TH
{-# LANGUAGE TemplateHaskell #-}
#endif
module Data.Time.Zones.Internal (
-- * Time conversion to/from @Int64@
utcTimeToInt64,
utcTimeToInt64Pair,
localTimeToInt64Pair,
int64PairToUTCTime,
int64PairToLocalTime,
-- * Low-level \"coercions\"
picoToInteger,
integerToPico,
diffTimeToPico,
picoToDiffTime,
diffTimeToInteger,
integerToDiffTime,
) where
import Data.Fixed
import Data.Int
import Data.Time
#ifdef TZ_TH
import Data.Time.Zones.Internal.CoerceTH
#else
import Unsafe.Coerce
#endif
utcTimeToInt64Pair :: UTCTime -> (Int64, Int64)
utcTimeToInt64Pair (UTCTime (ModifiedJulianDay d) t)
= (86400 * (fromIntegral d - unixEpochDay) + s, ps)
where
(s, ps) = fromIntegral (diffTimeToInteger t) `divMod` 1000000000000
unixEpochDay = 40587
{-# INLINE utcTimeToInt64Pair #-}
int64PairToLocalTime :: Int64 -> Int64 -> LocalTime
int64PairToLocalTime t ps = LocalTime (ModifiedJulianDay day) (TimeOfDay h m s)
where
(day64, tid64) = t `divMod` 86400
day = fromIntegral $ day64 + 40587
(h, ms) = fromIntegral tid64 `quotRem` 3600
(m, s0) = ms `quotRem` 60
s = integerToPico $ fromIntegral $ ps + 1000000000000 * fromIntegral s0
{-# INLINE int64PairToLocalTime #-}
localTimeToInt64Pair :: LocalTime -> (Int64, Int64)
localTimeToInt64Pair (LocalTime (ModifiedJulianDay day) (TimeOfDay h m s))
= (86400 * (fromIntegral day - unixEpochDay) + tid, ps)
where
(s64, ps) = fromIntegral (picoToInteger s) `divMod` 1000000000000
tid = s64 + fromIntegral (h * 3600 + m * 60)
unixEpochDay = 40587
{-# INLINE localTimeToInt64Pair #-}
int64PairToUTCTime :: Int64 -> Int64 -> UTCTime
int64PairToUTCTime t ps = UTCTime (ModifiedJulianDay day) tid
where
(day64, tid64) = t `divMod` 86400
day = fromIntegral $ day64 + 40587
tid = integerToDiffTime $ fromIntegral $ ps + tid64 * 1000000000000
{-# INLINE int64PairToUTCTime #-}
utcTimeToInt64 :: UTCTime -> Int64
utcTimeToInt64 (UTCTime (ModifiedJulianDay d) t)
= 86400 * (fromIntegral d - unixEpochDay)
+ fromIntegral (diffTimeToInteger t) `div` 1000000000000
where
unixEpochDay = 40587
{-# INLINE utcTimeToInt64 #-}
--------------------------------------------------------------------------------
-- Low-level zero-overhead conversions.
-- Basically we could have used 'coerce' if the constructors were exported.
-- TODO(klao): Is it better to inline them saturated or unsaturated?
#ifdef TZ_TH
picoToInteger :: Pico -> Integer
picoToInteger p = $(destructNewType ''Fixed) p
{-# INLINE picoToInteger #-}
integerToPico :: Integer -> Pico
integerToPico i = $(constructNewType ''Fixed) i
{-# INLINE integerToPico #-}
diffTimeToPico :: DiffTime -> Pico
diffTimeToPico dt = $(destructNewType ''DiffTime) dt
{-# INLINE diffTimeToPico #-}
picoToDiffTime :: Pico -> DiffTime
picoToDiffTime p = $(constructNewType ''DiffTime) p
{-# INLINE picoToDiffTime #-}
diffTimeToInteger :: DiffTime -> Integer
diffTimeToInteger dt = picoToInteger (diffTimeToPico dt)
{-# INLINE diffTimeToInteger #-}
integerToDiffTime :: Integer -> DiffTime
integerToDiffTime i = picoToDiffTime (integerToPico i)
{-# INLINE integerToDiffTime #-}
#else
picoToInteger :: Pico -> Integer
picoToInteger = unsafeCoerce
{-# INLINE picoToInteger #-}
integerToPico :: Integer -> Pico
integerToPico = unsafeCoerce
{-# INLINE integerToPico #-}
diffTimeToPico :: DiffTime -> Pico
diffTimeToPico = unsafeCoerce
{-# INLINE diffTimeToPico #-}
picoToDiffTime :: Pico -> DiffTime
picoToDiffTime = unsafeCoerce
{-# INLINE picoToDiffTime #-}
diffTimeToInteger :: DiffTime -> Integer
diffTimeToInteger = unsafeCoerce
{-# INLINE diffTimeToInteger #-}
integerToDiffTime :: Integer -> DiffTime
integerToDiffTime = unsafeCoerce
{-# INLINE integerToDiffTime #-}
#endif
| nilcons/haskell-tz | Data/Time/Zones/Internal.hs | apache-2.0 | 3,989 | 0 | 12 | 638 | 789 | 438 | 351 | 68 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Spark.Core.Internal.DatasetStructures where
import Data.Vector(Vector)
import qualified Data.Vector as V
import qualified Data.Text as T
import Spark.Core.StructuresInternal
import Spark.Core.Try
import Spark.Core.Row
import Spark.Core.Internal.OpStructures
import Spark.Core.Internal.TypesStructures
{-| (internal) The main data structure that represents a data node in the
computation graph.
This data structure forms the backbone of computation graphs expressed
with spark operations.
loc is a typed locality tag.
a is the type of the data, as seen by the Haskell compiler. If erased, it
will be a Cell type.
-}
-- TODO: separate the topology info from the node info. It will help when
-- building the graphs.
data ComputeNode loc a = ComputeNode {
-- | The id of the node.
--
-- Non strict because it may be expensive.
_cnNodeId :: NodeId,
-- The following fields are used to build a unique ID to
-- a compute node:
-- | The operation associated to this node.
_cnOp :: !NodeOp,
-- | The type of the node
_cnType :: !DataType,
-- | The direct parents of the node. The order of the parents is important
-- for the semantics of the operation.
_cnParents :: !(Vector UntypedNode),
-- | A set of extra dependencies that can be added to force an order between
-- the nodes.
--
-- The order is not important, they are sorted by ID.
--
-- TODO(kps) add this one to the id
_cnLogicalDeps :: !(Vector UntypedNode),
-- | The locality of this node.
--
-- TODO(kps) add this one to the id
_cnLocality :: !Locality,
-- Attributes that are not included in the id
-- These attributes are mostly for the user to relate to the nodes.
-- They are not necessary for the computation.
--
-- | The name
_cnName :: !(Maybe NodeName),
-- | A set of nodes considered as the logical input for this node.
-- This has no influence on the calculation of the id and is used
-- for organization purposes only.
_cnLogicalParents :: !(Maybe (Vector UntypedNode)),
-- | The path of this oned in a computation flow.
--
-- This path includes the node name.
-- Not strict because it may be expensive to compute.
-- By default it only contains the name of the node (i.e. the node is
-- attached to the root)
_cnPath :: NodePath
} deriving (Eq)
{-| Converts a compute node to an operator node.
-}
nodeOpNode :: ComputeNode loc a -> OperatorNode
nodeOpNode cn = OperatorNode {
onId = _cnNodeId cn,
onPath = _cnPath cn,
onNodeInfo = CoreNodeInfo {
cniShape = NodeShape {
nsType = _cnType cn,
nsLocality = _cnLocality cn
},
cniOp = _cnOp cn
}
}
nodeContext :: ComputeNode loc a -> NodeContext
nodeContext cn = NodeContext {
ncParents = nodeOpNode <$> V.toList (_cnParents cn),
ncLogicalDeps = nodeOpNode <$> V.toList (_cnLogicalDeps cn)
}
-- (internal) Phantom type tags for the locality
data TypedLocality loc = TypedLocality { unTypedLocality :: !Locality } deriving (Eq, Show)
data LocLocal
data LocDistributed
data LocUnknown
{-| (internal/developer)
The core data structure that represents an operator.
This contains all the information that is required in
the compute graph (except topological info), which is
expected to be stored in the edges.
These nodes are meant to be used after path resolution.
-}
data OperatorNode = OperatorNode {
{-| The ID of the node.
Lazy because it may be expensive to compute.
-- TODO: it should not be here?
-}
onId :: NodeId,
{-| The fully resolved path of the node.
Lazy because it may depend on the ID.
-}
onPath :: NodePath,
{-| The core node information. -}
onNodeInfo :: !CoreNodeInfo
} deriving (Eq)
-- Some helper functions:
onShape :: OperatorNode -> NodeShape
onShape = cniShape . onNodeInfo
onOp :: OperatorNode -> NodeOp
onOp = cniOp . onNodeInfo
onType :: OperatorNode -> DataType
onType = nsType . cniShape . onNodeInfo
onLocality :: OperatorNode -> Locality
onLocality = nsLocality . cniShape . onNodeInfo
{-| A node and some information about the parents of this node.
This information is enough to calculate most information relative
to a node.
This is the local context of the compute DAG.
-}
data NodeContext = NodeContext {
ncParents :: ![OperatorNode],
ncLogicalDeps :: ![OperatorNode]
}
-- (developer) The type for which we drop all the information expressed in
-- types.
--
-- This is useful to express parent dependencies (pending a more type-safe
-- interface)
type UntypedNode = ComputeNode LocUnknown Cell
-- (internal) A dataset for which we have dropped type information.
-- Used internally by columns.
type UntypedDataset = Dataset Cell
{-| (internal) An observable which has no associated type information. -}
type UntypedLocalData = LocalData Cell
{-| A typed collection of distributed data.
Most operations on datasets are type-checked by the Haskell
compiler: the type tag associated to this dataset is guaranteed
to be convertible to a proper Haskell type. In particular, building
a Dataset of dynamic cells is guaranteed to never happen.
If you want to do untyped operations and gain
some flexibility, consider using UDataFrames instead.
Computations with Datasets and observables are generally checked for
correctness using the type system of Haskell.
-}
type Dataset a = ComputeNode LocDistributed a
{-|
A unit of data that can be accessed by the user.
This is a typed unit of data. The type is guaranteed to be a proper
type accessible by the Haskell compiler (instead of simply a Cell
type, which represents types only accessible at runtime).
TODO(kps) rename to Observable
-}
type LocalData a = ComputeNode LocLocal a
type Observable a = LocalData a
{-|
The dataframe type. Any dataset can be converted to a dataframe.
For the Spark users: this is different than the definition of the
dataframe in Spark, which is a dataset of rows. Because the support
for single columns is more akward in the case of rows, it is more
natural to generalize datasets to contain cells.
When communicating with Spark, though, single cells are wrapped
into rows with single field, as Spark does.
-}
type DataFrame = Try UntypedDataset
{-| Observable, whose type can only be infered at runtime and
that can fail to be computed at runtime.
Any observable can be converted to an untyped
observable.
Untyped observables are more flexible and can be combined in
arbitrary manner, but they will fail during the validation of
the Spark computation graph.
TODO(kps) rename to DynObservable
-}
type LocalFrame = Observable'
newtype Observable' = Observable' { unObservable' :: Try UntypedLocalData }
type UntypedNode' = Try UntypedNode
{-| The different paths of edges in the compute DAG of nodes, at the
start of computations.
- scope edges specify the scope of a node for naming. They are not included in
the id.
-}
data NodeEdge = ScopeEdge | DataStructureEdge StructureEdge deriving (Show, Eq)
{-| The edges in a compute DAG, after name resolution (which is where most of
the checks and computations are being done)
- parent edges are the direct parents of a node, the only ones required for
defining computations. They are included in the id.
- logical edges define logical dependencies between nodes to force a specific
ordering of the nodes. They are included in the id.
-}
data StructureEdge = ParentEdge | LogicalEdge deriving (Show, Eq)
class CheckedLocalityCast loc where
_validLocalityValues :: [TypedLocality loc]
-- Class to retrieve the locality associated to a type.
-- Is it better to use type classes?
class (CheckedLocalityCast loc) => IsLocality loc where
_getTypedLocality :: TypedLocality loc
instance CheckedLocalityCast LocLocal where
_validLocalityValues = [TypedLocality Local]
instance CheckedLocalityCast LocDistributed where
_validLocalityValues = [TypedLocality Distributed]
instance Show OperatorNode where
show (OperatorNode _ np _) = "OperatorNode[" ++ T.unpack (prettyNodePath np) ++ "]"
-- LocLocal is a locality associated to Local
instance IsLocality LocLocal where
_getTypedLocality = TypedLocality Local
-- LocDistributed is a locality associated to Distributed
instance IsLocality LocDistributed where
_getTypedLocality = TypedLocality Distributed
instance CheckedLocalityCast LocUnknown where
_validLocalityValues = [TypedLocality Distributed, TypedLocality Local]
| tjhunter/karps | haskell/src/Spark/Core/Internal/DatasetStructures.hs | apache-2.0 | 8,561 | 0 | 13 | 1,591 | 906 | 538 | 368 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.