code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} module Utils ( roundTo , i2d ) where import GHC.Base (Int(I#), Char(C#), chr#, ord#, (+#)) roundTo :: Int -> [Int] -> (Int, [Int]) roundTo d is = case f d True is of x@(0,_) -> x (1,xs) -> (1, 1:xs) _ -> error "roundTo: bad Value" where base = 10 b2 = base `quot` 2 f n _ [] = (0, replicate n 0) f 0 e (x:xs) | x == b2 && e && all (== 0) xs = (0, []) -- Round to even when at exactly half the base | otherwise = (if x >= b2 then 1 else 0, []) f n _ (i:xs) | i' == base = (1,0:ds) | otherwise = (0,i':ds) where (c,ds) = f (n-1) (even i) xs i' = c + i -- | Unsafe conversion for decimal digits. {-# INLINE i2d #-} i2d :: Int -> Char i2d (I# i#) = C# (chr# (ord# '0'# +# i# ))
phadej/scientific
src/Utils.hs
bsd-3-clause
868
0
12
276
411
229
182
26
6
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "System/EasyFile/Missing.hs" #-} {-# LANGUAGE CPP #-} module System.EasyFile.Missing where ---------------------------------------------------------------- import Control.Applicative import Data.Time import Data.Time.Clock.POSIX import Data.Word (Word64) import System.Posix.Files import System.Posix.Types ---------------------------------------------------------------- {-| This function tells whether or not a file\/directory is symbolic link. -} isSymlink :: FilePath -> IO Bool isSymlink file = isSymbolicLink <$> getSymbolicLinkStatus file {-| This function returns the link counter of a file\/directory. -} getLinkCount :: FilePath -> IO (Maybe Int) getLinkCount file = Just . fromIntegral . linkCount <$> getFileStatus file {-| This function returns whether or not a directory has sub-directories. -} hasSubDirectories :: FilePath -> IO (Maybe Bool) hasSubDirectories file = do Just n <- getLinkCount file return $ Just (n > 2) ---------------------------------------------------------------- {-| The 'getCreationTime' operation returns the UTC time at which the file or directory was created. The time is only available on Windows. -} getCreationTime :: FilePath -> IO (Maybe UTCTime) getCreationTime _ = return Nothing {-| The 'getChangeTime' operation returns the UTC time at which the file or directory was changed. The time is only available on Unix and Mac. Note that Unix's rename() does not change ctime but MacOS's rename() does. -} getChangeTime :: FilePath -> IO (Maybe UTCTime) getChangeTime file = Just . epochTimeToUTCTime . statusChangeTime <$> getFileStatus file {-| The 'getModificationTime' operation returns the UTC time at which the file or directory was last modified. The operation may fail with: * 'isPermissionError' if the user is not permitted to access the modification time; or * 'isDoesNotExistError' if the file or directory does not exist. -} getModificationTime :: FilePath -> IO UTCTime getModificationTime file = epochTimeToUTCTime . modificationTime <$> getFileStatus file {- http://msdn.microsoft.com/en-us/library/ms724290%28VS.85%29.aspx The NTFS file system delays updates to the last access time for a file by up to 1 hour after the last access. -} {-| The 'getModificationTime' operation returns the UTC time at which the file or directory was last accessed. -} getAccessTime :: FilePath -> IO UTCTime getAccessTime file = epochTimeToUTCTime . accessTime <$> getFileStatus file ---------------------------------------------------------------- epochTimeToUTCTime :: EpochTime -> UTCTime epochTimeToUTCTime = posixSecondsToUTCTime . realToFrac -- | Getting the size of the file. getFileSize :: FilePath -> IO Word64 getFileSize file = fromIntegral . fileSize <$> getFileStatus file
phischu/fragnix
tests/packages/scotty/System.EasyFile.Missing.hs
bsd-3-clause
2,864
0
10
465
367
194
173
30
1
{- Copyright 2017 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 Block.Block (Type(..) ,Input(..) ,BlockI(..) ) where import qualified Data.Map -- input : name type connectedBlock data Type = Number | Bool | Color | Picture | Program | Poly Int | Empty data Input = Input Type Block | Text Type String | Disconnected deriving Show data Block = Block {name :: String, inputs :: M.Map String Input, outputType :: Type}
venkat24/codeworld
funblocks-client/src/Blocks/Block.hs
apache-2.0
1,120
0
10
328
122
77
45
16
0
{- | Module : $Id$ Copyright : (c) DFKI GmbH License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable utilities for writing new rules. -} module RuleUtils where import Text.PrettyPrint.HughesPJ import DataP (Statement (..), Data (..), Type (..), Class, Body (..), Constructor) -- Rule Declarations type Tag = String type Rule = (Tag, Data -> Doc) type RuleDef = (Tag, Data -> Doc, String, String, Maybe String) rArrow :: Doc rArrow = text "->" lArrow :: Doc lArrow = text "<-" prettyType :: Type -> Doc prettyType (Arrow x y) = parens (prettyType x <+> text "->" <+> prettyType y) prettyType (List x) = brackets (prettyType x) prettyType (Tuple xs) = tuple (map prettyType xs) prettyType (Var s) = text s prettyType (Con s) = text s prettyType (LApply t ts) = prettyType t <+> hsep (map prettyType ts) -- New Pretty Printers --------------- texts :: [String] -> [Doc] texts = map text block, parenList, bracketList :: [Doc] -> Doc block = nest 4 . vcat parenList = parens . fsep . sepWith comma bracketList = brackets . fsep . sepWith comma -- for bulding m1 >> m2 >> m3, f . g . h, etc sepWith :: Doc -> [Doc] -> [Doc] sepWith _ [] = [] sepWith _ [x] = [x] sepWith a (x : xs) = (x <> a) : sepWith a xs -- optional combinator, applys fn if arg is non-[] opt :: [a] -> ([a] -> Doc) -> Doc opt [] _ = empty opt a f = f a -- equivalent of `opt' for singleton lists opt1 :: [a] -> ([a] -> Doc) -> (a -> Doc) -> Doc opt1 [] _ _ = empty opt1 [x] _ g = g x opt1 a f _ = f a -- new simple docs commentLine :: Doc -> Doc commentLine x = text "--" <+> x -- useful for warnings / error messages commentBlock :: Doc -> Doc commentBlock x = text "{-" <+> x <+> text "-}" -- - Utility Functions ------------------------------------------------------- -- Instances strippedName :: Data -> String strippedName = reverse . takeWhile (/= '.') . reverse . name -- instance header, handling class constraints etc. simpleInstance :: Class -> Data -> Doc simpleInstance s d = hsep [text "instance" , opt1 constr (\ x -> parenList x <+> text "=>") ( \ x -> x <+> text "=>") , text s , opt1 (texts (strippedName d : vars d)) parenSpace id] where constr = map (\ v -> text "Ord" <+> text v) (concatMap getSetVars . concatMap types $ body d) ++ map (\ (c, v) -> text c <+> text v) (constraints d) ++ map (\ x -> text s <+> text x) (vars d) parenSpace = parens . hsep getSetVars :: Type -> [String] getSetVars ty = case ty of LApply (Con "Set.Set") [Var v] -> [v] _ -> [] {- instanceSkeleton handles most instance declarations, where instance functions are not related to one another. A member function is generated using a (IFunction,Doc) pair. The IFunction is applied to each body of the type, creating a block of pattern - matching cases. Default cases can be given using the Doc in the pair. If a default case is not required, set Doc to 'empty' -} type IFunction = Body -> Doc -- instance function instanceSkeleton :: Class -> [(IFunction, Doc)] -> Data -> Doc instanceSkeleton s ii d = (simpleInstance s d <+> text "where") $$ block functions where functions = concatMap f ii f (i, dflt) = map i (body d) ++ [dflt] -- little variable name generator, generates unique names a - z varNames :: [a] -> [Doc] varNames l = zipWith (const char) l ['a' .. 'z'] -- variant generating aa' - aZ' varNames' :: [a] -> [Doc] varNames' = map (<> char '\'') . varNames -- pattern matching a constructor and args pattern :: Constructor -> [a] -> Doc pattern c l = parens $ fsep (text c : varNames l) pattern_ :: Constructor -> [a] -> Doc pattern_ c l = parens $ fsep (text c : replicate (length l) (text "_")) pattern' :: Constructor -> [a] -> Doc pattern' c l = parens $ fsep (text c : varNames' l) -- test that a datatype has at least one record constructor hasRecord :: Data -> Bool hasRecord d = statement d == DataStmt && any (not . null . labels) (body d) tuple :: [Doc] -> Doc tuple xs = parens $ hcat (punctuate (char ',') xs)
spechub/Hets
utils/DrIFT-src/RuleUtils.hs
gpl-2.0
4,222
4
13
1,013
1,425
754
671
77
2
class Eq a where (==) :: a -> a -> Bool x == y = not (x /= y) (/=) :: a -> a -> Bool x /= y = not (x == y) infix 4 == infix 4 /= (&&) :: Bool -> Bool -> Bool (||) :: Bool -> Bool -> Bool -- listEq :: [a] -> [a] -> Bool -- listEq [] [] = True -- listEq (x:xs) (y:ys) = (x == y) && (listEq xs ys) member x [] = False member x (y:ys) = (x == y) || member x ys instance Eq Bool where True == True = True False == False = True _ == _ = False test = member True [True, False, False]
themattchan/tandoori
input/eq.hs
bsd-3-clause
577
0
9
222
230
122
108
16
1
module PackageTests.PathsModule.Executable.Check (suite) where import PackageTests.PackageTester (PackageSpec(..), assertBuildSucceeded, cabal_build) import System.FilePath import Test.Tasty.HUnit suite :: FilePath -> Assertion suite ghcPath = do let spec = PackageSpec { directory = "PackageTests" </> "PathsModule" </> "Executable" , distPref = Nothing , configOpts = [] } result <- cabal_build spec ghcPath assertBuildSucceeded result
Helkafen/cabal
Cabal/tests/PackageTests/PathsModule/Executable/Check.hs
bsd-3-clause
504
0
13
116
118
67
51
13
1
module ListSpec where import Control.Applicative import Language.Haskell.GhcMod import Test.Hspec spec :: Spec spec = do describe "listModules" $ do it "lists up module names" $ do cradle <- findCradle modules <- lines <$> listModules defaultOptions cradle modules `shouldContain` ["Data.Map"]
carlohamalainen/ghc-mod
test/ListSpec.hs
bsd-3-clause
344
0
15
89
85
44
41
11
1
{-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Ix -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- The 'Ix' class is used to map a contiguous subrange of values in -- type onto integers. It is used primarily for array indexing -- (see the array package). -- ----------------------------------------------------------------------------- module Data.Ix ( -- * The 'Ix' class Ix ( range , index , inRange , rangeSize ) -- Ix instances: -- -- Ix Char -- Ix Int -- Ix Integer -- Ix Bool -- Ix Ordering -- Ix () -- (Ix a, Ix b) => Ix (a, b) -- ... -- * Deriving Instances of 'Ix' -- | Derived instance declarations for the class 'Ix' are only possible -- for enumerations (i.e. datatypes having only nullary constructors) -- and single-constructor datatypes, including arbitrarily large tuples, -- whose constituent types are instances of 'Ix'. -- -- * For an enumeration, the nullary constructors are assumed to be -- numbered left-to-right with the indices being 0 to n-1 inclusive. This -- is the same numbering defined by the 'Enum' class. For example, given -- the datatype: -- -- > data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet -- -- we would have: -- -- > range (Yellow,Blue) == [Yellow,Green,Blue] -- > index (Yellow,Blue) Green == 1 -- > inRange (Yellow,Blue) Red == False -- -- * For single-constructor datatypes, the derived instance declarations -- are as shown for tuples in Figure 1 -- <http://www.haskell.org/onlinelibrary/ix.html#prelude-index>. ) where -- import Prelude import GHC.Arr
frantisekfarka/ghc-dsi
libraries/base/Data/Ix.hs
bsd-3-clause
2,048
0
5
571
76
69
7
12
0
{-# LANGUAGE FlexibleInstances #-} -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- module Thrift.Transport.Framed ( module Thrift.Transport , FramedTransport , openFramedTransport ) where import Thrift.Transport import Control.Monad (liftM) import Data.Int (Int32) import Data.Monoid (mappend, mempty) import Control.Concurrent.MVar import qualified Data.Binary as B import qualified Data.Binary.Builder as BB import qualified Data.ByteString.Lazy as LBS -- | FramedTransport wraps a given transport in framed mode. data FramedTransport t = FramedTransport { wrappedTrans :: t, -- ^ Underlying transport. writeBuffer :: WriteBuffer, -- ^ Write buffer. readBuffer :: ReadBuffer -- ^ Read buffer. } -- | Create a new framed transport which wraps the given transport. openFramedTransport :: Transport t => t -> IO (FramedTransport t) openFramedTransport trans = do wbuf <- newWriteBuffer rbuf <- newReadBuffer return FramedTransport{ wrappedTrans = trans, writeBuffer = wbuf, readBuffer = rbuf } instance Transport t => Transport (FramedTransport t) where tClose = tClose . wrappedTrans tRead trans n = do -- First, check the read buffer for any data. bs <- readBuf (readBuffer trans) n if LBS.null bs then -- When the buffer is empty, read another frame from the -- underlying transport. do len <- readFrame trans if len > 0 then tRead trans n else return bs else return bs tWrite trans = writeBuf (writeBuffer trans) tFlush trans = do bs <- flushBuf (writeBuffer trans) let szBs = B.encode $ (fromIntegral $ LBS.length bs :: Int32) tWrite (wrappedTrans trans) szBs tWrite (wrappedTrans trans) bs tFlush (wrappedTrans trans) tIsOpen = tIsOpen . wrappedTrans readFrame :: Transport t => FramedTransport t -> IO Int readFrame trans = do -- Read and decode the frame size. szBs <- tRead (wrappedTrans trans) 4 let sz = fromIntegral (B.decode szBs :: Int32) -- Read the frame and stuff it into the read buffer. bs <- tRead (wrappedTrans trans) sz fillBuf (readBuffer trans) bs -- Return the frame size so that the caller knows whether to expect -- something in the read buffer or not. return sz -- Mini IO buffers (stolen from HttpClient.hs) type WriteBuffer = MVar (BB.Builder) newWriteBuffer :: IO WriteBuffer newWriteBuffer = newMVar mempty writeBuf :: WriteBuffer -> LBS.ByteString -> IO () writeBuf w s = modifyMVar_ w $ return . (\builder -> builder `mappend` (BB.fromLazyByteString s)) flushBuf :: WriteBuffer -> IO (LBS.ByteString) flushBuf w = BB.toLazyByteString `liftM` swapMVar w mempty type ReadBuffer = MVar (LBS.ByteString) newReadBuffer :: IO ReadBuffer newReadBuffer = newMVar mempty fillBuf :: ReadBuffer -> LBS.ByteString -> IO () fillBuf r s = swapMVar r s >> return () readBuf :: ReadBuffer -> Int -> IO (LBS.ByteString) readBuf r n = modifyMVar r $ return . flipPair . LBS.splitAt (fromIntegral n) where flipPair (a, b) = (b, a)
YinYanfei/CadalWorkspace
thrift/src/thrift-0.8.0/lib/hs/src/Thrift/Transport/Framed.hs
gpl-3.0
3,889
0
15
855
847
452
395
63
1
module Main where main :: IO () main = do putStrLn "This is my-executable"
DavidAlphaFox/ghc
libraries/Cabal/cabal-install/tests/PackageTests/Exec/My.hs
bsd-3-clause
80
0
7
19
25
13
12
4
1
module Rebase.GHC.Arr ( module GHC.Arr ) where import GHC.Arr
nikita-volkov/rebase
library/Rebase/GHC/Arr.hs
mit
65
0
5
12
20
13
7
4
0
module RL.Generator.Dungeon (DungeonConfig(..), PlayerConfig(..), ItemConfig(..), levelGenerator, randomItemAppearances, module RL.Generator) where import RL.Map import RL.Generator import RL.Generator.Cells (cells, cmid, cpoint, CellConfig(CellConfig)) import RL.Generator.Paths (paths, getTileAt) import RL.Generator.Mobs (playerGenerator, mobGenerator, MobConfig(..), PlayerConfig(..)) import RL.Generator.Items import RL.Generator.Features import RL.Pathfinder import RL.Random (StdGen, pick) import RL.Util (comparing) import Control.Monad.Random (getSplit) import Control.Monad.Reader (ask) import Data.Maybe (fromMaybe, listToMaybe, isJust, fromJust, isNothing) import qualified Data.List as L data DungeonConfig = DungeonConfig { dwidth :: Int, dheight :: Int, maxTries :: Int, prevLevel :: Maybe DLevel, maxDepth :: Int, mobConfig :: MobConfig, itemConfig :: ItemConfig, playerConfig :: PlayerConfig, featureConfig :: FeatureConfig } instance GenConfig DungeonConfig where generating conf = (< maxTries conf) <$> getCounter levelGenerator :: Generator DungeonConfig s DLevel levelGenerator = do conf <- ask cs <- runGenerator' cells (mkCellConf conf) initState ps <- runGenerator' (paths cs) conf initState -- TODO ensure all reachable! player <- fromMaybe (error errPlayer) <$> runGenerator' playerGenerator (playerConfig conf) (mkGenState cs) let prev = prevLevel conf d = maybe 1 ((+1) . depth) prev lvl = toLevel conf d cs ps player -- generate features fs <- runGenerator' featuresGenerator (featureConfig conf) (mkGenState (lvl, cs)) let lvl' = lvl { features = L.filter (\(p,f) -> p /= at player) fs } g <- getSplit -- generate up/down stairs lastP <- pick (L.filter (\p -> isNothing (L.lookup p (features lvl')) && p /= at player) (map cmid cs)) let lvl'' = iterMap f lvl' f p t = if p == at player && not (isStair t) then (StairUp prev) else if Just p == lastP && d + 1 <= maxDepth conf then (StairDown nextLvl) else t nextLvl = fst (runGenerator levelGenerator (conf { prevLevel = Just lvl'' }) (initState g)) -- ensure we can reach the end if isJust lastP && isJust (findPath (dfinder lvl'' (fromJust lastP)) distance (fromJust lastP) (at player)) then do items <- runGenerator' itemsGenerator (itemConfig conf) (mkGenState lvl'') mobs <- runGenerator' mobGenerator (mobConfig conf) (mkGenState lvl'') return (lvl'' { mobs = mobs, items = items }) else levelGenerator where runGenerator' :: GenConfig c => Generator c s a -> c -> (StdGen -> GenState s) -> Generator DungeonConfig t a runGenerator' gen conf f = do g <- getSplit let r = runGenerator gen conf (f g) return (fst r) errPlayer = "No player generated" toLevel conf depth cs ps player = lvl { player = player } where lvl = iterMap fillDng (blankDng depth conf) fillDng p t = maybe t id $ getTileAt p cs ps blankDng depth conf = mkLevel depth $ blankMap (dwidth conf) (dheight conf) mkCellConf conf = CellConfig (dwidth conf) (dheight conf) (maxTries conf)
MichaelMackus/hsrl
RL/Generator/Dungeon.hs
mit
3,362
0
19
859
1,122
597
525
61
4
module Unison.Typechecker.Extractor where import Unison.Prelude hiding (whenM) import Control.Monad.Reader import qualified Data.List as List import Data.List.NonEmpty ( NonEmpty ) import qualified Data.Set as Set import Unison.Reference ( Reference ) import qualified Unison.Term as Term import qualified Unison.Type as Type import qualified Unison.Typechecker.Context as C import Unison.Util.Monoid ( whenM ) import qualified Unison.Blank as B import Unison.Var (Var) import qualified Unison.Var as Var import Unison.Type (Type) type RedundantTypeAnnotation = Bool type Extractor e a = MaybeT (Reader e) a type ErrorExtractor v loc a = Extractor (C.ErrorNote v loc) a type InfoExtractor v loc a = Extractor (C.InfoNote v loc) a type PathExtractor v loc a = Extractor (C.PathElement v loc) a type SubseqExtractor v loc a = SubseqExtractor' (C.ErrorNote v loc) a extractor :: (e -> Maybe a) -> Extractor e a extractor = MaybeT . reader extract :: Extractor e a -> e -> Maybe a extract = runReader . runMaybeT subseqExtractor :: (C.ErrorNote v loc -> [Ranged a]) -> SubseqExtractor v loc a subseqExtractor f = SubseqExtractor' f traceSubseq :: Show a => String -> SubseqExtractor' n a -> SubseqExtractor' n a traceSubseq s ex = SubseqExtractor' $ \n -> let rs = runSubseq ex n in trace (if null s then show rs else s ++ ": " ++ show rs) rs traceNote :: Show a => String -> ErrorExtractor v loc a -> ErrorExtractor v loc a traceNote s ex = extractor $ \n -> let result = extract ex n in trace (if null s then show result else s ++ ": " ++ show result) result unique :: SubseqExtractor v loc a -> ErrorExtractor v loc a unique ex = extractor $ \note -> case runSubseq ex note of [Pure a ] -> Just a [Ranged a _ _] -> Just a _ -> Nothing data SubseqExtractor' n a = SubseqExtractor' { runSubseq :: n -> [Ranged a] } data Ranged a = Pure a | Ranged { get :: a, start :: Int, end :: Int } deriving (Functor, Show) -- | collects the regions where `xa` doesn't match / aka invert a set of intervals -- unused, but don't want to delete it yet - Aug 30, 2018 _no :: SubseqExtractor' n a -> SubseqExtractor' n () _no xa = SubseqExtractor' $ \note -> let as = runSubseq xa note in if null [ a | Pure a <- as ] then -- results are not full if null as then [Pure ()] -- results are empty, make them full -- not full and not empty, find the negation else reverse . fst $ foldl' go ([], Nothing) (List.sort $ fmap toPairs as) else [] -- results were full, make them empty where toPairs :: Ranged a -> (Int, Int) toPairs (Pure _ ) = error "this case should be avoided by the if!" toPairs (Ranged _ start end) = (start, end) go :: ([Ranged ()], Maybe Int) -> (Int, Int) -> ([Ranged ()], Maybe Int) go ([] , Nothing) (0, r) = ([], Just (r + 1)) go ([] , Nothing) (l, r) = ([Ranged () 0 (l - 1)], Just r) go (_ : _, Nothing) _ = error "state machine bug in Extractor2.no" go (rs, Just r0) (l, r) = (if r0 + 1 <= l - 1 then Ranged () (r0 + 1) (l - 1) : rs else rs, Just r) -- unused / untested _any :: SubseqExtractor v loc () _any = _any' (\n -> pathLength n - 1) where pathLength :: C.ErrorNote v loc -> Int pathLength = length . toList . C.path _any' :: (n -> Int) -> SubseqExtractor' n () _any' getLast = SubseqExtractor' $ \note -> Pure () : do let last = getLast note start <- [0 .. last] end <- [0 .. last] pure $ Ranged () start end -- Kind of a newtype for Ranged.Ranged. -- The Eq instance ignores the embedded value data DistinctRanged a = DistinctRanged a Int Int instance Eq (DistinctRanged a) where DistinctRanged _ l r == DistinctRanged _ l' r' = l == l' && r == r' instance Ord (DistinctRanged a) where DistinctRanged _ l r <= DistinctRanged _ l' r' = l < l' || (l == l' && r <= r') -- todo: this could return NonEmpty some :: forall n a . SubseqExtractor' n a -> SubseqExtractor' n [a] some xa = SubseqExtractor' $ \note -> let as :: [Ranged a] as = runSubseq xa note -- Given a list of subseqs [Ranged a], find the adjacent groups [Ranged [a]]. -- `Pure`s arguably can't be adjacent; not sure what to do with them. Currently ignored. in fmap reverse <$> go Set.empty as where fromDistinct (DistinctRanged a l r) = Ranged a l r go :: Set (DistinctRanged [a]) -> [Ranged a] -> [Ranged [a]] go seen [] = fmap fromDistinct . toList $ seen go seen (rh@(Ranged h start end) : t) = let seen' :: Set (DistinctRanged [a]) seen' = Set.fromList . join . fmap (toList . consRange rh) . toList $ seen in go (Set.insert (DistinctRanged [h] start end) seen `Set.union` seen') t go seen (Pure _ : t) = go seen t consRange :: Ranged a -> DistinctRanged [a] -> Maybe (DistinctRanged [a]) consRange new group@(DistinctRanged as start' _) = if isAdjacent group new then Just (DistinctRanged (get new : as) start' (end new)) else Nothing -- Returns true if inputs are adjacent Ranged regions -- Question: Should a Pure be considered adjacent? isAdjacent :: forall a b . DistinctRanged a -> Ranged b -> Bool isAdjacent (DistinctRanged _ _ endA) (Ranged _ startB _) = endA + 1 == startB isAdjacent _ _ = False pathStart :: SubseqExtractor' n () pathStart = SubseqExtractor' $ \_ -> [Ranged () (-1) (-1)] -- Scopes -- asPathExtractor :: (C.PathElement v loc -> Maybe a) -> SubseqExtractor v loc a asPathExtractor = fromPathExtractor . extractor where fromPathExtractor :: PathExtractor v loc a -> SubseqExtractor v loc a fromPathExtractor ex = subseqExtractor $ join . fmap go . (`zip` [0 ..]) . toList . C.path where go (e, i) = case extract ex e of Just a -> [Ranged a i i] Nothing -> [] inSynthesize :: SubseqExtractor v loc (C.Term v loc) inSynthesize = asPathExtractor $ \case C.InSynthesize t -> Just t _ -> Nothing inSubtype :: SubseqExtractor v loc (C.Type v loc, C.Type v loc) inSubtype = asPathExtractor $ \case C.InSubtype found expected -> Just (found, expected) _ -> Nothing inCheck :: SubseqExtractor v loc (C.Term v loc, C.Type v loc) inCheck = asPathExtractor $ \case C.InCheck e t -> Just (e, t) _ -> Nothing -- inInstantiateL -- inInstantiateR inSynthesizeApp :: SubseqExtractor v loc (C.Type v loc, C.Term v loc, Int) inSynthesizeApp = asPathExtractor $ \case C.InSynthesizeApp t e n -> Just (t, e, n) _ -> Nothing inFunctionCall :: SubseqExtractor v loc ([v], C.Term v loc, C.Type v loc, [C.Term v loc]) inFunctionCall = asPathExtractor $ \case C.InFunctionCall vs f ft e -> case f of Term.Ann' f _ -> Just (vs, f, ft, e) f -> Just (vs, f, ft, e) _ -> Nothing inAndApp, inOrApp, inIfCond, inMatchGuard, inMatchBody :: SubseqExtractor v loc () inAndApp = asPathExtractor $ \case C.InAndApp -> Just () _ -> Nothing inOrApp = asPathExtractor $ \case C.InOrApp -> Just () _ -> Nothing inIfCond = asPathExtractor $ \case C.InIfCond -> Just () _ -> Nothing inMatchGuard = asPathExtractor $ \case C.InMatchGuard -> Just () _ -> Nothing inMatchBody = asPathExtractor $ \case C.InMatchBody -> Just () _ -> Nothing inMatch, inVector, inIfBody :: SubseqExtractor v loc loc inMatch = asPathExtractor $ \case C.InMatch loc -> Just loc _ -> Nothing inVector = asPathExtractor $ \case C.InVectorApp loc -> Just loc _ -> Nothing inIfBody = asPathExtractor $ \case C.InIfBody loc -> Just loc _ -> Nothing -- Causes -- cause :: ErrorExtractor v loc (C.Cause v loc) cause = extractor $ pure . C.cause duplicateDefinitions :: ErrorExtractor v loc (NonEmpty (v, [loc])) duplicateDefinitions = cause >>= \case C.DuplicateDefinitions vs -> pure vs _ -> mzero typeMismatch :: ErrorExtractor v loc (C.Context v loc) typeMismatch = cause >>= \case C.TypeMismatch c -> pure c _ -> mzero illFormedType :: ErrorExtractor v loc (C.Context v loc) illFormedType = cause >>= \case C.IllFormedType c -> pure c _ -> mzero unknownSymbol :: ErrorExtractor v loc (loc, v) unknownSymbol = cause >>= \case C.UnknownSymbol loc v -> pure (loc, v) _ -> mzero unknownTerm :: Var v => ErrorExtractor v loc (loc, v, [C.Suggestion v loc], C.Type v loc) unknownTerm = cause >>= \case C.UnknownTerm loc v suggestions expectedType -> do let k = Var.Inference Var.Ability cleanup = Type.cleanup . Type.removePureEffects . Type.generalize' k pure (loc, v, suggestions, cleanup expectedType) _ -> mzero abilityCheckFailure :: ErrorExtractor v loc ([C.Type v loc], [C.Type v loc], C.Context v loc) abilityCheckFailure = cause >>= \case C.AbilityCheckFailure ambient requested ctx -> pure (ambient, requested, ctx) _ -> mzero effectConstructorWrongArgCount :: ErrorExtractor v loc (C.ExpectedArgCount, C.ActualArgCount, Reference, C.ConstructorId) effectConstructorWrongArgCount = cause >>= \case C.EffectConstructorWrongArgCount expected actual r cid -> pure (expected, actual, r, cid) _ -> mzero malformedEffectBind :: ErrorExtractor v loc (C.Type v loc, C.Type v loc, [C.Type v loc]) malformedEffectBind = cause >>= \case C.MalformedEffectBind ctor ctorResult es -> pure (ctor, ctorResult, es) _ -> mzero solvedBlank :: InfoExtractor v loc (B.Recorded loc, v, C.Type v loc) solvedBlank = extractor $ \n -> case n of C.SolvedBlank b v t -> pure (b, v, t) _ -> mzero -- Misc -- errorNote :: ErrorExtractor v loc (C.ErrorNote v loc) errorNote = extractor $ Just . id infoNote :: InfoExtractor v loc (C.InfoNote v loc) infoNote = extractor $ Just . id innermostTerm :: ErrorExtractor v loc (C.Term v loc) innermostTerm = extractor $ \n -> case C.innermostErrorTerm n of Just e -> pure e Nothing -> mzero path :: ErrorExtractor v loc [C.PathElement v loc] path = extractor $ pure . toList . C.path -- Informational notes -- topLevelComponent :: InfoExtractor v loc [(v, Type v loc, RedundantTypeAnnotation)] topLevelComponent = extractor go where go (C.TopLevelComponent c) = Just c go _ = Nothing instance Functor (SubseqExtractor' n) where fmap = liftM instance Applicative (SubseqExtractor' n) where pure = return (<*>) = ap instance MonadFail (SubseqExtractor' n) where fail _ = mzero instance Monad (SubseqExtractor' n) where return a = SubseqExtractor' $ \_ -> [Pure a] xa >>= f = SubseqExtractor' $ \note -> let as = runSubseq xa note in do ra <- as case ra of Pure a -> runSubseq (f a) note Ranged a startA endA -> let rbs = runSubseq (f a) note in do rb <- rbs case rb of Pure b -> pure (Ranged b startA endA) Ranged b startB endB -> whenM (startB == endA + 1) (pure (Ranged b startA endB)) instance Alternative (SubseqExtractor' n) where empty = mzero (<|>) = mplus instance MonadPlus (SubseqExtractor' n) where mzero = SubseqExtractor' $ \_ -> [] mplus (SubseqExtractor' f1) (SubseqExtractor' f2) = SubseqExtractor' (\n -> f1 n `mplus` f2 n) instance Monoid (SubseqExtractor' n a) where mempty = mzero mappend = mplus instance Semigroup (SubseqExtractor' n a) where (<>) = mappend
unisonweb/platform
parser-typechecker/src/Unison/Typechecker/Extractor.hs
mit
11,800
0
26
3,130
4,317
2,251
2,066
-1
-1
#!/usr/bin/env stack {- stack --system-ghc --resolver lts-18.18 script --package "text" --package "vector" -} {-# LANGUAGE OverloadedStrings #-} module Main where import System.Environment import System.Exit import System.IO import Data.List import Data.Function (on) import Data.Vector (Vector, fromList, (!)) import Text.Printf coordinates :: Vector (Float, Float) coordinates = fromList [ (0,0), (1,0), (0,2), (1,1), (4,6), (2,3), (2,4) ] distance :: (Float, Float) -> (Float, Float) -> Float distance (x1,y1) (x2,y2) = sqrt ((x1-x2)^2 + (y1-y2)^2) tourLength :: Vector (Float, Float) -> [Int] -> Float tourLength pairs tour = let coords = [ y | x <- tour, let y = pairs ! x ] in sum $ zipWith distance coords (tail coords) display :: [([Int], Float)] -> IO () display [] = return () display (x:xs) = do display' x display xs display' :: ([Int], Float) -> IO () display' (k, v) = printf "route %s is length %2.2f\n" (show k) v mapTour :: [[Int]] -> [([Int], Float)] mapTour xs = [(k, v) | k <- xs, let v = tourLength coordinates k] fstSort :: Ord a => [(a, b)] -> [(a, b)] fstSort = sortBy (flip compare `on` fst) sndSort :: Ord b => [(a, b)] -> [(a, b)] sndSort = sortBy (flip compare `on` snd) main :: IO () main = do let tour = [1 .. 6] tours = permutations tour display' $ last (sndSort $ mapTour tours)
joelelmercarlson/stack
haskell/travel.hs
mit
1,428
0
14
345
663
373
290
34
1
module Gold55 where import Data.List -- 2014 latest year available gold1792Avg = (sum gold1792) / (genericLength gold1792) gold1823Avg = (sum gold1823) / (genericLength gold1823) gold1868Avg = (sum gold1868) / (genericLength gold1868) gold1917Avg = (sum gold1917) / (genericLength gold1917) gold1955Avg = (sum gold1955) / (genericLength gold1955) tSumYears = sum [(sum gold1792),(sum gold1823),(sum gold1868),(sum gold1917),(sum gold1955)] tLength =(genericLength gold1792)+(genericLength gold1823)+(genericLength gold1868)+(genericLength gold1868)+(genericLength gold1955) gold1955 = [1199.25, 1204.50 , 1664.00, 1531.00, 1420.25, 1087.50, 869.75, 836.50, 635.70, 513.00, 435.60, 417.25, 342.75, 276.50, 272.65, 290.25, 288.70, 287.05, 369.00, 387.00, 383.25, 391.75, 333.00, 353.15, 386.20, 401.00, 410.15, 486.50, 390.90, 327.00, 308.00, 380.00, 447.00, 400.00, 594.90, 459.00, 208.10, 161.10, 133.77, 139.29, 183.77, 106.48, 63.84, 44.60, 38.90, 41.00, 43.50, 35.50, 35.40, 35.50, 35.35, 35.25, 35.35, 35.50, 36.50, 35.25, 35.25, 35.25, 35.20, 35.15] gold1917=[ 35.25, 35.50, 38.70, 40.00, 40.25, 40.50, 42.00, 43.00, 38.25, 37.25, 36.25, 36.50, 35.50, 35.50, 34.50, 35.00, 35.00, 35.00, 35.00, 35.00, 35.00, 32.32, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67] gold1868 = [ 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.69, 21.25, 22.30, 23.54, 23.09, 22.74, 23.19, 22.59, 22.88, 25.11, 27.95] gold1823 = [ 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.67, 20.69, 20.67, 20.73, 20.73, 20.73, 21.60, 20.69, 20.69, 20.69, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39] gold1792 = [ 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.84, 22.16, 21.79, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39, 19.39]
HaskellForCats/HaskellForCats
gold55.hs
mit
3,035
325
10
1,175
1,193
710
483
221
1
module WoofEval (eval) where data WoofVal = WoofObjectRef Integer deriving (Eq) showVal :: WoofVal -> String showVal (WoofObjectRef num) = "Obj:" ++ (show num) instance Show WoofVal where show = showVal data WoofError = NumArgs Integer [WoofVal] | TypeMismatch String WoofVal | Parser ParseError | BadSpecialForm String WoofVal | NotFunction String String | UnboundVar String String | Default String showError :: WoofError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr instance Show WoofError where show = showError instance Error WoofError where noMsg = Default "An error has occurred" strMsg = Default type ThrowsError = Either WoofError trapError action = catchError action (return . show) extractValue :: ThrowsError a -> a extractValue (Right val) = val
aemoncannon/woof
compiler/woof_error.hs
mit
1,457
0
8
433
385
199
186
30
1
module Network.Acme.Util where import qualified Data.Aeson.TH as Aeson import Data.Char import Data.List import Language.Haskell.TH dropPrefix :: [Char] -> [Char] -> [Char] dropPrefix pre list = case stripPrefix pre list of Nothing -> error $ "Can't strip prefix " ++ pre ++ " from " ++ list Just l -> l decap :: [Char] -> [Char] decap [] = [] decap (c:cs) = toLower c : cs deriveJSON :: Name -> Q [Dec] deriveJSON name = do let nameStr = nameBase name pre = decap nameStr opts = Aeson.defaultOptions {Aeson.fieldLabelModifier = decap . dropPrefix pre} Aeson.deriveJSON opts name
Philonous/hs-acme
src/Network/Acme/Util.hs
mit
669
0
13
186
230
123
107
20
2
-- Mysterious function -- http://www.codewars.com/kata/55217af7ecb43366f8000f76/ module Codewars.Kata.Mysterious where getNum :: Integer -> Integer getNum = foldr f 0 . show where f c | c `elem` "069" = succ | c == '8' = succ . succ | otherwise = id
gafiatulin/codewars
src/6 kyu/Mysterious.hs
mit
284
0
10
75
80
42
38
6
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wno-unused-top-binds #-} import MyInit import Data.Time (Day, UTCTime (..), TimeOfDay, timeToTimeOfDay, timeOfDayToTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime) import Data.Fixed import Test.QuickCheck import qualified Data.Text as T import Data.IntMap (IntMap) import qualified Data.ByteString as BS import qualified CompositeTest import qualified CustomPersistFieldTest import qualified CustomPrimaryKeyReferenceTest import qualified DataTypeTest import qualified EmbedOrderTest import qualified EmbedTest import qualified EmptyEntityTest import qualified EquivalentTypeTest import qualified HtmlTest import qualified InsertDuplicateUpdate import qualified LargeNumberTest import qualified MaxLenTest import qualified MigrationColumnLengthTest import qualified MigrationIdempotencyTest import qualified MigrationOnlyTest import qualified MpsNoPrefixTest import qualified PersistentTest import qualified PersistUniqueTest -- FIXME: Not used... should it be? -- import qualified PrimaryTest import qualified RawSqlTest import qualified ReadWriteTest import qualified Recursive import qualified RenameTest import qualified SumTypeTest import qualified TransactionLevelTest import qualified UniqueTest import qualified UpsertTest import qualified CustomConstraintTest type Tuple a b = (a, b) -- Test lower case names share [mkPersist persistSettings, mkMigrate "dataTypeMigrate"] [persistLowerCase| DataTypeTable no-json text Text textMaxLen Text maxlen=100 bytes ByteString bytesTextTuple (Tuple ByteString Text) bytesMaxLen ByteString maxlen=100 int Int intList [Int] intMap (IntMap Int) double Double bool Bool day Day pico Pico time TimeOfDay utc UTCTime -- For MySQL, provide extra tests for time fields with fractional seconds, -- since the default (used above) is to have no fractional part. This -- requires the server version to be at least 5.6.4, and should be switched -- off for older servers by defining OLD_MYSQL. timeFrac TimeOfDay sqltype=TIME(6) utcFrac UTCTime sqltype=DATETIME(6) |] instance Arbitrary (DataTypeTableGeneric backend) where arbitrary = DataTypeTable <$> arbText -- text <*> (T.take 100 <$> arbText) -- textManLen <*> arbitrary -- bytes <*> liftA2 (,) arbitrary arbText -- bytesTextTuple <*> (BS.take 100 <$> arbitrary) -- bytesMaxLen <*> arbitrary -- int <*> arbitrary -- intList <*> arbitrary -- intMap <*> arbitrary -- double <*> arbitrary -- bool <*> arbitrary -- day <*> arbitrary -- pico <*> (truncateTimeOfDay =<< arbitrary) -- time <*> (truncateUTCTime =<< arbitrary) -- utc <*> (truncateTimeOfDay =<< arbitrary) -- timeFrac <*> (truncateUTCTime =<< arbitrary) -- utcFrac setup :: MonadIO m => Migration -> ReaderT SqlBackend m () setup migration = do printMigration migration runMigrationUnsafe migration main :: IO () main = do runConn $ do mapM_ setup [ PersistentTest.testMigrate , PersistentTest.noPrefixMigrate , EmbedTest.embedMigrate , EmbedOrderTest.embedOrderMigrate , LargeNumberTest.numberMigrate , UniqueTest.uniqueMigrate , MaxLenTest.maxlenMigrate , Recursive.recursiveMigrate , CompositeTest.compositeMigrate , PersistUniqueTest.migration , RenameTest.migration , CustomPersistFieldTest.customFieldMigrate , InsertDuplicateUpdate.duplicateMigrate , MigrationIdempotencyTest.migration , CustomPrimaryKeyReferenceTest.migration , MigrationColumnLengthTest.migration , TransactionLevelTest.migration ] PersistentTest.cleanDB hspec $ do RenameTest.specsWith db DataTypeTest.specsWith db (Just (runMigrationSilent dataTypeMigrate)) [ TestFn "text" dataTypeTableText , TestFn "textMaxLen" dataTypeTableTextMaxLen , TestFn "bytes" dataTypeTableBytes , TestFn "bytesTextTuple" dataTypeTableBytesTextTuple , TestFn "bytesMaxLen" dataTypeTableBytesMaxLen , TestFn "int" dataTypeTableInt , TestFn "intList" dataTypeTableIntList , TestFn "intMap" dataTypeTableIntMap , TestFn "bool" dataTypeTableBool , TestFn "day" dataTypeTableDay , TestFn "time" (roundTime . dataTypeTableTime) , TestFn "utc" (roundUTCTime . dataTypeTableUtc) , TestFn "timeFrac" (dataTypeTableTimeFrac) , TestFn "utcFrac" (dataTypeTableUtcFrac) ] [ ("pico", dataTypeTablePico) ] dataTypeTableDouble HtmlTest.specsWith db (Just (runMigrationSilent HtmlTest.htmlMigrate)) EmbedTest.specsWith db EmbedOrderTest.specsWith db LargeNumberTest.specsWith db UniqueTest.specsWith db MaxLenTest.specsWith db Recursive.specsWith db SumTypeTest.specsWith db (Just (runMigrationSilent SumTypeTest.sumTypeMigrate)) MigrationOnlyTest.specsWith db (Just $ runMigrationSilent MigrationOnlyTest.migrateAll1 >> runMigrationSilent MigrationOnlyTest.migrateAll2 ) PersistentTest.specsWith db PersistentTest.filterOrSpecs db ReadWriteTest.specsWith db RawSqlTest.specsWith db UpsertTest.specsWith db UpsertTest.Don'tUpdateNull UpsertTest.UpsertPreserveOldKey MpsNoPrefixTest.specsWith db EmptyEntityTest.specsWith db (Just (runMigrationSilent EmptyEntityTest.migration)) CompositeTest.specsWith db PersistUniqueTest.specsWith db CustomPersistFieldTest.specsWith db CustomPrimaryKeyReferenceTest.specsWith db InsertDuplicateUpdate.specs MigrationColumnLengthTest.specsWith db EquivalentTypeTest.specsWith db TransactionLevelTest.specsWith db MigrationIdempotencyTest.specsWith db CustomConstraintTest.specs db roundFn :: RealFrac a => a -> Integer roundFn = round roundTime :: TimeOfDay -> TimeOfDay roundTime t = timeToTimeOfDay $ fromIntegral $ roundFn $ timeOfDayToTime t roundUTCTime :: UTCTime -> UTCTime roundUTCTime t = posixSecondsToUTCTime $ fromIntegral $ roundFn $ utcTimeToPOSIXSeconds t
naushadh/persistent
persistent-mysql/test/main.hs
mit
6,583
0
24
1,399
1,117
598
519
151
1
-- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Kubernetes.Model.V1.ContainerPort ( ContainerPort (..) , name , hostPort , containerPort , protocol , hostIP , mkContainerPort ) where import Control.Lens.TH (makeLenses) import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import Data.Text (Text) import GHC.Generics (Generic) import Prelude hiding (drop, error, max, min) import qualified Prelude as P import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Instances () -- | ContainerPort represents a network port in a single container. data ContainerPort = ContainerPort { _name :: !(Maybe Text) , _hostPort :: !(Maybe Integer) , _containerPort :: !(Integer) , _protocol :: !(Maybe Text) , _hostIP :: !(Maybe Text) } deriving (Show, Eq, Generic) makeLenses ''ContainerPort $(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''ContainerPort) instance Arbitrary ContainerPort where arbitrary = ContainerPort <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- | Use this method to build a ContainerPort mkContainerPort :: Integer -> ContainerPort mkContainerPort xcontainerPortx = ContainerPort Nothing Nothing xcontainerPortx Nothing Nothing
soundcloud/haskell-kubernetes
lib/Kubernetes/Model/V1/ContainerPort.hs
mit
1,816
0
14
525
343
202
141
43
1
{-# LANGUAGE RecordWildCards, TemplateHaskell, ViewPatterns #-} module Yesod.Routes.TH.Dispatch ( MkDispatchSettings (..) , mkDispatchClause , defaultGetHandler ) where import Prelude hiding (exp) import Language.Haskell.TH.Syntax import Web.PathPieces import Data.Maybe (catMaybes) import Control.Monad (forM) import Data.List (foldl') import Control.Arrow (second) import System.Random (randomRIO) import Yesod.Routes.TH.Types import Data.Char (toLower) data MkDispatchSettings b site c = MkDispatchSettings { mdsRunHandler :: Q Exp , mdsSubDispatcher :: Q Exp , mdsGetPathInfo :: Q Exp , mdsSetPathInfo :: Q Exp , mdsMethod :: Q Exp , mds404 :: Q Exp , mds405 :: Q Exp , mdsGetHandler :: Maybe String -> String -> Q Exp , mdsUnwrapper :: Exp -> Q Exp } data SDC = SDC { clause404 :: Clause , extraParams :: [Exp] , extraCons :: [Exp] , envExp :: Exp , reqExp :: Exp } -- | A simpler version of Yesod.Routes.TH.Dispatch.mkDispatchClause, based on -- view patterns. -- -- Since 1.4.0 mkDispatchClause :: MkDispatchSettings b site c -> [ResourceTree a] -> Q Clause mkDispatchClause MkDispatchSettings {..} resources = do suffix <- qRunIO $ randomRIO (1000, 9999 :: Int) envName <- newName $ "env" ++ show suffix reqName <- newName $ "req" ++ show suffix helperName <- newName $ "helper" ++ show suffix let envE = VarE envName reqE = VarE reqName helperE = VarE helperName clause404' <- mkClause404 envE reqE getPathInfo <- mdsGetPathInfo let pathInfo = getPathInfo `AppE` reqE let sdc = SDC { clause404 = clause404' , extraParams = [] , extraCons = [] , envExp = envE , reqExp = reqE } clauses <- mapM (go sdc) resources return $ Clause [VarP envName, VarP reqName] (NormalB $ helperE `AppE` pathInfo) [FunD helperName $ clauses ++ [clause404']] where handlePiece :: Piece a -> Q (Pat, Maybe Exp) handlePiece (Static str) = return (LitP $ StringL str, Nothing) handlePiece (Dynamic _) = do x <- newName "dyn" let pat = ViewP (VarE 'fromPathPiece) (ConP 'Just [VarP x]) return (pat, Just $ VarE x) handlePieces :: [Piece a] -> Q ([Pat], [Exp]) handlePieces = fmap (second catMaybes . unzip) . mapM handlePiece mkCon :: String -> [Exp] -> Exp mkCon name = foldl' AppE (ConE $ mkName name) mkPathPat :: Pat -> [Pat] -> Pat mkPathPat final = foldr addPat final where addPat x y = ConP '(:) [x, y] go :: SDC -> ResourceTree a -> Q Clause go sdc (ResourceParent name _check pieces children) = do (pats, dyns) <- handlePieces pieces let sdc' = sdc { extraParams = extraParams sdc ++ dyns , extraCons = extraCons sdc ++ [mkCon name dyns] } childClauses <- mapM (go sdc') children restName <- newName "rest" let restE = VarE restName restP = VarP restName helperName <- newName $ "helper" ++ name let helperE = VarE helperName return $ Clause [mkPathPat restP pats] (NormalB $ helperE `AppE` restE) [FunD helperName $ childClauses ++ [clause404 sdc]] go SDC {..} (ResourceLeaf (Resource name pieces dispatch _ _check)) = do (pats, dyns) <- handlePieces pieces (chooseMethod, finalPat) <- handleDispatch dispatch dyns return $ Clause [mkPathPat finalPat pats] (NormalB chooseMethod) [] where handleDispatch :: Dispatch a -> [Exp] -> Q (Exp, Pat) handleDispatch dispatch' dyns = case dispatch' of Methods multi methods -> do (finalPat, mfinalE) <- case multi of Nothing -> return (ConP '[] [], Nothing) Just _ -> do multiName <- newName "multi" let pat = ViewP (VarE 'fromPathMultiPiece) (ConP 'Just [VarP multiName]) return (pat, Just $ VarE multiName) let dynsMulti = case mfinalE of Nothing -> dyns Just e -> dyns ++ [e] route' = foldl' AppE (ConE (mkName name)) dynsMulti route = foldr AppE route' extraCons jroute = ConE 'Just `AppE` route allDyns = extraParams ++ dynsMulti mkRunExp mmethod = do runHandlerE <- mdsRunHandler handlerE' <- mdsGetHandler mmethod name handlerE <- mdsUnwrapper $ foldl' AppE handlerE' allDyns return $ runHandlerE `AppE` handlerE `AppE` envExp `AppE` jroute `AppE` reqExp func <- case methods of [] -> mkRunExp Nothing _ -> do getMethod <- mdsMethod let methodE = getMethod `AppE` reqExp matches <- forM methods $ \method -> do exp <- mkRunExp (Just method) return $ Match (LitP $ StringL method) (NormalB exp) [] match405 <- do runHandlerE <- mdsRunHandler handlerE <- mds405 let exp = runHandlerE `AppE` handlerE `AppE` envExp `AppE` jroute `AppE` reqExp return $ Match WildP (NormalB exp) [] return $ CaseE methodE $ matches ++ [match405] return (func, finalPat) Subsite _ getSub -> do restPath <- newName "restPath" setPathInfoE <- mdsSetPathInfo subDispatcherE <- mdsSubDispatcher runHandlerE <- mdsRunHandler sub <- newName "sub" let sub2 = LamE [VarP sub] (foldl' (\a b -> a `AppE` b) (VarE (mkName getSub) `AppE` VarE sub) dyns) let reqExp' = setPathInfoE `AppE` VarE restPath `AppE` reqExp route' = foldl' AppE (ConE (mkName name)) dyns route = foldr AppE route' extraCons exp = subDispatcherE `AppE` runHandlerE `AppE` sub2 `AppE` route `AppE` envExp `AppE` reqExp' return (exp, VarP restPath) mkClause404 envE reqE = do handler <- mds404 runHandler <- mdsRunHandler let exp = runHandler `AppE` handler `AppE` envE `AppE` ConE 'Nothing `AppE` reqE return $ Clause [WildP] (NormalB exp) [] defaultGetHandler :: Maybe String -> String -> Q Exp defaultGetHandler Nothing s = return $ VarE $ mkName $ "handle" ++ s defaultGetHandler (Just method) s = return $ VarE $ mkName $ map toLower method ++ s
meteficha/yesod
yesod-core/Yesod/Routes/TH/Dispatch.hs
mit
7,794
1
29
3,328
2,154
1,108
1,046
-1
-1
{- | module: $Header$ description: Probability license: MIT maintainer: Joe Leslie-Hurd <[email protected]> stability: provisional portability: portable -} module OpenTheory.Random where import qualified OpenTheory.Primitive.Natural as Natural import qualified OpenTheory.Primitive.Random as Random vector :: (Random.Random -> a) -> Natural.Natural -> Random.Random -> [a] vector f n r = if n == 0 then [] else let (r1, r2) = Random.split r in f r1 : vector f (n - 1) r2 bits :: Natural.Natural -> Random.Random -> [Bool] bits = vector Random.bit
gilith/opentheory
data/haskell/opentheory-probability/src/OpenTheory/Random.hs
mit
553
0
11
89
158
88
70
9
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-activity.html module Stratosphere.Resources.StepFunctionsActivity where import Stratosphere.ResourceImports -- | Full data type definition for StepFunctionsActivity. See -- 'stepFunctionsActivity' for a more convenient constructor. data StepFunctionsActivity = StepFunctionsActivity { _stepFunctionsActivityName :: Val Text } deriving (Show, Eq) instance ToResourceProperties StepFunctionsActivity where toResourceProperties StepFunctionsActivity{..} = ResourceProperties { resourcePropertiesType = "AWS::StepFunctions::Activity" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ (Just . ("Name",) . toJSON) _stepFunctionsActivityName ] } -- | Constructor for 'StepFunctionsActivity' containing required fields as -- arguments. stepFunctionsActivity :: Val Text -- ^ 'sfaName' -> StepFunctionsActivity stepFunctionsActivity namearg = StepFunctionsActivity { _stepFunctionsActivityName = namearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-activity.html#cfn-stepfunctions-activity-name sfaName :: Lens' StepFunctionsActivity (Val Text) sfaName = lens _stepFunctionsActivityName (\s a -> s { _stepFunctionsActivityName = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/StepFunctionsActivity.hs
mit
1,476
0
15
197
188
109
79
25
1
module WrapEnum where -- Move through an enumeration, but wrap around when hitting the end wrapSucc, wrapPred :: (Enum a, Bounded a, Eq a) => a -> a wrapSucc a | a == maxBound = minBound | otherwise = succ a wrapPred a | a == minBound = maxBound | otherwise = pred a
blitzcode/rust-exp
hs-src/WrapEnum.hs
mit
300
0
8
87
97
48
49
6
1
module GHCJS.DOM.RTCConfiguration ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/RTCConfiguration.hs
mit
46
0
3
7
10
7
3
1
0
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Consensus.Raft -- Copyright : (c) Phil Hargett 2014 -- License : MIT (see LICENSE file) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (requires STM) -- -- Generalized implementation of the Raft consensus algorithm. -- -- Application writers generally need only supply an implementation of -- 'Control.Consensus.Raft.Log.RaftLog' and 'Control.Consensus.Log.State'. For many -- applications, the provided 'Control.Consensus.Raft.Log.ListLog' may be sufficient for -- the 'Control.Consensus.Raft.Log.RaftLog' implementation. -- Applications also may choose to define how to externally persist the application's log and state. -- Note that use of strong persistence (e.g., to disk or stable storage) or weak persistence -- (e.g., retain in memory or volatile storage only) is up to the application, with the -- caveat that Raft can only recover certain failure scenarios when strong persistence -- is in use. -- -- The function 'withConsensus' takes the supplied log and state (and an 'Endpoint') -- and performs the Raft algorithm to ensure consistency with other members of the cluster -- (all of which must also be executing 'withConsensus' and reachable through their 'Endpoint's). -- Server applications should execute 'withConsensus', client applications can use the -- "Control.Consensus.Raft.Client" module to interface with the cluster over a network -- (or other transport). -- ----------------------------------------------------------------------------- module Control.Consensus.Raft ( withConsensus, module Data.Log, module Control.Consensus.Raft.Actions, module Control.Consensus.Raft.Client, module Control.Consensus.Raft.Log, module Control.Consensus.Raft.Types ) where -- local imports import Control.Consensus.Raft.Actions import Control.Consensus.Raft.Client import Control.Consensus.Raft.Protocol import Control.Consensus.Raft.Log import Control.Consensus.Raft.Members import Control.Consensus.Raft.Types import Data.Log -- external imports import Control.Concurrent import Control.Concurrent.Async import Control.Exception import Control.Concurrent.STM import qualified Data.Map as M import Network.Endpoints import Network.RPC import Prelude hiding (log) import System.Log.Logger import Text.Printf -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- _log :: String _log = "raft.consensus" {-| Run the core Raft consensus algorithm for the indicated server. This function takes care of coordinating the transitions among followers, candidates, and leaders as necessary. -} withConsensus :: (RaftLog l e v) => Endpoint -> Name -> l -> RaftState v -> (Raft l e v -> IO ()) -> IO () withConsensus endpoint name initialLog initialState fn = do vRaft <- atomically $ mkRaft endpoint initialLog initialState withAsync (run vRaft) (\_ -> fn vRaft) where run vRaft = do infoM _log $ printf "Starting server %v" name finally (catch (participate vRaft) (\e -> case e of ThreadKilled -> return () _ -> debugM _log $ printf "%v encountered error: %v" name (show (e :: AsyncException)))) (do infoM _log $ printf "Stopped server %v" name) participate vRaft = do follow vRaft won <- volunteer vRaft if won then do lead vRaft else return () participate vRaft follow :: (RaftLog l e v) => Raft l e v -> IO () follow vRaft = do initialRaft <- atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftMembers M.empty $ setRaftLeader Nothing oldRaft readTVar (raftContext vRaft) let name = raftName initialRaft term = raftCurrentTerm initialRaft infoM _log $ printf "Server %v following in term %v" name term raceAll_ [doFollow vRaft, doVote vRaft, doRedirect vRaft] {-| As a follower, wait for 'AppendEntries' requests and process them, commit new changes as necessary, and stop when no heartbeat received. -} doFollow :: (RaftLog l e v) => Raft l e v -> IO () doFollow vRaft = do doSynchronize vRaft onRequest alwaysContinue where onRequest raft req = do let log = raftLog raft nextIndex = (1 + (logIndex $ aePreviousTime req)) count = length $ aeEntries req if count > 0 then infoM _log $ printf "%v: Appending %d at %d" (raftName raft) count nextIndex else return () newLog <- appendEntries log nextIndex (aeEntries req) if count > 0 then infoM _log $ printf "%v: Appended %d at %d" (raftName raft) count (lastAppended newLog) else return () updatedRaft <- atomically $ do preCommitConfigurationChange vRaft (aeEntries req) modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLog newLog oldRaft readTVar (raftContext vRaft) if (logIndex $ aeCommittedTime req) > (lastCommitted $ raftLog updatedRaft) then do infoM _log $ printf "%v: Committing at %d" (raftName raft) (logIndex $ aeCommittedTime req) (committedLog,committedState) <- commitEntries (raftLog updatedRaft) (logIndex $ aeCommittedTime req) (raftState updatedRaft) infoM _log $ printf "%v: Committed at %d" (raftName raft) (lastCommitted committedLog) (checkpointedLog,checkpointedState) <- checkpoint committedLog committedState checkpointedRaft <- atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLog checkpointedLog $ setRaftState checkpointedState oldRaft readTVar (raftContext vRaft) return checkpointedRaft else return updatedRaft alwaysContinue _ = True doSynchronize :: (RaftLog l e v) => Raft l e v -> ((RaftContext l e v) -> AppendEntries e -> IO (RaftContext l e v)) -> (Name -> Bool) -> IO () doSynchronize vRaft reqfn contfn = do initialRaft <- atomically $ readTVar (raftContext vRaft) let endpoint = raftEndpoint initialRaft cfg = raftStateConfiguration $ raftState initialRaft name = raftName initialRaft maybeLeader <- onAppendEntries endpoint cfg name $ \req -> do raft <- atomically $ do raft <-readTVar (raftContext vRaft) if (aeLeaderTerm req) < (raftCurrentTerm raft) then return raft else do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftTerm (aeLeaderTerm req) $ setRaftLeader (Just $ aeLeader req) $ setRaftLastCandidate Nothing oldRaft readTVar (raftContext vRaft) -- check previous entry for consistency let requestPreviousTerm = (logTerm $ aePreviousTime req) prevIndex = (logIndex $ aePreviousTime req) localPreviousTerm <- if prevIndex < 0 then return (-1) else do prevEntries <- fetchEntries (raftLog raft) prevIndex 1 return $ entryTerm $ head prevEntries let valid = requestPreviousTerm == localPreviousTerm synchronizedRaft <- if valid then reqfn raft req else return raft return $ mkResult valid synchronizedRaft case maybeLeader of -- we did hear a message before the timeout, and we have a committed time Just leader -> do if contfn leader then doSynchronize vRaft reqfn contfn else return () Nothing -> return () preCommitConfigurationChange :: (RaftLog l e v) => Raft l e v -> [RaftLogEntry e] -> STM () preCommitConfigurationChange _ [] = return () preCommitConfigurationChange vRaft (entry:_) = do case entryAction entry of Cmd _ -> return () action -> do raft <- readTVar (raftContext vRaft) let oldRaftState = raftState raft newCfg = applyConfigurationAction (clusterConfiguration $ raftStateConfiguration oldRaftState) action newRaft = setRaftConfiguration newCfg raft writeTVar (raftContext vRaft) newRaft -- we don't need to recurse, because we expect the configuration change at the beginning -- preCommitConfigurationChange vRaft entries {-| Wait for request vote requests and process them -} doVote :: (RaftLog l e v) => Raft l e v -> IO () doVote vRaft = do initialRaft <- atomically $ readTVar (raftContext vRaft) let endpoint = raftEndpoint initialRaft cfg = raftStateConfiguration $ raftState initialRaft name = raftName initialRaft leading = (Just name) == (clusterLeader $ clusterConfiguration cfg) votedForCandidate <- onRequestVote endpoint name $ \req -> do debugM _log $ printf "Server %v received vote request from %v" name (show $ rvCandidate req) (raft,vote,reason) <- atomically $ do raft <- readTVar (raftContext vRaft) let log = raftLog raft if (rvCandidateTerm req) < (raftCurrentTerm raft) then return (raft,False,"Candidate term too old") else do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftTerm (rvCandidateTerm req) oldRaft case raftStateLastCandidate $ raftState raft of Just candidate -> do if (candidate == rvCandidate req) then return (raft,True,"Candidate already seen") else return (raft,False,"Already saw different candidate") Nothing -> do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLastCandidate (Just $ rvCandidate req) oldRaft if name == rvCandidate req then return (raft,True,"Voting for self") else do if (rvCandidateLastEntryTime req) >= (lastAppendedTime log) then do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLastCandidate (Just $ rvCandidate req) oldRaft return (raft,True,"Candidate log more up to date") else return (raft,False,"Candidate log out of date") infoM _log $ printf "Server %v vote for %v is %v because %v" name (rvCandidate req) (show (raftCurrentTerm raft,vote)) reason return $ mkResult vote raft if leading && votedForCandidate then return () else doVote vRaft {-| Initiate an election, volunteering to lead the cluster if elected. -} volunteer :: (RaftLog l e v) => Raft l e v -> IO Bool volunteer vRaft = do participant <- atomically $ do raft <- readTVar $ raftContext vRaft let name = raftName raft cfg = raftStateConfiguration $ raftState raft return $ isClusterParticipant name (clusterConfiguration cfg) -- this allows us to have raft servers that are up and running, -- but they will just patiently wait until they are a participant -- before volunteering if participant then do results <- race (doVote vRaft) (doVolunteer vRaft) case results of Left _ -> return False Right won -> return won else return False doVolunteer :: (RaftLog l e v) => Raft l e v -> IO Bool doVolunteer vRaft = do raft <- atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftTerm ((raftCurrentTerm oldRaft) + 1) $ setRaftLastCandidate Nothing oldRaft readTVar (raftContext vRaft) let candidate = raftName raft cfg = raftStateConfiguration $ raftState raft endpoint = raftEndpoint raft members = clusterMembers $ clusterConfiguration cfg cs = newCallSite endpoint candidate term = raftCurrentTerm raft log = raftLog raft RaftTime lastTerm lastIndex = lastAppendedTime log infoM _log $ printf "Server %v volunteering in term %v" candidate (show $ raftCurrentTerm raft) debugM _log $ printf "Server %v is soliciting votes from %v" candidate (show members) votes <- goRequestVote cs cfg term candidate (RaftTime lastTerm lastIndex) debugM _log $ printf "Server %v (%v) received votes %v" candidate (show (term,lastIndex)) (show votes) return $ wonElection votes where wonElection :: M.Map Name (Maybe MemberResult) -> Bool wonElection votes = majority votes $ M.foldl (\tally ballot -> case ballot of Just (result) -> if (memberActionSuccess result) then tally + 1 else tally _ -> tally) 0 votes majority :: M.Map Name (Maybe MemberResult) -> Int -> Bool majority votes tally = tally > ((M.size $ votes) `quot` 2) lead :: (RaftLog l e v) => Raft l e v -> IO () lead vRaft = do raft <- atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> do let name = raftName oldRaft cfg = raftStateConfiguration $ raftState oldRaft members = mkMembers cfg $ lastCommittedTime $ raftLog oldRaft setRaftLeader (Just name) $ setRaftLastCandidate Nothing $ setRaftMembers members oldRaft readTVar (raftContext vRaft) let name = raftName raft term = raftCurrentTerm raft clients <- atomically $ newMailbox actions <- atomically $ newMailbox infoM _log $ printf "Server %v leading in term %v with members %s" name (show term) (show $ raftMembers raft) raceAll_ $ [doPulse vRaft actions, doVote vRaft, doRespond vRaft, doServe vRaft actions, doPerform vRaft actions clients] type Actions c = Mailbox (Maybe (RaftAction c,Reply MemberResult)) type Clients = Mailbox (Index,Reply MemberResult) doPulse :: (RaftLog l e v) => Raft l e v -> Actions c -> IO () doPulse vRaft actions = do raft <- atomically $ do raft <- readTVar (raftContext vRaft) empty <- isEmptyMailbox actions if empty then writeMailbox actions Nothing else return () return raft let cfg = raftStateConfiguration $ raftState raft threadDelay $ timeoutPulse $ clusterTimeouts cfg doPulse vRaft actions {-| As a leader, wait for 'AppendEntries' requests and process them, commit new changes as necessary, and stop when no heartbeat received. -} doRespond :: (RaftLog l e v) => Raft l e v -> IO () doRespond vRaft = do initialRaft <- atomically $ readTVar (raftContext vRaft) let name = raftName initialRaft doSynchronize vRaft onRequest (continueIfLeader name) where onRequest raft _ = return raft continueIfLeader name leader = name == leader {-| Service requests from clients -} doServe :: (RaftLog l e v) => Raft l e v -> Actions e -> IO () doServe vRaft actions = do raft <- atomically $ readTVar (raftContext vRaft) let endpoint = raftEndpoint raft leader = raftName raft onPerformAction endpoint leader $ \action reply -> do atomically $ writeMailbox actions $ Just (action,reply) doServe vRaft actions {-| Leaders commit entries to their log, once enough members have appended those entries. Once committed, the leader replies to the client who requested the action. -} doPerform :: (RaftLog l e v) => Raft l e v -> Actions e -> Clients -> IO () doPerform vRaft actions clients = do append vRaft actions clients commit vRaft clients doPerform vRaft actions clients append :: (RaftLog l e v) => Raft l e v -> Actions e -> Clients -> IO () append vRaft actions clients = do (raft,maybeAction) <- atomically $ do maybeAction <- readMailbox actions raft <- readTVar (raftContext vRaft) return (raft,maybeAction) case maybeAction of Nothing -> return () Just (action,reply) -> do let oldLog = raftLog raft oldState = raftState raft term = raftCurrentTerm raft nextIndex = (lastAppended oldLog) + 1 revisedAction = case action of Cmd _ -> action cfgAction -> Cfg $ SetConfiguration $ applyConfigurationAction (clusterConfiguration $ raftStateConfiguration oldState) cfgAction newLog <- appendEntries oldLog nextIndex [RaftLogEntry term revisedAction] (revisedLog,revisedState) <- case revisedAction of Cfg (SetConfiguration newCfg) -> do let newState = oldState { raftStateConfiguration = (raftStateConfiguration oldState) { clusterConfiguration = newCfg }, raftStateConfigurationIndex = case newCfg of JointConfiguration _ _ -> Just nextIndex _ -> Nothing } checkpoint newLog newState _ -> return (newLog,oldState) atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLog revisedLog $ setRaftState revisedState oldRaft writeMailbox clients (lastAppended revisedLog,reply) infoM _log $ printf "%v: Appended 1 action at index %v" (raftName raft) nextIndex return () commit :: (RaftLog l e v) => Raft l e v -> Clients -> IO () commit vRaft clients = do raft <- atomically $ readTVar (raftContext vRaft) let initialLog = raftLog raft leader = raftName raft endpoint = raftEndpoint raft cs = newCallSite endpoint leader term = raftCurrentTerm raft cfg = raftStateConfiguration $ raftState raft (prevTime,entries) <- gatherUnsynchronizedEntries (raftMembers raft) (clusterConfiguration cfg) initialLog infoM _log $ printf "%v: Broadcasting %d entries after %d" leader (length entries) (logIndex $ prevTime) results <- goAppendEntries cs cfg term prevTime (lastCommittedTime initialLog) entries let members = raftMembers raft newMembers = updateMembers members results newCommittedIndex = membersSafeAppendedIndex newMembers $ clusterConfiguration cfg newTerm = membersHighestTerm newMembers infoM _log $ printf "%v: Member appended indexes are %v" leader (show $ membersAppendedIndex newMembers $ clusterConfiguration cfg) atomically $ modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftMembers newMembers oldRaft if newTerm > (raftCurrentTerm raft) then do atomically $ modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftTerm newTerm oldRaft infoM _log $ printf "Leader stepping down; new term %v discovered" (show newTerm) return () else do newRaft <- atomically $ readTVar $ raftContext vRaft (newLog,newState) <- if (newCommittedIndex > lastCommitted initialLog) then do infoM _log $ printf "%v: Committing at %d" leader newCommittedIndex (log,state) <- commitEntries initialLog newCommittedIndex (raftState newRaft) checkpoint log state else return (initialLog,raftState newRaft) (revisedLog,revisedState) <- case raftStateConfigurationIndex newState of Nothing -> return (newLog,newState) Just cfgIndex -> if lastCommitted newLog >= cfgIndex then do let revisedCfg = case (clusterConfiguration $ raftStateConfiguration newState) of JointConfiguration _ jointNew -> jointNew newCfg -> newCfg revisedLog <- appendEntries newLog ((lastAppended newLog) + 1) [RaftLogEntry (raftStateCurrentTerm newState) (Cfg $ SetConfiguration revisedCfg)] let revisedState = newState {raftStateConfigurationIndex = Nothing} return (revisedLog,revisedState) else return (newLog,newState) atomically $ modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLog revisedLog $ setRaftState revisedState $ setRaftMembers newMembers oldRaft notifyClients vRaft clients revisedLog revisedState return () gatherUnsynchronizedEntries :: (RaftLog l e v) => Members -> Configuration -> l -> IO (RaftTime,[RaftLogEntry e]) gatherUnsynchronizedEntries members cfg log = do let prevIndex = minimum $ membersAppendedIndex members cfg startIndex = prevIndex + 1 if prevIndex < 0 then do let count = (lastAppended log - startIndex) + 1 entries <- fetchEntries log startIndex count return (initialRaftTime,groupEntries entries) else do let count = (lastAppended log - prevIndex) + 1 (prev:rest) <- fetchEntries log prevIndex count return (RaftTime (entryTerm prev) prevIndex,groupEntries rest) where -- we return a list of entries that either has 1 configuration -- entry at the beginning (e.g., 'Cfg') and no others, or has no -- 'Cfg' entry at all. groupEntries [] = [] groupEntries (first:rest) = if isConfigurationEntry first then (first:commandEntries rest) else (commandEntries (first:rest)) isConfigurationEntry = isConfigurationAction . entryAction isCommandEntry = isCommandAction . entryAction commandEntries = takeWhile isCommandEntry notifyClients :: (RaftLog l e v) => Raft l e v -> Clients -> l -> RaftState v -> IO () notifyClients vRaft clients newLog newState = do maybeReply <- atomically $ do modifyTVar (raftContext vRaft) $ \oldRaft -> setRaftLog newLog $ setRaftState newState oldRaft maybeClient <- tryPeekMailbox clients case maybeClient of Nothing -> return Nothing Just (index,reply) -> if index <= (lastCommitted newLog) then do updatedRaft <- readTVar (raftContext vRaft) _ <- readMailbox clients return $ Just $ reply $ mkResult True updatedRaft else return Nothing case maybeReply of Nothing -> do return () Just reply -> reply doRedirect :: (RaftLog l e v) => Raft l e v -> IO () doRedirect vRaft = do raft <- atomically $ readTVar (raftContext vRaft) let endpoint = raftEndpoint raft member = raftName raft onPassAction endpoint member $ \reply -> do newRaft <- atomically $ readTVar (raftContext vRaft) reply $ mkResult False newRaft doRedirect vRaft mkResult :: (RaftLog l e v) => Bool -> RaftContext l e v -> MemberResult mkResult success raft = MemberResult { memberActionSuccess = success, memberLeader = clusterLeader $ clusterConfiguration $ raftStateConfiguration $ raftState raft, memberCurrentTerm = raftCurrentTerm raft, memberLastAppended = lastAppendedTime $ raftLog raft, memberLastCommitted = lastCommittedTime $ raftLog raft } raceAll_ :: [IO ()] -> IO () raceAll_ actions = do tasks <- mapM async actions _ <- waitAnyCancel tasks return ()
hargettp/raft
src/Control/Consensus/Raft.hs
mit
24,515
0
35
7,524
6,018
2,934
3,084
419
7
module Day5 (day5, day5', run, startsWithZeros, applyHash) where import Crypto.Hash.MD5 (hash) import Data.ByteString.Base16 (encode) import qualified Data.ByteString.Char8 (pack, unpack) import Data.ByteString (ByteString) import qualified Data.ByteString as BS (index, isPrefixOf, pack) import Data.List (elemIndex, nub, scanl) import Data.Map.Strict (Map, (!), insert, member) import qualified Data.Map.Strict as Map (empty) import Data.Word (Word8) applyHash :: String -> Int -> ByteString applyHash prefix x = hash . Data.ByteString.Char8.pack $ prefix ++ show x startsWithZeros :: ByteString -> Bool startsWithZeros b = zeros `BS.isPrefixOf` b && ((BS.index b 2) < 16) where zeros = BS.pack [0, 0] -- All base16 representations of hashes whose first 5 characters are '0' interestingHashes :: String -> [String] interestingHashes prefix = map (Data.ByteString.Char8.unpack . encode) . filter startsWithZeros . map (applyHash prefix) $ [1..] newtype PartiallyDecrypted = PartiallyDecrypted (Map Int Char) deriving (Eq, Ord) instance Show PartiallyDecrypted where show (PartiallyDecrypted m) = map charOrUnderscore [0..7] where charOrUnderscore i = if (member i m) then m ! i else '_' isFullyDecrypted :: PartiallyDecrypted -> Bool isFullyDecrypted (PartiallyDecrypted m) = all (\i -> member i m) [0..7] decryptStep :: PartiallyDecrypted -> String -> PartiallyDecrypted decryptStep p@(PartiallyDecrypted m) s = if pos < 8 then (PartiallyDecrypted $ insertIgnore pos char m) else p where pos = maybe 9 id $ elemIndex (s !! 5) "01234567" char = s !! 6 insertIgnore position character map = if member position map then map else insert position character map -- Expects to be fed results of interestingHashes, so that interestingHashes can -- be cached between parts day5Impl :: [String] -> String day5Impl = take 8 . map (!! 5) day5Impl' :: [String] -> String day5Impl' = show . head . dropWhile (not . isFullyDecrypted) . scanl decryptStep (PartiallyDecrypted Map.empty) -- Final, top-level exports day5 :: String -> String day5 = day5Impl . interestingHashes day5' :: String -> String day5' = day5Impl' . interestingHashes -- Input run :: IO () run = do -- The actual solution here is commented out, because it takes ~45 seconds --putStrLn "Day 5 results: " --let input = "ojvtpuvg" --let hashes = interestingHashes input --putStrLn $ " " ++ show (day5Impl hashes) --putStrLn $ " " ++ show (day5Impl' hashes) putStrLn "Day 5 results (cached): " putStrLn $ " " ++ show "4543c154" putStrLn $ " " ++ show "1050cbbd"
brianshourd/adventOfCode2016
src/Day5.hs
mit
2,606
0
11
471
757
421
336
41
3
{- Copyright (C) 2014 Calvin Beck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} {-# LANGUAGE OverloadedStrings #-} module TimePaper.Parser (parseTimeLog) where import TimePaper.TimeEntry import TimePaper.WeekDay import Control.Applicative import Data.Attoparsec.Text hiding (take, takeWhile) import Data.Time.Calendar import Data.Time.Clock import Data.Time.LocalTime -- | Parse a bunch of time log lines! parseTimeLog :: Parser [TimeEntry] parseTimeLog = many parseEntry -- | Parse a single line from the time log. parseEntry :: Parser TimeEntry parseEntry = do epochTime <- decimal skipSpace actions <- many parseAction (date, time, weekDay) <- parseTimeStamp endOfLine return (TimeEntry date time weekDay actions) -- | Parsing of an action. These are just strings separated by spaces. parseAction :: Parser String parseAction = do action <- many (letter <|> digit) char ' ' skipSpace return action -- | Parse the timestamp for an entry in the log. parseTimeStamp :: Parser (Day, TimeOfDay, WeekDay) parseTimeStamp = do char '[' date <- parseDate skipSpace time <- parseTime skipSpace weekDay <- parseWeekDay char ']' return (date, time, weekDay) -- | Parse date strings with a format like: 2014.09.20 parseDate :: Parser Day parseDate = do year <- decimal char '.' month <- decimal char '.' day <- decimal return (fromGregorian year month day) -- | Parse the time of day. parseTime :: Parser TimeOfDay parseTime = do hours <- decimal char ':' minutes <- decimal char ':' seconds <- decimal return (TimeOfDay hours minutes (fromIntegral seconds)) -- | Parse the day of the week field. parseWeekDay :: Parser WeekDay parseWeekDay = do string "Mon"; return Monday <|> do string "Tue"; return Tuesday <|> do string "Wed"; return Wednesday <|> do string "Thu"; return Thursday <|> do string "Fri"; return Friday <|> do string "Sat"; return Saturday <|> do string "Sun"; return Sunday
Chobbes/TimePaper
TimePaper/Parser.hs
mit
3,431
0
13
1,014
536
257
279
54
1
{-# LANGUAGE OverloadedStrings #-} module PGIP.GraphQL.Resolver (resolve) where import qualified PGIP.GraphQL.Resolver.DGraph as DGraphResolver import qualified PGIP.GraphQL.Resolver.OMS as OMSResolver import qualified PGIP.GraphQL.Resolver.Serialization as SerializationResolver import qualified PGIP.GraphQL.Resolver.Signature as SignatureResolver import qualified PGIP.GraphQL.Resolver.SignatureMorphism as SignatureMorphismResolver import PGIP.GraphQL.Result as GraphQLResult import PGIP.Shared import Driver.Options import Data.Map (Map) import qualified Data.Map as Map import Data.Text (Text) import qualified Data.Text as Text resolve :: HetcatsOpts -> Cache -> Text -> Map Text Text -> IO String resolve opts sessionReference query variables = do queryType <- determineQueryType query resultM <- case queryType of QTSerialization -> case Map.lookup "id" variables of Nothing -> fail "Serialization query: Variable \"id\" not provided." Just idVar -> SerializationResolver.resolve opts sessionReference $ unencloseQuotesAndUnpack idVar QTDGraph -> case Map.lookup "locId" variables of Nothing -> fail "OMS query: Variable \"locId\" not provided." Just idVar -> DGraphResolver.resolve opts sessionReference $ unencloseQuotesAndUnpack idVar QTOMS -> case Map.lookup "locId" variables of Nothing -> fail "OMS query: Variable \"locId\" not provided." Just idVar -> OMSResolver.resolve opts sessionReference $ unencloseQuotesAndUnpack idVar QTSignature -> case Map.lookup "id" variables of Nothing -> fail "Signature query: Variable \"id\" not provided." Just idVar -> SignatureResolver.resolve opts sessionReference $ read $ Text.unpack idVar QTSignatureMorphism -> case Map.lookup "id" variables of Nothing -> fail "SignatureMorphism query: Variable \"id\" not provided." Just idVar -> SignatureMorphismResolver.resolve opts sessionReference $ read $ Text.unpack idVar return $ resultToResponse queryType resultM unencloseQuotesAndUnpack :: Text.Text -> String unencloseQuotesAndUnpack = Text.unpack . Text.init . Text.tail resultToResponse :: QueryType -> Maybe GraphQLResult.Result -> String resultToResponse queryType = maybe noData (responseData queryType . GraphQLResult.toJson) responseData :: QueryType -> String -> String responseData queryType json = let keyword = case queryType of QTDGraph -> "dgraph" QTOMS -> "oms" QTSerialization -> "serialization" QTSignature -> "signature" QTSignatureMorphism -> "signatureMorphism" in "{\"data\": {\n \"" ++ keyword ++ "\":" ++ json ++ "}}" noData :: String noData = "{\"data\": null}" data QueryType = QTDGraph | QTOMS | QTSerialization | QTSignature | QTSignatureMorphism deriving Show determineQueryType :: Text -> IO QueryType determineQueryType queryArg | isQueryPrefix "query DGraph" = return QTDGraph | isQueryPrefix "query OMS" = return QTOMS | isQueryPrefix "query Serialization" = return QTSerialization | isQueryPrefix "query SignatureMorphism" = return QTSignatureMorphism | isQueryPrefix "query Signature" = return QTSignature | otherwise = fail ("Query not supported.\n" ++ "The query must begin with \"query X\", where X is one of " ++ "DGraph, OMS, Serialization, Signature, SignatureMorphism\n" ++ "This is due to a limitation of only mimicking a GraphQL API.") where isQueryPrefix :: String -> Bool isQueryPrefix s = Text.isPrefixOf (Text.pack s) queryArg
spechub/Hets
PGIP/GraphQL/Resolver.hs
gpl-2.0
3,556
0
17
637
792
403
389
65
10
module TestFakeAst where import FakeAst f x = ( (HsModule (AJust ((ModuleName("TestFakeAst")))) (ANothing) (SomeArray([ ( (ImportDecl (NoSourceText) ((ModuleName("FakeAst"))) (ANothing) (False) (False) (False) (False) (ANothing) (ANothing)))])) (SomeArray([ ( (ValD (FunBind ( (Unqual (OccName("f")))) (MG ( (SomeArray([ ( (Match (FunRhs ( (Unqual (OccName("f")))) (Prefix) (NoSrcStrict)) (SomeArray([ ( (VarPat ( (Unqual (OccName("x"))))))])) (ANothing) (GRHSs (SomeArray([ ( (GRHS (EmptyArray) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsModule")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("ModuleName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"FakeAst\"") FastString("FakeAst")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("TyClD")))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("DataDecl")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsQTvs")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("Prefix")))))))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsDataDefn")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("DataType")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsModule\"") FastString("HsModule")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"MyFuncF\"") FastString("MyFuncF")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"OccName\"") FastString("OccName")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsParTy")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))]))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Match\"") FastString("Match")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"PlaceHolder\"") FastString("PlaceHolder")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"WpHole\"") FastString("WpHole")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"FromSource\"") FastString("FromSource")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"MG\"") FastString("MG")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Unqual\"") FastString("Unqual")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"FunBind\"") FastString("FunBind")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ValD\"") FastString("ValD")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"EmptyLocalBinds\"") FastString("EmptyLocalBinds")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"SourceText\"") FastString("SourceText")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsString\"") FastString("HsString")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsLit\"") FastString("HsLit")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"IL\"") FastString("IL")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Bool\"") FastString("Bool")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Integer\"") FastString("Integer"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsIntegral\"") FastString("HsIntegral")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"OverLit\"") FastString("OverLit")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsOverLit\"") FastString("HsOverLit")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"GRHS\"") FastString("GRHS")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"GRHSs\"") FastString("GRHSs")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"FunRhs\"") FastString("FunRhs")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Prefix\"") FastString("Prefix")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"NoSrcStrict\"") FastString("NoSrcStrict")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"NoLocationInfo\"") FastString("NoLocationInfo")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"FastString\"") FastString("FastString")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Source\"") FastString("Source")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTupleTy")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("HsBoxedOrConstraintTuple")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))])))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))])))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))]))))))))))))))))]))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"VarPat\"") FastString("VarPat")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ModuleName\"") FastString("ModuleName")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ANothing\"") FastString("ANothing")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"AJust\"") FastString("AJust")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"CheckSource\"") FastString("CheckSource")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"EmptyArray\"") FastString("EmptyArray")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"SomeArray\"") FastString("SomeArray")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsListTy")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))))))))]))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"PrefixCon\"") FastString("PrefixCon")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsVar\"") FastString("HsVar")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ConDeclH98\"") FastString("ConDeclH98")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"DataType\"") FastString("DataType")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"DataDecl\"") FastString("DataDecl")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsDataDefn\"") FastString("HsDataDefn")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsQTvs\"") FastString("HsQTvs")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"TyClD\"") FastString("TyClD")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"GHCPrimName\"") FastString("GHCPrimName")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTupleTy")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("HsBoxedOrConstraintTuple")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))])))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))])))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))])))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppsTy")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsAppPrefix")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"String\"") FastString("String"))))))))))))))))))))))))))))]))))))))))))))))]))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Exact\"") FastString("Exact")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ConPatIn\"") FastString("ConPatIn")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"ImportDecl\"") FastString("ImportDecl")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Bool\"") FastString("Bool")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Bool\"") FastString("Bool")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Bool\"") FastString("Bool")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Bool\"") FastString("Bool")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsPar\"") FastString("HsPar")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsApp\"") FastString("HsApp")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsTyVar\"") FastString("HsTyVar")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"NotPromoted\"") FastString("NotPromoted")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsParTy\"") FastString("HsParTy")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsAppsTy\"") FastString("HsAppsTy")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsAppPrefix\"") FastString("HsAppPrefix")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsTupleTy\"") FastString("HsTupleTy")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsBoxedOrConstraintTuple\"") FastString("HsBoxedOrConstraintTuple")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsListTy\"") FastString("HsListTy")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsDerivingClause\"") FastString("HsDerivingClause")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"HsIB\"") FastString("HsIB")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Foo\"") FastString("Foo"))))))))))))))))))))))])))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("ConDeclH98")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"NoSourceText\"") FastString("NoSourceText")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("AJust")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("PrefixCon")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing"))))))))))))))])))))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsDerivingClause")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsIB")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsTyVar")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NotPromoted")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"Show\"") FastString("Show")))))))))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder"))))))))))))]))))))))))))))))))])))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("ValD")))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("FunBind")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"checkSrc\"") FastString("checkSrc")))))))))))))))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("MG")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("Match")))))) ( (HsPar ( (HsApp ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("FunRhs")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"checkSrc\"") FastString("checkSrc")))))))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("Prefix")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("NoSrcStrict")))))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("VarPat")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"x\"") FastString("x")))))))))))))))))))))), ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("VarPat")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"y\"") FastString("y"))))))))))))))))))))))])))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("GRHSs")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("SomeArray")))))) ( (HsPar ( (ExplicitList (PlaceHolder) (ANothing) (SomeArray([ ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("GRHS")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsApp")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsApp ( (HsVar ( (Unqual (OccName("HsApp")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsVar")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"CheckSource\"") FastString("CheckSource")))))))))))))))))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsVar")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"x\"") FastString("x")))))))))))))))))))))))))))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("HsVar")))))) ( (HsPar ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("Unqual")))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("OccName")))))) ( (HsPar ( (HsLit (HsString (SourceText "\"y\"") FastString("y"))))))))))))))))))))))))))))))))))])))))))))))) ( (HsPar ( (HsApp ( (HsVar ( (Unqual (OccName("NoLocationInfo")))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyLocalBinds"))))))))))))))))))))))])))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("FromSource")))))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("WpHole")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("PlaceHolder")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("EmptyArray"))))))))))))))))))])))))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing")))))))))) ( (HsPar ( (HsVar ( (Unqual (OccName("ANothing"))))))))))))))))])) (NoLocationInfo (EmptyLocalBinds)))))]))) (EmptyArray) (PlaceHolder) (FromSource)) (WpHole) (PlaceHolder) (EmptyArray))))])) (ANothing) (ANothing)))
h4ck3rm1k3/gcc-ontology
tests/FakeAst3.hs
gpl-3.0
135,387
0
239
47,793
67,519
37,375
30,144
11,570
1
-- Haskell Music Player, client for the MPD (Music Player Daemon) -- Copyright (C) 2011 Ivan Vitjuk <[email protected]> -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module GuiData ( GuiData(GData), GuiDataRef, mpd, pbar, playButton, prevStatus, currentStatus, plist, GuiData.currentSong ) where import Network.MPD import Graphics.UI.Gtk import Data.IORef import {-# SOURCE #-} qualified Progressbar as PB import {-# SOURCE #-} qualified Playlist as PL import {-# SOURCE #-} qualified CurrentSong as CS data GuiData = GData { mpd :: MPDPersistent, playButton :: Button, prevStatus :: Network.MPD.Status, currentStatus :: Network.MPD.Status, pbar :: PB.Data, plist :: PL.Data, currentSong :: CS.Data } type GuiDataRef = IORef GuiData
ivitjuk/Haskell-Music-Player
src/GuiData.hs
gpl-3.0
1,461
0
9
346
160
111
49
22
0
{-# LANGUAGE GeneralizedNewtypeDeriving , MultiParamTypeClasses , FunctionalDependencies , NamedFieldPuns #-} module Runtime.Runtime where import Control.Concurrent import Control.Monad.State (StateT, execStateT) import Control.Monad.Except import Data.Map.Strict (Map, (!)) import qualified Data.Map.Strict as M import Runtime.Hole import Runtime.GarbageCollector import Runtime.PID import Name type RunTimeM s obj = StateT (RunTimeState s obj) (ExceptT obj IO) type ShadowMap obj = Map ThreadId (PID obj) type Fn st a = Name -> [a] -> Runtime st a Response data Response = Response newtype Runtime st obj a = Runtime {unRuntime :: RunTimeM st obj a} deriving (Functor, Applicative, Monad) class Obj a where toObj :: PID a -> a class StateClass st obj | st -> obj where markState :: st -> IO [PID obj] data RunTimeState st obj = RTS { response :: Hole obj , error :: Hole obj , state :: st , gc :: GC obj , ourself :: PID obj , shadows :: ShadowMap obj , fn :: Fn st obj -- this is where eval goes } run :: RunTimeState st obj -> RunTimeM st obj a -> IO (Either obj (RunTimeState st obj)) run s a = runExceptT $ execStateT a s markRTS :: StateClass st obj => RunTimeState st obj -> IO [PID obj] markRTS rts = ((M.elems (shadows rts)) ++) <$> markState (state rts)
antarestrader/sapphire
Runtime/Runtime.hs
gpl-3.0
1,348
0
11
299
457
254
203
39
1
{-# LANGUAGE DeriveDataTypeable, TypeFamilies #-} module Main where import Hip.HipSpec import Prelude hiding ((+), (*), (++), (&&),(||),not) import Data.Typeable import Test.QuickCheck hiding (Prop) import Control.Applicative data Bin = One | ZeroAnd Bin | OneAnd Bin deriving (Show, Eq, Ord, Typeable) data Nat = Z | S Nat deriving (Show,Eq,Ord,Typeable) instance Enum Nat where toEnum 0 = Z toEnum n = S (toEnum (pred n)) fromEnum Z = 0 fromEnum (S n) = succ (fromEnum n) instance Arbitrary Nat where arbitrary = sized $ \s -> do x <- choose (0,round (sqrt (toEnum s))) return (toEnum x) instance CoArbitrary Nat where coarbitrary Z = variant 0 coarbitrary (S x) = variant (-1) . coarbitrary x instance Classify Nat where type Value Nat = Nat evaluate x = count 100 x `seq` return x where count 0 _ = undefined count n Z = () count n (S x) = count (n-1) x {-toNat :: Bin -> Nat toNat = toNatFrom (S Z) toNatFrom :: Nat -> Bin -> Nat toNatFrom k One = k toNatFrom k (ZeroAnd xs) = toNatFrom (k + k) xs toNatFrom k (OneAnd xs) = k + toNatFrom (k + k) xs-} toNat :: Bin -> Nat toNat One = S Z toNat (ZeroAnd xs) = toNat xs + toNat xs toNat (OneAnd xs) = S (toNat xs + toNat xs) infixl 6 + -- infixl 7 * (+) :: Nat -> Nat -> Nat Z + m = m S n + m = S (n + m) -- (*) :: Nat -> Nat -> Nat -- Z * m = Z -- S n * m = m + (n * m) s :: Bin -> Bin s One = ZeroAnd One s (ZeroAnd xs) = OneAnd xs s (OneAnd xs) = ZeroAnd (s xs) plus :: Bin -> Bin -> Bin plus One xs = s xs plus xs One = s xs plus (ZeroAnd xs) (ZeroAnd ys) = ZeroAnd (plus xs ys) plus (ZeroAnd xs) (OneAnd ys) = OneAnd (plus xs ys) plus (OneAnd xs) (ZeroAnd ys) = OneAnd (plus xs ys) plus (OneAnd xs) (OneAnd ys) = ZeroAnd (s (plus xs ys)) prop_s :: Bin -> Prop Nat prop_s n = toNat (s n) =:= S (toNat n) prop_plus :: Bin -> Bin -> Prop Nat prop_plus x y = toNat (x `plus` y) =:= toNat x + toNat y main = hipSpec "BinLists.hs" conf 3 where conf = [ var "x" natType , var "y" natType , var "z" natType , var "x" boolType , var "y" boolType , var "z" boolType , var "xs" listType , var "ys" listType , var "zs" listType , con "Z" Z , con "S" S , con "+" (+) -- , con "*" (*) , con "s" s , con "plus" plus , con "One" One , con "ZeroAnd" ZeroAnd , con "OneAnd" OneAnd , con "toNat" toNat -- , con "toNatFrom" toNatFrom ] where boolType = undefined :: Bool natType = undefined :: Nat listType = undefined :: Bin instance Arbitrary Bin where arbitrary = sized arbBin where arbBin s = frequency [(1, return One), (s, ZeroAnd <$> arbBin (s-1)), (s, OneAnd <$> arbBin (s-1))] instance Classify Bin where type Value Bin = Bin evaluate = return -- The tiny Hip Prelude (=:=) = (=:=) type Prop a = a
danr/hipspec
examples/old-examples/quickspec/BinLists.hs
gpl-3.0
3,241
2
17
1,154
1,190
621
569
82
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.WebmasterTools.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.WebmasterTools.Types.Product where import Network.Google.Prelude import Network.Google.WebmasterTools.Types.Sum -- | Information about the various content types in the sitemap. -- -- /See:/ 'wmxSitemapContent' smart constructor. data WmxSitemapContent = WmxSitemapContent' { _wscIndexed :: !(Maybe (Textual Int64)) , _wscType :: !(Maybe Text) , _wscSubmitted :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WmxSitemapContent' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wscIndexed' -- -- * 'wscType' -- -- * 'wscSubmitted' wmxSitemapContent :: WmxSitemapContent wmxSitemapContent = WmxSitemapContent' {_wscIndexed = Nothing, _wscType = Nothing, _wscSubmitted = Nothing} -- | The number of URLs from the sitemap that were indexed (of the content -- type). wscIndexed :: Lens' WmxSitemapContent (Maybe Int64) wscIndexed = lens _wscIndexed (\ s a -> s{_wscIndexed = a}) . mapping _Coerce -- | The specific type of content in this sitemap. For example: web. wscType :: Lens' WmxSitemapContent (Maybe Text) wscType = lens _wscType (\ s a -> s{_wscType = a}) -- | The number of URLs in the sitemap (of the content type). wscSubmitted :: Lens' WmxSitemapContent (Maybe Int64) wscSubmitted = lens _wscSubmitted (\ s a -> s{_wscSubmitted = a}) . mapping _Coerce instance FromJSON WmxSitemapContent where parseJSON = withObject "WmxSitemapContent" (\ o -> WmxSitemapContent' <$> (o .:? "indexed") <*> (o .:? "type") <*> (o .:? "submitted")) instance ToJSON WmxSitemapContent where toJSON WmxSitemapContent'{..} = object (catMaybes [("indexed" .=) <$> _wscIndexed, ("type" .=) <$> _wscType, ("submitted" .=) <$> _wscSubmitted]) -- -- /See:/ 'apidimensionFilterGroup' smart constructor. data APIdimensionFilterGroup = APIdimensionFilterGroup' { _afgFilters :: !(Maybe [APIdimensionFilter]) , _afgGroupType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'APIdimensionFilterGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'afgFilters' -- -- * 'afgGroupType' apidimensionFilterGroup :: APIdimensionFilterGroup apidimensionFilterGroup = APIdimensionFilterGroup' {_afgFilters = Nothing, _afgGroupType = Nothing} afgFilters :: Lens' APIdimensionFilterGroup [APIdimensionFilter] afgFilters = lens _afgFilters (\ s a -> s{_afgFilters = a}) . _Default . _Coerce afgGroupType :: Lens' APIdimensionFilterGroup (Maybe Text) afgGroupType = lens _afgGroupType (\ s a -> s{_afgGroupType = a}) instance FromJSON APIdimensionFilterGroup where parseJSON = withObject "APIdimensionFilterGroup" (\ o -> APIdimensionFilterGroup' <$> (o .:? "filters" .!= mempty) <*> (o .:? "groupType")) instance ToJSON APIdimensionFilterGroup where toJSON APIdimensionFilterGroup'{..} = object (catMaybes [("filters" .=) <$> _afgFilters, ("groupType" .=) <$> _afgGroupType]) -- -- /See:/ 'apiDataRow' smart constructor. data APIDataRow = APIDataRow' { _adrImpressions :: !(Maybe (Textual Double)) , _adrKeys :: !(Maybe [Text]) , _adrCtr :: !(Maybe (Textual Double)) , _adrClicks :: !(Maybe (Textual Double)) , _adrPosition :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'APIDataRow' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adrImpressions' -- -- * 'adrKeys' -- -- * 'adrCtr' -- -- * 'adrClicks' -- -- * 'adrPosition' apiDataRow :: APIDataRow apiDataRow = APIDataRow' { _adrImpressions = Nothing , _adrKeys = Nothing , _adrCtr = Nothing , _adrClicks = Nothing , _adrPosition = Nothing } adrImpressions :: Lens' APIDataRow (Maybe Double) adrImpressions = lens _adrImpressions (\ s a -> s{_adrImpressions = a}) . mapping _Coerce adrKeys :: Lens' APIDataRow [Text] adrKeys = lens _adrKeys (\ s a -> s{_adrKeys = a}) . _Default . _Coerce adrCtr :: Lens' APIDataRow (Maybe Double) adrCtr = lens _adrCtr (\ s a -> s{_adrCtr = a}) . mapping _Coerce adrClicks :: Lens' APIDataRow (Maybe Double) adrClicks = lens _adrClicks (\ s a -> s{_adrClicks = a}) . mapping _Coerce adrPosition :: Lens' APIDataRow (Maybe Double) adrPosition = lens _adrPosition (\ s a -> s{_adrPosition = a}) . mapping _Coerce instance FromJSON APIDataRow where parseJSON = withObject "APIDataRow" (\ o -> APIDataRow' <$> (o .:? "impressions") <*> (o .:? "keys" .!= mempty) <*> (o .:? "ctr") <*> (o .:? "clicks") <*> (o .:? "position")) instance ToJSON APIDataRow where toJSON APIDataRow'{..} = object (catMaybes [("impressions" .=) <$> _adrImpressions, ("keys" .=) <$> _adrKeys, ("ctr" .=) <$> _adrCtr, ("clicks" .=) <$> _adrClicks, ("position" .=) <$> _adrPosition]) -- -- /See:/ 'apidimensionFilter' smart constructor. data APIdimensionFilter = APIdimensionFilter' { _afOperator :: !(Maybe Text) , _afDimension :: !(Maybe Text) , _afExpression :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'APIdimensionFilter' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'afOperator' -- -- * 'afDimension' -- -- * 'afExpression' apidimensionFilter :: APIdimensionFilter apidimensionFilter = APIdimensionFilter' {_afOperator = Nothing, _afDimension = Nothing, _afExpression = Nothing} afOperator :: Lens' APIdimensionFilter (Maybe Text) afOperator = lens _afOperator (\ s a -> s{_afOperator = a}) afDimension :: Lens' APIdimensionFilter (Maybe Text) afDimension = lens _afDimension (\ s a -> s{_afDimension = a}) afExpression :: Lens' APIdimensionFilter (Maybe Text) afExpression = lens _afExpression (\ s a -> s{_afExpression = a}) instance FromJSON APIdimensionFilter where parseJSON = withObject "APIdimensionFilter" (\ o -> APIdimensionFilter' <$> (o .:? "operator") <*> (o .:? "dimension") <*> (o .:? "expression")) instance ToJSON APIdimensionFilter where toJSON APIdimensionFilter'{..} = object (catMaybes [("operator" .=) <$> _afOperator, ("dimension" .=) <$> _afDimension, ("expression" .=) <$> _afExpression]) -- | A list of rows, one per result, grouped by key. Metrics in each row are -- aggregated for all data grouped by that key either by page or property, -- as specified by the aggregation type parameter. -- -- /See:/ 'searchAnalyticsQueryResponse' smart constructor. data SearchAnalyticsQueryResponse = SearchAnalyticsQueryResponse' { _saqrRows :: !(Maybe [APIDataRow]) , _saqrResponseAggregationType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SearchAnalyticsQueryResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'saqrRows' -- -- * 'saqrResponseAggregationType' searchAnalyticsQueryResponse :: SearchAnalyticsQueryResponse searchAnalyticsQueryResponse = SearchAnalyticsQueryResponse' {_saqrRows = Nothing, _saqrResponseAggregationType = Nothing} -- | A list of rows grouped by the key values in the order given in the -- query. saqrRows :: Lens' SearchAnalyticsQueryResponse [APIDataRow] saqrRows = lens _saqrRows (\ s a -> s{_saqrRows = a}) . _Default . _Coerce -- | How the results were aggregated. saqrResponseAggregationType :: Lens' SearchAnalyticsQueryResponse (Maybe Text) saqrResponseAggregationType = lens _saqrResponseAggregationType (\ s a -> s{_saqrResponseAggregationType = a}) instance FromJSON SearchAnalyticsQueryResponse where parseJSON = withObject "SearchAnalyticsQueryResponse" (\ o -> SearchAnalyticsQueryResponse' <$> (o .:? "rows" .!= mempty) <*> (o .:? "responseAggregationType")) instance ToJSON SearchAnalyticsQueryResponse where toJSON SearchAnalyticsQueryResponse'{..} = object (catMaybes [("rows" .=) <$> _saqrRows, ("responseAggregationType" .=) <$> _saqrResponseAggregationType]) -- | Contains detailed information about a specific URL submitted as a -- sitemap. -- -- /See:/ 'wmxSitemap' smart constructor. data WmxSitemap = WmxSitemap' { _wsContents :: !(Maybe [WmxSitemapContent]) , _wsPath :: !(Maybe Text) , _wsIsSitemapsIndex :: !(Maybe Bool) , _wsLastSubmitted :: !(Maybe DateTime') , _wsWarnings :: !(Maybe (Textual Int64)) , _wsLastDownloaded :: !(Maybe DateTime') , _wsIsPending :: !(Maybe Bool) , _wsType :: !(Maybe Text) , _wsErrors :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WmxSitemap' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wsContents' -- -- * 'wsPath' -- -- * 'wsIsSitemapsIndex' -- -- * 'wsLastSubmitted' -- -- * 'wsWarnings' -- -- * 'wsLastDownloaded' -- -- * 'wsIsPending' -- -- * 'wsType' -- -- * 'wsErrors' wmxSitemap :: WmxSitemap wmxSitemap = WmxSitemap' { _wsContents = Nothing , _wsPath = Nothing , _wsIsSitemapsIndex = Nothing , _wsLastSubmitted = Nothing , _wsWarnings = Nothing , _wsLastDownloaded = Nothing , _wsIsPending = Nothing , _wsType = Nothing , _wsErrors = Nothing } -- | The various content types in the sitemap. wsContents :: Lens' WmxSitemap [WmxSitemapContent] wsContents = lens _wsContents (\ s a -> s{_wsContents = a}) . _Default . _Coerce -- | The url of the sitemap. wsPath :: Lens' WmxSitemap (Maybe Text) wsPath = lens _wsPath (\ s a -> s{_wsPath = a}) -- | If true, the sitemap is a collection of sitemaps. wsIsSitemapsIndex :: Lens' WmxSitemap (Maybe Bool) wsIsSitemapsIndex = lens _wsIsSitemapsIndex (\ s a -> s{_wsIsSitemapsIndex = a}) -- | Date & time in which this sitemap was submitted. Date format is in RFC -- 3339 format (yyyy-mm-dd). wsLastSubmitted :: Lens' WmxSitemap (Maybe UTCTime) wsLastSubmitted = lens _wsLastSubmitted (\ s a -> s{_wsLastSubmitted = a}) . mapping _DateTime -- | Number of warnings for the sitemap. These are generally non-critical -- issues with URLs in the sitemaps. wsWarnings :: Lens' WmxSitemap (Maybe Int64) wsWarnings = lens _wsWarnings (\ s a -> s{_wsWarnings = a}) . mapping _Coerce -- | Date & time in which this sitemap was last downloaded. Date format is in -- RFC 3339 format (yyyy-mm-dd). wsLastDownloaded :: Lens' WmxSitemap (Maybe UTCTime) wsLastDownloaded = lens _wsLastDownloaded (\ s a -> s{_wsLastDownloaded = a}) . mapping _DateTime -- | If true, the sitemap has not been processed. wsIsPending :: Lens' WmxSitemap (Maybe Bool) wsIsPending = lens _wsIsPending (\ s a -> s{_wsIsPending = a}) -- | The type of the sitemap. For example: rssFeed. wsType :: Lens' WmxSitemap (Maybe Text) wsType = lens _wsType (\ s a -> s{_wsType = a}) -- | Number of errors in the sitemap. These are issues with the sitemap -- itself that need to be fixed before it can be processed correctly. wsErrors :: Lens' WmxSitemap (Maybe Int64) wsErrors = lens _wsErrors (\ s a -> s{_wsErrors = a}) . mapping _Coerce instance FromJSON WmxSitemap where parseJSON = withObject "WmxSitemap" (\ o -> WmxSitemap' <$> (o .:? "contents" .!= mempty) <*> (o .:? "path") <*> (o .:? "isSitemapsIndex") <*> (o .:? "lastSubmitted") <*> (o .:? "warnings") <*> (o .:? "lastDownloaded") <*> (o .:? "isPending") <*> (o .:? "type") <*> (o .:? "errors")) instance ToJSON WmxSitemap where toJSON WmxSitemap'{..} = object (catMaybes [("contents" .=) <$> _wsContents, ("path" .=) <$> _wsPath, ("isSitemapsIndex" .=) <$> _wsIsSitemapsIndex, ("lastSubmitted" .=) <$> _wsLastSubmitted, ("warnings" .=) <$> _wsWarnings, ("lastDownloaded" .=) <$> _wsLastDownloaded, ("isPending" .=) <$> _wsIsPending, ("type" .=) <$> _wsType, ("errors" .=) <$> _wsErrors]) -- | List of sitemaps. -- -- /See:/ 'sitemapsListResponse' smart constructor. newtype SitemapsListResponse = SitemapsListResponse' { _slrSitemap :: Maybe [WmxSitemap] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SitemapsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slrSitemap' sitemapsListResponse :: SitemapsListResponse sitemapsListResponse = SitemapsListResponse' {_slrSitemap = Nothing} -- | Contains detailed information about a specific URL submitted as a -- sitemap. slrSitemap :: Lens' SitemapsListResponse [WmxSitemap] slrSitemap = lens _slrSitemap (\ s a -> s{_slrSitemap = a}) . _Default . _Coerce instance FromJSON SitemapsListResponse where parseJSON = withObject "SitemapsListResponse" (\ o -> SitemapsListResponse' <$> (o .:? "sitemap" .!= mempty)) instance ToJSON SitemapsListResponse where toJSON SitemapsListResponse'{..} = object (catMaybes [("sitemap" .=) <$> _slrSitemap]) -- -- /See:/ 'searchAnalyticsQueryRequest' smart constructor. data SearchAnalyticsQueryRequest = SearchAnalyticsQueryRequest' { _saqrAggregationType :: !(Maybe Text) , _saqrDataState :: !(Maybe Text) , _saqrRowLimit :: !(Maybe (Textual Int32)) , _saqrEndDate :: !(Maybe Text) , _saqrSearchType :: !(Maybe Text) , _saqrDimensionFilterGroups :: !(Maybe [APIdimensionFilterGroup]) , _saqrStartDate :: !(Maybe Text) , _saqrStartRow :: !(Maybe (Textual Int32)) , _saqrDimensions :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SearchAnalyticsQueryRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'saqrAggregationType' -- -- * 'saqrDataState' -- -- * 'saqrRowLimit' -- -- * 'saqrEndDate' -- -- * 'saqrSearchType' -- -- * 'saqrDimensionFilterGroups' -- -- * 'saqrStartDate' -- -- * 'saqrStartRow' -- -- * 'saqrDimensions' searchAnalyticsQueryRequest :: SearchAnalyticsQueryRequest searchAnalyticsQueryRequest = SearchAnalyticsQueryRequest' { _saqrAggregationType = Nothing , _saqrDataState = Nothing , _saqrRowLimit = Nothing , _saqrEndDate = Nothing , _saqrSearchType = Nothing , _saqrDimensionFilterGroups = Nothing , _saqrStartDate = Nothing , _saqrStartRow = Nothing , _saqrDimensions = Nothing } -- | [Optional; Default is \"auto\"] How data is aggregated. If aggregated by -- property, all data for the same property is aggregated; if aggregated by -- page, all data is aggregated by canonical URI. If you filter or group by -- page, choose AUTO; otherwise you can aggregate either by property or by -- page, depending on how you want your data calculated; see the help -- documentation to learn how data is calculated differently by site versus -- by page. Note: If you group or filter by page, you cannot aggregate by -- property. If you specify any value other than AUTO, the aggregation type -- in the result will match the requested type, or if you request an -- invalid type, you will get an error. The API will never change your -- aggregation type if the requested type is invalid. saqrAggregationType :: Lens' SearchAnalyticsQueryRequest (Maybe Text) saqrAggregationType = lens _saqrAggregationType (\ s a -> s{_saqrAggregationType = a}) -- | [Optional] If \"all\" (case-insensitive), data will include fresh data. -- If \"final\" (case-insensitive) or if this parameter is omitted, the -- returned data will include only finalized data. saqrDataState :: Lens' SearchAnalyticsQueryRequest (Maybe Text) saqrDataState = lens _saqrDataState (\ s a -> s{_saqrDataState = a}) -- | [Optional; Default is 1000] The maximum number of rows to return. Must -- be a number from 1 to 5,000 (inclusive). saqrRowLimit :: Lens' SearchAnalyticsQueryRequest (Maybe Int32) saqrRowLimit = lens _saqrRowLimit (\ s a -> s{_saqrRowLimit = a}) . mapping _Coerce -- | [Required] End date of the requested date range, in YYYY-MM-DD format, -- in PST (UTC - 8:00). Must be greater than or equal to the start date. -- This value is included in the range. saqrEndDate :: Lens' SearchAnalyticsQueryRequest (Maybe Text) saqrEndDate = lens _saqrEndDate (\ s a -> s{_saqrEndDate = a}) -- | [Optional; Default is \"web\"] The search type to filter for. saqrSearchType :: Lens' SearchAnalyticsQueryRequest (Maybe Text) saqrSearchType = lens _saqrSearchType (\ s a -> s{_saqrSearchType = a}) -- | [Optional] Zero or more filters to apply to the dimension grouping -- values; for example, \'query contains \"buy\"\' to see only data where -- the query string contains the substring \"buy\" (not case-sensitive). -- You can filter by a dimension without grouping by it. saqrDimensionFilterGroups :: Lens' SearchAnalyticsQueryRequest [APIdimensionFilterGroup] saqrDimensionFilterGroups = lens _saqrDimensionFilterGroups (\ s a -> s{_saqrDimensionFilterGroups = a}) . _Default . _Coerce -- | [Required] Start date of the requested date range, in YYYY-MM-DD format, -- in PST time (UTC - 8:00). Must be less than or equal to the end date. -- This value is included in the range. saqrStartDate :: Lens' SearchAnalyticsQueryRequest (Maybe Text) saqrStartDate = lens _saqrStartDate (\ s a -> s{_saqrStartDate = a}) -- | [Optional; Default is 0] Zero-based index of the first row in the -- response. Must be a non-negative number. saqrStartRow :: Lens' SearchAnalyticsQueryRequest (Maybe Int32) saqrStartRow = lens _saqrStartRow (\ s a -> s{_saqrStartRow = a}) . mapping _Coerce -- | [Optional] Zero or more dimensions to group results by. Dimensions are -- the group-by values in the Search Analytics page. Dimensions are -- combined to create a unique row key for each row. Results are grouped in -- the order that you supply these dimensions. saqrDimensions :: Lens' SearchAnalyticsQueryRequest [Text] saqrDimensions = lens _saqrDimensions (\ s a -> s{_saqrDimensions = a}) . _Default . _Coerce instance FromJSON SearchAnalyticsQueryRequest where parseJSON = withObject "SearchAnalyticsQueryRequest" (\ o -> SearchAnalyticsQueryRequest' <$> (o .:? "aggregationType") <*> (o .:? "dataState") <*> (o .:? "rowLimit") <*> (o .:? "endDate") <*> (o .:? "searchType") <*> (o .:? "dimensionFilterGroups" .!= mempty) <*> (o .:? "startDate") <*> (o .:? "startRow") <*> (o .:? "dimensions" .!= mempty)) instance ToJSON SearchAnalyticsQueryRequest where toJSON SearchAnalyticsQueryRequest'{..} = object (catMaybes [("aggregationType" .=) <$> _saqrAggregationType, ("dataState" .=) <$> _saqrDataState, ("rowLimit" .=) <$> _saqrRowLimit, ("endDate" .=) <$> _saqrEndDate, ("searchType" .=) <$> _saqrSearchType, ("dimensionFilterGroups" .=) <$> _saqrDimensionFilterGroups, ("startDate" .=) <$> _saqrStartDate, ("startRow" .=) <$> _saqrStartRow, ("dimensions" .=) <$> _saqrDimensions]) -- | List of sites with access level information. -- -- /See:/ 'sitesListResponse' smart constructor. newtype SitesListResponse = SitesListResponse' { _slrSiteEntry :: Maybe [WmxSite] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SitesListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slrSiteEntry' sitesListResponse :: SitesListResponse sitesListResponse = SitesListResponse' {_slrSiteEntry = Nothing} -- | Contains permission level information about a Search Console site. For -- more information, see Permissions in Search Console. slrSiteEntry :: Lens' SitesListResponse [WmxSite] slrSiteEntry = lens _slrSiteEntry (\ s a -> s{_slrSiteEntry = a}) . _Default . _Coerce instance FromJSON SitesListResponse where parseJSON = withObject "SitesListResponse" (\ o -> SitesListResponse' <$> (o .:? "siteEntry" .!= mempty)) instance ToJSON SitesListResponse where toJSON SitesListResponse'{..} = object (catMaybes [("siteEntry" .=) <$> _slrSiteEntry]) -- | Contains permission level information about a Search Console site. For -- more information, see Permissions in Search Console. -- -- /See:/ 'wmxSite' smart constructor. data WmxSite = WmxSite' { _wsPermissionLevel :: !(Maybe Text) , _wsSiteURL :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WmxSite' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wsPermissionLevel' -- -- * 'wsSiteURL' wmxSite :: WmxSite wmxSite = WmxSite' {_wsPermissionLevel = Nothing, _wsSiteURL = Nothing} -- | The user\'s permission level for the site. wsPermissionLevel :: Lens' WmxSite (Maybe Text) wsPermissionLevel = lens _wsPermissionLevel (\ s a -> s{_wsPermissionLevel = a}) -- | The URL of the site. wsSiteURL :: Lens' WmxSite (Maybe Text) wsSiteURL = lens _wsSiteURL (\ s a -> s{_wsSiteURL = a}) instance FromJSON WmxSite where parseJSON = withObject "WmxSite" (\ o -> WmxSite' <$> (o .:? "permissionLevel") <*> (o .:? "siteUrl")) instance ToJSON WmxSite where toJSON WmxSite'{..} = object (catMaybes [("permissionLevel" .=) <$> _wsPermissionLevel, ("siteUrl" .=) <$> _wsSiteURL])
brendanhay/gogol
gogol-webmaster-tools/gen/Network/Google/WebmasterTools/Types/Product.hs
mpl-2.0
24,097
0
20
5,919
4,614
2,649
1,965
512
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidEnterprise.Grouplicenses.Get -- 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) -- -- Retrieves details of an enterprise\'s group license for a product. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.grouplicenses.get@. module Network.Google.Resource.AndroidEnterprise.Grouplicenses.Get ( -- * REST Resource GrouplicensesGetResource -- * Creating a Request , grouplicensesGet , GrouplicensesGet -- * Request Lenses , ggXgafv , ggUploadProtocol , ggEnterpriseId , ggAccessToken , ggUploadType , ggGroupLicenseId , ggCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.grouplicenses.get@ method which the -- 'GrouplicensesGet' request conforms to. type GrouplicensesGetResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "groupLicenses" :> Capture "groupLicenseId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GroupLicense -- | Retrieves details of an enterprise\'s group license for a product. -- -- /See:/ 'grouplicensesGet' smart constructor. data GrouplicensesGet = GrouplicensesGet' { _ggXgafv :: !(Maybe Xgafv) , _ggUploadProtocol :: !(Maybe Text) , _ggEnterpriseId :: !Text , _ggAccessToken :: !(Maybe Text) , _ggUploadType :: !(Maybe Text) , _ggGroupLicenseId :: !Text , _ggCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GrouplicensesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggXgafv' -- -- * 'ggUploadProtocol' -- -- * 'ggEnterpriseId' -- -- * 'ggAccessToken' -- -- * 'ggUploadType' -- -- * 'ggGroupLicenseId' -- -- * 'ggCallback' grouplicensesGet :: Text -- ^ 'ggEnterpriseId' -> Text -- ^ 'ggGroupLicenseId' -> GrouplicensesGet grouplicensesGet pGgEnterpriseId_ pGgGroupLicenseId_ = GrouplicensesGet' { _ggXgafv = Nothing , _ggUploadProtocol = Nothing , _ggEnterpriseId = pGgEnterpriseId_ , _ggAccessToken = Nothing , _ggUploadType = Nothing , _ggGroupLicenseId = pGgGroupLicenseId_ , _ggCallback = Nothing } -- | V1 error format. ggXgafv :: Lens' GrouplicensesGet (Maybe Xgafv) ggXgafv = lens _ggXgafv (\ s a -> s{_ggXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ggUploadProtocol :: Lens' GrouplicensesGet (Maybe Text) ggUploadProtocol = lens _ggUploadProtocol (\ s a -> s{_ggUploadProtocol = a}) -- | The ID of the enterprise. ggEnterpriseId :: Lens' GrouplicensesGet Text ggEnterpriseId = lens _ggEnterpriseId (\ s a -> s{_ggEnterpriseId = a}) -- | OAuth access token. ggAccessToken :: Lens' GrouplicensesGet (Maybe Text) ggAccessToken = lens _ggAccessToken (\ s a -> s{_ggAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ggUploadType :: Lens' GrouplicensesGet (Maybe Text) ggUploadType = lens _ggUploadType (\ s a -> s{_ggUploadType = a}) -- | The ID of the product the group license is for, e.g. -- \"app:com.google.android.gm\". ggGroupLicenseId :: Lens' GrouplicensesGet Text ggGroupLicenseId = lens _ggGroupLicenseId (\ s a -> s{_ggGroupLicenseId = a}) -- | JSONP ggCallback :: Lens' GrouplicensesGet (Maybe Text) ggCallback = lens _ggCallback (\ s a -> s{_ggCallback = a}) instance GoogleRequest GrouplicensesGet where type Rs GrouplicensesGet = GroupLicense type Scopes GrouplicensesGet = '["https://www.googleapis.com/auth/androidenterprise"] requestClient GrouplicensesGet'{..} = go _ggEnterpriseId _ggGroupLicenseId _ggXgafv _ggUploadProtocol _ggAccessToken _ggUploadType _ggCallback (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy GrouplicensesGetResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Grouplicenses/Get.hs
mpl-2.0
5,190
0
19
1,231
782
455
327
116
1
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module Main where import AttoScoped (sep,value,statefulParseOnly) import Event(Event,eventOrNamespace,event,source) import Decision(Decision,decisionClass) import Maker import GatherStrings (gatherStrings) import qualified GatherLocalisations as GL (localisations) import qualified GatherTraits as GT(traits) import Localisation import Extract(extractArchiveToTemp) import Codec.Archive.FileCollection ( FileCollection, AssocFile, File, getDirectoryContents, doesFileExist, getFile, readFile, fileName ) import Debug.Trace(trace) import System.Console.GetOpt(ArgDescr(..),ArgOrder(Permute),OptDescr(..),getOpt,usageInfo) import System.Environment(getArgs) import System.Exit(ExitCode(..),exitWith,exitSuccess) import System.Directory(doesDirectoryExist) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BS(toStrict,fromStrict) import qualified Data.Text as T import Data.Text.IO as TIO hiding (readFile) import Data.Text.Encoding (decodeLatin1) import Text.Parsec.Pos(sourceName,initialPos) import Data.Attoparsec.Text(many',parseOnly) import Data.Either(isLeft,isRight,lefts,rights) import Data.Maybe(fromJust,isNothing) import Data.Monoid((<>)) import Data.Foldable(foldl') import Data.List as L(nub,sort) import qualified Data.Set as S(Set,fromList,difference,toList,map,size) import Control.Monad(filterM,liftM,when) import Control.Applicative(liftA2) import Codec.Archive.Zip(Archive,toArchive) import Control.Monad.STM(atomically) import Control.Concurrent.STM.TChan import Control.Concurrent(forkIO) import Control.Parallel.Strategies(parListChunk,rseq,using) import Control.Monad.State(runStateT) import Prelude hiding (readFile) printErrors file (Left (e,Nothing)) = TIO.putStrLn (T.pack (fileName file) <> ": " <> e) printErrors _ (Left (e,Just source)) = TIO.putStrLn $ e <> "\n\tat: " <> T.pack (show source) printErrors _ (Right _) = return () stripBoM input = if BS.length input < 3 then input else case BS.take 3 input of "\xef\xbb\xbf" → BS.drop 3 input _ → input readEventFile :: File f ⇒ f → IO (Maybe [Event]) readEventFile file = do fileContents ← decodeLatin1 . stripBoM . BS.toStrict <$> readFile file parseResult ← case statefulParseOnly (sep *> many' value) (initialPos $ fileName file) fileContents of Right x → return x Left x → trace ("Parse failed in " <> fileName file) $ Prelude.putStrLn (fileName file <> ": " <> show x) >> return [] let events' = map (runMaker eventOrNamespace) parseResult mapM_ (printErrors file) events' return $ if isRight $ sequence events' then Just $ lefts $ rights events' else Nothing -- checkFiles takes a list of file paths and checks the syntax in each of them. -- If any errors are found, a summary of the files with errors is printed and -- the program exits. If no errors are found, the function returns a list of all -- the events parsed. readEventFiles :: [FilePath] → IO [Event] readEventFiles = readFiles readEventFile readDecisionFile :: FilePath → IO (Maybe [Decision]) readDecisionFile file = do fileContents ← decodeLatin1 . stripBoM . BS.toStrict <$> readFile file parseResult ← case statefulParseOnly (sep *> many' value) (initialPos file) fileContents of Right x → return x Left e → trace ("Parse failed in " <> file) $ return [] let decisions = map (runMaker decisionClass) parseResult mapM_ (printErrors file) decisions return $ if isRight $ sequence decisions then Just $ concat $ rights decisions else mempty readFiles :: (FilePath → IO (Maybe [a])) → [FilePath] → IO [a] readFiles handler files = do checked ← mapM handler files case filter isNothing checked of [] → return $ concatMap fromJust checked _ → exitWith $ ExitFailure 1 strings :: ([Event],[Event]) → ([Decision],[Decision]) → T.Text strings (_,modEvents) (_,modDecisions) = T.unlines . L.nub . L.sort $ gatherStrings modEvents <> gatherStrings modDecisions locals :: S.Set Event → S.Set Entry → T.Text locals events keys = -- For each event, get all the localisation keys and pair them with the name of the file let usedKeys = S.fromList $ concatMap (\e → map (`emptyEntry` (fileFromSource $ Event.source e)) $ GL.localisations e) $ S.toList events in let notDefined = usedKeys `S.difference` keys in "Used keys: " <> T.pack (show $ S.size usedKeys) <> ("\nUndefined keys:\n" <> T.unlines (S.toList $ S.map (\l → Localisation.key l <> " in " <> T.pack (Localisation.source l)) notDefined)) <> "Total undefined keys: " <> T.pack (show $ S.size notDefined) where emptyEntry k = Entry k "" "" "" "" "" "" "" "" fileFromSource (Just s) = sourceName s fileFromSource Nothing = "unknown" traits (_,modEvents) (_,modDecisions) = T.unlines . L.nub . L.sort $ GT.traits modEvents <> GT.traits modDecisions allLocalisations :: (FileCollection base, FileCollection mod) ⇒ base → Maybe mod → IO [Entry] allLocalisations game mod = do rawLocalisations ← getLocalisations game mod if any isLeft rawLocalisations then TIO.putStr (T.unlines $ lefts rawLocalisations) >> return [] else return $ concat $ rights rawLocalisations getLocalisations :: (FileCollection base, FileCollection mod) ⇒ base → Maybe mod → IO [Either T.Text [Entry]] getLocalisations gamePath modPath = do (baseFiles,modFiles) ← getFiles gamePath modPath "localisation" contents ← liftA2 (<>) (zip (map fileName baseFiles) <$> decodeFiles gamePath baseFiles) (zip (map fileName modFiles) <$> decodeFiles (fromJust modPath) modFiles) return $ map (uncurry localisationFile) contents where decodeFiles :: FileCollection fc ⇒ fc → [AssocFile fc] → IO [T.Text] -- The dummy fc parameter is needed to typecheck correctly decodeFiles _ = mapM (\f → decodeLatin1 <$> BS.toStrict <$> readFile f) getDirectoryFiles :: FileCollection d ⇒ d → FilePath → IO [FilePath] getDirectoryFiles root dir = (map (dir<>) <$> getDirectoryContents root dir) >>= filterM (doesFileExist root) -- Is is a regular file? getFiles :: (FileCollection base, FileCollection mod) ⇒ base → Maybe mod → FilePath → IO ([AssocFile base],[AssocFile mod]) getFiles base (Just mod) subPath = do modFiles ← getDirectoryFiles mod ("geheimnisnacht" <> "/"<>subPath<>"/") baseFiles ← filter (not . flip elem modFiles) <$> getDirectoryFiles base ("/"<>subPath<>"/") return (map (getFile base) baseFiles,map (getFile mod) modFiles) getFiles base Nothing subPath = do baseFiles ← getDirectoryFiles base ("/"<>subPath<>"/") return (map (getFile base) baseFiles,[]) -- Get the base game events and any mod events getEvents :: FilePath → Maybe FilePath → IO ([Event],[Event]) getEvents base mod = do (baseFiles,modFiles) ← getFiles base mod "events" trace ("Found " <> show (length baseFiles + length modFiles) <> " event files") $ return () (,) <$> readEventFiles baseFiles <*> readEventFiles modFiles -- | Given the base and mod directories, return lists of all decisions in the -- game. readDecisions :: FilePath → Maybe FilePath → IO ([Decision],[Decision]) readDecisions base mod = do (baseFiles,modFiles) ← getFiles base mod "decisions" trace ("Found " <> show (length baseFiles + length modFiles) <> " decision files") $ return () (,) <$> readFiles readDecisionFile baseFiles <*> readFiles readDecisionFile modFiles data Action = Localisations | Strings | Traits deriving (Eq,Show) data Resources = Resources { baseEvents :: [Event], modEvents :: [Event], baseDecisions :: [Decision], modDecisions :: [Decision], localisations :: [Entry] } deriving (Eq,Show) dispatch :: Resources → Action → T.Text dispatch r Localisations = locals (S.fromList $ baseEvents r <> modEvents r) (S.fromList $ localisations r) dispatch r Strings = strings (baseEvents r, modEvents r) (baseDecisions r, modDecisions r) dispatch r Traits = traits (baseEvents r, modEvents r) (baseDecisions r, modDecisions r) dispatchFromChan :: Resources → TChan Action → TChan T.Text → IO () dispatchFromChan resources action response = do atomically $ do next ← readTChan action let result = dispatch resources next writeTChan response result dispatchFromChan resources action response -- Start a checker thread for a given mod. The first TChan is used to send check -- requests to the thread, while the second is used to send results back startCheck :: Resources → IO (TChan Action, TChan T.Text) startCheck resources = do action ← atomically newTChan response ← atomically newTChan _ ← forkIO $ dispatchFromChan resources action response return (action,response) argDispatcher :: Args → TChan Action → TChan T.Text → IO () argDispatcher a action result = do _ ← when (_traits a) $ onChan Traits _ ← when (stringResources a) $ onChan Strings when (localisationKeys a) $ onChan Localisations where onChan a = atomically (writeTChan action a) >> atomically (readTChan result) >>= TIO.putStrLn -- There will be three entry possibilities. -- Mode | baseType | modType -- server | directory | archive -- local | directory | archivePath -- local | directory | directoryPath -- In each mode, we want a function that returns a path to a directory containing -- the mod files. archiveMod :: Archive → IO FilePath archiveMod = extractArchiveToTemp localMod path = do isDir ← doesDirectoryExist path if isDir then return path else liftM ( toArchive . BS.fromStrict ) (BS.readFile path) >>= extractArchiveToTemp data Args = Args { showHelp :: Bool , stringResources :: Bool , localisationKeys :: Bool , _traits :: Bool , gameRootPath :: FilePath , modRootPath :: Maybe FilePath } deriving (Eq,Show) defaultArgs = Args { showHelp = False , stringResources = False , localisationKeys = False , _traits = False , gameRootPath = "/home/joel/.local/share/Steam/steamapps/common/Crusader Kings II/" , modRootPath = Nothing } options :: [OptDescr (Args → Args)] options = [ Option "s" ["strings"] (NoArg $ \o → o { stringResources = True }) "find all string resources" , Option "l" ["localisations"] (NoArg $ \o → o { localisationKeys = True }) "find all localisation keys" , Option "t" ["traits"] (NoArg $ \o → o { _traits = True }) "find all referenced traits" ] <> [ Option "G" ["game-dir"] (ReqArg (\fp o → o { gameRootPath = fp }) "DIR") "folder containing the base game" , Option "M" ["mod-dir"] (ReqArg (\fp o → o { modRootPath = Just fp}) "DIR") "folder containing the mod" ] <> [ Option "h" ["help"] (NoArg $ \o → o { showHelp = True }) "print this message" ] main = do (rawArgs,_,_) ← getOpt Permute options <$> getArgs let args = foldl' (flip ($)) defaultArgs rawArgs when (showHelp args) $ Prelude.putStrLn (usageInfo "validator:" options) >> exitSuccess let (rawModPath,gamePath) = (modRootPath args,gameRootPath args) modPath ← sequence $ localMod <$> rawModPath (baseEvents,modEvents) ← getEvents gamePath modPath (baseDecisions,modDecisions) ← readDecisions gamePath modPath uncheckedLocalisations ← sequence <$> getLocalisations gamePath modPath let locs = case uncheckedLocalisations of Right l → trace "got localisations" l Left e → error $ "localisation error: " <> T.unpack e (action,result) ← startCheck Resources { baseEvents, modEvents, baseDecisions, modDecisions, localisations = concat locs } argDispatcher args action result exitSuccess
joelwilliamson/validator
CheckFile.hs
agpl-3.0
11,928
0
24
2,241
3,845
2,011
1,834
217
3
{-# OPTIONS_GHC -Wall #-} -- | -- Module : Data.Change.Row -- Copyright : Copyright (C) 2013 Leigh Simpson <[email protected]> -- License : GNU LGPL 2.1 -- -- Functions and types for operations involving rows. module Data.Change.Row ( -- * Row type Row(), -- ** Creating rows fromList, rounds, queens, kings, tittums, reverseRounds, plainBobLeadHead, cyclicLeadHead, fromNumber, -- ** Accessing rows toList, getBell, findBell, -- ** Row transpositions transpose, divide, inverse, -- ** Properties of rows bells, isRounds, isPlainBobLeadhead, isCyclicLeadHead, sign, number, cycles, order, -- * Length type Length(), -- ** Length functions getLength, makeLength, -- * Parity type Parity(Even, Odd), -- * Number type Number, ) where import Data.Change.Bell import Data.List(sort) import Data.Maybe(fromJust, isNothing) import qualified Data.List(transpose) ----------------------------------------------------------------------------- -- | The row type -- A row is defined as a list of bells with the restrictions that bells may not -- be repeated nor omitted. -- Rows act as mathematical permutations, and may be manipulated as such. newtype Row = Row { -- | Returns the row as a @Bell@ list. toList :: [Bell] } deriving (Eq) -- | Construct a row from a list of bells fromList :: [Bell] -> Maybe Row fromList [] = Nothing fromList bs | (length bs) > maxLength = Nothing | (sort bs) == roundsList = Just $ Row bs | otherwise = Nothing where maxLength = toInt (maxBound :: Bell) roundsList = [fromInt 1 .. fromInt $ length bs] -- | Construct rounds on @n@ bells. rounds :: Length -> Row rounds (Length n) = Row [fromInt 1 .. fromInt n] -- | Construct queens on @n@ bells. queens :: Length -> Row queens (Length n) = Row $ [fromInt 1, fromInt 3 .. fromInt n] ++ [fromInt 2, fromInt 4 .. fromInt n] -- | Construct kings on @n@ bells. kings :: Length -> Row kings (Length 1) = Row [fromInt 1] kings (Length n) = Row $ reverse [fromInt 1, fromInt 3 .. fromInt n] ++ [fromInt 2, fromInt 4 .. fromInt n] -- | Construct tittums on @n@ bells. tittums :: Length -> Row tittums (Length n) = Row $ concat $ Data.List.transpose [[fromInt 1 .. fromInt half], [fromInt $ half + 1 .. fromInt n]] where half = (n + 1) `div` 2 -- | Construct reverse rounds on @n@ bells. reverseRounds :: Length -> Row reverseRounds (Length n) = Row $ reverse [fromInt 1 .. fromInt n] -- | Construct a plain bob lead head. -- Returns the first plain bob lead head on @n@ bells with @h@ hunt bells. plainBobLeadHead :: Length -- ^ Number of bells, @n@ -> Length -- ^ Number of hunt bells, @h@ -> Row plainBobLeadHead _ _ = error "Not implemented" -- | Construct a cyclic lead head. -- Computed as @(13456..2)^c@ on @n@ bells with @h@ hunt bells. cyclicLeadHead :: Length -- ^ Number of bells, @n@ -> Length -- ^ Number of hunt bells, @h@ -> Int -- ^ Lead head number, @c@ -> Row cyclicLeadHead _ _ _ = error "Not implemented" -- | Generates a row from an index number. fromNumber :: Number -> Row fromNumber _ = error "Not implemented" -- | Retrieve a bell by index. getBell :: Row -> Int -> Bell getBell (Row bs) i = bs !! (i - 1) -- | Find the index of a bell. Indices are 1-based, i.e. they are between 1 and -- @n@, the number of bells. findBell :: Row -> Bell -> Int findBell (Row bs) b | toInt b > length bs = error "Bell out of range" | otherwise = (1+) $ length $ takeWhile (/= b) bs -- | Transpose a row by another. transpose :: Row -> Row -> Row transpose x y | bells x /= bells y = error "Mismatched row length" | otherwise = Row [getBell x (toInt b) | b <- toList y] -- | Divide a row by another. divide :: Row -> Row -> Row divide x y | bells x /= bells y = error "Mismatched row length" | otherwise = transpose x (inverse y) -- | Find the inverse of a row. inverse :: Row -> Row inverse r = Row [fromInt $ findBell r b | b <- toList $ rounds $ bells r] -- | How many bells are in the row? bells :: Row -> Length bells (Row bs) = Length $ length bs -- | Is the row rounds? isRounds :: Row -> Bool isRounds r = r == (rounds . bells $ r) -- | Is the row a plain bob lead head? isPlainBobLeadhead :: Row -> Maybe (Length, Int) isPlainBobLeadhead _ = error "Not implemented" -- | Is the row a cyclic lead head? isCyclicLeadHead :: Row -> Maybe (Length, Int) isCyclicLeadHead _ = error "Not implemented" -- | Is the row odd or even? sign :: Row -> Parity sign _ = error "Not implemented" -- | Calculates a unique index number for the row. number :: Row -> Number number _ = error "Not implemented" -- | Express the row as a product of disjoint cycles. cycles :: Row -> [[Bell]] cycles _ = error "Not implemented" -- | Calculate the order of the row. order :: Row -> Integer order _ = error "Not implemented" instance Show Row where showsPrec _ r = foldr (.) id (map ((:) . toChar) (toList r)) instance Read Row where readsPrec _ [] = [] readsPrec _ cs | or $ map isNothing maybeBellList = [] | otherwise = case bellList of Just r -> [(r, [])] Nothing -> [] where maybeBellList = map fromChar cs bellList = fromList $ map fromJust maybeBellList instance Ord Row where compare x y | cx /= cy = compare cx cy | otherwise = compare ix iy where cx = bells x cy = bells y ix = number x iy = number y ----------------------------------------------------------------------------- -- | Type representing the length of a row. newtype Length = Length { -- | Access row length. getLength :: Int } deriving (Eq, Ord, Show, Read) -- | Construct a row length. makeLength :: Int -> Length makeLength i | i < minLength = error $ "Length must be >= " ++ show minLength | i > maxLength = error $ "Length must be <= " ++ show maxLength | otherwise = Length i where minLength = getLength (minBound :: Length) maxLength = getLength (maxBound :: Length) instance Bounded Length where minBound = Length 1 maxBound = Length $ toInt $ (maxBound :: Bell) ----------------------------------------------------------------------------- -- | The parity of a row. -- Rows are defined as even or odd. -- Even rows require an even number of pairwise swaps to return to rounds. data Parity = Even | Odd deriving (Eq, Enum, Show, Read) ----------------------------------------------------------------------------- -- | Type representing a row number. -- A row may be identified by a unique row number in the range @1 .. n!@ where -- @n@ is the number of bells. type Number = Integer
simpleigh/change.hs
src/Data/Change/Row.hs
lgpl-2.1
7,406
0
12
2,254
1,736
932
804
137
1
-------------------------------------------------------------------------------- -- See end of this file for licence information. -------------------------------------------------------------------------------- -- | -- Module : Swish -- Copyright : (c) 2003, Graham Klyne, 2009 Vasili I Galchin, 2011, 2012 Douglas Burke -- License : GPL V2 -- -- Maintainer : Douglas Burke -- Stability : experimental -- Portability : H98 -- -- Swish: Semantic Web Inference Scripting in Haskell -- -- This program is a simple skeleton for constructing Semantic Web [1] -- inference tools in Haskell, using the RDF graph and several RDF -- parsers (at present Notation 3 and NTriples). -- -- It might be viewed as a kind of embroyonic CWM [2] in Haskell, -- except that the intent is that Haskell will be used as a primary -- language for defining inferences. As such, Swish is an open-ended -- toolkit for constructing new special-purpose Semantic Web -- applications rather than a closed, self-contained general-purpose -- SW application. As such, it is part of another experiment along -- the lines described in [3]. -- -- The script format used by Swish is described in -- "Swish.Script". -- -- Users wishing to process RDF data directly may prefer to look at -- the following modules; "Swish.RDF", "Swish.RDF.Parser.Turtle", -- "Swish.RDF.Parser.N3", "Swish.RDF.Parser.NTriples", -- "Swish.RDF.Formatter.Turtle", "Swish.RDF.Formatter.N3" -- and "Swish.RDF.Formatter.NTriples". -- -- (1) Semantic web: <http://www.w3.org/2001/sw/> -- -- (2) CWM: <http://www.w3.org/2000/10/swap/doc/cwm.html> -- -- (3) Motivation: <http://www.w3.org/2000/10/swap/doc/Motivation.html> -- -- (4) Notation 3: <http://www.w3.org/TeamSubmission/2008/SUBM-n3-20080114/> -- -- (5) Turtle: <http://www.w3.org/TR/turtle/> -- -- (6) RDF: <http://www.w3.org/RDF/> -- -- Notes -- -- I anticipate that this module may be used as a starting point for -- creating new programs rather then as a complete program in its own -- right. The functionality built into this code is selected with a -- view to testing the Haskell modules for handling RDF rather than -- for performing any particular application processing (though -- development as a tool with some broader utility is not ruled out). -- -- With the following in ghci: -- -- >>> :m + Swish -- >>> :set prompt "swish> " -- -- then we can run a Swish script (format described in "Swish.Script") -- by saying: -- -- >>> runSwish "-s=script.ss" -- ExitSuccess -- -- or convert a file from Turtle to NTriples format with: -- -- >>> runSwish "-ttl -i=foo.ttl -nt -o=foo.nt" -- ExitSuccess -- -- You can also use `validateCommands` by giving it the individual commands, -- such as -- -- >>> let Right cs = validateCommands ["-ttl", "-i=file1.ttl", "-c=file2.ttl"] -- >>> cs -- [SwishAction: -ttl,SwishAction: -i=file1.ttl,SwishAction: -c=file2.ttl] -- >>> st <- runSwishActions cs -- >>> st -- The graphs do not compare as equal. -- -------------------------------------------------------------------------------- module Swish ( SwishStatus(..) , SwishAction , runSwish , runSwishActions , displaySwishHelp , splitArguments , validateCommands ) where import Swish.Commands ( swishFormat , swishBase , swishInput , swishOutput , swishMerge , swishCompare , swishGraphDiff , swishScript ) import Swish.Monad (SwishStateIO, SwishState(..), SwishStatus(..) , SwishFormat(..) , emptyState) import Swish.QName (qnameFromURI) import Control.Monad.State (execStateT) import Control.Monad (liftM) import Network.URI (parseURI) import Data.Char (isSpace) import Data.Either (partitionEithers) import System.Exit (ExitCode(ExitSuccess, ExitFailure)) ------------------------------------------------------------ -- Command line description ------------------------------------------------------------ -- we do not display the version in the help file to avoid having -- to include the Paths_swish module (so that we can use this from -- an interactive environment). -- usageText :: [String] usageText = [ "Swish: Read, merge, write, compare and process RDF graphs." , "" , "Usage: swish option option ..." , "" , "where the options are processed from left to right, and may be" , "any of the following:" , "-h display this message." , "-? display this message." , "-v display Swish version and quit." , "-q do not display Swish version on start up." , "-nt use Ntriples format for subsequent input and output." , "-ttl use Turtle format for subsequent input and output." , "-n3 use Notation3 format for subsequent input and output (default)" , "-i[=file] read file in selected format into the graph workspace," , " replacing any existing graph." , "-m[=file] merge file in selected format with the graph workspace." , "-c[=file] compare file in selected format with the graph workspace." , "-d[=file] show graph differences between the file in selected" , " format and the graph workspace. Differences are displayed" , " to the standard output stream." , "-o[=file] write the graph workspace to a file in the selected format." , "-s[=file] read and execute Swish script commands from the named file." , "-b[=base] set or clear the base URI. The semantics of this are not" , " fully defined yet." , "" , " If an optional filename value is omitted, the standard input" , " or output stream is used, as appropriate." , "" , "Exit status codes:" , "Success - operation completed successfully/graphs compare equal" , "1 - graphs compare different" , "2 - input data format error" , "3 - file access problem" , "4 - command line error" , "5 - script file execution error" , "" , "Examples:" , "" , "swish -i=file" , " read file as Notation3, and report any syntax errors." , "swish -i=file1 -o=file2" , " read file1 as Notation3, report any syntax errors, and output the" , " resulting graph as reformatted Notation3 (the output format" , " is not perfect but may be improved)." , "swish -nt -i=file -n3 -o" , " read file as NTriples and output as Notation3 to the screen." , "swich -i=file1 -c=file2" , " read file1 and file2 as notation3, report any syntax errors, and" , " if both are OK, compare the resulting graphs to indicate whether" , " or not they are equivalent." ] -- | Write out the help for Swish displaySwishHelp :: IO () displaySwishHelp = mapM_ putStrLn usageText ------------------------------------------------------------ -- Swish command line interpreter ------------------------------------------------------------ -- -- This is a composite monad combining some state with an IO -- Monad. lift allows a pure IO monad to be used as a step -- of the computation. -- -- | Return any arguments that need processing immediately, namely -- the \"help\", \"quiet\" and \"version\" options. -- splitArguments :: [String] -> ([String], [String]) splitArguments = partitionEithers . map splitArgument splitArgument :: String -> Either String String splitArgument "-?" = Left "-h" splitArgument "-h" = Left "-h" splitArgument "-v" = Left "-v" splitArgument "-q" = Left "-q" splitArgument x = Right x -- | Represent a Swish action. At present there is no way to create these -- actions other than 'validateCommands'. -- newtype SwishAction = SA (String, SwishStateIO ()) instance Show SwishAction where show (SA (lbl,_)) = "SwishAction: " ++ lbl -- | Given a list of command-line arguments create the list of actions -- to perform or a string and status value indicating an input error. validateCommands :: [String] -> Either (String, SwishStatus) [SwishAction] validateCommands args = let (ls, rs) = partitionEithers (map validateCommand args) in case ls of (e:_) -> Left e [] -> Right rs -- This allows you to say "-nt=foo" and currently ignores the values -- passed through. This may change -- validateCommand :: String -> Either (String, SwishStatus) SwishAction validateCommand cmd = let (nam,more) = break (=='=') cmd arg = drop 1 more marg = if null arg then Nothing else Just arg wrap f = Right $ SA (cmd, f marg) wrap1 f = Right $ SA (cmd, f) in case nam of "-ttl" -> wrap1 $ swishFormat Turtle "-nt" -> wrap1 $ swishFormat NT "-n3" -> wrap1 $ swishFormat N3 "-i" -> wrap swishInput "-m" -> wrap swishMerge "-c" -> wrap swishCompare "-d" -> wrap swishGraphDiff "-o" -> wrap swishOutput "-b" -> validateBase cmd marg "-s" -> wrap swishScript _ -> Left ("Invalid command line argument: "++cmd, SwishArgumentError) -- | Execute the given set of actions. swishCommands :: [SwishAction] -> SwishStateIO () swishCommands = mapM_ swishCommand -- | Execute an action. swishCommand :: SwishAction -> SwishStateIO () swishCommand (SA (_,act)) = act validateBase :: String -> Maybe String -> Either (String, SwishStatus) SwishAction validateBase arg Nothing = Right $ SA (arg, swishBase Nothing) validateBase arg (Just b) = case parseURI b >>= qnameFromURI of j@(Just _) -> Right $ SA (arg, swishBase j) _ -> Left ("Invalid base URI <" ++ b ++ ">", SwishArgumentError) ------------------------------------------------------------ -- Interactive test function (e.g. for use in ghci) ------------------------------------------------------------ -- this ignores the "flags" options, namely -- -q / -h / -? / -v -- | Parse and run the given string as if given at the command -- line. The \"quiet\", \"version\" and \"help\" options are -- ignored. -- runSwish :: String -> IO ExitCode runSwish cmdline = do let args = breakAll isSpace cmdline (_, cmds) = splitArguments args case validateCommands cmds of Left (emsg, ecode) -> do putStrLn $ "Swish exit: " ++ emsg return $ ExitFailure $ fromEnum ecode Right acts -> do ec <- runSwishActions acts case ec of SwishSuccess -> return ExitSuccess _ -> do putStrLn $ "Swish exit: " ++ show ec return $ ExitFailure $ fromEnum ec -- |Break list into a list of sublists, separated by element -- satisfying supplied condition. breakAll :: (a -> Bool) -> [a] -> [[a]] breakAll _ [] = [] breakAll p s = let (h,s') = break p s in h : breakAll p (drop 1 s') -- | Execute the given set of actions. runSwishActions :: [SwishAction] -> IO SwishStatus runSwishActions acts = exitcode `liftM` execStateT (swishCommands acts) emptyState -------------------------------------------------------------------------------- -- -- Copyright (c) 2003, Graham Klyne, 2009 Vasili I Galchin, -- 2011, 2012 Douglas Burke -- All rights reserved. -- -- This file is part of Swish. -- -- Swish is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- Swish is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Swish; if not, write to: -- The Free Software Foundation, Inc., -- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- --------------------------------------------------------------------------------
DougBurke/swish
src/Swish.hs
lgpl-2.1
12,019
0
18
2,667
1,504
878
626
147
12
module Main where data Position t = Position t deriving (Show) stagger (Position d) = Position (d + 2) crawl (Position d) = Position (d + 1) rtn x = x x >>== f = f x
Leonidas-from-XIV/7langs7weeks
haskell/drunken-monad.hs
apache-2.0
188
0
7
59
91
47
44
6
1
{- Copyright 2015 Tristan Aubrey-Jones 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. -} {-| Copyright : (c) Tristan Aubrey-Jones, 2015 License : Apache-2 Maintainer : [email protected] Stability : experimental For more information please see <http://www.flocc.net/> -} module Compiler.Front.Indices (Idx, IdxSet, IdxMonad, getnid, newid, newid', newid'', getid', getidST, newidST, newidST', getNextIdxST, setMinIndices) where import Control.Monad ( mapM ) import Control.Monad.State.Strict type Idx = Int type IdxSet = [Int] type IdxMonad m = StateT IdxSet m -- |Creates a new id for the given entry in the IdxSet, incrementing the set and returning the -- |modified one nid :: Int -> IdxSet -> IdxSet -> IdxSet nid i hl (h:t) = if (i == 0) then (nid (i-1) ((h+1):hl) t) else (nid (i-1) (h:hl) t) nid i hl [] = reverse hl -- |Gets the next id for a column in the idx set, and -- |returns that id, and the updated list. getnid :: Int -> IdxSet -> (Idx, IdxSet) getnid n s = let id = (s !! n) in (id, nid n [] s) getNextIdxST :: Monad m => String -> Int -> IdxMonad m Idx getNextIdxST msg col = do curMax <- get if col >= (length curMax) then error $ msg ++ ": index too large " ++ (show col) ++ " " ++ (show curMax) else return () return $ (curMax !! col)+1 setMinIndices :: Monad m => Idx -> IdxMonad m () setMinIndices minIdx = do modify (\st -> map (max minIdx) st) return () -- |Creates a new id (for the list of ids specified by the first paramter) newid :: Int -> State IdxSet Idx newid i = do curMax <- get modify (\max -> (nid i [] max)) return (curMax !! i) -- |Returns the id in the map list if it exists. if it does not, creates a new one -- |adds it to the map newid' :: Int -> Idx -> StateT [(Idx, Idx)] (State IdxSet) Idx newid' i v = do mp <- get case lookup v mp of Just v' -> return v' Nothing -> do v' <- lift (newid i) modify (\mp' -> (v,v') : mp') return v' -- |Returns the id in the map list if it exists. if it does not, creates a new one -- |adds it to the map, using a state transformer. newidST' :: Monad m => Int -> Idx -> StateT [(Idx, Idx)] (StateT IdxSet m) Idx newidST' i v = do mp <- get case lookup v mp of Just v' -> return v' Nothing -> do v' <- lift (newidST i) modify (\mp' -> (v,v') : mp') return v' -- |Creates a new id (for the list of ids specified by the first parameter) using -- |a state transformer, rather than a state monad. newid'' :: Monad m => Int -> StateT IdxSet m Idx newid'' i = do curMax <- get modify (\max -> (nid i [] max)) return (curMax !! i) newidST :: Monad m => Int -> StateT IdxSet m Idx newidST = newid'' -- |Looks up the id in the list, and returns the replacement if it exists -- |or the original if it doesnt getid' :: Idx -> StateT [(Idx, Idx)] (State IdxSet) Idx getid' v = do mp <- get case lookup v mp of Just v' -> return v' Nothing -> return v -- |Looks up the id in the list, and returns the replacement if it exists -- |or the original if it doesnt getidST :: Monad m => Idx -> StateT [(Idx, Idx)] (StateT IdxSet m) Idx getidST v = do mp <- get case lookup v mp of Just v' -> return v' Nothing -> return v
flocc-net/flocc
v0.1/Compiler/Front/Indices.hs
apache-2.0
3,748
0
16
883
1,081
556
525
62
2
module AlecSequences.A333400 (a333400, a333400_list) where import AlecSequences.A333398 (a333398_list) import Helpers.ListHelpers (firstDifferences) a333400_list = 0 : firstDifferences a333398_list a333400 n = a333400_list !! (n - 1)
peterokagey/haskellOEIS
src/AlecSequences/A333400.hs
apache-2.0
236
0
7
27
65
37
28
5
1
module Aws where -- module that gets list of spot prices import System.IO import Control.Monad.IO.Class import Control.Applicative import Data.Time.Clock import qualified Data.List as List import Control.Lens import Data.Maybe import Data.Text import qualified Data.Map as Map -- amazon imports import Network.AWS.EC2.DescribeSpotPriceHistory import Network.AWS.EC2.Types import Network.AWS.EC2 import Network.AWS.Data import Network.AWS.Prelude import Control.Monad.Trans.AWS --local imports -- import Debug.Trace as Trace data HawsSpotPrice = HawsSpotPrice { price :: Float, priceStr :: Text, zone :: Text, region :: Region, instanceType :: InstanceType, timestamp :: UTCTime } deriving (Show, Eq, Ord) fromAmazonka :: Region -> SpotPrice -> HawsSpotPrice fromAmazonka r s = HawsSpotPrice { price = (read . unpack . fromJust . (view sSpotPrice)) s, priceStr = (fromJust . (view sSpotPrice)) s, zone = (fromJust . (view sAvailabilityZone)) s, region = r, instanceType = fromJust $ view sInstanceType s, timestamp = (fromJust . (view sTimestamp)) s } filterLatestPrices :: [HawsSpotPrice] -> [HawsSpotPrice] filterLatestPrices ps = Map.elems $ List.foldl (\ m price@HawsSpotPrice{zone=a, instanceType=t, price=p} -> let key = (a, t) in if Map.member key m then m else Map.insert key price m) Map.empty sorted_list where sorted_list = (List.reverse . List.sortOn(timestamp)) ps getSpotPrices :: [Region] -> [Text] -> [InstanceType] -> IO [HawsSpotPrice] getSpotPrices rs zs ts= do lgr <- newLogger Info stdout env <- newEnv Discover <&> set envLogger lgr now <- getCurrentTime let rs' = if rs == [] then [NorthVirginia] else rs ts' = if ts == [] then [R3_XLarge] else ts start_time = addUTCTime (-60 * 15) now query = describeSpotPriceHistory & dsphInstanceTypes .~ ts' & dsphProductDescriptions .~ ["Linux/UNIX (Amazon VPC)"] & dsphStartTime .~ (Just start_time) & dsphEndTime .~ (Just now) pss <- sequenceA $ fmap (request env query) rs' let ps = mconcat pss return $ (List.sort . filterLatestPrices . filterByZone) ps where request :: Env -> DescribeSpotPriceHistory -> Region -> IO [HawsSpotPrice] request env query r = do resp <- (runResourceT . runAWST env . (within r). send) query return $ processResponse r resp processResponse:: Region -> DescribeSpotPriceHistoryResponse -> [HawsSpotPrice] processResponse r resp = fmap (fromAmazonka r) (resp ^. dsphrsSpotPriceHistory) filterByZone :: [HawsSpotPrice] -> [HawsSpotPrice] filterByZone ps | zs == [] = ps | True = List.filter (\s-> List.elem (zone s) zs) ps
huseyinyilmaz/spotprices
src/Aws.hs
apache-2.0
2,981
0
17
825
904
491
413
67
3
module Database.SqlServer.Create.FullTextStopList ( FullTextStopList ) where import Database.SqlServer.Create.Identifier import Database.SqlServer.Create.Entity import Test.QuickCheck import Text.PrettyPrint hiding (render) import Control.Monad data FullTextStopList = FullTextStopList { stoplistName :: RegularIdentifier , sourceStopList :: Maybe (Maybe FullTextStopList) } instance Arbitrary FullTextStopList where arbitrary = do x <- arbitrary y <- frequency [(50, return Nothing), (50, arbitrary)] return (FullTextStopList x y) instance Entity FullTextStopList where name = stoplistName render f = maybe empty render (join (sourceStopList f)) $+$ text "CREATE FULLTEXT STOPLIST" <+> renderName f <+> maybe (text ";") (\ q -> text "FROM" <+> systop q <> text "GO\n") (sourceStopList f) where systop = maybe (text "SYSTEM STOPLIST;\n") (\ x -> renderRegularIdentifier (stoplistName x) <> text ";\n")
fffej/sql-server-gen
src/Database/SqlServer/Create/FullTextStopList.hs
bsd-2-clause
1,102
0
14
312
287
152
135
28
0
{-# LANGUAGE OverloadedStrings #-} module Distribution.Nixpkgs.Haskell.FromCabal.Name ( toNixName, libNixName, buildToolNixName ) where import Data.Maybe import Data.String import Distribution.Package import Distribution.Text import Language.Nix -- | Map Cabal names to Nix attribute names. toNixName :: PackageName -> Identifier toNixName "" = error "toNixName: invalid empty package name" toNixName n = fromString (unPackageName n) -- | Map library names specified in Cabal files to Nix package identifiers. -- -- TODO: This list should not be hard-coded here; it belongs into the Nixpkgs -- repository. -- -- TODO: Re-use hook matching system from PostProcess.hs here. libNixName :: String -> [Identifier] libNixName "" = [] libNixName "adns" = return "adns" libNixName "alsa" = return "alsaLib" libNixName "alut" = return "freealut" libNixName "appindicator-0.1" = return "libappindicator-gtk2" libNixName "appindicator3-0.1" = return "libappindicator-gtk3" libNixName "asound" = return "alsaLib" libNixName "b2" = return "libb2" libNixName "bz2" = return "bzip2" libNixName "c++" = [] -- What is that? libNixName "cairo-gobject" = return "cairo" libNixName "cairo-pdf" = return "cairo" libNixName "cairo-ps" = return "cairo" libNixName "cairo-svg" = return "cairo" libNixName "crypt" = [] -- provided by glibc libNixName "crypto" = return "openssl" libNixName "curses" = return "ncurses" libNixName "dl" = [] -- provided by glibc libNixName "fftw3" = return "fftw" libNixName "fftw3f" = return "fftwFloat" libNixName "gconf" = return "GConf" libNixName "gconf-2.0" = return "GConf" libNixName "gdk-2.0" = return "gtk2" libNixName "gdk-3.0" = return "gtk3" libNixName "gdk-pixbuf-2.0" = return "gdk_pixbuf" libNixName "gdk-x11-2.0" = return "gdk_x11" libNixName "gio-2.0" = return "glib" libNixName "GL" = return "mesa" libNixName "GLU" = ["freeglut","mesa"] libNixName "glut" = ["freeglut","mesa"] libNixName "gnome-keyring" = return "gnome_keyring" libNixName "gnome-keyring-1" = return "gnome_keyring" libNixName "gnome-vfs-2.0" = return "gnome_vfs" libNixName "gnome-vfs-module-2.0" = return "gnome_vfs_module" libNixName "gobject-2.0" = return "glib" libNixName "gobject-introspection-1.0" = return "gobjectIntrospection" libNixName "gstreamer-audio-0.10" = return "gst-plugins-base" libNixName "gstreamer-audio-1.0" = return "gst-plugins-base" libNixName "gstreamer-base-0.10" = return "gst-plugins-base" libNixName "gstreamer-base-1.0" = return "gst-plugins-base" libNixName "gstreamer-controller-0.10" = return "gstreamer" libNixName "gstreamer-dataprotocol-0.10" = return "gstreamer" libNixName "gstreamer-net-0.10" = return "gst-plugins-base" libNixName "gstreamer-plugins-base-0.10" = return "gst-plugins-base" libNixName "gstreamer-video-1.0" = return "gst-plugins-base" libNixName "gthread-2.0" = return "glib" libNixName "gtk+-2.0" = return "gtk2" libNixName "gtk+-3.0" = return "gtk3" libNixName "gtk-x11-2.0" = return "gtk_x11" libNixName "gtksourceview-3.0" = return "gtksourceview3" libNixName "hidapi-libusb" = return "hidapi" libNixName "icudata" = return "icu" libNixName "icui18n" = return "icu" libNixName "icuuc" = return "icu" libNixName "idn" = return "libidn" libNixName "IL" = return "libdevil" libNixName "ImageMagick" = return "imagemagick" libNixName "Imlib2" = return "imlib2" libNixName "iw" = return "wirelesstools" libNixName "jack" = return "libjack2" libNixName "javascriptcoregtk-3.0" = return "webkitgtk24x-gtk3" -- These are the old APIs, of which 2.4 is the last provider, so map directly to that. libNixName "javascriptcoregtk-4.0" = return "webkitgtk" -- This is the current API, so let it reference an alias for the latest version. libNixName "jpeg" = return "libjpeg" libNixName "jvm" = return "jdk" libNixName "lapack" = return "liblapack" libNixName "lber" = return "openldap" libNixName "ldap" = return "openldap" libNixName "libavutil" = return "ffmpeg" libNixName "libgsasl" = return "gsasl" libNixName "libpcre" = return "pcre" libNixName "libR" = return "R" libNixName "libsoup-gnome-2.4" = return "libsoup" libNixName "libsystemd" = return "systemd" libNixName "libxml-2.0" = return "libxml2" libNixName "libzip" = return "libzip" libNixName "libzmq" = return "zeromq" libNixName "m" = [] -- in stdenv libNixName "magic" = return "file" libNixName "MagickWand" = return "imagemagick" libNixName "mpi" = return "openmpi" libNixName "ncursesw" = return "ncurses" libNixName "netsnmp" = return "net_snmp" libNixName "notify" = return "libnotify" libNixName "odbc" = return "unixODBC" libNixName "openblas" = return "openblasCompat" libNixName "panelw" = return "ncurses" libNixName "pangocairo" = return "pango" libNixName "pcap" = return "libpcap" libNixName "pfs-1.2" = return "pfstools" libNixName "png" = return "libpng" libNixName "poppler-glib" = return "poppler" libNixName "pq" = return "postgresql" libNixName "pthread" = [] libNixName "pulse" = return "libpulseaudio" libNixName "pulse-simple" = return "libpulseaudio" libNixName "python-3.3" = return "python33" libNixName "python-3.4" = return "python34" libNixName "Qt5Core" = return "qt5" libNixName "Qt5Gui" = return "qt5" libNixName "Qt5Qml" = return "qt5" libNixName "Qt5Quick" = return "qt5" libNixName "Qt5Widgets" = return "qt5" libNixName "rt" = [] -- in glibc libNixName "rtlsdr" = return "rtl-sdr" libNixName "ruby1.8" = return "ruby" libNixName "sane-backends" = return "saneBackends" libNixName "sass" = return "libsass" libNixName "sctp" = return "lksctp-tools" -- This is linux-specific, we should create a common attribute if we ever add sctp support for other systems. libNixName "sdl2" = return "SDL2" libNixName "ssh2" = return "libssh2" libNixName "sndfile" = return "libsndfile" libNixName "sodium" = return "libsodium" libNixName "sqlite3" = return "sqlite" libNixName "ssl" = return "openssl" libNixName "statgrab" = return "libstatgrab" libNixName "stdc++" = [] -- What is that? libNixName "stdc++.dll" = [] -- What is that? libNixName "systemd-journal" = return "systemd" libNixName "tag_c" = return "taglib" libNixName "taglib_c" = return "taglib" libNixName "udev" = return "systemd"; libNixName "uuid" = return "libossp_uuid"; libNixName "wayland-client" = return "wayland" libNixName "wayland-cursor" = return "wayland" libNixName "wayland-egl" = return "mesa" libNixName "wayland-server" = return "wayland" libNixName "webkit2gtk-4.0" = return "webkitgtk" -- This is the current API, so let it reference an alias for the latest version. libNixName "webkit2gtk-web-extension-4.0" = return "webkitgtk-web-extension" -- This package doesn't actually exist in nixpkgs at present. libNixName "webkitgtk-3.0" = return "webkitgtk24x-gtk3" -- These are the old APIs, of which 2.4 is the last provider, so map directly to that libNixName "X11" = return "libX11" libNixName "xau" = return "libXau" libNixName "Xcursor" = return "libXcursor" libNixName "xerces-c" = return "xercesc" libNixName "Xext" = return "libXext" libNixName "xft" = return "libXft" libNixName "Xi" = return "libXi" libNixName "Xinerama" = return "libXinerama" libNixName "xkbcommon" = return "libxkbcommon" libNixName "xml2" = return "libxml2" libNixName "Xpm" = return "libXpm" libNixName "Xrandr" = return "libXrandr" libNixName "Xrender" = return "libXrender" libNixName "Xss" = return "libXScrnSaver" libNixName "Xtst" = return "libXtst" libNixName "Xxf86vm" = return "libXxf86vm" libNixName "yaml-0.1" = return "libyaml" libNixName "z" = return "zlib" libNixName "zmq" = return "zeromq" libNixName x = return (guessNixIdentifier x) -- | Map build tool names to Nix attribute names. buildToolNixName :: String -> [Identifier] buildToolNixName "" = return (error "buildToolNixName: invalid empty dependency name") buildToolNixName "cabal" = return "cabal-install" buildToolNixName "ghc" = [] buildToolNixName "gtk2hsC2hs" = return "gtk2hs-buildtools" buildToolNixName "gtk2hsHookGenerator" = return "gtk2hs-buildtools" buildToolNixName "gtk2hsTypeGen" = return "gtk2hs-buildtools" buildToolNixName "hsc2hs" = [] buildToolNixName "nix-build" = return "nix" buildToolNixName "nix-env" = return "nix" buildToolNixName "nix-instantiate" = return "nix" buildToolNixName "nix-store" = return "nix" buildToolNixName x = return (fromString x) -- | Helper function to extract the package name from a String that may or may -- not be formatted like a Cabal package identifier. -- -- >>> guessNixIdentifier "foo-1.0" -- Identifier "foo" -- >>> guessNixIdentifier "foo" -- Identifier "foo" -- >>> guessNixIdentifier "foo - 0" -- Identifier "foo - 0" -- >>> guessNixIdentifier "1foo-1.0" -- Identifier "1foo" -- >>> guessNixIdentifier "-foo-1.0" -- Identifier "-foo-1.0" guessNixIdentifier :: String -> Identifier guessNixIdentifier x = fromString (fromMaybe x maybePackageId) where maybePackageId = unPackageName . pkgName <$> simpleParse x
Fuuzetsu/cabal2nix
src/Distribution/Nixpkgs/Haskell/FromCabal/Name.hs
bsd-3-clause
12,942
0
8
5,221
1,973
941
1,032
176
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Control.Applicative.Stacks where import Data.Functor.Compose import Data.Coerce import Control.Applicative import Control.Applicative.IO import Control.Applicative.Reader import Control.Applicative.Error import Data.Functor.Compose.Where -- Some syntax for stacks of some Compose type `c` type family Composing (c :: (* -> *) -> (* -> *) -> * -> *) (fs :: [* -> *]) where Composing c (f ': '[]) = f Composing c (f ': fs) = c f (Composing c fs) type Composed = Composing Compose -- An Example! all2 :: Composed '[(->) Int, IO] [Float] all2 = liftIO (putStrLn "Hi") *> (work <$> pure (1.0) <*> ask) where work :: Float -> Int -> [Float] work = flip replicate -- How to Use Your Own IO Type -- Note the deriving ApplicativeIO newtype MyIO a = MyIO (IO a) deriving (Functor, Applicative, ApplicativeIO) -- We now wrap up MyCompose with a new type, and instance all the Applicative***C classes newtype MyCompose f g a = MyCompose (Compose f g a) deriving (Functor,Applicative ,ApplicativeIOC OnLeft,ApplicativeIOC OnRight ,ApplicativeReaderC OnLeft r,ApplicativeReaderC OnRight r) -- And provide the top level Applicative*** classes. For IO, note that we use MyIO in the HasApplicativeIO constraint instance (HasApplicativeIO MyCompose MyIO f g flag) => ApplicativeIO (MyCompose f g) where liftIO = cliftIO (undefined :: flag) instance (HasApplicativeReader MyCompose (->) r f g flag) => ApplicativeReader r (MyCompose f g) where local = local' (undefined :: flag) -- all1 :: (MyCompose (MyCompose ((->) Int) ((->) Float)) MyIO) [Float] -- all1 :: Composing MyCompose '[(->) Int, (->) Float, MyIO] [Float] all1 :: (ApplicativeIO f, ApplicativeReader Float f, ApplicativeReader Int f) => f [Float] all1 = liftIO (putStrLn "Hi") *> (work <$> ask <*> ask) where work :: Float -> Int -> [Float] work = flip replicate runAll1 :: Int -> Float -> MyIO [Float] runAll1 = coerce (all1 :: Composing MyCompose [(->) Int, (->) Float, MyIO] [Float]) runAll1' :: Float -> Int -> MyIO [Float] runAll1' = coerce (all1 :: Composing MyCompose [(->) Float, (->) Int, MyIO] [Float]) runAll1'' :: Float -> Int -> IO [Float] runAll1'' = coerce (all1 :: Composed [(->) Float, (->) Int, IO] [Float]) -- instance (Applicative f,Applicative g,WhereIs IO (Compose f g) ~ flag,ComposedApplicativeIO flag (Compose f g)) => ApplicativeIO (Compose f g) where -- liftIO = cliftIO (undefined :: flag) -- | Alternative Stacks to compose -- | A Compose type that fails with Either newtype ComposeE f g a = ComposeE (Compose f g a) deriving (Functor, Applicative ,ApplicativeIOC OnLeft,ApplicativeIOC OnRight ,ApplicativeReaderC OnLeft r,ApplicativeReaderC OnRight r ,ApplicativeErrorC OnLeft r,ApplicativeErrorC OnRight r ) instance (HasApplicativeIO ComposeE IO f g flag) => ApplicativeIO (ComposeE f g) where liftIO = cliftIO (undefined :: flag) instance (HasApplicativeReader ComposeE (->) r f g flag) => ApplicativeReader r (ComposeE f g) where local = local' (undefined :: flag) instance (HasApplicativeError ComposeE Either r f g flag) => ApplicativeError r (ComposeE f g) where throwError = throwError' (undefined :: flag) catchError = catchError' (undefined :: flag)
nkpart/applicatives
src/Control/Applicative/Stacks.hs
bsd-3-clause
3,785
0
10
780
990
553
437
58
1
{-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- The fuel monad ----------------------------------------------------------------------------- module Compiler.Hoopl.Fuel ( Fuel, infiniteFuel, fuelRemaining , withFuel , FuelMonad(..) , FuelMonadT(..) , CheckingFuelMonad , InfiniteFuelMonad , SimpleFuelMonad ) where import Compiler.Hoopl.Checkpoint import Compiler.Hoopl.Unique class Monad m => FuelMonad m where getFuel :: m Fuel setFuel :: Fuel -> m () -- | Find out how much fuel remains after a computation. -- Can be subtracted from initial fuel to get total consumption. fuelRemaining :: FuelMonad m => m Fuel fuelRemaining = getFuel class FuelMonadT fm where runWithFuel :: (Monad m, FuelMonad (fm m)) => Fuel -> fm m a -> m a type Fuel = Int withFuel :: FuelMonad m => Maybe a -> m (Maybe a) withFuel Nothing = return Nothing withFuel (Just a) = do f <- getFuel if f == 0 then return Nothing else setFuel (f-1) >> return (Just a) ---------------------------------------------------------------- newtype CheckingFuelMonad m a = FM { unFM :: Fuel -> m (a, Fuel) } instance Monad m => Monad (CheckingFuelMonad m) where return a = FM (\f -> return (a, f)) fm >>= k = FM (\f -> do { (a, f') <- unFM fm f; unFM (k a) f' }) instance CheckpointMonad m => CheckpointMonad (CheckingFuelMonad m) where type Checkpoint (CheckingFuelMonad m) = (Fuel, Checkpoint m) checkpoint = FM $ \fuel -> do { s <- checkpoint ; return ((fuel, s), fuel) } restart (fuel, s) = FM $ \_ -> do { restart s; return ((), fuel) } instance UniqueMonad m => UniqueMonad (CheckingFuelMonad m) where freshUnique = FM (\f -> do { l <- freshUnique; return (l, f) }) instance Monad m => FuelMonad (CheckingFuelMonad m) where getFuel = FM (\f -> return (f, f)) setFuel f = FM (\_ -> return ((),f)) instance FuelMonadT CheckingFuelMonad where runWithFuel fuel m = do { (a, _) <- unFM m fuel; return a } ---------------------------------------------------------------- newtype InfiniteFuelMonad m a = IFM { unIFM :: m a } instance Monad m => Monad (InfiniteFuelMonad m) where return a = IFM $ return a m >>= k = IFM $ do { a <- unIFM m; unIFM (k a) } instance UniqueMonad m => UniqueMonad (InfiniteFuelMonad m) where freshUnique = IFM $ freshUnique instance Monad m => FuelMonad (InfiniteFuelMonad m) where getFuel = return infiniteFuel setFuel _ = return () instance CheckpointMonad m => CheckpointMonad (InfiniteFuelMonad m) where type Checkpoint (InfiniteFuelMonad m) = Checkpoint m checkpoint = IFM checkpoint restart s = IFM $ restart s instance FuelMonadT InfiniteFuelMonad where runWithFuel _ = unIFM infiniteFuel :: Fuel -- effectively infinite, any, but subtractable infiniteFuel = maxBound type SimpleFuelMonad = CheckingFuelMonad SimpleUniqueMonad {- runWithFuelAndUniques :: Fuel -> [Unique] -> FuelMonad a -> a runWithFuelAndUniques fuel uniques m = a where (a, _, _) = unFM m fuel uniques freshUnique :: FuelMonad Unique freshUnique = FM (\f (l:ls) -> (l, f, ls)) -}
ezyang/hoopl
src/Compiler/Hoopl/Fuel.hs
bsd-3-clause
3,209
0
13
680
992
523
469
59
2
module Web.Zenfolio.PhotoSets ( createPhotoSet, deletePhotoSet, getPopularSets, getRecentSets, loadPhotoSet, movePhotoSet, reorderPhotoSet, searchSetByCategory, searchSetByText, setPhotoSetTitlePhoto, setPhotoSetFeaturedIndex, updatePhotoSet, updatePhotoSetAccess, newUpdater ) where import Web.Zenfolio.Auth (updatePhotoSetAccess) import Web.Zenfolio.Monad (ZM) import Web.Zenfolio.RPC (zfRemote) import Web.Zenfolio.Types (Void, GroupID, GroupIndex, PhotoSet, PhotoSetID, PhotoSetType, PhotoSetUpdater(..), PhotoID, ShiftOrder, SearchID, PhotoSetResult, SortOrder, CategoryID) createPhotoSet :: GroupID -> PhotoSetType -> PhotoSetUpdater -> ZM PhotoSet createPhotoSet = zfRemote "CreatePhotoSet" deletePhotoSet :: PhotoSetID -> ZM Void deletePhotoSet = zfRemote "DeletePhotoSet" getPopularSets :: PhotoSetType -> Int -> Int -> ZM [PhotoSet] getPopularSets = zfRemote "GetPopularSets" getRecentSets :: PhotoSetType -> Int -> Int -> ZM [PhotoSet] getRecentSets = zfRemote "GetRecentSets" loadPhotoSet :: PhotoSetID -> ZM PhotoSet loadPhotoSet = zfRemote "LoadPhotoSet" movePhotoSet :: PhotoSetID -> GroupID -> GroupIndex -> ZM Void movePhotoSet = zfRemote "MovePhotoSet" reorderPhotoSet :: PhotoSetID -> ShiftOrder -> ZM Void reorderPhotoSet = zfRemote "ReorderPhotoSet" searchSetByCategory :: SearchID -> PhotoSetType -> SortOrder -> CategoryID -> Int -> Int -> ZM PhotoSetResult searchSetByCategory = zfRemote "SearchSetByCategory" searchSetByText :: SearchID -> PhotoSetType -> SortOrder -> String -> Int -> Int -> ZM PhotoSetResult searchSetByText = zfRemote "SearchSetByText" setPhotoSetFeaturedIndex :: PhotoSetID -> GroupIndex -> ZM Void setPhotoSetFeaturedIndex = zfRemote "SetPhotoSetFeaturedIndex" setPhotoSetTitlePhoto :: PhotoSetID -> PhotoID -> ZM Void setPhotoSetTitlePhoto = zfRemote "SetPhotoSetTitlePhoto" updatePhotoSet :: PhotoSetID -> PhotoSetUpdater -> ZM PhotoSet updatePhotoSet = zfRemote "UpdatePhotoSet" newUpdater :: PhotoSetUpdater newUpdater = PhotoSetUpdater { psuTitle = Nothing, psuCaption = Nothing, psuKeywords = Nothing, psuCategories = Nothing, psuCustomReference = Nothing }
md5/hs-zenfolio
Web/Zenfolio/PhotoSets.hs
bsd-3-clause
2,370
0
11
489
511
284
227
54
1
module Domains.Trigonometric where class Trigonometric a where sin :: a -> a cos :: a -> a tan :: a -> a asin :: a -> a acos :: a -> a atan :: a -> a instance Trigonometric Double where sin = Prelude.sin cos = Prelude.cos tan = Prelude.tan asin = Prelude.asin acos = Prelude.acos atan = Prelude.atan
pmilne/algebra
src/Domains/Trigonometric.hs
bsd-3-clause
326
0
7
85
119
66
53
15
0
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} -- | PureB - restrict a behavior to the pure subset. PureB does not -- export a `wrap` function, thus developers cannot inject effectful -- behaviors into PureB. Instead, one can only compose or unwrap a -- pure behavior. -- -- The advantage of pure behaviors over just using Haskell functions -- is their ability to model distribution, delay, synchronization, -- and independent update of complex signals. `beval` and `bcross` -- are both accessible for pure behaviors. -- module Sirea.Trans.Pure ( PureB, unwrapPure ) where import Prelude hiding (id,(.)) import Control.Category import Sirea.Behavior import Sirea.Partition -- | PureB is a behavior that has no side-effects and no access to -- external resources. This can be useful to enforce purity on RDP -- subprograms, e.g. to isolate a dynamic behavior. newtype PureB b x y = PB (b x y) liftPure :: b x y -> PureB b x y liftPure = PB -- | Pure behaviors can be unwrapped and treated as impure behaviors unwrapPure :: PureB b x y -> b x y unwrapPure (PB f) = f -- from Sirea.Behavior instance (Category b) => Category (PureB b) where id = liftPure id (PB f) . (PB g) = PB (f . g) instance (BFmap b) => BFmap (PureB b) where bfmap = liftPure . bfmap bconst = liftPure . bconst bstrat = liftPure bstrat btouch = liftPure btouch badjeqf = liftPure badjeqf instance (BProd b) => BProd (PureB b) where bfirst (PB f) = PB (bfirst f) bdup = liftPure bdup b1i = liftPure b1i b1e = liftPure b1e btrivial= liftPure btrivial bswap = liftPure bswap bassoclp= liftPure bassoclp instance (BSum b) => BSum (PureB b) where bleft (PB f) = PB (bleft f) bmirror = liftPure bmirror bmerge = liftPure bmerge b0i = liftPure b0i b0e = liftPure b0e bvacuous= liftPure bvacuous bassocls= liftPure bassocls instance (BDisjoin b) => BDisjoin (PureB b) where bdisjoin= liftPure bdisjoin instance (BZip b) => BZip (PureB b) where bzap = liftPure bzap instance (BSplit b) => BSplit (PureB b) where bsplit = liftPure bsplit instance (BTemporal b) => BTemporal (PureB b) where bdelay = liftPure . bdelay bsynch = liftPure bsynch instance (Behavior b) => Behavior (PureB b) instance (BDynamic b b') => BDynamic b (PureB b') where bevalx bdt = bfirst (bfmap unwrapPure) >>> bevalx (unwrapPure bdt) bexec = bfirst (bfmap unwrapPure) >>> bexec instance (BDynamic b b') => BDynamic (PureB b) (PureB b') where bevalx = liftPure . bevalx bexec = liftPure bexec -- from Sirea.Partition instance (BCross b) => BCross (PureB b) where bcross = liftPure bcross
dmbarbour/Sirea
src/Sirea/Trans/Pure.hs
bsd-3-clause
2,714
0
9
616
769
407
362
55
1
{-# LANGUAGE OverloadedStrings, RankNTypes, GADTs, OverloadedLists, MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, StandaloneDeriving, DeriveDataTypeable #-} {- Column datastore approach -} module Quark.Base.Raw ( ColumnMemoryStore(..), VPair(..), NumericVector(..), GenericVector(..), emptyCMS, getColNames, getColNamesTypes, checkColType, checkColType', extractVec, getIntColumn, getDoubleColumn, getTextColumn, cTableToCMS ) where import Data.Int import Data.Word import qualified Data.Vector.Unboxed as U import qualified Data.Vector as V import Data.Vector.Generic as G import Data.Text import Data.Time import Data.Time.Calendar -- import Text.Read import Data.Text.Read import Data.Binary -- import qualified Data.Map.Strict as Map import qualified Data.HashMap.Strict as Map import Data.Hashable import Control.Monad (mapM_) import Data.Typeable import Data.Data import Data.Dynamic import Data.Vector.Binary -- Binary instances for Vectors!!! -- So, primitive serialization for unboxed types (suitable for not very large files) should be covered automatically -- Actually, Text is Binary so works automagically as well! Supah! :) import Quark.Base.Data import Quark.Base.Column type UColMap a = Map.HashMap Text (U.Vector a) type BColMap a = Map.HashMap Text (V.Vector a) data VPair where MkHM :: (Hashable k, Show k, Show v) => Map.HashMap k v -> VPair MkVec :: (Eq a1, Show a1, Hashable a1, Vector v1 a1, Show (v1 a1) ) => v1 a1 -> VPair MkPair2 :: (Vector v1 a1, Vector v2 a2) => v1 a1 -> v2 a2 -> VPair MkPair3 :: (Vector v1 a1, Vector v2 a2, Vector v3 a3) => v1 a1 -> v2 a2 -> v3 a3 -> VPair MkPair4 :: (Vector v1 a1, Vector v2 a2, Vector v3 a3, Vector v4 a4) => v1 a1 -> v2 a2 -> v3 a3 -> v4 a4 -> VPair data NumericVector where NumericVector :: (Num a, Show a, U.Unbox a) => U.Vector a -> NumericVector data GenericVector where GenericVector :: (Show a, Eq a, Hashable a, Vector v a, Show (v a)) => v a -> GenericVector -- numToGen (NumericVector n) = GenericVector n -- genToNum (GenericVector (U.Vector a) ) = NumericVector (U.Vector a) data Type a where TBool :: Type Bool TInt :: Type Int def :: Type a -> a def TBool = False def TInt = 0 deriving instance Show GenericVector deriving instance Show NumericVector instance Show VPair where show (MkVec v) = show v show (MkHM hm) = show hm -- Ok, trying different approach -- storing all columns in maps by type data ColumnMemoryStore = ColumnMemoryStore { intCols :: UColMap Int64, doubleCols :: UColMap Double, textCols :: BColMap Text, typeSchema :: Map.HashMap Text SupportedTypes -- helper map from column names to their types } deriving (Show) data HColumn = HColumn { intCol :: U.Vector Int64, doubleCol :: U.Vector Double, accessor :: HColumn -> (forall v a. (Vector v a, Num a) => v a) } data SomeVec = forall v a . (Typeable v, Typeable a, Show (v a)) => SomeVec (v a) deriving (Typeable) -- deriving instance Data SomeVec deriving instance Show SomeVec data HVec = HVec { dynVec :: Dynamic, castVec :: Dynamic -> (forall v a. (Vector v a, Num a, Typeable v, Typeable a, Show (v a)) => Maybe (v a)) } {- data ColumnMemoryStoreRaw = forall a. (Num a, Show a, U.Unbox a) => CMSR (Map.HashMap Text (U.Vector a) ) cmsrInsert :: Text -> (forall a. (Num a, Show a, U.Unbox a) => U.Vector a )-> ColumnMemoryStoreRaw -> ColumnMemoryStoreRaw cmsrInsert k v (CMSR m) = CMSR $ Map.insert k v m cmsrLookup :: Text -> ColumnMemoryStoreRaw -> Maybe NumericVector cmsrLookup k (CMSR m) = case Map.lookup k m of Just x -> Just $ NumericVector x Nothing -> Nothing -} -- nGroupCols :: NumericVector -> (forall a. Num a => a -> a -> a) -> NumericVector {- extractVec' :: forall v a. Vector v a => Text -> ColumnMemoryStore -> v a extractVec' nm cms = let t = checkColType' nm cms in case t of PInt -> getUColumn nm (intCols cms) -} -- Ok, this class is what we need to extract any kind of Vectors from our storage by telling the type of what we need class (Vector v a, Eq a, Hashable a) => ExV t v a where extractVec :: Text -> t -> v a instance ExV ColumnMemoryStore U.Vector Int64 where extractVec = getIntColumn instance ExV ColumnMemoryStore U.Vector Double where extractVec = getDoubleColumn instance ExV ColumnMemoryStore V.Vector Text where extractVec = getTextColumn instance ExV (UColMap Int64) U.Vector Int64 where extractVec = getUColumn instance ExV (UColMap Double) U.Vector Double where extractVec = getUColumn instance ExV (BColMap Text) V.Vector Text where extractVec = getBColumn emptyCMS = ColumnMemoryStore {intCols = Map.empty, doubleCols = Map.empty, textCols = Map.empty, typeSchema = Map.empty} getColNames :: ColumnMemoryStore -> [Text] getColNames cms = Map.keys (typeSchema cms) getColNamesTypes :: ColumnMemoryStore -> [(Text, SupportedTypes)] getColNamesTypes cms = Map.toList (typeSchema cms) -- checks type of the column and returns Maybe SupportedType - useful to check if the column is in the store checkColType :: Text -> ColumnMemoryStore -> Maybe SupportedTypes checkColType nm cms = Map.lookup nm (typeSchema cms) -- use this if you are sure column is in the store, it's incomplete (returns nothing for Nothing) so - DANGEROUS!!! checkColType' :: Text -> ColumnMemoryStore -> SupportedTypes checkColType' nm cms = let c = checkColType nm cms in case c of Just t -> t -- return any unboxed columns - specific definitions below getUColumn :: U.Unbox a => Text -> UColMap a -> U.Vector a getUColumn nm cms = let mclm = Map.lookup nm cms in case mclm of Just v -> v Nothing -> U.fromList [] getIntColumn nm cms = getUColumn nm (intCols cms) getDoubleColumn nm cms = getUColumn nm (doubleCols cms) -- return any boxed column - specific definitions below getBColumn :: Text -> BColMap a -> V.Vector a getBColumn nm cms = let mclm = Map.lookup nm cms in case mclm of Just v -> v Nothing -> V.fromList [] getTextColumn nm cms = getBColumn nm (textCols cms) -- compatibility conversion function cTableToCMS :: CTable -> ColumnMemoryStore cTableToCMS ct = Prelude.foldl proc emptyCMS (Map.toList ct) where proc acc (k,v) = case v of (CDouble c) -> acc {doubleCols = Map.insert k c (doubleCols acc), typeSchema = Map.insert k PDouble (typeSchema acc)} (CInt c) -> acc { intCols = Map.insert k c (intCols acc), typeSchema = Map.insert k PInt (typeSchema acc)} (CText c) -> acc {textCols = Map.insert k c (textCols acc), typeSchema = Map.insert k PText (typeSchema acc)}
jhoxray/muon
src/Quark/Base/Raw.hs
bsd-3-clause
7,069
0
15
1,716
1,810
972
838
-1
-1
{-# LANGUAGE LambdaCase, RecordWildCards, TemplateHaskell, OverloadedStrings #-} module AbstractInterpretation.Sharing.CodeGen where import Control.Monad.State import Data.Set (Set) import Data.Map (Map) import Data.Vector (Vector) import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Vector as Vec import qualified Data.Set.Extra as Set import Data.Maybe import Data.Foldable import Data.Functor.Foldable import Lens.Micro.Platform import Grin.Syntax import Grin.TypeEnvDefs import AbstractInterpretation.Util (converge) import AbstractInterpretation.IR (Instruction(..), Reg, AbstractProgram) import qualified AbstractInterpretation.IR as IR import AbstractInterpretation.HeapPointsTo.CodeGenBase import qualified AbstractInterpretation.HeapPointsTo.CodeGen as HPT {- [x] Calc non-linear variables, optionally ignoring updates. [x] Assumption: all the non-linear variables have registers already. [x] For all non-linear variables set the locations as shared. [x] For all the shared locations, look up the pointed locations and set to shared them. [x] Create a register to maintain sharing information [x] Add Sharing register as parameter to HPT [x] Add Sharing register as parameter to Sharing [x] Remove _shared field from Reduce [-] Add 'In' to the Condition [x] Remove GetShared from IR [x] Remove SetShared from IR [x] CodeGenMain: depend on optimisation phase, before InLineAfter inline [x] CodeGenMain: add an extra parameter [x] Pipeline: Set a variable if the codegen is after or before [-] Add mode as parameter for the eval'' and typecheck [x] Remove Mode for calcNonLinearVars -} data SharingMapping = SharingMapping { _shRegName :: Reg , _hptMapping :: HPTMapping } deriving (Show) concat <$> mapM makeLenses [''SharingMapping] -- | Calc non linear variables, ignores variables that are used in update locations -- This is an important difference, if a variable would become non-linear due to -- being subject to an update, that would make the sharing analysis incorrect. -- One possible improvement is to count the updates in a different set and make a variable -- linear if it is subject to an update more than once. But that could not happen, thus the only -- introdcution of new updates comes from inlining eval. calcNonLinearNonUpdateLocVariables :: Exp -> Set Name calcNonLinearNonUpdateLocVariables exp = Set.fromList $ Map.keys $ Map.filter (>1) $ cata collect exp where union = Map.unionsWith (+) collect = \case ECaseF val alts -> union (seen val : alts) SStoreF val -> seen val SFetchIF var _ -> seen (Var var) SUpdateF var val -> seen val SReturnF val -> seen val SAppF _ ps -> union $ fmap seen ps rest -> Data.Foldable.foldr (Map.unionWith (+)) mempty rest seen = \case Var v -> Map.singleton v 1 ConstTagNode _ ps -> union $ fmap seen ps VarTagNode v ps -> union $ fmap seen (Var v : ps) _ -> Map.empty calcSharedLocationsPure :: TypeEnv -> Exp -> Set Loc calcSharedLocationsPure TypeEnv{..} e = converge (==) (Set.concatMap fetchLocs) origShVarLocs where nonLinearVars = calcNonLinearNonUpdateLocVariables e shVarTypes = Set.mapMaybe (`Map.lookup` _variable) $ nonLinearVars origShVarLocs = onlyLocations . onlySimpleTys $ shVarTypes onlySimpleTys :: Set Type -> Set SimpleType onlySimpleTys tys = Set.fromList [ sty | T_SimpleType sty <- Set.toList tys ] onlyLocations :: Set SimpleType -> Set Loc onlyLocations stys = Set.fromList $ concat [ ls | T_Location ls <- Set.toList stys ] fetchLocs :: Loc -> Set Loc fetchLocs l = onlyLocations . fieldsFromNodeSet . fromMaybe (error msg) . (Vec.!?) _location $ l where msg = "Sharing: Invalid heap index: " ++ show l fieldsFromNodeSet :: NodeSet -> Set SimpleType fieldsFromNodeSet = Set.fromList . concatMap Vec.toList . Map.elems sharingCodeGen :: Reg -> Exp -> CG () sharingCodeGen shReg e = do forM_ nonLinearVars $ \name -> do -- For all non-linear variables set the locations as shared. nonLinearVarReg <- getReg name -- this will copy node field info as well, but we will only use "simpleType" info emit $ copyStructureWithPtrInfo nonLinearVarReg shReg mergedFields <- newReg pointsToNodeReg <- newReg emit IR.Fetch { addressReg = shReg , dstReg = pointsToNodeReg } emit IR.Project { srcReg = pointsToNodeReg , srcSelector = IR.AllFields , dstReg = mergedFields } emit $ copyStructureWithPtrInfo mergedFields shReg where nonLinearVars = calcNonLinearNonUpdateLocVariables e codeGenM :: Exp -> CG (AbstractProgram, SharingMapping) codeGenM e = do HPT.codeGenM e shReg <- newReg sharingCodeGen shReg e (prg, hptMapping) <- HPT.mkAbstractProgramM let mapping = SharingMapping { _shRegName = shReg , _hptMapping = hptMapping } pure (prg, mapping) codeGen :: Program -> (AbstractProgram, SharingMapping) codeGen prg@(Program{}) = evalState (codeGenM prg) emptyCGState codeGen _ = error "Program expected"
andorp/grin
grin/src/AbstractInterpretation/Sharing/CodeGen.hs
bsd-3-clause
5,082
0
14
961
1,095
577
518
85
10
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PolyKinds #-} module Control.LnMonad.List.Reader where import Data.LnFunctor import Data.LnFunctor.Apply import Data.LnFunctor.Bind import Control.LnApplicative import Type.Families import Data.Proxy newtype LReader (i :: [*]) (j :: [*]) (a :: *) = LReader { unLReader :: List i -> a } instance IxFunctor LReader where imap f (LReader mi) = LReader $ f . mi instance LnFunctor LReader where type L LReader i k = IsSub i k type R LReader j l = () weaken (LReader (m :: List i -> a)) = LReader $ \lk -> case subProof (Proxy :: Proxy i) lk of SubProof li -> m li strengthen (LReader m) = LReader m lmap f = imap f . stretch instance LnInitial LReader where type Init LReader i j = () instance LnApply LReader where type Link LReader i j k l h m = (IsSub i h, IsSub k h) lap (LReader (fi :: List i -> a -> b)) (LReader (ak :: List k -> a)) = LReader $ \lh -> case (subProof pi lh,subProof pk lh) of (SubProof li,SubProof lk) -> fi li $ ak lk where pi = Proxy :: Proxy i pk = Proxy :: Proxy k instance LnApplicative LReader where lpure = LReader . const instance LnBind LReader where lbind (LReader (ai :: List i -> a)) (fk :: a -> LReader k l b) = LReader $ \lh -> case (subProof pi lh,subProof pk lh) of (SubProof li,SubProof lk) -> unLReader (fk $ ai li) lk where pi = Proxy :: Proxy i pk = Proxy :: Proxy k ask :: LReader i i (List i) ask = LReader $ \li -> li local :: (List i -> List k) -> LReader k l a -> LReader i l a local f (LReader ak) = LReader $ ak . f reader :: (List i -> a) -> LReader i j a reader = LReader
kylcarte/lnfunctors
src/Control/LnMonad/List/Reader.hs
bsd-3-clause
1,963
0
14
457
759
401
358
57
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module BSP.Tests.UART.Types where import Ivory.Language [ivory| string struct UARTBuffer 128 |]
GaloisInc/ivory-tower-stm32
ivory-bsp-tests/BSP/Tests/UART/Types.hs
bsd-3-clause
259
0
4
35
25
19
6
8
0
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Series (largestProduct) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "largestProduct" $ do it "finds the largest product if span equals length" $ largestProduct 2 "29" `shouldBe` Just 18 it "can find the largest product of 2 with numbers in order" $ largestProduct 2 "0123456789" `shouldBe` Just 72 it "can find the largest product of 2" $ largestProduct 2 "576802143" `shouldBe` Just 48 it "can find the largest product of 3 with numbers in order" $ largestProduct 3 "0123456789" `shouldBe` Just 504 it "can find the largest product of 3" $ largestProduct 3 "1027839564" `shouldBe` Just 270 it "can find the largest product of 5 with numbers in order" $ largestProduct 5 "0123456789" `shouldBe` Just 15120 it "can get the largest product of a big number" $ largestProduct 6 "73167176531330624919225119674426574742355349194934" `shouldBe` Just 23520 it "reports zero if the only digits are zero" $ largestProduct 2 "0000" `shouldBe` Just 0 it "reports zero if all spans include zero" $ largestProduct 3 "99099" `shouldBe` Just 0 it "rejects span longer than string length" $ largestProduct 4 "123" `shouldBe` Nothing it "reports 1 for empty string and empty product (0 span)" $ largestProduct 0 "" `shouldBe` Just 1 it "reports 1 for nonempty string and empty product (0 span)" $ largestProduct 0 "123" `shouldBe` Just 1 it "rejects empty string and nonzero span" $ largestProduct 1 "" `shouldBe` Nothing it "rejects invalid character in digits" $ largestProduct 2 "1234a5" `shouldBe` Nothing it "rejects negative span" $ largestProduct (-1) "12345" `shouldBe` Nothing
c19/Exercism-Haskell
largest-series-product/test/Tests.hs
mit
2,154
0
12
630
444
217
227
53
1
{- Copyright © 2014 Intel Corporation Copyright © 2016-2017 Auke Booij Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of the copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The copyright holders make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -} {-# LANGUAGE CPP #-} {-# LANGUAGE ForeignFunctionInterface #-} module Graphics.Sudbury.Socket.Wayland (sendToWayland, recvFromWayland) where import qualified Control.Concurrent as CC import qualified Data.ByteString as BS import Foreign import Foreign.C.Types import System.Posix.Types (Fd(..)) foreign import ccall unsafe "wayland-msg-handling.h sendmsg_wayland" c_sendmsg_wayland :: CInt -- fd -> Ptr CChar -- buf -> CInt -- bufsize -> Ptr CInt -- fds -> CInt -- n_fds -> IO CInt -- bytes sent foreign import ccall unsafe "wayland-msg-handling.h recvmsg_wayland" c_recvmsg_wayland :: CInt -- fd -> Ptr CChar -- buf -> CInt -- bufsize -> Ptr CInt -- fds -> CInt -- fdbufsize -> Ptr CInt -- n_fds -> IO CInt -- bytes received -- TODO limit number of `Fd`s to be sent to 28. sendToWayland :: Fd -> BS.ByteString -> [Fd] -> IO CInt sendToWayland socket bs fds = do CC.threadWaitWrite $ fromIntegral socket BS.useAsCStringLen bs sendData where c_fds = map fromIntegral fds sendData (bytePtr, byteLen) = withArrayLen c_fds $ \fdLen fdArray -> do let c_byteLen = fromIntegral byteLen let c_fdLen = fromIntegral fdLen len <- c_sendmsg_wayland (fromIntegral socket) bytePtr c_byteLen fdArray c_fdLen if len < 0 then ioError $ userError "sendmsg failed" else return len recvFromWayland :: Fd -> IO (BS.ByteString, [Fd]) recvFromWayland socket = allocaArray 4096 $ \cbuf -> do CC.threadWaitRead $ fromIntegral socket alloca $ \nFds_ptr -> allocaArray (4*28) $ \fdArray -> do len <- c_recvmsg_wayland (fromIntegral socket) cbuf 4096 fdArray (4*28) nFds_ptr if len < 0 then ioError $ userError "recvmsg failed" else do bs <- BS.packCStringLen (cbuf, fromIntegral len) nFds <- peek nFds_ptr fds <- peekArray (fromIntegral nFds) fdArray return (bs, map fromIntegral fds)
abooij/sudbury
Graphics/Sudbury/Socket/Wayland.hs
mit
3,350
0
21
865
545
284
261
48
2
{- | Module : $Id: Haskell.hs 13959 2010-08-31 22:15:26Z cprodescu $ Copyright : (c) Christian Maeder and Uni Bremen 2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : mostly portable This folder contains the Haskell logic based on programatica <http://www.cse.ogi.edu/PacSoft/projects/programatica> from Thomas Hallgren * "Haskell.ATC_Haskell" generated ATC instances * "Haskell.BaseATC" handwritten ATC instances for "Haskell.ATC_Haskell" * "Haskell.HatAna" calling the type checker for Haskell * "Haskell.Haskell2DG" unfinished translation to development graphs * "Haskell.HatParser" parsing Haskell as basic specs * "Haskell.Logic_Haskell" the logic instance * "Haskell.PreludeString" the programatica prelude as string * "Haskell.TiATC" remaining ATC instances for "Haskell.Logic_Haskell" * "Haskell.TranslateId" translating CASL ids to Haskell ids * "Haskell.Wrapper" extracting Haskell code from structured specs -} module Haskell where
nevrenato/HetsAlloy
Haskell.hs
gpl-2.0
1,101
0
2
207
5
4
1
1
0
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Pane.PackageEditor -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : Juergen Nicklisch-Franken <[email protected]> -- Stability : provisional -- Portability : portable -- -- | Module for editing of cabal packages and build infos -- ----------------------------------------------------------------------------------- module IDE.Pane.PackageEditor ( packageNew' , packageClone , packageEdit , packageEditText , choosePackageDir , choosePackageFile , hasConfigs , standardSetup ) where import Graphics.UI.Gtk import Distribution.Package import Distribution.PackageDescription import Distribution.Verbosity import System.FilePath import Data.Maybe import System.Directory import IDE.Core.State import IDE.Utils.FileUtils import Graphics.UI.Editor.MakeEditor import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.PackageDescription.Configuration (flattenPackageDescription) import Distribution.ModuleName(ModuleName) import Data.Typeable (Typeable(..)) import Graphics.UI.Editor.Composite (versionEditor, versionRangeEditor, dependenciesEditor, textsEditor, filesEditor, tupel3Editor, eitherOrEditor, maybeEditor, pairEditor, ColumnDescr(..), multisetEditor) import Distribution.Text (simpleParse, display) import Graphics.UI.Editor.Parameters (paraInnerPadding, paraInnerAlignment, paraOuterPadding, paraOuterAlignment, Parameter(..), paraPack, Direction(..), paraDirection, paraMinSize, paraShadow, paraSynopsis, (<<<-), emptyParams, paraName, getParameterPrim) import Graphics.UI.Editor.Simple (stringEditor, comboEntryEditor, staticListMultiEditor, intEditor, boolEditor, fileEditor, comboSelectionEditor, multilineStringEditor, textEditor) import Graphics.UI.Editor.Basics (Notifier, Editor(..), GUIEventSelector(..), GUIEvent(..)) import Distribution.Compiler (CompilerFlavor(..)) import Distribution.Simple (knownExtensions) import Distribution.Simple (Extension(..), VersionRange, anyVersion) import Default (Default(..)) import IDE.Utils.GUIUtils import IDE.Pane.SourceBuffer (fileOpenThis) import Control.Event (EventSource(..)) import qualified Graphics.UI.Gtk.Gdk.Events as GTK (Event(..)) import Data.List (isPrefixOf, sort, nub, sortBy) import Data.Text (Text) import Control.Monad.Trans.Reader (ask) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Class (lift) import Control.Monad (when) import Distribution.PackageDescription.PrettyPrint (writeGenericPackageDescription) import Distribution.Version (Version(..), orLaterVersion) import Control.Applicative ((<*>), (<$>)) import IDE.Utils.Tool (ToolOutput(..)) import System.Exit (ExitCode(..)) import qualified Data.Conduit.List as CL (fold) import qualified Data.Conduit as C (Sink, ZipSink(..), getZipSink) import IDE.Utils.ExternalTool (runExternalTool') import qualified System.IO.Strict as S (readFile) import Data.Char (toLower) import qualified Data.Text as T (replace, span, splitAt, isPrefixOf, length, toLower, lines, unlines, pack, unpack, null) import Data.Monoid ((<>)) import qualified Data.Text.IO as T (writeFile, readFile) import qualified Text.Printf as S (printf) import Text.Printf (PrintfType) import MyMissing (forceJust) import Language.Haskell.Extension (Language(..)) import Distribution.License (License(..)) printf :: PrintfType r => Text -> r printf = S.printf . T.unpack -- | Get the last item sinkLast = CL.fold (\_ a -> Just a) Nothing -------------------------------------------------------------------------- -- Handling of Generic Package Descriptions toGenericPackageDescription :: PackageDescription -> GenericPackageDescription toGenericPackageDescription pd = GenericPackageDescription { packageDescription = pd{ library = Nothing, executables = [], testSuites = [], benchmarks = [], buildDepends = []}, genPackageFlags = [], condLibrary = case library pd of Nothing -> Nothing Just lib -> Just (buildCondTreeLibrary lib), condExecutables = map buildCondTreeExe (executables pd), condTestSuites = map buildCondTreeTest (testSuites pd), condBenchmarks = map buildCondTreeBenchmark (benchmarks pd)} where buildCondTreeLibrary lib = CondNode { condTreeData = lib { libBuildInfo = (libBuildInfo lib) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []} buildCondTreeExe exe = (exeName exe, CondNode { condTreeData = exe { buildInfo = (buildInfo exe) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) buildCondTreeTest test = (testName test, CondNode { condTreeData = test { testBuildInfo = (testBuildInfo test) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) buildCondTreeBenchmark bm = (benchmarkName bm, CondNode { condTreeData = bm { benchmarkBuildInfo = (benchmarkBuildInfo bm) { targetBuildDepends = buildDepends pd } }, condTreeConstraints = buildDepends pd, condTreeComponents = []}) -- --------------------------------------------------------------------- -- The exported stuff goes here -- choosePackageDir :: Window -> Maybe FilePath -> IO (Maybe FilePath) choosePackageDir window mbDir = chooseDir window (__ "Select root folder for package") mbDir choosePackageFile :: Window -> Maybe FilePath -> IO (Maybe FilePath) choosePackageFile window mbDir = chooseFile window (__ "Select cabal package file (.cabal)") mbDir packageEdit :: PackageAction packageEdit = do idePackage <- ask let dirName = dropFileName (ipdCabalFile idePackage) modules <- liftIO $ allModules dirName package <- liftIO $ readPackageDescription normal (ipdCabalFile idePackage) if hasConfigs package then do liftIDE $ ideMessage High (__ "Cabal file with configurations can't be edited with the current version of the editor") liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () else do let flat = flattenPackageDescription package if hasUnknownTestTypes flat || hasUnknownBenchmarkTypes flat then do liftIDE $ ideMessage High (__ "Cabal file with tests or benchmarks of this type can't be edited with the current version of the editor") liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () else do liftIDE $ editPackage flat dirName modules (\ _ -> return ()) return () packageEditText :: PackageAction packageEditText = do idePackage <- ask liftIDE $ fileOpenThis $ ipdCabalFile idePackage return () hasConfigs :: GenericPackageDescription -> Bool hasConfigs gpd = let libConds = case condLibrary gpd of Nothing -> False Just condTree -> not (null (condTreeComponents condTree)) exeConds = foldr (\ (_,condTree) hasConfigs -> if hasConfigs then True else not (null (condTreeComponents condTree))) False (condExecutables gpd) testConds = foldr (\ (_,condTree) hasConfigs -> if hasConfigs then True else not (null (condTreeComponents condTree))) False (condTestSuites gpd) in libConds || exeConds || testConds hasUnknownTestTypes :: PackageDescription -> Bool hasUnknownTestTypes pd = not . null . filter unknown $ testSuites pd where unknown (TestSuite _ (TestSuiteExeV10 _ _) _ _) = False unknown _ = True hasUnknownBenchmarkTypes :: PackageDescription -> Bool hasUnknownBenchmarkTypes pd = not . null . filter unknown $ benchmarks pd where unknown (Benchmark _ (BenchmarkExeV10 _ _) _ _) = False unknown _ = True data NewPackage = NewPackage { newPackageName :: Text, newPackageParentDir :: FilePath, templatePackage :: Maybe Text} packageFields :: FilePath -> FieldDescription NewPackage packageFields workspaceDir = VFD emptyParams [ mkField (paraName <<<- ParaName ((__ "New package name")) $ emptyParams) newPackageName (\ a b -> b{newPackageName = a}) (textEditor (const True) True), mkField (paraName <<<- ParaName ((__ "Parent directory")) $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) (\a -> newPackageParentDir a) (\ a b -> b{newPackageParentDir = a}) (fileEditor (Just workspaceDir) FileChooserActionSelectFolder "Select"), mkField (paraName <<<- ParaName ((__ "Copy existing package")) $ emptyParams) templatePackage (\ a b -> b{templatePackage = a}) (maybeEditor (comboEntryEditor examplePackages, emptyParams) True "")] examplePackages = [ "hello" , "gtk2hs-hello" , "ghcjs-dom-hello" , "jsaddle-hello"] newPackageDialog :: Window -> FilePath -> IO (Maybe NewPackage) newPackageDialog parent workspaceDir = do dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := (__ "Create New Package") ] #ifdef MIN_VERSION_gtk3 upper <- dialogGetContentArea dia #else upper <- dialogGetUpper dia #endif lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (packageFields workspaceDir) (NewPackage "" workspaceDir Nothing) okButton <- dialogAddButton dia (__"Create Package") ResponseOk dialogAddButton dia (__"Cancel") ResponseCancel boxPackStart (castToBox upper) widget PackGrow 7 set okButton [widgetCanDefault := True] widgetGrabDefault okButton widgetShowAll dia resp <- dialogRun dia value <- ext (NewPackage "" workspaceDir Nothing) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing packageNew' :: FilePath -> C.Sink ToolOutput IDEM () -> (Bool -> FilePath -> IDEAction) -> IDEAction packageNew' workspaceDir log activateAction = do windows <- getWindows mbNewPackage <- liftIO $ newPackageDialog (head windows) workspaceDir case mbNewPackage of Nothing -> return () Just NewPackage{..} | templatePackage == Nothing -> do let dirName = newPackageParentDir </> T.unpack newPackageName mbCabalFile <- liftIO $ cabalFileName dirName window <- getMainWindow case mbCabalFile of Just cfn -> do add <- liftIO $ do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (T.pack $ printf (__ "There is already file %s in this directory. Would you like to add this package to the workspace?") (takeFileName cfn)) dialogAddButton md (__ "_Add Package") (ResponseUser 1) dialogSetDefaultResponse md (ResponseUser 1) set md [ windowWindowPosition := WinPosCenterOnParent ] rid <- dialogRun md widgetDestroy md return $ rid == ResponseUser 1 when add $ activateAction False cfn Nothing -> do liftIO $ createDirectoryIfMissing True dirName isEmptyDir <- liftIO $ isEmptyDirectory dirName make <- if isEmptyDir then return True else liftIO $ do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (T.pack $ printf (__ "The path you have choosen %s is not an empty directory. Are you sure you want to make a new package here?") dirName) dialogAddButton md (__ "_Make Package Here") (ResponseUser 1) dialogSetDefaultResponse md (ResponseUser 1) set md [ windowWindowPosition := WinPosCenterOnParent ] rid <- dialogRun md widgetDestroy md return $ rid == ResponseUser 1 when make $ do modules <- liftIO $ allModules dirName let Just initialVersion = simpleParse "0.0.1" editPackage emptyPackageDescription { package = PackageIdentifier (PackageName $ T.unpack newPackageName) initialVersion , buildType = Just Simple , specVersionRaw = Right (orLaterVersion (Version [1,12] [])) , license = AllRightsReserved , executables = [emptyExecutable { exeName = T.unpack newPackageName , modulePath = "Main.hs" , buildInfo = emptyBuildInfo { hsSourceDirs = ["src"] , targetBuildDepends = [Dependency (PackageName "base") anyVersion] , defaultLanguage = Just Haskell2010}}] , testSuites = [emptyTestSuite { testName = "test-" ++ T.unpack newPackageName , testInterface = (TestSuiteExeV10 (Version [1,0] []) "Main.hs") , testBuildInfo = emptyBuildInfo { hsSourceDirs = ["test"] , targetBuildDepends = [ Dependency (PackageName "base") anyVersion , Dependency (PackageName "QuickCheck") anyVersion , Dependency (PackageName "doctest") anyVersion] , defaultLanguage = Just Haskell2010}}] , benchmarks = [] } dirName modules (activateAction True) return () Just NewPackage{..} -> cabalUnpack newPackageParentDir (fromJust templatePackage) False (Just newPackageName) log (activateAction False) standardSetup :: Text standardSetup = "#!/usr/bin/runhaskell \n" <> "> module Main where\n" <> "> import Distribution.Simple\n" <> "> main :: IO ()\n" <> "> main = defaultMain\n\n" data ClonePackageSourceRepo = ClonePackageSourceRepo { packageToClone :: Text, cloneParentDir :: FilePath} cloneFields :: [PackageId] -> FilePath -> FieldDescription ClonePackageSourceRepo cloneFields packages workspaceDir = VFD emptyParams [ mkField (paraName <<<- ParaName ((__ "Existing package to clone source repository")) $ emptyParams) packageToClone (\ a b -> b{packageToClone = a}) (comboEntryEditor ((sort . nub) (map (T.pack . display . pkgName) packages))), mkField (paraName <<<- ParaName ((__ "Parent directory")) $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) (\a -> cloneParentDir a) (\ a b -> b{cloneParentDir = a}) (fileEditor (Just workspaceDir) FileChooserActionSelectFolder "Select")] clonePackageSourceDialog :: Window -> FilePath -> IO (Maybe ClonePackageSourceRepo) clonePackageSourceDialog parent workspaceDir = do packages <- getInstalledPackageIds dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := (__ "Clone Package") ] #ifdef MIN_VERSION_gtk3 upper <- dialogGetContentArea dia #else upper <- dialogGetUpper dia #endif lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (cloneFields packages workspaceDir) (ClonePackageSourceRepo "" workspaceDir) okButton <- dialogAddButton dia (__"Clone Package") ResponseOk dialogAddButton dia (__"Cancel") ResponseCancel boxPackStart (castToBox upper) widget PackGrow 7 set okButton [widgetCanDefault := True] widgetGrabDefault okButton widgetShowAll dia resp <- dialogRun dia value <- ext (ClonePackageSourceRepo "" workspaceDir) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing packageClone :: FilePath -> C.Sink ToolOutput IDEM () -> (FilePath -> IDEAction) -> IDEAction packageClone workspaceDir log activateAction = do windows <- getWindows mbResult <- liftIO $ clonePackageSourceDialog (head windows) workspaceDir case mbResult of Nothing -> return () Just ClonePackageSourceRepo{..} -> cabalUnpack cloneParentDir packageToClone True Nothing log activateAction cabalUnpack :: FilePath -> Text -> Bool -> Maybe Text -> C.Sink ToolOutput IDEM () -> (FilePath -> IDEAction) -> IDEAction cabalUnpack parentDir packageToUnpack sourceRepo mbNewName log activateAction = do let tempDir = parentDir </> (T.unpack packageToUnpack ++ ".leksah.temp") liftIO $ do oldDirExists <- doesDirectoryExist tempDir when oldDirExists $ removeDirectoryRecursive tempDir createDirectory tempDir runExternalTool' (__ "Unpacking") "cabal" (["unpack"] ++ (if sourceRepo then ["--source-repository"] else []) ++ ["--destdir=" <> T.pack tempDir, packageToUnpack]) tempDir $ do mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> C.ZipSink log case mbLastOutput of Just (ToolExit ExitSuccess) -> do contents <- liftIO $ getDirectoryContents tempDir case filter (not . isPrefixOf ".") contents of [] -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "Nothing found in " <> T.pack tempDir <> " after doing a cabal unpack." [repoName] -> do let destDir = parentDir </> (fromMaybe repoName $ T.unpack <$> mbNewName) exists <- liftIO $ (||) <$> doesDirectoryExist destDir <*> doesFileExist destDir if exists then lift $ ideMessage High $ T.pack destDir <> " already exists" else do liftIO $ renameDirectory (tempDir </> repoName) destDir mbCabalFile <- liftIO $ cabalFileName destDir window <- lift $ getMainWindow lift $ case (mbCabalFile, mbNewName) of (Just cfn, Just newName) -> do let newCfn = takeDirectory cfn </> (T.unpack newName) ++ ".cabal" when (cfn /= newCfn) . liftIO $ do s <- T.readFile cfn T.writeFile newCfn $ renameCabalFile (T.pack $ takeBaseName cfn) newName s removeFile cfn activateAction newCfn (Just cfn, _) -> activateAction cfn _ -> ideMessage High $ "Unpacked source reposity to " <> T.pack destDir <> " but it does not contain a .cabal file in the root directory." liftIO $ removeDirectoryRecursive tempDir _ -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "More than one subdirectory found in " <> T.pack tempDir <> " after doing a cabal unpack." _ -> do liftIO $ removeDirectoryRecursive tempDir lift $ ideMessage High $ "Failed to unpack source reposity to " <> T.pack tempDir renameCabalFile :: Text -> Text -> Text -> Text renameCabalFile oldName newName = T.unlines . map renameLine . T.lines where prefixes = ["name:", "executable ", "test-suite "] prefixesWithLength :: [(Text, Int)] prefixesWithLength = zip prefixes $ map T.length prefixes renameLine :: Text -> Text renameLine line = case catMaybes $ map (rename (line, T.toLower line)) prefixesWithLength of l:_ -> l [] -> line rename :: (Text, Text) -> (Text, Int) -> Maybe Text rename (line, lcLine) (lcPrefix, pLen) | lcPrefix `T.isPrefixOf` lcLine = let (prefix, rest) = T.splitAt pLen line (spaces, value) = T.span (==' ') rest in Just $ prefix <> spaces <> T.replace oldName newName value rename _ _ = Nothing -- --------------------------------------------------------------------- -- | We do some twist for handling build infos seperately to edit them in one editor together -- with the other stuff. This type show what we really edit here -- data PackageDescriptionEd = PDE { pd :: PackageDescription, exes :: [Executable'], tests :: [Test'], bms :: [Benchmark'], mbLib :: Maybe Library', bis :: [BuildInfo]} deriving Eq comparePDE a b = do when (pd a /= pd b) $ putStrLn "pd" when (exes a /= exes b) $ putStrLn "exes" when (tests a /= tests b) $ putStrLn "tests" when (mbLib a /= mbLib b) $ putStrLn "mbLib" when (bis a /= bis b) $ putStrLn "bis" fromEditor :: PackageDescriptionEd -> PackageDescription fromEditor (PDE pd exes' tests' benchmarks' mbLib' buildInfos) = let exes = map (\ (Executable' s fb bii) -> if bii + 1 > length buildInfos then Executable (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) else Executable (T.unpack s) fb (buildInfos !! bii)) exes' tests = map (\ (Test' s fb bii) -> if bii + 1 > length buildInfos then TestSuite (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) False else TestSuite (T.unpack s) fb (buildInfos !! bii) False) tests' bms = map (\ (Benchmark' s fb bii) -> if bii + 1 > length buildInfos then Benchmark (T.unpack s) fb (buildInfos !! (length buildInfos - 1)) False else Benchmark (T.unpack s) fb (buildInfos !! bii) False) benchmarks' mbLib = case mbLib' of Nothing -> Nothing #if MIN_VERSION_Cabal(1,22,0) Just (Library' mn rmn rs es b bii) -> if bii + 1 > length buildInfos then Just (Library mn rmn rs es b (buildInfos !! (length buildInfos - 1))) else Just (Library mn rmn rs es b (buildInfos !! bii)) #else Just (Library' mn b bii) -> if bii + 1 > length buildInfos then Just (Library mn b (buildInfos !! (length buildInfos - 1))) else Just (Library mn b (buildInfos !! bii)) #endif in pd { library = mbLib , executables = exes , testSuites = tests , benchmarks = bms } toEditor :: PackageDescription -> PackageDescriptionEd toEditor pd = let (exes,exeBis) = unzip $ map (\((Executable s fb bi), i) -> ((Executable' (T.pack s) fb i), bi)) (zip (executables pd) [0..]) (tests,testBis) = unzip $ map (\((TestSuite s fb bi _), i) -> ((Test' (T.pack s) fb i), bi)) (zip (testSuites pd) [length exeBis..]) (bms,benchmarkBis) = unzip $ map (\((Benchmark s fb bi _), i) -> ((Benchmark' (T.pack s) fb i), bi)) (zip (benchmarks pd) [length testBis..]) bis = exeBis ++ testBis ++ benchmarkBis (mbLib,bis2) = case library pd of Nothing -> (Nothing,bis) #if MIN_VERSION_Cabal(1,22,0) Just (Library mn rmn rs es b bi) -> (Just (Library' (sort mn) rmn rs es b (length bis)), bis ++ [bi]) #else Just (Library mn b bi) -> (Just (Library' (sort mn) b (length bis)), bis ++ [bi]) #endif bis3 = if null bis2 then [emptyBuildInfo] else bis2 in PDE (pd {library = Nothing , executables = []}) exes tests bms mbLib bis3 -- --------------------------------------------------------------------- -- The pane stuff -- data PackagePane = PackagePane { packageBox :: VBox, packageNotifer :: Notifier } deriving Typeable data PackageState = PackageState deriving (Read, Show, Typeable) instance Pane PackagePane IDEM where primPaneName _ = (__ "Package") getAddedIndex _ = 0 getTopWidget = castToWidget . packageBox paneId b = "*Package" instance RecoverablePane PackagePane PackageState IDEM where saveState p = return Nothing recoverState pp st = return Nothing buildPane panePath notebook builder = return Nothing builder pp nb w = return (Nothing,[]) editPackage :: PackageDescription -> FilePath -> [ModuleName] -> (FilePath -> IDEAction) -> IDEAction editPackage packageD packagePath modules afterSaveAction = do mbPane :: Maybe PackagePane <- getPane case mbPane of Nothing -> do pp <- getBestPathForId "*Package" nb <- getNotebook pp packageInfos <- liftIO $ getInstalledPackageIds let packageEd = toEditor packageD initPackage packagePath packageEd (packageDD packageInfos (takeDirectory packagePath) modules (length (bis packageEd)) (concatMap (buildInfoD (Just (takeDirectory packagePath)) modules) [0..length (bis packageEd) - 1])) pp nb modules afterSaveAction packageEd Just p -> liftIO $ bringPaneToFront p initPackage :: FilePath -> PackageDescriptionEd -> FieldDescription PackageDescriptionEd -> PanePath -> Notebook -> [ModuleName] -> (FilePath -> IDEAction) -> PackageDescriptionEd -> IDEM () initPackage packageDir packageD packageDescr panePath nb modules afterSaveAction origPackageD = do let fields = flattenFieldDescription packageDescr let initialPackagePath = packageDir </> (display . pkgName . package . pd) packageD ++ ".cabal" packageInfos <- liftIO $ getInstalledPackageIds mbP <- buildThisPane panePath nb (builder' packageDir packageD packageDescr afterSaveAction initialPackagePath modules packageInfos fields origPackageD) case mbP of Nothing -> return () Just (PackagePane{packageNotifer = pn}) -> do liftIO $ triggerEvent pn (GUIEvent { selector = MayHaveChanged, eventText = "", gtkReturn = True}) return () builder' :: FilePath -> PackageDescriptionEd -> FieldDescription PackageDescriptionEd -> (FilePath -> IDEAction) -> FilePath -> [ModuleName] -> [PackageId] -> [FieldDescription PackageDescriptionEd] -> PackageDescriptionEd -> PanePath -> Notebook -> Window -> IDEM (Maybe PackagePane,Connections) builder' packageDir packageD packageDescr afterSaveAction initialPackagePath modules packageInfos fields origPackageD panePath nb window = reifyIDE $ \ ideR -> do vb <- vBoxNew False 0 bb <- hButtonBoxNew save <- buttonNewFromStock "gtk-save" widgetSetSensitive save False closeB <- buttonNewFromStock "gtk-close" addB <- buttonNewFromStock (__ "Add Build Info") removeB <- buttonNewFromStock (__ "Remove Build Info") label <- labelNew (Nothing :: Maybe Text) boxPackStart bb addB PackNatural 0 boxPackStart bb removeB PackNatural 0 boxPackEnd bb closeB PackNatural 0 boxPackEnd bb save PackNatural 0 (widget, setInj, getExt, notifier) <- buildEditor packageDescr packageD let packagePane = PackagePane vb notifier boxPackStart vb widget PackGrow 7 boxPackStart vb label PackNatural 0 boxPackEnd vb bb PackNatural 7 let fieldNames = map (\fd -> case getParameterPrim paraName (parameters fd) of Just s -> s Nothing -> (__ "Unnamed")) fields on addB buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> sysMessage Normal (__ "Content doesn't validate") Just pde -> reflectIDE (do closePane packagePane initPackage packageDir pde {bis = bis pde ++ [bis pde !! 0]} (packageDD (packageInfos) packageDir modules (length (bis pde) + 1) (concatMap (buildInfoD (Just packageDir) modules) [0..length (bis pde)])) panePath nb modules afterSaveAction origPackageD) ideR on removeB buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> sysMessage Normal (__ "Content doesn't validate") Just pde | length (bis pde) == 1 -> sysMessage Normal (__ "Just one Build Info") | otherwise -> reflectIDE (do closePane packagePane initPackage packageDir pde{bis = take (length (bis pde) - 1) (bis pde)} (packageDD packageInfos packageDir modules (length (bis pde) - 1) (concatMap (buildInfoD (Just packageDir) modules) [0..length (bis pde) - 2])) panePath nb modules afterSaveAction origPackageD) ideR on closeB buttonActivated $ do mbP <- extract packageD [getExt] let hasChanged = case mbP of Nothing -> False Just p -> p /= origPackageD if not hasChanged then reflectIDE (closePane packagePane >> return ()) ideR else do md <- messageDialogNew (Just window) [] MessageQuestion ButtonsYesNo (__ "Unsaved changes. Close anyway?") set md [ windowWindowPosition := WinPosCenterOnParent ] resp <- dialogRun md widgetDestroy md case resp of ResponseYes -> do reflectIDE (closePane packagePane >> return ()) ideR _ -> return () on save buttonActivated $ do mbNewPackage' <- extract packageD [getExt] case mbNewPackage' of Nothing -> return () Just newPackage' -> let newPackage = fromEditor newPackage' in do let packagePath = packageDir </> (display . pkgName . package . pd) newPackage' ++ ".cabal" writeGenericPackageDescription packagePath (toGenericPackageDescription newPackage) reflectIDE (do afterSaveAction packagePath closePane packagePane return ()) ideR registerEvent notifier MayHaveChanged (\ e -> do mbP <- extract packageD [getExt] let hasChanged = case mbP of Nothing -> False Just p -> p /= origPackageD when (isJust mbP) $ labelSetMarkup label ("" :: Text) when (isJust mbP) $ comparePDE (fromJust mbP) packageD markLabel nb (getTopWidget packagePane) hasChanged widgetSetSensitive save hasChanged return (e{gtkReturn=False})) registerEvent notifier ValidationError (\e -> do labelSetMarkup label $ "<span foreground=\"red\" size=\"x-large\">The following fields have invalid values: " <> eventText e <> "</span>" return e) return (Just packagePane,[]) -- --------------------------------------------------------------------- -- The description with some tricks -- packageDD :: [PackageIdentifier] -> FilePath -> [ModuleName] -> Int -> [(Text, FieldDescription PackageDescriptionEd)] -> FieldDescription PackageDescriptionEd packageDD packages fp modules numBuildInfos extras = NFD ([ ((__ "Package"), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Synopsis") $ paraSynopsis <<<- ParaSynopsis (__ "A one-line summary of this package") $ emptyParams) (synopsis . pd) (\ a b -> b{pd = (pd b){synopsis = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Package Identifier") $ emptyParams) (package . pd) (\ a b -> b{pd = (pd b){package = a}}) packageEditor , mkField (paraName <<<- ParaName (__ "Description") $ paraSynopsis <<<- ParaSynopsis (__ "A more verbose description of this package") $ paraShadow <<<- ParaShadow ShadowOut $ paraMinSize <<<- ParaMinSize (-1,210) $ emptyParams) (T.pack . description . pd) (\ a b -> b{pd = (pd b){description = T.unpack $ if T.null a then " " else a}}) multilineStringEditor , mkField (paraName <<<- ParaName (__ "Homepage") $ emptyParams) (homepage . pd) (\ a b -> b{pd = (pd b){homepage = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Package URL") $ emptyParams) (pkgUrl . pd) (\ a b -> b{pd = (pd b){pkgUrl = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Category") $ emptyParams) (category . pd) (\ a b -> b{pd = (pd b){category = a}}) (stringEditor (const True) True) ]), ((__ "Description"), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Stability") $ emptyParams) (stability . pd) (\ a b -> b{pd = (pd b){stability = a}}) (stringEditor (const True) True) -- TODO Fix this up to work with current Cabal -- , mkField -- (paraName <<<- ParaName (__ "License") $ emptyParams) -- (license . pd) -- (\ a b -> b{pd = (pd b){license = a}}) -- (comboSelectionEditor [GPL, LGPL, BSD3, BSD4, PublicDomain, AllRightsReserved, OtherLicense] show) , mkField #if MIN_VERSION_Cabal(1,22,0) (paraName <<<- ParaName (__ "License Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of license files.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (licenseFiles . pd) (\ a b -> b{pd = (pd b){licenseFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) #else (paraName <<<- ParaName (__ "License File") $ emptyParams) (licenseFile . pd) (\ a b -> b{pd = (pd b){licenseFile = a}}) (fileEditor (Just fp) FileChooserActionOpen (__ "Select file")) #endif , mkField (paraName <<<- ParaName (__ "Copyright") $ emptyParams) (copyright . pd) (\ a b -> b{pd = (pd b){copyright = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Author") $ emptyParams) (author . pd) (\ a b -> b{pd = (pd b){author = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Maintainer") $ emptyParams) (maintainer . pd) (\ a b -> b{pd = (pd b){maintainer = a}}) (stringEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Bug Reports") $ emptyParams) (bugReports . pd) (\ a b -> b{pd = (pd b){bugReports = a}}) (stringEditor (const True) True) ]), -- ("Repositories", VFD emptyParams [ -- mkField -- (paraName <<<- ParaName "Source Repositories" $ emptyParams) -- (sourceRepos . pd) -- (\ a b -> b{pd = (pd b){sourceRepos = a}}) -- reposEditor]), ((__ "Dependencies "), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Build Dependencies") $ paraSynopsis <<<- ParaSynopsis (__ "Does this package depends on other packages?") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (nub . buildDepends . pd) (\ a b -> b{pd = (pd b){buildDepends = a}}) (dependenciesEditor packages) ]), ((__ "Meta Dep."), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Cabal version") $ paraSynopsis <<<- ParaSynopsis (__ "Does this package depends on a specific version of Cabal?") $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams) (specVersion . pd) (\ a b -> b{pd = (pd b){specVersionRaw = Left a}}) versionEditor , mkField (paraName <<<- ParaName (__ "Tested with compiler") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,150) $ emptyParams) (\a -> case (testedWith . pd) a of [] -> []--(GHC,anyVersion)] l -> l) (\ a b -> b{pd = (pd b){testedWith = a}}) testedWithEditor ]), ((__ "Data Files"), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Data Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of files to be installed for run-time use by the package.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,250) $ emptyParams) (dataFiles . pd) (\ a b -> b{pd = (pd b){dataFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) , mkField (paraName <<<- ParaName (__ "Data directory") $ emptyParams) (dataDir . pd) (\ a b -> b{pd = (pd b){dataDir = a}}) (fileEditor (Just fp) FileChooserActionSelectFolder (__ "Select file")) ]), ((__ "Extra Files"), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Extra Source Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of additional files to be included in source distributions.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (extraSrcFiles . pd) (\ a b -> b{pd = (pd b){extraSrcFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) , mkField (paraName <<<- ParaName (__ "Extra Tmp Files") $ paraSynopsis <<<- ParaSynopsis (__ "A list of additional files or directories to be removed by setup clean.") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (extraTmpFiles . pd) (\ a b -> b{pd = (pd b){extraTmpFiles = a}}) (filesEditor (Just fp) FileChooserActionOpen (__ "Select File")) ]), ((__ "Other"),VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Build Type") $ paraSynopsis <<<- ParaSynopsis (__ "Describe executable programs contained in the package") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (buildType . pd) (\ a b -> b{pd = (pd b){buildType = a}}) (maybeEditor (buildTypeEditor, emptyParams) True (__ "Specify?")) , mkField (paraName <<<- ParaName (__ "Custom Fields") $ paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (customFieldsPD . pd) (\ a b -> b{pd = (pd b){customFieldsPD = a}}) (multisetEditor (ColumnDescr True [((__ "Name"),\(n,_) -> [cellText := T.pack n]) ,((__ "Value"),\(_,v) -> [cellText := T.pack v])]) ((pairEditor (stringxEditor (const True),emptyParams) (stringEditor (const True) True,emptyParams)),emptyParams) Nothing Nothing) ]), ((__ "Executables"),VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Executables") $ paraSynopsis <<<- ParaSynopsis (__ "Describe executable programs contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) exes (\ a b -> b{exes = a}) (executablesEditor (Just fp) modules numBuildInfos) ]), ((__ "Tests"),VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Tests") $ paraSynopsis <<<- ParaSynopsis (__ "Describe tests contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) tests (\ a b -> b{tests = a}) (testsEditor (Just fp) modules numBuildInfos) ]), ((__ "Benchmarks"),VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Benchmarks") $ paraSynopsis <<<- ParaSynopsis (__ "Describe tests contained in the package") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) bms (\ a b -> b{bms = a}) (benchmarksEditor (Just fp) modules numBuildInfos) ]), ((__ "Library"), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Library") $ paraSynopsis <<<- ParaSynopsis (__ "If the package contains a library, specify the exported modules here") $ paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams) mbLib (\ a b -> b{mbLib = a}) (maybeEditor (libraryEditor (Just fp) modules numBuildInfos, paraName <<<- ParaName (__ "Specify exported modules") $ emptyParams) True (__ "Does this package contain a library?")) ]) ] ++ extras) update :: [BuildInfo] -> Int -> (BuildInfo -> BuildInfo) -> [BuildInfo] update bis index func = map (\(bi,ind) -> if ind == index then func bi else bi) (zip bis [0..length bis - 1]) buildInfoD :: Maybe FilePath -> [ModuleName] -> Int -> [(Text,FieldDescription PackageDescriptionEd)] buildInfoD fp modules i = [ ((T.pack $ printf (__ "%s Build Info") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Component is buildable here") $ emptyParams) (buildable . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{buildable = a})}) boolEditor , mkField (paraName <<<- ParaName (__ "Where to look for the source hierarchy") $ paraSynopsis <<<- ParaSynopsis (__ "Root directories for the source hierarchy.") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,150) $ emptyParams) (hsSourceDirs . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{hsSourceDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select folder")) , mkField (paraName <<<- ParaName (__ "Non-exposed or non-main modules") $ paraSynopsis <<<- ParaSynopsis (__ "A list of modules used by the component but not exposed to users.") $ paraShadow <<<- ParaShadow ShadowIn $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,300) $ paraPack <<<- ParaPack PackGrow $ emptyParams) (map (T.pack . display) . otherModules . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{otherModules = (map (\i -> forceJust (simpleParse $ T.unpack i) " PackageEditor >> buildInfoD: no parse for moduile name" ) a)})}) (modulesEditor modules) ]), ((T.pack $ printf (__ "%s Compiler ") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for haskell compilers") $ paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ paraPack <<<- ParaPack PackGrow $ emptyParams) (options . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{options = a})}) (multisetEditor (ColumnDescr True [( (__ "Compiler Flavor"),\(cv,_) -> [cellText := T.pack $ show cv]) ,( (__ "Options"),\(_,op) -> [cellText := T.pack $ concatMap (\s -> ' ' : s) op])]) ((pairEditor (compilerFlavorEditor,emptyParams) (optsEditor,emptyParams)), (paraDirection <<<- ParaDirection Vertical $ paraShadow <<<- ParaShadow ShadowIn $ emptyParams)) Nothing Nothing) #if MIN_VERSION_Cabal(1,22,0) , mkField (paraName <<<- ParaName (__ "Additional options for GHC when built with profiling") $ emptyParams) (profOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{profOptions = a})}) compilerOptsEditor , mkField (paraName <<<- ParaName (__ "Additional options for GHC when the package is built as shared library") $ emptyParams) (sharedOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{sharedOptions = a})}) compilerOptsEditor #else , mkField (paraName <<<- ParaName (__ "Additional options for GHC when built with profiling") $ emptyParams) (ghcProfOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ghcProfOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Additional options for GHC when the package is built as shared library") $ emptyParams) (ghcSharedOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ghcSharedOptions = a})}) optsEditor #endif ]), ((T.pack $ printf (__ "%s Extensions ") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Extensions") $ paraSynopsis <<<- ParaSynopsis (__ "A list of Haskell extensions used by every module.") $ paraMinSize <<<- ParaMinSize (-1,400) $ paraPack <<<- ParaPack PackGrow $ emptyParams) (oldExtensions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{oldExtensions = a})}) extensionsEditor ]), ((T.pack $ printf (__ "%s Build Tools ") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Tools needed for a build") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (buildTools . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{buildTools = a})}) (dependenciesEditor []) ]), ((T.pack $ printf (__ "%s Pkg Config ") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of pkg-config packages, needed to build this package") $ paraDirection <<<- ParaDirection Vertical $ paraMinSize <<<- ParaMinSize (-1,120) $ emptyParams) (pkgconfigDepends . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{pkgconfigDepends = a})}) (dependenciesEditor []) ]), ((T.pack $ printf (__ "%s Opts C -1-") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for C compiler") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (ccOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ccOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Options for linker") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (ldOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{ldOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "A list of header files to use when compiling") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . includes . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{includes = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "A list of header files to install") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (installIncludes . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{installIncludes = a})}) (filesEditor fp FileChooserActionOpen (__ "Select File")) ]), ((T.pack $ printf (__ "%s Opts C -2-") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of directories to search for header files") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (includeDirs . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{includeDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select Folder")) , mkField (paraName <<<- ParaName (__ "A list of C source files to be compiled,linked with the Haskell files.") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (cSources . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{cSources = a})}) (filesEditor fp FileChooserActionOpen (__ "Select file")) ]), ((T.pack $ printf (__ "%s Opts Libs ") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "A list of extra libraries to link with") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . extraLibs . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{extraLibs = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "A list of directories to search for libraries.") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (extraLibDirs . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{extraLibDirs = a})}) (filesEditor fp FileChooserActionSelectFolder (__ "Select Folder")) ]), ((T.pack $ printf (__ "%s Other") (show (i + 1))), VFD emptyParams [ mkField (paraName <<<- ParaName (__ "Options for C preprocessor") $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (cppOptions . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{cppOptions = a})}) optsEditor , mkField (paraName <<<- ParaName (__ "Support frameworks for Mac OS X") $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (map T.pack . frameworks . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{frameworks = map T.unpack a})}) (textsEditor (const True) True) , mkField (paraName <<<- ParaName (__ "Custom fields build info") $ paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,150) $ paraDirection <<<- ParaDirection Vertical $ emptyParams) (customFieldsBI . (\a -> a !! i) . bis) (\ a b -> b{bis = update (bis b) i (\bi -> bi{customFieldsBI = a})}) (multisetEditor (ColumnDescr True [((__ "Name"),\(n,_) -> [cellText := T.pack n]) ,((__ "Value"),\(_,v) -> [cellText := T.pack v])]) ((pairEditor (stringxEditor (const True),emptyParams) (stringEditor (const True) True,emptyParams)),emptyParams) Nothing Nothing) ])] stringxEditor :: (String -> Bool) -> Editor String stringxEditor val para noti = do (wid,inj,ext) <- stringEditor val True para noti let xinj ("") = inj "" xinj ('x':'-':rest) = inj rest xinj _ = throwIDE "PackageEditor>>stringxEditor: field without leading x-" xext = do res <- ext case res of Nothing -> return Nothing Just str -> return (Just ("x-" ++ str)) return (wid,xinj,xext) optsEditor :: Editor [String] optsEditor para noti = do (wid,inj,ext) <- stringEditor (const True) True para noti let oinj = inj . unwords oext = do res <- ext case res of Nothing -> return Nothing Just str -> return (Just (words str)) return (wid,oinj,oext) compilerOptRecordEditor :: Editor (CompilerFlavor, [String]) compilerOptRecordEditor para noti = do pairEditor (compilerFlavorEditor , paraName <<<- ParaName "Compiler" $ emptyParams) (optsEditor,paraName <<<- ParaName "Options" $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti compilerOptsEditor :: Editor [(CompilerFlavor, [String])] compilerOptsEditor p noti = multisetEditor (ColumnDescr True [("Compiler",\(compiler, _) -> [cellText := T.pack $ show compiler]) ,("Options",\(_, opts ) -> [cellText := T.pack $ unwords opts])]) (compilerOptRecordEditor, paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ emptyParams) (Just (sortBy (\ (f1, _) (f2, _) -> compare f1 f2))) (Just (\ (f1, _) (f2, _) -> f1 == f2)) (paraShadow <<<- ParaShadow ShadowIn $ paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ paraDirection <<<- ParaDirection Vertical $ paraPack <<<- ParaPack PackGrow $ p) noti packageEditor :: Editor PackageIdentifier packageEditor para noti = do (wid,inj,ext) <- pairEditor (stringEditor (\s -> not (null s)) True, paraName <<<- ParaName (__ "Name") $ emptyParams) (versionEditor, paraName <<<- ParaName (__ "Version") $ emptyParams) (paraDirection <<<- ParaDirection Horizontal $ paraShadow <<<- ParaShadow ShadowIn $ para) noti let pinj (PackageIdentifier (PackageName n) v) = inj (n,v) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (n,v) -> do if null n then return Nothing else return (Just $PackageIdentifier (PackageName n) v) return (wid,pinj,pext) testedWithEditor :: Editor [(CompilerFlavor, VersionRange)] testedWithEditor para = do multisetEditor (ColumnDescr True [((__ "Compiler Flavor"),\(cv,_) -> [cellText := T.pack $ show cv]) ,((__ "Version Range"),\(_,vr) -> [cellText := T.pack $ display vr])]) (pairEditor (compilerFlavorEditor, paraShadow <<<- (ParaShadow ShadowNone) $ emptyParams) (versionRangeEditor, paraShadow <<<- (ParaShadow ShadowNone) $ emptyParams), (paraDirection <<<- (ParaDirection Vertical) $ emptyParams)) Nothing (Just (==)) para compilerFlavorEditor :: Editor CompilerFlavor compilerFlavorEditor para noti = do (wid,inj,ext) <- eitherOrEditor (comboSelectionEditor flavors (T.pack . show), paraName <<<- (ParaName (__ "Select compiler")) $ emptyParams) (textEditor (\s -> not (T.null s)) True, paraName <<<- (ParaName (__ "Specify compiler")) $ emptyParams) (__ "Other") (paraName <<<- ParaName (__ "Select") $ para) noti let cfinj comp = case comp of (OtherCompiler str) -> inj (Right $ T.pack str) other -> inj (Left other) let cfext = do mbp <- ext case mbp of Nothing -> return Nothing Just (Right s) -> return (Just . OtherCompiler $ T.unpack s) Just (Left other) -> return (Just other) return (wid,cfinj,cfext) where flavors = [GHC, NHC, Hugs, HBC, Helium, JHC] buildTypeEditor :: Editor BuildType buildTypeEditor para noti = do (wid,inj,ext) <- eitherOrEditor (comboSelectionEditor flavors (T.pack . show), paraName <<<- (ParaName (__ "Select")) $ emptyParams) (textEditor (const True) True, paraName <<<- (ParaName (__ "Unknown")) $ emptyParams) (__ "Unknown") (paraName <<<- ParaName (__ "Select") $ para) noti let cfinj comp = case comp of (UnknownBuildType str) -> inj (Right $ T.pack str) other -> inj (Left other) let cfext = do mbp <- ext case mbp of Nothing -> return Nothing Just (Right s) -> return (Just . UnknownBuildType $ T.unpack s) Just (Left other) -> return (Just other) return (wid,cfinj,cfext) where flavors = [Simple, Configure, Make, Custom] extensionsEditor :: Editor [Extension] extensionsEditor = staticListMultiEditor extensionsL (T.pack . show) extensionsL :: [Extension] extensionsL = map EnableExtension [minBound..maxBound] {-- reposEditor :: Editor [SourceRepo] reposEditor p noti = multisetEditor (ColumnDescr False [("",\repo -> [cellText := display repo])]) (repoEditor, paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraOuterAlignment <<<- ParaInnerAlignment (0.0, 0.5, 1.0, 1.0) $ paraInnerAlignment <<<- ParaOuterAlignment (0.0, 0.5, 1.0, 1.0) $ paraDirection <<<- ParaDirection Vertical $ paraPack <<<- ParaPack PackGrow $ p) noti instance Text SourceRepo where disp (SourceRepo repoKind repoType repoLocation repoModule repoBranch repoTag repoSubdir) = disp repoKind <+> case repoType of Nothing -> empty Just repoT -> disp repoT <+> case repoLocation of Nothing -> empty Just repoL -> text repoL repoEditor :: Editor SourceRepo repoEditor paras noti = do (widg,inj,ext) <- tupel7Editor (repoKindEditor,noBorder) (maybeEditor (repoTypeEditor,noBorder) True "Specify a type", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a location", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a module", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a branch", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a tag", emptyParams) (maybeEditor (textEditor (const True) True,noBorder) True "Specify a subdir", emptyParams) (paraDirection <<<- ParaDirection Vertical $ noBorder) noti return (widg, (\ r -> inj (repoKind r,repoType r,repoLocation r,repoModule r,repoBranch r,repoTag r,repoSubdir r)), (do mb <- ext case mb of Nothing -> return Nothing Just (a,b,c,d,e,f,g) -> return (Just (SourceRepo a b c d e f g)))) where noBorder = paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams repoKindEditor :: Editor RepoKind repoKindEditor paras noti = do (widg,inj,ext) <- pairEditor (comboSelectionEditor selectionList show, emptyParams) (textEditor (const True) True,emptyParams) paras noti return (widg, (\kind -> case kind of RepoKindUnknown str -> inj (RepoKindUnknown "",str) other -> inj (other,"")), (do mbRes <- ext case mbRes of Nothing -> return Nothing Just (RepoKindUnknown "",str) -> return (Just (RepoKindUnknown str)) Just (other,_) -> return (Just other))) where selectionList = [RepoHead, RepoThis, RepoKindUnknown ""] repoTypeEditor :: Editor RepoType repoTypeEditor paras noti = do (widg,inj,ext) <- pairEditor (comboSelectionEditor selectionList show, emptyParams) (textEditor (const True) True,emptyParams) paras noti return (widg, (\kind -> case kind of OtherRepoType str -> inj (OtherRepoType "",str) other -> inj (other,"")), (do mbRes <- ext case mbRes of Nothing -> return Nothing Just (OtherRepoType "",str) -> return (Just (OtherRepoType str)) Just (other,_) -> return (Just other))) where selectionList = [Darcs, Git, SVN, CVS, Mercurial, GnuArch, Bazaar, Monotone, OtherRepoType ""] --} -- ------------------------------------------------------------ -- * BuildInfos -- ------------------------------------------------------------ data Library' = Library'{ exposedModules' :: [ModuleName] #if MIN_VERSION_Cabal(1,22,0) , reexportedModules' :: [ModuleReexport] , requiredSignatures':: [ModuleName] , exposedSignatures' :: [ModuleName] #endif , libExposed' :: Bool , libBuildInfoIdx :: Int} deriving (Show, Eq) data Executable' = Executable'{ exeName' :: Text , modulePath' :: FilePath , buildInfoIdx :: Int} deriving (Show, Eq) data Test' = Test'{ testName' :: Text , testInterface' :: TestSuiteInterface , testBuildInfoIdx :: Int} deriving (Show, Eq) data Benchmark' = Benchmark'{ benchmarkName' :: Text , benchmarkInterface' :: BenchmarkInterface , benchmarkBuildInfoIdx :: Int} deriving (Show, Eq) instance Default Library' #if MIN_VERSION_Cabal(1,22,0) where getDefault = Library' [] [] [] [] getDefault getDefault #else where getDefault = Library' [] getDefault getDefault #endif instance Default Executable' where getDefault = Executable' getDefault getDefault getDefault instance Default Test' where getDefault = Test' getDefault (TestSuiteExeV10 (Version [1,0] []) getDefault) getDefault instance Default Benchmark' where getDefault = Benchmark' getDefault (BenchmarkExeV10 (Version [1,0] []) getDefault) getDefault #if MIN_VERSION_Cabal(1,22,0) libraryEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Library' libraryEditor fp modules numBuildInfos para noti = do (wid,inj,ext) <- pairEditor (tupel3Editor (boolEditor, paraName <<<- ParaName (__ "Exposed") $ paraSynopsis <<<- ParaSynopsis (__ "Is the lib to be exposed by default?") $ emptyParams) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (buildInfoEditorP numBuildInfos, paraName <<<- ParaName (__ "Build Info") $ paraPack <<<- ParaPack PackNatural $ para), (paraDirection <<<- ParaDirection Vertical $ emptyParams)) (tupel3Editor (modulesEditor (sort modules), paraName <<<- ParaName (__ "Reexported Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Required Signatures") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Signatures") $ paraMinSize <<<- ParaMinSize (-1,300) $ para), (paraDirection <<<- ParaDirection Vertical $ emptyParams)) (paraDirection <<<- ParaDirection Vertical $ emptyParams) noti let pinj (Library' em rmn rs es exp bi) = inj ((exp, map (T.pack . display) em,bi), (map (T.pack . display) rmn, map (T.pack . display) rs, map (T.pack . display) es)) parseModuleNames = map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") parseRexportedModules = map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") pext = do mbp <- ext case mbp of Nothing -> return Nothing Just ((exp,em,bi), (rmn, rs, es)) -> return (Just $ Library' (parseModuleNames em) (parseRexportedModules rmn) (parseModuleNames rs) (parseModuleNames es) exp bi) return (wid,pinj,pext) #else libraryEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Library' libraryEditor fp modules numBuildInfos para noti = do (wid,inj,ext) <- tupel3Editor (boolEditor, paraName <<<- ParaName (__ "Exposed") $ paraSynopsis <<<- ParaSynopsis (__ "Is the lib to be exposed by default?") $ emptyParams) (modulesEditor (sort modules), paraName <<<- ParaName (__ "Exposed Modules") $ paraMinSize <<<- ParaMinSize (-1,300) $ para) (buildInfoEditorP numBuildInfos, paraName <<<- ParaName (__ "Build Info") $ paraPack <<<- ParaPack PackNatural $ para) (paraDirection <<<- ParaDirection Vertical $ emptyParams) noti let pinj (Library' em exp bi) = inj (exp, map (T.pack . display) em,bi) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (exp,em,bi) -> return (Just $ Library' (map (\s -> forceJust (simpleParse $ T.unpack s) "SpecialEditor >> libraryEditor: no parse for moduile name") em) exp bi) return (wid,pinj,pext) #endif modulesEditor :: [ModuleName] -> Editor [Text] modulesEditor modules = staticListMultiEditor (map (T.pack . display) modules) id executablesEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Executable'] executablesEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [( (__ "Executable Name"),\(Executable' exeName _ _) -> [cellText := exeName]) ,( (__ "Module Path"),\(Executable' _ mp _) -> [cellText := T.pack mp]) ,( (__ "Build info index"),\(Executable' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (executableEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) executableEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Executable' executableEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (\s -> not (T.null s)) True, paraName <<<- ParaName (__ "Executable Name") $ emptyParams) (stringEditor (\s -> not (null s)) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Executable' s f bi) = inj (s,f,bi) let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Executable' s f bi) return (wid,pinj,pext) testsEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Test'] testsEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [( (__ "Test Name"),\(Test' testName _ _) -> [cellText := testName]) ,( (__ "Interface"),\(Test' _ i _) -> [cellText := T.pack $ interfaceName i]) ,( (__ "Build info index"),\(Test' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (testEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) where interfaceName (TestSuiteExeV10 _ f) = f interfaceName i = show i testEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Test' testEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (\s -> not (T.null s)) True, paraName <<<- ParaName (__ "Test Name") $ emptyParams) (stringEditor (\s -> not (null s)) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Test' s (TestSuiteExeV10 (Version [1,0] []) f) bi) = inj (s,f,bi) pinj _ = error "Unexpected Test Interface" let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Test' s (TestSuiteExeV10 (Version [1,0] []) f) bi) return (wid,pinj,pext) benchmarksEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor [Benchmark'] benchmarksEditor fp modules countBuildInfo p = multisetEditor (ColumnDescr True [( (__ "Benchmark Name"),\(Benchmark' benchmarkName _ _) -> [cellText := benchmarkName]) ,( (__ "Interface"),\(Benchmark' _ i _) -> [cellText := T.pack $ interfaceName i]) ,( (__ "Build info index"),\(Benchmark' _ _ bii) -> [cellText := T.pack $ show (bii + 1)])]) (benchmarkEditor fp modules countBuildInfo,emptyParams) Nothing Nothing (paraShadow <<<- ParaShadow ShadowIn $ paraMinSize <<<- ParaMinSize (-1,200) $ p) where interfaceName (BenchmarkExeV10 _ f) = f interfaceName i = show i benchmarkEditor :: Maybe FilePath -> [ModuleName] -> Int -> Editor Benchmark' benchmarkEditor fp modules countBuildInfo para noti = do (wid,inj,ext) <- tupel3Editor (textEditor (\s -> not (T.null s)) True, paraName <<<- ParaName (__ "Benchmark Name") $ emptyParams) (stringEditor (\s -> not (null s)) True, paraDirection <<<- ParaDirection Vertical $ paraName <<<- ParaName (__ "File with main function") $ emptyParams) (buildInfoEditorP countBuildInfo, paraName <<<- ParaName (__ "Build Info") $ paraOuterAlignment <<<- ParaOuterAlignment (0.0, 0.0, 0.0, 0.0) $ paraOuterPadding <<<- ParaOuterPadding (0, 0, 0, 0) $ paraInnerAlignment <<<- ParaInnerAlignment (0.0, 0.0, 0.0, 0.0) $ paraInnerPadding <<<- ParaInnerPadding (0, 0, 0, 0) $ emptyParams) (paraDirection <<<- ParaDirection Vertical $ para) noti let pinj (Benchmark' s (BenchmarkExeV10 (Version [1,0] []) f) bi) = inj (s,f,bi) pinj _ = error "Unexpected Benchmark Interface" let pext = do mbp <- ext case mbp of Nothing -> return Nothing Just (s,f,bi) -> return (Just $Benchmark' s (BenchmarkExeV10 (Version [1,0] []) f) bi) return (wid,pinj,pext) buildInfoEditorP :: Int -> Editor Int buildInfoEditorP numberOfBuildInfos para noti = do (wid,inj,ext) <- intEditor (1.0,fromIntegral numberOfBuildInfos,1.0) (paraName <<<- ParaName (__ "Build Info") $para) noti let pinj i = inj (i + 1) let pext = do mbV <- ext case mbV of Nothing -> return Nothing Just i -> return (Just (i - 1)) return (wid,pinj,pext) -- ------------------------------------------------------------ -- * (Boring) default values -- ------------------------------------------------------------ instance Default CompilerFlavor where getDefault = GHC instance Default BuildInfo where getDefault = emptyBuildInfo instance Default Library where getDefault = Library [] #if MIN_VERSION_Cabal(1,22,0) [] [] [] #endif getDefault getDefault instance Default Executable where getDefault = Executable getDefault getDefault getDefault instance Default RepoType where getDefault = Darcs instance Default RepoKind where getDefault = RepoThis instance Default SourceRepo where getDefault = SourceRepo getDefault getDefault getDefault getDefault getDefault getDefault getDefault instance Default BuildType where getDefault = Simple
573/leksah
src/IDE/Pane/PackageEditor.hs
gpl-2.0
80,244
0
36
27,779
20,786
10,846
9,940
-1
-1
module XorTernary (combineTernaryXors, tests) where import XorCnf --import XorGauss import XorCnfSimplify import qualified Data.Map as Map import Data.List import Data.Maybe import Test.HUnit import qualified Data.Set as Set key :: Var -> Var -> (Var,Var) key x y | x < y = (x,y) | otherwise = (y,x) addXor :: Clause -> Clause -> Maybe Clause addXor (Xor p vs) (Xor p' vs') = simplify $ newXor (addParity p p') (Set.toList (union `Set.difference` intersect)) where intersect = vs `Set.intersection` vs' union = vs `Set.union` vs' addXor _ _ = error "One of the operands is not a xor-clause" combineTernaryXors :: [Clause] -> [Clause] combineTernaryXors clauses = binXors where triXors = [ c | c <- clauses, isXor c, length (getVars c) == 3 ] xorGroups = map (map snd) (xorPairGroups triXors) xorGroups' = [ (head xg, tail xg) | xg <- xorGroups, length xg > 1 ] binXors = catMaybes [ (addXor xor xor') | (xor, xors) <- xorGroups', xor' <- xors ] varPairs :: Clause -> [((Var, Var), Clause)] varPairs xor@(Xor _ vars) = [ (key v1 v2,xor), (key v1 v3,xor), (key v2 v3,xor) ] where [v1,v2,v3] = Set.toList vars xorPairGroups :: [Clause] -> [[((Var, Var), Clause)]] xorPairGroups triXors = groupBy sameGroup $ sortBy cmpGroup (concatMap varPairs triXors) where sameGroup (k1,_) (k2,_) = k1 == k2 cmpGroup (k1,_) (k2,_) = compare k1 k2 tests = test [ "test1" ~: "varPairs" ~: varPairs (newXor Even [Var 4, Var 3, Var 8]) ~=? [ ((Var 3, Var 4), newXor Even [Var 4, Var 3, Var 8]), ((Var 4, Var 8), newXor Even [Var 4, Var 3, Var 8]), ((Var 3, Var 8), newXor Even [Var 4, Var 3, Var 8]) ], "test2" ~: "xorPairGroups" ~: xorPairGroups [newXor Even [Var 1, Var 2, Var 3], newXor Odd [Var 1, Var 2, Var 4]] ~=? [[((Var 1, Var 2), newXor Even [Var 1, Var 2, Var 3]), ((Var 1, Var 2), newXor Odd [Var 1, Var 2, Var 4])], [((Var 1, Var 3), newXor Even [Var 1, Var 2, Var 3])], [((Var 1, Var 4), newXor Odd [Var 1, Var 2, Var 4])], [((Var 2, Var 3), newXor Even [Var 1, Var 2, Var 3])], [((Var 2, Var 4), newXor Odd [Var 1, Var 2, Var 4])]] ]
a1880/xor
xcnf-preprocess/XorTernary.hs
gpl-3.0
2,785
0
13
1,131
1,149
618
531
50
1
module TypeUndefTycon2 where data A a = A Ink
roberth/uu-helium
test/staticerrors/TypeUndefTycon2.hs
gpl-3.0
48
0
6
11
14
9
5
2
0
{-# 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.Kinesis.GetShardIterator -- 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) -- -- Gets a shard iterator. A shard iterator expires five minutes after it is -- returned to the requester. -- -- A shard iterator specifies the position in the shard from which to start -- reading data records sequentially. A shard iterator specifies this -- position using the sequence number of a data record in a shard. A -- sequence number is the identifier associated with every record ingested -- in the Amazon Kinesis stream. The sequence number is assigned when a -- record is put into the stream. -- -- You must specify the shard iterator type. For example, you can set the -- 'ShardIteratorType' parameter to read exactly from the position denoted -- by a specific sequence number by using the 'AT_SEQUENCE_NUMBER' shard -- iterator type, or right after the sequence number by using the -- 'AFTER_SEQUENCE_NUMBER' shard iterator type, using sequence numbers -- returned by earlier calls to PutRecord, PutRecords, GetRecords, or -- DescribeStream. You can specify the shard iterator type 'TRIM_HORIZON' -- in the request to cause 'ShardIterator' to point to the last untrimmed -- record in the shard in the system, which is the oldest data record in -- the shard. Or you can point to just after the most recent record in the -- shard, by using the shard iterator type 'LATEST', so that you always -- read the most recent data in the shard. -- -- When you repeatedly read from an Amazon Kinesis stream use a -- GetShardIterator request to get the first shard iterator for use in your -- first GetRecords request and then use the shard iterator returned by the -- GetRecords request in 'NextShardIterator' for subsequent reads. A new -- shard iterator is returned by every GetRecords request in -- 'NextShardIterator', which you use in the 'ShardIterator' parameter of -- the next GetRecords request. -- -- If a GetShardIterator request is made too often, you receive a -- 'ProvisionedThroughputExceededException'. For more information about -- throughput limits, see GetRecords. -- -- If the shard is closed, the iterator can\'t return more data, and -- GetShardIterator returns 'null' for its 'ShardIterator'. A shard can be -- closed using SplitShard or MergeShards. -- -- GetShardIterator has a limit of 5 transactions per second per account -- per open shard. -- -- /See:/ <http://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html AWS API Reference> for GetShardIterator. module Network.AWS.Kinesis.GetShardIterator ( -- * Creating a Request getShardIterator , GetShardIterator -- * Request Lenses , gsiStartingSequenceNumber , gsiStreamName , gsiShardId , gsiShardIteratorType -- * Destructuring the Response , getShardIteratorResponse , GetShardIteratorResponse -- * Response Lenses , gsirsShardIterator , gsirsResponseStatus ) where import Network.AWS.Kinesis.Types import Network.AWS.Kinesis.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input for 'GetShardIterator'. -- -- /See:/ 'getShardIterator' smart constructor. data GetShardIterator = GetShardIterator' { _gsiStartingSequenceNumber :: !(Maybe Text) , _gsiStreamName :: !Text , _gsiShardId :: !Text , _gsiShardIteratorType :: !ShardIteratorType } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetShardIterator' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gsiStartingSequenceNumber' -- -- * 'gsiStreamName' -- -- * 'gsiShardId' -- -- * 'gsiShardIteratorType' getShardIterator :: Text -- ^ 'gsiStreamName' -> Text -- ^ 'gsiShardId' -> ShardIteratorType -- ^ 'gsiShardIteratorType' -> GetShardIterator getShardIterator pStreamName_ pShardId_ pShardIteratorType_ = GetShardIterator' { _gsiStartingSequenceNumber = Nothing , _gsiStreamName = pStreamName_ , _gsiShardId = pShardId_ , _gsiShardIteratorType = pShardIteratorType_ } -- | The sequence number of the data record in the shard from which to start -- reading from. gsiStartingSequenceNumber :: Lens' GetShardIterator (Maybe Text) gsiStartingSequenceNumber = lens _gsiStartingSequenceNumber (\ s a -> s{_gsiStartingSequenceNumber = a}); -- | The name of the stream. gsiStreamName :: Lens' GetShardIterator Text gsiStreamName = lens _gsiStreamName (\ s a -> s{_gsiStreamName = a}); -- | The shard ID of the shard to get the iterator for. gsiShardId :: Lens' GetShardIterator Text gsiShardId = lens _gsiShardId (\ s a -> s{_gsiShardId = a}); -- | Determines how the shard iterator is used to start reading data records -- from the shard. -- -- The following are the valid shard iterator types: -- -- - AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted -- by a specific sequence number. -- - AFTER_SEQUENCE_NUMBER - Start reading right after the position -- denoted by a specific sequence number. -- - TRIM_HORIZON - Start reading at the last untrimmed record in the -- shard in the system, which is the oldest data record in the shard. -- - LATEST - Start reading just after the most recent record in the -- shard, so that you always read the most recent data in the shard. gsiShardIteratorType :: Lens' GetShardIterator ShardIteratorType gsiShardIteratorType = lens _gsiShardIteratorType (\ s a -> s{_gsiShardIteratorType = a}); instance AWSRequest GetShardIterator where type Rs GetShardIterator = GetShardIteratorResponse request = postJSON kinesis response = receiveJSON (\ s h x -> GetShardIteratorResponse' <$> (x .?> "ShardIterator") <*> (pure (fromEnum s))) instance ToHeaders GetShardIterator where toHeaders = const (mconcat ["X-Amz-Target" =# ("Kinesis_20131202.GetShardIterator" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON GetShardIterator where toJSON GetShardIterator'{..} = object (catMaybes [("StartingSequenceNumber" .=) <$> _gsiStartingSequenceNumber, Just ("StreamName" .= _gsiStreamName), Just ("ShardId" .= _gsiShardId), Just ("ShardIteratorType" .= _gsiShardIteratorType)]) instance ToPath GetShardIterator where toPath = const "/" instance ToQuery GetShardIterator where toQuery = const mempty -- | Represents the output for 'GetShardIterator'. -- -- /See:/ 'getShardIteratorResponse' smart constructor. data GetShardIteratorResponse = GetShardIteratorResponse' { _gsirsShardIterator :: !(Maybe Text) , _gsirsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetShardIteratorResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gsirsShardIterator' -- -- * 'gsirsResponseStatus' getShardIteratorResponse :: Int -- ^ 'gsirsResponseStatus' -> GetShardIteratorResponse getShardIteratorResponse pResponseStatus_ = GetShardIteratorResponse' { _gsirsShardIterator = Nothing , _gsirsResponseStatus = pResponseStatus_ } -- | The position in the shard from which to start reading data records -- sequentially. A shard iterator specifies this position using the -- sequence number of a data record in a shard. gsirsShardIterator :: Lens' GetShardIteratorResponse (Maybe Text) gsirsShardIterator = lens _gsirsShardIterator (\ s a -> s{_gsirsShardIterator = a}); -- | The response status code. gsirsResponseStatus :: Lens' GetShardIteratorResponse Int gsirsResponseStatus = lens _gsirsResponseStatus (\ s a -> s{_gsirsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-kinesis/gen/Network/AWS/Kinesis/GetShardIterator.hs
mpl-2.0
8,681
0
13
1,764
877
543
334
106
1
{-# 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.CodePipeline.PollForThirdPartyJobs -- 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) -- -- Determines whether there are any third party jobs for a job worker to -- act on. Only used for partner actions. -- -- When this API is called, AWS CodePipeline returns temporary credentials -- for the Amazon S3 bucket used to store artifacts for the pipeline, if -- the action requires access to that Amazon S3 bucket for input or output -- artifacts. -- -- /See:/ <http://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForThirdPartyJobs.html AWS API Reference> for PollForThirdPartyJobs. module Network.AWS.CodePipeline.PollForThirdPartyJobs ( -- * Creating a Request pollForThirdPartyJobs , PollForThirdPartyJobs -- * Request Lenses , pftpjMaxBatchSize , pftpjActionTypeId -- * Destructuring the Response , pollForThirdPartyJobsResponse , PollForThirdPartyJobsResponse -- * Response Lenses , pftpjrsJobs , pftpjrsResponseStatus ) where import Network.AWS.CodePipeline.Types import Network.AWS.CodePipeline.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input of a poll for third party jobs action. -- -- /See:/ 'pollForThirdPartyJobs' smart constructor. data PollForThirdPartyJobs = PollForThirdPartyJobs' { _pftpjMaxBatchSize :: !(Maybe Nat) , _pftpjActionTypeId :: !ActionTypeId } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PollForThirdPartyJobs' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pftpjMaxBatchSize' -- -- * 'pftpjActionTypeId' pollForThirdPartyJobs :: ActionTypeId -- ^ 'pftpjActionTypeId' -> PollForThirdPartyJobs pollForThirdPartyJobs pActionTypeId_ = PollForThirdPartyJobs' { _pftpjMaxBatchSize = Nothing , _pftpjActionTypeId = pActionTypeId_ } -- | The maximum number of jobs to return in a poll for jobs call. pftpjMaxBatchSize :: Lens' PollForThirdPartyJobs (Maybe Natural) pftpjMaxBatchSize = lens _pftpjMaxBatchSize (\ s a -> s{_pftpjMaxBatchSize = a}) . mapping _Nat; -- | Undocumented member. pftpjActionTypeId :: Lens' PollForThirdPartyJobs ActionTypeId pftpjActionTypeId = lens _pftpjActionTypeId (\ s a -> s{_pftpjActionTypeId = a}); instance AWSRequest PollForThirdPartyJobs where type Rs PollForThirdPartyJobs = PollForThirdPartyJobsResponse request = postJSON codePipeline response = receiveJSON (\ s h x -> PollForThirdPartyJobsResponse' <$> (x .?> "jobs" .!@ mempty) <*> (pure (fromEnum s))) instance ToHeaders PollForThirdPartyJobs where toHeaders = const (mconcat ["X-Amz-Target" =# ("CodePipeline_20150709.PollForThirdPartyJobs" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON PollForThirdPartyJobs where toJSON PollForThirdPartyJobs'{..} = object (catMaybes [("maxBatchSize" .=) <$> _pftpjMaxBatchSize, Just ("actionTypeId" .= _pftpjActionTypeId)]) instance ToPath PollForThirdPartyJobs where toPath = const "/" instance ToQuery PollForThirdPartyJobs where toQuery = const mempty -- | Represents the output of a poll for third party jobs action. -- -- /See:/ 'pollForThirdPartyJobsResponse' smart constructor. data PollForThirdPartyJobsResponse = PollForThirdPartyJobsResponse' { _pftpjrsJobs :: !(Maybe [ThirdPartyJob]) , _pftpjrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PollForThirdPartyJobsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pftpjrsJobs' -- -- * 'pftpjrsResponseStatus' pollForThirdPartyJobsResponse :: Int -- ^ 'pftpjrsResponseStatus' -> PollForThirdPartyJobsResponse pollForThirdPartyJobsResponse pResponseStatus_ = PollForThirdPartyJobsResponse' { _pftpjrsJobs = Nothing , _pftpjrsResponseStatus = pResponseStatus_ } -- | Information about the jobs to take action on. pftpjrsJobs :: Lens' PollForThirdPartyJobsResponse [ThirdPartyJob] pftpjrsJobs = lens _pftpjrsJobs (\ s a -> s{_pftpjrsJobs = a}) . _Default . _Coerce; -- | The response status code. pftpjrsResponseStatus :: Lens' PollForThirdPartyJobsResponse Int pftpjrsResponseStatus = lens _pftpjrsResponseStatus (\ s a -> s{_pftpjrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-codepipeline/gen/Network/AWS/CodePipeline/PollForThirdPartyJobs.hs
mpl-2.0
5,370
0
13
1,128
691
412
279
89
1
{-# LANGUAGE FlexibleContexts #-} -- | -- Module : Statistics.Sample -- Copyright : (c) 2008 Don Stewart, 2009 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Commonly used sample statistics, also known as descriptive -- statistics. module Statistics.Sample ( -- * Types Sample , WeightedSample -- * Descriptive functions , range -- * Statistics of location , mean , welfordMean , meanWeighted , harmonicMean , geometricMean -- * Statistics of dispersion -- $variance -- ** Functions over central moments , centralMoment , centralMoments , skewness , kurtosis -- ** Two-pass functions (numerically robust) -- $robust , variance , varianceUnbiased , meanVariance , meanVarianceUnb , stdDev , varianceWeighted , stdErrMean -- ** Single-pass functions (faster, less safe) -- $cancellation , fastVariance , fastVarianceUnbiased , fastStdDev -- * Joint distirbutions , covariance , correlation , pair -- * References -- $references ) where import Statistics.Function (minMax) import Statistics.Sample.Internal (robustSumVar, sum) import Statistics.Types.Internal (Sample,WeightedSample) import qualified Data.Vector as V import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U -- Operator ^ will be overridden import Prelude hiding ((^), sum) -- | /O(n)/ Range. The difference between the largest and smallest -- elements of a sample. range :: (G.Vector v Double) => v Double -> Double range s = hi - lo where (lo , hi) = minMax s {-# INLINE range #-} -- | /O(n)/ Arithmetic mean. This uses Kahan-Babuška-Neumaier -- summation, so is more accurate than 'welfordMean' unless the input -- values are very large. mean :: (G.Vector v Double) => v Double -> Double mean xs = sum xs / fromIntegral (G.length xs) {-# SPECIALIZE mean :: U.Vector Double -> Double #-} {-# SPECIALIZE mean :: V.Vector Double -> Double #-} -- | /O(n)/ Arithmetic mean. This uses Welford's algorithm to provide -- numerical stability, using a single pass over the sample data. -- -- Compared to 'mean', this loses a surprising amount of precision -- unless the inputs are very large. welfordMean :: (G.Vector v Double) => v Double -> Double welfordMean = fini . G.foldl' go (T 0 0) where fini (T a _) = a go (T m n) x = T m' n' where m' = m + (x - m) / fromIntegral n' n' = n + 1 {-# SPECIALIZE welfordMean :: U.Vector Double -> Double #-} {-# SPECIALIZE welfordMean :: V.Vector Double -> Double #-} -- | /O(n)/ Arithmetic mean for weighted sample. It uses a single-pass -- algorithm analogous to the one used by 'welfordMean'. meanWeighted :: (G.Vector v (Double,Double)) => v (Double,Double) -> Double meanWeighted = fini . G.foldl' go (V 0 0) where fini (V a _) = a go (V m w) (x,xw) = V m' w' where m' | w' == 0 = 0 | otherwise = m + xw * (x - m) / w' w' = w + xw {-# INLINE meanWeighted #-} -- | /O(n)/ Harmonic mean. This algorithm performs a single pass over -- the sample. harmonicMean :: (G.Vector v Double) => v Double -> Double harmonicMean = fini . G.foldl' go (T 0 0) where fini (T b a) = fromIntegral a / b go (T x y) n = T (x + (1/n)) (y+1) {-# INLINE harmonicMean #-} -- | /O(n)/ Geometric mean of a sample containing no negative values. geometricMean :: (G.Vector v Double) => v Double -> Double geometricMean = exp . mean . G.map log {-# INLINE geometricMean #-} -- | Compute the /k/th central moment of a sample. The central moment -- is also known as the moment about the mean. -- -- This function performs two passes over the sample, so is not subject -- to stream fusion. -- -- For samples containing many values very close to the mean, this -- function is subject to inaccuracy due to catastrophic cancellation. centralMoment :: (G.Vector v Double) => Int -> v Double -> Double centralMoment a xs | a < 0 = error "Statistics.Sample.centralMoment: negative input" | a == 0 = 1 | a == 1 = 0 | otherwise = sum (G.map go xs) / fromIntegral (G.length xs) where go x = (x-m) ^ a m = mean xs {-# SPECIALIZE centralMoment :: Int -> U.Vector Double -> Double #-} {-# SPECIALIZE centralMoment :: Int -> V.Vector Double -> Double #-} -- | Compute the /k/th and /j/th central moments of a sample. -- -- This function performs two passes over the sample, so is not subject -- to stream fusion. -- -- For samples containing many values very close to the mean, this -- function is subject to inaccuracy due to catastrophic cancellation. centralMoments :: (G.Vector v Double) => Int -> Int -> v Double -> (Double, Double) centralMoments a b xs | a < 2 || b < 2 = (centralMoment a xs , centralMoment b xs) | otherwise = fini . G.foldl' go (V 0 0) $ xs where go (V i j) x = V (i + d^a) (j + d^b) where d = x - m fini (V i j) = (i / n , j / n) m = mean xs n = fromIntegral (G.length xs) {-# SPECIALIZE centralMoments :: Int -> Int -> U.Vector Double -> (Double, Double) #-} {-# SPECIALIZE centralMoments :: Int -> Int -> V.Vector Double -> (Double, Double) #-} -- | Compute the skewness of a sample. This is a measure of the -- asymmetry of its distribution. -- -- A sample with negative skew is said to be /left-skewed/. Most of -- its mass is on the right of the distribution, with the tail on the -- left. -- -- > skewness $ U.to [1,100,101,102,103] -- > ==> -1.497681449918257 -- -- A sample with positive skew is said to be /right-skewed/. -- -- > skewness $ U.to [1,2,3,4,100] -- > ==> 1.4975367033335198 -- -- A sample's skewness is not defined if its 'variance' is zero. -- -- This function performs two passes over the sample, so is not subject -- to stream fusion. -- -- For samples containing many values very close to the mean, this -- function is subject to inaccuracy due to catastrophic cancellation. skewness :: (G.Vector v Double) => v Double -> Double skewness xs = c3 * c2 ** (-1.5) where (c3 , c2) = centralMoments 3 2 xs {-# SPECIALIZE skewness :: U.Vector Double -> Double #-} {-# SPECIALIZE skewness :: V.Vector Double -> Double #-} -- | Compute the excess kurtosis of a sample. This is a measure of -- the \"peakedness\" of its distribution. A high kurtosis indicates -- that more of the sample's variance is due to infrequent severe -- deviations, rather than more frequent modest deviations. -- -- A sample's excess kurtosis is not defined if its 'variance' is -- zero. -- -- This function performs two passes over the sample, so is not subject -- to stream fusion. -- -- For samples containing many values very close to the mean, this -- function is subject to inaccuracy due to catastrophic cancellation. kurtosis :: (G.Vector v Double) => v Double -> Double kurtosis xs = c4 / (c2 * c2) - 3 where (c4 , c2) = centralMoments 4 2 xs {-# SPECIALIZE kurtosis :: U.Vector Double -> Double #-} {-# SPECIALIZE kurtosis :: V.Vector Double -> Double #-} -- $variance -- -- The variance&#8212;and hence the standard deviation&#8212;of a -- sample of fewer than two elements are both defined to be zero. -- $robust -- -- These functions use the compensated summation algorithm of Chan et -- al. for numerical robustness, but require two passes over the -- sample data as a result. -- -- Because of the need for two passes, these functions are /not/ -- subject to stream fusion. data V = V {-# UNPACK #-} !Double {-# UNPACK #-} !Double -- | Maximum likelihood estimate of a sample's variance. Also known -- as the population variance, where the denominator is /n/. variance :: (G.Vector v Double) => v Double -> Double variance samp | n > 1 = robustSumVar (mean samp) samp / fromIntegral n | otherwise = 0 where n = G.length samp {-# SPECIALIZE variance :: U.Vector Double -> Double #-} {-# SPECIALIZE variance :: V.Vector Double -> Double #-} -- | Unbiased estimate of a sample's variance. Also known as the -- sample variance, where the denominator is /n/-1. varianceUnbiased :: (G.Vector v Double) => v Double -> Double varianceUnbiased samp | n > 1 = robustSumVar (mean samp) samp / fromIntegral (n-1) | otherwise = 0 where n = G.length samp {-# SPECIALIZE varianceUnbiased :: U.Vector Double -> Double #-} {-# SPECIALIZE varianceUnbiased :: V.Vector Double -> Double #-} -- | Calculate mean and maximum likelihood estimate of variance. This -- function should be used if both mean and variance are required -- since it will calculate mean only once. meanVariance :: (G.Vector v Double) => v Double -> (Double,Double) meanVariance samp | n > 1 = (m, robustSumVar m samp / fromIntegral n) | otherwise = (m, 0) where n = G.length samp m = mean samp {-# SPECIALIZE meanVariance :: U.Vector Double -> (Double,Double) #-} {-# SPECIALIZE meanVariance :: V.Vector Double -> (Double,Double) #-} -- | Calculate mean and unbiased estimate of variance. This -- function should be used if both mean and variance are required -- since it will calculate mean only once. meanVarianceUnb :: (G.Vector v Double) => v Double -> (Double,Double) meanVarianceUnb samp | n > 1 = (m, robustSumVar m samp / fromIntegral (n-1)) | otherwise = (m, 0) where n = G.length samp m = mean samp {-# SPECIALIZE meanVarianceUnb :: U.Vector Double -> (Double,Double) #-} {-# SPECIALIZE meanVarianceUnb :: V.Vector Double -> (Double,Double) #-} -- | Standard deviation. This is simply the square root of the -- unbiased estimate of the variance. stdDev :: (G.Vector v Double) => v Double -> Double stdDev = sqrt . varianceUnbiased {-# SPECIALIZE stdDev :: U.Vector Double -> Double #-} {-# SPECIALIZE stdDev :: V.Vector Double -> Double #-} -- | Standard error of the mean. This is the standard deviation -- divided by the square root of the sample size. stdErrMean :: (G.Vector v Double) => v Double -> Double stdErrMean samp = stdDev samp / (sqrt . fromIntegral . G.length) samp {-# SPECIALIZE stdErrMean :: U.Vector Double -> Double #-} {-# SPECIALIZE stdErrMean :: V.Vector Double -> Double #-} robustSumVarWeighted :: (G.Vector v (Double,Double)) => v (Double,Double) -> V robustSumVarWeighted samp = G.foldl' go (V 0 0) samp where go (V s w) (x,xw) = V (s + xw*d*d) (w + xw) where d = x - m m = meanWeighted samp {-# INLINE robustSumVarWeighted #-} -- | Weighted variance. This is biased estimation. varianceWeighted :: (G.Vector v (Double,Double)) => v (Double,Double) -> Double varianceWeighted samp | G.length samp > 1 = fini $ robustSumVarWeighted samp | otherwise = 0 where fini (V s w) = s / w {-# SPECIALIZE varianceWeighted :: U.Vector (Double,Double) -> Double #-} {-# SPECIALIZE varianceWeighted :: V.Vector (Double,Double) -> Double #-} -- $cancellation -- -- The functions prefixed with the name @fast@ below perform a single -- pass over the sample data using Knuth's algorithm. They usually -- work well, but see below for caveats. These functions are subject -- to array fusion. -- -- /Note/: in cases where most sample data is close to the sample's -- mean, Knuth's algorithm gives inaccurate results due to -- catastrophic cancellation. fastVar :: (G.Vector v Double) => v Double -> T1 fastVar = G.foldl' go (T1 0 0 0) where go (T1 n m s) x = T1 n' m' s' where n' = n + 1 m' = m + d / fromIntegral n' s' = s + d * (x - m') d = x - m -- | Maximum likelihood estimate of a sample's variance. fastVariance :: (G.Vector v Double) => v Double -> Double fastVariance = fini . fastVar where fini (T1 n _m s) | n > 1 = s / fromIntegral n | otherwise = 0 {-# INLINE fastVariance #-} -- | Unbiased estimate of a sample's variance. fastVarianceUnbiased :: (G.Vector v Double) => v Double -> Double fastVarianceUnbiased = fini . fastVar where fini (T1 n _m s) | n > 1 = s / fromIntegral (n - 1) | otherwise = 0 {-# INLINE fastVarianceUnbiased #-} -- | Standard deviation. This is simply the square root of the -- maximum likelihood estimate of the variance. fastStdDev :: (G.Vector v Double) => v Double -> Double fastStdDev = sqrt . fastVariance {-# INLINE fastStdDev #-} -- | Covariance of sample of pairs. For empty sample it's set to -- zero covariance :: (G.Vector v (Double,Double), G.Vector v Double) => v (Double,Double) -> Double covariance xy | n == 0 = 0 | otherwise = mean $ G.zipWith (*) (G.map (\x -> x - muX) xs) (G.map (\y -> y - muY) ys) where n = G.length xy (xs,ys) = G.unzip xy muX = mean xs muY = mean ys {-# SPECIALIZE covariance :: U.Vector (Double,Double) -> Double #-} {-# SPECIALIZE covariance :: V.Vector (Double,Double) -> Double #-} -- | Correlation coefficient for sample of pairs. Also known as -- Pearson's correlation. For empty sample it's set to zero. correlation :: (G.Vector v (Double,Double), G.Vector v Double) => v (Double,Double) -> Double correlation xy | n == 0 = 0 | otherwise = cov / sqrt (varX * varY) where n = G.length xy (xs,ys) = G.unzip xy (muX,varX) = meanVariance xs (muY,varY) = meanVariance ys cov = mean $ G.zipWith (*) (G.map (\x -> x - muX) xs) (G.map (\y -> y - muY) ys) {-# SPECIALIZE correlation :: U.Vector (Double,Double) -> Double #-} {-# SPECIALIZE correlation :: V.Vector (Double,Double) -> Double #-} -- | Pair two samples. It's like 'G.zip' but requires that both -- samples have equal size. pair :: (G.Vector v a, G.Vector v b, G.Vector v (a,b)) => v a -> v b -> v (a,b) pair va vb | G.length va == G.length vb = G.zip va vb | otherwise = error "Statistics.Sample.pair: vector must have same length" {-# INLINE pair #-} ------------------------------------------------------------------------ -- Helper code. Monomorphic unpacked accumulators. -- (^) operator from Prelude is just slow. (^) :: Double -> Int -> Double x ^ 1 = x x ^ n = x * (x ^ (n-1)) {-# INLINE (^) #-} -- don't support polymorphism, as we can't get unboxed returns if we use it. data T = T {-# UNPACK #-}!Double {-# UNPACK #-}!Int data T1 = T1 {-# UNPACK #-}!Int {-# UNPACK #-}!Double {-# UNPACK #-}!Double {- Consider this core: with data T a = T !a !Int $wfold :: Double# -> Int# -> Int# -> (# Double, Int# #) and without, $wfold :: Double# -> Int# -> Int# -> (# Double#, Int# #) yielding to boxed returns and heap checks. -} -- $references -- -- * Chan, T. F.; Golub, G.H.; LeVeque, R.J. (1979) Updating formulae -- and a pairwise algorithm for computing sample -- variances. Technical Report STAN-CS-79-773, Department of -- Computer Science, Stanford -- University. <ftp://reports.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf> -- -- * Knuth, D.E. (1998) The art of computer programming, volume 2: -- seminumerical algorithms, 3rd ed., p. 232. -- -- * Welford, B.P. (1962) Note on a method for calculating corrected -- sums of squares and products. /Technometrics/ -- 4(3):419&#8211;420. <http://www.jstor.org/stable/1266577> -- -- * West, D.H.D. (1979) Updating mean and variance estimates: an -- improved method. /Communications of the ACM/ -- 22(9):532&#8211;535. <http://doi.acm.org/10.1145/359146.359153>
bos/statistics
Statistics/Sample.hs
bsd-2-clause
15,666
0
13
3,613
3,069
1,687
1,382
214
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[RnPat]{Renaming of patterns} Basically dependency analysis. Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In general, all of these functions return a renamed thing, and a set of free variables. -} {-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-} module RnPat (-- main entry points rnPat, rnPats, rnBindPat, rnPatAndThen, NameMaker, applyNameMaker, -- a utility for making names: localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names, -- sometimes we want to make top (qualified) names. isTopRecNameMaker, rnHsRecFields, HsRecFieldContext(..), rnHsRecUpdFields, -- CpsRn monad CpsRn, liftCps, -- Literals rnLit, rnOverLit, -- Pattern Error messages that are also used elsewhere checkTupSize, patSigErr ) where -- ENH: thin imports to only what is necessary for patterns import {-# SOURCE #-} RnExpr ( rnLExpr ) import {-# SOURCE #-} RnSplice ( rnSplicePat ) #include "HsVersions.h" import HsSyn import TcRnMonad import TcHsSyn ( hsOverLitName ) import RnEnv import RnTypes import PrelNames import TyCon ( tyConName ) import ConLike import Type ( TyThing(..) ) import Name import NameSet import RdrName import BasicTypes import Util import ListSetOps ( removeDups ) import Outputable import SrcLoc import Literal ( inCharRange ) import TysWiredIn ( nilDataCon ) import DataCon import qualified GHC.LanguageExtensions as LangExt import Control.Monad ( when, liftM, ap, unless ) import Data.Ratio {- ********************************************************* * * The CpsRn Monad * * ********************************************************* Note [CpsRn monad] ~~~~~~~~~~~~~~~~~~ The CpsRn monad uses continuation-passing style to support this style of programming: do { ... ; ns <- bindNames rs ; ...blah... } where rs::[RdrName], ns::[Name] The idea is that '...blah...' a) sees the bindings of ns b) returns the free variables it mentions so that bindNames can report unused ones In particular, mapM rnPatAndThen [p1, p2, p3] has a *left-to-right* scoping: it makes the binders in p1 scope over p2,p3. -} newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars)) -> RnM (r, FreeVars) } -- See Note [CpsRn monad] instance Functor CpsRn where fmap = liftM instance Applicative CpsRn where pure x = CpsRn (\k -> k x) (<*>) = ap instance Monad CpsRn where (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k)) runCps :: CpsRn a -> RnM (a, FreeVars) runCps (CpsRn m) = m (\r -> return (r, emptyFVs)) liftCps :: RnM a -> CpsRn a liftCps rn_thing = CpsRn (\k -> rn_thing >>= k) liftCpsFV :: RnM (a, FreeVars) -> CpsRn a liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing ; (r,fvs2) <- k v ; return (r, fvs1 `plusFV` fvs2) }) wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b) -- Set the location, and also wrap it around the value returned wrapSrcSpanCps fn (L loc a) = CpsRn (\k -> setSrcSpan loc $ unCpsRn (fn a) $ \v -> k (L loc v)) lookupConCps :: Located RdrName -> CpsRn (Located Name) lookupConCps con_rdr = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr ; (r, fvs) <- k con_name ; return (r, addOneFV fvs (unLoc con_name)) }) -- We add the constructor name to the free vars -- See Note [Patterns are uses] {- Note [Patterns are uses] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider module Foo( f, g ) where data T = T1 | T2 f T1 = True f T2 = False g _ = T1 Arguably we should report T2 as unused, even though it appears in a pattern, because it never occurs in a constructed position. See Trac #7336. However, implementing this in the face of pattern synonyms would be less straightforward, since given two pattern synonyms pattern P1 <- P2 pattern P2 <- () we need to observe the dependency between P1 and P2 so that type checking can be done in the correct order (just like for value bindings). Dependencies between bindings is analyzed in the renamer, where we don't know yet whether P2 is a constructor or a pattern synonym. So for now, we do report conid occurrences in patterns as uses. ********************************************************* * * Name makers * * ********************************************************* Externally abstract type of name makers, which is how you go from a RdrName to a Name -} data NameMaker = LamMk -- Lambdas Bool -- True <=> report unused bindings -- (even if True, the warning only comes out -- if -Wunused-matches is on) | LetMk -- Let bindings, incl top level -- Do *not* check for unused bindings TopLevelFlag MiniFixityEnv topRecNameMaker :: MiniFixityEnv -> NameMaker topRecNameMaker fix_env = LetMk TopLevel fix_env isTopRecNameMaker :: NameMaker -> Bool isTopRecNameMaker (LetMk TopLevel _) = True isTopRecNameMaker _ = False localRecNameMaker :: MiniFixityEnv -> NameMaker localRecNameMaker fix_env = LetMk NotTopLevel fix_env matchNameMaker :: HsMatchContext a -> NameMaker matchNameMaker ctxt = LamMk report_unused where -- Do not report unused names in interactive contexts -- i.e. when you type 'x <- e' at the GHCi prompt report_unused = case ctxt of StmtCtxt GhciStmtCtxt -> False -- also, don't warn in pattern quotes, as there -- is no RHS where the variables can be used! ThPatQuote -> False _ -> True rnHsSigCps :: LHsSigWcType RdrName -> CpsRn (LHsSigWcType Name) rnHsSigCps sig = CpsRn (rnHsSigWcTypeScoped PatCtx sig) newPatLName :: NameMaker -> Located RdrName -> CpsRn (Located Name) newPatLName name_maker rdr_name@(L loc _) = do { name <- newPatName name_maker rdr_name ; return (L loc name) } newPatName :: NameMaker -> Located RdrName -> CpsRn Name newPatName (LamMk report_unused) rdr_name = CpsRn (\ thing_inside -> do { name <- newLocalBndrRn rdr_name ; (res, fvs) <- bindLocalNames [name] (thing_inside name) ; when report_unused $ warnUnusedMatches [name] fvs ; return (res, name `delFV` fvs) }) newPatName (LetMk is_top fix_env) rdr_name = CpsRn (\ thing_inside -> do { name <- case is_top of NotTopLevel -> newLocalBndrRn rdr_name TopLevel -> newTopSrcBinder rdr_name ; bindLocalNames [name] $ -- Do *not* use bindLocalNameFV here -- See Note [View pattern usage] addLocalFixities fix_env [name] $ thing_inside name }) -- Note: the bindLocalNames is somewhat suspicious -- because it binds a top-level name as a local name. -- however, this binding seems to work, and it only exists for -- the duration of the patterns and the continuation; -- then the top-level name is added to the global env -- before going on to the RHSes (see RnSource.hs). {- Note [View pattern usage] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider let (r, (r -> x)) = x in ... Here the pattern binds 'r', and then uses it *only* in the view pattern. We want to "see" this use, and in let-bindings we collect all uses and report unused variables at the binding level. So we must use bindLocalNames here, *not* bindLocalNameFV. Trac #3943. Note: [Don't report shadowing for pattern synonyms] There is one special context where a pattern doesn't introduce any new binders - pattern synonym declarations. Therefore we don't check to see if pattern variables shadow existing identifiers as they are never bound to anything and have no scope. Without this check, there would be quite a cryptic warning that the `x` in the RHS of the pattern synonym declaration shadowed the top level `x`. ``` x :: () x = () pattern P x = Just x ``` See #12615 for some more examples. ********************************************************* * * External entry points * * ********************************************************* There are various entry points to renaming patterns, depending on (1) whether the names created should be top-level names or local names (2) whether the scope of the names is entirely given in a continuation (e.g., in a case or lambda, but not in a let or at the top-level, because of the way mutually recursive bindings are handled) (3) whether the a type signature in the pattern can bind lexically-scoped type variables (for unpacking existential type vars in data constructors) (4) whether we do duplicate and unused variable checking (5) whether there are fixity declarations associated with the names bound by the patterns that need to be brought into scope with them. Rather than burdening the clients of this module with all of these choices, we export the three points in this design space that we actually need: -} -- ----------- Entry point 1: rnPats ------------------- -- Binds local names; the scope of the bindings is entirely in the thing_inside -- * allows type sigs to bind type vars -- * local namemaker -- * unused and duplicate checking -- * no fixities rnPats :: HsMatchContext Name -- for error messages -> [LPat RdrName] -> ([LPat Name] -> RnM (a, FreeVars)) -> RnM (a, FreeVars) rnPats ctxt pats thing_inside = do { envs_before <- getRdrEnvs -- (1) rename the patterns, bringing into scope all of the term variables -- (2) then do the thing inside. ; unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do { -- Check for duplicated and shadowed names -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- Because we don't bind the vars all at once, we can't -- check incrementally for duplicates; -- Nor can we check incrementally for shadowing, else we'll -- complain *twice* about duplicates e.g. f (x,x) = ... -- -- See note [Don't report shadowing for pattern synonyms] ; unless (isPatSynCtxt ctxt) (addErrCtxt doc_pat $ checkDupAndShadowedNames envs_before $ collectPatsBinders pats') ; thing_inside pats' } } where doc_pat = text "In" <+> pprMatchContext ctxt rnPat :: HsMatchContext Name -- for error messages -> LPat RdrName -> (LPat Name -> RnM (a, FreeVars)) -> RnM (a, FreeVars) -- Variables bound by pattern do not -- appear in the result FreeVars rnPat ctxt pat thing_inside = rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat') applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name) applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatLName mk rdr) ; return n } -- ----------- Entry point 2: rnBindPat ------------------- -- Binds local names; in a recursive scope that involves other bound vars -- e.g let { (x, Just y) = e1; ... } in ... -- * does NOT allows type sig to bind type vars -- * local namemaker -- * no unused and duplicate checking -- * fixities might be coming in rnBindPat :: NameMaker -> LPat RdrName -> RnM (LPat Name, FreeVars) -- Returned FreeVars are the free variables of the pattern, -- of course excluding variables bound by this pattern rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat) {- ********************************************************* * * The main event * * ********************************************************* -} -- ----------- Entry point 3: rnLPatAndThen ------------------- -- General version: parametrized by how you make new names rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name] rnLPatsAndThen mk = mapM (rnLPatAndThen mk) -- Despite the map, the monad ensures that each pattern binds -- variables that may be mentioned in subsequent patterns in the list -------------------- -- The workhorse rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name) rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name) rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType) rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') } rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') } rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') } rnPatAndThen mk (VarPat (L l rdr)) = do { loc <- liftCps getSrcSpanM ; name <- newPatName mk (L loc rdr) ; return (VarPat (L l name)) } -- we need to bind pattern variables for view pattern expressions -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple) rnPatAndThen mk (SigPatIn pat sig) -- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is -- important to rename its type signature _before_ renaming the rest of the -- pattern, so that type variables are first bound by the _outermost_ pattern -- type signature they occur in. This keeps the type checker happy when -- pattern type signatures happen to be nested (#7827) -- -- f ((Just (x :: a) :: Maybe a) -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~^ `a' is first bound here -- ~~~~~~~~~~~~~~~^ the same `a' then used here = do { sig' <- rnHsSigCps sig ; pat' <- rnLPatAndThen mk pat ; return (SigPatIn pat' sig') } rnPatAndThen mk (LitPat lit) | HsString src s <- lit = do { ovlStr <- liftCps (xoptM LangExt.OverloadedStrings) ; if ovlStr then rnPatAndThen mk (mkNPat (noLoc (mkHsIsString src s placeHolderType)) Nothing) else normal_lit } | otherwise = normal_lit where normal_lit = do { liftCps (rnLit lit); return (LitPat lit) } rnPatAndThen _ (NPat (L l lit) mb_neg _eq _) = do { lit' <- liftCpsFV $ rnOverLit lit ; mb_neg' <- liftCpsFV $ case mb_neg of Nothing -> return (Nothing, emptyFVs) Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName ; return (Just neg, fvs) } ; eq' <- liftCpsFV $ lookupSyntaxName eqName ; return (NPat (L l lit') mb_neg' eq' placeHolderType) } rnPatAndThen mk (NPlusKPat rdr (L l lit) _ _ _ _) = do { new_name <- newPatName mk rdr ; lit' <- liftCpsFV $ rnOverLit lit ; minus <- liftCpsFV $ lookupSyntaxName minusName ; ge <- liftCpsFV $ lookupSyntaxName geName ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) (L l lit') lit' ge minus placeHolderType) } -- The Report says that n+k patterns must be in Integral rnPatAndThen mk (AsPat rdr pat) = do { new_name <- newPatLName mk rdr ; pat' <- rnLPatAndThen mk pat ; return (AsPat new_name pat') } rnPatAndThen mk p@(ViewPat expr pat _ty) = do { liftCps $ do { vp_flag <- xoptM LangExt.ViewPatterns ; checkErr vp_flag (badViewPat p) } -- Because of the way we're arranging the recursive calls, -- this will be in the right context ; expr' <- liftCpsFV $ rnLExpr expr ; pat' <- rnLPatAndThen mk pat -- Note: at this point the PreTcType in ty can only be a placeHolder -- ; return (ViewPat expr' pat' ty) } ; return (ViewPat expr' pat' placeHolderType) } rnPatAndThen mk (ConPatIn con stuff) -- rnConPatAndThen takes care of reconstructing the pattern -- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on. = case unLoc con == nameRdrName (dataConName nilDataCon) of True -> do { ol_flag <- liftCps $ xoptM LangExt.OverloadedLists ; if ol_flag then rnPatAndThen mk (ListPat [] placeHolderType Nothing) else rnConPatAndThen mk con stuff} False -> rnConPatAndThen mk con stuff rnPatAndThen mk (ListPat pats _ _) = do { opt_OverloadedLists <- liftCps $ xoptM LangExt.OverloadedLists ; pats' <- rnLPatsAndThen mk pats ; case opt_OverloadedLists of True -> do { (to_list_name,_) <- liftCps $ lookupSyntaxName toListName ; return (ListPat pats' placeHolderType (Just (placeHolderType, to_list_name)))} False -> return (ListPat pats' placeHolderType Nothing) } rnPatAndThen mk (PArrPat pats _) = do { pats' <- rnLPatsAndThen mk pats ; return (PArrPat pats' placeHolderType) } rnPatAndThen mk (TuplePat pats boxed _) = do { liftCps $ checkTupSize (length pats) ; pats' <- rnLPatsAndThen mk pats ; return (TuplePat pats' boxed []) } rnPatAndThen mk (SumPat pat alt arity _) = do { pat <- rnLPatAndThen mk pat ; return (SumPat pat alt arity PlaceHolder) } -- If a splice has been run already, just rename the result. rnPatAndThen mk (SplicePat (HsSpliced mfs (HsSplicedPat pat))) = SplicePat . HsSpliced mfs . HsSplicedPat <$> rnPatAndThen mk pat rnPatAndThen mk (SplicePat splice) = do { eith <- liftCpsFV $ rnSplicePat splice ; case eith of -- See Note [rnSplicePat] in RnSplice Left not_yet_renamed -> rnPatAndThen mk not_yet_renamed Right already_renamed -> return already_renamed } rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat) -------------------- rnConPatAndThen :: NameMaker -> Located RdrName -- the constructor -> HsConPatDetails RdrName -> CpsRn (Pat Name) rnConPatAndThen mk con (PrefixCon pats) = do { con' <- lookupConCps con ; pats' <- rnLPatsAndThen mk pats ; return (ConPatIn con' (PrefixCon pats')) } rnConPatAndThen mk con (InfixCon pat1 pat2) = do { con' <- lookupConCps con ; pat1' <- rnLPatAndThen mk pat1 ; pat2' <- rnLPatAndThen mk pat2 ; fixity <- liftCps $ lookupFixityRn (unLoc con') ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' } rnConPatAndThen mk con (RecCon rpats) = do { con' <- lookupConCps con ; rpats' <- rnHsRecPatsAndThen mk con' rpats ; return (ConPatIn con' (RecCon rpats')) } -------------------- rnHsRecPatsAndThen :: NameMaker -> Located Name -- Constructor -> HsRecFields RdrName (LPat RdrName) -> CpsRn (HsRecFields Name (LPat Name)) rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd }) = do { flds <- liftCpsFV $ rnHsRecFields (HsRecFieldPat con) mkVarPat hs_rec_fields ; flds' <- mapM rn_field (flds `zip` [1..]) ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) } where mkVarPat l n = VarPat (L l n) rn_field (L l fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n') (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldArg = arg' })) } -- Suppress unused-match reporting for fields introduced by ".." nested_mk Nothing mk _ = mk nested_mk (Just _) mk@(LetMk {}) _ = mk nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n)) {- ************************************************************************ * * Record fields * * ************************************************************************ -} data HsRecFieldContext = HsRecFieldCon Name | HsRecFieldPat Name | HsRecFieldUpd rnHsRecFields :: forall arg. HsRecFieldContext -> (SrcSpan -> RdrName -> arg) -- When punning, use this to build a new field -> HsRecFields RdrName (Located arg) -> RnM ([LHsRecField Name (Located arg)], FreeVars) -- This surprisingly complicated pass -- a) looks up the field name (possibly using disambiguation) -- b) fills in puns and dot-dot stuff -- When we we've finished, we've renamed the LHS, but not the RHS, -- of each x=e binding -- -- This is used for record construction and pattern-matching, but not updates. rnHsRecFields ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot }) = do { pun_ok <- xoptM LangExt.RecordPuns ; disambig_ok <- xoptM LangExt.DisambiguateRecordFields ; parent <- check_disambiguation disambig_ok mb_con ; flds1 <- mapM (rn_fld pun_ok parent) flds ; mapM_ (addErr . dupFieldErr ctxt) dup_flds ; dotdot_flds <- rn_dotdot dotdot mb_con flds1 ; let all_flds | null dotdot_flds = flds1 | otherwise = flds1 ++ dotdot_flds ; return (all_flds, mkFVs (getFieldIds all_flds)) } where mb_con = case ctxt of HsRecFieldCon con | not (isUnboundName con) -> Just con HsRecFieldPat con | not (isUnboundName con) -> Just con _ {- update or isUnboundName con -} -> Nothing -- The unbound name test is because if the constructor -- isn't in scope the constructor lookup will add an error -- add an error, but still return an unbound name. -- We don't want that to screw up the dot-dot fill-in stuff. doc = case mb_con of Nothing -> text "constructor field name" Just con -> text "field of constructor" <+> quotes (ppr con) rn_fld :: Bool -> Maybe Name -> LHsRecField RdrName (Located arg) -> RnM (LHsRecField Name (Located arg)) rn_fld pun_ok parent (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L ll lbl) _) , hsRecFieldArg = arg , hsRecPun = pun })) = do { sel <- setSrcSpan loc $ lookupRecFieldOcc parent doc lbl ; arg' <- if pun then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl) ; return (L loc (mk_arg loc arg_rdr)) } else return arg ; return (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L ll lbl) sel) , hsRecFieldArg = arg' , hsRecPun = pun })) } rn_dotdot :: Maybe Int -- See Note [DotDot fields] in HsPat -> Maybe Name -- The constructor (Nothing for an -- out of scope constructor) -> [LHsRecField Name (Located arg)] -- Explicit fields -> RnM [LHsRecField Name (Located arg)] -- Filled in .. fields rn_dotdot Nothing _mb_con _flds -- No ".." at all = return [] rn_dotdot (Just {}) Nothing _flds -- Constructor out of scope = return [] rn_dotdot (Just n) (Just con) flds -- ".." on record construction / pat match = ASSERT( n == length flds ) do { loc <- getSrcSpanM -- Rather approximate ; dd_flag <- xoptM LangExt.RecordWildCards ; checkErr dd_flag (needFlagDotDot ctxt) ; (rdr_env, lcl_env) <- getRdrEnvs ; con_fields <- lookupConstructorFields con ; when (null con_fields) (addErr (badDotDotCon con)) ; let present_flds = map (occNameFS . rdrNameOcc) $ getFieldLbls flds -- For constructor uses (but not patterns) -- the arg should be in scope locally; -- i.e. not top level or imported -- Eg. data R = R { x,y :: Int } -- f x = R { .. } -- Should expand to R {x=x}, not R{x=x,y=y} arg_in_scope lbl = mkVarUnqual lbl `elemLocalRdrEnv` lcl_env dot_dot_gres = [ (lbl, sel, head gres) | fl <- con_fields , let lbl = flLabel fl , let sel = flSelector fl , not (lbl `elem` present_flds) , let gres = lookupGRE_Field_Name rdr_env sel lbl , not (null gres) -- Check selector is in scope , case ctxt of HsRecFieldCon {} -> arg_in_scope lbl _other -> True ] ; addUsedGREs (map thdOf3 dot_dot_gres) ; return [ L loc (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L loc arg_rdr) sel) , hsRecFieldArg = L loc (mk_arg loc arg_rdr) , hsRecPun = False }) | (lbl, sel, _) <- dot_dot_gres , let arg_rdr = mkVarUnqual lbl ] } check_disambiguation :: Bool -> Maybe Name -> RnM (Maybe Name) -- When disambiguation is on, return name of parent tycon. check_disambiguation disambig_ok mb_con | disambig_ok, Just con <- mb_con = do { env <- getGlobalRdrEnv; return (find_tycon env con) } | otherwise = return Nothing find_tycon :: GlobalRdrEnv -> Name {- DataCon -} -> Maybe Name {- TyCon -} -- Return the parent *type constructor* of the data constructor -- (that is, the parent of the data constructor), -- or 'Nothing' if it is a pattern synonym or not in scope. -- That's the parent to use for looking up record fields. find_tycon env con_name | Just (AConLike (RealDataCon dc)) <- wiredInNameTyThing_maybe con_name = Just (tyConName (dataConTyCon dc)) -- Special case for [], which is built-in syntax -- and not in the GlobalRdrEnv (Trac #8448) | Just gre <- lookupGRE_Name env con_name = case gre_par gre of ParentIs p -> Just p _ -> Nothing -- Can happen if the con_name -- is for a pattern synonym | otherwise = Nothing -- Data constructor not lexically in scope at all -- See Note [Disambiguation and Template Haskell] dup_flds :: [[RdrName]] -- Each list represents a RdrName that occurred more than once -- (the list contains all occurrences) -- Each list in dup_fields is non-empty (_, dup_flds) = removeDups compare (getFieldLbls flds) {- Note [Disambiguation and Template Haskell] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (Trac #12130) module Foo where import M b = $(funny) module M(funny) where data T = MkT { x :: Int } funny :: Q Exp funny = [| MkT { x = 3 } |] When we splice, neither T nor MkT are lexically in scope, so find_tycon will fail. But there is no need for diambiguation anyway, so we just return Nothing -} rnHsRecUpdFields :: [LHsRecUpdField RdrName] -> RnM ([LHsRecUpdField Name], FreeVars) rnHsRecUpdFields flds = do { pun_ok <- xoptM LangExt.RecordPuns ; overload_ok <- xoptM LangExt.DuplicateRecordFields ; (flds1, fvss) <- mapAndUnzipM (rn_fld pun_ok overload_ok) flds ; mapM_ (addErr . dupFieldErr HsRecFieldUpd) dup_flds -- Check for an empty record update e {} -- NB: don't complain about e { .. }, because rn_dotdot has done that already ; when (null flds) $ addErr emptyUpdateErr ; return (flds1, plusFVs fvss) } where doc = text "constructor field name" rn_fld :: Bool -> Bool -> LHsRecUpdField RdrName -> RnM (LHsRecUpdField Name, FreeVars) rn_fld pun_ok overload_ok (L l (HsRecField { hsRecFieldLbl = L loc f , hsRecFieldArg = arg , hsRecPun = pun })) = do { let lbl = rdrNameAmbiguousFieldOcc f ; sel <- setSrcSpan loc $ -- Defer renaming of overloaded fields to the typechecker -- See Note [Disambiguating record fields] in TcExpr if overload_ok then do { mb <- lookupGlobalOccRn_overloaded overload_ok lbl ; case mb of Nothing -> do { addErr (unknownSubordinateErr doc lbl) ; return (Right []) } Just r -> return r } else fmap Left $ lookupGlobalOccRn lbl ; arg' <- if pun then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl) ; return (L loc (HsVar (L loc arg_rdr))) } else return arg ; (arg'', fvs) <- rnLExpr arg' ; let fvs' = case sel of Left sel_name -> fvs `addOneFV` sel_name Right [FieldOcc _ sel_name] -> fvs `addOneFV` sel_name Right _ -> fvs lbl' = case sel of Left sel_name -> L loc (Unambiguous (L loc lbl) sel_name) Right [FieldOcc lbl sel_name] -> L loc (Unambiguous lbl sel_name) Right _ -> L loc (Ambiguous (L loc lbl) PlaceHolder) ; return (L l (HsRecField { hsRecFieldLbl = lbl' , hsRecFieldArg = arg'' , hsRecPun = pun }), fvs') } dup_flds :: [[RdrName]] -- Each list represents a RdrName that occurred more than once -- (the list contains all occurrences) -- Each list in dup_fields is non-empty (_, dup_flds) = removeDups compare (getFieldUpdLbls flds) getFieldIds :: [LHsRecField Name arg] -> [Name] getFieldIds flds = map (unLoc . hsRecFieldSel . unLoc) flds getFieldLbls :: [LHsRecField id arg] -> [RdrName] getFieldLbls flds = map (unLoc . rdrNameFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds getFieldUpdLbls :: [LHsRecUpdField id] -> [RdrName] getFieldUpdLbls flds = map (rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds needFlagDotDot :: HsRecFieldContext -> SDoc needFlagDotDot ctxt = vcat [text "Illegal `..' in record" <+> pprRFC ctxt, text "Use RecordWildCards to permit this"] badDotDotCon :: Name -> SDoc badDotDotCon con = vcat [ text "Illegal `..' notation for constructor" <+> quotes (ppr con) , nest 2 (text "The constructor has no labelled fields") ] emptyUpdateErr :: SDoc emptyUpdateErr = text "Empty record update" badPun :: Located RdrName -> SDoc badPun fld = vcat [text "Illegal use of punning for field" <+> quotes (ppr fld), text "Use NamedFieldPuns to permit this"] dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc dupFieldErr ctxt dups = hsep [text "duplicate field name", quotes (ppr (head dups)), text "in record", pprRFC ctxt] pprRFC :: HsRecFieldContext -> SDoc pprRFC (HsRecFieldCon {}) = text "construction" pprRFC (HsRecFieldPat {}) = text "pattern" pprRFC (HsRecFieldUpd {}) = text "update" {- ************************************************************************ * * \subsubsection{Literals} * * ************************************************************************ When literals occur we have to make sure that the types and classes they involve are made available. -} rnLit :: HsLit -> RnM () rnLit (HsChar _ c) = checkErr (inCharRange c) (bogusCharError c) rnLit _ = return () -- Turn a Fractional-looking literal which happens to be an integer into an -- Integer-looking literal. generalizeOverLitVal :: OverLitVal -> OverLitVal generalizeOverLitVal (HsFractional (FL {fl_text=src,fl_value=val})) | denominator val == 1 = HsIntegral (SourceText src) (numerator val) generalizeOverLitVal lit = lit rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars) rnOverLit origLit = do { opt_NumDecimals <- xoptM LangExt.NumDecimals ; let { lit@(OverLit {ol_val=val}) | opt_NumDecimals = origLit {ol_val = generalizeOverLitVal (ol_val origLit)} | otherwise = origLit } ; let std_name = hsOverLitName val ; (SyntaxExpr { syn_expr = from_thing_name }, fvs) <- lookupSyntaxName std_name ; let rebindable = case from_thing_name of HsVar (L _ v) -> v /= std_name _ -> panic "rnOverLit" ; return (lit { ol_witness = from_thing_name , ol_rebindable = rebindable , ol_type = placeHolderType }, fvs) } {- ************************************************************************ * * \subsubsection{Errors} * * ************************************************************************ -} patSigErr :: Outputable a => a -> SDoc patSigErr ty = (text "Illegal signature in pattern:" <+> ppr ty) $$ nest 4 (text "Use ScopedTypeVariables to permit it") bogusCharError :: Char -> SDoc bogusCharError c = text "character literal out of range: '\\" <> char c <> char '\'' badViewPat :: Pat RdrName -> SDoc badViewPat pat = vcat [text "Illegal view pattern: " <+> ppr pat, text "Use ViewPatterns to enable view patterns"]
olsner/ghc
compiler/rename/RnPat.hs
bsd-3-clause
35,303
29
23
11,408
6,625
3,578
3,047
-1
-1
{-# LANGUAGE RebindableSyntax #-} {-# OPTIONS_GHC -fplugin Control.Supermonad.Plugin #-} {- ****************************************************************************** * H M T C * * * * Module: Name * * Purpose: Representation of names * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2006 - 2012 * * * ****************************************************************************** -} -- | Representation of names. Types, variables, procedures, operators ... module Name where import Control.Supermonad.Prelude type Name = String
jbracker/supermonad-plugin
examples/monad/hmtc/supermonad/Name.hs
bsd-3-clause
1,035
0
4
553
20
15
5
5
0
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for mutli-maps -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.Utils.MultiMap ( testUtils_MultiMap ) where import Prelude () import Ganeti.Prelude import qualified Data.Set as S import qualified Data.Map as M import Test.QuickCheck import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Ganeti.Utils.MultiMap as MM instance (Arbitrary k, Ord k, Arbitrary v, Ord v) => Arbitrary (MultiMap k v) where arbitrary = frequency [ (1, (multiMap . M.fromList) <$> listOf ((,) <$> arbitrary <*> (S.fromList <$> listOf arbitrary))) , (4, MM.insert <$> arbitrary <*> arbitrary <*> arbitrary) , (1, MM.fromList <$> listOf ((,) <$> arbitrary <*> arbitrary)) , (3, MM.delete <$> arbitrary <*> arbitrary <*> arbitrary) , (1, MM.deleteAll <$> arbitrary <*> arbitrary) ] -- | A data type for testing extensional equality. data Three = One | Two | Three deriving (Eq, Ord, Show, Enum, Bounded) instance Arbitrary Three where arbitrary = elements [minBound..maxBound] -- | Tests the extensional equality of multi-maps. prop_MultiMap_equality :: MultiMap Three Three -> MultiMap Three Three -> Property prop_MultiMap_equality m1 m2 = let testKey k = MM.lookup k m1 == MM.lookup k m2 in counterexample ("Extensional equality of '" ++ show m1 ++ "' and '" ++ show m2 ++ " doesn't match '=='.") $ all testKey [minBound..maxBound] ==? (m1 == m2) prop_MultiMap_serialisation :: MultiMap Int Int -> Property prop_MultiMap_serialisation = testSerialisation testSuite "Utils/MultiMap" [ 'prop_MultiMap_equality , 'prop_MultiMap_serialisation ]
leshchevds/ganeti
test/hs/Test/Ganeti/Utils/MultiMap.hs
bsd-2-clause
3,018
0
15
560
480
266
214
38
1
data X = A | B data Y = C | D data Z = E | F
itchyny/vim-haskell-indent
test/datatype/multiple.out.hs
mit
45
0
5
18
31
18
13
3
0
module HList ( H , repH , absH ) where type H a = [a] -> [a] {-# INLINE repH #-} repH :: [a] -> H a repH xs = (xs ++) {-# INLINE absH #-} absH :: H a -> [a] absH f = f [] -- -- Should be in a "List" module -- {-# RULES "++ []" forall xs . xs ++ [] = xs #-} -- {-# RULES "++ strict" (++) undefined = undefined #-} -- -- The "Algebra" for repH -- {-# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #-} -- {-# RULES "repH []" repH [] = id #-} -- {-# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs #-}
conal/hermit
examples/flatten/HList.hs
bsd-2-clause
627
0
6
226
96
59
37
11
1
-- Bug.hs {-# LANGUAGE ApplicativeDo #-} module Main where import Data.Functor.Identity f :: Identity () -> Identity [Int] -> Identity Int f i0 i1 = do _ <- i0 [x] <- i1 pure (x + 42) main :: IO () main = print $ f (Identity ()) (Identity [])
sdiehl/ghc
testsuite/tests/ado/T16628.hs
bsd-3-clause
258
0
9
64
119
61
58
10
1
{- (c) Galois, 2006 (c) University of Glasgow, 2007 -} {-# LANGUAGE NondecreasingIndentation #-} module Coverage (addTicksToBinds, hpcInitCode) where import Type import HsSyn import Module import Outputable import DynFlags import Control.Monad import SrcLoc import ErrUtils import NameSet hiding (FreeVars) import Name import Bag import CostCentre import CoreSyn import Id import VarSet import Data.List import FastString import HscTypes import TyCon import UniqSupply import BasicTypes import MonadUtils import Maybes import CLabel import Util import Data.Array import Data.Time import System.Directory import Trace.Hpc.Mix import Trace.Hpc.Util import BreakArray import Data.Map (Map) import qualified Data.Map as Map {- ************************************************************************ * * * The main function: addTicksToBinds * * ************************************************************************ -} addTicksToBinds :: DynFlags -> Module -> ModLocation -- ... off the current module -> NameSet -- Exported Ids. When we call addTicksToBinds, -- isExportedId doesn't work yet (the desugarer -- hasn't set it), so we have to work from this set. -> [TyCon] -- Type constructor in this module -> LHsBinds Id -> IO (LHsBinds Id, HpcInfo, ModBreaks) addTicksToBinds dflags mod mod_loc exports tyCons binds | let passes = coveragePasses dflags, not (null passes), Just orig_file <- ml_hs_file mod_loc = do if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, emptyModBreaks) else do us <- mkSplitUniqSupply 'C' -- for cost centres let orig_file2 = guessSourceFile binds orig_file tickPass tickish (binds,st) = let env = TTE { fileName = mkFastString orig_file2 , declPath = [] , tte_dflags = dflags , exports = exports , inlines = emptyVarSet , inScope = emptyVarSet , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),()) | tyCon <- tyCons ] , density = mkDensity tickish dflags , this_mod = mod , tickishType = tickish } (binds',_,st') = unTM (addTickLHsBinds binds) env st in (binds', st') initState = TT { tickBoxCount = 0 , mixEntries = [] , breakCount = 0 , breaks = [] , uniqSupply = us } (binds1,st) = foldr tickPass (binds, initState) passes let tickCount = tickBoxCount st hashNo <- writeMixEntries dflags mod tickCount (reverse $ mixEntries st) orig_file2 modBreaks <- mkModBreaks dflags (breakCount st) (reverse $ breaks st) when (dopt Opt_D_dump_ticked dflags) $ log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (pprLHsBinds binds1) return (binds1, HpcInfo tickCount hashNo, modBreaks) | otherwise = return (binds, emptyHpcInfo False, emptyModBreaks) guessSourceFile :: LHsBinds Id -> FilePath -> FilePath guessSourceFile binds orig_file = -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name _ -> orig_file mkModBreaks :: DynFlags -> Int -> [MixEntry_] -> IO ModBreaks mkModBreaks dflags count entries = do breakArray <- newBreakArray dflags $ length entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ] varsTicks = listArray (0,count-1) [ vars | (_,_,vars,_) <- entries ] declsTicks= listArray (0,count-1) [ decls | (_,decls,_,_) <- entries ] modBreaks = emptyModBreaks { modBreaks_flags = breakArray , modBreaks_locs = locsTicks , modBreaks_vars = varsTicks , modBreaks_decls = declsTicks } -- return modBreaks writeMixEntries :: DynFlags -> Module -> Int -> [MixEntry_] -> FilePath -> IO Int writeMixEntries dflags mod count entries filename | not (gopt Opt_Hpc dflags) = return 0 | otherwise = do let hpc_dir = hpcDir dflags mod_name = moduleNameString (moduleName mod) hpc_mod_dir | modulePackageKey mod == mainPackageKey = hpc_dir | otherwise = hpc_dir ++ "/" ++ packageKeyString (modulePackageKey mod) tabStop = 8 -- <tab> counts as a normal char in GHC's location ranges. createDirectoryIfMissing True hpc_mod_dir modTime <- getModificationUTCTime filename let entries' = [ (hpcPos, box) | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ] when (length entries' /= count) $ do panic "the number of .mix entries are inconsistent" let hashNo = mixHash filename modTime tabStop entries' mixCreate hpc_mod_dir mod_name $ Mix filename modTime (toHash hashNo) tabStop entries' return hashNo -- ----------------------------------------------------------------------------- -- TickDensity: where to insert ticks data TickDensity = TickForCoverage -- for Hpc | TickForBreakPoints -- for GHCi | TickAllFunctions -- for -prof-auto-all | TickTopFunctions -- for -prof-auto-top | TickExportedFunctions -- for -prof-auto-exported | TickCallSites -- for stack tracing deriving Eq mkDensity :: TickishType -> DynFlags -> TickDensity mkDensity tickish dflags = case tickish of HpcTicks -> TickForCoverage SourceNotes -> TickForCoverage Breakpoints -> TickForBreakPoints ProfNotes -> case profAuto dflags of ProfAutoAll -> TickAllFunctions ProfAutoTop -> TickTopFunctions ProfAutoExports -> TickExportedFunctions ProfAutoCalls -> TickCallSites _other -> panic "mkDensity" -- | Decide whether to add a tick to a binding or not. shouldTickBind :: TickDensity -> Bool -- top level? -> Bool -- exported? -> Bool -- simple pat bind? -> Bool -- INLINE pragma? -> Bool shouldTickBind density top_lev exported simple_pat inline = case density of TickForBreakPoints -> not simple_pat -- we never add breakpoints to simple pattern bindings -- (there's always a tick on the rhs anyway). TickAllFunctions -> not inline TickTopFunctions -> top_lev && not inline TickExportedFunctions -> exported && not inline TickForCoverage -> True TickCallSites -> False shouldTickPatBind :: TickDensity -> Bool -> Bool shouldTickPatBind density top_lev = case density of TickForBreakPoints -> False TickAllFunctions -> True TickTopFunctions -> top_lev TickExportedFunctions -> False TickForCoverage -> False TickCallSites -> False -- ----------------------------------------------------------------------------- -- Adding ticks to bindings addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id) addTickLHsBinds = mapBagM addTickLHsBind addTickLHsBind :: LHsBind Id -> TM (LHsBind Id) addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds, abs_exports = abs_exports })) = do withEnv add_exports $ do withEnv add_inlines $ do binds' <- addTickLHsBinds binds return $ L pos $ bind { abs_binds = binds' } where -- in AbsBinds, the Id on each binding is not the actual top-level -- Id that we are defining, they are related by the abs_exports -- field of AbsBinds. So if we're doing TickExportedFunctions we need -- to add the local Ids to the set of exported Names so that we know to -- tick the right bindings. add_exports env = env{ exports = exports env `extendNameSetList` [ idName mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , idName pid `elemNameSet` (exports env) ] } add_inlines env = env{ inlines = inlines env `extendVarSetList` [ mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , isAnyInlinePragma (idInlinePragma pid) ] } addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do let name = getOccString id decl_path <- getPathEntry density <- getDensity inline_ids <- liftM inlines getEnv let inline = isAnyInlinePragma (idInlinePragma id) || id `elemVarSet` inline_ids -- See Note [inline sccs] tickish <- tickishType `liftM` getEnv if inline && tickish == ProfNotes then return (L pos funBind) else do (fvs, mg@(MG { mg_alts = matches' })) <- getFreeVars $ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) blackListed <- isBlackListed pos exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions -- We don't want redundant ticks on simple pattern bindings -- We don't want to tick non-exported bindings in TickExportedFunctions let simple = isSimplePatBind funBind toplev = null decl_path exported = idName id `elemNameSet` exported_names tick <- if not blackListed && shouldTickBind density toplev exported simple inline then bindTick density name pos fvs else return Nothing let mbCons = maybe Prelude.id (:) return $ L pos $ funBind { fun_matches = mg { mg_alts = matches' } , fun_tick = tick `mbCons` fun_tick funBind } where -- a binding is a simple pattern binding if it is a funbind with zero patterns isSimplePatBind :: HsBind a -> Bool isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0 -- TODO: Revisit this addTickLHsBind (L pos (pat@(PatBind { pat_lhs = lhs, pat_rhs = rhs }))) = do let name = "(...)" (fvs, rhs') <- getFreeVars $ addPathEntry name $ addTickGRHSs False False rhs let pat' = pat { pat_rhs = rhs'} -- Should create ticks here? density <- getDensity decl_path <- getPathEntry let top_lev = null decl_path if not (shouldTickPatBind density top_lev) then return (L pos pat') else do -- Allocate the ticks rhs_tick <- bindTick density name pos fvs let patvars = map getOccString (collectPatBinders lhs) patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars -- Add to pattern let mbCons = maybe id (:) rhs_ticks = rhs_tick `mbCons` fst (pat_ticks pat') patvar_tickss = zipWith mbCons patvar_ticks (snd (pat_ticks pat') ++ repeat []) return $ L pos $ pat' { pat_ticks = (rhs_ticks, patvar_tickss) } -- Only internal stuff, not from source, uses VarBind, so we ignore it. addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) bindTick density name pos fvs = do decl_path <- getPathEntry let toplev = null decl_path count_entries = toplev || density == TickAllFunctions top_only = density /= TickAllFunctions box_label = if toplev then TopLevelBox [name] else LocalBox (decl_path ++ [name]) -- allocATickBox box_label count_entries top_only pos fvs -- Note [inline sccs] -- -- It should be reasonable to add ticks to INLINE functions; however -- currently this tickles a bug later on because the SCCfinal pass -- does not look inside unfoldings to find CostCentres. It would be -- difficult to fix that, because SCCfinal currently works on STG and -- not Core (and since it also generates CostCentres for CAFs, -- changing this would be difficult too). -- -- Another reason not to add ticks to INLINE functions is that this -- sometimes handy for avoiding adding a tick to a particular function -- (see #6131) -- -- So for now we do not add any ticks to INLINE functions at all. -- ----------------------------------------------------------------------------- -- Decorate an LHsExpr with ticks -- selectively add ticks to interesting expressions addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExpr e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | isGoodBreakExpr e0 -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding. -- We always consider these to be breakpoints, unless the expression is a 'let' -- (because the body will definitely have a tick somewhere). ToDo: perhaps -- we should treat 'case' and 'if' the same way? addTickLHsExprRHS :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprRHS e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context: -- let binds in [], ( [] ) -- we never tick these if we're doing HPC, but otherwise -- we treat it like an ordinary expression. addTickLHsExprEvalInner :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprEvalInner e = do d <- getDensity case d of TickForCoverage -> addTickLHsExprNever e _otherwise -> addTickLHsExpr e -- | A let body is treated differently from addTickLHsExprEvalInner -- above with TickForBreakPoints, because for breakpoints we always -- want to tick the body, even if it is not a redex. See test -- break012. This gives the user the opportunity to inspect the -- values of the let-bound variables. addTickLHsExprLetBody :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprLetBody e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick, -- because the scope of this tick is completely subsumed by -- another. addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprNever (L pos e0) = do e1 <- addTickHsExpr e0 return $ L pos e1 -- general heuristic: expressions which do not denote values are good break points isGoodBreakExpr :: HsExpr Id -> Bool isGoodBreakExpr (HsApp {}) = True isGoodBreakExpr (OpApp {}) = True isGoodBreakExpr (NegApp {}) = True isGoodBreakExpr (HsIf {}) = True isGoodBreakExpr (HsMultiIf {}) = True isGoodBreakExpr (HsCase {}) = True isGoodBreakExpr (RecordCon {}) = True isGoodBreakExpr (RecordUpd {}) = True isGoodBreakExpr (ArithSeq {}) = True isGoodBreakExpr (PArrSeq {}) = True isGoodBreakExpr _other = False isCallSite :: HsExpr Id -> Bool isCallSite HsApp{} = True isCallSite OpApp{} = True isCallSite _ = False addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage (allocBinTickBox boxLabel pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) -- ----------------------------------------------------------------------------- -- Decoarate an HsExpr with ticks addTickHsExpr :: HsExpr Id -> TM (HsExpr Id) addTickHsExpr e@(HsVar id) = do freeVar id; return e addTickHsExpr e@(HsIPVar _) = return e addTickHsExpr e@(HsOverLit _) = return e addTickHsExpr e@(HsLit _) = return e addTickHsExpr (HsLam matchgroup) = liftM HsLam (addTickMatchGroup True matchgroup) addTickHsExpr (HsLamCase ty mgs) = liftM (HsLamCase ty) (addTickMatchGroup True mgs) addTickHsExpr (HsApp e1 e2) = liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (OpApp e1 e2 fix e3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsExprNever e2) (return fix) (addTickLHsExpr e3) addTickHsExpr (NegApp e neg) = liftM2 NegApp (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan neg) addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprEvalInner e) addTickHsExpr (SectionL e1 e2) = liftM2 SectionL (addTickLHsExpr e1) (addTickLHsExprNever e2) addTickHsExpr (SectionR e1 e2) = liftM2 SectionR (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (ExplicitTuple es boxity) = liftM2 ExplicitTuple (mapM addTickTupArg es) (return boxity) addTickHsExpr (HsCase e mgs) = liftM2 HsCase (addTickLHsExpr e) -- not an EvalInner; e might not necessarily -- be evaluated. (addTickMatchGroup False mgs) addTickHsExpr (HsIf cnd e1 e2 e3) = liftM3 (HsIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsExprOptAlt True e2) (addTickLHsExprOptAlt True e3) addTickHsExpr (HsMultiIf ty alts) = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' } addTickHsExpr (HsLet binds e) = bindLocals (collectLocalBinders binds) $ liftM2 HsLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo cxt stmts srcloc) = do { (stmts', _) <- addTickLStmts' forQual stmts (return ()) ; return (HsDo cxt stmts' srcloc) } where forQual = case cxt of ListComp -> Just $ BinBox QualBinBox _ -> Nothing addTickHsExpr (ExplicitList ty wit es) = liftM3 ExplicitList (return ty) (addTickWit wit) (mapM (addTickLHsExpr) es) where addTickWit Nothing = return Nothing addTickWit (Just fln) = do fln' <- addTickHsExpr fln return (Just fln') addTickHsExpr (ExplicitPArr ty es) = liftM2 ExplicitPArr (return ty) (mapM (addTickLHsExpr) es) addTickHsExpr (HsStatic e) = HsStatic <$> addTickLHsExpr e addTickHsExpr (RecordCon id ty rec_binds) = liftM3 RecordCon (return id) (return ty) (addTickHsRecordBinds rec_binds) addTickHsExpr (RecordUpd e rec_binds cons tys1 tys2) = liftM5 RecordUpd (addTickLHsExpr e) (addTickHsRecordBinds rec_binds) (return cons) (return tys1) (return tys2) addTickHsExpr (ExprWithTySigOut e ty) = liftM2 ExprWithTySigOut (addTickLHsExprNever e) -- No need to tick the inner expression -- for expressions with signatures (return ty) addTickHsExpr (ArithSeq ty wit arith_seq) = liftM3 ArithSeq (return ty) (addTickWit wit) (addTickArithSeqInfo arith_seq) where addTickWit Nothing = return Nothing addTickWit (Just fl) = do fl' <- addTickHsExpr fl return (Just fl') -- We might encounter existing ticks (multiple Coverage passes) addTickHsExpr (HsTick t e) = liftM (HsTick t) (addTickLHsExprNever e) addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e) addTickHsExpr (HsTickPragma _ _ (L pos e0)) = do e2 <- allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 return $ unLoc e2 addTickHsExpr (PArrSeq ty arith_seq) = liftM2 PArrSeq (return ty) (addTickArithSeqInfo arith_seq) addTickHsExpr (HsSCC src nm e) = liftM3 HsSCC (return src) (return nm) (addTickLHsExpr e) addTickHsExpr (HsCoreAnn src nm e) = liftM3 HsCoreAnn (return src) (return nm) (addTickLHsExpr e) addTickHsExpr e@(HsBracket {}) = return e addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e addTickHsExpr (HsProc pat cmdtop) = liftM2 HsProc (addTickLPat pat) (liftL (addTickHsCmdTop) cmdtop) addTickHsExpr (HsWrap w e) = liftM2 HsWrap (return w) (addTickHsExpr e) -- explicitly no tick on inside addTickHsExpr e@(HsType _) = return e addTickHsExpr (HsUnboundVar {}) = panic "addTickHsExpr.HsUnboundVar" -- Others dhould never happen in expression content. addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e) addTickTupArg :: LHsTupArg Id -> TM (LHsTupArg Id) addTickTupArg (L l (Present e)) = do { e' <- addTickLHsExpr e ; return (L l (Present e')) } addTickTupArg (L l (Missing ty)) = return (L l (Missing ty)) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup Id (LHsExpr Id) -> TM (MatchGroup Id (LHsExpr Id)) addTickMatchGroup is_lam mg@(MG { mg_alts = matches }) = do let isOneOfMany = matchesOneOfMany matches matches' <- mapM (liftL (addTickMatch isOneOfMany is_lam)) matches return $ mg { mg_alts = matches' } addTickMatch :: Bool -> Bool -> Match Id (LHsExpr Id) -> TM (Match Id (LHsExpr Id)) addTickMatch isOneOfMany isLambda (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs return $ Match mf pats opSig gRHSs' addTickGRHSs :: Bool -> Bool -> GRHSs Id (LHsExpr Id) -> TM (GRHSs Id (LHsExpr Id)) addTickGRHSs isOneOfMany isLambda (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickGRHS :: Bool -> Bool -> GRHS Id (LHsExpr Id) -> TM (GRHS Id (LHsExpr Id)) addTickGRHS isOneOfMany isLambda (GRHS stmts expr) = do (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickGRHSBody isOneOfMany isLambda expr) return $ GRHS stmts' expr' addTickGRHSBody :: Bool -> Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickGRHSBody isOneOfMany isLambda expr@(L pos e0) = do d <- getDensity case d of TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $ allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM [ExprLStmt Id] addTickLStmts isGuard stmts = do (stmts, _) <- addTickLStmts' isGuard stmts (return ()) return stmts addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM a -> TM ([ExprLStmt Id], a) addTickLStmts' isGuard lstmts res = bindLocals (collectLStmtsBinders lstmts) $ do { lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts ; a <- res ; return (lstmts', a) } addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id (LHsExpr Id) -> TM (Stmt Id (LHsExpr Id)) addTickStmt _isGuard (LastStmt e ret) = do liftM2 LastStmt (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan ret) addTickStmt _isGuard (BindStmt pat e bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsExprRHS e) (addTickSyntaxExpr hpcSrcSpan bind) (addTickSyntaxExpr hpcSrcSpan fail) addTickStmt isGuard (BodyStmt e bind' guard' ty) = do liftM4 BodyStmt (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickStmt _isGuard (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt pairs mzipExpr bindExpr) = do liftM3 ParStmt (mapM (addTickStmtAndBinders isGuard) pairs) (addTickSyntaxExpr hpcSrcSpan mzipExpr) (addTickSyntaxExpr hpcSrcSpan bindExpr) addTickStmt isGuard stmt@(TransStmt { trS_stmts = stmts , trS_by = by, trS_using = using , trS_ret = returnExpr, trS_bind = bindExpr , trS_fmap = liftMExpr }) = do t_s <- addTickLStmts isGuard stmts t_y <- fmapMaybeM addTickLHsExprRHS by t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr t_m <- addTickSyntaxExpr hpcSrcSpan liftMExpr return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {}) = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e | otherwise = addTickLHsExprRHS e addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ParStmtBlock Id Id -> TM (ParStmtBlock Id Id) addTickStmtAndBinders isGuard (ParStmtBlock stmts ids returnExpr) = liftM3 ParStmtBlock (addTickLStmts isGuard stmts) (return ids) (addTickSyntaxExpr hpcSrcSpan returnExpr) addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id) addTickHsLocalBinds (HsValBinds binds) = liftM HsValBinds (addTickHsValBinds binds) addTickHsLocalBinds (HsIPBinds binds) = liftM HsIPBinds (addTickHsIPBinds binds) addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b) addTickHsValBinds (ValBindsOut binds sigs) = liftM2 ValBindsOut (mapM (\ (rec,binds') -> liftM2 (,) (return rec) (addTickLHsBinds binds')) binds) (return sigs) addTickHsValBinds _ = panic "addTickHsValBinds" addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id) addTickHsIPBinds (IPBinds ipbinds dictbinds) = liftM2 IPBinds (mapM (liftL (addTickIPBind)) ipbinds) (return dictbinds) addTickIPBind :: IPBind Id -> TM (IPBind Id) addTickIPBind (IPBind nm e) = liftM2 IPBind (return nm) (addTickLHsExpr e) -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id) addTickSyntaxExpr pos x = do L _ x' <- addTickLHsExpr (L pos x) return $ x' -- we do not walk into patterns. addTickLPat :: LPat Id -> TM (LPat Id) addTickLPat pat = return pat addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id) addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) = liftM4 HsCmdTop (addTickLHsCmd cmd) (return tys) (return ty) (return syntaxtable) addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id) addTickLHsCmd (L pos c0) = do c1 <- addTickHsCmd c0 return $ L pos c1 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id) addTickHsCmd (HsCmdLam matchgroup) = liftM HsCmdLam (addTickCmdMatchGroup matchgroup) addTickHsCmd (HsCmdApp c e) = liftM2 HsCmdApp (addTickLHsCmd c) (addTickLHsExpr e) {- addTickHsCmd (OpApp e1 c2 fix c3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsCmd c2) (return fix) (addTickLHsCmd c3) -} addTickHsCmd (HsCmdPar e) = liftM HsCmdPar (addTickLHsCmd e) addTickHsCmd (HsCmdCase e mgs) = liftM2 HsCmdCase (addTickLHsExpr e) (addTickCmdMatchGroup mgs) addTickHsCmd (HsCmdIf cnd e1 c2 c3) = liftM3 (HsCmdIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3) addTickHsCmd (HsCmdLet binds c) = bindLocals (collectLocalBinders binds) $ liftM2 HsCmdLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo stmts srcloc) = do { (stmts', _) <- addTickLCmdStmts' stmts (return ()) ; return (HsCmdDo stmts' srcloc) } addTickHsCmd (HsCmdArrApp e1 e2 ty1 arr_ty lr) = liftM5 HsCmdArrApp (addTickLHsExpr e1) (addTickLHsExpr e2) (return ty1) (return arr_ty) (return lr) addTickHsCmd (HsCmdArrForm e fix cmdtop) = liftM3 HsCmdArrForm (addTickLHsExpr e) (return fix) (mapM (liftL (addTickHsCmdTop)) cmdtop) addTickHsCmd (HsCmdCast co cmd) = liftM2 HsCmdCast (return co) (addTickHsCmd cmd) -- Others should never happen in a command context. --addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e) addTickCmdMatchGroup :: MatchGroup Id (LHsCmd Id) -> TM (MatchGroup Id (LHsCmd Id)) addTickCmdMatchGroup mg@(MG { mg_alts = matches }) = do matches' <- mapM (liftL addTickCmdMatch) matches return $ mg { mg_alts = matches' } addTickCmdMatch :: Match Id (LHsCmd Id) -> TM (Match Id (LHsCmd Id)) addTickCmdMatch (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickCmdGRHSs gRHSs return $ Match mf pats opSig gRHSs' addTickCmdGRHSs :: GRHSs Id (LHsCmd Id) -> TM (GRHSs Id (LHsCmd Id)) addTickCmdGRHSs (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickCmdGRHS :: GRHS Id (LHsCmd Id) -> TM (GRHS Id (LHsCmd Id)) -- The *guards* are *not* Cmds, although the body is -- C.f. addTickGRHS for the BinBox stuff addTickCmdGRHS (GRHS stmts cmd) = do { (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickLHsCmd cmd) ; return $ GRHS stmts' expr' } addTickLCmdStmts :: [LStmt Id (LHsCmd Id)] -> TM [LStmt Id (LHsCmd Id)] addTickLCmdStmts stmts = do (stmts, _) <- addTickLCmdStmts' stmts (return ()) return stmts addTickLCmdStmts' :: [LStmt Id (LHsCmd Id)] -> TM a -> TM ([LStmt Id (LHsCmd Id)], a) addTickLCmdStmts' lstmts res = bindLocals binders $ do lstmts' <- mapM (liftL addTickCmdStmt) lstmts a <- res return (lstmts', a) where binders = collectLStmtsBinders lstmts addTickCmdStmt :: Stmt Id (LHsCmd Id) -> TM (Stmt Id (LHsCmd Id)) addTickCmdStmt (BindStmt pat c bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsCmd c) (return bind) (return fail) addTickCmdStmt (LastStmt c ret) = do liftM2 LastStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan ret) addTickCmdStmt (BodyStmt c bind' guard' ty) = do liftM4 BodyStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickCmdStmt (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {}) = do { stmts' <- addTickLCmdStmts (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } -- Others should never happen in a command context. addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt) addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id) addTickHsRecordBinds (HsRecFields fields dd) = do { fields' <- mapM process fields ; return (HsRecFields fields' dd) } where process (L l (HsRecField ids expr doc)) = do { expr' <- addTickLHsExpr expr ; return (L l (HsRecField ids expr' doc)) } addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id) addTickArithSeqInfo (From e1) = liftM From (addTickLHsExpr e1) addTickArithSeqInfo (FromThen e1 e2) = liftM2 FromThen (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromTo e1 e2) = liftM2 FromTo (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromThenTo e1 e2 e3) = liftM3 FromThenTo (addTickLHsExpr e1) (addTickLHsExpr e2) (addTickLHsExpr e3) liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a) liftL f (L loc a) = do a' <- f a return $ L loc a' data TickTransState = TT { tickBoxCount:: Int , mixEntries :: [MixEntry_] , breakCount :: Int , breaks :: [MixEntry_] , uniqSupply :: UniqSupply } data TickTransEnv = TTE { fileName :: FastString , density :: TickDensity , tte_dflags :: DynFlags , exports :: NameSet , inlines :: VarSet , declPath :: [String] , inScope :: VarSet , blackList :: Map SrcSpan () , this_mod :: Module , tickishType :: TickishType } -- deriving Show data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (hscTarget dflags == HscInterpreted) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (gopt Opt_SccProfilingOn dflags && profAuto dflags /= NoProfAuto) ProfNotes $ ifa (gopt Opt_Debug dflags) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs -- | Tickishs that only make sense when their source code location -- refers to the current file. This might not always be true due to -- LINE pragmas in the code - which would confuse at least HPC. tickSameFileOnly :: TickishType -> Bool tickSameFileOnly HpcTicks = True tickSameFileOnly _other = False type FreeVars = OccEnv Id noFVs :: FreeVars noFVs = emptyOccEnv -- Note [freevars] -- For breakpoints we want to collect the free variables of an -- expression for pinning on the HsTick. We don't want to collect -- *all* free variables though: in particular there's no point pinning -- on free variables that are will otherwise be in scope at the GHCi -- prompt, which means all top-level bindings. Unfortunately detecting -- top-level bindings isn't easy (collectHsBindsBinders on the top-level -- bindings doesn't do it), so we keep track of a set of "in-scope" -- variables in addition to the free variables, and the former is used -- to filter additions to the latter. This gives us complete control -- over what free variables we track. data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) } -- a combination of a state monad (TickTransState) and a writer -- monad (FreeVars). instance Functor TM where fmap = liftM instance Applicative TM where pure = return (<*>) = ap instance Monad TM where return a = TM $ \ _env st -> (a,noFVs,st) (TM m) >>= k = TM $ \ env st -> case m env st of (r1,fv1,st1) -> case unTM (k r1) env st1 of (r2,fv2,st2) -> (r2, fv1 `plusOccEnv` fv2, st2) instance HasDynFlags TM where getDynFlags = TM $ \ env st -> (tte_dflags env, noFVs, st) instance MonadUnique TM where getUniqueSupplyM = TM $ \_ st -> (uniqSupply st, noFVs, st) getUniqueM = TM $ \_ st -> let (u, us') = takeUniqFromSupply (uniqSupply st) in (u, noFVs, st { uniqSupply = us' }) getState :: TM TickTransState getState = TM $ \ _ st -> (st, noFVs, st) setState :: (TickTransState -> TickTransState) -> TM () setState f = TM $ \ _ st -> ((), noFVs, f st) getEnv :: TM TickTransEnv getEnv = TM $ \ env st -> (env, noFVs, st) withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a withEnv f (TM m) = TM $ \ env st -> case m (f env) st of (a, fvs, st') -> (a, fvs, st') getDensity :: TM TickDensity getDensity = TM $ \env st -> (density env, noFVs, st) ifDensity :: TickDensity -> TM a -> TM a -> TM a ifDensity d th el = do d0 <- getDensity; if d == d0 then th else el getFreeVars :: TM a -> TM (FreeVars, a) getFreeVars (TM m) = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st') freeVar :: Id -> TM () freeVar id = TM $ \ env st -> if id `elemVarSet` inScope env then ((), unitOccEnv (nameOccName (idName id)) id, st) else ((), noFVs, st) addPathEntry :: String -> TM a -> TM a addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] }) getPathEntry :: TM [String] getPathEntry = declPath `liftM` getEnv getFileName :: TM FastString getFileName = fileName `liftM` getEnv isGoodSrcSpan' :: SrcSpan -> Bool isGoodSrcSpan' pos@(RealSrcSpan _) = srcSpanStart pos /= srcSpanEnd pos isGoodSrcSpan' (UnhelpfulSpan _) = False isGoodTickSrcSpan :: SrcSpan -> TM Bool isGoodTickSrcSpan pos = do file_name <- getFileName tickish <- tickishType `liftM` getEnv let need_same_file = tickSameFileOnly tickish same_file = Just file_name == srcSpanFileName_maybe pos return (isGoodSrcSpan' pos && (not need_same_file || same_file)) ifGoodTickSrcSpan :: SrcSpan -> TM a -> TM a -> TM a ifGoodTickSrcSpan pos then_code else_code = do good <- isGoodTickSrcSpan pos if good then then_code else else_code bindLocals :: [Id] -> TM a -> TM a bindLocals new_ids (TM m) = TM $ \ env st -> case m env{ inScope = inScope env `extendVarSetList` new_ids } st of (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st') where occs = [ nameOccName (idName id) | id <- new_ids ] isBlackListed :: SrcSpan -> TM Bool isBlackListed pos = TM $ \ env st -> case Map.lookup pos (blackList env) of Nothing -> (False,noFVs,st) Just () -> (True,noFVs,st) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocTickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocTickBox boxLabel countEntries topOnly pos m = ifGoodTickSrcSpan pos (do (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env) return (L pos (HsTick tickish (L pos e))) ) (do e <- m return (L pos e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let mydecl_path = case boxLabel of TopLevelBox x -> x LocalBox xs -> xs _ -> panic "allocATickBox" tickish <- mkTickish boxLabel countEntries topOnly pos fvs mydecl_path return (Just tickish) ) (return Nothing) mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String] -> TM (Tickish Id) mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnLiftedType . idType) $ occEnvElts fvs -- unlifted types cause two problems here: -- * we can't bind them at the GHCi prompt -- (bindLocalsAtBreakpoint already fliters them out), -- * the simplifier might try to substitute a literal for -- the Id, and we can't handle that. me = (pos, decl_path, map (nameOccName.idName) ids, boxLabel) cc_name | topOnly = head decl_path | otherwise = concat (intersperse "." decl_path) dflags <- getDynFlags env <- getEnv case tickishType env of HpcTicks -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me : mixEntries st } return $ HpcTick (this_mod env) c ProfNotes -> do ccUnique <- getUniqueM let cc = mkUserCC (mkFastString cc_name) (this_mod env) pos ccUnique count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} Breakpoints -> do c <- liftM breakCount getState setState $ \st -> st { breakCount = c + 1 , breaks = me:breaks st } return $ Breakpoint c ids SourceNotes | RealSrcSpan pos' <- pos -> return $ SourceNote pos' cc_name _otherwise -> panic "mkTickish: bad source span!" allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of HpcTicks -> do e <- liftM (L pos) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e) _other -> allocTickBox (ExpBox False) False False pos m mkBinTickBoxHpc :: (Bool -> BoxLabel) -> SrcSpan -> LHsExpr Id -> TM (LHsExpr Id) mkBinTickBoxHpc boxLabel pos e = TM $ \ env st -> let meT = (pos,declPath env, [],boxLabel True) meF = (pos,declPath env, [],boxLabel False) meE = (pos,declPath env, [],ExpBox False) c = tickBoxCount st mes = mixEntries st in ( L pos $ HsTick (HpcTick (this_mod env) c) $ L pos $ HsBinTick (c+1) (c+2) e -- notice that F and T are reversed, -- because we are building the list in -- reverse... , noFVs , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes} ) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s) | isGoodSrcSpan' pos = toHpcPos (srcSpanStartLine s, srcSpanStartCol s, srcSpanEndLine s, srcSpanEndCol s - 1) -- the end column of a SrcSpan is one -- greater than the last column of the -- span (see SrcLoc), whereas HPC -- expects to the column range to be -- inclusive, hence we subtract one above. mkHpcPos _ = panic "bad source span; expected such spans to be filtered out" hpcSrcSpan :: SrcSpan hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals") matchesOneOfMany :: [LMatch Id body] -> Bool matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1 where matchCount (L _ (Match _ _pats _ty (GRHSs grhss _binds))) = length grhss type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel) -- For the hash value, we hash everything: the file name, -- the timestamp of the original source file, the tab stop, -- and the mix entries. We cheat, and hash the show'd string. -- This hash only has to be hashed at Mix creation time, -- and is for sanity checking only. mixHash :: FilePath -> UTCTime -> Int -> [MixEntry] -> Int mixHash file tm tabstop entries = fromIntegral $ hashString (show $ Mix file tm 0 tabstop entries) {- ************************************************************************ * * * initialisation * * ************************************************************************ Each module compiled with -fhpc declares an initialisation function of the form `hpc_init_<module>()`, which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) {extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} hpcInitCode :: Module -> HpcInfo -> SDoc hpcInitCode _ (NoHpcInfo {}) = Outputable.empty hpcInitCode this_mod (HpcInfo tickCount hashNo) = vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)" , braces (vcat [ ptext (sLit "extern StgWord64 ") <> tickboxes <> ptext (sLit "[]") <> semi, ptext (sLit "hs_hpc_module") <> parens (hcat (punctuate comma [ doubleQuotes full_name_str, int tickCount, -- really StgWord32 int hashNo, -- really StgWord32 tickboxes ])) <> semi ]) ] where tickboxes = ppr (mkHpcTicksLabel $ this_mod) module_name = hcat (map (text.charToC) $ bytesFS (moduleNameFS (Module.moduleName this_mod))) package_name = hcat (map (text.charToC) $ bytesFS (packageKeyFS (modulePackageKey this_mod))) full_name_str | modulePackageKey this_mod == mainPackageKey = module_name | otherwise = package_name <> char '/' <> module_name
green-haskell/ghc
compiler/deSugar/Coverage.hs
bsd-3-clause
48,683
0
25
14,708
12,975
6,578
6,397
931
8
{-# LANGUAGE BangPatterns #-} -- | -- Module : Data.Text.Internal.Encoding.Fusion.Common -- Copyright : (c) Tom Harper 2008-2009, -- (c) Bryan O'Sullivan 2009, -- (c) Duncan Coutts 2009, -- (c) Jasper Van der Jeugt 2011 -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- /Warning/: this is an internal module, and does not have a stable -- API or name. Use at your own risk! -- -- Fusible 'Stream'-oriented functions for converting between 'Text' -- and several common encodings. module Data.Text.Internal.Encoding.Fusion.Common ( -- * Restreaming -- Restreaming is the act of converting from one 'Stream' -- representation to another. restreamUtf16LE , restreamUtf16BE , restreamUtf32LE , restreamUtf32BE ) where import Data.Bits ((.&.)) import Data.Text.Internal.Fusion (Step(..), Stream(..)) import Data.Text.Internal.Fusion.Types (RS(..)) import Data.Text.Internal.Unsafe.Char (ord) import Data.Text.Internal.Unsafe.Shift (shiftR) import Data.Word (Word8) restreamUtf16BE :: Stream Char -> Stream Word8 restreamUtf16BE (Stream next0 s0 len) = Stream next (RS0 s0) (len * 2) where next (RS0 s) = case next0 s of Done -> Done Skip s' -> Skip (RS0 s') Yield x s' | n < 0x10000 -> Yield (fromIntegral $ n `shiftR` 8) $ RS1 s' (fromIntegral n) | otherwise -> Yield c1 $ RS3 s' c2 c3 c4 where n = ord x n1 = n - 0x10000 c1 = fromIntegral (n1 `shiftR` 18 + 0xD8) c2 = fromIntegral (n1 `shiftR` 10) n2 = n1 .&. 0x3FF c3 = fromIntegral (n2 `shiftR` 8 + 0xDC) c4 = fromIntegral n2 next (RS1 s x2) = Yield x2 (RS0 s) next (RS2 s x2 x3) = Yield x2 (RS1 s x3) next (RS3 s x2 x3 x4) = Yield x2 (RS2 s x3 x4) {-# INLINE next #-} {-# INLINE restreamUtf16BE #-} restreamUtf16LE :: Stream Char -> Stream Word8 restreamUtf16LE (Stream next0 s0 len) = Stream next (RS0 s0) (len * 2) where next (RS0 s) = case next0 s of Done -> Done Skip s' -> Skip (RS0 s') Yield x s' | n < 0x10000 -> Yield (fromIntegral n) $ RS1 s' (fromIntegral $ shiftR n 8) | otherwise -> Yield c1 $ RS3 s' c2 c3 c4 where n = ord x n1 = n - 0x10000 c2 = fromIntegral (shiftR n1 18 + 0xD8) c1 = fromIntegral (shiftR n1 10) n2 = n1 .&. 0x3FF c4 = fromIntegral (shiftR n2 8 + 0xDC) c3 = fromIntegral n2 next (RS1 s x2) = Yield x2 (RS0 s) next (RS2 s x2 x3) = Yield x2 (RS1 s x3) next (RS3 s x2 x3 x4) = Yield x2 (RS2 s x3 x4) {-# INLINE next #-} {-# INLINE restreamUtf16LE #-} restreamUtf32BE :: Stream Char -> Stream Word8 restreamUtf32BE (Stream next0 s0 len) = Stream next (RS0 s0) (len * 2) where next (RS0 s) = case next0 s of Done -> Done Skip s' -> Skip (RS0 s') Yield x s' -> Yield c1 (RS3 s' c2 c3 c4) where n = ord x c1 = fromIntegral $ shiftR n 24 c2 = fromIntegral $ shiftR n 16 c3 = fromIntegral $ shiftR n 8 c4 = fromIntegral n next (RS1 s x2) = Yield x2 (RS0 s) next (RS2 s x2 x3) = Yield x2 (RS1 s x3) next (RS3 s x2 x3 x4) = Yield x2 (RS2 s x3 x4) {-# INLINE next #-} {-# INLINE restreamUtf32BE #-} restreamUtf32LE :: Stream Char -> Stream Word8 restreamUtf32LE (Stream next0 s0 len) = Stream next (RS0 s0) (len * 2) where next (RS0 s) = case next0 s of Done -> Done Skip s' -> Skip (RS0 s') Yield x s' -> Yield c1 (RS3 s' c2 c3 c4) where n = ord x c4 = fromIntegral $ shiftR n 24 c3 = fromIntegral $ shiftR n 16 c2 = fromIntegral $ shiftR n 8 c1 = fromIntegral n next (RS1 s x2) = Yield x2 (RS0 s) next (RS2 s x2 x3) = Yield x2 (RS1 s x3) next (RS3 s x2 x3 x4) = Yield x2 (RS2 s x3 x4) {-# INLINE next #-} {-# INLINE restreamUtf32LE #-}
bgamari/text
src/Data/Text/Internal/Encoding/Fusion/Common.hs
bsd-2-clause
4,275
0
15
1,473
1,429
734
695
87
6
{-# LANGUAGE ImplicitParams #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Test where class C t where type TF t ttt :: TF t -> t b :: (C t, ?x :: TF t) => t b = ttt ?x
ezyang/ghc
testsuite/tests/typecheck/should_compile/T5120.hs
bsd-3-clause
216
0
8
53
63
36
27
9
1
{-# LANGUAGE MultiParamTypeClasses,RankNTypes,ExistentialQuantification,DatatypeContexts #-} module RnFail055 where import RnFail055_aux -- Id with different type f1 :: Int -> Float f1 = undefined -- type synonym with different arity type S1 a b = (a,b) -- type synonym with different rhs type S2 a b = forall a. (a,b) -- type synonym with alpha-renaming (should be ok) type S3 a = [a] -- datatype with different fields data T1 a b = T1 [b] [a] -- datatype with different stupid theta data (Eq b) => T2 a b = T2 a -- different constructor name data T3' = T3 data T3 = T3' -- check alpha equivalence data T4 a = T4 (forall b. a -> b) -- different field labels data T5 a = T5 { field5 :: a } -- different strict marks data T6 = T6 Int -- different existential quantification data T7 a = forall a . T7 a -- extra method in the hs-boot class C1 a b where {} -- missing method in the hs-boot class C2 a b where { m2 :: a -> b; m2' :: a -> b } -- different superclasses class (Eq a, Ord a) => C3 a where { }
urbanslug/ghc
testsuite/tests/rename/should_fail/RnFail055.hs
bsd-3-clause
1,017
0
9
216
265
166
99
-1
-1
{-# LANGUAGE MultiWayIf #-} module Main where x = 10 x1 = if | x < 10 -> "< 10" | otherwise -> "" x2 = if | x < 10 -> "< 10" | otherwise -> "" x3 = if | x < 10 -> "< 10" | otherwise -> "" x4 = if | True -> "yes" x5 = if | True -> if | False -> 1 | True -> 2 x6 = if | x < 10 -> if | True -> "yes" | False -> "no" | otherwise -> "maybe" x7 = (if | True -> 0) main = print $ x5 == 2 && x6 == "maybe" && x7 == 0
urbanslug/ghc
testsuite/tests/parser/should_run/ParserMultiWayIf.hs
bsd-3-clause
462
0
10
170
228
113
115
15
3
module Haks.Types where import BasicPrelude hiding (empty) import Control.Monad.Reader import Data.Sequence import Data.Maybe import Data.Text hiding (empty) data ParticleConfig = ParticleConfig { pre_processor_hc :: [Char] -> [Char] , tokenizer_hc :: Char -> Maybe (Token,Char) , cleanup_hc :: [(Token,Char)] -> [(Token,Char)] , particlate_hc :: Text -> [Particle] -> [(Token,Char)] -> [Particle] } type Particle = Text data Token = Chinese | TIBETAN_ROMAN | Space | TIBETAN_UCHEN UChenToken | SANSKRIT_ROMAN SKTR | SANSKRIT_DEVA deriving (Eq,Show) data SKTR = SKTR_CONSONANT | SKTR_VOWEL | SKTR_TERMINAL | SKTR_DIGIT deriving (Eq,Show) data UChenToken = TSheg | StdChar_UC deriving (Eq,Show) type NGram = Text init_syllable :: Seq Particle init_syllable = empty
mlitchard/haks
src/Haks/Types.hs
isc
832
0
13
172
257
156
101
33
1
module Test.Laws ( prop_leftIdentity, prop_rightIdentity, prop_identity, prop_annihilation , prop_associative, prop_commutative, prop_monotonic , prop_monoid, prop_Monoid , prop_tnorm, prop_Tnorm , prop_tconorm, prop_Tconorm , T(..) ) where import Data.Tnorm import Data.Tconorm import Test.PropBox import Test.QuickCheck import Data.Monoid (Monoid (..)) prop_leftIdentity :: (Eq a, Show a, Arbitrary a) => a -> (a -> a -> a) -> PropBox prop_leftIdentity iden f = atomProp "left identity" prop where prop x = f iden x == x prop_rightIdentity :: (Eq a, Show a, Arbitrary a) => a -> (a -> a -> a) -> PropBox prop_rightIdentity iden f = atomProp "rigth identity" prop where prop x = f x iden == x prop_identity :: (Eq a, Show a, Arbitrary a) => a -> (a -> a -> a) -> PropBox prop_identity iden f = propGroup "identity" [prop_leftIdentity iden f, prop_rightIdentity iden f] prop_associative :: (Eq a, Show a, Arbitrary a) => (a -> a -> a) -> PropBox prop_associative f = atomProp "associative" prop where prop a b c = f a (f b c) == f (f a b) c prop_commutative :: (Eq b, Show a, Arbitrary a) => (a -> a -> b) -> PropBox prop_commutative f = atomProp "commutative" prop where prop a b = f a b == f b a prop_monotonic :: (Ord a, Show a, Arbitrary a) => (a -> a -> a) -> PropBox prop_monotonic f = atomProp "monotonic" prop where prop a b c d = f (min a c) (min b d) <= f (max a c) (max b d) prop_annihilation :: (Eq a, Show a, Arbitrary a) => a -> (a -> a -> a) -> PropBox prop_annihilation an f = atomProp "annihilation" prop where prop x = f an x == an && an == f x an data T a = T prop_monoid :: (Eq a, Show a, Arbitrary a) => a -> (a -> a -> a) -> PropBox prop_monoid iden f = propGroup "monoid" [ prop_associative f , prop_identity iden f ] prop_Monoid :: (Eq a, Show a, Arbitrary a, Monoid a) => T a -> PropBox prop_Monoid t = prop_monoid (tie t) mappend where tie :: Monoid a => T a -> a tie _ = mempty prop_tnorm :: (Ord a, Num a, Show a, Arbitrary a) => (a -> a -> a) -> PropBox prop_tnorm f = propGroup "t-norm" [ prop_monoid 1 f , prop_commutative f , prop_monotonic f , prop_annihilation 0 f ] prop_Tnorm :: (Show a, Arbitrary a, Tnorm a) => T a -> PropBox prop_Tnorm = prop_tnorm . tie where tie :: Tnorm a => T a -> (a -> a -> a) tie _ = tnorm prop_tconorm :: (Show a, Arbitrary a, Tconorm a) => (a -> a -> a) -> PropBox prop_tconorm f = propGroup "t-conorm" [ prop_monoid 0 f , prop_commutative f , prop_monotonic f , prop_annihilation 1 f ] prop_Tconorm :: (Show a, Arbitrary a, Tconorm a) => T a -> PropBox prop_Tconorm = prop_tconorm . tie where tie :: Tconorm a => T a -> (a -> a -> a) tie _ = snorm
pxqr/fuzzy-set
Test/Laws.hs
mit
3,011
0
11
909
1,211
626
585
59
1
{-# LANGUAGE PatternGuards #-} import Data.List import Data.List.Split import Data.Char (isDigit) import Control.Monad.Par main :: IO () main = do content <- readFile "input.txt" let ls = lines content let instructions = map parseInstruction ls let g = createGridPar instructions putStr . show $ countTrue g return () type Grid = [[Int]] type Pos = (Int, Int) type Instruction = (Pos, Pos, (Int -> Int)) parseInstruction :: String -> Instruction parseInstruction s | Just s' <- stripPrefix "turn on " s = createInstruction s' on | Just s' <- stripPrefix "turn off " s = createInstruction s' off | Just s' <- stripPrefix "toggle " s = createInstruction s' toggle | otherwise = error $ "Error, invalid instruction: " ++ s off :: Int -> Int off 0 = 0 off n = n-1 toggle :: Int -> Int toggle n = n+2 on :: Int -> Int on n = n+1 createInstruction :: String -> (Int -> Int) -> Instruction createInstruction s f = (first_pos, second_pos, f) where ps = getListOfPositions first_pos second_pos (first_pos, second_pos) = getPositions s createGrid :: [Instruction] -> Grid createGrid is = chunksOf 1000 $ [ applyRelevantInstructions is (x,y) | x <- [0..999] , y <- [0..999] ] createGridPar :: [Instruction] -> Grid createGridPar is = chunksOf 1000 $ runPar $ do l1' <- spawnP [ applyRelevantInstructions is (x,y) | x <- [0..250] , y <- [0..250] ] l2' <- spawnP [ applyRelevantInstructions is (x,y) | x <- [251..500] , y <- [251..500] ] l3' <- spawnP [ applyRelevantInstructions is (x,y) | x <- [501..750] , y <- [501..750] ] l4' <- spawnP [ applyRelevantInstructions is (x,y) | x <- [751..999] , y <- [751..999] ] l1 <- get l1' l2 <- get l2' l3 <- get l3' l4 <- get l4' return $ l1 ++ l2 ++ l3 ++ l4 applyRelevantInstructions :: [Instruction] -> Pos -> Int applyRelevantInstructions is p = foldl' apply 0 ris where ris = filter (\(p1, p2, _) -> positionWithinRect p (p1, p2)) is apply :: (Int -> Instruction -> Int) apply b (_, _, f) = f b countTrue :: Grid -> Int countTrue g = sum $ concat g getListOfPositions :: Pos -> Pos -> [Pos] getListOfPositions (x1,y1) (x2, y2) = [(x,y) | x <- [x1..x2], y <- [y1..y2]] getPositions :: String -> (Pos, Pos) getPositions s = (extractPos s1, extractPos s2) where s1 = head ws s2 = last ws ws = words s extractPos :: String -> (Int, Int) extractPos s = (p, p') where p = (read . twd) s p' = (read . reverse . twd . reverse) s twd :: [Char] -> [Char] twd s = takeWhile isDigit s positionWithinRect :: Pos -> (Pos, Pos) -> Bool positionWithinRect (x, y) ((x1, y1), (x2, y2)) = x >= x1 && x <= x2 && y >= y1 && y <= y2 printGrid :: Grid -> IO () printGrid g = sequence_ $ stuff where stuff = map (putStr . nicefyRow) g nicefyRow :: [Int] -> String nicefyRow ls = (show ls) ++ "\n"
Dr-Horv/Advent-of-code
day06/day6.hs
mit
3,032
0
13
834
1,285
672
613
72
1
module NewickParser (parseNewickTree) where -- Hm, for now it will parse String, not Data.Text (but the trees should be very -- small compared to the alignments, so it should make no difference). import Text.ParserCombinators.Parsec import qualified Data.Text as T import Data.Tree identifier :: Parser String identifier = many (letter <|> digit <|> char '_' <|> char '|') <?> "identifier" -- Note: these "number" parsers actually return (), because they are used to -- recognize branch lengths in Newick, which are not used in the classifier. -- They are only needed to allow phylograms to parse (otherwise only cladograms -- would be accepted). digits :: Parser () digits = many digit >> return () period :: Parser () period = char '.' >> return () number :: Parser () number = digits >> option () (period >> digits) oParen :: Parser () oParen = char '(' >> return () cParen :: Parser () cParen = char ')' >> return () colon :: Parser () colon = char ':' >> return () semicolon :: Parser () semicolon = char ';' >> return () comma :: Parser () comma = char ',' >> return () nwLeaf :: Parser (Tree T.Text) nwLeaf = do id <- identifier length <- option () (colon >> number) return $ Node (T.pack id) [] nwNode :: Parser (Tree T.Text) nwNode = do {oParen ; children <- nwNode `sepBy` comma ; cParen ; label <- option "" identifier ; length <- option () (colon >> number) ; return $ Node (T.pack label) children } <|> nwLeaf newickTree :: Parser (Tree T.Text) newickTree = do tree <- nwNode semicolon return tree parseNewickTree :: String -> Either ParseError (Tree T.Text) parseNewickTree newick = (parse newickTree "" newick) run :: Show a => Parser a -> String -> IO () run p input = case (parse p "" input) of Left err -> do { putStr "parse error at " ; print err } Right x -> print x
tjunier/mlgsc
src/NewickParser.hs
mit
1,975
0
12
515
637
318
319
48
2
import SFML.System main = do clock <- createClock loop clock 3 destroy clock loop clock 0 = return () loop clock n = do sfSleep $ seconds 0.150 time <- getElapsedTime clock if asSeconds time >= 1 then putStrLn "tick" >> restartClock clock >> loop clock (n-1) else loop clock n
SFML-haskell/SFML
demos/time/main.hs
mit
322
0
11
96
126
57
69
12
2
module Oden.Output.Compiler where import Text.PrettyPrint.Leijen import Oden.Compiler import Oden.Compiler.Monomorphization import Oden.Output import Oden.Output.Instantiate () import Oden.Pretty () instance OdenOutput MonomorphError where outputType _ = Error name (NotInScope _) = "Compiler.Monomorph.NotInScope" name (UnexpectedPolyType _ _) = "Compiler.Monomorph.UnexpectedPolyType" name (MonomorphInstantiateError err) = name err header (NotInScope i) s = code s (pretty i) <+> text "is not in scope" header (UnexpectedPolyType _ e) s = text "Unexpected polymorphic type" <+> code s (pretty e) header (MonomorphInstantiateError err) s = header err s details (MonomorphInstantiateError e) s = details e s details (NotInScope _) _ = empty details (UnexpectedPolyType _ _) _ = text "This can usually be fixed by adding (stricter) type signatures to top-level forms." sourceInfo (MonomorphInstantiateError e) = sourceInfo e sourceInfo (UnexpectedPolyType si _) = Just si sourceInfo _ = Nothing instance OdenOutput CompilationError where outputType (MonomorphError e) = outputType e name (MonomorphError e) = name e header (MonomorphError e) = header e details (MonomorphError e) = details e sourceInfo (MonomorphError e) = sourceInfo e
AlbinTheander/oden
src/Oden/Output/Compiler.hs
mit
1,443
0
9
371
395
197
198
27
0
{-| Eyre: Http Server Driver -} module Urbit.Vere.Eyre ( eyre , eyre' ) where import Urbit.Prelude hiding (Builder) import Urbit.Arvo hiding (ServerId, reqUrl) import Urbit.King.App ( killKingActionL , HasKingId(..) , HasMultiEyreApi(..) , HasPierEnv(..) ) import Urbit.King.Config import Urbit.Vere.Eyre.Multi import Urbit.Vere.Eyre.PortsFile import Urbit.Vere.Eyre.Serv import Urbit.Vere.Eyre.Service import Urbit.Vere.Eyre.Wai import Urbit.Vere.Pier.Types import Data.List.NonEmpty (NonEmpty((:|))) import Data.PEM (pemParseBS, pemWriteBS) import RIO.Prelude (decodeUtf8Lenient) import System.Random (randomIO) import Urbit.Vere.Http (convertHeaders, unconvertHeaders) import Urbit.Vere.Eyre.KingSubsite (KingSubsite) import qualified Network.HTTP.Types as H -- Types ----------------------------------------------------------------------- type HasShipEnv e = (HasLogFunc e, HasNetworkConfig e, HasPierConfig e) type ReqId = UD newtype Drv = Drv (MVar (Maybe Serv)) data SockOpts = SockOpts { soLocalhost :: Bool , soWhich :: ServPort } data PortsToTry = PortsToTry { pttSec :: SockOpts , pttIns :: SockOpts , pttLop :: SockOpts } data Serv = Serv { sServId :: ServId , sConfig :: HttpServerConf , sLop :: ServApi , sIns :: ServApi , sSec :: Maybe ServApi , sPorts :: Ports , sPortsFile :: FilePath , sLiveReqs :: TVar LiveReqs } -- Utilities for Constructing Events ------------------------------------------- servEv :: HttpServerEv -> Ev servEv = EvBlip . BlipEvHttpServer bornEv :: KingId -> Ev bornEv king = servEv $ HttpServerEvBorn (king, ()) () liveEv :: ServId -> Ports -> Ev liveEv sId Ports {..} = servEv $ HttpServerEvLive (sId, ()) pHttp pHttps cancelEv :: ServId -> ReqId -> EvErr cancelEv sId reqId = EvErr (servEv (HttpServerEvCancelRequest (sId, reqId, 1, ()) ())) cancelFailed cancelFailed :: WorkError -> IO () cancelFailed _ = pure () reqEv :: ServId -> ReqId -> WhichServer -> Address -> HttpRequest -> Ev reqEv sId reqId which addr req = case which of Loopback -> servEv $ HttpServerEvRequestLocal (sId, reqId, 1, ()) $ HttpServerReq False addr req _ -> servEv $ HttpServerEvRequest (sId, reqId, 1, ()) $ HttpServerReq (which == Secure) addr req -- Based on Pier+Config, which ports should each server run? ------------------- httpServerPorts :: HasShipEnv e => Bool -> RIO e PortsToTry httpServerPorts fak = do ins <- view (networkConfigL . ncHttpPort . to (fmap fromIntegral)) sec <- view (networkConfigL . ncHttpsPort . to (fmap fromIntegral)) lop <- view (networkConfigL . ncLocalPort . to (fmap fromIntegral)) localMode <- view (networkConfigL . ncNetMode . to (== NMLocalhost)) let local = localMode || fak let pttSec = case (sec, fak) of (Just p , _ ) -> SockOpts local (SPChoices $ singleton p) (Nothing, False) -> SockOpts local (SPChoices (443 :| [8443 .. 8453])) (Nothing, True ) -> SockOpts local (SPChoices (8443 :| [8444 .. 8453])) let pttIns = case (ins, fak) of (Just p , _ ) -> SockOpts local (SPChoices $ singleton p) (Nothing, False) -> SockOpts local (SPChoices (80 :| [8080 .. 8090])) (Nothing, True ) -> SockOpts local (SPChoices (8080 :| [8081 .. 8090])) let pttLop = case (lop, fak) of (Just p , _) -> SockOpts local (SPChoices $ singleton p) (Nothing, _) -> SockOpts local SPAnyPort pure (PortsToTry { .. }) -- Convert Between Urbit and WAI types. ---------------------------------------- parseTlsConfig :: (Key, Cert) -> Maybe TlsConfig parseTlsConfig (PEM key, PEM certs) = do let (cerByt, keyByt) = (wainBytes certs, wainBytes key) pems <- pemParseBS cerByt & either (const Nothing) Just (cert, chain) <- case pems of [] -> Nothing p : ps -> pure (pemWriteBS p, pemWriteBS <$> ps) pure $ TlsConfig keyByt cert chain where wainBytes :: Wain -> ByteString wainBytes = encodeUtf8 . unWain parseHttpEvent :: HttpEvent -> [RespAct] parseHttpEvent = \case Start h b True -> [RAFull (hSta h) (hHdr h) (fByt $ fromMaybe "" b)] Start h b False -> [RAHead (hSta h) (hHdr h) (fByt $ fromMaybe "" b)] Cancel () -> [RADone] Continue b done -> toList (RABloc . fByt <$> b) <> if done then [RADone] else [] where hHdr :: ResponseHeader -> [H.Header] hHdr = unconvertHeaders . headers hSta :: ResponseHeader -> H.Status hSta = toEnum . fromIntegral . statusCode fByt :: File -> ByteString fByt = unOcts . unFile requestEvent :: ServId -> WhichServer -> Word64 -> ReqInfo -> Ev requestEvent srvId which reqId ReqInfo{..} = reqEv srvId reqUd which riAdr evReq where evBod = bodFile riBod evHdr = convertHeaders riHdr evUrl = Cord (decodeUtf8Lenient riUrl) evReq = HttpRequest riMet evUrl evHdr evBod reqUd = fromIntegral reqId bodFile :: ByteString -> Maybe File bodFile "" = Nothing bodFile bs = Just $ File $ Octs bs -- Running Servers ------------------------------------------------------------- execRespActs :: HasLogFunc e => Drv -> Ship -> Word64 -> HttpEvent -> RIO e () execRespActs (Drv v) who reqId ev = readMVar v >>= \case Nothing -> logError "Got a response to a request that does not exist." Just sv -> do logDebug $ displayShow ev for_ (parseHttpEvent ev) $ \act -> do atomically (routeRespAct who (sLiveReqs sv) reqId act) startServ :: (HasPierConfig e, HasLogFunc e, HasMultiEyreApi e, HasNetworkConfig e) => Ship -> Bool -> HttpServerConf -> (EvErr -> STM ()) -> (Text -> RIO e ()) -> IO () -> KingSubsite -> RIO e Serv startServ who isFake conf plan stderr onFatal sub = do logInfo (displayShow ("EYRE", "startServ")) multi <- view multiEyreApiL let vLive = meaLive multi srvId <- io $ ServId . UV . fromIntegral <$> (randomIO :: IO Word32) let mTls = hscSecure conf >>= parseTlsConfig mCre <- mTls & \case Nothing -> pure Nothing Just tc -> configCreds tc & \case Right rs -> pure (Just (tc, rs)) Left err -> do logError "Couldn't Load TLS Credentials." pure Nothing ptt <- httpServerPorts isFake {- TODO If configuration requests a redirect, get the HTTPS port (if configuration specifies a specific port, use that. Otherwise, wait for the HTTPS server to start and then use the port that it chose). and run an HTTP server that simply redirects to the HTTPS server. -} let secRedi = Nothing let soHost :: SockOpts -> ServHost soHost so = if soLocalhost so then SHLocalhost else SHAnyHostOk noHttp <- view (networkConfigL . ncNoHttp) noHttps <- view (networkConfigL . ncNoHttps) let reqEvFailed _ = pure () let onReq :: WhichServer -> Ship -> Word64 -> ReqInfo -> STM () onReq which _ship reqId reqInfo = plan $ EvErr (requestEvent srvId which reqId reqInfo) reqEvFailed let onKilReq :: Ship -> Word64 -> STM () onKilReq _ship = plan . cancelEv srvId . fromIntegral logInfo (displayShow ("EYRE", "joinMultiEyre", who, mTls, mCre)) atomically (joinMultiEyre multi who mCre onReq onKilReq sub) logInfo $ displayShow ("EYRE", "Starting loopback server") lop <- serv vLive onFatal $ ServConf { scHost = soHost (pttLop ptt) , scPort = soWhich (pttLop ptt) , scRedi = Nothing , scFake = False , scType = STHttp who sub $ ReqApi { rcReq = onReq Loopback , rcKil = onKilReq } } logInfo $ displayShow ("EYRE", "Starting insecure server") ins <- serv vLive onFatal $ ServConf { scHost = soHost (pttIns ptt) , scPort = soWhich (pttIns ptt) , scRedi = secRedi , scFake = noHttp , scType = STHttp who sub $ ReqApi { rcReq = onReq Insecure , rcKil = onKilReq } } mSec <- for mTls $ \tls -> do logInfo "Starting secure server" serv vLive onFatal $ ServConf { scHost = soHost (pttSec ptt) , scPort = soWhich (pttSec ptt) , scRedi = Nothing , scFake = noHttps , scType = STHttps who tls sub $ ReqApi { rcReq = onReq Secure , rcKil = onKilReq } } pierPath <- view pierPathL lopPor <- atomically (fmap fromIntegral $ saPor lop) insPor <- atomically (fmap fromIntegral $ saPor ins) secPor <- for mSec (fmap fromIntegral . atomically . saPor) let por = Ports secPor insPor lopPor fil = pierPath <> "/.http.ports" logInfo $ displayShow ("EYRE", "All Servers Started.", srvId, por, fil) for secPor $ \p -> stderr ("http: secure web interface live on https://localhost:" <> tshow p) stderr ("http: web interface live on http://localhost:" <> tshow insPor) stderr ("http: loopback live on http://localhost:" <> tshow lopPor) pure (Serv srvId conf lop ins mSec por fil vLive) -- Eyre Driver ----------------------------------------------------------------- _bornFailed :: e -> WorkError -> IO () _bornFailed env _ = runRIO env $ do pure () -- TODO What should this do? eyre' :: (HasPierEnv e, HasMultiEyreApi e) => Ship -> Bool -> (Text -> RIO e ()) -> KingSubsite -> RIO e ([Ev], RAcquire e (DriverApi HttpServerEf)) eyre' who isFake stderr sub = do ventQ :: TQueue EvErr <- newTQueueIO env <- ask let (bornEvs, startDriver) = eyre env who (writeTQueue ventQ) isFake stderr sub let runDriver = do diOnEffect <- startDriver let diEventSource = fmap RRWork <$> tryReadTQueue ventQ pure (DriverApi {..}) pure (bornEvs, runDriver) {-| Eyre -- HTTP Server Driver Inject born events. Until born events succeeds, ignore effects. Wait until born event callbacks invoked. If success, signal success. If failure, try again several times. If still failure, bring down ship. Once born event succeeds: - Begin normal operation (start accepting requests) -} eyre :: forall e . (HasPierEnv e) => e -> Ship -> (EvErr -> STM ()) -> Bool -> (Text -> RIO e ()) -> KingSubsite -> ([Ev], RAcquire e (HttpServerEf -> IO ())) eyre env who plan isFake stderr sub = (initialEvents, runHttpServer) where king = fromIntegral (env ^. kingIdL) multi = env ^. multiEyreApiL initialEvents :: [Ev] initialEvents = [bornEv king] runHttpServer :: RAcquire e (HttpServerEf -> IO ()) runHttpServer = handleEf <$> mkRAcquire (Drv <$> newMVar Nothing) (\(Drv v) -> stopService v kill >>= fromEither) kill :: HasLogFunc e => Serv -> RIO e () kill Serv{..} = do atomically (leaveMultiEyre multi who) io (saKil sLop) io (saKil sIns) io $ for_ sSec (\sec -> (saKil sec)) io (removePortsFile sPortsFile) restart :: Drv -> HttpServerConf -> RIO e Serv restart (Drv var) conf = do logInfo "Restarting http server" let onFatal = runRIO env $ do -- XX instead maybe restart following logic under HSESetConfig below stderr "A web server problem has occurred. Please restart your ship." view killKingActionL >>= atomically let startAct = startServ who isFake conf plan stderr onFatal sub res <- fromEither =<< restartService var startAct kill logInfo "Done restating http server" pure res liveFailed _ = pure () handleEf :: Drv -> HttpServerEf -> IO () handleEf drv = runRIO env . \case HSESetConfig (i, ()) conf -> do logInfo (displayShow ("EYRE", "%set-config")) Serv {..} <- restart drv conf logInfo (displayShow ("EYRE", "%set-config", "Sending %live")) atomically $ plan (EvErr (liveEv sServId sPorts) liveFailed) logInfo "Write ports file" io (writePortsFile sPortsFile sPorts) HSEResponse (i, req, _seq, ()) ev -> do logDebug (displayShow ("EYRE", "%response")) execRespActs drv who (fromIntegral req) ev
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/Vere/Eyre.hs
mit
12,047
0
19
2,990
3,916
2,004
1,912
-1
-1
module Solidran.Iprb.DetailSpec (spec) where import Test.Hspec import Solidran.Iprb.Detail import qualified Data.Map as Map spec :: Spec spec = do describe "Solidran.Iprb.Detail" $ do describe "totalProb" $ do it "should work on the given example" $ do totalProb (Map.fromList [(HomoDom, 2), (Hetero, 2), (HomoRec, 2)]) `shouldBe` 0.7833333333333333 it "should return 0 on no organisms" $ do totalProb (Map.fromList []) `shouldBe` 0.0 it "should return 1 when there are all HomoDom" $ do totalProb (Map.fromList [(HomoDom, 5)]) `shouldBe` 1.0 it "should return 0 on all HomoRec" $ do totalProb (Map.fromList [(HomoRec, 52)]) `shouldBe` 0.0 it "should return 3/4 on all Hetero" $ do totalProb (Map.fromList [(Hetero, 43)]) `shouldBe` 0.75 it "should return 0 on single organisms" $ do totalProb (Map.fromList [(HomoDom, 1)]) `shouldBe` 0.0 totalProb (Map.fromList [(Hetero, 1)]) `shouldBe` 0.0 totalProb (Map.fromList [(HomoRec, 1)]) `shouldBe` 0.0
Jefffrey/Solidran
test/Solidran/Iprb/DetailSpec.hs
mit
1,330
0
21
516
364
194
170
30
1
import Data.List import qualified Control.Monad import qualified Data.Map as Map import Text.Regex import Control.Concurrent import Control.Concurrent.STM.TChan import Control.Concurrent.Async import Control.Monad.STM import Control.Monad --Premiere étape du pipeline, écrit dans le channel fstPipe :: (a -> b) -> TChan b -> MVar () -> [a] -> IO () fstPipe f chIn m xs = do ( mapM_(\x-> atomically $ writeTChan chIn $! f x) xs) >> putMVar m () --Lis les données du channel entrant et les met dans le channel sortant pipe :: (a -> b) -> TChan a -> TChan b -> MVar () -> MVar () -> IO() pipe f chIn chOut mIn mOut = iter where iter = do val <- fmap f $ atomically $ readTChan chIn atomically $ writeTChan chOut val estFini <- pipelineEstFini chIn mIn if estFini then putMVar mOut () else iter --Vérifi si le pipeline est fini pipelineEstFini channel mIn = do rouleEncore <- isEmptyMVar mIn estVide <- atomically $ isEmptyTChan channel return $ estVide && not rouleEncore --Derniere etape du pipeline lastPipe::(Show a) => (a->IO()) -> TChan a -> MVar () -> IO() lastPipe f chIn mIn = iter where iter = do r <- atomically $ readTChan chIn f r estFini <- pipelineEstFini chIn mIn unless estFini $ iter --Crée un pipeline a partir d'une liste de fonction. La dernière fonction doit être séparé car elle n'est pas du même type creerPipeAsync::(Show a) => [a -> a] -> (a -> IO()) -> [a] -> IO () creerPipeAsync (f:fs) final xs = do chIn <- atomically newTChan m <- newEmptyMVar th <- async $ fstPipe f chIn m xs reste <- lkn fs chIn m mapM_ wait (th:reste) where --lkn fait le lien entre les fonctions avec les channels lkn [] chIn mIn = do th <- async $ lastPipe final chIn mIn return [th] lkn (f:fs) chIn mIn = do (th, channel, fin) <- linkPipeline f chIn mIn reste <- (lkn fs channel fin) return (th:reste) linkPipeline f chIn mIn = do chOut <- atomically newTChan mOut <- newEmptyMVar a <- async $ pipe f chIn chOut mIn mOut return (a, chOut, mOut) --Pour chaque charactere de la string, si il est speciaux, le remplacer, sinon on garde le même charactere remplacerCaracSpeciaux (nom, code)= let speciaux = Map.fromList [('&', "&amp;"),('>',"&gt;"), ('<',"&lt;"), ('\"', "&quot;")] in foldr (\c acc ->(Map.findWithDefault [c] c speciaux)++acc) "" code colorierMotsClef motsClef (nom,code) = let delimitateurs = "(&gt;|&lt;|\\(|\\)|;|[[:space:]])" reg = mkRegex $ delimitateurs ++ "(" ++ (intercalate "|" motsClef) ++ ")" ++ delimitateurs in subRegex reg code "\\1<span class='motClef'>\\2</span>\\3" colorierCommentaires (nom,code) = subRegex (mkRegex "(//.*$|/\\*(.|[\r\n])*\\*/)") code "<span class='commentaire'>\\0</span>" colorierPreprocesseur motsClef (nom,code) = let reg = mkRegex $ "#(" ++ (intercalate "|" motsClef) ++ ")[[:space:]]" in subRegex reg code "<span class='preprocesseur'>\\0</span>" transformerHTML (nom,code) = "<!DOCTYPE html><html><head><style> .motClef { font-weight: bold; color:blue } .preprocesseur { font-weight: bold; color:red } .commentaire, .commentaire * {font-style: italic; color: brown}</style></head><body><pre>"++code++"</pre></body></html>" exporterFichier mode (nom,code) = writeFile (nom++"."++mode++".html") code pipelineFuncs motsClef preproc = map ajoutNom $ [remplacerCaracSpeciaux, colorierMotsClef motsClef, colorierCommentaires ,colorierPreprocesseur preproc, transformerHTML] lireFichiers = mapM readFile ajoutNom f (a,b)= (a,f(a,b)) pipelineSeq funcs fichiers = do mapM_ (exporterFichier "seq") $ foldl (\codes f-> map f codes) fichiers $ funcs pipelinePar funcs fichiers = creerPipeAsync funcs (exporterFichier "par") fichiers main = do nomFichiers <- fmap lines $ readFile "fichiers.txt" motsClef <- fmap lines $ readFile "motsClef.txt" preproc <- fmap lines $ readFile "preprocesseur.txt" fichiers <- lireFichiers nomFichiers pipelinePar (pipelineFuncs motsClef preproc) $ zip nomFichiers fichiers
bruno-cadorette/IFT630-TP1
TP1.hs
mit
4,067
13
14
773
1,341
670
671
78
2
module Mega1 where mega1 :: String mega1 = "mega1"
fpco/simple-mega-repo
mega1/Mega1.hs
mit
52
0
4
10
14
9
5
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html module Stratosphere.ResourceProperties.CognitoUserPoolAdminCreateUserConfig where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.CognitoUserPoolInviteMessageTemplate -- | Full data type definition for CognitoUserPoolAdminCreateUserConfig. See -- 'cognitoUserPoolAdminCreateUserConfig' for a more convenient constructor. data CognitoUserPoolAdminCreateUserConfig = CognitoUserPoolAdminCreateUserConfig { _cognitoUserPoolAdminCreateUserConfigAllowAdminCreateUserOnly :: Maybe (Val Bool) , _cognitoUserPoolAdminCreateUserConfigInviteMessageTemplate :: Maybe CognitoUserPoolInviteMessageTemplate , _cognitoUserPoolAdminCreateUserConfigUnusedAccountValidityDays :: Maybe (Val Double) } deriving (Show, Eq) instance ToJSON CognitoUserPoolAdminCreateUserConfig where toJSON CognitoUserPoolAdminCreateUserConfig{..} = object $ catMaybes [ fmap (("AllowAdminCreateUserOnly",) . toJSON) _cognitoUserPoolAdminCreateUserConfigAllowAdminCreateUserOnly , fmap (("InviteMessageTemplate",) . toJSON) _cognitoUserPoolAdminCreateUserConfigInviteMessageTemplate , fmap (("UnusedAccountValidityDays",) . toJSON) _cognitoUserPoolAdminCreateUserConfigUnusedAccountValidityDays ] -- | Constructor for 'CognitoUserPoolAdminCreateUserConfig' containing -- required fields as arguments. cognitoUserPoolAdminCreateUserConfig :: CognitoUserPoolAdminCreateUserConfig cognitoUserPoolAdminCreateUserConfig = CognitoUserPoolAdminCreateUserConfig { _cognitoUserPoolAdminCreateUserConfigAllowAdminCreateUserOnly = Nothing , _cognitoUserPoolAdminCreateUserConfigInviteMessageTemplate = Nothing , _cognitoUserPoolAdminCreateUserConfigUnusedAccountValidityDays = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-allowadmincreateuseronly cupacucAllowAdminCreateUserOnly :: Lens' CognitoUserPoolAdminCreateUserConfig (Maybe (Val Bool)) cupacucAllowAdminCreateUserOnly = lens _cognitoUserPoolAdminCreateUserConfigAllowAdminCreateUserOnly (\s a -> s { _cognitoUserPoolAdminCreateUserConfigAllowAdminCreateUserOnly = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-invitemessagetemplate cupacucInviteMessageTemplate :: Lens' CognitoUserPoolAdminCreateUserConfig (Maybe CognitoUserPoolInviteMessageTemplate) cupacucInviteMessageTemplate = lens _cognitoUserPoolAdminCreateUserConfigInviteMessageTemplate (\s a -> s { _cognitoUserPoolAdminCreateUserConfigInviteMessageTemplate = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-unusedaccountvaliditydays cupacucUnusedAccountValidityDays :: Lens' CognitoUserPoolAdminCreateUserConfig (Maybe (Val Double)) cupacucUnusedAccountValidityDays = lens _cognitoUserPoolAdminCreateUserConfigUnusedAccountValidityDays (\s a -> s { _cognitoUserPoolAdminCreateUserConfigUnusedAccountValidityDays = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/CognitoUserPoolAdminCreateUserConfig.hs
mit
3,415
0
12
252
349
200
149
33
1
{-# LANGUAGE DeriveGeneric #-} module Web.Google.Calendar.User where import Data.Text (Text) import GHC.Generics data User = User { id :: Text, email :: Text, displayName :: Text, self :: Bool } deriving (Show, Eq, Generic, Ord)
tippenein/google-calendar
src/Web/Google/Calendar/User.hs
mit
263
0
8
69
76
47
29
10
0
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module JobApplication.Types ( Applicant(..) , ApplicantResponse(..) ) where import Data.Aeson import Data.SafeCopy import Data.Text import Data.Typeable import GHC.Generics instance SafeCopy Applicant where putCopy Applicant{..} = contain $ do safePut name; safePut email; safePut resume; safePut github; safePut website; getCopy = contain $ Applicant <$> safeGet <*> safeGet <*> safeGet <*> safeGet <*> safeGet data Applicant = Applicant { name :: Text, email :: Text, resume :: Text, github :: Maybe Text, website :: Maybe Text } deriving (Show, Eq, Ord, Typeable, ToJSON, FromJSON, Generic) data ApplicantResponse = ApplicantResponse { message :: Text } deriving (Show, Generic, FromJSON, ToJSON)
tippenein/job-application
src/JobApplication/Types.hs
mit
882
0
11
165
251
139
112
26
0
{-# LANGUAGE TemplateHaskell #-} module NPDA.Konfiguration where import NPDA.Type import Autolib.ToDoc import Autolib.Set import Data.Typeable data Konfiguration x y z = Konfiguration { schritt :: Int , eingabe :: [ x ] , zustand :: z , keller :: [ y ] , link :: Maybe (Konfiguration x y z) } deriving ( Typeable ) instance NPDAC x y z => ToDoc (Konfiguration x y z) where toDoc k = named_dutch_record (text "Konfiguration") [ text "schritt" <+.> equals <+.> toDoc (schritt k) , text "eingabe" <+.> equals <+.> toDoc (eingabe k) , text "zustand" <+.> equals <+.> toDoc (zustand k) , text "keller" <+.> equals <+.> toDoc (keller k) ] -- keine Reader/Read-Instanzen doclinks :: NPDAC x y z => Konfiguration x y z -> Doc doclinks = fsep . map toDoc . links --------------------------------------------------------------------------- wesentlich k = (eingabe k, zustand k, keller k) -- aber link nicht instance (Eq x, Eq y, Eq z) => Eq (Konfiguration x y z) where k1 == k2 = wesentlich k1 == wesentlich k2 instance (Ord x, Ord y, Ord z) => Ord (Konfiguration x y z) where k1 `compare` k2 = wesentlich k1 `compare` wesentlich k2 links :: Konfiguration x y z -> [ Konfiguration x y z ] links k = k : case link k of Just k' -> links k'; Nothing -> [] start_konfiguration :: NPDAC x y z => NPDA x y z -> [x] -> Konfiguration x y z start_konfiguration a xs = Konfiguration { schritt = 0 , eingabe = xs , zustand = startzustand a , keller = [ startsymbol a ] , link = Nothing } leere_keller_konfigurationen :: NPDAC x y z => NPDA x y z -> Set (Konfiguration x y z) leere_keller_konfigurationen a = mkSet $ do z <- setToList $ zustandsmenge a return $ Konfiguration { schritt = 0 -- ?? , eingabe = [] , keller = [] , zustand = z , link = Nothing }
marcellussiegburg/autotool
collection/src/NPDA/Konfiguration.hs
gpl-2.0
1,903
64
10
494
694
365
329
47
2
module Test where { f x = case x of {0 -> case x of {0->1};2->3}; }
bredelings/BAli-Phy
tests/optimizer/4/test.hs
gpl-2.0
68
0
10
17
46
28
18
2
2
{-# OPTIONS_GHC -optc-DDBUS_API_SUBJECT_TO_CHANGE #-} {-# LINE 1 "DBus/Shared.hsc" #-} -- HDBus -- Haskell bindings for D-Bus. {-# LINE 2 "DBus/Shared.hsc" #-} -- Copyright (C) 2006 Evan Martin <[email protected]> -- tell Haddock not to doc this module: -- #hide {-# LINE 8 "DBus/Shared.hsc" #-} {-# LINE 9 "DBus/Shared.hsc" #-} module DBus.Shared ( -- * Constants -- |Well-known service, path, and interface names. ServiceName, PathName, InterfaceName, serviceDBus, pathDBus, pathLocal, interfaceDBus, interfaceIntrospectable, interfaceLocal, ) where import Foreign import Foreign.C.String type ServiceName = String type PathName = FilePath type InterfaceName = String serviceDBus :: ServiceName pathDBus, pathLocal :: PathName interfaceDBus, interfaceIntrospectable, interfaceLocal :: InterfaceName serviceDBus = "org.freedesktop.DBus" {-# LINE 30 "DBus/Shared.hsc" #-} pathDBus = "/org/freedesktop/DBus" {-# LINE 31 "DBus/Shared.hsc" #-} pathLocal = "/org/freedesktop/DBus/Local" {-# LINE 32 "DBus/Shared.hsc" #-} interfaceDBus = "org.freedesktop.DBus" {-# LINE 33 "DBus/Shared.hsc" #-} interfaceIntrospectable = "org.freedesktop.DBus.Introspectable" {-# LINE 34 "DBus/Shared.hsc" #-} interfaceLocal = "org.freedesktop.DBus.Local" {-# LINE 35 "DBus/Shared.hsc" #-} -- vim: set ts=2 sw=2 tw=72 et ft=haskell :
hamaxx/unity-2d-for-xmonad
xmonad-files/DBus-0.4/dist/build/DBus/Shared.hs
gpl-3.0
1,340
0
4
185
132
93
39
21
1
module HEP.Automation.MadGraph.Dataset.Set20110316set11 where import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.Cluster import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Dataset.Common my_ssetup :: ScriptSetup my_ssetup = SS { scriptbase = "/nobackup/iankim/nfs/workspace/ttbar/mc_script/" , mg5base = "/nobackup/iankim/montecarlo/MG_ME_V4.4.44/MadGraph5_v0_6_1/" , workbase = "/nobackup/iankim/nfs/workspace/ttbar/mc/" } ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 1.2 , uc_etcutlep = 18.0 , uc_etacutjet = 2.5 , uc_etcutjet = 15.0 } processTTBar0or1jet :: [Char] processTTBar0or1jet = "\ngenerate P P > t t~ QED=99 @1 \nadd process P P > t t~ J QED=99 @2 \n" psetup_six_ttbar01j :: ProcessSetup psetup_six_ttbar01j = PS { mversion = MadGraph5 , model = Six , process = processTTBar0or1jet , processBrief = "ttbar01j" , workname = "316Six1JBig" } my_csetup :: ClusterSetup my_csetup = CS { cluster = Parallel 10 } sixparamset :: [Param] sixparamset = [ SixParam mass g | mass <- [1400.0] , g <- [4.0] ] psetuplist :: [ProcessSetup] psetuplist = [ psetup_six_ttbar01j ] sets :: [Int] sets = [35,36,37] sixtasklist :: [WorkSetup] sixtasklist = [ WS my_ssetup (psetup_six_ttbar01j) (rsetupGen p MLM (UserCutDef ucut) RunPGS 100000 num) my_csetup | p <- sixparamset , num <- sets ] totaltasklist :: [WorkSetup] totaltasklist = sixtasklist
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110316set11.hs
gpl-3.0
1,697
0
10
409
360
222
138
46
1
import Algorithms.Hungarian import Criterion.Main import Data.Algorithm.Munkres import Data.Array.Unboxed import System.Random sample :: [Double] sample = take 2000 $ randomRs (-100, 100) (mkStdGen 4) sample' :: [Double] sample' = take 40000 $ randomRs (-1000, 1000) (mkStdGen 24) sampleArray :: UArray (Int, Int) Double sampleArray = listArray ((1,1), (40,50)) sample sampleArray' :: UArray (Int, Int) Double sampleArray' = listArray ((1,1), (200,200)) sample' main :: IO () main = defaultMain [ bgroup "Hungarian Algorithm Benchmarks" [ bench "C version (40 * 50)" $ nf (\x -> hungarian x 40 50) sample , bench "Pure Haskell (40 * 50)" $ nf hungarianMethodDouble sampleArray , bench "C version (200 * 200)" $ nf (\x -> hungarian x 200 200) sample' , bench "Pure Haskell (200 * 200)" $ nf hungarianMethodDouble sampleArray' ] ]
kaizhang/hungarian-munkres
benchmarks/bench.hs
gpl-3.0
883
0
13
182
310
168
142
20
1
module Language.Mulang.Parsers.JavaScript (js, js', parseJavaScript) where import Language.Mulang.Ast import Language.Mulang.Ast.Operator (Operator (..)) import Language.Mulang.Builder (compact, compactMap) import Language.Mulang.Parsers import Language.Mulang.Transform.Normalizer (normalize) import Language.Mulang.Normalizers.JavaScript (javaScriptNormalizationOptions ) import Language.JavaScript.Parser.Parser (parse) import Language.JavaScript.Parser.AST import Data.Either () import Data.List (partition) import Data.List.Extra (headOrElse) import Data.Function.Extra ((<==)) import Control.Fallible js :: Parser js = normalize javaScriptNormalizationOptions . js' js' :: Parser js' = orFail . parseJavaScript' parseJavaScript :: MaybeParser parseJavaScript = orNothing . parseJavaScript' parseJavaScript' :: String -> Either String Expression parseJavaScript' = fmap muJSAST . (`parse` "src") muJSAST:: JSAST -> Expression muJSAST (JSAstProgram statements _) = compactMap muJSStatement statements muJSAST (JSAstStatement statement _) = muJSStatement statement muJSAST (JSAstExpression expression _) = muJSExpression expression muJSAST (JSAstLiteral expression _) = muJSExpression expression muJSStatement:: JSStatement -> Expression muJSStatement (JSStatementBlock _ statements _ _) = compactMap muJSStatement statements --muJSStatement (JSConstant _ (JSCommaList JSExpression) _) -- ^const, decl, autosemi muJSStatement (JSDoWhile _ statement _ _ expression _ _) = While (muJSExpression expression) (muJSStatement statement) muJSStatement (JSForLetIn _ _ _ (JSVarInitExpression id _) _ gen _ body) = muForIn VariablePattern id gen body muJSStatement (JSForIn _ _ id _ gen _ body) = muForIn muJsVarPattern id gen body muJSStatement (JSForVarIn _ _ _ (JSVarInitExpression id _) _ gen _ body) = muForIn muJsVarPattern id gen body muJSStatement (JSFor _ _ inits _ conds _ progs _ body) = muFor inits conds progs body muJSStatement (JSForVar _ _ _ inits _ conds _ progs _ body) = muFor inits conds progs body muJSStatement (JSForLet _ _ _ inits _ conds _ progs _ body) = muFor inits conds progs body muJSStatement (JSForConstOf _ _ _ (JSVarInitExpression id _) _ gen _ body) = muForOf ConstantPattern id gen body muJSStatement (JSForLetOf _ _ _ (JSVarInitExpression id _) _ gen _ body) = muForOf VariablePattern id gen body muJSStatement (JSForOf _ _ id _ gen _ body) = muForOf muJsVarPattern id gen body muJSStatement (JSForVarOf _ _ _ (JSVarInitExpression id _) _ gen _ body) = muForOf muJsVarPattern id gen body muJSStatement (JSFunction _ ident _ params _ body _) = muComputation ident params body muJSStatement (JSIf _ _ expression _ statement) = If (muJSExpression expression) (muJSStatement statement) None muJSStatement (JSIfElse _ _ expression _ ifStatement _ elseStatement) = If (muJSExpression expression) (muJSStatement ifStatement) (muJSStatement elseStatement) muJSStatement (JSLabelled _ _ statement) = muJSStatement statement muJSStatement (JSEmptyStatement _) = None muJSStatement (JSExpressionStatement (JSIdentifier _ val) _) = Reference val muJSStatement (JSExpressionStatement expression _) = muJSExpression expression muJSStatement (JSAssignStatement to op value _) = muAssignment to op (muJSExpression value) muJSStatement (JSMethodCall (JSMemberDot receptor _ message) _ params _ _) = muSend receptor message params muJSStatement (JSMethodCall ident _ params _ _) = normalizeReference $ Application (muJSExpression ident) (muJSExpressionList params) muJSStatement (JSReturn _ maybeExpression _) = Return (maybe None muJSExpression maybeExpression) muJSStatement (JSSwitch _ _ expression _ _ cases _ _) = muSwitch expression . partition isDefault $ cases muJSStatement (JSThrow _ expression _) = Raise (muJSExpression expression) muJSStatement (JSTry _ block catches finally) = Try (muJSBlock block) (map muJSTryCatch catches) (muJSTryFinally finally) muJSStatement (JSVariable _ list _) = muLValue (other "JSVar" <== Variable) list muJSStatement (JSLet _ list _) = muLValue Variable list muJSStatement (JSConstant _ list _) = muLValue Constant list muJSStatement (JSWhile _ _ expression _ statement) = While (muJSExpression expression) (muJSStatement statement) muJSStatement e = debug e normalizeReference (SimpleSend (Reference "console") "log" [value]) = Print value normalizeReference (SimpleSend (Reference "assert") "equals" [expected, actual]) = Assert False $ Equality expected actual normalizeReference (SimpleSend (Reference "assert") "notEquals" [expected, actual]) = Assert True $ Equality expected actual normalizeReference (SimpleSend (Reference "assert") "throws" [block, error]) = Assert False $ Failure block error normalizeReference (SimpleSend list "push" [value]) = Application (Primitive Push) [list, value] normalizeReference (Application (Reference "assert") [expression]) = Assert False $ Truth expression normalizeReference (Application (Reference "describe") [description, Lambda [] e]) = TestGroup description e normalizeReference (Application (Reference "context") [description, Lambda [] e]) = TestGroup description e normalizeReference (Application (Reference "it") [description, Lambda [] e]) = Test description e normalizeReference e = e muAssignment (JSIdentifier _ name) op value = Assignment name (muJSAssignOp op name value) muAssignment (JSMemberDot e _ (JSIdentifier _ name)) op value = muFieldAssignment e name op value muAssignment (JSCallExpressionDot e _ (JSIdentifier _ name)) op value = muFieldAssignment e name op value muAssignment other op value = MuTuple [debug other, debug op, debug value] muLValue :: (Identifier -> Expression -> Expression) -> JSCommaList JSExpression -> Expression muLValue kind = compact . mapJSList f where f (JSVarInitExpression (JSIdentifier _ name) initial) = kind name (muJSVarInitializer initial) mapJSList :: (a -> b) -> JSCommaList a -> [b] mapJSList f = map f . muJSCommaList muJSExpressionList :: JSCommaList JSExpression -> [Expression] muJSExpressionList = mapJSList muJSExpression muJSPatternList :: JSCommaList JSExpression -> [Pattern] muJSPatternList = mapJSList muExpressionPattern muJSExpressionFromList = compact . muJSExpressionList muJsVarPattern = otherPattern "JSVar" . VariablePattern muFor inits conds progs body = (ForLoop (muJSExpressionFromList inits) (muJSExpressionFromList conds) (muJSExpressionFromList progs) (muJSStatement body)) muForOf kind (JSIdentifier _ id) generator body = (For [Generator (kind id) (muJSExpression generator)] (muJSStatement body)) muForIn kind id generator body = other "JSForIn" $ muForOf kind id generator body muSwitch expression (def, cases) = Switch (muJSExpression expression) (map muCase cases) (headOrElse None . map muDefault $ def) muCase (JSCase _ expression _ statements) = (muJSExpression expression, compactMap muJSStatement statements) muDefault (JSDefault _ _ statements) = compactMap muJSStatement statements muComputation :: JSIdent -> JSCommaList JSExpression -> JSBlock -> Expression muComputation JSIdentNone params body = Lambda (muJSPatternList params) (muJSBlock body) muComputation (JSIdentName _ name) params body = (computationFor (muJSBlock body)) name (muEquation (muJSPatternList params) (muJSBlock body)) isDefault:: JSSwitchParts -> Bool isDefault (JSDefault _ _ _) = True isDefault _ = False muIdentPattern :: JSIdent -> Pattern muIdentPattern (JSIdentName _ name) = VariablePattern name muExpressionPattern :: JSExpression -> Pattern muExpressionPattern (JSIdentifier _ name) = VariablePattern name muExpressionPattern other = debugPattern other muEquation :: [Pattern] -> Expression -> SubroutineBody muEquation params body = [SimpleEquation params body] computationFor :: Expression -> Identifier -> [Equation] -> Expression computationFor body | containsReturn body = Function | otherwise = Procedure containsReturn :: Expression -> Bool containsReturn (Return _) = True containsReturn (Sequence xs) = any containsReturn xs containsReturn _ = False muFieldReference :: JSExpression -> String -> Expression muFieldReference e "length" = Application (Primitive Size) [(muJSExpression e)] muFieldReference e other = FieldReference (muJSExpression e) other muFieldAssignment :: JSExpression -> String -> JSAssignOp -> Expression -> Expression muFieldAssignment e name op value = FieldAssignment (muJSExpression e) name (muJSAssignOp op name value) muSend :: JSExpression -> JSExpression -> JSCommaList JSExpression -> Expression muSend r m ps = normalizeReference $ Send (muJSExpression r) (muJSExpression m) (muJSExpressionList ps) muJSExpression:: JSExpression -> Expression muJSExpression (JSIdentifier _ "undefined") = None muJSExpression (JSIdentifier _ name) = Reference name muJSExpression (JSDecimal _ val) = muDecimal val muJSExpression (JSLiteral _ "null") = MuNil muJSExpression (JSLiteral _ "true") = MuTrue muJSExpression (JSLiteral _ "false") = MuFalse muJSExpression (JSLiteral _ "this") = Self --muJSExpression (JSHexInteger _ String) --muJSExpression (JSOctal _ String) muJSExpression (JSStringLiteral _ val) = MuString (removeQuotes val) --muJSExpression (JSRegEx _ String) muJSExpression (JSArrayLiteral _ list _) = MuList (muJSArrayList list) muJSExpression (JSAssignExpression (JSIdentifier _ name) op value) = Assignment name (muJSAssignOp op name.muJSExpression $ value) muJSExpression (JSMemberExpression (JSMemberDot r _ m) _ ps _) = muSend r m ps muJSExpression (JSCallExpression (JSCallExpressionDot r _ m) _ ps _)= muSend r m ps muJSExpression (JSMemberDot e _ (JSIdentifier _ field)) = muFieldReference e field muJSExpression (JSCallExpressionDot e _ (JSIdentifier _ field)) = muFieldReference e field --muJSExpression (JSCallExpressionSquare JSExpression _ JSExpression _) -- ^expr, [, expr, ] --muJSExpression (JSCommaExpression JSExpression _ JSExpression) -- ^expression components muJSExpression (JSExpressionBinary firstVal op secondVal) = Application (muJSBinOp op) [muJSExpression firstVal, muJSExpression secondVal] muJSExpression (JSExpressionParen _ expression _) = muJSExpression expression muJSExpression (JSExpressionPostfix (JSIdentifier _ name) op) = Assignment name (muJSUnaryOp op name) muJSExpression (JSExpressionTernary condition _ trueVal _ falseVal) = If (muJSExpression condition) (muJSExpression trueVal) (muJSExpression falseVal) muJSExpression (JSFunctionExpression _ ident _ params _ body) = muComputation ident params body muJSExpression (JSArrowExpression params _ body) = Lambda (muJSArrowParameterList params) (muJSStatement body) muJSExpression (JSMemberExpression id _ params _) = Application (muJSExpression id) (muJSExpressionList params) muJSExpression (JSMemberNew _ (JSIdentifier _ name) _ args _) = New (Reference name) (muJSExpressionList args) muJSExpression (JSMemberSquare receptor _ index _) = Application (Primitive GetAt) [muJSExpression receptor, muJSExpression index] muJSExpression (JSNewExpression _ (JSIdentifier _ name)) = New (Reference name) [] muJSExpression (JSObjectLiteral _ propertyList _) = MuObject (compactMap muJSObjectProperty . muJSCommaTrailingList $ propertyList) muJSExpression (JSUnaryExpression (JSUnaryOpNot _) e) = Application (Primitive Negation) [muJSExpression e] muJSExpression (JSUnaryExpression op (JSIdentifier _ name)) = Assignment name (muJSUnaryOp op name) muJSExpression (JSVarInitExpression (JSIdentifier _ name) initial) = Variable name (muJSVarInitializer initial) muJSExpression e = debug e removeQuotes = filter (flip notElem quoteMarks) where quoteMarks = "\"'" muJSBinOp:: JSBinOp -> Expression muJSBinOp (JSBinOpAnd _) = Primitive And muJSBinOp (JSBinOpBitAnd _) = Primitive BitwiseAnd muJSBinOp (JSBinOpBitOr _) = Primitive BitwiseOr muJSBinOp (JSBinOpBitXor _) = Primitive BitwiseXor muJSBinOp (JSBinOpDivide _) = Primitive Divide muJSBinOp (JSBinOpEq _) = Primitive Similar muJSBinOp (JSBinOpGe _) = Primitive GreatherOrEqualThan muJSBinOp (JSBinOpGt _) = Primitive GreatherThan muJSBinOp (JSBinOpInstanceOf _) = Reference "instanceof" muJSBinOp (JSBinOpLe _) = Primitive LessOrEqualThan muJSBinOp (JSBinOpLsh _) = Primitive BitwiseLeftShift muJSBinOp (JSBinOpLt _) = Primitive LessThan muJSBinOp (JSBinOpMinus _) = Primitive Minus muJSBinOp (JSBinOpMod _) = Primitive Modulo muJSBinOp (JSBinOpNeq _) = Primitive NotSimilar muJSBinOp (JSBinOpOr _) = Primitive Or muJSBinOp (JSBinOpPlus _) = Primitive Plus muJSBinOp (JSBinOpRsh _) = Primitive BitwiseRightShift muJSBinOp (JSBinOpStrictEq _) = Primitive Equal muJSBinOp (JSBinOpStrictNeq _) = Primitive NotEqual muJSBinOp (JSBinOpTimes _) = Primitive Multiply muJSUnaryOp:: JSUnaryOp -> Identifier -> Expression muJSUnaryOp (JSUnaryOpDecr _) r = (Application (Primitive Minus) [Reference r, MuNumber 1]) --muJSUnaryOp (JSUnaryOpDelete _) muJSUnaryOp (JSUnaryOpIncr _) r = (Application (Primitive Plus) [Reference r, MuNumber 1]) --muJSUnaryOp (JSUnaryOpMinus _) --muJSUnaryOp (JSUnaryOpPlus _) --muJSUnaryOp (JSUnaryOpTilde _) --muJSUnaryOp (JSUnaryOpTypeof _) --muJSUnaryOp (JSUnaryOpVoid _) muJSUnaryOp e _ = debug e muJSAssignOp:: JSAssignOp -> Identifier -> Expression -> Expression muJSAssignOp (JSAssign _) _ v = v muJSAssignOp op r v = (Application (muJSAssignOp' op) [Reference r, v]) muJSAssignOp':: JSAssignOp -> Expression muJSAssignOp' (JSTimesAssign _) = Primitive Multiply muJSAssignOp' (JSDivideAssign _) = Primitive Divide --muJSAssignOp' (JSModAssign _) muJSAssignOp' (JSPlusAssign _) = Primitive Plus muJSAssignOp' (JSMinusAssign _) = Primitive Minus --muJSAssignOp' (JSLshAssign _) --muJSAssignOp' (JSRshAssign _) --muJSAssignOp' (JSUrshAssign _) muJSAssignOp' (JSBwAndAssign _) = Reference "&" muJSAssignOp' (JSBwXorAssign _) = Reference "^" muJSAssignOp' (JSBwOrAssign _) = Reference "|" muJSAssignOp' e = debug e muJSTryCatch:: JSTryCatch -> (Pattern, Expression) muJSTryCatch (JSCatch _ _ (JSIdentifier _ name) _ block) = (VariablePattern name, muJSBlock block) --muJSTryCatch JSCatchIf _ _ JSExpression _ JSExpression _ JSBlock -- ^catch,lb,ident,if,expr,rb,block muJSTryCatch e = (WildcardPattern, debug e) muJSTryFinally:: JSTryFinally -> Expression muJSTryFinally (JSFinally _ block) = muJSBlock block muJSTryFinally JSNoFinally = None muJSBlock:: JSBlock -> Expression muJSBlock (JSBlock _ statements _) = compactMap muJSStatement statements muJSVarInitializer:: JSVarInitializer -> Expression muJSVarInitializer (JSVarInit _ expression) = muJSExpression expression --muJSVarInitializer JSVarInitNone muJSVarInitializer e = debug e muJSObjectProperty:: JSObjectProperty -> Expression --muJSObjectProperty JSPropertyAccessor JSAccessor JSPropertyName _ [JSExpression] _ JSBlock -- ^(get|set), name, lb, params, rb, block muJSObjectProperty (JSPropertyNameandValue id _ [JSFunctionExpression _ _ _ params _ block]) = Method (muJSPropertyName id) (muEquation (muJSPatternList params) (muJSBlock block)) muJSObjectProperty (JSPropertyNameandValue id _ [expression]) = Variable (muJSPropertyName id) (muJSExpression expression) muJSObjectProperty e = debug e muJSPropertyName:: JSPropertyName -> Identifier muJSPropertyName = removeQuotes.muJSPropertyName' muJSPropertyName':: JSPropertyName -> Identifier muJSPropertyName' (JSPropertyIdent _ name) = name muJSPropertyName' (JSPropertyString _ name) = name muJSPropertyName' (JSPropertyNumber _ name) = name muJSArrayList:: [JSArrayElement] -> [Expression] muJSArrayList list = [muJSExpression expression | (JSArrayElement expression) <- list] muJSCommaList:: JSCommaList a -> [a] muJSCommaList (JSLCons xs _ x) = muJSCommaList xs ++ [x] muJSCommaList (JSLOne x) = [x] muJSCommaList JSLNil = [] muJSCommaTrailingList:: JSCommaTrailingList a -> [a] muJSCommaTrailingList (JSCTLComma list _) = muJSCommaList list muJSCommaTrailingList (JSCTLNone list) = muJSCommaList list muJSArrowParameterList :: JSArrowParameterList -> [Pattern] muJSArrowParameterList (JSUnparenthesizedArrowParameter ident) = [muIdentPattern ident] muJSArrowParameterList (JSParenthesizedArrowParameterList _ params _) = muJSPatternList params muDecimal s@('.':_) = muDecimal ('0':s) muDecimal str = decode (reads str) where decode [(n, "")] = MuNumber n decode [(n, ".")] = MuNumber n decode [(n, s)] = other ("JSDecimal:" ++ s) (MuNumber n) decode _ = debug ("JSDecimal:" ++ str)
mumuki/mulang
src/Language/Mulang/Parsers/JavaScript.hs
gpl-3.0
18,526
0
11
4,322
5,217
2,613
2,604
232
4
import Distribution.Simple import Distribution.Simple.Setup import Distribution.Simple.Program import Distribution.Simple.Program.Types import Distribution.Simple.Utils import Distribution.Verbosity import Distribution.PackageDescription import System.FilePath import System.Process import System.Exit main = defaultMainWithHooks $ simpleUserHooks { hookedPrograms = [], --scons : hookedPrograms simpleUserHooks, preConf = sconsPreConf -- >> (preConf simpleUserHooks) a c } sconsPreConf :: Args -> ConfigFlags -> IO HookedBuildInfo sconsPreConf args cf = do let flags = configConfigurationsFlags cf mf = lookup (FlagName "build_lapacke") flags case mf of Just True -> invokeScons _ -> return (Nothing, []) invokeScons = do let lapackeDir = currentDir </> "lapacke" msl <- programFindLocation scons verbose let mSconsInvoke = msl >>= \sl -> return (simpleConfiguredProgram "scons" (FoundOnSystem sl)) >>= \confScons -> return (programInvocation confScons []) >>= \sconsInvoke -> return (sconsInvoke { progInvokeCwd = Just lapackeDir }) success <- case mSconsInvoke of Just sconsInvoke -> callProgram (progInvokePath sconsInvoke) [] (progInvokeCwd sconsInvoke) -- runProgramInvocation deafening sconsInvoke -- This is apparently not implemented in cabal. _ -> die "*** Running scons has failed while trying to build LAPACKE. Is scons installed?" >> return False return $ if success then (Just (emptyBuildInfo { buildable = True }), []) else (Just (emptyBuildInfo { buildable = False }), []) callProgram :: FilePath -> [String] -> Maybe FilePath -> IO Bool callProgram prog args cwd = do h <- runProcess prog args cwd Nothing Nothing Nothing Nothing e <- waitForProcess h return $ e == ExitSuccess findScons :: Verbosity -> IO (Maybe FilePath) findScons verb = do let locs = ["/usr/bin","/usr/local/bin","/usr/sbin","/usr/local/sbin"] ml <- mapM (findProgramLocation verb) locs return $ firstJust ml scons :: Program scons = simpleProgram "scons" firstJust :: [Maybe a] -> Maybe a firstJust [] = Nothing firstJust (Just a:as) = Just a firstJust (_:as) = firstJust as
cgo/jalla
Setup.hs
gpl-3.0
2,270
0
20
486
636
326
310
54
3
{-# LANGUAGE TemplateHaskell #-} module Main where import Test.Framework.TH import Test.Framework import Test.HUnit import Test.Framework.Providers.HUnit import Language.C2ATS main :: IO () main = $(defaultMainGenerator) case_1 = 1 @=? 1
metasepi/c2ats
test/Main.hs
gpl-3.0
242
0
6
33
61
37
24
10
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.SafeBrowsing -- 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) -- -- Enables client applications to check web resources (most commonly URLs) -- against Google-generated lists of unsafe web resources. -- -- /See:/ <https://developers.google.com/safe-browsing/ Safe Browsing APIs Reference> module Network.Google.SafeBrowsing ( -- * Service Configuration safeBrowsingService -- * API Declaration , SafeBrowsingAPI -- * Resources -- ** safebrowsing.fullHashes.find , module Network.Google.Resource.SafeBrowsing.FullHashes.Find -- ** safebrowsing.threatListUpdates.fetch , module Network.Google.Resource.SafeBrowsing.ThreatListUpdates.Fetch -- ** safebrowsing.threatLists.list , module Network.Google.Resource.SafeBrowsing.ThreatLists.List -- ** safebrowsing.threatMatches.find , module Network.Google.Resource.SafeBrowsing.ThreatMatches.Find -- * Types -- ** ThreatEntryMetadata , ThreatEntryMetadata , threatEntryMetadata , temEntries -- ** Checksum , Checksum , checksum , cSha256 -- ** FindThreatMatchesResponse , FindThreatMatchesResponse , findThreatMatchesResponse , ftmrMatches -- ** ThreatInfo , ThreatInfo , threatInfo , tiThreatEntries , tiThreatTypes , tiPlatformTypes , tiThreatEntryTypes -- ** FetchThreatListUpdatesRequest , FetchThreatListUpdatesRequest , fetchThreatListUpdatesRequest , ftlurListUpdateRequests , ftlurClient -- ** FindFullHashesRequest , FindFullHashesRequest , findFullHashesRequest , ffhrThreatInfo , ffhrClientStates , ffhrClient -- ** Constraints , Constraints , constraints , cMaxUpdateEntries , cRegion , cSupportedCompressions , cMaxDatabaseEntries -- ** RiceDeltaEncoding , RiceDeltaEncoding , riceDeltaEncoding , rdeFirstValue , rdeRiceParameter , rdeNumEntries , rdeEncodedData -- ** ListThreatListsResponse , ListThreatListsResponse , listThreatListsResponse , ltlrThreatLists -- ** ThreatListDescriptor , ThreatListDescriptor , threatListDescriptor , tldThreatEntryType , tldThreatType , tldPlatformType -- ** ClientInfo , ClientInfo , clientInfo , ciClientId , ciClientVersion -- ** FindThreatMatchesRequest , FindThreatMatchesRequest , findThreatMatchesRequest , ftmrThreatInfo , ftmrClient -- ** ListUpdateRequest , ListUpdateRequest , listUpdateRequest , lurState , lurThreatEntryType , lurConstraints , lurThreatType , lurPlatformType -- ** ThreatEntry , ThreatEntry , threatEntry , teHash , teURL , teDigest -- ** ThreatMatch , ThreatMatch , threatMatch , tmThreatEntryMetadata , tmThreatEntryType , tmThreatType , tmPlatformType , tmCacheDuration , tmThreat -- ** RawHashes , RawHashes , rawHashes , rhPrefixSize , rhRawHashes -- ** ListUpdateResponse , ListUpdateResponse , listUpdateResponse , lAdditions , lThreatEntryType , lChecksum , lThreatType , lPlatformType , lNewClientState , lRemovals , lResponseType -- ** ThreatEntrySet , ThreatEntrySet , threatEntrySet , tesRiceHashes , tesRiceIndices , tesRawHashes , tesRawIndices , tesCompressionType -- ** RawIndices , RawIndices , rawIndices , riIndices -- ** FindFullHashesResponse , FindFullHashesResponse , findFullHashesResponse , ffhrMatches , ffhrNegativeCacheDuration , ffhrMinimumWaitDuration -- ** MetadataEntry , MetadataEntry , metadataEntry , meValue , meKey -- ** FetchThreatListUpdatesResponse , FetchThreatListUpdatesResponse , fetchThreatListUpdatesResponse , ftlurListUpdateResponses , ftlurMinimumWaitDuration ) where import Network.Google.Prelude import Network.Google.Resource.SafeBrowsing.FullHashes.Find import Network.Google.Resource.SafeBrowsing.ThreatLists.List import Network.Google.Resource.SafeBrowsing.ThreatListUpdates.Fetch import Network.Google.Resource.SafeBrowsing.ThreatMatches.Find import Network.Google.SafeBrowsing.Types {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Safe Browsing APIs service. type SafeBrowsingAPI = FullHashesFindResource :<|> ThreatMatchesFindResource :<|> ThreatListUpdatesFetchResource :<|> ThreatListsListResource
rueshyna/gogol
gogol-safebrowsing/gen/Network/Google/SafeBrowsing.hs
mpl-2.0
5,048
0
7
1,190
498
356
142
132
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DNS.Changes.Create -- 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) -- -- Atomically update the ResourceRecordSet collection. -- -- /See:/ <https://developers.google.com/cloud-dns Google Cloud DNS API Reference> for @dns.changes.create@. module Network.Google.Resource.DNS.Changes.Create ( -- * REST Resource ChangesCreateResource -- * Creating a Request , changesCreate , ChangesCreate -- * Request Lenses , ccProject , ccPayload , ccManagedZone , ccClientOperationId ) where import Network.Google.DNS.Types import Network.Google.Prelude -- | A resource alias for @dns.changes.create@ method which the -- 'ChangesCreate' request conforms to. type ChangesCreateResource = "dns" :> "v2beta1" :> "projects" :> Capture "project" Text :> "managedZones" :> Capture "managedZone" Text :> "changes" :> QueryParam "clientOperationId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Change :> Post '[JSON] Change -- | Atomically update the ResourceRecordSet collection. -- -- /See:/ 'changesCreate' smart constructor. data ChangesCreate = ChangesCreate' { _ccProject :: !Text , _ccPayload :: !Change , _ccManagedZone :: !Text , _ccClientOperationId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ChangesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccProject' -- -- * 'ccPayload' -- -- * 'ccManagedZone' -- -- * 'ccClientOperationId' changesCreate :: Text -- ^ 'ccProject' -> Change -- ^ 'ccPayload' -> Text -- ^ 'ccManagedZone' -> ChangesCreate changesCreate pCcProject_ pCcPayload_ pCcManagedZone_ = ChangesCreate' { _ccProject = pCcProject_ , _ccPayload = pCcPayload_ , _ccManagedZone = pCcManagedZone_ , _ccClientOperationId = Nothing } -- | Identifies the project addressed by this request. ccProject :: Lens' ChangesCreate Text ccProject = lens _ccProject (\ s a -> s{_ccProject = a}) -- | Multipart request metadata. ccPayload :: Lens' ChangesCreate Change ccPayload = lens _ccPayload (\ s a -> s{_ccPayload = a}) -- | Identifies the managed zone addressed by this request. Can be the -- managed zone name or id. ccManagedZone :: Lens' ChangesCreate Text ccManagedZone = lens _ccManagedZone (\ s a -> s{_ccManagedZone = a}) -- | For mutating operation requests only. An optional identifier specified -- by the client. Must be unique for operation resources in the Operations -- collection. ccClientOperationId :: Lens' ChangesCreate (Maybe Text) ccClientOperationId = lens _ccClientOperationId (\ s a -> s{_ccClientOperationId = a}) instance GoogleRequest ChangesCreate where type Rs ChangesCreate = Change type Scopes ChangesCreate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/ndev.clouddns.readwrite"] requestClient ChangesCreate'{..} = go _ccProject _ccManagedZone _ccClientOperationId (Just AltJSON) _ccPayload dNSService where go = buildClient (Proxy :: Proxy ChangesCreateResource) mempty
rueshyna/gogol
gogol-dns/gen/Network/Google/Resource/DNS/Changes/Create.hs
mpl-2.0
4,147
0
17
1,008
551
327
224
86
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdExchangeBuyer2.Accounts.Clients.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists all the clients for the current sponsor buyer. -- -- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.accounts.clients.list@. module Network.Google.Resource.AdExchangeBuyer2.Accounts.Clients.List ( -- * REST Resource AccountsClientsListResource -- * Creating a Request , accountsClientsList , AccountsClientsList -- * Request Lenses , aclcXgafv , aclcUploadProtocol , aclcAccessToken , aclcUploadType , aclcAccountId , aclcPartnerClientId , aclcPageToken , aclcPageSize , aclcCallback ) where import Network.Google.AdExchangeBuyer2.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer2.accounts.clients.list@ method which the -- 'AccountsClientsList' request conforms to. type AccountsClientsListResource = "v2beta1" :> "accounts" :> Capture "accountId" (Textual Int64) :> "clients" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "partnerClientId" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListClientsResponse -- | Lists all the clients for the current sponsor buyer. -- -- /See:/ 'accountsClientsList' smart constructor. data AccountsClientsList = AccountsClientsList' { _aclcXgafv :: !(Maybe Xgafv) , _aclcUploadProtocol :: !(Maybe Text) , _aclcAccessToken :: !(Maybe Text) , _aclcUploadType :: !(Maybe Text) , _aclcAccountId :: !(Textual Int64) , _aclcPartnerClientId :: !(Maybe Text) , _aclcPageToken :: !(Maybe Text) , _aclcPageSize :: !(Maybe (Textual Int32)) , _aclcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsClientsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aclcXgafv' -- -- * 'aclcUploadProtocol' -- -- * 'aclcAccessToken' -- -- * 'aclcUploadType' -- -- * 'aclcAccountId' -- -- * 'aclcPartnerClientId' -- -- * 'aclcPageToken' -- -- * 'aclcPageSize' -- -- * 'aclcCallback' accountsClientsList :: Int64 -- ^ 'aclcAccountId' -> AccountsClientsList accountsClientsList pAclcAccountId_ = AccountsClientsList' { _aclcXgafv = Nothing , _aclcUploadProtocol = Nothing , _aclcAccessToken = Nothing , _aclcUploadType = Nothing , _aclcAccountId = _Coerce # pAclcAccountId_ , _aclcPartnerClientId = Nothing , _aclcPageToken = Nothing , _aclcPageSize = Nothing , _aclcCallback = Nothing } -- | V1 error format. aclcXgafv :: Lens' AccountsClientsList (Maybe Xgafv) aclcXgafv = lens _aclcXgafv (\ s a -> s{_aclcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). aclcUploadProtocol :: Lens' AccountsClientsList (Maybe Text) aclcUploadProtocol = lens _aclcUploadProtocol (\ s a -> s{_aclcUploadProtocol = a}) -- | OAuth access token. aclcAccessToken :: Lens' AccountsClientsList (Maybe Text) aclcAccessToken = lens _aclcAccessToken (\ s a -> s{_aclcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). aclcUploadType :: Lens' AccountsClientsList (Maybe Text) aclcUploadType = lens _aclcUploadType (\ s a -> s{_aclcUploadType = a}) -- | Unique numerical account ID of the sponsor buyer to list the clients -- for. aclcAccountId :: Lens' AccountsClientsList Int64 aclcAccountId = lens _aclcAccountId (\ s a -> s{_aclcAccountId = a}) . _Coerce -- | Optional unique identifier (from the standpoint of an Ad Exchange -- sponsor buyer partner) of the client to return. If specified, at most -- one client will be returned in the response. aclcPartnerClientId :: Lens' AccountsClientsList (Maybe Text) aclcPartnerClientId = lens _aclcPartnerClientId (\ s a -> s{_aclcPartnerClientId = a}) -- | A token identifying a page of results the server should return. -- Typically, this is the value of ListClientsResponse.nextPageToken -- returned from the previous call to the accounts.clients.list method. aclcPageToken :: Lens' AccountsClientsList (Maybe Text) aclcPageToken = lens _aclcPageToken (\ s a -> s{_aclcPageToken = a}) -- | Requested page size. The server may return fewer clients than requested. -- If unspecified, the server will pick an appropriate default. aclcPageSize :: Lens' AccountsClientsList (Maybe Int32) aclcPageSize = lens _aclcPageSize (\ s a -> s{_aclcPageSize = a}) . mapping _Coerce -- | JSONP aclcCallback :: Lens' AccountsClientsList (Maybe Text) aclcCallback = lens _aclcCallback (\ s a -> s{_aclcCallback = a}) instance GoogleRequest AccountsClientsList where type Rs AccountsClientsList = ListClientsResponse type Scopes AccountsClientsList = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient AccountsClientsList'{..} = go _aclcAccountId _aclcXgafv _aclcUploadProtocol _aclcAccessToken _aclcUploadType _aclcPartnerClientId _aclcPageToken _aclcPageSize _aclcCallback (Just AltJSON) adExchangeBuyer2Service where go = buildClient (Proxy :: Proxy AccountsClientsListResource) mempty
brendanhay/gogol
gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Accounts/Clients/List.hs
mpl-2.0
6,573
0
20
1,531
988
570
418
140
1
-- The HiPar Toolkit: generates unique names -- -- Author : Manuel M T Chakravarty -- Created: 3 April 98 -- -- Version $Revision: 1.2 $ from $Date: 2004/11/13 17:26:50 $ -- -- Copyright (C) [1998..2003] Manuel M T Chakravarty -- -- This file is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This file is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- --- DESCRIPTION --------------------------------------------------------------- -- -- Generates unqiue names according to a method of L. Augustsson, M. Rittri -- & D. Synek ``Functional pearl: On generating unique names'', Journal of -- Functional Programming 4(1), pp 117-123, 1994. -- -- WARNING: DON'T tinker with the implementation! It uses UNSAFE low-level -- operations! -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- -- * This module provides an ordering relation on names (e.g., for using -- `Maps'), but no assumption maybe made on the order in which names -- are generated from the name space. Furthermore, names are instances of -- `Ix' to allow to use them as indicies. -- -- * A supply should be used *at most* once to *either* split it or extract a -- stream of names. A supply used repeatedly will always generate the same -- set of names (otherwise, the whole thing wouldn't be referential -- transparent). -- -- * If you ignored the warning below, looked at the implementation, and lost -- faith, consider that laziness means call-by-need *and* sharing, and that -- sharing is realized by updating evaluated thunks. -- -- * ATTENTION: No clever CSE or unnecessary argument elimination may be -- applied to the function `names'! -- --- TODO -- module UNames (NameSupply, Name, rootSupply, splitSupply, names, saveRootNameSupply, restoreRootNameSupply) where import Monad (when) import Ix import System.IO.Unsafe (unsafePerformIO) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Binary (Binary(..)) -- Name supply definition (EXPORTED ABSTRACTLY) -- newtype NameSupply = NameSupply (IORef Int) -- Name (EXPORTED ABSTRACTLY) -- newtype Name = Name Int -- deriving (Show, Eq, Ord, Ix) -- FIXME: nhc98, v1.08 can't derive Ix deriving (Eq, Ord) instance Ix Name where range (Name from, Name to) = map Name (range (from, to)) index (Name from, Name to) (Name idx) = index (from, to) idx inRange (Name from, Name to) (Name idx) = inRange (from, to) idx -- we want to show the number only, to be useful for generating unqiue -- printable names -- instance Show Name where show (Name i) = show i -- *** DON'T TOUCH THE FOLLOWING *** -- and if you believe in the lambda calculus better also don't look at it -- ! here lives the daemon of unordered destructive updates ! -- The initial supply (EXPORTED) -- rootSupply :: NameSupply {-# NOINLINE rootSupply #-} rootSupply = NameSupply (unsafeNewIntRef 1) -- Split a name supply into a stream of supplies (EXPORTED) -- splitSupply :: NameSupply -> [NameSupply] splitSupply s = repeat s -- Given a name supply, yield a stream of names (EXPORTED) -- names :: NameSupply -> [Name] -- -- The recursion of `theNames' where `s' is passed as an argument is crucial, -- as it forces the creation of a new closure for `unsafeReadAndIncIntRef s' -- in each recursion step. Sharing a single closure or building a cyclic -- graph for a nullary `theNames' would always result in the same name! If -- the compiler ever gets clever enough to optimize this, we have to prevent -- it from doing so. -- names (NameSupply s) = theNames s where theNames s = Name (unsafeReadAndIncIntRef s) : theNames s -- Actions for saving and restoring the state of the whole program. (EXPORTED) -- The rules for these functions are as follows: -- you must not use the root name supply after saving it -- you must not use the root namue supply before restoring it -- Otherwise bad things will happen, your unique Ids will no longer be unique saveRootNameSupply :: IO Name saveRootNameSupply = case rootSupply of NameSupply ref -> do val <- readIORef ref writeIORef ref (error "UName: root name supply used after saving") return (Name val) restoreRootNameSupply :: Name -> IO () restoreRootNameSupply (Name val) = case rootSupply of NameSupply ref -> do prev <- readIORef ref when (prev /= 1) (error "UName: root name supply used before restoring") writeIORef ref val {-! for Name derive : GhcBinary !-} {-* Generated by DrIFT : Look, but Don't Touch. *-} instance Binary Name where put_ bh (Name aa) = do put_ bh aa get bh = do aa <- get bh return (Name aa) -- UNSAFE mutable variables -- ------------------------ -- WARNING: The following does not exist, or at least, it belongs to another -- world. And if you believe into the lambda calculus, you don't -- want to know about this other world. -- -- *** DON'T TOUCH NOR USE THIS STUFF *** -- (unless you really know what you are doing!) -- UNSAFELY create a mutable integer (EXPORTED) -- unsafeNewIntRef :: Int -> IORef Int unsafeNewIntRef i = unsafePerformIO (newIORef i) -- UNSAFELY increment a mutable integer and yield its value before the -- increment (EXPORTED) -- unsafeReadAndIncIntRef :: IORef Int -> Int unsafeReadAndIncIntRef mv = unsafePerformIO $ do v <- readIORef mv writeIORef mv (v + 1) return v
thiagoarrais/gtk2hs
tools/c2hs/base/general/UNames.hs
lgpl-2.1
5,951
4
12
1,294
748
427
321
-1
-1
-- | The Parser monad. module Data.GI.GIR.Parser ( Parser , ParseError , parseError , runParser , parseName , parseDeprecation , parseDocumentation , parseIntegral , parseBool , parseChildrenWithLocalName , parseAllChildrenWithLocalName , parseChildrenWithNSName , getAttr , getAttrWithNamespace , queryAttr , queryAttrWithNamespace , optionalAttr , currentNamespace , qualifyName , resolveQualifiedTypeName -- Reexported for convenience , Name(..) , Element , GIRXMLNamespace(..) , DeprecationInfo , Documentation ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad.Except import Control.Monad.Reader import Data.Monoid ((<>)) import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.Read as TR import Data.Text (Text) import qualified Text.XML as XML import Text.XML (Element(elementAttributes)) import Text.Show.Pretty (ppShow) import Data.GI.GIR.BasicTypes (Name(..), Alias(..), Type(TInterface)) import Data.GI.GIR.Deprecation (DeprecationInfo, queryDeprecated) import Data.GI.GIR.Documentation (Documentation, queryDocumentation) import Data.GI.GIR.XMLUtils (localName, GIRXMLNamespace(..), childElemsWithLocalName, childElemsWithNSName, lookupAttr, lookupAttrWithNamespace) -- | Info to carry around when parsing. data ParseContext = ParseContext { ctxNamespace :: Text, -- Location in the XML tree of the node being parsed (for -- debugging purposes). treePosition :: [Text], -- Current element being parsed (to be set by withElement) currentElement :: Element, knownAliases :: M.Map Alias Type } deriving Show -- | A message describing a parsing error in human readable form. type ParseError = Text -- | Monad where parsers live: we carry a context around, and can -- throw errors that abort the parsing. type Parser a = ReaderT ParseContext (Except ParseError) a -- | Throw a parse error. parseError :: ParseError -> Parser a parseError msg = do ctx <- ask let position = (T.intercalate " / " . reverse . treePosition) ctx throwError $ "Error when parsing \"" <> position <> "\": " <> msg <> "\n" <> (T.pack . ppShow . currentElement) ctx -- | Build a textual description (for debug purposes) of a given element. elementDescription :: Element -> Text elementDescription element = case M.lookup "name" (elementAttributes element) of Nothing -> localName element Just n -> localName element <> " [" <> n <> "]" -- | Build a name in the current namespace. nameInCurrentNS :: Text -> Parser Name nameInCurrentNS n = do ctx <- ask return $ Name (ctxNamespace ctx) n -- | Return the current namespace. currentNamespace :: Parser Text currentNamespace = ctxNamespace <$> ask -- | Check whether there is an alias for the given name, and return -- the corresponding type in case it exists, and otherwise a TInterface. resolveQualifiedTypeName :: Name -> Parser Type resolveQualifiedTypeName name = do ctx <- ask case M.lookup (Alias name) (knownAliases ctx) of -- The resolved type may be an alias itself, like for -- Gtk.Allocation -> Gdk.Rectangle -> cairo.RectangleInt Just (TInterface n) -> resolveQualifiedTypeName n Just t -> return t Nothing -> return $ TInterface name -- | Return the value of an attribute for the given element. If the -- attribute is not present this throws an error. getAttr :: XML.Name -> Parser Text getAttr attr = do ctx <- ask case lookupAttr attr (currentElement ctx) of Just val -> return val Nothing -> parseError $ "Expected attribute \"" <> (T.pack . show) attr <> "\" not present." -- | Like 'getAttr', but allow for specifying the namespace. getAttrWithNamespace :: GIRXMLNamespace -> XML.Name -> Parser Text getAttrWithNamespace ns attr = do ctx <- ask case lookupAttrWithNamespace ns attr (currentElement ctx) of Just val -> return val Nothing -> parseError $ "Expected attribute \"" <> (T.pack . show) attr <> "\" in namespace \"" <> (T.pack . show) ns <> "\" not present." -- | Return the value of an attribute if it is present, and Nothing otherwise. queryAttr :: XML.Name -> Parser (Maybe Text) queryAttr attr = do ctx <- ask return $ lookupAttr attr (currentElement ctx) -- | Like `queryAttr`, but allow for specifying the namespace. queryAttrWithNamespace :: GIRXMLNamespace -> XML.Name -> Parser (Maybe Text) queryAttrWithNamespace ns attr = do ctx <- ask return $ lookupAttrWithNamespace ns attr (currentElement ctx) -- | Ask for an optional attribute, applying the given parser to -- it. If the argument does not exist return the default value provided. optionalAttr :: XML.Name -> a -> (Text -> Parser a) -> Parser a optionalAttr attr def parser = queryAttr attr >>= \case Just a -> parser a Nothing -> return def -- | Build a 'Name' out of the (possibly qualified) supplied name. If -- the supplied name is unqualified we qualify with the current -- namespace, and otherwise we simply parse it. qualifyName :: Text -> Parser Name qualifyName n = case T.split (== '.') n of [ns, name] -> return $ Name ns name [name] -> nameInCurrentNS name _ -> parseError "Could not understand name" -- | Get the qualified name for the current element. parseName :: Parser Name parseName = getAttr "name" >>= qualifyName -- | Parse the deprecation text, if present. parseDeprecation :: Parser (Maybe DeprecationInfo) parseDeprecation = do ctx <- ask return $ queryDeprecated (currentElement ctx) -- | Parse the documentation info for the current node. parseDocumentation :: Parser Documentation parseDocumentation = do ctx <- ask return $ queryDocumentation (currentElement ctx) -- | Parse a signed integral number. parseIntegral :: Integral a => Text -> Parser a parseIntegral str = case TR.signed TR.decimal str of Right (n, r) | T.null r -> return n _ -> parseError $ "Could not parse integral value: \"" <> str <> "\"." -- | A boolean value given by a numerical constant. parseBool :: Text -> Parser Bool parseBool "0" = return False parseBool "1" = return True parseBool other = parseError $ "Unsupported boolean value: " <> T.pack (show other) -- | Parse all the introspectable subelements with the given local name. parseChildrenWithLocalName :: Text -> Parser a -> Parser [a] parseChildrenWithLocalName n parser = do ctx <- ask let introspectableChildren = filter introspectable (childElemsWithLocalName n (currentElement ctx)) mapM (withElement parser) introspectableChildren where introspectable :: Element -> Bool introspectable e = lookupAttr "introspectable" e /= Just "0" && lookupAttr "shadowed-by" e == Nothing -- | Parse all subelements with the given local name. parseAllChildrenWithLocalName :: Text -> Parser a -> Parser [a] parseAllChildrenWithLocalName n parser = do ctx <- ask mapM (withElement parser) (childElemsWithLocalName n (currentElement ctx)) -- | Parse all introspectable children with the given namespace and -- local name. parseChildrenWithNSName :: GIRXMLNamespace -> Text -> Parser a -> Parser [a] parseChildrenWithNSName ns n parser = do ctx <- ask let introspectableChildren = filter introspectable (childElemsWithNSName ns n (currentElement ctx)) mapM (withElement parser) introspectableChildren where introspectable :: Element -> Bool introspectable e = lookupAttr "introspectable" e /= Just "0" -- | Run the given parser for a given subelement in the XML tree. withElement :: Parser a -> Element -> Parser a withElement parser element = local modifyParsePosition parser where modifyParsePosition ctx = ctx { treePosition = elementDescription element : treePosition ctx , currentElement = element} -- | Run the given parser, returning either success or an error. runParser :: Text -> M.Map Alias Type -> Element -> Parser a -> Either ParseError a runParser ns aliases element parser = runExcept (runReaderT parser ctx) where ctx = ParseContext { ctxNamespace = ns , treePosition = [elementDescription element] , currentElement = element , knownAliases = aliases }
ford-prefect/haskell-gi
lib/Data/GI/GIR/Parser.hs
lgpl-2.1
8,628
0
17
1,990
1,920
1,010
910
-1
-1
module Main where import Millionaire import System.Environment (getArgs) showAnswer :: Bool -> IO () showAnswer correct = putStrLn $ if correct then "You are right!" else "You are wrong." gameloop :: [Question] -> IO () gameloop [] = return () gameloop (q:qs) = do answer <- askQuestion q showAnswer answer gameloop qs main :: IO () main = do [questionsFile] <- getArgs questions <- getQuestions questionsFile gameloop questions
ayakovlenko/millionaire
src/main/Main.hs
unlicense
446
0
8
85
161
80
81
16
2