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
-- generated by HCPN NetEdit v0.0 module Unnamed where import SimpleHCPN import GuiHCPN import List (intersperse) -- declarations -- markings data Mark = Mark { final_bc :: [String] , final_ab_c :: [String] , sab_ :: [String] , sb :: [String] , start :: [String] } deriving Show -- transition actions t5 :: Mark -> [Mark] t5 m = do let sb_marking = sb m let final_bc_marking = final_bc m ('c':input, sb_marking) <- select $ sb_marking if True then return m{ sb = sb_marking , final_bc = (input) : final_bc_marking } else fail "guard failed" t3 :: Mark -> [Mark] t3 m = do let sab__marking = sab_ m let final_ab_c_marking = final_ab_c m ('c':input, sab__marking) <- select $ sab__marking if True then return m{ sab_ = sab__marking , final_ab_c = (input) : final_ab_c_marking } else fail "guard failed" t2 :: Mark -> [Mark] t2 m = do let sab__marking = sab_ m ('b':input, sab__marking) <- select $ sab__marking if True then return m{ sab_ = (input) : sab__marking } else fail "guard failed" t4 :: Mark -> [Mark] t4 m = do let start_marking = start m let sb_marking = sb m ('b':input, start_marking) <- select $ start_marking if True then return m{ start = start_marking , sb = (input) : sb_marking } else fail "guard failed" t1 :: Mark -> [Mark] t1 m = do let start_marking = start m let sab__marking = sab_ m ('a':input, start_marking) <- select $ start_marking if True then return m{ start = start_marking , sab_ = (input) : sab__marking } else fail "guard failed" -- transitions net = Net{trans=[ Trans{name="t5",info=Nothing,action=t5} , Trans{name="t3",info=Nothing,action=t3} , Trans{name="t2",info=Nothing,action=t2} , Trans{name="t4",info=Nothing,action=t4} , Trans{name="t1",info=Nothing,action=t1} ]} -- initial marking mark = Mark{ final_bc = [] , final_ab_c = [] , sab_ = [] , sb = [] , start = ["ac","abbbbbbbbbc","bc","bac","aa"] } -- end of net code main = simMain "fa_regular.hcpn" showMarking net mark showMarking pmap = let (Just nV_final_bc) = lookup "final_bc" pmap (Just nV_final_ab_c) = lookup "final_ab_c" pmap (Just nV_sab_) = lookup "sab_" pmap (Just nV_sb) = lookup "sb" pmap (Just nV_start) = lookup "start" pmap in \setPlaceMark m-> do setPlaceMark nV_final_bc (concat $ intersperse "," $ map show $ final_bc m) setPlaceMark nV_final_ab_c (concat $ intersperse "," $ map show $ final_ab_c m) setPlaceMark nV_sab_ (concat $ intersperse "," $ map show $ sab_ m) setPlaceMark nV_sb (concat $ intersperse "," $ map show $ sb m) setPlaceMark nV_start (concat $ intersperse "," $ map show $ start m)
haroldcarr/learn-haskell-coq-ml-etc
haskell/playpen/hcpn/examples/fa_regular.hs
unlicense
3,341
0
15
1,233
1,047
560
487
86
2
module Tables.A342237 (a342237, a342237T) where import qualified Data.MemoCombinators as Memo import Helpers.Table (tableByAntidiagonals) a342237T :: Integer -> Integer -> Integer a342237T = Memo.memo2 Memo.integral Memo.integral a342237T' where a342237T' n 1 = 0 a342237T' n k | even k = n * a342237T n (k - 1) + n^(k `div` 2) - a342237T n (k `div` 2) | odd k = n * a342237T n (k - 1) + n^(k `div` 2 + 1) - a342237T n (k `div` 2 + 1) a342237 :: Integer -> Integer a342237 n = case tableByAntidiagonals (n - 1) of (n', k') -> a342237T (n' + 1) (k' + 1) -- k = 1 -- ceiling((k+1)/2) = 1 -- k = 2 -- ceiling((k+1)/2) = 2 -- k = 3 -- ceiling((k+1)/2) = 2
peterokagey/haskellOEIS
src/Tables/A342237.hs
apache-2.0
670
0
14
147
284
155
129
11
2
{- Copyright 2010-2012 Cognimeta Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE TemplateHaskell, TypeFamilies, Rank2Types, GADTs, TupleSections, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables, FlexibleContexts #-} module Database.Perdure.RawDevice ( RawStoreFile(..), storeFileWriteWords, storeFileReadWords, LocalStoreFile, withFileStoreFile, withRawDeviceStoreFile, withRawDeviceStoreFiles, module Database.Perdure.StoreFile, narrowBufsLen, storeFileWrite1, storeFileRead1 ) where import Prelude () import Cgm.Prelude import Data.Typeable import qualified Data.ByteString as B import Control.Concurrent import Data.Word import Data.Bool import qualified Data.Map as Map import Cgm.Data.Super import Cgm.Data.Len import Cgm.Data.Monoid import Cgm.Data.NEList import Cgm.Data.Either import Cgm.System.Endian import Cgm.Control.Concurrent.TThread import Cgm.Control.Concurrent.Await import Cgm.System.Mem.Alloc import Database.Perdure.Validator import System.IO import System.Posix.Files import System.Posix.IO import System.Posix.Types import Data.Bits import Control.Monad.Error hiding (sequence_) import Database.Perdure.StoreFile(SyncableStoreFile(..)) import Database.Perdure.LocalStoreFile import Control.Monad.Trans.Except --import System.Posix.Fsync -- not needed with raw devices -- | Opens the specified raw device as a LocalStoreFile, runs the provided function and closes the device. -- Do not make concurrent calls on the same device, place concurrency in the passed function. withRawDeviceStoreFile :: FilePath -> (LocalStoreFile -> IO a) -> ExceptT String IO a withRawDeviceStoreFile path user = ExceptT $ bracket (openFd path ReadWrite Nothing $ defaultFileFlags {exclusive = True, append = True}) closeFd $ \fd -> runExceptT $ do fs <- lift $ getFdStatus fd bool (throwError "Not a raw device") (lift $ withRawFile (RawDevice fd fs 9) user) $ isCharacterDevice fs -- | Like nesting multiple calls to 'withRawDeviceStoreFile'. withRawDeviceStoreFiles :: [FilePath] -> ([LocalStoreFile] -> IO a) -> ExceptT String IO a withRawDeviceStoreFiles ps user = foldr (\p u fs -> (>>= ExceptT . pure) $ withRawDeviceStoreFile p $ \f -> runExceptT $ u $ fs `mappend` [f]) (lift . user) ps [] toFileOffset :: Integral n => Len Word8 n -> FileOffset toFileOffset = fromIntegral . getLen toByteCount :: Integral n => Len Word8 n -> ByteCount toByteCount = fromIntegral . getLen fdSeekLen :: Fd -> ByteAddr -> IO () fdSeekLen fd seek = () <$ fdSeek fd AbsoluteSeek (toFileOffset seek) -- TODO: consider adding support for a 'STPrimArray RealWorld Pinned Block', and a matching address type, that would enfoce the above requirements -- However we would have to cast/view it as an array of Word8 later on. -- | Array's size and start must be aligned on the block size, and the ByteAddr too. fdReadArray :: Fd -> ByteAddr -> ArrayRange (STPrimArray RealWorld Pinned Word8) -> ExceptT String IO () fdReadArray fd start a = ExceptT $ fmap (boolEither "" () . (==) (toByteCount $ arrayLen a)) $ fdSeekLen fd start >> withArrayPtr (\ptr len -> fdReadBuf fd ptr $ toByteCount len) a fdWriteArray :: Fd -> ByteAddr -> ArrayRange (STPrimArray RealWorld Pinned Word8) -> ExceptT String IO () fdWriteArray fd start a = ExceptT $ fmap (boolEither "" () . (==) (toByteCount $ arrayLen a)) $ fdSeekLen fd start >> withArrayPtr (\ptr len -> fdWriteBuf fd ptr $ toByteCount len) a -- A bit of info on raw devices that i did not find easily elsewhere: http://www.win.tue.nl/~aeb/linux/lk/lk-11.html#ss11.4 data RawDevice = RawDevice Fd FileStatus Int rawDeviceBlockBytes :: RawDevice -> Len Word8 Word rawDeviceBlockBytes (RawDevice _ _ lg) = unsafeLen $ 1 `shiftL` lg instance Show RawDevice where show (RawDevice _ fs _) = show $ specialDeviceID fs -- TODO merge consecutive writes to improve performance (avoids many needless reads to preserve data that will be overwritten) instance RawFile RawDevice where fileWriteRaw r@(RawDevice fd _ _) start bufs = let len = up $ sum $ arrayLen <$> bufs in withBlockArray r start len $ ((. fullArrayRange) .) $ \tStart t -> do let bb = rawDeviceBlockBytes r let tLen = arrayLen t let tEnd = tStart + up tLen when (tStart < start) $ fdReadArray fd tStart $ headArrayRange bb t when (start + len < tEnd) $ fdReadArray fd (tEnd - up bb) $ skipArrayRange (tLen - bb) t let dest = skipArrayRange (fromJust $ unapply super $ start - tStart) t _ <- lift $ stToIO $ foldlM (\d b -> skipArrayRange (arrayLen b) d <$ mapMArrayCopyImm return b d) dest bufs fdWriteArray fd tStart t fileReadRaw r@(RawDevice fd _ _) start buf = withBlockArray r start (up $ arrayLen buf) $ ((. fullArrayRange) .) $ \tStart t -> do -- liftIO $ putStrLn $ "Before fdReadArray " ++ show start fdReadArray fd tStart t let rangeToCopy = skipArrayRange (fromJust $ unapply super $ start - tStart) t lift $ stToIO (mapMArrayCopy return rangeToCopy buf) fileFlush _ = return () -- Takes start and length, and passes rounded start and an aligned buffer withBlockArray :: MonadIO m => RawDevice -> ByteAddr -> ByteAddr -> (ByteAddr -> STPrimArray RealWorld Pinned Word8 -> m a) -> m a withBlockArray r@(RawDevice _ _ lgBlockBytes) seek len f = let blockBytes = rawDeviceBlockBytes r seek' = getLen seek len' = getLen len start = (seek' `shiftR` lgBlockBytes) `shiftL` lgBlockBytes end = ((seek' + len' + up (getLen blockBytes) - 1) `shiftR` lgBlockBytes) `shiftL` lgBlockBytes in liftIO (stToIO $ newAlignedPinnedWord8Array blockBytes $ unsafeLen $ fromJust $ unapply super $ end - start) >>= f (unsafeLen start) -- . trace ("withBlockArray blockBytes=" ++ show blockBytes ++ " start=" ++ show (unsafeLen start) ++ " size=" ++ (show $ arrayLen r))
Cognimeta/perdure-file-raw
src/Database/Perdure/RawDevice.hs
apache-2.0
6,476
0
20
1,246
1,622
854
768
93
1
module Scene where data Camera = Camera { } deriving (Show, Eq) data Scene = Scene { camera :: Camera } deriving (Show, Eq)
epeld/zatacka
src/Graphics/Scene.hs
apache-2.0
126
1
8
26
51
30
21
3
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TypeOperators #-} module SAML2.XML ( module SAML2.XML.Types , module SAML2.Core.Datatypes , URI , xpTrimAnyElem , xpTrimElemNS , xpXmlLang , IP, xpIP , Identified(..) , Identifiable(..) , unidentify , xpIdentified , xpIdentifier , IdentifiedURI , samlToDoc , samlToXML , docToSAML , docToXML , xmlToSAML , xmlToDoc ) where import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Lazy.UTF8 as BSLU import Data.Default (Default(..)) import qualified Data.Invertible as Inv import Data.Maybe (listToMaybe) import Network.URI (URI) import qualified Text.XML.HXT.Core as HXT import Text.XML.HXT.Arrow.Edit (escapeXmlRefs) import Text.XML.HXT.DOM.ShowXml (xshow') import Text.XML.HXT.DOM.XmlNode (getChildren) import SAML2.XML.Types import SAML2.Core.Datatypes import qualified Text.XML.HXT.Arrow.Pickle.Xml.Invertible as XP import qualified SAML2.XML.Schema as XS xpTrimAnyElem :: XP.PU HXT.XmlTree xpTrimAnyElem = XP.xpTrim XP.xpAnyElem xpTrimElemNS :: Namespace -> String -> XP.PU a -> XP.PU a xpTrimElemNS ns n c = XP.xpTrim $ XP.xpElemQN (mkNName ns n) (c XP.>* XP.xpWhitespace) xpXmlLang :: XP.PU XS.Language xpXmlLang = XP.xpAttrQN (mkNName xmlNS "lang") $ XS.xpLanguage type IP = XS.String xpIP :: XP.PU IP xpIP = XS.xpString data Identified b a = Identified !a | Unidentified !b deriving (Eq, Show) instance Default a => Default (Identified b a) where def = Identified def class Eq b => Identifiable b a | a -> b where identifier :: a -> b identifiedValues :: [a] default identifiedValues :: (Bounded a, Enum a) => [a] identifiedValues = [minBound..maxBound] reidentify :: b -> Identified b a reidentify u = maybe (Unidentified u) Identified $ lookup u l where l = [ (identifier a, a) | a <- identifiedValues ] unidentify :: Identifiable b a => Identified b a -> b unidentify (Identified a) = identifier a unidentify (Unidentified b) = b identify :: Identifiable b a => b Inv.<-> Identified b a identify = reidentify Inv.:<->: unidentify xpIdentified :: Identifiable b a => XP.PU b -> XP.PU (Identified b a) xpIdentified = Inv.fmap identify xpIdentifier :: Identifiable b a => XP.PU b -> String -> XP.PU a xpIdentifier b t = XP.xpWrapEither ( \u -> case reidentify u of Identified a -> Right a Unidentified _ -> Left ("invalid " ++ t) , identifier ) b type IdentifiedURI = Identified URI instance Identifiable URI a => XP.XmlPickler (Identified URI a) where xpickle = xpIdentified XS.xpAnyURI samlToDoc :: XP.XmlPickler a => a -> HXT.XmlTree samlToDoc = head . HXT.runLA (HXT.processChildren $ HXT.cleanupNamespaces HXT.collectPrefixUriPairs) . XP.pickleDoc XP.xpickle docToXML :: HXT.XmlTree -> BSL.ByteString docToXML = xshow' cquot aquot (:) . getChildren where (cquot, aquot) = escapeXmlRefs samlToXML :: XP.XmlPickler a => a -> BSL.ByteString samlToXML = docToXML . samlToDoc xmlToDoc :: BSL.ByteString -> Maybe HXT.XmlTree xmlToDoc = listToMaybe . HXT.runLA (HXT.xreadDoc HXT.>>> HXT.removeWhiteSpace HXT.>>> HXT.neg HXT.isXmlPi HXT.>>> HXT.propagateNamespaces) . BSLU.toString docToSAML :: XP.XmlPickler a => HXT.XmlTree -> Either String a docToSAML = XP.unpickleDoc' XP.xpickle . head . HXT.runLA (HXT.processBottomUp (HXT.processAttrl (HXT.neg HXT.isNamespaceDeclAttr))) xmlToSAML :: XP.XmlPickler a => BSL.ByteString -> Either String a xmlToSAML = maybe (Left "invalid XML") docToSAML . xmlToDoc
dylex/hsaml2
SAML2/XML.hs
apache-2.0
3,612
0
13
614
1,200
652
548
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, MagicHash, OverlappingInstances, TemplateHaskell, TypeSynonymInstances #-} {-| Module: HaskHOL.Core.Lib.Lift Copyright: (c) Ian Lynagh 2006 LICENSE: BSD3 Maintainer: [email protected] Stability: unstable Portability: unknown This module is a re-export of the th-lift library originally written by Ian Lynagh and maintained by Mathieu Boespflug. A very minor change was made by Evan Austin in order to facilitate derivation of lift instances for quantified type constructors. The decision to include this source as part of the HaskHOL system, rather than import the original library, was made to facilitate the above change and to sever HaskHOL's only dependence on a non-Haskell Platform library. -} {- The original copyright is included in its entirety below, as required by BSD3: Copyright (c) Ian Lynagh. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 HaskHOL.Core.Lib.Lift ( deriveLift' -- :: Info -> Q [Dec] , deriveLift -- :: Name -> Q [Dec] , deriveLiftMany -- :: [Name] -> Q [Dec] , module TH {-| Re-exports 'Lift' for the purpose of writing type signatures external to this module. -} ) where import GHC.Exts import Language.Haskell.TH import Language.Haskell.TH.Syntax import qualified Language.Haskell.TH.Syntax as TH (Lift) import Control.Monad ((<=<)) -- | Derive Lift instances for the given datatype. deriveLift :: Name -> Q [Dec] deriveLift = deriveLift' <=< reify -- | Derive Lift instances for many datatypes. deriveLiftMany :: [Name] -> Q [Dec] deriveLiftMany = deriveLiftMany' <=< mapM reify -- | Obtain Info values through a custom reification function. This is useful -- when generating instances for datatypes that have not yet been declared. deriveLift' :: Info -> Q [Dec] deriveLift' = fmap (:[]) . deriveLiftOne deriveLiftMany' :: [Info] -> Q [Dec] deriveLiftMany' = mapM deriveLiftOne deriveLiftOne :: Info -> Q Dec deriveLiftOne i = case i of TyConI (DataD dcx n vsk cons _) -> liftInstance dcx n (map unTyVarBndr vsk) (map doCons cons) TyConI (NewtypeD dcx n vsk con _) -> liftInstance dcx n (map unTyVarBndr vsk) [doCons con] _ -> fail ("deriveLift: unhandled: " ++ pprint i) where liftInstance dcx n vs cases = instanceD (ctxt dcx vs) (conT ''Lift `appT` typ n vs) [funD 'lift cases] typ n = foldl appT (conT n) . map varT ctxt dcx = fmap (dcx ++) . cxt . map liftPred unTyVarBndr (PlainTV v) = v unTyVarBndr (KindedTV v _) = v liftPred n = classP ''Lift [varT n] doCons :: Con -> Q Clause doCons (NormalC c sts) = do let ns = zipWith (\_ i -> 'x' : show i) sts [(0::Integer)..] con = [| conE c |] args = [ [| lift $(varE (mkName n)) |] | n <- ns ] e = foldl (\e1 e2 -> [| appE $e1 $e2 |]) con args clause [conP c (map (varP . mkName) ns)] (normalB e) [] doCons (RecC c sts) = doCons $ NormalC c [(s, t) | (_, s, t) <- sts] doCons (InfixC sty1 c sty2) = do let con = [| conE c |] left = [| lift $(varE (mkName "x0")) |] right = [| lift $(varE (mkName "x1")) |] e = [| infixApp $left $con $right |] clause [infixP (varP (mkName "x0")) c (varP (mkName "x1"))] (normalB e) [] -- ECA doCons (ForallC _ _ con) = doCons con instance Lift Name where lift (Name occName nameFlavour) = [| Name occName nameFlavour |] instance Lift OccName where lift n = [| mkOccName $(lift $ occString n) |] instance Lift PkgName where lift n = [| mkPkgName $(lift $ pkgString n) |] instance Lift ModName where lift n = [| mkModName $(lift $ modString n) |] instance Lift NameFlavour where lift NameS = [| NameS |] lift (NameQ moduleName) = [| NameQ moduleName |] lift (NameU i) = [| case $( lift (I# i) ) of I# i' -> NameU i' |] lift (NameL i) = [| case $( lift (I# i) ) of I# i' -> NameL i' |] lift (NameG nameSpace pkgName moduleName) = [| NameG nameSpace pkgName moduleName |] instance Lift NameSpace where lift VarName = [| VarName |] lift DataName = [| DataName |] lift TcClsName = [| TcClsName |] -- These instances should really go in the template-haskell package. instance Lift () where lift _ = [| () |] instance Lift Rational where lift x = return (LitE (RationalL x)) --ECA instance Lift String where lift = liftString
ecaustin/haskhol-core
src/HaskHOL/Core/Lib/Lift.hs
bsd-2-clause
5,876
0
14
1,346
1,117
615
502
78
4
module Utils.Drasil.Sentence (andIts, andThe, inThe, isExpctdToHv, isThe, ofGiv, ofGiv', ofThe, ofThe', sOf, sOr, sVersus, sAnd, sAre, sIn, sIs, toThe) where import Language.Drasil sentHelper :: String -> Sentence -> Sentence -> Sentence sentHelper inStr a b = a +:+ S inStr +:+ b andIts, andThe, inThe, isExpctdToHv, isThe, ofGiv, ofGiv', ofThe, ofThe', sOf, sOr, sVersus, sAnd, sAre, sIn, sIs, toThe :: Sentence -> Sentence -> Sentence andIts = sentHelper "and its" andThe = sentHelper "and the" inThe = sentHelper "in the" isThe = sentHelper "is the" sAnd = sentHelper "and" sAre = sentHelper "are" sIn = sentHelper "in" sIs = sentHelper "is" sOf = sentHelper "of" sOr = sentHelper "or" sVersus = sentHelper "versus" toThe = sentHelper "to the" isExpctdToHv a b = S "The" +:+ sentHelper "is expected to have" a b ofGiv a b = S "the" +:+ sentHelper "of a given" a b ofGiv' a b = S "The" +:+ sentHelper "of a given" a b ofThe a b = S "the" +:+ sentHelper "of the" a b ofThe' a b = S "The" +:+ sentHelper "of the" a b
JacquesCarette/literate-scientific-software
code/drasil-utils/Utils/Drasil/Sentence.hs
bsd-2-clause
1,127
0
7
291
366
205
161
24
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : Text.CSL.Eval.Output -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Andrea Rossato <[email protected]> -- Stability : unstable -- Portability : unportable -- -- The CSL implementation -- ----------------------------------------------------------------------------- module Text.CSL.Eval.Output where import Prelude import Data.Maybe (mapMaybe) import Data.String (fromString) import Data.Text (Text) import qualified Data.Text as T import Text.CSL.Output.Pandoc (lastInline) import Text.CSL.Style import Text.CSL.Util (capitalize, isPunct, titlecase, unTitlecase) import Text.Pandoc.Definition import Text.Pandoc.Walk (walk) import Text.Parsec import Text.Parsec.Text (Parser) -- Parse affix or delimiter into Formatted, splitting out -- raw components in @{{format}}...{{/format}}@. formatString :: Text -> Formatted formatString s = case parse pAffix (T.unpack s) s of Left _ -> fromString (T.unpack s) Right ils -> Formatted ils pAffix :: Parser [Inline] pAffix = many (pRaw <|> pString <|> pSpace) pRaw :: Parser Inline pRaw = try $ do _ <- string "{{" format <- many1 letter _ <- string "}}" contents <- manyTill anyChar (try (string ("{{/" ++ format ++ "}}"))) return $ RawInline (Format $ T.pack format) $ T.pack contents pString :: Parser Inline pString = Str . T.pack <$> (many1 (noneOf " \t\n\r{}") <|> count 1 (oneOf "{}")) pSpace :: Parser Inline pSpace = Space <$ many1 (oneOf " \t\n\r") output :: Formatting -> Text -> [Output] output fm s = case T.uncons s of Nothing -> [] Just (' ', xs) -> OSpace : output fm xs _ -> [OStr s fm] appendOutput :: Formatting -> [Output] -> [Output] appendOutput fm xs = [Output xs fm | xs /= []] outputList :: Formatting -> Delimiter -> [Output] -> [Output] outputList fm d = appendOutput fm . addDelim d . mapMaybe cleanOutput' where cleanOutput' o | Output xs f <- o = case cleanOutput xs of [] -> Nothing ys -> Just (Output ys f) | otherwise = rmEmptyOutput o cleanOutput :: [Output] -> [Output] cleanOutput = flatten where flatten [] = [] flatten (o:os) | ONull <- o = flatten os | Output xs f <- o , f == emptyFormatting = flatten (mapMaybe rmEmptyOutput xs) ++ flatten os | Output xs f <- o = Output (flatten $ mapMaybe rmEmptyOutput xs) f : flatten os | otherwise = maybe id (:) (rmEmptyOutput o) $ flatten os rmEmptyOutput :: Output -> Maybe Output rmEmptyOutput o | Output [] _ <- o = Nothing | OStr "" _ <- o = Nothing | OPan [] <- o = Nothing | OStatus [] <- o = Nothing | ODel "" <- o = Nothing | otherwise = Just o addDelim :: Text -> [Output] -> [Output] addDelim "" = id addDelim d = foldr check [] where check ONull xs = xs check x [] = [x] check x (z:zs) = if formatOutput x == mempty || formatOutput z == mempty then x : z : zs else x : ODel d : z : zs noOutputError :: Output noOutputError = OErr NoOutput noBibDataError :: Cite -> Output noBibDataError c = OErr $ ReferenceNotFound (citeId c) oStr :: Text -> [Output] oStr s = oStr' s emptyFormatting oStr' :: Text -> Formatting -> [Output] oStr' "" _ = [] oStr' s f = [OStr s f] oPan :: [Inline] -> [Output] oPan [] = [] oPan ils = [OPan ils] oPan' :: [Inline] -> Formatting -> [Output] oPan' [] _ = [] oPan' ils f = [Output [OPan ils] f] formatOutputList :: [Output] -> Formatted formatOutputList = mconcat . map formatOutput -- | Convert evaluated 'Output' into 'Formatted', ready for the -- output filters. formatOutput :: Output -> Formatted formatOutput o = case o of OSpace -> Formatted [Space] OPan i -> Formatted i OStatus i -> Formatted i ODel "" -> Formatted [] ODel " " -> Formatted [Space] ODel "\n" -> Formatted [SoftBreak] ODel s -> formatString s OStr "" _ -> Formatted [] OStr s f -> addFormatting f $ formatString s OErr NoOutput -> Formatted [Span ("",["citeproc-no-output"],[]) [Strong [Str "???"]]] OErr (ReferenceNotFound r) -> Formatted [Span ("",["citeproc-not-found"], [("data-reference-id",r)]) [Strong [Str "???"]]] OLabel "" _ -> Formatted [] OLabel s f -> addFormatting f $ formatString s ODate os -> formatOutputList os OYear s _ f -> addFormatting f $ formatString s OYearSuf s _ _ f -> addFormatting f $ formatString s ONum i f -> formatOutput (OStr (T.pack (show i)) f) OCitNum i f -> if i == 0 then Formatted [Strong [Str "???"]] else formatOutput (OStr (T.pack $ show i) f) OCitLabel s f -> if s == "" then Formatted [Strong [Str "???"]] else formatOutput (OStr s f) OName _ os _ f -> formatOutput (Output os f) OContrib _ _ os _ _ -> formatOutputList os OLoc os f -> formatOutput (Output os f) Output [] _ -> Formatted [] Output os f -> addFormatting f $ formatOutputList os _ -> Formatted [] addFormatting :: Formatting -> Formatted -> Formatted addFormatting f = addDisplay . addLink . addSuffix . pref . quote . font . text_case . strip_periods where addLink i = case hyperlink f of "" -> i url -> Formatted [Link nullAttr (unFormatted i) (url, "")] pref i = case prefix f of "" -> i x -> formatString x <> i addSuffix i | T.null (suffix f) = i | maybe False (isPunct . fst) (T.uncons (suffix f)) , case lastInline (unFormatted i) of {Just c | isPunct c -> True; _ -> False} = i <> formatString (T.tail $ suffix f) | otherwise = i <> formatString (suffix f) strip_periods (Formatted ils) = Formatted (walk removePeriod ils) removePeriod (Str xs) | stripPeriods f = Str (T.filter (/='.') xs) removePeriod x = x quote (Formatted []) = Formatted [] quote (Formatted ils) = case quotes f of NoQuote -> Formatted $ valign ils NativeQuote -> Formatted [Span ("",["csl-inquote"],[]) ils] _ -> Formatted [Quoted DoubleQuote $ valign ils] addDisplay (Formatted []) = Formatted [] addDisplay (Formatted ils) = case display f of "block" -> Formatted (LineBreak : ils ++ [LineBreak]) _ -> Formatted ils font (Formatted ils) | noDecor f = Formatted [Span ("",["nodecor"],[]) ils] | otherwise = Formatted $ font_variant . font_style . font_weight $ ils font_variant ils = case fontVariant f of "small-caps" -> [SmallCaps ils] _ -> ils font_style ils = case fontStyle f of "italic" -> [Emph ils] "oblique" -> [Emph ils] _ -> ils font_weight ils = case fontWeight f of "bold" -> [Strong ils] _ -> ils text_case (Formatted []) = Formatted [] text_case (Formatted ils@(i:is')) | noCase f = Formatted [Span ("",["nocase"],[]) ils] | otherwise = Formatted $ case textCase f of "lowercase" -> walk lowercaseStr ils "uppercase" -> walk uppercaseStr ils "capitalize-all" -> walk capitalizeStr ils "title" -> titlecase ils "capitalize-first" -> case i of Str cs -> Str (capitalize cs) : is' _ -> unTitlecase [i] ++ is' "sentence" -> unTitlecase ils _ -> ils lowercaseStr (Str xs) = Str $ T.toLower xs lowercaseStr x = x uppercaseStr (Str xs) = Str $ T.toUpper xs uppercaseStr x = x capitalizeStr (Str xs) = Str $ capitalize xs capitalizeStr x = x valign [] = [] valign ils | "sup" <- verticalAlign f = [Superscript ils] | "sub" <- verticalAlign f = [Subscript ils] | "baseline" <- verticalAlign f = [Span ("",["csl-baseline"],[]) ils] | otherwise = ils
jgm/pandoc-citeproc
src/Text/CSL/Eval/Output.hs
bsd-3-clause
9,696
0
18
3,788
3,085
1,525
1,560
202
27
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} module Fission2 where import Control.Monad import Data.Array.Accelerate ((:.) (..), Array, Elt, Shape) import qualified Data.Array.Accelerate as A import Prelude as P hiding (concat) type TuneM a = IO a arr :: A.Acc (A.Vector Double) arr = A.use (A.fromList (A.Z :. 10) [0..]) map :: (A.Slice sh,Shape sh,Elt a,Elt b) => (A.Exp a -> A.Exp b) -> A.Acc (Array (sh A.:. Int) a) -> TuneM (A.Acc (Array (sh A.:. Int) b)) map f arr = do (a1, a2) <- split arr let m1 = A.map f a1 m2 = A.map f a2 concat m1 m2 split :: (A.Slice sh,Shape sh,Elt a) => A.Acc (Array (sh A.:. Int) a) -> TuneM (A.Acc (Array (sh A.:. Int) a), A.Acc (Array (sh A.:. Int) a)) split arr = return (splitArray (A.constant 0), splitArray (A.constant 1)) where splitArray i = let shead = A.indexHead $ A.shape arr (chunk, leftover) = shead `quotRem` 2 start = (i A.<* leftover) A.? (i * (chunk + 1), i * chunk + leftover) end = ((i+1) A.<* leftover) A.? (start + chunk, (i+1) * chunk + leftover) bsh = A.lift $ (A.indexTail $ A.shape arr) A.:. (end - start) f x = A.lift $ (A.indexTail x) A.:. ((A.indexHead x) + start) in A.backpermute bsh f arr concat :: (A.Slice sh,Shape sh,Elt a) => A.Acc (Array (sh A.:. Int) a) -> A.Acc (Array (sh A.:. Int) a) -> TuneM (A.Acc (Array (sh A.:. Int) a)) concat xs ys = return $ A.generate gsh f where (sh1 A.:. n) = A.unlift $ A.shape xs (sh2 A.:. m) = A.unlift $ A.shape ys gsh = A.lift $ (A.intersect sh1 sh2) A.:. (n + m) f ix = ((A.indexHead ix) A.<* n) A.? (xs A.! ix, ys A.! (A.lift ((A.indexTail ix) A.:. ((A.indexHead ix) - n))))
vollmerm/shallow-fission
icebox/Fission2.hs
bsd-3-clause
2,131
0
18
828
977
514
463
41
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} module Fragment.Pair.Rules.Type.Infer.SyntaxDirected ( PairInferTypeContext , pairInferTypeRules ) where import Control.Monad.Except (MonadError) import Control.Lens (review) import Rules.Type.Infer.SyntaxDirected import Ast.Type import Fragment.Pair.Ast.Type import Fragment.Pair.Ast.Error import Fragment.Pair.Ast.Pattern import Fragment.Pair.Ast.Term import Fragment.Pair.Rules.Type.Infer.Common createPair :: (Monad m, AsTyPair ki ty) => Type ki ty a -> Type ki ty a -> m (Type ki ty a) createPair ty1 ty2 = return . review _TyPair $ (ty1, ty2) expectPair :: (MonadError e m, AsExpectedTyPair e ki ty a, AsTyPair ki ty) => Type ki ty a -> m (Type ki ty a, Type ki ty a) expectPair = expectTyPair type PairInferTypeContext e w s r m ki ty pt tm a = (InferTypeContext e w s r m ki ty pt tm a, AsTyPair ki ty, AsExpectedTyPair e ki ty a, AsPtPair pt, AsTmPair ki ty pt tm) pairInferTypeRules :: PairInferTypeContext e w s r m ki ty pt tm a => InferTypeInput e w s r m m ki ty pt tm a pairInferTypeRules = let ph = PairHelper createPair expectPair in inferTypeInput ph
dalaing/type-systems
src/Fragment/Pair/Rules/Type/Infer/SyntaxDirected.hs
bsd-3-clause
1,301
0
10
248
404
225
179
26
1
module Main where import Highlight.Highlight (defaultMain) main :: IO () main = defaultMain
cdepillabout/highlight
app/highlight/Main.hs
bsd-3-clause
95
0
6
16
29
17
12
4
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : -- Copyright : (c) 2012 Boyun Tang -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : ghc -- -- -- ----------------------------------------------------------------------------- module Main where import Bio.Seq.EMBL.Parser import Bio.Seq.EMBL.Types import qualified Data.ByteString.Lazy.Char8 as B8 import Data.Attoparsec.ByteString.Char8 import Data.Maybe import System.Environment import Control.Monad import Data.List import Bio.Seq.EMBL main = do seqs <- readEMBL =<< fmap head getArgs -- str <- B8.readFile =<< fmap head getArgs -- let (s:ss) = init $ groupBy (\_ b -> B8.take 2 b /= "//") $ B8.lines $ B8.filter (/= '\r') str -- seqs = B8.append (B8.unlines s) "//\n" : map ((flip B8.append "//\n") . B8.unlines . tail) ss -- func = flip feed "" . parse parseEMBL . B8.toStrict -- forM_ seqs $ \sq -> do -- case func sq of -- Done _ _ -> return () -- result -> print result >> B8.writeFile "Error.embl" sq >> error "Stop" print $ length seqs
tangboyun/bio-seq-embl
src/test.hs
bsd-3-clause
1,176
0
9
208
113
77
36
14
1
module Main where import Control.Applicative import Control.Monad import Data.Char import Data.Complex import Data.Maybe import Data.Ratio import Numeric import System.Environment import Text.ParserCombinators.Parsec hiding (spaces, many, (<|>), optional) main :: IO () main = do args <- getArgs print args mapM_ putStrLn $ fmap readExpr args symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~" spaces :: Parser () spaces = skipMany1 space data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | Float Double | Rational (Ratio Integer) | Complex (Complex Double) | String String | Bool Bool | Character String deriving Show readExpr :: String -> String readExpr input = case parse parseExpr "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value: " ++ show val parseBool :: Parser LispVal parseBool = Bool . (== 't') <$> (char '#' *> oneOf "ft") parseString :: Parser LispVal parseString = String <$> between quote quote escChars where quote = char '"' escChars = many (escapedOrNot "nrt\\\"") escapedOrNot :: String -> Parser Char escapedOrNot escChars = readChar <$> (escaped <|> noneOf "\"") where escaped = char '\\' *> oneOf escChars readChar c = read $ "'\\" ++ [c] ++ "'" parseCharacter :: Parser LispVal parseCharacter = (Character . readChar) <$> (prefix *> many nonWhitespace) where prefix = try $ char '#' *> char '\\' nonWhitespace = satisfy (not . isSpace) readChar [c] = return . read $ "'\\" ++ [c] ++ "'" readChar s = s parseAtom :: Parser LispVal parseAtom = Atom <$> atom where first = letter <|> symbol rest = many (letter <|> digit <|> symbol) atom = (:) <$> first <*> rest parseDecimalNumber :: Parser LispVal parseDecimalNumber = Number . read <$> (optional (string "#d") *> many1 digit) parseBinaryNumber :: Parser LispVal parseBinaryNumber = parseRadixNumber "01" readBin where readBin = readInt 2 (`elem` "01") (read . return) parseOctalNumber :: Parser LispVal parseOctalNumber = parseRadixNumber "01234567" readOct parseHexNumber :: Parser LispVal parseHexNumber = parseRadixNumber "0123456789abcdefABCDEF" readHex parseRadixNumber :: String -> ReadS Integer -> Parser LispVal parseRadixNumber chars decimalize = try $ prefix *> fmap numberfy digits where prefix = char '#' *> char 'o' numberfy = Number . fst . head . decimalize digits = many1 (oneOf chars) parseNumber :: Parser LispVal parseNumber = try (parseOctalNumber <|> parseHexNumber <|> parseBinaryNumber <|> parseDecimalNumber) parseFloat :: Parser LispVal parseFloat = fmap (Float . fst . head . readFloat) parseFloatString parseFloatString :: Parser String parseFloatString = try $ do beginning <- many digit <* char '.' end <- many digit guard $ (not . null) (beginning ++ end) -- We can slap extra 0's in there to avoid ".###" and "###.". return $ "0" ++ beginning ++ "." ++ end ++ "0" parseRational :: Parser LispVal parseRational = try $ numberfy <$> int <* over <*> int where int = many1 digit over = ws <* char '/' <* ws ws = skipMany space numberfy num denom = Rational (read num % read denom) parseComplex :: Parser LispVal parseComplex = try $ numberfy <$> real <*> imag where real = read . fromMaybe "0" <$> (optionMaybe . try $ numFollowedBy '+') imag = read <$> numFollowedBy 'i' numberfy r i = Complex (r :+ i) numFollowedBy c = (parseFloatString <|> many1 digit) <* char c parseExpr :: Parser LispVal parseExpr = parseRational <|> parseComplex <|> parseFloat <|> parseNumber <|> parseCharacter <|> parseAtom <|> parseString <|> parseBool
johntyree/Hascheme
Main.hs
bsd-3-clause
3,941
0
12
996
1,220
628
592
103
2
{-#Language GeneralizedNewtypeDeriving #-} module Control.Monad.ErrorM ( runErrorM , ErrorM (..) , Error (..) , Warning (..) , Errors , addError , throwFatalError , addWarning , showWarnings , showErrors ) where import Control.Applicative import Control.Monad.Fix import Control.Monad.Trans.Class import Control.Monad.Trans.State import Data.Either import Text.PrettyPrint data Warning = Warning Doc warningDoc :: Warning -> Doc warningDoc (Warning d) = d data Error = Error Doc | FatalError Doc errorDoc :: Error -> Doc errorDoc (Error d) = d errorDoc (FatalError d) = d type Errors = [Either Error Warning] newtype ErrorM a = ErrorM (StateT Errors (Either Errors) a) deriving (Monad, Applicative, Functor, MonadFix) runErrorM :: ErrorM a -> Either Errors ([Warning], a) runErrorM (ErrorM m) = do (a, errorsAndWarnings) <- runStateT m [] let (errors, warnings) = partitionEithers errorsAndWarnings case errors of [] -> Right (warnings, a) _ -> Left errorsAndWarnings addError :: Doc -> ErrorM () addError d = ErrorM $ modify $ ((Left $ Error d) :) throwFatalError ::Doc -> ErrorM a throwFatalError d = ErrorM $ do modify $ ((Left $ FatalError d) :) errorsAndWarnings <- get -- extract errors from the State monad _ <- lift $ Left errorsAndWarnings -- and lift them into the Either monad (this causes an immediate error, skipping further evaluation) return undefined addWarning :: Doc -> ErrorM () addWarning d = ErrorM $ modify $ ((Right $ Warning d) :) showWarnings :: [Warning] -> String showWarnings warns = render $ vcat (fmap warningDoc warns) showErrors :: Errors -> String showErrors a = render $ vcat (fmap errorDoc errs) $+$ vcat (fmap warningDoc warns) where (errs, warns) = partitionEithers a -- #TODO maybe add a particular type of error for compiler errors (to make it easier to quickcheck that they are never generated)
jvranish/TheExperiment
src/Control/Monad/ErrorM.hs
bsd-3-clause
2,200
0
12
654
602
324
278
50
2
module Entity.Position where import qualified Data.List as L import qualified GameData.Entity as E import qualified GameData.Animation as A import qualified Gamgine.Math.Vect as V currentPosition :: E.Entity -> V.Vect currentPosition E.Player {E.playerPosition = pos} = pos currentPosition E.Enemy {E.enemyPosition = Left pos} = pos currentPosition E.Enemy {E.enemyPosition = Right ani} = A.currentPosition ani currentPosition E.Star {E.starPosition = pos} = pos currentPosition E.Platform {E.platformPosition = Left pos} = pos currentPosition E.Platform {E.platformPosition = Right ani} = A.currentPosition ani setCurrentPosition :: E.Entity -> V.Vect -> E.Entity setCurrentPosition [email protected] {} newPos = p {E.playerPosition = newPos} setCurrentPosition [email protected] {E.enemyPosition = Left _} newPos = e {E.enemyPosition = Left newPos} setCurrentPosition [email protected] {E.enemyPosition = Right ani} newPos = e {E.enemyPosition = Right ani {A.currentPosition = newPos}} setCurrentPosition [email protected] {} newPos = s {E.starPosition = newPos} setCurrentPosition [email protected] {E.platformPosition = Left _} newPos = p {E.platformPosition = Left newPos} setCurrentPosition [email protected] {E.platformPosition = Right ani} newPos = p {E.platformPosition = Right ani {A.currentPosition = newPos}} position :: E.Entity -> V.Vect position E.Enemy {E.enemyPosition = Right ani} = A.basePosition ani position E.Platform {E.platformPosition = Right ani} = A.basePosition ani position entity = currentPosition entity setPosition :: E.Entity -> V.Vect -> E.Entity setPosition [email protected] {} newPos = p {E.playerInitialPos = newPos, E.playerPosition = newPos} setPosition [email protected] {E.enemyPosition = Right ani} newPos = e {E.enemyPosition = Right $ A.setBasePosition ani newPos} setPosition [email protected] {E.platformPosition = Right ani} newPos = p {E.platformPosition = Right $ A.setBasePosition ani newPos} setPosition entity newPos = setCurrentPosition entity newPos
dan-t/layers
src/Entity/Position.hs
bsd-3-clause
2,063
0
10
365
718
382
336
34
1
module Main where import XKCD import System.Environment (getArgs) import System.Directory (getCurrentDirectory) import System.Exit (exitSuccess) import System.FilePath (pathSeparator) main :: IO () main = getPath >>= downloadXKCD -- |Gets the into which it should download the comic getPath :: IO FilePath getPath = do path <- processArgs case path of Just path' -> return path' Nothing -> fmap (++ fileName) getCurrentDirectory where fileName = pathSeparator:"strip.png" -- |Checks whether the arguments contain a path, or help flag. If they do, prints the USAGE message processArgs :: IO (Maybe FilePath) processArgs = do args <- getArgs case args of [] -> return Nothing ("-h":_) -> printHelp ("--help":_) -> printHelp path -> return $ Just . head $ path where printHelp = putStrLn help >> exitSuccess -- |USAGE string help :: String help = "USAGE: xkcd [path|-h|-help]\nDownloads current xkcd strip to path or to current directory (with name xkcd.jpg)"
sellweek/xkcd
src/main.hs
bsd-3-clause
1,000
0
12
188
246
131
115
26
4
{-# LANGUAGE TemplateHaskell #-} -- | This module uses scope lookup techniques to either export -- 'lookupValueName' from @Language.Haskell.TH@, or define -- its own 'lookupValueName', which attempts to do the -- same job with just 'reify'. This will sometimes fail, but if it -- succeeds it will give the answer that the real function would have -- given. -- -- The idea is that if you use lookupValueName from this module, -- your client code will automatically use the best available name -- lookup mechanism. This means that e.g. 'scopeLookup' can work -- very well on recent GHCs and less well but still somewhat -- usefully on older GHCs. module NotCPP.LookupValueName ( lookupValueName ) where import Language.Haskell.TH import NotCPP.Utils bestValueGuess :: String -> Q (Maybe Name) bestValueGuess s = do mi <- maybeReify (mkName s) case mi of Nothing -> no Just i -> case i of VarI n _ _ _ -> yes n DataConI n _ _ _ -> yes n _ -> err ["unexpected info:", show i] where no = return Nothing yes = return . Just err = fail . showString "NotCPP.bestValueGuess: " . unwords $(recover [d| lookupValueName = bestValueGuess |] $ do VarI _ _ _ _ <- reify (mkName "lookupValueName") return [])
bmillwood/notcpp
NotCPP/LookupValueName.hs
bsd-3-clause
1,241
0
15
256
243
126
117
20
4
{-| Description: path consumer tools for consuming request path -} {-# LANGUAGE TemplateHaskell #-} module Web.Respond.Types.Path where import qualified Data.Text as T import Control.Monad.Trans.State import qualified Data.Sequence as S import Data.Foldable (toList) import Data.Monoid ((<>)) import Control.Lens (makeLenses, snoc, (%=), uses) import Safe (headMay, tailSafe) -- * working with the path. -- | stores the path and how much of it has been consumed data PathConsumer = PathConsumer { -- | the consumed part of the path. _pcConsumed :: S.Seq T.Text, -- | the unconsumed part _pcUnconsumed :: [T.Text] } deriving (Eq, Show) makeLenses ''PathConsumer -- | build a path consumer starting with nothing consumed mkPathConsumer :: [T.Text] -> PathConsumer mkPathConsumer = PathConsumer S.empty -- | get the next path element pcGetNext :: PathConsumer -> Maybe T.Text pcGetNext = headMay . _pcUnconsumed -- | move forward in the path pcConsumeNext :: PathConsumer -> PathConsumer pcConsumeNext = execState $ do next <- uses pcUnconsumed headMay pcConsumed %= maybe id (flip snoc) next pcUnconsumed %= tailSafe getFullPath :: PathConsumer -> [T.Text] getFullPath pc = toList (_pcConsumed pc) <> _pcUnconsumed pc
raptros/respond
src/Web/Respond/Types/Path.hs
bsd-3-clause
1,256
0
11
218
288
166
122
25
1
module Codex.Lib.Game ( ) where
adarqui/Codex
src/Codex/Lib/Game.hs
bsd-3-clause
32
0
3
5
10
7
3
1
0
module Forum.Internal.Encodable where import Data.Default.Class (def) import qualified Hasql.Encoders as Hasql import Data.Time (DiffTime, UTCTime, Day, TimeOfDay, LocalTime) import Data.Text (Text) import Data.ByteString (ByteString) import Data.Functor.Contravariant.Generic import Data.Functor.Contravariant (Op(..)) import Data.Int (Int16, Int32, Int64) import Data.Proxy (Proxy(..)) import Data.Monoid (Sum(..)) class Encodable a where encode :: Hasql.Params a default encode :: Deciding Encodable a => Hasql.Params a encode = deciding (Proxy :: Proxy Encodable) encode fieldCount :: a -> Int -- Not sure this is right for sum types etc. default fieldCount :: Deciding (Eq) a => a -> Int fieldCount x = getSum $ getOp (deciding (Proxy :: Proxy Eq) (Op $ \_ -> Sum 1) ) x instance Encodable Char where encode = Hasql.value def fieldCount _ = 1 instance Encodable Bool where encode = Hasql.value def fieldCount _ = 1 instance Encodable Int16 where encode = Hasql.value def fieldCount _ = 1 instance Encodable Int32 where encode = Hasql.value def fieldCount _ = 1 instance Encodable Int64 where encode = Hasql.value def fieldCount _ = 1 instance Encodable Double where encode = Hasql.value def fieldCount _ = 1 instance Encodable Float where encode = Hasql.value def fieldCount _ = 1 instance Encodable Text where encode = Hasql.value def fieldCount _ = 1 instance Encodable ByteString where encode = Hasql.value def fieldCount _ = 1 instance Encodable DiffTime where encode = Hasql.value def fieldCount _ = 1 instance Encodable UTCTime where encode = Hasql.value def fieldCount _ = 1 instance Encodable Day where encode = Hasql.value def fieldCount _ = 1 instance Encodable TimeOfDay where encode = Hasql.value def fieldCount _ = 1 instance Encodable LocalTime where encode = Hasql.value def fieldCount _ = 1
jkarni/forum
src/Forum/Internal/Encodable.hs
bsd-3-clause
1,918
0
14
383
639
341
298
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {- Copyright (c) 2014, Markus Barenhoff <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 Data.Geodetic.GeodeticModel where import qualified Prelude () import Data.Geodetic.Coordinate import Numeric.Units.Dimensional.TF.Prelude data Hemisphere = Northern | Soutern class (Ord t, Floating t, Show t, Show m, Show (GeodeticCoordinate m t)) => GeodeticModel m t where data GeodeticCoordinate m t :: * refElipsoid :: GeodeticCoordinate m t -> m latitude :: GeodeticCoordinate m t -> PlaneAngle t longitude :: GeodeticCoordinate m t -> PlaneAngle t height :: GeodeticCoordinate m t -> Length t mkCoordinate :: PlaneAngle t -> PlaneAngle t -> Length t -> GeodeticCoordinate m t semiMajorAxis :: (Fractional t) => m -> Length t recProcFlattening :: (Fractional t) => m -> Dimensionless t flattening :: (Fractional t) => m -> Dimensionless t flattening m = _1 / (recProcFlattening m) semiMinorAxis :: (Fractional t) => m -> Length t semiMinorAxis m = (semiMajorAxis m) * (_1 - flattening m) fstEccentricity :: (Floating t, Fractional t) => m -> Dimensionless t fstEccentricity m = let f = flattening m in (_2 * f) - (f ** _2) sndEccentricity :: (Floating t, Fractional t) => m -> Dimensionless t sndEccentricity m = let f = flattening m a = f * (_2 - f) b = ((_1 - f) ** _2) in a / b toEcef :: (Floating t) => GeodeticCoordinate m t -> ECEF t toEcef c = let φ = longitude c λ = latitude c h = height c e2 = fstEccentricity $ refElipsoid c x = sqrt (_1 - (e2 * ((sin φ) ** _2))) a = semiMajorAxis $ refElipsoid c normal = a / x normalh = normal + h rx = normalh * (cos φ) * (cos λ) ry = normalh * (cos φ) * (sin λ) rz = (((a * ( _1 - e2)) / x) + h) * (sin φ) in ECEF rx ry rz fromEcef :: (RealFloat t) => m -> ECEF t -> GeodeticCoordinate m t fromEcef m coord = let x = _coordX coord y = _coordY coord z = _coordZ coord a = semiMajorAxis m b = semiMinorAxis m e2 = fstEccentricity m e'2 = sndEccentricity m r = sqrt ((x * x) + (y * y)) ee2 = (a * a) - (b * b) f = (54 *~ one) * (b * b) * (z * z) g = (r * r) + ((_1 - e2) * z * z) - (e2 * e2 * ee2) c = (e2 * e2 * f * r * r ) / ( g * g * g ) s = cbrt (_1 + c + sqrt ((c*c) + (_2 * c))) p = f / (_3 * ((s + (_1 / s) + _1) ** _2) * (g * g)) q = sqrt (_1 + (_2 * e2 * e2 * p)) r0a = ((_0 - _1) * (p * e2 * r)) / (_1 + q) r0b = sqrt ((((_1 / _2) * a * a) * (_1 + (_1 / q)))- ((p * (_1 - e2) * z * z)/(q * (_1 + q))) - ((_1 / _2) * p * r * r)) r0 = r0a + r0b ub = z * z ua = (r - (e2 * r0)) * (r - (e2 * r0)) u = sqrt (ua + ub) v = sqrt (ua + ((_1 - e2) * ub)) z0 = (b * b * z) / (a * v) h = u * (_1 - ((b * b)/(a * v))) φ = atan ((z + (e'2 * z0)) / r) λ = atan2 y x in mkCoordinate λ φ h
alios/geodetic
src/Data/Geodetic/GeodeticModel.hs
bsd-3-clause
4,661
0
22
1,354
1,498
799
699
78
0
{-# LANGUAGE OverloadedStrings, CPP #-} module Happstack.Server.Wai ( toApplication , run , Warp.Port -- ** Low-level functions , convertRequest , convertResponse , standardHeaders ) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad.IO.Class import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as BL import Data.Char (toLower) import qualified Data.Map as Map import Data.Maybe (mapMaybe) import Data.Text (Text) import qualified Data.Text as T import qualified Happstack.Server as H import qualified Happstack.Server.Internal.Clock as H import qualified Happstack.Server.Internal.Cookie as H import qualified Happstack.Server.Internal.MessageWrap as H import Control.Monad.Trans.Resource import qualified Data.CaseInsensitive as CI import qualified Data.Conduit.Lazy as C import qualified Network.HTTP.Types as W import qualified Network.Wai as W import qualified Network.Wai.Handler.Warp as Warp -- | Convert a Happstack 'H.ServerPart' to a WAI 'W.Application'. toApplication :: H.ServerPart H.Response -> W.Application toApplication sp wReq = do hReq <- convertRequest wReq hResp <- liftIO $ H.simpleHTTP'' sp hReq additionalHeaders <- liftIO standardHeaders return $ convertResponse additionalHeaders hResp -- | Run a 'H.ServerPart' on warp at the specified port. run :: Warp.Port -> H.ServerPart H.Response -> IO () run port = Warp.run port . toApplication -- TODO - return '400 bad request' if we can't convert it -- | Convert a WAI 'W.Request' to a Happstack 'H.Request'. convertRequest :: W.Request -- ^ WAI request -> ResourceT IO H.Request convertRequest wReq = do bodyInputRef <- liftIO newEmptyMVar bodyLbs <- BL.fromChunks <$> C.lazyConsume (W.requestBody wReq) bodyRef <- liftIO $ newMVar $ H.Body bodyLbs return $ H.Request #if MIN_VERSION_happstack_server(6,5,0) (W.isSecure wReq) #endif (convertMethod $ W.requestMethod wReq) (convertPath $ W.pathInfo wReq) rawPath -- includes leading slash, does not include query rawQuery -- includes leading questionmark parsedQuery bodyInputRef cookies httpVersion headers bodyRef (B8.unpack (W.serverName wReq), W.serverPort wReq) where headers :: H.Headers -- Map ByteString HeaderPair headers = let assocs = flip map (W.requestHeaders wReq) $ \(ciName, val) -> (CI.original ciName, val) in mkHeadersBs assocs httpVersion :: H.HttpVersion httpVersion = case W.httpVersion wReq of W.HttpVersion major minor -> H.HttpVersion major minor cookies :: [(String, H.Cookie)] cookies = let cookieHeaders = filter (\x -> fst x == "Cookie") $ W.requestHeaders wReq rawCookies = map snd cookieHeaders foundCookies = concat $ mapMaybe H.getCookies rawCookies in map (\c -> (H.cookieName c, c)) foundCookies parsedQuery :: [(String,H.Input)] parsedQuery = case rawQuery of '?':xs -> H.formDecode xs xs -> H.formDecode xs rawQuery :: String rawQuery = B8.unpack $ W.rawQueryString wReq rawPath :: String rawPath = B8.unpack . fst $ B.breakByte 63 (W.rawPathInfo wReq) -- 63 == '?' convertPath :: [Text] -> [String] convertPath [] = [] convertPath xs = -- the WAI paths include a blank for the trailing slash case reverse xs of ("":rest) -> map T.unpack (reverse rest) _ -> map T.unpack xs convertMethod :: W.Method -> H.Method convertMethod m = -- TODO: somehow return 'Bad Request' response -- instead of expecting the application host to -- catch errors. case W.parseMethod m of Left{} -> error $ "Unknown method " ++ (show . B8.unpack) m Right stdM -> case stdM of W.GET -> H.GET W.POST -> H.POST W.HEAD -> H.HEAD W.PUT -> H.PUT W.DELETE -> H.DELETE W.TRACE -> H.TRACE W.CONNECT -> H.CONNECT W.OPTIONS -> H.OPTIONS -- | 'Date' header and server identification. standardHeaders :: IO W.ResponseHeaders standardHeaders = do dtStr <- H.getApproximateTime return [ ("Date", dtStr) , serverIdent , waiIdent ] -- | Convert a Happstack 'H.Response' to a WAI 'W.Response' convertResponse :: W.ResponseHeaders -- ^ Headers not in the response to send to the client (see 'standardHeaders') -> H.Response -- ^ Happstack response -> W.Response convertResponse additionalHeaders hResp = case hResp of H.SendFile{H.sfOffset=off,H.sfCount=count,H.sfFilePath=filePath} -> let fp = W.FilePart off count in W.ResponseFile status headersNoCl filePath (Just fp) H.Response{H.rsBody=body} -> W.responseLBS status headers body where -- TODO description status = W.Status (H.rsCode hResp) "" headersNoCl = (additionalHeaders ++) $ concatMap (\(H.HeaderPair k vs) -> map (\v -> (CI.mk k, v)) vs) $ Map.elems (H.rsHeaders hResp) headers = case H.rsfLength (H.rsFlags hResp) of H.ContentLength -> ("Content-Length", B8.pack $ show $ BL.length $ H.rsBody hResp) : headersNoCl _ -> headersNoCl serverIdent :: W.Header serverIdent = ( "Server" , B8.pack $ "Happstack/" ++ VERSION_happstack_server ) waiIdent :: W.Header waiIdent = ( "X-Wai-Version" , VERSION_wai ) -- stuff to feed back to happstack-server -- | Takes a list of (key,val) pairs and converts it into Headers. The -- keys will be converted to lowercase. mkHeadersBs :: [(ByteString,ByteString)] -> H.Headers mkHeadersBs hdrs = Map.fromListWith join [ (B8.map toLower key, H.HeaderPair key [value]) | (key,value) <- hdrs ] where join (H.HeaderPair key vs1) (H.HeaderPair _ vs2) = H.HeaderPair key (vs1++vs2)
aslatter/happstack-wai
src/Happstack/Server/Wai.hs
bsd-3-clause
6,137
0
17
1,553
1,602
871
731
147
9
{-| Module : Examples.Parser Description : Type level parsing. Copyright : (c) Alexander Vieth, 2016 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeInType #-} module Examples.List where import GHC.TypeLits hiding (SplitSymbol) import qualified GHC.TypeLits as TypeLits import Data.Kind import Data.Proxy import Data.Type.Function data Parser (t :: Type) where Parser :: (Symbol :-> Maybe (t, Symbol)) -> Parser t type RunParser = F RunParserProxy data RunParserProxy (p :: Parser t) (q :: Proxy (Symbol :-> Maybe (t, Symbol))) type instance EvalFunction (RunParserProxy ('Parser f)) = f -- Parser is a functor. type instance FmapInstance g ('Parser f) = 'Parser ((Fmap `At` (Swap :. (Fmap `At` g) :. Swap)) :. f) -- Parser is an applicative. type instance PureInstance Parser t = 'Parser (C 'Just :. (C '(,) `At` t)) -- Tuple the output of mf and mx, then apply the former to the latter. -- mf >>= fmap applyTuple . flip fmap mx . (,) type instance ApInstance (mf :: Parser (s :-> t)) (mx :: Parser s) = Bind `At` mf `At` ((Fmap `At` ApplyTuple) :. (Flip `At` Fmap `At` mx) :. C '(,)) -- Parser is an alternative. type instance AltInstance (left :: Parser t) (right :: Parser t) = 'Parser ( (AnalyseEither `At` C 'Just `At` (RunParser `At` right)) :. MakeEither -- Pass the input through so that we can re-use it if necessary. :. (Passthrough `At` (RunParser `At` left)) ) type MakeEither = F MakeEitherProxy data MakeEitherProxy (tuple :: (Maybe k, l)) (p :: Proxy (Either k l)) type instance EvalFunction (MakeEitherProxy '( 'Just x, y )) = 'Left x type instance EvalFunction (MakeEitherProxy '( 'Nothing, y )) = 'Right y -- Parser is a monad. type instance BindInstance (p :: Parser t) k = ParserJoin `At` (Fmap `At` k `At` p) type ParserJoin = F ParserJoinProxy data ParserJoinProxy (p :: Parser (Parser t)) (q :: Proxy (Parser t)) -- \p -> (=<<) (uncurry runParser) . runParser p type instance EvalFunction (ParserJoinProxy p) = 'Parser ( ((Flip `At` Bind) `At` (Uncurry `At` RunParser)) :. (RunParser `At` p) ) type SplitSymbol = F SplitSymbolProxy data SplitSymbolProxy (s :: Symbol) (p :: Proxy (Maybe (Character, Symbol))) type instance EvalFunction (SplitSymbolProxy s) = TypeLits.SplitSymbol s type ParserCharacter = 'Parser SplitSymbol -- :kind! RunParser `At` ((Const `At` 'True) :<$> ParserCharacter) `At` "hello" -- = 'Just '('True, "ello")
avieth/type-function
Examples/Parser.hs
bsd-3-clause
2,698
0
14
504
816
473
343
-1
-1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Tests.Readers.RST (tests) where import Text.Pandoc.Definition import Test.Framework import Tests.Helpers import Tests.Arbitrary() import Text.Pandoc.Builder import Text.Pandoc import Data.Monoid (mempty) rst :: String -> Pandoc rst = readRST def{ readerStandalone = True } infix 4 =: (=:) :: ToString c => String -> (String, c) -> Test (=:) = test rst tests :: [Test] tests = [ "line block with blank line" =: "| a\n|\n| b" =?> para (str "a") <> para (str "\160b") , "field list" =: unlines [ "para" , "" , ":Hostname: media08" , ":IP address: 10.0.0.19" , ":Size: 3ru" , ":Version: 1" , ":Indentation: Since the field marker may be quite long, the second" , " and subsequent lines of the field body do not have to line up" , " with the first line, but they must be indented relative to the" , " field name marker, and they must line up with each other." , ":Parameter i: integer" , ":Final: item" , " on two lines" ] =?> ( doc $ para "para" <> definitionList [ (str "Hostname", [para "media08"]) , (str "IP address", [para "10.0.0.19"]) , (str "Size", [para "3ru"]) , (str "Version", [para "1"]) , (str "Indentation", [para "Since the field marker may be quite long, the second and subsequent lines of the field body do not have to line up with the first line, but they must be indented relative to the field name marker, and they must line up with each other."]) , (str "Parameter i", [para "integer"]) , (str "Final", [para "item on two lines"]) ]) , "initial field list" =: unlines [ "=====" , "Title" , "=====" , "--------" , "Subtitle" , "--------" , "" , ":Version: 1" ] =?> ( setMeta "version" (para "1") $ setMeta "title" ("Title" :: Inlines) $ setMeta "subtitle" ("Subtitle" :: Inlines) $ doc mempty ) , "URLs with following punctuation" =: ("http://google.com, http://yahoo.com; http://foo.bar.baz.\n" ++ "http://foo.bar/baz_(bam) (http://foo.bar)") =?> para (link "http://google.com" "" "http://google.com" <> ", " <> link "http://yahoo.com" "" "http://yahoo.com" <> "; " <> link "http://foo.bar.baz" "" "http://foo.bar.baz" <> ". " <> link "http://foo.bar/baz_(bam)" "" "http://foo.bar/baz_(bam)" <> " (" <> link "http://foo.bar" "" "http://foo.bar" <> ")") , testGroup "literal / line / code blocks" [ "indented literal block" =: unlines [ "::" , "" , " block quotes" , "" , " can go on for many lines" , "but must stop here"] =?> (doc $ codeBlock "block quotes\n\ncan go on for many lines" <> para "but must stop here") , "line block with 3 lines" =: "| a\n| b\n| c" =?> para ("a" <> linebreak <> "b" <> linebreak <> "c") , "quoted literal block using >" =: "::\n\n> quoted\n> block\n\nOrdinary paragraph" =?> codeBlock "> quoted\n> block" <> para "Ordinary paragraph" , "quoted literal block using | (not a line block)" =: "::\n\n| quoted\n| block\n\nOrdinary paragraph" =?> codeBlock "| quoted\n| block" <> para "Ordinary paragraph" , "class directive with single paragraph" =: ".. class:: special\n\nThis is a \"special\" paragraph." =?> divWith ("", ["special"], []) (para "This is a \"special\" paragraph.") , "class directive with two paragraphs" =: ".. class:: exceptional remarkable\n\n First paragraph.\n\n Second paragraph." =?> divWith ("", ["exceptional", "remarkable"], []) (para "First paragraph." <> para "Second paragraph.") , "class directive around literal block" =: ".. class:: classy\n\n::\n\n a\n b" =?> divWith ("", ["classy"], []) (codeBlock "a\nb")] , testGroup "interpreted text roles" [ "literal role prefix" =: ":literal:`a`" =?> para (code "a") , "literal role postfix" =: "`a`:literal:" =?> para (code "a") , "literal text" =: "``text``" =?> para (code "text") , "code role" =: ":code:`a`" =?> para (codeWith ("", ["sourceCode"], []) "a") , "inherited code role" =: ".. role:: codeLike(code)\n\n:codeLike:`a`" =?> para (codeWith ("", ["codeLike", "sourceCode"], []) "a") , "custom code role with language field" =: ".. role:: lhs(code)\n :language: haskell\n\n:lhs:`a`" =?> para (codeWith ("", ["lhs", "haskell","sourceCode"], []) "a") , "custom role with unspecified parent role" =: ".. role:: classy\n\n:classy:`text`" =?> para (spanWith ("", ["classy"], []) "text") , "role with recursive inheritance" =: ".. role:: haskell(code)\n.. role:: lhs(haskell)\n\n:lhs:`text`" =?> para (codeWith ("", ["lhs", "haskell", "sourceCode"], []) "text") , "unknown role" =: ":unknown:`text`" =?> para (str "text") ] ]
sapek/pandoc
tests/Tests/Readers/RST.hs
gpl-2.0
5,683
0
18
1,952
1,085
593
492
103
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} module SugarScape.Agent.Loan ( agentLoan , handleLoanOffer , handleLoanPayback , handleLoanLenderDied , handleLoanInherit , splitLoanBorrowed , splitLoanLent ) where import Data.List import Data.Maybe import Control.Monad.Random import Data.MonadicStreamFunction import SugarScape.Agent.Common import SugarScape.Agent.Utils import SugarScape.Core.Common import SugarScape.Core.Discrete import SugarScape.Core.Model import SugarScape.Core.Random import SugarScape.Core.Scenario import SugarScape.Core.Utils import Debug.Trace as DBG agentLoan :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g)) -> AgentLocalMonad g (Maybe (EventHandler g)) agentLoan cont = ifThenElseM (isNothing . spLoansEnabled <$> scenario) cont (do checkBorrowedLoans offerLending cont) checkBorrowedLoans :: RandomGen g => AgentLocalMonad g () checkBorrowedLoans = do cs <- agentProperty sugAgBorrowed ret <- mapM checkLoan cs let (mcs, sugDebts, spiDebts) = unzip3 ret cs' = catMaybes mcs sugDebtSum = sum sugDebts spiDebtSum = sum spiDebts -- reduce the net-income by the debts payed back from Loans updateAgentState (\s -> s { sugAgBorrowed = cs' , sugAgNetIncome = sugAgNetIncome s - (sugDebtSum + spiDebtSum)}) -- NOTE: need to update occupier-info in environment because wealth (and MRS) might have changed updateSiteOccupied where checkLoan :: RandomGen g => Loan -> AgentLocalMonad g (Maybe Loan, Double, Double) checkLoan borrowerLoan@(Loan dueDate lender sugarFace spiceFace) = do t <- absStateLift getSimTime if dueDate /= t then return (Just borrowerLoan, 0, 0) -- Loan not yet due else do rate <- ((/100) . snd . fromJust . spLoansEnabled) <$> scenario let sugPay = sugarFace + (sugarFace * rate) -- payback the original face-value + a given percentage (interest) spiPay = spiceFace + (spiceFace * rate) -- payback the original face-value + a given percentage (interest) sugLvl <- agentProperty sugAgSugarLevel spiLvl <- agentProperty sugAgSpiceLevel if sugLvl >= sugPay && spiLvl >= spiPay then do -- own enough wealth to pay back the Loan fully -- NOTE: need to adjust wealth already here otherwise could pay more back than this agent has updateAgentState (\s -> s { sugAgSugarLevel = sugAgSugarLevel s - sugPay , sugAgSpiceLevel = sugAgSpiceLevel s - spiPay}) -- NOTE: need to update occupier-info in environment because wealth (and MRS) might have changed updateSiteOccupied sendEventTo lender (LoanPayback borrowerLoan sugPay spiPay) aid <- myId DBG.trace ("Agent " ++ show aid ++ ": " ++ show borrowerLoan ++ " is now due at t = " ++ show t ++ ", pay FULLY back to lender " ++ show lender) return (Nothing, sugPay, spiPay) else do -- not enough wealth, just pay back half of wealth and issue new Loan for the remaining face value(s) dueDate' <- ((t+) . fst . fromJust . spLoansEnabled) <$> scenario -- prevent negative values in facevalues: if agent has enough sugar/spice but not the other -- then it could be the case that it pays back one part of the Loan fully let sugPay' = min sugarFace sugLvl / 2 spiPay' = min spiceFace spiLvl / 2 c' = Loan dueDate' lender (sugarFace - sugPay') (spiceFace - spiPay') sendEventTo lender (LoanPayback borrowerLoan sugPay' spiPay') -- NOTE: need to adjust wealth already here otherwise could pay more back than this agent has updateAgentState (\s -> s { sugAgSugarLevel = sugAgSugarLevel s - sugPay' , sugAgSpiceLevel = sugAgSpiceLevel s - spiPay'}) -- NOTE: need to update occupier-info in environment because wealth (and MRS) might have changed updateSiteOccupied aid <- myId DBG.trace ("Agent " ++ show aid ++ ": " ++ show borrowerLoan ++ " is now due at t = " ++ show t ++ ", pays PARTIALLY back with half of its wealth " ++ show (sugPay', spiPay') ++ " to lender " ++ show lender) return (Just c', sugPay', spiPay') offerLending :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g)) -> AgentLocalMonad g (Maybe (EventHandler g)) offerLending cont = do pl <- potentialLender if isNothing pl then cont else do myCoord <- agentProperty sugAgCoord sites <- envLift $ neighboursM myCoord False let ns = mapMaybe (sugEnvSiteOccupier . snd) sites if null ns then cont else do t <- absStateLift getSimTime dueDate <- ((t+) . fst . fromJust . spLoansEnabled) <$> scenario ns' <- randLift $ randomShuffleM ns lendTo cont dueDate ns' lendTo :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g)) -> Time -> [SugEnvSiteOccupier] -> AgentLocalMonad g (Maybe (EventHandler g)) lendTo cont _ [] = cont -- iterated through all neighbours, finished, quit lendingTo and switch back to globalHandler lendTo cont dueDate (neighbour : ns) = do pl <- potentialLender -- always check because could have changed while iterating case pl of Nothing -> cont -- not potential lender, quit Just (sug, spi) -> do aid <- myId let borrowerId = sugEnvOccId neighbour borrowerLoan = Loan dueDate aid sug spi evtHandler = lendingToHandler cont dueDate ns borrowerLoan sendEventTo borrowerId (LoanOffer borrowerLoan) return $ Just evtHandler lendingToHandler :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g)) -> Time -> [SugEnvSiteOccupier] -> Loan -> EventHandler g lendingToHandler cont0 dueDate ns borrowerLoan@(Loan _ _ sugarFace spiceFace) = continueWithAfter (proc evt -> case evt of (DomainEvent borrowerId (LoanReply reply)) -> do mhdl <- arrM (uncurry (handleLendingReply cont0)) -< (borrowerId, reply) returnA -< ((), mhdl) _ -> do aid <- constM myId -< () returnA -< error $ "Agent " ++ show aid ++ ": received unexpected event " ++ show evt ++ " during lending, terminating simulation!") where handleLendingReply :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g)) -> AgentId -> LoanReply -> AgentLocalMonad g (Maybe (EventHandler g)) handleLendingReply cont _ (RefuseLoan _) = -- the sender refuses the Loan-offer, continue with the next neighbour lendTo cont dueDate ns handleLendingReply cont borrowerId AcceptLoan = do let lenderLoan = Loan dueDate borrowerId sugarFace spiceFace -- the sender accepts the Loan-offer, remove Loan-wealth from lender and add borrower updateAgentState (\s -> s { sugAgSugarLevel = sugAgSugarLevel s - sugarFace , sugAgSpiceLevel = sugAgSpiceLevel s - spiceFace , sugAgLent = lenderLoan : sugAgLent s}) -- NOTE: need to update occupier-info in environment because wealth has (and MRS) changed updateSiteOccupied -- continue with next neighbour aid <- myId DBG.trace ("Agent " ++ show aid ++ ": lending " ++ show borrowerLoan ++ " to " ++ show borrowerId ++ " with lenderLoan = " ++ show lenderLoan) lendTo cont dueDate ns handleLoanOffer :: RandomGen g => Loan -> AgentLocalMonad g () handleLoanOffer borrowerLoan@(Loan _ lender sugarFace spiceFace) = do pb <- potentialBorrower case pb of Just reason -> sendEventTo lender (LoanReply $ RefuseLoan reason) Nothing -> do -- the borrower accepts the Loan-offer, increase wealth of borrower -- and add to borrowers obligations updateAgentState (\s -> s { sugAgSugarLevel = sugAgSugarLevel s + sugarFace , sugAgSpiceLevel = sugAgSpiceLevel s + spiceFace , sugAgBorrowed = borrowerLoan : sugAgBorrowed s }) -- NOTE: need to update occupier-info in environment because wealth has (and MRS) changed updateSiteOccupied aid <- myId DBG.trace ("Agent " ++ show aid ++ ": borrowing " ++ show borrowerLoan ++ " from " ++ show lender) sendEventTo lender (LoanReply AcceptLoan) handleLoanPayback :: RandomGen g => AgentId -> Loan -> Double -> Double -> AgentLocalMonad g () handleLoanPayback borrower borrowerLoan@(Loan dueDate _ sugarFace spiceFace) sugarBack spiceBack = do t <- absStateLift getSimTime newDueDate <- (t+) . fst . fromJust . spLoansEnabled <$> scenario rate <- (/100) . snd . fromJust . spLoansEnabled <$> scenario aid <- myId ls <- processBorrower rate aid newDueDate <$> agentProperty sugAgLent updateAgentState (\s -> s { sugAgLent = ls , sugAgSugarLevel = sugAgSugarLevel s + sugarBack , sugAgSpiceLevel = sugAgSpiceLevel s + spiceBack}) -- NOTE: need to update occupier-info in environment because wealth (and MRS) might have changed updateSiteOccupied where processBorrower :: Double -> AgentId -> Time -> [Loan] -> [Loan] processBorrower rate aid newDueDate ls -- TODO: when inheritance is turned on, this error occurs sometimes, no idea why | isNothing mxid = error $ "Agent " ++ show aid ++ ": couldn't find " ++ show borrowerLoan ++ " for borrower payback in my loans " ++ show ls ++ ", exit." | otherwise = if fullyPaidBack l then DBG.trace ("Agent " ++ show aid ++ ": received FULL Loan payback of " ++ show l ++ " from " ++ show borrower) ls' else DBG.trace("Agent " ++ show aid ++ ": received PARTIAL Loan payback of " ++ show l ++ " from " ++ show borrower) (l' : ls') where mxid = findIndex findBorrowerLoan ls idx = fromJust mxid l = ls !! idx l' = newLoan ls' = removeElemByIdx idx ls fullyPaidBack :: Loan -> Bool fullyPaidBack (Loan _ _ sugarFace' spiceFace') = fullSugarBack == sugarBack && fullSpiceBack == spiceBack where -- NOTE: need to include the interest! fullSugarBack = sugarFace' + (sugarFace' * rate) fullSpiceBack = spiceFace' + (spiceFace' * rate) newLoan :: Loan newLoan = Loan newDueDate borrower (sugarFace - sugarBack) (spiceFace - spiceBack) findBorrowerLoan :: Loan -> Bool findBorrowerLoan (Loan dueDate' borrower' sugarFace' spiceFace') = borrower' == borrower && dueDate' == dueDate && sugarFace' == sugarFace && spiceFace' == spiceFace handleLoanLenderDied :: RandomGen g => AgentId -> [AgentId] -> AgentLocalMonad g () handleLoanLenderDied lender children = do oldLs <- agentProperty sugAgBorrowed ls <- processLoans [] <$> agentProperty sugAgBorrowed aid <- myId DBG.trace ("Agent " ++ show aid ++ ": lender " ++ show lender ++ " died and inherits its loan to its children " ++ show children ++ "\nold loans = " ++ show oldLs ++ "\nnew loans = " ++ show ls) updateAgentState (\s -> s { sugAgBorrowed = ls }) where processLoans :: [Loan] -> [Loan] -> [Loan] processLoans acc [] = acc processLoans acc (l@(Loan _ lender' _ _) : ls) | lender' /= lender = processLoans (l : acc) ls -- different lender, keep as it is | otherwise = processLoans (newLs ++ acc) ls -- died lender, change to new where newLs = splitLoanBorrowed children l handleLoanInherit :: RandomGen g => AgentId -> Loan -> AgentLocalMonad g () handleLoanInherit parent loan = do aid <- myId DBG.trace ("Agent " ++ show aid ++ ": inherited " ++ show loan ++ " from parent " ++ show parent) updateAgentState (\s -> s { sugAgLent = loan : sugAgLent s }) potentialLender :: AgentLocalMonad g (Maybe (Double, Double)) potentialLender = do age <- agentProperty sugAgAge (fertMin, fertMax) <- agentProperty sugAgFertAgeRange sugLvl <- agentProperty sugAgSugarLevel spiLvl <- agentProperty sugAgSpiceLevel if age > fertMax then return $ Just (sugLvl / 2, spiLvl / 2) -- agent is too old to bear children, will lend half of its current wealth else -- agent is within child-bearing age if age >= fertMin && age <= fertMax then do initSugLvl <- agentProperty sugAgInitSugEndow initSpiLvl <- agentProperty sugAgInitSpiEndow -- check if this agent has wealth excess if sugLvl > initSugLvl && spiLvl > initSpiLvl then return $ Just (sugLvl - initSugLvl, spiLvl - initSpiLvl) -- lend excess wealth else return Nothing -- no wealth excess else return Nothing -- not within child-bearing age, too young, nothing potentialBorrower :: AgentLocalMonad g (Maybe LoanRefuse) potentialBorrower = do age <- agentProperty sugAgAge (fertMin, fertMax) <- agentProperty sugAgFertAgeRange sugLvl <- agentProperty sugAgSugarLevel spiLvl <- agentProperty sugAgSpiceLevel if age >= fertMin && age <= fertMax then do initSugLvl <- agentProperty sugAgInitSugEndow initSpiLvl <- agentProperty sugAgInitSpiEndow if sugLvl > initSugLvl && spiLvl > initSpiLvl then return $ Just EnoughWealth -- agent has already enough wealth else do netInc <- agentProperty sugAgNetIncome if netInc <= 0 then return $ Just NotLoanWorthy -- not Loanworthy: has the agent had a net income in the most recent time-step? else return Nothing else return $ Just NotFertileAge -- agent is not child-bearing age splitLoanBorrowed :: [AgentId] -> Loan -> [Loan] splitLoanBorrowed as (Loan dueDate _ sugarFace spiceFace) = map (\a -> Loan dueDate a (sugarFace / n) (spiceFace / n)) as where n = fromIntegral $ length as splitLoanLent :: Int -> Loan -> [Loan] splitLoanLent n (Loan dueDate borrower sugarFace spiceFace) = replicate n (Loan dueDate borrower (sugarFace / n') (spiceFace / n')) where n' = fromIntegral n
thalerjonathan/phd
thesis/code/sugarscape/src/SugarScape/Agent/Loan.hs
gpl-3.0
15,401
1
26
4,897
3,577
1,794
1,783
282
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.OpsWorks.CreateStack -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new stack. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-edit.html Create a New Stack>. -- -- __Required Permissions__: To use this action, an IAM user must have an -- attached policy that explicitly grants permissions. For more information -- on user permissions, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_CreateStack.html AWS API Reference> for CreateStack. module Network.AWS.OpsWorks.CreateStack ( -- * Creating a Request createStack , CreateStack -- * Request Lenses , csDefaultRootDeviceType , csVPCId , csChefConfiguration , csAgentVersion , csDefaultSSHKeyName , csCustomJSON , csCustomCookbooksSource , csDefaultAvailabilityZone , csAttributes , csDefaultOS , csUseOpsworksSecurityGroups , csUseCustomCookbooks , csDefaultSubnetId , csConfigurationManager , csHostnameTheme , csName , csRegion , csServiceRoleARN , csDefaultInstanceProfileARN -- * Destructuring the Response , createStackResponse , CreateStackResponse -- * Response Lenses , crsStackId , crsResponseStatus ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createStack' smart constructor. data CreateStack = CreateStack' { _csDefaultRootDeviceType :: !(Maybe RootDeviceType) , _csVPCId :: !(Maybe Text) , _csChefConfiguration :: !(Maybe ChefConfiguration) , _csAgentVersion :: !(Maybe Text) , _csDefaultSSHKeyName :: !(Maybe Text) , _csCustomJSON :: !(Maybe Text) , _csCustomCookbooksSource :: !(Maybe Source) , _csDefaultAvailabilityZone :: !(Maybe Text) , _csAttributes :: !(Maybe (Map StackAttributesKeys Text)) , _csDefaultOS :: !(Maybe Text) , _csUseOpsworksSecurityGroups :: !(Maybe Bool) , _csUseCustomCookbooks :: !(Maybe Bool) , _csDefaultSubnetId :: !(Maybe Text) , _csConfigurationManager :: !(Maybe StackConfigurationManager) , _csHostnameTheme :: !(Maybe Text) , _csName :: !Text , _csRegion :: !Text , _csServiceRoleARN :: !Text , _csDefaultInstanceProfileARN :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateStack' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csDefaultRootDeviceType' -- -- * 'csVPCId' -- -- * 'csChefConfiguration' -- -- * 'csAgentVersion' -- -- * 'csDefaultSSHKeyName' -- -- * 'csCustomJSON' -- -- * 'csCustomCookbooksSource' -- -- * 'csDefaultAvailabilityZone' -- -- * 'csAttributes' -- -- * 'csDefaultOS' -- -- * 'csUseOpsworksSecurityGroups' -- -- * 'csUseCustomCookbooks' -- -- * 'csDefaultSubnetId' -- -- * 'csConfigurationManager' -- -- * 'csHostnameTheme' -- -- * 'csName' -- -- * 'csRegion' -- -- * 'csServiceRoleARN' -- -- * 'csDefaultInstanceProfileARN' createStack :: Text -- ^ 'csName' -> Text -- ^ 'csRegion' -> Text -- ^ 'csServiceRoleARN' -> Text -- ^ 'csDefaultInstanceProfileARN' -> CreateStack createStack pName_ pRegion_ pServiceRoleARN_ pDefaultInstanceProfileARN_ = CreateStack' { _csDefaultRootDeviceType = Nothing , _csVPCId = Nothing , _csChefConfiguration = Nothing , _csAgentVersion = Nothing , _csDefaultSSHKeyName = Nothing , _csCustomJSON = Nothing , _csCustomCookbooksSource = Nothing , _csDefaultAvailabilityZone = Nothing , _csAttributes = Nothing , _csDefaultOS = Nothing , _csUseOpsworksSecurityGroups = Nothing , _csUseCustomCookbooks = Nothing , _csDefaultSubnetId = Nothing , _csConfigurationManager = Nothing , _csHostnameTheme = Nothing , _csName = pName_ , _csRegion = pRegion_ , _csServiceRoleARN = pServiceRoleARN_ , _csDefaultInstanceProfileARN = pDefaultInstanceProfileARN_ } -- | The default root device type. This value is the default for all -- instances in the stack, but you can override it when you create an -- instance. The default option is 'instance-store'. For more information, -- see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device Storage for the Root Device>. csDefaultRootDeviceType :: Lens' CreateStack (Maybe RootDeviceType) csDefaultRootDeviceType = lens _csDefaultRootDeviceType (\ s a -> s{_csDefaultRootDeviceType = a}); -- | The ID of the VPC that the stack is to be launched into. The VPC must be -- in the stack\'s region. All instances are launched into this VPC. You -- cannot change the ID later. -- -- - If your account supports EC2-Classic, the default value is 'no VPC'. -- - If your account does not support EC2-Classic, the default value is -- the default VPC for the specified region. -- -- If the VPC ID corresponds to a default VPC and you have specified either -- the 'DefaultAvailabilityZone' or the 'DefaultSubnetId' parameter only, -- AWS OpsWorks infers the value of the other parameter. If you specify -- neither parameter, AWS OpsWorks sets these parameters to the first valid -- Availability Zone for the specified region and the corresponding default -- VPC subnet ID, respectively. -- -- If you specify a nondefault VPC ID, note the following: -- -- - It must belong to a VPC in your account that is in the specified -- region. -- - You must specify a value for 'DefaultSubnetId'. -- -- For more information on how to use AWS OpsWorks with a VPC, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html Running a Stack in a VPC>. -- For more information on default VPC and EC2-Classic, see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html Supported Platforms>. csVPCId :: Lens' CreateStack (Maybe Text) csVPCId = lens _csVPCId (\ s a -> s{_csVPCId = a}); -- | A 'ChefConfiguration' object that specifies whether to enable Berkshelf -- and the Berkshelf version on Chef 11.10 stacks. For more information, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html Create a New Stack>. csChefConfiguration :: Lens' CreateStack (Maybe ChefConfiguration) csChefConfiguration = lens _csChefConfiguration (\ s a -> s{_csChefConfiguration = a}); -- | The default AWS OpsWorks agent version. You have the following options: -- -- - Auto-update - Set this parameter to 'LATEST'. AWS OpsWorks -- automatically installs new agent versions on the stack\'s instances -- as soon as they are available. -- - Fixed version - Set this parameter to your preferred agent version. -- To update the agent version, you must edit the stack configuration -- and specify a new version. AWS OpsWorks then automatically installs -- that version on the stack\'s instances. -- -- The default setting is 'LATEST'. To specify an agent version, you must -- use the complete version number, not the abbreviated number shown on the -- console. For a list of available agent version numbers, call -- DescribeAgentVersions. -- -- You can also specify an agent version when you create or update an -- instance, which overrides the stack\'s default setting. csAgentVersion :: Lens' CreateStack (Maybe Text) csAgentVersion = lens _csAgentVersion (\ s a -> s{_csAgentVersion = a}); -- | A default Amazon EC2 key pair name. The default value is none. If you -- specify a key pair name, AWS OpsWorks installs the public key on the -- instance and you can use the private key with an SSH client to log in to -- the instance. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-ssh.html Using SSH to Communicate with an Instance> -- and -- <http://docs.aws.amazon.com/opsworks/latest/userguide/security-ssh-access.html Managing SSH Access>. -- You can override this setting by specifying a different key pair, or no -- key pair, when you -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-add.html create an instance>. csDefaultSSHKeyName :: Lens' CreateStack (Maybe Text) csDefaultSSHKeyName = lens _csDefaultSSHKeyName (\ s a -> s{_csDefaultSSHKeyName = a}); -- | A string that contains user-defined, custom JSON. It can be used to -- override the corresponding default stack configuration attribute values -- or to pass data to recipes. The string should be in the following escape -- characters such as \'\"\': -- -- '\"{\\\"key1\\\": \\\"value1\\\", \\\"key2\\\": \\\"value2\\\",...}\"' -- -- For more information on custom JSON, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html Use Custom JSON to Modify the Stack Configuration Attributes>. csCustomJSON :: Lens' CreateStack (Maybe Text) csCustomJSON = lens _csCustomJSON (\ s a -> s{_csCustomJSON = a}); -- | Undocumented member. csCustomCookbooksSource :: Lens' CreateStack (Maybe Source) csCustomCookbooksSource = lens _csCustomCookbooksSource (\ s a -> s{_csCustomCookbooksSource = a}); -- | The stack\'s default Availability Zone, which must be in the specified -- region. For more information, see -- <http://docs.aws.amazon.com/general/latest/gr/rande.html Regions and Endpoints>. -- If you also specify a value for 'DefaultSubnetId', the subnet must be in -- the same zone. For more information, see the 'VpcId' parameter -- description. csDefaultAvailabilityZone :: Lens' CreateStack (Maybe Text) csDefaultAvailabilityZone = lens _csDefaultAvailabilityZone (\ s a -> s{_csDefaultAvailabilityZone = a}); -- | One or more user-defined key-value pairs to be added to the stack -- attributes. csAttributes :: Lens' CreateStack (HashMap StackAttributesKeys Text) csAttributes = lens _csAttributes (\ s a -> s{_csAttributes = a}) . _Default . _Map; -- | The stack\'s default operating system, which is installed on every -- instance unless you specify a different operating system when you create -- the instance. You can specify one of the following. -- -- - A supported Linux operating system: An Amazon Linux version, such as -- 'Amazon Linux 2015.03', 'Red Hat Enterprise Linux 7', -- 'Ubuntu 12.04 LTS', or 'Ubuntu 14.04 LTS'. -- - 'Microsoft Windows Server 2012 R2 Base'. -- - A custom AMI: 'Custom'. You specify the custom AMI you want to use -- when you create instances. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html Using Custom AMIs>. -- -- The default option is the current Amazon Linux version. For more -- information on the supported operating systems, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html AWS OpsWorks Operating Systems>. csDefaultOS :: Lens' CreateStack (Maybe Text) csDefaultOS = lens _csDefaultOS (\ s a -> s{_csDefaultOS = a}); -- | Whether to associate the AWS OpsWorks built-in security groups with the -- stack\'s layers. -- -- AWS OpsWorks provides a standard set of built-in security groups, one -- for each layer, which are associated with layers by default. With -- 'UseOpsworksSecurityGroups' you can instead provide your own custom -- security groups. 'UseOpsworksSecurityGroups' has the following settings: -- -- - True - AWS OpsWorks automatically associates the appropriate -- built-in security group with each layer (default setting). You can -- associate additional security groups with a layer after you create -- it, but you cannot delete the built-in security group. -- - False - AWS OpsWorks does not associate built-in security groups -- with layers. You must create appropriate EC2 security groups and -- associate a security group with each layer that you create. However, -- you can still manually associate a built-in security group with a -- layer on creation; custom security groups are required only for -- those layers that need custom settings. -- -- For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html Create a New Stack>. csUseOpsworksSecurityGroups :: Lens' CreateStack (Maybe Bool) csUseOpsworksSecurityGroups = lens _csUseOpsworksSecurityGroups (\ s a -> s{_csUseOpsworksSecurityGroups = a}); -- | Whether the stack uses custom cookbooks. csUseCustomCookbooks :: Lens' CreateStack (Maybe Bool) csUseCustomCookbooks = lens _csUseCustomCookbooks (\ s a -> s{_csUseCustomCookbooks = a}); -- | The stack\'s default VPC subnet ID. This parameter is required if you -- specify a value for the 'VpcId' parameter. All instances are launched -- into this subnet unless you specify otherwise when you create the -- instance. If you also specify a value for 'DefaultAvailabilityZone', the -- subnet must be in that zone. For information on default values and when -- this parameter is required, see the 'VpcId' parameter description. csDefaultSubnetId :: Lens' CreateStack (Maybe Text) csDefaultSubnetId = lens _csDefaultSubnetId (\ s a -> s{_csDefaultSubnetId = a}); -- | The configuration manager. When you clone a stack we recommend that you -- use the configuration manager to specify the Chef version: 0.9, 11.4, or -- 11.10. The default value is currently 11.4. csConfigurationManager :: Lens' CreateStack (Maybe StackConfigurationManager) csConfigurationManager = lens _csConfigurationManager (\ s a -> s{_csConfigurationManager = a}); -- | The stack\'s host name theme, with spaces replaced by underscores. The -- theme is used to generate host names for the stack\'s instances. By -- default, 'HostnameTheme' is set to 'Layer_Dependent', which creates host -- names by appending integers to the layer\'s short name. The other themes -- are: -- -- - 'Baked_Goods' -- - 'Clouds' -- - 'Europe_Cities' -- - 'Fruits' -- - 'Greek_Deities' -- - 'Legendary_creatures_from_Japan' -- - 'Planets_and_Moons' -- - 'Roman_Deities' -- - 'Scottish_Islands' -- - 'US_Cities' -- - 'Wild_Cats' -- -- To obtain a generated host name, call 'GetHostNameSuggestion', which -- returns a host name based on the current theme. csHostnameTheme :: Lens' CreateStack (Maybe Text) csHostnameTheme = lens _csHostnameTheme (\ s a -> s{_csHostnameTheme = a}); -- | The stack name. csName :: Lens' CreateStack Text csName = lens _csName (\ s a -> s{_csName = a}); -- | The stack\'s AWS region, such as \"us-east-1\". For more information -- about Amazon regions, see -- <http://docs.aws.amazon.com/general/latest/gr/rande.html Regions and Endpoints>. csRegion :: Lens' CreateStack Text csRegion = lens _csRegion (\ s a -> s{_csRegion = a}); -- | The stack\'s AWS Identity and Access Management (IAM) role, which allows -- AWS OpsWorks to work with AWS resources on your behalf. You must set -- this parameter to the Amazon Resource Name (ARN) for an existing IAM -- role. For more information about IAM ARNs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html Using Identifiers>. csServiceRoleARN :: Lens' CreateStack Text csServiceRoleARN = lens _csServiceRoleARN (\ s a -> s{_csServiceRoleARN = a}); -- | The Amazon Resource Name (ARN) of an IAM profile that is the default -- profile for all of the stack\'s EC2 instances. For more information -- about IAM ARNs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html Using Identifiers>. csDefaultInstanceProfileARN :: Lens' CreateStack Text csDefaultInstanceProfileARN = lens _csDefaultInstanceProfileARN (\ s a -> s{_csDefaultInstanceProfileARN = a}); instance AWSRequest CreateStack where type Rs CreateStack = CreateStackResponse request = postJSON opsWorks response = receiveJSON (\ s h x -> CreateStackResponse' <$> (x .?> "StackId") <*> (pure (fromEnum s))) instance ToHeaders CreateStack where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.CreateStack" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON CreateStack where toJSON CreateStack'{..} = object (catMaybes [("DefaultRootDeviceType" .=) <$> _csDefaultRootDeviceType, ("VpcId" .=) <$> _csVPCId, ("ChefConfiguration" .=) <$> _csChefConfiguration, ("AgentVersion" .=) <$> _csAgentVersion, ("DefaultSshKeyName" .=) <$> _csDefaultSSHKeyName, ("CustomJson" .=) <$> _csCustomJSON, ("CustomCookbooksSource" .=) <$> _csCustomCookbooksSource, ("DefaultAvailabilityZone" .=) <$> _csDefaultAvailabilityZone, ("Attributes" .=) <$> _csAttributes, ("DefaultOs" .=) <$> _csDefaultOS, ("UseOpsworksSecurityGroups" .=) <$> _csUseOpsworksSecurityGroups, ("UseCustomCookbooks" .=) <$> _csUseCustomCookbooks, ("DefaultSubnetId" .=) <$> _csDefaultSubnetId, ("ConfigurationManager" .=) <$> _csConfigurationManager, ("HostnameTheme" .=) <$> _csHostnameTheme, Just ("Name" .= _csName), Just ("Region" .= _csRegion), Just ("ServiceRoleArn" .= _csServiceRoleARN), Just ("DefaultInstanceProfileArn" .= _csDefaultInstanceProfileARN)]) instance ToPath CreateStack where toPath = const "/" instance ToQuery CreateStack where toQuery = const mempty -- | Contains the response to a 'CreateStack' request. -- -- /See:/ 'createStackResponse' smart constructor. data CreateStackResponse = CreateStackResponse' { _crsStackId :: !(Maybe Text) , _crsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateStackResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crsStackId' -- -- * 'crsResponseStatus' createStackResponse :: Int -- ^ 'crsResponseStatus' -> CreateStackResponse createStackResponse pResponseStatus_ = CreateStackResponse' { _crsStackId = Nothing , _crsResponseStatus = pResponseStatus_ } -- | The stack ID, which is an opaque string that you use to identify the -- stack when performing actions such as 'DescribeStacks'. crsStackId :: Lens' CreateStackResponse (Maybe Text) crsStackId = lens _crsStackId (\ s a -> s{_crsStackId = a}); -- | The response status code. crsResponseStatus :: Lens' CreateStackResponse Int crsResponseStatus = lens _crsResponseStatus (\ s a -> s{_crsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/CreateStack.hs
mpl-2.0
19,930
0
13
3,987
2,196
1,359
837
233
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- | Chris Done's style. -- -- Documented here: <https://github.com/chrisdone/haskell-style-guide> module HIndent.Styles.ChrisDone where import HIndent.Pretty import HIndent.Comments import HIndent.Types import Control.Monad import Control.Monad.Loops import Control.Monad.State.Class import Data.Int import Data.Maybe import Language.Haskell.Exts (parseExpWithComments) import Language.Haskell.Exts.Fixity import Language.Haskell.Exts.Syntax import Language.Haskell.Exts.Parser (ParseResult(..)) import Prelude hiding (exp) import Data.Monoid -------------------------------------------------------------------------------- -- Style configuration -- | A short function name. shortName :: Int64 shortName = 10 -- | Column limit: 50 smallColumnLimit :: Int64 smallColumnLimit = 50 -- | Empty state. data State = State -- | The printer style. chrisDone :: Style chrisDone = Style {styleName = "chris-done" ,styleAuthor = "Chris Done" ,styleDescription = "Chris Done's personal style. Documented here: <https://github.com/chrisdone/haskell-style-guide>" ,styleInitialState = State ,styleExtenders = [Extender exp ,Extender fieldupdate ,Extender fieldpattern ,Extender rhs ,Extender contextualGuardedRhs ,Extender stmt ,Extender decl ,Extender match ,Extender types] ,styleDefConfig = defaultConfig {configMaxColumns = 80 ,configIndentSpaces = 2} ,styleCommentPreprocessor = return} -------------------------------------------------------------------------------- -- Extenders types :: Type NodeInfo -> Printer s () types (TyTuple _ boxed tys) = depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do (fits,_) <- fitsOnOneLine p if fits then p else prefixedLined "," (map pretty tys) write (case boxed of Unboxed -> "#)" Boxed -> ")")) where p = commas (map pretty tys) types e = prettyNoExt e -- | Pretty print type signatures like -- -- foo :: (Show x,Read x) -- => (Foo -> Bar) -- -> Maybe Int -- -> (Char -> X -> Y) -- -> IO () -- decl :: Decl NodeInfo -> Printer s () decl (TypeDecl _ head ty) = do write "type " pretty head write " = " (fits,st) <- fitsOnOneLine (pretty ty) if fits then put st else do newline indented 2 (pretty ty) decl (TypeSig _ names ty') = do (fitting,st) <- isSmallFitting dependent if fitting then put st else do inter (write ", ") (map pretty names) newline indentSpaces <- getIndentSpaces indented indentSpaces (depend (write ":: ") (declTy ty')) where dependent = depend (do inter (write ", ") (map pretty names) write " :: ") (declTy ty') declTy dty = case dty of TyForall _ mbinds mctx ty -> do case mbinds of Nothing -> return () Just ts -> do write "forall " spaced (map pretty ts) write ". " newline case mctx of Nothing -> prettyTy ty Just ctx -> do pretty ctx newline indented (-3) (depend (write "=> ") (prettyTy ty)) _ -> prettyTy dty collapseFaps (TyFun _ arg result) = arg : collapseFaps result collapseFaps e = [e] prettyTy ty = do (fits,st) <- fitsOnOneLine (pretty ty) if fits then put st else case collapseFaps ty of [] -> pretty ty tys -> prefixedLined "-> " (map pretty tys) decl e = prettyNoExt e -- | Patterns of function declarations match :: Match NodeInfo -> Printer t () match (Match _ name pats rhs mbinds) = do orig <- gets psIndentLevel dependBind (do (short,st) <- isShort name put st space return short) (\headIsShort -> do let flats = map isFlatPat pats flatish = length (filter not flats) < 2 if (headIsShort && flatish) || all id flats then do ((singleLiner,overflow),st) <- sandboxNonOverflowing pats if singleLiner && not overflow then put st else multi orig pats headIsShort else multi orig pats headIsShort) withCaseContext False (pretty rhs) case mbinds of Nothing -> return () Just binds -> do newline indentSpaces <- getIndentSpaces indented indentSpaces (depend (write "where ") (pretty binds)) match e = prettyNoExt e -- | I want field updates to be dependent or newline. fieldupdate :: FieldUpdate NodeInfo -> Printer t () fieldupdate e = case e of FieldUpdate _ n e' -> dependOrNewline (do pretty n write " = ") e' pretty _ -> prettyNoExt e -- | Record field pattern, handled the same as record field updates fieldpattern :: PatField NodeInfo -> Printer t () fieldpattern e = case e of PFieldPat _ n e' -> dependOrNewline (do pretty n write " = ") e' pretty _ -> prettyNoExt e -- | Right-hand sides are dependent. rhs :: Rhs NodeInfo -> Printer t () rhs grhs = do inCase <- gets psInsideCase if inCase then unguardedalt grhs else unguardedrhs grhs -- | Right-hand sides are dependent. unguardedrhs :: Rhs NodeInfo -> Printer t () unguardedrhs (UnGuardedRhs _ e) = do indentSpaces <- getIndentSpaces indented indentSpaces (dependOrNewline (write " = ") e pretty) unguardedrhs e = prettyNoExt e -- | Unguarded case alts. unguardedalt :: Rhs NodeInfo -> Printer t () unguardedalt (UnGuardedRhs _ e) = dependOrNewline (write " -> ") e (indented 2 . pretty) unguardedalt e = prettyNoExt e -- | Decide whether to do alts or rhs based on the context. contextualGuardedRhs :: GuardedRhs NodeInfo -> Printer t () contextualGuardedRhs grhs = do inCase <- gets psInsideCase if inCase then guardedalt grhs else guardedrhs grhs -- | I want guarded RHS be dependent or newline. guardedrhs :: GuardedRhs NodeInfo -> Printer t () guardedrhs (GuardedRhs _ stmts e) = indented 1 (do prefixedLined "," (map (\p -> do space pretty p) stmts) dependOrNewline (write " = ") e (indented 1 . pretty)) -- | I want guarded alts be dependent or newline. guardedalt :: GuardedRhs NodeInfo -> Printer t () guardedalt (GuardedRhs _ stmts e) = indented 1 (do (prefixedLined "," (map (\p -> do space pretty p) stmts)) dependOrNewline (write " -> ") e (indented 1 . pretty)) -- Do statements need to handle infix expression indentation specially because -- do x * -- y -- is two invalid statements, not one valid infix op. stmt :: Stmt NodeInfo -> Printer t () stmt (Qualifier _ e@(InfixApp _ a op b)) = do col <- fmap (psColumn . snd) (sandbox (write "")) infixApp e a op b (Just col) stmt (Generator _ p e) = do indentSpaces <- getIndentSpaces pretty p indented indentSpaces (dependOrNewline (write " <- ") e pretty) stmt e = prettyNoExt e -- | Expressions exp :: Exp NodeInfo -> Printer t () exp e@(QuasiQuote _ "i" s) = do parseMode <- gets psParseMode case parseExpWithComments parseMode s of ParseOk (e',comments) -> do depend (do write "[" string "i" write "|") (do exp (snd (annotateComments (fromMaybe e' (applyFixities baseFixities e')) comments)) write "|]") _ -> prettyNoExt e -- Infix applications will render on one line if possible, otherwise -- if any of the arguments are not "flat" then that expression is -- line-separated. exp e@(InfixApp _ a op b) = infixApp e a op b Nothing -- | We try to render everything on a flat line. More than one of the -- arguments are not flat and it wouldn't be a single liner. -- If the head is short we depend, otherwise we swing. exp (App _ op a) = do orig <- gets psIndentLevel dependBind (do (short,st) <- isShort f put st space return short) (\headIsShort -> do let flats = map isFlatExp args flatish = length (filter not flats) < 2 if (headIsShort && flatish) || all id flats then do ((singleLiner,overflow),st) <- sandboxNonOverflowing args if singleLiner && not overflow then put st else multi orig args headIsShort else multi orig args headIsShort) where (f,args) = flatten op [a] flatten :: Exp NodeInfo -> [Exp NodeInfo] -> (Exp NodeInfo,[Exp NodeInfo]) flatten (App _ f' a') b = flatten f' (a' : b) flatten f' as = (f',as) -- | Lambdas are dependent if they can be. exp (Lambda _ ps b) = depend (write "\\" >> maybeSpace) (do spaced (map pretty ps) dependOrNewline (write " -> ") b (indented 1 . pretty)) where maybeSpace = case ps of (PBangPat {}):_ -> space (PIrrPat {}):_ -> space _ -> return () exp (Tuple _ boxed exps) = depend (write (case boxed of Unboxed -> "(#" Boxed -> "(")) (do (fits,_) <- fitsOnOneLine p if fits then p else prefixedLined "," (map pretty exps) write (case boxed of Unboxed -> "#)" Boxed -> ")")) where p = commas (map pretty exps) exp (List _ es) = do (ok,st) <- sandbox renderFlat if ok then put st else brackets (prefixedLined "," (map pretty es)) where renderFlat = do line <- gets psLine brackets (commas (map pretty es)) st <- get columnLimit <- getColumnLimit let overflow = psColumn st > columnLimit single = psLine st == line return (not overflow && single) exp (ListComp _ e qstmt) = brackets (do pretty e unless (null qstmt) (do (ok,st) <- sandbox oneLiner if ok then put st else lined)) where oneLiner = do line <- gets psLine write "|" commas (map pretty qstmt) st <- get columnLimit <- getColumnLimit let overflow = psColumn st > columnLimit single = psLine st == line return (not overflow && single) lined = do newline indented (-1) (write "|") prefixedLined "," (map pretty qstmt) exp e = prettyNoExt e -------------------------------------------------------------------------------- -- Indentation helpers -- | Sandbox and render the nodes on multiple lines, returning whether -- each is a single line. sandboxSingles :: Pretty ast => [ast NodeInfo] -> Printer t (Bool,PrintState t) sandboxSingles args = sandbox (allM (\(i,arg) -> do when (i /= (0 :: Int)) newline line <- gets psLine pretty arg st <- get return (psLine st == line)) (zip [0 ..] args)) -- | Render multi-line nodes. multi :: Pretty ast => Int64 -> [ast NodeInfo] -> Bool -> Printer t () multi orig args headIsShort = if headIsShort then lined (map pretty args) else do (allAreSingle,st) <- sandboxSingles args if allAreSingle then put st else do newline indentSpaces <- getIndentSpaces column (orig + indentSpaces) (lined (map pretty args)) -- | Sandbox and render the node on a single line, return whether it's -- on a single line and whether it's overflowing. sandboxNonOverflowing :: Pretty ast => [ast NodeInfo] -> Printer t ((Bool,Bool),PrintState t) sandboxNonOverflowing args = sandbox (do line <- gets psLine columnLimit <- getColumnLimit singleLineRender st <- get return (psLine st == line,psColumn st > columnLimit + 20)) where singleLineRender = spaced (map pretty args) -------------------------------------------------------------------------------- -- Predicates -- | Is the expression "short"? Used for app heads. isShort :: (Pretty ast) => ast NodeInfo -> Printer t (Bool,PrintState t) isShort p = do line <- gets psLine orig <- fmap (psColumn . snd) (sandbox (write "")) (_,st) <- sandbox (pretty p) return (psLine st == line && (psColumn st < orig + shortName) ,st) -- | Is the given expression "small"? I.e. does it fit on one line and -- under 'smallColumnLimit' columns. isSmall :: MonadState (PrintState t) m => m a -> m (Bool,PrintState t) isSmall p = do line <- gets psLine (_,st) <- sandbox p return (psLine st == line && psColumn st < smallColumnLimit,st) -- | Is the given expression "small"? I.e. does it fit under -- 'smallColumnLimit' columns. isSmallFitting :: MonadState (PrintState t) m => m a -> m (Bool,PrintState t) isSmallFitting p = do (_,st) <- sandbox p return (psColumn st < smallColumnLimit,st) isFlatPat :: Pat NodeInfo -> Bool isFlatPat (PApp _ _ b) = all isFlatPat b where isName (PVar{}) = True isName _ = False isFlatPat (PAsPat _ _ b) = isFlatPat b isFlatPat (PInfixApp _ a _ b) = isFlatPat a && isFlatPat b isFlatPat (PList _ []) = True isFlatPat PVar{} = True isFlatPat PLit{} = True isFlatPat _ = False -- | Is an expression flat? isFlatExp :: Exp NodeInfo -> Bool isFlatExp (Lambda _ _ e) = isFlatExp e isFlatExp (App _ a b) = isName a && isName b where isName (Var{}) = True isName _ = False isFlatExp (InfixApp _ a _ b) = isFlatExp a && isFlatExp b isFlatExp (NegApp _ a) = isFlatExp a isFlatExp VarQuote{} = True isFlatExp TypQuote{} = True isFlatExp (List _ []) = True isFlatExp Var{} = True isFlatExp Lit{} = True isFlatExp Con{} = True isFlatExp (LeftSection _ e _) = isFlatExp e isFlatExp (RightSection _ _ e) = isFlatExp e isFlatExp _ = False -- | Does printing the given thing overflow column limit? (e.g. 80) fitsOnOneLine :: MonadState (PrintState s) m => m a -> m (Bool,PrintState s) fitsOnOneLine p = do line <- gets psLine (_,st) <- sandbox p columnLimit <- getColumnLimit return (psLine st == line && psColumn st < columnLimit,st) -- | Does printing the given thing overflow column limit? (e.g. 80) fitsInColumnLimit :: Printer t a -> Printer t (Bool,PrintState t) fitsInColumnLimit p = do (_,st) <- sandbox p columnLimit <- getColumnLimit return (psColumn st < columnLimit,st) -------------------------------------------------------------------------------- -- Helpers infixApp :: Exp NodeInfo -> Exp NodeInfo -> QOp NodeInfo -> Exp NodeInfo -> Maybe Int64 -> Printer s () infixApp e a op b indent = do (fits,st) <- fitsOnOneLine (spaced (map (\link -> case link of OpChainExp e' -> pretty e' OpChainLink qop -> pretty qop) (flattenOpChain e))) if fits then put st else do prettyWithIndent a space pretty op newline case indent of Nothing -> prettyWithIndent b Just col -> do indentSpaces <- getIndentSpaces column (col + indentSpaces) (prettyWithIndent b) where prettyWithIndent e' = case e' of (InfixApp _ a' op' b') -> infixApp e' a' op' b' indent _ -> pretty e' -- | A link in a chain of operator applications. data OpChainLink l = OpChainExp (Exp l) | OpChainLink (QOp l) deriving (Show) -- | Flatten a tree of InfixApp expressions into a chain of operator -- links. flattenOpChain :: Exp l -> [OpChainLink l] flattenOpChain (InfixApp _ left op right) = flattenOpChain left <> [OpChainLink op] <> flattenOpChain right flattenOpChain e = [OpChainExp e] -- | Make the right hand side dependent if it's flat, otherwise -- newline it. dependOrNewline :: Pretty ast => Printer t () -> ast NodeInfo -> (ast NodeInfo -> Printer t ()) -> Printer t () dependOrNewline left right f = do (fits,st) <- fitsOnOneLine (depend left (f right)) if fits then put st else do left newline (f right)
ennocramer/hindent
src/HIndent/Styles/ChrisDone.hs
bsd-3-clause
18,807
0
24
7,261
5,132
2,517
2,615
482
12
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative ((<$>)) import Data.Monoid import qualified Data.Text as T import qualified Graphics.Vty as V import qualified Brick.Main as M import Brick.Util (fg, bg, on) import qualified Brick.AttrMap as A import Brick.Widgets.Core ( Widget , (<=>) , (<+>) , vLimit , hLimit , hBox , updateAttrMap , withBorderStyle , txt ) import qualified Brick.Widgets.Center as C import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.Border.Style as BS styles :: [(T.Text, BS.BorderStyle)] styles = [ ("ascii", BS.ascii) , ("unicode", BS.unicode) , ("unicode bold", BS.unicodeBold) , ("unicode rounded", BS.unicodeRounded) , ("custom", custom) , ("from 'x'", BS.borderStyleFromChar 'x') ] custom :: BS.BorderStyle custom = BS.BorderStyle { BS.bsCornerTL = '/' , BS.bsCornerTR = '\\' , BS.bsCornerBR = '/' , BS.bsCornerBL = '\\' , BS.bsIntersectFull = '.' , BS.bsIntersectL = '.' , BS.bsIntersectR = '.' , BS.bsIntersectT = '.' , BS.bsIntersectB = '.' , BS.bsHorizontal = '*' , BS.bsVertical = '!' } borderDemos :: [Widget] borderDemos = mkBorderDemo <$> styles mkBorderDemo :: (T.Text, BS.BorderStyle) -> Widget mkBorderDemo (styleName, sty) = withBorderStyle sty $ B.borderWithLabel "label" $ vLimit 5 $ C.vCenter $ txt $ " " <> styleName <> " style " borderMappings :: [(A.AttrName, V.Attr)] borderMappings = [ (B.borderAttr, V.yellow `on` V.black) , (B.vBorderAttr, V.green `on` V.red) , (B.hBorderAttr, V.white `on` V.green) , (B.hBorderLabelAttr, fg V.blue) , (B.tlCornerAttr, bg V.red) , (B.trCornerAttr, bg V.blue) , (B.blCornerAttr, bg V.yellow) , (B.brCornerAttr, bg V.green) ] colorDemo :: Widget colorDemo = updateAttrMap (A.applyAttrMappings borderMappings) $ B.borderWithLabel "title" $ hLimit 20 $ vLimit 5 $ C.center $ "colors!" ui :: Widget ui = hBox borderDemos <=> B.hBorder <=> colorDemo <=> B.hBorderWithLabel "horizontal border label" <=> (C.center "Left of vertical border" <+> B.vBorder <+> C.center "Right of vertical border") main :: IO () main = M.simpleMain ui
FranklinChen/brick
programs/BorderDemo.hs
bsd-3-clause
2,502
0
13
732
721
429
292
81
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} -- | This module provides a parser and printer for the low-level IRC -- message format. module Irc.Format ( UserInfo(..) , RawIrcMsg(..) , parseRawIrcMsg , renderRawIrcMsg , parseUserInfo , renderUserInfo , Identifier , mkId , idBytes , idDenote , asUtf8 , ircFoldCase ) where import Control.Applicative import Control.Monad (when) import Data.Array import Data.Attoparsec.ByteString.Char8 as P import Data.ByteString (ByteString) import Data.ByteString.Builder (Builder) import Data.Functor import Data.Monoid import Data.String import Data.Text (Text) import Data.Time (UTCTime) import Data.Word (Word8) import qualified Data.ByteString as B import qualified Data.ByteString.Builder as Builder import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as L import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Irc.Time (myParseTime) -- | 'UserInfo' packages a nickname along with the username and hsotname -- if they are known in the current context. data UserInfo = UserInfo { userNick :: Identifier , userName :: Maybe ByteString , userHost :: Maybe ByteString } deriving (Read, Show) -- | 'RawIrcMsg' breaks down the IRC protocol into its most basic parts. -- The "trailing" parameter indicated in the IRC protocol with a leading -- colon will appear as the last parameter in the parameter list. -- -- Note that RFC 2812 specifies a maximum of 15 parameters. -- -- @:prefix COMMAND param0 param1 param2 .. paramN@ data RawIrcMsg = RawIrcMsg { msgTime :: Maybe UTCTime , msgPrefix :: Maybe UserInfo , msgCommand :: ByteString , msgParams :: [ByteString] } deriving (Read, Show) -- | Case insensitive identifier representing channels and nicknames data Identifier = Identifier ByteString ByteString deriving (Read, Show) -- Equality on normalized 'Identifiers' instance Eq Identifier where x == y = idDenote x == idDenote y -- Comparison on normalized 'Identifiers' instance Ord Identifier where compare x y = compare (idDenote x) (idDenote y) instance IsString Identifier where fromString = mkId . fromString -- | Construct an 'Identifier' from a 'ByteString' mkId :: ByteString -> Identifier mkId x = Identifier x (ircFoldCase x) -- | Returns the original 'ByteString' of an 'Identifier' idBytes :: Identifier -> ByteString idBytes (Identifier x _) = x -- | Returns the case-normalized 'ByteString' of an 'Identifier' -- which is suitable for comparison. idDenote :: Identifier -> ByteString idDenote (Identifier _ x) = x -- | Attempt to split an IRC protocol message without its trailing newline -- information into a structured message. parseRawIrcMsg :: ByteString -> Maybe RawIrcMsg parseRawIrcMsg x = case parseOnly rawIrcMsgParser x of Left{} -> Nothing Right r -> Just r -- | RFC 2812 specifies that there can only be up to -- 14 "middle" parameters, after that the fifteenth is -- the final parameter and the trailing : is optional! maxMiddleParams :: Int maxMiddleParams = 14 -- Excerpt from https://tools.ietf.org/html/rfc2812#section-2.3.1 -- message = [ ":" prefix SPACE ] command [ params ] crlf -- prefix = servername / ( nickname [ [ "!" user ] "@" host ] ) -- command = 1*letter / 3digit -- params = *14( SPACE middle ) [ SPACE ":" trailing ] -- =/ 14( SPACE middle ) [ SPACE [ ":" ] trailing ] -- nospcrlfcl = %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF -- ; any octet except NUL, CR, LF, " " and ":" -- middle = nospcrlfcl *( ":" / nospcrlfcl ) -- trailing = *( ":" / " " / nospcrlfcl ) -- SPACE = %x20 ; space character -- crlf = %x0D %x0A ; "carriage return" "linefeed" -- | Parse a whole IRC message assuming that the trailing -- newlines have already been removed. This parser will -- parse valid messages correctly but will also accept some -- invalid messages. Presumably the server isn't sending -- invalid messages! rawIrcMsgParser :: Parser RawIrcMsg rawIrcMsgParser = do time <- guarded (string "@time=") timeParser prefix <- guarded (char ':') prefixParser cmd <- simpleTokenParser params <- paramsParser maxMiddleParams return RawIrcMsg { msgTime = time , msgPrefix = prefix , msgCommand = cmd , msgParams = params } -- | Parse the list of parameters in a raw message. The RFC -- allows for up to 15 parameters. paramsParser :: Int -> Parser [ByteString] paramsParser n = do _ <- skipMany (char ' ') -- Freenode requires this exception endOfInput $> [] <|> more where more | n == 0 = do _ <- optional (char ':') finalParam | otherwise = do mbColon <- optional (char ':') case mbColon of Just{} -> finalParam Nothing -> middleParam finalParam = do x <- takeByteString let !x' = B.copy x return [x'] middleParam = do x <- P.takeWhile (/= ' ') when (B8.null x) (fail "Empty middle parameter") let !x' = B.copy x xs <- paramsParser (n-1) return (x':xs) -- | Parse the server-time message prefix: -- @time=2015-03-04T22:29:04.064Z timeParser :: Parser UTCTime timeParser = do timeBytes <- simpleTokenParser _ <- char ' ' case parseIrcTime (B8.unpack timeBytes) of Nothing -> fail "Bad server-time format" Just t -> return t parseIrcTime :: String -> Maybe UTCTime parseIrcTime = myParseTime "%Y-%m-%dT%H:%M:%S%Q%Z" prefixParser :: Parser UserInfo prefixParser = do tok <- simpleTokenParser _ <- char ' ' return (parseUserInfo tok) -- | Take the bytes up to the next space delimiter simpleTokenParser :: Parser ByteString simpleTokenParser = do xs <- P.takeWhile (/= ' ') when (B8.null xs) (fail "Empty token") return $! B8.copy xs -- | Take the bytes up to the next space delimiter. -- If the first character of this token is a ':' -- then take the whole remaining bytestring -- | Render 'UserInfo' as @nick!username\@hostname@ renderUserInfo :: UserInfo -> ByteString renderUserInfo u = idBytes (userNick u) <> maybe B.empty ("!" <>) (userName u) <> maybe B.empty ("@" <>) (userHost u) -- | Split up a hostmask into a nickname, username, and hostname. -- The username and hostname might not be defined but are delimited by -- a @!@ and @\@@ respectively. parseUserInfo :: ByteString -> UserInfo parseUserInfo x = UserInfo { userNick = mkId nick , userName = if B.null user then Nothing else Just (B.drop 1 user) , userHost = if B.null host then Nothing else Just (B.drop 1 host) } where (nickuser,host) = B8.break (=='@') x (nick,user) = B8.break (=='!') nickuser -- | Serialize a structured IRC protocol message back into its wire -- format. This command adds the required trailing newline. renderRawIrcMsg :: RawIrcMsg -> ByteString renderRawIrcMsg m = L.toStrict $ Builder.toLazyByteString $ maybe mempty renderPrefix (msgPrefix m) <> Builder.byteString (msgCommand m) <> buildParams (msgParams m) <> Builder.word8 13 <> Builder.word8 10 renderPrefix :: UserInfo -> Builder renderPrefix u = Builder.char8 ':' <> Builder.byteString (renderUserInfo u) <> Builder.char8 ' ' -- | Build concatenate a list of parameters into a single, space- -- delimited bytestring. Use a colon for the last parameter if it contains -- a colon or a space. buildParams :: [ByteString] -> Builder buildParams [x] | B.elem 32 x || B.elem 58 x = Builder.word8 32 <> Builder.word8 58 <> Builder.byteString x buildParams (x:xs) = Builder.word8 32 <> Builder.byteString x <> buildParams xs buildParams [] = mempty -- | When the first parser succeeds require the second parser to succeed. -- Otherwise return Nothing guarded :: Parser a -> Parser b -> Parser (Maybe b) guarded pa pb = do mb <- optional pa case mb of Nothing -> return Nothing Just{} -> fmap Just pb -- | Capitalize a string according to RFC 2812 -- Latin letters are capitalized and {|}~ are mapped to [\]^ ircFoldCase :: ByteString -> ByteString ircFoldCase = B.map (B.index casemap . fromIntegral) casemap :: ByteString casemap = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\ \\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\ \ !\"#$%&'()*+,-./0123456789:;<=>?\ \@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\ \`ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^\x7f\ \\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\ \\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\ \\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\ \\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\ \\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\ \\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\ \\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\ \\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" -- Try to decode a message as UTF-8. If that fails interpret it as Windows CP1252 -- This helps deal with clients like XChat that get clever and otherwise misconfigured -- clients. asUtf8 :: ByteString -> Text asUtf8 x = case Text.decodeUtf8' x of Right txt -> txt Left{} -> decodeCP1252 x decodeCP1252 :: ByteString -> Text decodeCP1252 = Text.pack . map (cp1252!) . B.unpack cp1252 :: Array Word8 Char cp1252 = listArray (0,255) ['\NUL','\SOH','\STX','\ETX','\EOT','\ENQ','\ACK','\a','\b','\t','\n','\v','\f','\r','\SO','\SI', '\DLE','\DC1','\DC2','\DC3','\DC4','\NAK','\SYN','\ETB','\CAN','\EM','\SUB','\ESC','\FS','\GS','\RS','\US', ' ','!','\"','#','$','%','&','\'','(',')','*','+',',','-','.','/', '0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?', '@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_', '`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z','{','|','}','~','\DEL', '\8364','\129','\8218','\402','\8222','\8230','\8224','\8225','\710','\8240','\352','\8249','\338','\141','\381','\143', '\144','\8216','\8217','\8220','\8221','\8226','\8211','\8212','\732','\8482','\353','\8250','\339','\157','\382','\376', '\160','\161','\162','\163','\164','\165','\166','\167','\168','\169','\170','\171','\172','\173','\174','\175', '\176','\177','\178','\179','\180','\181','\182','\183','\184','\185','\186','\187','\188','\189','\190','\191', '\192','\193','\194','\195','\196','\197','\198','\199','\200','\201','\202','\203','\204','\205','\206','\207', '\208','\209','\210','\211','\212','\213','\214','\215','\216','\217','\218','\219','\220','\221','\222','\223', '\224','\225','\226','\227','\228','\229','\230','\231','\232','\233','\234','\235','\236','\237','\238','\239', '\240','\241','\242','\243','\244','\245','\246','\247','\248','\249','\250','\251','\252','\253','\254','\255']
bitemyapp/irc-core
src/Irc/Format.hs
bsd-3-clause
11,276
0
13
2,165
2,128
1,168
960
182
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} module Database.DSH.Translate.VSL2Algebra ( VecBuild , runVecBuild , vl2Algebra ) where import qualified Data.IntMap as IM import Data.List import qualified Data.Traversable as T import Control.Monad.State import qualified Database.Algebra.Dag.Build as B import Database.Algebra.Dag.Common import Database.DSH.Common.Impossible import Database.DSH.Common.QueryPlan import qualified Database.DSH.Common.Vector as V import Database.DSH.Common.VectorLang import qualified Database.DSH.VSL.Lang as VSL import Database.DSH.VSL.VirtualSegmentAlgebra -- FIXME the vector types d r are determined by the algebra a. -- The only type variable necessary should be a. type Cache d r = IM.IntMap (Res d r) -- | A layer on top of the DAG builder monad that caches the -- translation result of VSL nodes. type VecBuild a d r = StateT (Cache d r) (B.Build a) runVecBuild :: VecBuild a (VSLDVec a) (VSLRVec a) r -> B.Build a r runVecBuild c = evalStateT c IM.empty data Res d r = RRVec r | RDVec d | RLPair (Res d r) (Res d r) | RTriple (Res d r) (Res d r) (Res d r) deriving Show fromDict :: AlgNode -> VecBuild a d r (Maybe (Res d r)) fromDict n = gets (IM.lookup n) insertTranslation :: AlgNode -> Res d r -> VecBuild a d r () insertTranslation n res = modify (IM.insert n res) -------------------------------------------------------------------------------- -- Wrappers and unwrappers for vector references fromRVec :: r -> Res d r fromRVec p = RRVec p fromDVec :: d -> Res d r fromDVec v = RDVec v toDVec :: Res d r -> d toDVec (RDVec v) = v toDVec _ = error "toDVec: Not a RDVec" toRVec :: Res d r -> r toRVec (RRVec p) = p toRVec _ = error "toRVec: Not a replication vector" -------------------------------------------------------------------------------- -- | Refresh vectors in a shape from the cache. refreshShape :: VirtualSegmentAlgebra a => Shape V.DVec -> VecBuild a d r (Shape d) refreshShape shape = T.mapM refreshVec shape where refreshVec (V.DVec n) = do mv <- fromDict n case mv of Just v -> return $ toDVec v Nothing -> $impossible translate :: VirtualSegmentAlgebra a => NodeMap VSL.TVSL -> AlgNode -> VecBuild a (VSLDVec a) (VSLRVec a) (Res (VSLDVec a) (VSLRVec a)) translate vlNodes n = do r <- fromDict n case r of -- The VSL node has already been encountered and translated. Just res -> return $ res -- The VSL node has not been translated yet. Nothing -> do let vlOp = getVSL n vlNodes r' <- case VSL.unVSL vlOp of TerOp t c1 c2 c3 -> do c1' <- translate vlNodes c1 c2' <- translate vlNodes c2 c3' <- translate vlNodes c3 lift $ translateTerOp t c1' c2' c3' BinOp b c1 c2 -> do c1' <- translate vlNodes c1 c2' <- translate vlNodes c2 lift $ translateBinOp b c1' c2' UnOp u c1 -> do c1' <- translate vlNodes c1 lift $ translateUnOp u c1' NullaryOp o -> lift $ translateNullary o insertTranslation n r' return r' getVSL :: AlgNode -> NodeMap VSL.TVSL -> VSL.TVSL getVSL n vlNodes = case IM.lookup n vlNodes of Just op -> op Nothing -> error $ "getVSL: node " ++ (show n) ++ " not in VSL nodes map " ++ (pp vlNodes) pp :: NodeMap VSL.TVSL -> String pp m = intercalate ",\n" $ map show $ IM.toList m vl2Algebra :: VirtualSegmentAlgebra a => NodeMap VSL.TVSL -> Shape V.DVec -> B.Build a (Shape (VSLDVec a)) vl2Algebra vlNodes plan = runVecBuild $ do mapM_ (translate vlNodes) roots refreshShape plan where roots :: [AlgNode] roots = shapeNodes plan translateTerOp :: VirtualSegmentAlgebra a => VSL.TerOp -> Res (VSLDVec a) (VSLRVec a) -> Res (VSLDVec a) (VSLRVec a) -> Res (VSLDVec a) (VSLRVec a) -> B.Build a (Res (VSLDVec a) (VSLRVec a)) translateTerOp t c1 c2 c3 = case t of VSL.Combine -> do (d, r1, r2) <- vecCombine (toDVec c1) (toDVec c2) (toDVec c3) return $ RTriple (fromDVec d) (fromRVec r1) (fromRVec r2) translateBinOp :: VirtualSegmentAlgebra a => VSL.BinOp TExpr -> Res (VSLDVec a) (VSLRVec a) -> Res (VSLDVec a) (VSLRVec a) -> B.Build a (Res (VSLDVec a) (VSLRVec a)) translateBinOp b c1 c2 = case b of VSL.ReplicateSeg -> do (v, p) <- vecReplicateSeg (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec p) VSL.ReplicateScalar -> do (v, p) <- vecReplicateScalar (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec p) VSL.Materialize -> do (v, p) <- vecMaterialize (toRVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec p) VSL.UnboxSng -> do (v, k) <- vecUnboxSng (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec k) VSL.Append -> do (v, r1, r2) <- vecAppend (toDVec c1) (toDVec c2) return $ RTriple (fromDVec v) (fromRVec r1) (fromRVec r2) VSL.Align -> fromDVec <$> vecAlign (toDVec c1) (toDVec c2) VSL.Zip -> do (v, r1 ,r2) <- vecZip (toDVec c1) (toDVec c2) return $ RTriple (fromDVec v) (fromRVec r1) (fromRVec r2) VSL.CartProduct -> do (v, p1, p2) <- vecCartProduct (toDVec c1) (toDVec c2) return $ RTriple (fromDVec v) (fromRVec p1) (fromRVec p2) VSL.ThetaJoin (l1, l2, p) -> do (v, p1, p2) <- vecThetaJoin l1 l2 p (toDVec c1) (toDVec c2) return $ RTriple (fromDVec v) (fromRVec p1) (fromRVec p2) VSL.NestJoin (l1, l2, p) -> do (v, p1, p2) <- vecNestJoin l1 l2 p (toDVec c1) (toDVec c2) return $ RTriple (fromDVec v) (fromRVec p1) (fromRVec p2) VSL.GroupJoin (l1, l2, p, as) -> fromDVec <$> vecGroupJoin l1 l2 p as (toDVec c1) (toDVec c2) VSL.SemiJoin (l1, l2, p) -> do (v, r) <- vecSemiJoin l1 l2 p (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec r) VSL.AntiJoin (l1, l2, p) -> do (v, r) <- vecAntiJoin l1 l2 p (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec r) VSL.UnboxDefault vs -> do (v, r) <- vecUnboxDefault vs (toDVec c1) (toDVec c2) return $ RLPair (fromDVec v) (fromRVec r) VSL.UpdateMap -> fromRVec <$> vecUpdateMap (toRVec c1) (toRVec c2) translateUnOp :: VirtualSegmentAlgebra a => VSL.UnOp TExpr TExpr -> Res (VSLDVec a) (VSLRVec a) -> B.Build a (Res (VSLDVec a) (VSLRVec a)) translateUnOp unop c = case unop of VSL.Fold a -> fromDVec <$> vecFold a (toDVec c) VSL.Distinct -> fromDVec <$> vecDistinct (toDVec c) VSL.Number -> fromDVec <$> vecNumber (toDVec c) VSL.MergeMap -> fromRVec <$> vecMergeMap (toDVec c) VSL.WinFun (a, w) -> fromDVec <$> vecWinFun a w (toDVec c) VSL.Segment -> fromDVec <$> vecSegment (toDVec c) VSL.Unsegment -> fromDVec <$> vecUnsegment (toDVec c) VSL.Select e -> do (d, r) <- vecSelect e (toDVec c) return $ RLPair (fromDVec d) (fromRVec r) VSL.Sort e -> do (d, p) <- vecSort e (toDVec c) return $ RLPair (fromDVec d) (fromRVec p) VSL.Group es -> do (qo, qi, p) <- vecGroup es (toDVec c) return $ RTriple (fromDVec qo) (fromDVec qi) (fromRVec p) VSL.Project cols -> fromDVec <$> vecProject cols (toDVec c) VSL.Reverse -> do (d, p) <- vecReverse (toDVec c) return $ RLPair (fromDVec d) (fromRVec p) VSL.GroupAggr (g, as) -> fromDVec <$> vecGroupAggr g as (toDVec c) VSL.UnitMap -> fromRVec <$> vecUnitMap (toDVec c) VSL.UpdateUnit -> fromRVec <$> vecUpdateUnit (toRVec c) VSL.R1 -> case c of (RLPair c1 _) -> return c1 (RTriple c1 _ _) -> return c1 _ -> error "R1: Not a tuple" VSL.R2 -> case c of (RLPair _ c2) -> return c2 (RTriple _ c2 _) -> return c2 _ -> error "R2: Not a tuple" VSL.R3 -> case c of (RTriple _ _ c3) -> return c3 _ -> error "R3: Not a tuple" translateNullary :: VirtualSegmentAlgebra a => VSL.NullOp -> B.Build a (Res (VSLDVec a) (VSLRVec a)) translateNullary (VSL.Lit (tys, segs)) = fromDVec <$> vecLit tys segs translateNullary (VSL.TableRef (n, schema)) = fromDVec <$> vecTableRef n schema
ulricha/dsh
src/Database/DSH/Translate/VSL2Algebra.hs
bsd-3-clause
9,026
0
19
2,876
3,346
1,653
1,693
190
23
{-# LANGUAGE CPP #-} module Options.Applicative.Builder ( -- * Parser builders -- -- | This module contains utility functions and combinators to create parsers -- for individual options. -- -- Each parser builder takes an option modifier. A modifier can be created by -- composing the basic modifiers provided by this module using the 'Monoid' -- operations 'mempty' and 'mappend', or their aliases 'idm' and '<>'. -- -- For example: -- -- > out = strOption -- > ( long "output" -- > <> short 'o' -- > <> metavar "FILENAME" ) -- -- creates a parser for an option called \"output\". subparser, strArgument, argument, flag, flag', switch, abortOption, infoOption, strOption, option, nullOption, -- * Modifiers short, long, help, helpDoc, value, showDefaultWith, showDefault, metavar, eitherReader, noArgError, ParseError(..), hidden, internal, command, completeWith, action, completer, idm, #if __GLASGOW_HASKELL__ > 702 (<>), #endif mappend, -- * Readers -- -- | A collection of basic 'Option' readers. auto, str, disabled, readerAbort, readerError, -- * Builder for 'ParserInfo' InfoMod, fullDesc, briefDesc, header, headerDoc, footer, footerDoc, progDesc, progDescDoc, failureCode, noIntersperse, info, -- * Builder for 'ParserPrefs' PrefsMod, multiSuffix, disambiguate, showHelpOnError, noBacktrack, columns, prefs, defaultPrefs, -- * Types Mod, ReadM, OptionFields, FlagFields, ArgumentFields, CommandFields ) where import Control.Applicative (pure, (<|>)) import Data.Monoid (Monoid (..) #if __GLASGOW_HASKELL__ > 702 , (<>) #endif ) import Options.Applicative.Builder.Completer import Options.Applicative.Builder.Internal import Options.Applicative.Common import Options.Applicative.Types import Options.Applicative.Help.Pretty import Options.Applicative.Help.Chunk -- readers -- -- | 'Option' reader based on the 'Read' type class. auto :: Read a => ReadM a auto = eitherReader $ \arg -> case reads arg of [(r, "")] -> return r _ -> Left $ "cannot parse value `" ++ arg ++ "'" -- | String 'Option' reader. str :: ReadM String str = readerAsk -- | Null 'Option' reader. All arguments will fail validation. disabled :: ReadM a disabled = readerError "disabled option" -- modifiers -- -- | Specify a short name for an option. short :: HasName f => Char -> Mod f a short = fieldMod . name . OptShort -- | Specify a long name for an option. long :: HasName f => String -> Mod f a long = fieldMod . name . OptLong -- | Specify a default value for an option. -- -- /Note/: Because this modifier means the parser will never fail, -- do not use it with combinators such as 'some' or 'many', as -- these combinators continue until a failure occurs. -- Careless use will thus result in a hang. value :: HasValue f => a -> Mod f a value x = Mod id (DefaultProp (Just x) Nothing) id -- | Specify a function to show the default value for an option. showDefaultWith :: (a -> String) -> Mod f a showDefaultWith s = Mod id (DefaultProp Nothing (Just s)) id -- | Show the default value for this option using its 'Show' instance. showDefault :: Show a => Mod f a showDefault = showDefaultWith show -- | Specify the help text for an option. help :: String -> Mod f a help s = optionMod $ \p -> p { propHelp = paragraph s } -- | Specify the help text for an option as a 'Text.PrettyPrint.ANSI.Leijen.Doc' -- value. helpDoc :: Maybe Doc -> Mod f a helpDoc doc = optionMod $ \p -> p { propHelp = Chunk doc } -- | Convert a function in the 'Either' monad to a reader. eitherReader :: (String -> Either String a) -> ReadM a eitherReader f = readerAsk >>= either readerError return . f -- | Specify the error to display when no argument is provided to this option. noArgError :: ParseError -> Mod OptionFields a noArgError e = fieldMod $ \p -> p { optNoArgError = e } -- | Specify a metavariable for the argument. -- -- Metavariables have no effect on the actual parser, and only serve to specify -- the symbolic name for an argument to be displayed in the help text. metavar :: HasMetavar f => String -> Mod f a metavar var = optionMod $ \p -> p { propMetaVar = var } -- | Hide this option from the brief description. hidden :: Mod f a hidden = optionMod $ \p -> p { propVisibility = min Hidden (propVisibility p) } -- | Add a command to a subparser option. command :: String -> ParserInfo a -> Mod CommandFields a command cmd pinfo = fieldMod $ \p -> p { cmdCommands = (cmd, pinfo) : cmdCommands p } -- | Add a list of possible completion values. completeWith :: HasCompleter f => [String] -> Mod f a completeWith xs = completer (listCompleter xs) -- | Add a bash completion action. Common actions include @file@ and -- @directory@. See -- <http://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html#Programmable-Completion-Builtins> -- for a complete list. action :: HasCompleter f => String -> Mod f a action act = completer (bashCompleter act) -- | Add a completer to an argument. -- -- A completer is a function String -> IO String which, given a partial -- argument, returns all possible completions for that argument. completer :: HasCompleter f => Completer -> Mod f a completer f = fieldMod $ modCompleter (`mappend` f) -- parsers -- -- | Builder for a command parser. The 'command' modifier can be used to -- specify individual commands. subparser :: Mod CommandFields a -> Parser a subparser m = mkParser d g rdr where Mod _ d g = metavar "COMMAND" `mappend` m rdr = uncurry CmdReader (mkCommand m) -- | Builder for an argument parser. argument :: ReadM a -> Mod ArgumentFields a -> Parser a argument p (Mod f d g) = mkParser d g (ArgReader rdr) where ArgumentFields compl = f (ArgumentFields mempty) rdr = CReader compl p -- | Builder for a 'String' argument. strArgument :: Mod ArgumentFields String -> Parser String strArgument = argument str -- | Builder for a flag parser. -- -- A flag that switches from a \"default value\" to an \"active value\" when -- encountered. For a simple boolean value, use `switch` instead. flag :: a -- ^ default value -> a -- ^ active value -> Mod FlagFields a -- ^ option modifier -> Parser a flag defv actv m = flag' actv m <|> pure defv -- | Builder for a flag parser without a default value. -- -- Same as 'flag', but with no default value. In particular, this flag will -- never parse successfully by itself. -- -- It still makes sense to use it as part of a composite parser. For example -- -- > length <$> many (flag' () (short 't')) -- -- is a parser that counts the number of "-t" arguments on the command line. flag' :: a -- ^ active value -> Mod FlagFields a -- ^ option modifier -> Parser a flag' actv (Mod f d g) = mkParser d g rdr where rdr = let fields = f (FlagFields [] actv) in FlagReader (flagNames fields) (flagActive fields) -- | Builder for a boolean flag. -- -- > switch = flag False True switch :: Mod FlagFields Bool -> Parser Bool switch = flag False True -- | An option that always fails. -- -- When this option is encountered, the option parser immediately aborts with -- the given parse error. If you simply want to output a message, use -- 'infoOption' instead. abortOption :: ParseError -> Mod OptionFields (a -> a) -> Parser (a -> a) abortOption err m = option (readerAbort err) . (`mappend` m) $ mconcat [ noArgError err , value id , metavar "" ] -- | An option that always fails and displays a message. infoOption :: String -> Mod OptionFields (a -> a) -> Parser (a -> a) infoOption = abortOption . InfoMsg -- | Builder for an option taking a 'String' argument. strOption :: Mod OptionFields String -> Parser String strOption = option str -- | Same as 'option'. {-# DEPRECATED nullOption "Use 'option' instead" #-} nullOption :: ReadM a -> Mod OptionFields a -> Parser a nullOption = option -- | Builder for an option using the given reader. option :: ReadM a -> Mod OptionFields a -> Parser a option r m = mkParser d g rdr where Mod f d g = metavar "ARG" `mappend` m fields = f (OptionFields [] mempty (ErrorMsg "")) crdr = CReader (optCompleter fields) r rdr = OptReader (optNames fields) crdr (optNoArgError fields) -- | Modifier for 'ParserInfo'. newtype InfoMod a = InfoMod { applyInfoMod :: ParserInfo a -> ParserInfo a } instance Monoid (InfoMod a) where mempty = InfoMod id mappend m1 m2 = InfoMod $ applyInfoMod m2 . applyInfoMod m1 -- | Show a full description in the help text of this parser. fullDesc :: InfoMod a fullDesc = InfoMod $ \i -> i { infoFullDesc = True } -- | Only show a brief description in the help text of this parser. briefDesc :: InfoMod a briefDesc = InfoMod $ \i -> i { infoFullDesc = False } -- | Specify a header for this parser. header :: String -> InfoMod a header s = InfoMod $ \i -> i { infoHeader = paragraph s } -- | Specify a header for this parser as a 'Text.PrettyPrint.ANSI.Leijen.Doc' -- value. headerDoc :: Maybe Doc -> InfoMod a headerDoc doc = InfoMod $ \i -> i { infoHeader = Chunk doc } -- | Specify a footer for this parser. footer :: String -> InfoMod a footer s = InfoMod $ \i -> i { infoFooter = paragraph s } -- | Specify a footer for this parser as a 'Text.PrettyPrint.ANSI.Leijen.Doc' -- value. footerDoc :: Maybe Doc -> InfoMod a footerDoc doc = InfoMod $ \i -> i { infoFooter = Chunk doc } -- | Specify a short program description. progDesc :: String -> InfoMod a progDesc s = InfoMod $ \i -> i { infoProgDesc = paragraph s } -- | Specify a short program description as a 'Text.PrettyPrint.ANSI.Leijen.Doc' -- value. progDescDoc :: Maybe Doc -> InfoMod a progDescDoc doc = InfoMod $ \i -> i { infoProgDesc = Chunk doc } -- | Specify an exit code if a parse error occurs. failureCode :: Int -> InfoMod a failureCode n = InfoMod $ \i -> i { infoFailureCode = n } -- | Disable parsing of regular options after arguments noIntersperse :: InfoMod a noIntersperse = InfoMod $ \p -> p { infoIntersperse = False } -- | Create a 'ParserInfo' given a 'Parser' and a modifier. info :: Parser a -> InfoMod a -> ParserInfo a info parser m = applyInfoMod m base where base = ParserInfo { infoParser = parser , infoFullDesc = True , infoProgDesc = mempty , infoHeader = mempty , infoFooter = mempty , infoFailureCode = 1 , infoIntersperse = True } newtype PrefsMod = PrefsMod { applyPrefsMod :: ParserPrefs -> ParserPrefs } instance Monoid PrefsMod where mempty = PrefsMod id mappend m1 m2 = PrefsMod $ applyPrefsMod m2 . applyPrefsMod m1 multiSuffix :: String -> PrefsMod multiSuffix s = PrefsMod $ \p -> p { prefMultiSuffix = s } disambiguate :: PrefsMod disambiguate = PrefsMod $ \p -> p { prefDisambiguate = True } showHelpOnError :: PrefsMod showHelpOnError = PrefsMod $ \p -> p { prefShowHelpOnError = True } noBacktrack :: PrefsMod noBacktrack = PrefsMod $ \p -> p { prefBacktrack = False } columns :: Int -> PrefsMod columns cols = PrefsMod $ \p -> p { prefColumns = cols } prefs :: PrefsMod -> ParserPrefs prefs m = applyPrefsMod m base where base = ParserPrefs { prefMultiSuffix = "" , prefDisambiguate = False , prefShowHelpOnError = False , prefBacktrack = True , prefColumns = 80 } -- convenience shortcuts -- | Trivial option modifier. idm :: Monoid m => m idm = mempty -- | Default preferences. defaultPrefs :: ParserPrefs defaultPrefs = prefs idm
ntc2/optparse-applicative
Options/Applicative/Builder.hs
bsd-3-clause
11,662
0
14
2,538
2,635
1,462
1,173
215
2
{-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Hadrian.Oracles.TextFile -- Copyright : (c) Andrey Mokhov 2014-2018 -- License : MIT (see the file LICENSE) -- Maintainer : [email protected] -- Stability : experimental -- -- Read and parse text files, tracking their contents. This oracle can be used -- to read configuration or package metadata files and cache the parsing. ----------------------------------------------------------------------------- module Hadrian.Oracles.TextFile ( lookupValue, lookupValueOrEmpty, lookupValueOrError, lookupValues, lookupValuesOrEmpty, lookupValuesOrError, lookupDependencies, textFileOracle ) where import Control.Monad import qualified Data.HashMap.Strict as Map import Data.Maybe import Development.Shake import Development.Shake.Classes import Development.Shake.Config import Hadrian.Utilities -- | Lookup a value in a text file, tracking the result. Each line of the file -- is expected to have @key = value@ format. lookupValue :: FilePath -> String -> Action (Maybe String) lookupValue file key = askOracle $ KeyValue (file, key) -- | Like 'lookupValue' but returns the empty string if the key is not found. lookupValueOrEmpty :: FilePath -> String -> Action String lookupValueOrEmpty file key = fromMaybe "" <$> lookupValue file key -- | Like 'lookupValue' but raises an error if the key is not found. lookupValueOrError :: FilePath -> String -> Action String lookupValueOrError file key = fromMaybe (error msg) <$> lookupValue file key where msg = "Key " ++ quote key ++ " not found in file " ++ quote file -- | Lookup a list of values in a text file, tracking the result. Each line of -- the file is expected to have @key value1 value2 ...@ format. lookupValues :: FilePath -> String -> Action (Maybe [String]) lookupValues file key = askOracle $ KeyValues (file, key) -- | Like 'lookupValues' but returns the empty list if the key is not found. lookupValuesOrEmpty :: FilePath -> String -> Action [String] lookupValuesOrEmpty file key = fromMaybe [] <$> lookupValues file key -- | Like 'lookupValues' but raises an error if the key is not found. lookupValuesOrError :: FilePath -> String -> Action [String] lookupValuesOrError file key = fromMaybe (error msg) <$> lookupValues file key where msg = "Key " ++ quote key ++ " not found in file " ++ quote file -- | The 'Action' @lookupDependencies depFile file@ looks up dependencies of a -- @file@ in a (typically generated) dependency file @depFile@. The action -- returns a pair @(source, files)@, such that the @file@ can be produced by -- compiling @source@, which in turn also depends on a number of other @files@. lookupDependencies :: FilePath -> FilePath -> Action (FilePath, [FilePath]) lookupDependencies depFile file = do deps <- lookupValues depFile file case deps of Nothing -> error $ "No dependencies found for file " ++ quote file Just [] -> error $ "No source file found for file " ++ quote file Just (source : files) -> return (source, files) newtype KeyValue = KeyValue (FilePath, String) deriving (Binary, Eq, Hashable, NFData, Show, Typeable) type instance RuleResult KeyValue = Maybe String newtype KeyValues = KeyValues (FilePath, String) deriving (Binary, Eq, Hashable, NFData, Show, Typeable) type instance RuleResult KeyValues = Maybe [String] -- | These oracle rules are used to cache and track answers to the following -- queries, which are implemented by parsing text files: -- -- 1) Looking up key-value pairs formatted as @key = value1 value2 ...@ that -- are often used in text configuration files. See functions 'lookupValue', -- 'lookupValueOrEmpty', 'lookupValueOrError', 'lookupValues', -- 'lookupValuesOrEmpty' and 'lookupValuesOrError'. -- -- 2) Parsing Makefile dependency files generated by commands like @gcc -MM@: -- see 'lookupDependencies'. textFileOracle :: Rules () textFileOracle = do kv <- newCache $ \file -> do need [file] putLoud $ "| KeyValue oracle: reading " ++ quote file ++ "..." liftIO $ readConfigFile file void $ addOracleCache $ \(KeyValue (file, key)) -> Map.lookup key <$> kv file kvs <- newCache $ \file -> do need [file] putLoud $ "| KeyValues oracle: reading " ++ quote file ++ "..." contents <- map words <$> readFileLines file return $ Map.fromList [ (key, values) | (key:values) <- contents ] void $ addOracleCache $ \(KeyValues (file, key)) -> Map.lookup key <$> kvs file
sdiehl/ghc
hadrian/src/Hadrian/Oracles/TextFile.hs
bsd-3-clause
4,591
0
18
841
896
476
420
51
3
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE PatternSynonyms #-} -- | This module performs optimizations on the Nested Kernel Language (NKL). module Database.DSH.NKL.Opt ( opt ) where import Debug.Trace import qualified Data.Set as S import qualified Database.DSH.NKL.Lang as NKL import Database.DSH.NKL.Quote import Database.DSH.Common.Impossible
ulricha/dsh
src/Database/DSH/NKL/Opt.hs
bsd-3-clause
420
0
4
88
54
40
14
10
0
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.ByteOrder -- Copyright : (c) The University of Glasgow, 1994-2000 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Target byte ordering. -- -- @since 4.11.0.0 ----------------------------------------------------------------------------- module GHC.ByteOrder where -- Required for WORDS_BIGENDIAN #include <ghcautoconf.h> -- | Byte ordering. data ByteOrder = BigEndian -- ^ most-significant-byte occurs in lowest address. | LittleEndian -- ^ least-significant-byte occurs in lowest address. deriving ( Eq -- ^ @since 4.11.0.0 , Ord -- ^ @since 4.11.0.0 , Bounded -- ^ @since 4.11.0.0 , Enum -- ^ @since 4.11.0.0 , Read -- ^ @since 4.11.0.0 , Show -- ^ @since 4.11.0.0 ) -- | The byte ordering of the target machine. targetByteOrder :: ByteOrder #if defined(WORDS_BIGENDIAN) targetByteOrder = BigEndian #else targetByteOrder = LittleEndian #endif
sdiehl/ghc
libraries/base/GHC/ByteOrder.hs
bsd-3-clause
1,208
0
6
279
83
60
23
13
1
{- (c) The University of Glasgow 2006-2008 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -} {-# LANGUAGE CPP, NondecreasingIndentation #-} -- | Module for constructing @ModIface@ values (interface files), -- writing them to disk and comparing two versions to see if -- recompilation is required. module MkIface ( mkIface, -- Build a ModIface from a ModGuts, -- including computing version information mkIfaceTc, writeIfaceFile, -- Write the interface file checkOldIface, -- See if recompilation is required, by -- comparing version information RecompileRequired(..), recompileRequired, tyThingToIfaceDecl -- Converting things to their Iface equivalents ) where {- ----------------------------------------------- Recompilation checking ----------------------------------------------- A complete description of how recompilation checking works can be found in the wiki commentary: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance Please read the above page for a top-down description of how this all works. Notes below cover specific issues related to the implementation. Basic idea: * In the mi_usages information in an interface, we record the fingerprint of each free variable of the module * In mkIface, we compute the fingerprint of each exported thing A.f. For each external thing that A.f refers to, we include the fingerprint of the external reference when computing the fingerprint of A.f. So if anything that A.f depends on changes, then A.f's fingerprint will change. Also record any dependent files added with * addDependentFile * #include * -optP-include * In checkOldIface we compare the mi_usages for the module with the actual fingerprint for all each thing recorded in mi_usages -} #include "HsVersions.h" import IfaceSyn import LoadIface import FlagChecker import Desugar ( mkUsageInfo, mkUsedNames, mkDependencies ) import Id import IdInfo import Demand import Coercion( tidyCo ) import Annotations import CoreSyn import Class import TyCon import CoAxiom import ConLike import DataCon import PatSyn import Type import TcType import TysPrim ( alphaTyVars ) import InstEnv import FamInstEnv import TcRnMonad import HsSyn import HscTypes import Finder import DynFlags import VarEnv import VarSet import Var import Name import Avail import RdrName import NameEnv import NameSet import Module import BinIface import ErrUtils import Digraph import SrcLoc import Outputable import BasicTypes hiding ( SuccessFlag(..) ) import Unique import Util hiding ( eqListBy ) import FastString import FastStringEnv import Maybes import Binary import Fingerprint import Exception import Control.Monad import Data.Function import Data.List import qualified Data.Map as Map import Data.Ord import Data.IORef import System.Directory import System.FilePath {- ************************************************************************ * * \subsection{Completing an interface} * * ************************************************************************ -} mkIface :: HscEnv -> Maybe Fingerprint -- The old fingerprint, if we have it -> ModDetails -- The trimmed, tidied interface -> ModGuts -- Usages, deprecations, etc -> IO (ModIface, -- The new one Bool) -- True <=> there was an old Iface, and the -- new one is identical, so no need -- to write it mkIface hsc_env maybe_old_fingerprint mod_details ModGuts{ mg_module = this_mod, mg_hsc_src = hsc_src, mg_usages = usages, mg_used_th = used_th, mg_deps = deps, mg_rdr_env = rdr_env, mg_fix_env = fix_env, mg_warns = warns, mg_hpc_info = hpc_info, mg_safe_haskell = safe_mode, mg_trust_pkg = self_trust } = mkIface_ hsc_env maybe_old_fingerprint this_mod hsc_src used_th deps rdr_env fix_env warns hpc_info self_trust safe_mode usages mod_details -- | make an interface from the results of typechecking only. Useful -- for non-optimising compilation, or where we aren't generating any -- object code at all ('HscNothing'). mkIfaceTc :: HscEnv -> Maybe Fingerprint -- The old fingerprint, if we have it -> SafeHaskellMode -- The safe haskell mode -> ModDetails -- gotten from mkBootModDetails, probably -> TcGblEnv -- Usages, deprecations, etc -> IO (ModIface, Bool) mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details tc_result@TcGblEnv{ tcg_mod = this_mod, tcg_src = hsc_src, tcg_imports = imports, tcg_rdr_env = rdr_env, tcg_fix_env = fix_env, tcg_warns = warns, tcg_hpc = other_hpc_info, tcg_th_splice_used = tc_splice_used, tcg_dependent_files = dependent_files } = do let used_names = mkUsedNames tc_result deps <- mkDependencies tc_result let hpc_info = emptyHpcInfo other_hpc_info used_th <- readIORef tc_splice_used dep_files <- (readIORef dependent_files) usages <- mkUsageInfo hsc_env this_mod (imp_mods imports) used_names dep_files mkIface_ hsc_env maybe_old_fingerprint this_mod hsc_src used_th deps rdr_env fix_env warns hpc_info (imp_trust_own_pkg imports) safe_mode usages mod_details mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> HscSource -> Bool -> Dependencies -> GlobalRdrEnv -> NameEnv FixItem -> Warnings -> HpcInfo -> Bool -> SafeHaskellMode -> [Usage] -> ModDetails -> IO (ModIface, Bool) mkIface_ hsc_env maybe_old_fingerprint this_mod hsc_src used_th deps rdr_env fix_env src_warns hpc_info pkg_trust_req safe_mode usages ModDetails{ md_insts = insts, md_fam_insts = fam_insts, md_rules = rules, md_anns = anns, md_vect_info = vect_info, md_types = type_env, md_exports = exports } -- NB: notice that mkIface does not look at the bindings -- only at the TypeEnv. The previous Tidy phase has -- put exactly the info into the TypeEnv that we want -- to expose in the interface = do let entities = typeEnvElts type_env decls = [ tyThingToIfaceDecl entity | entity <- entities, let name = getName entity, not (isImplicitTyThing entity), -- No implicit Ids and class tycons in the interface file not (isWiredInName name), -- Nor wired-in things; the compiler knows about them anyhow nameIsLocalOrFrom this_mod name ] -- Sigh: see Note [Root-main Id] in TcRnDriver fixities = sortBy (comparing fst) [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env] -- The order of fixities returned from nameEnvElts is not -- deterministic, so we sort by OccName to canonicalize it. -- See Note [Deterministic UniqFM] in UniqDFM for more details. warns = src_warns iface_rules = map coreRuleToIfaceRule rules iface_insts = map instanceToIfaceInst $ fixSafeInstances safe_mode insts iface_fam_insts = map famInstToIfaceFamInst fam_insts iface_vect_info = flattenVectInfo vect_info trust_info = setSafeMode safe_mode annotations = map mkIfaceAnnotation anns sig_of = getSigOf dflags (moduleName this_mod) intermediate_iface = ModIface { mi_module = this_mod, mi_sig_of = sig_of, mi_hsc_src = hsc_src, mi_deps = deps, mi_usages = usages, mi_exports = mkIfaceExports exports, -- Sort these lexicographically, so that -- the result is stable across compilations mi_insts = sortBy cmp_inst iface_insts, mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts, mi_rules = sortBy cmp_rule iface_rules, mi_vect_info = iface_vect_info, mi_fixities = fixities, mi_warns = warns, mi_anns = annotations, mi_globals = maybeGlobalRdrEnv rdr_env, -- Left out deliberately: filled in by addFingerprints mi_iface_hash = fingerprint0, mi_mod_hash = fingerprint0, mi_flag_hash = fingerprint0, mi_exp_hash = fingerprint0, mi_used_th = used_th, mi_orphan_hash = fingerprint0, mi_orphan = False, -- Always set by addFingerprints, but -- it's a strict field, so we can't omit it. mi_finsts = False, -- Ditto mi_decls = deliberatelyOmitted "decls", mi_hash_fn = deliberatelyOmitted "hash_fn", mi_hpc = isHpcUsed hpc_info, mi_trust = trust_info, mi_trust_pkg = pkg_trust_req, -- And build the cached values mi_warn_fn = mkIfaceWarnCache warns, mi_fix_fn = mkIfaceFixCache fixities } (new_iface, no_change_at_all) <- {-# SCC "versioninfo" #-} addFingerprints hsc_env maybe_old_fingerprint intermediate_iface decls -- Debug printing dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" (pprModIface new_iface) -- bug #1617: on reload we weren't updating the PrintUnqualified -- correctly. This stems from the fact that the interface had -- not changed, so addFingerprints returns the old ModIface -- with the old GlobalRdrEnv (mi_globals). let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env } return (final_iface, no_change_at_all) where cmp_rule = comparing ifRuleName -- Compare these lexicographically by OccName, *not* by unique, -- because the latter is not stable across compilations: cmp_inst = comparing (nameOccName . ifDFun) cmp_fam_inst = comparing (nameOccName . ifFamInstTcName) dflags = hsc_dflags hsc_env -- We only fill in mi_globals if the module was compiled to byte -- code. Otherwise, the compiler may not have retained all the -- top-level bindings and they won't be in the TypeEnv (see -- Desugar.addExportFlagsAndRules). The mi_globals field is used -- by GHCi to decide whether the module has its full top-level -- scope available. (#5534) maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv maybeGlobalRdrEnv rdr_env | targetRetainsAllBindings (hscTarget dflags) = Just rdr_env | otherwise = Nothing deliberatelyOmitted :: String -> a deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x) ifFamInstTcName = ifFamInstFam flattenVectInfo (VectInfo { vectInfoVar = vVar , vectInfoTyCon = vTyCon , vectInfoParallelVars = vParallelVars , vectInfoParallelTyCons = vParallelTyCons }) = IfaceVectInfo { ifaceVectInfoVar = [Var.varName v | (v, _ ) <- varEnvElts vVar] , ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v] , ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v] , ifaceVectInfoParallelVars = [Var.varName v | v <- varSetElems vParallelVars] , ifaceVectInfoParallelTyCons = nameSetElems vParallelTyCons } ----------------------------- writeIfaceFile :: DynFlags -> FilePath -> ModIface -> IO () writeIfaceFile dflags hi_file_path new_iface = do createDirectoryIfMissing True (takeDirectory hi_file_path) writeBinIface dflags hi_file_path new_iface -- ----------------------------------------------------------------------------- -- Look up parents and versions of Names -- This is like a global version of the mi_hash_fn field in each ModIface. -- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get -- the parent and version info. mkHashFun :: HscEnv -- needed to look up versions -> ExternalPackageState -- ditto -> (Name -> Fingerprint) mkHashFun hsc_env eps = \name -> let mod = ASSERT2( isExternalName name, ppr name ) nameModule name occ = nameOccName name iface = lookupIfaceByModule dflags hpt pit mod `orElse` pprPanic "lookupVers2" (ppr mod <+> ppr occ) in snd (mi_hash_fn iface occ `orElse` pprPanic "lookupVers1" (ppr mod <+> ppr occ)) where dflags = hsc_dflags hsc_env hpt = hsc_HPT hsc_env pit = eps_PIT eps -- --------------------------------------------------------------------------- -- Compute fingerprints for the interface addFingerprints :: HscEnv -> Maybe Fingerprint -- the old fingerprint, if any -> ModIface -- The new interface (lacking decls) -> [IfaceDecl] -- The new decls -> IO (ModIface, -- Updated interface Bool) -- True <=> no changes at all; -- no need to write Iface addFingerprints hsc_env mb_old_fingerprint iface0 new_decls = do eps <- hscEPS hsc_env let -- The ABI of a declaration represents everything that is made -- visible about the declaration that a client can depend on. -- see IfaceDeclABI below. declABI :: IfaceDecl -> IfaceDeclABI declABI decl = (this_mod, decl, extras) where extras = declExtras fix_fn ann_fn non_orph_rules non_orph_insts non_orph_fis decl edges :: [(IfaceDeclABI, Unique, [Unique])] edges = [ (abi, getUnique (ifName decl), out) | decl <- new_decls , let abi = declABI decl , let out = localOccs $ freeNamesDeclABI abi ] name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n localOccs = map (getUnique . getParent . getOccName) . filter ((== this_mod) . name_module) . nameSetElems where getParent occ = lookupOccEnv parent_map occ `orElse` occ -- maps OccNames to their parents in the current module. -- e.g. a reference to a constructor must be turned into a reference -- to the TyCon for the purposes of calculating dependencies. parent_map :: OccEnv OccName parent_map = foldr extend emptyOccEnv new_decls where extend d env = extendOccEnvList env [ (b,n) | b <- ifaceDeclImplicitBndrs d ] where n = ifName d -- strongly-connected groups of declarations, in dependency order groups = stronglyConnCompFromEdgedVertices edges global_hash_fn = mkHashFun hsc_env eps -- how to output Names when generating the data to fingerprint. -- Here we want to output the fingerprint for each top-level -- Name, whether it comes from the current module or another -- module. In this way, the fingerprint for a declaration will -- change if the fingerprint for anything it refers to (transitively) -- changes. mk_put_name :: (OccEnv (OccName,Fingerprint)) -> BinHandle -> Name -> IO () mk_put_name local_env bh name | isWiredInName name = putNameLiterally bh name -- wired-in names don't have fingerprints | otherwise = ASSERT2( isExternalName name, ppr name ) let hash | nameModule name /= this_mod = global_hash_fn name | otherwise = snd (lookupOccEnv local_env (getOccName name) `orElse` pprPanic "urk! lookup local fingerprint" (ppr name)) -- (undefined,fingerprint0)) -- This panic indicates that we got the dependency -- analysis wrong, because we needed a fingerprint for -- an entity that wasn't in the environment. To debug -- it, turn the panic into a trace, uncomment the -- pprTraces below, run the compile again, and inspect -- the output and the generated .hi file with -- --show-iface. in put_ bh hash -- take a strongly-connected group of declarations and compute -- its fingerprint. fingerprint_group :: (OccEnv (OccName,Fingerprint), [(Fingerprint,IfaceDecl)]) -> SCC IfaceDeclABI -> IO (OccEnv (OccName,Fingerprint), [(Fingerprint,IfaceDecl)]) fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi) = do let hash_fn = mk_put_name local_env decl = abiDecl abi --pprTrace "fingerprinting" (ppr (ifName decl) ) $ do hash <- computeFingerprint hash_fn abi env' <- extend_hash_env local_env (hash,decl) return (env', (hash,decl) : decls_w_hashes) fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis) = do let decls = map abiDecl abis local_env1 <- foldM extend_hash_env local_env (zip (repeat fingerprint0) decls) let hash_fn = mk_put_name local_env1 -- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do let stable_abis = sortBy cmp_abiNames abis -- put the cycle in a canonical order hash <- computeFingerprint hash_fn stable_abis let pairs = zip (repeat hash) decls local_env2 <- foldM extend_hash_env local_env pairs return (local_env2, pairs ++ decls_w_hashes) -- we have fingerprinted the whole declaration, but we now need -- to assign fingerprints to all the OccNames that it binds, to -- use when referencing those OccNames in later declarations. -- extend_hash_env :: OccEnv (OccName,Fingerprint) -> (Fingerprint,IfaceDecl) -> IO (OccEnv (OccName,Fingerprint)) extend_hash_env env0 (hash,d) = do return (foldr (\(b,fp) env -> extendOccEnv env b (b,fp)) env0 (ifaceDeclFingerprints hash d)) -- (local_env, decls_w_hashes) <- foldM fingerprint_group (emptyOccEnv, []) groups -- when calculating fingerprints, we always need to use canonical -- ordering for lists of things. In particular, the mi_deps has various -- lists of modules and suchlike, so put these all in canonical order: let sorted_deps = sortDependencies (mi_deps iface0) -- the export hash of a module depends on the orphan hashes of the -- orphan modules below us in the dependency tree. This is the way -- that changes in orphans get propagated all the way up the -- dependency tree. We only care about orphan modules in the current -- package, because changes to orphans outside this package will be -- tracked by the usage on the ABI hash of package modules that we import. let orph_mods = filter (/= this_mod) -- Note [Do not update EPS with your own hi-boot] . filter ((== this_pkg) . moduleUnitId) $ dep_orphs sorted_deps dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods -- Note [Do not update EPS with your own hi-boot] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- (See also Trac #10182). When your hs-boot file includes an orphan -- instance declaration, you may find that the dep_orphs of a module you -- import contains reference to yourself. DO NOT actually load this module -- or add it to the orphan hashes: you're going to provide the orphan -- instances yourself, no need to consult hs-boot; if you do load the -- interface into EPS, you will see a duplicate orphan instance. orphan_hash <- computeFingerprint (mk_put_name local_env) (map ifDFun orph_insts, orph_rules, orph_fis) -- the export list hash doesn't depend on the fingerprints of -- the Names it mentions, only the Names themselves, hence putNameLiterally. export_hash <- computeFingerprint putNameLiterally (mi_exports iface0, orphan_hash, dep_orphan_hashes, dep_pkgs (mi_deps iface0), -- dep_pkgs: see "Package Version Changes" on -- wiki/Commentary/Compiler/RecompilationAvoidance mi_trust iface0) -- Make sure change of Safe Haskell mode causes recomp. -- put the declarations in a canonical order, sorted by OccName let sorted_decls = Map.elems $ Map.fromList $ [(ifName d, e) | e@(_, d) <- decls_w_hashes] -- the flag hash depends on: -- - (some of) dflags -- it returns two hashes, one that shouldn't change -- the abi hash and one that should flag_hash <- fingerprintDynFlags dflags this_mod putNameLiterally -- the ABI hash depends on: -- - decls -- - export list -- - orphans -- - deprecations -- - vect info -- - flag abi hash mod_hash <- computeFingerprint putNameLiterally (map fst sorted_decls, export_hash, -- includes orphan_hash mi_warns iface0, mi_vect_info iface0) -- The interface hash depends on: -- - the ABI hash, plus -- - the module level annotations, -- - usages -- - deps (home and external packages, dependent files) -- - hpc iface_hash <- computeFingerprint putNameLiterally (mod_hash, ann_fn (mkVarOcc "module"), -- See mkIfaceAnnCache mi_usages iface0, sorted_deps, mi_hpc iface0) let no_change_at_all = Just iface_hash == mb_old_fingerprint final_iface = iface0 { mi_mod_hash = mod_hash, mi_iface_hash = iface_hash, mi_exp_hash = export_hash, mi_orphan_hash = orphan_hash, mi_flag_hash = flag_hash, mi_orphan = not ( all ifRuleAuto orph_rules -- See Note [Orphans and auto-generated rules] && null orph_insts && null orph_fis && isNoIfaceVectInfo (mi_vect_info iface0)), mi_finsts = not . null $ mi_fam_insts iface0, mi_decls = sorted_decls, mi_hash_fn = lookupOccEnv local_env } -- return (final_iface, no_change_at_all) where this_mod = mi_module iface0 dflags = hsc_dflags hsc_env this_pkg = thisPackage dflags (non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0) (non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0) (non_orph_fis, orph_fis) = mkOrphMap ifFamInstOrph (mi_fam_insts iface0) fix_fn = mi_fix_fn iface0 ann_fn = mkIfaceAnnCache (mi_anns iface0) getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint] getOrphanHashes hsc_env mods = do eps <- hscEPS hsc_env let hpt = hsc_HPT hsc_env pit = eps_PIT eps dflags = hsc_dflags hsc_env get_orph_hash mod = case lookupIfaceByModule dflags hpt pit mod of Nothing -> pprPanic "moduleOrphanHash" (ppr mod) Just iface -> mi_orphan_hash iface -- return (map get_orph_hash mods) sortDependencies :: Dependencies -> Dependencies sortDependencies d = Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d), dep_pkgs = sortBy (stableUnitIdCmp `on` fst) (dep_pkgs d), dep_orphs = sortBy stableModuleCmp (dep_orphs d), dep_finsts = sortBy stableModuleCmp (dep_finsts d) } -- | Creates cached lookup for the 'mi_anns' field of ModIface -- Hackily, we use "module" as the OccName for any module-level annotations mkIfaceAnnCache :: [IfaceAnnotation] -> OccName -> [AnnPayload] mkIfaceAnnCache anns = \n -> lookupOccEnv env n `orElse` [] where pair (IfaceAnnotation target value) = (case target of NamedTarget occn -> occn ModuleTarget _ -> mkVarOcc "module" , [value]) -- flipping (++), so the first argument is always short env = mkOccEnv_C (flip (++)) (map pair anns) {- ************************************************************************ * * The ABI of an IfaceDecl * * ************************************************************************ Note [The ABI of an IfaceDecl] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ABI of a declaration consists of: (a) the full name of the identifier (inc. module and package, because these are used to construct the symbol name by which the identifier is known externally). (b) the declaration itself, as exposed to clients. That is, the definition of an Id is included in the fingerprint only if it is made available as an unfolding in the interface. (c) the fixity of the identifier (if it exists) (d) for Ids: rules (e) for classes: instances, fixity & rules for methods (f) for datatypes: instances, fixity & rules for constrs Items (c)-(f) are not stored in the IfaceDecl, but instead appear elsewhere in the interface file. But they are *fingerprinted* with the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras, and fingerprinting that as part of the declaration. -} type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras) data IfaceDeclExtras = IfaceIdExtras IfaceIdExtras | IfaceDataExtras (Maybe Fixity) -- Fixity of the tycon itself (if it exists) [IfaceInstABI] -- Local class and family instances of this tycon -- See Note [Orphans] in InstEnv [AnnPayload] -- Annotations of the type itself [IfaceIdExtras] -- For each constructor: fixity, RULES and annotations | IfaceClassExtras (Maybe Fixity) -- Fixity of the class itself (if it exists) [IfaceInstABI] -- Local instances of this class *or* -- of its associated data types -- See Note [Orphans] in InstEnv [AnnPayload] -- Annotations of the type itself [IfaceIdExtras] -- For each class method: fixity, RULES and annotations | IfaceSynonymExtras (Maybe Fixity) [AnnPayload] | IfaceFamilyExtras (Maybe Fixity) [IfaceInstABI] [AnnPayload] | IfaceOtherDeclExtras data IfaceIdExtras = IdExtras (Maybe Fixity) -- Fixity of the Id (if it exists) [IfaceRule] -- Rules for the Id [AnnPayload] -- Annotations for the Id -- When hashing a class or family instance, we hash only the -- DFunId or CoAxiom, because that depends on all the -- information about the instance. -- type IfaceInstABI = IfExtName -- Name of DFunId or CoAxiom that is evidence for the instance abiDecl :: IfaceDeclABI -> IfaceDecl abiDecl (_, decl, _) = decl cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare` ifName (abiDecl abi2) freeNamesDeclABI :: IfaceDeclABI -> NameSet freeNamesDeclABI (_mod, decl, extras) = freeNamesIfDecl decl `unionNameSet` freeNamesDeclExtras extras freeNamesDeclExtras :: IfaceDeclExtras -> NameSet freeNamesDeclExtras (IfaceIdExtras id_extras) = freeNamesIdExtras id_extras freeNamesDeclExtras (IfaceDataExtras _ insts _ subs) = unionNameSets (mkNameSet insts : map freeNamesIdExtras subs) freeNamesDeclExtras (IfaceClassExtras _ insts _ subs) = unionNameSets (mkNameSet insts : map freeNamesIdExtras subs) freeNamesDeclExtras (IfaceSynonymExtras _ _) = emptyNameSet freeNamesDeclExtras (IfaceFamilyExtras _ insts _) = mkNameSet insts freeNamesDeclExtras IfaceOtherDeclExtras = emptyNameSet freeNamesIdExtras :: IfaceIdExtras -> NameSet freeNamesIdExtras (IdExtras _ rules _) = unionNameSets (map freeNamesIfRule rules) instance Outputable IfaceDeclExtras where ppr IfaceOtherDeclExtras = Outputable.empty ppr (IfaceIdExtras extras) = ppr_id_extras extras ppr (IfaceSynonymExtras fix anns) = vcat [ppr fix, ppr anns] ppr (IfaceFamilyExtras fix finsts anns) = vcat [ppr fix, ppr finsts, ppr anns] ppr (IfaceDataExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns, ppr_id_extras_s stuff] ppr (IfaceClassExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns, ppr_id_extras_s stuff] ppr_insts :: [IfaceInstABI] -> SDoc ppr_insts _ = text "<insts>" ppr_id_extras_s :: [IfaceIdExtras] -> SDoc ppr_id_extras_s stuff = vcat (map ppr_id_extras stuff) ppr_id_extras :: IfaceIdExtras -> SDoc ppr_id_extras (IdExtras fix rules anns) = ppr fix $$ vcat (map ppr rules) $$ vcat (map ppr anns) -- This instance is used only to compute fingerprints instance Binary IfaceDeclExtras where get _bh = panic "no get for IfaceDeclExtras" put_ bh (IfaceIdExtras extras) = do putByte bh 1; put_ bh extras put_ bh (IfaceDataExtras fix insts anns cons) = do putByte bh 2; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh cons put_ bh (IfaceClassExtras fix insts anns methods) = do putByte bh 3; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh methods put_ bh (IfaceSynonymExtras fix anns) = do putByte bh 4; put_ bh fix; put_ bh anns put_ bh (IfaceFamilyExtras fix finsts anns) = do putByte bh 5; put_ bh fix; put_ bh finsts; put_ bh anns put_ bh IfaceOtherDeclExtras = putByte bh 6 instance Binary IfaceIdExtras where get _bh = panic "no get for IfaceIdExtras" put_ bh (IdExtras fix rules anns)= do { put_ bh fix; put_ bh rules; put_ bh anns } declExtras :: (OccName -> Maybe Fixity) -> (OccName -> [AnnPayload]) -> OccEnv [IfaceRule] -> OccEnv [IfaceClsInst] -> OccEnv [IfaceFamInst] -> IfaceDecl -> IfaceDeclExtras declExtras fix_fn ann_fn rule_env inst_env fi_env decl = case decl of IfaceId{} -> IfaceIdExtras (id_extras n) IfaceData{ifCons=cons} -> IfaceDataExtras (fix_fn n) (map ifFamInstAxiom (lookupOccEnvL fi_env n) ++ map ifDFun (lookupOccEnvL inst_env n)) (ann_fn n) (map (id_extras . ifConOcc) (visibleIfConDecls cons)) IfaceClass{ifSigs=sigs, ifATs=ats} -> IfaceClassExtras (fix_fn n) (map ifDFun $ (concatMap at_extras ats) ++ lookupOccEnvL inst_env n) -- Include instances of the associated types -- as well as instances of the class (Trac #5147) (ann_fn n) [id_extras op | IfaceClassOp op _ _ <- sigs] IfaceSynonym{} -> IfaceSynonymExtras (fix_fn n) (ann_fn n) IfaceFamily{} -> IfaceFamilyExtras (fix_fn n) (map ifFamInstAxiom (lookupOccEnvL fi_env n)) (ann_fn n) _other -> IfaceOtherDeclExtras where n = ifName decl id_extras occ = IdExtras (fix_fn occ) (lookupOccEnvL rule_env occ) (ann_fn occ) at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl) lookupOccEnvL :: OccEnv [v] -> OccName -> [v] lookupOccEnvL env k = lookupOccEnv env k `orElse` [] -- used when we want to fingerprint a structure without depending on the -- fingerprints of external Names that it refers to. putNameLiterally :: BinHandle -> Name -> IO () putNameLiterally bh name = ASSERT( isExternalName name ) do put_ bh $! nameModule name put_ bh $! nameOccName name {- -- for testing: use the md5sum command to generate fingerprints and -- compare the results against our built-in version. fp' <- oldMD5 dflags bh if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp') else return fp oldMD5 dflags bh = do tmp <- newTempName dflags "bin" writeBinMem bh tmp tmp2 <- newTempName dflags "md5" let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2 r <- system cmd case r of ExitFailure _ -> throwGhcExceptionIO (PhaseFailed cmd r) ExitSuccess -> do hash_str <- readFile tmp2 return $! readHexFingerprint hash_str -} ---------------------- -- mkOrphMap partitions instance decls or rules into -- (a) an OccEnv for ones that are not orphans, -- mapping the local OccName to a list of its decls -- (b) a list of orphan decls mkOrphMap :: (decl -> IsOrphan) -- Extract orphan status from decl -> [decl] -- Sorted into canonical order -> (OccEnv [decl], -- Non-orphan decls associated with their key; -- each sublist in canonical order [decl]) -- Orphan decls; in canonical order mkOrphMap get_key decls = foldl go (emptyOccEnv, []) decls where go (non_orphs, orphs) d | NotOrphan occ <- get_key d = (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs) | otherwise = (non_orphs, d:orphs) {- ************************************************************************ * * Keeping track of what we've slurped, and fingerprints * * ************************************************************************ -} mkIfaceAnnotation :: Annotation -> IfaceAnnotation mkIfaceAnnotation (Annotation { ann_target = target, ann_value = payload }) = IfaceAnnotation { ifAnnotatedTarget = fmap nameOccName target, ifAnnotatedValue = payload } mkIfaceExports :: [AvailInfo] -> [IfaceExport] -- Sort to make canonical mkIfaceExports exports = sortBy stableAvailCmp (map sort_subs exports) where sort_subs :: AvailInfo -> AvailInfo sort_subs (Avail b n) = Avail b n sort_subs (AvailTC n [] fs) = AvailTC n [] (sort_flds fs) sort_subs (AvailTC n (m:ms) fs) | n==m = AvailTC n (m:sortBy stableNameCmp ms) (sort_flds fs) | otherwise = AvailTC n (sortBy stableNameCmp (m:ms)) (sort_flds fs) -- Maintain the AvailTC Invariant sort_flds = sortBy (stableNameCmp `on` flSelector) {- Note [Orignal module] ~~~~~~~~~~~~~~~~~~~~~ Consider this: module X where { data family T } module Y( T(..) ) where { import X; data instance T Int = MkT Int } The exported Avail from Y will look like X.T{X.T, Y.MkT} That is, in Y, - only MkT is brought into scope by the data instance; - but the parent (used for grouping and naming in T(..) exports) is X.T - and in this case we export X.T too In the result of MkIfaceExports, the names are grouped by defining module, so we may need to split up a single Avail into multiple ones. Note [Internal used_names] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Most of the used_names are External Names, but we can have Internal Names too: see Note [Binders in Template Haskell] in Convert, and Trac #5362 for an example. Such Names are always - Such Names are always for locally-defined things, for which we don't gather usage info, so we can just ignore them in ent_map - They are always System Names, hence the assert, just as a double check. ************************************************************************ * * Load the old interface file for this module (unless we have it already), and check whether it is up to date * * ************************************************************************ -} data RecompileRequired = UpToDate -- ^ everything is up to date, recompilation is not required | MustCompile -- ^ The .hs file has been touched, or the .o/.hi file does not exist | RecompBecause String -- ^ The .o/.hi files are up to date, but something else has changed -- to force recompilation; the String says what (one-line summary) deriving Eq recompileRequired :: RecompileRequired -> Bool recompileRequired UpToDate = False recompileRequired _ = True -- | Top level function to check if the version of an old interface file -- is equivalent to the current source file the user asked us to compile. -- If the same, we can avoid recompilation. We return a tuple where the -- first element is a bool saying if we should recompile the object file -- and the second is maybe the interface file, where Nothng means to -- rebuild the interface file not use the exisitng one. checkOldIface :: HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -- Old interface from compilation manager, if any -> IO (RecompileRequired, Maybe ModIface) checkOldIface hsc_env mod_summary source_modified maybe_iface = do let dflags = hsc_dflags hsc_env showPass dflags $ "Checking old interface for " ++ (showPpr dflags $ ms_mod mod_summary) initIfaceCheck hsc_env $ check_old_iface hsc_env mod_summary source_modified maybe_iface check_old_iface :: HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -> IfG (RecompileRequired, Maybe ModIface) check_old_iface hsc_env mod_summary src_modified maybe_iface = let dflags = hsc_dflags hsc_env getIface = case maybe_iface of Just _ -> do traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary)) return maybe_iface Nothing -> loadIface loadIface = do let iface_path = msHiFilePath mod_summary read_result <- readIface (ms_mod mod_summary) iface_path case read_result of Failed err -> do traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err) return Nothing Succeeded iface -> do traceIf (text "Read the interface file" <+> text iface_path) return $ Just iface src_changed | gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True | SourceModified <- src_modified = True | otherwise = False in do when src_changed $ traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off") case src_changed of -- If the source has changed and we're in interactive mode, -- avoid reading an interface; just return the one we might -- have been supplied with. True | not (isObjectTarget $ hscTarget dflags) -> return (MustCompile, maybe_iface) -- Try and read the old interface for the current module -- from the .hi file left from the last time we compiled it True -> do maybe_iface' <- getIface return (MustCompile, maybe_iface') False -> do maybe_iface' <- getIface case maybe_iface' of -- We can't retrieve the iface Nothing -> return (MustCompile, Nothing) -- We have got the old iface; check its versions -- even in the SourceUnmodifiedAndStable case we -- should check versions because some packages -- might have changed or gone away. Just iface -> checkVersions hsc_env mod_summary iface -- | Check if a module is still the same 'version'. -- -- This function is called in the recompilation checker after we have -- determined that the module M being checked hasn't had any changes -- to its source file since we last compiled M. So at this point in general -- two things may have changed that mean we should recompile M: -- * The interface export by a dependency of M has changed. -- * The compiler flags specified this time for M have changed -- in a manner that is significant for recompilaiton. -- We return not just if we should recompile the object file but also -- if we should rebuild the interface file. checkVersions :: HscEnv -> ModSummary -> ModIface -- Old interface -> IfG (RecompileRequired, Maybe ModIface) checkVersions hsc_env mod_summary iface = do { traceHiDiffs (text "Considering whether compilation is required for" <+> ppr (mi_module iface) <> colon) ; recomp <- checkFlagHash hsc_env iface ; if recompileRequired recomp then return (recomp, Nothing) else do { ; if getSigOf (hsc_dflags hsc_env) (moduleName (mi_module iface)) /= mi_sig_of iface then return (RecompBecause "sig-of changed", Nothing) else do { ; recomp <- checkDependencies hsc_env mod_summary iface ; if recompileRequired recomp then return (recomp, Just iface) else do { -- Source code unchanged and no errors yet... carry on -- -- First put the dependent-module info, read from the old -- interface, into the envt, so that when we look for -- interfaces we look for the right one (.hi or .hi-boot) -- -- It's just temporary because either the usage check will succeed -- (in which case we are done with this module) or it'll fail (in which -- case we'll compile the module from scratch anyhow). -- -- We do this regardless of compilation mode, although in --make mode -- all the dependent modules should be in the HPT already, so it's -- quite redundant ; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps } ; recomp <- checkList [checkModUsage this_pkg u | u <- mi_usages iface] ; return (recomp, Just iface) }}}} where this_pkg = thisPackage (hsc_dflags hsc_env) -- This is a bit of a hack really mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface) mod_deps = mkModDeps (dep_mods (mi_deps iface)) -- | Check the flags haven't changed checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired checkFlagHash hsc_env iface = do let old_hash = mi_flag_hash iface new_hash <- liftIO $ fingerprintDynFlags (hsc_dflags hsc_env) (mi_module iface) putNameLiterally case old_hash == new_hash of True -> up_to_date (text "Module flags unchanged") False -> out_of_date_hash "flags changed" (text " Module flags have changed") old_hash new_hash -- If the direct imports of this module are resolved to targets that -- are not among the dependencies of the previous interface file, -- then we definitely need to recompile. This catches cases like -- - an exposed package has been upgraded -- - we are compiling with different package flags -- - a home module that was shadowing a package module has been removed -- - a new home module has been added that shadows a package module -- See bug #1372. -- -- Returns True if recompilation is required. checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired checkDependencies hsc_env summary iface = checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary)) where prev_dep_mods = dep_mods (mi_deps iface) prev_dep_pkgs = dep_pkgs (mi_deps iface) this_pkg = thisPackage (hsc_dflags hsc_env) dep_missing (mb_pkg, L _ mod) = do find_res <- liftIO $ findImportedModule hsc_env mod (mb_pkg) let reason = moduleNameString mod ++ " changed" case find_res of Found _ mod | pkg == this_pkg -> if moduleName mod `notElem` map fst prev_dep_mods then do traceHiDiffs $ text "imported module " <> quotes (ppr mod) <> text " not among previous dependencies" return (RecompBecause reason) else return UpToDate | otherwise -> if pkg `notElem` (map fst prev_dep_pkgs) then do traceHiDiffs $ text "imported module " <> quotes (ppr mod) <> text " is from package " <> quotes (ppr pkg) <> text ", which is not among previous dependencies" return (RecompBecause reason) else return UpToDate where pkg = moduleUnitId mod _otherwise -> return (RecompBecause reason) needInterface :: Module -> (ModIface -> IfG RecompileRequired) -> IfG RecompileRequired needInterface mod continue = do -- Load the imported interface if possible let doc_str = sep [text "need version info for", ppr mod] traceHiDiffs (text "Checking usages for module" <+> ppr mod) mb_iface <- loadInterface doc_str mod ImportBySystem -- Load the interface, but don't complain on failure; -- Instead, get an Either back which we can test case mb_iface of Failed _ -> do traceHiDiffs (sep [text "Couldn't load interface for module", ppr mod]) return MustCompile -- Couldn't find or parse a module mentioned in the -- old interface file. Don't complain: it might -- just be that the current module doesn't need that -- import and it's been deleted Succeeded iface -> continue iface -- | Given the usage information extracted from the old -- M.hi file for the module being compiled, figure out -- whether M needs to be recompiled. checkModUsage :: UnitId -> Usage -> IfG RecompileRequired checkModUsage _this_pkg UsagePackageModule{ usg_mod = mod, usg_mod_hash = old_mod_hash } = needInterface mod $ \iface -> do let reason = moduleNameString (moduleName mod) ++ " changed" checkModuleFingerprint reason old_mod_hash (mi_mod_hash iface) -- We only track the ABI hash of package modules, rather than -- individual entity usages, so if the ABI hash changes we must -- recompile. This is safe but may entail more recompilation when -- a dependent package has changed. checkModUsage this_pkg UsageHomeModule{ usg_mod_name = mod_name, usg_mod_hash = old_mod_hash, usg_exports = maybe_old_export_hash, usg_entities = old_decl_hash } = do let mod = mkModule this_pkg mod_name needInterface mod $ \iface -> do let new_mod_hash = mi_mod_hash iface new_decl_hash = mi_hash_fn iface new_export_hash = mi_exp_hash iface reason = moduleNameString mod_name ++ " changed" -- CHECK MODULE recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash if not (recompileRequired recompile) then return UpToDate else do -- CHECK EXPORT LIST checkMaybeHash reason maybe_old_export_hash new_export_hash (text " Export list changed") $ do -- CHECK ITEMS ONE BY ONE recompile <- checkList [ checkEntityUsage reason new_decl_hash u | u <- old_decl_hash] if recompileRequired recompile then return recompile -- This one failed, so just bail out now else up_to_date (text " Great! The bits I use are up to date") checkModUsage _this_pkg UsageFile{ usg_file_path = file, usg_file_hash = old_hash } = liftIO $ handleIO handle $ do new_hash <- getFileHash file if (old_hash /= new_hash) then return recomp else return UpToDate where recomp = RecompBecause (file ++ " changed") handle = #ifdef DEBUG \e -> pprTrace "UsageFile" (text (show e)) $ return recomp #else \_ -> return recomp -- if we can't find the file, just recompile, don't fail #endif ------------------------ checkModuleFingerprint :: String -> Fingerprint -> Fingerprint -> IfG RecompileRequired checkModuleFingerprint reason old_mod_hash new_mod_hash | new_mod_hash == old_mod_hash = up_to_date (text "Module fingerprint unchanged") | otherwise = out_of_date_hash reason (text " Module fingerprint has changed") old_mod_hash new_mod_hash ------------------------ checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc -> IfG RecompileRequired -> IfG RecompileRequired checkMaybeHash reason maybe_old_hash new_hash doc continue | Just hash <- maybe_old_hash, hash /= new_hash = out_of_date_hash reason doc hash new_hash | otherwise = continue ------------------------ checkEntityUsage :: String -> (OccName -> Maybe (OccName, Fingerprint)) -> (OccName, Fingerprint) -> IfG RecompileRequired checkEntityUsage reason new_hash (name,old_hash) = case new_hash name of Nothing -> -- We used it before, but it ain't there now out_of_date reason (sep [text "No longer exported:", ppr name]) Just (_, new_hash) -- It's there, but is it up to date? | new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash)) return UpToDate | otherwise -> out_of_date_hash reason (text " Out of date:" <+> ppr name) old_hash new_hash up_to_date :: SDoc -> IfG RecompileRequired up_to_date msg = traceHiDiffs msg >> return UpToDate out_of_date :: String -> SDoc -> IfG RecompileRequired out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason) out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired out_of_date_hash reason msg old_hash new_hash = out_of_date reason (hsep [msg, ppr old_hash, text "->", ppr new_hash]) ---------------------- checkList :: [IfG RecompileRequired] -> IfG RecompileRequired -- This helper is used in two places checkList [] = return UpToDate checkList (check:checks) = do recompile <- check if recompileRequired recompile then return recompile else checkList checks {- ************************************************************************ * * Converting things to their Iface equivalents * * ************************************************************************ -} tyThingToIfaceDecl :: TyThing -> IfaceDecl tyThingToIfaceDecl (AnId id) = idToIfaceDecl id tyThingToIfaceDecl (ATyCon tycon) = snd (tyConToIfaceDecl emptyTidyEnv tycon) tyThingToIfaceDecl (ACoAxiom ax) = coAxiomToIfaceDecl ax tyThingToIfaceDecl (AConLike cl) = case cl of RealDataCon dc -> dataConToIfaceDecl dc -- for ppr purposes only PatSynCon ps -> patSynToIfaceDecl ps -------------------------- idToIfaceDecl :: Id -> IfaceDecl -- The Id is already tidied, so that locally-bound names -- (lambdas, for-alls) already have non-clashing OccNames -- We can't tidy it here, locally, because it may have -- free variables in its type or IdInfo idToIfaceDecl id = IfaceId { ifName = getOccName id, ifType = toIfaceType (idType id), ifIdDetails = toIfaceIdDetails (idDetails id), ifIdInfo = toIfaceIdInfo (idInfo id) } -------------------------- dataConToIfaceDecl :: DataCon -> IfaceDecl dataConToIfaceDecl dataCon = IfaceId { ifName = getOccName dataCon, ifType = toIfaceType (dataConUserType dataCon), ifIdDetails = IfVanillaId, ifIdInfo = NoInfo } -------------------------- patSynToIfaceDecl :: PatSyn -> IfaceDecl patSynToIfaceDecl ps = IfacePatSyn { ifName = getOccName . getName $ ps , ifPatMatcher = to_if_pr (patSynMatcher ps) , ifPatBuilder = fmap to_if_pr (patSynBuilder ps) , ifPatIsInfix = patSynIsInfix ps , ifPatUnivTvs = toIfaceTvBndrs univ_tvs' , ifPatExTvs = toIfaceTvBndrs ex_tvs' , ifPatProvCtxt = tidyToIfaceContext env2 prov_theta , ifPatReqCtxt = tidyToIfaceContext env2 req_theta , ifPatArgs = map (tidyToIfaceType env2) args , ifPatTy = tidyToIfaceType env2 rhs_ty , ifFieldLabels = (patSynFieldLabels ps) } where (univ_tvs, req_theta, ex_tvs, prov_theta, args, rhs_ty) = patSynSig ps (env1, univ_tvs') = tidyTyCoVarBndrs emptyTidyEnv univ_tvs (env2, ex_tvs') = tidyTyCoVarBndrs env1 ex_tvs to_if_pr (id, needs_dummy) = (idName id, needs_dummy) -------------------------- coAxiomToIfaceDecl :: CoAxiom br -> IfaceDecl -- We *do* tidy Axioms, because they are not (and cannot -- conveniently be) built in tidy form coAxiomToIfaceDecl ax@(CoAxiom { co_ax_tc = tycon, co_ax_branches = branches , co_ax_role = role }) = IfaceAxiom { ifName = name , ifTyCon = toIfaceTyCon tycon , ifRole = role , ifAxBranches = map (coAxBranchToIfaceBranch tycon (map coAxBranchLHS branch_list)) branch_list } where branch_list = fromBranches branches name = getOccName ax -- 2nd parameter is the list of branch LHSs, for conversion from incompatible branches -- to incompatible indices -- See Note [Storing compatibility] in CoAxiom coAxBranchToIfaceBranch :: TyCon -> [[Type]] -> CoAxBranch -> IfaceAxBranch coAxBranchToIfaceBranch tc lhs_s branch@(CoAxBranch { cab_incomps = incomps }) = (coAxBranchToIfaceBranch' tc branch) { ifaxbIncomps = iface_incomps } where iface_incomps = map (expectJust "iface_incomps" . (flip findIndex lhs_s . eqTypes) . coAxBranchLHS) incomps -- use this one for standalone branches without incompatibles coAxBranchToIfaceBranch' :: TyCon -> CoAxBranch -> IfaceAxBranch coAxBranchToIfaceBranch' tc (CoAxBranch { cab_tvs = tvs, cab_cvs = cvs , cab_lhs = lhs , cab_roles = roles, cab_rhs = rhs }) = IfaceAxBranch { ifaxbTyVars = toIfaceTvBndrs tv_bndrs , ifaxbCoVars = map toIfaceIdBndr cvs , ifaxbLHS = tidyToIfaceTcArgs env1 tc lhs , ifaxbRoles = roles , ifaxbRHS = tidyToIfaceType env1 rhs , ifaxbIncomps = [] } where (env1, tv_bndrs) = tidyTyClTyCoVarBndrs emptyTidyEnv tvs -- Don't re-bind in-scope tyvars -- See Note [CoAxBranch type variables] in CoAxiom ----------------- tyConToIfaceDecl :: TidyEnv -> TyCon -> (TidyEnv, IfaceDecl) -- We *do* tidy TyCons, because they are not (and cannot -- conveniently be) built in tidy form -- The returned TidyEnv is the one after tidying the tyConTyVars tyConToIfaceDecl env tycon | Just clas <- tyConClass_maybe tycon = classToIfaceDecl env clas | Just syn_rhs <- synTyConRhs_maybe tycon = ( tc_env1 , IfaceSynonym { ifName = getOccName tycon, ifTyVars = if_tc_tyvars, ifRoles = tyConRoles tycon, ifSynRhs = if_syn_type syn_rhs, ifSynKind = if_kind }) | Just fam_flav <- famTyConFlav_maybe tycon = ( tc_env1 , IfaceFamily { ifName = getOccName tycon, ifTyVars = if_tc_tyvars, ifResVar = if_res_var, ifFamFlav = to_if_fam_flav fam_flav, ifFamKind = if_kind, ifFamInj = familyTyConInjectivityInfo tycon }) | isAlgTyCon tycon = ( tc_env1 , IfaceData { ifName = getOccName tycon, ifKind = if_kind, ifCType = tyConCType tycon, ifTyVars = if_tc_tyvars, ifRoles = tyConRoles tycon, ifCtxt = tidyToIfaceContext tc_env1 (tyConStupidTheta tycon), ifCons = ifaceConDecls (algTyConRhs tycon) (algTcFields tycon), ifRec = boolToRecFlag (isRecursiveTyCon tycon), ifGadtSyntax = isGadtSyntaxTyCon tycon, ifParent = parent }) | otherwise -- FunTyCon, PrimTyCon, promoted TyCon/DataCon -- For pretty printing purposes only. = ( env , IfaceData { ifName = getOccName tycon, ifKind = -- These don't have `tyConTyVars`, so we use an empty -- environment here, instead of `tc_env1` defined below. tidyToIfaceType emptyTidyEnv (tyConKind tycon), ifCType = Nothing, ifTyVars = funAndPrimTyVars, ifRoles = tyConRoles tycon, ifCtxt = [], ifCons = IfDataTyCon [] False [], ifRec = boolToRecFlag False, ifGadtSyntax = False, ifParent = IfNoParent }) where -- NOTE: Not all TyCons have `tyConTyVars` field. Forcing this when `tycon` -- is one of these TyCons (FunTyCon, PrimTyCon, PromotedDataCon) will cause -- an error. (tc_env1, tc_tyvars) = tidyTyClTyCoVarBndrs env (tyConTyVars tycon) if_tc_tyvars = toIfaceTvBndrs tc_tyvars if_kind = tidyToIfaceType tc_env1 (tyConKind tycon) if_syn_type ty = tidyToIfaceType tc_env1 ty if_res_var = getFS `fmap` tyConFamilyResVar_maybe tycon funAndPrimTyVars = toIfaceTvBndrs $ take (tyConArity tycon) alphaTyVars parent = case tyConFamInstSig_maybe tycon of Just (tc, ty, ax) -> IfDataInstance (coAxiomName ax) (toIfaceTyCon tc) (tidyToIfaceTcArgs tc_env1 tc ty) Nothing -> IfNoParent to_if_fam_flav OpenSynFamilyTyCon = IfaceOpenSynFamilyTyCon to_if_fam_flav (ClosedSynFamilyTyCon (Just ax)) = IfaceClosedSynFamilyTyCon (Just (axn, ibr)) where defs = fromBranches $ coAxiomBranches ax ibr = map (coAxBranchToIfaceBranch' tycon) defs axn = coAxiomName ax to_if_fam_flav (ClosedSynFamilyTyCon Nothing) = IfaceClosedSynFamilyTyCon Nothing to_if_fam_flav AbstractClosedSynFamilyTyCon = IfaceAbstractClosedSynFamilyTyCon to_if_fam_flav (DataFamilyTyCon {}) = IfaceDataFamilyTyCon to_if_fam_flav (BuiltInSynFamTyCon {}) = IfaceBuiltInSynFamTyCon ifaceConDecls (NewTyCon { data_con = con }) flds = IfNewTyCon (ifaceConDecl con) (ifaceOverloaded flds) (ifaceFields flds) ifaceConDecls (DataTyCon { data_cons = cons }) flds = IfDataTyCon (map ifaceConDecl cons) (ifaceOverloaded flds) (ifaceFields flds) ifaceConDecls (TupleTyCon { data_con = con }) _ = IfDataTyCon [ifaceConDecl con] False [] ifaceConDecls (AbstractTyCon distinct) _ = IfAbstractTyCon distinct -- The AbstractTyCon case happens when a TyCon has been trimmed -- during tidying. -- Furthermore, tyThingToIfaceDecl is also used in TcRnDriver -- for GHCi, when browsing a module, in which case the -- AbstractTyCon and TupleTyCon cases are perfectly sensible. -- (Tuple declarations are not serialised into interface files.) ifaceConDecl data_con = IfCon { ifConOcc = getOccName (dataConName data_con), ifConInfix = dataConIsInfix data_con, ifConWrapper = isJust (dataConWrapId_maybe data_con), ifConExTvs = toIfaceTvBndrs ex_tvs', ifConEqSpec = map (to_eq_spec . eqSpecPair) eq_spec, ifConCtxt = tidyToIfaceContext con_env2 theta, ifConArgTys = map (tidyToIfaceType con_env2) arg_tys, ifConFields = map (nameOccName . flSelector) (dataConFieldLabels data_con), ifConStricts = map (toIfaceBang con_env2) (dataConImplBangs data_con), ifConSrcStricts = map toIfaceSrcBang (dataConSrcBangs data_con)} where (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con -- Tidy the univ_tvs of the data constructor to be identical -- to the tyConTyVars of the type constructor. This means -- (a) we don't need to redundantly put them into the interface file -- (b) when pretty-printing an Iface data declaration in H98-style syntax, -- we know that the type variables will line up -- The latter (b) is important because we pretty-print type constructors -- by converting to IfaceSyn and pretty-printing that con_env1 = (fst tc_env1, mkVarEnv (zipEqual "ifaceConDecl" univ_tvs tc_tyvars)) -- A bit grimy, perhaps, but it's simple! (con_env2, ex_tvs') = tidyTyCoVarBndrs con_env1 ex_tvs to_eq_spec (tv,ty) = (toIfaceTyVar (tidyTyVar con_env2 tv), tidyToIfaceType con_env2 ty) ifaceOverloaded flds = case fsEnvElts flds of fl:_ -> flIsOverloaded fl [] -> False ifaceFields flds = sort $ map flLabel $ fsEnvElts flds -- We need to sort the labels because they come out -- of FastStringEnv in arbitrary order, because -- FastStringEnv is keyed on Uniques. -- Sorting FastString is ok here, because Uniques -- are only used for equality checks in the Ord -- instance for FastString. -- See Note [Unique Determinism] in Unique. toIfaceBang :: TidyEnv -> HsImplBang -> IfaceBang toIfaceBang _ HsLazy = IfNoBang toIfaceBang _ (HsUnpack Nothing) = IfUnpack toIfaceBang env (HsUnpack (Just co)) = IfUnpackCo (toIfaceCoercion (tidyCo env co)) toIfaceBang _ HsStrict = IfStrict toIfaceSrcBang :: HsSrcBang -> IfaceSrcBang toIfaceSrcBang (HsSrcBang _ unpk bang) = IfSrcBang unpk bang classToIfaceDecl :: TidyEnv -> Class -> (TidyEnv, IfaceDecl) classToIfaceDecl env clas = ( env1 , IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta, ifName = getOccName tycon, ifTyVars = toIfaceTvBndrs clas_tyvars', ifRoles = tyConRoles (classTyCon clas), ifKind = tidyToIfaceType env1 (tyConKind tycon), ifFDs = map toIfaceFD clas_fds, ifATs = map toIfaceAT clas_ats, ifSigs = map toIfaceClassOp op_stuff, ifMinDef = fmap getFS (classMinimalDef clas), ifRec = boolToRecFlag (isRecursiveTyCon tycon) }) where (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff) = classExtraBigSig clas tycon = classTyCon clas (env1, clas_tyvars') = tidyTyCoVarBndrs env clas_tyvars toIfaceAT :: ClassATItem -> IfaceAT toIfaceAT (ATI tc def) = IfaceAT if_decl (fmap (tidyToIfaceType env2 . fst) def) where (env2, if_decl) = tyConToIfaceDecl env1 tc toIfaceClassOp (sel_id, def_meth) = ASSERT(sel_tyvars == clas_tyvars) IfaceClassOp (getOccName sel_id) (tidyToIfaceType env1 op_ty) (fmap toDmSpec def_meth) where -- Be careful when splitting the type, because of things -- like class Foo a where -- op :: (?x :: String) => a -> a -- and class Baz a where -- op :: (Ord a) => a -> a (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id) op_ty = funResultTy rho_ty toDmSpec :: (Name, DefMethSpec Type) -> DefMethSpec IfaceType toDmSpec (_, VanillaDM) = VanillaDM toDmSpec (_, GenericDM dm_ty) = GenericDM (tidyToIfaceType env1 dm_ty) toIfaceFD (tvs1, tvs2) = (map (getFS . tidyTyVar env1) tvs1, map (getFS . tidyTyVar env1) tvs2) -------------------------- tidyToIfaceType :: TidyEnv -> Type -> IfaceType tidyToIfaceType env ty = toIfaceType (tidyType env ty) tidyToIfaceTcArgs :: TidyEnv -> TyCon -> [Type] -> IfaceTcArgs tidyToIfaceTcArgs env tc tys = toIfaceTcArgs tc (tidyTypes env tys) tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext tidyToIfaceContext env theta = map (tidyToIfaceType env) theta tidyTyClTyCoVarBndrs :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar]) tidyTyClTyCoVarBndrs env tvs = mapAccumL tidyTyClTyCoVarBndr env tvs tidyTyClTyCoVarBndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar) -- If the type variable "binder" is in scope, don't re-bind it -- In a class decl, for example, the ATD binders mention -- (amd must mention) the class tyvars tidyTyClTyCoVarBndr env@(_, subst) tv | Just tv' <- lookupVarEnv subst tv = (env, tv') | otherwise = tidyTyCoVarBndr env tv tidyTyVar :: TidyEnv -> TyVar -> TyVar tidyTyVar (_, subst) tv = lookupVarEnv subst tv `orElse` tv -- TcType.tidyTyVarOcc messes around with FlatSkols getFS :: NamedThing a => a -> FastString getFS x = occNameFS (getOccName x) -------------------------- instanceToIfaceInst :: ClsInst -> IfaceClsInst instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag , is_cls_nm = cls_name, is_cls = cls , is_tcs = mb_tcs , is_orphan = orph }) = ASSERT( cls_name == className cls ) IfaceClsInst { ifDFun = dfun_name, ifOFlag = oflag, ifInstCls = cls_name, ifInstTys = map do_rough mb_tcs, ifInstOrph = orph } where do_rough Nothing = Nothing do_rough (Just n) = Just (toIfaceTyCon_name n) dfun_name = idName dfun_id -------------------------- famInstToIfaceFamInst :: FamInst -> IfaceFamInst famInstToIfaceFamInst (FamInst { fi_axiom = axiom, fi_fam = fam, fi_tcs = roughs }) = IfaceFamInst { ifFamInstAxiom = coAxiomName axiom , ifFamInstFam = fam , ifFamInstTys = map do_rough roughs , ifFamInstOrph = orph } where do_rough Nothing = Nothing do_rough (Just n) = Just (toIfaceTyCon_name n) fam_decl = tyConName $ coAxiomTyCon axiom mod = ASSERT( isExternalName (coAxiomName axiom) ) nameModule (coAxiomName axiom) is_local name = nameIsLocalOrFrom mod name lhs_names = filterNameSet is_local (orphNamesOfCoCon axiom) orph | is_local fam_decl = NotOrphan (nameOccName fam_decl) | otherwise = chooseOrphanAnchor $ nameSetElems lhs_names -------------------------- toIfaceLetBndr :: Id -> IfaceLetBndr toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id)) (toIfaceType (idType id)) (toIfaceIdInfo (idInfo id)) -- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr -- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn --------------------------t toIfaceIdDetails :: IdDetails -> IfaceIdDetails toIfaceIdDetails VanillaId = IfVanillaId toIfaceIdDetails (DFunId {}) = IfDFunId toIfaceIdDetails (RecSelId { sel_naughty = n , sel_tycon = tc }) = let iface = case tc of RecSelData ty_con -> Left (toIfaceTyCon ty_con) RecSelPatSyn pat_syn -> Right (patSynToIfaceDecl pat_syn) in IfRecSelId iface n -- The remaining cases are all "implicit Ids" which don't -- appear in interface files at all toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other) IfVanillaId -- Unexpected; the other toIfaceIdInfo :: IdInfo -> IfaceIdInfo toIfaceIdInfo id_info = case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo, inline_hsinfo, unfold_hsinfo] of [] -> NoInfo infos -> HasInfo infos -- NB: strictness and arity must appear in the list before unfolding -- See TcIface.tcUnfolding where ------------ Arity -------------- arity_info = arityInfo id_info arity_hsinfo | arity_info == 0 = Nothing | otherwise = Just (HsArity arity_info) ------------ Caf Info -------------- caf_info = cafInfo id_info caf_hsinfo = case caf_info of NoCafRefs -> Just HsNoCafRefs _other -> Nothing ------------ Strictness -------------- -- No point in explicitly exporting TopSig sig_info = strictnessInfo id_info strict_hsinfo | not (isNopSig sig_info) = Just (HsStrictness sig_info) | otherwise = Nothing ------------ Unfolding -------------- unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info) loop_breaker = isStrongLoopBreaker (occInfo id_info) ------------ Inline prag -------------- inline_prag = inlinePragInfo id_info inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing | otherwise = Just (HsInline inline_prag) -------------------------- toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs , uf_src = src , uf_guidance = guidance }) = Just $ HsUnfold lb $ case src of InlineStable -> case guidance of UnfWhen {ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok } -> IfInlineRule arity unsat_ok boring_ok if_rhs _other -> IfCoreUnfold True if_rhs InlineCompulsory -> IfCompulsory if_rhs InlineRhs -> IfCoreUnfold False if_rhs -- Yes, even if guidance is UnfNever, expose the unfolding -- If we didn't want to expose the unfolding, TidyPgm would -- have stuck in NoUnfolding. For supercompilation we want -- to see that unfolding! where if_rhs = toIfaceExpr rhs toIfUnfolding lb (DFunUnfolding { df_bndrs = bndrs, df_args = args }) = Just (HsUnfold lb (IfDFunUnfold (map toIfaceBndr bndrs) (map toIfaceExpr args))) -- No need to serialise the data constructor; -- we can recover it from the type of the dfun toIfUnfolding _ _ = Nothing -------------------------- coreRuleToIfaceRule :: CoreRule -> IfaceRule coreRuleToIfaceRule (BuiltinRule { ru_fn = fn}) = pprTrace "toHsRule: builtin" (ppr fn) $ bogusIfaceRule fn coreRuleToIfaceRule (Rule { ru_name = name, ru_fn = fn, ru_act = act, ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs, ru_orphan = orph, ru_auto = auto }) = IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = map toIfaceBndr bndrs, ifRuleHead = fn, ifRuleArgs = map do_arg args, ifRuleRhs = toIfaceExpr rhs, ifRuleAuto = auto, ifRuleOrph = orph } where -- For type args we must remove synonyms from the outermost -- level. Reason: so that when we read it back in we'll -- construct the same ru_rough field as we have right now; -- see tcIfaceRule do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty)) do_arg (Coercion co) = IfaceCo (toIfaceCoercion co) do_arg arg = toIfaceExpr arg bogusIfaceRule :: Name -> IfaceRule bogusIfaceRule id_name = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive, ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [], ifRuleRhs = IfaceExt id_name, ifRuleOrph = IsOrphan, ifRuleAuto = True } --------------------- toIfaceExpr :: CoreExpr -> IfaceExpr toIfaceExpr (Var v) = toIfaceVar v toIfaceExpr (Lit l) = IfaceLit l toIfaceExpr (Type ty) = IfaceType (toIfaceType ty) toIfaceExpr (Coercion co) = IfaceCo (toIfaceCoercion co) toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x, toIfaceOneShot x) (toIfaceExpr b) toIfaceExpr (App f a) = toIfaceApp f [a] toIfaceExpr (Case s x ty as) | null as = IfaceECase (toIfaceExpr s) (toIfaceType ty) | otherwise = IfaceCase (toIfaceExpr s) (getFS x) (map toIfaceAlt as) toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e) toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceCoercion co) toIfaceExpr (Tick t e) | Just t' <- toIfaceTickish t = IfaceTick t' (toIfaceExpr e) | otherwise = toIfaceExpr e toIfaceOneShot :: Id -> IfaceOneShot toIfaceOneShot id | isId id , OneShotLam <- oneShotInfo (idInfo id) = IfaceOneShot | otherwise = IfaceNoOneShot --------------------- toIfaceTickish :: Tickish Id -> Maybe IfaceTickish toIfaceTickish (ProfNote cc tick push) = Just (IfaceSCC cc tick push) toIfaceTickish (HpcTick modl ix) = Just (IfaceHpcTick modl ix) toIfaceTickish (SourceNote src names) = Just (IfaceSource src names) toIfaceTickish (Breakpoint {}) = Nothing -- Ignore breakpoints, since they are relevant only to GHCi, and -- should not be serialised (Trac #8333) --------------------- toIfaceBind :: Bind Id -> IfaceBinding toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r) toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs] --------------------- toIfaceAlt :: (AltCon, [Var], CoreExpr) -> (IfaceConAlt, [FastString], IfaceExpr) toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r) --------------------- toIfaceCon :: AltCon -> IfaceConAlt toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc) toIfaceCon (LitAlt l) = IfaceLitAlt l toIfaceCon DEFAULT = IfaceDefault --------------------- toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr toIfaceApp (App f a) as = toIfaceApp f (a:as) toIfaceApp (Var v) as = case isDataConWorkId_maybe v of -- We convert the *worker* for tuples into IfaceTuples Just dc | saturated , Just tup_sort <- tyConTuple_maybe tc -> IfaceTuple tup_sort tup_args where val_args = dropWhile isTypeArg as saturated = val_args `lengthIs` idArity v tup_args = map toIfaceExpr val_args tc = dataConTyCon dc _ -> mkIfaceApps (toIfaceVar v) as toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as --------------------- toIfaceVar :: Id -> IfaceExpr toIfaceVar v | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v)) -- Foreign calls have special syntax | isExternalName name = IfaceExt name | otherwise = IfaceLcl (getFS name) where name = idName v
nushio3/ghc
compiler/iface/MkIface.hs
bsd-3-clause
78,421
3
22
24,829
14,095
7,405
6,690
-1
-1
-- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 {-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- Modify and collect code generation for final STG program {- This is now a sort-of-normal STG-to-STG pass (WDP 94/06), run by stg2stg. - Traverses the STG program collecting the cost centres. These are required to declare the cost centres at the start of code generation. Note: because of cross-module unfolding, some of these cost centres may be from other modules. - Puts on CAF cost-centres if the user has asked for individual CAF cost-centres. -} module ETA.Profiling.SCCfinal ( stgMassageForProfiling ) where #include "HsVersions.h" import ETA.StgSyn.StgSyn import ETA.Profiling.CostCentre -- lots of things import ETA.BasicTypes.Id import ETA.BasicTypes.Name import ETA.BasicTypes.Module import ETA.BasicTypes.UniqSupply ( UniqSupply ) import ETA.Utils.ListSetOps ( removeDups ) import ETA.Utils.Outputable import ETA.Main.DynFlags import ETA.Core.CoreSyn ( Tickish(..) ) import ETA.Utils.FastString import ETA.BasicTypes.SrcLoc import ETA.Utils.Util import Control.Monad (liftM, ap) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif stgMassageForProfiling :: DynFlags -> Module -- module name -> UniqSupply -- unique supply -> [StgBinding] -- input -> (CollectedCCs, [StgBinding]) stgMassageForProfiling dflags mod_name _us stg_binds = let ((local_ccs, extern_ccs, cc_stacks), stg_binds2) = initMM mod_name (do_top_bindings stg_binds) (fixed_ccs, fixed_cc_stacks) = if gopt Opt_AutoSccsOnIndividualCafs dflags then ([],[]) -- don't need "all CAFs" CC else ([all_cafs_cc], [all_cafs_ccs]) local_ccs_no_dups = fst (removeDups cmpCostCentre local_ccs) extern_ccs_no_dups = fst (removeDups cmpCostCentre extern_ccs) in ((fixed_ccs ++ local_ccs_no_dups, extern_ccs_no_dups, fixed_cc_stacks ++ cc_stacks), stg_binds2) where span = mkGeneralSrcSpan (mkFastString "<entire-module>") -- XXX do better all_cafs_cc = mkAllCafsCC mod_name span all_cafs_ccs = mkSingletonCCS all_cafs_cc ---------- do_top_bindings :: [StgBinding] -> MassageM [StgBinding] do_top_bindings [] = return [] do_top_bindings (StgNonRec b rhs : bs) = do rhs' <- do_top_rhs b rhs bs' <- do_top_bindings bs return (StgNonRec b rhs' : bs') do_top_bindings (StgRec pairs : bs) = do pairs2 <- mapM do_pair pairs bs' <- do_top_bindings bs return (StgRec pairs2 : bs') where do_pair (b, rhs) = do rhs2 <- do_top_rhs b rhs return (b, rhs2) ---------- do_top_rhs :: Id -> StgRhs -> MassageM StgRhs do_top_rhs _ (StgRhsClosure _ _ _ _ _ [] (StgTick (ProfNote _cc False{-not tick-} _push) (StgConApp con args))) | not (isDllConApp dflags mod_name con args) -- Trivial _scc_ around nothing but static data -- Eliminate _scc_ ... and turn into StgRhsCon -- isDllConApp checks for LitLit args too = return (StgRhsCon dontCareCCS con args) do_top_rhs binder (StgRhsClosure _ bi fv u srt [] body) = do -- Top level CAF without a cost centre attached -- Attach CAF cc (collect if individual CAF ccs) caf_ccs <- if gopt Opt_AutoSccsOnIndividualCafs dflags then let cc = mkAutoCC binder modl CafCC ccs = mkSingletonCCS cc -- careful: the binder might be :Main.main, -- which doesn't belong to module mod_name. -- bug #249, tests prof001, prof002 modl | Just m <- nameModule_maybe (idName binder) = m | otherwise = mod_name in do collectNewCC cc collectCCS ccs return ccs else return all_cafs_ccs body' <- do_expr body return (StgRhsClosure caf_ccs bi fv u srt [] body') do_top_rhs _ (StgRhsClosure _no_ccs bi fv u srt args body) = do body' <- do_expr body return (StgRhsClosure dontCareCCS bi fv u srt args body') do_top_rhs _ (StgRhsCon _ con args) -- Top-level (static) data is not counted in heap -- profiles; nor do we set CCCS from it; so we -- just slam in dontCareCostCentre = return (StgRhsCon dontCareCCS con args) ------ do_expr :: StgExpr -> MassageM StgExpr do_expr (StgLit l) = return (StgLit l) do_expr (StgApp fn args) = return (StgApp fn args) do_expr (StgConApp con args) = return (StgConApp con args) do_expr (StgOpApp con args res_ty) = return (StgOpApp con args res_ty) do_expr (StgTick note@(ProfNote cc _ _) expr) = do -- Ha, we found a cost centre! collectCC cc expr' <- do_expr expr return (StgTick note expr') do_expr (StgTick ti expr) = do expr' <- do_expr expr return (StgTick ti expr') do_expr (StgCase expr fv1 fv2 bndr srt alt_type alts) = do expr' <- do_expr expr alts' <- mapM do_alt alts return (StgCase expr' fv1 fv2 bndr srt alt_type alts') where do_alt (id, bs, use_mask, e) = do e' <- do_expr e return (id, bs, use_mask, e') do_expr (StgLet b e) = do (b,e) <- do_let b e return (StgLet b e) do_expr (StgLetNoEscape lvs1 lvs2 b e) = do (b,e) <- do_let b e return (StgLetNoEscape lvs1 lvs2 b e) do_expr other = pprPanic "SCCfinal.do_expr" (ppr other) ---------------------------------- do_let (StgNonRec b rhs) e = do rhs' <- do_rhs rhs e' <- do_expr e return (StgNonRec b rhs',e') do_let (StgRec pairs) e = do pairs' <- mapM do_pair pairs e' <- do_expr e return (StgRec pairs', e') where do_pair (b, rhs) = do rhs2 <- do_rhs rhs return (b, rhs2) ---------------------------------- do_rhs :: StgRhs -> MassageM StgRhs -- We play much the same game as we did in do_top_rhs above; -- but we don't have to worry about cafs etc. -- throw away the SCC if we don't have to count entries. This -- is a little bit wrong, because we're attributing the -- allocation of the constructor to the wrong place (XXX) -- We should really attach (PushCC cc CurrentCCS) to the rhs, -- but need to reinstate PushCC for that. do_rhs (StgRhsClosure _closure_cc _bi _fv _u _srt [] (StgTick (ProfNote cc False{-not tick-} _push) (StgConApp con args))) = do collectCC cc return (StgRhsCon currentCCS con args) do_rhs (StgRhsClosure _ bi fv u srt args expr) = do expr' <- do_expr expr return (StgRhsClosure currentCCS bi fv u srt args expr') do_rhs (StgRhsCon _ con args) = return (StgRhsCon currentCCS con args) -- ----------------------------------------------------------------------------- -- Boring monad stuff for this newtype MassageM result = MassageM { unMassageM :: Module -- module name -> CollectedCCs -> (CollectedCCs, result) } instance Functor MassageM where fmap = liftM instance Applicative MassageM where pure = return (<*>) = ap instance Monad MassageM where return x = MassageM (\_ ccs -> (ccs, x)) (>>=) = thenMM (>>) = thenMM_ -- the initMM function also returns the final CollectedCCs initMM :: Module -- module name, which we may consult -> MassageM a -> (CollectedCCs, a) initMM mod_name (MassageM m) = m mod_name ([],[],[]) thenMM :: MassageM a -> (a -> MassageM b) -> MassageM b thenMM_ :: MassageM a -> (MassageM b) -> MassageM b thenMM expr cont = MassageM $ \mod ccs -> case unMassageM expr mod ccs of { (ccs2, result) -> unMassageM (cont result) mod ccs2 } thenMM_ expr cont = MassageM $ \mod ccs -> case unMassageM expr mod ccs of { (ccs2, _) -> unMassageM cont mod ccs2 } collectCC :: CostCentre -> MassageM () collectCC cc = MassageM $ \mod_name (local_ccs, extern_ccs, ccss) -> if (cc `ccFromThisModule` mod_name) then ((cc : local_ccs, extern_ccs, ccss), ()) else -- must declare it "extern" ((local_ccs, cc : extern_ccs, ccss), ()) -- Version of collectCC used when we definitely want to declare this -- CC as local, even if its module name is not the same as the current -- module name (eg. the special :Main module) see bug #249, #1472, -- test prof001,prof002. collectNewCC :: CostCentre -> MassageM () collectNewCC cc = MassageM $ \_mod_name (local_ccs, extern_ccs, ccss) -> ((cc : local_ccs, extern_ccs, ccss), ()) collectCCS :: CostCentreStack -> MassageM () collectCCS ccs = MassageM $ \_mod_name (local_ccs, extern_ccs, ccss) -> ASSERT(not (noCCSAttached ccs)) ((local_ccs, extern_ccs, ccs : ccss), ())
pparkkin/eta
compiler/ETA/Profiling/SCCfinal.hs
bsd-3-clause
9,472
0
21
2,872
2,333
1,218
1,115
170
20
main = do a; a; a; a; a; a
mpickering/hlint-refactor
tests/examples/Duplicate1.hs
bsd-3-clause
26
0
6
8
29
14
15
1
1
-- | This module provides an API for turning "markup" values into -- widgets. This module uses the Data.Text.Markup interface in this -- package to assign attributes to substrings in a text string; to -- manipulate markup using (for example) syntax highlighters, see that -- module. module Brick.Markup ( Markup , markup , (@?) , GetAttr(..) ) where import Control.Lens ((.~), (&), (^.)) import Control.Monad (forM) import qualified Data.Text as T import Data.Text.Markup import Data.Default (def) import Graphics.Vty (Attr, horizCat, string) import Brick.AttrMap import Brick.Types -- | A type class for types that provide access to an attribute in the -- rendering monad. You probably won't need to instance this. class GetAttr a where -- | Where to get the attribute for this attribute metadata. getAttr :: a -> RenderM Attr instance GetAttr Attr where getAttr a = do c <- getContext return $ mergeWithDefault a (c^.ctxAttrMapL) instance GetAttr AttrName where getAttr = lookupAttrName -- | Build a piece of markup from text with an assigned attribute name. -- When the markup is rendered, the attribute name will be looked up in -- the rendering context's 'AttrMap' to determine the attribute to use -- for this piece of text. (@?) :: T.Text -> AttrName -> Markup AttrName (@?) = (@@) -- | Build a widget from markup. markup :: (Eq a, GetAttr a) => Markup a -> Widget markup m = Widget Fixed Fixed $ do let pairs = markupToList m imgs <- forM pairs $ \(t, aSrc) -> do a <- getAttr aSrc return $ string a $ T.unpack t return $ def & imageL .~ horizCat imgs
sisirkoppaka/brick
src/Brick/Markup.hs
bsd-3-clause
1,653
0
15
362
354
200
154
31
1
{-| Module : CSH.Eval.Frontend.Widget Description : Reusable widgets for use in EvalFrontend pages Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015 License : MIT Maintainer : [email protected] Stability : Provisional Portability : POSIX Defines the web application layer of Evals. -} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module CSH.Eval.Frontend.Widgets ( widgetPanel , widgetPanelOffset , widgetPanelText ) where import qualified Data.Text as T import CSH.Eval.Frontend.Data import Text.Blaze (preEscapedText) import Yesod -- | A helper function to convert integers to text, to make templates that use -- Integer arguments more readable. toText :: Integer -> T.Text toText = T.pack . show -- | A basic widget for a panel widgetPanel :: Integer -- horizontal size of the panel -> Widget -- widget for the title of the panel -> Widget -- widget for the body of the panel -> Widget widgetPanel mdsize = widgetPanelOffset mdsize 0 widgetPanelOffset :: Integer -> Integer -> Widget -> Widget -> Widget widgetPanelOffset mdsize mdoffset title body = $(whamletFile "frontend/templates/widgets/panel.hamlet") -- | A basic widget for a panel that takes text as arguments instead of widgets widgetPanelText :: Integer -- horizontal size of the panel -> T.Text -- html for the title of the panel -> T.Text -- html for the body of the panel -> Widget widgetPanelText mdsize title body = $(whamletFile "frontend/templates/widgets/panelText.hamlet")
gambogi/csh-eval
src/CSH/Eval/Frontend/Widgets.hs
mit
1,768
0
8
379
198
117
81
28
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 The @TyCon@ datatype -} {-# LANGUAGE CPP, DeriveDataTypeable #-} module TyCon( -- * Main TyCon data types TyCon, FieldLabel, AlgTyConRhs(..), visibleDataCons, TyConParent(..), isNoParent, FamTyConFlav(..), Role(..), -- ** Constructing TyCons mkAlgTyCon, mkClassTyCon, mkFunTyCon, mkPrimTyCon, mkKindTyCon, mkLiftedPrimTyCon, mkTupleTyCon, mkSynonymTyCon, mkFamilyTyCon, mkPromotedDataCon, mkPromotedTyCon, -- ** Predicates on TyCons isAlgTyCon, isClassTyCon, isFamInstTyCon, isFunTyCon, isPrimTyCon, isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, isTypeSynonymTyCon, isDecomposableTyCon, isPromotedDataCon, isPromotedTyCon, isPromotedDataCon_maybe, isPromotedTyCon_maybe, promotableTyCon_maybe, promoteTyCon, isDataTyCon, isProductTyCon, isDataProductTyCon_maybe, isEnumerationTyCon, isNewTyCon, isAbstractTyCon, isFamilyTyCon, isOpenFamilyTyCon, isTypeFamilyTyCon, isDataFamilyTyCon, isOpenTypeFamilyTyCon, isClosedSynFamilyTyCon_maybe, isBuiltInSynFamTyCon_maybe, isUnLiftedTyCon, isGadtSyntaxTyCon, isDistinctTyCon, isDistinctAlgRhs, isTyConAssoc, tyConAssoc_maybe, isRecursiveTyCon, isImplicitTyCon, -- ** Extracting information out of TyCons tyConName, tyConKind, tyConUnique, tyConTyVars, tyConCType, tyConCType_maybe, tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe, tyConSingleAlgDataCon_maybe, tyConFamilySize, tyConStupidTheta, tyConArity, tyConRoles, tyConParent, tyConTuple_maybe, tyConClass_maybe, tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe, synTyConDefn_maybe, synTyConRhs_maybe, famTyConFlav_maybe, algTyConRhs, newTyConRhs, newTyConEtadArity, newTyConEtadRhs, unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe, tupleTyConBoxity, tupleTyConSort, tupleTyConArity, -- ** Manipulating TyCons tcExpandTyCon_maybe, coreExpandTyCon_maybe, makeTyConAbstract, newTyConCo, newTyConCo_maybe, pprPromotionQuote, -- * Primitive representations of Types PrimRep(..), PrimElemRep(..), tyConPrimRep, isVoidRep, isGcPtrRep, primRepSizeW, primElemRepSizeB, -- * Recursion breaking RecTcChecker, initRecTc, checkRecTc ) where #include "HsVersions.h" import {-# SOURCE #-} TypeRep ( Kind, Type, PredType ) import {-# SOURCE #-} DataCon ( DataCon, isVanillaDataCon ) import Var import Class import BasicTypes import DynFlags import ForeignCall import Name import NameSet import CoAxiom import PrelNames import Maybes import Outputable import Constants import Util import qualified Data.Data as Data import Data.Typeable (Typeable) {- ----------------------------------------------- Notes about type families ----------------------------------------------- Note [Type synonym families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Type synonym families, also known as "type functions", map directly onto the type functions in FC: type family F a :: * type instance F Int = Bool ..etc... * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon * From the user's point of view (F Int) and Bool are simply equivalent types. * A Haskell 98 type synonym is a degenerate form of a type synonym family. * Type functions can't appear in the LHS of a type function: type instance F (F Int) = ... -- BAD! * Translation of type family decl: type family F a :: * translates to a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon type family G a :: * where G Int = Bool G Bool = Char G a = () translates to a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the appropriate CoAxiom representing the equations * In the future we might want to support * injective type families (allow decomposition) but we don't at the moment [2013] Note [Data type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ See also Note [Wrappers for data instance tycons] in MkId.lhs * Data type families are declared thus data family T a :: * data instance T Int = T1 | T2 Bool Here T is the "family TyCon". * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon * The user does not see any "equivalent types" as he did with type synonym families. He just sees constructors with types T1 :: T Int T2 :: Bool -> T Int * Here's the FC version of the above declarations: data T a data R:TInt = T1 | T2 Bool axiom ax_ti : T Int ~ R:TInt The R:TInt is the "representation TyCons". It has an AlgTyConParent of FamInstTyCon T [Int] ax_ti * The axiom ax_ti may be eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls * The data contructor T2 has a wrapper (which is what the source-level "T2" invokes): $WT2 :: Bool -> T Int $WT2 b = T2 b `cast` sym ax_ti * A data instance can declare a fully-fledged GADT: data instance T (a,b) where X1 :: T (Int,Bool) X2 :: a -> b -> T (a,b) Here's the FC version of the above declaration: data R:TPair a where X1 :: R:TPair Int Bool X2 :: a -> b -> R:TPair a b axiom ax_pr :: T (a,b) ~ R:TPair a b $WX1 :: forall a b. a -> b -> T (a,b) $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b) The R:TPair are the "representation TyCons". We have a bit of work to do, to unpick the result types of the data instance declaration for T (a,b), to get the result type in the representation; e.g. T (a,b) --> R:TPair a b The representation TyCon R:TList, has an AlgTyConParent of FamInstTyCon T [(a,b)] ax_pr * Notice that T is NOT translated to a FC type function; it just becomes a "data type" with no constructors, which can be coerced inot into R:TInt, R:TPair by the axioms. These axioms axioms come into play when (and *only* when) you - use a data constructor - do pattern matching Rather like newtype, in fact As a result - T behaves just like a data type so far as decomposition is concerned - (T Int) is not implicitly converted to R:TInt during type inference. Indeed the latter type is unknown to the programmer. - There *is* an instance for (T Int) in the type-family instance environment, but it is only used for overlap checking - It's fine to have T in the LHS of a type function: type instance F (T a) = [a] It was this last point that confused me! The big thing is that you should not think of a data family T as a *type function* at all, not even an injective one! We can't allow even injective type functions on the LHS of a type function: type family injective G a :: * type instance F (G Int) = Bool is no good, even if G is injective, because consider type instance G Int = Bool type instance F Bool = Char So a data type family is not an injective type function. It's just a data type with some axioms that connect it to other data types. Note [Associated families and their parent class] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *Associated* families are just like *non-associated* families, except that they have a TyConParent of AssocFamilyTyCon, which identifies the parent class. However there is an important sharing relationship between * the tyConTyVars of the parent Class * the tyConTyvars of the associated TyCon class C a b where data T p a type F a q b Here the 'a' and 'b' are shared with the 'Class'; that is, they have the same Unique. This is important. In an instance declaration we expect * all the shared variables to be instantiated the same way * the non-shared variables of the associated type should not be instantiated at all instance C [x] (Tree y) where data T p [x] = T1 x | T2 p type F [x] q (Tree y) = (x,y,q) Note [TyCon Role signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Every tycon has a role signature, assigning a role to each of the tyConTyVars (or of equal length to the tyConArity, if there are no tyConTyVars). An example demonstrates these best: say we have a tycon T, with parameters a at nominal, b at representational, and c at phantom. Then, to prove representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have nominal equality between a1 and a2, representational equality between b1 and b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This might happen, say, with the following declaration: data T a b c where MkT :: b -> T Int b c Data and class tycons have their roles inferred (see inferRoles in TcTyDecls), as do vanilla synonym tycons. Family tycons have all parameters at role N, though it is conceivable that we could relax this restriction. (->)'s and tuples' parameters are at role R. Each primitive tycon declares its roles; it's worth noting that (~#)'s parameters are at role N. Promoted data constructors' type arguments are at role R. All kind arguments are at role N. ************************************************************************ * * \subsection{The data type} * * ************************************************************************ -} -- | TyCons represent type constructors. Type constructors are introduced by -- things such as: -- -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of -- kind @*@ -- -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor -- -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor -- of kind @* -> *@ -- -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor -- of kind @*@ -- -- This data type also encodes a number of primitive, built in type constructors -- such as those for function and tuple types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.lhs data TyCon = -- | The function type constructor, @(->)@ FunTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) } -- | Algebraic type constructors, which are defined to be those -- arising @data@ type and @newtype@ declarations. All these -- constructors are lifted and boxed. See 'AlgTyConRhs' for more -- information. | AlgTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the -- type constructor. -- Invariant: length tyvars = arity -- Precisely, this list scopes over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in algTyConRhs.NewTyCon -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] tyConCType :: Maybe CType,-- ^ The C type that should be used -- for this type when using the FFI -- and CAPI algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT -- syntax? If so, that doesn't mean it's a -- true GADT; only that the "where" form -- was used. This field is used only to -- guide pretty-printing algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data -- type (always empty for GADTs). A -- \"stupid theta\" is the context to -- the left of an algebraic type -- declaration, e.g. @Eq a@ in the -- declaration @data Eq a => T a ...@. algTcRhs :: AlgTyConRhs, -- ^ Contains information about the -- data constructors of the algebraic type algTcRec :: RecFlag, -- ^ Tells us whether the data type is part -- of a mutually-recursive group or not algTcParent :: TyConParent, -- ^ Gives the class or family declaration -- 'TyCon' for derived 'TyCon's representing -- class or family instances, respectively. -- See also 'synTcParent' tcPromoted :: Maybe TyCon -- ^ Promoted TyCon, if any } -- | Represents the infinite family of tuple type constructors, -- @()@, @(a,b)@, @(# a, b #)@ etc. | TupleTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTupleSort :: TupleSort,-- ^ Is this a boxed, unboxed or constraint -- tuple? tyConTyVars :: [TyVar], -- ^ List of type and kind variables in this -- TyCon. Includes implicit kind variables. -- Invariant: -- length tyConTyVars = tyConArity dataCon :: DataCon, -- ^ Corresponding tuple data constructor tcPromoted :: Maybe TyCon -- ^ Nothing for unboxed tuples } -- | Represents type synonyms | SynonymTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ List of type and kind variables in this -- TyCon. Includes implicit kind variables. -- Invariant: length tyConTyVars = tyConArity tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] synTcRhs :: Type -- ^ Contains information about the expansion -- of the synonym } -- | Represents type families | FamilyTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the -- type constructor. -- Invariant: length tyvars = arity -- Precisely, this list scopes over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in 'algTyConRhs.NewTyCon' -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed, -- abstract, built-in. See comments for -- FamTyConFlav famTcParent :: TyConParent -- ^ TyCon of enclosing class for -- associated type families } -- | Primitive types; cannot be defined in Haskell. This includes -- the usual suspects (such as @Int#@) as well as foreign-imported -- types and kinds | PrimTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just -- the return kind) tyConArity :: Arity, -- ^ Number of arguments this TyCon must -- receive to be considered saturated -- (including implicit kind variables) tcRoles :: [Role], -- ^ The role for each type variable -- This list has the same length as tyConTyVars -- See also Note [TyCon Role signatures] primTyConRep :: PrimRep,-- ^ Many primitive tycons are unboxed, but -- some are boxed (represented by -- pointers). This 'PrimRep' holds that -- information. Only relevant if tyConKind = * isUnLifted :: Bool -- ^ Most primitive tycons are unlifted (may -- not contain bottom) but other are lifted, -- e.g. @RealWorld@ } -- | Represents promoted data constructor. | PromotedDataCon { -- See Note [Promoted data constructors] tyConUnique :: Unique, -- ^ Same Unique as the data constructor tyConName :: Name, -- ^ Same Name as the data constructor tyConArity :: Arity, tyConKind :: Kind, -- ^ Translated type of the data constructor tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars dataCon :: DataCon -- ^ Corresponding data constructor } -- | Represents promoted type constructor. | PromotedTyCon { tyConUnique :: Unique, -- ^ Same Unique as the type constructor tyConName :: Name, -- ^ Same Name as the type constructor tyConArity :: Arity, -- ^ n if ty_con :: * -> ... -> * n times tyConKind :: Kind, -- ^ Always TysPrim.superKind ty_con :: TyCon -- ^ Corresponding type constructor } deriving Typeable -- | Names of the fields in an algebraic record type type FieldLabel = Name -- | Represents right-hand-sides of 'TyCon's for algebraic types data AlgTyConRhs -- | Says that we know nothing about this data type, except that -- it's represented by a pointer. Used when we export a data type -- abstractly into an .hi file. = AbstractTyCon Bool -- True <=> It's definitely a distinct data type, -- equal only to itself; ie not a newtype -- False <=> Not sure -- See Note [AbstractTyCon and type equality] -- | Represents an open type family without a fixed right hand -- side. Additional instances can appear at any time. -- -- These are introduced by either a top level declaration: -- -- > data T a :: * -- -- Or an associated data type declaration, within a class declaration: -- -- > class C a b where -- > data T b :: * | DataFamilyTyCon -- | Information about those 'TyCon's derived from a @data@ -- declaration. This includes data types with no constructors at -- all. | DataTyCon { data_cons :: [DataCon], -- ^ The data type constructors; can be empty if the -- user declares the type to have no constructors -- -- INVARIANT: Kept in order of increasing 'DataCon' -- tag (see the tag assignment in DataCon.mkDataCon) is_enum :: Bool -- ^ Cached value: is this an enumeration type? -- See Note [Enumeration types] } -- | Information about those 'TyCon's derived from a @newtype@ declaration | NewTyCon { data_con :: DataCon, -- ^ The unique constructor for the @newtype@. -- It has no existentials nt_rhs :: Type, -- ^ Cached value: the argument type of the -- constructor, which is just the representation -- type of the 'TyCon' (remember that @newtype@s -- do not exist at runtime so need a different -- representation type). -- -- The free 'TyVar's of this type are the -- 'tyConTyVars' from the corresponding 'TyCon' nt_etad_rhs :: ([TyVar], Type), -- ^ Same as the 'nt_rhs', but this time eta-reduced. -- Hence the list of 'TyVar's in this field may be -- shorter than the declared arity of the 'TyCon'. -- See Note [Newtype eta] nt_co :: CoAxiom Unbranched -- The axiom coercion that creates the @newtype@ -- from the representation 'Type'. -- See Note [Newtype coercions] -- Invariant: arity = #tvs in nt_etad_rhs; -- See Note [Newtype eta] -- Watch out! If any newtypes become transparent -- again check Trac #1072. } {- Note [AbstractTyCon and type equality] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TODO -} -- | Extract those 'DataCon's that we are able to learn about. Note -- that visibility in this sense does not correspond to visibility in -- the context of any particular user program! visibleDataCons :: AlgTyConRhs -> [DataCon] visibleDataCons (AbstractTyCon {}) = [] visibleDataCons DataFamilyTyCon {} = [] visibleDataCons (DataTyCon{ data_cons = cs }) = cs visibleDataCons (NewTyCon{ data_con = c }) = [c] -- ^ Both type classes as well as family instances imply implicit -- type constructors. These implicit type constructors refer to their parent -- structure (ie, the class or family from which they derive) using a type of -- the following form. We use 'TyConParent' for both algebraic and synonym -- types, but the variant 'ClassTyCon' will only be used by algebraic 'TyCon's. data TyConParent = -- | An ordinary type constructor has no parent. NoParentTyCon -- | Type constructors representing a class dictionary. -- See Note [ATyCon for classes] in TypeRep | ClassTyCon Class -- INVARIANT: the classTyCon of this Class is the -- current tycon -- | An *associated* type of a class. | AssocFamilyTyCon Class -- The class in whose declaration the family is declared -- See Note [Associated families and their parent class] -- | Type constructors representing an instance of a *data* family. -- Parameters: -- -- 1) The type family in question -- -- 2) Instance types; free variables are the 'tyConTyVars' -- of the current 'TyCon' (not the family one). INVARIANT: -- the number of types matches the arity of the family 'TyCon' -- -- 3) A 'CoTyCon' identifying the representation -- type with the type instance family | FamInstTyCon -- See Note [Data type families] (CoAxiom Unbranched) -- The coercion axiom. -- Generally of kind T ty1 ty2 ~ R:T a b c -- where T is the family TyCon, -- and R:T is the representation TyCon (ie this one) -- and a,b,c are the tyConTyVars of this TyCon -- -- BUT may be eta-reduced; see TcInstDcls -- Note [Eta reduction for data family axioms] -- Cached fields of the CoAxiom, but adjusted to -- use the tyConTyVars of this TyCon TyCon -- The family TyCon [Type] -- Argument types (mentions the tyConTyVars of this TyCon) -- Match in length the tyConTyVars of the family TyCon -- E.g. data intance T [a] = ... -- gives a representation tycon: -- data R:TList a = ... -- axiom co a :: T [a] ~ R:TList a -- with R:TList's algTcParent = FamInstTyCon T [a] co instance Outputable TyConParent where ppr NoParentTyCon = text "No parent" ppr (ClassTyCon cls) = text "Class parent" <+> ppr cls ppr (AssocFamilyTyCon cls) = text "Class parent (assoc. family)" <+> ppr cls ppr (FamInstTyCon _ tc tys) = text "Family parent (family instance)" <+> ppr tc <+> sep (map ppr tys) -- | Checks the invariants of a 'TyConParent' given the appropriate type class -- name, if any okParent :: Name -> TyConParent -> Bool okParent _ NoParentTyCon = True okParent tc_name (AssocFamilyTyCon cls) = tc_name `elem` map tyConName (classATs cls) okParent tc_name (ClassTyCon cls) = tc_name == tyConName (classTyCon cls) okParent _ (FamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys isNoParent :: TyConParent -> Bool isNoParent NoParentTyCon = True isNoParent _ = False -------------------- -- | Information pertaining to the expansion of a type synonym (@type@) data FamTyConFlav = -- | An open type synonym family e.g. @type family F x y :: * -> *@ OpenSynFamilyTyCon -- | A closed type synonym family e.g. -- @type family F x where { F Int = Bool }@ | ClosedSynFamilyTyCon (CoAxiom Branched) -- The one axiom for this family -- | A closed type synonym family declared in an hs-boot file with -- type family F a where .. | AbstractClosedSynFamilyTyCon -- | Built-in type family used by the TypeNats solver | BuiltInSynFamTyCon BuiltInSynFamily {- Note [Closed type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ * In an open type family you can add new instances later. This is the usual case. * In a closed type family you can only put equations where the family is defined. Note [Promoted data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A data constructor can be promoted to become a type constructor, via the PromotedTyCon alternative in TyCon. * Only data constructors with (a) no kind polymorphism (b) no constraints in its type (eg GADTs) are promoted. Existentials are ok; see Trac #7347. * The TyCon promoted from a DataCon has the *same* Name and Unique as the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78, say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78) * The *kind* of a promoted DataCon may be polymorphic. Example: type of DataCon Just :: forall (a:*). a -> Maybe a kind of (promoted) tycon Just :: forall (a:box). a -> Maybe a The kind is not identical to the type, because of the */box kind signature on the forall'd variable; so the tyConKind field of PromotedTyCon is not identical to the dataConUserType of the DataCon. But it's the same modulo changing the variable kinds, done by DataCon.promoteType. * Small note: We promote the *user* type of the DataCon. Eg data T = MkT {-# UNPACK #-} !(Bool, Bool) The promoted kind is MkT :: (Bool,Bool) -> T *not* MkT :: Bool -> Bool -> T Note [Enumeration types] ~~~~~~~~~~~~~~~~~~~~~~~~ We define datatypes with no constructors to *not* be enumerations; this fixes trac #2578, Otherwise we end up generating an empty table for <mod>_<type>_closure_tbl which is used by tagToEnum# to map Int# to constructors in an enumeration. The empty table apparently upset the linker. Moreover, all the data constructor must be enumerations, meaning they have type (forall abc. T a b c). GADTs are not enumerations. For example consider data T a where T1 :: T Int T2 :: T Bool T3 :: T a What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them. See Trac #4528. Note [Newtype coercions] ~~~~~~~~~~~~~~~~~~~~~~~~ The NewTyCon field nt_co is a CoAxiom which is used for coercing from the representation type of the newtype, to the newtype itself. For example, newtype T a = MkT (a -> a) the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t. In the case that the right hand side is a type application ending with the same type variables as the left hand side, we "eta-contract" the coercion. So if we had newtype S a = MkT [a] then we would generate the arity 0 axiom CoS : S ~ []. The primary reason we do this is to make newtype deriving cleaner. In the paper we'd write axiom CoT : (forall t. T t) ~ (forall t. [t]) and then when we used CoT at a particular type, s, we'd say CoT @ s which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s]) Note [Newtype eta] ~~~~~~~~~~~~~~~~~~ Consider newtype Parser a = MkParser (IO a) deriving Monad Are these two types equal (to Core)? Monad Parser Monad IO which we need to make the derived instance for Monad Parser. Well, yes. But to see that easily we eta-reduce the RHS type of Parser, in this case to ([], Froogle), so that even unsaturated applications of Parser will work right. This eta reduction is done when the type constructor is built, and cached in NewTyCon. The cached field is only used in coreExpandTyCon_maybe. Here's an example that I think showed up in practice Source code: newtype T a = MkT [a] newtype Foo m = MkFoo (forall a. m a -> Int) w1 :: Foo [] w1 = ... w2 :: Foo T w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x) After desugaring, and discarding the data constructors for the newtypes, we get: w2 :: Foo T w2 = w1 And now Lint complains unless Foo T == Foo [], and that requires T==[] This point carries over to the newtype coercion, because we need to say w2 = w1 `cast` Foo CoT so the coercion tycon CoT must have kind: T ~ [] and arity: 0 ************************************************************************ * * \subsection{PrimRep} * * ************************************************************************ Note [rep swamp] GHC has a rich selection of types that represent "primitive types" of one kind or another. Each of them makes a different set of distinctions, and mostly the differences are for good reasons, although it's probably true that we could merge some of these. Roughly in order of "includes more information": - A Width (cmm/CmmType) is simply a binary value with the specified number of bits. It may represent a signed or unsigned integer, a floating-point value, or an address. data Width = W8 | W16 | W32 | W64 | W80 | W128 - Size, which is used in the native code generator, is Width + floating point information. data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80 it is necessary because e.g. the instruction to move a 64-bit float on x86 (movsd) is different from the instruction to move a 64-bit integer (movq), so the mov instruction is parameterised by Size. - CmmType wraps Width with more information: GC ptr, float, or other value. data CmmType = CmmType CmmCat Width data CmmCat -- "Category" (not exported) = GcPtrCat -- GC pointer | BitsCat -- Non-pointer | FloatCat -- Float It is important to have GcPtr information in Cmm, since we generate info tables containing pointerhood for the GC from this. As for why we have float (and not signed/unsigned) here, see Note [Signed vs unsigned]. - ArgRep makes only the distinctions necessary for the call and return conventions of the STG machine. It is essentially CmmType + void. - PrimRep makes a few more distinctions than ArgRep: it divides non-GC-pointers into signed/unsigned and addresses, information that is necessary for passing these values to foreign functions. There's another tension here: whether the type encodes its size in bytes, or whether its size depends on the machine word size. Width and CmmType have the size built-in, whereas ArgRep and PrimRep do not. This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags. On the other hand, CmmType includes some "nonsense" values, such as CmmType GcPtrCat W32 on a 64-bit machine. -} -- | A 'PrimRep' is an abstraction of a type. It contains information that -- the code generator needs in order to pass arguments, return results, -- and store values of this type. data PrimRep = VoidRep | PtrRep | IntRep -- ^ Signed, word-sized value | WordRep -- ^ Unsigned, word-sized value | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only) | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only) | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep') | FloatRep | DoubleRep | VecRep Int PrimElemRep -- ^ A vector deriving( Eq, Show ) data PrimElemRep = Int8ElemRep | Int16ElemRep | Int32ElemRep | Int64ElemRep | Word8ElemRep | Word16ElemRep | Word32ElemRep | Word64ElemRep | FloatElemRep | DoubleElemRep deriving( Eq, Show ) instance Outputable PrimRep where ppr r = text (show r) instance Outputable PrimElemRep where ppr r = text (show r) isVoidRep :: PrimRep -> Bool isVoidRep VoidRep = True isVoidRep _other = False isGcPtrRep :: PrimRep -> Bool isGcPtrRep PtrRep = True isGcPtrRep _ = False -- | Find the size of a 'PrimRep', in words primRepSizeW :: DynFlags -> PrimRep -> Int primRepSizeW _ IntRep = 1 primRepSizeW _ WordRep = 1 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW _ FloatRep = 1 -- NB. might not take a full word primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags primRepSizeW _ AddrRep = 1 primRepSizeW _ PtrRep = 1 primRepSizeW _ VoidRep = 0 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags primElemRepSizeB :: PrimElemRep -> Int primElemRepSizeB Int8ElemRep = 1 primElemRepSizeB Int16ElemRep = 2 primElemRepSizeB Int32ElemRep = 4 primElemRepSizeB Int64ElemRep = 8 primElemRepSizeB Word8ElemRep = 1 primElemRepSizeB Word16ElemRep = 2 primElemRepSizeB Word32ElemRep = 4 primElemRepSizeB Word64ElemRep = 8 primElemRepSizeB FloatElemRep = 4 primElemRepSizeB DoubleElemRep = 8 {- ************************************************************************ * * \subsection{TyCon Construction} * * ************************************************************************ Note: the TyCon constructors all take a Kind as one argument, even though they could, in principle, work out their Kind from their other arguments. But to do so they need functions from Types, and that makes a nasty module mutual-recursion. And they aren't called from many places. So we compromise, and move their Kind calculation to the call site. -} -- | Given the name of the function type constructor and it's kind, create the -- corresponding 'TyCon'. It is reccomended to use 'TypeRep.funTyCon' if you want -- this functionality mkFunTyCon :: Name -> Kind -> TyCon mkFunTyCon name kind = FunTyCon { tyConUnique = nameUnique name, tyConName = name, tyConKind = kind, tyConArity = 2 } -- | This is the making of an algebraic 'TyCon'. Notably, you have to -- pass in the generic (in the -XGenerics sense) information about the -- type constructor - you can get hold of it easily (see Generics -- module) mkAlgTyCon :: Name -> Kind -- ^ Kind of the resulting 'TyCon' -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'. -- Arity is inferred from the length of this -- list -> [Role] -- ^ The roles for each TyVar -> Maybe CType -- ^ The C type this type corresponds to -- when using the CAPI FFI -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta' -> AlgTyConRhs -- ^ Information about dat aconstructors -> TyConParent -> RecFlag -- ^ Is the 'TyCon' recursive? -> Bool -- ^ Was the 'TyCon' declared with GADT syntax? -> Maybe TyCon -- ^ Promoted version -> TyCon mkAlgTyCon name kind tyvars roles cType stupid rhs parent is_rec gadt_syn prom_tc = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length tyvars, tyConTyVars = tyvars, tcRoles = roles, tyConCType = cType, algTcStupidTheta = stupid, algTcRhs = rhs, algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent, algTcRec = is_rec, algTcGadtSyntax = gadt_syn, tcPromoted = prom_tc } -- | Simpler specialization of 'mkAlgTyCon' for classes mkClassTyCon :: Name -> Kind -> [TyVar] -> [Role] -> AlgTyConRhs -> Class -> RecFlag -> TyCon mkClassTyCon name kind tyvars roles rhs clas is_rec = mkAlgTyCon name kind tyvars roles Nothing [] rhs (ClassTyCon clas) is_rec False Nothing -- Class TyCons are not pormoted mkTupleTyCon :: Name -> Kind -- ^ Kind of the resulting 'TyCon' -> Arity -- ^ Arity of the tuple -> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars' -> DataCon -> TupleSort -- ^ Whether the tuple is boxed or unboxed -> Maybe TyCon -- ^ Promoted version -> TyCon mkTupleTyCon name kind arity tyvars con sort prom_tc = TupleTyCon { tyConUnique = nameUnique name, tyConName = name, tyConKind = kind, tyConArity = arity, tyConTupleSort = sort, tyConTyVars = tyvars, dataCon = con, tcPromoted = prom_tc } -- | Create an unlifted primitive 'TyCon', such as @Int#@ mkPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon mkPrimTyCon name kind roles rep = mkPrimTyCon' name kind roles rep True -- | Kind constructors mkKindTyCon :: Name -> Kind -> TyCon mkKindTyCon name kind = mkPrimTyCon' name kind [] VoidRep True -- | Create a lifted primitive 'TyCon' such as @RealWorld@ mkLiftedPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon mkLiftedPrimTyCon name kind roles rep = mkPrimTyCon' name kind roles rep False mkPrimTyCon' :: Name -> Kind -> [Role] -> PrimRep -> Bool -> TyCon mkPrimTyCon' name kind roles rep is_unlifted = PrimTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length roles, tcRoles = roles, primTyConRep = rep, isUnLifted = is_unlifted } -- | Create a type synonym 'TyCon' mkSynonymTyCon :: Name -> Kind -> [TyVar] -> [Role] -> Type -> TyCon mkSynonymTyCon name kind tyvars roles rhs = SynonymTyCon { tyConName = name, tyConUnique = nameUnique name, tyConKind = kind, tyConArity = length tyvars, tyConTyVars = tyvars, tcRoles = roles, synTcRhs = rhs } -- | Create a type family 'TyCon' mkFamilyTyCon:: Name -> Kind -> [TyVar] -> FamTyConFlav -> TyConParent -> TyCon mkFamilyTyCon name kind tyvars flav parent = FamilyTyCon { tyConUnique = nameUnique name , tyConName = name , tyConKind = kind , tyConArity = length tyvars , tyConTyVars = tyvars , famTcFlav = flav , famTcParent = parent } -- | Create a promoted data constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the data constructor itself; when we pretty-print -- the TyCon we add a quote; see the Outputable TyCon instance mkPromotedDataCon :: DataCon -> Name -> Unique -> Kind -> [Role] -> TyCon mkPromotedDataCon con name unique kind roles = PromotedDataCon { tyConName = name, tyConUnique = unique, tyConArity = arity, tcRoles = roles, tyConKind = kind, dataCon = con } where arity = length roles -- | Create a promoted type constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the type constructor itself mkPromotedTyCon :: TyCon -> Kind -> TyCon mkPromotedTyCon tc kind = PromotedTyCon { tyConName = getName tc, tyConUnique = getUnique tc, tyConArity = tyConArity tc, tyConKind = kind, ty_con = tc } isFunTyCon :: TyCon -> Bool isFunTyCon (FunTyCon {}) = True isFunTyCon _ = False -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors) isAbstractTyCon :: TyCon -> Bool isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True isAbstractTyCon _ = False -- | Make an algebraic 'TyCon' abstract. Panics if the supplied 'TyCon' is not -- algebraic makeTyConAbstract :: TyCon -> TyCon makeTyConAbstract tc@(AlgTyCon { algTcRhs = rhs }) = tc { algTcRhs = AbstractTyCon (isDistinctAlgRhs rhs) } makeTyConAbstract tc = pprPanic "makeTyConAbstract" (ppr tc) -- | Does this 'TyCon' represent something that cannot be defined in Haskell? isPrimTyCon :: TyCon -> Bool isPrimTyCon (PrimTyCon {}) = True isPrimTyCon _ = False -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can -- only be true for primitive and unboxed-tuple 'TyCon's isUnLiftedTyCon :: TyCon -> Bool isUnLiftedTyCon (PrimTyCon {isUnLifted = is_unlifted}) = is_unlifted isUnLiftedTyCon (TupleTyCon {tyConTupleSort = sort}) = not (isBoxed (tupleSortBoxity sort)) isUnLiftedTyCon _ = False -- | Returns @True@ if the supplied 'TyCon' resulted from either a -- @data@ or @newtype@ declaration isAlgTyCon :: TyCon -> Bool isAlgTyCon (AlgTyCon {}) = True isAlgTyCon (TupleTyCon {}) = True isAlgTyCon _ = False isDataTyCon :: TyCon -> Bool -- ^ Returns @True@ for data types that are /definitely/ represented by -- heap-allocated constructors. These are scrutinised by Core-level -- @case@ expressions, and they get info tables allocated for them. -- -- Generally, the function will be true for all @data@ types and false -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is -- not guaranteed to return @True@ in all cases that it could. -- -- NB: for a data type family, only the /instance/ 'TyCon's -- get an info table. The family declaration 'TyCon' does not isDataTyCon (AlgTyCon {algTcRhs = rhs}) = case rhs of DataTyCon {} -> True NewTyCon {} -> False DataFamilyTyCon {} -> False AbstractTyCon {} -> False -- We don't know, so return False isDataTyCon (TupleTyCon {tyConTupleSort = sort}) = isBoxed (tupleSortBoxity sort) isDataTyCon _ = False -- | 'isDistinctTyCon' is true of 'TyCon's that are equal only to -- themselves, even via coercions (except for unsafeCoerce). -- This excludes newtypes, type functions, type synonyms. -- It relates directly to the FC consistency story: -- If the axioms are consistent, -- and co : S tys ~ T tys, and S,T are "distinct" TyCons, -- then S=T. -- Cf Note [Pruning dead case alternatives] in Unify isDistinctTyCon :: TyCon -> Bool isDistinctTyCon (AlgTyCon {algTcRhs = rhs}) = isDistinctAlgRhs rhs isDistinctTyCon (FunTyCon {}) = True isDistinctTyCon (TupleTyCon {}) = True isDistinctTyCon (PrimTyCon {}) = True isDistinctTyCon (PromotedDataCon {}) = True isDistinctTyCon _ = False isDistinctAlgRhs :: AlgTyConRhs -> Bool isDistinctAlgRhs (DataTyCon {}) = True isDistinctAlgRhs (DataFamilyTyCon {}) = True isDistinctAlgRhs (AbstractTyCon distinct) = distinct isDistinctAlgRhs (NewTyCon {}) = False -- | Is this 'TyCon' that for a @newtype@ isNewTyCon :: TyCon -> Bool isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True isNewTyCon _ = False -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands -- into, and (possibly) a coercion from the representation type to the @newtype@. -- Returns @Nothing@ if this is not possible. unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, algTcRhs = NewTyCon { nt_co = co, nt_rhs = rhs }}) = Just (tvs, rhs, co) unwrapNewTyCon_maybe _ = Nothing unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co, nt_etad_rhs = (tvs,rhs) }}) = Just (tvs, rhs, co) unwrapNewTyConEtad_maybe _ = Nothing isProductTyCon :: TyCon -> Bool -- True of datatypes or newtypes that have -- one, vanilla, data constructor isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of DataTyCon{ data_cons = [data_con] } -> isVanillaDataCon data_con NewTyCon {} -> True _ -> False isProductTyCon (TupleTyCon {}) = True isProductTyCon _ = False isDataProductTyCon_maybe :: TyCon -> Maybe DataCon -- True of datatypes (not newtypes) with -- one, vanilla, data constructor isDataProductTyCon_maybe (AlgTyCon { algTcRhs = DataTyCon { data_cons = cons } }) | [con] <- cons -- Singleton , isVanillaDataCon con -- Vanilla = Just con isDataProductTyCon_maybe (TupleTyCon { dataCon = con }) = Just con isDataProductTyCon_maybe _ = Nothing -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)? isTypeSynonymTyCon :: TyCon -> Bool isTypeSynonymTyCon (SynonymTyCon {}) = True isTypeSynonymTyCon _ = False -- As for newtypes, it is in some contexts important to distinguish between -- closed synonyms and synonym families, as synonym families have no unique -- right hand side to which a synonym family application can expand. -- isDecomposableTyCon :: TyCon -> Bool -- True iff we can decompose (T a b c) into ((T a b) c) -- I.e. is it injective? -- Specifically NOT true of synonyms (open and otherwise) -- Ultimately we may have injective associated types -- in which case this test will become more interesting -- -- It'd be unusual to call isDecomposableTyCon on a regular H98 -- type synonym, because you should probably have expanded it first -- But regardless, it's not decomposable isDecomposableTyCon (SynonymTyCon {}) = False isDecomposableTyCon (FamilyTyCon {}) = False isDecomposableTyCon _other = True -- | Is this an algebraic 'TyCon' declared with the GADT syntax? isGadtSyntaxTyCon :: TyCon -> Bool isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res isGadtSyntaxTyCon _ = False -- | Is this an algebraic 'TyCon' which is just an enumeration of values? isEnumerationTyCon :: TyCon -> Bool -- See Note [Enumeration types] in TyCon isEnumerationTyCon (AlgTyCon {algTcRhs = DataTyCon { is_enum = res }}) = res isEnumerationTyCon (TupleTyCon {tyConArity = arity}) = arity == 0 isEnumerationTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family? isFamilyTyCon :: TyCon -> Bool isFamilyTyCon (FamilyTyCon {}) = True isFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True isFamilyTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family with -- instances? isOpenFamilyTyCon :: TyCon -> Bool isOpenFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True isOpenFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon }) = True isOpenFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isTypeFamilyTyCon :: TyCon -> Bool isTypeFamilyTyCon (FamilyTyCon {}) = True isTypeFamilyTyCon _ = False isOpenTypeFamilyTyCon :: TyCon -> Bool isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True isOpenTypeFamilyTyCon _ = False -- leave out abstract closed families here isClosedSynFamilyTyCon_maybe :: TyCon -> Maybe (CoAxiom Branched) isClosedSynFamilyTyCon_maybe (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon ax}) = Just ax isClosedSynFamilyTyCon_maybe _ = Nothing isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily isBuiltInSynFamTyCon_maybe (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops isBuiltInSynFamTyCon_maybe _ = Nothing -- | Is this a synonym 'TyCon' that can have may have further instances appear? isDataFamilyTyCon :: TyCon -> Bool isDataFamilyTyCon (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = True isDataFamilyTyCon _ = False -- | Are we able to extract informationa 'TyVar' to class argument list -- mappping from a given 'TyCon'? isTyConAssoc :: TyCon -> Bool isTyConAssoc tc = isJust (tyConAssoc_maybe tc) tyConAssoc_maybe :: TyCon -> Maybe Class tyConAssoc_maybe tc = case tyConParent tc of AssocFamilyTyCon cls -> Just cls _ -> Nothing -- The unit tycon didn't used to be classed as a tuple tycon -- but I thought that was silly so I've undone it -- If it can't be for some reason, it should be a AlgTyCon isTupleTyCon :: TyCon -> Bool -- ^ Does this 'TyCon' represent a tuple? -- -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they -- get spat into the interface file as tuple tycons, so I don't think -- it matters. isTupleTyCon (TupleTyCon {}) = True isTupleTyCon _ = False -- | Is this the 'TyCon' for an unboxed tuple? isUnboxedTupleTyCon :: TyCon -> Bool isUnboxedTupleTyCon (TupleTyCon {tyConTupleSort = sort}) = not (isBoxed (tupleSortBoxity sort)) isUnboxedTupleTyCon _ = False -- | Is this the 'TyCon' for a boxed tuple? isBoxedTupleTyCon :: TyCon -> Bool isBoxedTupleTyCon (TupleTyCon {tyConTupleSort = sort}) = isBoxed (tupleSortBoxity sort) isBoxedTupleTyCon _ = False -- | Extract the boxity of the given 'TyCon', if it is a 'TupleTyCon'. -- Panics otherwise tupleTyConBoxity :: TyCon -> Boxity tupleTyConBoxity tc = tupleSortBoxity (tyConTupleSort tc) -- | Extract the 'TupleSort' of the given 'TyCon', if it is a 'TupleTyCon'. -- Panics otherwise tupleTyConSort :: TyCon -> TupleSort tupleTyConSort tc = tyConTupleSort tc -- | Extract the arity of the given 'TyCon', if it is a 'TupleTyCon'. -- Panics otherwise tupleTyConArity :: TyCon -> Arity tupleTyConArity tc = tyConArity tc -- | Is this a recursive 'TyCon'? isRecursiveTyCon :: TyCon -> Bool isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True isRecursiveTyCon _ = False promotableTyCon_maybe :: TyCon -> Maybe TyCon promotableTyCon_maybe (AlgTyCon { tcPromoted = prom }) = prom promotableTyCon_maybe (TupleTyCon { tcPromoted = prom }) = prom promotableTyCon_maybe _ = Nothing promoteTyCon :: TyCon -> TyCon promoteTyCon tc = case promotableTyCon_maybe tc of Just prom_tc -> prom_tc Nothing -> pprPanic "promoteTyCon" (ppr tc) -- | Is this a PromotedTyCon? isPromotedTyCon :: TyCon -> Bool isPromotedTyCon (PromotedTyCon {}) = True isPromotedTyCon _ = False -- | Retrieves the promoted TyCon if this is a PromotedTyCon; isPromotedTyCon_maybe :: TyCon -> Maybe TyCon isPromotedTyCon_maybe (PromotedTyCon { ty_con = tc }) = Just tc isPromotedTyCon_maybe _ = Nothing -- | Is this a PromotedDataCon? isPromotedDataCon :: TyCon -> Bool isPromotedDataCon (PromotedDataCon {}) = True isPromotedDataCon _ = False -- | Retrieves the promoted DataCon if this is a PromotedDataCon; isPromotedDataCon_maybe :: TyCon -> Maybe DataCon isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc isPromotedDataCon_maybe _ = Nothing -- | Identifies implicit tycons that, in particular, do not go into interface -- files (because they are implicitly reconstructed when the interface is -- read). -- -- Note that: -- -- * Associated families are implicit, as they are re-constructed from -- the class declaration in which they reside, and -- -- * Family instances are /not/ implicit as they represent the instance body -- (similar to a @dfun@ does that for a class instance). isImplicitTyCon :: TyCon -> Bool isImplicitTyCon (FunTyCon {}) = True isImplicitTyCon (TupleTyCon {}) = True isImplicitTyCon (PrimTyCon {}) = True isImplicitTyCon (PromotedDataCon {}) = True isImplicitTyCon (PromotedTyCon {}) = True isImplicitTyCon (AlgTyCon { algTcParent = AssocFamilyTyCon {} }) = True isImplicitTyCon (AlgTyCon {}) = False isImplicitTyCon (FamilyTyCon { famTcParent = AssocFamilyTyCon {} }) = True isImplicitTyCon (FamilyTyCon {}) = False isImplicitTyCon (SynonymTyCon {}) = False tyConCType_maybe :: TyCon -> Maybe CType tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc tyConCType_maybe _ = Nothing {- ----------------------------------------------- -- Expand type-constructor applications ----------------------------------------------- -} tcExpandTyCon_maybe, coreExpandTyCon_maybe :: TyCon -> [tyco] -- ^ Arguments to 'TyCon' -> Maybe ([(TyVar,tyco)], Type, [tyco]) -- ^ Returns a 'TyVar' substitution, the body -- type of the synonym (not yet substituted) -- and any arguments remaining from the -- application -- ^ Used to create the view the /typechecker/ has on 'TyCon's. -- We expand (closed) synonyms only, cf. 'coreExpandTyCon_maybe' tcExpandTyCon_maybe (SynonymTyCon { tyConTyVars = tvs , synTcRhs = rhs }) tys = expand tvs rhs tys tcExpandTyCon_maybe _ _ = Nothing --------------- -- ^ Used to create the view /Core/ has on 'TyCon's. We expand -- not only closed synonyms like 'tcExpandTyCon_maybe', -- but also non-recursive @newtype@s coreExpandTyCon_maybe tycon tys = tcExpandTyCon_maybe tycon tys ---------------- expand :: [TyVar] -> Type -- Template -> [a] -- Args -> Maybe ([(TyVar,a)], Type, [a]) -- Expansion expand tvs rhs tys = case n_tvs `compare` length tys of LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys) EQ -> Just (tvs `zip` tys, rhs, []) GT -> Nothing where n_tvs = length tvs -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no -- constructors could be found tyConDataCons :: TyCon -> [DataCon] -- It's convenient for tyConDataCons to return the -- empty list for type synonyms etc tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` [] -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' -- is the sort that can have any constructors (note: this does not include -- abstract algebraic types) tyConDataCons_maybe :: TyCon -> Maybe [DataCon] tyConDataCons_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = cons }}) = Just cons tyConDataCons_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just [con] tyConDataCons_maybe (TupleTyCon {dataCon = con}) = Just [con] tyConDataCons_maybe _ = Nothing -- | Determine the number of value constructors a 'TyCon' has. Panics if the -- 'TyCon' is not algebraic or a tuple tyConFamilySize :: TyCon -> Int tyConFamilySize (AlgTyCon {algTcRhs = DataTyCon {data_cons = cons}}) = length cons tyConFamilySize (AlgTyCon {algTcRhs = NewTyCon {}}) = 1 tyConFamilySize (AlgTyCon {algTcRhs = DataFamilyTyCon {}}) = 0 tyConFamilySize (TupleTyCon {}) = 1 tyConFamilySize other = pprPanic "tyConFamilySize:" (ppr other) -- | Extract an 'AlgTyConRhs' with information about data constructors from an -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon' algTyConRhs :: TyCon -> AlgTyConRhs algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs algTyConRhs (TupleTyCon {dataCon = con, tyConArity = arity}) = DataTyCon { data_cons = [con], is_enum = arity == 0 } algTyConRhs other = pprPanic "algTyConRhs" (ppr other) -- | Get the list of roles for the type parameters of a TyCon tyConRoles :: TyCon -> [Role] -- See also Note [TyCon Role signatures] tyConRoles tc = case tc of { FunTyCon {} -> const_role Representational ; AlgTyCon { tcRoles = roles } -> roles ; TupleTyCon {} -> const_role Representational ; SynonymTyCon { tcRoles = roles } -> roles ; FamilyTyCon {} -> const_role Nominal ; PrimTyCon { tcRoles = roles } -> roles ; PromotedDataCon { tcRoles = roles } -> roles ; PromotedTyCon {} -> const_role Nominal } where const_role r = replicate (tyConArity tc) r -- | Extract the bound type variables and type expansion of a type synonym -- 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConRhs :: TyCon -> ([TyVar], Type) newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs) newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon) -- | The number of type parameters that need to be passed to a newtype to -- resolve it. May be less than in the definition if it can be eta-contracted. newTyConEtadArity :: TyCon -> Int newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = length (fst tvs_rhs) newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon) -- | Extract the bound type variables and type expansion of an eta-contracted -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConEtadRhs :: TyCon -> ([TyVar], Type) newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon) -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to -- construct something with the @newtype@s type from its representation type -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns -- @Nothing@ newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched) newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co newTyConCo_maybe _ = Nothing newTyConCo :: TyCon -> CoAxiom Unbranched newTyConCo tc = case newTyConCo_maybe tc of Just co -> co Nothing -> pprPanic "newTyConCo" (ppr tc) -- | Find the primitive representation of a 'TyCon' tyConPrimRep :: TyCon -> PrimRep tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration -- @data Eq a => T a ...@ tyConStupidTheta :: TyCon -> [PredType] tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid tyConStupidTheta (TupleTyCon {}) = [] tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon) -- | Extract the 'TyVar's bound by a vanilla type synonym -- and the corresponding (unsubstituted) right hand side. synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type) synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty}) = Just (tyvars, ty) synTyConDefn_maybe _ = Nothing -- | Extract the information pertaining to the right hand side of a type synonym -- (@type@) declaration. synTyConRhs_maybe :: TyCon -> Maybe Type synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs synTyConRhs_maybe _ = Nothing -- | Extract the flavour of a type family (with all the extra information that -- it carries) famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav famTyConFlav_maybe _ = Nothing -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ -- type with one alternative, a tuple type or a @newtype@ then that constructor -- is returned. If the 'TyCon' has more than one constructor, or represents a -- primitive or function type constructor then @Nothing@ is returned. In any -- other case, the function panics tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon tyConSingleDataCon_maybe (TupleTyCon {dataCon = c}) = Just c tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons = [c] }}) = Just c tyConSingleDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = c }}) = Just c tyConSingleDataCon_maybe _ = Nothing tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon -- Returns (Just con) for single-constructor *algebraic* data types -- *not* newtypes tyConSingleAlgDataCon_maybe (TupleTyCon {dataCon = c}) = Just c tyConSingleAlgDataCon_maybe (AlgTyCon {algTcRhs = DataTyCon { data_cons= [c] }}) = Just c tyConSingleAlgDataCon_maybe _ = Nothing -- | Is this 'TyCon' that for a class instance? isClassTyCon :: TyCon -> Bool isClassTyCon (AlgTyCon {algTcParent = ClassTyCon _}) = True isClassTyCon _ = False -- | If this 'TyCon' is that for a class instance, return the class it is for. -- Otherwise returns @Nothing@ tyConClass_maybe :: TyCon -> Maybe Class tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas}) = Just clas tyConClass_maybe _ = Nothing tyConTuple_maybe :: TyCon -> Maybe TupleSort tyConTuple_maybe (TupleTyCon {tyConTupleSort = sort}) = Just sort tyConTuple_maybe _ = Nothing ---------------------------------------------------------------------------- tyConParent :: TyCon -> TyConParent tyConParent (AlgTyCon {algTcParent = parent}) = parent tyConParent (FamilyTyCon {famTcParent = parent}) = parent tyConParent _ = NoParentTyCon ---------------------------------------------------------------------------- -- | Is this 'TyCon' that for a data family instance? isFamInstTyCon :: TyCon -> Bool isFamInstTyCon tc = case tyConParent tc of FamInstTyCon {} -> True _ -> False tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched) tyConFamInstSig_maybe tc = case tyConParent tc of FamInstTyCon ax f ts -> Just (f, ts, ax) _ -> Nothing -- | If this 'TyCon' is that of a family instance, return the family in question -- and the instance types. Otherwise, return @Nothing@ tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type]) tyConFamInst_maybe tc = case tyConParent tc of FamInstTyCon _ f ts -> Just (f, ts) _ -> Nothing -- | If this 'TyCon' is that of a family instance, return a 'TyCon' which -- represents a coercion identifying the representation type with the type -- instance family. Otherwise, return @Nothing@ tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched) tyConFamilyCoercion_maybe tc = case tyConParent tc of FamInstTyCon co _ _ -> Just co _ -> Nothing {- ************************************************************************ * * \subsection[TyCon-instances]{Instance declarations for @TyCon@} * * ************************************************************************ @TyCon@s are compared by comparing their @Unique@s. The strictness analyser needs @Ord@. It is a lexicographic order with the property @(a<=b) || (b<=a)@. -} instance Eq TyCon where a == b = case (a `compare` b) of { EQ -> True; _ -> False } a /= b = case (a `compare` b) of { EQ -> False; _ -> True } instance Ord TyCon where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } compare a b = getUnique a `compare` getUnique b instance Uniquable TyCon where getUnique tc = tyConUnique tc instance Outputable TyCon where -- At the moment a promoted TyCon has the same Name as its -- corresponding TyCon, so we add the quote to distinguish it here ppr tc = pprPromotionQuote tc <> ppr (tyConName tc) pprPromotionQuote :: TyCon -> SDoc pprPromotionQuote (PromotedDataCon {}) = char '\'' -- Quote promoted DataCons -- in types pprPromotionQuote (PromotedTyCon {}) = ifPprDebug (char '\'') pprPromotionQuote _ = empty -- However, we don't quote TyCons -- in kinds e.g. -- type family T a :: Bool -> * -- cf Trac #5952. -- Except with -dppr-debug instance NamedThing TyCon where getName = tyConName instance Data.Data TyCon where -- don't traverse? toConstr _ = abstractConstr "TyCon" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "TyCon" {- ************************************************************************ * * Walking over recursive TyCons * * ************************************************************************ Note [Expanding newtypes and products] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When expanding a type to expose a data-type constructor, we need to be careful about newtypes, lest we fall into an infinite loop. Here are the key examples: newtype Id x = MkId x newtype Fix f = MkFix (f (Fix f)) newtype T = MkT (T -> T) Type Expansion -------------------------- T T -> T Fix Maybe Maybe (Fix Maybe) Id (Id Int) Int Fix Id NO NO NO Notice that we can expand T, even though it's recursive. And we can expand Id (Id Int), even though the Id shows up twice at the outer level. So, when expanding, we keep track of when we've seen a recursive newtype at outermost level; and bale out if we see it again. We sometimes want to do the same for product types, so that the strictness analyser doesn't unbox infinitely deeply. The function that manages this is checkRecTc. -} newtype RecTcChecker = RC NameSet initRecTc :: RecTcChecker initRecTc = RC emptyNameSet checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker -- Nothing => Recursion detected -- Just rec_tcs => Keep going checkRecTc (RC rec_nts) tc | not (isRecursiveTyCon tc) = Just (RC rec_nts) | tc_name `elemNameSet` rec_nts = Nothing | otherwise = Just (RC (extendNameSet rec_nts tc_name)) where tc_name = tyConName tc
forked-upstream-packages-for-ghcjs/ghc
compiler/types/TyCon.hs
bsd-3-clause
71,906
0
16
21,635
8,170
4,707
3,463
712
8
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Plugins.Date -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <[email protected]> -- Stability : unstable -- Portability : unportable -- -- A date plugin for Xmobar -- -- Usage example: in template put -- -- > Run Date "%a %b %_d %Y <fc=#ee9a00> %H:%M:%S</fc>" "Mydate" 10 -- ----------------------------------------------------------------------------- module Plugins.Date (Date(..)) where import Plugins #if ! MIN_VERSION_time(1,5,0) import System.Locale #endif import Control.Monad (liftM) import Data.Time data Date = Date String String Int deriving (Read, Show) instance Exec Date where alias (Date _ a _) = a run (Date f _ _) = date f rate (Date _ _ r) = r date :: String -> IO String date format = liftM (formatTime defaultTimeLocale format) getZonedTime
dsalisbury/xmobar
src/Plugins/Date.hs
bsd-3-clause
978
0
8
181
180
105
75
14
1
module B1 (myFringe)where import D1 hiding (sumSquares) import D1 () import C1 hiding (myFringe) myFringe:: Tree a -> [a] myFringe (Leaf x ) = [x] myFringe (Branch left right) = myFringe right sumSquares (x:xs)= x^2 + sumSquares xs sumSquares [] =0
kmate/HaRe
old/testing/moveDefBtwMods/B1_TokOut.hs
bsd-3-clause
259
0
7
51
120
66
54
9
1
----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.Parsec.Expr -- Copyright : (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec.Expr ( Assoc (AssocNone,AssocLeft,AssocRight), Operator(..), OperatorTable, buildExpressionParser ) where import Text.Parsec.Expr(Assoc(..)) import qualified Text.Parsec.Expr as N import Text.ParserCombinators.Parsec(GenParser) import Control.Monad.Identity data Operator tok st a = Infix (GenParser tok st (a -> a -> a)) Assoc | Prefix (GenParser tok st (a -> a)) | Postfix (GenParser tok st (a -> a)) type OperatorTable tok st a = [[Operator tok st a]] convert :: Operator tok st a -> N.Operator [tok] st Identity a convert (Infix p a) = N.Infix p a convert (Prefix p) = N.Prefix p convert (Postfix p) = N.Postfix p buildExpressionParser :: OperatorTable tok st a -> GenParser tok st a -> GenParser tok st a buildExpressionParser = N.buildExpressionParser . map (map convert)
maurer/15-411-Haskell-Base-Code
src/Text/ParserCombinators/Parsec/Expr.hs
bsd-3-clause
1,396
0
11
315
334
194
140
23
1
{-# LANGUAGE Safe #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Marshal.Safe -- Copyright : (c) The FFI task force 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Marshalling support -- -- Safe API Only. -- ----------------------------------------------------------------------------- module Foreign.Marshal.Safe ( -- | The module "Foreign.Marshal.Safe" re-exports the other modules in the -- @Foreign.Marshal@ hierarchy: module Foreign.Marshal.Alloc , module Foreign.Marshal.Array , module Foreign.Marshal.Error , module Foreign.Marshal.Pool , module Foreign.Marshal.Utils ) where import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Marshal.Error import Foreign.Marshal.Pool import Foreign.Marshal.Utils
frantisekfarka/ghc-dsi
libraries/base/Foreign/Marshal/Safe.hs
bsd-3-clause
1,035
0
5
200
93
70
23
14
0
-- | Test file for issue #10320. module Main (main) where main :: IO () main = print $ map (+1) (map (+1) [1, 2, 3]) {-# RULES "map/map" forall f g xs. map f (map g xs) = map (f.g) xs #-}
olsner/ghc
testsuite/tests/driver/T10320.hs
bsd-3-clause
195
0
9
50
60
36
24
4
1
{-# LANGUAGE RankNTypes, FlexibleInstances #-} -- !!! Check that forall types can't be arguments module ShouldFail where data T s a = MkT s a instance Ord a => Ord (forall s. T s a) -- A for-all should not appear as an argument to Ord g :: T s (forall b.b) g = error "urk"
siddhanathan/ghc
testsuite/tests/typecheck/should_fail/tcfail088.hs
bsd-3-clause
282
0
8
65
73
41
32
6
1
----------------------------------------------------------------------------- -- -- Module : Graphics.GPipe.Expr -- Copyright : Tobias Bexelius -- License : MIT -- -- Maintainer : Tobias Bexelius -- Stability : Experimental -- Portability : Portable -- -- | -- This module provides the DSL for shader operations in GPipe. The type @'S' x a@ is an opaque type that represents a value of type @a@ in a shader stage @x@, eg @S F Float@ means a -- floating point value in a fragment stream. -- ----------------------------------------------------------------------------- module Graphics.GPipe.Expr ( -- * Atomic shader type S(), V, F, VFloat, VInt, VWord, VBool, FFloat, FInt, FWord, FBool, -- * Type classes where the Prelude ones are lacking Convert(..), Integral'(..), Real'(..), FloatingOrd(..), -- * Additional functions dFdx, dFdy, fwidth, -- * Shader control structures while, ifThen, ifThenElse, ifThenElse', ShaderBase(), ShaderType(..) ) where import Data.Boolean import Graphics.GPipe.Internal.Expr
Teaspot-Studio/GPipe-Core
src/Graphics/GPipe/Expr.hs
mit
1,129
0
5
259
138
100
38
24
0
module CFDI.Types.PaymentRelatedDocument where import CFDI.Chainable import CFDI.Types.Amount import CFDI.Types.Currency import CFDI.Types.Folio import CFDI.Types.ExchangeRate import CFDI.Types.Partiality import CFDI.Types.PaymentMethod import CFDI.Types.RelatedDocumentId import CFDI.Types.Series import CFDI.XmlNode import Data.Maybe (catMaybes) data PaymentRelatedDocument = PaymentRelatedDocument { prdCurrency :: Currency , prdExRate :: Maybe ExchangeRate , prdId :: RelatedDocumentId , prdFolio :: Maybe Folio , prdPaid :: Maybe Amount , prdPart :: Maybe Partiality , prdPayMet :: PaymentMethod , prdPrevBal :: Maybe Amount , prdRemain :: Maybe Amount , prdSeries :: Maybe Series } deriving (Eq, Show) instance Chainable PaymentRelatedDocument where chain c = prdId <@> prdSeries <~> prdFolio <~> prdCurrency <~> prdExRate <~> prdPayMet <~> prdPart <~> prdPrevBal <~> prdPaid <~> prdRemain <~> (c, "") instance XmlNode PaymentRelatedDocument where attributes n = [ attr "MonedaDR" $ prdCurrency n , attr "IdDocumento" $ prdId n , attr "MetodoDePagoDR" $ prdPayMet n ] ++ catMaybes [ attr "Folio" <$> prdFolio n , attr "Serie" <$> prdSeries n , attr "TipoCambioDR" <$> prdExRate n , attr "NumParcialidad" <$> prdPart n , attr "ImpSaldoAnt" <$> prdPrevBal n , attr "ImpPagado" <$> prdPaid n , attr "ImpSaldoInsoluto" <$> prdRemain n ] nodeName = const "DoctoRelacionado" nodePrefix = const "pago10" parseNode n = PaymentRelatedDocument <$> requireAttribute "MonedaDR" n <*> parseAttribute "TipoCambioDR" n <*> requireAttribute "IdDocumento" n <*> parseAttribute "Folio" n <*> parseAttribute "ImpPagado" n <*> parseAttribute "NumParcialidad" n <*> requireAttribute "MetodoDePagoDR" n <*> parseAttribute "ImpSaldoAnt" n <*> parseAttribute "ImpSaldoInsoluto" n <*> parseAttribute "Serie" n
yusent/cfdis
src/CFDI/Types/PaymentRelatedDocument.hs
mit
2,042
0
16
484
505
262
243
62
0
-- | For documentation, see the paper "SmallCheck and Lazy SmallCheck: -- automatic exhaustive testing for small values" available at -- <http://www.cs.york.ac.uk/fp/smallcheck/>. Several examples are -- also included in the package. module LazySmallCheck ( Serial(series) -- :: class , Series -- :: type Series a = Int -> Cons a , Cons -- :: * , cons -- :: a -> Series a , (><) -- :: Series (a -> b) -> Series a -> Series b , empty -- :: Series a , (\/) -- :: Series a -> Series a -> Series a , drawnFrom -- :: [a] -> Cons a , cons0 -- :: a -> Series a , cons1 -- :: Serial a => (a -> b) -> Series b , cons2 -- :: (Serial a, Serial b) => (a -> b -> c) -> Series c , cons3 -- :: ... , cons4 -- :: ... , cons5 -- :: ... , Testable -- :: class , depthCheck -- :: Testable a => Int -> a -> IO () , smallCheck -- :: Testable a => Int -> a -> IO () , test -- :: Testable a => a -> IO () , (==>) -- :: Bool -> Bool -> Bool , Property -- :: * , lift -- :: Bool -> Property , neg -- :: Property -> Property , (*&*) -- :: Property -> Property -> Property , (*|*) -- :: Property -> Property -> Property , (*=>*) -- :: Property -> Property -> Property , (*=*) -- :: Property -> Property -> Property , depthCheckResult , decValidCounter ) where import Control.Applicative ((<$>)) import Control.Monad import Control.Exception import Data.IORef import System.Exit import System.IO.Unsafe infixr 0 ==>, *=>* infixr 3 \/, *|* infixl 4 ><, *&* type Pos = [Int] data Term = Var Pos Type | Ctr Int [Term] data Type = SumOfProd [[Type]] type Series a = Int -> Cons a data Cons a = C Type ([[Term] -> a]) class Serial a where series :: Series a -- Series constructors cons :: a -> Series a cons a d = C (SumOfProd [[]]) [const a] empty :: Series a empty d = C (SumOfProd []) [] (><) :: Series (a -> b) -> Series a -> Series b (f >< a) d = C (SumOfProd [ta:p | shallow, p <- ps]) cs where C (SumOfProd ps) cfs = f d C ta cas = a (d-1) cs = [\(x:xs) -> cf xs (conv cas x) | shallow, cf <- cfs] shallow = d > 0 && nonEmpty ta nonEmpty :: Type -> Bool nonEmpty (SumOfProd ps) = not (null ps) (\/) :: Series a -> Series a -> Series a (a \/ b) d = C (SumOfProd (ssa ++ ssb)) (ca ++ cb) where C (SumOfProd ssa) ca = a d C (SumOfProd ssb) cb = b d conv :: [[Term] -> a] -> Term -> a conv cs (Var p _) = error ('\0':map toEnum p) conv cs (Ctr i xs) = (cs !! i) xs drawnFrom :: [a] -> Cons a drawnFrom xs = C (SumOfProd (map (const []) xs)) (map const xs) -- Helpers, a la SmallCheck cons0 :: a -> Series a cons0 f = cons f cons1 :: Serial a => (a -> b) -> Series b cons1 f = cons f >< series cons2 :: (Serial a, Serial b) => (a -> b -> c) -> Series c cons2 f = cons f >< series >< series cons3 :: (Serial a, Serial b, Serial c) => (a -> b -> c -> d) -> Series d cons3 f = cons f >< series >< series >< series cons4 :: (Serial a, Serial b, Serial c, Serial d) => (a -> b -> c -> d -> e) -> Series e cons4 f = cons f >< series >< series >< series >< series cons5 :: (Serial a, Serial b, Serial c, Serial d, Serial e) => (a -> b -> c -> d -> e -> f) -> Series f cons5 f = cons f >< series >< series >< series >< series >< series -- Standard instances instance Serial () where series = cons0 () instance Serial Bool where series = cons0 False \/ cons0 True instance Serial a => Serial (Maybe a) where series = cons0 Nothing \/ cons1 Just instance (Serial a, Serial b) => Serial (Either a b) where series = cons1 Left \/ cons1 Right instance Serial a => Serial [a] where series = cons0 [] \/ cons2 (:) instance (Serial a, Serial b) => Serial (a, b) where series = cons2 (,) . (+1) instance (Serial a, Serial b, Serial c) => Serial (a, b, c) where series = cons3 (,,) . (+1) instance (Serial a, Serial b, Serial c, Serial d) => Serial (a, b, c, d) where series = cons4 (,,,) . (+1) instance (Serial a, Serial b, Serial c, Serial d, Serial e) => Serial (a, b, c, d, e) where series = cons5 (,,,,) . (+1) instance Serial Int where series d = drawnFrom [-d..d] instance Serial Integer where series d = drawnFrom (map toInteger [-d..d]) instance Serial Char where series d = drawnFrom (take (d+1) ['a'..]) instance Serial Float where series d = drawnFrom (floats d) instance Serial Double where series d = drawnFrom (floats d) floats :: RealFloat a => Int -> [a] floats d = [ encodeFloat sig exp | sig <- map toInteger [-d..d] , exp <- [-d..d] , odd sig || sig == 0 && exp == 0 ] -- Term refinement refine :: Term -> Pos -> [Term] refine (Var p (SumOfProd ss)) [] = new p ss refine (Ctr c xs) p = map (Ctr c) (refineList xs p) refineList :: [Term] -> Pos -> [[Term]] refineList xs (i:is) = [ls ++ y:rs | y <- refine x is] where (ls, x:rs) = splitAt i xs new :: Pos -> [[Type]] -> [Term] new p ps = [ Ctr c (zipWith (\i t -> Var (p++[i]) t) [0..] ts) | (c, ts) <- zip [0..] ps ] -- Find total instantiations of a partial value total :: Term -> [Term] total val = tot val where tot (Ctr c xs) = [Ctr c ys | ys <- mapM tot xs] tot (Var p (SumOfProd ss)) = [y | x <- new p ss, y <- tot x] -- Answers answer :: a -> (a -> IO b) -> (Pos -> IO b) -> IO b answer a known unknown = do res <- try (evaluate a) case res of Right b -> known b Left (ErrorCall ('\0':p)) -> unknown (map fromEnum p) Left e -> throw e -- Refute refute :: Result -> IO Int refute r = ref (args r) where ref xs = eval (apply r xs) known unknown where known True = return 1 known False = report unknown p = sumMapM ref 1 (refineList xs p) report = do putStrLn "Counter example found:" mapM_ putStrLn $ zipWith ($) (showArgs r) $ head [ys | ys <- mapM total xs] exitWith ExitSuccess sumMapM :: (a -> IO Int) -> Int -> [a] -> IO Int sumMapM f n [] = return n sumMapM f n (a:as) = seq n (do m <- f a ; sumMapM f (n+m) as) -- Properties with parallel conjunction (Lindblad TFP'07) data Property = Bool Bool | Neg Property | And Property Property | ParAnd Property Property | Eq Property Property eval :: Property -> (Bool -> IO a) -> (Pos -> IO a) -> IO a eval p k u = answer p (\p -> eval' p k u) u eval' (Bool b) k u = answer b k u eval' (Neg p) k u = eval p (k . not) u eval' (And p q) k u = eval p (\b-> if b then eval q k u else k b) u eval' (Eq p q) k u = eval p (\b-> if b then eval q k u else eval (Neg q) k u) u eval' (ParAnd p q) k u = eval p (\b-> if b then eval q k u else k b) unknown where unknown pos = eval q (\b-> if b then u pos else k b) (\_-> u pos) lift :: Bool -> Property lift b = Bool b neg :: Property -> Property neg p = Neg p (*&*), (*|*), (*=>*), (*=*) :: Property -> Property -> Property p *&* q = ParAnd p q p *|* q = neg (neg p *&* neg q) p *=>* q = neg (p *&* neg q) p *=* q = Eq p q -- Boolean implication validCounter :: IORef Int validCounter = unsafePerformIO $ newIORef 0 {-# NOINLINE validCounter #-} decValidCounter = do n <- readIORef validCounter modifyIORef' validCounter (\n -> n - 1) when (n == 1) $ throw () {-# NOINLINE decValidCounter #-} (==>) :: Bool -> Bool -> Bool False ==> _ = True True ==> x = x -- Testable data Result = Result { args :: [Term] , showArgs :: [Term -> String] , apply :: [Term] -> Property } data P = P (Int -> Int -> Result) run :: Testable a => ([Term] -> a) -> Int -> Int -> Result run a = f where P f = property a class Testable a where property :: ([Term] -> a) -> P instance Testable Bool where property apply = P $ \n d -> Result [] [] (Bool . apply . reverse) instance Testable Property where property apply = P $ \n d -> Result [] [] (apply . reverse) instance (Show a, Serial a, Testable b) => Testable (a -> b) where property f = P $ \n d -> let C t c = series d c' = conv c r = run (\(x:xs) -> f xs (c' x)) (n+1) d in r { args = Var [n] t : args r, showArgs = (show . c') : showArgs r } -- Top-level interface depthCheck :: Testable a => Int -> a -> IO () depthCheck d p = do n <- refute $ run (const p) 0 d putStrLn $ "OK, required " ++ show n ++ " tests at depth " ++ show d smallCheck :: Testable a => Int -> a -> IO () smallCheck d p = mapM_ (`depthCheck` p) [0..d] -- refute returns the number of tests generated, not the number of *valid* -- tests generated, so we count the number of valid tests ourselves depthCheckResult :: Testable a => Int -> Int -> a -> IO Int depthCheckResult d n p = do writeIORef validCounter n refute (run (const p) 0 d) `catch` \() -> return n (n-) <$> readIORef validCounter instance Exception () test :: Testable a => a -> IO () test p = mapM_ (`depthCheck` p) [0..]
gridaphobe/target
bench/LazySmallCheck.hs
mit
9,043
0
17
2,558
4,010
2,097
1,913
218
5
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wall #-} module TreeGenerator ( searchAndGetTree ) where import BasicPrelude hiding (Word, liftIO, lift) import Data.Text.Encoding (decodeUtf8') import Data.Text (unpack, split) import qualified Data.ByteString.Char8 as BC import qualified Data.Map as M import Control.Lens hiding (children) import Control.Monad.IO.Class import Control.Monad.Random hiding (split) import Control.Monad.Trans.Class import Control.Monad.Trans.State import Control.Monad.Trans.Writer import Filesystem.Path.CurrentOS import qualified GHC.IO as GI import Types import Helpers import Parser import RandomName import Corner import RunCommand import Cache -- $setup -- >>> import Data.Text (pack) type TreeGenerator a = WriterT [Text] CachedIO a searchAndGetTree :: FilePath -> Int -> Int -> Pattern -> IO (Text, [Text]) searchAndGetTree wdir depth sourcelines pattern = do (trees, err_files) <- runTreeGenerator $ wordToTree wdir depth sourcelines pattern Nothing output_trees <- convertToOutputTree trees let jsn = jsonToText $ AllTree { nameA = "main", primary_wordA = Just pattern, cornersA = pattern, childrenA = output_trees, err_filesA = err_files } return (jsn, err_files) ---------------------------------------------------------------------------- runTreeGenerator :: TreeGenerator [Tree] -> IO ([Tree], [Text]) runTreeGenerator x = fst <$> (runStateT (runWriterT x) (M.fromList [])) wordToTree :: FilePath -> Int -> Int -> Pattern -> Maybe Pattern -> TreeGenerator [Tree] wordToTree _ 0 _ _ _ = return [] wordToTree wdir depth sourcelines pattern fname_pattern = do (results, errs) <- lift $ grepCommand 300 wdir pattern tell errs let results' = filter (\(path, _, _) -> hitPattern fname_pattern path) $ catMaybes $ map parseGrepResult results catMaybes <$> (forM results' (\(path, ln, _) -> do let abs_path = wdir </> path cnt <- readFileThroughCache abs_path let (objective, objecive_lnum, all_corners) = getPrimaryWord cnt (ln - 1) abs_path let text_range = sourcelines `div` 2 let source = slice (ln - text_range) (ln + text_range) $ zip [1..] cnt let current_line = cnt !! ln let is_filter_def_ = isFilterDefinition current_line let common_tree = defaultTree pattern path ln all_corners source case objective of NoObjective -> return $ Just common_tree WordObjective next_word -> (do is_action_ <- isAction wdir path next_word ts <- if (not is_action_ && not is_filter_def_) then wordToTree wdir (depth - 1) sourcelines next_word Nothing else return [] let ts_without_me = case objecive_lnum of Nothing -> ts Just lnum_ -> filter (not . is_myself path (lnum_ + 1)) ts return $ Just ( common_tree&primary_word.~(Just next_word)&is_action.~is_action_&is_filter_def.~is_filter_def_&children.~ts_without_me) ) RegexpObjective fname_pattern' next_pattern -> (do ts <- wordToTree wdir (depth - 1) sourcelines next_pattern fname_pattern' return $ Just ( common_tree&primary_word.~(Just next_pattern)&children.~ts )))) hitPattern :: Maybe Pattern -> FilePath -> Bool hitPattern Nothing _ = True hitPattern (Just pat) path = ((unpack $ "/" ++ pat ++ "_") `isInfixOf` path') || ((unpack $ "/" ++ pat ++ "/") `isInfixOf` path') where path' = encodeString path is_myself :: FilePath -> Int -> Tree -> Bool is_myself path ln tree = (path == _fname tree) && (ln == _lnum tree) convertToOutputTree :: [Tree] -> IO [OutputTree] convertToOutputTree trees = evalRandIO $ mapM toOutputTree trees toOutputTree :: (RandomGen g) => Tree -> Rand g OutputTree toOutputTree (Tree {..}) = do random_name <- randomName children' <- mapM toOutputTree _children return $ OutputTree { name = random_name, primary_wordO = _primary_word, search_wordO = _search_word, fnameO = toText' _fname, rails_directory = fnameToRailsDirectory _fname, lnumO = _lnum, is_actionO = _is_action, is_filter_defO = _is_filter_def, cornersO = corner_str, around_textO = _around_text, childrenO = children' } where corner_str = showCorners _corners -- | -- >>> parseGrepResult (pack "foo/bar.hs:123: foo bar") -- Just (FilePath "foo/bar.hs",123," foo bar") -- -- >>> parseGrepResult (pack "Binary file public/images/foo.jpg matches") -- Nothing parseGrepResult :: Text -> Maybe (FilePath, Int, Text) parseGrepResult line | length ss < 2 = if ("Binary file" `isPrefixOf` (unpack line)) then Nothing else error ("fail to parse the result of grep: " ++ unpack line) | otherwise = Just (fn, num, matched_string) where ss = split (== ':') $ line fn = fromText $ ss !! 0 num = read $ ss !! 1 matched_string = ss !! 2 -- | -- -- >>> getPrimaryWord (map pack ["<div>", " <%= foo %>", "</div>"]) 1 (fromText $ pack "/foo/bar.html.erb") -- (RegexpObjective (Just "foo") "render.*bar",Nothing,[]) -- -- >>> getPrimaryWord (map pack ["def foo", " print 123", "end"]) 1 (fromText $ pack "/foo/bar.rb") -- (WordObjective "foo",Just 0,[Corner (RbMethod (Just "foo")) "def foo",Corner CurrentLine " print 123",Corner RbEnd "end"]) -- -- >>> getPrimaryWord (map pack ["foo: function(e){", " console.log(e)", "}"]) 1 (fromText $ pack "/foo/bar.js") -- (WordObjective "foo",Just 0,[Corner (JsFunc (Just "foo")) "foo: function(e){",Corner CurrentLine " console.log(e)",Corner JsEnd "}"]) -- getPrimaryWord :: [Line] -> Int -> FilePath -> (Objective, Maybe Int, [Corner]) getPrimaryWord ls dpt path = case (extension path) of Nothing -> (NoObjective, Nothing, []) Just x | (x == "erb") || (x == "rhtml") -> (RegexpObjective fname_pattern $ "render.*" `mappend` basename_val, Nothing, []) | (x == "js") -> case primary_corner of Just x' -> (wordToObj $ getWord x', primary_lnum, all_corners) Nothing -> (NoObjective, primary_lnum, all_corners) | (x == "rb") || (x == "rake") -> case primary_corner of Just (Corner (RbClass _) _) -> (NoObjective, primary_lnum, all_corners) Just (Corner (RbModule _) _) -> (NoObjective, primary_lnum, all_corners) Nothing -> (NoObjective, primary_lnum, all_corners) Just x' -> (wordToObj $ getWord x', primary_lnum, all_corners) | otherwise -> (NoObjective, Nothing, []) where (primary_corner, primary_lnum, all_corners) = getCorners ls dpt basename_val = dropFirstUnderScore $ toText' $ basename path fname_pattern = Just $ toText' $ dirname path isAction :: FilePath -> FilePath -> Word -> TreeGenerator Bool isAction wdir path w = do cnt <- readFileThroughCache (wdir </> "rake_routes") let routes = parseRakeRouteLine cnt return $ (flip any) routes (\route -> ((((controllerName route) :: Text) `mappend` "_controller") == (toText' $ basename path)) && (((actionName route) :: Text) == w)) readFileThroughCache :: FilePath -> TreeGenerator [Text] readFileThroughCache path = do ls <- lift $ readCache (FileCache path) case ls of Just inner -> return inner Nothing -> do case (toText path) of Right path' -> do cnt_or_error <- decodeUtf8' <$> (liftIO $ BC.readFile (unpack path' :: GI.FilePath)) case cnt_or_error of Right cnt -> do let new_ls = lines cnt lift $ writeCache (FileCache path) new_ls return new_ls Left _ -> do tell [path'] return [] Left path' -> do tell [path'] return [] wordToObj :: Maybe Word -> Objective wordToObj Nothing = NoObjective wordToObj (Just w) = WordObjective w defaultTree :: Word -> FilePath -> Int -> [Corner] -> [(Int, Text)] -> Tree defaultTree pattern path ln all_corners source = Tree { _primary_word = Nothing, _search_word = pattern, _fname = path, _lnum = ln, _corners = all_corners, _around_text = source, _is_action = False, _is_filter_def = False, _children = [] } ---------------------------------------------------------------------------- -- | Command grepCommand :: Int -> FilePath -> Word -> CachedIO ([Text], [ErrMsg]) grepCommand limit wdir w = do result <- executeWithCache "git" ["grep", "-n", "-w", w] (Just wdir) case result of Left err -> return ([], [err]) Right result' -> do let limit_err = if (limit < length result') then ["git grep result of " `mappend` w `mappend` " is more than " `mappend` (show limit) `mappend` ": " `mappend` (show $ length result') ] else [] return (take limit result', limit_err)
mathfur/grep-tree
src/TreeGenerator.hs
mit
9,908
0
31
2,990
2,644
1,408
1,236
175
6
module Dffptch (diff, patch) where import Data.Maybe import Data.Aeson import qualified Data.ByteString.Lazy as B import qualified Data.Text.Lazy as L import qualified Data.HashMap.Strict as H import Dffptch.Internal main :: IO () main = do rawJSON <- B.readFile "./test.json" B.putStr rawJSON case decode rawJSON :: Maybe Value of Just jsonVal -> B.putStr $ encode (jsonVal) Nothing -> error "Parse err"
paldepind/dffptch-haskell
Dffptch.hs
mit
422
0
12
75
135
75
60
14
2
-- ex 10.3 import DataBuilder import Json -- data Product = Product { id :: Int, name :: String, price :: Double, descr :: String } deriving (Show, Ord, Eq) -- data Purchase = Purchase { client :: Client Int, products :: [Product] } deriving (Show, Ord, Eq) import Data.Conduit import qualified Data.Conduit.Binary as B -- import qualified Data.Conduit.Attoparsec as A -- import qualified Data.Conduit.Text as CT import qualified Data.Conduit.List as L import qualified Data.ByteString as LB import qualified Data.ByteString.Lazy as LLB import Control.Monad.Trans.Resource(runResourceT) import Data.Aeson -- import Data.Text savePurchases :: FilePath -> [Purchase] -> IO () savePurchases fPath purchases = runResourceT $ yield (toJSON purchases) $$ L.map (LLB.toStrict . encode) =$ B.sinkFile fPath purchases :: [Purchase] purchases = [ Purchase (GovOrg 1 "MoE") [ Product 11 "Soap" 1234.2 "Bubbly...", Product 22 "TV" 29394.2 "SONY" ], Purchase (Individual 2 (Person "John" "Huges")) [ Product 33 "Tester" 1.23 "Awe", Product 44 "Car" 2993.4 "Kia" ] ] displayP :: Monad m => Conduit LB.ByteString m [Purchase] displayP = do t <- await case t of Nothing -> return () Just c -> do let x = decodeStrict c :: (Maybe [Purchase]) case x of Nothing -> return () Just y -> do yield y displayP -- FIXME TODO -- List of list is pretty ugly showPurchases :: IO [[Purchase]] showPurchases = runResourceT $ B.sourceFile "test.db" $$ B.lines =$ displayP =$ L.consume main :: IO () -- main = savePurchases "test.db" purchases >> showPurchases main = do savePurchases "test.db" purchases ps <- showPurchases let pps = Prelude.concat ps print pps
hnfmr/beginning_haskell
chapter10/Main.hs
mit
1,729
0
17
355
462
243
219
36
3
module ProjectEuler.Problem43 ( problem ) where import Control.Monad import qualified Data.List.Match as LMatch import ProjectEuler.Types {- we could try every permutation, which is straightforward to do, but the search space is huge. so instead, we can do a search begin with a smaller branching factor - pick d10, d9, d8 first with 3 distinct numbers, verify they are divisible by 17, then choose d7, check with 13, then choose d6, check with 11, etc. this approach trims the branch very early: as soon as the current divisible property cannot be satisfied, there is no need of going any further, therefore search space is reduced to a small set of values very quickly. -} problem :: Problem problem = pureProblem 43 Solved result pickOne :: [a] -> [(a, [a])] pickOne xs = LMatch.take xs $ (\(a,b:c) -> (b,a<>c)) . (`splitAt` xs) <$> [0..] toNum :: [Int] -> Int toNum = foldl (\acc i -> acc*10 + i) 0 solution :: [[Int]] solution = do (d10, xs) <- pickOne [0..9] (d9, ys) <- pickOne xs solve' [d9,d10] ys initPrimeList where initPrimeList = [17,13,11,7,5,3,2] solve' chosenList remained primeList | null primeList = pure (remained <> chosenList) | otherwise = do -- choose x, -- and look into current chosen list of digits to get y and z (x,remained') <- pickOne remained let (y:z:_) = chosenList chosenList' = x : chosenList (p:primeList') = primeList n = x * 100 + y * 10 + z guard $ n `rem` p == 0 solve' chosenList' remained' primeList' result :: Int result = sum $ toNum <$> solution
Javran/Project-Euler
src/ProjectEuler/Problem43.hs
mit
1,661
0
16
432
438
242
196
29
1
module Main (main) where import qualified Graphics.UI.GLFW as GLFW main :: IO () main = do succeeded <- GLFW.initialize if succeeded then do putStrLn "Hm." return () else return ()
IreneKnapp/tactical-hydrangea
Haskell/Hydrangea.hs
mit
208
0
11
57
72
38
34
10
2
fibonacci n | n == 0 = 0 | n == 1 = 1 | n == 2 = 1 | otherwise = fibonacci (n - 1) + fibonacci (n - 2) main = do print $ fibonacci 0 print $ fibonacci 1 print $ fibonacci 2 print $ fibonacci 3 print $ fibonacci 4 print $ fibonacci 5 print $ fibonacci 6 print $ fibonacci 7 print $ fibonacci 8
shigemk2/haskell_abc
fibonacci-guard.hs
mit
370
0
9
148
173
75
98
15
1
{-# LANGUAGE TemplateHaskell #-} module Player where import Base.GraphicsManager import Base.InputHandler import Base.Geometry import qualified Base.Camera as C import qualified Platform as P import Graphics.UI.SDL (SDLKey(..), Surface) import Control.Monad.State import Control.Lens data Player = Player { _bounding :: Shape, _velocity :: (Int,Int), _alive :: Bool, _image :: IO Surface } $( makeLenses ''Player ) playerHeight = 20 playerWidth = 20 initialize :: (Int,Int) -> Player initialize (x,y) = Player (Rectangle x y playerWidth playerHeight) (0,2) True (loadImage "dot.bmp" Nothing) update :: KeyboardState -> [Shape] -> [P.Platform] -> Player -> Player update kS rects mp p = snd $ runState (updateS kS rects mp) p updateS :: KeyboardState -> [Shape] -> [P.Platform] -> State Player () updateS kS rects mp = do x <- use $ bounding.x y <- use $ bounding.y velocity._1 %= (\dx -> if strafe == 0 then ((if dx > 0 then floor else ceiling) $ ((fromIntegral dx)*0.9)) else (if dx*strafe > 0 then max (min (dx+strafe) 5) (-5) else strafe)) modify moveV curP <- get let (nP,oG) = (moveObjs mp) . (checkCollisionV rects y) $ curP put $ (checkCollisionH rects x) . moveH $ nP if oG && (isPressed kS SDLK_UP) then velocity._2 %= (\dy -> (min 0 dy) - 10 ) else return () where strafe = (if isDown kS SDLK_LEFT then -1 else 0) + (if isDown kS SDLK_RIGHT then 1 else 0) draw :: Surface -> C.FixedCamera -> Player -> IO () draw screen cam (Player (Rectangle x y _ _) _ _ image) = do img <- image let pt = C.shapeToScreen cam (Point x y) 640 480 case pt of Just (Point x' y') -> do drawImage screen img (x' , y') Nothing -> return True return () moveH :: Player -> Player moveH p = bounding.x +~ p^.velocity._1 $ p moveV :: Player -> Player moveV p = (bounding.y +~ p^.velocity._2) . (velocity._2 +~ 2) $ p checkCollisionH :: [Shape] -> Int -> Player -> Player checkCollisionH [] _ p = p checkCollisionH (r:rs) origX p@(Player _ (dx,dy) a i) | r `collides` (x .~ origX $ p^.bounding) = if r^.x - origX > 0 then if (p^.bounding.x + p^.velocity._1) < (r^.x - p^.bounding.width - 1) then ((bounding.x .~ (r^.x - p^.bounding.width - 1)) $ p) else p else if (p^.bounding.x + p^.velocity._1) > (r^.x - p^.bounding.width - 1) then ((bounding.x .~ (r^.x + r^.width + 1)) $ p) else p | p^.velocity._1 == 0 = p | p^.velocity._1 > 0 = if r `collides` ((x .~ origX) . (width .~ (p^.bounding.x - origX + p^.bounding.width)) $ p^.bounding) then bounding.x .~ (r^.x - p^.bounding.width - 1) $ p else checkCollisionH rs origX p | otherwise = if r `collides` (width .~ (origX - p^.bounding.x) $ p^.bounding) then (bounding.x .~ r^.x + r^.width + 1) $ p else checkCollisionH rs origX p checkCollisionV :: [Shape] -> Int -> Player -> (Player,Bool) checkCollisionV [] _ p = (p,False) checkCollisionV (r:rs) origY p@(Player _ (dx,dy) a i) | r `collides` (y .~ origY $ p^.bounding) = if r^.y - origY < 0 then if (p^.bounding.y+p^.velocity._2) < (r^.y)+(r^.height)+1 then ((bounding.y .~ (r^.y + r^.height + 1)) . (velocity._2 .~ 2) $ p, False) else (p,False) else if (p^.bounding.y+p^.velocity._2) > (r^.y)-(r^.height)-1 then ((bounding.y .~ (r^.y - p^.bounding.height - 1)) . (velocity._2 .~ 2) $ p, True) else (p,False) | p^.velocity._2 == 0 = (p, False) | p^.velocity._2 > 0 = if r `collides` ((y .~ origY) . (height .~ ((p^.bounding.y) - origY + (p^.bounding.height))) $ p^.bounding) then ((bounding.y .~ r^.y - p^.bounding.height - 1) . (velocity._2 .~ 2) $ p, True) else checkCollisionV rs origY p | otherwise = if r `collides` (height .~ (origY - (p^.bounding.y)) $ p^.bounding) then ((bounding.y .~ r^.y + r^.height + 1) . (velocity._2 .~ 2) $ p, False) else checkCollisionV rs origY p moveObjs :: [P.Platform] -> (Player,Bool) -> (Player,Bool) moveObjs ((P.MoveablePlatform _ _ r (dx',dy') _ fwd):rs) (p, b) | r `collides` (y +~ 3 $ p^.bounding) = ((bounding.x +~ dx) . (velocity._2 .~ dy) $ p,True) | otherwise = moveObjs rs (p,b) where dx = if fwd then dx' else dx'*(-1) dy = if fwd then dy' else dy'*(-1) moveObjs _ p = p
mdietz94/haskellgame
src/Player.hs
mit
4,276
0
19
967
2,213
1,191
1,022
-1
-1
module Zwerg.Generator.Level.TestSquare (testSquare) where import Zwerg.Generator import Zwerg.Generator.Default -- import Zwerg.Generator.Verify -- import Zwerg.Generator.Enemy.Goblin -- import Zwerg.Generator.Item.Weapon testSquare :: Generator testSquare = Generator testSquareHatch [] -- replicateM_ 5 $ goblin >>= putOnRandomEmptyTile testSquareLevelUUID -- replicateM_ 4 $ sword >>= putOnRandomEmptyTile testSquareLevelUUID testSquareHatch :: EntityHatcher testSquareHatch = MkEntityHatcher $ do testSquareLevelUUID <- generateSkeleton Level testSquareTiles <- tileMap <@> testSquareLevelUUID let wallGlyph = Glyph 'X' $ CellColor white $ Just black floorGlyph = Glyph '·' $ CellColor white $ Just black zTraverseWithKey_ testSquareTiles $ \pos tileUUID -> do let (x, y) = unwrap pos isWallTile = x == 0 || x == mapWidthINT - 1 || y == 0 || y == mapHeightINT - 1 (<@-) :: Component a -> a -> MonadCompState () (<@-) = setComp tileUUID if isWallTile then do tileType <@- Wall blocksPassage <@- True blocksVision <@- True glyph <@- wallGlyph name <@- "Wall tile in the test level" description <@- "It is a wall." else do tileType <@- Floor blocksPassage <@- False blocksVision <@- False glyph <@- floorGlyph name <@- "Floor tile in the test level" description <@- "It is a floor." return testSquareLevelUUID
zmeadows/zwerg
lib/Zwerg/Generator/Level/TestSquare.hs
mit
1,622
0
23
495
340
168
172
32
2
{- HAAP: Haskell Automated Assessment Platform This module provides the @Hakyll@ plugin (<https://hackage.haskell.org/package/hakyll>) for static web-page generation. -} {-# LANGUAGE StandaloneDeriving, TypeOperators, UndecidableInstances, FlexibleContexts, EmptyDataDecls, FlexibleInstances, TypeFamilies, OverloadedStrings, ScopedTypeVariables, GeneralizedNewtypeDeriving, MultiParamTypeClasses, Rank2Types #-} module HAAP.Web.Hakyll ( module HAAP.Web.Hakyll , module Hakyll ) where import HAAP.Core import HAAP.IO import HAAP.Pretty as PP import HAAP.Plugin import HAAP.Shelly import HAAP.Utils import HAAP.Log import System.FilePath import System.Directory import System.Environment import System.Exit import Control.Applicative import Control.Monad import Control.Monad.Fail import Control.Monad.Base import Control.Monad.Morph import Control.Monad.Trans.Compose import Control.Monad.Identity --import Control.Exception import Control.Monad.IO.Class import Control.Monad.Writer (MonadWriter(..),WriterT(..)) import qualified Control.Monad.Reader as Reader import qualified Control.Monad.Writer as Writer import qualified Control.Monad.Except as Except import qualified Control.Monad.State as State import qualified Control.Monad.RWS as RWS import Control.Monad.RWS (RWST(..)) import Control.Monad.State (MonadState(..)) import Control.Monad.Reader (MonadReader(..)) --import Control.Monad.Catch (MonadCatch,MonadThrow) import Control.Monad.Trans import Control.Exception.Safe import Control.Monad.Trans.Control import Data.Functor.Contravariant import Data.Default import Data.Proxy import Data.Semigroup import Data.List import qualified Text.Blaze.Html as H import qualified Text.Blaze.Html.Renderer.Pretty as H import Hakyll import Paths_HAAP import Debug.Trace -- * Hakyll plugin data Hakyll data HakyllArgs = HakyllArgs { hakyllCfg :: Configuration , hakyllClean :: Bool , hakyllCopy :: Bool , hakyllMatch :: Bool , hakyllP :: HakyllP } -- Hakyll focuses (add specific ignoreFiles to speed-up hakyll "Creating provider..." step) type HakyllF = [FilePath] instance Default HakyllArgs where def = defaultHakyllArgs defaultHakyllArgs :: HakyllArgs defaultHakyllArgs = HakyllArgs def True True True def instance HaapPlugin Hakyll where type PluginI Hakyll = HakyllArgs type PluginO Hakyll = () type PluginT Hakyll = HakyllT type PluginK Hakyll t m = (MonadIO m) usePlugin getArgs m = do args <- getArgs x <- runHaapHakyllT args m return (x,()) useHakyll :: (HaapStack t m,PluginK Hakyll t m) => (PluginI Hakyll) -> Haap (PluginT Hakyll :..: t) m a -> Haap t m a useHakyll args = usePlugin_ (return args) instance Semigroup (Rules ()) where (<>) = mappend instance Monoid (Rules ()) where mempty = return () mappend x y = x >> y newtype HakyllT m a = HakyllT { unHakyllT :: RWST HakyllArgs (Rules (),HakyllF) HakyllP m a } deriving (Functor,Applicative,Monad,MonadFail,MonadTrans,MFunctor,MonadIO,MonadCatch,MonadThrow,MonadMask,MonadReader HakyllArgs,MonadState HakyllP,MonadWriter (Rules (),HakyllF)) instance HaapMonad m => HasPlugin Hakyll HakyllT m where liftPlugin = id instance (HaapStack t2 m) => HasPlugin Hakyll (ComposeT HakyllT t2) m where liftPlugin m = ComposeT $ hoist' lift m morphHakyllT :: (forall b . m b -> n b) -> HakyllT m a -> HakyllT n a morphHakyllT f (HakyllT m) = HakyllT $ RWS.mapRWST f m hakyllFocus :: HasPlugin Hakyll t m => HakyllF -> Haap t m a -> Haap t m a hakyllFocus fs m = do liftPluginProxy (Proxy::Proxy Hakyll) $ Writer.tell (mempty,fs) m hakyllRules :: HasPlugin Hakyll t m => Rules () -> Haap t m () hakyllRules r = liftPluginProxy (Proxy::Proxy Hakyll) $ Writer.tell (r,[]) runHaapHakyllT :: (HaapStack t m,MonadIO m) => PluginI Hakyll -> Haap (HakyllT :..: t) m a -> Haap t m a runHaapHakyllT args m = do let go :: (MonadIO m,HaapStack t m) => forall b . (HakyllT :..: t) m b -> t m b go (ComposeT (HakyllT m)) = do (e,hp,(rules,noignores)) <- RWS.runRWST m (args) (hakyllP args) let datarules = do matchDataTemplates when (hakyllMatch args) $ matchDataCSSs >> matchDataJSs rules let ignore fp = {-trace ("ignore?" ++ fp ++" "++ show b1 ++ " " ++ show b2)-} (b1 || b2) where b1 = not $ any (\p -> p `isPrefixOf` fp || fp `isPrefixOf` p) noignores b2 = ignoreFile (hakyllCfg args) fp let cfg = (hakyllCfg args) { ignoreFile = ignore } let build = withArgs ["build"] $ hakyllWithExitCode cfg datarules let clean = withArgs ["clean"] $ hakyllWithExitCode cfg datarules lift $ liftIO $ putStrLn $ "Running Hakyll without ignoring... " ++ prettyString noignores lift $ liftIO $ hakyllIO hp $ if (hakyllClean args) then clean >> build else build -- else catch -- (build >>= \e -> case e of { ExitFailure _ -> clean >> build; otherwise -> return e }) -- (\(err::SomeException) -> clean >> build) return e when (hakyllCopy args) $ copyDataFiles (hakyllCfg args) let datapaths = if hakyllMatch args then ["js","css"] else [] e <- mapHaapMonad go $ hakyllFocus datapaths m return e copyDataFiles :: (MonadIO m,HaapStack t m) => Configuration -> Haap t m () copyDataFiles cfg = do datapath <- runBaseIO' $ getDataFileName "" xs <- runBaseIO' $ listDirectory datapath runBaseSh $ forM_ xs $ \x -> shCpRecursive (datapath </> x) (providerDirectory cfg </> x) matchDataJSs :: Rules () matchDataJSs = do match (fromGlob ("js" </> "*.js")) $ do route idRoute compile copyFileCompiler matchDataTemplates :: Rules () matchDataTemplates = do match (fromGlob ("templates" </> "*.html")) $ do --route idRoute compile templateBodyCompiler match (fromGlob ("templates" </> "*.css")) $ do --route idRoute compile templateBodyCompiler match (fromGlob ("templates" </> "*.php")) $ do --route idRoute compile templateBodyCompiler match (fromGlob ("templates" </> "*.markdown")) $ do --route $ setExtension "html" compile $ pandocCompiler matchDataCSSs :: Rules () matchDataCSSs = do match (fromGlob ("css" </> "*.css")) $ do route idRoute compile compressCssCompiler orErrorHakyllPage :: (MonadIO m,HasPlugin Hakyll t m,Pretty a) => FilePath -> a -> Haap t m a -> Haap t m a orErrorHakyllPage page def m = orDo go m where go e = do hp <- getHakyllP hakyllFocus ["templates"] $ hakyllRules $ create [fromFilePath page] $ do route $ idRoute `composeRoutes` (funRoute $ hakyllRoute hp) compile $ do let errCtx = constField "errorMessage" (H.renderHtml $ H.toHtml $ prettyString e) `mappend` constField "projectpath" (fileToRoot $ hakyllRoute hp page) makeItem "" >>= loadAndApplyHTMLTemplate "templates/error.html" errCtx >>= hakyllCompile hp return $! def orErrorHakyllPage' :: (MonadIO m,HaapStack t m,Pretty a) => HakyllArgs -> FilePath -> a -> Haap t m a -> Haap t m a orErrorHakyllPage' hakyllargs page def m = orDo go m where go e = useHakyll hakyllargs $ do hp <- getHakyllP hakyllFocus ["templates"] $ hakyllRules $ create [fromFilePath page] $ do route $ idRoute `composeRoutes` (funRoute $ hakyllRoute hp) compile $ do let errCtx = constField "errorMessage" (H.renderHtml $ H.toHtml $ prettyString e) `mappend` constField "projectpath" (fileToRoot $ hakyllRoute hp page) makeItem "" >>= loadAndApplyHTMLTemplate "templates/error.html" errCtx >>= hakyllCompile hp return $! def orErrorHakyllPageWith :: (MonadIO m,HaapStack t m,Pretty a) => (forall a . Haap (HakyllT :..: t) m a -> Haap t m a) -> FilePath -> a -> Haap t m a -> Haap t m a orErrorHakyllPageWith runHakyll page def m = orDo go m where go e = runHakyll $ do hp <- getHakyllP hakyllFocus ["templates"] $ hakyllRules $ create [fromFilePath page] $ do route $ idRoute `composeRoutes` (funRoute $ hakyllRoute hp) compile $ do let errCtx = constField "errorMessage" (H.renderHtml $ H.toHtml $ prettyString e) `mappend` constField "projectpath" (fileToRoot $ hakyllRoute hp page) makeItem "" >>= loadAndApplyHTMLTemplate "templates/error.html" errCtx >>= hakyllCompile hp return $! def getHakyllP :: (HasPlugin Hakyll t m) => Haap t m HakyllP getHakyllP = liftHaap $ liftPluginProxy (Proxy::Proxy Hakyll) $ State.get getHakyllArgs :: (HasPlugin Hakyll t m) => Haap t m HakyllArgs getHakyllArgs = liftHaap $ liftPluginProxy (Proxy::Proxy Hakyll) $ Reader.ask -- * Hakyll Utilities loadAndApplyHTMLTemplate :: Identifier -> Context a -> Item a -> Compiler (Item String) loadAndApplyHTMLTemplate iden ctx item = do i <- loadAndApplyTemplate iden ctx item return i traceRoute :: Routes traceRoute = customRoute $ \iden -> trace ("traceRoute " ++ show iden) (toFilePath iden) relativeRoute :: FilePath -> Routes relativeRoute prefix = customRoute $ \iden -> makeRelative (prefix) (toFilePath iden) addToRoute :: FilePath -> Routes addToRoute prefix = customRoute $ \iden -> prefix </> (toFilePath iden) liftCompiler :: (String -> String) -> Item String -> Compiler (Item String) liftCompiler f i = return $ fmap f i funRoute :: (FilePath -> FilePath) -> Routes funRoute f = customRoute (f . toFilePath) instance Contravariant Context where contramap f (Context g) = Context $ \n ns x -> g n ns (fmap f x) ----loadAndApplyDataTemplate :: Identifier -> Context a -> Item a -> Compiler (Item String) ----loadAndApplyDataTemplate path c i = do ---- path' <- fromDataFileName $ toFilePath path ---- loadAndApplyTemplate path' c i ---- ----fromDataFileName :: FilePath -> Compiler Identifier ----fromDataFileName path = liftM fromFilePath $ unsafeCompiler $ getDataFileName path loadCopyFile :: Item CopyFile -> Compiler (Item String) loadCopyFile = load . fromFilePath . (\(CopyFile f) -> f) . itemBody dataRoute :: FilePath -> Routes dataRoute datapath = customRoute (\iden -> makeRelative datapath $ toFilePath iden) -- * Hakyll pre-processor data HakyllP = HakyllP { hakyllRoute :: FilePath -> FilePath -- additional routing , hakyllCompile :: Item String -> Compiler (Item String) -- additional compilation pipepile , hakyllIO :: forall a . IO a -> IO a -- handling of the hakyll run process } instance Semigroup HakyllP where (<>) = mappend instance Monoid HakyllP where mempty = defaultHakyllP mappend x y = HakyllP (hakyllRoute y . hakyllRoute x) (hakyllCompile x >=> hakyllCompile y) (hakyllIO x . hakyllIO y) instance Default HakyllP where def = defaultHakyllP defaultHakyllP :: HakyllP defaultHakyllP = HakyllP id return id readHakyllP :: HasPlugin Hakyll t m => Haap t m HakyllP readHakyllP = liftHaap $ liftPluginProxy (Proxy::Proxy Hakyll) $ State.get writeHakyllP :: HasPlugin Hakyll t m => HakyllP -> Haap t m () writeHakyllP hp = liftHaap $ liftPluginProxy (Proxy::Proxy Hakyll) $ State.put hp withHakyllP :: HasPlugin Hakyll t m => HakyllP -> Haap t m a -> Haap t m a withHakyllP newhp m = do oldhp <- readHakyllP writeHakyllP newhp x <- m writeHakyllP oldhp return x instance MonadBase b m => MonadBase b (HakyllT m) where liftBase = liftBaseDefault deriving instance MonadBaseControl b m => MonadBaseControl b (HakyllT m) deriving instance MonadTransControl HakyllT instance (Monad m,MonadTransControl HakyllT) => MonadTransRestore' HakyllT m where type StT' HakyllT a = StT HakyllT a restoreT' = restoreT instance (Monad m,Monad n,MonadTransControl HakyllT) => MonadTransControl' HakyllT m n where liftWith' = liftWith
hpacheco/HAAP
src/HAAP/Web/Hakyll.hs
mit
12,102
0
24
2,696
3,691
1,898
1,793
-1
-1
module Bio.HiC ( ContactMap(..) , fromAL , mkContactMap , mkContactMap' -- * contact matrix normalization , vcNorm , vcNormVector , sqrtNorm , sqrtNormVector , obsDivExp , expectedVector ) where import Bio.SamTools.Bam import qualified Bio.SamTools.BamIndex as BI import Control.Monad (forM_, when, liftM, replicateM) import Control.Monad.Primitive import Control.Monad.Trans (lift) import qualified Data.ByteString.Char8 as B import Data.Binary (Binary(..)) import Data.Conduit import qualified Data.Conduit.List as CL import Data.List (foldl') import Data.Maybe (fromJust) import Data.Bits (shiftR) import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as GM import qualified Data.Vector.Unboxed as U import qualified Data.Matrix.Symmetric as MS import qualified Data.Matrix.Symmetric.Mutable as MSM import Statistics.Sample (mean) import Bio.Data.Bam import Bio.Data.Bed type Matrix a = MS.SymMatrix U.Vector a -- | a specific base in the genome type Site = (B.ByteString, Int) -- | two sites interacting with each other form a contact type Contact = (Site, Site) data ContactMap = ContactMap { _chroms :: [(B.ByteString, Int)] , _resolution :: !Int , _matrix :: !(Matrix Double) } instance Binary ContactMap where put (ContactMap chroms res mat) = do put n mapM_ put chroms put res put mat where n = length chroms get = do n <- get chroms <- replicateM n get res <- get mat <- get return $ ContactMap chroms res mat -- | Read HiC contact map from associate list fromAL :: PrimMonad m => [(B.ByteString, Int)] -> Int -> Sink ((Int, Int), Double) m ContactMap fromAL chrs res = do mat <- lift $ MSM.replicate (matSize,matSize) 0 CL.mapM_ $ \((i,j), v) -> MSM.write mat (i `div` res, j `div` res) v mat' <- lift $ MS.unsafeFreeze mat return $ ContactMap chrs res mat' where matSize = foldl' (+) 0 $ map (\(_,x) -> (x-1) `div` res + 1) chrs {-# INLINE fromAL #-} {- mkContactMap' :: FilePath -> [BED3] -> Int -> Int -> Source IO .. mkContactMap' bamFl regions w extend = do handle <- liftIO $ BI.open bamFl forM_ [0..n-1] where positions = V.scanl f 0 regions' n = V.last positions f acc (BED3 chr s e) = acc + (e - s) `div` w regions' = V.fromList regions g i = binarySearch positions i -} -- | O(n * (logN + k)). n = number of bins, N = number of tags. Generate contanct -- map using constant memory mkContactMap :: FilePath -> BED3 -> Int -> Int -> Source IO ((Int, Int), Int) mkContactMap bamFl (BED3 chr s e) w extend = do handle <- lift $ BI.open bamFl forM_ [0..n-1] $ \i -> forM_ [i..n-1] $ \j -> do let s1 = s + i * w c1 = s1 + w' s2 = s + j * w c2 = s2 + w' r <- lift $ readCount handle (w'+extend) ((chr, c1), (chr, c2)) if i == j then yield ((s1, s2), r `div` 2) else yield ((s1, s2), r) where n = (e - s) `div` w w' = w `div` 2 -- | O(N + n). Store matrix in memory, faster when region is big mkContactMap' :: PrimMonad m => BED3 -> Int -> Int -> Sink Bam1 m (U.Vector Int) mkContactMap' (BED3 chr s e) w extend = do vec <- lift $ GM.replicate vecLen 0 loop vec lift . liftM (G.map (`div` 2)) . G.unsafeFreeze $ vec where n = (e - s) `div` w e' = n * w vecLen = n * (n+1) `div` 2 loop v = do x <- await case x of Just bam -> let flag = do bamChr <- targetName bam matChr <- mateTargetName bam return $ bamChr == chr && matChr == chr in case flag of Just True -> do let (p, pMate) = getStarts bam a = (p - s) `div` w b = (pMate - s) `div` w i | a < b = idx a b | otherwise = idx b a when (p >= s && pMate >= s && p < e' && pMate < e') $ lift $ GM.read v i >>= GM.write v i . (+1) loop v _ -> loop v _ -> return () idx i j = i * (2 * n - i + 1) `div` 2 + j - i -- | get starting location of bam and its mate getStarts :: Bam1 -> (Int, Int) getStarts bam = let p1 = fromIntegral . fromJust . position $ bam p2 = fromIntegral . fromJust . matePosition $ bam l = fromIntegral . fromJust . queryLength $ bam p1' | isReverse bam = p1 + l | otherwise = p1 p2' | isReverse bam = p2 + l | otherwise = p2 in (p1', p2') {-# INLINE getStarts #-} -- | the number of tag pairs that overlap with the region -- covered by the contact readCount :: BI.IdxHandle -- ^ bam file handler -> Int -- ^ half window width -> Contact -> IO Int readCount handle w ((c1, p1), (c2, p2)) = viewBam handle (c1, p1-w, p1+w) $$ CL.fold f 0 where f acc x = case mateTargetName x of Just chr -> if chr == c2 then let mp = fromIntegral . fromJust . matePosition $ x l = fromIntegral . fromJust . queryLength $ x in if isOverlapped r2 (mp, mp+l) then acc + 1 else acc else acc _ -> acc isOverlapped (lo,hi) (lo',hi') = lo' < hi && hi' > lo r2 = (p2-w, p2+w) {-# INLINE readCount #-} -- | Vanilla coverage normalization (Lieberman-Aiden et al., 2009) vcNorm :: ContactMap -> ContactMap vcNorm c = normalizeBy (vcNormVector c) c sqrtNorm :: ContactMap -> ContactMap sqrtNorm c = normalizeBy (sqrtNormVector c) c normalizeBy :: U.Vector Double -> ContactMap -> ContactMap normalizeBy normVec c = c{_matrix = MS.SymMatrix n vec'} where (MS.SymMatrix n vec) = _matrix c vec' = U.create $ do v <- U.thaw vec loop 0 0 v return v loop i j v | i < n && j < n = do let i' = idx n i j x = (normVec U.! i) * (normVec U.! j) x' | x == 0 = 0 | otherwise = 1 / x GM.read v i' >>= GM.write v i' . (*x') loop i (j+1) v | i < n = loop (i+1) (i+1) v | otherwise = return () {-# INLINE normalizeBy #-} vcNormVector :: ContactMap -> U.Vector Double vcNormVector c = U.generate n $ \i -> (U.foldl1' (+) $ mat `MS.takeRow` i) / 1e6 where mat = _matrix c n = fst $ MS.dim mat {-# INLINE vcNormVector #-} sqrtNormVector :: ContactMap -> U.Vector Double sqrtNormVector = U.map sqrt . vcNormVector {-# INLINE sqrtNormVector #-} -- | O/E obsDivExp :: ContactMap -> ContactMap obsDivExp c = c{_matrix = MS.SymMatrix n vec'} where (MS.SymMatrix n vec) = _matrix c vec' = U.create $ do v <- U.thaw vec loop 0 0 v return v loop i j v | i < n && j < n = do let i' = idx n i j x = expect `U.unsafeIndex` (j-i) x' | x == 0 = 0 | otherwise = 1 / x GM.read v i' >>= GM.write v i' . (*x') loop i (j+1) v | i < n = loop (i+1) (i+1) v | otherwise = return () expect = expectedVector c -- | Expected contact frequency between two locus with distance d. expectedAt :: Int -> ContactMap -> Double expectedAt d c = mean $ U.generate (n-d) $ \i -> MS.unsafeIndex mat (i,i+d) where mat = _matrix c n = MS.rows mat {-# INLINE expectedAt #-} expectedVector :: ContactMap -> U.Vector Double expectedVector c = U.generate n $ \d -> expectedAt d c where n = MS.rows $ _matrix c {-# INLINE expectedVector #-} -- row major upper triangular indexing idx :: Int -> Int -> Int -> Int idx n i j = (i * (2 * n - i - 1)) `shiftR` 1 + j {-# INLINE idx #-}
kaizhang/bioinformatics-toolkit
bioinformatics-toolkit/src/Bio/HiC.hs
mit
8,288
0
31
3,003
2,817
1,490
1,327
195
4
module Print3Broken where greeting :: String greeting = "Yarrrrrrrrr" printSecond :: IO () printSecond = do putStrLn greeting main :: IO () main = do putStrLn greeting printSecond
rasheedja/HaskellFromFirstPrinciples
Chapter3/print3broken.hs
mit
189
0
7
37
59
30
29
10
1
{-# htermination (esEsMyBool :: MyBool -> MyBool -> MyBool) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil esEsMyBool :: MyBool -> MyBool -> MyBool esEsMyBool MyFalse MyFalse = MyTrue; esEsMyBool MyFalse MyTrue = MyFalse; esEsMyBool MyTrue MyFalse = MyFalse; esEsMyBool MyTrue MyTrue = MyTrue;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/EQEQ_3.hs
mit
356
0
8
69
94
53
41
8
1
module ExpressoesLambdaComposicaoLazyness where import FuncoesDeAltaOrdemFilterFold import FuncoesDeAltaOrdemAplicacaoParcialMap -- Relembrando foldr e seu tipo... -- fold :: x -> y -> z -> w -- fold :: x -> y -> [a] -> y -- fold :: x -> y -> [a] -> y {e :: a, es :: [a]} -- fold :: (a -> y -> y) -> y -> [a] -> y -- e a função global vista até agora (mediafr), compondo as menores... -- Mas varremos a lista duas vezes… Se eficiência for um problema, -- podemos varrer só uma vez? Como em Java? Recursão diferente, acumulando -- valores como parâmetros. Recursão direta. mediaaux s t [] = s/t mediaaux s t (e:l) = mediaaux (s+e) (t+1) l -- mediaaux 0 0 [1,3,5] = -- mediaaux (0+1) (0+1) [3,5] -- mediaaux 1 1 [3,5] -- mediaaux (1+3) (1+1) [5] -- mediaaux 4 2 [5] -- mediaaux (4+5) (2+1) [] -- mediaaux 9 3 [] -- 9/3 -- 3 mediao l = mediaaux 0 0 l -- mediao1 [1,2] = -- mediaaux 0 0 [1,2] -- Até agora, com frequência, repetimos o parâmetro em apenas um local -- do lado direito, na extremidade da chamada de outra função. Podemos -- evitar isso omitindo o parâmetro e definindo uma função diretamente -- em termos de outra... somafrp = foldr (+) 0 sizefrp = foldr soma1 0 -- f x = g x -- f = g -- ilustrar tipos de várias aplicações parciais -- :t foldr (+) -- :t foldr (+) 0 somae x y = x + y -- internamente é simulado assim somae1 x = somae2 where somae2 y = x + y -- Dizemos que a aplicação da função foldr é parcial… Não fornecemos -- todos os parâmetros… Notem os tipos somafrp :: [Integer] -> Integer -- A aplicação parcial de foldr retorna uma função como resultado. Na -- verdade, ao invés de ver foldr como uma função que tem 3 parâmetros, -- podemos ver como uma função que tem um parâmetro e retorna uma outra -- função, que tem um parâmetro também e recebe outra função que recebe uma -- lista e retorna um elemento de algum tipo. -- Funções também podem ser representadas por expressões lambda. Valor -- que denota uma função anônima. Similar a Java, mas bem mais limpo. -- sizefrpl :: [a] -> Integer sizefrpl = foldr (\x y -> 1 + y) 0 -- foldr soma 0 -- soma x y = x + y -- -- soma = \x y -> x + y -- soma = \x -> \y -> x + y -- -- f = \x -> x + 1 -- f x = x + 1 -- Podemos definir a função que computa a media com foldr, também sem -- varrer a lista duas vezes. mediafold [] = 0 mediafold l = s/t where (s,t) = foldr (\x (s1,t1) -> (x+s1,t1+1)) (0,0) l -- Sistema de tipos de Haskell às vezes complica! mfe [] = [] mfe l = 1.5 -- Podemos compor as partes de forma mais elegante, com composição de funções… -- (.) f g x = f (g x) -- (.) :: (b -> c) -> (a -> b) -> a -> c -- Compondo as definições que criamos até agora… -- principal :: [(a, Double, Double)] -> Double principal = mediafr . (map snd) . aprovadosf . mediasPLC -- Testando teste = principal turma -- Avaliação lazy, só avalia o que for necessário para a execução da função. -- Normalmente, em outras linguagens, a avaliação é estrita (não lazy), e da -- esquerda para a direita. lazy x y | x > 0 = x | otherwise = y loop x = loop x res5 = lazy 5 (loop 1) resloop1 = lazy (loop 1) 5 resloop2 = lazy 0 (loop 1) llazy [] = [] llazy (e:l) | e > 0 = [e] | otherwise = llazy l res1 = llazy [-10000000..] -- Funções como valores e resultados… -- twice :: (a -> a) -> a -> a -- Diferente de a -> a -> a -> a twice f = f . f -- Exercício avaliar (x,'+',y) = x + y avaliar (x,'-',y) = x - y avaliar (x,'*',y) = x * y avaliar (x,'/',y) = x / y av (x,op,y) = avOp op x y avOp '+' = (+) avOp '-' = (-) avOp '*' = (*) avOp '/' = (/) avaliarExpressoes [] = [] avaliarExpressoes (e : l) = avaliar e : avaliarExpressoes l ae = map av somaTotal l = sum (avaliarExpressoes (filtraDivisaoPorZero l)) st = sum . ae . fz filtraDivisaoPorZero [] = [] filtraDivisaoPorZero ((x,'/',0) : l) = filtraDivisaoPorZero l filtraDivisaoPorZero (e : l) = e : filtraDivisaoPorZero l fz = filter (\(x,op,y) -> not(op == '/' && y == 0)) testea = [(4,'+',3),(4,'/',3)] testeb = [(4,'+',3),(4,'/',0),(4,'/',3)] -- Quais os tipos das funções abaixo? -- f :: (a -> Bool) -> [[a]] -> [[a]] -- g :: (a1 -> a -> a) -> [a] -> [[a1] -> a] f = map.filter g = map.foldr -- Escopo estático e dinâmico... closure! scope x y = g where g w = x + y + w res17 = x + (scope 2 3) 3 where x = 9 res20 = x + (scope 5 3) 3 where x = 9
pauloborba/plc
src/ExpressoesLambdaComposicaoLazyness.hs
cc0-1.0
4,527
0
12
1,070
1,027
582
445
58
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} import Control.Monad.Error import Control.Monad.Reader import Control.Monad.Writer import Control.Monad.State data Options = Options data Ast = Ast data BlockingFunctions = BlockingFunctions data DefinedFunctions = DefinedFunctions data StartRoutines = StartRoutines data CallGraph = CallGraph data CriticalFunctions = CriticalFunctions -- IO options :: ErrorT String IO Options options = undefined parse :: ErrorT String IO Ast parse = undefined pretty_print :: Ast -> ErrorT String IO () pretty_print = undefined write_debug_symbols :: [DebugSymbol] -> ErrorT String IO () write_debug_symbols = undefined report :: Either String () -> IO () report (Left err) = putStrLn $ "failed: " ++ err report _ = putStrLn "complete" -- Analysis data Analysis = Analysis { getBlockingFunctions :: BlockingFunctions, getDefinedFunctions :: DefinedFunctions, getStartRoutines :: StartRoutines, getCallGraph :: CallGraph, getCriticalFunctions :: CriticalFunctions } check_sanity :: Ast -> ER () check_sanity = undefined check_call_graph :: CallGraph -> StartRoutines -> DefinedFunctions -> Ast -> ER () check_call_graph = undefined blocking_functions :: Ast -> ER BlockingFunctions blocking_functions = undefined defined_functions :: Ast -> ER DefinedFunctions defined_functions = undefined start_routines :: DefinedFunctions -> Ast -> ER StartRoutines start_routines = undefined call_graph :: DefinedFunctions -> BlockingFunctions -> Ast -> ER CallGraph call_graph = undefined critical_functions :: CallGraph -> BlockingFunctions -> Ast -> ER CriticalFunctions critical_functions = undefined check_constraints :: CriticalFunctions -> StartRoutines -> Ast -> ER () check_constraints = undefined analysis :: Options -> Ast -> ErrorT String IO (Analysis, Ast) analysis opt ast = ErrorT $ return $ runReader (runErrorT (runER (analysis' ast))) opt analysis' :: Ast -> ER (Analysis, Ast) analysis' ast = do check_sanity ast bf <- blocking_functions ast df <- defined_functions ast sr <- start_routines df ast cg <- call_graph df bf ast check_call_graph cg sr df ast cf <- critical_functions cg bf ast check_constraints cf sr ast let ana = Analysis bf df sr cg cf return (ana, ast) -- Transformation data DebugSymbol = DebugSymbol data TransEnv = TransEnv { getAnalysis :: Analysis, getOptions :: Options } newtype Trans a = Trans { runTrans :: WriterT [DebugSymbol] (Reader TransEnv) a } deriving ( Monad, MonadWriter [DebugSymbol], MonadReader TransEnv ) transform :: Options -> Analysis -> Ast -> (Ast, [DebugSymbol]) transform opt ana ast = runReader (runWriterT (runTrans (transform' ast))) $ TransEnv ana opt transform' :: Ast -> Trans Ast transform' = undefined main :: IO () main = do err <- runErrorT $ do opt <- options ast <- parse (ana, ast') <- analysis opt ast let (ast'', ds) = transform opt ana ast' pretty_print ast'' write_debug_symbols ds report err
copton/ocram
try/architecture/Arch.hs
gpl-2.0
2,964
60
12
485
932
494
438
83
1
module Language.Prolog (module Prolog) where import Prolog
nishiuramakoto/logiku
prolog/Prolog/Language/Prolog.hs
gpl-3.0
59
0
4
7
15
10
5
2
0
import Data.List (find) import Data.Maybe (fromMaybe, isJust) import Language.Dockerfile.Normalize import Language.Dockerfile.Parser import Language.Dockerfile.Rules import Language.Dockerfile.Syntax import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit assertAst s ast = case parseString (s ++ "\n") of Left err -> assertFailure $ show err Right dockerfile -> assertEqual "ASTs are not equal" ast $ map instruction dockerfile assertChecks rule s f = case parseString (s ++ "\n") of Left err -> assertFailure $ show err Right dockerfile -> f $ analyze [rule] dockerfile -- Assert a failed check exists for rule ruleCatches :: Rule -> String -> Assertion ruleCatches rule s = assertChecks rule s f where f checks = assertEqual "No check for rule found" 1 $ length checks ruleCatchesNot :: Rule -> String -> Assertion ruleCatchesNot rule s = assertChecks rule s f where f checks = assertEqual "Found check of rule" 0 $ length checks normalizeTests = [ "join escaped lines" ~: assertEqual "Lines are not joined" expected $ normalizeEscapedLines dockerfile , "join long cmd" ~: assertEqual "Lines are not joined" longEscapedCmdExpected $ normalizeEscapedLines longEscapedCmd ] where expected = unlines ["ENV foo=bar baz=foz", ""] dockerfile = unlines ["ENV foo=bar \\", "baz=foz"] longEscapedCmd = unlines [ "RUN wget https://download.com/${version}.tar.gz -O /tmp/logstash.tar.gz && \\" , "(cd /tmp && tar zxf logstash.tar.gz && mv logstash-${version} /opt/logstash && \\" , "rm logstash.tar.gz) && \\" , "(cd /opt/logstash && \\" , "/opt/logstash/bin/plugin install contrib)" ] longEscapedCmdExpected = concat [ "RUN wget https://download.com/${version}.tar.gz -O /tmp/logstash.tar.gz && " , "(cd /tmp && tar zxf logstash.tar.gz && mv logstash-${version} /opt/logstash && " , "rm logstash.tar.gz) && " , "(cd /opt/logstash && " , "/opt/logstash/bin/plugin install contrib)\n" , "\n" , "\n" , "\n" , "\n" ] astTests = [ "from untagged" ~: assertAst "FROM busybox" [From (UntaggedImage "busybox")] , "env pair" ~: assertAst "ENV foo=bar" [Env [("foo", "bar")]] , "env space pair" ~: assertAst "ENV foo bar" [Env [("foo", "bar")] ] , "env quoted pair" ~: assertAst "ENV foo=\"bar\"" [Env [("foo", "bar")]] , "env multi raw pair" ~: assertAst "ENV foo=bar baz=foo" [Env [("foo", "bar"), ("baz", "foo")]] , "env multi quoted pair" ~: assertAst "ENV foo=\"bar\" baz=\"foo\"" [Env [("foo", "bar"), ("baz", "foo")]] , "one line cmd" ~: assertAst "CMD true" [Cmd ["true"]] , "multiline cmd" ~: assertAst "CMD true \\\n && true" [Cmd ["true", "&&", "true"], EOL] , "maintainer " ~: assertAst "MAINTAINER [email protected]" [Maintainer "[email protected]"] , "maintainer from" ~: assertAst maintainerFromProg maintainerFromAst , "quoted exec" ~: assertAst "CMD [\"echo\", \"1\"]" [Cmd ["echo", "1"]] , "env works with cmd" ~: assertAst envWorksCmdProg envWorksCmdAst , "multicomments first" ~: assertAst multiCommentsProg1 [Comment " line 1", Comment " line 2", Run ["apt-get", "update"], EOL] , "multicomments after" ~: assertAst multiCommentsProg2 [Run ["apt-get", "update"], Comment " line 1", Comment " line 2", EOL] , "escape with space" ~: assertAst escapedWithSpaceProgram [Run ["yum", "install", "-y", "imagemagick", "mysql"], EOL, EOL] , "scratch and maintainer" ~: assertAst "FROM scratch\nMAINTAINER [email protected]" [From (UntaggedImage "scratch"), Maintainer "[email protected]"] ] where maintainerFromProg = "FROM busybox\nMAINTAINER [email protected]" maintainerFromAst = [ From (UntaggedImage "busybox") , Maintainer "[email protected]" ] envWorksCmdProg = "ENV PATH=\"/root\"\nCMD [\"hadolint\",\"-i\"]" envWorksCmdAst = [ Env [("PATH", "/root")] , Cmd ["hadolint", "-i"] ] multiCommentsProg1 = unlines [ "# line 1" , "# line 2" , "RUN apt-get update" ] multiCommentsProg2 = unlines [ "RUN apt-get update" , "# line 1" , "# line 2" ] escapedWithSpaceProgram = unlines [ "RUN yum install -y \\ " , "imagemagick \\ " , "mysql" ] ruleTests = [ "untagged" ~: ruleCatches noUntagged "FROM debian" , "explicit latest" ~: ruleCatches noLatestTag "FROM debian:latest" , "explicit tagged" ~: ruleCatchesNot noLatestTag "FROM debian:jessie" , "sudo" ~: ruleCatches noSudo "RUN sudo apt-get update" , "no root" ~: ruleCatches noRootUser "USER root" , "install sudo" ~: ruleCatchesNot noSudo "RUN apt-get install sudo" , "sudo chained programs" ~: ruleCatches noSudo "RUN apt-get update && sudo apt-get install" , "invalid cmd" ~: ruleCatches invalidCmd "RUN top" , "install ssh" ~: ruleCatchesNot invalidCmd "RUN apt-get install ssh" , "apt upgrade" ~: ruleCatches noUpgrade "RUN apt-get update && apt-get upgrade" , "apt-get version pinning" ~: ruleCatches aptGetVersionPinned "RUN apt-get update && apt-get install python" , "apt-get no cleanup" ~: ruleCatches aptGetCleanup "RUN apt-get update && apt-get install python" , "apt-get cleanup" ~: ruleCatchesNot aptGetCleanup "RUN apt-get update && apt-get install python && rm -rf /var/lib/apt/lists/*" , "use add" ~: ruleCatches useAdd "COPY packaged-app.tar /usr/src/app" , "use not add" ~: ruleCatchesNot useAdd "COPY package.json /usr/src/app" , "invalid port" ~: ruleCatches invalidPort "EXPOSE 80000" , "valid port" ~: ruleCatchesNot invalidPort "EXPOSE 60000" , "maintainer address" ~: ruleCatches maintainerAddress "MAINTAINER Lukas" , "maintainer uri" ~: ruleCatchesNot maintainerAddress "MAINTAINER Lukas <[email protected]>" , "maintainer uri" ~: ruleCatchesNot maintainerAddress "MAINTAINER John Doe <[email protected]>" , "maintainer mail" ~: ruleCatchesNot maintainerAddress "MAINTAINER http://lukasmartinelli.ch" , "pip requirements" ~: ruleCatchesNot pipVersionPinned "RUN pip install -r requirements.txt" , "pip version not pinned" ~: ruleCatches pipVersionPinned "RUN pip install MySQL_python" , "pip version pinned" ~: ruleCatchesNot pipVersionPinned "RUN pip install MySQL_python==1.2.2" , "apt-get auto yes" ~: ruleCatches aptGetYes "RUN apt-get install python" , "apt-get yes shortflag" ~: ruleCatchesNot aptGetYes "RUN apt-get install -yq python" , "apt-get yes different pos" ~: ruleCatchesNot aptGetYes "RUN apt-get install -y python" , "apt-get with auto yes" ~: ruleCatchesNot aptGetYes "RUN apt-get -y install python" , "apt-get with auto expanded yes" ~: ruleCatchesNot aptGetYes "RUN apt-get --yes install python" , "apt-get install recommends" ~: ruleCatchesNot aptGetNoRecommends "RUN apt-get install --no-install-recommends python" , "apt-get no install recommends" ~: ruleCatches aptGetNoRecommends "RUN apt-get install python" , "apt-get no install recommends" ~: ruleCatches aptGetNoRecommends "RUN apt-get -y install python" , "apt-get version" ~: ruleCatchesNot aptGetVersionPinned "RUN apt-get install -y python=1.2.2" , "apt-get pinned" ~: ruleCatchesNot aptGetVersionPinned "RUN apt-get -y --no-install-recommends install nodejs=0.10" , "apt-get pinned chained" ~: ruleCatchesNot aptGetVersionPinned $ unlines aptGetPinnedChainedProgram , "apt-get pinned regression" ~: ruleCatchesNot aptGetVersionPinned $ unlines aptGetPinnedRegressionProgram , "has maintainer named" ~: ruleCatchesNot hasMaintainer "FROM busybox\nMAINTAINER [email protected]" , "has maintainer" ~: ruleCatchesNot hasMaintainer "FROM debian\nMAINTAINER Lukas" , "has maintainer first" ~: ruleCatchesNot hasMaintainer "MAINTAINER Lukas\nFROM DEBIAN" , "has no maintainer" ~: ruleCatches hasMaintainer "FROM debian" , "using add" ~: ruleCatches copyInsteadAdd "ADD file /usr/src/app/" , "add is ok for archive" ~: ruleCatchesNot copyInsteadAdd "ADD file.tar /usr/src/app/" , "add is ok for url" ~: ruleCatchesNot copyInsteadAdd "ADD http://file.com /usr/src/app/" , "many cmds" ~: ruleCatches multipleCmds "CMD /bin/true\nCMD /bin/true" , "single cmd" ~: ruleCatchesNot multipleCmds "CMD /bin/true" , "no cmd" ~: ruleCatchesNot multipleEntrypoints "FROM busybox" , "many entries" ~: ruleCatches multipleEntrypoints "ENTRYPOINT /bin/true\nENTRYPOINT /bin/true" , "single entry" ~: ruleCatchesNot multipleEntrypoints "ENTRYPOINT /bin/true" , "no entry" ~: ruleCatchesNot multipleEntrypoints "FROM busybox" , "workdir variable" ~: ruleCatchesNot absoluteWorkdir "WORKDIR ${work}" , "scratch" ~: ruleCatchesNot noUntagged "FROM scratch" ] where aptGetPinnedChainedProgram = [ "RUN apt-get update \\" , " && apt-get -y --no-install-recommends install nodejs=0.10 \\" , " && rm -rf /var/lib/apt/lists/*" ] aptGetPinnedRegressionProgram = [ "RUN apt-get update && apt-get install --no-install-recommends -y \\" , "python-demjson=2.2.2* \\" , "wget=1.16.1* \\" , "git=1:2.5.0* \\" , "ruby=1:2.1.*" ] tests = test $ ruleTests ++ astTests ++ normalizeTests main = defaultMain $ hUnitTestToTests tests
beijaflor-io/haskell-language-dockerfile
test/Test.hs
gpl-3.0
9,823
0
11
2,320
1,683
888
795
137
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} module Language.LXDFile.InitScript.Types ( InitScript(..) , initScript , AST , Instruction(..) , InstructionPos(..) , Action(..) , Arguments(..) , InitScriptError(..) ) where import Control.Monad.Except (MonadError, throwError) import Data.Maybe (fromMaybe, mapMaybe) import Data.Aeson (FromJSON, ToJSON) import GHC.Generics (Generic) import Text.Parsec (ParseError) import Language.LXDFile.Types (Action(..), Arguments(..)) data InitScript = InitScript { onUpdate :: Bool , actions :: [Action] } deriving (Generic, Show) instance FromJSON InitScript where instance ToJSON InitScript where data InitScriptError = ParseError ParseError | ASTError ASTError deriving (Show) initScript :: MonadError ASTError m => AST -> m InitScript initScript ast = InitScript <$> (fromMaybe False <$> maybeOne ManyOnUpdates onUpdates) <*> allActions where instructions = map instruction ast onUpdates = mapMaybe onUpdate' instructions onUpdate' (OnUpdate x) = Just x onUpdate' _ = Nothing allActions = pure $ mapMaybe action' instructions action' (Action x) = Just x action' _ = Nothing maybeOne _ [x] = return $ Just x maybeOne _ [] = return Nothing maybeOne manyErr _ = throwError manyErr data ASTError = ManyOnUpdates instance Show ASTError where show ManyOnUpdates = "multiple on update directives" type AST = [InstructionPos] data InstructionPos = InstructionPos Instruction String Int deriving (Show) data Instruction = Action Action | Comment String | OnUpdate Bool | EOL deriving (Show) instruction :: InstructionPos -> Instruction instruction (InstructionPos i _ _) = i
hverr/lxdfile
src/Language/LXDFile/InitScript/Types.hs
gpl-3.0
1,883
0
9
477
508
286
222
52
5
{-# LANGUAGE TemplateHaskell #-} module Main where import Control.Monad (guard) import Control.Monad.IO.Class (liftIO) import Data.Char (isAscii, isSymbol, isPunctuation) import Data.FileEmbed import Data.Foldable (forM_) import Data.IORef (IORef, newIORef, writeIORef, readIORef) import Data.Text (unpack) import Graphics.UI.Gtk import Lib (parse, evaluate) import Text.Megaparsec (errorPos, sourceColumn) main :: IO () main = do _ <- initGUI -- Create the builder, and load the UI file builder <- builderNew builderAddFromString builder ($(embedStringFile "src-exe/calc.glade") :: String) mainLabel <- builderGetObject builder castToLabel "labelBig" sideLabel <- builderGetObject builder castToLabel "labelSmall" -- Fix UTF-8 sqrt symbol sqrtButton <- builderGetObject builder castToButton "buttonSqrt" mChild <- binGetChild sqrtButton case mChild of Just child -> labelSetText (castToLabel child) "√x" Nothing -> return () -- Color EventBoxes (= workaround for button colors) delBox <- builderGetObject builder castToEventBox "boxDel" widgetModifyBg delBox StateNormal (Color 59624 8824 8995) widgetModifyBg delBox StatePrelight (Color 59624 8824 8995) widgetModifyBg delBox StateActive (Color 59624 8824 8995) clrBox <- builderGetObject builder castToEventBox "boxClr" widgetModifyBg clrBox StateNormal (Color 59624 8824 8995) widgetModifyBg clrBox StatePrelight (Color 59624 8824 8995) widgetModifyBg clrBox StateActive (Color 59624 8824 8995) subBox <- builderGetObject builder castToEventBox "boxEq" widgetModifyBg subBox StateNormal (Color 0 65535 0) widgetModifyBg subBox StatePrelight (Color 0 65535 0) widgetModifyBg subBox StateActive (Color 0 65535 0) -- Global state hasAnswer <- newIORef False lastAnswer <- newIORef "0.0" window <- builderGetObject builder castToWindow "window1" _ <- on window objectDestroy mainQuit widgetModifyBg window StateNormal (Color 65535 65535 65535) _ <- on window keyPressEvent $ tryEvent $ do Just char <- eventKeyVal >>= (liftIO . keyvalToChar) guard $ isAscii char hasAnswer_ <- liftIO $ readIORef hasAnswer liftIO $ if isSymbol char || isPunctuation char then append [char] mainLabel hasAnswer_ else overwrite [char] mainLabel hasAnswer_ liftIO $ writeIORef hasAnswer False _ <- on window keyPressEvent $ tryEvent $ do "Return" <- fmap unpack eventKeyName liftIO $ submit mainLabel sideLabel hasAnswer lastAnswer _ <- on window keyPressEvent $ tryEvent $ do "BackSpace" <- fmap unpack eventKeyName liftIO $ delete mainLabel _ <- on window keyPressEvent $ tryEvent $ do "Delete" <- fmap unpack eventKeyName liftIO $ clear mainLabel sideLabel hasAnswer _ <- on window keyPressEvent $ tryEvent $ do "Escape" <- fmap unpack eventKeyName liftIO $ clear mainLabel sideLabel hasAnswer -- Bind all number/operator buttons forM_ textButtonBindings $ \(btnId,action) -> do button <- builderGetObject builder castToButton btnId on button buttonActivated $ do readIORef hasAnswer >>= action mainLabel writeIORef hasAnswer False -- Bind action buttons subButton <- builderGetObject builder castToButton "buttonEq" _ <- on subButton buttonActivated (submit mainLabel sideLabel hasAnswer lastAnswer) delButton <- builderGetObject builder castToButton "buttonDel" _ <- on delButton buttonActivated (delete mainLabel) clrButton <- builderGetObject builder castToButton "buttonClr" _ <- on clrButton buttonActivated (clear mainLabel sideLabel hasAnswer) ansButton <- builderGetObject builder castToButton "buttonAns" _ <- on ansButton buttonActivated (answer mainLabel hasAnswer lastAnswer) -- Display the window widgetShowAll window mainGUI textButtonBindings :: [(String, Label -> Bool -> IO ())] textButtonBindings = [ ("buttonFact", append "!") , ("buttonMod", append "%") , ("buttonExp", append "^") , ("buttonSciNot",append "*10^") , ("buttonNatExp", append "e^") , ("buttonInv", append "^-1") , ("buttonSqrt", append "^0.5") , ("buttonAdd", append "+") , ("buttonSub", append "-") , ("buttonMul", append "*") , ("buttonDiv", append "/") , ("buttonLog", overwrite "log(") , ("buttonLn", overwrite "ln(") , ("buttonLeft", overwrite "(") , ("buttonRight", overwrite ")") , ("buttonPoint", overwrite ".") , ("button0", overwrite "0") , ("button1", overwrite "1") , ("button2", overwrite "2") , ("button3", overwrite "3") , ("button4", overwrite "4") , ("button5", overwrite "5") , ("button6", overwrite "6") , ("button7", overwrite "7") , ("button8", overwrite "8") , ("button9", overwrite "9")] answer :: Label -> IORef Bool -> IORef String -> IO () answer mainLabel hasAnswer lastAnswer = do hasAnswer_ <- readIORef hasAnswer if hasAnswer_ then writeIORef hasAnswer False else do answer_ <- readIORef lastAnswer append answer_ mainLabel hasAnswer_ submit :: Label -> Label -> IORef Bool -> IORef String -> IO () submit mainLabel sideLabel hasAnswer lastAnswer = do expr <- labelGetText mainLabel case parse expr of Left e -> let start = max 0 $ sourceColumn (errorPos e) - 2 end = length expr in labelSetAttributes mainLabel [ AttrUnderlineColor start end (Color 65535 0 0) , AttrUnderline start end UnderlineError , AttrWeight 0 end WeightBold , AttrSize 0 end 12] Right val -> do let ans = case evaluate val of Just n -> show n Nothing -> "NaN" writeIORef hasAnswer True writeIORef lastAnswer ans labelSetText sideLabel expr setMainLabelText mainLabel ans delete :: Label -> IO () delete label = do text <- labelGetText label :: IO String labelSetText label $ take (length text - 1) text clear :: Label -> Label -> IORef Bool -> IO () clear label1 label2 hasAnswer = do writeIORef hasAnswer False labelSetText label1 "" labelSetText label2 "" append :: String -> Label -> Bool -> IO () append string label _ = do current <- labelGetText label setMainLabelText label (current ++ string) overwrite :: String -> Label -> Bool -> IO () overwrite string label hasAnswer = if hasAnswer then setMainLabelText label string else append string label False setMainLabelText :: Label -> String -> IO () setMainLabelText label str = do let len = length str labelSetText label str labelSetAttributes label [AttrWeight 0 len WeightBold, AttrSize 0 len 12]
fit-ivs/calc
src-exe/Main.hs
gpl-3.0
6,941
0
18
1,709
2,072
1,002
1,070
154
3
{-| Module : Parser License : GPL Maintainer : [email protected] Stability : experimental Portability : portable -} module Helium.Parser.Parser ( module_, exp_, exp0, type_, atype, contextAndType , parseOnlyImports ) where {- Absent: - records - "newtype" - strictness annotations - n+k patterns - [] and (,) and (,,,) etc as (type) constructor - empty declarations, qualifiers, alternatives or statements - "qualified", "as" in imports - import and export lists Simplified: - funlhs For example x:xs +++ ys = ... is not allowed, parentheses around x:xs necessary - pattern binding met pat10 i.p.v. pat0 For example (x:xs) = [1..] (parenthesis are obligatory) - sections: (fexp op) and (op fexp) For example (+2*3) is not allowed, should be (+(2*3)) - fixity declarations only at top-level -} import Control.Monad import Helium.Parser.ParseLibrary hiding (satisfy) import Data.Functor.Identity (Identity) import Text.ParserCombinators.Parsec import Text.Parsec.Prim (ParsecT) import Helium.Parser.Lexer import Helium.Parser.LayoutRule import qualified Helium.Utils.Texts as Texts import Helium.Syntax.UHA_Syntax import Helium.Syntax.UHA_Utils import Helium.Syntax.UHA_Range import qualified Helium.Parser.CollectFunctionBindings as CollectFunctionBindings import Helium.Utils.Utils parseOnlyImports :: String -> IO [String] parseOnlyImports fullName = do contents <- readSourceFile fullName return $ case lexer [] fullName contents of Left _ -> [] Right (toks, _) -> case runHParser onlyImports fullName (layout toks) False {- no EOF -} of Left _ -> [] Right imports -> map stringFromImportDeclaration imports {- module -> "module" modid exports? "where" body -- | body -} module_ :: HParser Module module_ = addRange $ do lexMODULE n <- modid let mes = MaybeExports_Nothing lexWHERE b <- body return (\r -> Module_Module r (MaybeName_Just n) mes b) <|> do b <- body return (\r -> Module_Module r MaybeName_Nothing MaybeExports_Nothing b) onlyImports :: HParser [ImportDeclaration] onlyImports = do lexMODULE _ <- modid let _ = MaybeExports_Nothing lexWHERE lexLBRACE <|> lexINSERTED_LBRACE many (do { i <- impdecl; semicolon; return i }) <|> do lexLBRACE <|> lexINSERTED_LBRACE many (do { i <- impdecl; semicolon; return i }) where semicolon = lexSEMI <|> lexINSERTED_SEMI <|> lexINSERTED_RBRACE -- the last of the three is a hack to support files that -- only contain imports {- body -> "{" topdecls "}" topdecls -> topdecl1 ";" ... ";" topdecln (n>=0) -} body :: HParser Body body = addRange $ withBraces' $ \explicit -> do lexHOLE return (\r -> Body_Hole r 0) <|> do (is, ds) <- importsThenTopdecls explicit let groupedDecls = CollectFunctionBindings.decls ds return $ \r -> Body_Body r is groupedDecls importsThenTopdecls :: Bool -> ParsecT [Token] SourcePos Identity ([ImportDeclaration], [Declaration]) importsThenTopdecls explicit = do is <- many (do { i <- impdecl ; if explicit then lexSEMI else lexSEMI <|> lexINSERTED_SEMI ; return i } ) ds <- topdeclCombinator topdecl return (is, ds) where topdeclCombinator = if explicit then semiSepTerm else semiOrInsertedSemiSepTerm -- JW: Need to add to topdecl '| "class" [scontext =>] tycls tyvar [where cdecls] ' -- First try " class tycon tyvar [where cdecls]" as class constraints do not yet exist -- in a later phase add them then also data has to be changed to deal with typeclass constraints -- please note that in ghc already this has some strange behaviour, read semantics carefully... {- topdecl -> impdecl | "data" simpletype "=" constrs derivings? | "type" simpletype "=" type | infixdecl | decl derivings -> "deriving" derivings' derivings' -> tycon | "(" ")" | "(" tycon ( "," tycon )* ")" simpletype -> tycon tyvar1 ... tyvark (k>=0) -} {- | Data range : Range context : ContextItems simpletype : SimpleType constructors : Constructors derivings : Names -} topdecl :: HParser Declaration topdecl = addRange ( do lexDATA st <- simpleType lexASG cs <- constrs ds <- option [] derivings return (\r -> Declaration_Data r [] st cs ds) <|> do lexTYPE st <- simpleType lexASG t <- type_ return $ \r -> Declaration_Type r st t <|> -- Declaration_Class (Range) (ContextItems) (SimpleType) (MaybeDeclarations) {- cdecls :: HParser Declarations cdecls = do ds <- withLayout cdecl return (CollectFunctionBindings.cdecls ds) -} do lexCLASS ct <- option [] (try $ do {c <- scontext ; lexDARROW ; return c} ) st <- simpleType ds <- option MaybeDeclarations_Nothing (try $ do lexWHERE d <- option MaybeDeclarations_Nothing (try $ do cds <- cdecls return (MaybeDeclarations_Just cds)) return d) return $ \r -> Declaration_Class r ct st ds <|> -- Declaration_Instance (Range) (ContextItems) (Name) (Types) (MaybeDeclarations) do lexINSTANCE ct <- option [] (try $ do {c <- scontext; lexDARROW ; return c} ) n <- tycls ts <- iType ds <- option MaybeDeclarations_Nothing (try $ do lexWHERE d <- idecls return (MaybeDeclarations_Just d)) return $ \r -> Declaration_Instance r ct n [ts] ds <|> infixdecl ) <|> addRange ( do lexHOLE jb <- optionMaybe normalRhs case jb of Just b -> return $ \r -> Declaration_PatternBinding r (Pattern_Hole r (-1)) b Nothing -> return $ \r -> Declaration_Hole r (-1) ) <|> decl <?> Texts.parserDeclaration derivings :: HParser [Name] derivings = do lexDERIVING ( do cls <- tycls return [cls] ) <|> ( do lexLPAREN clss <- tycls `sepBy` lexCOMMA lexRPAREN return clss ) simpleType :: HParser SimpleType simpleType = addRange ( do c <- tycon vs <- many tyvar return $ \r -> SimpleType_SimpleType r c vs ) {- infixdecl -> fixity [digit] ops (fixity declaration) fixity -> "infixl" | "infixr" | "infix" ops -> op1 "," ... "," opn (n>=1) -} infixdecl :: HParser (Range -> Declaration) infixdecl = do f <- fixity p <- fmap fromInteger (option 9 (fmap read lexInt)) :: HParser Int when (p < 0 || p > 9) (fail Texts.parserSingleDigitPriority) os <- ops return $ \r -> Declaration_Fixity r f (MaybeInt_Just p) os ops :: HParser Names ops = commas1 op fixity :: HParser Fixity fixity = addRange $ do lexINFIXL return $ \r -> Fixity_Infixl r <|> do lexINFIXR return $ \r -> Fixity_Infixr r <|> do lexINFIX return $ \r -> Fixity_Infix r {- constrs -> constr1 "|" ... "|" constrn (n>=1) -} constrs :: HParser Constructors constrs = constr `sepBy1` lexBAR {- constr -> btype conop btype (infix conop) | con atype1 ... atypek (arity con = k, k>=0) -} constr :: HParser Constructor constr = addRange $ do (t1, n) <- try $ do t1 <- annotatedType btype n <- conop return (t1, n) t2 <- annotatedType btype return (\r -> Constructor_Infix r t1 n t2) <|> do n <- con ts <- many (annotatedType atype) return (\r -> Constructor_Constructor r n ts) {- Simplified import: impdecl -> "import" modid impspec? impspec -> "hiding" "(" import "," ... ")" import -> var -} impdecl :: HParser ImportDeclaration impdecl = addRange ( do lexIMPORT let q = False m <- modid let a = MaybeName_Nothing i <- option MaybeImportSpecification_Nothing $ do{ is <- impspec ; return (MaybeImportSpecification_Just is) } return $ \r -> ImportDeclaration_Import r q m a i ) <?> Texts.parserImportDeclaration impspec :: HParser ImportSpecification impspec = addRange $ do h <- do { lexHIDING; return True } is <- parens (commas import_) return $ \r -> ImportSpecification_Import r h is import_ :: HParser Import import_ = addRange $ do n <- var return $ \r -> Import_Variable r n {- cdecls -> " {" decl1 ";" .... ";" decln "}" (n>=0) -} {- cdecl -> vars "::" type (type signature) | (funlhs | var) rhs -} cdecls :: HParser Declarations cdecls = do ds <- withLayout cdecl return (CollectFunctionBindings.decls ds) cdecl :: HParser Declaration cdecl = addRange ( try (do nr <- withRange var cdecl1 nr) <|> do l <- funlhs b <- normalRhs return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r l b] ) <?> Texts.parserDeclaration cdecl1 :: (Name, Range) -> HParser (Range -> Declaration) cdecl1 (n, _) = do lexCOMMA ns <- vars lexCOLCOL t <- contextAndType return $ \r -> Declaration_TypeSignature r (n:ns) t <|> do lexCOLCOL t <- contextAndType return $ \r -> Declaration_TypeSignature r [n] t <|> do b <- normalRhs return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r (LeftHandSide_Function r n []) b] {- idecl -> (funlhs | var) rhs | (empty) -} idecls :: HParser Declarations idecls = do ds <- withLayout idecl return ds -- (CollectFunctionBindings.decls ds) idecl :: HParser Declaration idecl = addRange ( try (do (n, _) <- try (withRange var) b <- normalRhs return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r (LeftHandSide_Function r n []) b]) <|> do l <- funlhs b <- normalRhs return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r l b] ) <?> Texts.parserDeclaration {- decls -> "{" decl1 ";" ... ";" decln "}" (n>=0) -} decls :: HParser Declarations decls = do ds <- withLayout decl return (CollectFunctionBindings.decls ds) {- decl -> vars "::" type (type signature) | ( funlhs | pat10 ) rhs vars -> var1 "," ..."," varn (n>=1) funlhs -> var apat* | pat10 varop pat10 | "(" funlhs ")" apat * Rewrite to reduce backtracking: decl -> [[ var ]] decl1 | [[ pat10 ]] decl2 | funlhs rhs decl1 -> "," vars "::" type | "::" type | varop pat10 rhs | "@" apat decl2 | apat* rhs decl2 -> varop pat10 rhs | rhs funlhs -> [[ var ]] funlhs1 | [[ pat10 ]] varop pat10 | "(" funlhs ")" apat* funlhs1 -> varop pat10 | apat* -} decl :: HParser Declaration decl = addRange ( do fb <- lexCaseFeedback return $ \r -> Declaration_FunctionBindings r [FunctionBinding_Feedback r fb $ FunctionBinding_Hole r 0] <|> do lexHOLE jb <- optionMaybe normalRhs case jb of Just b -> return $ \r -> Declaration_PatternBinding r (Pattern_Hole r (-1)) b Nothing -> return $ \r -> Declaration_Hole r (-1) <|> do nr <- try (withRange var) decl1 nr <|> do pr <- try (withRange pat10) decl2 pr <|> -- do -- lexHOLE -- return $ \r -> Declaration_Hole r (-1) do l <- funlhs b <- normalRhs return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r l b] ) <?> Texts.parserDeclaration decl1 :: (Name, Range) -> HParser (Range -> Declaration) decl1 (n, nr) = do lexCOMMA ns <- vars lexCOLCOL t <- contextAndType return $ \r -> Declaration_TypeSignature r (n:ns) t <|> do lexCOLCOL t <- contextAndType return $ \r -> Declaration_TypeSignature r [n] t <|> do o <- varop (p, pr) <- withRange pat10 b <- normalRhs let lr = mergeRanges nr pr return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r (LeftHandSide_Infix lr (Pattern_Variable nr n) o p) b] <|> do lexAT (p, pr) <- withRange apat let completeRange = mergeRanges nr pr asPat = Pattern_As completeRange n p decl2 (asPat, completeRange) <|> do (ps, rs) <- fmap unzip (many (withRange apat)) let lr = if null rs then nr else mergeRanges nr (last rs) b <- normalRhs return $ \r -> if null rs then Declaration_PatternBinding r (Pattern_Variable nr n) b else Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r (LeftHandSide_Function lr n ps) b] decl2 :: (Pattern, Range) -> HParser (Range -> Declaration) decl2 (p1, p1r) = do o <- varop (p2, p2r) <- withRange pat10 b <- normalRhs let lr = mergeRanges p1r p2r return $ \r -> Declaration_FunctionBindings r [FunctionBinding_FunctionBinding r (LeftHandSide_Infix lr p1 o p2) b] <|> do b <- normalRhs return $ \r -> Declaration_PatternBinding r p1 b funlhs :: HParser LeftHandSide funlhs = addRange $ do nr <- try (withRange var) funlhs1 nr <|> do p1 <- try pat10 o <- varop p2 <- pat10 return $ \r -> LeftHandSide_Infix r p1 o p2 <|> do l <- parens funlhs ps <- many apat return $ \r -> LeftHandSide_Parenthesized r l ps funlhs1 :: (Name, Range) -> HParser (Range -> LeftHandSide) funlhs1 (n, nr) = do o <- varop p <- pat10 return $ \r -> LeftHandSide_Infix r (Pattern_Variable nr n) o p <|> do ps <- many apat return $ \r -> LeftHandSide_Function r n ps vars :: HParser [Name] vars = commas1 var {- rhs -> "=" exp rhs1 | gdexp+ rhs1 rhs1 -> ( "where" decls )? gdexp -> "|" exp0 "=" exp -} normalRhs, caseRhs :: HParser RightHandSide normalRhs = rhs lexASG caseRhs = rhs lexRARROW -- The string is "->" for a case rhs and "=" for a normal rhs rhs :: HParser () -> HParser RightHandSide rhs equals = addRange $ do equals e <- exp_ mds <- option MaybeDeclarations_Nothing rhs1 return $ \r -> RightHandSide_Expression r e mds <|> do gs <- many1 (gdexp equals) mds <- option MaybeDeclarations_Nothing rhs1 return $ \r -> RightHandSide_Guarded r gs mds rhs1 :: HParser MaybeDeclarations rhs1 = do lexWHERE ds <- decls return (MaybeDeclarations_Just ds) gdexp :: HParser () -> HParser GuardedExpression gdexp equals = addRange $ do lexBAR g <- exp0 equals e <- exp_ return $ \r -> GuardedExpression_GuardedExpression r g e -- exp_ = addRange ( -- do -- feedback <- option Nothing (try $ lexFeedback >>= return . Just) -- e <- expOrg_ -- return (maybe (const e) (\s -> \r -> Expression_Feedback r s e) feedback) -- ) <?> Texts.parserExpression {- exp -> exp0 "::" type (expression type signature) | exp0 -} exp_ :: ParsecT [Token] SourcePos Identity Expression exp_ = addRange ( do e <- exp0 option (\_ -> e) $ do lexCOLCOL t <- contextAndType return $ \r -> Expression_Typed r e t ) <?> Texts.parserExpression contextAndType :: HParser Type contextAndType = addRange $ do mc <- option Nothing (try $ do { c <- scontext; lexDARROW; return (Just c) }) t <- type_ case mc of Nothing -> return $ \_ -> t Just c -> return $ \r -> Type_Qualified r c t {- expi -> expi+1 [op(n,i) expi+1] | lexpi | rexpi lexpi -> (lexpi | expi+1) op(l,i) expi+1 lexp6 -> - exp7 rexpi -> expi+1 op(r,i) (rexpi | expi+1) Simplified, post-processing exp0 -> ( "-" )? exp10 ( op ( "-" )? exp10 )* See noRange in ParseCommon for an explanation of the parsing of infix expressions. -} exp0 :: HParser Expression exp0 = addRange ( do u <- maybeUnaryMinus es <- exprChain return $ \_ -> Expression_List noRange (u ++ es) ) <?> Texts.parserExpression exprChain :: HParser [Expression] exprChain = do e <- exp10 es <- fmap concat $ many $ do o <- operatorAsExpression False u <- maybeUnaryMinus e' <- exp10 return ([o] ++ u ++ [e']) return (e:es) maybeUnaryMinus :: ParsecT [Token] SourcePos Identity [Expression] maybeUnaryMinus = option [] (fmap (:[]) unaryMinus) <?> Texts.parserExpression unaryMinus :: HParser Expression unaryMinus = do (_, r) <- withRange lexMINDOT return (Expression_Variable noRange (setNameRange floatUnaryMinusName r)) <|> do (_, r) <- withRange lexMIN return (Expression_Variable noRange (setNameRange intUnaryMinusName r)) {- exp10 -> "\" apat1 ... apatn "->" exp (lambda abstraction, n>=1) | "let" decls "in" exp (let expression) | "if" exp "then" exp "else" exp (conditional) | "case" exp "of" alts (case expression) | "do" stmts (do expression) | fexp -} exp10 :: HParser Expression exp10 = addRange ( do lexBSLASH ps <- many1 apat lexRARROW e <- exp_ return $ \r -> Expression_Lambda r ps e <|> (do lexLET ds <- decls lexIN e <- exp_ return $ \r -> Expression_Let r ds e) <|> do lexIF e1 <- exp_ lexTHEN e2 <- exp_ lexELSE e3 <- exp_ return $ \r -> Expression_If r e1 e2 e3 <|> do lexCASE e <- exp_ lexOF as <- alts return $ \r -> Expression_Case r e as <|> do lexDO ss <- stmts return $ \r -> Expression_Do r ss ) <|> fexp <?> Texts.parserExpression {- fexp -> aexp+ -} fexp :: HParser Expression fexp = addRange $ do (e:es) <- many1 aexp if null es then return $ \_ -> e else return $ \r -> Expression_NormalApplication r e es {- aexp -> var (variable) | con | literal | "[" "]" | "[" exp1 "," ... "," expk "]" | "[" exp1 ( "," exp2 )? ".." exp3? "]" | "[" exp "|" qual1 "," ... "," qualn "]" | () | (op fexp) (left section) | (fexp op) (right section) | ( exp ) (parenthesized expression) | ( exp1 , ... , expk ) (tuple, k>=2) Last cases parsed as: "(" "-" exprChain ( "," exp_ )* ")" | "(" op fexp ")" | "(" fexp op ")" | "(" ( exp_ )<sepBy ","> ")" -} operatorAsExpression :: Bool -> HParser Expression operatorAsExpression storeRange = (do (o, r) <- withRange ( fmap Left varsym <|> fmap Right consym <|> lexBACKQUOTEs (fmap Left varid <|> fmap Right conid)) let range = if storeRange then r else noRange return (case o of Left v -> Expression_Variable range v Right c -> Expression_Constructor range c )) <?> Texts.parserOperator aexp :: HParser Expression aexp = addRange ( do lexLPAREN ( -- dit haakje is nodig (snap niet waarom). Arjan try (do -- de try vanwege (-) DEZE PARSER MOET OPNIEUW GESCHREVEN WORDEN !!! ue <- do u <- unaryMinus es <- exprChain return (Expression_List noRange (u:es)) es <- many (do { lexCOMMA; exp_ }) lexRPAREN return $ if null es then \r -> Expression_Parenthesized r ue else \r -> Expression_Tuple r (ue:es)) <|> do -- operator followed by optional expression -- either full section (if there is no expression) or -- a left section (if there is) opExpr <- operatorAsExpression True me <- option Nothing (fmap Just fexp) lexRPAREN return $ \r -> Expression_InfixApplication r MaybeExpression_Nothing opExpr (case me of Nothing -> MaybeExpression_Nothing Just e -> MaybeExpression_Just e) <|> try (do -- right section, expression followed by operator -- or a parenthesized expression (if no operator is found) e <- fexp mo <- option Nothing (fmap Just (operatorAsExpression True)) lexRPAREN return $ \r -> case mo of Nothing -> Expression_Parenthesized r e Just opExpr -> Expression_InfixApplication r (MaybeExpression_Just e) opExpr MaybeExpression_Nothing ) <|> do -- unit "()", expression between parenthesis or a tuple es <- commas exp_ lexRPAREN return $ \r -> case es of [] -> Expression_Constructor r (Name_Special r [] "()") -- !!!Name [e] -> Expression_Parenthesized r e _ -> Expression_Tuple r es ) <|> do n <- varid return $ \r -> Expression_Variable r n <|> do n <- conid return $ \r -> Expression_Constructor r n <|> do lexHOLE return $ \r -> Expression_Hole r (-1) <|> do feedback <- lexFeedback e <- aexp return $ \r -> Expression_Feedback r feedback e <|> do lexeme LexMustUse e <- aexp return $ \r -> Expression_MustUse r e <|> do l <- literal return $ \r -> Expression_Literal r l <|> do lexLBRACKET aexp1 ) <?> Texts.parserExpression {- Last four cases, rewritten to eliminate backtracking aexp -> ... | "[" aexp1 aexp1 -> "]" | exp aexp2 "]" aexp2 -> "|" qual1 "," ... "," qualn | ".." exp? | "," exp aexp3 | (empty) aexp3 -> ".." exp? | ( "," exp )* -} aexp1 :: HParser (Range -> Expression) aexp1 = do lexRBRACKET return $ \r -> Expression_Constructor r (Name_Special r [] "[]") -- !!!Name <|> do e1 <- exp_ e2 <- aexp2 e1 lexRBRACKET return e2 aexp2 :: Expression -> HParser (Range -> Expression) aexp2 e1 = do lexBAR qs <- commas1 qual return $ \r -> Expression_Comprehension r e1 qs <|> do lexDOTDOT option (\r -> Expression_Enum r e1 MaybeExpression_Nothing MaybeExpression_Nothing) $ do e2 <- exp_ return $ \r -> Expression_Enum r e1 MaybeExpression_Nothing (MaybeExpression_Just e2) <|> do lexCOMMA e2 <- exp_ aexp3 e1 e2 <|> return (\r -> Expression_List r [e1]) aexp3 :: Expression -> Expression -> HParser (Range -> Expression) aexp3 e1 e2 = do lexDOTDOT option (\r -> Expression_Enum r e1 (MaybeExpression_Just e2) MaybeExpression_Nothing) $ do e3 <- exp_ return $ \r -> Expression_Enum r e1 (MaybeExpression_Just e2) (MaybeExpression_Just e3) <|> do es <- many (do { lexCOMMA; exp_ }) return $ \r -> Expression_List r (e1:e2:es) {- stmts -> "{" stmt1 ";" ... ";" stmtn "}" (n>=0) -} stmts :: HParser Statements stmts = withLayout stmt {- stmt -> "let" decls | pat "<-" exp | exp -} stmt :: HParser Statement stmt = addRange $ do lexLET ds <- decls option (\r -> Statement_Let r ds) $ do lexIN e <- exp_ return (\r -> Statement_Expression r (Expression_Let r ds e)) <|> do p <- try $ do p <- pat lexLARROW return p e <- exp_ return $ \r -> Statement_Generator r p e <|> do e <- exp_ return $ \r -> Statement_Expression r e {- alts -> "{" alt1 ";" ... ";" altn "}" (n>=0) -} alts :: HParser Alternatives alts = do as <- withLayout alt return $ CollectFunctionBindings.mergeCaseFeedback as {- alt -> pat rhs -} alt :: HParser Alternative alt = addRange $ do fb <- lexCaseFeedback return $ \r -> Alternative_Feedback r fb $ Alternative_Hole r (-1) <|> do lexHOLE return $ \r -> Alternative_Hole r (-1) <|> do p <- pat b <- caseRhs return $ \r -> Alternative_Alternative r p b {- qual -> "let" decls (local declaration) | pat "<-" exp (generator) | exp (guard) -} qual :: HParser Qualifier qual = addRange $ do lexLET ds <- decls option (\r -> Qualifier_Let r ds) $ do lexIN e <- exp_ return (\r -> Qualifier_Guard r (Expression_Let r ds e)) <|> do p <- try $ do p <- pat lexLARROW return p e <- exp_ return $ \r -> Qualifier_Generator r p e <|> do e <- exp_ return $ \r -> Qualifier_Guard r e {- pat -> pat0 pati -> pati+1 [conop(n,i) pati+1] | lpati | rpati lpati -> (lpati | pati+1) conop(l,i) pati+1 lpat6 -> - (integer | float) (negative literal) rpati -> pati+1 conop(r,i) (rpati | pati+1) See noRange in ParseCommon for an explanation of the parsing of infix expressions. -} pat :: HParser Pattern pat = addRange $ do u <- unaryMinusPat ps <- fmap concat $ many $ do o <- do { n <- conop; return (Pattern_Variable noRange n) } u' <- unaryMinusPat return (o : u') return $ \_ -> Pattern_List noRange (u ++ ps) unaryMinusPat :: HParser [Pattern] unaryMinusPat = do (n, mr) <- withRange (do { lexMINDOT; return floatUnaryMinusName } <|> do { lexMIN; return intUnaryMinusName } ) (l, lr) <- withRange numericLiteral return [ Pattern_Variable noRange (setNameRange n mr) , Pattern_Literal lr l ] <|> do p <- pat10 return [p] {- pat10 -> con apat* | apat -} pat10 :: HParser Pattern pat10 = addRange ( do n <- try con ps <- many apat return $ \r -> Pattern_Constructor r n ps ) <|> apat <?> Texts.parserPattern {- apat -> var ( "@" apat )? | "(" ")" | "(" pat ")" (parenthesized pattern) | "(" pat1 "," ... "," patk ")" (tuple pattern, k>=2) | "[" "]" | "[" pat1 "," ... "," patk "]" (list pattern, k>=1) | "_" (wildcard) | con (arity con = 0) | literal | "~" apat (irrefutable pattern) -} apat :: HParser Pattern apat = addRange ( do v <- try var -- because of parentheses option (\r -> Pattern_Variable r v) $ do lexAT p <- apat return $ \r -> Pattern_As r v p <|> do ps <- parens (commas pat) return $ \r -> case ps of [] -> Pattern_Constructor r (Name_Special r [] "()") [] -- !!!Name [p] -> Pattern_Parenthesized r p _ -> Pattern_Tuple r ps <|> do ps <- brackets (commas pat) return $ \r -> case ps of [] -> Pattern_Constructor r (Name_Special r [] "[]") [] -- !!!Name _ -> Pattern_List r ps <|> do lexUNDERSCORE return $ \r -> Pattern_Wildcard r <|> do n <- con return $ \r -> Pattern_Constructor r n [] <|> do l <- literal return $ \r -> Pattern_Literal r l <|> do lexTILDE p <- apat return $ \r -> Pattern_Irrefutable r p ) <|> phole <?> Texts.parserPattern phole :: HParser Pattern phole = addRange ( do lexHOLE return $ \r -> Pattern_Hole r (-1) ) {- scontext -> class | "(" class1 "," ... "," classn ")" (n>=0) simpleclass -> tycls tyvar (other case in Haskell report at 'class' is not supported in Helium because we do not have type variable application) -} scontext :: HParser ContextItems scontext = do { c <- simpleclass; return [c] } <|> parens (commas simpleclass) simpleclass :: HParser ContextItem simpleclass = addRange (do c <- tycon (v, vr) <- withRange tyvar return $ \r -> ContextItem_ContextItem r c [Type_Variable vr v] ) {- type -> btype ( "->" type )? -} type_ :: HParser Type type_ = addRange ( do left <- btype option (\_ -> left) $ do (_, rangeArrow) <- withRange lexRARROW right <- type_ return (\r -> Type_Application r False (Type_Constructor rangeArrow (Name_Special rangeArrow [] "->")) [left, right]) -- !!!Name ) <?> Texts.parserType {- btype -> atype+ -} btype :: HParser Type btype = addRange ( do ts <- many1 atype return $ \r -> case ts of [t] -> t (t:ts') -> Type_Application r True t ts' [] -> error "Pattern match failure in Parser.Parser.btype" ) <?> Texts.parserType {- iType -> tycon | "(" ")" (unit type) | "(" type1 "," ... "," typek ")" (tuple type, k>=2) | "(" type ")" (parenthesized constructor) | "[" type "]" (list type) -} iType :: HParser Type iType = addRange ( do c <- tycon return (\r -> Type_Constructor r c) <|> do ts <- parens (commas type_) return (\r -> case ts of [] -> Type_Constructor r (Name_Special r [] "()") -- !!!Name [t] -> Type_Parenthesized r t _ -> let n = Name_Special r [] -- !!!Name ( "(" ++ replicate (length ts - 1) ',' ++ ")" ) in Type_Application r False (Type_Constructor r n) ts ) <|> do t <- brackets type_ return $ \r -> let n = Name_Special r [] "[]" -- !!!Name in Type_Application r False (Type_Constructor r n) [t] ) <?> Texts.parserType {- atype -> tycon | tyvar | "(" ")" (unit type) | "(" type1 "," ... "," typek ")" (tuple type, k>=2) | "(" type ")" (parenthesized constructor) | "[" type "]" (list type) -} atype :: HParser Type atype = addRange ( do c <- tycon return (\r -> Type_Constructor r c) <|> do c <- tyvar return (\r -> Type_Variable r c) <|> do ts <- parens (commas type_) return (\r -> case ts of [] -> Type_Constructor r (Name_Special r [] "()") -- !!!Name [t] -> Type_Parenthesized r t _ -> let n = Name_Special r [] -- !!!Name ( "(" ++ replicate (length ts - 1) ',' ++ ")" ) in Type_Application r False (Type_Constructor r n) ts ) <|> do t <- brackets type_ return $ \r -> let n = Name_Special r [] "[]" -- !!!Name in Type_Application r False (Type_Constructor r n) [t] ) <?> Texts.parserType annotatedType :: HParser Type -> HParser AnnotatedType annotatedType p = addRange $ do t <- p return (\r -> AnnotatedType_AnnotatedType r False t) literal :: ParsecT [Token] SourcePos Identity Literal literal = addRange ( do i <- lexInt return $ \r -> Literal_Int r i <|> do d <- lexDouble return $ \r -> Literal_Float r d <|> do c <- lexChar return $ \r -> Literal_Char r c <|> do s <- lexString return $ \r -> Literal_String r s ) <?> Texts.parserLiteral numericLiteral :: ParsecT [Token] SourcePos Identity Literal numericLiteral = addRange ( do i <- lexInt return $ \r -> Literal_Int r i <|> do d <- lexDouble return $ \r -> Literal_Float r d ) <?> Texts.parserNumericLiteral
roberth/uu-helium
src/Helium/Parser/Parser.hs
gpl-3.0
34,976
0
32
13,509
8,285
4,021
4,264
885
6
{-# 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.YouTube.Videos.Delete -- 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) -- -- Deletes a resource. -- -- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.videos.delete@. module Network.Google.Resource.YouTube.Videos.Delete ( -- * REST Resource VideosDeleteResource -- * Creating a Request , videosDelete , VideosDelete -- * Request Lenses , vdXgafv , vdUploadProtocol , vdAccessToken , vdUploadType , vdOnBehalfOfContentOwner , vdId , vdCallback ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.videos.delete@ method which the -- 'VideosDelete' request conforms to. type VideosDeleteResource = "youtube" :> "v3" :> "videos" :> QueryParam "id" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "onBehalfOfContentOwner" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes a resource. -- -- /See:/ 'videosDelete' smart constructor. data VideosDelete = VideosDelete' { _vdXgafv :: !(Maybe Xgafv) , _vdUploadProtocol :: !(Maybe Text) , _vdAccessToken :: !(Maybe Text) , _vdUploadType :: !(Maybe Text) , _vdOnBehalfOfContentOwner :: !(Maybe Text) , _vdId :: !Text , _vdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'VideosDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vdXgafv' -- -- * 'vdUploadProtocol' -- -- * 'vdAccessToken' -- -- * 'vdUploadType' -- -- * 'vdOnBehalfOfContentOwner' -- -- * 'vdId' -- -- * 'vdCallback' videosDelete :: Text -- ^ 'vdId' -> VideosDelete videosDelete pVdId_ = VideosDelete' { _vdXgafv = Nothing , _vdUploadProtocol = Nothing , _vdAccessToken = Nothing , _vdUploadType = Nothing , _vdOnBehalfOfContentOwner = Nothing , _vdId = pVdId_ , _vdCallback = Nothing } -- | V1 error format. vdXgafv :: Lens' VideosDelete (Maybe Xgafv) vdXgafv = lens _vdXgafv (\ s a -> s{_vdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). vdUploadProtocol :: Lens' VideosDelete (Maybe Text) vdUploadProtocol = lens _vdUploadProtocol (\ s a -> s{_vdUploadProtocol = a}) -- | OAuth access token. vdAccessToken :: Lens' VideosDelete (Maybe Text) vdAccessToken = lens _vdAccessToken (\ s a -> s{_vdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). vdUploadType :: Lens' VideosDelete (Maybe Text) vdUploadType = lens _vdUploadType (\ s a -> s{_vdUploadType = a}) -- | *Note:* This parameter is intended exclusively for YouTube content -- partners. The *onBehalfOfContentOwner* parameter indicates that the -- request\'s authorization credentials identify a YouTube CMS user who is -- acting on behalf of the content owner specified in the parameter value. -- This parameter is intended for YouTube content partners that own and -- manage many different YouTube channels. It allows content owners to -- authenticate once and get access to all their video and channel data, -- without having to provide authentication credentials for each individual -- channel. The actual CMS account that the user authenticates with must be -- linked to the specified YouTube content owner. vdOnBehalfOfContentOwner :: Lens' VideosDelete (Maybe Text) vdOnBehalfOfContentOwner = lens _vdOnBehalfOfContentOwner (\ s a -> s{_vdOnBehalfOfContentOwner = a}) vdId :: Lens' VideosDelete Text vdId = lens _vdId (\ s a -> s{_vdId = a}) -- | JSONP vdCallback :: Lens' VideosDelete (Maybe Text) vdCallback = lens _vdCallback (\ s a -> s{_vdCallback = a}) instance GoogleRequest VideosDelete where type Rs VideosDelete = () type Scopes VideosDelete = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner"] requestClient VideosDelete'{..} = go (Just _vdId) _vdXgafv _vdUploadProtocol _vdAccessToken _vdUploadType _vdOnBehalfOfContentOwner _vdCallback (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy VideosDeleteResource) mempty
brendanhay/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/Videos/Delete.hs
mpl-2.0
5,419
0
18
1,271
806
471
335
113
1
module AlecSequences.A280172 (a280172, a280172_list) where import Tables.A273823 (a273823_row) import Tables.A273824 (a273824_row) import Data.List ((\\), sort, nub, genericIndex) a280172 :: Integer -> Integer a280172 n = genericIndex a280172_list (n - 1) a280172_list :: [Integer] a280172_list = map f [1..] where f n = head $ [1..] \\ map a280172 (rookIndices n) -- Indices of the array that are above or to the left of n. rookIndices :: Integral a => a -> [a] rookIndices n = nub $ sort $ a273824_row n ++ a273823_row n
peterokagey/haskellOEIS
src/AlecSequences/A280172.hs
apache-2.0
528
0
10
89
183
101
82
11
1
{-# LANGUAGE PatternSynonyms #-} {- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module CodeWorld.Event where import CodeWorld.Picture (Point) import Data.Text (Text) -- | An event initiated by the user. -- -- Values of this type represent events that the user triggers when -- using an interactive program. -- -- Key events describe the key as 'Text'. Most keys are represented -- by a single character text string, with the capital letter or other -- symbol from the key. Keys that don't correspond to a single -- character use longer names from the following list. Keep in mind -- that not all of these keys appear on all keyboards. -- -- * Up, Down, Left, and Right for the cursor keys. -- * F1, F2, etc. for function keys. -- * Backspace -- * Tab -- * Enter -- * Shift -- * Ctrl -- * Alt -- * Esc -- * PageUp -- * PageDown -- * End -- * Home -- * Insert -- * Delete -- * CapsLock -- * NumLock -- * ScrollLock -- * PrintScreen -- * Break -- * Separator -- * Cancel -- * Help data Event = KeyPress !Text | KeyRelease !Text | PointerPress !Point | PointerRelease !Point | PointerMovement !Point | TextEntry !Text | TimePassing !Double deriving (Eq, Show, Read)
alphalambda/codeworld
codeworld-api/src/CodeWorld/Event.hs
apache-2.0
1,837
0
7
437
123
83
40
27
0
-- http://www.codewars.com/kata/550756a881b8bdba99000348 module FunctionEvaluator where import qualified Data.Map as M evaluateFunction :: Ord a => (a -> Either b ([a], [b] -> b)) -> a -> b evaluateFunction f n = (M.!) (eval M.empty n) n where eval cache m = case M.lookup m cache of Just _ -> cache Nothing -> case f m of Left v -> M.insert m v cache Right (ks, reducer) -> M.insert m v cache' where cache' = foldl eval cache ks v = reducer $ map ((M.!) cache') ks
Bodigrim/katas
src/haskell/B-Recurrence-relations.hs
bsd-2-clause
522
0
19
142
215
112
103
12
3
-- | Data.Elf is a module for parsing a ByteString of an ELF file into an Elf record. module Data.Elf (parseElf , Elf(..) , ElfSection(..) , ElfSectionType(..) , ElfSectionFlags(..) , ElfSegment(..) , ElfSegmentType(..) , ElfSegmentFlag(..) , ElfClass(..) , ElfData(..) , ElfOSABI(..) , ElfType(..) , ElfMachine(..)) where import Data.Binary import Data.Binary.Get import Data.Bits import Data.Word import Numeric import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Lazy as L data Elf = Elf { elfClass :: ElfClass -- ^ Identifies the class of the object file. , elfData :: ElfData -- ^ Identifies the data encoding of the object file. , elfVersion :: Int -- ^ Identifies the version of the object file format. , elfOSABI :: ElfOSABI -- ^ Identifies the operating system and ABI for which the object is prepared. , elfABIVersion :: Int -- ^ Identifies the ABI version for which the object is prepared. , elfType :: ElfType -- ^ Identifies the object file type. , elfMachine :: ElfMachine -- ^ Identifies the target architecture. , elfEntry :: Word64 -- ^ Virtual address of the program entry point. 0 for non-executable Elfs. , elfSections :: [ElfSection] -- ^ List of sections in the file. , elfSegments :: [ElfSegment] -- ^ List of segments in the file. } deriving (Eq, Show) data ElfSection = ElfSection { elfSectionName :: String -- ^ Identifies the name of the section. , elfSectionType :: ElfSectionType -- ^ Identifies the type of the section. , elfSectionFlags :: [ElfSectionFlags] -- ^ Identifies the attributes of the section. , elfSectionAddr :: Word64 -- ^ The virtual address of the beginning of the section in memory. 0 for sections that are not loaded into target memory. , elfSectionSize :: Word64 -- ^ The size of the section. Except for SHT_NOBITS sections, this is the size of elfSectionData. , elfSectionLink :: Word32 -- ^ Contains a section index of an associated section, depending on section type. , elfSectionInfo :: Word32 -- ^ Contains extra information for the index, depending on type. , elfSectionAddrAlign :: Word64 -- ^ Contains the required alignment of the section. Must be a power of two. , elfSectionEntSize :: Word64 -- ^ Size of entries if section has a table. , elfSectionData :: B.ByteString -- ^ The raw data for the section. } deriving (Eq, Show) getElfMagic = do ei_magic <- liftM (map B.w2c) $ sequence [getWord8, getWord8, getWord8, getWord8] if ei_magic /= "\DELELF" then fail "Invalid magic number for ELF" else return ei_magic getElfVersion = do ei_version <- getWord8 if ei_version /= 1 then fail "Invalid version number for ELF" else return ei_version data ElfSectionType = SHT_NULL -- ^ Identifies an empty section header. | SHT_PROGBITS -- ^ Contains information defined by the program | SHT_SYMTAB -- ^ Contains a linker symbol table | SHT_STRTAB -- ^ Contains a string table | SHT_RELA -- ^ Contains "Rela" type relocation entries | SHT_HASH -- ^ Contains a symbol hash table | SHT_DYNAMIC -- ^ Contains dynamic linking tables | SHT_NOTE -- ^ Contains note information | SHT_NOBITS -- ^ Contains uninitialized space; does not occupy any space in the file | SHT_REL -- ^ Contains "Rel" type relocation entries | SHT_SHLIB -- ^ Reserved | SHT_DYNSYM -- ^ Contains a dynamic loader symbol table | SHT_EXT Word32 -- ^ Processor- or environment-specific type deriving (Eq, Show) getElfSectionType er = liftM getElfSectionType_ $ getWord32 er where getElfSectionType_ 0 = SHT_NULL getElfSectionType_ 1 = SHT_PROGBITS getElfSectionType_ 2 = SHT_SYMTAB getElfSectionType_ 3 = SHT_STRTAB getElfSectionType_ 4 = SHT_RELA getElfSectionType_ 5 = SHT_HASH getElfSectionType_ 6 = SHT_DYNAMIC getElfSectionType_ 7 = SHT_NOTE getElfSectionType_ 8 = SHT_NOBITS getElfSectionType_ 9 = SHT_REL getElfSectionType_ 10 = SHT_SHLIB getElfSectionType_ 11 = SHT_DYNSYM getElfSectionType_ n = SHT_EXT n data ElfSectionFlags = SHF_WRITE -- ^ Section contains writable data | SHF_ALLOC -- ^ Section is allocated in memory image of program | SHF_EXECINSTR -- ^ Section contains executable instructions | SHF_EXT Int -- ^ Processor- or environment-specific flag deriving (Eq, Show) getElfSectionFlags 0 word = [] getElfSectionFlags 1 word | testBit word 0 = SHF_WRITE : getElfSectionFlags 0 word getElfSectionFlags 2 word | testBit word 1 = SHF_ALLOC : getElfSectionFlags 1 word getElfSectionFlags 3 word | testBit word 2 = SHF_EXECINSTR : getElfSectionFlags 2 word getElfSectionFlags n word | testBit word (n-1) = SHF_EXT (n-1) : getElfSectionFlags (n-1) word getElfSectionFlags n word = getElfSectionFlags (n-1) word getElfSectionFlags32 = liftM (getElfSectionFlags 32) . getWord32 getElfSectionFlags64 = liftM (getElfSectionFlags 64) . getWord64 data ElfClass = ELFCLASS32 -- ^ 32-bit ELF format | ELFCLASS64 -- ^ 64-bit ELF format deriving (Eq, Show) getElfClass = getWord8 >>= getElfClass_ where getElfClass_ 1 = return ELFCLASS32 getElfClass_ 2 = return ELFCLASS64 getElfClass_ _ = fail "Invalid ELF class" data ElfData = ELFDATA2LSB -- ^ Little-endian ELF format | ELFDATA2MSB -- ^ Big-endian ELF format deriving (Eq, Show) getElfData = getWord8 >>= getElfData_ where getElfData_ 1 = return ELFDATA2LSB getElfData_ 2 = return ELFDATA2MSB getElfData_ _ = fail "Invalid ELF data" data ElfOSABI = ELFOSABI_SYSV -- ^ No extensions or unspecified | ELFOSABI_HPUX -- ^ Hewlett-Packard HP-UX | ELFOSABI_NETBSD -- ^ NetBSD | ELFOSABI_LINUX -- ^ Linux | ELFOSABI_SOLARIS -- ^ Sun Solaris | ELFOSABI_AIX -- ^ AIX | ELFOSABI_IRIX -- ^ IRIX | ELFOSABI_FREEBSD -- ^ FreeBSD | ELFOSABI_TRU64 -- ^ Compaq TRU64 UNIX | ELFOSABI_MODESTO -- ^ Novell Modesto | ELFOSABI_OPENBSD -- ^ Open BSD | ELFOSABI_OPENVMS -- ^ Open VMS | ELFOSABI_NSK -- ^ Hewlett-Packard Non-Stop Kernel | ELFOSABI_AROS -- ^ Amiga Research OS | ELFOSABI_ARM -- ^ ARM | ELFOSABI_STANDALONE -- ^ Standalone (embedded) application | ELFOSABI_EXT Word8 -- ^ Other deriving (Eq, Show) getElfOsabi = liftM getElfOsabi_ getWord8 where getElfOsabi_ 0 = ELFOSABI_SYSV getElfOsabi_ 1 = ELFOSABI_HPUX getElfOsabi_ 2 = ELFOSABI_NETBSD getElfOsabi_ 3 = ELFOSABI_LINUX getElfOsabi_ 6 = ELFOSABI_SOLARIS getElfOsabi_ 7 = ELFOSABI_AIX getElfOsabi_ 8 = ELFOSABI_IRIX getElfOsabi_ 9 = ELFOSABI_FREEBSD getElfOsabi_ 10 = ELFOSABI_TRU64 getElfOsabi_ 11 = ELFOSABI_MODESTO getElfOsabi_ 12 = ELFOSABI_OPENBSD getElfOsabi_ 13 = ELFOSABI_OPENVMS getElfOsabi_ 14 = ELFOSABI_NSK getElfOsabi_ 15 = ELFOSABI_AROS getElfOsabi_ 97 = ELFOSABI_ARM getElfOsabi_ 255 = ELFOSABI_STANDALONE getElfOsabi_ n = ELFOSABI_EXT n data ElfType = ET_NONE -- ^ Unspecified type | ET_REL -- ^ Relocatable object file | ET_EXEC -- ^ Executable object file | ET_DYN -- ^ Shared object file | ET_CORE -- ^ Core dump object file | ET_EXT Word16 -- ^ Other deriving (Eq, Show) getElfType = liftM getElfType_ . getWord16 where getElfType_ 0 = ET_NONE getElfType_ 1 = ET_REL getElfType_ 2 = ET_EXEC getElfType_ 3 = ET_DYN getElfType_ 4 = ET_CORE getElfType_ n = ET_EXT n data ElfMachine = EM_NONE -- ^ No machine | EM_M32 -- ^ AT&T WE 32100 | EM_SPARC -- ^ SPARC | EM_386 -- ^ Intel 80386 | EM_68K -- ^ Motorola 68000 | EM_88K -- ^ Motorola 88000 | EM_486 -- ^ Intel i486 (DO NOT USE THIS ONE) | EM_860 -- ^ Intel 80860 | EM_MIPS -- ^ MIPS I Architecture | EM_S370 -- ^ IBM System/370 Processor | EM_MIPS_RS3_LE -- ^ MIPS RS3000 Little-endian | EM_SPARC64 -- ^ SPARC 64-bit | EM_PARISC -- ^ Hewlett-Packard PA-RISC | EM_VPP500 -- ^ Fujitsu VPP500 | EM_SPARC32PLUS -- ^ Enhanced instruction set SPARC | EM_960 -- ^ Intel 80960 | EM_PPC -- ^ PowerPC | EM_PPC64 -- ^ 64-bit PowerPC | EM_S390 -- ^ IBM System/390 Processor | EM_SPU -- ^ Cell SPU | EM_V800 -- ^ NEC V800 | EM_FR20 -- ^ Fujitsu FR20 | EM_RH32 -- ^ TRW RH-32 | EM_RCE -- ^ Motorola RCE | EM_ARM -- ^ Advanced RISC Machines ARM | EM_ALPHA -- ^ Digital Alpha | EM_SH -- ^ Hitachi SH | EM_SPARCV9 -- ^ SPARC Version 9 | EM_TRICORE -- ^ Siemens TriCore embedded processor | EM_ARC -- ^ Argonaut RISC Core, Argonaut Technologies Inc. | EM_H8_300 -- ^ Hitachi H8/300 | EM_H8_300H -- ^ Hitachi H8/300H | EM_H8S -- ^ Hitachi H8S | EM_H8_500 -- ^ Hitachi H8/500 | EM_IA_64 -- ^ Intel IA-64 processor architecture | EM_MIPS_X -- ^ Stanford MIPS-X | EM_COLDFIRE -- ^ Motorola ColdFire | EM_68HC12 -- ^ Motorola M68HC12 | EM_MMA -- ^ Fujitsu MMA Multimedia Accelerator | EM_PCP -- ^ Siemens PCP | EM_NCPU -- ^ Sony nCPU embedded RISC processor | EM_NDR1 -- ^ Denso NDR1 microprocessor | EM_STARCORE -- ^ Motorola Star*Core processor | EM_ME16 -- ^ Toyota ME16 processor | EM_ST100 -- ^ STMicroelectronics ST100 processor | EM_TINYJ -- ^ Advanced Logic Corp. TinyJ embedded processor family | EM_X86_64 -- ^ AMD x86-64 architecture | EM_PDSP -- ^ Sony DSP Processor | EM_FX66 -- ^ Siemens FX66 microcontroller | EM_ST9PLUS -- ^ STMicroelectronics ST9+ 8/16 bit microcontroller | EM_ST7 -- ^ STMicroelectronics ST7 8-bit microcontroller | EM_68HC16 -- ^ Motorola MC68HC16 Microcontroller | EM_68HC11 -- ^ Motorola MC68HC11 Microcontroller | EM_68HC08 -- ^ Motorola MC68HC08 Microcontroller | EM_68HC05 -- ^ Motorola MC68HC05 Microcontroller | EM_SVX -- ^ Silicon Graphics SVx | EM_ST19 -- ^ STMicroelectronics ST19 8-bit microcontroller | EM_VAX -- ^ Digital VAX | EM_CRIS -- ^ Axis Communications 32-bit embedded processor | EM_JAVELIN -- ^ Infineon Technologies 32-bit embedded processor | EM_FIREPATH -- ^ Element 14 64-bit DSP Processor | EM_ZSP -- ^ LSI Logic 16-bit DSP Processor | EM_MMIX -- ^ Donald Knuth's educational 64-bit processor | EM_HUANY -- ^ Harvard University machine-independent object files | EM_PRISM -- ^ SiTera Prism | EM_AVR -- ^ Atmel AVR 8-bit microcontroller | EM_FR30 -- ^ Fujitsu FR30 | EM_D10V -- ^ Mitsubishi D10V | EM_D30V -- ^ Mitsubishi D30V | EM_V850 -- ^ NEC v850 | EM_M32R -- ^ Mitsubishi M32R | EM_MN10300 -- ^ Matsushita MN10300 | EM_MN10200 -- ^ Matsushita MN10200 | EM_PJ -- ^ picoJava | EM_OPENRISC -- ^ OpenRISC 32-bit embedded processor | EM_ARC_A5 -- ^ ARC Cores Tangent-A5 | EM_XTENSA -- ^ Tensilica Xtensa Architecture | EM_VIDEOCORE -- ^ Alphamosaic VideoCore processor | EM_TMM_GPP -- ^ Thompson Multimedia General Purpose Processor | EM_NS32K -- ^ National Semiconductor 32000 series | EM_TPC -- ^ Tenor Network TPC processor | EM_SNP1K -- ^ Trebia SNP 1000 processor | EM_ST200 -- ^ STMicroelectronics (www.st.com) ST200 microcontroller | EM_IP2K -- ^ Ubicom IP2xxx microcontroller family | EM_MAX -- ^ MAX Processor | EM_CR -- ^ National Semiconductor CompactRISC microprocessor | EM_F2MC16 -- ^ Fujitsu F2MC16 | EM_MSP430 -- ^ Texas Instruments embedded microcontroller msp430 | EM_BLACKFIN -- ^ Analog Devices Blackfin (DSP) processor | EM_SE_C33 -- ^ S1C33 Family of Seiko Epson processors | EM_SEP -- ^ Sharp embedded microprocessor | EM_ARCA -- ^ Arca RISC Microprocessor | EM_UNICORE -- ^ Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University | EM_EXT Word16 -- ^ Other deriving (Eq, Show) getElfMachine = liftM getElfMachine_ . getWord16 where getElfMachine_ 0 = EM_NONE getElfMachine_ 1 = EM_M32 getElfMachine_ 2 = EM_SPARC getElfMachine_ 3 = EM_386 getElfMachine_ 4 = EM_68K getElfMachine_ 5 = EM_88K getElfMachine_ 6 = EM_486 getElfMachine_ 7 = EM_860 getElfMachine_ 8 = EM_MIPS getElfMachine_ 9 = EM_S370 getElfMachine_ 10 = EM_MIPS_RS3_LE getElfMachine_ 11 = EM_SPARC64 getElfMachine_ 15 = EM_PARISC getElfMachine_ 17 = EM_VPP500 getElfMachine_ 18 = EM_SPARC32PLUS getElfMachine_ 19 = EM_960 getElfMachine_ 20 = EM_PPC getElfMachine_ 21 = EM_PPC64 getElfMachine_ 22 = EM_S390 getElfMachine_ 23 = EM_SPU getElfMachine_ 36 = EM_V800 getElfMachine_ 37 = EM_FR20 getElfMachine_ 38 = EM_RH32 getElfMachine_ 39 = EM_RCE getElfMachine_ 40 = EM_ARM getElfMachine_ 41 = EM_ALPHA getElfMachine_ 42 = EM_SH getElfMachine_ 43 = EM_SPARCV9 getElfMachine_ 44 = EM_TRICORE getElfMachine_ 45 = EM_ARC getElfMachine_ 46 = EM_H8_300 getElfMachine_ 47 = EM_H8_300H getElfMachine_ 48 = EM_H8S getElfMachine_ 49 = EM_H8_500 getElfMachine_ 50 = EM_IA_64 getElfMachine_ 51 = EM_MIPS_X getElfMachine_ 52 = EM_COLDFIRE getElfMachine_ 53 = EM_68HC12 getElfMachine_ 54 = EM_MMA getElfMachine_ 55 = EM_PCP getElfMachine_ 56 = EM_NCPU getElfMachine_ 57 = EM_NDR1 getElfMachine_ 58 = EM_STARCORE getElfMachine_ 59 = EM_ME16 getElfMachine_ 60 = EM_ST100 getElfMachine_ 61 = EM_TINYJ getElfMachine_ 62 = EM_X86_64 getElfMachine_ 63 = EM_PDSP getElfMachine_ 66 = EM_FX66 getElfMachine_ 67 = EM_ST9PLUS getElfMachine_ 68 = EM_ST7 getElfMachine_ 69 = EM_68HC16 getElfMachine_ 70 = EM_68HC11 getElfMachine_ 71 = EM_68HC08 getElfMachine_ 72 = EM_68HC05 getElfMachine_ 73 = EM_SVX getElfMachine_ 74 = EM_ST19 getElfMachine_ 75 = EM_VAX getElfMachine_ 76 = EM_CRIS getElfMachine_ 77 = EM_JAVELIN getElfMachine_ 78 = EM_FIREPATH getElfMachine_ 79 = EM_ZSP getElfMachine_ 80 = EM_MMIX getElfMachine_ 81 = EM_HUANY getElfMachine_ 82 = EM_PRISM getElfMachine_ 83 = EM_AVR getElfMachine_ 84 = EM_FR30 getElfMachine_ 85 = EM_D10V getElfMachine_ 86 = EM_D30V getElfMachine_ 87 = EM_V850 getElfMachine_ 88 = EM_M32R getElfMachine_ 89 = EM_MN10300 getElfMachine_ 90 = EM_MN10200 getElfMachine_ 91 = EM_PJ getElfMachine_ 92 = EM_OPENRISC getElfMachine_ 93 = EM_ARC_A5 getElfMachine_ 94 = EM_XTENSA getElfMachine_ 95 = EM_VIDEOCORE getElfMachine_ 96 = EM_TMM_GPP getElfMachine_ 97 = EM_NS32K getElfMachine_ 98 = EM_TPC getElfMachine_ 99 = EM_SNP1K getElfMachine_ 100 = EM_ST200 getElfMachine_ 101 = EM_IP2K getElfMachine_ 102 = EM_MAX getElfMachine_ 103 = EM_CR getElfMachine_ 104 = EM_F2MC16 getElfMachine_ 105 = EM_MSP430 getElfMachine_ 106 = EM_BLACKFIN getElfMachine_ 107 = EM_SE_C33 getElfMachine_ 108 = EM_SEP getElfMachine_ 109 = EM_ARCA getElfMachine_ 110 = EM_UNICORE getElfMachine_ n = EM_EXT n getElf_Shdr_OffsetSize :: ElfClass -> ElfReader -> Get (Word64, Word64) getElf_Shdr_OffsetSize ei_class er = case ei_class of ELFCLASS32 -> do skip 16 sh_offset <- liftM fromIntegral $ getWord32 er sh_size <- liftM fromIntegral $ getWord32 er return (sh_offset, sh_size) ELFCLASS64 -> do skip 24 sh_offset <- getWord64 er sh_size <- getWord64 er return (sh_offset, sh_size) getElf_Shdr :: ElfClass -> ElfReader -> B.ByteString -> B.ByteString -> Get ElfSection getElf_Shdr ei_class er elf_file string_section = case ei_class of ELFCLASS32 -> do sh_name <- getWord32 er sh_type <- getElfSectionType er sh_flags <- getElfSectionFlags32 er sh_addr <- getWord32 er sh_offset <- getWord32 er sh_size <- getWord32 er sh_link <- getWord32 er sh_info <- getWord32 er sh_addralign <- getWord32 er sh_entsize <- getWord32 er return ElfSection { elfSectionName = map B.w2c $ B.unpack $ B.takeWhile (/= 0) $ B.drop (fromIntegral sh_name) string_section , elfSectionType = sh_type , elfSectionFlags = sh_flags , elfSectionAddr = fromIntegral sh_addr , elfSectionSize = fromIntegral sh_size , elfSectionLink = sh_link , elfSectionInfo = sh_info , elfSectionAddrAlign = fromIntegral sh_addralign , elfSectionEntSize = fromIntegral sh_entsize , elfSectionData = B.take (fromIntegral sh_size) $ B.drop (fromIntegral sh_offset) elf_file } ELFCLASS64 -> do sh_name <- getWord32 er sh_type <- getElfSectionType er sh_flags <- getElfSectionFlags64 er sh_addr <- getWord64 er sh_offset <- getWord64 er sh_size <- getWord64 er sh_link <- getWord32 er sh_info <- getWord32 er sh_addralign <- getWord64 er sh_entsize <- getWord64 er return ElfSection { elfSectionName = map B.w2c $ B.unpack $ B.takeWhile (/= 0) $ B.drop (fromIntegral sh_name) string_section , elfSectionType = sh_type , elfSectionFlags = sh_flags , elfSectionAddr = sh_addr , elfSectionSize = sh_size , elfSectionLink = sh_link , elfSectionInfo = sh_info , elfSectionAddrAlign = sh_addralign , elfSectionEntSize = sh_entsize , elfSectionData = B.take (fromIntegral sh_size) $ B.drop (fromIntegral sh_offset) elf_file } data TableInfo = TableInfo { tableOffset :: Int, entrySize :: Int, entryNum :: Int } getElf_Ehdr :: Get (Elf, TableInfo, TableInfo, Word16) getElf_Ehdr = do ei_magic <- getElfMagic ei_class <- getElfClass ei_data <- getElfData ei_version <- liftM fromIntegral getElfVersion ei_osabi <- getElfOsabi ei_abiver <- liftM fromIntegral getWord8 skip 7 er <- return $ elfReader ei_data case ei_class of ELFCLASS32 -> do e_type <- getElfType er e_machine <- getElfMachine er e_version <- getWord32 er e_entry <- liftM fromIntegral $ getWord32 er e_phoff <- getWord32 er e_shoff <- liftM fromIntegral $ getWord32 er e_flags <- getWord32 er e_ehsize <- getWord16 er e_phentsize <- getWord16 er e_phnum <- getWord16 er e_shentsize <- getWord16 er e_shnum <- getWord16 er e_shstrndx <- getWord16 er return (Elf { elfClass = ei_class , elfData = ei_data , elfVersion = ei_version , elfOSABI = ei_osabi , elfABIVersion = ei_abiver , elfType = e_type , elfMachine = e_machine , elfEntry = e_entry , elfSections = [] , elfSegments = [] } , TableInfo { tableOffset = fromIntegral e_phoff, entrySize = fromIntegral e_phentsize, entryNum = fromIntegral e_phnum } , TableInfo { tableOffset = fromIntegral e_shoff, entrySize = fromIntegral e_shentsize, entryNum = fromIntegral e_shnum } , e_shstrndx) ELFCLASS64 -> do e_type <- getElfType er e_machine <- getElfMachine er e_version <- getWord32 er e_entry <- getWord64 er e_phoff <- getWord64 er e_shoff <- getWord64 er e_flags <- getWord32 er e_ehsize <- getWord16 er e_phentsize <- getWord16 er e_phnum <- getWord16 er e_shentsize <- getWord16 er e_shnum <- getWord16 er e_shstrndx <- getWord16 er return (Elf { elfClass = ei_class , elfData = ei_data , elfVersion = ei_version , elfOSABI = ei_osabi , elfABIVersion = ei_abiver , elfType = e_type , elfMachine = e_machine , elfEntry = e_entry , elfSections = [] , elfSegments = [] } , TableInfo { tableOffset = fromIntegral e_phoff, entrySize = fromIntegral e_phentsize, entryNum = fromIntegral e_phnum } , TableInfo { tableOffset = fromIntegral e_shoff, entrySize = fromIntegral e_shentsize, entryNum = fromIntegral e_shnum } , e_shstrndx) data ElfReader = ElfReader { getWord16 :: Get Word16 , getWord32 :: Get Word32 , getWord64 :: Get Word64 } elfReader ELFDATA2LSB = ElfReader { getWord16 = getWord16le, getWord32 = getWord32le, getWord64 = getWord64le } elfReader ELFDATA2MSB = ElfReader { getWord16 = getWord16be, getWord32 = getWord32be, getWord64 = getWord64be } divide :: B.ByteString -> Int -> Int -> [B.ByteString] divide bs s 0 = [] divide bs s n = let (x,y) = B.splitAt s bs in x : divide y s (n-1) -- | Parses a ByteString into an Elf record. Parse failures call error. 32-bit ELF objects have their -- fields promoted to 64-bit so that the 32- and 64-bit ELF records can be the same. parseElf :: B.ByteString -> Elf parseElf b = let ph = table segTab sh = table secTab (shstroff, shstrsize) = parseEntry getElf_Shdr_OffsetSize $ head $ drop (fromIntegral e_shstrndx) sh sh_str = B.take (fromIntegral shstrsize) $ B.drop (fromIntegral shstroff) b segments = filter (\seg -> elfSegmentType seg /= PT_NULL) $ map (parseEntry (\c r -> parseElfSegmentEntry c r b)) ph sections = filter (\sec -> elfSectionType sec /= SHT_NULL) $ map (parseEntry (\c r -> getElf_Shdr c r b sh_str)) sh in e { elfSections = sections, elfSegments = segments } where table i = divide (B.drop (tableOffset i) b) (entrySize i) (entryNum i) parseEntry p x = runGet (p (elfClass e) (elfReader (elfData e))) (L.fromChunks [x]) (e, segTab, secTab, e_shstrndx) = runGet getElf_Ehdr $ L.fromChunks [b] data ElfSegment = ElfSegment { elfSegmentType :: ElfSegmentType -- ^ Segment type , elfSegmentFlags :: [ElfSegmentFlag] -- ^ Segment flags , elfSegmentVirtAddr :: Word64 -- ^ Virtual address for the segment , elfSegmentPhysAddr :: Word64 -- ^ Physical address for the segment , elfSegmentAlign :: Word64 -- ^ Segment alignment , elfSegmentData :: B.ByteString -- ^ Data for the segment , elfSegmentMemSize :: Word64 -- ^ Size in memory (may be larger then the segment's data) } deriving (Eq,Show) -- | Segment Types. data ElfSegmentType = PT_NULL -- ^ Unused entry | PT_LOAD -- ^ Loadable segment | PT_DYNAMIC -- ^ Dynamic linking tables | PT_INTERP -- ^ Program interpreter path name | PT_NOTE -- ^ Note sectionks | PT_SHLIB -- ^ Reserved | PT_PHDR -- ^ Program header table | PT_Other Word32 -- ^ Some other type deriving (Eq,Show) parseElfSegmentType :: Word32 -> ElfSegmentType parseElfSegmentType x = case x of 0 -> PT_NULL 1 -> PT_LOAD 2 -> PT_DYNAMIC 3 -> PT_INTERP 4 -> PT_NOTE 5 -> PT_SHLIB 6 -> PT_PHDR _ -> PT_Other x parseElfSegmentEntry :: ElfClass -> ElfReader -> B.ByteString -> Get ElfSegment parseElfSegmentEntry elf_class er elf_file = do p_type <- parseElfSegmentType `fmap` getWord32 er p_flags <- parseElfSegmentFlags `fmap` getWord32 er p_offset <- getWord p_vaddr <- getWord p_paddr <- getWord p_filesz <- getWord p_memsz <- getWord p_align <- getWord return ElfSegment { elfSegmentType = p_type , elfSegmentFlags = p_flags , elfSegmentVirtAddr = p_vaddr , elfSegmentPhysAddr = p_paddr , elfSegmentAlign = p_align , elfSegmentData = B.take (fromIntegral p_filesz) $ B.drop (fromIntegral p_offset) elf_file , elfSegmentMemSize = p_memsz } where getWord = case elf_class of ELFCLASS64 -> getWord64 er ELFCLASS32 -> fromIntegral `fmap` getWord32 er data ElfSegmentFlag = PF_X -- ^ Execute permission | PF_W -- ^ Write permission | PF_R -- ^ Read permission | PF_Ext Int -- ^ Some other flag, the Int is the bit number for the flag. deriving (Eq,Show) parseElfSegmentFlags :: Word32 -> [ElfSegmentFlag] parseElfSegmentFlags word = [ cvt bit | bit <- [ 0 .. 31 ], testBit word bit ] where cvt 0 = PF_X cvt 1 = PF_W cvt 2 = PF_R cvt n = PF_Ext n
yav/elf
src/Data/Elf.hs
bsd-3-clause
28,336
0
17
10,208
4,989
2,717
2,272
568
94
{-# LANGUAGE OverloadedStrings #-} module Mp4AudioSegmentSpec (spec) where import qualified Data.ByteString as BS import Data.ByteString.IsoBaseFileFormat.ReExports import qualified Data.ByteString.Lazy as BL import Data.ByteString.Mp4.AudioStreaming import Data.Text () import Test.Hspec spec :: Spec spec = describe "AacMp4TrackFragment" $ do let args = moof doc = buildAacMp4TrackFragment args rendered = BL.unpack $ toLazyByteString $ doc dataOffset = 120 expected = [ -- styp box 0,0,0,24 ,115,116,121,112 ,109,115,100,104,0,0,0,0 ,109,115,100,104 ,100,97,115,104 -- moov box [offset here: 32] ,0,0,0,112 ,109,111,111,102 -- mfhd box ,0,0,0,16 ,109,102,104,100 ,0,0,0,0,0,0,0,13 -- traf ,0,0,0,88 ,116,114,97,102 -- tfhd ,0,0,0,16 ,116,102,104,100 ,0,2,0,0,0,0,0,1 -- tfdt ,0,0,0,20 ,116,102,100,116 ,1,0,0,0,0,0,0,0,0,0,0,37 -- trun ,0,0,0,44 ,116,114,117,110 ,0,0,7,1 ,0,0,0,2 ,0,0,0,dataOffset -- sample 1 ,0,0,0,23 -- duration ,0,0,0,192 -- length ,2,0,0,0 -- flags -- sample 2 ,0,0,0,23 ,0,0,0,192 ,2,0,0,0 -- mdat ,0,0,1,136 ,109,100,97,116] -- sample 1 ++ [0..191] -- sample 2 ++ [0..191] it "renders the exact expectected output" $ do #ifdef COMPLEXTESTS BL.writeFile "/tmp/isobmff-test-case-dash-spec.m4s" (BL.pack rendered) #endif rendered `shouldBe` expected it "calculates the data-offset correctly" $ drop ((fromIntegral dataOffset) + 12 * 2) rendered `shouldBe` ([0..191] ++ [0..191]) moof :: AacMp4TrackFragment moof = AacMp4TrackFragment 13 37 (replicate 2 (23, BS.pack [0..191]))
sheyll/isobmff-builder
spec/Mp4AudioSegmentSpec.hs
bsd-3-clause
2,688
0
15
1,367
713
452
261
57
1
{-#LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} module FileServer where import Network hiding (accept, sClose) import Network.Socket hiding (send, recv, sendTo, recvFrom, Broadcast) import Network.Socket.ByteString import Data.ByteString.Char8 (pack, unpack) import System.Environment import System.IO import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad (forever, when, join) import Data.List.Split import Data.Word import Text.Printf (printf) import System.Directory --Server data type allows me to pass address and port details easily data FileServer = FileServer { address :: String, port :: String } --Constructor newFileServer :: String -> String -> IO FileServer newFileServer address port = atomically $ do FileServer <$> return address <*> return port --4 is easy for testing the pooling maxnumThreads = 4 serverport :: String serverport = "7007" serverhost :: String serverhost = "localhost" hostname :: HostName hostname = "localhost" run:: IO () run = withSocketsDo $ do --Command line arguments for port and address --args <- getArgs createDirectoryIfMissing True ("distserver" ++ serverhost ++ ":" ++ serverport ++ "/") setCurrentDirectory ("distserver" ++ serverhost ++ ":" ++ serverport ++ "/") addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just "7008") let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "JOIN:" ++ "\\n" ++ "ADDRESS:" ++ serverhost ++ "\\n" ++ "PORT:" ++ serverport ++ "\\n" resp <- recv clsock 1024 let msg = unpack resp printf msg sClose clsock server <- newFileServer serverhost serverport --sock <- listenOn (PortNumber (fromIntegral serverport)) addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just serverport) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket sock (addrAddress serveraddr) listen sock 5 _ <- printf "Listening on port %s\n" serverport --Listen on port from command line argument --New Abstract FIFO Channel chan <- newChan --Tvars are variables Stored in memory, this way we can access the numThreads from any method numThreads <- atomically $ newTVar 0 --Spawns a new thread to handle the clientconnectHandler method, passes socket, channel, numThreads and server forkIO $ clientconnectHandler sock chan numThreads server --Calls the mainHandler which will monitor the FIFO channel mainHandler sock chan mainHandler :: Socket -> Chan String -> IO () mainHandler sock chan = do --Read current message on the FIFO channel chanMsg <- readChan chan --If KILL_SERVICE, stop mainHandler running, If anything else, call mainHandler again, keeping the service running case (chanMsg) of ("KILL_SERVICE") -> putStrLn "Terminating the Service!" _ -> mainHandler sock chan clientconnectHandler :: Socket -> Chan String -> TVar Int -> FileServer -> IO () clientconnectHandler sock chan numThreads server = do --Accept the socket which returns a handle, host and port --(handle, host, port) <- accept sock (s,a) <- accept sock --handle <- socketToHandle s ReadWriteMode --Read numThreads from memory and print it on server console count <- atomically $ readTVar numThreads putStrLn $ "numThreads = " ++ show count --If there are still threads remaining create new thread and increment (exception if thread is lost -> decrement), else tell user capacity has been reached if (count < maxnumThreads) then do forkFinally (clientHandler s chan server) (\_ -> atomically $ decrementTVar numThreads) atomically $ incrementTVar numThreads else do send s (pack ("Maximum number of threads in use. try again soon"++"\n\n")) sClose s clientconnectHandler sock chan numThreads server clientHandler :: Socket -> Chan String -> FileServer -> IO () clientHandler sock chan server@FileServer{..} = forever $ do message <- recv sock 1024 let msg = unpack message print $ msg ++ "!ENDLINE!" let cmd = head $ words $ head $ splitOn ":" msg print cmd case cmd of ("HELO") -> heloCommand sock server $ (words msg) !! 1 ("KILL_SERVICE") -> killCommand chan sock ("DOWNLOAD") -> downloadCommand sock server msg ("UPLOAD") -> uploadCommand sock server msg ("UPDATE") -> updateCommand sock server msg _ -> do send sock (pack ("Unknown Command - " ++ msg ++ "\n\n")) ; return () --Function called when HELO text command recieved heloCommand :: Socket -> FileServer -> String -> IO () heloCommand sock FileServer{..} msg = do send sock $ pack $ "HELO " ++ msg ++ "\n" ++ "IP:" ++ "192.168.6.129" ++ "\n" ++ "Port:" ++ port ++ "\n" ++ "StudentID:12306421\n\n" return () killCommand :: Chan String -> Socket -> IO () killCommand chan sock = do send sock $ pack $ "Service is now terminating!" writeChan chan "KILL_SERVICE" downloadCommand :: Socket -> FileServer -> String -> IO () downloadCommand sock server@FileServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 doesFileExist filename >>= \case True -> do fdata <- readFile filename send sock $ pack $ "DOWNLOAD:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\n\n" False -> send sock $ pack $ "DOWNLOAD:" ++ filename ++ "\\n" ++ "DATA:" ++ "File not Found!!" ++ "\\n\n" return () uploadCommand :: Socket -> FileServer -> String -> IO () uploadCommand sock server@FileServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 doesFileExist filename >>= \case True -> send sock $ pack $ "UPLOAD:" ++ filename ++ "\\n" ++ "Failed:" ++ "File Already Exists!" ++ "\\n\n" False -> do file <- writeFile filename fdata send sock $ pack $ "UPLOAD:" ++ filename ++ "\\n" ++ "STATUS:" ++ "Success" ++ "\\n\n" return () updateCommand :: Socket -> FileServer -> String -> IO () updateCommand sock server@FileServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 doesFileExist filename >>= \case True -> do file <- appendFile filename fdata send sock $ pack $ "UPDATE:" ++ filename ++ "\\n" ++ "STATUS:" ++ "Success" ++ "\\n\n" False -> send sock $ pack $ "UPLOAD:" ++ filename ++ "\\n" ++ "STATUS:" ++ "Failed; File doesn't exist!" ++ "\\n\n" return () --Increment Tvar stored in memory i.e. numThreads incrementTVar :: TVar Int -> STM () incrementTVar tv = modifyTVar tv ((+) 1) --Decrement Tvar stored in memory i.e. numThreads decrementTVar :: TVar Int -> STM () decrementTVar tv = modifyTVar tv (subtract 1)
Garygunn94/DFS
.stack-work/intero/intero39321abm.hs
bsd-3-clause
7,426
194
17
1,862
1,934
997
937
138
6
module Main where import Test.Tasty import qualified Paths main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [Paths.tests]
markus1189/pathfinder
tests/test.hs
bsd-3-clause
159
0
7
27
51
29
22
7
1
-- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- module Feldspar.Core.Frontend.NoInline where import Language.Syntactic import Feldspar.Core.Constructs import Feldspar.Core.Constructs.NoInline noInline :: (Syntax a) => a -> a noInline = sugarSymF NoInline
rCEx/feldspar-lang-small
src/Feldspar/Core/Frontend/NoInline.hs
bsd-3-clause
1,809
0
6
319
79
59
20
6
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveGeneric #-} module Main where import S3Parallel import System.Exit (exitFailure) import System.Random (randomIO) import System.IO import Data.UUID as UUID import Control.DeepSeq import Control.Lens import Control.Concurrent (ThreadId, myThreadId, withMVar, newMVar, MVar, forkFinally, newEmptyMVar, putMVar, takeMVar) import Control.Exception (try, SomeException, throwTo) import Control.Monad import Control.Monad.State import Control.Monad.Trans.AWS (Env, runResourceT, runAWST, send, envRetryCheck, timeout, envLogger, envRegion, Credentials(..), newLogger, LogLevel(..), newEnv) import Data.List (sort) import qualified Data.Foldable as Fold import Data.Text (Text) import qualified Data.Text.IO as Text import Data.Time import Network.AWS.S3 import qualified Data.Text as T import qualified Pipes.Prelude as P import Pipes (Consumer, lift, (>->), runEffect, each, yield, await, Pipe) import Pipes.Concurrent (unbounded, fromInput, toOutput, forkIO, withSpawn) import System.Metrics hiding (Value) import qualified System.Metrics.Counter as Counter import qualified System.Metrics.Distribution as Distribution import System.Remote.Monitoring buildEnv :: Region -> IO Env buildEnv r = do lgr <- newLogger Error stdout newEnv Discover <&> set envLogger lgr . set envRegion r <&> set envRetryCheck (\_ _ -> True) type PageRequest m = Monad m => SearchBounds -> m PageResult -- Examples: -- -- | -- >>> evalState (getPageTest (Nothing, Nothing)) [S3Object "andrew"] -- ([S3Object {s3ObjectKey = "andrew"}],Nothing) -- -- >>> evalState (getPageTest (Nothing, Just "a")) [S3Object "andrew"] -- ([],Nothing) -- -- >>> evalState (getPageTest (Just "c", Nothing)) [S3Object "andrew"] -- ([],Nothing) getPageTest :: MonadState [S3Object] m => SearchBounds -> m PageResult getPageTest (startBound,endBound) = do allObjects <- get let relevantObjects = sort $ filter withinBounds allObjects let (thisResult,nextResults) = splitAt 1000 relevantObjects if Fold.null nextResults then return (thisResult, Nothing) else let lastResult = (s3ObjectKey . last) thisResult in return (thisResult, Just (lastResult, endBound)) where withinBounds x = afterStartBound x && beforeEndBound x afterStartBound x = case startBound of Nothing -> True (Just bound) -> s3ObjectKey x > bound beforeEndBound x = case endBound of Nothing -> True (Just bound) -> s3ObjectKey x < bound getPage :: Env -> Text -> Distribution.Distribution -> Counter.Counter -> Counter.Counter -> Counter.Counter -> (Maybe Text, Maybe Text) -> IO PageResult getPage env bucketName items_returned_distribution zero_items_counter non_zero_items_counter requests_counter (start,end) = do let request = listObjectsV (BucketName bucketName) & lStartAfter .~ start response <- runResourceT . runAWST env $ timeout 10 $ send request let objects = filterEnd end $ view lrsContents response let objectCount = length objects Distribution.add items_returned_distribution (fromIntegral objectCount) if objectCount == 0 then Counter.inc zero_items_counter else Counter.inc non_zero_items_counter Counter.inc requests_counter let nextSegment = if view lrsIsTruncated response == Just False then Nothing else if Fold.null objects then Nothing else let start' = view (oKey . _ObjectKey) $ last objects in Just (start', end) return $ (fmap objectToS3Object objects, nextSegment) where filterEnd :: Maybe Text -> [Object] -> [Object] filterEnd Nothing x = x filterEnd (Just endKey) x = filter (\o -> view (oKey . _ObjectKey) o <= endKey) x log :: MVar () -> String -> IO () log lock text = withMVar lock $ \_ -> putStrLn text timeItem :: NFData b => (String -> IO ()) -> String -> (a -> IO b) -> a -> IO b timeItem logger name f a = do startTime <- getCurrentTime result <- f a _ <- deepseq result (return ()) -- Ensure we include deserialization endTime <- getCurrentTime let diff = diffUTCTime endTime startTime logger $ "Timing: " ++ name ++ " " ++ show diff return result pipeBind :: Monad m => (a -> [b]) -> Pipe a b m r pipeBind f = forever $ do a <- Pipes.await forM (f a) yield maxThreads :: Int maxThreads = 100 actionResult :: Int -> PageResult -> ([S3Object], [SearchBounds]) actionResult currentThreads (page,next) = case next of Nothing -> (page, []) (Just (start,end)) -> if currentThreads < maxThreads then do let subSpaces = splitKeySpace 10 (Just start, end) (page, subSpaces) else do (page, [(Just start, end)]) findAllItems :: ThreadId -> (String -> IO ()) -> b -> (b -> IO (Int -> ([a], [b]))) -> Consumer a IO () -> IO () findAllItems mainThreadId logger start next consumer = withSpawn unbounded go where go (output,input) = do requestId <- randomIO :: IO UUID.UUID _ <- asyncNextPage output (requestId, start) runEffect $ fromInput input >-> loop 1 output >-> consumer loop 0 _ = return () loop c output = do lift $ logger ("threads: " ++ show c) result <- Pipes.await let (resultObjects,nextBounds) = result c forM_ resultObjects yield nextBounds' <- lift $ traverse (\x -> (randomIO :: IO UUID) >>= \y -> return (y, x)) nextBounds lift $ forM_ nextBounds' (asyncNextPage output) loop (c - 1 + length nextBounds) output asyncNextPage output (requestId,bounds) = forkIO $ do logger $ "Starting: " ++ show requestId resultEx <- try (next bounds) case resultEx of Left (ex :: SomeException) -> do logger "Exception" throwTo mainThreadId ex exitFailure Right result -> do runEffect $ Pipes.each [result] >-> toOutput output logger $ "Complete: " ++ show requestId buildNextPage :: IO (Store, (Maybe Text, Maybe Text) -> IO PageResult) buildNextPage = do metricServer <- forkServer "localhost" 8001 let store = serverMetricStore metricServer items_returned_distribution <- createDistribution "items_returned" store zero_items_counter <- createCounter "zero_items_counter" store non_zero_items_counter <- createCounter "non_zero_items_counter" store requests_counter <- createCounter "requests" store env <- buildEnv NorthVirginia return ( store , \x -> getPage env "elevation-tiles-prod" items_returned_distribution zero_items_counter non_zero_items_counter requests_counter x) runNormally :: IO () runNormally = do logLock <- newMVar () let log' = Main.log logLock (store,nextPage) <- buildNextPage items_counter <- createCounter "items_counter" store let processResult = \x -> do r <- timeItem log' "nextPage" (nextPage) x return (\c -> actionResult c r) mainThreadId <- myThreadId findAllItems mainThreadId log' (Just "logs/2016-01-01", Just "m") processResult $ P.map s3ObjectKey >-> P.tee (P.mapM_ $ \_ -> Counter.inc items_counter) >-> P.map (\t -> "File: " ++ T.unpack t) >-> P.stdoutLn failOn10 :: Int -> IO (Int -> ([Int], [Int])) failOn10 b = do let result _ = if b > 10 then error "Bad" else ([b], [b + 1]) return result takeEveryNth :: Int -> String -> StateT Int IO Bool takeEveryNth n = go where go _ = do v <- get if (v == 0) then put n >> return True else put (v - 1) >> return False downloadSegment :: Counter.Counter -> ((Maybe Text, Maybe Text) -> IO PageResult) -> (Maybe Text, Maybe Text) -> IO () downloadSegment itemsCounter nextPage initial = do (items,next) <- nextPage initial forM_ items (\t -> (putStrLn $ "File: " ++ T.unpack (s3ObjectKey t)) >> Counter.inc itemsCounter) case next of Nothing -> return () (Just (start,end)) -> downloadSegment itemsCounter nextPage (Just start, end) forkThread :: IO () -> IO (MVar ()) forkThread proc = do handle <- newEmptyMVar _ <- forkFinally proc (\_ -> putMVar handle ()) return handle runStartingFromList :: FilePath -> IO () runStartingFromList filePath = do handle <- openFile filePath ReadMode handle2 <- openFile filePath ReadMode (store,nextPage) <- buildNextPage items_counter <- createCounter "items_counter" store r <- runEffect $ P.length (P.fromHandle handle) let itemsPerSegment = r `div` maxThreads print itemsPerSegment dividers <- evalStateT (P.toListM $ (P.fromHandle handle2) >-> P.filterM (takeEveryNth itemsPerSegment)) itemsPerSegment let dividers' = fmap (T.pack) dividers let startSegments = (Just "logs/2016-01-01") : (fmap Just dividers') let endSegments = fmap Just dividers' ++ [Just "m"] let segments = zip startSegments endSegments print segments print $ length segments threads <- forM segments (\s -> forkThread (downloadSegment items_counter nextPage s)) mapM_ takeMVar threads main :: IO () main = --runStartingFromList "./tiles2.files" runNormally --findAllItems 0 failOn10 $ P.print say :: MonadIO m => Text -> m () say = liftIO . Text.putStrLn
adbrowne/s3ls-parallel
Main.hs
bsd-3-clause
10,641
0
19
3,330
3,123
1,581
1,542
-1
-1
-- Extract from a list of type constructors those (1) which need to be vectorised and (2) those -- that could be, but need not be vectorised (as a scalar representation is sufficient and more -- efficient). The type constructors that cannot be vectorised will be dropped. -- -- A type constructor will only be vectorised if it is -- -- (1) a data type constructor, with vanilla data constructors (i.e., data constructors admitted by -- Haskell 98) and -- (2) at least one of the type constructors that appears in its definition is also vectorised. -- -- If (1) is met, but not (2), the type constructor may appear in vectorised code, but there is no -- need to vectorise that type constructor itself. This holds, for example, for all enumeration -- types. As '([::])' is being vectorised, any type constructor whose definition involves -- '([::])', either directly or indirectly, will be vectorised. module Vectorise.Type.Classify ( classifyTyCons ) where import UniqSet import UniqFM import DataCon import TyCon import TypeRep import Type import PrelNames import Digraph -- |From a list of type constructors, extract those that can be vectorised, returning them in two -- sets, where the first result list /must be/ vectorised and the second result list /need not be/ -- vectorised. The third result list are those type constructors that we cannot convert (either -- because they use language extensions or because they dependent on type constructors for which -- no vectorised version is available). -- The first argument determines the /conversion status/ of external type constructors as follows: -- -- * tycons which have converted versions are mapped to 'True' -- * tycons which are not changed by vectorisation are mapped to 'False' -- * tycons which can't be converted are not elements of the map -- classifyTyCons :: UniqFM Bool -- ^type constructor conversion status -> [TyCon] -- ^type constructors that need to be classified -> ([TyCon], [TyCon], [TyCon]) -- ^tycons to be converted & not to be converted classifyTyCons convStatus tcs = classify [] [] [] convStatus (tyConGroups tcs) where classify conv keep ignored _ [] = (conv, keep, ignored) classify conv keep ignored cs ((tcs, ds) : rs) | can_convert && must_convert = classify (tcs ++ conv) keep ignored (cs `addListToUFM` [(tc, True) | tc <- tcs]) rs | can_convert = classify conv (tcs ++ keep) ignored (cs `addListToUFM` [(tc, False) | tc <- tcs]) rs | otherwise = classify conv keep (tcs ++ ignored) cs rs where refs = ds `delListFromUniqSet` tcs can_convert = (isNullUFM (refs `minusUFM` cs) && all convertable tcs) || isShowClass tcs must_convert = foldUFM (||) False (intersectUFM_C const cs refs) && (not . isShowClass $ tcs) -- We currently admit Haskell 2011-style data and newtype declarations as well as type -- constructors representing classes. convertable tc = (isDataTyCon tc || isNewTyCon tc) && all isVanillaDataCon (tyConDataCons tc) || isClassTyCon tc -- !!!FIXME: currently we allow 'Show' in vectorised code without actually providing a -- vectorised definition (to be able to vectorise 'Num') isShowClass [tc] = tyConName tc == showClassName isShowClass _ = False -- Used to group type constructors into mutually dependent groups. -- type TyConGroup = ([TyCon], UniqSet TyCon) -- Compute mutually recursive groups of tycons in topological order. -- tyConGroups :: [TyCon] -> [TyConGroup] tyConGroups tcs = map mk_grp (stronglyConnCompFromEdgedVertices edges) where edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs , let ds = tyConsOfTyCon tc] mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds) mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss) where (tcs, dss) = unzip els -- |Collect the set of TyCons used by the representation of some data type. -- tyConsOfTyCon :: TyCon -> UniqSet TyCon tyConsOfTyCon = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons -- |Collect the set of TyCons that occur in these types. -- tyConsOfTypes :: [Type] -> UniqSet TyCon tyConsOfTypes = unionManyUniqSets . map tyConsOfType -- |Collect the set of TyCons that occur in this type. -- tyConsOfType :: Type -> UniqSet TyCon tyConsOfType ty | Just ty' <- coreView ty = tyConsOfType ty' tyConsOfType (TyVarTy _) = emptyUniqSet tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys) where extend | isUnLiftedTyCon tc || isTupleTyCon tc = id | otherwise = (`addOneToUniqSet` tc) tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b) `addOneToUniqSet` funTyCon tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
ilyasergey/GHC-XAppFix
compiler/vectorise/Vectorise/Type/Classify.hs
bsd-3-clause
5,074
0
14
1,219
922
508
414
56
3
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} module CLaSH.Util.CoreHW.Types ( CoreContext (..) , CoreBinding , TransformSession , TransformStep , OrdType(..) , tsTransformCounter , tsUniqSupply , emptyTransformState ) where -- External Modules import Control.Monad.State.Strict (StateT) import Control.Monad.Error (ErrorT) import qualified Data.Label import qualified Data.Label.PureM as Label import Language.KURE (RewriteM) -- GHC API import qualified Type import qualified VarEnv -- Internal Modules import CLaSH.Util (UniqSupply, MonadUnique(..), splitUniqSupply) import CLaSH.Util.CoreHW.Syntax (Var, Term, TyVar) newtype OrdType = OrdType Type.Type #if __GLASGOW_HASKELL__ < 702 instance Eq OrdType where (OrdType a) == (OrdType b) = Type.tcEqType a b instance Ord OrdType where compare (OrdType a) (OrdType b) = Type.tcCmpType a b #else instance Eq OrdType where (OrdType a) == (OrdType b) = Type.eqType a b instance Ord OrdType where compare (OrdType a) (OrdType b) = Type.cmpType a b #endif type CoreBinding = (Var, Term) data CoreContext = AppFirst | AppSecond | TyAppFirst | LetBinding [Var] | LetBody [Var] | LambdaBody Var | TyLambdaBody TyVar | CaseAlt | Other deriving (Show) data TransformState = TransformState { _tsTransformCounter :: Int , _tsUniqSupply :: UniqSupply } Data.Label.mkLabels [''TransformState] type TransformSession m = ErrorT String (StateT TransformState m) type TransformStep m = [CoreContext] -> Term -> RewriteM (TransformSession m) [CoreContext] Term emptyTransformState uniqSupply = TransformState 0 uniqSupply instance Monad m => MonadUnique (TransformSession m) where getUniqueSupplyM = do us <- Label.gets tsUniqSupply let (us',us'') = splitUniqSupply us Label.puts tsUniqSupply us'' return us'
christiaanb/clash-tryout
src/CLaSH/Util/CoreHW/Types.hs
bsd-3-clause
2,063
0
11
512
469
272
197
-1
-1
module Data.Array.Accelerate.BLAS.Internal.Dot where import Data.Array.Accelerate.BLAS.Internal.Common import Data.Array.Accelerate import Data.Array.Accelerate.CUDA.Foreign import qualified Foreign.CUDA.BLAS as BL import Prelude hiding (zipWith) -- TODO: cache the context accross multiple runs with the same dimension! -- maybe reuse the 'unsafePerformIO' trick in accelerate-fft, see FFT.hs cudaDotProductF :: (Vector Float, Vector Float) -- ^ vectors we're running dot product on -> CIO (Scalar Float) -- ^ result of the dot product cudaDotProductF (v1, v2) = do let n = arraySize (arrayShape v1) -- allocate result scalar o <- allocScalar -- get device pointers on the GPU memory -- for the two vectors and the result -- see Data.Array.Accelerate.BLAS.Common v1ptr <- devVF v1 v2ptr <- devVF v2 outPtr <- devSF o -- TODO: avoid doing the init/setPointerMode/cleanup on every call -- see the unsafePerformIO trick in accelerate-fft liftIO $ BL.withCublas $ \handle -> execute handle n v1ptr v2ptr outPtr -- return the output array, that now contains the result return o where execute h n v1ptr v2ptr optr = BL.sdot h n v1ptr 1 v2ptr 1 optr cudaDotProductD :: (Vector Double, Vector Double) -> CIO (Scalar Double) cudaDotProductD (v1, v2) = do let n = arraySize (arrayShape v1) o <- allocScalar v1ptr <- devVD v1 v2ptr <- devVD v2 outPtr <- devSD o liftIO $ BL.withCublas $ \handle -> execute handle n v1ptr v2ptr outPtr return o where execute h n v1ptr v2ptr optr = BL.ddot h n v1ptr 1 v2ptr 1 optr -- | Execute the dot product of the two vectors using -- CUBLAS in the CUDA backend if available, fallback to a "pure" -- implementation otherwise: -- -- >>> A.fold (+) 0 $ A.zipWith (*) v1 v2 sdot :: Acc (Vector Float) -> Acc (Vector Float) -> Acc (Scalar Float) sdot v1 v2 = foreignAcc foreignDPF pureDPF $ lift (v1, v2) where foreignDPF = CUDAForeignAcc "cudaDotProductF" cudaDotProductF pureDPF :: Acc (Vector Float, Vector Float) -> Acc (Scalar Float) pureDPF vs = let (u, v) = unlift vs in fold (+) 0 $ zipWith (*) u v -- | Execute the dot product of the two vectors using -- CUBLAS in the CUDA backend if available, fallback to a "pure" -- implementation otherwise: -- -- >>> A.fold (+) 0 $ A.zipWith (*) v1 v2 ddot :: Acc (Vector Double) -> Acc (Vector Double) -> Acc (Scalar Double) ddot v1 v2 = foreignAcc foreignDPD pureDPD $ lift (v1, v2) where foreignDPD = CUDAForeignAcc "cudaDotProductD" cudaDotProductD pureDPD :: Acc (Vector Double, Vector Double) -> Acc (Scalar Double) pureDPD vs = let (u, v) = unlift vs in fold (+) 0 $ zipWith (*) u v
alpmestan/accelerate-blas
src/Data/Array/Accelerate/BLAS/Internal/Dot.hs
bsd-3-clause
2,856
0
12
725
734
377
357
42
1
{-# LANGUAGE DeriveGeneric #-} module PeerTrader.Socket.Command where import GHC.Generics import Data.ByteString (ByteString) import Data.Serialize import Data.Serialize.Text () import Prosper.Invest import PeerTrader.Types data Command = ActivateAutoFilter UserLogin Int -- ^ User, DefaultKey (Strategy AutoFilter) | ActivateP2PPicks UserLogin Int -- ^ User, DefaultKey (Strategy P2PPicksType) | Deactivate UserLogin | NewProsperAccount UserLogin ByteString ByteString -- ^ User, Username, Password | DeleteProsperAccount UserLogin deriving (Generic, Show) instance Serialize Command where data Response = Response UserLogin InvestResponse deriving (Generic, Show) instance Serialize Response where
WraithM/peertrader-backend
src/PeerTrader/Socket/Command.hs
bsd-3-clause
801
0
6
180
136
80
56
19
0
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Pass.Calc -- Copyright : (C) 2012-2013 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable (GADTs, Rank2Types) -- ---------------------------------------------------------------------------- module Data.Pass.Calc ( Calc(..) ) where import Control.Category import Control.Applicative import Prelude hiding (id,(.)) import Data.Pass.Call import Data.Pass.Eval import Data.Pass.Eval.Naive import Data.Pass.L.By import Data.Pass.Prep import Data.Pass.Thrist import Data.Pass.Type import Data.Pass.Trans import Data.List (sortBy) import Data.Function (on) data Calc k a b where Stop :: b -> Calc k a b (:&) :: Pass k a b -> (b -> Calc k a c) -> Calc k a c Rank :: Ord b => Thrist k a b -> ([Int] -> Calc k a c) -> Calc k a c infixl 1 :& instance By (Calc k) where by (x :& f) r = by x r :& \b -> f b `by` r by (Rank m f) r = Rank m $ \b -> f b `by` r by x _ = x instance Functor (Calc k a) where fmap f (Stop b) = Stop (f b) fmap f (Rank m k) = Rank m (fmap f . k) fmap f (fb :& kba) = fb :& fmap f . kba instance Applicative (Calc k a) where pure = Stop Stop f <*> Stop a = Stop (f a) Stop f <*> (fb :& kba) = fb :& fmap f . kba Stop f <*> Rank fb kba = Rank fb $ fmap f . kba (fg :& kgf) <*> Rank fb kba = fg :& \g -> Rank fb $ \b -> kgf g <*> kba b (fg :& kgf) <*> Stop a = fg :& fmap ($a) . kgf (fg :& kgf) <*> (fb :& kba) = liftA2 (,) fg fb :& \(g,b) -> kgf g <*> kba b Rank fg kgf <*> (fb :& kba) = fb :& \b -> Rank fg $ \g -> kgf g <*> kba b Rank fg kgf <*> Stop a = Rank fg $ fmap ($a) . kgf Rank fg kgf <*> Rank fb kba = Rank fg $ \g -> Rank fb $ \b -> kgf g <*> kba b _ *> b = b a <* _ = a instance Monad (Calc k a) where return = Stop Stop a >>= f = f a (fb :& kba) >>= f = fb :& (>>= f) . kba Rank fb kba >>= f = Rank fb $ (>>= f) . kba (>>) = (*>) instance Prep Calc where prep _ (Stop b) = Stop b prep t (c :& k) = prep t c :& prep t . k prep t (Rank c k) = Rank (prep t c) (prep t . k) #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 704 instance Show (Calc k a b) where showsPrec _ _ = showString "<calc>" instance Eq (Calc k a b) where _ == _ = False #endif #endif instance Num b => Num (Calc k a b) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger instance Fractional b => Fractional (Calc k a b) where (/) = liftA2 (/) recip = fmap recip fromRational = pure . fromRational instance Floating b => Floating (Calc k a b) where pi = pure pi exp = fmap exp sqrt = fmap sqrt log = fmap log (**) = liftA2 (**) logBase = liftA2 logBase sin = fmap sin tan = fmap tan cos = fmap cos asin = fmap asin atan = fmap atan acos = fmap acos sinh = fmap sinh tanh = fmap tanh cosh = fmap cosh asinh = fmap asinh acosh = fmap acosh atanh = fmap atanh instance Trans Calc where trans t = trans t :& Stop instance Call k => Naive (Calc k) where naive (Stop b) _ _ = b naive (i :& k) n xs = naive (k $ naive i n xs) n xs naive (Rank m k) n xs = naive (k $ map fst $ sortBy (on compare (call m . snd)) $ zip [0..] xs) n xs instance Call k => Eval (Calc k) where eval (Stop b) _ _ = b eval (i :& k) n xs = eval (k (eval i n xs)) n xs eval (Rank m k) n xs = eval (k $ map fst $ sortBy (on compare $ call m . snd) $ zip [0..] xs) n xs
ekmett/multipass
Data/Pass/Calc.hs
bsd-3-clause
3,683
0
15
988
1,795
920
875
93
0
{-# LANGUAGE OverloadedStrings #-} module Sound.Player ( appMain ) where import qualified Brick.AttrMap as A import qualified Brick.Main as M import Brick.Types (Widget, EventM, Next, Name(Name), handleEvent) import Brick.Widgets.Core ((<+>), str, vBox) import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.List as L import qualified Brick.Widgets.ProgressBar as P import Brick.Util (on) import Control.Concurrent (Chan, ThreadId, forkIO, killThread, newChan, writeChan, threadDelay) import Control.Exception (SomeException, catch) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Default (def) import Data.List (isPrefixOf, stripPrefix) import Data.Maybe (fromMaybe) import qualified Data.Vector as Vec import qualified Graphics.Vty as V import Lens.Micro ((^.)) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.Environment (getEnv) import System.FilePath ((</>)) import System.Process (ProcessHandle) import Sound.Player.AudioInfo (SongInfo(SongInfo), fetchSongInfo) import qualified Sound.Player.AudioPlay as AP (play, pause, resume, stop) import Sound.Player.Types (Song(Song, songStatus), PlayerApp(PlayerApp, songsList, playerStatus, playback), Playback(Playback, playhead), Status(Play, Pause, Stop), PlayerEvent(VtyEvent, PlayheadAdvance)) import Sound.Player.Widgets (songWidget, playbackProgressBar) -- | Draws application UI. drawUI :: PlayerApp -> [Widget] drawUI (PlayerApp l _ _ mPlayback) = [ui] where label = str "Item " <+> cur <+> str " of " <+> total cur = case l ^. L.listSelectedL of Nothing -> str "-" Just i -> str (show (i + 1)) total = str $ show $ Vec.length $ l ^. L.listElementsL box = B.borderWithLabel label $ L.renderList l (const songWidget) ui = vBox [ box , playbackProgressBar mPlayback l , str $ "Press enter to play/stop, spacebar to pause/resume, " ++ "left/right to play prev/next song, " ++ "q to exit." ] -- Updates the selected song status and the song list in the app state. updateAppStatus :: PlayerApp -> Status -> Int -> PlayerApp updateAppStatus app@(PlayerApp l _ _ _) status pos = app { songsList = L.listReplace songs' mPos l, playerStatus = status } where songs = L.listElements l mPos = l ^. L.listSelectedL song = songs Vec.! pos songs' = songs Vec.// [(pos, song { songStatus = status })] -- | App events handler. appEvent :: PlayerApp -> PlayerEvent -> EventM (Next PlayerApp) appEvent app@(PlayerApp l status _ mPlayback) e = case e of -- press enter to play selected song, stop current song if playing VtyEvent (V.EvKey V.KEnter []) -> M.continue =<< stopAndPlaySelected app -- press spacebar to play/pause VtyEvent (V.EvKey (V.KChar ' ') []) -> case status of Play -> -- pause playing song case mPlayback of Nothing -> M.continue app Just (Playback playPos playProc _ _ _) -> do liftIO $ AP.pause playProc M.continue $ updateAppStatus app Pause playPos Pause -> -- resume playing song case mPlayback of Nothing -> M.continue app Just (Playback playPos playProc _ _ _) -> do liftIO $ AP.resume playProc M.continue $ updateAppStatus app Play playPos Stop -> -- play selected song M.continue =<< play (l ^. L.listSelectedL) app -- press left to play previous song VtyEvent (V.EvKey V.KLeft []) -> M.continue =<< stopAndPlayDelta (-1) app -- press right to play next song VtyEvent (V.EvKey V.KRight []) -> M.continue =<< stopAndPlayDelta 1 app -- press q to quit VtyEvent (V.EvKey (V.KChar 'q') []) -> M.halt =<< stop app -- any other event VtyEvent ev -> do l' <- handleEvent ev l M.continue app { songsList = l' } -- playhead advance event PlayheadAdvance -> M.continue =<< case status of Play -> case mPlayback of Nothing -> return app Just pb@(Playback _ _ ph _ _) -> if ph > 0 then -- advance playhead return app { playback = Just pb { playhead = ph - 1.0 } } else stopAndPlayDelta 1 app _ -> return app -- | Forks a thread that will trigger a 'Types.PlayheadAdvance' event every -- second. playheadAdvanceLoop :: Chan PlayerEvent -> IO ThreadId playheadAdvanceLoop chan = forkIO loop where loop = do threadDelay 1000000 writeChan chan PlayheadAdvance loop -- | Stops the song that is currently playing and kills the playback thread. stop :: (MonadIO m) => PlayerApp -> m PlayerApp stop app@(PlayerApp _ _ _ Nothing) = return app stop app@(PlayerApp _ _ _ (Just pb@(Playback playPos _ _ _ _))) = do liftIO $ stopPlayingSong pb return (updateAppStatus app Stop playPos) { playback = Nothing } where stopPlayingSong (Playback _ playProc _ _ threadId) = do AP.stop playProc killThread threadId -- | Fetches song info, plays it, and starts a thread to advance the playhead. play :: (MonadIO m) => Maybe Int -> PlayerApp -> m PlayerApp play Nothing app = return app play (Just _) app@(PlayerApp _ _ _ (Just _)) = return app play (Just pos) app@(PlayerApp l _ chan _) = do (proc, duration, tId) <- liftIO $ playSong song return (updateAppStatus app Play pos) { playback = Just (Playback pos proc duration duration tId) } where songs = L.listElements l song = songs Vec.! pos failSongInfo :: SomeException -> IO SongInfo failSongInfo _ = return $ SongInfo (-1) playSong :: Song -> IO (ProcessHandle, Double, ThreadId) playSong (Song _ path _) = do musicDir <- defaultMusicDirectory (SongInfo duration) <- catch (fetchSongInfo $ musicDir </> path) failSongInfo proc <- AP.play $ musicDir </> path tId <- playheadAdvanceLoop chan return (proc, duration, tId) -- Stops current song and play selected song. stopAndPlaySelected :: (MonadIO m) => PlayerApp -> m PlayerApp stopAndPlaySelected app = stop app >>= play mPos where mPos = songsList app ^. L.listSelectedL -- Stops current song and play current song pos + delta. stopAndPlayDelta :: (MonadIO m) => Int -> PlayerApp -> m PlayerApp stopAndPlayDelta _ app@(PlayerApp _ _ _ Nothing) = return app stopAndPlayDelta delta app@(PlayerApp l _ _ (Just (Playback playPos _ _ _ _))) = stop app >>= play (Just pos) where pos = (playPos + delta) `mod` Vec.length (L.listElements l) -- | Returns the initial state of the application. initialState :: IO PlayerApp initialState = do chan <- newChan paths <- listMusicDirectory let songs = map (\p -> Song Nothing p Stop) paths listWidget = L.list (Name "list") (Vec.fromList songs) 1 return $ PlayerApp listWidget Stop chan Nothing theMap :: A.AttrMap theMap = A.attrMap V.defAttr [ (L.listAttr, V.white `on` V.blue) , (L.listSelectedAttr, V.blue `on` V.white) , (P.progressCompleteAttr, V.blue `on` V.white) ] theApp :: M.App PlayerApp PlayerEvent theApp = M.App { M.appDraw = drawUI , M.appChooseCursor = M.showFirstCursor , M.appHandleEvent = appEvent , M.appStartEvent = return , M.appAttrMap = const theMap , M.appLiftVtyEvent = VtyEvent } -- TODO: return only audio files -- | Returns the list of files in the default music directory. listMusicDirectory :: IO [FilePath] listMusicDirectory = do musicDir <- defaultMusicDirectory map (stripMusicDirectory musicDir) <$> listMusicDirectoryRic [musicDir] where listMusicDirectoryRic [] = return [] listMusicDirectoryRic (p:ps) = do isDirectory <- doesDirectoryExist p if isDirectory then do files <- map (p </>) . filter visible <$> getDirectoryContents p listMusicDirectoryRic (files ++ ps) else do files <- listMusicDirectoryRic ps return $ p:files visible = not . isPrefixOf "." stripMusicDirectory musicDir = fromMaybe musicDir . stripPrefix musicDir -- | The default music directory is @$HOME/Music@. defaultMusicDirectory :: IO FilePath defaultMusicDirectory = (</> "Music/") <$> getEnv "HOME" appMain :: IO PlayerApp appMain = do playerApp@(PlayerApp _ _ chan _) <- initialState M.customMain (V.mkVty def) chan theApp playerApp
potomak/haskell-player
src/Sound/Player.hs
bsd-3-clause
8,573
0
22
2,140
2,575
1,372
1,203
178
14
{-| Module that logs all state modifying actions to a file so that they can be reprocessed. -} module State.Logger ( wrap , replay , foldLogFile , foldLogFile_ , foldComments , foldMapComments ) where import Control.Monad ( forever ) import System.IO.Error ( try ) import System.IO ( stderr, openBinaryFile, hPutStrLn, hClose, hFlush , IOMode(AppendMode), Handle ) import Data.ByteString.Lazy as B import Data.Binary.Get ( runGetState ) import Data.Binary ( Binary(..), getWord8, putWord8, encode ) import Control.Applicative ( (<$>), (<*>), pure ) import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar ) import Control.Concurrent ( forkIO, threadDelay ) import Data.Monoid ( mempty, mappend, Monoid ) import Network.URI ( URI, parseRelativeReference ) import qualified Data.Text as T import qualified Data.Text.Encoding as T import State.Types data Action = AddComment CommentId (Maybe ChapterId) Comment | AddChapter ChapterId [CommentId] (Maybe URI) deriving (Eq, Show) instance Binary Action where get = do ty <- getWord8 case ty of 0xfe -> AddComment <$> get <*> get <*> get 0xff -> AddChapter <$> get <*> get <*> pure Nothing 0xfd -> AddChapter <$> get <*> get <*> (parseRelativeReference <$> get) _ -> error $ "Bad type code: " ++ show ty put (AddComment cId mChId c) = do putWord8 0xfe put cId put mChId put c put (AddChapter chId cs Nothing) = do putWord8 0xff put chId put cs put (AddChapter chId cs (Just uri)) = do putWord8 0xfd put chId put cs put $ T.encodeUtf8 $ T.pack $ show uri -- Attempt to replay a log file, skipping corrupted sections of the file foldLogFile :: Binary act => (act -> a -> IO a) -> a -> B.ByteString -> IO a foldLogFile processAction initial = go initial where go x bs | B.null bs = return x go x bs = uncurry go =<< (step x bs `catch` \_ -> return (x, B.drop 1 bs)) step x bs = do let (act, bs', _) = runGetState get bs 0 x' <- processAction act x return (x', bs') foldLogFile_ :: Binary act => (act -> IO ()) -> B.ByteString -> IO () foldLogFile_ f = foldLogFile (const . f) () replay :: State -> B.ByteString -> IO () replay st = foldLogFile_ $ \act -> case act of AddComment cId mChId c -> addComment st cId mChId c AddChapter chId cs mURI -> addChapter st chId cs mURI -- | Strict fold over the comments in the log file foldComments :: (CommentId -> Maybe ChapterId -> Comment -> b -> b) -> b -> B.ByteString -> IO b foldComments f = foldLogFile $ \act -> case act of AddChapter _ _ _ -> return AddComment cId mChId c -> \x -> let x' = f cId mChId c x in x' `seq` return x' foldMapComments :: Monoid b => (CommentId -> Maybe ChapterId -> Comment -> b) -> B.ByteString -> IO b foldMapComments f = foldComments (\cId mChId c -> (f cId mChId c `mappend`)) mempty -- |Wrap a store so that all of its modifying operations are logged to -- a file. The file can later be replayed to restore the state. wrap :: FilePath -> State -> IO State wrap logFileName st = do ref <- newMVar Nothing forkIO $ rotateLog ref return st { addComment = \cId mChId c -> do writeLog logFileName ref $ AddComment cId mChId c addComment st cId mChId c , addChapter = \chId cs mURI -> do writeLog logFileName ref $ AddChapter chId cs mURI addChapter st chId cs mURI } -- |Attempt to close the log file every five minutes so that we can -- open new files and make sure that the entries are being written to -- a mapped disk file rotateLog :: MVar (Maybe Handle) -> IO () rotateLog v = forever $ do modifyMVar v $ \mh -> do hPutStrLn stderr "Rotating" maybe (return ()) closeLog mh return (Nothing, ()) -- reopen the log file every five minutes threadDelay $ 1000000 * 600 where closeLog h = hClose h `catch` putErr "Failed to close log handle" -- Write any errors to stderr so that we have a record of them -- somewhere putErr :: String -> IOError -> IO () putErr msg e = hPutStrLn stderr $ msg ++ ": " ++ show e -- |Write a log entry to a file, opening the file for append if -- necessary writeLog :: FilePath -> MVar (Maybe Handle) -> Action -> IO () writeLog fn v act = modifyMVar v $ \mh -> do mh' <- getHandle mh >>= writeEntry return (mh', ()) where -- If we don't have a handle, try to open one getHandle (Just h) = return $ Just h getHandle Nothing = do res <- try $ openBinaryFile fn AppendMode case res of Right h -> return $ Just h Left e -> do putErr "Failed to open log file" e return Nothing -- Try to write the log entry, but don't raise an exception if -- we can't, so that we have the best chance of actually saving -- the data writeEntry Nothing = return Nothing writeEntry (Just h) = do res <- try $ do B.hPut h (encode act) hFlush h case res of Right () -> return $ Just h Left e -> do putErr "Failed to write log entry" e hClose h `catch` putErr "Failed to close log file" return Nothing
j3h/doc-review
src/State/Logger.hs
bsd-3-clause
5,698
0
15
1,860
1,695
853
842
117
5
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Futhark.Optimise.InPlaceLowering.LowerIntoBinding ( lowerUpdate , DesiredUpdate (..) ) where import Control.Applicative import Control.Monad import Control.Monad.Writer import Data.List (find) import Data.Maybe (mapMaybe) import Data.Either import qualified Data.HashSet as HS import Prelude import Futhark.Representation.AST import Futhark.Construct import Futhark.MonadFreshNames import Futhark.Optimise.InPlaceLowering.SubstituteIndices data DesiredUpdate attr = DesiredUpdate { updateName :: VName -- ^ Name of result. , updateType :: attr -- ^ Type of result. , updateCertificates :: Certificates , updateSource :: VName , updateIndices :: [SubExp] , updateValue :: VName } deriving (Show) instance Functor DesiredUpdate where f `fmap` u = u { updateType = f $ updateType u } updateHasValue :: VName -> DesiredUpdate attr -> Bool updateHasValue name = (name==) . updateValue lowerUpdate :: (Bindable lore, MonadFreshNames m, LetAttr lore ~ Type) => Binding lore -> [DesiredUpdate (LetAttr lore)] -> Maybe (m [Binding lore]) lowerUpdate (Let pat _ (DoLoop ctx val form body)) updates = do canDo <- lowerUpdateIntoLoop updates pat ctx val body Just $ do (prebnds, postbnds, ctxpat, valpat, ctx', val', body') <- canDo return $ prebnds ++ [mkLet' ctxpat valpat $ DoLoop ctx' val' form body'] ++ postbnds lowerUpdate (Let pat _ (PrimOp (SubExp (Var v)))) [DesiredUpdate bindee_nm bindee_attr cs src is val] | patternNames pat == [src] = Just $ return [mkLet [] [(Ident bindee_nm $ typeOf bindee_attr, BindInPlace cs v is)] $ PrimOp $ SubExp $ Var val] lowerUpdate (Let (Pattern [] [PatElem v BindVar v_attr]) _ e) [DesiredUpdate bindee_nm bindee_attr cs src is val] | v == val = Just $ return [mkLet [] [(Ident bindee_nm $ typeOf bindee_attr, BindInPlace cs src is)] e, mkLet' [] [Ident v $ typeOf v_attr] $ PrimOp $ Index cs bindee_nm is] lowerUpdate _ _ = Nothing lowerUpdateIntoLoop :: (Bindable lore, MonadFreshNames m, LetAttr lore ~ Type) => [DesiredUpdate (LetAttr lore)] -> Pattern lore -> [(FParam lore, SubExp)] -> [(FParam lore, SubExp)] -> Body lore -> Maybe (m ([Binding lore], [Binding lore], [Ident], [Ident], [(FParam lore, SubExp)], [(FParam lore, SubExp)], Body lore)) lowerUpdateIntoLoop updates pat ctx val body = do -- Algorithm: -- -- 0) Map each result of the loop body to a corresponding in-place -- update, if one exists. -- -- 1) Create new merge variables corresponding to the arrays being -- updated; extend the pattern and the @res@ list with these, -- and remove the parts of the result list that have a -- corresponding in-place update. -- -- (The creation of the new merge variable identifiers is -- actually done at the same time as step (0)). -- -- 2) Create in-place updates at the end of the loop body. -- -- 3) Create index expressions that read back the values written -- in (2). If the merge parameter corresponding to this value -- is unique, also @copy@ this value. -- -- 4) Update the result of the loop body to properly pass the new -- arrays and indexed elements to the next iteration of the -- loop. -- -- We also check that the merge parameters we work with have -- loop-invariant shapes. mk_in_place_map <- summariseLoop updates usedInBody resmap val Just $ do in_place_map <- mk_in_place_map (val',prebnds,postbnds) <- mkMerges in_place_map let (ctxpat,valpat) = mkResAndPat in_place_map idxsubsts = indexSubstitutions in_place_map (idxsubsts', newbnds) <- substituteIndices idxsubsts $ bodyBindings body (body_res, res_bnds) <- manipulateResult in_place_map idxsubsts' let body' = mkBody (newbnds++res_bnds) body_res return (prebnds, postbnds, ctxpat, valpat, ctx, val', body') where usedInBody = freeInBody body resmap = zip (bodyResult body) $ patternValueIdents pat mkMerges :: (MonadFreshNames m, Bindable lore, LetAttr lore ~ Type) => [LoopResultSummary (LetAttr lore)] -> m ([(Param DeclType, SubExp)], [Binding lore], [Binding lore]) mkMerges summaries = do ((origmerge, extramerge), (prebnds, postbnds)) <- runWriterT $ partitionEithers <$> mapM mkMerge summaries return (origmerge ++ extramerge, prebnds, postbnds) mkMerge summary | Just (update, mergename, mergeattr) <- relatedUpdate summary = do source <- newVName "modified_source" let updpat = [(Ident source $ updateType update, BindInPlace (updateCertificates update) (updateSource update) (updateIndices update))] elmident = Ident (updateValue update) $ rowType $ typeOf $ updateType update tell ([mkLet [] updpat $ PrimOp $ SubExp $ snd $ mergeParam summary], [mkLet' [] [elmident] $ PrimOp $ Index [] (updateName update) (updateIndices update)]) return $ Right (Param mergename (toDecl (typeOf mergeattr) Unique), Var source) | otherwise = return $ Left $ mergeParam summary mkResAndPat summaries = let (origpat,extrapat) = partitionEithers $ map mkResAndPat' summaries in (patternContextIdents pat, origpat ++ extrapat) mkResAndPat' summary | Just (update, _, _) <- relatedUpdate summary = Right (Ident (updateName update) (updateType update)) | otherwise = Left (inPatternAs summary) summariseLoop :: MonadFreshNames m => [DesiredUpdate attr] -> Names -> [(SubExp, Ident)] -> [(Param DeclType, SubExp)] -> Maybe (m [LoopResultSummary attr]) summariseLoop updates usedInBody resmap merge = sequence <$> zipWithM summariseLoopResult resmap merge where summariseLoopResult (se, v) (fparam, mergeinit) | Just update <- find (updateHasValue $ identName v) updates = if updateSource update `HS.member` usedInBody then Nothing else if hasLoopInvariantShape fparam then Just $ do lowered_array <- newVName "lowered_array" return LoopResultSummary { resultSubExp = se , inPatternAs = v , mergeParam = (fparam, mergeinit) , relatedUpdate = Just (update, lowered_array, updateType update) } else Nothing summariseLoopResult (se, patpart) (fparam, mergeinit) = Just $ return LoopResultSummary { resultSubExp = se , inPatternAs = patpart , mergeParam = (fparam, mergeinit) , relatedUpdate = Nothing } hasLoopInvariantShape = all loopInvariant . arrayDims . paramType merge_param_names = map (paramName . fst) merge loopInvariant (Var v) = v `notElem` merge_param_names loopInvariant Constant{} = True data LoopResultSummary attr = LoopResultSummary { resultSubExp :: SubExp , inPatternAs :: Ident , mergeParam :: (Param DeclType, SubExp) , relatedUpdate :: Maybe (DesiredUpdate attr, VName, attr) } deriving (Show) indexSubstitutions :: [LoopResultSummary attr] -> IndexSubstitutions attr indexSubstitutions = mapMaybe getSubstitution where getSubstitution res = do (DesiredUpdate _ _ cs _ is _, nm, attr) <- relatedUpdate res let name = paramName $ fst $ mergeParam res return (name, (cs, nm, attr, is)) manipulateResult :: (Bindable lore, MonadFreshNames m) => [LoopResultSummary (LetAttr lore)] -> IndexSubstitutions (LetAttr lore) -> m (Result, [Binding lore]) manipulateResult summaries substs = do let (orig_ses,updated_ses) = partitionEithers $ map unchangedRes summaries (subst_ses, res_bnds) <- runWriterT $ zipWithM substRes updated_ses substs return (orig_ses ++ subst_ses, res_bnds) where unchangedRes summary = case relatedUpdate summary of Nothing -> Left $ resultSubExp summary Just _ -> Right $ resultSubExp summary substRes (Var res_v) (subst_v, (_, nm, _, _)) | res_v == subst_v = return $ Var nm substRes res_se (_, (cs, nm, attr, is)) = do v' <- newIdent' (++"_updated") $ Ident nm $ typeOf attr tell [mkLet [] [(v', BindInPlace cs nm is)] $ PrimOp $ SubExp res_se] return $ Var $ identName v'
CulpaBS/wbBach
src/Futhark/Optimise/InPlaceLowering/LowerIntoBinding.hs
bsd-3-clause
9,758
0
18
3,356
2,537
1,330
1,207
178
5
module Language.DemonL.TypeCheck where import Control.Applicative import Control.Monad import Control.Monad.Trans.Error import Data.Functor.Identity import Data.List import qualified Data.Map as M import qualified Language.DemonL.AST as A import Language.DemonL.AST (Struct (..), ProcedureU, Procedure (..), Clause (..), declsToMap, Domain (..), DomainU, UnOp (..), ROp (..), Decl (..)) import Language.DemonL.Types type TypeM a = ErrorT String Identity a type ProcedureT = Procedure TExpr type DomainT = Domain TExpr data TExpr = Call String [TExpr] Type | BinOpExpr BinOp TExpr TExpr Type | UnOpExpr UnOp TExpr Type | ForAll [Decl] TExpr | Access TExpr String Type | Var String Type | ResultVar Type | Cast TExpr Type | LitInt Integer | LitBool Bool | LitNull Type | LitDouble Double deriving (Show, Eq, Ord) data BinOp = Add | Sub | Mul | Div | Or | And | Implies | ArrayIndex | RelOp ROp Type deriving (Eq, Ord) instance Show BinOp where show Add = "+" show Sub = "-" show Mul = "*" show Div = "/" show Or = "or" show And = "and" show Implies = "implies" show (RelOp op _) = show op runTypeM = runIdentity . runErrorT texprType (Call _ _ t) = t texprType (BinOpExpr _ _ _ t) = t texprType (UnOpExpr _ _ t) = t texprType (ForAll _ _) = BoolType texprType (Access _ _ t) = t texprType (Var _ t) = t texprType (ResultVar t) = t texprType (Cast _ t) = t texprType (LitInt _) = IntType texprType (LitBool _) = BoolType texprType (LitNull t) = t texprType (LitDouble _) = DoubleType typecheckDomain :: DomainU -> TypeM DomainT typecheckDomain d@(Domain types procs funcs) = Domain <$> pure types <*> mapM (typecheckProc d) procs <*> mapM (typecheckProc d) funcs typecheckProc :: DomainU -> ProcedureU -> TypeM ProcedureT typecheckProc dom (Procedure name args res req ens) = let argMap = declsToMap args tcClause = typecheckClause argMap dom res req' = mapM tcClause req ens' = mapM tcClause ens in Procedure name args res <$> req' <*> ens' typecheckClause argMap dom res (Clause n e) = Clause n <$> typecheckExpr argMap dom res e noStructErr struct = throwError $ "<" ++ struct ++ "> not found" noAttrErr struct attr = throwError $ "<" ++ struct ++ ">." ++ attr ++ " not found" lookupName :: String -> M.Map String Type -> TypeM Type lookupName str decls = maybe (throwError $ str ++ " not found in declarations") return (M.lookup str decls) lookupAttrType :: [Struct] -> String -> String -> TypeM Type lookupAttrType types attr struct = let isStruct = (== struct) . structName mbStruct = find isStruct types getAttr = lookupName attr . declsToMap . structDecls in maybe (noStructErr struct) getAttr mbStruct getStructNameM :: Type -> TypeM String getStructNameM (StructType n _) = return n getStructNameM t = throwError $ show t ++ " not a struct" unsafeCheck decls dom e = let te = runTypeM $ typecheckExpr (declsToMap decls) dom NoType e in either error id te findFunction name dom = let fns = domFuncs dom p f = prcdName f == name in find p fns checkFunctionArgs argMap dom resType f args | length (prcdArgs f) /= length args = throwError $ "Arguments not same length" | otherwise = do let formalTypes = map declType (prcdArgs f) guardTypeM type1 type2 | type1 == type2 = return () | otherwise = throwError $ "Unconforming arguments: " ++ show type1 ++ " and " ++ show type2 actualArgs <- mapM (fmap texprType . typecheckExpr argMap dom resType) args zipWithM_ guardTypeM formalTypes actualArgs return (prcdResult f) typecheckExpr :: M.Map String Type -> DomainU -> Type -> A.Expr -> TypeM TExpr typecheckExpr argMap dom resType = let types = domStructs dom tc :: A.Expr -> TypeM TExpr tc (A.Access e attr) = let eM = tc e structStr = getStructNameM =<< (texprType <$> eM) attrTypM = lookupAttrType types attr =<< structStr in Access <$> eM <*> pure attr <*> attrTypM tc (A.Var n) = Var n <$> lookupName n argMap tc (A.LitInt i) = pure $ LitInt i tc (A.LitBool b) = pure $ LitBool b tc A.ResultVar = pure $ ResultVar resType tc (A.Call name args) = case findFunction name dom of Just f -> let argsM = mapM (typecheckExpr argMap dom resType) args in Call name <$> argsM <*> checkFunctionArgs argMap dom resType f args Nothing -> throwError $ "Coudln't find function " ++ name -- both equality and inequality are dealt with specially -- as they are needed to type `null' values. tc (A.BinOpExpr (A.RelOp Eq) A.LitNull A.LitNull) = pure $ BinOpExpr (RelOp Eq VoidType) (LitNull VoidType) (LitNull VoidType) BoolType tc (A.BinOpExpr (A.RelOp Eq) A.LitNull e) = let eM = tc e nullM = LitNull <$> (texprType <$> eM) in BinOpExpr <$> (RelOp Eq <$> (texprType <$> eM)) <*> nullM <*> eM <*> pure BoolType tc (A.BinOpExpr (A.RelOp Eq) e A.LitNull) = let eM = tc e nullM = LitNull <$> (texprType <$> eM) in BinOpExpr <$> (RelOp Eq <$> (texprType <$> eM)) <*> eM <*> nullM <*> pure BoolType tc (A.BinOpExpr (A.RelOp A.Neq) A.LitNull A.LitNull) = pure $ BinOpExpr (RelOp Neq VoidType) (LitNull VoidType) (LitNull VoidType) BoolType tc (A.BinOpExpr bOp@(A.RelOp Neq) A.LitNull e) = let eM = tc e nullM = LitNull <$> (texprType <$> eM) in BinOpExpr <$> (RelOp Neq <$> (texprType <$> eM)) <*> nullM <*> eM <*> pure BoolType tc (A.BinOpExpr bOp@(A.RelOp Neq) e A.LitNull) = let eM = tc e nullM = LitNull <$> (texprType <$> eM) in BinOpExpr <$> (RelOp Neq <$> (texprType <$> eM)) <*> eM <*> nullM <*> pure BoolType tc (A.BinOpExpr bOp e1 e2) = let e1M = tc e1 e2M = tc e2 tM = join $ binOpTypes bOp <$> e1M <*> e2M in BinOpExpr (typedBinOp bOp) <$> e1M <*> e2M <*> tM tc (A.UnOpExpr uop e) = let eM = tc e tM = join $ unOpTypes uop <$> eM in UnOpExpr uop <$> eM <*> tM tc (A.ForAll ds e) = ForAll ds <$> typecheckExpr ds' dom BoolType e where ds' = declsToMap ds `M.union` argMap tc e = throwError $ "Can't typecheck " ++ show e in tc typedBinOp op = case op of A.Add -> Add A.Sub -> Sub A.Mul -> Mul A.Div -> Div A.Or -> Or A.And -> And A.Implies -> Implies A.ArrayIndex -> error "typedBinOp: no array indexes" A.RelOp rop -> RelOp (typedROp rop) VoidType typedROp rop = case rop of A.Lte -> Lte A.Lt -> Lt A.Eq -> Eq A.Gt -> Gt A.Gte -> Gte isBool A.And = True isBool A.Or = True isBool A.Implies = True isBool _ = False isNumType IntType = True isNumType DoubleType = True isNumType _ = False isNum A.Add = True isNum A.Sub = True isNum A.Mul = True isNum A.Div = True isNum _ = False unOpTypes Not e | texprType e == BoolType = return BoolType unOpTypes Neg e | isNumType (texprType e) = return $ texprType e unOpTypes Old e = return $ texprType e unOpTypes op e = error $ "unOpTypes: " ++ show op ++ ", " ++ show e binOpTypes :: A.BinOp -> TExpr -> TExpr -> TypeM Type binOpTypes (A.RelOp r) e1 e2 | texprType e1 == texprType e2 = pure BoolType | otherwise = throwError $ show (e1,e2) ++ " are unsuitable arguments for " ++ show r binOpTypes op e1 e2 | isNum op = case (texprType e1, texprType e2) of (IntType, IntType) -> return IntType (DoubleType, DoubleType) -> return DoubleType _ -> throwError $ show (e1,e2) ++ " are unsuitable arguments for " ++ show op | isBool op = case (texprType e1, texprType e2) of (BoolType, BoolType) -> return BoolType _ -> throwError $ show (e1,e2) ++ " are unsuitable arguments for " ++ show op
scottgw/demonL
Language/DemonL/TypeCheck.hs
bsd-3-clause
8,711
0
18
2,874
3,039
1,519
1,520
222
17
-- | The data type definition for "Futhark.Analysis.Metrics", factored -- out to simplify the module import hierarchies when working on the -- test modules. module Futhark.Analysis.Metrics.Type (AstMetrics (..)) where import qualified Data.Map.Strict as M import Data.Text (Text) import qualified Data.Text as T -- | AST metrics are simply a collection from identifiable node names -- to the number of times that node appears. newtype AstMetrics = AstMetrics (M.Map Text Int) instance Show AstMetrics where show (AstMetrics m) = unlines $ map metric $ M.toList m where metric (k, v) = T.unpack k ++ " " ++ show v instance Read AstMetrics where readsPrec _ s = maybe [] success $ mapM onLine $ lines s where onLine l = case words l of [k, x] | [(n, "")] <- reads x -> Just (T.pack k, n) _ -> Nothing success m = [(AstMetrics $ M.fromList m, "")]
diku-dk/futhark
src/Futhark/Analysis/Metrics/Type.hs
isc
899
0
16
201
273
148
125
15
0
{-# Language RebindableSyntax #-} module Symmetry.Language.Syntax where import Prelude (Int) import Symmetry.Language.AST -- Import this module and use with the RebindableSyntax Language extension (+) :: DSL repr => repr Int -> repr Int -> repr Int m + n = plus m n (>>=) :: Symantics repr => repr (Process repr a) -> (repr a -> repr (Process repr b)) -> repr (Process repr b) m >>= f = bind m (lam f) (>>) :: Symantics repr => repr (Process repr a) -> repr (Process repr b) -> repr (Process repr b) m >> n = bind m (lam (\_ -> n)) fail :: Symantics repr => repr (Process repr a) fail = die return :: Symantics repr => repr a -> repr (Process repr a) return = ret x |> f = app f x
gokhankici/symmetry
checker/src/Symmetry/Language/Syntax.hs
mit
745
0
12
200
321
160
161
21
1
module TypeBug2 where f :: a -> [a] -> [a] f sep (x:xs) = x:sep++f xs
roberth/uu-helium
test/typeerrors/Examples/TypeBug2.hs
gpl-3.0
73
0
7
19
51
28
23
3
1
-- | -- Module: Main -- Description: Tests for Command Wrapper Subcommand library. -- Copyright: (c) 2019-2020 Peter Trško -- License: BSD3 -- -- Maintainer: [email protected] -- Stability: experimental -- Portability: GHC specific language extensions; POSIX. -- -- Tests for Command Wrapper Subcommand library. module Main ( main ) where import System.IO (IO) --import Data.CallStack (HasCallStack) import Test.Tasty (TestTree, defaultMain, testGroup) --import Test.Tasty.HUnit ((@?=), testCase, assertFailure) main :: IO () main = defaultMain (testGroup "CommandWrapper.Subcommand.Tests" tests) tests :: [TestTree] tests = [ ]
trskop/command-wrapper
command-wrapper-subcommand/test/Main.hs
bsd-3-clause
671
0
7
120
89
57
32
9
1
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE Rank2Types #-} module YesodCoreTest.Cache ( cacheTest , Widget , resourcesC ) where import Test.Hspec import Network.Wai import Network.Wai.Test import Yesod.Core import UnliftIO.IORef import Data.Typeable (Typeable) import qualified Data.ByteString.Lazy.Char8 as L8 data C = C newtype V1 = V1 Int deriving Typeable newtype V2 = V2 Int deriving Typeable mkYesod "C" [parseRoutes| / RootR GET /key KeyR GET /nested NestedR GET /nested-key NestedKeyR GET |] instance Yesod C where errorHandler e = liftIO (print e) >> defaultErrorHandler e getRootR :: Handler RepPlain getRootR = do ref <- newIORef 0 V1 v1a <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1) V1 v1b <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1) V2 v2a <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) V2 v2b <- cached $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) return $ RepPlain $ toContent $ show [v1a, v1b, v2a, v2b] getKeyR :: Handler RepPlain getKeyR = do ref <- newIORef 0 V1 v1a <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1) V1 v1b <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V1 $ i + 1) V2 v2a <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) V2 v2b <- cachedBy "1" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) V2 v3a <- cachedBy "2" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) V2 v3b <- cachedBy "2" $ atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) return $ RepPlain $ toContent $ show [v1a, v1b, v2a, v2b, v3a, v3b] getNestedR :: Handler RepPlain getNestedR = getNested cached getNestedKeyR :: Handler RepPlain getNestedKeyR = getNested $ cachedBy "3" -- | Issue #1266 getNested :: (forall a. Typeable a => (Handler a -> Handler a)) -> Handler RepPlain getNested cacheMethod = do ref <- newIORef 0 let getV2 = atomicModifyIORef ref $ \i -> (i + 1, V2 $ i + 1) V1 _ <- cacheMethod $ do V2 val <- cacheMethod $ getV2 return $ V1 val V2 v2 <- cacheMethod $ getV2 return $ RepPlain $ toContent $ show v2 cacheTest :: Spec cacheTest = describe "Test.Cache" $ do it "cached" $ runner $ do res <- request defaultRequest assertStatus 200 res assertBody (L8.pack $ show [1, 1, 2, 2 :: Int]) res it "cachedBy" $ runner $ do res <- request defaultRequest { pathInfo = ["key"] } assertStatus 200 res assertBody (L8.pack $ show [1, 1, 2, 2, 3, 3 :: Int]) res it "nested cached" $ runner $ do res <- request defaultRequest { pathInfo = ["nested"] } assertStatus 200 res assertBody (L8.pack $ show (1 :: Int)) res it "nested cachedBy" $ runner $ do res <- request defaultRequest { pathInfo = ["nested-key"] } assertStatus 200 res assertBody (L8.pack $ show (1 :: Int)) res runner :: Session () -> IO () runner f = toWaiApp C >>= runSession f
s9gf4ult/yesod
yesod-core/test/YesodCoreTest/Cache.hs
mit
3,157
0
15
788
1,258
634
624
76
1
{- | Module : $Header$ Description : Navigation through the Development Graph Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : non-portable (via imports) Navigation through the Development Graph based on Node and Link predicates using Depth First Search. -} module Static.DGNavigation where import Static.DevGraph import qualified Data.Set as Set import Data.List import Data.Maybe import Data.Graph.Inductive.Graph as Graph import Logic.Grothendieck import Common.Doc import Common.DocUtils import Syntax.AS_Library -- * Navigator Class class DevGraphNavigator a where -- | get all the incoming ledges of the given node incoming :: a -> Node -> [LEdge DGLinkLab] -- | get the label of the given node getLabel :: a -> Node -> DGNodeLab -- | get the local (not referenced) environment of the given node getLocalNode :: a -> Node -> (DGraph, LNode DGNodeLab) getInLibEnv :: a -> (LibEnv -> DGraph -> b) -> b getCurrent :: a -> [LNode DGNodeLab] relocate :: a -> DGraph -> [LNode DGNodeLab] -> a {- | Get all the incoming ledges of the given node and eventually cross the border to an other 'DGraph'. The new 'DevGraphNavigator' is returned with 'DGraph' set to the new graph and current node to the given node. -} followIncoming :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab, [LEdge DGLinkLab]) followIncoming dgn n = (dgn', lbln, incoming dgn' n') where (dgn', lbln@(n', _)) = followNode dgn n -- | get the local (not referenced) label of the given node getLocalLabel :: DevGraphNavigator a => a -> Node -> DGNodeLab getLocalLabel dgnav = snd . snd . getLocalNode dgnav followNode :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab) followNode dgnav n = (relocate dgnav dg [lbln], lbln) where (dg, lbln) = getLocalNode dgnav n -- | get all the incoming ledges of the current node directInn :: DevGraphNavigator a => a -> [LEdge DGLinkLab] directInn dgnav = concatMap (incoming dgnav . fst) $ getCurrent dgnav -- * Navigator Instance {- | The navigator instance consists of a 'LibEnv' a current 'DGraph' and a current 'Node' which is the starting point for navigation through the DG. -} data DGNav = DGNav { dgnLibEnv :: LibEnv , dgnDG :: DGraph , dgnCurrent :: [LNode DGNodeLab] } deriving Show instance Pretty DGNav where pretty dgn = d1 <> text ":" <+> pretty (map fst $ dgnCurrent dgn) where d1 = case optLibDefn $ dgnDG dgn of Just (Lib_defn ln _ _ _) -> pretty ln Nothing -> text "DG" makeDGNav :: LibEnv -> DGraph -> [LNode DGNodeLab] -> DGNav makeDGNav le dg cnl = DGNav le dg cnl' where cnl' | null cnl = filter f $ labNodesDG dg | otherwise = cnl where f (n, _) = not $ any isDefLink $ outDG dg n isDefLink :: LEdge DGLinkLab -> Bool isDefLink = isDefEdge . dgl_type . linkLabel instance DevGraphNavigator DGNav where -- we consider only the definition links in a DGraph incoming dgn = filter isDefLink . innDG (dgnDG dgn) getLabel = labDG . dgnDG getLocalNode (DGNav {dgnLibEnv = le, dgnDG = dg}) = lookupLocalNode le dg getInLibEnv (DGNav {dgnLibEnv = le, dgnDG = dg}) f = f le dg getCurrent (DGNav {dgnCurrent = lblnl}) = lblnl relocate dgn dg lblnl = dgn { dgnDG = dg, dgnCurrent = lblnl } -- * Basic search functionality -- | DFS based search firstMaybe :: (a -> Maybe b) -> [a] -> Maybe b firstMaybe _ [] = Nothing firstMaybe f (x : l) = case f x of Nothing -> firstMaybe f l y -> y {- | Searches all ancestor nodes of the current node and also the current node for a node matching the given predicate -} searchNode :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Maybe (a, LNode DGNodeLab) searchNode p dgnav = firstMaybe (searchNodeFrom p dgnav . fst) $ getCurrent dgnav searchNodeFrom :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Node -> Maybe (a, LNode DGNodeLab) searchNodeFrom p dgnav n = let (dgnav', lbln, ledgs) = followIncoming dgnav n in if p lbln then Just (dgnav', lbln) else firstMaybe (searchNodeFrom p dgnav') $ map linkSource ledgs searchLink :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Maybe (a, LEdge DGLinkLab) searchLink p dgnav = firstMaybe (searchLinkFrom p dgnav . fst) $ getCurrent dgnav searchLinkFrom :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Node -> Maybe (a, LEdge DGLinkLab) searchLinkFrom p dgnav n = let (dgnav', _, ledgs) = followIncoming dgnav n in case find p ledgs of Nothing -> firstMaybe (searchLinkFrom p dgnav') $ map linkSource ledgs x -> fmap ((,) dgnav') x -- * Predicates to be used with 'searchNode' -- | This predicate is true for nodes with a nodename equal to the given string dgnPredName :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredName n nd@(_, lbl) = if getDGNodeName lbl == n then Just nd else Nothing {- | This predicate is true for nodes which are instantiations of a specification with the given name -} dgnPredParameterized :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredParameterized n nd@(_, DGNodeLab { nodeInfo = DGNode { node_origin = DGInst sid } }) | show sid == n = Just nd | otherwise = Nothing dgnPredParameterized _ _ = Nothing {- * Predicates to be used with 'searchLink' This predicate is true for links which are argument instantiations of a parameterized specification with the given name -} dglPredActualParam :: String -> LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredActualParam n edg@(_, _, DGLink { dgl_origin = DGLinkInstArg sid }) | show sid == n = Just edg | otherwise = Nothing dglPredActualParam _ _ = Nothing -- | This predicate is true for links which are instantiation morphisms dglPredInstance :: LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredInstance edg@(_, _, DGLink { dgl_origin = DGLinkMorph _ }) = Just edg dglPredInstance _ = Nothing -- * Combined Node Queries -- | Search for the given name in an actual parameter link getActualParameterSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getActualParameterSpec n dgnav = -- search first actual param case searchLink (isJust . dglPredActualParam n) dgnav of Nothing -> Nothing Just (dgn', (sn, _, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in an instantiation node getParameterizedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getParameterizedSpec n dgnav = -- search first actual param case searchNode (isJust . dgnPredParameterized n) dgnav of Nothing -> Nothing Just (dgn', (sn, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in any node getNamedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getNamedSpec n = searchNode (isJust . dgnPredName n) -- | Combining a search function with an operation on nodes fromSearchResult :: (DevGraphNavigator a) => (a -> Maybe (a, LNode DGNodeLab)) -> (a -> Node -> b) -> a -> Maybe b fromSearchResult sf f dgnav = case sf dgnav of Just (dgn', (n, _)) -> Just $ f dgn' n _ -> Nothing -- * Other utils getLocalSyms :: DevGraphNavigator a => a -> Node -> Set.Set G_symbol getLocalSyms dgnav n = case dgn_origin $ getLocalLabel dgnav n of DGBasicSpec _ _ s -> s _ -> Set.empty linkSource :: LEdge a -> Node linkLabel :: LEdge a -> a linkSource (x, _, _) = x linkLabel (_, _, x) = x
nevrenato/HetsAlloy
Static/DGNavigation.hs
gpl-2.0
8,358
0
14
2,163
2,286
1,179
1,107
128
2
module Distribution.Client.Dependency.Modular.Builder where -- Building the search tree. -- -- In this phase, we build a search tree that is too large, i.e, it contains -- invalid solutions. We keep track of the open goals at each point. We -- nondeterministically pick an open goal (via a goal choice node), create -- subtrees according to the index and the available solutions, and extend the -- set of open goals by superficially looking at the dependencies recorded in -- the index. -- -- For each goal, we keep track of all the *reasons* why it is being -- introduced. These are for debugging and error messages, mainly. A little bit -- of care has to be taken due to the way we treat flags. If a package has -- flag-guarded dependencies, we cannot introduce them immediately. Instead, we -- store the entire dependency. import Control.Monad.Reader hiding (sequence, mapM) import Data.List as L import Data.Map as M import Prelude hiding (sequence, mapM) import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree -- | The state needed during the build phase of the search tree. data BuildState = BS { index :: Index, -- ^ information about packages and their dependencies scope :: Scope, -- ^ information about encapsulations rdeps :: RevDepMap, -- ^ set of all package goals, completed and open, with reverse dependencies open :: PSQ OpenGoal (), -- ^ set of still open goals (flag and package goals) next :: BuildType -- ^ kind of node to generate next } -- | Extend the set of open goals with the new goals listed. -- -- We also adjust the map of overall goals, and keep track of the -- reverse dependencies of each of the goals. extendOpen :: QPN -> [OpenGoal] -> BuildState -> BuildState extendOpen qpn' gs s@(BS { rdeps = gs', open = o' }) = go gs' o' gs where go :: RevDepMap -> PSQ OpenGoal () -> [OpenGoal] -> BuildState go g o [] = s { rdeps = g, open = o } go g o (ng@(OpenGoal (Flagged _ _ _ _) _gr) : ngs) = go g (cons ng () o) ngs go g o (ng@(OpenGoal (Stanza _ _ ) _gr) : ngs) = go g (cons ng () o) ngs go g o (ng@(OpenGoal (Simple (Dep qpn _)) _gr) : ngs) | qpn == qpn' = go g o ngs -- we ignore self-dependencies at this point; TODO: more care may be needed | qpn `M.member` g = go (M.adjust (qpn':) qpn g) o ngs | otherwise = go (M.insert qpn [qpn'] g) (cons ng () o) ngs -- code above is correct; insert/adjust have different arg order -- | Update the current scope by taking into account the encapsulations that -- are defined for the current package. establishScope :: QPN -> Encaps -> BuildState -> BuildState establishScope (Q pp pn) ecs s = s { scope = L.foldl (\ m e -> M.insert e pp' m) (scope s) ecs } where pp' = pn : pp -- new path -- | Given the current scope, qualify all the package names in the given set of -- dependencies and then extend the set of open goals accordingly. scopedExtendOpen :: QPN -> I -> QGoalReasonChain -> FlaggedDeps PN -> FlagInfo -> BuildState -> BuildState scopedExtendOpen qpn i gr fdeps fdefs s = extendOpen qpn gs s where sc = scope s qfdeps = L.map (fmap (qualify sc)) fdeps -- qualify all the package names qfdefs = L.map (\ (fn, b) -> Flagged (FN (PI qpn i) fn) b [] []) $ M.toList fdefs gs = L.map (flip OpenGoal gr) (qfdeps ++ qfdefs) data BuildType = Goals | OneGoal OpenGoal | Instance QPN I PInfo QGoalReasonChain build :: BuildState -> Tree (QGoalReasonChain, Scope) build = ana go where go :: BuildState -> TreeF (QGoalReasonChain, Scope) BuildState -- If we have a choice between many goals, we just record the choice in -- the tree. We select each open goal in turn, and before we descend, remove -- it from the queue of open goals. go bs@(BS { rdeps = rds, open = gs, next = Goals }) | P.null gs = DoneF rds | otherwise = GoalChoiceF (P.mapWithKey (\ g (_sc, gs') -> bs { next = OneGoal g, open = gs' }) (P.splits gs)) -- If we have already picked a goal, then the choice depends on the kind -- of goal. -- -- For a package, we look up the instances available in the global info, -- and then handle each instance in turn. go bs@(BS { index = idx, scope = sc, next = OneGoal (OpenGoal (Simple (Dep qpn@(Q _ pn) _)) gr) }) = case M.lookup pn idx of Nothing -> FailF (toConflictSet (Goal (P qpn) gr)) (BuildFailureNotInIndex pn) Just pis -> PChoiceF qpn (gr, sc) (P.fromList (L.map (\ (i, info) -> (i, bs { next = Instance qpn i info gr })) (M.toList pis))) -- TODO: data structure conversion is rather ugly here -- For a flag, we create only two subtrees, and we create them in the order -- that is indicated by the flag default. -- -- TODO: Should we include the flag default in the tree? go bs@(BS { scope = sc, next = OneGoal (OpenGoal (Flagged qfn@(FN (PI qpn _) _) (FInfo b m) t f) gr) }) = FChoiceF qfn (gr, sc) trivial m (P.fromList (reorder b [(True, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn True : gr)) t) bs) { next = Goals }), (False, (extendOpen qpn (L.map (flip OpenGoal (FDependency qfn False : gr)) f) bs) { next = Goals })])) where reorder True = id reorder False = reverse trivial = L.null t && L.null f go bs@(BS { scope = sc, next = OneGoal (OpenGoal (Stanza qsn@(SN (PI qpn _) _) t) gr) }) = SChoiceF qsn (gr, sc) trivial (P.fromList [(False, bs { next = Goals }), (True, (extendOpen qpn (L.map (flip OpenGoal (SDependency qsn : gr)) t) bs) { next = Goals })]) where trivial = L.null t -- For a particular instance, we change the state: we update the scope, -- and furthermore we update the set of goals. -- -- TODO: We could inline this above. go bs@(BS { next = Instance qpn i (PInfo fdeps fdefs ecs _) gr }) = go ((establishScope qpn ecs (scopedExtendOpen qpn i (PDependency (PI qpn i) : gr) fdeps fdefs bs)) { next = Goals }) -- | Interface to the tree builder. Just takes an index and a list of package names, -- and computes the initial state and then the tree from there. buildTree :: Index -> Bool -> [PN] -> Tree (QGoalReasonChain, Scope) buildTree idx ind igs = build (BS idx sc (M.fromList (L.map (\ qpn -> (qpn, [])) qpns)) (P.fromList (L.map (\ qpn -> (OpenGoal (Simple (Dep qpn (Constrained []))) [UserGoal], ())) qpns)) Goals) where sc | ind = makeIndependent igs | otherwise = emptyScope qpns = L.map (qualify sc) igs
jwiegley/ghc-release
libraries/Cabal/cabal-install/Distribution/Client/Dependency/Modular/Builder.hs
gpl-3.0
7,494
0
23
2,257
1,971
1,083
888
77
7
{-# LANGUAGE CPP #-} module Distribution.Solver.Modular.Cycles ( detectCyclesPhase ) where import Prelude hiding (cycle) import Data.Graph (SCC) import qualified Data.Graph as Gr import qualified Data.Map as Map import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.Tree import qualified Distribution.Solver.Modular.ConflictSet as CS -- | Find and reject any solutions that are cyclic detectCyclesPhase :: Tree QGoalReason -> Tree QGoalReason detectCyclesPhase = cata go where -- The only node of interest is DoneF go :: TreeF QGoalReason (Tree QGoalReason) -> Tree QGoalReason go (PChoiceF qpn gr cs) = PChoice qpn gr cs go (FChoiceF qfn gr w m cs) = FChoice qfn gr w m cs go (SChoiceF qsn gr w cs) = SChoice qsn gr w cs go (GoalChoiceF cs) = GoalChoice cs go (FailF cs reason) = Fail cs reason -- We check for cycles only if we have actually found a solution -- This minimizes the number of cycle checks we do as cycles are rare go (DoneF revDeps) = do case findCycles revDeps of Nothing -> Done revDeps Just relSet -> Fail relSet CyclicDependencies -- | Given the reverse dependency map from a 'Done' node in the tree, as well -- as the full conflict set containing all decisions that led to that 'Done' -- node, check if the solution is cyclic. If it is, return the conflict set -- containing all decisions that could potentially break the cycle. findCycles :: RevDepMap -> Maybe (ConflictSet QPN) findCycles revDeps = case cycles of [] -> Nothing c:_ -> Just $ CS.unions $ map (varToConflictSet . P) c where cycles :: [[QPN]] cycles = [vs | Gr.CyclicSCC vs <- scc] scc :: [SCC QPN] scc = Gr.stronglyConnComp . map aux . Map.toList $ revDeps aux :: (QPN, [(comp, QPN)]) -> (QPN, QPN, [QPN]) aux (fr, to) = (fr, fr, map snd to)
headprogrammingczar/cabal
cabal-install/Distribution/Solver/Modular/Cycles.hs
bsd-3-clause
1,962
0
12
460
511
280
231
34
7
foo = last (sortBy (compare `on` fst) xs)
mpickering/hlint-refactor
tests/examples/Default104.hs
bsd-3-clause
41
0
9
7
26
14
12
1
1
-- Simple StatusIcon example import Graphics.UI.Gtk main = do initGUI icon <- statusIconNewFromStock stockQuit statusIconSetVisible icon True statusIconSetTooltipText icon $ Just "This is a test" menu <- mkmenu icon on icon statusIconPopupMenu $ \b a -> do widgetShowAll menu print (b,a) menuPopup menu $ maybe Nothing (\b' -> Just (b',a)) b on icon statusIconActivate $ do putStrLn "'activate' signal triggered" mainGUI mkmenu s = do m <- menuNew mapM_ (mkitem m) [("Quit",mainQuit)] return m where mkitem menu (label,act) = do i <- menuItemNewWithLabel label menuShellAppend menu i on i menuItemActivated act
k0001/gtk2hs
gtk/demo/statusicon/StatusIcon.hs
gpl-3.0
725
0
16
205
239
109
130
22
1
-- Ensure that readInt and readInteger over lazy ByteStrings are not -- excessively strict. module Main (main) where import Data.ByteString.Char8 (pack) import Data.ByteString.Lazy.Char8 (readInt, readInteger) import Data.ByteString.Lazy.Internal (ByteString(..)) main :: IO () main = do let safe = Chunk (pack "1z") Empty let unsafe = Chunk (pack "2z") undefined print . fmap fst . readInt $ safe print . fmap fst . readInt $ unsafe print . fmap fst . readInteger $ safe print . fmap fst . readInteger $ unsafe
meiersi/bytestring-builder
tests/lazyread.hs
bsd-3-clause
529
0
12
98
180
94
86
12
1
module PackageTests.TestStanza.Check where import PackageTests.PackageTester import Distribution.Version import Distribution.Simple.LocalBuildInfo import Distribution.Package import Distribution.PackageDescription suite :: TestM () suite = do assertOutputDoesNotContain "unknown section type" =<< cabal' "configure" [] dist_dir <- distDir lbi <- liftIO $ getPersistBuildConfig dist_dir let anticipatedTestSuite = emptyTestSuite { testName = "dummy" , testInterface = TestSuiteExeV10 (Version [1,0] []) "dummy.hs" , testBuildInfo = emptyBuildInfo { targetBuildDepends = [ Dependency (PackageName "base") anyVersion ] , hsSourceDirs = ["."] } , testEnabled = False } gotTestSuite = head $ testSuites (localPkgDescr lbi) assertEqual "parsed test-suite stanza does not match anticipated" anticipatedTestSuite gotTestSuite return ()
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/tests/PackageTests/TestStanza/Check.hs
bsd-3-clause
1,047
0
17
314
209
111
98
24
1
{-# LANGUAGE DeriveGeneric #-} {-| Module : Idris.Colours Description : Support for colours within Idris. Copyright : License : BSD3 Maintainer : The Idris Community. -} module Idris.Colours ( IdrisColour(..) , ColourTheme(..) , defaultTheme , colouriseKwd, colouriseBound, colouriseImplicit, colourisePostulate , colouriseType, colouriseFun, colouriseData, colouriseKeyword , colourisePrompt, colourise, ColourType(..), hStartColourise, hEndColourise ) where import GHC.Generics (Generic) import System.Console.ANSI import System.IO (Handle) data IdrisColour = IdrisColour { colour :: Maybe Color , vivid :: Bool , underline :: Bool , bold :: Bool , italic :: Bool } deriving (Eq, Show) mkColour :: Color -> IdrisColour mkColour c = IdrisColour (Just c) True False False False data ColourTheme = ColourTheme { keywordColour :: IdrisColour , boundVarColour :: IdrisColour , implicitColour :: IdrisColour , functionColour :: IdrisColour , typeColour :: IdrisColour , dataColour :: IdrisColour , promptColour :: IdrisColour , postulateColour :: IdrisColour } deriving (Eq, Show, Generic) -- | Idris's default console colour theme defaultTheme :: ColourTheme defaultTheme = ColourTheme { keywordColour = IdrisColour Nothing True False True False , boundVarColour = mkColour Magenta , implicitColour = IdrisColour (Just Magenta) True True False False , functionColour = mkColour Green , typeColour = mkColour Blue , dataColour = mkColour Red , promptColour = IdrisColour Nothing True False True False , postulateColour = IdrisColour (Just Green) True False True False } -- | Compute the ANSI colours corresponding to an Idris colour mkSGR :: IdrisColour -> [SGR] mkSGR (IdrisColour c v u b i) = fg c ++ [SetUnderlining SingleUnderline | u] ++ [SetConsoleIntensity BoldIntensity | b] ++ [SetItalicized True | i] where fg Nothing = [] fg (Just c) = [SetColor Foreground (if v then Vivid else Dull) c] -- | Set the colour of a string using POSIX escape codes colourise :: IdrisColour -> String -> String colourise c str = setSGRCode (mkSGR c) ++ str ++ setSGRCode [Reset] -- | Start a colour on a handle, to support colour output on Windows hStartColourise :: Handle -> IdrisColour -> IO () hStartColourise h c = hSetSGR h (mkSGR c) -- | End a colour region on a handle hEndColourise :: Handle -> IdrisColour -> IO () hEndColourise h _ = hSetSGR h [Reset] -- | Set the colour of a string using POSIX escape codes, with trailing '\STX' denoting the end -- (required by Haskeline in the prompt string) colouriseWithSTX :: IdrisColour -> String -> String colouriseWithSTX (IdrisColour c v u b i) str = setSGRCode sgr ++ "\STX" ++ str ++ setSGRCode [Reset] ++ "\STX" where sgr = fg c ++ [SetUnderlining SingleUnderline | u] ++ [SetConsoleIntensity BoldIntensity | b] ++ [SetItalicized True | i] fg Nothing = [] fg (Just c) = [SetColor Foreground (if v then Vivid else Dull) c] colouriseKwd :: ColourTheme -> String -> String colouriseKwd t = colourise (keywordColour t) colouriseBound :: ColourTheme -> String -> String colouriseBound t = colourise (boundVarColour t) colouriseImplicit :: ColourTheme -> String -> String colouriseImplicit t = colourise (implicitColour t) colouriseFun :: ColourTheme -> String -> String colouriseFun t = colourise (functionColour t) colouriseType :: ColourTheme -> String -> String colouriseType t = colourise (typeColour t) colouriseData :: ColourTheme -> String -> String colouriseData t = colourise (dataColour t) colourisePrompt :: ColourTheme -> String -> String colourisePrompt t = colouriseWithSTX (promptColour t) colouriseKeyword :: ColourTheme -> String -> String colouriseKeyword t = colourise (keywordColour t) colourisePostulate :: ColourTheme -> String -> String colourisePostulate t = colourise (postulateColour t) data ColourType = KeywordColour | BoundVarColour | ImplicitColour | FunctionColour | TypeColour | DataColour | PromptColour | PostulateColour deriving (Eq, Show, Bounded, Enum)
uuhan/Idris-dev
src/Idris/Colours.hs
bsd-3-clause
4,896
0
11
1,558
1,113
603
510
86
3